이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

Python »

3.7.17 Documentation »

|

파이썬 설명서 목차

파이썬의 새로운 기능

파이썬 3.7의 새로운 기능

요약 – 배포 주요 사항

새로운 기능

PEP 563 : 어노테이션의 지연된 평가

PEP 538: 레거시 C 로케일 강제 변경

PEP 540: 강제 UTF-8 실행시간 모드

PEP 553: 내장 breakpoint()

PEP 539: 스레드-로컬 저장소를 위한 새로운 C API

PEP 562: 모듈 어트리뷰트에 대한 액세스 사용자 정의

PEP 564: 나노초 해상도의 새로운 시간 함수

PEP 565: __main__ 의 DeprecationWarning 표시

PEP 560: typing 모듈과 제네릭 형에 대한 코어 지원

PEP 552: 해시 기반 .pyc 파일

PEP 545: 파이썬 설명서 번역

개발 실행시간 모드: -X dev

기타 언어 변경

새 모듈

contextvars

dataclasses

importlib.resources

개선된 모듈

argparse

asyncio

binascii

calendar

collections

compileall

concurrent.futures

contextlib

cProfile

crypt

datetime

dbm

decimal

dis

distutils

enum

functools

gc

hmac

http.client

http.server

idlelib 및 IDLE

importlib

io

ipaddress

itertools

locale

logging

math

mimetypes

msilib

multiprocessing

os

pathlib

pdb

py_compile

pydoc

queue

re

signal

socket

socketserver

sqlite3

ssl

string

subprocess

sys

time

tkinter

tracemalloc

types

unicodedata

unittest

unittest.mock

urllib.parse

uu

uuid

warnings

xml

xml.etree

xmlrpc.server

zipapp

zipfile

C API 변경

빌드 변경

최적화

기타 CPython 구현 변경

폐지된 파이썬 동작

폐지된 파이썬 모듈, 함수 및 메서드

aifc

asyncio

collections

dbm

enum

gettext

importlib

locale

macpath

threading

socket

ssl

sunau

sys

wave

폐지된 C API의 함수 및 형

플랫폼 지원 제거

API 및 기능 제거

모듈 제거

윈도우 전용 변경

파이썬 3.7로 이식하기

파이썬 동작의 변경

파이썬 API의 변경

C API의 변경

CPython 바이트 코드 변경

윈도우 전용 변경

기타 CPython 구현 변경

파이썬 3.7.1의 주목할만한 변경 사항

파이썬 3.7.2의 주목할만한 변경 사항

Notable changes in Python 3.7.6

Notable changes in Python 3.7.10

Notable changes in Python 3.7.11

Notable security feature in 3.7.14

What’s New In Python 3.6

Summary – Release highlights

New Features

PEP 498: Formatted string literals

PEP 526: Syntax for variable annotations

PEP 515: Underscores in Numeric Literals

PEP 525: Asynchronous Generators

PEP 530: Asynchronous Comprehensions

PEP 487: Simpler customization of class creation

PEP 487: Descriptor Protocol Enhancements

PEP 519: Adding a file system path protocol

PEP 495: Local Time Disambiguation

PEP 529: Change Windows filesystem encoding to UTF-8

PEP 528: Change Windows console encoding to UTF-8

PEP 520: Preserving Class Attribute Definition Order

PEP 468: Preserving Keyword Argument Order

New dict implementation

PEP 523: Adding a frame evaluation API to CPython

PYTHONMALLOC environment variable

DTrace and SystemTap probing support

Other Language Changes

New Modules

secrets

Improved Modules

array

ast

asyncio

binascii

cmath

collections

concurrent.futures

contextlib

datetime

decimal

distutils

email

encodings

enum

faulthandler

fileinput

hashlib

http.client

idlelib and IDLE

importlib

inspect

json

logging

math

multiprocessing

os

pathlib

pdb

pickle

pickletools

pydoc

random

re

readline

rlcompleter

shlex

site

sqlite3

socket

socketserver

ssl

statistics

struct

subprocess

sys

telnetlib

time

timeit

tkinter

traceback

tracemalloc

typing

unicodedata

unittest.mock

urllib.request

urllib.robotparser

venv

warnings

winreg

winsound

xmlrpc.client

zipfile

zlib

Optimizations

Build and C API Changes

Other Improvements

Deprecated

New Keywords

Deprecated Python behavior

Deprecated Python modules, functions and methods

asynchat

asyncore

dbm

distutils

grp

importlib

os

re

ssl

tkinter

venv

Deprecated functions and types of the C API

Deprecated Build Options

Removed

API and Feature Removals

Porting to Python 3.6

Changes in ‘python’ Command Behavior

Changes in the Python API

Changes in the C API

CPython bytecode changes

Notable changes in Python 3.6.2

New make regen-all build target

Removal of make touch build target

Notable changes in Python 3.6.4

Notable changes in Python 3.6.5

Notable changes in Python 3.6.7

Notable changes in Python 3.6.10

Notable changes in Python 3.6.13

What’s New In Python 3.5

Summary – Release highlights

New Features

PEP 492 - Coroutines with async and await syntax

PEP 465 - A dedicated infix operator for matrix multiplication

PEP 448 - Additional Unpacking Generalizations

PEP 461 - percent formatting support for bytes and bytearray

PEP 484 - Type Hints

PEP 471 - os.scandir() function – a better and faster directory iterator

PEP 475: Retry system calls failing with EINTR

PEP 479: Change StopIteration handling inside generators

PEP 485: A function for testing approximate equality

PEP 486: Make the Python Launcher aware of virtual environments

PEP 488: Elimination of PYO files

PEP 489: Multi-phase extension module initialization

Other Language Changes

New Modules

typing

zipapp

Improved Modules

argparse

asyncio

bz2

cgi

cmath

code

collections

collections.abc

compileall

concurrent.futures

configparser

contextlib

csv

curses

dbm

difflib

distutils

doctest

email

enum

faulthandler

functools

glob

gzip

heapq

http

http.client

idlelib and IDLE

imaplib

imghdr

importlib

inspect

io

ipaddress

json

linecache

locale

logging

lzma

math

multiprocessing

operator

os

pathlib

pickle

poplib

re

readline

selectors

shutil

signal

smtpd

smtplib

sndhdr

socket

ssl

Memory BIO Support

Application-Layer Protocol Negotiation Support

Other Changes

sqlite3

subprocess

sys

sysconfig

tarfile

threading

time

timeit

tkinter

traceback

types

unicodedata

unittest

unittest.mock

urllib

wsgiref

xmlrpc

xml.sax

zipfile

Other module-level changes

Optimizations

Build and C API Changes

Deprecated

New Keywords

Deprecated Python Behavior

Unsupported Operating Systems

Deprecated Python modules, functions and methods

Removed

API and Feature Removals

Porting to Python 3.5

Changes in Python behavior

Changes in the Python API

Changes in the C API

Notable changes in Python 3.5.4

New make regen-all build target

Removal of make touch build target

What’s New In Python 3.4

Summary – Release Highlights

New Features

PEP 453: Explicit Bootstrapping of PIP in Python Installations

Bootstrapping pip By Default

Documentation Changes

PEP 446: Newly Created File Descriptors Are Non-Inheritable

Improvements to Codec Handling

PEP 451: A ModuleSpec Type for the Import System

Other Language Changes

New Modules

asyncio

ensurepip

enum

pathlib

selectors

statistics

tracemalloc

Improved Modules

abc

aifc

argparse

audioop

base64

collections

colorsys

contextlib

dbm

dis

doctest

email

filecmp

functools

gc

glob

hashlib

hmac

html

http

idlelib and IDLE

importlib

inspect

ipaddress

logging

marshal

mmap

multiprocessing

operator

os

pdb

pickle

plistlib

poplib

pprint

pty

pydoc

re

resource

select

shelve

shutil

smtpd

smtplib

socket

sqlite3

ssl

stat

struct

subprocess

sunau

sys

tarfile

textwrap

threading

traceback

types

urllib

unittest

venv

wave

weakref

xml.etree

zipfile

CPython Implementation Changes

PEP 445: Customization of CPython Memory Allocators

PEP 442: Safe Object Finalization

PEP 456: Secure and Interchangeable Hash Algorithm

PEP 436: Argument Clinic

Other Build and C API Changes

Other Improvements

Significant Optimizations

Deprecated

Deprecations in the Python API

Deprecated Features

Removed

Operating Systems No Longer Supported

API and Feature Removals

Code Cleanups

Porting to Python 3.4

Changes in ‘python’ Command Behavior

Changes in the Python API

Changes in the C API

Changed in 3.4.3

PEP 476: Enabling certificate verification by default for stdlib http clients

What’s New In Python 3.3

Summary – Release highlights

PEP 405: Virtual Environments

PEP 420: Implicit Namespace Packages

PEP 3118: New memoryview implementation and buffer protocol documentation

Features

API changes

PEP 393: Flexible String Representation

Functionality

Performance and resource usage

PEP 397: Python Launcher for Windows

PEP 3151: Reworking the OS and IO exception hierarchy

PEP 380: Syntax for Delegating to a Subgenerator

PEP 409: Suppressing exception context

PEP 414: Explicit Unicode literals

PEP 3155: Qualified name for classes and functions

PEP 412: Key-Sharing Dictionary

PEP 362: Function Signature Object

PEP 421: Adding sys.implementation

SimpleNamespace

Using importlib as the Implementation of Import

New APIs

Visible Changes

Other Language Changes

A Finer-Grained Import Lock

Builtin functions and types

New Modules

faulthandler

ipaddress

lzma

Improved Modules

abc

array

base64

binascii

bz2

codecs

collections

contextlib

crypt

curses

datetime

decimal

Features

API changes

email

Policy Framework

Provisional Policy with New Header API

Other API Changes

ftplib

functools

gc

hmac

http

html

imaplib

inspect

io

itertools

logging

math

mmap

multiprocessing

nntplib

os

pdb

pickle

pydoc

re

sched

select

shlex

shutil

signal

smtpd

smtplib

socket

socketserver

sqlite3

ssl

stat

struct

subprocess

sys

tarfile

tempfile

textwrap

threading

time

types

unittest

urllib

webbrowser

xml.etree.ElementTree

zlib

Optimizations

Build and C API Changes

Deprecated

Unsupported Operating Systems

Deprecated Python modules, functions and methods

Deprecated functions and types of the C API

Deprecated features

Porting to Python 3.3

Porting Python code

Porting C code

Building C extensions

Command Line Switch Changes

What’s New In Python 3.2

PEP 384: Defining a Stable ABI

PEP 389: Argparse Command Line Parsing Module

PEP 391: Dictionary Based Configuration for Logging

PEP 3148: The concurrent.futures module

PEP 3147: PYC Repository Directories

PEP 3149: ABI Version Tagged .so Files

PEP 3333: Python Web Server Gateway Interface v1.0.1

Other Language Changes

New, Improved, and Deprecated Modules

email

elementtree

functools

itertools

collections

threading

datetime and time

math

abc

io

reprlib

logging

csv

contextlib

decimal and fractions

ftp

popen

select

gzip and zipfile

tarfile

hashlib

ast

os

shutil

sqlite3

html

socket

ssl

nntp

certificates

imaplib

http.client

unittest

random

poplib

asyncore

tempfile

inspect

pydoc

dis

dbm

ctypes

site

sysconfig

pdb

configparser

urllib.parse

mailbox

turtledemo

Multi-threading

Optimizations

Unicode

Codecs

Documentation

IDLE

Code Repository

Build and C API Changes

Porting to Python 3.2

What’s New In Python 3.1

PEP 372: Ordered Dictionaries

PEP 378: Format Specifier for Thousands Separator

Other Language Changes

New, Improved, and Deprecated Modules

Optimizations

IDLE

Build and C API Changes

Porting to Python 3.1

What’s New In Python 3.0

Common Stumbling Blocks

Print Is A Function

Views And Iterators Instead Of Lists

Ordering Comparisons

Integers

Text Vs. Data Instead Of Unicode Vs. 8-bit

Overview Of Syntax Changes

New Syntax

Changed Syntax

Removed Syntax

Changes Already Present In Python 2.6

Library Changes

PEP 3101: A New Approach To String Formatting

Changes To Exceptions

Miscellaneous Other Changes

Operators And Special Methods

Builtins

Build and C API Changes

Performance

Porting To Python 3.0

What’s New in Python 2.7

The Future for Python 2.x

Changes to the Handling of Deprecation Warnings

Python 3.1 Features

PEP 372: Adding an Ordered Dictionary to collections

PEP 378: Format Specifier for Thousands Separator

PEP 389: The argparse Module for Parsing Command Lines

PEP 391: Dictionary-Based Configuration For Logging

PEP 3106: Dictionary Views

PEP 3137: The memoryview Object

Other Language Changes

Interpreter Changes

Optimizations

New and Improved Modules

New module: importlib

New module: sysconfig

ttk: Themed Widgets for Tk

Updated module: unittest

Updated module: ElementTree 1.3

Build and C API Changes

Capsules

Port-Specific Changes: Windows

Port-Specific Changes: Mac OS X

Port-Specific Changes: FreeBSD

Other Changes and Fixes

Porting to Python 2.7

New Features Added to Python 2.7 Maintenance Releases

Two new environment variables for debug mode

PEP 434: IDLE Enhancement Exception for All Branches

PEP 466: Network Security Enhancements for Python 2.7

PEP 477: Backport ensurepip (PEP 453) to Python 2.7

Bootstrapping pip By Default

Documentation Changes

PEP 476: Enabling certificate verification by default for stdlib http clients

PEP 493: HTTPS verification migration tools for Python 2.7

New make regen-all build target

Removal of make touch build target

Acknowledgements

What’s New in Python 2.6

Python 3.0

Changes to the Development Process

New Issue Tracker: Roundup

New Documentation Format: reStructuredText Using Sphinx

PEP 343: The ‘with’ statement

Writing Context Managers

The contextlib module

PEP 366: Explicit Relative Imports From a Main Module

PEP 370: Per-user site-packages Directory

PEP 371: The multiprocessing Package

PEP 3101: Advanced String Formatting

PEP 3105: print As a Function

PEP 3110: Exception-Handling Changes

PEP 3112: Byte Literals

PEP 3116: New I/O Library

PEP 3118: Revised Buffer Protocol

PEP 3119: Abstract Base Classes

PEP 3127: Integer Literal Support and Syntax

PEP 3129: Class Decorators

PEP 3141: A Type Hierarchy for Numbers

The fractions Module

Other Language Changes

Optimizations

Interpreter Changes

New and Improved Modules

The ast module

The future_builtins module

The json module: JavaScript Object Notation

The plistlib module: A Property-List Parser

ctypes Enhancements

Improved SSL Support

Deprecations and Removals

Build and C API Changes

Port-Specific Changes: Windows

Port-Specific Changes: Mac OS X

Port-Specific Changes: IRIX

Porting to Python 2.6

Acknowledgements

What’s New in Python 2.5

PEP 308: Conditional Expressions

PEP 309: Partial Function Application

PEP 314: Metadata for Python Software Packages v1.1

PEP 328: Absolute and Relative Imports

PEP 338: Executing Modules as Scripts

PEP 341: Unified try/except/finally

PEP 342: New Generator Features

PEP 343: The ‘with’ statement

Writing Context Managers

The contextlib module

PEP 352: Exceptions as New-Style Classes

PEP 353: Using ssize_t as the index type

PEP 357: The ‘__index__’ method

Other Language Changes

Interactive Interpreter Changes

Optimizations

New, Improved, and Removed Modules

The ctypes package

The ElementTree package

The hashlib package

The sqlite3 package

The wsgiref package

Build and C API Changes

Port-Specific Changes

Porting to Python 2.5

Acknowledgements

What’s New in Python 2.4

PEP 218: Built-In Set Objects

PEP 237: Unifying Long Integers and Integers

PEP 289: Generator Expressions

PEP 292: Simpler String Substitutions

PEP 318: Decorators for Functions and Methods

PEP 322: Reverse Iteration

PEP 324: New subprocess Module

PEP 327: Decimal Data Type

Why is Decimal needed?

The Decimal type

The Context type

PEP 328: Multi-line Imports

PEP 331: Locale-Independent Float/String Conversions

Other Language Changes

Optimizations

New, Improved, and Deprecated Modules

cookielib

doctest

Build and C API Changes

Port-Specific Changes

Porting to Python 2.4

Acknowledgements

What’s New in Python 2.3

PEP 218: A Standard Set Datatype

PEP 255: Simple Generators

PEP 263: Source Code Encodings

PEP 273: Importing Modules from ZIP Archives

PEP 277: Unicode file name support for Windows NT

PEP 278: Universal Newline Support

PEP 279: enumerate()

PEP 282: The logging Package

PEP 285: A Boolean Type

PEP 293: Codec Error Handling Callbacks

PEP 301: Package Index and Metadata for Distutils

PEP 302: New Import Hooks

PEP 305: Comma-separated Files

PEP 307: Pickle Enhancements

Extended Slices

Other Language Changes

String Changes

Optimizations

New, Improved, and Deprecated Modules

Date/Time Type

The optparse Module

Pymalloc: A Specialized Object Allocator

Build and C API Changes

Port-Specific Changes

Other Changes and Fixes

Porting to Python 2.3

Acknowledgements

What’s New in Python 2.2

Introduction

PEPs 252 and 253: Type and Class Changes

Old and New Classes

Descriptors

Multiple Inheritance: The Diamond Rule

Attribute Access

Related Links

PEP 234: Iterators

PEP 255: Simple Generators

PEP 237: Unifying Long Integers and Integers

PEP 238: Changing the Division Operator

Unicode Changes

PEP 227: Nested Scopes

New and Improved Modules

Interpreter Changes and Fixes

Other Changes and Fixes

Acknowledgements

What’s New in Python 2.1

Introduction

PEP 227: Nested Scopes

PEP 236: __future__ Directives

PEP 207: Rich Comparisons

PEP 230: Warning Framework

PEP 229: New Build System

PEP 205: Weak References

PEP 232: Function Attributes

PEP 235: Importing Modules on Case-Insensitive Platforms

PEP 217: Interactive Display Hook

PEP 208: New Coercion Model

PEP 241: Metadata in Python Packages

New and Improved Modules

Other Changes and Fixes

Acknowledgements

What’s New in Python 2.0

Introduction

What About Python 1.6?

New Development Process

Unicode

List Comprehensions

Augmented Assignment

String Methods

Garbage Collection of Cycles

Other Core Changes

Minor Language Changes

Changes to Built-in Functions

Porting to 2.0

Extending/Embedding Changes

Distutils: Making Modules Easy to Install

XML Modules

SAX2 Support

DOM Support

Relationship to PyXML

Module changes

New modules

IDLE Improvements

Deleted and Deprecated Modules

Acknowledgements

Changelog

Python 3.7.17 final

Security

Library

Build

Windows

Python 3.7.16 final

Security

Python 3.7.15 final

Security

Core and Builtins

Library

Windows

Python 3.7.14 final

Security

Core and Builtins

Library

Documentation

Tests

Windows

Python 3.7.13 final

Library

Build

Windows

Python 3.7.12 final

Security

Library

Python 3.7.11 final

Security

Core and Builtins

Tests

Python 3.7.10 final

Security

Library

Documentation

Tests

Python 3.7.9 final

Security

Core and Builtins

Library

macOS

Python 3.7.8 final

Tests

macOS

Python 3.7.8 release candidate 1

Security

Core and Builtins

Library

Documentation

Tests

Build

Windows

macOS

IDLE

Tools/Demos

C API

Python 3.7.7 final

Library

Documentation

Python 3.7.7 release candidate 1

Security

Core and Builtins

Library

Documentation

Tests

Build

Windows

macOS

IDLE

Python 3.7.6 final

macOS

Python 3.7.6 release candidate 1

Security

Core and Builtins

Library

Documentation

Tests

Build

Windows

IDLE

Tools/Demos

C API

Python 3.7.5 final

Library

Windows

Python 3.7.5 release candidate 1

Security

Core and Builtins

Library

Documentation

Tests

Build

Windows

macOS

IDLE

Tools/Demos

Python 3.7.4 final

Core and Builtins

Documentation

Python 3.7.4 release candidate 2

Security

Core and Builtins

Library

Windows

macOS

Python 3.7.4 release candidate 1

Security

Core and Builtins

Library

Documentation

Tests

Build

Windows

macOS

IDLE

Tools/Demos

C API

Python 3.7.3 final

Python 3.7.3 release candidate 1

Security

Core and Builtins

Library

Documentation

Tests

Build

Windows

IDLE

Tools/Demos

C API

Python 3.7.2 final

Library

Build

C API

Python 3.7.2 release candidate 1

Security

Core and Builtins

Library

Documentation

Tests

Build

Windows

macOS

IDLE

Tools/Demos

C API

Python 3.7.1 final

Library

Python 3.7.1 release candidate 2

Core and Builtins

Library

Documentation

Tests

macOS

C API

Python 3.7.1 release candidate 1

Security

Core and Builtins

Library

Documentation

Tests

Build

Windows

macOS

IDLE

Tools/Demos

C API

Python 3.7.0 final

Library

C API

Python 3.7.0 release candidate 1

Core and Builtins

Library

Documentation

Build

Windows

IDLE

Python 3.7.0 beta 5

Core and Builtins

Library

Documentation

Tests

Build

macOS

IDLE

Python 3.7.0 beta 4

Core and Builtins

Library

Documentation

Tests

Build

Windows

macOS

IDLE

Tools/Demos

Python 3.7.0 beta 3

Security

Core and Builtins

Library

Documentation

Tests

Build

Windows

macOS

IDLE

Tools/Demos

C API

Python 3.7.0 beta 2

Security

Core and Builtins

Library

Documentation

Tests

Build

Windows

macOS

IDLE

Tools/Demos

Python 3.7.0 beta 1

Core and Builtins

Library

Documentation

Tests

Build

Windows

macOS

C API

Python 3.7.0 alpha 4

Core and Builtins

Library

Documentation

Tests

Windows

Tools/Demos

C API

Python 3.7.0 alpha 3

Core and Builtins

Library

Documentation

Tests

Build

Windows

macOS

IDLE

Tools/Demos

C API

Python 3.7.0 alpha 2

Core and Builtins

Library

Documentation

Build

IDLE

C API

Python 3.7.0 alpha 1

Security

Core and Builtins

Library

Documentation

Tests

Build

Windows

IDLE

Tools/Demos

C API

Python 3.6.6 final

Python 3.6.6 release candidate 1

Core and Builtins

Library

Documentation

Tests

Build

Windows

macOS

IDLE

Tools/Demos

C API

Python 3.6.5 final

Tests

Build

Python 3.6.5 release candidate 1

Security

Core and Builtins

Library

Documentation

Tests

Build

Windows

macOS

IDLE

Tools/Demos

C API

Python 3.6.4 final

Python 3.6.4 release candidate 1

Core and Builtins

Library

Documentation

Tests

Build

Windows

macOS

IDLE

Tools/Demos

C API

Python 3.6.3 final

Library

Build

Python 3.6.3 release candidate 1

Security

Core and Builtins

Library

Documentation

Tests

Build

Windows

IDLE

Tools/Demos

Python 3.6.2 final

Python 3.6.2 release candidate 2

Security

Python 3.6.2 release candidate 1

Core and Builtins

Library

Security

Library

IDLE

C API

Build

Documentation

Tools/Demos

Tests

Windows

Python 3.6.1 final

Core and Builtins

Build

Python 3.6.1 release candidate 1

Core and Builtins

Library

IDLE

Windows

C API

Documentation

Tests

Build

Python 3.6.0 final

Python 3.6.0 release candidate 2

Core and Builtins

Tools/Demos

Windows

Build

Python 3.6.0 release candidate 1

Core and Builtins

Library

C API

Documentation

Tools/Demos

Python 3.6.0 beta 4

Core and Builtins

Library

Documentation

Tests

Build

Python 3.6.0 beta 3

Core and Builtins

Library

Windows

Build

Tests

Python 3.6.0 beta 2

Core and Builtins

Library

Windows

C API

Build

Tests

Python 3.6.0 beta 1

Core and Builtins

Library

IDLE

C API

Tests

Build

Tools/Demos

Windows

Python 3.6.0 alpha 4

Core and Builtins

Library

IDLE

Tests

Windows

Build

Python 3.6.0 alpha 3

Core and Builtins

Library

Security

Library

Security

Library

IDLE

C API

Build

Tools/Demos

Documentation

Tests

Python 3.6.0 alpha 2

Core and Builtins

Library

Security

Library

Security

Library

IDLE

Documentation

Tests

Windows

Build

Windows

C API

Tools/Demos

Python 3.6.0 alpha 1

Core and Builtins

Library

Security

Library

Security

Library

Security

Library

IDLE

Documentation

Tests

Build

Windows

Tools/Demos

C API

Python 3.5.5 final

Python 3.5.5 release candidate 1

Security

Core and Builtins

Library

Python 3.5.4 final

Library

Python 3.5.4 release candidate 1

Security

Core and Builtins

Library

Documentation

Tests

Build

Windows

C API

Python 3.5.3 final

Python 3.5.3 release candidate 1

Core and Builtins

Library

Security

Library

Security

Library

IDLE

C API

Documentation

Tests

Tools/Demos

Windows

Build

Python 3.5.2 final

Core and Builtins

Tests

IDLE

Python 3.5.2 release candidate 1

Core and Builtins

Security

Library

Security

Library

Security

Library

Security

Library

Security

Library

IDLE

Documentation

Tests

Build

Windows

Tools/Demos

Windows

Python 3.5.1 final

Core and Builtins

Windows

Python 3.5.1 release candidate 1

Core and Builtins

Library

IDLE

Documentation

Tests

Build

Windows

Tools/Demos

Python 3.5.0 final

Build

Python 3.5.0 release candidate 4

Library

Build

Python 3.5.0 release candidate 3

Core and Builtins

Library

Python 3.5.0 release candidate 2

Core and Builtins

Library

Python 3.5.0 release candidate 1

Core and Builtins

Library

IDLE

Documentation

Tests

Python 3.5.0 beta 4

Core and Builtins

Library

Build

Python 3.5.0 beta 3

Core and Builtins

Library

Tests

Documentation

Build

Python 3.5.0 beta 2

Core and Builtins

Library

Python 3.5.0 beta 1

Core and Builtins

Library

IDLE

Tests

Documentation

Tools/Demos

Python 3.5.0 alpha 4

Core and Builtins

Library

Build

Tests

Tools/Demos

C API

Python 3.5.0 alpha 3

Core and Builtins

Library

Build

Tests

Tools/Demos

Python 3.5.0 alpha 2

Core and Builtins

Library

Build

C API

Windows

Python 3.5.0 alpha 1

Core and Builtins

Library

IDLE

Build

C API

Documentation

Tests

Tools/Demos

Windows

파이썬 자습서

1. 입맛 돋우기

2. 파이썬 인터프리터 사용하기

2.1. 인터프리터 실행하기

2.1.1. 인자 전달

2.1.2. 대화형 모드

2.2. 인터프리터와 환경

2.2.1. 소스 코드 인코딩

3. 파이썬의 간략한 소개

3.1. 파이썬을 계산기로 사용하기

3.1.1. 숫자

3.1.2. 문자열

3.1.3. 리스트

3.2. 프로그래밍으로의 첫걸음

4. 기타 제어 흐름 도구

4.1. if 문

4.2. for 문

4.3. range() 함수

4.4. 루프의 break 와 continue 문, 그리고 else 절

4.5. pass 문

4.6. 함수 정의하기

4.7. 함수 정의 더 보기

4.7.1. 기본 인자 값

4.7.2. 키워드 인자

4.7.3. 임의의 인자 목록

4.7.4. 인자 목록 언 패킹

4.7.5. 람다 표현식

4.7.6. 도큐멘테이션 문자열

4.7.7. 함수 어노테이션

4.8. 막간극: 코딩 스타일

5. 자료 구조

5.1. 리스트 더 보기

5.1.1. 리스트를 스택으로 사용하기

5.1.2. 리스트를 큐로 사용하기

5.1.3. 리스트 컴프리헨션

5.1.4. 중첩된 리스트 컴프리헨션

5.2. del 문

5.3. 튜플과 시퀀스

5.4. 집합

5.5. 딕셔너리

5.6. 루프 테크닉

5.7. 조건 더 보기

5.8. 시퀀스와 다른 형들을 비교하기

6. 모듈

6.1. 모듈 더 보기

6.1.1. 모듈을 스크립트로 실행하기

6.1.2. 모듈 검색 경로

6.1.3. “컴파일된” 파이썬 파일

6.2. 표준 모듈들

6.3. dir() 함수

6.4. 패키지

6.4.1. 패키지에서 * 임포트 하기

6.4.2. 패키지 내부 간의 참조

6.4.3. 여러 디렉터리에 있는 패키지

7. 입력과 출력

7.1. 장식적인 출력 포매팅

7.1.1. 포맷 문자열 리터럴

7.1.2. 문자열 format() 메서드

7.1.3. 수동 문자열 포매팅

7.1.4. 예전의 문자열 포매팅

7.2. 파일을 읽고 쓰기

7.2.1. 파일 객체의 매소드

7.2.2. json 으로 구조적인 데이터를 저장하기

8. 에러와 예외

8.1. 문법 에러

8.2. 예외

8.3. 예외 처리하기

8.4. 예외 일으키기

8.5. 사용자 정의 예외

8.6. 뒷정리 동작 정의하기

8.7. 미리 정의된 뒷정리 동작들

9. 클래스

9.1. 이름과 객체에 관한 한마디

9.2. 파이썬 스코프와 이름 공간

9.2.1. 스코프와 이름 공간 예

9.3. 클래스와의 첫 만남

9.3.1. 클래스 정의 문법

9.3.2. 클래스 객체

9.3.3. 인스턴스 객체

9.3.4. 메서드 객체

9.3.5. 클래스와 인스턴스 변수

9.4. 기타 주의사항들

9.5. 상속

9.5.1. 다중 상속

9.6. 비공개 변수

9.7. 잡동사니

9.8. 이터레이터

9.9. 제너레이터

9.10. 제너레이터 표현식

10. 표준 라이브러리 둘러보기

10.1. 운영 체제 인터페이스

10.2. 파일 와일드카드

10.3. 명령행 인자

10.4. 에러 출력 리디렉션과 프로그램 종료

10.5. 문자열 패턴 매칭

10.6. 수학

10.7. 인터넷 액세스

10.8. 날짜와 시간

10.9. 데이터 압축

10.10. 성능 측정

10.11. 품질 관리

10.12. 배터리가 포함됩니다

11. 표준 라이브러리 둘러보기 — 2부

11.1. 출력 포매팅

11.2. 템플릿

11.3. 바이너리 데이터 레코드 배치 작업

11.4. 다중 스레딩

11.5. 로깅

11.6. 약한 참조

11.7. 리스트 작업 도구

11.8. 10진 부동 소수점 산술

12. 가상 환경 및 패키지

12.1. 소개

12.2. 가상 환경 만들기

12.3. pip로 패키지 관리하기

13. 이제 뭘 하지?

14. 대화형 입력 편집 및 히스토리 치환

14.1. 탭 완성 및 히스토리 편집

14.2. 대화형 인터프리터 대안

15. 부동 소수점 산술: 문제점 및 한계

15.1. 표현 오류

16. 부록

16.1. 대화형 모드

16.1.1. 에러 처리

16.1.2. 실행 가능한 파이썬 스크립트

16.1.3. 대화형 시작 파일

16.1.4. 커스터마이제이션 모듈

파이썬 설정 및 사용법

1. 명령 줄과 환경

1.1. 명령 줄

1.1.1. 인터페이스 옵션

1.1.2. 일반 옵션

1.1.3. 기타 옵션

1.1.4. 사용해서는 안 되는 옵션

1.2. 환경 변수

1.2.1. 디버그 모드 변수

2. 유닉스 플랫폼에서 파이썬 사용하기

2.1. 최신 버전의 파이썬 내려받기와 설치

2.1.1. 리눅스

2.1.2. FreeBSD와 OpenBSD

2.1.3. OpenSolaris

2.2. 파이썬 빌드하기

2.3. 파이썬 관련 경로와 파일

2.4. 잡동사니

3. Using Python on Windows

3.1. The full installer

3.1.1. Installation steps

3.1.2. Removing the MAX_PATH Limitation

3.1.3. Installing Without UI

3.1.4. Installing Without Downloading

3.1.5. Modifying an install

3.2. The Microsoft Store package

3.2.1. Known Issues

3.3. The nuget.org packages

3.4. The embeddable package

3.4.1. Python Application

3.4.2. Embedding Python

3.5. Alternative bundles

3.6. Configuring Python

3.6.1. Excursus: Setting environment variables

3.6.2. Finding the Python executable

3.7. UTF-8 mode

3.8. Python Launcher for Windows

3.8.1. Getting started

3.8.1.1. From the command-line

3.8.1.2. Virtual environments

3.8.1.3. From a script

3.8.1.4. From file associations

3.8.2. Shebang Lines

3.8.3. Arguments in shebang lines

3.8.4. Customization

3.8.4.1. Customization via INI files

3.8.4.2. Customizing default Python versions

3.8.5. Diagnostics

3.9. Finding modules

3.10. Additional modules

3.10.1. PyWin32

3.10.2. cx_Freeze

3.10.3. WConio

3.11. Compiling Python on Windows

3.12. Other Platforms

4. 매킨토시에서 파이썬 사용하기

4.1. MacPython을 구하고 설치하기

4.1.1. 파이썬 스크립트를 실행하는 방법

4.1.2. GUI로 스크립트 실행하기

4.1.3. 구성

4.2. IDE

4.3. 추가 파이썬 패키지 설치하기

4.4. Mac에서의 GUI 프로그래밍

4.5. Mac에서 파이썬 응용 프로그램 배포하기

4.6. 기타 자원

5. Editors and IDEs

파이썬 언어 레퍼런스

1. 개요

1.1. 대안 구현들

1.2. 표기법

2. 어휘 분석

2.1. 줄 구조(Line structure)

2.1.1. 논리적인 줄

2.1.2. 물리적인 줄

2.1.3. 주석

2.1.4. 인코딩 선언

2.1.5. 명시적인 줄 결합

2.1.6. 묵시적인 줄 결합

2.1.7. 빈 줄

2.1.8. 들여쓰기

2.1.9. 토큰 사이의 공백

2.2. 다른 토큰들

2.3. 식별자와 키워드

2.3.1. 키워드

2.3.2. 식별자의 예약 영역

2.4. 리터럴

2.4.1. 문자열과 바이트열 리터럴

2.4.2. 문자열 리터럴 이어붙이기

2.4.3. 포맷 문자열 리터럴

2.4.4. 숫자 리터럴

2.4.5. 정수 리터럴

2.4.6. 실수 리터럴

2.4.7. 허수 리터럴

2.5. 연산자

2.6. 구분자

3. 데이터 모델

3.1. 객체, 값, 형

3.2. 표준형 계층

3.3. 특수 메서드 이름들

3.3.1. 기본적인 커스터마이제이션

3.3.2. 어트리뷰트 액세스 커스터마이제이션

3.3.2.1. 모듈 어트리뷰트 액세스 커스터마이제이션

3.3.2.2. 디스크립터 구현하기

3.3.2.3. 디스크립터 호출하기

3.3.2.4. __slots__

3.3.2.4.1. __slots__ 사용에 관한 노트

3.3.3. 클래스 생성 커스터마이제이션

3.3.3.1. 메타 클래스

3.3.3.2. MRO 항목 결정하기

3.3.3.3. 적절한 메타 클래스 선택하기

3.3.3.4. 클래스 이름 공간 준비하기

3.3.3.5. 클래스 바디 실행하기

3.3.3.6. 클래스 객체 만들기

3.3.3.7. 메타 클래스의 용도

3.3.4. 인스턴스 및 서브 클래스 검사 커스터마이제이션

3.3.5. 제네릭 형 흉내 내기

3.3.6. 콜러블 객체 흉내 내기

3.3.7. 컨테이너형 흉내 내기

3.3.8. 숫자 형 흉내 내기

3.3.9. with 문 컨텍스트 관리자

3.3.10. 특수 메서드 조회

3.4. 코루틴(Coroutines)

3.4.1. 어웨이터블 객체(Awaitable Objects)

3.4.2. 코루틴 객체(Coroutine Objects)

3.4.3. 비동기 이터레이터(Asynchronous Iterators)

3.4.4. 비동기 컨텍스트 관리자

4. 실행 모델

4.1. 프로그램의 구조

4.2. 이름과 연결(binding)

4.2.1. 이름의 연결

4.2.2. 이름의 검색(resolution)

4.2.3. builtins 와 제한된 실행

4.2.4. 동적 기능과의 상호작용

4.3. 예외

5. 임포트 시스템

5.1. importlib

5.2. 패키지(package)

5.2.1. 정규 패키지

5.2.2. 이름 공간 패키지

5.3. 검색

5.3.1. 모듈 캐시

5.3.2. 파인더(finder)와 로더(loader)

5.3.3. 임포트 훅(import hooks)

5.3.4. 메타 경로(meta path)

5.4. 로딩(loading)

5.4.1. 로더

5.4.2. 서브 모듈

5.4.3. 모듈 스펙

5.4.4. 임포트 관련 모듈 어트리뷰트

5.4.5. module.__path__

5.4.6. 모듈 repr

5.4.7. 캐시된 바이트 코드 무효화

5.5. 경로 기반 파인더

5.5.1. 경로 엔트리 파인더

5.5.2. 경로 엔트리 파인더 프로토콜

5.6. 표준 임포트 시스템 교체하기

5.7. 패키지 상대 임포트

5.8. __main__ 에 대한 특별한 고려

5.8.1. __main__.__spec__

5.9. 열린 이슈들

5.10. 참고문헌

6. 표현식

6.1. 산술 변환

6.2. 아톰 (Atoms)

6.2.1. 식별자 (이름)

6.2.2. 리터럴 (Literals)

6.2.3. 괄호 안에 넣은 형

6.2.4. 리스트, 집합, 딕셔너리의 디스플레이(display)

6.2.5. 리스트 디스플레이

6.2.6. 집합 디스플레이

6.2.7. 딕셔너리 디스플레이

6.2.8. 제너레이터 표현식 (Generator expressions)

6.2.9. 일드 표현식(Yield expressions)

6.2.9.1. 제너레이터-이터레이터 메서드

6.2.9.2. 사용 예

6.2.9.3. 비동기 제너레이터 함수

6.2.9.4. 비동기 제너레이터-이터레이터 메서드

6.3. 프라이머리

6.3.1. 어트리뷰트 참조

6.3.2. 서브스크립션(Subscriptions)

6.3.3. 슬라이싱(Slicings)

6.3.4. 호출

6.4. 어웨이트 표현식

6.5. 거듭제곱 연산자

6.6. 일 항 산술과 비트 연산

6.7. 이항 산술 연산

6.8. 시프트 연산

6.9. 이항 비트 연산

6.10. 비교

6.10.1. 값 비교

6.10.2. 멤버십 검사 연산

6.10.3. 아이덴티티 비교

6.11. 논리 연산(Boolean operations)

6.12. 조건 표현식(Conditional expressions)

6.13. 람다(Lambdas)

6.14. 표현식 목록(Expression lists)

6.15. 값을 구하는 순서

6.16. 연산자 우선순위

7. 단순문(Simple statements)

7.1. 표현식 문

7.2. 대입문

7.2.1. 증분 대입문(Augmented assignment statements)

7.2.2. 어노테이트된 대입문(Annotated assignment statements)

7.3. assert 문

7.4. pass 문

7.5. del 문

7.6. return 문

7.7. yield 문

7.8. raise 문

7.9. break 문

7.10. continue 문

7.11. 임포트(import) 문

7.11.1. 퓨처 문

7.12. global 문

7.13. nonlocal 문

8. 복합문(Compound statements)

8.1. if 문

8.2. while 문

8.3. for 문

8.4. try 문

8.5. with 문

8.6. 함수 정의

8.7. 클래스 정의

8.8. 코루틴

8.8.1. 코루틴 함수 정의

8.8.2. async for 문

8.8.3. async with 문

9. 최상위 요소들

9.1. 완전한 파이썬 프로그램

9.2. 파일 입력

9.3. 대화형 입력

9.4. 표현식 입력

10. 전체 문법 규격

파이썬 표준 라이브러리

소개

가용성에 대한 참고 사항

내장 함수

내장 상수

site 모듈에 의해 추가된 상수들

내장형

논리값 검사

논리 연산 — and, or, not

비교

숫자 형 — int, float, complex

정수 형에 대한 비트 연산

정수 형에 대한 추가 메서드

실수에 대한 추가 메서드

숫자 형의 해싱

이터레이터 형

제너레이터 형

시퀀스 형 — list, tuple, range

공통 시퀀스 연산

불변 시퀀스 형

가변 시퀀스 형

리스트

튜플

범위

텍스트 시퀀스 형 — str

문자열 메서드

printf 스타일 문자열 포매팅

바이너리 시퀀스 형 — bytes, bytearray, memoryview

바이트열 객체

바이트 배열 객체

바이트열 과 바이트 배열 연산

printf 스타일 바이너리 포매팅

메모리 뷰

집합 형 — set, frozenset

매핑 형 — dict

딕셔너리 뷰 객체

컨텍스트 관리자 형

기타 내장형

모듈

클래스와 클래스 인스턴스

함수

메서드

코드 객체

형 객체

널 객체

Ellipsis 객체

NotImplemented 객체

논리값

내부 객체

특수 어트리뷰트

Integer string conversion length limitation

Affected APIs

Configuring the limit

Recommended configuration

내장 예외

베이스 클래스

구체적인 예외

OS 예외

경고

예외 계층 구조

텍스트 처리 서비스

string — 일반적인 문자열 연산

문자열 상수

사용자 지정 문자열 포매팅

포맷 문자열 문법

포맷 명세 미니 언어

포맷 예제

템플릿 문자열

도움 함수

re — Regular expression operations

Regular Expression Syntax

Module Contents

Regular Expression Objects

Match Objects

Regular Expression Examples

Checking for a Pair

Simulating scanf()

search() vs. match()

Making a Phonebook

Text Munging

Finding all Adverbs

Finding all Adverbs and their Positions

Raw String Notation

Writing a Tokenizer

difflib — 델타 계산을 위한 도우미

SequenceMatcher 객체

SequenceMatcher 예제

Differ 객체

Differ 예제

difflib의 명령 줄 인터페이스

textwrap — 텍스트 래핑과 채우기

unicodedata — 유니코드 데이터베이스

stringprep — 인터넷 문자열 준비

readline — GNU readline 인터페이스

초기화 파일

줄 버퍼

히스토리 파일

히스토리 목록

시동 훅

완성

예제

rlcompleter — GNU readline을 위한 완성 함수

Completer 객체

바이너리 데이터 서비스

struct — Interpret bytes as packed binary data

Functions and Exceptions

Format Strings

Byte Order, Size, and Alignment

Format Characters

Examples

Classes

codecs — Codec registry and base classes

Codec Base Classes

Error Handlers

Stateless Encoding and Decoding

Incremental Encoding and Decoding

IncrementalEncoder Objects

IncrementalDecoder Objects

Stream Encoding and Decoding

StreamWriter Objects

StreamReader Objects

StreamReaderWriter Objects

StreamRecoder Objects

Encodings and Unicode

Standard Encodings

Python Specific Encodings

Text Encodings

Binary Transforms

Text Transforms

encodings.idna — Internationalized Domain Names in Applications

encodings.mbcs — Windows ANSI codepage

encodings.utf_8_sig — UTF-8 codec with BOM signature

데이터형

datetime — 기본 날짜와 시간 형

사용 가능한 형

timedelta 객체

date 객체

datetime 객체

time 객체

tzinfo 객체

timezone 객체

strftime()과 strptime() 동작

calendar — General calendar-related functions

collections — Container datatypes

ChainMap objects

ChainMap Examples and Recipes

Counter objects

deque objects

deque Recipes

defaultdict objects

defaultdict Examples

namedtuple() Factory Function for Tuples with Named Fields

OrderedDict objects

OrderedDict Examples and Recipes

UserDict objects

UserList objects

UserString objects

collections.abc — 컨테이너의 추상 베이스 클래스

Collections 추상 베이스 클래스

heapq — Heap queue algorithm

Basic Examples

Priority Queue Implementation Notes

Theory

bisect — 배열 이진 분할 알고리즘

정렬된 리스트 검색하기

다른 예제

array — 효율적인 숫자 배열

weakref — Weak references

Weak Reference Objects

Example

Finalizer Objects

Comparing finalizers with __del__() methods

types — 동적 형 생성과 내장형 이름

동적 형 생성

표준 인터프리터 형

추가 유틸리티 클래스와 함수

코루틴 유틸리티 함수

copy — 얕은 복사와 깊은 복사 연산

pprint — 예쁜 데이터 인쇄기

PrettyPrinter 객체

예제

reprlib — 대안 repr() 구현

Repr 객체

Repr 객체 서브클래싱

enum — Support for enumerations

Module Contents

Creating an Enum

Programmatic access to enumeration members and their attributes

Duplicating enum members and values

Ensuring unique enumeration values

Using automatic values

Iteration

Comparisons

Allowed members and attributes of enumerations

Restricted Enum subclassing

Pickling

Functional API

Derived Enumerations

IntEnum

IntFlag

Flag

Others

Interesting examples

Omitting values

Using auto

Using object

Using a descriptive string

Using a custom __new__()

OrderedEnum

DuplicateFreeEnum

Planet

TimePeriod

How are Enums different?

Enum Classes

Enum Members (aka instances)

Finer Points

Supported __dunder__ names

Supported _sunder_ names

Enum member type

Boolean value of Enum classes and members

Enum classes with methods

Combining members of Flag

숫자와 수학 모듈

numbers — 숫자 추상 베이스 클래스

숫자 계층

형 구현을 위한 주의 사항

더 많은 숫자 추상 베이스 클래스(ABC) 추가

산술 연산 구현

math — Mathematical functions

Number-theoretic and representation functions

Power and logarithmic functions

Trigonometric functions

Angular conversion

Hyperbolic functions

Special functions

Constants

cmath — 복소수를 위한 수학 함수

극좌표 변환

거듭제곱과 로그 함수

삼각 함수

쌍곡선(hyperbolic) 함수

분류 함수

상수

decimal — 십진 고정 소수점 및 부동 소수점 산술

빠른 시작 자습서

Decimal 객체

논리적 피연산자

Context 객체

상수

자리 올림 모드

신호

부동 소수점 노트

증가시킨 정밀도로 자리 올림 오차 줄이기

특수 값

스레드로 작업하기

조리법

Decimal FAQ

fractions — 유리수

random — Generate pseudo-random numbers

Bookkeeping functions

Functions for integers

Functions for sequences

Real-valued distributions

Alternative Generator

Notes on Reproducibility

Examples and Recipes

statistics — Mathematical statistics functions

Averages and measures of central location

Measures of spread

Function details

Exceptions

함수형 프로그래밍 모듈

itertools — Functions creating iterators for efficient looping

Itertool functions

Itertools Recipes

functools — Higher-order functions and operations on callable objects

partial Objects

operator — 함수로서의 표준 연산자

연산자를 함수에 매핑하기

제자리 연산자

파일과 디렉터리 액세스

pathlib — Object-oriented filesystem paths

Basic use

Pure paths

General properties

Operators

Accessing individual parts

Methods and properties

Concrete paths

Methods

Correspondence to tools in the os module

os.path — Common pathname manipulations

fileinput — Iterate over lines from multiple input streams

stat — stat() 결과 해석하기

filecmp — 파일과 디렉터리 비교

dircmp 클래스

tempfile — Generate temporary files and directories

Examples

Deprecated functions and variables

glob — 유닉스 스타일 경로명 패턴 확장

fnmatch — 유닉스 파일명 패턴 일치

linecache — 텍스트 줄에 대한 무작위 액세스

shutil — High-level file operations

Directory and files operations

copytree example

rmtree example

Archiving operations

Archiving example

Archiving example with base_dir

Querying the size of the output terminal

macpath — Mac OS 9 path manipulation functions

데이터 지속성

pickle — 파이썬 객체 직렬화

다른 파이썬 모듈과의 관계

marshal 과의 비교

json 과의 비교

데이터 스트림 형식

모듈 인터페이스

어떤 것이 피클 되고 역 피클 될 수 있을까요?

클래스 인스턴스 피클링

외부 객체의 지속성

디스패치 테이블

상태 저장 객체 처리

전역 제한하기

성능

예제

copyreg — pickle 지원 함수 등록

예제

shelve — 파이썬 객체 지속성

제약 사항

예제

marshal — 내부 파이썬 객체 직렬화

dbm — 유닉스 “데이터베이스” 인터페이스

dbm.gnu — GNU의 dbm 재해석

dbm.ndbm — ndbm 기반 인터페이스

dbm.dumb — 이식성 있는 DBM 구현

sqlite3 — SQLite 데이터베이스용 DB-API 2.0 인터페이스

모듈 함수와 상수

Connection 객체

Cursor 객체

Row 객체

예외

SQLite 와 파이썬 형

소개

어댑터를 사용하여 SQLite 데이터베이스에 추가 파이썬 형을 저장하기

객체가 스스로 어댑트하도록 하기

어댑터 콜러블 등록하기

SQLite 값을 사용자 정의 파이썬 형으로 변환하기

기본 어댑터와 변환기

트랜잭션 제어

효율적으로 sqlite3 사용하기

바로 가기 메서드 사용하기

인덱스 대신 이름으로 열 액세스하기

컨텍스트 관리자로 연결 사용하기

일반적인 문제

다중 스레드

데이터 압축 및 보관

zlib — Compression compatible with gzip

gzip — gzip 파일 지원

사용 예

bz2 — bzip2 압축 지원

파일 압축(해제)

증분 압축(해제)

일괄 압축(해제)

사용 예

lzma — Compression using the LZMA algorithm

Reading and writing compressed files

Compressing and decompressing data in memory

Miscellaneous

Specifying custom filter chains

Examples

zipfile — Work with ZIP archives

ZipFile Objects

PyZipFile Objects

ZipInfo Objects

Command-Line Interface

Command-line options

tarfile — Read and write tar archive files

TarFile Objects

TarInfo Objects

Command-Line Interface

Command-line options

Examples

Supported tar formats

Unicode issues

파일 형식

csv — CSV 파일 읽기와 쓰기

모듈 내용

방언과 포매팅 파라미터

판독기 객체

기록기 객체

예제

configparser — Configuration file parser

Quick Start

Supported Datatypes

Fallback Values

Supported INI File Structure

Interpolation of values

Mapping Protocol Access

Customizing Parser Behaviour

Legacy API Examples

ConfigParser Objects

RawConfigParser Objects

Exceptions

netrc — netrc 파일 처리

netrc 객체

xdrlib — XDR 데이터 인코딩과 디코딩

Packer 객체

Unpacker 객체

예외

plistlib — 맥 OS X .plist 파일 생성과 구문 분석

예제

암호화 서비스

hashlib — Secure hashes and message digests

Hash algorithms

SHAKE variable length digests

Key derivation

BLAKE2

Creating hash objects

Constants

Examples

Simple hashing

Using different digest sizes

Keyed hashing

Randomized hashing

Personalization

Tree mode

Credits

hmac — 메시지 인증을 위한 키 해싱

secrets — 비밀 관리를 위한 안전한 난수 생성

난수

토큰 생성

토큰은 몇 바이트를 사용해야 합니까?

기타 함수

조리법과 모범 사례

일반 운영 체제 서비스

os — 기타 운영 체제 인터페이스

파일명, 명령 줄 인자 및 환경 변수

프로세스 매개 변수

파일 객체 생성

파일 기술자 연산

터미널의 크기 조회하기

파일 기술자의 상속

파일과 디렉터리

리눅스 확장 어트리뷰트

프로세스 관리

스케줄러에 대한 인터페이스

기타 시스템 정보

난수

io — Core tools for working with streams

Overview

Text I/O

Binary I/O

Raw I/O

High-level Module Interface

In-memory streams

Class hierarchy

I/O Base Classes

Raw File I/O

Buffered Streams

Text I/O

Performance

Binary I/O

Text I/O

Multi-threading

Reentrancy

time — Time access and conversions

Functions

Clock ID Constants

Timezone Constants

argparse — 명령행 옵션, 인자와 부속 명령을 위한 파서

예

파서 만들기

인자 추가하기

인자 파싱하기

ArgumentParser 객체

prog

usage

description

epilog

parents

formatter_class

prefix_chars

fromfile_prefix_chars

argument_default

allow_abbrev

conflict_handler

add_help

add_argument() 메서드

name or flags

action

nargs

const

default

type

choices

required

help

metavar

dest

Action 클래스

parse_args() 메서드

옵션값 문법

잘못된 인자

- 를 포함하는 인자들

인자 약어 (접두사 일치)

sys.argv 너머

Namespace 객체

기타 유틸리티

부속 명령

FileType 객체

인자 그룹

상호 배제

파서 기본값

도움말 인쇄

부분 파싱

파일 파싱 사용자 정의

종료 메서드

혼합 파싱

optparse 코드 업그레이드

getopt — 명령 줄 옵션용 C 스타일 구문 분석기

logging — 파이썬 로깅 시설

Logger 객체

로깅 수준

Handler 객체

Formatter 객체

Filter 객체

LogRecord 객체

LogRecord 어트리뷰트

LoggerAdapter 객체

스레드 안전성

모듈 수준 함수

모듈 수준 어트리뷰트

warnings 모듈과의 통합

logging.config — 로깅 구성

구성 함수

구성 딕셔너리 스키마

딕셔너리 스키마 세부사항

증분 구성

객체 연결

사용자 정의 객체

외부 객체에 대한 액세스

내부 객체에 대한 액세스

임포트 결정과 사용자 정의 임포터

구성 파일 형식

logging.handlers — 로깅 처리기

StreamHandler

FileHandler

NullHandler

WatchedFileHandler

BaseRotatingHandler

RotatingFileHandler

TimedRotatingFileHandler

SocketHandler

DatagramHandler

SysLogHandler

NTEventLogHandler

SMTPHandler

MemoryHandler

HTTPHandler

QueueHandler

QueueListener

getpass — 이식성 있는 암호 입력

curses — Terminal handling for character-cell displays

Functions

Window Objects

Constants

curses.textpad — Text input widget for curses programs

Textbox objects

curses.ascii — Utilities for ASCII characters

curses.panel — curses 용 패널 스택 확장

함수

Panel 객체

platform — 하부 플랫폼의 식별 데이터에 대한 액세스

크로스 플랫폼

자바 플랫폼

윈도우 플랫폼

Win95/98 specific

Mac OS 플랫폼

유닉스 플랫폼

errno — 표준 errno 시스템 기호

ctypes — 파이썬용 외부 함수 라이브러리

ctypes 자습서

동적 링크 라이브러리 로드하기

로드된 dll에서 함수에 액세스하기

함수 호출하기

기본 데이터형

함수 호출하기, 계속

사용자 정의 데이터형을 사용하여 함수 호출하기

필수 인자 형 (함수 프로토타입) 지정하기

반환형

포인터 전달하기 (또는: 참조로 매개 변수 전달하기)

구조체와 공용체

구조체/공용체 정렬과 바이트 순서

구조체와 공용체의 비트 필드

배열

포인터

형 변환

불완전한 형

콜백 함수

dll에서 내 보낸 값을 액세스하기

의외의 것들

가변 크기 데이터형

ctypes 레퍼런스

공유 라이브러리 찾기

공유 라이브러리 로드하기

외부 함수

함수 프로토타입

유틸리티 함수

데이터형

기본 데이터형

구조화된 데이터형

배열과 포인터

동시 실행

threading — Thread-based parallelism

Thread-Local Data

Thread Objects

Lock Objects

RLock Objects

Condition Objects

Semaphore Objects

Semaphore Example

Event Objects

Timer Objects

Barrier Objects

Using locks, conditions, and semaphores in the with statement

multiprocessing — 프로세스 기반 병렬 처리

소개

Process 클래스

컨텍스트 및 시작 방법

프로세스 간 객체 교환

프로세스 간 동기화

프로세스 간 상태 공유

작업자 풀 사용

레퍼런스

Process와 예외

파이프와 큐

잡동사니

Connection 객체

동기화 프리미티브

공유 ctypes 객체

multiprocessing.sharedctypes 모듈

관리자

사용자 정의 관리자

원격 관리자 사용하기

프락시 객체

정리

프로세스 풀

리스너와 클라이언트

주소 형식

인증 키

로깅

multiprocessing.dummy 모듈

프로그래밍 지침

모든 시작 방법

spawn 과 forkserver 시작 방법

예제

concurrent 패키지

concurrent.futures — 병렬 작업 실행하기

Executor 객체

ThreadPoolExecutor

ThreadPoolExecutor 예제

ProcessPoolExecutor

ProcessPoolExecutor 예제

Future 객체

모듈 함수

예외 클래스

subprocess — Subprocess management

Using the subprocess Module

Frequently Used Arguments

Popen Constructor

Exceptions

Security Considerations

Popen Objects

Windows Popen Helpers

Windows Constants

Older high-level API

Replacing Older Functions with the subprocess Module

Replacing /bin/sh shell backquote

Replacing shell pipeline

Replacing os.system()

Replacing the os.spawn family

Replacing os.popen(), os.popen2(), os.popen3()

Replacing functions from the popen2 module

Legacy Shell Invocation Functions

Notes

Converting an argument sequence to a string on Windows

sched — 이벤트 스케줄러

스케줄러 객체

queue — 동기화된 큐 클래스

큐 객체

SimpleQueue 객체

_thread — 저수준 스레드 API

_dummy_thread — Drop-in replacement for the _thread module

dummy_threading — Drop-in replacement for the threading module

contextvars — 컨텍스트 변수

컨텍스트 변수

수동 컨텍스트 관리

asyncio 지원

네트워킹과 프로세스 간 통신

asyncio — 비동기 I/O

코루틴과 태스크

코루틴

어웨이터블

asyncio 프로그램 실행하기

태스크 만들기

잠자기

동시에 태스크 실행하기

취소로부터 보호하기

시간제한

대기 프리미티브

다른 스레드에서 예약하기

인트로스팩션

Task 객체

제너레이터 기반 코루틴

스트림

StreamReader

StreamWriter

예제

스트림을 사용하는 TCP 메아리 클라이언트

스트림을 사용하는 TCP 메아리 서버

HTTP 헤더 가져오기

스트림을 사용하여 데이터를 기다리는 열린 소켓 등록

동기화 프리미티브

Lock

Event

Condition

Semaphore

BoundedSemaphore

서브 프로세스

서브 프로세스 만들기

상수

서브 프로세스와 상호 작용하기

서브 프로세스와 스레드

예제

큐

Queue

우선순위 큐

LIFO 큐

예외

예제

예외

이벤트 루프

이벤트 루프 메서드

루프 실행 및 중지

콜백 예약하기

지연된 콜백 예약

퓨처와 태스크 만들기

네트워크 연결 열기

네트워크 서버 만들기

파일 전송

TLS 업그레이드

파일 기술자 관찰하기

소켓 객체로 직접 작업하기

DNS

파이프로 작업하기

유닉스 시그널

스레드 또는 프로세스 풀에서 코드를 실행하기

에러 처리 API

디버그 모드 활성화

자식 프로세스 실행하기

콜백 핸들

서버 객체

이벤트 루프 구현

예제

call_soon()을 사용하는 Hello World

call_later()로 현재 날짜를 표시합니다.

파일 기술자에서 읽기 이벤트를 관찰하기

SIGINT 및 SIGTERM에 대한 시그널 처리기 설정

퓨처

퓨처 함수

Future 객체

트랜스포트와 프로토콜

트랜스포트

트랜스포트 계층 구조

베이스 트랜스포트

읽기 전용 트랜스포트

쓰기 전용 트랜스포트

데이터 그램 트랜스포트

서브 프로세스 트랜스포트

프로토콜

베이스 프로토콜

베이스 프로토콜

스트리밍 프로토콜

버퍼 된 스트리밍 프로토콜

데이터 그램 프로토콜

서브 프로세스 프로토콜

예제

TCP 메아리 서버

TCP 메아리 클라이언트

UDP 메아리 서버

UDP 메아리 클라이언트

기존 소켓 연결하기

loop.subprocess_exec() 와 SubprocessProtocol

정책

정책을 얻고 설정하기

정책 객체

프로세스 감시자

사용자 정의 정책

플랫폼 지원

모든 플랫폼

윈도우

윈도우에서의 서브 프로세스 지원

macOS

고수준 API 색인

태스크

큐

서브 프로세스

스트림

동기화

예외

저수준 API 색인

이벤트 루프 얻기

이벤트 루프 메서드

트랜스포트

프로토콜

이벤트 루프 정책

asyncio로 개발하기

디버그 모드

동시성과 다중 스레드

블로킹 코드 실행하기

로깅

await 하지 않은 코루틴 감지

전달되지 않은 예외 감지

socket — 저수준 네트워킹 인터페이스

소켓 패밀리

모듈 내용

예외

상수

함수

소켓 만들기

기타 함수

소켓 객체

소켓 시간제한에 대한 참고 사항

시간제한과 connect 메서드

시간제한과 accept 메서드

예제

ssl — 소켓 객체용 TLS/SSL 래퍼

함수, 상수 및 예외

소켓 생성

컨텍스트 생성

예외

난수 생성

인증서 처리

상수

SSL 소켓

SSL 컨텍스트

인증서

인증서 체인

CA 인증서

결합한 키와 인증서

자체 서명 인증서

예제

SSL 지원 검사하기

클라이언트 측 연산

서버 측 연산

비 블로킹 소켓에 대한 참고 사항

메모리 BIO 지원

SSL 세션

보안 고려 사항

가장 좋은 기본값

수동 설정

인증서 확인

프로토콜 버전

사이퍼 선택

다중 프로세싱

TLS 1.3

LibreSSL 지원

select — Waiting for I/O completion

/dev/poll Polling Objects

Edge and Level Trigger Polling (epoll) Objects

Polling Objects

Kqueue Objects

Kevent Objects

selectors — 고수준 I/O 다중화

소개

클래스

예제

asyncore — Asynchronous socket handler

asyncore Example basic HTTP client

asyncore Example basic echo server

asynchat — Asynchronous socket command/response handler

asynchat Example

signal — Set handlers for asynchronous events

General rules

Execution of Python signal handlers

Signals and threads

Module contents

Example

Note on SIGPIPE

mmap — 메모리 맵 파일 지원

인터넷 데이터 처리

email — 전자 메일과 MIME 처리 패키지

email.message: Representing an email message

email.parser: Parsing email messages

FeedParser API

Parser API

Additional notes

email.generator: Generating MIME documents

email.policy: Policy Objects

email.errors: 예외와 결함 클래스

email.headerregistry: Custom Header Objects

email.contentmanager: MIME 콘텐츠 관리

콘텐츠 관리자 인스턴스

email: 예제

email.message.Message: Representing an email message using the compat32 API

email.mime: Creating email and MIME objects from scratch

email.header: Internationalized headers

email.charset: Representing character sets

email.encoders: Encoders

email.utils: 기타 유틸리티

email.iterators: 이터레이터

json — JSON 인코더와 디코더

기본 사용법

인코더와 디코더

예외

표준 준수와 상호 운용성

문자 인코딩

무한대와 NaN 숫자 값

오브젝트 내에서 반복된 이름

오브젝트나 배열이 아닌 최상윗값

구현 제약 사항

명령 줄 인터페이스

명령 줄 옵션

mailcap — Mailcap 파일 처리

mailbox — Manipulate mailboxes in various formats

Mailbox objects

Maildir

mbox

MH

Babyl

MMDF

Message objects

MaildirMessage

mboxMessage

MHMessage

BabylMessage

MMDFMessage

Exceptions

Examples

mimetypes — 파일명을 MIME 유형에 매핑

MimeTypes 객체

base64 — Base16, Base32, Base64, Base85 데이터 인코딩

binhex — binhex4 파일 인코딩과 디코딩

노트

binascii — 바이너리와 ASCII 간의 변환

quopri — MIME quoted-printable 데이터 인코딩과 디코딩

uu — uuencode 파일 인코딩과 디코딩

구조화된 마크업 처리 도구

html — 하이퍼텍스트 마크업 언어 지원

html.parser — 간단한 HTML과 XHTML 구문 분석기

HTML 구문 분석기 응용 프로그램 예제

HTMLParser 메서드

예제

html.entities — HTML 일반 엔티티의 정의

XML 처리 모듈

XML 취약점

defusedxml와 defusedexpat 패키지

xml.etree.ElementTree — The ElementTree XML API

Tutorial

XML tree and elements

Parsing XML

Pull API for non-blocking parsing

Finding interesting elements

Modifying an XML File

Building XML documents

Parsing XML with Namespaces

Additional resources

XPath support

Example

Supported XPath syntax

Reference

Functions

XInclude support

Example

Reference

Functions

Element Objects

ElementTree Objects

QName Objects

TreeBuilder Objects

XMLParser Objects

XMLPullParser Objects

Exceptions

xml.dom — 문서 객체 모델 API

모듈 내용

DOM의 객체

DOMImplementation 객체

Node 객체

NodeList 객체

DocumentType 객체

Document 객체

Element 객체

Attr 객체

NamedNodeMap 객체

Comment 객체

Text와 CDATASection 객체

ProcessingInstruction 객체

예외

규격 준수

형 매핑

접근자 메서드

xml.dom.minidom — 최소 DOM 구현

DOM 객체

DOM 예제

minidom과 DOM 표준

xml.dom.pulldom — 부분 DOM 트리 구축 지원

DOMEventStream 객체

xml.sax — SAX2 구문 분석기 지원

SAXException 객체

xml.sax.handler — Base classes for SAX handlers

ContentHandler Objects

DTDHandler Objects

EntityResolver Objects

ErrorHandler Objects

xml.sax.saxutils — SAX 유틸리티

xml.sax.xmlreader — XML 구문 분석기 인터페이스

XMLReader 객체

IncrementalParser 객체

Locator 객체

InputSource 객체

Attributes 인터페이스

AttributesNS 인터페이스

xml.parsers.expat — Fast XML parsing using Expat

XMLParser Objects

ExpatError Exceptions

Example

Content Model Descriptions

Expat error constants

인터넷 프로토콜과 지원

webbrowser — 편리한 웹 브라우저 제어기

브라우저 제어기 객체

cgi — Common Gateway Interface support

Introduction

Using the cgi module

Higher Level Interface

Functions

Caring about security

Installing your CGI script on a Unix system

Testing your CGI script

Debugging CGI scripts

Common problems and solutions

cgitb — CGI 스크립트를 위한 트레이스백 관리자

wsgiref — WSGI 유틸리티와 참조 구현

wsgiref.util – WSGI 환경 유틸리티

wsgiref.headers – WSGI 응답 헤더 도구

wsgiref.simple_server – 간단한 WSGI HTTP 서버

wsgiref.validate — WSGI 적합성 검사기

wsgiref.handlers – 서버/게이트웨이 베이스 클래스

예제

urllib — URL 처리 모듈

urllib.request — Extensible library for opening URLs

Request Objects

OpenerDirector Objects

BaseHandler Objects

HTTPRedirectHandler Objects

HTTPCookieProcessor Objects

ProxyHandler Objects

HTTPPasswordMgr Objects

HTTPPasswordMgrWithPriorAuth Objects

AbstractBasicAuthHandler Objects

HTTPBasicAuthHandler Objects

ProxyBasicAuthHandler Objects

AbstractDigestAuthHandler Objects

HTTPDigestAuthHandler Objects

ProxyDigestAuthHandler Objects

HTTPHandler Objects

HTTPSHandler Objects

FileHandler Objects

DataHandler Objects

FTPHandler Objects

CacheFTPHandler Objects

UnknownHandler Objects

HTTPErrorProcessor Objects

Examples

Legacy interface

urllib.request Restrictions

urllib.response — Response classes used by urllib

urllib.parse — Parse URLs into components

URL Parsing

URL parsing security

Parsing ASCII Encoded Bytes

Structured Parse Results

URL Quoting

urllib.error — urllib.request에 의해 발생하는 예외 클래스

urllib.robotparser — robots.txt 구문 분석기

http — HTTP 모듈

HTTP 상태 코드

http.client — HTTP protocol client

HTTPConnection Objects

HTTPResponse Objects

Examples

HTTPMessage Objects

ftplib — FTP protocol client

FTP Objects

FTP_TLS Objects

poplib — POP3 프로토콜 클라이언트

POP3 객체

POP3 예제

imaplib — IMAP4 protocol client

IMAP4 Objects

IMAP4 Example

nntplib — NNTP protocol client

NNTP Objects

Attributes

Methods

Utility functions

smtplib — SMTP protocol client

SMTP Objects

SMTP Example

smtpd — SMTP Server

SMTPServer Objects

DebuggingServer Objects

PureProxy Objects

MailmanProxy Objects

SMTPChannel Objects

telnetlib — 텔넷 클라이언트

텔넷 객체

텔넷 예제

uuid — RFC 4122 에 따른 UUID 객체

예제

socketserver — A framework for network servers

Server Creation Notes

Server Objects

Request Handler Objects

Examples

socketserver.TCPServer Example

socketserver.UDPServer Example

Asynchronous Mixins

http.server — HTTP servers

Security Considerations

http.cookies — HTTP 상태 관리

쿠키 객체

Morsel 객체

예제

http.cookiejar — Cookie handling for HTTP clients

CookieJar and FileCookieJar Objects

FileCookieJar subclasses and co-operation with web browsers

CookiePolicy Objects

DefaultCookiePolicy Objects

Cookie Objects

Examples

xmlrpc — XMLRPC 서버와 클라이언트 모듈

xmlrpc.client — XML-RPC client access

ServerProxy Objects

DateTime Objects

Binary Objects

Fault Objects

ProtocolError Objects

MultiCall Objects

Convenience Functions

Example of Client Usage

Example of Client and Server Usage

xmlrpc.server — 기본 XML-RPC 서버

SimpleXMLRPCServer 객체

SimpleXMLRPCServer 예제

CGIXMLRPCRequestHandler

XMLRPC 서버 문서화

DocXMLRPCServer 객체

DocCGIXMLRPCRequestHandler

ipaddress — IPv4/IPv6 manipulation library

Convenience factory functions

IP Addresses

Address objects

Conversion to Strings and Integers

Operators

Comparison operators

Arithmetic operators

IP Network definitions

Prefix, net mask and host mask

Network objects

Operators

Logical operators

Iteration

Networks as containers of addresses

Interface objects

Operators

Logical operators

Other Module Level Functions

Custom Exceptions

멀티미디어 서비스

audioop — Manipulate raw audio data

aifc — AIFF와 AIFC 파일 읽고 쓰기

sunau — Sun AU 파일 읽고 쓰기

AU_read 객체

AU_write 객체

wave — WAV 파일 읽고 쓰기

Wave_read 객체

Wave_write 객체

chunk — IFF 청크된 데이터 읽기

colorsys — 색 체계 간의 변환

imghdr — 이미지 유형 판단

sndhdr — 음향 파일 유형 판단

ossaudiodev — Access to OSS-compatible audio devices

Audio Device Objects

Mixer Device Objects

국제화

gettext — Multilingual internationalization services

GNU gettext API

Class-based API

The NullTranslations class

The GNUTranslations class

Solaris message catalog support

The Catalog constructor

Internationalizing your programs and modules

Localizing your module

Localizing your application

Changing languages on the fly

Deferred translations

Acknowledgements

locale — Internationalization services

Background, details, hints, tips and caveats

For extension writers and programs that embed Python

Access to message catalogs

프로그램 프레임워크

turtle — Turtle graphics

Introduction

Overview of available Turtle and Screen methods

Turtle methods

Methods of TurtleScreen/Screen

Methods of RawTurtle/Turtle and corresponding functions

Turtle motion

Tell Turtle’s state

Settings for measurement

Pen control

Drawing state

Color control

Filling

More drawing control

Turtle state

Visibility

Appearance

Using events

Special Turtle methods

Compound shapes

Methods of TurtleScreen/Screen and corresponding functions

Window control

Animation control

Using screen events

Input methods

Settings and special methods

Methods specific to Screen, not inherited from TurtleScreen

Public classes

Help and configuration

How to use help

Translation of docstrings into different languages

How to configure Screen and Turtles

turtledemo — Demo scripts

Changes since Python 2.6

Changes since Python 3.0

cmd — 줄 지향 명령 인터프리터 지원

Cmd 객체

Cmd 예

shlex — Simple lexical analysis

shlex Objects

Parsing Rules

Improved Compatibility with Shells

Tk를 사용한 그래픽 사용자 인터페이스

tkinter — Tcl/Tk 파이썬 인터페이스

Tkinter 모듈

Tkinter 구명조끼

이 절을 사용하는 방법

간단한 Hello World 프로그램

Tcl/Tk (아주 빨리) 훑어보기

기본 Tk를 Tkinter로 매핑하기

Tk와 Tkinter의 관계

간편한 레퍼런스

옵션 설정

패커

패커 옵션

위젯 변수 결합하기

창 관리자

Tk 옵션 데이터형

바인딩과 이벤트

index 매개 변수

이미지

파일 처리기

tkinter.ttk — Tk themed widgets

Using Ttk

Ttk Widgets

Widget

Standard Options

Scrollable Widget Options

Label Options

Compatibility Options

Widget States

ttk.Widget

Combobox

Options

Virtual events

ttk.Combobox

Spinbox

Options

Virtual events

ttk.Spinbox

Notebook

Options

Tab Options

Tab Identifiers

Virtual Events

ttk.Notebook

Progressbar

Options

ttk.Progressbar

Separator

Options

Sizegrip

Platform-specific notes

Bugs

Treeview

Options

Item Options

Tag Options

Column Identifiers

Virtual Events

ttk.Treeview

Ttk Styling

Layouts

tkinter.tix — Extension widgets for Tk

Using Tix

Tix Widgets

Basic Widgets

File Selectors

Hierarchical ListBox

Tabular ListBox

Manager Widgets

Image Types

Miscellaneous Widgets

Form Geometry Manager

Tix Commands

tkinter.scrolledtext — 스크롤 되는 Text 위젯

IDLE

Menus

File menu (Shell and Editor)

Edit menu (Shell and Editor)

Format menu (Editor window only)

Run menu (Editor window only)

Shell menu (Shell window only)

Debug menu (Shell window only)

Options menu (Shell and Editor)

Window menu (Shell and Editor)

Help menu (Shell and Editor)

Context Menus

Editing and navigation

Editor windows

Key bindings

Automatic indentation

Completions

Calltips

Code Context

Python Shell window

Text colors

Startup and code execution

Command line usage

Startup failure

Running user code

User output in Shell

Developing tkinter applications

Running without a subprocess

Help and preferences

Help sources

Setting preferences

IDLE on macOS

Extensions

기타 그래픽 사용자 인터페이스 패키지

개발 도구

typing — Support for type hints

Type aliases

NewType

Callable

Generics

User-defined generic types

The Any type

Classes, functions, and decorators

pydoc — 설명서 생성과 온라인 도움말 시스템

doctest — 대화형 파이썬 예제 테스트

간단한 사용법: 독스트링에 있는 예제 확인하기

간단한 사용법: 텍스트 파일에 있는 예제 확인하기

작동 방법

어떤 독스트링을 검사합니까?

독스트링 예제는 어떻게 인식됩니까?

실행 컨텍스트란 무엇입니까?

예외는 어떻게 됩니까?

옵션 플래그

지시자

경고

기본 API

Unittest API

고급 API

DocTest 객체

Example 객체

DocTestFinder 객체

DocTestParser 객체

DocTestRunner 객체

OutputChecker 객체

디버깅

맺음말

unittest — 단위 테스트 프레임워크

기본 예시

명령행 인터페이스

명령행 옵션

테스트 탐색(Discovery)

테스트 코드 구조 잡기

이전의 테스트 코드를 다시 사용하기

테스트 건너뛰기와 예상된 실패

부분 테스트(subtest)를 사용하여 테스트 반복 구별 짖기

클래스와 함수

테스트 케이스

폐지된 에일리어스

테스트 분류

테스트를 로드하고 실행하기

load_tests 프로토콜

클래스와 모듈 픽스쳐

setUpClass 와 tearDownClass

setUpModule 과 tearDownModule

시그널 처리하기

unittest.mock — mock object library

Quick Guide

The Mock Class

Calling

Deleting Attributes

Mock names and the name attribute

Attaching Mocks as Attributes

The patchers

patch

patch.object

patch.dict

patch.multiple

patch methods: start and stop

patch builtins

TEST_PREFIX

Nesting Patch Decorators

Where to patch

Patching Descriptors and Proxy Objects

MagicMock and magic method support

Mocking Magic Methods

Magic Mock

Helpers

sentinel

DEFAULT

call

create_autospec

ANY

FILTER_DIR

mock_open

Autospeccing

Sealing mocks

unittest.mock — getting started

Using Mock

Mock Patching Methods

Mock for Method Calls on an Object

Mocking Classes

Naming your mocks

Tracking all Calls

Setting Return Values and Attributes

Raising exceptions with mocks

Side effect functions and iterables

Creating a Mock from an Existing Object

Patch Decorators

Further Examples

Mocking chained calls

Partial mocking

Mocking a Generator Method

Applying the same patch to every test method

Mocking Unbound Methods

Checking multiple calls with mock

Coping with mutable arguments

Nesting Patches

Mocking a dictionary with MagicMock

Mock subclasses and their attributes

Mocking imports with patch.dict

Tracking order of calls and less verbose call assertions

More complex argument matching

2to3 - 파이썬 2에서 파이썬 3으로 자동 코드 변환

2to3 사용법

변환자 목록

lib2to3 - 2to3 라이브러리

test — Regression tests package for Python

Writing Unit Tests for the test package

Running tests using the command-line interface

test.support — Utilities for the Python test suite

test.support.script_helper — Utilities for the Python execution tests

디버깅과 프로파일링

bdb — Debugger framework

faulthandler — 파이썬 트레이스백 덤프

트레이스백 덤프하기

결함 처리기 상태

시간 초과 후에 트레이스백 덤프하기

사용자 시그널에 트레이스백 덤프하기

파일 기술자 관련 문제

예제

pdb — 파이썬 디버거

디버거 명령들

The Python Profilers

Introduction to the profilers

Instant User’s Manual

profile and cProfile Module Reference

The Stats Class

What Is Deterministic Profiling?

Limitations

Calibration

Using a custom timer

timeit — 작은 코드 조각의 실행 시간 측정

기본 예제

파이썬 인터페이스

명령 줄 인터페이스

예제

trace — 파이썬 문장 실행 추적

명령 줄 사용법

주요 옵션

수정자

필터

프로그래밍 인터페이스

tracemalloc — Trace memory allocations

Examples

Display the top 10

Compute differences

Get the traceback of a memory block

Pretty top

API

Functions

DomainFilter

Filter

Frame

Snapshot

Statistic

StatisticDiff

Trace

Traceback

소프트웨어 패키징 및 배포

distutils — 파이썬 모듈 빌드와 설치

ensurepip — pip 설치 프로그램 부트스트랩

명령 줄 인터페이스

모듈 API

venv — 가상 환경 생성

가상 환경 만들기

API

EnvBuilder 확장 예제

zipapp — Manage executable Python zip archives

Basic Example

Command-Line Interface

Python API

Examples

Specifying the Interpreter

Creating Standalone Applications with zipapp

Making a Windows executable

Caveats

The Python Zip Application Archive Format

파이썬 실행시간 서비스

sys — System-specific parameters and functions

sysconfig — 파이썬의 구성 정보에 접근하기

구성 변수

설치 경로

기타 함수

sysconfig 를 스크립트로 사용하기

builtins — 내장 객체

__main__ — 최상위 스크립트 환경

warnings — Warning control

Warning Categories

The Warnings Filter

Describing Warning Filters

Default Warning Filter

Overriding the default filter

Temporarily Suppressing Warnings

Testing Warnings

Updating Code For New Versions of Dependencies

Available Functions

Available Context Managers

dataclasses — 데이터 클래스

모듈 수준의 데코레이터, 클래스 및 함수

초기화 후처리

클래스 변수

초기화 전용 변수

고정 인스턴스

계승

기본 팩토리 함수

가변 기본값

예외

contextlib — Utilities for with-statement contexts

Utilities

Examples and Recipes

Supporting a variable number of context managers

Catching exceptions from __enter__ methods

Cleaning up in an __enter__ implementation

Replacing any use of try-finally and flag variables

Using a context manager as a function decorator

Single use, reusable and reentrant context managers

Reentrant context managers

Reusable context managers

abc — 추상 베이스 클래스

atexit — 종료 처리기

atexit 예제

traceback — 스택 트레이스백 인쇄와 조회

TracebackException 객체

StackSummary 객체

FrameSummary 객체

트레이스백 예제

__future__ — 퓨처 문 정의

gc — 가비지 수거기 인터페이스

inspect — Inspect live objects

Types and members

Retrieving source code

Introspecting callables with the Signature object

Classes and functions

The interpreter stack

Fetching attributes statically

Current State of Generators and Coroutines

Code Objects Bit Flags

Command Line Interface

site — 사이트별 구성 훅

Readline 구성

모듈 내용

Command Line Interface

사용자 정의 파이썬 인터프리터

code — 인터프리터 베이스 클래스

대화형 인터프리터 객체

대화형 콘솔 객체

codeop — 파이썬 코드 컴파일

모듈 임포트 하기

zipimport — Zip 저장소에서 모듈 임포트

zipimporter 객체

예제

pkgutil — 패키지 확장 유틸리티

modulefinder — 스크립트에서 사용되는 모듈 찾기

ModuleFinder의 사용 예

runpy — 파이썬 모듈 찾기와 실행

importlib — The implementation of import

Introduction

Functions

importlib.abc – Abstract base classes related to import

importlib.resources – Resources

importlib.machinery – Importers and path hooks

importlib.util – Utility code for importers

Examples

Importing programmatically

Checking if a module can be imported

Importing a source file directly

Setting up an importer

Approximating importlib.import_module()

파이썬 언어 서비스

parser — Access Python parse trees

Creating ST Objects

Converting ST Objects

Queries on ST Objects

Exceptions and Error Handling

ST Objects

Example: Emulation of compile()

ast — Abstract Syntax Trees

Node classes

Abstract Grammar

ast Helpers

symtable — 컴파일러 심볼 테이블 액세스

심볼 테이블 생성하기

심볼 테이블 검사하기

symbol — 파이썬 구문 분석 트리에 사용되는 상수

token — 파이썬 구문 분석 트리에 사용되는 상수

keyword — 파이썬 키워드 검사

tokenize — 파이썬 소스를 위한 토크나이저

입력 토큰화하기

명령 줄 사용법

예제

tabnanny — 모호한 들여쓰기 감지

pyclbr — Python module browser support

Function 객체

Class 객체

py_compile — 파이썬 소스 파일 컴파일

compileall — 파이썬 라이브러리 바이트 컴파일하기

명령 줄 사용

공용 함수

dis — Disassembler for Python bytecode

Bytecode analysis

Analysis functions

Python Bytecode Instructions

Opcode collections

pickletools — 피클 개발자를 위한 도구

명령 줄 사용법

명령 줄 옵션

프로그래밍 인터페이스

기타 서비스

formatter — Generic output formatting

The Formatter Interface

Formatter Implementations

The Writer Interface

Writer Implementations

MS 윈도우 특정 서비스

msilib — Read and write Microsoft Installer files

Database Objects

View Objects

Summary Information Objects

Record Objects

Errors

CAB Objects

Directory Objects

Features

GUI classes

Precomputed tables

msvcrt — MS VC++ 런타임의 유용한 루틴

파일 연산

콘솔 I/O

기타 함수

winreg — Windows registry access

Functions

Constants

HKEY_* Constants

Access Rights

64-bit Specific

Value Types

Registry Handle Objects

winsound — 윈도우용 소리 재생 인터페이스

유닉스 특정 서비스

posix — 가장 일반적인 POSIX 시스템 호출

대용량 파일 지원

주목할만한 모듈 내용

pwd — 암호 데이터베이스

spwd — 섀도 암호 데이터베이스

grp — 그룹 데이터베이스

crypt — 유닉스 비밀번호 확인 함수

해싱 방법

모듈 어트리뷰트

모듈 함수

예제

termios — POSIX 스타일 tty 제어

예제

tty — 터미널 제어 함수

pty — 의사 터미널 유틸리티

예제

fcntl — fcntl과 ioctl 시스템 호출

pipes — 셸 파이프라인에 대한 인터페이스

Template 객체

resource — 자원 사용 정보

자원 제한

자원 사용량

nis — Sun의 NIS(옐로 페이지)에 대한 인터페이스

syslog — 유닉스 syslog 라이브러리 루틴

예제

간단한 예제

대체된 모듈

optparse — Parser for command line options

Background

Terminology

What are options for?

What are positional arguments for?

Tutorial

Understanding option actions

The store action

Handling boolean (flag) options

Other actions

Default values

Generating help

Grouping Options

Printing a version string

How optparse handles errors

Putting it all together

Reference Guide

Creating the parser

Populating the parser

Defining options

Option attributes

Standard option actions

Standard option types

Parsing arguments

Querying and manipulating your option parser

Conflicts between options

Cleanup

Other methods

Option Callbacks

Defining a callback option

How callbacks are called

Raising errors in a callback

Callback example 1: trivial callback

Callback example 2: check option order

Callback example 3: check option order (generalized)

Callback example 4: check arbitrary condition

Callback example 5: fixed arguments

Callback example 6: variable arguments

Extending optparse

Adding new types

Adding new actions

imp — Access the import internals

Examples

문서로 만들어지지 않은 모듈

플랫폼 특정 모듈

파이썬 인터프리터 확장 및 내장

권장 제삼자 도구

제삼자 도구 없이 확장 만들기

1. Extending Python with C or C++

1.1. A Simple Example

1.2. Intermezzo: Errors and Exceptions

1.3. Back to the Example

1.4. The Module’s Method Table and Initialization Function

1.5. Compilation and Linkage

1.6. Calling Python Functions from C

1.7. Extracting Parameters in Extension Functions

1.8. Keyword Parameters for Extension Functions

1.9. Building Arbitrary Values

1.10. Reference Counts

1.10.1. Reference Counting in Python

1.10.2. Ownership Rules

1.10.3. Thin Ice

1.10.4. NULL Pointers

1.11. Writing Extensions in C++

1.12. Providing a C API for an Extension Module

2. Defining Extension Types: Tutorial

2.1. The Basics

2.2. Adding data and methods to the Basic example

2.3. Providing finer control over data attributes

2.4. Supporting cyclic garbage collection

2.5. Subclassing other types

3. Defining Extension Types: Assorted Topics

3.1. Finalization and De-allocation

3.2. Object Presentation

3.3. Attribute Management

3.3.1. Generic Attribute Management

3.3.2. Type-specific Attribute Management

3.4. Object Comparison

3.5. Abstract Protocol Support

3.6. Weak Reference Support

3.7. More Suggestions

4. C와 C++ 확장 빌드하기

4.1. distutils로 C와 C++ 확장 빌드하기

4.2. 확장 모듈 배포하기

5. 윈도우에서 C와 C++ 확장 빌드하기

5.1. 요리책 접근법

5.2. 유닉스와 윈도우의 차이점

5.3. DLL을 실제로 사용하기

더 큰 응용 프로그램에 CPython 런타임을 내장하기

1. 다른 응용 프로그램에 파이썬 내장하기

1.1. 매우 고수준의 내장

1.2. 매우 고수준 내장을 넘어서: 개요

1.3. 순수한 내장

1.4. 내장된 파이썬을 확장하기

1.5. C++로 파이썬 내장하기

1.6. 유닉스 계열 시스템에서 컴파일과 링크하기

파이썬/C API 레퍼런스 설명서

Introduction

Coding standards

Include Files

Useful macros

Objects, Types and Reference Counts

Reference Counts

Reference Count Details

Types

Exceptions

Embedding Python

Debugging Builds

안정적인 응용 프로그램 바이너리 인터페이스

The Very High Level Layer

참조 횟수

Exception Handling

Printing and clearing

Raising exceptions

Issuing warnings

Querying the error indicator

Signal Handling

Exception Classes

Exception Objects

Unicode Exception Objects

Recursion Control

Standard Exceptions

Standard Warning Categories

유틸리티

Operating System Utilities

System Functions

Process Control

모듈 임포트 하기

데이터 마샬링 지원

Parsing arguments and building values

Parsing arguments

Strings and buffers

Numbers

Other objects

API Functions

Building values

문자열 변환과 포매팅

리플렉션

코덱 등록소와 지원 함수

코덱 조회 API

유니코드 인코딩 에러 처리기용 등록소 API

추상 객체 계층

Object Protocol

숫자 프로토콜

시퀀스 프로토콜

매핑 프로토콜

이터레이터 프로토콜

버퍼 프로토콜

버퍼 구조체

버퍼 요청 유형

요청 독립적 필드

readonly, format

shape, strides, suboffsets

연속성 요청

복합 요청

복잡한 배열

NumPy-스타일: shape과 strides

PIL-스타일: shape, strides 및 suboffsets

버퍼 관련 함수

낡은 버퍼 프로토콜

구상 객체 계층

기본 객체

형 객체

None 객체

숫자 객체

정수 객체

불리언 객체

부동 소수점 객체

복소수 객체

C 구조체로서의 복소수

파이썬 객체로서의 복소수

시퀀스 객체

바이트열 객체

바이트 배열 객체

형 검사 매크로

직접 API 함수

매크로

Unicode Objects and Codecs

Unicode Objects

Unicode Type

Unicode Character Properties

Creating and accessing Unicode strings

Deprecated Py_UNICODE APIs

Locale Encoding

File System Encoding

wchar_t Support

Built-in Codecs

Generic Codecs

UTF-8 Codecs

UTF-32 Codecs

UTF-16 Codecs

UTF-7 Codecs

Unicode-Escape Codecs

Raw-Unicode-Escape Codecs

Latin-1 Codecs

ASCII Codecs

Character Map Codecs

MBCS codecs for Windows

Methods & Slots

Methods and Slot Functions

튜플 객체

구조체 시퀀스 객체

리스트 객체

컨테이너 객체

딕셔너리 객체

집합 객체

함수 객체

함수 객체

인스턴스 메서드 객체

메서드 객체

셀 객체

코드 객체

기타 객체

파일 객체

Module Objects

Initializing C modules

Single-phase initialization

Multi-phase initialization

Low-level module creation functions

Support functions

Module lookup

이터레이터 객체

디스크립터 객체

슬라이스 객체

Ellipsis 객체

MemoryView 객체

약한 참조 객체

캡슐

제너레이터 객체

코루틴 객체

컨텍스트 변수 객체

DateTime 객체

Initialization, Finalization, and Threads

Before Python Initialization

Global configuration variables

Initializing and finalizing the interpreter

Process-wide parameters

Thread State and the Global Interpreter Lock

Releasing the GIL from extension code

Non-Python created threads

High-level API

Low-level API

Sub-interpreter support

Bugs and caveats

Asynchronous Notifications

Profiling and Tracing

Advanced Debugger Support

Thread Local Storage Support

Thread Specific Storage (TSS) API

Dynamic Allocation

Methods

Thread Local Storage (TLS) API

Memory Management

Overview

Raw Memory Interface

Memory Interface

Object allocators

Default Memory Allocators

Customize Memory Allocators

The pymalloc allocator

Customize pymalloc Arena Allocator

tracemalloc C API

Examples

객체 구현 지원

힙에 객체 할당하기

Common Object Structures

Type Objects

Number Object Structures

Mapping Object Structures

Sequence Object Structures

Buffer Object Structures

Async Object Structures

순환 가비지 수집 지원

API와 ABI 버전 붙이기

파이썬 모듈 배포하기

핵심 용어

공개 소스 라이센스 와 협업

도구 설치하기

파이썬 패키징 사용자 지침서 읽기

어떻게 …?

… 내 프로젝트의 이름을 고릅니까?

… 바이너리 확장을 만들고 배포합니까?

파이썬 모듈 설치하기

핵심 용어

기본 사용법

어떻게 …?

… 파이썬 3.4 이전 버전의 파이썬에서 pip 를 설치합니까?

… 현재 사용자만을 위해 패키지를 설치합니까?

… 과학 계산용 파이썬 패키지를 설치합니까?

… 병렬로 설치된 여러 버전의 파이썬으로 작업합니까?

흔히 만나는 설치 문제

리눅스에 시스템 파이썬 설치하기

Pip가 설치되지 않았습니다.

바이너리 확장 설치하기

파이썬 HOWTO

Porting Python 2 Code to Python 3

The Short Explanation

Details

Drop support for Python 2.6 and older

Make sure you specify the proper version support in your setup.py file

Have good test coverage

Learn the differences between Python 2 & 3

Update your code

Division

Text versus binary data

Use feature detection instead of version detection

Prevent compatibility regressions

Check which dependencies block your transition

Update your setup.py file to denote Python 3 compatibility

Use continuous integration to stay compatible

Consider using optional static type checking

확장 모듈을 파이썬 3에 이식하기

조건부 컴파일

객체 API의 변경 사항

str/unicode 통합

long/int 통합

모듈 초기화와 상태

캡슐로 대체된 CObject

다른 옵션

Curses Programming with Python

What is curses?

The Python curses module

Starting and ending a curses application

Windows and Pads

Displaying Text

Attributes and Color

User Input

For More Information

Descriptor HowTo Guide

Abstract

Definition and Introduction

Descriptor Protocol

Invoking Descriptors

Descriptor Example

Properties

Functions and Methods

Static Methods and Class Methods

함수형 프로그래밍 HOWTO

소개

형식적 증명 가능성

모듈성

디버깅과 테스트 용이성

결합성

이터레이터

이터레이터를 지원하는 데이터형

제너레이터 표현식과 리스트 컴프리헨션

제너레이터

제너레이터에 값 전달하기

내장 함수

itertools 모듈

새로운 이터레이터 만들기

요소에 대한 함수 호출

요소 선택하기

조합 함수

요소 분류

functools 모듈

operator 모듈

작은 함수와 람다 표현식

개정내역 및 감사의 글

참고 문헌

일반

파이썬 특정

파이썬 설명서

로깅 HOWTO

기초 로깅 자습서

로깅을 사용할 때

간단한 예

파일에 로깅 하기

여러 모듈에서의 로깅

변수 데이터 로깅

표시된 메시지의 포맷 변경

메시지에 날짜/시간 표시

다음 단계

고급 로깅 자습서

로깅 흐름

로거

처리기

포매터

로깅 구성

구성이 제공되지 않으면 어떻게 되는가

라이브러리 로깅 구성

로깅 수준

사용자 정의 수준

유용한 처리기

로깅 중에 발생하는 예외

임의의 객체를 메시지로 사용하기

최적화

로깅 요리책

여러 모듈에서 로깅 사용하기

여러 스레드에서 로깅 하기

다중 처리기 및 포매터

여러 대상으로 로깅 하기

구성 서버 예제

블록 하는 처리기 다루기

네트워크에서 로깅 이벤트 보내고 받기

로그 출력에 문맥 정보 추가

문맥 정보 전달에 LoggerAdapters 사용하기

딕셔너리 이외의 객체를 사용하여 문맥 정보 전달하기

문맥 정보 전달에 필터 사용하기

여러 프로세스에서 단일 파일에 로깅 하기

Using concurrent.futures.ProcessPoolExecutor

파일 회전 사용하기

대체 포매팅 스타일 사용하기

사용자 정의 LogRecord

QueueHandler 서브 클래스 만들기 - ZeroMQ 예제

QueueListener 서브 클래스 만들기 - ZeroMQ 예제

딕셔너리 기반 구성의 예

rotator와 namer를 사용해서 로그 회전 처리하기

좀 더 정교한 multiprocessing 예제

SysLogHandler로 전송된 메시지에 BOM 삽입하기

구조적 로깅 구현

dictConfig()로 처리기를 사용자 정의하기

응용 프로그램 전체에서 특정 포맷 스타일 사용하기

LogRecord 팩토리 사용

사용자 정의 메시지 객체 사용

dictConfig()로 필터 구성하기

사용자 정의된 예외 포매팅

로깅 메시지 말하기

로깅 메시지를 버퍼링하고 조건부 출력하기

구성을 통해 UTC(GMT)로 시간을 포맷하기

선택적 로깅을 위해 컨텍스트 관리자 사용하기

A CLI application starter template

A Qt GUI for logging

Regular Expression HOWTO

Introduction

Simple Patterns

Matching Characters

Repeating Things

Using Regular Expressions

Compiling Regular Expressions

The Backslash Plague

Performing Matches

Module-Level Functions

Compilation Flags

More Pattern Power

More Metacharacters

Grouping

Non-capturing and Named Groups

Lookahead Assertions

Modifying Strings

Splitting Strings

Search and Replace

Common Problems

Use String Methods

match() versus search()

Greedy versus Non-Greedy

Using re.VERBOSE

Feedback

소켓 프로그래밍 HOWTO

소켓

역사

소켓 만들기

IPC

소켓 사용하기

바이너리 데이터

연결 끊기

소켓이 죽을 때

비 블로킹 소켓

정렬 HOW TO

정렬 기초

키 함수

operator 모듈 함수

오름차순과 내림차순

정렬 안정성과 복잡한 정렬

장식-정렬-복원을 사용하는 낡은 방법

cmp 매개 변수를 사용하는 낡은 방법

잡동사니

유니코드 HOWTO

유니코드 소개

정의

인코딩

참조

파이썬의 유니코드 지원

문자열 형

바이트열로 변환

파이썬 소스 코드에서 유니코드 리터럴

유니코드 속성

Comparing Strings

유니코드 정규식

참조

유니코드 데이터 읽고 쓰기

유니코드 파일 이름

유니코드 인식 프로그램 작성 팁

파일 인코딩끼리 변환

알 수 없는 인코딩의 파일

참조

감사 인사

HOWTO Fetch Internet Resources Using The urllib Package

Introduction

Fetching URLs

Data

Headers

Handling Exceptions

URLError

HTTPError

Error Codes

Wrapping it Up

Number 1

Number 2

info and geturl

Openers and Handlers

Basic Authentication

Proxies

Sockets and Layers

Footnotes

Argparse 자습서

개념

기본

위치 인자 소개

옵션 인자 소개

짧은 옵션

위치 및 옵션 인자 결합하기

조금 더 발전시키기

충돌하는 옵션들

맺음말

ipaddress 모듈에 대한 소개

주소/네트워크/인터페이스 객체 만들기

IP 버전에 대한 참고 사항

IP 호스트 주소

네트워크 정의

호스트 인터페이스

주소/네트워크/인터페이스 객체 검사

주소 리스트로서의 네트워크

비교

다른 모듈과 함께 IP 주소 사용하기

인스턴스 생성 실패 시 세부 사항 가져오기

Argument Clinic How-To

The Goals Of Argument Clinic

Basic Concepts And Usage

Converting Your First Function

Advanced Topics

Symbolic default values

Renaming the C functions and variables generated by Argument Clinic

Converting functions using PyArg_UnpackTuple

Optional Groups

Using real Argument Clinic converters, instead of “legacy converters”

Py_buffer

Advanced converters

Parameter default values

The NULL default value

Expressions specified as default values

Using a return converter

Cloning existing functions

Calling Python code

Using a “self converter”

Writing a custom converter

Writing a custom return converter

METH_O and METH_NOARGS

tp_new and tp_init functions

Changing and redirecting Clinic’s output

The #ifdef trick

Using Argument Clinic in Python files

DTrace와 SystemTap으로 CPython 계측하기

정적 마커 활성화하기

정적 DTrace 프로브

정적 SystemTap 마커

사용 가능한 정적 마커

SystemTap 탭셋

예제

파이썬 자주 나오는 질문들

General Python FAQ

General Information

Python in the real world

Programming FAQ

General Questions

Core Language

Numbers and strings

Performance

Sequences (Tuples/Lists)

Objects

Modules

Design and History FAQ

Why does Python use indentation for grouping of statements?

Why am I getting strange results with simple arithmetic operations?

Why are floating-point calculations so inaccurate?

Why are Python strings immutable?

Why must ‘self’ be used explicitly in method definitions and calls?

Why can’t I use an assignment in an expression?

Why does Python use methods for some functionality (e.g. list.index()) but functions for other (e.g. len(list))?

Why is join() a string method instead of a list or tuple method?

How fast are exceptions?

Why isn’t there a switch or case statement in Python?

Can’t you emulate threads in the interpreter instead of relying on an OS-specific thread implementation?

Why can’t lambda expressions contain statements?

Can Python be compiled to machine code, C or some other language?

How does Python manage memory?

Why doesn’t CPython use a more traditional garbage collection scheme?

Why isn’t all memory freed when CPython exits?

Why are there separate tuple and list data types?

How are lists implemented in CPython?

How are dictionaries implemented in CPython?

Why must dictionary keys be immutable?

Why doesn’t list.sort() return the sorted list?

How do you specify and enforce an interface spec in Python?

Why is there no goto?

Why can’t raw strings (r-strings) end with a backslash?

Why doesn’t Python have a “with” statement for attribute assignments?

Why are colons required for the if/while/def/class statements?

Why does Python allow commas at the end of lists and tuples?

Library and Extension FAQ

General Library Questions

Common tasks

Threads

Input and Output

Network/Internet Programming

Databases

Mathematics and Numerics

확장/내장 FAQ

C로 나만의 함수를 만들 수 있습니까?

C++로 나만의 함수를 만들 수 있습니까?

C를 쓰는 것은 어렵습니다; 대안이 있습니까?

C에서 임의의 파이썬 문장을 어떻게 실행할 수 있습니까?

C에서 임의의 파이썬 표현식을 어떻게 평가할 수 있습니까?

파이썬 객체에서 C값을 어떻게 추출합니까?

Py_BuildValue()를 사용하여 임의 길이의 튜플을 만드는 방법은 무엇입니까?

C에서 객체의 메서드를 어떻게 호출합니까?

PyErr_Print()의 출력(또는 stdout/stderr로 인쇄되는 모든 것)을 어떻게 잡습니까?

C에서 파이썬으로 작성된 모듈에 어떻게 액세스합니까?

파이썬에서 C++ 객체에 어떻게 인터페이스 합니까?

Setup 파일을 사용하여 모듈을 추가했는데 make가 실패합니다; 왜 그렇습니까?

확장을 어떻게 디버깅합니까?

리눅스 시스템에서 파이썬 모듈을 컴파일하고 싶지만, 일부 파일이 없습니다. 왜 그렇습니까?

“잘못된 입력”과 “불완전한 입력”을 어떻게 구별할 수 있습니까?

정의되지 않은 g++ 기호 __builtin_new나 __pure_virtual을 어떻게 찾을 수 있습니까?

일부 메서드는 C로 구현되고 그 밖의 것은 파이썬으로 구현된 (예를 들어 상속을 통해) 객체 클래스를 만들 수 있습니까?

Python on Windows FAQ

How do I run a Python program under Windows?

How do I make Python scripts executable?

Why does Python sometimes take so long to start?

How do I make an executable from a Python script?

Is a *.pyd file the same as a DLL?

How can I embed Python into a Windows application?

How do I keep editors from inserting tabs into my Python source?

How do I check for a keypress without blocking?

그래픽 사용자 인터페이스 FAQ

일반적인 GUI 질문

파이썬에 어떤 플랫폼 독립적인 GUI 툴킷이 있습니까?

파이썬에 어떤 플랫폼 특정 GUI 툴킷이 있습니까?

Tkinter 질문

“왜 내 컴퓨터에 파이썬이 설치되어 있습니까?” FAQ

파이썬이 무엇입니까?

내 컴퓨터에 파이썬이 설치된 이유는 무엇입니까?

파이썬을 삭제할 수 있습니까?

용어집

이 설명서에 관하여

파이썬 설명서의 공헌자들

버그 다루기

설명서 버그

파이썬 문제 추적기 사용하기

파이썬에 직접 이바지하기 입문

저작권

역사와 라이센스

소프트웨어의 역사

파이썬에 액세스하거나 사용하기 위한 이용 약관

PSF LICENSE AGREEMENT FOR PYTHON 3.7.17

BEOPEN.COM LICENSE AGREEMENT FOR PYTHON 2.0

CNRI LICENSE AGREEMENT FOR PYTHON 1.6.1

CWI LICENSE AGREEMENT FOR PYTHON 0.9.0 THROUGH 1.2

포함된 소프트웨어에 대한 라이센스 및 승인

메르센 트위스터

소켓

비동기 소켓 서비스

쿠키 관리

실행 추적

UUencode 및 UUdecode 함수

XML 원격 프로시저 호출

test_epoll

Select kqueue

SipHash24

strtod 와 dtoa

OpenSSL

expat

libffi

zlib

cfuhash

libmpdec

탐색

색인

모듈 |

다음 |

Python »

3.7.17 Documentation »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

|

파이썬의 새로운 기능

“파이썬의 새로운 기능” 수필 시리즈는 주요 파이썬 버전 간의 가장 중요한 변화를 둘러 봅니다. 새로운 릴리스 이후에 최신 상태를 유지하고자 하는 사람들에게는 “꼭 읽어야 할” 문서입니다.

파이썬 3.7의 새로운 기능

요약 – 배포 주요 사항

새로운 기능

기타 언어 변경

새 모듈

개선된 모듈

C API 변경

빌드 변경

최적화

기타 CPython 구현 변경

폐지된 파이썬 동작

폐지된 파이썬 모듈, 함수 및 메서드

폐지된 C API의 함수 및 형

플랫폼 지원 제거

API 및 기능 제거

모듈 제거

윈도우 전용 변경

파이썬 3.7로 이식하기

파이썬 3.7.1의 주목할만한 변경 사항

파이썬 3.7.2의 주목할만한 변경 사항

Notable changes in Python 3.7.6

Notable changes in Python 3.7.10

Notable changes in Python 3.7.11

Notable security feature in 3.7.14

What’s New In Python 3.6

Summary – Release highlights

New Features

Other Language Changes

New Modules

Improved Modules

Optimizations

Build and C API Changes

Other Improvements

Deprecated

Removed

Porting to Python 3.6

Notable changes in Python 3.6.2

Notable changes in Python 3.6.4

Notable changes in Python 3.6.5

Notable changes in Python 3.6.7

Notable changes in Python 3.6.10

Notable changes in Python 3.6.13

What’s New In Python 3.5

Summary – Release highlights

New Features

Other Language Changes

New Modules

Improved Modules

Other module-level changes

Optimizations

Build and C API Changes

Deprecated

Removed

Porting to Python 3.5

Notable changes in Python 3.5.4

What’s New In Python 3.4

Summary – Release Highlights

New Features

New Modules

Improved Modules

CPython Implementation Changes

Deprecated

Removed

Porting to Python 3.4

Changed in 3.4.3

What’s New In Python 3.3

Summary – Release highlights

PEP 405: Virtual Environments

PEP 420: Implicit Namespace Packages

PEP 3118: New memoryview implementation and buffer protocol documentation

PEP 393: Flexible String Representation

PEP 397: Python Launcher for Windows

PEP 3151: Reworking the OS and IO exception hierarchy

PEP 380: Syntax for Delegating to a Subgenerator

PEP 409: Suppressing exception context

PEP 414: Explicit Unicode literals

PEP 3155: Qualified name for classes and functions

PEP 412: Key-Sharing Dictionary

PEP 362: Function Signature Object

PEP 421: Adding sys.implementation

Using importlib as the Implementation of Import

Other Language Changes

A Finer-Grained Import Lock

Builtin functions and types

New Modules

Improved Modules

Optimizations

Build and C API Changes

Deprecated

Porting to Python 3.3

What’s New In Python 3.2

PEP 384: Defining a Stable ABI

PEP 389: Argparse Command Line Parsing Module

PEP 391: Dictionary Based Configuration for Logging

PEP 3148: The concurrent.futures module

PEP 3147: PYC Repository Directories

PEP 3149: ABI Version Tagged .so Files

PEP 3333: Python Web Server Gateway Interface v1.0.1

Other Language Changes

New, Improved, and Deprecated Modules

Multi-threading

Optimizations

Unicode

Codecs

Documentation

IDLE

Code Repository

Build and C API Changes

Porting to Python 3.2

What’s New In Python 3.1

PEP 372: Ordered Dictionaries

PEP 378: Format Specifier for Thousands Separator

Other Language Changes

New, Improved, and Deprecated Modules

Optimizations

IDLE

Build and C API Changes

Porting to Python 3.1

What’s New In Python 3.0

Common Stumbling Blocks

Overview Of Syntax Changes

Changes Already Present In Python 2.6

Library Changes

PEP 3101: A New Approach To String Formatting

Changes To Exceptions

Miscellaneous Other Changes

Build and C API Changes

Performance

Porting To Python 3.0

What’s New in Python 2.7

The Future for Python 2.x

Changes to the Handling of Deprecation Warnings

Python 3.1 Features

PEP 372: Adding an Ordered Dictionary to collections

PEP 378: Format Specifier for Thousands Separator

PEP 389: The argparse Module for Parsing Command Lines

PEP 391: Dictionary-Based Configuration For Logging

PEP 3106: Dictionary Views

PEP 3137: The memoryview Object

Other Language Changes

New and Improved Modules

Build and C API Changes

Other Changes and Fixes

Porting to Python 2.7

New Features Added to Python 2.7 Maintenance Releases

Acknowledgements

What’s New in Python 2.6

Python 3.0

Changes to the Development Process

PEP 343: The ‘with’ statement

PEP 366: Explicit Relative Imports From a Main Module

PEP 370: Per-user site-packages Directory

PEP 371: The multiprocessing Package

PEP 3101: Advanced String Formatting

PEP 3105: print As a Function

PEP 3110: Exception-Handling Changes

PEP 3112: Byte Literals

PEP 3116: New I/O Library

PEP 3118: Revised Buffer Protocol

PEP 3119: Abstract Base Classes

PEP 3127: Integer Literal Support and Syntax

PEP 3129: Class Decorators

PEP 3141: A Type Hierarchy for Numbers

Other Language Changes

New and Improved Modules

Deprecations and Removals

Build and C API Changes

Porting to Python 2.6

Acknowledgements

What’s New in Python 2.5

PEP 308: Conditional Expressions

PEP 309: Partial Function Application

PEP 314: Metadata for Python Software Packages v1.1

PEP 328: Absolute and Relative Imports

PEP 338: Executing Modules as Scripts

PEP 341: Unified try/except/finally

PEP 342: New Generator Features

PEP 343: The ‘with’ statement

PEP 352: Exceptions as New-Style Classes

PEP 353: Using ssize_t as the index type

PEP 357: The ‘__index__’ method

Other Language Changes

New, Improved, and Removed Modules

Build and C API Changes

Porting to Python 2.5

Acknowledgements

What’s New in Python 2.4

PEP 218: Built-In Set Objects

PEP 237: Unifying Long Integers and Integers

PEP 289: Generator Expressions

PEP 292: Simpler String Substitutions

PEP 318: Decorators for Functions and Methods

PEP 322: Reverse Iteration

PEP 324: New subprocess Module

PEP 327: Decimal Data Type

PEP 328: Multi-line Imports

PEP 331: Locale-Independent Float/String Conversions

Other Language Changes

New, Improved, and Deprecated Modules

Build and C API Changes

Porting to Python 2.4

Acknowledgements

What’s New in Python 2.3

PEP 218: A Standard Set Datatype

PEP 255: Simple Generators

PEP 263: Source Code Encodings

PEP 273: Importing Modules from ZIP Archives

PEP 277: Unicode file name support for Windows NT

PEP 278: Universal Newline Support

PEP 279: enumerate()

PEP 282: The logging Package

PEP 285: A Boolean Type

PEP 293: Codec Error Handling Callbacks

PEP 301: Package Index and Metadata for Distutils

PEP 302: New Import Hooks

PEP 305: Comma-separated Files

PEP 307: Pickle Enhancements

Extended Slices

Other Language Changes

New, Improved, and Deprecated Modules

Pymalloc: A Specialized Object Allocator

Build and C API Changes

Other Changes and Fixes

Porting to Python 2.3

Acknowledgements

What’s New in Python 2.2

Introduction

PEPs 252 and 253: Type and Class Changes

PEP 234: Iterators

PEP 255: Simple Generators

PEP 237: Unifying Long Integers and Integers

PEP 238: Changing the Division Operator

Unicode Changes

PEP 227: Nested Scopes

New and Improved Modules

Interpreter Changes and Fixes

Other Changes and Fixes

Acknowledgements

What’s New in Python 2.1

Introduction

PEP 227: Nested Scopes

PEP 236: __future__ Directives

PEP 207: Rich Comparisons

PEP 230: Warning Framework

PEP 229: New Build System

PEP 205: Weak References

PEP 232: Function Attributes

PEP 235: Importing Modules on Case-Insensitive Platforms

PEP 217: Interactive Display Hook

PEP 208: New Coercion Model

PEP 241: Metadata in Python Packages

New and Improved Modules

Other Changes and Fixes

Acknowledgements

What’s New in Python 2.0

Introduction

What About Python 1.6?

New Development Process

Unicode

List Comprehensions

Augmented Assignment

String Methods

Garbage Collection of Cycles

Other Core Changes

Porting to 2.0

Extending/Embedding Changes

Distutils: Making Modules Easy to Install

XML Modules

Module changes

New modules

IDLE Improvements

Deleted and Deprecated Modules

Acknowledgements

“Changelog” 는 Misc/NEWS.d [https://github.com/python/cpython/tree/3.7/Misc/NEWS.d] 디렉터리 트리의 내용으로부터 만들어진 파일 [https://pypi.org/project/blurb]의 HTML 버전입니다. 현재 버전의 파이썬에 적용된 모든 사소하지 않은 변경들을 담고 있습니다

Changelog

Python 3.7.17 final

Python 3.7.16 final

Python 3.7.15 final

Python 3.7.14 final

Python 3.7.13 final

Python 3.7.12 final

Python 3.7.11 final

Python 3.7.10 final

Python 3.7.9 final

Python 3.7.8 final

Python 3.7.8 release candidate 1

Python 3.7.7 final

Python 3.7.7 release candidate 1

Python 3.7.6 final

Python 3.7.6 release candidate 1

Python 3.7.5 final

Python 3.7.5 release candidate 1

Python 3.7.4 final

Python 3.7.4 release candidate 2

Python 3.7.4 release candidate 1

Python 3.7.3 final

Python 3.7.3 release candidate 1

Python 3.7.2 final

Python 3.7.2 release candidate 1

Python 3.7.1 final

Python 3.7.1 release candidate 2

Python 3.7.1 release candidate 1

Python 3.7.0 final

Python 3.7.0 release candidate 1

Python 3.7.0 beta 5

Python 3.7.0 beta 4

Python 3.7.0 beta 3

Python 3.7.0 beta 2

Python 3.7.0 beta 1

Python 3.7.0 alpha 4

Python 3.7.0 alpha 3

Python 3.7.0 alpha 2

Python 3.7.0 alpha 1

Python 3.6.6 final

Python 3.6.6 release candidate 1

Python 3.6.5 final

Python 3.6.5 release candidate 1

Python 3.6.4 final

Python 3.6.4 release candidate 1

Python 3.6.3 final

Python 3.6.3 release candidate 1

Python 3.6.2 final

Python 3.6.2 release candidate 2

Python 3.6.2 release candidate 1

Python 3.6.1 final

Python 3.6.1 release candidate 1

Python 3.6.0 final

Python 3.6.0 release candidate 2

Python 3.6.0 release candidate 1

Python 3.6.0 beta 4

Python 3.6.0 beta 3

Python 3.6.0 beta 2

Python 3.6.0 beta 1

Python 3.6.0 alpha 4

Python 3.6.0 alpha 3

Python 3.6.0 alpha 2

Python 3.6.0 alpha 1

Python 3.5.5 final

Python 3.5.5 release candidate 1

Python 3.5.4 final

Python 3.5.4 release candidate 1

Python 3.5.3 final

Python 3.5.3 release candidate 1

Python 3.5.2 final

Python 3.5.2 release candidate 1

Python 3.5.1 final

Python 3.5.1 release candidate 1

Python 3.5.0 final

Python 3.5.0 release candidate 4

Python 3.5.0 release candidate 3

Python 3.5.0 release candidate 2

Python 3.5.0 release candidate 1

Python 3.5.0 beta 4

Python 3.5.0 beta 3

Python 3.5.0 beta 2

Python 3.5.0 beta 1

Python 3.5.0 alpha 4

Python 3.5.0 alpha 3

Python 3.5.0 alpha 2

Python 3.5.0 alpha 1

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬의 새로운 기능 »

|

파이썬 3.7의 새로운 기능

편집자

Elvis Pranskevichus <elvis@magic.io>

이 기사에서는 파이썬 3.6과 비교하여 3.7의 새로운 기능에 관해 설명합니다. 파이썬 3.7은 2018년 6월 27일에 배포되었습니다. 자세한 내용은 changelog 를 참조하세요.

요약 – 배포 주요 사항

새로운 문법 기능:

PEP 563, 형 어노테이션의 지연된 평가.

이전 버전과 호환되지 않는 문법 변경:

async와 await 는 이제 예약 키워드입니다.

새 라이브러리 모듈:

contextvars: PEP 567 – 컨텍스트 변수

dataclasses: PEP 557 – 데이터 클래스

importlib.resources

새로운 내장 기능:

PEP 553, 새로운 breakpoint() 함수.

파이썬 데이터 모델 개선:

PEP 562, 모듈 어트리뷰트에 대한 액세스의 사용자 정의.

PEP 560, typing 모듈과 제네릭 형에 대한 코어 지원.

dict 객체의 삽입 순서 보존 특성을 파이썬 언어 규격의 공식적인 일부로 선언했습니다 [https://mail.python.org/pipermail/python-dev/2017-December/151283.html].

표준 라이브러리의 현저한 개선:

asyncio 모듈에 새 기능과 현저한 사용성 및 성능 개선 이 추가되었습니다.

time 모듈은 나노초 해상도의 함수 지원을 얻었습니다.

CPython 구현 개선:

ASCII를 기본 텍스트 인코딩으로 사용하지 않기:

PEP 538, 레거시 C 로케일 강제 변경

PEP 540, 강제 UTF-8 실행시간 모드

PEP 552, 결정적 .pycs

새로운 개발 실행시간 모드

PEP 565, 개선된 DeprecationWarning 처리

C API 개선 사항:

PEP 539, 스레드-로컬 저장소를 위한 새로운 C API

설명서 개선 사항:

PEP 545, 파이썬 설명서 번역

새로운 설명서 번역: 일본어 [https://docs.python.org/ja/], 프랑스어 [https://docs.python.org/fr/], 한국어 [https://docs.python.org/ko/].

이 배포는 많은 영역에서 주목할만한 성능 향상을 제공합니다. 최적화 섹션에 자세히 나와 있습니다.

이전 파이썬 배포와의 호환성에 영향을 줄 수 있는 변경 사항 목록은 파이썬 3.7로 이식하기 섹션을 참조하십시오.

새로운 기능

PEP 563 : 어노테이션의 지연된 평가

파이썬에서 형 힌트의 출현은 PEP 3107 [https://www.python.org/dev/peps/pep-3107]에서 추가되고 PEP 526 [https://www.python.org/dev/peps/pep-0526]에서 더욱 다듬어진 어노테이션의 두 가지 사용성 문제를 드러냈습니다:

어노테이션은 현재 스코프에서 이미 사용 가능한 이름 만 사용할 수 있습니다. 즉, 어떤 종류의 전방 참조도 지원하지 않았습니다; 그리고

소스 코드에 어노테이션을 붙이는 것은 파이썬 프로그램의 시작 시간에 악영향을 미쳤습니다.

이 두 가지 문제는 어노테이션 평가를 지연시키는 것으로 해결됩니다. 정의 시간에 어노테이션의 표현식을 실행하는 코드를 컴파일하는 대신, 컴파일러는 해당 표현식의 AST와 동등한 문자열 형식으로 어노테이션을 저장합니다. 필요하다면, 실행시간에 typing.get_type_hints() 를 사용하여 어노테이션을 해석 할 수 있습니다. 이것이 필수적이지 않은 일반적인 경우에는, 어노테이션을 싸게 저장할 수 있고 (짧은 문자열은 인터프리터에 의해 한 번만 만들어지기 때문입니다), 시작 시간을 더 빠르게 할 수 있습니다.

사용성 측면에서, 이제 어노테이션이 전방 참조를 지원하므로 다음 문법이 유효합니다:

class C:
    @classmethod
    def from_string(cls, source: str) -> C:
        ...

    def validate_b(self, obj: B) -> bool:
        ...

class B:
    ...

이 변경으로 인해 호환성이 깨지기 때문에, 파이썬 3.7에서 새 동작은 __future__ 임포트를 사용하여 모듈별로 새로운 동작을 활성화해야 합니다:

from __future__ import annotations

It will become the default in Python 3.10.

더 보기

PEP 563 [https://www.python.org/dev/peps/pep-0563] – 어노테이션의 지연된 평가

Łukasz Langa가 작성하고 구현한 PEP.

PEP 538: 레거시 C 로케일 강제 변경

파이썬 3시리즈에서 진행 중인 과제는, 윈도우 이외의 플랫폼에서 기본 C 또는 POSIX 로케일 사용으로 인해 묵시적으로 가정되는 “7-비트 ASCII” 텍스트 인코딩을 처리하기 위한 적절한 기본 전략을 결정하는 것입니다.

새 PYTHONCOERCECLOCALE 환경 변수의 설명서에 설명되어있듯이, PEP 538 [https://www.python.org/dev/peps/pep-0538] 은 기본 인터프리터 명령행 인터페이스를 갱신하여, 사용 가능한 UTF-8 기반 로케일로 자동으로 강제 변경합니다. 이런 식으로 LC_CTYPE 을 자동 설정하는 것은, 핵심 인터프리터와 로케일을 인식하는 C 확장 (가령 readline) 모두 기본 텍스트 인코딩으로 ASCII 대신 UTF-8을 가정하게 된다는 뜻입니다.

PEP 11 [https://www.python.org/dev/peps/pep-0011] 의 플랫폼 지원 정의 역시 전체 텍스트 처리 지원을 적절히 구성된 비 ASCII 기반 로케일로 제한하도록 갱신되었습니다.

이 변경의 일부로, 이제 정의된 강제 변경 대상 로케일(현재 C.UTF-8, C.utf8, UTF-8)을 사용할 때, stdin 과 stdout 의 기본 에러 처리기는 (strict 대신) surrogateescape 입니다. stderr 의 기본 에러 처리기는 로케일에 관계없이 계속 backslashreplace 입니다.

로케일 강제 변경은 기본적으로 조용히 일어나지만, 로케일 관련 통합 문제를 디버깅하는 데 도움을 주기 위해 PYTHONCOERCECLOCALE=warn 를 설정해서 (stderr 로 직접 출력되는) 명시적 경고를 요청할 수 있습니다. 또한, 이 설정은 핵심 인터프리터가 초기화될 때 레거시 C 로케일이 활성 상태로 남아 있으면 파이썬 런타임이 경고를 하도록 만듭니다.

PEP 538 [https://www.python.org/dev/peps/pep-0538] 의 로케일 강제 변환이 (비 파이썬 응용 프로그램과 이전 버전의 파이썬을 실행하는 경우를 포함하는) 자식 프로세스뿐만 아니라 (GNU readline 같은) 확장 모듈에도 영향을 주는 장점이 있지만, 실행 중인 시스템에 적절한 대상 로케일이 있어야 한다는 단점이 있습니다. 적절한 대상 로케일을 사용할 수 없는 경우(예를 들어, RHEL/CentOS 7에서 발생하듯이)를 더 잘 처리하기 위해, 파이썬 3.7은 PEP 540: 강제 UTF-8 실행시간 모드 또한 구현합니다.

더 보기

PEP 538 [https://www.python.org/dev/peps/pep-0538] – 레거시 C 로케일을 UTF-8 기반 로케일로 강제 변경

Nick Coghlan 이 작성하고 구현한 PEP.

PEP 540: 강제 UTF-8 실행시간 모드

새로운 -X utf8 명령행 옵션과 PYTHONUTF8 환경 변수를 사용하여 CPython UTF-8 모드 를 활성화할 수 있습니다.

UTF-8 모드에서, CPython은 로케일 설정을 무시하고 기본적으로 UTF-8 인코딩을 사용합니다. sys.stdin 과 sys.stdout 스트림의 에러 처리기는 surrogateescape 로 설정됩니다.

강제 UTF-8 모드는 임베디드 응용 프로그램의 로케일 설정을 변경하지 않고 임베디드 파이썬 인터프리터의 텍스트 처리 동작을 변경하는 데 사용할 수 있습니다.

PEP 540 [https://www.python.org/dev/peps/pep-0540] 의 UTF-8 모드는 실행 중인 시스템에서 사용할 수 있는 로케일에 관계없이 작동하는 이점이 있지만, (GNU readline 과 같은) 확장 모듈, 비 파이썬 응용 프로그램을 실행하는 자식 프로세스, 이전 버전의 파이썬을 실행하는 자식 프로세스에 영향을 주지 못하는 단점이 있습니다. 이러한 구성 요소와 통신 할 때 텍스트 데이터가 손상될 위험을 줄이기 위해 파이썬 3.7은 PEP 540: 강제 UTF-8 실행시간 모드 또한 구현합니다.

UTF-8 모드는 로케일이 C 또는 POSIX 이고, PEP 538 [https://www.python.org/dev/peps/pep-0538] 로케일 강제 변환이 UTF-8 기반 대안으로의 변경에 실패할 때 (그 실패가 PYTHONCOERCECLOCALE=0 설정 때문이든, LC_ALL 설정 때문이든, 적절한 대상 로케일이 없기 때문이든 무관하게) 기본적으로 활성화됩니다.

더 보기

PEP 540 [https://www.python.org/dev/peps/pep-0540] – 새로운 UTF-8 모드 추가

Victor Stinner가 작성하고 구현한 PEP

PEP 553: 내장 breakpoint()

파이썬 3.7에는 파이썬 디버거에 진입하는 쉽고 일관된 방식을 제공하는 새로운 내장 breakpoint() 함수가 포함되어 있습니다.

내장 breakpoint() 는 sys.breakpointhook() 을 호출합니다. 기본적으로, 후자는 pdb를 임포트 한 다음 pdb.set_trace() 를 호출합니다. 하지만, sys.breakpointhook() 을 여러분이 선택한 함수에 연결하면, breakpoint() 는 임의의 디버거에 진입할 수 있습니다. 또한, 환경 변수 PYTHONBREAKPOINT 를 여러분이 선택한 디버거의 콜러블로 설정할 수 있습니다. 내장 breakpoint()` 를 완전히 비활성화하려면 PYTHONBREAKPOINT=0 를 설정하십시오.

더 보기

PEP 553 [https://www.python.org/dev/peps/pep-0553] – 내장 breakpoint()

Barry Warsaw가 작성하고 구현한 PEP

PEP 539: 스레드-로컬 저장소를 위한 새로운 C API

파이썬은 스레드 로컬 저장소 지원을 위한 C API를 제공하지만; 기존 스레드 로컬 저장소 (TLS) API 는 모든 플랫폼에서 TLS 키로 int를 사용합니다. 이것은 공식적으로 지원되는 플랫폼에서는 일반적으로 문제가 되지 않지만, POSIX를 준수하지도 실용적인 의미에서 이식성이 있지도 않습니다.

PEP 539 [https://www.python.org/dev/peps/pep-0539] 는 CPython에 새로운 스레드 특정 저장소 (TSS) API 를 제공해서 이를 변경하는데, CPython 인터프리터 내에서 기존 TLS API의 사용을 대체하는 동시에 기존 API를 폐지합니다. TSS API는 TSS 키를 나타내는데 int 대신 Py_tss_t라는 새로운 형을 사용합니다. 이 형은 하부 TLS 구현에 따라 달라질 수 있는 불투명 한 형입니다. 그래서 네이티브 TLS 키가 int로 안전하게 캐스팅될 수 없는 방식으로 정의된 플랫폼에서 CPython을 빌드 할 수 있게 합니다.

네이티브 TLS 키가 int로 안전하게 캐스팅될 수 없는 방식으로 정의된 플랫폼에서는, 기존 TLS API의 모든 함수는 작동하지 않고 즉시 실패를 반환합니다. 이는 이전 API가 신뢰성 있게 사용될 수 없는 플랫폼에서 지원되지 않으며, 이러한 지원을 추가하기 위한 노력이 없을 것을 분명하게 나타냅니다.

더 보기

PEP 539 [https://www.python.org/dev/peps/pep-0539] – CPython의 스레드-로컬 저장소를 위한 새로운 C-API

Erik M. Bray가 작성하고 Masayuki Yamamoto가 구현한 PEP.

PEP 562: 모듈 어트리뷰트에 대한 액세스 사용자 정의

파이썬 3.7은 모듈에, 발견되지 않는 어트리뷰트마다 호출되는 __getattr__() 을 정의할 수 있도록 합니다. 이제 모듈에 __dir__() 도 정의할 수 있게 되었습니다.

이것이 유용한 전형적인 예는 모듈 어트리뷰트 폐지와 지연 로딩입니다.

더 보기

PEP 562 [https://www.python.org/dev/peps/pep-0562] – 모듈 __getattr__ 과 __dir__

Ivan Levkivskyi가 작성하고 구현한 PEP

PEP 564: 나노초 해상도의 새로운 시간 함수

현대 시스템의 시계 해상도는 time.time() 함수와 그 변형이 반환하는 부동 소수점 숫자의 제한된 정밀도를 초과 할 수 있습니다. PEP 564 [https://www.python.org/dev/peps/pep-0564] 는 기존 타이머 함수의 새로운 “나노 초” 변형을 time 모듈에 추가합니다:

time.clock_gettime_ns()

time.clock_settime_ns()

time.monotonic_ns()

time.perf_counter_ns()

time.process_time_ns()

time.time_ns()

새로운 함수는 나노초의 수를 정숫값으로 반환합니다.

<https://www.python.org/dev/peps/pep-0564/#annex-clocks-resolution-in-python>`_ 의 측정에 의하면 리눅스와 윈도우에서 time.time_ns() 의 해상도는 time.time() 보다 약 3배 정밀합니다.

더 보기

PEP 564 [https://www.python.org/dev/peps/pep-0564] – 나노초 해상도의 새로운 시간 함수 추가

Victor Stinner가 작성하고 구현한 PEP

PEP 565: __main__ 의 DeprecationWarning 표시

DeprecationWarning 의 기본 처리 방식이 변경되어, 이러한 경고가 다시 한번 기본적으로 표시됩니다. 하지만, 이를 발생시킨 코드가 __main__ 모듈에서 직접 실행될 때만 표시됩니다. 결과적으로, 단일 파일 스크립트 개발자와 파이썬을 대화식으로 사용하는 개발자는 사용하는 API에 대한 폐지 경고를 다시 보게 되지만, 임포트되는 응용 프로그램, 라이브러리, 프레임웍 모듈에서 발생하는 폐지 경고는 계속 기본적으로 숨겨집니다.

이 변경으로 인해, 이제 표준 라이브러리는 개발자가 세 가지 다른 폐지 경고 동작 중 하나를 선택할 수 있도록 합니다:

FutureWarning: 기본적으로 항상 표시됩니다. 응용 프로그램 최종 사용자를 대상으로 하는 경고로 권장됩니다 (예, 폐지된 응용 프로그램 구성 설정).

DeprecationWarning: 기본적으로 __main__ 과 테스트 실행 시에 표시됩니다. 버전 업그레이드가 동작 변경이나 에러를 일으킬 수 있어서, 다른 파이썬 개발자를 대상으로 하는 경고로 권장됩니다.

PendingDeprecationWarning: 기본적으로 테스트 실행 시에만 표시됩니다. 향후 버전 업그레이드가 경고 범주를 DeprecationWarning 이나 FutureWarning으로 변경하게 될 경우를 위한 것입니다.

이전에는 DeprecationWarning 과 PendingDeprecationWarning 둘 다 테스트를 실행할 때만 볼 수 있었습니다. 주로 단일 파일 스크립트를 작성하거나 대화식으로 파이썬을 사용하는 개발자는 사용된 API가 호환되지 않는 방식으로 변경된 것을 보고 놀랄 수 있었습니다.

더 보기

PEP 565 [https://www.python.org/dev/peps/pep-0565] – __main__ 의 DeprecationWarning 표시

Nick Coghlan이 작성하고 구현한 PEP

PEP 560: typing 모듈과 제네릭 형에 대한 코어 지원

처음에는 PEP 484 [https://www.python.org/dev/peps/pep-0484] 가 핵심 CPython 인터프리터의 어떤 변경도 도입하지 않도록 설계되었습니다. 이제 형 힌트와 typing 모듈이 커뮤니티에서 광범위하게 사용되므로, 이 제한이 제거됩니다. PEP는 두 개의 특수 메서드 __class_getitem__() 과 __mro_entries__ 를 소개합니다. 이 메서드는 이제 typing 에 있는 대부분 클래스와 특수 구조물에서 사용됩니다. 그 결과로, 형과 관련된 여러 연산의 속도가 최대 7배까지 증가했고, 제네릭 형은 메타 클래스 충돌 없이 사용할 수 있으며, typing 모듈의 몇 가지 오랜 버그가 해결되었습니다.

더 보기

PEP 560 [https://www.python.org/dev/peps/pep-0560] – typing 모듈과 제네릭 형에 대한 코어 지원

Ivan Levkivskyi가 작성하고 구현한 PEP

PEP 552: 해시 기반 .pyc 파일

파이썬은 전통적으로 바이트 코드 캐시 파일(즉, .pyc 파일)의 최신성을 검사하기 위해, 소스 메타 데이터(최종 수정 타임스탬프와 크기)를 캐시 파일이 만들어질 때 헤더에 저장된 소스 메타 데이터와 비교했습니다. 효과적이지만, 이 무효화 방법에는 단점이 있습니다. 파일 시스템 타임스탬프가 너무 거친 경우, 파이썬은 소스 변경을 놓칠 수 있어 사용자 혼란을 낳을 수 있습니다. 또한, 캐시 파일에 타임스탬프를 갖는 것은 빌드 재현성 [https://reproducible-builds.org/] 과 콘텐츠 기반 빌드 시스템에서 문제가 됩니다.

PEP 552 [https://www.python.org/dev/peps/pep-0552] 는 소스 타임스탬프 대신 소스 파일의 해시가 소스 타임스탬프 대신 무효화에 사용될 수 있도록 pyc 형식을 확장합니다. 이러한 .pyc 파일을 “해시 기반”이라고 합니다. 기본적으로, 파이썬은 여전히 타임스탬프 기반 무효화를 사용하며 실행 시간에 해시 기반 .pyc 파일을 생성하지 않습니다. 해시 기반 .pyc 파일은 py_compile 또는 compileall로 만들 수 있습니다.

해시 기반 .pyc 파일에는 두 가지 변형이 있습니다: 검사형(checked)과 비검사형(unchecked). 파이썬은 검사형 해시 기반 .pyc 파일을 실행시간에 해당 소스 파일에 대해 유효성을 검사하지만, 비검사형 해시 기반 pyc에 대해서는 확인하지 않습니다. 비검사형 해시 기반 .pyc 파일은 파이썬 외부의 시스템(가령 빌드 시스템)이 .pyc 파일을 최신 상태로 유지하는 책임을 지는 환경에서 유용한 성능 최적화입니다.

자세한 정보는 캐시된 바이트 코드 무효화 를 보십시오.

더 보기

PEP 552 [https://www.python.org/dev/peps/pep-0552] – 결정적 pycs

Benjamin Peterson이 작성하고 구현한 PEP

PEP 545: 파이썬 설명서 번역

PEP 545 [https://www.python.org/dev/peps/pep-0545] 는 파이썬 설명서 번역을 만들고 유지하는 과정을 설명합니다.

세 가지 새로운 번역이 추가되었습니다:

일본어: https://docs.python.org/ja/

프랑스어: https://docs.python.org/fr/

한국어: https://docs.python.org/ko/

더 보기

PEP 545 [https://www.python.org/dev/peps/pep-0545] – 파이썬 설명서 번역

Julien Palard, Inada Naoki 및 Victor Stinner가 작성하고 구현한 PEP.

개발 실행시간 모드: -X dev

새 -X dev 명령행 옵션이나 새 PYTHONDEVMODE 환경 변수를 사용하여 CPython의 개발 모드 를 활성화할 수 있습니다. 개발 모드에 있을 때, CPython은 기본적으로 활성화되기에는 너무 비싼 추가적인 실행 시간 검사를 수행합니다. 이 모드의 효과에 대한 자세한 설명은 -X dev 설명서를 보십시오.

기타 언어 변경

An await expression and comprehensions containing an async for clause were illegal in the expressions in formatted string literals due to a problem with the implementation. In Python 3.7 this restriction was lifted.

이제 함수에 255개 이상의 인자를 전달할 수 있고, 함수는 255개 이상의 매개변수를 가질 수 있습니다. (Contributed by Serhiy Storchaka in bpo-12844 [https://bugs.python.org/issue?@action=redirect&bpo=12844] and bpo-18896 [https://bugs.python.org/issue?@action=redirect&bpo=18896].)

이제 bytes.fromhex() 와 bytearray.fromhex() 는 스페이스뿐만 아니라 모든 ASCII 공백을 무시합니다. (Contributed by Robert Xiao in bpo-28927 [https://bugs.python.org/issue?@action=redirect&bpo=28927].)

str, bytes, bytearray 는 새 isascii() 메서드에 대한 지원을 얻었습니다. 이 메서드를 사용하여 문자열이나 바이트열에 오직 ASCII 문자만 들어 있는지 검사할 수 있습니다. (Contributed by INADA Naoki in bpo-32677 [https://bugs.python.org/issue?@action=redirect&bpo=32677].)

이제 ImportError 는 from ... import ... 가 실패할 때 모듈 이름과 모듈 __file__ 경로를 출력합니다. (Contributed by Matthias Bussonnier in bpo-29546 [https://bugs.python.org/issue?@action=redirect&bpo=29546].)

이제 하위 모듈을 이름에 연결하는 절대 임포트가 수반되는 순환 임포트가 지원됩니다. (Contributed by Serhiy Storchaka in bpo-30024 [https://bugs.python.org/issue?@action=redirect&bpo=30024].)

이제 object.__format__(x, '') 는 format(str(self), '') 대신에 str(x) 과 동등합니다. (Contributed by Serhiy Storchaka in bpo-28974 [https://bugs.python.org/issue?@action=redirect&bpo=28974].)

이제 스택 트레이스의 동적 생성을 더욱 잘 지원하기 위해, 파이썬 코드에서 types.TracebackType 의 인스턴스를 만들 수 있고, 트레이스백 의 tb_next 어트리뷰트에 쓸 수 있습니다. (Contributed by Nathaniel J. Smith in bpo-30579 [https://bugs.python.org/issue?@action=redirect&bpo=30579].)

-m 스위치를 사용할 때, 이제 sys.path[0] 를 빈 디렉터리로 남겨두기보다는 전체 시작 디렉터리 경로로 확장됩니다 (빈 디렉터리를 남겨두면, 임포트가 일어날 때의 현재 작업 디렉터리로부터의 임포트가 가능해집니다) (Contributed by Nick Coghlan in bpo-33053 [https://bugs.python.org/issue?@action=redirect&bpo=33053].)

새 -X importtime 옵션 또는 PYTHONPROFILEIMPORTTIME 환경 변수는 각 모듈 임포트의 타이밍을 보여주기 위해 사용될 수 있습니다. (Contributed by Victor Stinner in bpo-31415 [https://bugs.python.org/issue?@action=redirect&bpo=31415].)

새 모듈

contextvars

새 contextvars 모듈과 새 C API 집합은 컨텍스트 변수 에 대한 지원을 도입합니다. 컨텍스트 변수는 개념적으로 스레드-로컬 변수와 유사합니다. TLS와 달리, 컨텍스트 변수는 비동기 코드를 올바르게 지원합니다.

asyncio와 decimal 모듈은 바로 사용할 수 있도록 컨텍스트 변수를 사용하고 지원하도록 업데이트되었습니다. 특히 활성 십진 컨텍스트는 이제 컨텍스트 변수에 저장되므로, 십진수 연산이 비동기 코드에서 올바른 컨텍스트에서 작동 할 수 있습니다.

더 보기

PEP 567 [https://www.python.org/dev/peps/pep-0567] – 컨텍스트 변수

Yury Selivanov가 작성하고 구현한 PEP

dataclasses

새 dataclass() 데코레이터는 데이터 클래스 를 선언하는 방법을 제공합니다. 데이터 클래스는 클래스 변수 어노테이션을 사용하여 어트리뷰트를 기술합니다. 생성자와 __repr__(), __eq__(), __hash__() 와 같은 다른 매직 메서드가 자동으로 생성됩니다.

예:

@dataclass
class Point:
    x: float
    y: float
    z: float = 0.0

p = Point(1.5, 2.5)
print(p)   # produces "Point(x=1.5, y=2.5, z=0.0)"

더 보기

PEP 557 [https://www.python.org/dev/peps/pep-0557] – 데이터 클래스

Eric V. Smith가 작성하고 구현한 PEP

importlib.resources

새 importlib.resources 모듈은 여러 개의 새로운 API와 하나의 새로운 ABC를 제공하여, 패키지 내부의 리소스 에 접근하고 읽는 것을 지원합니다. 리소스는 대략 패키지 안의 파일과 비슷하지만, 물리적인 파일 시스템에 있는 실제 파일 일 필요는 없습니다. 모듈 로더는 이 새로운 API를 지원하기 위해 importlib.abc.ResourceReader 인스턴스를 반환하는 get_resource_reader() 함수를 제공 할 수 있습니다. 내장 파일 경로 로더와 zip 파일 로더는 모두 이것을 지원합니다.

Contributed by Barry Warsaw and Brett Cannon in bpo-32248 [https://bugs.python.org/issue?@action=redirect&bpo=32248].

더 보기

importlib_resources [http://importlib-resources.readthedocs.io/en/latest/] – 이전 파이썬 버전을 위한 PyPI 백 포트.

개선된 모듈

argparse

새로운 ArgumentParser.parse_intermixed_args() 메서드는 옵션과 위치 인자의 혼합을 허용합니다. (Contributed by paul.j3 in bpo-14191 [https://bugs.python.org/issue?@action=redirect&bpo=14191].)

asyncio

asyncio 모듈은 많은 새로운 기능과 사용성 및 성능 개선이 추가되었습니다. 주목할만한 변경 사항은 다음과 같습니다:

새로운 잠정 asyncio.run() 함수는 자동으로 이벤트 루프를 생성하고 파괴함으로써 동기 코드에서 코루틴을 실행하는 데 사용될 수 있습니다. (Contributed by Yury Selivanov in bpo-32314 [https://bugs.python.org/issue?@action=redirect&bpo=32314].)

asyncio는 contextvars 에 대한 지원을 얻었습니다. loop.call_soon(), loop.call_soon_threadsafe(), loop.call_later(), loop.call_at() 및 Future.add_done_callback() 은 새로운 선택적 키워드-전용 context 매개 변수를 갖습니다. Tasks 는 이제 자신의 컨텍스트를 자동으로 추적합니다. 자세한 정보는 PEP 567 [https://www.python.org/dev/peps/pep-0567]을 보십시오. (Contributed by Yury Selivanov in bpo-32436 [https://bugs.python.org/issue?@action=redirect&bpo=32436].)

새로운 asyncio.create_task() 함수가 asyncio.get_event_loop().create_task() 의 손쉬운 방법으로 추가되었습니다. (Contributed by Andrew Svetlov in bpo-32311 [https://bugs.python.org/issue?@action=redirect&bpo=32311].)

새로운 loop.start_tls() 메서드를 사용하여 기존 연결을 TLS로 업그레이드할 수 있습니다. (Contributed by Yury Selivanov in bpo-23749 [https://bugs.python.org/issue?@action=redirect&bpo=23749].)

새로운 loop.sock_recv_into() 메서드는 데이터를 직접 소켓에서 제공된 버퍼로 읽어 들여 데이터 복사를 줄일 수 있게 합니다. (Contributed by Antoine Pitrou in bpo-31819 [https://bugs.python.org/issue?@action=redirect&bpo=31819].)

새로운 asyncio.current_task() 함수는 현재 실행 중인 Task 인스턴스를 반환하고, 새 asyncio.all_tasks() 함수는 주어진 루프에 있는 모든 기존 Task 인스턴스 집합을 반환합니다. Task.current_task() 와 Task.all_tasks() 메서드는 폐지되었습니다. (Contributed by Andrew Svetlov in bpo-32250 [https://bugs.python.org/issue?@action=redirect&bpo=32250].)

새로운 잠정적 BufferedProtocol 클래스는 수신 버퍼를 수동으로 제어하여 스트리밍 프로토콜을 구현할 수 있게 합니다. (Contributed by Yury Selivanov in bpo-32251 [https://bugs.python.org/issue?@action=redirect&bpo=32251].)

새로운 asyncio.get_running_loop() 함수는 현재 실행 중인 루프를 반환하고, 루프가 실행되고 있지 않으면 RuntimeError 를 발생시킵니다. 이는 아무것도 실행되고 있지 않으면 새로 만드는 asyncio.get_event_loop() 과는 대조적입니다. (Contributed by Yury Selivanov in bpo-32269 [https://bugs.python.org/issue?@action=redirect&bpo=32269].)

새로운 StreamWriter.wait_closed() 코루틴 메서드는 스트림 작성자가 닫힐 때까지 기다릴 수 있습니다. 새로운 StreamWriter.is_closing() 메서드를 사용하여 작성기가 닫히고 있는지 판별 할 수 있습니다. (Contributed by Andrew Svetlov in bpo-32391 [https://bugs.python.org/issue?@action=redirect&bpo=32391].)

새로운 loop.sock_sendfile() 코루틴 메서드는 가능한 경우 os.sendfile 을 사용하여 파일을 전송할 수 있도록 합니다. (Contributed by Andrew Svetlov in bpo-32410 [https://bugs.python.org/issue?@action=redirect&bpo=32410].)

새로운 Future.get_loop() 와 Task.get_loop() 메서드는 태스크 나 퓨처가 만들어진 루프의 인스턴스를 돌려줍니다. Server.get_loop() 는 asyncio.Server 객체에 대해서도 같은 일을 할 수 있도록 합니다. (Contributed by Yury Selivanov in bpo-32415 [https://bugs.python.org/issue?@action=redirect&bpo=32415] and Srinivas Reddy Thatiparthy in bpo-32418 [https://bugs.python.org/issue?@action=redirect&bpo=32418].)

이제 asyncio.Server 의 인스턴스가 어떻게 시작되는지 제어할 수 있습니다. 이전에는 서버를 만들 때 즉시 서버가 시작되었습니다. 새로운 start_serving 키워드 인자는 loop.create_server() 와 loop.create_unix_server() 뿐만 아니라 Server.start_serving() 와 Server.serve_forever() 에도 사용되어 서버 인스턴스를 만드는 것과 시작시키는 것을 분리할 수 있습니다. 새로운 Server.is_serving() 메서드는 서버가 실행 중이면 True 를 돌려줍니다. Server 객체는 이제 비동기 컨텍스트 관리자입니다:

srv = await loop.create_server(...)

async with srv:
    # some code

# At this point, srv is closed and no longer accepts new connections.

(Contributed by Yury Selivanov in bpo-32662 [https://bugs.python.org/issue?@action=redirect&bpo=32662].)

loop.call_later() 가 반환하는 콜백 객체는 예약된 절대 콜백 타임스탬프를 돌려주는 새 when() 메서드를 얻었습니다. (Contributed by Andrew Svetlov in bpo-32741 [https://bugs.python.org/issue?@action=redirect&bpo=32741].)

loop.create_datagram_endpoint() 메서드는 유닉스 소켓 지원을 얻었습니다. (Contributed by Quentin Dawans in bpo-31245 [https://bugs.python.org/issue?@action=redirect&bpo=31245].)

asyncio.open_connection(), asyncio.start_server() 함수, loop.create_connection(), loop.create_server(), loop.create_accepted_socket() 메서드와 해당 유닉스 소켓 변형은 이제 ssl_handshake_timeout 키워드 인자를 받아들입니다. (Contributed by Neil Aspinall in bpo-29970 [https://bugs.python.org/issue?@action=redirect&bpo=29970].)

새로운 Handle.cancelled() 메서드는 콜백이 취소된 경우 True 를 돌려줍니다. (Contributed by Marat Sharafutdinov in bpo-31943 [https://bugs.python.org/issue?@action=redirect&bpo=31943].)

asyncio 소스는 async/await 구문을 사용하도록 변환되었습니다. (Contributed by Andrew Svetlov in bpo-32193 [https://bugs.python.org/issue?@action=redirect&bpo=32193].)

새로운 ReadTransport.is_reading() 메서드를 사용하여 전송계층의 읽기 상태를 판별 할 수 있습니다. 또한 ReadTransport.resume_reading() 과 ReadTransport.pause_reading() 은 이제 멱등적(idempotent)입니다. (Contributed by Yury Selivanov in bpo-32356 [https://bugs.python.org/issue?@action=redirect&bpo=32356].)

소켓 경로를 받아들이는 루프 메서드에는 이제 경로류 객체 를 전달할 수 있습니다. (Contributed by Yury Selivanov in bpo-32066 [https://bugs.python.org/issue?@action=redirect&bpo=32066].)

asyncio 에서 리눅스의 TCP 소켓은 이제 기본적으로 TCP_NODELAY 플래그가 설정된 상태로 만들어집니다. (Contributed by Yury Selivanov and Victor Stinner in bpo-27456 [https://bugs.python.org/issue?@action=redirect&bpo=27456].)

취소된 작업에서 발생하는 예외는 더 로깅 되지 않습니다. (Contributed by Yury Selivanov in bpo-30508 [https://bugs.python.org/issue?@action=redirect&bpo=30508].)

새로운 WindowsSelectorEventLoopPolicy 와 WindowsProactorEventLoopPolicy 클래스. (Contributed by Yury Selivanov in bpo-33792 [https://bugs.python.org/issue?@action=redirect&bpo=33792].)

몇몇 asyncio API는 폐지되었습니다.

binascii

b2a_uu() 함수는 선택적 backtick 키워드 인자를 받아들입니다. 참일 때, 0은 스페이스 대신에 '`' 로 표현됩니다. (Contributed by Xiang Zhang in bpo-30103 [https://bugs.python.org/issue?@action=redirect&bpo=30103].)

calendar

HTMLCalendar 클래스는 생성된 HTML 달력에서 CSS 클래스의 개별화를 쉽게 해주는 새로운 클래스 어트리뷰트를 갖습니다. (Contributed by Oz Tiram in bpo-30095 [https://bugs.python.org/issue?@action=redirect&bpo=30095].)

collections

collections.namedtuple() 은 이제 기본값을 지원합니다. (Contributed by Raymond Hettinger in bpo-32320 [https://bugs.python.org/issue?@action=redirect&bpo=32320].)

compileall

compileall.compile_dir() 는 새로운 invalidation_mode 매개 변수를 갖습니다. 이 매개 변수는 해시 기반 .pyc 무효화 를 활성화하는데 사용할 수 있습니다. 무효화 모드는 새로운 --invalidation-mode 인자를 사용하여 명령행에서 지정할 수도 있습니다. (Contributed by Benjamin Peterson in bpo-31650 [https://bugs.python.org/issue?@action=redirect&bpo=31650].)

concurrent.futures

ProcessPoolExecutor 와 ThreadPoolExecutor 는 이제 새로운 initializer 및 initargs 생성자 인자를 지원합니다. (Contributed by Antoine Pitrou in bpo-21423 [https://bugs.python.org/issue?@action=redirect&bpo=21423].)

ProcessPoolExecutor 는 새로운 mp_context 인자를 통해 multiprocessing 컨텍스트를 받아들일 수 있습니다. (Contributed by Thomas Moreau in bpo-31540 [https://bugs.python.org/issue?@action=redirect&bpo=31540].)

contextlib

새로운 nullcontext() 는 ExitStack 보다 더 간단하고 빠른 no-op 컨텍스트 관리자입니다. (Contributed by Jesse-Bakker in bpo-10049 [https://bugs.python.org/issue?@action=redirect&bpo=10049].)

새로운 asynccontextmanager(), AbstractAsyncContextManager, AsyncExitStack 가 추가되어 동기 대응물을 보완합니다. (Contributed by Jelle Zijlstra in bpo-29679 [https://bugs.python.org/issue?@action=redirect&bpo=29679] and bpo-30241 [https://bugs.python.org/issue?@action=redirect&bpo=30241], and by Alexander Mohr and Ilya Kulakov in bpo-29302 [https://bugs.python.org/issue?@action=redirect&bpo=29302].)

cProfile

cProfile 명령행은 이제 스크립트 경로의 대안으로 -m module_name 을 허용합니다. (Contributed by Sanyam Khurana in bpo-21862 [https://bugs.python.org/issue?@action=redirect&bpo=21862].)

crypt

crypt 모듈은 이제 블로피시 해싱 방법을 지원합니다. (Contributed by Serhiy Storchaka in bpo-31664 [https://bugs.python.org/issue?@action=redirect&bpo=31664].)

mksalt() 함수는 이제 해싱을 위한 라운드 수를 지정할 수 있습니다. (Contributed by Serhiy Storchaka in bpo-31702 [https://bugs.python.org/issue?@action=redirect&bpo=31702].)

datetime

새로운 datetime.fromisoformat() 메서드는 datetime.isoformat() 이 출력하는 형식의 문자열로부터 datetime 객체를 생성합니다. (Contributed by Paul Ganssle in bpo-15873 [https://bugs.python.org/issue?@action=redirect&bpo=15873].)

tzinfo 클래스는 이제 분보다 작은 오프셋을 지원합니다. (Contributed by Alexander Belopolsky in bpo-5288 [https://bugs.python.org/issue?@action=redirect&bpo=5288].)

dbm

dbm.dumb 는 이제 읽기 전용 파일 읽기를 지원하며 변경되지 않았을 때 더는 색인 파일을 쓰지 않습니다.

decimal

decimal 모듈은 이제 십진 컨텍스트를 저장하는데 컨텍스트 변수 를 사용한다. (Contributed by Yury Selivanov in bpo-32630 [https://bugs.python.org/issue?@action=redirect&bpo=32630].)

dis

dis() 함수는 이제 중첩된 코드 객체 (컴프리헨션, 제너레이터 표현식 및 중첩된 함수의 코드와 중첩된 클래스를 만드는데 사용되는 코드)를 역 어셈블 할 수 있습니다. 해체 재귀의 최대 깊이는 새로운 * depth * 매개 변수에 의해 제어됩니다. (Contributed by Serhiy Storchaka in bpo-11822 [https://bugs.python.org/issue?@action=redirect&bpo=11822].)

distutils

README.rst 는 이제 distutils 표준 README 목록에 포함됩니다. 그래서 소스 배포판에 포함됩니다. (Contributed by Ryan Gonzalez in bpo-11913 [https://bugs.python.org/issue?@action=redirect&bpo=11913].)

enum

Enum 은 새로운 _ignore_ 클래스 프로퍼티를 얻었는데, 열거형 멤버가 되어서는 안 되는 프로퍼티의 이름들을 나열할 수 있도록 합니다. (Contributed by Ethan Furman in bpo-31801 [https://bugs.python.org/issue?@action=redirect&bpo=31801].)

파이썬 3.8에서 Enum 클래스에서 열거 이외의 객체를 포함 검사하려고 하면 TypeError 가 발생합니다 (예 1 in Color). 마찬가지로 Flag 멤버에서 플래그가 아닌 객체를 포함 검사하려고 하면 TypeError 를 일으킵니다 (예 1 in Perm.RW); 현재는, 두 연산 모두 대신 False 가 반환되며, 폐지되었습니다. (Contributed by Ethan Furman in bpo-33217 [https://bugs.python.org/issue?@action=redirect&bpo=33217].)

functools

functools.singledispatch() 는 이제 형 어노테이션을 사용해서 구현을 등록할 수 있습니다. (Contributed by Łukasz Langa in bpo-32227 [https://bugs.python.org/issue?@action=redirect&bpo=32227].)

gc

새로운 gc.freeze() 함수는 가비지 수집기가 추적 한 모든 객체를 고정하고 미래의 수집에서 그것들을 제외합니다. POSIX fork() 호출 전에 사용하면 GC를 쓰기 전에 복사(copy-on-write) 친화적으로 만들고 수집 속도를 높일 수 있습니다. 새로운 gc.unfreeze() 함수는 이 작업을 되돌립니다. 또한, gc.get_freeze_count()를 사용하여 고정된 객체의 수를 얻을 수 있습니다. (Contributed by Li Zekun in bpo-31558 [https://bugs.python.org/issue?@action=redirect&bpo=31558].)

hmac

hmac 모듈은 이제 최적화된 단일 호출 digest() 함수를 제공합니다. HMAC() 보다 최대 3배 빠릅니다. (Contributed by Christian Heimes in bpo-32433 [https://bugs.python.org/issue?@action=redirect&bpo=32433].)

http.client

HTTPConnection 과 HTTPSConnection 은 이제 향상된 업로드 처리량을 위해 새로운 blocksize 인자를 지원합니다. (Contributed by Nir Soffer in bpo-31945 [https://bugs.python.org/issue?@action=redirect&bpo=31945].)

http.server

SimpleHTTPRequestHandler 는 이제 HTTP If-Modified-Since 헤더를 지원합니다. 헤더에 지정된 시간 이후에 대상 파일이 수정되지 않았으면 서버는 304 응답 상태를 돌려줍니다. (Contributed by Pierre Quentel in bpo-29654 [https://bugs.python.org/issue?@action=redirect&bpo=29654].)

SimpleHTTPRequestHandler 는 새로운 --directory 명령행 인자와 더불어 새로운 directory 인자를 받아들입니다. 이 매개 변수를 사용하면 서버는 지정된 디렉터리를 제공하는데, 기본적으로는 현재 작업 디렉터리를 사용합니다. (Contributed by Stéphane Wirtel and Julien Palard in bpo-28707 [https://bugs.python.org/issue?@action=redirect&bpo=28707].)

새로운 ThreadingHTTPServer 클래스는 ThreadingMixin 을 사용하여 요청을 처리하는 데 스레드를 사용합니다. http.server 가 -m 로 실행될 때 사용됩니다. (Contributed by Julien Palard in bpo-31639 [https://bugs.python.org/issue?@action=redirect&bpo=31639].)

idlelib 및 IDLE

자동 완성을 위한 여러 수정. (Contributed by Louie Lu in bpo-15786 [https://bugs.python.org/issue?@action=redirect&bpo=15786].)

Module Browser (File 메뉴에 있는데, 예전에는 Class Browser라고 불렸습니다)는 이제 최상위 함수와 클래스 외에도 중첩된 함수와 클래스도 표시합니다. (Contributed by Guilherme Polo, Cheryl Sabella, and Terry Jan Reedy in bpo-1612262 [https://bugs.python.org/issue?@action=redirect&bpo=1612262].)

설정 대화 상자(Options, Configure IDLE)는 모양과 기능을 향상하기 위해 부분적으로 다시 작성되었습니다. (Contributed by Cheryl Sabella and Terry Jan Reedy in multiple issues.)

이제 글꼴 표본에 라틴 문자 이외의 문자가 포함되어 사용자가 특정 글꼴을 선택했을 때의 효과를 더 잘 볼 수 있습니다. (Contributed by Terry Jan Reedy in bpo-13802 [https://bugs.python.org/issue?@action=redirect&bpo=13802].) 표본을 편집하여 다른 문자를 포함할 수 있습니다. (Contributed by Serhiy Storchaka in bpo-31860 [https://bugs.python.org/issue?@action=redirect&bpo=31860].)

이전에는 확장 기능으로 구현된 IDLE 기능이 일반 기능으로 다시 구현되었습니다. 이것들의 설정을 Extensions 탭에서 다른 대화 상자 탭으로 옮겼습니다. (Contributed by Charles Wohlganger and Terry Jan Reedy in bpo-27099 [https://bugs.python.org/issue?@action=redirect&bpo=27099].)

편집기 코드 컨텍스트 옵션이 개정되었습니다. 상자는 최대 행 수까지 모든 컨텍스트 행을 표시합니다. 컨텍스트 행을 클릭하면 편집기가 해당 행으로 이동합니다. 사용자 정의 테마의 컨텍스트 색상이 설정 대화 상자의 강조 표시 탭에 추가되었습니다. (Contributed by Cheryl Sabella and Terry Jan Reedy in bpo-33642 [https://bugs.python.org/issue?@action=redirect&bpo=33642], bpo-33768 [https://bugs.python.org/issue?@action=redirect&bpo=33768], and bpo-33679 [https://bugs.python.org/issue?@action=redirect&bpo=33679].)

윈도우에서, 새로운 API 호출이 tk가 DPI에 맞게 조정된다는 것을 윈도우에 알려줍니다. Windows 8.1+ 또는 10에서, 파이썬 바이너리의 DPI 호환성 속성을 변경하지 않고도, 96DPI보다 큰 모니터 해상도를 사용하면, 텍스트와 선이 더 선명해집니다. 그렇지 않으면 아무런 효과도 일으키지 않습니다. (Contributed by Terry Jan Reedy in bpo-33656 [https://bugs.python.org/issue?@action=redirect&bpo=33656].)

3.7.1의 새로운 기능:

N 줄(기본값은 50)을 초과하는 출력은 버튼으로 축소됩니다. N은 설정 대화 상자의 General 페이지의 PyShell 섹션에서 변경할 수 있습니다. 저 작은, 하지만 아주 길 수도 있는, 줄은 출력을 마우스 오른쪽 버튼으로 클릭하면 축소할 수 있습니다. 축소된 출력은 버튼을 더블 클릭해서 재자리에서 확대하거나, 버튼을 마우스 오른쪽 단추로 클릭하여 클립 보드나 별도의 창으로 확대할 수 있습니다. (Contributed by Tal Einat in bpo-1529353 [https://bugs.python.org/issue?@action=redirect&bpo=1529353].).

위의 변경 사항은 3.6 유지 보수 배포로 역 이식되었습니다.

NEW in 3.7.4:

Add “Run Customized” to the Run menu to run a module with customized settings. Any command line arguments entered are added to sys.argv. They re-appear in the box for the next customized run. One can also suppress the normal Shell main module restart. (Contributed by Cheryl Sabella, Terry Jan Reedy, and others in bpo-5680 [https://bugs.python.org/issue?@action=redirect&bpo=5680] and bpo-37627 [https://bugs.python.org/issue?@action=redirect&bpo=37627].)

New in 3.7.5:

Add optional line numbers for IDLE editor windows. Windows open without line numbers unless set otherwise in the General tab of the configuration dialog. Line numbers for an existing window are shown and hidden in the Options menu. (Contributed by Tal Einat and Saimadhav Heblikar in bpo-17535 [https://bugs.python.org/issue?@action=redirect&bpo=17535].)

importlib

importlib.abc.ResourceReader ABC가 도입되어 패키지에서 리소스를 로딩하는 것을 지원합니다. importlib.resources 를 참조하세요. (Contributed by Barry Warsaw, Brett Cannon in bpo-32248 [https://bugs.python.org/issue?@action=redirect&bpo=32248].)

importlib.reload() 는 이제 모듈에 스펙이 없는 경우 ModuleNotFoundError 를 발생시킵니다. (Contributed by Garvit Khatri in bpo-29851 [https://bugs.python.org/issue?@action=redirect&bpo=29851].)

importlib.find_spec()은 이제 지정된 부모 모듈이 패키지가 아닌 경우 (즉 __path__ 어트리뷰트가 없는 경우) AttributeError 대신에 ModuleNotFoundError 를 발생시킵니다. (Contributed by Milan Oberkirch in bpo-30436 [https://bugs.python.org/issue?@action=redirect&bpo=30436].)

새로운 importlib.source_hash() 는 전달 된 소스의 해시를 계산하는 데 사용될 수 있습니다. 해시 기반 .pyc 파일 은 함수가 반환하는 값을 포함합니다.

io

새로운 TextIOWrapper.reconfigure() 메서드를 사용하여 텍스트 스트림을 새로운 설정으로 재구성 할 수 있습니다. (Contributed by Antoine Pitrou in bpo-30526 [https://bugs.python.org/issue?@action=redirect&bpo=30526] and INADA Naoki in bpo-15216 [https://bugs.python.org/issue?@action=redirect&bpo=15216].)

ipaddress

ipaddress.IPv6Network 와 ipaddress.IPv4Network 의 새로운 subnet_of() 와 supernet_of() 메서드는 네트워크 포함 테스트에 사용될 수 있습니다. (Contributed by Michel Albert and Cheryl Sabella in bpo-20825 [https://bugs.python.org/issue?@action=redirect&bpo=20825].)

itertools

itertools.islice() 는 start, stop, step 인자로 정수류 객체 를 받아들입니다. (Contributed by Will Roberts in bpo-30537 [https://bugs.python.org/issue?@action=redirect&bpo=30537].)

locale

locale.format_string() 의 새로운 monetary 인자는 변환에 화폐 천 단위 분리자 및 그룹화 문자열을 사용하도록 만듭니다. (Contributed by Garvit in bpo-10379 [https://bugs.python.org/issue?@action=redirect&bpo=10379].)

locale.getpreferredencoding() 함수는 이제 안드로이드나 강제 UTF-8 모드 일 때 항상 'UTF-8' 을 반환합니다.

logging

Logger 인스턴스는 이제 피클(pickle) 할 수 있습니다. (Contributed by Vinay Sajip in bpo-30520 [https://bugs.python.org/issue?@action=redirect&bpo=30520].)

새로운 StreamHandler.setStream() 메서드는 처리기 생성 후 로거 스트림을 대체하는 데 사용될 수 있습니다. (Contributed by Vinay Sajip in bpo-30522 [https://bugs.python.org/issue?@action=redirect&bpo=30522].)

이제 logging.config.fileConfig() 에 전달된 구성에서 처리기 생성자에 대한 키워드 인자를 지정할 수 있습니다. (Contributed by Preston Landers in bpo-31080 [https://bugs.python.org/issue?@action=redirect&bpo=31080].)

math

새로운 math.remainder() 함수는 IEEE 754 스타일의 나머지 연산을 구현합니다. (Contributed by Mark Dickinson in bpo-29962 [https://bugs.python.org/issue?@action=redirect&bpo=29962].)

mimetypes

.bmp의 MIME 형이 'image/x-ms-bmp' 에서 'image/bmp' 로 변경되었습니다. (Contributed by Nitish Chandra in bpo-22589 [https://bugs.python.org/issue?@action=redirect&bpo=22589].)

msilib

새로운 Database.Close() 메서드를 사용하여 MSI 데이터베이스를 닫을 수 있습니다. (Contributed by Berker Peksag in bpo-20486 [https://bugs.python.org/issue?@action=redirect&bpo=20486].)

multiprocessing

새로운 Process.close() 메서드는 명시적으로 프로세스 객체를 닫고 그와 연관된 모든 자원을 해제합니다. 하부 프로세스가 여전히 실행 중이면 ValueError 를 일으킵니다. (Contributed by Antoine Pitrou in bpo-30596 [https://bugs.python.org/issue?@action=redirect&bpo=30596].)

새로운 Process.kill() 메서드는 유닉스에서 SIGKILL 시그널을 사용하여 프로세스를 종료시키는데 사용될 수 있습니다. (Contributed by Vitor Pereira in bpo-30794 [https://bugs.python.org/issue?@action=redirect&bpo=30794].)

Process 에 의해 생성된 데몬이 아닌 스레드는 이제 프로세스 종료 시에 조인(join)됩니다. (Contributed by Antoine Pitrou in bpo-18966 [https://bugs.python.org/issue?@action=redirect&bpo=18966].)

os

os.fwalk() 는 이제 경로 인자로 bytes 도 받아들입니다. (Contributed by Serhiy Storchaka in bpo-28682 [https://bugs.python.org/issue?@action=redirect&bpo=28682].)

os.scandir() 은 파일 기술자 에 대한 지원을 얻었습니다. (Contributed by Serhiy Storchaka in bpo-25996 [https://bugs.python.org/issue?@action=redirect&bpo=25996].)

새로운 register_at_fork() 함수는 프로세스 포크 때 실행될 파이썬 콜백을 등록 할 수 있게 합니다. (Contributed by Antoine Pitrou in bpo-16500 [https://bugs.python.org/issue?@action=redirect&bpo=16500].)

os.preadv() (os.readv() 와 os.pread() 의 기능을 결합한 것)와 os.pwritev() 함수 (os.writev() 와 os.pwrite() 의 기능을 결합한 것)를 추가했습니다. (Contributed by Pablo Galindo in bpo-31368 [https://bugs.python.org/issue?@action=redirect&bpo=31368].)

os.makedirs() 의 mode 인자는 더는 새로 생성된 중간 수준 디렉터리의 파일 사용 권한 비트에 영향을 미치지 않습니다. (Contributed by Serhiy Storchaka in bpo-19930 [https://bugs.python.org/issue?@action=redirect&bpo=19930].)

os.dup2() 는 이제 새로운 파일 기술자를 반환합니다. 이전에는 항상 None 을 반환했습니다. (Contributed by Benjamin Peterson in bpo-32441 [https://bugs.python.org/issue?@action=redirect&bpo=32441].)

os.stat() 에 의해 반환된 구조체는 이제 솔라리스와 그 파생물에서 st_fstype 어트리뷰트를 포함합니다. (Contributed by Jesús Cea Avión in bpo-32659 [https://bugs.python.org/issue?@action=redirect&bpo=32659].)

pathlib

새로운 Path.is_mount() 메서드는 이제 POSIX 시스템에서 사용할 수 있으며 경로가 마운트 지점인지 아닌지를 결정하는 데 사용할 수 있습니다. (Contributed by Cooper Ry Lees in bpo-30897 [https://bugs.python.org/issue?@action=redirect&bpo=30897].)

pdb

pdb.set_trace() 는 이제 선택적 header 키워드 전용 인자를 취합니다. 주어진 경우, 디버깅이 시작되기 바로 전에 콘솔에 출력됩니다. (Contributed by Barry Warsaw in bpo-31389 [https://bugs.python.org/issue?@action=redirect&bpo=31389].)

pdb 명령행은 이제 스크립트 파일의 대안으로 -m module_name 을 받아들입니다. (Contributed by Mario Corchero in bpo-32206 [https://bugs.python.org/issue?@action=redirect&bpo=32206].)

py_compile

py_compile.compile() 은 – 그리고 자연히 compileall 도 – 이제 SOURCE_DATE_EPOCH 환경 변수가 설정되면 해시 기반 유효성 검사를 위해 .pyc 파일을 무조건 생성합니다. 이것은 .pyc 파일의 재현 가능한 빌드 [https://reproducible-builds.org/] 를 보장할 수 있도록 한다. (Contributed by Bernhard M. Wiedemann in bpo-29708 [https://bugs.python.org/issue?@action=redirect&bpo=29708].)

pydoc

pydoc 서버는 이제 새로운 -n 명령행 인자로 지정된 임의의 호스트 이름에 바인드 할 수 있습니다. (Contributed by Feanil Patel in bpo-31128 [https://bugs.python.org/issue?@action=redirect&bpo=31128].)

queue

새로운 SimpleQueue 클래스는 무제한 FIFO 큐입니다. (Contributed by Antoine Pitrou in bpo-14976 [https://bugs.python.org/issue?@action=redirect&bpo=14976].)

re

플래그 re.ASCII, re.LOCALE 및 re.UNICODE 를 그룹의 스코프 내에서 설정할 수 있습니다. (Contributed by Serhiy Storchaka in bpo-31690 [https://bugs.python.org/issue?@action=redirect&bpo=31690].)

re.split() 는 이제 빈 문자열과 일치하는 r'\b', '^$' 또는 (?=-) 와 같은 패턴으로 나누는 것을 지원합니다. (Contributed by Serhiy Storchaka in bpo-25054 [https://bugs.python.org/issue?@action=redirect&bpo=25054].)

re.LOCALE 플래그로 컴파일된 정규식은 더는 컴파일 시간의 로케일에 의존하지 않습니다. 로케일 설정은 컴파일된 정규식이 사용될 때 적용됩니다. (Contributed by Serhiy Storchaka in bpo-30215 [https://bugs.python.org/issue?@action=redirect&bpo=30215].)

정규식이 앞으로 의미적인 변경이 있을 문자 집합 구조물(가령 중첩된 집합과 집합 연산)을 포함하면 이제 FutureWarning 을 줍니다. (Contributed by Serhiy Storchaka in bpo-30349 [https://bugs.python.org/issue?@action=redirect&bpo=30349].)

copy.copy() 와 copy.deepcopy() 를 사용하여 컴파일된 정규식과 매치 객체를 복사 할 수 있습니다. (Contributed by Serhiy Storchaka in bpo-10076 [https://bugs.python.org/issue?@action=redirect&bpo=10076].)

signal

signal.set_wakeup_fd() 함수의 새로운 warn_on_full_buffer 인자는 웨이크업 버퍼 오버플로가 발생했을 때 파이썬이 표준 에러로 경고를 출력할지를 지정할 수 있게 합니다. (Contributed by Nathaniel J. Smith in bpo-30050 [https://bugs.python.org/issue?@action=redirect&bpo=30050].)

socket

새로운 socket.getblocking() 메서드는 소켓이 블로킹 모드에 있으면 True 를 반환하고, 그렇지 않으면 False 를 반환합니다. (Contributed by Yury Selivanov in bpo-32373 [https://bugs.python.org/issue?@action=redirect&bpo=32373].)

새로운 socket.close() 함수는 전달된 소켓 파일 기술자를 닫습니다. 이 함수는 플랫폼 간 호환성을 높이기 위해 os.close() 대신 사용되어야 합니다. (Contributed by Christian Heimes in bpo-32454 [https://bugs.python.org/issue?@action=redirect&bpo=32454].)

socket 모듈은 이제 socket.TCP_CONGESTION (리눅스 2.6.13), socket.TCP_USER_TIMEOUT (Linux 2.6.37) 그리고 socket.TCP_NOTSENT_LOWAT (리눅스 3.12) 상수를 노출합니다. (Contributed by Omar Sandoval in bpo-26273 [https://bugs.python.org/issue?@action=redirect&bpo=26273] and Nathaniel J. Smith in bpo-29728 [https://bugs.python.org/issue?@action=redirect&bpo=29728].)

가상 기계와 호스트 간의 통신을 허용하기 위해 socket.AF_VSOCK 소켓 지원이 추가되었습니다. (Contributed by Cathy Avery in bpo-27584 [https://bugs.python.org/issue?@action=redirect&bpo=27584].)

소켓은 이제 기본적으로 파일 기술자에서 패밀리, 형 및 프로토콜을 자동 감지합니다. (Contributed by Christian Heimes in bpo-28134 [https://bugs.python.org/issue?@action=redirect&bpo=28134].)

socketserver

socketserver.ThreadingMixIn.server_close() 는 이제 모든 데몬이 아닌 스레드가 완료될 때까지 대기합니다. socketserver.ForkingMixIn.server_close() 는 모든 자식 프로세스가 완료될 때까지 대기합니다.

새로운 socketserver.ForkingMixIn.block_on_close 클래스 어트리뷰트를 socketserver.ForkingMixIn 과 socketserver.ThreadingMixIn 클래스에 추가했습니다. 3.7 이전의 동작을 얻으려면 클래스 어트리뷰트를 False 로 설정하십시오.

sqlite3

sqlite3.Connection 은 이제 하부 SQLite 라이브러리의 버전이 3.6.11 이상일 때 backup() 메서드를 노출합니다. (Contributed by Lele Gaifax in bpo-27645 [https://bugs.python.org/issue?@action=redirect&bpo=27645].)

sqlite3.connect() 의 database 인자는 이제 문자열뿐만 아니라 모든 경로류 객체 를 받아들입니다. (Contributed by Anders Lorentsen in bpo-31843 [https://bugs.python.org/issue?@action=redirect&bpo=31843].)

ssl

ssl 모듈은 이제 match_hostname() 대신 OpenSSL의 내장 API를 사용하여 호스트 이름이나 IP 주소를 확인합니다. 값은 TLS 핸드 셰이크 중에 유효성이 검사됩니다. 호스트 이름 검사 실패와 같은 인증서 유효성 검사 오류가 발생하면 이제 SSLCertVerificationError 가 발생하고 적절한 TLS 경고 메시지와 함께 핸드 셰이크가 중단됩니다. 새 예외에는 추가 정보가 들어 있습니다. 호스트 이름 유효성 검증은 SSLContext.hostname_checks_common_name 을 사용하여 사용자 정의 할 수 있습니다. (Contributed by Christian Heimes in bpo-31399 [https://bugs.python.org/issue?@action=redirect&bpo=31399].)

참고

향상된 호스트 이름 검사에는 OpenSSL 1.0.2 또는 1.1과 호환되는 libssl 구현이 필요합니다. 따라서, OpenSSL 0.9.8 및 1.0.1은 더는 지원되지 않습니다 (더 자세한 내용은 플랫폼 지원 제거를 보세요). ssl 모듈은 대부분 LibreSSL 2.7.2 이상과 호환됩니다.

ssl 모듈은 더는 SNI TLS 확장에서 IP 주소를 전송하지 않습니다. (Contributed by Christian Heimes in bpo-32185 [https://bugs.python.org/issue?@action=redirect&bpo=32185].)

match_hostname()은 www*.example.org 와 같은 부분적인 와일드카드를 더는 지원하지 않습니다. (Contributed by Mandeep Singh in bpo-23033 [https://bugs.python.org/issue?@action=redirect&bpo=23033] and Christian Heimes in bpo-31399 [https://bugs.python.org/issue?@action=redirect&bpo=31399].)

ssl 모듈의 기본 사이퍼 군 선택은 이제 하드 코딩된 화이트리스트가 아닌 블랙리스트 접근법을 사용합니다. 파이썬은 더는 OpenSSL 보안 업데이트 때문에 차단된 사이퍼를 다시 활성화하지 않습니다. 기본 사이퍼 군 선택은 컴파일 시점에 구성 할 수 있습니다. (Contributed by Christian Heimes in bpo-31429 [https://bugs.python.org/issue?@action=redirect&bpo=31429].)

국제화된 도메인 이름 (IDN)을 포함하는 서버 인증서의 유효성 검사가 이제 지원됩니다. 이 변경의 일부로, SSLSocket.server_hostname 어트리뷰트는 이제 U-label 형식("pythön.org")보다는 A-label 형식("xn--pythn-mua.org")으로 기대하는 호스트 이름을 저장합니다. (Contributed by Nathaniel J. Smith and Christian Heimes in bpo-28414 [https://bugs.python.org/issue?@action=redirect&bpo=28414].)

ssl 모듈은 TLS 1.3과 OpenSSL 1.1.1을 예비적이고 실험적으로 지원합니다. 파이썬 3.7.0 배포 당시, OpenSSL 1.1.1은 아직 개발 중이며 TLS 1.3은 아직 완성되지 않았습니다. TLS 1.3 핸드 셰이크와 프로토콜은 TLS 1.2 및 그 이전 버전과 약간 다르게 동작합니다. TLS 1.3을 참조하세요. (Contributed by Christian Heimes in bpo-32947 [https://bugs.python.org/issue?@action=redirect&bpo=32947], bpo-20995 [https://bugs.python.org/issue?@action=redirect&bpo=20995], bpo-29136 [https://bugs.python.org/issue?@action=redirect&bpo=29136], bpo-30622 [https://bugs.python.org/issue?@action=redirect&bpo=30622] and bpo-33618 [https://bugs.python.org/issue?@action=redirect&bpo=33618])

SSLSocket 과 SSLObject 는 더는 공개 생성자를 가지고 있지 않습니다. 직접 인스턴스를 만드는 것은 결코 문서로 만들어지고 지원되는 기능이 아닙니다. 인스턴스는 SSLContext 메서드 wrap_socket()과 wrap_bio()로 생성되어야 합니다. (Contributed by Christian Heimes in bpo-32951 [https://bugs.python.org/issue?@action=redirect&bpo=32951])

최소 및 최대 TLS 프로토콜 버전을 설정하기 위한 OpenSSL 1.1 API는 SSLContext.minimum_version 과 SSLContext.maximum_version 로 제공됩니다. 지원되는 프로토콜은 여러 가지 새 플래그로 표시됩니다, 가령 HAS_TLSv1_1. (Contributed by Christian Heimes in bpo-32609 [https://bugs.python.org/issue?@action=redirect&bpo=32609].)

TLS 1.3 포스트 핸드 셰이크 인증을 활성화하는 SSLContext.post_handshake_auth과 시작시키는 ssl.SSLSocket.verify_client_post_handshake()를 추가했습니다. (Contributed by Christian Heimes in bpo-34670 [https://bugs.python.org/issue?@action=redirect&bpo=34670].)

string

string.Template 은 이제 중괄호로 둘러싼 치환식과 그렇지 않은 치환식의 정규식을 따로 선택적으로 수정할 수 있도록 합니다. (Contributed by Barry Warsaw in bpo-1198569 [https://bugs.python.org/issue?@action=redirect&bpo=1198569].)

subprocess

subprocess.run() 함수는 새로운 capture_output 키워드 인자를 받습니다. 참일 때, stdout과 stderr가 캡처됩니다. 이것은 subprocess.PIPE 를 stdout 및 stderr 인자로 전달하는 것과 같습니다. (Contributed by Bo Bayles in bpo-32102 [https://bugs.python.org/issue?@action=redirect&bpo=32102].)

subprocess.run 함수와 subprocess.Popen 생성자는 이제 text 키워드 인자를 universal_newlines 의 별칭으로 받아들입니다. (Contributed by Andrew Clegg in bpo-31756 [https://bugs.python.org/issue?@action=redirect&bpo=31756].)

윈도우에서 close_fds 의 기본값은 표준 핸들을 리디렉션 할 때 False 에서 True 로 변경되었습니다. 이제 표준 핸들을 리디렉션 할 때 close_fds 를 참으로 설정할 수 있습니다. subprocess.Popen 을 참조하세요. 이것은 지원되는 모든 플랫폼에서 이제 close_fds 의 기본값이 True 임을 뜻합니다. (Contributed by Segev Finer in bpo-19764 [https://bugs.python.org/issue?@action=redirect&bpo=19764].)

subprocess 모듈은 이제 subprocess.call(), subprocess.run() 중에, 또는 Popen 컨텍스트 관리자에 있는 동안 KeyboardInterrupt 를 더 우아하게 처리합니다. 이제 KeyboardInterrupt 예외 처리를 계속하기 전에 자식이 종료될 때까지 약간의 시간을 기다립니다. (Contributed by Gregory P. Smith in bpo-25942 [https://bugs.python.org/issue?@action=redirect&bpo=25942].)

sys

새로운 sys.breakpointhook() 훅 함수는 내장 breakpoint() 에 의해 호출됩니다. (Contributed by Barry Warsaw in bpo-31353 [https://bugs.python.org/issue?@action=redirect&bpo=31353].)

안드로이드에서, 새로운 sys.getandroidapilevel() 은 빌드 시간 안드로이드 API 버전을 반환합니다. (Contributed by Victor Stinner in bpo-28740 [https://bugs.python.org/issue?@action=redirect&bpo=28740].)

새로운 sys.get_coroutine_origin_tracking_depth() 함수는 새로운 sys.set_coroutine_origin_tracking_depth() 에 의해 설정된 현재 코루틴 원점 추적 깊이를 반환합니다. asyncio 가 폐지된 sys.set_coroutine_wrapper() 대신 이 새로운 API를 사용하도록 변환되었습니다. (Contributed by Nathaniel J. Smith in bpo-32591 [https://bugs.python.org/issue?@action=redirect&bpo=32591].)

time

PEP 564 [https://www.python.org/dev/peps/pep-0564] 는 time 모듈에 나노초 해상도의 새로운 함수 6개를 추가합니다:

time.clock_gettime_ns()

time.clock_settime_ns()

time.monotonic_ns()

time.perf_counter_ns()

time.process_time_ns()

time.time_ns()

새로운 시계 식별자가 추가되었습니다:

time.CLOCK_BOOTTIME (리눅스): 시스템이 일시 중지된 시간을 포함한다는 점만 제외하고는 time.CLOCK_MONOTONIC 과 같습니다.

time.CLOCK_PROF (FreeBSD, NetBSD, OpenBSD): 고해상도의 프로세스별 CPU 타이머.

time.CLOCK_UPTIME (FreeBSD, OpenBSD): 절댓값이 시스템이 실행 중이었고 중단되지 않은 시간인 시간. 정확한 업타임 측정을 제공합니다.

새로운 time.thread_time()과 time.thread_time_ns() 함수는 스레드 당 CPU 시간을 측정하는 데 사용될 수 있습니다. (Contributed by Antoine Pitrou in bpo-32025 [https://bugs.python.org/issue?@action=redirect&bpo=32025].)

새로운 time.pthread_getcpuclockid() 함수는 스레드 별 CPU 시간 시계의 시계 ID를 반환합니다.

tkinter

이제 새로운 tkinter.ttk.Spinbox 클래스를 사용할 수 있습니다. (Contributed by Alan Moore in bpo-32585 [https://bugs.python.org/issue?@action=redirect&bpo=32585].)

tracemalloc

tracemalloc.Traceback 은 더 일반 트레이스백과 같이 동작하여, 프레임을 가장 오래된 것부터 가장 최근의 것으로 정렬합니다. Traceback.format() 은 이제 음의 limit 을 받아들이고, 결과를 abs(limit) 개의 가장 오래된 프레임으로 잘라냅니다. 이전 동작을 얻으려면, Traceback.format() 에 새로운 most_recent_first 인자를 사용하십시오. (Contributed by Jesse Bakker in bpo-32121 [https://bugs.python.org/issue?@action=redirect&bpo=32121].)

types

이제 새로운 WrapperDescriptorType, MethodWrapperType, MethodDescriptorType, ClassMethodDescriptorType 클래스를 사용할 수 있습니다. (Contributed by Manuel Krebber and Guido van Rossum in bpo-29377 [https://bugs.python.org/issue?@action=redirect&bpo=29377], and Serhiy Storchaka in bpo-32265 [https://bugs.python.org/issue?@action=redirect&bpo=32265].)

새로운 types.resolve_bases() 함수는 PEP 560 [https://www.python.org/dev/peps/pep-0560] 에 지정된 대로 MRO 항목을 동적으로 결정합니다. (Contributed by Ivan Levkivskyi in bpo-32717 [https://bugs.python.org/issue?@action=redirect&bpo=32717].)

unicodedata

내부 unicodedata 데이터베이스가 유니코드 11 [http://www.unicode.org/versions/Unicode11.0.0/] 을 사용하도록 업그레이드되었습니다. (Contributed by Benjamin Peterson.)

unittest

새로운 -k 명령행 옵션은 이름 부분 문자열이나 유닉스 셸과 같은 패턴으로 테스트를 필터링 할 수 있습니다. 예를 들어 python -m unittest -k foo 는 foo_tests.SomeTest.test_something, bar_tests.SomeTest.test_foo 를 실행하지만, bar_tests.FooTest.test_something 는 실행하지 않습니다. (Contributed by Jonas Haag in bpo-32071 [https://bugs.python.org/issue?@action=redirect&bpo=32071].)

unittest.mock

sentinel 어트리뷰트는 이제 복사되거나 피클될 때 그들의 아이덴티티를 보존합니다. (Contributed by Serhiy Storchaka in bpo-20804 [https://bugs.python.org/issue?@action=redirect&bpo=20804].)

새로운 seal() 함수는 Mock 인스턴스를 봉인하도록 허용합니다. 추가적인 어트리뷰트 모의 객체를 만들 수 없도록 합니다. 봉인은 모의 객체인 모든 어트리뷰트에 재귀적으로 적용됩니다. (Contributed by Mario Corchero in bpo-30541 [https://bugs.python.org/issue?@action=redirect&bpo=30541].)

urllib.parse

urllib.parse.quote() 가 RFC 2396 [https://tools.ietf.org/html/rfc2396.html]에서 RFC 3986 [https://tools.ietf.org/html/rfc3986.html]으로 갱신되어, 기본적으로 이스케이프 되지 않는 문자 집합에 ~ 가 추가되었습니다. (Contributed by Christian Theune and Ratnadeep Debnath in bpo-16285 [https://bugs.python.org/issue?@action=redirect&bpo=16285].)

uu

uu.encode() 함수는 이제 선택적 backtick 키워드 인자를 받아들입니다. 참일 때, 0은 스페이스 대신에 '`' 로 표현됩니다. (Contributed by Xiang Zhang in bpo-30103 [https://bugs.python.org/issue?@action=redirect&bpo=30103].)

uuid

새로운 UUID.is_safe 어트리뷰트는 생성된 UUID가 다중 프로세스에 안전한 방법으로 생성되었는지에 대해 플랫폼이 주는 정보를 전달합니다. (Contributed by Barry Warsaw in bpo-22807 [https://bugs.python.org/issue?@action=redirect&bpo=22807].)

uuid.getnode() 는 이제 지역적으로 관리되는 MAC 주소보다 보편적으로 관리되는 MAC 주소를 선호합니다. 이것은 uuid.uuid1() 에서 반환된 UUID의 글로벌 유일성을 더 잘 보장합니다. 지역적으로 관리되는 MAC 주소 만 사용할 수 있는 경우, 처음 발견된 MAC 주소가 반환됩니다. (Contributed by Barry Warsaw in bpo-32107 [https://bugs.python.org/issue?@action=redirect&bpo=32107].)

warnings

기본 경고 필터의 초기화가 다음과 같이 변경되었습니다:

명령행 옵션(-b 및 새로운 CPython 특정 -X dev 옵션을 포함합니다)을 통해 활성화된 경고는 항상 sys.warnoptions 어트리뷰트를 통해 경고 절차로 전달됩니다.

명령행 또는 환경을 통해 활성화된 경고 필터의 우선순위는 다음과 같습니다:

-b (또는 -bb)에 의한 BytesWarning 필터

-W 옵션으로 지정된 모든 필터

PYTHONWARNINGS 환경 변수로 지정된 모든 필터

다른 모든 CPython 특정 필터 (예, 새로운 -X dev 모드를 위해 추가된 default 필터)

경고 절차에 의해 직접 정의된 모든 묵시적 필터

CPython 디버그 빌드에서, 이제 모든 경고가 기본적으로 표시됩니다 (묵시적 필터 목록이 비어 있습니다)

(Contributed by Nick Coghlan and Victor Stinner in bpo-20361 [https://bugs.python.org/issue?@action=redirect&bpo=20361], bpo-32043 [https://bugs.python.org/issue?@action=redirect&bpo=32043], and bpo-32230 [https://bugs.python.org/issue?@action=redirect&bpo=32230].)

폐지 경고는 단일 파일 스크립트 및 대화식 프롬프트에서 다시 한번 기본적으로 표시됩니다. 자세한 내용은 PEP 565: __main__ 의 DeprecationWarning 표시 를 참조하십시오. (Contributed by Nick Coghlan in bpo-31975 [https://bugs.python.org/issue?@action=redirect&bpo=31975].)

xml

DTD 및 외부 엔티티 조회에 대한 완화로서, xml.dom.minidom 및 xml.sax 모듈은 기본적으로 더는 외부 엔티티를 처리하지 않습니다. (Contributed by Christian Heimes in bpo-17239 [https://bugs.python.org/issue?@action=redirect&bpo=17239].)

xml.etree

find() 의 ElementPath 서술자는 이제 [. = "text"] 로 자식의 텍스트뿐만 아니라 현재 노드의 텍스트를 비교할 수 있습니다. 서술자는 가독성을 높이기 위해 스페이스를 추가할 수도 있습니다. (Contributed by Stefan Behnel in bpo-31648 [https://bugs.python.org/issue?@action=redirect&bpo=31648].)

xmlrpc.server

SimpleXMLRPCDispatcher.register_function 는 이제 데코레이터로 사용할 수 있습니다. (Contributed by Xiang Zhang in bpo-7769 [https://bugs.python.org/issue?@action=redirect&bpo=7769].)

zipapp

함수 create_archive() 는 이제 사용자가 저장소에 포함되어야 하는 파일을 선택할 수 있도록 선택적 filter 인자를 받아들입니다. (Contributed by Irmen de Jong in bpo-31072 [https://bugs.python.org/issue?@action=redirect&bpo=31072].)

함수 create_archive() 는 이제 압축된 저장소를 생성하기 위해 선택적 compressed 인자를 받아들입니다. 명령행 옵션 --compress 도 압축을 지원하기 위해 추가되었습니다. (Contributed by Zhiming Wang in bpo-31638 [https://bugs.python.org/issue?@action=redirect&bpo=31638].)

zipfile

ZipFile 은 이제 압축 수준을 제어하기 위해 새로운 compresslevel 매개변수를 받아들입니다. (Contributed by Bo Bayles in bpo-21417 [https://bugs.python.org/issue?@action=redirect&bpo=21417].)

ZipFile 에 의해 생성된 저장소에 있는 서브 디렉터리는 이제 알파벳순으로 저장됩니다. (Contributed by Bernhard M. Wiedemann in bpo-30693 [https://bugs.python.org/issue?@action=redirect&bpo=30693].)

C API 변경

스레드-로컬 저장소를 위한 새로운 API가 구현되었습니다. 개요는 PEP 539: 스레드-로컬 저장소를 위한 새로운 C API 를, 완전한 레퍼런스는 Thread Specific Storage (TSS) API를 보십시오. (Contributed by Masayuki Yamamoto in bpo-25658 [https://bugs.python.org/issue?@action=redirect&bpo=25658].)

새로운 컨텍스트 변수 기능은 다수의 새로운 C API를 노출합니다.

새로운 PyImport_GetModule() 함수는 주어진 이름으로 이전에 임포트 한 모듈을 반환합니다. (Contributed by Eric Snow in bpo-28411 [https://bugs.python.org/issue?@action=redirect&bpo=28411].)

새로운 Py_RETURN_RICHCOMPARE 매크로는 풍부한 비교 함수를 작성하기 쉽게 합니다. (Contributed by Petr Victorin in bpo-23699 [https://bugs.python.org/issue?@action=redirect&bpo=23699].)

새로운 Py_UNREACHABLE 매크로는 도달할 수 없는 코드 경로를 표시하는 데 사용될 수 있습니다. (Contributed by Barry Warsaw in bpo-31338 [https://bugs.python.org/issue?@action=redirect&bpo=31338].)

tracemalloc 은 이제 새로운 PyTraceMalloc_Track()과 PyTraceMalloc_Untrack() 함수를 통해 C API를 노출합니다. (Contributed by Victor Stinner in bpo-30054 [https://bugs.python.org/issue?@action=redirect&bpo=30054].)

새로운 import__find__load__start()와 import__find__load__done() 정적 마커를 사용하여 모듈 임포트를 추적 할 수 있습니다. (Contributed by Christian Heimes in bpo-31574 [https://bugs.python.org/issue?@action=redirect&bpo=31574].)

구조체 PyMemberDef, PyGetSetDef, PyStructSequence_Field, PyStructSequence_Desc 그리고 wrapperbase 의 필드 name과 doc 은 이제 char * 이 아니라 const char * 형입니다. (Contributed by Serhiy Storchaka in bpo-28761 [https://bugs.python.org/issue?@action=redirect&bpo=28761].)

PyUnicode_AsUTF8AndSize() 와 PyUnicode_AsUTF8()의 결과는 이제 char * 이 아니라 const char * 입니다. (Contributed by Serhiy Storchaka in bpo-28769 [https://bugs.python.org/issue?@action=redirect&bpo=28769].)

PyMapping_Keys(), PyMapping_Values() 및 PyMapping_Items()의 결과는 이제 리스트 또는 튜플이 아니라 항상 리스트입니다. (Contributed by Oren Milman in bpo-28280 [https://bugs.python.org/issue?@action=redirect&bpo=28280].)

함수 PySlice_Unpack()과 PySlice_AdjustIndices() 를 추가했습니다. (Contributed by Serhiy Storchaka in bpo-27867 [https://bugs.python.org/issue?@action=redirect&bpo=27867].)

PyOS_AfterFork() 는 폐지되고, 새 함수 PyOS_BeforeFork(), PyOS_AfterFork_Parent() 그리고 PyOS_AfterFork_Child()로 대체되었습니다. (Contributed by Antoine Pitrou in bpo-16500 [https://bugs.python.org/issue?@action=redirect&bpo=16500].)

공개 API의 일부였던 PyExc_RecursionErrorInst 싱글톤은 제거되었습니다. 청소되지 않은 멤버가 인터프리터의 파이널리제이션 과정에서 세그멘테이션 오류를 일으킬 수 있기 때문입니다. (Contributed by Xavier de Gaye in bpo-22898 [https://bugs.python.org/issue?@action=redirect&bpo=22898] and bpo-30697 [https://bugs.python.org/issue?@action=redirect&bpo=30697].)

시간대 지원을 위한 timezone 생성자 PyTimeZone_FromOffset() 과 PyTimeZone_FromOffsetAndName() 및 UTC 싱글톤에 액세스하는 PyDateTime_TimeZone_UTC C API 지원을 추가했습니다. (Contributed by Paul Ganssle in bpo-10381 [https://bugs.python.org/issue?@action=redirect&bpo=10381].)

PyThread_start_new_thread() 및 PyThread_get_thread_ident() 의 결과와 PyThreadState_SetAsyncExc() 의 id 매개 변수의 형이 long에서 unsigned long로 변경되었습니다. (Contributed by Serhiy Storchaka in bpo-6532 [https://bugs.python.org/issue?@action=redirect&bpo=6532].)

PyUnicode_AsWideCharString() now raises a ValueError if the second argument is NULL and the wchar_t* string contains null characters. (Contributed by Serhiy Storchaka in bpo-30708 [https://bugs.python.org/issue?@action=redirect&bpo=30708].)

시동 절차와 동적 메모리 할당자의 변경으로 인해 대부분의 C API 함수를 호출하기 전에 Py_Initialize() 를 호출해야 한다는 오래전부터 문서화 된 요구 사항이 이제 더 중요해졌고, 이를 지키지 않으면 내장형 응용 프로그램에서 세그멘테이션 오류로 이어질 수 있습니다. 자세한 내용은 이 문서의 파이썬 3.7로 이식하기 절과 C API 설명서의 Before Python Initialization 절을 참조하십시오.

새로운 PyInterpreterState_GetID() 는 주어진 인터프리터의 유일한 ID를 반환합니다. (Contributed by Eric Snow in bpo-29102 [https://bugs.python.org/issue?@action=redirect&bpo=29102].)

Py_DecodeLocale(), Py_EncodeLocale() 은 이제 UTF-8 모드 가 활성화될 때 UTF-8 인코딩을 사용합니다. (Contributed by Victor Stinner in bpo-29240 [https://bugs.python.org/issue?@action=redirect&bpo=29240].)

PyUnicode_DecodeLocaleAndSize() 와 PyUnicode_EncodeLocale()은 이제 surrogateescape 에러 처리기에 현재 로케일 인코딩을 사용합니다. (Contributed by Victor Stinner in bpo-29240 [https://bugs.python.org/issue?@action=redirect&bpo=29240].)

PyUnicode_FindChar() 의 start 와 end 매개 변수가 문자열 슬라이스처럼 동작하도록 조정되었습니다. (Contributed by Xiang Zhang in bpo-28822 [https://bugs.python.org/issue?@action=redirect&bpo=28822].)

빌드 변경

--without-threads 빌드 지원이 제거되었습니다. threading 모듈은 이제 항상 사용할 수 있습니다. (Contributed by Antoine Pitrou in bpo-31370 [https://bugs.python.org/issue?@action=redirect&bpo=31370].)

OSX 이외의 유닉스 플랫폼에서 _ctypes 모듈을 빌드할 때 사용되는 libffi의 전체 복사본이 더는 포함되지 않습니다. 이러한 플랫폼에서 _ctypes 를 빌드 할 때 libffi의 설치된 사본이 필요합니다. (Contributed by Zachary Ware in bpo-27979 [https://bugs.python.org/issue?@action=redirect&bpo=27979].)

윈도우 빌드 프로세스는 외부 소스를 가져오는 데 더는 서브버전에 의존하지 않습니다. 대신 파이썬 스크립트를 사용해서 GitHub에서 zip 파일을 내려받습니다. 시스템에서 파이썬 3.6이 발견되지 않으면 (py -3.6 를 통해), 이 목적을 위해 NuGet으로 32-비트 파이썬의 사본을 내려받습니다. (Contributed by Zachary Ware in bpo-30450 [https://bugs.python.org/issue?@action=redirect&bpo=30450].)

ssl 모듈은 OpenSSL 1.0.2 또는 1.1 호환 libssl을 요구합니다. OpenSSL 1.0.1의 유효 기간은 2016-12-31 에 만료되었고 더는 지원되지 않습니다. LibreSSL도 일시적으로 지원되지 않습니다. 버전 2.6.4까지의 LibreSSL 배포에는 필수 OpenSSL 1.0.2 API가 없습니다.

최적화

C로 구현된 다양한 표준 라이브러리 클래스의 많은 메서드를 호출하는 오버헤드가, METH_FASTCALL 규칙을 사용하도록 더 많은 코드를 이식함으로써 상당히 감소하였습니다. (Contributed by Victor Stinner in bpo-29300 [https://bugs.python.org/issue?@action=redirect&bpo=29300], bpo-29507 [https://bugs.python.org/issue?@action=redirect&bpo=29507], bpo-29452 [https://bugs.python.org/issue?@action=redirect&bpo=29452], and bpo-29286 [https://bugs.python.org/issue?@action=redirect&bpo=29286].)

다양한 최적화를 통해 파이썬의 시작 시간을 리눅스에서 10%, macOS에서 최대 30%까지 줄였습니다. (Contributed by Victor Stinner, INADA Naoki in bpo-29585 [https://bugs.python.org/issue?@action=redirect&bpo=29585], and Ivan Levkivskyi in bpo-31333 [https://bugs.python.org/issue?@action=redirect&bpo=31333].)

메서드 호출은 이제 연결된 메서드 인스턴스 생성을 피하는 바이트 코드 변경으로 인해 최대 20% 빨라졌습니다. (Contributed by Yury Selivanov and INADA Naoki in bpo-26110 [https://bugs.python.org/issue?@action=redirect&bpo=26110].)

asyncio 모듈은 자주 사용되는 함수들에 대해 여러 가지 주목할만한 최적화가 이루어졌습니다:

asyncio.get_event_loop() 함수가 C로 다시 구현되어 최대 15배 빨라졌습니다. (Contributed by Yury Selivanov in bpo-32296 [https://bugs.python.org/issue?@action=redirect&bpo=32296].)

asyncio.Future 콜백 관리가 최적화되었습니다. (Contributed by Yury Selivanov in bpo-32348 [https://bugs.python.org/issue?@action=redirect&bpo=32348].)

asyncio.gather() 는 이제 최대 15% 빨라졌습니다. (Contributed by Yury Selivanov in bpo-32355 [https://bugs.python.org/issue?@action=redirect&bpo=32355].)

asyncio.sleep()은 이제 delay 인자가 0이거나 음수일 때 최대 2배 빠릅니다. (Contributed by Andrew Svetlov in bpo-32351 [https://bugs.python.org/issue?@action=redirect&bpo=32351].)

asyncio 디버그 모드의 성능 오버헤드가 감소하였습니다. (Contributed by Antoine Pitrou in bpo-31970 [https://bugs.python.org/issue?@action=redirect&bpo=31970].)

PEP 560 작업 의 결과로, typing 의 임포트 시간이 7배 단축되었으며, 많은 typing 연산이 이제 더 빨라졌습니다. (Contributed by Ivan Levkivskyi in bpo-32226 [https://bugs.python.org/issue?@action=redirect&bpo=32226].)

sorted()와 list.sort() 는 일반적인 사용에 대해 최대 40-75% 더 빠르게 최적화되었습니다. (Contributed by Elliot Gorokhovsky in bpo-28685 [https://bugs.python.org/issue?@action=redirect&bpo=28685].)

dict.copy() 는 이제 5.5 배 빠릅니다. (Contributed by Yury Selivanov in bpo-31179 [https://bugs.python.org/issue?@action=redirect&bpo=31179].)

hasattr()과 getattr()은 이제 name 이 발견되지 않고 obj 가 object.__getattr__() 또는 object.__getattribute__() 를 재정의하지 않을 때 약 4배 빨라졌습니다. (Contributed by INADA Naoki in bpo-32544 [https://bugs.python.org/issue?@action=redirect&bpo=32544].)

문자열에서 특정 유니코드 문자 (가령 우크라이나어 “Є”)를 검색하는 것은 다른 문자를 검색하는 것보다 최대 25배까지 느렸습니다. 이제는 최악의 상황에도 겨우 3배 느립니다. (Contributed by Serhiy Storchaka in bpo-24821 [https://bugs.python.org/issue?@action=redirect&bpo=24821].)

collections.namedtuple() 팩토리가 재구현되어 네임드 튜플을 4 에서 6배 빠르게 생성합니다. (Contributed by Jelle Zijlstra with further improvements by INADA Naoki, Serhiy Storchaka, and Raymond Hettinger in bpo-28638 [https://bugs.python.org/issue?@action=redirect&bpo=28638].)

date.fromordinal() 과 date.fromtimestamp() 는 이제 일반적일 때 최대 30% 더 빠릅니다. (Contributed by Paul Ganssle in bpo-32403 [https://bugs.python.org/issue?@action=redirect&bpo=32403].)

os.fwalk() 함수는 os.scandir() 을 사용함으로써 이제 최대 2배 빨라졌습니다. (Contributed by Serhiy Storchaka in bpo-25996 [https://bugs.python.org/issue?@action=redirect&bpo=25996].)

os.scandir() 함수를 사용하여 shutil.rmtree() 함수의 속도가 20–40% 향상되었습니다. (Contributed by Serhiy Storchaka in bpo-28564 [https://bugs.python.org/issue?@action=redirect&bpo=28564].)

최적화된 정규식 의 대소 문자를 구별하지 않는 매칭과 검색. 일부 패턴 검색은 이제 최대 20배까지 빨라질 수 있습니다. (Contributed by Serhiy Storchaka in bpo-30285 [https://bugs.python.org/issue?@action=redirect&bpo=30285].)

re.compile() 은 이제 flags 매개 변수가 RegexFlag 인 경우 int 객체로 변환합니다. 이제 파이썬 3.5만큼 빠르고, 패턴에 따라 파이썬 3.6보다 약 10% 빠릅니다. (Contributed by INADA Naoki in bpo-31671 [https://bugs.python.org/issue?@action=redirect&bpo=31671].)

클래스 selectors.EpollSelector, selectors.PollSelector 와 selectors.DevpollSelector 의 modify() 메서드는 높은 부하가 걸릴 때 10% 정도 더 빨라질 수 있습니다. (Contributed by Giampaolo Rodola’ in bpo-30014 [https://bugs.python.org/issue?@action=redirect&bpo=30014])

상수 폴딩은 핍홀 최적화기에서 새로운 AST 최적화기로 이동되어, 더욱 일관된 최적화를 수행 할 수 있습니다. (Contributed by Eugene Toder and INADA Naoki in bpo-29469 [https://bugs.python.org/issue?@action=redirect&bpo=29469] and bpo-11549 [https://bugs.python.org/issue?@action=redirect&bpo=11549].)

abc 에 있는 대부분 함수와 메서드는 C로 재작성되었습니다. 이로 인해 추상 베이스 클래스 생성과, 이에 대한 isinstance() 와 issubclass() 호출이 1.5 배 더 빠릅니다. 또한, 파이썬 시작 시간을 최대 10% 단축합니다. (Contributed by Ivan Levkivskyi and INADA Naoki in bpo-31333 [https://bugs.python.org/issue?@action=redirect&bpo=31333])

datetime.date 와 datetime.datetime 의 대체 생성자의 경우, 서브 클래스를 만들지 않을 때 파이썬 생성자를 우회해서 속도가 현저히 향상되었습니다. (Contributed by Paul Ganssle in bpo-32403 [https://bugs.python.org/issue?@action=redirect&bpo=32403])

array.array 인스턴스의 비교 속도가 어떤 경우에는 상당히 향상되었습니다. 같은 정수 형의 값을 보유한 배열을 비교할 때, 이제는 10배에서 70배 빠릅니다. (Contributed by Adrian Wielgosik in bpo-24700 [https://bugs.python.org/issue?@action=redirect&bpo=24700].)

math.erf() 와 math.erfc() 함수는 이제 대부분 플랫폼에서 (더 빠른) C 라이브러리 구현을 사용합니다. (Contributed by Serhiy Storchaka in bpo-26121 [https://bugs.python.org/issue?@action=redirect&bpo=26121].)

기타 CPython 구현 변경

트레이스 훅은 이제 추적할 프레임의 새로운 f_trace_lines 와 f_trace_opcodes 어트리뷰트를 설정하여, 인터프리터로부터 line 대신 opcode 이벤트를 수신하도록 선택할 수 있습니다. (Contributed by Nick Coghlan in bpo-31344 [https://bugs.python.org/issue?@action=redirect&bpo=31344].)

이름 공간 패키지 모듈 어트리뷰트에 대한 일관성 문제를 수정했습니다. 이름 공간 모듈 객체는 이제 __file__ 을 None (이전에는 설정되지 않았습니다)으로 설정하고, __spec__.origin 도 None (이전에는 문자열 "namespace")으로 설정됩니다. bpo-32305 [https://bugs.python.org/issue?@action=redirect&bpo=32305]를 참조하세요. 또한, 이름 공간 모듈 객체의 __spec__.loader 는 __loader__ 와 같은 값으로 설정됩니다 (이전에는 None 으로 설정되었습니다). bpo-32303 [https://bugs.python.org/issue?@action=redirect&bpo=32303]을 참조하세요.

locals() 딕셔너리는 이제 변수가 정의된 어휘 순서로 표시됩니다. 이전에는 순서가 정의되지 않았습니다. (Contributed by Raymond Hettinger in bpo-32690 [https://bugs.python.org/issue?@action=redirect&bpo=32690].)

distutils upload 명령은 더는 CR 줄 마침 문자를 CRLF로 바꾸려고 시도하지 않습니다. 이것은 CR에 해당하는 바이트로 끝나는 sdists의 손상 문제를 수정합니다. (Contributed by Bo Bayles in bpo-32304 [https://bugs.python.org/issue?@action=redirect&bpo=32304].)

폐지된 파이썬 동작

일드 표현식(yield 와 yield from 절 모두)은 이제 컴프리헨션과 제너레이터 표현식에서 폐지되었습니다 (가장 왼쪽의 for 절의 이터러블 표현식은 제외합니다). 이것은 컴프리헨션이 언제나 적절한 유형의 컨테이너를 즉시 반환하도록 하고(잠재적으로 제너레이터 이터레이터 객체를 반환하는 것이 아니라), 제너레이터 표현식이 명시적 일드 표현식의 출력 중간에 묵시적 출력을 끼워 넣으려고 시도하지 못하게 하기 위함입니다. 파이썬 3.7에서 이러한 표현식은 컴파일될 때 DeprecationWarning 을 내보내고, 파이썬 3.8에서는 SyntaxError 가 됩니다. (Contributed by Serhiy Storchaka in bpo-10544 [https://bugs.python.org/issue?@action=redirect&bpo=10544].)

complex 의 서브 클래스를 object.__complex__() 에서 반환하는 것은 폐지되었고, 향후 파이썬 버전에서 에러가 발생할 것입니다. 이것은 __complex__() 를 object.__int__() 및 object.__float__() 와 일관성 있도록 만듭니다. (Contributed by Serhiy Storchaka in bpo-28894 [https://bugs.python.org/issue?@action=redirect&bpo=28894].)

폐지된 파이썬 모듈, 함수 및 메서드

aifc

aifc.openfp() 는 폐지되었고 파이썬 3.9에서 제거될 것입니다. 대신에 aifc.open() 을 사용하십시오. (Contributed by Brian Curtin in bpo-31985 [https://bugs.python.org/issue?@action=redirect&bpo=31985].)

asyncio

asyncio.Lock 및 다른 asyncio 동기화 프리미티브의 인스턴스를 직접 await 하는 지원은 폐지되었습니다. 동기화 자원을 획득하고 해제하기 위해서는 비동기 컨텍스트 관리자를 사용해야 합니다. (Contributed by Andrew Svetlov in bpo-32253 [https://bugs.python.org/issue?@action=redirect&bpo=32253].)

asyncio.Task.current_task()와 asyncio.Task.all_tasks() 메서드는 폐지되었습니다. (Contributed by Andrew Svetlov in bpo-32250 [https://bugs.python.org/issue?@action=redirect&bpo=32250].)

collections

파이썬 3.8에서, collections.abc 의 추상 베이스 클래스는 더는 collections 모듈에 노출되지 않습니다. 이것은 구상 클래스와 추상 베이스 클래스 사이의 명확한 구분을 만드는 데 도움이 됩니다. (Contributed by Serhiy Storchaka in bpo-25988 [https://bugs.python.org/issue?@action=redirect&bpo=25988].)

dbm

dbm.dumb 은 이제 읽기 전용 파일 읽기를 지원하며 변경되지 않았을 때 더는 색인 파일을 쓰지 않습니다. 'r' 및 'w' 모드에서 색인 파일이 빠지고 새로 만들어지면, 이제 폐지 경고가 표시됩니다 (향후의 파이썬 배포에서는 에러가 발생합니다). (Contributed by Serhiy Storchaka in bpo-28847 [https://bugs.python.org/issue?@action=redirect&bpo=28847].)

enum

파이썬 3.8에서, Enum 클래스에서 열거형 이외의 객체가 포함되었는지 검사하려고 하면 TypeError 가 발생합니다 (예 1 in Color); 마찬가지로 플래그가 아닌 객체를 Flag 멤버에 포함되었는지 검사하려고 하면 TypeError 가 발생합니다 (예 1 in Perm.RW); 현재 두 연산 모두 대신 False를 반환합니다. (Contributed by Ethan Furman in bpo-33217 [https://bugs.python.org/issue?@action=redirect&bpo=33217].)

gettext

gettext 에서 복수형을 선택하기 위해 정수가 아닌 값을 사용하는 것이 폐지되었습니다. 올바르게 작동된 적이 없습니다. (Contributed by Serhiy Storchaka in bpo-28692 [https://bugs.python.org/issue?@action=redirect&bpo=28692].)

importlib

메서드 MetaPathFinder.find_module() (MetaPathFinder.find_spec() 로 대체되었습니다)와 PathEntryFinder.find_loader() (PathEntryFinder.find_spec() 로 대체되었습니다) 는 둘 다 파이썬 3.4에서 폐지되었고, 이제는 DeprecationWarning 을 일으킵니다. (Contributed by Matthias Bussonnier in bpo-29576 [https://bugs.python.org/issue?@action=redirect&bpo=29576])

importlib.abc.ResourceLoader ABC는 폐지되었고, 대신 importlib.abc.ResourceReader 를 사용합니다.

locale

locale.format() 은 폐지되었습니다. 대신 locale.format_string()을 사용하십시오. (Contributed by Garvit in bpo-10379 [https://bugs.python.org/issue?@action=redirect&bpo=10379].)

macpath

macpath 는 이제 폐지되었고 파이썬 3.8에서 제거될 것입니다. (Contributed by Chi Hsuan Yen in bpo-9850 [https://bugs.python.org/issue?@action=redirect&bpo=9850].)

threading

dummy_threading과 _dummy_thread 는 폐지되었습니다. 스레딩을 비활성화하여 파이썬을 빌드하는 것이 더는 가능하지 않습니다. 대신 threading을 사용하십시오. (Contributed by Antoine Pitrou in bpo-31370 [https://bugs.python.org/issue?@action=redirect&bpo=31370].)

socket

socket.htons() 와 socket.ntohs() 에서 자동 인자 값 자름은 폐지되었습니다. 이후 버전의 파이썬에서는 전달된 인자가 16비트보다 큰 경우 예외가 발생합니다. (Contributed by Oren Milman in bpo-28332 [https://bugs.python.org/issue?@action=redirect&bpo=28332].)

ssl

ssl.wrap_socket() 은 폐지되었습니다. 대신 ssl.SSLContext.wrap_socket()을 사용하십시오. (Contributed by Christian Heimes in bpo-28124 [https://bugs.python.org/issue?@action=redirect&bpo=28124].)

sunau

sunau.openfp() 는 폐지되었고 파이썬 3.9에서 제거될 것입니다. 대신에 sunau.open() 을 사용하십시오. (Contributed by Brian Curtin in bpo-31985 [https://bugs.python.org/issue?@action=redirect&bpo=31985].)

sys

sys.set_coroutine_wrapper()와 sys.get_coroutine_wrapper()를 폐지했습니다.

문서로 만들어지지 않은 sys.callstats() 함수는 폐지되었고 향후 파이썬 버전에서 제거될 것입니다. (Contributed by Victor Stinner in bpo-28799 [https://bugs.python.org/issue?@action=redirect&bpo=28799].)

wave

wave.openfp() 는 폐지되었고 파이썬 3.9에서 제거될 것입니다. 대신 wave.open() 을 사용하십시오. (Contributed by Brian Curtin in bpo-31985 [https://bugs.python.org/issue?@action=redirect&bpo=31985].)

폐지된 C API의 함수 및 형

함수 PySlice_GetIndicesEx() 는 폐지되었고, Py_LIMITED_API 가 설정되어 있지 않거나, 0x03050400 과 0x03060000 (포함되지 않음) 사이의 값이나 0x03060100 이상의 값으로 설정되어 있으면 매크로로 대체됩니다. (Contributed by Serhiy Storchaka in bpo-27867 [https://bugs.python.org/issue?@action=redirect&bpo=27867].)

PyOS_AfterFork() 는 폐지되었습니다. PyOS_BeforeFork(), PyOS_AfterFork_Parent() 또는 PyOS_AfterFork_Child() 를 대신 사용하십시오. (Contributed by Antoine Pitrou in bpo-16500 [https://bugs.python.org/issue?@action=redirect&bpo=16500].)

플랫폼 지원 제거

FreeBSD 9와 그 이전 버전은 더는 공식적으로 지원되지 않습니다.

확장 모듈 내를 포함하여, 완전한 유니코드 지원을 위해 유닉스 플랫폼은 이제 레거시 ASCII 기반 C 로케일의 대안으로, C.UTF-8 (전체 로케일), C.utf8 (전체 로케일) 또는 UTF-8 (LC_CTYPE 전용 로케일) 중 적어도 하나를 제공할 것으로 기대됩니다.

OpenSSL 0.9.8 및 1.0.1은 더는 지원되지 않습니다. 이는 여전히 이 버전을 사용하는 이전 플랫폼에서 SSL/TLS를 지원하는 CPython 3.7을 빌드하려면 최신 버전의 OpenSSL에 링크되는 사용자 정의 빌드 옵션이 필요함을 뜻합니다.

특히, 이 문제는 Debian 8 (일명 “jessie”) 및 Ubuntu 14.04 (일명 “Trusty”) LTS 리눅스 배포판에 영향을 미칩니다. 아직 OpenSSL 1.0.1을 기본적으로 사용하기 때문입니다.

Debian 9 (“stretch”) 및 Ubuntu 16.04 (“xenial”) 는, 다른 LTS 리눅스 배포판(가령, RHEL/CentOS 7.5, SLES 12-SP3)의 최신 릴리스 역시, OpenSSL 1.0.2 이상을 사용하고, 기본 빌드 구성에서 여전히 지원됩니다.

CPython의 자체 CI 구성 파일 [https://github.com/python/cpython/tree/3.7/.travis.yml]은 CPython의 테스트 스위트에서 SSL 호환성 테스트 기반시설 [https://github.com/python/cpython/tree/3.7/Tools/ssl/multissltests.py]을 사용하여 구형 시스템이 제공하는 OpenSSL대신 OpenSSL 1.1.0을 빌드하고 링크하는 예를 제공합니다.

API 및 기능 제거

다음 기능과 API는 파이썬 3.7에서 제거되었습니다:

os.stat_float_times() 함수가 제거되었습니다. 이것은 파이썬 2.2와의 하위 호환성을 위해 파이썬 2.3에서 소개되었으며 파이썬 3.1부터 폐지되었습니다.

re.sub() 의 대체 템플릿에 있는 '\' 와 ASCII 글자로 이루어진 알 수 없는 이스케이프는 파이썬 3.5에서 폐지되었고, 이제는 에러를 일으킵니다.

tarfile.TarFile.add() 에서 exclude 인자의 지원이 제거되었습니다. 파이썬 2.7 및 3.2에서 폐지되었습니다. 대신 filter 인자를 사용하십시오.

ntpath 모듈의 splitunc() 함수는 파이썬 3.1에서 폐지되었고, 이제 제거되었습니다. 대신에 splitdrive() 함수를 사용하십시오.

collections.namedtuple()은 네임드 튜플 클래스에 대해 생성된 소스 코드를 보여주는 verbose 매개 변수 나 _source 어트리뷰트를 더는 지원하지 않습니다. 이것은 클래스 생성 속도를 높이기 위해 고안된 최적화 일부입니다. (Contributed by Jelle Zijlstra with further improvements by INADA Naoki, Serhiy Storchaka, and Raymond Hettinger in bpo-28638 [https://bugs.python.org/issue?@action=redirect&bpo=28638].)

함수 bool(), float(), list() 그리고 tuple() 은 더는 키워드 인자를 취하지 않습니다. int() 의 첫 번째 인자는 이제 위치 인자로만 전달될 수 있습니다.

plistlib 모듈에서, 이전에 파이썬 2.4에서 폐지된 클래스 Plist, Dict, _InternalDict 가 제거되었습니다. readPlist() 함수와 readPlistFromBytes() 함수의 결과에서 Dict 값은 이제 정상적인 딕셔너리입니다. 더는 어트리뷰트 액세스를 사용하여 이러한 딕셔너리의 항목에 액세스할 수 없습니다.

asyncio.windows_utils.socketpair() 함수가 삭제되었습니다. 대신에 socket.socketpair() 함수를 사용하십시오. 파이썬 3.5부터 모든 플랫폼에서 사용할 수 있습니다. asyncio.windows_utils.socketpair 는 파이썬 3.5 이상에서 socket.socketpair 의 별칭이었습니다.

asyncio 는 더는 selectors와 _overlapped 모듈을 asyncio.selectors 와 asyncio._overlapped 로 노출하지 않습니다. from asyncio import selectors 를 import selectors 로 대체하십시오.

ssl.SSLSocket 과 ssl.SSLObject 객체의 직접적인 인스턴스 생성이 금지되었습니다. 생성자는 공개 생성자로서 문서화, 테스트 또는 설계되지 않았습니다. 사용자는 ssl.wrap_socket() 또는 ssl.SSLContext 를 사용해야 합니다. (Contributed by Christian Heimes in bpo-32951 [https://bugs.python.org/issue?@action=redirect&bpo=32951].)

사용되지 않는 distutils install_misc 명령이 제거되었습니다. (Contributed by Eric N. Vander Weele in bpo-29218 [https://bugs.python.org/issue?@action=redirect&bpo=29218].)

모듈 제거

fpectl 모듈이 삭제되었습니다. 기본적으로 활성화된 적이 없고, x86-64에서 제대로 작동한 적도 없고, 예기치 않게 C 확장을 깨뜨리는 방식으로 파이썬 ABI를 변경했습니다. (Contributed by Nathaniel J. Smith in bpo-29137 [https://bugs.python.org/issue?@action=redirect&bpo=29137].)

윈도우 전용 변경

파이썬 런처(py.exe)는 32비트와 64비트 지정자를 받아들일 수 있는데, 마이너 버전을 지정하지 않아도 됩니다. 그래서 py -3.7-32 뿐만 아니라 py -3-32 와 py -3-64 도 유효합니다. 또한 -m-64와 -m.n-64 형식도 이제 받아들이는데, 지정하지 않을 때 32비트가 사용되는 경우도 64비트 파이썬을 강제합니다. 지정된 버전을 사용할 수 없는 경우 py.exe가 에러를 일으키며 종료됩니다. (Contributed by Steve Barnes in bpo-30291 [https://bugs.python.org/issue?@action=redirect&bpo=30291].)

런처는 py -0 처럼 실행시킬 수 있는데, 설치되어있는 파이썬의 목록을 만들고, 기본값을 애스터리스크로 표시합니다. py -0p 를 실행하면 경로가 포함됩니다. py가 일치할 수 없는 버전 지정자로 실행되면 사용 가능한 지정자의 짧은 양식 목록도 인쇄됩니다. (Contributed by Steve Barnes in bpo-30362 [https://bugs.python.org/issue?@action=redirect&bpo=30362].)

파이썬 3.7로 이식하기

이 섹션에서는 여러분의 코드 수정을 요구하는 앞서 설명한 변경 사항과 버그 수정을 나열합니다.

파이썬 동작의 변경

async와 await 이름은 이제 예약 키워드입니다. 이 이름을 식별자로 사용하는 코드는 이제 SyntaxError 를 발생시킵니다. (Contributed by Jelle Zijlstra in bpo-30406 [https://bugs.python.org/issue?@action=redirect&bpo=30406].)

PEP 479 [https://www.python.org/dev/peps/pep-0479] 는 파이썬 3.7의 모든 코드에서 활성화되었습니다. 즉 코루틴과 제너레이터에서 직접 또는 간접적으로 발생하는 StopIteration 예외는 RuntimeError 예외로 변환됩니다. (Contributed by Yury Selivanov in bpo-32670 [https://bugs.python.org/issue?@action=redirect&bpo=32670].)

object.__aiter__() 메서드는 더는 비동기로 선언될 수 없습니다. (Contributed by Yury Selivanov in bpo-31709 [https://bugs.python.org/issue?@action=redirect&bpo=31709].)

못 보고 넘기는 바람에, 이전 파이썬 버전에서 다음 문법이 받아들여 지는 잘못이 있었습니다:

f(1 for x in [1],)

class C(1 for x in [1]):
    pass

파이썬 3.7은 이제 올바르게 SyntaxError 를 일으킵니다. 제너레이터 표현식은 항상 괄호 안에 바로 들어가 있어야 하며 양쪽에 쉼표를 넣을 수 없고 중복된 괄호는 오직 호출 시에만 생략 할 수 있습니다. (Contributed by Serhiy Storchaka in bpo-32012 [https://bugs.python.org/issue?@action=redirect&bpo=32012] and bpo-32023 [https://bugs.python.org/issue?@action=redirect&bpo=32023].)

-m 스위치를 사용할 때, 이제 빈 문자열 대신에 초기 작업 디렉터리가 sys.path 에 추가됩니다 (빈 문자열은 각 임포트 시점의 작업 디렉터리가 동적으로 적용되게 만듭니다). 빈 문자열을 검사하는 프로그램이나 이전 동작에 의존하는 프로그램은 그에 따라 업데이트해야 합니다 (예를 들어, 왜 코드가 빈 문자열을 검사했는지에 따라 os.getcwd() 또는 os.path.dirname(__main__.__file__) 도 검사해서).

파이썬 API의 변경

socketserver.ThreadingMixIn.server_close() 는 이제 모든 데몬이 아닌 스레드가 완료될 때까지 대기합니다. 3.7 이전의 동작을 얻으려면 새로운 socketserver.ThreadingMixIn.block_on_close 클래스 어트리뷰트를 False 로 설정하십시오. (Contributed by Victor Stinner in bpo-31233 [https://bugs.python.org/issue?@action=redirect&bpo=31233] and bpo-33540 [https://bugs.python.org/issue?@action=redirect&bpo=33540].)

socketserver.ForkingMixIn.server_close() 는 이제 모든 자식 프로세스가 완료될 때까지 대기합니다. 3.7 이전의 동작을 얻으려면 새로운 socketserver.ForkingMixIn.block_on_close 클래스 어트리뷰트를 False 로 설정하십시오. (Contributed by Victor Stinner in bpo-31151 [https://bugs.python.org/issue?@action=redirect&bpo=31151] and bpo-33540 [https://bugs.python.org/issue?@action=redirect&bpo=33540].)

locale.localeconv() 함수는 이제 일시적으로 LC_CTYPE 로케일을 LC_NUMERIC 의 값으로 설정하는 때도 있습니다. (Contributed by Victor Stinner in bpo-31900 [https://bugs.python.org/issue?@action=redirect&bpo=31900].)

pkgutil.walk_packages() 는 path 가 문자열이면 ValueError 를 발생시킵니다. 이전에는 빈 리스트가 반환되었습니다. (Contributed by Sanyam Khurana in bpo-24744 [https://bugs.python.org/issue?@action=redirect&bpo=24744].)

string.Formatter.format() 의 포맷 문자열 인자는 이제 위치-전용 입니다. 키워드 인자로 전달하는 것은 파이썬 3.5에서 폐지되었습니다. (Contributed by Serhiy Storchaka in bpo-29193 [https://bugs.python.org/issue?@action=redirect&bpo=29193].)

클래스 http.cookies.Morsel 의 어트리뷰트 key, value 및 coded_value 는 이제 읽기 전용입니다. 그들에게 대입하는 것은 파이썬 3.5에서 폐지되었습니다. 그것들을 설정하려면 set() 메서드를 사용하십시오. (Contributed by Serhiy Storchaka in bpo-29192 [https://bugs.python.org/issue?@action=redirect&bpo=29192].)

os.makedirs() 의 mode 인자는 더는 새로 생성된 중간 수준 디렉터리의 파일 사용 권한 비트에 영향을 미치지 않습니다. 파일 사용 권한 비트를 설정하기 위해서 makedirs() 를 호출하기 전에 umask를 설정할 수 있습니다. (Contributed by Serhiy Storchaka in bpo-19930 [https://bugs.python.org/issue?@action=redirect&bpo=19930].)

struct.Struct.format 형은 이제 bytes 가 아니라 str 입니다. (Contributed by Victor Stinner in bpo-21071 [https://bugs.python.org/issue?@action=redirect&bpo=21071].)

parse_multipart() 는 이제 encoding 및 errors 인자를 받아들이고 FieldStorage 과 같은 결과를 반환합니다: 파일이 아닌 필드의 경우 키와 연관된 값은 바이트열이 아니라 문자열의 리스트입니다. (Contributed by Pierre Quentel in bpo-29979 [https://bugs.python.org/issue?@action=redirect&bpo=29979].)

socket 의 내부 변경으로 인해, 이번 버전의 파이썬에서 socket.share 로 만들어진 소켓에 socket.fromshare() 를 호출하는 것은 지원되지 않습니다.

BaseException 의 repr 은 후행 쉼표를 포함하지 않도록 변경되었습니다. 대부분의 예외는 이 변경의 영향을 받습니다. (Contributed by Serhiy Storchaka in bpo-30399 [https://bugs.python.org/issue?@action=redirect&bpo=30399].)

datetime.timedelta 의 repr 은 키워드 인자를 출력에 포함하도록 변경되었습니다. (Contributed by Utkarsh Upadhyay in bpo-30302 [https://bugs.python.org/issue?@action=redirect&bpo=30302].)

shutil.rmtree() 는 이제 os.scandir() 함수를 사용하여 구현되었으므로, 사용자 지정 처리기 onerror 는 이제 디렉터리의 목록을 얻는 데 실패하면 첫 번째 인자가 os.listdir 대신 os.scandir 로 호출됩니다.

유니코드 기술 표준 #18 [https://unicode.org/reports/tr18/] 과같이 정규 표현식에서 중첩 집합 및 집합 연산에 대한 지원이 향후 추가될 수 있습니다. 그러면 문법이 변경됩니다. 미래의 변화를 촉진하기 위해 당분간 모호한 경우에 FutureWarning 를 일으킬 것입니다. 이 경우는 리터럴 '[' 로 시작하거나 리터럴 문자 '--', '&&', '~~' 및 '||' 을 포함하는 집합을 포함합니다. 경고를 피하려면 백 슬래시로 이스케이프 처리하십시오. (Contributed by Serhiy Storchaka in bpo-30349 [https://bugs.python.org/issue?@action=redirect&bpo=30349].)

빈 문자열과 일치 할 수 있는 정규식 으로 문자열을 나눈 결과가 변경되었습니다. 예를 들어, r'\s*' 로 나누면, 이전처럼 공백 문자뿐만 아니라, 공백 문자가 아닌 문자의 앞과 문자열 끝 바로 직전의 빈 문자열로도 나눕니다. 패턴을 r'\s+' 로 변경하면 이전의 동작을 복원 할 수 있습니다. 파이썬 3.5부터 그러한 패턴에 대해 FutureWarning 을 만들었습니다.

빈 문자열과 비어 있지 않은 문자열 모두와 일치하는 패턴의 경우, 모든 일치를 검색한 결과가 다른 경우에도 변경될 수 있습니다. 예를 들어, 문자열 'a\n\n' 에서, 패턴 r'(?m)^\s*?$' 는 위치 2와 3의 빈 문자열을 일치시킬 뿐만 아니라, 위치 2–3의 문자열 '\n' 도 일치시킵니다. 빈 줄만 일치시키려면, 패턴을 r'(?m)^[^\S\n]*$' 으로 다시 써야 합니다.

re.sub()는 이제 이전의 비어 있지 않은 일치에 인접한 빈 일치를 치환합니다. 예를 들어 re.sub('x*', '-', 'abxd') 는 이제 '-a-b-d-' 대신에 '-a-b--d-' 를 돌려줍니다 (‘b’와 ‘d’ 사이의 첫 번째 마이너스는 ‘x’를 치환하고 두 번째 마이너스는 ‘x’와 ‘d’ 사이의 빈 문자열을 치환합니다).

(Contributed by Serhiy Storchaka in bpo-25054 [https://bugs.python.org/issue?@action=redirect&bpo=25054] and bpo-32308 [https://bugs.python.org/issue?@action=redirect&bpo=32308].)

변경 re.escape() 가 ASCII 문자, 숫자 및 '_' 이외의 모든 문자를 이스케이프 하는 대신 정규식 특수 문자만 이스케이프 하도록 변경합니다. (Contributed by Serhiy Storchaka in bpo-29995 [https://bugs.python.org/issue?@action=redirect&bpo=29995].)

tracemalloc.Traceback 프레임은 이제 가장 오래된 것부터 가장 최근의 것 순으로 정렬되어, traceback 과 더 일관성 있게 만듭니다. (Contributed by Jesse Bakker in bpo-32121 [https://bugs.python.org/issue?@action=redirect&bpo=32121].)

socket.SOCK_NONBLOCK 또는 socket.SOCK_CLOEXEC 비트 플래그를 지원하는 OS에서, socket.type 에 이것들을 더는 적용하지 않습니다. 따라서 if sock.type == socket.SOCK_STREAM 과 같은 검사는 모든 플랫폼에서 예상대로 작동합니다. (Contributed by Yury Selivanov in bpo-32331 [https://bugs.python.org/issue?@action=redirect&bpo=32331].)

윈도우에서 표준 핸들을 리디렉션 할 때 subprocess.Popen 의 close_fds 인자의 기본값이 False 에서 True 로 변경되었습니다. 이전에 표준 입출력 리디렉션으로 subprocess.Popen 을 사용할 때 상속된 핸들에 의존했다면, 이전 동작을 유지하기 위해서 close_fds=False 를 넘기거나 STARTUPINFO.lpAttributeList 를 사용해야 합니다.

importlib.machinery.PathFinder.invalidate_caches() – 묵시적으로 importlib.invalidate_caches() 에 영향을 줍니다 – 는 이제 sys.path_importer_cache 에서 None 으로 설정된 엔트리를 삭제합니다. (Contributed by Brett Cannon in bpo-33169 [https://bugs.python.org/issue?@action=redirect&bpo=33169].)

asyncio 에서, loop.sock_recv(), loop.sock_sendall(), loop.sock_accept(), loop.getaddrinfo(), loop.getnameinfo() 는 문서와 일치하도록 적절한 코루틴 메서드로 변경되었습니다. 이전에는, 이 메서드는 asyncio.Future 인스턴스를 반환했습니다. (Contributed by Yury Selivanov in bpo-32327 [https://bugs.python.org/issue?@action=redirect&bpo=32327].)

asyncio.Server.sockets 는 이제 내부 서버 소켓 리스트를 직접 돌려주는 대신 사본을 반환합니다. (Contributed by Yury Selivanov in bpo-32662 [https://bugs.python.org/issue?@action=redirect&bpo=32662].)

Struct.format 는 bytes 인스턴스 대신에 str 인스턴스가 되었습니다. (Contributed by Victor Stinner in bpo-21071 [https://bugs.python.org/issue?@action=redirect&bpo=21071].)

argparse subparsers can now be made mandatory by passing required=True to ArgumentParser.add_subparsers(). (Contributed by Anthony Sottile in bpo-26510 [https://bugs.python.org/issue?@action=redirect&bpo=26510].)

ast.literal_eval() 이 이제 더 엄격해졌습니다. 임의 숫자를 더하거나 빼는 것이 더는 허용되지 않습니다. (Contributed by Serhiy Storchaka in bpo-31778 [https://bugs.python.org/issue?@action=redirect&bpo=31778].)

Calendar.itermonthdates 는 이제 날짜가 0001-01-01 에서 9999-12-31 범위를 벗어나면 일관되게 예외를 일으킵니다. 이러한 예외를 허용할 수 없는 응용 프로그램을 지원하기 위해 새로운 Calendar.itermonthdays3 와 Calendar.itermonthdays4 를 사용할 수 있습니다. 새로운 메서드는 튜플을 반환하고 datetime.date 에 의해 지원되는 범위에 제한받지 않습니다. (Contributed by Alexander Belopolsky in bpo-28292 [https://bugs.python.org/issue?@action=redirect&bpo=28292].)

collections.ChainMap 은 이제 하부 매핑의 순서를 보존합니다. (Contributed by Raymond Hettinger in bpo-32792 [https://bugs.python.org/issue?@action=redirect&bpo=32792].)

concurrent.futures.ThreadPoolExecutor 와 concurrent.futures.ProcessPoolExecutor 의 submit() 메서드는 인터프리터가 종료하는 동안 호출되면 RuntimeError 를 발생시킵니다. (Contributed by Mark Nemec in bpo-33097 [https://bugs.python.org/issue?@action=redirect&bpo=33097].)

configparser.ConfigParser 생성자는 read_dict() 를 사용하여 기본값을 처리해서, 그 동작을 파서의 나머지와 일관되게 합니다. 이제 기본 딕셔너리의 문자열이 아닌 키와 값은 묵시적으로 문자열로 변환됩니다. (Contributed by James Tocknell in bpo-23835 [https://bugs.python.org/issue?@action=redirect&bpo=23835].)

문서로 만들어지지 않은 여러 가지 내부 임포트가 제거되었습니다. 한 가지 예는 os.errno를 더는 사용할 수 없다는 것입니다; 대신 import errno를 직접 사용하십시오. 이러한 문서로 만들어지지 않은 내부 임포트는, 마이크로 버전 배포에서도, 언제든지 예고 없이 삭제될 수 있음에 유의하십시오.

C API의 변경

함수 PySlice_GetIndicesEx() 는 크기 조절이 가능한 시퀀스에 대해 안전하지 않은 것으로 간주합니다. 슬라이스 인덱스가 int 의 인스턴스가 아니라 __index__() 메서드를 구현하는 객체인 경우, 시퀀스는 길이를 PySlice_GetIndicesEx() 에 전달한 후 크기를 조정할 수 있습니다. 이로 인해 시퀀스의 길이를 벗어나는 인덱스가 반환될 수 있습니다. 가능한 문제를 피하려면 PySlice_Unpack()과 PySlice_AdjustIndices() 라는 새로운 함수를 사용하십시오. (Contributed by Serhiy Storchaka in bpo-27867 [https://bugs.python.org/issue?@action=redirect&bpo=27867].)

CPython 바이트 코드 변경

두 개의 새로운 옵코드가 있습니다: LOAD_METHOD와 CALL_METHOD. (Contributed by Yury Selivanov and INADA Naoki in bpo-26110 [https://bugs.python.org/issue?@action=redirect&bpo=26110].)

STORE_ANNOTATION 옵코드가 삭제되었습니다. (Contributed by Mark Shannon in bpo-32550 [https://bugs.python.org/issue?@action=redirect&bpo=32550].)

윈도우 전용 변경

sys.path 를 재정의하는데 사용되는 파일은 이제 'sys.path' 대신에 <python-executable>._pth 라고 불립니다. 자세한 정보는 Finding modules 를 보십시오. (Contributed by Steve Dower in bpo-28137 [https://bugs.python.org/issue?@action=redirect&bpo=28137].)

기타 CPython 구현 변경

공개된 CPython 실행시간 초기화 API에 가해질 잠재적인 미래의 변경을 준비하기 위해 (초기의, 하지만 약간 낡은 초안은 PEP 432 [https://www.python.org/dev/peps/pep-0432]를 보십시오), CPython의 내부 시작 및 구성 관리 로직이 상당히 리팩토링 되었습니다. 이러한 업데이트는 내장형 응용 프로그램과 일반 CPython CLI의 사용자 모두에게 완전히 투명하도록 의도했지만, 리팩토링 변경이 인터프리터 시작 시 다양한 작업의 내부 순서를 변경하므로 내장형 응용 프로그램과 CPython 자체에서 잠재 결함을 드러낼 수 있으므로 여기에서 언급합니다. (처음에는 Nick Coghlan과 Eric Snow가 bpo-22257 [https://bugs.python.org/issue?@action=redirect&bpo=22257] 의 일부로 이바지했고, Nick, Eric, Victor Stinner가 여러 이슈를 통해 추가로 업데이트했습니다). 영향을 받는 일부 알려진 세부 정보는 이렇습니다:

PySys_AddWarnOptionUnicode() 는 Py_Initialize를 호출하기 전에 유니코드 객체를 생성해야 하는 요구사항 때문에 현재 내장형 응용 프로그램에서는 사용할 수 없습니다. 대신에 PySys_AddWarnOption() 을 사용하십시오.

PySys_AddWarnOption()으로 내장형 응용 프로그램이 추가한 경고 필터는 이제 인터프리터가 설정한 기본 필터보다 더 일관되게 우선해야 합니다.

기본 경고 필터가 구성되는 방식의 변경으로 인해, Py_BytesWarningFlag 를 1보다 큰 값으로 설정하는 것이 더는 BytesWarning 메시지를 내보내면서 동시에 예외로 변환되도록 하기에 충분하지 못합니다. 대신, 플래그를 설정해야 하고 (경고가 처음에 발생하도록), 예외로 변환하기 위해 명시적으로 error::BytesWarning 경고 필터를 추가해야 합니다.

컴파일러가 독스트링을 처리하는 방식의 변화 때문에, 독스트링만으로 구성된 함수 바디의 묵시적인 return None 은, 이제 함수의 헤더 행이 아니라 독스트링과 같은 줄에 등장하는 것으로 표시됩니다.

현재 예외 상태가 프레임 객체에서 코루틴으로 옮겨졌습니다. 이는 인터프리터를 간소화하고 제너레이터에 들어가거나 빠져나갈 때 예외 상태를 스와프함으로써 발생하는 모호한 두 가지 버그를 수정했습니다. (Contributed by Mark Shannon in bpo-25612 [https://bugs.python.org/issue?@action=redirect&bpo=25612].)

파이썬 3.7.1의 주목할만한 변경 사항

3.7.1부터, Py_Initialize()는 이제 Py_Main()과 같은 환경 설정을 일관되게 읽고 존중합니다 (이전 파이썬 버전에서는, 환경 변수 중 잘 정의되지 않은 부분 집합을 존중했지만 파이썬 3.7.0에서는 bpo-34247 [https://bugs.python.org/issue?@action=redirect&bpo=34247]로 인해 아무것도 읽지 않았습니다). 이 동작을 원하지 않으면, Py_Initialize()를 호출하기 전에 Py_IgnoreEnvironmentFlag를 1로 설정하십시오.

3.7.1에서, 컨텍스트 변수를 위한 C API는 PyObject 포인터를 사용하도록 변경되었습니다. bpo-34762 [https://bugs.python.org/issue?@action=redirect&bpo=34762]를 참조하세요.

xml.dom.minidom 및 xml.sax 모듈은 기본적으로 더는 외부 엔티티를 처리하지 않습니다. bpo-17239 [https://bugs.python.org/issue?@action=redirect&bpo=17239]를 참조하세요.

3.7.1에서, tokenize 모듈은 끝에 줄 바꿈이 없는 입력이 제공될 때 묵시적으로 NEWLINE 토큰을 산출합니다. 이 동작은 이제 C 토크나이저가 내부적으로 수행하는 것과 일치합니다. (Contributed by Ammar Askar in bpo-33899 [https://bugs.python.org/issue?@action=redirect&bpo=33899].)

파이썬 3.7.2의 주목할만한 변경 사항

3.7.2에서, 윈도우에서 venv는 더는 원본 바이너리를 복사하지 않고, 대신 python.exe 와 pythonw.exe라는 리디렉터 스크립트를 만듭니다. 이렇게 하면 각 파이썬 업데이트마다 모든 가상 환경을 업그레이드하거나 다시 만들어야 하는 오랜 문제를 해결할 수 있습니다. 그러나, 이 배포에서는 새 스크립트를 얻기 위해 가상 환경을 다시 만들어야 함에 유의하세요.

Notable changes in Python 3.7.6

Due to significant security concerns, the reuse_address parameter of asyncio.loop.create_datagram_endpoint() is no longer supported. This is because of the behavior of the socket option SO_REUSEADDR in UDP. For more details, see the documentation for loop.create_datagram_endpoint(). (Contributed by Kyle Stanley, Antoine Pitrou, and Yury Selivanov in bpo-37228 [https://bugs.python.org/issue?@action=redirect&bpo=37228].)

Notable changes in Python 3.7.10

Earlier Python versions allowed using both ; and & as query parameter separators in urllib.parse.parse_qs() and urllib.parse.parse_qsl(). Due to security concerns, and to conform with newer W3C recommendations, this has been changed to allow only a single separator key, with & as the default. This change also affects cgi.parse() and cgi.parse_multipart() as they use the affected functions internally. For more details, please see their respective documentation. (Contributed by Adam Goldschmidt, Senthil Kumaran and Ken Jin in bpo-42967 [https://bugs.python.org/issue?@action=redirect&bpo=42967].)

Notable changes in Python 3.7.11

A security fix alters the ftplib.FTP behavior to not trust the IPv4 address sent from the remote server when setting up a passive data channel. We reuse the ftp server IP address instead. For unusual code requiring the old behavior, set a trust_server_pasv_ipv4_address attribute on your FTP instance to True. (See bpo-43285 [https://bugs.python.org/issue?@action=redirect&bpo=43285])

The presence of newline or tab characters in parts of a URL allows for some forms of attacks. Following the WHATWG specification that updates RFC 3986, ASCII newline \n, \r and tab \t characters are stripped from the URL by the parser urllib.parse() preventing such attacks. The removal characters are controlled by a new module level variable urllib.parse._UNSAFE_URL_BYTES_TO_REMOVE. (See bpo-43882 [https://bugs.python.org/issue?@action=redirect&bpo=43882])

Notable security feature in 3.7.14

Converting between int and str in bases other than 2 (binary), 4, 8 (octal), 16 (hexadecimal), or 32 such as base 10 (decimal) now raises a ValueError if the number of digits in string form is above a limit to avoid potential denial of service attacks due to the algorithmic complexity. This is a mitigation for CVE-2020-10735 [https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2020-10735]. This limit can be configured or disabled by environment variable, command line flag, or sys APIs. See the integer string conversion length limitation documentation. The default limit is 4300 digits in string form.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬의 새로운 기능 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬의 새로운 기능 »

|

What’s New In Python 3.6

Editors

Elvis Pranskevichus <elvis@magic.io>, Yury Selivanov <yury@magic.io>

This article explains the new features in Python 3.6, compared to 3.5. Python 3.6 was released on December 23, 2016.  See the changelog [https://docs.python.org/3.6/whatsnew/changelog.html] for a full list of changes.

더 보기

PEP 494 [https://www.python.org/dev/peps/pep-0494] - Python 3.6 Release Schedule

Summary – Release highlights

New syntax features:

PEP 498, formatted string literals.

PEP 515, underscores in numeric literals.

PEP 526, syntax for variable annotations.

PEP 525, asynchronous generators.

PEP 530: asynchronous comprehensions.

New library modules:

secrets: PEP 506 – Adding A Secrets Module To The Standard Library.

CPython implementation improvements:

The dict type has been reimplemented to use a more compact representation based on a proposal by Raymond Hettinger [https://mail.python.org/pipermail/python-dev/2012-December/123028.html] and similar to the PyPy dict implementation [https://morepypy.blogspot.com/2015/01/faster-more-memory-efficient-and-more.html]. This resulted in dictionaries using 20% to 25% less memory when compared to Python 3.5.

Customization of class creation has been simplified with the new protocol.

The class attribute definition order is now preserved.

The order of elements in **kwargs now corresponds to the order in which keyword arguments were passed to the function.

DTrace and SystemTap probing support has been added.

The new PYTHONMALLOC environment variable can now be used to debug the interpreter memory allocation and access errors.

Significant improvements in the standard library:

The asyncio module has received new features, significant usability and performance improvements, and a fair amount of bug fixes. Starting with Python 3.6 the asyncio module is no longer provisional and its API is considered stable.

A new file system path protocol has been implemented to support path-like objects. All standard library functions operating on paths have been updated to work with the new protocol.

The datetime module has gained support for Local Time Disambiguation.

The typing module received a number of improvements.

The tracemalloc module has been significantly reworked and is now used to provide better output for ResourceWarning as well as provide better diagnostics for memory allocation errors. See the PYTHONMALLOC section for more information.

Security improvements:

The new secrets module has been added to simplify the generation of cryptographically strong pseudo-random numbers suitable for managing secrets such as account authentication, tokens, and similar.

On Linux, os.urandom() now blocks until the system urandom entropy pool is initialized to increase the security. See the PEP 524 [https://www.python.org/dev/peps/pep-0524] for the rationale.

The hashlib and ssl modules now support OpenSSL 1.1.0.

The default settings and feature set of the ssl module have been improved.

The hashlib module received support for the BLAKE2, SHA-3 and SHAKE hash algorithms and the scrypt() key derivation function.

Windows improvements:

PEP 528 and PEP 529, Windows filesystem and console encoding changed to UTF-8.

The py.exe launcher, when used interactively, no longer prefers Python 2 over Python 3 when the user doesn’t specify a version (via command line arguments or a config file). Handling of shebang lines remains unchanged - “python” refers to Python 2 in that case.

python.exe and pythonw.exe have been marked as long-path aware, which means that the 260 character path limit may no longer apply. See removing the MAX_PATH limitation for details.

A ._pth file can be added to force isolated mode and fully specify all search paths to avoid registry and environment lookup. See the documentation for more information.

A python36.zip file now works as a landmark to infer PYTHONHOME. See the documentation for more information.

New Features

PEP 498: Formatted string literals

PEP 498 [https://www.python.org/dev/peps/pep-0498] introduces a new kind of string literals: f-strings, or formatted string literals.

Formatted string literals are prefixed with 'f' and are similar to the format strings accepted by str.format(). They contain replacement fields surrounded by curly braces. The replacement fields are expressions, which are evaluated at run time, and then formatted using the format() protocol:

>>> name = "Fred"
>>> f"He said his name is {name}."
'He said his name is Fred.'
>>> width = 10
>>> precision = 4
>>> value = decimal.Decimal("12.34567")
>>> f"result: {value:{width}.{precision}}"  # nested fields
'result:      12.35'

더 보기

PEP 498 [https://www.python.org/dev/peps/pep-0498] – Literal String Interpolation.

PEP written and implemented by Eric V. Smith.

Feature documentation.

PEP 526: Syntax for variable annotations

PEP 484 [https://www.python.org/dev/peps/pep-0484] introduced the standard for type annotations of function parameters, a.k.a. type hints. This PEP adds syntax to Python for annotating the types of variables including class variables and instance variables:

primes: List[int] = []

captain: str  # Note: no initial value!

class Starship:
    stats: Dict[str, int] = {}

Just as for function annotations, the Python interpreter does not attach any particular meaning to variable annotations and only stores them in the __annotations__ attribute of a class or module.

In contrast to variable declarations in statically typed languages, the goal of annotation syntax is to provide an easy way to specify structured type metadata for third party tools and libraries via the abstract syntax tree and the __annotations__ attribute.

더 보기

PEP 526 [https://www.python.org/dev/peps/pep-0526] – Syntax for variable annotations.

PEP written by Ryan Gonzalez, Philip House, Ivan Levkivskyi, Lisa Roach, and Guido van Rossum. Implemented by Ivan Levkivskyi.

Tools that use or will use the new syntax: mypy [http://www.mypy-lang.org/], pytype [https://github.com/google/pytype], PyCharm, etc.

PEP 515: Underscores in Numeric Literals

PEP 515 [https://www.python.org/dev/peps/pep-0515] adds the ability to use underscores in numeric literals for improved readability. For example:

>>> 1_000_000_000_000_000
1000000000000000
>>> 0x_FF_FF_FF_FF
4294967295

Single underscores are allowed between digits and after any base specifier. Leading, trailing, or multiple underscores in a row are not allowed.

The string formatting language also now has support for the '_' option to signal the use of an underscore for a thousands separator for floating point presentation types and for integer presentation type 'd'. For integer presentation types 'b', 'o', 'x', and 'X', underscores will be inserted every 4 digits:

>>> '{:_}'.format(1000000)
'1_000_000'
>>> '{:_x}'.format(0xFFFFFFFF)
'ffff_ffff'

더 보기

PEP 515 [https://www.python.org/dev/peps/pep-0515] – Underscores in Numeric Literals

PEP written by Georg Brandl and Serhiy Storchaka.

PEP 525: Asynchronous Generators

PEP 492 [https://www.python.org/dev/peps/pep-0492] introduced support for native coroutines and async / await syntax to Python 3.5. A notable limitation of the Python 3.5 implementation is that it was not possible to use await and yield in the same function body. In Python 3.6 this restriction has been lifted, making it possible to define asynchronous generators:

async def ticker(delay, to):
    """Yield numbers from 0 to *to* every *delay* seconds."""
    for i in range(to):
        yield i
        await asyncio.sleep(delay)

The new syntax allows for faster and more concise code.

더 보기

PEP 525 [https://www.python.org/dev/peps/pep-0525] – Asynchronous Generators

PEP written and implemented by Yury Selivanov.

PEP 530: Asynchronous Comprehensions

PEP 530 [https://www.python.org/dev/peps/pep-0530] adds support for using async for in list, set, dict comprehensions and generator expressions:

result = [i async for i in aiter() if i % 2]

Additionally, await expressions are supported in all kinds of comprehensions:

result = [await fun() for fun in funcs if await condition()]

더 보기

PEP 530 [https://www.python.org/dev/peps/pep-0530] – Asynchronous Comprehensions

PEP written and implemented by Yury Selivanov.

PEP 487: Simpler customization of class creation

It is now possible to customize subclass creation without using a metaclass. The new __init_subclass__ classmethod will be called on the base class whenever a new subclass is created:

class PluginBase:
    subclasses = []

    def __init_subclass__(cls, **kwargs):
        super().__init_subclass__(**kwargs)
        cls.subclasses.append(cls)

class Plugin1(PluginBase):
    pass

class Plugin2(PluginBase):
    pass

In order to allow zero-argument super() calls to work correctly from __init_subclass__() implementations, custom metaclasses must ensure that the new __classcell__ namespace entry is propagated to type.__new__ (as described in 클래스 객체 만들기).

더 보기

PEP 487 [https://www.python.org/dev/peps/pep-0487] – Simpler customization of class creation

PEP written and implemented by Martin Teichmann.

Feature documentation

PEP 487: Descriptor Protocol Enhancements

PEP 487 [https://www.python.org/dev/peps/pep-0487] extends the descriptor protocol to include the new optional __set_name__() method. Whenever a new class is defined, the new method will be called on all descriptors included in the definition, providing them with a reference to the class being defined and the name given to the descriptor within the class namespace. In other words, instances of descriptors can now know the attribute name of the descriptor in the owner class:

class IntField:
    def __get__(self, instance, owner):
        return instance.__dict__[self.name]

    def __set__(self, instance, value):
        if not isinstance(value, int):
            raise ValueError(f'expecting integer in {self.name}')
        instance.__dict__[self.name] = value

    # this is the new initializer:
    def __set_name__(self, owner, name):
        self.name = name

class Model:
    int_field = IntField()

더 보기

PEP 487 [https://www.python.org/dev/peps/pep-0487] – Simpler customization of class creation

PEP written and implemented by Martin Teichmann.

Feature documentation

PEP 519: Adding a file system path protocol

File system paths have historically been represented as str or bytes objects. This has led to people who write code which operate on file system paths to assume that such objects are only one of those two types (an int representing a file descriptor does not count as that is not a file path). Unfortunately that assumption prevents alternative object representations of file system paths like pathlib from working with pre-existing code, including Python’s standard library.

To fix this situation, a new interface represented by os.PathLike has been defined. By implementing the __fspath__() method, an object signals that it represents a path. An object can then provide a low-level representation of a file system path as a str or bytes object. This means an object is considered path-like if it implements os.PathLike or is a str or bytes object which represents a file system path. Code can use os.fspath(), os.fsdecode(), or os.fsencode() to explicitly get a str and/or bytes representation of a path-like object.

The built-in open() function has been updated to accept os.PathLike objects, as have all relevant functions in the os and os.path modules, and most other functions and classes in the standard library. The os.DirEntry class and relevant classes in pathlib have also been updated to implement os.PathLike.

The hope is that updating the fundamental functions for operating on file system paths will lead to third-party code to implicitly support all path-like objects without any code changes, or at least very minimal ones (e.g. calling os.fspath() at the beginning of code before operating on a path-like object).

Here are some examples of how the new interface allows for pathlib.Path to be used more easily and transparently with pre-existing code:

>>> import pathlib
>>> with open(pathlib.Path("README")) as f:
...     contents = f.read()
...
>>> import os.path
>>> os.path.splitext(pathlib.Path("some_file.txt"))
('some_file', '.txt')
>>> os.path.join("/a/b", pathlib.Path("c"))
'/a/b/c'
>>> import os
>>> os.fspath(pathlib.Path("some_file.txt"))
'some_file.txt'

(Implemented by Brett Cannon, Ethan Furman, Dusty Phillips, and Jelle Zijlstra.)

더 보기

PEP 519 [https://www.python.org/dev/peps/pep-0519] – Adding a file system path protocol

PEP written by Brett Cannon and Koos Zevenhoven.

PEP 495: Local Time Disambiguation

In most world locations, there have been and will be times when local clocks are moved back. In those times, intervals are introduced in which local clocks show the same time twice in the same day. In these situations, the information displayed on a local clock (or stored in a Python datetime instance) is insufficient to identify a particular moment in time.

PEP 495 [https://www.python.org/dev/peps/pep-0495] adds the new fold attribute to instances of datetime.datetime and datetime.time classes to differentiate between two moments in time for which local times are the same:

>>> u0 = datetime(2016, 11, 6, 4, tzinfo=timezone.utc)
>>> for i in range(4):
...     u = u0 + i*HOUR
...     t = u.astimezone(Eastern)
...     print(u.time(), 'UTC =', t.time(), t.tzname(), t.fold)
...
04:00:00 UTC = 00:00:00 EDT 0
05:00:00 UTC = 01:00:00 EDT 0
06:00:00 UTC = 01:00:00 EST 1
07:00:00 UTC = 02:00:00 EST 0

The values of the fold attribute have the value 0 for all instances except those that represent the second (chronologically) moment in time in an ambiguous case.

더 보기

PEP 495 [https://www.python.org/dev/peps/pep-0495] – Local Time Disambiguation

PEP written by Alexander Belopolsky and Tim Peters, implementation by Alexander Belopolsky.

PEP 529: Change Windows filesystem encoding to UTF-8

Representing filesystem paths is best performed with str (Unicode) rather than bytes. However, there are some situations where using bytes is sufficient and correct.

Prior to Python 3.6, data loss could result when using bytes paths on Windows. With this change, using bytes to represent paths is now supported on Windows, provided those bytes are encoded with the encoding returned by sys.getfilesystemencoding(), which now defaults to 'utf-8'.

Applications that do not use str to represent paths should use os.fsencode() and os.fsdecode() to ensure their bytes are correctly encoded. To revert to the previous behaviour, set PYTHONLEGACYWINDOWSFSENCODING or call sys._enablelegacywindowsfsencoding().

See PEP 529 [https://www.python.org/dev/peps/pep-0529] for more information and discussion of code modifications that may be required.

PEP 528: Change Windows console encoding to UTF-8

The default console on Windows will now accept all Unicode characters and provide correctly read str objects to Python code. sys.stdin, sys.stdout and sys.stderr now default to utf-8 encoding.

This change only applies when using an interactive console, and not when redirecting files or pipes. To revert to the previous behaviour for interactive console use, set PYTHONLEGACYWINDOWSSTDIO.

더 보기

PEP 528 [https://www.python.org/dev/peps/pep-0528] – Change Windows console encoding to UTF-8

PEP written and implemented by Steve Dower.

PEP 520: Preserving Class Attribute Definition Order

Attributes in a class definition body have a natural ordering: the same order in which the names appear in the source. This order is now preserved in the new class’s __dict__ attribute.

Also, the effective default class execution namespace (returned from type.__prepare__()) is now an insertion-order-preserving mapping.

더 보기

PEP 520 [https://www.python.org/dev/peps/pep-0520] – Preserving Class Attribute Definition Order

PEP written and implemented by Eric Snow.

PEP 468: Preserving Keyword Argument Order

**kwargs in a function signature is now guaranteed to be an insertion-order-preserving mapping.

더 보기

PEP 468 [https://www.python.org/dev/peps/pep-0468] – Preserving Keyword Argument Order

PEP written and implemented by Eric Snow.

New dict implementation

The dict type now uses a “compact” representation based on a proposal by Raymond Hettinger [https://mail.python.org/pipermail/python-dev/2012-December/123028.html] which was first implemented by PyPy [https://morepypy.blogspot.com/2015/01/faster-more-memory-efficient-and-more.html]. The memory usage of the new dict() is between 20% and 25% smaller compared to Python 3.5.

The order-preserving aspect of this new implementation is considered an implementation detail and should not be relied upon (this may change in the future, but it is desired to have this new dict implementation in the language for a few releases before changing the language spec to mandate order-preserving semantics for all current and future Python implementations; this also helps preserve backwards-compatibility with older versions of the language where random iteration order is still in effect, e.g. Python 3.5).

(Contributed by INADA Naoki in bpo-27350 [https://bugs.python.org/issue?@action=redirect&bpo=27350]. Idea originally suggested by Raymond Hettinger [https://mail.python.org/pipermail/python-dev/2012-December/123028.html].)

PEP 523: Adding a frame evaluation API to CPython

While Python provides extensive support to customize how code executes, one place it has not done so is in the evaluation of frame objects. If you wanted some way to intercept frame evaluation in Python there really wasn’t any way without directly manipulating function pointers for defined functions.

PEP 523 [https://www.python.org/dev/peps/pep-0523] changes this by providing an API to make frame evaluation pluggable at the C level. This will allow for tools such as debuggers and JITs to intercept frame evaluation before the execution of Python code begins. This enables the use of alternative evaluation implementations for Python code, tracking frame evaluation, etc.

This API is not part of the limited C API and is marked as private to signal that usage of this API is expected to be limited and only applicable to very select, low-level use-cases. Semantics of the API will change with Python as necessary.

더 보기

PEP 523 [https://www.python.org/dev/peps/pep-0523] – Adding a frame evaluation API to CPython

PEP written by Brett Cannon and Dino Viehland.

PYTHONMALLOC environment variable

The new PYTHONMALLOC environment variable allows setting the Python memory allocators and installing debug hooks.

It is now possible to install debug hooks on Python memory allocators on Python compiled in release mode using PYTHONMALLOC=debug. Effects of debug hooks:

Newly allocated memory is filled with the byte 0xCB

Freed memory is filled with the byte 0xDB

Detect violations of the Python memory allocator API. For example, PyObject_Free() called on a memory block allocated by PyMem_Malloc().

Detect writes before the start of a buffer (buffer underflows)

Detect writes after the end of a buffer (buffer overflows)

Check that the GIL is held when allocator functions of PYMEM_DOMAIN_OBJ (ex: PyObject_Malloc()) and PYMEM_DOMAIN_MEM (ex: PyMem_Malloc()) domains are called.

Checking if the GIL is held is also a new feature of Python 3.6.

See the PyMem_SetupDebugHooks() function for debug hooks on Python memory allocators.

It is now also possible to force the usage of the malloc() allocator of the C library for all Python memory allocations using PYTHONMALLOC=malloc. This is helpful when using external memory debuggers like Valgrind on a Python compiled in release mode.

On error, the debug hooks on Python memory allocators now use the tracemalloc module to get the traceback where a memory block was allocated.

Example of fatal error on buffer overflow using python3.6 -X tracemalloc=5 (store 5 frames in traces):

Debug memory block at address p=0x7fbcd41666f8: API 'o'
    4 bytes originally requested
    The 7 pad bytes at p-7 are FORBIDDENBYTE, as expected.
    The 8 pad bytes at tail=0x7fbcd41666fc are not all FORBIDDENBYTE (0xfb):
        at tail+0: 0x02 *** OUCH
        at tail+1: 0xfb
        at tail+2: 0xfb
        at tail+3: 0xfb
        at tail+4: 0xfb
        at tail+5: 0xfb
        at tail+6: 0xfb
        at tail+7: 0xfb
    The block was made by call #1233329 to debug malloc/realloc.
    Data at p: 1a 2b 30 00

Memory block allocated at (most recent call first):
  File "test/test_bytes.py", line 323
  File "unittest/case.py", line 600
  File "unittest/case.py", line 648
  File "unittest/suite.py", line 122
  File "unittest/suite.py", line 84

Fatal Python error: bad trailing pad byte

Current thread 0x00007fbcdbd32700 (most recent call first):
  File "test/test_bytes.py", line 323 in test_hex
  File "unittest/case.py", line 600 in run
  File "unittest/case.py", line 648 in __call__
  File "unittest/suite.py", line 122 in run
  File "unittest/suite.py", line 84 in __call__
  File "unittest/suite.py", line 122 in run
  File "unittest/suite.py", line 84 in __call__
  ...

(Contributed by Victor Stinner in bpo-26516 [https://bugs.python.org/issue?@action=redirect&bpo=26516] and bpo-26564 [https://bugs.python.org/issue?@action=redirect&bpo=26564].)

DTrace and SystemTap probing support

Python can now be built --with-dtrace which enables static markers for the following events in the interpreter:

function call/return

garbage collection started/finished

line of code executed.

This can be used to instrument running interpreters in production, without the need to recompile specific debug builds or providing application-specific profiling/debugging code.

More details in DTrace와 SystemTap으로 CPython 계측하기.

The current implementation is tested on Linux and macOS. Additional markers may be added in the future.

(Contributed by Łukasz Langa in bpo-21590 [https://bugs.python.org/issue?@action=redirect&bpo=21590], based on patches by Jesús Cea Avión, David Malcolm, and Nikhil Benesch.)

Other Language Changes

Some smaller changes made to the core Python language are:

A global or nonlocal statement must now textually appear before the first use of the affected name in the same scope. Previously this was a SyntaxWarning.

It is now possible to set a special method to None to indicate that the corresponding operation is not available. For example, if a class sets __iter__() to None, the class is not iterable. (Contributed by Andrew Barnert and Ivan Levkivskyi in bpo-25958 [https://bugs.python.org/issue?@action=redirect&bpo=25958].)

Long sequences of repeated traceback lines are now abbreviated as "[Previous line repeated {count} more times]" (see traceback for an example). (Contributed by Emanuel Barry in bpo-26823 [https://bugs.python.org/issue?@action=redirect&bpo=26823].)

Import now raises the new exception ModuleNotFoundError (subclass of ImportError) when it cannot find a module. Code that currently checks for ImportError (in try-except) will still work. (Contributed by Eric Snow in bpo-15767 [https://bugs.python.org/issue?@action=redirect&bpo=15767].)

Class methods relying on zero-argument super() will now work correctly when called from metaclass methods during class creation. (Contributed by Martin Teichmann in bpo-23722 [https://bugs.python.org/issue?@action=redirect&bpo=23722].)

New Modules

secrets

The main purpose of the new secrets module is to provide an obvious way to reliably generate cryptographically strong pseudo-random values suitable for managing secrets, such as account authentication, tokens, and similar.

경고

Note that the pseudo-random generators in the random module should NOT be used for security purposes. Use secrets on Python 3.6+ and os.urandom() on Python 3.5 and earlier.

더 보기

PEP 506 [https://www.python.org/dev/peps/pep-0506] – Adding A Secrets Module To The Standard Library

PEP written and implemented by Steven D’Aprano.

Improved Modules

array

Exhausted iterators of array.array will now stay exhausted even if the iterated array is extended. This is consistent with the behavior of other mutable sequences.

Contributed by Serhiy Storchaka in bpo-26492 [https://bugs.python.org/issue?@action=redirect&bpo=26492].

ast

The new ast.Constant AST node has been added. It can be used by external AST optimizers for the purposes of constant folding.

Contributed by Victor Stinner in bpo-26146 [https://bugs.python.org/issue?@action=redirect&bpo=26146].

asyncio

Starting with Python 3.6 the asyncio module is no longer provisional and its API is considered stable.

Notable changes in the asyncio module since Python 3.5.0 (all backported to 3.5.x due to the provisional status):

The get_event_loop() function has been changed to always return the currently running loop when called from coroutines and callbacks. (Contributed by Yury Selivanov in bpo-28613 [https://bugs.python.org/issue?@action=redirect&bpo=28613].)

The ensure_future() function and all functions that use it, such as loop.run_until_complete(), now accept all kinds of awaitable objects. (Contributed by Yury Selivanov.)

New run_coroutine_threadsafe() function to submit coroutines to event loops from other threads. (Contributed by Vincent Michel.)

New Transport.is_closing() method to check if the transport is closing or closed. (Contributed by Yury Selivanov.)

The loop.create_server() method can now accept a list of hosts. (Contributed by Yann Sionneau.)

New loop.create_future() method to create Future objects. This allows alternative event loop implementations, such as uvloop [https://github.com/MagicStack/uvloop], to provide a faster asyncio.Future implementation. (Contributed by Yury Selivanov in bpo-27041 [https://bugs.python.org/issue?@action=redirect&bpo=27041].)

New loop.get_exception_handler() method to get the current exception handler. (Contributed by Yury Selivanov in bpo-27040 [https://bugs.python.org/issue?@action=redirect&bpo=27040].)

New StreamReader.readuntil() method to read data from the stream until a separator bytes sequence appears. (Contributed by Mark Korenberg.)

The performance of StreamReader.readexactly() has been improved. (Contributed by Mark Korenberg in bpo-28370 [https://bugs.python.org/issue?@action=redirect&bpo=28370].)

The loop.getaddrinfo() method is optimized to avoid calling the system getaddrinfo function if the address is already resolved. (Contributed by A. Jesse Jiryu Davis.)

The loop.stop() method has been changed to stop the loop immediately after the current iteration. Any new callbacks scheduled as a result of the last iteration will be discarded. (Contributed by Guido van Rossum in bpo-25593 [https://bugs.python.org/issue?@action=redirect&bpo=25593].)

Future.set_exception will now raise TypeError when passed an instance of the StopIteration exception. (Contributed by Chris Angelico in bpo-26221 [https://bugs.python.org/issue?@action=redirect&bpo=26221].)

New loop.connect_accepted_socket() method to be used by servers that accept connections outside of asyncio, but that use asyncio to handle them. (Contributed by Jim Fulton in bpo-27392 [https://bugs.python.org/issue?@action=redirect&bpo=27392].)

TCP_NODELAY flag is now set for all TCP transports by default. (Contributed by Yury Selivanov in bpo-27456 [https://bugs.python.org/issue?@action=redirect&bpo=27456].)

New loop.shutdown_asyncgens() to properly close pending asynchronous generators before closing the loop. (Contributed by Yury Selivanov in bpo-28003 [https://bugs.python.org/issue?@action=redirect&bpo=28003].)

Future and Task classes now have an optimized C implementation which makes asyncio code up to 30% faster. (Contributed by Yury Selivanov and INADA Naoki in bpo-26081 [https://bugs.python.org/issue?@action=redirect&bpo=26081] and bpo-28544 [https://bugs.python.org/issue?@action=redirect&bpo=28544].)

binascii

The b2a_base64() function now accepts an optional newline keyword argument to control whether the newline character is appended to the return value. (Contributed by Victor Stinner in bpo-25357 [https://bugs.python.org/issue?@action=redirect&bpo=25357].)

cmath

The new cmath.tau (τ) constant has been added. (Contributed by Lisa Roach in bpo-12345 [https://bugs.python.org/issue?@action=redirect&bpo=12345], see PEP 628 [https://www.python.org/dev/peps/pep-0628] for details.)

New constants: cmath.inf and cmath.nan to match math.inf and math.nan, and also cmath.infj and cmath.nanj to match the format used by complex repr. (Contributed by Mark Dickinson in bpo-23229 [https://bugs.python.org/issue?@action=redirect&bpo=23229].)

collections

The new Collection abstract base class has been added to represent sized iterable container classes. (Contributed by Ivan Levkivskyi, docs by Neil Girdhar in bpo-27598 [https://bugs.python.org/issue?@action=redirect&bpo=27598].)

The new Reversible abstract base class represents iterable classes that also provide the __reversed__() method. (Contributed by Ivan Levkivskyi in bpo-25987 [https://bugs.python.org/issue?@action=redirect&bpo=25987].)

The new AsyncGenerator abstract base class represents asynchronous generators. (Contributed by Yury Selivanov in bpo-28720 [https://bugs.python.org/issue?@action=redirect&bpo=28720].)

The namedtuple() function now accepts an optional keyword argument module, which, when specified, is used for the __module__ attribute of the returned named tuple class. (Contributed by Raymond Hettinger in bpo-17941 [https://bugs.python.org/issue?@action=redirect&bpo=17941].)

The verbose and rename arguments for namedtuple() are now keyword-only. (Contributed by Raymond Hettinger in bpo-25628 [https://bugs.python.org/issue?@action=redirect&bpo=25628].)

Recursive collections.deque instances can now be pickled. (Contributed by Serhiy Storchaka in bpo-26482 [https://bugs.python.org/issue?@action=redirect&bpo=26482].)

concurrent.futures

The ThreadPoolExecutor class constructor now accepts an optional thread_name_prefix argument to make it possible to customize the names of the threads created by the pool. (Contributed by Gregory P. Smith in bpo-27664 [https://bugs.python.org/issue?@action=redirect&bpo=27664].)

contextlib

The contextlib.AbstractContextManager class has been added to provide an abstract base class for context managers. It provides a sensible default implementation for __enter__() which returns self and leaves __exit__() an abstract method. A matching class has been added to the typing module as typing.ContextManager. (Contributed by Brett Cannon in bpo-25609 [https://bugs.python.org/issue?@action=redirect&bpo=25609].)

datetime

The datetime and time classes have the new fold attribute used to disambiguate local time when necessary. Many functions in the datetime have been updated to support local time disambiguation. See Local Time Disambiguation section for more information. (Contributed by Alexander Belopolsky in bpo-24773 [https://bugs.python.org/issue?@action=redirect&bpo=24773].)

The datetime.strftime() and date.strftime() methods now support ISO 8601 date directives %G, %u and %V. (Contributed by Ashley Anderson in bpo-12006 [https://bugs.python.org/issue?@action=redirect&bpo=12006].)

The datetime.isoformat() function now accepts an optional timespec argument that specifies the number of additional components of the time value to include. (Contributed by Alessandro Cucci and Alexander Belopolsky in bpo-19475 [https://bugs.python.org/issue?@action=redirect&bpo=19475].)

The datetime.combine() now accepts an optional tzinfo argument. (Contributed by Alexander Belopolsky in bpo-27661 [https://bugs.python.org/issue?@action=redirect&bpo=27661].)

decimal

New Decimal.as_integer_ratio() method that returns a pair (n, d) of integers that represent the given Decimal instance as a fraction, in lowest terms and with a positive denominator:

>>> Decimal('-3.14').as_integer_ratio()
(-157, 50)

(Contributed by Stefan Krah amd Mark Dickinson in bpo-25928 [https://bugs.python.org/issue?@action=redirect&bpo=25928].)

distutils

The default_format attribute has been removed from distutils.command.sdist.sdist and the formats attribute defaults to ['gztar']. Although not anticipated, any code relying on the presence of default_format may need to be adapted. See bpo-27819 [https://bugs.python.org/issue?@action=redirect&bpo=27819] for more details.

email

The new email API, enabled via the policy keyword to various constructors, is no longer provisional. The email documentation has been reorganized and rewritten to focus on the new API, while retaining the old documentation for the legacy API. (Contributed by R. David Murray in bpo-24277 [https://bugs.python.org/issue?@action=redirect&bpo=24277].)

The email.mime classes now all accept an optional policy keyword. (Contributed by Berker Peksag in bpo-27331 [https://bugs.python.org/issue?@action=redirect&bpo=27331].)

The DecodedGenerator now supports the policy keyword.

There is a new policy attribute, message_factory, that controls what class is used by default when the parser creates new message objects. For the email.policy.compat32 policy this is Message, for the new policies it is EmailMessage. (Contributed by R. David Murray in bpo-20476 [https://bugs.python.org/issue?@action=redirect&bpo=20476].)

encodings

On Windows, added the 'oem' encoding to use CP_OEMCP, and the 'ansi' alias for the existing 'mbcs' encoding, which uses the CP_ACP code page. (Contributed by Steve Dower in bpo-27959 [https://bugs.python.org/issue?@action=redirect&bpo=27959].)

enum

Two new enumeration base classes have been added to the enum module: Flag and IntFlags. Both are used to define constants that can be combined using the bitwise operators. (Contributed by Ethan Furman in bpo-23591 [https://bugs.python.org/issue?@action=redirect&bpo=23591].)

Many standard library modules have been updated to use the IntFlags class for their constants.

The new enum.auto value can be used to assign values to enum members automatically:

>>> from enum import Enum, auto
>>> class Color(Enum):
...     red = auto()
...     blue = auto()
...     green = auto()
...
>>> list(Color)
[<Color.red: 1>, <Color.blue: 2>, <Color.green: 3>]

faulthandler

On Windows, the faulthandler module now installs a handler for Windows exceptions: see faulthandler.enable(). (Contributed by Victor Stinner in bpo-23848 [https://bugs.python.org/issue?@action=redirect&bpo=23848].)

fileinput

hook_encoded() now supports the errors argument. (Contributed by Joseph Hackman in bpo-25788 [https://bugs.python.org/issue?@action=redirect&bpo=25788].)

hashlib

hashlib supports OpenSSL 1.1.0. The minimum recommend version is 1.0.2. (Contributed by Christian Heimes in bpo-26470 [https://bugs.python.org/issue?@action=redirect&bpo=26470].)

BLAKE2 hash functions were added to the module. blake2b() and blake2s() are always available and support the full feature set of BLAKE2. (Contributed by Christian Heimes in bpo-26798 [https://bugs.python.org/issue?@action=redirect&bpo=26798] based on code by Dmitry Chestnykh and Samuel Neves. Documentation written by Dmitry Chestnykh.)

The SHA-3 hash functions sha3_224(), sha3_256(), sha3_384(), sha3_512(), and SHAKE hash functions shake_128() and shake_256() were added. (Contributed by Christian Heimes in bpo-16113 [https://bugs.python.org/issue?@action=redirect&bpo=16113]. Keccak Code Package by Guido Bertoni, Joan Daemen, Michaël Peeters, Gilles Van Assche, and Ronny Van Keer.)

The password-based key derivation function scrypt() is now available with OpenSSL 1.1.0 and newer. (Contributed by Christian Heimes in bpo-27928 [https://bugs.python.org/issue?@action=redirect&bpo=27928].)

http.client

HTTPConnection.request() and endheaders() both now support chunked encoding request bodies. (Contributed by Demian Brecht and Rolf Krahl in bpo-12319 [https://bugs.python.org/issue?@action=redirect&bpo=12319].)

idlelib and IDLE

The idlelib package is being modernized and refactored to make IDLE look and work better and to make the code easier to understand, test, and improve. Part of making IDLE look better, especially on Linux and Mac, is using ttk widgets, mostly in the dialogs. As a result, IDLE no longer runs with tcl/tk 8.4. It now requires tcl/tk 8.5 or 8.6. We recommend running the latest release of either.

‘Modernizing’ includes renaming and consolidation of idlelib modules. The renaming of files with partial uppercase names is similar to the renaming of, for instance, Tkinter and TkFont to tkinter and tkinter.font in 3.0. As a result, imports of idlelib files that worked in 3.5 will usually not work in 3.6. At least a module name change will be needed (see idlelib/README.txt), sometimes more. (Name changes contributed by Al Swiegart and Terry Reedy in bpo-24225 [https://bugs.python.org/issue?@action=redirect&bpo=24225]. Most idlelib patches since have been and will be part of the process.)

In compensation, the eventual result with be that some idlelib classes will be easier to use, with better APIs and docstrings explaining them. Additional useful information will be added to idlelib when available.

New in 3.6.2:

Multiple fixes for autocompletion. (Contributed by Louie Lu in bpo-15786 [https://bugs.python.org/issue?@action=redirect&bpo=15786].)

New in 3.6.3:

Module Browser (on the File menu, formerly called Class Browser), now displays nested functions and classes in addition to top-level functions and classes. (Contributed by Guilherme Polo, Cheryl Sabella, and Terry Jan Reedy in bpo-1612262 [https://bugs.python.org/issue?@action=redirect&bpo=1612262].)

The IDLE features formerly implemented as extensions have been reimplemented as normal features. Their settings have been moved from the Extensions tab to other dialog tabs. (Contributed by Charles Wohlganger and Terry Jan Reedy in bpo-27099 [https://bugs.python.org/issue?@action=redirect&bpo=27099].)

The Settings dialog (Options, Configure IDLE) has been partly rewritten to improve both appearance and function. (Contributed by Cheryl Sabella and Terry Jan Reedy in multiple issues.)

New in 3.6.4:

The font sample now includes a selection of non-Latin characters so that users can better see the effect of selecting a particular font. (Contributed by Terry Jan Reedy in bpo-13802 [https://bugs.python.org/issue?@action=redirect&bpo=13802].) The sample can be edited to include other characters. (Contributed by Serhiy Storchaka in bpo-31860 [https://bugs.python.org/issue?@action=redirect&bpo=31860].)

New in 3.6.6:

Editor code context option revised. Box displays all context lines up to maxlines. Clicking on a context line jumps the editor to that line. Context colors for custom themes is added to Highlights tab of Settings dialog. (Contributed by Cheryl Sabella and Terry Jan Reedy in bpo-33642 [https://bugs.python.org/issue?@action=redirect&bpo=33642], bpo-33768 [https://bugs.python.org/issue?@action=redirect&bpo=33768], and bpo-33679 [https://bugs.python.org/issue?@action=redirect&bpo=33679].)

On Windows, a new API call tells Windows that tk scales for DPI. On Windows 8.1+ or 10, with DPI compatibility properties of the Python binary unchanged, and a monitor resolution greater than 96 DPI, this should make text and lines sharper. It should otherwise have no effect. (Contributed by Terry Jan Reedy in bpo-33656 [https://bugs.python.org/issue?@action=redirect&bpo=33656].)

New in 3.6.7:

Output over N lines (50 by default) is squeezed down to a button. N can be changed in the PyShell section of the General page of the Settings dialog. Fewer, but possibly extra long, lines can be squeezed by right clicking on the output. Squeezed output can be expanded in place by double-clicking the button or into the clipboard or a separate window by right-clicking the button. (Contributed by Tal Einat in bpo-1529353 [https://bugs.python.org/issue?@action=redirect&bpo=1529353].)

importlib

Import now raises the new exception ModuleNotFoundError (subclass of ImportError) when it cannot find a module. Code that current checks for ImportError (in try-except) will still work. (Contributed by Eric Snow in bpo-15767 [https://bugs.python.org/issue?@action=redirect&bpo=15767].)

importlib.util.LazyLoader now calls create_module() on the wrapped loader, removing the restriction that importlib.machinery.BuiltinImporter and importlib.machinery.ExtensionFileLoader couldn’t be used with importlib.util.LazyLoader.

importlib.util.cache_from_source(), importlib.util.source_from_cache(), and importlib.util.spec_from_file_location() now accept a path-like object.

inspect

The inspect.signature() function now reports the implicit .0 parameters generated by the compiler for comprehension and generator expression scopes as if they were positional-only parameters called implicit0. (Contributed by Jelle Zijlstra in bpo-19611 [https://bugs.python.org/issue?@action=redirect&bpo=19611].)

To reduce code churn when upgrading from Python 2.7 and the legacy inspect.getargspec() API, the previously documented deprecation of inspect.getfullargspec() has been reversed. While this function is convenient for single/source Python 2/3 code bases, the richer inspect.signature() interface remains the recommended approach for new code. (Contributed by Nick Coghlan in bpo-27172 [https://bugs.python.org/issue?@action=redirect&bpo=27172])

json

json.load() and json.loads() now support binary input. Encoded JSON should be represented using either UTF-8, UTF-16, or UTF-32. (Contributed by Serhiy Storchaka in bpo-17909 [https://bugs.python.org/issue?@action=redirect&bpo=17909].)

logging

The new WatchedFileHandler.reopenIfNeeded() method has been added to add the ability to check if the log file needs to be reopened. (Contributed by Marian Horban in bpo-24884 [https://bugs.python.org/issue?@action=redirect&bpo=24884].)

math

The tau (τ) constant has been added to the math and cmath modules. (Contributed by Lisa Roach in bpo-12345 [https://bugs.python.org/issue?@action=redirect&bpo=12345], see PEP 628 [https://www.python.org/dev/peps/pep-0628] for details.)

multiprocessing

Proxy Objects returned by multiprocessing.Manager() can now be nested. (Contributed by Davin Potts in bpo-6766 [https://bugs.python.org/issue?@action=redirect&bpo=6766].)

os

See the summary of PEP 519 for details on how the os and os.path modules now support path-like objects.

scandir() now supports bytes paths on Windows.

A new close() method allows explicitly closing a scandir() iterator. The scandir() iterator now supports the context manager protocol. If a scandir() iterator is neither exhausted nor explicitly closed a ResourceWarning will be emitted in its destructor. (Contributed by Serhiy Storchaka in bpo-25994 [https://bugs.python.org/issue?@action=redirect&bpo=25994].)

On Linux, os.urandom() now blocks until the system urandom entropy pool is initialized to increase the security. See the PEP 524 [https://www.python.org/dev/peps/pep-0524] for the rationale.

The Linux getrandom() syscall (get random bytes) is now exposed as the new os.getrandom() function. (Contributed by Victor Stinner, part of the PEP 524 [https://www.python.org/dev/peps/pep-0524])

pathlib

pathlib now supports path-like objects. (Contributed by Brett Cannon in bpo-27186 [https://bugs.python.org/issue?@action=redirect&bpo=27186].)

See the summary of PEP 519 for details.

pdb

The Pdb class constructor has a new optional readrc argument to control whether .pdbrc files should be read.

pickle

Objects that need __new__ called with keyword arguments can now be pickled using pickle protocols older than protocol version 4. Protocol version 4 already supports this case. (Contributed by Serhiy Storchaka in bpo-24164 [https://bugs.python.org/issue?@action=redirect&bpo=24164].)

pickletools

pickletools.dis() now outputs the implicit memo index for the MEMOIZE opcode. (Contributed by Serhiy Storchaka in bpo-25382 [https://bugs.python.org/issue?@action=redirect&bpo=25382].)

pydoc

The pydoc module has learned to respect the MANPAGER environment variable. (Contributed by Matthias Klose in bpo-8637 [https://bugs.python.org/issue?@action=redirect&bpo=8637].)

help() and pydoc can now list named tuple fields in the order they were defined rather than alphabetically. (Contributed by Raymond Hettinger in bpo-24879 [https://bugs.python.org/issue?@action=redirect&bpo=24879].)

random

The new choices() function returns a list of elements of specified size from the given population with optional weights. (Contributed by Raymond Hettinger in bpo-18844 [https://bugs.python.org/issue?@action=redirect&bpo=18844].)

re

Added support of modifier spans in regular expressions. Examples: '(?i:p)ython' matches 'python' and 'Python', but not 'PYTHON'; '(?i)g(?-i:v)r' matches 'GvR' and 'gvr', but not 'GVR'. (Contributed by Serhiy Storchaka in bpo-433028 [https://bugs.python.org/issue?@action=redirect&bpo=433028].)

Match object groups can be accessed by __getitem__, which is equivalent to group(). So mo['name'] is now equivalent to mo.group('name'). (Contributed by Eric Smith in bpo-24454 [https://bugs.python.org/issue?@action=redirect&bpo=24454].)

Match objects now support index-like objects as group indices. (Contributed by Jeroen Demeyer and Xiang Zhang in bpo-27177 [https://bugs.python.org/issue?@action=redirect&bpo=27177].)

readline

Added set_auto_history() to enable or disable automatic addition of input to the history list. (Contributed by Tyler Crompton in bpo-26870 [https://bugs.python.org/issue?@action=redirect&bpo=26870].)

rlcompleter

Private and special attribute names now are omitted unless the prefix starts with underscores. A space or a colon is added after some completed keywords. (Contributed by Serhiy Storchaka in bpo-25011 [https://bugs.python.org/issue?@action=redirect&bpo=25011] and bpo-25209 [https://bugs.python.org/issue?@action=redirect&bpo=25209].)

shlex

The shlex has much improved shell compatibility through the new punctuation_chars argument to control which characters are treated as punctuation. (Contributed by Vinay Sajip in bpo-1521950 [https://bugs.python.org/issue?@action=redirect&bpo=1521950].)

site

When specifying paths to add to sys.path in a .pth file, you may now specify file paths on top of directories (e.g. zip files). (Contributed by Wolfgang Langner in bpo-26587 [https://bugs.python.org/issue?@action=redirect&bpo=26587]).

sqlite3

sqlite3.Cursor.lastrowid now supports the REPLACE statement. (Contributed by Alex LordThorsen in bpo-16864 [https://bugs.python.org/issue?@action=redirect&bpo=16864].)

socket

The ioctl() function now supports the SIO_LOOPBACK_FAST_PATH control code. (Contributed by Daniel Stokes in bpo-26536 [https://bugs.python.org/issue?@action=redirect&bpo=26536].)

The getsockopt() constants SO_DOMAIN, SO_PROTOCOL, SO_PEERSEC, and SO_PASSSEC are now supported. (Contributed by Christian Heimes in bpo-26907 [https://bugs.python.org/issue?@action=redirect&bpo=26907].)

The setsockopt() now supports the setsockopt(level, optname, None, optlen: int) form. (Contributed by Christian Heimes in bpo-27744 [https://bugs.python.org/issue?@action=redirect&bpo=27744].)

The socket module now supports the address family AF_ALG to interface with Linux Kernel crypto API. ALG_*, SOL_ALG and sendmsg_afalg() were added. (Contributed by Christian Heimes in bpo-27744 [https://bugs.python.org/issue?@action=redirect&bpo=27744] with support from Victor Stinner.)

New Linux constants TCP_USER_TIMEOUT and TCP_CONGESTION were added. (Contributed by Omar Sandoval, issue:26273).

socketserver

Servers based on the socketserver module, including those defined in http.server, xmlrpc.server and wsgiref.simple_server, now support the context manager protocol. (Contributed by Aviv Palivoda in bpo-26404 [https://bugs.python.org/issue?@action=redirect&bpo=26404].)

The wfile attribute of StreamRequestHandler classes now implements the io.BufferedIOBase writable interface. In particular, calling write() is now guaranteed to send the data in full. (Contributed by Martin Panter in bpo-26721 [https://bugs.python.org/issue?@action=redirect&bpo=26721].)

ssl

ssl supports OpenSSL 1.1.0. The minimum recommend version is 1.0.2. (Contributed by Christian Heimes in bpo-26470 [https://bugs.python.org/issue?@action=redirect&bpo=26470].)

3DES has been removed from the default cipher suites and ChaCha20 Poly1305 cipher suites have been added. (Contributed by Christian Heimes in bpo-27850 [https://bugs.python.org/issue?@action=redirect&bpo=27850] and bpo-27766 [https://bugs.python.org/issue?@action=redirect&bpo=27766].)

SSLContext has better default configuration for options and ciphers. (Contributed by Christian Heimes in bpo-28043 [https://bugs.python.org/issue?@action=redirect&bpo=28043].)

SSL session can be copied from one client-side connection to another with the new SSLSession class. TLS session resumption can speed up the initial handshake, reduce latency and improve performance (Contributed by Christian Heimes in bpo-19500 [https://bugs.python.org/issue?@action=redirect&bpo=19500] based on a draft by Alex Warhawk.)

The new get_ciphers() method can be used to get a list of enabled ciphers in order of cipher priority.

All constants and flags have been converted to IntEnum and IntFlags. (Contributed by Christian Heimes in bpo-28025 [https://bugs.python.org/issue?@action=redirect&bpo=28025].)

Server and client-side specific TLS protocols for SSLContext were added. (Contributed by Christian Heimes in bpo-28085 [https://bugs.python.org/issue?@action=redirect&bpo=28085].)

statistics

A new harmonic_mean() function has been added. (Contributed by Steven D’Aprano in bpo-27181 [https://bugs.python.org/issue?@action=redirect&bpo=27181].)

struct

struct now supports IEEE 754 half-precision floats via the 'e' format specifier. (Contributed by Eli Stevens, Mark Dickinson in bpo-11734 [https://bugs.python.org/issue?@action=redirect&bpo=11734].)

subprocess

subprocess.Popen destructor now emits a ResourceWarning warning if the child process is still running. Use the context manager protocol (with proc: ...) or explicitly call the wait() method to read the exit status of the child process. (Contributed by Victor Stinner in bpo-26741 [https://bugs.python.org/issue?@action=redirect&bpo=26741].)

The subprocess.Popen constructor and all functions that pass arguments through to it now accept encoding and errors arguments. Specifying either of these will enable text mode for the stdin, stdout and stderr streams. (Contributed by Steve Dower in bpo-6135 [https://bugs.python.org/issue?@action=redirect&bpo=6135].)

sys

The new getfilesystemencodeerrors() function returns the name of the error mode used to convert between Unicode filenames and bytes filenames. (Contributed by Steve Dower in bpo-27781 [https://bugs.python.org/issue?@action=redirect&bpo=27781].)

On Windows the return value of the getwindowsversion() function now includes the platform_version field which contains the accurate major version, minor version and build number of the current operating system, rather than the version that is being emulated for the process (Contributed by Steve Dower in bpo-27932 [https://bugs.python.org/issue?@action=redirect&bpo=27932].)

telnetlib

Telnet is now a context manager (contributed by Stéphane Wirtel in bpo-25485 [https://bugs.python.org/issue?@action=redirect&bpo=25485]).

time

The struct_time attributes tm_gmtoff and tm_zone are now available on all platforms.

timeit

The new Timer.autorange() convenience method has been added to call Timer.timeit() repeatedly so that the total run time is greater or equal to 200 milliseconds. (Contributed by Steven D’Aprano in bpo-6422 [https://bugs.python.org/issue?@action=redirect&bpo=6422].)

timeit now warns when there is substantial (4x) variance between best and worst times. (Contributed by Serhiy Storchaka in bpo-23552 [https://bugs.python.org/issue?@action=redirect&bpo=23552].)

tkinter

Added methods trace_add(), trace_remove() and trace_info() in the tkinter.Variable class. They replace old methods trace_variable(), trace(), trace_vdelete() and trace_vinfo() that use obsolete Tcl commands and might not work in future versions of Tcl. (Contributed by Serhiy Storchaka in bpo-22115 [https://bugs.python.org/issue?@action=redirect&bpo=22115]).

traceback

Both the traceback module and the interpreter’s builtin exception display now abbreviate long sequences of repeated lines in tracebacks as shown in the following example:

>>> def f(): f()
...
>>> f()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in f
  File "<stdin>", line 1, in f
  File "<stdin>", line 1, in f
  [Previous line repeated 995 more times]
RecursionError: maximum recursion depth exceeded

(Contributed by Emanuel Barry in bpo-26823 [https://bugs.python.org/issue?@action=redirect&bpo=26823].)

tracemalloc

The tracemalloc module now supports tracing memory allocations in multiple different address spaces.

The new DomainFilter filter class has been added to filter block traces by their address space (domain).

(Contributed by Victor Stinner in bpo-26588 [https://bugs.python.org/issue?@action=redirect&bpo=26588].)

typing

Since the typing module is provisional, all changes introduced in Python 3.6 have also been backported to Python 3.5.x.

The typing module has a much improved support for generic type aliases. For example Dict[str, Tuple[S, T]] is now a valid type annotation. (Contributed by Guido van Rossum in Github #195 [https://github.com/python/typing/pull/195].)

The typing.ContextManager class has been added for representing contextlib.AbstractContextManager. (Contributed by Brett Cannon in bpo-25609 [https://bugs.python.org/issue?@action=redirect&bpo=25609].)

The typing.Collection class has been added for representing collections.abc.Collection. (Contributed by Ivan Levkivskyi in bpo-27598 [https://bugs.python.org/issue?@action=redirect&bpo=27598].)

The typing.ClassVar type construct has been added to mark class variables. As introduced in PEP 526 [https://www.python.org/dev/peps/pep-0526], a variable annotation wrapped in ClassVar indicates that a given attribute is intended to be used as a class variable and should not be set on instances of that class. (Contributed by Ivan Levkivskyi in Github #280 [https://github.com/python/typing/pull/280].)

A new TYPE_CHECKING constant that is assumed to be True by the static type checkers, but is False at runtime. (Contributed by Guido van Rossum in Github #230 [https://github.com/python/typing/issues/230].)

A new NewType() helper function has been added to create lightweight distinct types for annotations:

from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)

The static type checker will treat the new type as if it were a subclass of the original type. (Contributed by Ivan Levkivskyi in Github #189 [https://github.com/python/typing/issues/189].)

unicodedata

The unicodedata module now uses data from Unicode 9.0.0 [http://unicode.org/versions/Unicode9.0.0/]. (Contributed by Benjamin Peterson.)

unittest.mock

The Mock class has the following improvements:

Two new methods, Mock.assert_called() and Mock.assert_called_once() to check if the mock object was called. (Contributed by Amit Saha in bpo-26323 [https://bugs.python.org/issue?@action=redirect&bpo=26323].)

The Mock.reset_mock() method now has two optional keyword only arguments: return_value and side_effect. (Contributed by Kushal Das in bpo-21271 [https://bugs.python.org/issue?@action=redirect&bpo=21271].)

urllib.request

If a HTTP request has a file or iterable body (other than a bytes object) but no Content-Length header, rather than throwing an error, AbstractHTTPHandler now falls back to use chunked transfer encoding. (Contributed by Demian Brecht and Rolf Krahl in bpo-12319 [https://bugs.python.org/issue?@action=redirect&bpo=12319].)

urllib.robotparser

RobotFileParser now supports the Crawl-delay and Request-rate extensions. (Contributed by Nikolay Bogoychev in bpo-16099 [https://bugs.python.org/issue?@action=redirect&bpo=16099].)

venv

venv accepts a new parameter --prompt. This parameter provides an alternative prefix for the virtual environment. (Proposed by Łukasz Balcerzak and ported to 3.6 by Stéphane Wirtel in bpo-22829 [https://bugs.python.org/issue?@action=redirect&bpo=22829].)

warnings

A new optional source parameter has been added to the warnings.warn_explicit() function: the destroyed object which emitted a ResourceWarning. A source attribute has also been added to warnings.WarningMessage (contributed by Victor Stinner in bpo-26568 [https://bugs.python.org/issue?@action=redirect&bpo=26568] and bpo-26567 [https://bugs.python.org/issue?@action=redirect&bpo=26567]).

When a ResourceWarning warning is logged, the tracemalloc module is now used to try to retrieve the traceback where the destroyed object was allocated.

Example with the script example.py:

import warnings

def func():
    return open(__file__)

f = func()
f = None

Output of the command python3.6 -Wd -X tracemalloc=5 example.py:

example.py:7: ResourceWarning: unclosed file <_io.TextIOWrapper name='example.py' mode='r' encoding='UTF-8'>
  f = None
Object allocated at (most recent call first):
  File "example.py", lineno 4
    return open(__file__)
  File "example.py", lineno 6
    f = func()

The “Object allocated at” traceback is new and is only displayed if tracemalloc is tracing Python memory allocations and if the warnings module was already imported.

winreg

Added the 64-bit integer type REG_QWORD. (Contributed by Clement Rouault in bpo-23026 [https://bugs.python.org/issue?@action=redirect&bpo=23026].)

winsound

Allowed keyword arguments to be passed to Beep, MessageBeep, and PlaySound (bpo-27982 [https://bugs.python.org/issue?@action=redirect&bpo=27982]).

xmlrpc.client

The xmlrpc.client module now supports unmarshalling additional data types used by the Apache XML-RPC implementation for numerics and None. (Contributed by Serhiy Storchaka in bpo-26885 [https://bugs.python.org/issue?@action=redirect&bpo=26885].)

zipfile

A new ZipInfo.from_file() class method allows making a ZipInfo instance from a filesystem file. A new ZipInfo.is_dir() method can be used to check if the ZipInfo instance represents a directory. (Contributed by Thomas Kluyver in bpo-26039 [https://bugs.python.org/issue?@action=redirect&bpo=26039].)

The ZipFile.open() method can now be used to write data into a ZIP file, as well as for extracting data. (Contributed by Thomas Kluyver in bpo-26039 [https://bugs.python.org/issue?@action=redirect&bpo=26039].)

zlib

The compress() and decompress() functions now accept keyword arguments. (Contributed by Aviv Palivoda in bpo-26243 [https://bugs.python.org/issue?@action=redirect&bpo=26243] and Xiang Zhang in bpo-16764 [https://bugs.python.org/issue?@action=redirect&bpo=16764] respectively.)

Optimizations

The Python interpreter now uses a 16-bit wordcode instead of bytecode which made a number of opcode optimizations possible. (Contributed by Demur Rumed with input and reviews from Serhiy Storchaka and Victor Stinner in bpo-26647 [https://bugs.python.org/issue?@action=redirect&bpo=26647] and bpo-28050 [https://bugs.python.org/issue?@action=redirect&bpo=28050].)

The asyncio.Future class now has an optimized C implementation. (Contributed by Yury Selivanov and INADA Naoki in bpo-26081 [https://bugs.python.org/issue?@action=redirect&bpo=26081].)

The asyncio.Task class now has an optimized C implementation. (Contributed by Yury Selivanov in bpo-28544 [https://bugs.python.org/issue?@action=redirect&bpo=28544].)

Various implementation improvements in the typing module (such as caching of generic types) allow up to 30 times performance improvements and reduced memory footprint.

The ASCII decoder is now up to 60 times as fast for error handlers surrogateescape, ignore and replace (Contributed by Victor Stinner in bpo-24870 [https://bugs.python.org/issue?@action=redirect&bpo=24870]).

The ASCII and the Latin1 encoders are now up to 3 times as fast for the error handler surrogateescape (Contributed by Victor Stinner in bpo-25227 [https://bugs.python.org/issue?@action=redirect&bpo=25227]).

The UTF-8 encoder is now up to 75 times as fast for error handlers ignore, replace, surrogateescape, surrogatepass (Contributed by Victor Stinner in bpo-25267 [https://bugs.python.org/issue?@action=redirect&bpo=25267]).

The UTF-8 decoder is now up to 15 times as fast for error handlers ignore, replace and surrogateescape (Contributed by Victor Stinner in bpo-25301 [https://bugs.python.org/issue?@action=redirect&bpo=25301]).

bytes % args is now up to 2 times faster. (Contributed by Victor Stinner in bpo-25349 [https://bugs.python.org/issue?@action=redirect&bpo=25349]).

bytearray % args is now between 2.5 and 5 times faster. (Contributed by Victor Stinner in bpo-25399 [https://bugs.python.org/issue?@action=redirect&bpo=25399]).

Optimize bytes.fromhex() and bytearray.fromhex(): they are now between 2x and 3.5x faster. (Contributed by Victor Stinner in bpo-25401 [https://bugs.python.org/issue?@action=redirect&bpo=25401]).

Optimize bytes.replace(b'', b'.') and bytearray.replace(b'', b'.'): up to 80% faster. (Contributed by Josh Snider in bpo-26574 [https://bugs.python.org/issue?@action=redirect&bpo=26574]).

Allocator functions of the PyMem_Malloc() domain (PYMEM_DOMAIN_MEM) now use the pymalloc memory allocator instead of malloc() function of the C library. The pymalloc allocator is optimized for objects smaller or equal to 512 bytes with a short lifetime, and use malloc() for larger memory blocks. (Contributed by Victor Stinner in bpo-26249 [https://bugs.python.org/issue?@action=redirect&bpo=26249]).

pickle.load() and pickle.loads() are now up to 10% faster when deserializing many small objects (Contributed by Victor Stinner in bpo-27056 [https://bugs.python.org/issue?@action=redirect&bpo=27056]).

Passing keyword arguments to a function has an overhead in comparison with passing positional arguments. Now in extension functions implemented with using Argument Clinic this overhead is significantly decreased. (Contributed by Serhiy Storchaka in bpo-27574 [https://bugs.python.org/issue?@action=redirect&bpo=27574]).

Optimized glob() and iglob() functions in the glob module; they are now about 3–6 times faster. (Contributed by Serhiy Storchaka in bpo-25596 [https://bugs.python.org/issue?@action=redirect&bpo=25596]).

Optimized globbing in pathlib by using os.scandir(); it is now about 1.5–4 times faster. (Contributed by Serhiy Storchaka in bpo-26032 [https://bugs.python.org/issue?@action=redirect&bpo=26032]).

xml.etree.ElementTree parsing, iteration and deepcopy performance has been significantly improved. (Contributed by Serhiy Storchaka in bpo-25638 [https://bugs.python.org/issue?@action=redirect&bpo=25638], bpo-25873 [https://bugs.python.org/issue?@action=redirect&bpo=25873], and bpo-25869 [https://bugs.python.org/issue?@action=redirect&bpo=25869].)

Creation of fractions.Fraction instances from floats and decimals is now 2 to 3 times faster. (Contributed by Serhiy Storchaka in bpo-25971 [https://bugs.python.org/issue?@action=redirect&bpo=25971].)

Build and C API Changes

Python now requires some C99 support in the toolchain to build. Most notably, Python now uses standard integer types and macros in place of custom macros like PY_LONG_LONG. For more information, see PEP 7 [https://www.python.org/dev/peps/pep-0007] and bpo-17884 [https://bugs.python.org/issue?@action=redirect&bpo=17884].

Cross-compiling CPython with the Android NDK and the Android API level set to 21 (Android 5.0 Lollipop) or greater runs successfully. While Android is not yet a supported platform, the Python test suite runs on the Android emulator with only about 16 tests failures. See the Android meta-issue bpo-26865 [https://bugs.python.org/issue?@action=redirect&bpo=26865].

The --enable-optimizations configure flag has been added. Turning it on will activate expensive optimizations like PGO. (Original patch by Alecsandru Patrascu of Intel in bpo-26359 [https://bugs.python.org/issue?@action=redirect&bpo=26359].)

The GIL must now be held when allocator functions of PYMEM_DOMAIN_OBJ (ex: PyObject_Malloc()) and PYMEM_DOMAIN_MEM (ex: PyMem_Malloc()) domains are called.

New Py_FinalizeEx() API which indicates if flushing buffered data failed. (Contributed by Martin Panter in bpo-5319 [https://bugs.python.org/issue?@action=redirect&bpo=5319].)

PyArg_ParseTupleAndKeywords() now supports positional-only parameters. Positional-only parameters are defined by empty names. (Contributed by Serhiy Storchaka in bpo-26282 [https://bugs.python.org/issue?@action=redirect&bpo=26282]).

PyTraceback_Print method now abbreviates long sequences of repeated lines as "[Previous line repeated {count} more times]". (Contributed by Emanuel Barry in bpo-26823 [https://bugs.python.org/issue?@action=redirect&bpo=26823].)

The new PyErr_SetImportErrorSubclass() function allows for specifying a subclass of ImportError to raise. (Contributed by Eric Snow in bpo-15767 [https://bugs.python.org/issue?@action=redirect&bpo=15767].)

The new PyErr_ResourceWarning() function can be used to generate a ResourceWarning providing the source of the resource allocation. (Contributed by Victor Stinner in bpo-26567 [https://bugs.python.org/issue?@action=redirect&bpo=26567].)

The new PyOS_FSPath() function returns the file system representation of a path-like object. (Contributed by Brett Cannon in bpo-27186 [https://bugs.python.org/issue?@action=redirect&bpo=27186].)

The PyUnicode_FSConverter() and PyUnicode_FSDecoder() functions will now accept path-like objects.

Other Improvements

When --version (short form: -V) is supplied twice, Python prints sys.version for detailed information.

$ ./python -VV
Python 3.6.0b4+ (3.6:223967b49e49+, Nov 21 2016, 20:55:04)
[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.42.1)]

Deprecated

New Keywords

async and await are not recommended to be used as variable, class, function or module names. Introduced by PEP 492 [https://www.python.org/dev/peps/pep-0492] in Python 3.5, they will become proper keywords in Python 3.7. Starting in Python 3.6, the use of async or await as names will generate a DeprecationWarning.

Deprecated Python behavior

Raising the StopIteration exception inside a generator will now generate a DeprecationWarning, and will trigger a RuntimeError in Python 3.7. See PEP 479: Change StopIteration handling inside generators for details.

The __aiter__() method is now expected to return an asynchronous iterator directly instead of returning an awaitable as previously. Doing the former will trigger a DeprecationWarning. Backward compatibility will be removed in Python 3.7. (Contributed by Yury Selivanov in bpo-27243 [https://bugs.python.org/issue?@action=redirect&bpo=27243].)

A backslash-character pair that is not a valid escape sequence now generates a DeprecationWarning. Although this will eventually become a SyntaxError, that will not be for several Python releases. (Contributed by Emanuel Barry in bpo-27364 [https://bugs.python.org/issue?@action=redirect&bpo=27364].)

When performing a relative import, falling back on __name__ and __path__ from the calling module when __spec__ or __package__ are not defined now raises an ImportWarning. (Contributed by Rose Ames in bpo-25791 [https://bugs.python.org/issue?@action=redirect&bpo=25791].)

Deprecated Python modules, functions and methods

asynchat

The asynchat has been deprecated in favor of asyncio. (Contributed by Mariatta in bpo-25002 [https://bugs.python.org/issue?@action=redirect&bpo=25002].)

asyncore

The asyncore has been deprecated in favor of asyncio. (Contributed by Mariatta in bpo-25002 [https://bugs.python.org/issue?@action=redirect&bpo=25002].)

dbm

Unlike other dbm implementations, the dbm.dumb module creates databases with the 'rw' mode and allows modifying the database opened with the 'r' mode. This behavior is now deprecated and will be removed in 3.8. (Contributed by Serhiy Storchaka in bpo-21708 [https://bugs.python.org/issue?@action=redirect&bpo=21708].)

distutils

The undocumented extra_path argument to the Distribution constructor is now considered deprecated and will raise a warning if set. Support for this parameter will be removed in a future Python release. See bpo-27919 [https://bugs.python.org/issue?@action=redirect&bpo=27919] for details.

grp

The support of non-integer arguments in getgrgid() has been deprecated. (Contributed by Serhiy Storchaka in bpo-26129 [https://bugs.python.org/issue?@action=redirect&bpo=26129].)

importlib

The importlib.machinery.SourceFileLoader.load_module() and importlib.machinery.SourcelessFileLoader.load_module() methods are now deprecated. They were the only remaining implementations of importlib.abc.Loader.load_module() in importlib that had not been deprecated in previous versions of Python in favour of importlib.abc.Loader.exec_module().

The importlib.machinery.WindowsRegistryFinder class is now deprecated. As of 3.6.0, it is still added to sys.meta_path by default (on Windows), but this may change in future releases.

os

Undocumented support of general bytes-like objects as paths in os functions, compile() and similar functions is now deprecated. (Contributed by Serhiy Storchaka in bpo-25791 [https://bugs.python.org/issue?@action=redirect&bpo=25791] and bpo-26754 [https://bugs.python.org/issue?@action=redirect&bpo=26754].)

re

Support for inline flags (?letters) in the middle of the regular expression has been deprecated and will be removed in a future Python version. Flags at the start of a regular expression are still allowed. (Contributed by Serhiy Storchaka in bpo-22493 [https://bugs.python.org/issue?@action=redirect&bpo=22493].)

ssl

OpenSSL 0.9.8, 1.0.0 and 1.0.1 are deprecated and no longer supported. In the future the ssl module will require at least OpenSSL 1.0.2 or 1.1.0.

SSL-related arguments like certfile, keyfile and check_hostname in ftplib, http.client, imaplib, poplib, and smtplib have been deprecated in favor of context. (Contributed by Christian Heimes in bpo-28022 [https://bugs.python.org/issue?@action=redirect&bpo=28022].)

A couple of protocols and functions of the ssl module are now deprecated. Some features will no longer be available in future versions of OpenSSL. Other features are deprecated in favor of a different API. (Contributed by Christian Heimes in bpo-28022 [https://bugs.python.org/issue?@action=redirect&bpo=28022] and bpo-26470 [https://bugs.python.org/issue?@action=redirect&bpo=26470].)

tkinter

The tkinter.tix module is now deprecated. tkinter users should use tkinter.ttk instead.

venv

The pyvenv script has been deprecated in favour of python3 -m venv. This prevents confusion as to what Python interpreter pyvenv is connected to and thus what Python interpreter will be used by the virtual environment. (Contributed by Brett Cannon in bpo-25154 [https://bugs.python.org/issue?@action=redirect&bpo=25154].)

Deprecated functions and types of the C API

Undocumented functions PyUnicode_AsEncodedObject(), PyUnicode_AsDecodedObject(), PyUnicode_AsEncodedUnicode() and PyUnicode_AsDecodedUnicode() are deprecated now. Use the generic codec based API instead.

Deprecated Build Options

The --with-system-ffi configure flag is now on by default on non-macOS UNIX platforms. It may be disabled by using --without-system-ffi, but using the flag is deprecated and will not be accepted in Python 3.7. macOS is unaffected by this change. Note that many OS distributors already use the --with-system-ffi flag when building their system Python.

Removed

API and Feature Removals

Unknown escapes consisting of '\' and an ASCII letter in regular expressions will now cause an error. In replacement templates for re.sub() they are still allowed, but deprecated. The re.LOCALE flag can now only be used with binary patterns.

inspect.getmoduleinfo() was removed (was deprecated since CPython 3.3). inspect.getmodulename() should be used for obtaining the module name for a given path. (Contributed by Yury Selivanov in bpo-13248 [https://bugs.python.org/issue?@action=redirect&bpo=13248].)

traceback.Ignore class and traceback.usage, traceback.modname, traceback.fullmodname, traceback.find_lines_from_code, traceback.find_lines, traceback.find_strings, traceback.find_executable_lines methods were removed from the traceback module. They were undocumented methods deprecated since Python 3.2 and equivalent functionality is available from private methods.

The tk_menuBar() and tk_bindForTraversal() dummy methods in tkinter widget classes were removed (corresponding Tk commands were obsolete since Tk 4.0).

The open() method of the zipfile.ZipFile class no longer supports the 'U' mode (was deprecated since Python 3.4). Use io.TextIOWrapper for reading compressed text files in universal newlines mode.

The undocumented IN, CDROM, DLFCN, TYPES, CDIO, and STROPTS modules have been removed. They had been available in the platform specific Lib/plat-*/ directories, but were chronically out of date, inconsistently available across platforms, and unmaintained. The script that created these modules is still available in the source distribution at Tools/scripts/h2py.py [https://github.com/python/cpython/tree/3.7/Tools/scripts/h2py.py].

The deprecated asynchat.fifo class has been removed.

Porting to Python 3.6

This section lists previously described changes and other bugfixes that may require changes to your code.

Changes in ‘python’ Command Behavior

The output of a special Python build with defined COUNT_ALLOCS, SHOW_ALLOC_COUNT or SHOW_TRACK_COUNT macros is now off by default. It can be re-enabled using the -X showalloccount option. It now outputs to stderr instead of stdout. (Contributed by Serhiy Storchaka in bpo-23034 [https://bugs.python.org/issue?@action=redirect&bpo=23034].)

Changes in the Python API

open() will no longer allow combining the 'U' mode flag with '+'. (Contributed by Jeff Balogh and John O’Connor in bpo-2091 [https://bugs.python.org/issue?@action=redirect&bpo=2091].)

sqlite3 no longer implicitly commits an open transaction before DDL statements.

On Linux, os.urandom() now blocks until the system urandom entropy pool is initialized to increase the security.

When importlib.abc.Loader.exec_module() is defined, importlib.abc.Loader.create_module() must also be defined.

PyErr_SetImportError() now sets TypeError when its msg argument is not set. Previously only NULL was returned.

The format of the co_lnotab attribute of code objects changed to support a negative line number delta. By default, Python does not emit bytecode with a negative line number delta. Functions using frame.f_lineno, PyFrame_GetLineNumber() or PyCode_Addr2Line() are not affected. Functions directly decoding co_lnotab should be updated to use a signed 8-bit integer type for the line number delta, but this is only required to support applications using a negative line number delta. See Objects/lnotab_notes.txt for the co_lnotab format and how to decode it, and see the PEP 511 [https://www.python.org/dev/peps/pep-0511] for the rationale.

The functions in the compileall module now return booleans instead of 1 or 0 to represent success or failure, respectively. Thanks to booleans being a subclass of integers, this should only be an issue if you were doing identity checks for 1 or 0. See bpo-25768 [https://bugs.python.org/issue?@action=redirect&bpo=25768].

Reading the port attribute of urllib.parse.urlsplit() and urlparse() results now raises ValueError for out-of-range values, rather than returning None. See bpo-20059 [https://bugs.python.org/issue?@action=redirect&bpo=20059].

The imp module now raises a DeprecationWarning instead of PendingDeprecationWarning.

The following modules have had missing APIs added to their __all__ attributes to match the documented APIs: calendar, cgi, csv, ElementTree, enum, fileinput, ftplib, logging, mailbox, mimetypes, optparse, plistlib, smtpd, subprocess, tarfile, threading and wave. This means they will export new symbols when import * is used. (Contributed by Joel Taddei and Jacek Kołodziej in bpo-23883 [https://bugs.python.org/issue?@action=redirect&bpo=23883].)

When performing a relative import, if __package__ does not compare equal to __spec__.parent then ImportWarning is raised. (Contributed by Brett Cannon in bpo-25791 [https://bugs.python.org/issue?@action=redirect&bpo=25791].)

When a relative import is performed and no parent package is known, then ImportError will be raised. Previously, SystemError could be raised. (Contributed by Brett Cannon in bpo-18018 [https://bugs.python.org/issue?@action=redirect&bpo=18018].)

Servers based on the socketserver module, including those defined in http.server, xmlrpc.server and wsgiref.simple_server, now only catch exceptions derived from Exception. Therefore if a request handler raises an exception like SystemExit or KeyboardInterrupt, handle_error() is no longer called, and the exception will stop a single-threaded server. (Contributed by Martin Panter in bpo-23430 [https://bugs.python.org/issue?@action=redirect&bpo=23430].)

spwd.getspnam() now raises a PermissionError instead of KeyError if the user doesn’t have privileges.

The socket.socket.close() method now raises an exception if an error (e.g. EBADF) was reported by the underlying system call. (Contributed by Martin Panter in bpo-26685 [https://bugs.python.org/issue?@action=redirect&bpo=26685].)

The decode_data argument for the smtpd.SMTPChannel and smtpd.SMTPServer constructors is now False by default. This means that the argument passed to process_message() is now a bytes object by default, and process_message() will be passed keyword arguments. Code that has already been updated in accordance with the deprecation warning generated by 3.5 will not be affected.

All optional arguments of the dump(), dumps(), load() and loads() functions and JSONEncoder and JSONDecoder class constructors in the json module are now keyword-only. (Contributed by Serhiy Storchaka in bpo-18726 [https://bugs.python.org/issue?@action=redirect&bpo=18726].)

Subclasses of type which don’t override type.__new__ may no longer use the one-argument form to get the type of an object.

As part of PEP 487 [https://www.python.org/dev/peps/pep-0487], the handling of keyword arguments passed to type (other than the metaclass hint, metaclass) is now consistently delegated to object.__init_subclass__(). This means that type.__new__() and type.__init__() both now accept arbitrary keyword arguments, but object.__init_subclass__() (which is called from type.__new__()) will reject them by default. Custom metaclasses accepting additional keyword arguments will need to adjust their calls to type.__new__() (whether direct or via super) accordingly.

In distutils.command.sdist.sdist, the default_format attribute has been removed and is no longer honored. Instead, the gzipped tarfile format is the default on all platforms and no platform-specific selection is made. In environments where distributions are built on Windows and zip distributions are required, configure the project with a setup.cfg file containing the following:

[sdist]
formats=zip

This behavior has also been backported to earlier Python versions by Setuptools 26.0.0.

In the urllib.request module and the http.client.HTTPConnection.request() method, if no Content-Length header field has been specified and the request body is a file object, it is now sent with HTTP 1.1 chunked encoding. If a file object has to be sent to a HTTP 1.0 server, the Content-Length value now has to be specified by the caller. (Contributed by Demian Brecht and Rolf Krahl with tweaks from Martin Panter in bpo-12319 [https://bugs.python.org/issue?@action=redirect&bpo=12319].)

The DictReader now returns rows of type OrderedDict. (Contributed by Steve Holden in bpo-27842 [https://bugs.python.org/issue?@action=redirect&bpo=27842].)

The crypt.METHOD_CRYPT will no longer be added to crypt.methods if unsupported by the platform. (Contributed by Victor Stinner in bpo-25287 [https://bugs.python.org/issue?@action=redirect&bpo=25287].)

The verbose and rename arguments for namedtuple() are now keyword-only. (Contributed by Raymond Hettinger in bpo-25628 [https://bugs.python.org/issue?@action=redirect&bpo=25628].)

On Linux, ctypes.util.find_library() now looks in LD_LIBRARY_PATH for shared libraries. (Contributed by Vinay Sajip in bpo-9998 [https://bugs.python.org/issue?@action=redirect&bpo=9998].)

The imaplib.IMAP4 class now handles flags containing the ']' character in messages sent from the server to improve real-world compatibility. (Contributed by Lita Cho in bpo-21815 [https://bugs.python.org/issue?@action=redirect&bpo=21815].)

The mmap.write() function now returns the number of bytes written like other write methods. (Contributed by Jakub Stasiak in bpo-26335 [https://bugs.python.org/issue?@action=redirect&bpo=26335].)

The pkgutil.iter_modules() and pkgutil.walk_packages() functions now return ModuleInfo named tuples. (Contributed by Ramchandra Apte in bpo-17211 [https://bugs.python.org/issue?@action=redirect&bpo=17211].)

re.sub() now raises an error for invalid numerical group references in replacement templates even if the pattern is not found in the string. The error message for invalid group references now includes the group index and the position of the reference. (Contributed by SilentGhost, Serhiy Storchaka in bpo-25953 [https://bugs.python.org/issue?@action=redirect&bpo=25953].)

zipfile.ZipFile will now raise NotImplementedError for unrecognized compression values. Previously a plain RuntimeError was raised. Additionally, calling ZipFile methods on a closed ZipFile or calling the write() method on a ZipFile created with mode 'r' will raise a ValueError. Previously, a RuntimeError was raised in those scenarios.

when custom metaclasses are combined with zero-argument super() or direct references from methods to the implicit __class__ closure variable, the implicit __classcell__ namespace entry must now be passed up to type.__new__ for initialisation. Failing to do so will result in a DeprecationWarning in Python 3.6 and a RuntimeError in Python 3.8.

With the introduction of ModuleNotFoundError, import system consumers may start expecting import system replacements to raise that more specific exception when appropriate, rather than the less-specific ImportError. To provide future compatibility with such consumers, implementors of alternative import systems that completely replace __import__() will need to update their implementations to raise the new subclass when a module can’t be found at all. Implementors of compliant plugins to the default import system shouldn’t need to make any changes, as the default import system will raise the new subclass when appropriate.

Changes in the C API

The PyMem_Malloc() allocator family now uses the pymalloc allocator rather than the system malloc(). Applications calling PyMem_Malloc() without holding the GIL can now crash. Set the PYTHONMALLOC environment variable to debug to validate the usage of memory allocators in your application. See bpo-26249 [https://bugs.python.org/issue?@action=redirect&bpo=26249].

Py_Exit() (and the main interpreter) now override the exit status with 120 if flushing buffered data failed. See bpo-5319 [https://bugs.python.org/issue?@action=redirect&bpo=5319].

CPython bytecode changes

There have been several major changes to the bytecode in Python 3.6.

The Python interpreter now uses a 16-bit wordcode instead of bytecode. (Contributed by Demur Rumed with input and reviews from Serhiy Storchaka and Victor Stinner in bpo-26647 [https://bugs.python.org/issue?@action=redirect&bpo=26647] and bpo-28050 [https://bugs.python.org/issue?@action=redirect&bpo=28050].)

The new FORMAT_VALUE and BUILD_STRING opcodes as part of the formatted string literal implementation. (Contributed by Eric Smith in bpo-25483 [https://bugs.python.org/issue?@action=redirect&bpo=25483] and Serhiy Storchaka in bpo-27078 [https://bugs.python.org/issue?@action=redirect&bpo=27078].)

The new BUILD_CONST_KEY_MAP opcode to optimize the creation of dictionaries with constant keys. (Contributed by Serhiy Storchaka in bpo-27140 [https://bugs.python.org/issue?@action=redirect&bpo=27140].)

The function call opcodes have been heavily reworked for better performance and simpler implementation. The MAKE_FUNCTION, CALL_FUNCTION, CALL_FUNCTION_KW and BUILD_MAP_UNPACK_WITH_CALL opcodes have been modified, the new CALL_FUNCTION_EX and BUILD_TUPLE_UNPACK_WITH_CALL have been added, and CALL_FUNCTION_VAR, CALL_FUNCTION_VAR_KW and MAKE_CLOSURE opcodes have been removed. (Contributed by Demur Rumed in bpo-27095 [https://bugs.python.org/issue?@action=redirect&bpo=27095], and Serhiy Storchaka in bpo-27213 [https://bugs.python.org/issue?@action=redirect&bpo=27213], bpo-28257 [https://bugs.python.org/issue?@action=redirect&bpo=28257].)

The new SETUP_ANNOTATIONS and STORE_ANNOTATION opcodes have been added to support the new variable annotation syntax. (Contributed by Ivan Levkivskyi in bpo-27985 [https://bugs.python.org/issue?@action=redirect&bpo=27985].)

Notable changes in Python 3.6.2

New make regen-all build target

To simplify cross-compilation, and to ensure that CPython can reliably be compiled without requiring an existing version of Python to already be available, the autotools-based build system no longer attempts to implicitly recompile generated files based on file modification times.

Instead, a new make regen-all command has been added to force regeneration of these files when desired (e.g. after an initial version of Python has already been built based on the pregenerated versions).

More selective regeneration targets are also defined - see Makefile.pre.in [https://github.com/python/cpython/tree/3.7/Makefile.pre.in] for details.

(Contributed by Victor Stinner in bpo-23404 [https://bugs.python.org/issue?@action=redirect&bpo=23404].)

버전 3.6.2에 추가.

Removal of make touch build target

The make touch build target previously used to request implicit regeneration of generated files by updating their modification times has been removed.

It has been replaced by the new make regen-all target.

(Contributed by Victor Stinner in bpo-23404 [https://bugs.python.org/issue?@action=redirect&bpo=23404].)

버전 3.6.2에서 변경.

Notable changes in Python 3.6.4

The PyExc_RecursionErrorInst singleton that was part of the public API has been removed as its members being never cleared may cause a segfault during finalization of the interpreter. (Contributed by Xavier de Gaye in bpo-22898 [https://bugs.python.org/issue?@action=redirect&bpo=22898] and bpo-30697 [https://bugs.python.org/issue?@action=redirect&bpo=30697].)

Notable changes in Python 3.6.5

The locale.localeconv() function now sets temporarily the LC_CTYPE locale to the LC_NUMERIC locale in some cases. (Contributed by Victor Stinner in bpo-31900 [https://bugs.python.org/issue?@action=redirect&bpo=31900].)

Notable changes in Python 3.6.7

In 3.6.7 the tokenize module now implicitly emits a NEWLINE token when provided with input that does not have a trailing new line. This behavior now matches what the C tokenizer does internally. (Contributed by Ammar Askar in bpo-33899 [https://bugs.python.org/issue?@action=redirect&bpo=33899].)

Notable changes in Python 3.6.10

Due to significant security concerns, the reuse_address parameter of asyncio.loop.create_datagram_endpoint() is no longer supported. This is because of the behavior of the socket option SO_REUSEADDR in UDP. For more details, see the documentation for loop.create_datagram_endpoint(). (Contributed by Kyle Stanley, Antoine Pitrou, and Yury Selivanov in bpo-37228 [https://bugs.python.org/issue?@action=redirect&bpo=37228].)

Notable changes in Python 3.6.13

Earlier Python versions allowed using both ; and & as query parameter separators in urllib.parse.parse_qs() and urllib.parse.parse_qsl(). Due to security concerns, and to conform with newer W3C recommendations, this has been changed to allow only a single separator key, with & as the default. This change also affects cgi.parse() and cgi.parse_multipart() as they use the affected functions internally. For more details, please see their respective documentation. (Contributed by Adam Goldschmidt, Senthil Kumaran and Ken Jin in bpo-42967 [https://bugs.python.org/issue?@action=redirect&bpo=42967].)

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬의 새로운 기능 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬의 새로운 기능 »

|

What’s New In Python 3.5

Editors

Elvis Pranskevichus <elvis@magic.io>, Yury Selivanov <yury@magic.io>

This article explains the new features in Python 3.5, compared to 3.4. Python 3.5 was released on September 13, 2015.  See the changelog [https://docs.python.org/3.5/whatsnew/changelog.html] for a full list of changes.

더 보기

PEP 478 [https://www.python.org/dev/peps/pep-0478] - Python 3.5 Release Schedule

Summary – Release highlights

New syntax features:

PEP 492, coroutines with async and await syntax.

PEP 465, a new matrix multiplication operator: a @ b.

PEP 448, additional unpacking generalizations.

New library modules:

typing: PEP 484 – Type Hints.

zipapp: PEP 441 Improving Python ZIP Application Support.

New built-in features:

bytes % args, bytearray % args: PEP 461 – Adding % formatting to bytes and bytearray.

New bytes.hex(), bytearray.hex() and memoryview.hex() methods. (Contributed by Arnon Yaari in bpo-9951 [https://bugs.python.org/issue?@action=redirect&bpo=9951].)

memoryview now supports tuple indexing (including multi-dimensional). (Contributed by Antoine Pitrou in bpo-23632 [https://bugs.python.org/issue?@action=redirect&bpo=23632].)

Generators have a new gi_yieldfrom attribute, which returns the object being iterated by yield from expressions. (Contributed by Benno Leslie and Yury Selivanov in bpo-24450 [https://bugs.python.org/issue?@action=redirect&bpo=24450].)

A new RecursionError exception is now raised when maximum recursion depth is reached. (Contributed by Georg Brandl in bpo-19235 [https://bugs.python.org/issue?@action=redirect&bpo=19235].)

CPython implementation improvements:

When the LC_TYPE locale is the POSIX locale (C locale), sys.stdin and sys.stdout now use the surrogateescape error handler, instead of the strict error handler. (Contributed by Victor Stinner in bpo-19977 [https://bugs.python.org/issue?@action=redirect&bpo=19977].)

.pyo files are no longer used and have been replaced by a more flexible scheme that includes the optimization level explicitly in .pyc name. (See PEP 488 overview.)

Builtin and extension modules are now initialized in a multi-phase process, which is similar to how Python modules are loaded. (See PEP 489 overview.)

Significant improvements in the standard library:

collections.OrderedDict is now implemented in C, which makes it 4 to 100 times faster.

The ssl module gained support for Memory BIO, which decouples SSL protocol handling from network IO.

The new os.scandir() function provides a better and significantly faster way of directory traversal.

functools.lru_cache() has been mostly reimplemented in C, yielding much better performance.

The new subprocess.run() function provides a streamlined way to run subprocesses.

The traceback module has been significantly enhanced for improved performance and developer convenience.

Security improvements:

SSLv3 is now disabled throughout the standard library. It can still be enabled by instantiating a ssl.SSLContext manually. (See bpo-22638 [https://bugs.python.org/issue?@action=redirect&bpo=22638] for more details; this change was backported to CPython 3.4 and 2.7.)

HTTP cookie parsing is now stricter, in order to protect against potential injection attacks. (Contributed by Antoine Pitrou in bpo-22796 [https://bugs.python.org/issue?@action=redirect&bpo=22796].)

Windows improvements:

A new installer for Windows has replaced the old MSI. See Using Python on Windows for more information.

Windows builds now use Microsoft Visual C++ 14.0, and extension modules should use the same.

Please read on for a comprehensive list of user-facing changes, including many other smaller improvements, CPython optimizations, deprecations, and potential porting issues.

New Features

PEP 492 - Coroutines with async and await syntax

PEP 492 [https://www.python.org/dev/peps/pep-0492] greatly improves support for asynchronous programming in Python by adding awaitable objects, coroutine functions, asynchronous iteration, and asynchronous context managers.

Coroutine functions are declared using the new async def syntax:

>>> async def coro():
...     return 'spam'

Inside a coroutine function, the new await expression can be used to suspend coroutine execution until the result is available. Any object can be awaited, as long as it implements the awaitable protocol by defining the __await__() method.

PEP 492 also adds async for statement for convenient iteration over asynchronous iterables.

An example of a rudimentary HTTP client written using the new syntax:

import asyncio

async def http_get(domain):
    reader, writer = await asyncio.open_connection(domain, 80)

    writer.write(b'\r\n'.join([
        b'GET / HTTP/1.1',
        b'Host: %b' % domain.encode('latin-1'),
        b'Connection: close',
        b'', b''
    ]))

    async for line in reader:
        print('>>>', line)

    writer.close()

loop = asyncio.get_event_loop()
try:
    loop.run_until_complete(http_get('example.com'))
finally:
    loop.close()

Similarly to asynchronous iteration, there is a new syntax for asynchronous context managers. The following script:

import asyncio

async def coro(name, lock):
    print('coro {}: waiting for lock'.format(name))
    async with lock:
        print('coro {}: holding the lock'.format(name))
        await asyncio.sleep(1)
        print('coro {}: releasing the lock'.format(name))

loop = asyncio.get_event_loop()
lock = asyncio.Lock()
coros = asyncio.gather(coro(1, lock), coro(2, lock))
try:
    loop.run_until_complete(coros)
finally:
    loop.close()

will output:

coro 2: waiting for lock
coro 2: holding the lock
coro 1: waiting for lock
coro 2: releasing the lock
coro 1: holding the lock
coro 1: releasing the lock

Note that both async for and async with can only be used inside a coroutine function declared with async def.

Coroutine functions are intended to be run inside a compatible event loop, such as the asyncio loop.

참고

버전 3.5.2에서 변경: Starting with CPython 3.5.2, __aiter__ can directly return asynchronous iterators. Returning an awaitable object will result in a PendingDeprecationWarning.

See more details in the 비동기 이터레이터(Asynchronous Iterators) documentation section.

더 보기

PEP 492 [https://www.python.org/dev/peps/pep-0492] – Coroutines with async and await syntax

PEP written and implemented by Yury Selivanov.

PEP 465 - A dedicated infix operator for matrix multiplication

PEP 465 [https://www.python.org/dev/peps/pep-0465] adds the @ infix operator for matrix multiplication. Currently, no builtin Python types implement the new operator, however, it can be implemented by defining __matmul__(), __rmatmul__(), and __imatmul__() for regular, reflected, and in-place matrix multiplication. The semantics of these methods is similar to that of methods defining other infix arithmetic operators.

Matrix multiplication is a notably common operation in many fields of mathematics, science, engineering, and the addition of @ allows writing cleaner code:

S = (H @ beta - r).T @ inv(H @ V @ H.T) @ (H @ beta - r)

instead of:

S = dot((dot(H, beta) - r).T,
        dot(inv(dot(dot(H, V), H.T)), dot(H, beta) - r))

NumPy 1.10 has support for the new operator:

>>> import numpy

>>> x = numpy.ones(3)
>>> x
array([ 1., 1., 1.])

>>> m = numpy.eye(3)
>>> m
array([[ 1., 0., 0.],
       [ 0., 1., 0.],
       [ 0., 0., 1.]])

>>> x @ m
array([ 1., 1., 1.])

더 보기

PEP 465 [https://www.python.org/dev/peps/pep-0465] – A dedicated infix operator for matrix multiplication

PEP written by Nathaniel J. Smith; implemented by Benjamin Peterson.

PEP 448 - Additional Unpacking Generalizations

PEP 448 [https://www.python.org/dev/peps/pep-0448] extends the allowed uses of the * iterable unpacking operator and ** dictionary unpacking operator. It is now possible to use an arbitrary number of unpackings in function calls:

>>> print(*[1], *[2], 3, *[4, 5])
1 2 3 4 5

>>> def fn(a, b, c, d):
...     print(a, b, c, d)
...

>>> fn(**{'a': 1, 'c': 3}, **{'b': 2, 'd': 4})
1 2 3 4

Similarly, tuple, list, set, and dictionary displays allow multiple unpackings (see 표현식 목록(Expression lists) and 딕셔너리 디스플레이):

>>> *range(4), 4
(0, 1, 2, 3, 4)

>>> [*range(4), 4]
[0, 1, 2, 3, 4]

>>> {*range(4), 4, *(5, 6, 7)}
{0, 1, 2, 3, 4, 5, 6, 7}

>>> {'x': 1, **{'y': 2}}
{'x': 1, 'y': 2}

더 보기

PEP 448 [https://www.python.org/dev/peps/pep-0448] – Additional Unpacking Generalizations

PEP written by Joshua Landau; implemented by Neil Girdhar, Thomas Wouters, and Joshua Landau.

PEP 461 - percent formatting support for bytes and bytearray

PEP 461 [https://www.python.org/dev/peps/pep-0461] adds support for the % interpolation operator to bytes and bytearray.

While interpolation is usually thought of as a string operation, there are cases where interpolation on bytes or bytearrays makes sense, and the work needed to make up for this missing functionality detracts from the overall readability of the code. This issue is particularly important when dealing with wire format protocols, which are often a mixture of binary and ASCII compatible text.

Examples:

>>> b'Hello %b!' % b'World'
b'Hello World!'

>>> b'x=%i y=%f' % (1, 2.5)
b'x=1 y=2.500000'

Unicode is not allowed for %b, but it is accepted by %a (equivalent of repr(obj).encode('ascii', 'backslashreplace')):

>>> b'Hello %b!' % 'World'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: %b requires bytes, or an object that implements __bytes__, not 'str'

>>> b'price: %a' % '10€'
b"price: '10\\u20ac'"

Note that %s and %r conversion types, although supported, should only be used in codebases that need compatibility with Python 2.

더 보기

PEP 461 [https://www.python.org/dev/peps/pep-0461] – Adding % formatting to bytes and bytearray

PEP written by Ethan Furman; implemented by Neil Schemenauer and Ethan Furman.

PEP 484 - Type Hints

Function annotation syntax has been a Python feature since version 3.0 (PEP 3107 [https://www.python.org/dev/peps/pep-3107]), however the semantics of annotations has been left undefined.

Experience has shown that the majority of function annotation uses were to provide type hints to function parameters and return values. It became evident that it would be beneficial for Python users, if the standard library included the base definitions and tools for type annotations.

PEP 484 [https://www.python.org/dev/peps/pep-0484] introduces a provisional module to provide these standard definitions and tools, along with some conventions for situations where annotations are not available.

For example, here is a simple function whose argument and return type are declared in the annotations:

def greeting(name: str) -> str:
    return 'Hello ' + name

While these annotations are available at runtime through the usual __annotations__ attribute, no automatic type checking happens at runtime. Instead, it is assumed that a separate off-line type checker (e.g. mypy [http://mypy-lang.org]) will be used for on-demand source code analysis.

The type system supports unions, generic types, and a special type named Any which is consistent with (i.e. assignable to and from) all types.

더 보기

typing module documentation

PEP 484 [https://www.python.org/dev/peps/pep-0484] – Type Hints

PEP written by Guido van Rossum, Jukka Lehtosalo, and Łukasz Langa; implemented by Guido van Rossum.

PEP 483 [https://www.python.org/dev/peps/pep-0483] – The Theory of Type Hints

PEP written by Guido van Rossum

PEP 471 - os.scandir() function – a better and faster directory iterator

PEP 471 [https://www.python.org/dev/peps/pep-0471] adds a new directory iteration function, os.scandir(), to the standard library. Additionally, os.walk() is now implemented using scandir, which makes it 3 to 5 times faster on POSIX systems and 7 to 20 times faster on Windows systems. This is largely achieved by greatly reducing the number of calls to os.stat() required to walk a directory tree.

Additionally, scandir returns an iterator, as opposed to returning a list of file names, which improves memory efficiency when iterating over very large directories.

The following example shows a simple use of os.scandir() to display all the files (excluding directories) in the given path that don’t start with '.'. The entry.is_file() call will generally not make an additional system call:

for entry in os.scandir(path):
    if not entry.name.startswith('.') and entry.is_file():
        print(entry.name)

더 보기

PEP 471 [https://www.python.org/dev/peps/pep-0471] – os.scandir() function – a better and faster directory iterator

PEP written and implemented by Ben Hoyt with the help of Victor Stinner.

PEP 475: Retry system calls failing with EINTR

An errno.EINTR error code is returned whenever a system call, that is waiting for I/O, is interrupted by a signal. Previously, Python would raise InterruptedError in such cases. This meant that, when writing a Python application, the developer had two choices:

Ignore the InterruptedError.

Handle the InterruptedError and attempt to restart the interrupted system call at every call site.

The first option makes an application fail intermittently. The second option adds a large amount of boilerplate that makes the code nearly unreadable. Compare:

print("Hello World")

and:

while True:
    try:
        print("Hello World")
        break
    except InterruptedError:
        continue

PEP 475 [https://www.python.org/dev/peps/pep-0475] implements automatic retry of system calls on EINTR. This removes the burden of dealing with EINTR or InterruptedError in user code in most situations and makes Python programs, including the standard library, more robust. Note that the system call is only retried if the signal handler does not raise an exception.

Below is a list of functions which are now retried when interrupted by a signal:

open() and io.open();

functions of the faulthandler module;

os functions: fchdir(), fchmod(), fchown(), fdatasync(), fstat(), fstatvfs(), fsync(), ftruncate(), mkfifo(), mknod(), open(), posix_fadvise(), posix_fallocate(), pread(), pwrite(), read(), readv(), sendfile(), wait3(), wait4(), wait(), waitid(), waitpid(), write(), writev();

special cases: os.close() and os.dup2() now ignore EINTR errors; the syscall is not retried (see the PEP for the rationale);

select functions: devpoll.poll(), epoll.poll(), kqueue.control(), poll.poll(), select();

methods of the socket class: accept(), connect() (except for non-blocking sockets), recv(), recvfrom(), recvmsg(), send(), sendall(), sendmsg(), sendto();

signal.sigtimedwait() and signal.sigwaitinfo();

time.sleep().

더 보기

PEP 475 [https://www.python.org/dev/peps/pep-0475] – Retry system calls failing with EINTR

PEP and implementation written by Charles-François Natali and Victor Stinner, with the help of Antoine Pitrou (the French connection).

PEP 479: Change StopIteration handling inside generators

The interaction of generators and StopIteration in Python 3.4 and earlier was sometimes surprising, and could conceal obscure bugs. Previously, StopIteration raised accidentally inside a generator function was interpreted as the end of the iteration by the loop construct driving the generator.

PEP 479 [https://www.python.org/dev/peps/pep-0479] changes the behavior of generators: when a StopIteration exception is raised inside a generator, it is replaced with a RuntimeError before it exits the generator frame. The main goal of this change is to ease debugging in the situation where an unguarded next() call raises StopIteration and causes the iteration controlled by the generator to terminate silently. This is particularly pernicious in combination with the yield from construct.

This is a backwards incompatible change, so to enable the new behavior, a __future__ import is necessary:

>>> from __future__ import generator_stop

>>> def gen():
...     next(iter([]))
...     yield
...
>>> next(gen())
Traceback (most recent call last):
  File "<stdin>", line 2, in gen
StopIteration

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
RuntimeError: generator raised StopIteration

Without a __future__ import, a PendingDeprecationWarning will be raised whenever a StopIteration exception is raised inside a generator.

더 보기

PEP 479 [https://www.python.org/dev/peps/pep-0479] – Change StopIteration handling inside generators

PEP written by Chris Angelico and Guido van Rossum. Implemented by Chris Angelico, Yury Selivanov and Nick Coghlan.

PEP 485: A function for testing approximate equality

PEP 485 [https://www.python.org/dev/peps/pep-0485] adds the math.isclose() and cmath.isclose() functions which tell whether two values are approximately equal or “close” to each other. Whether or not two values are considered close is determined according to given absolute and relative tolerances. Relative tolerance is the maximum allowed difference between isclose arguments, relative to the larger absolute value:

>>> import math
>>> a = 5.0
>>> b = 4.99998
>>> math.isclose(a, b, rel_tol=1e-5)
True
>>> math.isclose(a, b, rel_tol=1e-6)
False

It is also possible to compare two values using absolute tolerance, which must be a non-negative value:

>>> import math
>>> a = 5.0
>>> b = 4.99998
>>> math.isclose(a, b, abs_tol=0.00003)
True
>>> math.isclose(a, b, abs_tol=0.00001)
False

더 보기

PEP 485 [https://www.python.org/dev/peps/pep-0485] – A function for testing approximate equality

PEP written by Christopher Barker; implemented by Chris Barker and Tal Einat.

PEP 486: Make the Python Launcher aware of virtual environments

PEP 486 [https://www.python.org/dev/peps/pep-0486] makes the Windows launcher (see PEP 397 [https://www.python.org/dev/peps/pep-0397]) aware of an active virtual environment. When the default interpreter would be used and the VIRTUAL_ENV environment variable is set, the interpreter in the virtual environment will be used.

더 보기

PEP 486 [https://www.python.org/dev/peps/pep-0486] – Make the Python Launcher aware of virtual environments

PEP written and implemented by Paul Moore.

PEP 488: Elimination of PYO files

PEP 488 [https://www.python.org/dev/peps/pep-0488] does away with the concept of .pyo files. This means that .pyc files represent both unoptimized and optimized bytecode. To prevent the need to constantly regenerate bytecode files, .pyc files now have an optional opt- tag in their name when the bytecode is optimized. This has the side-effect of no more bytecode file name clashes when running under either -O or -OO. Consequently, bytecode files generated from -O, and -OO may now exist simultaneously. importlib.util.cache_from_source() has an updated API to help with this change.

더 보기

PEP 488 [https://www.python.org/dev/peps/pep-0488] – Elimination of PYO files

PEP written and implemented by Brett Cannon.

PEP 489: Multi-phase extension module initialization

PEP 489 [https://www.python.org/dev/peps/pep-0489] updates extension module initialization to take advantage of the two step module loading mechanism introduced by PEP 451 [https://www.python.org/dev/peps/pep-0451] in Python 3.4.

This change brings the import semantics of extension modules that opt-in to using the new mechanism much closer to those of Python source and bytecode modules, including the ability to use any valid identifier as a module name, rather than being restricted to ASCII.

더 보기

PEP 489 [https://www.python.org/dev/peps/pep-0489] – Multi-phase extension module initialization

PEP written by Petr Viktorin, Stefan Behnel, and Nick Coghlan; implemented by Petr Viktorin.

Other Language Changes

Some smaller changes made to the core Python language are:

Added the "namereplace" error handlers. The "backslashreplace" error handlers now work with decoding and translating. (Contributed by Serhiy Storchaka in bpo-19676 [https://bugs.python.org/issue?@action=redirect&bpo=19676] and bpo-22286 [https://bugs.python.org/issue?@action=redirect&bpo=22286].)

The -b option now affects comparisons of bytes with int. (Contributed by Serhiy Storchaka in bpo-23681 [https://bugs.python.org/issue?@action=redirect&bpo=23681].)

New Kazakh kz1048 and Tajik koi8_t codecs. (Contributed by Serhiy Storchaka in bpo-22682 [https://bugs.python.org/issue?@action=redirect&bpo=22682] and bpo-22681 [https://bugs.python.org/issue?@action=redirect&bpo=22681].)

Property docstrings are now writable. This is especially useful for collections.namedtuple() docstrings. (Contributed by Berker Peksag in bpo-24064 [https://bugs.python.org/issue?@action=redirect&bpo=24064].)

Circular imports involving relative imports are now supported. (Contributed by Brett Cannon and Antoine Pitrou in bpo-17636 [https://bugs.python.org/issue?@action=redirect&bpo=17636].)

New Modules

typing

The new typing provisional module provides standard definitions and tools for function type annotations. See Type Hints for more information.

zipapp

The new zipapp module (specified in PEP 441 [https://www.python.org/dev/peps/pep-0441]) provides an API and command line tool for creating executable Python Zip Applications, which were introduced in Python 2.6 in bpo-1739468 [https://bugs.python.org/issue?@action=redirect&bpo=1739468], but which were not well publicized, either at the time or since.

With the new module, bundling your application is as simple as putting all the files, including a __main__.py file, into a directory myapp and running:

$ python -m zipapp myapp
$ python myapp.pyz

The module implementation has been contributed by Paul Moore in bpo-23491 [https://bugs.python.org/issue?@action=redirect&bpo=23491].

더 보기

PEP 441 [https://www.python.org/dev/peps/pep-0441] – Improving Python ZIP Application Support

Improved Modules

argparse

The ArgumentParser class now allows disabling abbreviated usage of long options by setting allow_abbrev to False. (Contributed by Jonathan Paugh, Steven Bethard, paul j3 and Daniel Eriksson in bpo-14910 [https://bugs.python.org/issue?@action=redirect&bpo=14910].)

asyncio

Since the asyncio module is provisional, all changes introduced in Python 3.5 have also been backported to Python 3.4.x.

Notable changes in the asyncio module since Python 3.4.0:

New debugging APIs: loop.set_debug() and loop.get_debug() methods. (Contributed by Victor Stinner.)

The proactor event loop now supports SSL. (Contributed by Antoine Pitrou and Victor Stinner in bpo-22560 [https://bugs.python.org/issue?@action=redirect&bpo=22560].)

A new loop.is_closed() method to check if the event loop is closed. (Contributed by Victor Stinner in bpo-21326 [https://bugs.python.org/issue?@action=redirect&bpo=21326].)

A new loop.create_task() to conveniently create and schedule a new Task for a coroutine. The create_task method is also used by all asyncio functions that wrap coroutines into tasks, such as asyncio.wait(), asyncio.gather(), etc. (Contributed by Victor Stinner.)

A new transport.get_write_buffer_limits() method to inquire for high- and low- water limits of the flow control. (Contributed by Victor Stinner.)

The async() function is deprecated in favor of ensure_future(). (Contributed by Yury Selivanov.)

New loop.set_task_factory() and loop.get_task_factory() methods to customize the task factory that loop.create_task() method uses. (Contributed by Yury Selivanov.)

New Queue.join() and Queue.task_done() queue methods. (Contributed by Victor Stinner.)

The JoinableQueue class was removed, in favor of the asyncio.Queue class. (Contributed by Victor Stinner.)

Updates in 3.5.1:

The ensure_future() function and all functions that use it, such as loop.run_until_complete(), now accept all kinds of awaitable objects. (Contributed by Yury Selivanov.)

New run_coroutine_threadsafe() function to submit coroutines to event loops from other threads. (Contributed by Vincent Michel.)

New Transport.is_closing() method to check if the transport is closing or closed. (Contributed by Yury Selivanov.)

The loop.create_server() method can now accept a list of hosts. (Contributed by Yann Sionneau.)

Updates in 3.5.2:

New loop.create_future() method to create Future objects. This allows alternative event loop implementations, such as uvloop [https://github.com/MagicStack/uvloop], to provide a faster asyncio.Future implementation. (Contributed by Yury Selivanov.)

New loop.get_exception_handler() method to get the current exception handler. (Contributed by Yury Selivanov.)

New StreamReader.readuntil() method to read data from the stream until a separator bytes sequence appears. (Contributed by Mark Korenberg.)

The loop.create_connection() and loop.create_server() methods are optimized to avoid calling the system getaddrinfo function if the address is already resolved. (Contributed by A. Jesse Jiryu Davis.)

The loop.sock_connect(sock, address) no longer requires the address to be resolved prior to the call. (Contributed by A. Jesse Jiryu Davis.)

bz2

The BZ2Decompressor.decompress method now accepts an optional max_length argument to limit the maximum size of decompressed data. (Contributed by Nikolaus Rath in bpo-15955 [https://bugs.python.org/issue?@action=redirect&bpo=15955].)

cgi

The FieldStorage class now supports the context manager protocol. (Contributed by Berker Peksag in bpo-20289 [https://bugs.python.org/issue?@action=redirect&bpo=20289].)

cmath

A new function isclose() provides a way to test for approximate equality. (Contributed by Chris Barker and Tal Einat in bpo-24270 [https://bugs.python.org/issue?@action=redirect&bpo=24270].)

code

The InteractiveInterpreter.showtraceback() method now prints the full chained traceback, just like the interactive interpreter. (Contributed by Claudiu Popa in bpo-17442 [https://bugs.python.org/issue?@action=redirect&bpo=17442].)

collections

The OrderedDict class is now implemented in C, which makes it 4 to 100 times faster. (Contributed by Eric Snow in bpo-16991 [https://bugs.python.org/issue?@action=redirect&bpo=16991].)

OrderedDict.items(), OrderedDict.keys(), OrderedDict.values() views now support reversed() iteration. (Contributed by Serhiy Storchaka in bpo-19505 [https://bugs.python.org/issue?@action=redirect&bpo=19505].)

The deque class now defines index(), insert(), and copy(), and supports the + and * operators. This allows deques to be recognized as a MutableSequence and improves their substitutability for lists. (Contributed by Raymond Hettinger in bpo-23704 [https://bugs.python.org/issue?@action=redirect&bpo=23704].)

Docstrings produced by namedtuple() can now be updated:

Point = namedtuple('Point', ['x', 'y'])
Point.__doc__ += ': Cartesian coodinate'
Point.x.__doc__ = 'abscissa'
Point.y.__doc__ = 'ordinate'

(Contributed by Berker Peksag in bpo-24064 [https://bugs.python.org/issue?@action=redirect&bpo=24064].)

The UserString class now implements the __getnewargs__(), __rmod__(), casefold(), format_map(), isprintable(), and maketrans() methods to match the corresponding methods of str. (Contributed by Joe Jevnik in bpo-22189 [https://bugs.python.org/issue?@action=redirect&bpo=22189].)

collections.abc

The Sequence.index() method now accepts start and stop arguments to match the corresponding methods of tuple, list, etc. (Contributed by Devin Jeanpierre in bpo-23086 [https://bugs.python.org/issue?@action=redirect&bpo=23086].)

A new Generator abstract base class. (Contributed by Stefan Behnel in bpo-24018 [https://bugs.python.org/issue?@action=redirect&bpo=24018].)

New Awaitable, Coroutine, AsyncIterator, and AsyncIterable abstract base classes. (Contributed by Yury Selivanov in bpo-24184 [https://bugs.python.org/issue?@action=redirect&bpo=24184].)

For earlier Python versions, a backport of the new ABCs is available in an external PyPI package [https://pypi.org/project/backports_abc].

compileall

A new compileall option, -j N, allows running N workers simultaneously to perform parallel bytecode compilation. The compile_dir() function has a corresponding workers parameter. (Contributed by Claudiu Popa in bpo-16104 [https://bugs.python.org/issue?@action=redirect&bpo=16104].)

Another new option, -r, allows controlling the maximum recursion level for subdirectories. (Contributed by Claudiu Popa in bpo-19628 [https://bugs.python.org/issue?@action=redirect&bpo=19628].)

The -q command line option can now be specified more than once, in which case all output, including errors, will be suppressed. The corresponding quiet parameter in compile_dir(), compile_file(), and compile_path() can now accept an integer value indicating the level of output suppression. (Contributed by Thomas Kluyver in bpo-21338 [https://bugs.python.org/issue?@action=redirect&bpo=21338].)

concurrent.futures

The Executor.map() method now accepts a chunksize argument to allow batching of tasks to improve performance when ProcessPoolExecutor() is used. (Contributed by Dan O’Reilly in bpo-11271 [https://bugs.python.org/issue?@action=redirect&bpo=11271].)

The number of workers in the ThreadPoolExecutor constructor is optional now. The default value is 5 times the number of CPUs. (Contributed by Claudiu Popa in bpo-21527 [https://bugs.python.org/issue?@action=redirect&bpo=21527].)

configparser

configparser now provides a way to customize the conversion of values by specifying a dictionary of converters in the ConfigParser constructor, or by defining them as methods in ConfigParser subclasses. Converters defined in a parser instance are inherited by its section proxies.

Example:

>>> import configparser
>>> conv = {}
>>> conv['list'] = lambda v: [e.strip() for e in v.split() if e.strip()]
>>> cfg = configparser.ConfigParser(converters=conv)
>>> cfg.read_string("""
... [s]
... list = a b c d e f g
... """)
>>> cfg.get('s', 'list')
'a b c d e f g'
>>> cfg.getlist('s', 'list')
['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> section = cfg['s']
>>> section.getlist('list')
['a', 'b', 'c', 'd', 'e', 'f', 'g']

(Contributed by Łukasz Langa in bpo-18159 [https://bugs.python.org/issue?@action=redirect&bpo=18159].)

contextlib

The new redirect_stderr() context manager (similar to redirect_stdout()) makes it easier for utility scripts to handle inflexible APIs that write their output to sys.stderr and don’t provide any options to redirect it:

>>> import contextlib, io, logging
>>> f = io.StringIO()
>>> with contextlib.redirect_stderr(f):
...     logging.warning('warning')
...
>>> f.getvalue()
'WARNING:root:warning\n'

(Contributed by Berker Peksag in bpo-22389 [https://bugs.python.org/issue?@action=redirect&bpo=22389].)

csv

The writerow() method now supports arbitrary iterables, not just sequences. (Contributed by Serhiy Storchaka in bpo-23171 [https://bugs.python.org/issue?@action=redirect&bpo=23171].)

curses

The new update_lines_cols() function updates the LINES and COLS environment variables. This is useful for detecting manual screen resizing. (Contributed by Arnon Yaari in bpo-4254 [https://bugs.python.org/issue?@action=redirect&bpo=4254].)

dbm

dumb.open always creates a new database when the flag has the value "n". (Contributed by Claudiu Popa in bpo-18039 [https://bugs.python.org/issue?@action=redirect&bpo=18039].)

difflib

The charset of HTML documents generated by HtmlDiff.make_file() can now be customized by using a new charset keyword-only argument. The default charset of HTML document changed from "ISO-8859-1" to "utf-8". (Contributed by Berker Peksag in bpo-2052 [https://bugs.python.org/issue?@action=redirect&bpo=2052].)

The diff_bytes() function can now compare lists of byte strings. This fixes a regression from Python 2. (Contributed by Terry J. Reedy and Greg Ward in bpo-17445 [https://bugs.python.org/issue?@action=redirect&bpo=17445].)

distutils

Both the build and build_ext commands now accept a -j option to enable parallel building of extension modules. (Contributed by Antoine Pitrou in bpo-5309 [https://bugs.python.org/issue?@action=redirect&bpo=5309].)

The distutils module now supports xz compression, and can be enabled by passing xztar as an argument to bdist --format. (Contributed by Serhiy Storchaka in bpo-16314 [https://bugs.python.org/issue?@action=redirect&bpo=16314].)

doctest

The DocTestSuite() function returns an empty unittest.TestSuite if module contains no docstrings, instead of raising ValueError. (Contributed by Glenn Jones in bpo-15916 [https://bugs.python.org/issue?@action=redirect&bpo=15916].)

email

A new policy option Policy.mangle_from_ controls whether or not lines that start with "From " in email bodies are prefixed with a ">" character by generators. The default is True for compat32 and False for all other policies. (Contributed by Milan Oberkirch in bpo-20098 [https://bugs.python.org/issue?@action=redirect&bpo=20098].)

A new Message.get_content_disposition() method provides easy access to a canonical value for the Content-Disposition header. (Contributed by Abhilash Raj in bpo-21083 [https://bugs.python.org/issue?@action=redirect&bpo=21083].)

A new policy option EmailPolicy.utf8 can be set to True to encode email headers using the UTF-8 charset instead of using encoded words. This allows Messages to be formatted according to RFC 6532 [https://tools.ietf.org/html/rfc6532.html] and used with an SMTP server that supports the RFC 6531 [https://tools.ietf.org/html/rfc6531.html] SMTPUTF8 extension. (Contributed by R. David Murray in bpo-24211 [https://bugs.python.org/issue?@action=redirect&bpo=24211].)

The mime.text.MIMEText constructor now accepts a charset.Charset instance. (Contributed by Claude Paroz and Berker Peksag in bpo-16324 [https://bugs.python.org/issue?@action=redirect&bpo=16324].)

enum

The Enum callable has a new parameter start to specify the initial number of enum values if only names are provided:

>>> Animal = enum.Enum('Animal', 'cat dog', start=10)
>>> Animal.cat
<Animal.cat: 10>
>>> Animal.dog
<Animal.dog: 11>

(Contributed by Ethan Furman in bpo-21706 [https://bugs.python.org/issue?@action=redirect&bpo=21706].)

faulthandler

The enable(), register(), dump_traceback() and dump_traceback_later() functions now accept file descriptors in addition to file-like objects. (Contributed by Wei Wu in bpo-23566 [https://bugs.python.org/issue?@action=redirect&bpo=23566].)

functools

Most of the lru_cache() machinery is now implemented in C, making it significantly faster. (Contributed by Matt Joiner, Alexey Kachayev, and Serhiy Storchaka in bpo-14373 [https://bugs.python.org/issue?@action=redirect&bpo=14373].)

glob

The iglob() and glob() functions now support recursive search in subdirectories, using the "**" pattern. (Contributed by Serhiy Storchaka in bpo-13968 [https://bugs.python.org/issue?@action=redirect&bpo=13968].)

gzip

The mode argument of the GzipFile constructor now accepts "x" to request exclusive creation. (Contributed by Tim Heaney in bpo-19222 [https://bugs.python.org/issue?@action=redirect&bpo=19222].)

heapq

Element comparison in merge() can now be customized by passing a key function in a new optional key keyword argument, and a new optional reverse keyword argument can be used to reverse element comparison:

>>> import heapq
>>> a = ['9', '777', '55555']
>>> b = ['88', '6666']
>>> list(heapq.merge(a, b, key=len))
['9', '88', '777', '6666', '55555']
>>> list(heapq.merge(reversed(a), reversed(b), key=len, reverse=True))
['55555', '6666', '777', '88', '9']

(Contributed by Raymond Hettinger in bpo-13742 [https://bugs.python.org/issue?@action=redirect&bpo=13742].)

http

A new HTTPStatus enum that defines a set of HTTP status codes, reason phrases and long descriptions written in English. (Contributed by Demian Brecht in bpo-21793 [https://bugs.python.org/issue?@action=redirect&bpo=21793].)

http.client

HTTPConnection.getresponse() now raises a RemoteDisconnected exception when a remote server connection is closed unexpectedly. Additionally, if a ConnectionError (of which RemoteDisconnected is a subclass) is raised, the client socket is now closed automatically, and will reconnect on the next request:

import http.client
conn = http.client.HTTPConnection('www.python.org')
for retries in range(3):
    try:
        conn.request('GET', '/')
        resp = conn.getresponse()
    except http.client.RemoteDisconnected:
        pass

(Contributed by Martin Panter in bpo-3566 [https://bugs.python.org/issue?@action=redirect&bpo=3566].)

idlelib and IDLE

Since idlelib implements the IDLE shell and editor and is not intended for import by other programs, it gets improvements with every release. See Lib/idlelib/NEWS.txt for a cumulative list of changes since 3.4.0, as well as changes made in future 3.5.x releases. This file is also available from the IDLE Help ‣ About IDLE dialog.

imaplib

The IMAP4 class now supports the context manager protocol. When used in a with statement, the IMAP4 LOGOUT command will be called automatically at the end of the block. (Contributed by Tarek Ziadé and Serhiy Storchaka in bpo-4972 [https://bugs.python.org/issue?@action=redirect&bpo=4972].)

The imaplib module now supports RFC 5161 [https://tools.ietf.org/html/rfc5161.html] (ENABLE Extension) and RFC 6855 [https://tools.ietf.org/html/rfc6855.html] (UTF-8 Support) via the IMAP4.enable() method. A new IMAP4.utf8_enabled attribute tracks whether or not RFC 6855 [https://tools.ietf.org/html/rfc6855.html] support is enabled. (Contributed by Milan Oberkirch, R. David Murray, and Maciej Szulik in bpo-21800 [https://bugs.python.org/issue?@action=redirect&bpo=21800].)

The imaplib module now automatically encodes non-ASCII string usernames and passwords using UTF-8, as recommended by the RFCs. (Contributed by Milan Oberkirch in bpo-21800 [https://bugs.python.org/issue?@action=redirect&bpo=21800].)

imghdr

The what() function now recognizes the OpenEXR [http://www.openexr.com] format (contributed by Martin Vignali and Claudiu Popa in bpo-20295 [https://bugs.python.org/issue?@action=redirect&bpo=20295]), and the WebP [https://en.wikipedia.org/wiki/WebP] format (contributed by Fabrice Aneche and Claudiu Popa in bpo-20197 [https://bugs.python.org/issue?@action=redirect&bpo=20197].)

importlib

The util.LazyLoader class allows for lazy loading of modules in applications where startup time is important. (Contributed by Brett Cannon in bpo-17621 [https://bugs.python.org/issue?@action=redirect&bpo=17621].)

The abc.InspectLoader.source_to_code() method is now a static method. This makes it easier to initialize a module object with code compiled from a string by running exec(code, module.__dict__). (Contributed by Brett Cannon in bpo-21156 [https://bugs.python.org/issue?@action=redirect&bpo=21156].)

The new util.module_from_spec() function is now the preferred way to create a new module. As opposed to creating a types.ModuleType instance directly, this new function will set the various import-controlled attributes based on the passed-in spec object. (Contributed by Brett Cannon in bpo-20383 [https://bugs.python.org/issue?@action=redirect&bpo=20383].)

inspect

Both the Signature and Parameter classes are now picklable and hashable. (Contributed by Yury Selivanov in bpo-20726 [https://bugs.python.org/issue?@action=redirect&bpo=20726] and bpo-20334 [https://bugs.python.org/issue?@action=redirect&bpo=20334].)

A new BoundArguments.apply_defaults() method provides a way to set default values for missing arguments:

>>> def foo(a, b='ham', *args): pass
>>> ba = inspect.signature(foo).bind('spam')
>>> ba.apply_defaults()
>>> ba.arguments
OrderedDict([('a', 'spam'), ('b', 'ham'), ('args', ())])

(Contributed by Yury Selivanov in bpo-24190 [https://bugs.python.org/issue?@action=redirect&bpo=24190].)

A new class method Signature.from_callable() makes subclassing of Signature easier. (Contributed by Yury Selivanov and Eric Snow in bpo-17373 [https://bugs.python.org/issue?@action=redirect&bpo=17373].)

The signature() function now accepts a follow_wrapped optional keyword argument, which, when set to False, disables automatic following of __wrapped__ links. (Contributed by Yury Selivanov in bpo-20691 [https://bugs.python.org/issue?@action=redirect&bpo=20691].)

A set of new functions to inspect coroutine functions and coroutine objects has been added: iscoroutine(), iscoroutinefunction(), isawaitable(), getcoroutinelocals(), and getcoroutinestate(). (Contributed by Yury Selivanov in bpo-24017 [https://bugs.python.org/issue?@action=redirect&bpo=24017] and bpo-24400 [https://bugs.python.org/issue?@action=redirect&bpo=24400].)

The stack(), trace(), getouterframes(), and getinnerframes() functions now return a list of named tuples. (Contributed by Daniel Shahaf in bpo-16808 [https://bugs.python.org/issue?@action=redirect&bpo=16808].)

io

A new BufferedIOBase.readinto1() method, that uses at most one call to the underlying raw stream’s RawIOBase.read() or RawIOBase.readinto() methods. (Contributed by Nikolaus Rath in bpo-20578 [https://bugs.python.org/issue?@action=redirect&bpo=20578].)

ipaddress

Both the IPv4Network and IPv6Network classes now accept an (address, netmask) tuple argument, so as to easily construct network objects from existing addresses:

>>> import ipaddress
>>> ipaddress.IPv4Network(('127.0.0.0', 8))
IPv4Network('127.0.0.0/8')
>>> ipaddress.IPv4Network(('127.0.0.0', '255.0.0.0'))
IPv4Network('127.0.0.0/8')

(Contributed by Peter Moody and Antoine Pitrou in bpo-16531 [https://bugs.python.org/issue?@action=redirect&bpo=16531].)

A new reverse_pointer attribute for the IPv4Network and IPv6Network classes returns the name of the reverse DNS PTR record:

>>> import ipaddress
>>> addr = ipaddress.IPv4Address('127.0.0.1')
>>> addr.reverse_pointer
'1.0.0.127.in-addr.arpa'
>>> addr6 = ipaddress.IPv6Address('::1')
>>> addr6.reverse_pointer
'1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.ip6.arpa'

(Contributed by Leon Weber in bpo-20480 [https://bugs.python.org/issue?@action=redirect&bpo=20480].)

json

The json.tool command line interface now preserves the order of keys in JSON objects passed in input. The new --sort-keys option can be used to sort the keys alphabetically. (Contributed by Berker Peksag in bpo-21650 [https://bugs.python.org/issue?@action=redirect&bpo=21650].)

JSON decoder now raises JSONDecodeError instead of ValueError to provide better context information about the error. (Contributed by Serhiy Storchaka in bpo-19361 [https://bugs.python.org/issue?@action=redirect&bpo=19361].)

linecache

A new lazycache() function can be used to capture information about a non-file-based module to permit getting its lines later via getline(). This avoids doing I/O until a line is actually needed, without having to carry the module globals around indefinitely. (Contributed by Robert Collins in bpo-17911 [https://bugs.python.org/issue?@action=redirect&bpo=17911].)

locale

A new delocalize() function can be used to convert a string into a normalized number string, taking the LC_NUMERIC settings into account:

>>> import locale
>>> locale.setlocale(locale.LC_NUMERIC, 'de_DE.UTF-8')
'de_DE.UTF-8'
>>> locale.delocalize('1.234,56')
'1234.56'
>>> locale.setlocale(locale.LC_NUMERIC, 'en_US.UTF-8')
'en_US.UTF-8'
>>> locale.delocalize('1,234.56')
'1234.56'

(Contributed by Cédric Krier in bpo-13918 [https://bugs.python.org/issue?@action=redirect&bpo=13918].)

logging

All logging methods (Logger log(), exception(), critical(), debug(), etc.), now accept exception instances as an exc_info argument, in addition to boolean values and exception tuples:

>>> import logging
>>> try:
...     1/0
... except ZeroDivisionError as ex:
...     logging.error('exception', exc_info=ex)
ERROR:root:exception

(Contributed by Yury Selivanov in bpo-20537 [https://bugs.python.org/issue?@action=redirect&bpo=20537].)

The handlers.HTTPHandler class now accepts an optional ssl.SSLContext instance to configure SSL settings used in an HTTP connection. (Contributed by Alex Gaynor in bpo-22788 [https://bugs.python.org/issue?@action=redirect&bpo=22788].)

The handlers.QueueListener class now takes a respect_handler_level keyword argument which, if set to True, will pass messages to handlers taking handler levels into account. (Contributed by Vinay Sajip.)

lzma

The LZMADecompressor.decompress() method now accepts an optional max_length argument to limit the maximum size of decompressed data. (Contributed by Martin Panter in bpo-15955 [https://bugs.python.org/issue?@action=redirect&bpo=15955].)

math

Two new constants have been added to the math module: inf and nan. (Contributed by Mark Dickinson in bpo-23185 [https://bugs.python.org/issue?@action=redirect&bpo=23185].)

A new function isclose() provides a way to test for approximate equality. (Contributed by Chris Barker and Tal Einat in bpo-24270 [https://bugs.python.org/issue?@action=redirect&bpo=24270].)

A new gcd() function has been added. The fractions.gcd() function is now deprecated. (Contributed by Mark Dickinson and Serhiy Storchaka in bpo-22486 [https://bugs.python.org/issue?@action=redirect&bpo=22486].)

multiprocessing

sharedctypes.synchronized() objects now support the context manager protocol. (Contributed by Charles-François Natali in bpo-21565 [https://bugs.python.org/issue?@action=redirect&bpo=21565].)

operator

attrgetter(), itemgetter(), and methodcaller() objects now support pickling. (Contributed by Josh Rosenberg and Serhiy Storchaka in bpo-22955 [https://bugs.python.org/issue?@action=redirect&bpo=22955].)

New matmul() and imatmul() functions to perform matrix multiplication. (Contributed by Benjamin Peterson in bpo-21176 [https://bugs.python.org/issue?@action=redirect&bpo=21176].)

os

The new scandir() function returning an iterator of DirEntry objects has been added. If possible, scandir() extracts file attributes while scanning a directory, removing the need to perform subsequent system calls to determine file type or attributes, which may significantly improve performance. (Contributed by Ben Hoyt with the help of Victor Stinner in bpo-22524 [https://bugs.python.org/issue?@action=redirect&bpo=22524].)

On Windows, a new stat_result.st_file_attributes attribute is now available. It corresponds to the dwFileAttributes member of the BY_HANDLE_FILE_INFORMATION structure returned by GetFileInformationByHandle(). (Contributed by Ben Hoyt in bpo-21719 [https://bugs.python.org/issue?@action=redirect&bpo=21719].)

The urandom() function now uses the getrandom() syscall on Linux 3.17 or newer, and getentropy() on OpenBSD 5.6 and newer, removing the need to use /dev/urandom and avoiding failures due to potential file descriptor exhaustion. (Contributed by Victor Stinner in bpo-22181 [https://bugs.python.org/issue?@action=redirect&bpo=22181].)

New get_blocking() and set_blocking() functions allow getting and setting a file descriptor’s blocking mode (O_NONBLOCK.) (Contributed by Victor Stinner in bpo-22054 [https://bugs.python.org/issue?@action=redirect&bpo=22054].)

The truncate() and ftruncate() functions are now supported on Windows. (Contributed by Steve Dower in bpo-23668 [https://bugs.python.org/issue?@action=redirect&bpo=23668].)

There is a new os.path.commonpath() function returning the longest common sub-path of each passed pathname. Unlike the os.path.commonprefix() function, it always returns a valid path:

>>> os.path.commonprefix(['/usr/lib', '/usr/local/lib'])
'/usr/l'

>>> os.path.commonpath(['/usr/lib', '/usr/local/lib'])
'/usr'

(Contributed by Rafik Draoui and Serhiy Storchaka in bpo-10395 [https://bugs.python.org/issue?@action=redirect&bpo=10395].)

pathlib

The new Path.samefile() method can be used to check whether the path points to the same file as another path, which can be either another Path object, or a string:

>>> import pathlib
>>> p1 = pathlib.Path('/etc/hosts')
>>> p2 = pathlib.Path('/etc/../etc/hosts')
>>> p1.samefile(p2)
True

(Contributed by Vajrasky Kok and Antoine Pitrou in bpo-19775 [https://bugs.python.org/issue?@action=redirect&bpo=19775].)

The Path.mkdir() method now accepts a new optional exist_ok argument to match mkdir -p and os.makedirs() functionality. (Contributed by Berker Peksag in bpo-21539 [https://bugs.python.org/issue?@action=redirect&bpo=21539].)

There is a new Path.expanduser() method to expand ~ and ~user prefixes. (Contributed by Serhiy Storchaka and Claudiu Popa in bpo-19776 [https://bugs.python.org/issue?@action=redirect&bpo=19776].)

A new Path.home() class method can be used to get a Path instance representing the user’s home directory. (Contributed by Victor Salgado and Mayank Tripathi in bpo-19777 [https://bugs.python.org/issue?@action=redirect&bpo=19777].)

New Path.write_text(), Path.read_text(), Path.write_bytes(), Path.read_bytes() methods to simplify read/write operations on files.

The following code snippet will create or rewrite existing file ~/spam42:

>>> import pathlib
>>> p = pathlib.Path('~/spam42')
>>> p.expanduser().write_text('ham')
3

(Contributed by Christopher Welborn in bpo-20218 [https://bugs.python.org/issue?@action=redirect&bpo=20218].)

pickle

Nested objects, such as unbound methods or nested classes, can now be pickled using pickle protocols older than protocol version 4. Protocol version 4 already supports these cases. (Contributed by Serhiy Storchaka in bpo-23611 [https://bugs.python.org/issue?@action=redirect&bpo=23611].)

poplib

A new POP3.utf8() command enables RFC 6856 [https://tools.ietf.org/html/rfc6856.html] (Internationalized Email) support, if a POP server supports it. (Contributed by Milan OberKirch in bpo-21804 [https://bugs.python.org/issue?@action=redirect&bpo=21804].)

re

References and conditional references to groups with fixed length are now allowed in lookbehind assertions:

>>> import re
>>> pat = re.compile(r'(a|b).(?<=\1)c')
>>> pat.match('aac')
<_sre.SRE_Match object; span=(0, 3), match='aac'>
>>> pat.match('bbc')
<_sre.SRE_Match object; span=(0, 3), match='bbc'>

(Contributed by Serhiy Storchaka in bpo-9179 [https://bugs.python.org/issue?@action=redirect&bpo=9179].)

The number of capturing groups in regular expressions is no longer limited to 100. (Contributed by Serhiy Storchaka in bpo-22437 [https://bugs.python.org/issue?@action=redirect&bpo=22437].)

The sub() and subn() functions now replace unmatched groups with empty strings instead of raising an exception. (Contributed by Serhiy Storchaka in bpo-1519638 [https://bugs.python.org/issue?@action=redirect&bpo=1519638].)

The re.error exceptions have new attributes, msg, pattern, pos, lineno, and colno, that provide better context information about the error:

>>> re.compile("""
...     (?x)
...     .++
... """)
Traceback (most recent call last):
   ...
sre_constants.error: multiple repeat at position 16 (line 3, column 7)

(Contributed by Serhiy Storchaka in bpo-22578 [https://bugs.python.org/issue?@action=redirect&bpo=22578].)

readline

A new append_history_file() function can be used to append the specified number of trailing elements in history to the given file. (Contributed by Bruno Cauet in bpo-22940 [https://bugs.python.org/issue?@action=redirect&bpo=22940].)

selectors

The new DevpollSelector supports efficient /dev/poll polling on Solaris. (Contributed by Giampaolo Rodola’ in bpo-18931 [https://bugs.python.org/issue?@action=redirect&bpo=18931].)

shutil

The move() function now accepts a copy_function argument, allowing, for example, the copy() function to be used instead of the default copy2() if there is a need to ignore file metadata when moving. (Contributed by Claudiu Popa in bpo-19840 [https://bugs.python.org/issue?@action=redirect&bpo=19840].)

The make_archive() function now supports the xztar format. (Contributed by Serhiy Storchaka in bpo-5411 [https://bugs.python.org/issue?@action=redirect&bpo=5411].)

signal

On Windows, the set_wakeup_fd() function now also supports socket handles. (Contributed by Victor Stinner in bpo-22018 [https://bugs.python.org/issue?@action=redirect&bpo=22018].)

Various SIG* constants in the signal module have been converted into Enums. This allows meaningful names to be printed during debugging, instead of integer “magic numbers”. (Contributed by Giampaolo Rodola’ in bpo-21076 [https://bugs.python.org/issue?@action=redirect&bpo=21076].)

smtpd

Both the SMTPServer and SMTPChannel classes now accept a decode_data keyword argument to determine if the DATA portion of the SMTP transaction is decoded using the "utf-8" codec or is instead provided to the SMTPServer.process_message() method as a byte string. The default is True for backward compatibility reasons, but will change to False in Python 3.6. If decode_data is set to False, the process_message method must be prepared to accept keyword arguments. (Contributed by Maciej Szulik in bpo-19662 [https://bugs.python.org/issue?@action=redirect&bpo=19662].)

The SMTPServer class now advertises the 8BITMIME extension (RFC 6152 [https://tools.ietf.org/html/rfc6152.html]) if decode_data has been set True. If the client specifies BODY=8BITMIME on the MAIL command, it is passed to SMTPServer.process_message() via the mail_options keyword. (Contributed by Milan Oberkirch and R. David Murray in bpo-21795 [https://bugs.python.org/issue?@action=redirect&bpo=21795].)

The SMTPServer class now also supports the SMTPUTF8 extension (RFC 6531 [https://tools.ietf.org/html/rfc6531.html]: Internationalized Email). If the client specified SMTPUTF8 BODY=8BITMIME on the MAIL command, they are passed to SMTPServer.process_message() via the mail_options keyword. It is the responsibility of the process_message method to correctly handle the SMTPUTF8 data. (Contributed by Milan Oberkirch in bpo-21725 [https://bugs.python.org/issue?@action=redirect&bpo=21725].)

It is now possible to provide, directly or via name resolution, IPv6 addresses in the SMTPServer constructor, and have it successfully connect. (Contributed by Milan Oberkirch in bpo-14758 [https://bugs.python.org/issue?@action=redirect&bpo=14758].)

smtplib

A new SMTP.auth() method provides a convenient way to implement custom authentication mechanisms. (Contributed by Milan Oberkirch in bpo-15014 [https://bugs.python.org/issue?@action=redirect&bpo=15014].)

The SMTP.set_debuglevel() method now accepts an additional debuglevel (2), which enables timestamps in debug messages. (Contributed by Gavin Chappell and Maciej Szulik in bpo-16914 [https://bugs.python.org/issue?@action=redirect&bpo=16914].)

Both the SMTP.sendmail() and SMTP.send_message() methods now support RFC 6531 [https://tools.ietf.org/html/rfc6531.html] (SMTPUTF8). (Contributed by Milan Oberkirch and R. David Murray in bpo-22027 [https://bugs.python.org/issue?@action=redirect&bpo=22027].)

sndhdr

The what() and whathdr() functions now return a namedtuple(). (Contributed by Claudiu Popa in bpo-18615 [https://bugs.python.org/issue?@action=redirect&bpo=18615].)

socket

Functions with timeouts now use a monotonic clock, instead of a system clock. (Contributed by Victor Stinner in bpo-22043 [https://bugs.python.org/issue?@action=redirect&bpo=22043].)

A new socket.sendfile() method allows sending a file over a socket by using the high-performance os.sendfile() function on UNIX, resulting in uploads being from 2 to 3 times faster than when using plain socket.send(). (Contributed by Giampaolo Rodola’ in bpo-17552 [https://bugs.python.org/issue?@action=redirect&bpo=17552].)

The socket.sendall() method no longer resets the socket timeout every time bytes are received or sent. The socket timeout is now the maximum total duration to send all data. (Contributed by Victor Stinner in bpo-23853 [https://bugs.python.org/issue?@action=redirect&bpo=23853].)

The backlog argument of the socket.listen() method is now optional. By default it is set to SOMAXCONN or to 128, whichever is less. (Contributed by Charles-François Natali in bpo-21455 [https://bugs.python.org/issue?@action=redirect&bpo=21455].)

ssl

Memory BIO Support

(Contributed by Geert Jansen in bpo-21965 [https://bugs.python.org/issue?@action=redirect&bpo=21965].)

The new SSLObject class has been added to provide SSL protocol support for cases when the network I/O capabilities of SSLSocket are not necessary or are suboptimal. SSLObject represents an SSL protocol instance, but does not implement any network I/O methods, and instead provides a memory buffer interface. The new MemoryBIO class can be used to pass data between Python and an SSL protocol instance.

The memory BIO SSL support is primarily intended to be used in frameworks implementing asynchronous I/O for which SSLSocket’s readiness model (“select/poll”) is inefficient.

A new SSLContext.wrap_bio() method can be used to create a new SSLObject instance.

Application-Layer Protocol Negotiation Support

(Contributed by Benjamin Peterson in bpo-20188 [https://bugs.python.org/issue?@action=redirect&bpo=20188].)

Where OpenSSL support is present, the ssl module now implements the Application-Layer Protocol Negotiation TLS extension as described in RFC 7301 [https://tools.ietf.org/html/rfc7301.html].

The new SSLContext.set_alpn_protocols() can be used to specify which protocols a socket should advertise during the TLS handshake.

The new SSLSocket.selected_alpn_protocol() returns the protocol that was selected during the TLS handshake. The HAS_ALPN flag indicates whether ALPN support is present.

Other Changes

There is a new SSLSocket.version() method to query the actual protocol version in use. (Contributed by Antoine Pitrou in bpo-20421 [https://bugs.python.org/issue?@action=redirect&bpo=20421].)

The SSLSocket class now implements a SSLSocket.sendfile() method. (Contributed by Giampaolo Rodola’ in bpo-17552 [https://bugs.python.org/issue?@action=redirect&bpo=17552].)

The SSLSocket.send() method now raises either the ssl.SSLWantReadError or ssl.SSLWantWriteError exception on a non-blocking socket if the operation would block. Previously, it would return 0. (Contributed by Nikolaus Rath in bpo-20951 [https://bugs.python.org/issue?@action=redirect&bpo=20951].)

The cert_time_to_seconds() function now interprets the input time as UTC and not as local time, per RFC 5280 [https://tools.ietf.org/html/rfc5280.html]. Additionally, the return value is always an int. (Contributed by Akira Li in bpo-19940 [https://bugs.python.org/issue?@action=redirect&bpo=19940].)

New SSLObject.shared_ciphers() and SSLSocket.shared_ciphers() methods return the list of ciphers sent by the client during the handshake. (Contributed by Benjamin Peterson in bpo-23186 [https://bugs.python.org/issue?@action=redirect&bpo=23186].)

The SSLSocket.do_handshake(), SSLSocket.read(), SSLSocket.shutdown(), and SSLSocket.write() methods of the SSLSocket class no longer reset the socket timeout every time bytes are received or sent. The socket timeout is now the maximum total duration of the method. (Contributed by Victor Stinner in bpo-23853 [https://bugs.python.org/issue?@action=redirect&bpo=23853].)

The match_hostname() function now supports matching of IP addresses. (Contributed by Antoine Pitrou in bpo-23239 [https://bugs.python.org/issue?@action=redirect&bpo=23239].)

sqlite3

The Row class now fully supports the sequence protocol, in particular reversed() iteration and slice indexing. (Contributed by Claudiu Popa in bpo-10203 [https://bugs.python.org/issue?@action=redirect&bpo=10203]; by Lucas Sinclair, Jessica McKellar, and Serhiy Storchaka in bpo-13583 [https://bugs.python.org/issue?@action=redirect&bpo=13583].)

subprocess

The new run() function has been added. It runs the specified command and returns a CompletedProcess object, which describes a finished process. The new API is more consistent and is the recommended approach to invoking subprocesses in Python code that does not need to maintain compatibility with earlier Python versions. (Contributed by Thomas Kluyver in bpo-23342 [https://bugs.python.org/issue?@action=redirect&bpo=23342].)

Examples:

>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], stdout=subprocess.PIPE)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n')

sys

A new set_coroutine_wrapper() function allows setting a global hook that will be called whenever a coroutine object is created by an async def function. A corresponding get_coroutine_wrapper() can be used to obtain a currently set wrapper. Both functions are provisional, and are intended for debugging purposes only. (Contributed by Yury Selivanov in bpo-24017 [https://bugs.python.org/issue?@action=redirect&bpo=24017].)

A new is_finalizing() function can be used to check if the Python interpreter is shutting down. (Contributed by Antoine Pitrou in bpo-22696 [https://bugs.python.org/issue?@action=redirect&bpo=22696].)

sysconfig

The name of the user scripts directory on Windows now includes the first two components of the Python version. (Contributed by Paul Moore in bpo-23437 [https://bugs.python.org/issue?@action=redirect&bpo=23437].)

tarfile

The mode argument of the open() function now accepts "x" to request exclusive creation. (Contributed by Berker Peksag in bpo-21717 [https://bugs.python.org/issue?@action=redirect&bpo=21717].)

The TarFile.extractall() and TarFile.extract() methods now take a keyword argument numeric_owner. If set to True, the extracted files and directories will be owned by the numeric uid and gid from the tarfile. If set to False (the default, and the behavior in versions prior to 3.5), they will be owned by the named user and group in the tarfile. (Contributed by Michael Vogt and Eric Smith in bpo-23193 [https://bugs.python.org/issue?@action=redirect&bpo=23193].)

The TarFile.list() now accepts an optional members keyword argument that can be set to a subset of the list returned by TarFile.getmembers(). (Contributed by Serhiy Storchaka in bpo-21549 [https://bugs.python.org/issue?@action=redirect&bpo=21549].)

threading

Both the Lock.acquire() and RLock.acquire() methods now use a monotonic clock for timeout management. (Contributed by Victor Stinner in bpo-22043 [https://bugs.python.org/issue?@action=redirect&bpo=22043].)

time

The monotonic() function is now always available. (Contributed by Victor Stinner in bpo-22043 [https://bugs.python.org/issue?@action=redirect&bpo=22043].)

timeit

A new command line option -u or --unit=U can be used to specify the time unit for the timer output. Supported options are usec, msec, or sec. (Contributed by Julian Gindi in bpo-18983 [https://bugs.python.org/issue?@action=redirect&bpo=18983].)

The timeit() function has a new globals parameter for specifying the namespace in which the code will be running. (Contributed by Ben Roberts in bpo-2527 [https://bugs.python.org/issue?@action=redirect&bpo=2527].)

tkinter

The tkinter._fix module used for setting up the Tcl/Tk environment on Windows has been replaced by a private function in the _tkinter module which makes no permanent changes to environment variables. (Contributed by Zachary Ware in bpo-20035 [https://bugs.python.org/issue?@action=redirect&bpo=20035].)

traceback

New walk_stack() and walk_tb() functions to conveniently traverse frame and traceback objects. (Contributed by Robert Collins in bpo-17911 [https://bugs.python.org/issue?@action=redirect&bpo=17911].)

New lightweight classes: TracebackException, StackSummary, and FrameSummary. (Contributed by Robert Collins in bpo-17911 [https://bugs.python.org/issue?@action=redirect&bpo=17911].)

Both the print_tb() and print_stack() functions now support negative values for the limit argument. (Contributed by Dmitry Kazakov in bpo-22619 [https://bugs.python.org/issue?@action=redirect&bpo=22619].)

types

A new coroutine() function to transform generator and generator-like objects into awaitables. (Contributed by Yury Selivanov in bpo-24017 [https://bugs.python.org/issue?@action=redirect&bpo=24017].)

A new type called CoroutineType, which is used for coroutine objects created by async def functions. (Contributed by Yury Selivanov in bpo-24400 [https://bugs.python.org/issue?@action=redirect&bpo=24400].)

unicodedata

The unicodedata module now uses data from Unicode 8.0.0 [http://unicode.org/versions/Unicode8.0.0/].

unittest

The TestLoader.loadTestsFromModule() method now accepts a keyword-only argument pattern which is passed to load_tests as the third argument. Found packages are now checked for load_tests regardless of whether their path matches pattern, because it is impossible for a package name to match the default pattern. (Contributed by Robert Collins and Barry A. Warsaw in bpo-16662 [https://bugs.python.org/issue?@action=redirect&bpo=16662].)

Unittest discovery errors now are exposed in the TestLoader.errors attribute of the TestLoader instance. (Contributed by Robert Collins in bpo-19746 [https://bugs.python.org/issue?@action=redirect&bpo=19746].)

A new command line option --locals to show local variables in tracebacks. (Contributed by Robert Collins in bpo-22936 [https://bugs.python.org/issue?@action=redirect&bpo=22936].)

unittest.mock

The Mock class has the following improvements:

The class constructor has a new unsafe parameter, which causes mock objects to raise AttributeError on attribute names starting with "assert". (Contributed by Kushal Das in bpo-21238 [https://bugs.python.org/issue?@action=redirect&bpo=21238].)

A new Mock.assert_not_called() method to check if the mock object was called. (Contributed by Kushal Das in bpo-21262 [https://bugs.python.org/issue?@action=redirect&bpo=21262].)

The MagicMock class now supports __truediv__(), __divmod__() and __matmul__() operators. (Contributed by Johannes Baiter in bpo-20968 [https://bugs.python.org/issue?@action=redirect&bpo=20968], and Håkan Lövdahl in bpo-23581 [https://bugs.python.org/issue?@action=redirect&bpo=23581] and bpo-23568 [https://bugs.python.org/issue?@action=redirect&bpo=23568].)

It is no longer necessary to explicitly pass create=True to the patch() function when patching builtin names. (Contributed by Kushal Das in bpo-17660 [https://bugs.python.org/issue?@action=redirect&bpo=17660].)

urllib

A new request.HTTPPasswordMgrWithPriorAuth class allows HTTP Basic Authentication credentials to be managed so as to eliminate unnecessary 401 response handling, or to unconditionally send credentials on the first request in order to communicate with servers that return a 404 response instead of a 401 if the Authorization header is not sent. (Contributed by Matej Cepl in bpo-19494 [https://bugs.python.org/issue?@action=redirect&bpo=19494] and Akshit Khurana in bpo-7159 [https://bugs.python.org/issue?@action=redirect&bpo=7159].)

A new quote_via argument for the parse.urlencode() function provides a way to control the encoding of query parts if needed. (Contributed by Samwyse and Arnon Yaari in bpo-13866 [https://bugs.python.org/issue?@action=redirect&bpo=13866].)

The request.urlopen() function accepts an ssl.SSLContext object as a context argument, which will be used for the HTTPS connection. (Contributed by Alex Gaynor in bpo-22366 [https://bugs.python.org/issue?@action=redirect&bpo=22366].)

The parse.urljoin() was updated to use the RFC 3986 [https://tools.ietf.org/html/rfc3986.html] semantics for the resolution of relative URLs, rather than RFC 1808 [https://tools.ietf.org/html/rfc1808.html] and RFC 2396 [https://tools.ietf.org/html/rfc2396.html]. (Contributed by Demian Brecht and Senthil Kumaran in bpo-22118 [https://bugs.python.org/issue?@action=redirect&bpo=22118].)

wsgiref

The headers argument of the headers.Headers class constructor is now optional. (Contributed by Pablo Torres Navarrete and SilentGhost in bpo-5800 [https://bugs.python.org/issue?@action=redirect&bpo=5800].)

xmlrpc

The client.ServerProxy class now supports the context manager protocol. (Contributed by Claudiu Popa in bpo-20627 [https://bugs.python.org/issue?@action=redirect&bpo=20627].)

The client.ServerProxy constructor now accepts an optional ssl.SSLContext instance. (Contributed by Alex Gaynor in bpo-22960 [https://bugs.python.org/issue?@action=redirect&bpo=22960].)

xml.sax

SAX parsers now support a character stream of the xmlreader.InputSource object. (Contributed by Serhiy Storchaka in bpo-2175 [https://bugs.python.org/issue?@action=redirect&bpo=2175].)

parseString() now accepts a str instance. (Contributed by Serhiy Storchaka in bpo-10590 [https://bugs.python.org/issue?@action=redirect&bpo=10590].)

zipfile

ZIP output can now be written to unseekable streams. (Contributed by Serhiy Storchaka in bpo-23252 [https://bugs.python.org/issue?@action=redirect&bpo=23252].)

The mode argument of ZipFile.open() method now accepts "x" to request exclusive creation. (Contributed by Serhiy Storchaka in bpo-21717 [https://bugs.python.org/issue?@action=redirect&bpo=21717].)

Other module-level changes

Many functions in the mmap, ossaudiodev, socket, ssl, and codecs modules now accept writable bytes-like objects. (Contributed by Serhiy Storchaka in bpo-23001 [https://bugs.python.org/issue?@action=redirect&bpo=23001].)

Optimizations

The os.walk() function has been sped up by 3 to 5 times on POSIX systems, and by 7 to 20 times on Windows. This was done using the new os.scandir() function, which exposes file information from the underlying readdir or FindFirstFile/FindNextFile system calls. (Contributed by Ben Hoyt with help from Victor Stinner in bpo-23605 [https://bugs.python.org/issue?@action=redirect&bpo=23605].)

Construction of bytes(int) (filled by zero bytes) is faster and uses less memory for large objects. calloc() is used instead of malloc() to allocate memory for these objects. (Contributed by Victor Stinner in bpo-21233 [https://bugs.python.org/issue?@action=redirect&bpo=21233].)

Some operations on ipaddress IPv4Network and IPv6Network have been massively sped up, such as subnets(), supernet(), summarize_address_range(), collapse_addresses(). The speed up can range from 3 to 15 times. (Contributed by Antoine Pitrou, Michel Albert, and Markus in bpo-21486 [https://bugs.python.org/issue?@action=redirect&bpo=21486], bpo-21487 [https://bugs.python.org/issue?@action=redirect&bpo=21487], bpo-20826 [https://bugs.python.org/issue?@action=redirect&bpo=20826], bpo-23266 [https://bugs.python.org/issue?@action=redirect&bpo=23266].)

Pickling of ipaddress objects was optimized to produce significantly smaller output. (Contributed by Serhiy Storchaka in bpo-23133 [https://bugs.python.org/issue?@action=redirect&bpo=23133].)

Many operations on io.BytesIO are now 50% to 100% faster. (Contributed by Serhiy Storchaka in bpo-15381 [https://bugs.python.org/issue?@action=redirect&bpo=15381] and David Wilson in bpo-22003 [https://bugs.python.org/issue?@action=redirect&bpo=22003].)

The marshal.dumps() function is now faster: 65–85% with versions 3 and 4, 20–25% with versions 0 to 2 on typical data, and up to 5 times in best cases. (Contributed by Serhiy Storchaka in bpo-20416 [https://bugs.python.org/issue?@action=redirect&bpo=20416] and bpo-23344 [https://bugs.python.org/issue?@action=redirect&bpo=23344].)

The UTF-32 encoder is now 3 to 7 times faster. (Contributed by Serhiy Storchaka in bpo-15027 [https://bugs.python.org/issue?@action=redirect&bpo=15027].)

Regular expressions are now parsed up to 10% faster. (Contributed by Serhiy Storchaka in bpo-19380 [https://bugs.python.org/issue?@action=redirect&bpo=19380].)

The json.dumps() function was optimized to run with ensure_ascii=False as fast as with ensure_ascii=True. (Contributed by Naoki Inada in bpo-23206 [https://bugs.python.org/issue?@action=redirect&bpo=23206].)

The PyObject_IsInstance() and PyObject_IsSubclass() functions have been sped up in the common case that the second argument has type as its metaclass. (Contributed Georg Brandl by in bpo-22540 [https://bugs.python.org/issue?@action=redirect&bpo=22540].)

Method caching was slightly improved, yielding up to 5% performance improvement in some benchmarks. (Contributed by Antoine Pitrou in bpo-22847 [https://bugs.python.org/issue?@action=redirect&bpo=22847].)

Objects from the random module now use 50% less memory on 64-bit builds. (Contributed by Serhiy Storchaka in bpo-23488 [https://bugs.python.org/issue?@action=redirect&bpo=23488].)

The property() getter calls are up to 25% faster. (Contributed by Joe Jevnik in bpo-23910 [https://bugs.python.org/issue?@action=redirect&bpo=23910].)

Instantiation of fractions.Fraction is now up to 30% faster. (Contributed by Stefan Behnel in bpo-22464 [https://bugs.python.org/issue?@action=redirect&bpo=22464].)

String methods find(), rfind(), split(), partition() and the in string operator are now significantly faster for searching 1-character substrings. (Contributed by Serhiy Storchaka in bpo-23573 [https://bugs.python.org/issue?@action=redirect&bpo=23573].)

Build and C API Changes

New calloc functions were added:

PyMem_RawCalloc(),

PyMem_Calloc(),

PyObject_Calloc().

(Contributed by Victor Stinner in bpo-21233 [https://bugs.python.org/issue?@action=redirect&bpo=21233].)

New encoding/decoding helper functions:

Py_DecodeLocale() (replaced _Py_char2wchar()),

Py_EncodeLocale() (replaced _Py_wchar2char()).

(Contributed by Victor Stinner in bpo-18395 [https://bugs.python.org/issue?@action=redirect&bpo=18395].)

A new PyCodec_NameReplaceErrors() function to replace the unicode encode error with \N{...} escapes. (Contributed by Serhiy Storchaka in bpo-19676 [https://bugs.python.org/issue?@action=redirect&bpo=19676].)

A new PyErr_FormatV() function similar to PyErr_Format(), but accepts a va_list argument. (Contributed by Antoine Pitrou in bpo-18711 [https://bugs.python.org/issue?@action=redirect&bpo=18711].)

A new PyExc_RecursionError exception. (Contributed by Georg Brandl in bpo-19235 [https://bugs.python.org/issue?@action=redirect&bpo=19235].)

New PyModule_FromDefAndSpec(), PyModule_FromDefAndSpec2(), and PyModule_ExecDef() functions introduced by PEP 489 [https://www.python.org/dev/peps/pep-0489] – multi-phase extension module initialization. (Contributed by Petr Viktorin in bpo-24268 [https://bugs.python.org/issue?@action=redirect&bpo=24268].)

New PyNumber_MatrixMultiply() and PyNumber_InPlaceMatrixMultiply() functions to perform matrix multiplication. (Contributed by Benjamin Peterson in bpo-21176 [https://bugs.python.org/issue?@action=redirect&bpo=21176]. See also PEP 465 [https://www.python.org/dev/peps/pep-0465] for details.)

The PyTypeObject.tp_finalize slot is now part of the stable ABI.

Windows builds now require Microsoft Visual C++ 14.0, which is available as part of Visual Studio 2015 [https://www.visualstudio.com/].

Extension modules now include a platform information tag in their filename on some platforms (the tag is optional, and CPython will import extensions without it, although if the tag is present and mismatched, the extension won’t be loaded):

On Linux, extension module filenames end with .cpython-<major><minor>m-<architecture>-<os>.pyd:

<major> is the major number of the Python version; for Python 3.5 this is 3.

<minor> is the minor number of the Python version; for Python 3.5 this is 5.

<architecture> is the hardware architecture the extension module was built to run on. It’s most commonly either i386 for 32-bit Intel platforms or x86_64 for 64-bit Intel (and AMD) platforms.

<os> is always linux-gnu, except for extensions built to talk to the 32-bit ABI on 64-bit platforms, in which case it is linux-gnu32 (and <architecture> will be x86_64).

On Windows, extension module filenames end with <debug>.cp<major><minor>-<platform>.pyd:

<major> is the major number of the Python version; for Python 3.5 this is 3.

<minor> is the minor number of the Python version; for Python 3.5 this is 5.

<platform> is the platform the extension module was built for, either win32 for Win32, win_amd64 for Win64, win_ia64 for Windows Itanium 64, and win_arm for Windows on ARM.

If built in debug mode, <debug> will be _d, otherwise it will be blank.

On OS X platforms, extension module filenames now end with -darwin.so.

On all other platforms, extension module filenames are the same as they were with Python 3.4.

Deprecated

New Keywords

async and await are not recommended to be used as variable, class, function or module names. Introduced by PEP 492 [https://www.python.org/dev/peps/pep-0492] in Python 3.5, they will become proper keywords in Python 3.7.

Deprecated Python Behavior

Raising the StopIteration exception inside a generator will now generate a silent PendingDeprecationWarning, which will become a non-silent deprecation warning in Python 3.6 and will trigger a RuntimeError in Python 3.7. See PEP 479: Change StopIteration handling inside generators for details.

Unsupported Operating Systems

Windows XP is no longer supported by Microsoft, thus, per PEP 11 [https://www.python.org/dev/peps/pep-0011], CPython 3.5 is no longer officially supported on this OS.

Deprecated Python modules, functions and methods

The formatter module has now graduated to full deprecation and is still slated for removal in Python 3.6.

The asyncio.async() function is deprecated in favor of ensure_future().

The smtpd module has in the past always decoded the DATA portion of email messages using the utf-8 codec. This can now be controlled by the new decode_data keyword to SMTPServer. The default value is True, but this default is deprecated. Specify the decode_data keyword with an appropriate value to avoid the deprecation warning.

Directly assigning values to the key, value and coded_value of http.cookies.Morsel objects is deprecated. Use the set() method instead. In addition, the undocumented LegalChars parameter of set() is deprecated, and is now ignored.

Passing a format string as keyword argument format_string to the format() method of the string.Formatter class has been deprecated. (Contributed by Serhiy Storchaka in bpo-23671 [https://bugs.python.org/issue?@action=redirect&bpo=23671].)

The platform.dist() and platform.linux_distribution() functions are now deprecated. Linux distributions use too many different ways of describing themselves, so the functionality is left to a package. (Contributed by Vajrasky Kok and Berker Peksag in bpo-1322 [https://bugs.python.org/issue?@action=redirect&bpo=1322].)

The previously undocumented from_function and from_builtin methods of inspect.Signature are deprecated. Use the new Signature.from_callable() method instead. (Contributed by Yury Selivanov in bpo-24248 [https://bugs.python.org/issue?@action=redirect&bpo=24248].)

The inspect.getargspec() function is deprecated and scheduled to be removed in Python 3.6. (See bpo-20438 [https://bugs.python.org/issue?@action=redirect&bpo=20438] for details.)

The inspect getfullargspec(), getcallargs(), and formatargspec() functions are deprecated in favor of the inspect.signature() API. (Contributed by Yury Selivanov in bpo-20438 [https://bugs.python.org/issue?@action=redirect&bpo=20438].)

getargvalues() and formatargvalues() functions were inadvertently marked as deprecated with the release of Python 3.5.0.

Use of re.LOCALE flag with str patterns or re.ASCII is now deprecated. (Contributed by Serhiy Storchaka in bpo-22407 [https://bugs.python.org/issue?@action=redirect&bpo=22407].)

Use of unrecognized special sequences consisting of '\' and an ASCII letter in regular expression patterns and replacement patterns now raises a deprecation warning and will be forbidden in Python 3.6. (Contributed by Serhiy Storchaka in bpo-23622 [https://bugs.python.org/issue?@action=redirect&bpo=23622].)

The undocumented and unofficial use_load_tests default argument of the unittest.TestLoader.loadTestsFromModule() method now is deprecated and ignored. (Contributed by Robert Collins and Barry A. Warsaw in bpo-16662 [https://bugs.python.org/issue?@action=redirect&bpo=16662].)

Removed

API and Feature Removals

The following obsolete and previously deprecated APIs and features have been removed:

The __version__ attribute has been dropped from the email package. The email code hasn’t been shipped separately from the stdlib for a long time, and the __version__ string was not updated in the last few releases.

The internal Netrc class in the ftplib module was deprecated in 3.4, and has now been removed. (Contributed by Matt Chaput in bpo-6623 [https://bugs.python.org/issue?@action=redirect&bpo=6623].)

The concept of .pyo files has been removed.

The JoinableQueue class in the provisional asyncio module was deprecated in 3.4.4 and is now removed. (Contributed by A. Jesse Jiryu Davis in bpo-23464 [https://bugs.python.org/issue?@action=redirect&bpo=23464].)

Porting to Python 3.5

This section lists previously described changes and other bugfixes that may require changes to your code.

Changes in Python behavior

Due to an oversight, earlier Python versions erroneously accepted the following syntax:

f(1 for x in [1], *args)
f(1 for x in [1], **kwargs)

Python 3.5 now correctly raises a SyntaxError, as generator expressions must be put in parentheses if not a sole argument to a function.

Changes in the Python API

PEP 475 [https://www.python.org/dev/peps/pep-0475]: System calls are now retried when interrupted by a signal instead of raising InterruptedError if the Python signal handler does not raise an exception.

Before Python 3.5, a datetime.time object was considered to be false if it represented midnight in UTC. This behavior was considered obscure and error-prone and has been removed in Python 3.5. See bpo-13936 [https://bugs.python.org/issue?@action=redirect&bpo=13936] for full details.

The ssl.SSLSocket.send() method now raises either ssl.SSLWantReadError or ssl.SSLWantWriteError on a non-blocking socket if the operation would block. Previously, it would return 0. (Contributed by Nikolaus Rath in bpo-20951 [https://bugs.python.org/issue?@action=redirect&bpo=20951].)

The __name__ attribute of generators is now set from the function name, instead of being set from the code name. Use gen.gi_code.co_name to retrieve the code name. Generators also have a new __qualname__ attribute, the qualified name, which is now used for the representation of a generator (repr(gen)). (Contributed by Victor Stinner in bpo-21205 [https://bugs.python.org/issue?@action=redirect&bpo=21205].)

The deprecated “strict” mode and argument of HTMLParser, HTMLParser.error(), and the HTMLParserError exception have been removed. (Contributed by Ezio Melotti in bpo-15114 [https://bugs.python.org/issue?@action=redirect&bpo=15114].) The convert_charrefs argument of HTMLParser is now True by default. (Contributed by Berker Peksag in bpo-21047 [https://bugs.python.org/issue?@action=redirect&bpo=21047].)

Although it is not formally part of the API, it is worth noting for porting purposes (ie: fixing tests) that error messages that were previously of the form “‘sometype’ does not support the buffer protocol” are now of the form “a bytes-like object is required, not ‘sometype’”. (Contributed by Ezio Melotti in bpo-16518 [https://bugs.python.org/issue?@action=redirect&bpo=16518].)

If the current directory is set to a directory that no longer exists then FileNotFoundError will no longer be raised and instead find_spec() will return None without caching None in sys.path_importer_cache, which is different than the typical case (bpo-22834 [https://bugs.python.org/issue?@action=redirect&bpo=22834]).

HTTP status code and messages from http.client and http.server were refactored into a common HTTPStatus enum. The values in http.client and http.server remain available for backwards compatibility. (Contributed by Demian Brecht in bpo-21793 [https://bugs.python.org/issue?@action=redirect&bpo=21793].)

When an import loader defines importlib.machinery.Loader.exec_module() it is now expected to also define create_module() (raises a DeprecationWarning now, will be an error in Python 3.6). If the loader inherits from importlib.abc.Loader then there is nothing to do, else simply define create_module() to return None. (Contributed by Brett Cannon in bpo-23014 [https://bugs.python.org/issue?@action=redirect&bpo=23014].)

The re.split() function always ignored empty pattern matches, so the "x*" pattern worked the same as "x+", and the "\b" pattern never worked. Now re.split() raises a warning if the pattern could match an empty string. For compatibility, use patterns that never match an empty string (e.g. "x+" instead of "x*"). Patterns that could only match an empty string (such as "\b") now raise an error. (Contributed by Serhiy Storchaka in bpo-22818 [https://bugs.python.org/issue?@action=redirect&bpo=22818].)

The http.cookies.Morsel dict-like interface has been made self consistent: morsel comparison now takes the key and value into account, copy() now results in a Morsel instance rather than a dict, and update() will now raise an exception if any of the keys in the update dictionary are invalid. In addition, the undocumented LegalChars parameter of set() is deprecated and is now ignored. (Contributed by Demian Brecht in bpo-2211 [https://bugs.python.org/issue?@action=redirect&bpo=2211].)

PEP 488 [https://www.python.org/dev/peps/pep-0488] has removed .pyo files from Python and introduced the optional opt- tag in .pyc file names. The importlib.util.cache_from_source() has gained an optimization parameter to help control the opt- tag. Because of this, the debug_override parameter of the function is now deprecated. .pyo files are also no longer supported as a file argument to the Python interpreter and thus serve no purpose when distributed on their own (i.e. sourceless code distribution). Due to the fact that the magic number for bytecode has changed in Python 3.5, all old .pyo files from previous versions of Python are invalid regardless of this PEP.

The socket module now exports the CAN_RAW_FD_FRAMES constant on linux 3.6 and greater.

The ssl.cert_time_to_seconds() function now interprets the input time as UTC and not as local time, per RFC 5280 [https://tools.ietf.org/html/rfc5280.html]. Additionally, the return value is always an int. (Contributed by Akira Li in bpo-19940 [https://bugs.python.org/issue?@action=redirect&bpo=19940].)

The pygettext.py Tool now uses the standard +NNNN format for timezones in the POT-Creation-Date header.

The smtplib module now uses sys.stderr instead of the previous module-level stderr variable for debug output. If your (test) program depends on patching the module-level variable to capture the debug output, you will need to update it to capture sys.stderr instead.

The str.startswith() and str.endswith() methods no longer return True when finding the empty string and the indexes are completely out of range. (Contributed by Serhiy Storchaka in bpo-24284 [https://bugs.python.org/issue?@action=redirect&bpo=24284].)

The inspect.getdoc() function now returns documentation strings inherited from base classes. Documentation strings no longer need to be duplicated if the inherited documentation is appropriate. To suppress an inherited string, an empty string must be specified (or the documentation may be filled in). This change affects the output of the pydoc module and the help() function. (Contributed by Serhiy Storchaka in bpo-15582 [https://bugs.python.org/issue?@action=redirect&bpo=15582].)

Nested functools.partial() calls are now flattened. If you were relying on the previous behavior, you can now either add an attribute to a functools.partial() object or you can create a subclass of functools.partial(). (Contributed by Alexander Belopolsky in bpo-7830 [https://bugs.python.org/issue?@action=redirect&bpo=7830].)

Changes in the C API

The undocumented format member of the (non-public) PyMemoryViewObject structure has been removed. All extensions relying on the relevant parts in memoryobject.h must be rebuilt.

The PyMemAllocator structure was renamed to PyMemAllocatorEx and a new calloc field was added.

Removed non-documented macro PyObject_REPR which leaked references. Use format character %R in PyUnicode_FromFormat()-like functions to format the repr() of the object. (Contributed by Serhiy Storchaka in bpo-22453 [https://bugs.python.org/issue?@action=redirect&bpo=22453].)

Because the lack of the __module__ attribute breaks pickling and introspection, a deprecation warning is now raised for builtin types without the __module__ attribute. This would be an AttributeError in the future. (Contributed by Serhiy Storchaka in bpo-20204 [https://bugs.python.org/issue?@action=redirect&bpo=20204].)

As part of the PEP 492 [https://www.python.org/dev/peps/pep-0492] implementation, the tp_reserved slot of PyTypeObject was replaced with a tp_as_async slot. Refer to 코루틴 객체 for new types, structures and functions.

Notable changes in Python 3.5.4

New make regen-all build target

To simplify cross-compilation, and to ensure that CPython can reliably be compiled without requiring an existing version of Python to already be available, the autotools-based build system no longer attempts to implicitly recompile generated files based on file modification times.

Instead, a new make regen-all command has been added to force regeneration of these files when desired (e.g. after an initial version of Python has already been built based on the pregenerated versions).

More selective regeneration targets are also defined - see Makefile.pre.in [https://github.com/python/cpython/tree/3.7/Makefile.pre.in] for details.

(Contributed by Victor Stinner in bpo-23404 [https://bugs.python.org/issue?@action=redirect&bpo=23404].)

버전 3.5.4에 추가.

Removal of make touch build target

The make touch build target previously used to request implicit regeneration of generated files by updating their modification times has been removed.

It has been replaced by the new make regen-all target.

(Contributed by Victor Stinner in bpo-23404 [https://bugs.python.org/issue?@action=redirect&bpo=23404].)

버전 3.5.4에서 변경.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬의 새로운 기능 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬의 새로운 기능 »

|

What’s New In Python 3.4

Author

R. David Murray <rdmurray@bitdance.com> (Editor)

This article explains the new features in Python 3.4, compared to 3.3. Python 3.4 was released on March 16, 2014. For full details, see the changelog [https://docs.python.org/3.4/whatsnew/changelog.html].

더 보기

PEP 429 [https://www.python.org/dev/peps/pep-0429] – Python 3.4 Release Schedule

Summary – Release Highlights

New syntax features:

No new syntax features were added in Python 3.4.

Other new features:

pip should always be available (PEP 453 [https://www.python.org/dev/peps/pep-0453]).

Newly created file descriptors are non-inheritable (PEP 446 [https://www.python.org/dev/peps/pep-0446]).

command line option for isolated mode (bpo-16499 [https://bugs.python.org/issue?@action=redirect&bpo=16499]).

improvements in the handling of codecs that are not text encodings (multiple issues).

A ModuleSpec Type for the Import System (PEP 451 [https://www.python.org/dev/peps/pep-0451]). (Affects importer authors.)

The marshal format has been made more compact and efficient (bpo-16475 [https://bugs.python.org/issue?@action=redirect&bpo=16475]).

New library modules:

asyncio: New provisional API for asynchronous IO (PEP 3156 [https://www.python.org/dev/peps/pep-3156]).

ensurepip: Bootstrapping the pip installer (PEP 453 [https://www.python.org/dev/peps/pep-0453]).

enum: Support for enumeration types (PEP 435 [https://www.python.org/dev/peps/pep-0435]).

pathlib: Object-oriented filesystem paths (PEP 428 [https://www.python.org/dev/peps/pep-0428]).

selectors: High-level and efficient I/O multiplexing, built upon the select module primitives (part of PEP 3156 [https://www.python.org/dev/peps/pep-3156]).

statistics: A basic numerically stable statistics library (PEP 450 [https://www.python.org/dev/peps/pep-0450]).

tracemalloc: Trace Python memory allocations (PEP 454 [https://www.python.org/dev/peps/pep-0454]).

Significantly improved library modules:

Single-dispatch generic functions in functools (PEP 443 [https://www.python.org/dev/peps/pep-0443]).

New pickle protocol 4 (PEP 3154 [https://www.python.org/dev/peps/pep-3154]).

multiprocessing now has an option to avoid using os.fork on Unix (bpo-8713 [https://bugs.python.org/issue?@action=redirect&bpo=8713]).

email has a new submodule, contentmanager, and a new Message subclass (EmailMessage) that simplify MIME handling (bpo-18891 [https://bugs.python.org/issue?@action=redirect&bpo=18891]).

The inspect and pydoc modules are now capable of correct introspection of a much wider variety of callable objects, which improves the output of the Python help() system.

The ipaddress module API has been declared stable

Security improvements:

Secure and interchangeable hash algorithm (PEP 456 [https://www.python.org/dev/peps/pep-0456]).

Make newly created file descriptors non-inheritable (PEP 446 [https://www.python.org/dev/peps/pep-0446]) to avoid leaking file descriptors to child processes.

New command line option for isolated mode, (bpo-16499 [https://bugs.python.org/issue?@action=redirect&bpo=16499]).

multiprocessing now has an option to avoid using os.fork on Unix. spawn and forkserver are more secure because they avoid sharing data with child processes.

multiprocessing child processes on Windows no longer inherit all of the parent’s inheritable handles, only the necessary ones.

A new hashlib.pbkdf2_hmac() function provides the PKCS#5 password-based key derivation function 2 [https://en.wikipedia.org/wiki/PBKDF2].

TLSv1.1 and TLSv1.2 support for ssl.

Retrieving certificates from the Windows system cert store support for ssl.

Server-side SNI (Server Name Indication) support for ssl.

The ssl.SSLContext class has a lot of improvements.

All modules in the standard library that support SSL now support server certificate verification, including hostname matching (ssl.match_hostname()) and CRLs (Certificate Revocation lists, see ssl.SSLContext.load_verify_locations()).

CPython implementation improvements:

Safe object finalization (PEP 442 [https://www.python.org/dev/peps/pep-0442]).

Leveraging PEP 442 [https://www.python.org/dev/peps/pep-0442], in most cases module globals are no longer set to None during finalization (bpo-18214 [https://bugs.python.org/issue?@action=redirect&bpo=18214]).

Configurable memory allocators (PEP 445 [https://www.python.org/dev/peps/pep-0445]).

Argument Clinic (PEP 436 [https://www.python.org/dev/peps/pep-0436]).

Please read on for a comprehensive list of user-facing changes, including many other smaller improvements, CPython optimizations, deprecations, and potential porting issues.

New Features

PEP 453: Explicit Bootstrapping of PIP in Python Installations

Bootstrapping pip By Default

The new ensurepip module (defined in PEP 453 [https://www.python.org/dev/peps/pep-0453]) provides a standard cross-platform mechanism to bootstrap the pip installer into Python installations and virtual environments. The version of pip included with Python 3.4.0 is pip 1.5.4, and future 3.4.x maintenance releases will update the bundled version to the latest version of pip that is available at the time of creating the release candidate.

By default, the commands pipX and pipX.Y will be installed on all platforms (where X.Y stands for the version of the Python installation), along with the pip Python package and its dependencies. On Windows and in virtual environments on all platforms, the unversioned pip command will also be installed. On other platforms, the system wide unversioned pip command typically refers to the separately installed Python 2 version.

The pyvenv command line utility and the venv module make use of the ensurepip module to make pip readily available in virtual environments. When using the command line utility, pip is installed by default, while when using the venv module API installation of pip must be requested explicitly.

For CPython source builds on POSIX systems, the make install and make altinstall commands bootstrap pip by default. This behaviour can be controlled through configure options, and overridden through Makefile options.

On Windows and Mac OS X, the CPython installers now default to installing pip along with CPython itself (users may opt out of installing it during the installation process). Window users will need to opt in to the automatic PATH modifications to have pip available from the command line by default, otherwise it can still be accessed through the Python launcher for Windows as py -m pip.

As discussed in the PEP [https://www.python.org/dev/peps/pep-0453/#recommendations-for-downstream-distributors], platform packagers may choose not to install these commands by default, as long as, when invoked, they provide clear and simple directions on how to install them on that platform (usually using the system package manager).

참고

To avoid conflicts between parallel Python 2 and Python 3 installations, only the versioned pip3 and pip3.4 commands are bootstrapped by default when ensurepip is invoked directly - the --default-pip option is needed to also request the unversioned pip command. pyvenv and the Windows installer ensure that the unqualified pip command is made available in those environments, and pip can always be invoked via the -m switch rather than directly to avoid ambiguity on systems with multiple Python installations.

Documentation Changes

As part of this change, the 파이썬 모듈 설치하기 and 파이썬 모듈 배포하기 sections of the documentation have been completely redesigned as short getting started and FAQ documents. Most packaging documentation has now been moved out to the Python Packaging Authority maintained Python Packaging User Guide [https://packaging.python.org] and the documentation of the individual projects.

However, as this migration is currently still incomplete, the legacy versions of those guides remaining available as 파이썬 모듈 설치 (레거시 버전) and 파이썬 모듈 배포 (레거시 버전).

더 보기

PEP 453 [https://www.python.org/dev/peps/pep-0453] – Explicit bootstrapping of pip in Python installations

PEP written by Donald Stufft and Nick Coghlan, implemented by Donald Stufft, Nick Coghlan, Martin von Löwis and Ned Deily.

PEP 446: Newly Created File Descriptors Are Non-Inheritable

PEP 446 [https://www.python.org/dev/peps/pep-0446] makes newly created file descriptors non-inheritable. In general, this is the behavior an application will want: when launching a new process, having currently open files also open in the new process can lead to all sorts of hard to find bugs, and potentially to security issues.

However, there are occasions when inheritance is desired. To support these cases, the following new functions and methods are available:

os.get_inheritable(), os.set_inheritable()

os.get_handle_inheritable(), os.set_handle_inheritable()

socket.socket.get_inheritable(), socket.socket.set_inheritable()

더 보기

PEP 446 [https://www.python.org/dev/peps/pep-0446] – Make newly created file descriptors non-inheritable

PEP written and implemented by Victor Stinner.

Improvements to Codec Handling

Since it was first introduced, the codecs module has always been intended to operate as a type-neutral dynamic encoding and decoding system. However, its close coupling with the Python text model, especially the type restricted convenience methods on the builtin str, bytes and bytearray types, has historically obscured that fact.

As a key step in clarifying the situation, the codecs.encode() and codecs.decode() convenience functions are now properly documented in Python 2.7, 3.3 and 3.4. These functions have existed in the codecs module (and have been covered by the regression test suite) since Python 2.4, but were previously only discoverable through runtime introspection.

Unlike the convenience methods on str, bytes and bytearray, the codecs convenience functions support arbitrary codecs in both Python 2 and Python 3, rather than being limited to Unicode text encodings (in Python 3) or basestring <-> basestring conversions (in Python 2).

In Python 3.4, the interpreter is able to identify the known non-text encodings provided in the standard library and direct users towards these general purpose convenience functions when appropriate:

>>> b"abcdef".decode("hex")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
LookupError: 'hex' is not a text encoding; use codecs.decode() to handle arbitrary codecs

>>> "hello".encode("rot13")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
LookupError: 'rot13' is not a text encoding; use codecs.encode() to handle arbitrary codecs

>>> open("foo.txt", encoding="hex")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
LookupError: 'hex' is not a text encoding; use codecs.open() to handle arbitrary codecs

In a related change, whenever it is feasible without breaking backwards compatibility, exceptions raised during encoding and decoding operations are wrapped in a chained exception of the same type that mentions the name of the codec responsible for producing the error:

>>> import codecs

>>> codecs.decode(b"abcdefgh", "hex")
Traceback (most recent call last):
  File "/usr/lib/python3.4/encodings/hex_codec.py", line 20, in hex_decode
    return (binascii.a2b_hex(input), len(input))
binascii.Error: Non-hexadecimal digit found

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
binascii.Error: decoding with 'hex' codec failed (Error: Non-hexadecimal digit found)

>>> codecs.encode("hello", "bz2")
Traceback (most recent call last):
  File "/usr/lib/python3.4/encodings/bz2_codec.py", line 17, in bz2_encode
    return (bz2.compress(input), len(input))
  File "/usr/lib/python3.4/bz2.py", line 498, in compress
    return comp.compress(data) + comp.flush()
TypeError: 'str' does not support the buffer interface

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: encoding with 'bz2' codec failed (TypeError: 'str' does not support the buffer interface)

Finally, as the examples above show, these improvements have permitted the restoration of the convenience aliases for the non-Unicode codecs that were themselves restored in Python 3.2. This means that encoding binary data to and from its hexadecimal representation (for example) can now be written as:

>>> from codecs import encode, decode
>>> encode(b"hello", "hex")
b'68656c6c6f'
>>> decode(b"68656c6c6f", "hex")
b'hello'

The binary and text transforms provided in the standard library are detailed in Binary Transforms and Text Transforms.

(Contributed by Nick Coghlan in bpo-7475 [https://bugs.python.org/issue?@action=redirect&bpo=7475], bpo-17827 [https://bugs.python.org/issue?@action=redirect&bpo=17827], bpo-17828 [https://bugs.python.org/issue?@action=redirect&bpo=17828] and bpo-19619 [https://bugs.python.org/issue?@action=redirect&bpo=19619].)

PEP 451: A ModuleSpec Type for the Import System

PEP 451 [https://www.python.org/dev/peps/pep-0451] provides an encapsulation of the information about a module that the import machinery will use to load it (that is, a module specification). This helps simplify both the import implementation and several import-related APIs. The change is also a stepping stone for several future import-related improvements [https://mail.python.org/pipermail/python-dev/2013-November/130111.html].

The public-facing changes from the PEP are entirely backward-compatible. Furthermore, they should be transparent to everyone but importer authors. Key finder and loader methods have been deprecated, but they will continue working. New importers should use the new methods described in the PEP. Existing importers should be updated to implement the new methods. See the Deprecated section for a list of methods that should be replaced and their replacements.

Other Language Changes

Some smaller changes made to the core Python language are:

Unicode database updated to UCD version 6.3.

min() and max() now accept a default keyword-only argument that can be used to specify the value they return if the iterable they are evaluating has no elements. (Contributed by Julian Berman in bpo-18111 [https://bugs.python.org/issue?@action=redirect&bpo=18111].)

Module objects are now weakref’able.

Module __file__ attributes (and related values) should now always contain absolute paths by default, with the sole exception of __main__.__file__ when a script has been executed directly using a relative path. (Contributed by Brett Cannon in bpo-18416 [https://bugs.python.org/issue?@action=redirect&bpo=18416].)

All the UTF-* codecs (except UTF-7) now reject surrogates during both encoding and decoding unless the surrogatepass error handler is used, with the exception of the UTF-16 decoder (which accepts valid surrogate pairs) and the UTF-16 encoder (which produces them while encoding non-BMP characters). (Contributed by Victor Stinner, Kang-Hao (Kenny) Lu and Serhiy Storchaka in bpo-12892 [https://bugs.python.org/issue?@action=redirect&bpo=12892].)

New German EBCDIC codec cp273. (Contributed by Michael Bierenfeld and Andrew Kuchling in bpo-1097797 [https://bugs.python.org/issue?@action=redirect&bpo=1097797].)

New Ukrainian codec cp1125. (Contributed by Serhiy Storchaka in bpo-19668 [https://bugs.python.org/issue?@action=redirect&bpo=19668].)

bytes.join() and bytearray.join() now accept arbitrary buffer objects as arguments. (Contributed by Antoine Pitrou in bpo-15958 [https://bugs.python.org/issue?@action=redirect&bpo=15958].)

The int constructor now accepts any object that has an __index__ method for its base argument. (Contributed by Mark Dickinson in bpo-16772 [https://bugs.python.org/issue?@action=redirect&bpo=16772].)

Frame objects now have a clear() method that clears all references to local variables from the frame. (Contributed by Antoine Pitrou in bpo-17934 [https://bugs.python.org/issue?@action=redirect&bpo=17934].)

memoryview is now registered as a Sequence, and supports the reversed() builtin. (Contributed by Nick Coghlan and Claudiu Popa in bpo-18690 [https://bugs.python.org/issue?@action=redirect&bpo=18690] and bpo-19078 [https://bugs.python.org/issue?@action=redirect&bpo=19078].)

Signatures reported by help() have been modified and improved in several cases as a result of the introduction of Argument Clinic and other changes to the inspect and pydoc modules.

__length_hint__() is now part of the formal language specification (see PEP 424 [https://www.python.org/dev/peps/pep-0424]). (Contributed by Armin Ronacher in bpo-16148 [https://bugs.python.org/issue?@action=redirect&bpo=16148].)

New Modules

asyncio

The new asyncio module (defined in PEP 3156 [https://www.python.org/dev/peps/pep-3156]) provides a standard pluggable event loop model for Python, providing solid asynchronous IO support in the standard library, and making it easier for other event loop implementations to interoperate with the standard library and each other.

For Python 3.4, this module is considered a provisional API.

더 보기

PEP 3156 [https://www.python.org/dev/peps/pep-3156] – Asynchronous IO Support Rebooted: the “asyncio” Module

PEP written and implementation led by Guido van Rossum.

ensurepip

The new ensurepip module is the primary infrastructure for the PEP 453 [https://www.python.org/dev/peps/pep-0453] implementation. In the normal course of events end users will not need to interact with this module, but it can be used to manually bootstrap pip if the automated bootstrapping into an installation or virtual environment was declined.

ensurepip includes a bundled copy of pip, up-to-date as of the first release candidate of the release of CPython with which it ships (this applies to both maintenance releases and feature releases). ensurepip does not access the internet. If the installation has Internet access, after ensurepip is run the bundled pip can be used to upgrade pip to a more recent release than the bundled one. (Note that such an upgraded version of pip is considered to be a separately installed package and will not be removed if Python is uninstalled.)

The module is named ensurepip because if called when pip is already installed, it does nothing. It also has an --upgrade option that will cause it to install the bundled copy of pip if the existing installed version of pip is older than the bundled copy.

enum

The new enum module (defined in PEP 435 [https://www.python.org/dev/peps/pep-0435]) provides a standard implementation of enumeration types, allowing other modules (such as socket) to provide more informative error messages and better debugging support by replacing opaque integer constants with backwards compatible enumeration values.

더 보기

PEP 435 [https://www.python.org/dev/peps/pep-0435] – Adding an Enum type to the Python standard library

PEP written by Barry Warsaw, Eli Bendersky and Ethan Furman, implemented by Ethan Furman.

pathlib

The new pathlib module offers classes representing filesystem paths with semantics appropriate for different operating systems. Path classes are divided between pure paths, which provide purely computational operations without I/O, and concrete paths, which inherit from pure paths but also provide I/O operations.

For Python 3.4, this module is considered a provisional API.

더 보기

PEP 428 [https://www.python.org/dev/peps/pep-0428] – The pathlib module – object-oriented filesystem paths

PEP written and implemented by Antoine Pitrou.

selectors

The new selectors module (created as part of implementing PEP 3156 [https://www.python.org/dev/peps/pep-3156]) allows high-level and efficient I/O multiplexing, built upon the select module primitives.

statistics

The new statistics module (defined in PEP 450 [https://www.python.org/dev/peps/pep-0450]) offers some core statistics functionality directly in the standard library. This module supports calculation of the mean, median, mode, variance and standard deviation of a data series.

더 보기

PEP 450 [https://www.python.org/dev/peps/pep-0450] – Adding A Statistics Module To The Standard Library

PEP written and implemented by Steven D’Aprano

tracemalloc

The new tracemalloc module (defined in PEP 454 [https://www.python.org/dev/peps/pep-0454]) is a debug tool to trace memory blocks allocated by Python. It provides the following information:

Trace where an object was allocated

Statistics on allocated memory blocks per filename and per line number: total size, number and average size of allocated memory blocks

Compute the differences between two snapshots to detect memory leaks

더 보기

PEP 454 [https://www.python.org/dev/peps/pep-0454] – Add a new tracemalloc module to trace Python memory allocations

PEP written and implemented by Victor Stinner

Improved Modules

abc

New function abc.get_cache_token() can be used to know when to invalidate caches that are affected by changes in the object graph. (Contributed by Łukasz Langa in bpo-16832 [https://bugs.python.org/issue?@action=redirect&bpo=16832].)

New class ABC has ABCMeta as its meta class. Using ABC as a base class has essentially the same effect as specifying metaclass=abc.ABCMeta, but is simpler to type and easier to read. (Contributed by Bruno Dupuis in bpo-16049 [https://bugs.python.org/issue?@action=redirect&bpo=16049].)

aifc

The getparams() method now returns a namedtuple rather than a plain tuple. (Contributed by Claudiu Popa in bpo-17818 [https://bugs.python.org/issue?@action=redirect&bpo=17818].)

aifc.open() now supports the context management protocol: when used in a with block, the close() method of the returned object will be called automatically at the end of the block. (Contributed by Serhiy Storchacha in bpo-16486 [https://bugs.python.org/issue?@action=redirect&bpo=16486].)

The writeframesraw() and writeframes() methods now accept any bytes-like object. (Contributed by Serhiy Storchaka in bpo-8311 [https://bugs.python.org/issue?@action=redirect&bpo=8311].)

argparse

The FileType class now accepts encoding and errors arguments, which are passed through to open(). (Contributed by Lucas Maystre in bpo-11175 [https://bugs.python.org/issue?@action=redirect&bpo=11175].)

audioop

audioop now supports 24-bit samples. (Contributed by Serhiy Storchaka in bpo-12866 [https://bugs.python.org/issue?@action=redirect&bpo=12866].)

New byteswap() function converts big-endian samples to little-endian and vice versa. (Contributed by Serhiy Storchaka in bpo-19641 [https://bugs.python.org/issue?@action=redirect&bpo=19641].)

All audioop functions now accept any bytes-like object. Strings are not accepted: they didn’t work before, now they raise an error right away. (Contributed by Serhiy Storchaka in bpo-16685 [https://bugs.python.org/issue?@action=redirect&bpo=16685].)

base64

The encoding and decoding functions in base64 now accept any bytes-like object in cases where it previously required a bytes or bytearray instance. (Contributed by Nick Coghlan in bpo-17839 [https://bugs.python.org/issue?@action=redirect&bpo=17839].)

New functions a85encode(), a85decode(), b85encode(), and b85decode() provide the ability to encode and decode binary data from and to Ascii85 and the git/mercurial Base85 formats, respectively. The a85 functions have options that can be used to make them compatible with the variants of the Ascii85 encoding, including the Adobe variant. (Contributed by Martin Morrison, the Mercurial project, Serhiy Storchaka, and Antoine Pitrou in bpo-17618 [https://bugs.python.org/issue?@action=redirect&bpo=17618].)

collections

The ChainMap.new_child() method now accepts an m argument specifying the child map to add to the chain. This allows an existing mapping and/or a custom mapping type to be used for the child. (Contributed by Vinay Sajip in bpo-16613 [https://bugs.python.org/issue?@action=redirect&bpo=16613].)

colorsys

The number of digits in the coefficients for the RGB — YIQ conversions have been expanded so that they match the FCC NTSC versions. The change in results should be less than 1% and may better match results found elsewhere. (Contributed by Brian Landers and Serhiy Storchaka in bpo-14323 [https://bugs.python.org/issue?@action=redirect&bpo=14323].)

contextlib

The new contextlib.suppress context manager helps to clarify the intent of code that deliberately suppresses exceptions from a single statement. (Contributed by Raymond Hettinger in bpo-15806 [https://bugs.python.org/issue?@action=redirect&bpo=15806] and Zero Piraeus in bpo-19266 [https://bugs.python.org/issue?@action=redirect&bpo=19266].)

The new contextlib.redirect_stdout() context manager makes it easier for utility scripts to handle inflexible APIs that write their output to sys.stdout and don’t provide any options to redirect it. Using the context manager, the sys.stdout output can be redirected to any other stream or, in conjunction with io.StringIO, to a string. The latter can be especially useful, for example, to capture output from a function that was written to implement a command line interface. It is recommended only for utility scripts because it affects the global state of sys.stdout. (Contributed by Raymond Hettinger in bpo-15805 [https://bugs.python.org/issue?@action=redirect&bpo=15805].)

The contextlib documentation has also been updated to include a discussion of the differences between single use, reusable and reentrant context managers.

dbm

dbm.open() objects now support the context management protocol. When used in a with statement, the close method of the database object will be called automatically at the end of the block. (Contributed by Claudiu Popa and Nick Coghlan in bpo-19282 [https://bugs.python.org/issue?@action=redirect&bpo=19282].)

dis

Functions show_code(), dis(), distb(), and disassemble() now accept a keyword-only file argument that controls where they write their output.

The dis module is now built around an Instruction class that provides object oriented access to the details of each individual bytecode operation.

A new method, get_instructions(), provides an iterator that emits the Instruction stream for a given piece of Python code. Thus it is now possible to write a program that inspects and manipulates a bytecode object in ways different from those provided by the dis module itself. For example:

>>> import dis
>>> for instr in dis.get_instructions(lambda x: x + 1):
...     print(instr.opname)
LOAD_FAST
LOAD_CONST
BINARY_ADD
RETURN_VALUE

The various display tools in the dis module have been rewritten to use these new components.

In addition, a new application-friendly class Bytecode provides an object-oriented API for inspecting bytecode in both in human-readable form and for iterating over instructions. The Bytecode constructor takes the same arguments that get_instruction() does (plus an optional current_offset), and the resulting object can be iterated to produce Instruction objects. But it also has a dis method, equivalent to calling dis on the constructor argument, but returned as a multi-line string:

>>> bytecode = dis.Bytecode(lambda x: x + 1, current_offset=3)
>>> for instr in bytecode:
...     print('{} ({})'.format(instr.opname, instr.opcode))
LOAD_FAST (124)
LOAD_CONST (100)
BINARY_ADD (23)
RETURN_VALUE (83)
>>> bytecode.dis().splitlines()
['  1           0 LOAD_FAST                0 (x)',
 '      -->     3 LOAD_CONST               1 (1)',
 '              6 BINARY_ADD',
 '              7 RETURN_VALUE']

Bytecode also has a class method, from_traceback(), that provides the ability to manipulate a traceback (that is, print(Bytecode.from_traceback(tb).dis()) is equivalent to distb(tb)).

(Contributed by Nick Coghlan, Ryan Kelly and Thomas Kluyver in bpo-11816 [https://bugs.python.org/issue?@action=redirect&bpo=11816] and Claudiu Popa in bpo-17916 [https://bugs.python.org/issue?@action=redirect&bpo=17916].)

New function stack_effect() computes the effect on the Python stack of a given opcode and argument, information that is not otherwise available. (Contributed by Larry Hastings in bpo-19722 [https://bugs.python.org/issue?@action=redirect&bpo=19722].)

doctest

A new option flag, FAIL_FAST, halts test running as soon as the first failure is detected. (Contributed by R. David Murray and Daniel Urban in bpo-16522 [https://bugs.python.org/issue?@action=redirect&bpo=16522].)

The doctest command line interface now uses argparse, and has two new options, -o and -f. -o allows doctest options to be specified on the command line, and -f is a shorthand for -o FAIL_FAST (to parallel the similar option supported by the unittest CLI). (Contributed by R. David Murray in bpo-11390 [https://bugs.python.org/issue?@action=redirect&bpo=11390].)

doctest will now find doctests in extension module __doc__ strings. (Contributed by Zachary Ware in bpo-3158 [https://bugs.python.org/issue?@action=redirect&bpo=3158].)

email

as_string() now accepts a policy argument to override the default policy of the message when generating a string representation of it. This means that as_string can now be used in more circumstances, instead of having to create and use a generator in order to pass formatting parameters to its flatten method. (Contributed by R. David Murray in bpo-18600 [https://bugs.python.org/issue?@action=redirect&bpo=18600].)

New method as_bytes() added to produce a bytes representation of the message in a fashion similar to how as_string produces a string representation. It does not accept the maxheaderlen argument, but does accept the unixfrom and policy arguments. The Message __bytes__() method calls it, meaning that bytes(mymsg) will now produce the intuitive result: a bytes object containing the fully formatted message. (Contributed by R. David Murray in bpo-18600 [https://bugs.python.org/issue?@action=redirect&bpo=18600].)

The Message.set_param() message now accepts a replace keyword argument. When specified, the associated header will be updated without changing its location in the list of headers. For backward compatibility, the default is False. (Contributed by R. David Murray in bpo-18891 [https://bugs.python.org/issue?@action=redirect&bpo=18891].)

A pair of new subclasses of Message have been added (EmailMessage and MIMEPart), along with a new sub-module, contentmanager and a new policy attribute content_manager. All documentation is currently in the new module, which is being added as part of email’s new provisional API. These classes provide a number of new methods that make extracting content from and inserting content into email messages much easier. For details, see the contentmanager documentation and the email: 예제. These API additions complete the bulk of the work that was planned as part of the email6 project. The currently provisional API is scheduled to become final in Python 3.5 (possibly with a few minor additions in the area of error handling). (Contributed by R. David Murray in bpo-18891 [https://bugs.python.org/issue?@action=redirect&bpo=18891].)

filecmp

A new clear_cache() function provides the ability to clear the filecmp comparison cache, which uses os.stat() information to determine if the file has changed since the last compare. This can be used, for example, if the file might have been changed and re-checked in less time than the resolution of a particular filesystem’s file modification time field. (Contributed by Mark Levitt in bpo-18149 [https://bugs.python.org/issue?@action=redirect&bpo=18149].)

New module attribute DEFAULT_IGNORES provides the list of directories that are used as the default value for the ignore parameter of the dircmp() function. (Contributed by Eli Bendersky in bpo-15442 [https://bugs.python.org/issue?@action=redirect&bpo=15442].)

functools

The new partialmethod() descriptor brings partial argument application to descriptors, just as partial() provides for normal callables. The new descriptor also makes it easier to get arbitrary callables (including partial() instances) to behave like normal instance methods when included in a class definition. (Contributed by Alon Horev and Nick Coghlan in bpo-4331 [https://bugs.python.org/issue?@action=redirect&bpo=4331].)

The new singledispatch() decorator brings support for single-dispatch generic functions to the Python standard library. Where object oriented programming focuses on grouping multiple operations on a common set of data into a class, a generic function focuses on grouping multiple implementations of an operation that allows it to work with different kinds of data.

더 보기

PEP 443 [https://www.python.org/dev/peps/pep-0443] – Single-dispatch generic functions

PEP written and implemented by Łukasz Langa.

total_ordering() now supports a return value of NotImplemented from the underlying comparison function. (Contributed by Katie Miller in bpo-10042 [https://bugs.python.org/issue?@action=redirect&bpo=10042].)

A pure-python version of the partial() function is now in the stdlib; in CPython it is overridden by the C accelerated version, but it is available for other implementations to use. (Contributed by Brian Thorne in bpo-12428 [https://bugs.python.org/issue?@action=redirect&bpo=12428].)

gc

New function get_stats() returns a list of three per-generation dictionaries containing the collections statistics since interpreter startup. (Contributed by Antoine Pitrou in bpo-16351 [https://bugs.python.org/issue?@action=redirect&bpo=16351].)

glob

A new function escape() provides a way to escape special characters in a filename so that they do not become part of the globbing expansion but are instead matched literally. (Contributed by Serhiy Storchaka in bpo-8402 [https://bugs.python.org/issue?@action=redirect&bpo=8402].)

hashlib

A new hashlib.pbkdf2_hmac() function provides the PKCS#5 password-based key derivation function 2 [https://en.wikipedia.org/wiki/PBKDF2]. (Contributed by Christian Heimes in bpo-18582 [https://bugs.python.org/issue?@action=redirect&bpo=18582].)

The name attribute of hashlib hash objects is now a formally supported interface. It has always existed in CPython’s hashlib (although it did not return lower case names for all supported hashes), but it was not a public interface and so some other Python implementations have not previously supported it. (Contributed by Jason R. Coombs in bpo-18532 [https://bugs.python.org/issue?@action=redirect&bpo=18532].)

hmac

hmac now accepts bytearray as well as bytes for the key argument to the new() function, and the msg parameter to both the new() function and the update() method now accepts any type supported by the hashlib module. (Contributed by Jonas Borgström in bpo-18240 [https://bugs.python.org/issue?@action=redirect&bpo=18240].)

The digestmod argument to the hmac.new() function may now be any hash digest name recognized by hashlib. In addition, the current behavior in which the value of digestmod defaults to MD5 is deprecated: in a future version of Python there will be no default value. (Contributed by Christian Heimes in bpo-17276 [https://bugs.python.org/issue?@action=redirect&bpo=17276].)

With the addition of block_size and name attributes (and the formal documentation of the digest_size attribute), the hmac module now conforms fully to the PEP 247 [https://www.python.org/dev/peps/pep-0247] API. (Contributed by Christian Heimes in bpo-18775 [https://bugs.python.org/issue?@action=redirect&bpo=18775].)

html

New function unescape() function converts HTML5 character references to the corresponding Unicode characters. (Contributed by Ezio Melotti in bpo-2927 [https://bugs.python.org/issue?@action=redirect&bpo=2927].)

HTMLParser accepts a new keyword argument convert_charrefs that, when True, automatically converts all character references. For backward-compatibility, its value defaults to False, but it will change to True in a future version of Python, so you are invited to set it explicitly and update your code to use this new feature. (Contributed by Ezio Melotti in bpo-13633 [https://bugs.python.org/issue?@action=redirect&bpo=13633].)

The strict argument of HTMLParser is now deprecated. (Contributed by Ezio Melotti in bpo-15114 [https://bugs.python.org/issue?@action=redirect&bpo=15114].)

http

send_error() now accepts an optional additional explain parameter which can be used to provide an extended error description, overriding the hardcoded default if there is one. This extended error description will be formatted using the error_message_format attribute and sent as the body of the error response. (Contributed by Karl Cow in bpo-12921 [https://bugs.python.org/issue?@action=redirect&bpo=12921].)

The http.server command line interface now has a -b/--bind option that causes the server to listen on a specific address. (Contributed by Malte Swart in bpo-17764 [https://bugs.python.org/issue?@action=redirect&bpo=17764].)

idlelib and IDLE

Since idlelib implements the IDLE shell and editor and is not intended for import by other programs, it gets improvements with every release. See Lib/idlelib/NEWS.txt for a cumulative list of changes since 3.3.0, as well as changes made in future 3.4.x releases. This file is also available from the IDLE Help ‣ About IDLE dialog.

importlib

The InspectLoader ABC defines a new method, source_to_code() that accepts source data and a path and returns a code object. The default implementation is equivalent to compile(data, path, 'exec', dont_inherit=True). (Contributed by Eric Snow and Brett Cannon in bpo-15627 [https://bugs.python.org/issue?@action=redirect&bpo=15627].)

InspectLoader also now has a default implementation for the get_code() method. However, it will normally be desirable to override the default implementation for performance reasons. (Contributed by Brett Cannon in bpo-18072 [https://bugs.python.org/issue?@action=redirect&bpo=18072].)

The reload() function has been moved from imp to importlib as part of the imp module deprecation. (Contributed by Berker Peksag in bpo-18193 [https://bugs.python.org/issue?@action=redirect&bpo=18193].)

importlib.util now has a MAGIC_NUMBER attribute providing access to the bytecode version number. This replaces the get_magic() function in the deprecated imp module. (Contributed by Brett Cannon in bpo-18192 [https://bugs.python.org/issue?@action=redirect&bpo=18192].)

New importlib.util functions cache_from_source() and source_from_cache() replace the same-named functions in the deprecated imp module. (Contributed by Brett Cannon in bpo-18194 [https://bugs.python.org/issue?@action=redirect&bpo=18194].)

The importlib bootstrap NamespaceLoader now conforms to the InspectLoader ABC, which means that runpy and python -m can now be used with namespace packages. (Contributed by Brett Cannon in bpo-18058 [https://bugs.python.org/issue?@action=redirect&bpo=18058].)

importlib.util has a new function decode_source() that decodes source from bytes using universal newline processing. This is useful for implementing InspectLoader.get_source() methods.

importlib.machinery.ExtensionFileLoader now has a get_filename() method. This was inadvertently omitted in the original implementation. (Contributed by Eric Snow in bpo-19152 [https://bugs.python.org/issue?@action=redirect&bpo=19152].)

inspect

The inspect module now offers a basic command line interface to quickly display source code and other information for modules, classes and functions. (Contributed by Claudiu Popa and Nick Coghlan in bpo-18626 [https://bugs.python.org/issue?@action=redirect&bpo=18626].)

unwrap() makes it easy to unravel wrapper function chains created by functools.wraps() (and any other API that sets the __wrapped__ attribute on a wrapper function). (Contributed by Daniel Urban, Aaron Iles and Nick Coghlan in bpo-13266 [https://bugs.python.org/issue?@action=redirect&bpo=13266].)

As part of the implementation of the new enum module, the inspect module now has substantially better support for custom __dir__ methods and dynamic class attributes provided through metaclasses. (Contributed by Ethan Furman in bpo-18929 [https://bugs.python.org/issue?@action=redirect&bpo=18929] and bpo-19030 [https://bugs.python.org/issue?@action=redirect&bpo=19030].)

getfullargspec() and getargspec() now use the signature() API. This allows them to support a much broader range of callables, including those with __signature__ attributes, those with metadata provided by argument clinic, functools.partial() objects and more. Note that, unlike signature(), these functions still ignore __wrapped__ attributes, and report the already bound first argument for bound methods, so it is still necessary to update your code to use signature() directly if those features are desired. (Contributed by Yury Selivanov in bpo-17481 [https://bugs.python.org/issue?@action=redirect&bpo=17481].)

signature() now supports duck types of CPython functions, which adds support for functions compiled with Cython. (Contributed by Stefan Behnel and Yury Selivanov in bpo-17159 [https://bugs.python.org/issue?@action=redirect&bpo=17159].)

ipaddress

ipaddress was added to the standard library in Python 3.3 as a provisional API. With the release of Python 3.4, this qualification has been removed: ipaddress is now considered a stable API, covered by the normal standard library requirements to maintain backwards compatibility.

A new is_global property is True if an address is globally routeable. (Contributed by Peter Moody in bpo-17400 [https://bugs.python.org/issue?@action=redirect&bpo=17400].)

logging

The TimedRotatingFileHandler has a new atTime parameter that can be used to specify the time of day when rollover should happen. (Contributed by Ronald Oussoren in bpo-9556 [https://bugs.python.org/issue?@action=redirect&bpo=9556].)

SocketHandler and DatagramHandler now support Unix domain sockets (by setting port to None). (Contributed by Vinay Sajip in commit ce46195b56a9.)

fileConfig() now accepts a configparser.RawConfigParser subclass instance for the fname parameter. This facilitates using a configuration file when logging configuration is just a part of the overall application configuration, or where the application modifies the configuration before passing it to fileConfig(). (Contributed by Vinay Sajip in bpo-16110 [https://bugs.python.org/issue?@action=redirect&bpo=16110].)

Logging configuration data received from a socket via the logging.config.listen() function can now be validated before being processed by supplying a verification function as the argument to the new verify keyword argument. (Contributed by Vinay Sajip in bpo-15452 [https://bugs.python.org/issue?@action=redirect&bpo=15452].)

marshal

The default marshal version has been bumped to 3. The code implementing the new version restores the Python2 behavior of recording only one copy of interned strings and preserving the interning on deserialization, and extends this “one copy” ability to any object type (including handling recursive references). This reduces both the size of .pyc files and the amount of memory a module occupies in memory when it is loaded from a .pyc (or .pyo) file. (Contributed by Kristján Valur Jónsson in bpo-16475 [https://bugs.python.org/issue?@action=redirect&bpo=16475], with additional speedups by Antoine Pitrou in bpo-19219 [https://bugs.python.org/issue?@action=redirect&bpo=19219].)

mmap

mmap objects can now be weakrefed. (Contributed by Valerie Lambert in bpo-4885 [https://bugs.python.org/issue?@action=redirect&bpo=4885].)

multiprocessing

On Unix two new start methods, spawn and forkserver, have been added for starting processes using multiprocessing. These make the mixing of processes with threads more robust, and the spawn method matches the semantics that multiprocessing has always used on Windows. New function get_all_start_methods() reports all start methods available on the platform, get_start_method() reports the current start method, and set_start_method() sets the start method. (Contributed by Richard Oudkerk in bpo-8713 [https://bugs.python.org/issue?@action=redirect&bpo=8713].)

multiprocessing also now has the concept of a context, which determines how child processes are created. New function get_context() returns a context that uses a specified start method. It has the same API as the multiprocessing module itself, so you can use it to create Pools and other objects that will operate within that context. This allows a framework and an application or different parts of the same application to use multiprocessing without interfering with each other. (Contributed by Richard Oudkerk in bpo-18999 [https://bugs.python.org/issue?@action=redirect&bpo=18999].)

Except when using the old fork start method, child processes no longer inherit unneeded handles/file descriptors from their parents (part of bpo-8713 [https://bugs.python.org/issue?@action=redirect&bpo=8713]).

multiprocessing now relies on runpy (which implements the -m switch) to initialise __main__ appropriately in child processes when using the spawn or forkserver start methods. This resolves some edge cases where combining multiprocessing, the -m command line switch, and explicit relative imports could cause obscure failures in child processes. (Contributed by Nick Coghlan in bpo-19946 [https://bugs.python.org/issue?@action=redirect&bpo=19946].)

operator

New function length_hint() provides an implementation of the specification for how the __length_hint__() special method should be used, as part of the PEP 424 [https://www.python.org/dev/peps/pep-0424] formal specification of this language feature. (Contributed by Armin Ronacher in bpo-16148 [https://bugs.python.org/issue?@action=redirect&bpo=16148].)

There is now a pure-python version of the operator module available for reference and for use by alternate implementations of Python. (Contributed by Zachary Ware in bpo-16694 [https://bugs.python.org/issue?@action=redirect&bpo=16694].)

os

There are new functions to get and set the inheritable flag of a file descriptor (os.get_inheritable(), os.set_inheritable()) or a Windows handle (os.get_handle_inheritable(), os.set_handle_inheritable()).

New function cpu_count() reports the number of CPUs available on the platform on which Python is running (or None if the count can’t be determined). The multiprocessing.cpu_count() function is now implemented in terms of this function). (Contributed by Trent Nelson, Yogesh Chaudhari, Victor Stinner, and Charles-François Natali in bpo-17914 [https://bugs.python.org/issue?@action=redirect&bpo=17914].)

os.path.samestat() is now available on the Windows platform (and the os.path.samefile() implementation is now shared between Unix and Windows). (Contributed by Brian Curtin in bpo-11939 [https://bugs.python.org/issue?@action=redirect&bpo=11939].)

os.path.ismount() now recognizes volumes mounted below a drive root on Windows. (Contributed by Tim Golden in bpo-9035 [https://bugs.python.org/issue?@action=redirect&bpo=9035].)

os.open() supports two new flags on platforms that provide them, O_PATH (un-opened file descriptor), and O_TMPFILE (unnamed temporary file; as of 3.4.0 release available only on Linux systems with a kernel version of 3.11 or newer that have uapi headers). (Contributed by Christian Heimes in bpo-18673 [https://bugs.python.org/issue?@action=redirect&bpo=18673] and Benjamin Peterson, respectively.)

pdb

pdb has been enhanced to handle generators, yield, and yield from in a more useful fashion. This is especially helpful when debugging asyncio based programs. (Contributed by Andrew Svetlov and Xavier de Gaye in bpo-16596 [https://bugs.python.org/issue?@action=redirect&bpo=16596].)

The print command has been removed from pdb, restoring access to the Python print() function from the pdb command line. Python2’s pdb did not have a print command; instead, entering print executed the print statement. In Python3 print was mistakenly made an alias for the pdb p command. p, however, prints the repr of its argument, not the str like the Python2 print command did. Worse, the Python3 pdb print command shadowed the Python3 print function, making it inaccessible at the pdb prompt. (Contributed by Connor Osborn in bpo-18764 [https://bugs.python.org/issue?@action=redirect&bpo=18764].)

pickle

pickle now supports (but does not use by default) a new pickle protocol, protocol 4. This new protocol addresses a number of issues that were present in previous protocols, such as the serialization of nested classes, very large strings and containers, and classes whose __new__() method takes keyword-only arguments. It also provides some efficiency improvements.

더 보기

PEP 3154 [https://www.python.org/dev/peps/pep-3154] – Pickle protocol 4

PEP written by Antoine Pitrou and implemented by Alexandre Vassalotti.

plistlib

plistlib now has an API that is similar to the standard pattern for stdlib serialization protocols, with new load(), dump(), loads(), and dumps() functions. (The older API is now deprecated.) In addition to the already supported XML plist format (FMT_XML), it also now supports the binary plist format (FMT_BINARY). (Contributed by Ronald Oussoren and others in bpo-14455 [https://bugs.python.org/issue?@action=redirect&bpo=14455].)

poplib

Two new methods have been added to poplib: capa(), which returns the list of capabilities advertised by the POP server, and stls(), which switches a clear-text POP3 session into an encrypted POP3 session if the POP server supports it. (Contributed by Lorenzo Catucci in bpo-4473 [https://bugs.python.org/issue?@action=redirect&bpo=4473].)

pprint

The pprint module’s PrettyPrinter class and its pformat(), and pprint() functions have a new option, compact, that controls how the output is formatted. Currently setting compact to True means that sequences will be printed with as many sequence elements as will fit within width on each (indented) line. (Contributed by Serhiy Storchaka in bpo-19132 [https://bugs.python.org/issue?@action=redirect&bpo=19132].)

Long strings are now wrapped using Python’s normal line continuation syntax. (Contributed by Antoine Pitrou in bpo-17150 [https://bugs.python.org/issue?@action=redirect&bpo=17150].)

pty

pty.spawn() now returns the status value from os.waitpid() on the child process, instead of None. (Contributed by Gregory P. Smith.)

pydoc

The pydoc module is now based directly on the inspect.signature() introspection API, allowing it to provide signature information for a wider variety of callable objects. This change also means that __wrapped__ attributes are now taken into account when displaying help information. (Contributed by Larry Hastings in bpo-19674 [https://bugs.python.org/issue?@action=redirect&bpo=19674].)

The pydoc module no longer displays the self parameter for already bound methods. Instead, it aims to always display the exact current signature of the supplied callable. (Contributed by Larry Hastings in bpo-20710 [https://bugs.python.org/issue?@action=redirect&bpo=20710].)

In addition to the changes that have been made to pydoc directly, its handling of custom __dir__ methods and various descriptor behaviours has also been improved substantially by the underlying changes in the inspect module.

As the help() builtin is based on pydoc, the above changes also affect the behaviour of help().

re

New fullmatch() function and regex.fullmatch() method anchor the pattern at both ends of the string to match. This provides a way to be explicit about the goal of the match, which avoids a class of subtle bugs where $ characters get lost during code changes or the addition of alternatives to an existing regular expression. (Contributed by Matthew Barnett in bpo-16203 [https://bugs.python.org/issue?@action=redirect&bpo=16203].)

The repr of regex objects now includes the pattern and the flags; the repr of match objects now includes the start, end, and the part of the string that matched. (Contributed by Hugo Lopes Tavares and Serhiy Storchaka in bpo-13592 [https://bugs.python.org/issue?@action=redirect&bpo=13592] and bpo-17087 [https://bugs.python.org/issue?@action=redirect&bpo=17087].)

resource

New prlimit() function, available on Linux platforms with a kernel version of 2.6.36 or later and glibc of 2.13 or later, provides the ability to query or set the resource limits for processes other than the one making the call. (Contributed by Christian Heimes in bpo-16595 [https://bugs.python.org/issue?@action=redirect&bpo=16595].)

On Linux kernel version 2.6.36 or later, there are also some new Linux specific constants: RLIMIT_MSGQUEUE, RLIMIT_NICE, RLIMIT_RTPRIO, RLIMIT_RTTIME, and RLIMIT_SIGPENDING. (Contributed by Christian Heimes in bpo-19324 [https://bugs.python.org/issue?@action=redirect&bpo=19324].)

On FreeBSD version 9 and later, there some new FreeBSD specific constants: RLIMIT_SBSIZE, RLIMIT_SWAP, and RLIMIT_NPTS. (Contributed by Claudiu Popa in bpo-19343 [https://bugs.python.org/issue?@action=redirect&bpo=19343].)

select

epoll objects now support the context management protocol. When used in a with statement, the close() method will be called automatically at the end of the block. (Contributed by Serhiy Storchaka in bpo-16488 [https://bugs.python.org/issue?@action=redirect&bpo=16488].)

devpoll objects now have fileno() and close() methods, as well as a new attribute closed. (Contributed by Victor Stinner in bpo-18794 [https://bugs.python.org/issue?@action=redirect&bpo=18794].)

shelve

Shelf instances may now be used in with statements, and will be automatically closed at the end of the with block. (Contributed by Filip Gruszczyński in bpo-13896 [https://bugs.python.org/issue?@action=redirect&bpo=13896].)

shutil

copyfile() now raises a specific Error subclass, SameFileError, when the source and destination are the same file, which allows an application to take appropriate action on this specific error. (Contributed by Atsuo Ishimoto and Hynek Schlawack in bpo-1492704 [https://bugs.python.org/issue?@action=redirect&bpo=1492704].)

smtpd

The SMTPServer and SMTPChannel classes now accept a map keyword argument which, if specified, is passed in to asynchat.async_chat as its map argument. This allows an application to avoid affecting the global socket map. (Contributed by Vinay Sajip in bpo-11959 [https://bugs.python.org/issue?@action=redirect&bpo=11959].)

smtplib

SMTPException is now a subclass of OSError, which allows both socket level errors and SMTP protocol level errors to be caught in one try/except statement by code that only cares whether or not an error occurred. (Contributed by Ned Jackson Lovely in bpo-2118 [https://bugs.python.org/issue?@action=redirect&bpo=2118].)

socket

The socket module now supports the CAN_BCM protocol on platforms that support it. (Contributed by Brian Thorne in bpo-15359 [https://bugs.python.org/issue?@action=redirect&bpo=15359].)

Socket objects have new methods to get or set their inheritable flag, get_inheritable() and set_inheritable().

The socket.AF_* and socket.SOCK_* constants are now enumeration values using the new enum module. This allows meaningful names to be printed during debugging, instead of integer “magic numbers”.

The AF_LINK constant is now available on BSD and OSX.

inet_pton() and inet_ntop() are now supported on Windows. (Contributed by Atsuo Ishimoto in bpo-7171 [https://bugs.python.org/issue?@action=redirect&bpo=7171].)

sqlite3

A new boolean parameter to the connect() function, uri, can be used to indicate that the database parameter is a uri (see the SQLite URI documentation [https://www.sqlite.org/uri.html]). (Contributed by poq in bpo-13773 [https://bugs.python.org/issue?@action=redirect&bpo=13773].)

ssl

PROTOCOL_TLSv1_1 and PROTOCOL_TLSv1_2 (TLSv1.1 and TLSv1.2 support) have been added; support for these protocols is only available if Python is linked with OpenSSL 1.0.1 or later. (Contributed by Michele Orrù and Antoine Pitrou in bpo-16692 [https://bugs.python.org/issue?@action=redirect&bpo=16692].)

New function create_default_context() provides a standard way to obtain an SSLContext whose settings are intended to be a reasonable balance between compatibility and security. These settings are more stringent than the defaults provided by the SSLContext constructor, and may be adjusted in the future, without prior deprecation, if best-practice security requirements change. The new recommended best practice for using stdlib libraries that support SSL is to use create_default_context() to obtain an SSLContext object, modify it if needed, and then pass it as the context argument of the appropriate stdlib API. (Contributed by Christian Heimes in bpo-19689 [https://bugs.python.org/issue?@action=redirect&bpo=19689].)

SSLContext method load_verify_locations() accepts a new optional argument cadata, which can be used to provide PEM or DER encoded certificates directly via strings or bytes, respectively. (Contributed by Christian Heimes in bpo-18138 [https://bugs.python.org/issue?@action=redirect&bpo=18138].)

New function get_default_verify_paths() returns a named tuple of the paths and environment variables that the set_default_verify_paths() method uses to set OpenSSL’s default cafile and capath. This can be an aid in debugging default verification issues. (Contributed by Christian Heimes in bpo-18143 [https://bugs.python.org/issue?@action=redirect&bpo=18143].)

SSLContext has a new method, cert_store_stats(), that reports the number of loaded X.509 certs, X.509 CA certs, and certificate revocation lists (crls), as well as a get_ca_certs() method that returns a list of the loaded CA certificates. (Contributed by Christian Heimes in bpo-18147 [https://bugs.python.org/issue?@action=redirect&bpo=18147].)

If OpenSSL 0.9.8 or later is available, SSLContext has a new attribute verify_flags that can be used to control the certificate verification process by setting it to some combination of the new constants VERIFY_DEFAULT, VERIFY_CRL_CHECK_LEAF, VERIFY_CRL_CHECK_CHAIN, or VERIFY_X509_STRICT. OpenSSL does not do any CRL verification by default. (Contributed by Christien Heimes in bpo-8813 [https://bugs.python.org/issue?@action=redirect&bpo=8813].)

New SSLContext method load_default_certs() loads a set of default “certificate authority” (CA) certificates from default locations, which vary according to the platform. It can be used to load both TLS web server authentication certificates (purpose=SERVER_AUTH) for a client to use to verify a server, and certificates for a server to use in verifying client certificates (purpose=CLIENT_AUTH). (Contributed by Christian Heimes in bpo-19292 [https://bugs.python.org/issue?@action=redirect&bpo=19292].)

Two new windows-only functions, enum_certificates() and enum_crls() provide the ability to retrieve certificates, certificate information, and CRLs from the Windows cert store. (Contributed by Christian Heimes in bpo-17134 [https://bugs.python.org/issue?@action=redirect&bpo=17134].)

Support for server-side SNI (Server Name Indication) using the new ssl.SSLContext.set_servername_callback() method. (Contributed by Daniel Black in bpo-8109 [https://bugs.python.org/issue?@action=redirect&bpo=8109].)

The dictionary returned by SSLSocket.getpeercert() contains additional X509v3 extension items: crlDistributionPoints, calIssuers, and OCSP URIs. (Contributed by Christian Heimes in bpo-18379 [https://bugs.python.org/issue?@action=redirect&bpo=18379].)

stat

The stat module is now backed by a C implementation in _stat. A C implementation is required as most of the values aren’t standardized and are platform-dependent. (Contributed by Christian Heimes in bpo-11016 [https://bugs.python.org/issue?@action=redirect&bpo=11016].)

The module supports new ST_MODE flags, S_IFDOOR, S_IFPORT, and S_IFWHT. (Contributed by Christian Hiemes in bpo-11016 [https://bugs.python.org/issue?@action=redirect&bpo=11016].)

struct

New function iter_unpack and a new struct.Struct.iter_unpack() method on compiled formats provide streamed unpacking of a buffer containing repeated instances of a given format of data. (Contributed by Antoine Pitrou in bpo-17804 [https://bugs.python.org/issue?@action=redirect&bpo=17804].)

subprocess

check_output() now accepts an input argument that can be used to provide the contents of stdin for the command that is run. (Contributed by Zack Weinberg in bpo-16624 [https://bugs.python.org/issue?@action=redirect&bpo=16624].)

getstatus() and getstatusoutput() now work on Windows. This change was actually inadvertently made in 3.3.4. (Contributed by Tim Golden in bpo-10197 [https://bugs.python.org/issue?@action=redirect&bpo=10197].)

sunau

The getparams() method now returns a namedtuple rather than a plain tuple. (Contributed by Claudiu Popa in bpo-18901 [https://bugs.python.org/issue?@action=redirect&bpo=18901].)

sunau.open() now supports the context management protocol: when used in a with block, the close method of the returned object will be called automatically at the end of the block. (Contributed by Serhiy Storchaka in bpo-18878 [https://bugs.python.org/issue?@action=redirect&bpo=18878].)

AU_write.setsampwidth() now supports 24 bit samples, thus adding support for writing 24 sample using the module. (Contributed by Serhiy Storchaka in bpo-19261 [https://bugs.python.org/issue?@action=redirect&bpo=19261].)

The writeframesraw() and writeframes() methods now accept any bytes-like object. (Contributed by Serhiy Storchaka in bpo-8311 [https://bugs.python.org/issue?@action=redirect&bpo=8311].)

sys

New function sys.getallocatedblocks() returns the current number of blocks allocated by the interpreter. (In CPython with the default --with-pymalloc setting, this is allocations made through the PyObject_Malloc() API.) This can be useful for tracking memory leaks, especially if automated via a test suite. (Contributed by Antoine Pitrou in bpo-13390 [https://bugs.python.org/issue?@action=redirect&bpo=13390].)

When the Python interpreter starts in interactive mode, it checks for an __interactivehook__ attribute on the sys module. If the attribute exists, its value is called with no arguments just before interactive mode is started. The check is made after the PYTHONSTARTUP file is read, so it can be set there. The site module sets it to a function that enables tab completion and history saving (in ~/.python-history) if the platform supports readline. If you do not want this (new) behavior, you can override it in PYTHONSTARTUP, sitecustomize, or usercustomize by deleting this attribute from sys (or setting it to some other callable). (Contributed by Éric Araujo and Antoine Pitrou in bpo-5845 [https://bugs.python.org/issue?@action=redirect&bpo=5845].)

tarfile

The tarfile module now supports a simple Command-Line Interface when called as a script directly or via -m. This can be used to create and extract tarfile archives. (Contributed by Berker Peksag in bpo-13477 [https://bugs.python.org/issue?@action=redirect&bpo=13477].)

textwrap

The TextWrapper class has two new attributes/constructor arguments: max_lines, which limits the number of lines in the output, and placeholder, which is a string that will appear at the end of the output if it has been truncated because of max_lines. Building on these capabilities, a new convenience function shorten() collapses all of the whitespace in the input to single spaces and produces a single line of a given width that ends with the placeholder (by default, [...]). (Contributed by Antoine Pitrou and Serhiy Storchaka in bpo-18585 [https://bugs.python.org/issue?@action=redirect&bpo=18585] and bpo-18725 [https://bugs.python.org/issue?@action=redirect&bpo=18725].)

threading

The Thread object representing the main thread can be obtained from the new main_thread() function. In normal conditions this will be the thread from which the Python interpreter was started. (Contributed by Andrew Svetlov in bpo-18882 [https://bugs.python.org/issue?@action=redirect&bpo=18882].)

traceback

A new traceback.clear_frames() function takes a traceback object and clears the local variables in all of the frames it references, reducing the amount of memory consumed. (Contributed by Andrew Kuchling in bpo-1565525 [https://bugs.python.org/issue?@action=redirect&bpo=1565525].)

types

A new DynamicClassAttribute() descriptor provides a way to define an attribute that acts normally when looked up through an instance object, but which is routed to the class __getattr__ when looked up through the class. This allows one to have properties active on a class, and have virtual attributes on the class with the same name (see Enum for an example). (Contributed by Ethan Furman in bpo-19030 [https://bugs.python.org/issue?@action=redirect&bpo=19030].)

urllib

urllib.request now supports data: URLs via the DataHandler class. (Contributed by Mathias Panzenböck in bpo-16423 [https://bugs.python.org/issue?@action=redirect&bpo=16423].)

The http method that will be used by a Request class can now be specified by setting a method class attribute on the subclass. (Contributed by Jason R Coombs in bpo-18978 [https://bugs.python.org/issue?@action=redirect&bpo=18978].)

Request objects are now reusable: if the full_url or data attributes are modified, all relevant internal properties are updated. This means, for example, that it is now possible to use the same Request object in more than one OpenerDirector.open() call with different data arguments, or to modify a Request’s url rather than recomputing it from scratch. There is also a new remove_header() method that can be used to remove headers from a Request. (Contributed by Alexey Kachayev in bpo-16464 [https://bugs.python.org/issue?@action=redirect&bpo=16464], Daniel Wozniak in bpo-17485 [https://bugs.python.org/issue?@action=redirect&bpo=17485], and Damien Brecht and Senthil Kumaran in bpo-17272 [https://bugs.python.org/issue?@action=redirect&bpo=17272].)

HTTPError objects now have a headers attribute that provides access to the HTTP response headers associated with the error. (Contributed by Berker Peksag in bpo-15701 [https://bugs.python.org/issue?@action=redirect&bpo=15701].)

unittest

The TestCase class has a new method, subTest(), that produces a context manager whose with block becomes a “sub-test”. This context manager allows a test method to dynamically generate subtests by, say, calling the subTest context manager inside a loop. A single test method can thereby produce an indefinite number of separately-identified and separately-counted tests, all of which will run even if one or more of them fail. For example:

class NumbersTest(unittest.TestCase):
    def test_even(self):
        for i in range(6):
            with self.subTest(i=i):
                self.assertEqual(i % 2, 0)

will result in six subtests, each identified in the unittest verbose output with a label consisting of the variable name i and a particular value for that variable (i=0, i=1, etc). See 부분 테스트(subtest)를 사용하여 테스트 반복 구별 짖기 for the full version of this example. (Contributed by Antoine Pitrou in bpo-16997 [https://bugs.python.org/issue?@action=redirect&bpo=16997].)

unittest.main() now accepts an iterable of test names for defaultTest, where previously it only accepted a single test name as a string. (Contributed by Jyrki Pulliainen in bpo-15132 [https://bugs.python.org/issue?@action=redirect&bpo=15132].)

If SkipTest is raised during test discovery (that is, at the module level in the test file), it is now reported as a skip instead of an error. (Contributed by Zach Ware in bpo-16935 [https://bugs.python.org/issue?@action=redirect&bpo=16935].)

discover() now sorts the discovered files to provide consistent test ordering. (Contributed by Martin Melin and Jeff Ramnani in bpo-16709 [https://bugs.python.org/issue?@action=redirect&bpo=16709].)

TestSuite now drops references to tests as soon as the test has been run, if the test is successful. On Python interpreters that do garbage collection, this allows the tests to be garbage collected if nothing else is holding a reference to the test. It is possible to override this behavior by creating a TestSuite subclass that defines a custom _removeTestAtIndex method. (Contributed by Tom Wardill, Matt McClure, and Andrew Svetlov in bpo-11798 [https://bugs.python.org/issue?@action=redirect&bpo=11798].)

A new test assertion context-manager, assertLogs(), will ensure that a given block of code emits a log message using the logging module. By default the message can come from any logger and have a priority of INFO or higher, but both the logger name and an alternative minimum logging level may be specified. The object returned by the context manager can be queried for the LogRecords and/or formatted messages that were logged. (Contributed by Antoine Pitrou in bpo-18937 [https://bugs.python.org/issue?@action=redirect&bpo=18937].)

Test discovery now works with namespace packages (Contributed by Claudiu Popa in bpo-17457 [https://bugs.python.org/issue?@action=redirect&bpo=17457].)

unittest.mock objects now inspect their specification signatures when matching calls, which means an argument can now be matched by either position or name, instead of only by position. (Contributed by Antoine Pitrou in bpo-17015 [https://bugs.python.org/issue?@action=redirect&bpo=17015].)

mock_open() objects now have readline and readlines methods. (Contributed by Toshio Kuratomi in bpo-17467 [https://bugs.python.org/issue?@action=redirect&bpo=17467].)

venv

venv now includes activation scripts for the csh and fish shells. (Contributed by Andrew Svetlov in bpo-15417 [https://bugs.python.org/issue?@action=redirect&bpo=15417].)

EnvBuilder and the create() convenience function take a new keyword argument with_pip, which defaults to False, that controls whether or not EnvBuilder ensures that pip is installed in the virtual environment. (Contributed by Nick Coghlan in bpo-19552 [https://bugs.python.org/issue?@action=redirect&bpo=19552] as part of the PEP 453 [https://www.python.org/dev/peps/pep-0453] implementation.)

wave

The getparams() method now returns a namedtuple rather than a plain tuple. (Contributed by Claudiu Popa in bpo-17487 [https://bugs.python.org/issue?@action=redirect&bpo=17487].)

wave.open() now supports the context management protocol. (Contributed by Claudiu Popa in bpo-17616 [https://bugs.python.org/issue?@action=redirect&bpo=17616].)

wave can now write output to unseekable files. (Contributed by David Jones, Guilherme Polo, and Serhiy Storchaka in bpo-5202 [https://bugs.python.org/issue?@action=redirect&bpo=5202].)

The writeframesraw() and writeframes() methods now accept any bytes-like object. (Contributed by Serhiy Storchaka in bpo-8311 [https://bugs.python.org/issue?@action=redirect&bpo=8311].)

weakref

New WeakMethod class simulates weak references to bound methods. (Contributed by Antoine Pitrou in bpo-14631 [https://bugs.python.org/issue?@action=redirect&bpo=14631].)

New finalize class makes it possible to register a callback to be invoked when an object is garbage collected, without needing to carefully manage the lifecycle of the weak reference itself. (Contributed by Richard Oudkerk in bpo-15528 [https://bugs.python.org/issue?@action=redirect&bpo=15528].)

The callback, if any, associated with a ref is now exposed via the __callback__ attribute. (Contributed by Mark Dickinson in bpo-17643 [https://bugs.python.org/issue?@action=redirect&bpo=17643].)

xml.etree

A new parser, XMLPullParser, allows a non-blocking applications to parse XML documents. An example can be seen at Pull API for non-blocking parsing. (Contributed by Antoine Pitrou in bpo-17741 [https://bugs.python.org/issue?@action=redirect&bpo=17741].)

The xml.etree.ElementTree tostring() and tostringlist() functions, and the ElementTree write() method, now have a short_empty_elements keyword-only parameter providing control over whether elements with no content are written in abbreviated (<tag />) or expanded (<tag></tag>) form. (Contributed by Ariel Poliak and Serhiy Storchaka in bpo-14377 [https://bugs.python.org/issue?@action=redirect&bpo=14377].)

zipfile

The writepy() method of the PyZipFile class has a new filterfunc option that can be used to control which directories and files are added to the archive. For example, this could be used to exclude test files from the archive. (Contributed by Christian Tismer in bpo-19274 [https://bugs.python.org/issue?@action=redirect&bpo=19274].)

The allowZip64 parameter to ZipFile and PyZipfile is now True by default. (Contributed by William Mallard in bpo-17201 [https://bugs.python.org/issue?@action=redirect&bpo=17201].)

CPython Implementation Changes

PEP 445: Customization of CPython Memory Allocators

PEP 445 [https://www.python.org/dev/peps/pep-0445] adds new C level interfaces to customize memory allocation in the CPython interpreter.

더 보기

PEP 445 [https://www.python.org/dev/peps/pep-0445] – Add new APIs to customize Python memory allocators

PEP written and implemented by Victor Stinner.

PEP 442: Safe Object Finalization

PEP 442 [https://www.python.org/dev/peps/pep-0442] removes the current limitations and quirks of object finalization in CPython. With it, objects with __del__() methods, as well as generators with finally clauses, can be finalized when they are part of a reference cycle.

As part of this change, module globals are no longer forcibly set to None during interpreter shutdown in most cases, instead relying on the normal operation of the cyclic garbage collector. This avoids a whole class of interpreter-shutdown-time errors, usually involving __del__ methods, that have plagued Python since the cyclic GC was first introduced.

더 보기

PEP 442 [https://www.python.org/dev/peps/pep-0442] – Safe object finalization

PEP written and implemented by Antoine Pitrou.

PEP 456: Secure and Interchangeable Hash Algorithm

PEP 456 [https://www.python.org/dev/peps/pep-0456] follows up on earlier security fix work done on Python’s hash algorithm to address certain DOS attacks to which public facing APIs backed by dictionary lookups may be subject. (See bpo-14621 [https://bugs.python.org/issue?@action=redirect&bpo=14621] for the start of the current round of improvements.) The PEP unifies CPython’s hash code to make it easier for a packager to substitute a different hash algorithm, and switches Python’s default implementation to a SipHash implementation on platforms that have a 64 bit data type. Any performance differences in comparison with the older FNV algorithm are trivial.

The PEP adds additional fields to the sys.hash_info named tuple to describe the hash algorithm in use by the currently executing binary. Otherwise, the PEP does not alter any existing CPython APIs.

PEP 436: Argument Clinic

“Argument Clinic” (PEP 436 [https://www.python.org/dev/peps/pep-0436]) is now part of the CPython build process and can be used to simplify the process of defining and maintaining accurate signatures for builtins and standard library extension modules implemented in C.

Some standard library extension modules have been converted to use Argument Clinic in Python 3.4, and pydoc and inspect have been updated accordingly.

It is expected that signature metadata for programmatic introspection will be added to additional callables implemented in C as part of Python 3.4 maintenance releases.

참고

The Argument Clinic PEP is not fully up to date with the state of the implementation. This has been deemed acceptable by the release manager and core development team in this case, as Argument Clinic will not be made available as a public API for third party use in Python 3.4.

더 보기

PEP 436 [https://www.python.org/dev/peps/pep-0436] – The Argument Clinic DSL

PEP written and implemented by Larry Hastings.

Other Build and C API Changes

The new PyType_GetSlot() function has been added to the stable ABI, allowing retrieval of function pointers from named type slots when using the limited API. (Contributed by Martin von Löwis in bpo-17162 [https://bugs.python.org/issue?@action=redirect&bpo=17162].)

The new Py_SetStandardStreamEncoding() pre-initialization API allows applications embedding the CPython interpreter to reliably force a particular encoding and error handler for the standard streams. (Contributed by Bastien Montagne and Nick Coghlan in bpo-16129 [https://bugs.python.org/issue?@action=redirect&bpo=16129].)

Most Python C APIs that don’t mutate string arguments are now correctly marked as accepting const char * rather than char *. (Contributed by Serhiy Storchaka in bpo-1772673 [https://bugs.python.org/issue?@action=redirect&bpo=1772673].)

A new shell version of python-config can be used even when a python interpreter is not available (for example, in cross compilation scenarios).

PyUnicode_FromFormat() now supports width and precision specifications for %s, %A, %U, %V, %S, and %R. (Contributed by Ysj Ray and Victor Stinner in bpo-7330 [https://bugs.python.org/issue?@action=redirect&bpo=7330].)

New function PyStructSequence_InitType2() supplements the existing PyStructSequence_InitType() function. The difference is that it returns 0 on success and -1 on failure.

The CPython source can now be compiled using the address sanity checking features of recent versions of GCC and clang: the false alarms in the small object allocator have been silenced. (Contributed by Dhiru Kholia in bpo-18596 [https://bugs.python.org/issue?@action=redirect&bpo=18596].)

The Windows build now uses Address Space Layout Randomization [https://en.wikipedia.org/wiki/Address_space_layout_randomization] and Data Execution Prevention [https://en.wikipedia.org/wiki/Data_Execution_Prevention]. (Contributed by Christian Heimes in bpo-16632 [https://bugs.python.org/issue?@action=redirect&bpo=16632].)

New function PyObject_LengthHint() is the C API equivalent of operator.length_hint(). (Contributed by Armin Ronacher in bpo-16148 [https://bugs.python.org/issue?@action=redirect&bpo=16148].)

Other Improvements

The python command has a new option, -I, which causes it to run in “isolated mode”, which means that sys.path contains neither the script’s directory nor the user’s site-packages directory, and all PYTHON* environment variables are ignored (it implies both -s and -E). Other restrictions may also be applied in the future, with the goal being to isolate the execution of a script from the user’s environment. This is appropriate, for example, when Python is used to run a system script. On most POSIX systems it can and should be used in the #! line of system scripts. (Contributed by Christian Heimes in bpo-16499 [https://bugs.python.org/issue?@action=redirect&bpo=16499].)

Tab-completion is now enabled by default in the interactive interpreter on systems that support readline. History is also enabled by default, and is written to (and read from) the file ~/.python-history. (Contributed by Antoine Pitrou and Éric Araujo in bpo-5845 [https://bugs.python.org/issue?@action=redirect&bpo=5845].)

Invoking the Python interpreter with --version now outputs the version to standard output instead of standard error (bpo-18338 [https://bugs.python.org/issue?@action=redirect&bpo=18338]). Similar changes were made to argparse (bpo-18920 [https://bugs.python.org/issue?@action=redirect&bpo=18920]) and other modules that have script-like invocation capabilities (bpo-18922 [https://bugs.python.org/issue?@action=redirect&bpo=18922]).

The CPython Windows installer now adds .py to the PATHEXT variable when extensions are registered, allowing users to run a python script at the windows command prompt by just typing its name without the .py extension. (Contributed by Paul Moore in bpo-18569 [https://bugs.python.org/issue?@action=redirect&bpo=18569].)

A new make target coverage-report [https://devguide.python.org/coverage/#measuring-coverage-of-c-code-with-gcov-and-lcov] will build python, run the test suite, and generate an HTML coverage report for the C codebase using gcov and lcov [http://ltp.sourceforge.net/coverage/lcov.php].

The -R option to the python regression test suite now also checks for memory allocation leaks, using sys.getallocatedblocks(). (Contributed by Antoine Pitrou in bpo-13390 [https://bugs.python.org/issue?@action=redirect&bpo=13390].)

python -m now works with namespace packages.

The stat module is now implemented in C, which means it gets the values for its constants from the C header files, instead of having the values hard-coded in the python module as was previously the case.

Loading multiple python modules from a single OS module (.so, .dll) now works correctly (previously it silently returned the first python module in the file). (Contributed by Václav Šmilauer in bpo-16421 [https://bugs.python.org/issue?@action=redirect&bpo=16421].)

A new opcode, LOAD_CLASSDEREF, has been added to fix a bug in the loading of free variables in class bodies that could be triggered by certain uses of __prepare__. (Contributed by Benjamin Peterson in bpo-17853 [https://bugs.python.org/issue?@action=redirect&bpo=17853].)

A number of MemoryError-related crashes were identified and fixed by Victor Stinner using his PEP 445 [https://www.python.org/dev/peps/pep-0445]-based pyfailmalloc tool (bpo-18408 [https://bugs.python.org/issue?@action=redirect&bpo=18408], bpo-18520 [https://bugs.python.org/issue?@action=redirect&bpo=18520]).

The pyvenv command now accepts a --copies option to use copies rather than symlinks even on systems where symlinks are the default. (Contributed by Vinay Sajip in bpo-18807 [https://bugs.python.org/issue?@action=redirect&bpo=18807].)

The pyvenv command also accepts a --without-pip option to suppress the otherwise-automatic bootstrapping of pip into the virtual environment. (Contributed by Nick Coghlan in bpo-19552 [https://bugs.python.org/issue?@action=redirect&bpo=19552] as part of the PEP 453 [https://www.python.org/dev/peps/pep-0453] implementation.)

The encoding name is now optional in the value set for the PYTHONIOENCODING environment variable. This makes it possible to set just the error handler, without changing the default encoding. (Contributed by Serhiy Storchaka in bpo-18818 [https://bugs.python.org/issue?@action=redirect&bpo=18818].)

The bz2, lzma, and gzip module open functions now support x (exclusive creation) mode. (Contributed by Tim Heaney and Vajrasky Kok in bpo-19201 [https://bugs.python.org/issue?@action=redirect&bpo=19201], bpo-19222 [https://bugs.python.org/issue?@action=redirect&bpo=19222], and bpo-19223 [https://bugs.python.org/issue?@action=redirect&bpo=19223].)

Significant Optimizations

The UTF-32 decoder is now 3x to 4x faster. (Contributed by Serhiy Storchaka in bpo-14625 [https://bugs.python.org/issue?@action=redirect&bpo=14625].)

The cost of hash collisions for sets is now reduced. Each hash table probe now checks a series of consecutive, adjacent key/hash pairs before continuing to make random probes through the hash table. This exploits cache locality to make collision resolution less expensive. The collision resolution scheme can be described as a hybrid of linear probing and open addressing. The number of additional linear probes defaults to nine. This can be changed at compile-time by defining LINEAR_PROBES to be any value. Set LINEAR_PROBES=0 to turn-off linear probing entirely. (Contributed by Raymond Hettinger in bpo-18771 [https://bugs.python.org/issue?@action=redirect&bpo=18771].)

The interpreter starts about 30% faster. A couple of measures lead to the speedup. The interpreter loads fewer modules on startup, e.g. the re, collections and locale modules and their dependencies are no longer imported by default. The marshal module has been improved to load compiled Python code faster. (Contributed by Antoine Pitrou, Christian Heimes and Victor Stinner in bpo-19219 [https://bugs.python.org/issue?@action=redirect&bpo=19219], bpo-19218 [https://bugs.python.org/issue?@action=redirect&bpo=19218], bpo-19209 [https://bugs.python.org/issue?@action=redirect&bpo=19209], bpo-19205 [https://bugs.python.org/issue?@action=redirect&bpo=19205] and bpo-9548 [https://bugs.python.org/issue?@action=redirect&bpo=9548].)

bz2.BZ2File is now as fast or faster than the Python2 version for most cases. lzma.LZMAFile has also been optimized. (Contributed by Serhiy Storchaka and Nadeem Vawda in bpo-16034 [https://bugs.python.org/issue?@action=redirect&bpo=16034].)

random.getrandbits() is 20%-40% faster for small integers (the most common use case). (Contributed by Serhiy Storchaka in bpo-16674 [https://bugs.python.org/issue?@action=redirect&bpo=16674].)

By taking advantage of the new storage format for strings, pickling of strings is now significantly faster. (Contributed by Victor Stinner and Antoine Pitrou in bpo-15596 [https://bugs.python.org/issue?@action=redirect&bpo=15596].)

A performance issue in io.FileIO.readall() has been solved. This particularly affects Windows, and significantly speeds up the case of piping significant amounts of data through subprocess. (Contributed by Richard Oudkerk in bpo-15758 [https://bugs.python.org/issue?@action=redirect&bpo=15758].)

html.escape() is now 10x faster. (Contributed by Matt Bryant in bpo-18020 [https://bugs.python.org/issue?@action=redirect&bpo=18020].)

On Windows, the native VirtualAlloc is now used instead of the CRT malloc in obmalloc. Artificial benchmarks show about a 3% memory savings.

os.urandom() now uses a lazily-opened persistent file descriptor so as to avoid using many file descriptors when run in parallel from multiple threads. (Contributed by Antoine Pitrou in bpo-18756 [https://bugs.python.org/issue?@action=redirect&bpo=18756].)

Deprecated

This section covers various APIs and other features that have been deprecated in Python 3.4, and will be removed in Python 3.5 or later. In most (but not all) cases, using the deprecated APIs will produce a DeprecationWarning when the interpreter is run with deprecation warnings enabled (for example, by using -Wd).

Deprecations in the Python API

As mentioned in PEP 451: A ModuleSpec Type for the Import System, a number of importlib methods and functions are deprecated: importlib.find_loader() is replaced by importlib.util.find_spec(); importlib.machinery.PathFinder.find_module() is replaced by importlib.machinery.PathFinder.find_spec(); importlib.abc.MetaPathFinder.find_module() is replaced by importlib.abc.MetaPathFinder.find_spec(); importlib.abc.PathEntryFinder.find_loader() and find_module() are replaced by importlib.abc.PathEntryFinder.find_spec(); all of the xxxLoader ABC load_module methods (importlib.abc.Loader.load_module(), importlib.abc.InspectLoader.load_module(), importlib.abc.FileLoader.load_module(), importlib.abc.SourceLoader.load_module()) should no longer be implemented, instead loaders should implement an exec_module method (importlib.abc.Loader.exec_module(), importlib.abc.InspectLoader.exec_module() importlib.abc.SourceLoader.exec_module()) and let the import system take care of the rest; and importlib.abc.Loader.module_repr(), importlib.util.module_for_loader(), importlib.util.set_loader(), and importlib.util.set_package() are no longer needed because their functions are now handled automatically by the import system.

The imp module is pending deprecation. To keep compatibility with Python 2/3 code bases, the module’s removal is currently not scheduled.

The formatter module is pending deprecation and is slated for removal in Python 3.6.

MD5 as the default digestmod for the hmac.new() function is deprecated. Python 3.6 will require an explicit digest name or constructor as digestmod argument.

The internal Netrc class in the ftplib module has been documented as deprecated in its docstring for quite some time. It now emits a DeprecationWarning and will be removed completely in Python 3.5.

The undocumented endtime argument to subprocess.Popen.wait() should not have been exposed and is hopefully not in use; it is deprecated and will mostly likely be removed in Python 3.5.

The strict argument of HTMLParser is deprecated.

The plistlib readPlist(), writePlist(), readPlistFromBytes(), and writePlistToBytes() functions are deprecated in favor of the corresponding new functions load(), dump(), loads(), and dumps(). Data() is deprecated in favor of just using the bytes constructor.

The sysconfig key SO is deprecated, it has been replaced by EXT_SUFFIX.

The U mode accepted by various open functions is deprecated. In Python3 it does not do anything useful, and should be replaced by appropriate uses of io.TextIOWrapper (if needed) and its newline argument.

The parser argument of xml.etree.ElementTree.iterparse() has been deprecated, as has the html argument of XMLParser(). To prepare for the removal of the latter, all arguments to XMLParser should be passed by keyword.

Deprecated Features

Running IDLE with the -n flag (no subprocess) is deprecated. However, the feature will not be removed until bpo-18823 [https://bugs.python.org/issue?@action=redirect&bpo=18823] is resolved.

The site module adding a “site-python” directory to sys.path, if it exists, is deprecated (bpo-19375 [https://bugs.python.org/issue?@action=redirect&bpo=19375]).

Removed

Operating Systems No Longer Supported

Support for the following operating systems has been removed from the source and build tools:

OS/2 (bpo-16135 [https://bugs.python.org/issue?@action=redirect&bpo=16135]).

Windows 2000 (changeset e52df05b496a).

Windows systems where COMSPEC points to command.com (bpo-14470 [https://bugs.python.org/issue?@action=redirect&bpo=14470]).

VMS (bpo-16136 [https://bugs.python.org/issue?@action=redirect&bpo=16136]).

API and Feature Removals

The following obsolete and previously deprecated APIs and features have been removed:

The unmaintained Misc/TextMate and Misc/vim directories have been removed (see the devguide [https://devguide.python.org] for suggestions on what to use instead).

The SO makefile macro is removed (it was replaced by the SHLIB_SUFFIX and EXT_SUFFIX macros) (bpo-16754 [https://bugs.python.org/issue?@action=redirect&bpo=16754]).

The PyThreadState.tick_counter field has been removed; its value has been meaningless since Python 3.2, when the “new GIL” was introduced (bpo-19199 [https://bugs.python.org/issue?@action=redirect&bpo=19199]).

PyLoader and PyPycLoader have been removed from importlib. (Contributed by Taras Lyapun in bpo-15641 [https://bugs.python.org/issue?@action=redirect&bpo=15641].)

The strict argument to HTTPConnection and HTTPSConnection has been removed. HTTP 0.9-style “Simple Responses” are no longer supported.

The deprecated urllib.request.Request getter and setter methods add_data, has_data, get_data, get_type, get_host, get_selector, set_proxy, get_origin_req_host, and is_unverifiable have been removed (use direct attribute access instead).

Support for loading the deprecated TYPE_INT64 has been removed from marshal. (Contributed by Dan Riti in bpo-15480 [https://bugs.python.org/issue?@action=redirect&bpo=15480].)

inspect.Signature: positional-only parameters are now required to have a valid name.

object.__format__() no longer accepts non-empty format strings, it now raises a TypeError instead. Using a non-empty string has been deprecated since Python 3.2. This change has been made to prevent a situation where previously working (but incorrect) code would start failing if an object gained a __format__ method, which means that your code may now raise a TypeError if you are using an 's' format code with objects that do not have a __format__ method that handles it. See bpo-7994 [https://bugs.python.org/issue?@action=redirect&bpo=7994] for background.

difflib.SequenceMatcher.isbjunk() and difflib.SequenceMatcher.isbpopular() were deprecated in 3.2, and have now been removed: use x in sm.bjunk and x in sm.bpopular, where sm is a SequenceMatcher object (bpo-13248 [https://bugs.python.org/issue?@action=redirect&bpo=13248]).

Code Cleanups

The unused and undocumented internal Scanner class has been removed from the pydoc module.

The private and effectively unused _gestalt module has been removed, along with the private platform functions _mac_ver_lookup, _mac_ver_gstalt, and _bcd2str, which would only have ever been called on badly broken OSX systems (see bpo-18393 [https://bugs.python.org/issue?@action=redirect&bpo=18393]).

The hardcoded copies of certain stat constants that were included in the tarfile module namespace have been removed.

Porting to Python 3.4

This section lists previously described changes and other bugfixes that may require changes to your code.

Changes in ‘python’ Command Behavior

In a posix shell, setting the PATH environment variable to an empty value is equivalent to not setting it at all. However, setting PYTHONPATH to an empty value was not equivalent to not setting it at all: setting PYTHONPATH to an empty value was equivalent to setting it to ., which leads to confusion when reasoning by analogy to how PATH works. The behavior now conforms to the posix convention for PATH.

The [X refs, Y blocks] output of a debug (--with-pydebug) build of the CPython interpreter is now off by default. It can be re-enabled using the -X showrefcount option. (Contributed by Ezio Melotti in bpo-17323 [https://bugs.python.org/issue?@action=redirect&bpo=17323].)

The python command and most stdlib scripts (as well as argparse) now output --version information to stdout instead of stderr (for issue list see Other Improvements above).

Changes in the Python API

The ABCs defined in importlib.abc now either raise the appropriate exception or return a default value instead of raising NotImplementedError blindly. This will only affect code calling super() and falling through all the way to the ABCs. For compatibility, catch both NotImplementedError or the appropriate exception as needed.

The module type now initializes the __package__ and __loader__ attributes to None by default. To determine if these attributes were set in a backwards-compatible fashion, use e.g. getattr(module, '__loader__', None) is not None. (bpo-17115 [https://bugs.python.org/issue?@action=redirect&bpo=17115].)

importlib.util.module_for_loader() now sets __loader__ and __package__ unconditionally to properly support reloading. If this is not desired then you will need to set these attributes manually. You can use importlib.util.module_to_load() for module management.

Import now resets relevant attributes (e.g. __name__, __loader__, __package__, __file__, __cached__) unconditionally when reloading. Note that this restores a pre-3.3 behavior in that it means a module is re-found when re-loaded (bpo-19413 [https://bugs.python.org/issue?@action=redirect&bpo=19413]).

Frozen packages no longer set __path__ to a list containing the package name, they now set it to an empty list. The previous behavior could cause the import system to do the wrong thing on submodule imports if there was also a directory with the same name as the frozen package. The correct way to determine if a module is a package or not is to use hasattr(module, '__path__') (bpo-18065 [https://bugs.python.org/issue?@action=redirect&bpo=18065]).

Frozen modules no longer define a __file__ attribute. It’s semantically incorrect for frozen modules to set the attribute as they are not loaded from any explicit location. If you must know that a module comes from frozen code then you can see if the module’s __spec__.location is set to 'frozen', check if the loader is a subclass of importlib.machinery.FrozenImporter, or if Python 2 compatibility is necessary you can use imp.is_frozen().

py_compile.compile() now raises FileExistsError if the file path it would write to is a symlink or a non-regular file. This is to act as a warning that import will overwrite those files with a regular file regardless of what type of file path they were originally.

importlib.abc.SourceLoader.get_source() no longer raises ImportError when the source code being loaded triggers a SyntaxError or UnicodeDecodeError. As ImportError is meant to be raised only when source code cannot be found but it should, it was felt to be over-reaching/overloading of that meaning when the source code is found but improperly structured. If you were catching ImportError before and wish to continue to ignore syntax or decoding issues, catch all three exceptions now.

functools.update_wrapper() and functools.wraps() now correctly set the __wrapped__ attribute to the function being wrapped, even if that function also had its __wrapped__ attribute set. This means __wrapped__ attributes now correctly link a stack of decorated functions rather than every __wrapped__ attribute in the chain referring to the innermost function. Introspection libraries that assumed the previous behaviour was intentional can use inspect.unwrap() to access the first function in the chain that has no __wrapped__ attribute.

inspect.getfullargspec() has been reimplemented on top of inspect.signature() and hence handles a much wider variety of callable objects than it did in the past. It is expected that additional builtin and extension module callables will gain signature metadata over the course of the Python 3.4 series. Code that assumes that inspect.getfullargspec() will fail on non-Python callables may need to be adjusted accordingly.

importlib.machinery.PathFinder now passes on the current working directory to objects in sys.path_hooks for the empty string. This results in sys.path_importer_cache never containing '', thus iterating through sys.path_importer_cache based on sys.path will not find all keys. A module’s __file__ when imported in the current working directory will also now have an absolute path, including when using -m with the interpreter (except for __main__.__file__ when a script has been executed directly using a relative path) (Contributed by Brett Cannon in bpo-18416 [https://bugs.python.org/issue?@action=redirect&bpo=18416]). is specified on the command-line) (bpo-18416 [https://bugs.python.org/issue?@action=redirect&bpo=18416]).

The removal of the strict argument to HTTPConnection and HTTPSConnection changes the meaning of the remaining arguments if you are specifying them positionally rather than by keyword. If you’ve been paying attention to deprecation warnings your code should already be specifying any additional arguments via keywords.

Strings between from __future__ import ... statements now always raise a SyntaxError. Previously if there was no leading docstring, an interstitial string would sometimes be ignored. This brings CPython into compliance with the language spec; Jython and PyPy already were. (bpo-17434 [https://bugs.python.org/issue?@action=redirect&bpo=17434]).

ssl.SSLSocket.getpeercert() and ssl.SSLSocket.do_handshake() now raise an OSError with ENOTCONN when the SSLSocket is not connected, instead of the previous behavior of raising an AttributeError. In addition, getpeercert() will raise a ValueError if the handshake has not yet been done.

base64.b32decode() now raises a binascii.Error when the input string contains non-b32-alphabet characters, instead of a TypeError. This particular TypeError was missed when the other TypeErrors were converted. (Contributed by Serhiy Storchaka in bpo-18011 [https://bugs.python.org/issue?@action=redirect&bpo=18011].) Note: this change was also inadvertently applied in Python 3.3.3.

The file attribute is now automatically closed when the creating cgi.FieldStorage instance is garbage collected. If you were pulling the file object out separately from the cgi.FieldStorage instance and not keeping the instance alive, then you should either store the entire cgi.FieldStorage instance or read the contents of the file before the cgi.FieldStorage instance is garbage collected.

Calling read or write on a closed SSL socket now raises an informative ValueError rather than the previous more mysterious AttributeError (bpo-9177 [https://bugs.python.org/issue?@action=redirect&bpo=9177]).

slice.indices() no longer produces an OverflowError for huge values. As a consequence of this fix, slice.indices() now raises a ValueError if given a negative length; previously it returned nonsense values (bpo-14794 [https://bugs.python.org/issue?@action=redirect&bpo=14794]).

The complex constructor, unlike the cmath functions, was incorrectly accepting float values if an object’s __complex__ special method returned one. This now raises a TypeError. (bpo-16290 [https://bugs.python.org/issue?@action=redirect&bpo=16290].)

The int constructor in 3.2 and 3.3 erroneously accepts float values for the base parameter. It is unlikely anyone was doing this, but if so, it will now raise a TypeError (bpo-16772 [https://bugs.python.org/issue?@action=redirect&bpo=16772]).

Defaults for keyword-only arguments are now evaluated after defaults for regular keyword arguments, instead of before. Hopefully no one wrote any code that depends on the previous buggy behavior (bpo-16967 [https://bugs.python.org/issue?@action=redirect&bpo=16967]).

Stale thread states are now cleared after fork(). This may cause some system resources to be released that previously were incorrectly kept perpetually alive (for example, database connections kept in thread-local storage). (bpo-17094 [https://bugs.python.org/issue?@action=redirect&bpo=17094].)

Parameter names in __annotations__ dicts are now mangled properly, similarly to __kwdefaults__. (Contributed by Yury Selivanov in bpo-20625 [https://bugs.python.org/issue?@action=redirect&bpo=20625].)

hashlib.hash.name now always returns the identifier in lower case. Previously some builtin hashes had uppercase names, but now that it is a formal public interface the naming has been made consistent (bpo-18532 [https://bugs.python.org/issue?@action=redirect&bpo=18532]).

Because unittest.TestSuite now drops references to tests after they are run, test harnesses that re-use a TestSuite to re-run a set of tests may fail. Test suites should not be re-used in this fashion since it means state is retained between test runs, breaking the test isolation that unittest is designed to provide. However, if the lack of isolation is considered acceptable, the old behavior can be restored by creating a TestSuite subclass that defines a _removeTestAtIndex method that does nothing (see TestSuite.__iter__()) (bpo-11798 [https://bugs.python.org/issue?@action=redirect&bpo=11798]).

unittest now uses argparse for command line parsing. There are certain invalid command forms that used to work that are no longer allowed; in theory this should not cause backward compatibility issues since the disallowed command forms didn’t make any sense and are unlikely to be in use.

The re.split(), re.findall(), and re.sub() functions, and the group() and groups() methods of match objects now always return a bytes object when the string to be matched is a bytes-like object. Previously the return type matched the input type, so if your code was depending on the return value being, say, a bytearray, you will need to change your code.

audioop functions now raise an error immediately if passed string input, instead of failing randomly later on (bpo-16685 [https://bugs.python.org/issue?@action=redirect&bpo=16685]).

The new convert_charrefs argument to HTMLParser currently defaults to False for backward compatibility, but will eventually be changed to default to True. It is recommended that you add this keyword, with the appropriate value, to any HTMLParser calls in your code (bpo-13633 [https://bugs.python.org/issue?@action=redirect&bpo=13633]).

Since the digestmod argument to the hmac.new() function will in the future have no default, all calls to hmac.new() should be changed to explicitly specify a digestmod (bpo-17276 [https://bugs.python.org/issue?@action=redirect&bpo=17276]).

Calling sysconfig.get_config_var() with the SO key, or looking SO up in the results of a call to sysconfig.get_config_vars() is deprecated. This key should be replaced by EXT_SUFFIX or SHLIB_SUFFIX, depending on the context (bpo-19555 [https://bugs.python.org/issue?@action=redirect&bpo=19555]).

Any calls to open functions that specify U should be modified. U is ineffective in Python3 and will eventually raise an error if used. Depending on the function, the equivalent of its old Python2 behavior can be achieved using either a newline argument, or if necessary by wrapping the stream in TextIOWrapper to use its newline argument (bpo-15204 [https://bugs.python.org/issue?@action=redirect&bpo=15204]).

If you use pyvenv in a script and desire that pip not be installed, you must add --without-pip to your command invocation.

The default behavior of json.dump() and json.dumps() when an indent is specified has changed: it no longer produces trailing spaces after the item separating commas at the ends of lines. This will matter only if you have tests that are doing white-space-sensitive comparisons of such output (bpo-16333 [https://bugs.python.org/issue?@action=redirect&bpo=16333]).

doctest now looks for doctests in extension module __doc__ strings, so if your doctest test discovery includes extension modules that have things that look like doctests in them you may see test failures you’ve never seen before when running your tests (bpo-3158 [https://bugs.python.org/issue?@action=redirect&bpo=3158]).

The collections.abc module has been slightly refactored as part of the Python startup improvements. As a consequence of this, it is no longer the case that importing collections automatically imports collections.abc. If your program depended on the (undocumented) implicit import, you will need to add an explicit import collections.abc (bpo-20784 [https://bugs.python.org/issue?@action=redirect&bpo=20784]).

Changes in the C API

PyEval_EvalFrameEx(), PyObject_Repr(), and PyObject_Str(), along with some other internal C APIs, now include a debugging assertion that ensures they are not used in situations where they may silently discard a currently active exception. In cases where discarding the active exception is expected and desired (for example, because it has already been saved locally with PyErr_Fetch() or is being deliberately replaced with a different exception), an explicit PyErr_Clear() call will be needed to avoid triggering the assertion when invoking these operations (directly or indirectly) and running against a version of Python that is compiled with assertions enabled.

PyErr_SetImportError() now sets TypeError when its msg argument is not set. Previously only NULL was returned with no exception set.

The result of the PyOS_ReadlineFunctionPointer callback must now be a string allocated by PyMem_RawMalloc() or PyMem_RawRealloc(), or NULL if an error occurred, instead of a string allocated by PyMem_Malloc() or PyMem_Realloc() (bpo-16742 [https://bugs.python.org/issue?@action=redirect&bpo=16742])

PyThread_set_key_value() now always set the value. In Python 3.3, the function did nothing if the key already exists (if the current value is a non-NULL pointer).

The f_tstate (thread state) field of the PyFrameObject structure has been removed to fix a bug: see bpo-14432 [https://bugs.python.org/issue?@action=redirect&bpo=14432] for the rationale.

Changed in 3.4.3

PEP 476: Enabling certificate verification by default for stdlib http clients

http.client and modules which use it, such as urllib.request and xmlrpc.client, will now verify that the server presents a certificate which is signed by a CA in the platform trust store and whose hostname matches the hostname being requested by default, significantly improving security for many applications.

For applications which require the old previous behavior, they can pass an alternate context:

import urllib.request
import ssl

# This disables all verification
context = ssl._create_unverified_context()

# This allows using a specific certificate for the host, which doesn't need
# to be in the trust store
context = ssl.create_default_context(cafile="/path/to/file.crt")

urllib.request.urlopen("https://invalid-cert", context=context)

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬의 새로운 기능 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬의 새로운 기능 »

|

What’s New In Python 3.3

This article explains the new features in Python 3.3, compared to 3.2. Python 3.3 was released on September 29, 2012. For full details, see the changelog [https://docs.python.org/3.3/whatsnew/changelog.html].

더 보기

PEP 398 [https://www.python.org/dev/peps/pep-0398] - Python 3.3 Release Schedule

Summary – Release highlights

New syntax features:

New yield from expression for generator delegation.

The u'unicode' syntax is accepted again for str objects.

New library modules:

faulthandler (helps debugging low-level crashes)

ipaddress (high-level objects representing IP addresses and masks)

lzma (compress data using the XZ / LZMA algorithm)

unittest.mock (replace parts of your system under test with mock objects)

venv (Python virtual environments, as in the popular virtualenv package)

New built-in features:

Reworked I/O exception hierarchy.

Implementation improvements:

Rewritten import machinery based on importlib.

More compact unicode strings.

More compact attribute dictionaries.

Significantly Improved Library Modules:

C Accelerator for the decimal module.

Better unicode handling in the email module (provisional).

Security improvements:

Hash randomization is switched on by default.

Please read on for a comprehensive list of user-facing changes.

PEP 405: Virtual Environments

Virtual environments help create separate Python setups while sharing a system-wide base install, for ease of maintenance. Virtual environments have their own set of private site packages (i.e. locally-installed libraries), and are optionally segregated from the system-wide site packages. Their concept and implementation are inspired by the popular virtualenv third-party package, but benefit from tighter integration with the interpreter core.

This PEP adds the venv module for programmatic access, and the pyvenv script for command-line access and administration. The Python interpreter checks for a pyvenv.cfg, file whose existence signals the base of a virtual environment’s directory tree.

더 보기

PEP 405 [https://www.python.org/dev/peps/pep-0405] - Python Virtual Environments

PEP written by Carl Meyer; implementation by Carl Meyer and Vinay Sajip

PEP 420: Implicit Namespace Packages

Native support for package directories that don’t require __init__.py marker files and can automatically span multiple path segments (inspired by various third party approaches to namespace packages, as described in PEP 420 [https://www.python.org/dev/peps/pep-0420])

더 보기

PEP 420 [https://www.python.org/dev/peps/pep-0420] - Implicit Namespace Packages

PEP written by Eric V. Smith; implementation by Eric V. Smith and Barry Warsaw

PEP 3118: New memoryview implementation and buffer protocol documentation

The implementation of PEP 3118 [https://www.python.org/dev/peps/pep-3118] has been significantly improved.

The new memoryview implementation comprehensively fixes all ownership and lifetime issues of dynamically allocated fields in the Py_buffer struct that led to multiple crash reports. Additionally, several functions that crashed or returned incorrect results for non-contiguous or multi-dimensional input have been fixed.

The memoryview object now has a PEP-3118 compliant getbufferproc() that checks the consumer’s request type. Many new features have been added, most of them work in full generality for non-contiguous arrays and arrays with suboffsets.

The documentation has been updated, clearly spelling out responsibilities for both exporters and consumers. Buffer request flags are grouped into basic and compound flags. The memory layout of non-contiguous and multi-dimensional NumPy-style arrays is explained.

Features

All native single character format specifiers in struct module syntax (optionally prefixed with ‘@’) are now supported.

With some restrictions, the cast() method allows changing of format and shape of C-contiguous arrays.

Multi-dimensional list representations are supported for any array type.

Multi-dimensional comparisons are supported for any array type.

One-dimensional memoryviews of hashable (read-only) types with formats B, b or c are now hashable. (Contributed by Antoine Pitrou in bpo-13411 [https://bugs.python.org/issue?@action=redirect&bpo=13411].)

Arbitrary slicing of any 1-D arrays type is supported. For example, it is now possible to reverse a memoryview in O(1) by using a negative step.

API changes

The maximum number of dimensions is officially limited to 64.

The representation of empty shape, strides and suboffsets is now an empty tuple instead of None.

Accessing a memoryview element with format ‘B’ (unsigned bytes) now returns an integer (in accordance with the struct module syntax). For returning a bytes object the view must be cast to ‘c’ first.

memoryview comparisons now use the logical structure of the operands and compare all array elements by value. All format strings in struct module syntax are supported. Views with unrecognised format strings are still permitted, but will always compare as unequal, regardless of view contents.

For further changes see Build and C API Changes and Porting C code.

(Contributed by Stefan Krah in bpo-10181 [https://bugs.python.org/issue?@action=redirect&bpo=10181].)

더 보기

PEP 3118 [https://www.python.org/dev/peps/pep-3118] - Revising the Buffer Protocol

PEP 393: Flexible String Representation

The Unicode string type is changed to support multiple internal representations, depending on the character with the largest Unicode ordinal (1, 2, or 4 bytes) in the represented string. This allows a space-efficient representation in common cases, but gives access to full UCS-4 on all systems. For compatibility with existing APIs, several representations may exist in parallel; over time, this compatibility should be phased out.

On the Python side, there should be no downside to this change.

On the C API side, PEP 393 is fully backward compatible. The legacy API should remain available at least five years. Applications using the legacy API will not fully benefit of the memory reduction, or - worse - may use a bit more memory, because Python may have to maintain two versions of each string (in the legacy format and in the new efficient storage).

Functionality

Changes introduced by PEP 393 [https://www.python.org/dev/peps/pep-0393] are the following:

Python now always supports the full range of Unicode code points, including non-BMP ones (i.e. from U+0000 to U+10FFFF). The distinction between narrow and wide builds no longer exists and Python now behaves like a wide build, even under Windows.

With the death of narrow builds, the problems specific to narrow builds have also been fixed, for example:

len() now always returns 1 for non-BMP characters, so len('\U0010FFFF') == 1;

surrogate pairs are not recombined in string literals, so '\uDBFF\uDFFF' != '\U0010FFFF';

indexing or slicing non-BMP characters returns the expected value, so '\U0010FFFF'[0] now returns '\U0010FFFF' and not '\uDBFF';

all other functions in the standard library now correctly handle non-BMP code points.

The value of sys.maxunicode is now always 1114111 (0x10FFFF in hexadecimal). The PyUnicode_GetMax() function still returns either 0xFFFF or 0x10FFFF for backward compatibility, and it should not be used with the new Unicode API (see bpo-13054 [https://bugs.python.org/issue?@action=redirect&bpo=13054]).

The ./configure flag --with-wide-unicode has been removed.

Performance and resource usage

The storage of Unicode strings now depends on the highest code point in the string:

pure ASCII and Latin1 strings (U+0000-U+00FF) use 1 byte per code point;

BMP strings (U+0000-U+FFFF) use 2 bytes per code point;

non-BMP strings (U+10000-U+10FFFF) use 4 bytes per code point.

The net effect is that for most applications, memory usage of string storage should decrease significantly - especially compared to former wide unicode builds - as, in many cases, strings will be pure ASCII even in international contexts (because many strings store non-human language data, such as XML fragments, HTTP headers, JSON-encoded data, etc.). We also hope that it will, for the same reasons, increase CPU cache efficiency on non-trivial applications. The memory usage of Python 3.3 is two to three times smaller than Python 3.2, and a little bit better than Python 2.7, on a Django benchmark (see the PEP for details).

더 보기

PEP 393 [https://www.python.org/dev/peps/pep-0393] - Flexible String Representation

PEP written by Martin von Löwis; implementation by Torsten Becker and Martin von Löwis.

PEP 397: Python Launcher for Windows

The Python 3.3 Windows installer now includes a py launcher application that can be used to launch Python applications in a version independent fashion.

This launcher is invoked implicitly when double-clicking *.py files. If only a single Python version is installed on the system, that version will be used to run the file. If multiple versions are installed, the most recent version is used by default, but this can be overridden by including a Unix-style “shebang line” in the Python script.

The launcher can also be used explicitly from the command line as the py application. Running py follows the same version selection rules as implicitly launching scripts, but a more specific version can be selected by passing appropriate arguments (such as -3 to request Python 3 when Python 2 is also installed, or -2.6 to specifically request an earlier Python version when a more recent version is installed).

In addition to the launcher, the Windows installer now includes an option to add the newly installed Python to the system PATH. (Contributed by Brian Curtin in bpo-3561 [https://bugs.python.org/issue?@action=redirect&bpo=3561].)

더 보기

PEP 397 [https://www.python.org/dev/peps/pep-0397] - Python Launcher for Windows

PEP written by Mark Hammond and Martin v. Löwis; implementation by Vinay Sajip.

Launcher documentation: Python Launcher for Windows

Installer PATH modification: Finding the Python executable

PEP 3151: Reworking the OS and IO exception hierarchy

The hierarchy of exceptions raised by operating system errors is now both simplified and finer-grained.

You don’t have to worry anymore about choosing the appropriate exception type between OSError, IOError, EnvironmentError, WindowsError, mmap.error, socket.error or select.error. All these exception types are now only one: OSError. The other names are kept as aliases for compatibility reasons.

Also, it is now easier to catch a specific error condition. Instead of inspecting the errno attribute (or args[0]) for a particular constant from the errno module, you can catch the adequate OSError subclass. The available subclasses are the following:

BlockingIOError

ChildProcessError

ConnectionError

FileExistsError

FileNotFoundError

InterruptedError

IsADirectoryError

NotADirectoryError

PermissionError

ProcessLookupError

TimeoutError

And the ConnectionError itself has finer-grained subclasses:

BrokenPipeError

ConnectionAbortedError

ConnectionRefusedError

ConnectionResetError

Thanks to the new exceptions, common usages of the errno can now be avoided. For example, the following code written for Python 3.2:

from errno import ENOENT, EACCES, EPERM

try:
    with open("document.txt") as f:
        content = f.read()
except IOError as err:
    if err.errno == ENOENT:
        print("document.txt file is missing")
    elif err.errno in (EACCES, EPERM):
        print("You are not allowed to read document.txt")
    else:
        raise

can now be written without the errno import and without manual inspection of exception attributes:

try:
    with open("document.txt") as f:
        content = f.read()
except FileNotFoundError:
    print("document.txt file is missing")
except PermissionError:
    print("You are not allowed to read document.txt")

더 보기

PEP 3151 [https://www.python.org/dev/peps/pep-3151] - Reworking the OS and IO Exception Hierarchy

PEP written and implemented by Antoine Pitrou

PEP 380: Syntax for Delegating to a Subgenerator

PEP 380 adds the yield from expression, allowing a generator to delegate part of its operations to another generator. This allows a section of code containing yield to be factored out and placed in another generator. Additionally, the subgenerator is allowed to return with a value, and the value is made available to the delegating generator.

While designed primarily for use in delegating to a subgenerator, the yield from expression actually allows delegation to arbitrary subiterators.

For simple iterators, yield from iterable is essentially just a shortened form of for item in iterable: yield item:

>>> def g(x):
...     yield from range(x, 0, -1)
...     yield from range(x)
...
>>> list(g(5))
[5, 4, 3, 2, 1, 0, 1, 2, 3, 4]

However, unlike an ordinary loop, yield from allows subgenerators to receive sent and thrown values directly from the calling scope, and return a final value to the outer generator:

>>> def accumulate():
...     tally = 0
...     while 1:
...         next = yield
...         if next is None:
...             return tally
...         tally += next
...
>>> def gather_tallies(tallies):
...     while 1:
...         tally = yield from accumulate()
...         tallies.append(tally)
...
>>> tallies = []
>>> acc = gather_tallies(tallies)
>>> next(acc)  # Ensure the accumulator is ready to accept values
>>> for i in range(4):
...     acc.send(i)
...
>>> acc.send(None)  # Finish the first tally
>>> for i in range(5):
...     acc.send(i)
...
>>> acc.send(None)  # Finish the second tally
>>> tallies
[6, 10]

The main principle driving this change is to allow even generators that are designed to be used with the send and throw methods to be split into multiple subgenerators as easily as a single large function can be split into multiple subfunctions.

더 보기

PEP 380 [https://www.python.org/dev/peps/pep-0380] - Syntax for Delegating to a Subgenerator

PEP written by Greg Ewing; implementation by Greg Ewing, integrated into 3.3 by Renaud Blanch, Ryan Kelly and Nick Coghlan; documentation by Zbigniew Jędrzejewski-Szmek and Nick Coghlan

PEP 409: Suppressing exception context

PEP 409 introduces new syntax that allows the display of the chained exception context to be disabled. This allows cleaner error messages in applications that convert between exception types:

>>> class D:
...     def __init__(self, extra):
...         self._extra_attributes = extra
...     def __getattr__(self, attr):
...         try:
...             return self._extra_attributes[attr]
...         except KeyError:
...             raise AttributeError(attr) from None
...
>>> D({}).x
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 8, in __getattr__
AttributeError: x

Without the from None suffix to suppress the cause, the original exception would be displayed by default:

>>> class C:
...     def __init__(self, extra):
...         self._extra_attributes = extra
...     def __getattr__(self, attr):
...         try:
...             return self._extra_attributes[attr]
...         except KeyError:
...             raise AttributeError(attr)
...
>>> C({}).x
Traceback (most recent call last):
  File "<stdin>", line 6, in __getattr__
KeyError: 'x'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 8, in __getattr__
AttributeError: x

No debugging capability is lost, as the original exception context remains available if needed (for example, if an intervening library has incorrectly suppressed valuable underlying details):

>>> try:
...     D({}).x
... except AttributeError as exc:
...     print(repr(exc.__context__))
...
KeyError('x',)

더 보기

PEP 409 [https://www.python.org/dev/peps/pep-0409] - Suppressing exception context

PEP written by Ethan Furman; implemented by Ethan Furman and Nick Coghlan.

PEP 414: Explicit Unicode literals

To ease the transition from Python 2 for Unicode aware Python applications that make heavy use of Unicode literals, Python 3.3 once again supports the “u” prefix for string literals. This prefix has no semantic significance in Python 3, it is provided solely to reduce the number of purely mechanical changes in migrating to Python 3, making it easier for developers to focus on the more significant semantic changes (such as the stricter default separation of binary and text data).

더 보기

PEP 414 [https://www.python.org/dev/peps/pep-0414] - Explicit Unicode literals

PEP written by Armin Ronacher.

PEP 3155: Qualified name for classes and functions

Functions and class objects have a new __qualname__ attribute representing the “path” from the module top-level to their definition. For global functions and classes, this is the same as __name__. For other functions and classes, it provides better information about where they were actually defined, and how they might be accessible from the global scope.

Example with (non-bound) methods:

>>> class C:
...     def meth(self):
...         pass
>>> C.meth.__name__
'meth'
>>> C.meth.__qualname__
'C.meth'

Example with nested classes:

>>> class C:
...     class D:
...         def meth(self):
...             pass
...
>>> C.D.__name__
'D'
>>> C.D.__qualname__
'C.D'
>>> C.D.meth.__name__
'meth'
>>> C.D.meth.__qualname__
'C.D.meth'

Example with nested functions:

>>> def outer():
...     def inner():
...         pass
...     return inner
...
>>> outer().__name__
'inner'
>>> outer().__qualname__
'outer.<locals>.inner'

The string representation of those objects is also changed to include the new, more precise information:

>>> str(C.D)
"<class '__main__.C.D'>"
>>> str(C.D.meth)
'<function C.D.meth at 0x7f46b9fe31e0>'

더 보기

PEP 3155 [https://www.python.org/dev/peps/pep-3155] - Qualified name for classes and functions

PEP written and implemented by Antoine Pitrou.

PEP 412: Key-Sharing Dictionary

Dictionaries used for the storage of objects’ attributes are now able to share part of their internal storage between each other (namely, the part which stores the keys and their respective hashes). This reduces the memory consumption of programs creating many instances of non-builtin types.

더 보기

PEP 412 [https://www.python.org/dev/peps/pep-0412] - Key-Sharing Dictionary

PEP written and implemented by Mark Shannon.

PEP 362: Function Signature Object

A new function inspect.signature() makes introspection of python callables easy and straightforward. A broad range of callables is supported: python functions, decorated or not, classes, and functools.partial() objects. New classes inspect.Signature, inspect.Parameter and inspect.BoundArguments hold information about the call signatures, such as, annotations, default values, parameters kinds, and bound arguments, which considerably simplifies writing decorators and any code that validates or amends calling signatures or arguments.

더 보기

PEP 362 [https://www.python.org/dev/peps/pep-0362]: - Function Signature Object

PEP written by Brett Cannon, Yury Selivanov, Larry Hastings, Jiwon Seo; implemented by Yury Selivanov.

PEP 421: Adding sys.implementation

A new attribute on the sys module exposes details specific to the implementation of the currently running interpreter. The initial set of attributes on sys.implementation are name, version, hexversion, and cache_tag.

The intention of sys.implementation is to consolidate into one namespace the implementation-specific data used by the standard library. This allows different Python implementations to share a single standard library code base much more easily. In its initial state, sys.implementation holds only a small portion of the implementation-specific data. Over time that ratio will shift in order to make the standard library more portable.

One example of improved standard library portability is cache_tag. As of Python 3.3, sys.implementation.cache_tag is used by importlib to support PEP 3147 [https://www.python.org/dev/peps/pep-3147] compliance. Any Python implementation that uses importlib for its built-in import system may use cache_tag to control the caching behavior for modules.

SimpleNamespace

The implementation of sys.implementation also introduces a new type to Python: types.SimpleNamespace. In contrast to a mapping-based namespace, like dict, SimpleNamespace is attribute-based, like object. However, unlike object, SimpleNamespace instances are writable. This means that you can add, remove, and modify the namespace through normal attribute access.

더 보기

PEP 421 [https://www.python.org/dev/peps/pep-0421] - Adding sys.implementation

PEP written and implemented by Eric Snow.

Using importlib as the Implementation of Import

bpo-2377 [https://bugs.python.org/issue?@action=redirect&bpo=2377] - Replace __import__ w/ importlib.__import__ bpo-13959 [https://bugs.python.org/issue?@action=redirect&bpo=13959] - Re-implement parts of imp in pure Python bpo-14605 [https://bugs.python.org/issue?@action=redirect&bpo=14605] - Make import machinery explicit bpo-14646 [https://bugs.python.org/issue?@action=redirect&bpo=14646] - Require loaders set __loader__ and __package__

The __import__() function is now powered by importlib.__import__(). This work leads to the completion of “phase 2” of PEP 302 [https://www.python.org/dev/peps/pep-0302]. There are multiple benefits to this change. First, it has allowed for more of the machinery powering import to be exposed instead of being implicit and hidden within the C code. It also provides a single implementation for all Python VMs supporting Python 3.3 to use, helping to end any VM-specific deviations in import semantics. And finally it eases the maintenance of import, allowing for future growth to occur.

For the common user, there should be no visible change in semantics. For those whose code currently manipulates import or calls import programmatically, the code changes that might possibly be required are covered in the Porting Python code section of this document.

New APIs

One of the large benefits of this work is the exposure of what goes into making the import statement work. That means the various importers that were once implicit are now fully exposed as part of the importlib package.

The abstract base classes defined in importlib.abc have been expanded to properly delineate between meta path finders and path entry finders by introducing importlib.abc.MetaPathFinder and importlib.abc.PathEntryFinder, respectively. The old ABC of importlib.abc.Finder is now only provided for backwards-compatibility and does not enforce any method requirements.

In terms of finders, importlib.machinery.FileFinder exposes the mechanism used to search for source and bytecode files of a module. Previously this class was an implicit member of sys.path_hooks.

For loaders, the new abstract base class importlib.abc.FileLoader helps write a loader that uses the file system as the storage mechanism for a module’s code. The loader for source files (importlib.machinery.SourceFileLoader), sourceless bytecode files (importlib.machinery.SourcelessFileLoader), and extension modules (importlib.machinery.ExtensionFileLoader) are now available for direct use.

ImportError now has name and path attributes which are set when there is relevant data to provide. The message for failed imports will also provide the full name of the module now instead of just the tail end of the module’s name.

The importlib.invalidate_caches() function will now call the method with the same name on all finders cached in sys.path_importer_cache to help clean up any stored state as necessary.

Visible Changes

For potential required changes to code, see the Porting Python code section.

Beyond the expanse of what importlib now exposes, there are other visible changes to import. The biggest is that sys.meta_path and sys.path_hooks now store all of the meta path finders and path entry hooks used by import. Previously the finders were implicit and hidden within the C code of import instead of being directly exposed. This means that one can now easily remove or change the order of the various finders to fit one’s needs.

Another change is that all modules have a __loader__ attribute, storing the loader used to create the module. PEP 302 [https://www.python.org/dev/peps/pep-0302] has been updated to make this attribute mandatory for loaders to implement, so in the future once 3rd-party loaders have been updated people will be able to rely on the existence of the attribute. Until such time, though, import is setting the module post-load.

Loaders are also now expected to set the __package__ attribute from PEP 366 [https://www.python.org/dev/peps/pep-0366]. Once again, import itself is already setting this on all loaders from importlib and import itself is setting the attribute post-load.

None is now inserted into sys.path_importer_cache when no finder can be found on sys.path_hooks. Since imp.NullImporter is not directly exposed on sys.path_hooks it could no longer be relied upon to always be available to use as a value representing no finder found.

All other changes relate to semantic changes which should be taken into consideration when updating code for Python 3.3, and thus should be read about in the Porting Python code section of this document.

(Implementation by Brett Cannon)

Other Language Changes

Some smaller changes made to the core Python language are:

Added support for Unicode name aliases and named sequences. Both unicodedata.lookup() and '\N{...}' now resolve name aliases, and unicodedata.lookup() resolves named sequences too.

(Contributed by Ezio Melotti in bpo-12753 [https://bugs.python.org/issue?@action=redirect&bpo=12753].)

Unicode database updated to UCD version 6.1.0

Equality comparisons on range() objects now return a result reflecting the equality of the underlying sequences generated by those range objects. (bpo-13201 [https://bugs.python.org/issue?@action=redirect&bpo=13201])

The count(), find(), rfind(), index() and rindex() methods of bytes and bytearray objects now accept an integer between 0 and 255 as their first argument.

(Contributed by Petri Lehtinen in bpo-12170 [https://bugs.python.org/issue?@action=redirect&bpo=12170].)

The rjust(), ljust(), and center() methods of bytes and bytearray now accept a bytearray for the fill argument. (Contributed by Petri Lehtinen in bpo-12380 [https://bugs.python.org/issue?@action=redirect&bpo=12380].)

New methods have been added to list and bytearray: copy() and clear() (bpo-10516 [https://bugs.python.org/issue?@action=redirect&bpo=10516]). Consequently, MutableSequence now also defines a clear() method (bpo-11388 [https://bugs.python.org/issue?@action=redirect&bpo=11388]).

Raw bytes literals can now be written rb"..." as well as br"...".

(Contributed by Antoine Pitrou in bpo-13748 [https://bugs.python.org/issue?@action=redirect&bpo=13748].)

dict.setdefault() now does only one lookup for the given key, making it atomic when used with built-in types.

(Contributed by Filip Gruszczyński in bpo-13521 [https://bugs.python.org/issue?@action=redirect&bpo=13521].)

The error messages produced when a function call does not match the function signature have been significantly improved.

(Contributed by Benjamin Peterson.)

A Finer-Grained Import Lock

Previous versions of CPython have always relied on a global import lock. This led to unexpected annoyances, such as deadlocks when importing a module would trigger code execution in a different thread as a side-effect. Clumsy workarounds were sometimes employed, such as the PyImport_ImportModuleNoBlock() C API function.

In Python 3.3, importing a module takes a per-module lock. This correctly serializes importation of a given module from multiple threads (preventing the exposure of incompletely initialized modules), while eliminating the aforementioned annoyances.

(Contributed by Antoine Pitrou in bpo-9260 [https://bugs.python.org/issue?@action=redirect&bpo=9260].)

Builtin functions and types

open() gets a new opener parameter: the underlying file descriptor for the file object is then obtained by calling opener with (file, flags). It can be used to use custom flags like os.O_CLOEXEC for example. The 'x' mode was added: open for exclusive creation, failing if the file already exists.

print(): added the flush keyword argument. If the flush keyword argument is true, the stream is forcibly flushed.

hash(): hash randomization is enabled by default, see object.__hash__() and PYTHONHASHSEED.

The str type gets a new casefold() method: return a casefolded copy of the string, casefolded strings may be used for caseless matching. For example, 'ß'.casefold() returns 'ss'.

The sequence documentation has been substantially rewritten to better explain the binary/text sequence distinction and to provide specific documentation sections for the individual builtin sequence types (bpo-4966 [https://bugs.python.org/issue?@action=redirect&bpo=4966]).

New Modules

faulthandler

This new debug module faulthandler contains functions to dump Python tracebacks explicitly, on a fault (a crash like a segmentation fault), after a timeout, or on a user signal. Call faulthandler.enable() to install fault handlers for the SIGSEGV, SIGFPE, SIGABRT, SIGBUS, and SIGILL signals. You can also enable them at startup by setting the PYTHONFAULTHANDLER environment variable or by using -X faulthandler command line option.

Example of a segmentation fault on Linux:

$ python -q -X faulthandler
>>> import ctypes
>>> ctypes.string_at(0)
Fatal Python error: Segmentation fault

Current thread 0x00007fb899f39700:
  File "/home/python/cpython/Lib/ctypes/__init__.py", line 486 in string_at
  File "<stdin>", line 1 in <module>
Segmentation fault

ipaddress

The new ipaddress module provides tools for creating and manipulating objects representing IPv4 and IPv6 addresses, networks and interfaces (i.e. an IP address associated with a specific IP subnet).

(Contributed by Google and Peter Moody in PEP 3144 [https://www.python.org/dev/peps/pep-3144].)

lzma

The newly-added lzma module provides data compression and decompression using the LZMA algorithm, including support for the .xz and .lzma file formats.

(Contributed by Nadeem Vawda and Per Øyvind Karlsen in bpo-6715 [https://bugs.python.org/issue?@action=redirect&bpo=6715].)

Improved Modules

abc

Improved support for abstract base classes containing descriptors composed with abstract methods. The recommended approach to declaring abstract descriptors is now to provide __isabstractmethod__ as a dynamically updated property. The built-in descriptors have been updated accordingly.

abc.abstractproperty has been deprecated, use property with abc.abstractmethod() instead.

abc.abstractclassmethod has been deprecated, use classmethod with abc.abstractmethod() instead.

abc.abstractstaticmethod has been deprecated, use staticmethod with abc.abstractmethod() instead.

(Contributed by Darren Dale in bpo-11610 [https://bugs.python.org/issue?@action=redirect&bpo=11610].)

abc.ABCMeta.register() now returns the registered subclass, which means it can now be used as a class decorator (bpo-10868 [https://bugs.python.org/issue?@action=redirect&bpo=10868]).

array

The array module supports the long long type using q and Q type codes.

(Contributed by Oren Tirosh and Hirokazu Yamamoto in bpo-1172711 [https://bugs.python.org/issue?@action=redirect&bpo=1172711].)

base64

ASCII-only Unicode strings are now accepted by the decoding functions of the base64 modern interface. For example, base64.b64decode('YWJj') returns b'abc'. (Contributed by Catalin Iacob in bpo-13641 [https://bugs.python.org/issue?@action=redirect&bpo=13641].)

binascii

In addition to the binary objects they normally accept, the a2b_ functions now all also accept ASCII-only strings as input. (Contributed by Antoine Pitrou in bpo-13637 [https://bugs.python.org/issue?@action=redirect&bpo=13637].)

bz2

The bz2 module has been rewritten from scratch. In the process, several new features have been added:

New bz2.open() function: open a bzip2-compressed file in binary or text mode.

bz2.BZ2File can now read from and write to arbitrary file-like objects, by means of its constructor’s fileobj argument.

(Contributed by Nadeem Vawda in bpo-5863 [https://bugs.python.org/issue?@action=redirect&bpo=5863].)

bz2.BZ2File and bz2.decompress() can now decompress multi-stream inputs (such as those produced by the pbzip2 tool). bz2.BZ2File can now also be used to create this type of file, using the 'a' (append) mode.

(Contributed by Nir Aides in bpo-1625 [https://bugs.python.org/issue?@action=redirect&bpo=1625].)

bz2.BZ2File now implements all of the io.BufferedIOBase API, except for the detach() and truncate() methods.

codecs

The mbcs codec has been rewritten to handle correctly replace and ignore error handlers on all Windows versions. The mbcs codec now supports all error handlers, instead of only replace to encode and ignore to decode.

A new Windows-only codec has been added: cp65001 (bpo-13216 [https://bugs.python.org/issue?@action=redirect&bpo=13216]). It is the Windows code page 65001 (Windows UTF-8, CP_UTF8). For example, it is used by sys.stdout if the console output code page is set to cp65001 (e.g., using chcp 65001 command).

Multibyte CJK decoders now resynchronize faster. They only ignore the first byte of an invalid byte sequence. For example, b'\xff\n'.decode('gb2312', 'replace') now returns a \n after the replacement character.

(bpo-12016 [https://bugs.python.org/issue?@action=redirect&bpo=12016])

Incremental CJK codec encoders are no longer reset at each call to their encode() methods. For example:

>>> import codecs
>>> encoder = codecs.getincrementalencoder('hz')('strict')
>>> b''.join(encoder.encode(x) for x in '\u52ff\u65bd\u65bc\u4eba\u3002 Bye.')
b'~{NpJ)l6HK!#~} Bye.'

This example gives b'~{Np~}~{J)~}~{l6~}~{HK~}~{!#~} Bye.' with older Python versions.

(bpo-12100 [https://bugs.python.org/issue?@action=redirect&bpo=12100])

The unicode_internal codec has been deprecated.

collections

Addition of a new ChainMap class to allow treating a number of mappings as a single unit. (Written by Raymond Hettinger for bpo-11089 [https://bugs.python.org/issue?@action=redirect&bpo=11089], made public in bpo-11297 [https://bugs.python.org/issue?@action=redirect&bpo=11297].)

The abstract base classes have been moved in a new collections.abc module, to better differentiate between the abstract and the concrete collections classes. Aliases for ABCs are still present in the collections module to preserve existing imports. (bpo-11085 [https://bugs.python.org/issue?@action=redirect&bpo=11085])

The Counter class now supports the unary + and - operators, as well as the in-place operators +=, -=, |=, and &=. (Contributed by Raymond Hettinger in bpo-13121 [https://bugs.python.org/issue?@action=redirect&bpo=13121].)

contextlib

ExitStack now provides a solid foundation for programmatic manipulation of context managers and similar cleanup functionality. Unlike the previous contextlib.nested API (which was deprecated and removed), the new API is designed to work correctly regardless of whether context managers acquire their resources in their __init__ method (for example, file objects) or in their __enter__ method (for example, synchronisation objects from the threading module).

(bpo-13585 [https://bugs.python.org/issue?@action=redirect&bpo=13585])

crypt

Addition of salt and modular crypt format (hashing method) and the mksalt() function to the crypt module.

(bpo-10924 [https://bugs.python.org/issue?@action=redirect&bpo=10924])

curses

If the curses module is linked to the ncursesw library, use Unicode functions when Unicode strings or characters are passed (e.g. waddwstr()), and bytes functions otherwise (e.g. waddstr()).

Use the locale encoding instead of utf-8 to encode Unicode strings.

curses.window has a new curses.window.encoding attribute.

The curses.window class has a new get_wch() method to get a wide character

The curses module has a new unget_wch() function to push a wide character so the next get_wch() will return it

(Contributed by Iñigo Serna in bpo-6755 [https://bugs.python.org/issue?@action=redirect&bpo=6755].)

datetime

Equality comparisons between naive and aware datetime instances now return False instead of raising TypeError (bpo-15006 [https://bugs.python.org/issue?@action=redirect&bpo=15006]).

New datetime.datetime.timestamp() method: Return POSIX timestamp corresponding to the datetime instance.

The datetime.datetime.strftime() method supports formatting years older than 1000.

The datetime.datetime.astimezone() method can now be called without arguments to convert datetime instance to the system timezone.

decimal

bpo-7652 [https://bugs.python.org/issue?@action=redirect&bpo=7652] - integrate fast native decimal arithmetic.

C-module and libmpdec written by Stefan Krah.

The new C version of the decimal module integrates the high speed libmpdec library for arbitrary precision correctly-rounded decimal floating point arithmetic. libmpdec conforms to IBM’s General Decimal Arithmetic Specification.

Performance gains range from 10x for database applications to 100x for numerically intensive applications. These numbers are expected gains for standard precisions used in decimal floating point arithmetic. Since the precision is user configurable, the exact figures may vary. For example, in integer bignum arithmetic the differences can be significantly higher.

The following table is meant as an illustration. Benchmarks are available at http://www.bytereef.org/mpdecimal/quickstart.html.

decimal.py

_decimal

speedup

pi

42.02s

0.345s

120x

telco

172.19s

5.68s

30x

psycopg

3.57s

0.29s

12x

Features

The FloatOperation signal optionally enables stricter semantics for mixing floats and Decimals.

If Python is compiled without threads, the C version automatically disables the expensive thread local context machinery. In this case, the variable HAVE_THREADS is set to False.

API changes

The C module has the following context limits, depending on the machine architecture:

32-bit

64-bit

MAX_PREC

425000000

999999999999999999

MAX_EMAX

425000000

999999999999999999

MIN_EMIN

-425000000

-999999999999999999

In the context templates (DefaultContext, BasicContext and ExtendedContext) the magnitude of Emax and Emin has changed to 999999.

The Decimal constructor in decimal.py does not observe the context limits and converts values with arbitrary exponents or precision exactly. Since the C version has internal limits, the following scheme is used: If possible, values are converted exactly, otherwise InvalidOperation is raised and the result is NaN. In the latter case it is always possible to use create_decimal() in order to obtain a rounded or inexact value.

The power function in decimal.py is always correctly-rounded. In the C version, it is defined in terms of the correctly-rounded exp() and ln() functions, but the final result is only “almost always correctly rounded”.

In the C version, the context dictionary containing the signals is a MutableMapping. For speed reasons, flags and traps always refer to the same MutableMapping that the context was initialized with. If a new signal dictionary is assigned, flags and traps are updated with the new values, but they do not reference the RHS dictionary.

Pickling a Context produces a different output in order to have a common interchange format for the Python and C versions.

The order of arguments in the Context constructor has been changed to match the order displayed by repr().

The watchexp parameter in the quantize() method is deprecated.

email

Policy Framework

The email package now has a policy framework. A Policy is an object with several methods and properties that control how the email package behaves. The primary policy for Python 3.3 is the Compat32 policy, which provides backward compatibility with the email package in Python 3.2. A policy can be specified when an email message is parsed by a parser, or when a Message object is created, or when an email is serialized using a generator. Unless overridden, a policy passed to a parser is inherited by all the Message object and sub-objects created by the parser. By default a generator will use the policy of the Message object it is serializing. The default policy is compat32.

The minimum set of controls implemented by all policy objects are:

max_line_length

The maximum length, excluding the linesep character(s), individual lines may have when a Message is serialized. Defaults to 78.

linesep

The character used to separate individual lines when a Message is serialized. Defaults to \n.

cte_type

7bit or 8bit. 8bit applies only to a Bytes generator, and means that non-ASCII may be used where allowed by the protocol (or where it exists in the original input).

raise_on_defect

Causes a parser to raise error when defects are encountered instead of adding them to the Message object’s defects list.

A new policy instance, with new settings, is created using the clone() method of policy objects. clone takes any of the above controls as keyword arguments. Any control not specified in the call retains its default value. Thus you can create a policy that uses \r\n linesep characters like this:

mypolicy = compat32.clone(linesep='\r\n')

Policies can be used to make the generation of messages in the format needed by your application simpler. Instead of having to remember to specify linesep='\r\n' in all the places you call a generator, you can specify it once, when you set the policy used by the parser or the Message, whichever your program uses to create Message objects. On the other hand, if you need to generate messages in multiple forms, you can still specify the parameters in the appropriate generator call. Or you can have custom policy instances for your different cases, and pass those in when you create the generator.

Provisional Policy with New Header API

While the policy framework is worthwhile all by itself, the main motivation for introducing it is to allow the creation of new policies that implement new features for the email package in a way that maintains backward compatibility for those who do not use the new policies. Because the new policies introduce a new API, we are releasing them in Python 3.3 as a provisional policy. Backwards incompatible changes (up to and including removal of the code) may occur if deemed necessary by the core developers.

The new policies are instances of EmailPolicy, and add the following additional controls:

refold_source

Controls whether or not headers parsed by a parser are refolded by the generator. It can be none, long, or all. The default is long, which means that source headers with a line longer than max_line_length get refolded. none means no line get refolded, and all means that all lines get refolded.

header_factory

A callable that take a name and value and produces a custom header object.

The header_factory is the key to the new features provided by the new policies. When one of the new policies is used, any header retrieved from a Message object is an object produced by the header_factory, and any time you set a header on a Message it becomes an object produced by header_factory. All such header objects have a name attribute equal to the header name. Address and Date headers have additional attributes that give you access to the parsed data of the header. This means you can now do things like this:

>>> m = Message(policy=SMTP)
>>> m['To'] = 'Éric <foo@example.com>'
>>> m['to']
'Éric <foo@example.com>'
>>> m['to'].addresses
(Address(display_name='Éric', username='foo', domain='example.com'),)
>>> m['to'].addresses[0].username
'foo'
>>> m['to'].addresses[0].display_name
'Éric'
>>> m['Date'] = email.utils.localtime()
>>> m['Date'].datetime
datetime.datetime(2012, 5, 25, 21, 39, 24, 465484, tzinfo=datetime.timezone(datetime.timedelta(-1, 72000), 'EDT'))
>>> m['Date']
'Fri, 25 May 2012 21:44:27 -0400'
>>> print(m)
To: =?utf-8?q?=C3=89ric?= <foo@example.com>
Date: Fri, 25 May 2012 21:44:27 -0400

You will note that the unicode display name is automatically encoded as utf-8 when the message is serialized, but that when the header is accessed directly, you get the unicode version. This eliminates any need to deal with the email.header decode_header() or make_header() functions.

You can also create addresses from parts:

>>> m['cc'] = [Group('pals', [Address('Bob', 'bob', 'example.com'),
...                           Address('Sally', 'sally', 'example.com')]),
...            Address('Bonzo', addr_spec='bonz@laugh.com')]
>>> print(m)
To: =?utf-8?q?=C3=89ric?= <foo@example.com>
Date: Fri, 25 May 2012 21:44:27 -0400
cc: pals: Bob <bob@example.com>, Sally <sally@example.com>;, Bonzo <bonz@laugh.com>

Decoding to unicode is done automatically:

>>> m2 = message_from_string(str(m))
>>> m2['to']
'Éric <foo@example.com>'

When you parse a message, you can use the addresses and groups attributes of the header objects to access the groups and individual addresses:

>>> m2['cc'].addresses
(Address(display_name='Bob', username='bob', domain='example.com'), Address(display_name='Sally', username='sally', domain='example.com'), Address(display_name='Bonzo', username='bonz', domain='laugh.com'))
>>> m2['cc'].groups
(Group(display_name='pals', addresses=(Address(display_name='Bob', username='bob', domain='example.com'), Address(display_name='Sally', username='sally', domain='example.com')), Group(display_name=None, addresses=(Address(display_name='Bonzo', username='bonz', domain='laugh.com'),))

In summary, if you use one of the new policies, header manipulation works the way it ought to: your application works with unicode strings, and the email package transparently encodes and decodes the unicode to and from the RFC standard Content Transfer Encodings.

Other API Changes

New BytesHeaderParser, added to the parser module to complement HeaderParser and complete the Bytes API.

New utility functions:

format_datetime(): given a datetime, produce a string formatted for use in an email header.

parsedate_to_datetime(): given a date string from an email header, convert it into an aware datetime, or a naive datetime if the offset is -0000.

localtime(): With no argument, returns the current local time as an aware datetime using the local timezone. Given an aware datetime, converts it into an aware datetime using the local timezone.

ftplib

ftplib.FTP now accepts a source_address keyword argument to specify the (host, port) to use as the source address in the bind call when creating the outgoing socket. (Contributed by Giampaolo Rodolà in bpo-8594 [https://bugs.python.org/issue?@action=redirect&bpo=8594].)

The FTP_TLS class now provides a new ccc() function to revert control channel back to plaintext. This can be useful to take advantage of firewalls that know how to handle NAT with non-secure FTP without opening fixed ports. (Contributed by Giampaolo Rodolà in bpo-12139 [https://bugs.python.org/issue?@action=redirect&bpo=12139].)

Added ftplib.FTP.mlsd() method which provides a parsable directory listing format and deprecates ftplib.FTP.nlst() and ftplib.FTP.dir(). (Contributed by Giampaolo Rodolà in bpo-11072 [https://bugs.python.org/issue?@action=redirect&bpo=11072].)

functools

The functools.lru_cache() decorator now accepts a typed keyword argument (that defaults to False to ensure that it caches values of different types that compare equal in separate cache slots. (Contributed by Raymond Hettinger in bpo-13227 [https://bugs.python.org/issue?@action=redirect&bpo=13227].)

gc

It is now possible to register callbacks invoked by the garbage collector before and after collection using the new callbacks list.

hmac

A new compare_digest() function has been added to prevent side channel attacks on digests through timing analysis. (Contributed by Nick Coghlan and Christian Heimes in bpo-15061 [https://bugs.python.org/issue?@action=redirect&bpo=15061].)

http

http.server.BaseHTTPRequestHandler now buffers the headers and writes them all at once when end_headers() is called. A new method flush_headers() can be used to directly manage when the accumulated headers are sent. (Contributed by Andrew Schaaf in bpo-3709 [https://bugs.python.org/issue?@action=redirect&bpo=3709].)

http.server now produces valid HTML 4.01 strict output. (Contributed by Ezio Melotti in bpo-13295 [https://bugs.python.org/issue?@action=redirect&bpo=13295].)

http.client.HTTPResponse now has a readinto() method, which means it can be used as an io.RawIOBase class. (Contributed by John Kuhn in bpo-13464 [https://bugs.python.org/issue?@action=redirect&bpo=13464].)

html

html.parser.HTMLParser is now able to parse broken markup without raising errors, therefore the strict argument of the constructor and the HTMLParseError exception are now deprecated. The ability to parse broken markup is the result of a number of bug fixes that are also available on the latest bug fix releases of Python 2.7/3.2. (Contributed by Ezio Melotti in bpo-15114 [https://bugs.python.org/issue?@action=redirect&bpo=15114], and bpo-14538 [https://bugs.python.org/issue?@action=redirect&bpo=14538], bpo-13993 [https://bugs.python.org/issue?@action=redirect&bpo=13993], bpo-13960 [https://bugs.python.org/issue?@action=redirect&bpo=13960], bpo-13358 [https://bugs.python.org/issue?@action=redirect&bpo=13358], bpo-1745761 [https://bugs.python.org/issue?@action=redirect&bpo=1745761], bpo-755670 [https://bugs.python.org/issue?@action=redirect&bpo=755670], bpo-13357 [https://bugs.python.org/issue?@action=redirect&bpo=13357], bpo-12629 [https://bugs.python.org/issue?@action=redirect&bpo=12629], bpo-1200313 [https://bugs.python.org/issue?@action=redirect&bpo=1200313], bpo-670664 [https://bugs.python.org/issue?@action=redirect&bpo=670664], bpo-13273 [https://bugs.python.org/issue?@action=redirect&bpo=13273], bpo-12888 [https://bugs.python.org/issue?@action=redirect&bpo=12888], bpo-7311 [https://bugs.python.org/issue?@action=redirect&bpo=7311].)

A new html5 dictionary that maps HTML5 named character references to the equivalent Unicode character(s) (e.g. html5['gt;'] == '>') has been added to the html.entities module. The dictionary is now also used by HTMLParser. (Contributed by Ezio Melotti in bpo-11113 [https://bugs.python.org/issue?@action=redirect&bpo=11113] and bpo-15156 [https://bugs.python.org/issue?@action=redirect&bpo=15156].)

imaplib

The IMAP4_SSL constructor now accepts an SSLContext parameter to control parameters of the secure channel.

(Contributed by Sijin Joseph in bpo-8808 [https://bugs.python.org/issue?@action=redirect&bpo=8808].)

inspect

A new getclosurevars() function has been added. This function reports the current binding of all names referenced from the function body and where those names were resolved, making it easier to verify correct internal state when testing code that relies on stateful closures.

(Contributed by Meador Inge and Nick Coghlan in bpo-13062 [https://bugs.python.org/issue?@action=redirect&bpo=13062].)

A new getgeneratorlocals() function has been added. This function reports the current binding of local variables in the generator’s stack frame, making it easier to verify correct internal state when testing generators.

(Contributed by Meador Inge in bpo-15153 [https://bugs.python.org/issue?@action=redirect&bpo=15153].)

io

The open() function has a new 'x' mode that can be used to exclusively create a new file, and raise a FileExistsError if the file already exists. It is based on the C11 ‘x’ mode to fopen().

(Contributed by David Townshend in bpo-12760 [https://bugs.python.org/issue?@action=redirect&bpo=12760].)

The constructor of the TextIOWrapper class has a new write_through optional argument. If write_through is True, calls to write() are guaranteed not to be buffered: any data written on the TextIOWrapper object is immediately handled to its underlying binary buffer.

itertools

accumulate() now takes an optional func argument for providing a user-supplied binary function.

logging

The basicConfig() function now supports an optional handlers argument taking an iterable of handlers to be added to the root logger.

A class level attribute append_nul has been added to SysLogHandler to allow control of the appending of the NUL (\000) byte to syslog records, since for some daemons it is required while for others it is passed through to the log.

math

The math module has a new function, log2(), which returns the base-2 logarithm of x.

(Written by Mark Dickinson in bpo-11888 [https://bugs.python.org/issue?@action=redirect&bpo=11888].)

mmap

The read() method is now more compatible with other file-like objects: if the argument is omitted or specified as None, it returns the bytes from the current file position to the end of the mapping. (Contributed by Petri Lehtinen in bpo-12021 [https://bugs.python.org/issue?@action=redirect&bpo=12021].)

multiprocessing

The new multiprocessing.connection.wait() function allows polling multiple objects (such as connections, sockets and pipes) with a timeout. (Contributed by Richard Oudkerk in bpo-12328 [https://bugs.python.org/issue?@action=redirect&bpo=12328].)

multiprocessing.Connection objects can now be transferred over multiprocessing connections. (Contributed by Richard Oudkerk in bpo-4892 [https://bugs.python.org/issue?@action=redirect&bpo=4892].)

multiprocessing.Process now accepts a daemon keyword argument to override the default behavior of inheriting the daemon flag from the parent process (bpo-6064 [https://bugs.python.org/issue?@action=redirect&bpo=6064]).

New attribute multiprocessing.Process.sentinel allows a program to wait on multiple Process objects at one time using the appropriate OS primitives (for example, select on posix systems).

New methods multiprocessing.pool.Pool.starmap() and starmap_async() provide itertools.starmap() equivalents to the existing multiprocessing.pool.Pool.map() and map_async() functions. (Contributed by Hynek Schlawack in bpo-12708 [https://bugs.python.org/issue?@action=redirect&bpo=12708].)

nntplib

The nntplib.NNTP class now supports the context management protocol to unconditionally consume socket.error exceptions and to close the NNTP connection when done:

>>> from nntplib import NNTP
>>> with NNTP('news.gmane.org') as n:
...     n.group('gmane.comp.python.committers')
...
('211 1755 1 1755 gmane.comp.python.committers', 1755, 1, 1755, 'gmane.comp.python.committers')
>>>

(Contributed by Giampaolo Rodolà in bpo-9795 [https://bugs.python.org/issue?@action=redirect&bpo=9795].)

os

The os module has a new pipe2() function that makes it possible to create a pipe with O_CLOEXEC or O_NONBLOCK flags set atomically. This is especially useful to avoid race conditions in multi-threaded programs.

The os module has a new sendfile() function which provides an efficient “zero-copy” way for copying data from one file (or socket) descriptor to another. The phrase “zero-copy” refers to the fact that all of the copying of data between the two descriptors is done entirely by the kernel, with no copying of data into userspace buffers. sendfile() can be used to efficiently copy data from a file on disk to a network socket, e.g. for downloading a file.

(Patch submitted by Ross Lagerwall and Giampaolo Rodolà in bpo-10882 [https://bugs.python.org/issue?@action=redirect&bpo=10882].)

To avoid race conditions like symlink attacks and issues with temporary files and directories, it is more reliable (and also faster) to manipulate file descriptors instead of file names. Python 3.3 enhances existing functions and introduces new functions to work on file descriptors (bpo-4761 [https://bugs.python.org/issue?@action=redirect&bpo=4761], bpo-10755 [https://bugs.python.org/issue?@action=redirect&bpo=10755] and bpo-14626 [https://bugs.python.org/issue?@action=redirect&bpo=14626]).

The os module has a new fwalk() function similar to walk() except that it also yields file descriptors referring to the directories visited. This is especially useful to avoid symlink races.

The following functions get new optional dir_fd (paths relative to directory descriptors) and/or follow_symlinks (not following symlinks): access(), chflags(), chmod(), chown(), link(), lstat(), mkdir(), mkfifo(), mknod(), open(), readlink(), remove(), rename(), replace(), rmdir(), stat(), symlink(), unlink(), utime(). Platform support for using these parameters can be checked via the sets os.supports_dir_fd and os.supports_follows_symlinks.

The following functions now support a file descriptor for their path argument: chdir(), chmod(), chown(), execve(), listdir(), pathconf(), exists(), stat(), statvfs(), utime(). Platform support for this can be checked via the os.supports_fd set.

access() accepts an effective_ids keyword argument to turn on using the effective uid/gid rather than the real uid/gid in the access check. Platform support for this can be checked via the supports_effective_ids set.

The os module has two new functions: getpriority() and setpriority(). They can be used to get or set process niceness/priority in a fashion similar to os.nice() but extended to all processes instead of just the current one.

(Patch submitted by Giampaolo Rodolà in bpo-10784 [https://bugs.python.org/issue?@action=redirect&bpo=10784].)

The new os.replace() function allows cross-platform renaming of a file with overwriting the destination. With os.rename(), an existing destination file is overwritten under POSIX, but raises an error under Windows. (Contributed by Antoine Pitrou in bpo-8828 [https://bugs.python.org/issue?@action=redirect&bpo=8828].)

The stat family of functions (stat(), fstat(), and lstat()) now support reading a file’s timestamps with nanosecond precision. Symmetrically, utime() can now write file timestamps with nanosecond precision. (Contributed by Larry Hastings in bpo-14127 [https://bugs.python.org/issue?@action=redirect&bpo=14127].)

The new os.get_terminal_size() function queries the size of the terminal attached to a file descriptor. See also shutil.get_terminal_size(). (Contributed by Zbigniew Jędrzejewski-Szmek in bpo-13609 [https://bugs.python.org/issue?@action=redirect&bpo=13609].)

New functions to support Linux extended attributes (bpo-12720 [https://bugs.python.org/issue?@action=redirect&bpo=12720]): getxattr(), listxattr(), removexattr(), setxattr().

New interface to the scheduler. These functions control how a process is allocated CPU time by the operating system. New functions: sched_get_priority_max(), sched_get_priority_min(), sched_getaffinity(), sched_getparam(), sched_getscheduler(), sched_rr_get_interval(), sched_setaffinity(), sched_setparam(), sched_setscheduler(), sched_yield(),

New functions to control the file system:

posix_fadvise(): Announces an intention to access data in a specific pattern thus allowing the kernel to make optimizations.

posix_fallocate(): Ensures that enough disk space is allocated for a file.

sync(): Force write of everything to disk.

Additional new posix functions:

lockf(): Apply, test or remove a POSIX lock on an open file descriptor.

pread(): Read from a file descriptor at an offset, the file offset remains unchanged.

pwrite(): Write to a file descriptor from an offset, leaving the file offset unchanged.

readv(): Read from a file descriptor into a number of writable buffers.

truncate(): Truncate the file corresponding to path, so that it is at most length bytes in size.

waitid(): Wait for the completion of one or more child processes.

writev(): Write the contents of buffers to a file descriptor, where buffers is an arbitrary sequence of buffers.

getgrouplist() (bpo-9344 [https://bugs.python.org/issue?@action=redirect&bpo=9344]): Return list of group ids that specified user belongs to.

times() and uname(): Return type changed from a tuple to a tuple-like object with named attributes.

Some platforms now support additional constants for the lseek() function, such as os.SEEK_HOLE and os.SEEK_DATA.

New constants RTLD_LAZY, RTLD_NOW, RTLD_GLOBAL, RTLD_LOCAL, RTLD_NODELETE, RTLD_NOLOAD, and RTLD_DEEPBIND are available on platforms that support them. These are for use with the sys.setdlopenflags() function, and supersede the similar constants defined in ctypes and DLFCN. (Contributed by Victor Stinner in bpo-13226 [https://bugs.python.org/issue?@action=redirect&bpo=13226].)

os.symlink() now accepts (and ignores) the target_is_directory keyword argument on non-Windows platforms, to ease cross-platform support.

pdb

Tab-completion is now available not only for command names, but also their arguments. For example, for the break command, function and file names are completed.

(Contributed by Georg Brandl in bpo-14210 [https://bugs.python.org/issue?@action=redirect&bpo=14210])

pickle

pickle.Pickler objects now have an optional dispatch_table attribute allowing per-pickler reduction functions to be set.

(Contributed by Richard Oudkerk in bpo-14166 [https://bugs.python.org/issue?@action=redirect&bpo=14166].)

pydoc

The Tk GUI and the serve() function have been removed from the pydoc module: pydoc -g and serve() have been deprecated in Python 3.2.

re

str regular expressions now support \u and \U escapes.

(Contributed by Serhiy Storchaka in bpo-3665 [https://bugs.python.org/issue?@action=redirect&bpo=3665].)

sched

run() now accepts a blocking parameter which when set to false makes the method execute the scheduled events due to expire soonest (if any) and then return immediately. This is useful in case you want to use the scheduler in non-blocking applications. (Contributed by Giampaolo Rodolà in bpo-13449 [https://bugs.python.org/issue?@action=redirect&bpo=13449].)

scheduler class can now be safely used in multi-threaded environments. (Contributed by Josiah Carlson and Giampaolo Rodolà in bpo-8684 [https://bugs.python.org/issue?@action=redirect&bpo=8684].)

timefunc and delayfunct parameters of scheduler class constructor are now optional and defaults to time.time() and time.sleep() respectively. (Contributed by Chris Clark in bpo-13245 [https://bugs.python.org/issue?@action=redirect&bpo=13245].)

enter() and enterabs() argument parameter is now optional. (Contributed by Chris Clark in bpo-13245 [https://bugs.python.org/issue?@action=redirect&bpo=13245].)

enter() and enterabs() now accept a kwargs parameter. (Contributed by Chris Clark in bpo-13245 [https://bugs.python.org/issue?@action=redirect&bpo=13245].)

select

Solaris and derivative platforms have a new class select.devpoll for high performance asynchronous sockets via /dev/poll. (Contributed by Jesús Cea Avión in bpo-6397 [https://bugs.python.org/issue?@action=redirect&bpo=6397].)

shlex

The previously undocumented helper function quote from the pipes modules has been moved to the shlex module and documented. quote() properly escapes all characters in a string that might be otherwise given special meaning by the shell.

shutil

New functions:

disk_usage(): provides total, used and free disk space statistics. (Contributed by Giampaolo Rodolà in bpo-12442 [https://bugs.python.org/issue?@action=redirect&bpo=12442].)

chown(): allows one to change user and/or group of the given path also specifying the user/group names and not only their numeric ids. (Contributed by Sandro Tosi in bpo-12191 [https://bugs.python.org/issue?@action=redirect&bpo=12191].)

shutil.get_terminal_size(): returns the size of the terminal window to which the interpreter is attached. (Contributed by Zbigniew Jędrzejewski-Szmek in bpo-13609 [https://bugs.python.org/issue?@action=redirect&bpo=13609].)

copy2() and copystat() now preserve file timestamps with nanosecond precision on platforms that support it. They also preserve file “extended attributes” on Linux. (Contributed by Larry Hastings in bpo-14127 [https://bugs.python.org/issue?@action=redirect&bpo=14127] and bpo-15238 [https://bugs.python.org/issue?@action=redirect&bpo=15238].)

Several functions now take an optional symlinks argument: when that parameter is true, symlinks aren’t dereferenced and the operation instead acts on the symlink itself (or creates one, if relevant). (Contributed by Hynek Schlawack in bpo-12715 [https://bugs.python.org/issue?@action=redirect&bpo=12715].)

When copying files to a different file system, move() now handles symlinks the way the posix mv command does, recreating the symlink rather than copying the target file contents. (Contributed by Jonathan Niehof in bpo-9993 [https://bugs.python.org/issue?@action=redirect&bpo=9993].) move() now also returns the dst argument as its result.

rmtree() is now resistant to symlink attacks on platforms which support the new dir_fd parameter in os.open() and os.unlink(). (Contributed by Martin von Löwis and Hynek Schlawack in bpo-4489 [https://bugs.python.org/issue?@action=redirect&bpo=4489].)

signal

The signal module has new functions:

pthread_sigmask(): fetch and/or change the signal mask of the calling thread (Contributed by Jean-Paul Calderone in bpo-8407 [https://bugs.python.org/issue?@action=redirect&bpo=8407]);

pthread_kill(): send a signal to a thread;

sigpending(): examine pending functions;

sigwait(): wait a signal;

sigwaitinfo(): wait for a signal, returning detailed information about it;

sigtimedwait(): like sigwaitinfo() but with a timeout.

The signal handler writes the signal number as a single byte instead of a nul byte into the wakeup file descriptor. So it is possible to wait more than one signal and know which signals were raised.

signal.signal() and signal.siginterrupt() raise an OSError, instead of a RuntimeError: OSError has an errno attribute.

smtpd

The smtpd module now supports RFC 5321 [https://tools.ietf.org/html/rfc5321.html] (extended SMTP) and RFC 1870 [https://tools.ietf.org/html/rfc1870.html] (size extension). Per the standard, these extensions are enabled if and only if the client initiates the session with an EHLO command.

(Initial ELHO support by Alberto Trevino. Size extension by Juhana Jauhiainen. Substantial additional work on the patch contributed by Michele Orrù and Dan Boswell. bpo-8739 [https://bugs.python.org/issue?@action=redirect&bpo=8739])

smtplib

The SMTP, SMTP_SSL, and LMTP classes now accept a source_address keyword argument to specify the (host, port) to use as the source address in the bind call when creating the outgoing socket. (Contributed by Paulo Scardine in bpo-11281 [https://bugs.python.org/issue?@action=redirect&bpo=11281].)

SMTP now supports the context management protocol, allowing an SMTP instance to be used in a with statement. (Contributed by Giampaolo Rodolà in bpo-11289 [https://bugs.python.org/issue?@action=redirect&bpo=11289].)

The SMTP_SSL constructor and the starttls() method now accept an SSLContext parameter to control parameters of the secure channel. (Contributed by Kasun Herath in bpo-8809 [https://bugs.python.org/issue?@action=redirect&bpo=8809].)

socket

The socket class now exposes additional methods to process ancillary data when supported by the underlying platform:

sendmsg()

recvmsg()

recvmsg_into()

(Contributed by David Watson in bpo-6560 [https://bugs.python.org/issue?@action=redirect&bpo=6560], based on an earlier patch by Heiko Wundram)

The socket class now supports the PF_CAN protocol family (https://en.wikipedia.org/wiki/Socketcan), on Linux (https://lwn.net/Articles/253425).

(Contributed by Matthias Fuchs, updated by Tiago Gonçalves in bpo-10141 [https://bugs.python.org/issue?@action=redirect&bpo=10141].)

The socket class now supports the PF_RDS protocol family (https://en.wikipedia.org/wiki/Reliable_Datagram_Sockets and https://oss.oracle.com/projects/rds/).

The socket class now supports the PF_SYSTEM protocol family on OS X. (Contributed by Michael Goderbauer in bpo-13777 [https://bugs.python.org/issue?@action=redirect&bpo=13777].)

New function sethostname() allows the hostname to be set on unix systems if the calling process has sufficient privileges. (Contributed by Ross Lagerwall in bpo-10866 [https://bugs.python.org/issue?@action=redirect&bpo=10866].)

socketserver

BaseServer now has an overridable method service_actions() that is called by the serve_forever() method in the service loop. ForkingMixIn now uses this to clean up zombie child processes. (Contributed by Justin Warkentin in bpo-11109 [https://bugs.python.org/issue?@action=redirect&bpo=11109].)

sqlite3

New sqlite3.Connection method set_trace_callback() can be used to capture a trace of all sql commands processed by sqlite. (Contributed by Torsten Landschoff in bpo-11688 [https://bugs.python.org/issue?@action=redirect&bpo=11688].)

ssl

The ssl module has two new random generation functions:

RAND_bytes(): generate cryptographically strong pseudo-random bytes.

RAND_pseudo_bytes(): generate pseudo-random bytes.

(Contributed by Victor Stinner in bpo-12049 [https://bugs.python.org/issue?@action=redirect&bpo=12049].)

The ssl module now exposes a finer-grained exception hierarchy in order to make it easier to inspect the various kinds of errors. (Contributed by Antoine Pitrou in bpo-11183 [https://bugs.python.org/issue?@action=redirect&bpo=11183].)

load_cert_chain() now accepts a password argument to be used if the private key is encrypted. (Contributed by Adam Simpkins in bpo-12803 [https://bugs.python.org/issue?@action=redirect&bpo=12803].)

Diffie-Hellman key exchange, both regular and Elliptic Curve-based, is now supported through the load_dh_params() and set_ecdh_curve() methods. (Contributed by Antoine Pitrou in bpo-13626 [https://bugs.python.org/issue?@action=redirect&bpo=13626] and bpo-13627 [https://bugs.python.org/issue?@action=redirect&bpo=13627].)

SSL sockets have a new get_channel_binding() method allowing the implementation of certain authentication mechanisms such as SCRAM-SHA-1-PLUS. (Contributed by Jacek Konieczny in bpo-12551 [https://bugs.python.org/issue?@action=redirect&bpo=12551].)

You can query the SSL compression algorithm used by an SSL socket, thanks to its new compression() method. The new attribute OP_NO_COMPRESSION can be used to disable compression. (Contributed by Antoine Pitrou in bpo-13634 [https://bugs.python.org/issue?@action=redirect&bpo=13634].)

Support has been added for the Next Protocol Negotiation extension using the ssl.SSLContext.set_npn_protocols() method. (Contributed by Colin Marc in bpo-14204 [https://bugs.python.org/issue?@action=redirect&bpo=14204].)

SSL errors can now be introspected more easily thanks to library and reason attributes. (Contributed by Antoine Pitrou in bpo-14837 [https://bugs.python.org/issue?@action=redirect&bpo=14837].)

The get_server_certificate() function now supports IPv6. (Contributed by Charles-François Natali in bpo-11811 [https://bugs.python.org/issue?@action=redirect&bpo=11811].)

New attribute OP_CIPHER_SERVER_PREFERENCE allows setting SSLv3 server sockets to use the server’s cipher ordering preference rather than the client’s (bpo-13635 [https://bugs.python.org/issue?@action=redirect&bpo=13635]).

stat

The undocumented tarfile.filemode function has been moved to stat.filemode(). It can be used to convert a file’s mode to a string of the form ‘-rwxrwxrwx’.

(Contributed by Giampaolo Rodolà in bpo-14807 [https://bugs.python.org/issue?@action=redirect&bpo=14807].)

struct

The struct module now supports ssize_t and size_t via the new codes n and N, respectively. (Contributed by Antoine Pitrou in bpo-3163 [https://bugs.python.org/issue?@action=redirect&bpo=3163].)

subprocess

Command strings can now be bytes objects on posix platforms. (Contributed by Victor Stinner in bpo-8513 [https://bugs.python.org/issue?@action=redirect&bpo=8513].)

A new constant DEVNULL allows suppressing output in a platform-independent fashion. (Contributed by Ross Lagerwall in bpo-5870 [https://bugs.python.org/issue?@action=redirect&bpo=5870].)

sys

The sys module has a new thread_info named tuple holding information about the thread implementation (bpo-11223 [https://bugs.python.org/issue?@action=redirect&bpo=11223]).

tarfile

tarfile now supports lzma encoding via the lzma module. (Contributed by Lars Gustäbel in bpo-5689 [https://bugs.python.org/issue?@action=redirect&bpo=5689].)

tempfile

tempfile.SpooledTemporaryFile’s truncate() method now accepts a size parameter. (Contributed by Ryan Kelly in bpo-9957 [https://bugs.python.org/issue?@action=redirect&bpo=9957].)

textwrap

The textwrap module has a new indent() that makes it straightforward to add a common prefix to selected lines in a block of text (bpo-13857 [https://bugs.python.org/issue?@action=redirect&bpo=13857]).

threading

threading.Condition, threading.Semaphore, threading.BoundedSemaphore, threading.Event, and threading.Timer, all of which used to be factory functions returning a class instance, are now classes and may be subclassed. (Contributed by Éric Araujo in bpo-10968 [https://bugs.python.org/issue?@action=redirect&bpo=10968].)

The threading.Thread constructor now accepts a daemon keyword argument to override the default behavior of inheriting the daemon flag value from the parent thread (bpo-6064 [https://bugs.python.org/issue?@action=redirect&bpo=6064]).

The formerly private function _thread.get_ident is now available as the public function threading.get_ident(). This eliminates several cases of direct access to the _thread module in the stdlib. Third party code that used _thread.get_ident should likewise be changed to use the new public interface.

time

The PEP 418 [https://www.python.org/dev/peps/pep-0418] added new functions to the time module:

get_clock_info(): Get information on a clock.

monotonic(): Monotonic clock (cannot go backward), not affected by system clock updates.

perf_counter(): Performance counter with the highest available resolution to measure a short duration.

process_time(): Sum of the system and user CPU time of the current process.

Other new functions:

clock_getres(), clock_gettime() and clock_settime() functions with CLOCK_xxx constants. (Contributed by Victor Stinner in bpo-10278 [https://bugs.python.org/issue?@action=redirect&bpo=10278].)

To improve cross platform consistency, sleep() now raises a ValueError when passed a negative sleep value. Previously this was an error on posix, but produced an infinite sleep on Windows.

types

Add a new types.MappingProxyType class: Read-only proxy of a mapping. (bpo-14386 [https://bugs.python.org/issue?@action=redirect&bpo=14386])

The new functions types.new_class() and types.prepare_class() provide support for PEP 3115 compliant dynamic type creation. (bpo-14588 [https://bugs.python.org/issue?@action=redirect&bpo=14588])

unittest

assertRaises(), assertRaisesRegex(), assertWarns(), and assertWarnsRegex() now accept a keyword argument msg when used as context managers. (Contributed by Ezio Melotti and Winston Ewert in bpo-10775 [https://bugs.python.org/issue?@action=redirect&bpo=10775].)

unittest.TestCase.run() now returns the TestResult object.

urllib

The Request class, now accepts a method argument used by get_method() to determine what HTTP method should be used. For example, this will send a 'HEAD' request:

>>> urlopen(Request('https://www.python.org', method='HEAD'))

(bpo-1673007 [https://bugs.python.org/issue?@action=redirect&bpo=1673007])

webbrowser

The webbrowser module supports more “browsers”: Google Chrome (named chrome, chromium, chrome-browser or chromium-browser depending on the version and operating system), and the generic launchers xdg-open, from the FreeDesktop.org project, and gvfs-open, which is the default URI handler for GNOME 3. (The former contributed by Arnaud Calmettes in bpo-13620 [https://bugs.python.org/issue?@action=redirect&bpo=13620], the latter by Matthias Klose in bpo-14493 [https://bugs.python.org/issue?@action=redirect&bpo=14493].)

xml.etree.ElementTree

The xml.etree.ElementTree module now imports its C accelerator by default; there is no longer a need to explicitly import xml.etree.cElementTree (this module stays for backwards compatibility, but is now deprecated). In addition, the iter family of methods of Element has been optimized (rewritten in C). The module’s documentation has also been greatly improved with added examples and a more detailed reference.

zlib

New attribute zlib.Decompress.eof makes it possible to distinguish between a properly-formed compressed stream and an incomplete or truncated one. (Contributed by Nadeem Vawda in bpo-12646 [https://bugs.python.org/issue?@action=redirect&bpo=12646].)

New attribute zlib.ZLIB_RUNTIME_VERSION reports the version string of the underlying zlib library that is loaded at runtime. (Contributed by Torsten Landschoff in bpo-12306 [https://bugs.python.org/issue?@action=redirect&bpo=12306].)

Optimizations

Major performance enhancements have been added:

Thanks to PEP 393 [https://www.python.org/dev/peps/pep-0393], some operations on Unicode strings have been optimized:

the memory footprint is divided by 2 to 4 depending on the text

encode an ASCII string to UTF-8 doesn’t need to encode characters anymore, the UTF-8 representation is shared with the ASCII representation

the UTF-8 encoder has been optimized

repeating a single ASCII letter and getting a substring of an ASCII string is 4 times faster

UTF-8 is now 2x to 4x faster. UTF-16 encoding is now up to 10x faster.

(Contributed by Serhiy Storchaka, bpo-14624 [https://bugs.python.org/issue?@action=redirect&bpo=14624], bpo-14738 [https://bugs.python.org/issue?@action=redirect&bpo=14738] and bpo-15026 [https://bugs.python.org/issue?@action=redirect&bpo=15026].)

Build and C API Changes

Changes to Python’s build process and to the C API include:

New PEP 3118 [https://www.python.org/dev/peps/pep-3118] related function:

PyMemoryView_FromMemory()

PEP 393 [https://www.python.org/dev/peps/pep-0393] added new Unicode types, macros and functions:

High-level API:

PyUnicode_CopyCharacters()

PyUnicode_FindChar()

PyUnicode_GetLength(), PyUnicode_GET_LENGTH

PyUnicode_New()

PyUnicode_Substring()

PyUnicode_ReadChar(), PyUnicode_WriteChar()

Low-level API:

Py_UCS1, Py_UCS2, Py_UCS4 types

PyASCIIObject and PyCompactUnicodeObject structures

PyUnicode_READY

PyUnicode_FromKindAndData()

PyUnicode_AsUCS4(), PyUnicode_AsUCS4Copy()

PyUnicode_DATA, PyUnicode_1BYTE_DATA, PyUnicode_2BYTE_DATA, PyUnicode_4BYTE_DATA

PyUnicode_KIND with PyUnicode_Kind enum: PyUnicode_WCHAR_KIND, PyUnicode_1BYTE_KIND, PyUnicode_2BYTE_KIND, PyUnicode_4BYTE_KIND

PyUnicode_READ, PyUnicode_READ_CHAR, PyUnicode_WRITE

PyUnicode_MAX_CHAR_VALUE

PyArg_ParseTuple now accepts a bytearray for the c format (bpo-12380 [https://bugs.python.org/issue?@action=redirect&bpo=12380]).

Deprecated

Unsupported Operating Systems

OS/2 and VMS are no longer supported due to the lack of a maintainer.

Windows 2000 and Windows platforms which set COMSPEC to command.com are no longer supported due to maintenance burden.

OSF support, which was deprecated in 3.2, has been completely removed.

Deprecated Python modules, functions and methods

Passing a non-empty string to object.__format__() is deprecated, and will produce a TypeError in Python 3.4 (bpo-9856 [https://bugs.python.org/issue?@action=redirect&bpo=9856]).

The unicode_internal codec has been deprecated because of the PEP 393 [https://www.python.org/dev/peps/pep-0393], use UTF-8, UTF-16 (utf-16-le or utf-16-be), or UTF-32 (utf-32-le or utf-32-be)

ftplib.FTP.nlst() and ftplib.FTP.dir(): use ftplib.FTP.mlsd()

platform.popen(): use the subprocess module. Check especially the Replacing Older Functions with the subprocess Module section (bpo-11377 [https://bugs.python.org/issue?@action=redirect&bpo=11377]).

bpo-13374 [https://bugs.python.org/issue?@action=redirect&bpo=13374]: The Windows bytes API has been deprecated in the os module. Use Unicode filenames, instead of bytes filenames, to not depend on the ANSI code page anymore and to support any filename.

bpo-13988 [https://bugs.python.org/issue?@action=redirect&bpo=13988]: The xml.etree.cElementTree module is deprecated. The accelerator is used automatically whenever available.

The behaviour of time.clock() depends on the platform: use the new time.perf_counter() or time.process_time() function instead, depending on your requirements, to have a well defined behaviour.

The os.stat_float_times() function is deprecated.

abc module:

abc.abstractproperty has been deprecated, use property with abc.abstractmethod() instead.

abc.abstractclassmethod has been deprecated, use classmethod with abc.abstractmethod() instead.

abc.abstractstaticmethod has been deprecated, use staticmethod with abc.abstractmethod() instead.

importlib package:

importlib.abc.SourceLoader.path_mtime() is now deprecated in favour of importlib.abc.SourceLoader.path_stats() as bytecode files now store both the modification time and size of the source file the bytecode file was compiled from.

Deprecated functions and types of the C API

The Py_UNICODE has been deprecated by PEP 393 [https://www.python.org/dev/peps/pep-0393] and will be removed in Python 4. All functions using this type are deprecated:

Unicode functions and methods using Py_UNICODE and Py_UNICODE* types:

PyUnicode_FromUnicode: use PyUnicode_FromWideChar() or PyUnicode_FromKindAndData()

PyUnicode_AS_UNICODE, PyUnicode_AsUnicode(), PyUnicode_AsUnicodeAndSize(): use PyUnicode_AsWideCharString()

PyUnicode_AS_DATA: use PyUnicode_DATA with PyUnicode_READ and PyUnicode_WRITE

PyUnicode_GET_SIZE, PyUnicode_GetSize(): use PyUnicode_GET_LENGTH or PyUnicode_GetLength()

PyUnicode_GET_DATA_SIZE: use PyUnicode_GET_LENGTH(str) * PyUnicode_KIND(str) (only work on ready strings)

PyUnicode_AsUnicodeCopy(): use PyUnicode_AsUCS4Copy() or PyUnicode_AsWideCharString()

PyUnicode_GetMax()

Functions and macros manipulating Py_UNICODE* strings:

Py_UNICODE_strlen: use PyUnicode_GetLength() or PyUnicode_GET_LENGTH

Py_UNICODE_strcat: use PyUnicode_CopyCharacters() or PyUnicode_FromFormat()

Py_UNICODE_strcpy, Py_UNICODE_strncpy, Py_UNICODE_COPY: use PyUnicode_CopyCharacters() or PyUnicode_Substring()

Py_UNICODE_strcmp: use PyUnicode_Compare()

Py_UNICODE_strncmp: use PyUnicode_Tailmatch()

Py_UNICODE_strchr, Py_UNICODE_strrchr: use PyUnicode_FindChar()

Py_UNICODE_FILL: use PyUnicode_Fill()

Py_UNICODE_MATCH

Encoders:

PyUnicode_Encode(): use PyUnicode_AsEncodedObject()

PyUnicode_EncodeUTF7()

PyUnicode_EncodeUTF8(): use PyUnicode_AsUTF8() or PyUnicode_AsUTF8String()

PyUnicode_EncodeUTF32()

PyUnicode_EncodeUTF16()

PyUnicode_EncodeUnicodeEscape:() use PyUnicode_AsUnicodeEscapeString()

PyUnicode_EncodeRawUnicodeEscape:() use PyUnicode_AsRawUnicodeEscapeString()

PyUnicode_EncodeLatin1(): use PyUnicode_AsLatin1String()

PyUnicode_EncodeASCII(): use PyUnicode_AsASCIIString()

PyUnicode_EncodeCharmap()

PyUnicode_TranslateCharmap()

PyUnicode_EncodeMBCS(): use PyUnicode_AsMBCSString() or PyUnicode_EncodeCodePage() (with CP_ACP code_page)

PyUnicode_EncodeDecimal(), PyUnicode_TransformDecimalToASCII()

Deprecated features

The array module’s 'u' format code is now deprecated and will be removed in Python 4 together with the rest of the (Py_UNICODE) API.

Porting to Python 3.3

This section lists previously described changes and other bugfixes that may require changes to your code.

Porting Python code

Hash randomization is enabled by default. Set the PYTHONHASHSEED environment variable to 0 to disable hash randomization. See also the object.__hash__() method.

bpo-12326 [https://bugs.python.org/issue?@action=redirect&bpo=12326]: On Linux, sys.platform doesn’t contain the major version anymore. It is now always ‘linux’, instead of ‘linux2’ or ‘linux3’ depending on the Linux version used to build Python. Replace sys.platform == ‘linux2’ with sys.platform.startswith(‘linux’), or directly sys.platform == ‘linux’ if you don’t need to support older Python versions.

bpo-13847 [https://bugs.python.org/issue?@action=redirect&bpo=13847], bpo-14180 [https://bugs.python.org/issue?@action=redirect&bpo=14180]: time and datetime: OverflowError is now raised instead of ValueError if a timestamp is out of range. OSError is now raised if C functions gmtime() or localtime() failed.

The default finders used by import now utilize a cache of what is contained within a specific directory. If you create a Python source file or sourceless bytecode file, make sure to call importlib.invalidate_caches() to clear out the cache for the finders to notice the new file.

ImportError now uses the full name of the module that was attempted to be imported. Doctests that check ImportErrors’ message will need to be updated to use the full name of the module instead of just the tail of the name.

The index argument to __import__() now defaults to 0 instead of -1 and no longer support negative values. It was an oversight when PEP 328 [https://www.python.org/dev/peps/pep-0328] was implemented that the default value remained -1. If you need to continue to perform a relative import followed by an absolute import, then perform the relative import using an index of 1, followed by another import using an index of 0. It is preferred, though, that you use importlib.import_module() rather than call __import__() directly.

__import__() no longer allows one to use an index value other than 0 for top-level modules. E.g. __import__('sys', level=1) is now an error.

Because sys.meta_path and sys.path_hooks now have finders on them by default, you will most likely want to use list.insert() instead of list.append() to add to those lists.

Because None is now inserted into sys.path_importer_cache, if you are clearing out entries in the dictionary of paths that do not have a finder, you will need to remove keys paired with values of None and imp.NullImporter to be backwards-compatible. This will lead to extra overhead on older versions of Python that re-insert None into sys.path_importer_cache where it represents the use of implicit finders, but semantically it should not change anything.

importlib.abc.Finder no longer specifies a find_module() abstract method that must be implemented. If you were relying on subclasses to implement that method, make sure to check for the method’s existence first. You will probably want to check for find_loader() first, though, in the case of working with path entry finders.

pkgutil has been converted to use importlib internally. This eliminates many edge cases where the old behaviour of the PEP 302 import emulation failed to match the behaviour of the real import system. The import emulation itself is still present, but is now deprecated. The pkgutil.iter_importers() and pkgutil.walk_packages() functions special case the standard import hooks so they are still supported even though they do not provide the non-standard iter_modules() method.

A longstanding RFC-compliance bug (bpo-1079 [https://bugs.python.org/issue?@action=redirect&bpo=1079]) in the parsing done by email.header.decode_header() has been fixed. Code that uses the standard idiom to convert encoded headers into unicode (str(make_header(decode_header(h))) will see no change, but code that looks at the individual tuples returned by decode_header will see that whitespace that precedes or follows ASCII sections is now included in the ASCII section. Code that builds headers using make_header should also continue to work without change, since make_header continues to add whitespace between ASCII and non-ASCII sections if it is not already present in the input strings.

email.utils.formataddr() now does the correct content transfer encoding when passed non-ASCII display names. Any code that depended on the previous buggy behavior that preserved the non-ASCII unicode in the formatted output string will need to be changed (bpo-1690608 [https://bugs.python.org/issue?@action=redirect&bpo=1690608]).

poplib.POP3.quit() may now raise protocol errors like all other poplib methods. Code that assumes quit does not raise poplib.error_proto errors may need to be changed if errors on quit are encountered by a particular application (bpo-11291 [https://bugs.python.org/issue?@action=redirect&bpo=11291]).

The strict argument to email.parser.Parser, deprecated since Python 2.4, has finally been removed.

The deprecated method unittest.TestCase.assertSameElements has been removed.

The deprecated variable time.accept2dyear has been removed.

The deprecated Context._clamp attribute has been removed from the decimal module. It was previously replaced by the public attribute clamp. (See bpo-8540 [https://bugs.python.org/issue?@action=redirect&bpo=8540].)

The undocumented internal helper class SSLFakeFile has been removed from smtplib, since its functionality has long been provided directly by socket.socket.makefile().

Passing a negative value to time.sleep() on Windows now raises an error instead of sleeping forever. It has always raised an error on posix.

The ast.__version__ constant has been removed. If you need to make decisions affected by the AST version, use sys.version_info to make the decision.

Code that used to work around the fact that the threading module used factory functions by subclassing the private classes will need to change to subclass the now-public classes.

The undocumented debugging machinery in the threading module has been removed, simplifying the code. This should have no effect on production code, but is mentioned here in case any application debug frameworks were interacting with it (bpo-13550 [https://bugs.python.org/issue?@action=redirect&bpo=13550]).

Porting C code

In the course of changes to the buffer API the undocumented smalltable member of the Py_buffer structure has been removed and the layout of the PyMemoryViewObject has changed.

All extensions relying on the relevant parts in memoryobject.h or object.h must be rebuilt.

Due to PEP 393, the Py_UNICODE type and all functions using this type are deprecated (but will stay available for at least five years). If you were using low-level Unicode APIs to construct and access unicode objects and you want to benefit of the memory footprint reduction provided by PEP 393, you have to convert your code to the new Unicode API.

However, if you only have been using high-level functions such as PyUnicode_Concat(), PyUnicode_Join() or PyUnicode_FromFormat(), your code will automatically take advantage of the new unicode representations.

PyImport_GetMagicNumber() now returns -1 upon failure.

As a negative value for the level argument to __import__() is no longer valid, the same now holds for PyImport_ImportModuleLevel(). This also means that the value of level used by PyImport_ImportModuleEx() is now 0 instead of -1.

Building C extensions

The range of possible file names for C extensions has been narrowed. Very rarely used spellings have been suppressed: under POSIX, files named xxxmodule.so, xxxmodule.abi3.so and xxxmodule.cpython-*.so are no longer recognized as implementing the xxx module. If you had been generating such files, you have to switch to the other spellings (i.e., remove the module string from the file names).

(implemented in bpo-14040 [https://bugs.python.org/issue?@action=redirect&bpo=14040].)

Command Line Switch Changes

The -Q command-line flag and related artifacts have been removed. Code checking sys.flags.division_warning will need updating.

(bpo-10998 [https://bugs.python.org/issue?@action=redirect&bpo=10998], contributed by Éric Araujo.)

When python is started with -S, import site will no longer add site-specific paths to the module search paths. In previous versions, it did.

(bpo-11591 [https://bugs.python.org/issue?@action=redirect&bpo=11591], contributed by Carl Meyer with editions by Éric Araujo.)

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬의 새로운 기능 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬의 새로운 기능 »

|

What’s New In Python 3.2

Author

Raymond Hettinger

This article explains the new features in Python 3.2 as compared to 3.1. It focuses on a few highlights and gives a few examples. For full details, see the Misc/NEWS [https://github.com/python/cpython/blob/076ca6c3c8df3030307e548d9be792ce3c1c6eea/Misc/NEWS] file.

더 보기

PEP 392 [https://www.python.org/dev/peps/pep-0392] - Python 3.2 Release Schedule

PEP 384: Defining a Stable ABI

In the past, extension modules built for one Python version were often not usable with other Python versions. Particularly on Windows, every feature release of Python required rebuilding all extension modules that one wanted to use. This requirement was the result of the free access to Python interpreter internals that extension modules could use.

With Python 3.2, an alternative approach becomes available: extension modules which restrict themselves to a limited API (by defining Py_LIMITED_API) cannot use many of the internals, but are constrained to a set of API functions that are promised to be stable for several releases. As a consequence, extension modules built for 3.2 in that mode will also work with 3.3, 3.4, and so on. Extension modules that make use of details of memory structures can still be built, but will need to be recompiled for every feature release.

더 보기

PEP 384 [https://www.python.org/dev/peps/pep-0384] - Defining a Stable ABI

PEP written by Martin von Löwis.

PEP 389: Argparse Command Line Parsing Module

A new module for command line parsing, argparse, was introduced to overcome the limitations of optparse which did not provide support for positional arguments (not just options), subcommands, required options and other common patterns of specifying and validating options.

This module has already had widespread success in the community as a third-party module. Being more fully featured than its predecessor, the argparse module is now the preferred module for command-line processing. The older module is still being kept available because of the substantial amount of legacy code that depends on it.

Here’s an annotated example parser showing features like limiting results to a set of choices, specifying a metavar in the help screen, validating that one or more positional arguments is present, and making a required option:

import argparse
parser = argparse.ArgumentParser(
            description = 'Manage servers',         # main description for help
            epilog = 'Tested on Solaris and Linux') # displayed after help
parser.add_argument('action',                       # argument name
            choices = ['deploy', 'start', 'stop'],  # three allowed values
            help = 'action on each target')         # help msg
parser.add_argument('targets',
            metavar = 'HOSTNAME',                   # var name used in help msg
            nargs = '+',                            # require one or more targets
            help = 'url for target machines')       # help msg explanation
parser.add_argument('-u', '--user',                 # -u or --user option
            required = True,                        # make it a required argument
            help = 'login as user')

Example of calling the parser on a command string:

>>> cmd = 'deploy sneezy.example.com sleepy.example.com -u skycaptain'
>>> result = parser.parse_args(cmd.split())
>>> result.action
'deploy'
>>> result.targets
['sneezy.example.com', 'sleepy.example.com']
>>> result.user
'skycaptain'

Example of the parser’s automatically generated help:

>>> parser.parse_args('-h'.split())

usage: manage_cloud.py [-h] -u USER
                       {deploy,start,stop} HOSTNAME [HOSTNAME ...]

Manage servers

positional arguments:
  {deploy,start,stop}   action on each target
  HOSTNAME              url for target machines

optional arguments:
  -h, --help            show this help message and exit
  -u USER, --user USER  login as user

Tested on Solaris and Linux

An especially nice argparse feature is the ability to define subparsers, each with their own argument patterns and help displays:

import argparse
parser = argparse.ArgumentParser(prog='HELM')
subparsers = parser.add_subparsers()

parser_l = subparsers.add_parser('launch', help='Launch Control')   # first subgroup
parser_l.add_argument('-m', '--missiles', action='store_true')
parser_l.add_argument('-t', '--torpedos', action='store_true')

parser_m = subparsers.add_parser('move', help='Move Vessel',        # second subgroup
                                 aliases=('steer', 'turn'))         # equivalent names
parser_m.add_argument('-c', '--course', type=int, required=True)
parser_m.add_argument('-s', '--speed', type=int, default=0)

$ ./helm.py --help                         # top level help (launch and move)
$ ./helm.py launch --help                  # help for launch options
$ ./helm.py launch --missiles              # set missiles=True and torpedos=False
$ ./helm.py steer --course 180 --speed 5   # set movement parameters

더 보기

PEP 389 [https://www.python.org/dev/peps/pep-0389] - New Command Line Parsing Module

PEP written by Steven Bethard.

optparse 코드 업그레이드 for details on the differences from optparse.

PEP 391: Dictionary Based Configuration for Logging

The logging module provided two kinds of configuration, one style with function calls for each option or another style driven by an external file saved in a ConfigParser format. Those options did not provide the flexibility to create configurations from JSON or YAML files, nor did they support incremental configuration, which is needed for specifying logger options from a command line.

To support a more flexible style, the module now offers logging.config.dictConfig() for specifying logging configuration with plain Python dictionaries. The configuration options include formatters, handlers, filters, and loggers. Here’s a working example of a configuration dictionary:

{"version": 1,
 "formatters": {"brief": {"format": "%(levelname)-8s: %(name)-15s: %(message)s"},
                "full": {"format": "%(asctime)s %(name)-15s %(levelname)-8s %(message)s"}
                },
 "handlers": {"console": {
                   "class": "logging.StreamHandler",
                   "formatter": "brief",
                   "level": "INFO",
                   "stream": "ext://sys.stdout"},
              "console_priority": {
                   "class": "logging.StreamHandler",
                   "formatter": "full",
                   "level": "ERROR",
                   "stream": "ext://sys.stderr"}
              },
 "root": {"level": "DEBUG", "handlers": ["console", "console_priority"]}}

If that dictionary is stored in a file called conf.json, it can be loaded and called with code like this:

>>> import json, logging.config
>>> with open('conf.json') as f:
...     conf = json.load(f)
...
>>> logging.config.dictConfig(conf)
>>> logging.info("Transaction completed normally")
INFO    : root           : Transaction completed normally
>>> logging.critical("Abnormal termination")
2011-02-17 11:14:36,694 root            CRITICAL Abnormal termination

더 보기

PEP 391 [https://www.python.org/dev/peps/pep-0391] - Dictionary Based Configuration for Logging

PEP written by Vinay Sajip.

PEP 3148: The concurrent.futures module

Code for creating and managing concurrency is being collected in a new top-level namespace, concurrent. Its first member is a futures package which provides a uniform high-level interface for managing threads and processes.

The design for concurrent.futures was inspired by the java.util.concurrent package. In that model, a running call and its result are represented by a Future object that abstracts features common to threads, processes, and remote procedure calls. That object supports status checks (running or done), timeouts, cancellations, adding callbacks, and access to results or exceptions.

The primary offering of the new module is a pair of executor classes for launching and managing calls. The goal of the executors is to make it easier to use existing tools for making parallel calls. They save the effort needed to setup a pool of resources, launch the calls, create a results queue, add time-out handling, and limit the total number of threads, processes, or remote procedure calls.

Ideally, each application should share a single executor across multiple components so that process and thread limits can be centrally managed. This solves the design challenge that arises when each component has its own competing strategy for resource management.

Both classes share a common interface with three methods: submit() for scheduling a callable and returning a Future object; map() for scheduling many asynchronous calls at a time, and shutdown() for freeing resources. The class is a context manager and can be used in a with statement to assure that resources are automatically released when currently pending futures are done executing.

A simple of example of ThreadPoolExecutor is a launch of four parallel threads for copying files:

import concurrent.futures, shutil
with concurrent.futures.ThreadPoolExecutor(max_workers=4) as e:
    e.submit(shutil.copy, 'src1.txt', 'dest1.txt')
    e.submit(shutil.copy, 'src2.txt', 'dest2.txt')
    e.submit(shutil.copy, 'src3.txt', 'dest3.txt')
    e.submit(shutil.copy, 'src3.txt', 'dest4.txt')

더 보기

PEP 3148 [https://www.python.org/dev/peps/pep-3148] - Futures – Execute Computations Asynchronously

PEP written by Brian Quinlan.

Code for Threaded Parallel URL reads, an example using threads to fetch multiple web pages in parallel.

Code for computing prime numbers in parallel, an example demonstrating ProcessPoolExecutor.

PEP 3147: PYC Repository Directories

Python’s scheme for caching bytecode in .pyc files did not work well in environments with multiple Python interpreters. If one interpreter encountered a cached file created by another interpreter, it would recompile the source and overwrite the cached file, thus losing the benefits of caching.

The issue of “pyc fights” has become more pronounced as it has become commonplace for Linux distributions to ship with multiple versions of Python. These conflicts also arise with CPython alternatives such as Unladen Swallow.

To solve this problem, Python’s import machinery has been extended to use distinct filenames for each interpreter. Instead of Python 3.2 and Python 3.3 and Unladen Swallow each competing for a file called “mymodule.pyc”, they will now look for “mymodule.cpython-32.pyc”, “mymodule.cpython-33.pyc”, and “mymodule.unladen10.pyc”. And to prevent all of these new files from cluttering source directories, the pyc files are now collected in a “__pycache__” directory stored under the package directory.

Aside from the filenames and target directories, the new scheme has a few aspects that are visible to the programmer:

Imported modules now have a __cached__ attribute which stores the name of the actual file that was imported:

>>> import collections
>>> collections.__cached__
'c:/py32/lib/__pycache__/collections.cpython-32.pyc'

The tag that is unique to each interpreter is accessible from the imp module:

>>> import imp
>>> imp.get_tag()
'cpython-32'

Scripts that try to deduce source filename from the imported file now need to be smarter. It is no longer sufficient to simply strip the “c” from a “.pyc” filename. Instead, use the new functions in the imp module:

>>> imp.source_from_cache('c:/py32/lib/__pycache__/collections.cpython-32.pyc')
'c:/py32/lib/collections.py'
>>> imp.cache_from_source('c:/py32/lib/collections.py')
'c:/py32/lib/__pycache__/collections.cpython-32.pyc'

The py_compile and compileall modules have been updated to reflect the new naming convention and target directory. The command-line invocation of compileall has new options: -i for specifying a list of files and directories to compile and -b which causes bytecode files to be written to their legacy location rather than __pycache__.

The importlib.abc module has been updated with new abstract base classes for loading bytecode files. The obsolete ABCs, PyLoader and PyPycLoader, have been deprecated (instructions on how to stay Python 3.1 compatible are included with the documentation).

더 보기

PEP 3147 [https://www.python.org/dev/peps/pep-3147] - PYC Repository Directories

PEP written by Barry Warsaw.

PEP 3149: ABI Version Tagged .so Files

The PYC repository directory allows multiple bytecode cache files to be co-located. This PEP implements a similar mechanism for shared object files by giving them a common directory and distinct names for each version.

The common directory is “pyshared” and the file names are made distinct by identifying the Python implementation (such as CPython, PyPy, Jython, etc.), the major and minor version numbers, and optional build flags (such as “d” for debug, “m” for pymalloc, “u” for wide-unicode). For an arbitrary package “foo”, you may see these files when the distribution package is installed:

/usr/share/pyshared/foo.cpython-32m.so
/usr/share/pyshared/foo.cpython-33md.so

In Python itself, the tags are accessible from functions in the sysconfig module:

>>> import sysconfig
>>> sysconfig.get_config_var('SOABI')       # find the version tag
'cpython-32mu'
>>> sysconfig.get_config_var('EXT_SUFFIX')  # find the full filename extension
'.cpython-32mu.so'

더 보기

PEP 3149 [https://www.python.org/dev/peps/pep-3149] - ABI Version Tagged .so Files

PEP written by Barry Warsaw.

PEP 3333: Python Web Server Gateway Interface v1.0.1

This informational PEP clarifies how bytes/text issues are to be handled by the WSGI protocol. The challenge is that string handling in Python 3 is most conveniently handled with the str type even though the HTTP protocol is itself bytes oriented.

The PEP differentiates so-called native strings that are used for request/response headers and metadata versus byte strings which are used for the bodies of requests and responses.

The native strings are always of type str but are restricted to code points between U+0000 through U+00FF which are translatable to bytes using Latin-1 encoding. These strings are used for the keys and values in the environment dictionary and for response headers and statuses in the start_response() function. They must follow RFC 2616 [https://tools.ietf.org/html/rfc2616.html] with respect to encoding. That is, they must either be ISO-8859-1 characters or use RFC 2047 [https://tools.ietf.org/html/rfc2047.html] MIME encoding.

For developers porting WSGI applications from Python 2, here are the salient points:

If the app already used strings for headers in Python 2, no change is needed.

If instead, the app encoded output headers or decoded input headers, then the headers will need to be re-encoded to Latin-1. For example, an output header encoded in utf-8 was using h.encode('utf-8') now needs to convert from bytes to native strings using h.encode('utf-8').decode('latin-1').

Values yielded by an application or sent using the write() method must be byte strings. The start_response() function and environ must use native strings. The two cannot be mixed.

For server implementers writing CGI-to-WSGI pathways or other CGI-style protocols, the users must to be able access the environment using native strings even though the underlying platform may have a different convention. To bridge this gap, the wsgiref module has a new function, wsgiref.handlers.read_environ() for transcoding CGI variables from os.environ into native strings and returning a new dictionary.

더 보기

PEP 3333 [https://www.python.org/dev/peps/pep-3333] - Python Web Server Gateway Interface v1.0.1

PEP written by Phillip Eby.

Other Language Changes

Some smaller changes made to the core Python language are:

String formatting for format() and str.format() gained new capabilities for the format character #. Previously, for integers in binary, octal, or hexadecimal, it caused the output to be prefixed with ‘0b’, ‘0o’, or ‘0x’ respectively. Now it can also handle floats, complex, and Decimal, causing the output to always have a decimal point even when no digits follow it.

>>> format(20, '#o')
'0o24'
>>> format(12.34, '#5.0f')
'  12.'

(Suggested by Mark Dickinson and implemented by Eric Smith in bpo-7094 [https://bugs.python.org/issue?@action=redirect&bpo=7094].)

There is also a new str.format_map() method that extends the capabilities of the existing str.format() method by accepting arbitrary mapping objects. This new method makes it possible to use string formatting with any of Python’s many dictionary-like objects such as defaultdict, Shelf, ConfigParser, or dbm. It is also useful with custom dict subclasses that normalize keys before look-up or that supply a __missing__() method for unknown keys:

>>> import shelve
>>> d = shelve.open('tmp.shl')
>>> 'The {project_name} status is {status} as of {date}'.format_map(d)
'The testing project status is green as of February 15, 2011'

>>> class LowerCasedDict(dict):
...     def __getitem__(self, key):
...         return dict.__getitem__(self, key.lower())
>>> lcd = LowerCasedDict(part='widgets', quantity=10)
>>> 'There are {QUANTITY} {Part} in stock'.format_map(lcd)
'There are 10 widgets in stock'

>>> class PlaceholderDict(dict):
...     def __missing__(self, key):
...         return '<{}>'.format(key)
>>> 'Hello {name}, welcome to {location}'.format_map(PlaceholderDict())
'Hello <name>, welcome to <location>'

(Suggested by Raymond Hettinger and implemented by Eric Smith in bpo-6081 [https://bugs.python.org/issue?@action=redirect&bpo=6081].)

The interpreter can now be started with a quiet option, -q, to prevent the copyright and version information from being displayed in the interactive mode. The option can be introspected using the sys.flags attribute:

$ python -q
>>> sys.flags
sys.flags(debug=0, division_warning=0, inspect=0, interactive=0,
optimize=0, dont_write_bytecode=0, no_user_site=0, no_site=0,
ignore_environment=0, verbose=0, bytes_warning=0, quiet=1)

(Contributed by Marcin Wojdyr in bpo-1772833 [https://bugs.python.org/issue?@action=redirect&bpo=1772833]).

The hasattr() function works by calling getattr() and detecting whether an exception is raised. This technique allows it to detect methods created dynamically by __getattr__() or __getattribute__() which would otherwise be absent from the class dictionary. Formerly, hasattr would catch any exception, possibly masking genuine errors. Now, hasattr has been tightened to only catch AttributeError and let other exceptions pass through:

>>> class A:
...     @property
...     def f(self):
...         return 1 // 0
...
>>> a = A()
>>> hasattr(a, 'f')
Traceback (most recent call last):
  ...
ZeroDivisionError: integer division or modulo by zero

(Discovered by Yury Selivanov and fixed by Benjamin Peterson; bpo-9666 [https://bugs.python.org/issue?@action=redirect&bpo=9666].)

The str() of a float or complex number is now the same as its repr(). Previously, the str() form was shorter but that just caused confusion and is no longer needed now that the shortest possible repr() is displayed by default:

>>> import math
>>> repr(math.pi)
'3.141592653589793'
>>> str(math.pi)
'3.141592653589793'

(Proposed and implemented by Mark Dickinson; bpo-9337 [https://bugs.python.org/issue?@action=redirect&bpo=9337].)

memoryview objects now have a release() method and they also now support the context management protocol. This allows timely release of any resources that were acquired when requesting a buffer from the original object.

>>> with memoryview(b'abcdefgh') as v:
...     print(v.tolist())
[97, 98, 99, 100, 101, 102, 103, 104]

(Added by Antoine Pitrou; bpo-9757 [https://bugs.python.org/issue?@action=redirect&bpo=9757].)

Previously it was illegal to delete a name from the local namespace if it occurs as a free variable in a nested block:

def outer(x):
    def inner():
        return x
    inner()
    del x

This is now allowed. Remember that the target of an except clause is cleared, so this code which used to work with Python 2.6, raised a SyntaxError with Python 3.1 and now works again:

def f():
    def print_error():
        print(e)
    try:
        something
    except Exception as e:
        print_error()
        # implicit "del e" here

(See bpo-4617 [https://bugs.python.org/issue?@action=redirect&bpo=4617].)

The internal structsequence tool now creates subclasses of tuple. This means that C structures like those returned by os.stat(), time.gmtime(), and sys.version_info now work like a named tuple and now work with functions and methods that expect a tuple as an argument. This is a big step forward in making the C structures as flexible as their pure Python counterparts:

>>> import sys
>>> isinstance(sys.version_info, tuple)
True
>>> 'Version %d.%d.%d %s(%d)' % sys.version_info
'Version 3.2.0 final(0)'

(Suggested by Arfrever Frehtes Taifersar Arahesis and implemented by Benjamin Peterson in bpo-8413 [https://bugs.python.org/issue?@action=redirect&bpo=8413].)

Warnings are now easier to control using the PYTHONWARNINGS environment variable as an alternative to using -W at the command line:

$ export PYTHONWARNINGS='ignore::RuntimeWarning::,once::UnicodeWarning::'

(Suggested by Barry Warsaw and implemented by Philip Jenvey in bpo-7301 [https://bugs.python.org/issue?@action=redirect&bpo=7301].)

A new warning category, ResourceWarning, has been added. It is emitted when potential issues with resource consumption or cleanup are detected. It is silenced by default in normal release builds but can be enabled through the means provided by the warnings module, or on the command line.

A ResourceWarning is issued at interpreter shutdown if the gc.garbage list isn’t empty, and if gc.DEBUG_UNCOLLECTABLE is set, all uncollectable objects are printed. This is meant to make the programmer aware that their code contains object finalization issues.

A ResourceWarning is also issued when a file object is destroyed without having been explicitly closed. While the deallocator for such object ensures it closes the underlying operating system resource (usually, a file descriptor), the delay in deallocating the object could produce various issues, especially under Windows. Here is an example of enabling the warning from the command line:

$ python -q -Wdefault
>>> f = open("foo", "wb")
>>> del f
__main__:1: ResourceWarning: unclosed file <_io.BufferedWriter name='foo'>

(Added by Antoine Pitrou and Georg Brandl in bpo-10093 [https://bugs.python.org/issue?@action=redirect&bpo=10093] and bpo-477863 [https://bugs.python.org/issue?@action=redirect&bpo=477863].)

range objects now support index and count methods. This is part of an effort to make more objects fully implement the collections.Sequence abstract base class. As a result, the language will have a more uniform API. In addition, range objects now support slicing and negative indices, even with values larger than sys.maxsize. This makes range more interoperable with lists:

>>> range(0, 100, 2).count(10)
1
>>> range(0, 100, 2).index(10)
5
>>> range(0, 100, 2)[5]
10
>>> range(0, 100, 2)[0:5]
range(0, 10, 2)

(Contributed by Daniel Stutzbach in bpo-9213 [https://bugs.python.org/issue?@action=redirect&bpo=9213], by Alexander Belopolsky in bpo-2690 [https://bugs.python.org/issue?@action=redirect&bpo=2690], and by Nick Coghlan in bpo-10889 [https://bugs.python.org/issue?@action=redirect&bpo=10889].)

The callable() builtin function from Py2.x was resurrected. It provides a concise, readable alternative to using an abstract base class in an expression like isinstance(x, collections.Callable):

>>> callable(max)
True
>>> callable(20)
False

(See bpo-10518 [https://bugs.python.org/issue?@action=redirect&bpo=10518].)

Python’s import mechanism can now load modules installed in directories with non-ASCII characters in the path name. This solved an aggravating problem with home directories for users with non-ASCII characters in their usernames.

(Required extensive work by Victor Stinner in bpo-9425 [https://bugs.python.org/issue?@action=redirect&bpo=9425].)

New, Improved, and Deprecated Modules

Python’s standard library has undergone significant maintenance efforts and quality improvements.

The biggest news for Python 3.2 is that the email package, mailbox module, and nntplib modules now work correctly with the bytes/text model in Python 3. For the first time, there is correct handling of messages with mixed encodings.

Throughout the standard library, there has been more careful attention to encodings and text versus bytes issues. In particular, interactions with the operating system are now better able to exchange non-ASCII data using the Windows MBCS encoding, locale-aware encodings, or UTF-8.

Another significant win is the addition of substantially better support for SSL connections and security certificates.

In addition, more classes now implement a context manager to support convenient and reliable resource clean-up using a with statement.

email

The usability of the email package in Python 3 has been mostly fixed by the extensive efforts of R. David Murray. The problem was that emails are typically read and stored in the form of bytes rather than str text, and they may contain multiple encodings within a single email. So, the email package had to be extended to parse and generate email messages in bytes format.

New functions message_from_bytes() and message_from_binary_file(), and new classes BytesFeedParser and BytesParser allow binary message data to be parsed into model objects.

Given bytes input to the model, get_payload() will by default decode a message body that has a Content-Transfer-Encoding of 8bit using the charset specified in the MIME headers and return the resulting string.

Given bytes input to the model, Generator will convert message bodies that have a Content-Transfer-Encoding of 8bit to instead have a 7bit Content-Transfer-Encoding.

Headers with unencoded non-ASCII bytes are deemed to be RFC 2047 [https://tools.ietf.org/html/rfc2047.html]-encoded using the unknown-8bit character set.

A new class BytesGenerator produces bytes as output, preserving any unchanged non-ASCII data that was present in the input used to build the model, including message bodies with a Content-Transfer-Encoding of 8bit.

The smtplib SMTP class now accepts a byte string for the msg argument to the sendmail() method, and a new method, send_message() accepts a Message object and can optionally obtain the from_addr and to_addrs addresses directly from the object.

(Proposed and implemented by R. David Murray, bpo-4661 [https://bugs.python.org/issue?@action=redirect&bpo=4661] and bpo-10321 [https://bugs.python.org/issue?@action=redirect&bpo=10321].)

elementtree

The xml.etree.ElementTree package and its xml.etree.cElementTree counterpart have been updated to version 1.3.

Several new and useful functions and methods have been added:

xml.etree.ElementTree.fromstringlist() which builds an XML document from a sequence of fragments

xml.etree.ElementTree.register_namespace() for registering a global namespace prefix

xml.etree.ElementTree.tostringlist() for string representation including all sublists

xml.etree.ElementTree.Element.extend() for appending a sequence of zero or more elements

xml.etree.ElementTree.Element.iterfind() searches an element and subelements

xml.etree.ElementTree.Element.itertext() creates a text iterator over an element and its subelements

xml.etree.ElementTree.TreeBuilder.end() closes the current element

xml.etree.ElementTree.TreeBuilder.doctype() handles a doctype declaration

Two methods have been deprecated:

xml.etree.ElementTree.getchildren() use list(elem) instead.

xml.etree.ElementTree.getiterator() use Element.iter instead.

For details of the update, see Introducing ElementTree [http://effbot.org/zone/elementtree-13-intro.htm] on Fredrik Lundh’s website.

(Contributed by Florent Xicluna and Fredrik Lundh, bpo-6472 [https://bugs.python.org/issue?@action=redirect&bpo=6472].)

functools

The functools module includes a new decorator for caching function calls. functools.lru_cache() can save repeated queries to an external resource whenever the results are expected to be the same.

For example, adding a caching decorator to a database query function can save database accesses for popular searches:

>>> import functools
>>> @functools.lru_cache(maxsize=300)
... def get_phone_number(name):
...     c = conn.cursor()
...     c.execute('SELECT phonenumber FROM phonelist WHERE name=?', (name,))
...     return c.fetchone()[0]

>>> for name in user_requests:
...     get_phone_number(name)        # cached lookup

To help with choosing an effective cache size, the wrapped function is instrumented for tracking cache statistics:

>>> get_phone_number.cache_info()
CacheInfo(hits=4805, misses=980, maxsize=300, currsize=300)

If the phonelist table gets updated, the outdated contents of the cache can be cleared with:

>>> get_phone_number.cache_clear()

(Contributed by Raymond Hettinger and incorporating design ideas from Jim Baker, Miki Tebeka, and Nick Coghlan; see recipe 498245 [https://code.activestate.com/recipes/498245], recipe 577479 [https://code.activestate.com/recipes/577479], bpo-10586 [https://bugs.python.org/issue?@action=redirect&bpo=10586], and bpo-10593 [https://bugs.python.org/issue?@action=redirect&bpo=10593].)

The functools.wraps() decorator now adds a __wrapped__ attribute pointing to the original callable function. This allows wrapped functions to be introspected. It also copies __annotations__ if defined. And now it also gracefully skips over missing attributes such as __doc__ which might not be defined for the wrapped callable.

In the above example, the cache can be removed by recovering the original function:

>>> get_phone_number = get_phone_number.__wrapped__    # uncached function

(By Nick Coghlan and Terrence Cole; bpo-9567 [https://bugs.python.org/issue?@action=redirect&bpo=9567], bpo-3445 [https://bugs.python.org/issue?@action=redirect&bpo=3445], and bpo-8814 [https://bugs.python.org/issue?@action=redirect&bpo=8814].)

To help write classes with rich comparison methods, a new decorator functools.total_ordering() will use existing equality and inequality methods to fill in the remaining methods.

For example, supplying __eq__ and __lt__ will enable total_ordering() to fill-in __le__, __gt__ and __ge__:

@total_ordering
class Student:
    def __eq__(self, other):
        return ((self.lastname.lower(), self.firstname.lower()) ==
                (other.lastname.lower(), other.firstname.lower()))

    def __lt__(self, other):
        return ((self.lastname.lower(), self.firstname.lower()) <
                (other.lastname.lower(), other.firstname.lower()))

With the total_ordering decorator, the remaining comparison methods are filled in automatically.

(Contributed by Raymond Hettinger.)

To aid in porting programs from Python 2, the functools.cmp_to_key() function converts an old-style comparison function to modern key function:

>>> # locale-aware sort order
>>> sorted(iterable, key=cmp_to_key(locale.strcoll))

For sorting examples and a brief sorting tutorial, see the Sorting HowTo [https://wiki.python.org/moin/HowTo/Sorting/] tutorial.

(Contributed by Raymond Hettinger.)

itertools

The itertools module has a new accumulate() function modeled on APL’s scan operator and Numpy’s accumulate function:

>>> from itertools import accumulate
>>> list(accumulate([8, 2, 50]))
[8, 10, 60]

>>> prob_dist = [0.1, 0.4, 0.2, 0.3]
>>> list(accumulate(prob_dist))      # cumulative probability distribution
[0.1, 0.5, 0.7, 1.0]

For an example using accumulate(), see the examples for the random module.

(Contributed by Raymond Hettinger and incorporating design suggestions from Mark Dickinson.)

collections

The collections.Counter class now has two forms of in-place subtraction, the existing -= operator for saturating subtraction [https://en.wikipedia.org/wiki/Saturation_arithmetic] and the new subtract() method for regular subtraction. The former is suitable for multisets [https://en.wikipedia.org/wiki/Multiset] which only have positive counts, and the latter is more suitable for use cases that allow negative counts:

>>> from collections import Counter
>>> tally = Counter(dogs=5, cats=3)
>>> tally -= Counter(dogs=2, cats=8)    # saturating subtraction
>>> tally
Counter({'dogs': 3})

>>> tally = Counter(dogs=5, cats=3)
>>> tally.subtract(dogs=2, cats=8)      # regular subtraction
>>> tally
Counter({'dogs': 3, 'cats': -5})

(Contributed by Raymond Hettinger.)

The collections.OrderedDict class has a new method move_to_end() which takes an existing key and moves it to either the first or last position in the ordered sequence.

The default is to move an item to the last position. This is equivalent of renewing an entry with od[k] = od.pop(k).

A fast move-to-end operation is useful for resequencing entries. For example, an ordered dictionary can be used to track order of access by aging entries from the oldest to the most recently accessed.

>>> from collections import OrderedDict
>>> d = OrderedDict.fromkeys(['a', 'b', 'X', 'd', 'e'])
>>> list(d)
['a', 'b', 'X', 'd', 'e']
>>> d.move_to_end('X')
>>> list(d)
['a', 'b', 'd', 'e', 'X']

(Contributed by Raymond Hettinger.)

The collections.deque class grew two new methods count() and reverse() that make them more substitutable for list objects:

>>> from collections import deque
>>> d = deque('simsalabim')
>>> d.count('s')
2
>>> d.reverse()
>>> d
deque(['m', 'i', 'b', 'a', 'l', 'a', 's', 'm', 'i', 's'])

(Contributed by Raymond Hettinger.)

threading

The threading module has a new Barrier synchronization class for making multiple threads wait until all of them have reached a common barrier point. Barriers are useful for making sure that a task with multiple preconditions does not run until all of the predecessor tasks are complete.

Barriers can work with an arbitrary number of threads. This is a generalization of a Rendezvous [https://en.wikipedia.org/wiki/Synchronous_rendezvous] which is defined for only two threads.

Implemented as a two-phase cyclic barrier, Barrier objects are suitable for use in loops. The separate filling and draining phases assure that all threads get released (drained) before any one of them can loop back and re-enter the barrier. The barrier fully resets after each cycle.

Example of using barriers:

from threading import Barrier, Thread

def get_votes(site):
    ballots = conduct_election(site)
    all_polls_closed.wait()        # do not count until all polls are closed
    totals = summarize(ballots)
    publish(site, totals)

all_polls_closed = Barrier(len(sites))
for site in sites:
    Thread(target=get_votes, args=(site,)).start()

In this example, the barrier enforces a rule that votes cannot be counted at any polling site until all polls are closed. Notice how a solution with a barrier is similar to one with threading.Thread.join(), but the threads stay alive and continue to do work (summarizing ballots) after the barrier point is crossed.

If any of the predecessor tasks can hang or be delayed, a barrier can be created with an optional timeout parameter. Then if the timeout period elapses before all the predecessor tasks reach the barrier point, all waiting threads are released and a BrokenBarrierError exception is raised:

def get_votes(site):
    ballots = conduct_election(site)
    try:
        all_polls_closed.wait(timeout=midnight - time.now())
    except BrokenBarrierError:
        lockbox = seal_ballots(ballots)
        queue.put(lockbox)
    else:
        totals = summarize(ballots)
        publish(site, totals)

In this example, the barrier enforces a more robust rule. If some election sites do not finish before midnight, the barrier times-out and the ballots are sealed and deposited in a queue for later handling.

See Barrier Synchronization Patterns [http://osl.cs.illinois.edu/media/papers/karmani-2009-barrier_synchronization_pattern.pdf] for more examples of how barriers can be used in parallel computing. Also, there is a simple but thorough explanation of barriers in The Little Book of Semaphores [https://greenteapress.com/semaphores/LittleBookOfSemaphores.pdf], section 3.6.

(Contributed by Kristján Valur Jónsson with an API review by Jeffrey Yasskin in bpo-8777 [https://bugs.python.org/issue?@action=redirect&bpo=8777].)

datetime and time

The datetime module has a new type timezone that implements the tzinfo interface by returning a fixed UTC offset and timezone name. This makes it easier to create timezone-aware datetime objects:

>>> from datetime import datetime, timezone

>>> datetime.now(timezone.utc)
datetime.datetime(2010, 12, 8, 21, 4, 2, 923754, tzinfo=datetime.timezone.utc)

>>> datetime.strptime("01/01/2000 12:00 +0000", "%m/%d/%Y %H:%M %z")
datetime.datetime(2000, 1, 1, 12, 0, tzinfo=datetime.timezone.utc)

Also, timedelta objects can now be multiplied by float and divided by float and int objects. And timedelta objects can now divide one another.

The datetime.date.strftime() method is no longer restricted to years after 1900. The new supported year range is from 1000 to 9999 inclusive.

Whenever a two-digit year is used in a time tuple, the interpretation has been governed by time.accept2dyear. The default is True which means that for a two-digit year, the century is guessed according to the POSIX rules governing the %y strptime format.

Starting with Py3.2, use of the century guessing heuristic will emit a DeprecationWarning. Instead, it is recommended that time.accept2dyear be set to False so that large date ranges can be used without guesswork:

>>> import time, warnings
>>> warnings.resetwarnings()      # remove the default warning filters

>>> time.accept2dyear = True      # guess whether 11 means 11 or 2011
>>> time.asctime((11, 1, 1, 12, 34, 56, 4, 1, 0))
Warning (from warnings module):
  ...
DeprecationWarning: Century info guessed for a 2-digit year.
'Fri Jan  1 12:34:56 2011'

>>> time.accept2dyear = False     # use the full range of allowable dates
>>> time.asctime((11, 1, 1, 12, 34, 56, 4, 1, 0))
'Fri Jan  1 12:34:56 11'

Several functions now have significantly expanded date ranges. When time.accept2dyear is false, the time.asctime() function will accept any year that fits in a C int, while the time.mktime() and time.strftime() functions will accept the full range supported by the corresponding operating system functions.

(Contributed by Alexander Belopolsky and Victor Stinner in bpo-1289118 [https://bugs.python.org/issue?@action=redirect&bpo=1289118], bpo-5094 [https://bugs.python.org/issue?@action=redirect&bpo=5094], bpo-6641 [https://bugs.python.org/issue?@action=redirect&bpo=6641], bpo-2706 [https://bugs.python.org/issue?@action=redirect&bpo=2706], bpo-1777412 [https://bugs.python.org/issue?@action=redirect&bpo=1777412], bpo-8013 [https://bugs.python.org/issue?@action=redirect&bpo=8013], and bpo-10827 [https://bugs.python.org/issue?@action=redirect&bpo=10827].)

math

The math module has been updated with six new functions inspired by the C99 standard.

The isfinite() function provides a reliable and fast way to detect special values. It returns True for regular numbers and False for Nan or Infinity:

>>> from math import isfinite
>>> [isfinite(x) for x in (123, 4.56, float('Nan'), float('Inf'))]
[True, True, False, False]

The expm1() function computes e**x-1 for small values of x without incurring the loss of precision that usually accompanies the subtraction of nearly equal quantities:

>>> from math import expm1
>>> expm1(0.013671875)   # more accurate way to compute e**x-1 for a small x
0.013765762467652909

The erf() function computes a probability integral or Gaussian error function [https://en.wikipedia.org/wiki/Error_function]. The complementary error function, erfc(), is 1 - erf(x):

>>> from math import erf, erfc, sqrt
>>> erf(1.0/sqrt(2.0))   # portion of normal distribution within 1 standard deviation
0.682689492137086
>>> erfc(1.0/sqrt(2.0))  # portion of normal distribution outside 1 standard deviation
0.31731050786291404
>>> erf(1.0/sqrt(2.0)) + erfc(1.0/sqrt(2.0))
1.0

The gamma() function is a continuous extension of the factorial function. See https://en.wikipedia.org/wiki/Gamma_function for details. Because the function is related to factorials, it grows large even for small values of x, so there is also a lgamma() function for computing the natural logarithm of the gamma function:

>>> from math import gamma, lgamma
>>> gamma(7.0)           # six factorial
720.0
>>> lgamma(801.0)        # log(800 factorial)
4551.950730698041

(Contributed by Mark Dickinson.)

abc

The abc module now supports abstractclassmethod() and abstractstaticmethod().

These tools make it possible to define an abstract base class that requires a particular classmethod() or staticmethod() to be implemented:

class Temperature(metaclass=abc.ABCMeta):
    @abc.abstractclassmethod
    def from_fahrenheit(cls, t):
        ...
    @abc.abstractclassmethod
    def from_celsius(cls, t):
        ...

(Patch submitted by Daniel Urban; bpo-5867 [https://bugs.python.org/issue?@action=redirect&bpo=5867].)

io

The io.BytesIO has a new method, getbuffer(), which provides functionality similar to memoryview(). It creates an editable view of the data without making a copy. The buffer’s random access and support for slice notation are well-suited to in-place editing:

>>> REC_LEN, LOC_START, LOC_LEN = 34, 7, 11

>>> def change_location(buffer, record_number, location):
...     start = record_number * REC_LEN + LOC_START
...     buffer[start: start+LOC_LEN] = location

>>> import io

>>> byte_stream = io.BytesIO(
...     b'G3805  storeroom  Main chassis    '
...     b'X7899  shipping   Reserve cog     '
...     b'L6988  receiving  Primary sprocket'
... )
>>> buffer = byte_stream.getbuffer()
>>> change_location(buffer, 1, b'warehouse  ')
>>> change_location(buffer, 0, b'showroom   ')
>>> print(byte_stream.getvalue())
b'G3805  showroom   Main chassis    '
b'X7899  warehouse  Reserve cog     '
b'L6988  receiving  Primary sprocket'

(Contributed by Antoine Pitrou in bpo-5506 [https://bugs.python.org/issue?@action=redirect&bpo=5506].)

reprlib

When writing a __repr__() method for a custom container, it is easy to forget to handle the case where a member refers back to the container itself. Python’s builtin objects such as list and set handle self-reference by displaying “…” in the recursive part of the representation string.

To help write such __repr__() methods, the reprlib module has a new decorator, recursive_repr(), for detecting recursive calls to __repr__() and substituting a placeholder string instead:

>>> class MyList(list):
...     @recursive_repr()
...     def __repr__(self):
...         return '<' + '|'.join(map(repr, self)) + '>'
...
>>> m = MyList('abc')
>>> m.append(m)
>>> m.append('x')
>>> print(m)
<'a'|'b'|'c'|...|'x'>

(Contributed by Raymond Hettinger in bpo-9826 [https://bugs.python.org/issue?@action=redirect&bpo=9826] and bpo-9840 [https://bugs.python.org/issue?@action=redirect&bpo=9840].)

logging

In addition to dictionary-based configuration described above, the logging package has many other improvements.

The logging documentation has been augmented by a basic tutorial, an advanced tutorial, and a cookbook of logging recipes. These documents are the fastest way to learn about logging.

The logging.basicConfig() set-up function gained a style argument to support three different types of string formatting. It defaults to “%” for traditional %-formatting, can be set to “{” for the new str.format() style, or can be set to “$” for the shell-style formatting provided by string.Template. The following three configurations are equivalent:

>>> from logging import basicConfig
>>> basicConfig(style='%', format="%(name)s -> %(levelname)s: %(message)s")
>>> basicConfig(style='{', format="{name} -> {levelname} {message}")
>>> basicConfig(style='$', format="$name -> $levelname: $message")

If no configuration is set-up before a logging event occurs, there is now a default configuration using a StreamHandler directed to sys.stderr for events of WARNING level or higher. Formerly, an event occurring before a configuration was set-up would either raise an exception or silently drop the event depending on the value of logging.raiseExceptions. The new default handler is stored in logging.lastResort.

The use of filters has been simplified. Instead of creating a Filter object, the predicate can be any Python callable that returns True or False.

There were a number of other improvements that add flexibility and simplify configuration. See the module documentation for a full listing of changes in Python 3.2.

csv

The csv module now supports a new dialect, unix_dialect, which applies quoting for all fields and a traditional Unix style with '\n' as the line terminator. The registered dialect name is unix.

The csv.DictWriter has a new method, writeheader() for writing-out an initial row to document the field names:

>>> import csv, sys
>>> w = csv.DictWriter(sys.stdout, ['name', 'dept'], dialect='unix')
>>> w.writeheader()
"name","dept"
>>> w.writerows([
...     {'name': 'tom', 'dept': 'accounting'},
...     {'name': 'susan', 'dept': 'Salesl'}])
"tom","accounting"
"susan","sales"

(New dialect suggested by Jay Talbot in bpo-5975 [https://bugs.python.org/issue?@action=redirect&bpo=5975], and the new method suggested by Ed Abraham in bpo-1537721 [https://bugs.python.org/issue?@action=redirect&bpo=1537721].)

contextlib

There is a new and slightly mind-blowing tool ContextDecorator that is helpful for creating a context manager that does double duty as a function decorator.

As a convenience, this new functionality is used by contextmanager() so that no extra effort is needed to support both roles.

The basic idea is that both context managers and function decorators can be used for pre-action and post-action wrappers. Context managers wrap a group of statements using a with statement, and function decorators wrap a group of statements enclosed in a function. So, occasionally there is a need to write a pre-action or post-action wrapper that can be used in either role.

For example, it is sometimes useful to wrap functions or groups of statements with a logger that can track the time of entry and time of exit. Rather than writing both a function decorator and a context manager for the task, the contextmanager() provides both capabilities in a single definition:

from contextlib import contextmanager
import logging

logging.basicConfig(level=logging.INFO)

@contextmanager
def track_entry_and_exit(name):
    logging.info('Entering: %s', name)
    yield
    logging.info('Exiting: %s', name)

Formerly, this would have only been usable as a context manager:

with track_entry_and_exit('widget loader'):
    print('Some time consuming activity goes here')
    load_widget()

Now, it can be used as a decorator as well:

@track_entry_and_exit('widget loader')
def activity():
    print('Some time consuming activity goes here')
    load_widget()

Trying to fulfill two roles at once places some limitations on the technique. Context managers normally have the flexibility to return an argument usable by a with statement, but there is no parallel for function decorators.

In the above example, there is not a clean way for the track_entry_and_exit context manager to return a logging instance for use in the body of enclosed statements.

(Contributed by Michael Foord in bpo-9110 [https://bugs.python.org/issue?@action=redirect&bpo=9110].)

decimal and fractions

Mark Dickinson crafted an elegant and efficient scheme for assuring that different numeric datatypes will have the same hash value whenever their actual values are equal (bpo-8188 [https://bugs.python.org/issue?@action=redirect&bpo=8188]):

assert hash(Fraction(3, 2)) == hash(1.5) == \
       hash(Decimal("1.5")) == hash(complex(1.5, 0))

Some of the hashing details are exposed through a new attribute, sys.hash_info, which describes the bit width of the hash value, the prime modulus, the hash values for infinity and nan, and the multiplier used for the imaginary part of a number:

>>> sys.hash_info
sys.hash_info(width=64, modulus=2305843009213693951, inf=314159, nan=0, imag=1000003)

An early decision to limit the inter-operability of various numeric types has been relaxed. It is still unsupported (and ill-advised) to have implicit mixing in arithmetic expressions such as Decimal('1.1') + float('1.1') because the latter loses information in the process of constructing the binary float. However, since existing floating point value can be converted losslessly to either a decimal or rational representation, it makes sense to add them to the constructor and to support mixed-type comparisons.

The decimal.Decimal constructor now accepts float objects directly so there in no longer a need to use the from_float() method (bpo-8257 [https://bugs.python.org/issue?@action=redirect&bpo=8257]).

Mixed type comparisons are now fully supported so that Decimal objects can be directly compared with float and fractions.Fraction (bpo-2531 [https://bugs.python.org/issue?@action=redirect&bpo=2531] and bpo-8188 [https://bugs.python.org/issue?@action=redirect&bpo=8188]).

Similar changes were made to fractions.Fraction so that the from_float() and from_decimal() methods are no longer needed (bpo-8294 [https://bugs.python.org/issue?@action=redirect&bpo=8294]):

>>> from decimal import Decimal
>>> from fractions import Fraction
>>> Decimal(1.1)
Decimal('1.100000000000000088817841970012523233890533447265625')
>>> Fraction(1.1)
Fraction(2476979795053773, 2251799813685248)

Another useful change for the decimal module is that the Context.clamp attribute is now public. This is useful in creating contexts that correspond to the decimal interchange formats specified in IEEE 754 (see bpo-8540 [https://bugs.python.org/issue?@action=redirect&bpo=8540]).

(Contributed by Mark Dickinson and Raymond Hettinger.)

ftp

The ftplib.FTP class now supports the context management protocol to unconditionally consume socket.error exceptions and to close the FTP connection when done:

>>> from ftplib import FTP
>>> with FTP("ftp1.at.proftpd.org") as ftp:
        ftp.login()
        ftp.dir()

'230 Anonymous login ok, restrictions apply.'
dr-xr-xr-x   9 ftp      ftp           154 May  6 10:43 .
dr-xr-xr-x   9 ftp      ftp           154 May  6 10:43 ..
dr-xr-xr-x   5 ftp      ftp          4096 May  6 10:43 CentOS
dr-xr-xr-x   3 ftp      ftp            18 Jul 10  2008 Fedora

Other file-like objects such as mmap.mmap and fileinput.input() also grew auto-closing context managers:

with fileinput.input(files=('log1.txt', 'log2.txt')) as f:
    for line in f:
        process(line)

(Contributed by Tarek Ziadé and Giampaolo Rodolà in bpo-4972 [https://bugs.python.org/issue?@action=redirect&bpo=4972], and by Georg Brandl in bpo-8046 [https://bugs.python.org/issue?@action=redirect&bpo=8046] and bpo-1286 [https://bugs.python.org/issue?@action=redirect&bpo=1286].)

The FTP_TLS class now accepts a context parameter, which is a ssl.SSLContext object allowing bundling SSL configuration options, certificates and private keys into a single (potentially long-lived) structure.

(Contributed by Giampaolo Rodolà; bpo-8806 [https://bugs.python.org/issue?@action=redirect&bpo=8806].)

popen

The os.popen() and subprocess.Popen() functions now support with statements for auto-closing of the file descriptors.

(Contributed by Antoine Pitrou and Brian Curtin in bpo-7461 [https://bugs.python.org/issue?@action=redirect&bpo=7461] and bpo-10554 [https://bugs.python.org/issue?@action=redirect&bpo=10554].)

select

The select module now exposes a new, constant attribute, PIPE_BUF, which gives the minimum number of bytes which are guaranteed not to block when select.select() says a pipe is ready for writing.

>>> import select
>>> select.PIPE_BUF
512

(Available on Unix systems. Patch by Sébastien Sablé in bpo-9862 [https://bugs.python.org/issue?@action=redirect&bpo=9862])

gzip and zipfile

gzip.GzipFile now implements the io.BufferedIOBase abstract base class (except for truncate()). It also has a peek() method and supports unseekable as well as zero-padded file objects.

The gzip module also gains the compress() and decompress() functions for easier in-memory compression and decompression. Keep in mind that text needs to be encoded as bytes before compressing and decompressing:

>>> import gzip
>>> s = 'Three shall be the number thou shalt count, '
>>> s += 'and the number of the counting shall be three'
>>> b = s.encode()                        # convert to utf-8
>>> len(b)
89
>>> c = gzip.compress(b)
>>> len(c)
77
>>> gzip.decompress(c).decode()[:42]      # decompress and convert to text
'Three shall be the number thou shalt count'

(Contributed by Anand B. Pillai in bpo-3488 [https://bugs.python.org/issue?@action=redirect&bpo=3488]; and by Antoine Pitrou, Nir Aides and Brian Curtin in bpo-9962 [https://bugs.python.org/issue?@action=redirect&bpo=9962], bpo-1675951 [https://bugs.python.org/issue?@action=redirect&bpo=1675951], bpo-7471 [https://bugs.python.org/issue?@action=redirect&bpo=7471] and bpo-2846 [https://bugs.python.org/issue?@action=redirect&bpo=2846].)

Also, the zipfile.ZipExtFile class was reworked internally to represent files stored inside an archive. The new implementation is significantly faster and can be wrapped in an io.BufferedReader object for more speedups. It also solves an issue where interleaved calls to read and readline gave the wrong results.

(Patch submitted by Nir Aides in bpo-7610 [https://bugs.python.org/issue?@action=redirect&bpo=7610].)

tarfile

The TarFile class can now be used as a context manager. In addition, its add() method has a new option, filter, that controls which files are added to the archive and allows the file metadata to be edited.

The new filter option replaces the older, less flexible exclude parameter which is now deprecated. If specified, the optional filter parameter needs to be a keyword argument. The user-supplied filter function accepts a TarInfo object and returns an updated TarInfo object, or if it wants the file to be excluded, the function can return None:

>>> import tarfile, glob

>>> def myfilter(tarinfo):
...     if tarinfo.isfile():             # only save real files
...         tarinfo.uname = 'monty'      # redact the user name
...         return tarinfo

>>> with tarfile.open(name='myarchive.tar.gz', mode='w:gz') as tf:
...     for filename in glob.glob('*.txt'):
...         tf.add(filename, filter=myfilter)
...     tf.list()
-rw-r--r-- monty/501        902 2011-01-26 17:59:11 annotations.txt
-rw-r--r-- monty/501        123 2011-01-26 17:59:11 general_questions.txt
-rw-r--r-- monty/501       3514 2011-01-26 17:59:11 prion.txt
-rw-r--r-- monty/501        124 2011-01-26 17:59:11 py_todo.txt
-rw-r--r-- monty/501       1399 2011-01-26 17:59:11 semaphore_notes.txt

(Proposed by Tarek Ziadé and implemented by Lars Gustäbel in bpo-6856 [https://bugs.python.org/issue?@action=redirect&bpo=6856].)

hashlib

The hashlib module has two new constant attributes listing the hashing algorithms guaranteed to be present in all implementations and those available on the current implementation:

>>> import hashlib

>>> hashlib.algorithms_guaranteed
{'sha1', 'sha224', 'sha384', 'sha256', 'sha512', 'md5'}

>>> hashlib.algorithms_available
{'md2', 'SHA256', 'SHA512', 'dsaWithSHA', 'mdc2', 'SHA224', 'MD4', 'sha256',
'sha512', 'ripemd160', 'SHA1', 'MDC2', 'SHA', 'SHA384', 'MD2',
'ecdsa-with-SHA1','md4', 'md5', 'sha1', 'DSA-SHA', 'sha224',
'dsaEncryption', 'DSA', 'RIPEMD160', 'sha', 'MD5', 'sha384'}

(Suggested by Carl Chenet in bpo-7418 [https://bugs.python.org/issue?@action=redirect&bpo=7418].)

ast

The ast module has a wonderful a general-purpose tool for safely evaluating expression strings using the Python literal syntax. The ast.literal_eval() function serves as a secure alternative to the builtin eval() function which is easily abused. Python 3.2 adds bytes and set literals to the list of supported types: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, and None.

>>> from ast import literal_eval

>>> request = "{'req': 3, 'func': 'pow', 'args': (2, 0.5)}"
>>> literal_eval(request)
{'args': (2, 0.5), 'req': 3, 'func': 'pow'}

>>> request = "os.system('do something harmful')"
>>> literal_eval(request)
Traceback (most recent call last):
  ...
ValueError: malformed node or string: <_ast.Call object at 0x101739a10>

(Implemented by Benjamin Peterson and Georg Brandl.)

os

Different operating systems use various encodings for filenames and environment variables. The os module provides two new functions, fsencode() and fsdecode(), for encoding and decoding filenames:

>>> import os
>>> filename = 'Sehenswürdigkeiten'
>>> os.fsencode(filename)
b'Sehensw\xc3\xbcrdigkeiten'

Some operating systems allow direct access to encoded bytes in the environment. If so, the os.supports_bytes_environ constant will be true.

For direct access to encoded environment variables (if available), use the new os.getenvb() function or use os.environb which is a bytes version of os.environ.

(Contributed by Victor Stinner.)

shutil

The shutil.copytree() function has two new options:

ignore_dangling_symlinks: when symlinks=False so that the function copies a file pointed to by a symlink, not the symlink itself. This option will silence the error raised if the file doesn’t exist.

copy_function: is a callable that will be used to copy files. shutil.copy2() is used by default.

(Contributed by Tarek Ziadé.)

In addition, the shutil module now supports archiving operations for zipfiles, uncompressed tarfiles, gzipped tarfiles, and bzipped tarfiles. And there are functions for registering additional archiving file formats (such as xz compressed tarfiles or custom formats).

The principal functions are make_archive() and unpack_archive(). By default, both operate on the current directory (which can be set by os.chdir()) and on any sub-directories. The archive filename needs to be specified with a full pathname. The archiving step is non-destructive (the original files are left unchanged).

>>> import shutil, pprint

>>> os.chdir('mydata')  # change to the source directory
>>> f = shutil.make_archive('/var/backup/mydata',
...                         'zip')      # archive the current directory
>>> f                                   # show the name of archive
'/var/backup/mydata.zip'
>>> os.chdir('tmp')                     # change to an unpacking
>>> shutil.unpack_archive('/var/backup/mydata.zip')  # recover the data

>>> pprint.pprint(shutil.get_archive_formats())  # display known formats
[('bztar', "bzip2'ed tar-file"),
 ('gztar', "gzip'ed tar-file"),
 ('tar', 'uncompressed tar file'),
 ('zip', 'ZIP file')]

>>> shutil.register_archive_format(     # register a new archive format
...     name='xz',
...     function=xz.compress,           # callable archiving function
...     extra_args=[('level', 8)],      # arguments to the function
...     description='xz compression'
... )

(Contributed by Tarek Ziadé.)

sqlite3

The sqlite3 module was updated to pysqlite version 2.6.0. It has two new capabilities.

The sqlite3.Connection.in_transit attribute is true if there is an active transaction for uncommitted changes.

The sqlite3.Connection.enable_load_extension() and sqlite3.Connection.load_extension() methods allows you to load SQLite extensions from “.so” files. One well-known extension is the fulltext-search extension distributed with SQLite.

(Contributed by R. David Murray and Shashwat Anand; bpo-8845 [https://bugs.python.org/issue?@action=redirect&bpo=8845].)

html

A new html module was introduced with only a single function, escape(), which is used for escaping reserved characters from HTML markup:

>>> import html
>>> html.escape('x > 2 && x < 7')
'x &gt; 2 &amp;&amp; x &lt; 7'

socket

The socket module has two new improvements.

Socket objects now have a detach() method which puts the socket into closed state without actually closing the underlying file descriptor. The latter can then be reused for other purposes. (Added by Antoine Pitrou; bpo-8524 [https://bugs.python.org/issue?@action=redirect&bpo=8524].)

socket.create_connection() now supports the context management protocol to unconditionally consume socket.error exceptions and to close the socket when done. (Contributed by Giampaolo Rodolà; bpo-9794 [https://bugs.python.org/issue?@action=redirect&bpo=9794].)

ssl

The ssl module added a number of features to satisfy common requirements for secure (encrypted, authenticated) internet connections:

A new class, SSLContext, serves as a container for persistent SSL data, such as protocol settings, certificates, private keys, and various other options. It includes a wrap_socket() for creating an SSL socket from an SSL context.

A new function, ssl.match_hostname(), supports server identity verification for higher-level protocols by implementing the rules of HTTPS (from RFC 2818 [https://tools.ietf.org/html/rfc2818.html]) which are also suitable for other protocols.

The ssl.wrap_socket() constructor function now takes a ciphers argument. The ciphers string lists the allowed encryption algorithms using the format described in the OpenSSL documentation [https://www.openssl.org/docs/manmaster/man1/ciphers.html#CIPHER-LIST-FORMAT].

When linked against recent versions of OpenSSL, the ssl module now supports the Server Name Indication extension to the TLS protocol, allowing multiple “virtual hosts” using different certificates on a single IP port. This extension is only supported in client mode, and is activated by passing the server_hostname argument to ssl.SSLContext.wrap_socket().

Various options have been added to the ssl module, such as OP_NO_SSLv2 which disables the insecure and obsolete SSLv2 protocol.

The extension now loads all the OpenSSL ciphers and digest algorithms. If some SSL certificates cannot be verified, they are reported as an “unknown algorithm” error.

The version of OpenSSL being used is now accessible using the module attributes ssl.OPENSSL_VERSION (a string), ssl.OPENSSL_VERSION_INFO (a 5-tuple), and ssl.OPENSSL_VERSION_NUMBER (an integer).

(Contributed by Antoine Pitrou in bpo-8850 [https://bugs.python.org/issue?@action=redirect&bpo=8850], bpo-1589 [https://bugs.python.org/issue?@action=redirect&bpo=1589], bpo-8322 [https://bugs.python.org/issue?@action=redirect&bpo=8322], bpo-5639 [https://bugs.python.org/issue?@action=redirect&bpo=5639], bpo-4870 [https://bugs.python.org/issue?@action=redirect&bpo=4870], bpo-8484 [https://bugs.python.org/issue?@action=redirect&bpo=8484], and bpo-8321 [https://bugs.python.org/issue?@action=redirect&bpo=8321].)

nntp

The nntplib module has a revamped implementation with better bytes and text semantics as well as more practical APIs. These improvements break compatibility with the nntplib version in Python 3.1, which was partly dysfunctional in itself.

Support for secure connections through both implicit (using nntplib.NNTP_SSL) and explicit (using nntplib.NNTP.starttls()) TLS has also been added.

(Contributed by Antoine Pitrou in bpo-9360 [https://bugs.python.org/issue?@action=redirect&bpo=9360] and Andrew Vant in bpo-1926 [https://bugs.python.org/issue?@action=redirect&bpo=1926].)

certificates

http.client.HTTPSConnection, urllib.request.HTTPSHandler and urllib.request.urlopen() now take optional arguments to allow for server certificate checking against a set of Certificate Authorities, as recommended in public uses of HTTPS.

(Added by Antoine Pitrou, bpo-9003 [https://bugs.python.org/issue?@action=redirect&bpo=9003].)

imaplib

Support for explicit TLS on standard IMAP4 connections has been added through the new imaplib.IMAP4.starttls method.

(Contributed by Lorenzo M. Catucci and Antoine Pitrou, bpo-4471 [https://bugs.python.org/issue?@action=redirect&bpo=4471].)

http.client

There were a number of small API improvements in the http.client module. The old-style HTTP 0.9 simple responses are no longer supported and the strict parameter is deprecated in all classes.

The HTTPConnection and HTTPSConnection classes now have a source_address parameter for a (host, port) tuple indicating where the HTTP connection is made from.

Support for certificate checking and HTTPS virtual hosts were added to HTTPSConnection.

The request() method on connection objects allowed an optional body argument so that a file object could be used to supply the content of the request. Conveniently, the body argument now also accepts an iterable object so long as it includes an explicit Content-Length header. This extended interface is much more flexible than before.

To establish an HTTPS connection through a proxy server, there is a new set_tunnel() method that sets the host and port for HTTP Connect tunneling.

To match the behavior of http.server, the HTTP client library now also encodes headers with ISO-8859-1 (Latin-1) encoding. It was already doing that for incoming headers, so now the behavior is consistent for both incoming and outgoing traffic. (See work by Armin Ronacher in bpo-10980 [https://bugs.python.org/issue?@action=redirect&bpo=10980].)

unittest

The unittest module has a number of improvements supporting test discovery for packages, easier experimentation at the interactive prompt, new testcase methods, improved diagnostic messages for test failures, and better method names.

The command-line call python -m unittest can now accept file paths instead of module names for running specific tests (bpo-10620 [https://bugs.python.org/issue?@action=redirect&bpo=10620]). The new test discovery can find tests within packages, locating any test importable from the top-level directory. The top-level directory can be specified with the -t option, a pattern for matching files with -p, and a directory to start discovery with -s:

$ python -m unittest discover -s my_proj_dir -p _test.py

(Contributed by Michael Foord.)

Experimentation at the interactive prompt is now easier because the unittest.case.TestCase class can now be instantiated without arguments:

>>> from unittest import TestCase
>>> TestCase().assertEqual(pow(2, 3), 8)

(Contributed by Michael Foord.)

The unittest module has two new methods, assertWarns() and assertWarnsRegex() to verify that a given warning type is triggered by the code under test:

with self.assertWarns(DeprecationWarning):
    legacy_function('XYZ')

(Contributed by Antoine Pitrou, bpo-9754 [https://bugs.python.org/issue?@action=redirect&bpo=9754].)

Another new method, assertCountEqual() is used to compare two iterables to determine if their element counts are equal (whether the same elements are present with the same number of occurrences regardless of order):

def test_anagram(self):
    self.assertCountEqual('algorithm', 'logarithm')

(Contributed by Raymond Hettinger.)

A principal feature of the unittest module is an effort to produce meaningful diagnostics when a test fails. When possible, the failure is recorded along with a diff of the output. This is especially helpful for analyzing log files of failed test runs. However, since diffs can sometime be voluminous, there is a new maxDiff attribute that sets maximum length of diffs displayed.

In addition, the method names in the module have undergone a number of clean-ups.

For example, assertRegex() is the new name for assertRegexpMatches() which was misnamed because the test uses re.search(), not re.match(). Other methods using regular expressions are now named using short form “Regex” in preference to “Regexp” – this matches the names used in other unittest implementations, matches Python’s old name for the re module, and it has unambiguous camel-casing.

(Contributed by Raymond Hettinger and implemented by Ezio Melotti.)

To improve consistency, some long-standing method aliases are being deprecated in favor of the preferred names:

Old Name

Preferred Name

assert_()

assertTrue()

assertEquals()

assertEqual()

assertNotEquals()

assertNotEqual()

assertAlmostEquals()

assertAlmostEqual()

assertNotAlmostEquals()

assertNotAlmostEqual()

Likewise, the TestCase.fail* methods deprecated in Python 3.1 are expected to be removed in Python 3.3. Also see the 폐지된 에일리어스 section in the unittest documentation.

(Contributed by Ezio Melotti; bpo-9424 [https://bugs.python.org/issue?@action=redirect&bpo=9424].)

The assertDictContainsSubset() method was deprecated because it was misimplemented with the arguments in the wrong order. This created hard-to-debug optical illusions where tests like TestCase().assertDictContainsSubset({'a':1, 'b':2}, {'a':1}) would fail.

(Contributed by Raymond Hettinger.)

random

The integer methods in the random module now do a better job of producing uniform distributions. Previously, they computed selections with int(n*random()) which had a slight bias whenever n was not a power of two. Now, multiple selections are made from a range up to the next power of two and a selection is kept only when it falls within the range 0 <= x < n. The functions and methods affected are randrange(), randint(), choice(), shuffle() and sample().

(Contributed by Raymond Hettinger; bpo-9025 [https://bugs.python.org/issue?@action=redirect&bpo=9025].)

poplib

POP3_SSL class now accepts a context parameter, which is a ssl.SSLContext object allowing bundling SSL configuration options, certificates and private keys into a single (potentially long-lived) structure.

(Contributed by Giampaolo Rodolà; bpo-8807 [https://bugs.python.org/issue?@action=redirect&bpo=8807].)

asyncore

asyncore.dispatcher now provides a handle_accepted() method returning a (sock, addr) pair which is called when a connection has actually been established with a new remote endpoint. This is supposed to be used as a replacement for old handle_accept() and avoids the user to call accept() directly.

(Contributed by Giampaolo Rodolà; bpo-6706 [https://bugs.python.org/issue?@action=redirect&bpo=6706].)

tempfile

The tempfile module has a new context manager, TemporaryDirectory which provides easy deterministic cleanup of temporary directories:

with tempfile.TemporaryDirectory() as tmpdirname:
    print('created temporary dir:', tmpdirname)

(Contributed by Neil Schemenauer and Nick Coghlan; bpo-5178 [https://bugs.python.org/issue?@action=redirect&bpo=5178].)

inspect

The inspect module has a new function getgeneratorstate() to easily identify the current state of a generator-iterator:

>>> from inspect import getgeneratorstate
>>> def gen():
...     yield 'demo'
>>> g = gen()
>>> getgeneratorstate(g)
'GEN_CREATED'
>>> next(g)
'demo'
>>> getgeneratorstate(g)
'GEN_SUSPENDED'
>>> next(g, None)
>>> getgeneratorstate(g)
'GEN_CLOSED'

(Contributed by Rodolpho Eckhardt and Nick Coghlan, bpo-10220 [https://bugs.python.org/issue?@action=redirect&bpo=10220].)

To support lookups without the possibility of activating a dynamic attribute, the inspect module has a new function, getattr_static(). Unlike hasattr(), this is a true read-only search, guaranteed not to change state while it is searching:

>>> class A:
...     @property
...     def f(self):
...         print('Running')
...         return 10
...
>>> a = A()
>>> getattr(a, 'f')
Running
10
>>> inspect.getattr_static(a, 'f')
<property object at 0x1022bd788>

(Contributed by Michael Foord.)

pydoc

The pydoc module now provides a much-improved Web server interface, as well as a new command-line option -b to automatically open a browser window to display that server:

$ pydoc3.2 -b

(Contributed by Ron Adam; bpo-2001 [https://bugs.python.org/issue?@action=redirect&bpo=2001].)

dis

The dis module gained two new functions for inspecting code, code_info() and show_code(). Both provide detailed code object information for the supplied function, method, source code string or code object. The former returns a string and the latter prints it:

>>> import dis, random
>>> dis.show_code(random.choice)
Name:              choice
Filename:          /Library/Frameworks/Python.framework/Versions/3.2/lib/python3.2/random.py
Argument count:    2
Kw-only arguments: 0
Number of locals:  3
Stack size:        11
Flags:             OPTIMIZED, NEWLOCALS, NOFREE
Constants:
   0: 'Choose a random element from a non-empty sequence.'
   1: 'Cannot choose from an empty sequence'
Names:
   0: _randbelow
   1: len
   2: ValueError
   3: IndexError
Variable names:
   0: self
   1: seq
   2: i

In addition, the dis() function now accepts string arguments so that the common idiom dis(compile(s, '', 'eval')) can be shortened to dis(s):

>>> dis('3*x+1 if x%2==1 else x//2')
  1           0 LOAD_NAME                0 (x)
              3 LOAD_CONST               0 (2)
              6 BINARY_MODULO
              7 LOAD_CONST               1 (1)
             10 COMPARE_OP               2 (==)
             13 POP_JUMP_IF_FALSE       28
             16 LOAD_CONST               2 (3)
             19 LOAD_NAME                0 (x)
             22 BINARY_MULTIPLY
             23 LOAD_CONST               1 (1)
             26 BINARY_ADD
             27 RETURN_VALUE
        >>   28 LOAD_NAME                0 (x)
             31 LOAD_CONST               0 (2)
             34 BINARY_FLOOR_DIVIDE
             35 RETURN_VALUE

Taken together, these improvements make it easier to explore how CPython is implemented and to see for yourself what the language syntax does under-the-hood.

(Contributed by Nick Coghlan in bpo-9147 [https://bugs.python.org/issue?@action=redirect&bpo=9147].)

dbm

All database modules now support the get() and setdefault() methods.

(Suggested by Ray Allen in bpo-9523 [https://bugs.python.org/issue?@action=redirect&bpo=9523].)

ctypes

A new type, ctypes.c_ssize_t represents the C ssize_t datatype.

site

The site module has three new functions useful for reporting on the details of a given Python installation.

getsitepackages() lists all global site-packages directories.

getuserbase() reports on the user’s base directory where data can be stored.

getusersitepackages() reveals the user-specific site-packages directory path.

>>> import site
>>> site.getsitepackages()
['/Library/Frameworks/Python.framework/Versions/3.2/lib/python3.2/site-packages',
 '/Library/Frameworks/Python.framework/Versions/3.2/lib/site-python',
 '/Library/Python/3.2/site-packages']
>>> site.getuserbase()
'/Users/raymondhettinger/Library/Python/3.2'
>>> site.getusersitepackages()
'/Users/raymondhettinger/Library/Python/3.2/lib/python/site-packages'

Conveniently, some of site’s functionality is accessible directly from the command-line:

$ python -m site --user-base
/Users/raymondhettinger/.local
$ python -m site --user-site
/Users/raymondhettinger/.local/lib/python3.2/site-packages

(Contributed by Tarek Ziadé in bpo-6693 [https://bugs.python.org/issue?@action=redirect&bpo=6693].)

sysconfig

The new sysconfig module makes it straightforward to discover installation paths and configuration variables that vary across platforms and installations.

The module offers access simple access functions for platform and version information:

get_platform() returning values like linux-i586 or macosx-10.6-ppc.

get_python_version() returns a Python version string such as “3.2”.

It also provides access to the paths and variables corresponding to one of seven named schemes used by distutils. Those include posix_prefix, posix_home, posix_user, nt, nt_user, os2, os2_home:

get_paths() makes a dictionary containing installation paths for the current installation scheme.

get_config_vars() returns a dictionary of platform specific variables.

There is also a convenient command-line interface:

C:\Python32>python -m sysconfig
Platform: "win32"
Python version: "3.2"
Current installation scheme: "nt"

Paths:
        data = "C:\Python32"
        include = "C:\Python32\Include"
        platinclude = "C:\Python32\Include"
        platlib = "C:\Python32\Lib\site-packages"
        platstdlib = "C:\Python32\Lib"
        purelib = "C:\Python32\Lib\site-packages"
        scripts = "C:\Python32\Scripts"
        stdlib = "C:\Python32\Lib"

Variables:
        BINDIR = "C:\Python32"
        BINLIBDEST = "C:\Python32\Lib"
        EXE = ".exe"
        INCLUDEPY = "C:\Python32\Include"
        LIBDEST = "C:\Python32\Lib"
        SO = ".pyd"
        VERSION = "32"
        abiflags = ""
        base = "C:\Python32"
        exec_prefix = "C:\Python32"
        platbase = "C:\Python32"
        prefix = "C:\Python32"
        projectbase = "C:\Python32"
        py_version = "3.2"
        py_version_nodot = "32"
        py_version_short = "3.2"
        srcdir = "C:\Python32"
        userbase = "C:\Documents and Settings\Raymond\Application Data\Python"

(Moved out of Distutils by Tarek Ziadé.)

pdb

The pdb debugger module gained a number of usability improvements:

pdb.py now has a -c option that executes commands as given in a .pdbrc script file.

A .pdbrc script file can contain continue and next commands that continue debugging.

The Pdb class constructor now accepts a nosigint argument.

New commands: l(list), ll(long list) and source for listing source code.

New commands: display and undisplay for showing or hiding the value of an expression if it has changed.

New command: interact for starting an interactive interpreter containing the global and local names found in the current scope.

Breakpoints can be cleared by breakpoint number.

(Contributed by Georg Brandl, Antonio Cuni and Ilya Sandler.)

configparser

The configparser module was modified to improve usability and predictability of the default parser and its supported INI syntax. The old ConfigParser class was removed in favor of SafeConfigParser which has in turn been renamed to ConfigParser. Support for inline comments is now turned off by default and section or option duplicates are not allowed in a single configuration source.

Config parsers gained a new API based on the mapping protocol:

>>> parser = ConfigParser()
>>> parser.read_string("""
... [DEFAULT]
... location = upper left
... visible = yes
... editable = no
... color = blue
...
... [main]
... title = Main Menu
... color = green
...
... [options]
... title = Options
... """)
>>> parser['main']['color']
'green'
>>> parser['main']['editable']
'no'
>>> section = parser['options']
>>> section['title']
'Options'
>>> section['title'] = 'Options (editable: %(editable)s)'
>>> section['title']
'Options (editable: no)'

The new API is implemented on top of the classical API, so custom parser subclasses should be able to use it without modifications.

The INI file structure accepted by config parsers can now be customized. Users can specify alternative option/value delimiters and comment prefixes, change the name of the DEFAULT section or switch the interpolation syntax.

There is support for pluggable interpolation including an additional interpolation handler ExtendedInterpolation:

>>> parser = ConfigParser(interpolation=ExtendedInterpolation())
>>> parser.read_dict({'buildout': {'directory': '/home/ambv/zope9'},
...                   'custom': {'prefix': '/usr/local'}})
>>> parser.read_string("""
... [buildout]
... parts =
...   zope9
...   instance
... find-links =
...   ${buildout:directory}/downloads/dist
...
... [zope9]
... recipe = plone.recipe.zope9install
... location = /opt/zope
...
... [instance]
... recipe = plone.recipe.zope9instance
... zope9-location = ${zope9:location}
... zope-conf = ${custom:prefix}/etc/zope.conf
... """)
>>> parser['buildout']['find-links']
'\n/home/ambv/zope9/downloads/dist'
>>> parser['instance']['zope-conf']
'/usr/local/etc/zope.conf'
>>> instance = parser['instance']
>>> instance['zope-conf']
'/usr/local/etc/zope.conf'
>>> instance['zope9-location']
'/opt/zope'

A number of smaller features were also introduced, like support for specifying encoding in read operations, specifying fallback values for get-functions, or reading directly from dictionaries and strings.

(All changes contributed by Łukasz Langa.)

urllib.parse

A number of usability improvements were made for the urllib.parse module.

The urlparse() function now supports IPv6 [https://en.wikipedia.org/wiki/IPv6] addresses as described in RFC 2732 [https://tools.ietf.org/html/rfc2732.html]:

>>> import urllib.parse
>>> urllib.parse.urlparse('http://[dead:beef:cafe:5417:affe:8FA3:deaf:feed]/foo/')
ParseResult(scheme='http',
            netloc='[dead:beef:cafe:5417:affe:8FA3:deaf:feed]',
            path='/foo/',
            params='',
            query='',
            fragment='')

The urldefrag() function now returns a named tuple:

>>> r = urllib.parse.urldefrag('http://python.org/about/#target')
>>> r
DefragResult(url='http://python.org/about/', fragment='target')
>>> r[0]
'http://python.org/about/'
>>> r.fragment
'target'

And, the urlencode() function is now much more flexible, accepting either a string or bytes type for the query argument. If it is a string, then the safe, encoding, and error parameters are sent to quote_plus() for encoding:

>>> urllib.parse.urlencode([
...      ('type', 'telenovela'),
...      ('name', '¿Dónde Está Elisa?')],
...      encoding='latin-1')
'type=telenovela&name=%BFD%F3nde+Est%E1+Elisa%3F'

As detailed in Parsing ASCII Encoded Bytes, all the urllib.parse functions now accept ASCII-encoded byte strings as input, so long as they are not mixed with regular strings. If ASCII-encoded byte strings are given as parameters, the return types will also be an ASCII-encoded byte strings:

>>> urllib.parse.urlparse(b'http://www.python.org:80/about/')
ParseResultBytes(scheme=b'http', netloc=b'www.python.org:80',
                 path=b'/about/', params=b'', query=b'', fragment=b'')

(Work by Nick Coghlan, Dan Mahn, and Senthil Kumaran in bpo-2987 [https://bugs.python.org/issue?@action=redirect&bpo=2987], bpo-5468 [https://bugs.python.org/issue?@action=redirect&bpo=5468], and bpo-9873 [https://bugs.python.org/issue?@action=redirect&bpo=9873].)

mailbox

Thanks to a concerted effort by R. David Murray, the mailbox module has been fixed for Python 3.2. The challenge was that mailbox had been originally designed with a text interface, but email messages are best represented with bytes because various parts of a message may have different encodings.

The solution harnessed the email package’s binary support for parsing arbitrary email messages. In addition, the solution required a number of API changes.

As expected, the add() method for mailbox.Mailbox objects now accepts binary input.

StringIO and text file input are deprecated. Also, string input will fail early if non-ASCII characters are used. Previously it would fail when the email was processed in a later step.

There is also support for binary output. The get_file() method now returns a file in the binary mode (where it used to incorrectly set the file to text-mode). There is also a new get_bytes() method that returns a bytes representation of a message corresponding to a given key.

It is still possible to get non-binary output using the old API’s get_string() method, but that approach is not very useful. Instead, it is best to extract messages from a Message object or to load them from binary input.

(Contributed by R. David Murray, with efforts from Steffen Daode Nurpmeso and an initial patch by Victor Stinner in bpo-9124 [https://bugs.python.org/issue?@action=redirect&bpo=9124].)

turtledemo

The demonstration code for the turtle module was moved from the Demo directory to main library. It includes over a dozen sample scripts with lively displays. Being on sys.path, it can now be run directly from the command-line:

$ python -m turtledemo

(Moved from the Demo directory by Alexander Belopolsky in bpo-10199 [https://bugs.python.org/issue?@action=redirect&bpo=10199].)

Multi-threading

The mechanism for serializing execution of concurrently running Python threads (generally known as the GIL or Global Interpreter Lock) has been rewritten. Among the objectives were more predictable switching intervals and reduced overhead due to lock contention and the number of ensuing system calls. The notion of a “check interval” to allow thread switches has been abandoned and replaced by an absolute duration expressed in seconds. This parameter is tunable through sys.setswitchinterval(). It currently defaults to 5 milliseconds.

Additional details about the implementation can be read from a python-dev mailing-list message [https://mail.python.org/pipermail/python-dev/2009-October/093321.html] (however, “priority requests” as exposed in this message have not been kept for inclusion).

(Contributed by Antoine Pitrou.)

Regular and recursive locks now accept an optional timeout argument to their acquire() method. (Contributed by Antoine Pitrou; bpo-7316 [https://bugs.python.org/issue?@action=redirect&bpo=7316].)

Similarly, threading.Semaphore.acquire() also gained a timeout argument. (Contributed by Torsten Landschoff; bpo-850728 [https://bugs.python.org/issue?@action=redirect&bpo=850728].)

Regular and recursive lock acquisitions can now be interrupted by signals on platforms using Pthreads. This means that Python programs that deadlock while acquiring locks can be successfully killed by repeatedly sending SIGINT to the process (by pressing Ctrl+C in most shells). (Contributed by Reid Kleckner; bpo-8844 [https://bugs.python.org/issue?@action=redirect&bpo=8844].)

Optimizations

A number of small performance enhancements have been added:

Python’s peephole optimizer now recognizes patterns such x in {1, 2, 3} as being a test for membership in a set of constants. The optimizer recasts the set as a frozenset and stores the pre-built constant.

Now that the speed penalty is gone, it is practical to start writing membership tests using set-notation. This style is both semantically clear and operationally fast:

extension = name.rpartition('.')[2]
if extension in {'xml', 'html', 'xhtml', 'css'}:
    handle(name)

(Patch and additional tests contributed by Dave Malcolm; bpo-6690 [https://bugs.python.org/issue?@action=redirect&bpo=6690]).

Serializing and unserializing data using the pickle module is now several times faster.

(Contributed by Alexandre Vassalotti, Antoine Pitrou and the Unladen Swallow team in bpo-9410 [https://bugs.python.org/issue?@action=redirect&bpo=9410] and bpo-3873 [https://bugs.python.org/issue?@action=redirect&bpo=3873].)

The Timsort algorithm [https://en.wikipedia.org/wiki/Timsort] used in list.sort() and sorted() now runs faster and uses less memory when called with a key function. Previously, every element of a list was wrapped with a temporary object that remembered the key value associated with each element. Now, two arrays of keys and values are sorted in parallel. This saves the memory consumed by the sort wrappers, and it saves time lost to delegating comparisons.

(Patch by Daniel Stutzbach in bpo-9915 [https://bugs.python.org/issue?@action=redirect&bpo=9915].)

JSON decoding performance is improved and memory consumption is reduced whenever the same string is repeated for multiple keys. Also, JSON encoding now uses the C speedups when the sort_keys argument is true.

(Contributed by Antoine Pitrou in bpo-7451 [https://bugs.python.org/issue?@action=redirect&bpo=7451] and by Raymond Hettinger and Antoine Pitrou in bpo-10314 [https://bugs.python.org/issue?@action=redirect&bpo=10314].)

Recursive locks (created with the threading.RLock() API) now benefit from a C implementation which makes them as fast as regular locks, and between 10x and 15x faster than their previous pure Python implementation.

(Contributed by Antoine Pitrou; bpo-3001 [https://bugs.python.org/issue?@action=redirect&bpo=3001].)

The fast-search algorithm in stringlib is now used by the split(), rsplit(), splitlines() and replace() methods on bytes, bytearray and str objects. Likewise, the algorithm is also used by rfind(), rindex(), rsplit() and rpartition().

(Patch by Florent Xicluna in bpo-7622 [https://bugs.python.org/issue?@action=redirect&bpo=7622] and bpo-7462 [https://bugs.python.org/issue?@action=redirect&bpo=7462].)

Integer to string conversions now work two “digits” at a time, reducing the number of division and modulo operations.

(bpo-6713 [https://bugs.python.org/issue?@action=redirect&bpo=6713] by Gawain Bolton, Mark Dickinson, and Victor Stinner.)

There were several other minor optimizations. Set differencing now runs faster when one operand is much larger than the other (patch by Andress Bennetts in bpo-8685 [https://bugs.python.org/issue?@action=redirect&bpo=8685]). The array.repeat() method has a faster implementation (bpo-1569291 [https://bugs.python.org/issue?@action=redirect&bpo=1569291] by Alexander Belopolsky). The BaseHTTPRequestHandler has more efficient buffering (bpo-3709 [https://bugs.python.org/issue?@action=redirect&bpo=3709] by Andrew Schaaf). The operator.attrgetter() function has been sped-up (bpo-10160 [https://bugs.python.org/issue?@action=redirect&bpo=10160] by Christos Georgiou). And ConfigParser loads multi-line arguments a bit faster (bpo-7113 [https://bugs.python.org/issue?@action=redirect&bpo=7113] by Łukasz Langa).

Unicode

Python has been updated to Unicode 6.0.0 [http://unicode.org/versions/Unicode6.0.0/]. The update to the standard adds over 2,000 new characters including emoji [https://en.wikipedia.org/wiki/Emoji] symbols which are important for mobile phones.

In addition, the updated standard has altered the character properties for two Kannada characters (U+0CF1, U+0CF2) and one New Tai Lue numeric character (U+19DA), making the former eligible for use in identifiers while disqualifying the latter. For more information, see Unicode Character Database Changes [http://www.unicode.org/versions/Unicode6.0.0/#Database_Changes].

Codecs

Support was added for cp720 Arabic DOS encoding (bpo-1616979 [https://bugs.python.org/issue?@action=redirect&bpo=1616979]).

MBCS encoding no longer ignores the error handler argument. In the default strict mode, it raises an UnicodeDecodeError when it encounters an undecodable byte sequence and an UnicodeEncodeError for an unencodable character.

The MBCS codec supports 'strict' and 'ignore' error handlers for decoding, and 'strict' and 'replace' for encoding.

To emulate Python3.1 MBCS encoding, select the 'ignore' handler for decoding and the 'replace' handler for encoding.

On Mac OS X, Python decodes command line arguments with 'utf-8' rather than the locale encoding.

By default, tarfile uses 'utf-8' encoding on Windows (instead of 'mbcs') and the 'surrogateescape' error handler on all operating systems.

Documentation

The documentation continues to be improved.

A table of quick links has been added to the top of lengthy sections such as 내장 함수. In the case of itertools, the links are accompanied by tables of cheatsheet-style summaries to provide an overview and memory jog without having to read all of the docs.

In some cases, the pure Python source code can be a helpful adjunct to the documentation, so now many modules now feature quick links to the latest version of the source code. For example, the functools module documentation has a quick link at the top labeled:

Source code Lib/functools.py [https://github.com/python/cpython/tree/3.7/Lib/functools.py].

(Contributed by Raymond Hettinger; see rationale [https://rhettinger.wordpress.com/2011/01/28/open-your-source-more/].)

The docs now contain more examples and recipes. In particular, re module has an extensive section, Regular Expression Examples. Likewise, the itertools module continues to be updated with new Itertools Recipes.

The datetime module now has an auxiliary implementation in pure Python. No functionality was changed. This just provides an easier-to-read alternate implementation.

(Contributed by Alexander Belopolsky in bpo-9528 [https://bugs.python.org/issue?@action=redirect&bpo=9528].)

The unmaintained Demo directory has been removed. Some demos were integrated into the documentation, some were moved to the Tools/demo directory, and others were removed altogether.

(Contributed by Georg Brandl in bpo-7962 [https://bugs.python.org/issue?@action=redirect&bpo=7962].)

IDLE

The format menu now has an option to clean source files by stripping trailing whitespace.

(Contributed by Raymond Hettinger; bpo-5150 [https://bugs.python.org/issue?@action=redirect&bpo=5150].)

IDLE on Mac OS X now works with both Carbon AquaTk and Cocoa AquaTk.

(Contributed by Kevin Walzer, Ned Deily, and Ronald Oussoren; bpo-6075 [https://bugs.python.org/issue?@action=redirect&bpo=6075].)

Code Repository

In addition to the existing Subversion code repository at http://svn.python.org there is now a Mercurial [https://www.mercurial-scm.org/] repository at https://hg.python.org/.

After the 3.2 release, there are plans to switch to Mercurial as the primary repository. This distributed version control system should make it easier for members of the community to create and share external changesets. See PEP 385 [https://www.python.org/dev/peps/pep-0385] for details.

To learn to use the new version control system, see the Quick Start [https://www.mercurial-scm.org/wiki/QuickStart] or the Guide to Mercurial Workflows [https://www.mercurial-scm.org/guide].

Build and C API Changes

Changes to Python’s build process and to the C API include:

The idle, pydoc and 2to3 scripts are now installed with a version-specific suffix on make altinstall (bpo-10679 [https://bugs.python.org/issue?@action=redirect&bpo=10679]).

The C functions that access the Unicode Database now accept and return characters from the full Unicode range, even on narrow unicode builds (Py_UNICODE_TOLOWER, Py_UNICODE_ISDECIMAL, and others). A visible difference in Python is that unicodedata.numeric() now returns the correct value for large code points, and repr() may consider more characters as printable.

(Reported by Bupjoe Lee and fixed by Amaury Forgeot D’Arc; bpo-5127 [https://bugs.python.org/issue?@action=redirect&bpo=5127].)

Computed gotos are now enabled by default on supported compilers (which are detected by the configure script). They can still be disabled selectively by specifying --without-computed-gotos.

(Contributed by Antoine Pitrou; bpo-9203 [https://bugs.python.org/issue?@action=redirect&bpo=9203].)

The option --with-wctype-functions was removed. The built-in unicode database is now used for all functions.

(Contributed by Amaury Forgeot D’Arc; bpo-9210 [https://bugs.python.org/issue?@action=redirect&bpo=9210].)

Hash values are now values of a new type, Py_hash_t, which is defined to be the same size as a pointer. Previously they were of type long, which on some 64-bit operating systems is still only 32 bits long. As a result of this fix, set and dict can now hold more than 2**32 entries on builds with 64-bit pointers (previously, they could grow to that size but their performance degraded catastrophically).

(Suggested by Raymond Hettinger and implemented by Benjamin Peterson; bpo-9778 [https://bugs.python.org/issue?@action=redirect&bpo=9778].)

A new macro Py_VA_COPY copies the state of the variable argument list. It is equivalent to C99 va_copy but available on all Python platforms (bpo-2443 [https://bugs.python.org/issue?@action=redirect&bpo=2443]).

A new C API function PySys_SetArgvEx() allows an embedded interpreter to set sys.argv without also modifying sys.path (bpo-5753 [https://bugs.python.org/issue?@action=redirect&bpo=5753]).

PyEval_CallObject is now only available in macro form. The function declaration, which was kept for backwards compatibility reasons, is now removed – the macro was introduced in 1997 (bpo-8276 [https://bugs.python.org/issue?@action=redirect&bpo=8276]).

There is a new function PyLong_AsLongLongAndOverflow() which is analogous to PyLong_AsLongAndOverflow(). They both serve to convert Python int into a native fixed-width type while providing detection of cases where the conversion won’t fit (bpo-7767 [https://bugs.python.org/issue?@action=redirect&bpo=7767]).

The PyUnicode_CompareWithASCIIString() function now returns not equal if the Python string is NUL terminated.

There is a new function PyErr_NewExceptionWithDoc() that is like PyErr_NewException() but allows a docstring to be specified. This lets C exceptions have the same self-documenting capabilities as their pure Python counterparts (bpo-7033 [https://bugs.python.org/issue?@action=redirect&bpo=7033]).

When compiled with the --with-valgrind option, the pymalloc allocator will be automatically disabled when running under Valgrind. This gives improved memory leak detection when running under Valgrind, while taking advantage of pymalloc at other times (bpo-2422 [https://bugs.python.org/issue?@action=redirect&bpo=2422]).

Removed the O? format from the PyArg_Parse functions. The format is no longer used and it had never been documented (bpo-8837 [https://bugs.python.org/issue?@action=redirect&bpo=8837]).

There were a number of other small changes to the C-API. See the Misc/NEWS [https://github.com/python/cpython/tree/3.7/Misc/NEWS] file for a complete list.

Also, there were a number of updates to the Mac OS X build, see Mac/BuildScript/README.txt [https://github.com/python/cpython/tree/3.7/Mac/BuildScript/README.txt] for details. For users running a 32/64-bit build, there is a known problem with the default Tcl/Tk on Mac OS X 10.6. Accordingly, we recommend installing an updated alternative such as ActiveState Tcl/Tk 8.5.9 [https://www.activestate.com/activetcl/downloads]. See https://www.python.org/download/mac/tcltk/ for additional details.

Porting to Python 3.2

This section lists previously described changes and other bugfixes that may require changes to your code:

The configparser module has a number of clean-ups. The major change is to replace the old ConfigParser class with long-standing preferred alternative SafeConfigParser. In addition there are a number of smaller incompatibilities:

The interpolation syntax is now validated on get() and set() operations. In the default interpolation scheme, only two tokens with percent signs are valid: %(name)s and %%, the latter being an escaped percent sign.

The set() and add_section() methods now verify that values are actual strings. Formerly, unsupported types could be introduced unintentionally.

Duplicate sections or options from a single source now raise either DuplicateSectionError or DuplicateOptionError. Formerly, duplicates would silently overwrite a previous entry.

Inline comments are now disabled by default so now the ; character can be safely used in values.

Comments now can be indented. Consequently, for ; or # to appear at the start of a line in multiline values, it has to be interpolated. This keeps comment prefix characters in values from being mistaken as comments.

"" is now a valid value and is no longer automatically converted to an empty string. For empty strings, use "option =" in a line.

The nntplib module was reworked extensively, meaning that its APIs are often incompatible with the 3.1 APIs.

bytearray objects can no longer be used as filenames; instead, they should be converted to bytes.

The array.tostring() and array.fromstring() have been renamed to array.tobytes() and array.frombytes() for clarity. The old names have been deprecated. (See bpo-8990 [https://bugs.python.org/issue?@action=redirect&bpo=8990].)

PyArg_Parse*() functions:

“t#” format has been removed: use “s#” or “s*” instead

“w” and “w#” formats has been removed: use “w*” instead

The PyCObject type, deprecated in 3.1, has been removed. To wrap opaque C pointers in Python objects, the PyCapsule API should be used instead; the new type has a well-defined interface for passing typing safety information and a less complicated signature for calling a destructor.

The sys.setfilesystemencoding() function was removed because it had a flawed design.

The random.seed() function and method now salt string seeds with an sha512 hash function. To access the previous version of seed in order to reproduce Python 3.1 sequences, set the version argument to 1, random.seed(s, version=1).

The previously deprecated string.maketrans() function has been removed in favor of the static methods bytes.maketrans() and bytearray.maketrans(). This change solves the confusion around which types were supported by the string module. Now, str, bytes, and bytearray each have their own maketrans and translate methods with intermediate translation tables of the appropriate type.

(Contributed by Georg Brandl; bpo-5675 [https://bugs.python.org/issue?@action=redirect&bpo=5675].)

The previously deprecated contextlib.nested() function has been removed in favor of a plain with statement which can accept multiple context managers. The latter technique is faster (because it is built-in), and it does a better job finalizing multiple context managers when one of them raises an exception:

with open('mylog.txt') as infile, open('a.out', 'w') as outfile:
    for line in infile:
        if '<critical>' in line:
            outfile.write(line)

(Contributed by Georg Brandl and Mattias Brändström; appspot issue 53094 [https://codereview.appspot.com/53094].)

struct.pack() now only allows bytes for the s string pack code. Formerly, it would accept text arguments and implicitly encode them to bytes using UTF-8. This was problematic because it made assumptions about the correct encoding and because a variable-length encoding can fail when writing to fixed length segment of a structure.

Code such as struct.pack('<6sHHBBB', 'GIF87a', x, y) should be rewritten with to use bytes instead of text, struct.pack('<6sHHBBB', b'GIF87a', x, y).

(Discovered by David Beazley and fixed by Victor Stinner; bpo-10783 [https://bugs.python.org/issue?@action=redirect&bpo=10783].)

The xml.etree.ElementTree class now raises an xml.etree.ElementTree.ParseError when a parse fails. Previously it raised an xml.parsers.expat.ExpatError.

The new, longer str() value on floats may break doctests which rely on the old output format.

In subprocess.Popen, the default value for close_fds is now True under Unix; under Windows, it is True if the three standard streams are set to None, False otherwise. Previously, close_fds was always False by default, which produced difficult to solve bugs or race conditions when open file descriptors would leak into the child process.

Support for legacy HTTP 0.9 has been removed from urllib.request and http.client. Such support is still present on the server side (in http.server).

(Contributed by Antoine Pitrou, bpo-10711 [https://bugs.python.org/issue?@action=redirect&bpo=10711].)

SSL sockets in timeout mode now raise socket.timeout when a timeout occurs, rather than a generic SSLError.

(Contributed by Antoine Pitrou, bpo-10272 [https://bugs.python.org/issue?@action=redirect&bpo=10272].)

The misleading functions PyEval_AcquireLock() and PyEval_ReleaseLock() have been officially deprecated. The thread-state aware APIs (such as PyEval_SaveThread() and PyEval_RestoreThread()) should be used instead.

Due to security risks, asyncore.handle_accept() has been deprecated, and a new function, asyncore.handle_accepted(), was added to replace it.

(Contributed by Giampaolo Rodola in bpo-6706 [https://bugs.python.org/issue?@action=redirect&bpo=6706].)

Due to the new GIL implementation, PyEval_InitThreads() cannot be called before Py_Initialize() anymore.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬의 새로운 기능 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬의 새로운 기능 »

|

What’s New In Python 3.1

Author

Raymond Hettinger

This article explains the new features in Python 3.1, compared to 3.0.

PEP 372: Ordered Dictionaries

Regular Python dictionaries iterate over key/value pairs in arbitrary order. Over the years, a number of authors have written alternative implementations that remember the order that the keys were originally inserted. Based on the experiences from those implementations, a new collections.OrderedDict class has been introduced.

The OrderedDict API is substantially the same as regular dictionaries but will iterate over keys and values in a guaranteed order depending on when a key was first inserted. If a new entry overwrites an existing entry, the original insertion position is left unchanged. Deleting an entry and reinserting it will move it to the end.

The standard library now supports use of ordered dictionaries in several modules. The configparser module uses them by default. This lets configuration files be read, modified, and then written back in their original order. The _asdict() method for collections.namedtuple() now returns an ordered dictionary with the values appearing in the same order as the underlying tuple indices. The json module is being built-out with an object_pairs_hook to allow OrderedDicts to be built by the decoder. Support was also added for third-party tools like PyYAML [http://pyyaml.org/].

더 보기

PEP 372 [https://www.python.org/dev/peps/pep-0372] - Ordered Dictionaries

PEP written by Armin Ronacher and Raymond Hettinger. Implementation written by Raymond Hettinger.

PEP 378: Format Specifier for Thousands Separator

The built-in format() function and the str.format() method use a mini-language that now includes a simple, non-locale aware way to format a number with a thousands separator. That provides a way to humanize a program’s output, improving its professional appearance and readability:

>>> format(1234567, ',d')
'1,234,567'
>>> format(1234567.89, ',.2f')
'1,234,567.89'
>>> format(12345.6 + 8901234.12j, ',f')
'12,345.600000+8,901,234.120000j'
>>> format(Decimal('1234567.89'), ',f')
'1,234,567.89'

The supported types are int, float, complex and decimal.Decimal.

Discussions are underway about how to specify alternative separators like dots, spaces, apostrophes, or underscores. Locale-aware applications should use the existing n format specifier which already has some support for thousands separators.

더 보기

PEP 378 [https://www.python.org/dev/peps/pep-0378] - Format Specifier for Thousands Separator

PEP written by Raymond Hettinger and implemented by Eric Smith and Mark Dickinson.

Other Language Changes

Some smaller changes made to the core Python language are:

Directories and zip archives containing a __main__.py file can now be executed directly by passing their name to the interpreter. The directory/zipfile is automatically inserted as the first entry in sys.path. (Suggestion and initial patch by Andy Chu; revised patch by Phillip J. Eby and Nick Coghlan; bpo-1739468 [https://bugs.python.org/issue?@action=redirect&bpo=1739468].)

The int() type gained a bit_length method that returns the number of bits necessary to represent its argument in binary:

>>> n = 37
>>> bin(37)
'0b100101'
>>> n.bit_length()
6
>>> n = 2**123-1
>>> n.bit_length()
123
>>> (n+1).bit_length()
124

(Contributed by Fredrik Johansson, Victor Stinner, Raymond Hettinger, and Mark Dickinson; bpo-3439 [https://bugs.python.org/issue?@action=redirect&bpo=3439].)

The fields in format() strings can now be automatically numbered:

>>> 'Sir {} of {}'.format('Gallahad', 'Camelot')
'Sir Gallahad of Camelot'

Formerly, the string would have required numbered fields such as: 'Sir {0} of {1}'.

(Contributed by Eric Smith; bpo-5237 [https://bugs.python.org/issue?@action=redirect&bpo=5237].)

The string.maketrans() function is deprecated and is replaced by new static methods, bytes.maketrans() and bytearray.maketrans(). This change solves the confusion around which types were supported by the string module. Now, str, bytes, and bytearray each have their own maketrans and translate methods with intermediate translation tables of the appropriate type.

(Contributed by Georg Brandl; bpo-5675 [https://bugs.python.org/issue?@action=redirect&bpo=5675].)

The syntax of the with statement now allows multiple context managers in a single statement:

>>> with open('mylog.txt') as infile, open('a.out', 'w') as outfile:
...     for line in infile:
...         if '<critical>' in line:
...             outfile.write(line)

With the new syntax, the contextlib.nested() function is no longer needed and is now deprecated.

(Contributed by Georg Brandl and Mattias Brändström; appspot issue 53094 [https://codereview.appspot.com/53094].)

round(x, n) now returns an integer if x is an integer. Previously it returned a float:

>>> round(1123, -2)
1100

(Contributed by Mark Dickinson; bpo-4707 [https://bugs.python.org/issue?@action=redirect&bpo=4707].)

Python now uses David Gay’s algorithm for finding the shortest floating point representation that doesn’t change its value. This should help mitigate some of the confusion surrounding binary floating point numbers.

The significance is easily seen with a number like 1.1 which does not have an exact equivalent in binary floating point. Since there is no exact equivalent, an expression like float('1.1') evaluates to the nearest representable value which is 0x1.199999999999ap+0 in hex or 1.100000000000000088817841970012523233890533447265625 in decimal. That nearest value was and still is used in subsequent floating point calculations.

What is new is how the number gets displayed. Formerly, Python used a simple approach. The value of repr(1.1) was computed as format(1.1, '.17g') which evaluated to '1.1000000000000001'. The advantage of using 17 digits was that it relied on IEEE-754 guarantees to assure that eval(repr(1.1)) would round-trip exactly to its original value. The disadvantage is that many people found the output to be confusing (mistaking intrinsic limitations of binary floating point representation as being a problem with Python itself).

The new algorithm for repr(1.1) is smarter and returns '1.1'. Effectively, it searches all equivalent string representations (ones that get stored with the same underlying float value) and returns the shortest representation.

The new algorithm tends to emit cleaner representations when possible, but it does not change the underlying values. So, it is still the case that 1.1 + 2.2 != 3.3 even though the representations may suggest otherwise.

The new algorithm depends on certain features in the underlying floating point implementation. If the required features are not found, the old algorithm will continue to be used. Also, the text pickle protocols assure cross-platform portability by using the old algorithm.

(Contributed by Eric Smith and Mark Dickinson; bpo-1580 [https://bugs.python.org/issue?@action=redirect&bpo=1580])

New, Improved, and Deprecated Modules

Added a collections.Counter class to support convenient counting of unique items in a sequence or iterable:

>>> Counter(['red', 'blue', 'red', 'green', 'blue', 'blue'])
Counter({'blue': 3, 'red': 2, 'green': 1})

(Contributed by Raymond Hettinger; bpo-1696199 [https://bugs.python.org/issue?@action=redirect&bpo=1696199].)

Added a new module, tkinter.ttk for access to the Tk themed widget set. The basic idea of ttk is to separate, to the extent possible, the code implementing a widget’s behavior from the code implementing its appearance.

(Contributed by Guilherme Polo; bpo-2983 [https://bugs.python.org/issue?@action=redirect&bpo=2983].)

The gzip.GzipFile and bz2.BZ2File classes now support the context management protocol:

>>> # Automatically close file after writing
>>> with gzip.GzipFile(filename, "wb") as f:
...     f.write(b"xxx")

(Contributed by Antoine Pitrou.)

The decimal module now supports methods for creating a decimal object from a binary float. The conversion is exact but can sometimes be surprising:

>>> Decimal.from_float(1.1)
Decimal('1.100000000000000088817841970012523233890533447265625')

The long decimal result shows the actual binary fraction being stored for 1.1. The fraction has many digits because 1.1 cannot be exactly represented in binary.

(Contributed by Raymond Hettinger and Mark Dickinson.)

The itertools module grew two new functions. The itertools.combinations_with_replacement() function is one of four for generating combinatorics including permutations and Cartesian products. The itertools.compress() function mimics its namesake from APL. Also, the existing itertools.count() function now has an optional step argument and can accept any type of counting sequence including fractions.Fraction and decimal.Decimal:

>>> [p+q for p,q in combinations_with_replacement('LOVE', 2)]
['LL', 'LO', 'LV', 'LE', 'OO', 'OV', 'OE', 'VV', 'VE', 'EE']

>>> list(compress(data=range(10), selectors=[0,0,1,1,0,1,0,1,0,0]))
[2, 3, 5, 7]

>>> c = count(start=Fraction(1,2), step=Fraction(1,6))
>>> [next(c), next(c), next(c), next(c)]
[Fraction(1, 2), Fraction(2, 3), Fraction(5, 6), Fraction(1, 1)]

(Contributed by Raymond Hettinger.)

collections.namedtuple() now supports a keyword argument rename which lets invalid fieldnames be automatically converted to positional names in the form _0, _1, etc. This is useful when the field names are being created by an external source such as a CSV header, SQL field list, or user input:

>>> query = input()
SELECT region, dept, count(*) FROM main GROUPBY region, dept

>>> cursor.execute(query)
>>> query_fields = [desc[0] for desc in cursor.description]
>>> UserQuery = namedtuple('UserQuery', query_fields, rename=True)
>>> pprint.pprint([UserQuery(*row) for row in cursor])
[UserQuery(region='South', dept='Shipping', _2=185),
 UserQuery(region='North', dept='Accounting', _2=37),
 UserQuery(region='West', dept='Sales', _2=419)]

(Contributed by Raymond Hettinger; bpo-1818 [https://bugs.python.org/issue?@action=redirect&bpo=1818].)

The re.sub(), re.subn() and re.split() functions now accept a flags parameter.

(Contributed by Gregory Smith.)

The logging module now implements a simple logging.NullHandler class for applications that are not using logging but are calling library code that does. Setting-up a null handler will suppress spurious warnings such as “No handlers could be found for logger foo”:

>>> h = logging.NullHandler()
>>> logging.getLogger("foo").addHandler(h)

(Contributed by Vinay Sajip; bpo-4384 [https://bugs.python.org/issue?@action=redirect&bpo=4384]).

The runpy module which supports the -m command line switch now supports the execution of packages by looking for and executing a __main__ submodule when a package name is supplied.

(Contributed by Andi Vajda; bpo-4195 [https://bugs.python.org/issue?@action=redirect&bpo=4195].)

The pdb module can now access and display source code loaded via zipimport (or any other conformant PEP 302 [https://www.python.org/dev/peps/pep-0302] loader).

(Contributed by Alexander Belopolsky; bpo-4201 [https://bugs.python.org/issue?@action=redirect&bpo=4201].)

functools.partial objects can now be pickled.

(Suggested by Antoine Pitrou and Jesse Noller. Implemented by Jack Diederich; bpo-5228 [https://bugs.python.org/issue?@action=redirect&bpo=5228].)

Add pydoc help topics for symbols so that help('@') works as expected in the interactive environment.

(Contributed by David Laban; bpo-4739 [https://bugs.python.org/issue?@action=redirect&bpo=4739].)

The unittest module now supports skipping individual tests or classes of tests. And it supports marking a test as an expected failure, a test that is known to be broken, but shouldn’t be counted as a failure on a TestResult:

class TestGizmo(unittest.TestCase):

    @unittest.skipUnless(sys.platform.startswith("win"), "requires Windows")
    def test_gizmo_on_windows(self):
        ...

    @unittest.expectedFailure
    def test_gimzo_without_required_library(self):
        ...

Also, tests for exceptions have been builtout to work with context managers using the with statement:

def test_division_by_zero(self):
    with self.assertRaises(ZeroDivisionError):
        x / 0

In addition, several new assertion methods were added including assertSetEqual(), assertDictEqual(), assertDictContainsSubset(), assertListEqual(), assertTupleEqual(), assertSequenceEqual(), assertRaisesRegexp(), assertIsNone(), and assertIsNotNone().

(Contributed by Benjamin Peterson and Antoine Pitrou.)

The io module has three new constants for the seek() method SEEK_SET, SEEK_CUR, and SEEK_END.

The sys.version_info tuple is now a named tuple:

>>> sys.version_info
sys.version_info(major=3, minor=1, micro=0, releaselevel='alpha', serial=2)

(Contributed by Ross Light; bpo-4285 [https://bugs.python.org/issue?@action=redirect&bpo=4285].)

The nntplib and imaplib modules now support IPv6.

(Contributed by Derek Morr; bpo-1655 [https://bugs.python.org/issue?@action=redirect&bpo=1655] and bpo-1664 [https://bugs.python.org/issue?@action=redirect&bpo=1664].)

The pickle module has been adapted for better interoperability with Python 2.x when used with protocol 2 or lower. The reorganization of the standard library changed the formal reference for many objects. For example, __builtin__.set in Python 2 is called builtins.set in Python 3. This change confounded efforts to share data between different versions of Python. But now when protocol 2 or lower is selected, the pickler will automatically use the old Python 2 names for both loading and dumping. This remapping is turned-on by default but can be disabled with the fix_imports option:

>>> s = {1, 2, 3}
>>> pickle.dumps(s, protocol=0)
b'c__builtin__\nset\np0\n((lp1\nL1L\naL2L\naL3L\natp2\nRp3\n.'
>>> pickle.dumps(s, protocol=0, fix_imports=False)
b'cbuiltins\nset\np0\n((lp1\nL1L\naL2L\naL3L\natp2\nRp3\n.'

An unfortunate but unavoidable side-effect of this change is that protocol 2 pickles produced by Python 3.1 won’t be readable with Python 3.0. The latest pickle protocol, protocol 3, should be used when migrating data between Python 3.x implementations, as it doesn’t attempt to remain compatible with Python 2.x.

(Contributed by Alexandre Vassalotti and Antoine Pitrou, bpo-6137 [https://bugs.python.org/issue?@action=redirect&bpo=6137].)

A new module, importlib was added. It provides a complete, portable, pure Python reference implementation of the import statement and its counterpart, the __import__() function. It represents a substantial step forward in documenting and defining the actions that take place during imports.

(Contributed by Brett Cannon.)

Optimizations

Major performance enhancements have been added:

The new I/O library (as defined in PEP 3116 [https://www.python.org/dev/peps/pep-3116]) was mostly written in Python and quickly proved to be a problematic bottleneck in Python 3.0. In Python 3.1, the I/O library has been entirely rewritten in C and is 2 to 20 times faster depending on the task at hand. The pure Python version is still available for experimentation purposes through the _pyio module.

(Contributed by Amaury Forgeot d’Arc and Antoine Pitrou.)

Added a heuristic so that tuples and dicts containing only untrackable objects are not tracked by the garbage collector. This can reduce the size of collections and therefore the garbage collection overhead on long-running programs, depending on their particular use of datatypes.

(Contributed by Antoine Pitrou, bpo-4688 [https://bugs.python.org/issue?@action=redirect&bpo=4688].)

Enabling a configure option named --with-computed-gotos on compilers that support it (notably: gcc, SunPro, icc), the bytecode evaluation loop is compiled with a new dispatch mechanism which gives speedups of up to 20%, depending on the system, the compiler, and the benchmark.

(Contributed by Antoine Pitrou along with a number of other participants, bpo-4753 [https://bugs.python.org/issue?@action=redirect&bpo=4753]).

The decoding of UTF-8, UTF-16 and LATIN-1 is now two to four times faster.

(Contributed by Antoine Pitrou and Amaury Forgeot d’Arc, bpo-4868 [https://bugs.python.org/issue?@action=redirect&bpo=4868].)

The json module now has a C extension to substantially improve its performance. In addition, the API was modified so that json works only with str, not with bytes. That change makes the module closely match the JSON specification [http://json.org/] which is defined in terms of Unicode.

(Contributed by Bob Ippolito and converted to Py3.1 by Antoine Pitrou and Benjamin Peterson; bpo-4136 [https://bugs.python.org/issue?@action=redirect&bpo=4136].)

Unpickling now interns the attribute names of pickled objects. This saves memory and allows pickles to be smaller.

(Contributed by Jake McGuire and Antoine Pitrou; bpo-5084 [https://bugs.python.org/issue?@action=redirect&bpo=5084].)

IDLE

IDLE’s format menu now provides an option to strip trailing whitespace from a source file.

(Contributed by Roger D. Serwy; bpo-5150 [https://bugs.python.org/issue?@action=redirect&bpo=5150].)

Build and C API Changes

Changes to Python’s build process and to the C API include:

Integers are now stored internally either in base 2**15 or in base 2**30, the base being determined at build time. Previously, they were always stored in base 2**15. Using base 2**30 gives significant performance improvements on 64-bit machines, but benchmark results on 32-bit machines have been mixed. Therefore, the default is to use base 2**30 on 64-bit machines and base 2**15 on 32-bit machines; on Unix, there’s a new configure option --enable-big-digits that can be used to override this default.

Apart from the performance improvements this change should be invisible to end users, with one exception: for testing and debugging purposes there’s a new sys.int_info that provides information about the internal format, giving the number of bits per digit and the size in bytes of the C type used to store each digit:

>>> import sys
>>> sys.int_info
sys.int_info(bits_per_digit=30, sizeof_digit=4)

(Contributed by Mark Dickinson; bpo-4258 [https://bugs.python.org/issue?@action=redirect&bpo=4258].)

The PyLong_AsUnsignedLongLong() function now handles a negative pylong by raising OverflowError instead of TypeError.

(Contributed by Mark Dickinson and Lisandro Dalcrin; bpo-5175 [https://bugs.python.org/issue?@action=redirect&bpo=5175].)

Deprecated PyNumber_Int(). Use PyNumber_Long() instead.

(Contributed by Mark Dickinson; bpo-4910 [https://bugs.python.org/issue?@action=redirect&bpo=4910].)

Added a new PyOS_string_to_double() function to replace the deprecated functions PyOS_ascii_strtod() and PyOS_ascii_atof().

(Contributed by Mark Dickinson; bpo-5914 [https://bugs.python.org/issue?@action=redirect&bpo=5914].)

Added PyCapsule as a replacement for the PyCObject API. The principal difference is that the new type has a well defined interface for passing typing safety information and a less complicated signature for calling a destructor. The old type had a problematic API and is now deprecated.

(Contributed by Larry Hastings; bpo-5630 [https://bugs.python.org/issue?@action=redirect&bpo=5630].)

Porting to Python 3.1

This section lists previously described changes and other bugfixes that may require changes to your code:

The new floating point string representations can break existing doctests. For example:

def e():
    '''Compute the base of natural logarithms.

    >>> e()
    2.7182818284590451

    '''
    return sum(1/math.factorial(x) for x in reversed(range(30)))

doctest.testmod()

**********************************************************************
Failed example:
    e()
Expected:
    2.7182818284590451
Got:
    2.718281828459045
**********************************************************************

The automatic name remapping in the pickle module for protocol 2 or lower can make Python 3.1 pickles unreadable in Python 3.0. One solution is to use protocol 3. Another solution is to set the fix_imports option to False. See the discussion above for more details.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬의 새로운 기능 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬의 새로운 기능 »

|

What’s New In Python 3.0

Author

Guido van Rossum

This article explains the new features in Python 3.0, compared to 2.6. Python 3.0, also known as “Python 3000” or “Py3K”, is the first ever intentionally backwards incompatible Python release. There are more changes than in a typical release, and more that are important for all Python users. Nevertheless, after digesting the changes, you’ll find that Python really hasn’t changed all that much – by and large, we’re mostly fixing well-known annoyances and warts, and removing a lot of old cruft.

This article doesn’t attempt to provide a complete specification of all new features, but instead tries to give a convenient overview. For full details, you should refer to the documentation for Python 3.0, and/or the many PEPs referenced in the text. If you want to understand the complete implementation and design rationale for a particular feature, PEPs usually have more details than the regular documentation; but note that PEPs usually are not kept up-to-date once a feature has been fully implemented.

Due to time constraints this document is not as complete as it should have been. As always for a new release, the Misc/NEWS file in the source distribution contains a wealth of detailed information about every small thing that was changed.

Common Stumbling Blocks

This section lists those few changes that are most likely to trip you up if you’re used to Python 2.5.

Print Is A Function

The print statement has been replaced with a print() function, with keyword arguments to replace most of the special syntax of the old print statement (PEP 3105 [https://www.python.org/dev/peps/pep-3105]). Examples:

Old: print "The answer is", 2*2
New: print("The answer is", 2*2)

Old: print x,           # Trailing comma suppresses newline
New: print(x, end=" ")  # Appends a space instead of a newline

Old: print              # Prints a newline
New: print()            # You must call the function!

Old: print >>sys.stderr, "fatal error"
New: print("fatal error", file=sys.stderr)

Old: print (x, y)       # prints repr((x, y))
New: print((x, y))      # Not the same as print(x, y)!

You can also customize the separator between items, e.g.:

print("There are <", 2**32, "> possibilities!", sep="")

which produces:

There are <4294967296> possibilities!

Note:

The print() function doesn’t support the “softspace” feature of the old print statement. For example, in Python 2.x, print "A\n", "B" would write "A\nB\n"; but in Python 3.0, print("A\n", "B") writes "A\n B\n".

Initially, you’ll be finding yourself typing the old print x a lot in interactive mode. Time to retrain your fingers to type print(x) instead!

When using the 2to3 source-to-source conversion tool, all print statements are automatically converted to print() function calls, so this is mostly a non-issue for larger projects.

Views And Iterators Instead Of Lists

Some well-known APIs no longer return lists:

dict methods dict.keys(), dict.items() and dict.values() return “views” instead of lists. For example, this no longer works: k = d.keys(); k.sort(). Use k = sorted(d) instead (this works in Python 2.5 too and is just as efficient).

Also, the dict.iterkeys(), dict.iteritems() and dict.itervalues() methods are no longer supported.

map() and filter() return iterators. If you really need a list and the input sequences are all of equal length, a quick fix is to wrap map() in list(), e.g. list(map(...)), but a better fix is often to use a list comprehension (especially when the original code uses lambda), or rewriting the code so it doesn’t need a list at all. Particularly tricky is map() invoked for the side effects of the function; the correct transformation is to use a regular for loop (since creating a list would just be wasteful).

If the input sequences are not of equal length, map() will stop at the termination of the shortest of the sequences. For full compatibility with map() from Python 2.x, also wrap the sequences in itertools.zip_longest(), e.g. map(func, *sequences) becomes list(map(func, itertools.zip_longest(*sequences))).

range() now behaves like xrange() used to behave, except it works with values of arbitrary size. The latter no longer exists.

zip() now returns an iterator.

Ordering Comparisons

Python 3.0 has simplified the rules for ordering comparisons:

The ordering comparison operators (<, <=, >=, >) raise a TypeError exception when the operands don’t have a meaningful natural ordering. Thus, expressions like 1 < '', 0 > None or len <= len are no longer valid, and e.g. None < None raises TypeError instead of returning False. A corollary is that sorting a heterogeneous list no longer makes sense – all the elements must be comparable to each other. Note that this does not apply to the == and != operators: objects of different incomparable types always compare unequal to each other.

builtin.sorted() and list.sort() no longer accept the cmp argument providing a comparison function. Use the key argument instead. N.B. the key and reverse arguments are now “keyword-only”.

The cmp() function should be treated as gone, and the __cmp__() special method is no longer supported. Use __lt__() for sorting, __eq__() with __hash__(), and other rich comparisons as needed. (If you really need the cmp() functionality, you could use the expression (a > b) - (a < b) as the equivalent for cmp(a, b).)

Integers

PEP 237 [https://www.python.org/dev/peps/pep-0237]: Essentially, long renamed to int. That is, there is only one built-in integral type, named int; but it behaves mostly like the old long type.

PEP 238 [https://www.python.org/dev/peps/pep-0238]: An expression like 1/2 returns a float. Use 1//2 to get the truncating behavior. (The latter syntax has existed for years, at least since Python 2.2.)

The sys.maxint constant was removed, since there is no longer a limit to the value of integers. However, sys.maxsize can be used as an integer larger than any practical list or string index. It conforms to the implementation’s “natural” integer size and is typically the same as sys.maxint in previous releases on the same platform (assuming the same build options).

The repr() of a long integer doesn’t include the trailing L anymore, so code that unconditionally strips that character will chop off the last digit instead. (Use str() instead.)

Octal literals are no longer of the form 0720; use 0o720 instead.

Text Vs. Data Instead Of Unicode Vs. 8-bit

Everything you thought you knew about binary data and Unicode has changed.

Python 3.0 uses the concepts of text and (binary) data instead of Unicode strings and 8-bit strings. All text is Unicode; however encoded Unicode is represented as binary data. The type used to hold text is str, the type used to hold data is bytes. The biggest difference with the 2.x situation is that any attempt to mix text and data in Python 3.0 raises TypeError, whereas if you were to mix Unicode and 8-bit strings in Python 2.x, it would work if the 8-bit string happened to contain only 7-bit (ASCII) bytes, but you would get UnicodeDecodeError if it contained non-ASCII values. This value-specific behavior has caused numerous sad faces over the years.

As a consequence of this change in philosophy, pretty much all code that uses Unicode, encodings or binary data most likely has to change. The change is for the better, as in the 2.x world there were numerous bugs having to do with mixing encoded and unencoded text. To be prepared in Python 2.x, start using unicode for all unencoded text, and str for binary or encoded data only. Then the 2to3 tool will do most of the work for you.

You can no longer use u"..." literals for Unicode text. However, you must use b"..." literals for binary data.

As the str and bytes types cannot be mixed, you must always explicitly convert between them. Use str.encode() to go from str to bytes, and bytes.decode() to go from bytes to str. You can also use bytes(s, encoding=...) and str(b, encoding=...), respectively.

Like str, the bytes type is immutable. There is a separate mutable type to hold buffered binary data, bytearray. Nearly all APIs that accept bytes also accept bytearray. The mutable API is based on collections.MutableSequence.

All backslashes in raw string literals are interpreted literally. This means that '\U' and '\u' escapes in raw strings are not treated specially. For example, r'\u20ac' is a string of 6 characters in Python 3.0, whereas in 2.6, ur'\u20ac' was the single “euro” character. (Of course, this change only affects raw string literals; the euro character is '\u20ac' in Python 3.0.)

The built-in basestring abstract type was removed. Use str instead. The str and bytes types don’t have functionality enough in common to warrant a shared base class. The 2to3 tool (see below) replaces every occurrence of basestring with str.

Files opened as text files (still the default mode for open()) always use an encoding to map between strings (in memory) and bytes (on disk). Binary files (opened with a b in the mode argument) always use bytes in memory. This means that if a file is opened using an incorrect mode or encoding, I/O will likely fail loudly, instead of silently producing incorrect data. It also means that even Unix users will have to specify the correct mode (text or binary) when opening a file. There is a platform-dependent default encoding, which on Unixy platforms can be set with the LANG environment variable (and sometimes also with some other platform-specific locale-related environment variables). In many cases, but not all, the system default is UTF-8; you should never count on this default. Any application reading or writing more than pure ASCII text should probably have a way to override the encoding. There is no longer any need for using the encoding-aware streams in the codecs module.

The initial values of sys.stdin, sys.stdout and sys.stderr are now unicode-only text files (i.e., they are instances of io.TextIOBase). To read and write bytes data with these streams, you need to use their io.TextIOBase.buffer attribute.

Filenames are passed to and returned from APIs as (Unicode) strings. This can present platform-specific problems because on some platforms filenames are arbitrary byte strings. (On the other hand, on Windows filenames are natively stored as Unicode.) As a work-around, most APIs (e.g. open() and many functions in the os module) that take filenames accept bytes objects as well as strings, and a few APIs have a way to ask for a bytes return value. Thus, os.listdir() returns a list of bytes instances if the argument is a bytes instance, and os.getcwdb() returns the current working directory as a bytes instance. Note that when os.listdir() returns a list of strings, filenames that cannot be decoded properly are omitted rather than raising UnicodeError.

Some system APIs like os.environ and sys.argv can also present problems when the bytes made available by the system is not interpretable using the default encoding. Setting the LANG variable and rerunning the program is probably the best approach.

PEP 3138 [https://www.python.org/dev/peps/pep-3138]: The repr() of a string no longer escapes non-ASCII characters. It still escapes control characters and code points with non-printable status in the Unicode standard, however.

PEP 3120 [https://www.python.org/dev/peps/pep-3120]: The default source encoding is now UTF-8.

PEP 3131 [https://www.python.org/dev/peps/pep-3131]: Non-ASCII letters are now allowed in identifiers. (However, the standard library remains ASCII-only with the exception of contributor names in comments.)

The StringIO and cStringIO modules are gone. Instead, import the io module and use io.StringIO or io.BytesIO for text and data respectively.

See also the 유니코드 HOWTO, which was updated for Python 3.0.

Overview Of Syntax Changes

This section gives a brief overview of every syntactic change in Python 3.0.

New Syntax

PEP 3107 [https://www.python.org/dev/peps/pep-3107]: Function argument and return value annotations. This provides a standardized way of annotating a function’s parameters and return value. There are no semantics attached to such annotations except that they can be introspected at runtime using the __annotations__ attribute. The intent is to encourage experimentation through metaclasses, decorators or frameworks.

PEP 3102 [https://www.python.org/dev/peps/pep-3102]: Keyword-only arguments. Named parameters occurring after *args in the parameter list must be specified using keyword syntax in the call. You can also use a bare * in the parameter list to indicate that you don’t accept a variable-length argument list, but you do have keyword-only arguments.

Keyword arguments are allowed after the list of base classes in a class definition. This is used by the new convention for specifying a metaclass (see next section), but can be used for other purposes as well, as long as the metaclass supports it.

PEP 3104 [https://www.python.org/dev/peps/pep-3104]: nonlocal statement. Using nonlocal x you can now assign directly to a variable in an outer (but non-global) scope. nonlocal is a new reserved word.

PEP 3132 [https://www.python.org/dev/peps/pep-3132]: Extended Iterable Unpacking. You can now write things like a, b, *rest = some_sequence. And even *rest, a = stuff. The rest object is always a (possibly empty) list; the right-hand side may be any iterable. Example:

(a, *rest, b) = range(5)

This sets a to 0, b to 4, and rest to [1, 2, 3].

Dictionary comprehensions: {k: v for k, v in stuff} means the same thing as dict(stuff) but is more flexible. (This is PEP 274 [https://www.python.org/dev/peps/pep-0274] vindicated. :-)

Set literals, e.g. {1, 2}. Note that {} is an empty dictionary; use set() for an empty set. Set comprehensions are also supported; e.g., {x for x in stuff} means the same thing as set(stuff) but is more flexible.

New octal literals, e.g. 0o720 (already in 2.6). The old octal literals (0720) are gone.

New binary literals, e.g. 0b1010 (already in 2.6), and there is a new corresponding built-in function, bin().

Bytes literals are introduced with a leading b or B, and there is a new corresponding built-in function, bytes().

Changed Syntax

PEP 3109 [https://www.python.org/dev/peps/pep-3109] and PEP 3134 [https://www.python.org/dev/peps/pep-3134]: new raise statement syntax: raise [expr [from expr]]. See below.

as and with are now reserved words. (Since 2.6, actually.)

True, False, and None are reserved words. (2.6 partially enforced the restrictions on None already.)

Change from except exc, var to except exc as var. See PEP 3110 [https://www.python.org/dev/peps/pep-3110].

PEP 3115 [https://www.python.org/dev/peps/pep-3115]: New Metaclass Syntax. Instead of:

class C:
    __metaclass__ = M
    ...

you must now use:

class C(metaclass=M):
    ...

The module-global __metaclass__ variable is no longer supported. (It was a crutch to make it easier to default to new-style classes without deriving every class from object.)

List comprehensions no longer support the syntactic form [... for var in item1, item2, ...]. Use [... for var in (item1, item2, ...)] instead. Also note that list comprehensions have different semantics: they are closer to syntactic sugar for a generator expression inside a list() constructor, and in particular the loop control variables are no longer leaked into the surrounding scope.

The ellipsis (...) can be used as an atomic expression anywhere. (Previously it was only allowed in slices.) Also, it must now be spelled as .... (Previously it could also be spelled as . . ., by a mere accident of the grammar.)

Removed Syntax

PEP 3113 [https://www.python.org/dev/peps/pep-3113]: Tuple parameter unpacking removed. You can no longer write def foo(a, (b, c)): .... Use def foo(a, b_c): b, c = b_c instead.

Removed backticks (use repr() instead).

Removed <> (use != instead).

Removed keyword: exec() is no longer a keyword; it remains as a function. (Fortunately the function syntax was also accepted in 2.x.) Also note that exec() no longer takes a stream argument; instead of exec(f) you can use exec(f.read()).

Integer literals no longer support a trailing l or L.

String literals no longer support a leading u or U.

The from module import * syntax is only allowed at the module level, no longer inside functions.

The only acceptable syntax for relative imports is from .[module] import name. All import forms not starting with . are interpreted as absolute imports. (PEP 328 [https://www.python.org/dev/peps/pep-0328])

Classic classes are gone.

Changes Already Present In Python 2.6

Since many users presumably make the jump straight from Python 2.5 to Python 3.0, this section reminds the reader of new features that were originally designed for Python 3.0 but that were back-ported to Python 2.6. The corresponding sections in What’s New in Python 2.6 should be consulted for longer descriptions.

PEP 343: The ‘with’ statement. The with statement is now a standard feature and no longer needs to be imported from the __future__. Also check out Writing Context Managers and The contextlib module.

PEP 366: Explicit Relative Imports From a Main Module. This enhances the usefulness of the -m option when the referenced module lives in a package.

PEP 370: Per-user site-packages Directory.

PEP 371: The multiprocessing Package.

PEP 3101: Advanced String Formatting. Note: the 2.6 description mentions the format() method for both 8-bit and Unicode strings. In 3.0, only the str type (text strings with Unicode support) supports this method; the bytes type does not. The plan is to eventually make this the only API for string formatting, and to start deprecating the % operator in Python 3.1.

PEP 3105: print As a Function. This is now a standard feature and no longer needs to be imported from __future__. More details were given above.

PEP 3110: Exception-Handling Changes. The except exc as var syntax is now standard and except exc, var is no longer supported. (Of course, the as var part is still optional.)

PEP 3112: Byte Literals. The b"..." string literal notation (and its variants like b'...', b"""...""", and br"...") now produces a literal of type bytes.

PEP 3116: New I/O Library. The io module is now the standard way of doing file I/O. The built-in open() function is now an alias for io.open() and has additional keyword arguments encoding, errors, newline and closefd. Also note that an invalid mode argument now raises ValueError, not IOError. The binary file object underlying a text file object can be accessed as f.buffer (but beware that the text object maintains a buffer of itself in order to speed up the encoding and decoding operations).

PEP 3118: Revised Buffer Protocol. The old builtin buffer() is now really gone; the new builtin memoryview() provides (mostly) similar functionality.

PEP 3119: Abstract Base Classes. The abc module and the ABCs defined in the collections module plays a somewhat more prominent role in the language now, and built-in collection types like dict and list conform to the collections.MutableMapping and collections.MutableSequence ABCs, respectively.

PEP 3127: Integer Literal Support and Syntax. As mentioned above, the new octal literal notation is the only one supported, and binary literals have been added.

PEP 3129: Class Decorators.

PEP 3141: A Type Hierarchy for Numbers. The numbers module is another new use of ABCs, defining Python’s “numeric tower”. Also note the new fractions module which implements numbers.Rational.

Library Changes

Due to time constraints, this document does not exhaustively cover the very extensive changes to the standard library. PEP 3108 [https://www.python.org/dev/peps/pep-3108] is the reference for the major changes to the library. Here’s a capsule review:

Many old modules were removed. Some, like gopherlib (no longer used) and md5 (replaced by hashlib), were already deprecated by PEP 4 [https://www.python.org/dev/peps/pep-0004]. Others were removed as a result of the removal of support for various platforms such as Irix, BeOS and Mac OS 9 (see PEP 11 [https://www.python.org/dev/peps/pep-0011]). Some modules were also selected for removal in Python 3.0 due to lack of use or because a better replacement exists. See PEP 3108 [https://www.python.org/dev/peps/pep-3108] for an exhaustive list.

The bsddb3 package was removed because its presence in the core standard library has proved over time to be a particular burden for the core developers due to testing instability and Berkeley DB’s release schedule. However, the package is alive and well, externally maintained at https://www.jcea.es/programacion/pybsddb.htm.

Some modules were renamed because their old name disobeyed PEP 8 [https://www.python.org/dev/peps/pep-0008], or for various other reasons. Here’s the list:

Old Name

New Name

_winreg

winreg

ConfigParser

configparser

copy_reg

copyreg

Queue

queue

SocketServer

socketserver

markupbase

_markupbase

repr

reprlib

test.test_support

test.support

A common pattern in Python 2.x is to have one version of a module implemented in pure Python, with an optional accelerated version implemented as a C extension; for example, pickle and cPickle. This places the burden of importing the accelerated version and falling back on the pure Python version on each user of these modules. In Python 3.0, the accelerated versions are considered implementation details of the pure Python versions. Users should always import the standard version, which attempts to import the accelerated version and falls back to the pure Python version. The pickle / cPickle pair received this treatment. The profile module is on the list for 3.1. The StringIO module has been turned into a class in the io module.

Some related modules have been grouped into packages, and usually the submodule names have been simplified. The resulting new packages are:

dbm (anydbm, dbhash, dbm, dumbdbm, gdbm, whichdb).

html (HTMLParser, htmlentitydefs).

http (httplib, BaseHTTPServer, CGIHTTPServer, SimpleHTTPServer, Cookie, cookielib).

tkinter (all Tkinter-related modules except turtle). The target audience of turtle doesn’t really care about tkinter. Also note that as of Python 2.6, the functionality of turtle has been greatly enhanced.

urllib (urllib, urllib2, urlparse, robotparse).

xmlrpc (xmlrpclib, DocXMLRPCServer, SimpleXMLRPCServer).

Some other changes to standard library modules, not covered by PEP 3108 [https://www.python.org/dev/peps/pep-3108]:

Killed sets. Use the built-in set() class.

Cleanup of the sys module: removed sys.exitfunc(), sys.exc_clear(), sys.exc_type, sys.exc_value, sys.exc_traceback. (Note that sys.last_type etc. remain.)

Cleanup of the array.array type: the read() and write() methods are gone; use fromfile() and tofile() instead. Also, the 'c' typecode for array is gone – use either 'b' for bytes or 'u' for Unicode characters.

Cleanup of the operator module: removed sequenceIncludes() and isCallable().

Cleanup of the thread module: acquire_lock() and release_lock() are gone; use acquire() and release() instead.

Cleanup of the random module: removed the jumpahead() API.

The new module is gone.

The functions os.tmpnam(), os.tempnam() and os.tmpfile() have been removed in favor of the tempfile module.

The tokenize module has been changed to work with bytes. The main entry point is now tokenize.tokenize(), instead of generate_tokens.

string.letters and its friends (string.lowercase and string.uppercase) are gone. Use string.ascii_letters etc. instead. (The reason for the removal is that string.letters and friends had locale-specific behavior, which is a bad idea for such attractively-named global “constants”.)

Renamed module __builtin__ to builtins (removing the underscores, adding an ‘s’). The __builtins__ variable found in most global namespaces is unchanged. To modify a builtin, you should use builtins, not __builtins__!

PEP 3101 [https://www.python.org/dev/peps/pep-3101]: A New Approach To String Formatting

A new system for built-in string formatting operations replaces the % string formatting operator. (However, the % operator is still supported; it will be deprecated in Python 3.1 and removed from the language at some later time.) Read PEP 3101 [https://www.python.org/dev/peps/pep-3101] for the full scoop.

Changes To Exceptions

The APIs for raising and catching exception have been cleaned up and new powerful features added:

PEP 352 [https://www.python.org/dev/peps/pep-0352]: All exceptions must be derived (directly or indirectly) from BaseException. This is the root of the exception hierarchy. This is not new as a recommendation, but the requirement to inherit from BaseException is new. (Python 2.6 still allowed classic classes to be raised, and placed no restriction on what you can catch.) As a consequence, string exceptions are finally truly and utterly dead.

Almost all exceptions should actually derive from Exception; BaseException should only be used as a base class for exceptions that should only be handled at the top level, such as SystemExit or KeyboardInterrupt. The recommended idiom for handling all exceptions except for this latter category is to use except Exception.

StandardError was removed.

Exceptions no longer behave as sequences. Use the args attribute instead.

PEP 3109 [https://www.python.org/dev/peps/pep-3109]: Raising exceptions. You must now use raise Exception(args) instead of raise Exception, args. Additionally, you can no longer explicitly specify a traceback; instead, if you have to do this, you can assign directly to the __traceback__ attribute (see below).

PEP 3110 [https://www.python.org/dev/peps/pep-3110]: Catching exceptions. You must now use except SomeException as variable instead of except SomeException, variable. Moreover, the variable is explicitly deleted when the except block is left.

PEP 3134 [https://www.python.org/dev/peps/pep-3134]: Exception chaining. There are two cases: implicit chaining and explicit chaining. Implicit chaining happens when an exception is raised in an except or finally handler block. This usually happens due to a bug in the handler block; we call this a secondary exception. In this case, the original exception (that was being handled) is saved as the __context__ attribute of the secondary exception. Explicit chaining is invoked with this syntax:

raise SecondaryException() from primary_exception

(where primary_exception is any expression that produces an exception object, probably an exception that was previously caught). In this case, the primary exception is stored on the __cause__ attribute of the secondary exception. The traceback printed when an unhandled exception occurs walks the chain of __cause__ and __context__ attributes and prints a separate traceback for each component of the chain, with the primary exception at the top. (Java users may recognize this behavior.)

PEP 3134 [https://www.python.org/dev/peps/pep-3134]: Exception objects now store their traceback as the __traceback__ attribute. This means that an exception object now contains all the information pertaining to an exception, and there are fewer reasons to use sys.exc_info() (though the latter is not removed).

A few exception messages are improved when Windows fails to load an extension module. For example, error code 193 is now %1 is not a valid Win32 application. Strings now deal with non-English locales.

Miscellaneous Other Changes

Operators And Special Methods

!= now returns the opposite of ==, unless == returns NotImplemented.

The concept of “unbound methods” has been removed from the language. When referencing a method as a class attribute, you now get a plain function object.

__getslice__(), __setslice__() and __delslice__() were killed. The syntax a[i:j] now translates to a.__getitem__(slice(i, j)) (or __setitem__() or __delitem__(), when used as an assignment or deletion target, respectively).

PEP 3114 [https://www.python.org/dev/peps/pep-3114]: the standard next() method has been renamed to __next__().

The __oct__() and __hex__() special methods are removed – oct() and hex() use __index__() now to convert the argument to an integer.

Removed support for __members__ and __methods__.

The function attributes named func_X have been renamed to use the __X__ form, freeing up these names in the function attribute namespace for user-defined attributes. To wit, func_closure, func_code, func_defaults, func_dict, func_doc, func_globals, func_name were renamed to __closure__, __code__, __defaults__, __dict__, __doc__, __globals__, __name__, respectively.

__nonzero__() is now __bool__().

Builtins

PEP 3135 [https://www.python.org/dev/peps/pep-3135]: New super(). You can now invoke super() without arguments and (assuming this is in a regular instance method defined inside a class statement) the right class and instance will automatically be chosen. With arguments, the behavior of super() is unchanged.

PEP 3111 [https://www.python.org/dev/peps/pep-3111]: raw_input() was renamed to input(). That is, the new input() function reads a line from sys.stdin and returns it with the trailing newline stripped. It raises EOFError if the input is terminated prematurely. To get the old behavior of input(), use eval(input()).

A new built-in function next() was added to call the __next__() method on an object.

The round() function rounding strategy and return type have changed. Exact halfway cases are now rounded to the nearest even result instead of away from zero. (For example, round(2.5) now returns 2 rather than 3.) round(x[, n]) now delegates to x.__round__([n]) instead of always returning a float. It generally returns an integer when called with a single argument and a value of the same type as x when called with two arguments.

Moved intern() to sys.intern().

Removed: apply(). Instead of apply(f, args) use f(*args).

Removed callable(). Instead of callable(f) you can use isinstance(f, collections.Callable). The operator.isCallable() function is also gone.

Removed coerce(). This function no longer serves a purpose now that classic classes are gone.

Removed execfile(). Instead of execfile(fn) use exec(open(fn).read()).

Removed the file type. Use open(). There are now several different kinds of streams that open can return in the io module.

Removed reduce(). Use functools.reduce() if you really need it; however, 99 percent of the time an explicit for loop is more readable.

Removed reload(). Use imp.reload().

Removed. dict.has_key() – use the in operator instead.

Build and C API Changes

Due to time constraints, here is a very incomplete list of changes to the C API.

Support for several platforms was dropped, including but not limited to Mac OS 9, BeOS, RISCOS, Irix, and Tru64.

PEP 3118 [https://www.python.org/dev/peps/pep-3118]: New Buffer API.

PEP 3121 [https://www.python.org/dev/peps/pep-3121]: Extension Module Initialization & Finalization.

PEP 3123 [https://www.python.org/dev/peps/pep-3123]: Making PyObject_HEAD conform to standard C.

No more C API support for restricted execution.

PyNumber_Coerce(), PyNumber_CoerceEx(), PyMember_Get(), and PyMember_Set() C APIs are removed.

New C API PyImport_ImportModuleNoBlock(), works like PyImport_ImportModule() but won’t block on the import lock (returning an error instead).

Renamed the boolean conversion C-level slot and method: nb_nonzero is now nb_bool.

Removed METH_OLDARGS and WITH_CYCLE_GC from the C API.

Performance

The net result of the 3.0 generalizations is that Python 3.0 runs the pystone benchmark around 10% slower than Python 2.5. Most likely the biggest cause is the removal of special-casing for small integers. There’s room for improvement, but it will happen after 3.0 is released!

Porting To Python 3.0

For porting existing Python 2.5 or 2.6 source code to Python 3.0, the best strategy is the following:

(Prerequisite:) Start with excellent test coverage.

Port to Python 2.6. This should be no more work than the average port from Python 2.x to Python 2.(x+1). Make sure all your tests pass.

(Still using 2.6:) Turn on the -3 command line switch. This enables warnings about features that will be removed (or change) in 3.0. Run your test suite again, and fix code that you get warnings about until there are no warnings left, and all your tests still pass.

Run the 2to3 source-to-source translator over your source code tree. (See 2to3 - 파이썬 2에서 파이썬 3으로 자동 코드 변환 for more on this tool.) Run the result of the translation under Python 3.0. Manually fix up any remaining issues, fixing problems until all tests pass again.

It is not recommended to try to write source code that runs unchanged under both Python 2.6 and 3.0; you’d have to use a very contorted coding style, e.g. avoiding print statements, metaclasses, and much more. If you are maintaining a library that needs to support both Python 2.6 and Python 3.0, the best approach is to modify step 3 above by editing the 2.6 version of the source code and running the 2to3 translator again, rather than editing the 3.0 version of the source code.

For porting C extensions to Python 3.0, please see 확장 모듈을 파이썬 3에 이식하기.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬의 새로운 기능 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬의 새로운 기능 »

|

What’s New in Python 2.7

Author

A.M. Kuchling (amk at amk.ca)

This article explains the new features in Python 2.7. Python 2.7 was released on July 3, 2010.

Numeric handling has been improved in many ways, for both floating-point numbers and for the Decimal class. There are some useful additions to the standard library, such as a greatly enhanced unittest module, the argparse module for parsing command-line options, convenient OrderedDict and Counter classes in the collections module, and many other improvements.

Python 2.7 is planned to be the last of the 2.x releases, so we worked on making it a good release for the long term. To help with porting to Python 3, several new features from the Python 3.x series have been included in 2.7.

This article doesn’t attempt to provide a complete specification of the new features, but instead provides a convenient overview. For full details, you should refer to the documentation for Python 2.7 at https://docs.python.org. If you want to understand the rationale for the design and implementation, refer to the PEP for a particular new feature or the issue on https://bugs.python.org in which a change was discussed. Whenever possible, “What’s New in Python” links to the bug/patch item for each change.

The Future for Python 2.x

Python 2.7 is the last major release in the 2.x series, as the Python maintainers have shifted the focus of their new feature development efforts to the Python 3.x series. This means that while Python 2 continues to receive bug fixes, and to be updated to build correctly on new hardware and versions of supported operated systems, there will be no new full feature releases for the language or standard library.

However, while there is a large common subset between Python 2.7 and Python 3, and many of the changes involved in migrating to that common subset, or directly to Python 3, can be safely automated, some other changes (notably those associated with Unicode handling) may require careful consideration, and preferably robust automated regression test suites, to migrate effectively.

This means that Python 2.7 will remain in place for a long time, providing a stable and supported base platform for production systems that have not yet been ported to Python 3. The full expected lifecycle of the Python 2.7 series is detailed in PEP 373 [https://www.python.org/dev/peps/pep-0373].

Some key consequences of the long-term significance of 2.7 are:

As noted above, the 2.7 release has a much longer period of maintenance when compared to earlier 2.x versions. Python 2.7 is currently expected to remain supported by the core development team (receiving security updates and other bug fixes) until at least 2020 (10 years after its initial release, compared to the more typical support period of 18–24 months).

As the Python 2.7 standard library ages, making effective use of the Python Package Index (either directly or via a redistributor) becomes more important for Python 2 users. In addition to a wide variety of third party packages for various tasks, the available packages include backports of new modules and features from the Python 3 standard library that are compatible with Python 2, as well as various tools and libraries that can make it easier to migrate to Python 3. The Python Packaging User Guide [https://packaging.python.org] provides guidance on downloading and installing software from the Python Package Index.

While the preferred approach to enhancing Python 2 is now the publication of new packages on the Python Package Index, this approach doesn’t necessarily work in all cases, especially those related to network security. In exceptional cases that cannot be handled adequately by publishing new or updated packages on PyPI, the Python Enhancement Proposal process may be used to make the case for adding new features directly to the Python 2 standard library. Any such additions, and the maintenance releases where they were added, will be noted in the New Features Added to Python 2.7 Maintenance Releases section below.

For projects wishing to migrate from Python 2 to Python 3, or for library and framework developers wishing to support users on both Python 2 and Python 3, there are a variety of tools and guides available to help decide on a suitable approach and manage some of the technical details involved. The recommended starting point is the Porting Python 2 Code to Python 3 HOWTO guide.

Changes to the Handling of Deprecation Warnings

For Python 2.7, a policy decision was made to silence warnings only of interest to developers by default. DeprecationWarning and its descendants are now ignored unless otherwise requested, preventing users from seeing warnings triggered by an application. This change was also made in the branch that became Python 3.2. (Discussed on stdlib-sig and carried out in bpo-7319 [https://bugs.python.org/issue?@action=redirect&bpo=7319].)

In previous releases, DeprecationWarning messages were enabled by default, providing Python developers with a clear indication of where their code may break in a future major version of Python.

However, there are increasingly many users of Python-based applications who are not directly involved in the development of those applications. DeprecationWarning messages are irrelevant to such users, making them worry about an application that’s actually working correctly and burdening application developers with responding to these concerns.

You can re-enable display of DeprecationWarning messages by running Python with the -Wdefault (short form: -Wd) switch, or by setting the PYTHONWARNINGS environment variable to "default" (or "d") before running Python. Python code can also re-enable them by calling warnings.simplefilter('default').

The unittest module also automatically reenables deprecation warnings when running tests.

Python 3.1 Features

Much as Python 2.6 incorporated features from Python 3.0, version 2.7 incorporates some of the new features in Python 3.1. The 2.x series continues to provide tools for migrating to the 3.x series.

A partial list of 3.1 features that were backported to 2.7:

The syntax for set literals ({1,2,3} is a mutable set).

Dictionary and set comprehensions ({i: i*2 for i in range(3)}).

Multiple context managers in a single with statement.

A new version of the io library, rewritten in C for performance.

The ordered-dictionary type described in PEP 372: Adding an Ordered Dictionary to collections.

The new "," format specifier described in PEP 378: Format Specifier for Thousands Separator.

The memoryview object.

A small subset of the importlib module, described below.

The repr() of a float x is shorter in many cases: it’s now based on the shortest decimal string that’s guaranteed to round back to x. As in previous versions of Python, it’s guaranteed that float(repr(x)) recovers x.

Float-to-string and string-to-float conversions are correctly rounded. The round() function is also now correctly rounded.

The PyCapsule type, used to provide a C API for extension modules.

The PyLong_AsLongAndOverflow() C API function.

Other new Python3-mode warnings include:

operator.isCallable() and operator.sequenceIncludes(), which are not supported in 3.x, now trigger warnings.

The -3 switch now automatically enables the -Qwarn switch that causes warnings about using classic division with integers and long integers.

PEP 372: Adding an Ordered Dictionary to collections

Regular Python dictionaries iterate over key/value pairs in arbitrary order. Over the years, a number of authors have written alternative implementations that remember the order that the keys were originally inserted. Based on the experiences from those implementations, 2.7 introduces a new OrderedDict class in the collections module.

The OrderedDict API provides the same interface as regular dictionaries but iterates over keys and values in a guaranteed order depending on when a key was first inserted:

>>> from collections import OrderedDict
>>> d = OrderedDict([('first', 1),
...                  ('second', 2),
...                  ('third', 3)])
>>> d.items()
[('first', 1), ('second', 2), ('third', 3)]

If a new entry overwrites an existing entry, the original insertion position is left unchanged:

>>> d['second'] = 4
>>> d.items()
[('first', 1), ('second', 4), ('third', 3)]

Deleting an entry and reinserting it will move it to the end:

>>> del d['second']
>>> d['second'] = 5
>>> d.items()
[('first', 1), ('third', 3), ('second', 5)]

The popitem() method has an optional last argument that defaults to True. If last is true, the most recently added key is returned and removed; if it’s false, the oldest key is selected:

>>> od = OrderedDict([(x,0) for x in range(20)])
>>> od.popitem()
(19, 0)
>>> od.popitem()
(18, 0)
>>> od.popitem(last=False)
(0, 0)
>>> od.popitem(last=False)
(1, 0)

Comparing two ordered dictionaries checks both the keys and values, and requires that the insertion order was the same:

>>> od1 = OrderedDict([('first', 1),
...                    ('second', 2),
...                    ('third', 3)])
>>> od2 = OrderedDict([('third', 3),
...                    ('first', 1),
...                    ('second', 2)])
>>> od1 == od2
False
>>> # Move 'third' key to the end
>>> del od2['third']; od2['third'] = 3
>>> od1 == od2
True

Comparing an OrderedDict with a regular dictionary ignores the insertion order and just compares the keys and values.

How does the OrderedDict work? It maintains a doubly-linked list of keys, appending new keys to the list as they’re inserted. A secondary dictionary maps keys to their corresponding list node, so deletion doesn’t have to traverse the entire linked list and therefore remains O(1).

The standard library now supports use of ordered dictionaries in several modules.

The ConfigParser module uses them by default, meaning that configuration files can now be read, modified, and then written back in their original order.

The _asdict() method for collections.namedtuple() now returns an ordered dictionary with the values appearing in the same order as the underlying tuple indices.

The json module’s JSONDecoder class constructor was extended with an object_pairs_hook parameter to allow OrderedDict instances to be built by the decoder. Support was also added for third-party tools like PyYAML [http://pyyaml.org/].

더 보기

PEP 372 [https://www.python.org/dev/peps/pep-0372] - Adding an ordered dictionary to collections

PEP written by Armin Ronacher and Raymond Hettinger; implemented by Raymond Hettinger.

PEP 378: Format Specifier for Thousands Separator

To make program output more readable, it can be useful to add separators to large numbers, rendering them as 18,446,744,073,709,551,616 instead of 18446744073709551616.

The fully general solution for doing this is the locale module, which can use different separators (“,” in North America, “.” in Europe) and different grouping sizes, but locale is complicated to use and unsuitable for multi-threaded applications where different threads are producing output for different locales.

Therefore, a simple comma-grouping mechanism has been added to the mini-language used by the str.format() method. When formatting a floating-point number, simply include a comma between the width and the precision:

>>> '{:20,.2f}'.format(18446744073709551616.0)
'18,446,744,073,709,551,616.00'

When formatting an integer, include the comma after the width:

>>> '{:20,d}'.format(18446744073709551616)
'18,446,744,073,709,551,616'

This mechanism is not adaptable at all; commas are always used as the separator and the grouping is always into three-digit groups. The comma-formatting mechanism isn’t as general as the locale module, but it’s easier to use.

더 보기

PEP 378 [https://www.python.org/dev/peps/pep-0378] - Format Specifier for Thousands Separator

PEP written by Raymond Hettinger; implemented by Eric Smith.

PEP 389: The argparse Module for Parsing Command Lines

The argparse module for parsing command-line arguments was added as a more powerful replacement for the optparse module.

This means Python now supports three different modules for parsing command-line arguments: getopt, optparse, and argparse. The getopt module closely resembles the C library’s getopt() function, so it remains useful if you’re writing a Python prototype that will eventually be rewritten in C. optparse becomes redundant, but there are no plans to remove it because there are many scripts still using it, and there’s no automated way to update these scripts. (Making the argparse API consistent with optparse’s interface was discussed but rejected as too messy and difficult.)

In short, if you’re writing a new script and don’t need to worry about compatibility with earlier versions of Python, use argparse instead of optparse.

Here’s an example:

import argparse

parser = argparse.ArgumentParser(description='Command-line example.')

# Add optional switches
parser.add_argument('-v', action='store_true', dest='is_verbose',
                    help='produce verbose output')
parser.add_argument('-o', action='store', dest='output',
                    metavar='FILE',
                    help='direct output to FILE instead of stdout')
parser.add_argument('-C', action='store', type=int, dest='context',
                    metavar='NUM', default=0,
                    help='display NUM lines of added context')

# Allow any number of additional arguments.
parser.add_argument(nargs='*', action='store', dest='inputs',
                    help='input filenames (default is stdin)')

args = parser.parse_args()
print args.__dict__

Unless you override it, -h and --help switches are automatically added, and produce neatly formatted output:

-> ./python.exe argparse-example.py --help
usage: argparse-example.py [-h] [-v] [-o FILE] [-C NUM] [inputs [inputs ...]]

Command-line example.

positional arguments:
  inputs      input filenames (default is stdin)

optional arguments:
  -h, --help  show this help message and exit
  -v          produce verbose output
  -o FILE     direct output to FILE instead of stdout
  -C NUM      display NUM lines of added context

As with optparse, the command-line switches and arguments are returned as an object with attributes named by the dest parameters:

-> ./python.exe argparse-example.py -v
{'output': None,
 'is_verbose': True,
 'context': 0,
 'inputs': []}

-> ./python.exe argparse-example.py -v -o /tmp/output -C 4 file1 file2
{'output': '/tmp/output',
 'is_verbose': True,
 'context': 4,
 'inputs': ['file1', 'file2']}

argparse has much fancier validation than optparse; you can specify an exact number of arguments as an integer, 0 or more arguments by passing '*', 1 or more by passing '+', or an optional argument with '?'. A top-level parser can contain sub-parsers to define subcommands that have different sets of switches, as in svn commit, svn checkout, etc. You can specify an argument’s type as FileType, which will automatically open files for you and understands that '-' means standard input or output.

더 보기

argparse documentation

The documentation page of the argparse module.

optparse 코드 업그레이드

Part of the Python documentation, describing how to convert code that uses optparse.

PEP 389 [https://www.python.org/dev/peps/pep-0389] - argparse - New Command Line Parsing Module

PEP written and implemented by Steven Bethard.

PEP 391: Dictionary-Based Configuration For Logging

The logging module is very flexible; applications can define a tree of logging subsystems, and each logger in this tree can filter out certain messages, format them differently, and direct messages to a varying number of handlers.

All this flexibility can require a lot of configuration. You can write Python statements to create objects and set their properties, but a complex set-up requires verbose but boring code. logging also supports a fileConfig() function that parses a file, but the file format doesn’t support configuring filters, and it’s messier to generate programmatically.

Python 2.7 adds a dictConfig() function that uses a dictionary to configure logging. There are many ways to produce a dictionary from different sources: construct one with code; parse a file containing JSON; or use a YAML parsing library if one is installed. For more information see 구성 함수.

The following example configures two loggers, the root logger and a logger named “network”. Messages sent to the root logger will be sent to the system log using the syslog protocol, and messages to the “network” logger will be written to a network.log file that will be rotated once the log reaches 1MB.

import logging
import logging.config

configdict = {
 'version': 1,    # Configuration schema in use; must be 1 for now
 'formatters': {
     'standard': {
         'format': ('%(asctime)s %(name)-15s '
                    '%(levelname)-8s %(message)s')}},

 'handlers': {'netlog': {'backupCount': 10,
                     'class': 'logging.handlers.RotatingFileHandler',
                     'filename': '/logs/network.log',
                     'formatter': 'standard',
                     'level': 'INFO',
                     'maxBytes': 1000000},
              'syslog': {'class': 'logging.handlers.SysLogHandler',
                         'formatter': 'standard',
                         'level': 'ERROR'}},

 # Specify all the subordinate loggers
 'loggers': {
             'network': {
                         'handlers': ['netlog']
             }
 },
 # Specify properties of the root logger
 'root': {
          'handlers': ['syslog']
 },
}

# Set up configuration
logging.config.dictConfig(configdict)

# As an example, log two error messages
logger = logging.getLogger('/')
logger.error('Database not found')

netlogger = logging.getLogger('network')
netlogger.error('Connection failed')

Three smaller enhancements to the logging module, all implemented by Vinay Sajip, are:

The SysLogHandler class now supports syslogging over TCP. The constructor has a socktype parameter giving the type of socket to use, either socket.SOCK_DGRAM for UDP or socket.SOCK_STREAM for TCP. The default protocol remains UDP.

Logger instances gained a getChild() method that retrieves a descendant logger using a relative path. For example, once you retrieve a logger by doing log = getLogger('app'), calling log.getChild('network.listen') is equivalent to getLogger('app.network.listen').

The LoggerAdapter class gained an isEnabledFor() method that takes a level and returns whether the underlying logger would process a message of that level of importance.

더 보기

PEP 391 [https://www.python.org/dev/peps/pep-0391] - Dictionary-Based Configuration For Logging

PEP written and implemented by Vinay Sajip.

PEP 3106: Dictionary Views

The dictionary methods keys(), values(), and items() are different in Python 3.x. They return an object called a view instead of a fully materialized list.

It’s not possible to change the return values of keys(), values(), and items() in Python 2.7 because too much code would break. Instead the 3.x versions were added under the new names viewkeys(), viewvalues(), and viewitems().

>>> d = dict((i*10, chr(65+i)) for i in range(26))
>>> d
{0: 'A', 130: 'N', 10: 'B', 140: 'O', 20: ..., 250: 'Z'}
>>> d.viewkeys()
dict_keys([0, 130, 10, 140, 20, 150, 30, ..., 250])

Views can be iterated over, but the key and item views also behave like sets. The & operator performs intersection, and | performs a union:

>>> d1 = dict((i*10, chr(65+i)) for i in range(26))
>>> d2 = dict((i**.5, i) for i in range(1000))
>>> d1.viewkeys() & d2.viewkeys()
set([0.0, 10.0, 20.0, 30.0])
>>> d1.viewkeys() | range(0, 30)
set([0, 1, 130, 3, 4, 5, 6, ..., 120, 250])

The view keeps track of the dictionary and its contents change as the dictionary is modified:

>>> vk = d.viewkeys()
>>> vk
dict_keys([0, 130, 10, ..., 250])
>>> d[260] = '&'
>>> vk
dict_keys([0, 130, 260, 10, ..., 250])

However, note that you can’t add or remove keys while you’re iterating over the view:

>>> for k in vk:
...     d[k*2] = k
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
RuntimeError: dictionary changed size during iteration

You can use the view methods in Python 2.x code, and the 2to3 converter will change them to the standard keys(), values(), and items() methods.

더 보기

PEP 3106 [https://www.python.org/dev/peps/pep-3106] - Revamping dict.keys(), .values() and .items()

PEP written by Guido van Rossum. Backported to 2.7 by Alexandre Vassalotti; bpo-1967 [https://bugs.python.org/issue?@action=redirect&bpo=1967].

PEP 3137: The memoryview Object

The memoryview object provides a view of another object’s memory content that matches the bytes type’s interface.

>>> import string
>>> m = memoryview(string.letters)
>>> m
<memory at 0x37f850>
>>> len(m)           # Returns length of underlying object
52
>>> m[0], m[25], m[26]   # Indexing returns one byte
('a', 'z', 'A')
>>> m2 = m[0:26]         # Slicing returns another memoryview
>>> m2
<memory at 0x37f080>

The content of the view can be converted to a string of bytes or a list of integers:

>>> m2.tobytes()
'abcdefghijklmnopqrstuvwxyz'
>>> m2.tolist()
[97, 98, 99, 100, 101, 102, 103, ... 121, 122]
>>>

memoryview objects allow modifying the underlying object if it’s a mutable object.

>>> m2[0] = 75
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: cannot modify read-only memory
>>> b = bytearray(string.letters)  # Creating a mutable object
>>> b
bytearray(b'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')
>>> mb = memoryview(b)
>>> mb[0] = '*'         # Assign to view, changing the bytearray.
>>> b[0:5]              # The bytearray has been changed.
bytearray(b'*bcde')
>>>

더 보기

PEP 3137 [https://www.python.org/dev/peps/pep-3137] - Immutable Bytes and Mutable Buffer

PEP written by Guido van Rossum. Implemented by Travis Oliphant, Antoine Pitrou and others. Backported to 2.7 by Antoine Pitrou; bpo-2396 [https://bugs.python.org/issue?@action=redirect&bpo=2396].

Other Language Changes

Some smaller changes made to the core Python language are:

The syntax for set literals has been backported from Python 3.x. Curly brackets are used to surround the contents of the resulting mutable set; set literals are distinguished from dictionaries by not containing colons and values. {} continues to represent an empty dictionary; use set() for an empty set.

>>> {1, 2, 3, 4, 5}
set([1, 2, 3, 4, 5])
>>> set() # empty set
set([])
>>> {}    # empty dict
{}

Backported by Alexandre Vassalotti; bpo-2335 [https://bugs.python.org/issue?@action=redirect&bpo=2335].

Dictionary and set comprehensions are another feature backported from 3.x, generalizing list/generator comprehensions to use the literal syntax for sets and dictionaries.

>>> {x: x*x for x in range(6)}
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
>>> {('a'*x) for x in range(6)}
set(['', 'a', 'aa', 'aaa', 'aaaa', 'aaaaa'])

Backported by Alexandre Vassalotti; bpo-2333 [https://bugs.python.org/issue?@action=redirect&bpo=2333].

The with statement can now use multiple context managers in one statement. Context managers are processed from left to right and each one is treated as beginning a new with statement. This means that:

with A() as a, B() as b:
    ... suite of statements ...

is equivalent to:

with A() as a:
    with B() as b:
        ... suite of statements ...

The contextlib.nested() function provides a very similar function, so it’s no longer necessary and has been deprecated.

(Proposed in https://codereview.appspot.com/53094; implemented by Georg Brandl.)

Conversions between floating-point numbers and strings are now correctly rounded on most platforms. These conversions occur in many different places: str() on floats and complex numbers; the float and complex constructors; numeric formatting; serializing and deserializing floats and complex numbers using the marshal, pickle and json modules; parsing of float and imaginary literals in Python code; and Decimal-to-float conversion.

Related to this, the repr() of a floating-point number x now returns a result based on the shortest decimal string that’s guaranteed to round back to x under correct rounding (with round-half-to-even rounding mode). Previously it gave a string based on rounding x to 17 decimal digits.

The rounding library responsible for this improvement works on Windows and on Unix platforms using the gcc, icc, or suncc compilers. There may be a small number of platforms where correct operation of this code cannot be guaranteed, so the code is not used on such systems. You can find out which code is being used by checking sys.float_repr_style, which will be short if the new code is in use and legacy if it isn’t.

Implemented by Eric Smith and Mark Dickinson, using David Gay’s dtoa.c library; bpo-7117 [https://bugs.python.org/issue?@action=redirect&bpo=7117].

Conversions from long integers and regular integers to floating point now round differently, returning the floating-point number closest to the number. This doesn’t matter for small integers that can be converted exactly, but for large numbers that will unavoidably lose precision, Python 2.7 now approximates more closely. For example, Python 2.6 computed the following:

>>> n = 295147905179352891391
>>> float(n)
2.9514790517935283e+20
>>> n - long(float(n))
65535L

Python 2.7’s floating-point result is larger, but much closer to the true value:

>>> n = 295147905179352891391
>>> float(n)
2.9514790517935289e+20
>>> n - long(float(n))
-1L

(Implemented by Mark Dickinson; bpo-3166 [https://bugs.python.org/issue?@action=redirect&bpo=3166].)

Integer division is also more accurate in its rounding behaviours. (Also implemented by Mark Dickinson; bpo-1811 [https://bugs.python.org/issue?@action=redirect&bpo=1811].)

Implicit coercion for complex numbers has been removed; the interpreter will no longer ever attempt to call a __coerce__() method on complex objects. (Removed by Meador Inge and Mark Dickinson; bpo-5211 [https://bugs.python.org/issue?@action=redirect&bpo=5211].)

The str.format() method now supports automatic numbering of the replacement fields. This makes using str.format() more closely resemble using %s formatting:

>>> '{}:{}:{}'.format(2009, 04, 'Sunday')
'2009:4:Sunday'
>>> '{}:{}:{day}'.format(2009, 4, day='Sunday')
'2009:4:Sunday'

The auto-numbering takes the fields from left to right, so the first {...} specifier will use the first argument to str.format(), the next specifier will use the next argument, and so on. You can’t mix auto-numbering and explicit numbering – either number all of your specifier fields or none of them – but you can mix auto-numbering and named fields, as in the second example above. (Contributed by Eric Smith; bpo-5237 [https://bugs.python.org/issue?@action=redirect&bpo=5237].)

Complex numbers now correctly support usage with format(), and default to being right-aligned. Specifying a precision or comma-separation applies to both the real and imaginary parts of the number, but a specified field width and alignment is applied to the whole of the resulting 1.5+3j output. (Contributed by Eric Smith; bpo-1588 [https://bugs.python.org/issue?@action=redirect&bpo=1588] and bpo-7988 [https://bugs.python.org/issue?@action=redirect&bpo=7988].)

The ‘F’ format code now always formats its output using uppercase characters, so it will now produce ‘INF’ and ‘NAN’. (Contributed by Eric Smith; bpo-3382 [https://bugs.python.org/issue?@action=redirect&bpo=3382].)

A low-level change: the object.__format__() method now triggers a PendingDeprecationWarning if it’s passed a format string, because the __format__() method for object converts the object to a string representation and formats that. Previously the method silently applied the format string to the string representation, but that could hide mistakes in Python code. If you’re supplying formatting information such as an alignment or precision, presumably you’re expecting the formatting to be applied in some object-specific way. (Fixed by Eric Smith; bpo-7994 [https://bugs.python.org/issue?@action=redirect&bpo=7994].)

The int() and long() types gained a bit_length method that returns the number of bits necessary to represent its argument in binary:

>>> n = 37
>>> bin(n)
'0b100101'
>>> n.bit_length()
6
>>> n = 2**123-1
>>> n.bit_length()
123
>>> (n+1).bit_length()
124

(Contributed by Fredrik Johansson and Victor Stinner; bpo-3439 [https://bugs.python.org/issue?@action=redirect&bpo=3439].)

The import statement will no longer try an absolute import if a relative import (e.g. from .os import sep) fails. This fixes a bug, but could possibly break certain import statements that were only working by accident. (Fixed by Meador Inge; bpo-7902 [https://bugs.python.org/issue?@action=redirect&bpo=7902].)

It’s now possible for a subclass of the built-in unicode type to override the __unicode__() method. (Implemented by Victor Stinner; bpo-1583863 [https://bugs.python.org/issue?@action=redirect&bpo=1583863].)

The bytearray type’s translate() method now accepts None as its first argument. (Fixed by Georg Brandl; bpo-4759 [https://bugs.python.org/issue?@action=redirect&bpo=4759].)

When using @classmethod and @staticmethod to wrap methods as class or static methods, the wrapper object now exposes the wrapped function as their __func__ attribute. (Contributed by Amaury Forgeot d’Arc, after a suggestion by George Sakkis; bpo-5982 [https://bugs.python.org/issue?@action=redirect&bpo=5982].)

When a restricted set of attributes were set using __slots__, deleting an unset attribute would not raise AttributeError as you would expect. Fixed by Benjamin Peterson; bpo-7604 [https://bugs.python.org/issue?@action=redirect&bpo=7604].)

Two new encodings are now supported: “cp720”, used primarily for Arabic text; and “cp858”, a variant of CP 850 that adds the euro symbol. (CP720 contributed by Alexander Belchenko and Amaury Forgeot d’Arc in bpo-1616979 [https://bugs.python.org/issue?@action=redirect&bpo=1616979]; CP858 contributed by Tim Hatch in bpo-8016 [https://bugs.python.org/issue?@action=redirect&bpo=8016].)

The file object will now set the filename attribute on the IOError exception when trying to open a directory on POSIX platforms (noted by Jan Kaliszewski; bpo-4764 [https://bugs.python.org/issue?@action=redirect&bpo=4764]), and now explicitly checks for and forbids writing to read-only file objects instead of trusting the C library to catch and report the error (fixed by Stefan Krah; bpo-5677 [https://bugs.python.org/issue?@action=redirect&bpo=5677]).

The Python tokenizer now translates line endings itself, so the compile() built-in function now accepts code using any line-ending convention. Additionally, it no longer requires that the code end in a newline.

Extra parentheses in function definitions are illegal in Python 3.x, meaning that you get a syntax error from def f((x)): pass. In Python3-warning mode, Python 2.7 will now warn about this odd usage. (Noted by James Lingard; bpo-7362 [https://bugs.python.org/issue?@action=redirect&bpo=7362].)

It’s now possible to create weak references to old-style class objects. New-style classes were always weak-referenceable. (Fixed by Antoine Pitrou; bpo-8268 [https://bugs.python.org/issue?@action=redirect&bpo=8268].)

When a module object is garbage-collected, the module’s dictionary is now only cleared if no one else is holding a reference to the dictionary (bpo-7140 [https://bugs.python.org/issue?@action=redirect&bpo=7140]).

Interpreter Changes

A new environment variable, PYTHONWARNINGS, allows controlling warnings. It should be set to a string containing warning settings, equivalent to those used with the -W switch, separated by commas. (Contributed by Brian Curtin; bpo-7301 [https://bugs.python.org/issue?@action=redirect&bpo=7301].)

For example, the following setting will print warnings every time they occur, but turn warnings from the Cookie module into an error. (The exact syntax for setting an environment variable varies across operating systems and shells.)

export PYTHONWARNINGS=all,error:::Cookie:0

Optimizations

Several performance enhancements have been added:

A new opcode was added to perform the initial setup for with statements, looking up the __enter__() and __exit__() methods. (Contributed by Benjamin Peterson.)

The garbage collector now performs better for one common usage pattern: when many objects are being allocated without deallocating any of them. This would previously take quadratic time for garbage collection, but now the number of full garbage collections is reduced as the number of objects on the heap grows. The new logic only performs a full garbage collection pass when the middle generation has been collected 10 times and when the number of survivor objects from the middle generation exceeds 10% of the number of objects in the oldest generation. (Suggested by Martin von Löwis and implemented by Antoine Pitrou; bpo-4074 [https://bugs.python.org/issue?@action=redirect&bpo=4074].)

The garbage collector tries to avoid tracking simple containers which can’t be part of a cycle. In Python 2.7, this is now true for tuples and dicts containing atomic types (such as ints, strings, etc.). Transitively, a dict containing tuples of atomic types won’t be tracked either. This helps reduce the cost of each garbage collection by decreasing the number of objects to be considered and traversed by the collector. (Contributed by Antoine Pitrou; bpo-4688 [https://bugs.python.org/issue?@action=redirect&bpo=4688].)

Long integers are now stored internally either in base 2**15 or in base 2**30, the base being determined at build time. Previously, they were always stored in base 2**15. Using base 2**30 gives significant performance improvements on 64-bit machines, but benchmark results on 32-bit machines have been mixed. Therefore, the default is to use base 2**30 on 64-bit machines and base 2**15 on 32-bit machines; on Unix, there’s a new configure option --enable-big-digits that can be used to override this default.

Apart from the performance improvements this change should be invisible to end users, with one exception: for testing and debugging purposes there’s a new structseq sys.long_info that provides information about the internal format, giving the number of bits per digit and the size in bytes of the C type used to store each digit:

>>> import sys
>>> sys.long_info
sys.long_info(bits_per_digit=30, sizeof_digit=4)

(Contributed by Mark Dickinson; bpo-4258 [https://bugs.python.org/issue?@action=redirect&bpo=4258].)

Another set of changes made long objects a few bytes smaller: 2 bytes smaller on 32-bit systems and 6 bytes on 64-bit. (Contributed by Mark Dickinson; bpo-5260 [https://bugs.python.org/issue?@action=redirect&bpo=5260].)

The division algorithm for long integers has been made faster by tightening the inner loop, doing shifts instead of multiplications, and fixing an unnecessary extra iteration. Various benchmarks show speedups of between 50% and 150% for long integer divisions and modulo operations. (Contributed by Mark Dickinson; bpo-5512 [https://bugs.python.org/issue?@action=redirect&bpo=5512].) Bitwise operations are also significantly faster (initial patch by Gregory Smith; bpo-1087418 [https://bugs.python.org/issue?@action=redirect&bpo=1087418]).

The implementation of % checks for the left-side operand being a Python string and special-cases it; this results in a 1–3% performance increase for applications that frequently use % with strings, such as templating libraries. (Implemented by Collin Winter; bpo-5176 [https://bugs.python.org/issue?@action=redirect&bpo=5176].)

List comprehensions with an if condition are compiled into faster bytecode. (Patch by Antoine Pitrou, back-ported to 2.7 by Jeffrey Yasskin; bpo-4715 [https://bugs.python.org/issue?@action=redirect&bpo=4715].)

Converting an integer or long integer to a decimal string was made faster by special-casing base 10 instead of using a generalized conversion function that supports arbitrary bases. (Patch by Gawain Bolton; bpo-6713 [https://bugs.python.org/issue?@action=redirect&bpo=6713].)

The split(), replace(), rindex(), rpartition(), and rsplit() methods of string-like types (strings, Unicode strings, and bytearray objects) now use a fast reverse-search algorithm instead of a character-by-character scan. This is sometimes faster by a factor of 10. (Added by Florent Xicluna; bpo-7462 [https://bugs.python.org/issue?@action=redirect&bpo=7462] and bpo-7622 [https://bugs.python.org/issue?@action=redirect&bpo=7622].)

The pickle and cPickle modules now automatically intern the strings used for attribute names, reducing memory usage of the objects resulting from unpickling. (Contributed by Jake McGuire; bpo-5084 [https://bugs.python.org/issue?@action=redirect&bpo=5084].)

The cPickle module now special-cases dictionaries, nearly halving the time required to pickle them. (Contributed by Collin Winter; bpo-5670 [https://bugs.python.org/issue?@action=redirect&bpo=5670].)

New and Improved Modules

As in every release, Python’s standard library received a number of enhancements and bug fixes. Here’s a partial list of the most notable changes, sorted alphabetically by module name. Consult the Misc/NEWS file in the source tree for a more complete list of changes, or look through the Subversion logs for all the details.

The bdb module’s base debugging class Bdb gained a feature for skipping modules. The constructor now takes an iterable containing glob-style patterns such as django.*; the debugger will not step into stack frames from a module that matches one of these patterns. (Contributed by Maru Newby after a suggestion by Senthil Kumaran; bpo-5142 [https://bugs.python.org/issue?@action=redirect&bpo=5142].)

The binascii module now supports the buffer API, so it can be used with memoryview instances and other similar buffer objects. (Backported from 3.x by Florent Xicluna; bpo-7703 [https://bugs.python.org/issue?@action=redirect&bpo=7703].)

Updated module: the bsddb module has been updated from 4.7.2devel9 to version 4.8.4 of the pybsddb package [https://www.jcea.es/programacion/pybsddb.htm]. The new version features better Python 3.x compatibility, various bug fixes, and adds several new BerkeleyDB flags and methods. (Updated by Jesús Cea Avión; bpo-8156 [https://bugs.python.org/issue?@action=redirect&bpo=8156]. The pybsddb changelog can be read at http://hg.jcea.es/pybsddb/file/tip/ChangeLog.)

The bz2 module’s BZ2File now supports the context management protocol, so you can write with bz2.BZ2File(...) as f:. (Contributed by Hagen Fürstenau; bpo-3860 [https://bugs.python.org/issue?@action=redirect&bpo=3860].)

New class: the Counter class in the collections module is useful for tallying data. Counter instances behave mostly like dictionaries but return zero for missing keys instead of raising a KeyError:

>>> from collections import Counter
>>> c = Counter()
>>> for letter in 'here is a sample of english text':
...   c[letter] += 1
...
>>> c
Counter({' ': 6, 'e': 5, 's': 3, 'a': 2, 'i': 2, 'h': 2,
'l': 2, 't': 2, 'g': 1, 'f': 1, 'm': 1, 'o': 1, 'n': 1,
'p': 1, 'r': 1, 'x': 1})
>>> c['e']
5
>>> c['z']
0

There are three additional Counter methods. most_common() returns the N most common elements and their counts. elements() returns an iterator over the contained elements, repeating each element as many times as its count. subtract() takes an iterable and subtracts one for each element instead of adding; if the argument is a dictionary or another Counter, the counts are subtracted.

>>> c.most_common(5)
[(' ', 6), ('e', 5), ('s', 3), ('a', 2), ('i', 2)]
>>> c.elements() ->
   'a', 'a', ' ', ' ', ' ', ' ', ' ', ' ',
   'e', 'e', 'e', 'e', 'e', 'g', 'f', 'i', 'i',
   'h', 'h', 'm', 'l', 'l', 'o', 'n', 'p', 's',
   's', 's', 'r', 't', 't', 'x'
>>> c['e']
5
>>> c.subtract('very heavy on the letter e')
>>> c['e']    # Count is now lower
-1

Contributed by Raymond Hettinger; bpo-1696199 [https://bugs.python.org/issue?@action=redirect&bpo=1696199].

New class: OrderedDict is described in the earlier section PEP 372: Adding an Ordered Dictionary to collections.

New method: The deque data type now has a count() method that returns the number of contained elements equal to the supplied argument x, and a reverse() method that reverses the elements of the deque in-place. deque also exposes its maximum length as the read-only maxlen attribute. (Both features added by Raymond Hettinger.)

The namedtuple class now has an optional rename parameter. If rename is true, field names that are invalid because they’ve been repeated or aren’t legal Python identifiers will be renamed to legal names that are derived from the field’s position within the list of fields:

>>> from collections import namedtuple
>>> T = namedtuple('T', ['field1', '$illegal', 'for', 'field2'], rename=True)
>>> T._fields
('field1', '_1', '_2', 'field2')

(Added by Raymond Hettinger; bpo-1818 [https://bugs.python.org/issue?@action=redirect&bpo=1818].)

Finally, the Mapping abstract base class now returns NotImplemented if a mapping is compared to another type that isn’t a Mapping. (Fixed by Daniel Stutzbach; bpo-8729 [https://bugs.python.org/issue?@action=redirect&bpo=8729].)

Constructors for the parsing classes in the ConfigParser module now take an allow_no_value parameter, defaulting to false; if true, options without values will be allowed. For example:

>>> import ConfigParser, StringIO
>>> sample_config = """
... [mysqld]
... user = mysql
... pid-file = /var/run/mysqld/mysqld.pid
... skip-bdb
... """
>>> config = ConfigParser.RawConfigParser(allow_no_value=True)
>>> config.readfp(StringIO.StringIO(sample_config))
>>> config.get('mysqld', 'user')
'mysql'
>>> print config.get('mysqld', 'skip-bdb')
None
>>> print config.get('mysqld', 'unknown')
Traceback (most recent call last):
  ...
NoOptionError: No option 'unknown' in section: 'mysqld'

(Contributed by Mats Kindahl; bpo-7005 [https://bugs.python.org/issue?@action=redirect&bpo=7005].)

Deprecated function: contextlib.nested(), which allows handling more than one context manager with a single with statement, has been deprecated, because the with statement now supports multiple context managers.

The cookielib module now ignores cookies that have an invalid version field, one that doesn’t contain an integer value. (Fixed by John J. Lee; bpo-3924 [https://bugs.python.org/issue?@action=redirect&bpo=3924].)

The copy module’s deepcopy() function will now correctly copy bound instance methods. (Implemented by Robert Collins; bpo-1515 [https://bugs.python.org/issue?@action=redirect&bpo=1515].)

The ctypes module now always converts None to a C NULL pointer for arguments declared as pointers. (Changed by Thomas Heller; bpo-4606 [https://bugs.python.org/issue?@action=redirect&bpo=4606].) The underlying libffi library [https://sourceware.org/libffi/] has been updated to version 3.0.9, containing various fixes for different platforms. (Updated by Matthias Klose; bpo-8142 [https://bugs.python.org/issue?@action=redirect&bpo=8142].)

New method: the datetime module’s timedelta class gained a total_seconds() method that returns the number of seconds in the duration. (Contributed by Brian Quinlan; bpo-5788 [https://bugs.python.org/issue?@action=redirect&bpo=5788].)

New method: the Decimal class gained a from_float() class method that performs an exact conversion of a floating-point number to a Decimal. This exact conversion strives for the closest decimal approximation to the floating-point representation’s value; the resulting decimal value will therefore still include the inaccuracy, if any. For example, Decimal.from_float(0.1) returns Decimal('0.1000000000000000055511151231257827021181583404541015625'). (Implemented by Raymond Hettinger; bpo-4796 [https://bugs.python.org/issue?@action=redirect&bpo=4796].)

Comparing instances of Decimal with floating-point numbers now produces sensible results based on the numeric values of the operands. Previously such comparisons would fall back to Python’s default rules for comparing objects, which produced arbitrary results based on their type. Note that you still cannot combine Decimal and floating-point in other operations such as addition, since you should be explicitly choosing how to convert between float and Decimal. (Fixed by Mark Dickinson; bpo-2531 [https://bugs.python.org/issue?@action=redirect&bpo=2531].)

The constructor for Decimal now accepts floating-point numbers (added by Raymond Hettinger; bpo-8257 [https://bugs.python.org/issue?@action=redirect&bpo=8257]) and non-European Unicode characters such as Arabic-Indic digits (contributed by Mark Dickinson; bpo-6595 [https://bugs.python.org/issue?@action=redirect&bpo=6595]).

Most of the methods of the Context class now accept integers as well as Decimal instances; the only exceptions are the canonical() and is_canonical() methods. (Patch by Juan José Conti; bpo-7633 [https://bugs.python.org/issue?@action=redirect&bpo=7633].)

When using Decimal instances with a string’s format() method, the default alignment was previously left-alignment. This has been changed to right-alignment, which is more sensible for numeric types. (Changed by Mark Dickinson; bpo-6857 [https://bugs.python.org/issue?@action=redirect&bpo=6857].)

Comparisons involving a signaling NaN value (or sNAN) now signal InvalidOperation instead of silently returning a true or false value depending on the comparison operator. Quiet NaN values (or NaN) are now hashable. (Fixed by Mark Dickinson; bpo-7279 [https://bugs.python.org/issue?@action=redirect&bpo=7279].)

The difflib module now produces output that is more compatible with modern diff/patch tools through one small change, using a tab character instead of spaces as a separator in the header giving the filename. (Fixed by Anatoly Techtonik; bpo-7585 [https://bugs.python.org/issue?@action=redirect&bpo=7585].)

The Distutils sdist command now always regenerates the MANIFEST file, since even if the MANIFEST.in or setup.py files haven’t been modified, the user might have created some new files that should be included. (Fixed by Tarek Ziadé; bpo-8688 [https://bugs.python.org/issue?@action=redirect&bpo=8688].)

The doctest module’s IGNORE_EXCEPTION_DETAIL flag will now ignore the name of the module containing the exception being tested. (Patch by Lennart Regebro; bpo-7490 [https://bugs.python.org/issue?@action=redirect&bpo=7490].)

The email module’s Message class will now accept a Unicode-valued payload, automatically converting the payload to the encoding specified by output_charset. (Added by R. David Murray; bpo-1368247 [https://bugs.python.org/issue?@action=redirect&bpo=1368247].)

The Fraction class now accepts a single float or Decimal instance, or two rational numbers, as arguments to its constructor. (Implemented by Mark Dickinson; rationals added in bpo-5812 [https://bugs.python.org/issue?@action=redirect&bpo=5812], and float/decimal in bpo-8294 [https://bugs.python.org/issue?@action=redirect&bpo=8294].)

Ordering comparisons (<, <=, >, >=) between fractions and complex numbers now raise a TypeError. This fixes an oversight, making the Fraction match the other numeric types.

New class: FTP_TLS in the ftplib module provides secure FTP connections using TLS encapsulation of authentication as well as subsequent control and data transfers. (Contributed by Giampaolo Rodola; bpo-2054 [https://bugs.python.org/issue?@action=redirect&bpo=2054].)

The storbinary() method for binary uploads can now restart uploads thanks to an added rest parameter (patch by Pablo Mouzo; bpo-6845 [https://bugs.python.org/issue?@action=redirect&bpo=6845].)

New class decorator: total_ordering() in the functools module takes a class that defines an __eq__() method and one of __lt__(), __le__(), __gt__(), or __ge__(), and generates the missing comparison methods. Since the __cmp__() method is being deprecated in Python 3.x, this decorator makes it easier to define ordered classes. (Added by Raymond Hettinger; bpo-5479 [https://bugs.python.org/issue?@action=redirect&bpo=5479].)

New function: cmp_to_key() will take an old-style comparison function that expects two arguments and return a new callable that can be used as the key parameter to functions such as sorted(), min() and max(), etc. The primary intended use is to help with making code compatible with Python 3.x. (Added by Raymond Hettinger.)

New function: the gc module’s is_tracked() returns true if a given instance is tracked by the garbage collector, false otherwise. (Contributed by Antoine Pitrou; bpo-4688 [https://bugs.python.org/issue?@action=redirect&bpo=4688].)

The gzip module’s GzipFile now supports the context management protocol, so you can write with gzip.GzipFile(...) as f: (contributed by Hagen Fürstenau; bpo-3860 [https://bugs.python.org/issue?@action=redirect&bpo=3860]), and it now implements the io.BufferedIOBase ABC, so you can wrap it with io.BufferedReader for faster processing (contributed by Nir Aides; bpo-7471 [https://bugs.python.org/issue?@action=redirect&bpo=7471]). It’s also now possible to override the modification time recorded in a gzipped file by providing an optional timestamp to the constructor. (Contributed by Jacques Frechet; bpo-4272 [https://bugs.python.org/issue?@action=redirect&bpo=4272].)

Files in gzip format can be padded with trailing zero bytes; the gzip module will now consume these trailing bytes. (Fixed by Tadek Pietraszek and Brian Curtin; bpo-2846 [https://bugs.python.org/issue?@action=redirect&bpo=2846].)

New attribute: the hashlib module now has an algorithms attribute containing a tuple naming the supported algorithms. In Python 2.7, hashlib.algorithms contains ('md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512'). (Contributed by Carl Chenet; bpo-7418 [https://bugs.python.org/issue?@action=redirect&bpo=7418].)

The default HTTPResponse class used by the httplib module now supports buffering, resulting in much faster reading of HTTP responses. (Contributed by Kristján Valur Jónsson; bpo-4879 [https://bugs.python.org/issue?@action=redirect&bpo=4879].)

The HTTPConnection and HTTPSConnection classes now support a source_address parameter, a (host, port) 2-tuple giving the source address that will be used for the connection. (Contributed by Eldon Ziegler; bpo-3972 [https://bugs.python.org/issue?@action=redirect&bpo=3972].)

The ihooks module now supports relative imports. Note that ihooks is an older module for customizing imports, superseded by the imputil module added in Python 2.0. (Relative import support added by Neil Schemenauer.)

The imaplib module now supports IPv6 addresses. (Contributed by Derek Morr; bpo-1655 [https://bugs.python.org/issue?@action=redirect&bpo=1655].)

New function: the inspect module’s getcallargs() takes a callable and its positional and keyword arguments, and figures out which of the callable’s parameters will receive each argument, returning a dictionary mapping argument names to their values. For example:

>>> from inspect import getcallargs
>>> def f(a, b=1, *pos, **named):
...     pass
>>> getcallargs(f, 1, 2, 3)
{'a': 1, 'b': 2, 'pos': (3,), 'named': {}}
>>> getcallargs(f, a=2, x=4)
{'a': 2, 'b': 1, 'pos': (), 'named': {'x': 4}}
>>> getcallargs(f)
Traceback (most recent call last):
...
TypeError: f() takes at least 1 argument (0 given)

Contributed by George Sakkis; bpo-3135 [https://bugs.python.org/issue?@action=redirect&bpo=3135].

Updated module: The io library has been upgraded to the version shipped with Python 3.1. For 3.1, the I/O library was entirely rewritten in C and is 2 to 20 times faster depending on the task being performed. The original Python version was renamed to the _pyio module.

One minor resulting change: the io.TextIOBase class now has an errors attribute giving the error setting used for encoding and decoding errors (one of 'strict', 'replace', 'ignore').

The io.FileIO class now raises an OSError when passed an invalid file descriptor. (Implemented by Benjamin Peterson; bpo-4991 [https://bugs.python.org/issue?@action=redirect&bpo=4991].) The truncate() method now preserves the file position; previously it would change the file position to the end of the new file. (Fixed by Pascal Chambon; bpo-6939 [https://bugs.python.org/issue?@action=redirect&bpo=6939].)

New function: itertools.compress(data, selectors) takes two iterators. Elements of data are returned if the corresponding value in selectors is true:

itertools.compress('ABCDEF', [1,0,1,0,1,1]) =>
  A, C, E, F

New function: itertools.combinations_with_replacement(iter, r) returns all the possible r-length combinations of elements from the iterable iter. Unlike combinations(), individual elements can be repeated in the generated combinations:

itertools.combinations_with_replacement('abc', 2) =>
  ('a', 'a'), ('a', 'b'), ('a', 'c'),
  ('b', 'b'), ('b', 'c'), ('c', 'c')

Note that elements are treated as unique depending on their position in the input, not their actual values.

The itertools.count() function now has a step argument that allows incrementing by values other than 1. count() also now allows keyword arguments, and using non-integer values such as floats or Decimal instances. (Implemented by Raymond Hettinger; bpo-5032 [https://bugs.python.org/issue?@action=redirect&bpo=5032].)

itertools.combinations() and itertools.product() previously raised ValueError for values of r larger than the input iterable. This was deemed a specification error, so they now return an empty iterator. (Fixed by Raymond Hettinger; bpo-4816 [https://bugs.python.org/issue?@action=redirect&bpo=4816].)

Updated module: The json module was upgraded to version 2.0.9 of the simplejson package, which includes a C extension that makes encoding and decoding faster. (Contributed by Bob Ippolito; bpo-4136 [https://bugs.python.org/issue?@action=redirect&bpo=4136].)

To support the new collections.OrderedDict type, json.load() now has an optional object_pairs_hook parameter that will be called with any object literal that decodes to a list of pairs. (Contributed by Raymond Hettinger; bpo-5381 [https://bugs.python.org/issue?@action=redirect&bpo=5381].)

The mailbox module’s Maildir class now records the timestamp on the directories it reads, and only re-reads them if the modification time has subsequently changed. This improves performance by avoiding unneeded directory scans. (Fixed by A.M. Kuchling and Antoine Pitrou; bpo-1607951 [https://bugs.python.org/issue?@action=redirect&bpo=1607951], bpo-6896 [https://bugs.python.org/issue?@action=redirect&bpo=6896].)

New functions: the math module gained erf() and erfc() for the error function and the complementary error function, expm1() which computes e**x - 1 with more precision than using exp() and subtracting 1, gamma() for the Gamma function, and lgamma() for the natural log of the Gamma function. (Contributed by Mark Dickinson and nirinA raseliarison; bpo-3366 [https://bugs.python.org/issue?@action=redirect&bpo=3366].)

The multiprocessing module’s Manager* classes can now be passed a callable that will be called whenever a subprocess is started, along with a set of arguments that will be passed to the callable. (Contributed by lekma; bpo-5585 [https://bugs.python.org/issue?@action=redirect&bpo=5585].)

The Pool class, which controls a pool of worker processes, now has an optional maxtasksperchild parameter. Worker processes will perform the specified number of tasks and then exit, causing the Pool to start a new worker. This is useful if tasks may leak memory or other resources, or if some tasks will cause the worker to become very large. (Contributed by Charles Cazabon; bpo-6963 [https://bugs.python.org/issue?@action=redirect&bpo=6963].)

The nntplib module now supports IPv6 addresses. (Contributed by Derek Morr; bpo-1664 [https://bugs.python.org/issue?@action=redirect&bpo=1664].)

New functions: the os module wraps the following POSIX system calls: getresgid() and getresuid(), which return the real, effective, and saved GIDs and UIDs; setresgid() and setresuid(), which set real, effective, and saved GIDs and UIDs to new values; initgroups(), which initialize the group access list for the current process. (GID/UID functions contributed by Travis H.; bpo-6508 [https://bugs.python.org/issue?@action=redirect&bpo=6508]. Support for initgroups added by Jean-Paul Calderone; bpo-7333 [https://bugs.python.org/issue?@action=redirect&bpo=7333].)

The os.fork() function now re-initializes the import lock in the child process; this fixes problems on Solaris when fork() is called from a thread. (Fixed by Zsolt Cserna; bpo-7242 [https://bugs.python.org/issue?@action=redirect&bpo=7242].)

In the os.path module, the normpath() and abspath() functions now preserve Unicode; if their input path is a Unicode string, the return value is also a Unicode string. (normpath() fixed by Matt Giuca in bpo-5827 [https://bugs.python.org/issue?@action=redirect&bpo=5827]; abspath() fixed by Ezio Melotti in bpo-3426 [https://bugs.python.org/issue?@action=redirect&bpo=3426].)

The pydoc module now has help for the various symbols that Python uses. You can now do help('<<') or help('@'), for example. (Contributed by David Laban; bpo-4739 [https://bugs.python.org/issue?@action=redirect&bpo=4739].)

The re module’s split(), sub(), and subn() now accept an optional flags argument, for consistency with the other functions in the module. (Added by Gregory P. Smith.)

New function: run_path() in the runpy module will execute the code at a provided path argument. path can be the path of a Python source file (example.py), a compiled bytecode file (example.pyc), a directory (./package/), or a zip archive (example.zip). If a directory or zip path is provided, it will be added to the front of sys.path and the module __main__ will be imported. It’s expected that the directory or zip contains a __main__.py; if it doesn’t, some other __main__.py might be imported from a location later in sys.path. This makes more of the machinery of runpy available to scripts that want to mimic the way Python’s command line processes an explicit path name. (Added by Nick Coghlan; bpo-6816 [https://bugs.python.org/issue?@action=redirect&bpo=6816].)

New function: in the shutil module, make_archive() takes a filename, archive type (zip or tar-format), and a directory path, and creates an archive containing the directory’s contents. (Added by Tarek Ziadé.)

shutil’s copyfile() and copytree() functions now raise a SpecialFileError exception when asked to copy a named pipe. Previously the code would treat named pipes like a regular file by opening them for reading, and this would block indefinitely. (Fixed by Antoine Pitrou; bpo-3002 [https://bugs.python.org/issue?@action=redirect&bpo=3002].)

The signal module no longer re-installs the signal handler unless this is truly necessary, which fixes a bug that could make it impossible to catch the EINTR signal robustly. (Fixed by Charles-Francois Natali; bpo-8354 [https://bugs.python.org/issue?@action=redirect&bpo=8354].)

New functions: in the site module, three new functions return various site- and user-specific paths. getsitepackages() returns a list containing all global site-packages directories, getusersitepackages() returns the path of the user’s site-packages directory, and getuserbase() returns the value of the USER_BASE environment variable, giving the path to a directory that can be used to store data. (Contributed by Tarek Ziadé; bpo-6693 [https://bugs.python.org/issue?@action=redirect&bpo=6693].)

The site module now reports exceptions occurring when the sitecustomize module is imported, and will no longer catch and swallow the KeyboardInterrupt exception. (Fixed by Victor Stinner; bpo-3137 [https://bugs.python.org/issue?@action=redirect&bpo=3137].)

The create_connection() function gained a source_address parameter, a (host, port) 2-tuple giving the source address that will be used for the connection. (Contributed by Eldon Ziegler; bpo-3972 [https://bugs.python.org/issue?@action=redirect&bpo=3972].)

The recv_into() and recvfrom_into() methods will now write into objects that support the buffer API, most usefully the bytearray and memoryview objects. (Implemented by Antoine Pitrou; bpo-8104 [https://bugs.python.org/issue?@action=redirect&bpo=8104].)

The SocketServer module’s TCPServer class now supports socket timeouts and disabling the Nagle algorithm. The disable_nagle_algorithm class attribute defaults to False; if overridden to be true, new request connections will have the TCP_NODELAY option set to prevent buffering many small sends into a single TCP packet. The timeout class attribute can hold a timeout in seconds that will be applied to the request socket; if no request is received within that time, handle_timeout() will be called and handle_request() will return. (Contributed by Kristján Valur Jónsson; bpo-6192 [https://bugs.python.org/issue?@action=redirect&bpo=6192] and bpo-6267 [https://bugs.python.org/issue?@action=redirect&bpo=6267].)

Updated module: the sqlite3 module has been updated to version 2.6.0 of the pysqlite package [https://github.com/ghaering/pysqlite]. Version 2.6.0 includes a number of bugfixes, and adds the ability to load SQLite extensions from shared libraries. Call the enable_load_extension(True) method to enable extensions, and then call load_extension() to load a particular shared library. (Updated by Gerhard Häring.)

The ssl module’s SSLSocket objects now support the buffer API, which fixed a test suite failure (fix by Antoine Pitrou; bpo-7133 [https://bugs.python.org/issue?@action=redirect&bpo=7133]) and automatically set OpenSSL’s SSL_MODE_AUTO_RETRY, which will prevent an error code being returned from recv() operations that trigger an SSL renegotiation (fix by Antoine Pitrou; bpo-8222 [https://bugs.python.org/issue?@action=redirect&bpo=8222]).

The ssl.wrap_socket() constructor function now takes a ciphers argument that’s a string listing the encryption algorithms to be allowed; the format of the string is described in the OpenSSL documentation [https://www.openssl.org/docs/manmaster/man1/ciphers.html#CIPHER-LIST-FORMAT]. (Added by Antoine Pitrou; bpo-8322 [https://bugs.python.org/issue?@action=redirect&bpo=8322].)

Another change makes the extension load all of OpenSSL’s ciphers and digest algorithms so that they’re all available. Some SSL certificates couldn’t be verified, reporting an “unknown algorithm” error. (Reported by Beda Kosata, and fixed by Antoine Pitrou; bpo-8484 [https://bugs.python.org/issue?@action=redirect&bpo=8484].)

The version of OpenSSL being used is now available as the module attributes ssl.OPENSSL_VERSION (a string), ssl.OPENSSL_VERSION_INFO (a 5-tuple), and ssl.OPENSSL_VERSION_NUMBER (an integer). (Added by Antoine Pitrou; bpo-8321 [https://bugs.python.org/issue?@action=redirect&bpo=8321].)

The struct module will no longer silently ignore overflow errors when a value is too large for a particular integer format code (one of bBhHiIlLqQ); it now always raises a struct.error exception. (Changed by Mark Dickinson; bpo-1523 [https://bugs.python.org/issue?@action=redirect&bpo=1523].) The pack() function will also attempt to use __index__() to convert and pack non-integers before trying the __int__() method or reporting an error. (Changed by Mark Dickinson; bpo-8300 [https://bugs.python.org/issue?@action=redirect&bpo=8300].)

New function: the subprocess module’s check_output() runs a command with a specified set of arguments and returns the command’s output as a string when the command runs without error, or raises a CalledProcessError exception otherwise.

>>> subprocess.check_output(['df', '-h', '.'])
'Filesystem     Size   Used  Avail Capacity  Mounted on\n
/dev/disk0s2    52G    49G   3.0G    94%    /\n'

>>> subprocess.check_output(['df', '-h', '/bogus'])
  ...
subprocess.CalledProcessError: Command '['df', '-h', '/bogus']' returned non-zero exit status 1

(Contributed by Gregory P. Smith.)

The subprocess module will now retry its internal system calls on receiving an EINTR signal. (Reported by several people; final patch by Gregory P. Smith in bpo-1068268 [https://bugs.python.org/issue?@action=redirect&bpo=1068268].)

New function: is_declared_global() in the symtable module returns true for variables that are explicitly declared to be global, false for ones that are implicitly global. (Contributed by Jeremy Hylton.)

The syslog module will now use the value of sys.argv[0] as the identifier instead of the previous default value of 'python'. (Changed by Sean Reifschneider; bpo-8451 [https://bugs.python.org/issue?@action=redirect&bpo=8451].)

The sys.version_info value is now a named tuple, with attributes named major, minor, micro, releaselevel, and serial. (Contributed by Ross Light; bpo-4285 [https://bugs.python.org/issue?@action=redirect&bpo=4285].)

sys.getwindowsversion() also returns a named tuple, with attributes named major, minor, build, platform, service_pack, service_pack_major, service_pack_minor, suite_mask, and product_type. (Contributed by Brian Curtin; bpo-7766 [https://bugs.python.org/issue?@action=redirect&bpo=7766].)

The tarfile module’s default error handling has changed, to no longer suppress fatal errors. The default error level was previously 0, which meant that errors would only result in a message being written to the debug log, but because the debug log is not activated by default, these errors go unnoticed. The default error level is now 1, which raises an exception if there’s an error. (Changed by Lars Gustäbel; bpo-7357 [https://bugs.python.org/issue?@action=redirect&bpo=7357].)

tarfile now supports filtering the TarInfo objects being added to a tar file. When you call add(), you may supply an optional filter argument that’s a callable. The filter callable will be passed the TarInfo for every file being added, and can modify and return it. If the callable returns None, the file will be excluded from the resulting archive. This is more powerful than the existing exclude argument, which has therefore been deprecated. (Added by Lars Gustäbel; bpo-6856 [https://bugs.python.org/issue?@action=redirect&bpo=6856].) The TarFile class also now supports the context management protocol. (Added by Lars Gustäbel; bpo-7232 [https://bugs.python.org/issue?@action=redirect&bpo=7232].)

The wait() method of the threading.Event class now returns the internal flag on exit. This means the method will usually return true because wait() is supposed to block until the internal flag becomes true. The return value will only be false if a timeout was provided and the operation timed out. (Contributed by Tim Lesher; bpo-1674032 [https://bugs.python.org/issue?@action=redirect&bpo=1674032].)

The Unicode database provided by the unicodedata module is now used internally to determine which characters are numeric, whitespace, or represent line breaks. The database also includes information from the Unihan.txt data file (patch by Anders Chrigström and Amaury Forgeot d’Arc; bpo-1571184 [https://bugs.python.org/issue?@action=redirect&bpo=1571184]) and has been updated to version 5.2.0 (updated by Florent Xicluna; bpo-8024 [https://bugs.python.org/issue?@action=redirect&bpo=8024]).

The urlparse module’s urlsplit() now handles unknown URL schemes in a fashion compliant with RFC 3986 [https://tools.ietf.org/html/rfc3986.html]: if the URL is of the form "<something>://...", the text before the :// is treated as the scheme, even if it’s a made-up scheme that the module doesn’t know about. This change may break code that worked around the old behaviour. For example, Python 2.6.4 or 2.5 will return the following:

>>> import urlparse
>>> urlparse.urlsplit('invented://host/filename?query')
('invented', '', '//host/filename?query', '', '')

Python 2.7 (and Python 2.6.5) will return:

>>> import urlparse
>>> urlparse.urlsplit('invented://host/filename?query')
('invented', 'host', '/filename?query', '', '')

(Python 2.7 actually produces slightly different output, since it returns a named tuple instead of a standard tuple.)

The urlparse module also supports IPv6 literal addresses as defined by RFC 2732 [https://tools.ietf.org/html/rfc2732.html] (contributed by Senthil Kumaran; bpo-2987 [https://bugs.python.org/issue?@action=redirect&bpo=2987]).

>>> urlparse.urlparse('http://[1080::8:800:200C:417A]/foo')
ParseResult(scheme='http', netloc='[1080::8:800:200C:417A]',
            path='/foo', params='', query='', fragment='')

New class: the WeakSet class in the weakref module is a set that only holds weak references to its elements; elements will be removed once there are no references pointing to them. (Originally implemented in Python 3.x by Raymond Hettinger, and backported to 2.7 by Michael Foord.)

The ElementTree library, xml.etree, no longer escapes ampersands and angle brackets when outputting an XML processing instruction (which looks like <?xml-stylesheet href="#style1"?>) or comment (which looks like <!-- comment -->). (Patch by Neil Muller; bpo-2746 [https://bugs.python.org/issue?@action=redirect&bpo=2746].)

The XML-RPC client and server, provided by the xmlrpclib and SimpleXMLRPCServer modules, have improved performance by supporting HTTP/1.1 keep-alive and by optionally using gzip encoding to compress the XML being exchanged. The gzip compression is controlled by the encode_threshold attribute of SimpleXMLRPCRequestHandler, which contains a size in bytes; responses larger than this will be compressed. (Contributed by Kristján Valur Jónsson; bpo-6267 [https://bugs.python.org/issue?@action=redirect&bpo=6267].)

The zipfile module’s ZipFile now supports the context management protocol, so you can write with zipfile.ZipFile(...) as f:. (Contributed by Brian Curtin; bpo-5511 [https://bugs.python.org/issue?@action=redirect&bpo=5511].)

zipfile now also supports archiving empty directories and extracts them correctly. (Fixed by Kuba Wieczorek; bpo-4710 [https://bugs.python.org/issue?@action=redirect&bpo=4710].) Reading files out of an archive is faster, and interleaving read() and readline() now works correctly. (Contributed by Nir Aides; bpo-7610 [https://bugs.python.org/issue?@action=redirect&bpo=7610].)

The is_zipfile() function now accepts a file object, in addition to the path names accepted in earlier versions. (Contributed by Gabriel Genellina; bpo-4756 [https://bugs.python.org/issue?@action=redirect&bpo=4756].)

The writestr() method now has an optional compress_type parameter that lets you override the default compression method specified in the ZipFile constructor. (Contributed by Ronald Oussoren; bpo-6003 [https://bugs.python.org/issue?@action=redirect&bpo=6003].)

New module: importlib

Python 3.1 includes the importlib package, a re-implementation of the logic underlying Python’s import statement. importlib is useful for implementors of Python interpreters and to users who wish to write new importers that can participate in the import process. Python 2.7 doesn’t contain the complete importlib package, but instead has a tiny subset that contains a single function, import_module().

import_module(name, package=None) imports a module. name is a string containing the module or package’s name. It’s possible to do relative imports by providing a string that begins with a . character, such as ..utils.errors. For relative imports, the package argument must be provided and is the name of the package that will be used as the anchor for the relative import. import_module() both inserts the imported module into sys.modules and returns the module object.

Here are some examples:

>>> from importlib import import_module
>>> anydbm = import_module('anydbm')  # Standard absolute import
>>> anydbm
<module 'anydbm' from '/p/python/Lib/anydbm.py'>
>>> # Relative import
>>> file_util = import_module('..file_util', 'distutils.command')
>>> file_util
<module 'distutils.file_util' from '/python/Lib/distutils/file_util.pyc'>

importlib was implemented by Brett Cannon and introduced in Python 3.1.

New module: sysconfig

The sysconfig module has been pulled out of the Distutils package, becoming a new top-level module in its own right. sysconfig provides functions for getting information about Python’s build process: compiler switches, installation paths, the platform name, and whether Python is running from its source directory.

Some of the functions in the module are:

get_config_var() returns variables from Python’s Makefile and the pyconfig.h file.

get_config_vars() returns a dictionary containing all of the configuration variables.

get_path() returns the configured path for a particular type of module: the standard library, site-specific modules, platform-specific modules, etc.

is_python_build() returns true if you’re running a binary from a Python source tree, and false otherwise.

Consult the sysconfig documentation for more details and for a complete list of functions.

The Distutils package and sysconfig are now maintained by Tarek Ziadé, who has also started a Distutils2 package (source repository at https://hg.python.org/distutils2/) for developing a next-generation version of Distutils.

ttk: Themed Widgets for Tk

Tcl/Tk 8.5 includes a set of themed widgets that re-implement basic Tk widgets but have a more customizable appearance and can therefore more closely resemble the native platform’s widgets. This widget set was originally called Tile, but was renamed to Ttk (for “themed Tk”) on being added to Tcl/Tck release 8.5.

To learn more, read the ttk module documentation. You may also wish to read the Tcl/Tk manual page describing the Ttk theme engine, available at https://www.tcl.tk/man/tcl8.5/TkCmd/ttk_intro.htm. Some screenshots of the Python/Ttk code in use are at https://code.google.com/archive/p/python-ttk/wikis/Screenshots.wiki.

The ttk module was written by Guilherme Polo and added in bpo-2983 [https://bugs.python.org/issue?@action=redirect&bpo=2983]. An alternate version called Tile.py, written by Martin Franklin and maintained by Kevin Walzer, was proposed for inclusion in bpo-2618 [https://bugs.python.org/issue?@action=redirect&bpo=2618], but the authors argued that Guilherme Polo’s work was more comprehensive.

Updated module: unittest

The unittest module was greatly enhanced; many new features were added. Most of these features were implemented by Michael Foord, unless otherwise noted. The enhanced version of the module is downloadable separately for use with Python versions 2.4 to 2.6, packaged as the unittest2 package, from https://pypi.org/project/unittest2.

When used from the command line, the module can automatically discover tests. It’s not as fancy as py.test [http://pytest.org] or nose [https://nose.readthedocs.io/], but provides a simple way to run tests kept within a set of package directories. For example, the following command will search the test/ subdirectory for any importable test files named test*.py:

python -m unittest discover -s test

Consult the unittest module documentation for more details. (Developed in bpo-6001 [https://bugs.python.org/issue?@action=redirect&bpo=6001].)

The main() function supports some other new options:

-b or --buffer will buffer the standard output and standard error streams during each test. If the test passes, any resulting output will be discarded; on failure, the buffered output will be displayed.

-c or --catch will cause the control-C interrupt to be handled more gracefully. Instead of interrupting the test process immediately, the currently running test will be completed and then the partial results up to the interruption will be reported. If you’re impatient, a second press of control-C will cause an immediate interruption.

This control-C handler tries to avoid causing problems when the code being tested or the tests being run have defined a signal handler of their own, by noticing that a signal handler was already set and calling it. If this doesn’t work for you, there’s a removeHandler() decorator that can be used to mark tests that should have the control-C handling disabled.

-f or --failfast makes test execution stop immediately when a test fails instead of continuing to execute further tests. (Suggested by Cliff Dyer and implemented by Michael Foord; bpo-8074 [https://bugs.python.org/issue?@action=redirect&bpo=8074].)

The progress messages now show ‘x’ for expected failures and ‘u’ for unexpected successes when run in verbose mode. (Contributed by Benjamin Peterson.)

Test cases can raise the SkipTest exception to skip a test (bpo-1034053 [https://bugs.python.org/issue?@action=redirect&bpo=1034053]).

The error messages for assertEqual(), assertTrue(), and assertFalse() failures now provide more information. If you set the longMessage attribute of your TestCase classes to true, both the standard error message and any additional message you provide will be printed for failures. (Added by Michael Foord; bpo-5663 [https://bugs.python.org/issue?@action=redirect&bpo=5663].)

The assertRaises() method now returns a context handler when called without providing a callable object to run. For example, you can write this:

with self.assertRaises(KeyError):
    {}['foo']

(Implemented by Antoine Pitrou; bpo-4444 [https://bugs.python.org/issue?@action=redirect&bpo=4444].)

Module- and class-level setup and teardown fixtures are now supported. Modules can contain setUpModule() and tearDownModule() functions. Classes can have setUpClass() and tearDownClass() methods that must be defined as class methods (using @classmethod or equivalent). These functions and methods are invoked when the test runner switches to a test case in a different module or class.

The methods addCleanup() and doCleanups() were added. addCleanup() lets you add cleanup functions that will be called unconditionally (after setUp() if setUp() fails, otherwise after tearDown()). This allows for much simpler resource allocation and deallocation during tests (bpo-5679 [https://bugs.python.org/issue?@action=redirect&bpo=5679]).

A number of new methods were added that provide more specialized tests. Many of these methods were written by Google engineers for use in their test suites; Gregory P. Smith, Michael Foord, and GvR worked on merging them into Python’s version of unittest.

assertIsNone() and assertIsNotNone() take one expression and verify that the result is or is not None.

assertIs() and assertIsNot() take two values and check whether the two values evaluate to the same object or not. (Added by Michael Foord; bpo-2578 [https://bugs.python.org/issue?@action=redirect&bpo=2578].)

assertIsInstance() and assertNotIsInstance() check whether the resulting object is an instance of a particular class, or of one of a tuple of classes. (Added by Georg Brandl; bpo-7031 [https://bugs.python.org/issue?@action=redirect&bpo=7031].)

assertGreater(), assertGreaterEqual(), assertLess(), and assertLessEqual() compare two quantities.

assertMultiLineEqual() compares two strings, and if they’re not equal, displays a helpful comparison that highlights the differences in the two strings. This comparison is now used by default when Unicode strings are compared with assertEqual().

assertRegexpMatches() and assertNotRegexpMatches() checks whether the first argument is a string matching or not matching the regular expression provided as the second argument (bpo-8038 [https://bugs.python.org/issue?@action=redirect&bpo=8038]).

assertRaisesRegexp() checks whether a particular exception is raised, and then also checks that the string representation of the exception matches the provided regular expression.

assertIn() and assertNotIn() tests whether first is or is not in second.

assertItemsEqual() tests whether two provided sequences contain the same elements.

assertSetEqual() compares whether two sets are equal, and only reports the differences between the sets in case of error.

Similarly, assertListEqual() and assertTupleEqual() compare the specified types and explain any differences without necessarily printing their full values; these methods are now used by default when comparing lists and tuples using assertEqual(). More generally, assertSequenceEqual() compares two sequences and can optionally check whether both sequences are of a particular type.

assertDictEqual() compares two dictionaries and reports the differences; it’s now used by default when you compare two dictionaries using assertEqual(). assertDictContainsSubset() checks whether all of the key/value pairs in first are found in second.

assertAlmostEqual() and assertNotAlmostEqual() test whether first and second are approximately equal. This method can either round their difference to an optionally-specified number of places (the default is 7) and compare it to zero, or require the difference to be smaller than a supplied delta value.

loadTestsFromName() properly honors the suiteClass attribute of the TestLoader. (Fixed by Mark Roddy; bpo-6866 [https://bugs.python.org/issue?@action=redirect&bpo=6866].)

A new hook lets you extend the assertEqual() method to handle new data types. The addTypeEqualityFunc() method takes a type object and a function. The function will be used when both of the objects being compared are of the specified type. This function should compare the two objects and raise an exception if they don’t match; it’s a good idea for the function to provide additional information about why the two objects aren’t matching, much as the new sequence comparison methods do.

unittest.main() now takes an optional exit argument. If false, main() doesn’t call sys.exit(), allowing main() to be used from the interactive interpreter. (Contributed by J. Pablo Fernández; bpo-3379 [https://bugs.python.org/issue?@action=redirect&bpo=3379].)

TestResult has new startTestRun() and stopTestRun() methods that are called immediately before and after a test run. (Contributed by Robert Collins; bpo-5728 [https://bugs.python.org/issue?@action=redirect&bpo=5728].)

With all these changes, the unittest.py was becoming awkwardly large, so the module was turned into a package and the code split into several files (by Benjamin Peterson). This doesn’t affect how the module is imported or used.

더 보기

http://www.voidspace.org.uk/python/articles/unittest2.shtml

Describes the new features, how to use them, and the rationale for various design decisions. (By Michael Foord.)

Updated module: ElementTree 1.3

The version of the ElementTree library included with Python was updated to version 1.3. Some of the new features are:

The various parsing functions now take a parser keyword argument giving an XMLParser instance that will be used. This makes it possible to override the file’s internal encoding:

p = ET.XMLParser(encoding='utf-8')
t = ET.XML("""<root/>""", parser=p)

Errors in parsing XML now raise a ParseError exception, whose instances have a position attribute containing a (line, column) tuple giving the location of the problem.

ElementTree’s code for converting trees to a string has been significantly reworked, making it roughly twice as fast in many cases. The ElementTree.write() and Element.write() methods now have a method parameter that can be “xml” (the default), “html”, or “text”. HTML mode will output empty elements as <empty></empty> instead of <empty/>, and text mode will skip over elements and only output the text chunks. If you set the tag attribute of an element to None but leave its children in place, the element will be omitted when the tree is written out, so you don’t need to do more extensive rearrangement to remove a single element.

Namespace handling has also been improved. All xmlns:<whatever> declarations are now output on the root element, not scattered throughout the resulting XML. You can set the default namespace for a tree by setting the default_namespace attribute and can register new prefixes with register_namespace(). In XML mode, you can use the true/false xml_declaration parameter to suppress the XML declaration.

New Element method: extend() appends the items from a sequence to the element’s children. Elements themselves behave like sequences, so it’s easy to move children from one element to another:

from xml.etree import ElementTree as ET

t = ET.XML("""<list>
  <item>1</item> <item>2</item>  <item>3</item>
</list>""")
new = ET.XML('<root/>')
new.extend(t)

# Outputs <root><item>1</item>...</root>
print ET.tostring(new)

New Element method: iter() yields the children of the element as a generator. It’s also possible to write for child in elem: to loop over an element’s children. The existing method getiterator() is now deprecated, as is getchildren() which constructs and returns a list of children.

New Element method: itertext() yields all chunks of text that are descendants of the element. For example:

t = ET.XML("""<list>
  <item>1</item> <item>2</item>  <item>3</item>
</list>""")

# Outputs ['\n  ', '1', ' ', '2', '  ', '3', '\n']
print list(t.itertext())

Deprecated: using an element as a Boolean (i.e., if elem:) would return true if the element had any children, or false if there were no children. This behaviour is confusing – None is false, but so is a childless element? – so it will now trigger a FutureWarning. In your code, you should be explicit: write len(elem) != 0 if you’re interested in the number of children, or elem is not None.

Fredrik Lundh develops ElementTree and produced the 1.3 version; you can read his article describing 1.3 at http://effbot.org/zone/elementtree-13-intro.htm. Florent Xicluna updated the version included with Python, after discussions on python-dev and in bpo-6472 [https://bugs.python.org/issue?@action=redirect&bpo=6472].)

Build and C API Changes

Changes to Python’s build process and to the C API include:

The latest release of the GNU Debugger, GDB 7, can be scripted using Python [https://sourceware.org/gdb/current/onlinedocs/gdb/Python.html]. When you begin debugging an executable program P, GDB will look for a file named P-gdb.py and automatically read it. Dave Malcolm contributed a python-gdb.py that adds a number of commands useful when debugging Python itself. For example, py-up and py-down go up or down one Python stack frame, which usually corresponds to several C stack frames. py-print prints the value of a Python variable, and py-bt prints the Python stack trace. (Added as a result of bpo-8032 [https://bugs.python.org/issue?@action=redirect&bpo=8032].)

If you use the .gdbinit file provided with Python, the “pyo” macro in the 2.7 version now works correctly when the thread being debugged doesn’t hold the GIL; the macro now acquires it before printing. (Contributed by Victor Stinner; bpo-3632 [https://bugs.python.org/issue?@action=redirect&bpo=3632].)

Py_AddPendingCall() is now thread-safe, letting any worker thread submit notifications to the main Python thread. This is particularly useful for asynchronous IO operations. (Contributed by Kristján Valur Jónsson; bpo-4293 [https://bugs.python.org/issue?@action=redirect&bpo=4293].)

New function: PyCode_NewEmpty() creates an empty code object; only the filename, function name, and first line number are required. This is useful for extension modules that are attempting to construct a more useful traceback stack. Previously such extensions needed to call PyCode_New(), which had many more arguments. (Added by Jeffrey Yasskin.)

New function: PyErr_NewExceptionWithDoc() creates a new exception class, just as the existing PyErr_NewException() does, but takes an extra char * argument containing the docstring for the new exception class. (Added by ‘lekma’ on the Python bug tracker; bpo-7033 [https://bugs.python.org/issue?@action=redirect&bpo=7033].)

New function: PyFrame_GetLineNumber() takes a frame object and returns the line number that the frame is currently executing. Previously code would need to get the index of the bytecode instruction currently executing, and then look up the line number corresponding to that address. (Added by Jeffrey Yasskin.)

New functions: PyLong_AsLongAndOverflow() and PyLong_AsLongLongAndOverflow() approximates a Python long integer as a C long or long long. If the number is too large to fit into the output type, an overflow flag is set and returned to the caller. (Contributed by Case Van Horsen; bpo-7528 [https://bugs.python.org/issue?@action=redirect&bpo=7528] and bpo-7767 [https://bugs.python.org/issue?@action=redirect&bpo=7767].)

New function: stemming from the rewrite of string-to-float conversion, a new PyOS_string_to_double() function was added. The old PyOS_ascii_strtod() and PyOS_ascii_atof() functions are now deprecated.

New function: PySys_SetArgvEx() sets the value of sys.argv and can optionally update sys.path to include the directory containing the script named by sys.argv[0] depending on the value of an updatepath parameter.

This function was added to close a security hole for applications that embed Python. The old function, PySys_SetArgv(), would always update sys.path, and sometimes it would add the current directory. This meant that, if you ran an application embedding Python in a directory controlled by someone else, attackers could put a Trojan-horse module in the directory (say, a file named os.py) that your application would then import and run.

If you maintain a C/C++ application that embeds Python, check whether you’re calling PySys_SetArgv() and carefully consider whether the application should be using PySys_SetArgvEx() with updatepath set to false.

Security issue reported as CVE-2008-5983 [https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2008-5983]; discussed in bpo-5753 [https://bugs.python.org/issue?@action=redirect&bpo=5753], and fixed by Antoine Pitrou.

New macros: the Python header files now define the following macros: Py_ISALNUM, Py_ISALPHA, Py_ISDIGIT, Py_ISLOWER, Py_ISSPACE, Py_ISUPPER, Py_ISXDIGIT, Py_TOLOWER, and Py_TOUPPER. All of these functions are analogous to the C standard macros for classifying characters, but ignore the current locale setting, because in several places Python needs to analyze characters in a locale-independent way. (Added by Eric Smith; bpo-5793 [https://bugs.python.org/issue?@action=redirect&bpo=5793].)

Removed function: PyEval_CallObject is now only available as a macro. A function version was being kept around to preserve ABI linking compatibility, but that was in 1997; it can certainly be deleted by now. (Removed by Antoine Pitrou; bpo-8276 [https://bugs.python.org/issue?@action=redirect&bpo=8276].)

New format codes: the PyFormat_FromString(), PyFormat_FromStringV(), and PyErr_Format() functions now accept %lld and %llu format codes for displaying C’s long long types. (Contributed by Mark Dickinson; bpo-7228 [https://bugs.python.org/issue?@action=redirect&bpo=7228].)

The complicated interaction between threads and process forking has been changed. Previously, the child process created by os.fork() might fail because the child is created with only a single thread running, the thread performing the os.fork(). If other threads were holding a lock, such as Python’s import lock, when the fork was performed, the lock would still be marked as “held” in the new process. But in the child process nothing would ever release the lock, since the other threads weren’t replicated, and the child process would no longer be able to perform imports.

Python 2.7 acquires the import lock before performing an os.fork(), and will also clean up any locks created using the threading module. C extension modules that have internal locks, or that call fork() themselves, will not benefit from this clean-up.

(Fixed by Thomas Wouters; bpo-1590864 [https://bugs.python.org/issue?@action=redirect&bpo=1590864].)

The Py_Finalize() function now calls the internal threading._shutdown() function; this prevents some exceptions from being raised when an interpreter shuts down. (Patch by Adam Olsen; bpo-1722344 [https://bugs.python.org/issue?@action=redirect&bpo=1722344].)

When using the PyMemberDef structure to define attributes of a type, Python will no longer let you try to delete or set a T_STRING_INPLACE attribute.

Global symbols defined by the ctypes module are now prefixed with Py, or with _ctypes. (Implemented by Thomas Heller; bpo-3102 [https://bugs.python.org/issue?@action=redirect&bpo=3102].)

New configure option: the --with-system-expat switch allows building the pyexpat module to use the system Expat library. (Contributed by Arfrever Frehtes Taifersar Arahesis; bpo-7609 [https://bugs.python.org/issue?@action=redirect&bpo=7609].)

New configure option: the --with-valgrind option will now disable the pymalloc allocator, which is difficult for the Valgrind memory-error detector to analyze correctly. Valgrind will therefore be better at detecting memory leaks and overruns. (Contributed by James Henstridge; bpo-2422 [https://bugs.python.org/issue?@action=redirect&bpo=2422].)

New configure option: you can now supply an empty string to --with-dbmliborder= in order to disable all of the various DBM modules. (Added by Arfrever Frehtes Taifersar Arahesis; bpo-6491 [https://bugs.python.org/issue?@action=redirect&bpo=6491].)

The configure script now checks for floating-point rounding bugs on certain 32-bit Intel chips and defines a X87_DOUBLE_ROUNDING preprocessor definition. No code currently uses this definition, but it’s available if anyone wishes to use it. (Added by Mark Dickinson; bpo-2937 [https://bugs.python.org/issue?@action=redirect&bpo=2937].)

configure also now sets a LDCXXSHARED Makefile variable for supporting C++ linking. (Contributed by Arfrever Frehtes Taifersar Arahesis; bpo-1222585 [https://bugs.python.org/issue?@action=redirect&bpo=1222585].)

The build process now creates the necessary files for pkg-config support. (Contributed by Clinton Roy; bpo-3585 [https://bugs.python.org/issue?@action=redirect&bpo=3585].)

The build process now supports Subversion 1.7. (Contributed by Arfrever Frehtes Taifersar Arahesis; bpo-6094 [https://bugs.python.org/issue?@action=redirect&bpo=6094].)

Capsules

Python 3.1 adds a new C datatype, PyCapsule, for providing a C API to an extension module. A capsule is essentially the holder of a C void * pointer, and is made available as a module attribute; for example, the socket module’s API is exposed as socket.CAPI, and unicodedata exposes ucnhash_CAPI. Other extensions can import the module, access its dictionary to get the capsule object, and then get the void * pointer, which will usually point to an array of pointers to the module’s various API functions.

There is an existing data type already used for this, PyCObject, but it doesn’t provide type safety. Evil code written in pure Python could cause a segmentation fault by taking a PyCObject from module A and somehow substituting it for the PyCObject in module B. Capsules know their own name, and getting the pointer requires providing the name:

void *vtable;

if (!PyCapsule_IsValid(capsule, "mymodule.CAPI") {
        PyErr_SetString(PyExc_ValueError, "argument type invalid");
        return NULL;
}

vtable = PyCapsule_GetPointer(capsule, "mymodule.CAPI");

You are assured that vtable points to whatever you’re expecting. If a different capsule was passed in, PyCapsule_IsValid() would detect the mismatched name and return false. Refer to Providing a C API for an Extension Module for more information on using these objects.

Python 2.7 now uses capsules internally to provide various extension-module APIs, but the PyCObject_AsVoidPtr() was modified to handle capsules, preserving compile-time compatibility with the CObject interface. Use of PyCObject_AsVoidPtr() will signal a PendingDeprecationWarning, which is silent by default.

Implemented in Python 3.1 and backported to 2.7 by Larry Hastings; discussed in bpo-5630 [https://bugs.python.org/issue?@action=redirect&bpo=5630].

Port-Specific Changes: Windows

The msvcrt module now contains some constants from the crtassem.h header file: CRT_ASSEMBLY_VERSION, VC_ASSEMBLY_PUBLICKEYTOKEN, and LIBRARIES_ASSEMBLY_NAME_PREFIX. (Contributed by David Cournapeau; bpo-4365 [https://bugs.python.org/issue?@action=redirect&bpo=4365].)

The _winreg module for accessing the registry now implements the CreateKeyEx() and DeleteKeyEx() functions, extended versions of previously-supported functions that take several extra arguments. The DisableReflectionKey(), EnableReflectionKey(), and QueryReflectionKey() were also tested and documented. (Implemented by Brian Curtin: bpo-7347 [https://bugs.python.org/issue?@action=redirect&bpo=7347].)

The new _beginthreadex() API is used to start threads, and the native thread-local storage functions are now used. (Contributed by Kristján Valur Jónsson; bpo-3582 [https://bugs.python.org/issue?@action=redirect&bpo=3582].)

The os.kill() function now works on Windows. The signal value can be the constants CTRL_C_EVENT, CTRL_BREAK_EVENT, or any integer. The first two constants will send Control-C and Control-Break keystroke events to subprocesses; any other value will use the TerminateProcess() API. (Contributed by Miki Tebeka; bpo-1220212 [https://bugs.python.org/issue?@action=redirect&bpo=1220212].)

The os.listdir() function now correctly fails for an empty path. (Fixed by Hirokazu Yamamoto; bpo-5913 [https://bugs.python.org/issue?@action=redirect&bpo=5913].)

The mimelib module will now read the MIME database from the Windows registry when initializing. (Patch by Gabriel Genellina; bpo-4969 [https://bugs.python.org/issue?@action=redirect&bpo=4969].)

Port-Specific Changes: Mac OS X

The path /Library/Python/2.7/site-packages is now appended to sys.path, in order to share added packages between the system installation and a user-installed copy of the same version. (Changed by Ronald Oussoren; bpo-4865 [https://bugs.python.org/issue?@action=redirect&bpo=4865].)

버전 2.7.13에서 변경: As of 2.7.13, this change was removed. /Library/Python/2.7/site-packages, the site-packages directory used by the Apple-supplied system Python 2.7 is no longer appended to sys.path for user-installed Pythons such as from the python.org installers. As of macOS 10.12, Apple changed how the system site-packages directory is configured, which could cause installation of pip components, like setuptools, to fail. Packages installed for the system Python will no longer be shared with user-installed Pythons. (bpo-28440 [https://bugs.python.org/issue?@action=redirect&bpo=28440])

Port-Specific Changes: FreeBSD

FreeBSD 7.1’s SO_SETFIB constant, used with getsockopt()/setsockopt() to select an alternate routing table, is now available in the socket module. (Added by Kyle VanderBeek; bpo-8235 [https://bugs.python.org/issue?@action=redirect&bpo=8235].)

Other Changes and Fixes

Two benchmark scripts, iobench and ccbench, were added to the Tools directory. iobench measures the speed of the built-in file I/O objects returned by open() while performing various operations, and ccbench is a concurrency benchmark that tries to measure computing throughput, thread switching latency, and IO processing bandwidth when performing several tasks using a varying number of threads.

The Tools/i18n/msgfmt.py script now understands plural forms in .po files. (Fixed by Martin von Löwis; bpo-5464 [https://bugs.python.org/issue?@action=redirect&bpo=5464].)

When importing a module from a .pyc or .pyo file with an existing .py counterpart, the co_filename attributes of the resulting code objects are overwritten when the original filename is obsolete. This can happen if the file has been renamed, moved, or is accessed through different paths. (Patch by Ziga Seilnacht and Jean-Paul Calderone; bpo-1180193 [https://bugs.python.org/issue?@action=redirect&bpo=1180193].)

The regrtest.py script now takes a --randseed= switch that takes an integer that will be used as the random seed for the -r option that executes tests in random order. The -r option also reports the seed that was used (Added by Collin Winter.)

Another regrtest.py switch is -j, which takes an integer specifying how many tests run in parallel. This allows reducing the total runtime on multi-core machines. This option is compatible with several other options, including the -R switch which is known to produce long runtimes. (Added by Antoine Pitrou, bpo-6152 [https://bugs.python.org/issue?@action=redirect&bpo=6152].) This can also be used with a new -F switch that runs selected tests in a loop until they fail. (Added by Antoine Pitrou; bpo-7312 [https://bugs.python.org/issue?@action=redirect&bpo=7312].)

When executed as a script, the py_compile.py module now accepts '-' as an argument, which will read standard input for the list of filenames to be compiled. (Contributed by Piotr Ożarowski; bpo-8233 [https://bugs.python.org/issue?@action=redirect&bpo=8233].)

Porting to Python 2.7

This section lists previously described changes and other bugfixes that may require changes to your code:

The range() function processes its arguments more consistently; it will now call __int__() on non-float, non-integer arguments that are supplied to it. (Fixed by Alexander Belopolsky; bpo-1533 [https://bugs.python.org/issue?@action=redirect&bpo=1533].)

The string format() method changed the default precision used for floating-point and complex numbers from 6 decimal places to 12, which matches the precision used by str(). (Changed by Eric Smith; bpo-5920 [https://bugs.python.org/issue?@action=redirect&bpo=5920].)

Because of an optimization for the with statement, the special methods __enter__() and __exit__() must belong to the object’s type, and cannot be directly attached to the object’s instance. This affects new-style classes (derived from object) and C extension types. (bpo-6101 [https://bugs.python.org/issue?@action=redirect&bpo=6101].)

Due to a bug in Python 2.6, the exc_value parameter to __exit__() methods was often the string representation of the exception, not an instance. This was fixed in 2.7, so exc_value will be an instance as expected. (Fixed by Florent Xicluna; bpo-7853 [https://bugs.python.org/issue?@action=redirect&bpo=7853].)

When a restricted set of attributes were set using __slots__, deleting an unset attribute would not raise AttributeError as you would expect. Fixed by Benjamin Peterson; bpo-7604 [https://bugs.python.org/issue?@action=redirect&bpo=7604].)

In the standard library:

Operations with datetime instances that resulted in a year falling outside the supported range didn’t always raise OverflowError. Such errors are now checked more carefully and will now raise the exception. (Reported by Mark Leander, patch by Anand B. Pillai and Alexander Belopolsky; bpo-7150 [https://bugs.python.org/issue?@action=redirect&bpo=7150].)

When using Decimal instances with a string’s format() method, the default alignment was previously left-alignment. This has been changed to right-alignment, which might change the output of your programs. (Changed by Mark Dickinson; bpo-6857 [https://bugs.python.org/issue?@action=redirect&bpo=6857].)

Comparisons involving a signaling NaN value (or sNAN) now signal InvalidOperation instead of silently returning a true or false value depending on the comparison operator. Quiet NaN values (or NaN) are now hashable. (Fixed by Mark Dickinson; bpo-7279 [https://bugs.python.org/issue?@action=redirect&bpo=7279].)

The ElementTree library, xml.etree, no longer escapes ampersands and angle brackets when outputting an XML processing instruction (which looks like <?xml-stylesheet href=”#style1”?>) or comment (which looks like <!– comment –>). (Patch by Neil Muller; bpo-2746 [https://bugs.python.org/issue?@action=redirect&bpo=2746].)

The readline() method of StringIO objects now does nothing when a negative length is requested, as other file-like objects do. (bpo-7348 [https://bugs.python.org/issue?@action=redirect&bpo=7348]).

The syslog module will now use the value of sys.argv[0] as the identifier instead of the previous default value of 'python'. (Changed by Sean Reifschneider; bpo-8451 [https://bugs.python.org/issue?@action=redirect&bpo=8451].)

The tarfile module’s default error handling has changed, to no longer suppress fatal errors. The default error level was previously 0, which meant that errors would only result in a message being written to the debug log, but because the debug log is not activated by default, these errors go unnoticed. The default error level is now 1, which raises an exception if there’s an error. (Changed by Lars Gustäbel; bpo-7357 [https://bugs.python.org/issue?@action=redirect&bpo=7357].)

The urlparse module’s urlsplit() now handles unknown URL schemes in a fashion compliant with RFC 3986 [https://tools.ietf.org/html/rfc3986.html]: if the URL is of the form "<something>://...", the text before the :// is treated as the scheme, even if it’s a made-up scheme that the module doesn’t know about. This change may break code that worked around the old behaviour. For example, Python 2.6.4 or 2.5 will return the following:

>>> import urlparse
>>> urlparse.urlsplit('invented://host/filename?query')
('invented', '', '//host/filename?query', '', '')

Python 2.7 (and Python 2.6.5) will return:

>>> import urlparse
>>> urlparse.urlsplit('invented://host/filename?query')
('invented', 'host', '/filename?query', '', '')

(Python 2.7 actually produces slightly different output, since it returns a named tuple instead of a standard tuple.)

For C extensions:

C extensions that use integer format codes with the PyArg_Parse* family of functions will now raise a TypeError exception instead of triggering a DeprecationWarning (bpo-5080 [https://bugs.python.org/issue?@action=redirect&bpo=5080]).

Use the new PyOS_string_to_double() function instead of the old PyOS_ascii_strtod() and PyOS_ascii_atof() functions, which are now deprecated.

For applications that embed Python:

The PySys_SetArgvEx() function was added, letting applications close a security hole when the existing PySys_SetArgv() function was used. Check whether you’re calling PySys_SetArgv() and carefully consider whether the application should be using PySys_SetArgvEx() with updatepath set to false.

New Features Added to Python 2.7 Maintenance Releases

New features may be added to Python 2.7 maintenance releases when the situation genuinely calls for it. Any such additions must go through the Python Enhancement Proposal process, and make a compelling case for why they can’t be adequately addressed by either adding the new feature solely to Python 3, or else by publishing it on the Python Package Index.

In addition to the specific proposals listed below, there is a general exemption allowing new -3 warnings to be added in any Python 2.7 maintenance release.

Two new environment variables for debug mode

In debug mode, the [xxx refs] statistic is not written by default, the PYTHONSHOWREFCOUNT environment variable now must also be set. (Contributed by Victor Stinner; bpo-31733 [https://bugs.python.org/issue?@action=redirect&bpo=31733].)

When Python is compiled with COUNT_ALLOC defined, allocation counts are no longer dumped by default anymore: the PYTHONSHOWALLOCCOUNT environment variable must now also be set. Moreover, allocation counts are now dumped into stderr, rather than stdout. (Contributed by Victor Stinner; bpo-31692 [https://bugs.python.org/issue?@action=redirect&bpo=31692].)

버전 2.7.15에 추가.

PEP 434: IDLE Enhancement Exception for All Branches

PEP 434 [https://www.python.org/dev/peps/pep-0434] describes a general exemption for changes made to the IDLE development environment shipped along with Python. This exemption makes it possible for the IDLE developers to provide a more consistent user experience across all supported versions of Python 2 and 3.

For details of any IDLE changes, refer to the NEWS file for the specific release.

PEP 466: Network Security Enhancements for Python 2.7

PEP 466 [https://www.python.org/dev/peps/pep-0466] describes a number of network security enhancement proposals that have been approved for inclusion in Python 2.7 maintenance releases, with the first of those changes appearing in the Python 2.7.7 release.

PEP 466 [https://www.python.org/dev/peps/pep-0466] related features added in Python 2.7.7:

hmac.compare_digest() was backported from Python 3 to make a timing attack resistant comparison operation available to Python 2 applications. (Contributed by Alex Gaynor; bpo-21306 [https://bugs.python.org/issue?@action=redirect&bpo=21306].)

OpenSSL 1.0.1g was upgraded in the official Windows installers published on python.org. (Contributed by Zachary Ware; bpo-21462 [https://bugs.python.org/issue?@action=redirect&bpo=21462].)

PEP 466 [https://www.python.org/dev/peps/pep-0466] related features added in Python 2.7.8:

hashlib.pbkdf2_hmac() was backported from Python 3 to make a hashing algorithm suitable for secure password storage broadly available to Python 2 applications. (Contributed by Alex Gaynor; bpo-21304 [https://bugs.python.org/issue?@action=redirect&bpo=21304].)

OpenSSL 1.0.1h was upgraded for the official Windows installers published on python.org. (contributed by Zachary Ware in bpo-21671 [https://bugs.python.org/issue?@action=redirect&bpo=21671] for CVE-2014-0224)

PEP 466 [https://www.python.org/dev/peps/pep-0466] related features added in Python 2.7.9:

Most of Python 3.4’s ssl module was backported. This means ssl now supports Server Name Indication, TLS1.x settings, access to the platform certificate store, the SSLContext class, and other features. (Contributed by Alex Gaynor and David Reid; bpo-21308 [https://bugs.python.org/issue?@action=redirect&bpo=21308].)

Refer to the “Version added: 2.7.9” notes in the module documentation for specific details.

os.urandom() was changed to cache a file descriptor to /dev/urandom instead of reopening /dev/urandom on every call. (Contributed by Alex Gaynor; bpo-21305 [https://bugs.python.org/issue?@action=redirect&bpo=21305].)

hashlib.algorithms_guaranteed and hashlib.algorithms_available were backported from Python 3 to make it easier for Python 2 applications to select the strongest available hash algorithm. (Contributed by Alex Gaynor in bpo-21307 [https://bugs.python.org/issue?@action=redirect&bpo=21307])

PEP 477: Backport ensurepip (PEP 453) to Python 2.7

PEP 477 [https://www.python.org/dev/peps/pep-0477] approves the inclusion of the PEP 453 [https://www.python.org/dev/peps/pep-0453] ensurepip module and the improved documentation that was enabled by it in the Python 2.7 maintenance releases, appearing first in the Python 2.7.9 release.

Bootstrapping pip By Default

The new ensurepip module (defined in PEP 453 [https://www.python.org/dev/peps/pep-0453]) provides a standard cross-platform mechanism to bootstrap the pip installer into Python installations. The version of pip included with Python 2.7.9 is pip 1.5.6, and future 2.7.x maintenance releases will update the bundled version to the latest version of pip that is available at the time of creating the release candidate.

By default, the commands pip, pipX and pipX.Y will be installed on all platforms (where X.Y stands for the version of the Python installation), along with the pip Python package and its dependencies.

For CPython source builds on POSIX systems, the make install and make altinstall commands do not bootstrap pip by default. This behaviour can be controlled through configure options, and overridden through Makefile options.

On Windows and Mac OS X, the CPython installers now default to installing pip along with CPython itself (users may opt out of installing it during the installation process). Window users will need to opt in to the automatic PATH modifications to have pip available from the command line by default, otherwise it can still be accessed through the Python launcher for Windows as py -m pip.

As discussed in the PEP [https://www.python.org/dev/peps/pep-0477/#disabling-ensurepip-by-downstream-distributors], platform packagers may choose not to install these commands by default, as long as, when invoked, they provide clear and simple directions on how to install them on that platform (usually using the system package manager).

Documentation Changes

As part of this change, the 파이썬 모듈 설치하기 and 파이썬 모듈 배포하기 sections of the documentation have been completely redesigned as short getting started and FAQ documents. Most packaging documentation has now been moved out to the Python Packaging Authority maintained Python Packaging User Guide [http://packaging.python.org] and the documentation of the individual projects.

However, as this migration is currently still incomplete, the legacy versions of those guides remaining available as 파이썬 모듈 설치 (레거시 버전) and 파이썬 모듈 배포 (레거시 버전).

더 보기

PEP 453 [https://www.python.org/dev/peps/pep-0453] – Explicit bootstrapping of pip in Python installations

PEP written by Donald Stufft and Nick Coghlan, implemented by Donald Stufft, Nick Coghlan, Martin von Löwis and Ned Deily.

PEP 476: Enabling certificate verification by default for stdlib http clients

PEP 476 [https://www.python.org/dev/peps/pep-0476] updated httplib and modules which use it, such as urllib2 and xmlrpclib, to now verify that the server presents a certificate which is signed by a Certificate Authority in the platform trust store and whose hostname matches the hostname being requested by default, significantly improving security for many applications. This change was made in the Python 2.7.9 release.

For applications which require the old previous behavior, they can pass an alternate context:

import urllib2
import ssl

# This disables all verification
context = ssl._create_unverified_context()

# This allows using a specific certificate for the host, which doesn't need
# to be in the trust store
context = ssl.create_default_context(cafile="/path/to/file.crt")

urllib2.urlopen("https://invalid-cert", context=context)

PEP 493: HTTPS verification migration tools for Python 2.7

PEP 493 [https://www.python.org/dev/peps/pep-0493] provides additional migration tools to support a more incremental infrastructure upgrade process for environments containing applications and services relying on the historically permissive processing of server certificates when establishing client HTTPS connections. These additions were made in the Python 2.7.12 release.

These tools are intended for use in cases where affected applications and services can’t be modified to explicitly pass a more permissive SSL context when establishing the connection.

For applications and services which can’t be modified at all, the new PYTHONHTTPSVERIFY environment variable may be set to 0 to revert an entire Python process back to the default permissive behaviour of Python 2.7.8 and earlier.

For cases where the connection establishment code can’t be modified, but the overall application can be, the new ssl._https_verify_certificates() function can be used to adjust the default behaviour at runtime.

New make regen-all build target

To simplify cross-compilation, and to ensure that CPython can reliably be compiled without requiring an existing version of Python to already be available, the autotools-based build system no longer attempts to implicitly recompile generated files based on file modification times.

Instead, a new make regen-all command has been added to force regeneration of these files when desired (e.g. after an initial version of Python has already been built based on the pregenerated versions).

More selective regeneration targets are also defined - see Makefile.pre.in [https://github.com/python/cpython/tree/3.7/Makefile.pre.in] for details.

(Contributed by Victor Stinner in bpo-23404 [https://bugs.python.org/issue?@action=redirect&bpo=23404].)

버전 2.7.14에 추가.

Removal of make touch build target

The make touch build target previously used to request implicit regeneration of generated files by updating their modification times has been removed.

It has been replaced by the new make regen-all target.

(Contributed by Victor Stinner in bpo-23404 [https://bugs.python.org/issue?@action=redirect&bpo=23404].)

버전 2.7.14에서 변경.

Acknowledgements

The author would like to thank the following people for offering suggestions, corrections and assistance with various drafts of this article: Nick Coghlan, Philip Jenvey, Ryan Lovett, R. David Murray, Hugh Secker-Walker.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬의 새로운 기능 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬의 새로운 기능 »

|

What’s New in Python 2.6

Author

A.M. Kuchling (amk at amk.ca)

This article explains the new features in Python 2.6, released on October 1 2008. The release schedule is described in PEP 361 [https://www.python.org/dev/peps/pep-0361].

The major theme of Python 2.6 is preparing the migration path to Python 3.0, a major redesign of the language. Whenever possible, Python 2.6 incorporates new features and syntax from 3.0 while remaining compatible with existing code by not removing older features or syntax. When it’s not possible to do that, Python 2.6 tries to do what it can, adding compatibility functions in a future_builtins module and a -3 switch to warn about usages that will become unsupported in 3.0.

Some significant new packages have been added to the standard library, such as the multiprocessing and json modules, but there aren’t many new features that aren’t related to Python 3.0 in some way.

Python 2.6 also sees a number of improvements and bugfixes throughout the source. A search through the change logs finds there were 259 patches applied and 612 bugs fixed between Python 2.5 and 2.6. Both figures are likely to be underestimates.

This article doesn’t attempt to provide a complete specification of the new features, but instead provides a convenient overview. For full details, you should refer to the documentation for Python 2.6. If you want to understand the rationale for the design and implementation, refer to the PEP for a particular new feature. Whenever possible, “What’s New in Python” links to the bug/patch item for each change.

Python 3.0

The development cycle for Python versions 2.6 and 3.0 was synchronized, with the alpha and beta releases for both versions being made on the same days. The development of 3.0 has influenced many features in 2.6.

Python 3.0 is a far-ranging redesign of Python that breaks compatibility with the 2.x series. This means that existing Python code will need some conversion in order to run on Python 3.0. However, not all the changes in 3.0 necessarily break compatibility. In cases where new features won’t cause existing code to break, they’ve been backported to 2.6 and are described in this document in the appropriate place. Some of the 3.0-derived features are:

A __complex__() method for converting objects to a complex number.

Alternate syntax for catching exceptions: except TypeError as exc.

The addition of functools.reduce() as a synonym for the built-in reduce() function.

Python 3.0 adds several new built-in functions and changes the semantics of some existing builtins. Functions that are new in 3.0 such as bin() have simply been added to Python 2.6, but existing builtins haven’t been changed; instead, the future_builtins module has versions with the new 3.0 semantics. Code written to be compatible with 3.0 can do from future_builtins import hex, map as necessary.

A new command-line switch, -3, enables warnings about features that will be removed in Python 3.0. You can run code with this switch to see how much work will be necessary to port code to 3.0. The value of this switch is available to Python code as the boolean variable sys.py3kwarning, and to C extension code as Py_Py3kWarningFlag.

더 보기

The 3xxx series of PEPs, which contains proposals for Python 3.0. PEP 3000 [https://www.python.org/dev/peps/pep-3000] describes the development process for Python 3.0. Start with PEP 3100 [https://www.python.org/dev/peps/pep-3100] that describes the general goals for Python 3.0, and then explore the higher-numbered PEPS that propose specific features.

Changes to the Development Process

While 2.6 was being developed, the Python development process underwent two significant changes: we switched from SourceForge’s issue tracker to a customized Roundup installation, and the documentation was converted from LaTeX to reStructuredText.

New Issue Tracker: Roundup

For a long time, the Python developers had been growing increasingly annoyed by SourceForge’s bug tracker. SourceForge’s hosted solution doesn’t permit much customization; for example, it wasn’t possible to customize the life cycle of issues.

The infrastructure committee of the Python Software Foundation therefore posted a call for issue trackers, asking volunteers to set up different products and import some of the bugs and patches from SourceForge. Four different trackers were examined: Jira [https://www.atlassian.com/software/jira/], Launchpad [https://launchpad.net/], Roundup [http://roundup.sourceforge.net/], and Trac [https://trac.edgewall.org/]. The committee eventually settled on Jira and Roundup as the two candidates. Jira is a commercial product that offers no-cost hosted instances to free-software projects; Roundup is an open-source project that requires volunteers to administer it and a server to host it.

After posting a call for volunteers, a new Roundup installation was set up at https://bugs.python.org. One installation of Roundup can host multiple trackers, and this server now also hosts issue trackers for Jython and for the Python web site. It will surely find other uses in the future. Where possible, this edition of “What’s New in Python” links to the bug/patch item for each change.

Hosting of the Python bug tracker is kindly provided by Upfront Systems [http://www.upfrontsoftware.co.za] of Stellenbosch, South Africa. Martin von Löwis put a lot of effort into importing existing bugs and patches from SourceForge; his scripts for this import operation are at http://svn.python.org/view/tracker/importer/ and may be useful to other projects wishing to move from SourceForge to Roundup.

더 보기

https://bugs.python.org

The Python bug tracker.

http://bugs.jython.org:

The Jython bug tracker.

http://roundup.sourceforge.net/

Roundup downloads and documentation.

http://svn.python.org/view/tracker/importer/

Martin von Löwis’s conversion scripts.

New Documentation Format: reStructuredText Using Sphinx

The Python documentation was written using LaTeX since the project started around 1989. In the 1980s and early 1990s, most documentation was printed out for later study, not viewed online. LaTeX was widely used because it provided attractive printed output while remaining straightforward to write once the basic rules of the markup were learned.

Today LaTeX is still used for writing publications destined for printing, but the landscape for programming tools has shifted. We no longer print out reams of documentation; instead, we browse through it online and HTML has become the most important format to support. Unfortunately, converting LaTeX to HTML is fairly complicated and Fred L. Drake Jr., the long-time Python documentation editor, spent a lot of time maintaining the conversion process. Occasionally people would suggest converting the documentation into SGML and later XML, but performing a good conversion is a major task and no one ever committed the time required to finish the job.

During the 2.6 development cycle, Georg Brandl put a lot of effort into building a new toolchain for processing the documentation. The resulting package is called Sphinx, and is available from http://sphinx-doc.org/.

Sphinx concentrates on HTML output, producing attractively styled and modern HTML; printed output is still supported through conversion to LaTeX. The input format is reStructuredText, a markup syntax supporting custom extensions and directives that is commonly used in the Python community.

Sphinx is a standalone package that can be used for writing, and almost two dozen other projects (listed on the Sphinx web site [https://www.sphinx-doc.org/en/master/examples.html]) have adopted Sphinx as their documentation tool.

더 보기

Documenting Python [https://devguide.python.org/documenting/]

Describes how to write for Python’s documentation.

Sphinx [http://sphinx-doc.org/]

Documentation and code for the Sphinx toolchain.

Docutils [http://docutils.sourceforge.net]

The underlying reStructuredText parser and toolset.

PEP 343: The ‘with’ statement

The previous version, Python 2.5, added the ‘with’ statement as an optional feature, to be enabled by a from __future__ import with_statement directive. In 2.6 the statement no longer needs to be specially enabled; this means that with is now always a keyword. The rest of this section is a copy of the corresponding section from the “What’s New in Python 2.5” document; if you’re familiar with the ‘with’ statement from Python 2.5, you can skip this section.

The ‘with’ statement clarifies code that previously would use try...finally blocks to ensure that clean-up code is executed. In this section, I’ll discuss the statement as it will commonly be used. In the next section, I’ll examine the implementation details and show how to write objects for use with this statement.

The ‘with’ statement is a control-flow structure whose basic structure is:

with expression [as variable]:
    with-block

The expression is evaluated, and it should result in an object that supports the context management protocol (that is, has __enter__() and __exit__() methods).

The object’s __enter__() is called before with-block is executed and therefore can run set-up code. It also may return a value that is bound to the name variable, if given. (Note carefully that variable is not assigned the result of expression.)

After execution of the with-block is finished, the object’s __exit__() method is called, even if the block raised an exception, and can therefore run clean-up code.

Some standard Python objects now support the context management protocol and can be used with the ‘with’ statement. File objects are one example:

with open('/etc/passwd', 'r') as f:
    for line in f:
        print line
        ... more processing code ...

After this statement has executed, the file object in f will have been automatically closed, even if the for loop raised an exception part-way through the block.

참고

In this case, f is the same object created by open(), because file.__enter__() returns self.

The threading module’s locks and condition variables also support the ‘with’ statement:

lock = threading.Lock()
with lock:
    # Critical section of code
    ...

The lock is acquired before the block is executed and always released once the block is complete.

The localcontext() function in the decimal module makes it easy to save and restore the current decimal context, which encapsulates the desired precision and rounding characteristics for computations:

from decimal import Decimal, Context, localcontext

# Displays with default precision of 28 digits
v = Decimal('578')
print v.sqrt()

with localcontext(Context(prec=16)):
    # All code in this block uses a precision of 16 digits.
    # The original context is restored on exiting the block.
    print v.sqrt()

Writing Context Managers

Under the hood, the ‘with’ statement is fairly complicated. Most people will only use ‘with’ in company with existing objects and don’t need to know these details, so you can skip the rest of this section if you like. Authors of new objects will need to understand the details of the underlying implementation and should keep reading.

A high-level explanation of the context management protocol is:

The expression is evaluated and should result in an object called a “context manager”. The context manager must have __enter__() and __exit__() methods.

The context manager’s __enter__() method is called. The value returned is assigned to VAR. If no as VAR clause is present, the value is simply discarded.

The code in BLOCK is executed.

If BLOCK raises an exception, the context manager’s __exit__() method is called with three arguments, the exception details (type, value, traceback, the same values returned by sys.exc_info(), which can also be None if no exception occurred). The method’s return value controls whether an exception is re-raised: any false value re-raises the exception, and True will result in suppressing it. You’ll only rarely want to suppress the exception, because if you do the author of the code containing the ‘with’ statement will never realize anything went wrong.

If BLOCK didn’t raise an exception, the __exit__() method is still called, but type, value, and traceback are all None.

Let’s think through an example. I won’t present detailed code but will only sketch the methods necessary for a database that supports transactions.

(For people unfamiliar with database terminology: a set of changes to the database are grouped into a transaction. Transactions can be either committed, meaning that all the changes are written into the database, or rolled back, meaning that the changes are all discarded and the database is unchanged. See any database textbook for more information.)

Let’s assume there’s an object representing a database connection. Our goal will be to let the user write code like this:

db_connection = DatabaseConnection()
with db_connection as cursor:
    cursor.execute('insert into ...')
    cursor.execute('delete from ...')
    # ... more operations ...

The transaction should be committed if the code in the block runs flawlessly or rolled back if there’s an exception. Here’s the basic interface for DatabaseConnection that I’ll assume:

class DatabaseConnection:
    # Database interface
    def cursor(self):
        "Returns a cursor object and starts a new transaction"
    def commit(self):
        "Commits current transaction"
    def rollback(self):
        "Rolls back current transaction"

The __enter__() method is pretty easy, having only to start a new transaction. For this application the resulting cursor object would be a useful result, so the method will return it. The user can then add as cursor to their ‘with’ statement to bind the cursor to a variable name.

class DatabaseConnection:
    ...
    def __enter__(self):
        # Code to start a new transaction
        cursor = self.cursor()
        return cursor

The __exit__() method is the most complicated because it’s where most of the work has to be done. The method has to check if an exception occurred. If there was no exception, the transaction is committed. The transaction is rolled back if there was an exception.

In the code below, execution will just fall off the end of the function, returning the default value of None. None is false, so the exception will be re-raised automatically. If you wished, you could be more explicit and add a return statement at the marked location.

class DatabaseConnection:
    ...
    def __exit__(self, type, value, tb):
        if tb is None:
            # No exception, so commit
            self.commit()
        else:
            # Exception occurred, so rollback.
            self.rollback()
            # return False

The contextlib module

The contextlib module provides some functions and a decorator that are useful when writing objects for use with the ‘with’ statement.

The decorator is called contextmanager(), and lets you write a single generator function instead of defining a new class. The generator should yield exactly one value. The code up to the yield will be executed as the __enter__() method, and the value yielded will be the method’s return value that will get bound to the variable in the ‘with’ statement’s as clause, if any. The code after the yield will be executed in the __exit__() method. Any exception raised in the block will be raised by the yield statement.

Using this decorator, our database example from the previous section could be written as:

from contextlib import contextmanager

@contextmanager
def db_transaction(connection):
    cursor = connection.cursor()
    try:
        yield cursor
    except:
        connection.rollback()
        raise
    else:
        connection.commit()

db = DatabaseConnection()
with db_transaction(db) as cursor:
    ...

The contextlib module also has a nested(mgr1, mgr2, ...) function that combines a number of context managers so you don’t need to write nested ‘with’ statements. In this example, the single ‘with’ statement both starts a database transaction and acquires a thread lock:

lock = threading.Lock()
with nested (db_transaction(db), lock) as (cursor, locked):
    ...

Finally, the closing() function returns its argument so that it can be bound to a variable, and calls the argument’s .close() method at the end of the block.

import urllib, sys
from contextlib import closing

with closing(urllib.urlopen('http://www.yahoo.com')) as f:
    for line in f:
        sys.stdout.write(line)

더 보기

PEP 343 [https://www.python.org/dev/peps/pep-0343] - The “with” statement

PEP written by Guido van Rossum and Nick Coghlan; implemented by Mike Bland, Guido van Rossum, and Neal Norwitz. The PEP shows the code generated for a ‘with’ statement, which can be helpful in learning how the statement works.

The documentation for the contextlib module.

PEP 366: Explicit Relative Imports From a Main Module

Python’s -m switch allows running a module as a script. When you ran a module that was located inside a package, relative imports didn’t work correctly.

The fix for Python 2.6 adds a __package__ attribute to modules. When this attribute is present, relative imports will be relative to the value of this attribute instead of the __name__ attribute.

PEP 302-style importers can then set __package__ as necessary. The runpy module that implements the -m switch now does this, so relative imports will now work correctly in scripts running from inside a package.

PEP 370: Per-user site-packages Directory

When you run Python, the module search path sys.path usually includes a directory whose path ends in "site-packages". This directory is intended to hold locally-installed packages available to all users using a machine or a particular site installation.

Python 2.6 introduces a convention for user-specific site directories. The directory varies depending on the platform:

Unix and Mac OS X: ~/.local/

Windows: %APPDATA%/Python

Within this directory, there will be version-specific subdirectories, such as lib/python2.6/site-packages on Unix/Mac OS and Python26/site-packages on Windows.

If you don’t like the default directory, it can be overridden by an environment variable. PYTHONUSERBASE sets the root directory used for all Python versions supporting this feature. On Windows, the directory for application-specific data can be changed by setting the APPDATA environment variable. You can also modify the site.py file for your Python installation.

The feature can be disabled entirely by running Python with the -s option or setting the PYTHONNOUSERSITE environment variable.

더 보기

PEP 370 [https://www.python.org/dev/peps/pep-0370] - Per-user site-packages Directory

PEP written and implemented by Christian Heimes.

PEP 371: The multiprocessing Package

The new multiprocessing package lets Python programs create new processes that will perform a computation and return a result to the parent. The parent and child processes can communicate using queues and pipes, synchronize their operations using locks and semaphores, and can share simple arrays of data.

The multiprocessing module started out as an exact emulation of the threading module using processes instead of threads. That goal was discarded along the path to Python 2.6, but the general approach of the module is still similar. The fundamental class is the Process, which is passed a callable object and a collection of arguments. The start() method sets the callable running in a subprocess, after which you can call the is_alive() method to check whether the subprocess is still running and the join() method to wait for the process to exit.

Here’s a simple example where the subprocess will calculate a factorial. The function doing the calculation is written strangely so that it takes significantly longer when the input argument is a multiple of 4.

import time
from multiprocessing import Process, Queue

def factorial(queue, N):
    "Compute a factorial."
    # If N is a multiple of 4, this function will take much longer.
    if (N % 4) == 0:
        time.sleep(.05 * N/4)

    # Calculate the result
    fact = 1L
    for i in range(1, N+1):
        fact = fact * i

    # Put the result on the queue
    queue.put(fact)

if __name__ == '__main__':
    queue = Queue()

    N = 5

    p = Process(target=factorial, args=(queue, N))
    p.start()
    p.join()

    result = queue.get()
    print 'Factorial', N, '=', result

A Queue is used to communicate the result of the factorial. The Queue object is stored in a global variable. The child process will use the value of the variable when the child was created; because it’s a Queue, parent and child can use the object to communicate. (If the parent were to change the value of the global variable, the child’s value would be unaffected, and vice versa.)

Two other classes, Pool and Manager, provide higher-level interfaces. Pool will create a fixed number of worker processes, and requests can then be distributed to the workers by calling apply() or apply_async() to add a single request, and map() or map_async() to add a number of requests. The following code uses a Pool to spread requests across 5 worker processes and retrieve a list of results:

from multiprocessing import Pool

def factorial(N, dictionary):
    "Compute a factorial."
    ...
p = Pool(5)
result = p.map(factorial, range(1, 1000, 10))
for v in result:
    print v

This produces the following output:

1
39916800
51090942171709440000
8222838654177922817725562880000000
33452526613163807108170062053440751665152000000000
...

The other high-level interface, the Manager class, creates a separate server process that can hold master copies of Python data structures. Other processes can then access and modify these data structures using proxy objects. The following example creates a shared dictionary by calling the dict() method; the worker processes then insert values into the dictionary. (Locking is not done for you automatically, which doesn’t matter in this example. Manager’s methods also include Lock(), RLock(), and Semaphore() to create shared locks.)

import time
from multiprocessing import Pool, Manager

def factorial(N, dictionary):
    "Compute a factorial."
    # Calculate the result
    fact = 1L
    for i in range(1, N+1):
        fact = fact * i

    # Store result in dictionary
    dictionary[N] = fact

if __name__ == '__main__':
    p = Pool(5)
    mgr = Manager()
    d = mgr.dict()         # Create shared dictionary

    # Run tasks using the pool
    for N in range(1, 1000, 10):
        p.apply_async(factorial, (N, d))

    # Mark pool as closed -- no more tasks can be added.
    p.close()

    # Wait for tasks to exit
    p.join()

    # Output results
    for k, v in sorted(d.items()):
        print k, v

This will produce the output:

1 1
11 39916800
21 51090942171709440000
31 8222838654177922817725562880000000
41 33452526613163807108170062053440751665152000000000
51 15511187532873822802242430164693032110632597200169861120000...

더 보기

The documentation for the multiprocessing module.

PEP 371 [https://www.python.org/dev/peps/pep-0371] - Addition of the multiprocessing package

PEP written by Jesse Noller and Richard Oudkerk; implemented by Richard Oudkerk and Jesse Noller.

PEP 3101: Advanced String Formatting

In Python 3.0, the % operator is supplemented by a more powerful string formatting method, format(). Support for the str.format() method has been backported to Python 2.6.

In 2.6, both 8-bit and Unicode strings have a .format() method that treats the string as a template and takes the arguments to be formatted. The formatting template uses curly brackets ({, }) as special characters:

>>> # Substitute positional argument 0 into the string.
>>> "User ID: {0}".format("root")
'User ID: root'
>>> # Use the named keyword arguments
>>> "User ID: {uid}   Last seen: {last_login}".format(
...    uid="root",
...    last_login = "5 Mar 2008 07:20")
'User ID: root   Last seen: 5 Mar 2008 07:20'

Curly brackets can be escaped by doubling them:

>>> "Empty dict: {{}}".format()
"Empty dict: {}"

Field names can be integers indicating positional arguments, such as {0}, {1}, etc. or names of keyword arguments. You can also supply compound field names that read attributes or access dictionary keys:

>>> import sys
>>> print 'Platform: {0.platform}\nPython version: {0.version}'.format(sys)
Platform: darwin
Python version: 2.6a1+ (trunk:61261M, Mar  5 2008, 20:29:41)
[GCC 4.0.1 (Apple Computer, Inc. build 5367)]'

>>> import mimetypes
>>> 'Content-type: {0[.mp4]}'.format(mimetypes.types_map)
'Content-type: video/mp4'

Note that when using dictionary-style notation such as [.mp4], you don’t need to put any quotation marks around the string; it will look up the value using .mp4 as the key. Strings beginning with a number will be converted to an integer. You can’t write more complicated expressions inside a format string.

So far we’ve shown how to specify which field to substitute into the resulting string. The precise formatting used is also controllable by adding a colon followed by a format specifier. For example:

>>> # Field 0: left justify, pad to 15 characters
>>> # Field 1: right justify, pad to 6 characters
>>> fmt = '{0:15} ${1:>6}'
>>> fmt.format('Registration', 35)
'Registration    $    35'
>>> fmt.format('Tutorial', 50)
'Tutorial        $    50'
>>> fmt.format('Banquet', 125)
'Banquet         $   125'

Format specifiers can reference other fields through nesting:

>>> fmt = '{0:{1}}'
>>> width = 15
>>> fmt.format('Invoice #1234', width)
'Invoice #1234  '
>>> width = 35
>>> fmt.format('Invoice #1234', width)
'Invoice #1234                      '

The alignment of a field within the desired width can be specified:

Character

Effect

< (default)

Left-align

>

Right-align

^

Center

=

(For numeric types only) Pad after the sign.

Format specifiers can also include a presentation type, which controls how the value is formatted. For example, floating-point numbers can be formatted as a general number or in exponential notation:

>>> '{0:g}'.format(3.75)
'3.75'
>>> '{0:e}'.format(3.75)
'3.750000e+00'

A variety of presentation types are available. Consult the 2.6 documentation for a complete list; here’s a sample:

b

Binary. Outputs the number in base 2.

c

Character. Converts the integer to the corresponding Unicode character before printing.

d

Decimal Integer. Outputs the number in base 10.

o

Octal format. Outputs the number in base 8.

x

Hex format. Outputs the number in base 16, using lower-case letters for the digits above 9.

e

Exponent notation. Prints the number in scientific notation using the letter ‘e’ to indicate the exponent.

g

General format. This prints the number as a fixed-point number, unless the number is too large, in which case it switches to ‘e’ exponent notation.

n

Number. This is the same as ‘g’ (for floats) or ‘d’ (for integers), except that it uses the current locale setting to insert the appropriate number separator characters.

%

Percentage. Multiplies the number by 100 and displays in fixed (‘f’) format, followed by a percent sign.

Classes and types can define a __format__() method to control how they’re formatted. It receives a single argument, the format specifier:

def __format__(self, format_spec):
    if isinstance(format_spec, unicode):
        return unicode(str(self))
    else:
        return str(self)

There’s also a format() builtin that will format a single value. It calls the type’s __format__() method with the provided specifier:

>>> format(75.6564, '.2f')
'75.66'

더 보기

포맷 문자열 문법

The reference documentation for format fields.

PEP 3101 [https://www.python.org/dev/peps/pep-3101] - Advanced String Formatting

PEP written by Talin. Implemented by Eric Smith.

PEP 3105: print As a Function

The print statement becomes the print() function in Python 3.0. Making print() a function makes it possible to replace the function by doing def print(...) or importing a new function from somewhere else.

Python 2.6 has a __future__ import that removes print as language syntax, letting you use the functional form instead. For example:

>>> from __future__ import print_function
>>> print('# of entries', len(dictionary), file=sys.stderr)

The signature of the new function is:

def print(*args, sep=' ', end='\n', file=None)

The parameters are:

args: positional arguments whose values will be printed out.

sep: the separator, which will be printed between arguments.

end: the ending text, which will be printed after all of the arguments have been output.

file: the file object to which the output will be sent.

더 보기

PEP 3105 [https://www.python.org/dev/peps/pep-3105] - Make print a function

PEP written by Georg Brandl.

PEP 3110: Exception-Handling Changes

One error that Python programmers occasionally make is writing the following code:

try:
    ...
except TypeError, ValueError:  # Wrong!
    ...

The author is probably trying to catch both TypeError and ValueError exceptions, but this code actually does something different: it will catch TypeError and bind the resulting exception object to the local name "ValueError". The ValueError exception will not be caught at all. The correct code specifies a tuple of exceptions:

try:
    ...
except (TypeError, ValueError):
    ...

This error happens because the use of the comma here is ambiguous: does it indicate two different nodes in the parse tree, or a single node that’s a tuple?

Python 3.0 makes this unambiguous by replacing the comma with the word “as”. To catch an exception and store the exception object in the variable exc, you must write:

try:
    ...
except TypeError as exc:
    ...

Python 3.0 will only support the use of “as”, and therefore interprets the first example as catching two different exceptions. Python 2.6 supports both the comma and “as”, so existing code will continue to work. We therefore suggest using “as” when writing new Python code that will only be executed with 2.6.

더 보기

PEP 3110 [https://www.python.org/dev/peps/pep-3110] - Catching Exceptions in Python 3000

PEP written and implemented by Collin Winter.

PEP 3112: Byte Literals

Python 3.0 adopts Unicode as the language’s fundamental string type and denotes 8-bit literals differently, either as b'string' or using a bytes constructor. For future compatibility, Python 2.6 adds bytes as a synonym for the str type, and it also supports the b'' notation.

The 2.6 str differs from 3.0’s bytes type in various ways; most notably, the constructor is completely different. In 3.0, bytes([65, 66, 67]) is 3 elements long, containing the bytes representing ABC; in 2.6, bytes([65, 66, 67]) returns the 12-byte string representing the str() of the list.

The primary use of bytes in 2.6 will be to write tests of object type such as isinstance(x, bytes). This will help the 2to3 converter, which can’t tell whether 2.x code intends strings to contain either characters or 8-bit bytes; you can now use either bytes or str to represent your intention exactly, and the resulting code will also be correct in Python 3.0.

There’s also a __future__ import that causes all string literals to become Unicode strings. This means that \u escape sequences can be used to include Unicode characters:

from __future__ import unicode_literals

s = ('\u751f\u3080\u304e\u3000\u751f\u3054'
     '\u3081\u3000\u751f\u305f\u307e\u3054')

print len(s)               # 12 Unicode characters

At the C level, Python 3.0 will rename the existing 8-bit string type, called PyStringObject in Python 2.x, to PyBytesObject. Python 2.6 uses #define to support using the names PyBytesObject(), PyBytes_Check(), PyBytes_FromStringAndSize(), and all the other functions and macros used with strings.

Instances of the bytes type are immutable just as strings are. A new bytearray type stores a mutable sequence of bytes:

>>> bytearray([65, 66, 67])
bytearray(b'ABC')
>>> b = bytearray(u'\u21ef\u3244', 'utf-8')
>>> b
bytearray(b'\xe2\x87\xaf\xe3\x89\x84')
>>> b[0] = '\xe3'
>>> b
bytearray(b'\xe3\x87\xaf\xe3\x89\x84')
>>> unicode(str(b), 'utf-8')
u'\u31ef \u3244'

Byte arrays support most of the methods of string types, such as startswith()/endswith(), find()/rfind(), and some of the methods of lists, such as append(), pop(), and reverse().

>>> b = bytearray('ABC')
>>> b.append('d')
>>> b.append(ord('e'))
>>> b
bytearray(b'ABCde')

There’s also a corresponding C API, with PyByteArray_FromObject(), PyByteArray_FromStringAndSize(), and various other functions.

더 보기

PEP 3112 [https://www.python.org/dev/peps/pep-3112] - Bytes literals in Python 3000

PEP written by Jason Orendorff; backported to 2.6 by Christian Heimes.

PEP 3116: New I/O Library

Python’s built-in file objects support a number of methods, but file-like objects don’t necessarily support all of them. Objects that imitate files usually support read() and write(), but they may not support readline(), for example. Python 3.0 introduces a layered I/O library in the io module that separates buffering and text-handling features from the fundamental read and write operations.

There are three levels of abstract base classes provided by the io module:

RawIOBase defines raw I/O operations: read(), readinto(), write(), seek(), tell(), truncate(), and close(). Most of the methods of this class will often map to a single system call. There are also readable(), writable(), and seekable() methods for determining what operations a given object will allow.

Python 3.0 has concrete implementations of this class for files and sockets, but Python 2.6 hasn’t restructured its file and socket objects in this way.

BufferedIOBase is an abstract base class that buffers data in memory to reduce the number of system calls used, making I/O processing more efficient. It supports all of the methods of RawIOBase, and adds a raw attribute holding the underlying raw object.

There are five concrete classes implementing this ABC. BufferedWriter and BufferedReader are for objects that support write-only or read-only usage that have a seek() method for random access. BufferedRandom objects support read and write access upon the same underlying stream, and BufferedRWPair is for objects such as TTYs that have both read and write operations acting upon unconnected streams of data. The BytesIO class supports reading, writing, and seeking over an in-memory buffer.

TextIOBase: Provides functions for reading and writing strings (remember, strings will be Unicode in Python 3.0), and supporting universal newlines. TextIOBase defines the readline() method and supports iteration upon objects.

There are two concrete implementations. TextIOWrapper wraps a buffered I/O object, supporting all of the methods for text I/O and adding a buffer attribute for access to the underlying object. StringIO simply buffers everything in memory without ever writing anything to disk.

(In Python 2.6, io.StringIO is implemented in pure Python, so it’s pretty slow. You should therefore stick with the existing StringIO module or cStringIO for now. At some point Python 3.0’s io module will be rewritten into C for speed, and perhaps the C implementation will be backported to the 2.x releases.)

In Python 2.6, the underlying implementations haven’t been restructured to build on top of the io module’s classes. The module is being provided to make it easier to write code that’s forward-compatible with 3.0, and to save developers the effort of writing their own implementations of buffering and text I/O.

더 보기

PEP 3116 [https://www.python.org/dev/peps/pep-3116] - New I/O

PEP written by Daniel Stutzbach, Mike Verdone, and Guido van Rossum. Code by Guido van Rossum, Georg Brandl, Walter Doerwald, Jeremy Hylton, Martin von Löwis, Tony Lownds, and others.

PEP 3118: Revised Buffer Protocol

The buffer protocol is a C-level API that lets Python types exchange pointers into their internal representations. A memory-mapped file can be viewed as a buffer of characters, for example, and this lets another module such as re treat memory-mapped files as a string of characters to be searched.

The primary users of the buffer protocol are numeric-processing packages such as NumPy, which expose the internal representation of arrays so that callers can write data directly into an array instead of going through a slower API. This PEP updates the buffer protocol in light of experience from NumPy development, adding a number of new features such as indicating the shape of an array or locking a memory region.

The most important new C API function is PyObject_GetBuffer(PyObject *obj, Py_buffer *view, int flags), which takes an object and a set of flags, and fills in the Py_buffer structure with information about the object’s memory representation. Objects can use this operation to lock memory in place while an external caller could be modifying the contents, so there’s a corresponding PyBuffer_Release(Py_buffer *view) to indicate that the external caller is done.

The flags argument to PyObject_GetBuffer() specifies constraints upon the memory returned. Some examples are:

PyBUF_WRITABLE indicates that the memory must be writable.

PyBUF_LOCK requests a read-only or exclusive lock on the memory.

PyBUF_C_CONTIGUOUS and PyBUF_F_CONTIGUOUS requests a C-contiguous (last dimension varies the fastest) or Fortran-contiguous (first dimension varies the fastest) array layout.

Two new argument codes for PyArg_ParseTuple(), s* and z*, return locked buffer objects for a parameter.

더 보기

PEP 3118 [https://www.python.org/dev/peps/pep-3118] - Revising the buffer protocol

PEP written by Travis Oliphant and Carl Banks; implemented by Travis Oliphant.

PEP 3119: Abstract Base Classes

Some object-oriented languages such as Java support interfaces, declaring that a class has a given set of methods or supports a given access protocol. Abstract Base Classes (or ABCs) are an equivalent feature for Python. The ABC support consists of an abc module containing a metaclass called ABCMeta, special handling of this metaclass by the isinstance() and issubclass() builtins, and a collection of basic ABCs that the Python developers think will be widely useful. Future versions of Python will probably add more ABCs.

Let’s say you have a particular class and wish to know whether it supports dictionary-style access. The phrase “dictionary-style” is vague, however. It probably means that accessing items with obj[1] works. Does it imply that setting items with obj[2] = value works? Or that the object will have keys(), values(), and items() methods? What about the iterative variants such as iterkeys()? copy() and update()? Iterating over the object with iter()?

The Python 2.6 collections module includes a number of different ABCs that represent these distinctions. Iterable indicates that a class defines __iter__(), and Container means the class defines a __contains__() method and therefore supports x in y expressions. The basic dictionary interface of getting items, setting items, and keys(), values(), and items(), is defined by the MutableMapping ABC.

You can derive your own classes from a particular ABC to indicate they support that ABC’s interface:

import collections

class Storage(collections.MutableMapping):
    ...

Alternatively, you could write the class without deriving from the desired ABC and instead register the class by calling the ABC’s register() method:

import collections

class Storage:
    ...

collections.MutableMapping.register(Storage)

For classes that you write, deriving from the ABC is probably clearer. The register() method is useful when you’ve written a new ABC that can describe an existing type or class, or if you want to declare that some third-party class implements an ABC. For example, if you defined a PrintableType ABC, it’s legal to do:

# Register Python's types
PrintableType.register(int)
PrintableType.register(float)
PrintableType.register(str)

Classes should obey the semantics specified by an ABC, but Python can’t check this; it’s up to the class author to understand the ABC’s requirements and to implement the code accordingly.

To check whether an object supports a particular interface, you can now write:

def func(d):
    if not isinstance(d, collections.MutableMapping):
        raise ValueError("Mapping object expected, not %r" % d)

Don’t feel that you must now begin writing lots of checks as in the above example. Python has a strong tradition of duck-typing, where explicit type-checking is never done and code simply calls methods on an object, trusting that those methods will be there and raising an exception if they aren’t. Be judicious in checking for ABCs and only do it where it’s absolutely necessary.

You can write your own ABCs by using abc.ABCMeta as the metaclass in a class definition:

from abc import ABCMeta, abstractmethod

class Drawable():
    __metaclass__ = ABCMeta

    @abstractmethod
    def draw(self, x, y, scale=1.0):
        pass

    def draw_doubled(self, x, y):
        self.draw(x, y, scale=2.0)

class Square(Drawable):
    def draw(self, x, y, scale):
        ...

In the Drawable ABC above, the draw_doubled() method renders the object at twice its size and can be implemented in terms of other methods described in Drawable. Classes implementing this ABC therefore don’t need to provide their own implementation of draw_doubled(), though they can do so. An implementation of draw() is necessary, though; the ABC can’t provide a useful generic implementation.

You can apply the @abstractmethod decorator to methods such as draw() that must be implemented; Python will then raise an exception for classes that don’t define the method. Note that the exception is only raised when you actually try to create an instance of a subclass lacking the method:

>>> class Circle(Drawable):
...     pass
...
>>> c = Circle()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Can't instantiate abstract class Circle with abstract methods draw
>>>

Abstract data attributes can be declared using the @abstractproperty decorator:

from abc import abstractproperty
...

@abstractproperty
def readonly(self):
   return self._x

Subclasses must then define a readonly() property.

더 보기

PEP 3119 [https://www.python.org/dev/peps/pep-3119] - Introducing Abstract Base Classes

PEP written by Guido van Rossum and Talin. Implemented by Guido van Rossum. Backported to 2.6 by Benjamin Aranguren, with Alex Martelli.

PEP 3127: Integer Literal Support and Syntax

Python 3.0 changes the syntax for octal (base-8) integer literals, prefixing them with “0o” or “0O” instead of a leading zero, and adds support for binary (base-2) integer literals, signalled by a “0b” or “0B” prefix.

Python 2.6 doesn’t drop support for a leading 0 signalling an octal number, but it does add support for “0o” and “0b”:

>>> 0o21, 2*8 + 1
(17, 17)
>>> 0b101111
47

The oct() builtin still returns numbers prefixed with a leading zero, and a new bin() builtin returns the binary representation for a number:

>>> oct(42)
'052'
>>> future_builtins.oct(42)
'0o52'
>>> bin(173)
'0b10101101'

The int() and long() builtins will now accept the “0o” and “0b” prefixes when base-8 or base-2 are requested, or when the base argument is zero (signalling that the base used should be determined from the string):

>>> int ('0o52', 0)
42
>>> int('1101', 2)
13
>>> int('0b1101', 2)
13
>>> int('0b1101', 0)
13

더 보기

PEP 3127 [https://www.python.org/dev/peps/pep-3127] - Integer Literal Support and Syntax

PEP written by Patrick Maupin; backported to 2.6 by Eric Smith.

PEP 3129: Class Decorators

Decorators have been extended from functions to classes. It’s now legal to write:

@foo
@bar
class A:
  pass

This is equivalent to:

class A:
  pass

A = foo(bar(A))

더 보기

PEP 3129 [https://www.python.org/dev/peps/pep-3129] - Class Decorators

PEP written by Collin Winter.

PEP 3141: A Type Hierarchy for Numbers

Python 3.0 adds several abstract base classes for numeric types inspired by Scheme’s numeric tower. These classes were backported to 2.6 as the numbers module.

The most general ABC is Number. It defines no operations at all, and only exists to allow checking if an object is a number by doing isinstance(obj, Number).

Complex is a subclass of Number. Complex numbers can undergo the basic operations of addition, subtraction, multiplication, division, and exponentiation, and you can retrieve the real and imaginary parts and obtain a number’s conjugate. Python’s built-in complex type is an implementation of Complex.

Real further derives from Complex, and adds operations that only work on real numbers: floor(), trunc(), rounding, taking the remainder mod N, floor division, and comparisons.

Rational numbers derive from Real, have numerator and denominator properties, and can be converted to floats. Python 2.6 adds a simple rational-number class, Fraction, in the fractions module. (It’s called Fraction instead of Rational to avoid a name clash with numbers.Rational.)

Integral numbers derive from Rational, and can be shifted left and right with << and >>, combined using bitwise operations such as & and |, and can be used as array indexes and slice boundaries.

In Python 3.0, the PEP slightly redefines the existing builtins round(), math.floor(), math.ceil(), and adds a new one, math.trunc(), that’s been backported to Python 2.6. math.trunc() rounds toward zero, returning the closest Integral that’s between the function’s argument and zero.

더 보기

PEP 3141 [https://www.python.org/dev/peps/pep-3141] - A Type Hierarchy for Numbers

PEP written by Jeffrey Yasskin.

Scheme’s numerical tower [https://www.gnu.org/software/guile/manual/html_node/Numerical-Tower.html#Numerical-Tower], from the Guile manual.

Scheme’s number datatypes [http://schemers.org/Documents/Standards/R5RS/HTML/r5rs-Z-H-9.html#%_sec_6.2] from the R5RS Scheme specification.

The fractions Module

To fill out the hierarchy of numeric types, the fractions module provides a rational-number class. Rational numbers store their values as a numerator and denominator forming a fraction, and can exactly represent numbers such as 2/3 that floating-point numbers can only approximate.

The Fraction constructor takes two Integral values that will be the numerator and denominator of the resulting fraction.

>>> from fractions import Fraction
>>> a = Fraction(2, 3)
>>> b = Fraction(2, 5)
>>> float(a), float(b)
(0.66666666666666663, 0.40000000000000002)
>>> a+b
Fraction(16, 15)
>>> a/b
Fraction(5, 3)

For converting floating-point numbers to rationals, the float type now has an as_integer_ratio() method that returns the numerator and denominator for a fraction that evaluates to the same floating-point value:

>>> (2.5) .as_integer_ratio()
(5, 2)
>>> (3.1415) .as_integer_ratio()
(7074029114692207L, 2251799813685248L)
>>> (1./3) .as_integer_ratio()
(6004799503160661L, 18014398509481984L)

Note that values that can only be approximated by floating-point numbers, such as 1./3, are not simplified to the number being approximated; the fraction attempts to match the floating-point value exactly.

The fractions module is based upon an implementation by Sjoerd Mullender that was in Python’s Demo/classes/ directory for a long time. This implementation was significantly updated by Jeffrey Yasskin.

Other Language Changes

Some smaller changes made to the core Python language are:

Directories and zip archives containing a __main__.py file can now be executed directly by passing their name to the interpreter. The directory or zip archive is automatically inserted as the first entry in sys.path. (Suggestion and initial patch by Andy Chu, subsequently revised by Phillip J. Eby and Nick Coghlan; bpo-1739468 [https://bugs.python.org/issue?@action=redirect&bpo=1739468].)

The hasattr() function was catching and ignoring all errors, under the assumption that they meant a __getattr__() method was failing somehow and the return value of hasattr() would therefore be False. This logic shouldn’t be applied to KeyboardInterrupt and SystemExit, however; Python 2.6 will no longer discard such exceptions when hasattr() encounters them. (Fixed by Benjamin Peterson; bpo-2196 [https://bugs.python.org/issue?@action=redirect&bpo=2196].)

When calling a function using the ** syntax to provide keyword arguments, you are no longer required to use a Python dictionary; any mapping will now work:

>>> def f(**kw):
...    print sorted(kw)
...
>>> ud=UserDict.UserDict()
>>> ud['a'] = 1
>>> ud['b'] = 'string'
>>> f(**ud)
['a', 'b']

(Contributed by Alexander Belopolsky; bpo-1686487 [https://bugs.python.org/issue?@action=redirect&bpo=1686487].)

It’s also become legal to provide keyword arguments after a *args argument to a function call.

>>> def f(*args, **kw):
...     print args, kw
...
>>> f(1,2,3, *(4,5,6), keyword=13)
(1, 2, 3, 4, 5, 6) {'keyword': 13}

Previously this would have been a syntax error. (Contributed by Amaury Forgeot d’Arc; bpo-3473 [https://bugs.python.org/issue?@action=redirect&bpo=3473].)

A new builtin, next(iterator, [default]) returns the next item from the specified iterator. If the default argument is supplied, it will be returned if iterator has been exhausted; otherwise, the StopIteration exception will be raised. (Backported in bpo-2719 [https://bugs.python.org/issue?@action=redirect&bpo=2719].)

Tuples now have index() and count() methods matching the list type’s index() and count() methods:

>>> t = (0,1,2,3,4,0,1,2)
>>> t.index(3)
3
>>> t.count(0)
2

(Contributed by Raymond Hettinger)

The built-in types now have improved support for extended slicing syntax, accepting various combinations of (start, stop, step). Previously, the support was partial and certain corner cases wouldn’t work. (Implemented by Thomas Wouters.)

Properties now have three attributes, getter, setter and deleter, that are decorators providing useful shortcuts for adding a getter, setter or deleter function to an existing property. You would use them like this:

class C(object):
    @property
    def x(self):
        return self._x

    @x.setter
    def x(self, value):
        self._x = value

    @x.deleter
    def x(self):
        del self._x

class D(C):
    @C.x.getter
    def x(self):
        return self._x * 2

    @x.setter
    def x(self, value):
        self._x = value / 2

Several methods of the built-in set types now accept multiple iterables: intersection(), intersection_update(), union(), update(), difference() and difference_update().

>>> s=set('1234567890')
>>> s.intersection('abc123', 'cdf246')  # Intersection between all inputs
set(['2'])
>>> s.difference('246', '789')
set(['1', '0', '3', '5'])

(Contributed by Raymond Hettinger.)

Many floating-point features were added. The float() function will now turn the string nan into an IEEE 754 Not A Number value, and +inf and -inf into positive or negative infinity. This works on any platform with IEEE 754 semantics. (Contributed by Christian Heimes; bpo-1635 [https://bugs.python.org/issue?@action=redirect&bpo=1635].)

Other functions in the math module, isinf() and isnan(), return true if their floating-point argument is infinite or Not A Number. (bpo-1640 [https://bugs.python.org/issue?@action=redirect&bpo=1640])

Conversion functions were added to convert floating-point numbers into hexadecimal strings (bpo-3008 [https://bugs.python.org/issue?@action=redirect&bpo=3008]). These functions convert floats to and from a string representation without introducing rounding errors from the conversion between decimal and binary. Floats have a hex() method that returns a string representation, and the float.fromhex() method converts a string back into a number:

>>> a = 3.75
>>> a.hex()
'0x1.e000000000000p+1'
>>> float.fromhex('0x1.e000000000000p+1')
3.75
>>> b=1./3
>>> b.hex()
'0x1.5555555555555p-2'

A numerical nicety: when creating a complex number from two floats on systems that support signed zeros (-0 and +0), the complex() constructor will now preserve the sign of the zero. (Fixed by Mark T. Dickinson; bpo-1507 [https://bugs.python.org/issue?@action=redirect&bpo=1507].)

Classes that inherit a __hash__() method from a parent class can set __hash__ = None to indicate that the class isn’t hashable. This will make hash(obj) raise a TypeError and the class will not be indicated as implementing the Hashable ABC.

You should do this when you’ve defined a __cmp__() or __eq__() method that compares objects by their value rather than by identity. All objects have a default hash method that uses id(obj) as the hash value. There’s no tidy way to remove the __hash__() method inherited from a parent class, so assigning None was implemented as an override. At the C level, extensions can set tp_hash to PyObject_HashNotImplemented(). (Fixed by Nick Coghlan and Amaury Forgeot d’Arc; bpo-2235 [https://bugs.python.org/issue?@action=redirect&bpo=2235].)

The GeneratorExit exception now subclasses BaseException instead of Exception. This means that an exception handler that does except Exception: will not inadvertently catch GeneratorExit. (Contributed by Chad Austin; bpo-1537 [https://bugs.python.org/issue?@action=redirect&bpo=1537].)

Generator objects now have a gi_code attribute that refers to the original code object backing the generator. (Contributed by Collin Winter; bpo-1473257 [https://bugs.python.org/issue?@action=redirect&bpo=1473257].)

The compile() built-in function now accepts keyword arguments as well as positional parameters. (Contributed by Thomas Wouters; bpo-1444529 [https://bugs.python.org/issue?@action=redirect&bpo=1444529].)

The complex() constructor now accepts strings containing parenthesized complex numbers, meaning that complex(repr(cplx)) will now round-trip values. For example, complex('(3+4j)') now returns the value (3+4j). (bpo-1491866 [https://bugs.python.org/issue?@action=redirect&bpo=1491866])

The string translate() method now accepts None as the translation table parameter, which is treated as the identity transformation. This makes it easier to carry out operations that only delete characters. (Contributed by Bengt Richter and implemented by Raymond Hettinger; bpo-1193128 [https://bugs.python.org/issue?@action=redirect&bpo=1193128].)

The built-in dir() function now checks for a __dir__() method on the objects it receives. This method must return a list of strings containing the names of valid attributes for the object, and lets the object control the value that dir() produces. Objects that have __getattr__() or __getattribute__() methods can use this to advertise pseudo-attributes they will honor. (bpo-1591665 [https://bugs.python.org/issue?@action=redirect&bpo=1591665])

Instance method objects have new attributes for the object and function comprising the method; the new synonym for im_self is __self__, and im_func is also available as __func__. The old names are still supported in Python 2.6, but are gone in 3.0.

An obscure change: when you use the locals() function inside a class statement, the resulting dictionary no longer returns free variables. (Free variables, in this case, are variables referenced in the class statement that aren’t attributes of the class.)

Optimizations

The warnings module has been rewritten in C. This makes it possible to invoke warnings from the parser, and may also make the interpreter’s startup faster. (Contributed by Neal Norwitz and Brett Cannon; bpo-1631171 [https://bugs.python.org/issue?@action=redirect&bpo=1631171].)

Type objects now have a cache of methods that can reduce the work required to find the correct method implementation for a particular class; once cached, the interpreter doesn’t need to traverse base classes to figure out the right method to call. The cache is cleared if a base class or the class itself is modified, so the cache should remain correct even in the face of Python’s dynamic nature. (Original optimization implemented by Armin Rigo, updated for Python 2.6 by Kevin Jacobs; bpo-1700288 [https://bugs.python.org/issue?@action=redirect&bpo=1700288].)

By default, this change is only applied to types that are included with the Python core. Extension modules may not necessarily be compatible with this cache, so they must explicitly add Py_TPFLAGS_HAVE_VERSION_TAG to the module’s tp_flags field to enable the method cache. (To be compatible with the method cache, the extension module’s code must not directly access and modify the tp_dict member of any of the types it implements. Most modules don’t do this, but it’s impossible for the Python interpreter to determine that. See bpo-1878 [https://bugs.python.org/issue?@action=redirect&bpo=1878] for some discussion.)

Function calls that use keyword arguments are significantly faster by doing a quick pointer comparison, usually saving the time of a full string comparison. (Contributed by Raymond Hettinger, after an initial implementation by Antoine Pitrou; bpo-1819 [https://bugs.python.org/issue?@action=redirect&bpo=1819].)

All of the functions in the struct module have been rewritten in C, thanks to work at the Need For Speed sprint. (Contributed by Raymond Hettinger.)

Some of the standard built-in types now set a bit in their type objects. This speeds up checking whether an object is a subclass of one of these types. (Contributed by Neal Norwitz.)

Unicode strings now use faster code for detecting whitespace and line breaks; this speeds up the split() method by about 25% and splitlines() by 35%. (Contributed by Antoine Pitrou.) Memory usage is reduced by using pymalloc for the Unicode string’s data.

The with statement now stores the __exit__() method on the stack, producing a small speedup. (Implemented by Jeffrey Yasskin.)

To reduce memory usage, the garbage collector will now clear internal free lists when garbage-collecting the highest generation of objects. This may return memory to the operating system sooner.

Interpreter Changes

Two command-line options have been reserved for use by other Python implementations. The -J switch has been reserved for use by Jython for Jython-specific options, such as switches that are passed to the underlying JVM. -X has been reserved for options specific to a particular implementation of Python such as CPython, Jython, or IronPython. If either option is used with Python 2.6, the interpreter will report that the option isn’t currently used.

Python can now be prevented from writing .pyc or .pyo files by supplying the -B switch to the Python interpreter, or by setting the PYTHONDONTWRITEBYTECODE environment variable before running the interpreter. This setting is available to Python programs as the sys.dont_write_bytecode variable, and Python code can change the value to modify the interpreter’s behaviour. (Contributed by Neal Norwitz and Georg Brandl.)

The encoding used for standard input, output, and standard error can be specified by setting the PYTHONIOENCODING environment variable before running the interpreter. The value should be a string in the form <encoding> or <encoding>:<errorhandler>. The encoding part specifies the encoding’s name, e.g. utf-8 or latin-1; the optional errorhandler part specifies what to do with characters that can’t be handled by the encoding, and should be one of “error”, “ignore”, or “replace”. (Contributed by Martin von Löwis.)

New and Improved Modules

As in every release, Python’s standard library received a number of enhancements and bug fixes. Here’s a partial list of the most notable changes, sorted alphabetically by module name. Consult the Misc/NEWS file in the source tree for a more complete list of changes, or look through the Subversion logs for all the details.

The asyncore and asynchat modules are being actively maintained again, and a number of patches and bugfixes were applied. (Maintained by Josiah Carlson; see bpo-1736190 [https://bugs.python.org/issue?@action=redirect&bpo=1736190] for one patch.)

The bsddb module also has a new maintainer, Jesús Cea Avión, and the package is now available as a standalone package. The web page for the package is www.jcea.es/programacion/pybsddb.htm [https://www.jcea.es/programacion/pybsddb.htm]. The plan is to remove the package from the standard library in Python 3.0, because its pace of releases is much more frequent than Python’s.

The bsddb.dbshelve module now uses the highest pickling protocol available, instead of restricting itself to protocol 1. (Contributed by W. Barnes.)

The cgi module will now read variables from the query string of an HTTP POST request. This makes it possible to use form actions with URLs that include query strings such as “/cgi-bin/add.py?category=1”. (Contributed by Alexandre Fiori and Nubis; bpo-1817 [https://bugs.python.org/issue?@action=redirect&bpo=1817].)

The parse_qs() and parse_qsl() functions have been relocated from the cgi module to the urlparse module. The versions still available in the cgi module will trigger PendingDeprecationWarning messages in 2.6 (bpo-600362 [https://bugs.python.org/issue?@action=redirect&bpo=600362]).

The cmath module underwent extensive revision, contributed by Mark Dickinson and Christian Heimes. Five new functions were added:

polar() converts a complex number to polar form, returning the modulus and argument of the complex number.

rect() does the opposite, turning a modulus, argument pair back into the corresponding complex number.

phase() returns the argument (also called the angle) of a complex number.

isnan() returns True if either the real or imaginary part of its argument is a NaN.

isinf() returns True if either the real or imaginary part of its argument is infinite.

The revisions also improved the numerical soundness of the cmath module. For all functions, the real and imaginary parts of the results are accurate to within a few units of least precision (ulps) whenever possible. See bpo-1381 [https://bugs.python.org/issue?@action=redirect&bpo=1381] for the details. The branch cuts for asinh(), atanh(): and atan() have also been corrected.

The tests for the module have been greatly expanded; nearly 2000 new test cases exercise the algebraic functions.

On IEEE 754 platforms, the cmath module now handles IEEE 754 special values and floating-point exceptions in a manner consistent with Annex ‘G’ of the C99 standard.

A new data type in the collections module: namedtuple(typename, fieldnames) is a factory function that creates subclasses of the standard tuple whose fields are accessible by name as well as index. For example:

>>> var_type = collections.namedtuple('variable',
...             'id name type size')
>>> # Names are separated by spaces or commas.
>>> # 'id, name, type, size' would also work.
>>> var_type._fields
('id', 'name', 'type', 'size')

>>> var = var_type(1, 'frequency', 'int', 4)
>>> print var[0], var.id    # Equivalent
1 1
>>> print var[2], var.type  # Equivalent
int int
>>> var._asdict()
{'size': 4, 'type': 'int', 'id': 1, 'name': 'frequency'}
>>> v2 = var._replace(name='amplitude')
>>> v2
variable(id=1, name='amplitude', type='int', size=4)

Several places in the standard library that returned tuples have been modified to return namedtuple instances. For example, the Decimal.as_tuple() method now returns a named tuple with sign, digits, and exponent fields.

(Contributed by Raymond Hettinger.)

Another change to the collections module is that the deque type now supports an optional maxlen parameter; if supplied, the deque’s size will be restricted to no more than maxlen items. Adding more items to a full deque causes old items to be discarded.

>>> from collections import deque
>>> dq=deque(maxlen=3)
>>> dq
deque([], maxlen=3)
>>> dq.append(1); dq.append(2); dq.append(3)
>>> dq
deque([1, 2, 3], maxlen=3)
>>> dq.append(4)
>>> dq
deque([2, 3, 4], maxlen=3)

(Contributed by Raymond Hettinger.)

The Cookie module’s Morsel objects now support an httponly attribute. In some browsers. cookies with this attribute set cannot be accessed or manipulated by JavaScript code. (Contributed by Arvin Schnell; bpo-1638033 [https://bugs.python.org/issue?@action=redirect&bpo=1638033].)

A new window method in the curses module, chgat(), changes the display attributes for a certain number of characters on a single line. (Contributed by Fabian Kreutz.)

# Boldface text starting at y=0,x=21
# and affecting the rest of the line.
stdscr.chgat(0, 21, curses.A_BOLD)

The Textbox class in the curses.textpad module now supports editing in insert mode as well as overwrite mode. Insert mode is enabled by supplying a true value for the insert_mode parameter when creating the Textbox instance.

The datetime module’s strftime() methods now support a %f format code that expands to the number of microseconds in the object, zero-padded on the left to six places. (Contributed by Skip Montanaro; bpo-1158 [https://bugs.python.org/issue?@action=redirect&bpo=1158].)

The decimal module was updated to version 1.66 of the General Decimal Specification [http://speleotrove.com/decimal/decarith.html]. New features include some methods for some basic mathematical functions such as exp() and log10():

>>> Decimal(1).exp()
Decimal("2.718281828459045235360287471")
>>> Decimal("2.7182818").ln()
Decimal("0.9999999895305022877376682436")
>>> Decimal(1000).log10()
Decimal("3")

The as_tuple() method of Decimal objects now returns a named tuple with sign, digits, and exponent fields.

(Implemented by Facundo Batista and Mark Dickinson. Named tuple support added by Raymond Hettinger.)

The difflib module’s SequenceMatcher class now returns named tuples representing matches, with a, b, and size attributes. (Contributed by Raymond Hettinger.)

An optional timeout parameter, specifying a timeout measured in seconds, was added to the ftplib.FTP class constructor as well as the connect() method. (Added by Facundo Batista.) Also, the FTP class’s storbinary() and storlines() now take an optional callback parameter that will be called with each block of data after the data has been sent. (Contributed by Phil Schwartz; bpo-1221598 [https://bugs.python.org/issue?@action=redirect&bpo=1221598].)

The reduce() built-in function is also available in the functools module. In Python 3.0, the builtin has been dropped and reduce() is only available from functools; currently there are no plans to drop the builtin in the 2.x series. (Patched by Christian Heimes; bpo-1739906 [https://bugs.python.org/issue?@action=redirect&bpo=1739906].)

When possible, the getpass module will now use /dev/tty to print a prompt message and read the password, falling back to standard error and standard input. If the password may be echoed to the terminal, a warning is printed before the prompt is displayed. (Contributed by Gregory P. Smith.)

The glob.glob() function can now return Unicode filenames if a Unicode path was used and Unicode filenames are matched within the directory. (bpo-1001604 [https://bugs.python.org/issue?@action=redirect&bpo=1001604])

A new function in the heapq module, merge(iter1, iter2, ...), takes any number of iterables returning data in sorted order, and returns a new generator that returns the contents of all the iterators, also in sorted order. For example:

>>> list(heapq.merge([1, 3, 5, 9], [2, 8, 16]))
[1, 2, 3, 5, 8, 9, 16]

Another new function, heappushpop(heap, item), pushes item onto heap, then pops off and returns the smallest item. This is more efficient than making a call to heappush() and then heappop().

heapq is now implemented to only use less-than comparison, instead of the less-than-or-equal comparison it previously used. This makes heapq’s usage of a type match the list.sort() method. (Contributed by Raymond Hettinger.)

An optional timeout parameter, specifying a timeout measured in seconds, was added to the httplib.HTTPConnection and HTTPSConnection class constructors. (Added by Facundo Batista.)

Most of the inspect module’s functions, such as getmoduleinfo() and getargs(), now return named tuples. In addition to behaving like tuples, the elements of the return value can also be accessed as attributes. (Contributed by Raymond Hettinger.)

Some new functions in the module include isgenerator(), isgeneratorfunction(), and isabstract().

The itertools module gained several new functions.

izip_longest(iter1, iter2, ...[, fillvalue]) makes tuples from each of the elements; if some of the iterables are shorter than others, the missing values are set to fillvalue. For example:

>>> tuple(itertools.izip_longest([1,2,3], [1,2,3,4,5]))
((1, 1), (2, 2), (3, 3), (None, 4), (None, 5))

product(iter1, iter2, ..., [repeat=N]) returns the Cartesian product of the supplied iterables, a set of tuples containing every possible combination of the elements returned from each iterable.

>>> list(itertools.product([1,2,3], [4,5,6]))
[(1, 4), (1, 5), (1, 6),
 (2, 4), (2, 5), (2, 6),
 (3, 4), (3, 5), (3, 6)]

The optional repeat keyword argument is used for taking the product of an iterable or a set of iterables with themselves, repeated N times. With a single iterable argument, N-tuples are returned:

>>> list(itertools.product([1,2], repeat=3))
[(1, 1, 1), (1, 1, 2), (1, 2, 1), (1, 2, 2),
 (2, 1, 1), (2, 1, 2), (2, 2, 1), (2, 2, 2)]

With two iterables, 2N-tuples are returned.

>>> list(itertools.product([1,2], [3,4], repeat=2))
[(1, 3, 1, 3), (1, 3, 1, 4), (1, 3, 2, 3), (1, 3, 2, 4),
 (1, 4, 1, 3), (1, 4, 1, 4), (1, 4, 2, 3), (1, 4, 2, 4),
 (2, 3, 1, 3), (2, 3, 1, 4), (2, 3, 2, 3), (2, 3, 2, 4),
 (2, 4, 1, 3), (2, 4, 1, 4), (2, 4, 2, 3), (2, 4, 2, 4)]

combinations(iterable, r) returns sub-sequences of length r from the elements of iterable.

>>> list(itertools.combinations('123', 2))
[('1', '2'), ('1', '3'), ('2', '3')]
>>> list(itertools.combinations('123', 3))
[('1', '2', '3')]
>>> list(itertools.combinations('1234', 3))
[('1', '2', '3'), ('1', '2', '4'),
 ('1', '3', '4'), ('2', '3', '4')]

permutations(iter[, r]) returns all the permutations of length r of the iterable’s elements. If r is not specified, it will default to the number of elements produced by the iterable.

>>> list(itertools.permutations([1,2,3,4], 2))
[(1, 2), (1, 3), (1, 4),
 (2, 1), (2, 3), (2, 4),
 (3, 1), (3, 2), (3, 4),
 (4, 1), (4, 2), (4, 3)]

itertools.chain(*iterables) is an existing function in itertools that gained a new constructor in Python 2.6. itertools.chain.from_iterable(iterable) takes a single iterable that should return other iterables. chain() will then return all the elements of the first iterable, then all the elements of the second, and so on.

>>> list(itertools.chain.from_iterable([[1,2,3], [4,5,6]]))
[1, 2, 3, 4, 5, 6]

(All contributed by Raymond Hettinger.)

The logging module’s FileHandler class and its subclasses WatchedFileHandler, RotatingFileHandler, and TimedRotatingFileHandler now have an optional delay parameter to their constructors. If delay is true, opening of the log file is deferred until the first emit() call is made. (Contributed by Vinay Sajip.)

TimedRotatingFileHandler also has a utc constructor parameter. If the argument is true, UTC time will be used in determining when midnight occurs and in generating filenames; otherwise local time will be used.

Several new functions were added to the math module:

isinf() and isnan() determine whether a given float is a (positive or negative) infinity or a NaN (Not a Number), respectively.

copysign() copies the sign bit of an IEEE 754 number, returning the absolute value of x combined with the sign bit of y. For example, math.copysign(1, -0.0) returns -1.0. (Contributed by Christian Heimes.)

factorial() computes the factorial of a number. (Contributed by Raymond Hettinger; bpo-2138 [https://bugs.python.org/issue?@action=redirect&bpo=2138].)

fsum() adds up the stream of numbers from an iterable, and is careful to avoid loss of precision through using partial sums. (Contributed by Jean Brouwers, Raymond Hettinger, and Mark Dickinson; bpo-2819 [https://bugs.python.org/issue?@action=redirect&bpo=2819].)

acosh(), asinh() and atanh() compute the inverse hyperbolic functions.

log1p() returns the natural logarithm of 1+x (base e).

trunc() rounds a number toward zero, returning the closest Integral that’s between the function’s argument and zero. Added as part of the backport of PEP 3141’s type hierarchy for numbers.

The math module has been improved to give more consistent behaviour across platforms, especially with respect to handling of floating-point exceptions and IEEE 754 special values.

Whenever possible, the module follows the recommendations of the C99 standard about 754’s special values. For example, sqrt(-1.) should now give a ValueError across almost all platforms, while sqrt(float('NaN')) should return a NaN on all IEEE 754 platforms. Where Annex ‘F’ of the C99 standard recommends signaling ‘divide-by-zero’ or ‘invalid’, Python will raise ValueError. Where Annex ‘F’ of the C99 standard recommends signaling ‘overflow’, Python will raise OverflowError. (See bpo-711019 [https://bugs.python.org/issue?@action=redirect&bpo=711019] and bpo-1640 [https://bugs.python.org/issue?@action=redirect&bpo=1640].)

(Contributed by Christian Heimes and Mark Dickinson.)

mmap objects now have a rfind() method that searches for a substring beginning at the end of the string and searching backwards. The find() method also gained an end parameter giving an index at which to stop searching. (Contributed by John Lenton.)

The operator module gained a methodcaller() function that takes a name and an optional set of arguments, returning a callable that will call the named function on any arguments passed to it. For example:

>>> # Equivalent to lambda s: s.replace('old', 'new')
>>> replacer = operator.methodcaller('replace', 'old', 'new')
>>> replacer('old wine in old bottles')
'new wine in new bottles'

(Contributed by Georg Brandl, after a suggestion by Gregory Petrosyan.)

The attrgetter() function now accepts dotted names and performs the corresponding attribute lookups:

>>> inst_name = operator.attrgetter(
...        '__class__.__name__')
>>> inst_name('')
'str'
>>> inst_name(help)
'_Helper'

(Contributed by Georg Brandl, after a suggestion by Barry Warsaw.)

The os module now wraps several new system calls. fchmod(fd, mode) and fchown(fd, uid, gid) change the mode and ownership of an opened file, and lchmod(path, mode) changes the mode of a symlink. (Contributed by Georg Brandl and Christian Heimes.)

chflags() and lchflags() are wrappers for the corresponding system calls (where they’re available), changing the flags set on a file. Constants for the flag values are defined in the stat module; some possible values include UF_IMMUTABLE to signal the file may not be changed and UF_APPEND to indicate that data can only be appended to the file. (Contributed by M. Levinson.)

os.closerange(low, high) efficiently closes all file descriptors from low to high, ignoring any errors and not including high itself. This function is now used by the subprocess module to make starting processes faster. (Contributed by Georg Brandl; bpo-1663329 [https://bugs.python.org/issue?@action=redirect&bpo=1663329].)

The os.environ object’s clear() method will now unset the environment variables using os.unsetenv() in addition to clearing the object’s keys. (Contributed by Martin Horcicka; bpo-1181 [https://bugs.python.org/issue?@action=redirect&bpo=1181].)

The os.walk() function now has a followlinks parameter. If set to True, it will follow symlinks pointing to directories and visit the directory’s contents. For backward compatibility, the parameter’s default value is false. Note that the function can fall into an infinite recursion if there’s a symlink that points to a parent directory. (bpo-1273829 [https://bugs.python.org/issue?@action=redirect&bpo=1273829])

In the os.path module, the splitext() function has been changed to not split on leading period characters. This produces better results when operating on Unix’s dot-files. For example, os.path.splitext('.ipython') now returns ('.ipython', '') instead of ('', '.ipython'). (bpo-1115886 [https://bugs.python.org/issue?@action=redirect&bpo=1115886])

A new function, os.path.relpath(path, start='.'), returns a relative path from the start path, if it’s supplied, or from the current working directory to the destination path. (Contributed by Richard Barran; bpo-1339796 [https://bugs.python.org/issue?@action=redirect&bpo=1339796].)

On Windows, os.path.expandvars() will now expand environment variables given in the form “%var%”, and “~user” will be expanded into the user’s home directory path. (Contributed by Josiah Carlson; bpo-957650 [https://bugs.python.org/issue?@action=redirect&bpo=957650].)

The Python debugger provided by the pdb module gained a new command: “run” restarts the Python program being debugged and can optionally take new command-line arguments for the program. (Contributed by Rocky Bernstein; bpo-1393667 [https://bugs.python.org/issue?@action=redirect&bpo=1393667].)

The pdb.post_mortem() function, used to begin debugging a traceback, will now use the traceback returned by sys.exc_info() if no traceback is supplied. (Contributed by Facundo Batista; bpo-1106316 [https://bugs.python.org/issue?@action=redirect&bpo=1106316].)

The pickletools module now has an optimize() function that takes a string containing a pickle and removes some unused opcodes, returning a shorter pickle that contains the same data structure. (Contributed by Raymond Hettinger.)

A get_data() function was added to the pkgutil module that returns the contents of resource files included with an installed Python package. For example:

>>> import pkgutil
>>> print pkgutil.get_data('test', 'exception_hierarchy.txt')
BaseException
 +-- SystemExit
 +-- KeyboardInterrupt
 +-- GeneratorExit
 +-- Exception
      +-- StopIteration
      +-- StandardError
 ...

(Contributed by Paul Moore; bpo-2439 [https://bugs.python.org/issue?@action=redirect&bpo=2439].)

The pyexpat module’s Parser objects now allow setting their buffer_size attribute to change the size of the buffer used to hold character data. (Contributed by Achim Gaedke; bpo-1137 [https://bugs.python.org/issue?@action=redirect&bpo=1137].)

The Queue module now provides queue variants that retrieve entries in different orders. The PriorityQueue class stores queued items in a heap and retrieves them in priority order, and LifoQueue retrieves the most recently added entries first, meaning that it behaves like a stack. (Contributed by Raymond Hettinger.)

The random module’s Random objects can now be pickled on a 32-bit system and unpickled on a 64-bit system, and vice versa. Unfortunately, this change also means that Python 2.6’s Random objects can’t be unpickled correctly on earlier versions of Python. (Contributed by Shawn Ligocki; bpo-1727780 [https://bugs.python.org/issue?@action=redirect&bpo=1727780].)

The new triangular(low, high, mode) function returns random numbers following a triangular distribution. The returned values are between low and high, not including high itself, and with mode as the most frequently occurring value in the distribution. (Contributed by Wladmir van der Laan and Raymond Hettinger; bpo-1681432 [https://bugs.python.org/issue?@action=redirect&bpo=1681432].)

Long regular expression searches carried out by the re module will check for signals being delivered, so time-consuming searches can now be interrupted. (Contributed by Josh Hoyt and Ralf Schmitt; bpo-846388 [https://bugs.python.org/issue?@action=redirect&bpo=846388].)

The regular expression module is implemented by compiling bytecodes for a tiny regex-specific virtual machine. Untrusted code could create malicious strings of bytecode directly and cause crashes, so Python 2.6 includes a verifier for the regex bytecode. (Contributed by Guido van Rossum from work for Google App Engine; bpo-3487 [https://bugs.python.org/issue?@action=redirect&bpo=3487].)

The rlcompleter module’s Completer.complete() method will now ignore exceptions triggered while evaluating a name. (Fixed by Lorenz Quack; bpo-2250 [https://bugs.python.org/issue?@action=redirect&bpo=2250].)

The sched module’s scheduler instances now have a read-only queue attribute that returns the contents of the scheduler’s queue, represented as a list of named tuples with the fields (time, priority, action, argument). (Contributed by Raymond Hettinger; bpo-1861 [https://bugs.python.org/issue?@action=redirect&bpo=1861].)

The select module now has wrapper functions for the Linux epoll() and BSD kqueue() system calls. modify() method was added to the existing poll objects; pollobj.modify(fd, eventmask) takes a file descriptor or file object and an event mask, modifying the recorded event mask for that file. (Contributed by Christian Heimes; bpo-1657 [https://bugs.python.org/issue?@action=redirect&bpo=1657].)

The shutil.copytree() function now has an optional ignore argument that takes a callable object. This callable will receive each directory path and a list of the directory’s contents, and returns a list of names that will be ignored, not copied.

The shutil module also provides an ignore_patterns() function for use with this new parameter. ignore_patterns() takes an arbitrary number of glob-style patterns and returns a callable that will ignore any files and directories that match any of these patterns. The following example copies a directory tree, but skips both .svn directories and Emacs backup files, which have names ending with ‘~’:

shutil.copytree('Doc/library', '/tmp/library',
                ignore=shutil.ignore_patterns('*~', '.svn'))

(Contributed by Tarek Ziadé; bpo-2663 [https://bugs.python.org/issue?@action=redirect&bpo=2663].)

Integrating signal handling with GUI handling event loops like those used by Tkinter or GTk+ has long been a problem; most software ends up polling, waking up every fraction of a second to check if any GUI events have occurred. The signal module can now make this more efficient. Calling signal.set_wakeup_fd(fd) sets a file descriptor to be used; when a signal is received, a byte is written to that file descriptor. There’s also a C-level function, PySignal_SetWakeupFd(), for setting the descriptor.

Event loops will use this by opening a pipe to create two descriptors, one for reading and one for writing. The writable descriptor will be passed to set_wakeup_fd(), and the readable descriptor will be added to the list of descriptors monitored by the event loop via select() or poll(). On receiving a signal, a byte will be written and the main event loop will be woken up, avoiding the need to poll.

(Contributed by Adam Olsen; bpo-1583 [https://bugs.python.org/issue?@action=redirect&bpo=1583].)

The siginterrupt() function is now available from Python code, and allows changing whether signals can interrupt system calls or not. (Contributed by Ralf Schmitt.)

The setitimer() and getitimer() functions have also been added (where they’re available). setitimer() allows setting interval timers that will cause a signal to be delivered to the process after a specified time, measured in wall-clock time, consumed process time, or combined process+system time. (Contributed by Guilherme Polo; bpo-2240 [https://bugs.python.org/issue?@action=redirect&bpo=2240].)

The smtplib module now supports SMTP over SSL thanks to the addition of the SMTP_SSL class. This class supports an interface identical to the existing SMTP class. (Contributed by Monty Taylor.) Both class constructors also have an optional timeout parameter that specifies a timeout for the initial connection attempt, measured in seconds. (Contributed by Facundo Batista.)

An implementation of the LMTP protocol (RFC 2033 [https://tools.ietf.org/html/rfc2033.html]) was also added to the module. LMTP is used in place of SMTP when transferring e-mail between agents that don’t manage a mail queue. (LMTP implemented by Leif Hedstrom; bpo-957003 [https://bugs.python.org/issue?@action=redirect&bpo=957003].)

SMTP.starttls() now complies with RFC 3207 [https://tools.ietf.org/html/rfc3207.html] and forgets any knowledge obtained from the server not obtained from the TLS negotiation itself. (Patch contributed by Bill Fenner; bpo-829951 [https://bugs.python.org/issue?@action=redirect&bpo=829951].)

The socket module now supports TIPC (http://tipc.sourceforge.net/), a high-performance non-IP-based protocol designed for use in clustered environments. TIPC addresses are 4- or 5-tuples. (Contributed by Alberto Bertogli; bpo-1646 [https://bugs.python.org/issue?@action=redirect&bpo=1646].)

A new function, create_connection(), takes an address and connects to it using an optional timeout value, returning the connected socket object. This function also looks up the address’s type and connects to it using IPv4 or IPv6 as appropriate. Changing your code to use create_connection() instead of socket(socket.AF_INET, ...) may be all that’s required to make your code work with IPv6.

The base classes in the SocketServer module now support calling a handle_timeout() method after a span of inactivity specified by the server’s timeout attribute. (Contributed by Michael Pomraning.) The serve_forever() method now takes an optional poll interval measured in seconds, controlling how often the server will check for a shutdown request. (Contributed by Pedro Werneck and Jeffrey Yasskin; bpo-742598 [https://bugs.python.org/issue?@action=redirect&bpo=742598], bpo-1193577 [https://bugs.python.org/issue?@action=redirect&bpo=1193577].)

The sqlite3 module, maintained by Gerhard Häring, has been updated from version 2.3.2 in Python 2.5 to version 2.4.1.

The struct module now supports the C99 _Bool type, using the format character '?'. (Contributed by David Remahl.)

The Popen objects provided by the subprocess module now have terminate(), kill(), and send_signal() methods. On Windows, send_signal() only supports the SIGTERM signal, and all these methods are aliases for the Win32 API function TerminateProcess(). (Contributed by Christian Heimes.)

A new variable in the sys module, float_info, is an object containing information derived from the float.h file about the platform’s floating-point support. Attributes of this object include mant_dig (number of digits in the mantissa), epsilon (smallest difference between 1.0 and the next largest value representable), and several others. (Contributed by Christian Heimes; bpo-1534 [https://bugs.python.org/issue?@action=redirect&bpo=1534].)

Another new variable, dont_write_bytecode, controls whether Python writes any .pyc or .pyo files on importing a module. If this variable is true, the compiled files are not written. The variable is initially set on start-up by supplying the -B switch to the Python interpreter, or by setting the PYTHONDONTWRITEBYTECODE environment variable before running the interpreter. Python code can subsequently change the value of this variable to control whether bytecode files are written or not. (Contributed by Neal Norwitz and Georg Brandl.)

Information about the command-line arguments supplied to the Python interpreter is available by reading attributes of a named tuple available as sys.flags. For example, the verbose attribute is true if Python was executed in verbose mode, debug is true in debugging mode, etc. These attributes are all read-only. (Contributed by Christian Heimes.)

A new function, getsizeof(), takes a Python object and returns the amount of memory used by the object, measured in bytes. Built-in objects return correct results; third-party extensions may not, but can define a __sizeof__() method to return the object’s size. (Contributed by Robert Schuppenies; bpo-2898 [https://bugs.python.org/issue?@action=redirect&bpo=2898].)

It’s now possible to determine the current profiler and tracer functions by calling sys.getprofile() and sys.gettrace(). (Contributed by Georg Brandl; bpo-1648 [https://bugs.python.org/issue?@action=redirect&bpo=1648].)

The tarfile module now supports POSIX.1-2001 (pax) tarfiles in addition to the POSIX.1-1988 (ustar) and GNU tar formats that were already supported. The default format is GNU tar; specify the format parameter to open a file using a different format:

tar = tarfile.open("output.tar", "w",
                   format=tarfile.PAX_FORMAT)

The new encoding and errors parameters specify an encoding and an error handling scheme for character conversions. 'strict', 'ignore', and 'replace' are the three standard ways Python can handle errors,; 'utf-8' is a special value that replaces bad characters with their UTF-8 representation. (Character conversions occur because the PAX format supports Unicode filenames, defaulting to UTF-8 encoding.)

The TarFile.add() method now accepts an exclude argument that’s a function that can be used to exclude certain filenames from an archive. The function must take a filename and return true if the file should be excluded or false if it should be archived. The function is applied to both the name initially passed to add() and to the names of files in recursively-added directories.

(All changes contributed by Lars Gustäbel).

An optional timeout parameter was added to the telnetlib.Telnet class constructor, specifying a timeout measured in seconds. (Added by Facundo Batista.)

The tempfile.NamedTemporaryFile class usually deletes the temporary file it created when the file is closed. This behaviour can now be changed by passing delete=False to the constructor. (Contributed by Damien Miller; bpo-1537850 [https://bugs.python.org/issue?@action=redirect&bpo=1537850].)

A new class, SpooledTemporaryFile, behaves like a temporary file but stores its data in memory until a maximum size is exceeded. On reaching that limit, the contents will be written to an on-disk temporary file. (Contributed by Dustin J. Mitchell.)

The NamedTemporaryFile and SpooledTemporaryFile classes both work as context managers, so you can write with tempfile.NamedTemporaryFile() as tmp: .... (Contributed by Alexander Belopolsky; bpo-2021 [https://bugs.python.org/issue?@action=redirect&bpo=2021].)

The test.test_support module gained a number of context managers useful for writing tests. EnvironmentVarGuard() is a context manager that temporarily changes environment variables and automatically restores them to their old values.

Another context manager, TransientResource, can surround calls to resources that may or may not be available; it will catch and ignore a specified list of exceptions. For example, a network test may ignore certain failures when connecting to an external web site:

with test_support.TransientResource(IOError,
                                errno=errno.ETIMEDOUT):
    f = urllib.urlopen('https://sf.net')
    ...

Finally, check_warnings() resets the warning module’s warning filters and returns an object that will record all warning messages triggered (bpo-3781 [https://bugs.python.org/issue?@action=redirect&bpo=3781]):

with test_support.check_warnings() as wrec:
    warnings.simplefilter("always")
    # ... code that triggers a warning ...
    assert str(wrec.message) == "function is outdated"
    assert len(wrec.warnings) == 1, "Multiple warnings raised"

(Contributed by Brett Cannon.)

The textwrap module can now preserve existing whitespace at the beginnings and ends of the newly-created lines by specifying drop_whitespace=False as an argument:

>>> S = """This  sentence  has a bunch   of
...   extra   whitespace."""
>>> print textwrap.fill(S, width=15)
This  sentence
has a bunch
of    extra
whitespace.
>>> print textwrap.fill(S, drop_whitespace=False, width=15)
This  sentence
  has a bunch
   of    extra
   whitespace.
>>>

(Contributed by Dwayne Bailey; bpo-1581073 [https://bugs.python.org/issue?@action=redirect&bpo=1581073].)

The threading module API is being changed to use properties such as daemon instead of setDaemon() and isDaemon() methods, and some methods have been renamed to use underscores instead of camel-case; for example, the activeCount() method is renamed to active_count(). Both the 2.6 and 3.0 versions of the module support the same properties and renamed methods, but don’t remove the old methods. No date has been set for the deprecation of the old APIs in Python 3.x; the old APIs won’t be removed in any 2.x version. (Carried out by several people, most notably Benjamin Peterson.)

The threading module’s Thread objects gained an ident property that returns the thread’s identifier, a nonzero integer. (Contributed by Gregory P. Smith; bpo-2871 [https://bugs.python.org/issue?@action=redirect&bpo=2871].)

The timeit module now accepts callables as well as strings for the statement being timed and for the setup code. Two convenience functions were added for creating Timer instances: repeat(stmt, setup, time, repeat, number) and timeit(stmt, setup, time, number) create an instance and call the corresponding method. (Contributed by Erik Demaine; bpo-1533909 [https://bugs.python.org/issue?@action=redirect&bpo=1533909].)

The Tkinter module now accepts lists and tuples for options, separating the elements by spaces before passing the resulting value to Tcl/Tk. (Contributed by Guilherme Polo; bpo-2906 [https://bugs.python.org/issue?@action=redirect&bpo=2906].)

The turtle module for turtle graphics was greatly enhanced by Gregor Lingl. New features in the module include:

Better animation of turtle movement and rotation.

Control over turtle movement using the new delay(), tracer(), and speed() methods.

The ability to set new shapes for the turtle, and to define a new coordinate system.

Turtles now have an undo() method that can roll back actions.

Simple support for reacting to input events such as mouse and keyboard activity, making it possible to write simple games.

A turtle.cfg file can be used to customize the starting appearance of the turtle’s screen.

The module’s docstrings can be replaced by new docstrings that have been translated into another language.

(bpo-1513695 [https://bugs.python.org/issue?@action=redirect&bpo=1513695])

An optional timeout parameter was added to the urllib.urlopen() function and the urllib.ftpwrapper class constructor, as well as the urllib2.urlopen() function. The parameter specifies a timeout measured in seconds. For example:

>>> u = urllib2.urlopen("http://slow.example.com",
                        timeout=3)
Traceback (most recent call last):
  ...
urllib2.URLError: <urlopen error timed out>
>>>

(Added by Facundo Batista.)

The Unicode database provided by the unicodedata module has been updated to version 5.1.0. (Updated by Martin von Löwis; bpo-3811 [https://bugs.python.org/issue?@action=redirect&bpo=3811].)

The warnings module’s formatwarning() and showwarning() gained an optional line argument that can be used to supply the line of source code. (Added as part of bpo-1631171 [https://bugs.python.org/issue?@action=redirect&bpo=1631171], which re-implemented part of the warnings module in C code.)

A new function, catch_warnings(), is a context manager intended for testing purposes that lets you temporarily modify the warning filters and then restore their original values (bpo-3781 [https://bugs.python.org/issue?@action=redirect&bpo=3781]).

The XML-RPC SimpleXMLRPCServer and DocXMLRPCServer classes can now be prevented from immediately opening and binding to their socket by passing False as the bind_and_activate constructor parameter. This can be used to modify the instance’s allow_reuse_address attribute before calling the server_bind() and server_activate() methods to open the socket and begin listening for connections. (Contributed by Peter Parente; bpo-1599845 [https://bugs.python.org/issue?@action=redirect&bpo=1599845].)

SimpleXMLRPCServer also has a _send_traceback_header attribute; if true, the exception and formatted traceback are returned as HTTP headers “X-Exception” and “X-Traceback”. This feature is for debugging purposes only and should not be used on production servers because the tracebacks might reveal passwords or other sensitive information. (Contributed by Alan McIntyre as part of his project for Google’s Summer of Code 2007.)

The xmlrpclib module no longer automatically converts datetime.date and datetime.time to the xmlrpclib.DateTime type; the conversion semantics were not necessarily correct for all applications. Code using xmlrpclib should convert date and time instances. (bpo-1330538 [https://bugs.python.org/issue?@action=redirect&bpo=1330538]) The code can also handle dates before 1900 (contributed by Ralf Schmitt; bpo-2014 [https://bugs.python.org/issue?@action=redirect&bpo=2014]) and 64-bit integers represented by using <i8> in XML-RPC responses (contributed by Riku Lindblad; bpo-2985 [https://bugs.python.org/issue?@action=redirect&bpo=2985]).

The zipfile module’s ZipFile class now has extract() and extractall() methods that will unpack a single file or all the files in the archive to the current directory, or to a specified directory:

z = zipfile.ZipFile('python-251.zip')

# Unpack a single file, writing it relative
# to the /tmp directory.
z.extract('Python/sysmodule.c', '/tmp')

# Unpack all the files in the archive.
z.extractall()

(Contributed by Alan McIntyre; bpo-467924 [https://bugs.python.org/issue?@action=redirect&bpo=467924].)

The open(), read() and extract() methods can now take either a filename or a ZipInfo object. This is useful when an archive accidentally contains a duplicated filename. (Contributed by Graham Horler; bpo-1775025 [https://bugs.python.org/issue?@action=redirect&bpo=1775025].)

Finally, zipfile now supports using Unicode filenames for archived files. (Contributed by Alexey Borzenkov; bpo-1734346 [https://bugs.python.org/issue?@action=redirect&bpo=1734346].)

The ast module

The ast module provides an Abstract Syntax Tree representation of Python code, and Armin Ronacher contributed a set of helper functions that perform a variety of common tasks. These will be useful for HTML templating packages, code analyzers, and similar tools that process Python code.

The parse() function takes an expression and returns an AST. The dump() function outputs a representation of a tree, suitable for debugging:

import ast

t = ast.parse("""
d = {}
for i in 'abcdefghijklm':
    d[i + i] = ord(i) - ord('a') + 1
print d
""")
print ast.dump(t)

This outputs a deeply nested tree:

Module(body=[
  Assign(targets=[
    Name(id='d', ctx=Store())
   ], value=Dict(keys=[], values=[]))
  For(target=Name(id='i', ctx=Store()),
      iter=Str(s='abcdefghijklm'), body=[
    Assign(targets=[
      Subscript(value=
        Name(id='d', ctx=Load()),
          slice=
          Index(value=
            BinOp(left=Name(id='i', ctx=Load()), op=Add(),
             right=Name(id='i', ctx=Load()))), ctx=Store())
     ], value=
     BinOp(left=
      BinOp(left=
       Call(func=
        Name(id='ord', ctx=Load()), args=[
          Name(id='i', ctx=Load())
         ], keywords=[], starargs=None, kwargs=None),
       op=Sub(), right=Call(func=
        Name(id='ord', ctx=Load()), args=[
          Str(s='a')
         ], keywords=[], starargs=None, kwargs=None)),
       op=Add(), right=Num(n=1)))
    ], orelse=[])
   Print(dest=None, values=[
     Name(id='d', ctx=Load())
   ], nl=True)
 ])

The literal_eval() method takes a string or an AST representing a literal expression, parses and evaluates it, and returns the resulting value. A literal expression is a Python expression containing only strings, numbers, dictionaries, etc. but no statements or function calls. If you need to evaluate an expression but cannot accept the security risk of using an eval() call, literal_eval() will handle it safely:

>>> literal = '("a", "b", {2:4, 3:8, 1:2})'
>>> print ast.literal_eval(literal)
('a', 'b', {1: 2, 2: 4, 3: 8})
>>> print ast.literal_eval('"a" + "b"')
Traceback (most recent call last):
  ...
ValueError: malformed string

The module also includes NodeVisitor and NodeTransformer classes for traversing and modifying an AST, and functions for common transformations such as changing line numbers.

The future_builtins module

Python 3.0 makes many changes to the repertoire of built-in functions, and most of the changes can’t be introduced in the Python 2.x series because they would break compatibility. The future_builtins module provides versions of these built-in functions that can be imported when writing 3.0-compatible code.

The functions in this module currently include:

ascii(obj): equivalent to repr(). In Python 3.0, repr() will return a Unicode string, while ascii() will return a pure ASCII bytestring.

filter(predicate, iterable), map(func, iterable1, ...): the 3.0 versions return iterators, unlike the 2.x builtins which return lists.

hex(value), oct(value): instead of calling the __hex__() or __oct__() methods, these versions will call the __index__() method and convert the result to hexadecimal or octal. oct() will use the new 0o notation for its result.

The json module: JavaScript Object Notation

The new json module supports the encoding and decoding of Python types in JSON (Javascript Object Notation). JSON is a lightweight interchange format often used in web applications. For more information about JSON, see http://www.json.org.

json comes with support for decoding and encoding most built-in Python types. The following example encodes and decodes a dictionary:

>>> import json
>>> data = {"spam": "foo", "parrot": 42}
>>> in_json = json.dumps(data) # Encode the data
>>> in_json
'{"parrot": 42, "spam": "foo"}'
>>> json.loads(in_json) # Decode into a Python object
{"spam": "foo", "parrot": 42}

It’s also possible to write your own decoders and encoders to support more types. Pretty-printing of the JSON strings is also supported.

json (originally called simplejson) was written by Bob Ippolito.

The plistlib module: A Property-List Parser

The .plist format is commonly used on Mac OS X to store basic data types (numbers, strings, lists, and dictionaries) by serializing them into an XML-based format. It resembles the XML-RPC serialization of data types.

Despite being primarily used on Mac OS X, the format has nothing Mac-specific about it and the Python implementation works on any platform that Python supports, so the plistlib module has been promoted to the standard library.

Using the module is simple:

import sys
import plistlib
import datetime

# Create data structure
data_struct = dict(lastAccessed=datetime.datetime.now(),
                   version=1,
                   categories=('Personal','Shared','Private'))

# Create string containing XML.
plist_str = plistlib.writePlistToString(data_struct)
new_struct = plistlib.readPlistFromString(plist_str)
print data_struct
print new_struct

# Write data structure to a file and read it back.
plistlib.writePlist(data_struct, '/tmp/customizations.plist')
new_struct = plistlib.readPlist('/tmp/customizations.plist')

# read/writePlist accepts file-like objects as well as paths.
plistlib.writePlist(data_struct, sys.stdout)

ctypes Enhancements

Thomas Heller continued to maintain and enhance the ctypes module.

ctypes now supports a c_bool datatype that represents the C99 bool type. (Contributed by David Remahl; bpo-1649190 [https://bugs.python.org/issue?@action=redirect&bpo=1649190].)

The ctypes string, buffer and array types have improved support for extended slicing syntax, where various combinations of (start, stop, step) are supplied. (Implemented by Thomas Wouters.)

All ctypes data types now support from_buffer() and from_buffer_copy() methods that create a ctypes instance based on a provided buffer object. from_buffer_copy() copies the contents of the object, while from_buffer() will share the same memory area.

A new calling convention tells ctypes to clear the errno or Win32 LastError variables at the outset of each wrapped call. (Implemented by Thomas Heller; bpo-1798 [https://bugs.python.org/issue?@action=redirect&bpo=1798].)

You can now retrieve the Unix errno variable after a function call. When creating a wrapped function, you can supply use_errno=True as a keyword parameter to the DLL() function and then call the module-level methods set_errno() and get_errno() to set and retrieve the error value.

The Win32 LastError variable is similarly supported by the DLL(), OleDLL(), and WinDLL() functions. You supply use_last_error=True as a keyword parameter and then call the module-level methods set_last_error() and get_last_error().

The byref() function, used to retrieve a pointer to a ctypes instance, now has an optional offset parameter that is a byte count that will be added to the returned pointer.

Improved SSL Support

Bill Janssen made extensive improvements to Python 2.6’s support for the Secure Sockets Layer by adding a new module, ssl, that’s built atop the OpenSSL [https://www.openssl.org/] library. This new module provides more control over the protocol negotiated, the X.509 certificates used, and has better support for writing SSL servers (as opposed to clients) in Python. The existing SSL support in the socket module hasn’t been removed and continues to work, though it will be removed in Python 3.0.

To use the new module, you must first create a TCP connection in the usual way and then pass it to the ssl.wrap_socket() function. It’s possible to specify whether a certificate is required, and to obtain certificate info by calling the getpeercert() method.

더 보기

The documentation for the ssl module.

Deprecations and Removals

String exceptions have been removed. Attempting to use them raises a TypeError.

Changes to the Exception interface as dictated by PEP 352 [https://www.python.org/dev/peps/pep-0352] continue to be made. For 2.6, the message attribute is being deprecated in favor of the args attribute.

(3.0-warning mode) Python 3.0 will feature a reorganized standard library that will drop many outdated modules and rename others. Python 2.6 running in 3.0-warning mode will warn about these modules when they are imported.

The list of deprecated modules is: audiodev, bgenlocations, buildtools, bundlebuilder, Canvas, compiler, dircache, dl, fpformat, gensuitemodule, ihooks, imageop, imgfile, linuxaudiodev, mhlib, mimetools, multifile, new, pure, statvfs, sunaudiodev, test.testall, and toaiff.

The gopherlib module has been removed.

The MimeWriter module and mimify module have been deprecated; use the email package instead.

The md5 module has been deprecated; use the hashlib module instead.

The posixfile module has been deprecated; fcntl.lockf() provides better locking.

The popen2 module has been deprecated; use the subprocess module.

The rgbimg module has been removed.

The sets module has been deprecated; it’s better to use the built-in set and frozenset types.

The sha module has been deprecated; use the hashlib module instead.

Build and C API Changes

Changes to Python’s build process and to the C API include:

Python now must be compiled with C89 compilers (after 19 years!). This means that the Python source tree has dropped its own implementations of memmove() and strerror(), which are in the C89 standard library.

Python 2.6 can be built with Microsoft Visual Studio 2008 (version 9.0), and this is the new default compiler. See the PCbuild directory for the build files. (Implemented by Christian Heimes.)

On Mac OS X, Python 2.6 can be compiled as a 4-way universal build. The configure script can take a --with-universal-archs=[32-bit|64-bit|all] switch, controlling whether the binaries are built for 32-bit architectures (x86, PowerPC), 64-bit (x86-64 and PPC-64), or both. (Contributed by Ronald Oussoren.)

The BerkeleyDB module now has a C API object, available as bsddb.db.api. This object can be used by other C extensions that wish to use the bsddb module for their own purposes. (Contributed by Duncan Grisby.)

The new buffer interface, previously described in the PEP 3118 section, adds PyObject_GetBuffer() and PyBuffer_Release(), as well as a few other functions.

Python’s use of the C stdio library is now thread-safe, or at least as thread-safe as the underlying library is. A long-standing potential bug occurred if one thread closed a file object while another thread was reading from or writing to the object. In 2.6 file objects have a reference count, manipulated by the PyFile_IncUseCount() and PyFile_DecUseCount() functions. File objects can’t be closed unless the reference count is zero. PyFile_IncUseCount() should be called while the GIL is still held, before carrying out an I/O operation using the FILE * pointer, and PyFile_DecUseCount() should be called immediately after the GIL is re-acquired. (Contributed by Antoine Pitrou and Gregory P. Smith.)

Importing modules simultaneously in two different threads no longer deadlocks; it will now raise an ImportError. A new API function, PyImport_ImportModuleNoBlock(), will look for a module in sys.modules first, then try to import it after acquiring an import lock. If the import lock is held by another thread, an ImportError is raised. (Contributed by Christian Heimes.)

Several functions return information about the platform’s floating-point support. PyFloat_GetMax() returns the maximum representable floating point value, and PyFloat_GetMin() returns the minimum positive value. PyFloat_GetInfo() returns an object containing more information from the float.h file, such as "mant_dig" (number of digits in the mantissa), "epsilon" (smallest difference between 1.0 and the next largest value representable), and several others. (Contributed by Christian Heimes; bpo-1534 [https://bugs.python.org/issue?@action=redirect&bpo=1534].)

C functions and methods that use PyComplex_AsCComplex() will now accept arguments that have a __complex__() method. In particular, the functions in the cmath module will now accept objects with this method. This is a backport of a Python 3.0 change. (Contributed by Mark Dickinson; bpo-1675423 [https://bugs.python.org/issue?@action=redirect&bpo=1675423].)

Python’s C API now includes two functions for case-insensitive string comparisons, PyOS_stricmp(char*, char*) and PyOS_strnicmp(char*, char*, Py_ssize_t). (Contributed by Christian Heimes; bpo-1635 [https://bugs.python.org/issue?@action=redirect&bpo=1635].)

Many C extensions define their own little macro for adding integers and strings to the module’s dictionary in the init* function. Python 2.6 finally defines standard macros for adding values to a module, PyModule_AddStringMacro and PyModule_AddIntMacro(). (Contributed by Christian Heimes.)

Some macros were renamed in both 3.0 and 2.6 to make it clearer that they are macros, not functions. Py_Size() became Py_SIZE(), Py_Type() became Py_TYPE(), and Py_Refcnt() became Py_REFCNT(). The mixed-case macros are still available in Python 2.6 for backward compatibility. (bpo-1629 [https://bugs.python.org/issue?@action=redirect&bpo=1629])

Distutils now places C extensions it builds in a different directory when running on a debug version of Python. (Contributed by Collin Winter; bpo-1530959 [https://bugs.python.org/issue?@action=redirect&bpo=1530959].)

Several basic data types, such as integers and strings, maintain internal free lists of objects that can be re-used. The data structures for these free lists now follow a naming convention: the variable is always named free_list, the counter is always named numfree, and a macro Py<typename>_MAXFREELIST is always defined.

A new Makefile target, “make patchcheck”, prepares the Python source tree for making a patch: it fixes trailing whitespace in all modified .py files, checks whether the documentation has been changed, and reports whether the Misc/ACKS and Misc/NEWS files have been updated. (Contributed by Brett Cannon.)

Another new target, “make profile-opt”, compiles a Python binary using GCC’s profile-guided optimization. It compiles Python with profiling enabled, runs the test suite to obtain a set of profiling results, and then compiles using these results for optimization. (Contributed by Gregory P. Smith.)

Port-Specific Changes: Windows

The support for Windows 95, 98, ME and NT4 has been dropped. Python 2.6 requires at least Windows 2000 SP4.

The new default compiler on Windows is Visual Studio 2008 (version 9.0). The build directories for Visual Studio 2003 (version 7.1) and 2005 (version 8.0) were moved into the PC/ directory. The new PCbuild directory supports cross compilation for X64, debug builds and Profile Guided Optimization (PGO). PGO builds are roughly 10% faster than normal builds. (Contributed by Christian Heimes with help from Amaury Forgeot d’Arc and Martin von Löwis.)

The msvcrt module now supports both the normal and wide char variants of the console I/O API. The getwch() function reads a keypress and returns a Unicode value, as does the getwche() function. The putwch() function takes a Unicode character and writes it to the console. (Contributed by Christian Heimes.)

os.path.expandvars() will now expand environment variables in the form “%var%”, and “~user” will be expanded into the user’s home directory path. (Contributed by Josiah Carlson; bpo-957650 [https://bugs.python.org/issue?@action=redirect&bpo=957650].)

The socket module’s socket objects now have an ioctl() method that provides a limited interface to the WSAIoctl() system interface.

The _winreg module now has a function, ExpandEnvironmentStrings(), that expands environment variable references such as %NAME% in an input string. The handle objects provided by this module now support the context protocol, so they can be used in with statements. (Contributed by Christian Heimes.)

_winreg also has better support for x64 systems, exposing the DisableReflectionKey(), EnableReflectionKey(), and QueryReflectionKey() functions, which enable and disable registry reflection for 32-bit processes running on 64-bit systems. (bpo-1753245 [https://bugs.python.org/issue?@action=redirect&bpo=1753245])

The msilib module’s Record object gained GetInteger() and GetString() methods that return field values as an integer or a string. (Contributed by Floris Bruynooghe; bpo-2125 [https://bugs.python.org/issue?@action=redirect&bpo=2125].)

Port-Specific Changes: Mac OS X

When compiling a framework build of Python, you can now specify the framework name to be used by providing the --with-framework-name= option to the configure script.

The macfs module has been removed. This in turn required the macostools.touched() function to be removed because it depended on the macfs module. (bpo-1490190 [https://bugs.python.org/issue?@action=redirect&bpo=1490190])

Many other Mac OS modules have been deprecated and will be removed in Python 3.0: _builtinSuites, aepack, aetools, aetypes, applesingle, appletrawmain, appletrunner, argvemulator, Audio_mac, autoGIL, Carbon, cfmfile, CodeWarrior, ColorPicker, EasyDialogs, Explorer, Finder, FrameWork, findertools, ic, icglue, icopen, macerrors, MacOS, macfs, macostools, macresource, MiniAEFrame, Nav, Netscape, OSATerminology, pimp, PixMapWrapper, StdSuites, SystemEvents, Terminal, and terminalcommand.

Port-Specific Changes: IRIX

A number of old IRIX-specific modules were deprecated and will be removed in Python 3.0: al and AL, cd, cddb, cdplayer, CL and cl, DEVICE, ERRNO, FILE, FL and fl, flp, fm, GET, GLWS, GL and gl, IN, IOCTL, jpeg, panelparser, readcd, SV and sv, torgb, videoreader, and WAIT.

Porting to Python 2.6

This section lists previously described changes and other bugfixes that may require changes to your code:

Classes that aren’t supposed to be hashable should set __hash__ = None in their definitions to indicate the fact.

String exceptions have been removed. Attempting to use them raises a TypeError.

The __init__() method of collections.deque now clears any existing contents of the deque before adding elements from the iterable. This change makes the behavior match list.__init__().

object.__init__() previously accepted arbitrary arguments and keyword arguments, ignoring them. In Python 2.6, this is no longer allowed and will result in a TypeError. This will affect __init__() methods that end up calling the corresponding method on object (perhaps through using super()). See bpo-1683368 [https://bugs.python.org/issue?@action=redirect&bpo=1683368] for discussion.

The Decimal constructor now accepts leading and trailing whitespace when passed a string. Previously it would raise an InvalidOperation exception. On the other hand, the create_decimal() method of Context objects now explicitly disallows extra whitespace, raising a ConversionSyntax exception.

Due to an implementation accident, if you passed a file path to the built-in __import__() function, it would actually import the specified file. This was never intended to work, however, and the implementation now explicitly checks for this case and raises an ImportError.

C API: the PyImport_Import() and PyImport_ImportModule() functions now default to absolute imports, not relative imports. This will affect C extensions that import other modules.

C API: extension data types that shouldn’t be hashable should define their tp_hash slot to PyObject_HashNotImplemented().

The socket module exception socket.error now inherits from IOError. Previously it wasn’t a subclass of StandardError but now it is, through IOError. (Implemented by Gregory P. Smith; bpo-1706815 [https://bugs.python.org/issue?@action=redirect&bpo=1706815].)

The xmlrpclib module no longer automatically converts datetime.date and datetime.time to the xmlrpclib.DateTime type; the conversion semantics were not necessarily correct for all applications. Code using xmlrpclib should convert date and time instances. (bpo-1330538 [https://bugs.python.org/issue?@action=redirect&bpo=1330538])

(3.0-warning mode) The Exception class now warns when accessed using slicing or index access; having Exception behave like a tuple is being phased out.

(3.0-warning mode) inequality comparisons between two dictionaries or two objects that don’t implement comparison methods are reported as warnings. dict1 == dict2 still works, but dict1 < dict2 is being phased out.

Comparisons between cells, which are an implementation detail of Python’s scoping rules, also cause warnings because such comparisons are forbidden entirely in 3.0.

Acknowledgements

The author would like to thank the following people for offering suggestions, corrections and assistance with various drafts of this article: Georg Brandl, Steve Brown, Nick Coghlan, Ralph Corderoy, Jim Jewett, Kent Johnson, Chris Lambacher, Martin Michlmayr, Antoine Pitrou, Brian Warner.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬의 새로운 기능 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬의 새로운 기능 »

|

What’s New in Python 2.5

Author

A.M. Kuchling

This article explains the new features in Python 2.5. The final release of Python 2.5 is scheduled for August 2006; PEP 356 [https://www.python.org/dev/peps/pep-0356] describes the planned release schedule.

The changes in Python 2.5 are an interesting mix of language and library improvements. The library enhancements will be more important to Python’s user community, I think, because several widely-useful packages were added. New modules include ElementTree for XML processing (xml.etree), the SQLite database module (sqlite), and the ctypes module for calling C functions.

The language changes are of middling significance. Some pleasant new features were added, but most of them aren’t features that you’ll use every day. Conditional expressions were finally added to the language using a novel syntax; see section PEP 308: Conditional Expressions. The new ‘with’ statement will make writing cleanup code easier (section PEP 343: The ‘with’ statement). Values can now be passed into generators (section PEP 342: New Generator Features). Imports are now visible as either absolute or relative (section PEP 328: Absolute and Relative Imports). Some corner cases of exception handling are handled better (section PEP 341: Unified try/except/finally). All these improvements are worthwhile, but they’re improvements to one specific language feature or another; none of them are broad modifications to Python’s semantics.

As well as the language and library additions, other improvements and bugfixes were made throughout the source tree. A search through the SVN change logs finds there were 353 patches applied and 458 bugs fixed between Python 2.4 and 2.5. (Both figures are likely to be underestimates.)

This article doesn’t try to be a complete specification of the new features; instead changes are briefly introduced using helpful examples. For full details, you should always refer to the documentation for Python 2.5 at https://docs.python.org. If you want to understand the complete implementation and design rationale, refer to the PEP for a particular new feature.

Comments, suggestions, and error reports for this document are welcome; please e-mail them to the author or open a bug in the Python bug tracker.

PEP 308: Conditional Expressions

For a long time, people have been requesting a way to write conditional expressions, which are expressions that return value A or value B depending on whether a Boolean value is true or false. A conditional expression lets you write a single assignment statement that has the same effect as the following:

if condition:
    x = true_value
else:
    x = false_value

There have been endless tedious discussions of syntax on both python-dev and comp.lang.python. A vote was even held that found the majority of voters wanted conditional expressions in some form, but there was no syntax that was preferred by a clear majority. Candidates included C’s cond ? true_v : false_v, if cond then true_v else false_v, and 16 other variations.

Guido van Rossum eventually chose a surprising syntax:

x = true_value if condition else false_value

Evaluation is still lazy as in existing Boolean expressions, so the order of evaluation jumps around a bit. The condition expression in the middle is evaluated first, and the true_value expression is evaluated only if the condition was true. Similarly, the false_value expression is only evaluated when the condition is false.

This syntax may seem strange and backwards; why does the condition go in the middle of the expression, and not in the front as in C’s c ? x : y? The decision was checked by applying the new syntax to the modules in the standard library and seeing how the resulting code read. In many cases where a conditional expression is used, one value seems to be the ‘common case’ and one value is an ‘exceptional case’, used only on rarer occasions when the condition isn’t met. The conditional syntax makes this pattern a bit more obvious:

contents = ((doc + '\n') if doc else '')

I read the above statement as meaning “here contents is usually assigned a value of doc+'\n'; sometimes doc is empty, in which special case an empty string is returned.” I doubt I will use conditional expressions very often where there isn’t a clear common and uncommon case.

There was some discussion of whether the language should require surrounding conditional expressions with parentheses. The decision was made to not require parentheses in the Python language’s grammar, but as a matter of style I think you should always use them. Consider these two statements:

# First version -- no parens
level = 1 if logging else 0

# Second version -- with parens
level = (1 if logging else 0)

In the first version, I think a reader’s eye might group the statement into ‘level = 1’, ‘if logging’, ‘else 0’, and think that the condition decides whether the assignment to level is performed. The second version reads better, in my opinion, because it makes it clear that the assignment is always performed and the choice is being made between two values.

Another reason for including the brackets: a few odd combinations of list comprehensions and lambdas could look like incorrect conditional expressions. See PEP 308 [https://www.python.org/dev/peps/pep-0308] for some examples. If you put parentheses around your conditional expressions, you won’t run into this case.

더 보기

PEP 308 [https://www.python.org/dev/peps/pep-0308] - Conditional Expressions

PEP written by Guido van Rossum and Raymond D. Hettinger; implemented by Thomas Wouters.

PEP 309: Partial Function Application

The functools module is intended to contain tools for functional-style programming.

One useful tool in this module is the partial() function. For programs written in a functional style, you’ll sometimes want to construct variants of existing functions that have some of the parameters filled in. Consider a Python function f(a, b, c); you could create a new function g(b, c) that was equivalent to f(1, b, c). This is called “partial function application”.

partial() takes the arguments (function, arg1, arg2, ... kwarg1=value1, kwarg2=value2). The resulting object is callable, so you can just call it to invoke function with the filled-in arguments.

Here’s a small but realistic example:

import functools

def log (message, subsystem):
    "Write the contents of 'message' to the specified subsystem."
    print '%s: %s' % (subsystem, message)
    ...

server_log = functools.partial(log, subsystem='server')
server_log('Unable to open socket')

Here’s another example, from a program that uses PyGTK. Here a context-sensitive pop-up menu is being constructed dynamically. The callback provided for the menu option is a partially applied version of the open_item() method, where the first argument has been provided.

...
class Application:
    def open_item(self, path):
       ...
    def init (self):
        open_func = functools.partial(self.open_item, item_path)
        popup_menu.append( ("Open", open_func, 1) )

Another function in the functools module is the update_wrapper(wrapper, wrapped) function that helps you write well-behaved decorators. update_wrapper() copies the name, module, and docstring attribute to a wrapper function so that tracebacks inside the wrapped function are easier to understand. For example, you might write:

def my_decorator(f):
    def wrapper(*args, **kwds):
        print 'Calling decorated function'
        return f(*args, **kwds)
    functools.update_wrapper(wrapper, f)
    return wrapper

wraps() is a decorator that can be used inside your own decorators to copy the wrapped function’s information. An alternate version of the previous example would be:

def my_decorator(f):
    @functools.wraps(f)
    def wrapper(*args, **kwds):
        print 'Calling decorated function'
        return f(*args, **kwds)
    return wrapper

더 보기

PEP 309 [https://www.python.org/dev/peps/pep-0309] - Partial Function Application

PEP proposed and written by Peter Harris; implemented by Hye-Shik Chang and Nick Coghlan, with adaptations by Raymond Hettinger.

PEP 314: Metadata for Python Software Packages v1.1

Some simple dependency support was added to Distutils. The setup() function now has requires, provides, and obsoletes keyword parameters. When you build a source distribution using the sdist command, the dependency information will be recorded in the PKG-INFO file.

Another new keyword parameter is download_url, which should be set to a URL for the package’s source code. This means it’s now possible to look up an entry in the package index, determine the dependencies for a package, and download the required packages.

VERSION = '1.0'
setup(name='PyPackage',
      version=VERSION,
      requires=['numarray', 'zlib (>=1.1.4)'],
      obsoletes=['OldPackage']
      download_url=('http://www.example.com/pypackage/dist/pkg-%s.tar.gz'
                    % VERSION),
     )

Another new enhancement to the Python package index at https://pypi.org is storing source and binary archives for a package. The new upload Distutils command will upload a package to the repository.

Before a package can be uploaded, you must be able to build a distribution using the sdist Distutils command. Once that works, you can run python setup.py upload to add your package to the PyPI archive. Optionally you can GPG-sign the package by supplying the --sign and --identity options.

Package uploading was implemented by Martin von Löwis and Richard Jones.

더 보기

PEP 314 [https://www.python.org/dev/peps/pep-0314] - Metadata for Python Software Packages v1.1

PEP proposed and written by A.M. Kuchling, Richard Jones, and Fred Drake; implemented by Richard Jones and Fred Drake.

PEP 328: Absolute and Relative Imports

The simpler part of PEP 328 was implemented in Python 2.4: parentheses could now be used to enclose the names imported from a module using the from ... import ... statement, making it easier to import many different names.

The more complicated part has been implemented in Python 2.5: importing a module can be specified to use absolute or package-relative imports. The plan is to move toward making absolute imports the default in future versions of Python.

Let’s say you have a package directory like this:

pkg/
pkg/__init__.py
pkg/main.py
pkg/string.py

This defines a package named pkg containing the pkg.main and pkg.string submodules.

Consider the code in the main.py module. What happens if it executes the statement import string? In Python 2.4 and earlier, it will first look in the package’s directory to perform a relative import, finds pkg/string.py, imports the contents of that file as the pkg.string module, and that module is bound to the name string in the pkg.main module’s namespace.

That’s fine if pkg.string was what you wanted. But what if you wanted Python’s standard string module? There’s no clean way to ignore pkg.string and look for the standard module; generally you had to look at the contents of sys.modules, which is slightly unclean. Holger Krekel’s py.std package provides a tidier way to perform imports from the standard library, import py; py.std.string.join(), but that package isn’t available on all Python installations.

Reading code which relies on relative imports is also less clear, because a reader may be confused about which module, string or pkg.string, is intended to be used. Python users soon learned not to duplicate the names of standard library modules in the names of their packages’ submodules, but you can’t protect against having your submodule’s name being used for a new module added in a future version of Python.

In Python 2.5, you can switch import’s behaviour to absolute imports using a from __future__ import absolute_import directive. This absolute-import behaviour will become the default in a future version (probably Python 2.7). Once absolute imports are the default, import string will always find the standard library’s version. It’s suggested that users should begin using absolute imports as much as possible, so it’s preferable to begin writing from pkg import string in your code.

Relative imports are still possible by adding a leading period to the module name when using the from ... import form:

# Import names from pkg.string
from .string import name1, name2
# Import pkg.string
from . import string

This imports the string module relative to the current package, so in pkg.main this will import name1 and name2 from pkg.string. Additional leading periods perform the relative import starting from the parent of the current package. For example, code in the A.B.C module can do:

from . import D                 # Imports A.B.D
from .. import E                # Imports A.E
from ..F import G               # Imports A.F.G

Leading periods cannot be used with the import modname form of the import statement, only the from ... import form.

더 보기

PEP 328 [https://www.python.org/dev/peps/pep-0328] - Imports: Multi-Line and Absolute/Relative

PEP written by Aahz; implemented by Thomas Wouters.

https://pylib.readthedocs.io/

The py library by Holger Krekel, which contains the py.std package.

PEP 338: Executing Modules as Scripts

The -m switch added in Python 2.4 to execute a module as a script gained a few more abilities. Instead of being implemented in C code inside the Python interpreter, the switch now uses an implementation in a new module, runpy.

The runpy module implements a more sophisticated import mechanism so that it’s now possible to run modules in a package such as pychecker.checker. The module also supports alternative import mechanisms such as the zipimport module. This means you can add a .zip archive’s path to sys.path and then use the -m switch to execute code from the archive.

더 보기

PEP 338 [https://www.python.org/dev/peps/pep-0338] - Executing modules as scripts

PEP written and implemented by Nick Coghlan.

PEP 341: Unified try/except/finally

Until Python 2.5, the try statement came in two flavours. You could use a finally block to ensure that code is always executed, or one or more except blocks to catch specific exceptions. You couldn’t combine both except blocks and a finally block, because generating the right bytecode for the combined version was complicated and it wasn’t clear what the semantics of the combined statement should be.

Guido van Rossum spent some time working with Java, which does support the equivalent of combining except blocks and a finally block, and this clarified what the statement should mean. In Python 2.5, you can now write:

try:
    block-1 ...
except Exception1:
    handler-1 ...
except Exception2:
    handler-2 ...
else:
    else-block
finally:
    final-block

The code in block-1 is executed. If the code raises an exception, the various except blocks are tested: if the exception is of class Exception1, handler-1 is executed; otherwise if it’s of class Exception2, handler-2 is executed, and so forth. If no exception is raised, the else-block is executed.

No matter what happened previously, the final-block is executed once the code block is complete and any raised exceptions handled. Even if there’s an error in an exception handler or the else-block and a new exception is raised, the code in the final-block is still run.

더 보기

PEP 341 [https://www.python.org/dev/peps/pep-0341] - Unifying try-except and try-finally

PEP written by Georg Brandl; implementation by Thomas Lee.

PEP 342: New Generator Features

Python 2.5 adds a simple way to pass values into a generator. As introduced in Python 2.3, generators only produce output; once a generator’s code was invoked to create an iterator, there was no way to pass any new information into the function when its execution is resumed. Sometimes the ability to pass in some information would be useful. Hackish solutions to this include making the generator’s code look at a global variable and then changing the global variable’s value, or passing in some mutable object that callers then modify.

To refresh your memory of basic generators, here’s a simple example:

def counter (maximum):
    i = 0
    while i < maximum:
        yield i
        i += 1

When you call counter(10), the result is an iterator that returns the values from 0 up to 9. On encountering the yield statement, the iterator returns the provided value and suspends the function’s execution, preserving the local variables. Execution resumes on the following call to the iterator’s next() method, picking up after the yield statement.

In Python 2.3, yield was a statement; it didn’t return any value. In 2.5, yield is now an expression, returning a value that can be assigned to a variable or otherwise operated on:

val = (yield i)

I recommend that you always put parentheses around a yield expression when you’re doing something with the returned value, as in the above example. The parentheses aren’t always necessary, but it’s easier to always add them instead of having to remember when they’re needed.

(PEP 342 [https://www.python.org/dev/peps/pep-0342] explains the exact rules, which are that a yield-expression must always be parenthesized except when it occurs at the top-level expression on the right-hand side of an assignment. This means you can write val = yield i but have to use parentheses when there’s an operation, as in val = (yield i) + 12.)

Values are sent into a generator by calling its send(value) method. The generator’s code is then resumed and the yield expression returns the specified value. If the regular next() method is called, the yield returns None.

Here’s the previous example, modified to allow changing the value of the internal counter.

def counter (maximum):
    i = 0
    while i < maximum:
        val = (yield i)
        # If value provided, change counter
        if val is not None:
            i = val
        else:
            i += 1

And here’s an example of changing the counter:

>>> it = counter(10)
>>> print it.next()
0
>>> print it.next()
1
>>> print it.send(8)
8
>>> print it.next()
9
>>> print it.next()
Traceback (most recent call last):
  File "t.py", line 15, in ?
    print it.next()
StopIteration

yield will usually return None, so you should always check for this case. Don’t just use its value in expressions unless you’re sure that the send() method will be the only method used to resume your generator function.

In addition to send(), there are two other new methods on generators:

throw(type, value=None, traceback=None) is used to raise an exception inside the generator; the exception is raised by the yield expression where the generator’s execution is paused.

close() raises a new GeneratorExit exception inside the generator to terminate the iteration. On receiving this exception, the generator’s code must either raise GeneratorExit or StopIteration. Catching the GeneratorExit exception and returning a value is illegal and will trigger a RuntimeError; if the function raises some other exception, that exception is propagated to the caller. close() will also be called by Python’s garbage collector when the generator is garbage-collected.

If you need to run cleanup code when a GeneratorExit occurs, I suggest using a try: ... finally: suite instead of catching GeneratorExit.

The cumulative effect of these changes is to turn generators from one-way producers of information into both producers and consumers.

Generators also become coroutines, a more generalized form of subroutines. Subroutines are entered at one point and exited at another point (the top of the function, and a return statement), but coroutines can be entered, exited, and resumed at many different points (the yield statements). We’ll have to figure out patterns for using coroutines effectively in Python.

The addition of the close() method has one side effect that isn’t obvious. close() is called when a generator is garbage-collected, so this means the generator’s code gets one last chance to run before the generator is destroyed. This last chance means that try...finally statements in generators can now be guaranteed to work; the finally clause will now always get a chance to run. The syntactic restriction that you couldn’t mix yield statements with a try...finally suite has therefore been removed. This seems like a minor bit of language trivia, but using generators and try...finally is actually necessary in order to implement the with statement described by PEP 343. I’ll look at this new statement in the following section.

Another even more esoteric effect of this change: previously, the gi_frame attribute of a generator was always a frame object. It’s now possible for gi_frame to be None once the generator has been exhausted.

더 보기

PEP 342 [https://www.python.org/dev/peps/pep-0342] - Coroutines via Enhanced Generators

PEP written by Guido van Rossum and Phillip J. Eby; implemented by Phillip J. Eby. Includes examples of some fancier uses of generators as coroutines.

Earlier versions of these features were proposed in PEP 288 [https://www.python.org/dev/peps/pep-0288] by Raymond Hettinger and PEP 325 [https://www.python.org/dev/peps/pep-0325] by Samuele Pedroni.

https://en.wikipedia.org/wiki/Coroutine

The Wikipedia entry for coroutines.

http://www.sidhe.org/~dan/blog/archives/000178.html

An explanation of coroutines from a Perl point of view, written by Dan Sugalski.

PEP 343: The ‘with’ statement

The ‘with’ statement clarifies code that previously would use try...finally blocks to ensure that clean-up code is executed. In this section, I’ll discuss the statement as it will commonly be used. In the next section, I’ll examine the implementation details and show how to write objects for use with this statement.

The ‘with’ statement is a new control-flow structure whose basic structure is:

with expression [as variable]:
    with-block

The expression is evaluated, and it should result in an object that supports the context management protocol (that is, has __enter__() and __exit__() methods.

The object’s __enter__() is called before with-block is executed and therefore can run set-up code. It also may return a value that is bound to the name variable, if given. (Note carefully that variable is not assigned the result of expression.)

After execution of the with-block is finished, the object’s __exit__() method is called, even if the block raised an exception, and can therefore run clean-up code.

To enable the statement in Python 2.5, you need to add the following directive to your module:

from __future__ import with_statement

The statement will always be enabled in Python 2.6.

Some standard Python objects now support the context management protocol and can be used with the ‘with’ statement. File objects are one example:

with open('/etc/passwd', 'r') as f:
    for line in f:
        print line
        ... more processing code ...

After this statement has executed, the file object in f will have been automatically closed, even if the for loop raised an exception part-way through the block.

참고

In this case, f is the same object created by open(), because file.__enter__() returns self.

The threading module’s locks and condition variables also support the ‘with’ statement:

lock = threading.Lock()
with lock:
    # Critical section of code
    ...

The lock is acquired before the block is executed and always released once the block is complete.

The new localcontext() function in the decimal module makes it easy to save and restore the current decimal context, which encapsulates the desired precision and rounding characteristics for computations:

from decimal import Decimal, Context, localcontext

# Displays with default precision of 28 digits
v = Decimal('578')
print v.sqrt()

with localcontext(Context(prec=16)):
    # All code in this block uses a precision of 16 digits.
    # The original context is restored on exiting the block.
    print v.sqrt()

Writing Context Managers

Under the hood, the ‘with’ statement is fairly complicated. Most people will only use ‘with’ in company with existing objects and don’t need to know these details, so you can skip the rest of this section if you like. Authors of new objects will need to understand the details of the underlying implementation and should keep reading.

A high-level explanation of the context management protocol is:

The expression is evaluated and should result in an object called a “context manager”. The context manager must have __enter__() and __exit__() methods.

The context manager’s __enter__() method is called. The value returned is assigned to VAR. If no 'as VAR' clause is present, the value is simply discarded.

The code in BLOCK is executed.

If BLOCK raises an exception, the __exit__(type, value, traceback) is called with the exception details, the same values returned by sys.exc_info(). The method’s return value controls whether the exception is re-raised: any false value re-raises the exception, and True will result in suppressing it. You’ll only rarely want to suppress the exception, because if you do the author of the code containing the ‘with’ statement will never realize anything went wrong.

If BLOCK didn’t raise an exception, the __exit__() method is still called, but type, value, and traceback are all None.

Let’s think through an example. I won’t present detailed code but will only sketch the methods necessary for a database that supports transactions.

(For people unfamiliar with database terminology: a set of changes to the database are grouped into a transaction. Transactions can be either committed, meaning that all the changes are written into the database, or rolled back, meaning that the changes are all discarded and the database is unchanged. See any database textbook for more information.)

Let’s assume there’s an object representing a database connection. Our goal will be to let the user write code like this:

db_connection = DatabaseConnection()
with db_connection as cursor:
    cursor.execute('insert into ...')
    cursor.execute('delete from ...')
    # ... more operations ...

The transaction should be committed if the code in the block runs flawlessly or rolled back if there’s an exception. Here’s the basic interface for DatabaseConnection that I’ll assume:

class DatabaseConnection:
    # Database interface
    def cursor (self):
        "Returns a cursor object and starts a new transaction"
    def commit (self):
        "Commits current transaction"
    def rollback (self):
        "Rolls back current transaction"

The __enter__() method is pretty easy, having only to start a new transaction. For this application the resulting cursor object would be a useful result, so the method will return it. The user can then add as cursor to their ‘with’ statement to bind the cursor to a variable name.

class DatabaseConnection:
    ...
    def __enter__ (self):
        # Code to start a new transaction
        cursor = self.cursor()
        return cursor

The __exit__() method is the most complicated because it’s where most of the work has to be done. The method has to check if an exception occurred. If there was no exception, the transaction is committed. The transaction is rolled back if there was an exception.

In the code below, execution will just fall off the end of the function, returning the default value of None. None is false, so the exception will be re-raised automatically. If you wished, you could be more explicit and add a return statement at the marked location.

class DatabaseConnection:
    ...
    def __exit__ (self, type, value, tb):
        if tb is None:
            # No exception, so commit
            self.commit()
        else:
            # Exception occurred, so rollback.
            self.rollback()
            # return False

The contextlib module

The new contextlib module provides some functions and a decorator that are useful for writing objects for use with the ‘with’ statement.

The decorator is called contextmanager(), and lets you write a single generator function instead of defining a new class. The generator should yield exactly one value. The code up to the yield will be executed as the __enter__() method, and the value yielded will be the method’s return value that will get bound to the variable in the ‘with’ statement’s as clause, if any. The code after the yield will be executed in the __exit__() method. Any exception raised in the block will be raised by the yield statement.

Our database example from the previous section could be written using this decorator as:

from contextlib import contextmanager

@contextmanager
def db_transaction (connection):
    cursor = connection.cursor()
    try:
        yield cursor
    except:
        connection.rollback()
        raise
    else:
        connection.commit()

db = DatabaseConnection()
with db_transaction(db) as cursor:
    ...

The contextlib module also has a nested(mgr1, mgr2, ...) function that combines a number of context managers so you don’t need to write nested ‘with’ statements. In this example, the single ‘with’ statement both starts a database transaction and acquires a thread lock:

lock = threading.Lock()
with nested (db_transaction(db), lock) as (cursor, locked):
    ...

Finally, the closing(object) function returns object so that it can be bound to a variable, and calls object.close at the end of the block.

import urllib, sys
from contextlib import closing

with closing(urllib.urlopen('http://www.yahoo.com')) as f:
    for line in f:
        sys.stdout.write(line)

더 보기

PEP 343 [https://www.python.org/dev/peps/pep-0343] - The “with” statement

PEP written by Guido van Rossum and Nick Coghlan; implemented by Mike Bland, Guido van Rossum, and Neal Norwitz. The PEP shows the code generated for a ‘with’ statement, which can be helpful in learning how the statement works.

The documentation for the contextlib module.

PEP 352: Exceptions as New-Style Classes

Exception classes can now be new-style classes, not just classic classes, and the built-in Exception class and all the standard built-in exceptions (NameError, ValueError, etc.) are now new-style classes.

The inheritance hierarchy for exceptions has been rearranged a bit. In 2.5, the inheritance relationships are:

BaseException       # New in Python 2.5
|- KeyboardInterrupt
|- SystemExit
|- Exception
   |- (all other current built-in exceptions)

This rearrangement was done because people often want to catch all exceptions that indicate program errors. KeyboardInterrupt and SystemExit aren’t errors, though, and usually represent an explicit action such as the user hitting Control-C or code calling sys.exit(). A bare except: will catch all exceptions, so you commonly need to list KeyboardInterrupt and SystemExit in order to re-raise them. The usual pattern is:

try:
    ...
except (KeyboardInterrupt, SystemExit):
    raise
except:
    # Log error...
    # Continue running program...

In Python 2.5, you can now write except Exception to achieve the same result, catching all the exceptions that usually indicate errors but leaving KeyboardInterrupt and SystemExit alone. As in previous versions, a bare except: still catches all exceptions.

The goal for Python 3.0 is to require any class raised as an exception to derive from BaseException or some descendant of BaseException, and future releases in the Python 2.x series may begin to enforce this constraint. Therefore, I suggest you begin making all your exception classes derive from Exception now. It’s been suggested that the bare except: form should be removed in Python 3.0, but Guido van Rossum hasn’t decided whether to do this or not.

Raising of strings as exceptions, as in the statement raise "Error occurred", is deprecated in Python 2.5 and will trigger a warning. The aim is to be able to remove the string-exception feature in a few releases.

더 보기

PEP 352 [https://www.python.org/dev/peps/pep-0352] - Required Superclass for Exceptions

PEP written by Brett Cannon and Guido van Rossum; implemented by Brett Cannon.

PEP 353: Using ssize_t as the index type

A wide-ranging change to Python’s C API, using a new Py_ssize_t type definition instead of int, will permit the interpreter to handle more data on 64-bit platforms. This change doesn’t affect Python’s capacity on 32-bit platforms.

Various pieces of the Python interpreter used C’s int type to store sizes or counts; for example, the number of items in a list or tuple were stored in an int. The C compilers for most 64-bit platforms still define int as a 32-bit type, so that meant that lists could only hold up to 2**31 - 1 = 2147483647 items. (There are actually a few different programming models that 64-bit C compilers can use – see http://www.unix.org/version2/whatsnew/lp64_wp.html for a discussion – but the most commonly available model leaves int as 32 bits.)

A limit of 2147483647 items doesn’t really matter on a 32-bit platform because you’ll run out of memory before hitting the length limit. Each list item requires space for a pointer, which is 4 bytes, plus space for a PyObject representing the item. 2147483647*4 is already more bytes than a 32-bit address space can contain.

It’s possible to address that much memory on a 64-bit platform, however. The pointers for a list that size would only require 16 GiB of space, so it’s not unreasonable that Python programmers might construct lists that large. Therefore, the Python interpreter had to be changed to use some type other than int, and this will be a 64-bit type on 64-bit platforms. The change will cause incompatibilities on 64-bit machines, so it was deemed worth making the transition now, while the number of 64-bit users is still relatively small. (In 5 or 10 years, we may all be on 64-bit machines, and the transition would be more painful then.)

This change most strongly affects authors of C extension modules. Python strings and container types such as lists and tuples now use Py_ssize_t to store their size. Functions such as PyList_Size() now return Py_ssize_t. Code in extension modules may therefore need to have some variables changed to Py_ssize_t.

The PyArg_ParseTuple() and Py_BuildValue() functions have a new conversion code, n, for Py_ssize_t. PyArg_ParseTuple()’s s# and t# still output int by default, but you can define the macro PY_SSIZE_T_CLEAN before including Python.h to make them return Py_ssize_t.

PEP 353 [https://www.python.org/dev/peps/pep-0353] has a section on conversion guidelines that extension authors should read to learn about supporting 64-bit platforms.

더 보기

PEP 353 [https://www.python.org/dev/peps/pep-0353] - Using ssize_t as the index type

PEP written and implemented by Martin von Löwis.

PEP 357: The ‘__index__’ method

The NumPy developers had a problem that could only be solved by adding a new special method, __index__(). When using slice notation, as in [start:stop:step], the values of the start, stop, and step indexes must all be either integers or long integers. NumPy defines a variety of specialized integer types corresponding to unsigned and signed integers of 8, 16, 32, and 64 bits, but there was no way to signal that these types could be used as slice indexes.

Slicing can’t just use the existing __int__() method because that method is also used to implement coercion to integers. If slicing used __int__(), floating-point numbers would also become legal slice indexes and that’s clearly an undesirable behaviour.

Instead, a new special method called __index__() was added. It takes no arguments and returns an integer giving the slice index to use. For example:

class C:
    def __index__ (self):
        return self.value

The return value must be either a Python integer or long integer. The interpreter will check that the type returned is correct, and raises a TypeError if this requirement isn’t met.

A corresponding nb_index slot was added to the C-level PyNumberMethods structure to let C extensions implement this protocol. PyNumber_Index(obj) can be used in extension code to call the __index__() function and retrieve its result.

더 보기

PEP 357 [https://www.python.org/dev/peps/pep-0357] - Allowing Any Object to be Used for Slicing

PEP written and implemented by Travis Oliphant.

Other Language Changes

Here are all of the changes that Python 2.5 makes to the core Python language.

The dict type has a new hook for letting subclasses provide a default value when a key isn’t contained in the dictionary. When a key isn’t found, the dictionary’s __missing__(key) method will be called. This hook is used to implement the new defaultdict class in the collections module. The following example defines a dictionary that returns zero for any missing key:

class zerodict (dict):
    def __missing__ (self, key):
        return 0

d = zerodict({1:1, 2:2})
print d[1], d[2]   # Prints 1, 2
print d[3], d[4]   # Prints 0, 0

Both 8-bit and Unicode strings have new partition(sep) and rpartition(sep) methods that simplify a common use case.

The find(S) method is often used to get an index which is then used to slice the string and obtain the pieces that are before and after the separator. partition(sep) condenses this pattern into a single method call that returns a 3-tuple containing the substring before the separator, the separator itself, and the substring after the separator. If the separator isn’t found, the first element of the tuple is the entire string and the other two elements are empty. rpartition(sep) also returns a 3-tuple but starts searching from the end of the string; the r stands for ‘reverse’.

Some examples:

>>> ('http://www.python.org').partition('://')
('http', '://', 'www.python.org')
>>> ('file:/usr/share/doc/index.html').partition('://')
('file:/usr/share/doc/index.html', '', '')
>>> (u'Subject: a quick question').partition(':')
(u'Subject', u':', u' a quick question')
>>> 'www.python.org'.rpartition('.')
('www.python', '.', 'org')
>>> 'www.python.org'.rpartition(':')
('', '', 'www.python.org')

(Implemented by Fredrik Lundh following a suggestion by Raymond Hettinger.)

The startswith() and endswith() methods of string types now accept tuples of strings to check for.

def is_image_file (filename):
    return filename.endswith(('.gif', '.jpg', '.tiff'))

(Implemented by Georg Brandl following a suggestion by Tom Lynn.)

The min() and max() built-in functions gained a key keyword parameter analogous to the key argument for sort(). This parameter supplies a function that takes a single argument and is called for every value in the list; min()/max() will return the element with the smallest/largest return value from this function. For example, to find the longest string in a list, you can do:

L = ['medium', 'longest', 'short']
# Prints 'longest'
print max(L, key=len)
# Prints 'short', because lexicographically 'short' has the largest value
print max(L)

(Contributed by Steven Bethard and Raymond Hettinger.)

Two new built-in functions, any() and all(), evaluate whether an iterator contains any true or false values. any() returns True if any value returned by the iterator is true; otherwise it will return False. all() returns True only if all of the values returned by the iterator evaluate as true. (Suggested by Guido van Rossum, and implemented by Raymond Hettinger.)

The result of a class’s __hash__() method can now be either a long integer or a regular integer. If a long integer is returned, the hash of that value is taken. In earlier versions the hash value was required to be a regular integer, but in 2.5 the id() built-in was changed to always return non-negative numbers, and users often seem to use id(self) in __hash__() methods (though this is discouraged).

ASCII is now the default encoding for modules. It’s now a syntax error if a module contains string literals with 8-bit characters but doesn’t have an encoding declaration. In Python 2.4 this triggered a warning, not a syntax error. See PEP 263 [https://www.python.org/dev/peps/pep-0263] for how to declare a module’s encoding; for example, you might add a line like this near the top of the source file:

# -*- coding: latin1 -*-

A new warning, UnicodeWarning, is triggered when you attempt to compare a Unicode string and an 8-bit string that can’t be converted to Unicode using the default ASCII encoding. The result of the comparison is false:

>>> chr(128) == unichr(128)   # Can't convert chr(128) to Unicode
__main__:1: UnicodeWarning: Unicode equal comparison failed
  to convert both arguments to Unicode - interpreting them
  as being unequal
False
>>> chr(127) == unichr(127)   # chr(127) can be converted
True

Previously this would raise a UnicodeDecodeError exception, but in 2.5 this could result in puzzling problems when accessing a dictionary. If you looked up unichr(128) and chr(128) was being used as a key, you’d get a UnicodeDecodeError exception. Other changes in 2.5 resulted in this exception being raised instead of suppressed by the code in dictobject.c that implements dictionaries.

Raising an exception for such a comparison is strictly correct, but the change might have broken code, so instead UnicodeWarning was introduced.

(Implemented by Marc-André Lemburg.)

One error that Python programmers sometimes make is forgetting to include an __init__.py module in a package directory. Debugging this mistake can be confusing, and usually requires running Python with the -v switch to log all the paths searched. In Python 2.5, a new ImportWarning warning is triggered when an import would have picked up a directory as a package but no __init__.py was found. This warning is silently ignored by default; provide the -Wd option when running the Python executable to display the warning message. (Implemented by Thomas Wouters.)

The list of base classes in a class definition can now be empty. As an example, this is now legal:

class C():
    pass

(Implemented by Brett Cannon.)

Interactive Interpreter Changes

In the interactive interpreter, quit and exit have long been strings so that new users get a somewhat helpful message when they try to quit:

>>> quit
'Use Ctrl-D (i.e. EOF) to exit.'

In Python 2.5, quit and exit are now objects that still produce string representations of themselves, but are also callable. Newbies who try quit() or exit() will now exit the interpreter as they expect. (Implemented by Georg Brandl.)

The Python executable now accepts the standard long options --help and --version; on Windows, it also accepts the /? option for displaying a help message. (Implemented by Georg Brandl.)

Optimizations

Several of the optimizations were developed at the NeedForSpeed sprint, an event held in Reykjavik, Iceland, from May 21–28 2006. The sprint focused on speed enhancements to the CPython implementation and was funded by EWT LLC with local support from CCP Games. Those optimizations added at this sprint are specially marked in the following list.

When they were introduced in Python 2.4, the built-in set and frozenset types were built on top of Python’s dictionary type. In 2.5 the internal data structure has been customized for implementing sets, and as a result sets will use a third less memory and are somewhat faster. (Implemented by Raymond Hettinger.)

The speed of some Unicode operations, such as finding substrings, string splitting, and character map encoding and decoding, has been improved. (Substring search and splitting improvements were added by Fredrik Lundh and Andrew Dalke at the NeedForSpeed sprint. Character maps were improved by Walter Dörwald and Martin von Löwis.)

The long(str, base) function is now faster on long digit strings because fewer intermediate results are calculated. The peak is for strings of around 800–1000 digits where the function is 6 times faster. (Contributed by Alan McIntyre and committed at the NeedForSpeed sprint.)

It’s now illegal to mix iterating over a file with for line in file and calling the file object’s read()/readline()/readlines() methods. Iteration uses an internal buffer and the read*() methods don’t use that buffer. Instead they would return the data following the buffer, causing the data to appear out of order. Mixing iteration and these methods will now trigger a ValueError from the read*() method. (Implemented by Thomas Wouters.)

The struct module now compiles structure format strings into an internal representation and caches this representation, yielding a 20% speedup. (Contributed by Bob Ippolito at the NeedForSpeed sprint.)

The re module got a 1 or 2% speedup by switching to Python’s allocator functions instead of the system’s malloc() and free(). (Contributed by Jack Diederich at the NeedForSpeed sprint.)

The code generator’s peephole optimizer now performs simple constant folding in expressions. If you write something like a = 2+3, the code generator will do the arithmetic and produce code corresponding to a = 5. (Proposed and implemented by Raymond Hettinger.)

Function calls are now faster because code objects now keep the most recently finished frame (a “zombie frame”) in an internal field of the code object, reusing it the next time the code object is invoked. (Original patch by Michael Hudson, modified by Armin Rigo and Richard Jones; committed at the NeedForSpeed sprint.) Frame objects are also slightly smaller, which may improve cache locality and reduce memory usage a bit. (Contributed by Neal Norwitz.)

Python’s built-in exceptions are now new-style classes, a change that speeds up instantiation considerably. Exception handling in Python 2.5 is therefore about 30% faster than in 2.4. (Contributed by Richard Jones, Georg Brandl and Sean Reifschneider at the NeedForSpeed sprint.)

Importing now caches the paths tried, recording whether they exist or not so that the interpreter makes fewer open() and stat() calls on startup. (Contributed by Martin von Löwis and Georg Brandl.)

New, Improved, and Removed Modules

The standard library received many enhancements and bug fixes in Python 2.5. Here’s a partial list of the most notable changes, sorted alphabetically by module name. Consult the Misc/NEWS file in the source tree for a more complete list of changes, or look through the SVN logs for all the details.

The audioop module now supports the a-LAW encoding, and the code for u-LAW encoding has been improved. (Contributed by Lars Immisch.)

The codecs module gained support for incremental codecs. The codec.lookup() function now returns a CodecInfo instance instead of a tuple. CodecInfo instances behave like a 4-tuple to preserve backward compatibility but also have the attributes encode, decode, incrementalencoder, incrementaldecoder, streamwriter, and streamreader. Incremental codecs can receive input and produce output in multiple chunks; the output is the same as if the entire input was fed to the non-incremental codec. See the codecs module documentation for details. (Designed and implemented by Walter Dörwald.)

The collections module gained a new type, defaultdict, that subclasses the standard dict type. The new type mostly behaves like a dictionary but constructs a default value when a key isn’t present, automatically adding it to the dictionary for the requested key value.

The first argument to defaultdict’s constructor is a factory function that gets called whenever a key is requested but not found. This factory function receives no arguments, so you can use built-in type constructors such as list() or int(). For example, you can make an index of words based on their initial letter like this:

words = """Nel mezzo del cammin di nostra vita
mi ritrovai per una selva oscura
che la diritta via era smarrita""".lower().split()

index = defaultdict(list)

for w in words:
    init_letter = w[0]
    index[init_letter].append(w)

Printing index results in the following output:

defaultdict(<type 'list'>, {'c': ['cammin', 'che'], 'e': ['era'],
        'd': ['del', 'di', 'diritta'], 'm': ['mezzo', 'mi'],
        'l': ['la'], 'o': ['oscura'], 'n': ['nel', 'nostra'],
        'p': ['per'], 's': ['selva', 'smarrita'],
        'r': ['ritrovai'], 'u': ['una'], 'v': ['vita', 'via']}

(Contributed by Guido van Rossum.)

The deque double-ended queue type supplied by the collections module now has a remove(value) method that removes the first occurrence of value in the queue, raising ValueError if the value isn’t found. (Contributed by Raymond Hettinger.)

New module: The contextlib module contains helper functions for use with the new ‘with’ statement. See section The contextlib module for more about this module.

New module: The cProfile module is a C implementation of the existing profile module that has much lower overhead. The module’s interface is the same as profile: you run cProfile.run('main()') to profile a function, can save profile data to a file, etc. It’s not yet known if the Hotshot profiler, which is also written in C but doesn’t match the profile module’s interface, will continue to be maintained in future versions of Python. (Contributed by Armin Rigo.)

Also, the pstats module for analyzing the data measured by the profiler now supports directing the output to any file object by supplying a stream argument to the Stats constructor. (Contributed by Skip Montanaro.)

The csv module, which parses files in comma-separated value format, received several enhancements and a number of bugfixes. You can now set the maximum size in bytes of a field by calling the csv.field_size_limit(new_limit) function; omitting the new_limit argument will return the currently-set limit. The reader class now has a line_num attribute that counts the number of physical lines read from the source; records can span multiple physical lines, so line_num is not the same as the number of records read.

The CSV parser is now stricter about multi-line quoted fields. Previously, if a line ended within a quoted field without a terminating newline character, a newline would be inserted into the returned field. This behavior caused problems when reading files that contained carriage return characters within fields, so the code was changed to return the field without inserting newlines. As a consequence, if newlines embedded within fields are important, the input should be split into lines in a manner that preserves the newline characters.

(Contributed by Skip Montanaro and Andrew McNamara.)

The datetime class in the datetime module now has a strptime(string, format) method for parsing date strings, contributed by Josh Spoerri. It uses the same format characters as time.strptime() and time.strftime():

from datetime import datetime

ts = datetime.strptime('10:13:15 2006-03-07',
                       '%H:%M:%S %Y-%m-%d')

The SequenceMatcher.get_matching_blocks() method in the difflib module now guarantees to return a minimal list of blocks describing matching subsequences. Previously, the algorithm would occasionally break a block of matching elements into two list entries. (Enhancement by Tim Peters.)

The doctest module gained a SKIP option that keeps an example from being executed at all. This is intended for code snippets that are usage examples intended for the reader and aren’t actually test cases.

An encoding parameter was added to the testfile() function and the DocFileSuite class to specify the file’s encoding. This makes it easier to use non-ASCII characters in tests contained within a docstring. (Contributed by Bjorn Tillenius.)

The email package has been updated to version 4.0. (Contributed by Barry Warsaw.)

The fileinput module was made more flexible. Unicode filenames are now supported, and a mode parameter that defaults to "r" was added to the input() function to allow opening files in binary or universal newlines mode. Another new parameter, openhook, lets you use a function other than open() to open the input files. Once you’re iterating over the set of files, the FileInput object’s new fileno() returns the file descriptor for the currently opened file. (Contributed by Georg Brandl.)

In the gc module, the new get_count() function returns a 3-tuple containing the current collection counts for the three GC generations. This is accounting information for the garbage collector; when these counts reach a specified threshold, a garbage collection sweep will be made. The existing gc.collect() function now takes an optional generation argument of 0, 1, or 2 to specify which generation to collect. (Contributed by Barry Warsaw.)

The nsmallest() and nlargest() functions in the heapq module now support a key keyword parameter similar to the one provided by the min()/max() functions and the sort() methods. For example:

>>> import heapq
>>> L = ["short", 'medium', 'longest', 'longer still']
>>> heapq.nsmallest(2, L)  # Return two lowest elements, lexicographically
['longer still', 'longest']
>>> heapq.nsmallest(2, L, key=len)   # Return two shortest elements
['short', 'medium']

(Contributed by Raymond Hettinger.)

The itertools.islice() function now accepts None for the start and step arguments. This makes it more compatible with the attributes of slice objects, so that you can now write the following:

s = slice(5)     # Create slice object
itertools.islice(iterable, s.start, s.stop, s.step)

(Contributed by Raymond Hettinger.)

The format() function in the locale module has been modified and two new functions were added, format_string() and currency().

The format() function’s val parameter could previously be a string as long as no more than one %char specifier appeared; now the parameter must be exactly one %char specifier with no surrounding text. An optional monetary parameter was also added which, if True, will use the locale’s rules for formatting currency in placing a separator between groups of three digits.

To format strings with multiple %char specifiers, use the new format_string() function that works like format() but also supports mixing %char specifiers with arbitrary text.

A new currency() function was also added that formats a number according to the current locale’s settings.

(Contributed by Georg Brandl.)

The mailbox module underwent a massive rewrite to add the capability to modify mailboxes in addition to reading them. A new set of classes that include mbox, MH, and Maildir are used to read mailboxes, and have an add(message) method to add messages, remove(key) to remove messages, and lock()/unlock() to lock/unlock the mailbox. The following example converts a maildir-format mailbox into an mbox-format one:

import mailbox

# 'factory=None' uses email.Message.Message as the class representing
# individual messages.
src = mailbox.Maildir('maildir', factory=None)
dest = mailbox.mbox('/tmp/mbox')

for msg in src:
    dest.add(msg)

(Contributed by Gregory K. Johnson. Funding was provided by Google’s 2005 Summer of Code.)

New module: the msilib module allows creating Microsoft Installer .msi files and CAB files. Some support for reading the .msi database is also included. (Contributed by Martin von Löwis.)

The nis module now supports accessing domains other than the system default domain by supplying a domain argument to the nis.match() and nis.maps() functions. (Contributed by Ben Bell.)

The operator module’s itemgetter() and attrgetter() functions now support multiple fields. A call such as operator.attrgetter('a', 'b') will return a function that retrieves the a and b attributes. Combining this new feature with the sort() method’s key parameter lets you easily sort lists using multiple fields. (Contributed by Raymond Hettinger.)

The optparse module was updated to version 1.5.1 of the Optik library. The OptionParser class gained an epilog attribute, a string that will be printed after the help message, and a destroy() method to break reference cycles created by the object. (Contributed by Greg Ward.)

The os module underwent several changes. The stat_float_times variable now defaults to true, meaning that os.stat() will now return time values as floats. (This doesn’t necessarily mean that os.stat() will return times that are precise to fractions of a second; not all systems support such precision.)

Constants named os.SEEK_SET, os.SEEK_CUR, and os.SEEK_END have been added; these are the parameters to the os.lseek() function. Two new constants for locking are os.O_SHLOCK and os.O_EXLOCK.

Two new functions, wait3() and wait4(), were added. They’re similar the waitpid() function which waits for a child process to exit and returns a tuple of the process ID and its exit status, but wait3() and wait4() return additional information. wait3() doesn’t take a process ID as input, so it waits for any child process to exit and returns a 3-tuple of process-id, exit-status, resource-usage as returned from the resource.getrusage() function. wait4(pid) does take a process ID. (Contributed by Chad J. Schroeder.)

On FreeBSD, the os.stat() function now returns times with nanosecond resolution, and the returned object now has st_gen and st_birthtime. The st_flags attribute is also available, if the platform supports it. (Contributed by Antti Louko and Diego Pettenò.)

The Python debugger provided by the pdb module can now store lists of commands to execute when a breakpoint is reached and execution stops. Once breakpoint #1 has been created, enter commands 1 and enter a series of commands to be executed, finishing the list with end. The command list can include commands that resume execution, such as continue or next. (Contributed by Grégoire Dooms.)

The pickle and cPickle modules no longer accept a return value of None from the __reduce__() method; the method must return a tuple of arguments instead. The ability to return None was deprecated in Python 2.4, so this completes the removal of the feature.

The pkgutil module, containing various utility functions for finding packages, was enhanced to support PEP 302’s import hooks and now also works for packages stored in ZIP-format archives. (Contributed by Phillip J. Eby.)

The pybench benchmark suite by Marc-André Lemburg is now included in the Tools/pybench directory. The pybench suite is an improvement on the commonly used pystone.py program because pybench provides a more detailed measurement of the interpreter’s speed. It times particular operations such as function calls, tuple slicing, method lookups, and numeric operations, instead of performing many different operations and reducing the result to a single number as pystone.py does.

The pyexpat module now uses version 2.0 of the Expat parser. (Contributed by Trent Mick.)

The Queue class provided by the Queue module gained two new methods. join() blocks until all items in the queue have been retrieved and all processing work on the items have been completed. Worker threads call the other new method, task_done(), to signal that processing for an item has been completed. (Contributed by Raymond Hettinger.)

The old regex and regsub modules, which have been deprecated ever since Python 2.0, have finally been deleted. Other deleted modules: statcache, tzparse, whrandom.

Also deleted: the lib-old directory, which includes ancient modules such as dircmp and ni, was removed. lib-old wasn’t on the default sys.path, so unless your programs explicitly added the directory to sys.path, this removal shouldn’t affect your code.

The rlcompleter module is no longer dependent on importing the readline module and therefore now works on non-Unix platforms. (Patch from Robert Kiendl.)

The SimpleXMLRPCServer and DocXMLRPCServer classes now have a rpc_paths attribute that constrains XML-RPC operations to a limited set of URL paths; the default is to allow only '/' and '/RPC2'. Setting rpc_paths to None or an empty tuple disables this path checking.

The socket module now supports AF_NETLINK sockets on Linux, thanks to a patch from Philippe Biondi. Netlink sockets are a Linux-specific mechanism for communications between a user-space process and kernel code; an introductory article about them is at https://www.linuxjournal.com/article/7356. In Python code, netlink addresses are represented as a tuple of 2 integers, (pid, group_mask).

Two new methods on socket objects, recv_into(buffer) and recvfrom_into(buffer), store the received data in an object that supports the buffer protocol instead of returning the data as a string. This means you can put the data directly into an array or a memory-mapped file.

Socket objects also gained getfamily(), gettype(), and getproto() accessor methods to retrieve the family, type, and protocol values for the socket.

New module: the spwd module provides functions for accessing the shadow password database on systems that support shadow passwords.

The struct is now faster because it compiles format strings into Struct objects with pack() and unpack() methods. This is similar to how the re module lets you create compiled regular expression objects. You can still use the module-level pack() and unpack() functions; they’ll create Struct objects and cache them. Or you can use Struct instances directly:

s = struct.Struct('ih3s')

data = s.pack(1972, 187, 'abc')
year, number, name = s.unpack(data)

You can also pack and unpack data to and from buffer objects directly using the pack_into(buffer, offset, v1, v2, ...) and unpack_from(buffer, offset) methods. This lets you store data directly into an array or a memory-mapped file.

(Struct objects were implemented by Bob Ippolito at the NeedForSpeed sprint. Support for buffer objects was added by Martin Blais, also at the NeedForSpeed sprint.)

The Python developers switched from CVS to Subversion during the 2.5 development process. Information about the exact build version is available as the sys.subversion variable, a 3-tuple of (interpreter-name, branch-name, revision-range). For example, at the time of writing my copy of 2.5 was reporting ('CPython', 'trunk', '45313:45315').

This information is also available to C extensions via the Py_GetBuildInfo() function that returns a string of build information like this: "trunk:45355:45356M, Apr 13 2006, 07:42:19". (Contributed by Barry Warsaw.)

Another new function, sys._current_frames(), returns the current stack frames for all running threads as a dictionary mapping thread identifiers to the topmost stack frame currently active in that thread at the time the function is called. (Contributed by Tim Peters.)

The TarFile class in the tarfile module now has an extractall() method that extracts all members from the archive into the current working directory. It’s also possible to set a different directory as the extraction target, and to unpack only a subset of the archive’s members.

The compression used for a tarfile opened in stream mode can now be autodetected using the mode 'r|*'. (Contributed by Lars Gustäbel.)

The threading module now lets you set the stack size used when new threads are created. The stack_size([*size*]) function returns the currently configured stack size, and supplying the optional size parameter sets a new value. Not all platforms support changing the stack size, but Windows, POSIX threading, and OS/2 all do. (Contributed by Andrew MacIntyre.)

The unicodedata module has been updated to use version 4.1.0 of the Unicode character database. Version 3.2.0 is required by some specifications, so it’s still available as unicodedata.ucd_3_2_0.

New module: the uuid module generates universally unique identifiers (UUIDs) according to RFC 4122 [https://tools.ietf.org/html/rfc4122.html]. The RFC defines several different UUID versions that are generated from a starting string, from system properties, or purely randomly. This module contains a UUID class and functions named uuid1(), uuid3(), uuid4(), and uuid5() to generate different versions of UUID. (Version 2 UUIDs are not specified in RFC 4122 [https://tools.ietf.org/html/rfc4122.html] and are not supported by this module.)

>>> import uuid
>>> # make a UUID based on the host ID and current time
>>> uuid.uuid1()
UUID('a8098c1a-f86e-11da-bd1a-00112444be1e')

>>> # make a UUID using an MD5 hash of a namespace UUID and a name
>>> uuid.uuid3(uuid.NAMESPACE_DNS, 'python.org')
UUID('6fa459ea-ee8a-3ca4-894e-db77e160355e')

>>> # make a random UUID
>>> uuid.uuid4()
UUID('16fd2706-8baf-433b-82eb-8c7fada847da')

>>> # make a UUID using a SHA-1 hash of a namespace UUID and a name
>>> uuid.uuid5(uuid.NAMESPACE_DNS, 'python.org')
UUID('886313e1-3b8a-5372-9b90-0c9aee199e5d')

(Contributed by Ka-Ping Yee.)

The weakref module’s WeakKeyDictionary and WeakValueDictionary types gained new methods for iterating over the weak references contained in the dictionary. iterkeyrefs() and keyrefs() methods were added to WeakKeyDictionary, and itervaluerefs() and valuerefs() were added to WeakValueDictionary. (Contributed by Fred L. Drake, Jr.)

The webbrowser module received a number of enhancements. It’s now usable as a script with python -m webbrowser, taking a URL as the argument; there are a number of switches to control the behaviour (-n for a new browser window, -t for a new tab). New module-level functions, open_new() and open_new_tab(), were added to support this. The module’s open() function supports an additional feature, an autoraise parameter that signals whether to raise the open window when possible. A number of additional browsers were added to the supported list such as Firefox, Opera, Konqueror, and elinks. (Contributed by Oleg Broytmann and Georg Brandl.)

The xmlrpclib module now supports returning datetime objects for the XML-RPC date type. Supply use_datetime=True to the loads() function or the Unmarshaller class to enable this feature. (Contributed by Skip Montanaro.)

The zipfile module now supports the ZIP64 version of the format, meaning that a .zip archive can now be larger than 4 GiB and can contain individual files larger than 4 GiB. (Contributed by Ronald Oussoren.)

The zlib module’s Compress and Decompress objects now support a copy() method that makes a copy of the object’s internal state and returns a new Compress or Decompress object. (Contributed by Chris AtLee.)

The ctypes package

The ctypes package, written by Thomas Heller, has been added to the standard library. ctypes lets you call arbitrary functions in shared libraries or DLLs. Long-time users may remember the dl module, which provides functions for loading shared libraries and calling functions in them. The ctypes package is much fancier.

To load a shared library or DLL, you must create an instance of the CDLL class and provide the name or path of the shared library or DLL. Once that’s done, you can call arbitrary functions by accessing them as attributes of the CDLL object.

import ctypes

libc = ctypes.CDLL('libc.so.6')
result = libc.printf("Line of output\n")

Type constructors for the various C types are provided: c_int(), c_float(), c_double(), c_char_p() (equivalent to char *), and so forth. Unlike Python’s types, the C versions are all mutable; you can assign to their value attribute to change the wrapped value. Python integers and strings will be automatically converted to the corresponding C types, but for other types you must call the correct type constructor. (And I mean must; getting it wrong will often result in the interpreter crashing with a segmentation fault.)

You shouldn’t use c_char_p() with a Python string when the C function will be modifying the memory area, because Python strings are supposed to be immutable; breaking this rule will cause puzzling bugs. When you need a modifiable memory area, use create_string_buffer():

s = "this is a string"
buf = ctypes.create_string_buffer(s)
libc.strfry(buf)

C functions are assumed to return integers, but you can set the restype attribute of the function object to change this:

>>> libc.atof('2.71828')
-1783957616
>>> libc.atof.restype = ctypes.c_double
>>> libc.atof('2.71828')
2.71828

ctypes also provides a wrapper for Python’s C API as the ctypes.pythonapi object. This object does not release the global interpreter lock before calling a function, because the lock must be held when calling into the interpreter’s code. There’s a py_object() type constructor that will create a PyObject * pointer. A simple usage:

import ctypes

d = {}
ctypes.pythonapi.PyObject_SetItem(ctypes.py_object(d),
          ctypes.py_object("abc"),  ctypes.py_object(1))
# d is now {'abc', 1}.

Don’t forget to use py_object(); if it’s omitted you end up with a segmentation fault.

ctypes has been around for a while, but people still write and distribution hand-coded extension modules because you can’t rely on ctypes being present. Perhaps developers will begin to write Python wrappers atop a library accessed through ctypes instead of extension modules, now that ctypes is included with core Python.

더 보기

http://starship.python.net/crew/theller/ctypes/

The ctypes web page, with a tutorial, reference, and FAQ.

The documentation for the ctypes module.

The ElementTree package

A subset of Fredrik Lundh’s ElementTree library for processing XML has been added to the standard library as xml.etree. The available modules are ElementTree, ElementPath, and ElementInclude from ElementTree 1.2.6. The cElementTree accelerator module is also included.

The rest of this section will provide a brief overview of using ElementTree. Full documentation for ElementTree is available at http://effbot.org/zone/element-index.htm.

ElementTree represents an XML document as a tree of element nodes. The text content of the document is stored as the text and tail attributes of (This is one of the major differences between ElementTree and the Document Object Model; in the DOM there are many different types of node, including TextNode.)

The most commonly used parsing function is parse(), that takes either a string (assumed to contain a filename) or a file-like object and returns an ElementTree instance:

from xml.etree import ElementTree as ET

tree = ET.parse('ex-1.xml')

feed = urllib.urlopen(
          'http://planet.python.org/rss10.xml')
tree = ET.parse(feed)

Once you have an ElementTree instance, you can call its getroot() method to get the root Element node.

There’s also an XML() function that takes a string literal and returns an Element node (not an ElementTree). This function provides a tidy way to incorporate XML fragments, approaching the convenience of an XML literal:

svg = ET.XML("""<svg width="10px" version="1.0">
             </svg>""")
svg.set('height', '320px')
svg.append(elem1)

Each XML element supports some dictionary-like and some list-like access methods. Dictionary-like operations are used to access attribute values, and list-like operations are used to access child nodes.

Operation

Result

elem[n]

Returns n’th child element.

elem[m:n]

Returns list of m’th through n’th child elements.

len(elem)

Returns number of child elements.

list(elem)

Returns list of child elements.

elem.append(elem2)

Adds elem2 as a child.

elem.insert(index, elem2)

Inserts elem2 at the specified location.

del elem[n]

Deletes n’th child element.

elem.keys()

Returns list of attribute names.

elem.get(name)

Returns value of attribute name.

elem.set(name, value)

Sets new value for attribute name.

elem.attrib

Retrieves the dictionary containing attributes.

del elem.attrib[name]

Deletes attribute name.

Comments and processing instructions are also represented as Element nodes. To check if a node is a comment or processing instructions:

if elem.tag is ET.Comment:
    ...
elif elem.tag is ET.ProcessingInstruction:
    ...

To generate XML output, you should call the ElementTree.write() method. Like parse(), it can take either a string or a file-like object:

# Encoding is US-ASCII
tree.write('output.xml')

# Encoding is UTF-8
f = open('output.xml', 'w')
tree.write(f, encoding='utf-8')

(Caution: the default encoding used for output is ASCII. For general XML work, where an element’s name may contain arbitrary Unicode characters, ASCII isn’t a very useful encoding because it will raise an exception if an element’s name contains any characters with values greater than 127. Therefore, it’s best to specify a different encoding such as UTF-8 that can handle any Unicode character.)

This section is only a partial description of the ElementTree interfaces. Please read the package’s official documentation for more details.

더 보기

http://effbot.org/zone/element-index.htm

Official documentation for ElementTree.

The hashlib package

A new hashlib module, written by Gregory P. Smith, has been added to replace the md5 and sha modules. hashlib adds support for additional secure hashes (SHA-224, SHA-256, SHA-384, and SHA-512). When available, the module uses OpenSSL for fast platform optimized implementations of algorithms.

The old md5 and sha modules still exist as wrappers around hashlib to preserve backwards compatibility. The new module’s interface is very close to that of the old modules, but not identical. The most significant difference is that the constructor functions for creating new hashing objects are named differently.

# Old versions
h = md5.md5()
h = md5.new()

# New version
h = hashlib.md5()

# Old versions
h = sha.sha()
h = sha.new()

# New version
h = hashlib.sha1()

# Hash that weren't previously available
h = hashlib.sha224()
h = hashlib.sha256()
h = hashlib.sha384()
h = hashlib.sha512()

# Alternative form
h = hashlib.new('md5')          # Provide algorithm as a string

Once a hash object has been created, its methods are the same as before: update(string) hashes the specified string into the current digest state, digest() and hexdigest() return the digest value as a binary string or a string of hex digits, and copy() returns a new hashing object with the same digest state.

더 보기

The documentation for the hashlib module.

The sqlite3 package

The pysqlite module (http://www.pysqlite.org), a wrapper for the SQLite embedded database, has been added to the standard library under the package name sqlite3.

SQLite is a C library that provides a lightweight disk-based database that doesn’t require a separate server process and allows accessing the database using a nonstandard variant of the SQL query language. Some applications can use SQLite for internal data storage. It’s also possible to prototype an application using SQLite and then port the code to a larger database such as PostgreSQL or Oracle.

pysqlite was written by Gerhard Häring and provides a SQL interface compliant with the DB-API 2.0 specification described by PEP 249 [https://www.python.org/dev/peps/pep-0249].

If you’re compiling the Python source yourself, note that the source tree doesn’t include the SQLite code, only the wrapper module. You’ll need to have the SQLite libraries and headers installed before compiling Python, and the build process will compile the module when the necessary headers are available.

To use the module, you must first create a Connection object that represents the database. Here the data will be stored in the /tmp/example file:

conn = sqlite3.connect('/tmp/example')

You can also supply the special name :memory: to create a database in RAM.

Once you have a Connection, you can create a Cursor object and call its execute() method to perform SQL commands:

c = conn.cursor()

# Create table
c.execute('''create table stocks
(date text, trans text, symbol text,
 qty real, price real)''')

# Insert a row of data
c.execute("""insert into stocks
          values ('2006-01-05','BUY','RHAT',100,35.14)""")

Usually your SQL operations will need to use values from Python variables. You shouldn’t assemble your query using Python’s string operations because doing so is insecure; it makes your program vulnerable to an SQL injection attack.

Instead, use the DB-API’s parameter substitution. Put ? as a placeholder wherever you want to use a value, and then provide a tuple of values as the second argument to the cursor’s execute() method. (Other database modules may use a different placeholder, such as %s or :1.) For example:

# Never do this -- insecure!
symbol = 'IBM'
c.execute("... where symbol = '%s'" % symbol)

# Do this instead
t = (symbol,)
c.execute('select * from stocks where symbol=?', t)

# Larger example
for t in (('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
          ('2006-04-05', 'BUY', 'MSOFT', 1000, 72.00),
          ('2006-04-06', 'SELL', 'IBM', 500, 53.00),
         ):
    c.execute('insert into stocks values (?,?,?,?,?)', t)

To retrieve data after executing a SELECT statement, you can either treat the cursor as an iterator, call the cursor’s fetchone() method to retrieve a single matching row, or call fetchall() to get a list of the matching rows.

This example uses the iterator form:

>>> c = conn.cursor()
>>> c.execute('select * from stocks order by price')
>>> for row in c:
...    print row
...
(u'2006-01-05', u'BUY', u'RHAT', 100, 35.140000000000001)
(u'2006-03-28', u'BUY', u'IBM', 1000, 45.0)
(u'2006-04-06', u'SELL', u'IBM', 500, 53.0)
(u'2006-04-05', u'BUY', u'MSOFT', 1000, 72.0)
>>>

For more information about the SQL dialect supported by SQLite, see https://www.sqlite.org.

더 보기

http://www.pysqlite.org

The pysqlite web page.

https://www.sqlite.org

The SQLite web page; the documentation describes the syntax and the available data types for the supported SQL dialect.

The documentation for the sqlite3 module.

PEP 249 [https://www.python.org/dev/peps/pep-0249] - Database API Specification 2.0

PEP written by Marc-André Lemburg.

The wsgiref package

The Web Server Gateway Interface (WSGI) v1.0 defines a standard interface between web servers and Python web applications and is described in PEP 333 [https://www.python.org/dev/peps/pep-0333]. The wsgiref package is a reference implementation of the WSGI specification.

The package includes a basic HTTP server that will run a WSGI application; this server is useful for debugging but isn’t intended for production use. Setting up a server takes only a few lines of code:

from wsgiref import simple_server

wsgi_app = ...

host = ''
port = 8000
httpd = simple_server.make_server(host, port, wsgi_app)
httpd.serve_forever()

더 보기

http://www.wsgi.org

A central web site for WSGI-related resources.

PEP 333 [https://www.python.org/dev/peps/pep-0333] - Python Web Server Gateway Interface v1.0

PEP written by Phillip J. Eby.

Build and C API Changes

Changes to Python’s build process and to the C API include:

The Python source tree was converted from CVS to Subversion, in a complex migration procedure that was supervised and flawlessly carried out by Martin von Löwis. The procedure was developed as PEP 347 [https://www.python.org/dev/peps/pep-0347].

Coverity, a company that markets a source code analysis tool called Prevent, provided the results of their examination of the Python source code. The analysis found about 60 bugs that were quickly fixed. Many of the bugs were refcounting problems, often occurring in error-handling code. See https://scan.coverity.com for the statistics.

The largest change to the C API came from PEP 353 [https://www.python.org/dev/peps/pep-0353], which modifies the interpreter to use a Py_ssize_t type definition instead of int. See the earlier section PEP 353: Using ssize_t as the index type for a discussion of this change.

The design of the bytecode compiler has changed a great deal, no longer generating bytecode by traversing the parse tree. Instead the parse tree is converted to an abstract syntax tree (or AST), and it is the abstract syntax tree that’s traversed to produce the bytecode.

It’s possible for Python code to obtain AST objects by using the compile() built-in and specifying _ast.PyCF_ONLY_AST as the value of the flags parameter:

from _ast import PyCF_ONLY_AST
ast = compile("""a=0
for i in range(10):
    a += i
""", "<string>", 'exec', PyCF_ONLY_AST)

assignment = ast.body[0]
for_loop = ast.body[1]

No official documentation has been written for the AST code yet, but PEP 339 [https://www.python.org/dev/peps/pep-0339] discusses the design. To start learning about the code, read the definition of the various AST nodes in Parser/Python.asdl. A Python script reads this file and generates a set of C structure definitions in Include/Python-ast.h. The PyParser_ASTFromString() and PyParser_ASTFromFile(), defined in Include/pythonrun.h, take Python source as input and return the root of an AST representing the contents. This AST can then be turned into a code object by PyAST_Compile(). For more information, read the source code, and then ask questions on python-dev.

The AST code was developed under Jeremy Hylton’s management, and implemented by (in alphabetical order) Brett Cannon, Nick Coghlan, Grant Edwards, John Ehresman, Kurt Kaiser, Neal Norwitz, Tim Peters, Armin Rigo, and Neil Schemenauer, plus the participants in a number of AST sprints at conferences such as PyCon.

Evan Jones’s patch to obmalloc, first described in a talk at PyCon DC 2005, was applied. Python 2.4 allocated small objects in 256K-sized arenas, but never freed arenas. With this patch, Python will free arenas when they’re empty. The net effect is that on some platforms, when you allocate many objects, Python’s memory usage may actually drop when you delete them and the memory may be returned to the operating system. (Implemented by Evan Jones, and reworked by Tim Peters.)

Note that this change means extension modules must be more careful when allocating memory. Python’s API has many different functions for allocating memory that are grouped into families. For example, PyMem_Malloc(), PyMem_Realloc(), and PyMem_Free() are one family that allocates raw memory, while PyObject_Malloc(), PyObject_Realloc(), and PyObject_Free() are another family that’s supposed to be used for creating Python objects.

Previously these different families all reduced to the platform’s malloc() and free() functions. This meant it didn’t matter if you got things wrong and allocated memory with the PyMem() function but freed it with the PyObject() function. With 2.5’s changes to obmalloc, these families now do different things and mismatches will probably result in a segfault. You should carefully test your C extension modules with Python 2.5.

The built-in set types now have an official C API. Call PySet_New() and PyFrozenSet_New() to create a new set, PySet_Add() and PySet_Discard() to add and remove elements, and PySet_Contains() and PySet_Size() to examine the set’s state. (Contributed by Raymond Hettinger.)

C code can now obtain information about the exact revision of the Python interpreter by calling the Py_GetBuildInfo() function that returns a string of build information like this: "trunk:45355:45356M, Apr 13 2006, 07:42:19". (Contributed by Barry Warsaw.)

Two new macros can be used to indicate C functions that are local to the current file so that a faster calling convention can be used. Py_LOCAL(type) declares the function as returning a value of the specified type and uses a fast-calling qualifier. Py_LOCAL_INLINE(type) does the same thing and also requests the function be inlined. If PY_LOCAL_AGGRESSIVE() is defined before python.h is included, a set of more aggressive optimizations are enabled for the module; you should benchmark the results to find out if these optimizations actually make the code faster. (Contributed by Fredrik Lundh at the NeedForSpeed sprint.)

PyErr_NewException(name, base, dict) can now accept a tuple of base classes as its base argument. (Contributed by Georg Brandl.)

The PyErr_Warn() function for issuing warnings is now deprecated in favour of PyErr_WarnEx(category, message, stacklevel) which lets you specify the number of stack frames separating this function and the caller. A stacklevel of 1 is the function calling PyErr_WarnEx(), 2 is the function above that, and so forth. (Added by Neal Norwitz.)

The CPython interpreter is still written in C, but the code can now be compiled with a C++ compiler without errors. (Implemented by Anthony Baxter, Martin von Löwis, Skip Montanaro.)

The PyRange_New() function was removed. It was never documented, never used in the core code, and had dangerously lax error checking. In the unlikely case that your extensions were using it, you can replace it by something like the following:

range = PyObject_CallFunction((PyObject*) &PyRange_Type, "lll",
                              start, stop, step);

Port-Specific Changes

MacOS X (10.3 and higher): dynamic loading of modules now uses the dlopen() function instead of MacOS-specific functions.

MacOS X: an --enable-universalsdk switch was added to the configure script that compiles the interpreter as a universal binary able to run on both PowerPC and Intel processors. (Contributed by Ronald Oussoren; bpo-2573 [https://bugs.python.org/issue?@action=redirect&bpo=2573].)

Windows: .dll is no longer supported as a filename extension for extension modules. .pyd is now the only filename extension that will be searched for.

Porting to Python 2.5

This section lists previously described changes that may require changes to your code:

ASCII is now the default encoding for modules. It’s now a syntax error if a module contains string literals with 8-bit characters but doesn’t have an encoding declaration. In Python 2.4 this triggered a warning, not a syntax error.

Previously, the gi_frame attribute of a generator was always a frame object. Because of the PEP 342 [https://www.python.org/dev/peps/pep-0342] changes described in section PEP 342: New Generator Features, it’s now possible for gi_frame to be None.

A new warning, UnicodeWarning, is triggered when you attempt to compare a Unicode string and an 8-bit string that can’t be converted to Unicode using the default ASCII encoding. Previously such comparisons would raise a UnicodeDecodeError exception.

Library: the csv module is now stricter about multi-line quoted fields. If your files contain newlines embedded within fields, the input should be split into lines in a manner which preserves the newline characters.

Library: the locale module’s format() function’s would previously accept any string as long as no more than one %char specifier appeared. In Python 2.5, the argument must be exactly one %char specifier with no surrounding text.

Library: The pickle and cPickle modules no longer accept a return value of None from the __reduce__() method; the method must return a tuple of arguments instead. The modules also no longer accept the deprecated bin keyword parameter.

Library: The SimpleXMLRPCServer and DocXMLRPCServer classes now have a rpc_paths attribute that constrains XML-RPC operations to a limited set of URL paths; the default is to allow only '/' and '/RPC2'. Setting rpc_paths to None or an empty tuple disables this path checking.

C API: Many functions now use Py_ssize_t instead of int to allow processing more data on 64-bit machines. Extension code may need to make the same change to avoid warnings and to support 64-bit machines. See the earlier section PEP 353: Using ssize_t as the index type for a discussion of this change.

C API: The obmalloc changes mean that you must be careful to not mix usage of the PyMem_*() and PyObject_*() families of functions. Memory allocated with one family’s *_Malloc() must be freed with the corresponding family’s *_Free() function.

Acknowledgements

The author would like to thank the following people for offering suggestions, corrections and assistance with various drafts of this article: Georg Brandl, Nick Coghlan, Phillip J. Eby, Lars Gustäbel, Raymond Hettinger, Ralf W. Grosse-Kunstleve, Kent Johnson, Iain Lowe, Martin von Löwis, Fredrik Lundh, Andrew McNamara, Skip Montanaro, Gustavo Niemeyer, Paul Prescod, James Pryor, Mike Rovner, Scott Weikart, Barry Warsaw, Thomas Wouters.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬의 새로운 기능 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬의 새로운 기능 »

|

What’s New in Python 2.4

Author

A.M. Kuchling

This article explains the new features in Python 2.4.1, released on March 30, 2005.

Python 2.4 is a medium-sized release. It doesn’t introduce as many changes as the radical Python 2.2, but introduces more features than the conservative 2.3 release. The most significant new language features are function decorators and generator expressions; most other changes are to the standard library.

According to the CVS change logs, there were 481 patches applied and 502 bugs fixed between Python 2.3 and 2.4. Both figures are likely to be underestimates.

This article doesn’t attempt to provide a complete specification of every single new feature, but instead provides a brief introduction to each feature. For full details, you should refer to the documentation for Python 2.4, such as the Python Library Reference and the Python Reference Manual. Often you will be referred to the PEP for a particular new feature for explanations of the implementation and design rationale.

PEP 218: Built-In Set Objects

Python 2.3 introduced the sets module. C implementations of set data types have now been added to the Python core as two new built-in types, set(iterable) and frozenset(iterable). They provide high speed operations for membership testing, for eliminating duplicates from sequences, and for mathematical operations like unions, intersections, differences, and symmetric differences.

>>> a = set('abracadabra')              # form a set from a string
>>> 'z' in a                            # fast membership testing
False
>>> a                                   # unique letters in a
set(['a', 'r', 'b', 'c', 'd'])
>>> ''.join(a)                          # convert back into a string
'arbcd'

>>> b = set('alacazam')                 # form a second set
>>> a - b                               # letters in a but not in b
set(['r', 'd', 'b'])
>>> a | b                               # letters in either a or b
set(['a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'])
>>> a & b                               # letters in both a and b
set(['a', 'c'])
>>> a ^ b                               # letters in a or b but not both
set(['r', 'd', 'b', 'm', 'z', 'l'])

>>> a.add('z')                          # add a new element
>>> a.update('wxy')                     # add multiple new elements
>>> a
set(['a', 'c', 'b', 'd', 'r', 'w', 'y', 'x', 'z'])
>>> a.remove('x')                       # take one element out
>>> a
set(['a', 'c', 'b', 'd', 'r', 'w', 'y', 'z'])

The frozenset() type is an immutable version of set(). Since it is immutable and hashable, it may be used as a dictionary key or as a member of another set.

The sets module remains in the standard library, and may be useful if you wish to subclass the Set or ImmutableSet classes. There are currently no plans to deprecate the module.

더 보기

PEP 218 [https://www.python.org/dev/peps/pep-0218] - Adding a Built-In Set Object Type

Originally proposed by Greg Wilson and ultimately implemented by Raymond Hettinger.

PEP 237: Unifying Long Integers and Integers

The lengthy transition process for this PEP, begun in Python 2.2, takes another step forward in Python 2.4. In 2.3, certain integer operations that would behave differently after int/long unification triggered FutureWarning warnings and returned values limited to 32 or 64 bits (depending on your platform). In 2.4, these expressions no longer produce a warning and instead produce a different result that’s usually a long integer.

The problematic expressions are primarily left shifts and lengthy hexadecimal and octal constants. For example, 2 << 32 results in a warning in 2.3, evaluating to 0 on 32-bit platforms. In Python 2.4, this expression now returns the correct answer, 8589934592.

더 보기

PEP 237 [https://www.python.org/dev/peps/pep-0237] - Unifying Long Integers and Integers

Original PEP written by Moshe Zadka and GvR. The changes for 2.4 were implemented by Kalle Svensson.

PEP 289: Generator Expressions

The iterator feature introduced in Python 2.2 and the itertools module make it easier to write programs that loop through large data sets without having the entire data set in memory at one time. List comprehensions don’t fit into this picture very well because they produce a Python list object containing all of the items. This unavoidably pulls all of the objects into memory, which can be a problem if your data set is very large. When trying to write a functionally-styled program, it would be natural to write something like:

links = [link for link in get_all_links() if not link.followed]
for link in links:
    ...

instead of

for link in get_all_links():
    if link.followed:
        continue
    ...

The first form is more concise and perhaps more readable, but if you’re dealing with a large number of link objects you’d have to write the second form to avoid having all link objects in memory at the same time.

Generator expressions work similarly to list comprehensions but don’t materialize the entire list; instead they create a generator that will return elements one by one. The above example could be written as:

links = (link for link in get_all_links() if not link.followed)
for link in links:
    ...

Generator expressions always have to be written inside parentheses, as in the above example. The parentheses signalling a function call also count, so if you want to create an iterator that will be immediately passed to a function you could write:

print sum(obj.count for obj in list_all_objects())

Generator expressions differ from list comprehensions in various small ways. Most notably, the loop variable (obj in the above example) is not accessible outside of the generator expression. List comprehensions leave the variable assigned to its last value; future versions of Python will change this, making list comprehensions match generator expressions in this respect.

더 보기

PEP 289 [https://www.python.org/dev/peps/pep-0289] - Generator Expressions

Proposed by Raymond Hettinger and implemented by Jiwon Seo with early efforts steered by Hye-Shik Chang.

PEP 292: Simpler String Substitutions

Some new classes in the standard library provide an alternative mechanism for substituting variables into strings; this style of substitution may be better for applications where untrained users need to edit templates.

The usual way of substituting variables by name is the % operator:

>>> '%(page)i: %(title)s' % {'page':2, 'title': 'The Best of Times'}
'2: The Best of Times'

When writing the template string, it can be easy to forget the i or s after the closing parenthesis. This isn’t a big problem if the template is in a Python module, because you run the code, get an “Unsupported format character” ValueError, and fix the problem. However, consider an application such as Mailman where template strings or translations are being edited by users who aren’t aware of the Python language. The format string’s syntax is complicated to explain to such users, and if they make a mistake, it’s difficult to provide helpful feedback to them.

PEP 292 adds a Template class to the string module that uses $ to indicate a substitution:

>>> import string
>>> t = string.Template('$page: $title')
>>> t.substitute({'page':2, 'title': 'The Best of Times'})
'2: The Best of Times'

If a key is missing from the dictionary, the substitute() method will raise a KeyError. There’s also a safe_substitute() method that ignores missing keys:

>>> t = string.Template('$page: $title')
>>> t.safe_substitute({'page':3})
'3: $title'

더 보기

PEP 292 [https://www.python.org/dev/peps/pep-0292] - Simpler String Substitutions

Written and implemented by Barry Warsaw.

PEP 318: Decorators for Functions and Methods

Python 2.2 extended Python’s object model by adding static methods and class methods, but it didn’t extend Python’s syntax to provide any new way of defining static or class methods. Instead, you had to write a def statement in the usual way, and pass the resulting method to a staticmethod() or classmethod() function that would wrap up the function as a method of the new type. Your code would look like this:

class C:
   def meth (cls):
       ...

   meth = classmethod(meth)   # Rebind name to wrapped-up class method

If the method was very long, it would be easy to miss or forget the classmethod() invocation after the function body.

The intention was always to add some syntax to make such definitions more readable, but at the time of 2.2’s release a good syntax was not obvious. Today a good syntax still isn’t obvious but users are asking for easier access to the feature; a new syntactic feature has been added to meet this need.

The new feature is called “function decorators”. The name comes from the idea that classmethod(), staticmethod(), and friends are storing additional information on a function object; they’re decorating functions with more details.

The notation borrows from Java and uses the '@' character as an indicator. Using the new syntax, the example above would be written:

class C:

   @classmethod
   def meth (cls):
       ...

The @classmethod is shorthand for the meth=classmethod(meth) assignment. More generally, if you have the following:

@A
@B
@C
def f ():
    ...

It’s equivalent to the following pre-decorator code:

def f(): ...
f = A(B(C(f)))

Decorators must come on the line before a function definition, one decorator per line, and can’t be on the same line as the def statement, meaning that @A def f(): ... is illegal. You can only decorate function definitions, either at the module level or inside a class; you can’t decorate class definitions.

A decorator is just a function that takes the function to be decorated as an argument and returns either the same function or some new object. The return value of the decorator need not be callable (though it typically is), unless further decorators will be applied to the result. It’s easy to write your own decorators. The following simple example just sets an attribute on the function object:

>>> def deco(func):
...    func.attr = 'decorated'
...    return func
...
>>> @deco
... def f(): pass
...
>>> f
<function f at 0x402ef0d4>
>>> f.attr
'decorated'
>>>

As a slightly more realistic example, the following decorator checks that the supplied argument is an integer:

def require_int (func):
    def wrapper (arg):
        assert isinstance(arg, int)
        return func(arg)

    return wrapper

@require_int
def p1 (arg):
    print arg

@require_int
def p2(arg):
    print arg*2

An example in PEP 318 [https://www.python.org/dev/peps/pep-0318] contains a fancier version of this idea that lets you both specify the required type and check the returned type.

Decorator functions can take arguments. If arguments are supplied, your decorator function is called with only those arguments and must return a new decorator function; this function must take a single function and return a function, as previously described. In other words, @A @B @C(args) becomes:

def f(): ...
_deco = C(args)
f = A(B(_deco(f)))

Getting this right can be slightly brain-bending, but it’s not too difficult.

A small related change makes the func_name attribute of functions writable. This attribute is used to display function names in tracebacks, so decorators should change the name of any new function that’s constructed and returned.

더 보기

PEP 318 [https://www.python.org/dev/peps/pep-0318] - Decorators for Functions, Methods and Classes

Written by Kevin D. Smith, Jim Jewett, and Skip Montanaro. Several people wrote patches implementing function decorators, but the one that was actually checked in was patch #979728, written by Mark Russell.

https://wiki.python.org/moin/PythonDecoratorLibrary

This Wiki page contains several examples of decorators.

PEP 322: Reverse Iteration

A new built-in function, reversed(seq), takes a sequence and returns an iterator that loops over the elements of the sequence in reverse order.

>>> for i in reversed(xrange(1,4)):
...    print i
...
3
2
1

Compared to extended slicing, such as range(1,4)[::-1], reversed() is easier to read, runs faster, and uses substantially less memory.

Note that reversed() only accepts sequences, not arbitrary iterators. If you want to reverse an iterator, first convert it to a list with list().

>>> input = open('/etc/passwd', 'r')
>>> for line in reversed(list(input)):
...   print line
...
root:*:0:0:System Administrator:/var/root:/bin/tcsh
  ...

더 보기

PEP 322 [https://www.python.org/dev/peps/pep-0322] - Reverse Iteration

Written and implemented by Raymond Hettinger.

PEP 324: New subprocess Module

The standard library provides a number of ways to execute a subprocess, offering different features and different levels of complexity. os.system(command) is easy to use, but slow (it runs a shell process which executes the command) and dangerous (you have to be careful about escaping the shell’s metacharacters). The popen2 module offers classes that can capture standard output and standard error from the subprocess, but the naming is confusing. The subprocess module cleans this up, providing a unified interface that offers all the features you might need.

Instead of popen2’s collection of classes, subprocess contains a single class called Popen whose constructor supports a number of different keyword arguments.

class Popen(args, bufsize=0, executable=None,
            stdin=None, stdout=None, stderr=None,
            preexec_fn=None, close_fds=False, shell=False,
            cwd=None, env=None, universal_newlines=False,
            startupinfo=None, creationflags=0):

args is commonly a sequence of strings that will be the arguments to the program executed as the subprocess. (If the shell argument is true, args can be a string which will then be passed on to the shell for interpretation, just as os.system() does.)

stdin, stdout, and stderr specify what the subprocess’s input, output, and error streams will be. You can provide a file object or a file descriptor, or you can use the constant subprocess.PIPE to create a pipe between the subprocess and the parent.

The constructor has a number of handy options:

close_fds requests that all file descriptors be closed before running the subprocess.

cwd specifies the working directory in which the subprocess will be executed (defaulting to whatever the parent’s working directory is).

env is a dictionary specifying environment variables.

preexec_fn is a function that gets called before the child is started.

universal_newlines opens the child’s input and output using Python’s universal newlines feature.

Once you’ve created the Popen instance, you can call its wait() method to pause until the subprocess has exited, poll() to check if it’s exited without pausing, or communicate(data) to send the string data to the subprocess’s standard input. communicate(data) then reads any data that the subprocess has sent to its standard output or standard error, returning a tuple (stdout_data, stderr_data).

call() is a shortcut that passes its arguments along to the Popen constructor, waits for the command to complete, and returns the status code of the subprocess. It can serve as a safer analog to os.system():

sts = subprocess.call(['dpkg', '-i', '/tmp/new-package.deb'])
if sts == 0:
    # Success
    ...
else:
    # dpkg returned an error
    ...

The command is invoked without use of the shell. If you really do want to use the shell, you can add shell=True as a keyword argument and provide a string instead of a sequence:

sts = subprocess.call('dpkg -i /tmp/new-package.deb', shell=True)

The PEP takes various examples of shell and Python code and shows how they’d be translated into Python code that uses subprocess. Reading this section of the PEP is highly recommended.

더 보기

PEP 324 [https://www.python.org/dev/peps/pep-0324] - subprocess - New process module

Written and implemented by Peter Åstrand, with assistance from Fredrik Lundh and others.

PEP 327: Decimal Data Type

Python has always supported floating-point (FP) numbers, based on the underlying C double type, as a data type. However, while most programming languages provide a floating-point type, many people (even programmers) are unaware that floating-point numbers don’t represent certain decimal fractions accurately. The new Decimal type can represent these fractions accurately, up to a user-specified precision limit.

Why is Decimal needed?

The limitations arise from the representation used for floating-point numbers. FP numbers are made up of three components:

The sign, which is positive or negative.

The mantissa, which is a single-digit binary number followed by a fractional part. For example, 1.01 in base-2 notation is 1 + 0/2 + 1/4, or 1.25 in decimal notation.

The exponent, which tells where the decimal point is located in the number represented.

For example, the number 1.25 has positive sign, a mantissa value of 1.01 (in binary), and an exponent of 0 (the decimal point doesn’t need to be shifted). The number 5 has the same sign and mantissa, but the exponent is 2 because the mantissa is multiplied by 4 (2 to the power of the exponent 2); 1.25 * 4 equals 5.

Modern systems usually provide floating-point support that conforms to a standard called IEEE 754. C’s double type is usually implemented as a 64-bit IEEE 754 number, which uses 52 bits of space for the mantissa. This means that numbers can only be specified to 52 bits of precision. If you’re trying to represent numbers whose expansion repeats endlessly, the expansion is cut off after 52 bits. Unfortunately, most software needs to produce output in base 10, and common fractions in base 10 are often repeating decimals in binary. For example, 1.1 decimal is binary 1.0001100110011 ...; .1 = 1/16 + 1/32 + 1/256 plus an infinite number of additional terms. IEEE 754 has to chop off that infinitely repeated decimal after 52 digits, so the representation is slightly inaccurate.

Sometimes you can see this inaccuracy when the number is printed:

>>> 1.1
1.1000000000000001

The inaccuracy isn’t always visible when you print the number because the FP-to-decimal-string conversion is provided by the C library, and most C libraries try to produce sensible output. Even if it’s not displayed, however, the inaccuracy is still there and subsequent operations can magnify the error.

For many applications this doesn’t matter. If I’m plotting points and displaying them on my monitor, the difference between 1.1 and 1.1000000000000001 is too small to be visible. Reports often limit output to a certain number of decimal places, and if you round the number to two or three or even eight decimal places, the error is never apparent. However, for applications where it does matter, it’s a lot of work to implement your own custom arithmetic routines.

Hence, the Decimal type was created.

The Decimal type

A new module, decimal, was added to Python’s standard library. It contains two classes, Decimal and Context. Decimal instances represent numbers, and Context instances are used to wrap up various settings such as the precision and default rounding mode.

Decimal instances are immutable, like regular Python integers and FP numbers; once it’s been created, you can’t change the value an instance represents. Decimal instances can be created from integers or strings:

>>> import decimal
>>> decimal.Decimal(1972)
Decimal("1972")
>>> decimal.Decimal("1.1")
Decimal("1.1")

You can also provide tuples containing the sign, the mantissa represented as a tuple of decimal digits, and the exponent:

>>> decimal.Decimal((1, (1, 4, 7, 5), -2))
Decimal("-14.75")

Cautionary note: the sign bit is a Boolean value, so 0 is positive and 1 is negative.

Converting from floating-point numbers poses a bit of a problem: should the FP number representing 1.1 turn into the decimal number for exactly 1.1, or for 1.1 plus whatever inaccuracies are introduced? The decision was to dodge the issue and leave such a conversion out of the API. Instead, you should convert the floating-point number into a string using the desired precision and pass the string to the Decimal constructor:

>>> f = 1.1
>>> decimal.Decimal(str(f))
Decimal("1.1")
>>> decimal.Decimal('%.12f' % f)
Decimal("1.100000000000")

Once you have Decimal instances, you can perform the usual mathematical operations on them. One limitation: exponentiation requires an integer exponent:

>>> a = decimal.Decimal('35.72')
>>> b = decimal.Decimal('1.73')
>>> a+b
Decimal("37.45")
>>> a-b
Decimal("33.99")
>>> a*b
Decimal("61.7956")
>>> a/b
Decimal("20.64739884393063583815028902")
>>> a ** 2
Decimal("1275.9184")
>>> a**b
Traceback (most recent call last):
  ...
decimal.InvalidOperation: x ** (non-integer)

You can combine Decimal instances with integers, but not with floating-point numbers:

>>> a + 4
Decimal("39.72")
>>> a + 4.5
Traceback (most recent call last):
  ...
TypeError: You can interact Decimal only with int, long or Decimal data types.
>>>

Decimal numbers can be used with the math and cmath modules, but note that they’ll be immediately converted to floating-point numbers before the operation is performed, resulting in a possible loss of precision and accuracy. You’ll also get back a regular floating-point number and not a Decimal.

>>> import math, cmath
>>> d = decimal.Decimal('123456789012.345')
>>> math.sqrt(d)
351364.18288201344
>>> cmath.sqrt(-d)
351364.18288201344j

Decimal instances have a sqrt() method that returns a Decimal, but if you need other things such as trigonometric functions you’ll have to implement them.

>>> d.sqrt()
Decimal("351364.1828820134592177245001")

The Context type

Instances of the Context class encapsulate several settings for decimal operations:

prec is the precision, the number of decimal places.

rounding specifies the rounding mode. The decimal module has constants for the various possibilities: ROUND_DOWN, ROUND_CEILING, ROUND_HALF_EVEN, and various others.

traps is a dictionary specifying what happens on encountering certain error conditions: either an exception is raised or a value is returned. Some examples of error conditions are division by zero, loss of precision, and overflow.

There’s a thread-local default context available by calling getcontext(); you can change the properties of this context to alter the default precision, rounding, or trap handling. The following example shows the effect of changing the precision of the default context:

>>> decimal.getcontext().prec
28
>>> decimal.Decimal(1) / decimal.Decimal(7)
Decimal("0.1428571428571428571428571429")
>>> decimal.getcontext().prec = 9
>>> decimal.Decimal(1) / decimal.Decimal(7)
Decimal("0.142857143")

The default action for error conditions is selectable; the module can either return a special value such as infinity or not-a-number, or exceptions can be raised:

>>> decimal.Decimal(1) / decimal.Decimal(0)
Traceback (most recent call last):
  ...
decimal.DivisionByZero: x / 0
>>> decimal.getcontext().traps[decimal.DivisionByZero] = False
>>> decimal.Decimal(1) / decimal.Decimal(0)
Decimal("Infinity")
>>>

The Context instance also has various methods for formatting numbers such as to_eng_string() and to_sci_string().

For more information, see the documentation for the decimal module, which includes a quick-start tutorial and a reference.

더 보기

PEP 327 [https://www.python.org/dev/peps/pep-0327] - Decimal Data Type

Written by Facundo Batista and implemented by Facundo Batista, Eric Price, Raymond Hettinger, Aahz, and Tim Peters.

http://www.lahey.com/float.htm

The article uses Fortran code to illustrate many of the problems that floating-point inaccuracy can cause.

http://speleotrove.com/decimal/

A description of a decimal-based representation. This representation is being proposed as a standard, and underlies the new Python decimal type. Much of this material was written by Mike Cowlishaw, designer of the Rexx language.

PEP 328: Multi-line Imports

One language change is a small syntactic tweak aimed at making it easier to import many names from a module. In a from module import names statement, names is a sequence of names separated by commas. If the sequence is very long, you can either write multiple imports from the same module, or you can use backslashes to escape the line endings like this:

from SimpleXMLRPCServer import SimpleXMLRPCServer,\
            SimpleXMLRPCRequestHandler,\
            CGIXMLRPCRequestHandler,\
            resolve_dotted_attribute

The syntactic change in Python 2.4 simply allows putting the names within parentheses. Python ignores newlines within a parenthesized expression, so the backslashes are no longer needed:

from SimpleXMLRPCServer import (SimpleXMLRPCServer,
                                SimpleXMLRPCRequestHandler,
                                CGIXMLRPCRequestHandler,
                                resolve_dotted_attribute)

The PEP also proposes that all import statements be absolute imports, with a leading . character to indicate a relative import. This part of the PEP was not implemented for Python 2.4, but was completed for Python 2.5.

더 보기

PEP 328 [https://www.python.org/dev/peps/pep-0328] - Imports: Multi-Line and Absolute/Relative

Written by Aahz. Multi-line imports were implemented by Dima Dorfman.

PEP 331: Locale-Independent Float/String Conversions

The locale modules lets Python software select various conversions and display conventions that are localized to a particular country or language. However, the module was careful to not change the numeric locale because various functions in Python’s implementation required that the numeric locale remain set to the 'C' locale. Often this was because the code was using the C library’s atof() function.

Not setting the numeric locale caused trouble for extensions that used third-party C libraries, however, because they wouldn’t have the correct locale set. The motivating example was GTK+, whose user interface widgets weren’t displaying numbers in the current locale.

The solution described in the PEP is to add three new functions to the Python API that perform ASCII-only conversions, ignoring the locale setting:

PyOS_ascii_strtod(str, ptr) and PyOS_ascii_atof(str, ptr) both convert a string to a C double.

PyOS_ascii_formatd(buffer, buf_len, format, d) converts a double to an ASCII string.

The code for these functions came from the GLib library (https://developer.gnome.org/glib/stable/), whose developers kindly relicensed the relevant functions and donated them to the Python Software Foundation. The locale module can now change the numeric locale, letting extensions such as GTK+ produce the correct results.

더 보기

PEP 331 [https://www.python.org/dev/peps/pep-0331] - Locale-Independent Float/String Conversions

Written by Christian R. Reis, and implemented by Gustavo Carneiro.

Other Language Changes

Here are all of the changes that Python 2.4 makes to the core Python language.

Decorators for functions and methods were added (PEP 318 [https://www.python.org/dev/peps/pep-0318]).

Built-in set() and frozenset() types were added (PEP 218 [https://www.python.org/dev/peps/pep-0218]). Other new built-ins include the reversed(seq) function (PEP 322 [https://www.python.org/dev/peps/pep-0322]).

Generator expressions were added (PEP 289 [https://www.python.org/dev/peps/pep-0289]).

Certain numeric expressions no longer return values restricted to 32 or 64 bits (PEP 237 [https://www.python.org/dev/peps/pep-0237]).

You can now put parentheses around the list of names in a from module import names statement (PEP 328 [https://www.python.org/dev/peps/pep-0328]).

The dict.update() method now accepts the same argument forms as the dict constructor. This includes any mapping, any iterable of key/value pairs, and keyword arguments. (Contributed by Raymond Hettinger.)

The string methods ljust(), rjust(), and center() now take an optional argument for specifying a fill character other than a space. (Contributed by Raymond Hettinger.)

Strings also gained an rsplit() method that works like the split() method but splits from the end of the string. (Contributed by Sean Reifschneider.)

>>> 'www.python.org'.split('.', 1)
['www', 'python.org']
'www.python.org'.rsplit('.', 1)
['www.python', 'org']

Three keyword parameters, cmp, key, and reverse, were added to the sort() method of lists. These parameters make some common usages of sort() simpler. All of these parameters are optional.

For the cmp parameter, the value should be a comparison function that takes two parameters and returns -1, 0, or +1 depending on how the parameters compare. This function will then be used to sort the list. Previously this was the only parameter that could be provided to sort().

key should be a single-parameter function that takes a list element and returns a comparison key for the element. The list is then sorted using the comparison keys. The following example sorts a list case-insensitively:

>>> L = ['A', 'b', 'c', 'D']
>>> L.sort()                 # Case-sensitive sort
>>> L
['A', 'D', 'b', 'c']
>>> # Using 'key' parameter to sort list
>>> L.sort(key=lambda x: x.lower())
>>> L
['A', 'b', 'c', 'D']
>>> # Old-fashioned way
>>> L.sort(cmp=lambda x,y: cmp(x.lower(), y.lower()))
>>> L
['A', 'b', 'c', 'D']

The last example, which uses the cmp parameter, is the old way to perform a case-insensitive sort. It works but is slower than using a key parameter. Using key calls lower() method once for each element in the list while using cmp will call it twice for each comparison, so using key saves on invocations of the lower() method.

For simple key functions and comparison functions, it is often possible to avoid a lambda expression by using an unbound method instead. For example, the above case-insensitive sort is best written as:

>>> L.sort(key=str.lower)
>>> L
['A', 'b', 'c', 'D']

Finally, the reverse parameter takes a Boolean value. If the value is true, the list will be sorted into reverse order. Instead of L.sort(); L.reverse(), you can now write L.sort(reverse=True).

The results of sorting are now guaranteed to be stable. This means that two entries with equal keys will be returned in the same order as they were input. For example, you can sort a list of people by name, and then sort the list by age, resulting in a list sorted by age where people with the same age are in name-sorted order.

(All changes to sort() contributed by Raymond Hettinger.)

There is a new built-in function sorted(iterable) that works like the in-place list.sort() method but can be used in expressions. The differences are:

the input may be any iterable;

a newly formed copy is sorted, leaving the original intact; and

the expression returns the new sorted copy

>>> L = [9,7,8,3,2,4,1,6,5]
>>> [10+i for i in sorted(L)]       # usable in a list comprehension
[11, 12, 13, 14, 15, 16, 17, 18, 19]
>>> L                               # original is left unchanged
[9,7,8,3,2,4,1,6,5]
>>> sorted('Monty Python')          # any iterable may be an input
[' ', 'M', 'P', 'h', 'n', 'n', 'o', 'o', 't', 't', 'y', 'y']

>>> # List the contents of a dict sorted by key values
>>> colormap = dict(red=1, blue=2, green=3, black=4, yellow=5)
>>> for k, v in sorted(colormap.iteritems()):
...     print k, v
...
black 4
blue 2
green 3
red 1
yellow 5

(Contributed by Raymond Hettinger.)

Integer operations will no longer trigger an OverflowWarning. The OverflowWarning warning will disappear in Python 2.5.

The interpreter gained a new switch, -m, that takes a name, searches for the corresponding module on sys.path, and runs the module as a script. For example, you can now run the Python profiler with python -m profile. (Contributed by Nick Coghlan.)

The eval(expr, globals, locals) and execfile(filename, globals, locals) functions and the exec statement now accept any mapping type for the locals parameter. Previously this had to be a regular Python dictionary. (Contributed by Raymond Hettinger.)

The zip() built-in function and itertools.izip() now return an empty list if called with no arguments. Previously they raised a TypeError exception. This makes them more suitable for use with variable length argument lists:

>>> def transpose(array):
...    return zip(*array)
...
>>> transpose([(1,2,3), (4,5,6)])
[(1, 4), (2, 5), (3, 6)]
>>> transpose([])
[]

(Contributed by Raymond Hettinger.)

Encountering a failure while importing a module no longer leaves a partially-initialized module object in sys.modules. The incomplete module object left behind would fool further imports of the same module into succeeding, leading to confusing errors. (Fixed by Tim Peters.)

None is now a constant; code that binds a new value to the name None is now a syntax error. (Contributed by Raymond Hettinger.)

Optimizations

The inner loops for list and tuple slicing were optimized and now run about one-third faster. The inner loops for dictionaries were also optimized, resulting in performance boosts for keys(), values(), items(), iterkeys(), itervalues(), and iteritems(). (Contributed by Raymond Hettinger.)

The machinery for growing and shrinking lists was optimized for speed and for space efficiency. Appending and popping from lists now runs faster due to more efficient code paths and less frequent use of the underlying system realloc(). List comprehensions also benefit. list.extend() was also optimized and no longer converts its argument into a temporary list before extending the base list. (Contributed by Raymond Hettinger.)

list(), tuple(), map(), filter(), and zip() now run several times faster with non-sequence arguments that supply a __len__() method. (Contributed by Raymond Hettinger.)

The methods list.__getitem__(), dict.__getitem__(), and dict.__contains__() are now implemented as method_descriptor objects rather than wrapper_descriptor objects. This form of access doubles their performance and makes them more suitable for use as arguments to functionals: map(mydict.__getitem__, keylist). (Contributed by Raymond Hettinger.)

Added a new opcode, LIST_APPEND, that simplifies the generated bytecode for list comprehensions and speeds them up by about a third. (Contributed by Raymond Hettinger.)

The peephole bytecode optimizer has been improved to produce shorter, faster bytecode; remarkably, the resulting bytecode is more readable. (Enhanced by Raymond Hettinger.)

String concatenations in statements of the form s = s + "abc" and s += "abc" are now performed more efficiently in certain circumstances. This optimization won’t be present in other Python implementations such as Jython, so you shouldn’t rely on it; using the join() method of strings is still recommended when you want to efficiently glue a large number of strings together. (Contributed by Armin Rigo.)

The net result of the 2.4 optimizations is that Python 2.4 runs the pystone benchmark around 5% faster than Python 2.3 and 35% faster than Python 2.2. (pystone is not a particularly good benchmark, but it’s the most commonly used measurement of Python’s performance. Your own applications may show greater or smaller benefits from Python 2.4.)

New, Improved, and Deprecated Modules

As usual, Python’s standard library received a number of enhancements and bug fixes. Here’s a partial list of the most notable changes, sorted alphabetically by module name. Consult the Misc/NEWS file in the source tree for a more complete list of changes, or look through the CVS logs for all the details.

The asyncore module’s loop() function now has a count parameter that lets you perform a limited number of passes through the polling loop. The default is still to loop forever.

The base64 module now has more complete RFC 3548 [https://tools.ietf.org/html/rfc3548.html] support for Base64, Base32, and Base16 encoding and decoding, including optional case folding and optional alternative alphabets. (Contributed by Barry Warsaw.)

The bisect module now has an underlying C implementation for improved performance. (Contributed by Dmitry Vasiliev.)

The CJKCodecs collections of East Asian codecs, maintained by Hye-Shik Chang, was integrated into 2.4. The new encodings are:

Chinese (PRC): gb2312, gbk, gb18030, big5hkscs, hz

Chinese (ROC): big5, cp950

Japanese: cp932, euc-jis-2004, euc-jp, euc-jisx0213, iso-2022-jp,

iso-2022-jp-1, iso-2022-jp-2, iso-2022-jp-3, iso-2022-jp-ext, iso-2022-jp-2004, shift-jis, shift-jisx0213, shift-jis-2004

Korean: cp949, euc-kr, johab, iso-2022-kr

Some other new encodings were added: HP Roman8, ISO_8859-11, ISO_8859-16, PCTP-154, and TIS-620.

The UTF-8 and UTF-16 codecs now cope better with receiving partial input. Previously the StreamReader class would try to read more data, making it impossible to resume decoding from the stream. The read() method will now return as much data as it can and future calls will resume decoding where previous ones left off. (Implemented by Walter Dörwald.)

There is a new collections module for various specialized collection datatypes. Currently it contains just one type, deque, a double-ended queue that supports efficiently adding and removing elements from either end:

>>> from collections import deque
>>> d = deque('ghi')        # make a new deque with three items
>>> d.append('j')           # add a new entry to the right side
>>> d.appendleft('f')       # add a new entry to the left side
>>> d                       # show the representation of the deque
deque(['f', 'g', 'h', 'i', 'j'])
>>> d.pop()                 # return and remove the rightmost item
'j'
>>> d.popleft()             # return and remove the leftmost item
'f'
>>> list(d)                 # list the contents of the deque
['g', 'h', 'i']
>>> 'h' in d                # search the deque
True

Several modules, such as the Queue and threading modules, now take advantage of collections.deque for improved performance. (Contributed by Raymond Hettinger.)

The ConfigParser classes have been enhanced slightly. The read() method now returns a list of the files that were successfully parsed, and the set() method raises TypeError if passed a value argument that isn’t a string. (Contributed by John Belmonte and David Goodger.)

The curses module now supports the ncurses extension use_default_colors(). On platforms where the terminal supports transparency, this makes it possible to use a transparent background. (Contributed by Jörg Lehmann.)

The difflib module now includes an HtmlDiff class that creates an HTML table showing a side by side comparison of two versions of a text. (Contributed by Dan Gass.)

The email package was updated to version 3.0, which dropped various deprecated APIs and removes support for Python versions earlier than 2.3. The 3.0 version of the package uses a new incremental parser for MIME messages, available in the email.FeedParser module. The new parser doesn’t require reading the entire message into memory, and doesn’t raise exceptions if a message is malformed; instead it records any problems in the defect attribute of the message. (Developed by Anthony Baxter, Barry Warsaw, Thomas Wouters, and others.)

The heapq module has been converted to C. The resulting tenfold improvement in speed makes the module suitable for handling high volumes of data. In addition, the module has two new functions nlargest() and nsmallest() that use heaps to find the N largest or smallest values in a dataset without the expense of a full sort. (Contributed by Raymond Hettinger.)

The httplib module now contains constants for HTTP status codes defined in various HTTP-related RFC documents. Constants have names such as OK, CREATED, CONTINUE, and MOVED_PERMANENTLY; use pydoc to get a full list. (Contributed by Andrew Eland.)

The imaplib module now supports IMAP’s THREAD command (contributed by Yves Dionne) and new deleteacl() and myrights() methods (contributed by Arnaud Mazin).

The itertools module gained a groupby(iterable[, *func*]) function. iterable is something that can be iterated over to return a stream of elements, and the optional func parameter is a function that takes an element and returns a key value; if omitted, the key is simply the element itself. groupby() then groups the elements into subsequences which have matching values of the key, and returns a series of 2-tuples containing the key value and an iterator over the subsequence.

Here’s an example to make this clearer. The key function simply returns whether a number is even or odd, so the result of groupby() is to return consecutive runs of odd or even numbers.

>>> import itertools
>>> L = [2, 4, 6, 7, 8, 9, 11, 12, 14]
>>> for key_val, it in itertools.groupby(L, lambda x: x % 2):
...    print key_val, list(it)
...
0 [2, 4, 6]
1 [7]
0 [8]
1 [9, 11]
0 [12, 14]
>>>

groupby() is typically used with sorted input. The logic for groupby() is similar to the Unix uniq filter which makes it handy for eliminating, counting, or identifying duplicate elements:

>>> word = 'abracadabra'
>>> letters = sorted(word)   # Turn string into a sorted list of letters
>>> letters
['a', 'a', 'a', 'a', 'a', 'b', 'b', 'c', 'd', 'r', 'r']
>>> for k, g in itertools.groupby(letters):
...    print k, list(g)
...
a ['a', 'a', 'a', 'a', 'a']
b ['b', 'b']
c ['c']
d ['d']
r ['r', 'r']
>>> # List unique letters
>>> [k for k, g in groupby(letters)]
['a', 'b', 'c', 'd', 'r']
>>> # Count letter occurrences
>>> [(k, len(list(g))) for k, g in groupby(letters)]
[('a', 5), ('b', 2), ('c', 1), ('d', 1), ('r', 2)]

(Contributed by Hye-Shik Chang.)

itertools also gained a function named tee(iterator, N) that returns N independent iterators that replicate iterator. If N is omitted, the default is 2.

>>> L = [1,2,3]
>>> i1, i2 = itertools.tee(L)
>>> i1,i2
(<itertools.tee object at 0x402c2080>, <itertools.tee object at 0x402c2090>)
>>> list(i1)               # Run the first iterator to exhaustion
[1, 2, 3]
>>> list(i2)               # Run the second iterator to exhaustion
[1, 2, 3]

Note that tee() has to keep copies of the values returned by the iterator; in the worst case, it may need to keep all of them. This should therefore be used carefully if the leading iterator can run far ahead of the trailing iterator in a long stream of inputs. If the separation is large, then you might as well use list() instead. When the iterators track closely with one another, tee() is ideal. Possible applications include bookmarking, windowing, or lookahead iterators. (Contributed by Raymond Hettinger.)

A number of functions were added to the locale module, such as bind_textdomain_codeset() to specify a particular encoding and a family of l*gettext() functions that return messages in the chosen encoding. (Contributed by Gustavo Niemeyer.)

Some keyword arguments were added to the logging package’s basicConfig() function to simplify log configuration. The default behavior is to log messages to standard error, but various keyword arguments can be specified to log to a particular file, change the logging format, or set the logging level. For example:

import logging
logging.basicConfig(filename='/var/log/application.log',
    level=0,  # Log all messages
    format='%(levelname):%(process):%(thread):%(message)')

Other additions to the logging package include a log(level, msg) convenience method, as well as a TimedRotatingFileHandler class that rotates its log files at a timed interval. The module already had RotatingFileHandler, which rotated logs once the file exceeded a certain size. Both classes derive from a new BaseRotatingHandler class that can be used to implement other rotating handlers.

(Changes implemented by Vinay Sajip.)

The marshal module now shares interned strings on unpacking a data structure. This may shrink the size of certain pickle strings, but the primary effect is to make .pyc files significantly smaller. (Contributed by Martin von Löwis.)

The nntplib module’s NNTP class gained description() and descriptions() methods to retrieve newsgroup descriptions for a single group or for a range of groups. (Contributed by Jürgen A. Erhard.)

Two new functions were added to the operator module, attrgetter(attr) and itemgetter(index). Both functions return callables that take a single argument and return the corresponding attribute or item; these callables make excellent data extractors when used with map() or sorted(). For example:

>>> L = [('c', 2), ('d', 1), ('a', 4), ('b', 3)]
>>> map(operator.itemgetter(0), L)
['c', 'd', 'a', 'b']
>>> map(operator.itemgetter(1), L)
[2, 1, 4, 3]
>>> sorted(L, key=operator.itemgetter(1)) # Sort list by second tuple item
[('d', 1), ('c', 2), ('b', 3), ('a', 4)]

(Contributed by Raymond Hettinger.)

The optparse module was updated in various ways. The module now passes its messages through gettext.gettext(), making it possible to internationalize Optik’s help and error messages. Help messages for options can now include the string '%default', which will be replaced by the option’s default value. (Contributed by Greg Ward.)

The long-term plan is to deprecate the rfc822 module in some future Python release in favor of the email package. To this end, the email.Utils.formatdate() function has been changed to make it usable as a replacement for rfc822.formatdate(). You may want to write new e-mail processing code with this in mind. (Change implemented by Anthony Baxter.)

A new urandom(n) function was added to the os module, returning a string containing n bytes of random data. This function provides access to platform-specific sources of randomness such as /dev/urandom on Linux or the Windows CryptoAPI. (Contributed by Trevor Perrin.)

Another new function: os.path.lexists(path) returns true if the file specified by path exists, whether or not it’s a symbolic link. This differs from the existing os.path.exists(path) function, which returns false if path is a symlink that points to a destination that doesn’t exist. (Contributed by Beni Cherniavsky.)

A new getsid() function was added to the posix module that underlies the os module. (Contributed by J. Raynor.)

The poplib module now supports POP over SSL. (Contributed by Hector Urtubia.)

The profile module can now profile C extension functions. (Contributed by Nick Bastin.)

The random module has a new method called getrandbits(N) that returns a long integer N bits in length. The existing randrange() method now uses getrandbits() where appropriate, making generation of arbitrarily large random numbers more efficient. (Contributed by Raymond Hettinger.)

The regular expression language accepted by the re module was extended with simple conditional expressions, written as (?(group)A|B). group is either a numeric group ID or a group name defined with (?P<group>...) earlier in the expression. If the specified group matched, the regular expression pattern A will be tested against the string; if the group didn’t match, the pattern B will be used instead. (Contributed by Gustavo Niemeyer.)

The re module is also no longer recursive, thanks to a massive amount of work by Gustavo Niemeyer. In a recursive regular expression engine, certain patterns result in a large amount of C stack space being consumed, and it was possible to overflow the stack. For example, if you matched a 30000-byte string of a characters against the expression (a|b)+, one stack frame was consumed per character. Python 2.3 tried to check for stack overflow and raise a RuntimeError exception, but certain patterns could sidestep the checking and if you were unlucky Python could segfault. Python 2.4’s regular expression engine can match this pattern without problems.

The signal module now performs tighter error-checking on the parameters to the signal.signal() function. For example, you can’t set a handler on the SIGKILL signal; previous versions of Python would quietly accept this, but 2.4 will raise a RuntimeError exception.

Two new functions were added to the socket module. socketpair() returns a pair of connected sockets and getservbyport(port) looks up the service name for a given port number. (Contributed by Dave Cole and Barry Warsaw.)

The sys.exitfunc() function has been deprecated. Code should be using the existing atexit module, which correctly handles calling multiple exit functions. Eventually sys.exitfunc() will become a purely internal interface, accessed only by atexit.

The tarfile module now generates GNU-format tar files by default. (Contributed by Lars Gustäbel.)

The threading module now has an elegantly simple way to support thread-local data. The module contains a local class whose attribute values are local to different threads.

import threading

data = threading.local()
data.number = 42
data.url = ('www.python.org', 80)

Other threads can assign and retrieve their own values for the number and url attributes. You can subclass local to initialize attributes or to add methods. (Contributed by Jim Fulton.)

The timeit module now automatically disables periodic garbage collection during the timing loop. This change makes consecutive timings more comparable. (Contributed by Raymond Hettinger.)

The weakref module now supports a wider variety of objects including Python functions, class instances, sets, frozensets, deques, arrays, files, sockets, and regular expression pattern objects. (Contributed by Raymond Hettinger.)

The xmlrpclib module now supports a multi-call extension for transmitting multiple XML-RPC calls in a single HTTP operation. (Contributed by Brian Quinlan.)

The mpz, rotor, and xreadlines modules have been removed.

cookielib

The cookielib library supports client-side handling for HTTP cookies, mirroring the Cookie module’s server-side cookie support. Cookies are stored in cookie jars; the library transparently stores cookies offered by the web server in the cookie jar, and fetches the cookie from the jar when connecting to the server. As in web browsers, policy objects control whether cookies are accepted or not.

In order to store cookies across sessions, two implementations of cookie jars are provided: one that stores cookies in the Netscape format so applications can use the Mozilla or Lynx cookie files, and one that stores cookies in the same format as the Perl libwww library.

urllib2 has been changed to interact with cookielib: HTTPCookieProcessor manages a cookie jar that is used when accessing URLs.

This module was contributed by John J. Lee.

doctest

The doctest module underwent considerable refactoring thanks to Edward Loper and Tim Peters. Testing can still be as simple as running doctest.testmod(), but the refactorings allow customizing the module’s operation in various ways

The new DocTestFinder class extracts the tests from a given object’s docstrings:

def f (x, y):
    """>>> f(2,2)
4
>>> f(3,2)
6
    """
    return x*y

finder = doctest.DocTestFinder()

# Get list of DocTest instances
tests = finder.find(f)

The new DocTestRunner class then runs individual tests and can produce a summary of the results:

runner = doctest.DocTestRunner()
for t in tests:
    tried, failed = runner.run(t)

runner.summarize(verbose=1)

The above example produces the following output:

1 items passed all tests:
   2 tests in f
2 tests in 1 items.
2 passed and 0 failed.
Test passed.

DocTestRunner uses an instance of the OutputChecker class to compare the expected output with the actual output. This class takes a number of different flags that customize its behaviour; ambitious users can also write a completely new subclass of OutputChecker.

The default output checker provides a number of handy features. For example, with the doctest.ELLIPSIS option flag, an ellipsis (...) in the expected output matches any substring, making it easier to accommodate outputs that vary in minor ways:

def o (n):
    """>>> o(1)
<__main__.C instance at 0x...>
>>>
"""

Another special string, <BLANKLINE>, matches a blank line:

def p (n):
    """>>> p(1)
<BLANKLINE>
>>>
"""

Another new capability is producing a diff-style display of the output by specifying the doctest.REPORT_UDIFF (unified diffs), doctest.REPORT_CDIFF (context diffs), or doctest.REPORT_NDIFF (delta-style) option flags. For example:

def g (n):
    """>>> g(4)
here
is
a
lengthy
>>>"""
    L = 'here is a rather lengthy list of words'.split()
    for word in L[:n]:
        print word

Running the above function’s tests with doctest.REPORT_UDIFF specified, you get the following output:

**********************************************************************
File "t.py", line 15, in g
Failed example:
    g(4)
Differences (unified diff with -expected +actual):
    @@ -2,3 +2,3 @@
     is
     a
    -lengthy
    +rather
**********************************************************************

Build and C API Changes

Some of the changes to Python’s build process and to the C API are:

Three new convenience macros were added for common return values from extension functions: Py_RETURN_NONE, Py_RETURN_TRUE, and Py_RETURN_FALSE. (Contributed by Brett Cannon.)

Another new macro, Py_CLEAR(obj), decreases the reference count of obj and sets obj to the null pointer. (Contributed by Jim Fulton.)

A new function, PyTuple_Pack(N, obj1, obj2, ..., objN), constructs tuples from a variable length argument list of Python objects. (Contributed by Raymond Hettinger.)

A new function, PyDict_Contains(d, k), implements fast dictionary lookups without masking exceptions raised during the look-up process. (Contributed by Raymond Hettinger.)

The Py_IS_NAN(X) macro returns 1 if its float or double argument X is a NaN. (Contributed by Tim Peters.)

C code can avoid unnecessary locking by using the new PyEval_ThreadsInitialized() function to tell if any thread operations have been performed. If this function returns false, no lock operations are needed. (Contributed by Nick Coghlan.)

A new function, PyArg_VaParseTupleAndKeywords(), is the same as PyArg_ParseTupleAndKeywords() but takes a va_list instead of a number of arguments. (Contributed by Greg Chapman.)

A new method flag, METH_COEXISTS, allows a function defined in slots to co-exist with a PyCFunction having the same name. This can halve the access time for a method such as set.__contains__(). (Contributed by Raymond Hettinger.)

Python can now be built with additional profiling for the interpreter itself, intended as an aid to people developing the Python core. Providing --enable-profiling to the configure script will let you profile the interpreter with gprof, and providing the --with-tsc switch enables profiling using the Pentium’s Time-Stamp-Counter register. Note that the --with-tsc switch is slightly misnamed, because the profiling feature also works on the PowerPC platform, though that processor architecture doesn’t call that register “the TSC register”. (Contributed by Jeremy Hylton.)

The tracebackobject type has been renamed to PyTracebackObject.

Port-Specific Changes

The Windows port now builds under MSVC++ 7.1 as well as version 6. (Contributed by Martin von Löwis.)

Porting to Python 2.4

This section lists previously described changes that may require changes to your code:

Left shifts and hexadecimal/octal constants that are too large no longer trigger a FutureWarning and return a value limited to 32 or 64 bits; instead they return a long integer.

Integer operations will no longer trigger an OverflowWarning. The OverflowWarning warning will disappear in Python 2.5.

The zip() built-in function and itertools.izip() now return an empty list instead of raising a TypeError exception if called with no arguments.

You can no longer compare the date and datetime instances provided by the datetime module. Two instances of different classes will now always be unequal, and relative comparisons (<, >) will raise a TypeError.

dircache.listdir() now passes exceptions to the caller instead of returning empty lists.

LexicalHandler.startDTD() used to receive the public and system IDs in the wrong order. This has been corrected; applications relying on the wrong order need to be fixed.

fcntl.ioctl() now warns if the mutate argument is omitted and relevant.

The tarfile module now generates GNU-format tar files by default.

Encountering a failure while importing a module no longer leaves a partially-initialized module object in sys.modules.

None is now a constant; code that binds a new value to the name None is now a syntax error.

The signals.signal() function now raises a RuntimeError exception for certain illegal values; previously these errors would pass silently. For example, you can no longer set a handler on the SIGKILL signal.

Acknowledgements

The author would like to thank the following people for offering suggestions, corrections and assistance with various drafts of this article: Koray Can, Hye-Shik Chang, Michael Dyck, Raymond Hettinger, Brian Hurt, Hamish Lawson, Fredrik Lundh, Sean Reifschneider, Sadruddin Rejeb.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬의 새로운 기능 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬의 새로운 기능 »

|

What’s New in Python 2.3

Author

A.M. Kuchling

This article explains the new features in Python 2.3. Python 2.3 was released on July 29, 2003.

The main themes for Python 2.3 are polishing some of the features added in 2.2, adding various small but useful enhancements to the core language, and expanding the standard library. The new object model introduced in the previous version has benefited from 18 months of bugfixes and from optimization efforts that have improved the performance of new-style classes. A few new built-in functions have been added such as sum() and enumerate(). The in operator can now be used for substring searches (e.g. "ab" in "abc" returns True).

Some of the many new library features include Boolean, set, heap, and date/time data types, the ability to import modules from ZIP-format archives, metadata support for the long-awaited Python catalog, an updated version of IDLE, and modules for logging messages, wrapping text, parsing CSV files, processing command-line options, using BerkeleyDB databases… the list of new and enhanced modules is lengthy.

This article doesn’t attempt to provide a complete specification of the new features, but instead provides a convenient overview. For full details, you should refer to the documentation for Python 2.3, such as the Python Library Reference and the Python Reference Manual. If you want to understand the complete implementation and design rationale, refer to the PEP for a particular new feature.

PEP 218: A Standard Set Datatype

The new sets module contains an implementation of a set datatype. The Set class is for mutable sets, sets that can have members added and removed. The ImmutableSet class is for sets that can’t be modified, and instances of ImmutableSet can therefore be used as dictionary keys. Sets are built on top of dictionaries, so the elements within a set must be hashable.

Here’s a simple example:

>>> import sets
>>> S = sets.Set([1,2,3])
>>> S
Set([1, 2, 3])
>>> 1 in S
True
>>> 0 in S
False
>>> S.add(5)
>>> S.remove(3)
>>> S
Set([1, 2, 5])
>>>

The union and intersection of sets can be computed with the union() and intersection() methods; an alternative notation uses the bitwise operators & and |. Mutable sets also have in-place versions of these methods, union_update() and intersection_update().

>>> S1 = sets.Set([1,2,3])
>>> S2 = sets.Set([4,5,6])
>>> S1.union(S2)
Set([1, 2, 3, 4, 5, 6])
>>> S1 | S2                  # Alternative notation
Set([1, 2, 3, 4, 5, 6])
>>> S1.intersection(S2)
Set([])
>>> S1 & S2                  # Alternative notation
Set([])
>>> S1.union_update(S2)
>>> S1
Set([1, 2, 3, 4, 5, 6])
>>>

It’s also possible to take the symmetric difference of two sets. This is the set of all elements in the union that aren’t in the intersection. Another way of putting it is that the symmetric difference contains all elements that are in exactly one set. Again, there’s an alternative notation (^), and an in-place version with the ungainly name symmetric_difference_update().

>>> S1 = sets.Set([1,2,3,4])
>>> S2 = sets.Set([3,4,5,6])
>>> S1.symmetric_difference(S2)
Set([1, 2, 5, 6])
>>> S1 ^ S2
Set([1, 2, 5, 6])
>>>

There are also issubset() and issuperset() methods for checking whether one set is a subset or superset of another:

>>> S1 = sets.Set([1,2,3])
>>> S2 = sets.Set([2,3])
>>> S2.issubset(S1)
True
>>> S1.issubset(S2)
False
>>> S1.issuperset(S2)
True
>>>

더 보기

PEP 218 [https://www.python.org/dev/peps/pep-0218] - Adding a Built-In Set Object Type

PEP written by Greg V. Wilson. Implemented by Greg V. Wilson, Alex Martelli, and GvR.

PEP 255: Simple Generators

In Python 2.2, generators were added as an optional feature, to be enabled by a from __future__ import generators directive. In 2.3 generators no longer need to be specially enabled, and are now always present; this means that yield is now always a keyword. The rest of this section is a copy of the description of generators from the “What’s New in Python 2.2” document; if you read it back when Python 2.2 came out, you can skip the rest of this section.

You’re doubtless familiar with how function calls work in Python or C. When you call a function, it gets a private namespace where its local variables are created. When the function reaches a return statement, the local variables are destroyed and the resulting value is returned to the caller. A later call to the same function will get a fresh new set of local variables. But, what if the local variables weren’t thrown away on exiting a function? What if you could later resume the function where it left off? This is what generators provide; they can be thought of as resumable functions.

Here’s the simplest example of a generator function:

def generate_ints(N):
    for i in range(N):
        yield i

A new keyword, yield, was introduced for generators. Any function containing a yield statement is a generator function; this is detected by Python’s bytecode compiler which compiles the function specially as a result.

When you call a generator function, it doesn’t return a single value; instead it returns a generator object that supports the iterator protocol. On executing the yield statement, the generator outputs the value of i, similar to a return statement. The big difference between yield and a return statement is that on reaching a yield the generator’s state of execution is suspended and local variables are preserved. On the next call to the generator’s .next() method, the function will resume executing immediately after the yield statement. (For complicated reasons, the yield statement isn’t allowed inside the try block of a try…finally statement; read PEP 255 [https://www.python.org/dev/peps/pep-0255] for a full explanation of the interaction between yield and exceptions.)

Here’s a sample usage of the generate_ints() generator:

>>> gen = generate_ints(3)
>>> gen
<generator object at 0x8117f90>
>>> gen.next()
0
>>> gen.next()
1
>>> gen.next()
2
>>> gen.next()
Traceback (most recent call last):
  File "stdin", line 1, in ?
  File "stdin", line 2, in generate_ints
StopIteration

You could equally write for i in generate_ints(5), or a,b,c = generate_ints(3).

Inside a generator function, the return statement can only be used without a value, and signals the end of the procession of values; afterwards the generator cannot return any further values. return with a value, such as return 5, is a syntax error inside a generator function. The end of the generator’s results can also be indicated by raising StopIteration manually, or by just letting the flow of execution fall off the bottom of the function.

You could achieve the effect of generators manually by writing your own class and storing all the local variables of the generator as instance variables. For example, returning a list of integers could be done by setting self.count to 0, and having the next() method increment self.count and return it. However, for a moderately complicated generator, writing a corresponding class would be much messier. Lib/test/test_generators.py contains a number of more interesting examples. The simplest one implements an in-order traversal of a tree using generators recursively.

# A recursive generator that generates Tree leaves in in-order.
def inorder(t):
    if t:
        for x in inorder(t.left):
            yield x
        yield t.label
        for x in inorder(t.right):
            yield x

Two other examples in Lib/test/test_generators.py produce solutions for the N-Queens problem (placing $N$ queens on an $NxN$ chess board so that no queen threatens another) and the Knight’s Tour (a route that takes a knight to every square of an $NxN$ chessboard without visiting any square twice).

The idea of generators comes from other programming languages, especially Icon (https://www.cs.arizona.edu/icon/), where the idea of generators is central. In Icon, every expression and function call behaves like a generator. One example from “An Overview of the Icon Programming Language” at https://www.cs.arizona.edu/icon/docs/ipd266.htm gives an idea of what this looks like:

sentence := "Store it in the neighboring harbor"
if (i := find("or", sentence)) > 5 then write(i)

In Icon the find() function returns the indexes at which the substring “or” is found: 3, 23, 33. In the if statement, i is first assigned a value of 3, but 3 is less than 5, so the comparison fails, and Icon retries it with the second value of 23. 23 is greater than 5, so the comparison now succeeds, and the code prints the value 23 to the screen.

Python doesn’t go nearly as far as Icon in adopting generators as a central concept. Generators are considered part of the core Python language, but learning or using them isn’t compulsory; if they don’t solve any problems that you have, feel free to ignore them. One novel feature of Python’s interface as compared to Icon’s is that a generator’s state is represented as a concrete object (the iterator) that can be passed around to other functions or stored in a data structure.

더 보기

PEP 255 [https://www.python.org/dev/peps/pep-0255] - Simple Generators

Written by Neil Schemenauer, Tim Peters, Magnus Lie Hetland. Implemented mostly by Neil Schemenauer and Tim Peters, with other fixes from the Python Labs crew.

PEP 263: Source Code Encodings

Python source files can now be declared as being in different character set encodings. Encodings are declared by including a specially formatted comment in the first or second line of the source file. For example, a UTF-8 file can be declared with:

#!/usr/bin/env python
# -*- coding: UTF-8 -*-

Without such an encoding declaration, the default encoding used is 7-bit ASCII. Executing or importing modules that contain string literals with 8-bit characters and have no encoding declaration will result in a DeprecationWarning being signalled by Python 2.3; in 2.4 this will be a syntax error.

The encoding declaration only affects Unicode string literals, which will be converted to Unicode using the specified encoding. Note that Python identifiers are still restricted to ASCII characters, so you can’t have variable names that use characters outside of the usual alphanumerics.

더 보기

PEP 263 [https://www.python.org/dev/peps/pep-0263] - Defining Python Source Code Encodings

Written by Marc-André Lemburg and Martin von Löwis; implemented by Suzuki Hisao and Martin von Löwis.

PEP 273: Importing Modules from ZIP Archives

The new zipimport module adds support for importing modules from a ZIP-format archive. You don’t need to import the module explicitly; it will be automatically imported if a ZIP archive’s filename is added to sys.path. For example:

amk@nyman:~/src/python$ unzip -l /tmp/example.zip
Archive:  /tmp/example.zip
  Length     Date   Time    Name
 --------    ----   ----    ----
     8467  11-26-02 22:30   jwzthreading.py
 --------                   -------
     8467                   1 file
amk@nyman:~/src/python$ ./python
Python 2.3 (#1, Aug 1 2003, 19:54:32)
>>> import sys
>>> sys.path.insert(0, '/tmp/example.zip')  # Add .zip file to front of path
>>> import jwzthreading
>>> jwzthreading.__file__
'/tmp/example.zip/jwzthreading.py'
>>>

An entry in sys.path can now be the filename of a ZIP archive. The ZIP archive can contain any kind of files, but only files named *.py, *.pyc, or *.pyo can be imported. If an archive only contains *.py files, Python will not attempt to modify the archive by adding the corresponding *.pyc file, meaning that if a ZIP archive doesn’t contain *.pyc files, importing may be rather slow.

A path within the archive can also be specified to only import from a subdirectory; for example, the path /tmp/example.zip/lib/ would only import from the lib/ subdirectory within the archive.

더 보기

PEP 273 [https://www.python.org/dev/peps/pep-0273] - Import Modules from Zip Archives

Written by James C. Ahlstrom, who also provided an implementation. Python 2.3 follows the specification in PEP 273 [https://www.python.org/dev/peps/pep-0273], but uses an implementation written by Just van Rossum that uses the import hooks described in PEP 302 [https://www.python.org/dev/peps/pep-0302]. See section PEP 302: New Import Hooks for a description of the new import hooks.

PEP 277: Unicode file name support for Windows NT

On Windows NT, 2000, and XP, the system stores file names as Unicode strings. Traditionally, Python has represented file names as byte strings, which is inadequate because it renders some file names inaccessible.

Python now allows using arbitrary Unicode strings (within the limitations of the file system) for all functions that expect file names, most notably the open() built-in function. If a Unicode string is passed to os.listdir(), Python now returns a list of Unicode strings. A new function, os.getcwdu(), returns the current directory as a Unicode string.

Byte strings still work as file names, and on Windows Python will transparently convert them to Unicode using the mbcs encoding.

Other systems also allow Unicode strings as file names but convert them to byte strings before passing them to the system, which can cause a UnicodeError to be raised. Applications can test whether arbitrary Unicode strings are supported as file names by checking os.path.supports_unicode_filenames, a Boolean value.

Under MacOS, os.listdir() may now return Unicode filenames.

더 보기

PEP 277 [https://www.python.org/dev/peps/pep-0277] - Unicode file name support for Windows NT

Written by Neil Hodgson; implemented by Neil Hodgson, Martin von Löwis, and Mark Hammond.

PEP 278: Universal Newline Support

The three major operating systems used today are Microsoft Windows, Apple’s Macintosh OS, and the various Unix derivatives. A minor irritation of cross-platform work is that these three platforms all use different characters to mark the ends of lines in text files. Unix uses the linefeed (ASCII character 10), MacOS uses the carriage return (ASCII character 13), and Windows uses a two-character sequence of a carriage return plus a newline.

Python’s file objects can now support end of line conventions other than the one followed by the platform on which Python is running. Opening a file with the mode 'U' or 'rU' will open a file for reading in universal newlines mode. All three line ending conventions will be translated to a '\n' in the strings returned by the various file methods such as read() and readline().

Universal newline support is also used when importing modules and when executing a file with the execfile() function. This means that Python modules can be shared between all three operating systems without needing to convert the line-endings.

This feature can be disabled when compiling Python by specifying the --without-universal-newlines switch when running Python’s configure script.

더 보기

PEP 278 [https://www.python.org/dev/peps/pep-0278] - Universal Newline Support

Written and implemented by Jack Jansen.

PEP 279: enumerate()

A new built-in function, enumerate(), will make certain loops a bit clearer. enumerate(thing), where thing is either an iterator or a sequence, returns an iterator that will return (0, thing[0]), (1, thing[1]), (2, thing[2]), and so forth.

A common idiom to change every element of a list looks like this:

for i in range(len(L)):
    item = L[i]
    # ... compute some result based on item ...
    L[i] = result

This can be rewritten using enumerate() as:

for i, item in enumerate(L):
    # ... compute some result based on item ...
    L[i] = result

더 보기

PEP 279 [https://www.python.org/dev/peps/pep-0279] - The enumerate() built-in function

Written and implemented by Raymond D. Hettinger.

PEP 282: The logging Package

A standard package for writing logs, logging, has been added to Python 2.3. It provides a powerful and flexible mechanism for generating logging output which can then be filtered and processed in various ways. A configuration file written in a standard format can be used to control the logging behavior of a program. Python includes handlers that will write log records to standard error or to a file or socket, send them to the system log, or even e-mail them to a particular address; of course, it’s also possible to write your own handler classes.

The Logger class is the primary class. Most application code will deal with one or more Logger objects, each one used by a particular subsystem of the application. Each Logger is identified by a name, and names are organized into a hierarchy using . as the component separator. For example, you might have Logger instances named server, server.auth and server.network. The latter two instances are below server in the hierarchy. This means that if you turn up the verbosity for server or direct server messages to a different handler, the changes will also apply to records logged to server.auth and server.network. There’s also a root Logger that’s the parent of all other loggers.

For simple uses, the logging package contains some convenience functions that always use the root log:

import logging

logging.debug('Debugging information')
logging.info('Informational message')
logging.warning('Warning:config file %s not found', 'server.conf')
logging.error('Error occurred')
logging.critical('Critical error -- shutting down')

This produces the following output:

WARNING:root:Warning:config file server.conf not found
ERROR:root:Error occurred
CRITICAL:root:Critical error -- shutting down

In the default configuration, informational and debugging messages are suppressed and the output is sent to standard error. You can enable the display of informational and debugging messages by calling the setLevel() method on the root logger.

Notice the warning() call’s use of string formatting operators; all of the functions for logging messages take the arguments (msg, arg1, arg2, ...) and log the string resulting from msg % (arg1, arg2, ...).

There’s also an exception() function that records the most recent traceback. Any of the other functions will also record the traceback if you specify a true value for the keyword argument exc_info.

def f():
    try:    1/0
    except: logging.exception('Problem recorded')

f()

This produces the following output:

ERROR:root:Problem recorded
Traceback (most recent call last):
  File "t.py", line 6, in f
    1/0
ZeroDivisionError: integer division or modulo by zero

Slightly more advanced programs will use a logger other than the root logger. The getLogger(name) function is used to get a particular log, creating it if it doesn’t exist yet. getLogger(None) returns the root logger.

log = logging.getLogger('server')
 ...
log.info('Listening on port %i', port)
 ...
log.critical('Disk full')
 ...

Log records are usually propagated up the hierarchy, so a message logged to server.auth is also seen by server and root, but a Logger can prevent this by setting its propagate attribute to False.

There are more classes provided by the logging package that can be customized. When a Logger instance is told to log a message, it creates a LogRecord instance that is sent to any number of different Handler instances. Loggers and handlers can also have an attached list of filters, and each filter can cause the LogRecord to be ignored or can modify the record before passing it along. When they’re finally output, LogRecord instances are converted to text by a Formatter class. All of these classes can be replaced by your own specially-written classes.

With all of these features the logging package should provide enough flexibility for even the most complicated applications. This is only an incomplete overview of its features, so please see the package’s reference documentation for all of the details. Reading PEP 282 [https://www.python.org/dev/peps/pep-0282] will also be helpful.

더 보기

PEP 282 [https://www.python.org/dev/peps/pep-0282] - A Logging System

Written by Vinay Sajip and Trent Mick; implemented by Vinay Sajip.

PEP 285: A Boolean Type

A Boolean type was added to Python 2.3. Two new constants were added to the __builtin__ module, True and False. (True and False constants were added to the built-ins in Python 2.2.1, but the 2.2.1 versions are simply set to integer values of 1 and 0 and aren’t a different type.)

The type object for this new type is named bool; the constructor for it takes any Python value and converts it to True or False.

>>> bool(1)
True
>>> bool(0)
False
>>> bool([])
False
>>> bool( (1,) )
True

Most of the standard library modules and built-in functions have been changed to return Booleans.

>>> obj = []
>>> hasattr(obj, 'append')
True
>>> isinstance(obj, list)
True
>>> isinstance(obj, tuple)
False

Python’s Booleans were added with the primary goal of making code clearer. For example, if you’re reading a function and encounter the statement return 1, you might wonder whether the 1 represents a Boolean truth value, an index, or a coefficient that multiplies some other quantity. If the statement is return True, however, the meaning of the return value is quite clear.

Python’s Booleans were not added for the sake of strict type-checking. A very strict language such as Pascal would also prevent you performing arithmetic with Booleans, and would require that the expression in an if statement always evaluate to a Boolean result. Python is not this strict and never will be, as PEP 285 [https://www.python.org/dev/peps/pep-0285] explicitly says. This means you can still use any expression in an if statement, even ones that evaluate to a list or tuple or some random object. The Boolean type is a subclass of the int class so that arithmetic using a Boolean still works.

>>> True + 1
2
>>> False + 1
1
>>> False * 75
0
>>> True * 75
75

To sum up True and False in a sentence: they’re alternative ways to spell the integer values 1 and 0, with the single difference that str() and repr() return the strings 'True' and 'False' instead of '1' and '0'.

더 보기

PEP 285 [https://www.python.org/dev/peps/pep-0285] - Adding a bool type

Written and implemented by GvR.

PEP 293: Codec Error Handling Callbacks

When encoding a Unicode string into a byte string, unencodable characters may be encountered. So far, Python has allowed specifying the error processing as either “strict” (raising UnicodeError), “ignore” (skipping the character), or “replace” (using a question mark in the output string), with “strict” being the default behavior. It may be desirable to specify alternative processing of such errors, such as inserting an XML character reference or HTML entity reference into the converted string.

Python now has a flexible framework to add different processing strategies. New error handlers can be added with codecs.register_error(), and codecs then can access the error handler with codecs.lookup_error(). An equivalent C API has been added for codecs written in C. The error handler gets the necessary state information such as the string being converted, the position in the string where the error was detected, and the target encoding. The handler can then either raise an exception or return a replacement string.

Two additional error handlers have been implemented using this framework: “backslashreplace” uses Python backslash quoting to represent unencodable characters and “xmlcharrefreplace” emits XML character references.

더 보기

PEP 293 [https://www.python.org/dev/peps/pep-0293] - Codec Error Handling Callbacks

Written and implemented by Walter Dörwald.

PEP 301: Package Index and Metadata for Distutils

Support for the long-requested Python catalog makes its first appearance in 2.3.

The heart of the catalog is the new Distutils register command. Running python setup.py register will collect the metadata describing a package, such as its name, version, maintainer, description, &c., and send it to a central catalog server. The resulting catalog is available from https://pypi.org.

To make the catalog a bit more useful, a new optional classifiers keyword argument has been added to the Distutils setup() function. A list of Trove [http://catb.org/~esr/trove/]-style strings can be supplied to help classify the software.

Here’s an example setup.py with classifiers, written to be compatible with older versions of the Distutils:

from distutils import core
kw = {'name': "Quixote",
      'version': "0.5.1",
      'description': "A highly Pythonic Web application framework",
      # ...
      }

if (hasattr(core, 'setup_keywords') and
    'classifiers' in core.setup_keywords):
    kw['classifiers'] = \
        ['Topic :: Internet :: WWW/HTTP :: Dynamic Content',
         'Environment :: No Input/Output (Daemon)',
         'Intended Audience :: Developers'],

core.setup(**kw)

The full list of classifiers can be obtained by running python setup.py register --list-classifiers.

더 보기

PEP 301 [https://www.python.org/dev/peps/pep-0301] - Package Index and Metadata for Distutils

Written and implemented by Richard Jones.

PEP 302: New Import Hooks

While it’s been possible to write custom import hooks ever since the ihooks module was introduced in Python 1.3, no one has ever been really happy with it because writing new import hooks is difficult and messy. There have been various proposed alternatives such as the imputil and iu modules, but none of them has ever gained much acceptance, and none of them were easily usable from C code.

PEP 302 [https://www.python.org/dev/peps/pep-0302] borrows ideas from its predecessors, especially from Gordon McMillan’s iu module. Three new items are added to the sys module:

sys.path_hooks is a list of callable objects; most often they’ll be classes. Each callable takes a string containing a path and either returns an importer object that will handle imports from this path or raises an ImportError exception if it can’t handle this path.

sys.path_importer_cache caches importer objects for each path, so sys.path_hooks will only need to be traversed once for each path.

sys.meta_path is a list of importer objects that will be traversed before sys.path is checked. This list is initially empty, but user code can add objects to it. Additional built-in and frozen modules can be imported by an object added to this list.

Importer objects must have a single method, find_module(fullname, path=None). fullname will be a module or package name, e.g. string or distutils.core. find_module() must return a loader object that has a single method, load_module(fullname), that creates and returns the corresponding module object.

Pseudo-code for Python’s new import logic, therefore, looks something like this (simplified a bit; see PEP 302 [https://www.python.org/dev/peps/pep-0302] for the full details):

for mp in sys.meta_path:
    loader = mp(fullname)
    if loader is not None:
        <module> = loader.load_module(fullname)

for path in sys.path:
    for hook in sys.path_hooks:
        try:
            importer = hook(path)
        except ImportError:
            # ImportError, so try the other path hooks
            pass
        else:
            loader = importer.find_module(fullname)
            <module> = loader.load_module(fullname)

# Not found!
raise ImportError

더 보기

PEP 302 [https://www.python.org/dev/peps/pep-0302] - New Import Hooks

Written by Just van Rossum and Paul Moore. Implemented by Just van Rossum.

PEP 305: Comma-separated Files

Comma-separated files are a format frequently used for exporting data from databases and spreadsheets. Python 2.3 adds a parser for comma-separated files.

Comma-separated format is deceptively simple at first glance:

Costs,150,200,3.95

Read a line and call line.split(','): what could be simpler? But toss in string data that can contain commas, and things get more complicated:

"Costs",150,200,3.95,"Includes taxes, shipping, and sundry items"

A big ugly regular expression can parse this, but using the new csv package is much simpler:

import csv

input = open('datafile', 'rb')
reader = csv.reader(input)
for line in reader:
    print line

The reader() function takes a number of different options. The field separator isn’t limited to the comma and can be changed to any character, and so can the quoting and line-ending characters.

Different dialects of comma-separated files can be defined and registered; currently there are two dialects, both used by Microsoft Excel. A separate csv.writer class will generate comma-separated files from a succession of tuples or lists, quoting strings that contain the delimiter.

더 보기

PEP 305 [https://www.python.org/dev/peps/pep-0305] - CSV File API

Written and implemented by Kevin Altis, Dave Cole, Andrew McNamara, Skip Montanaro, Cliff Wells.

PEP 307: Pickle Enhancements

The pickle and cPickle modules received some attention during the 2.3 development cycle. In 2.2, new-style classes could be pickled without difficulty, but they weren’t pickled very compactly; PEP 307 [https://www.python.org/dev/peps/pep-0307] quotes a trivial example where a new-style class results in a pickled string three times longer than that for a classic class.

The solution was to invent a new pickle protocol. The pickle.dumps() function has supported a text-or-binary flag for a long time. In 2.3, this flag is redefined from a Boolean to an integer: 0 is the old text-mode pickle format, 1 is the old binary format, and now 2 is a new 2.3-specific format. A new constant, pickle.HIGHEST_PROTOCOL, can be used to select the fanciest protocol available.

Unpickling is no longer considered a safe operation. 2.2’s pickle provided hooks for trying to prevent unsafe classes from being unpickled (specifically, a __safe_for_unpickling__ attribute), but none of this code was ever audited and therefore it’s all been ripped out in 2.3. You should not unpickle untrusted data in any version of Python.

To reduce the pickling overhead for new-style classes, a new interface for customizing pickling was added using three special methods: __getstate__(), __setstate__(), and __getnewargs__(). Consult PEP 307 [https://www.python.org/dev/peps/pep-0307] for the full semantics of these methods.

As a way to compress pickles yet further, it’s now possible to use integer codes instead of long strings to identify pickled classes. The Python Software Foundation will maintain a list of standardized codes; there’s also a range of codes for private use. Currently no codes have been specified.

더 보기

PEP 307 [https://www.python.org/dev/peps/pep-0307] - Extensions to the pickle protocol

Written and implemented by Guido van Rossum and Tim Peters.

Extended Slices

Ever since Python 1.4, the slicing syntax has supported an optional third “step” or “stride” argument. For example, these are all legal Python syntax: L[1:10:2], L[:-1:1], L[::-1]. This was added to Python at the request of the developers of Numerical Python, which uses the third argument extensively. However, Python’s built-in list, tuple, and string sequence types have never supported this feature, raising a TypeError if you tried it. Michael Hudson contributed a patch to fix this shortcoming.

For example, you can now easily extract the elements of a list that have even indexes:

>>> L = range(10)
>>> L[::2]
[0, 2, 4, 6, 8]

Negative values also work to make a copy of the same list in reverse order:

>>> L[::-1]
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

This also works for tuples, arrays, and strings:

>>> s='abcd'
>>> s[::2]
'ac'
>>> s[::-1]
'dcba'

If you have a mutable sequence such as a list or an array you can assign to or delete an extended slice, but there are some differences between assignment to extended and regular slices. Assignment to a regular slice can be used to change the length of the sequence:

>>> a = range(3)
>>> a
[0, 1, 2]
>>> a[1:3] = [4, 5, 6]
>>> a
[0, 4, 5, 6]

Extended slices aren’t this flexible. When assigning to an extended slice, the list on the right hand side of the statement must contain the same number of items as the slice it is replacing:

>>> a = range(4)
>>> a
[0, 1, 2, 3]
>>> a[::2]
[0, 2]
>>> a[::2] = [0, -1]
>>> a
[0, 1, -1, 3]
>>> a[::2] = [0,1,2]
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
ValueError: attempt to assign sequence of size 3 to extended slice of size 2

Deletion is more straightforward:

>>> a = range(4)
>>> a
[0, 1, 2, 3]
>>> a[::2]
[0, 2]
>>> del a[::2]
>>> a
[1, 3]

One can also now pass slice objects to the __getitem__() methods of the built-in sequences:

>>> range(10).__getitem__(slice(0, 5, 2))
[0, 2, 4]

Or use slice objects directly in subscripts:

>>> range(10)[slice(0, 5, 2)]
[0, 2, 4]

To simplify implementing sequences that support extended slicing, slice objects now have a method indices(length) which, given the length of a sequence, returns a (start, stop, step) tuple that can be passed directly to range(). indices() handles omitted and out-of-bounds indices in a manner consistent with regular slices (and this innocuous phrase hides a welter of confusing details!). The method is intended to be used like this:

class FakeSeq:
    ...
    def calc_item(self, i):
        ...
    def __getitem__(self, item):
        if isinstance(item, slice):
            indices = item.indices(len(self))
            return FakeSeq([self.calc_item(i) for i in range(*indices)])
        else:
            return self.calc_item(i)

From this example you can also see that the built-in slice object is now the type object for the slice type, and is no longer a function. This is consistent with Python 2.2, where int, str, etc., underwent the same change.

Other Language Changes

Here are all of the changes that Python 2.3 makes to the core Python language.

The yield statement is now always a keyword, as described in section PEP 255: Simple Generators of this document.

A new built-in function enumerate() was added, as described in section PEP 279: enumerate() of this document.

Two new constants, True and False were added along with the built-in bool type, as described in section PEP 285: A Boolean Type of this document.

The int() type constructor will now return a long integer instead of raising an OverflowError when a string or floating-point number is too large to fit into an integer. This can lead to the paradoxical result that isinstance(int(expression), int) is false, but that seems unlikely to cause problems in practice.

Built-in types now support the extended slicing syntax, as described in section Extended Slices of this document.

A new built-in function, sum(iterable, start=0), adds up the numeric items in the iterable object and returns their sum. sum() only accepts numbers, meaning that you can’t use it to concatenate a bunch of strings. (Contributed by Alex Martelli.)

list.insert(pos, value) used to insert value at the front of the list when pos was negative. The behaviour has now been changed to be consistent with slice indexing, so when pos is -1 the value will be inserted before the last element, and so forth.

list.index(value), which searches for value within the list and returns its index, now takes optional start and stop arguments to limit the search to only part of the list.

Dictionaries have a new method, pop(key[, *default*]), that returns the value corresponding to key and removes that key/value pair from the dictionary. If the requested key isn’t present in the dictionary, default is returned if it’s specified and KeyError raised if it isn’t.

>>> d = {1:2}
>>> d
{1: 2}
>>> d.pop(4)
Traceback (most recent call last):
  File "stdin", line 1, in ?
KeyError: 4
>>> d.pop(1)
2
>>> d.pop(1)
Traceback (most recent call last):
  File "stdin", line 1, in ?
KeyError: 'pop(): dictionary is empty'
>>> d
{}
>>>

There’s also a new class method, dict.fromkeys(iterable, value), that creates a dictionary with keys taken from the supplied iterator iterable and all values set to value, defaulting to None.

(Patches contributed by Raymond Hettinger.)

Also, the dict() constructor now accepts keyword arguments to simplify creating small dictionaries:

>>> dict(red=1, blue=2, green=3, black=4)
{'blue': 2, 'black': 4, 'green': 3, 'red': 1}

(Contributed by Just van Rossum.)

The assert statement no longer checks the __debug__ flag, so you can no longer disable assertions by assigning to __debug__. Running Python with the -O switch will still generate code that doesn’t execute any assertions.

Most type objects are now callable, so you can use them to create new objects such as functions, classes, and modules. (This means that the new module can be deprecated in a future Python version, because you can now use the type objects available in the types module.) For example, you can create a new module object with the following code:

>>> import types
>>> m = types.ModuleType('abc','docstring')
>>> m
<module 'abc' (built-in)>
>>> m.__doc__
'docstring'

A new warning, PendingDeprecationWarning was added to indicate features which are in the process of being deprecated. The warning will not be printed by default. To check for use of features that will be deprecated in the future, supply -Walways::PendingDeprecationWarning:: on the command line or use warnings.filterwarnings().

The process of deprecating string-based exceptions, as in raise "Error occurred", has begun. Raising a string will now trigger PendingDeprecationWarning.

Using None as a variable name will now result in a SyntaxWarning warning. In a future version of Python, None may finally become a keyword.

The xreadlines() method of file objects, introduced in Python 2.1, is no longer necessary because files now behave as their own iterator. xreadlines() was originally introduced as a faster way to loop over all the lines in a file, but now you can simply write for line in file_obj. File objects also have a new read-only encoding attribute that gives the encoding used by the file; Unicode strings written to the file will be automatically converted to bytes using the given encoding.

The method resolution order used by new-style classes has changed, though you’ll only notice the difference if you have a really complicated inheritance hierarchy. Classic classes are unaffected by this change. Python 2.2 originally used a topological sort of a class’s ancestors, but 2.3 now uses the C3 algorithm as described in the paper “A Monotonic Superclass Linearization for Dylan” [http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.19.3910]. To understand the motivation for this change, read Michele Simionato’s article “Python 2.3 Method Resolution Order” [http://www.phyast.pitt.edu/~micheles/mro.html], or read the thread on python-dev starting with the message at https://mail.python.org/pipermail/python-dev/2002-October/029035.html. Samuele Pedroni first pointed out the problem and also implemented the fix by coding the C3 algorithm.

Python runs multithreaded programs by switching between threads after executing N bytecodes. The default value for N has been increased from 10 to 100 bytecodes, speeding up single-threaded applications by reducing the switching overhead. Some multithreaded applications may suffer slower response time, but that’s easily fixed by setting the limit back to a lower number using sys.setcheckinterval(N). The limit can be retrieved with the new sys.getcheckinterval() function.

One minor but far-reaching change is that the names of extension types defined by the modules included with Python now contain the module and a '.' in front of the type name. For example, in Python 2.2, if you created a socket and printed its __class__, you’d get this output:

>>> s = socket.socket()
>>> s.__class__
<type 'socket'>

In 2.3, you get this:

>>> s.__class__
<type '_socket.socket'>

One of the noted incompatibilities between old- and new-style classes has been removed: you can now assign to the __name__ and __bases__ attributes of new-style classes. There are some restrictions on what can be assigned to __bases__ along the lines of those relating to assigning to an instance’s __class__ attribute.

String Changes

The in operator now works differently for strings. Previously, when evaluating X in Y where X and Y are strings, X could only be a single character. That’s now changed; X can be a string of any length, and X in Y will return True if X is a substring of Y. If X is the empty string, the result is always True.

>>> 'ab' in 'abcd'
True
>>> 'ad' in 'abcd'
False
>>> '' in 'abcd'
True

Note that this doesn’t tell you where the substring starts; if you need that information, use the find() string method.

The strip(), lstrip(), and rstrip() string methods now have an optional argument for specifying the characters to strip. The default is still to remove all whitespace characters:

>>> '   abc '.strip()
'abc'
>>> '><><abc<><><>'.strip('<>')
'abc'
>>> '><><abc<><><>\n'.strip('<>')
'abc<><><>\n'
>>> u'\u4000\u4001abc\u4000'.strip(u'\u4000')
u'\u4001abc'
>>>

(Suggested by Simon Brunning and implemented by Walter Dörwald.)

The startswith() and endswith() string methods now accept negative numbers for the start and end parameters.

Another new string method is zfill(), originally a function in the string module. zfill() pads a numeric string with zeros on the left until it’s the specified width. Note that the % operator is still more flexible and powerful than zfill().

>>> '45'.zfill(4)
'0045'
>>> '12345'.zfill(4)
'12345'
>>> 'goofy'.zfill(6)
'0goofy'

(Contributed by Walter Dörwald.)

A new type object, basestring, has been added. Both 8-bit strings and Unicode strings inherit from this type, so isinstance(obj, basestring) will return True for either kind of string. It’s a completely abstract type, so you can’t create basestring instances.

Interned strings are no longer immortal and will now be garbage-collected in the usual way when the only reference to them is from the internal dictionary of interned strings. (Implemented by Oren Tirosh.)

Optimizations

The creation of new-style class instances has been made much faster; they’re now faster than classic classes!

The sort() method of list objects has been extensively rewritten by Tim Peters, and the implementation is significantly faster.

Multiplication of large long integers is now much faster thanks to an implementation of Karatsuba multiplication, an algorithm that scales better than the O(n*n) required for the grade-school multiplication algorithm. (Original patch by Christopher A. Craig, and significantly reworked by Tim Peters.)

The SET_LINENO opcode is now gone. This may provide a small speed increase, depending on your compiler’s idiosyncrasies. See section Other Changes and Fixes for a longer explanation. (Removed by Michael Hudson.)

xrange() objects now have their own iterator, making for i in xrange(n) slightly faster than for i in range(n). (Patch by Raymond Hettinger.)

A number of small rearrangements have been made in various hotspots to improve performance, such as inlining a function or removing some code. (Implemented mostly by GvR, but lots of people have contributed single changes.)

The net result of the 2.3 optimizations is that Python 2.3 runs the pystone benchmark around 25% faster than Python 2.2.

New, Improved, and Deprecated Modules

As usual, Python’s standard library received a number of enhancements and bug fixes. Here’s a partial list of the most notable changes, sorted alphabetically by module name. Consult the Misc/NEWS file in the source tree for a more complete list of changes, or look through the CVS logs for all the details.

The array module now supports arrays of Unicode characters using the 'u' format character. Arrays also now support using the += assignment operator to add another array’s contents, and the *= assignment operator to repeat an array. (Contributed by Jason Orendorff.)

The bsddb module has been replaced by version 4.1.6 of the PyBSDDB [http://pybsddb.sourceforge.net] package, providing a more complete interface to the transactional features of the BerkeleyDB library.

The old version of the module has been renamed to bsddb185 and is no longer built automatically; you’ll have to edit Modules/Setup to enable it. Note that the new bsddb package is intended to be compatible with the old module, so be sure to file bugs if you discover any incompatibilities. When upgrading to Python 2.3, if the new interpreter is compiled with a new version of the underlying BerkeleyDB library, you will almost certainly have to convert your database files to the new version. You can do this fairly easily with the new scripts db2pickle.py and pickle2db.py which you will find in the distribution’s Tools/scripts directory. If you’ve already been using the PyBSDDB package and importing it as bsddb3, you will have to change your import statements to import it as bsddb.

The new bz2 module is an interface to the bz2 data compression library. bz2-compressed data is usually smaller than corresponding zlib-compressed data. (Contributed by Gustavo Niemeyer.)

A set of standard date/time types has been added in the new datetime module. See the following section for more details.

The Distutils Extension class now supports an extra constructor argument named depends for listing additional source files that an extension depends on. This lets Distutils recompile the module if any of the dependency files are modified. For example, if sampmodule.c includes the header file sample.h, you would create the Extension object like this:

ext = Extension("samp",
                sources=["sampmodule.c"],
                depends=["sample.h"])

Modifying sample.h would then cause the module to be recompiled. (Contributed by Jeremy Hylton.)

Other minor changes to Distutils: it now checks for the CC, CFLAGS, CPP, LDFLAGS, and CPPFLAGS environment variables, using them to override the settings in Python’s configuration (contributed by Robert Weber).

Previously the doctest module would only search the docstrings of public methods and functions for test cases, but it now also examines private ones as well. The DocTestSuite() function creates a unittest.TestSuite object from a set of doctest tests.

The new gc.get_referents(object) function returns a list of all the objects referenced by object.

The getopt module gained a new function, gnu_getopt(), that supports the same arguments as the existing getopt() function but uses GNU-style scanning mode. The existing getopt() stops processing options as soon as a non-option argument is encountered, but in GNU-style mode processing continues, meaning that options and arguments can be mixed. For example:

>>> getopt.getopt(['-f', 'filename', 'output', '-v'], 'f:v')
([('-f', 'filename')], ['output', '-v'])
>>> getopt.gnu_getopt(['-f', 'filename', 'output', '-v'], 'f:v')
([('-f', 'filename'), ('-v', '')], ['output'])

(Contributed by Peter Åstrand.)

The grp, pwd, and resource modules now return enhanced tuples:

>>> import grp
>>> g = grp.getgrnam('amk')
>>> g.gr_name, g.gr_gid
('amk', 500)

The gzip module can now handle files exceeding 2 GiB.

The new heapq module contains an implementation of a heap queue algorithm. A heap is an array-like data structure that keeps items in a partially sorted order such that, for every index k, heap[k] <= heap[2*k+1] and heap[k] <= heap[2*k+2]. This makes it quick to remove the smallest item, and inserting a new item while maintaining the heap property is O(lg n). (See https://xlinux.nist.gov/dads//HTML/priorityque.html for more information about the priority queue data structure.)

The heapq module provides heappush() and heappop() functions for adding and removing items while maintaining the heap property on top of some other mutable Python sequence type. Here’s an example that uses a Python list:

>>> import heapq
>>> heap = []
>>> for item in [3, 7, 5, 11, 1]:
...    heapq.heappush(heap, item)
...
>>> heap
[1, 3, 5, 11, 7]
>>> heapq.heappop(heap)
1
>>> heapq.heappop(heap)
3
>>> heap
[5, 7, 11]

(Contributed by Kevin O’Connor.)

The IDLE integrated development environment has been updated using the code from the IDLEfork project (http://idlefork.sourceforge.net). The most notable feature is that the code being developed is now executed in a subprocess, meaning that there’s no longer any need for manual reload() operations. IDLE’s core code has been incorporated into the standard library as the idlelib package.

The imaplib module now supports IMAP over SSL. (Contributed by Piers Lauder and Tino Lange.)

The itertools contains a number of useful functions for use with iterators, inspired by various functions provided by the ML and Haskell languages. For example, itertools.ifilter(predicate, iterator) returns all elements in the iterator for which the function predicate() returns True, and itertools.repeat(obj, N) returns obj N times. There are a number of other functions in the module; see the package’s reference documentation for details. (Contributed by Raymond Hettinger.)

Two new functions in the math module, degrees(rads) and radians(degs), convert between radians and degrees. Other functions in the math module such as math.sin() and math.cos() have always required input values measured in radians. Also, an optional base argument was added to math.log() to make it easier to compute logarithms for bases other than e and 10. (Contributed by Raymond Hettinger.)

Several new POSIX functions (getpgid(), killpg(), lchown(), loadavg(), major(), makedev(), minor(), and mknod()) were added to the posix module that underlies the os module. (Contributed by Gustavo Niemeyer, Geert Jansen, and Denis S. Otkidach.)

In the os module, the *stat() family of functions can now report fractions of a second in a timestamp. Such time stamps are represented as floats, similar to the value returned by time.time().

During testing, it was found that some applications will break if time stamps are floats. For compatibility, when using the tuple interface of the stat_result time stamps will be represented as integers. When using named fields (a feature first introduced in Python 2.2), time stamps are still represented as integers, unless os.stat_float_times() is invoked to enable float return values:

>>> os.stat("/tmp").st_mtime
1034791200
>>> os.stat_float_times(True)
>>> os.stat("/tmp").st_mtime
1034791200.6335014

In Python 2.4, the default will change to always returning floats.

Application developers should enable this feature only if all their libraries work properly when confronted with floating point time stamps, or if they use the tuple API. If used, the feature should be activated on an application level instead of trying to enable it on a per-use basis.

The optparse module contains a new parser for command-line arguments that can convert option values to a particular Python type and will automatically generate a usage message. See the following section for more details.

The old and never-documented linuxaudiodev module has been deprecated, and a new version named ossaudiodev has been added. The module was renamed because the OSS sound drivers can be used on platforms other than Linux, and the interface has also been tidied and brought up to date in various ways. (Contributed by Greg Ward and Nicholas FitzRoy-Dale.)

The new platform module contains a number of functions that try to determine various properties of the platform you’re running on. There are functions for getting the architecture, CPU type, the Windows OS version, and even the Linux distribution version. (Contributed by Marc-André Lemburg.)

The parser objects provided by the pyexpat module can now optionally buffer character data, resulting in fewer calls to your character data handler and therefore faster performance. Setting the parser object’s buffer_text attribute to True will enable buffering.

The sample(population, k) function was added to the random module. population is a sequence or xrange object containing the elements of a population, and sample() chooses k elements from the population without replacing chosen elements. k can be any value up to len(population). For example:

>>> days = ['Mo', 'Tu', 'We', 'Th', 'Fr', 'St', 'Sn']
>>> random.sample(days, 3)      # Choose 3 elements
['St', 'Sn', 'Th']
>>> random.sample(days, 7)      # Choose 7 elements
['Tu', 'Th', 'Mo', 'We', 'St', 'Fr', 'Sn']
>>> random.sample(days, 7)      # Choose 7 again
['We', 'Mo', 'Sn', 'Fr', 'Tu', 'St', 'Th']
>>> random.sample(days, 8)      # Can't choose eight
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "random.py", line 414, in sample
      raise ValueError, "sample larger than population"
ValueError: sample larger than population
>>> random.sample(xrange(1,10000,2), 10)   # Choose ten odd nos. under 10000
[3407, 3805, 1505, 7023, 2401, 2267, 9733, 3151, 8083, 9195]

The random module now uses a new algorithm, the Mersenne Twister, implemented in C. It’s faster and more extensively studied than the previous algorithm.

(All changes contributed by Raymond Hettinger.)

The readline module also gained a number of new functions: get_history_item(), get_current_history_length(), and redisplay().

The rexec and Bastion modules have been declared dead, and attempts to import them will fail with a RuntimeError. New-style classes provide new ways to break out of the restricted execution environment provided by rexec, and no one has interest in fixing them or time to do so. If you have applications using rexec, rewrite them to use something else.

(Sticking with Python 2.2 or 2.1 will not make your applications any safer because there are known bugs in the rexec module in those versions. To repeat: if you’re using rexec, stop using it immediately.)

The rotor module has been deprecated because the algorithm it uses for encryption is not believed to be secure. If you need encryption, use one of the several AES Python modules that are available separately.

The shutil module gained a move(src, dest) function that recursively moves a file or directory to a new location.

Support for more advanced POSIX signal handling was added to the signal but then removed again as it proved impossible to make it work reliably across platforms.

The socket module now supports timeouts. You can call the settimeout(t) method on a socket object to set a timeout of t seconds. Subsequent socket operations that take longer than t seconds to complete will abort and raise a socket.timeout exception.

The original timeout implementation was by Tim O’Malley. Michael Gilfix integrated it into the Python socket module and shepherded it through a lengthy review. After the code was checked in, Guido van Rossum rewrote parts of it. (This is a good example of a collaborative development process in action.)

On Windows, the socket module now ships with Secure Sockets Layer (SSL) support.

The value of the C PYTHON_API_VERSION macro is now exposed at the Python level as sys.api_version. The current exception can be cleared by calling the new sys.exc_clear() function.

The new tarfile module allows reading from and writing to tar-format archive files. (Contributed by Lars Gustäbel.)

The new textwrap module contains functions for wrapping strings containing paragraphs of text. The wrap(text, width) function takes a string and returns a list containing the text split into lines of no more than the chosen width. The fill(text, width) function returns a single string, reformatted to fit into lines no longer than the chosen width. (As you can guess, fill() is built on top of wrap(). For example:

>>> import textwrap
>>> paragraph = "Not a whit, we defy augury: ... more text ..."
>>> textwrap.wrap(paragraph, 60)
["Not a whit, we defy augury: there's a special providence in",
 "the fall of a sparrow. If it be now, 'tis not to come; if it",
 ...]
>>> print textwrap.fill(paragraph, 35)
Not a whit, we defy augury: there's
a special providence in the fall of
a sparrow. If it be now, 'tis not
to come; if it be not to come, it
will be now; if it be not now, yet
it will come: the readiness is all.
>>>

The module also contains a TextWrapper class that actually implements the text wrapping strategy. Both the TextWrapper class and the wrap() and fill() functions support a number of additional keyword arguments for fine-tuning the formatting; consult the module’s documentation for details. (Contributed by Greg Ward.)

The thread and threading modules now have companion modules, dummy_thread and dummy_threading, that provide a do-nothing implementation of the thread module’s interface for platforms where threads are not supported. The intention is to simplify thread-aware modules (ones that don’t rely on threads to run) by putting the following code at the top:

try:
    import threading as _threading
except ImportError:
    import dummy_threading as _threading

In this example, _threading is used as the module name to make it clear that the module being used is not necessarily the actual threading module. Code can call functions and use classes in _threading whether or not threads are supported, avoiding an if statement and making the code slightly clearer. This module will not magically make multithreaded code run without threads; code that waits for another thread to return or to do something will simply hang forever.

The time module’s strptime() function has long been an annoyance because it uses the platform C library’s strptime() implementation, and different platforms sometimes have odd bugs. Brett Cannon contributed a portable implementation that’s written in pure Python and should behave identically on all platforms.

The new timeit module helps measure how long snippets of Python code take to execute. The timeit.py file can be run directly from the command line, or the module’s Timer class can be imported and used directly. Here’s a short example that figures out whether it’s faster to convert an 8-bit string to Unicode by appending an empty Unicode string to it or by using the unicode() function:

import timeit

timer1 = timeit.Timer('unicode("abc")')
timer2 = timeit.Timer('"abc" + u""')

# Run three trials
print timer1.repeat(repeat=3, number=100000)
print timer2.repeat(repeat=3, number=100000)

# On my laptop this outputs:
# [0.36831796169281006, 0.37441694736480713, 0.35304892063140869]
# [0.17574405670166016, 0.18193507194519043, 0.17565798759460449]

The Tix module has received various bug fixes and updates for the current version of the Tix package.

The Tkinter module now works with a thread-enabled version of Tcl. Tcl’s threading model requires that widgets only be accessed from the thread in which they’re created; accesses from another thread can cause Tcl to panic. For certain Tcl interfaces, Tkinter will now automatically avoid this when a widget is accessed from a different thread by marshalling a command, passing it to the correct thread, and waiting for the results. Other interfaces can’t be handled automatically but Tkinter will now raise an exception on such an access so that you can at least find out about the problem. See https://mail.python.org/pipermail/python-dev/2002-December/031107.html for a more detailed explanation of this change. (Implemented by Martin von Löwis.)

Calling Tcl methods through _tkinter no longer returns only strings. Instead, if Tcl returns other objects those objects are converted to their Python equivalent, if one exists, or wrapped with a _tkinter.Tcl_Obj object if no Python equivalent exists. This behavior can be controlled through the wantobjects() method of tkapp objects.

When using _tkinter through the Tkinter module (as most Tkinter applications will), this feature is always activated. It should not cause compatibility problems, since Tkinter would always convert string results to Python types where possible.

If any incompatibilities are found, the old behavior can be restored by setting the wantobjects variable in the Tkinter module to false before creating the first tkapp object.

import Tkinter
Tkinter.wantobjects = 0

Any breakage caused by this change should be reported as a bug.

The UserDict module has a new DictMixin class which defines all dictionary methods for classes that already have a minimum mapping interface. This greatly simplifies writing classes that need to be substitutable for dictionaries, such as the classes in the shelve module.

Adding the mix-in as a superclass provides the full dictionary interface whenever the class defines __getitem__(), __setitem__(), __delitem__(), and keys(). For example:

>>> import UserDict
>>> class SeqDict(UserDict.DictMixin):
...     """Dictionary lookalike implemented with lists."""
...     def __init__(self):
...         self.keylist = []
...         self.valuelist = []
...     def __getitem__(self, key):
...         try:
...             i = self.keylist.index(key)
...         except ValueError:
...             raise KeyError
...         return self.valuelist[i]
...     def __setitem__(self, key, value):
...         try:
...             i = self.keylist.index(key)
...             self.valuelist[i] = value
...         except ValueError:
...             self.keylist.append(key)
...             self.valuelist.append(value)
...     def __delitem__(self, key):
...         try:
...             i = self.keylist.index(key)
...         except ValueError:
...             raise KeyError
...         self.keylist.pop(i)
...         self.valuelist.pop(i)
...     def keys(self):
...         return list(self.keylist)
...
>>> s = SeqDict()
>>> dir(s)      # See that other dictionary methods are implemented
['__cmp__', '__contains__', '__delitem__', '__doc__', '__getitem__',
 '__init__', '__iter__', '__len__', '__module__', '__repr__',
 '__setitem__', 'clear', 'get', 'has_key', 'items', 'iteritems',
 'iterkeys', 'itervalues', 'keylist', 'keys', 'pop', 'popitem',
 'setdefault', 'update', 'valuelist', 'values']

(Contributed by Raymond Hettinger.)

The DOM implementation in xml.dom.minidom can now generate XML output in a particular encoding by providing an optional encoding argument to the toxml() and toprettyxml() methods of DOM nodes.

The xmlrpclib module now supports an XML-RPC extension for handling nil data values such as Python’s None. Nil values are always supported on unmarshalling an XML-RPC response. To generate requests containing None, you must supply a true value for the allow_none parameter when creating a Marshaller instance.

The new DocXMLRPCServer module allows writing self-documenting XML-RPC servers. Run it in demo mode (as a program) to see it in action. Pointing the Web browser to the RPC server produces pydoc-style documentation; pointing xmlrpclib to the server allows invoking the actual methods. (Contributed by Brian Quinlan.)

Support for internationalized domain names (RFCs 3454, 3490, 3491, and 3492) has been added. The “idna” encoding can be used to convert between a Unicode domain name and the ASCII-compatible encoding (ACE) of that name.

>{}>{}> u"www.Alliancefrançaise.nu".encode("idna")
'www.xn--alliancefranaise-npb.nu'

The socket module has also been extended to transparently convert Unicode hostnames to the ACE version before passing them to the C library. Modules that deal with hostnames such as httplib and ftplib) also support Unicode host names; httplib also sends HTTP Host headers using the ACE version of the domain name. urllib supports Unicode URLs with non-ASCII host names as long as the path part of the URL is ASCII only.

To implement this change, the stringprep module, the mkstringprep tool and the punycode encoding have been added.

Date/Time Type

Date and time types suitable for expressing timestamps were added as the datetime module. The types don’t support different calendars or many fancy features, and just stick to the basics of representing time.

The three primary types are: date, representing a day, month, and year; time, consisting of hour, minute, and second; and datetime, which contains all the attributes of both date and time. There’s also a timedelta class representing differences between two points in time, and time zone logic is implemented by classes inheriting from the abstract tzinfo class.

You can create instances of date and time by either supplying keyword arguments to the appropriate constructor, e.g. datetime.date(year=1972, month=10, day=15), or by using one of a number of class methods. For example, the date.today() class method returns the current local date.

Once created, instances of the date/time classes are all immutable. There are a number of methods for producing formatted strings from objects:

>>> import datetime
>>> now = datetime.datetime.now()
>>> now.isoformat()
'2002-12-30T21:27:03.994956'
>>> now.ctime()  # Only available on date, datetime
'Mon Dec 30 21:27:03 2002'
>>> now.strftime('%Y %d %b')
'2002 30 Dec'

The replace() method allows modifying one or more fields of a date or datetime instance, returning a new instance:

>>> d = datetime.datetime.now()
>>> d
datetime.datetime(2002, 12, 30, 22, 15, 38, 827738)
>>> d.replace(year=2001, hour = 12)
datetime.datetime(2001, 12, 30, 12, 15, 38, 827738)
>>>

Instances can be compared, hashed, and converted to strings (the result is the same as that of isoformat()). date and datetime instances can be subtracted from each other, and added to timedelta instances. The largest missing feature is that there’s no standard library support for parsing strings and getting back a date or datetime.

For more information, refer to the module’s reference documentation. (Contributed by Tim Peters.)

The optparse Module

The getopt module provides simple parsing of command-line arguments. The new optparse module (originally named Optik) provides more elaborate command-line parsing that follows the Unix conventions, automatically creates the output for --help, and can perform different actions for different options.

You start by creating an instance of OptionParser and telling it what your program’s options are.

import sys
from optparse import OptionParser

op = OptionParser()
op.add_option('-i', '--input',
              action='store', type='string', dest='input',
              help='set input filename')
op.add_option('-l', '--length',
              action='store', type='int', dest='length',
              help='set maximum length of output')

Parsing a command line is then done by calling the parse_args() method.

options, args = op.parse_args(sys.argv[1:])
print options
print args

This returns an object containing all of the option values, and a list of strings containing the remaining arguments.

Invoking the script with the various arguments now works as you’d expect it to. Note that the length argument is automatically converted to an integer.

$ ./python opt.py -i data arg1
<Values at 0x400cad4c: {'input': 'data', 'length': None}>
['arg1']
$ ./python opt.py --input=data --length=4
<Values at 0x400cad2c: {'input': 'data', 'length': 4}>
[]
$

The help message is automatically generated for you:

$ ./python opt.py --help
usage: opt.py [options]

options:
  -h, --help            show this help message and exit
  -iINPUT, --input=INPUT
                        set input filename
  -lLENGTH, --length=LENGTH
                        set maximum length of output
$

See the module’s documentation for more details.

Optik was written by Greg Ward, with suggestions from the readers of the Getopt SIG.

Pymalloc: A Specialized Object Allocator

Pymalloc, a specialized object allocator written by Vladimir Marangozov, was a feature added to Python 2.1. Pymalloc is intended to be faster than the system malloc() and to have less memory overhead for allocation patterns typical of Python programs. The allocator uses C’s malloc() function to get large pools of memory and then fulfills smaller memory requests from these pools.

In 2.1 and 2.2, pymalloc was an experimental feature and wasn’t enabled by default; you had to explicitly enable it when compiling Python by providing the --with-pymalloc option to the configure script. In 2.3, pymalloc has had further enhancements and is now enabled by default; you’ll have to supply --without-pymalloc to disable it.

This change is transparent to code written in Python; however, pymalloc may expose bugs in C extensions. Authors of C extension modules should test their code with pymalloc enabled, because some incorrect code may cause core dumps at runtime.

There’s one particularly common error that causes problems. There are a number of memory allocation functions in Python’s C API that have previously just been aliases for the C library’s malloc() and free(), meaning that if you accidentally called mismatched functions the error wouldn’t be noticeable. When the object allocator is enabled, these functions aren’t aliases of malloc() and free() any more, and calling the wrong function to free memory may get you a core dump. For example, if memory was allocated using PyObject_Malloc(), it has to be freed using PyObject_Free(), not free(). A few modules included with Python fell afoul of this and had to be fixed; doubtless there are more third-party modules that will have the same problem.

As part of this change, the confusing multiple interfaces for allocating memory have been consolidated down into two API families. Memory allocated with one family must not be manipulated with functions from the other family. There is one family for allocating chunks of memory and another family of functions specifically for allocating Python objects.

To allocate and free an undistinguished chunk of memory use the “raw memory” family: PyMem_Malloc(), PyMem_Realloc(), and PyMem_Free().

The “object memory” family is the interface to the pymalloc facility described above and is biased towards a large number of “small” allocations: PyObject_Malloc(), PyObject_Realloc(), and PyObject_Free().

To allocate and free Python objects, use the “object” family PyObject_New(), PyObject_NewVar(), and PyObject_Del().

Thanks to lots of work by Tim Peters, pymalloc in 2.3 also provides debugging features to catch memory overwrites and doubled frees in both extension modules and in the interpreter itself. To enable this support, compile a debugging version of the Python interpreter by running configure with --with-pydebug.

To aid extension writers, a header file Misc/pymemcompat.h is distributed with the source to Python 2.3 that allows Python extensions to use the 2.3 interfaces to memory allocation while compiling against any version of Python since 1.5.2. You would copy the file from Python’s source distribution and bundle it with the source of your extension.

더 보기

https://hg.python.org/cpython/file/default/Objects/obmalloc.c

For the full details of the pymalloc implementation, see the comments at the top of the file Objects/obmalloc.c in the Python source code. The above link points to the file within the python.org SVN browser.

Build and C API Changes

Changes to Python’s build process and to the C API include:

The cycle detection implementation used by the garbage collection has proven to be stable, so it’s now been made mandatory. You can no longer compile Python without it, and the --with-cycle-gc switch to configure has been removed.

Python can now optionally be built as a shared library (libpython2.3.so) by supplying --enable-shared when running Python’s configure script. (Contributed by Ondrej Palkovsky.)

The DL_EXPORT and DL_IMPORT macros are now deprecated. Initialization functions for Python extension modules should now be declared using the new macro PyMODINIT_FUNC, while the Python core will generally use the PyAPI_FUNC and PyAPI_DATA macros.

The interpreter can be compiled without any docstrings for the built-in functions and modules by supplying --without-doc-strings to the configure script. This makes the Python executable about 10% smaller, but will also mean that you can’t get help for Python’s built-ins. (Contributed by Gustavo Niemeyer.)

The PyArg_NoArgs() macro is now deprecated, and code that uses it should be changed. For Python 2.2 and later, the method definition table can specify the METH_NOARGS flag, signalling that there are no arguments, and the argument checking can then be removed. If compatibility with pre-2.2 versions of Python is important, the code could use PyArg_ParseTuple(args, "") instead, but this will be slower than using METH_NOARGS.

PyArg_ParseTuple() accepts new format characters for various sizes of unsigned integers: B for unsigned char, H for unsigned short int, I for unsigned int, and K for unsigned long long.

A new function, PyObject_DelItemString(mapping, char *key) was added as shorthand for PyObject_DelItem(mapping, PyString_New(key)).

File objects now manage their internal string buffer differently, increasing it exponentially when needed. This results in the benchmark tests in Lib/test/test_bufio.py speeding up considerably (from 57 seconds to 1.7 seconds, according to one measurement).

It’s now possible to define class and static methods for a C extension type by setting either the METH_CLASS or METH_STATIC flags in a method’s PyMethodDef structure.

Python now includes a copy of the Expat XML parser’s source code, removing any dependence on a system version or local installation of Expat.

If you dynamically allocate type objects in your extension, you should be aware of a change in the rules relating to the __module__ and __name__ attributes. In summary, you will want to ensure the type’s dictionary contains a '__module__' key; making the module name the part of the type name leading up to the final period will no longer have the desired effect. For more detail, read the API reference documentation or the source.

Port-Specific Changes

Support for a port to IBM’s OS/2 using the EMX runtime environment was merged into the main Python source tree. EMX is a POSIX emulation layer over the OS/2 system APIs. The Python port for EMX tries to support all the POSIX-like capability exposed by the EMX runtime, and mostly succeeds; fork() and fcntl() are restricted by the limitations of the underlying emulation layer. The standard OS/2 port, which uses IBM’s Visual Age compiler, also gained support for case-sensitive import semantics as part of the integration of the EMX port into CVS. (Contributed by Andrew MacIntyre.)

On MacOS, most toolbox modules have been weaklinked to improve backward compatibility. This means that modules will no longer fail to load if a single routine is missing on the current OS version. Instead calling the missing routine will raise an exception. (Contributed by Jack Jansen.)

The RPM spec files, found in the Misc/RPM/ directory in the Python source distribution, were updated for 2.3. (Contributed by Sean Reifschneider.)

Other new platforms now supported by Python include AtheOS (http://www.atheos.cx/), GNU/Hurd, and OpenVMS.

Other Changes and Fixes

As usual, there were a bunch of other improvements and bugfixes scattered throughout the source tree. A search through the CVS change logs finds there were 523 patches applied and 514 bugs fixed between Python 2.2 and 2.3. Both figures are likely to be underestimates.

Some of the more notable changes are:

If the PYTHONINSPECT environment variable is set, the Python interpreter will enter the interactive prompt after running a Python program, as if Python had been invoked with the -i option. The environment variable can be set before running the Python interpreter, or it can be set by the Python program as part of its execution.

The regrtest.py script now provides a way to allow “all resources except foo.” A resource name passed to the -u option can now be prefixed with a hyphen ('-') to mean “remove this resource.” For example, the option ‘-uall,-bsddb’ could be used to enable the use of all resources except bsddb.

The tools used to build the documentation now work under Cygwin as well as Unix.

The SET_LINENO opcode has been removed. Back in the mists of time, this opcode was needed to produce line numbers in tracebacks and support trace functions (for, e.g., pdb). Since Python 1.5, the line numbers in tracebacks have been computed using a different mechanism that works with “python -O”. For Python 2.3 Michael Hudson implemented a similar scheme to determine when to call the trace function, removing the need for SET_LINENO entirely.

It would be difficult to detect any resulting difference from Python code, apart from a slight speed up when Python is run without -O.

C extensions that access the f_lineno field of frame objects should instead call PyCode_Addr2Line(f->f_code, f->f_lasti). This will have the added effect of making the code work as desired under “python -O” in earlier versions of Python.

A nifty new feature is that trace functions can now assign to the f_lineno attribute of frame objects, changing the line that will be executed next. A jump command has been added to the pdb debugger taking advantage of this new feature. (Implemented by Richie Hindle.)

Porting to Python 2.3

This section lists previously described changes that may require changes to your code:

yield is now always a keyword; if it’s used as a variable name in your code, a different name must be chosen.

For strings X and Y, X in Y now works if X is more than one character long.

The int() type constructor will now return a long integer instead of raising an OverflowError when a string or floating-point number is too large to fit into an integer.

If you have Unicode strings that contain 8-bit characters, you must declare the file’s encoding (UTF-8, Latin-1, or whatever) by adding a comment to the top of the file. See section PEP 263: Source Code Encodings for more information.

Calling Tcl methods through _tkinter no longer returns only strings. Instead, if Tcl returns other objects those objects are converted to their Python equivalent, if one exists, or wrapped with a _tkinter.Tcl_Obj object if no Python equivalent exists.

Large octal and hex literals such as 0xffffffff now trigger a FutureWarning. Currently they’re stored as 32-bit numbers and result in a negative value, but in Python 2.4 they’ll become positive long integers.

There are a few ways to fix this warning. If you really need a positive number, just add an L to the end of the literal. If you’re trying to get a 32-bit integer with low bits set and have previously used an expression such as ~(1 << 31), it’s probably clearest to start with all bits set and clear the desired upper bits. For example, to clear just the top bit (bit 31), you could write 0xffffffffL &~(1L<<31).

You can no longer disable assertions by assigning to __debug__.

The Distutils setup() function has gained various new keyword arguments such as depends. Old versions of the Distutils will abort if passed unknown keywords. A solution is to check for the presence of the new get_distutil_options() function in your setup.py and only uses the new keywords with a version of the Distutils that supports them:

from distutils import core

kw = {'sources': 'foo.c', ...}
if hasattr(core, 'get_distutil_options'):
    kw['depends'] = ['foo.h']
ext = Extension(**kw)

Using None as a variable name will now result in a SyntaxWarning warning.

Names of extension types defined by the modules included with Python now contain the module and a '.' in front of the type name.

Acknowledgements

The author would like to thank the following people for offering suggestions, corrections and assistance with various drafts of this article: Jeff Bauer, Simon Brunning, Brett Cannon, Michael Chermside, Andrew Dalke, Scott David Daniels, Fred L. Drake, Jr., David Fraser, Kelly Gerber, Raymond Hettinger, Michael Hudson, Chris Lambert, Detlef Lannert, Martin von Löwis, Andrew MacIntyre, Lalo Martins, Chad Netzer, Gustavo Niemeyer, Neal Norwitz, Hans Nowak, Chris Reedy, Francesco Ricciardi, Vinay Sajip, Neil Schemenauer, Roman Suzi, Jason Tishler, Just van Rossum.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬의 새로운 기능 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬의 새로운 기능 »

|

What’s New in Python 2.2

Author

A.M. Kuchling

Introduction

This article explains the new features in Python 2.2.2, released on October 14, 2002. Python 2.2.2 is a bugfix release of Python 2.2, originally released on December 21, 2001.

Python 2.2 can be thought of as the “cleanup release”. There are some features such as generators and iterators that are completely new, but most of the changes, significant and far-reaching though they may be, are aimed at cleaning up irregularities and dark corners of the language design.

This article doesn’t attempt to provide a complete specification of the new features, but instead provides a convenient overview. For full details, you should refer to the documentation for Python 2.2, such as the Python Library Reference [https://docs.python.org/2.2/lib/lib.html] and the Python Reference Manual [https://docs.python.org/2.2/ref/ref.html]. If you want to understand the complete implementation and design rationale for a change, refer to the PEP for a particular new feature.

PEPs 252 and 253: Type and Class Changes

The largest and most far-reaching changes in Python 2.2 are to Python’s model of objects and classes. The changes should be backward compatible, so it’s likely that your code will continue to run unchanged, but the changes provide some amazing new capabilities. Before beginning this, the longest and most complicated section of this article, I’ll provide an overview of the changes and offer some comments.

A long time ago I wrote a Web page listing flaws in Python’s design. One of the most significant flaws was that it’s impossible to subclass Python types implemented in C. In particular, it’s not possible to subclass built-in types, so you can’t just subclass, say, lists in order to add a single useful method to them. The UserList module provides a class that supports all of the methods of lists and that can be subclassed further, but there’s lots of C code that expects a regular Python list and won’t accept a UserList instance.

Python 2.2 fixes this, and in the process adds some exciting new capabilities. A brief summary:

You can subclass built-in types such as lists and even integers, and your subclasses should work in every place that requires the original type.

It’s now possible to define static and class methods, in addition to the instance methods available in previous versions of Python.

It’s also possible to automatically call methods on accessing or setting an instance attribute by using a new mechanism called properties. Many uses of __getattr__() can be rewritten to use properties instead, making the resulting code simpler and faster. As a small side benefit, attributes can now have docstrings, too.

The list of legal attributes for an instance can be limited to a particular set using slots, making it possible to safeguard against typos and perhaps make more optimizations possible in future versions of Python.

Some users have voiced concern about all these changes. Sure, they say, the new features are neat and lend themselves to all sorts of tricks that weren’t possible in previous versions of Python, but they also make the language more complicated. Some people have said that they’ve always recommended Python for its simplicity, and feel that its simplicity is being lost.

Personally, I think there’s no need to worry. Many of the new features are quite esoteric, and you can write a lot of Python code without ever needed to be aware of them. Writing a simple class is no more difficult than it ever was, so you don’t need to bother learning or teaching them unless they’re actually needed. Some very complicated tasks that were previously only possible from C will now be possible in pure Python, and to my mind that’s all for the better.

I’m not going to attempt to cover every single corner case and small change that were required to make the new features work. Instead this section will paint only the broad strokes. See section Related Links, “Related Links”, for further sources of information about Python 2.2’s new object model.

Old and New Classes

First, you should know that Python 2.2 really has two kinds of classes: classic or old-style classes, and new-style classes. The old-style class model is exactly the same as the class model in earlier versions of Python. All the new features described in this section apply only to new-style classes. This divergence isn’t intended to last forever; eventually old-style classes will be dropped, possibly in Python 3.0.

So how do you define a new-style class? You do it by subclassing an existing new-style class. Most of Python’s built-in types, such as integers, lists, dictionaries, and even files, are new-style classes now. A new-style class named object, the base class for all built-in types, has also been added so if no built-in type is suitable, you can just subclass object:

class C(object):
    def __init__ (self):
        ...
    ...

This means that class statements that don’t have any base classes are always classic classes in Python 2.2. (Actually you can also change this by setting a module-level variable named __metaclass__ — see PEP 253 [https://www.python.org/dev/peps/pep-0253] for the details — but it’s easier to just subclass object.)

The type objects for the built-in types are available as built-ins, named using a clever trick. Python has always had built-in functions named int(), float(), and str(). In 2.2, they aren’t functions any more, but type objects that behave as factories when called.

>>> int
<type 'int'>
>>> int('123')
123

To make the set of types complete, new type objects such as dict() and file() have been added. Here’s a more interesting example, adding a lock() method to file objects:

class LockableFile(file):
    def lock (self, operation, length=0, start=0, whence=0):
        import fcntl
        return fcntl.lockf(self.fileno(), operation,
                           length, start, whence)

The now-obsolete posixfile module contained a class that emulated all of a file object’s methods and also added a lock() method, but this class couldn’t be passed to internal functions that expected a built-in file, something which is possible with our new LockableFile.

Descriptors

In previous versions of Python, there was no consistent way to discover what attributes and methods were supported by an object. There were some informal conventions, such as defining __members__ and __methods__ attributes that were lists of names, but often the author of an extension type or a class wouldn’t bother to define them. You could fall back on inspecting the __dict__ of an object, but when class inheritance or an arbitrary __getattr__() hook were in use this could still be inaccurate.

The one big idea underlying the new class model is that an API for describing the attributes of an object using descriptors has been formalized. Descriptors specify the value of an attribute, stating whether it’s a method or a field. With the descriptor API, static methods and class methods become possible, as well as more exotic constructs.

Attribute descriptors are objects that live inside class objects, and have a few attributes of their own:

__name__ is the attribute’s name.

__doc__ is the attribute’s docstring.

__get__(object) is a method that retrieves the attribute value from object.

__set__(object, value) sets the attribute on object to value.

__delete__(object, value) deletes the value attribute of object.

For example, when you write obj.x, the steps that Python actually performs are:

descriptor = obj.__class__.x
descriptor.__get__(obj)

For methods, descriptor.__get__() returns a temporary object that’s callable, and wraps up the instance and the method to be called on it. This is also why static methods and class methods are now possible; they have descriptors that wrap up just the method, or the method and the class. As a brief explanation of these new kinds of methods, static methods aren’t passed the instance, and therefore resemble regular functions. Class methods are passed the class of the object, but not the object itself. Static and class methods are defined like this:

class C(object):
    def f(arg1, arg2):
        ...
    f = staticmethod(f)

    def g(cls, arg1, arg2):
        ...
    g = classmethod(g)

The staticmethod() function takes the function f(), and returns it wrapped up in a descriptor so it can be stored in the class object. You might expect there to be special syntax for creating such methods (def static f, defstatic f(), or something like that) but no such syntax has been defined yet; that’s been left for future versions of Python.

More new features, such as slots and properties, are also implemented as new kinds of descriptors, and it’s not difficult to write a descriptor class that does something novel. For example, it would be possible to write a descriptor class that made it possible to write Eiffel-style preconditions and postconditions for a method. A class that used this feature might be defined like this:

from eiffel import eiffelmethod

class C(object):
    def f(self, arg1, arg2):
        # The actual function
        ...
    def pre_f(self):
        # Check preconditions
        ...
    def post_f(self):
        # Check postconditions
        ...

    f = eiffelmethod(f, pre_f, post_f)

Note that a person using the new eiffelmethod() doesn’t have to understand anything about descriptors. This is why I think the new features don’t increase the basic complexity of the language. There will be a few wizards who need to know about it in order to write eiffelmethod() or the ZODB or whatever, but most users will just write code on top of the resulting libraries and ignore the implementation details.

Multiple Inheritance: The Diamond Rule

Multiple inheritance has also been made more useful through changing the rules under which names are resolved. Consider this set of classes (diagram taken from PEP 253 [https://www.python.org/dev/peps/pep-0253] by Guido van Rossum):

      class A:
        ^ ^  def save(self): ...
       /   \
      /     \
     /       \
    /         \
class B     class C:
    ^         ^  def save(self): ...
     \       /
      \     /
       \   /
        \ /
      class D

The lookup rule for classic classes is simple but not very smart; the base classes are searched depth-first, going from left to right. A reference to D.save() will search the classes D, B, and then A, where save() would be found and returned. C.save() would never be found at all. This is bad, because if C’s save() method is saving some internal state specific to C, not calling it will result in that state never getting saved.

New-style classes follow a different algorithm that’s a bit more complicated to explain, but does the right thing in this situation. (Note that Python 2.3 changes this algorithm to one that produces the same results in most cases, but produces more useful results for really complicated inheritance graphs.)

List all the base classes, following the classic lookup rule and include a class multiple times if it’s visited repeatedly. In the above example, the list of visited classes is [D, B, A, C, A].

Scan the list for duplicated classes. If any are found, remove all but one occurrence, leaving the last one in the list. In the above example, the list becomes [D, B, C, A] after dropping duplicates.

Following this rule, referring to D.save() will return C.save(), which is the behaviour we’re after. This lookup rule is the same as the one followed by Common Lisp. A new built-in function, super(), provides a way to get at a class’s superclasses without having to reimplement Python’s algorithm. The most commonly used form will be super(class, obj), which returns a bound superclass object (not the actual class object). This form will be used in methods to call a method in the superclass; for example, D’s save() method would look like this:

class D (B,C):
    def save (self):
        # Call superclass .save()
        super(D, self).save()
        # Save D's private information here
        ...

super() can also return unbound superclass objects when called as super(class) or super(class1, class2), but this probably won’t often be useful.

Attribute Access

A fair number of sophisticated Python classes define hooks for attribute access using __getattr__(); most commonly this is done for convenience, to make code more readable by automatically mapping an attribute access such as obj.parent into a method call such as obj.get_parent. Python 2.2 adds some new ways of controlling attribute access.

First, __getattr__(attr_name) is still supported by new-style classes, and nothing about it has changed. As before, it will be called when an attempt is made to access obj.foo and no attribute named foo is found in the instance’s dictionary.

New-style classes also support a new method, __getattribute__(attr_name). The difference between the two methods is that __getattribute__() is always called whenever any attribute is accessed, while the old __getattr__() is only called if foo isn’t found in the instance’s dictionary.

However, Python 2.2’s support for properties will often be a simpler way to trap attribute references. Writing a __getattr__() method is complicated because to avoid recursion you can’t use regular attribute accesses inside them, and instead have to mess around with the contents of __dict__. __getattr__() methods also end up being called by Python when it checks for other methods such as __repr__() or __coerce__(), and so have to be written with this in mind. Finally, calling a function on every attribute access results in a sizable performance loss.

property is a new built-in type that packages up three functions that get, set, or delete an attribute, and a docstring. For example, if you want to define a size attribute that’s computed, but also settable, you could write:

class C(object):
    def get_size (self):
        result = ... computation ...
        return result
    def set_size (self, size):
        ... compute something based on the size
        and set internal state appropriately ...

    # Define a property.  The 'delete this attribute'
    # method is defined as None, so the attribute
    # can't be deleted.
    size = property(get_size, set_size,
                    None,
                    "Storage size of this instance")

That is certainly clearer and easier to write than a pair of __getattr__()/__setattr__() methods that check for the size attribute and handle it specially while retrieving all other attributes from the instance’s __dict__. Accesses to size are also the only ones which have to perform the work of calling a function, so references to other attributes run at their usual speed.

Finally, it’s possible to constrain the list of attributes that can be referenced on an object using the new __slots__ class attribute. Python objects are usually very dynamic; at any time it’s possible to define a new attribute on an instance by just doing obj.new_attr=1. A new-style class can define a class attribute named __slots__ to limit the legal attributes to a particular set of names. An example will make this clear:

>>> class C(object):
...     __slots__ = ('template', 'name')
...
>>> obj = C()
>>> print obj.template
None
>>> obj.template = 'Test'
>>> print obj.template
Test
>>> obj.newattr = None
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AttributeError: 'C' object has no attribute 'newattr'

Note how you get an AttributeError on the attempt to assign to an attribute not listed in __slots__.

Related Links

This section has just been a quick overview of the new features, giving enough of an explanation to start you programming, but many details have been simplified or ignored. Where should you go to get a more complete picture?

https://docs.python.org/dev/howto/descriptor.html is a lengthy tutorial introduction to the descriptor features, written by Guido van Rossum. If my description has whetted your appetite, go read this tutorial next, because it goes into much more detail about the new features while still remaining quite easy to read.

Next, there are two relevant PEPs, PEP 252 [https://www.python.org/dev/peps/pep-0252] and PEP 253 [https://www.python.org/dev/peps/pep-0253]. PEP 252 [https://www.python.org/dev/peps/pep-0252] is titled “Making Types Look More Like Classes”, and covers the descriptor API. PEP 253 [https://www.python.org/dev/peps/pep-0253] is titled “Subtyping Built-in Types”, and describes the changes to type objects that make it possible to subtype built-in objects. PEP 253 [https://www.python.org/dev/peps/pep-0253] is the more complicated PEP of the two, and at a few points the necessary explanations of types and meta-types may cause your head to explode. Both PEPs were written and implemented by Guido van Rossum, with substantial assistance from the rest of the Zope Corp. team.

Finally, there’s the ultimate authority: the source code. Most of the machinery for the type handling is in Objects/typeobject.c, but you should only resort to it after all other avenues have been exhausted, including posting a question to python-list or python-dev.

PEP 234: Iterators

Another significant addition to 2.2 is an iteration interface at both the C and Python levels. Objects can define how they can be looped over by callers.

In Python versions up to 2.1, the usual way to make for item in obj work is to define a __getitem__() method that looks something like this:

def __getitem__(self, index):
    return <next item>

__getitem__() is more properly used to define an indexing operation on an object so that you can write obj[5] to retrieve the sixth element. It’s a bit misleading when you’re using this only to support for loops. Consider some file-like object that wants to be looped over; the index parameter is essentially meaningless, as the class probably assumes that a series of __getitem__() calls will be made with index incrementing by one each time. In other words, the presence of the __getitem__() method doesn’t mean that using file[5] to randomly access the sixth element will work, though it really should.

In Python 2.2, iteration can be implemented separately, and __getitem__() methods can be limited to classes that really do support random access. The basic idea of iterators is simple. A new built-in function, iter(obj) or iter(C, sentinel), is used to get an iterator. iter(obj) returns an iterator for the object obj, while iter(C, sentinel) returns an iterator that will invoke the callable object C until it returns sentinel to signal that the iterator is done.

Python classes can define an __iter__() method, which should create and return a new iterator for the object; if the object is its own iterator, this method can just return self. In particular, iterators will usually be their own iterators. Extension types implemented in C can implement a tp_iter function in order to return an iterator, and extension types that want to behave as iterators can define a tp_iternext function.

So, after all this, what do iterators actually do? They have one required method, next(), which takes no arguments and returns the next value. When there are no more values to be returned, calling next() should raise the StopIteration exception.

>>> L = [1,2,3]
>>> i = iter(L)
>>> print i
<iterator object at 0x8116870>
>>> i.next()
1
>>> i.next()
2
>>> i.next()
3
>>> i.next()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
StopIteration
>>>

In 2.2, Python’s for statement no longer expects a sequence; it expects something for which iter() will return an iterator. For backward compatibility and convenience, an iterator is automatically constructed for sequences that don’t implement __iter__() or a tp_iter slot, so for i in [1,2,3] will still work. Wherever the Python interpreter loops over a sequence, it’s been changed to use the iterator protocol. This means you can do things like this:

>>> L = [1,2,3]
>>> i = iter(L)
>>> a,b,c = i
>>> a,b,c
(1, 2, 3)

Iterator support has been added to some of Python’s basic types. Calling iter() on a dictionary will return an iterator which loops over its keys:

>>> m = {'Jan': 1, 'Feb': 2, 'Mar': 3, 'Apr': 4, 'May': 5, 'Jun': 6,
...      'Jul': 7, 'Aug': 8, 'Sep': 9, 'Oct': 10, 'Nov': 11, 'Dec': 12}
>>> for key in m: print key, m[key]
...
Mar 3
Feb 2
Aug 8
Sep 9
May 5
Jun 6
Jul 7
Jan 1
Apr 4
Nov 11
Dec 12
Oct 10

That’s just the default behaviour. If you want to iterate over keys, values, or key/value pairs, you can explicitly call the iterkeys(), itervalues(), or iteritems() methods to get an appropriate iterator. In a minor related change, the in operator now works on dictionaries, so key in dict is now equivalent to dict.has_key(key).

Files also provide an iterator, which calls the readline() method until there are no more lines in the file. This means you can now read each line of a file using code like this:

for line in file:
    # do something for each line
    ...

Note that you can only go forward in an iterator; there’s no way to get the previous element, reset the iterator, or make a copy of it. An iterator object could provide such additional capabilities, but the iterator protocol only requires a next() method.

더 보기

PEP 234 [https://www.python.org/dev/peps/pep-0234] - Iterators

Written by Ka-Ping Yee and GvR; implemented by the Python Labs crew, mostly by GvR and Tim Peters.

PEP 255: Simple Generators

Generators are another new feature, one that interacts with the introduction of iterators.

You’re doubtless familiar with how function calls work in Python or C. When you call a function, it gets a private namespace where its local variables are created. When the function reaches a return statement, the local variables are destroyed and the resulting value is returned to the caller. A later call to the same function will get a fresh new set of local variables. But, what if the local variables weren’t thrown away on exiting a function? What if you could later resume the function where it left off? This is what generators provide; they can be thought of as resumable functions.

Here’s the simplest example of a generator function:

def generate_ints(N):
    for i in range(N):
        yield i

A new keyword, yield, was introduced for generators. Any function containing a yield statement is a generator function; this is detected by Python’s bytecode compiler which compiles the function specially as a result. Because a new keyword was introduced, generators must be explicitly enabled in a module by including a from __future__ import generators statement near the top of the module’s source code. In Python 2.3 this statement will become unnecessary.

When you call a generator function, it doesn’t return a single value; instead it returns a generator object that supports the iterator protocol. On executing the yield statement, the generator outputs the value of i, similar to a return statement. The big difference between yield and a return statement is that on reaching a yield the generator’s state of execution is suspended and local variables are preserved. On the next call to the generator’s next() method, the function will resume executing immediately after the yield statement. (For complicated reasons, the yield statement isn’t allowed inside the try block of a try…finally statement; read PEP 255 [https://www.python.org/dev/peps/pep-0255] for a full explanation of the interaction between yield and exceptions.)

Here’s a sample usage of the generate_ints() generator:

>>> gen = generate_ints(3)
>>> gen
<generator object at 0x8117f90>
>>> gen.next()
0
>>> gen.next()
1
>>> gen.next()
2
>>> gen.next()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 2, in generate_ints
StopIteration

You could equally write for i in generate_ints(5), or a,b,c = generate_ints(3).

Inside a generator function, the return statement can only be used without a value, and signals the end of the procession of values; afterwards the generator cannot return any further values. return with a value, such as return 5, is a syntax error inside a generator function. The end of the generator’s results can also be indicated by raising StopIteration manually, or by just letting the flow of execution fall off the bottom of the function.

You could achieve the effect of generators manually by writing your own class and storing all the local variables of the generator as instance variables. For example, returning a list of integers could be done by setting self.count to 0, and having the next() method increment self.count and return it. However, for a moderately complicated generator, writing a corresponding class would be much messier. Lib/test/test_generators.py contains a number of more interesting examples. The simplest one implements an in-order traversal of a tree using generators recursively.

# A recursive generator that generates Tree leaves in in-order.
def inorder(t):
    if t:
        for x in inorder(t.left):
            yield x
        yield t.label
        for x in inorder(t.right):
            yield x

Two other examples in Lib/test/test_generators.py produce solutions for the N-Queens problem (placing $N$ queens on an $NxN$ chess board so that no queen threatens another) and the Knight’s Tour (a route that takes a knight to every square of an $NxN$ chessboard without visiting any square twice).

The idea of generators comes from other programming languages, especially Icon (https://www.cs.arizona.edu/icon/), where the idea of generators is central. In Icon, every expression and function call behaves like a generator. One example from “An Overview of the Icon Programming Language” at https://www.cs.arizona.edu/icon/docs/ipd266.htm gives an idea of what this looks like:

sentence := "Store it in the neighboring harbor"
if (i := find("or", sentence)) > 5 then write(i)

In Icon the find() function returns the indexes at which the substring “or” is found: 3, 23, 33. In the if statement, i is first assigned a value of 3, but 3 is less than 5, so the comparison fails, and Icon retries it with the second value of 23. 23 is greater than 5, so the comparison now succeeds, and the code prints the value 23 to the screen.

Python doesn’t go nearly as far as Icon in adopting generators as a central concept. Generators are considered a new part of the core Python language, but learning or using them isn’t compulsory; if they don’t solve any problems that you have, feel free to ignore them. One novel feature of Python’s interface as compared to Icon’s is that a generator’s state is represented as a concrete object (the iterator) that can be passed around to other functions or stored in a data structure.

더 보기

PEP 255 [https://www.python.org/dev/peps/pep-0255] - Simple Generators

Written by Neil Schemenauer, Tim Peters, Magnus Lie Hetland. Implemented mostly by Neil Schemenauer and Tim Peters, with other fixes from the Python Labs crew.

PEP 237: Unifying Long Integers and Integers

In recent versions, the distinction between regular integers, which are 32-bit values on most machines, and long integers, which can be of arbitrary size, was becoming an annoyance. For example, on platforms that support files larger than 2**32 bytes, the tell() method of file objects has to return a long integer. However, there were various bits of Python that expected plain integers and would raise an error if a long integer was provided instead. For example, in Python 1.5, only regular integers could be used as a slice index, and 'abc'[1L:] would raise a TypeError exception with the message ‘slice index must be int’.

Python 2.2 will shift values from short to long integers as required. The ‘L’ suffix is no longer needed to indicate a long integer literal, as now the compiler will choose the appropriate type. (Using the ‘L’ suffix will be discouraged in future 2.x versions of Python, triggering a warning in Python 2.4, and probably dropped in Python 3.0.) Many operations that used to raise an OverflowError will now return a long integer as their result. For example:

>>> 1234567890123
1234567890123L
>>> 2 ** 64
18446744073709551616L

In most cases, integers and long integers will now be treated identically. You can still distinguish them with the type() built-in function, but that’s rarely needed.

더 보기

PEP 237 [https://www.python.org/dev/peps/pep-0237] - Unifying Long Integers and Integers

Written by Moshe Zadka and Guido van Rossum. Implemented mostly by Guido van Rossum.

PEP 238: Changing the Division Operator

The most controversial change in Python 2.2 heralds the start of an effort to fix an old design flaw that’s been in Python from the beginning. Currently Python’s division operator, /, behaves like C’s division operator when presented with two integer arguments: it returns an integer result that’s truncated down when there would be a fractional part. For example, 3/2 is 1, not 1.5, and (-1)/2 is -1, not -0.5. This means that the results of division can vary unexpectedly depending on the type of the two operands and because Python is dynamically typed, it can be difficult to determine the possible types of the operands.

(The controversy is over whether this is really a design flaw, and whether it’s worth breaking existing code to fix this. It’s caused endless discussions on python-dev, and in July 2001 erupted into a storm of acidly sarcastic postings on comp.lang.python. I won’t argue for either side here and will stick to describing what’s implemented in 2.2. Read PEP 238 [https://www.python.org/dev/peps/pep-0238] for a summary of arguments and counter-arguments.)

Because this change might break code, it’s being introduced very gradually. Python 2.2 begins the transition, but the switch won’t be complete until Python 3.0.

First, I’ll borrow some terminology from PEP 238 [https://www.python.org/dev/peps/pep-0238]. “True division” is the division that most non-programmers are familiar with: 3/2 is 1.5, 1/4 is 0.25, and so forth. “Floor division” is what Python’s / operator currently does when given integer operands; the result is the floor of the value returned by true division. “Classic division” is the current mixed behaviour of /; it returns the result of floor division when the operands are integers, and returns the result of true division when one of the operands is a floating-point number.

Here are the changes 2.2 introduces:

A new operator, //, is the floor division operator. (Yes, we know it looks like C++’s comment symbol.) // always performs floor division no matter what the types of its operands are, so 1 // 2 is 0 and 1.0 // 2.0 is also 0.0.

// is always available in Python 2.2; you don’t need to enable it using a __future__ statement.

By including a from __future__ import division in a module, the / operator will be changed to return the result of true division, so 1/2 is 0.5. Without the __future__ statement, / still means classic division. The default meaning of / will not change until Python 3.0.

Classes can define methods called __truediv__() and __floordiv__() to overload the two division operators. At the C level, there are also slots in the PyNumberMethods structure so extension types can define the two operators.

Python 2.2 supports some command-line arguments for testing whether code will work with the changed division semantics. Running python with -Q warn will cause a warning to be issued whenever division is applied to two integers. You can use this to find code that’s affected by the change and fix it. By default, Python 2.2 will simply perform classic division without a warning; the warning will be turned on by default in Python 2.3.

더 보기

PEP 238 [https://www.python.org/dev/peps/pep-0238] - Changing the Division Operator

Written by Moshe Zadka and Guido van Rossum. Implemented by Guido van Rossum..

Unicode Changes

Python’s Unicode support has been enhanced a bit in 2.2. Unicode strings are usually stored as UCS-2, as 16-bit unsigned integers. Python 2.2 can also be compiled to use UCS-4, 32-bit unsigned integers, as its internal encoding by supplying --enable-unicode=ucs4 to the configure script. (It’s also possible to specify --disable-unicode to completely disable Unicode support.)

When built to use UCS-4 (a “wide Python”), the interpreter can natively handle Unicode characters from U+000000 to U+110000, so the range of legal values for the unichr() function is expanded accordingly. Using an interpreter compiled to use UCS-2 (a “narrow Python”), values greater than 65535 will still cause unichr() to raise a ValueError exception. This is all described in PEP 261 [https://www.python.org/dev/peps/pep-0261], “Support for ‘wide’ Unicode characters”; consult it for further details.

Another change is simpler to explain. Since their introduction, Unicode strings have supported an encode() method to convert the string to a selected encoding such as UTF-8 or Latin-1. A symmetric decode([*encoding*]) method has been added to 8-bit strings (though not to Unicode strings) in 2.2. decode() assumes that the string is in the specified encoding and decodes it, returning whatever is returned by the codec.

Using this new feature, codecs have been added for tasks not directly related to Unicode. For example, codecs have been added for uu-encoding, MIME’s base64 encoding, and compression with the zlib module:

>>> s = """Here is a lengthy piece of redundant, overly verbose,
... and repetitive text.
... """
>>> data = s.encode('zlib')
>>> data
'x\x9c\r\xc9\xc1\r\x80 \x10\x04\xc0?Ul...'
>>> data.decode('zlib')
'Here is a lengthy piece of redundant, overly verbose,\nand repetitive text.\n'
>>> print s.encode('uu')
begin 666 <data>
M2&5R92!I<R!A(&QE;F=T:'D@<&EE8V4@;V8@<F5D=6YD86YT+"!O=F5R;'D@
>=F5R8F]S92P*86YD(')E<&5T:71I=F4@=&5X="X*

end
>>> "sheesh".encode('rot-13')
'furrfu'

To convert a class instance to Unicode, a __unicode__() method can be defined by a class, analogous to __str__().

encode(), decode(), and __unicode__() were implemented by Marc-André Lemburg. The changes to support using UCS-4 internally were implemented by Fredrik Lundh and Martin von Löwis.

더 보기

PEP 261 [https://www.python.org/dev/peps/pep-0261] - Support for ‘wide’ Unicode characters

Written by Paul Prescod.

PEP 227: Nested Scopes

In Python 2.1, statically nested scopes were added as an optional feature, to be enabled by a from __future__ import nested_scopes directive. In 2.2 nested scopes no longer need to be specially enabled, and are now always present. The rest of this section is a copy of the description of nested scopes from my “What’s New in Python 2.1” document; if you read it when 2.1 came out, you can skip the rest of this section.

The largest change introduced in Python 2.1, and made complete in 2.2, is to Python’s scoping rules. In Python 2.0, at any given time there are at most three namespaces used to look up variable names: local, module-level, and the built-in namespace. This often surprised people because it didn’t match their intuitive expectations. For example, a nested recursive function definition doesn’t work:

def f():
    ...
    def g(value):
        ...
        return g(value-1) + 1
    ...

The function g() will always raise a NameError exception, because the binding of the name g isn’t in either its local namespace or in the module-level namespace. This isn’t much of a problem in practice (how often do you recursively define interior functions like this?), but this also made using the lambda expression clumsier, and this was a problem in practice. In code which uses lambda you can often find local variables being copied by passing them as the default values of arguments.

def find(self, name):
    "Return list of any entries equal to 'name'"
    L = filter(lambda x, name=name: x == name,
               self.list_attribute)
    return L

The readability of Python code written in a strongly functional style suffers greatly as a result.

The most significant change to Python 2.2 is that static scoping has been added to the language to fix this problem. As a first effect, the name=name default argument is now unnecessary in the above example. Put simply, when a given variable name is not assigned a value within a function (by an assignment, or the def, class, or import statements), references to the variable will be looked up in the local namespace of the enclosing scope. A more detailed explanation of the rules, and a dissection of the implementation, can be found in the PEP.

This change may cause some compatibility problems for code where the same variable name is used both at the module level and as a local variable within a function that contains further function definitions. This seems rather unlikely though, since such code would have been pretty confusing to read in the first place.

One side effect of the change is that the from module import * and exec statements have been made illegal inside a function scope under certain conditions. The Python reference manual has said all along that from module import * is only legal at the top level of a module, but the CPython interpreter has never enforced this before. As part of the implementation of nested scopes, the compiler which turns Python source into bytecodes has to generate different code to access variables in a containing scope. from module import * and exec make it impossible for the compiler to figure this out, because they add names to the local namespace that are unknowable at compile time. Therefore, if a function contains function definitions or lambda expressions with free variables, the compiler will flag this by raising a SyntaxError exception.

To make the preceding explanation a bit clearer, here’s an example:

x = 1
def f():
    # The next line is a syntax error
    exec 'x=2'
    def g():
        return x

Line 4 containing the exec statement is a syntax error, since exec would define a new local variable named x whose value should be accessed by g().

This shouldn’t be much of a limitation, since exec is rarely used in most Python code (and when it is used, it’s often a sign of a poor design anyway).

더 보기

PEP 227 [https://www.python.org/dev/peps/pep-0227] - Statically Nested Scopes

Written and implemented by Jeremy Hylton.

New and Improved Modules

The xmlrpclib module was contributed to the standard library by Fredrik Lundh, providing support for writing XML-RPC clients. XML-RPC is a simple remote procedure call protocol built on top of HTTP and XML. For example, the following snippet retrieves a list of RSS channels from the O’Reilly Network, and then lists the recent headlines for one channel:

import xmlrpclib
s = xmlrpclib.Server(
      'http://www.oreillynet.com/meerkat/xml-rpc/server.php')
channels = s.meerkat.getChannels()
# channels is a list of dictionaries, like this:
# [{'id': 4, 'title': 'Freshmeat Daily News'}
#  {'id': 190, 'title': '32Bits Online'},
#  {'id': 4549, 'title': '3DGamers'}, ... ]

# Get the items for one channel
items = s.meerkat.getItems( {'channel': 4} )

# 'items' is another list of dictionaries, like this:
# [{'link': 'http://freshmeat.net/releases/52719/',
#   'description': 'A utility which converts HTML to XSL FO.',
#   'title': 'html2fo 0.3 (Default)'}, ... ]

The SimpleXMLRPCServer module makes it easy to create straightforward XML-RPC servers. See http://xmlrpc.scripting.com/ for more information about XML-RPC.

The new hmac module implements the HMAC algorithm described by RFC 2104 [https://tools.ietf.org/html/rfc2104.html]. (Contributed by Gerhard Häring.)

Several functions that originally returned lengthy tuples now return pseudo-sequences that still behave like tuples but also have mnemonic attributes such as memberst_mtime or tm_year. The enhanced functions include stat(), fstat(), statvfs(), and fstatvfs() in the os module, and localtime(), gmtime(), and strptime() in the time module.

For example, to obtain a file’s size using the old tuples, you’d end up writing something like file_size = os.stat(filename)[stat.ST_SIZE], but now this can be written more clearly as file_size = os.stat(filename).st_size.

The original patch for this feature was contributed by Nick Mathewson.

The Python profiler has been extensively reworked and various errors in its output have been corrected. (Contributed by Fred L. Drake, Jr. and Tim Peters.)

The socket module can be compiled to support IPv6; specify the --enable-ipv6 option to Python’s configure script. (Contributed by Jun-ichiro “itojun” Hagino.)

Two new format characters were added to the struct module for 64-bit integers on platforms that support the C long long type. q is for a signed 64-bit integer, and Q is for an unsigned one. The value is returned in Python’s long integer type. (Contributed by Tim Peters.)

In the interpreter’s interactive mode, there’s a new built-in function help() that uses the pydoc module introduced in Python 2.1 to provide interactive help. help(object) displays any available help text about object. help() with no argument puts you in an online help utility, where you can enter the names of functions, classes, or modules to read their help text. (Contributed by Guido van Rossum, using Ka-Ping Yee’s pydoc module.)

Various bugfixes and performance improvements have been made to the SRE engine underlying the re module. For example, the re.sub() and re.split() functions have been rewritten in C. Another contributed patch speeds up certain Unicode character ranges by a factor of two, and a new finditer() method that returns an iterator over all the non-overlapping matches in a given string. (SRE is maintained by Fredrik Lundh. The BIGCHARSET patch was contributed by Martin von Löwis.)

The smtplib module now supports RFC 2487 [https://tools.ietf.org/html/rfc2487.html], “Secure SMTP over TLS”, so it’s now possible to encrypt the SMTP traffic between a Python program and the mail transport agent being handed a message. smtplib also supports SMTP authentication. (Contributed by Gerhard Häring.)

The imaplib module, maintained by Piers Lauder, has support for several new extensions: the NAMESPACE extension defined in RFC 2342 [https://tools.ietf.org/html/rfc2342.html], SORT, GETACL and SETACL. (Contributed by Anthony Baxter and Michel Pelletier.)

The rfc822 module’s parsing of email addresses is now compliant with RFC 2822 [https://tools.ietf.org/html/rfc2822.html], an update to RFC 822 [https://tools.ietf.org/html/rfc822.html]. (The module’s name is not going to be changed to rfc2822.) A new package, email, has also been added for parsing and generating e-mail messages. (Contributed by Barry Warsaw, and arising out of his work on Mailman.)

The difflib module now contains a new Differ class for producing human-readable lists of changes (a “delta”) between two sequences of lines of text. There are also two generator functions, ndiff() and restore(), which respectively return a delta from two sequences, or one of the original sequences from a delta. (Grunt work contributed by David Goodger, from ndiff.py code by Tim Peters who then did the generatorization.)

New constants ascii_letters, ascii_lowercase, and ascii_uppercase were added to the string module. There were several modules in the standard library that used string.letters to mean the ranges A-Za-z, but that assumption is incorrect when locales are in use, because string.letters varies depending on the set of legal characters defined by the current locale. The buggy modules have all been fixed to use ascii_letters instead. (Reported by an unknown person; fixed by Fred L. Drake, Jr.)

The mimetypes module now makes it easier to use alternative MIME-type databases by the addition of a MimeTypes class, which takes a list of filenames to be parsed. (Contributed by Fred L. Drake, Jr.)

A Timer class was added to the threading module that allows scheduling an activity to happen at some future time. (Contributed by Itamar Shtull-Trauring.)

Interpreter Changes and Fixes

Some of the changes only affect people who deal with the Python interpreter at the C level because they’re writing Python extension modules, embedding the interpreter, or just hacking on the interpreter itself. If you only write Python code, none of the changes described here will affect you very much.

Profiling and tracing functions can now be implemented in C, which can operate at much higher speeds than Python-based functions and should reduce the overhead of profiling and tracing. This will be of interest to authors of development environments for Python. Two new C functions were added to Python’s API, PyEval_SetProfile() and PyEval_SetTrace(). The existing sys.setprofile() and sys.settrace() functions still exist, and have simply been changed to use the new C-level interface. (Contributed by Fred L. Drake, Jr.)

Another low-level API, primarily of interest to implementors of Python debuggers and development tools, was added. PyInterpreterState_Head() and PyInterpreterState_Next() let a caller walk through all the existing interpreter objects; PyInterpreterState_ThreadHead() and PyThreadState_Next() allow looping over all the thread states for a given interpreter. (Contributed by David Beazley.)

The C-level interface to the garbage collector has been changed to make it easier to write extension types that support garbage collection and to debug misuses of the functions. Various functions have slightly different semantics, so a bunch of functions had to be renamed. Extensions that use the old API will still compile but will not participate in garbage collection, so updating them for 2.2 should be considered fairly high priority.

To upgrade an extension module to the new API, perform the following steps:

Rename Py_TPFLAGS_GC() to PyTPFLAGS_HAVE_GC().

Use PyObject_GC_New() or PyObject_GC_NewVar() to allocate

objects, and PyObject_GC_Del() to deallocate them.

Rename PyObject_GC_Init() to PyObject_GC_Track() and

PyObject_GC_Fini() to PyObject_GC_UnTrack().

Remove PyGC_HEAD_SIZE() from object size calculations.

Remove calls to PyObject_AS_GC() and PyObject_FROM_GC().

A new et format sequence was added to PyArg_ParseTuple(); et takes both a parameter and an encoding name, and converts the parameter to the given encoding if the parameter turns out to be a Unicode string, or leaves it alone if it’s an 8-bit string, assuming it to already be in the desired encoding. This differs from the es format character, which assumes that 8-bit strings are in Python’s default ASCII encoding and converts them to the specified new encoding. (Contributed by M.-A. Lemburg, and used for the MBCS support on Windows described in the following section.)

A different argument parsing function, PyArg_UnpackTuple(), has been added that’s simpler and presumably faster. Instead of specifying a format string, the caller simply gives the minimum and maximum number of arguments expected, and a set of pointers to PyObject* variables that will be filled in with argument values.

Two new flags METH_NOARGS and METH_O are available in method definition tables to simplify implementation of methods with no arguments or a single untyped argument. Calling such methods is more efficient than calling a corresponding method that uses METH_VARARGS. Also, the old METH_OLDARGS style of writing C methods is now officially deprecated.

Two new wrapper functions, PyOS_snprintf() and PyOS_vsnprintf() were added to provide cross-platform implementations for the relatively new snprintf() and vsnprintf() C lib APIs. In contrast to the standard sprintf() and vsprintf() functions, the Python versions check the bounds of the buffer used to protect against buffer overruns. (Contributed by M.-A. Lemburg.)

The _PyTuple_Resize() function has lost an unused parameter, so now it takes 2 parameters instead of 3. The third argument was never used, and can simply be discarded when porting code from earlier versions to Python 2.2.

Other Changes and Fixes

As usual there were a bunch of other improvements and bugfixes scattered throughout the source tree. A search through the CVS change logs finds there were 527 patches applied and 683 bugs fixed between Python 2.1 and 2.2; 2.2.1 applied 139 patches and fixed 143 bugs; 2.2.2 applied 106 patches and fixed 82 bugs. These figures are likely to be underestimates.

Some of the more notable changes are:

The code for the MacOS port for Python, maintained by Jack Jansen, is now kept in the main Python CVS tree, and many changes have been made to support MacOS X.

The most significant change is the ability to build Python as a framework, enabled by supplying the --enable-framework option to the configure script when compiling Python. According to Jack Jansen, “This installs a self-contained Python installation plus the OS X framework “glue” into /Library/Frameworks/Python.framework (or another location of choice). For now there is little immediate added benefit to this (actually, there is the disadvantage that you have to change your PATH to be able to find Python), but it is the basis for creating a full-blown Python application, porting the MacPython IDE, possibly using Python as a standard OSA scripting language and much more.”

Most of the MacPython toolbox modules, which interface to MacOS APIs such as windowing, QuickTime, scripting, etc. have been ported to OS X, but they’ve been left commented out in setup.py. People who want to experiment with these modules can uncomment them manually.

Keyword arguments passed to built-in functions that don’t take them now cause a TypeError exception to be raised, with the message “function takes no keyword arguments”.

Weak references, added in Python 2.1 as an extension module, are now part of the core because they’re used in the implementation of new-style classes. The ReferenceError exception has therefore moved from the weakref module to become a built-in exception.

A new script, Tools/scripts/cleanfuture.py by Tim Peters, automatically removes obsolete __future__ statements from Python source code.

An additional flags argument has been added to the built-in function compile(), so the behaviour of __future__ statements can now be correctly observed in simulated shells, such as those presented by IDLE and other development environments. This is described in PEP 264 [https://www.python.org/dev/peps/pep-0264]. (Contributed by Michael Hudson.)

The new license introduced with Python 1.6 wasn’t GPL-compatible. This is fixed by some minor textual changes to the 2.2 license, so it’s now legal to embed Python inside a GPLed program again. Note that Python itself is not GPLed, but instead is under a license that’s essentially equivalent to the BSD license, same as it always was. The license changes were also applied to the Python 2.0.1 and 2.1.1 releases.

When presented with a Unicode filename on Windows, Python will now convert it to an MBCS encoded string, as used by the Microsoft file APIs. As MBCS is explicitly used by the file APIs, Python’s choice of ASCII as the default encoding turns out to be an annoyance. On Unix, the locale’s character set is used if locale.nl_langinfo(CODESET) is available. (Windows support was contributed by Mark Hammond with assistance from Marc-André Lemburg. Unix support was added by Martin von Löwis.)

Large file support is now enabled on Windows. (Contributed by Tim Peters.)

The Tools/scripts/ftpmirror.py script now parses a .netrc file, if you have one. (Contributed by Mike Romberg.)

Some features of the object returned by the xrange() function are now deprecated, and trigger warnings when they’re accessed; they’ll disappear in Python 2.3. xrange objects tried to pretend they were full sequence types by supporting slicing, sequence multiplication, and the in operator, but these features were rarely used and therefore buggy. The tolist() method and the start, stop, and step attributes are also being deprecated. At the C level, the fourth argument to the PyRange_New() function, repeat, has also been deprecated.

There were a bunch of patches to the dictionary implementation, mostly to fix potential core dumps if a dictionary contains objects that sneakily changed their hash value, or mutated the dictionary they were contained in. For a while python-dev fell into a gentle rhythm of Michael Hudson finding a case that dumped core, Tim Peters fixing the bug, Michael finding another case, and round and round it went.

On Windows, Python can now be compiled with Borland C thanks to a number of patches contributed by Stephen Hansen, though the result isn’t fully functional yet. (But this is progress…)

Another Windows enhancement: Wise Solutions generously offered PythonLabs use of their InstallerMaster 8.1 system. Earlier PythonLabs Windows installers used Wise 5.0a, which was beginning to show its age. (Packaged up by Tim Peters.)

Files ending in .pyw can now be imported on Windows. .pyw is a Windows-only thing, used to indicate that a script needs to be run using PYTHONW.EXE instead of PYTHON.EXE in order to prevent a DOS console from popping up to display the output. This patch makes it possible to import such scripts, in case they’re also usable as modules. (Implemented by David Bolen.)

On platforms where Python uses the C dlopen() function to load extension modules, it’s now possible to set the flags used by dlopen() using the sys.getdlopenflags() and sys.setdlopenflags() functions. (Contributed by Bram Stolk.)

The pow() built-in function no longer supports 3 arguments when floating-point numbers are supplied. pow(x, y, z) returns (x**y) % z, but this is never useful for floating point numbers, and the final result varies unpredictably depending on the platform. A call such as pow(2.0, 8.0, 7.0) will now raise a TypeError exception.

Acknowledgements

The author would like to thank the following people for offering suggestions, corrections and assistance with various drafts of this article: Fred Bremmer, Keith Briggs, Andrew Dalke, Fred L. Drake, Jr., Carel Fellinger, David Goodger, Mark Hammond, Stephen Hansen, Michael Hudson, Jack Jansen, Marc-André Lemburg, Martin von Löwis, Fredrik Lundh, Michael McLay, Nick Mathewson, Paul Moore, Gustavo Niemeyer, Don O’Donnell, Joonas Paalasma, Tim Peters, Jens Quade, Tom Reinhardt, Neil Schemenauer, Guido van Rossum, Greg Ward, Edward Welbourne.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬의 새로운 기능 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬의 새로운 기능 »

|

What’s New in Python 2.1

Author

A.M. Kuchling

Introduction

This article explains the new features in Python 2.1. While there aren’t as many changes in 2.1 as there were in Python 2.0, there are still some pleasant surprises in store. 2.1 is the first release to be steered through the use of Python Enhancement Proposals, or PEPs, so most of the sizable changes have accompanying PEPs that provide more complete documentation and a design rationale for the change. This article doesn’t attempt to document the new features completely, but simply provides an overview of the new features for Python programmers. Refer to the Python 2.1 documentation, or to the specific PEP, for more details about any new feature that particularly interests you.

One recent goal of the Python development team has been to accelerate the pace of new releases, with a new release coming every 6 to 9 months. 2.1 is the first release to come out at this faster pace, with the first alpha appearing in January, 3 months after the final version of 2.0 was released.

The final release of Python 2.1 was made on April 17, 2001.

PEP 227: Nested Scopes

The largest change in Python 2.1 is to Python’s scoping rules. In Python 2.0, at any given time there are at most three namespaces used to look up variable names: local, module-level, and the built-in namespace. This often surprised people because it didn’t match their intuitive expectations. For example, a nested recursive function definition doesn’t work:

def f():
    ...
    def g(value):
        ...
        return g(value-1) + 1
    ...

The function g() will always raise a NameError exception, because the binding of the name g isn’t in either its local namespace or in the module-level namespace. This isn’t much of a problem in practice (how often do you recursively define interior functions like this?), but this also made using the lambda expression clumsier, and this was a problem in practice. In code which uses lambda you can often find local variables being copied by passing them as the default values of arguments.

def find(self, name):
    "Return list of any entries equal to 'name'"
    L = filter(lambda x, name=name: x == name,
               self.list_attribute)
    return L

The readability of Python code written in a strongly functional style suffers greatly as a result.

The most significant change to Python 2.1 is that static scoping has been added to the language to fix this problem. As a first effect, the name=name default argument is now unnecessary in the above example. Put simply, when a given variable name is not assigned a value within a function (by an assignment, or the def, class, or import statements), references to the variable will be looked up in the local namespace of the enclosing scope. A more detailed explanation of the rules, and a dissection of the implementation, can be found in the PEP.

This change may cause some compatibility problems for code where the same variable name is used both at the module level and as a local variable within a function that contains further function definitions. This seems rather unlikely though, since such code would have been pretty confusing to read in the first place.

One side effect of the change is that the from module import * and exec statements have been made illegal inside a function scope under certain conditions. The Python reference manual has said all along that from module import * is only legal at the top level of a module, but the CPython interpreter has never enforced this before. As part of the implementation of nested scopes, the compiler which turns Python source into bytecodes has to generate different code to access variables in a containing scope. from module import * and exec make it impossible for the compiler to figure this out, because they add names to the local namespace that are unknowable at compile time. Therefore, if a function contains function definitions or lambda expressions with free variables, the compiler will flag this by raising a SyntaxError exception.

To make the preceding explanation a bit clearer, here’s an example:

x = 1
def f():
    # The next line is a syntax error
    exec 'x=2'
    def g():
        return x

Line 4 containing the exec statement is a syntax error, since exec would define a new local variable named x whose value should be accessed by g().

This shouldn’t be much of a limitation, since exec is rarely used in most Python code (and when it is used, it’s often a sign of a poor design anyway).

Compatibility concerns have led to nested scopes being introduced gradually; in Python 2.1, they aren’t enabled by default, but can be turned on within a module by using a future statement as described in PEP 236. (See the following section for further discussion of PEP 236.) In Python 2.2, nested scopes will become the default and there will be no way to turn them off, but users will have had all of 2.1’s lifetime to fix any breakage resulting from their introduction.

더 보기

PEP 227 [https://www.python.org/dev/peps/pep-0227] - Statically Nested Scopes

Written and implemented by Jeremy Hylton.

PEP 236: __future__ Directives

The reaction to nested scopes was widespread concern about the dangers of breaking code with the 2.1 release, and it was strong enough to make the Pythoneers take a more conservative approach. This approach consists of introducing a convention for enabling optional functionality in release N that will become compulsory in release N+1.

The syntax uses a from...import statement using the reserved module name __future__. Nested scopes can be enabled by the following statement:

from __future__ import nested_scopes

While it looks like a normal import statement, it’s not; there are strict rules on where such a future statement can be put. They can only be at the top of a module, and must precede any Python code or regular import statements. This is because such statements can affect how the Python bytecode compiler parses code and generates bytecode, so they must precede any statement that will result in bytecodes being produced.

더 보기

PEP 236 [https://www.python.org/dev/peps/pep-0236] - Back to the __future__

Written by Tim Peters, and primarily implemented by Jeremy Hylton.

PEP 207: Rich Comparisons

In earlier versions, Python’s support for implementing comparisons on user-defined classes and extension types was quite simple. Classes could implement a __cmp__() method that was given two instances of a class, and could only return 0 if they were equal or +1 or -1 if they weren’t; the method couldn’t raise an exception or return anything other than a Boolean value. Users of Numeric Python often found this model too weak and restrictive, because in the number-crunching programs that numeric Python is used for, it would be more useful to be able to perform elementwise comparisons of two matrices, returning a matrix containing the results of a given comparison for each element. If the two matrices are of different sizes, then the compare has to be able to raise an exception to signal the error.

In Python 2.1, rich comparisons were added in order to support this need. Python classes can now individually overload each of the <, <=, >, >=, ==, and != operations. The new magic method names are:

Operation

Method name

<

__lt__()

<=

__le__()

>

__gt__()

>=

__ge__()

==

__eq__()

!=

__ne__()

(The magic methods are named after the corresponding Fortran operators .LT.. .LE., &c. Numeric programmers are almost certainly quite familiar with these names and will find them easy to remember.)

Each of these magic methods is of the form method(self, other), where self will be the object on the left-hand side of the operator, while other will be the object on the right-hand side. For example, the expression A < B will cause A.__lt__(B) to be called.

Each of these magic methods can return anything at all: a Boolean, a matrix, a list, or any other Python object. Alternatively they can raise an exception if the comparison is impossible, inconsistent, or otherwise meaningless.

The built-in cmp(A,B) function can use the rich comparison machinery, and now accepts an optional argument specifying which comparison operation to use; this is given as one of the strings "<", "<=", ">", ">=", "==", or "!=". If called without the optional third argument, cmp() will only return -1, 0, or +1 as in previous versions of Python; otherwise it will call the appropriate method and can return any Python object.

There are also corresponding changes of interest to C programmers; there’s a new slot tp_richcmp in type objects and an API for performing a given rich comparison. I won’t cover the C API here, but will refer you to PEP 207, or to 2.1’s C API documentation, for the full list of related functions.

더 보기

PEP 207 [https://www.python.org/dev/peps/pep-0207] - Rich Comparisons

Written by Guido van Rossum, heavily based on earlier work by David Ascher, and implemented by Guido van Rossum.

PEP 230: Warning Framework

Over its 10 years of existence, Python has accumulated a certain number of obsolete modules and features along the way. It’s difficult to know when a feature is safe to remove, since there’s no way of knowing how much code uses it — perhaps no programs depend on the feature, or perhaps many do. To enable removing old features in a more structured way, a warning framework was added. When the Python developers want to get rid of a feature, it will first trigger a warning in the next version of Python. The following Python version can then drop the feature, and users will have had a full release cycle to remove uses of the old feature.

Python 2.1 adds the warning framework to be used in this scheme. It adds a warnings module that provide functions to issue warnings, and to filter out warnings that you don’t want to be displayed. Third-party modules can also use this framework to deprecate old features that they no longer wish to support.

For example, in Python 2.1 the regex module is deprecated, so importing it causes a warning to be printed:

>>> import regex
__main__:1: DeprecationWarning: the regex module
         is deprecated; please use the re module
>>>

Warnings can be issued by calling the warnings.warn() function:

warnings.warn("feature X no longer supported")

The first parameter is the warning message; an additional optional parameters can be used to specify a particular warning category.

Filters can be added to disable certain warnings; a regular expression pattern can be applied to the message or to the module name in order to suppress a warning. For example, you may have a program that uses the regex module and not want to spare the time to convert it to use the re module right now. The warning can be suppressed by calling

import warnings
warnings.filterwarnings(action = 'ignore',
                        message='.*regex module is deprecated',
                        category=DeprecationWarning,
                        module = '__main__')

This adds a filter that will apply only to warnings of the class DeprecationWarning triggered in the __main__ module, and applies a regular expression to only match the message about the regex module being deprecated, and will cause such warnings to be ignored. Warnings can also be printed only once, printed every time the offending code is executed, or turned into exceptions that will cause the program to stop (unless the exceptions are caught in the usual way, of course).

Functions were also added to Python’s C API for issuing warnings; refer to PEP 230 or to Python’s API documentation for the details.

더 보기

PEP 5 [https://www.python.org/dev/peps/pep-0005] - Guidelines for Language Evolution

Written by Paul Prescod, to specify procedures to be followed when removing old features from Python. The policy described in this PEP hasn’t been officially adopted, but the eventual policy probably won’t be too different from Prescod’s proposal.

PEP 230 [https://www.python.org/dev/peps/pep-0230] - Warning Framework

Written and implemented by Guido van Rossum.

PEP 229: New Build System

When compiling Python, the user had to go in and edit the Modules/Setup file in order to enable various additional modules; the default set is relatively small and limited to modules that compile on most Unix platforms. This means that on Unix platforms with many more features, most notably Linux, Python installations often don’t contain all useful modules they could.

Python 2.0 added the Distutils, a set of modules for distributing and installing extensions. In Python 2.1, the Distutils are used to compile much of the standard library of extension modules, autodetecting which ones are supported on the current machine. It’s hoped that this will make Python installations easier and more featureful.

Instead of having to edit the Modules/Setup file in order to enable modules, a setup.py script in the top directory of the Python source distribution is run at build time, and attempts to discover which modules can be enabled by examining the modules and header files on the system. If a module is configured in Modules/Setup, the setup.py script won’t attempt to compile that module and will defer to the Modules/Setup file’s contents. This provides a way to specific any strange command-line flags or libraries that are required for a specific platform.

In another far-reaching change to the build mechanism, Neil Schemenauer restructured things so Python now uses a single makefile that isn’t recursive, instead of makefiles in the top directory and in each of the Python/, Parser/, Objects/, and Modules/ subdirectories. This makes building Python faster and also makes hacking the Makefiles clearer and simpler.

더 보기

PEP 229 [https://www.python.org/dev/peps/pep-0229] - Using Distutils to Build Python

Written and implemented by A.M. Kuchling.

PEP 205: Weak References

Weak references, available through the weakref module, are a minor but useful new data type in the Python programmer’s toolbox.

Storing a reference to an object (say, in a dictionary or a list) has the side effect of keeping that object alive forever. There are a few specific cases where this behaviour is undesirable, object caches being the most common one, and another being circular references in data structures such as trees.

For example, consider a memoizing function that caches the results of another function f(x) by storing the function’s argument and its result in a dictionary:

_cache = {}
def memoize(x):
    if _cache.has_key(x):
        return _cache[x]

    retval = f(x)

    # Cache the returned object
    _cache[x] = retval

    return retval

This version works for simple things such as integers, but it has a side effect; the _cache dictionary holds a reference to the return values, so they’ll never be deallocated until the Python process exits and cleans up. This isn’t very noticeable for integers, but if f() returns an object, or a data structure that takes up a lot of memory, this can be a problem.

Weak references provide a way to implement a cache that won’t keep objects alive beyond their time. If an object is only accessible through weak references, the object will be deallocated and the weak references will now indicate that the object it referred to no longer exists. A weak reference to an object obj is created by calling wr = weakref.ref(obj). The object being referred to is returned by calling the weak reference as if it were a function: wr(). It will return the referenced object, or None if the object no longer exists.

This makes it possible to write a memoize() function whose cache doesn’t keep objects alive, by storing weak references in the cache.

_cache = {}
def memoize(x):
    if _cache.has_key(x):
        obj = _cache[x]()
        # If weak reference object still exists,
        # return it
        if obj is not None: return obj

    retval = f(x)

    # Cache a weak reference
    _cache[x] = weakref.ref(retval)

    return retval

The weakref module also allows creating proxy objects which behave like weak references — an object referenced only by proxy objects is deallocated – but instead of requiring an explicit call to retrieve the object, the proxy transparently forwards all operations to the object as long as the object still exists. If the object is deallocated, attempting to use a proxy will cause a weakref.ReferenceError exception to be raised.

proxy = weakref.proxy(obj)
proxy.attr   # Equivalent to obj.attr
proxy.meth() # Equivalent to obj.meth()
del obj
proxy.attr   # raises weakref.ReferenceError

더 보기

PEP 205 [https://www.python.org/dev/peps/pep-0205] - Weak References

Written and implemented by Fred L. Drake, Jr.

PEP 232: Function Attributes

In Python 2.1, functions can now have arbitrary information attached to them. People were often using docstrings to hold information about functions and methods, because the __doc__ attribute was the only way of attaching any information to a function. For example, in the Zope Web application server, functions are marked as safe for public access by having a docstring, and in John Aycock’s SPARK parsing framework, docstrings hold parts of the BNF grammar to be parsed. This overloading is unfortunate, since docstrings are really intended to hold a function’s documentation; for example, it means you can’t properly document functions intended for private use in Zope.

Arbitrary attributes can now be set and retrieved on functions using the regular Python syntax:

def f(): pass

f.publish = 1
f.secure = 1
f.grammar = "A ::= B (C D)*"

The dictionary containing attributes can be accessed as the function’s __dict__. Unlike the __dict__ attribute of class instances, in functions you can actually assign a new dictionary to __dict__, though the new value is restricted to a regular Python dictionary; you can’t be tricky and set it to a UserDict instance, or any other random object that behaves like a mapping.

더 보기

PEP 232 [https://www.python.org/dev/peps/pep-0232] - Function Attributes

Written and implemented by Barry Warsaw.

PEP 235: Importing Modules on Case-Insensitive Platforms

Some operating systems have filesystems that are case-insensitive, MacOS and Windows being the primary examples; on these systems, it’s impossible to distinguish the filenames FILE.PY and file.py, even though they do store the file’s name in its original case (they’re case-preserving, too).

In Python 2.1, the import statement will work to simulate case-sensitivity on case-insensitive platforms. Python will now search for the first case-sensitive match by default, raising an ImportError if no such file is found, so import file will not import a module named FILE.PY. Case-insensitive matching can be requested by setting the PYTHONCASEOK environment variable before starting the Python interpreter.

PEP 217: Interactive Display Hook

When using the Python interpreter interactively, the output of commands is displayed using the built-in repr() function. In Python 2.1, the variable sys.displayhook() can be set to a callable object which will be called instead of repr(). For example, you can set it to a special pretty-printing function:

>>> # Create a recursive data structure
... L = [1,2,3]
>>> L.append(L)
>>> L # Show Python's default output
[1, 2, 3, [...]]
>>> # Use pprint.pprint() as the display function
... import sys, pprint
>>> sys.displayhook = pprint.pprint
>>> L
[1, 2, 3,  <Recursion on list with id=135143996>]
>>>

더 보기

PEP 217 [https://www.python.org/dev/peps/pep-0217] - Display Hook for Interactive Use

Written and implemented by Moshe Zadka.

PEP 208: New Coercion Model

How numeric coercion is done at the C level was significantly modified. This will only affect the authors of C extensions to Python, allowing them more flexibility in writing extension types that support numeric operations.

Extension types can now set the type flag Py_TPFLAGS_CHECKTYPES in their PyTypeObject structure to indicate that they support the new coercion model. In such extension types, the numeric slot functions can no longer assume that they’ll be passed two arguments of the same type; instead they may be passed two arguments of differing types, and can then perform their own internal coercion. If the slot function is passed a type it can’t handle, it can indicate the failure by returning a reference to the Py_NotImplemented singleton value. The numeric functions of the other type will then be tried, and perhaps they can handle the operation; if the other type also returns Py_NotImplemented, then a TypeError will be raised. Numeric methods written in Python can also return Py_NotImplemented, causing the interpreter to act as if the method did not exist (perhaps raising a TypeError, perhaps trying another object’s numeric methods).

더 보기

PEP 208 [https://www.python.org/dev/peps/pep-0208] - Reworking the Coercion Model

Written and implemented by Neil Schemenauer, heavily based upon earlier work by Marc-André Lemburg. Read this to understand the fine points of how numeric operations will now be processed at the C level.

PEP 241: Metadata in Python Packages

A common complaint from Python users is that there’s no single catalog of all the Python modules in existence. T. Middleton’s Vaults of Parnassus at http://www.vex.net/parnassus/ are the largest catalog of Python modules, but registering software at the Vaults is optional, and many people don’t bother.

As a first small step toward fixing the problem, Python software packaged using the Distutils sdist command will include a file named PKG-INFO containing information about the package such as its name, version, and author (metadata, in cataloguing terminology). PEP 241 contains the full list of fields that can be present in the PKG-INFO file. As people began to package their software using Python 2.1, more and more packages will include metadata, making it possible to build automated cataloguing systems and experiment with them. With the result experience, perhaps it’ll be possible to design a really good catalog and then build support for it into Python 2.2. For example, the Distutils sdist and bdist_* commands could support an upload option that would automatically upload your package to a catalog server.

You can start creating packages containing PKG-INFO even if you’re not using Python 2.1, since a new release of the Distutils will be made for users of earlier Python versions. Version 1.0.2 of the Distutils includes the changes described in PEP 241, as well as various bugfixes and enhancements. It will be available from the Distutils SIG at https://www.python.org/community/sigs/current/distutils-sig/.

더 보기

PEP 241 [https://www.python.org/dev/peps/pep-0241] - Metadata for Python Software Packages

Written and implemented by A.M. Kuchling.

PEP 243 [https://www.python.org/dev/peps/pep-0243] - Module Repository Upload Mechanism

Written by Sean Reifschneider, this draft PEP describes a proposed mechanism for uploading Python packages to a central server.

New and Improved Modules

Ka-Ping Yee contributed two new modules: inspect.py, a module for getting information about live Python code, and pydoc.py, a module for interactively converting docstrings to HTML or text. As a bonus, Tools/scripts/pydoc, which is now automatically installed, uses pydoc.py to display documentation given a Python module, package, or class name. For example, pydoc xml.dom displays the following:

Python Library Documentation: package xml.dom in xml

NAME
    xml.dom - W3C Document Object Model implementation for Python.

FILE
    /usr/local/lib/python2.1/xml/dom/__init__.pyc

DESCRIPTION
    The Python mapping of the Document Object Model is documented in the
    Python Library Reference in the section on the xml.dom package.

    This package contains the following modules:
      ...

pydoc also includes a Tk-based interactive help browser. pydoc quickly becomes addictive; try it out!

Two different modules for unit testing were added to the standard library. The doctest module, contributed by Tim Peters, provides a testing framework based on running embedded examples in docstrings and comparing the results against the expected output. PyUnit, contributed by Steve Purcell, is a unit testing framework inspired by JUnit, which was in turn an adaptation of Kent Beck’s Smalltalk testing framework. See http://pyunit.sourceforge.net/ for more information about PyUnit.

The difflib module contains a class, SequenceMatcher, which compares two sequences and computes the changes required to transform one sequence into the other. For example, this module can be used to write a tool similar to the Unix diff program, and in fact the sample program Tools/scripts/ndiff.py demonstrates how to write such a script.

curses.panel, a wrapper for the panel library, part of ncurses and of SYSV curses, was contributed by Thomas Gellekum. The panel library provides windows with the additional feature of depth. Windows can be moved higher or lower in the depth ordering, and the panel library figures out where panels overlap and which sections are visible.

The PyXML package has gone through a few releases since Python 2.0, and Python 2.1 includes an updated version of the xml package. Some of the noteworthy changes include support for Expat 1.2 and later versions, the ability for Expat parsers to handle files in any encoding supported by Python, and various bugfixes for SAX, DOM, and the minidom module.

Ping also contributed another hook for handling uncaught exceptions. sys.excepthook() can be set to a callable object. When an exception isn’t caught by any try…except blocks, the exception will be passed to sys.excepthook(), which can then do whatever it likes. At the Ninth Python Conference, Ping demonstrated an application for this hook: printing an extended traceback that not only lists the stack frames, but also lists the function arguments and the local variables for each frame.

Various functions in the time module, such as asctime() and localtime(), require a floating point argument containing the time in seconds since the epoch. The most common use of these functions is to work with the current time, so the floating point argument has been made optional; when a value isn’t provided, the current time will be used. For example, log file entries usually need a string containing the current time; in Python 2.1, time.asctime() can be used, instead of the lengthier time.asctime(time.localtime(time.time())) that was previously required.

This change was proposed and implemented by Thomas Wouters.

The ftplib module now defaults to retrieving files in passive mode, because passive mode is more likely to work from behind a firewall. This request came from the Debian bug tracking system, since other Debian packages use ftplib to retrieve files and then don’t work from behind a firewall. It’s deemed unlikely that this will cause problems for anyone, because Netscape defaults to passive mode and few people complain, but if passive mode is unsuitable for your application or network setup, call set_pasv(0) on FTP objects to disable passive mode.

Support for raw socket access has been added to the socket module, contributed by Grant Edwards.

The pstats module now contains a simple interactive statistics browser for displaying timing profiles for Python programs, invoked when the module is run as a script. Contributed by Eric S. Raymond.

A new implementation-dependent function, sys._getframe([depth]), has been added to return a given frame object from the current call stack. sys._getframe() returns the frame at the top of the call stack; if the optional integer argument depth is supplied, the function returns the frame that is depth calls below the top of the stack. For example, sys._getframe(1) returns the caller’s frame object.

This function is only present in CPython, not in Jython or the .NET implementation. Use it for debugging, and resist the temptation to put it into production code.

Other Changes and Fixes

There were relatively few smaller changes made in Python 2.1 due to the shorter release cycle. A search through the CVS change logs turns up 117 patches applied, and 136 bugs fixed; both figures are likely to be underestimates. Some of the more notable changes are:

A specialized object allocator is now optionally available, that should be faster than the system malloc() and have less memory overhead. The allocator uses C’s malloc() function to get large pools of memory, and then fulfills smaller memory requests from these pools. It can be enabled by providing the --with-pymalloc option to the configure script; see Objects/obmalloc.c for the implementation details.

Authors of C extension modules should test their code with the object allocator enabled, because some incorrect code may break, causing core dumps at runtime. There are a bunch of memory allocation functions in Python’s C API that have previously been just aliases for the C library’s malloc() and free(), meaning that if you accidentally called mismatched functions, the error wouldn’t be noticeable. When the object allocator is enabled, these functions aren’t aliases of malloc() and free() any more, and calling the wrong function to free memory will get you a core dump. For example, if memory was allocated using PyMem_New(), it has to be freed using PyMem_Del(), not free(). A few modules included with Python fell afoul of this and had to be fixed; doubtless there are more third-party modules that will have the same problem.

The object allocator was contributed by Vladimir Marangozov.

The speed of line-oriented file I/O has been improved because people often complain about its lack of speed, and because it’s often been used as a naïve benchmark. The readline() method of file objects has therefore been rewritten to be much faster. The exact amount of the speedup will vary from platform to platform depending on how slow the C library’s getc() was, but is around 66%, and potentially much faster on some particular operating systems. Tim Peters did much of the benchmarking and coding for this change, motivated by a discussion in comp.lang.python.

A new module and method for file objects was also added, contributed by Jeff Epler. The new method, xreadlines(), is similar to the existing xrange() built-in. xreadlines() returns an opaque sequence object that only supports being iterated over, reading a line on every iteration but not reading the entire file into memory as the existing readlines() method does. You’d use it like this:

for line in sys.stdin.xreadlines():
    # ... do something for each line ...
    ...

For a fuller discussion of the line I/O changes, see the python-dev summary for January 1–15, 2001 at https://mail.python.org/pipermail/python-dev/2001-January/.

A new method, popitem(), was added to dictionaries to enable destructively iterating through the contents of a dictionary; this can be faster for large dictionaries because there’s no need to construct a list containing all the keys or values. D.popitem() removes a random (key, value) pair from the dictionary D and returns it as a 2-tuple. This was implemented mostly by Tim Peters and Guido van Rossum, after a suggestion and preliminary patch by Moshe Zadka.

Modules can now control which names are imported when from module import * is used, by defining an __all__ attribute containing a list of names that will be imported. One common complaint is that if the module imports other modules such as sys or string, from module import * will add them to the importing module’s namespace. To fix this, simply list the public names in __all__:

# List public names
__all__ = ['Database', 'open']

A stricter version of this patch was first suggested and implemented by Ben Wolfson, but after some python-dev discussion, a weaker final version was checked in.

Applying repr() to strings previously used octal escapes for non-printable characters; for example, a newline was '\012'. This was a vestigial trace of Python’s C ancestry, but today octal is of very little practical use. Ka-Ping Yee suggested using hex escapes instead of octal ones, and using the \n, \t, \r escapes for the appropriate characters, and implemented this new formatting.

Syntax errors detected at compile-time can now raise exceptions containing the filename and line number of the error, a pleasant side effect of the compiler reorganization done by Jeremy Hylton.

C extensions which import other modules have been changed to use PyImport_ImportModule(), which means that they will use any import hooks that have been installed. This is also encouraged for third-party extensions that need to import some other module from C code.

The size of the Unicode character database was shrunk by another 340K thanks to Fredrik Lundh.

Some new ports were contributed: MacOS X (by Steven Majewski), Cygwin (by Jason Tishler); RISCOS (by Dietmar Schwertberger); Unixware 7 (by Billy G. Allie).

And there’s the usual list of minor bugfixes, minor memory leaks, docstring edits, and other tweaks, too lengthy to be worth itemizing; see the CVS logs for the full details if you want them.

Acknowledgements

The author would like to thank the following people for offering suggestions on various drafts of this article: Graeme Cross, David Goodger, Jay Graves, Michael Hudson, Marc-André Lemburg, Fredrik Lundh, Neil Schemenauer, Thomas Wouters.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬의 새로운 기능 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬의 새로운 기능 »

|

What’s New in Python 2.0

Author

A.M. Kuchling and Moshe Zadka

Introduction

A new release of Python, version 2.0, was released on October 16, 2000. This article covers the exciting new features in 2.0, highlights some other useful changes, and points out a few incompatible changes that may require rewriting code.

Python’s development never completely stops between releases, and a steady flow of bug fixes and improvements are always being submitted. A host of minor fixes, a few optimizations, additional docstrings, and better error messages went into 2.0; to list them all would be impossible, but they’re certainly significant. Consult the publicly-available CVS logs if you want to see the full list. This progress is due to the five developers working for PythonLabs are now getting paid to spend their days fixing bugs, and also due to the improved communication resulting from moving to SourceForge.

What About Python 1.6?

Python 1.6 can be thought of as the Contractual Obligations Python release. After the core development team left CNRI in May 2000, CNRI requested that a 1.6 release be created, containing all the work on Python that had been performed at CNRI. Python 1.6 therefore represents the state of the CVS tree as of May 2000, with the most significant new feature being Unicode support. Development continued after May, of course, so the 1.6 tree received a few fixes to ensure that it’s forward-compatible with Python 2.0. 1.6 is therefore part of Python’s evolution, and not a side branch.

So, should you take much interest in Python 1.6? Probably not. The 1.6final and 2.0beta1 releases were made on the same day (September 5, 2000), the plan being to finalize Python 2.0 within a month or so. If you have applications to maintain, there seems little point in breaking things by moving to 1.6, fixing them, and then having another round of breakage within a month by moving to 2.0; you’re better off just going straight to 2.0. Most of the really interesting features described in this document are only in 2.0, because a lot of work was done between May and September.

New Development Process

The most important change in Python 2.0 may not be to the code at all, but to how Python is developed: in May 2000 the Python developers began using the tools made available by SourceForge for storing source code, tracking bug reports, and managing the queue of patch submissions. To report bugs or submit patches for Python 2.0, use the bug tracking and patch manager tools available from Python’s project page, located at https://sourceforge.net/projects/python/.

The most important of the services now hosted at SourceForge is the Python CVS tree, the version-controlled repository containing the source code for Python. Previously, there were roughly 7 or so people who had write access to the CVS tree, and all patches had to be inspected and checked in by one of the people on this short list. Obviously, this wasn’t very scalable. By moving the CVS tree to SourceForge, it became possible to grant write access to more people; as of September 2000 there were 27 people able to check in changes, a fourfold increase. This makes possible large-scale changes that wouldn’t be attempted if they’d have to be filtered through the small group of core developers. For example, one day Peter Schneider-Kamp took it into his head to drop K&R C compatibility and convert the C source for Python to ANSI C. After getting approval on the python-dev mailing list, he launched into a flurry of checkins that lasted about a week, other developers joined in to help, and the job was done. If there were only 5 people with write access, probably that task would have been viewed as “nice, but not worth the time and effort needed” and it would never have gotten done.

The shift to using SourceForge’s services has resulted in a remarkable increase in the speed of development. Patches now get submitted, commented on, revised by people other than the original submitter, and bounced back and forth between people until the patch is deemed worth checking in. Bugs are tracked in one central location and can be assigned to a specific person for fixing, and we can count the number of open bugs to measure progress. This didn’t come without a cost: developers now have more e-mail to deal with, more mailing lists to follow, and special tools had to be written for the new environment. For example, SourceForge sends default patch and bug notification e-mail messages that are completely unhelpful, so Ka-Ping Yee wrote an HTML screen-scraper that sends more useful messages.

The ease of adding code caused a few initial growing pains, such as code was checked in before it was ready or without getting clear agreement from the developer group. The approval process that has emerged is somewhat similar to that used by the Apache group. Developers can vote +1, +0, -0, or -1 on a patch; +1 and -1 denote acceptance or rejection, while +0 and -0 mean the developer is mostly indifferent to the change, though with a slight positive or negative slant. The most significant change from the Apache model is that the voting is essentially advisory, letting Guido van Rossum, who has Benevolent Dictator For Life status, know what the general opinion is. He can still ignore the result of a vote, and approve or reject a change even if the community disagrees with him.

Producing an actual patch is the last step in adding a new feature, and is usually easy compared to the earlier task of coming up with a good design. Discussions of new features can often explode into lengthy mailing list threads, making the discussion hard to follow, and no one can read every posting to python-dev. Therefore, a relatively formal process has been set up to write Python Enhancement Proposals (PEPs), modelled on the Internet RFC process. PEPs are draft documents that describe a proposed new feature, and are continually revised until the community reaches a consensus, either accepting or rejecting the proposal. Quoting from the introduction to PEP 1, “PEP Purpose and Guidelines”:

PEP stands for Python Enhancement Proposal. A PEP is a design document providing information to the Python community, or describing a new feature for Python. The PEP should provide a concise technical specification of the feature and a rationale for the feature.

We intend PEPs to be the primary mechanisms for proposing new features, for collecting community input on an issue, and for documenting the design decisions that have gone into Python. The PEP author is responsible for building consensus within the community and documenting dissenting opinions.

Read the rest of PEP 1 for the details of the PEP editorial process, style, and format. PEPs are kept in the Python CVS tree on SourceForge, though they’re not part of the Python 2.0 distribution, and are also available in HTML form from https://www.python.org/dev/peps/. As of September 2000, there are 25 PEPS, ranging from PEP 201, “Lockstep Iteration”, to PEP 225, “Elementwise/Objectwise Operators”.

Unicode

The largest new feature in Python 2.0 is a new fundamental data type: Unicode strings. Unicode uses 16-bit numbers to represent characters instead of the 8-bit number used by ASCII, meaning that 65,536 distinct characters can be supported.

The final interface for Unicode support was arrived at through countless often-stormy discussions on the python-dev mailing list, and mostly implemented by Marc-André Lemburg, based on a Unicode string type implementation by Fredrik Lundh. A detailed explanation of the interface was written up as PEP 100 [https://www.python.org/dev/peps/pep-0100], “Python Unicode Integration”. This article will simply cover the most significant points about the Unicode interfaces.

In Python source code, Unicode strings are written as u"string". Arbitrary Unicode characters can be written using a new escape sequence, \uHHHH, where HHHH is a 4-digit hexadecimal number from 0000 to FFFF. The existing \xHHHH escape sequence can also be used, and octal escapes can be used for characters up to U+01FF, which is represented by \777.

Unicode strings, just like regular strings, are an immutable sequence type. They can be indexed and sliced, but not modified in place. Unicode strings have an encode( [encoding] ) method that returns an 8-bit string in the desired encoding. Encodings are named by strings, such as 'ascii', 'utf-8', 'iso-8859-1', or whatever. A codec API is defined for implementing and registering new encodings that are then available throughout a Python program. If an encoding isn’t specified, the default encoding is usually 7-bit ASCII, though it can be changed for your Python installation by calling the sys.setdefaultencoding(encoding) function in a customized version of site.py.

Combining 8-bit and Unicode strings always coerces to Unicode, using the default ASCII encoding; the result of 'a' + u'bc' is u'abc'.

New built-in functions have been added, and existing built-ins modified to support Unicode:

unichr(ch) returns a Unicode string 1 character long, containing the character ch.

ord(u), where u is a 1-character regular or Unicode string, returns the number of the character as an integer.

unicode(string [, encoding]  [, errors] ) creates a Unicode string from an 8-bit string. encoding is a string naming the encoding to use. The errors parameter specifies the treatment of characters that are invalid for the current encoding; passing 'strict' as the value causes an exception to be raised on any encoding error, while 'ignore' causes errors to be silently ignored and 'replace' uses U+FFFD, the official replacement character, in case of any problems.

The exec statement, and various built-ins such as eval(), getattr(), and setattr() will also accept Unicode strings as well as regular strings. (It’s possible that the process of fixing this missed some built-ins; if you find a built-in function that accepts strings but doesn’t accept Unicode strings at all, please report it as a bug.)

A new module, unicodedata, provides an interface to Unicode character properties. For example, unicodedata.category(u'A') returns the 2-character string ‘Lu’, the ‘L’ denoting it’s a letter, and ‘u’ meaning that it’s uppercase. unicodedata.bidirectional(u'\u0660') returns ‘AN’, meaning that U+0660 is an Arabic number.

The codecs module contains functions to look up existing encodings and register new ones. Unless you want to implement a new encoding, you’ll most often use the codecs.lookup(encoding) function, which returns a 4-element tuple: (encode_func, decode_func, stream_reader, stream_writer).

encode_func is a function that takes a Unicode string, and returns a 2-tuple (string, length). string is an 8-bit string containing a portion (perhaps all) of the Unicode string converted into the given encoding, and length tells you how much of the Unicode string was converted.

decode_func is the opposite of encode_func, taking an 8-bit string and returning a 2-tuple (ustring, length), consisting of the resulting Unicode string ustring and the integer length telling how much of the 8-bit string was consumed.

stream_reader is a class that supports decoding input from a stream. stream_reader(file_obj) returns an object that supports the read(), readline(), and readlines() methods. These methods will all translate from the given encoding and return Unicode strings.

stream_writer, similarly, is a class that supports encoding output to a stream. stream_writer(file_obj) returns an object that supports the write() and writelines() methods. These methods expect Unicode strings, translating them to the given encoding on output.

For example, the following code writes a Unicode string into a file, encoding it as UTF-8:

import codecs

unistr = u'\u0660\u2000ab ...'

(UTF8_encode, UTF8_decode,
 UTF8_streamreader, UTF8_streamwriter) = codecs.lookup('UTF-8')

output = UTF8_streamwriter( open( '/tmp/output', 'wb') )
output.write( unistr )
output.close()

The following code would then read UTF-8 input from the file:

input = UTF8_streamreader( open( '/tmp/output', 'rb') )
print repr(input.read())
input.close()

Unicode-aware regular expressions are available through the re module, which has a new underlying implementation called SRE written by Fredrik Lundh of Secret Labs AB.

A -U command line option was added which causes the Python compiler to interpret all string literals as Unicode string literals. This is intended to be used in testing and future-proofing your Python code, since some future version of Python may drop support for 8-bit strings and provide only Unicode strings.

List Comprehensions

Lists are a workhorse data type in Python, and many programs manipulate a list at some point. Two common operations on lists are to loop over them, and either pick out the elements that meet a certain criterion, or apply some function to each element. For example, given a list of strings, you might want to pull out all the strings containing a given substring, or strip off trailing whitespace from each line.

The existing map() and filter() functions can be used for this purpose, but they require a function as one of their arguments. This is fine if there’s an existing built-in function that can be passed directly, but if there isn’t, you have to create a little function to do the required work, and Python’s scoping rules make the result ugly if the little function needs additional information. Take the first example in the previous paragraph, finding all the strings in the list containing a given substring. You could write the following to do it:

# Given the list L, make a list of all strings
# containing the substring S.
sublist = filter( lambda s, substring=S:
                     string.find(s, substring) != -1,
                  L)

Because of Python’s scoping rules, a default argument is used so that the anonymous function created by the lambda expression knows what substring is being searched for. List comprehensions make this cleaner:

sublist = [ s for s in L if string.find(s, S) != -1 ]

List comprehensions have the form:

[ expression for expr in sequence1
             for expr2 in sequence2 ...
             for exprN in sequenceN
             if condition ]

The for…in clauses contain the sequences to be iterated over. The sequences do not have to be the same length, because they are not iterated over in parallel, but from left to right; this is explained more clearly in the following paragraphs. The elements of the generated list will be the successive values of expression. The final if clause is optional; if present, expression is only evaluated and added to the result if condition is true.

To make the semantics very clear, a list comprehension is equivalent to the following Python code:

for expr1 in sequence1:
    for expr2 in sequence2:
    ...
        for exprN in sequenceN:
             if (condition):
                  # Append the value of
                  # the expression to the
                  # resulting list.

This means that when there are multiple for…in clauses, the resulting list will be equal to the product of the lengths of all the sequences. If you have two lists of length 3, the output list is 9 elements long:

seq1 = 'abc'
seq2 = (1,2,3)
>>> [ (x,y) for x in seq1 for y in seq2]
[('a', 1), ('a', 2), ('a', 3), ('b', 1), ('b', 2), ('b', 3), ('c', 1),
('c', 2), ('c', 3)]

To avoid introducing an ambiguity into Python’s grammar, if expression is creating a tuple, it must be surrounded with parentheses. The first list comprehension below is a syntax error, while the second one is correct:

# Syntax error
[ x,y for x in seq1 for y in seq2]
# Correct
[ (x,y) for x in seq1 for y in seq2]

The idea of list comprehensions originally comes from the functional programming language Haskell (https://www.haskell.org). Greg Ewing argued most effectively for adding them to Python and wrote the initial list comprehension patch, which was then discussed for a seemingly endless time on the python-dev mailing list and kept up-to-date by Skip Montanaro.

Augmented Assignment

Augmented assignment operators, another long-requested feature, have been added to Python 2.0. Augmented assignment operators include +=, -=, *=, and so forth. For example, the statement a += 2 increments the value of the variable a by 2, equivalent to the slightly lengthier a = a + 2.

The full list of supported assignment operators is +=, -=, *=, /=, %=, **=, &=, |=, ^=, >>=, and <<=. Python classes can override the augmented assignment operators by defining methods named __iadd__(), __isub__(), etc. For example, the following Number class stores a number and supports using += to create a new instance with an incremented value.

class Number:
    def __init__(self, value):
        self.value = value
    def __iadd__(self, increment):
        return Number( self.value + increment)

n = Number(5)
n += 3
print n.value

The __iadd__() special method is called with the value of the increment, and should return a new instance with an appropriately modified value; this return value is bound as the new value of the variable on the left-hand side.

Augmented assignment operators were first introduced in the C programming language, and most C-derived languages, such as awk, C++, Java, Perl, and PHP also support them. The augmented assignment patch was implemented by Thomas Wouters.

String Methods

Until now string-manipulation functionality was in the string module, which was usually a front-end for the strop module written in C. The addition of Unicode posed a difficulty for the strop module, because the functions would all need to be rewritten in order to accept either 8-bit or Unicode strings. For functions such as string.replace(), which takes 3 string arguments, that means eight possible permutations, and correspondingly complicated code.

Instead, Python 2.0 pushes the problem onto the string type, making string manipulation functionality available through methods on both 8-bit strings and Unicode strings.

>>> 'andrew'.capitalize()
'Andrew'
>>> 'hostname'.replace('os', 'linux')
'hlinuxtname'
>>> 'moshe'.find('sh')
2

One thing that hasn’t changed, a noteworthy April Fools’ joke notwithstanding, is that Python strings are immutable. Thus, the string methods return new strings, and do not modify the string on which they operate.

The old string module is still around for backwards compatibility, but it mostly acts as a front-end to the new string methods.

Two methods which have no parallel in pre-2.0 versions, although they did exist in JPython for quite some time, are startswith() and endswith(). s.startswith(t) is equivalent to s[:len(t)] == t, while s.endswith(t) is equivalent to s[-len(t):] == t.

One other method which deserves special mention is join(). The join() method of a string receives one parameter, a sequence of strings, and is equivalent to the string.join() function from the old string module, with the arguments reversed. In other words, s.join(seq) is equivalent to the old string.join(seq, s).

Garbage Collection of Cycles

The C implementation of Python uses reference counting to implement garbage collection. Every Python object maintains a count of the number of references pointing to itself, and adjusts the count as references are created or destroyed. Once the reference count reaches zero, the object is no longer accessible, since you need to have a reference to an object to access it, and if the count is zero, no references exist any longer.

Reference counting has some pleasant properties: it’s easy to understand and implement, and the resulting implementation is portable, fairly fast, and reacts well with other libraries that implement their own memory handling schemes. The major problem with reference counting is that it sometimes doesn’t realise that objects are no longer accessible, resulting in a memory leak. This happens when there are cycles of references.

Consider the simplest possible cycle, a class instance which has a reference to itself:

instance = SomeClass()
instance.myself = instance

After the above two lines of code have been executed, the reference count of instance is 2; one reference is from the variable named 'instance', and the other is from the myself attribute of the instance.

If the next line of code is del instance, what happens? The reference count of instance is decreased by 1, so it has a reference count of 1; the reference in the myself attribute still exists. Yet the instance is no longer accessible through Python code, and it could be deleted. Several objects can participate in a cycle if they have references to each other, causing all of the objects to be leaked.

Python 2.0 fixes this problem by periodically executing a cycle detection algorithm which looks for inaccessible cycles and deletes the objects involved. A new gc module provides functions to perform a garbage collection, obtain debugging statistics, and tuning the collector’s parameters.

Running the cycle detection algorithm takes some time, and therefore will result in some additional overhead. It is hoped that after we’ve gotten experience with the cycle collection from using 2.0, Python 2.1 will be able to minimize the overhead with careful tuning. It’s not yet obvious how much performance is lost, because benchmarking this is tricky and depends crucially on how often the program creates and destroys objects. The detection of cycles can be disabled when Python is compiled, if you can’t afford even a tiny speed penalty or suspect that the cycle collection is buggy, by specifying the --without-cycle-gc switch when running the configure script.

Several people tackled this problem and contributed to a solution. An early implementation of the cycle detection approach was written by Toby Kelsey. The current algorithm was suggested by Eric Tiedemann during a visit to CNRI, and Guido van Rossum and Neil Schemenauer wrote two different implementations, which were later integrated by Neil. Lots of other people offered suggestions along the way; the March 2000 archives of the python-dev mailing list contain most of the relevant discussion, especially in the threads titled “Reference cycle collection for Python” and “Finalization again”.

Other Core Changes

Various minor changes have been made to Python’s syntax and built-in functions. None of the changes are very far-reaching, but they’re handy conveniences.

Minor Language Changes

A new syntax makes it more convenient to call a given function with a tuple of arguments and/or a dictionary of keyword arguments. In Python 1.5 and earlier, you’d use the apply() built-in function: apply(f, args, kw) calls the function f() with the argument tuple args and the keyword arguments in the dictionary kw. apply() is the same in 2.0, but thanks to a patch from Greg Ewing, f(*args, **kw) is a shorter and clearer way to achieve the same effect. This syntax is symmetrical with the syntax for defining functions:

def f(*args, **kw):
    # args is a tuple of positional args,
    # kw is a dictionary of keyword args
    ...

The print statement can now have its output directed to a file-like object by following the print with >> file, similar to the redirection operator in Unix shells. Previously you’d either have to use the write() method of the file-like object, which lacks the convenience and simplicity of print, or you could assign a new value to sys.stdout and then restore the old value. For sending output to standard error, it’s much easier to write this:

print >> sys.stderr, "Warning: action field not supplied"

Modules can now be renamed on importing them, using the syntax import module as name or from module import name as othername. The patch was submitted by Thomas Wouters.

A new format style is available when using the % operator; ‘%r’ will insert the repr() of its argument. This was also added from symmetry considerations, this time for symmetry with the existing ‘%s’ format style, which inserts the str() of its argument. For example, '%r %s' % ('abc', 'abc') returns a string containing 'abc' abc.

Previously there was no way to implement a class that overrode Python’s built-in in operator and implemented a custom version. obj in seq returns true if obj is present in the sequence seq; Python computes this by simply trying every index of the sequence until either obj is found or an IndexError is encountered. Moshe Zadka contributed a patch which adds a __contains__() magic method for providing a custom implementation for in. Additionally, new built-in objects written in C can define what in means for them via a new slot in the sequence protocol.

Earlier versions of Python used a recursive algorithm for deleting objects. Deeply nested data structures could cause the interpreter to fill up the C stack and crash; Christian Tismer rewrote the deletion logic to fix this problem. On a related note, comparing recursive objects recursed infinitely and crashed; Jeremy Hylton rewrote the code to no longer crash, producing a useful result instead. For example, after this code:

a = []
b = []
a.append(a)
b.append(b)

The comparison a==b returns true, because the two recursive data structures are isomorphic. See the thread “trashcan and PR#7” in the April 2000 archives of the python-dev mailing list for the discussion leading up to this implementation, and some useful relevant links. Note that comparisons can now also raise exceptions. In earlier versions of Python, a comparison operation such as cmp(a,b) would always produce an answer, even if a user-defined __cmp__() method encountered an error, since the resulting exception would simply be silently swallowed.

Work has been done on porting Python to 64-bit Windows on the Itanium processor, mostly by Trent Mick of ActiveState. (Confusingly, sys.platform is still 'win32' on Win64 because it seems that for ease of porting, MS Visual C++ treats code as 32 bit on Itanium.) PythonWin also supports Windows CE; see the Python CE page at http://pythonce.sourceforge.net/ for more information.

Another new platform is Darwin/MacOS X; initial support for it is in Python 2.0. Dynamic loading works, if you specify “configure –with-dyld –with-suffix=.x”. Consult the README in the Python source distribution for more instructions.

An attempt has been made to alleviate one of Python’s warts, the often-confusing NameError exception when code refers to a local variable before the variable has been assigned a value. For example, the following code raises an exception on the print statement in both 1.5.2 and 2.0; in 1.5.2 a NameError exception is raised, while 2.0 raises a new UnboundLocalError exception. UnboundLocalError is a subclass of NameError, so any existing code that expects NameError to be raised should still work.

def f():
    print "i=",i
    i = i + 1
f()

Two new exceptions, TabError and IndentationError, have been introduced. They’re both subclasses of SyntaxError, and are raised when Python code is found to be improperly indented.

Changes to Built-in Functions

A new built-in, zip(seq1, seq2, ...), has been added. zip() returns a list of tuples where each tuple contains the i-th element from each of the argument sequences. The difference between zip() and map(None, seq1, seq2) is that map() pads the sequences with None if the sequences aren’t all of the same length, while zip() truncates the returned list to the length of the shortest argument sequence.

The int() and long() functions now accept an optional “base” parameter when the first argument is a string. int('123', 10) returns 123, while int('123', 16) returns 291. int(123, 16) raises a TypeError exception with the message “can’t convert non-string with explicit base”.

A new variable holding more detailed version information has been added to the sys module. sys.version_info is a tuple (major, minor, micro, level, serial) For example, in a hypothetical 2.0.1beta1, sys.version_info would be (2, 0, 1, 'beta', 1). level is a string such as "alpha", "beta", or "final" for a final release.

Dictionaries have an odd new method, setdefault(key, default), which behaves similarly to the existing get() method. However, if the key is missing, setdefault() both returns the value of default as get() would do, and also inserts it into the dictionary as the value for key. Thus, the following lines of code:

if dict.has_key( key ): return dict[key]
else:
    dict[key] = []
    return dict[key]

can be reduced to a single return dict.setdefault(key, []) statement.

The interpreter sets a maximum recursion depth in order to catch runaway recursion before filling the C stack and causing a core dump or GPF.. Previously this limit was fixed when you compiled Python, but in 2.0 the maximum recursion depth can be read and modified using sys.getrecursionlimit() and sys.setrecursionlimit(). The default value is 1000, and a rough maximum value for a given platform can be found by running a new script, Misc/find_recursionlimit.py.

Porting to 2.0

New Python releases try hard to be compatible with previous releases, and the record has been pretty good. However, some changes are considered useful enough, usually because they fix initial design decisions that turned out to be actively mistaken, that breaking backward compatibility can’t always be avoided. This section lists the changes in Python 2.0 that may cause old Python code to break.

The change which will probably break the most code is tightening up the arguments accepted by some methods. Some methods would take multiple arguments and treat them as a tuple, particularly various list methods such as append() and insert(). In earlier versions of Python, if L is a list, L.append( 1,2 ) appends the tuple (1,2) to the list. In Python 2.0 this causes a TypeError exception to be raised, with the message: ‘append requires exactly 1 argument; 2 given’. The fix is to simply add an extra set of parentheses to pass both values as a tuple: L.append( (1,2) ).

The earlier versions of these methods were more forgiving because they used an old function in Python’s C interface to parse their arguments; 2.0 modernizes them to use PyArg_ParseTuple(), the current argument parsing function, which provides more helpful error messages and treats multi-argument calls as errors. If you absolutely must use 2.0 but can’t fix your code, you can edit Objects/listobject.c and define the preprocessor symbol NO_STRICT_LIST_APPEND to preserve the old behaviour; this isn’t recommended.

Some of the functions in the socket module are still forgiving in this way. For example, socket.connect( ('hostname', 25) )() is the correct form, passing a tuple representing an IP address, but socket.connect( 'hostname', 25 )() also works. socket.connect_ex() and socket.bind() are similarly easy-going. 2.0alpha1 tightened these functions up, but because the documentation actually used the erroneous multiple argument form, many people wrote code which would break with the stricter checking. GvR backed out the changes in the face of public reaction, so for the socket module, the documentation was fixed and the multiple argument form is simply marked as deprecated; it will be tightened up again in a future Python version.

The \x escape in string literals now takes exactly 2 hex digits. Previously it would consume all the hex digits following the ‘x’ and take the lowest 8 bits of the result, so \x123456 was equivalent to \x56.

The AttributeError and NameError exceptions have a more friendly error message, whose text will be something like 'Spam' instance has no attribute 'eggs' or name 'eggs' is not defined. Previously the error message was just the missing attribute name eggs, and code written to take advantage of this fact will break in 2.0.

Some work has been done to make integers and long integers a bit more interchangeable. In 1.5.2, large-file support was added for Solaris, to allow reading files larger than 2 GiB; this made the tell() method of file objects return a long integer instead of a regular integer. Some code would subtract two file offsets and attempt to use the result to multiply a sequence or slice a string, but this raised a TypeError. In 2.0, long integers can be used to multiply or slice a sequence, and it’ll behave as you’d intuitively expect it to; 3L * 'abc' produces ‘abcabcabc’, and (0,1,2,3)[2L:4L] produces (2,3). Long integers can also be used in various contexts where previously only integers were accepted, such as in the seek() method of file objects, and in the formats supported by the % operator (%d, %i, %x, etc.). For example, "%d" % 2L**64 will produce the string 18446744073709551616.

The subtlest long integer change of all is that the str() of a long integer no longer has a trailing ‘L’ character, though repr() still includes it. The ‘L’ annoyed many people who wanted to print long integers that looked just like regular integers, since they had to go out of their way to chop off the character. This is no longer a problem in 2.0, but code which does str(longval)[:-1] and assumes the ‘L’ is there, will now lose the final digit.

Taking the repr() of a float now uses a different formatting precision than str(). repr() uses %.17g format string for C’s sprintf(), while str() uses %.12g as before. The effect is that repr() may occasionally show more decimal places than str(), for certain numbers. For example, the number 8.1 can’t be represented exactly in binary, so repr(8.1) is '8.0999999999999996', while str(8.1) is '8.1'.

The -X command-line option, which turned all standard exceptions into strings instead of classes, has been removed; the standard exceptions will now always be classes. The exceptions module containing the standard exceptions was translated from Python to a built-in C module, written by Barry Warsaw and Fredrik Lundh.

Extending/Embedding Changes

Some of the changes are under the covers, and will only be apparent to people writing C extension modules or embedding a Python interpreter in a larger application. If you aren’t dealing with Python’s C API, you can safely skip this section.

The version number of the Python C API was incremented, so C extensions compiled for 1.5.2 must be recompiled in order to work with 2.0. On Windows, it’s not possible for Python 2.0 to import a third party extension built for Python 1.5.x due to how Windows DLLs work, so Python will raise an exception and the import will fail.

Users of Jim Fulton’s ExtensionClass module will be pleased to find out that hooks have been added so that ExtensionClasses are now supported by isinstance() and issubclass(). This means you no longer have to remember to write code such as if type(obj) == myExtensionClass, but can use the more natural if isinstance(obj, myExtensionClass).

The Python/importdl.c file, which was a mass of #ifdefs to support dynamic loading on many different platforms, was cleaned up and reorganised by Greg Stein. importdl.c is now quite small, and platform-specific code has been moved into a bunch of Python/dynload_*.c files. Another cleanup: there were also a number of my*.h files in the Include/ directory that held various portability hacks; they’ve been merged into a single file, Include/pyport.h.

Vladimir Marangozov’s long-awaited malloc restructuring was completed, to make it easy to have the Python interpreter use a custom allocator instead of C’s standard malloc(). For documentation, read the comments in Include/pymem.h and Include/objimpl.h. For the lengthy discussions during which the interface was hammered out, see the Web archives of the ‘patches’ and ‘python-dev’ lists at python.org.

Recent versions of the GUSI development environment for MacOS support POSIX threads. Therefore, Python’s POSIX threading support now works on the Macintosh. Threading support using the user-space GNU pth library was also contributed.

Threading support on Windows was enhanced, too. Windows supports thread locks that use kernel objects only in case of contention; in the common case when there’s no contention, they use simpler functions which are an order of magnitude faster. A threaded version of Python 1.5.2 on NT is twice as slow as an unthreaded version; with the 2.0 changes, the difference is only 10%. These improvements were contributed by Yakov Markovitch.

Python 2.0’s source now uses only ANSI C prototypes, so compiling Python now requires an ANSI C compiler, and can no longer be done using a compiler that only supports K&R C.

Previously the Python virtual machine used 16-bit numbers in its bytecode, limiting the size of source files. In particular, this affected the maximum size of literal lists and dictionaries in Python source; occasionally people who are generating Python code would run into this limit. A patch by Charles G. Waldman raises the limit from 2^16 to 2^{32}.

Three new convenience functions intended for adding constants to a module’s dictionary at module initialization time were added: PyModule_AddObject(), PyModule_AddIntConstant(), and PyModule_AddStringConstant(). Each of these functions takes a module object, a null-terminated C string containing the name to be added, and a third argument for the value to be assigned to the name. This third argument is, respectively, a Python object, a C long, or a C string.

A wrapper API was added for Unix-style signal handlers. PyOS_getsig() gets a signal handler and PyOS_setsig() will set a new handler.

Distutils: Making Modules Easy to Install

Before Python 2.0, installing modules was a tedious affair – there was no way to figure out automatically where Python is installed, or what compiler options to use for extension modules. Software authors had to go through an arduous ritual of editing Makefiles and configuration files, which only really work on Unix and leave Windows and MacOS unsupported. Python users faced wildly differing installation instructions which varied between different extension packages, which made administering a Python installation something of a chore.

The SIG for distribution utilities, shepherded by Greg Ward, has created the Distutils, a system to make package installation much easier. They form the distutils package, a new part of Python’s standard library. In the best case, installing a Python module from source will require the same steps: first you simply mean unpack the tarball or zip archive, and the run “python setup.py install”. The platform will be automatically detected, the compiler will be recognized, C extension modules will be compiled, and the distribution installed into the proper directory. Optional command-line arguments provide more control over the installation process, the distutils package offers many places to override defaults – separating the build from the install, building or installing in non-default directories, and more.

In order to use the Distutils, you need to write a setup.py script. For the simple case, when the software contains only .py files, a minimal setup.py can be just a few lines long:

from distutils.core import setup
setup (name = "foo", version = "1.0",
       py_modules = ["module1", "module2"])

The setup.py file isn’t much more complicated if the software consists of a few packages:

from distutils.core import setup
setup (name = "foo", version = "1.0",
       packages = ["package", "package.subpackage"])

A C extension can be the most complicated case; here’s an example taken from the PyXML package:

from distutils.core import setup, Extension

expat_extension = Extension('xml.parsers.pyexpat',
     define_macros = [('XML_NS', None)],
     include_dirs = [ 'extensions/expat/xmltok',
                      'extensions/expat/xmlparse' ],
     sources = [ 'extensions/pyexpat.c',
                 'extensions/expat/xmltok/xmltok.c',
                 'extensions/expat/xmltok/xmlrole.c', ]
       )
setup (name = "PyXML", version = "0.5.4",
       ext_modules =[ expat_extension ] )

The Distutils can also take care of creating source and binary distributions. The “sdist” command, run by “python setup.py sdist’, builds a source distribution such as foo-1.0.tar.gz. Adding new commands isn’t difficult, “bdist_rpm” and “bdist_wininst” commands have already been contributed to create an RPM distribution and a Windows installer for the software, respectively. Commands to create other distribution formats such as Debian packages and Solaris .pkg files are in various stages of development.

All this is documented in a new manual, Distributing Python Modules, that joins the basic set of Python documentation.

XML Modules

Python 1.5.2 included a simple XML parser in the form of the xmllib module, contributed by Sjoerd Mullender. Since 1.5.2’s release, two different interfaces for processing XML have become common: SAX2 (version 2 of the Simple API for XML) provides an event-driven interface with some similarities to xmllib, and the DOM (Document Object Model) provides a tree-based interface, transforming an XML document into a tree of nodes that can be traversed and modified. Python 2.0 includes a SAX2 interface and a stripped-down DOM interface as part of the xml package. Here we will give a brief overview of these new interfaces; consult the Python documentation or the source code for complete details. The Python XML SIG is also working on improved documentation.

SAX2 Support

SAX defines an event-driven interface for parsing XML. To use SAX, you must write a SAX handler class. Handler classes inherit from various classes provided by SAX, and override various methods that will then be called by the XML parser. For example, the startElement() and endElement() methods are called for every starting and end tag encountered by the parser, the characters() method is called for every chunk of character data, and so forth.

The advantage of the event-driven approach is that the whole document doesn’t have to be resident in memory at any one time, which matters if you are processing really huge documents. However, writing the SAX handler class can get very complicated if you’re trying to modify the document structure in some elaborate way.

For example, this little example program defines a handler that prints a message for every starting and ending tag, and then parses the file hamlet.xml using it:

from xml import sax

class SimpleHandler(sax.ContentHandler):
    def startElement(self, name, attrs):
        print 'Start of element:', name, attrs.keys()

    def endElement(self, name):
        print 'End of element:', name

# Create a parser object
parser = sax.make_parser()

# Tell it what handler to use
handler = SimpleHandler()
parser.setContentHandler( handler )

# Parse a file!
parser.parse( 'hamlet.xml' )

For more information, consult the Python documentation, or the XML HOWTO at http://pyxml.sourceforge.net/topics/howto/xml-howto.html.

DOM Support

The Document Object Model is a tree-based representation for an XML document. A top-level Document instance is the root of the tree, and has a single child which is the top-level Element instance. This Element has children nodes representing character data and any sub-elements, which may have further children of their own, and so forth. Using the DOM you can traverse the resulting tree any way you like, access element and attribute values, insert and delete nodes, and convert the tree back into XML.

The DOM is useful for modifying XML documents, because you can create a DOM tree, modify it by adding new nodes or rearranging subtrees, and then produce a new XML document as output. You can also construct a DOM tree manually and convert it to XML, which can be a more flexible way of producing XML output than simply writing <tag1>…</tag1> to a file.

The DOM implementation included with Python lives in the xml.dom.minidom module. It’s a lightweight implementation of the Level 1 DOM with support for XML namespaces. The parse() and parseString() convenience functions are provided for generating a DOM tree:

from xml.dom import minidom
doc = minidom.parse('hamlet.xml')

doc is a Document instance. Document, like all the other DOM classes such as Element and Text, is a subclass of the Node base class. All the nodes in a DOM tree therefore support certain common methods, such as toxml() which returns a string containing the XML representation of the node and its children. Each class also has special methods of its own; for example, Element and Document instances have a method to find all child elements with a given tag name. Continuing from the previous 2-line example:

perslist = doc.getElementsByTagName( 'PERSONA' )
print perslist[0].toxml()
print perslist[1].toxml()

For the Hamlet XML file, the above few lines output:

<PERSONA>CLAUDIUS, king of Denmark. </PERSONA>
<PERSONA>HAMLET, son to the late, and nephew to the present king.</PERSONA>

The root element of the document is available as doc.documentElement, and its children can be easily modified by deleting, adding, or removing nodes:

root = doc.documentElement

# Remove the first child
root.removeChild( root.childNodes[0] )

# Move the new first child to the end
root.appendChild( root.childNodes[0] )

# Insert the new first child (originally,
# the third child) before the 20th child.
root.insertBefore( root.childNodes[0], root.childNodes[20] )

Again, I will refer you to the Python documentation for a complete listing of the different Node classes and their various methods.

Relationship to PyXML

The XML Special Interest Group has been working on XML-related Python code for a while. Its code distribution, called PyXML, is available from the SIG’s Web pages at https://www.python.org/community/sigs/current/xml-sig. The PyXML distribution also used the package name xml. If you’ve written programs that used PyXML, you’re probably wondering about its compatibility with the 2.0 xml package.

The answer is that Python 2.0’s xml package isn’t compatible with PyXML, but can be made compatible by installing a recent version PyXML. Many applications can get by with the XML support that is included with Python 2.0, but more complicated applications will require that the full PyXML package will be installed. When installed, PyXML versions 0.6.0 or greater will replace the xml package shipped with Python, and will be a strict superset of the standard package, adding a bunch of additional features. Some of the additional features in PyXML include:

4DOM, a full DOM implementation from FourThought, Inc.

The xmlproc validating parser, written by Lars Marius Garshol.

The sgmlop parser accelerator module, written by Fredrik Lundh.

Module changes

Lots of improvements and bugfixes were made to Python’s extensive standard library; some of the affected modules include readline, ConfigParser, cgi, calendar, posix, readline, xmllib, aifc, chunk, wave, random, shelve, and nntplib. Consult the CVS logs for the exact patch-by-patch details.

Brian Gallew contributed OpenSSL support for the socket module. OpenSSL is an implementation of the Secure Socket Layer, which encrypts the data being sent over a socket. When compiling Python, you can edit Modules/Setup to include SSL support, which adds an additional function to the socket module: socket.ssl(socket, keyfile, certfile), which takes a socket object and returns an SSL socket. The httplib and urllib modules were also changed to support https:// URLs, though no one has implemented FTP or SMTP over SSL.

The httplib module has been rewritten by Greg Stein to support HTTP/1.1. Backward compatibility with the 1.5 version of httplib is provided, though using HTTP/1.1 features such as pipelining will require rewriting code to use a different set of interfaces.

The Tkinter module now supports Tcl/Tk version 8.1, 8.2, or 8.3, and support for the older 7.x versions has been dropped. The Tkinter module now supports displaying Unicode strings in Tk widgets. Also, Fredrik Lundh contributed an optimization which makes operations like create_line and create_polygon much faster, especially when using lots of coordinates.

The curses module has been greatly extended, starting from Oliver Andrich’s enhanced version, to provide many additional functions from ncurses and SYSV curses, such as colour, alternative character set support, pads, and mouse support. This means the module is no longer compatible with operating systems that only have BSD curses, but there don’t seem to be any currently maintained OSes that fall into this category.

As mentioned in the earlier discussion of 2.0’s Unicode support, the underlying implementation of the regular expressions provided by the re module has been changed. SRE, a new regular expression engine written by Fredrik Lundh and partially funded by Hewlett Packard, supports matching against both 8-bit strings and Unicode strings.

New modules

A number of new modules were added. We’ll simply list them with brief descriptions; consult the 2.0 documentation for the details of a particular module.

atexit: For registering functions to be called before the Python interpreter exits. Code that currently sets sys.exitfunc directly should be changed to use the atexit module instead, importing atexit and calling atexit.register() with the function to be called on exit. (Contributed by Skip Montanaro.)

codecs, encodings, unicodedata: Added as part of the new Unicode support.

filecmp: Supersedes the old cmp, cmpcache and dircmp modules, which have now become deprecated. (Contributed by Gordon MacMillan and Moshe Zadka.)

gettext: This module provides internationalization (I18N) and localization (L10N) support for Python programs by providing an interface to the GNU gettext message catalog library. (Integrated by Barry Warsaw, from separate contributions by Martin von Löwis, Peter Funk, and James Henstridge.)

linuxaudiodev: Support for the /dev/audio device on Linux, a twin to the existing sunaudiodev module. (Contributed by Peter Bosch, with fixes by Jeremy Hylton.)

mmap: An interface to memory-mapped files on both Windows and Unix. A file’s contents can be mapped directly into memory, at which point it behaves like a mutable string, so its contents can be read and modified. They can even be passed to functions that expect ordinary strings, such as the re module. (Contributed by Sam Rushing, with some extensions by A.M. Kuchling.)

pyexpat: An interface to the Expat XML parser. (Contributed by Paul Prescod.)

robotparser: Parse a robots.txt file, which is used for writing Web spiders that politely avoid certain areas of a Web site. The parser accepts the contents of a robots.txt file, builds a set of rules from it, and can then answer questions about the fetchability of a given URL. (Contributed by Skip Montanaro.)

tabnanny: A module/script to check Python source code for ambiguous indentation. (Contributed by Tim Peters.)

UserString: A base class useful for deriving objects that behave like strings.

webbrowser: A module that provides a platform independent way to launch a web browser on a specific URL. For each platform, various browsers are tried in a specific order. The user can alter which browser is launched by setting the BROWSER environment variable. (Originally inspired by Eric S. Raymond’s patch to urllib which added similar functionality, but the final module comes from code originally implemented by Fred Drake as Tools/idle/BrowserControl.py, and adapted for the standard library by Fred.)

_winreg: An interface to the Windows registry. _winreg is an adaptation of functions that have been part of PythonWin since 1995, but has now been added to the core distribution, and enhanced to support Unicode. _winreg was written by Bill Tutt and Mark Hammond.

zipfile: A module for reading and writing ZIP-format archives. These are archives produced by PKZIP on DOS/Windows or zip on Unix, not to be confused with gzip-format files (which are supported by the gzip module) (Contributed by James C. Ahlstrom.)

imputil: A module that provides a simpler way for writing customized import hooks, in comparison to the existing ihooks module. (Implemented by Greg Stein, with much discussion on python-dev along the way.)

IDLE Improvements

IDLE is the official Python cross-platform IDE, written using Tkinter. Python 2.0 includes IDLE 0.6, which adds a number of new features and improvements. A partial list:

UI improvements and optimizations, especially in the area of syntax highlighting and auto-indentation.

The class browser now shows more information, such as the top level functions in a module.

Tab width is now a user settable option. When opening an existing Python file, IDLE automatically detects the indentation conventions, and adapts.

There is now support for calling browsers on various platforms, used to open the Python documentation in a browser.

IDLE now has a command line, which is largely similar to the vanilla Python interpreter.

Call tips were added in many places.

IDLE can now be installed as a package.

In the editor window, there is now a line/column bar at the bottom.

Three new keystroke commands: Check module (Alt-F5), Import module (F5) and Run script (Ctrl-F5).

Deleted and Deprecated Modules

A few modules have been dropped because they’re obsolete, or because there are now better ways to do the same thing. The stdwin module is gone; it was for a platform-independent windowing toolkit that’s no longer developed.

A number of modules have been moved to the lib-old subdirectory: cmp, cmpcache, dircmp, dump, find, grep, packmail, poly, util, whatsound, zmod. If you have code which relies on a module that’s been moved to lib-old, you can simply add that directory to sys.path to get them back, but you’re encouraged to update any code that uses these modules.

Acknowledgements

The authors would like to thank the following people for offering suggestions on various drafts of this article: David Bolen, Mark Hammond, Gregg Hauser, Jeremy Hylton, Fredrik Lundh, Detlef Lannert, Aahz Maruch, Skip Montanaro, Vladimir Marangozov, Tobias Polzin, Guido van Rossum, Neil Schemenauer, and Russ Schmidt.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬의 새로운 기능 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬의 새로운 기능 »

|

Changelog

Python 3.7.17 final

Release date: 2023-06-05

Security

gh-103142 [https://github.com/python/cpython/issues/103142]: The version of OpenSSL used in our binary builds has been upgraded to 1.1.1u to address several CVEs.

gh-99889 [https://github.com/python/cpython/issues/99889]: Fixed a security in flaw in uu.decode() that could allow for directory traversal based on the input if no out_file was specified.

gh-104049 [https://github.com/python/cpython/issues/104049]: Do not expose the local on-disk location in directory indexes produced by http.client.SimpleHTTPRequestHandler.

gh-102153 [https://github.com/python/cpython/issues/102153]: urllib.parse.urlsplit() now strips leading C0 control and space characters following the specification for URLs defined by WHATWG in response to CVE-2023-24329. Patch by Illia Volochii.

gh-101727 [https://github.com/python/cpython/issues/101727]: Updated the OpenSSL version used in Windows and macOS binary release builds to 1.1.1t to address CVE-2023-0286, CVE-2022-4303, and CVE-2022-4303 per the OpenSSL 2023-02-07 security advisory [https://www.openssl.org/news/secadv/20230207.txt].

gh-101283 [https://github.com/python/cpython/issues/101283]: subprocess.Popen now uses a safer approach to find cmd.exe when launching with shell=True. Patch by Eryk Sun, based on a patch by Oleg Iarygin.

Library

gh-101997 [https://github.com/python/cpython/issues/101997]: Upgrade pip wheel bundled with ensurepip (pip 23.0.1)

Build

gh-102306 [https://github.com/python/cpython/issues/102306]: Avoid GHA CI macOS test_posix failure by using the appropriate macOS SDK.

Windows

gh-100180 [https://github.com/python/cpython/issues/100180]: Update Windows installer to OpenSSL 1.1.1s

Python 3.7.16 final

Release date: 2022-12-06

Security

gh-100001 [https://github.com/python/cpython/issues/100001]: python -m http.server no longer allows terminal control characters sent within a garbage request to be printed to the stderr server log.

This is done by changing the http.server BaseHTTPRequestHandler .log_message method to replace control characters with a \xHH hex escape before printing.

gh-98433 [https://github.com/python/cpython/issues/98433]: The IDNA codec decoder used on DNS hostnames by socket or asyncio related name resolution functions no longer involves a quadratic algorithm. This prevents a potential CPU denial of service if an out-of-spec excessive length hostname involving bidirectional characters were decoded. Some protocols such as urllib http 3xx redirects potentially allow for an attacker to supply such a name.

gh-98739 [https://github.com/python/cpython/issues/98739]: Update bundled libexpat to 2.5.0

gh-98517 [https://github.com/python/cpython/issues/98517]: Port XKCP’s fix for the buffer overflows in SHA-3 (CVE-2022-37454).

gh-68966 [https://github.com/python/cpython/issues/68966]: The deprecated mailcap module now refuses to inject unsafe text (filenames, MIME types, parameters) into shell commands. Instead of using such text, it will warn and act as if a match was not found (or for test commands, as if the test failed).

Python 3.7.15 final

Release date: 2022-10-10

Security

gh-97616 [https://github.com/python/cpython/issues/97616]: Fix multiplying a list by an integer (list *= int): detect the integer overflow when the new allocated length is close to the maximum size. Issue reported by Jordan Limor. Patch by Victor Stinner.

gh-97612 [https://github.com/python/cpython/issues/97612]: Fix a shell code injection vulnerability in the get-remote-certificate.py example script. The script no longer uses a shell to run openssl commands. Issue reported and initial fix by Caleb Shortt. Patch by Victor Stinner.

Core and Builtins

gh-96848 [https://github.com/python/cpython/issues/96848]: Fix command line parsing: reject -X int_max_str_digits option with no value (invalid) when the PYTHONINTMAXSTRDIGITS environment variable is set to a valid limit. Patch by Victor Stinner.

gh-95778 [https://github.com/python/cpython/issues/95778]: When ValueError is raised if an integer is larger than the limit, mention the sys.set_int_max_str_digits() function in the error message. Patch by Victor Stinner.

Library

gh-97005 [https://github.com/python/cpython/issues/97005]: Update bundled libexpat to 2.4.9

Windows

gh-96577 [https://github.com/python/cpython/issues/96577]: Fixes a potential buffer overrun in msilib.

Python 3.7.14 final

Release date: 2022-09-06

Security

gh-95778 [https://github.com/python/cpython/issues/95778]: Converting between int and str in bases other than 2 (binary), 4, 8 (octal), 16 (hexadecimal), or 32 such as base 10 (decimal) now raises a ValueError if the number of digits in string form is above a limit to avoid potential denial of service attacks due to the algorithmic complexity. This is a mitigation for CVE-2020-10735 [https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2020-10735].

This new limit can be configured or disabled by environment variable, command line flag, or sys APIs. See the integer string conversion length limitation documentation. The default limit is 4300 digits in string form.

Patch by Gregory P. Smith [Google] and Christian Heimes [Red Hat] with feedback from Victor Stinner, Thomas Wouters, Steve Dower, Ned Deily, and Mark Dickinson.

gh-87389 [https://github.com/python/cpython/issues/87389]: http.server: Fix an open redirection vulnerability in the HTTP server when an URI path starts with //. Vulnerability discovered, and initial fix proposed, by Hamza Avvan.

Core and Builtins

gh-93065 [https://github.com/python/cpython/issues/93065]: Fix contextvars HAMT implementation to handle iteration over deep trees.

The bug was discovered and fixed by Eli Libman. See MagicStack/immutables#84 [https://github.com/MagicStack/immutables/issues/84] for more details.

Library

bpo-36073 [https://bugs.python.org/issue?@action=redirect&bpo=36073]: Raise ProgrammingError instead of segfaulting on recursive usage of cursors in sqlite3 converters. Patch by Sergey Fedoseev.

Documentation

gh-91888 [https://github.com/python/cpython/issues/91888]: Add a new gh role to the documentation to link to GitHub issues.

bpo-47138 [https://bugs.python.org/issue?@action=redirect&bpo=47138]: Pin Jinja to a version compatible with Sphinx version 2.3.1.

Tests

gh-94208 [https://github.com/python/cpython/issues/94208]: test_ssl is now checking for supported TLS version and protocols in more tests.

bpo-47016 [https://bugs.python.org/issue?@action=redirect&bpo=47016]: Create a GitHub Actions workflow for verifying bundled pip and setuptools. Patch by Illia Volochii and Adam Turner.

bpo-41306 [https://bugs.python.org/issue?@action=redirect&bpo=41306]: Fixed a failure in test_tk.test_widgets.ScaleTest happening when executing the test with Tk 8.6.10.

Windows

bpo-47194 [https://bugs.python.org/issue?@action=redirect&bpo=47194]: Update zlib to v1.2.12 to resolve CVE-2018-25032.

Python 3.7.13 final

Release date: 2022-03-16

Library

bpo-46985 [https://bugs.python.org/issue?@action=redirect&bpo=46985]: Upgrade pip wheel bundled with ensurepip (pip 22.0.4)

bpo-46932 [https://bugs.python.org/issue?@action=redirect&bpo=46932]: Update bundled libexpat to 2.4.7

bpo-46811 [https://bugs.python.org/issue?@action=redirect&bpo=46811]: Make test suite support Expat >=2.4.5

bpo-46784 [https://bugs.python.org/issue?@action=redirect&bpo=46784]: Fix libexpat symbols collisions with user dynamically loaded or statically linked libexpat in embedded Python.

bpo-46756 [https://bugs.python.org/issue?@action=redirect&bpo=46756]: Fix a bug in urllib.request.HTTPPasswordMgr.find_user_password() and urllib.request.HTTPPasswordMgrWithPriorAuth.is_authenticated() which allowed to bypass authorization. For example, access to URI example.org/foobar was allowed if the user was authorized for URI example.org/foo.

Build

bpo-47024 [https://bugs.python.org/issue?@action=redirect&bpo=47024]: Update Windows builds and macOS installer build to use OpenSSL 1.1.1n.

bpo-45405 [https://bugs.python.org/issue?@action=redirect&bpo=45405]: Prevent internal configure error when running configure with recent versions of clang. Patch by David Bohman.

Windows

bpo-44549 [https://bugs.python.org/issue?@action=redirect&bpo=44549]: Update bzip2 to 1.0.8 in Windows builds to mitigate CVE-2016-3189 and CVE-2019-12900

bpo-46948 [https://bugs.python.org/issue?@action=redirect&bpo=46948]: Prevent CVE-2022-26488 by ensuring the Add to PATH option in the Windows installer uses the correct path when being repaired.

Python 3.7.12 final

Release date: 2021-09-03

Security

bpo-44394 [https://bugs.python.org/issue?@action=redirect&bpo=44394]: Update the vendored copy of libexpat to 2.4.1 (from 2.2.8) to get the fix for the CVE-2013-0340 “Billion Laughs” vulnerability. This copy is most used on Windows and macOS.

bpo-43124 [https://bugs.python.org/issue?@action=redirect&bpo=43124]: Made the internal putcmd function in smtplib sanitize input for presence of \r and \n characters to avoid (unlikely) command injection.

Library

bpo-45001 [https://bugs.python.org/issue?@action=redirect&bpo=45001]: Made email date parsing more robust against malformed input, namely a whitespace-only Date: header. Patch by Wouter Bolsterlee.

Python 3.7.11 final

Release date: 2021-06-28

Security

bpo-44022 [https://bugs.python.org/issue?@action=redirect&bpo=44022]: http.client now avoids infinitely reading potential HTTP headers after a 100 Continue status response from the server.

bpo-43882 [https://bugs.python.org/issue?@action=redirect&bpo=43882]: The presence of newline or tab characters in parts of a URL could allow some forms of attacks.

Following the controlling specification for URLs defined by WHATWG urllib.parse() now removes ASCII newlines and tabs from URLs, preventing such attacks.

bpo-42988 [https://bugs.python.org/issue?@action=redirect&bpo=42988]: CVE-2021-3426: Remove the getfile feature of the pydoc module which could be abused to read arbitrary files on the disk (directory traversal vulnerability). Moreover, even source code of Python modules can contain sensitive data like passwords. Vulnerability reported by David Schwörer.

bpo-43285 [https://bugs.python.org/issue?@action=redirect&bpo=43285]: ftplib no longer trusts the IP address value returned from the server in response to the PASV command by default. This prevents a malicious FTP server from using the response to probe IPv4 address and port combinations on the client network.

Code that requires the former vulnerable behavior may set a trust_server_pasv_ipv4_address attribute on their ftplib.FTP instances to True to re-enable it.

bpo-43075 [https://bugs.python.org/issue?@action=redirect&bpo=43075]: Fix Regular Expression Denial of Service (ReDoS) vulnerability in urllib.request.AbstractBasicAuthHandler. The ReDoS-vulnerable regex has quadratic worst-case complexity and it allows cause a denial of service when identifying crafted invalid RFCs. This ReDoS issue is on the client side and needs remote attackers to control the HTTP server.

Core and Builtins

bpo-43660 [https://bugs.python.org/issue?@action=redirect&bpo=43660]: Fix crash that happens when replacing sys.stderr with a callable that can remove the object while an exception is being printed. Patch by Pablo Galindo.

Tests

bpo-41561 [https://bugs.python.org/issue?@action=redirect&bpo=41561]: Add workaround for Ubuntu’s custom OpenSSL security level policy.

Python 3.7.10 final

Release date: 2021-02-15

Security

bpo-42967 [https://bugs.python.org/issue?@action=redirect&bpo=42967]: Fix web cache poisoning vulnerability by defaulting the query args separator to &, and allowing the user to choose a custom separator.

bpo-42938 [https://bugs.python.org/issue?@action=redirect&bpo=42938]: Avoid static buffers when computing the repr of ctypes.c_double and ctypes.c_longdouble values.

bpo-42103 [https://bugs.python.org/issue?@action=redirect&bpo=42103]: Prevented potential DoS attack via CPU and RAM exhaustion when processing malformed Apple Property List files in binary format.

bpo-42051 [https://bugs.python.org/issue?@action=redirect&bpo=42051]: The plistlib module no longer accepts entity declarations in XML plist files to avoid XML vulnerabilities. This should not affect users as entity declarations are not used in regular plist files.

bpo-40791 [https://bugs.python.org/issue?@action=redirect&bpo=40791]: Add volatile to the accumulator variable in hmac.compare_digest, making constant-time-defeating optimizations less likely.

Library

bpo-42103 [https://bugs.python.org/issue?@action=redirect&bpo=42103]: InvalidFileException and RecursionError are now the only errors caused by loading malformed binary Plist file (previously ValueError and TypeError could be raised in some specific cases).

bpo-41976 [https://bugs.python.org/issue?@action=redirect&bpo=41976]: Fixed a bug that was causing ctypes.util.find_library() to return None when triying to locate a library in an environment when gcc>=9 is available and ldconfig is not. Patch by Pablo Galindo

Documentation

bpo-17140 [https://bugs.python.org/issue?@action=redirect&bpo=17140]: Add documentation for the multiprocessing.pool.ThreadPool class.

Tests

bpo-42794 [https://bugs.python.org/issue?@action=redirect&bpo=42794]: Update test_nntplib to use offical group name of news.aioe.org for testing. Patch by Dong-hee Na.

bpo-41944 [https://bugs.python.org/issue?@action=redirect&bpo=41944]: Tests for CJK codecs no longer call eval() on content received via HTTP.

Python 3.7.9 final

Release date: 2020-08-15

Security

bpo-41304 [https://bugs.python.org/issue?@action=redirect&bpo=41304]: Fixes python3x._pth being ignored on Windows, caused by the fix for bpo-29778 [https://bugs.python.org/issue?@action=redirect&bpo=29778] (CVE-2020-15801).

bpo-29778 [https://bugs.python.org/issue?@action=redirect&bpo=29778]: Ensure python3.dll is loaded from correct locations when Python is embedded (CVE-2020-15523).

bpo-41004 [https://bugs.python.org/issue?@action=redirect&bpo=41004]: CVE-2020-14422: The __hash__() methods of ipaddress.IPv4Interface and ipaddress.IPv6Interface incorrectly generated constant hash values of 32 and 128 respectively. This resulted in always causing hash collisions. The fix uses hash() to generate hash values for the tuple of (address, mask length, network address).

bpo-39603 [https://bugs.python.org/issue?@action=redirect&bpo=39603]: Prevent http header injection by rejecting control characters in http.client.putrequest(…).

Core and Builtins

bpo-33786 [https://bugs.python.org/issue?@action=redirect&bpo=33786]: Fix asynchronous generators to handle GeneratorExit in athrow() correctly

Library

bpo-41288 [https://bugs.python.org/issue?@action=redirect&bpo=41288]: Unpickling invalid NEWOBJ_EX opcode with the C implementation raises now UnpicklingError instead of crashing.

bpo-39017 [https://bugs.python.org/issue?@action=redirect&bpo=39017]: Avoid infinite loop when reading specially crafted TAR files using the tarfile module (CVE-2019-20907).

bpo-41235 [https://bugs.python.org/issue?@action=redirect&bpo=41235]: Fix the error handling in ssl.SSLContext.load_dh_params().

macOS

bpo-41100 [https://bugs.python.org/issue?@action=redirect&bpo=41100]: Additional fixes for testing on macOS 11 Big Sur Intel. Note: macOS 11 is not yet released, this release of Python is not fully supported on 11.0, and not all tests pass.

Python 3.7.8 final

Release date: 2020-06-27

Tests

bpo-41009 [https://bugs.python.org/issue?@action=redirect&bpo=41009]: Fix use of support.require_{linux|mac|freebsd}_version() decorators as class decorator.

macOS

bpo-41100 [https://bugs.python.org/issue?@action=redirect&bpo=41100]: Fix configure error when building on macOS 11. Note that 3.7.8 was released shortly after the first developer preview of macOS 11 (Big Sur); there are other known issues with building and running on the developer preview. Big Sur is expected to be fully supported in a future bugfix release of Python 3.8.x and with 3.9.0.

Python 3.7.8 release candidate 1

Release date: 2020-06-17

Security

bpo-39073 [https://bugs.python.org/issue?@action=redirect&bpo=39073]: Disallow CR or LF in email.headerregistry.Address arguments to guard against header injection attacks.

bpo-38576 [https://bugs.python.org/issue?@action=redirect&bpo=38576]: Disallow control characters in hostnames in http.client, addressing CVE-2019-18348. Such potentially malicious header injection URLs now cause a InvalidURL to be raised.

bpo-39503 [https://bugs.python.org/issue?@action=redirect&bpo=39503]: CVE-2020-8492: The AbstractBasicAuthHandler class of the urllib.request module uses an inefficient regular expression which can be exploited by an attacker to cause a denial of service. Fix the regex to prevent the catastrophic backtracking. Vulnerability reported by Ben Caller and Matt Schwager.

Core and Builtins

bpo-40663 [https://bugs.python.org/issue?@action=redirect&bpo=40663]: Correctly generate annotations where parentheses are omitted but required (e.g: Type[(str, int, *other))].

bpo-40417 [https://bugs.python.org/issue?@action=redirect&bpo=40417]: Fix imp module deprecation warning when PyImport_ReloadModule is called. Patch by Robert Rouhani.

bpo-20526 [https://bugs.python.org/issue?@action=redirect&bpo=20526]: Fix PyThreadState_Clear(). PyThreadState.frame is a borrowed reference, not a strong reference: PyThreadState_Clear() must not call Py_CLEAR(tstate->frame).

bpo-38894 [https://bugs.python.org/issue?@action=redirect&bpo=38894]: Fix a bug that was causing incomplete results when calling pathlib.Path.glob in the presence of symlinks that point to files where the user does not have read access. Patch by Pablo Galindo and Matt Wozniski.

bpo-39871 [https://bugs.python.org/issue?@action=redirect&bpo=39871]: Fix a possible SystemError in math.{atan2,copysign,remainder}() when the first argument cannot be converted to a float. Patch by Zachary Spytz.

bpo-39520 [https://bugs.python.org/issue?@action=redirect&bpo=39520]: Fix unparsing of ext slices with no items (foo[:,]). Patch by Batuhan Taskaya.

bpo-24048 [https://bugs.python.org/issue?@action=redirect&bpo=24048]: Save the live exception during import.c’s remove_module().

bpo-22490 [https://bugs.python.org/issue?@action=redirect&bpo=22490]: Don’t leak environment variable __PYVENV_LAUNCHER__ into the interpreter session on macOS.

Library

bpo-40448 [https://bugs.python.org/issue?@action=redirect&bpo=40448]: ensurepip now disables the use of pip cache when installing the bundled versions of pip and setuptools. Patch by Krzysztof Konopko.

bpo-40807 [https://bugs.python.org/issue?@action=redirect&bpo=40807]: Stop codeop._maybe_compile, used by code.InteractiveInterpreter (and IDLE). from from emitting each warning three times.

bpo-38488 [https://bugs.python.org/issue?@action=redirect&bpo=38488]: Update ensurepip to install pip 20.1.1 and setuptools 47.1.0.

bpo-40767 [https://bugs.python.org/issue?@action=redirect&bpo=40767]: webbrowser now properly finds the default browser in pure Wayland systems by checking the WAYLAND_DISPLAY environment variable. Patch contributed by Jérémy Attali.

bpo-30008 [https://bugs.python.org/issue?@action=redirect&bpo=30008]: Fix ssl code to be compatible with OpenSSL 1.1.x builds that use no-deprecated and --api=1.1.0.

bpo-25872 [https://bugs.python.org/issue?@action=redirect&bpo=25872]: linecache could crash with a KeyError when accessed from multiple threads. Fix by Michael Graczyk.

bpo-40515 [https://bugs.python.org/issue?@action=redirect&bpo=40515]: The ssl and hashlib modules now actively check that OpenSSL is build with thread support. Python 3.7.0 made thread support mandatory and no longer works safely with a no-thread builds.

bpo-13097 [https://bugs.python.org/issue?@action=redirect&bpo=13097]: ctypes now raises an ArgumentError when a callback is invoked with more than 1024 arguments.

bpo-40559 [https://bugs.python.org/issue?@action=redirect&bpo=40559]: Fix possible memory leak in the C implementation of asyncio.Task.

bpo-40457 [https://bugs.python.org/issue?@action=redirect&bpo=40457]: The ssl module now support OpenSSL builds without TLS 1.0 and 1.1 methods.

bpo-40459 [https://bugs.python.org/issue?@action=redirect&bpo=40459]: platform.win32_ver() now produces correct ptype strings instead of empty strings.

bpo-40138 [https://bugs.python.org/issue?@action=redirect&bpo=40138]: Fix the Windows implementation of os.waitpid() for exit code larger than INT_MAX >> 8. The exit status is now interpreted as an unsigned number.

bpo-39942 [https://bugs.python.org/issue?@action=redirect&bpo=39942]: Set “__main__” as the default module name when “__name__” is missing in typing.TypeVar. Patch by Weipeng Hong.

bpo-40287 [https://bugs.python.org/issue?@action=redirect&bpo=40287]: Fixed SpooledTemporaryFile.seek() to return the position.

bpo-40196 [https://bugs.python.org/issue?@action=redirect&bpo=40196]: Fix a bug in the symtable module that was causing incorrectly report global variables as local. Patch by Pablo Galindo.

bpo-40126 [https://bugs.python.org/issue?@action=redirect&bpo=40126]: Fixed reverting multiple patches in unittest.mock. Patcher’s __exit__() is now never called if its __enter__() is failed. Returning true from __exit__() silences now the exception.

bpo-40089 [https://bugs.python.org/issue?@action=redirect&bpo=40089]: Fix threading._after_fork(): if fork was not called by a thread spawned by threading.Thread, threading._after_fork() now creates a _MainThread instance for _main_thread, instead of a _DummyThread instance.

bpo-39503 [https://bugs.python.org/issue?@action=redirect&bpo=39503]: AbstractBasicAuthHandler of urllib.request now parses all WWW-Authenticate HTTP headers and accepts multiple challenges per header: use the realm of the first Basic challenge.

bpo-40014 [https://bugs.python.org/issue?@action=redirect&bpo=40014]: Fix os.getgrouplist(): if getgrouplist() function fails because the group list is too small, retry with a larger group list. On failure, the glibc implementation of getgrouplist() sets ngroups to the total number of groups. For other implementations, double the group list size.

bpo-40025 [https://bugs.python.org/issue?@action=redirect&bpo=40025]: Raise TypeError when _generate_next_value_ is defined after members. Patch by Ethan Onstott.

bpo-40016 [https://bugs.python.org/issue?@action=redirect&bpo=40016]: In re docstring, clarify the relationship between inline and argument compile flags.

bpo-39652 [https://bugs.python.org/issue?@action=redirect&bpo=39652]: The column name found in sqlite3.Cursor.description is now truncated on the first ‘[’ only if the PARSE_COLNAMES option is set.

bpo-38662 [https://bugs.python.org/issue?@action=redirect&bpo=38662]: The ensurepip module now invokes pip via the runpy module. Hence it is no longer tightly coupled with the internal API of the bundled pip version, allowing easier updates to a newer pip version both internally and for distributors.

bpo-39916 [https://bugs.python.org/issue?@action=redirect&bpo=39916]: More reliable use of os.scandir() in Path.glob(). It no longer emits a ResourceWarning when interrupted.

bpo-39850 [https://bugs.python.org/issue?@action=redirect&bpo=39850]: multiprocessing now supports abstract socket addresses (if abstract sockets are supported in the running platform). Patch by Pablo Galindo.

bpo-39828 [https://bugs.python.org/issue?@action=redirect&bpo=39828]: Fix json.tool to catch BrokenPipeError. Patch by Dong-hee Na.

bpo-39040 [https://bugs.python.org/issue?@action=redirect&bpo=39040]: Fix parsing of invalid mime headers parameters by collapsing whitespace between encoded words in a bare-quote-string.

bpo-35714 [https://bugs.python.org/issue?@action=redirect&bpo=35714]: struct.error is now raised if there is a null character in a struct format string.

bpo-36541 [https://bugs.python.org/issue?@action=redirect&bpo=36541]: lib2to3 now recognizes named assignment expressions (the walrus operator, :=)

bpo-29620 [https://bugs.python.org/issue?@action=redirect&bpo=29620]: assertWarns() no longer raises a RuntimeException when accessing a module’s __warningregistry__ causes importation of a new module, or when a new module is imported in another thread. Patch by Kernc.

bpo-34226 [https://bugs.python.org/issue?@action=redirect&bpo=34226]: Fix cgi.parse_multipart without content_length. Patch by Roger Duran

bpo-31758 [https://bugs.python.org/issue?@action=redirect&bpo=31758]: Prevent crashes when using an uninitialized _elementtree.XMLParser object. Patch by Oren Milman.

Documentation

bpo-40561 [https://bugs.python.org/issue?@action=redirect&bpo=40561]: Provide docstrings for webbrowser open functions.

bpo-27635 [https://bugs.python.org/issue?@action=redirect&bpo=27635]: The pickle documentation incorrectly claimed that __new__ isn’t called by default when unpickling.

bpo-39879 [https://bugs.python.org/issue?@action=redirect&bpo=39879]: Updated 데이터 모델 docs to include dict() insertion order preservation. Patch by Furkan Onder and Samy Lahfa.

bpo-39677 [https://bugs.python.org/issue?@action=redirect&bpo=39677]: Changed operand name of MAKE_FUNCTION from argc to flags for module dis

bpo-39435 [https://bugs.python.org/issue?@action=redirect&bpo=39435]: Fix an incorrect signature for pickle.loads() in the docs

bpo-38387 [https://bugs.python.org/issue?@action=redirect&bpo=38387]: Document PyDoc_STRVAR macro in the C-API reference.

Tests

bpo-40964 [https://bugs.python.org/issue?@action=redirect&bpo=40964]: Disable remote imaplib tests, host cyrus.andrew.cmu.edu is blocking incoming connections.

bpo-40055 [https://bugs.python.org/issue?@action=redirect&bpo=40055]: distutils.tests now saves/restores warnings filters to leave them unchanged. Importing tests imports docutils which imports pkg_resources which adds a warnings filter.

bpo-40436 [https://bugs.python.org/issue?@action=redirect&bpo=40436]: test_gdb and test.pythoninfo now check gdb command exit code.

bpo-39932 [https://bugs.python.org/issue?@action=redirect&bpo=39932]: Fix multiprocessing test_heap(): a new Heap object is now created for each test run.

bpo-40162 [https://bugs.python.org/issue?@action=redirect&bpo=40162]: Update Travis CI configuration to OpenSSL 1.1.1f.

bpo-40146 [https://bugs.python.org/issue?@action=redirect&bpo=40146]: Update OpenSSL to 1.1.1f in Azure Pipelines.

bpo-40019 [https://bugs.python.org/issue?@action=redirect&bpo=40019]: test_gdb now skips tests if it detects that gdb failed to read debug information because the Python binary is optimized.

bpo-27807 [https://bugs.python.org/issue?@action=redirect&bpo=27807]: test_site.test_startup_imports() is now skipped if a path of sys.path contains a .pth file.

bpo-39793 [https://bugs.python.org/issue?@action=redirect&bpo=39793]: Use the same domain when testing make_msgid. Patch by Batuhan Taskaya.

bpo-1812 [https://bugs.python.org/issue?@action=redirect&bpo=1812]: Fix newline handling in doctest.testfile when loading from a package whose loader has a get_data method. Patch by Peter Donis.

bpo-37957 [https://bugs.python.org/issue?@action=redirect&bpo=37957]: test.regrtest now can receive a list of test patterns to ignore (using the -i/–ignore argument) or a file with a list of patterns to ignore (using the –ignore-file argument). Patch by Pablo Galindo.

bpo-38502 [https://bugs.python.org/issue?@action=redirect&bpo=38502]: test.regrtest now uses process groups in the multiprocessing mode (-jN command line option) if process groups are available: if os.setsid() and os.killpg() functions are available.

bpo-37421 [https://bugs.python.org/issue?@action=redirect&bpo=37421]: multiprocessing tests now stop the ForkServer instance if it’s running: close the “alive” file descriptor to ask the server to stop and then remove its UNIX address.

bpo-37421 [https://bugs.python.org/issue?@action=redirect&bpo=37421]: multiprocessing tests now explicitly call _run_finalizers() to immediately remove temporary directories created by tests.

Build

bpo-40653 [https://bugs.python.org/issue?@action=redirect&bpo=40653]: Move _dirnameW out of HAVE_SYMLINK to fix a potential compiling issue.

bpo-38360 [https://bugs.python.org/issue?@action=redirect&bpo=38360]: Support single-argument form of macOS -isysroot flag.

bpo-40204 [https://bugs.python.org/issue?@action=redirect&bpo=40204]: Pin Sphinx version to 2.3.1 in Doc/Makefile.

bpo-40158 [https://bugs.python.org/issue?@action=redirect&bpo=40158]: Fix CPython MSBuild Properties in NuGet Package (build/native/python.props)

Windows

bpo-40164 [https://bugs.python.org/issue?@action=redirect&bpo=40164]: Updates Windows OpenSSL to 1.1.1g

bpo-39631 [https://bugs.python.org/issue?@action=redirect&bpo=39631]: Changes the registered MIME type for .py files on Windows to text/x-python instead of text/plain.

bpo-40650 [https://bugs.python.org/issue?@action=redirect&bpo=40650]: Include winsock2.h in pytime.c for timeval.

bpo-39930 [https://bugs.python.org/issue?@action=redirect&bpo=39930]: Ensures the required vcruntime140.dll is included in install packages.

bpo-39847 [https://bugs.python.org/issue?@action=redirect&bpo=39847]: Avoid hang when computer is hibernated whilst waiting for a mutex (for lock-related objects from threading) around 49-day uptime.

bpo-38492 [https://bugs.python.org/issue?@action=redirect&bpo=38492]: Remove pythonw.exe dependency on the Microsoft C++ runtime.

macOS

bpo-39580 [https://bugs.python.org/issue?@action=redirect&bpo=39580]: Avoid opening Finder window if running installer from the command line.

bpo-40400 [https://bugs.python.org/issue?@action=redirect&bpo=40400]: Update the macOS installer build scripts to build with Python 3.x and to build correctly on newer macOS systems with SIP.

bpo-40741 [https://bugs.python.org/issue?@action=redirect&bpo=40741]: Update macOS installer to use SQLite 3.32.2.

bpo-38329 [https://bugs.python.org/issue?@action=redirect&bpo=38329]: python.org macOS installers now update the Current version symlink of /Library/Frameworks/Python.framework/Versions for 3.9 installs. Previously, Current was only updated for Python 2.x installs. This should make it easier to embed Python 3 into other macOS applications.

bpo-40164 [https://bugs.python.org/issue?@action=redirect&bpo=40164]: Update macOS installer builds to use OpenSSL 1.1.1g.

IDLE

bpo-39885 [https://bugs.python.org/issue?@action=redirect&bpo=39885]: Make context menu Cut and Copy work again when right-clicking within a selection.

bpo-40723 [https://bugs.python.org/issue?@action=redirect&bpo=40723]: Make test_idle pass when run after import.

bpo-27115 [https://bugs.python.org/issue?@action=redirect&bpo=27115]: For ‘Go to Line’, use a Query box subclass with IDLE standard behavior and improved error checking.

bpo-39885 [https://bugs.python.org/issue?@action=redirect&bpo=39885]: Since clicking to get an IDLE context menu moves the cursor, any text selection should be and now is cleared.

bpo-39852 [https://bugs.python.org/issue?@action=redirect&bpo=39852]: Edit “Go to line” now clears any selection, preventing accidental deletion. It also updates Ln and Col on the status bar.

bpo-38439 [https://bugs.python.org/issue?@action=redirect&bpo=38439]: Add a 256×256 pixel IDLE icon to support more modern environments. Created by Andrew Clover. Delete the unused macOS idle.icns icon file.

bpo-38689 [https://bugs.python.org/issue?@action=redirect&bpo=38689]: IDLE will no longer freeze when inspect.signature fails when fetching a calltip.

Tools/Demos

bpo-40479 [https://bugs.python.org/issue?@action=redirect&bpo=40479]: Update multissltest helper to test with latest OpenSSL 1.0.2, 1.1.0, 1.1.1, and 3.0.0-alpha.

bpo-40179 [https://bugs.python.org/issue?@action=redirect&bpo=40179]: Fixed translation of #elif in Argument Clinic.

bpo-40163 [https://bugs.python.org/issue?@action=redirect&bpo=40163]: Fix multissltest tool. OpenSSL has changed download URL for old releases. The multissltest tool now tries to download from current and old download URLs.

bpo-36184 [https://bugs.python.org/issue?@action=redirect&bpo=36184]: Port python-gdb.py to FreeBSD. python-gdb.py now checks for “take_gil” function name to check if a frame tries to acquire the GIL, instead of checking for “pthread_cond_timedwait” which is specific to Linux and can be a different condition than the GIL.

bpo-39889 [https://bugs.python.org/issue?@action=redirect&bpo=39889]: Fixed unparse.py for extended slices containing a single element (e.g. a[i:j,]). Remove redundant tuples when index with a tuple (e.g. a[i, j]).

C API

bpo-39884 [https://bugs.python.org/issue?@action=redirect&bpo=39884]: _PyMethodDef_RawFastCallDict() and _PyMethodDef_RawFastCallKeywords() now include the method name in the SystemError “bad call flags” error message to ease debug.

bpo-38643 [https://bugs.python.org/issue?@action=redirect&bpo=38643]: PyNumber_ToBase() now raises a SystemError instead of crashing when called with invalid base.

Python 3.7.7 final

Release date: 2020-03-10

Library

bpo-13487 [https://bugs.python.org/issue?@action=redirect&bpo=13487]: Avoid a possible “RuntimeError: dictionary changed size during iteration” from inspect.getmodule() when it tried to loop through sys.modules.

Documentation

bpo-17422 [https://bugs.python.org/issue?@action=redirect&bpo=17422]: The language reference no longer restricts default class namespaces to dicts only.

Python 3.7.7 release candidate 1

Release date: 2020-03-04

Security

bpo-39401 [https://bugs.python.org/issue?@action=redirect&bpo=39401]: Avoid unsafe load of api-ms-win-core-path-l1-1-0.dll at startup on Windows 7.

Core and Builtins

bpo-39776 [https://bugs.python.org/issue?@action=redirect&bpo=39776]: Fix race condition where threads created by PyGILState_Ensure() could get a duplicate id.

This affects consumers of tstate->id like the contextvar caching machinery, which could return invalid cached objects under heavy thread load (observed in embedded scenarios).

bpo-39778 [https://bugs.python.org/issue?@action=redirect&bpo=39778]: Fixed a crash due to incorrect handling of weak references in collections.OrderedDict classes. Patch by Pablo Galindo.

bpo-39382 [https://bugs.python.org/issue?@action=redirect&bpo=39382]: Fix a use-after-free in the single inheritance path of issubclass(), when the __bases__ of an object has a single reference, and so does its first item. Patch by Yonatan Goldschmidt.

bpo-39606 [https://bugs.python.org/issue?@action=redirect&bpo=39606]: Fix regression caused by fix for bpo-39386 [https://bugs.python.org/issue?@action=redirect&bpo=39386], that prevented calling aclose on an async generator that had already been closed or exhausted.

bpo-39510 [https://bugs.python.org/issue?@action=redirect&bpo=39510]: Fix segfault in readinto() method on closed BufferedReader.

bpo-39453 [https://bugs.python.org/issue?@action=redirect&bpo=39453]: Fixed a possible crash in list.__contains__() when a list is changed during comparing items. Patch by Dong-hee Na.

bpo-39427 [https://bugs.python.org/issue?@action=redirect&bpo=39427]: Document all possibilities for the -X options in the command line help section. Patch by Pablo Galindo.

bpo-39421 [https://bugs.python.org/issue?@action=redirect&bpo=39421]: Fix possible crashes when operating with the functions in the heapq module and custom comparison operators.

bpo-39386 [https://bugs.python.org/issue?@action=redirect&bpo=39386]: Prevent double awaiting of async iterator.

bpo-38588 [https://bugs.python.org/issue?@action=redirect&bpo=38588]: Fix possible crashes in dict and list when calling PyObject_RichCompareBool().

bpo-39031 [https://bugs.python.org/issue?@action=redirect&bpo=39031]: When parsing an “elif” node, lineno and col_offset of the node now point to the “elif” keyword and not to its condition, making it consistent with the “if” node. Patch by Lysandros Nikolaou.

bpo-38610 [https://bugs.python.org/issue?@action=redirect&bpo=38610]: Fix possible crashes in several list methods by holding strong references to list elements when calling PyObject_RichCompareBool().

Library

bpo-39794 [https://bugs.python.org/issue?@action=redirect&bpo=39794]: Add –without-decimal-contextvar build option. This enables a thread-local rather than a coroutine local context.

bpo-39769 [https://bugs.python.org/issue?@action=redirect&bpo=39769]: The compileall.compile_dir() function’s ddir parameter and the compileall command line flag -d no longer write the wrong pathname to the generated pyc file for submodules beneath the root of the directory tree being compiled. This fixes a regression introduced with Python 3.5.

bpo-30566 [https://bugs.python.org/issue?@action=redirect&bpo=30566]: Fix IndexError when trying to decode an invalid string with punycode codec.

bpo-39649 [https://bugs.python.org/issue?@action=redirect&bpo=39649]: Remove obsolete check for __args__ in bdb.Bdb.format_stack_entry.

bpo-27657 [https://bugs.python.org/issue?@action=redirect&bpo=27657]: The original fix for bpo-27657 [https://bugs.python.org/issue?@action=redirect&bpo=27657], “Fix urlparse() with numeric paths” (PR 16839) included in 3.7.6, inadvertently introduced a behavior change that broke several third-party packages relying on the original undefined parsing behavior. The change is reverted in 3.7.7, restoring the behavior of 3.7.5 and earlier releases.

bpo-21016 [https://bugs.python.org/issue?@action=redirect&bpo=21016]: The pydoc and trace modules now use the sysconfig module to get the path to the Python standard library, to support uncommon installation path like /usr/lib64/python3.9/ on Fedora. Patch by Jan Matějek.

bpo-39548 [https://bugs.python.org/issue?@action=redirect&bpo=39548]: Fix handling of header in urllib.request.AbstractDigestAuthHandler when the optional qop parameter is not present.

bpo-39450 [https://bugs.python.org/issue?@action=redirect&bpo=39450]: Striped whitespace from docstring before returning it from unittest.case.shortDescription().

bpo-39493 [https://bugs.python.org/issue?@action=redirect&bpo=39493]: Mark typing.IO.closed as a property

bpo-39485 [https://bugs.python.org/issue?@action=redirect&bpo=39485]: Fix a bug in unittest.mock.create_autospec() that would complain about the wrong number of arguments for custom descriptors defined in an extension module returning functions.

bpo-39430 [https://bugs.python.org/issue?@action=redirect&bpo=39430]: Fixed race condition in lazy imports in tarfile.

bpo-39389 [https://bugs.python.org/issue?@action=redirect&bpo=39389]: Write accurate compression level metadata in gzip archives, rather than always signaling maximum compression.

bpo-39274 [https://bugs.python.org/issue?@action=redirect&bpo=39274]: bool(fraction.Fraction) now returns a boolean even if (numerator != 0) does not return a boolean (ex: numpy number).

bpo-39242 [https://bugs.python.org/issue?@action=redirect&bpo=39242]: Updated the Gmane domain from news.gmane.org to news.gmane.io which is used for examples of NNTP news reader server and nntplib tests.

bpo-39152 [https://bugs.python.org/issue?@action=redirect&bpo=39152]: Fix ttk.Scale.configure([name]) to return configuration tuple for name or all options. Giovanni Lombardo contributed part of the patch.

bpo-39198 [https://bugs.python.org/issue?@action=redirect&bpo=39198]: If an exception were to be thrown in Logger.isEnabledFor (say, by asyncio timeouts or stopit) , the logging global lock may not be released appropriately, resulting in deadlock. This change wraps that block of code with try...finally to ensure the lock is released.

bpo-39191 [https://bugs.python.org/issue?@action=redirect&bpo=39191]: Perform a check for running loop before starting a new task in loop.run_until_complete() to fail fast; it prevents the side effect of new task spawning before exception raising.

bpo-38871 [https://bugs.python.org/issue?@action=redirect&bpo=38871]: Correctly parenthesize filter-based statements that contain lambda expressions in mod:lib2to3. Patch by Dong-hee Na.

bpo-39142 [https://bugs.python.org/issue?@action=redirect&bpo=39142]: A change was made to logging.config.dictConfig to avoid converting instances of named tuples to ConvertingTuple. It’s assumed that named tuples are too specialised to be treated like ordinary tuples; if a user of named tuples requires ConvertingTuple functionality, they will have to implement that themselves in their named tuple class.

bpo-38971 [https://bugs.python.org/issue?@action=redirect&bpo=38971]: Open issue in the BPO indicated a desire to make the implementation of codecs.open() at parity with io.open(), which implements a try/except to assure file stream gets closed before an exception is raised.

bpo-39057 [https://bugs.python.org/issue?@action=redirect&bpo=39057]: urllib.request.proxy_bypass_environment() now ignores leading dots and no longer ignores a trailing newline.

bpo-39056 [https://bugs.python.org/issue?@action=redirect&bpo=39056]: Fixed handling invalid warning category in the -W option. No longer import the re module if it is not needed.

bpo-39055 [https://bugs.python.org/issue?@action=redirect&bpo=39055]: base64.b64decode() with validate=True raises now a binascii.Error if the input ends with a single \n.

bpo-38878 [https://bugs.python.org/issue?@action=redirect&bpo=38878]: Fixed __subclasshook__ of os.PathLike to return a correct result upon inheritence. Patch by Bar Harel.

bpo-35182 [https://bugs.python.org/issue?@action=redirect&bpo=35182]: Fixed Popen.communicate() subsequent call crash when the child process has already closed any piped standard stream, but still continues to be running. Patch by Andriy Maletsky.

bpo-38473 [https://bugs.python.org/issue?@action=redirect&bpo=38473]: Use signature from inner mock for autospecced methods attached with unittest.mock.attach_mock(). Patch by Karthikeyan Singaravelan.

bpo-38293 [https://bugs.python.org/issue?@action=redirect&bpo=38293]: Add copy.copy() and copy.deepcopy() support to property() objects.

bpo-37953 [https://bugs.python.org/issue?@action=redirect&bpo=37953]: In typing, improved the __hash__ and __eq__ methods for ForwardReferences.

bpo-36406 [https://bugs.python.org/issue?@action=redirect&bpo=36406]: Handle namespace packages in doctest. Patch by Karthikeyan Singaravelan.

Documentation

bpo-13790 [https://bugs.python.org/issue?@action=redirect&bpo=13790]: Change ‘string’ to ‘specification’ in format doc.

bpo-39530 [https://bugs.python.org/issue?@action=redirect&bpo=39530]: Fix misleading documentation about mixed-type numeric comparisons.

bpo-17422 [https://bugs.python.org/issue?@action=redirect&bpo=17422]: The language reference now specifies restrictions on class namespaces. Adapted from a patch by Ethan Furman.

bpo-39654 [https://bugs.python.org/issue?@action=redirect&bpo=39654]: In pyclbr doc, update ‘class’ to ‘module’ where appropriate and add readmodule comment. Patch by Hakan Çelik.

bpo-39392 [https://bugs.python.org/issue?@action=redirect&bpo=39392]: Explain that when filling with turtle, overlap regions may be left unfilled.

bpo-39381 [https://bugs.python.org/issue?@action=redirect&bpo=39381]: Mention in docs that asyncio.get_event_loop() implicitly creates new event loop only if called from the main thread.

bpo-38918 [https://bugs.python.org/issue?@action=redirect&bpo=38918]: Add an entry for __module__ in the “function” & “method” sections of the inspect docs types and members table [https://docs.python.org/3/library/inspect.html#types-and-members]

bpo-3530 [https://bugs.python.org/issue?@action=redirect&bpo=3530]: In the ast module documentation, fix a misleading NodeTransformer example and add advice on when to use the fix_missing_locations function.

Tests

bpo-38546 [https://bugs.python.org/issue?@action=redirect&bpo=38546]: Fix test_ressources_gced_in_workers() of test_concurrent_futures: explicitly stop the manager to prevent leaking a child process running in the background after the test completes.

Build

bpo-39144 [https://bugs.python.org/issue?@action=redirect&bpo=39144]: The ctags and etags build targets both include Modules/_ctypes and Python standard library source files.

Windows

bpo-38597 [https://bugs.python.org/issue?@action=redirect&bpo=38597]: distutils will no longer statically link vcruntime140.dll when a redistributable version is unavailable. All future releases of CPython will include a copy of this DLL to ensure distributed extensions can continue to load.

bpo-38380 [https://bugs.python.org/issue?@action=redirect&bpo=38380]: Update Windows builds to use SQLite 3.31.1

bpo-39439 [https://bugs.python.org/issue?@action=redirect&bpo=39439]: Reduce overhead when using multiprocessing in a Windows virtual environment

bpo-39185 [https://bugs.python.org/issue?@action=redirect&bpo=39185]: The build.bat script has additional options for very-quiet output (-q) and very-verbose output (-vv)

macOS

bpo-38380 [https://bugs.python.org/issue?@action=redirect&bpo=38380]: Update macOS builds to use SQLite 3.31.1

IDLE

bpo-39781 [https://bugs.python.org/issue?@action=redirect&bpo=39781]: Selecting code context lines no longer causes a jump.

bpo-39663 [https://bugs.python.org/issue?@action=redirect&bpo=39663]: Add tests for pyparse find_good_parse_start().

bpo-39600 [https://bugs.python.org/issue?@action=redirect&bpo=39600]: In the font configuration window, remove duplicated font names.

bpo-30780 [https://bugs.python.org/issue?@action=redirect&bpo=30780]: Add remaining configdialog tests for buttons and highlights and keys tabs.

bpo-39388 [https://bugs.python.org/issue?@action=redirect&bpo=39388]: IDLE Settings Cancel button now cancels pending changes

bpo-39050 [https://bugs.python.org/issue?@action=redirect&bpo=39050]: Make IDLE Settings dialog Help button work again.

bpo-34118 [https://bugs.python.org/issue?@action=redirect&bpo=34118]: Tag memoryview, range, and tuple as classes, the same as list, etcetera, in the library manual built-in functions list.

bpo-38792 [https://bugs.python.org/issue?@action=redirect&bpo=38792]: Close an IDLE shell calltip if a KeyboardInterrupt or shell restart occurs. Patch by Zackery Spytz.

bpo-32989 [https://bugs.python.org/issue?@action=redirect&bpo=32989]: Add tests for editor newline_and_indent_event method. Remove dead code from pyparse find_good_parse_start method.

Python 3.7.6 final

Release date: 2019-12-18

macOS

bpo-38295 [https://bugs.python.org/issue?@action=redirect&bpo=38295]: Prevent failure of test_relative_path in test_py_compile on macOS Catalina.

Python 3.7.6 release candidate 1

Release date: 2019-12-11

Security

bpo-38945 [https://bugs.python.org/issue?@action=redirect&bpo=38945]: Newline characters have been escaped when performing uu encoding to prevent them from overflowing into to content section of the encoded file. This prevents malicious or accidental modification of data during the decoding process.

bpo-37228 [https://bugs.python.org/issue?@action=redirect&bpo=37228]: Due to significant security concerns, the reuse_address parameter of asyncio.loop.create_datagram_endpoint() is no longer supported. This is because of the behavior of SO_REUSEADDR in UDP. For more details, see the documentation for loop.create_datagram_endpoint(). (Contributed by Kyle Stanley, Antoine Pitrou, and Yury Selivanov in bpo-37228 [https://bugs.python.org/issue?@action=redirect&bpo=37228].)

bpo-38804 [https://bugs.python.org/issue?@action=redirect&bpo=38804]: Fixes a ReDoS vulnerability in http.cookiejar. Patch by Ben Caller.

Core and Builtins

bpo-38673 [https://bugs.python.org/issue?@action=redirect&bpo=38673]: In REPL mode, don’t switch to PS2 if the line starts with comment or whitespace. Based on work by Batuhan Taşkaya.

bpo-38535 [https://bugs.python.org/issue?@action=redirect&bpo=38535]: Fixed line numbers and column offsets for AST nodes for calls without arguments in decorators.

bpo-38379 [https://bugs.python.org/issue?@action=redirect&bpo=38379]: When cyclic garbage collection (gc) runs finalizers that resurrect unreachable objects, the current gc run ends, without collecting any cyclic trash. However, the statistics reported by collect() and get_stats() claimed that all cyclic trash found was collected, and that the resurrected objects were collected. Changed the stats to report that none were collected.

bpo-35409 [https://bugs.python.org/issue?@action=redirect&bpo=35409]: Ignore GeneratorExit exceptions when throwing an exception into the aclose coroutine of an asynchronous generator.

Library

bpo-39006 [https://bugs.python.org/issue?@action=redirect&bpo=39006]: Fix asyncio when the ssl module is missing: only check for ssl.SSLSocket instance if the ssl module is available.

bpo-38979 [https://bugs.python.org/issue?@action=redirect&bpo=38979]: Return class from ContextVar.__class_getitem__ to simplify subclassing.

bpo-38986 [https://bugs.python.org/issue?@action=redirect&bpo=38986]: Make repr of C accelerated TaskWakeupMethWrapper the same as of pure Python version.

bpo-33684 [https://bugs.python.org/issue?@action=redirect&bpo=33684]: Fix json.tool failed to read a JSON file with non-ASCII characters when locale encoding is not UTF-8.

bpo-26730 [https://bugs.python.org/issue?@action=redirect&bpo=26730]: Fix SpooledTemporaryFile.rollover() might corrupt the file when it is in text mode. Patch by Serhiy Storchaka.

bpo-37838 [https://bugs.python.org/issue?@action=redirect&bpo=37838]: typing.get_type_hints() properly handles functions decorated with functools.wraps().

bpo-38821 [https://bugs.python.org/issue?@action=redirect&bpo=38821]: Fix unhandled exceptions in argparse when internationalizing error messages for arguments with nargs set to special (non-integer) values. Patch by Federico Bond.

bpo-38820 [https://bugs.python.org/issue?@action=redirect&bpo=38820]: Make Python compatible with OpenSSL 3.0.0. ssl.SSLSocket.getpeercert() no longer returns IPv6 addresses with a trailing new line.

bpo-38785 [https://bugs.python.org/issue?@action=redirect&bpo=38785]: Prevent asyncio from crashing if parent __init__ is not called from a constructor of object derived from asyncio.Future.

bpo-27805 [https://bugs.python.org/issue?@action=redirect&bpo=27805]: Allow opening pipes and other non-seekable files in append mode with open().

bpo-38686 [https://bugs.python.org/issue?@action=redirect&bpo=38686]: Added support for multiple qop values in urllib.request.AbstractDigestAuthHandler.

bpo-38334 [https://bugs.python.org/issue?@action=redirect&bpo=38334]: Fixed seeking backward on an encrypted zipfile.ZipExtFile.

bpo-31202 [https://bugs.python.org/issue?@action=redirect&bpo=31202]: The case the result of pathlib.WindowsPath.glob() matches now the case of the pattern for literal parts.

bpo-38109 [https://bugs.python.org/issue?@action=redirect&bpo=38109]: Add missing stat.S_IFDOOR, stat.S_IFPORT, stat.S_IFWHT, stat.S_ISDOOR(), stat.S_ISPORT(), and stat.S_ISWHT() values to the Python implementation of stat.

bpo-38422 [https://bugs.python.org/issue?@action=redirect&bpo=38422]: Clarify docstrings of pathlib suffix(es)

bpo-38405 [https://bugs.python.org/issue?@action=redirect&bpo=38405]: Nested subclasses of typing.NamedTuple are now pickleable.

bpo-38332 [https://bugs.python.org/issue?@action=redirect&bpo=38332]: Prevent KeyError thrown by _encoded_words.decode() when given an encoded-word with invalid content-type encoding from propagating all the way to email.message.get().

bpo-38341 [https://bugs.python.org/issue?@action=redirect&bpo=38341]: Add smtplib.SMTPNotSupportedError to the smtplib exported names.

bpo-13153 [https://bugs.python.org/issue?@action=redirect&bpo=13153]: OS native encoding is now used for converting between Python strings and Tcl objects. This allows to display, copy and paste to clipboard emoji and other non-BMP characters. Converting strings from Tcl to Python and back now never fails (except MemoryError).

bpo-36993 [https://bugs.python.org/issue?@action=redirect&bpo=36993]: Improve error reporting for corrupt zip files with bad zip64 extra data. Patch by Daniel Hillier.

bpo-36952 [https://bugs.python.org/issue?@action=redirect&bpo=36952]: Starting with Python 3.3, importing ABCs from collections is deprecated, and import should be done from collections.abc. Still being able to import from collections was marked for removal in 3.8, but has been delayed to 3.9; documentation and DeprecationWarning clarified.

bpo-36820 [https://bugs.python.org/issue?@action=redirect&bpo=36820]: Break cycle generated when saving an exception in socket.py, codeop.py and dyld.py as they keep alive not only the exception but user objects through the __traceback__ attribute. Patch by Mario Corchero.

bpo-34776 [https://bugs.python.org/issue?@action=redirect&bpo=34776]: Fix dataclasses to support forward references in type annotations

bpo-33348 [https://bugs.python.org/issue?@action=redirect&bpo=33348]: lib2to3 now recognizes expressions after * and ** like in f(*[] or []).

bpo-27657 [https://bugs.python.org/issue?@action=redirect&bpo=27657]: Fix urllib.parse.urlparse() with numeric paths. A string like “path:80” is no longer parsed as a path but as a scheme (“path”) and a path (“80”).

Documentation

bpo-38351 [https://bugs.python.org/issue?@action=redirect&bpo=38351]: Modernize email examples from %-formatting to f-strings.

bpo-38592 [https://bugs.python.org/issue?@action=redirect&bpo=38592]: Add Brazilian Portuguese to the language switcher at Python Documentation website.

bpo-38294 [https://bugs.python.org/issue?@action=redirect&bpo=38294]: Add list of no-longer-escaped chars to re.escape documentation

Tests

bpo-38547 [https://bugs.python.org/issue?@action=redirect&bpo=38547]: Fix test_pty: if the process is the session leader, closing the master file descriptor raises a SIGHUP signal: simply ignore SIGHUP when running the tests.

bpo-38965 [https://bugs.python.org/issue?@action=redirect&bpo=38965]: Fix test_faulthandler on GCC 10. Use the “volatile” keyword in faulthandler._stack_overflow() to prevent tail call optimization on any compiler, rather than relying on compiler specific pragma.

bpo-38669 [https://bugs.python.org/issue?@action=redirect&bpo=38669]: Raise TypeError when passing target as a string with unittest.mock.patch.object().

bpo-35998 [https://bugs.python.org/issue?@action=redirect&bpo=35998]: Fix a race condition in test_asyncio.test_start_tls_server_1(). Previously, there was a race condition between the test main() function which replaces the protocol and the test ServerProto protocol which sends ANSWER once it gets HELLO. Now, only the test main() function is responsible to send data, ServerProto no longer sends data.

bpo-37531 [https://bugs.python.org/issue?@action=redirect&bpo=37531]: On timeout, regrtest no longer attempts to call popen.communicate() again: it can hang until all child processes using stdout and stderr pipes completes. Kill the worker process and ignores its output. Change also the faulthandler timeout of the main process from 1 minute to 5 minutes, for Python slowest buildbots.

Build

bpo-37404 [https://bugs.python.org/issue?@action=redirect&bpo=37404]: asyncio now raises TyperError when calling incompatible methods with an ssl.SSLSocket socket. Patch by Ido Michael.

bpo-38809 [https://bugs.python.org/issue?@action=redirect&bpo=38809]: On Windows, build scripts will now recognize and use python.exe from an active virtual env.

bpo-37415 [https://bugs.python.org/issue?@action=redirect&bpo=37415]: Fix stdatomic.h header check for ICC compiler: the ICC implementation lacks atomic_uintptr_t type which is needed by Python.

Windows

bpo-38589 [https://bugs.python.org/issue?@action=redirect&bpo=38589]: Fixes HTML Help shortcut when Windows is not installed to C drive

IDLE

bpo-38944 [https://bugs.python.org/issue?@action=redirect&bpo=38944]: Excape key now closes IDLE completion windows. Patch by Johnny Najera.

bpo-38943 [https://bugs.python.org/issue?@action=redirect&bpo=38943]: Fix IDLE autocomplete windows not always appearing on some systems. Patch by Johnny Najera.

bpo-38862 [https://bugs.python.org/issue?@action=redirect&bpo=38862]: ‘Strip Trailing Whitespace’ on the Format menu removes extra newlines at the end of non-shell files.

bpo-26353 [https://bugs.python.org/issue?@action=redirect&bpo=26353]: Stop adding newline when saving an IDLE shell window.

bpo-38636 [https://bugs.python.org/issue?@action=redirect&bpo=38636]: Fix IDLE Format menu tab toggle and file indent width. These functions (default shortcuts Alt-T and Alt-U) were mistakenly disabled in 3.7.5 and 3.8.0.

bpo-4630 [https://bugs.python.org/issue?@action=redirect&bpo=4630]: Add an option to toggle IDLE’s cursor blink for shell, editor, and output windows. See Settings, General, Window Preferences, Cursor Blink. Patch by Zachary Spytz.

bpo-38598 [https://bugs.python.org/issue?@action=redirect&bpo=38598]: Do not try to compile IDLE shell or output windows

bpo-36698 [https://bugs.python.org/issue?@action=redirect&bpo=36698]: IDLE no longer fails when write non-encodable characters to stderr. It now escapes them with a backslash, as the regular Python interpreter. Added the errors field to the standard streams.

Tools/Demos

bpo-38118 [https://bugs.python.org/issue?@action=redirect&bpo=38118]: Update Valgrind suppression file to ignore a false alarm in PyUnicode_Decode() when using GCC builtin strcmp().

bpo-38347 [https://bugs.python.org/issue?@action=redirect&bpo=38347]: pathfix.py: Assume all files that end on ‘.py’ are Python scripts when working recursively.

C API

bpo-38540 [https://bugs.python.org/issue?@action=redirect&bpo=38540]: Fixed possible leak in PyArg_Parse() and similar functions for format units "es#" and "et#" when the macro PY_SSIZE_T_CLEAN is not defined.

bpo-38395 [https://bugs.python.org/issue?@action=redirect&bpo=38395]: Fix a crash in weakref.proxy objects due to incorrect lifetime management when calling some associated methods that may delete the last reference to object being referenced by the proxy. Patch by Pablo Galindo.

Python 3.7.5 final

Release date: 2019-10-14

Library

bpo-38368 [https://bugs.python.org/issue?@action=redirect&bpo=38368]: Prevent ctypes crash when handling arrays in structs/unions.

bpo-38449 [https://bugs.python.org/issue?@action=redirect&bpo=38449]: Revert PR 15522, which introduces a regression in mimetypes.guess_type() due to improper handling of filenames as urls.

Windows

bpo-38344 [https://bugs.python.org/issue?@action=redirect&bpo=38344]: Fix syntax in activate.bat.

Python 3.7.5 release candidate 1

Release date: 2019-10-01

Security

bpo-38243 [https://bugs.python.org/issue?@action=redirect&bpo=38243]: Escape the server title of xmlrpc.server.DocXMLRPCServer when rendering the document page as HTML. (Contributed by Dong-hee Na in bpo-38243 [https://bugs.python.org/issue?@action=redirect&bpo=38243].)

bpo-38174 [https://bugs.python.org/issue?@action=redirect&bpo=38174]: Update vendorized expat library version to 2.2.8, which resolves CVE-2019-15903.

bpo-37764 [https://bugs.python.org/issue?@action=redirect&bpo=37764]: Fixes email._header_value_parser.get_unstructured going into an infinite loop for a specific case in which the email header does not have trailing whitespace, and the case in which it contains an invalid encoded word. Patch by Ashwin Ramaswami.

bpo-37461 [https://bugs.python.org/issue?@action=redirect&bpo=37461]: Fix an infinite loop when parsing specially crafted email headers. Patch by Abhilash Raj.

bpo-34155 [https://bugs.python.org/issue?@action=redirect&bpo=34155]: Fix parsing of invalid email addresses with more than one @ (e.g. a@b@c.com.) to not return the part before 2nd @ as valid email address. Patch by maxking & jpic.

Core and Builtins

bpo-36871 [https://bugs.python.org/issue?@action=redirect&bpo=36871]: Improve error handling for the assert_has_calls method of mocks. Fixed a bug where any errors encountered while binding the expected calls to the mock’s spec were silently swallowed, leading to misleading error output.

bpo-38013 [https://bugs.python.org/issue?@action=redirect&bpo=38013]: Allow to call async_generator_athrow().throw(...) even for non-started async generator helper. It fixes annoying warning at the end of asyncio.run() call.

bpo-38124 [https://bugs.python.org/issue?@action=redirect&bpo=38124]: Fix an off-by-one error in PyState_AddModule that could cause out-of-bounds memory access.

bpo-36946 [https://bugs.python.org/issue?@action=redirect&bpo=36946]: Fix possible signed integer overflow when handling slices. Patch by hongweipeng.

bpo-37409 [https://bugs.python.org/issue?@action=redirect&bpo=37409]: Ensure explicit relative imports from interactive sessions and scripts (having no parent package) always raise ImportError, rather than treating the current module as the package. Patch by Ben Lewis.

bpo-36311 [https://bugs.python.org/issue?@action=redirect&bpo=36311]: Decoding bytes objects larger than 2GiB is faster and no longer fails when a multibyte characters spans a chunk boundary.

bpo-37467 [https://bugs.python.org/issue?@action=redirect&bpo=37467]: Fix sys.excepthook() and PyErr_Display() if a filename is a bytes string. For example, for a SyntaxError exception where the filename attribute is a bytes string.

bpo-37417 [https://bugs.python.org/issue?@action=redirect&bpo=37417]: bytearray.extend() now correctly handles errors that arise during iteration. Patch by Brandt Bucher.

bpo-20523 [https://bugs.python.org/issue?@action=redirect&bpo=20523]: pdb.Pdb supports ~/.pdbrc in Windows 7. Patch by Tim Hopper and Dan Lidral-Porter.

Library

bpo-38019 [https://bugs.python.org/issue?@action=redirect&bpo=38019]: Correctly handle pause/resume reading of closed asyncio unix pipe.

bpo-38216 [https://bugs.python.org/issue?@action=redirect&bpo=38216]: Allow the rare code that wants to send invalid http requests from the http.client library a way to do so. The fixes for bpo-30458 [https://bugs.python.org/issue?@action=redirect&bpo=30458] led to breakage for some projects that were relying on this ability to test their own behavior in the face of bad requests.

bpo-38191 [https://bugs.python.org/issue?@action=redirect&bpo=38191]: Constructor of NamedTuple type now accepts arbitrary keyword argument names, including “cls”, “self”, “typename” and “fields”.

bpo-38185 [https://bugs.python.org/issue?@action=redirect&bpo=38185]: Fixed case-insensitive string comparison in sqlite3.Row indexing.

bpo-38175 [https://bugs.python.org/issue?@action=redirect&bpo=38175]: Fix a memory leak in comparison of sqlite3.Row objects.

bpo-33936 [https://bugs.python.org/issue?@action=redirect&bpo=33936]: _hashlib no longer calls obsolete OpenSSL initialization function with OpenSSL 1.1.0+.

bpo-34706 [https://bugs.python.org/issue?@action=redirect&bpo=34706]: Preserve subclassing in inspect.Signature.from_callable.

bpo-38059 [https://bugs.python.org/issue?@action=redirect&bpo=38059]: inspect.py now uses sys.exit() instead of exit()

bpo-38006 [https://bugs.python.org/issue?@action=redirect&bpo=38006]: weakref.WeakValueDictionary defines a local remove() function used as callback for weak references. This function was created with a closure. Modify the implementation to avoid the closure.

bpo-34410 [https://bugs.python.org/issue?@action=redirect&bpo=34410]: Fixed a crash in the tee() iterator when re-enter it. RuntimeError is now raised in this case.

bpo-37965 [https://bugs.python.org/issue?@action=redirect&bpo=37965]: Fix C compiler warning caused by distutils.ccompiler.CCompiler.has_function.

bpo-36205 [https://bugs.python.org/issue?@action=redirect&bpo=36205]: Fix the rusage implementation of time.process_time() to correctly report the sum of the system and user CPU time.

bpo-22347 [https://bugs.python.org/issue?@action=redirect&bpo=22347]: Update mimetypes.guess_type to allow proper parsing of URLs with only a host name. Patch by Dong-hee Na.

bpo-37950 [https://bugs.python.org/issue?@action=redirect&bpo=37950]: Fix ast.dump() when call with incompletely initialized node.

bpo-37915 [https://bugs.python.org/issue?@action=redirect&bpo=37915]: Fix a segmentation fault that appeared when comparing instances of datetime.timezone and datetime.tzinfo objects. Patch by Pablo Galindo.

bpo-37885 [https://bugs.python.org/issue?@action=redirect&bpo=37885]: venv: Don’t generate unset variable warning on deactivate.

bpo-37868 [https://bugs.python.org/issue?@action=redirect&bpo=37868]: Fix dataclasses.is_dataclass when given an instance that never raises AttributeError in __getattr__. That is, an object that returns something for __dataclass_fields__ even if it’s not a dataclass.

bpo-37811 [https://bugs.python.org/issue?@action=redirect&bpo=37811]: Fix socket module’s socket.connect(address) function being unable to establish connection in case of interrupted system call. The problem was observed on all OSes which poll(2) system call can take only non-negative integers and -1 as a timeout value.

bpo-21131 [https://bugs.python.org/issue?@action=redirect&bpo=21131]: Fix faulthandler.register(chain=True) stack. faulthandler now allocates a dedicated stack of SIGSTKSZ*2 bytes, instead of just SIGSTKSZ bytes. Calling the previous signal handler in faulthandler signal handler uses more than SIGSTKSZ bytes of stack memory on some platforms.

bpo-34621 [https://bugs.python.org/issue?@action=redirect&bpo=34621]: Fixed unpickle-ability in older Python versions (<3.7) of UUID objects with is_safe set to SafeUUID.unknown.

bpo-37738 [https://bugs.python.org/issue?@action=redirect&bpo=37738]: Fix the implementation of curses addch(str, color_pair): pass the color pair to setcchar(), instead of always passing 0 as the color pair.

bpo-37723 [https://bugs.python.org/issue?@action=redirect&bpo=37723]: Fix performance regression on regular expression parsing with huge character sets. Patch by Yann Vaginay.

bpo-32178 [https://bugs.python.org/issue?@action=redirect&bpo=32178]: Fix IndexError in email package when trying to parse invalid address fields starting with :.

bpo-37685 [https://bugs.python.org/issue?@action=redirect&bpo=37685]: Fixed comparisons of datetime.timedelta and datetime.timezone.

bpo-37695 [https://bugs.python.org/issue?@action=redirect&bpo=37695]: Correct curses.unget_wch() error message. Patch by Anthony Sottile.

bpo-29553 [https://bugs.python.org/issue?@action=redirect&bpo=29553]: Fixed argparse.ArgumentParser.format_usage() for mutually exclusive groups. Patch by Andrew Nester.

bpo-37664 [https://bugs.python.org/issue?@action=redirect&bpo=37664]: Update wheels bundled with ensurepip (pip 19.2.3 and setuptools 41.2.0)

bpo-37642 [https://bugs.python.org/issue?@action=redirect&bpo=37642]: Allowed the pure Python implementation of datetime.timezone to represent sub-minute offsets close to minimum and maximum boundaries, specifically in the ranges (23:59, 24:00) and (-23:59, 24:00). Patch by Ngalim Siregar

bpo-37491 [https://bugs.python.org/issue?@action=redirect&bpo=37491]: Fix IndexError when parsing email headers with unexpectedly ending bare-quoted string value. Patch by Abhilash Raj.

bpo-18378 [https://bugs.python.org/issue?@action=redirect&bpo=18378]: Recognize “UTF-8” as a valid value for LC_CTYPE in locale._parse_localename.

bpo-37579 [https://bugs.python.org/issue?@action=redirect&bpo=37579]: Return NotImplemented in Python implementation of __eq__ for timedelta and time when the other object being compared is not of the same type to match C implementation. Patch by Karthikeyan Singaravelan.

bpo-21478 [https://bugs.python.org/issue?@action=redirect&bpo=21478]: Record calls to parent when autospecced object is attached to a mock using unittest.mock.attach_mock(). Patch by Karthikeyan Singaravelan.

bpo-37531 [https://bugs.python.org/issue?@action=redirect&bpo=37531]: “python3 -m test -jN –timeout=TIMEOUT” now kills a worker process if it runs longer than TIMEOUT seconds.

bpo-37482 [https://bugs.python.org/issue?@action=redirect&bpo=37482]: Fix serialization of display name in originator or destination address fields with both encoded words and special chars.

bpo-37424 [https://bugs.python.org/issue?@action=redirect&bpo=37424]: Fixes a possible hang when using a timeout on subprocess.run() while capturing output. If the child process spawned its own children or otherwise connected its stdout or stderr handles with another process, we could hang after the timeout was reached and our child was killed when attempting to read final output from the pipes.

bpo-37421 [https://bugs.python.org/issue?@action=redirect&bpo=37421]: Fix multiprocessing.util.get_temp_dir() finalizer: clear also the ‘tempdir’ configuration of the current process, so next call to get_temp_dir() will create a new temporary directory, rather than reusing the removed temporary directory.

bpo-37420 [https://bugs.python.org/issue?@action=redirect&bpo=37420]: os.sched_setaffinity() now correctly handles errors that arise during iteration over its mask argument. Patch by Brandt Bucher.

bpo-29412 [https://bugs.python.org/issue?@action=redirect&bpo=29412]: Fix IndexError in parsing a header value ending unexpectedly. Patch by Abhilash Raj.

bpo-37372 [https://bugs.python.org/issue?@action=redirect&bpo=37372]: Fix error unpickling datetime.time objects from Python 2 with seconds>=24. Patch by Justin Blanchard.

bpo-27860 [https://bugs.python.org/issue?@action=redirect&bpo=27860]: Fix IPv4Interface and IPv6Interface didn’t accept string mask when the argument is tuple.

bpo-33972 [https://bugs.python.org/issue?@action=redirect&bpo=33972]: Email with single part but content-type set to multipart/* doesn’t raise AttributeError anymore.

bpo-21872 [https://bugs.python.org/issue?@action=redirect&bpo=21872]: Fix lzma: module decompresses data incompletely. When decompressing a FORMAT_ALONE format file, and it doesn’t have the end marker, sometimes the last one to dozens bytes can’t be output. Patch by Ma Lin.

bpo-12144 [https://bugs.python.org/issue?@action=redirect&bpo=12144]: Ensure cookies with expires attribute are handled in CookieJar.make_cookies().

bpo-37163 [https://bugs.python.org/issue?@action=redirect&bpo=37163]: dataclasses.replace() now supports the field named “obj”.

bpo-36871 [https://bugs.python.org/issue?@action=redirect&bpo=36871]: Ensure method signature is used instead of constructor signature of a class while asserting mock object against method calls. Patch by Karthikeyan Singaravelan.

bpo-36564 [https://bugs.python.org/issue?@action=redirect&bpo=36564]: Fix infinite loop in email header folding logic that would be triggered when an email policy’s max_line_length is not long enough to include the required markup and any values in the message. Patch by Paul Ganssle

bpo-35168 [https://bugs.python.org/issue?@action=redirect&bpo=35168]: shlex.shlex.punctuation_chars is now a read-only property.

bpo-20504 [https://bugs.python.org/issue?@action=redirect&bpo=20504]: Fixes a bug in cgi module when a multipart/form-data request has no Content-Length header.

bpo-4963 [https://bugs.python.org/issue?@action=redirect&bpo=4963]: Fixed non-deterministic behavior related to mimetypes extension mapping and module reinitialization.

Documentation

bpo-26868 [https://bugs.python.org/issue?@action=redirect&bpo=26868]: Fix example usage of PyModule_AddObject() to properly handle errors.

bpo-37979 [https://bugs.python.org/issue?@action=redirect&bpo=37979]: Added a link to dateutil.parser.isoparse in the datetime.fromisoformat documentation. Patch by Paul Ganssle

bpo-37937 [https://bugs.python.org/issue?@action=redirect&bpo=37937]: Mention frame.f_trace in sys.settrace() docs.

bpo-37726 [https://bugs.python.org/issue?@action=redirect&bpo=37726]: Stop recommending getopt in the tutorial for command line argument parsing and promote argparse.

bpo-32910 [https://bugs.python.org/issue?@action=redirect&bpo=32910]: Remove implementation-specific behaviour of how venv’s Deactivate works.

bpo-37256 [https://bugs.python.org/issue?@action=redirect&bpo=37256]: Fix wording of arguments for Request in urllib.request

bpo-37284 [https://bugs.python.org/issue?@action=redirect&bpo=37284]: Add a brief note to indicate that any new sys.implementation required attributes must go through the PEP process.

bpo-30088 [https://bugs.python.org/issue?@action=redirect&bpo=30088]: Documented that mailbox.Maildir constructor doesn’t attempt to verify the maildir folder layout correctness. Patch by Sviatoslav Sydorenko.

bpo-37487 [https://bugs.python.org/issue?@action=redirect&bpo=37487]: Fix PyList_GetItem index description to include 0.

bpo-37478 [https://bugs.python.org/issue?@action=redirect&bpo=37478]: Added possible exceptions to the description of os.chdir().

bpo-37004 [https://bugs.python.org/issue?@action=redirect&bpo=37004]: In the documentation for difflib, a note was added explicitly warning that the results of SequenceMatcher’s ratio method may depend on the order of the input strings.

bpo-35803 [https://bugs.python.org/issue?@action=redirect&bpo=35803]: Document and test that tempfile functions may accept a path-like object for the dir argument. Patch by Anthony Sottile.

bpo-34293 [https://bugs.python.org/issue?@action=redirect&bpo=34293]: Fix the Doc/Makefile regarding PAPER environment variable and PDF builds

Tests

bpo-38239 [https://bugs.python.org/issue?@action=redirect&bpo=38239]: Fix test_gdb for Link Time Optimization (LTO) builds.

bpo-38275 [https://bugs.python.org/issue?@action=redirect&bpo=38275]: test_ssl now handles disabled TLS/SSL versions better. OpenSSL’s crypto policy and run-time settings are recognized and tests for disabled versions are skipped. Tests also accept more TLS minimum_versions for platforms that override OpenSSL’s default with strict settings.

bpo-38271 [https://bugs.python.org/issue?@action=redirect&bpo=38271]: The private keys for test_ssl were encrypted with 3DES in traditional PKCS#5 format. 3DES and the digest algorithm of PKCS#5 are blocked by some strict crypto policies. Use PKCS#8 format with AES256 encryption instead.

bpo-37123 [https://bugs.python.org/issue?@action=redirect&bpo=37123]: Multiprocessing test test_mymanager() now also expects -SIGTERM, not only exitcode 0. BaseManager._finalize_manager() sends SIGTERM to the manager process if it takes longer than 1 second to stop, which happens on slow buildbots.

bpo-38212 [https://bugs.python.org/issue?@action=redirect&bpo=38212]: Multiprocessing tests: increase test_queue_feeder_donot_stop_onexc() timeout from 1 to 60 seconds.

bpo-38117 [https://bugs.python.org/issue?@action=redirect&bpo=38117]: Test with OpenSSL 1.1.1d

bpo-37805 [https://bugs.python.org/issue?@action=redirect&bpo=37805]: Add tests for json.dump(…, skipkeys=True). Patch by Dong-hee Na.

bpo-37531 [https://bugs.python.org/issue?@action=redirect&bpo=37531]: Enhance regrtest multiprocess timeout: write a message when killing a worker process, catch popen.kill() and popen.wait() exceptions, put a timeout on the second call to popen.communicate().

bpo-37335 [https://bugs.python.org/issue?@action=redirect&bpo=37335]: Improve locale coercion tests by using codec lookup instead of more fragile replace().

bpo-37411 [https://bugs.python.org/issue?@action=redirect&bpo=37411]: Fix test_wsgiref.testEnviron() to no longer depend on the environment variables (don’t fail if “X” variable is set).

bpo-37400 [https://bugs.python.org/issue?@action=redirect&bpo=37400]: Fix test_os.test_chown(): use os.getgroups() rather than grp.getgrall() to get groups. Rename also the test to test_chown_gid().

bpo-37359 [https://bugs.python.org/issue?@action=redirect&bpo=37359]: Add –cleanup option to python3 -m test to remove test_python_* directories of previous failed jobs. Add “make cleantest” to run python3 -m test --cleanup.

bpo-37362 [https://bugs.python.org/issue?@action=redirect&bpo=37362]: test_gdb no longer fails if it gets an “unexpected” message on stderr: it now ignores stderr. The purpose of test_gdb is to test that python-gdb.py commands work as expected, not to test gdb.

bpo-36919 [https://bugs.python.org/issue?@action=redirect&bpo=36919]: Make test_source_encoding.test_issue2301 implementation independent. The test will work now for both CPython and IronPython.

bpo-34720 [https://bugs.python.org/issue?@action=redirect&bpo=34720]: Assert m_state != NULL to mimic GC traversal functions that do not correctly handle module creation when the module state has not been created.

bpo-34347 [https://bugs.python.org/issue?@action=redirect&bpo=34347]: Fix test_utf8_mode.test_cmd_line for AIX. Patch by M. Felt

Build

bpo-38301 [https://bugs.python.org/issue?@action=redirect&bpo=38301]: In Solaris family, we must be sure to use -D_REENTRANT. Patch by Jesús Cea Avión.

bpo-36002 [https://bugs.python.org/issue?@action=redirect&bpo=36002]: Locate llvm-profdata and llvm-ar binaries using AC_PATH_TOOL rather than AC_PATH_TARGET_TOOL.

bpo-37936 [https://bugs.python.org/issue?@action=redirect&bpo=37936]: The .gitignore file no longer applies to any files that are in fact tracked in the Git repository. Patch by Greg Price.

Windows

bpo-38117 [https://bugs.python.org/issue?@action=redirect&bpo=38117]: Update bundled OpenSSL to 1.1.1d

bpo-36634 [https://bugs.python.org/issue?@action=redirect&bpo=36634]: venv activate.bat now works when the existing variables contain double quote characters.

bpo-38087 [https://bugs.python.org/issue?@action=redirect&bpo=38087]: Fix case sensitivity in test_pathlib and test_ntpath.

bpo-38088 [https://bugs.python.org/issue?@action=redirect&bpo=38088]: Fixes distutils not finding vcruntime140.dll with only the v142 toolset installed.

bpo-37283 [https://bugs.python.org/issue?@action=redirect&bpo=37283]: Ensure command-line and unattend.xml setting override previously detected states in Windows installer.

bpo-37705 [https://bugs.python.org/issue?@action=redirect&bpo=37705]: Improve the implementation of winerror_to_errno().

bpo-37549 [https://bugs.python.org/issue?@action=redirect&bpo=37549]: os.dup() no longer fails for standard streams on Windows 7.

bpo-37702 [https://bugs.python.org/issue?@action=redirect&bpo=37702]: Fix memory leak on Windows in creating an SSLContext object or running urllib.request.urlopen(’https://…’).

bpo-10945 [https://bugs.python.org/issue?@action=redirect&bpo=10945]: Officially drop support for creating bdist_wininst installers on non-Windows systems.

bpo-37445 [https://bugs.python.org/issue?@action=redirect&bpo=37445]: Include the FORMAT_MESSAGE_IGNORE_INSERTS flag in FormatMessageW() calls.

bpo-37380 [https://bugs.python.org/issue?@action=redirect&bpo=37380]: Don’t collect unfinished processes with subprocess._active on Windows to cleanup later. Patch by Ruslan Kuprieiev.

bpo-32587 [https://bugs.python.org/issue?@action=redirect&bpo=32587]: Make winreg.REG_MULTI_SZ support zero-length strings.

macOS

bpo-38117 [https://bugs.python.org/issue?@action=redirect&bpo=38117]: Updated OpenSSL to 1.1.1d in macOS installer.

bpo-38089 [https://bugs.python.org/issue?@action=redirect&bpo=38089]: Move Azure Pipelines to latest VM versions and make macOS tests optional

IDLE

bpo-35379 [https://bugs.python.org/issue?@action=redirect&bpo=35379]: When exiting IDLE, catch any AttributeError. One happens when EditorWindow.close is called twice. Printing a traceback, when IDLE is run from a terminal, is useless and annoying.

bpo-38183 [https://bugs.python.org/issue?@action=redirect&bpo=38183]: To avoid problems, test_idle ignores the user config directory. It no longer tries to create or access .idlerc or any files within. Users must run IDLE to discover problems with saving settings.

bpo-38077 [https://bugs.python.org/issue?@action=redirect&bpo=38077]: IDLE no longer adds ‘argv’ to the user namespace when initializing it. This bug only affected 3.7.4 and 3.8.0b2 to 3.8.0b4.

bpo-38041 [https://bugs.python.org/issue?@action=redirect&bpo=38041]: Shell restart lines now fill the window width, always start with ‘=’, and avoid wrapping unnecessarily. The line will still wrap if the included file name is long relative to the width.

bpo-35771 [https://bugs.python.org/issue?@action=redirect&bpo=35771]: To avoid occasional spurious test_idle failures on slower machines, increase the hover_delay in test_tooltip.

bpo-37824 [https://bugs.python.org/issue?@action=redirect&bpo=37824]: Properly handle user input warnings in IDLE shell. Cease turning SyntaxWarnings into SyntaxErrors.

bpo-37929 [https://bugs.python.org/issue?@action=redirect&bpo=37929]: IDLE Settings dialog now closes properly when there is no shell window.

bpo-37902 [https://bugs.python.org/issue?@action=redirect&bpo=37902]: Add mousewheel scrolling for IDLE module, path, and stack browsers. Patch by George Zhang.

bpo-37849 [https://bugs.python.org/issue?@action=redirect&bpo=37849]: Fixed completions list appearing too high or low when shown above the current line.

bpo-36419 [https://bugs.python.org/issue?@action=redirect&bpo=36419]: Refactor IDLE autocomplete and improve testing.

bpo-37748 [https://bugs.python.org/issue?@action=redirect&bpo=37748]: Reorder the Run menu. Put the most common choice, Run Module, at the top.

bpo-37692 [https://bugs.python.org/issue?@action=redirect&bpo=37692]: Improve highlight config sample with example shell interaction and better labels for shell elements.

bpo-37628 [https://bugs.python.org/issue?@action=redirect&bpo=37628]: Settings dialog no longer expands with font size.

bpo-37627 [https://bugs.python.org/issue?@action=redirect&bpo=37627]: Initialize the Customize Run dialog with the command line arguments most recently entered before. The user can optionally edit before submitting them.

bpo-33610 [https://bugs.python.org/issue?@action=redirect&bpo=33610]: Fix code context not showing the correct context when first toggled on.

bpo-37530 [https://bugs.python.org/issue?@action=redirect&bpo=37530]: Optimize code context to reduce unneeded background activity. Font and highlight changes now occur along with text changes instead of after a random delay.

bpo-27452 [https://bugs.python.org/issue?@action=redirect&bpo=27452]: Cleanup config.py by inlining RemoveFile and simplifying the handling of file in CreateConfigHandlers.

bpo-37325 [https://bugs.python.org/issue?@action=redirect&bpo=37325]: Fix tab focus traversal order for help source and custom run dialogs.

bpo-17535 [https://bugs.python.org/issue?@action=redirect&bpo=17535]: Add optional line numbers for IDLE editor windows. Windows open without line numbers unless set otherwise in the General tab of the configuration dialog.

bpo-26806 [https://bugs.python.org/issue?@action=redirect&bpo=26806]: To compensate for stack frames added by IDLE and avoid possible problems with low recursion limits, add 30 to limits in the user code execution process. Subtract 30 when reporting recursion limits to make this addition mostly transparent.

bpo-36390 [https://bugs.python.org/issue?@action=redirect&bpo=36390]: Gather Format menu functions into format.py. Combine paragraph.py, rstrip.py, and format methods from editor.py.

Tools/Demos

bpo-37803 [https://bugs.python.org/issue?@action=redirect&bpo=37803]: pdb’s --help and --version long options now work.

bpo-37675 [https://bugs.python.org/issue?@action=redirect&bpo=37675]: 2to3 now works when run from a zipped standard library.

Python 3.7.4 final

Release date: 2019-07-08

Core and Builtins

bpo-37500 [https://bugs.python.org/issue?@action=redirect&bpo=37500]: Due to unintended side effects, revert the change introduced by bpo-1875 [https://bugs.python.org/issue?@action=redirect&bpo=1875] in 3.7.4rc1 to check for syntax errors in dead conditional code blocks.

Documentation

bpo-37149 [https://bugs.python.org/issue?@action=redirect&bpo=37149]: Replace the dead link to the Tkinter 8.5 reference by John Shipman, New Mexico Tech, with a link to the archive.org copy.

Python 3.7.4 release candidate 2

Release date: 2019-07-02

Security

bpo-37463 [https://bugs.python.org/issue?@action=redirect&bpo=37463]: ssl.match_hostname() no longer accepts IPv4 addresses with additional text after the address and only quad-dotted notation without trailing whitespaces. Some inet_aton() implementations ignore whitespace and all data after whitespace, e.g. ‘127.0.0.1 whatever’.

Core and Builtins

bpo-24214 [https://bugs.python.org/issue?@action=redirect&bpo=24214]: Improved support of the surrogatepass error handler in the UTF-8 and UTF-16 incremental decoders.

Library

bpo-37440 [https://bugs.python.org/issue?@action=redirect&bpo=37440]: http.client now enables TLS 1.3 post-handshake authentication for default context or if a cert_file is passed to HTTPSConnection.

bpo-37437 [https://bugs.python.org/issue?@action=redirect&bpo=37437]: Update vendorized expat version to 2.2.7.

bpo-37428 [https://bugs.python.org/issue?@action=redirect&bpo=37428]: SSLContext.post_handshake_auth = True no longer sets SSL_VERIFY_POST_HANDSHAKE verify flag for client connections. Although the option is documented as ignored for clients, OpenSSL implicitly enables cert chain validation when the flag is set.

bpo-32627 [https://bugs.python.org/issue?@action=redirect&bpo=32627]: Fix compile error when _uuid headers conflicting included.

Windows

bpo-37369 [https://bugs.python.org/issue?@action=redirect&bpo=37369]: Fixes path for sys.executable when running from the Microsoft Store.

bpo-35360 [https://bugs.python.org/issue?@action=redirect&bpo=35360]: Update Windows builds to use SQLite 3.28.0.

macOS

bpo-34602 [https://bugs.python.org/issue?@action=redirect&bpo=34602]: Avoid test suite failures on macOS by no longer calling resource.setrlimit to increase the process stack size limit at runtime. The runtime change is no longer needed since the interpreter is being built with a larger default stack size.

Python 3.7.4 release candidate 1

Release date: 2019-06-18

Security

bpo-35907 [https://bugs.python.org/issue?@action=redirect&bpo=35907]: CVE-2019-9948: Avoid file reading by disallowing local-file:// and local_file:// URL schemes in URLopener().open() and URLopener().retrieve() of urllib.request.

bpo-36742 [https://bugs.python.org/issue?@action=redirect&bpo=36742]: Fixes mishandling of pre-normalization characters in urlsplit().

bpo-30458 [https://bugs.python.org/issue?@action=redirect&bpo=30458]: Address CVE-2019-9740 by disallowing URL paths with embedded whitespace or control characters through into the underlying http client request. Such potentially malicious header injection URLs now cause an http.client.InvalidURL exception to be raised.

bpo-33529 [https://bugs.python.org/issue?@action=redirect&bpo=33529]: Prevent fold function used in email header encoding from entering infinite loop when there are too many non-ASCII characters in a header.

bpo-35755 [https://bugs.python.org/issue?@action=redirect&bpo=35755]: shutil.which() now uses os.confstr("CS_PATH") if available and if the PATH environment variable is not set. Remove also the current directory from posixpath.defpath. On Unix, shutil.which() and the subprocess module no longer search the executable in the current directory if the PATH environment variable is not set.

Core and Builtins

bpo-37269 [https://bugs.python.org/issue?@action=redirect&bpo=37269]: Fix a bug in the peephole optimizer that was not treating correctly constant conditions with binary operators. Patch by Pablo Galindo.

bpo-37219 [https://bugs.python.org/issue?@action=redirect&bpo=37219]: Remove errorneous optimization for empty set differences.

bpo-26423 [https://bugs.python.org/issue?@action=redirect&bpo=26423]: Fix possible overflow in wrap_lenfunc() when sizeof(long) < sizeof(Py_ssize_t) (e.g., 64-bit Windows).

bpo-36829 [https://bugs.python.org/issue?@action=redirect&bpo=36829]: PyErr_WriteUnraisable() now displays the exception even if displaying the traceback failed. Moreover, hold a strong reference to sys.stderr while using it. Document that an exception must be set when calling PyErr_WriteUnraisable().

bpo-36907 [https://bugs.python.org/issue?@action=redirect&bpo=36907]: Fix a crash when calling a C function with a keyword dict (f(**kwargs)) and changing the dict kwargs while that function is running.

bpo-36946 [https://bugs.python.org/issue?@action=redirect&bpo=36946]: Fix possible signed integer overflow when handling slices.

bpo-27987 [https://bugs.python.org/issue?@action=redirect&bpo=27987]: PyGC_Head structure is aligned to long double. This is needed to ensure GC-ed objects are aligned properly. Patch by Inada Naoki.

bpo-1875 [https://bugs.python.org/issue?@action=redirect&bpo=1875]: A SyntaxError is now raised if a code blocks that will be optimized away (e.g. if conditions that are always false) contains syntax errors. Patch by Pablo Galindo. (Reverted in 3.7.4 final by bpo-37500 [https://bugs.python.org/issue?@action=redirect&bpo=37500].)

bpo-28866 [https://bugs.python.org/issue?@action=redirect&bpo=28866]: Avoid caching attributes of classes which type defines mro() to avoid a hard cache invalidation problem.

bpo-27639 [https://bugs.python.org/issue?@action=redirect&bpo=27639]: Correct return type for UserList slicing operations. Patch by Michael Blahay, Erick Cervantes, and vaultah

bpo-32849 [https://bugs.python.org/issue?@action=redirect&bpo=32849]: Fix Python Initialization code on FreeBSD to detect properly when stdin file descriptor (fd 0) is invalid.

bpo-27987 [https://bugs.python.org/issue?@action=redirect&bpo=27987]: pymalloc returns memory blocks aligned by 16 bytes, instead of 8 bytes, on 64-bit platforms to conform x86-64 ABI. Recent compilers assume this alignment more often. Patch by Inada Naoki.

bpo-36504 [https://bugs.python.org/issue?@action=redirect&bpo=36504]: Fix signed integer overflow in _ctypes.c’s PyCArrayType_new().

bpo-20844 [https://bugs.python.org/issue?@action=redirect&bpo=20844]: Fix running script with encoding cookie and LF line ending may fail on Windows.

bpo-24214 [https://bugs.python.org/issue?@action=redirect&bpo=24214]: Fixed support of the surrogatepass error handler in the UTF-8 incremental decoder.

bpo-36459 [https://bugs.python.org/issue?@action=redirect&bpo=36459]: Fix a possible double PyMem_FREE() due to tokenizer.c’s tok_nextc().

bpo-36433 [https://bugs.python.org/issue?@action=redirect&bpo=36433]: Fixed TypeError message in classmethoddescr_call.

bpo-36430 [https://bugs.python.org/issue?@action=redirect&bpo=36430]: Fix a possible reference leak in itertools.count().

bpo-36440 [https://bugs.python.org/issue?@action=redirect&bpo=36440]: Include node names in ParserError messages, instead of numeric IDs. Patch by A. Skrobov.

bpo-36421 [https://bugs.python.org/issue?@action=redirect&bpo=36421]: Fix a possible double decref in _ctypes.c’s PyCArrayType_new().

bpo-36256 [https://bugs.python.org/issue?@action=redirect&bpo=36256]: Fix bug in parsermodule when parsing a state in a DFA that has two or more arcs with labels of the same type. Patch by Pablo Galindo.

bpo-36236 [https://bugs.python.org/issue?@action=redirect&bpo=36236]: At Python initialization, the current directory is no longer prepended to sys.path if it has been removed.

bpo-36262 [https://bugs.python.org/issue?@action=redirect&bpo=36262]: Fix an unlikely memory leak on conversion from string to float in the function _Py_dg_strtod() used by float(str), complex(str), pickle.load(), marshal.load(), etc.

bpo-36218 [https://bugs.python.org/issue?@action=redirect&bpo=36218]: Fix a segfault occuring when sorting a list of heterogeneous values. Patch contributed by Rémi Lapeyre and Elliot Gorokhovsky.

bpo-36035 [https://bugs.python.org/issue?@action=redirect&bpo=36035]: Added fix for broken symlinks in combination with pathlib

bpo-18372 [https://bugs.python.org/issue?@action=redirect&bpo=18372]: Add missing PyObject_GC_Track() calls in the pickle module. Patch by Zackery Spytz.

bpo-34408 [https://bugs.python.org/issue?@action=redirect&bpo=34408]: Prevent a null pointer dereference and resource leakage in PyInterpreterState_New().

Library

bpo-37280 [https://bugs.python.org/issue?@action=redirect&bpo=37280]: Use threadpool for reading from file for sendfile fallback mode.

bpo-37279 [https://bugs.python.org/issue?@action=redirect&bpo=37279]: Fix asyncio sendfile support when sendfile sends extra data in fallback mode.

bpo-19865 [https://bugs.python.org/issue?@action=redirect&bpo=19865]: ctypes.create_unicode_buffer() now also supports non-BMP characters on platforms with 16-bit wchar_t (for example, Windows and AIX).

bpo-35922 [https://bugs.python.org/issue?@action=redirect&bpo=35922]: Fix RobotFileParser.crawl_delay() and RobotFileParser.request_rate() to return None rather than raise AttributeError when no relevant rule is defined in the robots.txt file. Patch by Rémi Lapeyre.

bpo-36607 [https://bugs.python.org/issue?@action=redirect&bpo=36607]: Eliminate RuntimeError raised by asyncio.all_tasks() if internal tasks weak set is changed by another thread during iteration.

bpo-36402 [https://bugs.python.org/issue?@action=redirect&bpo=36402]: Fix a race condition at Python shutdown when waiting for threads. Wait until the Python thread state of all non-daemon threads get deleted (join all non-daemon threads), rather than just wait until non-daemon Python threads complete.

bpo-34886 [https://bugs.python.org/issue?@action=redirect&bpo=34886]: Fix an unintended ValueError from subprocess.run() when checking for conflicting input and stdin or capture_output and stdout or stderr args when they were explicitly provided but with None values within a passed in **kwargs dict rather than as passed directly by name. Patch contributed by Rémi Lapeyre.

bpo-37173 [https://bugs.python.org/issue?@action=redirect&bpo=37173]: The exception message for inspect.getfile() now correctly reports the passed class rather than the builtins module.

bpo-12639 [https://bugs.python.org/issue?@action=redirect&bpo=12639]: msilib.Directory.start_component() no longer fails if keyfile is not None.

bpo-36520 [https://bugs.python.org/issue?@action=redirect&bpo=36520]: Lengthy email headers with UTF-8 characters are now properly encoded when they are folded. Patch by Jeffrey Kintscher.

bpo-37054 [https://bugs.python.org/issue?@action=redirect&bpo=37054]: Fix destructor _pyio.BytesIO and _pyio.TextIOWrapper: initialize their _buffer attribute as soon as possible (in the class body), because it’s used by __del__() which calls close().

bpo-30835 [https://bugs.python.org/issue?@action=redirect&bpo=30835]: Fixed a bug in email parsing where a message with invalid bytes in content-transfer-encoding of a multipart message can cause an AttributeError. Patch by Andrew Donnellan.

bpo-37035 [https://bugs.python.org/issue?@action=redirect&bpo=37035]: Don’t log OSError based exceptions if a fatal error has occurred in asyncio transport. Peer can generate almost any OSError, user cannot avoid these exceptions by fixing own code. Errors are still propagated to user code, it’s just logging them is pointless and pollute asyncio logs.

bpo-37008 [https://bugs.python.org/issue?@action=redirect&bpo=37008]: Add support for calling next() with the mock resulting from unittest.mock.mock_open()

bpo-27737 [https://bugs.python.org/issue?@action=redirect&bpo=27737]: Allow whitespace only header encoding in email.header - by Batuhan Taskaya

bpo-36969 [https://bugs.python.org/issue?@action=redirect&bpo=36969]: PDB command args now display keyword only arguments. Patch contributed by Rémi Lapeyre.

bpo-36983 [https://bugs.python.org/issue?@action=redirect&bpo=36983]: Add missing names to typing.__all__: ChainMap, ForwardRef, OrderedDict - by Anthony Sottile.

bpo-21315 [https://bugs.python.org/issue?@action=redirect&bpo=21315]: Email headers containing RFC2047 encoded words are parsed despite the missing whitespace, and a defect registered. Also missing trailing whitespace after encoded words is now registered as a defect.

bpo-33524 [https://bugs.python.org/issue?@action=redirect&bpo=33524]: Fix the folding of email header when the max_line_length is 0 or None and the header contains non-ascii characters. Contributed by Licht Takeuchi (@Licht-T).

bpo-24564 [https://bugs.python.org/issue?@action=redirect&bpo=24564]: shutil.copystat() now ignores errno.EINVAL on os.setxattr() which may occur when copying files on filesystems without extended attributes support.

Original patch by Giampaolo Rodola, updated by Ying Wang.

bpo-36845 [https://bugs.python.org/issue?@action=redirect&bpo=36845]: Added validation of integer prefixes to the construction of IP networks and interfaces in the ipaddress module.

bpo-35545 [https://bugs.python.org/issue?@action=redirect&bpo=35545]: Fix asyncio discarding IPv6 scopes when ensuring hostname resolutions internally

bpo-35070 [https://bugs.python.org/issue?@action=redirect&bpo=35070]: posix.getgrouplist() now works correctly when the user belongs to NGROUPS_MAX supplemental groups. Patch by Jeffrey Kintscher.

bpo-24538 [https://bugs.python.org/issue?@action=redirect&bpo=24538]: In shutil.copystat(), first copy extended file attributes and then file permissions, since extended attributes can only be set on the destination while it is still writeable.

bpo-33110 [https://bugs.python.org/issue?@action=redirect&bpo=33110]: Handle exceptions raised by functions added by concurrent.futures add_done_callback correctly when the Future has already completed.

bpo-26903 [https://bugs.python.org/issue?@action=redirect&bpo=26903]: Limit max_workers in ProcessPoolExecutor to 61 to work around a WaitForMultipleObjects limitation.

bpo-36813 [https://bugs.python.org/issue?@action=redirect&bpo=36813]: Fix QueueListener to call queue.task_done() upon stopping. Patch by Bar Harel.

bpo-36734 [https://bugs.python.org/issue?@action=redirect&bpo=36734]: Fix compilation of faulthandler.c on HP-UX. Initialize stack_t current_stack to zero using memset().

bpo-29183 [https://bugs.python.org/issue?@action=redirect&bpo=29183]: Fix double exceptions in wsgiref.handlers.BaseHandler by calling its close() method only when no exception is raised.

bpo-36650 [https://bugs.python.org/issue?@action=redirect&bpo=36650]: The C version of functools.lru_cache() was treating calls with an empty **kwargs dictionary as being distinct from calls with no keywords at all. This did not result in an incorrect answer, but it did trigger an unexpected cache miss.

bpo-28552 [https://bugs.python.org/issue?@action=redirect&bpo=28552]: Fix distutils.sysconfig if sys.executable is None or an empty string: use os.getcwd() to initialize project_base. Fix also the distutils build command: don’t use sys.executable if it is None or an empty string.

bpo-35755 [https://bugs.python.org/issue?@action=redirect&bpo=35755]: shutil.which() and distutils.spawn.find_executable() now use os.confstr("CS_PATH") if available instead of os.defpath, if the PATH environment variable is not set. Moreover, don’t use os.confstr("CS_PATH") nor os.defpath if the PATH environment variable is set to an empty string.

bpo-36613 [https://bugs.python.org/issue?@action=redirect&bpo=36613]: Fix asyncio wait() not removing callback if exception

bpo-36598 [https://bugs.python.org/issue?@action=redirect&bpo=36598]: Fix isinstance check for Mock objects with spec when the code is executed under tracing. Patch by Karthikeyan Singaravelan.

bpo-36533 [https://bugs.python.org/issue?@action=redirect&bpo=36533]: Reinitialize logging.Handler locks in forked child processes instead of attempting to acquire them all in the parent before forking only to be released in the child process. The acquire/release pattern was leading to deadlocks in code that has implemented any form of chained logging handlers that depend upon one another as the lock acquision order cannot be guaranteed.

bpo-36522 [https://bugs.python.org/issue?@action=redirect&bpo=36522]: If debuglevel is set to >0 in http.client, print all values for headers with multiple values for the same header name. Patch by Matt Houglum.

bpo-36492 [https://bugs.python.org/issue?@action=redirect&bpo=36492]: Arbitrary keyword arguments (even with names “self” and “func”) can now be passed to some functions which should accept arbitrary keyword arguments and pass them to other function (for example partialmethod(), TestCase.addCleanup() and Profile.runcall()) if the required arguments are passed as positional arguments.

bpo-36434 [https://bugs.python.org/issue?@action=redirect&bpo=36434]: Errors during writing to a ZIP file no longer prevent to properly close it.

bpo-34745 [https://bugs.python.org/issue?@action=redirect&bpo=34745]: Fix asyncio ssl memory issues caused by circular references

bpo-36321 [https://bugs.python.org/issue?@action=redirect&bpo=36321]: collections.namedtuple() misspelled the name of an attribute. To be consistent with typing.NamedTuple, the attribute name should have been “_field_defaults” instead of “_fields_defaults”. For backwards compatibility, both spellings are now created. The misspelled version may be removed in the future.

bpo-36272 [https://bugs.python.org/issue?@action=redirect&bpo=36272]: logging does not silently ignore RecursionError anymore. Patch contributed by Rémi Lapeyre.

bpo-36235 [https://bugs.python.org/issue?@action=redirect&bpo=36235]: Fix CFLAGS in customize_compiler() of distutils.sysconfig: when the CFLAGS environment variable is defined, don’t override CFLAGS variable with the OPT variable anymore. Initial patch written by David Malcolm.

bpo-35125 [https://bugs.python.org/issue?@action=redirect&bpo=35125]: Asyncio: Remove inner callback on outer cancellation in shield

bpo-35802 [https://bugs.python.org/issue?@action=redirect&bpo=35802]: Clean up code which checked presence of os.stat / os.lstat / os.chmod which are always present. Patch by Anthony Sottile.

bpo-23078 [https://bugs.python.org/issue?@action=redirect&bpo=23078]: Add support for classmethod() and staticmethod() to unittest.mock.create_autospec(). Initial patch by Felipe Ochoa.

bpo-35721 [https://bugs.python.org/issue?@action=redirect&bpo=35721]: Fix asyncio.SelectorEventLoop.subprocess_exec() leaks file descriptors if Popen fails and called with stdin=subprocess.PIPE. Patch by Niklas Fiekas.

bpo-35726 [https://bugs.python.org/issue?@action=redirect&bpo=35726]: QueueHandler.prepare() now makes a copy of the record before modifying and enqueueing it, to avoid affecting other handlers in the chain.

bpo-31855 [https://bugs.python.org/issue?@action=redirect&bpo=31855]: unittest.mock.mock_open() results now respects the argument of read([size]). Patch contributed by Rémi Lapeyre.

bpo-35082 [https://bugs.python.org/issue?@action=redirect&bpo=35082]: Don’t return deleted attributes when calling dir on a unittest.mock.Mock.

bpo-34547 [https://bugs.python.org/issue?@action=redirect&bpo=34547]: wsgiref.handlers.BaseHandler now handles abrupt client connection terminations gracefully. Patch by Petter Strandmark.

bpo-34424 [https://bugs.python.org/issue?@action=redirect&bpo=34424]: Fix serialization of messages containing encoded strings when the policy.linesep is set to a multi-character string. Patch by Jens Troeger.

bpo-33361 [https://bugs.python.org/issue?@action=redirect&bpo=33361]: Fix a bug in codecs.StreamRecoder where seeking might leave old data in a buffer and break subsequent read calls. Patch by Ammar Askar.

bpo-31922 [https://bugs.python.org/issue?@action=redirect&bpo=31922]: asyncio.AbstractEventLoop.create_datagram_endpoint(): Do not connect UDP socket when broadcast is allowed. This allows to receive replies after a UDP broadcast.

bpo-22102 [https://bugs.python.org/issue?@action=redirect&bpo=22102]: Added support for ZIP files with disks set to 0. Such files are commonly created by builtin tools on Windows when use ZIP64 extension. Patch by Francisco Facioni.

bpo-27141 [https://bugs.python.org/issue?@action=redirect&bpo=27141]: Added a __copy__() to collections.UserList and collections.UserDict in order to correctly implement shallow copying of the objects. Patch by Bar Harel.

bpo-31829 [https://bugs.python.org/issue?@action=redirect&bpo=31829]: \r, \0 and \x1a (end-of-file on Windows) are now escaped in protocol 0 pickles of Unicode strings. This allows to load them without loss from files open in text mode in Python 2.

bpo-31292 [https://bugs.python.org/issue?@action=redirect&bpo=31292]: Fix setup.py check --restructuredtext for files containing include directives.

bpo-23395 [https://bugs.python.org/issue?@action=redirect&bpo=23395]: _thread.interrupt_main() now avoids setting the Python error status if the SIGINT signal is ignored or not handled by Python.

Documentation

bpo-34903 [https://bugs.python.org/issue?@action=redirect&bpo=34903]: Documented that in datetime.datetime.strptime(), the leading zero in some two-digit formats is optional. Patch by Mike Gleen.

bpo-36984 [https://bugs.python.org/issue?@action=redirect&bpo=36984]: Improve version added references in typing module - by Anthony Sottile.

bpo-36868 [https://bugs.python.org/issue?@action=redirect&bpo=36868]: What’s new now mentions SSLContext.hostname_checks_common_name instead of SSLContext.host_flags.

bpo-36783 [https://bugs.python.org/issue?@action=redirect&bpo=36783]: Added C API Documentation for Time_FromTimeAndFold and PyDateTime_FromDateAndTimeAndFold as per PEP 495. Patch by Edison Abahurire.

bpo-30840 [https://bugs.python.org/issue?@action=redirect&bpo=30840]: Document relative imports

bpo-36523 [https://bugs.python.org/issue?@action=redirect&bpo=36523]: Add docstring for io.IOBase.writelines().

bpo-36425 [https://bugs.python.org/issue?@action=redirect&bpo=36425]: New documentation translation: Simplified Chinese [https://docs.python.org/zh-cn/].

bpo-36157 [https://bugs.python.org/issue?@action=redirect&bpo=36157]: Added Documention for PyInterpreterState_Main().

bpo-36138 [https://bugs.python.org/issue?@action=redirect&bpo=36138]: Improve documentation about converting datetime.timedelta to scalars.

bpo-22865 [https://bugs.python.org/issue?@action=redirect&bpo=22865]: Add detail to the documentation on the pty.spawn function.

bpo-35581 [https://bugs.python.org/issue?@action=redirect&bpo=35581]: @typing.type_check_only now allows type stubs to mark functions and classes not available during runtime.

bpo-35564 [https://bugs.python.org/issue?@action=redirect&bpo=35564]: Explicitly set master_doc variable in conf.py for compliance with Sphinx 2.0

bpo-10536 [https://bugs.python.org/issue?@action=redirect&bpo=10536]: Enhance the gettext docs. Patch by Éric Araujo

bpo-32995 [https://bugs.python.org/issue?@action=redirect&bpo=32995]: Added the context variable in glossary.

bpo-33832 [https://bugs.python.org/issue?@action=redirect&bpo=33832]: Add glossary entry for ‘magic method’.

bpo-33482 [https://bugs.python.org/issue?@action=redirect&bpo=33482]: Make codecs.StreamRecoder.writelines take a list of bytes.

bpo-25735 [https://bugs.python.org/issue?@action=redirect&bpo=25735]: Added documentation for func factorial to indicate that returns integer values

Tests

bpo-35998 [https://bugs.python.org/issue?@action=redirect&bpo=35998]: Avoid TimeoutError in test_asyncio: test_start_tls_server_1()

bpo-37153 [https://bugs.python.org/issue?@action=redirect&bpo=37153]: test_venv.test_mutiprocessing() now explicitly calls pool.terminate() to wait until the pool completes.

bpo-37081 [https://bugs.python.org/issue?@action=redirect&bpo=37081]: Test with OpenSSL 1.1.1c

bpo-36915 [https://bugs.python.org/issue?@action=redirect&bpo=36915]: The main regrtest process now always removes all temporary directories of worker processes even if they crash or if they are killed on KeyboardInterrupt (CTRL+c).

bpo-36719 [https://bugs.python.org/issue?@action=redirect&bpo=36719]: “python3 -m test -jN …” now continues the execution of next tests when a worker process crash (CHILD_ERROR state). Previously, the test suite stopped immediately. Use –failfast to stop at the first error.

bpo-36816 [https://bugs.python.org/issue?@action=redirect&bpo=36816]: Update Lib/test/selfsigned_pythontestdotnet.pem to match self-signed.pythontest.net’s new TLS certificate.

bpo-35925 [https://bugs.python.org/issue?@action=redirect&bpo=35925]: Skip httplib and nntplib networking tests when they would otherwise fail due to a modern OS or distro with a default OpenSSL policy of rejecting connections to servers with weak certificates.

bpo-36719 [https://bugs.python.org/issue?@action=redirect&bpo=36719]: regrtest now always detects uncollectable objects. Previously, the check was only enabled by --findleaks. The check now also works with -jN/--multiprocess N. --findleaks becomes a deprecated alias to --fail-env-changed.

bpo-36725 [https://bugs.python.org/issue?@action=redirect&bpo=36725]: When using mulitprocessing mode (-jN), regrtest now better reports errors if a worker process fails, and it exits immediately on a worker thread failure or when interrupted.

bpo-36454 [https://bugs.python.org/issue?@action=redirect&bpo=36454]: Change test_time.test_monotonic() to test only the lower bound of elapsed time after a sleep command rather than the upper bound. This prevents unnecessary test failures on slow buildbots. Patch by Victor Stinner.

bpo-36629 [https://bugs.python.org/issue?@action=redirect&bpo=36629]: Fix test_imap4_host_default_value() of test_imaplib: catch also errno.ENETUNREACH error.

bpo-36611 [https://bugs.python.org/issue?@action=redirect&bpo=36611]: Fix test_sys.test_getallocatedblocks() when tracemalloc is enabled.

bpo-36560 [https://bugs.python.org/issue?@action=redirect&bpo=36560]: Fix reference leak hunting in regrtest: compute also deltas (of reference count, allocated memory blocks, file descriptor count) during warmup, to ensure that everything is initialized before starting to hunt reference leaks.

bpo-36565 [https://bugs.python.org/issue?@action=redirect&bpo=36565]: Fix reference hunting (python3 -m test -R 3:3) when Python has no built-in abc module.

bpo-36436 [https://bugs.python.org/issue?@action=redirect&bpo=36436]: Fix _testcapi.pymem_buffer_overflow(): handle memory allocation failure.

Build

bpo-36605 [https://bugs.python.org/issue?@action=redirect&bpo=36605]: make tags and make TAGS now also parse Modules/_io/*.c and Modules/_io/*.h.

bpo-36508 [https://bugs.python.org/issue?@action=redirect&bpo=36508]: python-config --ldflags no longer includes flags of the LINKFORSHARED variable. The LINKFORSHARED variable must only be used to build executables.

Windows

bpo-34631 [https://bugs.python.org/issue?@action=redirect&bpo=34631]: Updated OpenSSL to 1.1.1c in Windows installer

bpo-37267 [https://bugs.python.org/issue?@action=redirect&bpo=37267]: On Windows, os.dup() no longer creates an inheritable fd when handling a character file.

bpo-36779 [https://bugs.python.org/issue?@action=redirect&bpo=36779]: Ensure time.tzname is correct on Windows when the active code page is set to CP_UTF7 or CP_UTF8.

bpo-36965 [https://bugs.python.org/issue?@action=redirect&bpo=36965]: include of STATUS_CONTROL_C_EXIT without depending on MSC compiler

bpo-36649 [https://bugs.python.org/issue?@action=redirect&bpo=36649]: Remove trailing spaces for registry keys when installed via the Store.

bpo-34144 [https://bugs.python.org/issue?@action=redirect&bpo=34144]: Fixed activate.bat to correctly update codepage when chcp.com returns dots in output. Patch by Lorenz Mende.

bpo-35941 [https://bugs.python.org/issue?@action=redirect&bpo=35941]: enum_certificates function of the ssl module now returns certificates from all available certificate stores inside windows in a query instead of returning only certificates from the system wide certificate store. This includes certificates from these certificate stores: local machine, local machine enterprise, local machine group policy, current user, current user group policy, services, users. ssl.enum_crls() function is changed in the same way to return all certificate revocation lists inside the windows certificate revocation list stores.

bpo-36441 [https://bugs.python.org/issue?@action=redirect&bpo=36441]: Fixes creating a venv when debug binaries are installed.

bpo-36312 [https://bugs.python.org/issue?@action=redirect&bpo=36312]: Fixed decoders for the following code pages: 50220, 50221, 50222, 50225, 50227, 50229, 57002 through 57011, 65000 and 42.

bpo-36010 [https://bugs.python.org/issue?@action=redirect&bpo=36010]: Add the venv standard library module to the nuget distribution for Windows.

bpo-34060 [https://bugs.python.org/issue?@action=redirect&bpo=34060]: Report system load when running test suite on Windows. Patch by Ammar Askar. Based on prior work by Jeremy Kloth.

macOS

bpo-35360 [https://bugs.python.org/issue?@action=redirect&bpo=35360]: Update macOS installer to use SQLite 3.28.0.

bpo-34631 [https://bugs.python.org/issue?@action=redirect&bpo=34631]: Updated OpenSSL to 1.1.1c in macOS installer.

bpo-36231 [https://bugs.python.org/issue?@action=redirect&bpo=36231]: Support building Python on macOS without /usr/include installed. As of macOS 10.14, system header files are only available within an SDK provided by either the Command Line Tools or the Xcode app.

bpo-34602 [https://bugs.python.org/issue?@action=redirect&bpo=34602]: Avoid failures setting macOS stack resource limit with resource.setrlimit. This reverts an earlier fix for bpo-18075 [https://bugs.python.org/issue?@action=redirect&bpo=18075] which forced a non-default stack size when building the interpreter executable on macOS.

IDLE

bpo-37321 [https://bugs.python.org/issue?@action=redirect&bpo=37321]: Both subprocess connection error messages now refer to the ‘Startup failure’ section of the IDLE doc.

bpo-37177 [https://bugs.python.org/issue?@action=redirect&bpo=37177]: Properly ‘attach’ search dialogs to their main window so that they behave like other dialogs and do not get hidden behind their main window.

bpo-37039 [https://bugs.python.org/issue?@action=redirect&bpo=37039]: Adjust “Zoom Height” to individual screens by momemtarily maximizing the window on first use with a particular screen. Changing screen settings may invalidate the saved height. While a window is maximized, “Zoom Height” has no effect.

bpo-35763 [https://bugs.python.org/issue?@action=redirect&bpo=35763]: Make calltip reminder about ‘/’ meaning positional-only less obtrusive by only adding it when there is room on the first line.

bpo-5680 [https://bugs.python.org/issue?@action=redirect&bpo=5680]: Add ‘Run… Customized’ to the Run menu to run a module with customized settings. Any ‘command line arguments’ entered are added to sys.argv. One can suppress the normal Shell main module restart.

bpo-35610 [https://bugs.python.org/issue?@action=redirect&bpo=35610]: Replace now redundant .context_use_ps1 with .prompt_last_line. This finishes change started in bpo-31858 [https://bugs.python.org/issue?@action=redirect&bpo=31858].

bpo-37038 [https://bugs.python.org/issue?@action=redirect&bpo=37038]: Make idlelib.run runnable; add test clause.

bpo-36958 [https://bugs.python.org/issue?@action=redirect&bpo=36958]: Print any argument other than None or int passed to SystemExit or sys.exit().

bpo-13102 [https://bugs.python.org/issue?@action=redirect&bpo=13102]: When saving a file, call os.fsync() so bits are flushed to e.g. USB drive.

bpo-36429 [https://bugs.python.org/issue?@action=redirect&bpo=36429]: Fix starting IDLE with pyshell. Add idlelib.pyshell alias at top; remove pyshell alias at bottom. Remove obsolete __name__==’__main__’ command.

bpo-36405 [https://bugs.python.org/issue?@action=redirect&bpo=36405]: Use dict unpacking in idlelib.

bpo-36396 [https://bugs.python.org/issue?@action=redirect&bpo=36396]: Remove fgBg param of idlelib.config.GetHighlight(). This param was only used twice and changed the return type.

bpo-23205 [https://bugs.python.org/issue?@action=redirect&bpo=23205]: For the grep module, add tests for findfiles, refactor findfiles to be a module-level function, and refactor findfiles to use os.walk.

bpo-23216 [https://bugs.python.org/issue?@action=redirect&bpo=23216]: Add docstrings to IDLE search modules.

bpo-30348 [https://bugs.python.org/issue?@action=redirect&bpo=30348]: Increase test coverage of idlelib.autocomplete by 30%.

bpo-32411 [https://bugs.python.org/issue?@action=redirect&bpo=32411]: In browser.py, remove extraneous sorting by line number since dictionary was created in line number order.

Tools/Demos

bpo-14546 [https://bugs.python.org/issue?@action=redirect&bpo=14546]: Fix the argument handling in Tools/scripts/lll.py.

bpo-32217 [https://bugs.python.org/issue?@action=redirect&bpo=32217]: Fix freeze script on Windows.

C API

bpo-28805 [https://bugs.python.org/issue?@action=redirect&bpo=28805]: The METH_FASTCALL calling convention has been documented.

bpo-37170 [https://bugs.python.org/issue?@action=redirect&bpo=37170]: Fix the cast on error in PyLong_AsUnsignedLongLongMask().

bpo-36389 [https://bugs.python.org/issue?@action=redirect&bpo=36389]: Change the value of CLEANBYTE, DEADDYTE and FORBIDDENBYTE internal constants used by debug hooks on Python memory allocators (PyMem_SetupDebugHooks() function). Byte patterns 0xCB, 0xDB and 0xFB have been replaced with 0xCD, 0xDD and 0xFD to use the same values than Windows CRT debug malloc() and free().

Python 3.7.3 final

Release date: 2019-03-25

There were no new changes in version 3.7.3.

Python 3.7.3 release candidate 1

Release date: 2019-03-12

Security

bpo-36216 [https://bugs.python.org/issue?@action=redirect&bpo=36216]: Changes urlsplit() to raise ValueError when the URL contains characters that decompose under IDNA encoding (NFKC-normalization) into characters that affect how the URL is parsed.

bpo-35746 [https://bugs.python.org/issue?@action=redirect&bpo=35746]: [CVE-2019-5010] Fix a NULL pointer deref in ssl module. The cert parser did not handle CRL distribution points with empty DP or URI correctly. A malicious or buggy certificate can result into segfault. Vulnerability (TALOS-2018-0758) reported by Colin Read and Nicolas Edet of Cisco.

bpo-35121 [https://bugs.python.org/issue?@action=redirect&bpo=35121]: Don’t send cookies of domain A without Domain attribute to domain B when domain A is a suffix match of domain B while using a cookiejar with http.cookiejar.DefaultCookiePolicy policy. Patch by Karthikeyan Singaravelan.

Core and Builtins

bpo-35942 [https://bugs.python.org/issue?@action=redirect&bpo=35942]: The error message emitted when returning invalid types from __fspath__ in interfaces that allow passing PathLike objects has been improved and now it does explain the origin of the error.

bpo-35992 [https://bugs.python.org/issue?@action=redirect&bpo=35992]: Fix __class_getitem__() not being called on a class with a custom non-subscriptable metaclass.

bpo-35991 [https://bugs.python.org/issue?@action=redirect&bpo=35991]: Fix a potential double free in Modules/_randommodule.c.

bpo-35961 [https://bugs.python.org/issue?@action=redirect&bpo=35961]: Fix a crash in slice_richcompare(): use strong references rather than stolen references for the two temporary internal tuples.

bpo-31506 [https://bugs.python.org/issue?@action=redirect&bpo=31506]: Clarify the errors reported when object.__new__ and object.__init__ receive more than one argument. Contributed by Sanyam Khurana.

bpo-35720 [https://bugs.python.org/issue?@action=redirect&bpo=35720]: Fixed a minor memory leak in pymain_parse_cmdline_impl function in Modules/main.c

bpo-35623 [https://bugs.python.org/issue?@action=redirect&bpo=35623]: Fix a crash when sorting very long lists. Patch by Stephan Hohe.

bpo-35214 [https://bugs.python.org/issue?@action=redirect&bpo=35214]: clang Memory Sanitizer build instrumentation was added to work around false positives from posix, socket, time, test_io, and test_faulthandler.

bpo-35560 [https://bugs.python.org/issue?@action=redirect&bpo=35560]: Fix an assertion error in format() in debug build for floating point formatting with “n” format, zero padding and small width. Release build is not impacted. Patch by Karthikeyan Singaravelan.

bpo-35552 [https://bugs.python.org/issue?@action=redirect&bpo=35552]: Format characters %s and %V in PyUnicode_FromFormat() and %s in PyBytes_FromFormat() no longer read memory past the limit if precision is specified.

bpo-35504 [https://bugs.python.org/issue?@action=redirect&bpo=35504]: Fix segfaults and SystemErrors when deleting certain attributes. Patch by Zackery Spytz.

bpo-33989 [https://bugs.python.org/issue?@action=redirect&bpo=33989]: Fix a possible crash in list.sort() when sorting objects with ob_type->tp_richcompare == NULL. Patch by Zackery Spytz.

Library

bpo-35931 [https://bugs.python.org/issue?@action=redirect&bpo=35931]: The pdb debug command now gracefully handles all exceptions.

bpo-36251 [https://bugs.python.org/issue?@action=redirect&bpo=36251]: Fix format strings used for stderrprinter and re.Match reprs. Patch by Stephan Hohe.

bpo-35807 [https://bugs.python.org/issue?@action=redirect&bpo=35807]: Update ensurepip to install pip 19.0.3 and setuptools 40.8.0.

bpo-36179 [https://bugs.python.org/issue?@action=redirect&bpo=36179]: Fix two unlikely reference leaks in _hashopenssl. The leaks only occur in out-of-memory cases.

bpo-35178 [https://bugs.python.org/issue?@action=redirect&bpo=35178]: Ensure custom warnings.formatwarning() function can receive line as positional argument. Based on patch by Tashrif Billah.

bpo-36106 [https://bugs.python.org/issue?@action=redirect&bpo=36106]: Resolve potential name clash with libm’s sinpi(). Patch by Dmitrii Pasechnik.

bpo-35512 [https://bugs.python.org/issue?@action=redirect&bpo=35512]: unittest.mock.patch.dict() used as a decorator with string target resolves the target during function call instead of during decorator construction. Patch by Karthikeyan Singaravelan.

bpo-36091 [https://bugs.python.org/issue?@action=redirect&bpo=36091]: Clean up reference to async generator in Lib/types. Patch by Henry Chen.

bpo-35899 [https://bugs.python.org/issue?@action=redirect&bpo=35899]: Enum has been fixed to correctly handle empty strings and strings with non-Latin characters (ie. ‘α’, ‘א’) without crashing. Original patch contributed by Maxwell. Assisted by Stéphane Wirtel.

bpo-35918 [https://bugs.python.org/issue?@action=redirect&bpo=35918]: Removed broken has_key method from multiprocessing.managers.SyncManager.dict. Contributed by Rémi Lapeyre.

bpo-35960 [https://bugs.python.org/issue?@action=redirect&bpo=35960]: Fix dataclasses.field() throwing away empty mapping objects passed as metadata.

bpo-35847 [https://bugs.python.org/issue?@action=redirect&bpo=35847]: RISC-V needed the CTYPES_PASS_BY_REF_HACK. Fixes ctypes Structure test_pass_by_value.

bpo-35780 [https://bugs.python.org/issue?@action=redirect&bpo=35780]: Fix lru_cache() errors arising in recursive, reentrant, or multi-threaded code. These errors could result in orphan links and in the cache being trapped in a state with fewer than the specified maximum number of links. Fix handling of negative maxsize which should have been treated as zero. Fix errors in toggling the “full” status flag. Fix misordering of links when errors are encountered. Sync-up the C code and pure Python code for the space saving path in functions with a single positional argument. In this common case, the space overhead of an lru cache entry is reduced by almost half. Fix counting of cache misses. In error cases, the miss count was out of sync with the actual number of times the underlying user function was called.

bpo-23846 [https://bugs.python.org/issue?@action=redirect&bpo=23846]: asyncio.ProactorEventLoop now catches and logs send errors when the self-pipe is full.

bpo-34323 [https://bugs.python.org/issue?@action=redirect&bpo=34323]: asyncio: Enhance IocpProactor.close() log: wait 1 second before the first log, then log every second. Log also the number of seconds since close() was called.

bpo-34294 [https://bugs.python.org/issue?@action=redirect&bpo=34294]: re module, fix wrong capturing groups in rare cases. re.search(), re.findall(), re.sub() and other functions that scan through string looking for a match, should reset capturing groups between two match attempts. Patch by Ma Lin.

bpo-35717 [https://bugs.python.org/issue?@action=redirect&bpo=35717]: Fix KeyError exception raised when using enums and compile. Patch contributed by Rémi Lapeyre.

bpo-35699 [https://bugs.python.org/issue?@action=redirect&bpo=35699]: Fixed detection of Visual Studio Build Tools 2017 in distutils

bpo-32710 [https://bugs.python.org/issue?@action=redirect&bpo=32710]: Fix memory leaks in asyncio ProactorEventLoop on overlapped operation failure.

bpo-32710 [https://bugs.python.org/issue?@action=redirect&bpo=32710]: Fix a memory leak in asyncio in the ProactorEventLoop when ReadFile() or WSASend() overlapped operation fail immediately: release the internal buffer.

bpo-35682 [https://bugs.python.org/issue?@action=redirect&bpo=35682]: Fix asyncio.ProactorEventLoop.sendfile(): don’t attempt to set the result of an internal future if it’s already done.

bpo-35283 [https://bugs.python.org/issue?@action=redirect&bpo=35283]: Add a pending deprecated warning for the threading.Thread.isAlive() method. Patch by Dong-hee Na.

bpo-35643 [https://bugs.python.org/issue?@action=redirect&bpo=35643]: Fixed a SyntaxWarning: invalid escape sequence in Modules/_sha3/cleanup.py. Patch by Mickaël Schoentgen.

bpo-35615 [https://bugs.python.org/issue?@action=redirect&bpo=35615]: weakref: Fix a RuntimeError when copying a WeakKeyDictionary or a WeakValueDictionary, due to some keys or values disappearing while iterating.

bpo-28503 [https://bugs.python.org/issue?@action=redirect&bpo=28503]: The crypt module now internally uses the crypt_r() library function instead of crypt() when available.

bpo-35121 [https://bugs.python.org/issue?@action=redirect&bpo=35121]: Don’t set cookie for a request when the request path is a prefix match of the cookie’s path attribute but doesn’t end with “/”. Patch by Karthikeyan Singaravelan.

bpo-35585 [https://bugs.python.org/issue?@action=redirect&bpo=35585]: Speed-up building enums by value, e.g. http.HTTPStatus(200).

bpo-21478 [https://bugs.python.org/issue?@action=redirect&bpo=21478]: Calls to a child function created with unittest.mock.create_autospec() should propagate to the parent. Patch by Karthikeyan Singaravelan.

bpo-35513 [https://bugs.python.org/issue?@action=redirect&bpo=35513]: TextTestRunner of unittest.runner now uses time.perf_counter() rather than time.time() to measure the execution time of a test: time.time() can go backwards, whereas time.perf_counter() is monotonic.

bpo-35502 [https://bugs.python.org/issue?@action=redirect&bpo=35502]: Fixed reference leaks in xml.etree.ElementTree.TreeBuilder in case of unfinished building of the tree (in particular when an error was raised during parsing XML).

bpo-31446 [https://bugs.python.org/issue?@action=redirect&bpo=31446]: Copy command line that was passed to CreateProcessW since this function can change the content of the input buffer.

bpo-20239 [https://bugs.python.org/issue?@action=redirect&bpo=20239]: Allow repeated assignment deletion of unittest.mock.Mock attributes. Patch by Pablo Galindo.

bpo-17185 [https://bugs.python.org/issue?@action=redirect&bpo=17185]: Set __signature__ on mock for inspect to get signature. Patch by Karthikeyan Singaravelan.

bpo-10496 [https://bugs.python.org/issue?@action=redirect&bpo=10496]: check_environ() of distutils.utils now catches KeyError on calling pwd.getpwuid(): don’t create the HOME environment variable in this case.

bpo-35066 [https://bugs.python.org/issue?@action=redirect&bpo=35066]: Previously, calling the strftime() method on a datetime object with a trailing ‘%’ in the format string would result in an exception. However, this only occured when the datetime C module was being used; the python implementation did not match this behavior. Datetime is now PEP-399 compliant, and will not throw an exception on a trailing ‘%’.

bpo-24746 [https://bugs.python.org/issue?@action=redirect&bpo=24746]: Avoid stripping trailing whitespace in doctest fancy diff. Orignial patch by R. David Murray & Jairo Trad. Enhanced by Sanyam Khurana.

bpo-35198 [https://bugs.python.org/issue?@action=redirect&bpo=35198]: Fix C++ extension compilation on AIX

bpo-28441 [https://bugs.python.org/issue?@action=redirect&bpo=28441]: On Cygwin and MinGW, ensure that sys.executable always includes the full filename in the path, including the .exe suffix (unless it is a symbolic link).

bpo-34572 [https://bugs.python.org/issue?@action=redirect&bpo=34572]: Fix C implementation of pickle.loads to use importlib’s locking mechanisms, and thereby avoid using partially-loaded modules. Patch by Tim Burgess.

bpo-33687 [https://bugs.python.org/issue?@action=redirect&bpo=33687]: Fix the call to os.chmod() for uu.decode() if a mode is given or decoded. Patch by Timo Furrer.

bpo-32146 [https://bugs.python.org/issue?@action=redirect&bpo=32146]: Document the interaction between frozen executables and the spawn and forkserver start methods in multiprocessing.

Documentation

bpo-36083 [https://bugs.python.org/issue?@action=redirect&bpo=36083]: Fix formatting of –check-hash-based-pycs options in the manpage Synopsis.

bpo-34764 [https://bugs.python.org/issue?@action=redirect&bpo=34764]: Improve example of iter() with 2nd sentinel argument.

bpo-21314 [https://bugs.python.org/issue?@action=redirect&bpo=21314]: A new entry was added to the Core Language Section of the Programming FAQ, which explaines the usage of slash(/) in the signature of a function. Patch by Lysandros Nikolaou

bpo-22062 [https://bugs.python.org/issue?@action=redirect&bpo=22062]: Update documentation and docstrings for pathlib. Original patch by Mike Short.

Tests

bpo-36234 [https://bugs.python.org/issue?@action=redirect&bpo=36234]: test_posix.PosixUidGidTests: add tests for invalid uid/gid type (str). Initial patch written by David Malcolm.

bpo-29571 [https://bugs.python.org/issue?@action=redirect&bpo=29571]: Fix test_re.test_locale_flag(): use locale.getpreferredencoding() rather than locale.getlocale() to get the locale encoding. With some locales, locale.getlocale() returns the wrong encoding. On Windows, set temporarily the LC_CTYPE locale to the user preferred encoding to ensure that it uses the ANSI code page, to be consistent with locale.getpreferredencoding().

bpo-36123 [https://bugs.python.org/issue?@action=redirect&bpo=36123]: Fix race condition in test_socket.

bpo-27313 [https://bugs.python.org/issue?@action=redirect&bpo=27313]: Avoid test_ttk_guionly ComboboxTest failure with macOS Cocoa Tk.

bpo-36019 [https://bugs.python.org/issue?@action=redirect&bpo=36019]: Add test.support.TEST_HTTP_URL and replace references of http://www.example.com by this new constant. Contributed by Stéphane Wirtel.

bpo-36037 [https://bugs.python.org/issue?@action=redirect&bpo=36037]: Fix test_ssl for strict OpenSSL configuration like RHEL8 strict crypto policy. Use older TLS version for minimum TLS version of the server SSL context if needed, to test TLS version older than default minimum TLS version.

bpo-35505 [https://bugs.python.org/issue?@action=redirect&bpo=35505]: Make test_imap4_host_default_value independent on whether the local IMAP server is running.

bpo-35917 [https://bugs.python.org/issue?@action=redirect&bpo=35917]: multiprocessing: provide unit tests for SyncManager and SharedMemoryManager classes + all the shareable types which are supposed to be supported by them. (patch by Giampaolo Rodola)

bpo-35772 [https://bugs.python.org/issue?@action=redirect&bpo=35772]: Fix sparse file tests of test_tarfile on ppc64 with the tmpfs filesystem. Fix the function testing if the filesystem supports sparse files: create a file which contains data and “holes”, instead of creating a file which contains no data. tmpfs effective block size is a page size (tmpfs lives in the page cache). RHEL uses 64 KiB pages on aarch64, ppc64, ppc64le, only s390x and x86_64 use 4 KiB pages, whereas the test punch holes of 4 KiB.

bpo-35045 [https://bugs.python.org/issue?@action=redirect&bpo=35045]: Make ssl tests less strict and also accept TLSv1 as system default. The changes unbreaks test_min_max_version on Fedora 29.

bpo-31731 [https://bugs.python.org/issue?@action=redirect&bpo=31731]: Fix a race condition in check_interrupted_write() of test_io: create directly the thread with SIGALRM signal blocked, rather than blocking the signal later from the thread. Previously, it was possible that the thread gets the signal before the signal is blocked.

bpo-35424 [https://bugs.python.org/issue?@action=redirect&bpo=35424]: Fix test_multiprocessing_main_handling: use multiprocessing.Pool with a context manager and then explicitly join the pool.

bpo-35519 [https://bugs.python.org/issue?@action=redirect&bpo=35519]: Rename test.bisect module to test.bisect_cmd to avoid conflict with bisect module when running directly a test like ./python Lib/test/test_xmlrpc.py.

bpo-35513 [https://bugs.python.org/issue?@action=redirect&bpo=35513]: Replace time.time() with time.monotonic() in tests to measure time delta.

bpo-34279 [https://bugs.python.org/issue?@action=redirect&bpo=34279]: test.support.run_unittest() no longer raise TestDidNotRun if the test result contains skipped tests. The exception is now only raised if no test have been run and no test have been skipped.

bpo-35412 [https://bugs.python.org/issue?@action=redirect&bpo=35412]: Add testcase to test_future4: check unicode literal.

bpo-26704 [https://bugs.python.org/issue?@action=redirect&bpo=26704]: Added test demonstrating double-patching of an instance method. Patch by Anthony Sottile.

Build

bpo-34691 [https://bugs.python.org/issue?@action=redirect&bpo=34691]: The _contextvars module is now built into the core Python library on Windows.

bpo-35683 [https://bugs.python.org/issue?@action=redirect&bpo=35683]: Improved Azure Pipelines build steps and now verifying layouts correctly

bpo-35642 [https://bugs.python.org/issue?@action=redirect&bpo=35642]: Remove asynciomodule.c from pythoncore.vcxproj

bpo-35550 [https://bugs.python.org/issue?@action=redirect&bpo=35550]: Fix incorrect Solaris #ifdef checks to look for __sun && __SVR4 instead of sun when compiling.

Windows

bpo-24643 [https://bugs.python.org/issue?@action=redirect&bpo=24643]: Fix name collisions due to #define timezone _timezone in PC/pyconfig.h.

bpo-35692 [https://bugs.python.org/issue?@action=redirect&bpo=35692]: pathlib no longer raises when checking file and directory existence on drives that are not ready

bpo-35872 [https://bugs.python.org/issue?@action=redirect&bpo=35872]: Uses the base Python executable when invoking venv in a virtual environment

bpo-35873 [https://bugs.python.org/issue?@action=redirect&bpo=35873]: Prevents venv paths being inherited by child processes

bpo-35299 [https://bugs.python.org/issue?@action=redirect&bpo=35299]: Fix sysconfig detection of the source directory and distutils handling of pyconfig.h during PGO profiling

bpo-32560 [https://bugs.python.org/issue?@action=redirect&bpo=32560]: The py launcher now forwards its STARTUPINFO structure to child processes.

bpo-35854 [https://bugs.python.org/issue?@action=redirect&bpo=35854]: Fix EnvBuilder and –symlinks in venv on Windows

bpo-35811 [https://bugs.python.org/issue?@action=redirect&bpo=35811]: Avoid propagating venv settings when launching via py.exe

bpo-35797 [https://bugs.python.org/issue?@action=redirect&bpo=35797]: Fix default executable used by the multiprocessing module

bpo-29734 [https://bugs.python.org/issue?@action=redirect&bpo=29734]: Fix handle leaks in os.stat on Windows.

bpo-35596 [https://bugs.python.org/issue?@action=redirect&bpo=35596]: Use unchecked PYCs for the embeddable distro to avoid zipimport restrictions.

bpo-35596 [https://bugs.python.org/issue?@action=redirect&bpo=35596]: Fix vcruntime140.dll being added to embeddable distro multiple times.

bpo-35402 [https://bugs.python.org/issue?@action=redirect&bpo=35402]: Update Windows build to use Tcl and Tk 8.6.9

bpo-33316 [https://bugs.python.org/issue?@action=redirect&bpo=33316]: PyThread_release_lock always fails

bpo-1104 [https://bugs.python.org/issue?@action=redirect&bpo=1104]: Correctly handle string length in msilib.SummaryInfo.GetProperty() to prevent it from truncating the last character.

IDLE

bpo-36176 [https://bugs.python.org/issue?@action=redirect&bpo=36176]: Fix IDLE autocomplete & calltip popup colors. Prevent conflicts with Linux dark themes (and slightly darken calltip background).

bpo-36152 [https://bugs.python.org/issue?@action=redirect&bpo=36152]: Remove colorizer.ColorDelegator.close_when_done and the corresponding argument of .close(). In IDLE, both have always been None or False since 2007.

bpo-32129 [https://bugs.python.org/issue?@action=redirect&bpo=32129]: Avoid blurry IDLE application icon on macOS with Tk 8.6. Patch by Kevin Walzer.

bpo-24310 [https://bugs.python.org/issue?@action=redirect&bpo=24310]: IDLE – Document settings dialog font tab sample.

bpo-36096 [https://bugs.python.org/issue?@action=redirect&bpo=36096]: Refactor class variables to instance variables in colorizer.

bpo-35833 [https://bugs.python.org/issue?@action=redirect&bpo=35833]: Revise IDLE doc for control codes sent to Shell. Add a code example block.

bpo-35770 [https://bugs.python.org/issue?@action=redirect&bpo=35770]: IDLE macosx deletes Options => Configure IDLE. It previously deleted Window => Zoom Height by mistake. (Zoom Height is now on the Options menu). On Mac, the settings dialog is accessed via Preferences on the IDLE menu.

bpo-35769 [https://bugs.python.org/issue?@action=redirect&bpo=35769]: Change IDLE’s new file name from ‘Untitled’ to ‘untitled’

bpo-35689 [https://bugs.python.org/issue?@action=redirect&bpo=35689]: Add docstrings and unittests for colorizer.py.

bpo-35660 [https://bugs.python.org/issue?@action=redirect&bpo=35660]: Fix imports in idlelib.window.

bpo-35641 [https://bugs.python.org/issue?@action=redirect&bpo=35641]: Proper format calltip when the function has no docstring.

bpo-33987 [https://bugs.python.org/issue?@action=redirect&bpo=33987]: Use ttk Frame for ttk widgets.

bpo-34055 [https://bugs.python.org/issue?@action=redirect&bpo=34055]: Fix erroneous ‘smart’ indents and newlines in IDLE Shell.

bpo-35591 [https://bugs.python.org/issue?@action=redirect&bpo=35591]: Find Selection now works when selection not found.

bpo-35196 [https://bugs.python.org/issue?@action=redirect&bpo=35196]: Speed up squeezer line counting.

bpo-35598 [https://bugs.python.org/issue?@action=redirect&bpo=35598]: Update config_key: use PEP 8 names and ttk widgets, make some objects global, and add tests.

bpo-28097 [https://bugs.python.org/issue?@action=redirect&bpo=28097]: Add Previous/Next History entries to Shell menu.

bpo-35208 [https://bugs.python.org/issue?@action=redirect&bpo=35208]: Squeezer now properly counts wrapped lines before newlines.

bpo-35555 [https://bugs.python.org/issue?@action=redirect&bpo=35555]: Gray out Code Context menu entry when it’s not applicable.

bpo-35521 [https://bugs.python.org/issue?@action=redirect&bpo=35521]: Document the IDLE editor code context feature. Add some internal references within the IDLE doc.

bpo-22703 [https://bugs.python.org/issue?@action=redirect&bpo=22703]: The Code Context menu label now toggles between Show/Hide Code Context. The Zoom Height menu now toggles between Zoom/Restore Height. Zoom Height has moved from the Window menu to the Options menu.

Tools/Demos

bpo-35132 [https://bugs.python.org/issue?@action=redirect&bpo=35132]: Fix py-list and py-bt commands of python-gdb.py on gdb7.

C API

bpo-33817 [https://bugs.python.org/issue?@action=redirect&bpo=33817]: Fixed _PyBytes_Resize() for empty bytes objects.

Python 3.7.2 final

Release date: 2018-12-23

Library

bpo-31715 [https://bugs.python.org/issue?@action=redirect&bpo=31715]: Associate .mjs file extension with application/javascript MIME Type.

Build

bpo-35499 [https://bugs.python.org/issue?@action=redirect&bpo=35499]: make profile-opt no longer replaces CFLAGS_NODIST with CFLAGS. It now adds profile-guided optimization (PGO) flags to CFLAGS_NODIST: existing CFLAGS_NODIST flags are kept.

bpo-35257 [https://bugs.python.org/issue?@action=redirect&bpo=35257]: Avoid leaking the linker flags from Link Time Optimizations (LTO) into distutils when compiling C extensions.

C API

bpo-35259 [https://bugs.python.org/issue?@action=redirect&bpo=35259]: Conditionally declare Py_FinalizeEx() (new in 3.6) based on Py_LIMITED_API. Patch by Arthur Neufeld.

Python 3.7.2 release candidate 1

Release date: 2018-12-11

Security

bpo-34812 [https://bugs.python.org/issue?@action=redirect&bpo=34812]: The -I command line option (run Python in isolated mode) is now also copied by the multiprocessing and distutils modules when spawning child processes. Previously, only -E and -s options (enabled by -I) were copied.

bpo-34791 [https://bugs.python.org/issue?@action=redirect&bpo=34791]: The xml.sax and xml.dom.domreg no longer use environment variables to override parser implementations when sys.flags.ignore_environment is set by -E or -I arguments.

Core and Builtins

bpo-35444 [https://bugs.python.org/issue?@action=redirect&bpo=35444]: Fixed error handling in pickling methods when fail to look up builtin “getattr”.

bpo-35436 [https://bugs.python.org/issue?@action=redirect&bpo=35436]: Fix various issues with memory allocation error handling. Patch by Zackery Spytz.

bpo-35357 [https://bugs.python.org/issue?@action=redirect&bpo=35357]: Internal attributes’ names of unittest.mock._Call and unittest.mock.MagicProxy (name, parent & from_kall) are now prefixed with _mock_ in order to prevent clashes with widely used object attributes. Fixed minor typo in test function name.

bpo-35372 [https://bugs.python.org/issue?@action=redirect&bpo=35372]: Fixed the code page decoder for input longer than 2 GiB containing undecodable bytes.

bpo-35336 [https://bugs.python.org/issue?@action=redirect&bpo=35336]: Fix PYTHONCOERCECLOCALE=1 environment variable: only coerce the C locale if the LC_CTYPE locale is “C”.

bpo-33954 [https://bugs.python.org/issue?@action=redirect&bpo=33954]: For str.format(), float.__format__() and complex.__format__() methods for non-ASCII decimal point when using the “n” formatter.

bpo-35269 [https://bugs.python.org/issue?@action=redirect&bpo=35269]: Fix a possible segfault involving a newly-created coroutine. Patch by Zackery Spytz.

bpo-35214 [https://bugs.python.org/issue?@action=redirect&bpo=35214]: Fixed an out of bounds memory access when parsing a truncated unicode escape sequence at the end of a string such as '\N'. It would read one byte beyond the end of the memory allocation.

bpo-35214 [https://bugs.python.org/issue?@action=redirect&bpo=35214]: The interpreter and extension modules have had annotations added so that they work properly under clang’s Memory Sanitizer. A new configure flag –with-memory-sanitizer has been added to make test builds of this nature easier to perform.

bpo-35193 [https://bugs.python.org/issue?@action=redirect&bpo=35193]: Fix an off by one error in the bytecode peephole optimizer where it could read bytes beyond the end of bounds of an array when removing unreachable code. This bug was present in every release of Python 3.6 and 3.7 until now.

bpo-29341 [https://bugs.python.org/issue?@action=redirect&bpo=29341]: Clarify in the docstrings of os methods that path-like objects are also accepted as input parameters.

bpo-35050 [https://bugs.python.org/issue?@action=redirect&bpo=35050]: socket: Fix off-by-one bug in length check for AF_ALG name and type.

bpo-34974 [https://bugs.python.org/issue?@action=redirect&bpo=34974]: bytes and bytearray constructors no longer convert unexpected exceptions (e.g. MemoryError and KeyboardInterrupt) to TypeError.

bpo-34973 [https://bugs.python.org/issue?@action=redirect&bpo=34973]: Fixed crash in bytes() when the list argument is mutated while it is iterated.

bpo-34824 [https://bugs.python.org/issue?@action=redirect&bpo=34824]: Fix a possible null pointer dereference in Modules/_ssl.c. Patch by Zackery Spytz.

bpo-1621 [https://bugs.python.org/issue?@action=redirect&bpo=1621]: Do not assume signed integer overflow behavior (C undefined behavior) when performing set hash table resizing.

Library

bpo-35052 [https://bugs.python.org/issue?@action=redirect&bpo=35052]: Fix xml.dom.minidom cloneNode() on a document with an entity: pass the correct arguments to the user data handler of an entity.

bpo-35330 [https://bugs.python.org/issue?@action=redirect&bpo=35330]: When a Mock instance was used to wrap an object, if side_effect is used in one of the mocks of it methods, don’t call the original implementation and return the result of using the side effect the same way that it is done with return_value.

bpo-34172 [https://bugs.python.org/issue?@action=redirect&bpo=34172]: Revert the fix for this issue previously released in 3.7.1 pending further investigation: Fix a reference issue inside multiprocessing.Pool that caused the pool to remain alive if it was deleted without being closed or terminated explicitly.

bpo-10496 [https://bugs.python.org/issue?@action=redirect&bpo=10496]: posixpath.expanduser() now returns the input path unchanged if the HOME environment variable is not set and the current user has no home directory (if the current user identifier doesn’t exist in the password database). This change fix the site module if the current user doesn’t exist in the password database (if the user has no home directory).

bpo-35310 [https://bugs.python.org/issue?@action=redirect&bpo=35310]: Fix a bug in select.select() where, in some cases, the file descriptor sequences were returned unmodified after a signal interruption, even though the file descriptors might not be ready yet. select.select() will now always return empty lists if a timeout has occurred. Patch by Oran Avraham.

bpo-35380 [https://bugs.python.org/issue?@action=redirect&bpo=35380]: Enable TCP_NODELAY on Windows for proactor asyncio event loop.

bpo-35341 [https://bugs.python.org/issue?@action=redirect&bpo=35341]: Add generic version of collections.OrderedDict to the typing module. Patch by Ismo Toijala.

bpo-35371 [https://bugs.python.org/issue?@action=redirect&bpo=35371]: Fixed possible crash in os.utime() on Windows when pass incorrect arguments.

bpo-27903 [https://bugs.python.org/issue?@action=redirect&bpo=27903]: Fix ResourceWarning in platform.dist() on SuSE and Caldera OpenLinux. Patch by Ville Skyttä.

bpo-35308 [https://bugs.python.org/issue?@action=redirect&bpo=35308]: Fix regression in webbrowser where default browsers may be preferred over browsers in the BROWSER environment variable.

bpo-28604 [https://bugs.python.org/issue?@action=redirect&bpo=28604]: locale.localeconv() now sets temporarily the LC_CTYPE locale to the LC_MONETARY locale if the two locales are different and monetary strings are non-ASCII. This temporary change affects other threads.

bpo-35277 [https://bugs.python.org/issue?@action=redirect&bpo=35277]: Update ensurepip to install pip 18.1 and setuptools 40.6.2.

bpo-35226 [https://bugs.python.org/issue?@action=redirect&bpo=35226]: Recursively check arguments when testing for equality of unittest.mock.call objects and add note that tracking of parameters used to create ancestors of mocks in mock_calls is not possible.

bpo-29564 [https://bugs.python.org/issue?@action=redirect&bpo=29564]: The warnings module now suggests to enable tracemalloc if the source is specified, the tracemalloc module is available, but tracemalloc is not tracing memory allocations.

bpo-35189 [https://bugs.python.org/issue?@action=redirect&bpo=35189]: Modify the following fnctl function to retry if interrupted by a signal (EINTR): flock, lockf, fnctl

bpo-35062 [https://bugs.python.org/issue?@action=redirect&bpo=35062]: Fix incorrect parsing of _io.IncrementalNewlineDecoder’s translate argument.

bpo-35079 [https://bugs.python.org/issue?@action=redirect&bpo=35079]: Improve difflib.SequenceManager.get_matching_blocks doc by adding ‘non-overlapping’ and changing ‘!=’ to ‘<’.

bpo-35017 [https://bugs.python.org/issue?@action=redirect&bpo=35017]: socketserver.BaseServer.serve_forever() now exits immediately if it’s shutdown() method is called while it is polling for new events.

bpo-31047 [https://bugs.python.org/issue?@action=redirect&bpo=31047]: Fix ntpath.abspath regression where it didn’t remove a trailing separator on Windows. Patch by Tim Graham.

bpo-34794 [https://bugs.python.org/issue?@action=redirect&bpo=34794]: Fixed a leak in Tkinter when pass the Python wrapper around Tcl_Obj back to Tcl/Tk.

bpo-35008 [https://bugs.python.org/issue?@action=redirect&bpo=35008]: Fixed references leaks when call the __setstate__() method of xml.etree.ElementTree.Element in the C implementation for already initialized element.

bpo-23420 [https://bugs.python.org/issue?@action=redirect&bpo=23420]: Verify the value for the parameter ‘-s’ of the cProfile CLI. Patch by Robert Kuska

bpo-33947 [https://bugs.python.org/issue?@action=redirect&bpo=33947]: dataclasses now handle recursive reprs without raising RecursionError.

bpo-16965 [https://bugs.python.org/issue?@action=redirect&bpo=16965]: The 2to3 execfile fixer now opens the file with mode 'rb'. Patch by Zackery Spytz.

bpo-34966 [https://bugs.python.org/issue?@action=redirect&bpo=34966]: pydoc now supports aliases not only to methods defined in the end class, but also to inherited methods. The docstring is not duplicated for aliases.

bpo-34941 [https://bugs.python.org/issue?@action=redirect&bpo=34941]: Methods find(), findtext() and findall() of the Element class in the xml.etree.ElementTree module are now able to find children which are instances of Element subclasses.

bpo-34936 [https://bugs.python.org/issue?@action=redirect&bpo=34936]: Fix TclError in tkinter.Spinbox.selection_element(). Patch by Juliette Monsel.

bpo-34866 [https://bugs.python.org/issue?@action=redirect&bpo=34866]: Adding max_num_fields to cgi.FieldStorage to make DOS attacks harder by limiting the number of MiniFieldStorage objects created by FieldStorage.

bpo-34022 [https://bugs.python.org/issue?@action=redirect&bpo=34022]: The SOURCE_DATE_EPOCH environment variable no longer overrides the value of the invalidation_mode argument to py_compile.compile(), and determines its default value instead.

bpo-34738 [https://bugs.python.org/issue?@action=redirect&bpo=34738]: ZIP files created by distutils will now include entries for directories.

bpo-31177 [https://bugs.python.org/issue?@action=redirect&bpo=31177]: Fix bug that prevented using reset_mock on mock instances with deleted attributes

bpo-34536 [https://bugs.python.org/issue?@action=redirect&bpo=34536]: Enum._missing_: raise ValueError if None returned and TypeError if non-member is returned.

bpo-34604 [https://bugs.python.org/issue?@action=redirect&bpo=34604]: Fix possible mojibake in the error message of pwd.getpwnam and grp.getgrnam using string representation because of invisible characters or trailing whitespaces. Patch by William Grzybowski.

bpo-34574 [https://bugs.python.org/issue?@action=redirect&bpo=34574]: OrderedDict iterators are not exhausted during pickling anymore. Patch by Sergey Fedoseev.

bpo-34052 [https://bugs.python.org/issue?@action=redirect&bpo=34052]: sqlite3.Connection.create_aggregate(), sqlite3.Connection.create_function(), sqlite3.Connection.set_authorizer(), sqlite3.Connection.set_progress_handler() methods raises TypeError when unhashable objects are passed as callable. These methods now don’t pass such objects to SQLite API. Previous behavior could lead to segfaults. Patch by Sergey Fedoseev.

bpo-29877 [https://bugs.python.org/issue?@action=redirect&bpo=29877]: compileall: import ProcessPoolExecutor only when needed, preventing hangs on low resource platforms

bpo-22005 [https://bugs.python.org/issue?@action=redirect&bpo=22005]: Implemented unpickling instances of datetime, date and time pickled by Python 2. encoding='latin1' should be used for successful decoding.

Documentation

bpo-35089 [https://bugs.python.org/issue?@action=redirect&bpo=35089]: Remove mention of typing.io and typing.re. Their types should be imported from typing directly.

bpo-35038 [https://bugs.python.org/issue?@action=redirect&bpo=35038]: Fix the documentation about an unexisting f_restricted attribute in the frame object. Patch by Stéphane Wirtel

bpo-35044 [https://bugs.python.org/issue?@action=redirect&bpo=35044]: Fix the documentation with the role exc for the appropriated exception. Patch by Stéphane Wirtel

bpo-35035 [https://bugs.python.org/issue?@action=redirect&bpo=35035]: Rename documentation for email.utils to email.utils.rst.

bpo-34967 [https://bugs.python.org/issue?@action=redirect&bpo=34967]: Use app.add_object_type() instead of the deprecated Sphinx function app.description_unit()

bpo-11233 [https://bugs.python.org/issue?@action=redirect&bpo=11233]: Create availability directive for documentation. Original patch by Georg Brandl.

bpo-33594 [https://bugs.python.org/issue?@action=redirect&bpo=33594]: Document getargspec, from_function and from_builtin as deprecated in their respective docstring, and include version since deprecation in DeprecationWarning message.

bpo-32613 [https://bugs.python.org/issue?@action=redirect&bpo=32613]: Update the faq/windows.html to use the py command from PEP 397 instead of python.

Tests

bpo-33725 [https://bugs.python.org/issue?@action=redirect&bpo=33725]: test_multiprocessing_fork may crash on recent versions of macOS. Until the issue is resolved, skip the test on macOS.

bpo-35352 [https://bugs.python.org/issue?@action=redirect&bpo=35352]: Modify test_asyncio to use the certificate set from the test directory.

bpo-35317 [https://bugs.python.org/issue?@action=redirect&bpo=35317]: Fix mktime() overflow error in test_email: run test_localtime_daylight_true_dst_true() and test_localtime_daylight_false_dst_true() with a specific timezone.

bpo-21263 [https://bugs.python.org/issue?@action=redirect&bpo=21263]: After several reports that test_gdb does not work properly on macOS and since gdb is not shipped by default anymore, test_gdb is now skipped on macOS when LLVM Clang has been used to compile Python. Patch by Lysandros Nikolaou

bpo-34279 [https://bugs.python.org/issue?@action=redirect&bpo=34279]: regrtest issue a warning when no tests have been executed in a particular test file. Also, a new final result state is issued if no test have been executed across all test files. Patch by Pablo Galindo.

Build

bpo-35296 [https://bugs.python.org/issue?@action=redirect&bpo=35296]: The Windows installer (MSI) now also install internal header files (Include/internal/ subdirectory).

bpo-35351 [https://bugs.python.org/issue?@action=redirect&bpo=35351]: When building Python with clang and LTO, LTO flags are no longer passed into CFLAGS to build third-party C extensions through distutils.

bpo-35139 [https://bugs.python.org/issue?@action=redirect&bpo=35139]: Fix a compiler error when statically linking pyexpat in Modules/Setup.

bpo-35011 [https://bugs.python.org/issue?@action=redirect&bpo=35011]: Restores the use of pyexpatns.h to isolate our embedded copy of the expat C library so that its symbols do not conflict at link or dynamic loading time with an embedding application or other extension modules with their own version of libexpat.

bpo-28015 [https://bugs.python.org/issue?@action=redirect&bpo=28015]: Have –with-lto works correctly with clang.

bpo-33015 [https://bugs.python.org/issue?@action=redirect&bpo=33015]: Fix an undefined behaviour in the pthread implementation of PyThread_start_new_thread(): add a function wrapper to always return NULL.

Windows

bpo-35401 [https://bugs.python.org/issue?@action=redirect&bpo=35401]: Updates Windows build to OpenSSL 1.1.0j

bpo-34977 [https://bugs.python.org/issue?@action=redirect&bpo=34977]: venv on Windows will now use a python.exe redirector rather than copying the actual binaries from the base environment.

bpo-34977 [https://bugs.python.org/issue?@action=redirect&bpo=34977]: Adds support for building a Windows App Store package

bpo-35067 [https://bugs.python.org/issue?@action=redirect&bpo=35067]: Remove _distutils_findvs module and use vswhere.exe instead.

bpo-34532 [https://bugs.python.org/issue?@action=redirect&bpo=34532]: Fixes exit code of list version arguments for py.exe.

bpo-32890 [https://bugs.python.org/issue?@action=redirect&bpo=32890]: Fix usage of GetLastError() instead of errno in os.execve() and os.truncate().

macOS

bpo-35402 [https://bugs.python.org/issue?@action=redirect&bpo=35402]: Update macOS installer to use Tcl/Tk 8.6.9.1. [NOTE: This change was reverted for the released python.org 3.7.2 macOS installers due to regressions found in Tk 8.6.9.1. For now, the installers provide Tcl/Tk 8.6.8.]

bpo-35401 [https://bugs.python.org/issue?@action=redirect&bpo=35401]: Update macOS installer to use OpenSSL 1.1.0j.

bpo-35025 [https://bugs.python.org/issue?@action=redirect&bpo=35025]: Properly guard the use of the CLOCK_GETTIME et al. macros in timemodule on macOS.

bpo-24658 [https://bugs.python.org/issue?@action=redirect&bpo=24658]: On macOS, fix reading from and writing into a file with a size larger than 2 GiB.

IDLE

bpo-35213 [https://bugs.python.org/issue?@action=redirect&bpo=35213]: Where appropriate, use ‘macOS’ in idlelib.

bpo-34864 [https://bugs.python.org/issue?@action=redirect&bpo=34864]: On macOS, warn if the system preference “Prefer tabs when opening documents” is set to “Always”.

bpo-34864 [https://bugs.python.org/issue?@action=redirect&bpo=34864]: Document two IDLE on MacOS issues. The System Preferences Dock “prefer tabs always” setting disables some IDLE features. Menus are a bit different than as described for Windows and Linux.

bpo-35202 [https://bugs.python.org/issue?@action=redirect&bpo=35202]: Remove unused imports from lib/idlelib

bpo-33000 [https://bugs.python.org/issue?@action=redirect&bpo=33000]: Document that IDLE’s shell has no line limit. A program that runs indefinitely can overfill memory.

bpo-23220 [https://bugs.python.org/issue?@action=redirect&bpo=23220]: Explain how IDLE’s Shell displays output.

bpo-35099 [https://bugs.python.org/issue?@action=redirect&bpo=35099]: Improve the doc about IDLE running user code. The section is renamed from “IDLE – console differences” is renamed “Running user code”. It mostly covers the implications of using custom sys.stdxxx objects.

bpo-35097 [https://bugs.python.org/issue?@action=redirect&bpo=35097]: Add IDLE doc subsection explaining editor windows. Topics include opening, title and status bar, .py* extension, and running.

bpo-35093 [https://bugs.python.org/issue?@action=redirect&bpo=35093]: Document the IDLE document viewer in the IDLE doc. Add a paragraph in “Help and preferences”, “Help sources” subsection.

bpo-35088 [https://bugs.python.org/issue?@action=redirect&bpo=35088]: Update idlelib.help.copy_string docstring. We now use git and backporting instead of hg and forward merging.

bpo-35087 [https://bugs.python.org/issue?@action=redirect&bpo=35087]: Update idlelib help files for the current doc build. The main change is the elimination of chapter-section numbers.

Tools/Demos

bpo-34989 [https://bugs.python.org/issue?@action=redirect&bpo=34989]: python-gdb.py now handles errors on computing the line number of a Python frame.

C API

bpo-35322 [https://bugs.python.org/issue?@action=redirect&bpo=35322]: Fix memory leak in PyUnicode_EncodeLocale() and PyUnicode_EncodeFSDefault() on error handling.

bpo-35296 [https://bugs.python.org/issue?@action=redirect&bpo=35296]: make install now also installs the internal API: Include/internal/*.h header files.

bpo-34725 [https://bugs.python.org/issue?@action=redirect&bpo=34725]: Adds _Py_SetProgramFullPath so embedders may override sys.executable

Python 3.7.1 final

Release date: 2018-10-20

Library

bpo-34970 [https://bugs.python.org/issue?@action=redirect&bpo=34970]: Protect tasks weak set manipulation in asyncio.all_tasks()

Python 3.7.1 release candidate 2

Release date: 2018-10-13

Core and Builtins

bpo-34879 [https://bugs.python.org/issue?@action=redirect&bpo=34879]: Fix a possible null pointer dereference in bytesobject.c. Patch by Zackery Spytz.

bpo-34854 [https://bugs.python.org/issue?@action=redirect&bpo=34854]: Fixed a crash in compiling string annotations containing a lambda with a keyword-only argument that doesn’t have a default value.

bpo-34320 [https://bugs.python.org/issue?@action=redirect&bpo=34320]: Fix dict(od) didn’t copy iteration order of OrderedDict.

Library

bpo-34769 [https://bugs.python.org/issue?@action=redirect&bpo=34769]: Fix for async generators not finalizing when event loop is in debug mode and garbage collector runs in another thread.

bpo-34922 [https://bugs.python.org/issue?@action=redirect&bpo=34922]: Fixed integer overflow in the digest() and hexdigest() methods for the SHAKE algorithm in the hashlib module.

bpo-34909 [https://bugs.python.org/issue?@action=redirect&bpo=34909]: Enum: fix grandchildren subclassing when parent mixed with concrete data types.

bpo-34900 [https://bugs.python.org/issue?@action=redirect&bpo=34900]: Fixed unittest.TestCase.debug() when used to call test methods with subtests. Patch by Bruno Oliveira.

bpo-34871 [https://bugs.python.org/issue?@action=redirect&bpo=34871]: Fix inspect module polluted sys.modules when parsing __text_signature__ of callable.

bpo-34872 [https://bugs.python.org/issue?@action=redirect&bpo=34872]: Fix self-cancellation in C implementation of asyncio.Task

bpo-34819 [https://bugs.python.org/issue?@action=redirect&bpo=34819]: Use a monotonic clock to compute timeouts in Executor.map() and as_completed(), in order to prevent timeouts from deviating when the system clock is adjusted.

bpo-34521 [https://bugs.python.org/issue?@action=redirect&bpo=34521]: Use socket.CMSG_SPACE() to calculate ancillary data size instead of socket.CMSG_LEN() in multiprocessing.reduction.recvfds() as RFC 3542 [https://tools.ietf.org/html/rfc3542.html] requires the use of the former for portable applications.

bpo-34334 [https://bugs.python.org/issue?@action=redirect&bpo=34334]: In QueueHandler, clear exc_text from LogRecord to prevent traceback from being written twice.

bpo-6721 [https://bugs.python.org/issue?@action=redirect&bpo=6721]: Acquire the logging module’s commonly used internal locks while fork()ing to avoid deadlocks in the child process.

bpo-34172 [https://bugs.python.org/issue?@action=redirect&bpo=34172]: Fix a reference issue inside multiprocessing.Pool that caused the pool to remain alive if it was deleted without being closed or terminated explicitly.

Documentation

bpo-32174 [https://bugs.python.org/issue?@action=redirect&bpo=32174]: chm document displays non-ASCII charaters properly on some MBCS Windows systems.

Tests

bpo-32962 [https://bugs.python.org/issue?@action=redirect&bpo=32962]: Fixed test_gdb when Python is compiled with flags -mcet -fcf-protection -O0.

macOS

bpo-34370 [https://bugs.python.org/issue?@action=redirect&bpo=34370]: Revert to using the released Tk 8.6.8 with macOS installers instead of the Tk 8.6.x development snapshot used with 3.7.1rc1 and 3.6.7rc1. The snapshot introduced at least one significant regression (bpo-34927 [https://bugs.python.org/issue?@action=redirect&bpo=34927]).

C API

bpo-34910 [https://bugs.python.org/issue?@action=redirect&bpo=34910]: Ensure that PyObject_Print() always returns -1 on error. Patch by Zackery Spytz.

Python 3.7.1 release candidate 1

Release date: 2018-09-26

Security

bpo-17239 [https://bugs.python.org/issue?@action=redirect&bpo=17239]: The xml.sax and xml.dom.minidom parsers no longer processes external entities by default. External DTD and ENTITY declarations no longer load files or create network connections.

bpo-34623 [https://bugs.python.org/issue?@action=redirect&bpo=34623]: CVE-2018-14647: The C accelerated _elementtree module now initializes hash randomization salt from _Py_HashSecret instead of libexpat’s default CSPRNG.

bpo-34405 [https://bugs.python.org/issue?@action=redirect&bpo=34405]: Updated to OpenSSL 1.1.0i for Windows builds.

bpo-33871 [https://bugs.python.org/issue?@action=redirect&bpo=33871]: Fixed sending the part of the file in os.sendfile() on macOS. Using the trailers argument could cause sending more bytes from the input file than was specified.

bpo-32533 [https://bugs.python.org/issue?@action=redirect&bpo=32533]: Fixed thread-safety of error handling in _ssl.

Core and Builtins

bpo-34783 [https://bugs.python.org/issue?@action=redirect&bpo=34783]: Fix a crash with musl libc (on Alpine Linux) when the script filename specified on the command line doesn’t exist.

bpo-34762 [https://bugs.python.org/issue?@action=redirect&bpo=34762]: Fix contextvars C API to use PyObject* pointer types.

bpo-34735 [https://bugs.python.org/issue?@action=redirect&bpo=34735]: Fix a memory leak in Modules/timemodule.c. Patch by Zackery Spytz.

bpo-34588 [https://bugs.python.org/issue?@action=redirect&bpo=34588]: Fix an off-by-one in the recursive call pruning feature of traceback formatting.

bpo-34485 [https://bugs.python.org/issue?@action=redirect&bpo=34485]: Standard streams like sys.stdout now use the “surrogateescape” error handler, instead of “strict”, on the POSIX locale (when the C locale is not coerced and the UTF-8 Mode is disabled).

bpo-34485 [https://bugs.python.org/issue?@action=redirect&bpo=34485]: Fix the error handler of standard streams like sys.stdout: PYTHONIOENCODING=”:” is now ignored instead of setting the error handler to “strict”.

bpo-34527 [https://bugs.python.org/issue?@action=redirect&bpo=34527]: On FreeBSD, Py_DecodeLocale() and Py_EncodeLocale() now also forces the ASCII encoding if the LC_CTYPE locale is “POSIX”, not only if the LC_CTYPE locale is “C”.

bpo-34527 [https://bugs.python.org/issue?@action=redirect&bpo=34527]: The UTF-8 Mode is now also enabled by the “POSIX” locale, not only by the “C” locale.

bpo-34400 [https://bugs.python.org/issue?@action=redirect&bpo=34400]: Fix undefined behavior in parsetok.c. Patch by Zackery Spytz.

bpo-34377 [https://bugs.python.org/issue?@action=redirect&bpo=34377]: Update valgrind suppression list to use _PyObject_Free/_PyObject_Realloc instead of PyObject_Free/PyObject_Realloc.

bpo-34170 [https://bugs.python.org/issue?@action=redirect&bpo=34170]: -X dev: it is now possible to override the memory allocator using PYTHONMALLOC even if the developer mode is enabled.

bpo-34126 [https://bugs.python.org/issue?@action=redirect&bpo=34126]: Fix crashes when profiling certain invalid calls of unbound methods. Patch by Jeroen Demeyer.

bpo-24618 [https://bugs.python.org/issue?@action=redirect&bpo=24618]: Fixed reading invalid memory when create the code object with too small varnames tuple or too large argument counts.

bpo-34068 [https://bugs.python.org/issue?@action=redirect&bpo=34068]: In io.IOBase.close(), ensure that the closed attribute is not set with a live exception. Patch by Zackery Spytz and Serhiy Storchaka.

bpo-34087 [https://bugs.python.org/issue?@action=redirect&bpo=34087]: Fix buffer overflow while converting unicode to numeric values.

bpo-34080 [https://bugs.python.org/issue?@action=redirect&bpo=34080]: Fixed a memory leak in the compiler when it raised some uncommon errors during tokenizing.

bpo-34066 [https://bugs.python.org/issue?@action=redirect&bpo=34066]: Disabled interruption by Ctrl-C between calling open() and entering a with block in with open().

bpo-34042 [https://bugs.python.org/issue?@action=redirect&bpo=34042]: Fix dict.copy() to maintain correct total refcount (as reported by sys.gettotalrefcount()).

bpo-33985 [https://bugs.python.org/issue?@action=redirect&bpo=33985]: Implement contextvars.ContextVar.name attribute.

bpo-33956 [https://bugs.python.org/issue?@action=redirect&bpo=33956]: Update vendored Expat library copy to version 2.2.5.

bpo-24596 [https://bugs.python.org/issue?@action=redirect&bpo=24596]: Decref the module object in PyRun_SimpleFileExFlags() before calling PyErr_Print(). Patch by Zackery Spytz.

bpo-33451 [https://bugs.python.org/issue?@action=redirect&bpo=33451]: Close directly executed pyc files before calling PyEval_EvalCode().

bpo-33824 [https://bugs.python.org/issue?@action=redirect&bpo=33824]: Fix “LC_ALL=C python3.7 -V”: reset properly the command line parser when the encoding changes after reading the Python configuration.

bpo-25750 [https://bugs.python.org/issue?@action=redirect&bpo=25750]: Fix rare Python crash due to bad refcounting in type_getattro() if a descriptor deletes itself from the class. Patch by Jeroen Demeyer.

bpo-31902 [https://bugs.python.org/issue?@action=redirect&bpo=31902]: Fix the col_offset attribute for ast nodes ast.AsyncFor, ast.AsyncFunctionDef, and ast.AsyncWith. Previously, col_offset pointed to the keyword after async.

bpo-25862 [https://bugs.python.org/issue?@action=redirect&bpo=25862]: Fix assertion failures in the tell() method of io.TextIOWrapper. Patch by Zackery Spytz.

bpo-31577 [https://bugs.python.org/issue?@action=redirect&bpo=31577]: Fix a crash in os.utime() in case of a bad ns argument. Patch by Oren Milman.

Library

bpo-29577 [https://bugs.python.org/issue?@action=redirect&bpo=29577]: Support multiple mixin classes when creating Enums.

bpo-34670 [https://bugs.python.org/issue?@action=redirect&bpo=34670]: Add SSLContext.post_handshake_auth and SSLSocket.verify_client_post_handshake for TLS 1.3’s post handshake authentication feature.

bpo-34658 [https://bugs.python.org/issue?@action=redirect&bpo=34658]: Fix a rare interpreter unhandled exception state SystemError only seen when using subprocess with a preexec_fn while an after_parent handler has been registered with os.register_at_fork and the fork system call fails.

bpo-34652 [https://bugs.python.org/issue?@action=redirect&bpo=34652]: Ensure os.lchmod() is never defined on Linux.

bpo-34363 [https://bugs.python.org/issue?@action=redirect&bpo=34363]: dataclasses.asdict() and .astuple() now handle namedtuples correctly.

bpo-34625 [https://bugs.python.org/issue?@action=redirect&bpo=34625]: Update vendorized expat library version to 2.2.6.

bpo-34621 [https://bugs.python.org/issue?@action=redirect&bpo=34621]: Fix un/pickling compatbility of uuid.UUID objects with older versions of Python (<3.7).

bpo-32270 [https://bugs.python.org/issue?@action=redirect&bpo=32270]: The subprocess module no longer mistakenly closes redirected fds even when they were in pass_fds when outside of the default {0, 1, 2} set.

bpo-34610 [https://bugs.python.org/issue?@action=redirect&bpo=34610]: Fixed iterator of multiprocessing.managers.DictProxy.

bpo-34421 [https://bugs.python.org/issue?@action=redirect&bpo=34421]: Fix distutils logging for non-ASCII strings. This caused installation issues on Windows.

bpo-34604 [https://bugs.python.org/issue?@action=redirect&bpo=34604]: Fix possible mojibake in the error message of pwd.getpwnam and grp.getgrnam. Patch by William Grzybowski.

bpo-34530 [https://bugs.python.org/issue?@action=redirect&bpo=34530]: distutils.spawn.find_executable() now falls back on os.defpath if the PATH environment variable is not set.

bpo-34282 [https://bugs.python.org/issue?@action=redirect&bpo=34282]: Fix enum members getting shadowed by parent attributes.

bpo-34563 [https://bugs.python.org/issue?@action=redirect&bpo=34563]: On Windows, fix multiprocessing.Connection for very large read: fix _winapi.PeekNamedPipe() and _winapi.ReadFile() for read larger than INT_MAX (usually 2^31-1).

bpo-34558 [https://bugs.python.org/issue?@action=redirect&bpo=34558]: Correct typo in Lib/ctypes/_aix.py

bpo-34515 [https://bugs.python.org/issue?@action=redirect&bpo=34515]: Fix parsing non-ASCII identifiers in lib2to3.pgen2.tokenize (PEP 3131).

bpo-13312 [https://bugs.python.org/issue?@action=redirect&bpo=13312]: Avoids a possible integer underflow (undefined behavior) in the time module’s year handling code when passed a very low negative year value.

bpo-34472 [https://bugs.python.org/issue?@action=redirect&bpo=34472]: Improved compatibility for streamed files in zipfile. Previously an optional signature was not being written and certain ZIP applications were not supported. Patch by Silas Sewell.

bpo-34454 [https://bugs.python.org/issue?@action=redirect&bpo=34454]: Fix the .fromisoformat() methods of datetime types crashing when given unicode with non-UTF-8-encodable code points. Specifically, datetime.fromisoformat() now accepts surrogate unicode code points used as the separator. Report and tests by Alexey Izbyshev, patch by Paul Ganssle.

bpo-6700 [https://bugs.python.org/issue?@action=redirect&bpo=6700]: Fix inspect.getsourcelines for module level frames/tracebacks. Patch by Vladimir Matveev.

bpo-34171 [https://bugs.python.org/issue?@action=redirect&bpo=34171]: Running the trace module no longer creates the trace.cover file.

bpo-34441 [https://bugs.python.org/issue?@action=redirect&bpo=34441]: Fix crash when an ABC-derived class with invalid __subclasses__ is passed as the second argument to issubclass(). Patch by Alexey Izbyshev.

bpo-34341 [https://bugs.python.org/issue?@action=redirect&bpo=34341]: Appending to the ZIP archive with the ZIP64 extension no longer grows the size of extra fields of existing entries.

bpo-34333 [https://bugs.python.org/issue?@action=redirect&bpo=34333]: Fix %-formatting in pathlib.PurePath.with_suffix() when formatting an error message.

bpo-18540 [https://bugs.python.org/issue?@action=redirect&bpo=18540]: The imaplib.IMAP4 and imaplib.IMAP4_SSL classes now resolve to the local host IP correctly when the default value of host parameter ('') is used.

bpo-34246 [https://bugs.python.org/issue?@action=redirect&bpo=34246]: smtplib.SMTP.send_message() no longer modifies the content of the mail_options argument. Patch by Pablo S. Blum de Aguiar.

bpo-31047 [https://bugs.python.org/issue?@action=redirect&bpo=31047]: Fix ntpath.abspath for invalid paths on windows. Patch by Franz Woellert.

bpo-34263 [https://bugs.python.org/issue?@action=redirect&bpo=34263]: asyncio’s event loop will not pass timeouts longer than one day to epoll/select etc.

bpo-34035 [https://bugs.python.org/issue?@action=redirect&bpo=34035]: Fix several AttributeError in zipfile seek() methods. Patch by Mickaël Schoentgen.

bpo-32215 [https://bugs.python.org/issue?@action=redirect&bpo=32215]: Fix performance regression in sqlite3 when a DML statement appeared in a different line than the rest of the SQL query.

bpo-34251 [https://bugs.python.org/issue?@action=redirect&bpo=34251]: Restore msilib.Win64 to preserve backwards compatibility since it’s already used by distutils’ bdist_msi command.

bpo-19891 [https://bugs.python.org/issue?@action=redirect&bpo=19891]: Ignore errors caused by missing / non-writable homedir while writing history during exit of an interactive session. Patch by Anthony Sottile.

bpo-34213 [https://bugs.python.org/issue?@action=redirect&bpo=34213]: Allow frozen dataclasses to have a field named “object”. Previously this conflicted with an internal use of “object”.

bpo-21446 [https://bugs.python.org/issue?@action=redirect&bpo=21446]: The reload fixer now uses importlib.reload() instead of deprecated imp.reload().

bpo-940286 [https://bugs.python.org/issue?@action=redirect&bpo=940286]: pydoc’s Helper.showtopic() method now prints the cross references of a topic correctly.

bpo-34164 [https://bugs.python.org/issue?@action=redirect&bpo=34164]: base64.b32decode() could raise UnboundLocalError or OverflowError for incorrect padding. Now it always raises base64.Error in these cases.

bpo-33729 [https://bugs.python.org/issue?@action=redirect&bpo=33729]: Fixed issues with arguments parsing in hashlib.

bpo-34108 [https://bugs.python.org/issue?@action=redirect&bpo=34108]: Remove extraneous CR in 2to3 refactor.

bpo-27494 [https://bugs.python.org/issue?@action=redirect&bpo=27494]: Reverted bpo-27494 [https://bugs.python.org/issue?@action=redirect&bpo=27494]. 2to3 rejects now a trailing comma in generator expressions.

bpo-33967 [https://bugs.python.org/issue?@action=redirect&bpo=33967]: functools.singledispatch now raises TypeError instead of IndexError when no positional arguments are passed.

bpo-34056 [https://bugs.python.org/issue?@action=redirect&bpo=34056]: Ensure the loader shim created by imp.load_module always returns bytes from its get_data() function. This fixes using imp.load_module with PEP 552 [https://www.python.org/dev/peps/pep-0552] hash-based pycs.

bpo-34054 [https://bugs.python.org/issue?@action=redirect&bpo=34054]: The multiprocessing module now uses the monotonic clock time.monotonic() instead of the system clock time.time() to implement timeout.

bpo-34044 [https://bugs.python.org/issue?@action=redirect&bpo=34044]: subprocess.Popen now copies the startupinfo argument to leave it unchanged: it will modify the copy, so that the same STARTUPINFO object can be used multiple times.

bpo-34010 [https://bugs.python.org/issue?@action=redirect&bpo=34010]: Fixed a performance regression for reading streams with tarfile. The buffered read should use a list, instead of appending to a bytes object.

bpo-34019 [https://bugs.python.org/issue?@action=redirect&bpo=34019]: webbrowser: Correct the arguments passed to Opera Browser when opening a new URL using the webbrowser module. Patch by Bumsik Kim.

bpo-33978 [https://bugs.python.org/issue?@action=redirect&bpo=33978]: Closed existing logging handlers before reconfiguration via fileConfig and dictConfig. Patch by Karthikeyan Singaravelan.

bpo-14117 [https://bugs.python.org/issue?@action=redirect&bpo=14117]: Make minor tweaks to turtledemo. The ‘wikipedia’ example is now ‘rosette’, decribing what it draws. The ‘penrose’ print output is reduced. The’1024’ output of ‘tree’ is eliminated.

bpo-33974 [https://bugs.python.org/issue?@action=redirect&bpo=33974]: Fixed passing lists and tuples of strings containing special characters ", \, {, } and \n as options to ttk widgets.

bpo-27500 [https://bugs.python.org/issue?@action=redirect&bpo=27500]: Fix getaddrinfo to resolve IPv6 addresses correctly.

bpo-24567 [https://bugs.python.org/issue?@action=redirect&bpo=24567]: Improve random.choices() to handle subnormal input weights that could occasionally trigger an IndexError.

bpo-33871 [https://bugs.python.org/issue?@action=redirect&bpo=33871]: Fixed integer overflow in os.readv(), os.writev(), os.preadv() and os.pwritev() and in os.sendfile() with headers or trailers arguments (on BSD-based OSes and macOS).

bpo-33899 [https://bugs.python.org/issue?@action=redirect&bpo=33899]: Tokenize module now implicitly emits a NEWLINE when provided with input that does not have a trailing new line. This behavior now matches what the C tokenizer does internally. Contributed by Ammar Askar.

bpo-33916 [https://bugs.python.org/issue?@action=redirect&bpo=33916]: bz2 and lzma: When Decompressor.__init__() is called twice, free the old lock to not leak memory.

bpo-32568 [https://bugs.python.org/issue?@action=redirect&bpo=32568]: Make select.epoll() and its documentation consistent regarding sizehint and flags.

bpo-33833 [https://bugs.python.org/issue?@action=redirect&bpo=33833]: Fixed bug in asyncio where ProactorSocketTransport logs AssertionError if force closed during write.

bpo-33663 [https://bugs.python.org/issue?@action=redirect&bpo=33663]: Convert content length to string before putting to header.

bpo-26544 [https://bugs.python.org/issue?@action=redirect&bpo=26544]: Fixed implementation of platform.libc_ver(). It almost always returned version ‘2.9’ for glibc.

bpo-33805 [https://bugs.python.org/issue?@action=redirect&bpo=33805]: Improve error message of dataclasses.replace() when an InitVar is not specified

bpo-27397 [https://bugs.python.org/issue?@action=redirect&bpo=27397]: Make email module properly handle invalid-length base64 strings.

bpo-33476 [https://bugs.python.org/issue?@action=redirect&bpo=33476]: Fix _header_value_parser.py when address group is missing final ‘;’. Contributed by Enrique Perez-Terron

bpo-31014 [https://bugs.python.org/issue?@action=redirect&bpo=31014]: Fixed creating a controller for webbrowser when a user specifies a path to an entry in the BROWSER environment variable. Based on patch by John Still.

bpo-33365 [https://bugs.python.org/issue?@action=redirect&bpo=33365]: Print the header values besides the header keys instead just the header keys if debuglevel is set to >0 in http.client. Patch by Marco Strigl.

bpo-32933 [https://bugs.python.org/issue?@action=redirect&bpo=32933]: unittest.mock.mock_open() now supports iteration over the file contents. Patch by Tony Flury.

bpo-33336 [https://bugs.python.org/issue?@action=redirect&bpo=33336]: imaplib now allows MOVE command in IMAP4.uid() (RFC 6851: IMAP MOVE Extension) and potentially as a name of supported method of IMAP4 object.

bpo-31608 [https://bugs.python.org/issue?@action=redirect&bpo=31608]: Raise a TypeError instead of crashing if a collections.deque subclass returns a non-deque from __new__. Patch by Oren Milman.

bpo-29456 [https://bugs.python.org/issue?@action=redirect&bpo=29456]: Fix bugs in hangul normalization: u1176, u11a7 and u11c3

Documentation

bpo-34790 [https://bugs.python.org/issue?@action=redirect&bpo=34790]: Document how passing coroutines to asyncio.wait() can be confusing.

bpo-28617 [https://bugs.python.org/issue?@action=redirect&bpo=28617]: Fixed info in the stdtypes docs concerning the types that support membership tests.

bpo-34065 [https://bugs.python.org/issue?@action=redirect&bpo=34065]: Fix wrongly written basicConfig documentation markup syntax

bpo-33460 [https://bugs.python.org/issue?@action=redirect&bpo=33460]: replaced ellipsis with correct error codes in tutorial chapter 3.

bpo-33847 [https://bugs.python.org/issue?@action=redirect&bpo=33847]: Add ‘@’ operator entry to index.

bpo-25041 [https://bugs.python.org/issue?@action=redirect&bpo=25041]: Document AF_PACKET in the socket module.

Tests

bpo-34537 [https://bugs.python.org/issue?@action=redirect&bpo=34537]: Fix test_gdb.test_strings() when LC_ALL=C and GDB was compiled with Python 3.6 or earlier.

bpo-34587 [https://bugs.python.org/issue?@action=redirect&bpo=34587]: test_socket: Remove RDSTest.testCongestion(). The test tries to fill the receiver’s socket buffer and expects an error. But the RDS protocol doesn’t require that. Moreover, the Linux implementation of RDS expects that the producer of the messages reduces its rate, it’s not the role of the receiver to trigger an error. The test fails on Fedora 28 by design, so just remove it.

bpo-34661 [https://bugs.python.org/issue?@action=redirect&bpo=34661]: Fix test_shutil if unzip doesn’t support -t.

bpo-34200 [https://bugs.python.org/issue?@action=redirect&bpo=34200]: Fixed non-deterministic flakiness of test_pkg by not using the scary test.support.module_cleanup() logic to save and restore sys.modules contents between test cases.

bpo-34594 [https://bugs.python.org/issue?@action=redirect&bpo=34594]: Fix usage of hardcoded errno values in the tests.

bpo-34542 [https://bugs.python.org/issue?@action=redirect&bpo=34542]: Use 3072 RSA keys and SHA-256 signature for test certs and keys.

bpo-11193 [https://bugs.python.org/issue?@action=redirect&bpo=11193]: Remove special condition for AIX in test_subprocess.test_undecodable_env

bpo-34490 [https://bugs.python.org/issue?@action=redirect&bpo=34490]: On AIX with AF_UNIX family sockets getsockname() does not provide ‘sockname’, so skip calls to transport.get_extra_info(‘sockname’)

bpo-34391 [https://bugs.python.org/issue?@action=redirect&bpo=34391]: Fix ftplib test for TLS 1.3 by reading from data socket.

bpo-34399 [https://bugs.python.org/issue?@action=redirect&bpo=34399]: Update all RSA keys and DH params to use at least 2048 bits.

bpo-33746 [https://bugs.python.org/issue?@action=redirect&bpo=33746]: Fix test_unittest when run in verbose mode.

bpo-33901 [https://bugs.python.org/issue?@action=redirect&bpo=33901]: Fix test_dbm_gnu on macOS with gdbm 1.15: add a larger value to make sure that the file size changes.

bpo-33873 [https://bugs.python.org/issue?@action=redirect&bpo=33873]: Fix a bug in regrtest that caused an extra test to run if –huntrleaks/-R was used. Exit with error in case that invalid parameters are specified to –huntrleaks/-R (at least one warmup run and one repetition must be used).

bpo-32663 [https://bugs.python.org/issue?@action=redirect&bpo=32663]: Making sure the SMTPUTF8SimTests class of tests gets run in test_smtplib.py.

Build

bpo-34710 [https://bugs.python.org/issue?@action=redirect&bpo=34710]: Fixed SSL module build with OpenSSL & pedantic CFLAGS.

bpo-34582 [https://bugs.python.org/issue?@action=redirect&bpo=34582]: Add JUnit XML output for regression tests and update Azure DevOps builds.

bpo-34555 [https://bugs.python.org/issue?@action=redirect&bpo=34555]: Fix for case where it was not possible to have both HAVE_LINUX_VM_SOCKETS_H and HAVE_SOCKADDR_ALG be undefined.

bpo-34121 [https://bugs.python.org/issue?@action=redirect&bpo=34121]: Fix detection of C11 atomic support on clang.

bpo-30345 [https://bugs.python.org/issue?@action=redirect&bpo=30345]: Add -g to LDFLAGS when compiling with LTO to get debug symbols.

bpo-33648 [https://bugs.python.org/issue?@action=redirect&bpo=33648]: The –with-c-locale-warning configuration flag has been removed. It has had no effect for about a year.

Windows

bpo-34770 [https://bugs.python.org/issue?@action=redirect&bpo=34770]: Fix a possible null pointer dereference in pyshellext.cpp.

bpo-34603 [https://bugs.python.org/issue?@action=redirect&bpo=34603]: Fix returning structs from functions produced by MSVC

bpo-34581 [https://bugs.python.org/issue?@action=redirect&bpo=34581]: Guard MSVC-specific code in socketmodule.c with #ifdef _MSC_VER.

bpo-34062 [https://bugs.python.org/issue?@action=redirect&bpo=34062]: Fixed the ‘–list’ and ‘–list-paths’ arguments for the py.exe launcher

bpo-34225 [https://bugs.python.org/issue?@action=redirect&bpo=34225]: Ensure INCLUDE and LIB directories do not end with a backslash.

bpo-34006 [https://bugs.python.org/issue?@action=redirect&bpo=34006]: Revert line length limit for Windows help docs. The line-length limit is not needed because the pages appear in a separate app rather than on a browser tab. It can also interact badly with the DPI setting.

bpo-31546 [https://bugs.python.org/issue?@action=redirect&bpo=31546]: Restore running PyOS_InputHook while waiting for user input at the prompt. The restores integration of interactive GUI windows (such as Matplotlib figures) with the prompt on Windows.

bpo-30237 [https://bugs.python.org/issue?@action=redirect&bpo=30237]: Output error when ReadConsole is canceled by CancelSynchronousIo instead of crashing.

bpo-29097 [https://bugs.python.org/issue?@action=redirect&bpo=29097]: Fix bug where datetime.fromtimestamp() erronously throws an OSError on Windows for values between 0 and 86400. Patch by Ammar Askar.

macOS

bpo-34370 [https://bugs.python.org/issue?@action=redirect&bpo=34370]: Have macOS 10.9+ installer builds for 3.7.1rc and 3.6.7rc use a development snapshot of Tk 8.6 (post-8.6.8) to mitigate certain scroller issues seen with IDLE and tkinter apps.

bpo-34405 [https://bugs.python.org/issue?@action=redirect&bpo=34405]: Update to OpenSSL 1.1.0i for macOS installer builds.

bpo-33635 [https://bugs.python.org/issue?@action=redirect&bpo=33635]: In macOS stat on some file descriptors (/dev/fd/3 f.e) will result in bad file descriptor OSError. Guard against this exception was added in is_dir, is_file and similar methods. DirEntry.is_dir can also throw this exception so _RecursiveWildcardSelector._iterate_directories was also extended with the same error ignoring pattern.

bpo-31903 [https://bugs.python.org/issue?@action=redirect&bpo=31903]: In _scproxy, drop the GIL when calling into SystemConfiguration to avoid deadlocks.

IDLE

bpo-34548 [https://bugs.python.org/issue?@action=redirect&bpo=34548]: Use configured color theme for read-only text views.

bpo-1529353 [https://bugs.python.org/issue?@action=redirect&bpo=1529353]: Enable “squeezing” of long outputs in the shell, to avoid performance degradation and to clean up the history without losing it. Squeezed outputs may be copied, viewed in a separate window, and “unsqueezed”.

bpo-34047 [https://bugs.python.org/issue?@action=redirect&bpo=34047]: Fixed mousewheel scrolling direction on macOS.

bpo-34275 [https://bugs.python.org/issue?@action=redirect&bpo=34275]: Make IDLE calltips always visible on Mac. Some MacOS-tk combinations need .update_idletasks(). Patch by Kevin Walzer.

bpo-34120 [https://bugs.python.org/issue?@action=redirect&bpo=34120]: Fix unresponsiveness after closing certain windows and dialogs.

bpo-33975 [https://bugs.python.org/issue?@action=redirect&bpo=33975]: Avoid small type when running htests. Since part of the purpose of human-viewed tests is to determine that widgets look right, it is important that they look the same for testing as when running IDLE.

bpo-33905 [https://bugs.python.org/issue?@action=redirect&bpo=33905]: Add test for idlelib.stackview.StackBrowser.

bpo-33924 [https://bugs.python.org/issue?@action=redirect&bpo=33924]: Change mainmenu.menudefs key ‘windows’ to ‘window’. Every other menudef key is lowercase version of main menu entry.

bpo-33906 [https://bugs.python.org/issue?@action=redirect&bpo=33906]: Rename idlelib.windows as window Match Window on the main menu and remove last plural module name.

bpo-33917 [https://bugs.python.org/issue?@action=redirect&bpo=33917]: Fix and document idlelib/idle_test/template.py. The revised file compiles, runs, and tests OK. idle_test/README.txt explains how to use it to create new IDLE test files.

bpo-33904 [https://bugs.python.org/issue?@action=redirect&bpo=33904]: IDLE: In rstrip, rename class RstripExtension as Rstrip

bpo-33907 [https://bugs.python.org/issue?@action=redirect&bpo=33907]: For consistency and clarity, rename an IDLE module and classes. Module calltips and its class CallTips are now calltip and Calltip. In module calltip_w, class CallTip is now CalltipWindow.

bpo-33856 [https://bugs.python.org/issue?@action=redirect&bpo=33856]: Add “help” in the welcome message of IDLE

bpo-33839 [https://bugs.python.org/issue?@action=redirect&bpo=33839]: IDLE: refactor ToolTip and CallTip and add documentation and tests

bpo-33855 [https://bugs.python.org/issue?@action=redirect&bpo=33855]: Minimally test all IDLE modules. Add missing files, import module, instantiate classes, and check coverage. Check existing files.

Tools/Demos

bpo-32962 [https://bugs.python.org/issue?@action=redirect&bpo=32962]: python-gdb now catches UnicodeDecodeError exceptions when calling string().

bpo-32962 [https://bugs.python.org/issue?@action=redirect&bpo=32962]: python-gdb now catches ValueError on read_var(): when Python has no debug symbols for example.

C API

bpo-34247 [https://bugs.python.org/issue?@action=redirect&bpo=34247]: Fix Py_Initialize() regression introduced in 3.7.0: read environment variables like PYTHONOPTIMIZE.

bpo-23927 [https://bugs.python.org/issue?@action=redirect&bpo=23927]: Fixed SystemError in PyArg_ParseTupleAndKeywords() when the w* format unit is used for optional parameter.

bpo-34008 [https://bugs.python.org/issue?@action=redirect&bpo=34008]: Py_Main() can again be called after Py_Initialize(), as in Python 3.6.

Python 3.7.0 final

Release date: 2018-06-27

Library

bpo-33851 [https://bugs.python.org/issue?@action=redirect&bpo=33851]: Fix ast.get_docstring() for a node that lacks a docstring.

C API

bpo-33932 [https://bugs.python.org/issue?@action=redirect&bpo=33932]: Calling Py_Initialize() twice does nothing, instead of failing with a fatal error: restore the Python 3.6 behaviour.

Python 3.7.0 release candidate 1

Release date: 2018-06-12

Core and Builtins

bpo-33803 [https://bugs.python.org/issue?@action=redirect&bpo=33803]: Fix a crash in hamt.c caused by enabling GC tracking for an object that hadn’t all of its fields set to NULL.

bpo-33706 [https://bugs.python.org/issue?@action=redirect&bpo=33706]: Fix a crash in Python initialization when parsing the command line options. Thanks Christoph Gohlke for the bug report and the fix!

bpo-30654 [https://bugs.python.org/issue?@action=redirect&bpo=30654]: Fixed reset of the SIGINT handler to SIG_DFL on interpreter shutdown even when there was a custom handler set previously. Patch by Philipp Kerling.

bpo-31849 [https://bugs.python.org/issue?@action=redirect&bpo=31849]: Fix signed/unsigned comparison warning in pyhash.c.

Library

bpo-30167 [https://bugs.python.org/issue?@action=redirect&bpo=30167]: Prevent site.main() exception if PYTHONSTARTUP is set. Patch by Steve Weber.

bpo-33812 [https://bugs.python.org/issue?@action=redirect&bpo=33812]: Datetime instance d with non-None tzinfo, but with d.tzinfo.utcoffset(d) returning None is now treated as naive by the astimezone() method.

bpo-30805 [https://bugs.python.org/issue?@action=redirect&bpo=30805]: Avoid race condition with debug logging

bpo-33694 [https://bugs.python.org/issue?@action=redirect&bpo=33694]: asyncio: Fix a race condition causing data loss on pause_reading()/resume_reading() when using the ProactorEventLoop.

bpo-32493 [https://bugs.python.org/issue?@action=redirect&bpo=32493]: Correct test for uuid_enc_be availability in configure.ac. Patch by Michael Felt.

bpo-33792 [https://bugs.python.org/issue?@action=redirect&bpo=33792]: Add asyncio.WindowsSelectorEventLoopPolicy and asyncio.WindowsProactorEventLoopPolicy.

bpo-33778 [https://bugs.python.org/issue?@action=redirect&bpo=33778]: Update unicodedata’s database to Unicode version 11.0.0.

bpo-33770 [https://bugs.python.org/issue?@action=redirect&bpo=33770]: improve base64 exception message for encoded inputs of invalid length

bpo-33769 [https://bugs.python.org/issue?@action=redirect&bpo=33769]: asyncio/start_tls: Fix error message; cancel callbacks in case of an unhandled error; mark SSLTransport as closed if it is aborted.

bpo-33767 [https://bugs.python.org/issue?@action=redirect&bpo=33767]: The concatenation (+) and repetition (*) sequence operations now raise TypeError instead of SystemError when performed on mmap.mmap objects. Patch by Zackery Spytz.

bpo-33734 [https://bugs.python.org/issue?@action=redirect&bpo=33734]: asyncio/ssl: Fix AttributeError, increase default handshake timeout

bpo-11874 [https://bugs.python.org/issue?@action=redirect&bpo=11874]: Use a better regex when breaking usage into wrappable parts. Avoids bogus assertion errors from custom metavar strings.

bpo-33582 [https://bugs.python.org/issue?@action=redirect&bpo=33582]: Emit a deprecation warning for inspect.formatargspec

Documentation

bpo-33409 [https://bugs.python.org/issue?@action=redirect&bpo=33409]: Clarified the relationship between PEP 538’s PYTHONCOERCECLOCALE and PEP 540’s PYTHONUTF8 mode.

bpo-33736 [https://bugs.python.org/issue?@action=redirect&bpo=33736]: Improve the documentation of asyncio.open_connection(), asyncio.start_server() and their UNIX socket counterparts.

bpo-31432 [https://bugs.python.org/issue?@action=redirect&bpo=31432]: Clarify meaning of CERT_NONE, CERT_OPTIONAL, and CERT_REQUIRED flags for ssl.SSLContext.verify_mode.

Build

bpo-5755 [https://bugs.python.org/issue?@action=redirect&bpo=5755]: Move -Wstrict-prototypes option to CFLAGS_NODIST from OPT. This option emitted annoying warnings when building extension modules written in C++.

Windows

bpo-33720 [https://bugs.python.org/issue?@action=redirect&bpo=33720]: Reduces maximum marshal recursion depth on release builds.

IDLE

bpo-33656 [https://bugs.python.org/issue?@action=redirect&bpo=33656]: On Windows, add API call saying that tk scales for DPI. On Windows 8.1+ or 10, with DPI compatibility properties of the Python binary unchanged, and a monitor resolution greater than 96 DPI, this should make text and lines sharper. It should otherwise have no effect.

bpo-33768 [https://bugs.python.org/issue?@action=redirect&bpo=33768]: Clicking on a context line moves that line to the top of the editor window.

bpo-33763 [https://bugs.python.org/issue?@action=redirect&bpo=33763]: IDLE: Use read-only text widget for code context instead of label widget.

bpo-33664 [https://bugs.python.org/issue?@action=redirect&bpo=33664]: Scroll IDLE editor text by lines. Previously, the mouse wheel and scrollbar slider moved text by a fixed number of pixels, resulting in partial lines at the top of the editor box. The change also applies to the shell and grep output windows, but not to read-only text views.

bpo-33679 [https://bugs.python.org/issue?@action=redirect&bpo=33679]: Enable theme-specific color configuration for Code Context. Use the Highlights tab to see the setting for built-in themes or add settings to custom themes.

bpo-33642 [https://bugs.python.org/issue?@action=redirect&bpo=33642]: Display up to maxlines non-blank lines for Code Context. If there is no current context, show a single blank line.

Python 3.7.0 beta 5

Release date: 2018-05-30

Core and Builtins

bpo-33622 [https://bugs.python.org/issue?@action=redirect&bpo=33622]: Fixed a leak when the garbage collector fails to add an object with the __del__ method or referenced by it into the gc.garbage list. PyGC_Collect() can now be called when an exception is set and preserves it.

bpo-33509 [https://bugs.python.org/issue?@action=redirect&bpo=33509]: Fix module_globals parameter of warnings.warn_explicit(): don’t crash if module_globals is not a dict.

bpo-20104 [https://bugs.python.org/issue?@action=redirect&bpo=20104]: The new os.posix_spawn added in 3.7.0b1 was removed as we are still working on what the API should look like. Expect this in 3.8 instead.

bpo-33475 [https://bugs.python.org/issue?@action=redirect&bpo=33475]: Fixed miscellaneous bugs in converting annotations to strings and optimized parentheses in the string representation.

bpo-33391 [https://bugs.python.org/issue?@action=redirect&bpo=33391]: Fix a leak in set_symmetric_difference().

bpo-28055 [https://bugs.python.org/issue?@action=redirect&bpo=28055]: Fix unaligned accesses in siphash24(). Patch by Rolf Eike Beer.

bpo-32911 [https://bugs.python.org/issue?@action=redirect&bpo=32911]: Due to unexpected compatibility issues discovered during downstream beta testing, reverted bpo-29463 [https://bugs.python.org/issue?@action=redirect&bpo=29463]. docstring field is removed from Module, ClassDef, FunctionDef, and AsyncFunctionDef ast nodes which was added in 3.7a1. Docstring expression is restored as a first statement in their body. Based on patch by Inada Naoki.

bpo-21983 [https://bugs.python.org/issue?@action=redirect&bpo=21983]: Fix a crash in ctypes.cast() in case the type argument is a ctypes structured data type. Patch by Eryk Sun and Oren Milman.

Library

bpo-32751 [https://bugs.python.org/issue?@action=redirect&bpo=32751]: When cancelling the task due to a timeout, asyncio.wait_for() will now wait until the cancellation is complete.

bpo-32684 [https://bugs.python.org/issue?@action=redirect&bpo=32684]: Fix gather to propagate cancellation of itself even with return_exceptions.

bpo-33654 [https://bugs.python.org/issue?@action=redirect&bpo=33654]: Support protocol type switching in SSLTransport.set_protocol().

bpo-33674 [https://bugs.python.org/issue?@action=redirect&bpo=33674]: Pause the transport as early as possible to further reduce the risk of data_received() being called before connection_made().

bpo-33674 [https://bugs.python.org/issue?@action=redirect&bpo=33674]: Fix a race condition in SSLProtocol.connection_made() of asyncio.sslproto: start immediately the handshake instead of using call_soon(). Previously, data_received() could be called before the handshake started, causing the handshake to hang or fail.

bpo-31647 [https://bugs.python.org/issue?@action=redirect&bpo=31647]: Fixed bug where calling write_eof() on a _SelectorSocketTransport after it’s already closed raises AttributeError.

bpo-32610 [https://bugs.python.org/issue?@action=redirect&bpo=32610]: Make asyncio.all_tasks() return only pending tasks.

bpo-32410 [https://bugs.python.org/issue?@action=redirect&bpo=32410]: Avoid blocking on file IO in sendfile fallback code

bpo-33469 [https://bugs.python.org/issue?@action=redirect&bpo=33469]: Fix RuntimeError after closing loop that used run_in_executor

bpo-33672 [https://bugs.python.org/issue?@action=redirect&bpo=33672]: Fix Task.__repr__ crash with Cython’s bogus coroutines

bpo-33654 [https://bugs.python.org/issue?@action=redirect&bpo=33654]: Fix transport.set_protocol() to support switching between asyncio.Protocol and asyncio.BufferedProtocol. Fix loop.start_tls() to work with asyncio.BufferedProtocols.

bpo-33652 [https://bugs.python.org/issue?@action=redirect&bpo=33652]: Pickles of type variables and subscripted generics are now future-proof and compatible with older Python versions.

bpo-32493 [https://bugs.python.org/issue?@action=redirect&bpo=32493]: Fixed uuid.uuid1() on FreeBSD.

bpo-33618 [https://bugs.python.org/issue?@action=redirect&bpo=33618]: Finalize and document preliminary and experimental TLS 1.3 support with OpenSSL 1.1.1

bpo-33623 [https://bugs.python.org/issue?@action=redirect&bpo=33623]: Fix possible SIGSGV when asyncio.Future is created in __del__

bpo-30877 [https://bugs.python.org/issue?@action=redirect&bpo=30877]: Fixed a bug in the Python implementation of the JSON decoder that prevented the cache of parsed strings from clearing after finishing the decoding. Based on patch by c-fos.

bpo-33570 [https://bugs.python.org/issue?@action=redirect&bpo=33570]: Change TLS 1.3 cipher suite settings for compatibility with OpenSSL 1.1.1-pre6 and newer. OpenSSL 1.1.1 will have TLS 1.3 ciphers enabled by default.

bpo-28556 [https://bugs.python.org/issue?@action=redirect&bpo=28556]: Do not simplify arguments to typing.Union. Now Union[Manager, Employee] is not simplified to Employee at runtime. Such simplification previously caused several bugs and limited possibilities for introspection.

bpo-33540 [https://bugs.python.org/issue?@action=redirect&bpo=33540]: Add a new block_on_close class attribute to ForkingMixIn and ThreadingMixIn classes of socketserver.

bpo-33548 [https://bugs.python.org/issue?@action=redirect&bpo=33548]: tempfile._candidate_tempdir_list should consider common TEMP locations

bpo-33109 [https://bugs.python.org/issue?@action=redirect&bpo=33109]: argparse subparsers are once again not required by default, reverting the change in behavior introduced by bpo-26510 [https://bugs.python.org/issue?@action=redirect&bpo=26510] in 3.7.0a2.

bpo-33536 [https://bugs.python.org/issue?@action=redirect&bpo=33536]: dataclasses.make_dataclass now checks for invalid field names and duplicate fields. Also, added a check for invalid field specifications.

bpo-33542 [https://bugs.python.org/issue?@action=redirect&bpo=33542]: Prevent uuid.get_node from using a DUID instead of a MAC on Windows. Patch by Zvi Effron

bpo-26819 [https://bugs.python.org/issue?@action=redirect&bpo=26819]: Fix race condition with ReadTransport.resume_reading in Windows proactor event loop.

Fix failure in typing.get_type_hints() when ClassVar was provided as a string forward reference.

bpo-33505 [https://bugs.python.org/issue?@action=redirect&bpo=33505]: Optimize asyncio.ensure_future() by reordering if checks: 1.17x faster.

bpo-33497 [https://bugs.python.org/issue?@action=redirect&bpo=33497]: Add errors param to cgi.parse_multipart and make an encoding in FieldStorage use the given errors (needed for Twisted). Patch by Amber Brown.

bpo-33495 [https://bugs.python.org/issue?@action=redirect&bpo=33495]: Change dataclasses.Fields repr to use the repr of each of its members, instead of str. This makes it more clear what each field actually represents. This is especially true for the ‘type’ member.

bpo-33453 [https://bugs.python.org/issue?@action=redirect&bpo=33453]: Fix dataclasses to work if using literal string type annotations or if using PEP 563 “Postponed Evaluation of Annotations”. Only specific string prefixes are detected for both ClassVar (“ClassVar” and “typing.ClassVar”) and InitVar (“InitVar” and “dataclasses.InitVar”).

bpo-28556 [https://bugs.python.org/issue?@action=redirect&bpo=28556]: Minor fixes in typing module: add annotations to NamedTuple.__new__, pass *args and **kwds in Generic.__new__. Original PRs by Paulius Šarka and Chad Dombrova.

bpo-20087 [https://bugs.python.org/issue?@action=redirect&bpo=20087]: Updated alias mapping with glibc 2.27 supported locales.

bpo-33422 [https://bugs.python.org/issue?@action=redirect&bpo=33422]: Fix trailing quotation marks getting deleted when looking up byte/string literals on pydoc. Patch by Andrés Delfino.

bpo-28167 [https://bugs.python.org/issue?@action=redirect&bpo=28167]: The function platform.linux_distribution and platform.dist now trigger a DeprecationWarning and have been marked for removal in Python 3.8

bpo-33197 [https://bugs.python.org/issue?@action=redirect&bpo=33197]: Update error message when constructing invalid inspect.Parameters Patch by Dong-hee Na.

bpo-33263 [https://bugs.python.org/issue?@action=redirect&bpo=33263]: Fix FD leak in _SelectorSocketTransport Patch by Vlad Starostin.

bpo-32861 [https://bugs.python.org/issue?@action=redirect&bpo=32861]: The urllib.robotparser’s __str__ representation now includes wildcard entries and the “Crawl-delay” and “Request-rate” fields. Patch by Michael Lazar.

bpo-32257 [https://bugs.python.org/issue?@action=redirect&bpo=32257]: The ssl module now contains OP_NO_RENEGOTIATION constant, available with OpenSSL 1.1.0h or 1.1.1.

bpo-16865 [https://bugs.python.org/issue?@action=redirect&bpo=16865]: Support arrays >=2GiB in ctypes. Patch by Segev Finer.

Documentation

bpo-23859 [https://bugs.python.org/issue?@action=redirect&bpo=23859]: Document that asyncio.wait() does not cancel its futures on timeout.

bpo-32436 [https://bugs.python.org/issue?@action=redirect&bpo=32436]: Document PEP 567 changes to asyncio.

bpo-33604 [https://bugs.python.org/issue?@action=redirect&bpo=33604]: Update HMAC md5 default to a DeprecationWarning, bump removal to 3.8.

bpo-33503 [https://bugs.python.org/issue?@action=redirect&bpo=33503]: Fix broken pypi link

bpo-33421 [https://bugs.python.org/issue?@action=redirect&bpo=33421]: Add missing documentation for typing.AsyncContextManager.

Tests

bpo-33655 [https://bugs.python.org/issue?@action=redirect&bpo=33655]: Ignore test_posix_fallocate failures on BSD platforms that might be due to running on ZFS.

bpo-32604 [https://bugs.python.org/issue?@action=redirect&bpo=32604]: Remove the _xxsubinterpreters module (meant for testing) and associated helpers. This module was originally added recently in 3.7b1.

Build

bpo-33614 [https://bugs.python.org/issue?@action=redirect&bpo=33614]: Ensures module definition files for the stable ABI on Windows are correctly regenerated.

bpo-33522 [https://bugs.python.org/issue?@action=redirect&bpo=33522]: Enable CI builds on Visual Studio Team Services at https://python.visualstudio.com/cpython

bpo-33012 [https://bugs.python.org/issue?@action=redirect&bpo=33012]: Add -Wno-cast-function-type for gcc 8 for silencing warnings about function casts like casting to PyCFunction in method definition lists.

macOS

bpo-13631 [https://bugs.python.org/issue?@action=redirect&bpo=13631]: The .editrc file in user’s home directory is now processed correctly during the readline initialization through editline emulation on macOS.

IDLE

bpo-33628 [https://bugs.python.org/issue?@action=redirect&bpo=33628]: IDLE: Cleanup codecontext.py and its test.

bpo-33564 [https://bugs.python.org/issue?@action=redirect&bpo=33564]: IDLE’s code context now recognizes async as a block opener.

bpo-32831 [https://bugs.python.org/issue?@action=redirect&bpo=32831]: Add docstrings and tests for codecontext.

Python 3.7.0 beta 4

Release date: 2018-05-02

Core and Builtins

bpo-33363 [https://bugs.python.org/issue?@action=redirect&bpo=33363]: Raise a SyntaxError for async with and async for statements outside of async functions.

bpo-33128 [https://bugs.python.org/issue?@action=redirect&bpo=33128]: Fix a bug that causes PathFinder to appear twice on sys.meta_path. Patch by Pablo Galindo Salgado.

bpo-33312 [https://bugs.python.org/issue?@action=redirect&bpo=33312]: Fixed clang ubsan (undefined behavior sanitizer) warnings in dictobject.c by adjusting how the internal struct _dictkeysobject shared keys structure is declared.

bpo-33231 [https://bugs.python.org/issue?@action=redirect&bpo=33231]: Fix potential memory leak in normalizestring().

bpo-33205 [https://bugs.python.org/issue?@action=redirect&bpo=33205]: Change dict growth function from round_up_to_power_2(used*2+hashtable_size/2) to round_up_to_power_2(used*3). Previously, dict is shrinked only when used == 0. Now dict has more chance to be shrinked.

bpo-29922 [https://bugs.python.org/issue?@action=redirect&bpo=29922]: Improved error messages in ‘async with’ when __aenter__() or __aexit__() return non-awaitable object.

bpo-33199 [https://bugs.python.org/issue?@action=redirect&bpo=33199]: Fix ma_version_tag in dict implementation is uninitialized when copying from key-sharing dict.

Library

bpo-33281 [https://bugs.python.org/issue?@action=redirect&bpo=33281]: Fix ctypes.util.find_library regression on macOS.

bpo-33383 [https://bugs.python.org/issue?@action=redirect&bpo=33383]: Fixed crash in the get() method of the dbm.ndbm database object when it is called with a single argument.

bpo-33329 [https://bugs.python.org/issue?@action=redirect&bpo=33329]: Fix multiprocessing regression on newer glibcs

bpo-991266 [https://bugs.python.org/issue?@action=redirect&bpo=991266]: Fix quoting of the Comment attribute of http.cookies.SimpleCookie.

bpo-33131 [https://bugs.python.org/issue?@action=redirect&bpo=33131]: Upgrade bundled version of pip to 10.0.1.

bpo-33308 [https://bugs.python.org/issue?@action=redirect&bpo=33308]: Fixed a crash in the parser module when converting an ST object to a tree of tuples or lists with line_info=False and col_info=True.

bpo-33266 [https://bugs.python.org/issue?@action=redirect&bpo=33266]: lib2to3 now recognizes rf'...' strings.

bpo-11594 [https://bugs.python.org/issue?@action=redirect&bpo=11594]: Ensure line-endings are respected when using lib2to3.

bpo-33254 [https://bugs.python.org/issue?@action=redirect&bpo=33254]: Have importlib.resources.contents() and importlib.abc.ResourceReader.contents() return an iterable instead of an iterator.

bpo-33256 [https://bugs.python.org/issue?@action=redirect&bpo=33256]: Fix display of <module> call in the html produced by cgitb.html(). Patch by Stéphane Blondon.

bpo-33185 [https://bugs.python.org/issue?@action=redirect&bpo=33185]: Fixed regression when running pydoc with the -m switch. (The regression was introduced in 3.7.0b3 by the resolution of bpo-33053 [https://bugs.python.org/issue?@action=redirect&bpo=33053])

This fix also changed pydoc to add os.getcwd() to sys.path when necessary, rather than adding ".".

bpo-33169 [https://bugs.python.org/issue?@action=redirect&bpo=33169]: Delete entries of None in sys.path_importer_cache when importlib.machinery.invalidate_caches() is called.

bpo-33217 [https://bugs.python.org/issue?@action=redirect&bpo=33217]: Deprecate looking up non-Enum objects in Enum classes and Enum members (will raise TypeError in 3.8+).

bpo-33203 [https://bugs.python.org/issue?@action=redirect&bpo=33203]: random.Random.choice() now raises IndexError for empty sequences consistently even when called from subclasses without a getrandbits() implementation.

bpo-33224 [https://bugs.python.org/issue?@action=redirect&bpo=33224]: Update difflib.mdiff() for PEP 479. Convert an uncaught StopIteration in a generator into a return-statement.

bpo-33209 [https://bugs.python.org/issue?@action=redirect&bpo=33209]: End framing at the end of C implementation of pickle.Pickler.dump().

bpo-20104 [https://bugs.python.org/issue?@action=redirect&bpo=20104]: Improved error handling and fixed a reference leak in os.posix_spawn().

bpo-33175 [https://bugs.python.org/issue?@action=redirect&bpo=33175]: In dataclasses, Field.__set_name__ now looks up the __set_name__ special method on the class, not the instance, of the default value.

bpo-33097 [https://bugs.python.org/issue?@action=redirect&bpo=33097]: Raise RuntimeError when executor.submit is called during interpreter shutdown.

bpo-31908 [https://bugs.python.org/issue?@action=redirect&bpo=31908]: Fix output of cover files for trace module command-line tool. Previously emitted cover files only when --missing option was used. Patch by Michael Selik.

Documentation

bpo-33378 [https://bugs.python.org/issue?@action=redirect&bpo=33378]: Add Korean language switcher for https://docs.python.org/3/

bpo-33276 [https://bugs.python.org/issue?@action=redirect&bpo=33276]: Clarify that the __path__ attribute on modules cannot be just any value.

bpo-33201 [https://bugs.python.org/issue?@action=redirect&bpo=33201]: Modernize documentation for writing C extension types.

bpo-33195 [https://bugs.python.org/issue?@action=redirect&bpo=33195]: Deprecate Py_UNICODE usage in c-api/arg document. Py_UNICODE related APIs are deprecated since Python 3.3, but it is missed in the document.

bpo-8243 [https://bugs.python.org/issue?@action=redirect&bpo=8243]: Add a note about curses.addch and curses.addstr exception behavior when writing outside a window, or pad.

bpo-32337 [https://bugs.python.org/issue?@action=redirect&bpo=32337]: Update documentation related with dict order.

Tests

bpo-33358 [https://bugs.python.org/issue?@action=redirect&bpo=33358]: Fix test_embed.test_pre_initialization_sys_options() when the interpreter is built with --enable-shared.

Build

bpo-33394 [https://bugs.python.org/issue?@action=redirect&bpo=33394]: Enable the verbose build for extension modules, when GNU make is passed macros on the command line.

bpo-33393 [https://bugs.python.org/issue?@action=redirect&bpo=33393]: Update config.guess and config.sub files.

bpo-33377 [https://bugs.python.org/issue?@action=redirect&bpo=33377]: Add new triplets for mips r6 and riscv variants (used in extension suffixes).

bpo-32232 [https://bugs.python.org/issue?@action=redirect&bpo=32232]: By default, modules configured in Modules/Setup are no longer built with -DPy_BUILD_CORE. Instead, modules that specifically need that preprocessor definition include it in their individual entries.

bpo-33182 [https://bugs.python.org/issue?@action=redirect&bpo=33182]: The embedding tests can once again be built with clang 6.0

Windows

bpo-33184 [https://bugs.python.org/issue?@action=redirect&bpo=33184]: Update Windows installer to use OpenSSL 1.1.0h.

macOS

bpo-33184 [https://bugs.python.org/issue?@action=redirect&bpo=33184]: Update macOS installer build to use OpenSSL 1.1.0h.

IDLE

bpo-21474 [https://bugs.python.org/issue?@action=redirect&bpo=21474]: Update word/identifier definition from ascii to unicode. In text and entry boxes, this affects selection by double-click, movement left/right by control-left/right, and deletion left/right by control-BACKSPACE/DEL.

bpo-33204 [https://bugs.python.org/issue?@action=redirect&bpo=33204]: IDLE: consistently color invalid string prefixes. A ‘u’ string prefix cannot be paired with either ‘r’ or ‘f’. Consistently color as much of the prefix, starting at the right, as is valid. Revise and extend colorizer test.

Tools/Demos

bpo-33189 [https://bugs.python.org/issue?@action=redirect&bpo=33189]: pygettext.py now recognizes only literal strings as docstrings and translatable strings, and rejects bytes literals and f-string expressions.

bpo-31920 [https://bugs.python.org/issue?@action=redirect&bpo=31920]: Fixed handling directories as arguments in the pygettext script. Based on patch by Oleg Krasnikov.

bpo-29673 [https://bugs.python.org/issue?@action=redirect&bpo=29673]: Fix pystackv and pystack gdbinit macros.

bpo-31583 [https://bugs.python.org/issue?@action=redirect&bpo=31583]: Fix 2to3 for using with –add-suffix option but without –output-dir option for relative path to files in current directory.

Python 3.7.0 beta 3

Release date: 2018-03-29

Security

bpo-33136 [https://bugs.python.org/issue?@action=redirect&bpo=33136]: Harden ssl module against LibreSSL CVE-2018-8970. X509_VERIFY_PARAM_set1_host() is called with an explicit namelen. A new test ensures that NULL bytes are not allowed.

bpo-33001 [https://bugs.python.org/issue?@action=redirect&bpo=33001]: Minimal fix to prevent buffer overrun in os.symlink on Windows

bpo-32981 [https://bugs.python.org/issue?@action=redirect&bpo=32981]: Regexes in difflib and poplib were vulnerable to catastrophic backtracking. These regexes formed potential DOS vectors (REDOS). They have been refactored. This resolves CVE-2018-1060 and CVE-2018-1061. Patch by Jamie Davis.

Core and Builtins

bpo-33053 [https://bugs.python.org/issue?@action=redirect&bpo=33053]: When using the -m switch, sys.path[0] is now explicitly expanded as the starting working directory, rather than being left as the empty path (which allows imports from the current working directory at the time of the import)

bpo-33018 [https://bugs.python.org/issue?@action=redirect&bpo=33018]: Improve consistency of errors raised by issubclass() when called with a non-class and an abstract base class as the first and second arguments, respectively. Patch by Josh Bronson.

bpo-33041 [https://bugs.python.org/issue?@action=redirect&bpo=33041]: Fixed jumping when the function contains an async for loop.

bpo-33026 [https://bugs.python.org/issue?@action=redirect&bpo=33026]: Fixed jumping out of “with” block by setting f_lineno.

bpo-33005 [https://bugs.python.org/issue?@action=redirect&bpo=33005]: Fix a crash on fork when using a custom memory allocator (ex: using PYTHONMALLOC env var). _PyGILState_Reinit() and _PyInterpreterState_Enable() now use the default RAW memory allocator to allocate a new interpreters mutex on fork.

bpo-17288 [https://bugs.python.org/issue?@action=redirect&bpo=17288]: Prevent jumps from ‘return’ and ‘exception’ trace events.

bpo-32836 [https://bugs.python.org/issue?@action=redirect&bpo=32836]: Don’t use temporary variables in cases of list/dict/set comprehensions

Library

bpo-33141 [https://bugs.python.org/issue?@action=redirect&bpo=33141]: Have Field objects pass through __set_name__ to their default values, if they have their own __set_name__.

bpo-33096 [https://bugs.python.org/issue?@action=redirect&bpo=33096]: Allow ttk.Treeview.insert to insert iid that has a false boolean value. Note iid=0 and iid=False would be same. Patch by Garvit Khatri.

bpo-32873 [https://bugs.python.org/issue?@action=redirect&bpo=32873]: Treat type variables and special typing forms as immutable by copy and pickle. This fixes several minor issues and inconsistencies, and improves backwards compatibility with Python 3.6.

bpo-33134 [https://bugs.python.org/issue?@action=redirect&bpo=33134]: When computing dataclass’s __hash__, use the lookup table to contain the function which returns the __hash__ value. This is an improvement over looking up a string, and then testing that string to see what to do.

bpo-33127 [https://bugs.python.org/issue?@action=redirect&bpo=33127]: The ssl module now compiles with LibreSSL 2.7.1.

bpo-32505 [https://bugs.python.org/issue?@action=redirect&bpo=32505]: Raise TypeError if a member variable of a dataclass is of type Field, but doesn’t have a type annotation.

bpo-33078 [https://bugs.python.org/issue?@action=redirect&bpo=33078]: Fix the failure on OSX caused by the tests relying on sem_getvalue

bpo-33116 [https://bugs.python.org/issue?@action=redirect&bpo=33116]: Add ‘Field’ to dataclasses.__all__.

bpo-32896 [https://bugs.python.org/issue?@action=redirect&bpo=32896]: Fix an error where subclassing a dataclass with a field that uses a default_factory would generate an incorrect class.

bpo-33100 [https://bugs.python.org/issue?@action=redirect&bpo=33100]: Dataclasses: If a field has a default value that’s a MemberDescriptorType, then it’s from that field being in __slots__, not an actual default value.

bpo-32953 [https://bugs.python.org/issue?@action=redirect&bpo=32953]: If a non-dataclass inherits from a frozen dataclass, allow attributes to be added to the derived class. Only attributes from the frozen dataclass cannot be assigned to. Require all dataclasses in a hierarchy to be either all frozen or all non-frozen.

bpo-33061 [https://bugs.python.org/issue?@action=redirect&bpo=33061]: Add missing NoReturn to __all__ in typing.py

bpo-33078 [https://bugs.python.org/issue?@action=redirect&bpo=33078]: Fix the size handling in multiprocessing.Queue when a pickling error occurs.

bpo-33064 [https://bugs.python.org/issue?@action=redirect&bpo=33064]: lib2to3 now properly supports trailing commas after *args and **kwargs in function signatures.

bpo-33056 [https://bugs.python.org/issue?@action=redirect&bpo=33056]: FIX properly close leaking fds in concurrent.futures.ProcessPoolExecutor.

bpo-33021 [https://bugs.python.org/issue?@action=redirect&bpo=33021]: Release the GIL during fstat() calls, avoiding hang of all threads when calling mmap.mmap(), os.urandom(), and random.seed(). Patch by Nir Soffer.

bpo-31804 [https://bugs.python.org/issue?@action=redirect&bpo=31804]: Avoid failing in multiprocessing.Process if the standard streams are closed or None at exit.

bpo-33037 [https://bugs.python.org/issue?@action=redirect&bpo=33037]: Skip sending/receiving data after SSL transport closing.

bpo-27683 [https://bugs.python.org/issue?@action=redirect&bpo=27683]: Fix a regression in ipaddress that result of hosts() is empty when the network is constructed by a tuple containing an integer mask and only 1 bit left for addresses.

bpo-32999 [https://bugs.python.org/issue?@action=redirect&bpo=32999]: Fix C implementation of ABC.__subclasscheck__(cls, subclass) crashed when subclass is not a type object.

bpo-33009 [https://bugs.python.org/issue?@action=redirect&bpo=33009]: Fix inspect.signature() for single-parameter partialmethods.

bpo-32969 [https://bugs.python.org/issue?@action=redirect&bpo=32969]: Expose several missing constants in zlib and fix corresponding documentation.

bpo-32056 [https://bugs.python.org/issue?@action=redirect&bpo=32056]: Improved exceptions raised for invalid number of channels and sample width when read an audio file in modules aifc, wave and sunau.

bpo-32844 [https://bugs.python.org/issue?@action=redirect&bpo=32844]: Fix wrong redirection of a low descriptor (0 or 1) to stderr in subprocess if another low descriptor is closed.

bpo-32857 [https://bugs.python.org/issue?@action=redirect&bpo=32857]: In tkinter, after_cancel(None) now raises a ValueError instead of canceling the first scheduled function. Patch by Cheryl Sabella.

bpo-31639 [https://bugs.python.org/issue?@action=redirect&bpo=31639]: http.server now exposes a ThreadedHTTPServer class and uses it when the module is run with -m to cope with web browsers pre-opening sockets.

bpo-27645 [https://bugs.python.org/issue?@action=redirect&bpo=27645]: sqlite3.Connection now exposes a backup method, if the underlying SQLite library is at version 3.6.11 or higher. Patch by Lele Gaifax.

Documentation

bpo-33126 [https://bugs.python.org/issue?@action=redirect&bpo=33126]: Document PyBuffer_ToContiguous().

bpo-27212 [https://bugs.python.org/issue?@action=redirect&bpo=27212]: Modify documentation for the islice() recipe to consume initial values up to the start index.

bpo-28247 [https://bugs.python.org/issue?@action=redirect&bpo=28247]: Update zipapp documentation to describe how to make standalone applications.

bpo-18802 [https://bugs.python.org/issue?@action=redirect&bpo=18802]: Documentation changes for ipaddress. Patch by Jon Foster and Berker Peksag.

bpo-27428 [https://bugs.python.org/issue?@action=redirect&bpo=27428]: Update documentation to clarify that WindowsRegistryFinder implements MetaPathFinder. (Patch by Himanshu Lakhara)

Tests

bpo-32872 [https://bugs.python.org/issue?@action=redirect&bpo=32872]: Avoid regrtest compatibility issue with namespace packages.

bpo-32517 [https://bugs.python.org/issue?@action=redirect&bpo=32517]: Fix failing test_asyncio on macOS 10.12.2+ due to transport of KqueueSelector loop was not being closed.

bpo-19417 [https://bugs.python.org/issue?@action=redirect&bpo=19417]: Add test_bdb.py.

Build

bpo-33163 [https://bugs.python.org/issue?@action=redirect&bpo=33163]: Upgrade pip to 9.0.3 and setuptools to v39.0.1.

Windows

bpo-33016 [https://bugs.python.org/issue?@action=redirect&bpo=33016]: Fix potential use of uninitialized memory in nt._getfinalpathname

bpo-32903 [https://bugs.python.org/issue?@action=redirect&bpo=32903]: Fix a memory leak in os.chdir() on Windows if the current directory is set to a UNC path.

macOS

bpo-32726 [https://bugs.python.org/issue?@action=redirect&bpo=32726]: Build and link with private copy of Tcl/Tk 8.6 for the macOS 10.6+ installer. The 10.9+ installer variant already does this. This means that the Python 3.7 provided by the python.org macOS installers no longer need or use any external versions of Tcl/Tk, either system-provided or user-installed, such as ActiveTcl.

IDLE

bpo-32984 [https://bugs.python.org/issue?@action=redirect&bpo=32984]: Set __file__ while running a startup file. Like Python, IDLE optionally runs one startup file in the Shell window before presenting the first interactive input prompt. For IDLE, -s runs a file named in environmental variable IDLESTARTUP or PYTHONSTARTUP; -r file runs file. Python sets __file__ to the startup file name before running the file and unsets it before the first prompt. IDLE now does the same when run normally, without the -n option.

bpo-32940 [https://bugs.python.org/issue?@action=redirect&bpo=32940]: Simplify and rename StringTranslatePseudoMapping in pyparse.

Tools/Demos

bpo-32885 [https://bugs.python.org/issue?@action=redirect&bpo=32885]: Add an -n flag for Tools/scripts/pathfix.py to disable automatic backup creation (files with ~ suffix).

C API

bpo-33042 [https://bugs.python.org/issue?@action=redirect&bpo=33042]: Embedding applications may once again call PySys_ResetWarnOptions, PySys_AddWarnOption, and PySys_AddXOption prior to calling Py_Initialize.

bpo-32374 [https://bugs.python.org/issue?@action=redirect&bpo=32374]: Document that m_traverse for multi-phase initialized modules can be called with m_state=NULL, and add a sanity check

Python 3.7.0 beta 2

Release date: 2018-02-27

Security

bpo-28414 [https://bugs.python.org/issue?@action=redirect&bpo=28414]: The ssl module now allows users to perform their own IDN en/decoding when using SNI.

Core and Builtins

bpo-32889 [https://bugs.python.org/issue?@action=redirect&bpo=32889]: Update Valgrind suppression list to account for the rename of Py_ADDRESS_IN_RANG to address_in_range.

bpo-31356 [https://bugs.python.org/issue?@action=redirect&bpo=31356]: Remove the new API added in bpo-31356 [https://bugs.python.org/issue?@action=redirect&bpo=31356] (gc.ensure_disabled() context manager).

bpo-32305 [https://bugs.python.org/issue?@action=redirect&bpo=32305]: For namespace packages, ensure that both __file__ and __spec__.origin are set to None.

bpo-32303 [https://bugs.python.org/issue?@action=redirect&bpo=32303]: Make sure __spec__.loader matches __loader__ for namespace packages.

bpo-32711 [https://bugs.python.org/issue?@action=redirect&bpo=32711]: Fix the warning messages for Python/ast_unparse.c. Patch by Stéphane Wirtel

bpo-32583 [https://bugs.python.org/issue?@action=redirect&bpo=32583]: Fix possible crashing in builtin Unicode decoders caused by write out-of-bound errors when using customized decode error handlers.

Library

bpo-32960 [https://bugs.python.org/issue?@action=redirect&bpo=32960]: For dataclasses, disallow inheriting frozen from non-frozen classes, and also disallow inheriting non-frozen from frozen classes. This restriction will be relaxed at a future date.

bpo-32713 [https://bugs.python.org/issue?@action=redirect&bpo=32713]: Fixed tarfile.itn handling of out-of-bounds float values. Patch by Joffrey Fuhrer.

bpo-32951 [https://bugs.python.org/issue?@action=redirect&bpo=32951]: Direct instantiation of SSLSocket and SSLObject objects is now prohibited. The constructors were never documented, tested, or designed as public constructors. Users were suppose to use ssl.wrap_socket() or SSLContext.

bpo-32929 [https://bugs.python.org/issue?@action=redirect&bpo=32929]: Remove the tri-state parameter “hash”, and add the boolean “unsafe_hash”. If unsafe_hash is True, add a __hash__ function, but if a __hash__ exists, raise TypeError. If unsafe_hash is False, add a __hash__ based on the values of eq= and frozen=. The unsafe_hash=False behavior is the same as the old hash=None behavior. unsafe_hash=False is the default, just as hash=None used to be.

bpo-32947 [https://bugs.python.org/issue?@action=redirect&bpo=32947]: Add OP_ENABLE_MIDDLEBOX_COMPAT and test workaround for TLSv1.3 for future compatibility with OpenSSL 1.1.1.

bpo-30622 [https://bugs.python.org/issue?@action=redirect&bpo=30622]: The ssl module now detects missing NPN support in LibreSSL.

bpo-32922 [https://bugs.python.org/issue?@action=redirect&bpo=32922]: dbm.open() now encodes filename with the filesystem encoding rather than default encoding.

bpo-32859 [https://bugs.python.org/issue?@action=redirect&bpo=32859]: In os.dup2, don’t check every call whether the dup3 syscall exists or not.

bpo-32556 [https://bugs.python.org/issue?@action=redirect&bpo=32556]: nt._getfinalpathname, nt._getvolumepathname and nt._getdiskusage now correctly convert from bytes.

bpo-25988 [https://bugs.python.org/issue?@action=redirect&bpo=25988]: Emit a DeprecationWarning when using or importing an ABC directly from collections rather than from collections.abc.

bpo-21060 [https://bugs.python.org/issue?@action=redirect&bpo=21060]: Rewrite confusing message from setup.py upload from “No dist file created in earlier command” to the more helpful “Must create and upload files in one command”.

bpo-32852 [https://bugs.python.org/issue?@action=redirect&bpo=32852]: Make sure sys.argv remains as a list when running trace.

bpo-31333 [https://bugs.python.org/issue?@action=redirect&bpo=31333]: _abc module is added. It is a speedup module with C implementations for various functions and methods in abc. Creating an ABC subclass and calling isinstance or issubclass with an ABC subclass are up to 1.5x faster. In addition, this makes Python start-up up to 10% faster.

Note that the new implementation hides internal registry and caches, previously accessible via private attributes _abc_registry, _abc_cache, and _abc_negative_cache. There are three debugging helper methods that can be used instead _dump_registry, _abc_registry_clear, and _abc_caches_clear.

bpo-32841 [https://bugs.python.org/issue?@action=redirect&bpo=32841]: Fixed asyncio.Condition issue which silently ignored cancellation after notifying and cancelling a conditional lock. Patch by Bar Harel.

bpo-32819 [https://bugs.python.org/issue?@action=redirect&bpo=32819]: ssl.match_hostname() has been simplified and no longer depends on re and ipaddress module for wildcard and IP addresses. Error reporting for invalid wildcards has been improved.

bpo-32394 [https://bugs.python.org/issue?@action=redirect&bpo=32394]: socket: Remove TCP_FASTOPEN,TCP_KEEPCNT,TCP_KEEPIDLE,TCP_KEEPINTVL flags on older version Windows during run-time.

bpo-31787 [https://bugs.python.org/issue?@action=redirect&bpo=31787]: Fixed refleaks of __init__() methods in various modules. (Contributed by Oren Milman)

bpo-30157 [https://bugs.python.org/issue?@action=redirect&bpo=30157]: Fixed guessing quote and delimiter in csv.Sniffer.sniff() when only the last field is quoted. Patch by Jake Davis.

bpo-32792 [https://bugs.python.org/issue?@action=redirect&bpo=32792]: collections.ChainMap() preserves the order of the underlying mappings.

bpo-32775 [https://bugs.python.org/issue?@action=redirect&bpo=32775]: fnmatch.translate() no longer produces patterns which contain set operations. Sets starting with ‘[’ or containing ‘–’, ‘&&’, ‘~~’ or ‘||’ will be interpreted differently in regular expressions in future versions. Currently they emit warnings. fnmatch.translate() now avoids producing patterns containing such sets by accident.

bpo-32622 [https://bugs.python.org/issue?@action=redirect&bpo=32622]: Implement native fast sendfile for Windows proactor event loop.

bpo-32777 [https://bugs.python.org/issue?@action=redirect&bpo=32777]: Fix a rare but potential pre-exec child process deadlock in subprocess on POSIX systems when marking file descriptors inheritable on exec in the child process. This bug appears to have been introduced in 3.4.

bpo-32647 [https://bugs.python.org/issue?@action=redirect&bpo=32647]: The ctypes module used to depend on indirect linking for dlopen. The shared extension is now explicitly linked against libdl on platforms with dl.

bpo-32741 [https://bugs.python.org/issue?@action=redirect&bpo=32741]: Implement asyncio.TimerHandle.when() method.

bpo-32691 [https://bugs.python.org/issue?@action=redirect&bpo=32691]: Use mod_spec.parent when running modules with pdb

bpo-32734 [https://bugs.python.org/issue?@action=redirect&bpo=32734]: Fixed asyncio.Lock() safety issue which allowed acquiring and locking the same lock multiple times, without it being free. Patch by Bar Harel.

bpo-32727 [https://bugs.python.org/issue?@action=redirect&bpo=32727]: Do not include name field in SMTP envelope from address. Patch by Stéphane Wirtel

bpo-31453 [https://bugs.python.org/issue?@action=redirect&bpo=31453]: Add TLSVersion constants and SSLContext.maximum_version / minimum_version attributes. The new API wraps OpenSSL 1.1 https://www.openssl.org/docs/man1.1.0/ssl/SSL_CTX_set_min_proto_version.html feature.

bpo-24334 [https://bugs.python.org/issue?@action=redirect&bpo=24334]: Internal implementation details of ssl module were cleaned up. The SSLSocket has one less layer of indirection. Owner and session information are now handled by the SSLSocket and SSLObject constructor. Channel binding implementation has been simplified.

bpo-31848 [https://bugs.python.org/issue?@action=redirect&bpo=31848]: Fix the error handling in Aifc_read.initfp() when the SSND chunk is not found. Patch by Zackery Spytz.

bpo-32585 [https://bugs.python.org/issue?@action=redirect&bpo=32585]: Add Ttk spinbox widget to tkinter.ttk. Patch by Alan D Moore.

bpo-32221 [https://bugs.python.org/issue?@action=redirect&bpo=32221]: Various functions returning tuple containing IPv6 addresses now omit %scope part since the same information is already encoded in scopeid tuple item. Especially this speeds up socket.recvfrom() when it receives multicast packet since useless resolving of network interface name is omitted.

bpo-30693 [https://bugs.python.org/issue?@action=redirect&bpo=30693]: The TarFile class now recurses directories in a reproducible way.

bpo-30693 [https://bugs.python.org/issue?@action=redirect&bpo=30693]: The ZipFile class now recurses directories in a reproducible way.

Documentation

bpo-28124 [https://bugs.python.org/issue?@action=redirect&bpo=28124]: The ssl module function ssl.wrap_socket() has been de-emphasized and deprecated in favor of the more secure and efficient SSLContext.wrap_socket() method.

bpo-17232 [https://bugs.python.org/issue?@action=redirect&bpo=17232]: Clarify docs for -O and -OO. Patch by Terry Reedy.

bpo-32436 [https://bugs.python.org/issue?@action=redirect&bpo=32436]: Add documentation for the contextvars module (PEP 567).

bpo-32800 [https://bugs.python.org/issue?@action=redirect&bpo=32800]: Update link to w3c doc for xml default namespaces.

bpo-11015 [https://bugs.python.org/issue?@action=redirect&bpo=11015]: Update test.support documentation.

bpo-8722 [https://bugs.python.org/issue?@action=redirect&bpo=8722]: Document __getattr__() behavior when property get() method raises AttributeError.

bpo-32614 [https://bugs.python.org/issue?@action=redirect&bpo=32614]: Modify RE examples in documentation to use raw strings to prevent DeprecationWarning and add text to REGEX HOWTO to highlight the deprecation.

bpo-31972 [https://bugs.python.org/issue?@action=redirect&bpo=31972]: Improve docstrings for pathlib.PurePath subclasses.

Tests

bpo-31809 [https://bugs.python.org/issue?@action=redirect&bpo=31809]: Add tests to verify connection with secp ECDH curves.

Build

bpo-32898 [https://bugs.python.org/issue?@action=redirect&bpo=32898]: Fix the python debug build when using COUNT_ALLOCS.

Windows

bpo-32901 [https://bugs.python.org/issue?@action=redirect&bpo=32901]: Update Tcl and Tk versions to 8.6.8

bpo-31966 [https://bugs.python.org/issue?@action=redirect&bpo=31966]: Fixed WindowsConsoleIO.write() for writing empty data.

bpo-32409 [https://bugs.python.org/issue?@action=redirect&bpo=32409]: Ensures activate.bat can handle Unicode contents.

bpo-32457 [https://bugs.python.org/issue?@action=redirect&bpo=32457]: Improves handling of denormalized executable path when launching Python.

bpo-32370 [https://bugs.python.org/issue?@action=redirect&bpo=32370]: Use the correct encoding for ipconfig output in the uuid module. Patch by Segev Finer.

bpo-29248 [https://bugs.python.org/issue?@action=redirect&bpo=29248]: Fix os.readlink() on Windows, which was mistakenly treating the PrintNameOffset field of the reparse data buffer as a number of characters instead of bytes. Patch by Craig Holmquist and SSE4.

macOS

bpo-32901 [https://bugs.python.org/issue?@action=redirect&bpo=32901]: Update macOS 10.9+ installer to Tcl/Tk 8.6.8.

IDLE

bpo-32916 [https://bugs.python.org/issue?@action=redirect&bpo=32916]: Change str to code in pyparse.

bpo-32905 [https://bugs.python.org/issue?@action=redirect&bpo=32905]: Remove unused code in pyparse module.

bpo-32874 [https://bugs.python.org/issue?@action=redirect&bpo=32874]: Add tests for pyparse.

bpo-32837 [https://bugs.python.org/issue?@action=redirect&bpo=32837]: Using the system and place-dependent default encoding for open() is a bad idea for IDLE’s system and location-independent files.

bpo-32826 [https://bugs.python.org/issue?@action=redirect&bpo=32826]: Add “encoding=utf-8” to open() in IDLE’s test_help_about. GUI test test_file_buttons() only looks at initial ascii-only lines, but failed on systems where open() defaults to ‘ascii’ because readline() internally reads and decodes far enough ahead to encounter a non-ascii character in CREDITS.txt.

bpo-32765 [https://bugs.python.org/issue?@action=redirect&bpo=32765]: Update configdialog General tab docstring to add new widgets to the widget list.

Tools/Demos

bpo-32222 [https://bugs.python.org/issue?@action=redirect&bpo=32222]: Fix pygettext not extracting docstrings for functions with type annotated arguments. Patch by Toby Harradine.

Python 3.7.0 beta 1

Release date: 2018-01-30

Core and Builtins

bpo-32703 [https://bugs.python.org/issue?@action=redirect&bpo=32703]: Fix coroutine’s ResourceWarning when there’s an active error set when it’s being finalized.

bpo-32650 [https://bugs.python.org/issue?@action=redirect&bpo=32650]: Pdb and other debuggers dependent on bdb.py will correctly step over (next command) native coroutines. Patch by Pablo Galindo.

bpo-28685 [https://bugs.python.org/issue?@action=redirect&bpo=28685]: Optimize list.sort() and sorted() by using type specialized comparisons when possible.

bpo-32685 [https://bugs.python.org/issue?@action=redirect&bpo=32685]: Improve suggestion when the Python 2 form of print statement is either present on the same line as the header of a compound statement or else terminated by a semi-colon instead of a newline. Patch by Nitish Chandra.

bpo-32697 [https://bugs.python.org/issue?@action=redirect&bpo=32697]: Python now explicitly preserves the definition order of keyword-only parameters. It’s always preserved their order, but this behavior was never guaranteed before; this behavior is now guaranteed and tested.

bpo-32690 [https://bugs.python.org/issue?@action=redirect&bpo=32690]: The locals() dictionary now displays in the lexical order that variables were defined. Previously, the order was reversed.

bpo-32677 [https://bugs.python.org/issue?@action=redirect&bpo=32677]: Add .isascii() method to str, bytes and bytearray. It can be used to test that string contains only ASCII characters.

bpo-32670 [https://bugs.python.org/issue?@action=redirect&bpo=32670]: Enforce PEP 479 [https://www.python.org/dev/peps/pep-0479] for all code.

This means that manually raising a StopIteration exception from a generator is prohibited for all code, regardless of whether ‘from __future__ import generator_stop’ was used or not.

bpo-32591 [https://bugs.python.org/issue?@action=redirect&bpo=32591]: Added built-in support for tracking the origin of coroutine objects; see sys.set_coroutine_origin_tracking_depth and CoroutineType.cr_origin. This replaces the asyncio debug mode’s use of coroutine wrapping for native coroutine objects.

bpo-31368 [https://bugs.python.org/issue?@action=redirect&bpo=31368]: Expose preadv and pwritev system calls in the os module. Patch by Pablo Galindo

bpo-32544 [https://bugs.python.org/issue?@action=redirect&bpo=32544]: hasattr(obj, name) and getattr(obj, name, default) are about 4 times faster than before when name is not found and obj doesn’t override __getattr__ or __getattribute__.

bpo-26163 [https://bugs.python.org/issue?@action=redirect&bpo=26163]: Improved frozenset() hash to create more distinct hash values when faced with datasets containing many similar values.

bpo-32550 [https://bugs.python.org/issue?@action=redirect&bpo=32550]: Remove the STORE_ANNOTATION bytecode.

bpo-20104 [https://bugs.python.org/issue?@action=redirect&bpo=20104]: Expose posix_spawn as a low level API in the os module. (removed before 3.7.0rc1)

bpo-24340 [https://bugs.python.org/issue?@action=redirect&bpo=24340]: Fixed estimation of the code stack size.

bpo-32436 [https://bugs.python.org/issue?@action=redirect&bpo=32436]: Implement PEP 567 [https://www.python.org/dev/peps/pep-0567] Context Variables.

bpo-18533 [https://bugs.python.org/issue?@action=redirect&bpo=18533]: repr() on a dict containing its own values() or items() no longer raises RecursionError; OrderedDict similarly. Instead, use ..., as for other recursive structures. Patch by Ben North.

bpo-20891 [https://bugs.python.org/issue?@action=redirect&bpo=20891]: Py_Initialize() now creates the GIL. The GIL is no longer created “on demand” to fix a race condition when PyGILState_Ensure() is called in a non-Python thread.

bpo-32028 [https://bugs.python.org/issue?@action=redirect&bpo=32028]: Leading whitespace is now correctly ignored when generating suggestions for converting Py2 print statements to Py3 builtin print function calls. Patch by Sanyam Khurana.

bpo-31179 [https://bugs.python.org/issue?@action=redirect&bpo=31179]: Make dict.copy() up to 5.5 times faster.

bpo-31113 [https://bugs.python.org/issue?@action=redirect&bpo=31113]: Get rid of recursion in the compiler for normal control flow.

Library

bpo-25988 [https://bugs.python.org/issue?@action=redirect&bpo=25988]: Deprecate exposing the contents of collections.abc in the regular collections module.

bpo-31429 [https://bugs.python.org/issue?@action=redirect&bpo=31429]: The default cipher suite selection of the ssl module now uses a blacklist approach rather than a hard-coded whitelist. Python no longer re-enables ciphers that have been blocked by OpenSSL security update. Default cipher suite selection can be configured on compile time.

bpo-30306 [https://bugs.python.org/issue?@action=redirect&bpo=30306]: contextlib.contextmanager now releases the arguments passed to the underlying generator as soon as the context manager is entered. Previously it would keep them alive for as long as the context manager was alive, even when not being used as a function decorator. Patch by Martin Teichmann.

bpo-21417 [https://bugs.python.org/issue?@action=redirect&bpo=21417]: Added support for setting the compression level for zipfile.ZipFile.

bpo-32251 [https://bugs.python.org/issue?@action=redirect&bpo=32251]: Implement asyncio.BufferedProtocol (provisional API).

bpo-32513 [https://bugs.python.org/issue?@action=redirect&bpo=32513]: In dataclasses, allow easier overriding of dunder methods without specifying decorator parameters.

bpo-32660 [https://bugs.python.org/issue?@action=redirect&bpo=32660]: termios makes available FIONREAD, FIONCLEX, FIOCLEX, FIOASYNC and FIONBIO also under Solaris/derivatives.

bpo-27931 [https://bugs.python.org/issue?@action=redirect&bpo=27931]: Fix email address header parsing error when the username is an empty quoted string. Patch by Xiang Zhang.

bpo-32659 [https://bugs.python.org/issue?@action=redirect&bpo=32659]: Under Solaris and derivatives, os.stat_result provides a st_fstype attribute.

bpo-32662 [https://bugs.python.org/issue?@action=redirect&bpo=32662]: Implement Server.start_serving(), Server.serve_forever(), and Server.is_serving() methods. Add ‘start_serving’ keyword parameter to loop.create_server() and loop.create_unix_server().

bpo-32391 [https://bugs.python.org/issue?@action=redirect&bpo=32391]: Implement asyncio.StreamWriter.wait_closed() and asyncio.StreamWriter.is_closing() methods

bpo-32643 [https://bugs.python.org/issue?@action=redirect&bpo=32643]: Make Task._step, Task._wakeup and Future._schedule_callbacks methods private.

bpo-32630 [https://bugs.python.org/issue?@action=redirect&bpo=32630]: Refactor decimal module to use contextvars to store decimal context.

bpo-32622 [https://bugs.python.org/issue?@action=redirect&bpo=32622]: Add asyncio.AbstractEventLoop.sendfile() method.

bpo-32304 [https://bugs.python.org/issue?@action=redirect&bpo=32304]: distutils’ upload command no longer corrupts tar files ending with a CR byte, and no longer tries to convert CR to CRLF in any of the upload text fields.

bpo-32502 [https://bugs.python.org/issue?@action=redirect&bpo=32502]: uuid.uuid1 no longer raises an exception if a 64-bit hardware address is encountered.

bpo-32596 [https://bugs.python.org/issue?@action=redirect&bpo=32596]: concurrent.futures imports ThreadPoolExecutor and ProcessPoolExecutor lazily (using PEP 562 [https://www.python.org/dev/peps/pep-0562]). It makes import asyncio about 15% faster because asyncio uses only ThreadPoolExecutor by default.

bpo-31801 [https://bugs.python.org/issue?@action=redirect&bpo=31801]: Add _ignore_ to Enum so temporary variables can be used during class construction without being turned into members.

bpo-32576 [https://bugs.python.org/issue?@action=redirect&bpo=32576]: Use queue.SimpleQueue() in places where it can be invoked from a weakref callback.

bpo-32574 [https://bugs.python.org/issue?@action=redirect&bpo=32574]: Fix memory leak in asyncio.Queue, when the queue has limited size and it is full, the cancelation of queue.put() can cause a memory leak. Patch by: José Melero.

bpo-32521 [https://bugs.python.org/issue?@action=redirect&bpo=32521]: The nis module is now compatible with new libnsl and headers location.

bpo-32467 [https://bugs.python.org/issue?@action=redirect&bpo=32467]: collections.abc.ValuesView now inherits from collections.abc.Collection.

bpo-32473 [https://bugs.python.org/issue?@action=redirect&bpo=32473]: Improve ABCMeta._dump_registry() output readability

bpo-32102 [https://bugs.python.org/issue?@action=redirect&bpo=32102]: New argument capture_output for subprocess.run

bpo-32521 [https://bugs.python.org/issue?@action=redirect&bpo=32521]: glibc has removed Sun RPC. Use replacement libtirpc headers and library in nis module.

bpo-32493 [https://bugs.python.org/issue?@action=redirect&bpo=32493]: UUID module fixes build for FreeBSD/OpenBSD

bpo-32503 [https://bugs.python.org/issue?@action=redirect&bpo=32503]: Pickling with protocol 4 no longer creates too small frames.

bpo-29237 [https://bugs.python.org/issue?@action=redirect&bpo=29237]: Create enum for pstats sorting options

bpo-32454 [https://bugs.python.org/issue?@action=redirect&bpo=32454]: Add close(fd) function to the socket module.

bpo-25942 [https://bugs.python.org/issue?@action=redirect&bpo=25942]: The subprocess module is now more graceful when handling a Ctrl-C KeyboardInterrupt during subprocess.call, subprocess.run, or a Popen context manager. It now waits a short amount of time for the child (presumed to have also gotten the SIGINT) to exit, before continuing the KeyboardInterrupt exception handling. This still includes a SIGKILL in the call() and run() APIs, but at least the child had a chance first.

bpo-32433 [https://bugs.python.org/issue?@action=redirect&bpo=32433]: The hmac module now has hmac.digest(), which provides an optimized HMAC digest.

bpo-28134 [https://bugs.python.org/issue?@action=redirect&bpo=28134]: Sockets now auto-detect family, type and protocol from file descriptor by default.

bpo-32404 [https://bugs.python.org/issue?@action=redirect&bpo=32404]: Fix bug where datetime.datetime.fromtimestamp() did not call __new__ in datetime.datetime subclasses.

bpo-32403 [https://bugs.python.org/issue?@action=redirect&bpo=32403]: Improved speed of datetime.date and datetime.datetime alternate constructors.

bpo-32228 [https://bugs.python.org/issue?@action=redirect&bpo=32228]: Ensure that truncate() preserves the file position (as reported by tell()) after writes longer than the buffer size.

bpo-32410 [https://bugs.python.org/issue?@action=redirect&bpo=32410]: Implement loop.sock_sendfile for asyncio event loop.

bpo-22908 [https://bugs.python.org/issue?@action=redirect&bpo=22908]: Added seek and tell to the ZipExtFile class. This only works if the file object used to open the zipfile is seekable.

bpo-32373 [https://bugs.python.org/issue?@action=redirect&bpo=32373]: Add socket.getblocking() method.

bpo-32248 [https://bugs.python.org/issue?@action=redirect&bpo=32248]: Add importlib.resources and importlib.abc.ResourceReader as the unified API for reading resources contained within packages. Loaders wishing to support resource reading must implement the get_resource_reader() method. File-based and zipimport-based loaders both implement these APIs. importlib.abc.ResourceLoader is deprecated in favor of these new APIs.

bpo-32320 [https://bugs.python.org/issue?@action=redirect&bpo=32320]: collections.namedtuple() now supports default values.

bpo-29302 [https://bugs.python.org/issue?@action=redirect&bpo=29302]: Add contextlib.AsyncExitStack. Patch by Alexander Mohr and Ilya Kulakov.

bpo-31961 [https://bugs.python.org/issue?@action=redirect&bpo=31961]: Removed in Python 3.7.0b2. The args argument of subprocess.Popen can now be a path-like object. If args is given as a sequence, it’s first element can now be a path-like object as well.

bpo-31900 [https://bugs.python.org/issue?@action=redirect&bpo=31900]: The locale.localeconv() function now sets temporarily the LC_CTYPE locale to the LC_NUMERIC locale to decode decimal_point and thousands_sep byte strings if they are non-ASCII or longer than 1 byte, and the LC_NUMERIC locale is different than the LC_CTYPE locale. This temporary change affects other threads.

Same change for the str.format() method when formatting a number (int, float, float and subclasses) with the n type (ex: '{:n}'.format(1234)).

bpo-31853 [https://bugs.python.org/issue?@action=redirect&bpo=31853]: Use super().method instead of socket.method in SSLSocket. They were there most likely for legacy reasons.

bpo-31399 [https://bugs.python.org/issue?@action=redirect&bpo=31399]: The ssl module now uses OpenSSL’s X509_VERIFY_PARAM_set1_host() and X509_VERIFY_PARAM_set1_ip() API to verify hostname and IP addresses. Subject common name fallback can be disabled with SSLContext.hostname_checks_common_name.

bpo-14976 [https://bugs.python.org/issue?@action=redirect&bpo=14976]: Add a queue.SimpleQueue class, an unbounded FIFO queue with a reentrant C implementation of put().

Documentation

bpo-32724 [https://bugs.python.org/issue?@action=redirect&bpo=32724]: Add references to some commands in the documentation of Pdb. Patch by Stéphane Wirtel

bpo-32649 [https://bugs.python.org/issue?@action=redirect&bpo=32649]: Complete the C API documentation, profiling and tracing part with the newly added per-opcode events.

bpo-17799 [https://bugs.python.org/issue?@action=redirect&bpo=17799]: Explain real behaviour of sys.settrace and sys.setprofile and their C-API counterparts regarding which type of events are received in each function. Patch by Pablo Galindo Salgado.

Tests

bpo-32721 [https://bugs.python.org/issue?@action=redirect&bpo=32721]: Fix test_hashlib to not fail if the _md5 module is not built.

bpo-28414 [https://bugs.python.org/issue?@action=redirect&bpo=28414]: Add test cases for IDNA 2003 and 2008 host names. IDNA 2003 internationalized host names are working since bpo-31399 [https://bugs.python.org/issue?@action=redirect&bpo=31399] has landed. IDNA 2008 are still broken.

bpo-32604 [https://bugs.python.org/issue?@action=redirect&bpo=32604]: Add a new “_xxsubinterpreters” extension module that exposes the existing subinterpreter C-API and a new cross-interpreter data sharing mechanism. The module is primarily intended for more thorough testing of the existing subinterpreter support.

Note that the _xxsubinterpreters module has been removed in 3.7.0rc1.

bpo-32602 [https://bugs.python.org/issue?@action=redirect&bpo=32602]: Add test certs and test for ECDSA cert and EC/RSA dual mode.

bpo-32549 [https://bugs.python.org/issue?@action=redirect&bpo=32549]: On Travis CI, Python now Compiles and uses a local copy of OpenSSL 1.1.0g for testing.

Build

bpo-32635 [https://bugs.python.org/issue?@action=redirect&bpo=32635]: Fix segfault of the crypt module when libxcrypt is provided instead of libcrypt at the system.

bpo-32598 [https://bugs.python.org/issue?@action=redirect&bpo=32598]: Use autoconf to detect OpenSSL libs, headers and supported features. The ax_check_openssl M4 macro uses pkg-config to locate OpenSSL and falls back to manual search.

bpo-32593 [https://bugs.python.org/issue?@action=redirect&bpo=32593]: Drop support of FreeBSD 9 and older.

bpo-29708 [https://bugs.python.org/issue?@action=redirect&bpo=29708]: If the SOURCE_DATE_EPOCH environment variable is set, py_compile will always create hash-based .pyc files.

Windows

bpo-32588 [https://bugs.python.org/issue?@action=redirect&bpo=32588]: Create standalone _distutils_findvs module and add missing _queue module to installer.

bpo-29911 [https://bugs.python.org/issue?@action=redirect&bpo=29911]: Ensure separate Modify and Uninstall buttons are displayed.

bpo-32507 [https://bugs.python.org/issue?@action=redirect&bpo=32507]: Use app-local UCRT install rather than the proper update for old versions of Windows.

macOS

bpo-32726 [https://bugs.python.org/issue?@action=redirect&bpo=32726]: Provide an additional, more modern macOS installer variant that supports macOS 10.9+ systems in 64-bit mode only. Upgrade the supplied third-party libraries to OpenSSL 1.1.0g and to SQLite 3.22.0. The 10.9+ installer now links with and supplies its own copy of Tcl/Tk 8.6.

bpo-28440 [https://bugs.python.org/issue?@action=redirect&bpo=28440]: No longer add /Library/Python/3.x/site-packages to sys.path for macOS framework builds to avoid future conflicts.

C API

bpo-32681 [https://bugs.python.org/issue?@action=redirect&bpo=32681]: Fix uninitialized variable ‘res’ in the C implementation of os.dup2. Patch by Stéphane Wirtel

bpo-10381 [https://bugs.python.org/issue?@action=redirect&bpo=10381]: Add C API access to the datetime.timezone constructor and datetime.timzone.UTC singleton.

Python 3.7.0 alpha 4

Release date: 2018-01-08

Core and Builtins

bpo-31975 [https://bugs.python.org/issue?@action=redirect&bpo=31975]: The default warning filter list now starts with a “default::DeprecationWarning:__main__” entry, so deprecation warnings are once again shown by default in single-file scripts and at the interactive prompt.

bpo-32226 [https://bugs.python.org/issue?@action=redirect&bpo=32226]: __class_getitem__ is now an automatic class method.

bpo-32399 [https://bugs.python.org/issue?@action=redirect&bpo=32399]: Add AIX uuid library support for RFC4122 using uuid_create() in libc.a

bpo-32390 [https://bugs.python.org/issue?@action=redirect&bpo=32390]: Fix the compilation failure on AIX after the f_fsid field has been added to the object returned by os.statvfs() (bpo-32143 [https://bugs.python.org/issue?@action=redirect&bpo=32143]). Original patch by Michael Felt.

bpo-32379 [https://bugs.python.org/issue?@action=redirect&bpo=32379]: Make MRO computation faster when a class inherits from a single base.

bpo-32259 [https://bugs.python.org/issue?@action=redirect&bpo=32259]: The error message of a TypeError raised when unpack non-iterable is now more specific.

bpo-27169 [https://bugs.python.org/issue?@action=redirect&bpo=27169]: The __debug__ constant is now optimized out at compile time. This fixes also bpo-22091 [https://bugs.python.org/issue?@action=redirect&bpo=22091].

bpo-32329 [https://bugs.python.org/issue?@action=redirect&bpo=32329]: The -R option now turns on hash randomization when the PYTHONHASHSEED environment variable is set to 0. Previously, the option was ignored. Moreover, sys.flags.hash_randomization is now properly set to 0 when hash randomization is turned off by PYTHONHASHSEED=0.

bpo-30416 [https://bugs.python.org/issue?@action=redirect&bpo=30416]: The optimizer is now protected from spending much time doing complex calculations and consuming much memory for creating large constants in constant folding. Increased limits for constants that can be produced in constant folding.

bpo-32282 [https://bugs.python.org/issue?@action=redirect&bpo=32282]: Fix an unnecessary ifdef in the include of VersionHelpers.h in socketmodule on Windows.

bpo-30579 [https://bugs.python.org/issue?@action=redirect&bpo=30579]: Implement TracebackType.__new__ to allow Python-level creation of traceback objects, and make TracebackType.tb_next mutable.

bpo-32260 [https://bugs.python.org/issue?@action=redirect&bpo=32260]: Don’t byte swap the input keys to the SipHash algorithm on big-endian platforms. This should ensure siphash gives consistent results across platforms.

bpo-31506 [https://bugs.python.org/issue?@action=redirect&bpo=31506]: Improve the error message logic for object.__new__ and object.__init__. Patch by Sanyam Khurana.

bpo-20361 [https://bugs.python.org/issue?@action=redirect&bpo=20361]: -b and -bb now inject 'default::BytesWarning' and error::BytesWarning entries into sys.warnoptions, ensuring that they take precedence over any other warning filters configured via the -W option or the PYTHONWARNINGS environment variable.

bpo-32230 [https://bugs.python.org/issue?@action=redirect&bpo=32230]: -X dev now injects a 'default' entry into sys.warnoptions, ensuring that it behaves identically to actually passing -Wdefault at the command line.

bpo-29240 [https://bugs.python.org/issue?@action=redirect&bpo=29240]: Add a new UTF-8 mode: implementation of the PEP 540 [https://www.python.org/dev/peps/pep-0540].

bpo-32226 [https://bugs.python.org/issue?@action=redirect&bpo=32226]: PEP 560 [https://www.python.org/dev/peps/pep-0560]: Add support for __mro_entries__ and __class_getitem__. Implemented by Ivan Levkivskyi.

bpo-32225 [https://bugs.python.org/issue?@action=redirect&bpo=32225]: PEP 562 [https://www.python.org/dev/peps/pep-0562]: Add support for module __getattr__ and __dir__. Implemented by Ivan Levkivskyi.

bpo-31901 [https://bugs.python.org/issue?@action=redirect&bpo=31901]: The atexit module now has its callback stored per interpreter.

bpo-31650 [https://bugs.python.org/issue?@action=redirect&bpo=31650]: Implement PEP 552 [https://www.python.org/dev/peps/pep-0552] (Deterministic pycs). Python now supports invalidating bytecode cache files bashed on a source content hash rather than source last-modified time.

bpo-29469 [https://bugs.python.org/issue?@action=redirect&bpo=29469]: Move constant folding from bytecode layer to AST layer. Original patch by Eugene Toder.

Library

bpo-32506 [https://bugs.python.org/issue?@action=redirect&bpo=32506]: Now that dict is defined as keeping insertion order, drop OrderedDict and just use plain dict.

bpo-32279 [https://bugs.python.org/issue?@action=redirect&bpo=32279]: Add params to dataclasses.make_dataclasses(): init, repr, eq, order, hash, and frozen. Pass them through to dataclass().

bpo-32278 [https://bugs.python.org/issue?@action=redirect&bpo=32278]: Make type information optional on dataclasses.make_dataclass(). If omitted, the string ‘typing.Any’ is used.

bpo-32499 [https://bugs.python.org/issue?@action=redirect&bpo=32499]: Add dataclasses.is_dataclass(obj), which returns True if obj is a dataclass or an instance of one.

bpo-32468 [https://bugs.python.org/issue?@action=redirect&bpo=32468]: Improve frame repr() to mention filename, code name and current line number.

bpo-23749 [https://bugs.python.org/issue?@action=redirect&bpo=23749]: asyncio: Implement loop.start_tls()

bpo-32441 [https://bugs.python.org/issue?@action=redirect&bpo=32441]: Return the new file descriptor (i.e., the second argument) from os.dup2. Previously, None was always returned.

bpo-32422 [https://bugs.python.org/issue?@action=redirect&bpo=32422]: functools.lru_cache uses less memory (3 words for each cached key) and takes about 1/3 time for cyclic GC.

bpo-31721 [https://bugs.python.org/issue?@action=redirect&bpo=31721]: Prevent Python crash from happening when Future._log_traceback is set to True manually. Now it can only be set to False, or a ValueError is raised.

bpo-32415 [https://bugs.python.org/issue?@action=redirect&bpo=32415]: asyncio: Add Task.get_loop() and Future.get_loop()

bpo-26133 [https://bugs.python.org/issue?@action=redirect&bpo=26133]: Don’t unsubscribe signals in asyncio UNIX event loop on interpreter shutdown.

bpo-32363 [https://bugs.python.org/issue?@action=redirect&bpo=32363]: Make asyncio.Task.set_exception() and set_result() raise NotImplementedError. Task._step() and Future.__await__() raise proper exceptions when they are in an invalid state, instead of raising an AssertionError.

bpo-32357 [https://bugs.python.org/issue?@action=redirect&bpo=32357]: Optimize asyncio.iscoroutine() and loop.create_task() for non-native coroutines (e.g. async/await compiled with Cython).

‘loop.create_task(python_coroutine)’ used to be 20% faster than ‘loop.create_task(cython_coroutine)’. Now, the latter is as fast.

bpo-32356 [https://bugs.python.org/issue?@action=redirect&bpo=32356]: asyncio.transport.resume_reading() and pause_reading() are now idempotent. New transport.is_reading() method is added.

bpo-32355 [https://bugs.python.org/issue?@action=redirect&bpo=32355]: Optimize asyncio.gather(); now up to 15% faster.

bpo-32351 [https://bugs.python.org/issue?@action=redirect&bpo=32351]: Use fastpath in asyncio.sleep if delay<0 (2x boost)

bpo-32348 [https://bugs.python.org/issue?@action=redirect&bpo=32348]: Optimize asyncio.Future schedule/add/remove callback. The optimization shows 3-6% performance improvements of async/await code.

bpo-32331 [https://bugs.python.org/issue?@action=redirect&bpo=32331]: Fix socket.settimeout() and socket.setblocking() to keep socket.type as is. Fix socket.socket() constructor to reset any bit flags applied to socket’s type. This change only affects OSes that have SOCK_NONBLOCK and/or SOCK_CLOEXEC.

bpo-32248 [https://bugs.python.org/issue?@action=redirect&bpo=32248]: Add importlib.abc.ResourceReader as an ABC for loaders to provide a unified API for reading resources contained within packages. Also add importlib.resources as the port of importlib_resources.

bpo-32311 [https://bugs.python.org/issue?@action=redirect&bpo=32311]: Implement asyncio.create_task(coro) shortcut

bpo-32327 [https://bugs.python.org/issue?@action=redirect&bpo=32327]: Convert asyncio functions that were documented as coroutines to coroutines. Affected functions: loop.sock_sendall, loop.sock_recv, loop.sock_accept, loop.getaddrinfo, loop.getnameinfo.

bpo-32323 [https://bugs.python.org/issue?@action=redirect&bpo=32323]: urllib.parse.urlsplit() does not convert zone-id (scope) to lower case for scoped IPv6 addresses in hostnames now.

bpo-32302 [https://bugs.python.org/issue?@action=redirect&bpo=32302]: Fix bdist_wininst of distutils for CRT v142: it binary compatible with CRT v140.

bpo-29711 [https://bugs.python.org/issue?@action=redirect&bpo=29711]: Fix stop_serving in asyncio proactor loop kill all listening servers

bpo-32308 [https://bugs.python.org/issue?@action=redirect&bpo=32308]: re.sub() now replaces empty matches adjacent to a previous non-empty match.

bpo-29970 [https://bugs.python.org/issue?@action=redirect&bpo=29970]: Abort asyncio SSLProtocol connection if handshake not complete within 10s

bpo-32314 [https://bugs.python.org/issue?@action=redirect&bpo=32314]: Implement asyncio.run().

bpo-17852 [https://bugs.python.org/issue?@action=redirect&bpo=17852]: Revert incorrect fix based on misunderstanding of _Py_PyAtExit() semantics.

bpo-32296 [https://bugs.python.org/issue?@action=redirect&bpo=32296]: Implement asyncio._get_running_loop() and get_event_loop() in C. This makes them 4x faster.

bpo-32250 [https://bugs.python.org/issue?@action=redirect&bpo=32250]: Implement asyncio.current_task() and asyncio.all_tasks(). Add helpers intended to be used by alternative task implementations: asyncio._register_task, asyncio._enter_task, asyncio._leave_task and asyncio._unregister_task. Deprecate asyncio.Task.current_task() and asyncio.Task.all_tasks().

bpo-32255 [https://bugs.python.org/issue?@action=redirect&bpo=32255]: A single empty field is now always quoted when written into a CSV file. This allows to distinguish an empty row from a row consisting of a single empty field. Patch by Licht Takeuchi.

bpo-32277 [https://bugs.python.org/issue?@action=redirect&bpo=32277]: Raise NotImplementedError instead of SystemError on platforms where chmod(..., follow_symlinks=False) is not supported. Patch by Anthony Sottile.

bpo-30050 [https://bugs.python.org/issue?@action=redirect&bpo=30050]: New argument warn_on_full_buffer to signal.set_wakeup_fd lets you control whether Python prints a warning on stderr when the wakeup fd buffer overflows.

bpo-29137 [https://bugs.python.org/issue?@action=redirect&bpo=29137]: The fpectl library has been removed. It was never enabled by default, never worked correctly on x86-64, and it changed the Python ABI in ways that caused unexpected breakage of C extensions.

bpo-32273 [https://bugs.python.org/issue?@action=redirect&bpo=32273]: Move asyncio.test_utils to test.test_asyncio.

bpo-32272 [https://bugs.python.org/issue?@action=redirect&bpo=32272]: Remove asyncio.async() function.

bpo-32269 [https://bugs.python.org/issue?@action=redirect&bpo=32269]: Add asyncio.get_running_loop() function.

bpo-32265 [https://bugs.python.org/issue?@action=redirect&bpo=32265]: All class and static methods of builtin types now are correctly classified by inspect.classify_class_attrs() and grouped in pydoc ouput. Added types.ClassMethodDescriptorType for unbound class methods of builtin types.

bpo-32253 [https://bugs.python.org/issue?@action=redirect&bpo=32253]: Deprecate yield from lock, await lock, with (yield from lock) and with await lock for asyncio synchronization primitives.

bpo-22589 [https://bugs.python.org/issue?@action=redirect&bpo=22589]: Changed MIME type of .bmp from ‘image/x-ms-bmp’ to ‘image/bmp’

bpo-32193 [https://bugs.python.org/issue?@action=redirect&bpo=32193]: Convert asyncio to use async/await syntax. Old styled yield from is still supported too.

bpo-32206 [https://bugs.python.org/issue?@action=redirect&bpo=32206]: Add support to run modules with pdb

bpo-32227 [https://bugs.python.org/issue?@action=redirect&bpo=32227]: functools.singledispatch now supports registering implementations using type annotations.

bpo-15873 [https://bugs.python.org/issue?@action=redirect&bpo=15873]: Added new alternate constructors datetime.datetime.fromisoformat(), datetime.time.fromisoformat() and datetime.date.fromisoformat() as the inverse operation of each classes’s respective isoformat methods.

bpo-32199 [https://bugs.python.org/issue?@action=redirect&bpo=32199]: The getnode() ip getter now uses ‘ip link’ instead of ‘ip link list’.

bpo-32143 [https://bugs.python.org/issue?@action=redirect&bpo=32143]: os.statvfs() includes the f_fsid field from statvfs(2)

bpo-26439 [https://bugs.python.org/issue?@action=redirect&bpo=26439]: Fix ctypes.util.find_library() for AIX by implementing ctypes._aix.find_library() Patch by: Michael Felt

bpo-31993 [https://bugs.python.org/issue?@action=redirect&bpo=31993]: The pickler now uses less memory when serializing large bytes and str objects into a file. Pickles created with protocol 4 will require less memory for unpickling large bytes and str objects.

bpo-27456 [https://bugs.python.org/issue?@action=redirect&bpo=27456]: Ensure TCP_NODELAY is set on Linux. Tests by Victor Stinner.

bpo-31778 [https://bugs.python.org/issue?@action=redirect&bpo=31778]: ast.literal_eval() is now more strict. Addition and subtraction of arbitrary numbers no longer allowed.

bpo-31802 [https://bugs.python.org/issue?@action=redirect&bpo=31802]: Importing native path module (posixpath, ntpath) now works even if the os module still is not imported.

bpo-30241 [https://bugs.python.org/issue?@action=redirect&bpo=30241]: Add contextlib.AbstractAsyncContextManager. Patch by Jelle Zijlstra.

bpo-31699 [https://bugs.python.org/issue?@action=redirect&bpo=31699]: Fix deadlocks in concurrent.futures.ProcessPoolExecutor when task arguments or results cause pickling or unpickling errors. This should make sure that calls to the ProcessPoolExecutor API always eventually return.

bpo-15216 [https://bugs.python.org/issue?@action=redirect&bpo=15216]: TextIOWrapper.reconfigure() supports changing encoding, errors, and newline.

Documentation

bpo-32418 [https://bugs.python.org/issue?@action=redirect&bpo=32418]: Add get_loop() method to Server and AbstractServer classes.

Tests

bpo-32252 [https://bugs.python.org/issue?@action=redirect&bpo=32252]: Fix faulthandler_suppress_crash_report() used to prevent core dump files when testing crashes. getrlimit() returns zero on success.

bpo-32002 [https://bugs.python.org/issue?@action=redirect&bpo=32002]: Adjust C locale coercion testing for the empty locale and POSIX locale cases to more readily adjust to platform dependent behaviour.

Windows

bpo-19764 [https://bugs.python.org/issue?@action=redirect&bpo=19764]: Implement support for subprocess.Popen(close_fds=True) on Windows. Patch by Segev Finer.

Tools/Demos

bpo-24960 [https://bugs.python.org/issue?@action=redirect&bpo=24960]: 2to3 and lib2to3 can now read pickled grammar files using pkgutil.get_data() rather than probing the filesystem. This lets 2to3 and lib2to3 work when run from a zipfile.

C API

bpo-32030 [https://bugs.python.org/issue?@action=redirect&bpo=32030]: Py_Initialize() doesn’t reset the memory allocators to default if the PYTHONMALLOC environment variable is not set.

bpo-29084 [https://bugs.python.org/issue?@action=redirect&bpo=29084]: Undocumented C API for OrderedDict has been excluded from the limited C API. It was added by mistake and actually never worked in the limited C API.

bpo-32264 [https://bugs.python.org/issue?@action=redirect&bpo=32264]: Moved the pygetopt.h header into internal/, since it has no public APIs.

bpo-32241 [https://bugs.python.org/issue?@action=redirect&bpo=32241]: Py_SetProgramName() and Py_SetPythonHome() now take the const wchar * arguments instead of wchar *.

Python 3.7.0 alpha 3

Release date: 2017-12-05

Core and Builtins

bpo-32176 [https://bugs.python.org/issue?@action=redirect&bpo=32176]: co_flags.CO_NOFREE is now always set correctly by the code object constructor based on freevars and cellvars, rather than needing to be set correctly by the caller. This ensures it will be cleared automatically when additional cell references are injected into a modified code object and function.

bpo-10544 [https://bugs.python.org/issue?@action=redirect&bpo=10544]: Yield expressions are now deprecated in comprehensions and generator expressions. They are still permitted in the definition of the outermost iterable, as that is evaluated directly in the enclosing scope.

bpo-32137 [https://bugs.python.org/issue?@action=redirect&bpo=32137]: The repr of deeply nested dict now raises a RecursionError instead of crashing due to a stack overflow.

bpo-32096 [https://bugs.python.org/issue?@action=redirect&bpo=32096]: Revert memory allocator changes in the C API: move structures back from _PyRuntime to Objects/obmalloc.c. The memory allocators are once again initialized statically, and so PyMem_RawMalloc() and Py_DecodeLocale() can be called before _PyRuntime_Initialize().

bpo-32043 [https://bugs.python.org/issue?@action=redirect&bpo=32043]: Add a new “developer mode”: new “-X dev” command line option to enable debug checks at runtime.

bpo-32023 [https://bugs.python.org/issue?@action=redirect&bpo=32023]: SyntaxError is now correctly raised when a generator expression without parenthesis is used instead of an inheritance list in a class definition. The duplication of the parentheses can be omitted only on calls.

bpo-32012 [https://bugs.python.org/issue?@action=redirect&bpo=32012]: SyntaxError is now correctly raised when a generator expression without parenthesis is passed as an argument, but followed by a trailing comma. A generator expression always needs to be directly inside a set of parentheses and cannot have a comma on either side.

bpo-28180 [https://bugs.python.org/issue?@action=redirect&bpo=28180]: A new internal _Py_SetLocaleFromEnv(category) helper function has been added in order to improve the consistency of behaviour across different libc implementations (e.g. Android doesn’t support setting the locale from the environment by default).

bpo-31949 [https://bugs.python.org/issue?@action=redirect&bpo=31949]: Fixed several issues in printing tracebacks (PyTraceBack_Print()).

Setting sys.tracebacklimit to 0 or less now suppresses printing tracebacks.

Setting sys.tracebacklimit to None now causes using the default limit.

Setting sys.tracebacklimit to an integer larger than LONG_MAX now means using the limit LONG_MAX rather than the default limit.

Fixed integer overflows in the case of more than 2**31 traceback items on Windows.

Fixed output errors handling.

bpo-30696 [https://bugs.python.org/issue?@action=redirect&bpo=30696]: Fix the interactive interpreter looping endlessly when no memory.

bpo-20047 [https://bugs.python.org/issue?@action=redirect&bpo=20047]: Bytearray methods partition() and rpartition() now accept only bytes-like objects as separator, as documented. In particular they now raise TypeError rather of returning a bogus result when an integer is passed as a separator.

bpo-21720 [https://bugs.python.org/issue?@action=redirect&bpo=21720]: BytesWarning no longer emitted when the fromlist argument of __import__() or the __all__ attribute of the module contain bytes instances.

bpo-31845 [https://bugs.python.org/issue?@action=redirect&bpo=31845]: Environment variables are once more read correctly at interpreter startup.

bpo-28936 [https://bugs.python.org/issue?@action=redirect&bpo=28936]: Ensure that lexically first syntax error involving a parameter and global or nonlocal is detected first at a given scope. Patch by Ivan Levkivskyi.

bpo-31825 [https://bugs.python.org/issue?@action=redirect&bpo=31825]: Fixed OverflowError in the ‘unicode-escape’ codec and in codecs.escape_decode() when decode an escaped non-ascii byte.

bpo-31618 [https://bugs.python.org/issue?@action=redirect&bpo=31618]: The per-frame tracing logic added in 3.7a1 has been altered so that frame->f_lineno is updated before either "line" or "opcode" events are emitted. Previously, opcode events were emitted first, and therefore would occasionally see stale line numbers on the frame. The behavior of this feature has changed slightly as a result: when both f_trace_lines and f_trace_opcodes are enabled, line events now occur first.

bpo-28603 [https://bugs.python.org/issue?@action=redirect&bpo=28603]: Print the full context/cause chain of exceptions on interpreter exit, even if an exception in the chain is unhashable or compares equal to later ones. Patch by Zane Bitter.

bpo-31786 [https://bugs.python.org/issue?@action=redirect&bpo=31786]: Fix timeout rounding in the select module to round correctly negative timeouts between -1.0 and 0.0. The functions now block waiting for events as expected. Previously, the call was incorrectly non-blocking. Patch by Pablo Galindo.

bpo-31781 [https://bugs.python.org/issue?@action=redirect&bpo=31781]: Prevent crashes when calling methods of an uninitialized zipimport.zipimporter object. Patch by Oren Milman.

bpo-30399 [https://bugs.python.org/issue?@action=redirect&bpo=30399]: Standard repr() of BaseException with a single argument no longer contains redundant trailing comma.

bpo-31626 [https://bugs.python.org/issue?@action=redirect&bpo=31626]: Fixed a bug in debug memory allocator. There was a write to freed memory after shrinking a memory block.

bpo-30817 [https://bugs.python.org/issue?@action=redirect&bpo=30817]: PyErr_PrintEx() clears now the ignored exception that may be raised by _PySys_SetObjectId(), for example when no memory.

Library

bpo-28556 [https://bugs.python.org/issue?@action=redirect&bpo=28556]: Two minor fixes for typing module: allow shallow copying instances of generic classes, improve interaction of __init_subclass__ with generics. Original PRs by Ivan Levkivskyi.

bpo-32214 [https://bugs.python.org/issue?@action=redirect&bpo=32214]: PEP 557, Data Classes. Provides a decorator which adds boilerplate methods to classes which use type annotations so specify fields.

bpo-27240 [https://bugs.python.org/issue?@action=redirect&bpo=27240]: The header folding algorithm for the new email policies has been rewritten, which also fixes bpo-30788 [https://bugs.python.org/issue?@action=redirect&bpo=30788], bpo-31831 [https://bugs.python.org/issue?@action=redirect&bpo=31831], and bpo-32182 [https://bugs.python.org/issue?@action=redirect&bpo=32182]. In particular, RFC2231 folding is now done correctly.

bpo-32186 [https://bugs.python.org/issue?@action=redirect&bpo=32186]: io.FileIO.readall() and io.FileIO.read() now release the GIL when getting the file size. Fixed hang of all threads with inaccessible NFS server. Patch by Nir Soffer.

bpo-32101 [https://bugs.python.org/issue?@action=redirect&bpo=32101]: Add sys.flags.dev_mode flag

bpo-32154 [https://bugs.python.org/issue?@action=redirect&bpo=32154]: The asyncio.windows_utils.socketpair() function has been removed: use directly socket.socketpair() which is available on all platforms since Python 3.5 (before, it wasn’t available on Windows). asyncio.windows_utils.socketpair() was just an alias to socket.socketpair on Python 3.5 and newer.

bpo-32089 [https://bugs.python.org/issue?@action=redirect&bpo=32089]: warnings: In development (-X dev) and debug mode (pydebug build), use the “default” action for ResourceWarning, rather than the “always” action, in the default warnings filters.

bpo-32107 [https://bugs.python.org/issue?@action=redirect&bpo=32107]: uuid.getnode() now preferentially returns universally administered MAC addresses if available, over locally administered MAC addresses. This makes a better guarantee for global uniqueness of UUIDs returned from uuid.uuid1(). If only locally administered MAC addresses are available, the first such one found is returned.

bpo-23033 [https://bugs.python.org/issue?@action=redirect&bpo=23033]: Wildcard is now supported in hostname when it is one and only character in the left most segment of hostname in second argument of ssl.match_hostname(). Patch by Mandeep Singh.

bpo-12239 [https://bugs.python.org/issue?@action=redirect&bpo=12239]: Make msilib.SummaryInformation.GetProperty() return None when the value of property is VT_EMPTY. Initial patch by Mark Mc Mahon.

bpo-28334 [https://bugs.python.org/issue?@action=redirect&bpo=28334]: Use os.path.expanduser() to find the ~/.netrc file in netrc.netrc. If it does not exist, FileNotFoundError is raised. Patch by Dimitri Merejkowsky.

bpo-32121 [https://bugs.python.org/issue?@action=redirect&bpo=32121]: Made tracemalloc.Traceback behave more like the traceback module, sorting the frames from oldest to most recent. Traceback.format() now accepts negative limit, truncating the result to the abs(limit) oldest frames. To get the old behaviour, one can use the new most_recent_first argument to Traceback.format(). (Patch by Jesse Bakker.)

bpo-31325 [https://bugs.python.org/issue?@action=redirect&bpo=31325]: Fix wrong usage of collections.namedtuple() in the RobotFileParser.parse() method.

Initial patch by Robin Wellner.

bpo-12382 [https://bugs.python.org/issue?@action=redirect&bpo=12382]: msilib.OpenDatabase() now raises a better exception message when it couldn’t open or create an MSI file. Initial patch by William Tisäter.

bpo-19610 [https://bugs.python.org/issue?@action=redirect&bpo=19610]: setup() now warns about invalid types for some fields.

The distutils.dist.Distribution class now warns when classifiers, keywords and platforms fields are not specified as a list or a string.

bpo-32071 [https://bugs.python.org/issue?@action=redirect&bpo=32071]: Added the -k command-line option to python -m unittest to run only tests that match the given pattern(s).

bpo-10049 [https://bugs.python.org/issue?@action=redirect&bpo=10049]: Added nullcontext no-op context manager to contextlib. This provides a simpler and faster alternative to ExitStack() when handling optional context managers.

bpo-28684 [https://bugs.python.org/issue?@action=redirect&bpo=28684]: The new test.support.skip_unless_bind_unix_socket() decorator is used here to skip asyncio tests that fail because the platform lacks a functional bind() function for unix domain sockets (as it is the case for non root users on the recent Android versions that run now SELinux in enforcing mode).

bpo-32110 [https://bugs.python.org/issue?@action=redirect&bpo=32110]: codecs.StreamReader.read(n) now returns not more than n characters/bytes for non-negative n. This makes it compatible with read() methods of other file-like objects.

bpo-27535 [https://bugs.python.org/issue?@action=redirect&bpo=27535]: The warnings module doesn’t leak memory anymore in the hidden warnings registry for the “ignore” action of warnings filters. warn_explicit() function doesn’t add the warning key to the registry anymore for the “ignore” action.

bpo-32088 [https://bugs.python.org/issue?@action=redirect&bpo=32088]: warnings: When Python is build is debug mode (Py_DEBUG), DeprecationWarning, PendingDeprecationWarning and ImportWarning warnings are now displayed by default.

bpo-1647489 [https://bugs.python.org/issue?@action=redirect&bpo=1647489]: Fixed searching regular expression patterns that could match an empty string. Non-empty string can now be correctly found after matching an empty string.

bpo-25054 [https://bugs.python.org/issue?@action=redirect&bpo=25054]: Added support of splitting on a pattern that could match an empty string.

bpo-32072 [https://bugs.python.org/issue?@action=redirect&bpo=32072]: Fixed issues with binary plists:

Fixed saving bytearrays.

Identical objects will be saved only once.

Equal references will be load as identical objects.

Added support for saving and loading recursive data structures.

bpo-32069 [https://bugs.python.org/issue?@action=redirect&bpo=32069]: Drop legacy SSL transport from asyncio, ssl.MemoryBIO is always used anyway.

bpo-32066 [https://bugs.python.org/issue?@action=redirect&bpo=32066]: asyncio: Support pathlib.Path in create_unix_connection; sock arg should be optional

bpo-32046 [https://bugs.python.org/issue?@action=redirect&bpo=32046]: Updates 2to3 to convert from operator.isCallable(obj) to callable(obj). Patch by Dong-hee Na.

bpo-32018 [https://bugs.python.org/issue?@action=redirect&bpo=32018]: inspect.signature should follow PEP 8, if the parameter has an annotation and a default value. Patch by Dong-hee Na.

bpo-32025 [https://bugs.python.org/issue?@action=redirect&bpo=32025]: Add time.thread_time() and time.thread_time_ns()

bpo-32037 [https://bugs.python.org/issue?@action=redirect&bpo=32037]: Integers that fit in a signed 32-bit integer will be now pickled with protocol 0 using the INT opcode. This will decrease the size of a pickle, speed up pickling and unpickling, and make these integers be unpickled as int instances in Python 2.

bpo-32034 [https://bugs.python.org/issue?@action=redirect&bpo=32034]: Make asyncio.IncompleteReadError and LimitOverrunError pickleable.

bpo-32015 [https://bugs.python.org/issue?@action=redirect&bpo=32015]: Fixed the looping of asyncio in the case of reconnection the socket during waiting async read/write from/to the socket.

bpo-32011 [https://bugs.python.org/issue?@action=redirect&bpo=32011]: Restored support of loading marshal files with the TYPE_INT64 code. These files can be produced in Python 2.7.

bpo-28369 [https://bugs.python.org/issue?@action=redirect&bpo=28369]: Enhance add_reader/writer check that socket is not used by some transport. Before, only cases when add_reader/writer were called with an int FD were supported. Now the check is implemented correctly for all file-like objects.

bpo-31976 [https://bugs.python.org/issue?@action=redirect&bpo=31976]: Fix race condition when flushing a file is slow, which can cause a segfault if closing the file from another thread.

bpo-31985 [https://bugs.python.org/issue?@action=redirect&bpo=31985]: Formally deprecated aifc.openfp, sunau.openfp, and wave.openfp. Since change 7bc817d5ba917528e8bd07ec461c635291e7b06a in 1993, openfp in each of the three modules had been pointing to that module’s open function as a matter of backwards compatibility, though it had been both untested and undocumented.

bpo-21862 [https://bugs.python.org/issue?@action=redirect&bpo=21862]: cProfile command line now accepts -m module_name as an alternative to script path. Patch by Sanyam Khurana.

bpo-31970 [https://bugs.python.org/issue?@action=redirect&bpo=31970]: Reduce performance overhead of asyncio debug mode.

bpo-31843 [https://bugs.python.org/issue?@action=redirect&bpo=31843]: database argument of sqlite3.connect() now accepts a path-like object, instead of just a string.

bpo-31945 [https://bugs.python.org/issue?@action=redirect&bpo=31945]: Add Configurable blocksize to HTTPConnection and HTTPSConnection for improved upload throughput. Patch by Nir Soffer.

bpo-31943 [https://bugs.python.org/issue?@action=redirect&bpo=31943]: Add a cancelled() method to asyncio.Handle. Patch by Marat Sharafutdinov.

bpo-9678 [https://bugs.python.org/issue?@action=redirect&bpo=9678]: Fixed determining the MAC address in the uuid module:

Using ifconfig on NetBSD and OpenBSD.

Using arp on Linux, FreeBSD, NetBSD and OpenBSD.

Based on patch by Takayuki Shimizukawa.

bpo-30057 [https://bugs.python.org/issue?@action=redirect&bpo=30057]: Fix potential missed signal in signal.signal().

bpo-31933 [https://bugs.python.org/issue?@action=redirect&bpo=31933]: Fix Blake2 params leaf_size and node_offset on big endian platforms. Patch by Jack O’Connor.

bpo-21423 [https://bugs.python.org/issue?@action=redirect&bpo=21423]: Add an initializer argument to {Process,Thread}PoolExecutor

bpo-31927 [https://bugs.python.org/issue?@action=redirect&bpo=31927]: Fixed compilation of the socket module on NetBSD 8. Fixed assertion failure or reading arbitrary data when parse a AF_BLUETOOTH address on NetBSD and DragonFly BSD.

bpo-27666 [https://bugs.python.org/issue?@action=redirect&bpo=27666]: Fixed stack corruption in curses.box() and curses.ungetmouse() when the size of types chtype or mmask_t is less than the size of C long. curses.box() now accepts characters as arguments. Based on patch by Steve Fink.

bpo-31917 [https://bugs.python.org/issue?@action=redirect&bpo=31917]: Add 3 new clock identifiers: time.CLOCK_BOOTTIME, time.CLOCK_PROF and time.CLOCK_UPTIME.

bpo-31897 [https://bugs.python.org/issue?@action=redirect&bpo=31897]: plistlib now catches more errors when read binary plists and raises InvalidFileException instead of unexpected exceptions.

bpo-25720 [https://bugs.python.org/issue?@action=redirect&bpo=25720]: Fix the method for checking pad state of curses WINDOW. Patch by Masayuki Yamamoto.

bpo-31893 [https://bugs.python.org/issue?@action=redirect&bpo=31893]: Fixed the layout of the kqueue_event structure on OpenBSD and NetBSD. Fixed the comparison of the kqueue_event objects.

bpo-31891 [https://bugs.python.org/issue?@action=redirect&bpo=31891]: Fixed building the curses module on NetBSD.

bpo-31884 [https://bugs.python.org/issue?@action=redirect&bpo=31884]: added required constants to subprocess module for setting priority on windows

bpo-28281 [https://bugs.python.org/issue?@action=redirect&bpo=28281]: Remove year (1-9999) limits on the Calendar.weekday() function.

Patch by Mark Gollahon.

bpo-31702 [https://bugs.python.org/issue?@action=redirect&bpo=31702]: crypt.mksalt() now allows to specify the number of rounds for SHA-256 and SHA-512 hashing.

bpo-30639 [https://bugs.python.org/issue?@action=redirect&bpo=30639]: inspect.getfile() no longer computes the repr of unknown objects to display in an error message, to protect against badly behaved custom reprs.

bpo-30768 [https://bugs.python.org/issue?@action=redirect&bpo=30768]: Fix the pthread+semaphore implementation of PyThread_acquire_lock_timed() when called with timeout > 0 and intr_flag=0: recompute the timeout if sem_timedwait() is interrupted by a signal (EINTR). See also the PEP 475 [https://www.python.org/dev/peps/pep-0475].

bpo-31854 [https://bugs.python.org/issue?@action=redirect&bpo=31854]: Add mmap.ACCESS_DEFAULT constant.

bpo-31834 [https://bugs.python.org/issue?@action=redirect&bpo=31834]: Use optimized code for BLAKE2 only with SSSE3+. The pure SSE2 implementation is slower than the pure C reference implementation.

bpo-28292 [https://bugs.python.org/issue?@action=redirect&bpo=28292]: Calendar.itermonthdates() will now consistently raise an exception when a date falls outside of the 0001-01-01 through 9999-12-31 range. To support applications that cannot tolerate such exceptions, the new methods itermonthdays3() and itermonthdays4() are added. The new methods return tuples and are not restricted by the range supported by datetime.date.

bpo-28564 [https://bugs.python.org/issue?@action=redirect&bpo=28564]: The shutil.rmtree() function has been sped up to 20–40%. This was done using the os.scandir() function.

bpo-28416 [https://bugs.python.org/issue?@action=redirect&bpo=28416]: Instances of pickle.Pickler subclass with the persistent_id() method and pickle.Unpickler subclass with the persistent_load() method no longer create reference cycles.

bpo-31653 [https://bugs.python.org/issue?@action=redirect&bpo=31653]: Don’t release the GIL if we can acquire a multiprocessing semaphore immediately.

bpo-28326 [https://bugs.python.org/issue?@action=redirect&bpo=28326]: Fix multiprocessing.Process when stdout and/or stderr is closed or None.

bpo-20825 [https://bugs.python.org/issue?@action=redirect&bpo=20825]: Add subnet_of and superset_of containment tests to ipaddress.IPv6Network and ipaddress.IPv4Network. Patch by Michel Albert and Cheryl Sabella.

bpo-31827 [https://bugs.python.org/issue?@action=redirect&bpo=31827]: Remove the os.stat_float_times() function. It was introduced in Python 2.3 for backward compatibility with Python 2.2, and was deprecated since Python 3.1.

bpo-31756 [https://bugs.python.org/issue?@action=redirect&bpo=31756]: Add a subprocess.Popen(text=False) keyword argument to subprocess functions to be more explicit about when the library should attempt to decode outputs into text. Patch by Andrew Clegg.

bpo-31819 [https://bugs.python.org/issue?@action=redirect&bpo=31819]: Add AbstractEventLoop.sock_recv_into().

bpo-31457 [https://bugs.python.org/issue?@action=redirect&bpo=31457]: If nested log adapters are used, the inner process() methods are no longer omitted.

bpo-31457 [https://bugs.python.org/issue?@action=redirect&bpo=31457]: The manager property on LoggerAdapter objects is now properly settable.

bpo-31806 [https://bugs.python.org/issue?@action=redirect&bpo=31806]: Fix timeout rounding in time.sleep(), threading.Lock.acquire() and socket.socket.settimeout() to round correctly negative timeouts between -1.0 and 0.0. The functions now block waiting for events as expected. Previously, the call was incorrectly non-blocking. Patch by Pablo Galindo.

bpo-31803 [https://bugs.python.org/issue?@action=redirect&bpo=31803]: time.clock() and time.get_clock_info(‘clock’) now emit a DeprecationWarning warning.

bpo-31800 [https://bugs.python.org/issue?@action=redirect&bpo=31800]: Extended support for parsing UTC offsets. strptime ‘%z’ can now parse the output generated by datetime.isoformat, including seconds and microseconds.

bpo-28603 [https://bugs.python.org/issue?@action=redirect&bpo=28603]: traceback: Fix a TypeError that occurred during printing of exception tracebacks when either the current exception or an exception in its context/cause chain is unhashable. Patch by Zane Bitter.

bpo-30541 [https://bugs.python.org/issue?@action=redirect&bpo=30541]: Add new function to seal a mock and prevent the automatically creation of child mocks. Patch by Mario Corchero.

bpo-31784 [https://bugs.python.org/issue?@action=redirect&bpo=31784]: Implement the PEP 564 [https://www.python.org/dev/peps/pep-0564], add new 6 new functions with nanosecond resolution to the time module: clock_gettime_ns(), clock_settime_ns(), monotonic_ns(), perf_counter_ns(), process_time_ns(), time_ns().

bpo-30143 [https://bugs.python.org/issue?@action=redirect&bpo=30143]: 2to3 now generates a code that uses abstract collection classes from collections.abc rather than collections.

bpo-31770 [https://bugs.python.org/issue?@action=redirect&bpo=31770]: Prevent a crash when calling the __init__() method of a sqlite3.Cursor object more than once. Patch by Oren Milman.

bpo-31764 [https://bugs.python.org/issue?@action=redirect&bpo=31764]: Prevent a crash in sqlite3.Cursor.close() in case the Cursor object is uninitialized. Patch by Oren Milman.

bpo-31752 [https://bugs.python.org/issue?@action=redirect&bpo=31752]: Fix possible crash in timedelta constructor called with custom integers.

bpo-31620 [https://bugs.python.org/issue?@action=redirect&bpo=31620]: an empty asyncio.Queue now doesn’t leak memory when queue.get pollers timeout

bpo-31690 [https://bugs.python.org/issue?@action=redirect&bpo=31690]: Allow the flags re.ASCII, re.LOCALE, and re.UNICODE to be used as group flags for regular expressions.

bpo-30349 [https://bugs.python.org/issue?@action=redirect&bpo=30349]: FutureWarning is now emitted if a regular expression contains character set constructs that will change semantically in the future (nested sets and set operations).

bpo-31664 [https://bugs.python.org/issue?@action=redirect&bpo=31664]: Added support for the Blowfish hashing in the crypt module.

bpo-31632 [https://bugs.python.org/issue?@action=redirect&bpo=31632]: Fix method set_protocol() of class _SSLProtocolTransport in asyncio module. This method was previously modifying a wrong reference to the protocol.

bpo-15037 [https://bugs.python.org/issue?@action=redirect&bpo=15037]: Added a workaround for getkey() in curses for ncurses 5.7 and earlier.

bpo-31307 [https://bugs.python.org/issue?@action=redirect&bpo=31307]: Allow use of bytes objects for arguments to configparser.ConfigParser.read(). Patch by Vincent Michel.

bpo-31334 [https://bugs.python.org/issue?@action=redirect&bpo=31334]: Fix poll.poll([timeout]) in the select module for arbitrary negative timeouts on all OSes where it can only be a non-negative integer or -1. Patch by Riccardo Coccioli.

bpo-31310 [https://bugs.python.org/issue?@action=redirect&bpo=31310]: multiprocessing’s semaphore tracker should be launched again if crashed.

bpo-31308 [https://bugs.python.org/issue?@action=redirect&bpo=31308]: Make multiprocessing’s forkserver process immune to Ctrl-C and other user interruptions. If it crashes, restart it when necessary.

bpo-31245 [https://bugs.python.org/issue?@action=redirect&bpo=31245]: Added support for AF_UNIX socket in asyncio create_datagram_endpoint.

bpo-30553 [https://bugs.python.org/issue?@action=redirect&bpo=30553]: Add HTTP/2 status code 421 (Misdirected Request) to http.HTTPStatus. Patch by Vitor Pereira.

Documentation

bpo-32105 [https://bugs.python.org/issue?@action=redirect&bpo=32105]: Added asyncio.BaseEventLoop.connect_accepted_socket versionadded marker.

Tests

bpo-31380 [https://bugs.python.org/issue?@action=redirect&bpo=31380]: Skip test_httpservers test_undecodable_file on macOS: fails on APFS.

bpo-31705 [https://bugs.python.org/issue?@action=redirect&bpo=31705]: Skip test_socket.test_sha256() on Linux kernel older than 4.5. The test fails with ENOKEY on kernel 3.10 (on ppc64le). A fix was merged into the kernel 4.5.

bpo-32138 [https://bugs.python.org/issue?@action=redirect&bpo=32138]: Skip on Android test_faulthandler tests that raise SIGSEGV and remove the test.support.requires_android_level decorator.

bpo-32136 [https://bugs.python.org/issue?@action=redirect&bpo=32136]: The runtime embedding tests have been split out from Lib/test/test_capi.py into a new Lib/test/test_embed.py file.

bpo-28668 [https://bugs.python.org/issue?@action=redirect&bpo=28668]: test.support.requires_multiprocessing_queue is removed. Skip tests with test.support.import_module(‘multiprocessing.synchronize’) instead when the semaphore implementation is broken or missing.

bpo-32126 [https://bugs.python.org/issue?@action=redirect&bpo=32126]: Skip test_get_event_loop_new_process in test.test_asyncio.test_events when sem_open() is not functional.

bpo-31174 [https://bugs.python.org/issue?@action=redirect&bpo=31174]: Fix test_tools.test_unparse: DirectoryTestCase now stores the names sample to always test the same files. It prevents false alarms when hunting reference leaks.

Build

bpo-28538 [https://bugs.python.org/issue?@action=redirect&bpo=28538]: Revert the previous changes, the if_nameindex structure is defined by Unified Headers.

bpo-28762 [https://bugs.python.org/issue?@action=redirect&bpo=28762]: Revert the last commit, the F_LOCK macro is defined by Android Unified Headers.

bpo-29040 [https://bugs.python.org/issue?@action=redirect&bpo=29040]: Support building Android with Unified Headers. The first NDK release to support Unified Headers is android-ndk-r14.

bpo-32059 [https://bugs.python.org/issue?@action=redirect&bpo=32059]: detect_modules() in setup.py now also searches the sysroot paths when cross-compiling.

bpo-31957 [https://bugs.python.org/issue?@action=redirect&bpo=31957]: Fixes Windows SDK version detection when building for Windows.

bpo-31609 [https://bugs.python.org/issue?@action=redirect&bpo=31609]: Fixes quotes in PCbuild/clean.bat

bpo-31934 [https://bugs.python.org/issue?@action=redirect&bpo=31934]: Abort the build when building out of a not clean source tree.

bpo-31926 [https://bugs.python.org/issue?@action=redirect&bpo=31926]: Fixed Argument Clinic sometimes causing compilation errors when there was more than one function and/or method in a .c file with the same name.

bpo-28791 [https://bugs.python.org/issue?@action=redirect&bpo=28791]: Update Windows builds to use SQLite 3.21.0.

bpo-28791 [https://bugs.python.org/issue?@action=redirect&bpo=28791]: Update OS X installer to use SQLite 3.21.0.

bpo-28643 [https://bugs.python.org/issue?@action=redirect&bpo=28643]: Record profile-opt build progress with stamp files.

bpo-31866 [https://bugs.python.org/issue?@action=redirect&bpo=31866]: Finish removing support for AtheOS.

Windows

bpo-1102 [https://bugs.python.org/issue?@action=redirect&bpo=1102]: Return None when View.Fetch() returns ERROR_NO_MORE_ITEMS instead of raising MSIError.

Initial patch by Anthony Tuininga.

bpo-31944 [https://bugs.python.org/issue?@action=redirect&bpo=31944]: Fixes Modify button in Apps and Features dialog.

bpo-20486 [https://bugs.python.org/issue?@action=redirect&bpo=20486]: Implement the Database.Close() method to help closing MSI database objects.

bpo-31857 [https://bugs.python.org/issue?@action=redirect&bpo=31857]: Make the behavior of USE_STACKCHECK deterministic in a multi-threaded environment.

macOS

bpo-31392 [https://bugs.python.org/issue?@action=redirect&bpo=31392]: Update macOS installer to use OpenSSL 1.0.2m

IDLE

bpo-32207 [https://bugs.python.org/issue?@action=redirect&bpo=32207]: Improve tk event exception tracebacks in IDLE. When tk event handling is driven by IDLE’s run loop, a confusing and distracting queue.EMPTY traceback context is no longer added to tk event exception tracebacks. The traceback is now the same as when event handling is driven by user code. Patch based on a suggestion by Serhiy Storchaka.

bpo-32164 [https://bugs.python.org/issue?@action=redirect&bpo=32164]: Delete unused file idlelib/tabbedpages.py. Use of TabbedPageSet in configdialog was replaced by ttk.Notebook.

bpo-32100 [https://bugs.python.org/issue?@action=redirect&bpo=32100]: IDLE: Fix old and new bugs in pathbrowser; improve tests. Patch mostly by Cheryl Sabella.

bpo-31858 [https://bugs.python.org/issue?@action=redirect&bpo=31858]: IDLE – Restrict shell prompt manipulation to the shell. Editor and output windows only see an empty last prompt line. This simplifies the code and fixes a minor bug when newline is inserted. Sys.ps1, if present, is read on Shell start-up, but is not set or changed.

bpo-31860 [https://bugs.python.org/issue?@action=redirect&bpo=31860]: The font sample in the IDLE configuration dialog is now editable. Changes persist while IDLE remains open

bpo-31836 [https://bugs.python.org/issue?@action=redirect&bpo=31836]: Test_code_module now passes if run after test_idle, which sets ps1.

The code module uses sys.ps1 if present or sets it to ‘>>> ‘ if not. Test_code_module now properly tests both behaviors. Ditto for ps2.

bpo-28603 [https://bugs.python.org/issue?@action=redirect&bpo=28603]: Fix a TypeError that caused a shell restart when printing a traceback that includes an exception that is unhashable. Patch by Zane Bitter.

bpo-13802 [https://bugs.python.org/issue?@action=redirect&bpo=13802]: Use non-Latin characters in the IDLE’s Font settings sample. Even if one selects a font that defines a limited subset of the unicode Basic Multilingual Plane, tcl/tk will use other fonts that define a character. The expanded example give users of non-Latin characters a better idea of what they might see in IDLE’s shell and editors.

To make room for the expanded sample, frames on the Font tab are re-arranged. The Font/Tabs help explains a bit about the additions.

Tools/Demos

bpo-32159 [https://bugs.python.org/issue?@action=redirect&bpo=32159]: Remove CVS and Subversion tools: remove svneol.py and treesync.py scripts. CPython migrated from CVS to Subversion, to Mercurial, and then to Git. CVS and Subversion are no longer used to develop CPython.

bpo-30722 [https://bugs.python.org/issue?@action=redirect&bpo=30722]: Make redemo work with Python 3.6 and newer versions.

Also, remove the LOCALE option since it doesn’t work with string patterns in Python 3.

Patch by Christoph Sarnowski.

C API

bpo-20891 [https://bugs.python.org/issue?@action=redirect&bpo=20891]: Fix PyGILState_Ensure(). When PyGILState_Ensure() is called in a non-Python thread before PyEval_InitThreads(), only call PyEval_InitThreads() after calling PyThreadState_New() to fix a crash.

bpo-32125 [https://bugs.python.org/issue?@action=redirect&bpo=32125]: The Py_UseClassExceptionsFlag flag has been removed. It was deprecated and wasn’t used anymore since Python 2.0.

bpo-25612 [https://bugs.python.org/issue?@action=redirect&bpo=25612]: Move the current exception state from the frame object to the co-routine. This simplifies the interpreter and fixes a couple of obscure bugs caused by having swap exception state when entering or exiting a generator.

bpo-23699 [https://bugs.python.org/issue?@action=redirect&bpo=23699]: Add Py_RETURN_RICHCOMPARE macro to reduce boilerplate code in rich comparison functions.

bpo-30697 [https://bugs.python.org/issue?@action=redirect&bpo=30697]: The PyExc_RecursionErrorInst singleton is removed and PyErr_NormalizeException() does not use it anymore. This singleton is persistent and its members being never cleared may cause a segfault during finalization of the interpreter. See also bpo-22898 [https://bugs.python.org/issue?@action=redirect&bpo=22898].

Python 3.7.0 alpha 2

Release date: 2017-10-16

Core and Builtins

bpo-31558 [https://bugs.python.org/issue?@action=redirect&bpo=31558]: gc.freeze() is a new API that allows for moving all objects currently tracked by the garbage collector to a permanent generation, effectively removing them from future collection events. This can be used to protect those objects from having their PyGC_Head mutated. In effect, this enables great copy-on-write stability at fork().

bpo-31642 [https://bugs.python.org/issue?@action=redirect&bpo=31642]: Restored blocking “from package import module” by setting sys.modules[“package.module”] to None.

bpo-31708 [https://bugs.python.org/issue?@action=redirect&bpo=31708]: Allow use of asynchronous generator expressions in synchronous functions.

bpo-31709 [https://bugs.python.org/issue?@action=redirect&bpo=31709]: Drop support of asynchronous __aiter__.

bpo-30404 [https://bugs.python.org/issue?@action=redirect&bpo=30404]: The -u option now makes the stdout and stderr streams unbuffered rather than line-buffered.

bpo-31619 [https://bugs.python.org/issue?@action=redirect&bpo=31619]: Fixed a ValueError when convert a string with large number of underscores to integer with binary base.

bpo-31602 [https://bugs.python.org/issue?@action=redirect&bpo=31602]: Fix an assertion failure in zipimporter.get_source() in case of a bad zlib.decompress(). Patch by Oren Milman.

bpo-31592 [https://bugs.python.org/issue?@action=redirect&bpo=31592]: Fixed an assertion failure in Python parser in case of a bad unicodedata.normalize(). Patch by Oren Milman.

bpo-31588 [https://bugs.python.org/issue?@action=redirect&bpo=31588]: Raise a TypeError with a helpful error message when class creation fails due to a metaclass with a bad __prepare__() method. Patch by Oren Milman.

bpo-31574 [https://bugs.python.org/issue?@action=redirect&bpo=31574]: Importlib was instrumented with two dtrace probes to profile import timing.

bpo-31566 [https://bugs.python.org/issue?@action=redirect&bpo=31566]: Fix an assertion failure in _warnings.warn() in case of a bad __name__ global. Patch by Oren Milman.

bpo-31506 [https://bugs.python.org/issue?@action=redirect&bpo=31506]: Improved the error message logic for object.__new__ and object.__init__.

bpo-31505 [https://bugs.python.org/issue?@action=redirect&bpo=31505]: Fix an assertion failure in json, in case _json.make_encoder() received a bad encoder() argument. Patch by Oren Milman.

bpo-31492 [https://bugs.python.org/issue?@action=redirect&bpo=31492]: Fix assertion failures in case of failing to import from a module with a bad __name__ attribute, and in case of failing to access an attribute of such a module. Patch by Oren Milman.

bpo-31478 [https://bugs.python.org/issue?@action=redirect&bpo=31478]: Fix an assertion failure in _random.Random.seed() in case the argument has a bad __abs__() method. Patch by Oren Milman.

bpo-31336 [https://bugs.python.org/issue?@action=redirect&bpo=31336]: Speed up class creation by 10-20% by reducing the overhead in the necessary special method lookups. Patch by Stefan Behnel.

bpo-31415 [https://bugs.python.org/issue?@action=redirect&bpo=31415]: Add -X importtime option to show how long each import takes. It can be used to optimize application’s startup time. Support the PYTHONPROFILEIMPORTTIME as an equivalent way to enable this.

bpo-31410 [https://bugs.python.org/issue?@action=redirect&bpo=31410]: Optimized calling wrapper and classmethod descriptors.

bpo-31353 [https://bugs.python.org/issue?@action=redirect&bpo=31353]: PEP 553 [https://www.python.org/dev/peps/pep-0553] - Add a new built-in called breakpoint() which calls sys.breakpointhook(). By default this imports pdb and calls pdb.set_trace(), but users may override sys.breakpointhook() to call whatever debugger they want. The original value of the hook is saved in sys.__breakpointhook__.

bpo-17852 [https://bugs.python.org/issue?@action=redirect&bpo=17852]: Maintain a list of open buffered files, flush them before exiting the interpreter. Based on a patch from Armin Rigo.

bpo-31315 [https://bugs.python.org/issue?@action=redirect&bpo=31315]: Fix an assertion failure in imp.create_dynamic(), when spec.name is not a string. Patch by Oren Milman.

bpo-31311 [https://bugs.python.org/issue?@action=redirect&bpo=31311]: Fix a crash in the __setstate__() method of ctypes._CData, in case of a bad __dict__. Patch by Oren Milman.

bpo-31293 [https://bugs.python.org/issue?@action=redirect&bpo=31293]: Fix crashes in true division and multiplication of a timedelta object by a float with a bad as_integer_ratio() method. Patch by Oren Milman.

bpo-31285 [https://bugs.python.org/issue?@action=redirect&bpo=31285]: Fix an assertion failure in warnings.warn_explicit, when the return value of the received loader’s get_source() has a bad splitlines() method. Patch by Oren Milman.

bpo-30406 [https://bugs.python.org/issue?@action=redirect&bpo=30406]: Make async and await proper keywords, as specified in PEP 492.

Library

bpo-30058 [https://bugs.python.org/issue?@action=redirect&bpo=30058]: Fixed buffer overflow in select.kqueue.control().

bpo-31672 [https://bugs.python.org/issue?@action=redirect&bpo=31672]: idpattern in string.Template matched some non-ASCII characters. Now it uses -i regular expression local flag to avoid non-ASCII characters.

bpo-31701 [https://bugs.python.org/issue?@action=redirect&bpo=31701]: On Windows, faulthandler.enable() now ignores MSC and COM exceptions.

bpo-31728 [https://bugs.python.org/issue?@action=redirect&bpo=31728]: Prevent crashes in _elementtree due to unsafe cleanup of Element.text and Element.tail. Patch by Oren Milman.

bpo-31671 [https://bugs.python.org/issue?@action=redirect&bpo=31671]: Now re.compile() converts passed RegexFlag to normal int object before compiling. bm_regex_compile benchmark shows 14% performance improvements.

bpo-30397 [https://bugs.python.org/issue?@action=redirect&bpo=30397]: The types of compiled regular objects and match objects are now exposed as re.Pattern and re.Match. This adds information in pydoc output for the re module.

bpo-31675 [https://bugs.python.org/issue?@action=redirect&bpo=31675]: Fixed memory leaks in Tkinter’s methods splitlist() and split() when pass a string larger than 2 GiB.

bpo-31673 [https://bugs.python.org/issue?@action=redirect&bpo=31673]: Fixed typo in the name of Tkinter’s method adderrorinfo().

bpo-31648 [https://bugs.python.org/issue?@action=redirect&bpo=31648]: Improvements to path predicates in ElementTree:

Allow whitespace around predicate parts, i.e. “[a = ‘text’]” instead of requiring the less readable “[a=’text’]”.

Add support for text comparison of the current node, like “[.=’text’]”.

Patch by Stefan Behnel.

bpo-30806 [https://bugs.python.org/issue?@action=redirect&bpo=30806]: Fix the string representation of a netrc object.

bpo-31638 [https://bugs.python.org/issue?@action=redirect&bpo=31638]: Add optional argument compressed to zipapp.create_archive, and add option --compress to the command line interface of zipapp.

bpo-25351 [https://bugs.python.org/issue?@action=redirect&bpo=25351]: Avoid venv activate failures with undefined variables

bpo-20519 [https://bugs.python.org/issue?@action=redirect&bpo=20519]: Avoid ctypes use (if possible) and improve import time for uuid.

bpo-28293 [https://bugs.python.org/issue?@action=redirect&bpo=28293]: The regular expression cache is no longer completely dumped when it is full.

bpo-31596 [https://bugs.python.org/issue?@action=redirect&bpo=31596]: Added pthread_getcpuclockid() to the time module

bpo-27494 [https://bugs.python.org/issue?@action=redirect&bpo=27494]: Make 2to3 accept a trailing comma in generator expressions. For example, set(x for x in [],) is now allowed.

bpo-30347 [https://bugs.python.org/issue?@action=redirect&bpo=30347]: Stop crashes when concurrently iterate over itertools.groupby() iterators.

bpo-30346 [https://bugs.python.org/issue?@action=redirect&bpo=30346]: An iterator produced by itertools.groupby() iterator now becomes exhausted after advancing the groupby iterator.

bpo-31556 [https://bugs.python.org/issue?@action=redirect&bpo=31556]: Cancel asyncio.wait_for future faster if timeout <= 0

bpo-31540 [https://bugs.python.org/issue?@action=redirect&bpo=31540]: Allow passing a context object in concurrent.futures.ProcessPoolExecutor constructor. Also, free job resources in concurrent.futures.ProcessPoolExecutor earlier to improve memory usage when a worker waits for new jobs.

bpo-31516 [https://bugs.python.org/issue?@action=redirect&bpo=31516]: threading.current_thread() should not return a dummy thread at shutdown.

bpo-31525 [https://bugs.python.org/issue?@action=redirect&bpo=31525]: In the sqlite module, require the sqlite3_prepare_v2 API. Thus, the sqlite module now requires sqlite version at least 3.3.9.

bpo-26510 [https://bugs.python.org/issue?@action=redirect&bpo=26510]: argparse subparsers are now required by default. This matches behaviour in Python 2. For optional subparsers, use the new parameter add_subparsers(required=False). Patch by Anthony Sottile. (As of 3.7.0rc1, the default was changed to not required as had been the case since Python 3.3.)

bpo-27541 [https://bugs.python.org/issue?@action=redirect&bpo=27541]: Reprs of subclasses of some collection and iterator classes (bytearray, array.array, collections.deque, collections.defaultdict, itertools.count, itertools.repeat) now contain actual type name insteads of hardcoded name of the base class.

bpo-31351 [https://bugs.python.org/issue?@action=redirect&bpo=31351]: python -m ensurepip now exits with non-zero exit code if pip bootstrapping has failed.

bpo-31389 [https://bugs.python.org/issue?@action=redirect&bpo=31389]: pdb.set_trace() now takes an optional keyword-only argument header. If given, this is printed to the console just before debugging begins.

Documentation

bpo-31537 [https://bugs.python.org/issue?@action=redirect&bpo=31537]: Fix incorrect usage of get_history_length in readline documentation example code. Patch by Brad Smith.

bpo-30085 [https://bugs.python.org/issue?@action=redirect&bpo=30085]: The operator functions without double underscores are preferred for clarity. The one with underscores are only kept for back-compatibility.

Build

bpo-31696 [https://bugs.python.org/issue?@action=redirect&bpo=31696]: Improve compiler version information in sys.version when Python is built with Clang.

bpo-31625 [https://bugs.python.org/issue?@action=redirect&bpo=31625]: Stop using ranlib on static libraries. Instead, we assume ar supports the ‘s’ flag.

bpo-31624 [https://bugs.python.org/issue?@action=redirect&bpo=31624]: Remove support for BSD/OS.

bpo-22140 [https://bugs.python.org/issue?@action=redirect&bpo=22140]: Prevent double substitution of prefix in python-config.sh.

bpo-31569 [https://bugs.python.org/issue?@action=redirect&bpo=31569]: Correct PCBuild/ case to PCbuild/ in build scripts and documentation.

bpo-31536 [https://bugs.python.org/issue?@action=redirect&bpo=31536]: Avoid wholesale rebuild after make regen-all if nothing changed.

IDLE

bpo-31460 [https://bugs.python.org/issue?@action=redirect&bpo=31460]: Simplify the API of IDLE’s Module Browser.

Passing a widget instead of an flist with a root widget opens the option of creating a browser frame that is only part of a window. Passing a full file name instead of pieces assumed to come from a .py file opens the possibility of browsing python files that do not end in .py.

bpo-31649 [https://bugs.python.org/issue?@action=redirect&bpo=31649]: IDLE - Make _htest, _utest parameters keyword only.

bpo-31559 [https://bugs.python.org/issue?@action=redirect&bpo=31559]: Remove test order dependence in idle_test.test_browser.

bpo-31459 [https://bugs.python.org/issue?@action=redirect&bpo=31459]: Rename IDLE’s module browser from Class Browser to Module Browser. The original module-level class and method browser became a module browser, with the addition of module-level functions, years ago. Nested classes and functions were added yesterday. For back-compatibility, the virtual event <<open-class-browser>>, which appears on the Keys tab of the Settings dialog, is not changed. Patch by Cheryl Sabella.

bpo-31500 [https://bugs.python.org/issue?@action=redirect&bpo=31500]: Default fonts now are scaled on HiDPI displays.

bpo-1612262 [https://bugs.python.org/issue?@action=redirect&bpo=1612262]: IDLE module browser now shows nested classes and functions. Original patches for code and tests by Guilherme Polo and Cheryl Sabella, respectively.

C API

bpo-28280 [https://bugs.python.org/issue?@action=redirect&bpo=28280]: Make PyMapping_Keys(), PyMapping_Values() and PyMapping_Items() always return a list (rather than a list or a tuple). Patch by Oren Milman.

bpo-31532 [https://bugs.python.org/issue?@action=redirect&bpo=31532]: Fix memory corruption due to allocator mix in getpath.c between Py_GetPath() and Py_SetPath()

bpo-25658 [https://bugs.python.org/issue?@action=redirect&bpo=25658]: Implement PEP 539 for Thread Specific Storage (TSS) API: it is a new Thread Local Storage (TLS) API to CPython which would supersede use of the existing TLS API within the CPython interpreter, while deprecating the existing API. PEP written by Erik M. Bray, patch by Masayuki Yamamoto.

Python 3.7.0 alpha 1

Release date: 2017-09-19

Security

bpo-29781 [https://bugs.python.org/issue?@action=redirect&bpo=29781]: SSLObject.version() now correctly returns None when handshake over BIO has not been performed yet.

bpo-29505 [https://bugs.python.org/issue?@action=redirect&bpo=29505]: Add fuzz tests for float(str), int(str), unicode(str); for oss-fuzz.

bpo-30947 [https://bugs.python.org/issue?@action=redirect&bpo=30947]: Upgrade libexpat embedded copy from version 2.2.1 to 2.2.3 to get security fixes.

bpo-30730 [https://bugs.python.org/issue?@action=redirect&bpo=30730]: Prevent environment variables injection in subprocess on Windows. Prevent passing other environment variables and command arguments.

bpo-30694 [https://bugs.python.org/issue?@action=redirect&bpo=30694]: Upgrade expat copy from 2.2.0 to 2.2.1 to get fixes of multiple security vulnerabilities including: CVE-2017-9233 (External entity infinite loop DoS), CVE-2016-9063 (Integer overflow, re-fix), CVE-2016-0718 (Fix regression bugs from 2.2.0’s fix to CVE-2016-0718) and CVE-2012-0876 (Counter hash flooding with SipHash). Note: the CVE-2016-5300 (Use os-specific entropy sources like getrandom) doesn’t impact Python, since Python already gets entropy from the OS to set the expat secret using XML_SetHashSalt().

bpo-30500 [https://bugs.python.org/issue?@action=redirect&bpo=30500]: Fix urllib.parse.splithost() to correctly parse fragments. For example, splithost('//127.0.0.1#@evil.com/') now correctly returns the 127.0.0.1 host, instead of treating @evil.com as the host in an authentication (login@host).

bpo-29591 [https://bugs.python.org/issue?@action=redirect&bpo=29591]: Update expat copy from 2.1.1 to 2.2.0 to get fixes of CVE-2016-0718 and CVE-2016-4472. See https://sourceforge.net/p/expat/bugs/537/ for more information.

Core and Builtins

bpo-31490 [https://bugs.python.org/issue?@action=redirect&bpo=31490]: Fix an assertion failure in ctypes class definition, in case the class has an attribute whose name is specified in _anonymous_ but not in _fields_. Patch by Oren Milman.

bpo-31471 [https://bugs.python.org/issue?@action=redirect&bpo=31471]: Fix an assertion failure in subprocess.Popen() on Windows, in case the env argument has a bad keys() method. Patch by Oren Milman.

bpo-31418 [https://bugs.python.org/issue?@action=redirect&bpo=31418]: Fix an assertion failure in PyErr_WriteUnraisable() in case of an exception with a bad __module__ attribute. Patch by Oren Milman.

bpo-31416 [https://bugs.python.org/issue?@action=redirect&bpo=31416]: Fix assertion failures in case of a bad warnings.filters or warnings.defaultaction. Patch by Oren Milman.

bpo-28411 [https://bugs.python.org/issue?@action=redirect&bpo=28411]: Change direct usage of PyInterpreterState.modules to PyImport_GetModuleDict(). Also introduce more uniformity in other code that deals with sys.modules. This helps reduce complications when working on sys.modules.

bpo-28411 [https://bugs.python.org/issue?@action=redirect&bpo=28411]: Switch to the abstract API when dealing with PyInterpreterState.modules. This allows later support for all dict subclasses and other Mapping implementations. Also add a PyImport_GetModule() function to reduce a bunch of duplicated code.

bpo-31411 [https://bugs.python.org/issue?@action=redirect&bpo=31411]: Raise a TypeError instead of SystemError in case warnings.onceregistry is not a dictionary. Patch by Oren Milman.

bpo-31344 [https://bugs.python.org/issue?@action=redirect&bpo=31344]: For finer control of tracing behaviour when testing the interpreter, two new frame attributes have been added to control the emission of particular trace events: f_trace_lines (True by default) to turn off per-line trace events; and f_trace_opcodes (False by default) to turn on per-opcode trace events.

bpo-31373 [https://bugs.python.org/issue?@action=redirect&bpo=31373]: Fix several possible instances of undefined behavior due to floating-point demotions.

bpo-30465 [https://bugs.python.org/issue?@action=redirect&bpo=30465]: Location information (lineno and col_offset) in f-strings is now (mostly) correct. This fixes tools like flake8 from showing warnings on the wrong line (typically the first line of the file).

bpo-30860 [https://bugs.python.org/issue?@action=redirect&bpo=30860]: Consolidate CPython’s global runtime state under a single struct. This improves discoverability of the runtime state.

bpo-31347 [https://bugs.python.org/issue?@action=redirect&bpo=31347]: Fix possible undefined behavior in _PyObject_FastCall_Prepend.

bpo-31343 [https://bugs.python.org/issue?@action=redirect&bpo=31343]: Include sys/sysmacros.h for major(), minor(), and makedev(). GNU C libray plans to remove the functions from sys/types.h.

bpo-31291 [https://bugs.python.org/issue?@action=redirect&bpo=31291]: Fix an assertion failure in zipimport.zipimporter.get_data on Windows, when the return value of pathname.replace('/','\\') isn’t a string. Patch by Oren Milman.

bpo-31271 [https://bugs.python.org/issue?@action=redirect&bpo=31271]: Fix an assertion failure in the write() method of io.TextIOWrapper, when the encoder doesn’t return a bytes object. Patch by Oren Milman.

bpo-31243 [https://bugs.python.org/issue?@action=redirect&bpo=31243]: Fix a crash in some methods of io.TextIOWrapper, when the decoder’s state is invalid. Patch by Oren Milman.

bpo-30721 [https://bugs.python.org/issue?@action=redirect&bpo=30721]: print now shows correct usage hint for using Python 2 redirection syntax. Patch by Sanyam Khurana.

bpo-31070 [https://bugs.python.org/issue?@action=redirect&bpo=31070]: Fix a race condition in importlib _get_module_lock().

bpo-30747 [https://bugs.python.org/issue?@action=redirect&bpo=30747]: Add a non-dummy implementation of _Py_atomic_store and _Py_atomic_load on MSVC.

bpo-31095 [https://bugs.python.org/issue?@action=redirect&bpo=31095]: Fix potential crash during GC caused by tp_dealloc which doesn’t call PyObject_GC_UnTrack().

bpo-31071 [https://bugs.python.org/issue?@action=redirect&bpo=31071]: Avoid masking original TypeError in call with * unpacking when other arguments are passed.

bpo-30978 [https://bugs.python.org/issue?@action=redirect&bpo=30978]: str.format_map() now passes key lookup exceptions through. Previously any exception was replaced with a KeyError exception.

bpo-30808 [https://bugs.python.org/issue?@action=redirect&bpo=30808]: Use _Py_atomic API for concurrency-sensitive signal state.

bpo-30876 [https://bugs.python.org/issue?@action=redirect&bpo=30876]: Relative import from unloaded package now reimports the package instead of failing with SystemError. Relative import from non-package now fails with ImportError rather than SystemError.

bpo-30703 [https://bugs.python.org/issue?@action=redirect&bpo=30703]: Improve signal delivery.

Avoid using Py_AddPendingCall from signal handler, to avoid calling signal-unsafe functions. The tests I’m adding here fail without the rest of the patch, on Linux and OS X. This means our signal delivery logic had defects (some signals could be lost).

bpo-30765 [https://bugs.python.org/issue?@action=redirect&bpo=30765]: Avoid blocking in pthread_mutex_lock() when PyThread_acquire_lock() is asked not to block.

bpo-31161 [https://bugs.python.org/issue?@action=redirect&bpo=31161]: Make sure the ‘Missing parentheses’ syntax error message is only applied to SyntaxError, not to subclasses. Patch by Martijn Pieters.

bpo-30814 [https://bugs.python.org/issue?@action=redirect&bpo=30814]: Fixed a race condition when import a submodule from a package.

bpo-30736 [https://bugs.python.org/issue?@action=redirect&bpo=30736]: The internal unicodedata database has been upgraded to Unicode 10.0.

bpo-30604 [https://bugs.python.org/issue?@action=redirect&bpo=30604]: Move co_extra_freefuncs from per-thread to per-interpreter to avoid crashes.

bpo-30597 [https://bugs.python.org/issue?@action=redirect&bpo=30597]: print now shows expected input in custom error message when used as a Python 2 statement. Patch by Sanyam Khurana.

bpo-30682 [https://bugs.python.org/issue?@action=redirect&bpo=30682]: Removed a too-strict assertion that failed for certain f-strings, such as eval(“f’\n’”) and eval(“f’\r’”).

bpo-30501 [https://bugs.python.org/issue?@action=redirect&bpo=30501]: The compiler now produces more optimal code for complex condition expressions in the “if”, “while” and “assert” statement, the “if” expression, and generator expressions and comprehensions.

bpo-28180 [https://bugs.python.org/issue?@action=redirect&bpo=28180]: Implement PEP 538 (legacy C locale coercion). This means that when a suitable coercion target locale is available, both the core interpreter and locale-aware C extensions will assume the use of UTF-8 as the default text encoding, rather than ASCII.

bpo-30486 [https://bugs.python.org/issue?@action=redirect&bpo=30486]: Allows setting cell values for __closure__. Patch by Lisa Roach.

bpo-30537 [https://bugs.python.org/issue?@action=redirect&bpo=30537]: itertools.islice now accepts integer-like objects (having an __index__ method) as start, stop, and slice arguments

bpo-25324 [https://bugs.python.org/issue?@action=redirect&bpo=25324]: Tokens needed for parsing in Python moved to C. COMMENT, NL and ENCODING. This way the tokens and tok_names in the token module don’t get changed when you import the tokenize module.

bpo-29104 [https://bugs.python.org/issue?@action=redirect&bpo=29104]: Fixed parsing backslashes in f-strings.

bpo-27945 [https://bugs.python.org/issue?@action=redirect&bpo=27945]: Fixed various segfaults with dict when input collections are mutated during searching, inserting or comparing. Based on patches by Duane Griffin and Tim Mitchell.

bpo-25794 [https://bugs.python.org/issue?@action=redirect&bpo=25794]: Fixed type.__setattr__() and type.__delattr__() for non-interned attribute names. Based on patch by Eryk Sun.

bpo-30039 [https://bugs.python.org/issue?@action=redirect&bpo=30039]: If a KeyboardInterrupt happens when the interpreter is in the middle of resuming a chain of nested ‘yield from’ or ‘await’ calls, it’s now correctly delivered to the innermost frame.

bpo-28974 [https://bugs.python.org/issue?@action=redirect&bpo=28974]: object.__format__(x, '') is now equivalent to str(x) rather than format(str(self), '').

bpo-30024 [https://bugs.python.org/issue?@action=redirect&bpo=30024]: Circular imports involving absolute imports with binding a submodule to a name are now supported.

bpo-12414 [https://bugs.python.org/issue?@action=redirect&bpo=12414]: sys.getsizeof() on a code object now returns the sizes which includes the code struct and sizes of objects which it references. Patch by Dong-hee Na.

bpo-29839 [https://bugs.python.org/issue?@action=redirect&bpo=29839]: len() now raises ValueError rather than OverflowError if __len__() returned a large negative integer.

bpo-11913 [https://bugs.python.org/issue?@action=redirect&bpo=11913]: README.rst is now included in the list of distutils standard READMEs and therefore included in source distributions.

bpo-29914 [https://bugs.python.org/issue?@action=redirect&bpo=29914]: Fixed default implementations of __reduce__ and __reduce_ex__(). object.__reduce__() no longer takes arguments, object.__reduce_ex__() now requires one argument.

bpo-29949 [https://bugs.python.org/issue?@action=redirect&bpo=29949]: Fix memory usage regression of set and frozenset object.

bpo-29935 [https://bugs.python.org/issue?@action=redirect&bpo=29935]: Fixed error messages in the index() method of tuple, list and deque when pass indices of wrong type.

bpo-29816 [https://bugs.python.org/issue?@action=redirect&bpo=29816]: Shift operation now has less opportunity to raise OverflowError. ValueError always is raised rather than OverflowError for negative counts. Shifting zero with non-negative count always returns zero.

bpo-24821 [https://bugs.python.org/issue?@action=redirect&bpo=24821]: Fixed the slowing down to 25 times in the searching of some unlucky Unicode characters.

bpo-29102 [https://bugs.python.org/issue?@action=redirect&bpo=29102]: Add a unique ID to PyInterpreterState. This makes it easier to identify each subinterpreter.

bpo-29894 [https://bugs.python.org/issue?@action=redirect&bpo=29894]: The deprecation warning is emitted if __complex__ returns an instance of a strict subclass of complex. In a future versions of Python this can be an error.

bpo-29859 [https://bugs.python.org/issue?@action=redirect&bpo=29859]: Show correct error messages when any of the pthread_* calls in thread_pthread.h fails.

bpo-29849 [https://bugs.python.org/issue?@action=redirect&bpo=29849]: Fix a memory leak when an ImportError is raised during from import.

bpo-28856 [https://bugs.python.org/issue?@action=redirect&bpo=28856]: Fix an oversight that %b format for bytes should support objects follow the buffer protocol.

bpo-29723 [https://bugs.python.org/issue?@action=redirect&bpo=29723]: The sys.path[0] initialization change for bpo-29139 [https://bugs.python.org/issue?@action=redirect&bpo=29139] caused a regression by revealing an inconsistency in how sys.path is initialized when executing __main__ from a zipfile, directory, or other import location. The interpreter now consistently avoids ever adding the import location’s parent directory to sys.path, and ensures no other sys.path entries are inadvertently modified when inserting the import location named on the command line.

bpo-29568 [https://bugs.python.org/issue?@action=redirect&bpo=29568]: Escaped percent “%%” in the format string for classic string formatting no longer allows any characters between two percents.

bpo-29714 [https://bugs.python.org/issue?@action=redirect&bpo=29714]: Fix a regression that bytes format may fail when containing zero bytes inside.

bpo-29695 [https://bugs.python.org/issue?@action=redirect&bpo=29695]: bool(), float(), list() and tuple() no longer take keyword arguments. The first argument of int() can now be passes only as positional argument.

bpo-28893 [https://bugs.python.org/issue?@action=redirect&bpo=28893]: Set correct __cause__ for errors about invalid awaitables returned from __aiter__ and __anext__.

bpo-28876 [https://bugs.python.org/issue?@action=redirect&bpo=28876]: bool(range) works even if len(range) raises OverflowError.

bpo-29683 [https://bugs.python.org/issue?@action=redirect&bpo=29683]: Fixes to memory allocation in _PyCode_SetExtra. Patch by Brian Coleman.

bpo-29684 [https://bugs.python.org/issue?@action=redirect&bpo=29684]: Fix minor regression of PyEval_CallObjectWithKeywords. It should raise TypeError when kwargs is not a dict. But it might cause segv when args=NULL and kwargs is not a dict.

bpo-28598 [https://bugs.python.org/issue?@action=redirect&bpo=28598]: Support __rmod__ for subclasses of str being called before str.__mod__. Patch by Martijn Pieters.

bpo-29607 [https://bugs.python.org/issue?@action=redirect&bpo=29607]: Fix stack_effect computation for CALL_FUNCTION_EX. Patch by Matthieu Dartiailh.

bpo-29602 [https://bugs.python.org/issue?@action=redirect&bpo=29602]: Fix incorrect handling of signed zeros in complex constructor for complex subclasses and for inputs having a __complex__ method. Patch by Serhiy Storchaka.

bpo-29347 [https://bugs.python.org/issue?@action=redirect&bpo=29347]: Fixed possibly dereferencing undefined pointers when creating weakref objects.

bpo-29463 [https://bugs.python.org/issue?@action=redirect&bpo=29463]: Add docstring field to Module, ClassDef, FunctionDef, and AsyncFunctionDef ast nodes. docstring is not first stmt in their body anymore. It affects co_firstlineno and co_lnotab of code object for module and class. (Reverted in bpo-32911 [https://bugs.python.org/issue?@action=redirect&bpo=32911].)

bpo-29438 [https://bugs.python.org/issue?@action=redirect&bpo=29438]: Fixed use-after-free problem in key sharing dict.

bpo-29546 [https://bugs.python.org/issue?@action=redirect&bpo=29546]: Set the ‘path’ and ‘name’ attribute on ImportError for from ... import ....

bpo-29546 [https://bugs.python.org/issue?@action=redirect&bpo=29546]: Improve from-import error message with location

bpo-29478 [https://bugs.python.org/issue?@action=redirect&bpo=29478]: If max_line_length=None is specified while using the Compat32 policy, it is no longer ignored. Patch by Mircea Cosbuc.

bpo-29319 [https://bugs.python.org/issue?@action=redirect&bpo=29319]: Prevent RunMainFromImporter overwriting sys.path[0].

bpo-29337 [https://bugs.python.org/issue?@action=redirect&bpo=29337]: Fixed possible BytesWarning when compare the code objects. Warnings could be emitted at compile time.

bpo-29327 [https://bugs.python.org/issue?@action=redirect&bpo=29327]: Fixed a crash when pass the iterable keyword argument to sorted().

bpo-29034 [https://bugs.python.org/issue?@action=redirect&bpo=29034]: Fix memory leak and use-after-free in os module (path_converter).

bpo-29159 [https://bugs.python.org/issue?@action=redirect&bpo=29159]: Fix regression in bytes(x) when x.__index__() raises Exception.

bpo-29049 [https://bugs.python.org/issue?@action=redirect&bpo=29049]: Call _PyObject_GC_TRACK() lazily when calling Python function. Calling function is up to 5% faster.

bpo-28927 [https://bugs.python.org/issue?@action=redirect&bpo=28927]: bytes.fromhex() and bytearray.fromhex() now ignore all ASCII whitespace, not only spaces. Patch by Robert Xiao.

bpo-28932 [https://bugs.python.org/issue?@action=redirect&bpo=28932]: Do not include <sys/random.h> if it does not exist.

bpo-25677 [https://bugs.python.org/issue?@action=redirect&bpo=25677]: Correct the positioning of the syntax error caret for indented blocks. Based on patch by Michael Layzell.

bpo-29000 [https://bugs.python.org/issue?@action=redirect&bpo=29000]: Fixed bytes formatting of octals with zero padding in alternate form.

bpo-18896 [https://bugs.python.org/issue?@action=redirect&bpo=18896]: Python function can now have more than 255 parameters. collections.namedtuple() now supports tuples with more than 255 elements.

bpo-28596 [https://bugs.python.org/issue?@action=redirect&bpo=28596]: The preferred encoding is UTF-8 on Android. Patch written by Chi Hsuan Yen.

bpo-22257 [https://bugs.python.org/issue?@action=redirect&bpo=22257]: Clean up interpreter startup (see PEP 432).

bpo-26919 [https://bugs.python.org/issue?@action=redirect&bpo=26919]: On Android, operating system data is now always encoded/decoded to/from UTF-8, instead of the locale encoding to avoid inconsistencies with os.fsencode() and os.fsdecode() which are already using UTF-8.

bpo-28991 [https://bugs.python.org/issue?@action=redirect&bpo=28991]: functools.lru_cache() was susceptible to an obscure reentrancy bug triggerable by a monkey-patched len() function.

bpo-28147 [https://bugs.python.org/issue?@action=redirect&bpo=28147]: Fix a memory leak in split-table dictionaries: setattr() must not convert combined table into split table. Patch written by INADA Naoki.

bpo-28739 [https://bugs.python.org/issue?@action=redirect&bpo=28739]: f-string expressions are no longer accepted as docstrings and by ast.literal_eval() even if they do not include expressions.

bpo-28512 [https://bugs.python.org/issue?@action=redirect&bpo=28512]: Fixed setting the offset attribute of SyntaxError by PyErr_SyntaxLocationEx() and PyErr_SyntaxLocationObject().

bpo-28918 [https://bugs.python.org/issue?@action=redirect&bpo=28918]: Fix the cross compilation of xxlimited when Python has been built with Py_DEBUG defined.

bpo-23722 [https://bugs.python.org/issue?@action=redirect&bpo=23722]: Rather than silently producing a class that doesn’t support zero-argument super() in methods, failing to pass the new __classcell__ namespace entry up to type.__new__ now results in a DeprecationWarning and a class that supports zero-argument super().

bpo-28797 [https://bugs.python.org/issue?@action=redirect&bpo=28797]: Modifying the class __dict__ inside the __set_name__ method of a descriptor that is used inside that class no longer prevents calling the __set_name__ method of other descriptors.

bpo-28799 [https://bugs.python.org/issue?@action=redirect&bpo=28799]: Remove the PyEval_GetCallStats() function and deprecate the untested and undocumented sys.callstats() function. Remove the CALL_PROFILE special build: use the sys.setprofile() function, cProfile or profile to profile function calls.

bpo-12844 [https://bugs.python.org/issue?@action=redirect&bpo=12844]: More than 255 arguments can now be passed to a function.

bpo-28782 [https://bugs.python.org/issue?@action=redirect&bpo=28782]: Fix a bug in the implementation yield from when checking if the next instruction is YIELD_FROM. Regression introduced by WORDCODE (bpo-26647 [https://bugs.python.org/issue?@action=redirect&bpo=26647]).

bpo-28774 [https://bugs.python.org/issue?@action=redirect&bpo=28774]: Fix error position of the unicode error in ASCII and Latin1 encoders when a string returned by the error handler contains multiple non-encodable characters (non-ASCII for the ASCII codec, characters out of the U+0000-U+00FF range for Latin1).

bpo-28731 [https://bugs.python.org/issue?@action=redirect&bpo=28731]: Optimize _PyDict_NewPresized() to create correct size dict. Improve speed of dict literal with constant keys up to 30%.

bpo-28532 [https://bugs.python.org/issue?@action=redirect&bpo=28532]: Show sys.version when -V option is supplied twice.

bpo-27100 [https://bugs.python.org/issue?@action=redirect&bpo=27100]: The with-statement now checks for __enter__ before it checks for __exit__. This gives less confusing error messages when both methods are missing. Patch by Jonathan Ellington.

bpo-28746 [https://bugs.python.org/issue?@action=redirect&bpo=28746]: Fix the set_inheritable() file descriptor method on platforms that do not have the ioctl FIOCLEX and FIONCLEX commands.

bpo-26920 [https://bugs.python.org/issue?@action=redirect&bpo=26920]: Fix not getting the locale’s charset upon initializing the interpreter, on platforms that do not have langinfo.

bpo-28648 [https://bugs.python.org/issue?@action=redirect&bpo=28648]: Fixed crash in Py_DecodeLocale() in debug build on Mac OS X when decode astral characters. Patch by Xiang Zhang.

bpo-28665 [https://bugs.python.org/issue?@action=redirect&bpo=28665]: Improve speed of the STORE_DEREF opcode by 40%.

bpo-19398 [https://bugs.python.org/issue?@action=redirect&bpo=19398]: Extra slash no longer added to sys.path components in case of empty compile-time PYTHONPATH components.

bpo-28621 [https://bugs.python.org/issue?@action=redirect&bpo=28621]: Sped up converting int to float by reusing faster bits counting implementation. Patch by Adrian Wielgosik.

bpo-28580 [https://bugs.python.org/issue?@action=redirect&bpo=28580]: Optimize iterating split table values. Patch by Xiang Zhang.

bpo-28583 [https://bugs.python.org/issue?@action=redirect&bpo=28583]: PyDict_SetDefault didn’t combine split table when needed. Patch by Xiang Zhang.

bpo-28128 [https://bugs.python.org/issue?@action=redirect&bpo=28128]: Deprecation warning for invalid str and byte escape sequences now prints better information about where the error occurs. Patch by Serhiy Storchaka and Eric Smith.

bpo-28509 [https://bugs.python.org/issue?@action=redirect&bpo=28509]: dict.update() no longer allocate unnecessary large memory.

bpo-28426 [https://bugs.python.org/issue?@action=redirect&bpo=28426]: Fixed potential crash in PyUnicode_AsDecodedObject() in debug build.

bpo-28517 [https://bugs.python.org/issue?@action=redirect&bpo=28517]: Fixed of-by-one error in the peephole optimizer that caused keeping unreachable code.

bpo-28214 [https://bugs.python.org/issue?@action=redirect&bpo=28214]: Improved exception reporting for problematic __set_name__ attributes.

bpo-23782 [https://bugs.python.org/issue?@action=redirect&bpo=23782]: Fixed possible memory leak in _PyTraceback_Add() and exception loss in PyTraceBack_Here().

bpo-28183 [https://bugs.python.org/issue?@action=redirect&bpo=28183]: Optimize and cleanup dict iteration.

bpo-26081 [https://bugs.python.org/issue?@action=redirect&bpo=26081]: Added C implementation of asyncio.Future. Original patch by Yury Selivanov.

bpo-28379 [https://bugs.python.org/issue?@action=redirect&bpo=28379]: Added sanity checks and tests for PyUnicode_CopyCharacters(). Patch by Xiang Zhang.

bpo-28376 [https://bugs.python.org/issue?@action=redirect&bpo=28376]: The type of long range iterator is now registered as Iterator. Patch by Oren Milman.

bpo-28376 [https://bugs.python.org/issue?@action=redirect&bpo=28376]: Creating instances of range_iterator by calling range_iterator type now is disallowed. Calling iter() on range instance is the only way. Patch by Oren Milman.

bpo-26906 [https://bugs.python.org/issue?@action=redirect&bpo=26906]: Resolving special methods of uninitialized type now causes implicit initialization of the type instead of a fail.

bpo-18287 [https://bugs.python.org/issue?@action=redirect&bpo=18287]: PyType_Ready() now checks that tp_name is not NULL. Original patch by Niklas Koep.

bpo-24098 [https://bugs.python.org/issue?@action=redirect&bpo=24098]: Fixed possible crash when AST is changed in process of compiling it.

bpo-28201 [https://bugs.python.org/issue?@action=redirect&bpo=28201]: Dict reduces possibility of 2nd conflict in hash table when hashes have same lower bits.

bpo-28350 [https://bugs.python.org/issue?@action=redirect&bpo=28350]: String constants with null character no longer interned.

bpo-26617 [https://bugs.python.org/issue?@action=redirect&bpo=26617]: Fix crash when GC runs during weakref callbacks.

bpo-27942 [https://bugs.python.org/issue?@action=redirect&bpo=27942]: String constants now interned recursively in tuples and frozensets.

bpo-28289 [https://bugs.python.org/issue?@action=redirect&bpo=28289]: ImportError.__init__ now resets not specified attributes.

bpo-21578 [https://bugs.python.org/issue?@action=redirect&bpo=21578]: Fixed misleading error message when ImportError called with invalid keyword args.

bpo-28203 [https://bugs.python.org/issue?@action=redirect&bpo=28203]: Fix incorrect type in complex(1.0, {2:3}) error message. Patch by Soumya Sharma.

bpo-28086 [https://bugs.python.org/issue?@action=redirect&bpo=28086]: Single var-positional argument of tuple subtype was passed unscathed to the C-defined function. Now it is converted to exact tuple.

bpo-28214 [https://bugs.python.org/issue?@action=redirect&bpo=28214]: Now __set_name__ is looked up on the class instead of the instance.

bpo-27955 [https://bugs.python.org/issue?@action=redirect&bpo=27955]: Fallback on reading /dev/urandom device when the getrandom() syscall fails with EPERM, for example when blocked by SECCOMP.

bpo-28192 [https://bugs.python.org/issue?@action=redirect&bpo=28192]: Don’t import readline in isolated mode.

bpo-27441 [https://bugs.python.org/issue?@action=redirect&bpo=27441]: Remove some redundant assignments to ob_size in longobject.c. Thanks Oren Milman.

bpo-27222 [https://bugs.python.org/issue?@action=redirect&bpo=27222]: Clean up redundant code in long_rshift function. Thanks Oren Milman.

Upgrade internal unicode databases to Unicode version 9.0.0.

bpo-28131 [https://bugs.python.org/issue?@action=redirect&bpo=28131]: Fix a regression in zipimport’s compile_source(). zipimport should use the same optimization level as the interpreter.

bpo-28126 [https://bugs.python.org/issue?@action=redirect&bpo=28126]: Replace Py_MEMCPY with memcpy(). Visual Studio can properly optimize memcpy().

bpo-28120 [https://bugs.python.org/issue?@action=redirect&bpo=28120]: Fix dict.pop() for splitted dictionary when trying to remove a “pending key” (Not yet inserted in split-table). Patch by Xiang Zhang.

bpo-26182 [https://bugs.python.org/issue?@action=redirect&bpo=26182]: Raise DeprecationWarning when async and await keywords are used as variable/attribute/class/function name.

bpo-26182 [https://bugs.python.org/issue?@action=redirect&bpo=26182]: Fix a refleak in code that raises DeprecationWarning.

bpo-28721 [https://bugs.python.org/issue?@action=redirect&bpo=28721]: Fix asynchronous generators aclose() and athrow() to handle StopAsyncIteration propagation properly.

bpo-26110 [https://bugs.python.org/issue?@action=redirect&bpo=26110]: Speed-up method calls: add LOAD_METHOD and CALL_METHOD opcodes.

Library

bpo-31499 [https://bugs.python.org/issue?@action=redirect&bpo=31499]: xml.etree: Fix a crash when a parser is part of a reference cycle.

bpo-31482 [https://bugs.python.org/issue?@action=redirect&bpo=31482]: random.seed() now works with bytes in version=1

bpo-28556 [https://bugs.python.org/issue?@action=redirect&bpo=28556]: typing.get_type_hints now finds the right globalns for classes and modules by default (when no globalns was specified by the caller).

bpo-28556 [https://bugs.python.org/issue?@action=redirect&bpo=28556]: Speed improvements to the typing module. Original PRs by Ivan Levkivskyi and Mitar.

bpo-31544 [https://bugs.python.org/issue?@action=redirect&bpo=31544]: The C accelerator module of ElementTree ignored exceptions raised when looking up TreeBuilder target methods in XMLParser().

bpo-31234 [https://bugs.python.org/issue?@action=redirect&bpo=31234]: socket.create_connection() now fixes manually a reference cycle: clear the variable storing the last exception on success.

bpo-31457 [https://bugs.python.org/issue?@action=redirect&bpo=31457]: LoggerAdapter objects can now be nested.

bpo-31431 [https://bugs.python.org/issue?@action=redirect&bpo=31431]: SSLContext.check_hostname now automatically sets SSLContext.verify_mode to ssl.CERT_REQUIRED instead of failing with a ValueError.

bpo-31233 [https://bugs.python.org/issue?@action=redirect&bpo=31233]: socketserver.ThreadingMixIn now keeps a list of non-daemonic threads to wait until all these threads complete in server_close().

bpo-28638 [https://bugs.python.org/issue?@action=redirect&bpo=28638]: Changed the implementation strategy for collections.namedtuple() to substantially reduce the use of exec() in favor of precomputed methods. As a result, the verbose parameter and _source attribute are no longer supported. The benefits include 1) having a smaller memory footprint for applications using multiple named tuples, 2) faster creation of the named tuple class (approx 4x to 6x depending on how it is measured), and 3) minor speed-ups for instance creation using __new__, _make, and _replace. (The primary patch contributor is Jelle Zijlstra with further improvements by INADA Naoki, Serhiy Storchaka, and Raymond Hettinger.)

bpo-31400 [https://bugs.python.org/issue?@action=redirect&bpo=31400]: Improves SSL error handling to avoid losing error numbers.

bpo-27629 [https://bugs.python.org/issue?@action=redirect&bpo=27629]: Make return types of SSLContext.wrap_bio() and SSLContext.wrap_socket() customizable.

bpo-28958 [https://bugs.python.org/issue?@action=redirect&bpo=28958]: ssl.SSLContext() now uses OpenSSL error information when a context cannot be instantiated.

bpo-28182 [https://bugs.python.org/issue?@action=redirect&bpo=28182]: The SSL module now raises SSLCertVerificationError when OpenSSL fails to verify the peer’s certificate. The exception contains more information about the error.

bpo-27340 [https://bugs.python.org/issue?@action=redirect&bpo=27340]: SSLSocket.sendall() now uses memoryview to create slices of data. This fixes support for all bytes-like object. It is also more efficient and avoids costly copies.

bpo-14191 [https://bugs.python.org/issue?@action=redirect&bpo=14191]: A new function argparse.ArgumentParser.parse_intermixed_args provides the ability to parse command lines where there user intermixes options and positional arguments.

bpo-31178 [https://bugs.python.org/issue?@action=redirect&bpo=31178]: Fix string concatenation bug in rare error path in the subprocess module

bpo-31350 [https://bugs.python.org/issue?@action=redirect&bpo=31350]: Micro-optimize asyncio._get_running_loop() to become up to 10% faster.

bpo-31170 [https://bugs.python.org/issue?@action=redirect&bpo=31170]: expat: Update libexpat from 2.2.3 to 2.2.4. Fix copying of partial characters for UTF-8 input (libexpat bug 115): https://github.com/libexpat/libexpat/issues/115

bpo-29136 [https://bugs.python.org/issue?@action=redirect&bpo=29136]: Add TLS 1.3 cipher suites and OP_NO_TLSv1_3.

bpo-1198569 [https://bugs.python.org/issue?@action=redirect&bpo=1198569]: string.Template subclasses can optionally define braceidpattern if they want to specify different placeholder patterns inside and outside the braces. If None (the default) it falls back to idpattern.

bpo-31326 [https://bugs.python.org/issue?@action=redirect&bpo=31326]: concurrent.futures.ProcessPoolExecutor.shutdown() now explicitly closes the call queue. Moreover, shutdown(wait=True) now also join the call queue thread, to prevent leaking a dangling thread.

bpo-27144 [https://bugs.python.org/issue?@action=redirect&bpo=27144]: The map() and as_completed() iterators in concurrent.futures now avoid keeping a reference to yielded objects.

bpo-31281 [https://bugs.python.org/issue?@action=redirect&bpo=31281]: Fix fileinput.FileInput(files, inplace=True) when files contain pathlib.Path objects.

bpo-10746 [https://bugs.python.org/issue?@action=redirect&bpo=10746]: Fix ctypes producing wrong PEP 3118 type codes for integer types.

bpo-27584 [https://bugs.python.org/issue?@action=redirect&bpo=27584]: AF_VSOCK has been added to the socket interface which allows communication between virtual machines and their host.

bpo-22536 [https://bugs.python.org/issue?@action=redirect&bpo=22536]: The subprocess module now sets the filename when FileNotFoundError is raised on POSIX systems due to the executable or cwd not being found.

bpo-29741 [https://bugs.python.org/issue?@action=redirect&bpo=29741]: Update some methods in the _pyio module to also accept integer types. Patch by Oren Milman.

bpo-31249 [https://bugs.python.org/issue?@action=redirect&bpo=31249]: concurrent.futures: WorkItem.run() used by ThreadPoolExecutor now breaks a reference cycle between an exception object and the WorkItem object.

bpo-31247 [https://bugs.python.org/issue?@action=redirect&bpo=31247]: xmlrpc.server now explicitly breaks reference cycles when using sys.exc_info() in code handling exceptions.

bpo-23835 [https://bugs.python.org/issue?@action=redirect&bpo=23835]: configparser: reading defaults in the ConfigParser() constructor is now using read_dict(), making its behavior consistent with the rest of the parser. Non-string keys and values in the defaults dictionary are now being implicitly converted to strings. Patch by James Tocknell.

bpo-31238 [https://bugs.python.org/issue?@action=redirect&bpo=31238]: pydoc: the stop() method of the private ServerThread class now waits until DocServer.serve_until_quit() completes and then explicitly sets its docserver attribute to None to break a reference cycle.

bpo-5001 [https://bugs.python.org/issue?@action=redirect&bpo=5001]: Many asserts in multiprocessing are now more informative, and some error types have been changed to more specific ones.

bpo-31109 [https://bugs.python.org/issue?@action=redirect&bpo=31109]: Convert zipimport to use Argument Clinic.

bpo-30102 [https://bugs.python.org/issue?@action=redirect&bpo=30102]: The ssl and hashlib modules now call OPENSSL_add_all_algorithms_noconf() on OpenSSL < 1.1.0. The function detects CPU features and enables optimizations on some CPU architectures such as POWER8. Patch is based on research from Gustavo Serra Scalet.

bpo-18966 [https://bugs.python.org/issue?@action=redirect&bpo=18966]: Non-daemonic threads created by a multiprocessing.Process are now joined on child exit.

bpo-31183 [https://bugs.python.org/issue?@action=redirect&bpo=31183]: dis now works with asynchronous generator and coroutine objects. Patch by George Collins based on diagnosis by Luciano Ramalho.

bpo-5001 [https://bugs.python.org/issue?@action=redirect&bpo=5001]: There are a number of uninformative asserts in the multiprocessing module, as noted in issue 5001. This change fixes two of the most potentially problematic ones, since they are in error-reporting code, in the multiprocessing.managers.convert_to_error function. (It also makes more informative a ValueError message.) The only potentially problematic change is that the AssertionError is now a TypeError; however, this should also help distinguish it from an AssertionError being reported by the function/its caller (such as in issue 31169). - Patch by Allen W. Smith (drallensmith on github).

bpo-31185 [https://bugs.python.org/issue?@action=redirect&bpo=31185]: Fixed miscellaneous errors in asyncio speedup module.

bpo-31151 [https://bugs.python.org/issue?@action=redirect&bpo=31151]: socketserver.ForkingMixIn.server_close() now waits until all child processes completed to prevent leaking zombie processes.

bpo-31072 [https://bugs.python.org/issue?@action=redirect&bpo=31072]: Add an include_file parameter to zipapp.create_archive()

bpo-24700 [https://bugs.python.org/issue?@action=redirect&bpo=24700]: Optimize array.array comparison. It is now from 10x up to 70x faster when comparing arrays holding values of the same integer type.

bpo-31135 [https://bugs.python.org/issue?@action=redirect&bpo=31135]: ttk: fix the destroy() method of LabeledScale and OptionMenu classes. Call the parent destroy() method even if the used attribute doesn’t exist. The LabeledScale.destroy() method now also explicitly clears label and scale attributes to help the garbage collector to destroy all widgets.

bpo-31107 [https://bugs.python.org/issue?@action=redirect&bpo=31107]: Fix copyreg._slotnames() mangled attribute calculation for classes whose name begins with an underscore. Patch by Shane Harvey.

bpo-31080 [https://bugs.python.org/issue?@action=redirect&bpo=31080]: Allow logging.config.fileConfig to accept kwargs and/or args.

bpo-30897 [https://bugs.python.org/issue?@action=redirect&bpo=30897]: pathlib.Path objects now include an is_mount() method (only implemented on POSIX). This is similar to os.path.ismount(p). Patch by Cooper Ry Lees.

bpo-31061 [https://bugs.python.org/issue?@action=redirect&bpo=31061]: Fixed a crash when using asyncio and threads.

bpo-30987 [https://bugs.python.org/issue?@action=redirect&bpo=30987]: Added support for CAN ISO-TP protocol in the socket module.

bpo-30522 [https://bugs.python.org/issue?@action=redirect&bpo=30522]: Added a setStream method to logging.StreamHandler to allow the stream to be set after creation.

bpo-30502 [https://bugs.python.org/issue?@action=redirect&bpo=30502]: Fix handling of long oids in ssl. Based on patch by Christian Heimes.

bpo-5288 [https://bugs.python.org/issue?@action=redirect&bpo=5288]: Support tzinfo objects with sub-minute offsets.

bpo-30919 [https://bugs.python.org/issue?@action=redirect&bpo=30919]: Fix shared memory performance regression in multiprocessing in 3.x.

Shared memory used anonymous memory mappings in 2.x, while 3.x mmaps actual files. Try to be careful to do as little disk I/O as possible.

bpo-26732 [https://bugs.python.org/issue?@action=redirect&bpo=26732]: Fix too many fds in processes started with the “forkserver” method.

A child process would inherit as many fds as the number of still-running children.

bpo-29403 [https://bugs.python.org/issue?@action=redirect&bpo=29403]: Fix unittest.mock’s autospec to not fail on method-bound builtin functions. Patch by Aaron Gallagher.

bpo-30961 [https://bugs.python.org/issue?@action=redirect&bpo=30961]: Fix decrementing a borrowed reference in tracemalloc.

bpo-19896 [https://bugs.python.org/issue?@action=redirect&bpo=19896]: Fix multiprocessing.sharedctypes to recognize typecodes 'q' and 'Q'.

bpo-30946 [https://bugs.python.org/issue?@action=redirect&bpo=30946]: Remove obsolete code in readline module for platforms where GNU readline is older than 2.1 or where select() is not available.

bpo-25684 [https://bugs.python.org/issue?@action=redirect&bpo=25684]: Change ttk.OptionMenu radiobuttons to be unique across instances of OptionMenu.

bpo-30886 [https://bugs.python.org/issue?@action=redirect&bpo=30886]: Fix multiprocessing.Queue.join_thread(): it now waits until the thread completes, even if the thread was started by the same process which created the queue.

bpo-29854 [https://bugs.python.org/issue?@action=redirect&bpo=29854]: Fix segfault in readline when using readline’s history-size option. Patch by Nir Soffer.

bpo-30794 [https://bugs.python.org/issue?@action=redirect&bpo=30794]: Added multiprocessing.Process.kill method to terminate using the SIGKILL signal on Unix.

bpo-30319 [https://bugs.python.org/issue?@action=redirect&bpo=30319]: socket.close() now ignores ECONNRESET error.

bpo-30828 [https://bugs.python.org/issue?@action=redirect&bpo=30828]: Fix out of bounds write in asyncio.CFuture.remove_done_callback().

bpo-30302 [https://bugs.python.org/issue?@action=redirect&bpo=30302]: Use keywords in the repr of datetime.timedelta.

bpo-30807 [https://bugs.python.org/issue?@action=redirect&bpo=30807]: signal.setitimer() may disable the timer when passed a tiny value.

Tiny values (such as 1e-6) are valid non-zero values for setitimer(), which is specified as taking microsecond-resolution intervals. However, on some platform, our conversion routine could convert 1e-6 into a zero interval, therefore disabling the timer instead of (re-)scheduling it.

bpo-30441 [https://bugs.python.org/issue?@action=redirect&bpo=30441]: Fix bug when modifying os.environ while iterating over it

bpo-29585 [https://bugs.python.org/issue?@action=redirect&bpo=29585]: Avoid importing sysconfig from site to improve startup speed. Python startup is about 5% faster on Linux and 30% faster on macOS.

bpo-29293 [https://bugs.python.org/issue?@action=redirect&bpo=29293]: Add missing parameter “n” on multiprocessing.Condition.notify().

The doc claims multiprocessing.Condition behaves like threading.Condition, but its notify() method lacked the optional “n” argument (to specify the number of sleepers to wake up) that threading.Condition.notify() accepts.

bpo-30532 [https://bugs.python.org/issue?@action=redirect&bpo=30532]: Fix email header value parser dropping folding white space in certain cases.

bpo-30596 [https://bugs.python.org/issue?@action=redirect&bpo=30596]: Add a close() method to multiprocessing.Process.

bpo-9146 [https://bugs.python.org/issue?@action=redirect&bpo=9146]: Fix a segmentation fault in _hashopenssl when standard hash functions such as md5 are not available in the linked OpenSSL library. As in some special FIPS-140 build environments.

bpo-29169 [https://bugs.python.org/issue?@action=redirect&bpo=29169]: Update zlib to 1.2.11.

bpo-30119 [https://bugs.python.org/issue?@action=redirect&bpo=30119]: ftplib.FTP.putline() now throws ValueError on commands that contains CR or LF. Patch by Dong-hee Na.

bpo-30879 [https://bugs.python.org/issue?@action=redirect&bpo=30879]: os.listdir() and os.scandir() now emit bytes names when called with bytes-like argument.

bpo-30746 [https://bugs.python.org/issue?@action=redirect&bpo=30746]: Prohibited the ‘=’ character in environment variable names in os.putenv() and os.spawn*().

bpo-30664 [https://bugs.python.org/issue?@action=redirect&bpo=30664]: The description of a unittest subtest now preserves the order of keyword arguments of TestCase.subTest().

bpo-21071 [https://bugs.python.org/issue?@action=redirect&bpo=21071]: struct.Struct.format type is now str instead of bytes.

bpo-29212 [https://bugs.python.org/issue?@action=redirect&bpo=29212]: Fix concurrent.futures.thread.ThreadPoolExecutor threads to have a non repr() based thread name by default when no thread_name_prefix is supplied. They will now identify themselves as “ThreadPoolExecutor-y_n”.

bpo-29755 [https://bugs.python.org/issue?@action=redirect&bpo=29755]: Fixed the lgettext() family of functions in the gettext module. They now always return bytes.

bpo-30616 [https://bugs.python.org/issue?@action=redirect&bpo=30616]: Functional API of enum allows to create empty enums. Patched by Dong-hee Na

bpo-30038 [https://bugs.python.org/issue?@action=redirect&bpo=30038]: Fix race condition between signal delivery and wakeup file descriptor. Patch by Nathaniel Smith.

bpo-23894 [https://bugs.python.org/issue?@action=redirect&bpo=23894]: lib2to3 now recognizes rb'...' and f'...' strings.

bpo-24744 [https://bugs.python.org/issue?@action=redirect&bpo=24744]: pkgutil.walk_packages function now raises ValueError if path is a string. Patch by Sanyam Khurana.

bpo-24484 [https://bugs.python.org/issue?@action=redirect&bpo=24484]: Avoid race condition in multiprocessing cleanup.

bpo-30589 [https://bugs.python.org/issue?@action=redirect&bpo=30589]: Fix multiprocessing.Process.exitcode to return the opposite of the signal number when the process is killed by a signal (instead of 255) when using the “forkserver” method.

bpo-28994 [https://bugs.python.org/issue?@action=redirect&bpo=28994]: The traceback no longer displayed for SystemExit raised in a callback registered by atexit.

bpo-30508 [https://bugs.python.org/issue?@action=redirect&bpo=30508]: Don’t log exceptions if Task/Future “cancel()” method was called.

bpo-30645 [https://bugs.python.org/issue?@action=redirect&bpo=30645]: Fix path calculation in imp.load_package(), fixing it for cases when a package is only shipped with bytecodes. Patch by Alexandru Ardelean.

bpo-11822 [https://bugs.python.org/issue?@action=redirect&bpo=11822]: The dis.dis() function now is able to disassemble nested code objects.

bpo-30624 [https://bugs.python.org/issue?@action=redirect&bpo=30624]: selectors does not take KeyboardInterrupt and SystemExit into account, leaving a fd in a bad state in case of error. Patch by Giampaolo Rodola’.

bpo-30595 [https://bugs.python.org/issue?@action=redirect&bpo=30595]: multiprocessing.Queue.get() with a timeout now polls its reader in non-blocking mode if it succeeded to acquire the lock but the acquire took longer than the timeout.

bpo-28556 [https://bugs.python.org/issue?@action=redirect&bpo=28556]: Updates to typing module: Add generic AsyncContextManager, add support for ContextManager on all versions. Original PRs by Jelle Zijlstra and Ivan Levkivskyi

bpo-30605 [https://bugs.python.org/issue?@action=redirect&bpo=30605]: re.compile() no longer raises a BytesWarning when compiling a bytes instance with misplaced inline modifier. Patch by Roy Williams.

bpo-29870 [https://bugs.python.org/issue?@action=redirect&bpo=29870]: Fix ssl sockets leaks when connection is aborted in asyncio/ssl implementation. Patch by Michaël Sghaïer.

bpo-29743 [https://bugs.python.org/issue?@action=redirect&bpo=29743]: Closing transport during handshake process leaks open socket. Patch by Nikolay Kim

bpo-27585 [https://bugs.python.org/issue?@action=redirect&bpo=27585]: Fix waiter cancellation in asyncio.Lock. Patch by Mathieu Sornay.

bpo-30014 [https://bugs.python.org/issue?@action=redirect&bpo=30014]: modify() method of poll(), epoll() and devpoll() based classes of selectors module is around 10% faster. Patch by Giampaolo Rodola’.

bpo-30418 [https://bugs.python.org/issue?@action=redirect&bpo=30418]: On Windows, subprocess.Popen.communicate() now also ignore EINVAL on stdin.write() if the child process is still running but closed the pipe.

bpo-30463 [https://bugs.python.org/issue?@action=redirect&bpo=30463]: Addded empty __slots__ to abc.ABC. This allows subclassers to deny __dict__ and __weakref__ creation. Patch by Aaron Hall.

bpo-30520 [https://bugs.python.org/issue?@action=redirect&bpo=30520]: Loggers are now pickleable.

bpo-30557 [https://bugs.python.org/issue?@action=redirect&bpo=30557]: faulthandler now correctly filters and displays exception codes on Windows

bpo-30526 [https://bugs.python.org/issue?@action=redirect&bpo=30526]: Add TextIOWrapper.reconfigure() and a TextIOWrapper.write_through attribute.

bpo-30245 [https://bugs.python.org/issue?@action=redirect&bpo=30245]: Fix possible overflow when organize struct.pack_into error message. Patch by Yuan Liu.

bpo-30378 [https://bugs.python.org/issue?@action=redirect&bpo=30378]: Fix the problem that logging.handlers.SysLogHandler cannot handle IPv6 addresses.

bpo-16500 [https://bugs.python.org/issue?@action=redirect&bpo=16500]: Allow registering at-fork handlers.

bpo-30470 [https://bugs.python.org/issue?@action=redirect&bpo=30470]: Deprecate invalid ctypes call protection on Windows. Patch by Mariatta Wijaya.

bpo-30414 [https://bugs.python.org/issue?@action=redirect&bpo=30414]: multiprocessing.Queue._feed background running thread do not break from main loop on exception.

bpo-30003 [https://bugs.python.org/issue?@action=redirect&bpo=30003]: Fix handling escape characters in HZ codec. Based on patch by Ma Lin.

bpo-30149 [https://bugs.python.org/issue?@action=redirect&bpo=30149]: inspect.signature() now supports callables with variable-argument parameters wrapped with partialmethod. Patch by Dong-hee Na.

bpo-30436 [https://bugs.python.org/issue?@action=redirect&bpo=30436]: importlib.find_spec() raises ModuleNotFoundError instead of AttributeError if the specified parent module is not a package (i.e. lacks a __path__ attribute).

bpo-30301 [https://bugs.python.org/issue?@action=redirect&bpo=30301]: Fix AttributeError when using SimpleQueue.empty() under spawn and forkserver start methods.

bpo-30375 [https://bugs.python.org/issue?@action=redirect&bpo=30375]: Warnings emitted when compile a regular expression now always point to the line in the user code. Previously they could point into inners of the re module if emitted from inside of groups or conditionals.

bpo-30329 [https://bugs.python.org/issue?@action=redirect&bpo=30329]: imaplib and poplib now catch the Windows socket WSAEINVAL error (code 10022) on shutdown(SHUT_RDWR): An invalid operation was attempted. This error occurs sometimes on SSL connections.

bpo-29196 [https://bugs.python.org/issue?@action=redirect&bpo=29196]: Removed previously deprecated in Python 2.4 classes Plist, Dict and _InternalDict in the plistlib module. Dict values in the result of functions readPlist() and readPlistFromBytes() are now normal dicts. You no longer can use attribute access to access items of these dictionaries.

bpo-9850 [https://bugs.python.org/issue?@action=redirect&bpo=9850]: The macpath is now deprecated and will be removed in Python 3.8.

bpo-30299 [https://bugs.python.org/issue?@action=redirect&bpo=30299]: Compiling regular expression in debug mode on CPython now displays the compiled bytecode in human readable form.

bpo-30048 [https://bugs.python.org/issue?@action=redirect&bpo=30048]: Fixed Task.cancel() can be ignored when the task is running coroutine and the coroutine returned without any more await.

bpo-30266 [https://bugs.python.org/issue?@action=redirect&bpo=30266]: contextlib.AbstractContextManager now supports anti-registration by setting __enter__ = None or __exit__ = None, following the pattern introduced in bpo-25958 [https://bugs.python.org/issue?@action=redirect&bpo=25958]. Patch by Jelle Zijlstra.

bpo-30340 [https://bugs.python.org/issue?@action=redirect&bpo=30340]: Enhanced regular expressions optimization. This increased the performance of matching some patterns up to 25 times.

bpo-30298 [https://bugs.python.org/issue?@action=redirect&bpo=30298]: Weaken the condition of deprecation warnings for inline modifiers. Now allowed several subsequential inline modifiers at the start of the pattern (e.g. '(?i)(?s)...'). In verbose mode whitespaces and comments now are allowed before and between inline modifiers (e.g. '(?x) (?i) (?s)...').

bpo-30285 [https://bugs.python.org/issue?@action=redirect&bpo=30285]: Optimized case-insensitive matching and searching of regular expressions.

bpo-29990 [https://bugs.python.org/issue?@action=redirect&bpo=29990]: Fix range checking in GB18030 decoder. Original patch by Ma Lin.

bpo-29979 [https://bugs.python.org/issue?@action=redirect&bpo=29979]: rewrite cgi.parse_multipart, reusing the FieldStorage class and making its results consistent with those of FieldStorage for multipart/form-data requests. Patch by Pierre Quentel.

bpo-30243 [https://bugs.python.org/issue?@action=redirect&bpo=30243]: Removed the __init__ methods of _json’s scanner and encoder. Misusing them could cause memory leaks or crashes. Now scanner and encoder objects are completely initialized in the __new__ methods.

bpo-30215 [https://bugs.python.org/issue?@action=redirect&bpo=30215]: Compiled regular expression objects with the re.LOCALE flag no longer depend on the locale at compile time. Only the locale at matching time affects the result of matching.

bpo-30185 [https://bugs.python.org/issue?@action=redirect&bpo=30185]: Avoid KeyboardInterrupt tracebacks in forkserver helper process when Ctrl-C is received.

bpo-30103 [https://bugs.python.org/issue?@action=redirect&bpo=30103]: binascii.b2a_uu() and uu.encode() now support using '`' as zero instead of space.

bpo-28556 [https://bugs.python.org/issue?@action=redirect&bpo=28556]: Various updates to typing module: add typing.NoReturn type, use WrapperDescriptorType, minor bug-fixes. Original PRs by Jim Fasarakis-Hilliard and Ivan Levkivskyi.

bpo-30205 [https://bugs.python.org/issue?@action=redirect&bpo=30205]: Fix getsockname() for unbound AF_UNIX sockets on Linux.

bpo-30228 [https://bugs.python.org/issue?@action=redirect&bpo=30228]: The seek() and tell() methods of io.FileIO now set the internal seekable attribute to avoid one syscall on open() (in buffered or text mode).

bpo-30190 [https://bugs.python.org/issue?@action=redirect&bpo=30190]: unittest’s assertAlmostEqual and assertNotAlmostEqual provide a better message in case of failure which includes the difference between left and right arguments. (patch by Giampaolo Rodola’)

bpo-30101 [https://bugs.python.org/issue?@action=redirect&bpo=30101]: Add support for curses.A_ITALIC.

bpo-29822 [https://bugs.python.org/issue?@action=redirect&bpo=29822]: inspect.isabstract() now works during __init_subclass__. Patch by Nate Soares.

bpo-29960 [https://bugs.python.org/issue?@action=redirect&bpo=29960]: Preserve generator state when _random.Random.setstate() raises an exception. Patch by Bryan Olson.

bpo-30070 [https://bugs.python.org/issue?@action=redirect&bpo=30070]: Fixed leaks and crashes in errors handling in the parser module.

bpo-22352 [https://bugs.python.org/issue?@action=redirect&bpo=22352]: Column widths in the output of dis.dis() are now adjusted for large line numbers and instruction offsets.

bpo-30061 [https://bugs.python.org/issue?@action=redirect&bpo=30061]: Fixed crashes in IOBase methods __next__() and readlines() when readline() or __next__() respectively return non-sizeable object. Fixed possible other errors caused by not checking results of PyObject_Size(), PySequence_Size(), or PyMapping_Size().

bpo-30218 [https://bugs.python.org/issue?@action=redirect&bpo=30218]: Fix PathLike support for shutil.unpack_archive. Patch by Jelle Zijlstra.

bpo-10076 [https://bugs.python.org/issue?@action=redirect&bpo=10076]: Compiled regular expression and match objects in the re module now support copy.copy() and copy.deepcopy() (they are considered atomic).

bpo-30068 [https://bugs.python.org/issue?@action=redirect&bpo=30068]: _io._IOBase.readlines will check if it’s closed first when hint is present.

bpo-29694 [https://bugs.python.org/issue?@action=redirect&bpo=29694]: Fixed race condition in pathlib mkdir with flags parents=True. Patch by Armin Rigo.

bpo-29692 [https://bugs.python.org/issue?@action=redirect&bpo=29692]: Fixed arbitrary unchaining of RuntimeError exceptions in contextlib.contextmanager. Patch by Siddharth Velankar.

bpo-26187 [https://bugs.python.org/issue?@action=redirect&bpo=26187]: Test that sqlite3 trace callback is not called multiple times when schema is changing. Indirectly fixed by switching to use sqlite3_prepare_v2() in bpo-9303 [https://bugs.python.org/issue?@action=redirect&bpo=9303]. Patch by Aviv Palivoda.

bpo-30017 [https://bugs.python.org/issue?@action=redirect&bpo=30017]: Allowed calling the close() method of the zip entry writer object multiple times. Writing to a closed writer now always produces a ValueError.

bpo-29998 [https://bugs.python.org/issue?@action=redirect&bpo=29998]: Pickling and copying ImportError now preserves name and path attributes.

bpo-29995 [https://bugs.python.org/issue?@action=redirect&bpo=29995]: re.escape() now escapes only regex special characters.

bpo-29962 [https://bugs.python.org/issue?@action=redirect&bpo=29962]: Add math.remainder operation, implementing remainder as specified in IEEE 754.

bpo-29649 [https://bugs.python.org/issue?@action=redirect&bpo=29649]: Improve struct.pack_into() exception messages for problems with the buffer size and offset. Patch by Andrew Nester.

bpo-29654 [https://bugs.python.org/issue?@action=redirect&bpo=29654]: Support If-Modified-Since HTTP header (browser cache). Patch by Pierre Quentel.

bpo-29931 [https://bugs.python.org/issue?@action=redirect&bpo=29931]: Fixed comparison check for ipaddress.ip_interface objects. Patch by Sanjay Sundaresan.

bpo-29953 [https://bugs.python.org/issue?@action=redirect&bpo=29953]: Fixed memory leaks in the replace() method of datetime and time objects when pass out of bound fold argument.

bpo-29942 [https://bugs.python.org/issue?@action=redirect&bpo=29942]: Fix a crash in itertools.chain.from_iterable when encountering long runs of empty iterables.

bpo-10030 [https://bugs.python.org/issue?@action=redirect&bpo=10030]: Sped up reading encrypted ZIP files by 2 times.

bpo-29204 [https://bugs.python.org/issue?@action=redirect&bpo=29204]: Element.getiterator() and the html parameter of XMLParser() were deprecated only in the documentation (since Python 3.2 and 3.4 correspondintly). Now using them emits a deprecation warning.

bpo-27863 [https://bugs.python.org/issue?@action=redirect&bpo=27863]: Fixed multiple crashes in ElementTree caused by race conditions and wrong types.

bpo-25996 [https://bugs.python.org/issue?@action=redirect&bpo=25996]: Added support of file descriptors in os.scandir() on Unix. os.fwalk() is sped up by 2 times by using os.scandir().

bpo-28699 [https://bugs.python.org/issue?@action=redirect&bpo=28699]: Fixed a bug in pools in multiprocessing.pool that raising an exception at the very first of an iterable may swallow the exception or make the program hang. Patch by Davin Potts and Xiang Zhang.

bpo-23890 [https://bugs.python.org/issue?@action=redirect&bpo=23890]: unittest.TestCase.assertRaises() now manually breaks a reference cycle to not keep objects alive longer than expected.

bpo-29901 [https://bugs.python.org/issue?@action=redirect&bpo=29901]: The zipapp module now supports general path-like objects, not just pathlib.Path.

bpo-25803 [https://bugs.python.org/issue?@action=redirect&bpo=25803]: Avoid incorrect errors raised by Path.mkdir(exist_ok=True) when the OS gives priority to errors such as EACCES over EEXIST.

bpo-29861 [https://bugs.python.org/issue?@action=redirect&bpo=29861]: Release references to tasks, their arguments and their results as soon as they are finished in multiprocessing.Pool.

bpo-19930 [https://bugs.python.org/issue?@action=redirect&bpo=19930]: The mode argument of os.makedirs() no longer affects the file permission bits of newly-created intermediate-level directories.

bpo-29884 [https://bugs.python.org/issue?@action=redirect&bpo=29884]: faulthandler: Restore the old sigaltstack during teardown. Patch by Christophe Zeitouny.

bpo-25455 [https://bugs.python.org/issue?@action=redirect&bpo=25455]: Fixed crashes in repr of recursive buffered file-like objects.

bpo-29800 [https://bugs.python.org/issue?@action=redirect&bpo=29800]: Fix crashes in partial.__repr__ if the keys of partial.keywords are not strings. Patch by Michael Seifert.

bpo-8256 [https://bugs.python.org/issue?@action=redirect&bpo=8256]: Fixed possible failing or crashing input() if attributes “encoding” or “errors” of sys.stdin or sys.stdout are not set or are not strings.

bpo-28692 [https://bugs.python.org/issue?@action=redirect&bpo=28692]: Using non-integer value for selecting a plural form in gettext is now deprecated.

bpo-26121 [https://bugs.python.org/issue?@action=redirect&bpo=26121]: Use C library implementation for math functions erf() and erfc().

bpo-29619 [https://bugs.python.org/issue?@action=redirect&bpo=29619]: os.stat() and os.DirEntry.inode() now convert inode (st_ino) using unsigned integers.

bpo-28298 [https://bugs.python.org/issue?@action=redirect&bpo=28298]: Fix a bug that prevented array ‘Q’, ‘L’ and ‘I’ from accepting big intables (objects that have __int__) as elements.

bpo-29645 [https://bugs.python.org/issue?@action=redirect&bpo=29645]: Speed up importing the webbrowser module. webbrowser.register() is now thread-safe.

bpo-28231 [https://bugs.python.org/issue?@action=redirect&bpo=28231]: The zipfile module now accepts path-like objects for external paths.

bpo-26915 [https://bugs.python.org/issue?@action=redirect&bpo=26915]: index() and count() methods of collections.abc.Sequence now check identity before checking equality when do comparisons.

bpo-28682 [https://bugs.python.org/issue?@action=redirect&bpo=28682]: Added support for bytes paths in os.fwalk().

bpo-29728 [https://bugs.python.org/issue?@action=redirect&bpo=29728]: Add new socket.TCP_NOTSENT_LOWAT (Linux 3.12) constant. Patch by Nathaniel J. Smith.

bpo-29623 [https://bugs.python.org/issue?@action=redirect&bpo=29623]: Allow use of path-like object as a single argument in ConfigParser.read(). Patch by David Ellis.

bpo-9303 [https://bugs.python.org/issue?@action=redirect&bpo=9303]: Migrate sqlite3 module to _v2 API. Patch by Aviv Palivoda.

bpo-28963 [https://bugs.python.org/issue?@action=redirect&bpo=28963]: Fix out of bound iteration in asyncio.Future.remove_done_callback implemented in C.

bpo-29704 [https://bugs.python.org/issue?@action=redirect&bpo=29704]: asyncio.subprocess.SubprocessStreamProtocol no longer closes before all pipes are closed.

bpo-29271 [https://bugs.python.org/issue?@action=redirect&bpo=29271]: Fix Task.current_task and Task.all_tasks implemented in C to accept None argument as their pure Python implementation.

bpo-29703 [https://bugs.python.org/issue?@action=redirect&bpo=29703]: Fix asyncio to support instantiation of new event loops in child processes.

bpo-29615 [https://bugs.python.org/issue?@action=redirect&bpo=29615]: SimpleXMLRPCDispatcher no longer chains KeyError (or any other exception) to exception(s) raised in the dispatched methods. Patch by Petr Motejlek.

bpo-7769 [https://bugs.python.org/issue?@action=redirect&bpo=7769]: Method register_function() of xmlrpc.server.SimpleXMLRPCDispatcher and its subclasses can now be used as a decorator.

bpo-29376 [https://bugs.python.org/issue?@action=redirect&bpo=29376]: Fix assertion error in threading._DummyThread.is_alive().

bpo-28624 [https://bugs.python.org/issue?@action=redirect&bpo=28624]: Add a test that checks that cwd parameter of Popen() accepts PathLike objects. Patch by Sayan Chowdhury.

bpo-28518 [https://bugs.python.org/issue?@action=redirect&bpo=28518]: Start a transaction implicitly before a DML statement. Patch by Aviv Palivoda.

bpo-29742 [https://bugs.python.org/issue?@action=redirect&bpo=29742]: get_extra_info() raises exception if get called on closed ssl transport. Patch by Nikolay Kim.

bpo-16285 [https://bugs.python.org/issue?@action=redirect&bpo=16285]: urllib.parse.quote is now based on RFC 3986 and hence includes ‘~’ in the set of characters that is not quoted by default. Patch by Christian Theune and Ratnadeep Debnath.

bpo-29532 [https://bugs.python.org/issue?@action=redirect&bpo=29532]: Altering a kwarg dictionary passed to functools.partial() no longer affects a partial object after creation.

bpo-29110 [https://bugs.python.org/issue?@action=redirect&bpo=29110]: Fix file object leak in aifc.open() when file is given as a filesystem path and is not in valid AIFF format. Patch by Anthony Zhang.

bpo-22807 [https://bugs.python.org/issue?@action=redirect&bpo=22807]: Add uuid.SafeUUID and uuid.UUID.is_safe to relay information from the platform about whether generated UUIDs are generated with a multiprocessing safe method.

bpo-29576 [https://bugs.python.org/issue?@action=redirect&bpo=29576]: Improve some deprecations in importlib. Some deprecated methods now emit DeprecationWarnings and have better descriptive messages.

bpo-29534 [https://bugs.python.org/issue?@action=redirect&bpo=29534]: Fixed different behaviour of Decimal.from_float() for _decimal and _pydecimal. Thanks Andrew Nester.

bpo-10379 [https://bugs.python.org/issue?@action=redirect&bpo=10379]: locale.format_string now supports the ‘monetary’ keyword argument, and locale.format is deprecated.

bpo-29851 [https://bugs.python.org/issue?@action=redirect&bpo=29851]: importlib.reload() now raises ModuleNotFoundError if the module lacks a spec.

bpo-28556 [https://bugs.python.org/issue?@action=redirect&bpo=28556]: Various updates to typing module: typing.Counter, typing.ChainMap, improved ABC caching, etc. Original PRs by Jelle Zijlstra, Ivan Levkivskyi, Manuel Krebber, and Łukasz Langa.

bpo-29100 [https://bugs.python.org/issue?@action=redirect&bpo=29100]: Fix datetime.fromtimestamp() regression introduced in Python 3.6.0: check minimum and maximum years.

bpo-29416 [https://bugs.python.org/issue?@action=redirect&bpo=29416]: Prevent infinite loop in pathlib.Path.mkdir

bpo-29444 [https://bugs.python.org/issue?@action=redirect&bpo=29444]: Fixed out-of-bounds buffer access in the group() method of the match object. Based on patch by WGH.

bpo-29377 [https://bugs.python.org/issue?@action=redirect&bpo=29377]: Add WrapperDescriptorType, MethodWrapperType, and MethodDescriptorType built-in types to types module. Original patch by Manuel Krebber.

bpo-29218 [https://bugs.python.org/issue?@action=redirect&bpo=29218]: Unused install_misc command is now removed. It has been documented as unused since 2000. Patch by Eric N. Vander Weele.

bpo-29368 [https://bugs.python.org/issue?@action=redirect&bpo=29368]: The extend() method is now called instead of the append() method when unpickle collections.deque and other list-like objects. This can speed up unpickling to 2 times.

bpo-29338 [https://bugs.python.org/issue?@action=redirect&bpo=29338]: The help of a builtin or extension class now includes the constructor signature if __text_signature__ is provided for the class.

bpo-29335 [https://bugs.python.org/issue?@action=redirect&bpo=29335]: Fix subprocess.Popen.wait() when the child process has exited to a stopped instead of terminated state (ex: when under ptrace).

bpo-29290 [https://bugs.python.org/issue?@action=redirect&bpo=29290]: Fix a regression in argparse that help messages would wrap at non-breaking spaces.

bpo-28735 [https://bugs.python.org/issue?@action=redirect&bpo=28735]: Fixed the comparison of mock.MagickMock with mock.ANY.

bpo-29197 [https://bugs.python.org/issue?@action=redirect&bpo=29197]: Removed deprecated function ntpath.splitunc().

bpo-29210 [https://bugs.python.org/issue?@action=redirect&bpo=29210]: Removed support of deprecated argument “exclude” in tarfile.TarFile.add().

bpo-29219 [https://bugs.python.org/issue?@action=redirect&bpo=29219]: Fixed infinite recursion in the repr of uninitialized ctypes.CDLL instances.

bpo-29192 [https://bugs.python.org/issue?@action=redirect&bpo=29192]: Removed deprecated features in the http.cookies module.

bpo-29193 [https://bugs.python.org/issue?@action=redirect&bpo=29193]: A format string argument for string.Formatter.format() is now positional-only.

bpo-29195 [https://bugs.python.org/issue?@action=redirect&bpo=29195]: Removed support of deprecated undocumented keyword arguments in methods of regular expression objects.

bpo-28969 [https://bugs.python.org/issue?@action=redirect&bpo=28969]: Fixed race condition in C implementation of functools.lru_cache. KeyError could be raised when cached function with full cache was simultaneously called from differen threads with the same uncached arguments.

bpo-20804 [https://bugs.python.org/issue?@action=redirect&bpo=20804]: The unittest.mock.sentinel attributes now preserve their identity when they are copied or pickled.

bpo-29142 [https://bugs.python.org/issue?@action=redirect&bpo=29142]: In urllib.request, suffixes in no_proxy environment variable with leading dots could match related hostnames again (e.g. .b.c matches a.b.c). Patch by Milan Oberkirch.

bpo-28961 [https://bugs.python.org/issue?@action=redirect&bpo=28961]: Fix unittest.mock._Call helper: don’t ignore the name parameter anymore. Patch written by Jiajun Huang.

bpo-15812 [https://bugs.python.org/issue?@action=redirect&bpo=15812]: inspect.getframeinfo() now correctly shows the first line of a context. Patch by Sam Breese.

bpo-28985 [https://bugs.python.org/issue?@action=redirect&bpo=28985]: Update authorizer constants in sqlite3 module. Patch by Dingyuan Wang.

bpo-29079 [https://bugs.python.org/issue?@action=redirect&bpo=29079]: Prevent infinite loop in pathlib.resolve() on Windows

bpo-13051 [https://bugs.python.org/issue?@action=redirect&bpo=13051]: Fixed recursion errors in large or resized curses.textpad.Textbox. Based on patch by Tycho Andersen.

bpo-9770 [https://bugs.python.org/issue?@action=redirect&bpo=9770]: curses.ascii predicates now work correctly with negative integers.

bpo-28427 [https://bugs.python.org/issue?@action=redirect&bpo=28427]: old keys should not remove new values from WeakValueDictionary when collecting from another thread.

bpo-28923 [https://bugs.python.org/issue?@action=redirect&bpo=28923]: Remove editor artifacts from Tix.py.

bpo-28871 [https://bugs.python.org/issue?@action=redirect&bpo=28871]: Fixed a crash when deallocate deep ElementTree.

bpo-19542 [https://bugs.python.org/issue?@action=redirect&bpo=19542]: Fix bugs in WeakValueDictionary.setdefault() and WeakValueDictionary.pop() when a GC collection happens in another thread.

bpo-20191 [https://bugs.python.org/issue?@action=redirect&bpo=20191]: Fixed a crash in resource.prlimit() when passing a sequence that doesn’t own its elements as limits.

bpo-16255 [https://bugs.python.org/issue?@action=redirect&bpo=16255]: subprocess.Popen uses /system/bin/sh on Android as the shell, instead of /bin/sh.

bpo-28779 [https://bugs.python.org/issue?@action=redirect&bpo=28779]: multiprocessing.set_forkserver_preload() would crash the forkserver process if a preloaded module instantiated some multiprocessing objects such as locks.

bpo-26937 [https://bugs.python.org/issue?@action=redirect&bpo=26937]: The chown() method of the tarfile.TarFile class does not fail now when the grp module cannot be imported, as for example on Android platforms.

bpo-28847 [https://bugs.python.org/issue?@action=redirect&bpo=28847]: dbm.dumb now supports reading read-only files and no longer writes the index file when it is not changed. A deprecation warning is now emitted if the index file is missed and recreated in the ‘r’ and ‘w’ modes (will be an error in future Python releases).

bpo-27030 [https://bugs.python.org/issue?@action=redirect&bpo=27030]: Unknown escapes consisting of '\' and an ASCII letter in re.sub() replacement templates regular expressions now are errors.

bpo-28835 [https://bugs.python.org/issue?@action=redirect&bpo=28835]: Fix a regression introduced in warnings.catch_warnings(): call warnings.showwarning() if it was overridden inside the context manager.

bpo-27172 [https://bugs.python.org/issue?@action=redirect&bpo=27172]: To assist with upgrades from 2.7, the previously documented deprecation of inspect.getfullargspec() has been reversed. This decision may be revisited again after the Python 2.7 branch is no longer officially supported.

bpo-28740 [https://bugs.python.org/issue?@action=redirect&bpo=28740]: Add sys.getandroidapilevel(): return the build time API version of Android as an integer. Function only available on Android.

bpo-26273 [https://bugs.python.org/issue?@action=redirect&bpo=26273]: Add new socket.TCP_CONGESTION (Linux 2.6.13) and socket.TCP_USER_TIMEOUT (Linux 2.6.37) constants. Patch written by Omar Sandoval.

bpo-28752 [https://bugs.python.org/issue?@action=redirect&bpo=28752]: Restored the __reduce__() methods of datetime objects.

bpo-28727 [https://bugs.python.org/issue?@action=redirect&bpo=28727]: Regular expression patterns, _sre.SRE_Pattern objects created by re.compile(), become comparable (only x==y and x!=y operators). This change should fix the bpo-18383 [https://bugs.python.org/issue?@action=redirect&bpo=18383]: don’t duplicate warning filters when the warnings module is reloaded (thing usually only done in unit tests).

bpo-20572 [https://bugs.python.org/issue?@action=redirect&bpo=20572]: Remove the subprocess.Popen.wait endtime parameter. It was deprecated in 3.4 and undocumented prior to that.

bpo-25659 [https://bugs.python.org/issue?@action=redirect&bpo=25659]: In ctypes, prevent a crash calling the from_buffer() and from_buffer_copy() methods on abstract classes like Array.

bpo-28548 [https://bugs.python.org/issue?@action=redirect&bpo=28548]: In the “http.server” module, parse the protocol version if possible, to avoid using HTTP 0.9 in some error responses.

bpo-19717 [https://bugs.python.org/issue?@action=redirect&bpo=19717]: Makes Path.resolve() succeed on paths that do not exist. Patch by Vajrasky Kok

bpo-28563 [https://bugs.python.org/issue?@action=redirect&bpo=28563]: Fixed possible DoS and arbitrary code execution when handle plural form selections in the gettext module. The expression parser now supports exact syntax supported by GNU gettext.

bpo-28387 [https://bugs.python.org/issue?@action=redirect&bpo=28387]: Fixed possible crash in _io.TextIOWrapper deallocator when the garbage collector is invoked in other thread. Based on patch by Sebastian Cufre.

bpo-27517 [https://bugs.python.org/issue?@action=redirect&bpo=27517]: LZMA compressor and decompressor no longer raise exceptions if given empty data twice. Patch by Benjamin Fogle.

bpo-28549 [https://bugs.python.org/issue?@action=redirect&bpo=28549]: Fixed segfault in curses’s addch() with ncurses6.

bpo-28449 [https://bugs.python.org/issue?@action=redirect&bpo=28449]: tarfile.open() with mode “r” or “r:” now tries to open a tar file with compression before trying to open it without compression. Otherwise it had 50% chance failed with ignore_zeros=True.

bpo-23262 [https://bugs.python.org/issue?@action=redirect&bpo=23262]: The webbrowser module now supports Firefox 36+ and derived browsers. Based on patch by Oleg Broytman.

bpo-24241 [https://bugs.python.org/issue?@action=redirect&bpo=24241]: The webbrowser in an X environment now prefers using the default browser directly. Also, the webbrowser register() function now has a documented ‘preferred’ argument, to specify browsers to be returned by get() with no arguments. Patch by David Steele

bpo-27939 [https://bugs.python.org/issue?@action=redirect&bpo=27939]: Fixed bugs in tkinter.ttk.LabeledScale and tkinter.Scale caused by representing the scale as float value internally in Tk. tkinter.IntVar now works if float value is set to underlying Tk variable.

bpo-28255 [https://bugs.python.org/issue?@action=redirect&bpo=28255]: calendar.TextCalendar.prweek() no longer prints a space after a weeks’s calendar. calendar.TextCalendar.pryear() no longer prints redundant newline after a year’s calendar. Based on patch by Xiang Zhang.

bpo-28255 [https://bugs.python.org/issue?@action=redirect&bpo=28255]: calendar.TextCalendar.prmonth() no longer prints a space at the start of new line after printing a month’s calendar. Patch by Xiang Zhang.

bpo-20491 [https://bugs.python.org/issue?@action=redirect&bpo=20491]: The textwrap.TextWrapper class now honors non-breaking spaces. Based on patch by Kaarle Ritvanen.

bpo-28353 [https://bugs.python.org/issue?@action=redirect&bpo=28353]: os.fwalk() no longer fails on broken links.

bpo-28430 [https://bugs.python.org/issue?@action=redirect&bpo=28430]: Fix iterator of C implemented asyncio.Future doesn’t accept non-None value is passed to it.send(val).

bpo-27025 [https://bugs.python.org/issue?@action=redirect&bpo=27025]: Generated names for Tkinter widgets now start by the “!” prefix for readability.

bpo-25464 [https://bugs.python.org/issue?@action=redirect&bpo=25464]: Fixed HList.header_exists() in tkinter.tix module by addin a workaround to Tix library bug.

bpo-28488 [https://bugs.python.org/issue?@action=redirect&bpo=28488]: shutil.make_archive() no longer adds entry “./” to ZIP archive.

bpo-25953 [https://bugs.python.org/issue?@action=redirect&bpo=25953]: re.sub() now raises an error for invalid numerical group reference in replacement template even if the pattern is not found in the string. Error message for invalid group reference now includes the group index and the position of the reference. Based on patch by SilentGhost.

bpo-28469 [https://bugs.python.org/issue?@action=redirect&bpo=28469]: timeit now uses the sequence 1, 2, 5, 10, 20, 50,… instead of 1, 10, 100,… for autoranging.

bpo-28115 [https://bugs.python.org/issue?@action=redirect&bpo=28115]: Command-line interface of the zipfile module now uses argparse. Added support of long options.

bpo-18219 [https://bugs.python.org/issue?@action=redirect&bpo=18219]: Optimize csv.DictWriter for large number of columns. Patch by Mariatta Wijaya.

bpo-28448 [https://bugs.python.org/issue?@action=redirect&bpo=28448]: Fix C implemented asyncio.Future didn’t work on Windows.

bpo-23214 [https://bugs.python.org/issue?@action=redirect&bpo=23214]: In the “io” module, the argument to BufferedReader and BytesIO’s read1() methods is now optional and can be -1, matching the BufferedIOBase specification.

bpo-28480 [https://bugs.python.org/issue?@action=redirect&bpo=28480]: Fix error building socket module when multithreading is disabled.

bpo-28240 [https://bugs.python.org/issue?@action=redirect&bpo=28240]: timeit: remove -c/--clock and -t/--time command line options which were deprecated since Python 3.3.

bpo-28240 [https://bugs.python.org/issue?@action=redirect&bpo=28240]: timeit now repeats the benchmarks 5 times instead of only 3 to make benchmarks more reliable.

bpo-28240 [https://bugs.python.org/issue?@action=redirect&bpo=28240]: timeit autorange now uses a single loop iteration if the benchmark takes less than 10 seconds, instead of 10 iterations. “python3 -m timeit -s ‘import time’ ‘time.sleep(1)’” now takes 4 seconds instead of 40 seconds.

Distutils.sdist now looks for README and setup.py files with case sensitivity. This behavior matches that found in Setuptools 6.0 and later. See setuptools 100 [https://github.com/pypa/setuptools/issues/100] for rationale.

bpo-24452 [https://bugs.python.org/issue?@action=redirect&bpo=24452]: Make webbrowser support Chrome on Mac OS X. Patch by Ned Batchelder.

bpo-20766 [https://bugs.python.org/issue?@action=redirect&bpo=20766]: Fix references leaked by pdb in the handling of SIGINT handlers.

bpo-27998 [https://bugs.python.org/issue?@action=redirect&bpo=27998]: Fixed bytes path support in os.scandir() on Windows. Patch by Eryk Sun.

bpo-28317 [https://bugs.python.org/issue?@action=redirect&bpo=28317]: The disassembler now decodes FORMAT_VALUE argument.

bpo-28380 [https://bugs.python.org/issue?@action=redirect&bpo=28380]: unittest.mock Mock autospec functions now properly support assert_called, assert_not_called, and assert_called_once.

bpo-28229 [https://bugs.python.org/issue?@action=redirect&bpo=28229]: lzma module now supports pathlib.

bpo-28321 [https://bugs.python.org/issue?@action=redirect&bpo=28321]: Fixed writing non-BMP characters with binary format in plistlib.

bpo-28225 [https://bugs.python.org/issue?@action=redirect&bpo=28225]: bz2 module now supports pathlib. Initial patch by Ethan Furman.

bpo-28227 [https://bugs.python.org/issue?@action=redirect&bpo=28227]: gzip now supports pathlib. Patch by Ethan Furman.

bpo-28332 [https://bugs.python.org/issue?@action=redirect&bpo=28332]: Deprecated silent truncations in socket.htons and socket.ntohs. Original patch by Oren Milman.

bpo-27358 [https://bugs.python.org/issue?@action=redirect&bpo=27358]: Optimized merging var-keyword arguments and improved error message when passing a non-mapping as a var-keyword argument.

bpo-28257 [https://bugs.python.org/issue?@action=redirect&bpo=28257]: Improved error message when passing a non-iterable as a var-positional argument. Added opcode BUILD_TUPLE_UNPACK_WITH_CALL.

bpo-28322 [https://bugs.python.org/issue?@action=redirect&bpo=28322]: Fixed possible crashes when unpickle itertools objects from incorrect pickle data. Based on patch by John Leitch.

bpo-28228 [https://bugs.python.org/issue?@action=redirect&bpo=28228]: imghdr now supports pathlib.

bpo-28226 [https://bugs.python.org/issue?@action=redirect&bpo=28226]: compileall now supports pathlib.

bpo-28314 [https://bugs.python.org/issue?@action=redirect&bpo=28314]: Fix function declaration (C flags) for the getiterator() method of xml.etree.ElementTree.Element.

bpo-28148 [https://bugs.python.org/issue?@action=redirect&bpo=28148]: Stop using localtime() and gmtime() in the time module.

Introduced platform independent _PyTime_localtime API that is similar to POSIX localtime_r, but available on all platforms. Patch by Ed Schouten.

bpo-28253 [https://bugs.python.org/issue?@action=redirect&bpo=28253]: Fixed calendar functions for extreme months: 0001-01 and 9999-12.

Methods itermonthdays() and itermonthdays2() are reimplemented so that they don’t call itermonthdates() which can cause datetime.date under/overflow.

bpo-28275 [https://bugs.python.org/issue?@action=redirect&bpo=28275]: Fixed possible use after free in the decompress() methods of the LZMADecompressor and BZ2Decompressor classes. Original patch by John Leitch.

bpo-27897 [https://bugs.python.org/issue?@action=redirect&bpo=27897]: Fixed possible crash in sqlite3.Connection.create_collation() if pass invalid string-like object as a name. Patch by Xiang Zhang.

bpo-18844 [https://bugs.python.org/issue?@action=redirect&bpo=18844]: random.choices() now has k as a keyword-only argument to improve the readability of common cases and come into line with the signature used in other languages.

bpo-18893 [https://bugs.python.org/issue?@action=redirect&bpo=18893]: Fix invalid exception handling in Lib/ctypes/macholib/dyld.py. Patch by Madison May.

bpo-27611 [https://bugs.python.org/issue?@action=redirect&bpo=27611]: Fixed support of default root window in the tkinter.tix module. Added the master parameter in the DisplayStyle constructor.

bpo-27348 [https://bugs.python.org/issue?@action=redirect&bpo=27348]: In the traceback module, restore the formatting of exception messages like “Exception: None”. This fixes a regression introduced in 3.5a2.

bpo-25651 [https://bugs.python.org/issue?@action=redirect&bpo=25651]: Allow falsy values to be used for msg parameter of subTest().

bpo-27778 [https://bugs.python.org/issue?@action=redirect&bpo=27778]: Fix a memory leak in os.getrandom() when the getrandom() is interrupted by a signal and a signal handler raises a Python exception.

bpo-28200 [https://bugs.python.org/issue?@action=redirect&bpo=28200]: Fix memory leak on Windows in the os module (fix path_converter() function).

bpo-25400 [https://bugs.python.org/issue?@action=redirect&bpo=25400]: RobotFileParser now correctly returns default values for crawl_delay and request_rate. Initial patch by Peter Wirtz.

bpo-27932 [https://bugs.python.org/issue?@action=redirect&bpo=27932]: Prevent memory leak in win32_ver().

Fix UnboundLocalError in socket._sendfile_use_sendfile.

bpo-28075 [https://bugs.python.org/issue?@action=redirect&bpo=28075]: Check for ERROR_ACCESS_DENIED in Windows implementation of os.stat(). Patch by Eryk Sun.

bpo-22493 [https://bugs.python.org/issue?@action=redirect&bpo=22493]: Warning message emitted by using inline flags in the middle of regular expression now contains a (truncated) regex pattern. Patch by Tim Graham.

bpo-25270 [https://bugs.python.org/issue?@action=redirect&bpo=25270]: Prevent codecs.escape_encode() from raising SystemError when an empty bytestring is passed.

bpo-28181 [https://bugs.python.org/issue?@action=redirect&bpo=28181]: Get antigravity over HTTPS. Patch by Kaartic Sivaraam.

bpo-25895 [https://bugs.python.org/issue?@action=redirect&bpo=25895]: Enable WebSocket URL schemes in urllib.parse.urljoin. Patch by Gergely Imreh and Markus Holtermann.

bpo-28114 [https://bugs.python.org/issue?@action=redirect&bpo=28114]: Fix a crash in parse_envlist() when env contains byte strings. Patch by Eryk Sun.

bpo-27599 [https://bugs.python.org/issue?@action=redirect&bpo=27599]: Fixed buffer overrun in binascii.b2a_qp() and binascii.a2b_qp().

bpo-27906 [https://bugs.python.org/issue?@action=redirect&bpo=27906]: Fix socket accept exhaustion during high TCP traffic. Patch by Kevin Conway.

bpo-28174 [https://bugs.python.org/issue?@action=redirect&bpo=28174]: Handle when SO_REUSEPORT isn’t properly supported. Patch by Seth Michael Larson.

bpo-26654 [https://bugs.python.org/issue?@action=redirect&bpo=26654]: Inspect functools.partial in asyncio.Handle.__repr__. Patch by iceboy.

bpo-26909 [https://bugs.python.org/issue?@action=redirect&bpo=26909]: Fix slow pipes IO in asyncio. Patch by INADA Naoki.

bpo-28176 [https://bugs.python.org/issue?@action=redirect&bpo=28176]: Fix callbacks race in asyncio.SelectorLoop.sock_connect.

bpo-27759 [https://bugs.python.org/issue?@action=redirect&bpo=27759]: Fix selectors incorrectly retain invalid file descriptors. Patch by Mark Williams.

bpo-28325 [https://bugs.python.org/issue?@action=redirect&bpo=28325]: Remove vestigial MacOS 9 macurl2path module and its tests.

bpo-28368 [https://bugs.python.org/issue?@action=redirect&bpo=28368]: Refuse monitoring processes if the child watcher has no loop attached. Patch by Vincent Michel.

bpo-28369 [https://bugs.python.org/issue?@action=redirect&bpo=28369]: Raise RuntimeError when transport’s FD is used with add_reader, add_writer, etc.

bpo-28370 [https://bugs.python.org/issue?@action=redirect&bpo=28370]: Speedup asyncio.StreamReader.readexactly. Patch by Коренберг Марк.

bpo-28371 [https://bugs.python.org/issue?@action=redirect&bpo=28371]: Deprecate passing asyncio.Handles to run_in_executor.

bpo-28372 [https://bugs.python.org/issue?@action=redirect&bpo=28372]: Fix asyncio to support formatting of non-python coroutines.

bpo-28399 [https://bugs.python.org/issue?@action=redirect&bpo=28399]: Remove UNIX socket from FS before binding. Patch by Коренберг Марк.

bpo-27972 [https://bugs.python.org/issue?@action=redirect&bpo=27972]: Prohibit Tasks to await on themselves.

bpo-24142 [https://bugs.python.org/issue?@action=redirect&bpo=24142]: Reading a corrupt config file left configparser in an invalid state. Original patch by Florian Höch.

bpo-29581 [https://bugs.python.org/issue?@action=redirect&bpo=29581]: ABCMeta.__new__ now accepts **kwargs, allowing abstract base classes to use keyword parameters in __init_subclass__. Patch by Nate Soares.

bpo-25532 [https://bugs.python.org/issue?@action=redirect&bpo=25532]: inspect.unwrap() will now only try to unwrap an object sys.getrecursionlimit() times, to protect against objects which create a new object on every attribute access.

bpo-30177 [https://bugs.python.org/issue?@action=redirect&bpo=30177]: path.resolve(strict=False) no longer cuts the path after the first element not present in the filesystem. Patch by Antoine Pietri.

Documentation

bpo-31294 [https://bugs.python.org/issue?@action=redirect&bpo=31294]: Fix incomplete code snippet in the ZeroMQSocketListener and ZeroMQSocketHandler examples and adapt them to Python 3.

bpo-21649 [https://bugs.python.org/issue?@action=redirect&bpo=21649]: Add RFC 7525 and Mozilla server side TLS links to SSL documentation.

bpo-31128 [https://bugs.python.org/issue?@action=redirect&bpo=31128]: Allow the pydoc server to bind to arbitrary hostnames.

bpo-30803 [https://bugs.python.org/issue?@action=redirect&bpo=30803]: Clarify doc on truth value testing. Original patch by Peter Thomassen.

bpo-30176 [https://bugs.python.org/issue?@action=redirect&bpo=30176]: Add missing attribute related constants in curses documentation.

bpo-30052 [https://bugs.python.org/issue?@action=redirect&bpo=30052]: the link targets for bytes() and bytearray() are now their respective type definitions, rather than the corresponding builtin function entries. Use bytes and bytearray to reference the latter.

In order to ensure this and future cross-reference updates are applied automatically, the daily documentation builds now disable the default output caching features in Sphinx.

bpo-26985 [https://bugs.python.org/issue?@action=redirect&bpo=26985]: Add missing info of code object in inspect documentation.

bpo-19824 [https://bugs.python.org/issue?@action=redirect&bpo=19824]: Improve the documentation for, and links to, template strings by emphasizing their utility for internationalization, and by clarifying some usage constraints. (See also: bpo-20314 [https://bugs.python.org/issue?@action=redirect&bpo=20314], bpo-12518 [https://bugs.python.org/issue?@action=redirect&bpo=12518])

bpo-28929 [https://bugs.python.org/issue?@action=redirect&bpo=28929]: Link the documentation to its source file on GitHub.

bpo-25008 [https://bugs.python.org/issue?@action=redirect&bpo=25008]: Document smtpd.py as effectively deprecated and add a pointer to aiosmtpd, a third-party asyncio-based replacement.

bpo-26355 [https://bugs.python.org/issue?@action=redirect&bpo=26355]: Add canonical header link on each page to corresponding major version of the documentation. Patch by Matthias Bussonnier.

bpo-29349 [https://bugs.python.org/issue?@action=redirect&bpo=29349]: Fix Python 2 syntax in code for building the documentation.

bpo-23722 [https://bugs.python.org/issue?@action=redirect&bpo=23722]: The data model reference and the porting section in the 3.6 What’s New guide now cover the additional __classcell__ handling needed for custom metaclasses to fully support PEP 487 and zero-argument super().

bpo-28513 [https://bugs.python.org/issue?@action=redirect&bpo=28513]: Documented command-line interface of zipfile.

Tests

bpo-29639 [https://bugs.python.org/issue?@action=redirect&bpo=29639]: test.support.HOST is now “localhost”, a new HOSTv4 constant has been added for your 127.0.0.1 needs, similar to the existing HOSTv6 constant.

bpo-31320 [https://bugs.python.org/issue?@action=redirect&bpo=31320]: Silence traceback in test_ssl

bpo-31346 [https://bugs.python.org/issue?@action=redirect&bpo=31346]: Prefer PROTOCOL_TLS_CLIENT and PROTOCOL_TLS_SERVER protocols for SSLContext.

bpo-25674 [https://bugs.python.org/issue?@action=redirect&bpo=25674]: Remove sha256.tbs-internet.com ssl test

bpo-30715 [https://bugs.python.org/issue?@action=redirect&bpo=30715]: Address ALPN callback changes for OpenSSL 1.1.0f. The latest version behaves like OpenSSL 1.0.2 and no longer aborts handshake.

bpo-30822 [https://bugs.python.org/issue?@action=redirect&bpo=30822]: regrtest: Exclude tzdata from regrtest –all. When running the test suite using –use=all / -u all, exclude tzdata since it makes test_datetime too slow (15-20 min on some buildbots) which then times out on some buildbots. Fix also regrtest command line parser to allow passing -u extralargefile to run test_zipfile64.

bpo-30695 [https://bugs.python.org/issue?@action=redirect&bpo=30695]: Add the set_nomemory(start, stop) and remove_mem_hooks() functions to the _testcapi module.

bpo-30357 [https://bugs.python.org/issue?@action=redirect&bpo=30357]: test_thread: setUp() now uses support.threading_setup() and support.threading_cleanup() to wait until threads complete to avoid random side effects on following tests. Initial patch written by Grzegorz Grzywacz.

bpo-30197 [https://bugs.python.org/issue?@action=redirect&bpo=30197]: Enhanced functions swap_attr() and swap_item() in the test.support module. They now work when delete replaced attribute or item inside the with statement. The old value of the attribute or item (or None if it doesn’t exist) now will be assigned to the target of the “as” clause, if there is one.

bpo-24932 [https://bugs.python.org/issue?@action=redirect&bpo=24932]: Use proper command line parsing in _testembed

bpo-28950 [https://bugs.python.org/issue?@action=redirect&bpo=28950]: Disallow -j0 to be combined with -T/-l in regrtest command line arguments.

bpo-28683 [https://bugs.python.org/issue?@action=redirect&bpo=28683]: Fix the tests that bind() a unix socket and raise PermissionError on Android for a non-root user.

bpo-26936 [https://bugs.python.org/issue?@action=redirect&bpo=26936]: Fix the test_socket failures on Android - getservbyname(), getservbyport() and getaddrinfo() are broken on some Android API levels.

bpo-28666 [https://bugs.python.org/issue?@action=redirect&bpo=28666]: Now test.support.rmtree is able to remove unwritable or unreadable directories.

bpo-23839 [https://bugs.python.org/issue?@action=redirect&bpo=23839]: Various caches now are cleared before running every test file.

bpo-26944 [https://bugs.python.org/issue?@action=redirect&bpo=26944]: Fix test_posix for Android where ‘id -G’ is entirely wrong or missing the effective gid.

bpo-28409 [https://bugs.python.org/issue?@action=redirect&bpo=28409]: regrtest: fix the parser of command line arguments.

bpo-28217 [https://bugs.python.org/issue?@action=redirect&bpo=28217]: Adds _testconsole module to test console input.

bpo-26939 [https://bugs.python.org/issue?@action=redirect&bpo=26939]: Add the support.setswitchinterval() function to fix test_functools hanging on the Android armv7 qemu emulator.

Build

bpo-31354 [https://bugs.python.org/issue?@action=redirect&bpo=31354]: Allow –with-lto to be used on all builds, not just make profile-opt.

bpo-31370 [https://bugs.python.org/issue?@action=redirect&bpo=31370]: Remove support for building –without-threads.

This option is not really useful anymore in the 21st century. Removing lots of conditional paths allows us to simplify the code base, including in difficult to maintain low-level internal code.

bpo-31341 [https://bugs.python.org/issue?@action=redirect&bpo=31341]: Per PEP 11, support for the IRIX operating system was removed.

bpo-30854 [https://bugs.python.org/issue?@action=redirect&bpo=30854]: Fix compile error when compiling –without-threads. Patch by Masayuki Yamamoto.

bpo-30687 [https://bugs.python.org/issue?@action=redirect&bpo=30687]: Locate msbuild.exe on Windows when building rather than vcvarsall.bat

bpo-20210 [https://bugs.python.org/issue?@action=redirect&bpo=20210]: Support the disabled marker in Setup files. Extension modules listed after this marker are not built at all, neither by the Makefile nor by setup.py.

bpo-29941 [https://bugs.python.org/issue?@action=redirect&bpo=29941]: Add --with-assertions configure flag to explicitly enable C assert() checks. Defaults to off. --with-pydebug implies --with-assertions.

bpo-28787 [https://bugs.python.org/issue?@action=redirect&bpo=28787]: Fix out-of-tree builds of Python when configured with --with--dtrace.

bpo-29243 [https://bugs.python.org/issue?@action=redirect&bpo=29243]: Prevent unnecessary rebuilding of Python during make test, make install and some other make targets when configured with --enable-optimizations.

bpo-23404 [https://bugs.python.org/issue?@action=redirect&bpo=23404]: Don’t regenerate generated files based on file modification time anymore: the action is now explicit. Replace make touch with make regen-all.

bpo-29643 [https://bugs.python.org/issue?@action=redirect&bpo=29643]: Fix --enable-optimization didn’t work.

bpo-27593 [https://bugs.python.org/issue?@action=redirect&bpo=27593]: sys.version and the platform module python_build(), python_branch(), and python_revision() functions now use git information rather than hg when building from a repo.

bpo-29572 [https://bugs.python.org/issue?@action=redirect&bpo=29572]: Update Windows build and OS X installers to use OpenSSL 1.0.2k.

bpo-27659 [https://bugs.python.org/issue?@action=redirect&bpo=27659]: Prohibit implicit C function declarations: use -Werror=implicit-function-declaration when possible (GCC and Clang, but it depends on the compiler version). Patch written by Chi Hsuan Yen.

bpo-29384 [https://bugs.python.org/issue?@action=redirect&bpo=29384]: Remove old Be OS helper scripts.

bpo-26851 [https://bugs.python.org/issue?@action=redirect&bpo=26851]: Set Android compilation and link flags.

bpo-28768 [https://bugs.python.org/issue?@action=redirect&bpo=28768]: Fix implicit declaration of function _setmode. Patch by Masayuki Yamamoto

bpo-29080 [https://bugs.python.org/issue?@action=redirect&bpo=29080]: Removes hard dependency on hg.exe from PCBuild/build.bat

bpo-23903 [https://bugs.python.org/issue?@action=redirect&bpo=23903]: Added missed names to PC/python3.def.

bpo-28762 [https://bugs.python.org/issue?@action=redirect&bpo=28762]: lockf() is available on Android API level 24, but the F_LOCK macro is not defined in android-ndk-r13.

bpo-28538 [https://bugs.python.org/issue?@action=redirect&bpo=28538]: Fix the compilation error that occurs because if_nameindex() is available on Android API level 24, but the if_nameindex structure is not defined.

bpo-20211 [https://bugs.python.org/issue?@action=redirect&bpo=20211]: Do not add the directory for installing C header files and the directory for installing object code libraries to the cross compilation search paths. Original patch by Thomas Petazzoni.

bpo-28849 [https://bugs.python.org/issue?@action=redirect&bpo=28849]: Do not define sys.implementation._multiarch on Android.

bpo-10656 [https://bugs.python.org/issue?@action=redirect&bpo=10656]: Fix out-of-tree building on AIX. Patch by Tristan Carel and Michael Haubenwallner.

bpo-26359 [https://bugs.python.org/issue?@action=redirect&bpo=26359]: Rename –with-optimiations to –enable-optimizations.

bpo-28444 [https://bugs.python.org/issue?@action=redirect&bpo=28444]: Fix missing extensions modules when cross compiling.

bpo-28208 [https://bugs.python.org/issue?@action=redirect&bpo=28208]: Update Windows build and OS X installers to use SQLite 3.14.2.

bpo-28248 [https://bugs.python.org/issue?@action=redirect&bpo=28248]: Update Windows build and OS X installers to use OpenSSL 1.0.2j.

bpo-21124 [https://bugs.python.org/issue?@action=redirect&bpo=21124]: Fix building the _struct module on Cygwin by passing NULL instead of &PyType_Type to PyVarObject_HEAD_INIT. Patch by Masayuki Yamamoto.

bpo-13756 [https://bugs.python.org/issue?@action=redirect&bpo=13756]: Fix building extensions modules on Cygwin. Patch by Roumen Petrov, based on original patch by Jason Tishler.

bpo-21085 [https://bugs.python.org/issue?@action=redirect&bpo=21085]: Add configure check for siginfo_t.si_band, which Cygwin does not provide. Patch by Masayuki Yamamoto with review and rebase by Erik Bray.

bpo-28258 [https://bugs.python.org/issue?@action=redirect&bpo=28258]: Fixed build with Estonian locale (python-config and distclean targets in Makefile). Patch by Arfrever Frehtes Taifersar Arahesis.

bpo-26661 [https://bugs.python.org/issue?@action=redirect&bpo=26661]: setup.py now detects system libffi with multiarch wrapper.

bpo-27979 [https://bugs.python.org/issue?@action=redirect&bpo=27979]: A full copy of libffi is no longer bundled for use when building _ctypes on non-OSX UNIX platforms. An installed copy of libffi is now required when building _ctypes on such platforms.

bpo-15819 [https://bugs.python.org/issue?@action=redirect&bpo=15819]: Remove redundant include search directory option for building outside the source tree.

bpo-28676 [https://bugs.python.org/issue?@action=redirect&bpo=28676]: Prevent missing ‘getentropy’ declaration warning on macOS. Patch by Gareth Rees.

Windows

bpo-31392 [https://bugs.python.org/issue?@action=redirect&bpo=31392]: Update Windows build to use OpenSSL 1.1.0f

bpo-30389 [https://bugs.python.org/issue?@action=redirect&bpo=30389]: Adds detection of Visual Studio 2017 to distutils on Windows.

bpo-31358 [https://bugs.python.org/issue?@action=redirect&bpo=31358]: zlib is no longer bundled in the CPython source, instead it is downloaded on demand just like bz2, lzma, OpenSSL, Tcl/Tk, and SQLite.

bpo-31340 [https://bugs.python.org/issue?@action=redirect&bpo=31340]: Change to building with MSVC v141 (included with Visual Studio 2017)

bpo-30581 [https://bugs.python.org/issue?@action=redirect&bpo=30581]: os.cpu_count() now returns the correct number of processors on Windows when the number of logical processors is greater than 64.

bpo-30916 [https://bugs.python.org/issue?@action=redirect&bpo=30916]: Pre-build OpenSSL, Tcl and Tk and include the binaries in the build.

bpo-30731 [https://bugs.python.org/issue?@action=redirect&bpo=30731]: Add a missing xmlns to python.manifest so that it matches the schema.

bpo-30291 [https://bugs.python.org/issue?@action=redirect&bpo=30291]: Allow requiring 64-bit interpreters from py.exe using -64 suffix. Contributed by Steve (Gadget) Barnes.

bpo-30362 [https://bugs.python.org/issue?@action=redirect&bpo=30362]: Adds list options (-0, -0p) to py.exe launcher. Contributed by Steve Barnes.

bpo-23451 [https://bugs.python.org/issue?@action=redirect&bpo=23451]: Fix socket deprecation warnings in socketmodule.c. Patch by Segev Finer.

bpo-30450 [https://bugs.python.org/issue?@action=redirect&bpo=30450]: The build process on Windows no longer depends on Subversion, instead pulling external code from GitHub via a Python script. If Python 3.6 is not found on the system (via py -3.6), NuGet is used to download a copy of 32-bit Python.

bpo-29579 [https://bugs.python.org/issue?@action=redirect&bpo=29579]: Removes readme.txt from the installer.

bpo-25778 [https://bugs.python.org/issue?@action=redirect&bpo=25778]: winreg does not truncate string correctly (Patch by Eryk Sun)

bpo-28896 [https://bugs.python.org/issue?@action=redirect&bpo=28896]: Deprecate WindowsRegistryFinder and disable it by default

bpo-28522 [https://bugs.python.org/issue?@action=redirect&bpo=28522]: Fixes mishandled buffer reallocation in getpathp.c

bpo-28402 [https://bugs.python.org/issue?@action=redirect&bpo=28402]: Adds signed catalog files for stdlib on Windows.

bpo-28333 [https://bugs.python.org/issue?@action=redirect&bpo=28333]: Enables Unicode for ps1/ps2 and input() prompts. (Patch by Eryk Sun)

bpo-28251 [https://bugs.python.org/issue?@action=redirect&bpo=28251]: Improvements to help manuals on Windows.

bpo-28110 [https://bugs.python.org/issue?@action=redirect&bpo=28110]: launcher.msi has different product codes between 32-bit and 64-bit

bpo-28161 [https://bugs.python.org/issue?@action=redirect&bpo=28161]: Opening CON for write access fails

bpo-28162 [https://bugs.python.org/issue?@action=redirect&bpo=28162]: WindowsConsoleIO readall() fails if first line starts with Ctrl+Z

bpo-28163 [https://bugs.python.org/issue?@action=redirect&bpo=28163]: WindowsConsoleIO fileno() passes wrong flags to _open_osfhandle

bpo-28164 [https://bugs.python.org/issue?@action=redirect&bpo=28164]: _PyIO_get_console_type fails for various paths

bpo-28137 [https://bugs.python.org/issue?@action=redirect&bpo=28137]: Renames Windows path file to ._pth

bpo-28138 [https://bugs.python.org/issue?@action=redirect&bpo=28138]: Windows ._pth file should allow import site

IDLE

bpo-31493 [https://bugs.python.org/issue?@action=redirect&bpo=31493]: IDLE code context – fix code update and font update timers.

Canceling timers prevents a warning message when test_idle completes.

bpo-31488 [https://bugs.python.org/issue?@action=redirect&bpo=31488]: IDLE - Update non-key options in former extension classes. When applying configdialog changes, call .reload for each feature class. Change ParenMatch so updated options affect existing instances attached to existing editor windows.

bpo-31477 [https://bugs.python.org/issue?@action=redirect&bpo=31477]: IDLE - Improve rstrip entry in doc. Strip trailing whitespace strips more than blank spaces. Multiline string literals are not skipped.

bpo-31480 [https://bugs.python.org/issue?@action=redirect&bpo=31480]: IDLE - make tests pass with zzdummy extension disabled by default.

bpo-31421 [https://bugs.python.org/issue?@action=redirect&bpo=31421]: Document how IDLE runs tkinter programs. IDLE calls tcl/tk update in the background in order to make live

interaction and experimentation with tkinter applications much easier.

bpo-31414 [https://bugs.python.org/issue?@action=redirect&bpo=31414]: IDLE – fix tk entry box tests by deleting first. Adding to an int entry is not the same as deleting and inserting because int(‘’) will fail.

bpo-31051 [https://bugs.python.org/issue?@action=redirect&bpo=31051]: Rearrange IDLE configdialog GenPage into Window, Editor, and Help sections.

bpo-30617 [https://bugs.python.org/issue?@action=redirect&bpo=30617]: IDLE - Add docstrings and tests for outwin subclass of editor.

Move some data and functions from the class to module level. Patch by Cheryl Sabella.

bpo-31287 [https://bugs.python.org/issue?@action=redirect&bpo=31287]: IDLE - Do not modify tkinter.message in test_configdialog.

bpo-27099 [https://bugs.python.org/issue?@action=redirect&bpo=27099]: Convert IDLE’s built-in ‘extensions’ to regular features.

About 10 IDLE features were implemented as supposedly optional extensions. Their different behavior could be confusing or worse for users and not good for maintenance. Hence the conversion.

The main difference for users is that user configurable key bindings for builtin features are now handled uniformly. Now, editing a binding in a keyset only affects its value in the keyset. All bindings are defined together in the system-specific default keysets in config-extensions.def. All custom keysets are saved as a whole in config-extension.cfg. All take effect as soon as one clicks Apply or Ok.

The affected events are ‘<<force-open-completions>>’, ‘<<expand-word>>’, ‘<<force-open-calltip>>’, ‘<<flash-paren>>’, ‘<<format-paragraph>>’, ‘<<run-module>>’, ‘<<check-module>>’, and ‘<<zoom-height>>’. Any (global) customizations made before 3.6.3 will not affect their keyset-specific customization after 3.6.3. and vice versa.

Initial patch by Charles Wohlganger.

bpo-31206 [https://bugs.python.org/issue?@action=redirect&bpo=31206]: IDLE: Factor HighPage(Frame) class from ConfigDialog. Patch by Cheryl Sabella.

bpo-31001 [https://bugs.python.org/issue?@action=redirect&bpo=31001]: Add tests for configdialog highlight tab. Patch by Cheryl Sabella.

bpo-31205 [https://bugs.python.org/issue?@action=redirect&bpo=31205]: IDLE: Factor KeysPage(Frame) class from ConfigDialog. The slightly modified tests continue to pass. Patch by Cheryl Sabella.

bpo-31130 [https://bugs.python.org/issue?@action=redirect&bpo=31130]: IDLE – stop leaks in test_configdialog. Initial patch by Victor Stinner.

bpo-31002 [https://bugs.python.org/issue?@action=redirect&bpo=31002]: Add tests for configdialog keys tab. Patch by Cheryl Sabella.

bpo-19903 [https://bugs.python.org/issue?@action=redirect&bpo=19903]: IDLE: Calltips use inspect.signature instead of inspect.getfullargspec. This improves calltips for builtins converted to use Argument Clinic. Patch by Louie Lu.

bpo-31083 [https://bugs.python.org/issue?@action=redirect&bpo=31083]: IDLE - Add an outline of a TabPage class in configdialog. Update existing classes to match outline. Initial patch by Cheryl Sabella.

bpo-31050 [https://bugs.python.org/issue?@action=redirect&bpo=31050]: Factor GenPage(Frame) class from ConfigDialog. The slightly modified tests continue to pass. Patch by Cheryl Sabella.

bpo-31004 [https://bugs.python.org/issue?@action=redirect&bpo=31004]: IDLE - Factor FontPage(Frame) class from ConfigDialog.

Slightly modified tests continue to pass. Fix General tests. Patch mostly by Cheryl Sabella.

bpo-30781 [https://bugs.python.org/issue?@action=redirect&bpo=30781]: IDLE - Use ttk widgets in ConfigDialog. Patches by Terry Jan Reedy and Cheryl Sabella.

bpo-31060 [https://bugs.python.org/issue?@action=redirect&bpo=31060]: IDLE - Finish rearranging methods of ConfigDialog Grouping methods pertaining to each tab and the buttons will aid writing tests and improving the tabs and will enable splitting the groups into classes.

bpo-30853 [https://bugs.python.org/issue?@action=redirect&bpo=30853]: IDLE – Factor a VarTrace class out of ConfigDialog.

Instance tracers manages pairs consisting of a tk variable and a callback function. When tracing is turned on, setting the variable calls the function. Test coverage for the new class is 100%.

bpo-31003 [https://bugs.python.org/issue?@action=redirect&bpo=31003]: IDLE: Add more tests for General tab.

bpo-30993 [https://bugs.python.org/issue?@action=redirect&bpo=30993]: IDLE - Improve configdialog font page and tests.

In configdialog: Document causal pathways in create_font_tab docstring. Simplify some attribute names. Move set_samples calls to var_changed_font (idea from Cheryl Sabella). Move related functions to positions after the create widgets function.

In test_configdialog: Fix test_font_set so not order dependent. Fix renamed test_indent_scale so it tests the widget. Adjust tests for movement of set_samples call. Add tests for load functions. Put all font tests in one class and tab indent tests in another. Except for two lines, these tests completely cover the related functions.

bpo-30981 [https://bugs.python.org/issue?@action=redirect&bpo=30981]: IDLE – Add more configdialog font page tests.

bpo-28523 [https://bugs.python.org/issue?@action=redirect&bpo=28523]: IDLE: replace ‘colour’ with ‘color’ in configdialog.

bpo-30917 [https://bugs.python.org/issue?@action=redirect&bpo=30917]: Add tests for idlelib.config.IdleConf. Increase coverage from 46% to 96%. Patch by Louie Lu.

bpo-30934 [https://bugs.python.org/issue?@action=redirect&bpo=30934]: Document coverage details for idlelib tests.

Add section to idlelib/idle-test/README.txt.

Include check that branches are taken both ways.

Exclude IDLE-specific code that does not run during unit tests.

bpo-30913 [https://bugs.python.org/issue?@action=redirect&bpo=30913]: IDLE: Document ConfigDialog tk Vars, methods, and widgets in docstrings This will facilitate improving the dialog and splitting up the class. Original patch by Cheryl Sabella.

bpo-30899 [https://bugs.python.org/issue?@action=redirect&bpo=30899]: IDLE: Add tests for ConfigParser subclasses in config. Patch by Louie Lu.

bpo-30881 [https://bugs.python.org/issue?@action=redirect&bpo=30881]: IDLE: Add docstrings to browser.py. Patch by Cheryl Sabella.

bpo-30851 [https://bugs.python.org/issue?@action=redirect&bpo=30851]: IDLE: Remove unused variables in configdialog. One is a duplicate, one is set but cannot be altered by users. Patch by Cheryl Sabella.

bpo-30870 [https://bugs.python.org/issue?@action=redirect&bpo=30870]: IDLE: In Settings dialog, select font with Up, Down keys as well as mouse. Initial patch by Louie Lu.

bpo-8231 [https://bugs.python.org/issue?@action=redirect&bpo=8231]: IDLE: call config.IdleConf.GetUserCfgDir only once.

bpo-30779 [https://bugs.python.org/issue?@action=redirect&bpo=30779]: IDLE: Factor ConfigChanges class from configdialog, put in config; test. * In config, put dump test code in a function; run it and unittest in ‘if __name__ == ‘__main__’. * Add class config.ConfigChanges based on changes_class_v4.py on bpo issue. * Add class test_config.ChangesTest, partly using configdialog_tests_v1.py. * Revise configdialog to use ConfigChanges; see tracker msg297804. * Revise test_configdialog to match configdialog changes. * Remove configdialog functions unused or moved to ConfigChanges. Cheryl Sabella contributed parts of the patch.

bpo-30777 [https://bugs.python.org/issue?@action=redirect&bpo=30777]: IDLE: configdialog - Add docstrings and fix comments. Patch by Cheryl Sabella.

bpo-30495 [https://bugs.python.org/issue?@action=redirect&bpo=30495]: IDLE: Improve textview with docstrings, PEP8 names, and more tests. Patch by Cheryl Sabella.

bpo-30723 [https://bugs.python.org/issue?@action=redirect&bpo=30723]: IDLE: Make several improvements to parenmatch. Add ‘parens’ style to highlight both opener and closer. Make ‘default’ style, which is not default, a synonym for ‘opener’. Make time-delay work the same with all styles. Add help for config dialog extensions tab, including help for parenmatch. Add new tests. Original patch by Charles Wohlganger.

bpo-30674 [https://bugs.python.org/issue?@action=redirect&bpo=30674]: IDLE: add docstrings to grep module. Patch by Cheryl Sabella

bpo-21519 [https://bugs.python.org/issue?@action=redirect&bpo=21519]: IDLE’s basic custom key entry dialog now detects duplicates properly. Original patch by Saimadhav Heblikar.

bpo-29910 [https://bugs.python.org/issue?@action=redirect&bpo=29910]: IDLE no longer deletes a character after commenting out a region by a key shortcut. Add return 'break' for this and other potential conflicts between IDLE and default key bindings.

bpo-30728 [https://bugs.python.org/issue?@action=redirect&bpo=30728]: Review and change idlelib.configdialog names. Lowercase method and attribute names. Replace ‘colour’ with ‘color’, expand overly cryptic names, delete unneeded underscores. Replace import * with specific imports. Patches by Cheryl Sabella.

bpo-6739 [https://bugs.python.org/issue?@action=redirect&bpo=6739]: IDLE: Verify user-entered key sequences by trying to bind them with tk. Add tests for all 3 validation functions. Original patch by G Polo. Tests added by Cheryl Sabella.

bpo-15786 [https://bugs.python.org/issue?@action=redirect&bpo=15786]: Fix several problems with IDLE’s autocompletion box. The following should now work: clicking on selection box items; using the scrollbar; selecting an item by hitting Return. Hangs on MacOSX should no longer happen. Patch by Louie Lu.

bpo-25514 [https://bugs.python.org/issue?@action=redirect&bpo=25514]: Add doc subsubsection about IDLE failure to start. Popup no-connection message directs users to this section.

bpo-30642 [https://bugs.python.org/issue?@action=redirect&bpo=30642]: Fix reference leaks in IDLE tests. Patches by Louie Lu and Terry Jan Reedy.

bpo-30495 [https://bugs.python.org/issue?@action=redirect&bpo=30495]: Add docstrings for textview.py and use PEP8 names. Patches by Cheryl Sabella and Terry Jan Reedy.

bpo-30290 [https://bugs.python.org/issue?@action=redirect&bpo=30290]: Help-about: use pep8 names and add tests. Increase coverage to 100%. Patches by Louie Lu, Cheryl Sabella, and Terry Jan Reedy.

bpo-30303 [https://bugs.python.org/issue?@action=redirect&bpo=30303]: Add _utest option to textview; add new tests. Increase coverage to 100%. Patches by Louie Lu and Terry Jan Reedy.

bpo-29071 [https://bugs.python.org/issue?@action=redirect&bpo=29071]: IDLE colors f-string prefixes (but not invalid ur prefixes).

bpo-28572 [https://bugs.python.org/issue?@action=redirect&bpo=28572]: Add 10% to coverage of IDLE’s test_configdialog. Update and augment description of the configuration system.

Tools/Demos

bpo-30983 [https://bugs.python.org/issue?@action=redirect&bpo=30983]: gdb integration commands (py-bt, etc.) work on optimized shared builds now, too. PEP 523 introduced _PyEval_EvalFrameDefault which inlines PyEval_EvalFrameEx on non-debug shared builds. This broke the ability to use py-bt, py-up, and a few other Python-specific gdb integrations. The problem is fixed by only looking for _PyEval_EvalFrameDefault frames in python-gdb.py. Original patch by Bruno “Polaco” Penteado.

bpo-29748 [https://bugs.python.org/issue?@action=redirect&bpo=29748]: Added the slice index converter in Argument Clinic.

bpo-24037 [https://bugs.python.org/issue?@action=redirect&bpo=24037]: Argument Clinic now uses the converter bool(accept={int}) rather than int for semantical booleans. This avoids repeating the default value for Python and C and will help in converting to bool in future.

bpo-29367 [https://bugs.python.org/issue?@action=redirect&bpo=29367]: python-gdb.py now supports also method-wrapper (wrapperobject) objects.

bpo-28023 [https://bugs.python.org/issue?@action=redirect&bpo=28023]: Fix python-gdb.py didn’t support new dict implementation.

bpo-15369 [https://bugs.python.org/issue?@action=redirect&bpo=15369]: The pybench and pystone microbenchmark have been removed from Tools. Please use the new Python benchmark suite https://github.com/python/performance which is more reliable and includes a portable version of pybench working on Python 2 and Python 3.

bpo-28102 [https://bugs.python.org/issue?@action=redirect&bpo=28102]: The zipfile module CLI now prints usage to stderr. Patch by Stephen J. Turnbull.

C API

bpo-31338 [https://bugs.python.org/issue?@action=redirect&bpo=31338]: Added the Py_UNREACHABLE() macro for code paths which are never expected to be reached. This and a few other useful macros are now documented in the C API manual.

bpo-30832 [https://bugs.python.org/issue?@action=redirect&bpo=30832]: Remove own implementation for thread-local storage.

CPython has provided the own implementation for thread-local storage (TLS) on Python/thread.c, it’s used in the case which a platform has not supplied native TLS. However, currently all supported platforms (Windows and pthreads) have provided native TLS and defined the Py_HAVE_NATIVE_TLS macro with unconditional in any case.

bpo-30708 [https://bugs.python.org/issue?@action=redirect&bpo=30708]: PyUnicode_AsWideCharString() now raises a ValueError if the second argument is NULL and the wchar_t* string contains null characters.

bpo-16500 [https://bugs.python.org/issue?@action=redirect&bpo=16500]: Deprecate PyOS_AfterFork() and add PyOS_BeforeFork(), PyOS_AfterFork_Parent() and PyOS_AfterFork_Child().

bpo-6532 [https://bugs.python.org/issue?@action=redirect&bpo=6532]: The type of results of PyThread_start_new_thread() and PyThread_get_thread_ident(), and the id parameter of PyThreadState_SetAsyncExc() changed from “long” to “unsigned long”.

bpo-27867 [https://bugs.python.org/issue?@action=redirect&bpo=27867]: Function PySlice_GetIndicesEx() is deprecated and replaced with a macro if Py_LIMITED_API is not set or set to the value between 0x03050400 and 0x03060000 (not including) or 0x03060100 or higher. Added functions PySlice_Unpack() and PySlice_AdjustIndices().

bpo-29083 [https://bugs.python.org/issue?@action=redirect&bpo=29083]: Fixed the declaration of some public API functions. PyArg_VaParse() and PyArg_VaParseTupleAndKeywords() were not available in limited API. PyArg_ValidateKeywordArguments(), PyArg_UnpackTuple() and Py_BuildValue() were not available in limited API of version < 3.3 when PY_SSIZE_T_CLEAN is defined.

bpo-28769 [https://bugs.python.org/issue?@action=redirect&bpo=28769]: The result of PyUnicode_AsUTF8AndSize() and PyUnicode_AsUTF8() is now of type const char * rather of char *.

bpo-29058 [https://bugs.python.org/issue?@action=redirect&bpo=29058]: All stable API extensions added after Python 3.2 are now available only when Py_LIMITED_API is set to the PY_VERSION_HEX value of the minimum Python version supporting this API.

bpo-28822 [https://bugs.python.org/issue?@action=redirect&bpo=28822]: The index parameters start and end of PyUnicode_FindChar() are now adjusted to behave like str[start:end].

bpo-28808 [https://bugs.python.org/issue?@action=redirect&bpo=28808]: PyUnicode_CompareWithASCIIString() now never raises exceptions.

bpo-28761 [https://bugs.python.org/issue?@action=redirect&bpo=28761]: The fields name and doc of structures PyMemberDef, PyGetSetDef, PyStructSequence_Field, PyStructSequence_Desc, and wrapperbase are now of type const char * rather of char *.

bpo-28748 [https://bugs.python.org/issue?@action=redirect&bpo=28748]: Private variable _Py_PackageContext is now of type const char * rather of char *.

bpo-19569 [https://bugs.python.org/issue?@action=redirect&bpo=19569]: Compiler warnings are now emitted if use most of deprecated functions.

bpo-28426 [https://bugs.python.org/issue?@action=redirect&bpo=28426]: Deprecated undocumented functions PyUnicode_AsEncodedObject(), PyUnicode_AsDecodedObject(), PyUnicode_AsDecodedUnicode() and PyUnicode_AsEncodedUnicode().

Python 3.6.6 final

Release date: 2018-06-27

There were no new changes in version 3.6.6.

Python 3.6.6 release candidate 1

Release date: 2018-06-11

Core and Builtins

bpo-33786 [https://bugs.python.org/issue?@action=redirect&bpo=33786]: Fix asynchronous generators to handle GeneratorExit in athrow() correctly

bpo-30654 [https://bugs.python.org/issue?@action=redirect&bpo=30654]: Fixed reset of the SIGINT handler to SIG_DFL on interpreter shutdown even when there was a custom handler set previously. Patch by Philipp Kerling.

bpo-33622 [https://bugs.python.org/issue?@action=redirect&bpo=33622]: Fixed a leak when the garbage collector fails to add an object with the __del__ method or referenced by it into the gc.garbage list. PyGC_Collect() can now be called when an exception is set and preserves it.

bpo-31849 [https://bugs.python.org/issue?@action=redirect&bpo=31849]: Fix signed/unsigned comparison warning in pyhash.c.

bpo-33391 [https://bugs.python.org/issue?@action=redirect&bpo=33391]: Fix a leak in set_symmetric_difference().

bpo-28055 [https://bugs.python.org/issue?@action=redirect&bpo=28055]: Fix unaligned accesses in siphash24(). Patch by Rolf Eike Beer.

bpo-33231 [https://bugs.python.org/issue?@action=redirect&bpo=33231]: Fix potential memory leak in normalizestring().

bpo-29922 [https://bugs.python.org/issue?@action=redirect&bpo=29922]: Improved error messages in ‘async with’ when __aenter__() or __aexit__() return non-awaitable object.

bpo-33199 [https://bugs.python.org/issue?@action=redirect&bpo=33199]: Fix ma_version_tag in dict implementation is uninitialized when copying from key-sharing dict.

bpo-33041 [https://bugs.python.org/issue?@action=redirect&bpo=33041]: Fixed jumping when the function contains an async for loop.

bpo-32282 [https://bugs.python.org/issue?@action=redirect&bpo=32282]: Fix an unnecessary ifdef in the include of VersionHelpers.h in socketmodule on Windows.

bpo-21983 [https://bugs.python.org/issue?@action=redirect&bpo=21983]: Fix a crash in ctypes.cast() in case the type argument is a ctypes structured data type. Patch by Eryk Sun and Oren Milman.

Library

bpo-30167 [https://bugs.python.org/issue?@action=redirect&bpo=30167]: Prevent site.main() exception if PYTHONSTARTUP is set. Patch by Steve Weber.

bpo-33812 [https://bugs.python.org/issue?@action=redirect&bpo=33812]: Datetime instance d with non-None tzinfo, but with d.tzinfo.utcoffset(d) returning None is now treated as naive by the astimezone() method.

bpo-30805 [https://bugs.python.org/issue?@action=redirect&bpo=30805]: Avoid race condition with debug logging

bpo-33767 [https://bugs.python.org/issue?@action=redirect&bpo=33767]: The concatenation (+) and repetition (*) sequence operations now raise TypeError instead of SystemError when performed on mmap.mmap objects. Patch by Zackery Spytz.

bpo-32684 [https://bugs.python.org/issue?@action=redirect&bpo=32684]: Fix gather to propagate cancellation of itself even with return_exceptions.

bpo-33674 [https://bugs.python.org/issue?@action=redirect&bpo=33674]: Fix a race condition in SSLProtocol.connection_made() of asyncio.sslproto: start immediately the handshake instead of using call_soon(). Previously, data_received() could be called before the handshake started, causing the handshake to hang or fail.

bpo-31647 [https://bugs.python.org/issue?@action=redirect&bpo=31647]: Fixed bug where calling write_eof() on a _SelectorSocketTransport after it’s already closed raises AttributeError.

bpo-33672 [https://bugs.python.org/issue?@action=redirect&bpo=33672]: Fix Task.__repr__ crash with Cython’s bogus coroutines

bpo-33469 [https://bugs.python.org/issue?@action=redirect&bpo=33469]: Fix RuntimeError after closing loop that used run_in_executor

bpo-11874 [https://bugs.python.org/issue?@action=redirect&bpo=11874]: Use a better regex when breaking usage into wrappable parts. Avoids bogus assertion errors from custom metavar strings.

bpo-30877 [https://bugs.python.org/issue?@action=redirect&bpo=30877]: Fixed a bug in the Python implementation of the JSON decoder that prevented the cache of parsed strings from clearing after finishing the decoding. Based on patch by c-fos.

bpo-33548 [https://bugs.python.org/issue?@action=redirect&bpo=33548]: tempfile._candidate_tempdir_list should consider common TEMP locations

bpo-33542 [https://bugs.python.org/issue?@action=redirect&bpo=33542]: Prevent uuid.get_node from using a DUID instead of a MAC on Windows. Patch by Zvi Effron

bpo-26819 [https://bugs.python.org/issue?@action=redirect&bpo=26819]: Fix race condition with ReadTransport.resume_reading in Windows proactor event loop.

bpo-28556 [https://bugs.python.org/issue?@action=redirect&bpo=28556]: Minor fixes in typing module: add annotations to NamedTuple.__new__, pass *args and **kwds in Generic.__new__. Original PRs by Paulius Šarka and Chad Dombrova.

bpo-20087 [https://bugs.python.org/issue?@action=redirect&bpo=20087]: Updated alias mapping with glibc 2.27 supported locales.

bpo-33422 [https://bugs.python.org/issue?@action=redirect&bpo=33422]: Fix trailing quotation marks getting deleted when looking up byte/string literals on pydoc. Patch by Andrés Delfino.

bpo-33197 [https://bugs.python.org/issue?@action=redirect&bpo=33197]: Update error message when constructing invalid inspect.Parameters Patch by Dong-hee Na.

bpo-33383 [https://bugs.python.org/issue?@action=redirect&bpo=33383]: Fixed crash in the get() method of the dbm.ndbm database object when it is called with a single argument.

bpo-33329 [https://bugs.python.org/issue?@action=redirect&bpo=33329]: Fix multiprocessing regression on newer glibcs

bpo-991266 [https://bugs.python.org/issue?@action=redirect&bpo=991266]: Fix quoting of the Comment attribute of http.cookies.SimpleCookie.

bpo-33131 [https://bugs.python.org/issue?@action=redirect&bpo=33131]: Upgrade bundled version of pip to 10.0.1.

bpo-33308 [https://bugs.python.org/issue?@action=redirect&bpo=33308]: Fixed a crash in the parser module when converting an ST object to a tree of tuples or lists with line_info=False and col_info=True.

bpo-33263 [https://bugs.python.org/issue?@action=redirect&bpo=33263]: Fix FD leak in _SelectorSocketTransport Patch by Vlad Starostin.

bpo-33256 [https://bugs.python.org/issue?@action=redirect&bpo=33256]: Fix display of <module> call in the html produced by cgitb.html(). Patch by Stéphane Blondon.

bpo-33203 [https://bugs.python.org/issue?@action=redirect&bpo=33203]: random.Random.choice() now raises IndexError for empty sequences consistently even when called from subclasses without a getrandbits() implementation.

bpo-33224 [https://bugs.python.org/issue?@action=redirect&bpo=33224]: Update difflib.mdiff() for PEP 479. Convert an uncaught StopIteration in a generator into a return-statement.

bpo-33209 [https://bugs.python.org/issue?@action=redirect&bpo=33209]: End framing at the end of C implementation of pickle.Pickler.dump().

bpo-32861 [https://bugs.python.org/issue?@action=redirect&bpo=32861]: The urllib.robotparser’s __str__ representation now includes wildcard entries and the “Crawl-delay” and “Request-rate” fields. Patch by Michael Lazar.

bpo-33096 [https://bugs.python.org/issue?@action=redirect&bpo=33096]: Allow ttk.Treeview.insert to insert iid that has a false boolean value. Note iid=0 and iid=False would be same. Patch by Garvit Khatri.

bpo-33127 [https://bugs.python.org/issue?@action=redirect&bpo=33127]: The ssl module now compiles with LibreSSL 2.7.1.

bpo-33021 [https://bugs.python.org/issue?@action=redirect&bpo=33021]: Release the GIL during fstat() calls, avoiding hang of all threads when calling mmap.mmap(), os.urandom(), and random.seed(). Patch by Nir Soffer.

bpo-27683 [https://bugs.python.org/issue?@action=redirect&bpo=27683]: Fix a regression in ipaddress that result of hosts() is empty when the network is constructed by a tuple containing an integer mask and only 1 bit left for addresses.

bpo-32844 [https://bugs.python.org/issue?@action=redirect&bpo=32844]: Fix wrong redirection of a low descriptor (0 or 1) to stderr in subprocess if another low descriptor is closed.

bpo-31908 [https://bugs.python.org/issue?@action=redirect&bpo=31908]: Fix output of cover files for trace module command-line tool. Previously emitted cover files only when --missing option was used. Patch by Michael Selik.

bpo-31457 [https://bugs.python.org/issue?@action=redirect&bpo=31457]: If nested log adapters are used, the inner process() methods are no longer omitted.

bpo-16865 [https://bugs.python.org/issue?@action=redirect&bpo=16865]: Support arrays >=2GiB in ctypes. Patch by Segev Finer.

bpo-31238 [https://bugs.python.org/issue?@action=redirect&bpo=31238]: pydoc: the stop() method of the private ServerThread class now waits until DocServer.serve_until_quit() completes and then explicitly sets its docserver attribute to None to break a reference cycle.

Documentation

bpo-33503 [https://bugs.python.org/issue?@action=redirect&bpo=33503]: Fix broken pypi link

bpo-33421 [https://bugs.python.org/issue?@action=redirect&bpo=33421]: Add missing documentation for typing.AsyncContextManager.

bpo-33378 [https://bugs.python.org/issue?@action=redirect&bpo=33378]: Add Korean language switcher for https://docs.python.org/3/

bpo-33276 [https://bugs.python.org/issue?@action=redirect&bpo=33276]: Clarify that the __path__ attribute on modules cannot be just any value.

bpo-33201 [https://bugs.python.org/issue?@action=redirect&bpo=33201]: Modernize documentation for writing C extension types.

bpo-33195 [https://bugs.python.org/issue?@action=redirect&bpo=33195]: Deprecate Py_UNICODE usage in c-api/arg document. Py_UNICODE related APIs are deprecated since Python 3.3, but it is missed in the document.

bpo-33126 [https://bugs.python.org/issue?@action=redirect&bpo=33126]: Document PyBuffer_ToContiguous().

bpo-27212 [https://bugs.python.org/issue?@action=redirect&bpo=27212]: Modify documentation for the islice() recipe to consume initial values up to the start index.

bpo-28247 [https://bugs.python.org/issue?@action=redirect&bpo=28247]: Update zipapp documentation to describe how to make standalone applications.

bpo-18802 [https://bugs.python.org/issue?@action=redirect&bpo=18802]: Documentation changes for ipaddress. Patch by Jon Foster and Berker Peksag.

bpo-27428 [https://bugs.python.org/issue?@action=redirect&bpo=27428]: Update documentation to clarify that WindowsRegistryFinder implements MetaPathFinder. (Patch by Himanshu Lakhara)

bpo-8243 [https://bugs.python.org/issue?@action=redirect&bpo=8243]: Add a note about curses.addch and curses.addstr exception behavior when writing outside a window, or pad.

bpo-31432 [https://bugs.python.org/issue?@action=redirect&bpo=31432]: Clarify meaning of CERT_NONE, CERT_OPTIONAL, and CERT_REQUIRED flags for ssl.SSLContext.verify_mode.

Tests

bpo-33655 [https://bugs.python.org/issue?@action=redirect&bpo=33655]: Ignore test_posix_fallocate failures on BSD platforms that might be due to running on ZFS.

bpo-19417 [https://bugs.python.org/issue?@action=redirect&bpo=19417]: Add test_bdb.py.

Build

bpo-5755 [https://bugs.python.org/issue?@action=redirect&bpo=5755]: Move -Wstrict-prototypes option to CFLAGS_NODIST from OPT. This option emitted annoying warnings when building extension modules written in C++.

bpo-33614 [https://bugs.python.org/issue?@action=redirect&bpo=33614]: Ensures module definition files for the stable ABI on Windows are correctly regenerated.

bpo-33522 [https://bugs.python.org/issue?@action=redirect&bpo=33522]: Enable CI builds on Visual Studio Team Services at https://python.visualstudio.com/cpython

bpo-33012 [https://bugs.python.org/issue?@action=redirect&bpo=33012]: Add -Wno-cast-function-type for gcc 8 for silencing warnings about function casts like casting to PyCFunction in method definition lists.

bpo-33394 [https://bugs.python.org/issue?@action=redirect&bpo=33394]: Enable the verbose build for extension modules, when GNU make is passed macros on the command line.

Windows

bpo-33184 [https://bugs.python.org/issue?@action=redirect&bpo=33184]: Update Windows installer to OpenSSL 1.0.2o.

macOS

bpo-33184 [https://bugs.python.org/issue?@action=redirect&bpo=33184]: Update macOS installer build to use OpenSSL 1.0.2o.

IDLE

bpo-33656 [https://bugs.python.org/issue?@action=redirect&bpo=33656]: On Windows, add API call saying that tk scales for DPI. On Windows 8.1+ or 10, with DPI compatibility properties of the Python binary unchanged, and a monitor resolution greater than 96 DPI, this should make text and lines sharper. It should otherwise have no effect.

bpo-33768 [https://bugs.python.org/issue?@action=redirect&bpo=33768]: Clicking on a context line moves that line to the top of the editor window.

bpo-33763 [https://bugs.python.org/issue?@action=redirect&bpo=33763]: IDLE: Use read-only text widget for code context instead of label widget.

bpo-33664 [https://bugs.python.org/issue?@action=redirect&bpo=33664]: Scroll IDLE editor text by lines. Previously, the mouse wheel and scrollbar slider moved text by a fixed number of pixels, resulting in partial lines at the top of the editor box. The change also applies to the shell and grep output windows, but not to read-only text views.

bpo-33679 [https://bugs.python.org/issue?@action=redirect&bpo=33679]: Enable theme-specific color configuration for Code Context. Use the Highlights tab to see the setting for built-in themes or add settings to custom themes.

bpo-33642 [https://bugs.python.org/issue?@action=redirect&bpo=33642]: Display up to maxlines non-blank lines for Code Context. If there is no current context, show a single blank line.

bpo-33628 [https://bugs.python.org/issue?@action=redirect&bpo=33628]: IDLE: Cleanup codecontext.py and its test.

bpo-33564 [https://bugs.python.org/issue?@action=redirect&bpo=33564]: IDLE’s code context now recognizes async as a block opener.

bpo-29706 [https://bugs.python.org/issue?@action=redirect&bpo=29706]: IDLE now colors async and await as keywords in 3.6. They become full keywords in 3.7.

bpo-21474 [https://bugs.python.org/issue?@action=redirect&bpo=21474]: Update word/identifier definition from ascii to unicode. In text and entry boxes, this affects selection by double-click, movement left/right by control-left/right, and deletion left/right by control-BACKSPACE/DEL.

bpo-33204 [https://bugs.python.org/issue?@action=redirect&bpo=33204]: IDLE: consistently color invalid string prefixes. A ‘u’ string prefix cannot be paired with either ‘r’ or ‘f’. Consistently color as much of the prefix, starting at the right, as is valid. Revise and extend colorizer test.

bpo-32831 [https://bugs.python.org/issue?@action=redirect&bpo=32831]: Add docstrings and tests for codecontext.

Tools/Demos

bpo-33189 [https://bugs.python.org/issue?@action=redirect&bpo=33189]: pygettext.py now recognizes only literal strings as docstrings and translatable strings, and rejects bytes literals and f-string expressions.

bpo-31920 [https://bugs.python.org/issue?@action=redirect&bpo=31920]: Fixed handling directories as arguments in the pygettext script. Based on patch by Oleg Krasnikov.

bpo-29673 [https://bugs.python.org/issue?@action=redirect&bpo=29673]: Fix pystackv and pystack gdbinit macros.

bpo-32885 [https://bugs.python.org/issue?@action=redirect&bpo=32885]: Add an -n flag for Tools/scripts/pathfix.py to disable automatic backup creation (files with ~ suffix).

bpo-31583 [https://bugs.python.org/issue?@action=redirect&bpo=31583]: Fix 2to3 for using with –add-suffix option but without –output-dir option for relative path to files in current directory.

C API

bpo-32374 [https://bugs.python.org/issue?@action=redirect&bpo=32374]: Document that m_traverse for multi-phase initialized modules can be called with m_state=NULL, and add a sanity check

Python 3.6.5 final

Release date: 2018-03-28

Tests

bpo-32872 [https://bugs.python.org/issue?@action=redirect&bpo=32872]: Avoid regrtest compatibility issue with namespace packages.

Build

bpo-33163 [https://bugs.python.org/issue?@action=redirect&bpo=33163]: Upgrade pip to 9.0.3 and setuptools to v39.0.1.

Python 3.6.5 release candidate 1

Release date: 2018-03-13

Security

bpo-33001 [https://bugs.python.org/issue?@action=redirect&bpo=33001]: Minimal fix to prevent buffer overrun in os.symlink on Windows

bpo-32981 [https://bugs.python.org/issue?@action=redirect&bpo=32981]: Regexes in difflib and poplib were vulnerable to catastrophic backtracking. These regexes formed potential DOS vectors (REDOS). They have been refactored. This resolves CVE-2018-1060 and CVE-2018-1061. Patch by Jamie Davis.

Core and Builtins

bpo-33026 [https://bugs.python.org/issue?@action=redirect&bpo=33026]: Fixed jumping out of “with” block by setting f_lineno.

bpo-17288 [https://bugs.python.org/issue?@action=redirect&bpo=17288]: Prevent jumps from ‘return’ and ‘exception’ trace events.

bpo-32889 [https://bugs.python.org/issue?@action=redirect&bpo=32889]: Update Valgrind suppression list to account for the rename of Py_ADDRESS_IN_RANG to address_in_range.

bpo-32650 [https://bugs.python.org/issue?@action=redirect&bpo=32650]: Pdb and other debuggers dependent on bdb.py will correctly step over (next command) native coroutines. Patch by Pablo Galindo.

bpo-32685 [https://bugs.python.org/issue?@action=redirect&bpo=32685]: Improve suggestion when the Python 2 form of print statement is either present on the same line as the header of a compound statement or else terminated by a semi-colon instead of a newline. Patch by Nitish Chandra.

bpo-32583 [https://bugs.python.org/issue?@action=redirect&bpo=32583]: Fix possible crashing in builtin Unicode decoders caused by write out-of-bound errors when using customized decode error handlers.

bpo-26163 [https://bugs.python.org/issue?@action=redirect&bpo=26163]: Improved frozenset() hash to create more distinct hash values when faced with datasets containing many similar values.

bpo-27169 [https://bugs.python.org/issue?@action=redirect&bpo=27169]: The __debug__ constant is now optimized out at compile time. This fixes also bpo-22091 [https://bugs.python.org/issue?@action=redirect&bpo=22091].

bpo-32329 [https://bugs.python.org/issue?@action=redirect&bpo=32329]: sys.flags.hash_randomization is now properly set to 0 when hash randomization is turned off by PYTHONHASHSEED=0.

bpo-30416 [https://bugs.python.org/issue?@action=redirect&bpo=30416]: The optimizer is now protected from spending much time doing complex calculations and consuming much memory for creating large constants in constant folding.

bpo-18533 [https://bugs.python.org/issue?@action=redirect&bpo=18533]: repr() on a dict containing its own values() or items() no longer raises RecursionError; OrderedDict similarly. Instead, use ..., as for other recursive structures. Patch by Ben North.

bpo-32028 [https://bugs.python.org/issue?@action=redirect&bpo=32028]: Leading whitespace is now correctly ignored when generating suggestions for converting Py2 print statements to Py3 builtin print function calls. Patch by Sanyam Khurana.

bpo-32137 [https://bugs.python.org/issue?@action=redirect&bpo=32137]: The repr of deeply nested dict now raises a RecursionError instead of crashing due to a stack overflow.

Library

bpo-33064 [https://bugs.python.org/issue?@action=redirect&bpo=33064]: lib2to3 now properly supports trailing commas after *args and **kwargs in function signatures.

bpo-31804 [https://bugs.python.org/issue?@action=redirect&bpo=31804]: Avoid failing in multiprocessing.Process if the standard streams are closed or None at exit.

bpo-33037 [https://bugs.python.org/issue?@action=redirect&bpo=33037]: Skip sending/receiving data after SSL transport closing.

bpo-30353 [https://bugs.python.org/issue?@action=redirect&bpo=30353]: Fix ctypes pass-by-value for structs on 64-bit Cygwin/MinGW.

bpo-33009 [https://bugs.python.org/issue?@action=redirect&bpo=33009]: Fix inspect.signature() for single-parameter partialmethods.

bpo-32969 [https://bugs.python.org/issue?@action=redirect&bpo=32969]: Expose several missing constants in zlib and fix corresponding documentation.

bpo-32713 [https://bugs.python.org/issue?@action=redirect&bpo=32713]: Fixed tarfile.itn handling of out-of-bounds float values. Patch by Joffrey Fuhrer.

bpo-30622 [https://bugs.python.org/issue?@action=redirect&bpo=30622]: The ssl module now detects missing NPN support in LibreSSL.

bpo-32922 [https://bugs.python.org/issue?@action=redirect&bpo=32922]: dbm.open() now encodes filename with the filesystem encoding rather than default encoding.

bpo-32859 [https://bugs.python.org/issue?@action=redirect&bpo=32859]: In os.dup2, don’t check every call whether the dup3 syscall exists or not.

bpo-21060 [https://bugs.python.org/issue?@action=redirect&bpo=21060]: Rewrite confusing message from setup.py upload from “No dist file created in earlier command” to the more helpful “Must create and upload files in one command”.

bpo-32857 [https://bugs.python.org/issue?@action=redirect&bpo=32857]: In tkinter, after_cancel(None) now raises a ValueError instead of canceling the first scheduled function. Patch by Cheryl Sabella.

bpo-32852 [https://bugs.python.org/issue?@action=redirect&bpo=32852]: Make sure sys.argv remains as a list when running trace.

bpo-32841 [https://bugs.python.org/issue?@action=redirect&bpo=32841]: Fixed asyncio.Condition issue which silently ignored cancellation after notifying and cancelling a conditional lock. Patch by Bar Harel.

bpo-31787 [https://bugs.python.org/issue?@action=redirect&bpo=31787]: Fixed refleaks of __init__() methods in various modules. (Contributed by Oren Milman)

bpo-30157 [https://bugs.python.org/issue?@action=redirect&bpo=30157]: Fixed guessing quote and delimiter in csv.Sniffer.sniff() when only the last field is quoted. Patch by Jake Davis.

bpo-32394 [https://bugs.python.org/issue?@action=redirect&bpo=32394]: socket: Remove TCP_FASTOPEN, TCP_KEEPCNT flags on older version Windows during run-time.

bpo-32777 [https://bugs.python.org/issue?@action=redirect&bpo=32777]: Fix a rare but potential pre-exec child process deadlock in subprocess on POSIX systems when marking file descriptors inheritable on exec in the child process. This bug appears to have been introduced in 3.4.

bpo-32647 [https://bugs.python.org/issue?@action=redirect&bpo=32647]: The ctypes module used to depend on indirect linking for dlopen. The shared extension is now explicitly linked against libdl on platforms with dl.

bpo-32734 [https://bugs.python.org/issue?@action=redirect&bpo=32734]: Fixed asyncio.Lock() safety issue which allowed acquiring and locking the same lock multiple times, without it being free. Patch by Bar Harel.

bpo-32727 [https://bugs.python.org/issue?@action=redirect&bpo=32727]: Do not include name field in SMTP envelope from address. Patch by Stéphane Wirtel

bpo-27931 [https://bugs.python.org/issue?@action=redirect&bpo=27931]: Fix email address header parsing error when the username is an empty quoted string. Patch by Xiang Zhang.

bpo-32304 [https://bugs.python.org/issue?@action=redirect&bpo=32304]: distutils’ upload command no longer corrupts tar files ending with a CR byte, and no longer tries to convert CR to CRLF in any of the upload text fields.

bpo-32502 [https://bugs.python.org/issue?@action=redirect&bpo=32502]: uuid.uuid1 no longer raises an exception if a 64-bit hardware address is encountered.

bpo-31848 [https://bugs.python.org/issue?@action=redirect&bpo=31848]: Fix the error handling in Aifc_read.initfp() when the SSND chunk is not found. Patch by Zackery Spytz.

bpo-32555 [https://bugs.python.org/issue?@action=redirect&bpo=32555]: On FreeBSD and Solaris, os.strerror() now always decode the byte string from the current locale encoding, rather than using ASCII/surrogateescape in some cases.

bpo-32521 [https://bugs.python.org/issue?@action=redirect&bpo=32521]: The nis module is now compatible with new libnsl and headers location.

bpo-32473 [https://bugs.python.org/issue?@action=redirect&bpo=32473]: Improve ABCMeta._dump_registry() output readability

bpo-32521 [https://bugs.python.org/issue?@action=redirect&bpo=32521]: glibc has removed Sun RPC. Use replacement libtirpc headers and library in nis module.

bpo-32228 [https://bugs.python.org/issue?@action=redirect&bpo=32228]: Ensure that truncate() preserves the file position (as reported by tell()) after writes longer than the buffer size.

bpo-26133 [https://bugs.python.org/issue?@action=redirect&bpo=26133]: Don’t unsubscribe signals in asyncio UNIX event loop on interpreter shutdown.

bpo-32185 [https://bugs.python.org/issue?@action=redirect&bpo=32185]: The SSL module no longer sends IP addresses in SNI TLS extension on platforms with OpenSSL 1.0.2+ or inet_pton.

bpo-32323 [https://bugs.python.org/issue?@action=redirect&bpo=32323]: urllib.parse.urlsplit() does not convert zone-id (scope) to lower case for scoped IPv6 addresses in hostnames now.

bpo-32302 [https://bugs.python.org/issue?@action=redirect&bpo=32302]: Fix bdist_wininst of distutils for CRT v142: it binary compatible with CRT v140.

bpo-32255 [https://bugs.python.org/issue?@action=redirect&bpo=32255]: A single empty field is now always quoted when written into a CSV file. This allows to distinguish an empty row from a row consisting of a single empty field. Patch by Licht Takeuchi.

bpo-32277 [https://bugs.python.org/issue?@action=redirect&bpo=32277]: Raise NotImplementedError instead of SystemError on platforms where chmod(..., follow_symlinks=False) is not supported. Patch by Anthony Sottile.

bpo-32199 [https://bugs.python.org/issue?@action=redirect&bpo=32199]: The getnode() ip getter now uses ‘ip link’ instead of ‘ip link list’.

bpo-27456 [https://bugs.python.org/issue?@action=redirect&bpo=27456]: Ensure TCP_NODELAY is set on Linux. Tests by Victor Stinner.

bpo-31900 [https://bugs.python.org/issue?@action=redirect&bpo=31900]: The locale.localeconv() function now sets temporarily the LC_CTYPE locale to the LC_NUMERIC locale to decode decimal_point and thousands_sep byte strings if they are non-ASCII or longer than 1 byte, and the LC_NUMERIC locale is different than the LC_CTYPE locale. This temporary change affects other threads.

Same change for the str.format() method when formatting a number (int, float, float and subclasses) with the n type (ex: '{:n}'.format(1234)).

bpo-31802 [https://bugs.python.org/issue?@action=redirect&bpo=31802]: Importing native path module (posixpath, ntpath) now works even if the os module still is not imported.

Documentation

bpo-17232 [https://bugs.python.org/issue?@action=redirect&bpo=17232]: Clarify docs for -O and -OO. Patch by Terry Reedy.

bpo-32800 [https://bugs.python.org/issue?@action=redirect&bpo=32800]: Update link to w3c doc for xml default namespaces.

bpo-8722 [https://bugs.python.org/issue?@action=redirect&bpo=8722]: Document __getattr__() behavior when property get() method raises AttributeError.

bpo-32614 [https://bugs.python.org/issue?@action=redirect&bpo=32614]: Modify RE examples in documentation to use raw strings to prevent DeprecationWarning and add text to REGEX HOWTO to highlight the deprecation.

bpo-31972 [https://bugs.python.org/issue?@action=redirect&bpo=31972]: Improve docstrings for pathlib.PurePath subclasses.

bpo-17799 [https://bugs.python.org/issue?@action=redirect&bpo=17799]: Explain real behaviour of sys.settrace and sys.setprofile and their C-API counterparts regarding which type of events are received in each function. Patch by Pablo Galindo Salgado.

Tests

bpo-32517 [https://bugs.python.org/issue?@action=redirect&bpo=32517]: Fix failing test_asyncio on macOS 10.12.2+ due to transport of KqueueSelector loop was not being closed.

bpo-32721 [https://bugs.python.org/issue?@action=redirect&bpo=32721]: Fix test_hashlib to not fail if the _md5 module is not built.

bpo-32252 [https://bugs.python.org/issue?@action=redirect&bpo=32252]: Fix faulthandler_suppress_crash_report() used to prevent core dump files when testing crashes. getrlimit() returns zero on success.

bpo-31518 [https://bugs.python.org/issue?@action=redirect&bpo=31518]: Debian Unstable has disabled TLS 1.0 and 1.1 for SSLv23_METHOD(). Change TLS/SSL protocol of some tests to PROTOCOL_TLS or PROTOCOL_TLSv1_2 to make them pass on Debian.

Build

bpo-32635 [https://bugs.python.org/issue?@action=redirect&bpo=32635]: Fix segfault of the crypt module when libxcrypt is provided instead of libcrypt at the system.

Windows

bpo-33016 [https://bugs.python.org/issue?@action=redirect&bpo=33016]: Fix potential use of uninitialized memory in nt._getfinalpathname

bpo-32903 [https://bugs.python.org/issue?@action=redirect&bpo=32903]: Fix a memory leak in os.chdir() on Windows if the current directory is set to a UNC path.

bpo-31966 [https://bugs.python.org/issue?@action=redirect&bpo=31966]: Fixed WindowsConsoleIO.write() for writing empty data.

bpo-32409 [https://bugs.python.org/issue?@action=redirect&bpo=32409]: Ensures activate.bat can handle Unicode contents.

bpo-32457 [https://bugs.python.org/issue?@action=redirect&bpo=32457]: Improves handling of denormalized executable path when launching Python.

bpo-32370 [https://bugs.python.org/issue?@action=redirect&bpo=32370]: Use the correct encoding for ipconfig output in the uuid module. Patch by Segev Finer.

bpo-29248 [https://bugs.python.org/issue?@action=redirect&bpo=29248]: Fix os.readlink() on Windows, which was mistakenly treating the PrintNameOffset field of the reparse data buffer as a number of characters instead of bytes. Patch by Craig Holmquist and SSE4.

bpo-32588 [https://bugs.python.org/issue?@action=redirect&bpo=32588]: Create standalone _distutils_findvs module.

macOS

bpo-32726 [https://bugs.python.org/issue?@action=redirect&bpo=32726]: Provide an additional, more modern macOS installer variant that supports macOS 10.9+ systems in 64-bit mode only. Upgrade the supplied third-party libraries to OpenSSL 1.0.2n, XZ 5.2.3, and SQLite 3.22.0. The 10.9+ installer now links with and supplies its own copy of Tcl/Tk 8.6.8.

IDLE

bpo-32984 [https://bugs.python.org/issue?@action=redirect&bpo=32984]: Set __file__ while running a startup file. Like Python, IDLE optionally runs one startup file in the Shell window before presenting the first interactive input prompt. For IDLE, -s runs a file named in environmental variable IDLESTARTUP or PYTHONSTARTUP; -r file runs file. Python sets __file__ to the startup file name before running the file and unsets it before the first prompt. IDLE now does the same when run normally, without the -n option.

bpo-32940 [https://bugs.python.org/issue?@action=redirect&bpo=32940]: Simplify and rename StringTranslatePseudoMapping in pyparse.

bpo-32916 [https://bugs.python.org/issue?@action=redirect&bpo=32916]: Change str to code in pyparse.

bpo-32905 [https://bugs.python.org/issue?@action=redirect&bpo=32905]: Remove unused code in pyparse module.

bpo-32874 [https://bugs.python.org/issue?@action=redirect&bpo=32874]: Add tests for pyparse.

bpo-32837 [https://bugs.python.org/issue?@action=redirect&bpo=32837]: Using the system and place-dependent default encoding for open() is a bad idea for IDLE’s system and location-independent files.

bpo-32826 [https://bugs.python.org/issue?@action=redirect&bpo=32826]: Add “encoding=utf-8” to open() in IDLE’s test_help_about. GUI test test_file_buttons() only looks at initial ascii-only lines, but failed on systems where open() defaults to ‘ascii’ because readline() internally reads and decodes far enough ahead to encounter a non-ascii character in CREDITS.txt.

bpo-32765 [https://bugs.python.org/issue?@action=redirect&bpo=32765]: Update configdialog General tab docstring to add new widgets to the widget list.

Tools/Demos

bpo-24960 [https://bugs.python.org/issue?@action=redirect&bpo=24960]: 2to3 and lib2to3 can now read pickled grammar files using pkgutil.get_data() rather than probing the filesystem. This lets 2to3 and lib2to3 work when run from a zipfile.

bpo-32222 [https://bugs.python.org/issue?@action=redirect&bpo=32222]: Fix pygettext not extracting docstrings for functions with type annotated arguments. Patch by Toby Harradine.

C API

bpo-29084 [https://bugs.python.org/issue?@action=redirect&bpo=29084]: Undocumented C API for OrderedDict has been excluded from the limited C API. It was added by mistake and actually never worked in the limited C API.

Python 3.6.4 final

Release date: 2017-12-18

There were no new code changes in version 3.6.4 since v3.6.4rc1.

Python 3.6.4 release candidate 1

Release date: 2017-12-05

Core and Builtins

bpo-32176 [https://bugs.python.org/issue?@action=redirect&bpo=32176]: co_flags.CO_NOFREE is now always set correctly by the code object constructor based on freevars and cellvars, rather than needing to be set correctly by the caller. This ensures it will be cleared automatically when additional cell references are injected into a modified code object and function.

bpo-31949 [https://bugs.python.org/issue?@action=redirect&bpo=31949]: Fixed several issues in printing tracebacks (PyTraceBack_Print()).

Setting sys.tracebacklimit to 0 or less now suppresses printing tracebacks.

Setting sys.tracebacklimit to None now causes using the default limit.

Setting sys.tracebacklimit to an integer larger than LONG_MAX now means using the limit LONG_MAX rather than the default limit.

Fixed integer overflows in the case of more than 2**31 traceback items on Windows.

Fixed output errors handling.

bpo-30696 [https://bugs.python.org/issue?@action=redirect&bpo=30696]: Fix the interactive interpreter looping endlessly when no memory.

bpo-20047 [https://bugs.python.org/issue?@action=redirect&bpo=20047]: Bytearray methods partition() and rpartition() now accept only bytes-like objects as separator, as documented. In particular they now raise TypeError rather of returning a bogus result when an integer is passed as a separator.

bpo-31852 [https://bugs.python.org/issue?@action=redirect&bpo=31852]: Fix a segmentation fault caused by a combination of the async soft keyword and continuation lines.

bpo-21720 [https://bugs.python.org/issue?@action=redirect&bpo=21720]: BytesWarning no longer emitted when the fromlist argument of __import__() or the __all__ attribute of the module contain bytes instances.

bpo-31825 [https://bugs.python.org/issue?@action=redirect&bpo=31825]: Fixed OverflowError in the ‘unicode-escape’ codec and in codecs.escape_decode() when decode an escaped non-ascii byte.

bpo-28603 [https://bugs.python.org/issue?@action=redirect&bpo=28603]: Print the full context/cause chain of exceptions on interpreter exit, even if an exception in the chain is unhashable or compares equal to later ones. Patch by Zane Bitter.

bpo-31786 [https://bugs.python.org/issue?@action=redirect&bpo=31786]: Fix timeout rounding in the select module to round correctly negative timeouts between -1.0 and 0.0. The functions now block waiting for events as expected. Previously, the call was incorrectly non-blocking. Patch by Pablo Galindo.

bpo-31642 [https://bugs.python.org/issue?@action=redirect&bpo=31642]: Restored blocking “from package import module” by setting sys.modules[“package.module”] to None.

bpo-31626 [https://bugs.python.org/issue?@action=redirect&bpo=31626]: Fixed a bug in debug memory allocator. There was a write to freed memory after shrinking a memory block.

bpo-31619 [https://bugs.python.org/issue?@action=redirect&bpo=31619]: Fixed a ValueError when convert a string with large number of underscores to integer with binary base.

bpo-31592 [https://bugs.python.org/issue?@action=redirect&bpo=31592]: Fixed an assertion failure in Python parser in case of a bad unicodedata.normalize(). Patch by Oren Milman.

bpo-31588 [https://bugs.python.org/issue?@action=redirect&bpo=31588]: Raise a TypeError with a helpful error message when class creation fails due to a metaclass with a bad __prepare__() method. Patch by Oren Milman.

bpo-31566 [https://bugs.python.org/issue?@action=redirect&bpo=31566]: Fix an assertion failure in _warnings.warn() in case of a bad __name__ global. Patch by Oren Milman.

bpo-31505 [https://bugs.python.org/issue?@action=redirect&bpo=31505]: Fix an assertion failure in json, in case _json.make_encoder() received a bad encoder() argument. Patch by Oren Milman.

bpo-31492 [https://bugs.python.org/issue?@action=redirect&bpo=31492]: Fix assertion failures in case of failing to import from a module with a bad __name__ attribute, and in case of failing to access an attribute of such a module. Patch by Oren Milman.

bpo-31490 [https://bugs.python.org/issue?@action=redirect&bpo=31490]: Fix an assertion failure in ctypes class definition, in case the class has an attribute whose name is specified in _anonymous_ but not in _fields_. Patch by Oren Milman.

bpo-31478 [https://bugs.python.org/issue?@action=redirect&bpo=31478]: Fix an assertion failure in _random.Random.seed() in case the argument has a bad __abs__() method. Patch by Oren Milman.

bpo-31315 [https://bugs.python.org/issue?@action=redirect&bpo=31315]: Fix an assertion failure in imp.create_dynamic(), when spec.name is not a string. Patch by Oren Milman.

bpo-31311 [https://bugs.python.org/issue?@action=redirect&bpo=31311]: Fix a crash in the __setstate__() method of ctypes._CData, in case of a bad __dict__. Patch by Oren Milman.

bpo-31293 [https://bugs.python.org/issue?@action=redirect&bpo=31293]: Fix crashes in true division and multiplication of a timedelta object by a float with a bad as_integer_ratio() method. Patch by Oren Milman.

bpo-31285 [https://bugs.python.org/issue?@action=redirect&bpo=31285]: Fix an assertion failure in warnings.warn_explicit, when the return value of the received loader’s get_source() has a bad splitlines() method. Patch by Oren Milman.

bpo-30817 [https://bugs.python.org/issue?@action=redirect&bpo=30817]: PyErr_PrintEx() clears now the ignored exception that may be raised by _PySys_SetObjectId(), for example when no memory.

Library

bpo-28556 [https://bugs.python.org/issue?@action=redirect&bpo=28556]: Two minor fixes for typing module: allow shallow copying instances of generic classes, improve interaction of __init_subclass__ with generics. Original PRs by Ivan Levkivskyi.

bpo-27240 [https://bugs.python.org/issue?@action=redirect&bpo=27240]: The header folding algorithm for the new email policies has been rewritten, which also fixes bpo-30788 [https://bugs.python.org/issue?@action=redirect&bpo=30788], bpo-31831 [https://bugs.python.org/issue?@action=redirect&bpo=31831], and bpo-32182 [https://bugs.python.org/issue?@action=redirect&bpo=32182]. In particular, RFC2231 folding is now done correctly.

bpo-32186 [https://bugs.python.org/issue?@action=redirect&bpo=32186]: io.FileIO.readall() and io.FileIO.read() now release the GIL when getting the file size. Fixed hang of all threads with inaccessible NFS server. Patch by Nir Soffer.

bpo-12239 [https://bugs.python.org/issue?@action=redirect&bpo=12239]: Make msilib.SummaryInformation.GetProperty() return None when the value of property is VT_EMPTY. Initial patch by Mark Mc Mahon.

bpo-31325 [https://bugs.python.org/issue?@action=redirect&bpo=31325]: Fix wrong usage of collections.namedtuple() in the RobotFileParser.parse() method.

Initial patch by Robin Wellner.

bpo-12382 [https://bugs.python.org/issue?@action=redirect&bpo=12382]: msilib.OpenDatabase() now raises a better exception message when it couldn’t open or create an MSI file. Initial patch by William Tisäter.

bpo-32110 [https://bugs.python.org/issue?@action=redirect&bpo=32110]: codecs.StreamReader.read(n) now returns not more than n characters/bytes for non-negative n. This makes it compatible with read() methods of other file-like objects.

bpo-32072 [https://bugs.python.org/issue?@action=redirect&bpo=32072]: Fixed issues with binary plists:

Fixed saving bytearrays.

Identical objects will be saved only once.

Equal references will be load as identical objects.

Added support for saving and loading recursive data structures.

bpo-32034 [https://bugs.python.org/issue?@action=redirect&bpo=32034]: Make asyncio.IncompleteReadError and LimitOverrunError pickleable.

bpo-32015 [https://bugs.python.org/issue?@action=redirect&bpo=32015]: Fixed the looping of asyncio in the case of reconnection the socket during waiting async read/write from/to the socket.

bpo-32011 [https://bugs.python.org/issue?@action=redirect&bpo=32011]: Restored support of loading marshal files with the TYPE_INT64 code. These files can be produced in Python 2.7.

bpo-31970 [https://bugs.python.org/issue?@action=redirect&bpo=31970]: Reduce performance overhead of asyncio debug mode.

bpo-9678 [https://bugs.python.org/issue?@action=redirect&bpo=9678]: Fixed determining the MAC address in the uuid module:

Using ifconfig on NetBSD and OpenBSD.

Using arp on Linux, FreeBSD, NetBSD and OpenBSD.

Based on patch by Takayuki Shimizukawa.

bpo-30057 [https://bugs.python.org/issue?@action=redirect&bpo=30057]: Fix potential missed signal in signal.signal().

bpo-31933 [https://bugs.python.org/issue?@action=redirect&bpo=31933]: Fix Blake2 params leaf_size and node_offset on big endian platforms. Patch by Jack O’Connor.

bpo-31927 [https://bugs.python.org/issue?@action=redirect&bpo=31927]: Fixed compilation of the socket module on NetBSD 8. Fixed assertion failure or reading arbitrary data when parse a AF_BLUETOOTH address on NetBSD and DragonFly BSD.

bpo-27666 [https://bugs.python.org/issue?@action=redirect&bpo=27666]: Fixed stack corruption in curses.box() and curses.ungetmouse() when the size of types chtype or mmask_t is less than the size of C long. curses.box() now accepts characters as arguments. Based on patch by Steve Fink.

bpo-31897 [https://bugs.python.org/issue?@action=redirect&bpo=31897]: plistlib now catches more errors when read binary plists and raises InvalidFileException instead of unexpected exceptions.

bpo-25720 [https://bugs.python.org/issue?@action=redirect&bpo=25720]: Fix the method for checking pad state of curses WINDOW. Patch by Masayuki Yamamoto.

bpo-31893 [https://bugs.python.org/issue?@action=redirect&bpo=31893]: Fixed the layout of the kqueue_event structure on OpenBSD and NetBSD. Fixed the comparison of the kqueue_event objects.

bpo-31891 [https://bugs.python.org/issue?@action=redirect&bpo=31891]: Fixed building the curses module on NetBSD.

bpo-28416 [https://bugs.python.org/issue?@action=redirect&bpo=28416]: Instances of pickle.Pickler subclass with the persistent_id() method and pickle.Unpickler subclass with the persistent_load() method no longer create reference cycles.

bpo-28326 [https://bugs.python.org/issue?@action=redirect&bpo=28326]: Fix multiprocessing.Process when stdout and/or stderr is closed or None.

bpo-31457 [https://bugs.python.org/issue?@action=redirect&bpo=31457]: If nested log adapters are used, the inner process() methods are no longer omitted.

bpo-31457 [https://bugs.python.org/issue?@action=redirect&bpo=31457]: The manager property on LoggerAdapter objects is now properly settable.

bpo-31806 [https://bugs.python.org/issue?@action=redirect&bpo=31806]: Fix timeout rounding in time.sleep(), threading.Lock.acquire() and socket.socket.settimeout() to round correctly negative timeouts between -1.0 and 0.0. The functions now block waiting for events as expected. Previously, the call was incorrectly non-blocking. Patch by Pablo Galindo.

bpo-28603 [https://bugs.python.org/issue?@action=redirect&bpo=28603]: traceback: Fix a TypeError that occurred during printing of exception tracebacks when either the current exception or an exception in its context/cause chain is unhashable. Patch by Zane Bitter.

bpo-30058 [https://bugs.python.org/issue?@action=redirect&bpo=30058]: Fixed buffer overflow in select.kqueue.control().

bpo-31770 [https://bugs.python.org/issue?@action=redirect&bpo=31770]: Prevent a crash when calling the __init__() method of a sqlite3.Cursor object more than once. Patch by Oren Milman.

bpo-31672 [https://bugs.python.org/issue?@action=redirect&bpo=31672]: idpattern in string.Template matched some non-ASCII characters. Now it uses -i regular expression local flag to avoid non-ASCII characters.

bpo-31764 [https://bugs.python.org/issue?@action=redirect&bpo=31764]: Prevent a crash in sqlite3.Cursor.close() in case the Cursor object is uninitialized. Patch by Oren Milman.

bpo-31752 [https://bugs.python.org/issue?@action=redirect&bpo=31752]: Fix possible crash in timedelta constructor called with custom integers.

bpo-31701 [https://bugs.python.org/issue?@action=redirect&bpo=31701]: On Windows, faulthandler.enable() now ignores MSC and COM exceptions.

bpo-31728 [https://bugs.python.org/issue?@action=redirect&bpo=31728]: Prevent crashes in _elementtree due to unsafe cleanup of Element.text and Element.tail. Patch by Oren Milman.

bpo-31620 [https://bugs.python.org/issue?@action=redirect&bpo=31620]: an empty asyncio.Queue now doesn’t leak memory when queue.get pollers timeout

bpo-31632 [https://bugs.python.org/issue?@action=redirect&bpo=31632]: Fix method set_protocol() of class _SSLProtocolTransport in asyncio module. This method was previously modifying a wrong reference to the protocol.

bpo-31675 [https://bugs.python.org/issue?@action=redirect&bpo=31675]: Fixed memory leaks in Tkinter’s methods splitlist() and split() when pass a string larger than 2 GiB.

bpo-31673 [https://bugs.python.org/issue?@action=redirect&bpo=31673]: Fixed typo in the name of Tkinter’s method adderrorinfo().

bpo-30806 [https://bugs.python.org/issue?@action=redirect&bpo=30806]: Fix the string representation of a netrc object.

bpo-15037 [https://bugs.python.org/issue?@action=redirect&bpo=15037]: Added a workaround for getkey() in curses for ncurses 5.7 and earlier.

bpo-25351 [https://bugs.python.org/issue?@action=redirect&bpo=25351]: Avoid venv activate failures with undefined variables

bpo-25532 [https://bugs.python.org/issue?@action=redirect&bpo=25532]: inspect.unwrap() will now only try to unwrap an object sys.getrecursionlimit() times, to protect against objects which create a new object on every attribute access.

bpo-30347 [https://bugs.python.org/issue?@action=redirect&bpo=30347]: Stop crashes when concurrently iterate over itertools.groupby() iterators.

bpo-31516 [https://bugs.python.org/issue?@action=redirect&bpo=31516]: threading.current_thread() should not return a dummy thread at shutdown.

bpo-31351 [https://bugs.python.org/issue?@action=redirect&bpo=31351]: python -m ensurepip now exits with non-zero exit code if pip bootstrapping has failed.

bpo-31482 [https://bugs.python.org/issue?@action=redirect&bpo=31482]: random.seed() now works with bytes in version=1

bpo-31334 [https://bugs.python.org/issue?@action=redirect&bpo=31334]: Fix poll.poll([timeout]) in the select module for arbitrary negative timeouts on all OSes where it can only be a non-negative integer or -1. Patch by Riccardo Coccioli.

bpo-31310 [https://bugs.python.org/issue?@action=redirect&bpo=31310]: multiprocessing’s semaphore tracker should be launched again if crashed.

bpo-31308 [https://bugs.python.org/issue?@action=redirect&bpo=31308]: Make multiprocessing’s forkserver process immune to Ctrl-C and other user interruptions. If it crashes, restart it when necessary.

Documentation

bpo-32105 [https://bugs.python.org/issue?@action=redirect&bpo=32105]: Added asyncio.BaseEventLoop.connect_accepted_socket versionadded marker.

bpo-31537 [https://bugs.python.org/issue?@action=redirect&bpo=31537]: Fix incorrect usage of get_history_length in readline documentation example code. Patch by Brad Smith.

bpo-30085 [https://bugs.python.org/issue?@action=redirect&bpo=30085]: The operator functions without double underscores are preferred for clarity. The one with underscores are only kept for back-compatibility.

Tests

bpo-31380 [https://bugs.python.org/issue?@action=redirect&bpo=31380]: Skip test_httpservers test_undecodable_file on macOS: fails on APFS.

bpo-31705 [https://bugs.python.org/issue?@action=redirect&bpo=31705]: Skip test_socket.test_sha256() on Linux kernel older than 4.5. The test fails with ENOKEY on kernel 3.10 (on ppc64le). A fix was merged into the kernel 4.5.

bpo-31174 [https://bugs.python.org/issue?@action=redirect&bpo=31174]: Fix test_tools.test_unparse: DirectoryTestCase now stores the names sample to always test the same files. It prevents false alarms when hunting reference leaks.

bpo-30695 [https://bugs.python.org/issue?@action=redirect&bpo=30695]: Add the set_nomemory(start, stop) and remove_mem_hooks() functions to the _testcapi module.

Build

bpo-32059 [https://bugs.python.org/issue?@action=redirect&bpo=32059]: detect_modules() in setup.py now also searches the sysroot paths when cross-compiling.

bpo-31957 [https://bugs.python.org/issue?@action=redirect&bpo=31957]: Fixes Windows SDK version detection when building for Windows.

bpo-31609 [https://bugs.python.org/issue?@action=redirect&bpo=31609]: Fixes quotes in PCbuild/clean.bat

bpo-31934 [https://bugs.python.org/issue?@action=redirect&bpo=31934]: Abort the build when building out of a not clean source tree.

bpo-31926 [https://bugs.python.org/issue?@action=redirect&bpo=31926]: Fixed Argument Clinic sometimes causing compilation errors when there was more than one function and/or method in a .c file with the same name.

bpo-28791 [https://bugs.python.org/issue?@action=redirect&bpo=28791]: Update Windows builds to use SQLite 3.21.0.

bpo-28791 [https://bugs.python.org/issue?@action=redirect&bpo=28791]: Update OS X installer to use SQLite 3.21.0.

bpo-22140 [https://bugs.python.org/issue?@action=redirect&bpo=22140]: Prevent double substitution of prefix in python-config.sh.

bpo-31536 [https://bugs.python.org/issue?@action=redirect&bpo=31536]: Avoid wholesale rebuild after make regen-all if nothing changed.

Windows

bpo-1102 [https://bugs.python.org/issue?@action=redirect&bpo=1102]: Return None when View.Fetch() returns ERROR_NO_MORE_ITEMS instead of raising MSIError.

Initial patch by Anthony Tuininga.

bpo-31944 [https://bugs.python.org/issue?@action=redirect&bpo=31944]: Fixes Modify button in Apps and Features dialog.

macOS

bpo-31392 [https://bugs.python.org/issue?@action=redirect&bpo=31392]: Update macOS installer to use OpenSSL 1.0.2m

IDLE

bpo-32207 [https://bugs.python.org/issue?@action=redirect&bpo=32207]: Improve tk event exception tracebacks in IDLE. When tk event handling is driven by IDLE’s run loop, a confusing and distracting queue.EMPTY traceback context is no longer added to tk event exception tracebacks. The traceback is now the same as when event handling is driven by user code. Patch based on a suggestion by Serhiy Storchaka.

bpo-32164 [https://bugs.python.org/issue?@action=redirect&bpo=32164]: Delete unused file idlelib/tabbedpages.py. Use of TabbedPageSet in configdialog was replaced by ttk.Notebook.

bpo-32100 [https://bugs.python.org/issue?@action=redirect&bpo=32100]: IDLE: Fix old and new bugs in pathbrowser; improve tests. Patch mostly by Cheryl Sabella.

bpo-31858 [https://bugs.python.org/issue?@action=redirect&bpo=31858]: IDLE – Restrict shell prompt manipulation to the shell. Editor and output windows only see an empty last prompt line. This simplifies the code and fixes a minor bug when newline is inserted. Sys.ps1, if present, is read on Shell start-up, but is not set or changed.

bpo-31860 [https://bugs.python.org/issue?@action=redirect&bpo=31860]: The font sample in the IDLE configuration dialog is now editable. Changes persist while IDLE remains open

bpo-31836 [https://bugs.python.org/issue?@action=redirect&bpo=31836]: Test_code_module now passes if run after test_idle, which sets ps1.

The code module uses sys.ps1 if present or sets it to ‘>>> ‘ if not. Test_code_module now properly tests both behaviors. Ditto for ps2.

bpo-28603 [https://bugs.python.org/issue?@action=redirect&bpo=28603]: Fix a TypeError that caused a shell restart when printing a traceback that includes an exception that is unhashable. Patch by Zane Bitter.

bpo-13802 [https://bugs.python.org/issue?@action=redirect&bpo=13802]: Use non-Latin characters in the IDLE’s Font settings sample. Even if one selects a font that defines a limited subset of the unicode Basic Multilingual Plane, tcl/tk will use other fonts that define a character. The expanded example give users of non-Latin characters a better idea of what they might see in IDLE’s shell and editors. To make room for the expanded sample, frames on the Font tab are re-arranged. The Font/Tabs help explains a bit about the additions.

bpo-31460 [https://bugs.python.org/issue?@action=redirect&bpo=31460]: Simplify the API of IDLE’s Module Browser.

Passing a widget instead of an flist with a root widget opens the option of creating a browser frame that is only part of a window. Passing a full file name instead of pieces assumed to come from a .py file opens the possibility of browsing python files that do not end in .py.

bpo-31649 [https://bugs.python.org/issue?@action=redirect&bpo=31649]: IDLE - Make _htest, _utest parameters keyword only.

bpo-31559 [https://bugs.python.org/issue?@action=redirect&bpo=31559]: Remove test order dependence in idle_test.test_browser.

bpo-31459 [https://bugs.python.org/issue?@action=redirect&bpo=31459]: Rename IDLE’s module browser from Class Browser to Module Browser. The original module-level class and method browser became a module browser, with the addition of module-level functions, years ago. Nested classes and functions were added yesterday. For back-compatibility, the virtual event <<open-class-browser>>, which appears on the Keys tab of the Settings dialog, is not changed. Patch by Cheryl Sabella.

bpo-31500 [https://bugs.python.org/issue?@action=redirect&bpo=31500]: Default fonts now are scaled on HiDPI displays.

bpo-1612262 [https://bugs.python.org/issue?@action=redirect&bpo=1612262]: IDLE module browser now shows nested classes and functions. Original patches for code and tests by Guilherme Polo and Cheryl Sabella, respectively.

Tools/Demos

bpo-30722 [https://bugs.python.org/issue?@action=redirect&bpo=30722]: Make redemo work with Python 3.6 and newer versions.

Also, remove the LOCALE option since it doesn’t work with string patterns in Python 3.

Patch by Christoph Sarnowski.

C API

bpo-20891 [https://bugs.python.org/issue?@action=redirect&bpo=20891]: Fix PyGILState_Ensure(). When PyGILState_Ensure() is called in a non-Python thread before PyEval_InitThreads(), only call PyEval_InitThreads() after calling PyThreadState_New() to fix a crash.

bpo-31532 [https://bugs.python.org/issue?@action=redirect&bpo=31532]: Fix memory corruption due to allocator mix in getpath.c between Py_GetPath() and Py_SetPath()

bpo-30697 [https://bugs.python.org/issue?@action=redirect&bpo=30697]: The PyExc_RecursionErrorInst singleton is removed and PyErr_NormalizeException() does not use it anymore. This singleton is persistent and its members being never cleared may cause a segfault during finalization of the interpreter. See also bpo-22898 [https://bugs.python.org/issue?@action=redirect&bpo=22898].

Python 3.6.3 final

Release date: 2017-10-03

Library

bpo-31641 [https://bugs.python.org/issue?@action=redirect&bpo=31641]: Re-allow arbitrary iterables in concurrent.futures.as_completed(). Fixes regression in 3.6.3rc1.

Build

bpo-31662 [https://bugs.python.org/issue?@action=redirect&bpo=31662]: Fix typos in Windows uploadrelease.bat script. Fix Windows Doc build issues in Doc/make.bat.

bpo-31423 [https://bugs.python.org/issue?@action=redirect&bpo=31423]: Fix building the PDF documentation with newer versions of Sphinx.

Python 3.6.3 release candidate 1

Release date: 2017-09-18

Security

bpo-29781 [https://bugs.python.org/issue?@action=redirect&bpo=29781]: SSLObject.version() now correctly returns None when handshake over BIO has not been performed yet.

bpo-30947 [https://bugs.python.org/issue?@action=redirect&bpo=30947]: Upgrade libexpat embedded copy from version 2.2.1 to 2.2.3 to get security fixes.

Core and Builtins

bpo-31471 [https://bugs.python.org/issue?@action=redirect&bpo=31471]: Fix an assertion failure in subprocess.Popen() on Windows, in case the env argument has a bad keys() method. Patch by Oren Milman.

bpo-31418 [https://bugs.python.org/issue?@action=redirect&bpo=31418]: Fix an assertion failure in PyErr_WriteUnraisable() in case of an exception with a bad __module__ attribute. Patch by Oren Milman.

bpo-31416 [https://bugs.python.org/issue?@action=redirect&bpo=31416]: Fix assertion failures in case of a bad warnings.filters or warnings.defaultaction. Patch by Oren Milman.

bpo-31411 [https://bugs.python.org/issue?@action=redirect&bpo=31411]: Raise a TypeError instead of SystemError in case warnings.onceregistry is not a dictionary. Patch by Oren Milman.

bpo-31373 [https://bugs.python.org/issue?@action=redirect&bpo=31373]: Fix several possible instances of undefined behavior due to floating-point demotions.

bpo-30465 [https://bugs.python.org/issue?@action=redirect&bpo=30465]: Location information (lineno and col_offset) in f-strings is now (mostly) correct. This fixes tools like flake8 from showing warnings on the wrong line (typically the first line of the file).

bpo-31343 [https://bugs.python.org/issue?@action=redirect&bpo=31343]: Include sys/sysmacros.h for major(), minor(), and makedev(). GNU C libray plans to remove the functions from sys/types.h.

bpo-31291 [https://bugs.python.org/issue?@action=redirect&bpo=31291]: Fix an assertion failure in zipimport.zipimporter.get_data on Windows, when the return value of pathname.replace('/','\\') isn’t a string. Patch by Oren Milman.

bpo-31271 [https://bugs.python.org/issue?@action=redirect&bpo=31271]: Fix an assertion failure in the write() method of io.TextIOWrapper, when the encoder doesn’t return a bytes object. Patch by Oren Milman.

bpo-31243 [https://bugs.python.org/issue?@action=redirect&bpo=31243]: Fix a crash in some methods of io.TextIOWrapper, when the decoder’s state is invalid. Patch by Oren Milman.

bpo-30721 [https://bugs.python.org/issue?@action=redirect&bpo=30721]: print now shows correct usage hint for using Python 2 redirection syntax. Patch by Sanyam Khurana.

bpo-31070 [https://bugs.python.org/issue?@action=redirect&bpo=31070]: Fix a race condition in importlib _get_module_lock().

bpo-31095 [https://bugs.python.org/issue?@action=redirect&bpo=31095]: Fix potential crash during GC caused by tp_dealloc which doesn’t call PyObject_GC_UnTrack().

bpo-31071 [https://bugs.python.org/issue?@action=redirect&bpo=31071]: Avoid masking original TypeError in call with * unpacking when other arguments are passed.

bpo-30978 [https://bugs.python.org/issue?@action=redirect&bpo=30978]: str.format_map() now passes key lookup exceptions through. Previously any exception was replaced with a KeyError exception.

bpo-30808 [https://bugs.python.org/issue?@action=redirect&bpo=30808]: Use _Py_atomic API for concurrency-sensitive signal state.

bpo-30876 [https://bugs.python.org/issue?@action=redirect&bpo=30876]: Relative import from unloaded package now reimports the package instead of failing with SystemError. Relative import from non-package now fails with ImportError rather than SystemError.

bpo-30703 [https://bugs.python.org/issue?@action=redirect&bpo=30703]: Improve signal delivery.

Avoid using Py_AddPendingCall from signal handler, to avoid calling signal-unsafe functions. The tests I’m adding here fail without the rest of the patch, on Linux and OS X. This means our signal delivery logic had defects (some signals could be lost).

bpo-30765 [https://bugs.python.org/issue?@action=redirect&bpo=30765]: Avoid blocking in pthread_mutex_lock() when PyThread_acquire_lock() is asked not to block.

bpo-31161 [https://bugs.python.org/issue?@action=redirect&bpo=31161]: Make sure the ‘Missing parentheses’ syntax error message is only applied to SyntaxError, not to subclasses. Patch by Martijn Pieters.

bpo-30814 [https://bugs.python.org/issue?@action=redirect&bpo=30814]: Fixed a race condition when import a submodule from a package.

bpo-30597 [https://bugs.python.org/issue?@action=redirect&bpo=30597]: print now shows expected input in custom error message when used as a Python 2 statement. Patch by Sanyam Khurana.

Library

bpo-31499 [https://bugs.python.org/issue?@action=redirect&bpo=31499]: xml.etree: Fix a crash when a parser is part of a reference cycle.

bpo-28556 [https://bugs.python.org/issue?@action=redirect&bpo=28556]: typing.get_type_hints now finds the right globalns for classes and modules by default (when no globalns was specified by the caller).

bpo-28556 [https://bugs.python.org/issue?@action=redirect&bpo=28556]: Speed improvements to the typing module. Original PRs by Ivan Levkivskyi and Mitar.

bpo-31544 [https://bugs.python.org/issue?@action=redirect&bpo=31544]: The C accelerator module of ElementTree ignored exceptions raised when looking up TreeBuilder target methods in XMLParser().

bpo-31234 [https://bugs.python.org/issue?@action=redirect&bpo=31234]: socket.create_connection() now fixes manually a reference cycle: clear the variable storing the last exception on success.

bpo-31457 [https://bugs.python.org/issue?@action=redirect&bpo=31457]: LoggerAdapter objects can now be nested.

bpo-31400 [https://bugs.python.org/issue?@action=redirect&bpo=31400]: Improves SSL error handling to avoid losing error numbers.

bpo-28958 [https://bugs.python.org/issue?@action=redirect&bpo=28958]: ssl.SSLContext() now uses OpenSSL error information when a context cannot be instantiated.

bpo-27340 [https://bugs.python.org/issue?@action=redirect&bpo=27340]: SSLSocket.sendall() now uses memoryview to create slices of data. This fixes support for all bytes-like object. It is also more efficient and avoids costly copies.

bpo-31178 [https://bugs.python.org/issue?@action=redirect&bpo=31178]: Fix string concatenation bug in rare error path in the subprocess module

bpo-31350 [https://bugs.python.org/issue?@action=redirect&bpo=31350]: Micro-optimize asyncio._get_running_loop() to become up to 10% faster.

bpo-31170 [https://bugs.python.org/issue?@action=redirect&bpo=31170]: expat: Update libexpat from 2.2.3 to 2.2.4. Fix copying of partial characters for UTF-8 input (libexpat bug 115): https://github.com/libexpat/libexpat/issues/115

bpo-29136 [https://bugs.python.org/issue?@action=redirect&bpo=29136]: Add TLS 1.3 cipher suites and OP_NO_TLSv1_3.

bpo-29212 [https://bugs.python.org/issue?@action=redirect&bpo=29212]: Fix concurrent.futures.thread.ThreadPoolExecutor threads to have a non repr() based thread name by default when no thread_name_prefix is supplied. They will now identify themselves as “ThreadPoolExecutor-y_n”.

bpo-9146 [https://bugs.python.org/issue?@action=redirect&bpo=9146]: Fix a segmentation fault in _hashopenssl when standard hash functions such as md5 are not available in the linked OpenSSL library. As in some special FIPS-140 build environments.

bpo-27144 [https://bugs.python.org/issue?@action=redirect&bpo=27144]: The map() and as_completed() iterators in concurrent.futures now avoid keeping a reference to yielded objects.

bpo-10746 [https://bugs.python.org/issue?@action=redirect&bpo=10746]: Fix ctypes producing wrong PEP 3118 type codes for integer types.

bpo-22536 [https://bugs.python.org/issue?@action=redirect&bpo=22536]: The subprocess module now sets the filename when FileNotFoundError is raised on POSIX systems due to the executable or cwd not being found.

bpo-31249 [https://bugs.python.org/issue?@action=redirect&bpo=31249]: concurrent.futures: WorkItem.run() used by ThreadPoolExecutor now breaks a reference cycle between an exception object and the WorkItem object.

bpo-31247 [https://bugs.python.org/issue?@action=redirect&bpo=31247]: xmlrpc.server now explicitly breaks reference cycles when using sys.exc_info() in code handling exceptions.

bpo-30102 [https://bugs.python.org/issue?@action=redirect&bpo=30102]: The ssl and hashlib modules now call OPENSSL_add_all_algorithms_noconf() on OpenSSL < 1.1.0. The function detects CPU features and enables optimizations on some CPU architectures such as POWER8. Patch is based on research from Gustavo Serra Scalet.

bpo-31185 [https://bugs.python.org/issue?@action=redirect&bpo=31185]: Fixed miscellaneous errors in asyncio speedup module.

bpo-31135 [https://bugs.python.org/issue?@action=redirect&bpo=31135]: ttk: fix the destroy() method of LabeledScale and OptionMenu classes. Call the parent destroy() method even if the used attribute doesn’t exist. The LabeledScale.destroy() method now also explicitly clears label and scale attributes to help the garbage collector to destroy all widgets.

bpo-31107 [https://bugs.python.org/issue?@action=redirect&bpo=31107]: Fix copyreg._slotnames() mangled attribute calculation for classes whose name begins with an underscore. Patch by Shane Harvey.

bpo-31061 [https://bugs.python.org/issue?@action=redirect&bpo=31061]: Fixed a crash when using asyncio and threads.

bpo-30502 [https://bugs.python.org/issue?@action=redirect&bpo=30502]: Fix handling of long oids in ssl. Based on patch by Christian Heimes.

bpo-30119 [https://bugs.python.org/issue?@action=redirect&bpo=30119]: ftplib.FTP.putline() now throws ValueError on commands that contains CR or LF. Patch by Dong-hee Na.

bpo-30595 [https://bugs.python.org/issue?@action=redirect&bpo=30595]: multiprocessing.Queue.get() with a timeout now polls its reader in non-blocking mode if it succeeded to acquire the lock but the acquire took longer than the timeout.

bpo-29403 [https://bugs.python.org/issue?@action=redirect&bpo=29403]: Fix unittest.mock’s autospec to not fail on method-bound builtin functions. Patch by Aaron Gallagher.

bpo-30961 [https://bugs.python.org/issue?@action=redirect&bpo=30961]: Fix decrementing a borrowed reference in tracemalloc.

bpo-25684 [https://bugs.python.org/issue?@action=redirect&bpo=25684]: Change ttk.OptionMenu radiobuttons to be unique across instances of OptionMenu.

bpo-30886 [https://bugs.python.org/issue?@action=redirect&bpo=30886]: Fix multiprocessing.Queue.join_thread(): it now waits until the thread completes, even if the thread was started by the same process which created the queue.

bpo-29854 [https://bugs.python.org/issue?@action=redirect&bpo=29854]: Fix segfault in readline when using readline’s history-size option. Patch by Nir Soffer.

bpo-30319 [https://bugs.python.org/issue?@action=redirect&bpo=30319]: socket.close() now ignores ECONNRESET error.

bpo-30828 [https://bugs.python.org/issue?@action=redirect&bpo=30828]: Fix out of bounds write in asyncio.CFuture.remove_done_callback().

bpo-30807 [https://bugs.python.org/issue?@action=redirect&bpo=30807]: signal.setitimer() may disable the timer when passed a tiny value.

Tiny values (such as 1e-6) are valid non-zero values for setitimer(), which is specified as taking microsecond-resolution intervals. However, on some platform, our conversion routine could convert 1e-6 into a zero interval, therefore disabling the timer instead of (re-)scheduling it.

bpo-30441 [https://bugs.python.org/issue?@action=redirect&bpo=30441]: Fix bug when modifying os.environ while iterating over it

bpo-30532 [https://bugs.python.org/issue?@action=redirect&bpo=30532]: Fix email header value parser dropping folding white space in certain cases.

bpo-30879 [https://bugs.python.org/issue?@action=redirect&bpo=30879]: os.listdir() and os.scandir() now emit bytes names when called with bytes-like argument.

bpo-30746 [https://bugs.python.org/issue?@action=redirect&bpo=30746]: Prohibited the ‘=’ character in environment variable names in os.putenv() and os.spawn*().

bpo-29755 [https://bugs.python.org/issue?@action=redirect&bpo=29755]: Fixed the lgettext() family of functions in the gettext module. They now always return bytes.

Documentation

bpo-31294 [https://bugs.python.org/issue?@action=redirect&bpo=31294]: Fix incomplete code snippet in the ZeroMQSocketListener and ZeroMQSocketHandler examples and adapt them to Python 3.

bpo-21649 [https://bugs.python.org/issue?@action=redirect&bpo=21649]: Add RFC 7525 and Mozilla server side TLS links to SSL documentation.

bpo-30803 [https://bugs.python.org/issue?@action=redirect&bpo=30803]: Clarify doc on truth value testing. Original patch by Peter Thomassen.

Tests

bpo-31320 [https://bugs.python.org/issue?@action=redirect&bpo=31320]: Silence traceback in test_ssl

bpo-25674 [https://bugs.python.org/issue?@action=redirect&bpo=25674]: Remove sha256.tbs-internet.com ssl test

bpo-30715 [https://bugs.python.org/issue?@action=redirect&bpo=30715]: Address ALPN callback changes for OpenSSL 1.1.0f. The latest version behaves like OpenSSL 1.0.2 and no longer aborts handshake.

bpo-30822 [https://bugs.python.org/issue?@action=redirect&bpo=30822]: regrtest: Exclude tzdata from regrtest –all. When running the test suite using –use=all / -u all, exclude tzdata since it makes test_datetime too slow (15-20 min on some buildbots) which then times out on some buildbots. Fix also regrtest command line parser to allow passing -u extralargefile to run test_zipfile64.

Build

bpo-30854 [https://bugs.python.org/issue?@action=redirect&bpo=30854]: Fix compile error when compiling –without-threads. Patch by Masayuki Yamamoto.

Windows

bpo-30389 [https://bugs.python.org/issue?@action=redirect&bpo=30389]: Adds detection of Visual Studio 2017 to distutils on Windows.

bpo-31340 [https://bugs.python.org/issue?@action=redirect&bpo=31340]: Change to building with MSVC v141 (included with Visual Studio 2017)

bpo-30581 [https://bugs.python.org/issue?@action=redirect&bpo=30581]: os.cpu_count() now returns the correct number of processors on Windows when the number of logical processors is greater than 64.

bpo-30731 [https://bugs.python.org/issue?@action=redirect&bpo=30731]: Add a missing xmlns to python.manifest so that it matches the schema.

IDLE

bpo-31493 [https://bugs.python.org/issue?@action=redirect&bpo=31493]: IDLE code context – fix code update and font update timers.

Canceling timers prevents a warning message when test_idle completes.

bpo-31488 [https://bugs.python.org/issue?@action=redirect&bpo=31488]: IDLE - Update non-key options in former extension classes. When applying configdialog changes, call .reload for each feature class. Change ParenMatch so updated options affect existing instances attached to existing editor windows.

bpo-31477 [https://bugs.python.org/issue?@action=redirect&bpo=31477]: IDLE - Improve rstrip entry in doc. Strip trailing whitespace strips more than blank spaces. Multiline string literals are not skipped.

bpo-31480 [https://bugs.python.org/issue?@action=redirect&bpo=31480]: IDLE - make tests pass with zzdummy extension disabled by default.

bpo-31421 [https://bugs.python.org/issue?@action=redirect&bpo=31421]: Document how IDLE runs tkinter programs. IDLE calls tcl/tk update in the background in order to make live

interaction and experimentation with tkinter applications much easier.

bpo-31414 [https://bugs.python.org/issue?@action=redirect&bpo=31414]: IDLE – fix tk entry box tests by deleting first. Adding to an int entry is not the same as deleting and inserting because int(‘’) will fail.

bpo-31051 [https://bugs.python.org/issue?@action=redirect&bpo=31051]: Rearrange IDLE configdialog GenPage into Window, Editor, and Help sections.

bpo-30617 [https://bugs.python.org/issue?@action=redirect&bpo=30617]: IDLE - Add docstrings and tests for outwin subclass of editor.

Move some data and functions from the class to module level. Patch by Cheryl Sabella.

bpo-31287 [https://bugs.python.org/issue?@action=redirect&bpo=31287]: IDLE - Do not modify tkinter.message in test_configdialog.

bpo-27099 [https://bugs.python.org/issue?@action=redirect&bpo=27099]: Convert IDLE’s built-in ‘extensions’ to regular features.

About 10 IDLE features were implemented as supposedly optional extensions. Their different behavior could be confusing or worse for users and not good for maintenance. Hence the conversion.

The main difference for users is that user configurable key bindings for builtin features are now handled uniformly. Now, editing a binding in a keyset only affects its value in the keyset. All bindings are defined together in the system-specific default keysets in config-extensions.def. All custom keysets are saved as a whole in config-extension.cfg. All take effect as soon as one clicks Apply or Ok.

The affected events are ‘<<force-open-completions>>’, ‘<<expand-word>>’, ‘<<force-open-calltip>>’, ‘<<flash-paren>>’, ‘<<format-paragraph>>’, ‘<<run-module>>’, ‘<<check-module>>’, and ‘<<zoom-height>>’. Any (global) customizations made before 3.6.3 will not affect their keyset-specific customization after 3.6.3. and vice versa. Initial patch by Charles Wohlganger.

bpo-31206 [https://bugs.python.org/issue?@action=redirect&bpo=31206]: IDLE: Factor HighPage(Frame) class from ConfigDialog. Patch by Cheryl Sabella.

bpo-31001 [https://bugs.python.org/issue?@action=redirect&bpo=31001]: Add tests for configdialog highlight tab. Patch by Cheryl Sabella.

bpo-31205 [https://bugs.python.org/issue?@action=redirect&bpo=31205]: IDLE: Factor KeysPage(Frame) class from ConfigDialog. The slightly modified tests continue to pass. Patch by Cheryl Sabella.

bpo-31130 [https://bugs.python.org/issue?@action=redirect&bpo=31130]: IDLE – stop leaks in test_configdialog. Initial patch by Victor Stinner.

bpo-31002 [https://bugs.python.org/issue?@action=redirect&bpo=31002]: Add tests for configdialog keys tab. Patch by Cheryl Sabella.

bpo-19903 [https://bugs.python.org/issue?@action=redirect&bpo=19903]: IDLE: Calltips use inspect.signature instead of inspect.getfullargspec. This improves calltips for builtins converted to use Argument Clinic. Patch by Louie Lu.

bpo-31083 [https://bugs.python.org/issue?@action=redirect&bpo=31083]: IDLE - Add an outline of a TabPage class in configdialog. Update existing classes to match outline. Initial patch by Cheryl Sabella.

bpo-31050 [https://bugs.python.org/issue?@action=redirect&bpo=31050]: Factor GenPage(Frame) class from ConfigDialog. The slightly modified tests continue to pass. Patch by Cheryl Sabella.

bpo-31004 [https://bugs.python.org/issue?@action=redirect&bpo=31004]: IDLE - Factor FontPage(Frame) class from ConfigDialog.

Slightly modified tests continue to pass. Fix General tests. Patch mostly by Cheryl Sabella.

bpo-30781 [https://bugs.python.org/issue?@action=redirect&bpo=30781]: IDLE - Use ttk widgets in ConfigDialog. Patches by Terry Jan Reedy and Cheryl Sabella.

bpo-31060 [https://bugs.python.org/issue?@action=redirect&bpo=31060]: IDLE - Finish rearranging methods of ConfigDialog Grouping methods pertaining to each tab and the buttons will aid writing tests and improving the tabs and will enable splitting the groups into classes.

bpo-30853 [https://bugs.python.org/issue?@action=redirect&bpo=30853]: IDLE – Factor a VarTrace class out of ConfigDialog.

Instance tracers manages pairs consisting of a tk variable and a callback function. When tracing is turned on, setting the variable calls the function. Test coverage for the new class is 100%.

bpo-31003 [https://bugs.python.org/issue?@action=redirect&bpo=31003]: IDLE: Add more tests for General tab.

bpo-30993 [https://bugs.python.org/issue?@action=redirect&bpo=30993]: IDLE - Improve configdialog font page and tests.

In configdialog: Document causal pathways in create_font_tab docstring. Simplify some attribute names. Move set_samples calls to var_changed_font (idea from Cheryl Sabella). Move related functions to positions after the create widgets function.

In test_configdialog: Fix test_font_set so not order dependent. Fix renamed test_indent_scale so it tests the widget. Adjust tests for movement of set_samples call. Add tests for load functions. Put all font tests in one class and tab indent tests in another. Except for two lines, these tests completely cover the related functions.

bpo-30981 [https://bugs.python.org/issue?@action=redirect&bpo=30981]: IDLE – Add more configdialog font page tests.

bpo-28523 [https://bugs.python.org/issue?@action=redirect&bpo=28523]: IDLE: replace ‘colour’ with ‘color’ in configdialog.

bpo-30917 [https://bugs.python.org/issue?@action=redirect&bpo=30917]: Add tests for idlelib.config.IdleConf. Increase coverage from 46% to 96%. Patch by Louie Lu.

bpo-30934 [https://bugs.python.org/issue?@action=redirect&bpo=30934]: Document coverage details for idlelib tests.

Add section to idlelib/idle-test/README.txt.

Include check that branches are taken both ways.

Exclude IDLE-specific code that does not run during unit tests.

bpo-30913 [https://bugs.python.org/issue?@action=redirect&bpo=30913]: IDLE: Document ConfigDialog tk Vars, methods, and widgets in docstrings This will facilitate improving the dialog and splitting up the class. Original patch by Cheryl Sabella.

bpo-30899 [https://bugs.python.org/issue?@action=redirect&bpo=30899]: IDLE: Add tests for ConfigParser subclasses in config. Patch by Louie Lu.

bpo-30881 [https://bugs.python.org/issue?@action=redirect&bpo=30881]: IDLE: Add docstrings to browser.py. Patch by Cheryl Sabella.

bpo-30851 [https://bugs.python.org/issue?@action=redirect&bpo=30851]: IDLE: Remove unused variables in configdialog. One is a duplicate, one is set but cannot be altered by users. Patch by Cheryl Sabella.

bpo-30870 [https://bugs.python.org/issue?@action=redirect&bpo=30870]: IDLE: In Settings dialog, select font with Up, Down keys as well as mouse. Initial patch by Louie Lu.

bpo-8231 [https://bugs.python.org/issue?@action=redirect&bpo=8231]: IDLE: call config.IdleConf.GetUserCfgDir only once.

bpo-30779 [https://bugs.python.org/issue?@action=redirect&bpo=30779]: IDLE: Factor ConfigChanges class from configdialog, put in config; test. * In config, put dump test code in a function; run it and unittest in ‘if __name__ == ‘__main__’. * Add class config.ConfigChanges based on changes_class_v4.py on bpo issue. * Add class test_config.ChangesTest, partly using configdialog_tests_v1.py. * Revise configdialog to use ConfigChanges; see tracker msg297804. * Revise test_configdialog to match configdialog changes. * Remove configdialog functions unused or moved to ConfigChanges. Cheryl Sabella contributed parts of the patch.

bpo-30777 [https://bugs.python.org/issue?@action=redirect&bpo=30777]: IDLE: configdialog - Add docstrings and fix comments. Patch by Cheryl Sabella.

bpo-30495 [https://bugs.python.org/issue?@action=redirect&bpo=30495]: IDLE: Improve textview with docstrings, PEP8 names, and more tests. Patch by Cheryl Sabella.

bpo-30723 [https://bugs.python.org/issue?@action=redirect&bpo=30723]: IDLE: Make several improvements to parenmatch. Add ‘parens’ style to highlight both opener and closer. Make ‘default’ style, which is not default, a synonym for ‘opener’. Make time-delay work the same with all styles. Add help for config dialog extensions tab, including help for parenmatch. Add new tests. Original patch by Charles Wohlganger.

bpo-30674 [https://bugs.python.org/issue?@action=redirect&bpo=30674]: IDLE: add docstrings to grep module. Patch by Cheryl Sabella

bpo-21519 [https://bugs.python.org/issue?@action=redirect&bpo=21519]: IDLE’s basic custom key entry dialog now detects duplicates properly. Original patch by Saimadhav Heblikar.

bpo-29910 [https://bugs.python.org/issue?@action=redirect&bpo=29910]: IDLE no longer deletes a character after commenting out a region by a key shortcut. Add return 'break' for this and other potential conflicts between IDLE and default key bindings.

bpo-30728 [https://bugs.python.org/issue?@action=redirect&bpo=30728]: Review and change idlelib.configdialog names. Lowercase method and attribute names. Replace ‘colour’ with ‘color’, expand overly cryptic names, delete unneeded underscores. Replace import * with specific imports. Patches by Cheryl Sabella.

bpo-6739 [https://bugs.python.org/issue?@action=redirect&bpo=6739]: IDLE: Verify user-entered key sequences by trying to bind them with tk. Add tests for all 3 validation functions. Original patch by G Polo. Tests added by Cheryl Sabella.

Tools/Demos

bpo-30983 [https://bugs.python.org/issue?@action=redirect&bpo=30983]: gdb integration commands (py-bt, etc.) work on optimized shared builds now, too. PEP 523 introduced _PyEval_EvalFrameDefault which inlines PyEval_EvalFrameEx on non-debug shared builds. This broke the ability to use py-bt, py-up, and a few other Python-specific gdb integrations. The problem is fixed by only looking for _PyEval_EvalFrameDefault frames in python-gdb.py. Original patch by Bruno “Polaco” Penteado.

Python 3.6.2 final

Release date: 2017-07-17

No changes since release candidate 2

Python 3.6.2 release candidate 2

Release date: 2017-07-07

Security

bpo-30730 [https://bugs.python.org/issue?@action=redirect&bpo=30730]: Prevent environment variables injection in subprocess on Windows. Prevent passing other environment variables and command arguments.

bpo-30694 [https://bugs.python.org/issue?@action=redirect&bpo=30694]: Upgrade expat copy from 2.2.0 to 2.2.1 to get fixes of multiple security vulnerabilities including: CVE-2017-9233 (External entity infinite loop DoS), CVE-2016-9063 (Integer overflow, re-fix), CVE-2016-0718 (Fix regression bugs from 2.2.0’s fix to CVE-2016-0718) and CVE-2012-0876 (Counter hash flooding with SipHash). Note: the CVE-2016-5300 (Use os-specific entropy sources like getrandom) doesn’t impact Python, since Python already gets entropy from the OS to set the expat secret using XML_SetHashSalt().

bpo-30500 [https://bugs.python.org/issue?@action=redirect&bpo=30500]: Fix urllib.parse.splithost() to correctly parse fragments. For example, splithost('//127.0.0.1#@evil.com/') now correctly returns the 127.0.0.1 host, instead of treating @evil.com as the host in an authentication (login@host).

Python 3.6.2 release candidate 1

Release date: 2017-06-17

Core and Builtins

bpo-30682 [https://bugs.python.org/issue?@action=redirect&bpo=30682]: Removed a too-strict assertion that failed for certain f-strings, such as eval(“f’\n’”) and eval(“f’\r’”).

bpo-30604 [https://bugs.python.org/issue?@action=redirect&bpo=30604]: Move co_extra_freefuncs to not be per-thread to avoid crashes

bpo-29104 [https://bugs.python.org/issue?@action=redirect&bpo=29104]: Fixed parsing backslashes in f-strings.

bpo-27945 [https://bugs.python.org/issue?@action=redirect&bpo=27945]: Fixed various segfaults with dict when input collections are mutated during searching, inserting or comparing. Based on patches by Duane Griffin and Tim Mitchell.

bpo-25794 [https://bugs.python.org/issue?@action=redirect&bpo=25794]: Fixed type.__setattr__() and type.__delattr__() for non-interned attribute names. Based on patch by Eryk Sun.

bpo-30039 [https://bugs.python.org/issue?@action=redirect&bpo=30039]: If a KeyboardInterrupt happens when the interpreter is in the middle of resuming a chain of nested ‘yield from’ or ‘await’ calls, it’s now correctly delivered to the innermost frame.

bpo-12414 [https://bugs.python.org/issue?@action=redirect&bpo=12414]: sys.getsizeof() on a code object now returns the sizes which includes the code struct and sizes of objects which it references. Patch by Dong-hee Na.

bpo-29949 [https://bugs.python.org/issue?@action=redirect&bpo=29949]: Fix memory usage regression of set and frozenset object.

bpo-29935 [https://bugs.python.org/issue?@action=redirect&bpo=29935]: Fixed error messages in the index() method of tuple, list and deque when pass indices of wrong type.

bpo-29859 [https://bugs.python.org/issue?@action=redirect&bpo=29859]: Show correct error messages when any of the pthread_* calls in thread_pthread.h fails.

bpo-28876 [https://bugs.python.org/issue?@action=redirect&bpo=28876]: bool(range) works even if len(range) raises OverflowError.

bpo-29600 [https://bugs.python.org/issue?@action=redirect&bpo=29600]: Fix wrapping coroutine return values in StopIteration.

bpo-28856 [https://bugs.python.org/issue?@action=redirect&bpo=28856]: Fix an oversight that %b format for bytes should support objects follow the buffer protocol.

bpo-29714 [https://bugs.python.org/issue?@action=redirect&bpo=29714]: Fix a regression that bytes format may fail when containing zero bytes inside.

bpo-29478 [https://bugs.python.org/issue?@action=redirect&bpo=29478]: If max_line_length=None is specified while using the Compat32 policy, it is no longer ignored. Patch by Mircea Cosbuc.

Library

bpo-30616 [https://bugs.python.org/issue?@action=redirect&bpo=30616]: Functional API of enum allows to create empty enums. Patched by Dong-hee Na

bpo-30038 [https://bugs.python.org/issue?@action=redirect&bpo=30038]: Fix race condition between signal delivery and wakeup file descriptor. Patch by Nathaniel Smith.

bpo-23894 [https://bugs.python.org/issue?@action=redirect&bpo=23894]: lib2to3 now recognizes rb'...' and f'...' strings.

bpo-23890 [https://bugs.python.org/issue?@action=redirect&bpo=23890]: unittest.TestCase.assertRaises() now manually breaks a reference cycle to not keep objects alive longer than expected.

bpo-30149 [https://bugs.python.org/issue?@action=redirect&bpo=30149]: inspect.signature() now supports callables with variable-argument parameters wrapped with partialmethod. Patch by Dong-hee Na.

bpo-30645 [https://bugs.python.org/issue?@action=redirect&bpo=30645]: Fix path calculation in imp.load_package(), fixing it for cases when a package is only shipped with bytecodes. Patch by Alexandru Ardelean.

bpo-29931 [https://bugs.python.org/issue?@action=redirect&bpo=29931]: Fixed comparison check for ipaddress.ip_interface objects. Patch by Sanjay Sundaresan.

bpo-30605 [https://bugs.python.org/issue?@action=redirect&bpo=30605]: re.compile() no longer raises a BytesWarning when compiling a bytes instance with misplaced inline modifier. Patch by Roy Williams.

Security

bpo-29591 [https://bugs.python.org/issue?@action=redirect&bpo=29591]: Update expat copy from 2.1.1 to 2.2.0 to get fixes of CVE-2016-0718 and CVE-2016-4472. See https://sourceforge.net/p/expat/bugs/537/ for more information.

Library

bpo-24484 [https://bugs.python.org/issue?@action=redirect&bpo=24484]: Avoid race condition in multiprocessing cleanup (#2159)

bpo-28994 [https://bugs.python.org/issue?@action=redirect&bpo=28994]: The traceback no longer displayed for SystemExit raised in a callback registered by atexit.

bpo-30508 [https://bugs.python.org/issue?@action=redirect&bpo=30508]: Don’t log exceptions if Task/Future “cancel()” method was called.

bpo-28556 [https://bugs.python.org/issue?@action=redirect&bpo=28556]: Updates to typing module: Add generic AsyncContextManager, add support for ContextManager on all versions. Original PRs by Jelle Zijlstra and Ivan Levkivskyi

bpo-29870 [https://bugs.python.org/issue?@action=redirect&bpo=29870]: Fix ssl sockets leaks when connection is aborted in asyncio/ssl implementation. Patch by Michaël Sghaïer.

bpo-29743 [https://bugs.python.org/issue?@action=redirect&bpo=29743]: Closing transport during handshake process leaks open socket. Patch by Nikolay Kim

bpo-27585 [https://bugs.python.org/issue?@action=redirect&bpo=27585]: Fix waiter cancellation in asyncio.Lock. Patch by Mathieu Sornay.

bpo-30418 [https://bugs.python.org/issue?@action=redirect&bpo=30418]: On Windows, subprocess.Popen.communicate() now also ignore EINVAL on stdin.write() if the child process is still running but closed the pipe.

bpo-29822 [https://bugs.python.org/issue?@action=redirect&bpo=29822]: inspect.isabstract() now works during __init_subclass__. Patch by Nate Soares.

bpo-29581 [https://bugs.python.org/issue?@action=redirect&bpo=29581]: ABCMeta.__new__ now accepts **kwargs, allowing abstract base classes to use keyword parameters in __init_subclass__. Patch by Nate Soares.

bpo-30557 [https://bugs.python.org/issue?@action=redirect&bpo=30557]: faulthandler now correctly filters and displays exception codes on Windows

bpo-30378 [https://bugs.python.org/issue?@action=redirect&bpo=30378]: Fix the problem that logging.handlers.SysLogHandler cannot handle IPv6 addresses.

bpo-29960 [https://bugs.python.org/issue?@action=redirect&bpo=29960]: Preserve generator state when _random.Random.setstate() raises an exception. Patch by Bryan Olson.

bpo-30414 [https://bugs.python.org/issue?@action=redirect&bpo=30414]: multiprocessing.Queue._feed background running thread do not break from main loop on exception.

bpo-30003 [https://bugs.python.org/issue?@action=redirect&bpo=30003]: Fix handling escape characters in HZ codec. Based on patch by Ma Lin.

bpo-30301 [https://bugs.python.org/issue?@action=redirect&bpo=30301]: Fix AttributeError when using SimpleQueue.empty() under spawn and forkserver start methods.

bpo-30329 [https://bugs.python.org/issue?@action=redirect&bpo=30329]: imaplib and poplib now catch the Windows socket WSAEINVAL error (code 10022) on shutdown(SHUT_RDWR): An invalid operation was attempted. This error occurs sometimes on SSL connections.

bpo-30375 [https://bugs.python.org/issue?@action=redirect&bpo=30375]: Warnings emitted when compile a regular expression now always point to the line in the user code. Previously they could point into inners of the re module if emitted from inside of groups or conditionals.

bpo-30048 [https://bugs.python.org/issue?@action=redirect&bpo=30048]: Fixed Task.cancel() can be ignored when the task is running coroutine and the coroutine returned without any more await.

bpo-30266 [https://bugs.python.org/issue?@action=redirect&bpo=30266]: contextlib.AbstractContextManager now supports anti-registration by setting __enter__ = None or __exit__ = None, following the pattern introduced in bpo-25958 [https://bugs.python.org/issue?@action=redirect&bpo=25958]. Patch by Jelle Zijlstra.

bpo-30298 [https://bugs.python.org/issue?@action=redirect&bpo=30298]: Weaken the condition of deprecation warnings for inline modifiers. Now allowed several subsequential inline modifiers at the start of the pattern (e.g. '(?i)(?s)...'). In verbose mode whitespaces and comments now are allowed before and between inline modifiers (e.g. '(?x) (?i) (?s)...').

bpo-29990 [https://bugs.python.org/issue?@action=redirect&bpo=29990]: Fix range checking in GB18030 decoder. Original patch by Ma Lin.

bpo-26293 [https://bugs.python.org/issue?@action=redirect&bpo=26293]: Change resulted because of zipfile breakage. (See also: bpo-29094 [https://bugs.python.org/issue?@action=redirect&bpo=29094])

bpo-30243 [https://bugs.python.org/issue?@action=redirect&bpo=30243]: Removed the __init__ methods of _json’s scanner and encoder. Misusing them could cause memory leaks or crashes. Now scanner and encoder objects are completely initialized in the __new__ methods.

bpo-30185 [https://bugs.python.org/issue?@action=redirect&bpo=30185]: Avoid KeyboardInterrupt tracebacks in forkserver helper process when Ctrl-C is received.

bpo-28556 [https://bugs.python.org/issue?@action=redirect&bpo=28556]: Various updates to typing module: add typing.NoReturn type, use WrapperDescriptorType, minor bug-fixes. Original PRs by Jim Fasarakis-Hilliard and Ivan Levkivskyi.

bpo-30205 [https://bugs.python.org/issue?@action=redirect&bpo=30205]: Fix getsockname() for unbound AF_UNIX sockets on Linux.

bpo-30070 [https://bugs.python.org/issue?@action=redirect&bpo=30070]: Fixed leaks and crashes in errors handling in the parser module.

bpo-30061 [https://bugs.python.org/issue?@action=redirect&bpo=30061]: Fixed crashes in IOBase methods __next__() and readlines() when readline() or __next__() respectively return non-sizeable object. Fixed possible other errors caused by not checking results of PyObject_Size(), PySequence_Size(), or PyMapping_Size().

bpo-30017 [https://bugs.python.org/issue?@action=redirect&bpo=30017]: Allowed calling the close() method of the zip entry writer object multiple times. Writing to a closed writer now always produces a ValueError.

bpo-30068 [https://bugs.python.org/issue?@action=redirect&bpo=30068]: _io._IOBase.readlines will check if it’s closed first when hint is present.

bpo-29694 [https://bugs.python.org/issue?@action=redirect&bpo=29694]: Fixed race condition in pathlib mkdir with flags parents=True. Patch by Armin Rigo.

bpo-29692 [https://bugs.python.org/issue?@action=redirect&bpo=29692]: Fixed arbitrary unchaining of RuntimeError exceptions in contextlib.contextmanager. Patch by Siddharth Velankar.

bpo-29998 [https://bugs.python.org/issue?@action=redirect&bpo=29998]: Pickling and copying ImportError now preserves name and path attributes.

bpo-29953 [https://bugs.python.org/issue?@action=redirect&bpo=29953]: Fixed memory leaks in the replace() method of datetime and time objects when pass out of bound fold argument.

bpo-29942 [https://bugs.python.org/issue?@action=redirect&bpo=29942]: Fix a crash in itertools.chain.from_iterable when encountering long runs of empty iterables.

bpo-27863 [https://bugs.python.org/issue?@action=redirect&bpo=27863]: Fixed multiple crashes in ElementTree caused by race conditions and wrong types.

bpo-28699 [https://bugs.python.org/issue?@action=redirect&bpo=28699]: Fixed a bug in pools in multiprocessing.pool that raising an exception at the very first of an iterable may swallow the exception or make the program hang. Patch by Davin Potts and Xiang Zhang.

bpo-25803 [https://bugs.python.org/issue?@action=redirect&bpo=25803]: Avoid incorrect errors raised by Path.mkdir(exist_ok=True) when the OS gives priority to errors such as EACCES over EEXIST.

bpo-29861 [https://bugs.python.org/issue?@action=redirect&bpo=29861]: Release references to tasks, their arguments and their results as soon as they are finished in multiprocessing.Pool.

bpo-29884 [https://bugs.python.org/issue?@action=redirect&bpo=29884]: faulthandler: Restore the old sigaltstack during teardown. Patch by Christophe Zeitouny.

bpo-25455 [https://bugs.python.org/issue?@action=redirect&bpo=25455]: Fixed crashes in repr of recursive buffered file-like objects.

bpo-29800 [https://bugs.python.org/issue?@action=redirect&bpo=29800]: Fix crashes in partial.__repr__ if the keys of partial.keywords are not strings. Patch by Michael Seifert.

bpo-29742 [https://bugs.python.org/issue?@action=redirect&bpo=29742]: get_extra_info() raises exception if get called on closed ssl transport. Patch by Nikolay Kim.

bpo-8256 [https://bugs.python.org/issue?@action=redirect&bpo=8256]: Fixed possible failing or crashing input() if attributes “encoding” or “errors” of sys.stdin or sys.stdout are not set or are not strings.

bpo-28298 [https://bugs.python.org/issue?@action=redirect&bpo=28298]: Fix a bug that prevented array ‘Q’, ‘L’ and ‘I’ from accepting big intables (objects that have __int__) as elements. Patch by Oren Milman.

bpo-28231 [https://bugs.python.org/issue?@action=redirect&bpo=28231]: The zipfile module now accepts path-like objects for external paths.

bpo-26915 [https://bugs.python.org/issue?@action=redirect&bpo=26915]: index() and count() methods of collections.abc.Sequence now check identity before checking equality when do comparisons.

bpo-29615 [https://bugs.python.org/issue?@action=redirect&bpo=29615]: SimpleXMLRPCDispatcher no longer chains KeyError (or any other exception) to exception(s) raised in the dispatched methods. Patch by Petr Motejlek.

bpo-30177 [https://bugs.python.org/issue?@action=redirect&bpo=30177]: path.resolve(strict=False) no longer cuts the path after the first element not present in the filesystem. Patch by Antoine Pietri.

IDLE

bpo-15786 [https://bugs.python.org/issue?@action=redirect&bpo=15786]: Fix several problems with IDLE’s autocompletion box. The following should now work: clicking on selection box items; using the scrollbar; selecting an item by hitting Return. Hangs on MacOSX should no longer happen. Patch by Louie Lu.

bpo-25514 [https://bugs.python.org/issue?@action=redirect&bpo=25514]: Add doc subsubsection about IDLE failure to start. Popup no-connection message directs users to this section.

bpo-30642 [https://bugs.python.org/issue?@action=redirect&bpo=30642]: Fix reference leaks in IDLE tests. Patches by Louie Lu and Terry Jan Reedy.

bpo-30495 [https://bugs.python.org/issue?@action=redirect&bpo=30495]: Add docstrings for textview.py and use PEP8 names. Patches by Cheryl Sabella and Terry Jan Reedy.

bpo-30290 [https://bugs.python.org/issue?@action=redirect&bpo=30290]: Help-about: use pep8 names and add tests. Increase coverage to 100%. Patches by Louie Lu, Cheryl Sabella, and Terry Jan Reedy.

bpo-30303 [https://bugs.python.org/issue?@action=redirect&bpo=30303]: Add _utest option to textview; add new tests. Increase coverage to 100%. Patches by Louie Lu and Terry Jan Reedy.

C API

bpo-27867 [https://bugs.python.org/issue?@action=redirect&bpo=27867]: Function PySlice_GetIndicesEx() no longer replaced with a macro if Py_LIMITED_API is not set.

Build

bpo-29941 [https://bugs.python.org/issue?@action=redirect&bpo=29941]: Add --with-assertions configure flag to explicitly enable C assert() checks. Defaults to off. --with-pydebug implies --with-assertions.

bpo-28787 [https://bugs.python.org/issue?@action=redirect&bpo=28787]: Fix out-of-tree builds of Python when configured with --with--dtrace.

bpo-29243 [https://bugs.python.org/issue?@action=redirect&bpo=29243]: Prevent unnecessary rebuilding of Python during make test, make install and some other make targets when configured with --enable-optimizations.

bpo-23404 [https://bugs.python.org/issue?@action=redirect&bpo=23404]: Don’t regenerate generated files based on file modification time anymore: the action is now explicit. Replace make touch with make regen-all.

bpo-29643 [https://bugs.python.org/issue?@action=redirect&bpo=29643]: Fix --enable-optimization didn’t work.

Documentation

bpo-30176 [https://bugs.python.org/issue?@action=redirect&bpo=30176]: Add missing attribute related constants in curses documentation.

bpo-30052 [https://bugs.python.org/issue?@action=redirect&bpo=30052]: the link targets for bytes() and bytearray() are now their respective type definitions, rather than the corresponding builtin function entries. Use bytes and bytearray to reference the latter.

In order to ensure this and future cross-reference updates are applied automatically, the daily documentation builds now disable the default output caching features in Sphinx.

bpo-26985 [https://bugs.python.org/issue?@action=redirect&bpo=26985]: Add missing info of code object in inspect documentation.

Tools/Demos

bpo-29367 [https://bugs.python.org/issue?@action=redirect&bpo=29367]: python-gdb.py now supports also method-wrapper (wrapperobject) objects.

Tests

bpo-30357 [https://bugs.python.org/issue?@action=redirect&bpo=30357]: test_thread: setUp() now uses support.threading_setup() and support.threading_cleanup() to wait until threads complete to avoid random side effects on following tests. Initial patch written by Grzegorz Grzywacz.

bpo-30197 [https://bugs.python.org/issue?@action=redirect&bpo=30197]: Enhanced functions swap_attr() and swap_item() in the test.support module. They now work when delete replaced attribute or item inside the with statement. The old value of the attribute or item (or None if it doesn’t exist) now will be assigned to the target of the “as” clause, if there is one.

Windows

bpo-30687 [https://bugs.python.org/issue?@action=redirect&bpo=30687]: Locate msbuild.exe on Windows when building rather than vcvarsall.bat

bpo-30450 [https://bugs.python.org/issue?@action=redirect&bpo=30450]: The build process on Windows no longer depends on Subversion, instead pulling external code from GitHub via a Python script. If Python 3.6 is not found on the system (via py -3.6), NuGet is used to download a copy of 32-bit Python.

Python 3.6.1 final

Release date: 2017-03-21

Core and Builtins

bpo-29723 [https://bugs.python.org/issue?@action=redirect&bpo=29723]: The sys.path[0] initialization change for bpo-29139 [https://bugs.python.org/issue?@action=redirect&bpo=29139] caused a regression by revealing an inconsistency in how sys.path is initialized when executing __main__ from a zipfile, directory, or other import location. The interpreter now consistently avoids ever adding the import location’s parent directory to sys.path, and ensures no other sys.path entries are inadvertently modified when inserting the import location named on the command line.

Build

bpo-27593 [https://bugs.python.org/issue?@action=redirect&bpo=27593]: fix format of git information used in sys.version

Fix incompatible comment in python.h

Python 3.6.1 release candidate 1

Release date: 2017-03-04

Core and Builtins

bpo-28893 [https://bugs.python.org/issue?@action=redirect&bpo=28893]: Set correct __cause__ for errors about invalid awaitables returned from __aiter__ and __anext__.

bpo-29683 [https://bugs.python.org/issue?@action=redirect&bpo=29683]: Fixes to memory allocation in _PyCode_SetExtra. Patch by Brian Coleman.

bpo-29684 [https://bugs.python.org/issue?@action=redirect&bpo=29684]: Fix minor regression of PyEval_CallObjectWithKeywords. It should raise TypeError when kwargs is not a dict. But it might cause segv when args=NULL and kwargs is not a dict.

bpo-28598 [https://bugs.python.org/issue?@action=redirect&bpo=28598]: Support __rmod__ for subclasses of str being called before str.__mod__. Patch by Martijn Pieters.

bpo-29607 [https://bugs.python.org/issue?@action=redirect&bpo=29607]: Fix stack_effect computation for CALL_FUNCTION_EX. Patch by Matthieu Dartiailh.

bpo-29602 [https://bugs.python.org/issue?@action=redirect&bpo=29602]: Fix incorrect handling of signed zeros in complex constructor for complex subclasses and for inputs having a __complex__ method. Patch by Serhiy Storchaka.

bpo-29347 [https://bugs.python.org/issue?@action=redirect&bpo=29347]: Fixed possibly dereferencing undefined pointers when creating weakref objects.

bpo-29438 [https://bugs.python.org/issue?@action=redirect&bpo=29438]: Fixed use-after-free problem in key sharing dict.

bpo-29319 [https://bugs.python.org/issue?@action=redirect&bpo=29319]: Prevent RunMainFromImporter overwriting sys.path[0].

bpo-29337 [https://bugs.python.org/issue?@action=redirect&bpo=29337]: Fixed possible BytesWarning when compare the code objects. Warnings could be emitted at compile time.

bpo-29327 [https://bugs.python.org/issue?@action=redirect&bpo=29327]: Fixed a crash when pass the iterable keyword argument to sorted().

bpo-29034 [https://bugs.python.org/issue?@action=redirect&bpo=29034]: Fix memory leak and use-after-free in os module (path_converter).

bpo-29159 [https://bugs.python.org/issue?@action=redirect&bpo=29159]: Fix regression in bytes(x) when x.__index__() raises Exception.

bpo-28932 [https://bugs.python.org/issue?@action=redirect&bpo=28932]: Do not include <sys/random.h> if it does not exist.

bpo-25677 [https://bugs.python.org/issue?@action=redirect&bpo=25677]: Correct the positioning of the syntax error caret for indented blocks. Based on patch by Michael Layzell.

bpo-29000 [https://bugs.python.org/issue?@action=redirect&bpo=29000]: Fixed bytes formatting of octals with zero padding in alternate form.

bpo-26919 [https://bugs.python.org/issue?@action=redirect&bpo=26919]: On Android, operating system data is now always encoded/decoded to/from UTF-8, instead of the locale encoding to avoid inconsistencies with os.fsencode() and os.fsdecode() which are already using UTF-8.

bpo-28991 [https://bugs.python.org/issue?@action=redirect&bpo=28991]: functools.lru_cache() was susceptible to an obscure reentrancy bug triggerable by a monkey-patched len() function.

bpo-28739 [https://bugs.python.org/issue?@action=redirect&bpo=28739]: f-string expressions are no longer accepted as docstrings and by ast.literal_eval() even if they do not include expressions.

bpo-28512 [https://bugs.python.org/issue?@action=redirect&bpo=28512]: Fixed setting the offset attribute of SyntaxError by PyErr_SyntaxLocationEx() and PyErr_SyntaxLocationObject().

bpo-28918 [https://bugs.python.org/issue?@action=redirect&bpo=28918]: Fix the cross compilation of xxlimited when Python has been built with Py_DEBUG defined.

bpo-28731 [https://bugs.python.org/issue?@action=redirect&bpo=28731]: Optimize _PyDict_NewPresized() to create correct size dict. Improve speed of dict literal with constant keys up to 30%.

Library

bpo-29169 [https://bugs.python.org/issue?@action=redirect&bpo=29169]: Update zlib to 1.2.11.

bpo-29623 [https://bugs.python.org/issue?@action=redirect&bpo=29623]: Allow use of path-like object as a single argument in ConfigParser.read(). Patch by David Ellis.

bpo-28963 [https://bugs.python.org/issue?@action=redirect&bpo=28963]: Fix out of bound iteration in asyncio.Future.remove_done_callback implemented in C.

bpo-29704 [https://bugs.python.org/issue?@action=redirect&bpo=29704]: asyncio.subprocess.SubprocessStreamProtocol no longer closes before all pipes are closed.

bpo-29271 [https://bugs.python.org/issue?@action=redirect&bpo=29271]: Fix Task.current_task and Task.all_tasks implemented in C to accept None argument as their pure Python implementation.

bpo-29703 [https://bugs.python.org/issue?@action=redirect&bpo=29703]: Fix asyncio to support instantiation of new event loops in child processes.

bpo-29376 [https://bugs.python.org/issue?@action=redirect&bpo=29376]: Fix assertion error in threading._DummyThread.is_alive().

bpo-28624 [https://bugs.python.org/issue?@action=redirect&bpo=28624]: Add a test that checks that cwd parameter of Popen() accepts PathLike objects. Patch by Sayan Chowdhury.

bpo-28518 [https://bugs.python.org/issue?@action=redirect&bpo=28518]: Start a transaction implicitly before a DML statement. Patch by Aviv Palivoda.

bpo-29532 [https://bugs.python.org/issue?@action=redirect&bpo=29532]: Altering a kwarg dictionary passed to functools.partial() no longer affects a partial object after creation.

bpo-29110 [https://bugs.python.org/issue?@action=redirect&bpo=29110]: Fix file object leak in aifc.open() when file is given as a filesystem path and is not in valid AIFF format. Patch by Anthony Zhang.

bpo-28556 [https://bugs.python.org/issue?@action=redirect&bpo=28556]: Various updates to typing module: typing.Counter, typing.ChainMap, improved ABC caching, etc. Original PRs by Jelle Zijlstra, Ivan Levkivskyi, Manuel Krebber, and Łukasz Langa.

bpo-29100 [https://bugs.python.org/issue?@action=redirect&bpo=29100]: Fix datetime.fromtimestamp() regression introduced in Python 3.6.0: check minimum and maximum years.

bpo-29519 [https://bugs.python.org/issue?@action=redirect&bpo=29519]: Fix weakref spewing exceptions during interpreter shutdown when used with a rare combination of multiprocessing and custom codecs.

bpo-29416 [https://bugs.python.org/issue?@action=redirect&bpo=29416]: Prevent infinite loop in pathlib.Path.mkdir

bpo-29444 [https://bugs.python.org/issue?@action=redirect&bpo=29444]: Fixed out-of-bounds buffer access in the group() method of the match object. Based on patch by WGH.

bpo-29335 [https://bugs.python.org/issue?@action=redirect&bpo=29335]: Fix subprocess.Popen.wait() when the child process has exited to a stopped instead of terminated state (ex: when under ptrace).

bpo-29290 [https://bugs.python.org/issue?@action=redirect&bpo=29290]: Fix a regression in argparse that help messages would wrap at non-breaking spaces.

bpo-28735 [https://bugs.python.org/issue?@action=redirect&bpo=28735]: Fixed the comparison of mock.MagickMock with mock.ANY.

bpo-29316 [https://bugs.python.org/issue?@action=redirect&bpo=29316]: Restore the provisional status of typing module, add corresponding note to documentation. Patch by Ivan L.

bpo-29219 [https://bugs.python.org/issue?@action=redirect&bpo=29219]: Fixed infinite recursion in the repr of uninitialized ctypes.CDLL instances.

bpo-29011 [https://bugs.python.org/issue?@action=redirect&bpo=29011]: Fix an important omission by adding Deque to the typing module.

bpo-28969 [https://bugs.python.org/issue?@action=redirect&bpo=28969]: Fixed race condition in C implementation of functools.lru_cache. KeyError could be raised when cached function with full cache was simultaneously called from differen threads with the same uncached arguments.

bpo-29142 [https://bugs.python.org/issue?@action=redirect&bpo=29142]: In urllib.request, suffixes in no_proxy environment variable with leading dots could match related hostnames again (e.g. .b.c matches a.b.c). Patch by Milan Oberkirch.

bpo-28961 [https://bugs.python.org/issue?@action=redirect&bpo=28961]: Fix unittest.mock._Call helper: don’t ignore the name parameter anymore. Patch written by Jiajun Huang.

bpo-29203 [https://bugs.python.org/issue?@action=redirect&bpo=29203]: functools.lru_cache() now respects PEP 468 and preserves the order of keyword arguments. f(a=1, b=2) is now cached separately from f(b=2, a=1) since both calls could potentially give different results.

bpo-15812 [https://bugs.python.org/issue?@action=redirect&bpo=15812]: inspect.getframeinfo() now correctly shows the first line of a context. Patch by Sam Breese.

bpo-29094 [https://bugs.python.org/issue?@action=redirect&bpo=29094]: Offsets in a ZIP file created with extern file object and modes “w” and “x” now are relative to the start of the file.

bpo-29085 [https://bugs.python.org/issue?@action=redirect&bpo=29085]: Allow random.Random.seed() to use high quality OS randomness rather than the pid and time.

bpo-29061 [https://bugs.python.org/issue?@action=redirect&bpo=29061]: Fixed bug in secrets.randbelow() which would hang when given a negative input. Patch by Brendan Donegan.

bpo-29079 [https://bugs.python.org/issue?@action=redirect&bpo=29079]: Prevent infinite loop in pathlib.resolve() on Windows

bpo-13051 [https://bugs.python.org/issue?@action=redirect&bpo=13051]: Fixed recursion errors in large or resized curses.textpad.Textbox. Based on patch by Tycho Andersen.

bpo-29119 [https://bugs.python.org/issue?@action=redirect&bpo=29119]: Fix weakrefs in the pure python version of collections.OrderedDict move_to_end() method. Contributed by Andra Bogildea.

bpo-9770 [https://bugs.python.org/issue?@action=redirect&bpo=9770]: curses.ascii predicates now work correctly with negative integers.

bpo-28427 [https://bugs.python.org/issue?@action=redirect&bpo=28427]: old keys should not remove new values from WeakValueDictionary when collecting from another thread.

bpo-28923 [https://bugs.python.org/issue?@action=redirect&bpo=28923]: Remove editor artifacts from Tix.py.

bpo-29055 [https://bugs.python.org/issue?@action=redirect&bpo=29055]: Neaten-up empty population error on random.choice() by suppressing the upstream exception.

bpo-28871 [https://bugs.python.org/issue?@action=redirect&bpo=28871]: Fixed a crash when deallocate deep ElementTree.

bpo-19542 [https://bugs.python.org/issue?@action=redirect&bpo=19542]: Fix bugs in WeakValueDictionary.setdefault() and WeakValueDictionary.pop() when a GC collection happens in another thread.

bpo-20191 [https://bugs.python.org/issue?@action=redirect&bpo=20191]: Fixed a crash in resource.prlimit() when passing a sequence that doesn’t own its elements as limits.

bpo-28779 [https://bugs.python.org/issue?@action=redirect&bpo=28779]: multiprocessing.set_forkserver_preload() would crash the forkserver process if a preloaded module instantiated some multiprocessing objects such as locks.

bpo-28847 [https://bugs.python.org/issue?@action=redirect&bpo=28847]: dbm.dumb now supports reading read-only files and no longer writes the index file when it is not changed.

bpo-26937 [https://bugs.python.org/issue?@action=redirect&bpo=26937]: The chown() method of the tarfile.TarFile class does not fail now when the grp module cannot be imported, as for example on Android platforms.

IDLE

bpo-29071 [https://bugs.python.org/issue?@action=redirect&bpo=29071]: IDLE colors f-string prefixes (but not invalid ur prefixes).

bpo-28572 [https://bugs.python.org/issue?@action=redirect&bpo=28572]: Add 10% to coverage of IDLE’s test_configdialog. Update and augment description of the configuration system.

Windows

bpo-29579 [https://bugs.python.org/issue?@action=redirect&bpo=29579]: Removes readme.txt from the installer

bpo-29326 [https://bugs.python.org/issue?@action=redirect&bpo=29326]: Ignores blank lines in ._pth files (Patch by Alexey Izbyshev)

bpo-28164 [https://bugs.python.org/issue?@action=redirect&bpo=28164]: Correctly handle special console filenames (patch by Eryk Sun)

bpo-29409 [https://bugs.python.org/issue?@action=redirect&bpo=29409]: Implement PEP 529 for io.FileIO (Patch by Eryk Sun)

bpo-29392 [https://bugs.python.org/issue?@action=redirect&bpo=29392]: Prevent crash when passing invalid arguments into msvcrt module.

bpo-25778 [https://bugs.python.org/issue?@action=redirect&bpo=25778]: winreg does not truncate string correctly (Patch by Eryk Sun)

bpo-28896 [https://bugs.python.org/issue?@action=redirect&bpo=28896]: Deprecate WindowsRegistryFinder and disable it by default.

C API

bpo-27867 [https://bugs.python.org/issue?@action=redirect&bpo=27867]: Function PySlice_GetIndicesEx() is replaced with a macro if Py_LIMITED_API is not set or set to the value between 0x03050400 and 0x03060000 (not including) or 0x03060100 or higher.

bpo-29083 [https://bugs.python.org/issue?@action=redirect&bpo=29083]: Fixed the declaration of some public API functions. PyArg_VaParse() and PyArg_VaParseTupleAndKeywords() were not available in limited API. PyArg_ValidateKeywordArguments(), PyArg_UnpackTuple() and Py_BuildValue() were not available in limited API of version < 3.3 when PY_SSIZE_T_CLEAN is defined.

bpo-29058 [https://bugs.python.org/issue?@action=redirect&bpo=29058]: All stable API extensions added after Python 3.2 are now available only when Py_LIMITED_API is set to the PY_VERSION_HEX value of the minimum Python version supporting this API.

Documentation

bpo-28929 [https://bugs.python.org/issue?@action=redirect&bpo=28929]: Link the documentation to its source file on GitHub.

bpo-25008 [https://bugs.python.org/issue?@action=redirect&bpo=25008]: Document smtpd.py as effectively deprecated and add a pointer to aiosmtpd, a third-party asyncio-based replacement.

bpo-26355 [https://bugs.python.org/issue?@action=redirect&bpo=26355]: Add canonical header link on each page to corresponding major version of the documentation. Patch by Matthias Bussonnier.

bpo-29349 [https://bugs.python.org/issue?@action=redirect&bpo=29349]: Fix Python 2 syntax in code for building the documentation.

Tests

bpo-28087 [https://bugs.python.org/issue?@action=redirect&bpo=28087]: Skip test_asyncore and test_eintr poll failures on macOS. Skip some tests of select.poll when running on macOS due to unresolved issues with the underlying system poll function on some macOS versions.

bpo-29571 [https://bugs.python.org/issue?@action=redirect&bpo=29571]: to match the behaviour of the re.LOCALE flag, test_re.test_locale_flag now uses locale.getpreferredencoding(False) to determine the candidate encoding for the test regex (allowing it to correctly skip the test when the default locale encoding is a multi-byte encoding)

bpo-28950 [https://bugs.python.org/issue?@action=redirect&bpo=28950]: Disallow -j0 to be combined with -T/-l in regrtest command line arguments.

bpo-28683 [https://bugs.python.org/issue?@action=redirect&bpo=28683]: Fix the tests that bind() a unix socket and raise PermissionError on Android for a non-root user.

bpo-26939 [https://bugs.python.org/issue?@action=redirect&bpo=26939]: Add the support.setswitchinterval() function to fix test_functools hanging on the Android armv7 qemu emulator.

Build

bpo-27593 [https://bugs.python.org/issue?@action=redirect&bpo=27593]: sys.version and the platform module python_build(), python_branch(), and python_revision() functions now use git information rather than hg when building from a repo.

bpo-29572 [https://bugs.python.org/issue?@action=redirect&bpo=29572]: Update Windows build and OS X installers to use OpenSSL 1.0.2k.

bpo-26851 [https://bugs.python.org/issue?@action=redirect&bpo=26851]: Set Android compilation and link flags.

bpo-28768 [https://bugs.python.org/issue?@action=redirect&bpo=28768]: Fix implicit declaration of function _setmode. Patch by Masayuki Yamamoto

bpo-29080 [https://bugs.python.org/issue?@action=redirect&bpo=29080]: Removes hard dependency on hg.exe from PCBuild/build.bat

bpo-23903 [https://bugs.python.org/issue?@action=redirect&bpo=23903]: Added missed names to PC/python3.def.

bpo-28762 [https://bugs.python.org/issue?@action=redirect&bpo=28762]: lockf() is available on Android API level 24, but the F_LOCK macro is not defined in android-ndk-r13.

bpo-28538 [https://bugs.python.org/issue?@action=redirect&bpo=28538]: Fix the compilation error that occurs because if_nameindex() is available on Android API level 24, but the if_nameindex structure is not defined.

bpo-20211 [https://bugs.python.org/issue?@action=redirect&bpo=20211]: Do not add the directory for installing C header files and the directory for installing object code libraries to the cross compilation search paths. Original patch by Thomas Petazzoni.

bpo-28849 [https://bugs.python.org/issue?@action=redirect&bpo=28849]: Do not define sys.implementation._multiarch on Android.

Python 3.6.0 final

Release date: 2016-12-23

No changes since release candidate 2

Python 3.6.0 release candidate 2

Release date: 2016-12-16

Core and Builtins

bpo-28147 [https://bugs.python.org/issue?@action=redirect&bpo=28147]: Fix a memory leak in split-table dictionaries: setattr() must not convert combined table into split table. Patch written by INADA Naoki.

bpo-28990 [https://bugs.python.org/issue?@action=redirect&bpo=28990]: Fix asyncio SSL hanging if connection is closed before handshake is completed. (Patch by HoHo-Ho)

Tools/Demos

bpo-28770 [https://bugs.python.org/issue?@action=redirect&bpo=28770]: Fix python-gdb.py for fastcalls.

Windows

bpo-28896 [https://bugs.python.org/issue?@action=redirect&bpo=28896]: Deprecate WindowsRegistryFinder.

Build

bpo-28898 [https://bugs.python.org/issue?@action=redirect&bpo=28898]: Prevent gdb build errors due to HAVE_LONG_LONG redefinition.

Python 3.6.0 release candidate 1

Release date: 2016-12-06

Core and Builtins

bpo-23722 [https://bugs.python.org/issue?@action=redirect&bpo=23722]: Rather than silently producing a class that doesn’t support zero-argument super() in methods, failing to pass the new __classcell__ namespace entry up to type.__new__ now results in a DeprecationWarning and a class that supports zero-argument super().

bpo-28797 [https://bugs.python.org/issue?@action=redirect&bpo=28797]: Modifying the class __dict__ inside the __set_name__ method of a descriptor that is used inside that class no longer prevents calling the __set_name__ method of other descriptors.

bpo-28782 [https://bugs.python.org/issue?@action=redirect&bpo=28782]: Fix a bug in the implementation yield from when checking if the next instruction is YIELD_FROM. Regression introduced by WORDCODE (bpo-26647 [https://bugs.python.org/issue?@action=redirect&bpo=26647]).

Library

bpo-27030 [https://bugs.python.org/issue?@action=redirect&bpo=27030]: Unknown escapes in re.sub() replacement template are allowed again. But they still are deprecated and will be disabled in 3.7.

bpo-28835 [https://bugs.python.org/issue?@action=redirect&bpo=28835]: Fix a regression introduced in warnings.catch_warnings(): call warnings.showwarning() if it was overriden inside the context manager.

bpo-27172 [https://bugs.python.org/issue?@action=redirect&bpo=27172]: To assist with upgrades from 2.7, the previously documented deprecation of inspect.getfullargspec() has been reversed. This decision may be revisited again after the Python 2.7 branch is no longer officially supported.

bpo-26273 [https://bugs.python.org/issue?@action=redirect&bpo=26273]: Add new socket.TCP_CONGESTION (Linux 2.6.13) and socket.TCP_USER_TIMEOUT (Linux 2.6.37) constants. Patch written by Omar Sandoval.

bpo-24142 [https://bugs.python.org/issue?@action=redirect&bpo=24142]: Reading a corrupt config file left configparser in an invalid state. Original patch by Florian Höch.

bpo-28843 [https://bugs.python.org/issue?@action=redirect&bpo=28843]: Fix asyncio C Task to handle exceptions __traceback__.

C API

bpo-28808 [https://bugs.python.org/issue?@action=redirect&bpo=28808]: PyUnicode_CompareWithASCIIString() now never raises exceptions.

Documentation

bpo-23722 [https://bugs.python.org/issue?@action=redirect&bpo=23722]: The data model reference and the porting section in the What’s New guide now cover the additional __classcell__ handling needed for custom metaclasses to fully support PEP 487 and zero-argument super().

Tools/Demos

bpo-28023 [https://bugs.python.org/issue?@action=redirect&bpo=28023]: Fix python-gdb.py didn’t support new dict implementation.

Python 3.6.0 beta 4

Release date: 2016-11-21

Core and Builtins

bpo-28532 [https://bugs.python.org/issue?@action=redirect&bpo=28532]: Show sys.version when -V option is supplied twice.

bpo-27100 [https://bugs.python.org/issue?@action=redirect&bpo=27100]: The with-statement now checks for __enter__ before it checks for __exit__. This gives less confusing error messages when both methods are missing. Patch by Jonathan Ellington.

bpo-28746 [https://bugs.python.org/issue?@action=redirect&bpo=28746]: Fix the set_inheritable() file descriptor method on platforms that do not have the ioctl FIOCLEX and FIONCLEX commands.

bpo-26920 [https://bugs.python.org/issue?@action=redirect&bpo=26920]: Fix not getting the locale’s charset upon initializing the interpreter, on platforms that do not have langinfo.

bpo-28648 [https://bugs.python.org/issue?@action=redirect&bpo=28648]: Fixed crash in Py_DecodeLocale() in debug build on Mac OS X when decode astral characters. Patch by Xiang Zhang.

bpo-19398 [https://bugs.python.org/issue?@action=redirect&bpo=19398]: Extra slash no longer added to sys.path components in case of empty compile-time PYTHONPATH components.

bpo-28665 [https://bugs.python.org/issue?@action=redirect&bpo=28665]: Improve speed of the STORE_DEREF opcode by 40%.

bpo-28583 [https://bugs.python.org/issue?@action=redirect&bpo=28583]: PyDict_SetDefault didn’t combine split table when needed. Patch by Xiang Zhang.

bpo-27243 [https://bugs.python.org/issue?@action=redirect&bpo=27243]: Change PendingDeprecationWarning -> DeprecationWarning. As it was agreed in the issue, __aiter__ returning an awaitable should result in PendingDeprecationWarning in 3.5 and in DeprecationWarning in 3.6.

bpo-26182 [https://bugs.python.org/issue?@action=redirect&bpo=26182]: Fix a refleak in code that raises DeprecationWarning.

bpo-28721 [https://bugs.python.org/issue?@action=redirect&bpo=28721]: Fix asynchronous generators aclose() and athrow() to handle StopAsyncIteration propagation properly.

Library

bpo-28752 [https://bugs.python.org/issue?@action=redirect&bpo=28752]: Restored the __reduce__() methods of datetime objects.

bpo-28727 [https://bugs.python.org/issue?@action=redirect&bpo=28727]: Regular expression patterns, _sre.SRE_Pattern objects created by re.compile(), become comparable (only x==y and x!=y operators). This change should fix the bpo-18383 [https://bugs.python.org/issue?@action=redirect&bpo=18383]: don’t duplicate warning filters when the warnings module is reloaded (thing usually only done in unit tests).

bpo-20572 [https://bugs.python.org/issue?@action=redirect&bpo=20572]: The subprocess.Popen.wait method’s undocumented endtime parameter now raises a DeprecationWarning.

bpo-25659 [https://bugs.python.org/issue?@action=redirect&bpo=25659]: In ctypes, prevent a crash calling the from_buffer() and from_buffer_copy() methods on abstract classes like Array.

bpo-19717 [https://bugs.python.org/issue?@action=redirect&bpo=19717]: Makes Path.resolve() succeed on paths that do not exist. Patch by Vajrasky Kok

bpo-28563 [https://bugs.python.org/issue?@action=redirect&bpo=28563]: Fixed possible DoS and arbitrary code execution when handle plural form selections in the gettext module. The expression parser now supports exact syntax supported by GNU gettext.

bpo-28387 [https://bugs.python.org/issue?@action=redirect&bpo=28387]: Fixed possible crash in _io.TextIOWrapper deallocator when the garbage collector is invoked in other thread. Based on patch by Sebastian Cufre.

bpo-28600 [https://bugs.python.org/issue?@action=redirect&bpo=28600]: Optimize loop.call_soon.

bpo-28613 [https://bugs.python.org/issue?@action=redirect&bpo=28613]: Fix get_event_loop() return the current loop if called from coroutines/callbacks.

bpo-28634 [https://bugs.python.org/issue?@action=redirect&bpo=28634]: Fix asyncio.isfuture() to support unittest.Mock.

bpo-26081 [https://bugs.python.org/issue?@action=redirect&bpo=26081]: Fix refleak in _asyncio.Future.__iter__().throw.

bpo-28639 [https://bugs.python.org/issue?@action=redirect&bpo=28639]: Fix inspect.isawaitable to always return bool Patch by Justin Mayfield.

bpo-28652 [https://bugs.python.org/issue?@action=redirect&bpo=28652]: Make loop methods reject socket kinds they do not support.

bpo-28653 [https://bugs.python.org/issue?@action=redirect&bpo=28653]: Fix a refleak in functools.lru_cache.

bpo-28703 [https://bugs.python.org/issue?@action=redirect&bpo=28703]: Fix asyncio.iscoroutinefunction to handle Mock objects.

bpo-28704 [https://bugs.python.org/issue?@action=redirect&bpo=28704]: Fix create_unix_server to support Path-like objects (PEP 519).

bpo-28720 [https://bugs.python.org/issue?@action=redirect&bpo=28720]: Add collections.abc.AsyncGenerator.

Documentation

bpo-28513 [https://bugs.python.org/issue?@action=redirect&bpo=28513]: Documented command-line interface of zipfile.

Tests

bpo-28666 [https://bugs.python.org/issue?@action=redirect&bpo=28666]: Now test.support.rmtree is able to remove unwritable or unreadable directories.

bpo-23839 [https://bugs.python.org/issue?@action=redirect&bpo=23839]: Various caches now are cleared before running every test file.

Build

bpo-10656 [https://bugs.python.org/issue?@action=redirect&bpo=10656]: Fix out-of-tree building on AIX. Patch by Tristan Carel and Michael Haubenwallner.

bpo-26359 [https://bugs.python.org/issue?@action=redirect&bpo=26359]: Rename –with-optimiations to –enable-optimizations.

bpo-28676 [https://bugs.python.org/issue?@action=redirect&bpo=28676]: Prevent missing ‘getentropy’ declaration warning on macOS. Patch by Gareth Rees.

Python 3.6.0 beta 3

Release date: 2016-10-31

Core and Builtins

bpo-28128 [https://bugs.python.org/issue?@action=redirect&bpo=28128]: Deprecation warning for invalid str and byte escape sequences now prints better information about where the error occurs. Patch by Serhiy Storchaka and Eric Smith.

bpo-28509 [https://bugs.python.org/issue?@action=redirect&bpo=28509]: dict.update() no longer allocate unnecessary large memory.

bpo-28426 [https://bugs.python.org/issue?@action=redirect&bpo=28426]: Fixed potential crash in PyUnicode_AsDecodedObject() in debug build.

bpo-28517 [https://bugs.python.org/issue?@action=redirect&bpo=28517]: Fixed of-by-one error in the peephole optimizer that caused keeping unreachable code.

bpo-28214 [https://bugs.python.org/issue?@action=redirect&bpo=28214]: Improved exception reporting for problematic __set_name__ attributes.

bpo-23782 [https://bugs.python.org/issue?@action=redirect&bpo=23782]: Fixed possible memory leak in _PyTraceback_Add() and exception loss in PyTraceBack_Here().

bpo-28471 [https://bugs.python.org/issue?@action=redirect&bpo=28471]: Fix “Python memory allocator called without holding the GIL” crash in socket.setblocking.

Library

bpo-27517 [https://bugs.python.org/issue?@action=redirect&bpo=27517]: LZMA compressor and decompressor no longer raise exceptions if given empty data twice. Patch by Benjamin Fogle.

bpo-28549 [https://bugs.python.org/issue?@action=redirect&bpo=28549]: Fixed segfault in curses’s addch() with ncurses6.

bpo-28449 [https://bugs.python.org/issue?@action=redirect&bpo=28449]: tarfile.open() with mode “r” or “r:” now tries to open a tar file with compression before trying to open it without compression. Otherwise it had 50% chance failed with ignore_zeros=True.

bpo-23262 [https://bugs.python.org/issue?@action=redirect&bpo=23262]: The webbrowser module now supports Firefox 36+ and derived browsers. Based on patch by Oleg Broytman.

bpo-27939 [https://bugs.python.org/issue?@action=redirect&bpo=27939]: Fixed bugs in tkinter.ttk.LabeledScale and tkinter.Scale caused by representing the scale as float value internally in Tk. tkinter.IntVar now works if float value is set to underlying Tk variable.

bpo-18844 [https://bugs.python.org/issue?@action=redirect&bpo=18844]: The various ways of specifying weights for random.choices() now produce the same result sequences.

bpo-28255 [https://bugs.python.org/issue?@action=redirect&bpo=28255]: calendar.TextCalendar().prmonth() no longer prints a space at the start of new line after printing a month’s calendar. Patch by Xiang Zhang.

bpo-20491 [https://bugs.python.org/issue?@action=redirect&bpo=20491]: The textwrap.TextWrapper class now honors non-breaking spaces. Based on patch by Kaarle Ritvanen.

bpo-28353 [https://bugs.python.org/issue?@action=redirect&bpo=28353]: os.fwalk() no longer fails on broken links.

bpo-28430 [https://bugs.python.org/issue?@action=redirect&bpo=28430]: Fix iterator of C implemented asyncio.Future doesn’t accept non-None value is passed to it.send(val).

bpo-27025 [https://bugs.python.org/issue?@action=redirect&bpo=27025]: Generated names for Tkinter widgets now start by the “!” prefix for readability.

bpo-25464 [https://bugs.python.org/issue?@action=redirect&bpo=25464]: Fixed HList.header_exists() in tkinter.tix module by addin a workaround to Tix library bug.

bpo-28488 [https://bugs.python.org/issue?@action=redirect&bpo=28488]: shutil.make_archive() no longer adds entry “./” to ZIP archive.

bpo-25953 [https://bugs.python.org/issue?@action=redirect&bpo=25953]: re.sub() now raises an error for invalid numerical group reference in replacement template even if the pattern is not found in the string. Error message for invalid group reference now includes the group index and the position of the reference. Based on patch by SilentGhost.

bpo-18219 [https://bugs.python.org/issue?@action=redirect&bpo=18219]: Optimize csv.DictWriter for large number of columns. Patch by Mariatta Wijaya.

bpo-28448 [https://bugs.python.org/issue?@action=redirect&bpo=28448]: Fix C implemented asyncio.Future didn’t work on Windows.

bpo-28480 [https://bugs.python.org/issue?@action=redirect&bpo=28480]: Fix error building socket module when multithreading is disabled.

bpo-24452 [https://bugs.python.org/issue?@action=redirect&bpo=24452]: Make webbrowser support Chrome on Mac OS X.

bpo-20766 [https://bugs.python.org/issue?@action=redirect&bpo=20766]: Fix references leaked by pdb in the handling of SIGINT handlers.

bpo-28492 [https://bugs.python.org/issue?@action=redirect&bpo=28492]: Fix how StopIteration exception is raised in _asyncio.Future.

bpo-28500 [https://bugs.python.org/issue?@action=redirect&bpo=28500]: Fix asyncio to handle async gens GC from another thread.

bpo-26923 [https://bugs.python.org/issue?@action=redirect&bpo=26923]: Fix asyncio.Gather to refuse being cancelled once all children are done. Patch by Johannes Ebke.

bpo-26796 [https://bugs.python.org/issue?@action=redirect&bpo=26796]: Don’t configure the number of workers for default threadpool executor. Initial patch by Hans Lawrenz.

bpo-28544 [https://bugs.python.org/issue?@action=redirect&bpo=28544]: Implement asyncio.Task in C.

Windows

bpo-28522 [https://bugs.python.org/issue?@action=redirect&bpo=28522]: Fixes mishandled buffer reallocation in getpathp.c

Build

bpo-28444 [https://bugs.python.org/issue?@action=redirect&bpo=28444]: Fix missing extensions modules when cross compiling.

bpo-28208 [https://bugs.python.org/issue?@action=redirect&bpo=28208]: Update Windows build and OS X installers to use SQLite 3.14.2.

bpo-28248 [https://bugs.python.org/issue?@action=redirect&bpo=28248]: Update Windows build and OS X installers to use OpenSSL 1.0.2j.

Tests

bpo-26944 [https://bugs.python.org/issue?@action=redirect&bpo=26944]: Fix test_posix for Android where ‘id -G’ is entirely wrong or missing the effective gid.

bpo-28409 [https://bugs.python.org/issue?@action=redirect&bpo=28409]: regrtest: fix the parser of command line arguments.

Python 3.6.0 beta 2

Release date: 2016-10-10

Core and Builtins

bpo-28183 [https://bugs.python.org/issue?@action=redirect&bpo=28183]: Optimize and cleanup dict iteration.

bpo-26081 [https://bugs.python.org/issue?@action=redirect&bpo=26081]: Added C implementation of asyncio.Future. Original patch by Yury Selivanov.

bpo-28379 [https://bugs.python.org/issue?@action=redirect&bpo=28379]: Added sanity checks and tests for PyUnicode_CopyCharacters(). Patch by Xiang Zhang.

bpo-28376 [https://bugs.python.org/issue?@action=redirect&bpo=28376]: The type of long range iterator is now registered as Iterator. Patch by Oren Milman.

bpo-28376 [https://bugs.python.org/issue?@action=redirect&bpo=28376]: Creating instances of range_iterator by calling range_iterator type now is deprecated. Patch by Oren Milman.

bpo-28376 [https://bugs.python.org/issue?@action=redirect&bpo=28376]: The constructor of range_iterator now checks that step is not 0. Patch by Oren Milman.

bpo-26906 [https://bugs.python.org/issue?@action=redirect&bpo=26906]: Resolving special methods of uninitialized type now causes implicit initialization of the type instead of a fail.

bpo-18287 [https://bugs.python.org/issue?@action=redirect&bpo=18287]: PyType_Ready() now checks that tp_name is not NULL. Original patch by Niklas Koep.

bpo-24098 [https://bugs.python.org/issue?@action=redirect&bpo=24098]: Fixed possible crash when AST is changed in process of compiling it.

bpo-28201 [https://bugs.python.org/issue?@action=redirect&bpo=28201]: Dict reduces possibility of 2nd conflict in hash table when hashes have same lower bits.

bpo-28350 [https://bugs.python.org/issue?@action=redirect&bpo=28350]: String constants with null character no longer interned.

bpo-26617 [https://bugs.python.org/issue?@action=redirect&bpo=26617]: Fix crash when GC runs during weakref callbacks.

bpo-27942 [https://bugs.python.org/issue?@action=redirect&bpo=27942]: String constants now interned recursively in tuples and frozensets.

bpo-21578 [https://bugs.python.org/issue?@action=redirect&bpo=21578]: Fixed misleading error message when ImportError called with invalid keyword args.

bpo-28203 [https://bugs.python.org/issue?@action=redirect&bpo=28203]: Fix incorrect type in complex(1.0, {2:3}) error message. Patch by Soumya Sharma.

bpo-28086 [https://bugs.python.org/issue?@action=redirect&bpo=28086]: Single var-positional argument of tuple subtype was passed unscathed to the C-defined function. Now it is converted to exact tuple.

bpo-28214 [https://bugs.python.org/issue?@action=redirect&bpo=28214]: Now __set_name__ is looked up on the class instead of the instance.

bpo-27955 [https://bugs.python.org/issue?@action=redirect&bpo=27955]: Fallback on reading /dev/urandom device when the getrandom() syscall fails with EPERM, for example when blocked by SECCOMP.

bpo-28192 [https://bugs.python.org/issue?@action=redirect&bpo=28192]: Don’t import readline in isolated mode.

Upgrade internal unicode databases to Unicode version 9.0.0.

bpo-28131 [https://bugs.python.org/issue?@action=redirect&bpo=28131]: Fix a regression in zipimport’s compile_source(). zipimport should use the same optimization level as the interpreter.

bpo-28126 [https://bugs.python.org/issue?@action=redirect&bpo=28126]: Replace Py_MEMCPY with memcpy(). Visual Studio can properly optimize memcpy().

bpo-28120 [https://bugs.python.org/issue?@action=redirect&bpo=28120]: Fix dict.pop() for splitted dictionary when trying to remove a “pending key” (Not yet inserted in split-table). Patch by Xiang Zhang.

bpo-26182 [https://bugs.python.org/issue?@action=redirect&bpo=26182]: Raise DeprecationWarning when async and await keywords are used as variable/attribute/class/function name.

Library

bpo-27998 [https://bugs.python.org/issue?@action=redirect&bpo=27998]: Fixed bytes path support in os.scandir() on Windows. Patch by Eryk Sun.

bpo-28317 [https://bugs.python.org/issue?@action=redirect&bpo=28317]: The disassembler now decodes FORMAT_VALUE argument.

bpo-26293 [https://bugs.python.org/issue?@action=redirect&bpo=26293]: Fixed writing ZIP files that starts not from the start of the file. Offsets in ZIP file now are relative to the start of the archive in conforming to the specification.

bpo-28380 [https://bugs.python.org/issue?@action=redirect&bpo=28380]: unittest.mock Mock autospec functions now properly support assert_called, assert_not_called, and assert_called_once.

bpo-27181 [https://bugs.python.org/issue?@action=redirect&bpo=27181]: remove statistics.geometric_mean and defer until 3.7.

bpo-28229 [https://bugs.python.org/issue?@action=redirect&bpo=28229]: lzma module now supports pathlib.

bpo-28321 [https://bugs.python.org/issue?@action=redirect&bpo=28321]: Fixed writing non-BMP characters with binary format in plistlib.

bpo-28225 [https://bugs.python.org/issue?@action=redirect&bpo=28225]: bz2 module now supports pathlib. Initial patch by Ethan Furman.

bpo-28227 [https://bugs.python.org/issue?@action=redirect&bpo=28227]: gzip now supports pathlib. Patch by Ethan Furman.

bpo-27358 [https://bugs.python.org/issue?@action=redirect&bpo=27358]: Optimized merging var-keyword arguments and improved error message when passing a non-mapping as a var-keyword argument.

bpo-28257 [https://bugs.python.org/issue?@action=redirect&bpo=28257]: Improved error message when passing a non-iterable as a var-positional argument. Added opcode BUILD_TUPLE_UNPACK_WITH_CALL.

bpo-28322 [https://bugs.python.org/issue?@action=redirect&bpo=28322]: Fixed possible crashes when unpickle itertools objects from incorrect pickle data. Based on patch by John Leitch.

bpo-28228 [https://bugs.python.org/issue?@action=redirect&bpo=28228]: imghdr now supports pathlib.

bpo-28226 [https://bugs.python.org/issue?@action=redirect&bpo=28226]: compileall now supports pathlib.

bpo-28314 [https://bugs.python.org/issue?@action=redirect&bpo=28314]: Fix function declaration (C flags) for the getiterator() method of xml.etree.ElementTree.Element.

bpo-28148 [https://bugs.python.org/issue?@action=redirect&bpo=28148]: Stop using localtime() and gmtime() in the time module.

Introduced platform independent _PyTime_localtime API that is similar to POSIX localtime_r, but available on all platforms. Patch by Ed Schouten.

bpo-28253 [https://bugs.python.org/issue?@action=redirect&bpo=28253]: Fixed calendar functions for extreme months: 0001-01 and 9999-12.

Methods itermonthdays() and itermonthdays2() are reimplemented so that they don’t call itermonthdates() which can cause datetime.date under/overflow.

bpo-28275 [https://bugs.python.org/issue?@action=redirect&bpo=28275]: Fixed possible use after free in the decompress() methods of the LZMADecompressor and BZ2Decompressor classes. Original patch by John Leitch.

bpo-27897 [https://bugs.python.org/issue?@action=redirect&bpo=27897]: Fixed possible crash in sqlite3.Connection.create_collation() if pass invalid string-like object as a name. Patch by Xiang Zhang.

bpo-18844 [https://bugs.python.org/issue?@action=redirect&bpo=18844]: random.choices() now has k as a keyword-only argument to improve the readability of common cases and come into line with the signature used in other languages.

bpo-18893 [https://bugs.python.org/issue?@action=redirect&bpo=18893]: Fix invalid exception handling in Lib/ctypes/macholib/dyld.py. Patch by Madison May.

bpo-27611 [https://bugs.python.org/issue?@action=redirect&bpo=27611]: Fixed support of default root window in the tkinter.tix module. Added the master parameter in the DisplayStyle constructor.

bpo-27348 [https://bugs.python.org/issue?@action=redirect&bpo=27348]: In the traceback module, restore the formatting of exception messages like “Exception: None”. This fixes a regression introduced in 3.5a2.

bpo-25651 [https://bugs.python.org/issue?@action=redirect&bpo=25651]: Allow falsy values to be used for msg parameter of subTest().

bpo-27778 [https://bugs.python.org/issue?@action=redirect&bpo=27778]: Fix a memory leak in os.getrandom() when the getrandom() is interrupted by a signal and a signal handler raises a Python exception.

bpo-28200 [https://bugs.python.org/issue?@action=redirect&bpo=28200]: Fix memory leak on Windows in the os module (fix path_converter() function).

bpo-25400 [https://bugs.python.org/issue?@action=redirect&bpo=25400]: RobotFileParser now correctly returns default values for crawl_delay and request_rate. Initial patch by Peter Wirtz.

bpo-27932 [https://bugs.python.org/issue?@action=redirect&bpo=27932]: Prevent memory leak in win32_ver().

Fix UnboundLocalError in socket._sendfile_use_sendfile.

bpo-28075 [https://bugs.python.org/issue?@action=redirect&bpo=28075]: Check for ERROR_ACCESS_DENIED in Windows implementation of os.stat(). Patch by Eryk Sun.

bpo-22493 [https://bugs.python.org/issue?@action=redirect&bpo=22493]: Warning message emitted by using inline flags in the middle of regular expression now contains a (truncated) regex pattern. Patch by Tim Graham.

bpo-25270 [https://bugs.python.org/issue?@action=redirect&bpo=25270]: Prevent codecs.escape_encode() from raising SystemError when an empty bytestring is passed.

bpo-28181 [https://bugs.python.org/issue?@action=redirect&bpo=28181]: Get antigravity over HTTPS. Patch by Kaartic Sivaraam.

bpo-25895 [https://bugs.python.org/issue?@action=redirect&bpo=25895]: Enable WebSocket URL schemes in urllib.parse.urljoin. Patch by Gergely Imreh and Markus Holtermann.

bpo-28114 [https://bugs.python.org/issue?@action=redirect&bpo=28114]: Fix a crash in parse_envlist() when env contains byte strings. Patch by Eryk Sun.

bpo-27599 [https://bugs.python.org/issue?@action=redirect&bpo=27599]: Fixed buffer overrun in binascii.b2a_qp() and binascii.a2b_qp().

bpo-27906 [https://bugs.python.org/issue?@action=redirect&bpo=27906]: Fix socket accept exhaustion during high TCP traffic. Patch by Kevin Conway.

bpo-28174 [https://bugs.python.org/issue?@action=redirect&bpo=28174]: Handle when SO_REUSEPORT isn’t properly supported. Patch by Seth Michael Larson.

bpo-26654 [https://bugs.python.org/issue?@action=redirect&bpo=26654]: Inspect functools.partial in asyncio.Handle.__repr__. Patch by iceboy.

bpo-26909 [https://bugs.python.org/issue?@action=redirect&bpo=26909]: Fix slow pipes IO in asyncio. Patch by INADA Naoki.

bpo-28176 [https://bugs.python.org/issue?@action=redirect&bpo=28176]: Fix callbacks race in asyncio.SelectorLoop.sock_connect.

bpo-27759 [https://bugs.python.org/issue?@action=redirect&bpo=27759]: Fix selectors incorrectly retain invalid file descriptors. Patch by Mark Williams.

bpo-28368 [https://bugs.python.org/issue?@action=redirect&bpo=28368]: Refuse monitoring processes if the child watcher has no loop attached. Patch by Vincent Michel.

bpo-28369 [https://bugs.python.org/issue?@action=redirect&bpo=28369]: Raise RuntimeError when transport’s FD is used with add_reader, add_writer, etc.

bpo-28370 [https://bugs.python.org/issue?@action=redirect&bpo=28370]: Speedup asyncio.StreamReader.readexactly. Patch by Коренберг Марк.

bpo-28371 [https://bugs.python.org/issue?@action=redirect&bpo=28371]: Deprecate passing asyncio.Handles to run_in_executor.

bpo-28372 [https://bugs.python.org/issue?@action=redirect&bpo=28372]: Fix asyncio to support formatting of non-python coroutines.

bpo-28399 [https://bugs.python.org/issue?@action=redirect&bpo=28399]: Remove UNIX socket from FS before binding. Patch by Коренберг Марк.

bpo-27972 [https://bugs.python.org/issue?@action=redirect&bpo=27972]: Prohibit Tasks to await on themselves.

Windows

bpo-28402 [https://bugs.python.org/issue?@action=redirect&bpo=28402]: Adds signed catalog files for stdlib on Windows.

bpo-28333 [https://bugs.python.org/issue?@action=redirect&bpo=28333]: Enables Unicode for ps1/ps2 and input() prompts. (Patch by Eryk Sun)

bpo-28251 [https://bugs.python.org/issue?@action=redirect&bpo=28251]: Improvements to help manuals on Windows.

bpo-28110 [https://bugs.python.org/issue?@action=redirect&bpo=28110]: launcher.msi has different product codes between 32-bit and 64-bit

bpo-28161 [https://bugs.python.org/issue?@action=redirect&bpo=28161]: Opening CON for write access fails

bpo-28162 [https://bugs.python.org/issue?@action=redirect&bpo=28162]: WindowsConsoleIO readall() fails if first line starts with Ctrl+Z

bpo-28163 [https://bugs.python.org/issue?@action=redirect&bpo=28163]: WindowsConsoleIO fileno() passes wrong flags to _open_osfhandle

bpo-28164 [https://bugs.python.org/issue?@action=redirect&bpo=28164]: _PyIO_get_console_type fails for various paths

bpo-28137 [https://bugs.python.org/issue?@action=redirect&bpo=28137]: Renames Windows path file to ._pth

bpo-28138 [https://bugs.python.org/issue?@action=redirect&bpo=28138]: Windows ._pth file should allow import site

C API

bpo-28426 [https://bugs.python.org/issue?@action=redirect&bpo=28426]: Deprecated undocumented functions PyUnicode_AsEncodedObject(), PyUnicode_AsDecodedObject(), PyUnicode_AsDecodedUnicode() and PyUnicode_AsEncodedUnicode().

Build

bpo-28258 [https://bugs.python.org/issue?@action=redirect&bpo=28258]: Fixed build with Estonian locale (python-config and distclean targets in Makefile). Patch by Arfrever Frehtes Taifersar Arahesis.

bpo-26661 [https://bugs.python.org/issue?@action=redirect&bpo=26661]: setup.py now detects system libffi with multiarch wrapper.

bpo-15819 [https://bugs.python.org/issue?@action=redirect&bpo=15819]: Remove redundant include search directory option for building outside the source tree.

Tests

bpo-28217 [https://bugs.python.org/issue?@action=redirect&bpo=28217]: Adds _testconsole module to test console input.

Python 3.6.0 beta 1

Release date: 2016-09-12

Core and Builtins

bpo-23722 [https://bugs.python.org/issue?@action=redirect&bpo=23722]: The __class__ cell used by zero-argument super() is now initialized from type.__new__ rather than __build_class__, so class methods relying on that will now work correctly when called from metaclass methods during class creation. Patch by Martin Teichmann.

bpo-25221 [https://bugs.python.org/issue?@action=redirect&bpo=25221]: Fix corrupted result from PyLong_FromLong(0) when Python is compiled with NSMALLPOSINTS = 0.

bpo-27080 [https://bugs.python.org/issue?@action=redirect&bpo=27080]: Implement formatting support for PEP 515. Initial patch by Chris Angelico.

bpo-27199 [https://bugs.python.org/issue?@action=redirect&bpo=27199]: In tarfile, expose copyfileobj bufsize to improve throughput. Patch by Jason Fried.

bpo-27948 [https://bugs.python.org/issue?@action=redirect&bpo=27948]: In f-strings, only allow backslashes inside the braces (where the expressions are). This is a breaking change from the 3.6 alpha releases, where backslashes are allowed anywhere in an f-string. Also, require that expressions inside f-strings be enclosed within literal braces, and not escapes like f'\x7b"hi"\x7d'.

bpo-28046 [https://bugs.python.org/issue?@action=redirect&bpo=28046]: Remove platform-specific directories from sys.path.

bpo-28071 [https://bugs.python.org/issue?@action=redirect&bpo=28071]: Add early-out for differencing from an empty set.

bpo-25758 [https://bugs.python.org/issue?@action=redirect&bpo=25758]: Prevents zipimport from unnecessarily encoding a filename (patch by Eryk Sun)

bpo-25856 [https://bugs.python.org/issue?@action=redirect&bpo=25856]: The __module__ attribute of extension classes and functions now is interned. This leads to more compact pickle data with protocol 4.

bpo-27213 [https://bugs.python.org/issue?@action=redirect&bpo=27213]: Rework CALL_FUNCTION* opcodes to produce shorter and more efficient bytecode. Patch by Demur Rumed, design by Serhiy Storchaka, reviewed by Serhiy Storchaka and Victor Stinner.

bpo-26331 [https://bugs.python.org/issue?@action=redirect&bpo=26331]: Implement tokenizing support for PEP 515. Patch by Georg Brandl.

bpo-27999 [https://bugs.python.org/issue?@action=redirect&bpo=27999]: Make “global after use” a SyntaxError, and ditto for nonlocal. Patch by Ivan Levkivskyi.

bpo-28003 [https://bugs.python.org/issue?@action=redirect&bpo=28003]: Implement PEP 525 – Asynchronous Generators.

bpo-27985 [https://bugs.python.org/issue?@action=redirect&bpo=27985]: Implement PEP 526 – Syntax for Variable Annotations. Patch by Ivan Levkivskyi.

bpo-26058 [https://bugs.python.org/issue?@action=redirect&bpo=26058]: Add a new private version to the builtin dict type, incremented at each dictionary creation and at each dictionary change. Implementation of the PEP 509.

bpo-27364 [https://bugs.python.org/issue?@action=redirect&bpo=27364]: A backslash-character pair that is not a valid escape sequence now generates a DeprecationWarning. Patch by Emanuel Barry.

bpo-27350 [https://bugs.python.org/issue?@action=redirect&bpo=27350]: dict implementation is changed like PyPy. It is more compact and preserves insertion order. (Concept developed by Raymond Hettinger and patch by Inada Naoki.)

bpo-27911 [https://bugs.python.org/issue?@action=redirect&bpo=27911]: Remove unnecessary error checks in exec_builtin_or_dynamic().

bpo-27078 [https://bugs.python.org/issue?@action=redirect&bpo=27078]: Added BUILD_STRING opcode. Optimized f-strings evaluation.

bpo-17884 [https://bugs.python.org/issue?@action=redirect&bpo=17884]: Python now requires systems with inttypes.h and stdint.h

bpo-27961 [https://bugs.python.org/issue?@action=redirect&bpo=27961]: Require platforms to support long long. Python hasn’t compiled without long long for years, so this is basically a formality.

bpo-27355 [https://bugs.python.org/issue?@action=redirect&bpo=27355]: Removed support for Windows CE. It was never finished, and Windows CE is no longer a relevant platform for Python.

Implement PEP 523.

bpo-27870 [https://bugs.python.org/issue?@action=redirect&bpo=27870]: A left shift of zero by a large integer no longer attempts to allocate large amounts of memory.

bpo-25402 [https://bugs.python.org/issue?@action=redirect&bpo=25402]: In int-to-decimal-string conversion, improve the estimate of the intermediate memory required, and remove an unnecessarily strict overflow check. Patch by Serhiy Storchaka.

bpo-27214 [https://bugs.python.org/issue?@action=redirect&bpo=27214]: In long_invert, be more careful about modifying object returned by long_add, and remove an unnecessary check for small longs. Thanks Oren Milman for analysis and patch.

bpo-27506 [https://bugs.python.org/issue?@action=redirect&bpo=27506]: Support passing the bytes/bytearray.translate() “delete” argument by keyword.

bpo-27812 [https://bugs.python.org/issue?@action=redirect&bpo=27812]: Properly clear out a generator’s frame’s backreference to the generator to prevent crashes in frame.clear().

bpo-27811 [https://bugs.python.org/issue?@action=redirect&bpo=27811]: Fix a crash when a coroutine that has not been awaited is finalized with warnings-as-errors enabled.

bpo-27587 [https://bugs.python.org/issue?@action=redirect&bpo=27587]: Fix another issue found by PVS-Studio: Null pointer check after use of ‘def’ in _PyState_AddModule(). Initial patch by Christian Heimes.

bpo-27792 [https://bugs.python.org/issue?@action=redirect&bpo=27792]: The modulo operation applied to bool and other int subclasses now always returns an int. Previously the return type depended on the input values. Patch by Xiang Zhang.

bpo-26984 [https://bugs.python.org/issue?@action=redirect&bpo=26984]: int() now always returns an instance of exact int.

bpo-25604 [https://bugs.python.org/issue?@action=redirect&bpo=25604]: Fix a minor bug in integer true division; this bug could potentially have caused off-by-one-ulp results on platforms with unreliable ldexp implementations.

bpo-24254 [https://bugs.python.org/issue?@action=redirect&bpo=24254]: Make class definition namespace ordered by default.

bpo-27662 [https://bugs.python.org/issue?@action=redirect&bpo=27662]: Fix an overflow check in List_New: the original code was checking against Py_SIZE_MAX instead of the correct upper bound of Py_SSIZE_T_MAX. Patch by Xiang Zhang.

bpo-27782 [https://bugs.python.org/issue?@action=redirect&bpo=27782]: Multi-phase extension module import now correctly allows the m_methods field to be used to add module level functions to instances of non-module types returned from Py_create_mod. Patch by Xiang Zhang.

bpo-27936 [https://bugs.python.org/issue?@action=redirect&bpo=27936]: The round() function accepted a second None argument for some types but not for others. Fixed the inconsistency by accepting None for all numeric types.

bpo-27487 [https://bugs.python.org/issue?@action=redirect&bpo=27487]: Warn if a submodule argument to “python -m” or runpy.run_module() is found in sys.modules after parent packages are imported, but before the submodule is executed.

bpo-27157 [https://bugs.python.org/issue?@action=redirect&bpo=27157]: Make only type() itself accept the one-argument form. Patch by Eryk Sun and Emanuel Barry.

bpo-27558 [https://bugs.python.org/issue?@action=redirect&bpo=27558]: Fix a SystemError in the implementation of “raise” statement. In a brand new thread, raise a RuntimeError since there is no active exception to reraise. Patch written by Xiang Zhang.

bpo-28008 [https://bugs.python.org/issue?@action=redirect&bpo=28008]: Implement PEP 530 – asynchronous comprehensions.

bpo-27942 [https://bugs.python.org/issue?@action=redirect&bpo=27942]: Fix memory leak in codeobject.c

Library

bpo-28732 [https://bugs.python.org/issue?@action=redirect&bpo=28732]: Fix crash in os.spawnv() with no elements in args

bpo-28485 [https://bugs.python.org/issue?@action=redirect&bpo=28485]: Always raise ValueError for negative compileall.compile_dir(workers=…) parameter, even when multithreading is unavailable.

bpo-28037 [https://bugs.python.org/issue?@action=redirect&bpo=28037]: Use sqlite3_get_autocommit() instead of setting Connection->inTransaction manually.

bpo-25283 [https://bugs.python.org/issue?@action=redirect&bpo=25283]: Attributes tm_gmtoff and tm_zone are now available on all platforms in the return values of time.localtime() and time.gmtime().

bpo-24454 [https://bugs.python.org/issue?@action=redirect&bpo=24454]: Regular expression match object groups are now accessible using __getitem__. “mo[x]” is equivalent to “mo.group(x)”.

bpo-10740 [https://bugs.python.org/issue?@action=redirect&bpo=10740]: sqlite3 no longer implicitly commit an open transaction before DDL statements.

bpo-17941 [https://bugs.python.org/issue?@action=redirect&bpo=17941]: Add a module parameter to collections.namedtuple().

bpo-22493 [https://bugs.python.org/issue?@action=redirect&bpo=22493]: Inline flags now should be used only at the start of the regular expression. Deprecation warning is emitted if uses them in the middle of the regular expression.

bpo-26885 [https://bugs.python.org/issue?@action=redirect&bpo=26885]: xmlrpc now supports unmarshalling additional data types used by Apache XML-RPC implementation for numerics and None.

bpo-28070 [https://bugs.python.org/issue?@action=redirect&bpo=28070]: Fixed parsing inline verbose flag in regular expressions.

bpo-19500 [https://bugs.python.org/issue?@action=redirect&bpo=19500]: Add client-side SSL session resumption to the ssl module.

bpo-28022 [https://bugs.python.org/issue?@action=redirect&bpo=28022]: Deprecate ssl-related arguments in favor of SSLContext. The deprecation include manual creation of SSLSocket and certfile/keyfile (or similar) in ftplib, httplib, imaplib, smtplib, poplib and urllib.

bpo-28043 [https://bugs.python.org/issue?@action=redirect&bpo=28043]: SSLContext has improved default settings: OP_NO_SSLv2, OP_NO_SSLv3, OP_NO_COMPRESSION, OP_CIPHER_SERVER_PREFERENCE, OP_SINGLE_DH_USE, OP_SINGLE_ECDH_USE and HIGH ciphers without MD5.

bpo-24693 [https://bugs.python.org/issue?@action=redirect&bpo=24693]: Changed some RuntimeError’s in the zipfile module to more appropriate types. Improved some error messages and debugging output.

bpo-17909 [https://bugs.python.org/issue?@action=redirect&bpo=17909]: json.load and json.loads now support binary input encoded as UTF-8, UTF-16 or UTF-32. Patch by Serhiy Storchaka.

bpo-27137 [https://bugs.python.org/issue?@action=redirect&bpo=27137]: the pure Python fallback implementation of functools.partial now matches the behaviour of its accelerated C counterpart for subclassing, pickling and text representation purposes. Patch by Emanuel Barry and Serhiy Storchaka.

Fix possible integer overflows and crashes in the mmap module with unusual usage patterns.

bpo-1703178 [https://bugs.python.org/issue?@action=redirect&bpo=1703178]: Fix the ability to pass the –link-objects option to the distutils build_ext command.

bpo-28019 [https://bugs.python.org/issue?@action=redirect&bpo=28019]: itertools.count() no longer rounds non-integer step in range between 1.0 and 2.0 to 1.

bpo-18401 [https://bugs.python.org/issue?@action=redirect&bpo=18401]: Pdb now supports the ‘readrc’ keyword argument to control whether .pdbrc files should be read. Patch by Martin Matusiak and Sam Kimbrel.

bpo-25969 [https://bugs.python.org/issue?@action=redirect&bpo=25969]: Update the lib2to3 grammar to handle the unpacking generalizations added in 3.5.

bpo-14977 [https://bugs.python.org/issue?@action=redirect&bpo=14977]: mailcap now respects the order of the lines in the mailcap files (“first match”), as required by RFC 1542. Patch by Michael Lazar.

bpo-28082 [https://bugs.python.org/issue?@action=redirect&bpo=28082]: Convert re flag constants to IntFlag.

bpo-28025 [https://bugs.python.org/issue?@action=redirect&bpo=28025]: Convert all ssl module constants to IntEnum and IntFlags. SSLContext properties now return flags and enums.

bpo-23591 [https://bugs.python.org/issue?@action=redirect&bpo=23591]: Add Flag, IntFlag, and auto() to enum module.

bpo-433028 [https://bugs.python.org/issue?@action=redirect&bpo=433028]: Added support of modifier spans in regular expressions.

bpo-24594 [https://bugs.python.org/issue?@action=redirect&bpo=24594]: Validates persist parameter when opening MSI database

bpo-17582 [https://bugs.python.org/issue?@action=redirect&bpo=17582]: xml.etree.ElementTree nows preserves whitespaces in attributes (Patch by Duane Griffin. Reviewed and approved by Stefan Behnel.)

bpo-28047 [https://bugs.python.org/issue?@action=redirect&bpo=28047]: Fixed calculation of line length used for the base64 CTE in the new email policies.

bpo-27576 [https://bugs.python.org/issue?@action=redirect&bpo=27576]: Fix call order in OrderedDict.__init__().

email.generator.DecodedGenerator now supports the policy keyword.

bpo-28027 [https://bugs.python.org/issue?@action=redirect&bpo=28027]: Remove undocumented modules from Lib/plat-*: IN, CDROM, DLFCN, TYPES, CDIO, and STROPTS.

bpo-27445 [https://bugs.python.org/issue?@action=redirect&bpo=27445]: Don’t pass str(_charset) to MIMEText.set_payload(). Patch by Claude Paroz.

bpo-24277 [https://bugs.python.org/issue?@action=redirect&bpo=24277]: The new email API is no longer provisional, and the docs have been reorganized and rewritten to emphasize the new API.

bpo-22450 [https://bugs.python.org/issue?@action=redirect&bpo=22450]: urllib now includes an Accept: */* header among the default headers. This makes the results of REST API requests more consistent and predictable especially when proxy servers are involved.

lib2to3.pgen3.driver.load_grammar() now creates a stable cache file between runs given the same Grammar.txt input regardless of the hash randomization setting.

bpo-28005 [https://bugs.python.org/issue?@action=redirect&bpo=28005]: Allow ImportErrors in encoding implementation to propagate.

bpo-26667 [https://bugs.python.org/issue?@action=redirect&bpo=26667]: Support path-like objects in importlib.util.

bpo-27570 [https://bugs.python.org/issue?@action=redirect&bpo=27570]: Avoid zero-length memcpy() etc calls with null source pointers in the “ctypes” and “array” modules.

bpo-22233 [https://bugs.python.org/issue?@action=redirect&bpo=22233]: Break email header lines only on the RFC specified CR and LF characters, not on arbitrary unicode line breaks. This also fixes a bug in HTTP header parsing.

bpo-27331 [https://bugs.python.org/issue?@action=redirect&bpo=27331]: The email.mime classes now all accept an optional policy keyword.

bpo-27988 [https://bugs.python.org/issue?@action=redirect&bpo=27988]: Fix email iter_attachments incorrect mutation of payload list.

bpo-16113 [https://bugs.python.org/issue?@action=redirect&bpo=16113]: Add SHA-3 and SHAKE support to hashlib module.

Eliminate a tautological-pointer-compare warning in _scproxy.c.

bpo-27776 [https://bugs.python.org/issue?@action=redirect&bpo=27776]: The os.urandom() function does now block on Linux 3.17 and newer until the system urandom entropy pool is initialized to increase the security. This change is part of the PEP 524 [https://www.python.org/dev/peps/pep-0524].

bpo-27778 [https://bugs.python.org/issue?@action=redirect&bpo=27778]: Expose the Linux getrandom() syscall as a new os.getrandom() function. This change is part of the PEP 524 [https://www.python.org/dev/peps/pep-0524].

bpo-27691 [https://bugs.python.org/issue?@action=redirect&bpo=27691]: Fix ssl module’s parsing of GEN_RID subject alternative name fields in X.509 certs.

bpo-18844 [https://bugs.python.org/issue?@action=redirect&bpo=18844]: Add random.choices().

bpo-25761 [https://bugs.python.org/issue?@action=redirect&bpo=25761]: Improved error reporting about truncated pickle data in C implementation of unpickler. UnpicklingError is now raised instead of AttributeError and ValueError in some cases.

bpo-26798 [https://bugs.python.org/issue?@action=redirect&bpo=26798]: Add BLAKE2 (blake2b and blake2s) to hashlib.

bpo-26032 [https://bugs.python.org/issue?@action=redirect&bpo=26032]: Optimized globbing in pathlib by using os.scandir(); it is now about 1.5–4 times faster.

bpo-25596 [https://bugs.python.org/issue?@action=redirect&bpo=25596]: Optimized glob() and iglob() functions in the glob module; they are now about 3–6 times faster.

bpo-27928 [https://bugs.python.org/issue?@action=redirect&bpo=27928]: Add scrypt (password-based key derivation function) to hashlib module (requires OpenSSL 1.1.0).

bpo-27850 [https://bugs.python.org/issue?@action=redirect&bpo=27850]: Remove 3DES from ssl module’s default cipher list to counter measure sweet32 attack (CVE-2016-2183).

bpo-27766 [https://bugs.python.org/issue?@action=redirect&bpo=27766]: Add ChaCha20 Poly1305 to ssl module’s default cipher list. (Required OpenSSL 1.1.0 or LibreSSL).

bpo-25387 [https://bugs.python.org/issue?@action=redirect&bpo=25387]: Check return value of winsound.MessageBeep.

bpo-27866 [https://bugs.python.org/issue?@action=redirect&bpo=27866]: Add SSLContext.get_ciphers() method to get a list of all enabled ciphers.

bpo-27744 [https://bugs.python.org/issue?@action=redirect&bpo=27744]: Add AF_ALG (Linux Kernel crypto) to socket module.

bpo-26470 [https://bugs.python.org/issue?@action=redirect&bpo=26470]: Port ssl and hashlib module to OpenSSL 1.1.0.

bpo-11620 [https://bugs.python.org/issue?@action=redirect&bpo=11620]: Fix support for SND_MEMORY in winsound.PlaySound. Based on a patch by Tim Lesher.

bpo-11734 [https://bugs.python.org/issue?@action=redirect&bpo=11734]: Add support for IEEE 754 half-precision floats to the struct module. Based on a patch by Eli Stevens.

bpo-27919 [https://bugs.python.org/issue?@action=redirect&bpo=27919]: Deprecated extra_path distribution option in distutils packaging.

bpo-23229 [https://bugs.python.org/issue?@action=redirect&bpo=23229]: Add new cmath constants: cmath.inf and cmath.nan to match math.inf and math.nan, and also cmath.infj and cmath.nanj to match the format used by complex repr.

bpo-27842 [https://bugs.python.org/issue?@action=redirect&bpo=27842]: The csv.DictReader now returns rows of type OrderedDict. (Contributed by Steve Holden.)

Remove support for passing a file descriptor to os.access. It never worked but previously didn’t raise.

bpo-12885 [https://bugs.python.org/issue?@action=redirect&bpo=12885]: Fix error when distutils encounters symlink.

bpo-27881 [https://bugs.python.org/issue?@action=redirect&bpo=27881]: Fixed possible bugs when setting sqlite3.Connection.isolation_level. Based on patch by Xiang Zhang.

bpo-27861 [https://bugs.python.org/issue?@action=redirect&bpo=27861]: Fixed a crash in sqlite3.Connection.cursor() when a factory creates not a cursor. Patch by Xiang Zhang.

bpo-19884 [https://bugs.python.org/issue?@action=redirect&bpo=19884]: Avoid spurious output on OS X with Gnu Readline.

bpo-27706 [https://bugs.python.org/issue?@action=redirect&bpo=27706]: Restore deterministic behavior of random.Random().seed() for string seeds using seeding version 1. Allows sequences of calls to random() to exactly match those obtained in Python 2. Patch by Nofar Schnider.

bpo-10513 [https://bugs.python.org/issue?@action=redirect&bpo=10513]: Fix a regression in Connection.commit(). Statements should not be reset after a commit.

bpo-12319 [https://bugs.python.org/issue?@action=redirect&bpo=12319]: Chunked transfer encoding support added to http.client.HTTPConnection requests. The urllib.request.AbstractHTTPHandler class does not enforce a Content-Length header any more. If a HTTP request has a file or iterable body, but no Content-Length header, the library now falls back to use chunked transfer-encoding.

A new version of typing.py from https://github.com/python/typing: - Collection (only for 3.6) (bpo-27598 [https://bugs.python.org/issue?@action=redirect&bpo=27598]) - Add FrozenSet to __all__ (upstream #261) - fix crash in _get_type_vars() (upstream #259) - Remove the dict constraint in ForwardRef._eval_type (upstream #252)

bpo-27832 [https://bugs.python.org/issue?@action=redirect&bpo=27832]: Make _normalize parameter to Fraction constuctor keyword-only, so that Fraction(2, 3, 4) now raises TypeError.

bpo-27539 [https://bugs.python.org/issue?@action=redirect&bpo=27539]: Fix unnormalised Fraction.__pow__ result in the case of negative exponent and negative base.

bpo-21718 [https://bugs.python.org/issue?@action=redirect&bpo=21718]: cursor.description is now available for queries using CTEs.

bpo-27819 [https://bugs.python.org/issue?@action=redirect&bpo=27819]: In distutils sdists, simply produce the “gztar” (gzipped tar format) distributions on all platforms unless “formats” is supplied.

bpo-2466 [https://bugs.python.org/issue?@action=redirect&bpo=2466]: posixpath.ismount now correctly recognizes mount points which the user does not have permission to access.

bpo-9998 [https://bugs.python.org/issue?@action=redirect&bpo=9998]: On Linux, ctypes.util.find_library now looks in LD_LIBRARY_PATH for shared libraries.

bpo-27573 [https://bugs.python.org/issue?@action=redirect&bpo=27573]: exit message for code.interact is now configurable.

bpo-27930 [https://bugs.python.org/issue?@action=redirect&bpo=27930]: Improved behaviour of logging.handlers.QueueListener. Thanks to Paulo Andrade and Petr Viktorin for the analysis and patch.

bpo-6766 [https://bugs.python.org/issue?@action=redirect&bpo=6766]: Distributed reference counting added to multiprocessing to support nesting of shared values / proxy objects.

bpo-21201 [https://bugs.python.org/issue?@action=redirect&bpo=21201]: Improves readability of multiprocessing error message. Thanks to Wojciech Walczak for patch.

asyncio: Add set_protocol / get_protocol to Transports.

bpo-27456 [https://bugs.python.org/issue?@action=redirect&bpo=27456]: asyncio: Set TCP_NODELAY by default.

IDLE

bpo-15308 [https://bugs.python.org/issue?@action=redirect&bpo=15308]: Add ‘interrupt execution’ (^C) to Shell menu. Patch by Roger Serwy, updated by Bayard Randel.

bpo-27922 [https://bugs.python.org/issue?@action=redirect&bpo=27922]: Stop IDLE tests from ‘flashing’ gui widgets on the screen.

bpo-27891 [https://bugs.python.org/issue?@action=redirect&bpo=27891]: Consistently group and sort imports within idlelib modules.

bpo-17642 [https://bugs.python.org/issue?@action=redirect&bpo=17642]: add larger font sizes for classroom projection.

Add version to title of IDLE help window.

bpo-25564 [https://bugs.python.org/issue?@action=redirect&bpo=25564]: In section on IDLE – console differences, mention that using exec means that __builtins__ is defined for each statement.

bpo-27821 [https://bugs.python.org/issue?@action=redirect&bpo=27821]: Fix 3.6.0a3 regression that prevented custom key sets from being selected when no custom theme was defined.

C API

bpo-26900 [https://bugs.python.org/issue?@action=redirect&bpo=26900]: Excluded underscored names and other private API from limited API.

bpo-26027 [https://bugs.python.org/issue?@action=redirect&bpo=26027]: Add support for path-like objects in PyUnicode_FSConverter() & PyUnicode_FSDecoder().

Tests

bpo-27427 [https://bugs.python.org/issue?@action=redirect&bpo=27427]: Additional tests for the math module. Patch by Francisco Couzo.

bpo-27953 [https://bugs.python.org/issue?@action=redirect&bpo=27953]: Skip math and cmath tests that fail on OS X 10.4 due to a poor libm implementation of tan.

bpo-26040 [https://bugs.python.org/issue?@action=redirect&bpo=26040]: Improve test_math and test_cmath coverage and rigour. Patch by Jeff Allen.

bpo-27787 [https://bugs.python.org/issue?@action=redirect&bpo=27787]: Call gc.collect() before checking each test for “dangling threads”, since the dangling threads are weak references.

Build

bpo-27566 [https://bugs.python.org/issue?@action=redirect&bpo=27566]: Fix clean target in freeze makefile (patch by Lisa Roach)

bpo-27705 [https://bugs.python.org/issue?@action=redirect&bpo=27705]: Update message in validate_ucrtbase.py

bpo-27976 [https://bugs.python.org/issue?@action=redirect&bpo=27976]: Deprecate building _ctypes with the bundled copy of libffi on non-OSX UNIX platforms.

bpo-27983 [https://bugs.python.org/issue?@action=redirect&bpo=27983]: Cause lack of llvm-profdata tool when using clang as required for PGO linking to be a configure time error rather than make time when --with-optimizations is enabled. Also improve our ability to find the llvm-profdata tool on MacOS and some Linuxes.

bpo-21590 [https://bugs.python.org/issue?@action=redirect&bpo=21590]: Support for DTrace and SystemTap probes.

bpo-26307 [https://bugs.python.org/issue?@action=redirect&bpo=26307]: The profile-opt build now applies PGO to the built-in modules.

bpo-26359 [https://bugs.python.org/issue?@action=redirect&bpo=26359]: Add the –with-optimizations flag to turn on LTO and PGO build support when available.

bpo-27917 [https://bugs.python.org/issue?@action=redirect&bpo=27917]: Set platform triplets for Android builds.

bpo-25825 [https://bugs.python.org/issue?@action=redirect&bpo=25825]: Update references to the $(LIBPL) installation path on AIX. This path was changed in 3.2a4.

Update OS X installer to use SQLite 3.14.1 and XZ 5.2.2.

bpo-21122 [https://bugs.python.org/issue?@action=redirect&bpo=21122]: Fix LTO builds on OS X.

bpo-17128 [https://bugs.python.org/issue?@action=redirect&bpo=17128]: Build OS X installer with a private copy of OpenSSL. Also provide a sample Install Certificates command script to install a set of root certificates from the third-party certifi module.

Tools/Demos

bpo-27952 [https://bugs.python.org/issue?@action=redirect&bpo=27952]: Get Tools/scripts/fixcid.py working with Python 3 and the current “re” module, avoid invalid Python backslash escapes, and fix a bug parsing escaped C quote signs.

Windows

bpo-28065 [https://bugs.python.org/issue?@action=redirect&bpo=28065]: Update xz dependency to 5.2.2 and build it from source.

bpo-25144 [https://bugs.python.org/issue?@action=redirect&bpo=25144]: Ensures TargetDir is set before continuing with custom install.

bpo-1602 [https://bugs.python.org/issue?@action=redirect&bpo=1602]: Windows console doesn’t input or print Unicode (PEP 528)

bpo-27781 [https://bugs.python.org/issue?@action=redirect&bpo=27781]: Change file system encoding on Windows to UTF-8 (PEP 529)

bpo-27731 [https://bugs.python.org/issue?@action=redirect&bpo=27731]: Opt-out of MAX_PATH on Windows 10

bpo-6135 [https://bugs.python.org/issue?@action=redirect&bpo=6135]: Adds encoding and errors parameters to subprocess.

bpo-27959 [https://bugs.python.org/issue?@action=redirect&bpo=27959]: Adds oem encoding, alias ansi to mbcs, move aliasmbcs to codec lookup.

bpo-27982 [https://bugs.python.org/issue?@action=redirect&bpo=27982]: The functions of the winsound module now accept keyword arguments.

bpo-20366 [https://bugs.python.org/issue?@action=redirect&bpo=20366]: Build full text search support into SQLite on Windows.

bpo-27756 [https://bugs.python.org/issue?@action=redirect&bpo=27756]: Adds new icons for Python files and processes on Windows. Designs by Cherry Wang.

bpo-27883 [https://bugs.python.org/issue?@action=redirect&bpo=27883]: Update sqlite to 3.14.1.0 on Windows.

Python 3.6.0 alpha 4

Release date: 2016-08-15

Core and Builtins

bpo-27704 [https://bugs.python.org/issue?@action=redirect&bpo=27704]: Optimized creating bytes and bytearray from byte-like objects and iterables. Speed up to 3 times for short objects. Original patch by Naoki Inada.

bpo-26823 [https://bugs.python.org/issue?@action=redirect&bpo=26823]: Large sections of repeated lines in tracebacks are now abbreviated as “[Previous line repeated {count} more times]” by the builtin traceback rendering. Patch by Emanuel Barry.

bpo-27574 [https://bugs.python.org/issue?@action=redirect&bpo=27574]: Decreased an overhead of parsing keyword arguments in functions implemented with using Argument Clinic.

bpo-22557 [https://bugs.python.org/issue?@action=redirect&bpo=22557]: Now importing already imported modules is up to 2.5 times faster.

bpo-17596 [https://bugs.python.org/issue?@action=redirect&bpo=17596]: Include <wincrypt.h> to help with Min GW building.

bpo-17599 [https://bugs.python.org/issue?@action=redirect&bpo=17599]: On Windows, rename the privately defined REPARSE_DATA_BUFFER structure to avoid conflicting with the definition from Min GW.

bpo-27507 [https://bugs.python.org/issue?@action=redirect&bpo=27507]: Add integer overflow check in bytearray.extend(). Patch by Xiang Zhang.

bpo-27581 [https://bugs.python.org/issue?@action=redirect&bpo=27581]: Don’t rely on wrapping for overflow check in PySequence_Tuple(). Patch by Xiang Zhang.

bpo-1621 [https://bugs.python.org/issue?@action=redirect&bpo=1621]: Avoid signed integer overflow in list and tuple operations. Patch by Xiang Zhang.

bpo-27419 [https://bugs.python.org/issue?@action=redirect&bpo=27419]: Standard __import__() no longer look up “__import__” in globals or builtins for importing submodules or “from import”. Fixed a crash if raise a warning about unabling to resolve package from __spec__ or __package__.

bpo-27083 [https://bugs.python.org/issue?@action=redirect&bpo=27083]: Respect the PYTHONCASEOK environment variable under Windows.

bpo-27514 [https://bugs.python.org/issue?@action=redirect&bpo=27514]: Make having too many statically nested blocks a SyntaxError instead of SystemError.

bpo-27366 [https://bugs.python.org/issue?@action=redirect&bpo=27366]: Implemented PEP 487 (Simpler customization of class creation). Upon subclassing, the __init_subclass__ classmethod is called on the base class. Descriptors are initialized with __set_name__ after class creation.

Library

bpo-26027 [https://bugs.python.org/issue?@action=redirect&bpo=26027]: Add PEP 519/__fspath__() support to the os and os.path modules. Includes code from Jelle Zijlstra. (See also: bpo-27524 [https://bugs.python.org/issue?@action=redirect&bpo=27524])

bpo-27598 [https://bugs.python.org/issue?@action=redirect&bpo=27598]: Add Collections to collections.abc. Patch by Ivan Levkivskyi, docs by Neil Girdhar.

bpo-25958 [https://bugs.python.org/issue?@action=redirect&bpo=25958]: Support “anti-registration” of special methods from various ABCs, like __hash__, __iter__ or __len__. All these (and several more) can be set to None in an implementation class and the behavior will be as if the method is not defined at all. (Previously, this mechanism existed only for __hash__, to make mutable classes unhashable.) Code contributed by Andrew Barnert and Ivan Levkivskyi.

bpo-16764 [https://bugs.python.org/issue?@action=redirect&bpo=16764]: Support keyword arguments to zlib.decompress(). Patch by Xiang Zhang.

bpo-27736 [https://bugs.python.org/issue?@action=redirect&bpo=27736]: Prevent segfault after interpreter re-initialization due to ref count problem introduced in code for bpo-27038 [https://bugs.python.org/issue?@action=redirect&bpo=27038] in 3.6.0a3. Patch by Xiang Zhang.

bpo-25628 [https://bugs.python.org/issue?@action=redirect&bpo=25628]: The verbose and rename parameters for collections.namedtuple are now keyword-only.

bpo-12345 [https://bugs.python.org/issue?@action=redirect&bpo=12345]: Add mathematical constant tau to math and cmath. See also PEP 628.

bpo-26823 [https://bugs.python.org/issue?@action=redirect&bpo=26823]: traceback.StackSummary.format now abbreviates large sections of repeated lines as “[Previous line repeated {count} more times]” (this change then further affects other traceback display operations in the module). Patch by Emanuel Barry.

bpo-27664 [https://bugs.python.org/issue?@action=redirect&bpo=27664]: Add to concurrent.futures.thread.ThreadPoolExecutor() the ability to specify a thread name prefix.

bpo-27181 [https://bugs.python.org/issue?@action=redirect&bpo=27181]: Add geometric_mean and harmonic_mean to statistics module.

bpo-27573 [https://bugs.python.org/issue?@action=redirect&bpo=27573]: code.interact now prints an message when exiting.

bpo-6422 [https://bugs.python.org/issue?@action=redirect&bpo=6422]: Add autorange method to timeit.Timer objects.

bpo-27773 [https://bugs.python.org/issue?@action=redirect&bpo=27773]: Correct some memory management errors server_hostname in _ssl.wrap_socket().

bpo-26750 [https://bugs.python.org/issue?@action=redirect&bpo=26750]: unittest.mock.create_autospec() now works properly for subclasses of property() and other data descriptors. Removes the never publicly used, never documented unittest.mock.DescriptorTypes tuple.

bpo-26754 [https://bugs.python.org/issue?@action=redirect&bpo=26754]: Undocumented support of general bytes-like objects as path in compile() and similar functions is now deprecated.

bpo-26800 [https://bugs.python.org/issue?@action=redirect&bpo=26800]: Undocumented support of general bytes-like objects as paths in os functions is now deprecated.

bpo-26981 [https://bugs.python.org/issue?@action=redirect&bpo=26981]: Add _order_ compatibility shim to enum.Enum for Python 2/3 code bases.

bpo-27661 [https://bugs.python.org/issue?@action=redirect&bpo=27661]: Added tzinfo keyword argument to datetime.combine.

In the curses module, raise an error if window.getstr() or window.instr() is passed a negative value.

bpo-27783 [https://bugs.python.org/issue?@action=redirect&bpo=27783]: Fix possible usage of uninitialized memory in operator.methodcaller.

bpo-27774 [https://bugs.python.org/issue?@action=redirect&bpo=27774]: Fix possible Py_DECREF on unowned object in _sre.

bpo-27760 [https://bugs.python.org/issue?@action=redirect&bpo=27760]: Fix possible integer overflow in binascii.b2a_qp.

bpo-27758 [https://bugs.python.org/issue?@action=redirect&bpo=27758]: Fix possible integer overflow in the _csv module for large record lengths.

bpo-27568 [https://bugs.python.org/issue?@action=redirect&bpo=27568]: Prevent HTTPoxy attack (CVE-2016-1000110). Ignore the HTTP_PROXY variable when REQUEST_METHOD environment is set, which indicates that the script is in CGI mode.

bpo-7063 [https://bugs.python.org/issue?@action=redirect&bpo=7063]: Remove dead code from the “array” module’s slice handling. Patch by Chuck.

bpo-27656 [https://bugs.python.org/issue?@action=redirect&bpo=27656]: Do not assume sched.h defines any SCHED_* constants.

bpo-27130 [https://bugs.python.org/issue?@action=redirect&bpo=27130]: In the “zlib” module, fix handling of large buffers (typically 4 GiB) when compressing and decompressing. Previously, inputs were limited to 4 GiB, and compression and decompression operations did not properly handle results of 4 GiB.

bpo-24773 [https://bugs.python.org/issue?@action=redirect&bpo=24773]: Implemented PEP 495 (Local Time Disambiguation).

Expose the EPOLLEXCLUSIVE constant (when it is defined) in the select module.

bpo-27567 [https://bugs.python.org/issue?@action=redirect&bpo=27567]: Expose the EPOLLRDHUP and POLLRDHUP constants in the select module.

bpo-1621 [https://bugs.python.org/issue?@action=redirect&bpo=1621]: Avoid signed int negation overflow in the “audioop” module.

bpo-27533 [https://bugs.python.org/issue?@action=redirect&bpo=27533]: Release GIL in nt._isdir

bpo-17711 [https://bugs.python.org/issue?@action=redirect&bpo=17711]: Fixed unpickling by the persistent ID with protocol 0. Original patch by Alexandre Vassalotti.

bpo-27522 [https://bugs.python.org/issue?@action=redirect&bpo=27522]: Avoid an unintentional reference cycle in email.feedparser.

bpo-27512 [https://bugs.python.org/issue?@action=redirect&bpo=27512]: Fix a segfault when os.fspath() called an __fspath__() method that raised an exception. Patch by Xiang Zhang.

IDLE

bpo-27714 [https://bugs.python.org/issue?@action=redirect&bpo=27714]: text_textview and test_autocomplete now pass when re-run in the same process. This occurs when test_idle fails when run with the -w option but without -jn. Fix warning from test_config.

bpo-27621 [https://bugs.python.org/issue?@action=redirect&bpo=27621]: Put query response validation error messages in the query box itself instead of in a separate messagebox. Redo tests to match. Add Mac OSX refinements. Original patch by Mark Roseman.

bpo-27620 [https://bugs.python.org/issue?@action=redirect&bpo=27620]: Escape key now closes Query box as cancelled.

bpo-27609 [https://bugs.python.org/issue?@action=redirect&bpo=27609]: IDLE: tab after initial whitespace should tab, not autocomplete. This fixes problem with writing docstrings at least twice indented.

bpo-27609 [https://bugs.python.org/issue?@action=redirect&bpo=27609]: Explicitly return None when there are also non-None returns. In a few cases, reverse a condition and eliminate a return.

bpo-25507 [https://bugs.python.org/issue?@action=redirect&bpo=25507]: IDLE no longer runs buggy code because of its tkinter imports. Users must include the same imports required to run directly in Python.

bpo-27173 [https://bugs.python.org/issue?@action=redirect&bpo=27173]: Add ‘IDLE Modern Unix’ to the built-in key sets. Make the default key set depend on the platform. Add tests for the changes to the config module.

bpo-27452 [https://bugs.python.org/issue?@action=redirect&bpo=27452]: add line counter and crc to IDLE configHandler test dump.

Tests

bpo-25805 [https://bugs.python.org/issue?@action=redirect&bpo=25805]: Skip a test in test_pkgutil as needed that doesn’t work when __name__ == __main__. Patch by SilentGhost.

bpo-27472 [https://bugs.python.org/issue?@action=redirect&bpo=27472]: Add test.support.unix_shell as the path to the default shell.

bpo-27369 [https://bugs.python.org/issue?@action=redirect&bpo=27369]: In test_pyexpat, avoid testing an error message detail that changed in Expat 2.2.0.

bpo-27594 [https://bugs.python.org/issue?@action=redirect&bpo=27594]: Prevent assertion error when running test_ast with coverage enabled: ensure code object has a valid first line number. Patch suggested by Ivan Levkivskyi.

Windows

bpo-27647 [https://bugs.python.org/issue?@action=redirect&bpo=27647]: Update bundled Tcl/Tk to 8.6.6.

bpo-27610 [https://bugs.python.org/issue?@action=redirect&bpo=27610]: Adds PEP 514 metadata to Windows installer

bpo-27469 [https://bugs.python.org/issue?@action=redirect&bpo=27469]: Adds a shell extension to the launcher so that drag and drop works correctly.

bpo-27309 [https://bugs.python.org/issue?@action=redirect&bpo=27309]: Enables proper Windows styles in python[w].exe manifest.

Build

bpo-27713 [https://bugs.python.org/issue?@action=redirect&bpo=27713]: Suppress spurious build warnings when updating importlib’s bootstrap files. Patch by Xiang Zhang

bpo-25825 [https://bugs.python.org/issue?@action=redirect&bpo=25825]: Correct the references to Modules/python.exp, which is required on AIX. The references were accidentally changed in 3.5.0a1.

bpo-27453 [https://bugs.python.org/issue?@action=redirect&bpo=27453]: CPP invocation in configure must use CPPFLAGS. Patch by Chi Hsuan Yen.

bpo-27641 [https://bugs.python.org/issue?@action=redirect&bpo=27641]: The configure script now inserts comments into the makefile to prevent the pgen and _freeze_importlib executables from being cross-compiled.

bpo-26662 [https://bugs.python.org/issue?@action=redirect&bpo=26662]: Set PYTHON_FOR_GEN in configure as the Python program to be used for file generation during the build.

bpo-10910 [https://bugs.python.org/issue?@action=redirect&bpo=10910]: Avoid C++ compilation errors on FreeBSD and OS X. Also update FreedBSD version checks for the original ctype UTF-8 workaround.

Python 3.6.0 alpha 3

Release date: 2016-07-11

Core and Builtins

bpo-27473 [https://bugs.python.org/issue?@action=redirect&bpo=27473]: Fixed possible integer overflow in bytes and bytearray concatenations. Patch by Xiang Zhang.

bpo-23034 [https://bugs.python.org/issue?@action=redirect&bpo=23034]: The output of a special Python build with defined COUNT_ALLOCS, SHOW_ALLOC_COUNT or SHOW_TRACK_COUNT macros is now off by default. It can be re-enabled using the “-X showalloccount” option. It now outputs to stderr instead of stdout.

bpo-27443 [https://bugs.python.org/issue?@action=redirect&bpo=27443]: __length_hint__() of bytearray iterators no longer return a negative integer for a resized bytearray.

bpo-27007 [https://bugs.python.org/issue?@action=redirect&bpo=27007]: The fromhex() class methods of bytes and bytearray subclasses now return an instance of corresponding subclass.

Library

bpo-26844 [https://bugs.python.org/issue?@action=redirect&bpo=26844]: Fix error message for imp.find_module() to refer to ‘path’ instead of ‘name’. Patch by Lev Maximov.

bpo-23804 [https://bugs.python.org/issue?@action=redirect&bpo=23804]: Fix SSL zero-length recv() calls to not block and not raise an error about unclean EOF.

bpo-27466 [https://bugs.python.org/issue?@action=redirect&bpo=27466]: Change time format returned by http.cookie.time2netscape, confirming the netscape cookie format and making it consistent with documentation.

bpo-21708 [https://bugs.python.org/issue?@action=redirect&bpo=21708]: Deprecated dbm.dumb behavior that differs from common dbm behavior: creating a database in ‘r’ and ‘w’ modes and modifying a database in ‘r’ mode.

bpo-26721 [https://bugs.python.org/issue?@action=redirect&bpo=26721]: Change the socketserver.StreamRequestHandler.wfile attribute to implement BufferedIOBase. In particular, the write() method no longer does partial writes.

bpo-22115 [https://bugs.python.org/issue?@action=redirect&bpo=22115]: Added methods trace_add, trace_remove and trace_info in the tkinter.Variable class. They replace old methods trace_variable, trace, trace_vdelete and trace_vinfo that use obsolete Tcl commands and might not work in future versions of Tcl. Fixed old tracing methods: trace_vdelete() with wrong mode no longer break tracing, trace_vinfo() now always returns a list of pairs of strings, tracing in the “u” mode now works.

bpo-26243 [https://bugs.python.org/issue?@action=redirect&bpo=26243]: Only the level argument to zlib.compress() is keyword argument now. The first argument is positional-only.

bpo-27038 [https://bugs.python.org/issue?@action=redirect&bpo=27038]: Expose the DirEntry type as os.DirEntry. Code patch by Jelle Zijlstra.

bpo-27186 [https://bugs.python.org/issue?@action=redirect&bpo=27186]: Update os.fspath()/PyOS_FSPath() to check the return value of __fspath__() to be either str or bytes.

bpo-18726 [https://bugs.python.org/issue?@action=redirect&bpo=18726]: All optional parameters of the dump(), dumps(), load() and loads() functions and JSONEncoder and JSONDecoder class constructors in the json module are now keyword-only.

bpo-27319 [https://bugs.python.org/issue?@action=redirect&bpo=27319]: Methods selection_set(), selection_add(), selection_remove() and selection_toggle() of ttk.TreeView now allow passing multiple items as multiple arguments instead of passing them as a tuple. Deprecated undocumented ability of calling the selection() method with arguments.

bpo-27079 [https://bugs.python.org/issue?@action=redirect&bpo=27079]: Fixed curses.ascii functions isblank(), iscntrl() and ispunct().

bpo-27294 [https://bugs.python.org/issue?@action=redirect&bpo=27294]: Numerical state in the repr for Tkinter event objects is now represented as a combination of known flags.

bpo-27177 [https://bugs.python.org/issue?@action=redirect&bpo=27177]: Match objects in the re module now support index-like objects as group indices. Based on patches by Jeroen Demeyer and Xiang Zhang.

bpo-26754 [https://bugs.python.org/issue?@action=redirect&bpo=26754]: Some functions (compile() etc) accepted a filename argument encoded as an iterable of integers. Now only strings and byte-like objects are accepted.

bpo-26536 [https://bugs.python.org/issue?@action=redirect&bpo=26536]: socket.ioctl now supports SIO_LOOPBACK_FAST_PATH. Patch by Daniel Stokes.

bpo-27048 [https://bugs.python.org/issue?@action=redirect&bpo=27048]: Prevents distutils failing on Windows when environment variables contain non-ASCII characters

bpo-27330 [https://bugs.python.org/issue?@action=redirect&bpo=27330]: Fixed possible leaks in the ctypes module.

bpo-27238 [https://bugs.python.org/issue?@action=redirect&bpo=27238]: Got rid of bare excepts in the turtle module. Original patch by Jelle Zijlstra.

bpo-27122 [https://bugs.python.org/issue?@action=redirect&bpo=27122]: When an exception is raised within the context being managed by a contextlib.ExitStack() and one of the exit stack generators catches and raises it in a chain, do not re-raise the original exception when exiting, let the new chained one through. This avoids the PEP 479 bug described in issue25782.

Security

bpo-27278 [https://bugs.python.org/issue?@action=redirect&bpo=27278]: Fix os.urandom() implementation using getrandom() on Linux. Truncate size to INT_MAX and loop until we collected enough random bytes, instead of casting a directly Py_ssize_t to int.

Library

bpo-16864 [https://bugs.python.org/issue?@action=redirect&bpo=16864]: sqlite3.Cursor.lastrowid now supports REPLACE statement. Initial patch by Alex LordThorsen.

bpo-26386 [https://bugs.python.org/issue?@action=redirect&bpo=26386]: Fixed ttk.TreeView selection operations with item id’s containing spaces.

bpo-8637 [https://bugs.python.org/issue?@action=redirect&bpo=8637]: Honor a pager set by the env var MANPAGER (in preference to one set by the env var PAGER).

Security

bpo-22636 [https://bugs.python.org/issue?@action=redirect&bpo=22636]: Avoid shell injection problems with ctypes.util.find_library().

Library

bpo-16182 [https://bugs.python.org/issue?@action=redirect&bpo=16182]: Fix various functions in the “readline” module to use the locale encoding, and fix get_begidx() and get_endidx() to return code point indexes.

bpo-27392 [https://bugs.python.org/issue?@action=redirect&bpo=27392]: Add loop.connect_accepted_socket(). Patch by Jim Fulton.

IDLE

bpo-27477 [https://bugs.python.org/issue?@action=redirect&bpo=27477]: IDLE search dialogs now use ttk widgets.

bpo-27173 [https://bugs.python.org/issue?@action=redirect&bpo=27173]: Add ‘IDLE Modern Unix’ to the built-in key sets. Make the default key set depend on the platform. Add tests for the changes to the config module.

bpo-27452 [https://bugs.python.org/issue?@action=redirect&bpo=27452]: make command line “idle-test> python test_help.py” work. __file__ is relative when python is started in the file’s directory.

bpo-27452 [https://bugs.python.org/issue?@action=redirect&bpo=27452]: add line counter and crc to IDLE configHandler test dump.

bpo-27380 [https://bugs.python.org/issue?@action=redirect&bpo=27380]: IDLE: add query.py with base Query dialog and ttk widgets. Module had subclasses SectionName, ModuleName, and HelpSource, which are used to get information from users by configdialog and file =>Load Module. Each subclass has itw own validity checks. Using ModuleName allows users to edit bad module names instead of starting over. Add tests and delete the two files combined into the new one.

bpo-27372 [https://bugs.python.org/issue?@action=redirect&bpo=27372]: Test_idle no longer changes the locale.

bpo-27365 [https://bugs.python.org/issue?@action=redirect&bpo=27365]: Allow non-ascii chars in IDLE NEWS.txt, for contributor names.

bpo-27245 [https://bugs.python.org/issue?@action=redirect&bpo=27245]: IDLE: Cleanly delete custom themes and key bindings. Previously, when IDLE was started from a console or by import, a cascade of warnings was emitted. Patch by Serhiy Storchaka.

bpo-24137 [https://bugs.python.org/issue?@action=redirect&bpo=24137]: Run IDLE, test_idle, and htest with tkinter default root disabled. Fix code and tests that fail with this restriction. Fix htests to not create a second and redundant root and mainloop.

bpo-27310 [https://bugs.python.org/issue?@action=redirect&bpo=27310]: Fix IDLE.app failure to launch on OS X due to vestigial import.

C API

bpo-26754 [https://bugs.python.org/issue?@action=redirect&bpo=26754]: PyUnicode_FSDecoder() accepted a filename argument encoded as an iterable of integers. Now only strings and byte-like objects are accepted.

Build

bpo-28066 [https://bugs.python.org/issue?@action=redirect&bpo=28066]: Fix the logic that searches build directories for generated include files when building outside the source tree.

bpo-27442 [https://bugs.python.org/issue?@action=redirect&bpo=27442]: Expose the Android API level that python was built against, in sysconfig.get_config_vars() as ‘ANDROID_API_LEVEL’.

bpo-27434 [https://bugs.python.org/issue?@action=redirect&bpo=27434]: The interpreter that runs the cross-build, found in PATH, must now be of the same feature version (e.g. 3.6) as the source being built.

bpo-26930 [https://bugs.python.org/issue?@action=redirect&bpo=26930]: Update Windows builds to use OpenSSL 1.0.2h.

bpo-23968 [https://bugs.python.org/issue?@action=redirect&bpo=23968]: Rename the platform directory from plat-$(MACHDEP) to plat-$(PLATFORM_TRIPLET). Rename the config directory (LIBPL) from config-$(LDVERSION) to config-$(LDVERSION)-$(PLATFORM_TRIPLET). Install the platform specific _sysconfigdata module into the platform directory and rename it to include the ABIFLAGS.

Don’t use largefile support for GNU/Hurd.

Tools/Demos

bpo-27332 [https://bugs.python.org/issue?@action=redirect&bpo=27332]: Fixed the type of the first argument of module-level functions generated by Argument Clinic. Patch by Petr Viktorin.

bpo-27418 [https://bugs.python.org/issue?@action=redirect&bpo=27418]: Fixed Tools/importbench/importbench.py.

Documentation

bpo-19489 [https://bugs.python.org/issue?@action=redirect&bpo=19489]: Moved the search box from the sidebar to the header and footer of each page. Patch by Ammar Askar.

bpo-27285 [https://bugs.python.org/issue?@action=redirect&bpo=27285]: Update documentation to reflect the deprecation of pyvenv and normalize on the term “virtual environment”. Patch by Steve Piercy.

Tests

bpo-27027 [https://bugs.python.org/issue?@action=redirect&bpo=27027]: Added test.support.is_android that is True when this is an Android build.

Python 3.6.0 alpha 2

Release date: 2016-06-13

Core and Builtins

bpo-27095 [https://bugs.python.org/issue?@action=redirect&bpo=27095]: Simplified MAKE_FUNCTION and removed MAKE_CLOSURE opcodes. Patch by Demur Rumed.

bpo-27190 [https://bugs.python.org/issue?@action=redirect&bpo=27190]: Raise NotSupportedError if sqlite3 is older than 3.3.1. Patch by Dave Sawyer.

bpo-27286 [https://bugs.python.org/issue?@action=redirect&bpo=27286]: Fixed compiling BUILD_MAP_UNPACK_WITH_CALL opcode. Calling function with generalized unpacking (PEP 448) and conflicting keyword names could cause undefined behavior.

bpo-27140 [https://bugs.python.org/issue?@action=redirect&bpo=27140]: Added BUILD_CONST_KEY_MAP opcode.

bpo-27186 [https://bugs.python.org/issue?@action=redirect&bpo=27186]: Add support for os.PathLike objects to open() (part of PEP 519).

bpo-27066 [https://bugs.python.org/issue?@action=redirect&bpo=27066]: Fixed SystemError if a custom opener (for open()) returns a negative number without setting an exception.

bpo-26983 [https://bugs.python.org/issue?@action=redirect&bpo=26983]: float() now always return an instance of exact float. The deprecation warning is emitted if __float__ returns an instance of a strict subclass of float. In a future versions of Python this can be an error.

bpo-27097 [https://bugs.python.org/issue?@action=redirect&bpo=27097]: Python interpreter is now about 7% faster due to optimized instruction decoding. Based on patch by Demur Rumed.

bpo-26647 [https://bugs.python.org/issue?@action=redirect&bpo=26647]: Python interpreter now uses 16-bit wordcode instead of bytecode. Patch by Demur Rumed.

bpo-23275 [https://bugs.python.org/issue?@action=redirect&bpo=23275]: Allow assigning to an empty target list in round brackets: () = iterable.

bpo-27243 [https://bugs.python.org/issue?@action=redirect&bpo=27243]: Update the __aiter__ protocol: instead of returning an awaitable that resolves to an asynchronous iterator, the asynchronous iterator should be returned directly. Doing the former will trigger a PendingDeprecationWarning.

Library

Comment out socket (SO_REUSEPORT) and posix (O_SHLOCK, O_EXLOCK) constants exposed on the API which are not implemented on GNU/Hurd. They would not work at runtime anyway.

bpo-27025 [https://bugs.python.org/issue?@action=redirect&bpo=27025]: Generated names for Tkinter widgets are now more meaningful and recognizable.

bpo-25455 [https://bugs.python.org/issue?@action=redirect&bpo=25455]: Fixed crashes in repr of recursive ElementTree.Element and functools.partial objects.

bpo-27294 [https://bugs.python.org/issue?@action=redirect&bpo=27294]: Improved repr for Tkinter event objects.

bpo-20508 [https://bugs.python.org/issue?@action=redirect&bpo=20508]: Improve exception message of IPv{4,6}Network.__getitem__. Patch by Gareth Rees.

Security

bpo-26556 [https://bugs.python.org/issue?@action=redirect&bpo=26556]: Update expat to 2.1.1, fixes CVE-2015-1283.

Fix TLS stripping vulnerability in smtplib, CVE-2016-0772. Reported by Team Oststrom.

Library

bpo-21386 [https://bugs.python.org/issue?@action=redirect&bpo=21386]: Implement missing IPv4Address.is_global property. It was documented since 07a5610bae9d. Initial patch by Roger Luethi.

bpo-27029 [https://bugs.python.org/issue?@action=redirect&bpo=27029]: Removed deprecated support of universal newlines mode from ZipFile.open().

bpo-27030 [https://bugs.python.org/issue?@action=redirect&bpo=27030]: Unknown escapes consisting of '\' and an ASCII letter in regular expressions now are errors. The re.LOCALE flag now can be used only with bytes patterns.

bpo-27186 [https://bugs.python.org/issue?@action=redirect&bpo=27186]: Add os.PathLike support to DirEntry (part of PEP 519). Initial patch by Jelle Zijlstra.

bpo-20900 [https://bugs.python.org/issue?@action=redirect&bpo=20900]: distutils register command now decodes HTTP responses correctly. Initial patch by ingrid.

bpo-27186 [https://bugs.python.org/issue?@action=redirect&bpo=27186]: Add os.PathLike support to pathlib, removing its provisional status (part of PEP 519). Initial patch by Dusty Phillips.

bpo-27186 [https://bugs.python.org/issue?@action=redirect&bpo=27186]: Add support for os.PathLike objects to os.fsencode() and os.fsdecode() (part of PEP 519).

bpo-27186 [https://bugs.python.org/issue?@action=redirect&bpo=27186]: Introduce os.PathLike and os.fspath() (part of PEP 519).

A new version of typing.py provides several new classes and features: @overload outside stubs, Reversible, DefaultDict, Text, ContextManager, Type[], NewType(), TYPE_CHECKING, and numerous bug fixes (note that some of the new features are not yet implemented in mypy or other static analyzers). Also classes for PEP 492 (Awaitable, AsyncIterable, AsyncIterator) have been added (in fact they made it into 3.5.1 but were never mentioned).

bpo-25738 [https://bugs.python.org/issue?@action=redirect&bpo=25738]: Stop http.server.BaseHTTPRequestHandler.send_error() from sending a message body for 205 Reset Content. Also, don’t send Content header fields in responses that don’t have a body. Patch by Susumu Koshiba.

bpo-21313 [https://bugs.python.org/issue?@action=redirect&bpo=21313]: Fix the “platform” module to tolerate when sys.version contains truncated build information.

Security

bpo-26839 [https://bugs.python.org/issue?@action=redirect&bpo=26839]: On Linux, os.urandom() now calls getrandom() with GRND_NONBLOCK to fall back on reading /dev/urandom if the urandom entropy pool is not initialized yet. Patch written by Colm Buckley.

Library

bpo-23883 [https://bugs.python.org/issue?@action=redirect&bpo=23883]: Added missing APIs to __all__ to match the documented APIs for the following modules: cgi, mailbox, mimetypes, plistlib and smtpd. Patches by Jacek Kołodziej.

bpo-27164 [https://bugs.python.org/issue?@action=redirect&bpo=27164]: In the zlib module, allow decompressing raw Deflate streams with a predefined zdict. Based on patch by Xiang Zhang.

bpo-24291 [https://bugs.python.org/issue?@action=redirect&bpo=24291]: Fix wsgiref.simple_server.WSGIRequestHandler to completely write data to the client. Previously it could do partial writes and truncate data. Also, wsgiref.handler.ServerHandler can now handle stdout doing partial writes, but this is deprecated.

bpo-21272 [https://bugs.python.org/issue?@action=redirect&bpo=21272]: Use _sysconfigdata.py to initialize distutils.sysconfig.

bpo-19611 [https://bugs.python.org/issue?@action=redirect&bpo=19611]: inspect now reports the implicit .0 parameters generated by the compiler for comprehension and generator expression scopes as if they were positional-only parameters called implicit0. Patch by Jelle Zijlstra.

bpo-26809 [https://bugs.python.org/issue?@action=redirect&bpo=26809]: Add __all__ to string. Patch by Emanuel Barry.

bpo-26373 [https://bugs.python.org/issue?@action=redirect&bpo=26373]: subprocess.Popen.communicate now correctly ignores BrokenPipeError when the child process dies before .communicate() is called in more/all circumstances.

signal, socket, and ssl module IntEnum constant name lookups now return a consistent name for values having multiple names. Ex: signal.Signals(6) now refers to itself as signal.SIGALRM rather than flipping between that and signal.SIGIOT based on the interpreter’s hash randomization seed.

bpo-27167 [https://bugs.python.org/issue?@action=redirect&bpo=27167]: Clarify the subprocess.CalledProcessError error message text when the child process died due to a signal.

bpo-25931 [https://bugs.python.org/issue?@action=redirect&bpo=25931]: Don’t define socketserver.Forking* names on platforms such as Windows that do not support os.fork().

bpo-21776 [https://bugs.python.org/issue?@action=redirect&bpo=21776]: distutils.upload now correctly handles HTTPError. Initial patch by Claudiu Popa.

bpo-26526 [https://bugs.python.org/issue?@action=redirect&bpo=26526]: Replace custom parse tree validation in the parser module with a simple DFA validator.

bpo-27114 [https://bugs.python.org/issue?@action=redirect&bpo=27114]: Fix SSLContext._load_windows_store_certs fails with PermissionError

bpo-18383 [https://bugs.python.org/issue?@action=redirect&bpo=18383]: Avoid creating duplicate filters when using filterwarnings and simplefilter. Based on patch by Alex Shkop.

bpo-23026 [https://bugs.python.org/issue?@action=redirect&bpo=23026]: winreg.QueryValueEx() now return an integer for REG_QWORD type.

bpo-26741 [https://bugs.python.org/issue?@action=redirect&bpo=26741]: subprocess.Popen destructor now emits a ResourceWarning warning if the child process is still running.

bpo-27056 [https://bugs.python.org/issue?@action=redirect&bpo=27056]: Optimize pickle.load() and pickle.loads(), up to 10% faster to deserialize a lot of small objects.

bpo-21271 [https://bugs.python.org/issue?@action=redirect&bpo=21271]: New keyword only parameters in reset_mock call.

IDLE

bpo-5124 [https://bugs.python.org/issue?@action=redirect&bpo=5124]: Paste with text selected now replaces the selection on X11. This matches how paste works on Windows, Mac, most modern Linux apps, and ttk widgets. Original patch by Serhiy Storchaka.

bpo-24750 [https://bugs.python.org/issue?@action=redirect&bpo=24750]: Switch all scrollbars in IDLE to ttk versions. Where needed, minimal tests are added to cover changes.

bpo-24759 [https://bugs.python.org/issue?@action=redirect&bpo=24759]: IDLE requires tk 8.5 and availability ttk widgets. Delete now unneeded tk version tests and code for older versions. Add test for IDLE syntax colorizer.

bpo-27239 [https://bugs.python.org/issue?@action=redirect&bpo=27239]: idlelib.macosx.isXyzTk functions initialize as needed.

bpo-27262 [https://bugs.python.org/issue?@action=redirect&bpo=27262]: move Aqua unbinding code, which enable context menus, to macosx.

bpo-24759 [https://bugs.python.org/issue?@action=redirect&bpo=24759]: Make clear in idlelib.idle_test.__init__ that the directory is a private implementation of test.test_idle and tool for maintainers.

bpo-27196 [https://bugs.python.org/issue?@action=redirect&bpo=27196]: Stop ‘ThemeChanged’ warnings when running IDLE tests. These persisted after other warnings were suppressed in #20567. Apply Serhiy Storchaka’s update_idletasks solution to four test files. Record this additional advice in idle_test/README.txt

bpo-20567 [https://bugs.python.org/issue?@action=redirect&bpo=20567]: Revise idle_test/README.txt with advice about avoiding tk warning messages from tests. Apply advice to several IDLE tests.

bpo-24225 [https://bugs.python.org/issue?@action=redirect&bpo=24225]: Update idlelib/README.txt with new file names and event handlers.

bpo-27156 [https://bugs.python.org/issue?@action=redirect&bpo=27156]: Remove obsolete code not used by IDLE.

bpo-27117 [https://bugs.python.org/issue?@action=redirect&bpo=27117]: Make colorizer htest and turtledemo work with dark themes. Move code for configuring text widget colors to a new function.

bpo-24225 [https://bugs.python.org/issue?@action=redirect&bpo=24225]: Rename many idlelib/*.py and idle_test/test_*.py files. Edit files to replace old names with new names when the old name referred to the module rather than the class it contained. See the issue and IDLE section in What’s New in 3.6 for more.

bpo-26673 [https://bugs.python.org/issue?@action=redirect&bpo=26673]: When tk reports font size as 0, change to size 10. Such fonts on Linux prevented the configuration dialog from opening.

bpo-21939 [https://bugs.python.org/issue?@action=redirect&bpo=21939]: Add test for IDLE’s percolator. Original patch by Saimadhav Heblikar.

bpo-21676 [https://bugs.python.org/issue?@action=redirect&bpo=21676]: Add test for IDLE’s replace dialog. Original patch by Saimadhav Heblikar.

bpo-18410 [https://bugs.python.org/issue?@action=redirect&bpo=18410]: Add test for IDLE’s search dialog. Original patch by Westley Martínez.

bpo-21703 [https://bugs.python.org/issue?@action=redirect&bpo=21703]: Add test for undo delegator. Patch mostly by Saimadhav Heblikar .

bpo-27044 [https://bugs.python.org/issue?@action=redirect&bpo=27044]: Add ConfigDialog.remove_var_callbacks to stop memory leaks.

bpo-23977 [https://bugs.python.org/issue?@action=redirect&bpo=23977]: Add more asserts to test_delegator.

Documentation

bpo-16484 [https://bugs.python.org/issue?@action=redirect&bpo=16484]: Change the default PYTHONDOCS URL to “https:”, and fix the resulting links to use lowercase. Patch by Sean Rodman, test by Kaushik Nadikuditi.

bpo-24136 [https://bugs.python.org/issue?@action=redirect&bpo=24136]: Document the new PEP 448 unpacking syntax of 3.5.

bpo-22558 [https://bugs.python.org/issue?@action=redirect&bpo=22558]: Add remaining doc links to source code for Python-coded modules. Patch by Yoni Lavi.

Tests

bpo-25285 [https://bugs.python.org/issue?@action=redirect&bpo=25285]: regrtest now uses subprocesses when the -j1 command line option is used: each test file runs in a fresh child process. Before, the -j1 option was ignored.

bpo-25285 [https://bugs.python.org/issue?@action=redirect&bpo=25285]: Tools/buildbot/test.bat script now uses -j1 by default to run each test file in fresh child process.

Windows

bpo-27064 [https://bugs.python.org/issue?@action=redirect&bpo=27064]: The py.exe launcher now defaults to Python 3. The Windows launcher py.exe no longer prefers an installed Python 2 version over Python 3 by default when used interactively.

Build

bpo-27229 [https://bugs.python.org/issue?@action=redirect&bpo=27229]: Fix the cross-compiling pgen rule for in-tree builds. Patch by Xavier de Gaye.

bpo-26930 [https://bugs.python.org/issue?@action=redirect&bpo=26930]: Update OS X 10.5+ 32-bit-only installer to build and link with OpenSSL 1.0.2h.

Windows

bpo-17500 [https://bugs.python.org/issue?@action=redirect&bpo=17500]: Remove unused and outdated icons. (See also: https://github.com/python/pythondotorg/issues/945)

C API

bpo-27186 [https://bugs.python.org/issue?@action=redirect&bpo=27186]: Add the PyOS_FSPath() function (part of PEP 519).

bpo-26282 [https://bugs.python.org/issue?@action=redirect&bpo=26282]: PyArg_ParseTupleAndKeywords() now supports positional-only parameters.

Tools/Demos

bpo-26282 [https://bugs.python.org/issue?@action=redirect&bpo=26282]: Argument Clinic now supports positional-only and keyword parameters in the same function.

Python 3.6.0 alpha 1

Release date: 2016-05-16

Core and Builtins

bpo-20041 [https://bugs.python.org/issue?@action=redirect&bpo=20041]: Fixed TypeError when frame.f_trace is set to None. Patch by Xavier de Gaye.

bpo-26168 [https://bugs.python.org/issue?@action=redirect&bpo=26168]: Fixed possible refleaks in failing Py_BuildValue() with the “N” format unit.

bpo-26991 [https://bugs.python.org/issue?@action=redirect&bpo=26991]: Fix possible refleak when creating a function with annotations.

bpo-27039 [https://bugs.python.org/issue?@action=redirect&bpo=27039]: Fixed bytearray.remove() for values greater than 127. Based on patch by Joe Jevnik.

bpo-23640 [https://bugs.python.org/issue?@action=redirect&bpo=23640]: int.from_bytes() no longer bypasses constructors for subclasses.

bpo-27005 [https://bugs.python.org/issue?@action=redirect&bpo=27005]: Optimized the float.fromhex() class method for exact float. It is now 2 times faster.

bpo-18531 [https://bugs.python.org/issue?@action=redirect&bpo=18531]: Single var-keyword argument of dict subtype was passed unscathed to the C-defined function. Now it is converted to exact dict.

bpo-26811 [https://bugs.python.org/issue?@action=redirect&bpo=26811]: gc.get_objects() no longer contains a broken tuple with NULL pointer.

bpo-20120 [https://bugs.python.org/issue?@action=redirect&bpo=20120]: Use RawConfigParser for .pypirc parsing, removing support for interpolation unintentionally added with move to Python 3. Behavior no longer does any interpolation in .pypirc files, matching behavior in Python 2.7 and Setuptools 19.0.

bpo-26249 [https://bugs.python.org/issue?@action=redirect&bpo=26249]: Memory functions of the PyMem_Malloc() domain (PYMEM_DOMAIN_MEM) now use the pymalloc allocator rather than system malloc(). Applications calling PyMem_Malloc() without holding the GIL can now crash: use PYTHONMALLOC=debug environment variable to validate the usage of memory allocators in your application.

bpo-26802 [https://bugs.python.org/issue?@action=redirect&bpo=26802]: Optimize function calls only using unpacking like func(*tuple) (no other positional argument, no keyword): avoid copying the tuple. Patch written by Joe Jevnik.

bpo-26659 [https://bugs.python.org/issue?@action=redirect&bpo=26659]: Make the builtin slice type support cycle collection.

bpo-26718 [https://bugs.python.org/issue?@action=redirect&bpo=26718]: super.__init__ no longer leaks memory if called multiple times. NOTE: A direct call of super.__init__ is not endorsed!

bpo-27138 [https://bugs.python.org/issue?@action=redirect&bpo=27138]: Fix the doc comment for FileFinder.find_spec().

bpo-27147 [https://bugs.python.org/issue?@action=redirect&bpo=27147]: Mention PEP 420 in the importlib docs.

bpo-25339 [https://bugs.python.org/issue?@action=redirect&bpo=25339]: PYTHONIOENCODING now has priority over locale in setting the error handler for stdin and stdout.

bpo-26494 [https://bugs.python.org/issue?@action=redirect&bpo=26494]: Fixed crash on iterating exhausting iterators. Affected classes are generic sequence iterators, iterators of str, bytes, bytearray, list, tuple, set, frozenset, dict, OrderedDict, corresponding views and os.scandir() iterator.

bpo-26574 [https://bugs.python.org/issue?@action=redirect&bpo=26574]: Optimize bytes.replace(b'', b'.') and bytearray.replace(b'', b'.'). Patch written by Josh Snider.

bpo-26581 [https://bugs.python.org/issue?@action=redirect&bpo=26581]: If coding cookie is specified multiple times on a line in Python source code file, only the first one is taken to account.

bpo-19711 [https://bugs.python.org/issue?@action=redirect&bpo=19711]: Add tests for reloading namespace packages.

bpo-21099 [https://bugs.python.org/issue?@action=redirect&bpo=21099]: Switch applicable importlib tests to use PEP 451 API.

bpo-26563 [https://bugs.python.org/issue?@action=redirect&bpo=26563]: Debug hooks on Python memory allocators now raise a fatal error if functions of the PyMem_Malloc() family are called without holding the GIL.

bpo-26564 [https://bugs.python.org/issue?@action=redirect&bpo=26564]: On error, the debug hooks on Python memory allocators now use the tracemalloc module to get the traceback where a memory block was allocated.

bpo-26558 [https://bugs.python.org/issue?@action=redirect&bpo=26558]: The debug hooks on Python memory allocator PyObject_Malloc() now detect when functions are called without holding the GIL.

bpo-26516 [https://bugs.python.org/issue?@action=redirect&bpo=26516]: Add PYTHONMALLOC environment variable to set the Python memory allocators and/or install debug hooks.

bpo-26516 [https://bugs.python.org/issue?@action=redirect&bpo=26516]: The PyMem_SetupDebugHooks() function can now also be used on Python compiled in release mode.

bpo-26516 [https://bugs.python.org/issue?@action=redirect&bpo=26516]: The PYTHONMALLOCSTATS environment variable can now also be used on Python compiled in release mode. It now has no effect if set to an empty string.

bpo-26516 [https://bugs.python.org/issue?@action=redirect&bpo=26516]: In debug mode, debug hooks are now also installed on Python memory allocators when Python is configured without pymalloc.

bpo-26464 [https://bugs.python.org/issue?@action=redirect&bpo=26464]: Fix str.translate() when string is ASCII and first replacements removes character, but next replacement uses a non-ASCII character or a string longer than 1 character. Regression introduced in Python 3.5.0.

bpo-22836 [https://bugs.python.org/issue?@action=redirect&bpo=22836]: Ensure exception reports from PyErr_Display() and PyErr_WriteUnraisable() are sensible even when formatting them produces secondary errors. This affects the reports produced by sys.__excepthook__() and when __del__() raises an exception.

bpo-26302 [https://bugs.python.org/issue?@action=redirect&bpo=26302]: Correct behavior to reject comma as a legal character for cookie names.

bpo-26136 [https://bugs.python.org/issue?@action=redirect&bpo=26136]: Upgrade the warning when a generator raises StopIteration from PendingDeprecationWarning to DeprecationWarning. Patch by Anish Shah.

bpo-26204 [https://bugs.python.org/issue?@action=redirect&bpo=26204]: The compiler now ignores all constant statements: bytes, str, int, float, complex, name constants (None, False, True), Ellipsis and ast.Constant; not only str and int. For example, 1.0 is now ignored in def f(): 1.0.

bpo-4806 [https://bugs.python.org/issue?@action=redirect&bpo=4806]: Avoid masking the original TypeError exception when using star (*) unpacking in function calls. Based on patch by Hagen Fürstenau and Daniel Urban.

bpo-26146 [https://bugs.python.org/issue?@action=redirect&bpo=26146]: Add a new kind of AST node: ast.Constant. It can be used by external AST optimizers, but the compiler does not emit directly such node.

bpo-23601 [https://bugs.python.org/issue?@action=redirect&bpo=23601]: Sped-up allocation of dict key objects by using Python’s small object allocator. (Contributed by Julian Taylor.)

bpo-18018 [https://bugs.python.org/issue?@action=redirect&bpo=18018]: Import raises ImportError instead of SystemError if a relative import is attempted without a known parent package.

bpo-25843 [https://bugs.python.org/issue?@action=redirect&bpo=25843]: When compiling code, don’t merge constants if they are equal but have a different types. For example, f1, f2 = lambda: 1, lambda: 1.0 is now correctly compiled to two different functions: f1() returns 1 (int) and f2() returns 1.0 (float), even if 1 and 1.0 are equal.

bpo-26107 [https://bugs.python.org/issue?@action=redirect&bpo=26107]: The format of the co_lnotab attribute of code objects changes to support negative line number delta.

bpo-26154 [https://bugs.python.org/issue?@action=redirect&bpo=26154]: Add a new private _PyThreadState_UncheckedGet() function to get the current Python thread state, but don’t issue a fatal error if it is NULL. This new function must be used instead of accessing directly the _PyThreadState_Current variable. The variable is no more exposed since Python 3.5.1 to hide the exact implementation of atomic C types, to avoid compiler issues.

bpo-25791 [https://bugs.python.org/issue?@action=redirect&bpo=25791]: If __package__ != __spec__.parent or if neither __package__ or __spec__ are defined then ImportWarning is raised.

bpo-22995 [https://bugs.python.org/issue?@action=redirect&bpo=22995]: [UPDATE] Comment out the one of the pickleability tests in _PyObject_GetState() due to regressions observed in Cython-based projects.

bpo-25961 [https://bugs.python.org/issue?@action=redirect&bpo=25961]: Disallowed null characters in the type name.

bpo-25973 [https://bugs.python.org/issue?@action=redirect&bpo=25973]: Fix segfault when an invalid nonlocal statement binds a name starting with two underscores.

bpo-22995 [https://bugs.python.org/issue?@action=redirect&bpo=22995]: Instances of extension types with a state that aren’t subclasses of list or dict and haven’t implemented any pickle-related methods (__reduce__, __reduce_ex__, __getnewargs__, __getnewargs_ex__, or __getstate__), can no longer be pickled. Including memoryview.

bpo-20440 [https://bugs.python.org/issue?@action=redirect&bpo=20440]: Massive replacing unsafe attribute setting code with special macro Py_SETREF.

bpo-25766 [https://bugs.python.org/issue?@action=redirect&bpo=25766]: Special method __bytes__() now works in str subclasses.

bpo-25421 [https://bugs.python.org/issue?@action=redirect&bpo=25421]: __sizeof__ methods of builtin types now use dynamic basic size. This allows sys.getsize() to work correctly with their subclasses with __slots__ defined.

bpo-25709 [https://bugs.python.org/issue?@action=redirect&bpo=25709]: Fixed problem with in-place string concatenation and utf-8 cache.

bpo-5319 [https://bugs.python.org/issue?@action=redirect&bpo=5319]: New Py_FinalizeEx() API allowing Python to set an exit status of 120 on failure to flush buffered streams.

bpo-25485 [https://bugs.python.org/issue?@action=redirect&bpo=25485]: telnetlib.Telnet is now a context manager.

bpo-24097 [https://bugs.python.org/issue?@action=redirect&bpo=24097]: Fixed crash in object.__reduce__() if slot name is freed inside __getattr__.

bpo-24731 [https://bugs.python.org/issue?@action=redirect&bpo=24731]: Fixed crash on converting objects with special methods __bytes__, __trunc__, and __float__ returning instances of subclasses of bytes, int, and float to subclasses of bytes, int, and float correspondingly.

bpo-25630 [https://bugs.python.org/issue?@action=redirect&bpo=25630]: Fix a possible segfault during argument parsing in functions that accept filesystem paths.

bpo-23564 [https://bugs.python.org/issue?@action=redirect&bpo=23564]: Fixed a partially broken sanity check in the _posixsubprocess internals regarding how fds_to_pass were passed to the child. The bug had no actual impact as subprocess.py already avoided it.

bpo-25388 [https://bugs.python.org/issue?@action=redirect&bpo=25388]: Fixed tokenizer crash when processing undecodable source code with a null byte.

bpo-25462 [https://bugs.python.org/issue?@action=redirect&bpo=25462]: The hash of the key now is calculated only once in most operations in C implementation of OrderedDict.

bpo-22995 [https://bugs.python.org/issue?@action=redirect&bpo=22995]: Default implementation of __reduce__ and __reduce_ex__ now rejects builtin types with not defined __new__.

bpo-24802 [https://bugs.python.org/issue?@action=redirect&bpo=24802]: Avoid buffer overreads when int(), float(), compile(), exec() and eval() are passed bytes-like objects. These objects are not necessarily terminated by a null byte, but the functions assumed they were.

bpo-25555 [https://bugs.python.org/issue?@action=redirect&bpo=25555]: Fix parser and AST: fill lineno and col_offset of “arg” node when compiling AST from Python objects.

bpo-24726 [https://bugs.python.org/issue?@action=redirect&bpo=24726]: Fixed a crash and leaking NULL in repr() of OrderedDict that was mutated by direct calls of dict methods.

bpo-25449 [https://bugs.python.org/issue?@action=redirect&bpo=25449]: Iterating OrderedDict with keys with unstable hash now raises KeyError in C implementations as well as in Python implementation.

bpo-25395 [https://bugs.python.org/issue?@action=redirect&bpo=25395]: Fixed crash when highly nested OrderedDict structures were garbage collected.

bpo-25401 [https://bugs.python.org/issue?@action=redirect&bpo=25401]: Optimize bytes.fromhex() and bytearray.fromhex(): they are now between 2x and 3.5x faster.

bpo-25399 [https://bugs.python.org/issue?@action=redirect&bpo=25399]: Optimize bytearray % args using the new private _PyBytesWriter API. Formatting is now between 2.5 and 5 times faster.

bpo-25274 [https://bugs.python.org/issue?@action=redirect&bpo=25274]: sys.setrecursionlimit() now raises a RecursionError if the new recursion limit is too low depending at the current recursion depth. Modify also the “lower-water mark” formula to make it monotonic. This mark is used to decide when the overflowed flag of the thread state is reset.

bpo-24402 [https://bugs.python.org/issue?@action=redirect&bpo=24402]: Fix input() to prompt to the redirected stdout when sys.stdout.fileno() fails.

bpo-25349 [https://bugs.python.org/issue?@action=redirect&bpo=25349]: Optimize bytes % args using the new private _PyBytesWriter API. Formatting is now up to 2 times faster.

bpo-24806 [https://bugs.python.org/issue?@action=redirect&bpo=24806]: Prevent builtin types that are not allowed to be subclassed from being subclassed through multiple inheritance.

bpo-25301 [https://bugs.python.org/issue?@action=redirect&bpo=25301]: The UTF-8 decoder is now up to 15 times as fast for error handlers: ignore, replace and surrogateescape.

bpo-24848 [https://bugs.python.org/issue?@action=redirect&bpo=24848]: Fixed a number of bugs in UTF-7 decoding of misformed data.

bpo-25267 [https://bugs.python.org/issue?@action=redirect&bpo=25267]: The UTF-8 encoder is now up to 75 times as fast for error handlers: ignore, replace, surrogateescape, surrogatepass. Patch co-written with Serhiy Storchaka.

bpo-25280 [https://bugs.python.org/issue?@action=redirect&bpo=25280]: Import trace messages emitted in verbose (-v) mode are no longer formatted twice.

bpo-25227 [https://bugs.python.org/issue?@action=redirect&bpo=25227]: Optimize ASCII and latin1 encoders with the surrogateescape error handler: the encoders are now up to 3 times as fast. Initial patch written by Serhiy Storchaka.

bpo-25003 [https://bugs.python.org/issue?@action=redirect&bpo=25003]: On Solaris 11.3 or newer, os.urandom() now uses the getrandom() function instead of the getentropy() function. The getentropy() function is blocking to generate very good quality entropy, os.urandom() doesn’t need such high-quality entropy.

bpo-9232 [https://bugs.python.org/issue?@action=redirect&bpo=9232]: Modify Python’s grammar to allow trailing commas in the argument list of a function declaration. For example, “def f(*, a = 3,): pass” is now legal. Patch from Mark Dickinson.

bpo-24965 [https://bugs.python.org/issue?@action=redirect&bpo=24965]: Implement PEP 498 “Literal String Interpolation”. This allows you to embed expressions inside f-strings, which are converted to normal strings at run time. Given x=3, then f’value={x}’ == ‘value=3’. Patch by Eric V. Smith.

bpo-26478 [https://bugs.python.org/issue?@action=redirect&bpo=26478]: Fix semantic bugs when using binary operators with dictionary views and tuples.

bpo-26171 [https://bugs.python.org/issue?@action=redirect&bpo=26171]: Fix possible integer overflow and heap corruption in zipimporter.get_data().

bpo-25660 [https://bugs.python.org/issue?@action=redirect&bpo=25660]: Fix TAB key behaviour in REPL with readline.

bpo-26288 [https://bugs.python.org/issue?@action=redirect&bpo=26288]: Optimize PyLong_AsDouble.

bpo-26289 [https://bugs.python.org/issue?@action=redirect&bpo=26289]: Optimize floor and modulo division for single-digit longs. Microbenchmarks show 2-2.5x improvement. Built-in ‘divmod’ function is now also ~10% faster. (See also: bpo-26315 [https://bugs.python.org/issue?@action=redirect&bpo=26315])

bpo-25887 [https://bugs.python.org/issue?@action=redirect&bpo=25887]: Raise a RuntimeError when a coroutine object is awaited more than once.

Library

bpo-27057 [https://bugs.python.org/issue?@action=redirect&bpo=27057]: Fix os.set_inheritable() on Android, ioctl() is blocked by SELinux and fails with EACCESS. The function now falls back to fcntl(). Patch written by Michał Bednarski.

bpo-27014 [https://bugs.python.org/issue?@action=redirect&bpo=27014]: Fix infinite recursion using typing.py. Thanks to Kalle Tuure!

bpo-27031 [https://bugs.python.org/issue?@action=redirect&bpo=27031]: Removed dummy methods in Tkinter widget classes: tk_menuBar() and tk_bindForTraversal().

bpo-14132 [https://bugs.python.org/issue?@action=redirect&bpo=14132]: Fix urllib.request redirect handling when the target only has a query string. Original fix by Ján Janech.

bpo-17214 [https://bugs.python.org/issue?@action=redirect&bpo=17214]: The “urllib.request” module now percent-encodes non-ASCII bytes found in redirect target URLs. Some servers send Location header fields with non-ASCII bytes, but “http.client” requires the request target to be ASCII-encodable, otherwise a UnicodeEncodeError is raised. Based on patch by Christian Heimes.

bpo-27033 [https://bugs.python.org/issue?@action=redirect&bpo=27033]: The default value of the decode_data parameter for smtpd.SMTPChannel and smtpd.SMTPServer constructors is changed to False.

bpo-27034 [https://bugs.python.org/issue?@action=redirect&bpo=27034]: Removed deprecated class asynchat.fifo.

bpo-26870 [https://bugs.python.org/issue?@action=redirect&bpo=26870]: Added readline.set_auto_history(), which can stop entries being automatically added to the history list. Based on patch by Tyler Crompton.

bpo-26039 [https://bugs.python.org/issue?@action=redirect&bpo=26039]: zipfile.ZipFile.open() can now be used to write data into a ZIP file, as well as for extracting data. Patch by Thomas Kluyver.

bpo-26892 [https://bugs.python.org/issue?@action=redirect&bpo=26892]: Honor debuglevel flag in urllib.request.HTTPHandler. Patch contributed by Chi Hsuan Yen.

bpo-22274 [https://bugs.python.org/issue?@action=redirect&bpo=22274]: In the subprocess module, allow stderr to be redirected to stdout even when stdout is not redirected. Patch by Akira Li.

bpo-26807 [https://bugs.python.org/issue?@action=redirect&bpo=26807]: mock_open ‘files’ no longer error on readline at end of file. Patch from Yolanda Robla.

bpo-25745 [https://bugs.python.org/issue?@action=redirect&bpo=25745]: Fixed leaking a userptr in curses panel destructor.

bpo-26977 [https://bugs.python.org/issue?@action=redirect&bpo=26977]: Removed unnecessary, and ignored, call to sum of squares helper in statistics.pvariance.

bpo-26002 [https://bugs.python.org/issue?@action=redirect&bpo=26002]: Use bisect in statistics.median instead of a linear search. Patch by Upendra Kuma.

bpo-25974 [https://bugs.python.org/issue?@action=redirect&bpo=25974]: Make use of new Decimal.as_integer_ratio() method in statistics module. Patch by Stefan Krah.

bpo-26996 [https://bugs.python.org/issue?@action=redirect&bpo=26996]: Add secrets module as described in PEP 506.

bpo-26881 [https://bugs.python.org/issue?@action=redirect&bpo=26881]: The modulefinder module now supports extended opcode arguments.

bpo-23815 [https://bugs.python.org/issue?@action=redirect&bpo=23815]: Fixed crashes related to directly created instances of types in _tkinter and curses.panel modules.

bpo-17765 [https://bugs.python.org/issue?@action=redirect&bpo=17765]: weakref.ref() no longer silently ignores keyword arguments. Patch by Georg Brandl.

bpo-26873 [https://bugs.python.org/issue?@action=redirect&bpo=26873]: xmlrpc now raises ResponseError on unsupported type tags instead of silently return incorrect result.

bpo-26915 [https://bugs.python.org/issue?@action=redirect&bpo=26915]: The __contains__ methods in the collections ABCs now check for identity before checking equality. This better matches the behavior of the concrete classes, allows sensible handling of NaNs, and makes it easier to reason about container invariants.

bpo-26711 [https://bugs.python.org/issue?@action=redirect&bpo=26711]: Fixed the comparison of plistlib.Data with other types.

bpo-24114 [https://bugs.python.org/issue?@action=redirect&bpo=24114]: Fix an uninitialized variable in ctypes.util.

The bug only occurs on SunOS when the ctypes implementation searches for the crle program. Patch by Xiang Zhang. Tested on SunOS by Kees Bos.

bpo-26864 [https://bugs.python.org/issue?@action=redirect&bpo=26864]: In urllib.request, change the proxy bypass host checking against no_proxy to be case-insensitive, and to not match unrelated host names that happen to have a bypassed hostname as a suffix. Patch by Xiang Zhang.

bpo-24902 [https://bugs.python.org/issue?@action=redirect&bpo=24902]: Print server URL on http.server startup. Initial patch by Felix Kaiser.

bpo-25788 [https://bugs.python.org/issue?@action=redirect&bpo=25788]: fileinput.hook_encoded() now supports an “errors” argument for passing to open. Original patch by Joseph Hackman.

bpo-26634 [https://bugs.python.org/issue?@action=redirect&bpo=26634]: recursive_repr() now sets __qualname__ of wrapper. Patch by Xiang Zhang.

bpo-26804 [https://bugs.python.org/issue?@action=redirect&bpo=26804]: urllib.request will prefer lower_case proxy environment variables over UPPER_CASE or Mixed_Case ones. Patch contributed by Hans-Peter Jansen.

bpo-26837 [https://bugs.python.org/issue?@action=redirect&bpo=26837]: assertSequenceEqual() now correctly outputs non-stringified differing items (like bytes in the -b mode). This affects assertListEqual() and assertTupleEqual().

bpo-26041 [https://bugs.python.org/issue?@action=redirect&bpo=26041]: Remove “will be removed in Python 3.7” from deprecation messages of platform.dist() and platform.linux_distribution(). Patch by Kumaripaba Miyurusara Athukorala.

bpo-26822 [https://bugs.python.org/issue?@action=redirect&bpo=26822]: itemgetter, attrgetter and methodcaller objects no longer silently ignore keyword arguments.

bpo-26733 [https://bugs.python.org/issue?@action=redirect&bpo=26733]: Disassembling a class now disassembles class and static methods. Patch by Xiang Zhang.

bpo-26801 [https://bugs.python.org/issue?@action=redirect&bpo=26801]: Fix error handling in shutil.get_terminal_size(), catch AttributeError instead of NameError. Patch written by Emanuel Barry.

bpo-24838 [https://bugs.python.org/issue?@action=redirect&bpo=24838]: tarfile’s ustar and gnu formats now correctly calculate name and link field limits for multibyte character encodings like utf-8.

Security

bpo-26657 [https://bugs.python.org/issue?@action=redirect&bpo=26657]: Fix directory traversal vulnerability with http.server on Windows. This fixes a regression that was introduced in 3.3.4rc1 and 3.4.0rc1. Based on patch by Philipp Hagemeister.

Library

bpo-26717 [https://bugs.python.org/issue?@action=redirect&bpo=26717]: Stop encoding Latin-1-ized WSGI paths with UTF-8. Patch by Anthony Sottile.

bpo-26782 [https://bugs.python.org/issue?@action=redirect&bpo=26782]: Add STARTUPINFO to subprocess.__all__ on Windows.

bpo-26404 [https://bugs.python.org/issue?@action=redirect&bpo=26404]: Add context manager to socketserver. Patch by Aviv Palivoda.

bpo-26735 [https://bugs.python.org/issue?@action=redirect&bpo=26735]: Fix os.urandom() on Solaris 11.3 and newer when reading more than 1,024 bytes: call getrandom() multiple times with a limit of 1024 bytes per call.

bpo-26585 [https://bugs.python.org/issue?@action=redirect&bpo=26585]: Eliminate http.server._quote_html() and use html.escape(quote=False). Patch by Xiang Zhang.

bpo-26685 [https://bugs.python.org/issue?@action=redirect&bpo=26685]: Raise OSError if closing a socket fails.

bpo-16329 [https://bugs.python.org/issue?@action=redirect&bpo=16329]: Add .webm to mimetypes.types_map. Patch by Giampaolo Rodola’.

bpo-13952 [https://bugs.python.org/issue?@action=redirect&bpo=13952]: Add .csv to mimetypes.types_map. Patch by Geoff Wilson.

bpo-26587 [https://bugs.python.org/issue?@action=redirect&bpo=26587]: the site module now allows .pth files to specify files to be added to sys.path (e.g. zip files).

bpo-25609 [https://bugs.python.org/issue?@action=redirect&bpo=25609]: Introduce contextlib.AbstractContextManager and typing.ContextManager.

bpo-26709 [https://bugs.python.org/issue?@action=redirect&bpo=26709]: Fixed Y2038 problem in loading binary PLists.

bpo-23735 [https://bugs.python.org/issue?@action=redirect&bpo=23735]: Handle terminal resizing with Readline 6.3+ by installing our own SIGWINCH handler. Patch by Eric Price.

bpo-25951 [https://bugs.python.org/issue?@action=redirect&bpo=25951]: Change SSLSocket.sendall() to return None, as explicitly documented for plain socket objects. Patch by Aviv Palivoda.

bpo-26586 [https://bugs.python.org/issue?@action=redirect&bpo=26586]: In http.server, respond with “413 Request header fields too large” if there are too many header fields to parse, rather than killing the connection and raising an unhandled exception. Patch by Xiang Zhang.

bpo-26676 [https://bugs.python.org/issue?@action=redirect&bpo=26676]: Added missing XMLPullParser to ElementTree.__all__.

bpo-22854 [https://bugs.python.org/issue?@action=redirect&bpo=22854]: Change BufferedReader.writable() and BufferedWriter.readable() to always return False.

bpo-26492 [https://bugs.python.org/issue?@action=redirect&bpo=26492]: Exhausted iterator of array.array now conforms with the behavior of iterators of other mutable sequences: it lefts exhausted even if iterated array is extended.

bpo-26641 [https://bugs.python.org/issue?@action=redirect&bpo=26641]: doctest.DocFileTest and doctest.testfile() now support packages (module splitted into multiple directories) for the package parameter.

bpo-25195 [https://bugs.python.org/issue?@action=redirect&bpo=25195]: Fix a regression in mock.MagicMock. _Call is a subclass of tuple (changeset 3603bae63c13 only works for classes) so we need to implement __ne__ ourselves. Patch by Andrew Plummer.

bpo-26644 [https://bugs.python.org/issue?@action=redirect&bpo=26644]: Raise ValueError rather than SystemError when a negative length is passed to SSLSocket.recv() or read().

bpo-23804 [https://bugs.python.org/issue?@action=redirect&bpo=23804]: Fix SSL recv(0) and read(0) methods to return zero bytes instead of up to 1024.

bpo-26616 [https://bugs.python.org/issue?@action=redirect&bpo=26616]: Fixed a bug in datetime.astimezone() method.

bpo-26637 [https://bugs.python.org/issue?@action=redirect&bpo=26637]: The importlib module now emits an ImportError rather than a TypeError if __import__() is tried during the Python shutdown process but sys.path is already cleared (set to None).

bpo-21925 [https://bugs.python.org/issue?@action=redirect&bpo=21925]: warnings.formatwarning() now catches exceptions when calling linecache.getline() and tracemalloc.get_object_traceback() to be able to log ResourceWarning emitted late during the Python shutdown process.

bpo-23848 [https://bugs.python.org/issue?@action=redirect&bpo=23848]: On Windows, faulthandler.enable() now also installs an exception handler to dump the traceback of all Python threads on any Windows exception, not only on UNIX signals (SIGSEGV, SIGFPE, SIGABRT).

bpo-26530 [https://bugs.python.org/issue?@action=redirect&bpo=26530]: Add C functions _PyTraceMalloc_Track() and _PyTraceMalloc_Untrack() to track memory blocks using the tracemalloc module. Add _PyTraceMalloc_GetTraceback() to get the traceback of an object.

bpo-26588 [https://bugs.python.org/issue?@action=redirect&bpo=26588]: The _tracemalloc now supports tracing memory allocations of multiple address spaces (domains).

bpo-24266 [https://bugs.python.org/issue?@action=redirect&bpo=24266]: Ctrl+C during Readline history search now cancels the search mode when compiled with Readline 7.

bpo-26590 [https://bugs.python.org/issue?@action=redirect&bpo=26590]: Implement a safe finalizer for the _socket.socket type. It now releases the GIL to close the socket.

bpo-18787 [https://bugs.python.org/issue?@action=redirect&bpo=18787]: spwd.getspnam() now raises a PermissionError if the user doesn’t have privileges.

bpo-26560 [https://bugs.python.org/issue?@action=redirect&bpo=26560]: Avoid potential ValueError in BaseHandler.start_response. Initial patch by Peter Inglesby.

bpo-26567 [https://bugs.python.org/issue?@action=redirect&bpo=26567]: Add a new function PyErr_ResourceWarning() function to pass the destroyed object. Add a source attribute to warnings.WarningMessage. Add warnings._showwarnmsg() which uses tracemalloc to get the traceback where source object was allocated.

Security

bpo-26313 [https://bugs.python.org/issue?@action=redirect&bpo=26313]: ssl.py _load_windows_store_certs fails if windows cert store is empty. Patch by Baji.

Library

bpo-26569 [https://bugs.python.org/issue?@action=redirect&bpo=26569]: Fix pyclbr.readmodule() and pyclbr.readmodule_ex() to support importing packages.

bpo-26499 [https://bugs.python.org/issue?@action=redirect&bpo=26499]: Account for remaining Content-Length in HTTPResponse.readline() and read1(). Based on patch by Silent Ghost. Also document that HTTPResponse now supports these methods.

bpo-25320 [https://bugs.python.org/issue?@action=redirect&bpo=25320]: Handle sockets in directories unittest discovery is scanning. Patch from Victor van den Elzen.

bpo-16181 [https://bugs.python.org/issue?@action=redirect&bpo=16181]: cookiejar.http2time() now returns None if year is higher than datetime.MAXYEAR.

bpo-26513 [https://bugs.python.org/issue?@action=redirect&bpo=26513]: Fixes platform module detection of Windows Server

bpo-23718 [https://bugs.python.org/issue?@action=redirect&bpo=23718]: Fixed parsing time in week 0 before Jan 1. Original patch by Tamás Bence Gedai.

bpo-26323 [https://bugs.python.org/issue?@action=redirect&bpo=26323]: Add Mock.assert_called() and Mock.assert_called_once() methods to unittest.mock. Patch written by Amit Saha.

bpo-20589 [https://bugs.python.org/issue?@action=redirect&bpo=20589]: Invoking Path.owner() and Path.group() on Windows now raise NotImplementedError instead of ImportError.

bpo-26177 [https://bugs.python.org/issue?@action=redirect&bpo=26177]: Fixed the keys() method for Canvas and Scrollbar widgets.

bpo-15068 [https://bugs.python.org/issue?@action=redirect&bpo=15068]: Got rid of excessive buffering in fileinput. The bufsize parameter is now deprecated and ignored.

bpo-19475 [https://bugs.python.org/issue?@action=redirect&bpo=19475]: Added an optional argument timespec to the datetime isoformat() method to choose the precision of the time component.

bpo-2202 [https://bugs.python.org/issue?@action=redirect&bpo=2202]: Fix UnboundLocalError in AbstractDigestAuthHandler.get_algorithm_impls. Initial patch by Mathieu Dupuy.

bpo-26167 [https://bugs.python.org/issue?@action=redirect&bpo=26167]: Minimized overhead in copy.copy() and copy.deepcopy(). Optimized copying and deepcopying bytearrays, NotImplemented, slices, short lists, tuples, dicts, sets.

bpo-25718 [https://bugs.python.org/issue?@action=redirect&bpo=25718]: Fixed pickling and copying the accumulate() iterator with total is None.

bpo-26475 [https://bugs.python.org/issue?@action=redirect&bpo=26475]: Fixed debugging output for regular expressions with the (?x) flag.

bpo-26482 [https://bugs.python.org/issue?@action=redirect&bpo=26482]: Allowed pickling recursive dequeues.

bpo-26335 [https://bugs.python.org/issue?@action=redirect&bpo=26335]: Make mmap.write() return the number of bytes written like other write methods. Patch by Jakub Stasiak.

bpo-26457 [https://bugs.python.org/issue?@action=redirect&bpo=26457]: Fixed the subnets() methods in IP network classes for the case when resulting prefix length is equal to maximal prefix length. Based on patch by Xiang Zhang.

bpo-26385 [https://bugs.python.org/issue?@action=redirect&bpo=26385]: Remove the file if the internal open() call in NamedTemporaryFile() fails. Patch by Silent Ghost.

bpo-26402 [https://bugs.python.org/issue?@action=redirect&bpo=26402]: Fix XML-RPC client to retry when the server shuts down a persistent connection. This was a regression related to the new http.client.RemoteDisconnected exception in 3.5.0a4.

bpo-25913 [https://bugs.python.org/issue?@action=redirect&bpo=25913]: Leading <~ is optional now in base64.a85decode() with adobe=True. Patch by Swati Jaiswal.

bpo-26186 [https://bugs.python.org/issue?@action=redirect&bpo=26186]: Remove an invalid type check in importlib.util.LazyLoader.

bpo-26367 [https://bugs.python.org/issue?@action=redirect&bpo=26367]: importlib.__import__() raises ImportError like builtins.__import__() when level is specified but without an accompanying package specified.

bpo-26309 [https://bugs.python.org/issue?@action=redirect&bpo=26309]: In the “socketserver” module, shut down the request (closing the connected socket) when verify_request() returns false. Patch by Aviv Palivoda.

bpo-23430 [https://bugs.python.org/issue?@action=redirect&bpo=23430]: Change the socketserver module to only catch exceptions raised from a request handler that are derived from Exception (instead of BaseException). Therefore SystemExit and KeyboardInterrupt no longer trigger the handle_error() method, and will now to stop a single-threaded server.

Security

bpo-25939 [https://bugs.python.org/issue?@action=redirect&bpo=25939]: On Windows open the cert store readonly in ssl.enum_certificates.

Library

bpo-25995 [https://bugs.python.org/issue?@action=redirect&bpo=25995]: os.walk() no longer uses FDs proportional to the tree depth.

bpo-25994 [https://bugs.python.org/issue?@action=redirect&bpo=25994]: Added the close() method and the support of the context manager protocol for the os.scandir() iterator.

bpo-23992 [https://bugs.python.org/issue?@action=redirect&bpo=23992]: multiprocessing: make MapResult not fail-fast upon exception.

bpo-26243 [https://bugs.python.org/issue?@action=redirect&bpo=26243]: Support keyword arguments to zlib.compress(). Patch by Aviv Palivoda.

bpo-26117 [https://bugs.python.org/issue?@action=redirect&bpo=26117]: The os.scandir() iterator now closes file descriptor not only when the iteration is finished, but when it was failed with error.

bpo-25949 [https://bugs.python.org/issue?@action=redirect&bpo=25949]: __dict__ for an OrderedDict instance is now created only when needed.

bpo-25911 [https://bugs.python.org/issue?@action=redirect&bpo=25911]: Restored support of bytes paths in os.walk() on Windows.

bpo-26045 [https://bugs.python.org/issue?@action=redirect&bpo=26045]: Add UTF-8 suggestion to error message when posting a non-Latin-1 string with http.client.

bpo-26039 [https://bugs.python.org/issue?@action=redirect&bpo=26039]: Added zipfile.ZipInfo.from_file() and zipinfo.ZipInfo.is_dir(). Patch by Thomas Kluyver.

bpo-12923 [https://bugs.python.org/issue?@action=redirect&bpo=12923]: Reset FancyURLopener’s redirect counter even if there is an exception. Based on patches by Brian Brazil and Daniel Rocco.

bpo-25945 [https://bugs.python.org/issue?@action=redirect&bpo=25945]: Fixed a crash when unpickle the functools.partial object with wrong state. Fixed a leak in failed functools.partial constructor. “args” and “keywords” attributes of functools.partial have now always types tuple and dict correspondingly.

bpo-26202 [https://bugs.python.org/issue?@action=redirect&bpo=26202]: copy.deepcopy() now correctly copies range() objects with non-atomic attributes.

bpo-23076 [https://bugs.python.org/issue?@action=redirect&bpo=23076]: Path.glob() now raises a ValueError if it’s called with an invalid pattern. Patch by Thomas Nyberg.

bpo-19883 [https://bugs.python.org/issue?@action=redirect&bpo=19883]: Fixed possible integer overflows in zipimport.

bpo-26227 [https://bugs.python.org/issue?@action=redirect&bpo=26227]: On Windows, getnameinfo(), gethostbyaddr() and gethostbyname_ex() functions of the socket module now decode the hostname from the ANSI code page rather than UTF-8.

bpo-26099 [https://bugs.python.org/issue?@action=redirect&bpo=26099]: The site module now writes an error into stderr if sitecustomize module can be imported but executing the module raise an ImportError. Same change for usercustomize.

bpo-26147 [https://bugs.python.org/issue?@action=redirect&bpo=26147]: xmlrpc now works with strings not encodable with used non-UTF-8 encoding.

bpo-25935 [https://bugs.python.org/issue?@action=redirect&bpo=25935]: Garbage collector now breaks reference loops with OrderedDict.

bpo-16620 [https://bugs.python.org/issue?@action=redirect&bpo=16620]: Fixed AttributeError in msilib.Directory.glob().

bpo-26013 [https://bugs.python.org/issue?@action=redirect&bpo=26013]: Added compatibility with broken protocol 2 pickles created in old Python 3 versions (3.4.3 and lower).

bpo-26129 [https://bugs.python.org/issue?@action=redirect&bpo=26129]: Deprecated accepting non-integers in grp.getgrgid().

bpo-25850 [https://bugs.python.org/issue?@action=redirect&bpo=25850]: Use cross-compilation by default for 64-bit Windows.

bpo-25822 [https://bugs.python.org/issue?@action=redirect&bpo=25822]: Add docstrings to the fields of urllib.parse results. Patch contributed by Swati Jaiswal.

bpo-22642 [https://bugs.python.org/issue?@action=redirect&bpo=22642]: Convert trace module option parsing mechanism to argparse. Patch contributed by SilentGhost.

bpo-24705 [https://bugs.python.org/issue?@action=redirect&bpo=24705]: Fix sysconfig._parse_makefile not expanding ${} vars appearing before $() vars.

bpo-26069 [https://bugs.python.org/issue?@action=redirect&bpo=26069]: Remove the deprecated apis in the trace module.

bpo-22138 [https://bugs.python.org/issue?@action=redirect&bpo=22138]: Fix mock.patch behavior when patching descriptors. Restore original values after patching. Patch contributed by Sean McCully.

bpo-25672 [https://bugs.python.org/issue?@action=redirect&bpo=25672]: In the ssl module, enable the SSL_MODE_RELEASE_BUFFERS mode option if it is safe to do so.

bpo-26012 [https://bugs.python.org/issue?@action=redirect&bpo=26012]: Don’t traverse into symlinks for ** pattern in pathlib.Path.[r]glob().

bpo-24120 [https://bugs.python.org/issue?@action=redirect&bpo=24120]: Ignore PermissionError when traversing a tree with pathlib.Path.[r]glob(). Patch by Ulrich Petri.

bpo-21815 [https://bugs.python.org/issue?@action=redirect&bpo=21815]: Accept ] characters in the data portion of imap responses, in order to handle the flags with square brackets accepted and produced by servers such as gmail.

bpo-25447 [https://bugs.python.org/issue?@action=redirect&bpo=25447]: fileinput now uses sys.stdin as-is if it does not have a buffer attribute (restores backward compatibility).

bpo-25971 [https://bugs.python.org/issue?@action=redirect&bpo=25971]: Optimized creating Fractions from floats by 2 times and from Decimals by 3 times.

bpo-25802 [https://bugs.python.org/issue?@action=redirect&bpo=25802]: Document as deprecated the remaining implementations of importlib.abc.Loader.load_module().

bpo-25928 [https://bugs.python.org/issue?@action=redirect&bpo=25928]: Add Decimal.as_integer_ratio().

bpo-25447 [https://bugs.python.org/issue?@action=redirect&bpo=25447]: Copying the lru_cache() wrapper object now always works, independently from the type of the wrapped object (by returning the original object unchanged).

bpo-25768 [https://bugs.python.org/issue?@action=redirect&bpo=25768]: Have the functions in compileall return booleans instead of ints and add proper documentation and tests for the return values.

bpo-24103 [https://bugs.python.org/issue?@action=redirect&bpo=24103]: Fixed possible use after free in ElementTree.XMLPullParser.

bpo-25860 [https://bugs.python.org/issue?@action=redirect&bpo=25860]: os.fwalk() no longer skips remaining directories when error occurs. Original patch by Samson Lee.

bpo-25914 [https://bugs.python.org/issue?@action=redirect&bpo=25914]: Fixed and simplified OrderedDict.__sizeof__.

bpo-25869 [https://bugs.python.org/issue?@action=redirect&bpo=25869]: Optimized deepcopying ElementTree; it is now 20 times faster.

bpo-25873 [https://bugs.python.org/issue?@action=redirect&bpo=25873]: Optimized iterating ElementTree. Iterating elements Element.iter() is now 40% faster, iterating text Element.itertext() is now up to 2.5 times faster.

bpo-25902 [https://bugs.python.org/issue?@action=redirect&bpo=25902]: Fixed various refcount issues in ElementTree iteration.

bpo-22227 [https://bugs.python.org/issue?@action=redirect&bpo=22227]: The TarFile iterator is reimplemented using generator. This implementation is simpler that using class.

bpo-25638 [https://bugs.python.org/issue?@action=redirect&bpo=25638]: Optimized ElementTree.iterparse(); it is now 2x faster. Optimized ElementTree parsing; it is now 10% faster.

bpo-25761 [https://bugs.python.org/issue?@action=redirect&bpo=25761]: Improved detecting errors in broken pickle data.

bpo-25717 [https://bugs.python.org/issue?@action=redirect&bpo=25717]: Restore the previous behaviour of tolerating most fstat() errors when opening files. This was a regression in 3.5a1, and stopped anonymous temporary files from working in special cases.

bpo-24903 [https://bugs.python.org/issue?@action=redirect&bpo=24903]: Fix regression in number of arguments compileall accepts when ‘-d’ is specified. The check on the number of arguments has been dropped completely as it never worked correctly anyway.

bpo-25764 [https://bugs.python.org/issue?@action=redirect&bpo=25764]: In the subprocess module, preserve any exception caused by fork() failure when preexec_fn is used.

bpo-25771 [https://bugs.python.org/issue?@action=redirect&bpo=25771]: Tweak the exception message for importlib.util.resolve_name() when ‘package’ isn’t specified but necessary.

bpo-6478 [https://bugs.python.org/issue?@action=redirect&bpo=6478]: _strptime’s regexp cache now is reset after changing timezone with time.tzset().

bpo-14285 [https://bugs.python.org/issue?@action=redirect&bpo=14285]: When executing a package with the “python -m package” option, and package initialization fails, a proper traceback is now reported. The “runpy” module now lets exceptions from package initialization pass back to the caller, rather than raising ImportError.

bpo-19771 [https://bugs.python.org/issue?@action=redirect&bpo=19771]: Also in runpy and the “-m” option, omit the irrelevant message “… is a package and cannot be directly executed” if the package could not even be initialized (e.g. due to a bad *.pyc file).

bpo-25177 [https://bugs.python.org/issue?@action=redirect&bpo=25177]: Fixed problem with the mean of very small and very large numbers. As a side effect, statistics.mean and statistics.variance should be significantly faster.

bpo-25718 [https://bugs.python.org/issue?@action=redirect&bpo=25718]: Fixed copying object with state with boolean value is false.

bpo-10131 [https://bugs.python.org/issue?@action=redirect&bpo=10131]: Fixed deep copying of minidom documents. Based on patch by Marian Ganisin.

bpo-7990 [https://bugs.python.org/issue?@action=redirect&bpo=7990]: dir() on ElementTree.Element now lists properties: “tag”, “text”, “tail” and “attrib”. Original patch by Santoso Wijaya.

bpo-25725 [https://bugs.python.org/issue?@action=redirect&bpo=25725]: Fixed a reference leak in pickle.loads() when unpickling invalid data including tuple instructions.

bpo-25663 [https://bugs.python.org/issue?@action=redirect&bpo=25663]: In the Readline completer, avoid listing duplicate global names, and search the global namespace before searching builtins.

bpo-25688 [https://bugs.python.org/issue?@action=redirect&bpo=25688]: Fixed file leak in ElementTree.iterparse() raising an error.

bpo-23914 [https://bugs.python.org/issue?@action=redirect&bpo=23914]: Fixed SystemError raised by unpickler on broken pickle data.

bpo-25691 [https://bugs.python.org/issue?@action=redirect&bpo=25691]: Fixed crash on deleting ElementTree.Element attributes.

bpo-25624 [https://bugs.python.org/issue?@action=redirect&bpo=25624]: ZipFile now always writes a ZIP_STORED header for directory entries. Patch by Dingyuan Wang.

bpo-25626 [https://bugs.python.org/issue?@action=redirect&bpo=25626]: Change three zlib functions to accept sizes that fit in Py_ssize_t, but internally cap those sizes to UINT_MAX. This resolves a regression in 3.5 where GzipFile.read() failed to read chunks larger than 2 or 4 GiB. The change affects the zlib.Decompress.decompress() max_length parameter, the zlib.decompress() bufsize parameter, and the zlib.Decompress.flush() length parameter.

bpo-25583 [https://bugs.python.org/issue?@action=redirect&bpo=25583]: Avoid incorrect errors raised by os.makedirs(exist_ok=True) when the OS gives priority to errors such as EACCES over EEXIST.

bpo-25593 [https://bugs.python.org/issue?@action=redirect&bpo=25593]: Change semantics of EventLoop.stop() in asyncio.

bpo-6973 [https://bugs.python.org/issue?@action=redirect&bpo=6973]: When we know a subprocess.Popen process has died, do not allow the send_signal(), terminate(), or kill() methods to do anything as they could potentially signal a different process.

bpo-23883 [https://bugs.python.org/issue?@action=redirect&bpo=23883]: Added missing APIs to __all__ to match the documented APIs for the following modules: calendar, csv, enum, fileinput, ftplib, logging, optparse, tarfile, threading and wave. Also added a test.support.check__all__() helper. Patches by Jacek Kołodziej, Mauro S. M. Rodrigues and Joel Taddei.

bpo-25590 [https://bugs.python.org/issue?@action=redirect&bpo=25590]: In the Readline completer, only call getattr() once per attribute. Also complete names of attributes such as properties and slots which are listed by dir() but not yet created on an instance.

bpo-25498 [https://bugs.python.org/issue?@action=redirect&bpo=25498]: Fix a crash when garbage-collecting ctypes objects created by wrapping a memoryview. This was a regression made in 3.5a1. Based on patch by Eryksun.

bpo-25584 [https://bugs.python.org/issue?@action=redirect&bpo=25584]: Added “escape” to the __all__ list in the glob module.

bpo-25584 [https://bugs.python.org/issue?@action=redirect&bpo=25584]: Fixed recursive glob() with patterns starting with **.

bpo-25446 [https://bugs.python.org/issue?@action=redirect&bpo=25446]: Fix regression in smtplib’s AUTH LOGIN support.

bpo-18010 [https://bugs.python.org/issue?@action=redirect&bpo=18010]: Fix the pydoc web server’s module search function to handle exceptions from importing packages.

bpo-25554 [https://bugs.python.org/issue?@action=redirect&bpo=25554]: Got rid of circular references in regular expression parsing.

bpo-18973 [https://bugs.python.org/issue?@action=redirect&bpo=18973]: Command-line interface of the calendar module now uses argparse instead of optparse.

bpo-25510 [https://bugs.python.org/issue?@action=redirect&bpo=25510]: fileinput.FileInput.readline() now returns b’’ instead of ‘’ at the end if the FileInput was opened with binary mode. Patch by Ryosuke Ito.

bpo-25503 [https://bugs.python.org/issue?@action=redirect&bpo=25503]: Fixed inspect.getdoc() for inherited docstrings of properties. Original patch by John Mark Vandenberg.

bpo-25515 [https://bugs.python.org/issue?@action=redirect&bpo=25515]: Always use os.urandom as a source of randomness in uuid.uuid4.

bpo-21827 [https://bugs.python.org/issue?@action=redirect&bpo=21827]: Fixed textwrap.dedent() for the case when largest common whitespace is a substring of smallest leading whitespace. Based on patch by Robert Li.

bpo-25447 [https://bugs.python.org/issue?@action=redirect&bpo=25447]: The lru_cache() wrapper objects now can be copied and pickled (by returning the original object unchanged).

bpo-25390 [https://bugs.python.org/issue?@action=redirect&bpo=25390]: typing: Don’t crash on Union[str, Pattern].

bpo-25441 [https://bugs.python.org/issue?@action=redirect&bpo=25441]: asyncio: Raise error from drain() when socket is closed.

bpo-25410 [https://bugs.python.org/issue?@action=redirect&bpo=25410]: Cleaned up and fixed minor bugs in C implementation of OrderedDict.

bpo-25411 [https://bugs.python.org/issue?@action=redirect&bpo=25411]: Improved Unicode support in SMTPHandler through better use of the email package. Thanks to user simon04 for the patch.

Move the imp module from a PendingDeprecationWarning to DeprecationWarning.

bpo-25407 [https://bugs.python.org/issue?@action=redirect&bpo=25407]: Remove mentions of the formatter module being removed in Python 3.6.

bpo-25406 [https://bugs.python.org/issue?@action=redirect&bpo=25406]: Fixed a bug in C implementation of OrderedDict.move_to_end() that caused segmentation fault or hang in iterating after moving several items to the start of ordered dict.

bpo-25382 [https://bugs.python.org/issue?@action=redirect&bpo=25382]: pickletools.dis() now outputs implicit memo index for the MEMOIZE opcode.

bpo-25357 [https://bugs.python.org/issue?@action=redirect&bpo=25357]: Add an optional newline parameter to binascii.b2a_base64(). base64.b64encode() uses it to avoid a memory copy.

bpo-24164 [https://bugs.python.org/issue?@action=redirect&bpo=24164]: Objects that need calling __new__ with keyword arguments, can now be pickled using pickle protocols older than protocol version 4.

bpo-25364 [https://bugs.python.org/issue?@action=redirect&bpo=25364]: zipfile now works in threads disabled builds.

bpo-25328 [https://bugs.python.org/issue?@action=redirect&bpo=25328]: smtpd’s SMTPChannel now correctly raises a ValueError if both decode_data and enable_SMTPUTF8 are set to true.

bpo-16099 [https://bugs.python.org/issue?@action=redirect&bpo=16099]: RobotFileParser now supports Crawl-delay and Request-rate extensions. Patch by Nikolay Bogoychev.

bpo-25316 [https://bugs.python.org/issue?@action=redirect&bpo=25316]: distutils raises OSError instead of DistutilsPlatformError when MSVC is not installed.

bpo-25380 [https://bugs.python.org/issue?@action=redirect&bpo=25380]: Fixed protocol for the STACK_GLOBAL opcode in pickletools.opcodes.

bpo-23972 [https://bugs.python.org/issue?@action=redirect&bpo=23972]: Updates asyncio datagram create method allowing reuseport and reuseaddr socket options to be set prior to binding the socket. Mirroring the existing asyncio create_server method the reuseaddr option for datagram sockets defaults to True if the O/S is ‘posix’ (except if the platform is Cygwin). Patch by Chris Laws.

bpo-25304 [https://bugs.python.org/issue?@action=redirect&bpo=25304]: Add asyncio.run_coroutine_threadsafe(). This lets you submit a coroutine to a loop from another thread, returning a concurrent.futures.Future. By Vincent Michel.

bpo-25232 [https://bugs.python.org/issue?@action=redirect&bpo=25232]: Fix CGIRequestHandler to split the query from the URL at the first question mark (?) rather than the last. Patch from Xiang Zhang.

bpo-24657 [https://bugs.python.org/issue?@action=redirect&bpo=24657]: Prevent CGIRequestHandler from collapsing slashes in the query part of the URL as if it were a path. Patch from Xiang Zhang.

bpo-25287 [https://bugs.python.org/issue?@action=redirect&bpo=25287]: Don’t add crypt.METHOD_CRYPT to crypt.methods if it’s not supported. Check if it is supported, it may not be supported on OpenBSD for example.

bpo-23600 [https://bugs.python.org/issue?@action=redirect&bpo=23600]: Default implementation of tzinfo.fromutc() was returning wrong results in some cases.

bpo-25203 [https://bugs.python.org/issue?@action=redirect&bpo=25203]: Failed readline.set_completer_delims() no longer left the module in inconsistent state.

bpo-25011 [https://bugs.python.org/issue?@action=redirect&bpo=25011]: rlcompleter now omits private and special attribute names unless the prefix starts with underscores.

bpo-25209 [https://bugs.python.org/issue?@action=redirect&bpo=25209]: rlcompleter now can add a space or a colon after completed keyword.

bpo-22241 [https://bugs.python.org/issue?@action=redirect&bpo=22241]: timezone.utc name is now plain ‘UTC’, not ‘UTC-00:00’.

bpo-23517 [https://bugs.python.org/issue?@action=redirect&bpo=23517]: fromtimestamp() and utcfromtimestamp() methods of datetime.datetime now round microseconds to nearest with ties going to nearest even integer (ROUND_HALF_EVEN), as round(float), instead of rounding towards -Infinity (ROUND_FLOOR).

bpo-23552 [https://bugs.python.org/issue?@action=redirect&bpo=23552]: Timeit now warns when there is substantial (4x) variance between best and worst times. Patch from Serhiy Storchaka.

bpo-24633 [https://bugs.python.org/issue?@action=redirect&bpo=24633]: site-packages/README -> README.txt.

bpo-24879 [https://bugs.python.org/issue?@action=redirect&bpo=24879]: help() and pydoc can now list named tuple fields in the order they were defined rather than alphabetically. The ordering is determined by the _fields attribute if present.

bpo-24874 [https://bugs.python.org/issue?@action=redirect&bpo=24874]: Improve speed of itertools.cycle() and make its pickle more compact.

Fix crash in itertools.cycle.__setstate__() when the first argument wasn’t a list.

bpo-20059 [https://bugs.python.org/issue?@action=redirect&bpo=20059]: urllib.parse raises ValueError on all invalid ports. Patch by Martin Panter.

bpo-24360 [https://bugs.python.org/issue?@action=redirect&bpo=24360]: Improve __repr__ of argparse.Namespace() for invalid identifiers. Patch by Matthias Bussonnier.

bpo-23426 [https://bugs.python.org/issue?@action=redirect&bpo=23426]: run_setup was broken in distutils. Patch from Alexander Belopolsky.

bpo-13938 [https://bugs.python.org/issue?@action=redirect&bpo=13938]: 2to3 converts StringTypes to a tuple. Patch from Mark Hammond.

bpo-2091 [https://bugs.python.org/issue?@action=redirect&bpo=2091]: open() accepted a ‘U’ mode string containing ‘+’, but ‘U’ can only be used with ‘r’. Patch from Jeff Balogh and John O’Connor.

bpo-8585 [https://bugs.python.org/issue?@action=redirect&bpo=8585]: improved tests for zipimporter2. Patch from Mark Lawrence.

bpo-18622 [https://bugs.python.org/issue?@action=redirect&bpo=18622]: unittest.mock.mock_open().reset_mock would recurse infinitely. Patch from Nicola Palumbo and Laurent De Buyst.

bpo-24426 [https://bugs.python.org/issue?@action=redirect&bpo=24426]: Fast searching optimization in regular expressions now works for patterns that starts with capturing groups. Fast searching optimization now can’t be disabled at compile time.

bpo-23661 [https://bugs.python.org/issue?@action=redirect&bpo=23661]: unittest.mock side_effects can now be exceptions again. This was a regression vs Python 3.4. Patch from Ignacio Rossi

bpo-13248 [https://bugs.python.org/issue?@action=redirect&bpo=13248]: Remove deprecated inspect.getmoduleinfo function.

bpo-25578 [https://bugs.python.org/issue?@action=redirect&bpo=25578]: Fix (another) memory leak in SSLSocket.getpeercer().

bpo-25530 [https://bugs.python.org/issue?@action=redirect&bpo=25530]: Disable the vulnerable SSLv3 protocol by default when creating ssl.SSLContext.

bpo-25569 [https://bugs.python.org/issue?@action=redirect&bpo=25569]: Fix memory leak in SSLSocket.getpeercert().

bpo-25471 [https://bugs.python.org/issue?@action=redirect&bpo=25471]: Sockets returned from accept() shouldn’t appear to be nonblocking.

bpo-25319 [https://bugs.python.org/issue?@action=redirect&bpo=25319]: When threading.Event is reinitialized, the underlying condition should use a regular lock rather than a recursive lock.

Skip getaddrinfo if host is already resolved. Patch by A. Jesse Jiryu Davis.

bpo-26050 [https://bugs.python.org/issue?@action=redirect&bpo=26050]: Add asyncio.StreamReader.readuntil() method. Patch by Марк Коренберг.

bpo-25924 [https://bugs.python.org/issue?@action=redirect&bpo=25924]: Avoid unnecessary serialization of getaddrinfo(3) calls on OS X versions 10.5 or higher. Original patch by A. Jesse Jiryu Davis.

bpo-26406 [https://bugs.python.org/issue?@action=redirect&bpo=26406]: Avoid unnecessary serialization of getaddrinfo(3) calls on current versions of OpenBSD and NetBSD. Patch by A. Jesse Jiryu Davis.

bpo-26848 [https://bugs.python.org/issue?@action=redirect&bpo=26848]: Fix asyncio/subprocess.communicate() to handle empty input. Patch by Jack O’Connor.

bpo-27040 [https://bugs.python.org/issue?@action=redirect&bpo=27040]: Add loop.get_exception_handler method

bpo-27041 [https://bugs.python.org/issue?@action=redirect&bpo=27041]: asyncio: Add loop.create_future method

IDLE

bpo-20640 [https://bugs.python.org/issue?@action=redirect&bpo=20640]: Add tests for idlelib.configHelpSourceEdit. Patch by Saimadhav Heblikar.

In the ‘IDLE-console differences’ section of the IDLE doc, clarify how running with IDLE affects sys.modules and the standard streams.

bpo-25507 [https://bugs.python.org/issue?@action=redirect&bpo=25507]: fix incorrect change in IOBinding that prevented printing. Augment IOBinding htest to include all major IOBinding functions.

bpo-25905 [https://bugs.python.org/issue?@action=redirect&bpo=25905]: Revert unwanted conversion of ‘ to ’ RIGHT SINGLE QUOTATION MARK in README.txt and open this and NEWS.txt with ‘ascii’. Re-encode CREDITS.txt to utf-8 and open it with ‘utf-8’.

bpo-15348 [https://bugs.python.org/issue?@action=redirect&bpo=15348]: Stop the debugger engine (normally in a user process) before closing the debugger window (running in the IDLE process). This prevents the RuntimeErrors that were being caught and ignored.

bpo-24455 [https://bugs.python.org/issue?@action=redirect&bpo=24455]: Prevent IDLE from hanging when a) closing the shell while the debugger is active (15347); b) closing the debugger with the [X] button (15348); and c) activating the debugger when already active (24455). The patch by Mark Roseman does this by making two changes. 1. Suspend and resume the gui.interaction method with the tcl vwait mechanism intended for this purpose (instead of root.mainloop & .quit). 2. In gui.run, allow any existing interaction to terminate first.

Change ‘The program’ to ‘Your program’ in an IDLE ‘kill program?’ message to make it clearer that the program referred to is the currently running user program, not IDLE itself.

bpo-24750 [https://bugs.python.org/issue?@action=redirect&bpo=24750]: Improve the appearance of the IDLE editor window status bar. Patch by Mark Roseman.

bpo-25313 [https://bugs.python.org/issue?@action=redirect&bpo=25313]: Change the handling of new built-in text color themes to better address the compatibility problem introduced by the addition of IDLE Dark. Consistently use the revised idleConf.CurrentTheme everywhere in idlelib.

bpo-24782 [https://bugs.python.org/issue?@action=redirect&bpo=24782]: Extension configuration is now a tab in the IDLE Preferences dialog rather than a separate dialog. The former tabs are now a sorted list. Patch by Mark Roseman.

bpo-22726 [https://bugs.python.org/issue?@action=redirect&bpo=22726]: Re-activate the config dialog help button with some content about the other buttons and the new IDLE Dark theme.

bpo-24820 [https://bugs.python.org/issue?@action=redirect&bpo=24820]: IDLE now has an ‘IDLE Dark’ built-in text color theme. It is more or less IDLE Classic inverted, with a cobalt blue background. Strings, comments, keywords, … are still green, red, orange, … . To use it with IDLEs released before November 2015, hit the ‘Save as New Custom Theme’ button and enter a new name, such as ‘Custom Dark’. The custom theme will work with any IDLE release, and can be modified.

bpo-25224 [https://bugs.python.org/issue?@action=redirect&bpo=25224]: README.txt is now an idlelib index for IDLE developers and curious users. The previous user content is now in the IDLE doc chapter. ‘IDLE’ now means ‘Integrated Development and Learning Environment’.

bpo-24820 [https://bugs.python.org/issue?@action=redirect&bpo=24820]: Users can now set breakpoint colors in Settings -> Custom Highlighting. Original patch by Mark Roseman.

bpo-24972 [https://bugs.python.org/issue?@action=redirect&bpo=24972]: Inactive selection background now matches active selection background, as configured by users, on all systems. Found items are now always highlighted on Windows. Initial patch by Mark Roseman.

bpo-24570 [https://bugs.python.org/issue?@action=redirect&bpo=24570]: Idle: make calltip and completion boxes appear on Macs affected by a tk regression. Initial patch by Mark Roseman.

bpo-24988 [https://bugs.python.org/issue?@action=redirect&bpo=24988]: Idle ScrolledList context menus (used in debugger) now work on Mac Aqua. Patch by Mark Roseman.

bpo-24801 [https://bugs.python.org/issue?@action=redirect&bpo=24801]: Make right-click for context menu work on Mac Aqua. Patch by Mark Roseman.

bpo-25173 [https://bugs.python.org/issue?@action=redirect&bpo=25173]: Associate tkinter messageboxes with a specific widget. For Mac OSX, make them a ‘sheet’. Patch by Mark Roseman.

bpo-25198 [https://bugs.python.org/issue?@action=redirect&bpo=25198]: Enhance the initial html viewer now used for Idle Help. Properly indent fixed-pitch text (patch by Mark Roseman). Give code snippet a very Sphinx-like light blueish-gray background. Re-use initial width and height set by users for shell and editor. When the Table of Contents (TOC) menu is used, put the section header at the top of the screen.

bpo-25225 [https://bugs.python.org/issue?@action=redirect&bpo=25225]: Condense and rewrite Idle doc section on text colors.

bpo-21995 [https://bugs.python.org/issue?@action=redirect&bpo=21995]: Explain some differences between IDLE and console Python.

bpo-22820 [https://bugs.python.org/issue?@action=redirect&bpo=22820]: Explain need for print when running file from Idle editor.

bpo-25224 [https://bugs.python.org/issue?@action=redirect&bpo=25224]: Doc: augment Idle feature list and no-subprocess section.

bpo-25219 [https://bugs.python.org/issue?@action=redirect&bpo=25219]: Update doc for Idle command line options. Some were missing and notes were not correct.

bpo-24861 [https://bugs.python.org/issue?@action=redirect&bpo=24861]: Most of idlelib is private and subject to change. Use idleib.idle.* to start Idle. See idlelib.__init__.__doc__.

bpo-25199 [https://bugs.python.org/issue?@action=redirect&bpo=25199]: Idle: add synchronization comments for future maintainers.

bpo-16893 [https://bugs.python.org/issue?@action=redirect&bpo=16893]: Replace help.txt with help.html for Idle doc display. The new idlelib/help.html is rstripped Doc/build/html/library/idle.html. It looks better than help.txt and will better document Idle as released. The tkinter html viewer that works for this file was written by Rose Roseman. The now unused EditorWindow.HelpDialog class and helt.txt file are deprecated.

bpo-24199 [https://bugs.python.org/issue?@action=redirect&bpo=24199]: Deprecate unused idlelib.idlever with possible removal in 3.6.

bpo-24790 [https://bugs.python.org/issue?@action=redirect&bpo=24790]: Remove extraneous code (which also create 2 & 3 conflicts).

Documentation

bpo-26736 [https://bugs.python.org/issue?@action=redirect&bpo=26736]: Used HTTPS for external links in the documentation if possible.

bpo-6953 [https://bugs.python.org/issue?@action=redirect&bpo=6953]: Rework the Readline module documentation to group related functions together, and add more details such as what underlying Readline functions and variables are accessed.

bpo-23606 [https://bugs.python.org/issue?@action=redirect&bpo=23606]: Adds note to ctypes documentation regarding cdll.msvcrt.

bpo-24952 [https://bugs.python.org/issue?@action=redirect&bpo=24952]: Clarify the default size argument of stack_size() in the “threading” and “_thread” modules. Patch from Mattip.

bpo-26014 [https://bugs.python.org/issue?@action=redirect&bpo=26014]: Update 3.x packaging documentation: * “See also” links to the new docs are now provided in the legacy pages * links to setuptools documentation have been updated

Tests

bpo-21916 [https://bugs.python.org/issue?@action=redirect&bpo=21916]: Added tests for the turtle module. Patch by ingrid, Gregory Loyse and Jelle Zijlstra.

bpo-26295 [https://bugs.python.org/issue?@action=redirect&bpo=26295]: When using “python3 -m test –testdir=TESTDIR”, regrtest doesn’t add “test.” prefix to test module names.

bpo-26523 [https://bugs.python.org/issue?@action=redirect&bpo=26523]: The multiprocessing thread pool (multiprocessing.dummy.Pool) was untested.

bpo-26015 [https://bugs.python.org/issue?@action=redirect&bpo=26015]: Added new tests for pickling iterators of mutable sequences.

bpo-26325 [https://bugs.python.org/issue?@action=redirect&bpo=26325]: Added test.support.check_no_resource_warning() to check that no ResourceWarning is emitted.

bpo-25940 [https://bugs.python.org/issue?@action=redirect&bpo=25940]: Changed test_ssl to use its internal local server more. This avoids relying on svn.python.org, which recently changed root certificate.

bpo-25616 [https://bugs.python.org/issue?@action=redirect&bpo=25616]: Tests for OrderedDict are extracted from test_collections into separate file test_ordered_dict.

bpo-25449 [https://bugs.python.org/issue?@action=redirect&bpo=25449]: Added tests for OrderedDict subclasses.

bpo-25188 [https://bugs.python.org/issue?@action=redirect&bpo=25188]: Add -P/–pgo to test.regrtest to suppress error output when running the test suite for the purposes of a PGO build. Initial patch by Alecsandru Patrascu.

bpo-22806 [https://bugs.python.org/issue?@action=redirect&bpo=22806]: Add python -m test --list-tests command to list tests.

bpo-18174 [https://bugs.python.org/issue?@action=redirect&bpo=18174]: python -m test --huntrleaks ... now also checks for leak of file descriptors. Patch written by Richard Oudkerk.

bpo-25260 [https://bugs.python.org/issue?@action=redirect&bpo=25260]: Fix python -m test --coverage on Windows. Remove the list of ignored directories.

PCbuild\rt.bat now accepts an unlimited number of arguments to pass along to regrtest.py. Previously there was a limit of 9.

bpo-26583 [https://bugs.python.org/issue?@action=redirect&bpo=26583]: Skip test_timestamp_overflow in test_import if bytecode files cannot be written.

Build

bpo-21277 [https://bugs.python.org/issue?@action=redirect&bpo=21277]: Don’t try to link _ctypes with a ffi_convenience library.

bpo-26884 [https://bugs.python.org/issue?@action=redirect&bpo=26884]: Fix linking extension modules for cross builds. Patch by Xavier de Gaye.

bpo-26932 [https://bugs.python.org/issue?@action=redirect&bpo=26932]: Fixed support of RTLD_* constants defined as enum values, not via macros (in particular on Android). Patch by Chi Hsuan Yen.

bpo-22359 [https://bugs.python.org/issue?@action=redirect&bpo=22359]: Disable the rules for running _freeze_importlib and pgen when cross-compiling. The output of these programs is normally saved with the source code anyway, and is still regenerated when doing a native build. Patch by Xavier de Gaye.

bpo-21668 [https://bugs.python.org/issue?@action=redirect&bpo=21668]: Link audioop, _datetime, _ctypes_test modules to libm, except on Mac OS X. Patch written by Chi Hsuan Yen.

bpo-25702 [https://bugs.python.org/issue?@action=redirect&bpo=25702]: A –with-lto configure option has been added that will enable link time optimizations at build time during a make profile-opt. Some compilers and toolchains are known to not produce stable code when using LTO, be sure to test things thoroughly before relying on it. It can provide a few % speed up over profile-opt alone.

bpo-26624 [https://bugs.python.org/issue?@action=redirect&bpo=26624]: Adds validation of ucrtbase[d].dll version with warning for old versions.

bpo-17603 [https://bugs.python.org/issue?@action=redirect&bpo=17603]: Avoid error about nonexistent fileblocks.o file by using a lower-level check for st_blocks in struct stat.

bpo-26079 [https://bugs.python.org/issue?@action=redirect&bpo=26079]: Fixing the build output folder for tix-8.4.3.6. Patch by Bjoern Thiel.

bpo-26465 [https://bugs.python.org/issue?@action=redirect&bpo=26465]: Update Windows builds to use OpenSSL 1.0.2g.

bpo-25348 [https://bugs.python.org/issue?@action=redirect&bpo=25348]: Added --pgo and --pgo-job arguments to PCbuild\build.bat for building with Profile-Guided Optimization. The old PCbuild\build_pgo.bat script is removed.

bpo-25827 [https://bugs.python.org/issue?@action=redirect&bpo=25827]: Add support for building with ICC to configure, including a new --with-icc flag.

bpo-25696 [https://bugs.python.org/issue?@action=redirect&bpo=25696]: Fix installation of Python on UNIX with make -j9.

bpo-24986 [https://bugs.python.org/issue?@action=redirect&bpo=24986]: It is now possible to build Python on Windows without errors when external libraries are not available.

bpo-24421 [https://bugs.python.org/issue?@action=redirect&bpo=24421]: Compile Modules/_math.c once, before building extensions. Previously it could fail to compile properly if the math and cmath builds were concurrent.

bpo-26465 [https://bugs.python.org/issue?@action=redirect&bpo=26465]: Update OS X 10.5+ 32-bit-only installer to build and link with OpenSSL 1.0.2g.

bpo-26268 [https://bugs.python.org/issue?@action=redirect&bpo=26268]: Update Windows builds to use OpenSSL 1.0.2f.

bpo-25136 [https://bugs.python.org/issue?@action=redirect&bpo=25136]: Support Apple Xcode 7’s new textual SDK stub libraries.

bpo-24324 [https://bugs.python.org/issue?@action=redirect&bpo=24324]: Do not enable unreachable code warnings when using gcc as the option does not work correctly in older versions of gcc and has been silently removed as of gcc-4.5.

Windows

bpo-27053 [https://bugs.python.org/issue?@action=redirect&bpo=27053]: Updates make_zip.py to correctly generate library ZIP file.

bpo-26268 [https://bugs.python.org/issue?@action=redirect&bpo=26268]: Update the prepare_ssl.py script to handle OpenSSL releases that don’t include the contents of the include directory (that is, 1.0.2e and later).

bpo-26071 [https://bugs.python.org/issue?@action=redirect&bpo=26071]: bdist_wininst created binaries fail to start and find 32bit Python

bpo-26073 [https://bugs.python.org/issue?@action=redirect&bpo=26073]: Update the list of magic numbers in launcher

bpo-26065 [https://bugs.python.org/issue?@action=redirect&bpo=26065]: Excludes venv from library when generating embeddable distro.

bpo-25022 [https://bugs.python.org/issue?@action=redirect&bpo=25022]: Removed very outdated PC/example_nt/ directory.

Tools/Demos

bpo-26799 [https://bugs.python.org/issue?@action=redirect&bpo=26799]: Fix python-gdb.py: don’t get C types once when the Python code is loaded, but get C types on demand. The C types can change if python-gdb.py is loaded before the Python executable. Patch written by Thomas Ilsche.

bpo-26271 [https://bugs.python.org/issue?@action=redirect&bpo=26271]: Fix the Freeze tool to properly use flags passed through configure. Patch by Daniel Shaulov.

bpo-26489 [https://bugs.python.org/issue?@action=redirect&bpo=26489]: Add dictionary unpacking support to Tools/parser/unparse.py. Patch by Guo Ci Teo.

bpo-26316 [https://bugs.python.org/issue?@action=redirect&bpo=26316]: Fix variable name typo in Argument Clinic.

bpo-25440 [https://bugs.python.org/issue?@action=redirect&bpo=25440]: Fix output of python-config –extension-suffix.

bpo-25154 [https://bugs.python.org/issue?@action=redirect&bpo=25154]: The pyvenv script has been deprecated in favour of python3 -m venv.

C API

bpo-26312 [https://bugs.python.org/issue?@action=redirect&bpo=26312]: SystemError is now raised in all programming bugs with using PyArg_ParseTupleAndKeywords(). RuntimeError did raised before in some programming bugs.

bpo-26198 [https://bugs.python.org/issue?@action=redirect&bpo=26198]: ValueError is now raised instead of TypeError on buffer overflow in parsing “es#” and “et#” format units. SystemError is now raised instead of TypeError on programmatical error in parsing format string.

Python 3.5.5 final

Release date: 2018-02-04

There were no new changes in version 3.5.5.

Python 3.5.5 release candidate 1

Release date: 2018-01-23

Security

bpo-32551 [https://bugs.python.org/issue?@action=redirect&bpo=32551]: The sys.path[0] initialization change for bpo-29139 [https://bugs.python.org/issue?@action=redirect&bpo=29139] caused a regression by revealing an inconsistency in how sys.path is initialized when executing __main__ from a zipfile, directory, or other import location. This is considered a potential security issue, as it may lead to privileged processes unexpectedly loading code from user controlled directories in situations where that was not previously the case.

The interpreter now consistently avoids ever adding the import location’s parent directory to sys.path, and ensures no other sys.path entries are inadvertently modified when inserting the import location named on the command line. (Originally reported as bpo-29723 [https://bugs.python.org/issue?@action=redirect&bpo=29723] against Python 3.6rc1, but it was missed at the time that the then upcoming Python 3.5.4 release would also be affected)

bpo-30657 [https://bugs.python.org/issue?@action=redirect&bpo=30657]: Fixed possible integer overflow in PyBytes_DecodeEscape, CVE-2017-1000158. Original patch by Jay Bosamiya; rebased to Python 3 by Miro Hrončok.

bpo-30947 [https://bugs.python.org/issue?@action=redirect&bpo=30947]: Upgrade libexpat embedded copy from version 2.2.1 to 2.2.3 to get security fixes.

Core and Builtins

bpo-31095 [https://bugs.python.org/issue?@action=redirect&bpo=31095]: Fix potential crash during GC caused by tp_dealloc which doesn’t call PyObject_GC_UnTrack().

Library

bpo-32072 [https://bugs.python.org/issue?@action=redirect&bpo=32072]: Fixed issues with binary plists:

Fixed saving bytearrays.

Identical objects will be saved only once.

Equal references will be load as identical objects.

Added support for saving and loading recursive data structures.

bpo-31170 [https://bugs.python.org/issue?@action=redirect&bpo=31170]: expat: Update libexpat from 2.2.3 to 2.2.4. Fix copying of partial characters for UTF-8 input (libexpat bug 115): https://github.com/libexpat/libexpat/issues/115

Python 3.5.4 final

Release date: 2017-08-07

Library

bpo-30119 [https://bugs.python.org/issue?@action=redirect&bpo=30119]: ftplib.FTP.putline() now throws ValueError on commands that contains CR or LF. Patch by Dong-hee Na.

Python 3.5.4 release candidate 1

Release date: 2017-07-23

Security

bpo-30730 [https://bugs.python.org/issue?@action=redirect&bpo=30730]: Prevent environment variables injection in subprocess on Windows. Prevent passing other environment variables and command arguments.

bpo-30694 [https://bugs.python.org/issue?@action=redirect&bpo=30694]: Upgrade expat copy from 2.2.0 to 2.2.1 to get fixes of multiple security vulnerabilities including: CVE-2017-9233 (External entity infinite loop DoS), CVE-2016-9063 (Integer overflow, re-fix), CVE-2016-0718 (Fix regression bugs from 2.2.0’s fix to CVE-2016-0718) and CVE-2012-0876 (Counter hash flooding with SipHash). Note: the CVE-2016-5300 (Use os-specific entropy sources like getrandom) doesn’t impact Python, since Python already gets entropy from the OS to set the expat secret using XML_SetHashSalt().

bpo-30500 [https://bugs.python.org/issue?@action=redirect&bpo=30500]: Fix urllib.parse.splithost() to correctly parse fragments. For example, splithost('//127.0.0.1#@evil.com/') now correctly returns the 127.0.0.1 host, instead of treating @evil.com as the host in an authentication (login@host).

bpo-29591 [https://bugs.python.org/issue?@action=redirect&bpo=29591]: Update expat copy from 2.1.1 to 2.2.0 to get fixes of CVE-2016-0718 and CVE-2016-4472. See https://sourceforge.net/p/expat/bugs/537/ for more information.

Core and Builtins

bpo-30876 [https://bugs.python.org/issue?@action=redirect&bpo=30876]: Relative import from unloaded package now reimports the package instead of failing with SystemError. Relative import from non-package now fails with ImportError rather than SystemError.

bpo-30765 [https://bugs.python.org/issue?@action=redirect&bpo=30765]: Avoid blocking in pthread_mutex_lock() when PyThread_acquire_lock() is asked not to block.

bpo-27945 [https://bugs.python.org/issue?@action=redirect&bpo=27945]: Fixed various segfaults with dict when input collections are mutated during searching, inserting or comparing. Based on patches by Duane Griffin and Tim Mitchell.

bpo-25794 [https://bugs.python.org/issue?@action=redirect&bpo=25794]: Fixed type.__setattr__() and type.__delattr__() for non-interned attribute names. Based on patch by Eryk Sun.

bpo-29935 [https://bugs.python.org/issue?@action=redirect&bpo=29935]: Fixed error messages in the index() method of tuple, list and deque when pass indices of wrong type.

bpo-28876 [https://bugs.python.org/issue?@action=redirect&bpo=28876]: bool(range) works even if len(range) raises OverflowError.

bpo-29600 [https://bugs.python.org/issue?@action=redirect&bpo=29600]: Fix wrapping coroutine return values in StopIteration.

bpo-29537 [https://bugs.python.org/issue?@action=redirect&bpo=29537]: Restore runtime compatibility with bytecode files generated by CPython 3.5.0 to 3.5.2, and adjust the eval loop to avoid the problems that could be caused by the malformed variant of the BUILD_MAP_UNPACK_WITH_CALL opcode that they may contain. Patch by Petr Viktorin, Serhiy Storchaka, and Nick Coghlan.

bpo-28598 [https://bugs.python.org/issue?@action=redirect&bpo=28598]: Support __rmod__ for subclasses of str being called before str.__mod__. Patch by Martijn Pieters.

bpo-29602 [https://bugs.python.org/issue?@action=redirect&bpo=29602]: Fix incorrect handling of signed zeros in complex constructor for complex subclasses and for inputs having a __complex__ method. Patch by Serhiy Storchaka.

bpo-29347 [https://bugs.python.org/issue?@action=redirect&bpo=29347]: Fixed possibly dereferencing undefined pointers when creating weakref objects.

bpo-29438 [https://bugs.python.org/issue?@action=redirect&bpo=29438]: Fixed use-after-free problem in key sharing dict.

bpo-29319 [https://bugs.python.org/issue?@action=redirect&bpo=29319]: Prevent RunMainFromImporter overwriting sys.path[0].

bpo-29337 [https://bugs.python.org/issue?@action=redirect&bpo=29337]: Fixed possible BytesWarning when compare the code objects. Warnings could be emitted at compile time.

bpo-29478 [https://bugs.python.org/issue?@action=redirect&bpo=29478]: If max_line_length=None is specified while using the Compat32 policy, it is no longer ignored. Patch by Mircea Cosbuc.

Library

bpo-29403 [https://bugs.python.org/issue?@action=redirect&bpo=29403]: Fix unittest.mock’s autospec to not fail on method-bound builtin functions. Patch by Aaron Gallagher.

bpo-30961 [https://bugs.python.org/issue?@action=redirect&bpo=30961]: Fix decrementing a borrowed reference in tracemalloc.

bpo-30886 [https://bugs.python.org/issue?@action=redirect&bpo=30886]: Fix multiprocessing.Queue.join_thread(): it now waits until the thread completes, even if the thread was started by the same process which created the queue.

bpo-29854 [https://bugs.python.org/issue?@action=redirect&bpo=29854]: Fix segfault in readline when using readline’s history-size option. Patch by Nir Soffer.

bpo-30807 [https://bugs.python.org/issue?@action=redirect&bpo=30807]: signal.setitimer() may disable the timer when passed a tiny value.

Tiny values (such as 1e-6) are valid non-zero values for setitimer(), which is specified as taking microsecond-resolution intervals. However, on some platform, our conversion routine could convert 1e-6 into a zero interval, therefore disabling the timer instead of (re-)scheduling it.

bpo-30441 [https://bugs.python.org/issue?@action=redirect&bpo=30441]: Fix bug when modifying os.environ while iterating over it

bpo-30532 [https://bugs.python.org/issue?@action=redirect&bpo=30532]: Fix email header value parser dropping folding white space in certain cases.

bpo-29169 [https://bugs.python.org/issue?@action=redirect&bpo=29169]: Update zlib to 1.2.11.

bpo-30879 [https://bugs.python.org/issue?@action=redirect&bpo=30879]: os.listdir() and os.scandir() now emit bytes names when called with bytes-like argument.

bpo-30746 [https://bugs.python.org/issue?@action=redirect&bpo=30746]: Prohibited the ‘=’ character in environment variable names in os.putenv() and os.spawn*().

bpo-29755 [https://bugs.python.org/issue?@action=redirect&bpo=29755]: Fixed the lgettext() family of functions in the gettext module. They now always return bytes.

bpo-30645 [https://bugs.python.org/issue?@action=redirect&bpo=30645]: Fix path calculation in imp.load_package(), fixing it for cases when a package is only shipped with bytecodes. Patch by Alexandru Ardelean.

bpo-23890 [https://bugs.python.org/issue?@action=redirect&bpo=23890]: unittest.TestCase.assertRaises() now manually breaks a reference cycle to not keep objects alive longer than expected.

bpo-30149 [https://bugs.python.org/issue?@action=redirect&bpo=30149]: inspect.signature() now supports callables with variable-argument parameters wrapped with partialmethod. Patch by Dong-hee Na.

bpo-29931 [https://bugs.python.org/issue?@action=redirect&bpo=29931]: Fixed comparison check for ipaddress.ip_interface objects. Patch by Sanjay Sundaresan.

bpo-24484 [https://bugs.python.org/issue?@action=redirect&bpo=24484]: Avoid race condition in multiprocessing cleanup.

bpo-28994 [https://bugs.python.org/issue?@action=redirect&bpo=28994]: The traceback no longer displayed for SystemExit raised in a callback registered by atexit.

bpo-30508 [https://bugs.python.org/issue?@action=redirect&bpo=30508]: Don’t log exceptions if Task/Future “cancel()” method was called.

bpo-28556 [https://bugs.python.org/issue?@action=redirect&bpo=28556]: Updates to typing module: Add generic AsyncContextManager, add support for ContextManager on all versions. Original PRs by Jelle Zijlstra and Ivan Levkivskyi

bpo-29870 [https://bugs.python.org/issue?@action=redirect&bpo=29870]: Fix ssl sockets leaks when connection is aborted in asyncio/ssl implementation. Patch by Michaël Sghaïer.

bpo-29743 [https://bugs.python.org/issue?@action=redirect&bpo=29743]: Closing transport during handshake process leaks open socket. Patch by Nikolay Kim

bpo-27585 [https://bugs.python.org/issue?@action=redirect&bpo=27585]: Fix waiter cancellation in asyncio.Lock. Patch by Mathieu Sornay.

bpo-30418 [https://bugs.python.org/issue?@action=redirect&bpo=30418]: On Windows, subprocess.Popen.communicate() now also ignore EINVAL on stdin.write() if the child process is still running but closed the pipe.

bpo-30378 [https://bugs.python.org/issue?@action=redirect&bpo=30378]: Fix the problem that logging.handlers.SysLogHandler cannot handle IPv6 addresses.

bpo-29960 [https://bugs.python.org/issue?@action=redirect&bpo=29960]: Preserve generator state when _random.Random.setstate() raises an exception. Patch by Bryan Olson.

bpo-30414 [https://bugs.python.org/issue?@action=redirect&bpo=30414]: multiprocessing.Queue._feed background running thread do not break from main loop on exception.

bpo-30003 [https://bugs.python.org/issue?@action=redirect&bpo=30003]: Fix handling escape characters in HZ codec. Based on patch by Ma Lin.

bpo-30301 [https://bugs.python.org/issue?@action=redirect&bpo=30301]: Fix AttributeError when using SimpleQueue.empty() under spawn and forkserver start methods.

bpo-30329 [https://bugs.python.org/issue?@action=redirect&bpo=30329]: imaplib and poplib now catch the Windows socket WSAEINVAL error (code 10022) on shutdown(SHUT_RDWR): An invalid operation was attempted. This error occurs sometimes on SSL connections.

bpo-30375 [https://bugs.python.org/issue?@action=redirect&bpo=30375]: Warnings emitted when compile a regular expression now always point to the line in the user code. Previously they could point into inners of the re module if emitted from inside of groups or conditionals.

bpo-30048 [https://bugs.python.org/issue?@action=redirect&bpo=30048]: Fixed Task.cancel() can be ignored when the task is running coroutine and the coroutine returned without any more await.

bpo-29990 [https://bugs.python.org/issue?@action=redirect&bpo=29990]: Fix range checking in GB18030 decoder. Original patch by Ma Lin.

bpo-26293 [https://bugs.python.org/issue?@action=redirect&bpo=26293]: Change resulted because of zipfile breakage. (See also: bpo-29094 [https://bugs.python.org/issue?@action=redirect&bpo=29094])

bpo-30243 [https://bugs.python.org/issue?@action=redirect&bpo=30243]: Removed the __init__ methods of _json’s scanner and encoder. Misusing them could cause memory leaks or crashes. Now scanner and encoder objects are completely initialized in the __new__ methods.

bpo-30185 [https://bugs.python.org/issue?@action=redirect&bpo=30185]: Avoid KeyboardInterrupt tracebacks in forkserver helper process when Ctrl-C is received.

bpo-28556 [https://bugs.python.org/issue?@action=redirect&bpo=28556]: Various updates to typing module: add typing.NoReturn type, use WrapperDescriptorType, minor bug-fixes. Original PRs by Jim Fasarakis-Hilliard and Ivan Levkivskyi.

bpo-30205 [https://bugs.python.org/issue?@action=redirect&bpo=30205]: Fix getsockname() for unbound AF_UNIX sockets on Linux.

bpo-30070 [https://bugs.python.org/issue?@action=redirect&bpo=30070]: Fixed leaks and crashes in errors handling in the parser module.

bpo-30061 [https://bugs.python.org/issue?@action=redirect&bpo=30061]: Fixed crashes in IOBase methods __next__() and readlines() when readline() or __next__() respectively return non-sizeable object. Fixed possible other errors caused by not checking results of PyObject_Size(), PySequence_Size(), or PyMapping_Size().

bpo-30068 [https://bugs.python.org/issue?@action=redirect&bpo=30068]: _io._IOBase.readlines will check if it’s closed first when hint is present.

bpo-29694 [https://bugs.python.org/issue?@action=redirect&bpo=29694]: Fixed race condition in pathlib mkdir with flags parents=True. Patch by Armin Rigo.

bpo-29692 [https://bugs.python.org/issue?@action=redirect&bpo=29692]: Fixed arbitrary unchaining of RuntimeError exceptions in contextlib.contextmanager. Patch by Siddharth Velankar.

bpo-29998 [https://bugs.python.org/issue?@action=redirect&bpo=29998]: Pickling and copying ImportError now preserves name and path attributes.

bpo-29942 [https://bugs.python.org/issue?@action=redirect&bpo=29942]: Fix a crash in itertools.chain.from_iterable when encountering long runs of empty iterables.

bpo-27863 [https://bugs.python.org/issue?@action=redirect&bpo=27863]: Fixed multiple crashes in ElementTree caused by race conditions and wrong types.

bpo-28699 [https://bugs.python.org/issue?@action=redirect&bpo=28699]: Fixed a bug in pools in multiprocessing.pool that raising an exception at the very first of an iterable may swallow the exception or make the program hang. Patch by Davin Potts and Xiang Zhang.

bpo-25803 [https://bugs.python.org/issue?@action=redirect&bpo=25803]: Avoid incorrect errors raised by Path.mkdir(exist_ok=True) when the OS gives priority to errors such as EACCES over EEXIST.

bpo-29861 [https://bugs.python.org/issue?@action=redirect&bpo=29861]: Release references to tasks, their arguments and their results as soon as they are finished in multiprocessing.Pool.

bpo-29884 [https://bugs.python.org/issue?@action=redirect&bpo=29884]: faulthandler: Restore the old sigaltstack during teardown. Patch by Christophe Zeitouny.

bpo-25455 [https://bugs.python.org/issue?@action=redirect&bpo=25455]: Fixed crashes in repr of recursive buffered file-like objects.

bpo-29800 [https://bugs.python.org/issue?@action=redirect&bpo=29800]: Fix crashes in partial.__repr__ if the keys of partial.keywords are not strings. Patch by Michael Seifert.

bpo-29742 [https://bugs.python.org/issue?@action=redirect&bpo=29742]: get_extra_info() raises exception if get called on closed ssl transport. Patch by Nikolay Kim.

bpo-8256 [https://bugs.python.org/issue?@action=redirect&bpo=8256]: Fixed possible failing or crashing input() if attributes “encoding” or “errors” of sys.stdin or sys.stdout are not set or are not strings.

bpo-28298 [https://bugs.python.org/issue?@action=redirect&bpo=28298]: Fix a bug that prevented array ‘Q’, ‘L’ and ‘I’ from accepting big intables (objects that have __int__) as elements. Patch by Oren Milman.

bpo-29615 [https://bugs.python.org/issue?@action=redirect&bpo=29615]: SimpleXMLRPCDispatcher no longer chains KeyError (or any other exception) to exception(s) raised in the dispatched methods. Patch by Petr Motejlek.

bpo-29704 [https://bugs.python.org/issue?@action=redirect&bpo=29704]: asyncio.subprocess.SubprocessStreamProtocol no longer closes before all pipes are closed.

bpo-29703 [https://bugs.python.org/issue?@action=redirect&bpo=29703]: Fix asyncio to support instantiation of new event loops in child processes.

bpo-29376 [https://bugs.python.org/issue?@action=redirect&bpo=29376]: Fix assertion error in threading._DummyThread.is_alive().

bpo-29110 [https://bugs.python.org/issue?@action=redirect&bpo=29110]: Fix file object leak in aifc.open() when file is given as a filesystem path and is not in valid AIFF format. Patch by Anthony Zhang.

bpo-28961 [https://bugs.python.org/issue?@action=redirect&bpo=28961]: Fix unittest.mock._Call helper: don’t ignore the name parameter anymore. Patch written by Jiajun Huang.

bpo-29532 [https://bugs.python.org/issue?@action=redirect&bpo=29532]: Altering a kwarg dictionary passed to functools.partial() no longer affects a partial object after creation.

bpo-28556 [https://bugs.python.org/issue?@action=redirect&bpo=28556]: Various updates to typing module: typing.Counter, typing.ChainMap, improved ABC caching, etc. Original PRs by Jelle Zijlstra, Ivan Levkivskyi, Manuel Krebber, and Łukasz Langa.

bpo-29100 [https://bugs.python.org/issue?@action=redirect&bpo=29100]: Fix datetime.fromtimestamp() regression introduced in Python 3.6.0: check minimum and maximum years.

bpo-29519 [https://bugs.python.org/issue?@action=redirect&bpo=29519]: Fix weakref spewing exceptions during interpreter shutdown when used with a rare combination of multiprocessing and custom codecs.

bpo-29416 [https://bugs.python.org/issue?@action=redirect&bpo=29416]: Prevent infinite loop in pathlib.Path.mkdir

bpo-29444 [https://bugs.python.org/issue?@action=redirect&bpo=29444]: Fixed out-of-bounds buffer access in the group() method of the match object. Based on patch by WGH.

bpo-29335 [https://bugs.python.org/issue?@action=redirect&bpo=29335]: Fix subprocess.Popen.wait() when the child process has exited to a stopped instead of terminated state (ex: when under ptrace).

bpo-29290 [https://bugs.python.org/issue?@action=redirect&bpo=29290]: Fix a regression in argparse that help messages would wrap at non-breaking spaces.

bpo-28735 [https://bugs.python.org/issue?@action=redirect&bpo=28735]: Fixed the comparison of mock.MagickMock with mock.ANY.

bpo-29011 [https://bugs.python.org/issue?@action=redirect&bpo=29011]: Fix an important omission by adding Deque to the typing module.

bpo-29219 [https://bugs.python.org/issue?@action=redirect&bpo=29219]: Fixed infinite recursion in the repr of uninitialized ctypes.CDLL instances.

bpo-28969 [https://bugs.python.org/issue?@action=redirect&bpo=28969]: Fixed race condition in C implementation of functools.lru_cache. KeyError could be raised when cached function with full cache was simultaneously called from differen threads with the same uncached arguments.

bpo-29142 [https://bugs.python.org/issue?@action=redirect&bpo=29142]: In urllib.request, suffixes in no_proxy environment variable with leading dots could match related hostnames again (e.g. .b.c matches a.b.c). Patch by Milan Oberkirch.

Documentation

bpo-30176 [https://bugs.python.org/issue?@action=redirect&bpo=30176]: Add missing attribute related constants in curses documentation.

bpo-26985 [https://bugs.python.org/issue?@action=redirect&bpo=26985]: Add missing info of code object in inspect documentation.

bpo-28929 [https://bugs.python.org/issue?@action=redirect&bpo=28929]: Link the documentation to its source file on GitHub.

bpo-25008 [https://bugs.python.org/issue?@action=redirect&bpo=25008]: Document smtpd.py as effectively deprecated and add a pointer to aiosmtpd, a third-party asyncio-based replacement.

bpo-26355 [https://bugs.python.org/issue?@action=redirect&bpo=26355]: Add canonical header link on each page to corresponding major version of the documentation. Patch by Matthias Bussonnier.

bpo-29349 [https://bugs.python.org/issue?@action=redirect&bpo=29349]: Fix Python 2 syntax in code for building the documentation.

Tests

bpo-30822 [https://bugs.python.org/issue?@action=redirect&bpo=30822]: Fix regrtest command line parser to allow passing -u extralargefile to run test_zipfile64.

bpo-30383 [https://bugs.python.org/issue?@action=redirect&bpo=30383]: regrtest: Enhance regrtest and backport features from the master branch.

Add options: –coverage, –testdir, –list-tests (list test files, don’t run them), –list-cases (list test identifiers, don’t run them, bpo-30523 [https://bugs.python.org/issue?@action=redirect&bpo=30523]), –matchfile (load a list of test filters from a text file, bpo-30540 [https://bugs.python.org/issue?@action=redirect&bpo=30540]), –slowest (alias to –slow).

Enhance output: add timestamp, test result, currently running tests, “Tests result: xxx” summary with total duration, etc.

Fix reference leak hunting in regrtest, –huntrleaks: regrtest now warms up caches, create explicitly all internal singletons which are created on demand to prevent false positives when checking for reference leaks. (bpo-30675 [https://bugs.python.org/issue?@action=redirect&bpo=30675]).

bpo-30357 [https://bugs.python.org/issue?@action=redirect&bpo=30357]: test_thread: setUp() now uses support.threading_setup() and support.threading_cleanup() to wait until threads complete to avoid random side effects on following tests. Initial patch written by Grzegorz Grzywacz.

bpo-28087 [https://bugs.python.org/issue?@action=redirect&bpo=28087]: Skip test_asyncore and test_eintr poll failures on macOS. Skip some tests of select.poll when running on macOS due to unresolved issues with the underlying system poll function on some macOS versions.

bpo-30197 [https://bugs.python.org/issue?@action=redirect&bpo=30197]: Enhanced functions swap_attr() and swap_item() in the test.support module. They now work when delete replaced attribute or item inside the with statement. The old value of the attribute or item (or None if it doesn’t exist) now will be assigned to the target of the “as” clause, if there is one.

bpo-29571 [https://bugs.python.org/issue?@action=redirect&bpo=29571]: to match the behaviour of the re.LOCALE flag, test_re.test_locale_flag now uses locale.getpreferredencoding(False) to determine the candidate encoding for the test regex (allowing it to correctly skip the test when the default locale encoding is a multi-byte encoding)

Build

bpo-29243 [https://bugs.python.org/issue?@action=redirect&bpo=29243]: Prevent unnecessary rebuilding of Python during make test, make install and some other make targets when configured with --enable-optimizations.

bpo-23404 [https://bugs.python.org/issue?@action=redirect&bpo=23404]: Don’t regenerate generated files based on file modification time anymore: the action is now explicit. Replace make touch with make regen-all.

bpo-29643 [https://bugs.python.org/issue?@action=redirect&bpo=29643]: Fix --enable-optimization didn’t work.

Windows

bpo-30687 [https://bugs.python.org/issue?@action=redirect&bpo=30687]: Locate msbuild.exe on Windows when building rather than vcvarsall.bat

bpo-29392 [https://bugs.python.org/issue?@action=redirect&bpo=29392]: Prevent crash when passing invalid arguments into msvcrt module.

C API

bpo-27867 [https://bugs.python.org/issue?@action=redirect&bpo=27867]: Function PySlice_GetIndicesEx() is replaced with a macro if Py_LIMITED_API is set to the value between 0x03050400 and 0x03060000 (not including) or 0x03060100 or higher.

bpo-29083 [https://bugs.python.org/issue?@action=redirect&bpo=29083]: Fixed the declaration of some public API functions. PyArg_VaParse() and PyArg_VaParseTupleAndKeywords() were not available in limited API. PyArg_ValidateKeywordArguments(), PyArg_UnpackTuple() and Py_BuildValue() were not available in limited API of version < 3.3 when PY_SSIZE_T_CLEAN is defined.

Python 3.5.3 final

Release date: 2017-01-17

There were no code changes between 3.5.3rc1 and 3.5.3 final.

Python 3.5.3 release candidate 1

Release date: 2017-01-02

Core and Builtins

bpo-29073 [https://bugs.python.org/issue?@action=redirect&bpo=29073]: bytearray formatting no longer truncates on first null byte.

bpo-28932 [https://bugs.python.org/issue?@action=redirect&bpo=28932]: Do not include <sys/random.h> if it does not exist.

bpo-28147 [https://bugs.python.org/issue?@action=redirect&bpo=28147]: Fix a memory leak in split-table dictionaries: setattr() must not convert combined table into split table.

bpo-25677 [https://bugs.python.org/issue?@action=redirect&bpo=25677]: Correct the positioning of the syntax error caret for indented blocks. Based on patch by Michael Layzell.

bpo-29000 [https://bugs.python.org/issue?@action=redirect&bpo=29000]: Fixed bytes formatting of octals with zero padding in alternate form.

bpo-28512 [https://bugs.python.org/issue?@action=redirect&bpo=28512]: Fixed setting the offset attribute of SyntaxError by PyErr_SyntaxLocationEx() and PyErr_SyntaxLocationObject().

bpo-28991 [https://bugs.python.org/issue?@action=redirect&bpo=28991]: functools.lru_cache() was susceptible to an obscure reentrancy bug caused by a monkey-patched len() function.

bpo-28648 [https://bugs.python.org/issue?@action=redirect&bpo=28648]: Fixed crash in Py_DecodeLocale() in debug build on Mac OS X when decode astral characters. Patch by Xiang Zhang.

bpo-19398 [https://bugs.python.org/issue?@action=redirect&bpo=19398]: Extra slash no longer added to sys.path components in case of empty compile-time PYTHONPATH components.

bpo-28426 [https://bugs.python.org/issue?@action=redirect&bpo=28426]: Fixed potential crash in PyUnicode_AsDecodedObject() in debug build.

bpo-23782 [https://bugs.python.org/issue?@action=redirect&bpo=23782]: Fixed possible memory leak in _PyTraceback_Add() and exception loss in PyTraceBack_Here().

bpo-28379 [https://bugs.python.org/issue?@action=redirect&bpo=28379]: Added sanity checks and tests for PyUnicode_CopyCharacters(). Patch by Xiang Zhang.

bpo-28376 [https://bugs.python.org/issue?@action=redirect&bpo=28376]: The type of long range iterator is now registered as Iterator. Patch by Oren Milman.

bpo-28376 [https://bugs.python.org/issue?@action=redirect&bpo=28376]: The constructor of range_iterator now checks that step is not 0. Patch by Oren Milman.

bpo-26906 [https://bugs.python.org/issue?@action=redirect&bpo=26906]: Resolving special methods of uninitialized type now causes implicit initialization of the type instead of a fail.

bpo-18287 [https://bugs.python.org/issue?@action=redirect&bpo=18287]: PyType_Ready() now checks that tp_name is not NULL. Original patch by Niklas Koep.

bpo-24098 [https://bugs.python.org/issue?@action=redirect&bpo=24098]: Fixed possible crash when AST is changed in process of compiling it.

bpo-28350 [https://bugs.python.org/issue?@action=redirect&bpo=28350]: String constants with null character no longer interned.

bpo-26617 [https://bugs.python.org/issue?@action=redirect&bpo=26617]: Fix crash when GC runs during weakref callbacks.

bpo-27942 [https://bugs.python.org/issue?@action=redirect&bpo=27942]: String constants now interned recursively in tuples and frozensets.

bpo-21578 [https://bugs.python.org/issue?@action=redirect&bpo=21578]: Fixed misleading error message when ImportError called with invalid keyword args.

bpo-28203 [https://bugs.python.org/issue?@action=redirect&bpo=28203]: Fix incorrect type in error message from complex(1.0, {2:3}). Patch by Soumya Sharma.

bpo-27955 [https://bugs.python.org/issue?@action=redirect&bpo=27955]: Fallback on reading /dev/urandom device when the getrandom() syscall fails with EPERM, for example when blocked by SECCOMP.

bpo-28131 [https://bugs.python.org/issue?@action=redirect&bpo=28131]: Fix a regression in zipimport’s compile_source(). zipimport should use the same optimization level as the interpreter.

bpo-25221 [https://bugs.python.org/issue?@action=redirect&bpo=25221]: Fix corrupted result from PyLong_FromLong(0) when Python is compiled with NSMALLPOSINTS = 0.

bpo-25758 [https://bugs.python.org/issue?@action=redirect&bpo=25758]: Prevents zipimport from unnecessarily encoding a filename (patch by Eryk Sun)

bpo-28189 [https://bugs.python.org/issue?@action=redirect&bpo=28189]: dictitems_contains no longer swallows compare errors. (Patch by Xiang Zhang)

bpo-27812 [https://bugs.python.org/issue?@action=redirect&bpo=27812]: Properly clear out a generator’s frame’s backreference to the generator to prevent crashes in frame.clear().

bpo-27811 [https://bugs.python.org/issue?@action=redirect&bpo=27811]: Fix a crash when a coroutine that has not been awaited is finalized with warnings-as-errors enabled.

bpo-27587 [https://bugs.python.org/issue?@action=redirect&bpo=27587]: Fix another issue found by PVS-Studio: Null pointer check after use of ‘def’ in _PyState_AddModule(). Initial patch by Christian Heimes.

bpo-26020 [https://bugs.python.org/issue?@action=redirect&bpo=26020]: set literal evaluation order did not match documented behaviour.

bpo-27782 [https://bugs.python.org/issue?@action=redirect&bpo=27782]: Multi-phase extension module import now correctly allows the m_methods field to be used to add module level functions to instances of non-module types returned from Py_create_mod. Patch by Xiang Zhang.

bpo-27936 [https://bugs.python.org/issue?@action=redirect&bpo=27936]: The round() function accepted a second None argument for some types but not for others. Fixed the inconsistency by accepting None for all numeric types.

bpo-27487 [https://bugs.python.org/issue?@action=redirect&bpo=27487]: Warn if a submodule argument to “python -m” or runpy.run_module() is found in sys.modules after parent packages are imported, but before the submodule is executed.

bpo-27558 [https://bugs.python.org/issue?@action=redirect&bpo=27558]: Fix a SystemError in the implementation of “raise” statement. In a brand new thread, raise a RuntimeError since there is no active exception to reraise. Patch written by Xiang Zhang.

bpo-27419 [https://bugs.python.org/issue?@action=redirect&bpo=27419]: Standard __import__() no longer look up “__import__” in globals or builtins for importing submodules or “from import”. Fixed handling an error of non-string package name.

bpo-27083 [https://bugs.python.org/issue?@action=redirect&bpo=27083]: Respect the PYTHONCASEOK environment variable under Windows.

bpo-27514 [https://bugs.python.org/issue?@action=redirect&bpo=27514]: Make having too many statically nested blocks a SyntaxError instead of SystemError.

bpo-27473 [https://bugs.python.org/issue?@action=redirect&bpo=27473]: Fixed possible integer overflow in bytes and bytearray concatenations. Patch by Xiang Zhang.

bpo-27507 [https://bugs.python.org/issue?@action=redirect&bpo=27507]: Add integer overflow check in bytearray.extend(). Patch by Xiang Zhang.

bpo-27581 [https://bugs.python.org/issue?@action=redirect&bpo=27581]: Don’t rely on wrapping for overflow check in PySequence_Tuple(). Patch by Xiang Zhang.

bpo-27443 [https://bugs.python.org/issue?@action=redirect&bpo=27443]: __length_hint__() of bytearray iterators no longer return a negative integer for a resized bytearray.

bpo-27942 [https://bugs.python.org/issue?@action=redirect&bpo=27942]: Fix memory leak in codeobject.c

Library

bpo-15812 [https://bugs.python.org/issue?@action=redirect&bpo=15812]: inspect.getframeinfo() now correctly shows the first line of a context. Patch by Sam Breese.

bpo-29094 [https://bugs.python.org/issue?@action=redirect&bpo=29094]: Offsets in a ZIP file created with extern file object and modes “w” and “x” now are relative to the start of the file.

bpo-13051 [https://bugs.python.org/issue?@action=redirect&bpo=13051]: Fixed recursion errors in large or resized curses.textpad.Textbox. Based on patch by Tycho Andersen.

bpo-29119 [https://bugs.python.org/issue?@action=redirect&bpo=29119]: Fix weakrefs in the pure python version of collections.OrderedDict move_to_end() method. Contributed by Andra Bogildea.

bpo-9770 [https://bugs.python.org/issue?@action=redirect&bpo=9770]: curses.ascii predicates now work correctly with negative integers.

bpo-28427 [https://bugs.python.org/issue?@action=redirect&bpo=28427]: old keys should not remove new values from WeakValueDictionary when collecting from another thread.

bpo-28923 [https://bugs.python.org/issue?@action=redirect&bpo=28923]: Remove editor artifacts from Tix.py.

bpo-28871 [https://bugs.python.org/issue?@action=redirect&bpo=28871]: Fixed a crash when deallocate deep ElementTree.

bpo-19542 [https://bugs.python.org/issue?@action=redirect&bpo=19542]: Fix bugs in WeakValueDictionary.setdefault() and WeakValueDictionary.pop() when a GC collection happens in another thread.

bpo-20191 [https://bugs.python.org/issue?@action=redirect&bpo=20191]: Fixed a crash in resource.prlimit() when pass a sequence that doesn’t own its elements as limits.

bpo-28779 [https://bugs.python.org/issue?@action=redirect&bpo=28779]: multiprocessing.set_forkserver_preload() would crash the forkserver process if a preloaded module instantiated some multiprocessing objects such as locks.

bpo-28847 [https://bugs.python.org/issue?@action=redirect&bpo=28847]: dbm.dumb now supports reading read-only files and no longer writes the index file when it is not changed.

bpo-25659 [https://bugs.python.org/issue?@action=redirect&bpo=25659]: In ctypes, prevent a crash calling the from_buffer() and from_buffer_copy() methods on abstract classes like Array.

bpo-28732 [https://bugs.python.org/issue?@action=redirect&bpo=28732]: Fix crash in os.spawnv() with no elements in args

bpo-28485 [https://bugs.python.org/issue?@action=redirect&bpo=28485]: Always raise ValueError for negative compileall.compile_dir(workers=…) parameter, even when multithreading is unavailable.

bpo-28387 [https://bugs.python.org/issue?@action=redirect&bpo=28387]: Fixed possible crash in _io.TextIOWrapper deallocator when the garbage collector is invoked in other thread. Based on patch by Sebastian Cufre.

bpo-27517 [https://bugs.python.org/issue?@action=redirect&bpo=27517]: LZMA compressor and decompressor no longer raise exceptions if given empty data twice. Patch by Benjamin Fogle.

bpo-28549 [https://bugs.python.org/issue?@action=redirect&bpo=28549]: Fixed segfault in curses’s addch() with ncurses6.

bpo-28449 [https://bugs.python.org/issue?@action=redirect&bpo=28449]: tarfile.open() with mode “r” or “r:” now tries to open a tar file with compression before trying to open it without compression. Otherwise it had 50% chance failed with ignore_zeros=True.

bpo-23262 [https://bugs.python.org/issue?@action=redirect&bpo=23262]: The webbrowser module now supports Firefox 36+ and derived browsers. Based on patch by Oleg Broytman.

bpo-27939 [https://bugs.python.org/issue?@action=redirect&bpo=27939]: Fixed bugs in tkinter.ttk.LabeledScale and tkinter.Scale caused by representing the scale as float value internally in Tk. tkinter.IntVar now works if float value is set to underlying Tk variable.

bpo-28255 [https://bugs.python.org/issue?@action=redirect&bpo=28255]: calendar.TextCalendar().prmonth() no longer prints a space at the start of new line after printing a month’s calendar. Patch by Xiang Zhang.

bpo-20491 [https://bugs.python.org/issue?@action=redirect&bpo=20491]: The textwrap.TextWrapper class now honors non-breaking spaces. Based on patch by Kaarle Ritvanen.

bpo-28353 [https://bugs.python.org/issue?@action=redirect&bpo=28353]: os.fwalk() no longer fails on broken links.

bpo-25464 [https://bugs.python.org/issue?@action=redirect&bpo=25464]: Fixed HList.header_exists() in tkinter.tix module by addin a workaround to Tix library bug.

bpo-28488 [https://bugs.python.org/issue?@action=redirect&bpo=28488]: shutil.make_archive() no longer add entry “./” to ZIP archive.

bpo-24452 [https://bugs.python.org/issue?@action=redirect&bpo=24452]: Make webbrowser support Chrome on Mac OS X.

bpo-20766 [https://bugs.python.org/issue?@action=redirect&bpo=20766]: Fix references leaked by pdb in the handling of SIGINT handlers.

bpo-26293 [https://bugs.python.org/issue?@action=redirect&bpo=26293]: Fixed writing ZIP files that starts not from the start of the file. Offsets in ZIP file now are relative to the start of the archive in conforming to the specification.

bpo-28321 [https://bugs.python.org/issue?@action=redirect&bpo=28321]: Fixed writing non-BMP characters with binary format in plistlib.

bpo-28322 [https://bugs.python.org/issue?@action=redirect&bpo=28322]: Fixed possible crashes when unpickle itertools objects from incorrect pickle data. Based on patch by John Leitch.

Fix possible integer overflows and crashes in the mmap module with unusual usage patterns.

bpo-1703178 [https://bugs.python.org/issue?@action=redirect&bpo=1703178]: Fix the ability to pass the –link-objects option to the distutils build_ext command.

bpo-28253 [https://bugs.python.org/issue?@action=redirect&bpo=28253]: Fixed calendar functions for extreme months: 0001-01 and 9999-12.

Methods itermonthdays() and itermonthdays2() are reimplemented so that they don’t call itermonthdates() which can cause datetime.date under/overflow.

bpo-28275 [https://bugs.python.org/issue?@action=redirect&bpo=28275]: Fixed possible use after free in the decompress() methods of the LZMADecompressor and BZ2Decompressor classes. Original patch by John Leitch.

bpo-27897 [https://bugs.python.org/issue?@action=redirect&bpo=27897]: Fixed possible crash in sqlite3.Connection.create_collation() if pass invalid string-like object as a name. Patch by Xiang Zhang.

bpo-18893 [https://bugs.python.org/issue?@action=redirect&bpo=18893]: Fix invalid exception handling in Lib/ctypes/macholib/dyld.py. Patch by Madison May.

bpo-27611 [https://bugs.python.org/issue?@action=redirect&bpo=27611]: Fixed support of default root window in the tkinter.tix module.

bpo-27348 [https://bugs.python.org/issue?@action=redirect&bpo=27348]: In the traceback module, restore the formatting of exception messages like “Exception: None”. This fixes a regression introduced in 3.5a2.

bpo-25651 [https://bugs.python.org/issue?@action=redirect&bpo=25651]: Allow falsy values to be used for msg parameter of subTest().

bpo-27932 [https://bugs.python.org/issue?@action=redirect&bpo=27932]: Prevent memory leak in win32_ver().

Fix UnboundLocalError in socket._sendfile_use_sendfile.

bpo-28075 [https://bugs.python.org/issue?@action=redirect&bpo=28075]: Check for ERROR_ACCESS_DENIED in Windows implementation of os.stat(). Patch by Eryk Sun.

bpo-25270 [https://bugs.python.org/issue?@action=redirect&bpo=25270]: Prevent codecs.escape_encode() from raising SystemError when an empty bytestring is passed.

bpo-28181 [https://bugs.python.org/issue?@action=redirect&bpo=28181]: Get antigravity over HTTPS. Patch by Kaartic Sivaraam.

bpo-25895 [https://bugs.python.org/issue?@action=redirect&bpo=25895]: Enable WebSocket URL schemes in urllib.parse.urljoin. Patch by Gergely Imreh and Markus Holtermann.

bpo-27599 [https://bugs.python.org/issue?@action=redirect&bpo=27599]: Fixed buffer overrun in binascii.b2a_qp() and binascii.a2b_qp().

bpo-19003 [https://bugs.python.org/issue?@action=redirect&bpo=19003]: m email.generator now replaces only \r and/or \n line endings, per the RFC, instead of all unicode line endings.

bpo-28019 [https://bugs.python.org/issue?@action=redirect&bpo=28019]: itertools.count() no longer rounds non-integer step in range between 1.0 and 2.0 to 1.

bpo-25969 [https://bugs.python.org/issue?@action=redirect&bpo=25969]: Update the lib2to3 grammar to handle the unpacking generalizations added in 3.5.

bpo-14977 [https://bugs.python.org/issue?@action=redirect&bpo=14977]: mailcap now respects the order of the lines in the mailcap files (“first match”), as required by RFC 1542. Patch by Michael Lazar.

bpo-24594 [https://bugs.python.org/issue?@action=redirect&bpo=24594]: Validates persist parameter when opening MSI database

bpo-17582 [https://bugs.python.org/issue?@action=redirect&bpo=17582]: xml.etree.ElementTree nows preserves whitespaces in attributes (Patch by Duane Griffin. Reviewed and approved by Stefan Behnel.)

bpo-28047 [https://bugs.python.org/issue?@action=redirect&bpo=28047]: Fixed calculation of line length used for the base64 CTE in the new email policies.

bpo-27445 [https://bugs.python.org/issue?@action=redirect&bpo=27445]: Don’t pass str(_charset) to MIMEText.set_payload(). Patch by Claude Paroz.

bpo-22450 [https://bugs.python.org/issue?@action=redirect&bpo=22450]: urllib now includes an Accept: */* header among the default headers. This makes the results of REST API requests more consistent and predictable especially when proxy servers are involved.

lib2to3.pgen3.driver.load_grammar() now creates a stable cache file between runs given the same Grammar.txt input regardless of the hash randomization setting.

bpo-27570 [https://bugs.python.org/issue?@action=redirect&bpo=27570]: Avoid zero-length memcpy() etc calls with null source pointers in the “ctypes” and “array” modules.

bpo-22233 [https://bugs.python.org/issue?@action=redirect&bpo=22233]: Break email header lines only on the RFC specified CR and LF characters, not on arbitrary unicode line breaks. This also fixes a bug in HTTP header parsing.

bpo-27988 [https://bugs.python.org/issue?@action=redirect&bpo=27988]: Fix email iter_attachments incorrect mutation of payload list.

bpo-27691 [https://bugs.python.org/issue?@action=redirect&bpo=27691]: Fix ssl module’s parsing of GEN_RID subject alternative name fields in X.509 certs.

bpo-27850 [https://bugs.python.org/issue?@action=redirect&bpo=27850]: Remove 3DES from ssl module’s default cipher list to counter measure sweet32 attack (CVE-2016-2183).

bpo-27766 [https://bugs.python.org/issue?@action=redirect&bpo=27766]: Add ChaCha20 Poly1305 to ssl module’s default cipher list. (Required OpenSSL 1.1.0 or LibreSSL).

bpo-26470 [https://bugs.python.org/issue?@action=redirect&bpo=26470]: Port ssl and hashlib module to OpenSSL 1.1.0.

Remove support for passing a file descriptor to os.access. It never worked but previously didn’t raise.

bpo-12885 [https://bugs.python.org/issue?@action=redirect&bpo=12885]: Fix error when distutils encounters symlink.

bpo-27881 [https://bugs.python.org/issue?@action=redirect&bpo=27881]: Fixed possible bugs when setting sqlite3.Connection.isolation_level. Based on patch by Xiang Zhang.

bpo-27861 [https://bugs.python.org/issue?@action=redirect&bpo=27861]: Fixed a crash in sqlite3.Connection.cursor() when a factory creates not a cursor. Patch by Xiang Zhang.

bpo-19884 [https://bugs.python.org/issue?@action=redirect&bpo=19884]: Avoid spurious output on OS X with Gnu Readline.

bpo-27706 [https://bugs.python.org/issue?@action=redirect&bpo=27706]: Restore deterministic behavior of random.Random().seed() for string seeds using seeding version 1. Allows sequences of calls to random() to exactly match those obtained in Python 2. Patch by Nofar Schnider.

bpo-10513 [https://bugs.python.org/issue?@action=redirect&bpo=10513]: Fix a regression in Connection.commit(). Statements should not be reset after a commit.

A new version of typing.py from https://github.com/python/typing: Collection (only for 3.6) (bpo-27598 [https://bugs.python.org/issue?@action=redirect&bpo=27598]). Add FrozenSet to __all__ (upstream #261). Fix crash in _get_type_vars() (upstream #259). Remove the dict constraint in ForwardRef._eval_type (upstream #252).

bpo-27539 [https://bugs.python.org/issue?@action=redirect&bpo=27539]: Fix unnormalised Fraction.__pow__ result in the case of negative exponent and negative base.

bpo-21718 [https://bugs.python.org/issue?@action=redirect&bpo=21718]: cursor.description is now available for queries using CTEs.

bpo-2466 [https://bugs.python.org/issue?@action=redirect&bpo=2466]: posixpath.ismount now correctly recognizes mount points which the user does not have permission to access.

bpo-27773 [https://bugs.python.org/issue?@action=redirect&bpo=27773]: Correct some memory management errors server_hostname in _ssl.wrap_socket().

bpo-26750 [https://bugs.python.org/issue?@action=redirect&bpo=26750]: unittest.mock.create_autospec() now works properly for subclasses of property() and other data descriptors.

In the curses module, raise an error if window.getstr() or window.instr() is passed a negative value.

bpo-27783 [https://bugs.python.org/issue?@action=redirect&bpo=27783]: Fix possible usage of uninitialized memory in operator.methodcaller.

bpo-27774 [https://bugs.python.org/issue?@action=redirect&bpo=27774]: Fix possible Py_DECREF on unowned object in _sre.

bpo-27760 [https://bugs.python.org/issue?@action=redirect&bpo=27760]: Fix possible integer overflow in binascii.b2a_qp.

bpo-27758 [https://bugs.python.org/issue?@action=redirect&bpo=27758]: Fix possible integer overflow in the _csv module for large record lengths.

bpo-27568 [https://bugs.python.org/issue?@action=redirect&bpo=27568]: Prevent HTTPoxy attack (CVE-2016-1000110). Ignore the HTTP_PROXY variable when REQUEST_METHOD environment is set, which indicates that the script is in CGI mode.

bpo-27656 [https://bugs.python.org/issue?@action=redirect&bpo=27656]: Do not assume sched.h defines any SCHED_* constants.

bpo-27130 [https://bugs.python.org/issue?@action=redirect&bpo=27130]: In the “zlib” module, fix handling of large buffers (typically 4 GiB) when compressing and decompressing. Previously, inputs were limited to 4 GiB, and compression and decompression operations did not properly handle results of 4 GiB.

bpo-27533 [https://bugs.python.org/issue?@action=redirect&bpo=27533]: Release GIL in nt._isdir

bpo-17711 [https://bugs.python.org/issue?@action=redirect&bpo=17711]: Fixed unpickling by the persistent ID with protocol 0. Original patch by Alexandre Vassalotti.

bpo-27522 [https://bugs.python.org/issue?@action=redirect&bpo=27522]: Avoid an unintentional reference cycle in email.feedparser.

bpo-26844 [https://bugs.python.org/issue?@action=redirect&bpo=26844]: Fix error message for imp.find_module() to refer to ‘path’ instead of ‘name’. Patch by Lev Maximov.

bpo-23804 [https://bugs.python.org/issue?@action=redirect&bpo=23804]: Fix SSL zero-length recv() calls to not block and not raise an error about unclean EOF.

bpo-27466 [https://bugs.python.org/issue?@action=redirect&bpo=27466]: Change time format returned by http.cookie.time2netscape, confirming the netscape cookie format and making it consistent with documentation.

bpo-26664 [https://bugs.python.org/issue?@action=redirect&bpo=26664]: Fix activate.fish by removing mis-use of $.

bpo-22115 [https://bugs.python.org/issue?@action=redirect&bpo=22115]: Fixed tracing Tkinter variables: trace_vdelete() with wrong mode no longer break tracing, trace_vinfo() now always returns a list of pairs of strings, tracing in the “u” mode now works.

Fix a scoping issue in importlib.util.LazyLoader which triggered an UnboundLocalError when lazy-loading a module that was already put into sys.modules.

bpo-27079 [https://bugs.python.org/issue?@action=redirect&bpo=27079]: Fixed curses.ascii functions isblank(), iscntrl() and ispunct().

bpo-26754 [https://bugs.python.org/issue?@action=redirect&bpo=26754]: Some functions (compile() etc) accepted a filename argument encoded as an iterable of integers. Now only strings and byte-like objects are accepted.

bpo-27048 [https://bugs.python.org/issue?@action=redirect&bpo=27048]: Prevents distutils failing on Windows when environment variables contain non-ASCII characters

bpo-27330 [https://bugs.python.org/issue?@action=redirect&bpo=27330]: Fixed possible leaks in the ctypes module.

bpo-27238 [https://bugs.python.org/issue?@action=redirect&bpo=27238]: Got rid of bare excepts in the turtle module. Original patch by Jelle Zijlstra.

bpo-27122 [https://bugs.python.org/issue?@action=redirect&bpo=27122]: When an exception is raised within the context being managed by a contextlib.ExitStack() and one of the exit stack generators catches and raises it in a chain, do not re-raise the original exception when exiting, let the new chained one through. This avoids the PEP 479 bug described in issue25782.

Security

bpo-27278 [https://bugs.python.org/issue?@action=redirect&bpo=27278]: Fix os.urandom() implementation using getrandom() on Linux. Truncate size to INT_MAX and loop until we collected enough random bytes, instead of casting a directly Py_ssize_t to int.

Library

bpo-26386 [https://bugs.python.org/issue?@action=redirect&bpo=26386]: Fixed ttk.TreeView selection operations with item id’s containing spaces.

Security

bpo-22636 [https://bugs.python.org/issue?@action=redirect&bpo=22636]: Avoid shell injection problems with ctypes.util.find_library().

Library

bpo-16182 [https://bugs.python.org/issue?@action=redirect&bpo=16182]: Fix various functions in the “readline” module to use the locale encoding, and fix get_begidx() and get_endidx() to return code point indexes.

bpo-27392 [https://bugs.python.org/issue?@action=redirect&bpo=27392]: Add loop.connect_accepted_socket(). Patch by Jim Fulton.

bpo-27930 [https://bugs.python.org/issue?@action=redirect&bpo=27930]: Improved behaviour of logging.handlers.QueueListener. Thanks to Paulo Andrade and Petr Viktorin for the analysis and patch.

bpo-21201 [https://bugs.python.org/issue?@action=redirect&bpo=21201]: Improves readability of multiprocessing error message. Thanks to Wojciech Walczak for patch.

bpo-27456 [https://bugs.python.org/issue?@action=redirect&bpo=27456]: asyncio: Set TCP_NODELAY by default.

bpo-27906 [https://bugs.python.org/issue?@action=redirect&bpo=27906]: Fix socket accept exhaustion during high TCP traffic. Patch by Kevin Conway.

bpo-28174 [https://bugs.python.org/issue?@action=redirect&bpo=28174]: Handle when SO_REUSEPORT isn’t properly supported. Patch by Seth Michael Larson.

bpo-26654 [https://bugs.python.org/issue?@action=redirect&bpo=26654]: Inspect functools.partial in asyncio.Handle.__repr__. Patch by iceboy.

bpo-26909 [https://bugs.python.org/issue?@action=redirect&bpo=26909]: Fix slow pipes IO in asyncio. Patch by INADA Naoki.

bpo-28176 [https://bugs.python.org/issue?@action=redirect&bpo=28176]: Fix callbacks race in asyncio.SelectorLoop.sock_connect.

bpo-27759 [https://bugs.python.org/issue?@action=redirect&bpo=27759]: Fix selectors incorrectly retain invalid file descriptors. Patch by Mark Williams.

bpo-28368 [https://bugs.python.org/issue?@action=redirect&bpo=28368]: Refuse monitoring processes if the child watcher has no loop attached. Patch by Vincent Michel.

bpo-28369 [https://bugs.python.org/issue?@action=redirect&bpo=28369]: Raise RuntimeError when transport’s FD is used with add_reader, add_writer, etc.

bpo-28370 [https://bugs.python.org/issue?@action=redirect&bpo=28370]: Speedup asyncio.StreamReader.readexactly. Patch by Коренберг Марк.

bpo-28371 [https://bugs.python.org/issue?@action=redirect&bpo=28371]: Deprecate passing asyncio.Handles to run_in_executor.

bpo-28372 [https://bugs.python.org/issue?@action=redirect&bpo=28372]: Fix asyncio to support formatting of non-python coroutines.

bpo-28399 [https://bugs.python.org/issue?@action=redirect&bpo=28399]: Remove UNIX socket from FS before binding. Patch by Коренберг Марк.

bpo-27972 [https://bugs.python.org/issue?@action=redirect&bpo=27972]: Prohibit Tasks to await on themselves.

bpo-26923 [https://bugs.python.org/issue?@action=redirect&bpo=26923]: Fix asyncio.Gather to refuse being cancelled once all children are done. Patch by Johannes Ebke.

bpo-26796 [https://bugs.python.org/issue?@action=redirect&bpo=26796]: Don’t configure the number of workers for default threadpool executor. Initial patch by Hans Lawrenz.

bpo-28600 [https://bugs.python.org/issue?@action=redirect&bpo=28600]: Optimize loop.call_soon().

bpo-28613 [https://bugs.python.org/issue?@action=redirect&bpo=28613]: Fix get_event_loop() return the current loop if called from coroutines/callbacks.

bpo-28639 [https://bugs.python.org/issue?@action=redirect&bpo=28639]: Fix inspect.isawaitable to always return bool Patch by Justin Mayfield.

bpo-28652 [https://bugs.python.org/issue?@action=redirect&bpo=28652]: Make loop methods reject socket kinds they do not support.

bpo-28653 [https://bugs.python.org/issue?@action=redirect&bpo=28653]: Fix a refleak in functools.lru_cache.

bpo-28703 [https://bugs.python.org/issue?@action=redirect&bpo=28703]: Fix asyncio.iscoroutinefunction to handle Mock objects.

bpo-24142 [https://bugs.python.org/issue?@action=redirect&bpo=24142]: Reading a corrupt config file left the parser in an invalid state. Original patch by Florian Höch.

bpo-28990 [https://bugs.python.org/issue?@action=redirect&bpo=28990]: Fix SSL hanging if connection is closed before handshake completed. (Patch by HoHo-Ho)

IDLE

bpo-15308 [https://bugs.python.org/issue?@action=redirect&bpo=15308]: Add ‘interrupt execution’ (^C) to Shell menu. Patch by Roger Serwy, updated by Bayard Randel.

bpo-27922 [https://bugs.python.org/issue?@action=redirect&bpo=27922]: Stop IDLE tests from ‘flashing’ gui widgets on the screen.

Add version to title of IDLE help window.

bpo-25564 [https://bugs.python.org/issue?@action=redirect&bpo=25564]: In section on IDLE – console differences, mention that using exec means that __builtins__ is defined for each statement.

bpo-27714 [https://bugs.python.org/issue?@action=redirect&bpo=27714]: text_textview and test_autocomplete now pass when re-run in the same process. This occurs when test_idle fails when run with the -w option but without -jn. Fix warning from test_config.

bpo-25507 [https://bugs.python.org/issue?@action=redirect&bpo=25507]: IDLE no longer runs buggy code because of its tkinter imports. Users must include the same imports required to run directly in Python.

bpo-27452 [https://bugs.python.org/issue?@action=redirect&bpo=27452]: add line counter and crc to IDLE configHandler test dump.

bpo-27365 [https://bugs.python.org/issue?@action=redirect&bpo=27365]: Allow non-ascii chars in IDLE NEWS.txt, for contributor names.

bpo-27245 [https://bugs.python.org/issue?@action=redirect&bpo=27245]: IDLE: Cleanly delete custom themes and key bindings. Previously, when IDLE was started from a console or by import, a cascade of warnings was emitted. Patch by Serhiy Storchaka.

C API

bpo-28808 [https://bugs.python.org/issue?@action=redirect&bpo=28808]: PyUnicode_CompareWithASCIIString() now never raises exceptions.

bpo-26754 [https://bugs.python.org/issue?@action=redirect&bpo=26754]: PyUnicode_FSDecoder() accepted a filename argument encoded as an iterable of integers. Now only strings and bytes-like objects are accepted.

Documentation

bpo-28513 [https://bugs.python.org/issue?@action=redirect&bpo=28513]: Documented command-line interface of zipfile.

Tests

bpo-28950 [https://bugs.python.org/issue?@action=redirect&bpo=28950]: Disallow -j0 to be combined with -T/-l/-M in regrtest command line arguments.

bpo-28666 [https://bugs.python.org/issue?@action=redirect&bpo=28666]: Now test.support.rmtree is able to remove unwritable or unreadable directories.

bpo-23839 [https://bugs.python.org/issue?@action=redirect&bpo=23839]: Various caches now are cleared before running every test file.

bpo-28409 [https://bugs.python.org/issue?@action=redirect&bpo=28409]: regrtest: fix the parser of command line arguments.

bpo-27787 [https://bugs.python.org/issue?@action=redirect&bpo=27787]: Call gc.collect() before checking each test for “dangling threads”, since the dangling threads are weak references.

bpo-27369 [https://bugs.python.org/issue?@action=redirect&bpo=27369]: In test_pyexpat, avoid testing an error message detail that changed in Expat 2.2.0.

Tools/Demos

bpo-27952 [https://bugs.python.org/issue?@action=redirect&bpo=27952]: Get Tools/scripts/fixcid.py working with Python 3 and the current “re” module, avoid invalid Python backslash escapes, and fix a bug parsing escaped C quote signs.

bpo-27332 [https://bugs.python.org/issue?@action=redirect&bpo=27332]: Fixed the type of the first argument of module-level functions generated by Argument Clinic. Patch by Petr Viktorin.

bpo-27418 [https://bugs.python.org/issue?@action=redirect&bpo=27418]: Fixed Tools/importbench/importbench.py.

Windows

bpo-28251 [https://bugs.python.org/issue?@action=redirect&bpo=28251]: Improvements to help manuals on Windows.

bpo-28110 [https://bugs.python.org/issue?@action=redirect&bpo=28110]: launcher.msi has different product codes between 32-bit and 64-bit

bpo-25144 [https://bugs.python.org/issue?@action=redirect&bpo=25144]: Ensures TargetDir is set before continuing with custom install.

bpo-27469 [https://bugs.python.org/issue?@action=redirect&bpo=27469]: Adds a shell extension to the launcher so that drag and drop works correctly.

bpo-27309 [https://bugs.python.org/issue?@action=redirect&bpo=27309]: Enabled proper Windows styles in python[w].exe manifest.

Build

bpo-29080 [https://bugs.python.org/issue?@action=redirect&bpo=29080]: Removes hard dependency on hg.exe from PCBuild/build.bat

bpo-23903 [https://bugs.python.org/issue?@action=redirect&bpo=23903]: Added missed names to PC/python3.def.

bpo-10656 [https://bugs.python.org/issue?@action=redirect&bpo=10656]: Fix out-of-tree building on AIX. Patch by Tristan Carel and Michael Haubenwallner.

bpo-26359 [https://bugs.python.org/issue?@action=redirect&bpo=26359]: Rename –with-optimiations to –enable-optimizations.

bpo-28444 [https://bugs.python.org/issue?@action=redirect&bpo=28444]: Fix missing extensions modules when cross compiling.

bpo-28248 [https://bugs.python.org/issue?@action=redirect&bpo=28248]: Update Windows build and OS X installers to use OpenSSL 1.0.2j.

bpo-28258 [https://bugs.python.org/issue?@action=redirect&bpo=28258]: Fixed build with Estonian locale (python-config and distclean targets in Makefile). Patch by Arfrever Frehtes Taifersar Arahesis.

bpo-26661 [https://bugs.python.org/issue?@action=redirect&bpo=26661]: setup.py now detects system libffi with multiarch wrapper.

bpo-28066 [https://bugs.python.org/issue?@action=redirect&bpo=28066]: Fix the logic that searches build directories for generated include files when building outside the source tree.

bpo-15819 [https://bugs.python.org/issue?@action=redirect&bpo=15819]: Remove redundant include search directory option for building outside the source tree.

bpo-27566 [https://bugs.python.org/issue?@action=redirect&bpo=27566]: Fix clean target in freeze makefile (patch by Lisa Roach)

bpo-27705 [https://bugs.python.org/issue?@action=redirect&bpo=27705]: Update message in validate_ucrtbase.py

bpo-27983 [https://bugs.python.org/issue?@action=redirect&bpo=27983]: Cause lack of llvm-profdata tool when using clang as required for PGO linking to be a configure time error rather than make time when –with-optimizations is enabled. Also improve our ability to find the llvm-profdata tool on MacOS and some Linuxes.

bpo-26307 [https://bugs.python.org/issue?@action=redirect&bpo=26307]: The profile-opt build now applies PGO to the built-in modules.

bpo-26359 [https://bugs.python.org/issue?@action=redirect&bpo=26359]: Add the –with-optimizations configure flag.

bpo-27713 [https://bugs.python.org/issue?@action=redirect&bpo=27713]: Suppress spurious build warnings when updating importlib’s bootstrap files. Patch by Xiang Zhang

bpo-25825 [https://bugs.python.org/issue?@action=redirect&bpo=25825]: Correct the references to Modules/python.exp and ld_so_aix, which are required on AIX. This updates references to an installation path that was changed in 3.2a4, and undoes changed references to the build tree that were made in 3.5.0a1.

bpo-27453 [https://bugs.python.org/issue?@action=redirect&bpo=27453]: CPP invocation in configure must use CPPFLAGS. Patch by Chi Hsuan Yen.

bpo-27641 [https://bugs.python.org/issue?@action=redirect&bpo=27641]: The configure script now inserts comments into the makefile to prevent the pgen and _freeze_importlib executables from being cross-compiled.

bpo-26662 [https://bugs.python.org/issue?@action=redirect&bpo=26662]: Set PYTHON_FOR_GEN in configure as the Python program to be used for file generation during the build.

bpo-10910 [https://bugs.python.org/issue?@action=redirect&bpo=10910]: Avoid C++ compilation errors on FreeBSD and OS X. Also update FreedBSD version checks for the original ctype UTF-8 workaround.

bpo-28676 [https://bugs.python.org/issue?@action=redirect&bpo=28676]: Prevent missing ‘getentropy’ declaration warning on macOS. Patch by Gareth Rees.

Python 3.5.2 final

Release date: 2016-06-26

Core and Builtins

bpo-26930 [https://bugs.python.org/issue?@action=redirect&bpo=26930]: Update Windows builds to use OpenSSL 1.0.2h.

Tests

bpo-26867 [https://bugs.python.org/issue?@action=redirect&bpo=26867]: Ubuntu’s openssl OP_NO_SSLv3 is forced on by default; fix test.

IDLE

bpo-27365 [https://bugs.python.org/issue?@action=redirect&bpo=27365]: Allow non-ascii in idlelib/NEWS.txt - minimal part for 3.5.2.

Python 3.5.2 release candidate 1

Release date: 2016-06-12

Core and Builtins

bpo-27066 [https://bugs.python.org/issue?@action=redirect&bpo=27066]: Fixed SystemError if a custom opener (for open()) returns a negative number without setting an exception.

bpo-20041 [https://bugs.python.org/issue?@action=redirect&bpo=20041]: Fixed TypeError when frame.f_trace is set to None. Patch by Xavier de Gaye.

bpo-26168 [https://bugs.python.org/issue?@action=redirect&bpo=26168]: Fixed possible refleaks in failing Py_BuildValue() with the “N” format unit.

bpo-26991 [https://bugs.python.org/issue?@action=redirect&bpo=26991]: Fix possible refleak when creating a function with annotations.

bpo-27039 [https://bugs.python.org/issue?@action=redirect&bpo=27039]: Fixed bytearray.remove() for values greater than 127. Patch by Joe Jevnik.

bpo-23640 [https://bugs.python.org/issue?@action=redirect&bpo=23640]: int.from_bytes() no longer bypasses constructors for subclasses.

bpo-26811 [https://bugs.python.org/issue?@action=redirect&bpo=26811]: gc.get_objects() no longer contains a broken tuple with NULL pointer.

bpo-20120 [https://bugs.python.org/issue?@action=redirect&bpo=20120]: Use RawConfigParser for .pypirc parsing, removing support for interpolation unintentionally added with move to Python 3. Behavior no longer does any interpolation in .pypirc files, matching behavior in Python 2.7 and Setuptools 19.0.

bpo-26659 [https://bugs.python.org/issue?@action=redirect&bpo=26659]: Make the builtin slice type support cycle collection.

bpo-26718 [https://bugs.python.org/issue?@action=redirect&bpo=26718]: super.__init__ no longer leaks memory if called multiple times. NOTE: A direct call of super.__init__ is not endorsed!

bpo-25339 [https://bugs.python.org/issue?@action=redirect&bpo=25339]: PYTHONIOENCODING now has priority over locale in setting the error handler for stdin and stdout.

bpo-26494 [https://bugs.python.org/issue?@action=redirect&bpo=26494]: Fixed crash on iterating exhausting iterators. Affected classes are generic sequence iterators, iterators of str, bytes, bytearray, list, tuple, set, frozenset, dict, OrderedDict, corresponding views and os.scandir() iterator.

bpo-26581 [https://bugs.python.org/issue?@action=redirect&bpo=26581]: If coding cookie is specified multiple times on a line in Python source code file, only the first one is taken to account.

bpo-26464 [https://bugs.python.org/issue?@action=redirect&bpo=26464]: Fix str.translate() when string is ASCII and first replacements removes character, but next replacement uses a non-ASCII character or a string longer than 1 character. Regression introduced in Python 3.5.0.

bpo-22836 [https://bugs.python.org/issue?@action=redirect&bpo=22836]: Ensure exception reports from PyErr_Display() and PyErr_WriteUnraisable() are sensible even when formatting them produces secondary errors. This affects the reports produced by sys.__excepthook__() and when __del__() raises an exception.

bpo-26302 [https://bugs.python.org/issue?@action=redirect&bpo=26302]: Correct behavior to reject comma as a legal character for cookie names.

bpo-4806 [https://bugs.python.org/issue?@action=redirect&bpo=4806]: Avoid masking the original TypeError exception when using star (*) unpacking in function calls. Based on patch by Hagen Fürstenau and Daniel Urban.

bpo-27138 [https://bugs.python.org/issue?@action=redirect&bpo=27138]: Fix the doc comment for FileFinder.find_spec().

bpo-26154 [https://bugs.python.org/issue?@action=redirect&bpo=26154]: Add a new private _PyThreadState_UncheckedGet() function to get the current Python thread state, but don’t issue a fatal error if it is NULL. This new function must be used instead of accessing directly the _PyThreadState_Current variable. The variable is no more exposed since Python 3.5.1 to hide the exact implementation of atomic C types, to avoid compiler issues.

bpo-26194 [https://bugs.python.org/issue?@action=redirect&bpo=26194]: Deque.insert() gave odd results for bounded deques that had reached their maximum size. Now an IndexError will be raised when attempting to insert into a full deque.

bpo-25843 [https://bugs.python.org/issue?@action=redirect&bpo=25843]: When compiling code, don’t merge constants if they are equal but have a different types. For example, f1, f2 = lambda: 1, lambda: 1.0 is now correctly compiled to two different functions: f1() returns 1 (int) and f2() returns 1.0 (int), even if 1 and 1.0 are equal.

bpo-22995 [https://bugs.python.org/issue?@action=redirect&bpo=22995]: [UPDATE] Comment out the one of the pickleability tests in _PyObject_GetState() due to regressions observed in Cython-based projects.

bpo-25961 [https://bugs.python.org/issue?@action=redirect&bpo=25961]: Disallowed null characters in the type name.

bpo-25973 [https://bugs.python.org/issue?@action=redirect&bpo=25973]: Fix segfault when an invalid nonlocal statement binds a name starting with two underscores.

bpo-22995 [https://bugs.python.org/issue?@action=redirect&bpo=22995]: Instances of extension types with a state that aren’t subclasses of list or dict and haven’t implemented any pickle-related methods (__reduce__, __reduce_ex__, __getnewargs__, __getnewargs_ex__, or __getstate__), can no longer be pickled. Including memoryview.

bpo-20440 [https://bugs.python.org/issue?@action=redirect&bpo=20440]: Massive replacing unsafe attribute setting code with special macro Py_SETREF.

bpo-25766 [https://bugs.python.org/issue?@action=redirect&bpo=25766]: Special method __bytes__() now works in str subclasses.

bpo-25421 [https://bugs.python.org/issue?@action=redirect&bpo=25421]: __sizeof__ methods of builtin types now use dynamic basic size. This allows sys.getsize() to work correctly with their subclasses with __slots__ defined.

bpo-25709 [https://bugs.python.org/issue?@action=redirect&bpo=25709]: Fixed problem with in-place string concatenation and utf-8 cache.

bpo-27147 [https://bugs.python.org/issue?@action=redirect&bpo=27147]: Mention PEP 420 in the importlib docs.

bpo-24097 [https://bugs.python.org/issue?@action=redirect&bpo=24097]: Fixed crash in object.__reduce__() if slot name is freed inside __getattr__.

bpo-24731 [https://bugs.python.org/issue?@action=redirect&bpo=24731]: Fixed crash on converting objects with special methods __bytes__, __trunc__, and __float__ returning instances of subclasses of bytes, int, and float to subclasses of bytes, int, and float correspondingly.

bpo-26478 [https://bugs.python.org/issue?@action=redirect&bpo=26478]: Fix semantic bugs when using binary operators with dictionary views and tuples.

bpo-26171 [https://bugs.python.org/issue?@action=redirect&bpo=26171]: Fix possible integer overflow and heap corruption in zipimporter.get_data().

bpo-25660 [https://bugs.python.org/issue?@action=redirect&bpo=25660]: Fix TAB key behaviour in REPL with readline.

bpo-25887 [https://bugs.python.org/issue?@action=redirect&bpo=25887]: Raise a RuntimeError when a coroutine object is awaited more than once.

bpo-27243 [https://bugs.python.org/issue?@action=redirect&bpo=27243]: Update the __aiter__ protocol: instead of returning an awaitable that resolves to an asynchronous iterator, the asynchronous iterator should be returned directly. Doing the former will trigger a PendingDeprecationWarning.

Security

bpo-26556 [https://bugs.python.org/issue?@action=redirect&bpo=26556]: Update expat to 2.1.1, fixes CVE-2015-1283.

Fix TLS stripping vulnerability in smtplib, CVE-2016-0772. Reported by Team Oststrom

Library

bpo-21386 [https://bugs.python.org/issue?@action=redirect&bpo=21386]: Implement missing IPv4Address.is_global property. It was documented since 07a5610bae9d. Initial patch by Roger Luethi.

bpo-20900 [https://bugs.python.org/issue?@action=redirect&bpo=20900]: distutils register command now decodes HTTP responses correctly. Initial patch by ingrid.

A new version of typing.py provides several new classes and features: @overload outside stubs, Reversible, DefaultDict, Text, ContextManager, Type[], NewType(), TYPE_CHECKING, and numerous bug fixes (note that some of the new features are not yet implemented in mypy or other static analyzers). Also classes for PEP 492 (Awaitable, AsyncIterable, AsyncIterator) have been added (in fact they made it into 3.5.1 but were never mentioned).

bpo-25738 [https://bugs.python.org/issue?@action=redirect&bpo=25738]: Stop http.server.BaseHTTPRequestHandler.send_error() from sending a message body for 205 Reset Content. Also, don’t send Content header fields in responses that don’t have a body. Patch by Susumu Koshiba.

bpo-21313 [https://bugs.python.org/issue?@action=redirect&bpo=21313]: Fix the “platform” module to tolerate when sys.version contains truncated build information.

Security

bpo-26839 [https://bugs.python.org/issue?@action=redirect&bpo=26839]: On Linux, os.urandom() now calls getrandom() with GRND_NONBLOCK to fall back on reading /dev/urandom if the urandom entropy pool is not initialized yet. Patch written by Colm Buckley.

Library

bpo-27164 [https://bugs.python.org/issue?@action=redirect&bpo=27164]: In the zlib module, allow decompressing raw Deflate streams with a predefined zdict. Based on patch by Xiang Zhang.

bpo-24291 [https://bugs.python.org/issue?@action=redirect&bpo=24291]: Fix wsgiref.simple_server.WSGIRequestHandler to completely write data to the client. Previously it could do partial writes and truncate data. Also, wsgiref.handler.ServerHandler can now handle stdout doing partial writes, but this is deprecated.

bpo-26809 [https://bugs.python.org/issue?@action=redirect&bpo=26809]: Add __all__ to string. Patch by Emanuel Barry.

bpo-26373 [https://bugs.python.org/issue?@action=redirect&bpo=26373]: subprocess.Popen.communicate now correctly ignores BrokenPipeError when the child process dies before .communicate() is called in more/all circumstances.

bpo-21776 [https://bugs.python.org/issue?@action=redirect&bpo=21776]: distutils.upload now correctly handles HTTPError. Initial patch by Claudiu Popa.

bpo-27114 [https://bugs.python.org/issue?@action=redirect&bpo=27114]: Fix SSLContext._load_windows_store_certs fails with PermissionError

bpo-18383 [https://bugs.python.org/issue?@action=redirect&bpo=18383]: Avoid creating duplicate filters when using filterwarnings and simplefilter. Based on patch by Alex Shkop.

bpo-27057 [https://bugs.python.org/issue?@action=redirect&bpo=27057]: Fix os.set_inheritable() on Android, ioctl() is blocked by SELinux and fails with EACCESS. The function now falls back to fcntl(). Patch written by Michał Bednarski.

bpo-27014 [https://bugs.python.org/issue?@action=redirect&bpo=27014]: Fix infinite recursion using typing.py. Thanks to Kalle Tuure!

bpo-14132 [https://bugs.python.org/issue?@action=redirect&bpo=14132]: Fix urllib.request redirect handling when the target only has a query string. Original fix by Ján Janech.

bpo-17214 [https://bugs.python.org/issue?@action=redirect&bpo=17214]: The “urllib.request” module now percent-encodes non-ASCII bytes found in redirect target URLs. Some servers send Location header fields with non-ASCII bytes, but “http.client” requires the request target to be ASCII-encodable, otherwise a UnicodeEncodeError is raised. Based on patch by Christian Heimes.

bpo-26892 [https://bugs.python.org/issue?@action=redirect&bpo=26892]: Honor debuglevel flag in urllib.request.HTTPHandler. Patch contributed by Chi Hsuan Yen.

bpo-22274 [https://bugs.python.org/issue?@action=redirect&bpo=22274]: In the subprocess module, allow stderr to be redirected to stdout even when stdout is not redirected. Patch by Akira Li.

bpo-26807 [https://bugs.python.org/issue?@action=redirect&bpo=26807]: mock_open ‘files’ no longer error on readline at end of file. Patch from Yolanda Robla.

bpo-25745 [https://bugs.python.org/issue?@action=redirect&bpo=25745]: Fixed leaking a userptr in curses panel destructor.

bpo-26977 [https://bugs.python.org/issue?@action=redirect&bpo=26977]: Removed unnecessary, and ignored, call to sum of squares helper in statistics.pvariance.

bpo-26881 [https://bugs.python.org/issue?@action=redirect&bpo=26881]: The modulefinder module now supports extended opcode arguments.

bpo-23815 [https://bugs.python.org/issue?@action=redirect&bpo=23815]: Fixed crashes related to directly created instances of types in _tkinter and curses.panel modules.

bpo-17765 [https://bugs.python.org/issue?@action=redirect&bpo=17765]: weakref.ref() no longer silently ignores keyword arguments. Patch by Georg Brandl.

bpo-26873 [https://bugs.python.org/issue?@action=redirect&bpo=26873]: xmlrpc now raises ResponseError on unsupported type tags instead of silently return incorrect result.

bpo-26711 [https://bugs.python.org/issue?@action=redirect&bpo=26711]: Fixed the comparison of plistlib.Data with other types.

bpo-24114 [https://bugs.python.org/issue?@action=redirect&bpo=24114]: Fix an uninitialized variable in ctypes.util.

The bug only occurs on SunOS when the ctypes implementation searches for the crle program. Patch by Xiang Zhang. Tested on SunOS by Kees Bos.

bpo-26864 [https://bugs.python.org/issue?@action=redirect&bpo=26864]: In urllib.request, change the proxy bypass host checking against no_proxy to be case-insensitive, and to not match unrelated host names that happen to have a bypassed hostname as a suffix. Patch by Xiang Zhang.

bpo-26634 [https://bugs.python.org/issue?@action=redirect&bpo=26634]: recursive_repr() now sets __qualname__ of wrapper. Patch by Xiang Zhang.

bpo-26804 [https://bugs.python.org/issue?@action=redirect&bpo=26804]: urllib.request will prefer lower_case proxy environment variables over UPPER_CASE or Mixed_Case ones. Patch contributed by Hans-Peter Jansen.

bpo-26837 [https://bugs.python.org/issue?@action=redirect&bpo=26837]: assertSequenceEqual() now correctly outputs non-stringified differing items (like bytes in the -b mode). This affects assertListEqual() and assertTupleEqual().

bpo-26041 [https://bugs.python.org/issue?@action=redirect&bpo=26041]: Remove “will be removed in Python 3.7” from deprecation messages of platform.dist() and platform.linux_distribution(). Patch by Kumaripaba Miyurusara Athukorala.

bpo-26822 [https://bugs.python.org/issue?@action=redirect&bpo=26822]: itemgetter, attrgetter and methodcaller objects no longer silently ignore keyword arguments.

bpo-26733 [https://bugs.python.org/issue?@action=redirect&bpo=26733]: Disassembling a class now disassembles class and static methods. Patch by Xiang Zhang.

bpo-26801 [https://bugs.python.org/issue?@action=redirect&bpo=26801]: Fix error handling in shutil.get_terminal_size(), catch AttributeError instead of NameError. Patch written by Emanuel Barry.

bpo-24838 [https://bugs.python.org/issue?@action=redirect&bpo=24838]: tarfile’s ustar and gnu formats now correctly calculate name and link field limits for multibyte character encodings like utf-8.

Security

bpo-26657 [https://bugs.python.org/issue?@action=redirect&bpo=26657]: Fix directory traversal vulnerability with http.server on Windows. This fixes a regression that was introduced in 3.3.4rc1 and 3.4.0rc1. Based on patch by Philipp Hagemeister.

Library

bpo-26717 [https://bugs.python.org/issue?@action=redirect&bpo=26717]: Stop encoding Latin-1-ized WSGI paths with UTF-8. Patch by Anthony Sottile.

bpo-26735 [https://bugs.python.org/issue?@action=redirect&bpo=26735]: Fix os.urandom() on Solaris 11.3 and newer when reading more than 1,024 bytes: call getrandom() multiple times with a limit of 1024 bytes per call.

bpo-16329 [https://bugs.python.org/issue?@action=redirect&bpo=16329]: Add .webm to mimetypes.types_map. Patch by Giampaolo Rodola’.

bpo-13952 [https://bugs.python.org/issue?@action=redirect&bpo=13952]: Add .csv to mimetypes.types_map. Patch by Geoff Wilson.

bpo-26709 [https://bugs.python.org/issue?@action=redirect&bpo=26709]: Fixed Y2038 problem in loading binary PLists.

bpo-23735 [https://bugs.python.org/issue?@action=redirect&bpo=23735]: Handle terminal resizing with Readline 6.3+ by installing our own SIGWINCH handler. Patch by Eric Price.

bpo-26586 [https://bugs.python.org/issue?@action=redirect&bpo=26586]: In http.server, respond with “413 Request header fields too large” if there are too many header fields to parse, rather than killing the connection and raising an unhandled exception. Patch by Xiang Zhang.

bpo-22854 [https://bugs.python.org/issue?@action=redirect&bpo=22854]: Change BufferedReader.writable() and BufferedWriter.readable() to always return False.

bpo-25195 [https://bugs.python.org/issue?@action=redirect&bpo=25195]: Fix a regression in mock.MagicMock. _Call is a subclass of tuple (changeset 3603bae63c13 only works for classes) so we need to implement __ne__ ourselves. Patch by Andrew Plummer.

bpo-26644 [https://bugs.python.org/issue?@action=redirect&bpo=26644]: Raise ValueError rather than SystemError when a negative length is passed to SSLSocket.recv() or read().

bpo-23804 [https://bugs.python.org/issue?@action=redirect&bpo=23804]: Fix SSL recv(0) and read(0) methods to return zero bytes instead of up to 1024.

bpo-26616 [https://bugs.python.org/issue?@action=redirect&bpo=26616]: Fixed a bug in datetime.astimezone() method.

bpo-21925 [https://bugs.python.org/issue?@action=redirect&bpo=21925]: warnings.formatwarning() now catches exceptions on linecache.getline(...) to be able to log ResourceWarning emitted late during the Python shutdown process.

bpo-24266 [https://bugs.python.org/issue?@action=redirect&bpo=24266]: Ctrl+C during Readline history search now cancels the search mode when compiled with Readline 7.

bpo-26560 [https://bugs.python.org/issue?@action=redirect&bpo=26560]: Avoid potential ValueError in BaseHandler.start_response. Initial patch by Peter Inglesby.

Security

bpo-26313 [https://bugs.python.org/issue?@action=redirect&bpo=26313]: ssl.py _load_windows_store_certs fails if windows cert store is empty. Patch by Baji.

Library

bpo-26569 [https://bugs.python.org/issue?@action=redirect&bpo=26569]: Fix pyclbr.readmodule() and pyclbr.readmodule_ex() to support importing packages.

bpo-26499 [https://bugs.python.org/issue?@action=redirect&bpo=26499]: Account for remaining Content-Length in HTTPResponse.readline() and read1(). Based on patch by Silent Ghost. Also document that HTTPResponse now supports these methods.

bpo-25320 [https://bugs.python.org/issue?@action=redirect&bpo=25320]: Handle sockets in directories unittest discovery is scanning. Patch from Victor van den Elzen.

bpo-16181 [https://bugs.python.org/issue?@action=redirect&bpo=16181]: cookiejar.http2time() now returns None if year is higher than datetime.MAXYEAR.

bpo-26513 [https://bugs.python.org/issue?@action=redirect&bpo=26513]: Fixes platform module detection of Windows Server

bpo-23718 [https://bugs.python.org/issue?@action=redirect&bpo=23718]: Fixed parsing time in week 0 before Jan 1. Original patch by Tamás Bence Gedai.

bpo-20589 [https://bugs.python.org/issue?@action=redirect&bpo=20589]: Invoking Path.owner() and Path.group() on Windows now raise NotImplementedError instead of ImportError.

bpo-26177 [https://bugs.python.org/issue?@action=redirect&bpo=26177]: Fixed the keys() method for Canvas and Scrollbar widgets.

bpo-15068 [https://bugs.python.org/issue?@action=redirect&bpo=15068]: Got rid of excessive buffering in the fileinput module. The bufsize parameter is no longer used.

bpo-2202 [https://bugs.python.org/issue?@action=redirect&bpo=2202]: Fix UnboundLocalError in AbstractDigestAuthHandler.get_algorithm_impls. Initial patch by Mathieu Dupuy.

bpo-25718 [https://bugs.python.org/issue?@action=redirect&bpo=25718]: Fixed pickling and copying the accumulate() iterator with total is None.

bpo-26475 [https://bugs.python.org/issue?@action=redirect&bpo=26475]: Fixed debugging output for regular expressions with the (?x) flag.

bpo-26457 [https://bugs.python.org/issue?@action=redirect&bpo=26457]: Fixed the subnets() methods in IP network classes for the case when resulting prefix length is equal to maximal prefix length. Based on patch by Xiang Zhang.

bpo-26385 [https://bugs.python.org/issue?@action=redirect&bpo=26385]: Remove the file if the internal open() call in NamedTemporaryFile() fails. Patch by Silent Ghost.

bpo-26402 [https://bugs.python.org/issue?@action=redirect&bpo=26402]: Fix XML-RPC client to retry when the server shuts down a persistent connection. This was a regression related to the new http.client.RemoteDisconnected exception in 3.5.0a4.

bpo-25913 [https://bugs.python.org/issue?@action=redirect&bpo=25913]: Leading <~ is optional now in base64.a85decode() with adobe=True. Patch by Swati Jaiswal.

bpo-26186 [https://bugs.python.org/issue?@action=redirect&bpo=26186]: Remove an invalid type check in importlib.util.LazyLoader.

bpo-26367 [https://bugs.python.org/issue?@action=redirect&bpo=26367]: importlib.__import__() raises SystemError like builtins.__import__() when level is specified but without an accompanying package specified.

bpo-26309 [https://bugs.python.org/issue?@action=redirect&bpo=26309]: In the “socketserver” module, shut down the request (closing the connected socket) when verify_request() returns false. Patch by Aviv Palivoda.

Security

bpo-25939 [https://bugs.python.org/issue?@action=redirect&bpo=25939]: On Windows open the cert store readonly in ssl.enum_certificates.

Library

bpo-25995 [https://bugs.python.org/issue?@action=redirect&bpo=25995]: os.walk() no longer uses FDs proportional to the tree depth.

bpo-26117 [https://bugs.python.org/issue?@action=redirect&bpo=26117]: The os.scandir() iterator now closes file descriptor not only when the iteration is finished, but when it was failed with error.

bpo-25911 [https://bugs.python.org/issue?@action=redirect&bpo=25911]: Restored support of bytes paths in os.walk() on Windows.

bpo-26045 [https://bugs.python.org/issue?@action=redirect&bpo=26045]: Add UTF-8 suggestion to error message when posting a non-Latin-1 string with http.client.

bpo-12923 [https://bugs.python.org/issue?@action=redirect&bpo=12923]: Reset FancyURLopener’s redirect counter even if there is an exception. Based on patches by Brian Brazil and Daniel Rocco.

bpo-25945 [https://bugs.python.org/issue?@action=redirect&bpo=25945]: Fixed a crash when unpickle the functools.partial object with wrong state. Fixed a leak in failed functools.partial constructor. “args” and “keywords” attributes of functools.partial have now always types tuple and dict correspondingly.

bpo-26202 [https://bugs.python.org/issue?@action=redirect&bpo=26202]: copy.deepcopy() now correctly copies range() objects with non-atomic attributes.

bpo-23076 [https://bugs.python.org/issue?@action=redirect&bpo=23076]: Path.glob() now raises a ValueError if it’s called with an invalid pattern. Patch by Thomas Nyberg.

bpo-19883 [https://bugs.python.org/issue?@action=redirect&bpo=19883]: Fixed possible integer overflows in zipimport.

bpo-26227 [https://bugs.python.org/issue?@action=redirect&bpo=26227]: On Windows, getnameinfo(), gethostbyaddr() and gethostbyname_ex() functions of the socket module now decode the hostname from the ANSI code page rather than UTF-8.

bpo-26147 [https://bugs.python.org/issue?@action=redirect&bpo=26147]: xmlrpc now works with strings not encodable with used non-UTF-8 encoding.

bpo-25935 [https://bugs.python.org/issue?@action=redirect&bpo=25935]: Garbage collector now breaks reference loops with OrderedDict.

bpo-16620 [https://bugs.python.org/issue?@action=redirect&bpo=16620]: Fixed AttributeError in msilib.Directory.glob().

bpo-26013 [https://bugs.python.org/issue?@action=redirect&bpo=26013]: Added compatibility with broken protocol 2 pickles created in old Python 3 versions (3.4.3 and lower).

bpo-25850 [https://bugs.python.org/issue?@action=redirect&bpo=25850]: Use cross-compilation by default for 64-bit Windows.

bpo-17633 [https://bugs.python.org/issue?@action=redirect&bpo=17633]: Improve zipimport’s support for namespace packages.

bpo-24705 [https://bugs.python.org/issue?@action=redirect&bpo=24705]: Fix sysconfig._parse_makefile not expanding ${} vars appearing before $() vars.

bpo-22138 [https://bugs.python.org/issue?@action=redirect&bpo=22138]: Fix mock.patch behavior when patching descriptors. Restore original values after patching. Patch contributed by Sean McCully.

bpo-25672 [https://bugs.python.org/issue?@action=redirect&bpo=25672]: In the ssl module, enable the SSL_MODE_RELEASE_BUFFERS mode option if it is safe to do so.

bpo-26012 [https://bugs.python.org/issue?@action=redirect&bpo=26012]: Don’t traverse into symlinks for ** pattern in pathlib.Path.[r]glob().

bpo-24120 [https://bugs.python.org/issue?@action=redirect&bpo=24120]: Ignore PermissionError when traversing a tree with pathlib.Path.[r]glob(). Patch by Ulrich Petri.

bpo-25447 [https://bugs.python.org/issue?@action=redirect&bpo=25447]: fileinput now uses sys.stdin as-is if it does not have a buffer attribute (restores backward compatibility).

bpo-25447 [https://bugs.python.org/issue?@action=redirect&bpo=25447]: Copying the lru_cache() wrapper object now always works, independently from the type of the wrapped object (by returning the original object unchanged).

bpo-24103 [https://bugs.python.org/issue?@action=redirect&bpo=24103]: Fixed possible use after free in ElementTree.XMLPullParser.

bpo-25860 [https://bugs.python.org/issue?@action=redirect&bpo=25860]: os.fwalk() no longer skips remaining directories when error occurs. Original patch by Samson Lee.

bpo-25914 [https://bugs.python.org/issue?@action=redirect&bpo=25914]: Fixed and simplified OrderedDict.__sizeof__.

bpo-25902 [https://bugs.python.org/issue?@action=redirect&bpo=25902]: Fixed various refcount issues in ElementTree iteration.

bpo-25717 [https://bugs.python.org/issue?@action=redirect&bpo=25717]: Restore the previous behaviour of tolerating most fstat() errors when opening files. This was a regression in 3.5a1, and stopped anonymous temporary files from working in special cases.

bpo-24903 [https://bugs.python.org/issue?@action=redirect&bpo=24903]: Fix regression in number of arguments compileall accepts when ‘-d’ is specified. The check on the number of arguments has been dropped completely as it never worked correctly anyway.

bpo-25764 [https://bugs.python.org/issue?@action=redirect&bpo=25764]: In the subprocess module, preserve any exception caused by fork() failure when preexec_fn is used.

bpo-6478 [https://bugs.python.org/issue?@action=redirect&bpo=6478]: _strptime’s regexp cache now is reset after changing timezone with time.tzset().

bpo-14285 [https://bugs.python.org/issue?@action=redirect&bpo=14285]: When executing a package with the “python -m package” option, and package initialization fails, a proper traceback is now reported. The “runpy” module now lets exceptions from package initialization pass back to the caller, rather than raising ImportError.

bpo-19771 [https://bugs.python.org/issue?@action=redirect&bpo=19771]: Also in runpy and the “-m” option, omit the irrelevant message “… is a package and cannot be directly executed” if the package could not even be initialized (e.g. due to a bad *.pyc file).

bpo-25177 [https://bugs.python.org/issue?@action=redirect&bpo=25177]: Fixed problem with the mean of very small and very large numbers. As a side effect, statistics.mean and statistics.variance should be significantly faster.

bpo-25718 [https://bugs.python.org/issue?@action=redirect&bpo=25718]: Fixed copying object with state with boolean value is false.

bpo-10131 [https://bugs.python.org/issue?@action=redirect&bpo=10131]: Fixed deep copying of minidom documents. Based on patch by Marian Ganisin.

bpo-25725 [https://bugs.python.org/issue?@action=redirect&bpo=25725]: Fixed a reference leak in pickle.loads() when unpickling invalid data including tuple instructions.

bpo-25663 [https://bugs.python.org/issue?@action=redirect&bpo=25663]: In the Readline completer, avoid listing duplicate global names, and search the global namespace before searching builtins.

bpo-25688 [https://bugs.python.org/issue?@action=redirect&bpo=25688]: Fixed file leak in ElementTree.iterparse() raising an error.

bpo-23914 [https://bugs.python.org/issue?@action=redirect&bpo=23914]: Fixed SystemError raised by unpickler on broken pickle data.

bpo-25691 [https://bugs.python.org/issue?@action=redirect&bpo=25691]: Fixed crash on deleting ElementTree.Element attributes.

bpo-25624 [https://bugs.python.org/issue?@action=redirect&bpo=25624]: ZipFile now always writes a ZIP_STORED header for directory entries. Patch by Dingyuan Wang.

Skip getaddrinfo if host is already resolved. Patch by A. Jesse Jiryu Davis.

bpo-26050 [https://bugs.python.org/issue?@action=redirect&bpo=26050]: Add asyncio.StreamReader.readuntil() method. Patch by Марк Коренберг.

bpo-25924 [https://bugs.python.org/issue?@action=redirect&bpo=25924]: Avoid unnecessary serialization of getaddrinfo(3) calls on OS X versions 10.5 or higher. Original patch by A. Jesse Jiryu Davis.

bpo-26406 [https://bugs.python.org/issue?@action=redirect&bpo=26406]: Avoid unnecessary serialization of getaddrinfo(3) calls on current versions of OpenBSD and NetBSD. Patch by A. Jesse Jiryu Davis.

bpo-26848 [https://bugs.python.org/issue?@action=redirect&bpo=26848]: Fix asyncio/subprocess.communicate() to handle empty input. Patch by Jack O’Connor.

bpo-27040 [https://bugs.python.org/issue?@action=redirect&bpo=27040]: Add loop.get_exception_handler method

bpo-27041 [https://bugs.python.org/issue?@action=redirect&bpo=27041]: asyncio: Add loop.create_future method

bpo-27223 [https://bugs.python.org/issue?@action=redirect&bpo=27223]: asyncio: Fix _read_ready and _write_ready to respect _conn_lost. Patch by Łukasz Langa.

bpo-22970 [https://bugs.python.org/issue?@action=redirect&bpo=22970]: asyncio: Fix inconsistency cancelling Condition.wait. Patch by David Coles.

IDLE

bpo-5124 [https://bugs.python.org/issue?@action=redirect&bpo=5124]: Paste with text selected now replaces the selection on X11. This matches how paste works on Windows, Mac, most modern Linux apps, and ttk widgets. Original patch by Serhiy Storchaka.

bpo-24759 [https://bugs.python.org/issue?@action=redirect&bpo=24759]: Make clear in idlelib.idle_test.__init__ that the directory is a private implementation of test.test_idle and tool for maintainers.

bpo-27196 [https://bugs.python.org/issue?@action=redirect&bpo=27196]: Stop ‘ThemeChanged’ warnings when running IDLE tests. These persisted after other warnings were suppressed in #20567. Apply Serhiy Storchaka’s update_idletasks solution to four test files. Record this additional advice in idle_test/README.txt

bpo-20567 [https://bugs.python.org/issue?@action=redirect&bpo=20567]: Revise idle_test/README.txt with advice about avoiding tk warning messages from tests. Apply advice to several IDLE tests.

bpo-27117 [https://bugs.python.org/issue?@action=redirect&bpo=27117]: Make colorizer htest and turtledemo work with dark themes. Move code for configuring text widget colors to a new function.

bpo-26673 [https://bugs.python.org/issue?@action=redirect&bpo=26673]: When tk reports font size as 0, change to size 10. Such fonts on Linux prevented the configuration dialog from opening.

bpo-21939 [https://bugs.python.org/issue?@action=redirect&bpo=21939]: Add test for IDLE’s percolator. Original patch by Saimadhav Heblikar.

bpo-21676 [https://bugs.python.org/issue?@action=redirect&bpo=21676]: Add test for IDLE’s replace dialog. Original patch by Saimadhav Heblikar.

bpo-18410 [https://bugs.python.org/issue?@action=redirect&bpo=18410]: Add test for IDLE’s search dialog. Original patch by Westley Martínez.

bpo-21703 [https://bugs.python.org/issue?@action=redirect&bpo=21703]: Add test for IDLE’s undo delegator. Original patch by Saimadhav Heblikar .

bpo-27044 [https://bugs.python.org/issue?@action=redirect&bpo=27044]: Add ConfigDialog.remove_var_callbacks to stop memory leaks.

bpo-23977 [https://bugs.python.org/issue?@action=redirect&bpo=23977]: Add more asserts to test_delegator.

bpo-20640 [https://bugs.python.org/issue?@action=redirect&bpo=20640]: Add tests for idlelib.configHelpSourceEdit. Patch by Saimadhav Heblikar.

In the ‘IDLE-console differences’ section of the IDLE doc, clarify how running with IDLE affects sys.modules and the standard streams.

bpo-25507 [https://bugs.python.org/issue?@action=redirect&bpo=25507]: fix incorrect change in IOBinding that prevented printing. Augment IOBinding htest to include all major IOBinding functions.

bpo-25905 [https://bugs.python.org/issue?@action=redirect&bpo=25905]: Revert unwanted conversion of ‘ to ’ RIGHT SINGLE QUOTATION MARK in README.txt and open this and NEWS.txt with ‘ascii’. Re-encode CREDITS.txt to utf-8 and open it with ‘utf-8’.

Documentation

bpo-19489 [https://bugs.python.org/issue?@action=redirect&bpo=19489]: Moved the search box from the sidebar to the header and footer of each page. Patch by Ammar Askar.

bpo-24136 [https://bugs.python.org/issue?@action=redirect&bpo=24136]: Document the new PEP 448 unpacking syntax of 3.5.

bpo-26736 [https://bugs.python.org/issue?@action=redirect&bpo=26736]: Used HTTPS for external links in the documentation if possible.

bpo-6953 [https://bugs.python.org/issue?@action=redirect&bpo=6953]: Rework the Readline module documentation to group related functions together, and add more details such as what underlying Readline functions and variables are accessed.

bpo-23606 [https://bugs.python.org/issue?@action=redirect&bpo=23606]: Adds note to ctypes documentation regarding cdll.msvcrt.

bpo-25500 [https://bugs.python.org/issue?@action=redirect&bpo=25500]: Fix documentation to not claim that __import__ is searched for in the global scope.

bpo-26014 [https://bugs.python.org/issue?@action=redirect&bpo=26014]: Update 3.x packaging documentation: * “See also” links to the new docs are now provided in the legacy pages * links to setuptools documentation have been updated

Tests

bpo-21916 [https://bugs.python.org/issue?@action=redirect&bpo=21916]: Added tests for the turtle module. Patch by ingrid, Gregory Loyse and Jelle Zijlstra.

bpo-26523 [https://bugs.python.org/issue?@action=redirect&bpo=26523]: The multiprocessing thread pool (multiprocessing.dummy.Pool) was untested.

bpo-26015 [https://bugs.python.org/issue?@action=redirect&bpo=26015]: Added new tests for pickling iterators of mutable sequences.

bpo-26325 [https://bugs.python.org/issue?@action=redirect&bpo=26325]: Added test.support.check_no_resource_warning() to check that no ResourceWarning is emitted.

bpo-25940 [https://bugs.python.org/issue?@action=redirect&bpo=25940]: Changed test_ssl to use self-signed.pythontest.net. This avoids relying on svn.python.org, which recently changed root certificate.

bpo-25616 [https://bugs.python.org/issue?@action=redirect&bpo=25616]: Tests for OrderedDict are extracted from test_collections into separate file test_ordered_dict.

bpo-26583 [https://bugs.python.org/issue?@action=redirect&bpo=26583]: Skip test_timestamp_overflow in test_import if bytecode files cannot be written.

Build

bpo-26884 [https://bugs.python.org/issue?@action=redirect&bpo=26884]: Fix linking extension modules for cross builds. Patch by Xavier de Gaye.

bpo-22359 [https://bugs.python.org/issue?@action=redirect&bpo=22359]: Disable the rules for running _freeze_importlib and pgen when cross-compiling. The output of these programs is normally saved with the source code anyway, and is still regenerated when doing a native build. Patch by Xavier de Gaye.

bpo-27229 [https://bugs.python.org/issue?@action=redirect&bpo=27229]: Fix the cross-compiling pgen rule for in-tree builds. Patch by Xavier de Gaye.

bpo-21668 [https://bugs.python.org/issue?@action=redirect&bpo=21668]: Link audioop, _datetime, _ctypes_test modules to libm, except on Mac OS X. Patch written by Xavier de Gaye.

bpo-25702 [https://bugs.python.org/issue?@action=redirect&bpo=25702]: A –with-lto configure option has been added that will enable link time optimizations at build time during a make profile-opt. Some compilers and toolchains are known to not produce stable code when using LTO, be sure to test things thoroughly before relying on it. It can provide a few % speed up over profile-opt alone.

bpo-26624 [https://bugs.python.org/issue?@action=redirect&bpo=26624]: Adds validation of ucrtbase[d].dll version with warning for old versions.

bpo-17603 [https://bugs.python.org/issue?@action=redirect&bpo=17603]: Avoid error about nonexistent fileblocks.o file by using a lower-level check for st_blocks in struct stat.

bpo-26079 [https://bugs.python.org/issue?@action=redirect&bpo=26079]: Fixing the build output folder for tix-8.4.3.6. Patch by Bjoern Thiel.

bpo-26465 [https://bugs.python.org/issue?@action=redirect&bpo=26465]: Update Windows builds to use OpenSSL 1.0.2g.

bpo-24421 [https://bugs.python.org/issue?@action=redirect&bpo=24421]: Compile Modules/_math.c once, before building extensions. Previously it could fail to compile properly if the math and cmath builds were concurrent.

bpo-25348 [https://bugs.python.org/issue?@action=redirect&bpo=25348]: Added --pgo and --pgo-job arguments to PCbuild\build.bat for building with Profile-Guided Optimization. The old PCbuild\build_pgo.bat script is now deprecated, and simply calls PCbuild\build.bat --pgo %*.

bpo-25827 [https://bugs.python.org/issue?@action=redirect&bpo=25827]: Add support for building with ICC to configure, including a new --with-icc flag.

bpo-25696 [https://bugs.python.org/issue?@action=redirect&bpo=25696]: Fix installation of Python on UNIX with make -j9.

bpo-26930 [https://bugs.python.org/issue?@action=redirect&bpo=26930]: Update OS X 10.5+ 32-bit-only installer to build and link with OpenSSL 1.0.2h.

bpo-26268 [https://bugs.python.org/issue?@action=redirect&bpo=26268]: Update Windows builds to use OpenSSL 1.0.2f.

bpo-25136 [https://bugs.python.org/issue?@action=redirect&bpo=25136]: Support Apple Xcode 7’s new textual SDK stub libraries.

bpo-24324 [https://bugs.python.org/issue?@action=redirect&bpo=24324]: Do not enable unreachable code warnings when using gcc as the option does not work correctly in older versions of gcc and has been silently removed as of gcc-4.5.

Windows

bpo-27053 [https://bugs.python.org/issue?@action=redirect&bpo=27053]: Updates make_zip.py to correctly generate library ZIP file.

bpo-26268 [https://bugs.python.org/issue?@action=redirect&bpo=26268]: Update the prepare_ssl.py script to handle OpenSSL releases that don’t include the contents of the include directory (that is, 1.0.2e and later).

bpo-26071 [https://bugs.python.org/issue?@action=redirect&bpo=26071]: bdist_wininst created binaries fail to start and find 32bit Python

bpo-26073 [https://bugs.python.org/issue?@action=redirect&bpo=26073]: Update the list of magic numbers in launcher

bpo-26065 [https://bugs.python.org/issue?@action=redirect&bpo=26065]: Excludes venv from library when generating embeddable distro.

Tools/Demos

bpo-26799 [https://bugs.python.org/issue?@action=redirect&bpo=26799]: Fix python-gdb.py: don’t get C types once when the Python code is loaded, but get C types on demand. The C types can change if python-gdb.py is loaded before the Python executable. Patch written by Thomas Ilsche.

bpo-26271 [https://bugs.python.org/issue?@action=redirect&bpo=26271]: Fix the Freeze tool to properly use flags passed through configure. Patch by Daniel Shaulov.

bpo-26489 [https://bugs.python.org/issue?@action=redirect&bpo=26489]: Add dictionary unpacking support to Tools/parser/unparse.py. Patch by Guo Ci Teo.

bpo-26316 [https://bugs.python.org/issue?@action=redirect&bpo=26316]: Fix variable name typo in Argument Clinic.

Windows

bpo-17500 [https://bugs.python.org/issue?@action=redirect&bpo=17500]: Remove unused and outdated icons. (See also: https://github.com/python/pythondotorg/issues/945)

Python 3.5.1 final

Release date: 2015-12-06

Core and Builtins

bpo-25709 [https://bugs.python.org/issue?@action=redirect&bpo=25709]: Fixed problem with in-place string concatenation and utf-8 cache.

Windows

bpo-25715 [https://bugs.python.org/issue?@action=redirect&bpo=25715]: Python 3.5.1 installer shows wrong upgrade path and incorrect logic for launcher detection.

Python 3.5.1 release candidate 1

Release date: 2015-11-22

Core and Builtins

bpo-25630 [https://bugs.python.org/issue?@action=redirect&bpo=25630]: Fix a possible segfault during argument parsing in functions that accept filesystem paths.

bpo-23564 [https://bugs.python.org/issue?@action=redirect&bpo=23564]: Fixed a partially broken sanity check in the _posixsubprocess internals regarding how fds_to_pass were passed to the child. The bug had no actual impact as subprocess.py already avoided it.

bpo-25388 [https://bugs.python.org/issue?@action=redirect&bpo=25388]: Fixed tokenizer crash when processing undecodable source code with a null byte.

bpo-25462 [https://bugs.python.org/issue?@action=redirect&bpo=25462]: The hash of the key now is calculated only once in most operations in C implementation of OrderedDict.

bpo-22995 [https://bugs.python.org/issue?@action=redirect&bpo=22995]: Default implementation of __reduce__ and __reduce_ex__ now rejects builtin types with not defined __new__.

bpo-25555 [https://bugs.python.org/issue?@action=redirect&bpo=25555]: Fix parser and AST: fill lineno and col_offset of “arg” node when compiling AST from Python objects.

bpo-24802 [https://bugs.python.org/issue?@action=redirect&bpo=24802]: Avoid buffer overreads when int(), float(), compile(), exec() and eval() are passed bytes-like objects. These objects are not necessarily terminated by a null byte, but the functions assumed they were.

bpo-24726 [https://bugs.python.org/issue?@action=redirect&bpo=24726]: Fixed a crash and leaking NULL in repr() of OrderedDict that was mutated by direct calls of dict methods.

bpo-25449 [https://bugs.python.org/issue?@action=redirect&bpo=25449]: Iterating OrderedDict with keys with unstable hash now raises KeyError in C implementations as well as in Python implementation.

bpo-25395 [https://bugs.python.org/issue?@action=redirect&bpo=25395]: Fixed crash when highly nested OrderedDict structures were garbage collected.

bpo-25274 [https://bugs.python.org/issue?@action=redirect&bpo=25274]: sys.setrecursionlimit() now raises a RecursionError if the new recursion limit is too low depending at the current recursion depth. Modify also the “lower-water mark” formula to make it monotonic. This mark is used to decide when the overflowed flag of the thread state is reset.

bpo-24402 [https://bugs.python.org/issue?@action=redirect&bpo=24402]: Fix input() to prompt to the redirected stdout when sys.stdout.fileno() fails.

bpo-24806 [https://bugs.python.org/issue?@action=redirect&bpo=24806]: Prevent builtin types that are not allowed to be subclassed from being subclassed through multiple inheritance.

bpo-24848 [https://bugs.python.org/issue?@action=redirect&bpo=24848]: Fixed a number of bugs in UTF-7 decoding of misformed data.

bpo-25280 [https://bugs.python.org/issue?@action=redirect&bpo=25280]: Import trace messages emitted in verbose (-v) mode are no longer formatted twice.

bpo-25003 [https://bugs.python.org/issue?@action=redirect&bpo=25003]: On Solaris 11.3 or newer, os.urandom() now uses the getrandom() function instead of the getentropy() function. The getentropy() function is blocking to generate very good quality entropy, os.urandom() doesn’t need such high-quality entropy.

bpo-25182 [https://bugs.python.org/issue?@action=redirect&bpo=25182]: The stdprinter (used as sys.stderr before the io module is imported at startup) now uses the backslashreplace error handler.

bpo-25131 [https://bugs.python.org/issue?@action=redirect&bpo=25131]: Make the line number and column offset of set/dict literals and comprehensions correspond to the opening brace.

bpo-25150 [https://bugs.python.org/issue?@action=redirect&bpo=25150]: Hide the private _Py_atomic_xxx symbols from the public Python.h header to fix a compilation error with OpenMP. PyThreadState_GET() becomes an alias to PyThreadState_Get() to avoid ABI incompatibilities.

Library

bpo-25626 [https://bugs.python.org/issue?@action=redirect&bpo=25626]: Change three zlib functions to accept sizes that fit in Py_ssize_t, but internally cap those sizes to UINT_MAX. This resolves a regression in 3.5 where GzipFile.read() failed to read chunks larger than 2 or 4 GiB. The change affects the zlib.Decompress.decompress() max_length parameter, the zlib.decompress() bufsize parameter, and the zlib.Decompress.flush() length parameter.

bpo-25583 [https://bugs.python.org/issue?@action=redirect&bpo=25583]: Avoid incorrect errors raised by os.makedirs(exist_ok=True) when the OS gives priority to errors such as EACCES over EEXIST.

bpo-25593 [https://bugs.python.org/issue?@action=redirect&bpo=25593]: Change semantics of EventLoop.stop() in asyncio.

bpo-6973 [https://bugs.python.org/issue?@action=redirect&bpo=6973]: When we know a subprocess.Popen process has died, do not allow the send_signal(), terminate(), or kill() methods to do anything as they could potentially signal a different process.

bpo-25590 [https://bugs.python.org/issue?@action=redirect&bpo=25590]: In the Readline completer, only call getattr() once per attribute.

bpo-25498 [https://bugs.python.org/issue?@action=redirect&bpo=25498]: Fix a crash when garbage-collecting ctypes objects created by wrapping a memoryview. This was a regression made in 3.5a1. Based on patch by Eryksun.

bpo-25584 [https://bugs.python.org/issue?@action=redirect&bpo=25584]: Added “escape” to the __all__ list in the glob module.

bpo-25584 [https://bugs.python.org/issue?@action=redirect&bpo=25584]: Fixed recursive glob() with patterns starting with **.

bpo-25446 [https://bugs.python.org/issue?@action=redirect&bpo=25446]: Fix regression in smtplib’s AUTH LOGIN support.

bpo-18010 [https://bugs.python.org/issue?@action=redirect&bpo=18010]: Fix the pydoc web server’s module search function to handle exceptions from importing packages.

bpo-25554 [https://bugs.python.org/issue?@action=redirect&bpo=25554]: Got rid of circular references in regular expression parsing.

bpo-25510 [https://bugs.python.org/issue?@action=redirect&bpo=25510]: fileinput.FileInput.readline() now returns b’’ instead of ‘’ at the end if the FileInput was opened with binary mode. Patch by Ryosuke Ito.

bpo-25503 [https://bugs.python.org/issue?@action=redirect&bpo=25503]: Fixed inspect.getdoc() for inherited docstrings of properties. Original patch by John Mark Vandenberg.

bpo-25515 [https://bugs.python.org/issue?@action=redirect&bpo=25515]: Always use os.urandom as a source of randomness in uuid.uuid4.

bpo-21827 [https://bugs.python.org/issue?@action=redirect&bpo=21827]: Fixed textwrap.dedent() for the case when largest common whitespace is a substring of smallest leading whitespace. Based on patch by Robert Li.

bpo-25447 [https://bugs.python.org/issue?@action=redirect&bpo=25447]: The lru_cache() wrapper objects now can be copied and pickled (by returning the original object unchanged).

bpo-25390 [https://bugs.python.org/issue?@action=redirect&bpo=25390]: typing: Don’t crash on Union[str, Pattern].

bpo-25441 [https://bugs.python.org/issue?@action=redirect&bpo=25441]: asyncio: Raise error from drain() when socket is closed.

bpo-25410 [https://bugs.python.org/issue?@action=redirect&bpo=25410]: Cleaned up and fixed minor bugs in C implementation of OrderedDict.

bpo-25411 [https://bugs.python.org/issue?@action=redirect&bpo=25411]: Improved Unicode support in SMTPHandler through better use of the email package. Thanks to user simon04 for the patch.

bpo-25407 [https://bugs.python.org/issue?@action=redirect&bpo=25407]: Remove mentions of the formatter module being removed in Python 3.6.

bpo-25406 [https://bugs.python.org/issue?@action=redirect&bpo=25406]: Fixed a bug in C implementation of OrderedDict.move_to_end() that caused segmentation fault or hang in iterating after moving several items to the start of ordered dict.

bpo-25364 [https://bugs.python.org/issue?@action=redirect&bpo=25364]: zipfile now works in threads disabled builds.

bpo-25328 [https://bugs.python.org/issue?@action=redirect&bpo=25328]: smtpd’s SMTPChannel now correctly raises a ValueError if both decode_data and enable_SMTPUTF8 are set to true.

bpo-25316 [https://bugs.python.org/issue?@action=redirect&bpo=25316]: distutils raises OSError instead of DistutilsPlatformError when MSVC is not installed.

bpo-25380 [https://bugs.python.org/issue?@action=redirect&bpo=25380]: Fixed protocol for the STACK_GLOBAL opcode in pickletools.opcodes.

bpo-23972 [https://bugs.python.org/issue?@action=redirect&bpo=23972]: Updates asyncio datagram create method allowing reuseport and reuseaddr socket options to be set prior to binding the socket. Mirroring the existing asyncio create_server method the reuseaddr option for datagram sockets defaults to True if the O/S is ‘posix’ (except if the platform is Cygwin). Patch by Chris Laws.

bpo-25304 [https://bugs.python.org/issue?@action=redirect&bpo=25304]: Add asyncio.run_coroutine_threadsafe(). This lets you submit a coroutine to a loop from another thread, returning a concurrent.futures.Future. By Vincent Michel.

bpo-25232 [https://bugs.python.org/issue?@action=redirect&bpo=25232]: Fix CGIRequestHandler to split the query from the URL at the first question mark (?) rather than the last. Patch from Xiang Zhang.

bpo-24657 [https://bugs.python.org/issue?@action=redirect&bpo=24657]: Prevent CGIRequestHandler from collapsing slashes in the query part of the URL as if it were a path. Patch from Xiang Zhang.

bpo-24483 [https://bugs.python.org/issue?@action=redirect&bpo=24483]: C implementation of functools.lru_cache() now calculates key’s hash only once.

bpo-22958 [https://bugs.python.org/issue?@action=redirect&bpo=22958]: Constructor and update method of weakref.WeakValueDictionary now accept the self and the dict keyword arguments.

bpo-22609 [https://bugs.python.org/issue?@action=redirect&bpo=22609]: Constructor of collections.UserDict now accepts the self keyword argument.

bpo-25111 [https://bugs.python.org/issue?@action=redirect&bpo=25111]: Fixed comparison of traceback.FrameSummary.

bpo-25262 [https://bugs.python.org/issue?@action=redirect&bpo=25262]: Added support for BINBYTES8 opcode in Python implementation of unpickler. Highest 32 bits of 64-bit size for BINUNICODE8 and BINBYTES8 opcodes no longer silently ignored on 32-bit platforms in C implementation.

bpo-25034 [https://bugs.python.org/issue?@action=redirect&bpo=25034]: Fix string.Formatter problem with auto-numbering and nested format_specs. Patch by Anthon van der Neut.

bpo-25233 [https://bugs.python.org/issue?@action=redirect&bpo=25233]: Rewrite the guts of asyncio.Queue and asyncio.Semaphore to be more understandable and correct.

bpo-25203 [https://bugs.python.org/issue?@action=redirect&bpo=25203]: Failed readline.set_completer_delims() no longer left the module in inconsistent state.

bpo-23600 [https://bugs.python.org/issue?@action=redirect&bpo=23600]: Default implementation of tzinfo.fromutc() was returning wrong results in some cases.

bpo-23329 [https://bugs.python.org/issue?@action=redirect&bpo=23329]: Allow the ssl module to be built with older versions of LibreSSL.

Prevent overflow in _Unpickler_Read.

bpo-25047 [https://bugs.python.org/issue?@action=redirect&bpo=25047]: The XML encoding declaration written by Element Tree now respects the letter case given by the user. This restores the ability to write encoding names in uppercase like “UTF-8”, which worked in Python 2.

bpo-25135 [https://bugs.python.org/issue?@action=redirect&bpo=25135]: Make deque_clear() safer by emptying the deque before clearing. This helps avoid possible reentrancy issues.

bpo-19143 [https://bugs.python.org/issue?@action=redirect&bpo=19143]: platform module now reads Windows version from kernel32.dll to avoid compatibility shims.

bpo-25092 [https://bugs.python.org/issue?@action=redirect&bpo=25092]: Fix datetime.strftime() failure when errno was already set to EINVAL.

bpo-23517 [https://bugs.python.org/issue?@action=redirect&bpo=23517]: Fix rounding in fromtimestamp() and utcfromtimestamp() methods of datetime.datetime: microseconds are now rounded to nearest with ties going to nearest even integer (ROUND_HALF_EVEN), instead of being rounding towards minus infinity (ROUND_FLOOR). It’s important that these methods use the same rounding mode than datetime.timedelta to keep the property: (datetime(1970,1,1) + timedelta(seconds=t)) == datetime.utcfromtimestamp(t). It also the rounding mode used by round(float) for example.

bpo-25155 [https://bugs.python.org/issue?@action=redirect&bpo=25155]: Fix datetime.datetime.now() and datetime.datetime.utcnow() on Windows to support date after year 2038. It was a regression introduced in Python 3.5.0.

bpo-25108 [https://bugs.python.org/issue?@action=redirect&bpo=25108]: Omitted internal frames in traceback functions print_stack(), format_stack(), and extract_stack() called without arguments.

bpo-25118 [https://bugs.python.org/issue?@action=redirect&bpo=25118]: Fix a regression of Python 3.5.0 in os.waitpid() on Windows.

bpo-24684 [https://bugs.python.org/issue?@action=redirect&bpo=24684]: socket.socket.getaddrinfo() now calls PyUnicode_AsEncodedString() instead of calling the encode() method of the host, to handle correctly custom string with an encode() method which doesn’t return a byte string. The encoder of the IDNA codec is now called directly instead of calling the encode() method of the string.

bpo-25060 [https://bugs.python.org/issue?@action=redirect&bpo=25060]: Correctly compute stack usage of the BUILD_MAP opcode.

bpo-24857 [https://bugs.python.org/issue?@action=redirect&bpo=24857]: Comparing call_args to a long sequence now correctly returns a boolean result instead of raising an exception. Patch by A Kaptur.

bpo-23144 [https://bugs.python.org/issue?@action=redirect&bpo=23144]: Make sure that HTMLParser.feed() returns all the data, even when convert_charrefs is True.

bpo-24982 [https://bugs.python.org/issue?@action=redirect&bpo=24982]: shutil.make_archive() with the “zip” format now adds entries for directories (including empty directories) in ZIP file.

bpo-25019 [https://bugs.python.org/issue?@action=redirect&bpo=25019]: Fixed a crash caused by setting non-string key of expat parser. Based on patch by John Leitch.

bpo-16180 [https://bugs.python.org/issue?@action=redirect&bpo=16180]: Exit pdb if file has syntax error, instead of trapping user in an infinite loop. Patch by Xavier de Gaye.

bpo-24891 [https://bugs.python.org/issue?@action=redirect&bpo=24891]: Fix a race condition at Python startup if the file descriptor of stdin (0), stdout (1) or stderr (2) is closed while Python is creating sys.stdin, sys.stdout and sys.stderr objects. These attributes are now set to None if the creation of the object failed, instead of raising an OSError exception. Initial patch written by Marco Paolini.

bpo-24992 [https://bugs.python.org/issue?@action=redirect&bpo=24992]: Fix error handling and a race condition (related to garbage collection) in collections.OrderedDict constructor.

bpo-24881 [https://bugs.python.org/issue?@action=redirect&bpo=24881]: Fixed setting binary mode in Python implementation of FileIO on Windows and Cygwin. Patch from Akira Li.

bpo-25578 [https://bugs.python.org/issue?@action=redirect&bpo=25578]: Fix (another) memory leak in SSLSocket.getpeercer().

bpo-25530 [https://bugs.python.org/issue?@action=redirect&bpo=25530]: Disable the vulnerable SSLv3 protocol by default when creating ssl.SSLContext.

bpo-25569 [https://bugs.python.org/issue?@action=redirect&bpo=25569]: Fix memory leak in SSLSocket.getpeercert().

bpo-25471 [https://bugs.python.org/issue?@action=redirect&bpo=25471]: Sockets returned from accept() shouldn’t appear to be nonblocking.

bpo-25319 [https://bugs.python.org/issue?@action=redirect&bpo=25319]: When threading.Event is reinitialized, the underlying condition should use a regular lock rather than a recursive lock.

bpo-21112 [https://bugs.python.org/issue?@action=redirect&bpo=21112]: Fix regression in unittest.expectedFailure on subclasses. Patch from Berker Peksag.

bpo-24764 [https://bugs.python.org/issue?@action=redirect&bpo=24764]: cgi.FieldStorage.read_multi() now ignores the Content-Length header in part headers. Patch written by Peter Landry and reviewed by Pierre Quentel.

bpo-24913 [https://bugs.python.org/issue?@action=redirect&bpo=24913]: Fix overrun error in deque.index(). Found by John Leitch and Bryce Darling.

bpo-24774 [https://bugs.python.org/issue?@action=redirect&bpo=24774]: Fix docstring in http.server.test. Patch from Chiu-Hsiang Hsu.

bpo-21159 [https://bugs.python.org/issue?@action=redirect&bpo=21159]: Improve message in configparser.InterpolationMissingOptionError. Patch from Łukasz Langa.

bpo-20362 [https://bugs.python.org/issue?@action=redirect&bpo=20362]: Honour TestCase.longMessage correctly in assertRegex. Patch from Ilia Kurenkov.

bpo-23572 [https://bugs.python.org/issue?@action=redirect&bpo=23572]: Fixed functools.singledispatch on classes with falsy metaclasses. Patch by Ethan Furman.

asyncio: ensure_future() now accepts awaitable objects.

IDLE

bpo-15348 [https://bugs.python.org/issue?@action=redirect&bpo=15348]: Stop the debugger engine (normally in a user process) before closing the debugger window (running in the IDLE process). This prevents the RuntimeErrors that were being caught and ignored.

bpo-24455 [https://bugs.python.org/issue?@action=redirect&bpo=24455]: Prevent IDLE from hanging when a) closing the shell while the debugger is active (15347); b) closing the debugger with the [X] button (15348); and c) activating the debugger when already active (24455). The patch by Mark Roseman does this by making two changes. 1. Suspend and resume the gui.interaction method with the tcl vwait mechanism intended for this purpose (instead of root.mainloop & .quit). 2. In gui.run, allow any existing interaction to terminate first.

Change ‘The program’ to ‘Your program’ in an IDLE ‘kill program?’ message to make it clearer that the program referred to is the currently running user program, not IDLE itself.

bpo-24750 [https://bugs.python.org/issue?@action=redirect&bpo=24750]: Improve the appearance of the IDLE editor window status bar. Patch by Mark Roseman.

bpo-25313 [https://bugs.python.org/issue?@action=redirect&bpo=25313]: Change the handling of new built-in text color themes to better address the compatibility problem introduced by the addition of IDLE Dark. Consistently use the revised idleConf.CurrentTheme everywhere in idlelib.

bpo-24782 [https://bugs.python.org/issue?@action=redirect&bpo=24782]: Extension configuration is now a tab in the IDLE Preferences dialog rather than a separate dialog. The former tabs are now a sorted list. Patch by Mark Roseman.

bpo-22726 [https://bugs.python.org/issue?@action=redirect&bpo=22726]: Re-activate the config dialog help button with some content about the other buttons and the new IDLE Dark theme.

bpo-24820 [https://bugs.python.org/issue?@action=redirect&bpo=24820]: IDLE now has an ‘IDLE Dark’ built-in text color theme. It is more or less IDLE Classic inverted, with a cobalt blue background. Strings, comments, keywords, … are still green, red, orange, … . To use it with IDLEs released before November 2015, hit the ‘Save as New Custom Theme’ button and enter a new name, such as ‘Custom Dark’. The custom theme will work with any IDLE release, and can be modified.

bpo-25224 [https://bugs.python.org/issue?@action=redirect&bpo=25224]: README.txt is now an idlelib index for IDLE developers and curious users. The previous user content is now in the IDLE doc chapter. ‘IDLE’ now means ‘Integrated Development and Learning Environment’.

bpo-24820 [https://bugs.python.org/issue?@action=redirect&bpo=24820]: Users can now set breakpoint colors in Settings -> Custom Highlighting. Original patch by Mark Roseman.

bpo-24972 [https://bugs.python.org/issue?@action=redirect&bpo=24972]: Inactive selection background now matches active selection background, as configured by users, on all systems. Found items are now always highlighted on Windows. Initial patch by Mark Roseman.

bpo-24570 [https://bugs.python.org/issue?@action=redirect&bpo=24570]: Idle: make calltip and completion boxes appear on Macs affected by a tk regression. Initial patch by Mark Roseman.

bpo-24988 [https://bugs.python.org/issue?@action=redirect&bpo=24988]: Idle ScrolledList context menus (used in debugger) now work on Mac Aqua. Patch by Mark Roseman.

bpo-24801 [https://bugs.python.org/issue?@action=redirect&bpo=24801]: Make right-click for context menu work on Mac Aqua. Patch by Mark Roseman.

bpo-25173 [https://bugs.python.org/issue?@action=redirect&bpo=25173]: Associate tkinter messageboxes with a specific widget. For Mac OSX, make them a ‘sheet’. Patch by Mark Roseman.

bpo-25198 [https://bugs.python.org/issue?@action=redirect&bpo=25198]: Enhance the initial html viewer now used for Idle Help. Properly indent fixed-pitch text (patch by Mark Roseman). Give code snippet a very Sphinx-like light blueish-gray background. Re-use initial width and height set by users for shell and editor. When the Table of Contents (TOC) menu is used, put the section header at the top of the screen.

bpo-25225 [https://bugs.python.org/issue?@action=redirect&bpo=25225]: Condense and rewrite Idle doc section on text colors.

bpo-21995 [https://bugs.python.org/issue?@action=redirect&bpo=21995]: Explain some differences between IDLE and console Python.

bpo-22820 [https://bugs.python.org/issue?@action=redirect&bpo=22820]: Explain need for print when running file from Idle editor.

bpo-25224 [https://bugs.python.org/issue?@action=redirect&bpo=25224]: Doc: augment Idle feature list and no-subprocess section.

bpo-25219 [https://bugs.python.org/issue?@action=redirect&bpo=25219]: Update doc for Idle command line options. Some were missing and notes were not correct.

bpo-24861 [https://bugs.python.org/issue?@action=redirect&bpo=24861]: Most of idlelib is private and subject to change. Use idleib.idle.* to start Idle. See idlelib.__init__.__doc__.

bpo-25199 [https://bugs.python.org/issue?@action=redirect&bpo=25199]: Idle: add synchronization comments for future maintainers.

bpo-16893 [https://bugs.python.org/issue?@action=redirect&bpo=16893]: Replace help.txt with help.html for Idle doc display. The new idlelib/help.html is rstripped Doc/build/html/library/idle.html. It looks better than help.txt and will better document Idle as released. The tkinter html viewer that works for this file was written by Mark Roseman. The now unused EditorWindow.HelpDialog class and helt.txt file are deprecated.

bpo-24199 [https://bugs.python.org/issue?@action=redirect&bpo=24199]: Deprecate unused idlelib.idlever with possible removal in 3.6.

bpo-24790 [https://bugs.python.org/issue?@action=redirect&bpo=24790]: Remove extraneous code (which also create 2 & 3 conflicts).

Documentation

bpo-22558 [https://bugs.python.org/issue?@action=redirect&bpo=22558]: Add remaining doc links to source code for Python-coded modules. Patch by Yoni Lavi.

bpo-12067 [https://bugs.python.org/issue?@action=redirect&bpo=12067]: Rewrite Comparisons section in the Expressions chapter of the language reference. Some of the details of comparing mixed types were incorrect or ambiguous. NotImplemented is only relevant at a lower level than the Expressions chapter. Added details of comparing range() objects, and default behaviour and consistency suggestions for user-defined classes. Patch from Andy Maier.

bpo-24952 [https://bugs.python.org/issue?@action=redirect&bpo=24952]: Clarify the default size argument of stack_size() in the “threading” and “_thread” modules. Patch from Mattip.

bpo-23725 [https://bugs.python.org/issue?@action=redirect&bpo=23725]: Overhaul tempfile docs. Note deprecated status of mktemp. Patch from Zbigniew Jędrzejewski-Szmek.

bpo-24808 [https://bugs.python.org/issue?@action=redirect&bpo=24808]: Update the types of some PyTypeObject fields. Patch by Joseph Weston.

bpo-22812 [https://bugs.python.org/issue?@action=redirect&bpo=22812]: Fix unittest discovery examples. Patch from Pam McA’Nulty.

Tests

bpo-25449 [https://bugs.python.org/issue?@action=redirect&bpo=25449]: Added tests for OrderedDict subclasses.

bpo-25099 [https://bugs.python.org/issue?@action=redirect&bpo=25099]: Make test_compileall not fail when an entry on sys.path cannot be written to (commonly seen in administrative installs on Windows).

bpo-23919 [https://bugs.python.org/issue?@action=redirect&bpo=23919]: Prevents assert dialogs appearing in the test suite.

PCbuild\rt.bat now accepts an unlimited number of arguments to pass along to regrtest.py. Previously there was a limit of 9.

Build

bpo-24915 [https://bugs.python.org/issue?@action=redirect&bpo=24915]: Add LLVM support for PGO builds and use the test suite to generate the profile data. Initial patch by Alecsandru Patrascu of Intel.

bpo-24910 [https://bugs.python.org/issue?@action=redirect&bpo=24910]: Windows MSIs now have unique display names.

bpo-24986 [https://bugs.python.org/issue?@action=redirect&bpo=24986]: It is now possible to build Python on Windows without errors when external libraries are not available.

Windows

bpo-25450 [https://bugs.python.org/issue?@action=redirect&bpo=25450]: Updates shortcuts to start Python in installation directory.

bpo-25164 [https://bugs.python.org/issue?@action=redirect&bpo=25164]: Changes default all-users install directory to match per-user directory.

bpo-25143 [https://bugs.python.org/issue?@action=redirect&bpo=25143]: Improves installer error messages for unsupported platforms.

bpo-25163 [https://bugs.python.org/issue?@action=redirect&bpo=25163]: Display correct directory in installer when using non-default settings.

bpo-25361 [https://bugs.python.org/issue?@action=redirect&bpo=25361]: Disables use of SSE2 instructions in Windows 32-bit build

bpo-25089 [https://bugs.python.org/issue?@action=redirect&bpo=25089]: Adds logging to installer for case where launcher is not selected on upgrade.

bpo-25165 [https://bugs.python.org/issue?@action=redirect&bpo=25165]: Windows uninstallation should not remove launcher if other versions remain

bpo-25112 [https://bugs.python.org/issue?@action=redirect&bpo=25112]: py.exe launcher is missing icons

bpo-25102 [https://bugs.python.org/issue?@action=redirect&bpo=25102]: Windows installer does not precompile for -O or -OO.

bpo-25081 [https://bugs.python.org/issue?@action=redirect&bpo=25081]: Makes Back button in installer go back to upgrade page when upgrading.

bpo-25091 [https://bugs.python.org/issue?@action=redirect&bpo=25091]: Increases font size of the installer.

bpo-25126 [https://bugs.python.org/issue?@action=redirect&bpo=25126]: Clarifies that the non-web installer will download some components.

bpo-25213 [https://bugs.python.org/issue?@action=redirect&bpo=25213]: Restores requestedExecutionLevel to manifest to disable UAC virtualization.

bpo-25022 [https://bugs.python.org/issue?@action=redirect&bpo=25022]: Removed very outdated PC/example_nt/ directory.

Tools/Demos

bpo-25440 [https://bugs.python.org/issue?@action=redirect&bpo=25440]: Fix output of python-config –extension-suffix.

Python 3.5.0 final

Release date: 2015-09-13

Build

bpo-25071 [https://bugs.python.org/issue?@action=redirect&bpo=25071]: Windows installer should not require TargetDir parameter when installing quietly.

Python 3.5.0 release candidate 4

Release date: 2015-09-09

Library

bpo-25029 [https://bugs.python.org/issue?@action=redirect&bpo=25029]: Fixes MemoryError in test_strptime.

Build

bpo-25027 [https://bugs.python.org/issue?@action=redirect&bpo=25027]: Reverts partial-static build options and adds vcruntime140.dll to Windows installation.

Python 3.5.0 release candidate 3

Release date: 2015-09-07

Core and Builtins

bpo-24305 [https://bugs.python.org/issue?@action=redirect&bpo=24305]: Prevent import subsystem stack frames from being counted by the warnings.warn(stacklevel=) parameter.

bpo-24912 [https://bugs.python.org/issue?@action=redirect&bpo=24912]: Prevent __class__ assignment to immutable built-in objects.

bpo-24975 [https://bugs.python.org/issue?@action=redirect&bpo=24975]: Fix AST compilation for PEP 448 syntax.

Library

bpo-24917 [https://bugs.python.org/issue?@action=redirect&bpo=24917]: time_strftime() buffer over-read.

bpo-24748 [https://bugs.python.org/issue?@action=redirect&bpo=24748]: To resolve a compatibility problem found with py2exe and pywin32, imp.load_dynamic() once again ignores previously loaded modules to support Python modules replacing themselves with extension modules. Patch by Petr Viktorin.

bpo-24635 [https://bugs.python.org/issue?@action=redirect&bpo=24635]: Fixed a bug in typing.py where isinstance([], typing.Iterable) would return True once, then False on subsequent calls.

bpo-24989 [https://bugs.python.org/issue?@action=redirect&bpo=24989]: Fixed buffer overread in BytesIO.readline() if a position is set beyond size. Based on patch by John Leitch.

bpo-24913 [https://bugs.python.org/issue?@action=redirect&bpo=24913]: Fix overrun error in deque.index(). Found by John Leitch and Bryce Darling.

Python 3.5.0 release candidate 2

Release date: 2015-08-25

Core and Builtins

bpo-24769 [https://bugs.python.org/issue?@action=redirect&bpo=24769]: Interpreter now starts properly when dynamic loading is disabled. Patch by Petr Viktorin.

bpo-21167 [https://bugs.python.org/issue?@action=redirect&bpo=21167]: NAN operations are now handled correctly when python is compiled with ICC even if -fp-model strict is not specified.

bpo-24492 [https://bugs.python.org/issue?@action=redirect&bpo=24492]: A “package” lacking a __name__ attribute when trying to perform a from .. import ... statement will trigger an ImportError instead of an AttributeError.

Library

bpo-24847 [https://bugs.python.org/issue?@action=redirect&bpo=24847]: Removes vcruntime140.dll dependency from Tcl/Tk.

bpo-24839 [https://bugs.python.org/issue?@action=redirect&bpo=24839]: platform._syscmd_ver raises DeprecationWarning

bpo-24867 [https://bugs.python.org/issue?@action=redirect&bpo=24867]: Fix Task.get_stack() for ‘async def’ coroutines

Python 3.5.0 release candidate 1

Release date: 2015-08-09

Core and Builtins

bpo-24667 [https://bugs.python.org/issue?@action=redirect&bpo=24667]: Resize odict in all cases that the underlying dict resizes.

Library

bpo-24824 [https://bugs.python.org/issue?@action=redirect&bpo=24824]: Signatures of codecs.encode() and codecs.decode() now are compatible with pydoc.

bpo-24634 [https://bugs.python.org/issue?@action=redirect&bpo=24634]: Importing uuid should not try to load libc on Windows

bpo-24798 [https://bugs.python.org/issue?@action=redirect&bpo=24798]: _msvccompiler.py doesn’t properly support manifests

bpo-4395 [https://bugs.python.org/issue?@action=redirect&bpo=4395]: Better testing and documentation of binary operators. Patch by Martin Panter.

bpo-23973 [https://bugs.python.org/issue?@action=redirect&bpo=23973]: Update typing.py from GitHub repo.

bpo-23004 [https://bugs.python.org/issue?@action=redirect&bpo=23004]: mock_open() now reads binary data correctly when the type of read_data is bytes. Initial patch by Aaron Hill.

bpo-23888 [https://bugs.python.org/issue?@action=redirect&bpo=23888]: Handle fractional time in cookie expiry. Patch by ssh.

bpo-23652 [https://bugs.python.org/issue?@action=redirect&bpo=23652]: Make it possible to compile the select module against the libc headers from the Linux Standard Base, which do not include some EPOLL macros. Patch by Matt Frank.

bpo-22932 [https://bugs.python.org/issue?@action=redirect&bpo=22932]: Fix timezones in email.utils.formatdate. Patch from Dmitry Shachnev.

bpo-23779 [https://bugs.python.org/issue?@action=redirect&bpo=23779]: imaplib raises TypeError if authenticator tries to abort. Patch from Craig Holmquist.

bpo-23319 [https://bugs.python.org/issue?@action=redirect&bpo=23319]: Fix ctypes.BigEndianStructure, swap correctly bytes. Patch written by Matthieu Gautier.

bpo-23254 [https://bugs.python.org/issue?@action=redirect&bpo=23254]: Document how to close the TCPServer listening socket. Patch from Martin Panter.

bpo-19450 [https://bugs.python.org/issue?@action=redirect&bpo=19450]: Update Windows and OS X installer builds to use SQLite 3.8.11.

bpo-17527 [https://bugs.python.org/issue?@action=redirect&bpo=17527]: Add PATCH to wsgiref.validator. Patch from Luca Sbardella.

bpo-24791 [https://bugs.python.org/issue?@action=redirect&bpo=24791]: Fix grammar regression for call syntax: ‘g(*a or b)’.

IDLE

bpo-23672 [https://bugs.python.org/issue?@action=redirect&bpo=23672]: Allow Idle to edit and run files with astral chars in name. Patch by Mohd Sanad Zaki Rizvi.

bpo-24745 [https://bugs.python.org/issue?@action=redirect&bpo=24745]: Idle editor default font. Switch from Courier to platform-sensitive TkFixedFont. This should not affect current customized font selections. If there is a problem, edit $HOME/.idlerc/config-main.cfg and remove ‘fontxxx’ entries from [Editor Window]. Patch by Mark Roseman.

bpo-21192 [https://bugs.python.org/issue?@action=redirect&bpo=21192]: Idle editor. When a file is run, put its name in the restart bar. Do not print false prompts. Original patch by Adnan Umer.

bpo-13884 [https://bugs.python.org/issue?@action=redirect&bpo=13884]: Idle menus. Remove tearoff lines. Patch by Roger Serwy.

Documentation

bpo-24129 [https://bugs.python.org/issue?@action=redirect&bpo=24129]: Clarify the reference documentation for name resolution. This includes removing the assumption that readers will be familiar with the name resolution scheme Python used prior to the introduction of lexical scoping for function namespaces. Patch by Ivan Levkivskyi.

bpo-20769 [https://bugs.python.org/issue?@action=redirect&bpo=20769]: Improve reload() docs. Patch by Dorian Pula.

bpo-23589 [https://bugs.python.org/issue?@action=redirect&bpo=23589]: Remove duplicate sentence from the FAQ. Patch by Yongzhi Pan.

bpo-24729 [https://bugs.python.org/issue?@action=redirect&bpo=24729]: Correct IO tutorial to match implementation regarding encoding parameter to open function.

Tests

bpo-24751 [https://bugs.python.org/issue?@action=redirect&bpo=24751]: When running regrtest with the -w command line option, a test run is no longer marked as a failure if all tests succeed when re-run.

Python 3.5.0 beta 4

Release date: 2015-07-26

Core and Builtins

bpo-23573 [https://bugs.python.org/issue?@action=redirect&bpo=23573]: Restored optimization of bytes.rfind() and bytearray.rfind() for single-byte argument on Linux.

bpo-24569 [https://bugs.python.org/issue?@action=redirect&bpo=24569]: Make PEP 448 dictionary evaluation more consistent.

bpo-24583 [https://bugs.python.org/issue?@action=redirect&bpo=24583]: Fix crash when set is mutated while being updated.

bpo-24407 [https://bugs.python.org/issue?@action=redirect&bpo=24407]: Fix crash when dict is mutated while being updated.

bpo-24619 [https://bugs.python.org/issue?@action=redirect&bpo=24619]: New approach for tokenizing async/await. As a consequence, it is now possible to have one-line ‘async def foo(): await ..’ functions.

bpo-24687 [https://bugs.python.org/issue?@action=redirect&bpo=24687]: Plug refleak on SyntaxError in function parameters annotations.

bpo-15944 [https://bugs.python.org/issue?@action=redirect&bpo=15944]: memoryview: Allow arbitrary formats when casting to bytes. Patch by Martin Panter.

Library

bpo-23441 [https://bugs.python.org/issue?@action=redirect&bpo=23441]: rcompleter now prints a tab character instead of displaying possible completions for an empty word. Initial patch by Martin Sekera.

bpo-24683 [https://bugs.python.org/issue?@action=redirect&bpo=24683]: Fixed crashes in _json functions called with arguments of inappropriate type.

bpo-21697 [https://bugs.python.org/issue?@action=redirect&bpo=21697]: shutil.copytree() now correctly handles symbolic links that point to directories. Patch by Eduardo Seabra and Thomas Kluyver.

bpo-14373 [https://bugs.python.org/issue?@action=redirect&bpo=14373]: Fixed segmentation fault when gc.collect() is called during constructing lru_cache (C implementation).

bpo-24695 [https://bugs.python.org/issue?@action=redirect&bpo=24695]: Fix a regression in traceback.print_exception(). If exc_traceback is None we shouldn’t print a traceback header like described in the documentation.

bpo-24620 [https://bugs.python.org/issue?@action=redirect&bpo=24620]: Random.setstate() now validates the value of state last element.

bpo-22485 [https://bugs.python.org/issue?@action=redirect&bpo=22485]: Fixed an issue that caused inspect.getsource to return incorrect results on nested functions.

bpo-22153 [https://bugs.python.org/issue?@action=redirect&bpo=22153]: Improve unittest docs. Patch from Martin Panter and evilzero.

bpo-24580 [https://bugs.python.org/issue?@action=redirect&bpo=24580]: Symbolic group references to open group in re patterns now are explicitly forbidden as well as numeric group references.

bpo-24206 [https://bugs.python.org/issue?@action=redirect&bpo=24206]: Fixed __eq__ and __ne__ methods of inspect classes.

bpo-24631 [https://bugs.python.org/issue?@action=redirect&bpo=24631]: Fixed regression in the timeit module with multiline setup.

bpo-18622 [https://bugs.python.org/issue?@action=redirect&bpo=18622]: unittest.mock.mock_open().reset_mock would recurse infinitely. Patch from Nicola Palumbo and Laurent De Buyst.

bpo-23661 [https://bugs.python.org/issue?@action=redirect&bpo=23661]: unittest.mock side_effects can now be exceptions again. This was a regression vs Python 3.4. Patch from Ignacio Rossi

bpo-24608 [https://bugs.python.org/issue?@action=redirect&bpo=24608]: chunk.Chunk.read() now always returns bytes, not str.

bpo-18684 [https://bugs.python.org/issue?@action=redirect&bpo=18684]: Fixed reading out of the buffer in the re module.

bpo-24259 [https://bugs.python.org/issue?@action=redirect&bpo=24259]: tarfile now raises a ReadError if an archive is truncated inside a data segment.

bpo-15014 [https://bugs.python.org/issue?@action=redirect&bpo=15014]: SMTP.auth() and SMTP.login() now support RFC 4954’s optional initial-response argument to the SMTP AUTH command.

bpo-24669 [https://bugs.python.org/issue?@action=redirect&bpo=24669]: Fix inspect.getsource() for ‘async def’ functions. Patch by Kai Groner.

bpo-24688 [https://bugs.python.org/issue?@action=redirect&bpo=24688]: ast.get_docstring() for ‘async def’ functions.

Build

bpo-24603 [https://bugs.python.org/issue?@action=redirect&bpo=24603]: Update Windows builds and OS X 10.5 installer to use OpenSSL 1.0.2d.

Python 3.5.0 beta 3

Release date: 2015-07-05

Core and Builtins

bpo-24467 [https://bugs.python.org/issue?@action=redirect&bpo=24467]: Fixed possible buffer over-read in bytearray. The bytearray object now always allocates place for trailing null byte and it’s buffer now is always null-terminated.

Upgrade to Unicode 8.0.0.

bpo-24345 [https://bugs.python.org/issue?@action=redirect&bpo=24345]: Add Py_tp_finalize slot for the stable ABI.

bpo-24400 [https://bugs.python.org/issue?@action=redirect&bpo=24400]: Introduce a distinct type for PEP 492 coroutines; add types.CoroutineType, inspect.getcoroutinestate, inspect.getcoroutinelocals; coroutines no longer use CO_GENERATOR flag; sys.set_coroutine_wrapper works only for ‘async def’ coroutines; inspect.iscoroutine no longer uses collections.abc.Coroutine, it’s intended to test for pure ‘async def’ coroutines only; add new opcode: GET_YIELD_FROM_ITER; fix generators wrapper used in types.coroutine to be instance of collections.abc.Generator; collections.abc.Awaitable and collections.abc.Coroutine can no longer be used to detect generator-based coroutines–use inspect.isawaitable instead.

bpo-24450 [https://bugs.python.org/issue?@action=redirect&bpo=24450]: Add gi_yieldfrom to generators and cr_await to coroutines. Contributed by Benno Leslie and Yury Selivanov.

bpo-19235 [https://bugs.python.org/issue?@action=redirect&bpo=19235]: Add new RecursionError exception. Patch by Georg Brandl.

Library

bpo-21750 [https://bugs.python.org/issue?@action=redirect&bpo=21750]: mock_open.read_data can now be read from each instance, as it could in Python 3.3.

bpo-24552 [https://bugs.python.org/issue?@action=redirect&bpo=24552]: Fix use after free in an error case of the _pickle module.

bpo-24514 [https://bugs.python.org/issue?@action=redirect&bpo=24514]: tarfile now tolerates number fields consisting of only whitespace.

bpo-19176 [https://bugs.python.org/issue?@action=redirect&bpo=19176]: Fixed doctype() related bugs in C implementation of ElementTree. A deprecation warning no longer issued by XMLParser subclass with default doctype() method. Direct call of doctype() now issues a warning. Parser’s doctype() now is not called if target’s doctype() is called. Based on patch by Martin Panter.

bpo-20387 [https://bugs.python.org/issue?@action=redirect&bpo=20387]: Restore semantic round-trip correctness in tokenize/untokenize for tab-indented blocks.

bpo-24456 [https://bugs.python.org/issue?@action=redirect&bpo=24456]: Fixed possible buffer over-read in adpcm2lin() and lin2adpcm() functions of the audioop module.

bpo-24336 [https://bugs.python.org/issue?@action=redirect&bpo=24336]: The contextmanager decorator now works with functions with keyword arguments called “func” and “self”. Patch by Martin Panter.

bpo-24522 [https://bugs.python.org/issue?@action=redirect&bpo=24522]: Fix possible integer overflow in json accelerator module.

bpo-24489 [https://bugs.python.org/issue?@action=redirect&bpo=24489]: ensure a previously set C errno doesn’t disturb cmath.polar().

bpo-24408 [https://bugs.python.org/issue?@action=redirect&bpo=24408]: Fixed AttributeError in measure() and metrics() methods of tkinter.Font.

bpo-14373 [https://bugs.python.org/issue?@action=redirect&bpo=14373]: C implementation of functools.lru_cache() now can be used with methods.

bpo-24347 [https://bugs.python.org/issue?@action=redirect&bpo=24347]: Set KeyError if PyDict_GetItemWithError returns NULL.

bpo-24348 [https://bugs.python.org/issue?@action=redirect&bpo=24348]: Drop superfluous incref/decref.

bpo-24359 [https://bugs.python.org/issue?@action=redirect&bpo=24359]: Check for changed OrderedDict size during iteration.

bpo-24368 [https://bugs.python.org/issue?@action=redirect&bpo=24368]: Support keyword arguments in OrderedDict methods.

bpo-24362 [https://bugs.python.org/issue?@action=redirect&bpo=24362]: Simplify the C OrderedDict fast nodes resize logic.

bpo-24377 [https://bugs.python.org/issue?@action=redirect&bpo=24377]: Fix a ref leak in OrderedDict.__repr__.

bpo-24369 [https://bugs.python.org/issue?@action=redirect&bpo=24369]: Defend against key-changes during iteration.

Tests

bpo-24373 [https://bugs.python.org/issue?@action=redirect&bpo=24373]: _testmultiphase and xxlimited now use tp_traverse and tp_finalize to avoid reference leaks encountered when combining tp_dealloc with PyType_FromSpec (see bpo-16690 [https://bugs.python.org/issue?@action=redirect&bpo=16690] for details)

Documentation

bpo-24458 [https://bugs.python.org/issue?@action=redirect&bpo=24458]: Update documentation to cover multi-phase initialization for extension modules (PEP 489). Patch by Petr Viktorin.

bpo-24351 [https://bugs.python.org/issue?@action=redirect&bpo=24351]: Clarify what is meant by “identifier” in the context of string.Template instances.

Build

bpo-24432 [https://bugs.python.org/issue?@action=redirect&bpo=24432]: Update Windows builds and OS X 10.5 installer to use OpenSSL 1.0.2c.

Python 3.5.0 beta 2

Release date: 2015-05-31

Core and Builtins

bpo-24284 [https://bugs.python.org/issue?@action=redirect&bpo=24284]: The startswith and endswith methods of the str class no longer return True when finding the empty string and the indexes are completely out of range.

bpo-24115 [https://bugs.python.org/issue?@action=redirect&bpo=24115]: Update uses of PyObject_IsTrue(), PyObject_Not(), PyObject_IsInstance(), PyObject_RichCompareBool() and _PyDict_Contains() to check for and handle errors correctly.

bpo-24328 [https://bugs.python.org/issue?@action=redirect&bpo=24328]: Fix importing one character extension modules.

bpo-11205 [https://bugs.python.org/issue?@action=redirect&bpo=11205]: In dictionary displays, evaluate the key before the value.

bpo-24285 [https://bugs.python.org/issue?@action=redirect&bpo=24285]: Fixed regression that prevented importing extension modules from inside packages. Patch by Petr Viktorin.

Library

bpo-23247 [https://bugs.python.org/issue?@action=redirect&bpo=23247]: Fix a crash in the StreamWriter.reset() of CJK codecs.

bpo-24270 [https://bugs.python.org/issue?@action=redirect&bpo=24270]: Add math.isclose() and cmath.isclose() functions as per PEP 485. Contributed by Chris Barker and Tal Einat.

bpo-5633 [https://bugs.python.org/issue?@action=redirect&bpo=5633]: Fixed timeit when the statement is a string and the setup is not.

bpo-24326 [https://bugs.python.org/issue?@action=redirect&bpo=24326]: Fixed audioop.ratecv() with non-default weightB argument. Original patch by David Moore.

bpo-16991 [https://bugs.python.org/issue?@action=redirect&bpo=16991]: Add a C implementation of OrderedDict.

bpo-23934 [https://bugs.python.org/issue?@action=redirect&bpo=23934]: Fix inspect.signature to fail correctly for builtin types lacking signature information. Initial patch by James Powell.

Python 3.5.0 beta 1

Release date: 2015-05-24

Core and Builtins

bpo-24276 [https://bugs.python.org/issue?@action=redirect&bpo=24276]: Fixed optimization of property descriptor getter.

bpo-24268 [https://bugs.python.org/issue?@action=redirect&bpo=24268]: PEP 489: Multi-phase extension module initialization. Patch by Petr Viktorin.

bpo-23955 [https://bugs.python.org/issue?@action=redirect&bpo=23955]: Add pyvenv.cfg option to suppress registry/environment lookup for generating sys.path on Windows.

bpo-24257 [https://bugs.python.org/issue?@action=redirect&bpo=24257]: Fixed system error in the comparison of faked types.SimpleNamespace.

bpo-22939 [https://bugs.python.org/issue?@action=redirect&bpo=22939]: Fixed integer overflow in iterator object. Patch by Clement Rouault.

bpo-23985 [https://bugs.python.org/issue?@action=redirect&bpo=23985]: Fix a possible buffer overrun when deleting a slice from the front of a bytearray and then appending some other bytes data.

bpo-24102 [https://bugs.python.org/issue?@action=redirect&bpo=24102]: Fixed exception type checking in standard error handlers.

bpo-15027 [https://bugs.python.org/issue?@action=redirect&bpo=15027]: The UTF-32 encoder is now 3x to 7x faster.

bpo-23290 [https://bugs.python.org/issue?@action=redirect&bpo=23290]: Optimize set_merge() for cases where the target is empty. (Contributed by Serhiy Storchaka.)

bpo-2292 [https://bugs.python.org/issue?@action=redirect&bpo=2292]: PEP 448: Additional Unpacking Generalizations.

bpo-24096 [https://bugs.python.org/issue?@action=redirect&bpo=24096]: Make warnings.warn_explicit more robust against mutation of the warnings.filters list.

bpo-23996 [https://bugs.python.org/issue?@action=redirect&bpo=23996]: Avoid a crash when a delegated generator raises an unnormalized StopIteration exception. Patch by Stefan Behnel.

bpo-23910 [https://bugs.python.org/issue?@action=redirect&bpo=23910]: Optimize property() getter calls. Patch by Joe Jevnik.

bpo-23911 [https://bugs.python.org/issue?@action=redirect&bpo=23911]: Move path-based importlib bootstrap code to a separate frozen module.

bpo-24192 [https://bugs.python.org/issue?@action=redirect&bpo=24192]: Fix namespace package imports.

bpo-24022 [https://bugs.python.org/issue?@action=redirect&bpo=24022]: Fix tokenizer crash when processing undecodable source code.

bpo-9951 [https://bugs.python.org/issue?@action=redirect&bpo=9951]: Added a hex() method to bytes, bytearray, and memoryview.

bpo-22906 [https://bugs.python.org/issue?@action=redirect&bpo=22906]: PEP 479: Change StopIteration handling inside generators.

bpo-24017 [https://bugs.python.org/issue?@action=redirect&bpo=24017]: PEP 492: Coroutines with async and await syntax.

Library

bpo-14373 [https://bugs.python.org/issue?@action=redirect&bpo=14373]: Added C implementation of functools.lru_cache(). Based on patches by Matt Joiner and Alexey Kachayev.

bpo-24230 [https://bugs.python.org/issue?@action=redirect&bpo=24230]: The tempfile module now accepts bytes for prefix, suffix and dir parameters and returns bytes in such situations (matching the os module APIs).

bpo-22189 [https://bugs.python.org/issue?@action=redirect&bpo=22189]: collections.UserString now supports __getnewargs__(), __rmod__(), casefold(), format_map(), isprintable(), and maketrans(). Patch by Joe Jevnik.

bpo-24244 [https://bugs.python.org/issue?@action=redirect&bpo=24244]: Prevents termination when an invalid format string is encountered on Windows in strftime.

bpo-23973 [https://bugs.python.org/issue?@action=redirect&bpo=23973]: PEP 484: Add the typing module.

bpo-23086 [https://bugs.python.org/issue?@action=redirect&bpo=23086]: The collections.abc.Sequence() abstract base class added start and stop parameters to the index() mixin. Patch by Devin Jeanpierre.

bpo-20035 [https://bugs.python.org/issue?@action=redirect&bpo=20035]: Replaced the tkinter._fix module used for setting up the Tcl/Tk environment on Windows with a private function in the _tkinter module that makes no permanent changes to the environment.

bpo-24257 [https://bugs.python.org/issue?@action=redirect&bpo=24257]: Fixed segmentation fault in sqlite3.Row constructor with faked cursor type.

bpo-15836 [https://bugs.python.org/issue?@action=redirect&bpo=15836]: assertRaises(), assertRaisesRegex(), assertWarns() and assertWarnsRegex() assertments now check the type of the first argument to prevent possible user error. Based on patch by Daniel Wagner-Hall.

bpo-9858 [https://bugs.python.org/issue?@action=redirect&bpo=9858]: Add missing method stubs to _io.RawIOBase. Patch by Laura Rupprecht.

bpo-22955 [https://bugs.python.org/issue?@action=redirect&bpo=22955]: attrgetter, itemgetter and methodcaller objects in the operator module now support pickling. Added readable and evaluable repr for these objects. Based on patch by Josh Rosenberg.

bpo-22107 [https://bugs.python.org/issue?@action=redirect&bpo=22107]: tempfile.gettempdir() and tempfile.mkdtemp() now try again when a directory with the chosen name already exists on Windows as well as on Unix. tempfile.mkstemp() now fails early if parent directory is not valid (not exists or is a file) on Windows.

bpo-23780 [https://bugs.python.org/issue?@action=redirect&bpo=23780]: Improved error message in os.path.join() with single argument.

bpo-6598 [https://bugs.python.org/issue?@action=redirect&bpo=6598]: Increased time precision and random number range in email.utils.make_msgid() to strengthen the uniqueness of the message ID.

bpo-24091 [https://bugs.python.org/issue?@action=redirect&bpo=24091]: Fixed various crashes in corner cases in C implementation of ElementTree.

bpo-21931 [https://bugs.python.org/issue?@action=redirect&bpo=21931]: msilib.FCICreate() now raises TypeError in the case of a bad argument instead of a ValueError with a bogus FCI error number. Patch by Jeffrey Armstrong.

bpo-13866 [https://bugs.python.org/issue?@action=redirect&bpo=13866]: quote_via argument added to urllib.parse.urlencode.

bpo-20098 [https://bugs.python.org/issue?@action=redirect&bpo=20098]: New mangle_from policy option for email, default True for compat32, but False for all other policies.

bpo-24211 [https://bugs.python.org/issue?@action=redirect&bpo=24211]: The email library now supports RFC 6532: it can generate headers using utf-8 instead of encoded words.

bpo-16314 [https://bugs.python.org/issue?@action=redirect&bpo=16314]: Added support for the LZMA compression in distutils.

bpo-21804 [https://bugs.python.org/issue?@action=redirect&bpo=21804]: poplib now supports RFC 6856 (UTF8).

bpo-18682 [https://bugs.python.org/issue?@action=redirect&bpo=18682]: Optimized pprint functions for builtin scalar types.

bpo-22027 [https://bugs.python.org/issue?@action=redirect&bpo=22027]: smtplib now supports RFC 6531 (SMTPUTF8).

bpo-23488 [https://bugs.python.org/issue?@action=redirect&bpo=23488]: Random generator objects now consume 2x less memory on 64-bit.

bpo-1322 [https://bugs.python.org/issue?@action=redirect&bpo=1322]: platform.dist() and platform.linux_distribution() functions are now deprecated. Initial patch by Vajrasky Kok.

bpo-22486 [https://bugs.python.org/issue?@action=redirect&bpo=22486]: Added the math.gcd() function. The fractions.gcd() function now is deprecated. Based on patch by Mark Dickinson.

bpo-24064 [https://bugs.python.org/issue?@action=redirect&bpo=24064]: Property() docstrings are now writeable. (Patch by Berker Peksag.)

bpo-22681 [https://bugs.python.org/issue?@action=redirect&bpo=22681]: Added support for the koi8_t encoding.

bpo-22682 [https://bugs.python.org/issue?@action=redirect&bpo=22682]: Added support for the kz1048 encoding.

bpo-23796 [https://bugs.python.org/issue?@action=redirect&bpo=23796]: peek and read1 methods of BufferedReader now raise ValueError if they called on a closed object. Patch by John Hergenroeder.

bpo-21795 [https://bugs.python.org/issue?@action=redirect&bpo=21795]: smtpd now supports the 8BITMIME extension whenever the new decode_data constructor argument is set to False.

bpo-24155 [https://bugs.python.org/issue?@action=redirect&bpo=24155]: optimize heapq.heapify() for better cache performance when heapifying large lists.

bpo-21800 [https://bugs.python.org/issue?@action=redirect&bpo=21800]: imaplib now supports RFC 5161 (enable), RFC 6855 (utf8/internationalized email) and automatically encodes non-ASCII usernames and passwords to UTF8.

bpo-20274 [https://bugs.python.org/issue?@action=redirect&bpo=20274]: When calling a _sqlite.Connection, it now complains if passed any keyword arguments. Previously it silently ignored them.

bpo-20274 [https://bugs.python.org/issue?@action=redirect&bpo=20274]: Remove ignored and erroneous “kwargs” parameters from three METH_VARARGS methods on _sqlite.Connection.

bpo-24134 [https://bugs.python.org/issue?@action=redirect&bpo=24134]: assertRaises(), assertRaisesRegex(), assertWarns() and assertWarnsRegex() checks now emits a deprecation warning when callable is None or keyword arguments except msg is passed in the context manager mode.

bpo-24018 [https://bugs.python.org/issue?@action=redirect&bpo=24018]: Add a collections.abc.Generator abstract base class. Contributed by Stefan Behnel.

bpo-23880 [https://bugs.python.org/issue?@action=redirect&bpo=23880]: Tkinter’s getint() and getdouble() now support Tcl_Obj. Tkinter’s getdouble() now supports any numbers (in particular int).

bpo-22619 [https://bugs.python.org/issue?@action=redirect&bpo=22619]: Added negative limit support in the traceback module. Based on patch by Dmitry Kazakov.

bpo-24094 [https://bugs.python.org/issue?@action=redirect&bpo=24094]: Fix possible crash in json.encode with poorly behaved dict subclasses.

bpo-9246 [https://bugs.python.org/issue?@action=redirect&bpo=9246]: On POSIX, os.getcwd() now supports paths longer than 1025 bytes. Patch written by William Orr.

bpo-17445 [https://bugs.python.org/issue?@action=redirect&bpo=17445]: add difflib.diff_bytes() to support comparison of byte strings (fixes a regression from Python 2).

bpo-23917 [https://bugs.python.org/issue?@action=redirect&bpo=23917]: Fall back to sequential compilation when ProcessPoolExecutor doesn’t exist. Patch by Claudiu Popa.

bpo-23008 [https://bugs.python.org/issue?@action=redirect&bpo=23008]: Fixed resolving attributes with boolean value is False in pydoc.

Fix asyncio issue 235: LifoQueue and PriorityQueue’s put didn’t increment unfinished tasks (this bug was introduced when JoinableQueue was merged with Queue).

bpo-23908 [https://bugs.python.org/issue?@action=redirect&bpo=23908]: os functions now reject paths with embedded null character on Windows instead of silently truncating them.

bpo-23728 [https://bugs.python.org/issue?@action=redirect&bpo=23728]: binascii.crc_hqx() could return an integer outside of the range 0-0xffff for empty data.

bpo-23887 [https://bugs.python.org/issue?@action=redirect&bpo=23887]: urllib.error.HTTPError now has a proper repr() representation. Patch by Berker Peksag.

asyncio: New event loop APIs: set_task_factory() and get_task_factory().

asyncio: async() function is deprecated in favour of ensure_future().

bpo-24178 [https://bugs.python.org/issue?@action=redirect&bpo=24178]: asyncio.Lock, Condition, Semaphore, and BoundedSemaphore support new ‘async with’ syntax. Contributed by Yury Selivanov.

bpo-24179 [https://bugs.python.org/issue?@action=redirect&bpo=24179]: Support ‘async for’ for asyncio.StreamReader. Contributed by Yury Selivanov.

bpo-24184 [https://bugs.python.org/issue?@action=redirect&bpo=24184]: Add AsyncIterator and AsyncIterable ABCs to collections.abc. Contributed by Yury Selivanov.

bpo-22547 [https://bugs.python.org/issue?@action=redirect&bpo=22547]: Implement informative __repr__ for inspect.BoundArguments. Contributed by Yury Selivanov.

bpo-24190 [https://bugs.python.org/issue?@action=redirect&bpo=24190]: Implement inspect.BoundArgument.apply_defaults() method. Contributed by Yury Selivanov.

bpo-20691 [https://bugs.python.org/issue?@action=redirect&bpo=20691]: Add ‘follow_wrapped’ argument to inspect.Signature.from_callable() and inspect.signature(). Contributed by Yury Selivanov.

bpo-24248 [https://bugs.python.org/issue?@action=redirect&bpo=24248]: Deprecate inspect.Signature.from_function() and inspect.Signature.from_builtin().

bpo-23898 [https://bugs.python.org/issue?@action=redirect&bpo=23898]: Fix inspect.classify_class_attrs() to support attributes with overloaded __eq__ and __bool__. Patch by Mike Bayer.

bpo-24298 [https://bugs.python.org/issue?@action=redirect&bpo=24298]: Fix inspect.signature() to correctly unwrap wrappers around bound methods.

IDLE

bpo-23184 [https://bugs.python.org/issue?@action=redirect&bpo=23184]: remove unused names and imports in idlelib. Initial patch by Al Sweigart.

Tests

bpo-21520 [https://bugs.python.org/issue?@action=redirect&bpo=21520]: test_zipfile no longer fails if the word ‘bad’ appears anywhere in the name of the current directory.

bpo-9517 [https://bugs.python.org/issue?@action=redirect&bpo=9517]: Move script_helper into the support package. Patch by Christie Wilson.

Documentation

bpo-22155 [https://bugs.python.org/issue?@action=redirect&bpo=22155]: Add File Handlers subsection with createfilehandler to tkinter doc. Remove obsolete example from FAQ. Patch by Martin Panter.

bpo-24029 [https://bugs.python.org/issue?@action=redirect&bpo=24029]: Document the name binding behavior for submodule imports.

bpo-24077 [https://bugs.python.org/issue?@action=redirect&bpo=24077]: Fix typo in man page for -I command option: -s, not -S

Tools/Demos

bpo-24000 [https://bugs.python.org/issue?@action=redirect&bpo=24000]: Improved Argument Clinic’s mapping of converters to legacy “format units”. Updated the documentation to match.

bpo-24001 [https://bugs.python.org/issue?@action=redirect&bpo=24001]: Argument Clinic converters now use accept={type} instead of types={‘type’} to specify the types the converter accepts.

bpo-23330 [https://bugs.python.org/issue?@action=redirect&bpo=23330]: h2py now supports arbitrary filenames in #include.

bpo-24031 [https://bugs.python.org/issue?@action=redirect&bpo=24031]: make patchcheck now supports git checkouts, too.

Python 3.5.0 alpha 4

Release date: 2015-04-19

Core and Builtins

bpo-22980 [https://bugs.python.org/issue?@action=redirect&bpo=22980]: Under Linux, GNU/KFreeBSD and the Hurd, C extensions now include the architecture triplet in the extension name, to make it easy to test builds for different ABIs in the same working tree. Under OS X, the extension name now includes PEP 3149-style information.

bpo-22631 [https://bugs.python.org/issue?@action=redirect&bpo=22631]: Added Linux-specific socket constant CAN_RAW_FD_FRAMES. Patch courtesy of Joe Jevnik.

bpo-23731 [https://bugs.python.org/issue?@action=redirect&bpo=23731]: Implement PEP 488: removal of .pyo files.

bpo-23726 [https://bugs.python.org/issue?@action=redirect&bpo=23726]: Don’t enable GC for user subclasses of non-GC types that don’t add any new fields. Patch by Eugene Toder.

bpo-23309 [https://bugs.python.org/issue?@action=redirect&bpo=23309]: Avoid a deadlock at shutdown if a daemon thread is aborted while it is holding a lock to a buffered I/O object, and the main thread tries to use the same I/O object (typically stdout or stderr). A fatal error is emitted instead.

bpo-22977 [https://bugs.python.org/issue?@action=redirect&bpo=22977]: Fixed formatting Windows error messages on Wine. Patch by Martin Panter.

bpo-23466 [https://bugs.python.org/issue?@action=redirect&bpo=23466]: %c, %o, %x, and %X in bytes formatting now raise TypeError on non-integer input.

bpo-24044 [https://bugs.python.org/issue?@action=redirect&bpo=24044]: Fix possible null pointer dereference in list.sort in out of memory conditions.

bpo-21354 [https://bugs.python.org/issue?@action=redirect&bpo=21354]: PyCFunction_New function is exposed by python DLL again.

Library

bpo-23840 [https://bugs.python.org/issue?@action=redirect&bpo=23840]: tokenize.open() now closes the temporary binary file on error to fix a resource warning.

bpo-16914 [https://bugs.python.org/issue?@action=redirect&bpo=16914]: new debuglevel 2 in smtplib adds timestamps to debug output.

bpo-7159 [https://bugs.python.org/issue?@action=redirect&bpo=7159]: urllib.request now supports sending auth credentials automatically after the first 401. This enhancement is a superset of the enhancement from bpo-19494 [https://bugs.python.org/issue?@action=redirect&bpo=19494] and supersedes that change.

bpo-23703 [https://bugs.python.org/issue?@action=redirect&bpo=23703]: Fix a regression in urljoin() introduced in 901e4e52b20a. Patch by Demian Brecht.

bpo-4254 [https://bugs.python.org/issue?@action=redirect&bpo=4254]: Adds _curses.update_lines_cols(). Patch by Arnon Yaari

bpo-19933 [https://bugs.python.org/issue?@action=redirect&bpo=19933]: Provide default argument for ndigits in round. Patch by Vajrasky Kok.

bpo-23193 [https://bugs.python.org/issue?@action=redirect&bpo=23193]: Add a numeric_owner parameter to tarfile.TarFile.extract and tarfile.TarFile.extractall. Patch by Michael Vogt and Eric Smith.

bpo-23342 [https://bugs.python.org/issue?@action=redirect&bpo=23342]: Add a subprocess.run() function than returns a CalledProcess instance for a more consistent API than the existing call* functions.

bpo-21217 [https://bugs.python.org/issue?@action=redirect&bpo=21217]: inspect.getsourcelines() now tries to compute the start and end lines from the code object, fixing an issue when a lambda function is used as decorator argument. Patch by Thomas Ballinger and Allison Kaptur.

bpo-24521 [https://bugs.python.org/issue?@action=redirect&bpo=24521]: Fix possible integer overflows in the pickle module.

bpo-22931 [https://bugs.python.org/issue?@action=redirect&bpo=22931]: Allow ‘[’ and ‘]’ in cookie values.

The keywords attribute of functools.partial is now always a dictionary.

bpo-23811 [https://bugs.python.org/issue?@action=redirect&bpo=23811]: Add missing newline to the PyCompileError error message. Patch by Alex Shkop.

bpo-21116 [https://bugs.python.org/issue?@action=redirect&bpo=21116]: Avoid blowing memory when allocating a multiprocessing shared array that’s larger than 50% of the available RAM. Patch by Médéric Boquien.

bpo-22982 [https://bugs.python.org/issue?@action=redirect&bpo=22982]: Improve BOM handling when seeking to multiple positions of a writable text file.

bpo-23464 [https://bugs.python.org/issue?@action=redirect&bpo=23464]: Removed deprecated asyncio JoinableQueue.

bpo-23529 [https://bugs.python.org/issue?@action=redirect&bpo=23529]: Limit the size of decompressed data when reading from GzipFile, BZ2File or LZMAFile. This defeats denial of service attacks using compressed bombs (i.e. compressed payloads which decompress to a huge size). Patch by Martin Panter and Nikolaus Rath.

bpo-21859 [https://bugs.python.org/issue?@action=redirect&bpo=21859]: Added Python implementation of io.FileIO.

bpo-23865 [https://bugs.python.org/issue?@action=redirect&bpo=23865]: close() methods in multiple modules now are idempotent and more robust at shutdown. If they need to release multiple resources, all are released even if errors occur.

bpo-23400 [https://bugs.python.org/issue?@action=redirect&bpo=23400]: Raise same exception on both Python 2 and 3 if sem_open is not available. Patch by Davin Potts.

bpo-10838 [https://bugs.python.org/issue?@action=redirect&bpo=10838]: The subprocess now module includes SubprocessError and TimeoutError in its list of exported names for the users wild enough to use from subprocess import *.

bpo-23411 [https://bugs.python.org/issue?@action=redirect&bpo=23411]: Added DefragResult, ParseResult, SplitResult, DefragResultBytes, ParseResultBytes, and SplitResultBytes to urllib.parse.__all__. Patch by Martin Panter.

bpo-23881 [https://bugs.python.org/issue?@action=redirect&bpo=23881]: urllib.request.ftpwrapper constructor now closes the socket if the FTP connection failed to fix a ResourceWarning.

bpo-23853 [https://bugs.python.org/issue?@action=redirect&bpo=23853]: socket.socket.sendall() does no more reset the socket timeout each time data is sent successfully. The socket timeout is now the maximum total duration to send all data.

bpo-22721 [https://bugs.python.org/issue?@action=redirect&bpo=22721]: An order of multiline pprint output of set or dict containing orderable and non-orderable elements no longer depends on iteration order of set or dict.

bpo-15133 [https://bugs.python.org/issue?@action=redirect&bpo=15133]: _tkinter.tkapp.getboolean() now supports Tcl_Obj and always returns bool. tkinter.BooleanVar now validates input values (accepted bool, int, str, and Tcl_Obj). tkinter.BooleanVar.get() now always returns bool.

bpo-10590 [https://bugs.python.org/issue?@action=redirect&bpo=10590]: xml.sax.parseString() now supports string argument.

bpo-23338 [https://bugs.python.org/issue?@action=redirect&bpo=23338]: Fixed formatting ctypes error messages on Cygwin. Patch by Makoto Kato.

bpo-15582 [https://bugs.python.org/issue?@action=redirect&bpo=15582]: inspect.getdoc() now follows inheritance chains.

bpo-2175 [https://bugs.python.org/issue?@action=redirect&bpo=2175]: SAX parsers now support a character stream of InputSource object.

bpo-16840 [https://bugs.python.org/issue?@action=redirect&bpo=16840]: Tkinter now supports 64-bit integers added in Tcl 8.4 and arbitrary precision integers added in Tcl 8.5.

bpo-23834 [https://bugs.python.org/issue?@action=redirect&bpo=23834]: Fix socket.sendto(), use the C Py_ssize_t type to store the result of sendto() instead of the C int type.

bpo-23618 [https://bugs.python.org/issue?@action=redirect&bpo=23618]: socket.socket.connect() now waits until the connection completes instead of raising InterruptedError if the connection is interrupted by signals, signal handlers don’t raise an exception and the socket is blocking or has a timeout. socket.socket.connect() still raise InterruptedError for non-blocking sockets.

bpo-21526 [https://bugs.python.org/issue?@action=redirect&bpo=21526]: Tkinter now supports new boolean type in Tcl 8.5.

bpo-23836 [https://bugs.python.org/issue?@action=redirect&bpo=23836]: Fix the faulthandler module to handle reentrant calls to its signal handlers.

bpo-23838 [https://bugs.python.org/issue?@action=redirect&bpo=23838]: linecache now clears the cache and returns an empty result on MemoryError.

bpo-10395 [https://bugs.python.org/issue?@action=redirect&bpo=10395]: Added os.path.commonpath(). Implemented in posixpath and ntpath. Based on patch by Rafik Draoui.

bpo-23611 [https://bugs.python.org/issue?@action=redirect&bpo=23611]: Serializing more “lookupable” objects (such as unbound methods or nested classes) now are supported with pickle protocols < 4.

bpo-13583 [https://bugs.python.org/issue?@action=redirect&bpo=13583]: sqlite3.Row now supports slice indexing.

bpo-18473 [https://bugs.python.org/issue?@action=redirect&bpo=18473]: Fixed 2to3 and 3to2 compatible pickle mappings. Fixed ambiguous reverse mappings. Added many new mappings. Import mapping is no longer applied to modules already mapped with full name mapping.

bpo-23485 [https://bugs.python.org/issue?@action=redirect&bpo=23485]: select.select() is now retried automatically with the recomputed timeout when interrupted by a signal, except if the signal handler raises an exception. This change is part of the PEP 475.

bpo-23752 [https://bugs.python.org/issue?@action=redirect&bpo=23752]: When built from an existing file descriptor, io.FileIO() now only calls fstat() once. Before fstat() was called twice, which was not necessary.

bpo-23704 [https://bugs.python.org/issue?@action=redirect&bpo=23704]: collections.deque() objects now support __add__, __mul__, and __imul__().

bpo-23171 [https://bugs.python.org/issue?@action=redirect&bpo=23171]: csv.Writer.writerow() now supports arbitrary iterables.

bpo-23745 [https://bugs.python.org/issue?@action=redirect&bpo=23745]: The new email header parser now handles duplicate MIME parameter names without error, similar to how get_param behaves.

bpo-22117 [https://bugs.python.org/issue?@action=redirect&bpo=22117]: Fix os.utime(), it now rounds the timestamp towards minus infinity (-inf) instead of rounding towards zero.

bpo-23310 [https://bugs.python.org/issue?@action=redirect&bpo=23310]: Fix MagicMock’s initializer to work with __methods__, just like configure_mock(). Patch by Kasia Jachim.

Build

bpo-23817 [https://bugs.python.org/issue?@action=redirect&bpo=23817]: FreeBSD now uses “1.0” in the SOVERSION as other operating systems, instead of just “1”.

bpo-23501 [https://bugs.python.org/issue?@action=redirect&bpo=23501]: Argument Clinic now generates code into separate files by default.

Tests

bpo-23799 [https://bugs.python.org/issue?@action=redirect&bpo=23799]: Added test.support.start_threads() for running and cleaning up multiple threads.

bpo-22390 [https://bugs.python.org/issue?@action=redirect&bpo=22390]: test.regrtest now emits a warning if temporary files or directories are left after running a test.

Tools/Demos

bpo-18128 [https://bugs.python.org/issue?@action=redirect&bpo=18128]: pygettext now uses standard +NNNN format in the POT-Creation-Date header.

bpo-23935 [https://bugs.python.org/issue?@action=redirect&bpo=23935]: Argument Clinic’s understanding of format units accepting bytes, bytearrays, and buffers is now consistent with both the documentation and the implementation.

bpo-23944 [https://bugs.python.org/issue?@action=redirect&bpo=23944]: Argument Clinic now wraps long impl prototypes at column 78.

bpo-20586 [https://bugs.python.org/issue?@action=redirect&bpo=20586]: Argument Clinic now ensures that functions without docstrings have signatures.

bpo-23492 [https://bugs.python.org/issue?@action=redirect&bpo=23492]: Argument Clinic now generates argument parsing code with PyArg_Parse instead of PyArg_ParseTuple if possible.

bpo-23500 [https://bugs.python.org/issue?@action=redirect&bpo=23500]: Argument Clinic is now smarter about generating the “#ifndef” (empty) definition of the methoddef macro: it’s only generated once, even if Argument Clinic processes the same symbol multiple times, and it’s emitted at the end of all processing rather than immediately after the first use.

C API

bpo-23998 [https://bugs.python.org/issue?@action=redirect&bpo=23998]: PyImport_ReInitLock() now checks for lock allocation error

Python 3.5.0 alpha 3

Release date: 2015-03-28

Core and Builtins

bpo-23573 [https://bugs.python.org/issue?@action=redirect&bpo=23573]: Increased performance of string search operations (str.find, str.index, str.count, the in operator, str.split, str.partition) with arguments of different kinds (UCS1, UCS2, UCS4).

bpo-23753 [https://bugs.python.org/issue?@action=redirect&bpo=23753]: Python doesn’t support anymore platforms without stat() or fstat(), these functions are always required.

bpo-23681 [https://bugs.python.org/issue?@action=redirect&bpo=23681]: The -b option now affects comparisons of bytes with int.

bpo-23632 [https://bugs.python.org/issue?@action=redirect&bpo=23632]: Memoryviews now allow tuple indexing (including for multi-dimensional memoryviews).

bpo-23192 [https://bugs.python.org/issue?@action=redirect&bpo=23192]: Fixed generator lambdas. Patch by Bruno Cauet.

bpo-23629 [https://bugs.python.org/issue?@action=redirect&bpo=23629]: Fix the default __sizeof__ implementation for variable-sized objects.

Library

bpo-14260 [https://bugs.python.org/issue?@action=redirect&bpo=14260]: The groupindex attribute of regular expression pattern object now is non-modifiable mapping.

bpo-23792 [https://bugs.python.org/issue?@action=redirect&bpo=23792]: Ignore KeyboardInterrupt when the pydoc pager is active. This mimics the behavior of the standard unix pagers, and prevents pipepager from shutting down while the pager itself is still running.

bpo-23775 [https://bugs.python.org/issue?@action=redirect&bpo=23775]: pprint() of OrderedDict now outputs the same representation as repr().

bpo-23765 [https://bugs.python.org/issue?@action=redirect&bpo=23765]: Removed IsBadStringPtr calls in ctypes

bpo-22364 [https://bugs.python.org/issue?@action=redirect&bpo=22364]: Improved some re error messages using regex for hints.

bpo-23742 [https://bugs.python.org/issue?@action=redirect&bpo=23742]: ntpath.expandvars() no longer loses unbalanced single quotes.

bpo-21717 [https://bugs.python.org/issue?@action=redirect&bpo=21717]: The zipfile.ZipFile.open function now supports ‘x’ (exclusive creation) mode.

bpo-21802 [https://bugs.python.org/issue?@action=redirect&bpo=21802]: The reader in BufferedRWPair now is closed even when closing writer failed in BufferedRWPair.close().

bpo-23622 [https://bugs.python.org/issue?@action=redirect&bpo=23622]: Unknown escapes in regular expressions that consist of '\' and ASCII letter now raise a deprecation warning and will be forbidden in Python 3.6.

bpo-23671 [https://bugs.python.org/issue?@action=redirect&bpo=23671]: string.Template now allows specifying the “self” parameter as a keyword argument. string.Formatter now allows specifying the “self” and the “format_string” parameters as keyword arguments.

bpo-23502 [https://bugs.python.org/issue?@action=redirect&bpo=23502]: The pprint module now supports mapping proxies.

bpo-17530 [https://bugs.python.org/issue?@action=redirect&bpo=17530]: pprint now wraps long bytes objects and bytearrays.

bpo-22687 [https://bugs.python.org/issue?@action=redirect&bpo=22687]: Fixed some corner cases in breaking words in tetxtwrap. Got rid of quadratic complexity in breaking long words.

bpo-4727 [https://bugs.python.org/issue?@action=redirect&bpo=4727]: The copy module now uses pickle protocol 4 (PEP 3154) and supports copying of instances of classes whose __new__ method takes keyword-only arguments.

bpo-23491 [https://bugs.python.org/issue?@action=redirect&bpo=23491]: Added a zipapp module to support creating executable zip file archives of Python code. Registered “.pyz” and “.pyzw” extensions on Windows for these archives (PEP 441).

bpo-23657 [https://bugs.python.org/issue?@action=redirect&bpo=23657]: Avoid explicit checks for str in zipapp, adding support for pathlib.Path objects as arguments.

bpo-23688 [https://bugs.python.org/issue?@action=redirect&bpo=23688]: Added support of arbitrary bytes-like objects and avoided unnecessary copying of memoryview in gzip.GzipFile.write(). Original patch by Wolfgang Maier.

bpo-23252 [https://bugs.python.org/issue?@action=redirect&bpo=23252]: Added support for writing ZIP files to unseekable streams.

bpo-23647 [https://bugs.python.org/issue?@action=redirect&bpo=23647]: Increase imaplib’s MAXLINE to accommodate modern mailbox sizes.

bpo-23539 [https://bugs.python.org/issue?@action=redirect&bpo=23539]: If body is None, http.client.HTTPConnection.request now sets Content-Length to 0 for PUT, POST, and PATCH headers to avoid 411 errors from some web servers.

bpo-22351 [https://bugs.python.org/issue?@action=redirect&bpo=22351]: The nntplib.NNTP constructor no longer leaves the connection and socket open until the garbage collector cleans them up. Patch by Martin Panter.

bpo-23704 [https://bugs.python.org/issue?@action=redirect&bpo=23704]: collections.deque() objects now support methods for index(), insert(), and copy(). This allows deques to be registered as a MutableSequence and it improves their substitutability for lists.

bpo-23715 [https://bugs.python.org/issue?@action=redirect&bpo=23715]: signal.sigwaitinfo() and signal.sigtimedwait() are now retried when interrupted by a signal not in the sigset parameter, if the signal handler does not raise an exception. signal.sigtimedwait() recomputes the timeout with a monotonic clock when it is retried.

bpo-23001 [https://bugs.python.org/issue?@action=redirect&bpo=23001]: Few functions in modules mmap, ossaudiodev, socket, ssl, and codecs, that accepted only read-only bytes-like object now accept writable bytes-like object too.

bpo-23646 [https://bugs.python.org/issue?@action=redirect&bpo=23646]: If time.sleep() is interrupted by a signal, the sleep is now retried with the recomputed delay, except if the signal handler raises an exception (PEP 475).

bpo-23136 [https://bugs.python.org/issue?@action=redirect&bpo=23136]: _strptime now uniformly handles all days in week 0, including Dec 30 of previous year. Based on patch by Jim Carroll.

bpo-23700 [https://bugs.python.org/issue?@action=redirect&bpo=23700]: Iterator of NamedTemporaryFile now keeps a reference to NamedTemporaryFile instance. Patch by Bohuslav Kabrda.

bpo-22903 [https://bugs.python.org/issue?@action=redirect&bpo=22903]: The fake test case created by unittest.loader when it fails importing a test module is now picklable.

bpo-22181 [https://bugs.python.org/issue?@action=redirect&bpo=22181]: On Linux, os.urandom() now uses the new getrandom() syscall if available, syscall introduced in the Linux kernel 3.17. It is more reliable and more secure, because it avoids the need of a file descriptor and waits until the kernel has enough entropy.

bpo-2211 [https://bugs.python.org/issue?@action=redirect&bpo=2211]: Updated the implementation of the http.cookies.Morsel class. Setting attributes key, value and coded_value directly now is deprecated. update() and setdefault() now transform and check keys. Comparing for equality now takes into account attributes key, value and coded_value. copy() now returns a Morsel, not a dict. repr() now contains all attributes. Optimized checking keys and quoting values. Added new tests. Original patch by Demian Brecht.

bpo-18983 [https://bugs.python.org/issue?@action=redirect&bpo=18983]: Allow selection of output units in timeit. Patch by Julian Gindi.

bpo-23631 [https://bugs.python.org/issue?@action=redirect&bpo=23631]: Fix traceback.format_list when a traceback has been mutated.

bpo-23568 [https://bugs.python.org/issue?@action=redirect&bpo=23568]: Add rdivmod support to MagicMock() objects. Patch by Håkan Lövdahl.

bpo-2052 [https://bugs.python.org/issue?@action=redirect&bpo=2052]: Add charset parameter to HtmlDiff.make_file().

bpo-23668 [https://bugs.python.org/issue?@action=redirect&bpo=23668]: Support os.truncate and os.ftruncate on Windows.

bpo-23138 [https://bugs.python.org/issue?@action=redirect&bpo=23138]: Fixed parsing cookies with absent keys or values in cookiejar. Patch by Demian Brecht.

bpo-23051 [https://bugs.python.org/issue?@action=redirect&bpo=23051]: multiprocessing.Pool methods imap() and imap_unordered() now handle exceptions raised by an iterator. Patch by Alon Diamant and Davin Potts.

bpo-23581 [https://bugs.python.org/issue?@action=redirect&bpo=23581]: Add matmul support to MagicMock. Patch by Håkan Lövdahl.

bpo-23566 [https://bugs.python.org/issue?@action=redirect&bpo=23566]: enable(), register(), dump_traceback() and dump_traceback_later() functions of faulthandler now accept file descriptors. Patch by Wei Wu.

bpo-22928 [https://bugs.python.org/issue?@action=redirect&bpo=22928]: Disabled HTTP header injections in http.client. Original patch by Demian Brecht.

bpo-23615 [https://bugs.python.org/issue?@action=redirect&bpo=23615]: Modules bz2, tarfile and tokenize now can be reloaded with imp.reload(). Patch by Thomas Kluyver.

bpo-23605 [https://bugs.python.org/issue?@action=redirect&bpo=23605]: os.walk() now calls os.scandir() instead of os.listdir(). The usage of os.scandir() reduces the number of calls to os.stat(). Initial patch written by Ben Hoyt.

Build

bpo-23585 [https://bugs.python.org/issue?@action=redirect&bpo=23585]: make patchcheck will ensure the interpreter is built.

Tests

bpo-23583 [https://bugs.python.org/issue?@action=redirect&bpo=23583]: Added tests for standard IO streams in IDLE.

bpo-22289 [https://bugs.python.org/issue?@action=redirect&bpo=22289]: Prevent test_urllib2net failures due to ftp connection timeout.

Tools/Demos

bpo-22826 [https://bugs.python.org/issue?@action=redirect&bpo=22826]: The result of open() in Tools/freeze/bkfile.py is now better compatible with regular files (in particular it now supports the context management protocol).

Python 3.5.0 alpha 2

Release date: 2015-03-09

Core and Builtins

bpo-23571 [https://bugs.python.org/issue?@action=redirect&bpo=23571]: PyObject_Call() and PyCFunction_Call() now raise a SystemError if a function returns a result and raises an exception. The SystemError is chained to the previous exception.

Library

bpo-22524 [https://bugs.python.org/issue?@action=redirect&bpo=22524]: New os.scandir() function, part of the PEP 471: “os.scandir() function – a better and faster directory iterator”. Patch written by Ben Hoyt.

bpo-23103 [https://bugs.python.org/issue?@action=redirect&bpo=23103]: Reduced the memory consumption of IPv4Address and IPv6Address.

bpo-21793 [https://bugs.python.org/issue?@action=redirect&bpo=21793]: BaseHTTPRequestHandler again logs response code as numeric, not as stringified enum. Patch by Demian Brecht.

bpo-23476 [https://bugs.python.org/issue?@action=redirect&bpo=23476]: In the ssl module, enable OpenSSL’s X509_V_FLAG_TRUSTED_FIRST flag on certificate stores when it is available.

bpo-23576 [https://bugs.python.org/issue?@action=redirect&bpo=23576]: Avoid stalling in SSL reads when EOF has been reached in the SSL layer but the underlying connection hasn’t been closed.

bpo-23504 [https://bugs.python.org/issue?@action=redirect&bpo=23504]: Added an __all__ to the types module.

bpo-23563 [https://bugs.python.org/issue?@action=redirect&bpo=23563]: Optimized utility functions in urllib.parse.

bpo-7830 [https://bugs.python.org/issue?@action=redirect&bpo=7830]: Flatten nested functools.partial.

bpo-20204 [https://bugs.python.org/issue?@action=redirect&bpo=20204]: Added the __module__ attribute to _tkinter classes.

bpo-19980 [https://bugs.python.org/issue?@action=redirect&bpo=19980]: Improved help() for non-recognized strings. help(‘’) now shows the help on str. help(‘help’) now shows the help on help(). Original patch by Mark Lawrence.

bpo-23521 [https://bugs.python.org/issue?@action=redirect&bpo=23521]: Corrected pure python implementation of timedelta division.

Eliminated OverflowError from timedelta * float for some floats; Corrected rounding in timedelta true division.

bpo-21619 [https://bugs.python.org/issue?@action=redirect&bpo=21619]: Popen objects no longer leave a zombie after exit in the with statement if the pipe was broken. Patch by Martin Panter.

bpo-22936 [https://bugs.python.org/issue?@action=redirect&bpo=22936]: Make it possible to show local variables in tracebacks for both the traceback module and unittest.

bpo-15955 [https://bugs.python.org/issue?@action=redirect&bpo=15955]: Add an option to limit the output size in bz2.decompress(). Patch by Nikolaus Rath.

bpo-6639 [https://bugs.python.org/issue?@action=redirect&bpo=6639]: Module-level turtle functions no longer raise TclError after closing the window.

bpo-814253 [https://bugs.python.org/issue?@action=redirect&bpo=814253]: Group references and conditional group references now work in lookbehind assertions in regular expressions. (See also: bpo-9179 [https://bugs.python.org/issue?@action=redirect&bpo=9179])

bpo-23215 [https://bugs.python.org/issue?@action=redirect&bpo=23215]: Multibyte codecs with custom error handlers that ignores errors consumed too much memory and raised SystemError or MemoryError. Original patch by Aleksi Torhamo.

bpo-5700 [https://bugs.python.org/issue?@action=redirect&bpo=5700]: io.FileIO() called flush() after closing the file. flush() was not called in close() if closefd=False.

bpo-23374 [https://bugs.python.org/issue?@action=redirect&bpo=23374]: Fixed pydoc failure with non-ASCII files when stdout encoding differs from file system encoding (e.g. on Mac OS).

bpo-23481 [https://bugs.python.org/issue?@action=redirect&bpo=23481]: Remove RC4 from the SSL module’s default cipher list.

bpo-21548 [https://bugs.python.org/issue?@action=redirect&bpo=21548]: Fix pydoc.synopsis() and pydoc.apropos() on modules with empty docstrings.

bpo-22885 [https://bugs.python.org/issue?@action=redirect&bpo=22885]: Fixed arbitrary code execution vulnerability in the dbm.dumb module. Original patch by Claudiu Popa.

bpo-23239 [https://bugs.python.org/issue?@action=redirect&bpo=23239]: ssl.match_hostname() now supports matching of IP addresses.

bpo-23146 [https://bugs.python.org/issue?@action=redirect&bpo=23146]: Fix mishandling of absolute Windows paths with forward slashes in pathlib.

bpo-23096 [https://bugs.python.org/issue?@action=redirect&bpo=23096]: Pickle representation of floats with protocol 0 now is the same for both Python and C implementations.

bpo-19105 [https://bugs.python.org/issue?@action=redirect&bpo=19105]: pprint now more efficiently uses free space at the right.

bpo-14910 [https://bugs.python.org/issue?@action=redirect&bpo=14910]: Add allow_abbrev parameter to argparse.ArgumentParser. Patch by Jonathan Paugh, Steven Bethard, paul j3 and Daniel Eriksson.

bpo-21717 [https://bugs.python.org/issue?@action=redirect&bpo=21717]: tarfile.open() now supports ‘x’ (exclusive creation) mode.

bpo-23344 [https://bugs.python.org/issue?@action=redirect&bpo=23344]: marshal.dumps() is now 20-25% faster on average.

bpo-20416 [https://bugs.python.org/issue?@action=redirect&bpo=20416]: marshal.dumps() with protocols 3 and 4 is now 40-50% faster on average.

bpo-23421 [https://bugs.python.org/issue?@action=redirect&bpo=23421]: Fixed compression in tarfile CLI. Patch by wdv4758h.

bpo-23367 [https://bugs.python.org/issue?@action=redirect&bpo=23367]: Fix possible overflows in the unicodedata module.

bpo-23361 [https://bugs.python.org/issue?@action=redirect&bpo=23361]: Fix possible overflow in Windows subprocess creation code.

logging.handlers.QueueListener now takes a respect_handler_level keyword argument which, if set to True, will pass messages to handlers taking handler levels into account.

bpo-19705 [https://bugs.python.org/issue?@action=redirect&bpo=19705]: turtledemo now has a visual sorting algorithm demo. Original patch from Jason Yeo.

bpo-23801 [https://bugs.python.org/issue?@action=redirect&bpo=23801]: Fix issue where cgi.FieldStorage did not always ignore the entire preamble to a multipart body.

Build

bpo-23445 [https://bugs.python.org/issue?@action=redirect&bpo=23445]: pydebug builds now use “gcc -Og” where possible, to make the resulting executable faster.

bpo-23686 [https://bugs.python.org/issue?@action=redirect&bpo=23686]: Update OS X 10.5 installer build to use OpenSSL 1.0.2a.

C API

bpo-20204 [https://bugs.python.org/issue?@action=redirect&bpo=20204]: Deprecation warning is now raised for builtin types without the __module__ attribute.

Windows

bpo-23465 [https://bugs.python.org/issue?@action=redirect&bpo=23465]: Implement PEP 486 - Make the Python Launcher aware of virtual environments. Patch by Paul Moore.

bpo-23437 [https://bugs.python.org/issue?@action=redirect&bpo=23437]: Make user scripts directory versioned on Windows. Patch by Paul Moore.

Python 3.5.0 alpha 1

Release date: 2015-02-08

Core and Builtins

bpo-23285 [https://bugs.python.org/issue?@action=redirect&bpo=23285]: PEP 475 - EINTR handling.

bpo-22735 [https://bugs.python.org/issue?@action=redirect&bpo=22735]: Fix many edge cases (including crashes) involving custom mro() implementations.

bpo-22896 [https://bugs.python.org/issue?@action=redirect&bpo=22896]: Avoid using PyObject_AsCharBuffer(), PyObject_AsReadBuffer() and PyObject_AsWriteBuffer().

bpo-21295 [https://bugs.python.org/issue?@action=redirect&bpo=21295]: Revert some changes (bpo-16795 [https://bugs.python.org/issue?@action=redirect&bpo=16795]) to AST line numbers and column offsets that constituted a regression.

bpo-22986 [https://bugs.python.org/issue?@action=redirect&bpo=22986]: Allow changing an object’s __class__ between a dynamic type and static type in some cases.

bpo-15859 [https://bugs.python.org/issue?@action=redirect&bpo=15859]: PyUnicode_EncodeFSDefault(), PyUnicode_EncodeMBCS() and PyUnicode_EncodeCodePage() now raise an exception if the object is not a Unicode object. For PyUnicode_EncodeFSDefault(), it was already the case on platforms other than Windows. Patch written by Campbell Barton.

bpo-21408 [https://bugs.python.org/issue?@action=redirect&bpo=21408]: The default __ne__() now returns NotImplemented if __eq__() returned NotImplemented. Original patch by Martin Panter.

bpo-23321 [https://bugs.python.org/issue?@action=redirect&bpo=23321]: Fixed a crash in str.decode() when error handler returned replacement string longer than malformed input data.

bpo-22286 [https://bugs.python.org/issue?@action=redirect&bpo=22286]: The “backslashreplace” error handlers now works with decoding and translating.

bpo-23253 [https://bugs.python.org/issue?@action=redirect&bpo=23253]: Delay-load ShellExecute[AW] in os.startfile for reduced startup overhead on Windows.

bpo-22038 [https://bugs.python.org/issue?@action=redirect&bpo=22038]: pyatomic.h now uses stdatomic.h or GCC built-in functions for atomic memory access if available. Patch written by Vitor de Lima and Gustavo Temple.

bpo-20284 [https://bugs.python.org/issue?@action=redirect&bpo=20284]: %-interpolation (aka printf) formatting added for bytes and bytearray.

bpo-23048 [https://bugs.python.org/issue?@action=redirect&bpo=23048]: Fix jumping out of an infinite while loop in the pdb.

bpo-20335 [https://bugs.python.org/issue?@action=redirect&bpo=20335]: bytes constructor now raises TypeError when encoding or errors is specified with non-string argument. Based on patch by Renaud Blanch.

bpo-22834 [https://bugs.python.org/issue?@action=redirect&bpo=22834]: If the current working directory ends up being set to a non-existent directory then import will no longer raise FileNotFoundError.

bpo-22869 [https://bugs.python.org/issue?@action=redirect&bpo=22869]: Move the interpreter startup & shutdown code to a new dedicated pylifecycle.c module

bpo-22847 [https://bugs.python.org/issue?@action=redirect&bpo=22847]: Improve method cache efficiency.

bpo-22335 [https://bugs.python.org/issue?@action=redirect&bpo=22335]: Fix crash when trying to enlarge a bytearray to 0x7fffffff bytes on a 32-bit platform.

bpo-22653 [https://bugs.python.org/issue?@action=redirect&bpo=22653]: Fix an assertion failure in debug mode when doing a reentrant dict insertion in debug mode.

bpo-22643 [https://bugs.python.org/issue?@action=redirect&bpo=22643]: Fix integer overflow in Unicode case operations (upper, lower, title, swapcase, casefold).

bpo-17636 [https://bugs.python.org/issue?@action=redirect&bpo=17636]: Circular imports involving relative imports are now supported.

bpo-22604 [https://bugs.python.org/issue?@action=redirect&bpo=22604]: Fix assertion error in debug mode when dividing a complex number by (nan+0j).

bpo-21052 [https://bugs.python.org/issue?@action=redirect&bpo=21052]: Do not raise ImportWarning when sys.path_hooks or sys.meta_path are set to None.

bpo-16518 [https://bugs.python.org/issue?@action=redirect&bpo=16518]: Use ‘bytes-like object required’ in error messages that previously used the far more cryptic “‘x’ does not support the buffer protocol.

bpo-22470 [https://bugs.python.org/issue?@action=redirect&bpo=22470]: Fixed integer overflow issues in “backslashreplace”, “xmlcharrefreplace”, and “surrogatepass” error handlers.

bpo-22540 [https://bugs.python.org/issue?@action=redirect&bpo=22540]: speed up PyObject_IsInstance and PyObject_IsSubclass in the common case that the second argument has metaclass type.

bpo-18711 [https://bugs.python.org/issue?@action=redirect&bpo=18711]: Add a new PyErr_FormatV function, similar to PyErr_Format but accepting a va_list argument.

bpo-22520 [https://bugs.python.org/issue?@action=redirect&bpo=22520]: Fix overflow checking when generating the repr of a unicode object.

bpo-22519 [https://bugs.python.org/issue?@action=redirect&bpo=22519]: Fix overflow checking in PyBytes_Repr.

bpo-22518 [https://bugs.python.org/issue?@action=redirect&bpo=22518]: Fix integer overflow issues in latin-1 encoding.

bpo-16324 [https://bugs.python.org/issue?@action=redirect&bpo=16324]: _charset parameter of MIMEText now also accepts email.charset.Charset instances. Initial patch by Claude Paroz.

bpo-1764286 [https://bugs.python.org/issue?@action=redirect&bpo=1764286]: Fix inspect.getsource() to support decorated functions. Patch by Claudiu Popa.

bpo-18554 [https://bugs.python.org/issue?@action=redirect&bpo=18554]: os.__all__ includes posix functions.

bpo-21391 [https://bugs.python.org/issue?@action=redirect&bpo=21391]: Use os.path.abspath in the shutil module.

bpo-11471 [https://bugs.python.org/issue?@action=redirect&bpo=11471]: avoid generating a JUMP_FORWARD instruction at the end of an if-block if there is no else-clause. Original patch by Eugene Toder.

bpo-22215 [https://bugs.python.org/issue?@action=redirect&bpo=22215]: Now ValueError is raised instead of TypeError when str or bytes argument contains not permitted null character or byte.

bpo-22258 [https://bugs.python.org/issue?@action=redirect&bpo=22258]: Fix the internal function set_inheritable() on Illumos. This platform exposes the function ioctl(FIOCLEX), but calling it fails with errno is ENOTTY: “Inappropriate ioctl for device”. set_inheritable() now falls back to the slower fcntl() (F_GETFD and then F_SETFD).

bpo-21389 [https://bugs.python.org/issue?@action=redirect&bpo=21389]: Displaying the __qualname__ of the underlying function in the repr of a bound method.

bpo-22206 [https://bugs.python.org/issue?@action=redirect&bpo=22206]: Using pthread, PyThread_create_key() now sets errno to ENOMEM and returns -1 (error) on integer overflow.

bpo-20184 [https://bugs.python.org/issue?@action=redirect&bpo=20184]: Argument Clinic based signature introspection added for 30 of the builtin functions.

bpo-22116 [https://bugs.python.org/issue?@action=redirect&bpo=22116]: C functions and methods (of the ‘builtin_function_or_method’ type) can now be weakref’ed. Patch by Wei Wu.

bpo-22077 [https://bugs.python.org/issue?@action=redirect&bpo=22077]: Improve index error messages for bytearrays, bytes, lists, and tuples by adding ‘or slices’. Added ‘, not <typename>’ for bytearrays. Original patch by Claudiu Popa.

bpo-20179 [https://bugs.python.org/issue?@action=redirect&bpo=20179]: Apply Argument Clinic to bytes and bytearray. Patch by Tal Einat.

bpo-22082 [https://bugs.python.org/issue?@action=redirect&bpo=22082]: Clear interned strings in slotdefs.

Upgrade Unicode database to Unicode 7.0.0.

bpo-21897 [https://bugs.python.org/issue?@action=redirect&bpo=21897]: Fix a crash with the f_locals attribute with closure variables when frame.clear() has been called.

bpo-21205 [https://bugs.python.org/issue?@action=redirect&bpo=21205]: Add a new __qualname__ attribute to generator, the qualified name, and use it in the representation of a generator (repr(gen)). The default name of the generator (__name__ attribute) is now get from the function instead of the code. Use gen.gi_code.co_name to get the name of the code.

bpo-21669 [https://bugs.python.org/issue?@action=redirect&bpo=21669]: With the aid of heuristics in SyntaxError.__init__, the parser now attempts to generate more meaningful (or at least more search engine friendly) error messages when “exec” and “print” are used as statements.

bpo-21642 [https://bugs.python.org/issue?@action=redirect&bpo=21642]: In the conditional if-else expression, allow an integer written with no space between itself and the else keyword (e.g. True if 42else False) to be valid syntax.

bpo-21523 [https://bugs.python.org/issue?@action=redirect&bpo=21523]: Fix over-pessimistic computation of the stack effect of some opcodes in the compiler. This also fixes a quadratic compilation time issue noticeable when compiling code with a large number of “and” and “or” operators.

bpo-21418 [https://bugs.python.org/issue?@action=redirect&bpo=21418]: Fix a crash in the builtin function super() when called without argument and without current frame (ex: embedded Python).

bpo-21425 [https://bugs.python.org/issue?@action=redirect&bpo=21425]: Fix flushing of standard streams in the interactive interpreter.

bpo-21435 [https://bugs.python.org/issue?@action=redirect&bpo=21435]: In rare cases, when running finalizers on objects in cyclic trash a bad pointer dereference could occur due to a subtle flaw in internal iteration logic.

bpo-21377 [https://bugs.python.org/issue?@action=redirect&bpo=21377]: PyBytes_Concat() now tries to concatenate in-place when the first argument has a reference count of 1. Patch by Nikolaus Rath.

bpo-20355 [https://bugs.python.org/issue?@action=redirect&bpo=20355]: -W command line options now have higher priority than the PYTHONWARNINGS environment variable. Patch by Arfrever.

bpo-21274 [https://bugs.python.org/issue?@action=redirect&bpo=21274]: Define PATH_MAX for GNU/Hurd in Python/pythonrun.c.

bpo-20904 [https://bugs.python.org/issue?@action=redirect&bpo=20904]: Support setting FPU precision on m68k.

bpo-21209 [https://bugs.python.org/issue?@action=redirect&bpo=21209]: Fix sending tuples to custom generator objects with the yield from syntax.

bpo-21193 [https://bugs.python.org/issue?@action=redirect&bpo=21193]: pow(a, b, c) now raises ValueError rather than TypeError when b is negative. Patch by Josh Rosenberg.

bpo-21176 [https://bugs.python.org/issue?@action=redirect&bpo=21176]: PEP 465: Add the ‘@’ operator for matrix multiplication.

bpo-21134 [https://bugs.python.org/issue?@action=redirect&bpo=21134]: Fix segfault when str is called on an uninitialized UnicodeEncodeError, UnicodeDecodeError, or UnicodeTranslateError object.

bpo-19537 [https://bugs.python.org/issue?@action=redirect&bpo=19537]: Fix PyUnicode_DATA() alignment under m68k. Patch by Andreas Schwab.

bpo-20929 [https://bugs.python.org/issue?@action=redirect&bpo=20929]: Add a type cast to avoid shifting a negative number.

bpo-20731 [https://bugs.python.org/issue?@action=redirect&bpo=20731]: Properly position in source code files even if they are opened in text mode. Patch by Serhiy Storchaka.

bpo-20637 [https://bugs.python.org/issue?@action=redirect&bpo=20637]: Key-sharing now also works for instance dictionaries of subclasses. Patch by Peter Ingebretson.

bpo-8297 [https://bugs.python.org/issue?@action=redirect&bpo=8297]: Attributes missing from modules now include the module name in the error text. Original patch by ysj.ray.

bpo-19995 [https://bugs.python.org/issue?@action=redirect&bpo=19995]: %c, %o, %x, and %X now raise TypeError on non-integer input.

bpo-19655 [https://bugs.python.org/issue?@action=redirect&bpo=19655]: The ASDL parser - used by the build process to generate code for managing the Python AST in C - was rewritten. The new parser is self contained and does not require to carry long the spark.py parser-generator library; spark.py was removed from the source base.

bpo-12546 [https://bugs.python.org/issue?@action=redirect&bpo=12546]: Allow \x00 to be used as a fill character when using str, int, float, and complex __format__ methods.

bpo-20480 [https://bugs.python.org/issue?@action=redirect&bpo=20480]: Add ipaddress.reverse_pointer. Patch by Leon Weber.

bpo-13598 [https://bugs.python.org/issue?@action=redirect&bpo=13598]: Modify string.Formatter to support auto-numbering of replacement fields. It now matches the behavior of str.format() in this regard. Patches by Phil Elson and Ramchandra Apte.

bpo-8931 [https://bugs.python.org/issue?@action=redirect&bpo=8931]: Make alternate formatting (‘#’) for type ‘c’ raise an exception. In versions prior to 3.5, ‘#’ with ‘c’ had no effect. Now specifying it is an error. Patch by Torsten Landschoff.

bpo-23165 [https://bugs.python.org/issue?@action=redirect&bpo=23165]: Perform overflow checks before allocating memory in the _Py_char2wchar function.

Library

bpo-23399 [https://bugs.python.org/issue?@action=redirect&bpo=23399]: pyvenv creates relative symlinks where possible.

bpo-20289 [https://bugs.python.org/issue?@action=redirect&bpo=20289]: cgi.FieldStorage() now supports the context management protocol.

bpo-13128 [https://bugs.python.org/issue?@action=redirect&bpo=13128]: Print response headers for CONNECT requests when debuglevel > 0. Patch by Demian Brecht.

bpo-15381 [https://bugs.python.org/issue?@action=redirect&bpo=15381]: Optimized io.BytesIO to make less allocations and copyings.

bpo-22818 [https://bugs.python.org/issue?@action=redirect&bpo=22818]: Splitting on a pattern that could match an empty string now raises a warning. Patterns that can only match empty strings are now rejected.

bpo-23099 [https://bugs.python.org/issue?@action=redirect&bpo=23099]: Closing io.BytesIO with exported buffer is rejected now to prevent corrupting exported buffer.

bpo-23326 [https://bugs.python.org/issue?@action=redirect&bpo=23326]: Removed __ne__ implementations. Since fixing default __ne__ implementation in bpo-21408 [https://bugs.python.org/issue?@action=redirect&bpo=21408] they are redundant.

bpo-23363 [https://bugs.python.org/issue?@action=redirect&bpo=23363]: Fix possible overflow in itertools.permutations.

bpo-23364 [https://bugs.python.org/issue?@action=redirect&bpo=23364]: Fix possible overflow in itertools.product.

bpo-23366 [https://bugs.python.org/issue?@action=redirect&bpo=23366]: Fixed possible integer overflow in itertools.combinations.

bpo-23369 [https://bugs.python.org/issue?@action=redirect&bpo=23369]: Fixed possible integer overflow in _json.encode_basestring_ascii.

bpo-23353 [https://bugs.python.org/issue?@action=redirect&bpo=23353]: Fix the exception handling of generators in PyEval_EvalFrameEx(). At entry, save or swap the exception state even if PyEval_EvalFrameEx() is called with throwflag=0. At exit, the exception state is now always restored or swapped, not only if why is WHY_YIELD or WHY_RETURN. Patch co-written with Antoine Pitrou.

bpo-14099 [https://bugs.python.org/issue?@action=redirect&bpo=14099]: Restored support of writing ZIP files to tellable but non-seekable streams.

bpo-14099 [https://bugs.python.org/issue?@action=redirect&bpo=14099]: Writing to ZipFile and reading multiple ZipExtFiles is threadsafe now.

bpo-19361 [https://bugs.python.org/issue?@action=redirect&bpo=19361]: JSON decoder now raises JSONDecodeError instead of ValueError.

bpo-18518 [https://bugs.python.org/issue?@action=redirect&bpo=18518]: timeit now rejects statements which can’t be compiled outside a function or a loop (e.g. “return” or “break”).

bpo-23094 [https://bugs.python.org/issue?@action=redirect&bpo=23094]: Fixed readline with frames in Python implementation of pickle.

bpo-23268 [https://bugs.python.org/issue?@action=redirect&bpo=23268]: Fixed bugs in the comparison of ipaddress classes.

bpo-21408 [https://bugs.python.org/issue?@action=redirect&bpo=21408]: Removed incorrect implementations of __ne__() which didn’t returned NotImplemented if __eq__() returned NotImplemented. The default __ne__() now works correctly.

bpo-19996 [https://bugs.python.org/issue?@action=redirect&bpo=19996]: email.feedparser.FeedParser now handles (malformed) headers with no key rather than assuming the body has started.

bpo-20188 [https://bugs.python.org/issue?@action=redirect&bpo=20188]: Support Application-Layer Protocol Negotiation (ALPN) in the ssl module.

bpo-23133 [https://bugs.python.org/issue?@action=redirect&bpo=23133]: Pickling of ipaddress objects now produces more compact and portable representation.

bpo-23248 [https://bugs.python.org/issue?@action=redirect&bpo=23248]: Update ssl error codes from latest OpenSSL git master.

bpo-23266 [https://bugs.python.org/issue?@action=redirect&bpo=23266]: Much faster implementation of ipaddress.collapse_addresses() when there are many non-consecutive addresses.

bpo-23098 [https://bugs.python.org/issue?@action=redirect&bpo=23098]: 64-bit dev_t is now supported in the os module.

bpo-21817 [https://bugs.python.org/issue?@action=redirect&bpo=21817]: When an exception is raised in a task submitted to a ProcessPoolExecutor, the remote traceback is now displayed in the parent process. Patch by Claudiu Popa.

bpo-15955 [https://bugs.python.org/issue?@action=redirect&bpo=15955]: Add an option to limit output size when decompressing LZMA data. Patch by Nikolaus Rath and Martin Panter.

bpo-23250 [https://bugs.python.org/issue?@action=redirect&bpo=23250]: In the http.cookies module, capitalize “HttpOnly” and “Secure” as they are written in the standard.

bpo-23063 [https://bugs.python.org/issue?@action=redirect&bpo=23063]: In the distutils’ check command, fix parsing of reST with code or code-block directives.

bpo-23209 [https://bugs.python.org/issue?@action=redirect&bpo=23209]: selectors.BaseSelector.get_key() now raises a RuntimeError if the selector is closed. And selectors.BaseSelector.close() now clears its internal reference to the selector mapping to break a reference cycle. Initial patch written by Martin Richard. (See also: bpo-23225 [https://bugs.python.org/issue?@action=redirect&bpo=23225])

bpo-17911 [https://bugs.python.org/issue?@action=redirect&bpo=17911]: Provide a way to seed the linecache for a PEP-302 module without actually loading the code.

bpo-17911 [https://bugs.python.org/issue?@action=redirect&bpo=17911]: Provide a new object API for traceback, including the ability to not lookup lines at all until the traceback is actually rendered, without any trace of the original objects being kept alive.

bpo-19777 [https://bugs.python.org/issue?@action=redirect&bpo=19777]: Provide a home() classmethod on Path objects. Contributed by Victor Salgado and Mayank Tripathi.

bpo-23206 [https://bugs.python.org/issue?@action=redirect&bpo=23206]: Make json.dumps(..., ensure_ascii=False) as fast as the default case of ensure_ascii=True. Patch by Naoki Inada.

bpo-23185 [https://bugs.python.org/issue?@action=redirect&bpo=23185]: Add math.inf and math.nan constants.

bpo-23186 [https://bugs.python.org/issue?@action=redirect&bpo=23186]: Add ssl.SSLObject.shared_ciphers() and ssl.SSLSocket.shared_ciphers() to fetch the client’s list ciphers sent at handshake.

bpo-23143 [https://bugs.python.org/issue?@action=redirect&bpo=23143]: Remove compatibility with OpenSSLs older than 0.9.8.

bpo-23132 [https://bugs.python.org/issue?@action=redirect&bpo=23132]: Improve performance and introspection support of comparison methods created by functool.total_ordering.

bpo-19776 [https://bugs.python.org/issue?@action=redirect&bpo=19776]: Add an expanduser() method on Path objects.

bpo-23112 [https://bugs.python.org/issue?@action=redirect&bpo=23112]: Fix SimpleHTTPServer to correctly carry the query string and fragment when it redirects to add a trailing slash.

bpo-21793 [https://bugs.python.org/issue?@action=redirect&bpo=21793]: Added http.HTTPStatus enums (i.e. HTTPStatus.OK, HTTPStatus.NOT_FOUND). Patch by Demian Brecht.

bpo-23093 [https://bugs.python.org/issue?@action=redirect&bpo=23093]: In the io, module allow more operations to work on detached streams.

bpo-23111 [https://bugs.python.org/issue?@action=redirect&bpo=23111]: In the ftplib, make ssl.PROTOCOL_SSLv23 the default protocol version.

bpo-22585 [https://bugs.python.org/issue?@action=redirect&bpo=22585]: On OpenBSD 5.6 and newer, os.urandom() now calls getentropy(), instead of reading /dev/urandom, to get pseudo-random bytes.

bpo-19104 [https://bugs.python.org/issue?@action=redirect&bpo=19104]: pprint now produces evaluable output for wrapped strings.

bpo-23071 [https://bugs.python.org/issue?@action=redirect&bpo=23071]: Added missing names to codecs.__all__. Patch by Martin Panter.

bpo-22783 [https://bugs.python.org/issue?@action=redirect&bpo=22783]: Pickling now uses the NEWOBJ opcode instead of the NEWOBJ_EX opcode if possible.

bpo-15513 [https://bugs.python.org/issue?@action=redirect&bpo=15513]: Added a __sizeof__ implementation for pickle classes.

bpo-19858 [https://bugs.python.org/issue?@action=redirect&bpo=19858]: pickletools.optimize() now aware of the MEMOIZE opcode, can produce more compact result and no longer produces invalid output if input data contains MEMOIZE opcodes together with PUT or BINPUT opcodes.

bpo-22095 [https://bugs.python.org/issue?@action=redirect&bpo=22095]: Fixed HTTPConnection.set_tunnel with default port. The port value in the host header was set to “None”. Patch by Demian Brecht.

bpo-23016 [https://bugs.python.org/issue?@action=redirect&bpo=23016]: A warning no longer produces an AttributeError when the program is run with pythonw.exe.

bpo-21775 [https://bugs.python.org/issue?@action=redirect&bpo=21775]: shutil.copytree(): fix crash when copying to VFAT. An exception handler assumed that OSError objects always have a ‘winerror’ attribute. That is not the case, so the exception handler itself raised AttributeError when run on Linux (and, presumably, any other non-Windows OS). Patch by Greg Ward.

bpo-1218234 [https://bugs.python.org/issue?@action=redirect&bpo=1218234]: Fix inspect.getsource() to load updated source of reloaded module. Initial patch by Berker Peksag.

bpo-21740 [https://bugs.python.org/issue?@action=redirect&bpo=21740]: Support wrapped callables in doctest. Patch by Claudiu Popa.

bpo-23009 [https://bugs.python.org/issue?@action=redirect&bpo=23009]: Make sure selectors.EpollSelecrtor.select() works when no FD is registered.

bpo-22959 [https://bugs.python.org/issue?@action=redirect&bpo=22959]: In the constructor of http.client.HTTPSConnection, prefer the context’s check_hostname attribute over the check_hostname parameter.

bpo-22696 [https://bugs.python.org/issue?@action=redirect&bpo=22696]: Add function sys.is_finalizing() to know about interpreter shutdown.

bpo-16043 [https://bugs.python.org/issue?@action=redirect&bpo=16043]: Add a default limit for the amount of data xmlrpclib.gzip_decode will return. This resolves CVE-2013-1753.

bpo-14099 [https://bugs.python.org/issue?@action=redirect&bpo=14099]: ZipFile.open() no longer reopen the underlying file. Objects returned by ZipFile.open() can now operate independently of the ZipFile even if the ZipFile was created by passing in a file-like object as the first argument to the constructor.

bpo-22966 [https://bugs.python.org/issue?@action=redirect&bpo=22966]: Fix __pycache__ pyc file name clobber when pyc_compile is asked to compile a source file containing multiple dots in the source file name.

bpo-21971 [https://bugs.python.org/issue?@action=redirect&bpo=21971]: Update turtledemo doc and add module to the index.

bpo-21032 [https://bugs.python.org/issue?@action=redirect&bpo=21032]: Fixed socket leak if HTTPConnection.getresponse() fails. Original patch by Martin Panter.

bpo-22407 [https://bugs.python.org/issue?@action=redirect&bpo=22407]: Deprecated the use of re.LOCALE flag with str patterns or re.ASCII. It was newer worked.

bpo-22902 [https://bugs.python.org/issue?@action=redirect&bpo=22902]: The “ip” command is now used on Linux to determine MAC address in uuid.getnode(). Pach by Bruno Cauet.

bpo-22960 [https://bugs.python.org/issue?@action=redirect&bpo=22960]: Add a context argument to xmlrpclib.ServerProxy constructor.

bpo-22389 [https://bugs.python.org/issue?@action=redirect&bpo=22389]: Add contextlib.redirect_stderr().

bpo-21356 [https://bugs.python.org/issue?@action=redirect&bpo=21356]: Make ssl.RAND_egd() optional to support LibreSSL. The availability of the function is checked during the compilation. Patch written by Bernard Spil.

bpo-22915 [https://bugs.python.org/issue?@action=redirect&bpo=22915]: SAX parser now supports files opened with file descriptor or bytes path.

bpo-22609 [https://bugs.python.org/issue?@action=redirect&bpo=22609]: Constructors and update methods of mapping classes in the collections module now accept the self keyword argument.

bpo-22940 [https://bugs.python.org/issue?@action=redirect&bpo=22940]: Add readline.append_history_file.

bpo-19676 [https://bugs.python.org/issue?@action=redirect&bpo=19676]: Added the “namereplace” error handler.

bpo-22788 [https://bugs.python.org/issue?@action=redirect&bpo=22788]: Add context parameter to logging.handlers.HTTPHandler.

bpo-22921 [https://bugs.python.org/issue?@action=redirect&bpo=22921]: Allow SSLContext to take the hostname parameter even if OpenSSL doesn’t support SNI.

bpo-22894 [https://bugs.python.org/issue?@action=redirect&bpo=22894]: TestCase.subTest() would cause the test suite to be stopped when in failfast mode, even in the absence of failures.

bpo-22796 [https://bugs.python.org/issue?@action=redirect&bpo=22796]: HTTP cookie parsing is now stricter, in order to protect against potential injection attacks.

bpo-22370 [https://bugs.python.org/issue?@action=redirect&bpo=22370]: Windows detection in pathlib is now more robust.

bpo-22841 [https://bugs.python.org/issue?@action=redirect&bpo=22841]: Reject coroutines in asyncio add_signal_handler(). Patch by Ludovic.Gasc.

bpo-19494 [https://bugs.python.org/issue?@action=redirect&bpo=19494]: Added urllib.request.HTTPBasicPriorAuthHandler. Patch by Matej Cepl.

bpo-22578 [https://bugs.python.org/issue?@action=redirect&bpo=22578]: Added attributes to the re.error class.

bpo-22849 [https://bugs.python.org/issue?@action=redirect&bpo=22849]: Fix possible double free in the io.TextIOWrapper constructor.

bpo-12728 [https://bugs.python.org/issue?@action=redirect&bpo=12728]: Different Unicode characters having the same uppercase but different lowercase are now matched in case-insensitive regular expressions.

bpo-22821 [https://bugs.python.org/issue?@action=redirect&bpo=22821]: Fixed fcntl() with integer argument on 64-bit big-endian platforms.

bpo-21650 [https://bugs.python.org/issue?@action=redirect&bpo=21650]: Add an --sort-keys option to json.tool CLI.

bpo-22824 [https://bugs.python.org/issue?@action=redirect&bpo=22824]: Updated reprlib output format for sets to use set literals. Patch contributed by Berker Peksag.

bpo-22824 [https://bugs.python.org/issue?@action=redirect&bpo=22824]: Updated reprlib output format for arrays to display empty arrays without an unnecessary empty list. Suggested by Serhiy Storchaka.

bpo-22406 [https://bugs.python.org/issue?@action=redirect&bpo=22406]: Fixed the uu_codec codec incorrectly ported to 3.x. Based on patch by Martin Panter.

bpo-17293 [https://bugs.python.org/issue?@action=redirect&bpo=17293]: uuid.getnode() now determines MAC address on AIX using netstat. Based on patch by Aivars Kalvāns.

bpo-22769 [https://bugs.python.org/issue?@action=redirect&bpo=22769]: Fixed ttk.Treeview.tag_has() when called without arguments.

bpo-22417 [https://bugs.python.org/issue?@action=redirect&bpo=22417]: Verify certificates by default in httplib (PEP 476).

bpo-22775 [https://bugs.python.org/issue?@action=redirect&bpo=22775]: Fixed unpickling of http.cookies.SimpleCookie with protocol 2 and above. Patch by Tim Graham.

bpo-22776 [https://bugs.python.org/issue?@action=redirect&bpo=22776]: Brought excluded code into the scope of a try block in SysLogHandler.emit().

bpo-22665 [https://bugs.python.org/issue?@action=redirect&bpo=22665]: Add missing get_terminal_size and SameFileError to shutil.__all__.

bpo-6623 [https://bugs.python.org/issue?@action=redirect&bpo=6623]: Remove deprecated Netrc class in the ftplib module. Patch by Matt Chaput.

bpo-17381 [https://bugs.python.org/issue?@action=redirect&bpo=17381]: Fixed handling of case-insensitive ranges in regular expressions.

bpo-22410 [https://bugs.python.org/issue?@action=redirect&bpo=22410]: Module level functions in the re module now cache compiled locale-dependent regular expressions taking into account the locale.

bpo-22759 [https://bugs.python.org/issue?@action=redirect&bpo=22759]: Query methods on pathlib.Path() (exists(), is_dir(), etc.) now return False when the underlying stat call raises NotADirectoryError.

bpo-8876 [https://bugs.python.org/issue?@action=redirect&bpo=8876]: distutils now falls back to copying files when hard linking doesn’t work. This allows use with special filesystems such as VirtualBox shared folders.

bpo-22217 [https://bugs.python.org/issue?@action=redirect&bpo=22217]: Implemented reprs of classes in the zipfile module.

bpo-22457 [https://bugs.python.org/issue?@action=redirect&bpo=22457]: Honour load_tests in the start_dir of discovery.

bpo-18216 [https://bugs.python.org/issue?@action=redirect&bpo=18216]: gettext now raises an error when a .mo file has an unsupported major version number. Patch by Aaron Hill.

bpo-13918 [https://bugs.python.org/issue?@action=redirect&bpo=13918]: Provide a locale.delocalize() function which can remove locale-specific number formatting from a string representing a number, without then converting it to a specific type. Patch by Cédric Krier.

bpo-22676 [https://bugs.python.org/issue?@action=redirect&bpo=22676]: Make the pickling of global objects which don’t have a __module__ attribute less slow.

bpo-18853 [https://bugs.python.org/issue?@action=redirect&bpo=18853]: Fixed ResourceWarning in shlex.__nain__.

bpo-9351 [https://bugs.python.org/issue?@action=redirect&bpo=9351]: Defaults set with set_defaults on an argparse subparser are no longer ignored when also set on the parent parser.

bpo-7559 [https://bugs.python.org/issue?@action=redirect&bpo=7559]: unittest test loading ImportErrors are reported as import errors with their import exception rather than as attribute errors after the import has already failed.

bpo-19746 [https://bugs.python.org/issue?@action=redirect&bpo=19746]: Make it possible to examine the errors from unittest discovery without executing the test suite. The new errors attribute on TestLoader exposes these non-fatal errors encountered during discovery.

bpo-21991 [https://bugs.python.org/issue?@action=redirect&bpo=21991]: Make email.headerregistry’s header ‘params’ attributes be read-only (MappingProxyType). Previously the dictionary was modifiable but a new one was created on each access of the attribute.

bpo-22638 [https://bugs.python.org/issue?@action=redirect&bpo=22638]: SSLv3 is now disabled throughout the standard library. It can still be enabled by instantiating a SSLContext manually.

bpo-22641 [https://bugs.python.org/issue?@action=redirect&bpo=22641]: In asyncio, the default SSL context for client connections is now created using ssl.create_default_context(), for stronger security.

bpo-17401 [https://bugs.python.org/issue?@action=redirect&bpo=17401]: Include closefd in io.FileIO repr.

bpo-21338 [https://bugs.python.org/issue?@action=redirect&bpo=21338]: Add silent mode for compileall. quiet parameters of compile_{dir, file, path} functions now have a multilevel value. Also, -q option of the CLI now have a multilevel value. Patch by Thomas Kluyver.

bpo-20152 [https://bugs.python.org/issue?@action=redirect&bpo=20152]: Convert the array and cmath modules to Argument Clinic.

bpo-18643 [https://bugs.python.org/issue?@action=redirect&bpo=18643]: Add socket.socketpair() on Windows.

bpo-22435 [https://bugs.python.org/issue?@action=redirect&bpo=22435]: Fix a file descriptor leak when socketserver bind fails.

bpo-13096 [https://bugs.python.org/issue?@action=redirect&bpo=13096]: Fixed segfault in CTypes POINTER handling of large values.

bpo-11694 [https://bugs.python.org/issue?@action=redirect&bpo=11694]: Raise ConversionError in xdrlib as documented. Patch by Filip Gruszczyński and Claudiu Popa.

bpo-19380 [https://bugs.python.org/issue?@action=redirect&bpo=19380]: Optimized parsing of regular expressions.

bpo-1519638 [https://bugs.python.org/issue?@action=redirect&bpo=1519638]: Now unmatched groups are replaced with empty strings in re.sub() and re.subn().

bpo-18615 [https://bugs.python.org/issue?@action=redirect&bpo=18615]: sndhdr.what/whathdr now return a namedtuple.

bpo-22462 [https://bugs.python.org/issue?@action=redirect&bpo=22462]: Fix pyexpat’s creation of a dummy frame to make it appear in exception tracebacks.

bpo-21965 [https://bugs.python.org/issue?@action=redirect&bpo=21965]: Add support for in-memory SSL to the ssl module. Patch by Geert Jansen.

bpo-21173 [https://bugs.python.org/issue?@action=redirect&bpo=21173]: Fix len() on a WeakKeyDictionary when .clear() was called with an iterator alive.

bpo-11866 [https://bugs.python.org/issue?@action=redirect&bpo=11866]: Eliminated race condition in the computation of names for new threads.

bpo-21905 [https://bugs.python.org/issue?@action=redirect&bpo=21905]: Avoid RuntimeError in pickle.whichmodule() when sys.modules is mutated while iterating. Patch by Olivier Grisel.

bpo-11271 [https://bugs.python.org/issue?@action=redirect&bpo=11271]: concurrent.futures.Executor.map() now takes a chunksize argument to allow batching of tasks in child processes and improve performance of ProcessPoolExecutor. Patch by Dan O’Reilly.

bpo-21883 [https://bugs.python.org/issue?@action=redirect&bpo=21883]: os.path.join() and os.path.relpath() now raise a TypeError with more helpful error message for unsupported or mismatched types of arguments.

bpo-22219 [https://bugs.python.org/issue?@action=redirect&bpo=22219]: The zipfile module CLI now adds entries for directories (including empty directories) in ZIP file.

bpo-22449 [https://bugs.python.org/issue?@action=redirect&bpo=22449]: In the ssl.SSLContext.load_default_certs, consult the environmental variables SSL_CERT_DIR and SSL_CERT_FILE on Windows.

bpo-22508 [https://bugs.python.org/issue?@action=redirect&bpo=22508]: The email.__version__ variable has been removed; the email code is no longer shipped separately from the stdlib, and __version__ hasn’t been updated in several releases.

bpo-20076 [https://bugs.python.org/issue?@action=redirect&bpo=20076]: Added non derived UTF-8 aliases to locale aliases table.

bpo-20079 [https://bugs.python.org/issue?@action=redirect&bpo=20079]: Added locales supported in glibc 2.18 to locale alias table.

bpo-20218 [https://bugs.python.org/issue?@action=redirect&bpo=20218]: Added convenience methods read_text/write_text and read_bytes/ write_bytes to pathlib.Path objects.

bpo-22396 [https://bugs.python.org/issue?@action=redirect&bpo=22396]: On 32-bit AIX platform, don’t expose os.posix_fadvise() nor os.posix_fallocate() because their prototypes in system headers are wrong.

bpo-22517 [https://bugs.python.org/issue?@action=redirect&bpo=22517]: When an io.BufferedRWPair object is deallocated, clear its weakrefs.

bpo-22437 [https://bugs.python.org/issue?@action=redirect&bpo=22437]: Number of capturing groups in regular expression is no longer limited by 100.

bpo-17442 [https://bugs.python.org/issue?@action=redirect&bpo=17442]: InteractiveInterpreter now displays the full chained traceback in its showtraceback method, to match the built in interactive interpreter.

bpo-23392 [https://bugs.python.org/issue?@action=redirect&bpo=23392]: Added tests for marshal C API that works with FILE*.

bpo-10510 [https://bugs.python.org/issue?@action=redirect&bpo=10510]: distutils register and upload methods now use HTML standards compliant CRLF line endings.

bpo-9850 [https://bugs.python.org/issue?@action=redirect&bpo=9850]: Fixed macpath.join() for empty first component. Patch by Oleg Oshmyan.

bpo-5309 [https://bugs.python.org/issue?@action=redirect&bpo=5309]: distutils’ build and build_ext commands now accept a -j option to enable parallel building of extension modules.

bpo-22448 [https://bugs.python.org/issue?@action=redirect&bpo=22448]: Improve canceled timer handles cleanup to prevent unbound memory usage. Patch by Joshua Moore-Oliva.

bpo-22427 [https://bugs.python.org/issue?@action=redirect&bpo=22427]: TemporaryDirectory no longer attempts to clean up twice when used in the with statement in generator.

bpo-22362 [https://bugs.python.org/issue?@action=redirect&bpo=22362]: Forbidden ambiguous octal escapes out of range 0-0o377 in regular expressions.

bpo-20912 [https://bugs.python.org/issue?@action=redirect&bpo=20912]: Now directories added to ZIP file have correct Unix and MS-DOS directory attributes.

bpo-21866 [https://bugs.python.org/issue?@action=redirect&bpo=21866]: ZipFile.close() no longer writes ZIP64 central directory records if allowZip64 is false.

bpo-22278 [https://bugs.python.org/issue?@action=redirect&bpo=22278]: Fix urljoin problem with relative urls, a regression observed after changes to issue22118 were submitted.

bpo-22415 [https://bugs.python.org/issue?@action=redirect&bpo=22415]: Fixed debugging output of the GROUPREF_EXISTS opcode in the re module. Removed trailing spaces in debugging output.

bpo-22423 [https://bugs.python.org/issue?@action=redirect&bpo=22423]: Unhandled exception in thread no longer causes unhandled AttributeError when sys.stderr is None.

bpo-21332 [https://bugs.python.org/issue?@action=redirect&bpo=21332]: Ensure that bufsize=1 in subprocess.Popen() selects line buffering, rather than block buffering. Patch by Akira Li.

bpo-21091 [https://bugs.python.org/issue?@action=redirect&bpo=21091]: Fix API bug: email.message.EmailMessage.is_attachment is now a method.

bpo-21079 [https://bugs.python.org/issue?@action=redirect&bpo=21079]: Fix email.message.EmailMessage.is_attachment to return the correct result when the header has parameters as well as a value.

bpo-22247 [https://bugs.python.org/issue?@action=redirect&bpo=22247]: Add NNTPError to nntplib.__all__.

bpo-22366 [https://bugs.python.org/issue?@action=redirect&bpo=22366]: urllib.request.urlopen will accept a context object (SSLContext) as an argument which will then be used for HTTPS connection. Patch by Alex Gaynor.

bpo-4180 [https://bugs.python.org/issue?@action=redirect&bpo=4180]: The warnings registries are now reset when the filters are modified.

bpo-22419 [https://bugs.python.org/issue?@action=redirect&bpo=22419]: Limit the length of incoming HTTP request in wsgiref server to 65536 bytes and send a 414 error code for higher lengths. Patch contributed by Devin Cook.

Lax cookie parsing in http.cookies could be a security issue when combined with non-standard cookie handling in some Web browsers. Reported by Sergey Bobrov.

bpo-20537 [https://bugs.python.org/issue?@action=redirect&bpo=20537]: logging methods now accept an exception instance as well as a Boolean value or exception tuple. Thanks to Yury Selivanov for the patch.

bpo-22384 [https://bugs.python.org/issue?@action=redirect&bpo=22384]: An exception in Tkinter callback no longer crashes the program when it is run with pythonw.exe.

bpo-22168 [https://bugs.python.org/issue?@action=redirect&bpo=22168]: Prevent turtle AttributeError with non-default Canvas on OS X.

bpo-21147 [https://bugs.python.org/issue?@action=redirect&bpo=21147]: sqlite3 now raises an exception if the request contains a null character instead of truncating it. Based on patch by Victor Stinner.

bpo-13968 [https://bugs.python.org/issue?@action=redirect&bpo=13968]: The glob module now supports recursive search in subdirectories using the ** pattern.

bpo-21951 [https://bugs.python.org/issue?@action=redirect&bpo=21951]: Fixed a crash in Tkinter on AIX when called Tcl command with empty string or tuple argument.

bpo-21951 [https://bugs.python.org/issue?@action=redirect&bpo=21951]: Tkinter now most likely raises MemoryError instead of crash if the memory allocation fails.

bpo-22338 [https://bugs.python.org/issue?@action=redirect&bpo=22338]: Fix a crash in the json module on memory allocation failure.

bpo-12410 [https://bugs.python.org/issue?@action=redirect&bpo=12410]: imaplib.IMAP4 now supports the context management protocol. Original patch by Tarek Ziadé.

bpo-21270 [https://bugs.python.org/issue?@action=redirect&bpo=21270]: We now override tuple methods in mock.call objects so that they can be used as normal call attributes.

bpo-16662 [https://bugs.python.org/issue?@action=redirect&bpo=16662]: load_tests() is now unconditionally run when it is present in a package’s __init__.py. TestLoader.loadTestsFromModule() still accepts use_load_tests, but it is deprecated and ignored. A new keyword-only attribute pattern is added and documented. Patch given by Robert Collins, tweaked by Barry Warsaw.

bpo-22226 [https://bugs.python.org/issue?@action=redirect&bpo=22226]: First letter no longer is stripped from the “status” key in the result of Treeview.heading().

bpo-19524 [https://bugs.python.org/issue?@action=redirect&bpo=19524]: Fixed resource leak in the HTTP connection when an invalid response is received. Patch by Martin Panter.

bpo-20421 [https://bugs.python.org/issue?@action=redirect&bpo=20421]: Add a .version() method to SSL sockets exposing the actual protocol version in use.

bpo-19546 [https://bugs.python.org/issue?@action=redirect&bpo=19546]: configparser exceptions no longer expose implementation details. Chained KeyErrors are removed, which leads to cleaner tracebacks. Patch by Claudiu Popa.

bpo-22051 [https://bugs.python.org/issue?@action=redirect&bpo=22051]: turtledemo no longer reloads examples to re-run them. Initialization of variables and gui setup should be done in main(), which is called each time a demo is run, but not on import.

bpo-21933 [https://bugs.python.org/issue?@action=redirect&bpo=21933]: Turtledemo users can change the code font size with a menu selection or control(command) ‘-’ or ‘+’ or control-mousewheel. Original patch by Lita Cho.

bpo-21597 [https://bugs.python.org/issue?@action=redirect&bpo=21597]: The separator between the turtledemo text pane and the drawing canvas can now be grabbed and dragged with a mouse. The code text pane can be widened to easily view or copy the full width of the text. The canvas can be widened on small screens. Original patches by Jan Kanis and Lita Cho.

bpo-18132 [https://bugs.python.org/issue?@action=redirect&bpo=18132]: Turtledemo buttons no longer disappear when the window is shrunk. Original patches by Jan Kanis and Lita Cho.

bpo-22043 [https://bugs.python.org/issue?@action=redirect&bpo=22043]: time.monotonic() is now always available. threading.Lock.acquire(), threading.RLock.acquire() and socket operations now use a monotonic clock, instead of the system clock, when a timeout is used.

bpo-21527 [https://bugs.python.org/issue?@action=redirect&bpo=21527]: Add a default number of workers to ThreadPoolExecutor equal to 5 times the number of CPUs. Patch by Claudiu Popa.

bpo-22216 [https://bugs.python.org/issue?@action=redirect&bpo=22216]: smtplib now resets its state more completely after a quit. The most obvious consequence of the previous behavior was a STARTTLS failure during a connect/starttls/quit/connect/starttls sequence.

bpo-22098 [https://bugs.python.org/issue?@action=redirect&bpo=22098]: ctypes’ BigEndianStructure and LittleEndianStructure now define an empty __slots__ so that subclasses don’t always get an instance dict. Patch by Claudiu Popa.

bpo-22185 [https://bugs.python.org/issue?@action=redirect&bpo=22185]: Fix an occasional RuntimeError in threading.Condition.wait() caused by mutation of the waiters queue without holding the lock. Patch by Doug Zongker.

bpo-22287 [https://bugs.python.org/issue?@action=redirect&bpo=22287]: On UNIX, _PyTime_gettimeofday() now uses clock_gettime(CLOCK_REALTIME) if available. As a side effect, Python now depends on the librt library on Solaris and on Linux (only with glibc older than 2.17).

bpo-22182 [https://bugs.python.org/issue?@action=redirect&bpo=22182]: Use e.args to unpack exceptions correctly in distutils.file_util.move_file. Patch by Claudiu Popa.

The webbrowser module now uses subprocess’s start_new_session=True rather than a potentially risky preexec_fn=os.setsid call.

bpo-22042 [https://bugs.python.org/issue?@action=redirect&bpo=22042]: signal.set_wakeup_fd(fd) now raises an exception if the file descriptor is in blocking mode.

bpo-16808 [https://bugs.python.org/issue?@action=redirect&bpo=16808]: inspect.stack() now returns a named tuple instead of a tuple. Patch by Daniel Shahaf.

bpo-22236 [https://bugs.python.org/issue?@action=redirect&bpo=22236]: Fixed Tkinter images copying operations in NoDefaultRoot mode.

bpo-2527 [https://bugs.python.org/issue?@action=redirect&bpo=2527]: Add a globals argument to timeit functions, in order to override the globals namespace in which the timed code is executed. Patch by Ben Roberts.

bpo-22118 [https://bugs.python.org/issue?@action=redirect&bpo=22118]: Switch urllib.parse to use RFC 3986 semantics for the resolution of relative URLs, rather than RFCs 1808 and 2396. Patch by Demian Brecht.

bpo-21549 [https://bugs.python.org/issue?@action=redirect&bpo=21549]: Added the “members” parameter to TarFile.list().

bpo-19628 [https://bugs.python.org/issue?@action=redirect&bpo=19628]: Allow compileall recursion depth to be specified with a -r option.

bpo-15696 [https://bugs.python.org/issue?@action=redirect&bpo=15696]: Add a __sizeof__ implementation for mmap objects on Windows.

bpo-22068 [https://bugs.python.org/issue?@action=redirect&bpo=22068]: Avoided reference loops with Variables and Fonts in Tkinter.

bpo-22165 [https://bugs.python.org/issue?@action=redirect&bpo=22165]: SimpleHTTPRequestHandler now supports undecodable file names.

bpo-15381 [https://bugs.python.org/issue?@action=redirect&bpo=15381]: Optimized line reading in io.BytesIO.

bpo-8797 [https://bugs.python.org/issue?@action=redirect&bpo=8797]: Raise HTTPError on failed Basic Authentication immediately. Initial patch by Sam Bull.

bpo-20729 [https://bugs.python.org/issue?@action=redirect&bpo=20729]: Restored the use of lazy iterkeys()/itervalues()/iteritems() in the mailbox module.

bpo-21448 [https://bugs.python.org/issue?@action=redirect&bpo=21448]: Changed FeedParser feed() to avoid O(N**2) behavior when parsing long line. Original patch by Raymond Hettinger.

bpo-22184 [https://bugs.python.org/issue?@action=redirect&bpo=22184]: The functools LRU Cache decorator factory now gives an earlier and clearer error message when the user forgets the required parameters.

bpo-17923 [https://bugs.python.org/issue?@action=redirect&bpo=17923]: glob() patterns ending with a slash no longer match non-dirs on AIX. Based on patch by Delhallt.

bpo-21725 [https://bugs.python.org/issue?@action=redirect&bpo=21725]: Added support for RFC 6531 (SMTPUTF8) in smtpd.

bpo-22176 [https://bugs.python.org/issue?@action=redirect&bpo=22176]: Update the ctypes module’s libffi to v3.1. This release adds support for the Linux AArch64 and POWERPC ELF ABIv2 little endian architectures.

bpo-5411 [https://bugs.python.org/issue?@action=redirect&bpo=5411]: Added support for the “xztar” format in the shutil module.

bpo-21121 [https://bugs.python.org/issue?@action=redirect&bpo=21121]: Don’t force 3rd party C extensions to be built with -Werror=declaration-after-statement.

bpo-21975 [https://bugs.python.org/issue?@action=redirect&bpo=21975]: Fixed crash when using uninitialized sqlite3.Row (in particular when unpickling pickled sqlite3.Row). sqlite3.Row is now initialized in the __new__() method.

bpo-20170 [https://bugs.python.org/issue?@action=redirect&bpo=20170]: Convert posixmodule to use Argument Clinic.

bpo-21539 [https://bugs.python.org/issue?@action=redirect&bpo=21539]: Add an exists_ok argument to Pathlib.mkdir() to mimic mkdir -p and os.makedirs() functionality. When true, ignore FileExistsErrors. Patch by Berker Peksag.

bpo-22127 [https://bugs.python.org/issue?@action=redirect&bpo=22127]: Bypass IDNA for pure-ASCII host names in the socket module (in particular for numeric IPs).

bpo-21047 [https://bugs.python.org/issue?@action=redirect&bpo=21047]: set the default value for the convert_charrefs argument of HTMLParser to True. Patch by Berker Peksag.

Add an __all__ to html.entities.

bpo-15114 [https://bugs.python.org/issue?@action=redirect&bpo=15114]: the strict mode and argument of HTMLParser, HTMLParser.error, and the HTMLParserError exception have been removed.

bpo-22085 [https://bugs.python.org/issue?@action=redirect&bpo=22085]: Dropped support of Tk 8.3 in Tkinter.

bpo-21580 [https://bugs.python.org/issue?@action=redirect&bpo=21580]: Now Tkinter correctly handles bytes arguments passed to Tk. In particular this allows initializing images from binary data.

bpo-22003 [https://bugs.python.org/issue?@action=redirect&bpo=22003]: When initialized from a bytes object, io.BytesIO() now defers making a copy until it is mutated, improving performance and memory use on some use cases. Patch by David Wilson.

bpo-22018 [https://bugs.python.org/issue?@action=redirect&bpo=22018]: On Windows, signal.set_wakeup_fd() now also supports sockets. A side effect is that Python depends to the WinSock library.

bpo-22054 [https://bugs.python.org/issue?@action=redirect&bpo=22054]: Add os.get_blocking() and os.set_blocking() functions to get and set the blocking mode of a file descriptor (False if the O_NONBLOCK flag is set, True otherwise). These functions are not available on Windows.

bpo-17172 [https://bugs.python.org/issue?@action=redirect&bpo=17172]: Make turtledemo start as active on OS X even when run with subprocess. Patch by Lita Cho.

bpo-21704 [https://bugs.python.org/issue?@action=redirect&bpo=21704]: Fix build error for _multiprocessing when semaphores are not available. Patch by Arfrever Frehtes Taifersar Arahesis.

bpo-20173 [https://bugs.python.org/issue?@action=redirect&bpo=20173]: Convert sha1, sha256, sha512 and md5 to ArgumentClinic. Patch by Vajrasky Kok.

Fix repr(_socket.socket) on Windows 64-bit: don’t fail with OverflowError on closed socket. repr(socket.socket) already works fine.

bpo-22033 [https://bugs.python.org/issue?@action=redirect&bpo=22033]: Reprs of most Python implemented classes now contain actual class name instead of hardcoded one.

bpo-21947 [https://bugs.python.org/issue?@action=redirect&bpo=21947]: The dis module can now disassemble generator-iterator objects based on their gi_code attribute. Patch by Clement Rouault.

bpo-16133 [https://bugs.python.org/issue?@action=redirect&bpo=16133]: The asynchat.async_chat.handle_read() method now ignores BlockingIOError exceptions.

bpo-22044 [https://bugs.python.org/issue?@action=redirect&bpo=22044]: Fixed premature DECREF in call_tzinfo_method. Patch by Tom Flanagan.

bpo-19884 [https://bugs.python.org/issue?@action=redirect&bpo=19884]: readline: Disable the meta modifier key if stdout is not a terminal to not write the ANSI sequence "\033[1034h" into stdout. This sequence is used on some terminal (ex: TERM=xterm-256color”) to enable support of 8 bit characters.

bpo-4350 [https://bugs.python.org/issue?@action=redirect&bpo=4350]: Removed a number of out-of-dated and non-working for a long time Tkinter methods.

bpo-6167 [https://bugs.python.org/issue?@action=redirect&bpo=6167]: Scrollbar.activate() now returns the name of active element if the argument is not specified. Scrollbar.set() now always accepts only 2 arguments.

bpo-15275 [https://bugs.python.org/issue?@action=redirect&bpo=15275]: Clean up and speed up the ntpath module.

bpo-21888 [https://bugs.python.org/issue?@action=redirect&bpo=21888]: plistlib’s load() and loads() now work if the fmt parameter is specified.

bpo-22032 [https://bugs.python.org/issue?@action=redirect&bpo=22032]: __qualname__ instead of __name__ is now always used to format fully qualified class names of Python implemented classes.

bpo-22031 [https://bugs.python.org/issue?@action=redirect&bpo=22031]: Reprs now always use hexadecimal format with the “0x” prefix when contain an id in form ” at 0x…”.

bpo-22018 [https://bugs.python.org/issue?@action=redirect&bpo=22018]: signal.set_wakeup_fd() now raises an OSError instead of a ValueError on fstat() failure.

bpo-21044 [https://bugs.python.org/issue?@action=redirect&bpo=21044]: tarfile.open() now handles fileobj with an integer ‘name’ attribute. Based on patch by Antoine Pietri.

bpo-21966 [https://bugs.python.org/issue?@action=redirect&bpo=21966]: Respect -q command-line option when code module is ran.

bpo-19076 [https://bugs.python.org/issue?@action=redirect&bpo=19076]: Don’t pass the redundant ‘file’ argument to self.error().

bpo-16382 [https://bugs.python.org/issue?@action=redirect&bpo=16382]: Improve exception message of warnings.warn() for bad category. Initial patch by Phil Elson.

bpo-21932 [https://bugs.python.org/issue?@action=redirect&bpo=21932]: os.read() now uses a Py_ssize_t() type instead of int for the size to support reading more than 2 GB at once. On Windows, the size is truncated to INT_MAX. As any call to os.read(), the OS may read less bytes than the number of requested bytes.

bpo-21942 [https://bugs.python.org/issue?@action=redirect&bpo=21942]: Fixed source file viewing in pydoc’s server mode on Windows.

bpo-11259 [https://bugs.python.org/issue?@action=redirect&bpo=11259]: asynchat.async_chat().set_terminator() now raises a ValueError if the number of received bytes is negative.

bpo-12523 [https://bugs.python.org/issue?@action=redirect&bpo=12523]: asynchat.async_chat.push() now raises a TypeError if it doesn’t get a bytes string

bpo-21707 [https://bugs.python.org/issue?@action=redirect&bpo=21707]: Add missing kwonlyargcount argument to ModuleFinder.replace_paths_in_code().

bpo-20639 [https://bugs.python.org/issue?@action=redirect&bpo=20639]: calling Path.with_suffix(‘’) allows removing the suffix again. Patch by July Tikhonov.

bpo-21714 [https://bugs.python.org/issue?@action=redirect&bpo=21714]: Disallow the construction of invalid paths using Path.with_name(). Original patch by Antony Lee.

bpo-15014 [https://bugs.python.org/issue?@action=redirect&bpo=15014]: Added ‘auth’ method to smtplib to make implementing auth mechanisms simpler, and used it internally in the login method.

bpo-21151 [https://bugs.python.org/issue?@action=redirect&bpo=21151]: Fixed a segfault in the winreg module when None is passed as a REG_BINARY value to SetValueEx. Patch by John Ehresman.

bpo-21090 [https://bugs.python.org/issue?@action=redirect&bpo=21090]: io.FileIO.readall() does not ignore I/O errors anymore. Before, it ignored I/O errors if at least the first C call read() succeed.

bpo-5800 [https://bugs.python.org/issue?@action=redirect&bpo=5800]: headers parameter of wsgiref.headers.Headers is now optional. Initial patch by Pablo Torres Navarrete and SilentGhost.

bpo-21781 [https://bugs.python.org/issue?@action=redirect&bpo=21781]: ssl.RAND_add() now supports strings longer than 2 GB.

bpo-21679 [https://bugs.python.org/issue?@action=redirect&bpo=21679]: Prevent extraneous fstat() calls during open(). Patch by Bohuslav Kabrda.

bpo-21863 [https://bugs.python.org/issue?@action=redirect&bpo=21863]: cProfile now displays the module name of C extension functions, in addition to their own name.

bpo-11453 [https://bugs.python.org/issue?@action=redirect&bpo=11453]: asyncore: emit a ResourceWarning when an unclosed file_wrapper object is destroyed. The destructor now closes the file if needed. The close() method can now be called twice: the second call does nothing.

bpo-21858 [https://bugs.python.org/issue?@action=redirect&bpo=21858]: Better handling of Python exceptions in the sqlite3 module.

bpo-21476 [https://bugs.python.org/issue?@action=redirect&bpo=21476]: Make sure the email.parser.BytesParser TextIOWrapper is discarded after parsing, so the input file isn’t unexpectedly closed.

bpo-20295 [https://bugs.python.org/issue?@action=redirect&bpo=20295]: imghdr now recognizes OpenEXR format images.

bpo-21729 [https://bugs.python.org/issue?@action=redirect&bpo=21729]: Used the “with” statement in the dbm.dumb module to ensure files closing. Patch by Claudiu Popa.

bpo-21491 [https://bugs.python.org/issue?@action=redirect&bpo=21491]: socketserver: Fix a race condition in child processes reaping.

bpo-21719 [https://bugs.python.org/issue?@action=redirect&bpo=21719]: Added the st_file_attributes field to os.stat_result on Windows.

bpo-21832 [https://bugs.python.org/issue?@action=redirect&bpo=21832]: Require named tuple inputs to be exact strings.

bpo-21722 [https://bugs.python.org/issue?@action=redirect&bpo=21722]: The distutils “upload” command now exits with a non-zero return code when uploading fails. Patch by Martin Dengler.

bpo-21723 [https://bugs.python.org/issue?@action=redirect&bpo=21723]: asyncio.Queue: support any type of number (ex: float) for the maximum size. Patch written by Vajrasky Kok.

bpo-21711 [https://bugs.python.org/issue?@action=redirect&bpo=21711]: support for “site-python” directories has now been removed from the site module (it was deprecated in 3.4).

bpo-17552 [https://bugs.python.org/issue?@action=redirect&bpo=17552]: new socket.sendfile() method allowing a file to be sent over a socket by using high-performance os.sendfile() on UNIX. Patch by Giampaolo Rodola’.

bpo-18039 [https://bugs.python.org/issue?@action=redirect&bpo=18039]: dbm.dump.open() now always creates a new database when the flag has the value ‘n’. Patch by Claudiu Popa.

bpo-21326 [https://bugs.python.org/issue?@action=redirect&bpo=21326]: Add a new is_closed() method to asyncio.BaseEventLoop. run_forever() and run_until_complete() methods of asyncio.BaseEventLoop now raise an exception if the event loop was closed.

bpo-21766 [https://bugs.python.org/issue?@action=redirect&bpo=21766]: Prevent a security hole in CGIHTTPServer by URL unquoting paths before checking for a CGI script at that path.

bpo-21310 [https://bugs.python.org/issue?@action=redirect&bpo=21310]: Fixed possible resource leak in failed open().

bpo-21256 [https://bugs.python.org/issue?@action=redirect&bpo=21256]: Printout of keyword args should be in deterministic order in a mock function call. This will help to write better doctests.

bpo-21677 [https://bugs.python.org/issue?@action=redirect&bpo=21677]: Fixed chaining nonnormalized exceptions in io close() methods.

bpo-11709 [https://bugs.python.org/issue?@action=redirect&bpo=11709]: Fix the pydoc.help function to not fail when sys.stdin is not a valid file.

bpo-21515 [https://bugs.python.org/issue?@action=redirect&bpo=21515]: tempfile.TemporaryFile now uses os.O_TMPFILE flag is available.

bpo-13223 [https://bugs.python.org/issue?@action=redirect&bpo=13223]: Fix pydoc.writedoc so that the HTML documentation for methods that use ‘self’ in the example code is generated correctly.

bpo-21463 [https://bugs.python.org/issue?@action=redirect&bpo=21463]: In urllib.request, fix pruning of the FTP cache.

bpo-21618 [https://bugs.python.org/issue?@action=redirect&bpo=21618]: The subprocess module could fail to close open fds that were inherited by the calling process and already higher than POSIX resource limits would otherwise allow. On systems with a functioning /proc/self/fd or /dev/fd interface the max is now ignored and all fds are closed.

bpo-20383 [https://bugs.python.org/issue?@action=redirect&bpo=20383]: Introduce importlib.util.module_from_spec() as the preferred way to create a new module.

bpo-21552 [https://bugs.python.org/issue?@action=redirect&bpo=21552]: Fixed possible integer overflow of too long string lengths in the tkinter module on 64-bit platforms.

bpo-14315 [https://bugs.python.org/issue?@action=redirect&bpo=14315]: The zipfile module now ignores extra fields in the central directory that are too short to be parsed instead of letting a struct.unpack error bubble up as this “bad data” appears in many real world zip files in the wild and is ignored by other zip tools.

bpo-13742 [https://bugs.python.org/issue?@action=redirect&bpo=13742]: Added “key” and “reverse” parameters to heapq.merge(). (First draft of patch contributed by Simon Sapin.)

bpo-21402 [https://bugs.python.org/issue?@action=redirect&bpo=21402]: tkinter.ttk now works when default root window is not set.

bpo-3015 [https://bugs.python.org/issue?@action=redirect&bpo=3015]: _tkinter.create() now creates tkapp object with wantobject=1 by default.

bpo-10203 [https://bugs.python.org/issue?@action=redirect&bpo=10203]: sqlite3.Row now truly supports sequence protocol. In particular it supports reverse() and negative indices. Original patch by Claudiu Popa.

bpo-18807 [https://bugs.python.org/issue?@action=redirect&bpo=18807]: If copying (no symlinks) specified for a venv, then the python interpreter aliases (python, python3) are now created by copying rather than symlinking.

bpo-20197 [https://bugs.python.org/issue?@action=redirect&bpo=20197]: Added support for the WebP image type in the imghdr module. Patch by Fabrice Aneche and Claudiu Popa.

bpo-21513 [https://bugs.python.org/issue?@action=redirect&bpo=21513]: Speedup some properties of IP addresses (IPv4Address, IPv6Address) such as .is_private or .is_multicast.

bpo-21137 [https://bugs.python.org/issue?@action=redirect&bpo=21137]: Improve the repr for threading.Lock() and its variants by showing the “locked” or “unlocked” status. Patch by Berker Peksag.

bpo-21538 [https://bugs.python.org/issue?@action=redirect&bpo=21538]: The plistlib module now supports loading of binary plist files when reference or offset size is not a power of two.

bpo-21455 [https://bugs.python.org/issue?@action=redirect&bpo=21455]: Add a default backlog to socket.listen().

bpo-21525 [https://bugs.python.org/issue?@action=redirect&bpo=21525]: Most Tkinter methods which accepted tuples now accept lists too.

bpo-22166 [https://bugs.python.org/issue?@action=redirect&bpo=22166]: With the assistance of a new internal _codecs._forget_codec helping function, test_codecs now clears the encoding caches to avoid the appearance of a reference leak

bpo-22236 [https://bugs.python.org/issue?@action=redirect&bpo=22236]: Tkinter tests now don’t reuse default root window. New root window is created for every test class.

bpo-10744 [https://bugs.python.org/issue?@action=redirect&bpo=10744]: Fix PEP 3118 format strings on ctypes objects with a nontrivial shape.

bpo-20826 [https://bugs.python.org/issue?@action=redirect&bpo=20826]: Optimize ipaddress.collapse_addresses().

bpo-21487 [https://bugs.python.org/issue?@action=redirect&bpo=21487]: Optimize ipaddress.summarize_address_range() and ipaddress.{IPv4Network,IPv6Network}.subnets().

bpo-21486 [https://bugs.python.org/issue?@action=redirect&bpo=21486]: Optimize parsing of netmasks in ipaddress.IPv4Network and ipaddress.IPv6Network.

bpo-13916 [https://bugs.python.org/issue?@action=redirect&bpo=13916]: Disallowed the surrogatepass error handler for non UTF-* encodings.

bpo-20998 [https://bugs.python.org/issue?@action=redirect&bpo=20998]: Fixed re.fullmatch() of repeated single character pattern with ignore case. Original patch by Matthew Barnett.

bpo-21075 [https://bugs.python.org/issue?@action=redirect&bpo=21075]: fileinput.FileInput now reads bytes from standard stream if binary mode is specified. Patch by Sam Kimbrel.

bpo-19775 [https://bugs.python.org/issue?@action=redirect&bpo=19775]: Add a samefile() method to pathlib Path objects. Initial patch by Vajrasky Kok.

bpo-21226 [https://bugs.python.org/issue?@action=redirect&bpo=21226]: Set up modules properly in PyImport_ExecCodeModuleObject (and friends).

bpo-21398 [https://bugs.python.org/issue?@action=redirect&bpo=21398]: Fix a unicode error in the pydoc pager when the documentation contains characters not encodable to the stdout encoding.

bpo-16531 [https://bugs.python.org/issue?@action=redirect&bpo=16531]: ipaddress.IPv4Network and ipaddress.IPv6Network now accept an (address, netmask) tuple argument, so as to easily construct network objects from existing addresses.

bpo-21156 [https://bugs.python.org/issue?@action=redirect&bpo=21156]: importlib.abc.InspectLoader.source_to_code() is now a staticmethod.

bpo-21424 [https://bugs.python.org/issue?@action=redirect&bpo=21424]: Simplified and optimized heaqp.nlargest() and nmsmallest() to make fewer tuple comparisons.

bpo-21396 [https://bugs.python.org/issue?@action=redirect&bpo=21396]: Fix TextIOWrapper(…, write_through=True) to not force a flush() on the underlying binary stream. Patch by akira.

bpo-18314 [https://bugs.python.org/issue?@action=redirect&bpo=18314]: Unlink now removes junctions on Windows. Patch by Kim Gräsman

bpo-21088 [https://bugs.python.org/issue?@action=redirect&bpo=21088]: Bugfix for curses.window.addch() regression in 3.4.0. In porting to Argument Clinic, the first two arguments were reversed.

bpo-21407 [https://bugs.python.org/issue?@action=redirect&bpo=21407]: _decimal: The module now supports function signatures.

bpo-10650 [https://bugs.python.org/issue?@action=redirect&bpo=10650]: Remove the non-standard ‘watchexp’ parameter from the Decimal.quantize() method in the Python version. It had never been present in the C version.

bpo-21469 [https://bugs.python.org/issue?@action=redirect&bpo=21469]: Reduced the risk of false positives in robotparser by checking to make sure that robots.txt has been read or does not exist prior to returning True in can_fetch().

bpo-19414 [https://bugs.python.org/issue?@action=redirect&bpo=19414]: Have the OrderedDict mark deleted links as unusable. This gives an early failure if the link is deleted during iteration.

bpo-21421 [https://bugs.python.org/issue?@action=redirect&bpo=21421]: Add __slots__ to the MappingViews ABC. Patch by Josh Rosenberg.

bpo-21101 [https://bugs.python.org/issue?@action=redirect&bpo=21101]: Eliminate double hashing in the C speed-up code for collections.Counter().

bpo-21321 [https://bugs.python.org/issue?@action=redirect&bpo=21321]: itertools.islice() now releases the reference to the source iterator when the slice is exhausted. Patch by Anton Afanasyev.

bpo-21057 [https://bugs.python.org/issue?@action=redirect&bpo=21057]: TextIOWrapper now allows the underlying binary stream’s read() or read1() method to return an arbitrary bytes-like object (such as a memoryview). Patch by Nikolaus Rath.

bpo-20951 [https://bugs.python.org/issue?@action=redirect&bpo=20951]: SSLSocket.send() now raises either SSLWantReadError or SSLWantWriteError on a non-blocking socket if the operation would block. Previously, it would return 0. Patch by Nikolaus Rath.

bpo-13248 [https://bugs.python.org/issue?@action=redirect&bpo=13248]: removed previously deprecated asyncore.dispatcher __getattr__ cheap inheritance hack.

bpo-9815 [https://bugs.python.org/issue?@action=redirect&bpo=9815]: assertRaises now tries to clear references to local variables in the exception’s traceback.

bpo-19940 [https://bugs.python.org/issue?@action=redirect&bpo=19940]: ssl.cert_time_to_seconds() now interprets the given time string in the UTC timezone (as specified in RFC 5280), not the local timezone.

bpo-13204 [https://bugs.python.org/issue?@action=redirect&bpo=13204]: Calling sys.flags.__new__ would crash the interpreter, now it raises a TypeError.

bpo-19385 [https://bugs.python.org/issue?@action=redirect&bpo=19385]: Make operations on a closed dbm.dumb database always raise the same exception.

bpo-21207 [https://bugs.python.org/issue?@action=redirect&bpo=21207]: Detect when the os.urandom cached fd has been closed or replaced, and open it anew.

bpo-21291 [https://bugs.python.org/issue?@action=redirect&bpo=21291]: subprocess’s Popen.wait() is now thread safe so that multiple threads may be calling wait() or poll() on a Popen instance at the same time without losing the Popen.returncode value.

bpo-21127 [https://bugs.python.org/issue?@action=redirect&bpo=21127]: Path objects can now be instantiated from str subclass instances (such as numpy.str_).

bpo-15002 [https://bugs.python.org/issue?@action=redirect&bpo=15002]: urllib.response object to use _TemporaryFileWrapper (and _TemporaryFileCloser) facility. Provides a better way to handle file descriptor close. Patch contributed by Christian Theune.

bpo-12220 [https://bugs.python.org/issue?@action=redirect&bpo=12220]: mindom now raises a custom ValueError indicating it doesn’t support spaces in URIs instead of letting a ‘split’ ValueError bubble up.

bpo-21068 [https://bugs.python.org/issue?@action=redirect&bpo=21068]: The ssl.PROTOCOL* constants are now enum members.

bpo-21276 [https://bugs.python.org/issue?@action=redirect&bpo=21276]: posixmodule: Don’t define USE_XATTRS on KFreeBSD and the Hurd.

bpo-21262 [https://bugs.python.org/issue?@action=redirect&bpo=21262]: New method assert_not_called for Mock. It raises AssertionError if the mock has been called.

bpo-21238 [https://bugs.python.org/issue?@action=redirect&bpo=21238]: New keyword argument unsafe to Mock. It raises AttributeError incase of an attribute startswith assert or assret.

bpo-20896 [https://bugs.python.org/issue?@action=redirect&bpo=20896]: ssl.get_server_certificate() now uses PROTOCOL_SSLv23, not PROTOCOL_SSLv3, for maximum compatibility.

bpo-21239 [https://bugs.python.org/issue?@action=redirect&bpo=21239]: patch.stopall() didn’t work deterministically when the same name was patched more than once.

bpo-21203 [https://bugs.python.org/issue?@action=redirect&bpo=21203]: Updated fileConfig and dictConfig to remove inconsistencies. Thanks to Jure Koren for the patch.

bpo-21222 [https://bugs.python.org/issue?@action=redirect&bpo=21222]: Passing name keyword argument to mock.create_autospec now works.

bpo-21197 [https://bugs.python.org/issue?@action=redirect&bpo=21197]: Add lib64 -> lib symlink in venvs on 64-bit non-OS X POSIX.

bpo-17498 [https://bugs.python.org/issue?@action=redirect&bpo=17498]: Some SMTP servers disconnect after certain errors, violating strict RFC conformance. Instead of losing the error code when we issue the subsequent RSET, smtplib now returns the error code and defers raising the SMTPServerDisconnected error until the next command is issued.

bpo-17826 [https://bugs.python.org/issue?@action=redirect&bpo=17826]: setting an iterable side_effect on a mock function created by create_autospec now works. Patch by Kushal Das.

bpo-7776 [https://bugs.python.org/issue?@action=redirect&bpo=7776]: Fix Host: header and reconnection when using http.client.HTTPConnection.set_tunnel(). Patch by Nikolaus Rath.

bpo-20968 [https://bugs.python.org/issue?@action=redirect&bpo=20968]: unittest.mock.MagicMock now supports division. Patch by Johannes Baiter.

bpo-21529 [https://bugs.python.org/issue?@action=redirect&bpo=21529]: Fix arbitrary memory access in JSONDecoder.raw_decode with a negative second parameter. Bug reported by Guido Vranken. (See also: CVE-2014-4616)

bpo-21169 [https://bugs.python.org/issue?@action=redirect&bpo=21169]: getpass now handles non-ascii characters that the input stream encoding cannot encode by re-encoding using the replace error handler.

bpo-21171 [https://bugs.python.org/issue?@action=redirect&bpo=21171]: Fixed undocumented filter API of the rot13 codec. Patch by Berker Peksag.

bpo-20539 [https://bugs.python.org/issue?@action=redirect&bpo=20539]: Improved math.factorial error message for large positive inputs and changed exception type (OverflowError -> ValueError) for large negative inputs.

bpo-21172 [https://bugs.python.org/issue?@action=redirect&bpo=21172]: isinstance check relaxed from dict to collections.Mapping.

bpo-21155 [https://bugs.python.org/issue?@action=redirect&bpo=21155]: asyncio.EventLoop.create_unix_server() now raises a ValueError if path and sock are specified at the same time.

bpo-21136 [https://bugs.python.org/issue?@action=redirect&bpo=21136]: Avoid unnecessary normalization of Fractions resulting from power and other operations. Patch by Raymond Hettinger.

bpo-17621 [https://bugs.python.org/issue?@action=redirect&bpo=17621]: Introduce importlib.util.LazyLoader.

bpo-21076 [https://bugs.python.org/issue?@action=redirect&bpo=21076]: signal module constants were turned into enums. Patch by Giampaolo Rodola’.

bpo-20636 [https://bugs.python.org/issue?@action=redirect&bpo=20636]: Improved the repr of Tkinter widgets.

bpo-19505 [https://bugs.python.org/issue?@action=redirect&bpo=19505]: The items, keys, and values views of OrderedDict now support reverse iteration using reversed().

bpo-21149 [https://bugs.python.org/issue?@action=redirect&bpo=21149]: Improved thread-safety in logging cleanup during interpreter shutdown. Thanks to Devin Jeanpierre for the patch.

bpo-21058 [https://bugs.python.org/issue?@action=redirect&bpo=21058]: Fix a leak of file descriptor in tempfile.NamedTemporaryFile(), close the file descriptor if io.open() fails

bpo-21200 [https://bugs.python.org/issue?@action=redirect&bpo=21200]: Return None from pkgutil.get_loader() when __spec__ is missing.

bpo-21013 [https://bugs.python.org/issue?@action=redirect&bpo=21013]: Enhance ssl.create_default_context() when used for server side sockets to provide better security by default.

bpo-20145 [https://bugs.python.org/issue?@action=redirect&bpo=20145]: assertRaisesRegex and assertWarnsRegex now raise a TypeError if the second argument is not a string or compiled regex.

bpo-20633 [https://bugs.python.org/issue?@action=redirect&bpo=20633]: Replace relative import by absolute import.

bpo-20980 [https://bugs.python.org/issue?@action=redirect&bpo=20980]: Stop wrapping exception when using ThreadPool.

bpo-21082 [https://bugs.python.org/issue?@action=redirect&bpo=21082]: In os.makedirs, do not set the process-wide umask. Note this changes behavior of makedirs when exist_ok=True.

bpo-20990 [https://bugs.python.org/issue?@action=redirect&bpo=20990]: Fix issues found by pyflakes for multiprocessing.

bpo-21015 [https://bugs.python.org/issue?@action=redirect&bpo=21015]: SSL contexts will now automatically select an elliptic curve for ECDH key exchange on OpenSSL 1.0.2 and later, and otherwise default to “prime256v1”.

bpo-21000 [https://bugs.python.org/issue?@action=redirect&bpo=21000]: Improve the command-line interface of json.tool.

bpo-20995 [https://bugs.python.org/issue?@action=redirect&bpo=20995]: Enhance default ciphers used by the ssl module to enable better security and prioritize perfect forward secrecy.

bpo-20884 [https://bugs.python.org/issue?@action=redirect&bpo=20884]: Don’t assume that __file__ is defined on importlib.__init__.

bpo-21499 [https://bugs.python.org/issue?@action=redirect&bpo=21499]: Ignore __builtins__ in several test_importlib.test_api tests.

bpo-20627 [https://bugs.python.org/issue?@action=redirect&bpo=20627]: xmlrpc.client.ServerProxy is now a context manager.

bpo-19165 [https://bugs.python.org/issue?@action=redirect&bpo=19165]: The formatter module now raises DeprecationWarning instead of PendingDeprecationWarning.

bpo-13936 [https://bugs.python.org/issue?@action=redirect&bpo=13936]: Remove the ability of datetime.time instances to be considered false in boolean contexts.

bpo-18931 [https://bugs.python.org/issue?@action=redirect&bpo=18931]: selectors module now supports /dev/poll on Solaris. Patch by Giampaolo Rodola’.

bpo-19977 [https://bugs.python.org/issue?@action=redirect&bpo=19977]: When the LC_TYPE locale is the POSIX locale (C locale), sys.stdin and sys.stdout are now using the surrogateescape error handler, instead of the strict error handler.

bpo-20574 [https://bugs.python.org/issue?@action=redirect&bpo=20574]: Implement incremental decoder for cp65001 code (Windows code page 65001, Microsoft UTF-8).

bpo-20879 [https://bugs.python.org/issue?@action=redirect&bpo=20879]: Delay the initialization of encoding and decoding tables for base32, ascii85 and base85 codecs in the base64 module, and delay the initialization of the unquote_to_bytes() table of the urllib.parse module, to not waste memory if these modules are not used.

bpo-19157 [https://bugs.python.org/issue?@action=redirect&bpo=19157]: Include the broadcast address in the usuable hosts for IPv6 in ipaddress.

bpo-11599 [https://bugs.python.org/issue?@action=redirect&bpo=11599]: When an external command (e.g. compiler) fails, distutils now prints out the whole command line (instead of just the command name) if the environment variable DISTUTILS_DEBUG is set.

bpo-4931 [https://bugs.python.org/issue?@action=redirect&bpo=4931]: distutils should not produce unhelpful “error: None” messages anymore. distutils.util.grok_environment_error is kept but doc-deprecated.

bpo-20875 [https://bugs.python.org/issue?@action=redirect&bpo=20875]: Prevent possible gzip “‘read’ is not defined” NameError. Patch by Claudiu Popa.

bpo-11558 [https://bugs.python.org/issue?@action=redirect&bpo=11558]: email.message.Message.attach now returns a more useful error message if attach is called on a message for which is_multipart is False.

bpo-20283 [https://bugs.python.org/issue?@action=redirect&bpo=20283]: RE pattern methods now accept the string keyword parameters as documented. The pattern and source keyword parameters are left as deprecated aliases.

bpo-20778 [https://bugs.python.org/issue?@action=redirect&bpo=20778]: Fix modulefinder to work with bytecode-only modules.

bpo-20791 [https://bugs.python.org/issue?@action=redirect&bpo=20791]: copy.copy() now doesn’t make a copy when the input is a bytes object. Initial patch by Peter Otten.

bpo-19748 [https://bugs.python.org/issue?@action=redirect&bpo=19748]: On AIX, time.mktime() now raises an OverflowError for year outsize range [1902; 2037].

bpo-19573 [https://bugs.python.org/issue?@action=redirect&bpo=19573]: inspect.signature: Use enum for parameter kind constants.

bpo-20726 [https://bugs.python.org/issue?@action=redirect&bpo=20726]: inspect.signature: Make Signature and Parameter picklable.

bpo-17373 [https://bugs.python.org/issue?@action=redirect&bpo=17373]: Add inspect.Signature.from_callable method.

bpo-20378 [https://bugs.python.org/issue?@action=redirect&bpo=20378]: Improve repr of inspect.Signature and inspect.Parameter.

bpo-20816 [https://bugs.python.org/issue?@action=redirect&bpo=20816]: Fix inspect.getcallargs() to raise correct TypeError for missing keyword-only arguments. Patch by Jeremiah Lowin.

bpo-20817 [https://bugs.python.org/issue?@action=redirect&bpo=20817]: Fix inspect.getcallargs() to fail correctly if more than 3 arguments are missing. Patch by Jeremiah Lowin.

bpo-6676 [https://bugs.python.org/issue?@action=redirect&bpo=6676]: Ensure a meaningful exception is raised when attempting to parse more than one XML document per pyexpat xmlparser instance. (Original patches by Hirokazu Yamamoto and Amaury Forgeot d’Arc, with suggested wording by David Gutteridge)

bpo-21117 [https://bugs.python.org/issue?@action=redirect&bpo=21117]: Fix inspect.signature to better support functools.partial. Due to the specifics of functools.partial implementation, positional-or-keyword arguments passed as keyword arguments become keyword-only.

bpo-20334 [https://bugs.python.org/issue?@action=redirect&bpo=20334]: inspect.Signature and inspect.Parameter are now hashable. Thanks to Antony Lee for bug reports and suggestions.

bpo-15916 [https://bugs.python.org/issue?@action=redirect&bpo=15916]: doctest.DocTestSuite returns an empty unittest.TestSuite instead of raising ValueError if it finds no tests

bpo-21209 [https://bugs.python.org/issue?@action=redirect&bpo=21209]: Fix asyncio.tasks.CoroWrapper to workaround a bug in yield-from implementation in CPythons prior to 3.4.1.

asyncio: Add gi_{frame,running,code} properties to CoroWrapper (upstream bpo-163 [https://bugs.python.org/issue?@action=redirect&bpo=163]).

bpo-21311 [https://bugs.python.org/issue?@action=redirect&bpo=21311]: Avoid exception in _osx_support with non-standard compiler configurations. Patch by John Szakmeister.

bpo-11571 [https://bugs.python.org/issue?@action=redirect&bpo=11571]: Ensure that the turtle window becomes the topmost window when launched on OS X.

bpo-21801 [https://bugs.python.org/issue?@action=redirect&bpo=21801]: Validate that __signature__ is None or an instance of Signature.

bpo-21923 [https://bugs.python.org/issue?@action=redirect&bpo=21923]: Prevent AttributeError in distutils.sysconfig.customize_compiler due to possible uninitialized _config_vars.

bpo-21323 [https://bugs.python.org/issue?@action=redirect&bpo=21323]: Fix http.server to again handle scripts in CGI subdirectories, broken by the fix for security bpo-19435 [https://bugs.python.org/issue?@action=redirect&bpo=19435]. Patch by Zach Byrne.

bpo-22733 [https://bugs.python.org/issue?@action=redirect&bpo=22733]: Fix ffi_prep_args not zero-extending argument values correctly on 64-bit Windows.

bpo-23302 [https://bugs.python.org/issue?@action=redirect&bpo=23302]: Default to TCP_NODELAY=1 upon establishing an HTTPConnection. Removed use of hard-coded MSS as it’s an optimization that’s no longer needed with Nagle disabled.

IDLE

bpo-20577 [https://bugs.python.org/issue?@action=redirect&bpo=20577]: Configuration of the max line length for the FormatParagraph extension has been moved from the General tab of the Idle preferences dialog to the FormatParagraph tab of the Config Extensions dialog. Patch by Tal Einat.

bpo-16893 [https://bugs.python.org/issue?@action=redirect&bpo=16893]: Update Idle doc chapter to match current Idle and add new information.

bpo-3068 [https://bugs.python.org/issue?@action=redirect&bpo=3068]: Add Idle extension configuration dialog to Options menu. Changes are written to HOME/.idlerc/config-extensions.cfg. Original patch by Tal Einat.

bpo-16233 [https://bugs.python.org/issue?@action=redirect&bpo=16233]: A module browser (File : Class Browser, Alt+C) requires an editor window with a filename. When Class Browser is requested otherwise, from a shell, output window, or ‘Untitled’ editor, Idle no longer displays an error box. It now pops up an Open Module box (Alt+M). If a valid name is entered and a module is opened, a corresponding browser is also opened.

bpo-4832 [https://bugs.python.org/issue?@action=redirect&bpo=4832]: Save As to type Python files automatically adds .py to the name you enter (even if your system does not display it). Some systems automatically add .txt when type is Text files.

bpo-21986 [https://bugs.python.org/issue?@action=redirect&bpo=21986]: Code objects are not normally pickled by the pickle module. To match this, they are no longer pickled when running under Idle.

bpo-17390 [https://bugs.python.org/issue?@action=redirect&bpo=17390]: Adjust Editor window title; remove ‘Python’, move version to end.

bpo-14105 [https://bugs.python.org/issue?@action=redirect&bpo=14105]: Idle debugger breakpoints no longer disappear when inserting or deleting lines.

bpo-17172 [https://bugs.python.org/issue?@action=redirect&bpo=17172]: Turtledemo can now be run from Idle. Currently, the entry is on the Help menu, but it may move to Run. Patch by Ramchandra Apt and Lita Cho.

bpo-21765 [https://bugs.python.org/issue?@action=redirect&bpo=21765]: Add support for non-ascii identifiers to HyperParser.

bpo-21940 [https://bugs.python.org/issue?@action=redirect&bpo=21940]: Add unittest for WidgetRedirector. Initial patch by Saimadhav Heblikar.

bpo-18592 [https://bugs.python.org/issue?@action=redirect&bpo=18592]: Add unittest for SearchDialogBase. Patch by Phil Webster.

bpo-21694 [https://bugs.python.org/issue?@action=redirect&bpo=21694]: Add unittest for ParenMatch. Patch by Saimadhav Heblikar.

bpo-21686 [https://bugs.python.org/issue?@action=redirect&bpo=21686]: add unittest for HyperParser. Original patch by Saimadhav Heblikar.

bpo-12387 [https://bugs.python.org/issue?@action=redirect&bpo=12387]: Add missing upper(lower)case versions of default Windows key bindings for Idle so Caps Lock does not disable them. Patch by Roger Serwy.

bpo-21695 [https://bugs.python.org/issue?@action=redirect&bpo=21695]: Closing a Find-in-files output window while the search is still in progress no longer closes Idle.

bpo-18910 [https://bugs.python.org/issue?@action=redirect&bpo=18910]: Add unittest for textView. Patch by Phil Webster.

bpo-18292 [https://bugs.python.org/issue?@action=redirect&bpo=18292]: Add unittest for AutoExpand. Patch by Saihadhav Heblikar.

bpo-18409 [https://bugs.python.org/issue?@action=redirect&bpo=18409]: Add unittest for AutoComplete. Patch by Phil Webster.

bpo-21477 [https://bugs.python.org/issue?@action=redirect&bpo=21477]: htest.py - Improve framework, complete set of tests. Patches by Saimadhav Heblikar

bpo-18104 [https://bugs.python.org/issue?@action=redirect&bpo=18104]: Add idlelib/idle_test/htest.py with a few sample tests to begin consolidating and improving human-validated tests of Idle. Change other files as needed to work with htest. Running the module as __main__ runs all tests.

bpo-21139 [https://bugs.python.org/issue?@action=redirect&bpo=21139]: Change default paragraph width to 72, the PEP 8 recommendation.

bpo-21284 [https://bugs.python.org/issue?@action=redirect&bpo=21284]: Paragraph reformat test passes after user changes reformat width.

bpo-17654 [https://bugs.python.org/issue?@action=redirect&bpo=17654]: Ensure IDLE menus are customized properly on OS X for non-framework builds and for all variants of Tk.

bpo-23180 [https://bugs.python.org/issue?@action=redirect&bpo=23180]: Rename IDLE “Windows” menu item to “Window”. Patch by Al Sweigart.

Build

bpo-15506 [https://bugs.python.org/issue?@action=redirect&bpo=15506]: Use standard PKG_PROG_PKG_CONFIG autoconf macro in the configure script.

bpo-22935 [https://bugs.python.org/issue?@action=redirect&bpo=22935]: Allow the ssl module to be compiled if openssl doesn’t support SSL 3.

bpo-22592 [https://bugs.python.org/issue?@action=redirect&bpo=22592]: Drop support of the Borland C compiler to build Python. The distutils module still supports it to build extensions.

bpo-22591 [https://bugs.python.org/issue?@action=redirect&bpo=22591]: Drop support of MS-DOS, especially of the DJGPP compiler (MS-DOS port of GCC).

bpo-16537 [https://bugs.python.org/issue?@action=redirect&bpo=16537]: Check whether self.extensions is empty in setup.py. Patch by Jonathan Hosmer.

bpo-22359 [https://bugs.python.org/issue?@action=redirect&bpo=22359]: Remove incorrect uses of recursive make. Patch by Jonas Wagner.

bpo-21958 [https://bugs.python.org/issue?@action=redirect&bpo=21958]: Define HAVE_ROUND when building with Visual Studio 2013 and above. Patch by Zachary Turner.

bpo-18093 [https://bugs.python.org/issue?@action=redirect&bpo=18093]: the programs that embed the CPython runtime are now in a separate “Programs” directory, rather than being kept in the Modules directory.

bpo-15759 [https://bugs.python.org/issue?@action=redirect&bpo=15759]: “make suspicious”, “make linkcheck” and “make doctest” in Doc/ now display special message when and only when there are failures.

bpo-21141 [https://bugs.python.org/issue?@action=redirect&bpo=21141]: The Windows build process no longer attempts to find Perl, instead relying on OpenSSL source being configured and ready to build. The PCbuild\build_ssl.py script has been re-written and re-named to PCbuild\prepare_ssl.py, and takes care of configuring OpenSSL source for both 32 and 64 bit platforms. OpenSSL sources obtained from svn.python.org will always be pre-configured and ready to build.

bpo-21037 [https://bugs.python.org/issue?@action=redirect&bpo=21037]: Add a build option to enable AddressSanitizer support.

bpo-19962 [https://bugs.python.org/issue?@action=redirect&bpo=19962]: The Windows build process now creates “python.bat” in the root of the source tree, which passes all arguments through to the most recently built interpreter.

bpo-21285 [https://bugs.python.org/issue?@action=redirect&bpo=21285]: Refactor and fix curses configure check to always search in a ncursesw directory.

bpo-15234 [https://bugs.python.org/issue?@action=redirect&bpo=15234]: For BerkelyDB and Sqlite, only add the found library and include directories if they aren’t already being searched. This avoids an explicit runtime library dependency.

bpo-17861 [https://bugs.python.org/issue?@action=redirect&bpo=17861]: Tools/scripts/generate_opcode_h.py automatically regenerates Include/opcode.h from Lib/opcode.py if the latter gets any change.

bpo-20644 [https://bugs.python.org/issue?@action=redirect&bpo=20644]: OS X installer build support for documentation build changes in 3.4.1: assume externally supplied sphinx-build is available in /usr/bin.

bpo-20022 [https://bugs.python.org/issue?@action=redirect&bpo=20022]: Eliminate use of deprecated bundlebuilder in OS X builds.

bpo-15968 [https://bugs.python.org/issue?@action=redirect&bpo=15968]: Incorporated Tcl, Tk, and Tix builds into the Windows build solution.

bpo-17095 [https://bugs.python.org/issue?@action=redirect&bpo=17095]: Fix Modules/Setup shared support.

bpo-21811 [https://bugs.python.org/issue?@action=redirect&bpo=21811]: Anticipated fixes to support OS X versions > 10.9.

bpo-21166 [https://bugs.python.org/issue?@action=redirect&bpo=21166]: Prevent possible segfaults and other random failures of python –generate-posix-vars in pybuilddir.txt build target.

bpo-18096 [https://bugs.python.org/issue?@action=redirect&bpo=18096]: Fix library order returned by python-config.

bpo-17219 [https://bugs.python.org/issue?@action=redirect&bpo=17219]: Add library build dir for Python extension cross-builds.

bpo-22919 [https://bugs.python.org/issue?@action=redirect&bpo=22919]: Windows build updated to support VC 14.0 (Visual Studio 2015), which will be used for the official release.

bpo-21236 [https://bugs.python.org/issue?@action=redirect&bpo=21236]: Build _msi.pyd with cabinet.lib instead of fci.lib

bpo-17128 [https://bugs.python.org/issue?@action=redirect&bpo=17128]: Use private version of OpenSSL for OS X 10.5+ installer.

C API

bpo-14203 [https://bugs.python.org/issue?@action=redirect&bpo=14203]: Remove obsolete support for view==NULL in PyBuffer_FillInfo(), bytearray_getbuffer(), bytesiobuf_getbuffer() and array_buffer_getbuf(). All functions now raise BufferError in that case.

bpo-22445 [https://bugs.python.org/issue?@action=redirect&bpo=22445]: PyBuffer_IsContiguous() now implements precise contiguity tests, compatible with NumPy’s NPY_RELAXED_STRIDES_CHECKING compilation flag. Previously the function reported false negatives for corner cases.

bpo-22079 [https://bugs.python.org/issue?@action=redirect&bpo=22079]: PyType_Ready() now checks that statically allocated type has no dynamically allocated bases.

bpo-22453 [https://bugs.python.org/issue?@action=redirect&bpo=22453]: Removed non-documented macro PyObject_REPR().

bpo-18395 [https://bugs.python.org/issue?@action=redirect&bpo=18395]: Rename _Py_char2wchar() to Py_DecodeLocale(), rename _Py_wchar2char() to Py_EncodeLocale(), and document these functions.

bpo-21233 [https://bugs.python.org/issue?@action=redirect&bpo=21233]: Add new C functions: PyMem_RawCalloc(), PyMem_Calloc(), PyObject_Calloc(), _PyObject_GC_Calloc(). bytes(int) is now using calloc() instead of malloc() for large objects which is faster and use less memory.

bpo-20942 [https://bugs.python.org/issue?@action=redirect&bpo=20942]: PyImport_ImportFrozenModuleObject() no longer sets __file__ to match what importlib does; this affects _frozen_importlib as well as any module loaded using imp.init_frozen().

Documentation

bpo-19548 [https://bugs.python.org/issue?@action=redirect&bpo=19548]: Update the codecs module documentation to better cover the distinction between text encodings and other codecs, together with other clarifications. Patch by Martin Panter.

bpo-22394 [https://bugs.python.org/issue?@action=redirect&bpo=22394]: Doc/Makefile now supports make venv PYTHON=../python to create a venv for generating the documentation, e.g., make html PYTHON=venv/bin/python3.

bpo-21514 [https://bugs.python.org/issue?@action=redirect&bpo=21514]: The documentation of the json module now refers to new JSON RFC 7159 instead of obsoleted RFC 4627.

bpo-21777 [https://bugs.python.org/issue?@action=redirect&bpo=21777]: The binary sequence methods on bytes and bytearray are now documented explicitly, rather than assuming users will be able to derive the expected behaviour from the behaviour of the corresponding str methods.

bpo-6916 [https://bugs.python.org/issue?@action=redirect&bpo=6916]: undocument deprecated asynchat.fifo class.

bpo-17386 [https://bugs.python.org/issue?@action=redirect&bpo=17386]: Expanded functionality of the Doc/make.bat script to make it much more comparable to Doc/Makefile.

bpo-21312 [https://bugs.python.org/issue?@action=redirect&bpo=21312]: Update the thread_foobar.h template file to include newer threading APIs. Patch by Jack McCracken.

bpo-21043 [https://bugs.python.org/issue?@action=redirect&bpo=21043]: Remove the recommendation for specific CA organizations and to mention the ability to load the OS certificates.

bpo-20765 [https://bugs.python.org/issue?@action=redirect&bpo=20765]: Add missing documentation for PurePath.with_name() and PurePath.with_suffix().

bpo-19407 [https://bugs.python.org/issue?@action=redirect&bpo=19407]: New package installation and distribution guides based on the Python Packaging Authority tools. Existing guides have been retained as legacy links from the distutils docs, as they still contain some required reference material for tool developers that isn’t recorded anywhere else.

bpo-19697 [https://bugs.python.org/issue?@action=redirect&bpo=19697]: Document cases where __main__.__spec__ is None.

Tests

bpo-18982 [https://bugs.python.org/issue?@action=redirect&bpo=18982]: Add tests for CLI of the calendar module.

bpo-19548 [https://bugs.python.org/issue?@action=redirect&bpo=19548]: Added some additional checks to test_codecs to ensure that statements in the updated documentation remain accurate. Patch by Martin Panter.

bpo-22838 [https://bugs.python.org/issue?@action=redirect&bpo=22838]: All test_re tests now work with unittest test discovery.

bpo-22173 [https://bugs.python.org/issue?@action=redirect&bpo=22173]: Update lib2to3 tests to use unittest test discovery.

bpo-16000 [https://bugs.python.org/issue?@action=redirect&bpo=16000]: Convert test_curses to use unittest.

bpo-21456 [https://bugs.python.org/issue?@action=redirect&bpo=21456]: Skip two tests in test_urllib2net.py if _ssl module not present. Patch by Remi Pointel.

bpo-20746 [https://bugs.python.org/issue?@action=redirect&bpo=20746]: Fix test_pdb to run in refleak mode (-R). Patch by Xavier de Gaye.

bpo-22060 [https://bugs.python.org/issue?@action=redirect&bpo=22060]: test_ctypes has been somewhat cleaned up and simplified; it now uses unittest test discovery to find its tests.

bpo-22104 [https://bugs.python.org/issue?@action=redirect&bpo=22104]: regrtest.py no longer holds a reference to the suite of tests loaded from test modules that don’t define test_main().

bpo-22111 [https://bugs.python.org/issue?@action=redirect&bpo=22111]: Assorted cleanups in test_imaplib. Patch by Milan Oberkirch.

bpo-22002 [https://bugs.python.org/issue?@action=redirect&bpo=22002]: Added load_package_tests function to test.support and used it to implement/augment test discovery in test_asyncio, test_email, test_importlib, test_json, and test_tools.

bpo-21976 [https://bugs.python.org/issue?@action=redirect&bpo=21976]: Fix test_ssl to accept LibreSSL version strings. Thanks to William Orr.

bpo-21918 [https://bugs.python.org/issue?@action=redirect&bpo=21918]: Converted test_tools from a module to a package containing separate test files for each tested script.

bpo-9554 [https://bugs.python.org/issue?@action=redirect&bpo=9554]: Use modern unittest features in test_argparse. Initial patch by Denver Coneybeare and Radu Voicilas.

bpo-20155 [https://bugs.python.org/issue?@action=redirect&bpo=20155]: Changed HTTP method names in failing tests in test_httpservers so that packet filtering software (specifically Windows Base Filtering Engine) does not interfere with the transaction semantics expected by the tests.

bpo-19493 [https://bugs.python.org/issue?@action=redirect&bpo=19493]: Refactored the ctypes test package to skip tests explicitly rather than silently.

bpo-18492 [https://bugs.python.org/issue?@action=redirect&bpo=18492]: All resources are now allowed when tests are not run by regrtest.py.

bpo-21634 [https://bugs.python.org/issue?@action=redirect&bpo=21634]: Fix pystone micro-benchmark: use floor division instead of true division to benchmark integers instead of floating point numbers. Set pystone version to 1.2. Patch written by Lennart Regebro.

bpo-21605 [https://bugs.python.org/issue?@action=redirect&bpo=21605]: Added tests for Tkinter images.

bpo-21493 [https://bugs.python.org/issue?@action=redirect&bpo=21493]: Added test for ntpath.expanduser(). Original patch by Claudiu Popa.

bpo-19925 [https://bugs.python.org/issue?@action=redirect&bpo=19925]: Added tests for the spwd module. Original patch by Vajrasky Kok.

bpo-21522 [https://bugs.python.org/issue?@action=redirect&bpo=21522]: Added Tkinter tests for Listbox.itemconfigure(), PanedWindow.paneconfigure(), and Menu.entryconfigure().

bpo-17756 [https://bugs.python.org/issue?@action=redirect&bpo=17756]: Fix test_code test when run from the installed location.

bpo-17752 [https://bugs.python.org/issue?@action=redirect&bpo=17752]: Fix distutils tests when run from the installed location.

bpo-18604 [https://bugs.python.org/issue?@action=redirect&bpo=18604]: Consolidated checks for GUI availability. All platforms now at least check whether Tk can be instantiated when the GUI resource is requested.

bpo-21275 [https://bugs.python.org/issue?@action=redirect&bpo=21275]: Fix a socket test on KFreeBSD.

bpo-21223 [https://bugs.python.org/issue?@action=redirect&bpo=21223]: Pass test_site/test_startup_imports when some of the extensions are built as builtins.

bpo-20635 [https://bugs.python.org/issue?@action=redirect&bpo=20635]: Added tests for Tk geometry managers.

Add test case for freeze.

bpo-20743 [https://bugs.python.org/issue?@action=redirect&bpo=20743]: Fix a reference leak in test_tcl.

bpo-21097 [https://bugs.python.org/issue?@action=redirect&bpo=21097]: Move test_namespace_pkgs into test_importlib.

bpo-21503 [https://bugs.python.org/issue?@action=redirect&bpo=21503]: Use test_both() consistently in test_importlib.

bpo-20939 [https://bugs.python.org/issue?@action=redirect&bpo=20939]: Avoid various network test failures due to new redirect of http://www.python.org/ to https://www.python.org: use http://www.example.com instead.

bpo-20668 [https://bugs.python.org/issue?@action=redirect&bpo=20668]: asyncio tests no longer rely on tests.txt file. (Patch by Vajrasky Kok)

bpo-21093 [https://bugs.python.org/issue?@action=redirect&bpo=21093]: Prevent failures of ctypes test_macholib on OS X if a copy of libz exists in $HOME/lib or /usr/local/lib.

bpo-22770 [https://bugs.python.org/issue?@action=redirect&bpo=22770]: Prevent some Tk segfaults on OS X when running gui tests.

bpo-23211 [https://bugs.python.org/issue?@action=redirect&bpo=23211]: Workaround test_logging failure on some OS X 10.6 systems.

bpo-23345 [https://bugs.python.org/issue?@action=redirect&bpo=23345]: Prevent test_ssl failures with large OpenSSL patch level values (like 0.9.8zc).

Tools/Demos

bpo-22314 [https://bugs.python.org/issue?@action=redirect&bpo=22314]: pydoc now works when the LINES environment variable is set.

bpo-22615 [https://bugs.python.org/issue?@action=redirect&bpo=22615]: Argument Clinic now supports the “type” argument for the int converter. This permits using the int converter with enums and typedefs.

bpo-20076 [https://bugs.python.org/issue?@action=redirect&bpo=20076]: The makelocalealias.py script no longer ignores UTF-8 mapping.

bpo-20079 [https://bugs.python.org/issue?@action=redirect&bpo=20079]: The makelocalealias.py script now can parse the SUPPORTED file from glibc sources and supports command line options for source paths.

bpo-22201 [https://bugs.python.org/issue?@action=redirect&bpo=22201]: Command-line interface of the zipfile module now correctly extracts ZIP files with directory entries. Patch by Ryan Wilson.

bpo-22120 [https://bugs.python.org/issue?@action=redirect&bpo=22120]: For functions using an unsigned integer return converter, Argument Clinic now generates a cast to that type for the comparison to -1 in the generated code. (This suppresses a compilation warning.)

bpo-18974 [https://bugs.python.org/issue?@action=redirect&bpo=18974]: Tools/scripts/diff.py now uses argparse instead of optparse.

bpo-21906 [https://bugs.python.org/issue?@action=redirect&bpo=21906]: Make Tools/scripts/md5sum.py work in Python 3. Patch by Zachary Ware.

bpo-21629 [https://bugs.python.org/issue?@action=redirect&bpo=21629]: Fix Argument Clinic’s “–converters” feature.

Add support for yield from to 2to3.

Add support for the PEP 465 matrix multiplication operator to 2to3.

bpo-16047 [https://bugs.python.org/issue?@action=redirect&bpo=16047]: Fix module exception list and __file__ handling in freeze. Patch by Meador Inge.

bpo-11824 [https://bugs.python.org/issue?@action=redirect&bpo=11824]: Consider ABI tags in freeze. Patch by Meador Inge.

bpo-20535 [https://bugs.python.org/issue?@action=redirect&bpo=20535]: PYTHONWARNING no longer affects the run_tests.py script. Patch by Arfrever Frehtes Taifersar Arahesis.

Windows

bpo-23260 [https://bugs.python.org/issue?@action=redirect&bpo=23260]: Update Windows installer

The bundled version of Tcl/Tk has been updated to 8.6.3. The most visible result of this change is the addition of new native file dialogs when running on Windows Vista or newer. See Tcl/Tk’s TIP 432 for more information. Also, this version of Tcl/Tk includes support for Windows 10.

bpo-17896 [https://bugs.python.org/issue?@action=redirect&bpo=17896]: The Windows build scripts now expect external library sources to be in PCbuild\..\externals rather than PCbuild\..\...

bpo-17717 [https://bugs.python.org/issue?@action=redirect&bpo=17717]: The Windows build scripts now use a copy of NASM pulled from svn.python.org to build OpenSSL.

bpo-21907 [https://bugs.python.org/issue?@action=redirect&bpo=21907]: Improved the batch scripts provided for building Python.

bpo-22644 [https://bugs.python.org/issue?@action=redirect&bpo=22644]: The bundled version of OpenSSL has been updated to 1.0.1j.

bpo-10747 [https://bugs.python.org/issue?@action=redirect&bpo=10747]: Use versioned labels in the Windows start menu. Patch by Olive Kilburn.

bpo-22980 [https://bugs.python.org/issue?@action=redirect&bpo=22980]: .pyd files with a version and platform tag (for example, “.cp35-win32.pyd”) will now be loaded in preference to those without tags.

(For information about older versions, consult the HISTORY file.)

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬의 새로운 기능 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

|

파이썬 자습서

파이썬은 배우기 쉽고, 강력한 프로그래밍 언어입니다. 효율적인 자료 구조들과 객체 지향 프로그래밍에 대해 간단하고도 효과적인 접근법을 제공합니다. 우아한 문법과 동적 타이핑(typing)은, 인터프리터 적인 특징들과 더불어, 대부분 플랫폼과 다양한 문제 영역에서 스크립트 작성과 빠른 응용 프로그램 개발에 이상적인 환경을 제공합니다.

파이썬 인터프리터와 풍부한 표준 라이브러리는 소스나 바이너리 형태로 파이썬 웹 사이트, https://www.python.org/, 에서 무료로 제공되고, 자유롭게 배포할 수 있습니다. 같은 사이트는 제삼자들이 무료로 제공하는 확장 모듈, 프로그램, 도구, 문서들의 배포판이나 링크를 포함합니다.

파이썬 인터프리터는 C 나 C++ (또는 C에서 호출 가능한 다른 언어들)로 구현된 새 함수나 자료 구조를 쉽게 추가할 수 있습니다. 파이썬은 고객화 가능한 응용 프로그램을 위한 확장 언어로도 적합합니다.

이 학습서는 파이썬 언어와 시스템의 기본 개념과 기능들을 격식 없이 소개합니다. 파이썬 인터프리터를 직접 만져볼 수 있도록 돕지만, 모든 예제가 독립적이기 때문에 오프라인에서 읽기에도 적합합니다.

표준 객체들과 모듈들에 대한 설명은 파이썬 표준 라이브러리 를 보세요. 파이썬 언어 레퍼런스 는 언어에 대한 좀 더 형식적인 정의를 제공합니다. C 나 C++ 로 확장하려면 파이썬 인터프리터 확장 및 내장 와 파이썬/C API 레퍼런스 설명서 를 읽으세요. 파이썬을 깊이 있게 다룬 책들도 많습니다.

이 자습서는 포괄적이려고 시도하지 않습니다. 모든 기능을 다루지는 않는데, 심지어 자주 사용되는 기능조차도 그렇습니다. 대신에, 파이썬의 가장 주목할만한 기능들을 소개하고, 언어의 맛과 스타일에 대한 전체적인 인상을 제공합니다. 이 학습서를 읽은 후에는 파이썬 모듈과 프로그램을 작성할 수 있고, 파이썬 표준 라이브러리 에 기술된 다양한 파이썬 라이브러리 모듈들에 대해 학습할 수 있는 준비가 될 것입니다.

용어집 또한 훑어볼 만한 가치가 있습니다.

1. 입맛 돋우기

2. 파이썬 인터프리터 사용하기

2.1. 인터프리터 실행하기

2.1.1. 인자 전달

2.1.2. 대화형 모드

2.2. 인터프리터와 환경

2.2.1. 소스 코드 인코딩

3. 파이썬의 간략한 소개

3.1. 파이썬을 계산기로 사용하기

3.1.1. 숫자

3.1.2. 문자열

3.1.3. 리스트

3.2. 프로그래밍으로의 첫걸음

4. 기타 제어 흐름 도구

4.1. if 문

4.2. for 문

4.3. range() 함수

4.4. 루프의 break 와 continue 문, 그리고 else 절

4.5. pass 문

4.6. 함수 정의하기

4.7. 함수 정의 더 보기

4.7.1. 기본 인자 값

4.7.2. 키워드 인자

4.7.3. 임의의 인자 목록

4.7.4. 인자 목록 언 패킹

4.7.5. 람다 표현식

4.7.6. 도큐멘테이션 문자열

4.7.7. 함수 어노테이션

4.8. 막간극: 코딩 스타일

5. 자료 구조

5.1. 리스트 더 보기

5.1.1. 리스트를 스택으로 사용하기

5.1.2. 리스트를 큐로 사용하기

5.1.3. 리스트 컴프리헨션

5.1.4. 중첩된 리스트 컴프리헨션

5.2. del 문

5.3. 튜플과 시퀀스

5.4. 집합

5.5. 딕셔너리

5.6. 루프 테크닉

5.7. 조건 더 보기

5.8. 시퀀스와 다른 형들을 비교하기

6. 모듈

6.1. 모듈 더 보기

6.1.1. 모듈을 스크립트로 실행하기

6.1.2. 모듈 검색 경로

6.1.3. “컴파일된” 파이썬 파일

6.2. 표준 모듈들

6.3. dir() 함수

6.4. 패키지

6.4.1. 패키지에서 * 임포트 하기

6.4.2. 패키지 내부 간의 참조

6.4.3. 여러 디렉터리에 있는 패키지

7. 입력과 출력

7.1. 장식적인 출력 포매팅

7.1.1. 포맷 문자열 리터럴

7.1.2. 문자열 format() 메서드

7.1.3. 수동 문자열 포매팅

7.1.4. 예전의 문자열 포매팅

7.2. 파일을 읽고 쓰기

7.2.1. 파일 객체의 매소드

7.2.2. json 으로 구조적인 데이터를 저장하기

8. 에러와 예외

8.1. 문법 에러

8.2. 예외

8.3. 예외 처리하기

8.4. 예외 일으키기

8.5. 사용자 정의 예외

8.6. 뒷정리 동작 정의하기

8.7. 미리 정의된 뒷정리 동작들

9. 클래스

9.1. 이름과 객체에 관한 한마디

9.2. 파이썬 스코프와 이름 공간

9.2.1. 스코프와 이름 공간 예

9.3. 클래스와의 첫 만남

9.3.1. 클래스 정의 문법

9.3.2. 클래스 객체

9.3.3. 인스턴스 객체

9.3.4. 메서드 객체

9.3.5. 클래스와 인스턴스 변수

9.4. 기타 주의사항들

9.5. 상속

9.5.1. 다중 상속

9.6. 비공개 변수

9.7. 잡동사니

9.8. 이터레이터

9.9. 제너레이터

9.10. 제너레이터 표현식

10. 표준 라이브러리 둘러보기

10.1. 운영 체제 인터페이스

10.2. 파일 와일드카드

10.3. 명령행 인자

10.4. 에러 출력 리디렉션과 프로그램 종료

10.5. 문자열 패턴 매칭

10.6. 수학

10.7. 인터넷 액세스

10.8. 날짜와 시간

10.9. 데이터 압축

10.10. 성능 측정

10.11. 품질 관리

10.12. 배터리가 포함됩니다

11. 표준 라이브러리 둘러보기 — 2부

11.1. 출력 포매팅

11.2. 템플릿

11.3. 바이너리 데이터 레코드 배치 작업

11.4. 다중 스레딩

11.5. 로깅

11.6. 약한 참조

11.7. 리스트 작업 도구

11.8. 10진 부동 소수점 산술

12. 가상 환경 및 패키지

12.1. 소개

12.2. 가상 환경 만들기

12.3. pip로 패키지 관리하기

13. 이제 뭘 하지?

14. 대화형 입력 편집 및 히스토리 치환

14.1. 탭 완성 및 히스토리 편집

14.2. 대화형 인터프리터 대안

15. 부동 소수점 산술: 문제점 및 한계

15.1. 표현 오류

16. 부록

16.1. 대화형 모드

16.1.1. 에러 처리

16.1.2. 실행 가능한 파이썬 스크립트

16.1.3. 대화형 시작 파일

16.1.4. 커스터마이제이션 모듈

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 자습서 »

|

1. 입맛 돋우기

여러분이 컴퓨터를 많이 사용한다면, 결국 자동화하고 싶은 작업을 발견하게 됩니다. 예를 들어, 많은 텍스트 파일들을 검색-수정하고 싶거나, 사진 파일들을 복잡한 방법으로 이름을 바꾸거나 재배치하고 싶을 수 있습니다. 어쩌면 자그마한 자신만의 데이터베이스나 GUI 응용 프로그램, 또는 간단한 게임을 만들고 싶을 것입니다.

만약 여러분이 전문 소프트웨어 개발자라면, 여러 C/C++/Java 라이브러리들을 갖고 작업해야만 할 수 있는데, 일반적인 코드작성/컴파일/테스트/재컴파일 순환이 너무 느리다는 것을 깨닫게 됩니다. 어쩌면 그 라이브러리들을 위한 테스트 스위트를 작성하다가, 테스트 코드 작성에 따분해하는 자신을 발견하게 됩니다. 또는 확장 언어를 사용하는 프로그램을 작성했는데, 완전히 새로운 언어 전체를 설계하고 구현하고 싶지 않을 수 있습니다.

파이썬은 바로 여러분을 위한 언어입니다.

여러분은 이런 작업들을 유닉스 셸 스크립트나 윈도우 배치 파일을 작성해서 해결할 수도 있습니다. 하지만 셸 스크립트는 파일을 이리저리 옮기거나 텍스트 데이터를 변경하는 데는 쓸모 있지만, GUI 응용 프로그램이나 게임을 만드는 데는 적합하지 않습니다. C/C++/Java 프로그램을 작성할 수도 있지만, 첫 초벌 프로그램을 만드는데도 막대한 개발 시간이 들어갑니다. 파이썬은 사용하기에 더 간단하고, 윈도우, 맥 OS X, 유닉스 운영체제에서 사용할 수 있으며, 더 빨리 작업을 완료할 수 있도록 합니다.

파이썬은 사용이 간단하지만, 제대로 갖춰진 프로그래밍 언어인데, 셸 스크립트나 배치 파일보다 더 많은 구조를 제공하고 커다란 프로그램을 위한 지원을 제공합니다. 반면에, 파이썬은 C보다 훨씬 많은 에러 검사를 제공하고, 유연한 배열과 딕셔너리같은 고수준의 자료형들을 내장하고 있습니다. 더 일반적인 자료형들 때문에 Awk 나 Perl보다도 더 많은 문제영역에 쓸모가 있는데, 그러면서도 여전히 많은 것들이 적어도 이들 언어를 사용하는 것만큼 파이썬에서도 쉽게 해결할 수 있습니다.

파이썬은 여러분의 프로그램을 여러 모듈로 나눌 수 있도록 하는데, 각 모듈은 다른 파이썬 프로그램에서 재사용할 수 있습니다. 대규모의 표준 모듈들이 따라오는데 여러분의 프로그램 기초로 사용하거나 파이썬 프로그래밍을 배우기 위한 예제로 활용할 수 있습니다. 이 모듈에는 파일 입출력, 시스템 호출, 소켓들이 포함되는데, 심지어 Tk 와 같은 GUI 도구상자에 대한 인터페이스도 들어있습니다.

파이썬은 인터프리터 언어입니다. 컴파일과 링크 단계가 필요 없으므로 개발 시간을 상당히 단축해줍니다. 인터프리터는 대화형으로 사용할 수 있어서, 언어의 기능을 실험하거나, 쓰고 버릴 프로그램을 만들거나, 바닥부터 프로그램을 만들어가는 동안 함수들을 테스트하기 쉽습니다. 간편한 탁상용 계산기이기도 합니다.

파이썬은 간결하고 읽기 쉽게 프로그램을 작성할 수 있도록 합니다. 파이썬 프로그램은 여러 가지 이유로 같은 기능의 C, C++, Java 프로그램들에 비교해 간결합니다:

고수준의 자료형 때문에 복잡한 연산을 한 문장으로 표현할 수 있습니다;

문장의 묶음은 괄호 대신에 들여쓰기를 통해 이루어집니다;

변수나 인자의 선언이 필요 없다.

파이썬은 확장 가능 하다: C로 프로그램하는 법을 안다면, 인터프리터에 새로운 내장 함수나 자료형을 추가해서, 핵심 연산을 최대 속도로 수행하거나 바이너리 형태로만 제공되는 라이브러리(가령 업체가 제공하는 그래픽스 라이브러리)에 파이썬 프로그램을 연결할 수 있습니다. 진짜 파이썬에 매료되었다면, C로 만든 응용 프로그램에 파이썬 인터프리터를 연결하여 그 응용 프로그램의 확장이나 명령 언어로 사용할 수 있습니다.

파이썬 이라는 이름은 “Monty Python’s Flying Circus”라는 BBC 쇼에서 따온 것이고, 파충류와는 아무런 관련이 없습니다. 문서에서 Monty Python의 농담을 인용하는 것은 허락된 것일 뿐만 아니라, 권장되고 있습니다.

이제 여러분은 파이썬에 한껏 흥분한 상태고 좀 더 자세히 들여다보길 원할 것입니다. 언어를 배우는 가장 좋은 방법은 사용하는 것이기 때문에, 이 학습서를 읽으면서 직접 파이썬 인터프리터를 만져볼 것을 권합니다.

다음 장에서, 인터프리터를 사용하는 방법을 설명합니다. 이것은 약간 지루할 수도 있는 정보지만, 이후에 나오는 예제들을 실행하기 위해서는 꼭 필요합니다.

자습서의 나머지는 파이썬 언어와 시스템의 여러 기능을 예제를 통해 소개합니다. 간단한 표현식, 문장, 자료형에서 출발해서 함수와 모듈을 거쳐, 마지막으로 예외와 사용자 정의 클래스와 같은 고급 개념들을 다룹니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 자습서 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 자습서 »

|

2. 파이썬 인터프리터 사용하기

2.1. 인터프리터 실행하기

파이썬 인터프리터는 보통 /usr/local/bin/python3.7 에 설치됩니다; 유닉스 셸의 검색 경로에 /usr/local/bin 를 넣으면 명령:

python3.7

을 셸에 입력해서 실행할 수 있습니다. 1 인터프리터가 위치하는 디렉터리의 선택은 설치 옵션이기 때문에, 다른 장소도 가능합니다; 주변의 파이썬 전문가나 시스템 관리자에게 확인할 필요가 있습니다. (예를 들어, /usr/local/python 도 널리 사용되는 위치입니다.)

On Windows machines where you have installed Python from the Microsoft Store, the python3.7 command will be available. If you have the py.exe launcher installed, you can use the py command. See Excursus: Setting environment variables for other ways to launch Python.

기본 프롬프트에서 EOF(end-of-file) 문자(유닉스에서는 Control-D, 윈도우에서는 Control-Z)를 입력하면 인터프리터가 종료하고, 종료 상태 코드는 0 이 됩니다. 이 방법이 통하지 않는다면 quit() 명령을 입력해서 인터프리터를 종료시킬 수 있습니다.

The interpreter’s line-editing features include interactive editing, history substitution and code completion on systems that support the GNU Readline [https://tiswww.case.edu/php/chet/readline/rltop.html] library. Perhaps the quickest check to see whether command line editing is supported is typing Control-P to the first Python prompt you get. If it beeps, you have command line editing; see Appendix 대화형 입력 편집 및 히스토리 치환 for an introduction to the keys. If nothing appears to happen, or if ^P is echoed, command line editing isn’t available; you’ll only be able to use backspace to remove characters from the current line.

인터프리터는 어느 정도 유닉스 셸처럼 동작합니다: tty 장치에 표준 입력이 연결된 상태로 실행되면, 대화형으로 명령을 읽고 실행합니다; 파일명을 인자로 주거나 파일을 표준입력으로 연결한 상태로 실행되면 스크립트를 읽고 실행합니다.

인터프리터를 실행하는 두 번째 방법은 python -c command [arg] ... 인데, command 에 있는 문장들을 실행합니다. 셸의 -c 옵션에 해당합니다. 파이썬 문장은 종종 셸에서 특별한 의미가 있는 공백이나 다른 문자들을 포함하기 때문에, command 전체를 작은따옴표로 감싸주는 것이 좋습니다.

몇몇 파이썬 모듈들은 스크립트로도 쓸모가 있습니다. python -m module [arg] ... 로 실행할 수 있는데, 마치 module 모듈 소스 파일의 경로명을 명령행에 입력한 것처럼 실행되게 됩니다.

스크립트 파일이 사용될 때, 때로 스크립트를 실행한 후에 대화형 모드로 들어가는 것이 편리할 때가 있습니다. 스크립트 앞에 -i 를 전달하면 됩니다.

모든 명령행 옵션은 명령 줄과 환경 에서 찾을 수 있습니다.

2.1.1. 인자 전달

스크립트 이름과 추가의 인자들이 인터프리터로 전달될 때, 문자열의 목록으로 변환된 후 sys 모듈의 argv 변수에 저장됩니다. import sys 를 사용해서 이 목록에 접근할 수 있습니다. 목록의 길이는 최소한 1이고, 스크립트도 추가의 인자도 없는 경우로, sys.argv[0] 은 빈 문자열입니다. 스크립트 이름을 '-' (표준 입력을 뜻한다) 로 주면 sys.argv[0] 는 '-' 가 됩니다. -c command 가 사용되면 sys.argv[0] 는 '-c' 로 설정됩니다. -m module 이 사용되면 sys.argv[0] 는 모듈의 절대 경로명이 됩니다. -c command 나 -m module 뒤에 오는 옵션들은 파이썬 인터프리터가 소모하지 않고 명령이나 모듈이 처리하도록 sys.argv 로 전달됩니다.

2.1.2. 대화형 모드

명령을 tty 에서 읽을 때, 인터프리터가 대화형 모드 로 동작한다고 말합니다. 이 모드에서는 기본 프롬프트 를 표시해서 다음 명령을 요청하는데, 보통 세 개의 …보다 크다 기호입니다 (>>>); 한 줄로 끝나지 않고 이어지는 줄의 입력을 요청할 때는 보조 프롬프트가 사용되는데, 기본적으로 세 개의 점입니다 (...). 인터프리터는 첫 번째 프롬프트를 인쇄하기 전에 버전 번호와 저작권 공지를 포함하는 환영 메시지를 출력합니다.

$ python3.7
Python 3.7 (default, Sep 16 2015, 09:25:04)
[GCC 4.8.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>

이어지는 줄은 여러 줄로 구성된 구조물을 입력할 때 필요합니다. 예를 들자면, 이런 식의 if 문이 가능합니다:

>>> the_world_is_flat = True
>>> if the_world_is_flat:
...     print("Be careful not to fall off!")
...
Be careful not to fall off!

대화형 모드에 대해 더 알고 싶다면, 대화형 모드 를 보세요.

2.2. 인터프리터와 환경

2.2.1. 소스 코드 인코딩

기본적으로, 파이썬 소스 파일들은 UTF-8으로 인코드 된 것으로 취급됩니다. 이 인코딩에서는 대부분 언어에서 사용되는 문자들을 문자열 상수, 식별자, 주석 등에서 함께 사용할 수 있습니다. (하지만 표준 라이브러리는 오직 ASCII 문자만 식별자로 사용하고 있는데, 범용 코드에서는 이 관례를 따르는 것이 좋습니다.) 이 문자들을 모두 올바로 표시하기 위해서는 편집기가 파일이 UTF-8임을 인식해야 하고, 이 파일에 포함된 모든 문자를 지원할 수 있는 폰트를 사용해야 합니다.

인코딩을 기본값 외의 것으로 선언하려면, 파일의 첫 줄에 특별한 형태의 주석 문을 추가해야 합니다. 문법은 이렇습니다:

# -*- coding: encoding -*-

encoding 은 파이썬이 지원하는 코덱 (codecs) 중 하나여야 합니다.

예를 들어, Windows-1252 인코딩을 사용하도록 선언하려면, 소스 코드 파일의 첫 줄은 이렇게 되어야 합니다:

# -*- coding: cp1252 -*-

첫 줄 규칙의 한가지 예외는 소스 코드가 유닉스 “셔뱅 (shebang)” 줄 로 시작하는 경우입니다. 이 경우에, 인코딩 선언은 두 번째 줄에 들어갑니다. 예를 들어:

#!/usr/bin/env python3
# -*- coding: cp1252 -*-

각주

1

유닉스에서, 파이썬 3.x 인터프리터는 보통 python 이라는 이름의 실행 파일로 설치되지 않는데, 동시에 설치되는 파이썬 2.x 실행 파일과 충돌하지 않도록 하기 위해섭니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 자습서 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 자습서 »

|

3. 파이썬의 간략한 소개

다음에 나올 예에서, 입력과 출력은 프롬프트(>>> 와 …)의 존재 여부로 구분됩니다: 예제를 실행하기 위해서는 프롬프트가 나올 때 프롬프트 뒤에 오는 모든 것들을 입력해야 합니다; 프롬프트로 시작하지 않는 줄들은 인터프리터가 출력하는 것들입니다. 예에서 보조 프롬프트 외에 아무것도 없는 줄은 빈 줄을 입력해야 한다는 뜻임에 주의하세요; 여러 줄로 구성된 명령을 끝내는 방법입니다.

이 설명서에 나오는 많은 예는 (대화형 프롬프트에서 입력되는 것들조차도) 주석을 포함하고 있습니다. 파이썬에서 주석은 해시 문자, #, 로 시작하고 줄의 끝까지 이어집니다. 주석은 줄의 처음에서 시작할 수도 있고, 공백이나 코드 뒤에 나올 수도 있습니다. 하지만 문자열 리터럴 안에는 들어갈 수 없습니다. 문자열 리터럴 안에 등장하는 해시 문자는 주석이 아니라 해시 문자일 뿐입니다. 주석은 코드의 의미를 정확히 전달하기 위한 것이고, 파이썬이 해석하지 않는 만큼, 예를 입력할 때는 생략해도 됩니다.

몇 가지 예를 듭니다:

# this is the first comment
spam = 1  # and this is the second comment
          # ... and now a third!
text = "# This is not a comment because it's inside quotes."

3.1. 파이썬을 계산기로 사용하기

몇 가지 간단한 파이썬 명령을 사용해봅시다. 인터프리터를 실행하고 기본 프롬프트, >>>, 를 기다리세요. (얼마 걸리지 않아야 합니다.)

3.1.1. 숫자

인터프리터는 간단한 계산기로 기능합니다: 표현식을 입력하면 값을 출력합니다. 표현식 문법은 간단합니다. +, -, *, / 연산자들은 대부분의 다른 언어들 (예를 들어, 파스칼이나 C)처럼 동작합니다; 괄호 (()) 는 묶는 데 사용합니다. 예를 들어:

>>> 2 + 2
4
>>> 50 - 5*6
20
>>> (50 - 5*6) / 4
5.0
>>> 8 / 5  # division always returns a floating point number
1.6

정수 (예를 들어 2, 4, 20)는 int 형입니다. 소수부가 있는 것들 (예를 들어 5.0, 1.6)은 float 형입니다. 이 자습서 뒤에서 숫자 형들에 관해 더 자세히 살펴볼 예정입니다.

나눗셈 (/) 은 항상 float를 돌려줍니다. 정수 나눗셈 으로 (소수부 없이) 정수 결과를 얻으려면 // 연산자를 사용하면 됩니다; 나머지를 얻으려면 % 를 사용할 수 있습니다:

>>> 17 / 3  # classic division returns a float
5.666666666666667
>>>
>>> 17 // 3  # floor division discards the fractional part
5
>>> 17 % 3  # the % operator returns the remainder of the division
2
>>> 5 * 3 + 2  # result * divisor + remainder
17

파이썬에서는 거듭제곱을 계산할 때 ** 연산자를 사용합니다 1:

>>> 5 ** 2  # 5 squared
25
>>> 2 ** 7  # 2 to the power of 7
128

변수에 값을 대입할 때는 등호(=)를 사용합니다. 이 경우 다음 대화형 프롬프트 전에 표시되는 출력은 없습니다:

>>> width = 20
>>> height = 5 * 9
>>> width * height
900

변수가 “정의되어” 있지 않을 때 (값을 대입하지 않았을 때) 사용하려고 시도하는 것은 에러를 일으킵니다:

>>> n  # try to access an undefined variable
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'n' is not defined

실수를 본격적으로 지원합니다; 서로 다른 형의 피연산자를 갖는 연산자는 정수 피연산자를 실수로 변환합니다:

>>> 4 * 3.75 - 1
14.0

대화형 모드에서는, 마지막에 인쇄된 표현식은 변수 _ 에 대입됩니다. 이것은 파이썬을 탁상용 계산기로 사용할 때, 계산을 이어 가기가 좀 더 쉬워짐을 의미합니다. 예를 들어:

>>> tax = 12.5 / 100
>>> price = 100.50
>>> price * tax
12.5625
>>> price + _
113.0625
>>> round(_, 2)
113.06

이 변수는 사용자로서는 읽기만 가능한 것처럼 취급되어야 합니다. 값을 직접 대입하지 마세요 — 만약 그렇게 한다면 같은 이름의 지역 변수를 새로 만드는 것이 되는데, 내장 변수의 마술 같은 동작을 차단하는 결과를 낳습니다.

int 와 float 에 더해, 파이썬은 Decimal 이나 Fraction 등의 다른 형의 숫자들도 지원합니다. 파이썬은 복소수 에 대한 지원도 내장하고 있는데, 허수부를 가리키는데 j 나 J 접미사를 사용합니다 (예를 들어 3+5j).

3.1.2. 문자열

숫자와는 별개로, 파이썬은 문자열도 다룰 수 있는데 여러 가지 방법으로 표현됩니다. 작은따옴표('...') 나 큰따옴표("...")로 둘러쌀 수 있는데 모두 같은 결과를 줍니다 2. 따옴표를 이스케이핑 할 때는 \ 를 사용할 수 있습니다:

>>> 'spam eggs'  # single quotes
'spam eggs'
>>> 'doesn\'t'  # use \' to escape the single quote...
"doesn't"
>>> "doesn't"  # ...or use double quotes instead
"doesn't"
>>> '"Yes," they said.'
'"Yes," they said.'
>>> "\"Yes,\" they said."
'"Yes," they said.'
>>> '"Isn\'t," they said.'
'"Isn\'t," they said.'

대화형 인터프리터에서, 출력 문자열은 따옴표로 둘러싸여 있고, 특수 문자들은 역 슬래시로 이스케이핑 됩니다. 때로 입력한 것과 달라 보여도 (따옴표의 종류가 바뀔 수 있다), 두 문자열은 동등합니다. 문자열이 작은따옴표를 포함하고 큰따옴표를 포함하지 않으면 큰따옴표가 사용되고, 그 외의 경우는 작은따옴표가 사용됩니다. print() 함수는 따옴표를 생략하고, 이스케이핑된 특수 문자를 출력해서 더 읽기 쉬운 출력을 만들어냅니다:

>>> '"Isn\'t," they said.'
'"Isn\'t," they said.'
>>> print('"Isn\'t," they said.')
"Isn't," they said.
>>> s = 'First line.\nSecond line.'  # \n means newline
>>> s  # without print(), \n is included in the output
'First line.\nSecond line.'
>>> print(s)  # with print(), \n produces a new line
First line.
Second line.

\ 뒤에 나오는 문자가 특수 문자로 취급되게 하고 싶지 않다면, 첫 따옴표 앞에 r 을 붙여서 날 문자열 (raw string) 을 만들 수 있습니다:

>>> print('C:\some\name')  # here \n means newline!
C:\some
ame
>>> print(r'C:\some\name')  # note the r before the quote
C:\some\name

문자열 리터럴은 여러 줄로 확장될 수 있습니다. 한 가지 방법은 삼중 따옴표를 사용하는 것입니다: """...""" 또는 '''...'''. 줄 넘김 문자는 자동으로 문자열에 포함됩니다. 하지만 줄 끝에 \ 를 붙여 이를 방지할 수도 있습니다. 다음 예:

print("""\
Usage: thingy [OPTIONS]
     -h                        Display this usage message
     -H hostname               Hostname to connect to
""")

는 이런 결과를 출력합니다 (첫 번째 개행문자가 포함되지 않는 것에 주목하세요):

Usage: thingy [OPTIONS]
     -h                        Display this usage message
     -H hostname               Hostname to connect to

문자열은 + 연산자로 이어붙이고, * 연산자로 반복시킬 수 있습니다:

>>> # 3 times 'un', followed by 'ium'
>>> 3 * 'un' + 'ium'
'unununium'

두 개 이상의 문자열 리터럴 (즉, 따옴표로 둘러싸인 것들) 가 연속해서 나타나면 자동으로 이어 붙여집니다.

>>> 'Py' 'thon'
'Python'

이 기능은 긴 문자열을 쪼개고자 할 때 특별히 쓸모 있습니다:

>>> text = ('Put several strings within parentheses '
...         'to have them joined together.')
>>> text
'Put several strings within parentheses to have them joined together.'

이것은 오직 두 개의 리터럴에만 적용될 뿐 변수나 표현식에는 해당하지 않습니다:

>>> prefix = 'Py'
>>> prefix 'thon'  # can't concatenate a variable and a string literal
  File "<stdin>", line 1
    prefix 'thon'
                ^
SyntaxError: invalid syntax
>>> ('un' * 3) 'ium'
  File "<stdin>", line 1
    ('un' * 3) 'ium'
                   ^
SyntaxError: invalid syntax

변수들끼리 혹은 변수와 문자열 리터럴을 이어붙이려면 + 를 사용해야 합니다

>>> prefix + 'thon'
'Python'

문자열은 인덱스 (서브 스크립트) 될 수 있습니다. 첫 번째 문자가 인덱스 0에 대응됩니다. 문자를 위한 별도의 형은 없습니다; 단순히 길이가 1인 문자열입니다:

>>> word = 'Python'
>>> word[0]  # character in position 0
'P'
>>> word[5]  # character in position 5
'n'

인덱스는 음수가 될 수도 있는데, 끝에서부터 셉니다:

>>> word[-1]  # last character
'n'
>>> word[-2]  # second-last character
'o'
>>> word[-6]
'P'

-0은 0과 같으므로, 음의 인덱스는 -1에서 시작한다는 것에 주목하세요.

인덱싱에 더해 슬라이싱(slicing) 도 지원됩니다. 인덱싱이 개별 문자를 얻는데 사용되는 반면, 슬라이싱 은 부분 문자열(substring)을 얻는 데 사용됩니다:

>>> word[0:2]  # characters from position 0 (included) to 2 (excluded)
'Py'
>>> word[2:5]  # characters from position 2 (included) to 5 (excluded)
'tho'

시작 위치의 문자는 항상 포함되는 반면, 종료 위치의 문자는 항상 포함되지 않는 것에 주의하세요. 이 때문에 s[:i] + s[i:] 는 항상 s 와 같아집니다

>>> word[:2] + word[2:]
'Python'
>>> word[:4] + word[4:]
'Python'

슬라이스 인덱스는 편리한 기본값을 갖고 있습니다; 첫 번째 인덱스를 생략하면 기본값 0 이 사용되고, 두 번째 인덱스가 생략되면 기본값으로 슬라이싱 되는 문자열의 길이가 사용됩니다.

>>> word[:2]   # character from the beginning to position 2 (excluded)
'Py'
>>> word[4:]   # characters from position 4 (included) to the end
'on'
>>> word[-2:]  # characters from the second-last (included) to the end
'on'

슬라이스가 동작하는 방법을 기억하는 한 가지 방법은 인덱스가 문자들 사이의 위치를 가리킨다고 생각하는 것입니다. 첫 번째 문자의 왼쪽 경계가 0입니다. n 개의 문자들로 구성된 문자열의 오른쪽 끝 경계는 인덱스 n 이 됩니다, 예를 들어:

 +---+---+---+---+---+---+
 | P | y | t | h | o | n |
 +---+---+---+---+---+---+
 0   1   2   3   4   5   6
-6  -5  -4  -3  -2  -1

첫 번째 숫자 행은 인덱스 0…6 의 위치를 보여주고; 두 번째 행은 대응하는 음의 인덱스들을 보여줍니다. i 에서 j 범위의 슬라이스는 i 와 j 로 번호 붙여진 경계 사이의 문자들로 구성됩니다.

음이 아닌 인덱스들의 경우, 두 인덱스 모두 범위 내에 있다면 슬라이스의 길이는 인덱스 간의 차입니다. 예를 들어 word[1:3] 의 길이는 2입니다.

너무 큰 값을 인덱스로 사용하는 것은 에러입니다:

>>> word[42]  # the word only has 6 characters
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: string index out of range

하지만, 범위를 벗어나는 슬라이스 인덱스는 슬라이싱할 때 부드럽게 처리됩니다:

>>> word[4:42]
'on'
>>> word[42:]
''

파이썬 문자열은 변경할 수 없다 — 불변 이라고 합니다. 그래서 문자열의 인덱스로 참조한 위치에 대입하려고 하면 에러를 일으킵니다:

>>> word[0] = 'J'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
>>> word[2:] = 'py'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment

다른 문자열이 필요하면, 새로 만들어야 합니다:

>>> 'J' + word[1:]
'Jython'
>>> word[:2] + 'py'
'Pypy'

내장 함수 len() 은 문자열의 길이를 돌려줍니다:

>>> s = 'supercalifragilisticexpialidocious'
>>> len(s)
34

더 보기

텍스트 시퀀스 형 — str

문자열은 시퀀스 형 의 일종이고, 시퀀스가 지원하는 공통 연산들이 지원됩니다.

문자열 메서드

문자열은 기본적인 변환과 검색을 위한 여러 가지 메서드들을 지원합니다.

포맷 문자열 리터럴

내장된 표현식을 갖는 문자열 리터럴

포맷 문자열 문법

str.format() 으로 문자열을 포맷하는 방법에 대한 정보.

printf 스타일 문자열 포매팅

이곳에서 문자열을 % 연산자 왼쪽에 사용하는 예전 방식의 포매팅에 관해 좀 더 상세하게 설명하고 있습니다.

3.1.3. 리스트

파이썬은 다른 값들을 덩어리로 묶는데 사용되는 여러 가지 컴파운드 (compound) 자료 형을 알고 있습니다. 가장 융통성이 있는 것은 리스트 인데, 대괄호 사이에 쉼표로 구분된 값(항목)들의 목록으로 표현될 수 있습니다. 리스트는 서로 다른 형의 항목들을 포함할 수 있지만, 항목들이 모두 같은 형인 경우가 많습니다.

>>> squares = [1, 4, 9, 16, 25]
>>> squares
[1, 4, 9, 16, 25]

문자열(그리고, 다른 모든 내장 시퀀스 형들)처럼 리스트는 인덱싱하고 슬라이싱할 수 있습니다:

>>> squares[0]  # indexing returns the item
1
>>> squares[-1]
25
>>> squares[-3:]  # slicing returns a new list
[9, 16, 25]

모든 슬라이스 연산은 요청한 항목들을 포함하는 새 리스트를 돌려줍니다. 이는 다음과 같은 슬라이스가 리스트의 새로운 (얕은) 복사본을 돌려준다는 뜻입니다:

>>> squares[:]
[1, 4, 9, 16, 25]

리스트는 이어붙이기 같은 연산도 지원합니다:

>>> squares + [36, 49, 64, 81, 100]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

불변 인 문자열과는 달리, 리스트는 가변 입니다. 즉 내용을 변경할 수 있습니다:

>>> cubes = [1, 8, 27, 65, 125]  # something's wrong here
>>> 4 ** 3  # the cube of 4 is 64, not 65!
64
>>> cubes[3] = 64  # replace the wrong value
>>> cubes
[1, 8, 27, 64, 125]

append() 메서드 (method) (나중에 메서드에 대해 더 자세히 알아볼 것입니다) 를 사용하면 리스트의 끝에 새 항목을 추가할 수 있습니다:

>>> cubes.append(216)  # add the cube of 6
>>> cubes.append(7 ** 3)  # and the cube of 7
>>> cubes
[1, 8, 27, 64, 125, 216, 343]

슬라이스에 대입하는 것도 가능한데, 리스트의 길이를 변경할 수 있고, 모든 항목을 삭제할 수조차 있습니다:

>>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> letters
['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> # replace some values
>>> letters[2:5] = ['C', 'D', 'E']
>>> letters
['a', 'b', 'C', 'D', 'E', 'f', 'g']
>>> # now remove them
>>> letters[2:5] = []
>>> letters
['a', 'b', 'f', 'g']
>>> # clear the list by replacing all the elements with an empty list
>>> letters[:] = []
>>> letters
[]

내장 함수 len() 은 리스트에도 적용됩니다:

>>> letters = ['a', 'b', 'c', 'd']
>>> len(letters)
4

리스트를 중첩할 수도 있습니다. (다른 리스트를 포함하는 리스트를 만듭니다). 예를 들어:

>>> a = ['a', 'b', 'c']
>>> n = [1, 2, 3]
>>> x = [a, n]
>>> x
[['a', 'b', 'c'], [1, 2, 3]]
>>> x[0]
['a', 'b', 'c']
>>> x[0][1]
'b'

3.2. 프로그래밍으로의 첫걸음

물론, 2 에 2를 더하는 것보다는 더 복잡한 방법으로 파이썬을 사용할 수 있습니다. 예를 들어, 다음처럼 피보나치 수열 [https://en.wikipedia.org/wiki/Fibonacci_number]의 앞부분을 계산할 수 있습니다:

>>> # Fibonacci series:
... # the sum of two elements defines the next
... a, b = 0, 1
>>> while a < 10:
...     print(a)
...     a, b = b, a+b
...
0
1
1
2
3
5
8

이 예는 몇 가지 새로운 기능을 소개하고 있습니다.

첫 줄은 다중 대입 을 포함하고 있습니다: 변수 a 와 b 에 동시에 값 0과1이 대입됩니다. 마지막 줄에서 다시 사용되는데, 대입이 어느 하나라도 이루어지기 전에 우변의 표현식들이 모두 계산됩니다. 우변의 표현식은 왼쪽부터 오른쪽으로 가면서 순서대로 계산됩니다.

while 루프는 조건(여기서는: a < 10)이 참인 동안 실행됩니다. C와 마찬가지로 파이썬에서 0 이 아닌 모든 정수는 참이고, 0은 거짓입니다. 조건은 문자열이나 리스트 (사실 모든 종류의 시퀀스)가 될 수도 있는데 길이가 0 이 아닌 것은 모두 참이고, 빈 시퀀스는 거짓입니다. 이 예에서 사용한 검사는 간단한 비교입니다. 표준 비교 연산자는 C와 같은 방식으로 표현됩니다: < (작다), > (크다), == (같다), <= (작거나 같다), >= (크거나 같다), != (다르다).

루프의 바디 (body) 는 들여쓰기 됩니다. 들여쓰기는 파이썬에서 문장을 덩어리로 묶는 방법입니다. 대화형 프롬프트에서 각각 들여 쓰는 줄에서 탭(tab)이나 공백(space)을 입력해야 합니다. 실제적으로는 텍스트 편집기를 사용해서 좀 더 복잡한 파이썬 코드를 준비하게 됩니다; 웬만한 텍스트 편집기들은 자동 들여쓰기 기능을 제공합니다. 복합문을 대화형으로 입력할 때는 끝을 알리기 위해 빈 줄을 입력해야 합니다. (해석기가 언제 마지막 줄을 입력할지 짐작할 수 없기 때문입니다.) 같은 블록에 포함되는 모든 줄은 같은 양만큼 들여쓰기 되어야 함에 주의하세요.

print() 함수는 주어진 인자들의 값을 인쇄합니다. 다중 인자, 실수의 값, 문자열을 다루는 방식에서 (계산기 예제에서 본 것과 같이) 출력하고자 하는 표현식을 그냥 입력하는 것과는 다릅니다. 문자열은 따옴표 없이 출력되고, 인자들 간에는 빈칸이 삽입됩니다. 그래서 이런 식으로 보기 좋게 포매팅할 수 있습니다:

>>> i = 256*256
>>> print('The value of i is', i)
The value of i is 65536

키워드 인자 end 는 출력 끝에 포함되는 개행문자를 제거하거나 출력을 다른 문자열로 끝나게 하고 싶을 때 사용됩니다:

>>> a, b = 0, 1
>>> while a < 1000:
...     print(a, end=',')
...     a, b = b, a+b
...
0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,

각주

1

** 가 - 보다 우선순위가 높으므로, -3**2 는 -(3**2) 로 해석되어서 결과는 -9 가 됩니다. 9 를 얻고 싶으면 (-3)**2 를 사용할 수 있습니다.

2

다른 언어들과는 달리, `` `` 과 같은 특수 문자들은 작은따옴표('...')와 큰따옴표("...")에서 같은 의미가 있습니다. 둘 간의 유일한 차이는 작은따옴표 안에서 " 를 이스케이핑할 필요가 없고 (하지만 \' 는 이스케이핑 시켜야 합니다), 그 역도 성립한다는 것입니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 자습서 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 자습서 »

|

4. 기타 제어 흐름 도구

Besides the while statement just introduced, Python uses the usual flow control statements known from other languages, with some twists.

4.1. if 문

아마도 가장 잘 알려진 문장 형은 if 문일 것입니다. 예를 들어:

>>> x = int(input("Please enter an integer: "))
Please enter an integer: 42
>>> if x < 0:
...     x = 0
...     print('Negative changed to zero')
... elif x == 0:
...     print('Zero')
... elif x == 1:
...     print('Single')
... else:
...     print('More')
...
More

없거나 여러 개의 elif 부가 있을 수 있고, else 부는 선택적입니다. 키워드 ‘elif’ 는 ‘else if’ 의 줄임 표현인데, 과도한 들여쓰기를 피하는 데 유용합니다. if … elif … elif … 시퀀스는 다른 언어들에서 발견되는 switch 나 case 문을 대신합니다.

4.2. for 문

파이썬에서 for 문은 C 나 파스칼에서 사용하던 것과 약간 다릅니다. (파스칼처럼) 항상 숫자의 산술적인 진행을 통해 이터레이션 하거나, (C처럼) 사용자가 이터레이션 단계와 중지 조건을 정의할 수 있도록 하는 대신, 파이썬의 for 문은 임의의 시퀀스 (리스트나 문자열)의 항목들을 그 시퀀스에 들어있는 순서대로 이터레이션 합니다. 예를 들어 (말장난이 아니라):

>>> # Measure some strings:
... words = ['cat', 'window', 'defenestrate']
>>> for w in words:
...     print(w, len(w))
...
cat 3
window 6
defenestrate 12

루프 안에서 이터레이트하는 시퀀스를 수정할 필요가 있다면 (예를 들어, 선택한 항목들을 중복시키기), 먼저 사본을 만들 것을 권합니다. 시퀀스를 이터레이트할 때 묵시적으로 사본이 만들어지지는 않습니다. 슬라이스 표기법은 이럴 때 특히 편리합니다:

>>> for w in words[:]:  # Loop over a slice copy of the entire list.
...     if len(w) > 6:
...         words.insert(0, w)
...
>>> words
['defenestrate', 'cat', 'window', 'defenestrate']

for w in words: 를 쓰면, 위의 예는 defenestrate를 반복해서 넣고 또 넣음으로써, 무한한 리스트를 만들려고 시도하게 됩니다.

4.3. range() 함수

숫자들의 시퀀스로 이터레이트할 필요가 있으면, 내장 함수 range()가 편리합니다. 수열을 만듭니다:

>>> for i in range(5):
...     print(i)
...
0
1
2
3
4

끝값은 만들어지는 수열에 포함되지 않습니다; range(10) 은 10개의 값을 만드는데, 길이 10인 시퀀스의 항목들을 가리키는 올바른 인덱스들입니다. 범위가 다른 숫자로 시작하거나, 다른 증가분을 (음수조차 가능합니다; 때로 이것을 ‘스텝(step)’이라고 부릅니다) 지정하는 것도 가능합니다:

range(5, 10)
   5, 6, 7, 8, 9

range(0, 10, 3)
   0, 3, 6, 9

range(-10, -100, -30)
  -10, -40, -70

시퀀스의 인덱스들로 이터레이트 하려면, 다음처럼 range()와 len() 을 결합할 수 있습니다:

>>> a = ['Mary', 'had', 'a', 'little', 'lamb']
>>> for i in range(len(a)):
...     print(i, a[i])
...
0 Mary
1 had
2 a
3 little
4 lamb

하지만, 그럴 때 대부분은, enumerate() 함수를 쓰는 것이 편리합니다, 루프 테크닉 를 보세요.

범위를 그냥 인쇄하면 이상한 일이 일어납니다:

>>> print(range(10))
range(0, 10)

많은 경우에 range()가 돌려준 객체는 리스트인 것처럼 동작하지만, 사실 리스트가 아닙니다. 이터레이트할 때 원하는 시퀀스 항목들을 순서대로 돌려주는 객체이지만, 실제로 리스트를 만들지 않아서 공간을 절약합니다.

이런 객체를 이터러블 이라고 부릅니다. 공급이 소진될 때까지 일련의 항목들을 얻을 수 있는 무엇인가를 기대하는 함수와 구조물들의 타깃으로 적합합니다. 우리는 for 문이 그런 구조물임을 보았습니다. 함수 list() 도 그런 것입니다; 이터러블로 리스트를 만듭니다:

>>> list(range(5))
[0, 1, 2, 3, 4]

나중에 이터러블을 돌려주고 이터러블을 인자로 받는 함수들을 더 보게 됩니다.

4.4. 루프의 break 와 continue 문, 그리고 else 절

break 문은, C처럼, 가장 가까이서 둘러싸는 for 나 while 루프로부터 빠져나가게 만듭니다.

루프 문은 else 절을 가질 수 있습니다; 루프가 리스트의 소진이나 (for 의 경우) 조건이 거짓이 돼서 (while 의 경우) 종료할 때 실행됩니다. 하지만 루프가 break 문으로 종료할 때는 실행되지 않습니다. 소수를 찾는 루프를 통해 다음에서 예시합니다:

>>> for n in range(2, 10):
...     for x in range(2, n):
...         if n % x == 0:
...             print(n, 'equals', x, '*', n//x)
...             break
...     else:
...         # loop fell through without finding a factor
...         print(n, 'is a prime number')
...
2 is a prime number
3 is a prime number
4 equals 2 * 2
5 is a prime number
6 equals 2 * 3
7 is a prime number
8 equals 2 * 4
9 equals 3 * 3

(이것은 올바른 코드입니다. 자세히 들여다보면: else 절은 if 문이 아니라 for 루프에 속합니다.)

루프와 함께 사용될 때, else 절은 if 문보다는 try 문의 else 절과 비슷한 면이 많습니다: try 문의 else 절은 예외가 발생하지 않을 때 실행되고, 루프의 else 절은 break 가 발생하지 않을 때 실행됩니다. try 문과 예외에 관한 자세한 내용은 예외 처리하기 를 보세요.

continue 문은, 역시 C에서 빌렸습니다, 루프의 다음 이터레이션에서 계속하도록 만듭니다:

>>> for num in range(2, 10):
...     if num % 2 == 0:
...         print("Found an even number", num)
...         continue
...     print("Found a number", num)
Found an even number 2
Found a number 3
Found an even number 4
Found a number 5
Found an even number 6
Found a number 7
Found an even number 8
Found a number 9

4.5. pass 문

pass 문은 아무것도 하지 않습니다. 문법적으로 문장이 필요하지만, 프로그램이 특별히 할 일이 없을 때 사용할 수 있습니다. 예를 들어:

>>> while True:
...     pass  # Busy-wait for keyboard interrupt (Ctrl+C)
...

최소한의 클래스를 만들 때 흔히 사용됩니다:

>>> class MyEmptyClass:
...     pass
...

pass가 사용될 수 있는 다른 장소는 새 코드를 작업할 때 함수나 조건부 바디의 자리를 채우는 것인데, 여러분이 더 추상적인 수준에서 생각할 수 있게 합니다. pass 는 조용히 무시됩니다:

>>> def initlog(*args):
...     pass   # Remember to implement this!
...

4.6. 함수 정의하기

피보나치 수열을 임의의 한도까지 출력하는 함수를 만들 수 있습니다:

>>> def fib(n):    # write Fibonacci series up to n
...     """Print a Fibonacci series up to n."""
...     a, b = 0, 1
...     while a < n:
...         print(a, end=' ')
...         a, b = b, a+b
...     print()
...
>>> # Now call the function we just defined:
... fib(2000)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597

키워드 def는 함수 정의를 시작합니다. 함수 이름과 괄호로 싸인 형식 매개변수들의 목록이 뒤따릅니다. 함수의 바디를 형성하는 문장들이 다음 줄에서 시작되고, 반드시 들여쓰기 되어야 합니다.

함수 바디의 첫 번째 문장은 선택적으로 문자열 리터럴이 될 수 있습니다; 이 문자열 리터럴은 함수의 도큐멘테이션 문자열, 즉 독스트링 (docstring) 입니다. (독스트링에 대한 자세한 내용은 도큐멘테이션 문자열 에 나옵니다.) 독스트링을 사용해서 온라인이나 인쇄된 설명서를 자동 생성하거나, 사용자들이 대화형으로 코드를 열람할 수 있도록 하는 도구들이 있습니다; 여러분이 작성하는 코드에 독스트링을 첨부하는 것은 좋은 관습입니다, 그러니 버릇을 들이는 것이 좋습니다.

함수의 실행은 함수의 지역 변수들을 위한 새 심볼 테이블을 만듭니다. 좀 더 구체적으로, 함수에서의 모든 변수 대입들은 값을 지역 심볼 테이블에 저장합니다; 반면에 변수 참조는 먼저 지역 심볼 테이블을 본 다음, 전역 심볼 테이블을 본 후, 마지막으로 내장 이름들의 테이블을 살핍니다. 그래서, 참조될 수는 있다 하더라도, 전역 변수들과 둘러싸는 함수의 변수들은 함수 내에서 직접 값이 대입될 수 없습니다 (전역 변수를 global 문으로 명시하거나 둘러싸는 함수의 변수를 nonlocal 문으로 명시하지 않는 이상).

함수 호출로 전달되는 실제 매개변수들 (인자들)은 호출될 때 호출되는 함수의 지역 심볼 테이블에 만들어집니다; 그래서 인자들은 값에 의한 호출(call by value)로 전달됩니다 (값은 항상 객체의 값이 아니라 객체 참조입니다). 1 함수가 다른 함수를 호출할 때, 그 호출을 위한 새 지역 심볼 테이블이 만들어집니다.

함수 정의는 현재 심볼 테이블에 함수 이름을 만듭니다. 함수 이름의 값은 인터프리터가 사용자 정의 함수로 인식하는 형입니다. 이 값은 다른 이름에 대입될 수 있는데, 이 역시 함수로 사용될 수 있습니다. 이것이 이름을 바꾸는 일반적인 방법입니다:

>>> fib
<function fib at 10042ed0>
>>> f = fib
>>> f(100)
0 1 1 2 3 5 8 13 21 34 55 89

다른 언어들을 사용했다면, fib 가 값을 돌려주지 않기 때문에 함수가 아니라 프로시저라고 생각할 수 있습니다. 사실, return 문이 없는 함수도 값을 돌려줍니다, 비록 따분한 값이기는 하지만. 이 값은 None이라고 불립니다 (내장 이름입니다). None 이 출력할 유일한 값이라면, 인터프리터는 보통 None 값 출력을 억제합니다. 꼭 보길 원한다면 print()를 사용할 수 있습니다:

>>> fib(0)
>>> print(fib(0))
None

인쇄하는 대신, 피보나치 수열의 숫자들 리스트를 돌려주는 함수를 작성하는 것도 간단합니다:

>>> def fib2(n):  # return Fibonacci series up to n
...     """Return a list containing the Fibonacci series up to n."""
...     result = []
...     a, b = 0, 1
...     while a < n:
...         result.append(a)    # see below
...         a, b = b, a+b
...     return result
...
>>> f100 = fib2(100)    # call it
>>> f100                # write the result
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

여느 때처럼, 이 예는 몇 가지 새 파이썬 기능을 보여줍니다:

return 문은 함수로부터 값을 갖고 복귀하게 만듭니다. 표현식 인자 없는 return 은 None을 돌려줍니다. 함수의 끝으로 떨어지면 역시 None을 돌려줍니다.

문장 result.append(a) 은 리스트 객체 result의 메서드를 호출합니다. 메서드는 객체에 ‘속하는’ 함수이고 obj.methodname 라고 이름 붙여지는데, obj는 어떤 객체이고 (표현식이 될 수 있습니다), methodname 는 객체의 형에 의해 정의된 메서드의 이름입니다. 다른 형은 다른 메서드들을 정의합니다. 서로 다른 형들의 메서드는 모호함 없이 같은 이름을 가질 수 있습니다. (클래스를 사용해서 여러분 자신의 형과 메서드를 정의하는 것이 가능합니다, 클래스를 보세요) 예에 나오는 메서드 append()는 리스트 객체들에 정의되어 있습니다; 요소를 리스트의 끝에 덧붙입니다. 이 예에서는 result = result + [a] 와 동등하지만, 더 효율적입니다.

4.7. 함수 정의 더 보기

정해지지 않은 개수의 인자들로 함수를 정의하는 것도 가능합니다. 세 가지 형식이 있는데, 조합할 수 있습니다.

4.7.1. 기본 인자 값

가장 쓸모 있는 형식은 하나나 그 이상 인자들의 기본값을 지정하는 것입니다. 정의된 것보다 더 적은 개수의 인자들로 호출될 수 있는 함수를 만듭니다. 예를 들어:

def ask_ok(prompt, retries=4, reminder='Please try again!'):
    while True:
        ok = input(prompt)
        if ok in ('y', 'ye', 'yes'):
            return True
        if ok in ('n', 'no', 'nop', 'nope'):
            return False
        retries = retries - 1
        if retries < 0:
            raise ValueError('invalid user response')
        print(reminder)

이 함수는 여러 가지 방법으로 호출될 수 있습니다:

오직 꼭 필요한 인자만 전달해서: ask_ok('정말 끝내길 원하세요?')

선택적 인자 하나를 제공해서: ask_ok('파일을 덮어써도 좋습니까?', 2)

또는 모든 인자를 제공해서: ask_ok('파일을 덮어써도 좋습니까?', 2, '자, 예나 아니요로만 답하세요!')

이 예는 in 키워드도 소개하고 있습니다. 시퀀스가 어떤 값을 가졌는지 아닌지를 검사합니다.

기본값은 함수 정의 시점에 정의되고 있는 스코프에서 구해집니다, 그래서

i = 5

def f(arg=i):
    print(arg)

i = 6
f()

는 5를 인쇄합니다.

중요한 주의사항: 기본값은 오직 한 번만 값이 구해집니다. 이것은 기본값이 리스트나 딕셔너리나 대부분 클래스의 인스턴스와 같은 가변 객체일 때 차이를 만듭니다. 예를 들어, 다음 함수는 계속되는 호출로 전달된 인자들을 누적합니다:

def f(a, L=[]):
    L.append(a)
    return L

print(f(1))
print(f(2))
print(f(3))

다음과 같은 것을 인쇄합니다

[1]
[1, 2]
[1, 2, 3]

연속된 호출 간에 기본값이 공유되지 않기를 원한다면, 대신 함수를 이런 식으로 쓸 수 있습니다:

def f(a, L=None):
    if L is None:
        L = []
    L.append(a)
    return L

4.7.2. 키워드 인자

함수는 kwarg=value 형식의 키워드 인자 를 사용해서 호출될 수 있습니다. 예를 들어, 다음 함수는:

def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
    print("-- This parrot wouldn't", action, end=' ')
    print("if you put", voltage, "volts through it.")
    print("-- Lovely plumage, the", type)
    print("-- It's", state, "!")

하나의 필수 인자(voltage)와 세 개의 선택적 인자 (state, action, type) 를 받아들입니다. 이 함수는 다음과 같은 방법 중 아무것으로나 호출될 수 있습니다.

parrot(1000)                                          # 1 positional argument
parrot(voltage=1000)                                  # 1 keyword argument
parrot(voltage=1000000, action='VOOOOOM')             # 2 keyword arguments
parrot(action='VOOOOOM', voltage=1000000)             # 2 keyword arguments
parrot('a million', 'bereft of life', 'jump')         # 3 positional arguments
parrot('a thousand', state='pushing up the daisies')  # 1 positional, 1 keyword

하지만 다음과 같은 호출들은 모두 올바르지 않습니다:

parrot()                     # required argument missing
parrot(voltage=5.0, 'dead')  # non-keyword argument after a keyword argument
parrot(110, voltage=220)     # duplicate value for the same argument
parrot(actor='John Cleese')  # unknown keyword argument

함수 호출에서, 키워드 인자는 위치 인자 뒤에 나와야 합니다. 전달된 모든 키워드 인자는 함수가 받아들이는 인자 중 하나와 맞아야 하며 (예를 들어, actor는 parrot 함수의 올바른 인자가 아니다), 그 순서는 중요하지 않습니다. 이것들에는 필수 인자들도 포함됩니다 (예를 들어, parrot(voltage=1000) 도 올바릅니다). 어떤 인자도 두 개 이상의 값을 받을 수 없습니다. 여기, 이 제약 때문에 실패하는 예가 있습니다:

>>> def function(a):
...     pass
...
>>> function(0, a=0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: function() got multiple values for keyword argument 'a'

**name 형식의 마지막 형식 매개변수가 존재하면, 형식 매개변수들에 대응하지 않는 모든 키워드 인자들을 담은 딕셔너리 (매핑 형 — dict 를 보세요) 를 받습니다. 이것은 *name (다음 서브섹션에서 설명합니다) 형식의 형식 매개변수와 조합될 수 있는데, 형식 매개변수 목록 밖의 위치 인자들을 담은 튜플을 받습니다. (*name은 **name 앞에 나와야 합니다.) 예를 들어, 이런 함수를 정의하면:

def cheeseshop(kind, *arguments, **keywords):
    print("-- Do you have any", kind, "?")
    print("-- I'm sorry, we're all out of", kind)
    for arg in arguments:
        print(arg)
    print("-" * 40)
    for kw in keywords:
        print(kw, ":", keywords[kw])

이런 식으로 호출될 수 있습니다:

cheeseshop("Limburger", "It's very runny, sir.",
           "It's really very, VERY runny, sir.",
           shopkeeper="Michael Palin",
           client="John Cleese",
           sketch="Cheese Shop Sketch")

그리고 당연히 이렇게 인쇄합니다:

-- Do you have any Limburger ?
-- I'm sorry, we're all out of Limburger
It's very runny, sir.
It's really very, VERY runny, sir.
----------------------------------------
shopkeeper : Michael Palin
client : John Cleese
sketch : Cheese Shop Sketch

인쇄되는 키워드 인자들의 순서 함수 호출로 전달된 순서와 일치함이 보장됨에 주목하세요.

4.7.3. 임의의 인자 목록

마지막으로, 가장 덜 사용되는 옵션은 함수가 임의의 개수 인자로 호출될 수 있도록 지정하는 것입니다. 이 인자들은 튜플로 묶입니다 (튜플과 시퀀스 을 보세요). 가변 길이 인자 앞에, 없거나 여러 개의 일반 인자들이 올 수 있습니다.

def write_multiple_items(file, separator, *args):
    file.write(separator.join(args))

보통, 이 가변 길이 인자들은 형식 매개변수 목록의 마지막에 옵니다, 함수로 전달된 남은 입력 인자들 전부를 그러모으기 때문입니다. *args 매개변수 뒤에 등장하는 형식 매개변수들은 모두 ‘키워드-전용’ 인자들인데, 위치 인자 대신 키워드 인자로만 사용될 수 있다는 뜻입니다.

>>> def concat(*args, sep="/"):
...     return sep.join(args)
...
>>> concat("earth", "mars", "venus")
'earth/mars/venus'
>>> concat("earth", "mars", "venus", sep=".")
'earth.mars.venus'

4.7.4. 인자 목록 언 패킹

The reverse situation occurs when the arguments are already in a list or tuple but need to be unpacked for a function call requiring separate positional arguments. For instance, the built-in range() function expects separate start and stop arguments. If they are not available separately, write the function call with the * operator to unpack the arguments out of a list or tuple:

>>> list(range(3, 6))            # normal call with separate arguments
[3, 4, 5]
>>> args = [3, 6]
>>> list(range(*args))            # call with arguments unpacked from a list
[3, 4, 5]

In the same fashion, dictionaries can deliver keyword arguments with the ** operator:

>>> def parrot(voltage, state='a stiff', action='voom'):
...     print("-- This parrot wouldn't", action, end=' ')
...     print("if you put", voltage, "volts through it.", end=' ')
...     print("E's", state, "!")
...
>>> d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"}
>>> parrot(**d)
-- This parrot wouldn't VOOM if you put four million volts through it. E's bleedin' demised !

4.7.5. 람다 표현식

lambda 키워드들 사용해서 작고 이름 없는 함수를 만들 수 있습니다. 이 함수는 두 인자의 합을 돌려줍니다: lambda a, b: a+b. 함수 객체가 있어야 하는 곳이면 어디나 람다 함수가 사용될 수 있습니다. 문법적으로는 하나의 표현식으로 제한됩니다. 의미적으로는, 일반적인 함수 정의의 편의 문법일 뿐입니다. 중첩된 함수 정의처럼, 람다 함수는 둘러싸는 스코프에 있는 변수들을 참조할 수 있습니다:

>>> def make_incrementor(n):
...     return lambda x: x + n
...
>>> f = make_incrementor(42)
>>> f(0)
42
>>> f(1)
43

위의 예는 함수를 돌려주기 위해 람다 표현식을 사용합니다. 또 다른 용도는 작은 함수를 인자로 전달하는 것입니다:

>>> pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
>>> pairs.sort(key=lambda pair: pair[1])
>>> pairs
[(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]

4.7.6. 도큐멘테이션 문자열

여기에 도큐멘테이션 문자열의 내용과 포매팅에 관한 몇 가지 관례가 있습니다.

첫 줄은 항상 객체의 목적을 짧고, 간결하게 요약해야 합니다. 간결함을 위해, 객체의 이름이나 형을 명시적으로 언급하지 않아야 하는데, 이것들은 다른 방법으로 제공되기 때문입니다 (이름이 함수의 작업을 설명하는 동사라면 예외입니다). 이 줄은 대문자로 시작하고 마침표로 끝나야 합니다.

도큐멘테이션 문자열에 여러 줄이 있다면, 두 번째 줄은 비어있어서, 시각적으로 요약과 나머지 설명을 분리해야 합니다. 뒤따르는 줄들은 하나나 그 이상의 문단으로, 객체의 호출 규약, 부작용 등을 설명해야 합니다.

파이썬 파서는 여러 줄 문자열 리터럴에서 들여쓰기를 제거하지 않기 때문에, 설명서를 처리하는 도구들은 필요하면 들여쓰기를 제거합니다. 이것은 다음과 같은 관례를 사용합니다. 문자열의 첫줄 뒤에 오는 첫 번째 비어있지 않은 줄이 전체 도튜멘테이션 문자열의 들여쓰기 수준을 결정합니다. (우리는 첫 줄을 사용할 수 없는데, 일반적으로 문자열을 시작하는 따옴표에 붙어있어서 들여쓰기가 문자열 리터럴의 것을 반영하지 않기 때문입니다.) 이 들여쓰기와 “동등한” 공백이 문자열의 모든 줄의 시작 부분에서 제거됩니다. 덜 들여쓰기 된 줄이 나타나지는 말아야 하지만, 나타난다면 모든 앞부분의 공백이 제거됩니다. 공백의 동등성은 탭 확장 (보통 8개의 스페이스) 후에 검사됩니다.

여기 여러 줄 독스트링의 예가 있습니다:

>>> def my_function():
...     """Do nothing, but document it.
...
...     No, really, it doesn't do anything.
...     """
...     pass
...
>>> print(my_function.__doc__)
Do nothing, but document it.

    No, really, it doesn't do anything.

4.7.7. 함수 어노테이션

함수 어노테이션 은 사용자 정의 함수가 사용하는 형들에 대한 완전히 선택적인 메타데이터 정보입니다 (자세한 내용은 PEP 3107 [https://www.python.org/dev/peps/pep-3107] 과 PEP 484 [https://www.python.org/dev/peps/pep-0484] 를 보세요).

어노테이션은 함수의 __annotations__ 어트리뷰트에 딕셔너리로 저장되고 함수의 다른 부분에는 아무런 영향을 미치지 않습니다. 매개변수 어노테이션은 매개변수 이름 뒤에 오는 콜론으로 정의되는데, 값을 구할 때 어노테이션의 값을 주는 표현식이 뒤따릅니다. 반환 값 어노테이션은 리터럴 -> 와 그 뒤를 따르는 표현식으로 정의되는데, 매개변수 목록과 def 문의 끝을 나타내는 콜론 사이에 놓입니다. 다음 예에서 위치 인자, 키워드 인자, 반환 값이 어노테이트 됩니다:

>>> def f(ham: str, eggs: str = 'eggs') -> str:
...     print("Annotations:", f.__annotations__)
...     print("Arguments:", ham, eggs)
...     return ham + ' and ' + eggs
...
>>> f('spam')
Annotations: {'ham': <class 'str'>, 'return': <class 'str'>, 'eggs': <class 'str'>}
Arguments: spam eggs
'spam and eggs'

4.8. 막간극: 코딩 스타일

이제 여러분은 파이썬의 더 길고, 더 복잡한 조각들을 작성하려고 합니다, 코딩 스타일에 대해 말할 적절한 시간입니다. 대부분 언어는 서로 다른 스타일로 작성될 (또는 더 간략하게, 포맷될) 수 있습니다; 어떤 것들은 다른 것들보다 더 읽기 쉽습니다. 다른 사람들이 여러분의 코드를 읽기 쉽게 만드는 것은 항상 좋은 생각이고, 훌륭한 코딩 스타일을 도입하는 것은 그렇게 하는 데 큰 도움을 줍니다.

파이썬을 위해, 대부분 프로젝트가 고수하는 스타일 가이드로 PEP 8 [https://www.python.org/dev/peps/pep-0008]이 나왔습니다; 이것은 매우 읽기 쉽고 눈이 편안한 코딩 스타일을 장려합니다. 모든 파이썬 개발자는 언젠가는 이 문서를 읽어야 합니다; 여러분을 위해 가장 중요한 부분들을 추려봤습니다:

들려 쓰기에 4-스페이스를 사용하고, 탭을 사용하지 마세요.

4개의 스페이스는 작은 들여쓰기 (더 많은 중첩 도를 허락합니다) 와 큰 들여쓰기 (읽기 쉽습니다) 사이의 좋은 절충입니다. 탭은 혼란을 일으키고, 없애는 것이 최선입니다.

79자를 넘지 않도록 줄 넘김 하세요.

이것은 작은 화면을 가진 사용자를 돕고 큰 화면에서는 여러 코드 파일들을 나란히 볼 수 있게 합니다.

함수, 클래스, 함수 내의 큰 코드 블록 사이에 빈 줄을 넣어 분리하세요.

가능하다면, 주석은 별도의 줄로 넣으세요.

독스트링을 사용하세요.

연산자들 주변과 콤마 뒤에 스페이스를 넣고, 괄호 바로 안쪽에는 스페이스를 넣지 마세요: a = f(1, 2) + g(3, 4).

Name your classes and functions consistently; the convention is to use UpperCamelCase for classes and lowercase_with_underscores for functions and methods. Always use self as the name for the first method argument (see 클래스와의 첫 만남 for more on classes and methods).

여러분의 코드를 국제적인 환경에서 사용하려고 한다면 특별한 인코딩을 사용하지 마세요. 어떤 경우에도 파이썬의 기본, UTF-8, 또는 단순 ASCII조차, 이 최선입니다.

마찬가지로, 다른 언어를 사용하는 사람이 코드를 읽거나 유지할 약간의 가능성만 있더라도, 식별자에 ASCII 이외의 문자를 사용하지 마세요.

각주

1

실제로, 객체 참조에 의한 호출 (call by object reference) 이 더 좋은 표현인데, 가변 객체가 전달되면, 호출자는 피호출자가 만든 변경을 볼 수 있기 때문입니다 (가령 리스트에 항목을 추가합니다).

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 자습서 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 자습서 »

|

5. 자료 구조

이 장에서는 여러분이 이미 배운 것들을 좀 더 자세히 설명하고, 몇 가지 새로운 것들을 덧붙입니다.

5.1. 리스트 더 보기

리스트 자료 형은 몇 가지 메서드들을 더 갖고 있습니다. 이것들이 리스트 객체의 모든 메서드 들입니다:

list.append(x)

리스트의 끝에 항목을 더합니다. a[len(a):] = [x] 와 동등합니다.

list.extend(iterable)

리스트의 끝에 이터러블의 모든 항목을 덧붙여서 확장합니다. a[len(a):] = iterable 와 동등합니다.

list.insert(i, x)

주어진 위치에 항목을 삽입합니다. 첫 번째 인자는 삽입되는 요소가 갖게 될 인덱스입니다. 그래서 a.insert(0, x) 는 리스트의 처음에 삽입하고, a.insert(len(a), x) 는 a.append(x) 와 동등합니다.

list.remove(x)

리스트에서 값이 x 와 같은 첫 번째 항목을 삭제합니다. 그런 항목이 없으면 ValueError를 일으킵니다.

list.pop([i])

리스트에서 주어진 위치에 있는 항목을 삭제하고, 그 항목을 돌려줍니다. 인덱스를 지정하지 않으면, a.pop() 은 리스트의 마지막 항목을 삭제하고 돌려줍니다. (메서드 시그니처에서 i 를 둘러싼 대괄호는 매개변수가 선택적임을 나타냅니다. 그 위치에 대괄호를 입력해야 한다는 뜻이 아닙니다. 이 표기법은 파이썬 라이브러리 레퍼런스에서 지주 등장합니다.)

list.clear()

리스트의 모든 항목을 삭제합니다. del a[:] 와 동등합니다.

list.index(x[, start[, end]])

리스트에 있는 항목 중 값이 x 와 같은 첫 번째 것의 0부터 시작하는 인덱스를 돌려줍니다. 그런 항목이 없으면 ValueError 를 일으킵니다.

선택적인 인자 start 와 end 는 슬라이스 표기법처럼 해석되고, 검색을 리스트의 특별한 서브 시퀀스로 제한하는 데 사용됩니다. 돌려주는 인덱스는 start 인자가 아니라 전체 시퀀스의 시작을 기준으로 합니다.

list.count(x)

리스트에서 x 가 등장하는 횟수를 돌려줍니다.

list.sort(key=None, reverse=False)

리스트의 항목들을 제자리에서 정렬합니다 (인자들은 정렬 커스터마이제이션에 사용될 수 있습니다. 설명은 sorted() 를 보세요).

list.reverse()

리스트의 요소들을 제자리에서 뒤집습니다.

list.copy()

리스트의 얕은 사본을 돌려줍니다. a[:] 와 동등합니다.

리스트 메서드 대부분을 사용하는 예:

>>> fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']
>>> fruits.count('apple')
2
>>> fruits.count('tangerine')
0
>>> fruits.index('banana')
3
>>> fruits.index('banana', 4)  # Find next banana starting a position 4
6
>>> fruits.reverse()
>>> fruits
['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange']
>>> fruits.append('grape')
>>> fruits
['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange', 'grape']
>>> fruits.sort()
>>> fruits
['apple', 'apple', 'banana', 'banana', 'grape', 'kiwi', 'orange', 'pear']
>>> fruits.pop()
'pear'

아마도 여러분은 insert, remove, sort 같은 메서드들이 리스트를 수정할 뿐 반환 값이 출력되지 않는 것을 알아챘을 것입니다 – 기본 None 을 돌려주고 있습니다. 1 이것은 파이썬에서 모든 가변 자료 구조들에 적용되는 설계 원리입니다.

5.1.1. 리스트를 스택으로 사용하기

리스트 메서드들은 리스트를 스택으로 사용하기 쉽게 만드는데, 마지막에 넣은 요소가 처음으로 꺼내지는 요소입니다 (“last-in, first-out”). 스택의 꼭대기에 항목을 넣으려면 append() 를 사용하세요. 스택의 꼭대기에서 값을 꺼내려면 명시적인 인덱스 없이 pop() 을 사용하세요. 예를 들어:

>>> stack = [3, 4, 5]
>>> stack.append(6)
>>> stack.append(7)
>>> stack
[3, 4, 5, 6, 7]
>>> stack.pop()
7
>>> stack
[3, 4, 5, 6]
>>> stack.pop()
6
>>> stack.pop()
5
>>> stack
[3, 4]

5.1.2. 리스트를 큐로 사용하기

리스트를 큐로 사용하는 것도 가능한데, 처음으로 넣은 요소가 처음으로 꺼내지는 요소입니다 (“first-in, first-out”); 하지만, 리스트는 이 목적에는 효율적이지 않습니다. 리스트의 끝에 덧붙이거나, 끝에서 꺼내는 것은 빠르지만, 리스트의 머리에 덧붙이거나 머리에서 꺼내는 것은 느립니다 (다른 요소들을 모두 한 칸씩 이동시켜야 하기 때문입니다).

큐를 구현하려면, 양 끝에서의 덧붙이기와 꺼내기가 모두 빠르도록 설계된 collections.deque 를 사용하세요. 예를 들어:

>>> from collections import deque
>>> queue = deque(["Eric", "John", "Michael"])
>>> queue.append("Terry")           # Terry arrives
>>> queue.append("Graham")          # Graham arrives
>>> queue.popleft()                 # The first to arrive now leaves
'Eric'
>>> queue.popleft()                 # The second to arrive now leaves
'John'
>>> queue                           # Remaining queue in order of arrival
deque(['Michael', 'Terry', 'Graham'])

5.1.3. 리스트 컴프리헨션

리스트 컴프리헨션은 리스트를 만드는 간결한 방법을 제공합니다. 흔한 용도는, 각 요소가 다른 시퀀스나 이터러블의 멤버들에 어떤 연산을 적용한 결과인 리스트를 만들거나, 어떤 조건을 만족하는 요소들로 구성된 서브 시퀀스를 만드는 것입니다.

예를 들어, 제곱수의 리스트를 만들고 싶다고 가정하자, 이런 식입니다:

>>> squares = []
>>> for x in range(10):
...     squares.append(x**2)
...
>>> squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

이것은 x 라는 이름의 변수를 만들고 (또는 덮어쓰고) 루프가 종료된 후에도 남아있게 만든다는 것에 유의하세요. 어떤 부작용도 없이, 제곱수의 리스트를 이런 식으로 계산할 수 있습니다:

squares = list(map(lambda x: x**2, range(10)))

또는, 이렇게 할 수도 있습니다:

squares = [x**2 for x in range(10)]

이것이 더 간결하고 읽기 쉽습니다.

리스트 컴프리헨션은 표현식과 그 뒤를 따르는 for 절과 없거나 여러 개의 for 나 if 절들을 감싸는 대괄호로 구성됩니다. 그 결과는 새 리스트인데, for 와 if 절의 문맥에서 표현식의 값을 구해서 만들어집니다. 예를 들어, 이 리스트 컴프리헨션은 두 리스트의 요소들을 서로 같지 않은 것끼리 결합합니다:

>>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

그리고, 이것은 다음과 동등합니다:

>>> combs = []
>>> for x in [1,2,3]:
...     for y in [3,1,4]:
...         if x != y:
...             combs.append((x, y))
...
>>> combs
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

두 코드 조각에서 for 와 if 문의 순서가 같음에 유의하세요.

표현식이 튜플이면 (즉 앞의 예에서 (x, y)), 반드시 괄호로 둘러싸야 합니다.

>>> vec = [-4, -2, 0, 2, 4]
>>> # create a new list with the values doubled
>>> [x*2 for x in vec]
[-8, -4, 0, 4, 8]
>>> # filter the list to exclude negative numbers
>>> [x for x in vec if x >= 0]
[0, 2, 4]
>>> # apply a function to all the elements
>>> [abs(x) for x in vec]
[4, 2, 0, 2, 4]
>>> # call a method on each element
>>> freshfruit = ['  banana', '  loganberry ', 'passion fruit  ']
>>> [weapon.strip() for weapon in freshfruit]
['banana', 'loganberry', 'passion fruit']
>>> # create a list of 2-tuples like (number, square)
>>> [(x, x**2) for x in range(6)]
[(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]
>>> # the tuple must be parenthesized, otherwise an error is raised
>>> [x, x**2 for x in range(6)]
  File "<stdin>", line 1, in <module>
    [x, x**2 for x in range(6)]
               ^
SyntaxError: invalid syntax
>>> # flatten a list using a listcomp with two 'for'
>>> vec = [[1,2,3], [4,5,6], [7,8,9]]
>>> [num for elem in vec for num in elem]
[1, 2, 3, 4, 5, 6, 7, 8, 9]

리스트 컴프리헨션은 복잡한 표현식과 중첩된 함수들을 포함할 수 있습니다:

>>> from math import pi
>>> [str(round(pi, i)) for i in range(1, 6)]
['3.1', '3.14', '3.142', '3.1416', '3.14159']

5.1.4. 중첩된 리스트 컴프리헨션

리스트 컴프리헨션의 첫 표현식으로 임의의 표현식이 올 수 있는데, 다른 리스트 컴프리헨션도 가능합니다.

다음과 같은 길이가 4인 리스트 3개의 리스트로 구현된 3x4 행렬의 예를 봅시다:

>>> matrix = [
...     [1, 2, 3, 4],
...     [5, 6, 7, 8],
...     [9, 10, 11, 12],
... ]

다음 리스트 컴프리헨션은 행과 열을 전치 시킵니다:

>>> [[row[i] for row in matrix] for i in range(4)]
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]

앞절에서 보았듯이, 중첩된 리스트 컴프리헨션은 뒤따르는 for 의 문맥에서 값이 구해집니다. 그래서 이 예는 다음과 동등합니다:

>>> transposed = []
>>> for i in range(4):
...     transposed.append([row[i] for row in matrix])
...
>>> transposed
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]

이것은 다시 다음과 같습니다:

>>> transposed = []
>>> for i in range(4):
...     # the following 3 lines implement the nested listcomp
...     transposed_row = []
...     for row in matrix:
...         transposed_row.append(row[i])
...     transposed.append(transposed_row)
...
>>> transposed
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]

실제 세상에서는, 복잡한 흐름문보다 내장 함수들을 선호해야 합니다. 이 경우에는 zip() 함수가 제 역할을 할 수 있습니다:

>>> list(zip(*matrix))
[(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]

이 줄에 나오는 에스터리스크에 대한 자세한 내용은 인자 목록 언 패킹 을 보세요.

5.2. del 문

리스트에서 값 대신에 인덱스를 사용해서 항목을 삭제하는 방법이 있습니다: del 문입니다. 이것은 값을 돌려주는 pop() 메서드와 다릅니다. del 문은 리스트에서 슬라이스를 삭제하거나 전체 리스트를 비우는 데도 사용될 수 있습니다 (앞에서 빈 리스트를 슬라이스에 대입해서 했던 일입니다). 예를 들어:

>>> a = [-1, 1, 66.25, 333, 333, 1234.5]
>>> del a[0]
>>> a
[1, 66.25, 333, 333, 1234.5]
>>> del a[2:4]
>>> a
[1, 66.25, 1234.5]
>>> del a[:]
>>> a
[]

del 는 변 자체를 삭제하는데에도 사용될 수 있습니다:

>>> del a

이후에 이름 a 를 참조하는 것은 에러입니다 (적어도 다른 값이 새로 대입되기 전까지). 뒤에서 del 의 다른 용도를 보게 됩니다.

5.3. 튜플과 시퀀스

리스트와 문자열이 인덱싱과 슬라이싱 연산과 같은 많은 성질을 공유함을 보았습니다. 이것들은 시퀀스 자료 형의 두 가지 예입니다 (시퀀스 형 — list, tuple, range 를 보세요). 파이썬은 진화하는 언어이기 때문에, 다른 시퀀스 자료형이 추가될 수도 있습니다. 다른 표준 시퀀스 자료 형이 있습니다: 튜플 입니다.

튜플은 쉼표로 구분되는 여러 값으로 구성됩니다. 예를 들어:

>>> t = 12345, 54321, 'hello!'
>>> t[0]
12345
>>> t
(12345, 54321, 'hello!')
>>> # Tuples may be nested:
... u = t, (1, 2, 3, 4, 5)
>>> u
((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))
>>> # Tuples are immutable:
... t[0] = 88888
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> # but they can contain mutable objects:
... v = ([1, 2, 3], [3, 2, 1])
>>> v
([1, 2, 3], [3, 2, 1])

여러분이 보듯이, 출력되는 튜플은 항상 괄호로 둘러싸입니다, 그래서 중첩된 튜플이 올바르게 해석됩니다; 종종 괄호가 필요하기는 하지만 (튜플이 더 큰 표현식의 일부일 때), 둘러싼 괄호와 함께 또는 없이 입력될 수 있습니다. 튜플의 개별 항목에 대입하는 것은 가능하지 않지만, 리스트 같은 가변 객체를 포함하는 튜플을 만들 수는 있습니다.

튜플이 리스트처럼 보인다 하더라도, 이것들은 다른 상황에서 다른 목적으로 사용됩니다. 튜플은 불변 이고, 보통 이질적인 요소들의 시퀀스를 포함합니다. 요소들은 언 패킹 (이 섹션의 뒤에 나온다) 이나 인덱싱 (또는 네임드 튜플 의 경우는 어트리뷰트로도) 으로 액세스합니다. 리스트는 가변 이고, 요소들은 보통 등질 적이고 리스트에 대한 이터레이션으로 액세스 됩니다.

특별한 문제는 비었거나 하나의 항목을 갖는 튜플을 만드는 것입니다: 이 경우를 수용하기 위해 문법은 추가적인 예외 사항을 갖고 있습니다. 빈 튜플은 빈 괄호 쌍으로 만들어집니다; 하나의 항목으로 구성된 튜플은 값 뒤에 쉼표를 붙여서 만듭니다 (값 하나를 괄호로 둘러싸기만 하는 것으로는 충분하지 않습니다). 추합니다, 하지만 효과적입니다. 예를 들어:

>>> empty = ()
>>> singleton = 'hello',    # <-- note trailing comma
>>> len(empty)
0
>>> len(singleton)
1
>>> singleton
('hello',)

문장 t = 12345, 54321, 'hello!' 는 튜플 패킹 의 예입니다: 값 12345, 54321, 'hello!' 는 함께 튜플로 패킹 됩니다. 반대 연산 또한 가능합니다:

>>> x, y, z = t

이것은, 충분히 적절하게도, 시퀀스 언 패킹 이라고 불리고 오른쪽에 어떤 시퀀스가 와도 됩니다. 시퀀스 언 패킹은 등호의 좌변에 시퀀스에 있는 요소들과 같은 개수의 변수들이 올 것을 요구합니다. 다중 대입은 사실 튜플 패킹과 시퀀스 언 패킹의 조합일뿐이라는 것에 유의하세요.

5.4. 집합

파이썬은 집합 을 위한 자료 형도 포함합니다. 집합은 중복되는 요소가 없는 순서 없는 컬렉션입니다. 기본적인 용도는 멤버십 검사와 중복 엔트리 제거입니다. 집합 객체는 합집합, 교집합, 차집합, 대칭 차집합과 같은 수학적인 연산들도 지원합니다.

집합을 만들 때는 중괄호나 set() 함수를 사용할 수 있습니다. 주의사항: 빈 집합을 만들려면 set() 을 사용해야 합니다. {} 가 아닙니다; 후자는 빈 딕셔너리를 만드는데, 다음 섹션에서 다룹니다.

여기 간략한 실연이 있습니다:

>>> basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
>>> print(basket)                      # show that duplicates have been removed
{'orange', 'banana', 'pear', 'apple'}
>>> 'orange' in basket                 # fast membership testing
True
>>> 'crabgrass' in basket
False

>>> # Demonstrate set operations on unique letters from two words
...
>>> a = set('abracadabra')
>>> b = set('alacazam')
>>> a                                  # unique letters in a
{'a', 'r', 'b', 'c', 'd'}
>>> a - b                              # letters in a but not in b
{'r', 'd', 'b'}
>>> a | b                              # letters in a or b or both
{'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}
>>> a & b                              # letters in both a and b
{'a', 'c'}
>>> a ^ b                              # letters in a or b but not both
{'r', 'd', 'b', 'm', 'z', 'l'}

리스트 컴프리헨션 과 유사하게, 집합 컴프리헨션도 지원됩니다:

>>> a = {x for x in 'abracadabra' if x not in 'abc'}
>>> a
{'r', 'd'}

5.5. 딕셔너리

파이썬에 내장된 또 하나의 쓸모있는 자료 형은 딕셔너리 입니다 (매핑 형 — dict 를 보세요). 딕셔너리는 종종 다른 언어들에서 “연관 메모리(associative memories)” 나 “연관 배열(associative arrays)” 의 형태로 발견됩니다. 숫자들로 인덱싱되는 시퀀스와 달리, 딕셔너리는 키 로 인덱싱되는데, 모든 불변형을 사용할 수 있습니다; 문자열과 숫자들은 항상 키가 될 수 있습니다. 튜플이 문자열, 숫자, 튜플들만 포함하면, 키로 사용될 수 있습니다; 튜플이 직접적이나 간접적으로 가변 객체를 포함하면, 키로 사용될 수 없습니다. 리스트는 키로 사용할 수 없는데, 리스트는 인덱스 대입, 슬라이스 대입, append() 나 extend() 같은 메서드들로 값이 수정될 수 있기 때문입니다.

딕셔너리를 (한 딕셔너리 안에서) 키가 중복되지 않는다는 제약 조건을 가진 키: 값 쌍의 집합으로 생각하는 것이 최선입니다. 중괄호 쌍은 빈 딕셔너리를 만듭니다: {}. 중괄호 안에 쉼표로 분리된 키:값 쌍들의 목록을 넣으면, 딕셔너리에 초기 키:값 쌍들을 제공합니다; 이것이 딕셔너리가 출력되는 방식이기도 합니다.

딕셔너리의 주 연산은 값을 키와 함께 저장하고 주어진 키로 값을 추출하는 것입니다. del 로 키:값 쌍을 삭제하는 것도 가능합니다. 이미 사용하고 있는 키로 저장하면, 그 키로 저장된 예전 값은 잊힙니다. 존재하지 않는 키로 값을 추출하는 것은 에러입니다.

딕셔러리에 list(d) 를 수행하면 딕셔너리에서 사용되고 있는 모든 키의 리스트를 삽입 순서대로 돌려줍니다 (정렬을 원하면 대신 sorted(d) 를 사용하면 됩니다). 하나의 키가 딕셔너리에 있는지 검사하려면, in 키워드들 사용하세요.

여기에 딕셔너리를 사용하는 조그마한 예가 있습니다:

>>> tel = {'jack': 4098, 'sape': 4139}
>>> tel['guido'] = 4127
>>> tel
{'jack': 4098, 'sape': 4139, 'guido': 4127}
>>> tel['jack']
4098
>>> del tel['sape']
>>> tel['irv'] = 4127
>>> tel
{'jack': 4098, 'guido': 4127, 'irv': 4127}
>>> list(tel)
['jack', 'guido', 'irv']
>>> sorted(tel)
['guido', 'irv', 'jack']
>>> 'guido' in tel
True
>>> 'jack' not in tel
False

dict() 생성자는 키-값 쌍들의 시퀀스로 부터 직접 딕셔너리를 구성합니다.

>>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
{'sape': 4139, 'guido': 4127, 'jack': 4098}

이에 더해, 딕셔너리 컴프리헨션은 임의의 키와 값 표현식들로 부터 딕셔너리를 만드는데 사용될 수 있습니다:

>>> {x: x**2 for x in (2, 4, 6)}
{2: 4, 4: 16, 6: 36}

키가 간단한 문자열일 때, 때로 키워드 인자들을 사용해서 쌍을 지정하기가 쉽습니다:

>>> dict(sape=4139, guido=4127, jack=4098)
{'sape': 4139, 'guido': 4127, 'jack': 4098}

5.6. 루프 테크닉

딕셔너리로 루핑할 때, items() 메서드를 사용하면 키와 거기에 대응하는 값을 동시에 얻을 수 있습니다.

>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
>>> for k, v in knights.items():
...     print(k, v)
...
gallahad the pure
robin the brave

시퀀스를 루핑할 때, enumerate() 함수를 사용하면 위치 인덱스와 대응하는 값을 동시에 얻을 수 있습니다.

>>> for i, v in enumerate(['tic', 'tac', 'toe']):
...     print(i, v)
...
0 tic
1 tac
2 toe

둘이나 그 이상의 시퀀스를 동시에 루핑하려면, zip() 함수로 엔트리들의 쌍을 만들 수 있습니다.

>>> questions = ['name', 'quest', 'favorite color']
>>> answers = ['lancelot', 'the holy grail', 'blue']
>>> for q, a in zip(questions, answers):
...     print('What is your {0}?  It is {1}.'.format(q, a))
...
What is your name?  It is lancelot.
What is your quest?  It is the holy grail.
What is your favorite color?  It is blue.

시퀀스를 거꾸로 루핑하려면, 먼저 정방향으로 시퀀스를 지정한 다음에 reversed() 함수를 호출하세요.

>>> for i in reversed(range(1, 10, 2)):
...     print(i)
...
9
7
5
3
1

정렬된 순서로 시퀀스를 루핑하려면, sorted() 함수를 사용해서 소스를 변경하지 않고도 정렬된 새 리스트를 받을 수 있습니다.

>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
>>> for f in sorted(set(basket)):
...     print(f)
...
apple
banana
orange
pear

때로 루프를 돌고 있는 리스트를 변경하고픈 유혹을 느낍니다; 하지만, 종종, 대신 새 리스트를 만드는 것이 더 간단하고 더 안전합니다.

>>> import math
>>> raw_data = [56.2, float('NaN'), 51.7, 55.3, 52.5, float('NaN'), 47.8]
>>> filtered_data = []
>>> for value in raw_data:
...     if not math.isnan(value):
...         filtered_data.append(value)
...
>>> filtered_data
[56.2, 51.7, 55.3, 52.5, 47.8]

5.7. 조건 더 보기

while 과 if 문에서 사용되는 조건에는 비교뿐만 아니라 모든 연산자를 사용할 수 있습니다.

비교 연산자 in 과 not in 은 값이 시퀀스에 있는지 (없는지) 검사합니다. 연산자 is 와 is not 은 두 객체가 진짜로 같은 객체인지 비교합니다; 이것은 리스트와 같은 가변 객체에서만 의미가 있습니다. 모든 비교 연산자들은 같은 우선순위를 갖는데, 모든 산술 연산자들보다 낮습니다.

비교는 연쇄할 수 있습니다. 예를 들어, a < b == c 는, a 가 b 보다 작고, 동시에 b 가 c 와 같은지 검사합니다.

비교는 논리 연산자 and 와 or 를 사용해서 결합할 수 있고, 비교의 결과는 (또는 그 밖의 모든 논리 표현식은) not 으로 부정될 수 있습니다. 이것들은 비교 연산자보다 낮은 우선순위를 갖습니다. 이것 간에는 not 이 가장 높은 우선순위를 갖고, or 가 가장 낮습니다. 그래서 A and not B or C 는 (A and (not B)) or C 와 동등합니다. 여느 때처럼, 원하는 조합을 표현하기 위해 괄호를 사용할 수 있습니다.

논리 연산자 and 와 or 는 소위 단락-회로(short-circuit) 연산자입니다: 인자들은 왼쪽에서 오른쪽으로 값이 구해지고, 결과가 결정되자마자 값 구하기는 중단됩니다. 예를 들어, A 와 C 가 참이고 B 가 거짓이면, A and B and C 는 표현식 C 의 값을 구하지 않습니다. 논리값이 아닌 일반 값으로 사용될 때, 단락-회로 연산자의 반환 값은 마지막으로 값이 구해진 인자입니다.

비교의 결과나 다른 논리 표현식의 결과를 변수에 대입할 수 있습니다. 예를 들어,

>>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance'
>>> non_null = string1 or string2 or string3
>>> non_null
'Trondheim'

파이썬에서, C와는 달리, 대입은 표현식 안에 등장할 수 없습니다. C 프로그래머들이 이 문제로 투덜거리지만, C 프로그램에서 흔히 마주치는 부류의 문제들을 회피하도록 합니다: == 를 사용할 표현식에 = 를 입력하는 실수.

5.8. 시퀀스와 다른 형들을 비교하기

시퀀스 객체들은 같은 시퀀스 형의 다른 객체들과 비교될 수 있습니다. 비교는 사전식 순서를 사용합니다: 먼저 첫 두 항목을 비교해서 다르면 이것이 비교의 결과를 결정합니다; 같으면, 다음 두 항목을 비교하고, 이런 식으로 어느 한 시퀀스가 소진될 때까지 계속합니다. 만약 비교되는 두 항목 자체가 같은 형의 시퀀스면, 사전식 비교가 재귀적으로 수행됩니다. 두 시퀀스의 모든 항목이 같다고 비교되면, 시퀀스들은 같은 것으로 취급됩니다. 한 시퀀스가 다른 하나의 머리 부분 서브 시퀀스면, 짧은 시퀀스가 작은 것입니다. 문자열의 사전식 배열은 개별 문자들의 순서를 정하는데 유니코드 코드 포인트 숫자를 사용합니다. 같은 형의 시퀀스들 간의 비교의 몇 가지 예는 이렇습니다:

(1, 2, 3)              < (1, 2, 4)
[1, 2, 3]              < [1, 2, 4]
'ABC' < 'C' < 'Pascal' < 'Python'
(1, 2, 3, 4)           < (1, 2, 4)
(1, 2)                 < (1, 2, -1)
(1, 2, 3)             == (1.0, 2.0, 3.0)
(1, 2, ('aa', 'ab'))   < (1, 2, ('abc', 'a'), 4)

서로 다른 형의 객체들을 < 나 > 로 비교하는 것은, 그 객체들이 적절한 비교 메서드들을 갖고 있을 때만 허락된다는 것에 유의하세요. 예를 들어, 서로 다른 숫자 형들은 그들의 숫자 값에 따라 비교됩니다. 그래서 0은 0.0과 같고, 등등. 그렇지 않으면, 임의의 순서를 제공하는 대신, 인터프리터는 TypeError 를 일으킵니다.

각주

1

다른 언어들에서는 가변 객체를 돌려주기도 하는데, d->insert("a")->remove("b")->sort(); 와 같은 메서드 연쇄를 허락합니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 자습서 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 자습서 »

|

6. 모듈

파이썬 인터프리터를 종료한 후에 다시 들어가면, 여러분이 만들었던 정의들이 사라집니다 (함수나 변수들). 그래서, 좀 긴 프로그램을 쓰고자 한다면, 대신 인터프리터 입력을 편집기를 사용해서 준비한 후에 그 파일을 입력으로 사용해서 실행하는 것이 좋습니다. 이렇게 하는 것을 스크립트 를 만든다고 합니다. 프로그램이 길어짐에 따라, 유지를 쉽게 하려고 여러 개의 파일로 나누고 싶을 수 있습니다. 여러 프로그램에서 썼던 편리한 함수를 각 프로그램에 정의를 복사하지 않고도 사용하고 싶을 수도 있습니다.

이런 것을 지원하기 위해, 파이썬은 정의들을 파일에 넣고 스크립트나 인터프리터의 대화형 모드에서 사용할 수 있는 방법을 제공합니다. 그런 파일을 모듈 이라고 부릅니다; 모듈로부터 정의들이 다른 모듈이나 메인 모듈로 임포트 될 수 있습니다 (메인 모듈은 최상위 수준에서 실행되는 스크립트나 계산기 모드에서 액세스하는 변수들의 컬렉션입니다).

모듈은 파이썬 정의와 문장들을 담고 있는 파일입니다. 파일의 이름은 모듈 이름에 확장자 .py 를 붙입니다. 모듈 내에서, 모듈의 이름은 전역 변수 __name__ 으로 제공됩니다. 예를 들어, 여러분이 좋아하는 편집기로 fibo.py 라는 이름의 파일을 현재 디렉터리에 만들고 다음과 같은 내용으로 채웁니다:

# Fibonacci numbers module

def fib(n):    # write Fibonacci series up to n
    a, b = 0, 1
    while a < n:
        print(a, end=' ')
        a, b = b, a+b
    print()

def fib2(n):   # return Fibonacci series up to n
    result = []
    a, b = 0, 1
    while a < n:
        result.append(a)
        a, b = b, a+b
    return result

이제 파이썬 인터프리터에 들어가서 이 모듈을 다음과 같은 명령으로 임포트 합니다:

>>> import fibo

이렇게 한다고 fibo 에 정의된 함수들의 이름이 현재 심볼 테이블에 직접 들어가지는 않습니다; 오직 모듈 이름 fibo 만 들어갈 뿐입니다. 이 모듈 이름을 사용해서 함수들을 액세스할 수 있습니다:

>>> fibo.fib(1000)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
>>> fibo.fib2(100)
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
>>> fibo.__name__
'fibo'

함수를 자주 사용할 거라면 지역 이름으로 대입할 수 있습니다:

>>> fib = fibo.fib
>>> fib(500)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

6.1. 모듈 더 보기

모듈은 함수 정의뿐만 아니라 실행 가능한 문장들도 포함할 수 있습니다. 이 문장들은 모듈을 초기화하는 데 사용됩니다. 이것들은 임포트 문에서 모듈 이름이 처음 등장할 때만 실행됩니다. 1 (이것들은 파일이 스크립트로 실행될 때도 실행됩니다.)

각 모듈은 자신만의 심볼 테이블을 갖고 있는데, 그 모듈에서 정의된 함수들의 전역 심볼 테이블로 사용됩니다. 그래서, 모듈의 저자는 사용자의 전역 변수와 우연히 충돌할 것을 걱정하지 않고 전역 변수를 사용할 수 있습니다. 반면에, 여러분이 무얼 하는지 안다면, 모듈의 함수를 참조하는데 사용된 것과 같은 표기법으로 모듈의 전역 변수들을 건드릴 수 있습니다, modname.itemname.

모듈은 다른 모듈들을 임포트할 수 있습니다. 모든 import 문들을 모듈의 처음에 놓는 것이 관례지만 반드시 그래야 하는 것은 아닙니다 (그 점에 관한 한 스크립트도 마찬가집니다). 임포트되는 모듈 이름은 임포트하는 모듈의 전역 심볼 테이블에 들어갑니다.

모듈에 들어있는 이름들을 직접 임포트하는 모듈의 심볼 테이블로 임포트하는 import 문의 변종이 있습니다. 예를 들어:

>>> from fibo import fib, fib2
>>> fib(500)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

이것은 지역 심볼 테이블에 임포트되는 모듈의 이름을 만들지 않습니다 (그래서 이 예에서는, fibo 가 정의되지 않습니다).

모듈이 정의하는 모든 이름을 임포트하는 변종도 있습니다:

>>> from fibo import *
>>> fib(500)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

이것은 밑줄 (_) 로 시작하는 것들을 제외한 모든 이름을 임포트 합니다. 대부분 파이썬 프로그래머들은 이 기능을 사용하지 않는데, 인터프리터로 알려지지 않은 이름들의 집합을 도입하게 되어, 여러분이 이미 정의한 것들을 가리게 될 수 있기 때문입니다.

일반적으로 모듈이나 패키지에서 * 를 임포트하는 것은 눈살을 찌푸리게 한다는 것에 유의하세요, 종종 읽기에 편하지 않은 코드를 만들기 때문입니다. 하지만, 대화형 세션에서 입력을 줄이고자 사용하는 것은 상관없습니다.

모듈 이름 다음에 as 가 올 경우, as 다음의 이름을 임포트한 모듈에 직접 연결합니다.

>>> import fibo as fib
>>> fib.fib(500)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

이것은 import fibo 가하는 것과 같은 방식으로 모듈을 임포트 하는데, 유일한 차이점은 그 모듈을 fib 라는 이름으로 사용할 수 있다는 것입니다.

from을 써서 비슷한 효과를 낼 때도 사용할 수 있습니다:

>>> from fibo import fib as fibonacci
>>> fibonacci(500)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

참고

효율성의 이유로, 각 모듈은 인터프리터 세션마다 한 번만 임포트됩니다. 그래서, 여러분이 모듈을 수정하면, 인터프리터를 다시 시작시켜야 합니다 — 또는, 대화형으로 시험하는 모듈이 하나뿐이라면, importlib.reload() 를 사용하세요. 예를 들어, import importlib; importlib.reload(modulename).

6.1.1. 모듈을 스크립트로 실행하기

여러분이 파이썬 모듈을 이렇게 실행하면

python fibo.py <arguments>

모듈에 있는 코드는, 그것을 임포트할 때처럼 실행됩니다. 하지만 __name__ 은 "__main__" 로 설정됩니다. 이것은, 이 코드를 모듈의 끝에 붙여서:

if __name__ == "__main__":
    import sys
    fib(int(sys.argv[1]))

파일을 임포트할 수 있는 모듈뿐만 아니라 스크립트로도 사용할 수 있도록 만들 수 있음을 의미하는데, 오직 모듈이 “메인” 파일로 실행될 때만 명령행을 파싱하는 코드가 실행되기 때문입니다:

$ python fibo.py 50
0 1 1 2 3 5 8 13 21 34

모듈이 임포트될 때, 코드는 실행되지 않습니다:

>>> import fibo
>>>

이것은 종종 모듈에 대한 편리한 사용자 인터페이스를 제공하거나 테스트 목적으로 사용됩니다 (모듈을 스크립트로 실행하면 테스트 스위트를 실행하기).

6.1.2. 모듈 검색 경로

spam 이라는 이름의 모듈이 임포트될 때, 인터프리터는 먼저 그 이름의 내장 모듈을 찾습니다. 발견되지 않으면, 변수 sys.path 로 주어지는 디렉터리들에서 spam.py 라는 이름의 파일을 찾습니다. sys.path 는 이 위치들로 초기화됩니다:

입력 스크립트를 포함하는 디렉터리 (또는 파일이 지정되지 않았을 때는 현재 디렉터리).

PYTHONPATH (디렉터리 이름들의 목록, 셸 변수 PATH 와 같은 문법).

설치 의존적인 기본값

참고

심볼릭 링크를 지원하는 파일 시스템에서, 입력 스크립트를 포함하는 디렉터리는 심볼릭 링크를 변환한 후에 계산됩니다. 다른 말로, 심볼릭 링크를 포함하는 디렉터리는 모듈 검색 경로에 포함되지 않습니다.

초기화 후에, 파이썬 프로그램은 sys.path 를 수정할 수 있습니다. 스크립트를 포함하는 디렉터리는 검색 경로의 처음에, 표준 라이브러리 경로의 앞에 놓입니다. 이것은 같은 이름일 경우 라이브러리 디렉터리에 있는 것 대신 스크립트를 포함하는 디렉터리의 것이 로드된다는 뜻입니다. 이 치환이 의도된 것이 아니라면 에러입니다. 더 자세한 정보는 표준 모듈들 을 보세요.

6.1.3. “컴파일된” 파이썬 파일

모듈 로딩을 빠르게 하려고, 파이썬은 __pycache__ 디렉터리에 각 모듈의 컴파일된 버전을 module.version.pyc 라는 이름으로 캐싱합니다. version 은 컴파일된 파일의 형식을 지정합니다; 일반적으로 파이썬의 버전 번호를 포함합니다. 예를 들어, CPython 배포 3.3 에서 spam.py 의 컴파일된 버전은 __pycache__/spam.cpython-33.pyc 로 캐싱 됩니다. 이 명명법은 서로 다른 파이썬 배포와 버전의 컴파일된 모듈들이 공존할 수 있도록 합니다.

파이썬은 소스의 수정 시간을 컴파일된 버전과 비교해서 시효가 지나 다시 컴파일해야 하는지 검사합니다. 이것은 완전히 자동화된 과정입니다. 또한, 컴파일된 모듈은 플랫폼 독립적이기 때문에, 같은 라이브러리를 서로 다른 아키텍처를 갖는 시스템들에서 공유할 수 있습니다.

파이썬은 두 가지 상황에서 캐시를 검사하지 않습니다. 첫째로, 명령행에서 직접 로드되는 모듈들은 항상 재컴파일하고 그 결과를 저장하지 않습니다. 둘째로, 소스 모듈이 없으면 캐시를 검사하지 않습니다. 소스 없는 (컴파일된 파일만 있는) 배포를 지원하려면, 컴파일된 모듈이 소스 디렉터리에 있어야 하고, 소스 모듈이 없어야 합니다.

전문가를 위한 몇 가지 팁

컴파일된 모듈의 크기를 줄이려면 파이썬 명령에 -O 나 -OO 스위치를 사용할 수 있습니다. -O 스위치는 assert 문을 제거하고, -OO 스위치는 assert 문과 __doc__ 문자열을 모두 제거합니다. 어떤 프로그램들은 이것들에 의존하기 때문에, 무엇을 하고 있는지 아는 경우만 이 옵션을 사용해야 합니다. “최적화된” 모듈은 opt- 태그를 갖고, 보통 더 작습니다. 미래의 배포에서는 최적화의 효과가 변경될 수 있습니다.

.py 파일에서 읽을 때보다 .pyc 파일에서 읽을 때 프로그램이 더 빨리 실행되지는 않습니다; .pyc 파일에서 더 빨라지는 것은 로드되는 속도뿐입니다.

모듈 compileall 은 디렉터리에 있는 모든 모듈의 .pyc 파일들을 만들 수 있습니다.

이 절차에 대한 더 자세한 정보, 결정들의 순서도를 포함합니다, 는 PEP 3147 [https://www.python.org/dev/peps/pep-3147] 에 나옵니다.

6.2. 표준 모듈들

파이썬은 표준 모듈들의 라이브러리가 함께 오는데, 별도의 문서 파이썬 라이브러리 레퍼런스 (이후로는 “라이브러리 레퍼런스”) 에서 설명합니다. 어떤 모듈들은 인터프리터에 내장됩니다; 이것들은 언어의 핵심적인 부분은 아니지만 그런데도 내장된 연산들에 대한 액세스를 제공하는데, 효율이나 시스템 호출과 같은 운영 체제 기본 요소들에 대한 액세스를 제공하기 위함입니다. 그런 모듈들의 집합은 설정 옵션인데 기반 플랫폼 의존적입니다. 예를 들어, winreg 모듈은 윈도우 시스템에서만 제공됩니다. 특별한 모듈 하나는 주목을 받을 필요가 있습니다: sys. 모든 파이썬 인터프리터에 내장됩니다. 변수 sys.ps1 와 sys.ps2 는 기본과 보조 프롬프트로 사용되는 문자열을 정의합니다:

>>> import sys
>>> sys.ps1
'>>> '
>>> sys.ps2
'... '
>>> sys.ps1 = 'C> '
C> print('Yuck!')
Yuck!
C>

이 두 개의 변수들은 인터프리터가 대화형 모드일 때만 정의됩니다.

변수 sys.path 는 인터프리터의 모듈 검색 경로를 결정하는 문자열들의 리스트입니다. 환경 변수 PYTHONPATH 에서 취한 기본 경로나, PYTHONPATH 가 설정되지 않는 경우 내장 기본값으로 초기화됩니다. 표준 리스트 연산을 사용해서 수정할 수 있습니다:

>>> import sys
>>> sys.path.append('/ufs/guido/lib/python')

6.3. dir() 함수

내장 함수 dir() 은 모듈이 정의하는 이름들을 찾는 데 사용됩니다. 문자열들의 정렬된 리스트를 돌려줍니다:

>>> import fibo, sys
>>> dir(fibo)
['__name__', 'fib', 'fib2']
>>> dir(sys)
['__displayhook__', '__doc__', '__excepthook__', '__loader__', '__name__',
 '__package__', '__stderr__', '__stdin__', '__stdout__',
 '_clear_type_cache', '_current_frames', '_debugmallocstats', '_getframe',
 '_home', '_mercurial', '_xoptions', 'abiflags', 'api_version', 'argv',
 'base_exec_prefix', 'base_prefix', 'builtin_module_names', 'byteorder',
 'call_tracing', 'callstats', 'copyright', 'displayhook',
 'dont_write_bytecode', 'exc_info', 'excepthook', 'exec_prefix',
 'executable', 'exit', 'flags', 'float_info', 'float_repr_style',
 'getcheckinterval', 'getdefaultencoding', 'getdlopenflags',
 'getfilesystemencoding', 'getobjects', 'getprofile', 'getrecursionlimit',
 'getrefcount', 'getsizeof', 'getswitchinterval', 'gettotalrefcount',
 'gettrace', 'hash_info', 'hexversion', 'implementation', 'int_info',
 'intern', 'maxsize', 'maxunicode', 'meta_path', 'modules', 'path',
 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'ps1',
 'setcheckinterval', 'setdlopenflags', 'setprofile', 'setrecursionlimit',
 'setswitchinterval', 'settrace', 'stderr', 'stdin', 'stdout',
 'thread_info', 'version', 'version_info', 'warnoptions']

인자가 없으면, dir() 는 현재 정의한 이름들을 나열합니다:

>>> a = [1, 2, 3, 4, 5]
>>> import fibo
>>> fib = fibo.fib
>>> dir()
['__builtins__', '__name__', 'a', 'fib', 'fibo', 'sys']

모든 형의 이름을 나열한다는 것에 유의해야 합니다: 변수, 모듈, 함수, 등등.

dir() 은 내장 함수와 변수들의 이름을 나열하지 않습니다. 그것들의 목록을 원한다면, 표준 모듈 builtins 에 정의되어 있습니다:

>>> import builtins
>>> dir(builtins)
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException',
 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning',
 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError',
 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning',
 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False',
 'FileExistsError', 'FileNotFoundError', 'FloatingPointError',
 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError',
 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError',
 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError',
 'MemoryError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented',
 'NotImplementedError', 'OSError', 'OverflowError',
 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError',
 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning',
 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError',
 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError',
 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError',
 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning',
 'ValueError', 'Warning', 'ZeroDivisionError', '_', '__build_class__',
 '__debug__', '__doc__', '__import__', '__name__', '__package__', 'abs',
 'all', 'any', 'ascii', 'bin', 'bool', 'bytearray', 'bytes', 'callable',
 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits',
 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit',
 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr',
 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass',
 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview',
 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property',
 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice',
 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars',
 'zip']

6.4. 패키지

패키지는 “점으로 구분된 모듈 이름” 를 써서 파이썬의 모듈 이름 공간을 구조화하는 방법입니다. 예를 들어, 모듈 이름 A.B 는 A 라는 이름의 패키지에 있는 B 라는 이름의 서브 모듈을 가리킵니다. 모듈의 사용이 다른 모듈의 저자들이 서로의 전역 변수 이름들을 걱정할 필요 없게 만드는 것과 마찬가지로, 점으로 구분된 모듈의 이름들은 NumPy 나 Pillow 과 같은 다중 모듈 패키지들의 저자들이 서로의 모듈 이름들을 걱정할 필요 없게 만듭니다.

음향 파일과 과 음향 데이터의 일관된 처리를 위한 모듈들의 컬렉션 (“패키지”) 을 설계하길 원한다고 합시다. 여러 종류의 음향 파일 형식이 있으므로 (보통 확장자로 구분됩니다, 예를 들어: .wav, .aiff, .au), 다양한 파일 형식 간의 변환을 위해 계속 늘어나는 모듈들의 컬렉션을 만들고 유지할 필요가 있습니다. 또한, 음향 데이터에 적용하고자 하는 많은 종류의 연산들도 있으므로 (믹싱, 에코 넣기, 이퀄라이저 기능 적용, 인공적인 스테레오 효과 만들기와 같은), 이 연산들을 수행하기 위한 모듈들을 끊임없이 작성하게 될 것입니다. 패키지를 이렇게 구성해 볼 수 있습니다 (계층적 파일 시스템으로 표현했습니다):

sound/                          Top-level package
      __init__.py               Initialize the sound package
      formats/                  Subpackage for file format conversions
              __init__.py
              wavread.py
              wavwrite.py
              aiffread.py
              aiffwrite.py
              auread.py
              auwrite.py
              ...
      effects/                  Subpackage for sound effects
              __init__.py
              echo.py
              surround.py
              reverse.py
              ...
      filters/                  Subpackage for filters
              __init__.py
              equalizer.py
              vocoder.py
              karaoke.py
              ...

패키지를 임포트할 때, 파이썬은 sys.path 에 있는 디렉터리들을 검색하면서 패키지 서브 디렉터리를 찾습니다.

파이썬이 디렉터리를 패키지로 취급하게 만들기 위해서 __init__.py 파일이 필요합니다. 이렇게 하면 string 처럼 흔히 쓰는 이름의 디렉터리가, 의도하지 않게 모듈 검색 경로의 뒤에 등장하는 올바른 모듈들을 가리는 일을 방지합니다. 가장 간단한 경우, __init__.py 는 그냥 빈 파일일 수 있지만, 패키지의 초기화 코드를 실행하거나 뒤에서 설명하는 __all__ 변수를 설정할 수 있습니다.

패키지 사용자는 패키지로부터 개별 모듈을 임포트할 수 있습니다, 예를 들어:

import sound.effects.echo

이것은 서브 모듈 sound.effects.echo 를 로드합니다. 전체 이름으로 참조되어야 합니다.

sound.effects.echo.echofilter(input, output, delay=0.7, atten=4)

서브 모듈을 임포트하는 다른 방법은 이렇습니다:

from sound.effects import echo

이것도 서브 모듈 echo 를 로드하고, 패키지 접두어 없이 사용할 수 있게 합니다. 그래서 이런 식으로 사용할 수 있습니다:

echo.echofilter(input, output, delay=0.7, atten=4)

또 다른 방법은 원하는 함수나 변수를 직접 임포트하는 것입니다:

from sound.effects.echo import echofilter

또다시, 이것은 서브 모듈 echo 를 로드하지만, 함수 echofilter() 를 직접 사용할 수 있게 만듭니다:

echofilter(input, output, delay=0.7, atten=4)

from package import item 를 사용할 때, item은 패키지의 서브 모듈 (또는 서브 패키지)일 수도 있고 함수, 클래스, 변수 등 패키지에 정의된 다른 이름들일 수도 있음에 유의하세요. import 문은 먼저 item이 패키지에 정의되어 있는지 검사하고, 그렇지 않으면 모듈이라고 가정하고 로드를 시도합니다. 찾지 못한다면, ImportError 예외를 일으킵니다.

이에 반하여, import item.subitem.subsubitem 와 같은 문법을 사용할 때, 마지막 것을 제외한 각 항목은 반드시 패키지여야 합니다; 마지막 항목은 모듈이나 패키지가 될 수 있지만, 앞의 항목에서 정의된 클래스, 함수, 변수 등이 될 수는 없습니다.

6.4.1. 패키지에서 * 임포트 하기

이제 from sound.effects import * 라고 쓰면 어떻게 될까? 이상적으로는, 어떻게든 파일 시스템에서 패키지에 어떤 모듈들이 들어있는지 찾은 다음, 그것들 모두를 임포트 하기를 원할 것입니다. 이렇게 하는 데는 시간이 오래 걸리고 서브 모듈을 임포트 함에 따라 어떤 서브 모듈을 명시적으로 임포트할 경우만 일어나야만 하는 원하지 않는 부수적 효과가 발생할 수 있습니다.

유일한 해결책은 패키지 저자가 패키지의 색인을 명시적으로 제공하는 것입니다. import 문은 다음과 같은 관례가 있습니다: 패키지의 __init__.py 코드가 __all__ 이라는 이름의 목록을 제공하면, 이것을 from package import * 를 만날 때 임포트 해야만 하는 모듈 이름들의 목록으로 받아들입니다. 새 버전의 패키지를 출시할 때 이 목록을 최신 상태로 유지하는 것은 패키지 저자의 책임입니다. 패키지 저자가 패키지에서 * 를 임포트하는 용도가 없다고 판단한다면, 이것을 지원하지 않기로 할 수도 있습니다. 예를 들어, 파일 sound/effects/__init__.py 는 다음과 같은 코드를 포함할 수 있습니다:

__all__ = ["echo", "surround", "reverse"]

이것은 from sound.effects import * 이 sound.effects 패키지의 세 서브 모듈들을 임포트하게 됨을 의미합니다.

__all__ 이 정의되지 않으면, 문장 from sound.effects import * 은 패키지 sound.effects 의 모든 서브 모듈들을 현재 이름 공간으로 임포트 하지 않습니다; 이것은 오직 패키지 sound.effects 가 임포트 되도록 만들고 (__init__.py 에 있는 초기화 코드들이 수행될 수 있습니다), 그 패키지가 정의하는 이름들을 임포트 합니다. 이 이름들은 __init__.py 가 정의하는 모든 이름 (그리고 명시적으로 로드된 서브 모듈들)을 포함합니다. 이 이름들에는 사전에 import 문으로 명시적으로 로드된 패키지의 서브 모듈들 역시 포함됩니다. 이 코드를 생각해봅시다:

import sound.effects.echo
import sound.effects.surround
from sound.effects import *

이 예에서, echo 와 surround 모듈이 현재 이름 공간으로 임포트 되는데, from...import 문이 실행될 때 sound.effects 패키지에 정의되기 때문입니다. (__all__ 이 정의될 때도 마찬가집니다.)

설사 어떤 모듈이 import * 를 사용할 때 특정 패턴을 따르는 이름들만 익스포트 하도록 설계되었다 하더라도, 프로덕션 코드에서는 여전히 좋지 않은 사례로 여겨집니다.

from package import specific_submodule 을 사용하는데 잘못된 것은 없다는 것을 기억하세요! 사실, 임포트하는 모듈이 다른 패키지에서 같은 이름의 서브 모듈을 사용할 필요가 없는 한 권장되는 표기법입니다.

6.4.2. 패키지 내부 간의 참조

패키지가 서브 패키지들로 구조화될 때 (예에서 나온 sound 패키지처럼), 이웃 패키지의 서브 모듈을 가리키는데 절대 임포트를 사용할 수 있습니다. 예를 들어, 모듈 sound.filters.vocoder 이 sound.effects 패키지의 echo 모듈이 필요하면, from sound.effects import echo 를 사용할 수 있습니다.

상대 임포트를 쓸 수도 있는데, from module import name 형태의 임포트 문을 사용합니다. 이 임포트는 상대 임포트에 수반되는 현재와 부모 패키지를 가리키기 위해 앞에 붙는 점을 사용합니다. 예를 들어, surround 모듈에서, 이렇게 사용할 수 있습니다:

from . import echo
from .. import formats
from ..filters import equalizer

상대 임포트가 현재 모듈의 이름에 기반을 둔다는 것에 주의하세요. 메인 모듈의 이름은 항상 "__main__" 이기 때문에, 파이썬 응용 프로그램의 메인 모듈로 사용될 목적의 모듈들은 반드시 절대 임포트를 사용해야 합니다.

6.4.3. 여러 디렉터리에 있는 패키지

패키지는 특별한 어트리뷰트 하나를 더 지원합니다, __path__. 이것은 패키지의 __init__.py 파일을 실행하기 전에, 이 파일이 들어있는 디렉터리의 이름을 포함하는 리스트로 초기화됩니다. 이 변수는 수정할 수 있습니다; 그렇게 하면 그 이후로 패키지에 포함된 모듈과 서브 패키지를 검색하는 데 영향을 주게 됩니다.

이 기능이 자주 필요하지는 않지만, 패키지에서 발견되는 모듈의 집합을 확장하는 데 사용됩니다.

각주

1

사실 함수 정의도 ‘실행’ 되는 ‘문장’ 입니다; 모듈 수준의 함수 정의를 실행하면 함수의 이름이 전역 심볼 테이블에 들어갑니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 자습서 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 자습서 »

|

7. 입력과 출력

프로그램의 출력을 표현하는 여러 가지 방법이 있습니다; 사람이 일기에 적합한 형태로 데이터를 인쇄할 수도 있고, 나중에 사용하기 위해 파일에 쓸 수도 있습니다. 이 장에서는 몇 가지 가능성을 논합니다.

7.1. 장식적인 출력 포매팅

지금까지 우리는 값을 쓰는 두 가지 방법을 만났습니다: 표현식 문장 과 print() 함수입니다. (세 번째 방법은 파일 객체의 write() 메서드를 사용하는 것입니다; 표준 출력 파일은 sys.stdout 로 참조할 수 있습니다. 이것에 대한 자세한 정보는 라이브러리 레퍼런스를 보세요.)

종종 단순히 스페이스로 구분된 값을 인쇄하는 것보다 출력 형식을 더 많이 제어해야 하는 경우가 있습니다. 출력을 포맷하는 데는 여러 가지 방법이 있습니다.

포맷 문자열 리터럴을 사용하려면, 시작 인용 부호 또는 삼중 인용 부호 앞에 f 또는 F 를 붙여 문자열을 시작하십시오. 이 문자열 안에서, { 및 } 문자 사이에, 변수 또는 리터럴 값을 참조할 수 있는 파이썬 표현식을 작성할 수 있습니다.

>>> year = 2016
>>> event = 'Referendum'
>>> f'Results of the {year} {event}'
'Results of the 2016 Referendum'

문자열의 str.format() 메서드는 더 많은 수작업을 요구합니다. 변수가 대체 될 위치를 표시하기 위해 { 및 }를 여전히 사용하고, 자세한 포매팅 디렉티브를 제공할 수 있지만, 포맷할 정보도 제공해야 합니다.

>>> yes_votes = 42_572_654
>>> no_votes = 43_132_495
>>> percentage = yes_votes / (yes_votes + no_votes)
>>> '{:-9} YES votes  {:2.2%}'.format(yes_votes, percentage)
' 42572654 YES votes  49.67%'

마지막으로, 문자열 슬라이싱 및 이어붙이기 연산을 사용하여 상상할 수 있는 모든 배치를 만듦으로써, 모든 문자열 처리를 스스로 수행할 수 있습니다. 문자열형에는 주어진 열 너비로 문자열을 채우는 데 유용한 연산을 수행하는 몇 가지 메서드가 있습니다.

장식적인 출력이 필요하지 않고 단지 디버깅을 위해 일부 변수를 빠르게 표시하려면, repr() 또는 str() 함수를 사용하여 모든 값을 문자열로 변환할 수 있습니다.

str() 함수는 어느 정도 사람이 읽기에 적합한 형태로 값의 표현을 돌려주게 되어있습니다. 반면에 repr() 은 인터프리터에 의해 읽힐 수 있는 형태를 만들게 되어있습니다 (또는 그렇게 표현할 수 있는 문법이 없으면 SyntaxError 를 일으키도록 구성됩니다). 사람이 소비하기 위한 특별한 표현이 없는 객체의 경우, str() 는 repr() 과 같은 값을 돌려줍니다. 많은 값, 숫자들이나 리스트와 딕셔너리와 같은 구조들, 은 두 함수를 쓸 때 같은 표현을 합니다. 특별히, 문자열은 두 가지 표현을 합니다.

몇 가지 예를 듭니다:

>>> s = 'Hello, world.'
>>> str(s)
'Hello, world.'
>>> repr(s)
"'Hello, world.'"
>>> str(1/7)
'0.14285714285714285'
>>> x = 10 * 3.25
>>> y = 200 * 200
>>> s = 'The value of x is ' + repr(x) + ', and y is ' + repr(y) + '...'
>>> print(s)
The value of x is 32.5, and y is 40000...
>>> # The repr() of a string adds string quotes and backslashes:
... hello = 'hello, world\n'
>>> hellos = repr(hello)
>>> print(hellos)
'hello, world\n'
>>> # The argument to repr() may be any Python object:
... repr((x, y, ('spam', 'eggs')))
"(32.5, 40000, ('spam', 'eggs'))"

string 모듈에는 문자열에 값을 치환하는 또 다른 방법을 제공하는 Template 클래스가 포함되어 있습니다. $x와 같은 자리 표시자를 사용하고 이것들을 딕셔너리에서 오는 값으로 치환하지만, 포매팅에 대한 제어를 훨씬 덜 제공합니다.

7.1.1. 포맷 문자열 리터럴

포맷 문자열 리터럴(간단히 f-문자열이라고도 합니다)은 문자열에 f 또는 F 접두어를 붙이고 표현식을 {expression}로 작성하여 문자열에 파이썬 표현식의 값을 삽입할 수 있게 합니다.

선택적인 포맷 지정자가 표현식 뒤에 올 수 있습니다. 이것으로 값이 포맷되는 방식을 더 정교하게 제어할 수 있습니다. 다음 예는 원주율을 소수점 이하 세 자리로 반올림합니다.

>>> import math
>>> print(f'The value of pi is approximately {math.pi:.3f}.')
The value of pi is approximately 3.142.

':' 뒤에 정수를 전달하면 해당 필드의 최소 문자 폭이 됩니다. 열을 줄 맞춤할 때 편리합니다.

>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}
>>> for name, phone in table.items():
...     print(f'{name:10} ==> {phone:10d}')
...
Sjoerd     ==>       4127
Jack       ==>       4098
Dcab       ==>       7678

다른 수정자를 사용하면 포맷되기 전에 값을 변환할 수 있습니다. '!a'는 ascii()를, '!s'는 str()을, '!r'는 repr()을 적용합니다.:

>>> animals = 'eels'
>>> print(f'My hovercraft is full of {animals}.')
My hovercraft is full of eels.
>>> print(f'My hovercraft is full of {animals!r}.')
My hovercraft is full of 'eels'.

이러한 포맷 사양에 대한 레퍼런스는 포맷 명세 미니 언어에 대한 레퍼런스 지침서를 참조하십시오.

7.1.2. 문자열 format() 메서드

str.format() 메서드의 기본적인 사용법은 이런 식입니다:

>>> print('We are the {} who say "{}!"'.format('knights', 'Ni'))
We are the knights who say "Ni!"

중괄호와 그 안에 있는 문자들 (포맷 필드라고 부른다) 은 str.format() 메서드로 전달된 객체들로 치환됩니다. 중괄호 안의 숫자는 str.format() 메서드로 전달된 객체들의 위치를 가리키는데 사용될 수 있습니다.

>>> print('{0} and {1}'.format('spam', 'eggs'))
spam and eggs
>>> print('{1} and {0}'.format('spam', 'eggs'))
eggs and spam

str.format() 메서드에 키워드 인자가 사용되면, 그 값들은 인자의 이름을 사용해서 지정할 수 있습니다.

>>> print('This {food} is {adjective}.'.format(
...       food='spam', adjective='absolutely horrible'))
This spam is absolutely horrible.

위치와 키워드 인자를 자유롭게 조합할 수 있습니다:

>>> print('The story of {0}, {1}, and {other}.'.format('Bill', 'Manfred',
                                                       other='Georg'))
The story of Bill, Manfred, and Georg.

If you have a really long format string that you don’t want to split up, it would be nice if you could reference the variables to be formatted by name instead of by position. This can be done by simply passing the dict and using square brackets '[]' to access the keys.

>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
>>> print('Jack: {0[Jack]:d}; Sjoerd: {0[Sjoerd]:d}; '
...       'Dcab: {0[Dcab]:d}'.format(table))
Jack: 4098; Sjoerd: 4127; Dcab: 8637678

‘**’ 표기법을 사용해서 table을 키워드 인자로 전달해도 같은 결과를 얻을 수 있습니다.

>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
>>> print('Jack: {Jack:d}; Sjoerd: {Sjoerd:d}; Dcab: {Dcab:d}'.format(**table))
Jack: 4098; Sjoerd: 4127; Dcab: 8637678

이 방법은 모든 지역 변수들을 담은 딕셔너리를 돌려주는 내장 함수 vars() 와 함께 사용할 때 특히 쓸모가 있습니다.

예를 들어, 다음 줄은 정수와 그 제곱과 세제곱을 제공하는 빽빽하게 정렬된 열 집합을 생성합니다:

>>> for x in range(1, 11):
...     print('{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x))
...
 1   1    1
 2   4    8
 3   9   27
 4  16   64
 5  25  125
 6  36  216
 7  49  343
 8  64  512
 9  81  729
10 100 1000

str.format() 를 사용한 문자열 포매팅의 완전한 개요는 포맷 문자열 문법 을 보세요.

7.1.3. 수동 문자열 포매팅

여기 같은 제곱수와 세제곱수 표를 수동으로 포매팅했습니다:

>>> for x in range(1, 11):
...     print(repr(x).rjust(2), repr(x*x).rjust(3), end=' ')
...     # Note use of 'end' on previous line
...     print(repr(x*x*x).rjust(4))
...
 1   1    1
 2   4    8
 3   9   27
 4  16   64
 5  25  125
 6  36  216
 7  49  343
 8  64  512
 9  81  729
10 100 1000

(print() 의 동작 방식으로 인해 각 칼럼 사이에 스페이스 하나가 추가되었음에 유의하세요: 항상 인자들 사이에 스페이스를 추가합니다.)

문자열 객체의 str.rjust() 메서드는 왼쪽에 스페이스를 채워서 주어진 폭으로 문자열을 우측 줄 맞춤합니다. 비슷한 메서드 str.ljust() 와 str.center() 도 있습니다. 이 메서드들은 어떤 것도 출력하지 않습니다, 단지 새 문자열을 돌려줍니다. 입력 문자열이 너무 길면, 자르지 않고, 변경 없이 그냥 돌려줍니다; 이것이 열 배치를 엉망으로 만들겠지만, 보통 값에 대해 거짓말을 하게 될 대안보다는 낫습니다. (정말로 잘라내기를 원한다면, 항상 슬라이스 연산을 추가할 수 있습니다, x.ljust(n)[:n] 처럼.)

다른 메서드도 있습니다, str.zfill(). 숫자 문자열의 왼쪽에 0을 채웁니다. 플러스와 마이너스 부호도 이해합니다:

>>> '12'.zfill(5)
'00012'
>>> '-3.14'.zfill(7)
'-003.14'
>>> '3.14159265359'.zfill(5)
'3.14159265359'

7.1.4. 예전의 문자열 포매팅

The % operator (modulo) can also be used for string formatting. Given 'string' % values, instances of % in string are replaced with zero or more elements of values. This operation is commonly known as string interpolation. For example:

>>> import math
>>> print('The value of pi is approximately %5.3f.' % math.pi)
The value of pi is approximately 3.142.

더 자세한 내용은 printf 스타일 문자열 포매팅 섹션에 나옵니다.

7.2. 파일을 읽고 쓰기

open() 은 파일 객체 를 돌려주고, 두 개의 인자를 주는 방식이 가장 많이 사용됩니다: open(filename, mode).

>>> f = open('workfile', 'w')

첫 번째 인자는 파일 이름을 담은 문자열입니다. 두 번째 인자는 파일이 사용될 방식을 설명하는 몇 개의 문자들을 담은 또 하나의 문자열입니다. mode 는 파일을 읽기만 하면 'r', 쓰기만 하면 'w' (같은 이름의 이미 존재하는 파일은 삭제됩니다) 가 되고, 'a' 는 파일을 덧붙이기 위해 엽니다; 파일에 기록되는 모든 데이터는 자동으로 끝에 붙습니다. 'r+' 는 파일을 읽고 쓰기 위해 엽니다. mode 인자는 선택적인데, 생략하면 'r' 이 가정됩니다.

보통, 파일은 텍스트 모드 (text mode) 로 열리는데, 이 뜻은, 파일에 문자열을 읽고 쓰고, 파일에는 특정한 인코딩으로 저장된다는 것입니다. 인코딩이 지정되지 않으면 기본값은 플랫폼 의존적입니다 (open() 을 보세요). mode 에 덧붙여진 'b' 는 파일을 바이너리 모드 (binary mode) 로 엽니다: 이제 데이터는 바이트열 객체의 형태로 읽고 쓰입니다. 텍스트를 포함하지 않는 모든 파일에는 이 모드를 사용해야 합니다.

텍스트 모드에서, 읽을 때의 기본 동작은 플랫폼 의존적인 줄 종료 (유닉스에서 \n, 윈도우에서 \r\n) 를 단지 \n 로 변경하는 것입니다. 텍스트 모드로 쓸 때, 기본 동작은 \n 를 다시 플랫폼 의존적인 줄 종료로 변환하는 것입니다. 이 파일 데이터에 대한 무대 뒤의 수정은 텍스트 파일의 경우는 문제가 안 되지만, JPEG 이나 EXE 파일과 같은 바이너리 데이터를 망치게 됩니다. 그런 파일을 읽고 쓸 때 바이너리 모드를 사용하도록 주의하세요.

파일 객체를 다룰 때 with 키워드를 사용하는 것은 좋은 습관입니다. 혜택은 도중 예외가 발생하더라도 스위트가 종료될 때 파일이 올바르게 닫힌다는 것입니다. with 를 사용하는 것은 동등한 try-finally 블록을 쓰는 것에 비교해 훨씬 짧기도 합니다:

>>> with open('workfile') as f:
...     read_data = f.read()
>>> f.closed
True

with 키워드를 사용하지 않으면, f.close() 를 호출해서 파일을 닫고 사용된 시스템 자원을 즉시 반납해야 합니다. 명시적으로 파일을 닫지 않으면, 파이썬의 가비지 수거기가 결국에는 객체를 파괴하고 여러분을 대신해서 파일을 닫게 되지만, 파일이 한동안 열린 상태로 남아있게 됩니다. 또 다른 위험은 다른 파이썬 구현들은 이 뒷정리를 서로 다른 시점에 수행한다는 것입니다.

파일 객체가 닫힌 후에는, with 문이나 f.close() 를 호출하는 경우 모두, 파일 객체를 사용하려는 시도는 자동으로 실패합니다.

>>> f.close()
>>> f.read()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: I/O operation on closed file.

7.2.1. 파일 객체의 매소드

이 섹션의 나머지 예들은 f 라는 파일 객체가 이미 만들어졌다고 가정합니다.

To read a file’s contents, call f.read(size), which reads some quantity of data and returns it as a string (in text mode) or bytes object (in binary mode). size is an optional numeric argument. When size is omitted or negative, the entire contents of the file will be read and returned; it’s your problem if the file is twice as large as your machine’s memory. Otherwise, at most size characters (in text mode) or size bytes (in binary mode) are read and returned. If the end of the file has been reached, f.read() will return an empty string ('').

>>> f.read()
'This is the entire file.\n'
>>> f.read()
''

f.readline() 은 파일에서 한 줄을 읽습니다; 개행 문자 (\n) 는 문자열의 끝에 보존되고, 파일이 개행문자로 끝나지 않는 때에만 파일의 마지막 줄에서만 생략됩니다. 이렇게 반환 값을 모호하지 않게 만듭니다; f.readline() 가 빈 문자열을 돌려주면, 파일의 끝에 도달한 것이지만, 빈 줄은 '\n', 즉 하나의 개행문자만을 포함하는 문자열로 표현됩니다.

>>> f.readline()
'This is the first line of the file.\n'
>>> f.readline()
'Second line of the file\n'
>>> f.readline()
''

파일에서 줄들을 읽으려면, 파일 객체에 대해 루핑할 수 있습니다. 이것은 메모리 효율적이고, 빠르며 간단한 코드로 이어집니다:

>>> for line in f:
...     print(line, end='')
...
This is the first line of the file.
Second line of the file

파일의 모든 줄을 리스트로 읽어 들이려면 list(f) 나 f.readlines() 를 쓸 수 있습니다.

f.write(string) 은 string 의 내용을 파일에 쓰고, 출력된 문자들의 개수를 돌려줍니다.

>>> f.write('This is a test\n')
15

다른 형의 객체들은 쓰기 전에 변환될 필요가 있습니다 – 문자열 (텍스트 모드에서) 이나 바이트열 객체 (바이너리 모드에서) 로 –:

>>> value = ('the answer', 42)
>>> s = str(value)  # convert the tuple to string
>>> f.write(s)
18

f.tell() 은 파일의 현재 위치를 가리키는 정수를 돌려주는데, 바이너리 모드의 경우 파일의 처음부터의 바이트 수로 표현되고 텍스트 모드의 경우는 불투명한 숫자입니다.

To change the file object’s position, use f.seek(offset, whence). The position is computed from adding offset to a reference point; the reference point is selected by the whence argument. A whence value of 0 measures from the beginning of the file, 1 uses the current file position, and 2 uses the end of the file as the reference point. whence can be omitted and defaults to 0, using the beginning of the file as the reference point.

>>> f = open('workfile', 'rb+')
>>> f.write(b'0123456789abcdef')
16
>>> f.seek(5)      # Go to the 6th byte in the file
5
>>> f.read(1)
b'5'
>>> f.seek(-3, 2)  # Go to the 3rd byte before the end
13
>>> f.read(1)
b'd'

텍스트 파일에서는 (모드 문자열에 b 가 없이 열린 것들), 파일의 시작에 상대적인 위치 변경만 허락되고 (예외는 seek(0, 2) 를 사용해서 파일의 끝으로 위치를 변경하는 경우입니다), 올바른 offset 값은 f.tell() 이 돌려준 값과 0뿐입니다. 그 밖의 다른 offset 값은 정의되지 않은 결과를 낳습니다.

파일 객체는 isatty() 나 truncate() 같은 몇 가지 메서드를 더 갖고 있는데, 덜 자주 사용됩니다; 파일 객체에 대한 완전한 안내는 라이브러리 레퍼런스를 참조하세요.

7.2.2. json 으로 구조적인 데이터를 저장하기

문자열은 파일에 쉽게 읽고 쓸 수 있습니다. 숫자는 약간의 수고를 해야 하는데, read() 메서드가 문자열만을 돌려주기 때문입니다. 이 문자열을 int() 같은 함수로 전달해야만 하는데, '123' 같은 문자열을 받고 숫자 값 123을 돌려줍니다. 중첩된 리스트나 딕셔너리 같은 더 복잡한 데이터를 저장하려고 할 때, 수작업으로 파싱하고 직렬화하는 것이 까다로울 수 있습니다.

사용자가 반복적으로 복잡한 데이터형을 파일에 저장하는 코드를 작성하고 디버깅하도록 하는 대신, 파이썬은 JSON (JavaScript Object Notation) [http://json.org] 이라는 널리 쓰이는 데이터 교환 형식을 사용할 수 있게 합니다. json 이라는 표준 모듈은 파이썬 데이터 계층을 받아서 문자열 표현으로 바꿔줍니다; 이 절차를 직렬화 (serializing) 라고 부릅니다. 문자열 표현으로부터 데이터를 재구성하는 것은 역 직렬화 (deserializing) 라고 부릅니다. 직렬화와 역 직렬화 사이에서, 객체를 표현하는 문자열은 파일이나 데이터에 저장되거나 네트워크 연결을 통해 원격 기계로 전송될 수 있습니다.

참고

JSON 형식은 데이터 교환을 위해 현대 응용 프로그램들이 자주 사용합니다. 많은 프로그래머가 이미 이것에 익숙하므로, 연동성을 위한 좋은 선택이 됩니다.

객체 x 가 있을 때, 간단한 한 줄의 코드로 그것의 JSON 문자열 표현을 볼 수 있습니다:

>>> import json
>>> json.dumps([1, 'simple', 'list'])
'[1, "simple", "list"]'

dump()라는 dumps() 함수의 변종은 객체를 텍스트 파일 로 직렬화합니다. 그래서 f 가 쓰기를 위해 열린 텍스트 파일 이면, 이렇게 할 수 있습니다:

json.dump(x, f)

객체를 다시 디코드하려면, f 가 읽기를 위해 열린 텍스트 파일 객체일 때:

x = json.load(f)

이 간단한 직렬화 테크닉이 리스트와 딕셔너리를 다룰 수 있지만, 임의의 클래스 인스턴스를 JSON 으로 직렬화하기 위해서는 약간의 수고가 더 필요합니다. json 모듈의 레퍼런스는 이 방법에 대한 설명을 담고 있습니다.

더 보기

pickle - 피클 모듈

JSON 에 반해, pickle 은 임의의 복잡한 파이썬 객체들을 직렬화할 수 있는 프로토콜입니다. 파이썬에 국한되고 다른 언어로 작성된 응용 프로그램들과 통신하는데 사용될 수 없습니다. 기본적으로 안전하지 않기도 합니다: 믿을 수 없는 소스에서 온 데이터를 역 직렬화할 때, 숙련된 공격자에 의해 데이터가 조작되었다면 임의의 코드가 실행될 수 있습니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 자습서 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 자습서 »

|

8. 에러와 예외

지금까지 에러 메시지가 언급되지는 않았지만, 예제들을 직접 해보았다면 아마도 몇몇 개를 보았을 것입니다. (적어도) 두 가지 구별되는 에러들이 있습니다; 문법 에러 와 예외.

8.1. 문법 에러

문법 에러는, 파싱 에러라고도 알려져 있습니다, 아마도 여러분이 파이썬을 배우고 있는 동안에는 가장 자주 만나는 종류의 불평일 것입니다:

>>> while True print('Hello world')
  File "<stdin>", line 1
    while True print('Hello world')
                   ^
SyntaxError: invalid syntax

파서는 문제가 되는 줄을 다시 보여주고 줄에서 에러가 감지된 가장 앞의 위치를 가리키는 작은 ‘화살표’를 표시합니다. 에러는 화살표 앞에 오는 토큰이 원인입니다 (또는 적어도 그곳에서 감지되었습니다): 이 예에서, 에러는 함수 print() 에서 감지되었는데, 그 앞에 콜론 (':') 이 빠져있기 때문입니다. 파일 이름과 줄 번호가 인쇄되어서, 입력이 스크립트로부터 올 때 찾을 수 있도록 합니다.

8.2. 예외

문장이나 표현식이 문법적으로 올바르다 할지라도, 실행하려고 하면 에러를 일으킬 수 있습니다. 실행 중에 감지되는 에러들을 예외 라고 부르고 무조건 치명적이지는 않습니다: 파이썬 프로그램에서 이것들을 어떻게 다루는지 곧 배우게 됩니다. 하지만 대부분의 예외는 프로그램이 처리하지 않아서, 여기에서 볼 수 있듯이 에러 메시지를 만듭니다:

>>> 10 * (1/0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero
>>> 4 + spam*3
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'spam' is not defined
>>> '2' + 2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Can't convert 'int' object to str implicitly

에러 메시지의 마지막 줄은 어떤 일이 일어났는지 알려줍니다. 예외는 여러 형으로 나타나고, 형이 메시지 일부로 인쇄됩니다: 이 예에서의 형은 ZeroDivisionError, NameError, TypeError 입니다. 예외 형으로 인쇄된 문자열은 발생한 내장 예외의 이름입니다. 이것은 모든 내장 예외들의 경우는 항상 참이지만, 사용자 정의 예외의 경우는 (편리한 관례임에도 불구하고) 꼭 그럴 필요는 없습니다. 표준 예외 이름은 내장 식별자입니다 (예약 키워드가 아닙니다).

줄의 나머지 부분은 예외의 형과 원인에 기반을 둔 상세 명세를 제공합니다.

에러 메시지의 앞부분은 스택 트레이스의 형태로 예외가 일어난 위치의 문맥을 보여줍니다. 일반적으로 소스의 줄들을 나열하는 스택 트레이스를 포함하고 있습니다; 하지만, 표준 입력에서 읽어 들인 줄들은 표시하지 않습니다.

내장 예외 는 내장 예외들과 그 들의 의미를 나열하고 있습니다.

8.3. 예외 처리하기

선택한 예외를 처리하는 프로그램을 만드는 것이 가능합니다. 다음 예를 보면, 올바를 정수가 입력될 때까지 사용자에게 입력을 요청하지만, 사용자가 프로그램을 인터럽트 하는 것을 허용합니다 (Control-C 나 그 외에 운영 체제가 지원하는 것을 사용해서); 사용자가 만든 인터럽트는 KeyboardInterrupt 예외를 일으키는 형태로 나타남에 유의하세요.

>>> while True:
...     try:
...         x = int(input("Please enter a number: "))
...         break
...     except ValueError:
...         print("Oops!  That was no valid number.  Try again...")
...

try 문은 다음과 같이 동작합니다.

먼저, try 절 (try 와 except 사이의 문장들) 이 실행됩니다.

예외가 발생하지 않으면, except 절 을 건너뛰고 try 문의 실행은 종료됩니다.

try 절을 실행하는 동안 예외가 발생하면, 절의 남은 부분들을 건너뜁니다. 그런 다음 형이 except 키워드 뒤에 오는 예외 이름과 매치되면, 그 except 절이 실행되고, 그런 다음 실행은 try 문 뒤로 이어집니다.

except 절에 있는 예외 이름들과 매치되지 않는 예외가 발생하면, 외부에 있는 try 문으로 전달됩니다; 처리기가 발견되지 않으면, 처리되지 않은 예외 이고 위에서 보인 것과 같은 메시지를 출력하면서 실행이 멈춥니다.

각기 다른 예외에 대한 처리기를 지정하기 위해, try 문은 하나 이상의 except 절을 가질 수 있습니다. 최대 하나의 처리기가 실행됩니다. 처리기는 해당하는 try 절에서 발생한 예외만 처리할 뿐 같은 try 문의 다른 처리기가 일으킨 예외를 처리하지는 않습니다. except 절은 괄호가 있는 튜플로 여러 개의 예외를 지정할 수 있습니다, 예를 들어:

... except (RuntimeError, TypeError, NameError):
...     pass

except 절에 있는 클래스는 예외와 같은 클래스이거나 베이스 클래스일 때 매치됩니다 (하지만 다른 방식으로는 매치되지 않습니다 — 자식 클래스를 나열한 except 절은 베이스 클래스와 매치되지 않습니다). 예를 들어, 다음과 같은 코드는 B, C, D를 그 순서대로 인쇄합니다:

class B(Exception):
    pass

class C(B):
    pass

class D(C):
    pass

for cls in [B, C, D]:
    try:
        raise cls()
    except D:
        print("D")
    except C:
        print("C")
    except B:
        print("B")

except 절이 뒤집히면 (except B 가 처음에 오도록), B, B, B를 인쇄하게 됨에 주의하세요 — 처음으로 매치되는 절이 실행됩니다.

마지막 except 절은 예외 이름을 생략할 수 있는데, 와일드카드 역할을 합니다. 이것을 사용할 때는 극도의 주의를 필요로 합니다. 이런 식으로 실제 프로그래밍 에러를 가리기 쉽기 때문입니다! 에러 메시지를 인쇄한 후에 예외를 다시 일으키는데 사용될 수도 있습니다 (호출자도 예외를 처리할 수 있도록):

import sys

try:
    f = open('myfile.txt')
    s = f.readline()
    i = int(s.strip())
except OSError as err:
    print("OS error: {0}".format(err))
except ValueError:
    print("Could not convert data to an integer.")
except:
    print("Unexpected error:", sys.exc_info()[0])
    raise

try … except 문은 선택적인 else 절 을 갖는데, 있다면 모든 except 절 뒤에와야 합니다. try 절이 예외를 일으키지 않을 때 실행되어야만 하는 코드에 유용합니다. 예를 들어:

for arg in sys.argv[1:]:
    try:
        f = open(arg, 'r')
    except OSError:
        print('cannot open', arg)
    else:
        print(arg, 'has', len(f.readlines()), 'lines')
        f.close()

else 절의 사용이 try 절에 코드를 추가하는 것보다 좋은데, try … except 문에 의해 보호되고 있는 코드가 일으키지 않은 예외를 우연히 잡게 되는 것을 방지하기 때문입니다.

예외가 발생할 때, 연관된 값을 가질 수 있는데, 예외의 인자 라고도 알려져 있습니다. 인자의 존재와 형은 예외 형에 의존적입니다.

except 절은 예외 이름 뒤에 변수를 지정할 수 있습니다. 변수는 인자들이 instance.args 에 저장된 예외 인스턴스에 연결됩니다. 편의를 위해, 예외 인스턴스는 __str__() 를 정의해서, .args 를 참조하지 않고도 인자들을 직접 인쇄할 수 있습니다. 예외를 일으키기 전에 인스턴스를 먼저 만들고 필요한 어트리뷰트들을 추가할 수도 있습니다.

>>> try:
...     raise Exception('spam', 'eggs')
... except Exception as inst:
...     print(type(inst))    # the exception instance
...     print(inst.args)     # arguments stored in .args
...     print(inst)          # __str__ allows args to be printed directly,
...                          # but may be overridden in exception subclasses
...     x, y = inst.args     # unpack args
...     print('x =', x)
...     print('y =', y)
...
<class 'Exception'>
('spam', 'eggs')
('spam', 'eggs')
x = spam
y = eggs

예외가 인자를 가지면, 처리되지 않은 예외 메시지의 마지막 부분(‘상세 명세’)에 인쇄됩니다.

예외 처리기는 단지 try 절에 직접 등장하는 예외뿐만 아니라, try 절에서 (간접적으로라도) 호출되는 내부 함수들에서 발생하는 예외들도 처리합니다. 예를 들어:

>>> def this_fails():
...     x = 1/0
...
>>> try:
...     this_fails()
... except ZeroDivisionError as err:
...     print('Handling run-time error:', err)
...
Handling run-time error: division by zero

8.4. 예외 일으키기

raise 문은 프로그래머가 지정한 예외가 발생하도록 강제할 수 있게 합니다. 예를 들어:

>>> raise NameError('HiThere')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: HiThere

raise 에 제공하는 단일 인자는 발생시킬 예외를 가리킵니다. 예외 인스턴스이거나 예외 클래스 (Exception 를 계승하는 클래스) 이어야 합니다. 예외 클래스가 전달되면, 묵시적으로 인자 없이 생성자를 호출해서 인스턴스를 만듭니다:

raise ValueError  # shorthand for 'raise ValueError()'

만약 예외가 발생했는지는 알아야 하지만 처리하고 싶지는 않다면, 더 간단한 형태의 raise 문이 그 예외를 다시 일으킬 수 있게 합니다:

>>> try:
...     raise NameError('HiThere')
... except NameError:
...     print('An exception flew by!')
...     raise
...
An exception flew by!
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
NameError: HiThere

8.5. 사용자 정의 예외

새 예외 클래스를 만듦으로써 프로그램은 자신의 예외에 이름을 붙일 수 있습니다 (파이썬 클래스에 대한 자세한 내용은 클래스 를 보세요). 예외는 보통 직접적으로나 간접적으로 Exception 클래스를 계승합니다.

예외 클래스는 다른 클래스들이 할 수 있는 어떤 것도 가능하도록 정의될 수 있지만, 보통은 간단하게 유지합니다. 종종 예외 처리기가 에러에 관한 정보를 추출할 수 있도록 하기 위한 몇 가지 어트리뷰트들을 제공하기만 합니다. 여러 가지 서로 다른 에러들을 일으킬 수 있는 모듈을 만들 때, 흔히 사용되는 방식은 모듈에서 정의되는 예외들의 베이스 클래스를 정의한 후, 각기 다른 에러 조건마다 특정한 예외 클래스를 서브 클래스로 만드는 것입니다:

class Error(Exception):
    """Base class for exceptions in this module."""
    pass

class InputError(Error):
    """Exception raised for errors in the input.

    Attributes:
        expression -- input expression in which the error occurred
        message -- explanation of the error
    """

    def __init__(self, expression, message):
        self.expression = expression
        self.message = message

class TransitionError(Error):
    """Raised when an operation attempts a state transition that's not
    allowed.

    Attributes:
        previous -- state at beginning of transition
        next -- attempted new state
        message -- explanation of why the specific transition is not allowed
    """

    def __init__(self, previous, next, message):
        self.previous = previous
        self.next = next
        self.message = message

대부분의 예외는 표준 예외들의 이름들과 유사하게, “Error” 로 끝나는 이름으로 정의됩니다.

많은 표준 모듈들은 그들이 정의하는 함수들에서 발생할 수 있는 그 자신만의 예외들을 정의합니다. 클래스에 관한 더 자세한 정보는 클래스 장에서 다룹니다.

8.6. 뒷정리 동작 정의하기

try 문은 또 다른 선택적 절을 가질 수 있는데 모든 상황에 실행되어야만 하는 뒷정리 동작을 정의하는 데 사용됩니다. 예를 들어:

>>> try:
...     raise KeyboardInterrupt
... finally:
...     print('Goodbye, world!')
...
Goodbye, world!
KeyboardInterrupt
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>

If a finally clause is present, the finally clause will execute as the last task before the try statement completes. The finally clause runs whether or not the try statement produces an exception. The following points discuss more complex cases when an exception occurs:

If an exception occurs during execution of the try clause, the exception may be handled by an except clause. If the exception is not handled by an except clause, the exception is re-raised after the finally clause has been executed.

An exception could occur during execution of an except or else clause. Again, the exception is re-raised after the finally clause has been executed.

If the try statement reaches a break, continue or return statement, the finally clause will execute just prior to the break, continue or return statement’s execution.

If a finally clause includes a return statement, the returned value will be the one from the finally clause’s return statement, not the value from the try clause’s return statement.

For example:

>>> def bool_return():
...     try:
...         return True
...     finally:
...         return False
...
>>> bool_return()
False

A more complicated example:

>>> def divide(x, y):
...     try:
...         result = x / y
...     except ZeroDivisionError:
...         print("division by zero!")
...     else:
...         print("result is", result)
...     finally:
...         print("executing finally clause")
...
>>> divide(2, 1)
result is 2.0
executing finally clause
>>> divide(2, 0)
division by zero!
executing finally clause
>>> divide("2", "1")
executing finally clause
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in divide
TypeError: unsupported operand type(s) for /: 'str' and 'str'

보인 바와 같이, finally 절은 모든 경우에 실행됩니다. 두 문자열을 나눠서 발생한 TypeError 는 except 절에 의해 처리되지 않고 finally 절이 실행된 후에 다시 일어납니다.

실제 세상의 응용 프로그램에서, finally 절은 외부 자원을 사용할 때, 성공적인지 아닌지와 관계없이, 그 자원을 반납하는 데 유용합니다 (파일이나 네트워크 연결 같은 것들).

8.7. 미리 정의된 뒷정리 동작들

어떤 객체들은 객체가 더 필요 없을 때 개입하는 표준 뒷정리 동작을 정의합니다. 그 객체를 사용하는 연산의 성공 여부와 관계없습니다. 파일을 열고 그 내용을 화면에 인쇄하려고 하는 다음 예를 보세요.

for line in open("myfile.txt"):
    print(line, end="")

이 코드의 문제점은 이 부분이 실행을 끝낸 뒤에도 예측할 수 없는 기간 동안 파일을 열린 채로 둔다는 것입니다. 간단한 스크립트에서는 문제가 되지 않지만, 큰 응용 프로그램에서는 문제가 될 수 있습니다. with 문은 파일과 같은 객체들이 즉시 올바르게 뒷정리 되도록 보장하는 방법을 제공합니다.

with open("myfile.txt") as f:
    for line in f:
        print(line, end="")

문장이 실행된 후에, 줄을 처리하는 데 문제가 발생하더라도, 파일 f 는 항상 닫힙니다. 파일과 같이, 미리 정의된 뒷정리 동작들을 제공하는 객체들은 그들의 설명서에서 이 사실을 설명합니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 자습서 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 자습서 »

|

9. 클래스

클래스는 데이터와 기능을 함께 묶는 방법을 제공합니다. 새 클래스를 만드는 것은 객체의 새 형 을 만들어서, 그 형의 새 인스턴스 를 만들 수 있도록 합니다. 각 클래스 인스턴스는 상태를 유지하기 위해 그 자신에게 첨부된 어트리뷰트를 가질 수 있습니다. 클래스 인스턴스는 상태를 바꾸기 위한 (클래스에 의해 정의된) 메서드도 가질 수 있습니다.

다른 프로그래밍 언어들과 비교할 때, 파이썬의 클래스 메커니즘은 최소한의 새로운 문법과 개념을 써서 클래스를 추가합니다. C++ 과 모듈라-3 에서 발견되는 클래스 메커니즘을 혼합합니다. 파이썬 클래스는 객체 지향형 프로그래밍의 모든 표준 기능들을 제공합니다: 클래스 상속 메커니즘은 다중 베이스 클래스를 허락하고, 자식 클래스는 베이스 클래스나 클래스들의 어떤 메서드도 재정의할 수 있으며, 메서드는 같은 이름의 베이스 클래스의 메서드를 호출할 수 있습니다. 객체들은 임의의 종류의 데이터를 양적 제한 없이 가질 수 있습니다. 모듈과 마찬가지로, 클래스는 파이썬의 동적인 본성을 함께 나눕니다: 실행 시간에 만들어지고, 만들어진 후에도 더 수정될 수 있습니다.

C++ 용어로, 보통 클래스 멤버들은 (데이터 멤버를 포함해서) public (예외는 아래 비공개 변수 를 보세요) 하고, 모든 맴버 함수들은 virtual 입니다. 모듈라-3처럼, 객체의 매소드에서 그 객체의 멤버를 참조하는 줄임 표현은 없습니다: 메서드 함수는 그 객체를 표현하는 명시적인 첫 번째 인자를 선언하는데, 함수 호출 때 묵시적으로 제공됩니다. 스몰토크처럼, 클래스 자신도 객체입니다. 이것이 임포팅과 이름 변경을 위한 개념을 제공합니다. C++ 나 모듈라-3 와는 달리, 내장형도 사용자가 확장하기 위해 베이스 클래스로 사용할 수 있습니다. 또한, C++ 처럼, 특별한 문법을 갖는 대부분의 내장 연산자들은 (산술 연산자, 서브스크립팅, 등등) 클래스 인스턴스에 대해 새로 정의될 수 있습니다.

(클래스에 대해 보편적으로 받아들여지는 용어들이 없는 상태에서, 이따금 스몰토크나 C++ 용어들을 사용할 것입니다. C++ 보다 객체 지향적 개념들이 파이썬의 것과 더 가까우므로 모듈라-3 용어를 사용할 수도 있지만, 들어본 독자들이 별로 없을 것으로 예상합니다.)

9.1. 이름과 객체에 관한 한마디

객체는 개체성(individuality)을 갖고, 여러 개의 이름이 (여러 개의 스코프에서) 같은 객체에 연결될 수 있습니다. 이것은 다른 언어들에서는 에일리어싱(aliasing) 이라고 알려져 있습니다. 보통 파이썬을 처음 볼 때 이 점을 높이 평가하지는 않고, 불변 기본형들 (숫자, 문자열, 튜플)을 다루는 동안은 안전하게 무시할 수 있습니다. 하지만, 에일리어싱는 리스트, 딕셔너리나 그 밖의 다른 가변 객체들을 수반하는 파이썬 코드의 의미에 극적인 효과를 줄 수 있습니다. 이것은 보통 프로그램에 혜택이 되는데, 에일리어스는 어떤 면에서 포인터처럼 동작하기 때문입니다. 예를 들어, 구현이 포인터만 전달하기 때문에, 객체를 전달하는 비용이 적게 듭니다; 그리고 함수가 인자로 전달된 객체를 수정하면, 호출자는 그 변경을 보게 됩니다 — 이것은 파스칼에서 사용되는 두 가지 서로 다른 인자 전달 메커니즘의 필요를 제거합니다.

9.2. 파이썬 스코프와 이름 공간

클래스를 소개하기 전에, 파이썬의 스코프 규칙에 대해 몇 가지 말할 것이 있습니다. 클래스 정의는 이름 공간으로 깔끔한 요령을 부리고, 여러분은 무엇이 일어나는지 완전히 이해하기 위해 스코프와 이름 공간이 어떻게 동작하는지 알 필요가 있습니다. 덧붙여 말하자면, 이 주제에 대한 지식은 모든 고급 파이썬 프로그래머에게 쓸모가 있습니다.

몇 가지 정의로 시작합시다.

이름 공간 은 이름에서 객체로 가는 매핑입니다. 대부분의 이름 공간은 현재 파이썬 딕셔너리로 구현되어 있지만, 보통 다른 식으로는 알아차릴 수 없고 (성능은 예외입니다), 앞으로는 바뀔 수 있습니다. 이름 공간의 예는: 내장 이름들의 집합 (abs() 와 같은 함수들과 내장 예외 이름들을 포함합니다); 모듈의 전역 이름들; 함수 호출에서의 지역 이름들. 어떤 의미에서 객체의 어트리뷰트 집합도 이름 공간을 형성합니다. 이름 공간에 대해 알아야 할 중요한 것은 서로 다른 이름 공간들의 이름 간에는 아무런 관계가 없다는 것입니다; 예를 들어, 두 개의 서로 다른 모듈들은 모두 혼동 없이 함수 maximize 를 정의할 수 있습니다 — 모듈의 사용자들은 모듈 이름을 앞에 붙여야 합니다.

그런데, 저는 어트리뷰트 라는 단어를 점 뒤에 오는 모든 이름에 사용합니다 — 예를 들어, 표현식 z.real 에서, real 는 객체 z 의 어트리뷰트입니다. 엄밀하게 말해서, 모듈에 있는 이름들에 대한 참조는 어트리뷰트 참조입니다: 표현식 modname.funcname 에서, modname 은 모듈 객체고 funcname 는 그것의 어트리뷰트입니다. 이 경우에는 우연히도 모듈의 어트리뷰트와 모듈에서 정의된 전역 이름 간에 직접적인 매핑이 생깁니다: 같은 이름 공간을 공유합니다! 1

어트리뷰트는 읽기 전용 이거나 쓰기 가능할 수 있습니다. 후자의 경우, 어트리뷰트에 대한 대입이 가능합니다. 모듈 어트리뷰트는 쓰기 가능합니다: modname.the_answer = 42 라고 쓸 수 있습니다. 쓰기 가능한 어트리뷰트는 del 문으로 삭제할 수도 있습니다. 예를 들어, del modname.the_answer 는 modname 라는 이름의 객체에서 어트리뷰트 the_answer 를 제거합니다.

이름 공간들은 서로 다른 순간에 만들어지고 서로 다른 수명을 갖습니다. 내장 이름들을 담는 이름 공간은 파이썬 인터프리터가 시작할 때 만들어지고 영원히 지워지지 않습니다. 모듈의 전역 이름 공간은 모듈 정의를 읽는 동안 만들어집니다; 보통, 모듈 이름 공간은 인터프리터가 끝날 때까지 남습니다. 인터프리터의 최상위 호출 때문에 실행되는, 스크립트 파일이나 대화형으로 읽히는, 문장들은 __main__ 이라고 불리는 모듈 일부로 여겨져서 그 들 자신의 이름 공간을 갖습니다. (내장 이름들 또한 모듈에 속하는데; 이것을 builtins 라 부릅니다.)

함수의 지역 이름 공간은 함수가 호출될 때 만들어지고, 함수가 복귀하거나 함수 내에서 처리되지 않는 예외를 일으킬 때 삭제됩니다. (사실, 잊어버린다는 것이 실제로 일어나는 일에 대한 더 좋은 설명입니다.) 물론, 재귀적 호출은 각각 자기 자신만의 지역 이름 공간을 갖습니다.

스코프 는 이름 공간을 직접 액세스할 수 있는 파이썬 프로그램의 텍스트 적인 영역입니다. 여기에서 “직접 액세스 가능한” 이란 이름에 대한 정규화되지 않은 참조가 그 이름 공간에서 이름을 찾으려고 시도한다는 의미입니다.

스코프가 정적으로 결정됨에도 불구하고, 동적으로 사용됩니다. 실행 중 어느 시점에서건, 이름 공간을 직접 액세스 가능한, 적어도 세 개의 중첩된 스코프가 있습니다:

가장 먼저 검색되는, 가장 내부의 스코프는 지역 이름들을 포함합니다

둘러싸고 있는 함수들의 스코프는, 가장 가까이서 둘러싸는 스코프로부터 검색이 시작됩니다, 비 지역(non-local) 이지만 비 전역(non-global) 이름들을 포함합니다

마지막 직전의 스코프는 현재 모듈의 전역 이름들을 포함합니다

(가장 나중에 검색되는) 가장 외부의 스코프는 내장 이름들을 포함하고 있는 이름 공간입니다.

이름을 global로 선언하면, 모든 참조와 대입은 모듈의 전역 이름들을 포함하는 중간 스코프로 바로 갑니다. 가장 내부의 스코프 바깥에서 발견되는 변수들을 재연결하려면, nonlocal 키워드를 사용할 수 있습니다; nonlocal 로 선언되지 않으면, 그 변수들은 읽기 전용입니다 (그런 변수에 쓰려고 하면 단순히 가장 내부의 스코프에 새 지역 변수를 만들게 되어, 같은 이름의 바깥 변수를 바꾸지 않고 남겨둡니다).

보통, 지역 스코프는 현재 함수의 지역 이름들을 (텍스트 적으로) 참조합니다. 함수 바깥에서, 지역 스코프는 전역 스코프와 같은 이름 공간을 참조합니다: 모듈의 이름 공간. 클래스 정의들은 지역 스코프에 또 하나의 이름 공간을 배치합니다.

스코프가 텍스트 적으로 결정된다는 것을 깨닫는 것은 중요합니다: 모듈에서 정의된 함수의 전역 스코프는, 어디에서 어떤 에일리어스를 통해 그 함수가 호출되는지에 관계없이, 그 모듈의 이름 공간입니다. 반면에, 이름을 실제로 검색하는 것은 실행시간에 동적으로 수행됩니다 — 하지만, 언어 정의는 컴파일 시점의 정적인 이름 결정을 향해 진화하고 있어서, 동적인 이름 결정에 의존하지 말아야 합니다! (사실, 지역 변수들은 이미 정적으로 결정됩니다.)

A special quirk of Python is that – if no global or nonlocal statement is in effect – assignments to names always go into the innermost scope. Assignments do not copy data — they just bind names to objects. The same is true for deletions: the statement del x removes the binding of x from the namespace referenced by the local scope. In fact, all operations that introduce new names use the local scope: in particular, import statements and function definitions bind the module or function name in the local scope.

global 문은 특정 변수가 전역 스코프에 있으며 그곳에 재연결되어야 함을 가리킬 때 사용될 수 있습니다; nonlocal 문은 특정 변수가 둘러싸는 스코프에 있으며 그곳에 재연결되어야 함을 가리킵니다.

9.2.1. 스코프와 이름 공간 예

이것은 어떻게 서로 다른 스코프와 이름 공간을 참조하고, global 과 nonlocal 이 변수 연결에 어떤 영향을 주는지를 보여주는 예입니다:

def scope_test():
    def do_local():
        spam = "local spam"

    def do_nonlocal():
        nonlocal spam
        spam = "nonlocal spam"

    def do_global():
        global spam
        spam = "global spam"

    spam = "test spam"
    do_local()
    print("After local assignment:", spam)
    do_nonlocal()
    print("After nonlocal assignment:", spam)
    do_global()
    print("After global assignment:", spam)

scope_test()
print("In global scope:", spam)

예제 코드의 출력은 이렇게 됩니다:

After local assignment: test spam
After nonlocal assignment: nonlocal spam
After global assignment: nonlocal spam
In global scope: global spam

어떻게 지역 대입이 (이것이 기본입니다) scope_test 의 spam 연결을 바꾸지 않는지에 유의하세요. nonlocal 대입은 scope_test 의 spam 연결을 바꾸고 global 대입은 모듈 수준의 연결을 바꿉니다.

global 대입 전에는 spam 의 연결이 없다는 것도 볼 수 있습니다.

9.3. 클래스와의 첫 만남

클래스는 약간의 새 문법과 세 개의 객체형과 몇 가지 새 개념들을 도입합니다.

9.3.1. 클래스 정의 문법

클래스 정의의 가장 간단한 형태는 이렇게 생겼습니다:

class ClassName:
    <statement-1>
    .
    .
    .
    <statement-N>

함수 정의(def 문)처럼, 클래스 정의는 어떤 효과가 생기기 위해서는 먼저 실행되어야 합니다. (상상컨대 클래스 정의를 if 문의 분기나 함수 내부에 놓을 수 있습니다)

실재적으로, 클래스 정의 내부의 문장들은 보통 함수 정의들이지만, 다른 문장들도 허락되고 때로 쓸모가 있습니다 — 나중에 이 주제로 돌아올 것입니다. 클래스 내부의 함수 정의는 보통, 메서드 호출 규약의 영향을 받은, 특별한 형태의 인자 목록을 갖습니다. — 다시, 이것은 뒤에서 설명됩니다.

클래스 정의에 진입할 때, 새 이름 공간이 만들어지고 지역 스코프로 사용됩니다 — 그래서, 모든 지역 변수들로의 대입은 이 새 이름 공간으로 갑니다. 특히, 함수 정의는 새 함수의 이름을 이곳에 연결합니다.

클래스 정의가 (끝을 통해) 정상적으로 끝날 때, 클래스 객체 가 만들어집니다. 이것은 기본적으로 클래스 정의 때문에 만들어진 이름 공간의 내용물들을 감싸는 싸개입니다; 다음 섹션에서 클래스 객체에 대해 더 배우게 됩니다. 원래의 지역 스코프가 (클래스 정의에 들어가기 직전에 유효하던 것) 다시 사용되고, 클래스 객체는 클래스 정의 헤더에서 주어진 클래스 이름 (예에서 ClassName) 으로 여기에 연결됩니다.

9.3.2. 클래스 객체

클래스 객체는 두 종류의 연산을 지원합니다: 어트리뷰트 참조와 인스턴스 만들기.

어트리뷰트 참조 는 파이썬의 모든 어트리뷰트 참조에 사용되는 표준 문법을 사용합니다: obj.name. 올바른 어트리뷰트 이름은 클래스 객체가 만들어질 때 클래스의 이름 공간에 있던 모든 이름입니다. 그래서, 클래스 정의가 이렇게 될 때:

class MyClass:
    """A simple example class"""
    i = 12345

    def f(self):
        return 'hello world'

MyClass.i 와 MyClass.f 는 올바른 어트리뷰트 참조고, 각기 정수와 함수 객체를 돌려줍니다. 클래스 어트리뷰트는 대입할 수도 있어서, 대입을 통해 MyClass.i 의 값을 변경할 수 있습니다. __doc__ 도 역시 올바른 어트리뷰트고, 클래스에 속하는 독스트링을 돌려줍니다: "A simple example class".

클래스 인스턴스 만들기 는 함수 표기법을 사용합니다. 클래스 객체가 클래스의 새 인스턴스를 돌려주는 매개변수 없는 함수인 체합니다. 예를 들어 (위의 클래스를 가정하면):

x = MyClass()

는 클래스의 새 인스턴스 를 만들고 이 객체를 지역 변수 x 에 대입합니다.

인스턴스 만들기 연산 (클래스 객체 “호출하기”) 은 빈 객체를 만듭니다. 많은 클래스는 특정한 초기 상태로 커스터마이즈된 인스턴스로 객체를 만드는 것을 좋아합니다. 그래서 클래스는 이런 식으로 __init__() 라는 이름의 특수 메서드 정의할 수 있습니다:

def __init__(self):
    self.data = []

클래스가 __init__() 메서드를 정의할 때, 클래스 인스턴스 만들기는 새로 만들어진 클래스 인스턴스에 대해 자동으로 __init__() 를 호출합니다. 그래서 이 예에서, 새 초기화된 인스턴스를 이렇게 얻을 수 있습니다:

x = MyClass()

물론, __init__() 메서드는 더 높은 유연성을 위해 인자들을 가질 수 있습니다. 그 경우, 클래스 인스턴스 만들기 연산자로 주어진 인자들은 __init__() 로 전달됩니다. 예를 들어,

>>> class Complex:
...     def __init__(self, realpart, imagpart):
...         self.r = realpart
...         self.i = imagpart
...
>>> x = Complex(3.0, -4.5)
>>> x.r, x.i
(3.0, -4.5)

9.3.3. 인스턴스 객체

Now what can we do with instance objects? The only operations understood by instance objects are attribute references. There are two kinds of valid attribute names: data attributes and methods.

데이터 어트리뷰트 는 스몰토크의 “인스턴스 변수” 에, C++ 의 “데이터 멤버” 에 해당합니다. 데이터 어트리뷰트는 선언될 필요 없습니다; 지역 변수처럼, 처음 대입될 때 태어납니다. 예를 들어, x 가 위에서 만들어진 MyClass 의 인스턴스면, 다음과 같은 코드 조각은 트레이스 없이 값 16 을 인쇄합니다:

x.counter = 1
while x.counter < 10:
    x.counter = x.counter * 2
print(x.counter)
del x.counter

다른 인스턴스 어트리뷰트 참조는 메서드 입니다. 메서드는 객체에 “속하는” 함수입니다. (파이썬에서, 메서드 라는 용어는 클래스 인스턴스에만 사용되지 않습니다; 다른 객체 형들도 메서드를 가질 수 있습니다. 예를 들어, 리스트 객체는 append, insert, remove, sort 등과 같은 메서드들을 갖습니다. 하지만, 앞으로의 논의에서, 명시적으로 언급하지 않는 한, 메서드 라는 용어를 클래스 인스턴스 객체의 메서드에만 사용할 것입니다.)

인스턴스 객체의 올바른 메서드 이름은 그것의 클래스에 달려있습니다. 정의상, 함수 객체인 클래스의 모든 어트리뷰트들은 상응하는 인스턴스의 메서드들을 정의합니다. 그래서 우리의 예제에서, x.f 는 올바른 메서드 참조인데, MyClass.f 가 함수이기 때문입니다. 하지만 x.i 는 그렇지 않은데, MyClass.i 가 함수가 아니기 때문입니다. 그러나, x.f 는 MyClass.f 와 같은 것이 아닙니다 — 이것은 함수 객체가 아니라 메서드 객체 입니다.

9.3.4. 메서드 객체

보통, 메서드는 연결되자마자 호출됩니다:

x.f()

MyClass 예에서, 이것은 문자열 'hello world' 를 돌려줍니다. 하지만, 메서드를 즉시 호출할 필요는 없습니다: x.f 는 메서드 객체고, 저장된 후에 호출될 수 있습니다. 예를 들어:

xf = x.f
while True:
    print(xf())

는 영원히 계속 hello world 를 인쇄합니다.

메서드가 호출될 때 정확히 어떤 일이 일어날까? f() 의 함수 정의가 인자를 지정했음에도 불구하고, 위에서 x.f() 는 인자 없이 호출된 것을 알아챘을 것입니다. 인자는 어떻게 된 걸까? 확실히 파이썬은 인자를 필요로 하는 함수를 인자 없이 호출하면 예외를 일으킵니다 – 인자가 실제로는 사용되지 않는다 해도…

실제로, 여러분은 답을 짐작할 수 있습니다: 메서드의 특별함은 인스턴스 객체가 함수의 첫 번째 인자로 전달된다는 것입니다. 우리 예에서, 호출 x.f()``은 정확히 ``MyClass.f(x) 와 동등합니다. 일반적으로, n 개의 인자들의 목록으로 메서드를 호출하는 것은, 첫 번째 인자 앞에 메서드의 인스턴스 객체를 삽입해서 만든 인자 목록으로 상응하는 함수를 호출하는 것과 동등합니다.

아직 메서드가 어떻게 동작하는지 이해하지 못했다면, 구현을 살펴보는 것이 아마도 문제를 분명하게 만들 수 있을 것입니다. 데이터 어트리뷰트가 아닌 인스턴스 어트리뷰트를 참조하면, 그것의 클래스가 검색됩니다. 만약 그 이름이 함수 객체인 올바른 클래스 어트리뷰트면, 인스턴스 객체와 방금 발견된 함수 객체를 (가리키는 포인터들을) 추상 객체에 함께 묶어서 메서드 객체를 만듭니다: 이것이 메서드 객체입니다. 메서드 객체가 인자 목록으로 호출되면, 인스턴스 객체와 인자 목록으로부터 새 인자 목록이 구성된 후, 함수 객체를 이 새 인자 목록으로 호출합니다.

9.3.5. 클래스와 인스턴스 변수

일반적으로 말해서, 인스턴스 변수는 인스턴스별 데이터를 위한 것이고 클래스 변수는 그 클래스의 모든 인스턴스에서 공유되는 어트리뷰트와 메서드를 위한 것입니다:

class Dog:

    kind = 'canine'         # class variable shared by all instances

    def __init__(self, name):
        self.name = name    # instance variable unique to each instance

>>> d = Dog('Fido')
>>> e = Dog('Buddy')
>>> d.kind                  # shared by all dogs
'canine'
>>> e.kind                  # shared by all dogs
'canine'
>>> d.name                  # unique to d
'Fido'
>>> e.name                  # unique to e
'Buddy'

이름과 객체에 관한 한마디 에서 논의했듯이, 리스트나 딕셔너리와 같은 가변 객체가 참여할 때 공유 데이터는 예상치 못한 효과를 줄 가능성이 있습니다. 예를 들어, 다음 코드에서 tricks 리스트는 클래스 변수로 사용되지 않아야 하는데, 하나의 리스트가 모든 Dog 인스턴스들에 공유되기 때문입니다.

class Dog:

    tricks = []             # mistaken use of a class variable

    def __init__(self, name):
        self.name = name

    def add_trick(self, trick):
        self.tricks.append(trick)

>>> d = Dog('Fido')
>>> e = Dog('Buddy')
>>> d.add_trick('roll over')
>>> e.add_trick('play dead')
>>> d.tricks                # unexpectedly shared by all dogs
['roll over', 'play dead']

대신, 클래스의 올바른 설계는 인스턴스 변수를 사용해야 합니다:

class Dog:

    def __init__(self, name):
        self.name = name
        self.tricks = []    # creates a new empty list for each dog

    def add_trick(self, trick):
        self.tricks.append(trick)

>>> d = Dog('Fido')
>>> e = Dog('Buddy')
>>> d.add_trick('roll over')
>>> e.add_trick('play dead')
>>> d.tricks
['roll over']
>>> e.tricks
['play dead']

9.4. 기타 주의사항들

데이터 어트리뷰트는 같은 이름의 메서드 어트리뷰트를 덮어씁니다; 의도하지 않은 이름 충돌(큰 프로그램에서 찾기 어려운 버그를 만듭니다)을 피하려면, 충돌의 기회를 최소화하는 어떤 종류의 규칙을 사용하는 것이 현명합니다. 가능한 규칙에는 메서드 이름을 대문자로 시작하는 것, 데이터 어트리뷰트의 이름에 작고 특별한 문자열 (아마도 밑줄 하나)을 앞에 붙이는 것, 메서드에는 동사를 데이터 어트리뷰트에는 명사를 쓰는 것들이 있습니다.

데이터 어트리뷰트는 메서드 뿐만 아니라 객체의 일반적인 사용자 (“클라이언트”)에 의해서 참조될 수도 있습니다. 달리 표현하면, 클래스는 순수하게 추상적인 데이터형을 구현하는데 사용될 수 없습니다. 사실, 파이썬에서는 데이터 은닉을 강제할 방법이 없습니다 — 모두 관례에 의존합니다. (반면에, C로 작성된 파이썬 구현은 필요하다면 구현 상세를 완전히 숨기고 객체에 대한 액세스를 제어할 수 있습니다; 이것은 C로 작성된 파이썬 확장에서 사용될 수 있습니다.)

클라이언트는 데이터 어트리뷰트를 조심스럽게 사용해야 합니다 — 클라이언트는 데이터 어트리뷰트를 건드려서 메서드들에 의해 유지되는 불변성 들을 망가뜨릴 수 있습니다. 클라이언트는 이름 충돌을 피하는 한 메서드들의 유효성을 손상하지 않고도 그들 자신의 데이터 어트리뷰트를 인스턴스 객체에 추가할 수도 있음에 유의하세요 — 다시 한번, 명명 규칙은 여러 골칫거리를 피할 수 있게 합니다.

메서드 안에서 데이터 어트리뷰트들(또는 다른 메서드들!)을 참조하는 줄임 표현은 없습니다. 저는 이것이 실제로 메서드의 가독성을 높인다는 것을 알게 되었습니다: 메서드를 훑어볼 때 지역 변수와 인스턴스 변수를 혼동할 우려가 없습니다.

종종, 메서드의 첫 번째 인자는 self 라고 불립니다. 이것은 관례일 뿐입니다: 이름 self 는 파이썬에서 아무런 특별한 의미를 갖지 않습니다. 하지만, 이 규칙을 따르지 않을 때 여러분의 코드가 다른 파이썬 프로그래머들이 읽기에 불편하고, 클래스 브라우저 프로그램도 이런 규칙에 의존하도록 작성되었다고 상상할 수 있음에 유의하세요.

클래스 어트리뷰트인 모든 함수는 그 클래스의 인스턴스들을 위한 메서드를 정의합니다. 함수 정의가 클래스 정의에 텍스트 적으로 둘러싸일 필요는 없습니다: 함수 객체를 클래스의 지역 변수로 대입하는 것 역시 가능합니다. 예를 들어:

# Function defined outside the class
def f1(self, x, y):
    return min(x, x+y)

class C:
    f = f1

    def g(self):
        return 'hello world'

    h = g

이제 f, g, h 는 모두 함수 객체를 가리키는 클래스 C 의 어트리뷰트고, 결과적으로 이것들은 모두 C 의 인스턴스들의 메서드입니다 — h 는 정확히 g 와 동등합니다. 이런 방식은 프로그램의 독자들에게 혼란을 주기만 한다는 점에 주의하세요.

메서드는 self 인자의 메서드 어트리뷰트를 사용해서 다른 메서드를 호출할 수 있습니다:

class Bag:
    def __init__(self):
        self.data = []

    def add(self, x):
        self.data.append(x)

    def addtwice(self, x):
        self.add(x)
        self.add(x)

메서드는 일반 함수들과 마찬가지로 전역 이름을 참조할 수 있습니다. 메서드에 결합한 전역 스코프는 그것의 정의를 포함하는 모듈입니다. (클래스는 결코 전역 스코프로 사용되지 않습니다.) 메서드에서 전역 데이터를 사용할 좋은 이유를 거의 만나지 못하지만, 전역 스코프를 정당하게 사용하는 여러 가지 경우가 있습니다: 한가지는, 전역 스코프에 정의된 함수와 메서드 뿐만 아니라, 그곳에 임포트된 함수와 모듈도 메서드가 사용할 수 있다는 것입니다. 보통, 메서드를 포함하는 클래스 자신은 이 전역 스코프에 정의되고, 다음 섹션에서 메서드가 자신의 클래스를 참조하길 원하는 몇 가지 좋은 이유를 보게 될 것입니다.

각 값은 객체고, 그러므로 클래스 (형 이라고도 불린다) 를 갖습니다. 이것은 object.__class__ 에 저장되어 있습니다.

9.5. 상속

물론, 상속을 지원하지 않는다면 언어 기능은 “클래스”라는 이름을 붙일만한 가치가 없을 것입니다. 파생 클래스 정의의 문법은 이렇게 생겼습니다:

class DerivedClassName(BaseClassName):
    <statement-1>
    .
    .
    .
    <statement-N>

이름 BaseClassName 은 파생 클래스 정의를 포함하는 스코프에 정의되어 있어야 합니다. 베이스 클래스 이름의 자리에 다른 임의의 표현식도 허락됩니다. 예를 들어, 베이스 클래스가 다른 모듈에 정의되어 있을 때 유용합니다:

class DerivedClassName(modname.BaseClassName):

파생 클래스 정의의 실행은 베이스 클래스와 같은 방식으로 진행됩니다. 클래스 객체가 만들어질 때, 베이스 클래스가 기억됩니다. 이것은 어트리뷰트 참조를 결정할 때 사용됩니다: 요청된 어트리뷰트가 클래스에서 발견되지 않으면 베이스 클래스로 검색을 확장합니다. 베이스 클래스 또한 다른 클래스로부터 파생되었다면 이 규칙은 재귀적으로 적용됩니다.

파생 클래스의 인스턴스 만들기에 특별한 것은 없습니다: DerivedClassName() 는 그 클래스의 새 인스턴스를 만듭니다. 메서드 참조는 다음과 같이 결정됩니다: 대응하는 클래스 어트리뷰트가 검색되는데, 필요하면 베이스 클래스의 연쇄를 타고 내려갑니다. 이것이 함수 객체를 준다면 메서드 참조는 올바릅니다.

파생 클래스는 베이스 클래스의 메서드들을 재정의할 수 있습니다. 메서드가 같은 객체의 다른 메서드를 호출할 때 특별한 권한 같은 것은 없으므로, 베이스 클래스에 정의된 다른 메서드를 호출하는 베이스 클래스의 메서드는 재정의된 파생 클래스의 메서드를 호출하게 됩니다. (C++ 프로그래머를 위한 표현으로: 파이썬의 모든 메서드는 실질적으로 virtual 입니다.)

파생 클래스에서 재정의된 메서드가, 같은 이름의 베이스 클래스 메서드를 단순히 갈아치우기보다 사실은 확장하고 싶을 수 있습니다. 베이스 클래스의 메서드를 직접 호출하는 간단한 방법이 있습니다: 단지 BaseClassName.methodname(self, arguments) 를 호출하면 됩니다. 이것은 때로 클라이언트에게도 쓸모가 있습니다. (이것은 베이스 클래스가 전역 스코프에서 BaseClassName 으로 액세스 될 수 있을 때만 동작함에 주의하세요.)

파이썬에는 상속과 함께 사용할 수 있는 두 개의 내장 함수가 있습니다:

인스턴스의 형을 검사하려면 isinstance() 를 사용합니다: isinstance(obj, int) 는 obj.__class__ 가 int 거나 int 에서 파생된 클래스인 경우만 True 가 됩니다.

클래스 상속을 검사하려면 issubclass() 를 사용합니다: issubclass(bool, int) 는 True 인데, bool 이 int 의 서브 클래스이기 때문입니다. 하지만, issubclass(float, int) 는 False 인데, float 는 int 의 서브 클래스가 아니기 때문입니다.

9.5.1. 다중 상속

파이썬은 다중 상속의 형태도 지원합니다. 여러 개의 베이스 클래스를 갖는 클래스 정의는 이런 식입니다:

class DerivedClassName(Base1, Base2, Base3):
    <statement-1>
    .
    .
    .
    <statement-N>

대부분의 목적상, 가장 간단한 경우에, 부모 클래스로부터 상속된 어트리뷰트들의 검색을 깊이 우선으로, 왼쪽에서 오른쪽으로, 계층 구조에서 겹치는 같은 클래스를 두 번 검색하지 않는 것으로 생각할 수 있습니다. 그래서, 어트리뷰트가 DerivedClassName 에서 발견되지 않으면, Base1 에서 찾고, 그다음 (재귀적으로) Base1 의 베이스 클래스들을 검색합니다. 거기에서도 발견되지 않으면, Base2 에서 찾고, 이런 식으로 계속합니다.

사실, 이것보다는 약간 더 복잡합니다; 메서드 결정 순서는 super() 로의 협력적인 호출을 지원하기 위해 동적으로 변경됩니다. 이 접근법은 몇몇 다른 다중 상속 언어들에서 call-next-method 라고 알려져 있고, 단일 상속 언어들에서 발견되는 super 호출보다 더 강력합니다.

동적인 순서가 필요한 이유는, 모든 다중 상속의 경우는 하나나 그 이상의 다이아몬드 관계 (적어도 부모 클래스 중 하나가 가장 바닥 클래스들로부터 여러 경로를 통해 액세스 되는 경우) 를 만들기 때문입니다. 예를 들어, 모든 클래스는 object 를 계승하기 때문에, 모든 다중 상속은 object 에 이르는 여러 경로를 제공합니다. 베이스 클래스들이 여러 번 액세스 되지 않게 하려고, 동적인 알고리즘이 검색 순서를 선형화하는데, 각 클래스에서 지정된 왼쪽에서 오른쪽으로 가는 순서를 보존하고, 각 부모를 오직 한 번만 호출하고, 단조적 (부모들의 우선순위에 영향을 주지 않으면서 서브 클래스를 만들 수 있다는 의미입니다) 이도록 만듭니다. 모두 함께 사용될 때, 이 성질들은 다중 상속으로 신뢰성 있고 확장성 있는 클래스들을 설계할 수 있도록 만듭니다. 더 자세한 내용은, https://www.python.org/download/releases/2.3/mro/ 를 보세요.

9.6. 비공개 변수

객체 내부에서만 액세스할 수 있는 “비공개” 인스턴스 변수는 파이썬에 존재하지 않습니다. 하지만, 대부분의 파이썬 코드에서 따르고 있는 규약이 있습니다: 밑줄로 시작하는 이름은 (예를 들어, _spam) API의 공개적이지 않은 부분으로 취급되어야 합니다 (그것이 함수, 메서드, 데이터 멤버중 무엇이건 간에). 구현 상세이고 통보 없이 변경되는 대상으로 취급되어야 합니다.

클래스-비공개 멤버들의 올바른 사례가 있으므로 (즉 서브 클래스에서 정의된 이름들과의 충돌을 피하고자), 이름 뒤섞기 (name mangling) 라고 불리는 메커니즘에 대한 제한된 지원이 있습니다. __spam 형태의 (최소 두 개의 밑줄로 시작하고, 최대 한 개의 밑줄로 끝납니다) 모든 식별자는 _classname__spam 로 텍스트 적으로 치환되는데, classname 은 현재 클래스 이름에서 앞에 오는 밑줄을 제거한 것입니다. 이 뒤섞기는 클래스 정의에 등장하는 이상, 식별자의 문법적 위치와 무관하게 수행됩니다.

이름 뒤섞기는 클래스 내부의 메서드 호출을 방해하지 않고 서브 클래스들이 메서드를 재정의할 수 있도록 하는 데 도움을 줍니다. 예를 들어:

class Mapping:
    def __init__(self, iterable):
        self.items_list = []
        self.__update(iterable)

    def update(self, iterable):
        for item in iterable:
            self.items_list.append(item)

    __update = update   # private copy of original update() method

class MappingSubclass(Mapping):

    def update(self, keys, values):
        # provides new signature for update()
        # but does not break __init__()
        for item in zip(keys, values):
            self.items_list.append(item)

위의 예는 MappingSubclass가 __update 식별자를 도입하더라도 작동합니다. Mapping 클래스에서는 _Mapping__update로 MappingSubclass 클래스에서는 _MappingSubclass__update로 각각 대체 되기 때문입니다.

뒤섞기 규칙은 대체로 사고를 피하고자 설계되었다는 것에 주의하세요; 여전히 비공개로 취급되는 변수들을 액세스하거나 수정할 수 있습니다. 이것은 디버거와 같은 특별한 상황에서 쓸모 있기조차 합니다.

exec() 나 eval() 로 전달된 코드는 호출하는 클래스의 클래스 이름을 현재 클래스로 여기지 않는다는 것에 주의하세요; 이것은 global 문의 효과와 유사한데, 효과가 함께 바이트-컴파일된 코드로 제한됩니다. 같은 제약이 __dict__ 를 직접 참조할 때뿐만 아니라, getattr(), setattr(), delattr() 에도 적용됩니다.

9.7. 잡동사니

때로 몇몇 이름 붙은 데이터 항목들을 함께 묶어주는 파스칼의 “record” 나 C의 “struct” 와 유사한 데이터형을 갖는 것이 쓸모 있습니다. 빈 클래스 정의가 훌륭히 할 수 있는 일입니다:

class Employee:
    pass

john = Employee()  # Create an empty employee record

# Fill the fields of the record
john.name = 'John Doe'
john.dept = 'computer lab'
john.salary = 1000

특정한 추상적인 데이터형을 기대하는 파이썬 코드 조각은, 종종 그 데이터형의 메서드를 흉내 내는 클래스를 대신 전달받을 수 있습니다. 예를 들어, 파일 객체로부터 데이터를 포맷하는 함수가 있을 때, 대신 문자열 버퍼에서 데이터를 읽는 메서드 read() 와 readline() 을 제공하는 클래스를 정의한 후 인자로 전달할 수 있습니다.

인스턴스 메서드 객체도 어트리뷰트를 갖습니다: m.__self__ 는 메서드 m() 과 결합한 인스턴스 객체이고, m.__func__ 는 메서드에 상응하는 함수 객체입니다.

9.8. 이터레이터

지금쯤 아마도 여러분은 대부분의 컨테이너 객체들을 for 문으로 루핑할 수 있음을 눈치챘을 것입니다:

for element in [1, 2, 3]:
    print(element)
for element in (1, 2, 3):
    print(element)
for key in {'one':1, 'two':2}:
    print(key)
for char in "123":
    print(char)
for line in open("myfile.txt"):
    print(line, end='')

이런 스타일의 액세스는 명료하고, 간결하고, 편리합니다. 이터레이터를 사용하면 파이썬이 보편화하고 통합됩니다. 무대 뒤에서, for 문은 컨테이너 객체에 대해 iter() 를 호출합니다. 이 함수는 메서드 __next__() 를 정의하는 이터레이터 객체를 돌려주는데, 이 메서드는 컨테이너의 요소들을 한 번에 하나씩 액세스합니다. 남은 요소가 없으면, __next__() 는 StopIteration 예외를 일으켜서 for 루프에 종료를 알립니다. next() 내장 함수를 사용해서 __next__() 메서드를 호출할 수 있습니다; 이 예는 이 모든 것들이 어떻게 동작하는지 보여줍니다:

>>> s = 'abc'
>>> it = iter(s)
>>> it
<iterator object at 0x00A1DB50>
>>> next(it)
'a'
>>> next(it)
'b'
>>> next(it)
'c'
>>> next(it)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
    next(it)
StopIteration

이터레이터 프로토콜의 뒤에 있는 메커니즘을 살펴보면, 여러분의 클래스에 이터레이터 동작을 쉽게 추가할 수 있습니다. __next__() 메서드를 가진 객체를 돌려주는 __iter__() 메서드를 정의합니다. 클래스가 __next__() 를 정의하면, __iter__() 는 그냥 self 를 돌려줄 수 있습니다.

class Reverse:
    """Iterator for looping over a sequence backwards."""
    def __init__(self, data):
        self.data = data
        self.index = len(data)

    def __iter__(self):
        return self

    def __next__(self):
        if self.index == 0:
            raise StopIteration
        self.index = self.index - 1
        return self.data[self.index]

>>> rev = Reverse('spam')
>>> iter(rev)
<__main__.Reverse object at 0x00A1DB50>
>>> for char in rev:
...     print(char)
...
m
a
p
s

9.9. 제너레이터

제너레이터 는 이터레이터를 만드는 간단하고 강력한 도구입니다. 일반적인 함수처럼 작성되지만 값을 돌려주고 싶을 때마다 yield 문을 사용합니다. 제너레이터에 next() 가 호출될 때마다, 제너레이터는 떠난 곳에서 실행을 재개합니다 (모든 데이터 값들과 어떤 문장이 마지막으로 실행되었는지 기억합니다). 예는 제너레이터를 사소할 정도로 쉽게 만들 수 있음을 보여줍니다:

def reverse(data):
    for index in range(len(data)-1, -1, -1):
        yield data[index]

>>> for char in reverse('golf'):
...     print(char)
...
f
l
o
g

제너레이터로 할 수 있는 모든 것은 앞 절에서 설명했듯이 클래스 기반 이터레이터로도 할 수 있습니다. 제너레이터가 간단한 이유는 __iter__() 와 __next__() 메서드가 저절로 만들어지기 때문입니다.

또 하나의 주요 기능은 지역 변수들과 실행 상태가 호출 간에 자동으로 보관된다는 것입니다. 이것은 self.index 나 self.data 와 같은 인스턴스 변수를 사용하는 접근법에 비교해 함수를 쓰기 쉽고 명료하게 만듭니다.

자동 메서드 생성과 프로그램 상태의 저장에 더해, 제너레이터가 종료할 때 자동으로 StopIteration 을 일으킵니다. 조합하면, 이 기능들이 일반 함수를 작성하는 것만큼 이터레이터를 만들기 쉽게 만듭니다.

9.10. 제너레이터 표현식

간단한 제너레이터는 리스트 컴프리헨션과 비슷하지만, 대괄호 대신 괄호를 사용하는 문법을 사용한 표현식으로 간결하게 코딩할 수 있습니다. 이 표현식들은 둘러싸는 함수가 제너레이터를 즉시 사용하는 상황을 위해 설계되었습니다. 제너레이터 표현식은 완전한 제너레이터 정의보다 간결하지만, 융통성은 떨어지고, 비슷한 리스트 컴프리헨션보다 메모리를 덜 쓰는 경향이 있습니다.

예:

>>> sum(i*i for i in range(10))                 # sum of squares
285

>>> xvec = [10, 20, 30]
>>> yvec = [7, 5, 3]
>>> sum(x*y for x,y in zip(xvec, yvec))         # dot product
260

>>> from math import pi, sin
>>> sine_table = {x: sin(x*pi/180) for x in range(0, 91)}

>>> unique_words = set(word  for line in page  for word in line.split())

>>> valedictorian = max((student.gpa, student.name) for student in graduates)

>>> data = 'golf'
>>> list(data[i] for i in range(len(data)-1, -1, -1))
['f', 'l', 'o', 'g']

각주

1

한 가지만 제외하고. 모듈 객체는 __dict__ 라고 불리는 비밀스러운 읽기 전용 어트리뷰트를 갖는데, 모듈의 이름 공간을 구현하는데 사용하는 딕셔너리를 돌려줍니다; 이름 __dict__ 는 어트리뷰트 이지만 전역 이름은 아닙니다. 명백하게, 이것을 사용하는 것은 이름 공간 구현의 추상화를 파괴하는 것이고, 사후 디버거와 같은 것들로만 제한되어야 합니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 자습서 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 자습서 »

|

10. 표준 라이브러리 둘러보기

10.1. 운영 체제 인터페이스

os 모듈은 운영 체제와 상호 작용하기 위한 수십 가지 함수들을 제공합니다:

>>> import os
>>> os.getcwd()      # Return the current working directory
'C:\\Python37'
>>> os.chdir('/server/accesslogs')   # Change current working directory
>>> os.system('mkdir today')   # Run the command mkdir in the system shell
0

from os import * 대신에 import os 스타일을 사용해야 합니다. 그래야 os.open() 이 내장 open() 을 가리는 것을 피할 수 있는데, 두 함수는 아주 다르게 동작합니다.

os 와 같은 큰 모듈과 작업할 때, 내장 dir() 과 help() 함수는 대화형 도우미로 쓸모가 있습니다.

>>> import os
>>> dir(os)
<returns a list of all module functions>
>>> help(os)
<returns an extensive manual page created from the module's docstrings>

일상적인 파일과 디렉터리 관리 작업을 위해, shutil 모듈은 사용하기 쉬운 더 고수준의 인터페이스를 제공합니다:

>>> import shutil
>>> shutil.copyfile('data.db', 'archive.db')
'archive.db'
>>> shutil.move('/build/executables', 'installdir')
'installdir'

10.2. 파일 와일드카드

glob 모듈은 디렉터리 와일드카드 검색으로 파일 목록을 만드는 함수를 제공합니다:

>>> import glob
>>> glob.glob('*.py')
['primes.py', 'random.py', 'quote.py']

10.3. 명령행 인자

일반적인 유틸리티 스크립트는 종종 명령행 인자를 처리해야 할 필요가 있습니다. 이 인자들은 sys 모듈의 argv 어트리뷰트에 리스트로 저장됩니다. 예를 들어, 명령행에서 python demo.py one two three 를 실행하면 다음과 같은 결과가 출력됩니다:

>>> import sys
>>> print(sys.argv)
['demo.py', 'one', 'two', 'three']

The argparse module provides a more sophisticated mechanism to process command line arguments. The following script extracts one or more filenames and an optional number of lines to be displayed:

import argparse

parser = argparse.ArgumentParser(prog = 'top',
    description = 'Show top lines from each file')
parser.add_argument('filenames', nargs='+')
parser.add_argument('-l', '--lines', type=int, default=10)
args = parser.parse_args()
print(args)

When run at the command line with python top.py --lines=5 alpha.txt beta.txt, the script sets args.lines to 5 and args.filenames to ['alpha.txt', 'beta.txt'].

10.4. 에러 출력 리디렉션과 프로그램 종료

sys 모듈은 stdin, stdout, stderr 어트리뷰트도 갖고 있습니다. 가장 마지막 것은 stdout 이 리디렉트 되었을 때도 볼 수 있는 경고와 에러 메시지들을 출력하는데 쓸모가 있습니다:

>>> sys.stderr.write('Warning, log file not found starting a new one\n')
Warning, log file not found starting a new one

스크립트를 종료하는 가장 직접적인 방법은 sys.exit() 를 쓰는 것입니다.

10.5. 문자열 패턴 매칭

re 모듈은 고급 문자열 처리를 위한 정규식 도구들을 제공합니다. 복잡한 매칭과 조작을 위해, 정규식은 간결하고 최적화된 솔루션을 제공합니다:

>>> import re
>>> re.findall(r'\bf[a-z]*', 'which foot or hand fell fastest')
['foot', 'fell', 'fastest']
>>> re.sub(r'(\b[a-z]+) \1', r'\1', 'cat in the the hat')
'cat in the hat'

단지 간단한 기능만 필요한 경우에는, 문자열 메서드들이 선호되는데 읽기 쉽고 디버깅이 쉽기 때문입니다:

>>> 'tea for too'.replace('too', 'two')
'tea for two'

10.6. 수학

math 모듈은 부동 소수점 연산을 위한 하부 C 라이브러리 함수들에 대한 액세스를 제공합니다.

>>> import math
>>> math.cos(math.pi / 4)
0.70710678118654757
>>> math.log(1024, 2)
10.0

random 모듈은 무작위 선택을 할 수 있는 도구들을 제공합니다:

>>> import random
>>> random.choice(['apple', 'pear', 'banana'])
'apple'
>>> random.sample(range(100), 10)   # sampling without replacement
[30, 83, 16, 4, 8, 81, 41, 50, 18, 33]
>>> random.random()    # random float
0.17970987693706186
>>> random.randrange(6)    # random integer chosen from range(6)
4

statistics 모듈은 수치 데이터의 기본적인 통계적 특성들을 (평균, 중간값, 분산, 등등) 계산합니다.

>>> import statistics
>>> data = [2.75, 1.75, 1.25, 0.25, 0.5, 1.25, 3.5]
>>> statistics.mean(data)
1.6071428571428572
>>> statistics.median(data)
1.25
>>> statistics.variance(data)
1.3720238095238095

SciPy 프로젝트 <https://scipy.org> 는 다른 수치 계산용 모듈들을 많이 갖고 있습니다.

10.7. 인터넷 액세스

인터넷을 액세스하고 인터넷 프로토콜들을 처리하는 많은 모듈이 있습니다. 가장 간단한 두 개는 URL에서 데이터를 읽어오는 urllib.request 와 메일을 보내는 smtplib 입니다:

>>> from urllib.request import urlopen
>>> with urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl') as response:
...     for line in response:
...         line = line.decode('utf-8')  # Decoding the binary data to text.
...         if 'EST' in line or 'EDT' in line:  # look for Eastern Time
...             print(line)

<BR>Nov. 25, 09:43:32 PM EST

>>> import smtplib
>>> server = smtplib.SMTP('localhost')
>>> server.sendmail('soothsayer@example.org', 'jcaesar@example.org',
... """To: jcaesar@example.org
... From: soothsayer@example.org
...
... Beware the Ides of March.
... """)
>>> server.quit()

(두 번째 예는 localhost 에서 메일 서버가 실행되고 있어야 한다는 것에 주의하세요.)

10.8. 날짜와 시간

datetime 모듈은 날짜와 시간을 조작하는 클래스들을 제공하는데, 간단한 방법과 복잡한 방법 모두 제공합니다. 날짜와 시간 산술이 지원되지만, 구현의 초점은 출력 포매팅과 조작을 위해 효율적으로 멤버를 추출하는 데에 맞춰져 있습니다. 모듈은 시간대를 고려하는 객체들도 지원합니다.

>>> # dates are easily constructed and formatted
>>> from datetime import date
>>> now = date.today()
>>> now
datetime.date(2003, 12, 2)
>>> now.strftime("%m-%d-%y. %d %b %Y is a %A on the %d day of %B.")
'12-02-03. 02 Dec 2003 is a Tuesday on the 02 day of December.'

>>> # dates support calendar arithmetic
>>> birthday = date(1964, 7, 31)
>>> age = now - birthday
>>> age.days
14368

10.9. 데이터 압축

일반적인 데이터 보관 및 압축 형식들을 다음과 같은 모듈들이 직접 지원합니다: zlib, gzip, bz2, lzma, zipfile, tarfile.

>>> import zlib
>>> s = b'witch which has which witches wrist watch'
>>> len(s)
41
>>> t = zlib.compress(s)
>>> len(t)
37
>>> zlib.decompress(t)
b'witch which has which witches wrist watch'
>>> zlib.crc32(s)
226805979

10.10. 성능 측정

일부 파이썬 사용자들은 같은 문제에 대한 다른 접근법들의 상대적인 성능을 파악하는데 깊은 관심을 두고 있습니다. 파이썬은 이런 질문들에 즉시 답을 주는 측정 도구를 제공합니다.

예를 들어, 인자들을 맞교환하는 전통적인 방식 대신에, 튜플 패킹과 언 패킹을 사용하고자 하는 유혹을 느낄 수 있습니다. timeit 모듈은 적당한 성능 이점을 신속하게 보여줍니다:

>>> from timeit import Timer
>>> Timer('t=a; a=b; b=t', 'a=1; b=2').timeit()
0.57535828626024577
>>> Timer('a,b = b,a', 'a=1; b=2').timeit()
0.54962537085770791

timeit 의 정밀도와는 대조적으로, profile 과 pstats 모듈은 큰 블록의 코드에서 시간 임계 섹션을 식별하기 위한 도구들을 제공합니다.

10.11. 품질 관리

고품질의 소프트웨어를 개발하는 한 가지 접근법은 개발되는 각 함수에 대한 테스트를 작성하고, 그것들을 개발 프로세스 중에 자주 실행하는 것입니다.

doctest 모듈은 모듈을 훑어보고 프로그램의 독스트링들에 내장된 테스트들을 검사하는 도구를 제공합니다. 테스트 만들기는 평범한 호출을 그 결과와 함께 독스트링으로 복사해서 붙여넣기를 하는 수준으로 간단해집니다. 사용자에게 예제를 함께 제공해서 설명서를 개선하고, doctest 모듈이 설명서에서 코드가 여전히 사실인지 확인하도록 합니다.

def average(values):
    """Computes the arithmetic mean of a list of numbers.

    >>> print(average([20, 30, 70]))
    40.0
    """
    return sum(values) / len(values)

import doctest
doctest.testmod()   # automatically validate the embedded tests

unittest 모듈은 doctest 모듈만큼 쉬운 것은 아니지만, 더욱 포괄적인 테스트 집합을 별도의 파일로 관리할 수 있게 합니다:

import unittest

class TestStatisticalFunctions(unittest.TestCase):

    def test_average(self):
        self.assertEqual(average([20, 30, 70]), 40.0)
        self.assertEqual(round(average([1, 5, 7]), 1), 4.3)
        with self.assertRaises(ZeroDivisionError):
            average([])
        with self.assertRaises(TypeError):
            average(20, 30, 70)

unittest.main()  # Calling from the command line invokes all tests

10.12. 배터리가 포함됩니다

파이썬은 “배터리가 포함됩니다” 철학을 갖고 있습니다. 이는 더 큰 패키지의 정교하고 강력한 기능을 통해 가장 잘 나타납니다. 예를 들어:

xmlrpc.client 와 xmlrpc.server 모듈은 원격 프로시저 호출을 구현하는 일을 거의 사소한 일로 만듭니다. 모듈의 이름에도 불구하고, XML에 대한 직접적인 지식이나 처리가 필요하지 않습니다.

email 패키지는 MIME 및 기타 RFC 2822 [https://tools.ietf.org/html/rfc2822.html] 기반 메시지 문서를 포함하는 전자 메일 메시지를 관리하기 위한 라이브러리입니다. 실제로 메시지를 보내고 받는 smtplib 와 poplib 와는 달리, email 패키지는 복잡한 메시지 구조 (첨부 파일 포함) 를 작성하거나 해독하고 인터넷 인코딩과 헤더 프로토콜을 구현하기 위한 완벽한 도구 상자를 가지고 있습니다.

json 패키지는 널리 사용되는 데이터 교환 형식을 파싱하기위한 강력한 지원을 제공합니다. csv 모듈은 데이터베이스와 스프레드시트에서 일반적으로 지원되는 쉼표로 구분된 값 형식으로 파일을 직접 읽고 쓸 수 있도록 지원합니다. XML 처리는 xml.etree.ElementTree, xml.dom 및 xml.sax 패키지에 의해 지원됩니다. 이러한 모듈과 패키지를 함께 사용하면 파이썬 응용 프로그램과 다른 도구 간의 데이터 교환이 크게 단순해집니다.

sqlite3 모듈은 SQLite 데이터베이스 라이브러리의 래퍼인데, 약간 비표준 SQL 구문을 사용하여 업데이트되고 액세스 될 수 있는 퍼시스턴트 데이터베이스를 제공합니다.

국제화는 gettext, locale, 그리고 codecs 패키지를 포함한 많은 모듈에 의해 지원됩니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 자습서 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 자습서 »

|

11. 표준 라이브러리 둘러보기 — 2부

이 두 번째 둘러보기는 전문 프로그래밍 요구 사항을 지원하는 고급 모듈을 다루고 있습니다. 이러한 모듈은 작은 스크립트에서는 거의 사용되지 않습니다.

11.1. 출력 포매팅

reprlib 모듈은 크거나 깊게 중첩된 컨테이너의 축약 된 디스플레이를 위해 커스터마이즈된 repr() 의 버전을 제공합니다:

>>> import reprlib
>>> reprlib.repr(set('supercalifragilisticexpialidocious'))
"{'a', 'c', 'd', 'e', 'f', 'g', ...}"

pprint 모듈은 인터프리터가 읽을 수 있는 방식으로 내장 객체나 사용자 정의 객체를 인쇄하는 것을 보다 정교하게 제어할 수 있게 합니다. 결과가 한 줄보다 길면 “예쁜 프린터”가 줄 바꿈과 들여쓰기를 추가하여 데이터 구조를 보다 명확하게 나타냅니다:

>>> import pprint
>>> t = [[[['black', 'cyan'], 'white', ['green', 'red']], [['magenta',
...     'yellow'], 'blue']]]
...
>>> pprint.pprint(t, width=30)
[[[['black', 'cyan'],
   'white',
   ['green', 'red']],
  [['magenta', 'yellow'],
   'blue']]]

textwrap 모듈은 텍스트의 문단을 주어진 화면 너비에 맞게 포맷합니다:

>>> import textwrap
>>> doc = """The wrap() method is just like fill() except that it returns
... a list of strings instead of one big string with newlines to separate
... the wrapped lines."""
...
>>> print(textwrap.fill(doc, width=40))
The wrap() method is just like fill()
except that it returns a list of strings
instead of one big string with newlines
to separate the wrapped lines.

locale 모듈은 문화권 특정 데이터 포맷의 데이터베이스에 액세스합니다. locale의 format 함수의 grouping 어트리뷰트는 그룹 구분 기호로 숫자를 포매팅하는 직접적인 방법을 제공합니다:

>>> import locale
>>> locale.setlocale(locale.LC_ALL, 'English_United States.1252')
'English_United States.1252'
>>> conv = locale.localeconv()          # get a mapping of conventions
>>> x = 1234567.8
>>> locale.format("%d", x, grouping=True)
'1,234,567'
>>> locale.format_string("%s%.*f", (conv['currency_symbol'],
...                      conv['frac_digits'], x), grouping=True)
'$1,234,567.80'

11.2. 템플릿

string 모듈은 다재다능한 Template 클래스를 포함하고 있는데, 최종 사용자가 편집하기에 적절한 단순한 문법을 갖고 있습니다. 따라서 사용자는 응용 프로그램을 변경하지 않고도 응용 프로그램을 커스터마이즈할 수 있습니다.

형식은 $ 와 유효한 파이썬 식별자 (영숫자와 밑줄)로 만들어진 자리표시자 이름을 사용합니다. 중괄호를 사용하여 자리표시자를 둘러싸면 공백없이 영숫자가 뒤따르도록 할 수 있습니다. $$ 을 쓰면 하나의 이스케이프 된 $ 를 만듭니다:

>>> from string import Template
>>> t = Template('${village}folk send $$10 to $cause.')
>>> t.substitute(village='Nottingham', cause='the ditch fund')
'Nottinghamfolk send $10 to the ditch fund.'

substitute() 메서드는 자리표시자가 딕셔너리나 키워드 인자로 제공되지 않을 때 KeyError 를 일으킵니다. 메일 병합 스타일 응용 프로그램의 경우 사용자가 제공한 데이터가 불완전할 수 있으며 safe_substitute() 메서드가 더 적절할 수 있습니다. 데이터가 누락 된 경우 자리표시자를 변경하지 않습니다:

>>> t = Template('Return the $item to $owner.')
>>> d = dict(item='unladen swallow')
>>> t.substitute(d)
Traceback (most recent call last):
  ...
KeyError: 'owner'
>>> t.safe_substitute(d)
'Return the unladen swallow to $owner.'

Template 서브 클래스는 사용자 정의 구분자를 지정할 수 있습니다. 예를 들어 사진 브라우저를 위한 일괄 이름 바꾸기 유틸리티는 현재 날짜, 이미지 시퀀스 번호 또는 파일 형식과 같은 자리표시자에 백분율 기호를 사용하도록 선택할 수 있습니다:

>>> import time, os.path
>>> photofiles = ['img_1074.jpg', 'img_1076.jpg', 'img_1077.jpg']
>>> class BatchRename(Template):
...     delimiter = '%'
>>> fmt = input('Enter rename style (%d-date %n-seqnum %f-format):  ')
Enter rename style (%d-date %n-seqnum %f-format):  Ashley_%n%f

>>> t = BatchRename(fmt)
>>> date = time.strftime('%d%b%y')
>>> for i, filename in enumerate(photofiles):
...     base, ext = os.path.splitext(filename)
...     newname = t.substitute(d=date, n=i, f=ext)
...     print('{0} --> {1}'.format(filename, newname))

img_1074.jpg --> Ashley_0.jpg
img_1076.jpg --> Ashley_1.jpg
img_1077.jpg --> Ashley_2.jpg

템플릿의 또 다른 응용은 다중 출력 형식의 세부 사항에서 프로그램 논리를 분리하는 것입니다. 이렇게 하면 XML 파일, 일반 텍스트 보고서 및 HTML 웹 보고서에 대한 커스텀 템플릿을 치환할 수 있습니다.

11.3. 바이너리 데이터 레코드 배치 작업

struct 모듈은 가변 길이 바이너리 레코드 형식으로 작업하기 위한 pack() 과 unpack() 함수를 제공합니다. 다음 예제는 zipfile 모듈을 사용하지 않고 ZIP 파일의 헤더 정보를 루핑하는 법을 보여줍니다. 팩 코드 "H" 와 "I" 는 각각 2바이트와 4바이트의 부호 없는 숫자를 나타냅니다. "<" 는 표준 크기이면서 리틀 엔디안 바이트 순서를 가짐을 나타냅니다:

import struct

with open('myfile.zip', 'rb') as f:
    data = f.read()

start = 0
for i in range(3):                      # show the first 3 file headers
    start += 14
    fields = struct.unpack('<IIIHH', data[start:start+16])
    crc32, comp_size, uncomp_size, filenamesize, extra_size = fields

    start += 16
    filename = data[start:start+filenamesize]
    start += filenamesize
    extra = data[start:start+extra_size]
    print(filename, hex(crc32), comp_size, uncomp_size)

    start += extra_size + comp_size     # skip to the next header

11.4. 다중 스레딩

스레딩은 차례로 종속되지 않는 작업을 분리하는 기술입니다. 스레드는 다른 작업이 백그라운드에서 실행되는 동안 사용자 입력을 받는 응용 프로그램의 응답을 향상하는 데 사용할 수 있습니다. 관련된 사용 사례는 다른 스레드의 계산과 병렬로 I/O를 실행하는 경우입니다.

다음 코드는 메인 프로그램이 계속 실행되는 동안 고수준 threading 모듈이 백그라운드에서 작업을 어떻게 수행할 수 있는지 보여줍니다:

import threading, zipfile

class AsyncZip(threading.Thread):
    def __init__(self, infile, outfile):
        threading.Thread.__init__(self)
        self.infile = infile
        self.outfile = outfile

    def run(self):
        f = zipfile.ZipFile(self.outfile, 'w', zipfile.ZIP_DEFLATED)
        f.write(self.infile)
        f.close()
        print('Finished background zip of:', self.infile)

background = AsyncZip('mydata.txt', 'myarchive.zip')
background.start()
print('The main program continues to run in foreground.')

background.join()    # Wait for the background task to finish
print('Main program waited until background was done.')

다중 스레드 응용 프로그램의 가장 큰 문제점은 데이터 또는 다른 자원을 공유하는 스레드를 조정하는 것입니다. 이를 위해 threading 모듈은 록, 이벤트, 조건 변수 및 세마포어를 비롯한 많은 수의 동기화 기본 요소를 제공합니다.

이러한 도구는 강력하지만, 사소한 설계 오류로 인해 재현하기 어려운 문제가 발생할 수 있습니다. 따라서, 작업 조정에 대한 선호되는 접근 방식은 자원에 대한 모든 액세스를 단일 스레드에 집중시킨 다음 queue 모듈을 사용하여 해당 스레드에 다른 스레드의 요청을 제공하는 것입니다. 스레드 간 통신 및 조정을 위한 Queue 객체를 사용하는 응용 프로그램은 설계하기 쉽고, 읽기 쉽고, 신뢰성이 높습니다.

11.5. 로깅

logging 모듈은 완전한 기능을 갖춘 유연한 로깅 시스템을 제공합니다. 가장 단순한 경우, 로그 메시지는 파일이나 sys.stderr 로 보내집니다:

import logging
logging.debug('Debugging information')
logging.info('Informational message')
logging.warning('Warning:config file %s not found', 'server.conf')
logging.error('Error occurred')
logging.critical('Critical error -- shutting down')

그러면 다음과 같은 결과가 출력됩니다:

WARNING:root:Warning:config file server.conf not found
ERROR:root:Error occurred
CRITICAL:root:Critical error -- shutting down

기본적으로 정보 및 디버깅 메시지는 표시되지 않고 출력은 표준 에러로 보내집니다. 다른 출력 옵션에는 전자 메일, 데이터 그램, 소켓 또는 HTTP 서버를 통한 메시지 라우팅이 포함됩니다. 새로운 필터는 메시지 우선순위에 따라 다른 라우팅을 선택할 수 있습니다: DEBUG, INFO, WARNING, ERROR , 그리고 CRITICAL.

로깅 시스템은 파이썬에서 직접 구성하거나, 응용 프로그램을 변경하지 않고 사용자 정의 로깅을 위해 사용자가 편집할 수 있는 설정 파일에서 로드 할 수 있습니다.

11.6. 약한 참조

파이썬은 자동 메모리 관리 (대부분 객체에 대한 참조 횟수 추적 및 순환을 제거하기 위한 가비지 수거)를 수행합니다. 메모리는 마지막 참조가 제거된 직후에 해제됩니다.

이 접근법은 대부분의 응용 프로그램에서 잘 작동하지만, 때로는 다른 것들에 의해 사용되는 동안에만 객체를 추적해야 할 필요가 있습니다. 불행하게도, 단지 그것들을 추적하는 것만으로도 그들을 영구적으로 만드는 참조를 만듭니다. weakref 모듈은 참조를 만들지 않고 객체를 추적할 수 있는 도구를 제공합니다. 객체가 더 필요하지 않으면 weakref 테이블에서 객체가 자동으로 제거되고 weakref 객체에 대한 콜백이 트리거됩니다. 일반적인 응용에는 만드는 데 비용이 많이 드는 개체 캐싱이 포함됩니다:

>>> import weakref, gc
>>> class A:
...     def __init__(self, value):
...         self.value = value
...     def __repr__(self):
...         return str(self.value)
...
>>> a = A(10)                   # create a reference
>>> d = weakref.WeakValueDictionary()
>>> d['primary'] = a            # does not create a reference
>>> d['primary']                # fetch the object if it is still alive
10
>>> del a                       # remove the one reference
>>> gc.collect()                # run garbage collection right away
0
>>> d['primary']                # entry was automatically removed
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
    d['primary']                # entry was automatically removed
  File "C:/python37/lib/weakref.py", line 46, in __getitem__
    o = self.data[key]()
KeyError: 'primary'

11.7. 리스트 작업 도구

내장 리스트 형으로 많은 데이터 구조 요구를 충족시킬 수 있습니다. 그러나 때로는 다른 성능 상충 관계가 있는 대안적 구현이 필요할 수도 있습니다.

array 모듈은 array() 객체를 제공합니다. 이 객체는 등질적인 데이터만을 저장하고 보다 조밀하게 저장하는 리스트와 같습니다. 다음 예제는 파이썬 int 객체의 일반 리스트의 경우처럼 항목당 16바이트를 사용하는 대신에, 2바이트의 부호 없는 이진 숫자 (형 코드 "H")로 저장된 숫자 배열을 보여줍니다:

>>> from array import array
>>> a = array('H', [4000, 10, 700, 22222])
>>> sum(a)
26932
>>> a[1:3]
array('H', [10, 700])

collections 모듈은 deque() 객체를 제공합니다. 이 객체는 왼쪽에서 더 빠르게 추가/팝하지만 중간에서의 조회는 더 느려진 리스트와 같습니다. 이 객체는 대기열 및 넓이 우선 트리 검색을 구현하는 데 적합합니다:

>>> from collections import deque
>>> d = deque(["task1", "task2", "task3"])
>>> d.append("task4")
>>> print("Handling", d.popleft())
Handling task1

unsearched = deque([starting_node])
def breadth_first_search(unsearched):
    node = unsearched.popleft()
    for m in gen_moves(node):
        if is_goal(m):
            return m
        unsearched.append(m)

대안적 리스트 구현 외에도 라이브러리는 정렬된 리스트를 조작하는 함수들이 있는 bisect 모듈과 같은 다른 도구를 제공합니다:

>>> import bisect
>>> scores = [(100, 'perl'), (200, 'tcl'), (400, 'lua'), (500, 'python')]
>>> bisect.insort(scores, (300, 'ruby'))
>>> scores
[(100, 'perl'), (200, 'tcl'), (300, 'ruby'), (400, 'lua'), (500, 'python')]

heapq 모듈은 일반 리스트를 기반으로 힙을 구현하는 함수를 제공합니다. 가장 값이 작은 항목은 항상 위치 0에 유지됩니다. 이것은 가장 작은 요소에 반복적으로 액세스하지만, 전체 목록 정렬을 실행하지 않으려는 응용에 유용합니다:

>>> from heapq import heapify, heappop, heappush
>>> data = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0]
>>> heapify(data)                      # rearrange the list into heap order
>>> heappush(data, -5)                 # add a new entry
>>> [heappop(data) for i in range(3)]  # fetch the three smallest entries
[-5, 0, 1]

11.8. 10진 부동 소수점 산술

decimal 모듈은 10진 부동 소수점 산술을 위한 Decimal 데이터형을 제공합니다. 내장 float 이진 부동 소수점 구현과 비교할 때, 클래스는 특히 다음과 같은 것들에 유용합니다

정확한 10진수 표현이 필요한 금융 응용 및 기타 용도,

정밀도 제어,

법적 또는 규제 요구 사항을 충족하는 반올림 제어,

유효숫자 추적, 또는

사용자가 결과가 손으로 계산한 것과 일치 할 것으로 기대하는 응용.

예를 들어, 70센트 전화 요금에 대해 5% 세금을 계산하면, 십진 부동 소수점 및 이진 부동 소수점에 다른 결과가 나타납니다. 결과를 가장 가까운 센트로 반올림하면 차이가 드러납니다:

>>> from decimal import *
>>> round(Decimal('0.70') * Decimal('1.05'), 2)
Decimal('0.74')
>>> round(.70 * 1.05, 2)
0.73

Decimal 결과는 끝에 붙는 0을 유지하며, 두 개의 유효숫자를 가진 피승수로부터 네 자리의 유효숫자를 자동으로 추론합니다. Decimal은 손으로 한 수학을 재현하고 이진 부동 소수점이 십진수를 정확하게 표현할 수 없을 때 발생할 수 있는 문제를 피합니다.

정확한 표현은 Decimal 클래스가 이진 부동 소수점에 적합하지 않은 모듈로 계산과 동등성 검사를 수행할 수 있도록 합니다:

>>> Decimal('1.00') % Decimal('.10')
Decimal('0.00')
>>> 1.00 % 0.10
0.09999999999999995

>>> sum([Decimal('0.1')]*10) == Decimal('1.0')
True
>>> sum([0.1]*10) == 1.0
False

decimal 모듈은 필요한 만큼의 정밀도로 산술을 제공합니다:

>>> getcontext().prec = 36
>>> Decimal(1) / Decimal(7)
Decimal('0.142857142857142857142857142857142857')

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 자습서 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 자습서 »

|

12. 가상 환경 및 패키지

12.1. 소개

파이썬 응용 프로그램은 종종 표준 라이브러리의 일부로 제공되지 않는 패키지와 모듈을 사용합니다. 응용 프로그램에 특정 버전의 라이브러리가 필요할 수 있는데, 응용 프로그램에 특정 버그가 수정된 버전이 필요하거나, 라이브러리 인터페이스의 구식 버전을 사용하여 응용 프로그램을 작성할 수도 있기 때문입니다.

즉, 하나의 파이썬 설치가 모든 응용 프로그램의 요구 사항을 충족시키는 것이 불가능할 수도 있습니다. 응용 프로그램 A에 특정 모듈의 버전 1.0이 필요하지만, 응용 프로그램 B에 버전 2.0이 필요한 경우, 요구 사항이 충돌하고, 버전 1.0 또는 2.0을 설치하면 어느 한 응용 프로그램은 실행할 수 없게 됩니다.

이 문제에 대한 해결책은 가상 환경 을 만드는 것입니다. 이 가상 환경은 특정 버전 파이썬 설치와 여러 추가 패키지를 포함하는 완비된 디렉터리 트리입니다.

서로 다른 응용 프로그램은 서로 다른 가상 환경을 사용할 수 있습니다. 앞서 본 상충하는 요구 사항의 예를 해결하기 위해, 응용 프로그램 A에는 버전 1.0이 설치된 자체 가상 환경이 있고, 응용 프로그램 B에는 버전 2.0이 있는 다른 가상 환경이 있을 수 있습니다. 응용 프로그램 B에서 라이브러리를 버전 3.0으로 업그레이드해야 하는 경우, 응용 프로그램 A의 환경에 영향을 미치지 않습니다.

12.2. 가상 환경 만들기

가상 환경을 만들고 관리하는 데 사용되는 모듈은 venv 라고 합니다. venv 는 보통 여러분이 사용할 수 있는 최신 버전의 파이썬을 설치합니다. 시스템에 여러 버전의 파이썬이 있는 경우, python3 또는 원하는 버전을 실행하여 특정 파이썬 버전을 선택할 수 있습니다.

가상 환경을 만들려면, 원하는 디렉터리를 결정하고, venv 모듈을 스크립트로 실행하는데 디렉터리 경로를 명령행 인자로 전달합니다:

python3 -m venv tutorial-env

존재하지 않는다면 tutorial-env 디렉터리를 만들고, 그 안에 파이썬 인터프리터의 사본, 표준 라이브러리 및 다양한 지원 파일이 들어있는 디렉터리들을 만듭니다.

가상 환경을 만들었으면, 가상 환경을 활성화할 수 있습니다.

윈도우에서 이렇게 실행합니다:

tutorial-env\Scripts\activate.bat

Unix 또는 MacOS에서 이렇게 실행합니다:

source tutorial-env/bin/activate

(이 스크립트는 bash 셸을 위해 작성된 것으로, csh 또는 fish 셸을 사용하는 경우에는, 대신 activate.csh 와 activate.fish 스크립트를 사용해야 합니다.)

가상 환경을 활성화하면, 셸의 프롬프트가 변경되어 사용 중인 가상 환경을 보여주고, 환경을 수정하여 python 을 실행하면 특정 버전의 파이썬이 실행되도록 합니다. 예를 들어:

$ source ~/envs/tutorial-env/bin/activate
(tutorial-env) $ python
Python 3.5.1 (default, May  6 2016, 10:59:36)
  ...
>>> import sys
>>> sys.path
['', '/usr/local/lib/python35.zip', ...,
'~/envs/tutorial-env/lib/python3.5/site-packages']
>>>

12.3. pip로 패키지 관리하기

pip 라는 프로그램을 사용하여 패키지를 설치, 업그레이드 및 제거할 수 있습니다. 기본적으로 pip 는 파이썬 패키지 색인(Python Package Index), <https://pypi.org>, 에서 패키지를 설치합니다. 웹 브라우저에서 파이썬 패키지 색인을 살펴보거나, pip 의 제한된 검색 기능을 사용할 수 있습니다:

(tutorial-env) $ pip search astronomy
skyfield               - Elegant astronomy for Python
gary                   - Galactic astronomy and gravitational dynamics.
novas                  - The United States Naval Observatory NOVAS astronomy library
astroobs               - Provides astronomy ephemeris to plan telescope observations
PyAstronomy            - A collection of astronomy related tools for Python.
...

pip 는 “search”, “install”, “uninstall”, “freeze” 등 많은 부속 명령을 갖고 있습니다. (pip 에 대한 완전한 문서는 파이썬 모듈 설치하기 지침을 보면 됩니다.)

패키지 이름을 지정하여 최신 버전의 패키지를 설치할 수 있습니다:

(tutorial-env) $ pip install novas
Collecting novas
  Downloading novas-3.1.1.3.tar.gz (136kB)
Installing collected packages: novas
  Running setup.py install for novas
Successfully installed novas-3.1.1.3

패키지 이름 뒤에 == 과 버전 번호를 붙여 특정 버전의 패키지를 설치할 수도 있습니다:

(tutorial-env) $ pip install requests==2.6.0
Collecting requests==2.6.0
  Using cached requests-2.6.0-py2.py3-none-any.whl
Installing collected packages: requests
Successfully installed requests-2.6.0

이 명령을 다시 실행하면, pip 는 요청한 버전이 이미 설치되어 있음을 알리고, 아무것도 하지 않습니다. 다른 버전 번호를 지정해서 그 버전을 얻거나 pip install --upgrade 를 실행하여 패키지를 최신 버전으로 업그레이드할 수 있습니다:

(tutorial-env) $ pip install --upgrade requests
Collecting requests
Installing collected packages: requests
  Found existing installation: requests 2.6.0
    Uninstalling requests-2.6.0:
      Successfully uninstalled requests-2.6.0
Successfully installed requests-2.7.0

pip uninstall 다음에 하나 이상의 패키지 이름이 오면 가상 환경에서 패키지가 제거됩니다.

pip show 는 특정 패키지에 대한 정보를 표시합니다:

(tutorial-env) $ pip show requests
---
Metadata-Version: 2.0
Name: requests
Version: 2.7.0
Summary: Python HTTP for Humans.
Home-page: http://python-requests.org
Author: Kenneth Reitz
Author-email: me@kennethreitz.com
License: Apache 2.0
Location: /Users/akuchling/envs/tutorial-env/lib/python3.4/site-packages
Requires:

pip list 는 가상 환경에 설치된 모든 패키지를 표시합니다:

(tutorial-env) $ pip list
novas (3.1.1.3)
numpy (1.9.2)
pip (7.0.3)
requests (2.7.0)
setuptools (16.0)

pip freeze 는 설치된 패키지의 비슷한 목록을 만들지만, pip install 이 기대하는 형식을 사용합니다. 일반적인 규칙은 이 목록을 requirements.txt 파일에 넣는 것입니다:

(tutorial-env) $ pip freeze > requirements.txt
(tutorial-env) $ cat requirements.txt
novas==3.1.1.3
numpy==1.9.2
requests==2.7.0

requirements.txt 는 버전 제어에 커밋되어 응용 프로그램 일부로 제공될 수 있습니다. 사용자는 install -r 로 모든 필요한 패키지를 설치할 수 있습니다:

(tutorial-env) $ pip install -r requirements.txt
Collecting novas==3.1.1.3 (from -r requirements.txt (line 1))
  ...
Collecting numpy==1.9.2 (from -r requirements.txt (line 2))
  ...
Collecting requests==2.7.0 (from -r requirements.txt (line 3))
  ...
Installing collected packages: novas, numpy, requests
  Running setup.py install for novas
Successfully installed novas-3.1.1.3 numpy-1.9.2 requests-2.7.0

pip 에는 더 많은 옵션이 있습니다. pip 에 대한 완전한 문서는 파이썬 모듈 설치하기 지침을 참고하세요. 패키지를 작성했을 때 파이썬 패키지 색인에서 사용할 수 있게 하려면, 파이썬 모듈 배포하기 지침을 참고하세요.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 자습서 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 자습서 »

|

13. 이제 뭘 하지?

이 자습서를 읽어서 아마도 파이썬 사용에 관한 관심이 높아졌을 것입니다 — 실제 문제를 해결하기 위해 파이썬을 적용하려고 열망해야 합니다. 더 배우려면 어디로 가야 할까?

이 자습서는 파이썬의 문서 세트의 일부입니다. 세트의 다른 문서는 다음과 같습니다:

파이썬 표준 라이브러리:

표준 라이브러리의 형, 함수 및 모듈에 대한 완전한 (비록 딱딱하지만) 레퍼런스 자료를 제공하는 이 설명서를 탐색해야 합니다. 표준 파이썬 배포판에는 추가 코드가 많이 포함되어 있습니다. 유닉스 우편함을 읽고, HTTP를 통해 문서를 검색하고, 난수를 만들고, 명령행 옵션을 파싱하고, CGI 프로그램을 작성하고, 데이터를 압축하고, 기타 많은 작업을 수행하는 모듈이 있습니다. 라이브러리 레퍼런스를 훑어보면 어떤 것이 있는지 알 수 있습니다.

파이썬 모듈 설치하기 는 다른 파이썬 사용자가 작성한 추가 모듈을 설치하는 방법을 설명합니다.

파이썬 언어 레퍼런스: 파이썬의 문법과 의미에 대한 자세한 설명. 읽기에 부담스럽지만, 언어 자체에 대한 완전한 안내서로서 유용합니다.

기타 파이썬 자료:

https://www.python.org: 주요 파이썬 웹 사이트. 여기에는 코드, 문서 및 웹에 있는 파이썬 관련 페이지들에 대한 포인터가 들어 있습니다. 이 웹 사이트는 유럽, 일본 및 호주와 같이 전 세계 여러 곳에 미러가 만들어집니다. 지리적 위치에 따라 미러가 기본 사이트보다 빠를 수도 있습니다.

https://docs.python.org: 파이썬의 설명서에 빠르게 액세스할 수 있습니다.

https://pypi.org: 이전에 치즈 가게(Cheese Shop)로도 불렸던 1 파이썬 패키지 인덱스는 내려받을 수 있는 사용자 제작 파이썬 모듈의 색인입니다. 코드를 배포하기 시작하면 다른 사람들이 찾을 수 있도록 여기에 코드를 등록할 수 있습니다.

https://code.activestate.com/recipes/langs/python/: 파이썬 요리책(Python Cookbook)은 많은 코드 예제, 더 큰 모듈 및 유용한 스크립트 모음입니다. 특히 주목할만한 공헌들을 Python Cookbook (O’Reilly & Associates, ISBN 0-596-00797-3)이라는 제목의 책에 모았습니다.

http://www.pyvideo.org 는 콘퍼런스 및 사용자 그룹 회의에서 파이썬 관련 비디오에 대한 링크들을 수집합니다.

https://scipy.org: Scientific Python 프로젝트에는 빠른 배열 계산 및 조작을 위한 모듈들과 선형 대수, 푸리에 변환, 비선형 솔버, 난수 분포, 통계 분석 등과 같은 여러 가지 패키지들이 포함되어 있습니다.

파이썬 관련 질문 및 문제 보고의 경우, 뉴스 그룹 comp.lang.python 에 게시하거나 python-list@python.org 의 메일링 리스트로 보낼 수 있습니다. 뉴스 그룹과 메일링 리스트는 게이트웨이로 연결되어 있으므로 하나에 게시된 메시지는 자동으로 다른 그룹으로 전달됩니다. 하루에 수백 건의 게시물이 올라옵니다. 질문하고, 질문에 답변하고, 새로운 기능을 제안하고, 새로운 모듈을 발표합니다. 메일링 리스트 저장소는 https://mail.python.org/pipermail/ 에 있습니다.

게시하기 전에 자주 나오는 질문들 (FAQ라고도 한다) 목록을 확인해야 합니다. FAQ는 반복적으로 나타나는 많은 질문에 대한 답을 제공하며, 이미 여러분의 문제에 대한 해결 방법을 담고 있을 수 있습니다.

각주

1

“Cheese Shop” 은 Monty Python의 스케치입니다: 고객이 치즈 가게에 들어가지만, 찾는 치즈가 무엇이건, 점원은 없다고 말합니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 자습서 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 자습서 »

|

14. 대화형 입력 편집 및 히스토리 치환

일부 파이썬 인터프리터 버전은 Korn 셸 및 GNU Bash 셸에 있는 기능과 유사하게 현재 입력 줄 편집 및 히스토리 치환을 지원합니다. 이는 다양한 스타일의 편집을 지원하는 GNU Readline [https://tiswww.case.edu/php/chet/readline/rltop.html] 라이브러리를 사용하여 구현됩니다. 이 라이브러리에는 자체 설명서가 있고, 여기에서 반복하지는 않습니다.

14.1. 탭 완성 및 히스토리 편집

변수와 모듈 이름의 완성은 인터프리터 시작 시 자동으로 활성화 되어서 Tab 키가 완료 기능을 호출합니다; 파이썬 명령문 이름, 현재 지역 변수 및 사용 가능한 모듈 이름을 찾습니다. string.a 와 같은 점으로 구분된 표현식의 경우, 표현식을 마지막 '.' 까지 값을 구한 다음, 결과 객체의 어트리뷰트로 완성을 제안합니다. __getattr__() 메서드를 가진 객체가 표현식의 일부면 응용 프로그램이 정의한 코드를 실행할 수 있음에 주의해야 합니다. 기본 설정은 사용자 디렉터리에 .python_history 라는 파일로 히스토리를 저장합니다. 다음 대화형 인터프리터 세션에서 히스토리를 다시 사용할 수 있습니다.

14.2. 대화형 인터프리터 대안

이 기능은 이전 버전의 인터프리터에 비교해 엄청난 발전입니다; 그러나, 몇 가지 희망 사항이 남아 있습니다: 이어지는 줄에서 적절한 들여쓰기가 제안된다면 좋을 것입니다 (파서는 다음에 들여쓰기 토큰이 필요한지 알고 있습니다). 완료 메커니즘은 인터프리터의 심볼 테이블을 사용할 수 있습니다. 매치되는 괄호, 따옴표 등을 검사 (또는 제안)하는 명령도 유용할 것입니다.

꽤 오랫동안 사용됐던 개선된 대화형 인터프리터는 IPython [https://ipython.org/] 인데, 탭 완성, 객체 탐색 및 고급 히스토리 관리 기능을 갖추고 있습니다. 또한, 철저하게 커스터마이즈해서 다른 응용 프로그램에 내장할 수 있습니다. 비슷한 또 다른 개선된 대화형 환경은 bpython [https://www.bpython-interpreter.org/] 입니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 자습서 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 자습서 »

|

15. 부동 소수점 산술: 문제점 및 한계

부동 소수점 숫자는 컴퓨터 하드웨어에서 밑(base)이 2인(이진) 소수로 표현됩니다. 예를 들어, 소수

0.125

는 1/10 + 2/100 + 5/1000의 값을 가지며, 같은 방식으로 이진 소수

0.001

는 값 0/2 + 0/4 + 1/8을 가집니다. 이 두 소수는 같은 값을 가지며, 유일한 차이점은 첫 번째가 밑이 10인 분수 표기법으로 작성되었고 두 번째는 밑이 2라는 것입니다.

불행히도, 대부분의 십진 소수는 정확하게 이진 소수로 표현될 수 없습니다. 결과적으로, 일반적으로 입력하는 십진 부동 소수점 숫자가 실제로 기계에 저장될 때는 이진 부동 소수점 수로 근사 될 뿐입니다.

이 문제는 먼저 밑 10에서 따져보는 것이 이해하기 쉽습니다. 분수 1/3을 생각해봅시다. 이 값을 십진 소수로 근사할 수 있습니다:

0.3

또는, 더 정확하게,

0.33

또는, 더 정확하게,

0.333

등등. 아무리 많은 자릿수를 적어도 결과가 정확하게 1/3이 될 수 없지만, 점점 더 1/3에 가까운 근사치가 됩니다.

같은 방식으로, 아무리 많은 자릿수의 숫자를 사용해도, 십진수 0.1은 이진 소수로 정확하게 표현될 수 없습니다. 이진법에서, 1/10은 무한히 반복되는 소수입니다

0.0001100110011001100110011001100110011001100110011...

유한 한 비트 수에서 멈추면, 근삿값을 얻게 됩니다. 오늘날 대부분 기계에서, float는 이진 분수로 근사 되는 데, 최상위 비트로부터 시작하는 53비트를 분자로 사용하고, 2의 거듭제곱 수를 분모로 사용합니다. 1/10의 경우, 이진 분수는 3602879701896397 / 2 ** 55 인데, 실제 값 1/10과 거의 같지만 정확히 같지는 않습니다.

많은 사용자는 값이 표시되는 방식 때문에 근사를 인식하지 못합니다. 파이썬은 기계에 저장된 이진 근삿값의 진짜 십진 값에 대한 십진 근삿값을 인쇄할 뿐입니다. 대부분 기계에서, 만약 파이썬이 0.1로 저장된 이진 근삿값의 진짜 십진 값을 출력한다면 다음과 같이 표시해야 합니다

>>> 0.1
0.1000000000000000055511151231257827021181583404541015625

이것은 대부분 사람이 유용하다고 생각하는 것보다 많은 숫자이므로, 파이썬은 반올림된 값을 대신 표시하여 숫자를 다룰만하게 만듭니다

>>> 1 / 10
0.1

인쇄된 결과가 정확히 1/10인 것처럼 보여도, 실제 저장된 값은 가장 가까운 표현 가능한 이진 소수임을 기억하세요.

흥미롭게도, 가장 가까운 근사 이진 소수를 공유하는 여러 다른 십진수가 있습니다. 예를 들어, 0.1 과 0.10000000000000001 및 0.1000000000000000055511151231257827021181583404541015625 는 모두 3602879701896397 / 2 ** 55 로 근사 됩니다. 이 십진 값들이 모두 같은 근삿값을 공유하기 때문에 eval(repr(x)) == x 불변을 그대로 유지하면서 그중 하나를 표시할 수 있습니다.

역사적으로, 파이썬 프롬프트와 내장 repr() 함수는 유효 숫자 17개의 숫자인 0.10000000000000001 을 선택합니다. 파이썬 3.1부터, 이제 파이썬(대부분 시스템에서)이 가장 짧은 것을 선택할 수 있으며, 단순히 0.1 만 표시합니다.

이것이 이진 부동 소수점의 본질임에 주목하세요: 파이썬의 버그는 아니며, 여러분의 코드에 있는 버그도 아닙니다. 하드웨어의 부동 소수점 산술을 지원하는 모든 언어에서 같은 종류의 것을 볼 수 있습니다 (일부 언어는 기본적으로 혹은 모든 출력 모드에서 차이를 표시하지 않을 수 있지만).

좀 더 만족스러운 결과를 얻으려면, 문자열 포매팅을 사용하여 제한된 수의 유효 숫자를 생성할 수 있습니다:

>>> format(math.pi, '.12g')  # give 12 significant digits
'3.14159265359'

>>> format(math.pi, '.2f')   # give 2 digits after the point
'3.14'

>>> repr(math.pi)
'3.141592653589793'

이것이, 진정한 의미에서, 환영임을 깨닫는 것이 중요합니다: 여러분은 단순히 진짜 기곗값의 표시 를 반올림하고 있습니다.

하나의 환상은 다른 환상을 낳을 수 있습니다. 예를 들어, 0.1은 정확히 1/10이 아니므로, 0.1의 세 개를 합한 것 역시 정확히 0.3이 아닙니다:

>>> .1 + .1 + .1 == .3
False

또한, 0.1은 1/10의 정확한 값에 더 가까워질 수 없고, 0.3도 3/10의 정확한 값에 더 가까워질 수 없으므로, round() 함수로 미리 반올림하는 것은 도움이 되지 않습니다:

>>> round(.1, 1) + round(.1, 1) + round(.1, 1) == round(.3, 1)
False

숫자를 의도한 정확한 값에 더 가깝게 만들 수는 없지만, round() 함수는 사후 반올림에 유용하여 부정확한 값을 가진 결과를 서로 비교할 수 있게 합니다:

>>> round(.1 + .1 + .1, 10) == round(.3, 10)
True

이진 부동 소수점 산술은 이처럼 많은 놀라움을 안겨줍니다. “0.1”의 문제는 아래의 “표현 오류” 섹션에서 자세하게 설명합니다. 부동 소수점의 위험 [http://www.lahey.com/float.htm] 은 다른 흔히 만나는 놀라움에 대해 더욱 완전한 설명을 제공합니다.

끝이 가까이 오면 말하듯이, “쉬운 답은 없습니다.” 아직, 부동 소수점수를 지나치게 경계할 필요는 없습니다! 파이썬 float 연산의 에러는 부동 소수점 하드웨어에서 상속된 것이고, 대부분 기계에서는 연산당 2**53분의 1을 넘지 않는 규모입니다. 이것은 대부분 작업에서 필요한 수준 이상입니다. 하지만, 십진 산술이 아니며 모든 float 연산에 새로운 반올림 에러가 발생할 수 있다는 점을 명심해야 합니다.

병리학적 경우가 존재하지만, 무심히 부동 소수점 산술을 사용하는 대부분은, 단순히 최종 결과를 기대하는 자릿수로 반올림해서 표시하면 기대하는 결과를 보게 될 것입니다. 보통 str() 만으로도 충분하며, 더 세밀하게 제어하려면 포맷 문자열 문법 에서 str.format() 메서드의 포맷 지정자를 보세요.

정확한 십진 표현이 필요한 사용 사례의 경우, 회계 응용 프로그램 및 고정밀 응용 프로그램에 적합한 십진 산술을 구현하는 decimal 모듈을 사용해보세요.

정확한 산술의 또 다른 형태는 유리수를 기반으로 산술을 구현하는 fractions 모듈에 의해 지원됩니다 (따라서 1/3과 같은 숫자는 정확하게 나타낼 수 있습니다).

부동 소수점 연산을 많이 하는 사용자면 Numerical Python 패키지와 SciPy 프로젝트에서 제공하는 수학 및 통계 연산을 위한 다른 많은 패키지를 살펴봐야 합니다. <https://scipy.org> 를 보세요.

파이썬은 여러분이 float의 정확한 값을 진짜로 알아야 하는 드문 경우를 지원할 수 있는 도구들을 제공합니다. float.as_integer_ratio() 메서드는 float의 값을 분수로 표현합니다:

>>> x = 3.14159
>>> x.as_integer_ratio()
(3537115888337719, 1125899906842624)

비율은 정확한 값이기 때문에, 원래 값을 손실 없이 다시 만드는 데 사용할 수 있습니다:

>>> x == 3537115888337719 / 1125899906842624
True

float.hex() 메서드는 float를 16진수(밑이 16이다)로 표현하는데, 컴퓨터에 저장된 정확한 값을 줍니다:

>>> x.hex()
'0x1.921f9f01b866ep+1'

이 정확한 16진수 표현은 float 값을 정확하게 재구성하는 데 사용할 수 있습니다:

>>> x == float.fromhex('0x1.921f9f01b866ep+1')
True

표현이 정확하므로, 파이썬의 다른 버전 에 걸쳐 값을 신뢰성 있게 이식하고 (플랫폼 독립성), 같은 형식을 지원하는 다른 언어(자바나 C99 같은)와 데이터를 교환하는 데 유용합니다.

또 다른 유용한 도구는 math.fsum() 함수입니다. 이 함수는 합산 동안 정밀도 상실을 완화합니다. 누적 합계에 값이 더해지면서 “잃어버린 숫자들”을 추적합니다. 최종 합계에 영향을 주는 지점까지 에러가 누적되지 않아서 전체적인 정확도에 차이를 만들 수 있습니다:

>>> sum([0.1] * 10) == 1.0
False
>>> math.fsum([0.1] * 10) == 1.0
True

15.1. 표현 오류

이 섹션에서는 “0.1” 예제를 자세히 설명하고, 이러한 사례에 대한 정확한 분석을 여러분이 직접 수행하는 방법을 보여줍니다. 이진 부동 소수점 표현에 대한 기본 지식이 있다고 가정합니다.

표현 오류 (Representation error) 는 일부 (실제로는, 대부분의) 십진 소수가 이진(밑 2) 소수로 정확하게 표현될 수 없다는 사실을 나타냅니다. 이것이 파이썬(또는 펄, C, C++, 자바, 포트란 및 기타 여러 언어)이 종종 여러분이 기대하는 정확한 십진수를 표시하지 않는 주된 이유입니다.

왜 그럴까? 1/10은 이진 소수로 정확히 표현할 수 없습니다. 오늘날 (2000년 11월) 거의 모든 기계는 IEEE-754 부동 소수점 산술을 사용하고, 거의 모든 플랫폼은 파이썬 float를 IEEE-754 “배정밀도”에 매핑합니다. 754 배정밀도는 53비트의 정밀도가 포함되어 있어서, 입력 시 컴퓨터는 0.1을 J/2**N 형태의 가장 가까운 분수로 변환하려고 노력합니다. 여기서 J 는 정확히 53비트를 포함하는 정수입니다.:

1 / 10 ~= J / (2**N)

를

J ~= 2**N / 10

로 다시 쓰고, J 가 정확히 53 비트(>= 2**52 이지만 < 2**53 입니다)임을 고려하면, N 의 최적값은 56입니다:

>>> 2**52 <=  2**56 // 10  < 2**53
True

즉, 56은 J 가 정확히 53비트가 되도록 만드는 N 의 유일한 값입니다. J 의 가능한 값 중 가장 좋은 것은 반올림한 몫입니다:

>>> q, r = divmod(2**56, 10)
>>> r
6

나머지가 10의 절반보다 크므로, 가장 가까운 근삿값은 올림 해서 얻어집니다:

>>> q+1
7205759403792794

따라서 754 배정밀도로 1/10 에 가장 가까운 근삿값은 다음과 같습니다:

7205759403792794 / 2 ** 56

분자와 분모를 둘로 나누면 다음과 같이 약분됩니다:

3602879701896397 / 2 ** 55

올림을 했기 때문에, 이것은 실제로 1/10 보다 약간 크다는 것에 유의하세요; 내림을 했다면, 몫이 1/10 보다 약간 작아졌을 것입니다. 그러나 어떤 경우에도 정확하게 1/10일 수는 없습니다!

따라서 컴퓨터는 결코 1/10을 “보지” 못합니다: 볼 수 있는 것은 위에서 주어진 정확한 분수, 얻을 수 있는 최선의 754 배정밀도 근삿값입니다:

>>> 0.1 * 2 ** 55
3602879701896397.0

그 분수에 10**55를 곱하면, 55개의 십진 숫자를 볼 수 있습니다.:

>>> 3602879701896397 * 10 ** 55 // 2 ** 55
1000000000000000055511151231257827021181583404541015625

이는 컴퓨터에 저장된 정확한 숫자가 십진수 0.1000000000000000055511151231257827021181583404541015625와 같음을 의미합니다. 전체 십진법 값을 표시하는 대신, 많은 언어(이전 버전의 파이썬 포함)는 결과를 17개의 유효숫자로 반올림합니다:

>>> format(0.1, '.17f')
'0.10000000000000001'

fractions 와 decimal 모듈은 이 계산을 쉽게 만듭니다:

>>> from decimal import Decimal
>>> from fractions import Fraction

>>> Fraction.from_float(0.1)
Fraction(3602879701896397, 36028797018963968)

>>> (0.1).as_integer_ratio()
(3602879701896397, 36028797018963968)

>>> Decimal.from_float(0.1)
Decimal('0.1000000000000000055511151231257827021181583404541015625')

>>> format(Decimal.from_float(0.1), '.17')
'0.10000000000000001'

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 자습서 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 자습서 »

|

16. 부록

16.1. 대화형 모드

16.1.1. 에러 처리

에러가 발생하면 인터프리터는 에러 메시지와 스택 트레이스를 인쇄합니다. 대화형 모드에서는 기본 프롬프트로 돌아갑니다; 파일로부터 입력이 왔을 때는, 스택 트레이스를 인쇄한 후 0이 아닌 종료 상태로 종료합니다. (try 문에서 except 절에 의해 처리되는 예외는 이 문맥에서 에러가 아닙니다.) 일부 에러는 무조건 치명적이며 0이 아닌 종료 상태의 종료를 유발합니다; 이것은 내부 불일치와 메모리 부족으로 인한 경우에 적용됩니다. 모든 에러 메시지는 표준 에러 스트림에 기록됩니다. 실행된 명령의 정상 출력은 표준 출력에 기록됩니다.

기본 또는 보조 프롬프트에 인터럽트 문자 (일반적으로 Control-C 또는 Delete)를 입력하면 입력을 취소하고 기본 프롬프트로 돌아갑니다. 1 명령어가 실행되는 동안 인터럽트를 입력하면 try 문에 의해 처리될 수 있는 KeyboardInterrupt 예외가 발생합니다.

16.1.2. 실행 가능한 파이썬 스크립트

BSD 스타일의 유닉스 시스템에서 파이썬 스크립트는 셸 스크립트처럼 직접 실행할 수 있게 만들 수 있습니다. 다음과 같은 줄

#!/usr/bin/env python3.5

(인터프리터가 사용자의 PATH 에 있다고 가정할 때)을 스크립트의 시작 부분에 넣고 파일에 실행 가능 모드를 줍니다. #! 는 반드시 파일의 처음 두 문자여야 합니다. 일부 플랫폼에서는 이 첫 번째 줄이 유닉스 스타일의 줄 종료 ('\n')로 끝나야 하며, 윈도우 줄 종료('\r\n')는 허락되지 않습니다. 파이썬에서 해시, 또는 파운드, 문자 '#' 는 주석을 시작하는 데 사용됩니다.

스크립트는 chmod 명령을 사용하여 실행 가능한 모드, 또는 권한, 을 부여받을 수 있습니다.

$ chmod +x myscript.py

윈도우 시스템에서는 “실행 가능 모드”라는 개념이 없습니다. 파이썬 설치 프로그램은 .py 파일을 python.exe``와 자동으로 연결하여, 파이썬 파일을 이중 클릭하면 스크립트로 실행합니다. 확장자는.pyw`` 일 수도 있습니다. 이 경우, 일반적으로 나타나는 콘솔 창은 표시되지 않습니다.

16.1.3. 대화형 시작 파일

파이썬을 대화형으로 사용할 때, 종종 인터프리터가 시작될 때마다 실행되는 표준 명령들이 있으면 편리합니다. PYTHONSTARTUP 환경 변수를 시작 명령이 들어있는 파일 이름으로 설정하면 됩니다. 이것은 유닉스 셸의 .profile 기능과 유사합니다.

이 파일은 대화형 세션에서만 읽히며, 파이썬이 스크립트에서 명령을 읽을 때나, /dev/tty 가 명령의 명시적 소스인 경우(대화형 세션처럼 동작한다)에는 읽지 않습니다. 대화형 명령이 실행되는 같은 이름 공간에서 실행되므로, 이 파일에서 정의하거나 임포트하는 객체들을 대화형 세션에서 정규화하지 않은 이름으로 사용할 수 있습니다. 이 파일에서 sys.ps1 및 sys.ps2 프롬프트를 변경할 수도 있습니다.

현재 디렉터리에서 추가 시작 파일을 읽으려면, 전역 시작 파일에서 if os.path.isfile('.pythonrc.py'): exec(open('.pythonrc.py').read()) 와 같은 코드를 사용해서 프로그램할 수 있습니다. 스크립트에서 시작 파일을 사용하려면 스크립트에서 명시적으로 수행해야 합니다:

import os
filename = os.environ.get('PYTHONSTARTUP')
if filename and os.path.isfile(filename):
    with open(filename) as fobj:
        startup_file = fobj.read()
    exec(startup_file)

16.1.4. 커스터마이제이션 모듈

파이썬은 커스터마이즈할 수 있는 두 가지 훅을 제공합니다: sitecustomize 와 usercustomize. 어떻게 작동하는지 보려면, 먼저 여러분의 사용자 site-packages 디렉터리의 위치를 찾아야 합니다. 파이썬을 시작하고 다음 코드를 실행합니다:

>>> import site
>>> site.getusersitepackages()
'/home/user/.local/lib/python3.5/site-packages'

이제 그 디렉터리에 usercustomize.py 라는 이름의 파일을 만들고 원하는 것들을 넣을 수 있습니다. 자동 임포트를 비활성화하는 -s 옵션으로 시작하지 않는 한, 이 파일은 모든 파이썬 실행에 영향을 줍니다.

sitecustomize 는 같은 방식으로 작동하지만, 일반적으로 전역 site-packages 디렉터리에 컴퓨터 관리자가 만들고, usercustomize 전에 임포트됩니다. 자세한 내용은 site 모듈의 설명서를 보세요.

각주

1

GNU Readline 패키지에 있는 문제가 이것을 방해할 수 있습니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 자습서 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

|

파이썬 설정 및 사용법

설명서의 이 부분은 여러 플랫폼에서 파이썬 환경을 설정하고, 인터프리터를 호출하며, 파이썬으로 작업하기 더 쉽게 만드는 것들에 관한 일반적인 정보를 다루는데 할당되었습니다.

1. 명령 줄과 환경

1.1. 명령 줄

1.1.1. 인터페이스 옵션

1.1.2. 일반 옵션

1.1.3. 기타 옵션

1.1.4. 사용해서는 안 되는 옵션

1.2. 환경 변수

1.2.1. 디버그 모드 변수

2. 유닉스 플랫폼에서 파이썬 사용하기

2.1. 최신 버전의 파이썬 내려받기와 설치

2.1.1. 리눅스

2.1.2. FreeBSD와 OpenBSD

2.1.3. OpenSolaris

2.2. 파이썬 빌드하기

2.3. 파이썬 관련 경로와 파일

2.4. 잡동사니

3. Using Python on Windows

3.1. The full installer

3.1.1. Installation steps

3.1.2. Removing the MAX_PATH Limitation

3.1.3. Installing Without UI

3.1.4. Installing Without Downloading

3.1.5. Modifying an install

3.2. The Microsoft Store package

3.2.1. Known Issues

3.3. The nuget.org packages

3.4. The embeddable package

3.4.1. Python Application

3.4.2. Embedding Python

3.5. Alternative bundles

3.6. Configuring Python

3.6.1. Excursus: Setting environment variables

3.6.2. Finding the Python executable

3.7. UTF-8 mode

3.8. Python Launcher for Windows

3.8.1. Getting started

3.8.1.1. From the command-line

3.8.1.2. Virtual environments

3.8.1.3. From a script

3.8.1.4. From file associations

3.8.2. Shebang Lines

3.8.3. Arguments in shebang lines

3.8.4. Customization

3.8.4.1. Customization via INI files

3.8.4.2. Customizing default Python versions

3.8.5. Diagnostics

3.9. Finding modules

3.10. Additional modules

3.10.1. PyWin32

3.10.2. cx_Freeze

3.10.3. WConio

3.11. Compiling Python on Windows

3.12. Other Platforms

4. 매킨토시에서 파이썬 사용하기

4.1. MacPython을 구하고 설치하기

4.1.1. 파이썬 스크립트를 실행하는 방법

4.1.2. GUI로 스크립트 실행하기

4.1.3. 구성

4.2. IDE

4.3. 추가 파이썬 패키지 설치하기

4.4. Mac에서의 GUI 프로그래밍

4.5. Mac에서 파이썬 응용 프로그램 배포하기

4.6. 기타 자원

5. Editors and IDEs

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 설정 및 사용법 »

|

1. 명령 줄과 환경

CPython 인터프리터는 명령 줄과 환경에서 다양한 설정을 찾습니다.

CPython implementation detail: 다른 구현의 명령 줄 체계는 다를 수 있습니다. 자세한 내용은 대안 구현들 참조하십시오.

1.1. 명령 줄

파이썬을 호출할 때 다음 옵션들을 지정할 수 있습니다:

python [-bBdEhiIOqsSuvVWx?] [-c command | -m module-name | script | - ] [args]

물론, 가장 일반적인 사용 사례는 간단한 스크립트 호출입니다:

python myscript.py

1.1.1. 인터페이스 옵션

인터프리터 인터페이스는 유닉스 셸의 인터페이스와 비슷하지만, 몇 가지 추가 호출 방법을 제공합니다:

tty 장치에 연결된 표준 입력으로 호출하면, 명령을 입력하라는 프롬프트를 준 후 EOF(파일 끝 문자, 유닉스에서는 Ctrl-D, 윈도우에서는 Ctrl-Z, Enter로 만들 수 있습니다)가 읽힐 때까지 실행합니다.

파일 이름 인자나 파일을 표준 입력으로 사용해서 호출하면, 해당 파일에서 스크립트를 읽고 실행합니다.

디렉터리 이름 인자로 호출되면, 해당 디렉터리에서 적절히 이름 붙은 스크립트를 읽고 실행합니다.

-c command 로 호출되면, command로 주어지는 파이썬 문장을 실행합니다. 여기서 command는 개행 문자로 구분된 여러 개의 문장을 포함할 수 있습니다. 선행 공백은 파이썬 문장에서 중요합니다!

-m module-name 으로 호출되면, 주어진 모듈을 파이썬 모듈 경로에서 찾은 후에 스크립트로 실행합니다.

비대화형 모드에서는, 실행하기 전에 전체 입력을 구문 분석합니다.

인터페이스 옵션은 인터프리터에 의해 소비되는 옵션의 목록을 종료합니다, 뒤따르는 모든 인자는 sys.argv 로 들어갑니다 – 첫 번째 요소, 서브 스크립트 0(sys.argv[0])은 프로그램 소스를 반영하는 문자열임에 유의하세요.

-c <command>

command 의 파이썬 코드를 실행합니다. command 는 개행 문자로 구분된 하나 이상의 문장일 수 있는데, 일반 모듈 코드에서와같이 선행 공백은 의미가 있습니다.

이 옵션을 주면, sys.argv 의 첫 번째 요소는 "-c" 가 되고, 현재 디렉터리를 sys.path 의 시작 부분에 추가합니다 (그 디렉터리에 있는 모듈을 최상위 모듈로 임포트 할 수 있게 합니다).

-m <module-name>

제공된 이름의 모듈을 sys.path 에서 검색하고 그 내용을 __main__ 모듈로서 실행합니다.

인자가 모듈 이름이기 때문에, 파일 확장자(.py)를 주지 않아야 합니다. 모듈 이름은 유효한 절대 파이썬 모듈 이름이어야 하지만, 구현이 항상 이를 강제하는 것은 아닙니다 (예를 들어, 하이픈을 포함하는 이름을 허락할 수도 있습니다).

패키지 이름(이름 공간 패키지 포함)도 허용됩니다. 일반 모듈 대신 패키지 이름이 제공되면, 인터프리터는 <pkg>.__main__ 을 메인 모듈로 실행합니다. 이 동작은 인터프리터에 스크립트 인자로 전달되는 디렉터리 및 zip 파일의 처리와 의도적으로 유사합니다.

참고

이 옵션은 내장 모듈이나 확장 모듈에는 사용될 수 없는데, 이것들은 파이썬 모듈 파일을 갖고 있지 않기 때문입니다. 그러나, 원래 소스 파일이 없는 사전 컴파일된 모듈에는 여전히 사용할 수 있습니다.

이 옵션을 주면, sys.argv 의 첫 번째 요소는 모듈 파일의 전체 경로가 됩니다 (모듈 파일을 찾는 동안에는 첫 번째 요소를 "-m" 으로 설정합니다). -c 옵션과 마찬가지로, 현재 디렉터리가 sys.path 의 시작 부분에 추가됩니다.

-I option can be used to run the script in isolated mode where sys.path contains neither the current directory nor the user’s site-packages directory. All PYTHON* environment variables are ignored, too.

많은 표준 라이브러리 모듈에는 스크립트로 실행할 때 호출되는 코드가 들어 있습니다. 한 예는 timeit 모듈입니다:

python -m timeit -s 'setup here' 'benchmarked code here'
python -m timeit -h # for details

더 보기

runpy.run_module()

파이썬 코드에서 직접 사용할 수 있는 동등한 기능

PEP 338 [https://www.python.org/dev/peps/pep-0338] – 모듈을 스크립트로 실행하기

버전 3.1에서 변경: __main__ 서브 모듈을 실행할 패키지 이름을 제공할 수 있습니다.

버전 3.4에서 변경: 이름 공간 패키지도 지원됩니다.

-

표준 입력(sys.stdin)에서 명령을 읽습니다. 표준 입력이 터미널이면, -i 가 묵시적으로 적용됩니다.

이 옵션을 주면, sys.argv 의 첫 번째 요소는 "-" 이 되고, 현재 디렉터리가 sys.path 의 처음에 추가됩니다.

<script>

script 에 담긴 파이썬 코드를 실행합니다. script 는 파이썬 파일이나 __main__.py 파일이 들어있는 디렉터리나 __main__.py 파일을 포함하는 zip 파일을 가리키는 파일 시스템 경로(절대나 상대)여야 합니다.

이 옵션을 주면, sys.argv 의 첫 번째 요소는 명령 줄에서 주어진 스크립트 이름이 됩니다.

스크립트 이름이 파이썬 파일을 직접 가리키면, 해당 파일을 포함하는 디렉터리가 sys.path 의 시작 부분에 추가되고, 파일은 __main__ 모듈로 실행됩니다.

스크립트 이름이 디렉터리 나 zip 파일을 가리키면, 스크립트 이름이 sys.path 의 시작 부분에 추가되고, 해당 위치의 __main__.py 파일을 __main__ 모듈로 실행합니다.

-I option can be used to run the script in isolated mode where sys.path contains neither the script’s directory nor the user’s site-packages directory. All PYTHON* environment variables are ignored, too.

더 보기

runpy.run_path()

파이썬 코드에서 직접 사용할 수 있는 동등한 기능

인터페이스 옵션을 주지 않으면, -i 가 묵시적으로 적용되고, sys.argv[0] 는 빈 문자열("")이 되고, 현재 디렉터리가 sys.path 의 처음에 추가됩니다. 또한, 플랫폼에서 사용 가능한 경우 (Readline 구성 를 참조하세요), 탭 완성 및 히스토리 편집이 자동으로 활성화됩니다.

더 보기

인터프리터 실행하기

버전 3.4에서 변경: 탭 완성과 히스토리 편집의 자동 활성화.

1.1.2. 일반 옵션

-?

-h

--help

모든 명령 줄 옵션에 대한 간단한 설명을 인쇄합니다.

-V

--version

파이썬 버전 번호를 출력하고 종료합니다. 출력 예는 다음과 같습니다:

Python 3.7.0b2+

두 번 지정하면, 다음과 같이 빌드에 관한 추가 정보를 인쇄합니다:

Python 3.7.0b2+ (3.7:0c076caaa8, Sep 22 2018, 12:04:24)
[GCC 6.2.0 20161005]

버전 3.6에 추가: -VV 옵션.

1.1.3. 기타 옵션

-b

bytes 나 bytearray 를 str과, bytes를 int와 비교할 때 경고를 합니다. 옵션이 두 번 주어지면 (-bb) 에러를 줍니다.

버전 3.5에서 변경: bytes 와 int 비교에도 적용됩니다.

-B

주어지면, 파이썬은 소스 모듈을 임포트 할 때 .pyc 파일을 쓰려고 하지 않습니다. PYTHONDONTWRITEBYTECODE 도 참조하십시오.

--check-hash-based-pycs default|always|never

해시 기반 .pyc 파일의 검증 동작을 제어합니다. 캐시된 바이트 코드 무효화를 참조하세요. default 로 설정하면, 검사형과 비검사형 해시 기반 바이트 코드 캐시 파일은 기본 의미에 따라 유효성이 검사됩니다. always 로 설정하면, 모든 해시 기반 .pyc 파일들은, 검사형과 비검사형을 가리지 않고, 해당 소스 파일에 대해 유효성이 검사됩니다. never 로 설정되면, 해시 기반 .pyc 파일은 해당 소스 파일에 대해 유효성이 검사되지 않습니다.

타임스탬프 기반 .pyc 파일의 의미는 이 옵션의 영향을 받지 않습니다.

-d

파서 디버깅 출력을 켭니다 (컴파일 옵션에 따라 전문가만을 위한 기능입니다). PYTHONDEBUG 도 참조하십시오.

-E

설정되었을 수 있는 모든 PYTHON* 환경 변수를 무시합니다, 예를 들어 PYTHONPATH 와 PYTHONHOME.

-i

스크립트가 첫 번째 인자로 전달되거나 -c 옵션이 사용되면, sys.stdin 가 터미널로 보이지 않을 때도, 스크립트나 명령을 실행한 후에 대화형 모드에 진입합니다. PYTHONSTARTUP 파일은 읽지 않습니다.

이것은 스크립트가 예외를 발생시킬 때 전역 변수나 스택 트레이스를 검사하는 데 유용할 수 있습니다. PYTHONINSPECT 도 참조하십시오.

-I

격리된 모드로 파이썬을 실행합니다. 이것은 또한 -E와 -s를 묵시적으로 적용합니다. 격리 모드에서 sys.path 는 스크립트 디렉터리나 사용자의 site-packages 디렉터리를 포함하지 않습니다. 모든 PYTHON* 환경 변수도 무시됩니다. 사용자가 악성 코드를 주입하는 것을 방지하기 위해 추가 제한이 부과될 수 있습니다.

버전 3.4에 추가.

-O

assert 문과 __debug__ 의 값에 대한 조건부 코드를 제거합니다. .pyc 확장자 앞에 .opt-1 을 추가하여 컴파일된 (바이트 코드) 파일의 이름을 구분합니다 (PEP 488 [https://www.python.org/dev/peps/pep-0488]을 참조하세요). PYTHONOPTIMIZE 도 참조하십시오.

버전 3.5에서 변경: PEP 488 [https://www.python.org/dev/peps/pep-0488] 에 따라 .pyc 파일명을 수정합니다.

-OO

-O를 적용하고 독스트링도 버립니다. .pyc 확장자 앞에 .opt-2 를 추가하여 컴파일 된(바이트 코드) 파일의 이름을 구분합니다 (참조 PEP 488 [https://www.python.org/dev/peps/pep-0488]을 참조하세요).

버전 3.5에서 변경: PEP 488 [https://www.python.org/dev/peps/pep-0488] 에 따라 .pyc 파일명을 수정합니다.

-q

대화형 모드에서도 저작권과 버전 메시지를 표시하지 않습니다.

버전 3.2에 추가.

-R

해시 무작위화를 켭니다. 이 옵션은 PYTHONHASHSEED 환경 변수가 0 으로 설정된 경우에만 효과가 있습니다, 해시 무작위화는 기본적으로 활성화되기 때문입니다.

이전 버전의 파이썬에서는, 이 옵션이 해시 무작위화를 켜서, str, bytes, datetime의 __hash__() 값이 예측할 수 없는 난수로 “솔트(salt)” 됩니다. 개별 파이썬 프로세스 내에서 상수로 유지되지만, 반복되는 파이썬 실행 간에는 예측할 수 없습니다.

해시 무작위화는 신중하게 선택된 입력으로 딕셔너리 구성의 성능을 최악의 O(n^2) 복잡도를 갖도록 만드는 서비스 거부에 대한 보호를 제공하기 위한 것입니다. 자세한 내용은 http://www.ocert.org/advisories/ocert-2011-003.html 을 참조하십시오.

PYTHONHASHSEED 는 해시 시드 시크릿에 고정값을 설정할 수 있게 합니다.

버전 3.7에서 변경: 이 옵션은 더는 무시되지 않습니다.

버전 3.2.3에 추가.

-s

사용자 site-packages 디렉터리 를 sys.path 에 추가하지 않습니다.

더 보기

PEP 370 [https://www.python.org/dev/peps/pep-0370] – 사용자별 site-packages 디렉터리

-S

site 모듈의 임포트와 이 모듈이 수반하는 sys.path 의 사이트 의존적 조작을 비활성화합니다. 또한 site 가 나중에 명시적으로 임포트될 때도 이 조작을 비활성화합니다 (조작하기를 원하면 site.main() 을 호출하십시오).

-u

stdout 과 stderr 스트림을 버퍼링하지 않도록 만듭니다. 이 옵션은 stdin 스트림에는 영향을 미치지 않습니다.

PYTHONUNBUFFERED 도 참조하세요.

버전 3.7에서 변경: stdout 과 stderr 스트림의 텍스트 계층은 이제 버퍼링 되지 않습니다.

-v

모듈이 초기화될 때마다 메시지를 인쇄하여, 로드된 위치(파일명이나 내장 모듈)를 표시합니다. 두 번 주어지면 (-vv), 모듈을 검색할 때 검사되는 각 파일에 대한 메시지를 인쇄합니다. 종료 시 모듈 정리에 대한 정보도 제공합니다. PYTHONVERBOSE 도 참조하십시오.

-W arg

경고 제어. 파이썬의 경고 장치는 기본적으로 sys.stderr 로 경고 메시지를 인쇄합니다. 일반적인 경고 메시지의 형식은 다음과 같습니다:

file:line: category: message

기본적으로, 각 경고는 발생하는 각 소스 행마다 한 번씩 인쇄됩니다. 이 옵션은 경고 인쇄 빈도를 제어합니다.

다중 -W 옵션이 주어질 수 있습니다; 경고가 두 개 이상의 옵션과 일치하면 마지막으로 일치하는 옵션의 액션이 수행됩니다. 유효하지 않은 -W 옵션은 무시됩니다 (하지만, 최초의 경고가 발생할 때 유효하지 않은 옵션에 관한 경고 메시지가 출력됩니다).

경고는 PYTHONWARNINGS 환경 변수와 파이썬 프로그램 내에서 warnings 모듈을 사용해서 제어할 수도 있습니다.

가장 단순한 설정은 프로세스가 만드는 모든 경고에 무조건 특정 액션을 적용합니다 (그렇지 않으면 기본적으로 무시되는 경고조차도):

-Wdefault  # Warn once per call location
-Werror    # Convert to exceptions
-Walways   # Warn every time
-Wmodule   # Warn once per calling module
-Wonce     # Warn once per Python process
-Wignore   # Never warn

액션 이름은 원하면 줄일 수 있고 (예, -Wi, -Wd, -Wa, -We), 인터프리터는 이를 적절한 액션 이름으로 해석합니다.

자세한 내용은 The Warnings Filter와 Describing Warning Filters를 참조하십시오.

-x

소스의 첫 번째 줄을 건너 뛰어서, 유닉스 이외의 형식의 #!cmd 을 사용할 수 있게 합니다. 이것은 DOS 전용 핵(hack)을 위한 것입니다.

-X

다양한 구현 특정 옵션을 위해 예약되어 있습니다. CPython은 현재 다음과 같은 가능한 값을 정의합니다:

-X faulthandler 는 faulthandler 를 활성화합니다;

-X showrefcount 는 프로그램이 끝나거나 대화형 인터프리터에서 각각의 문장 뒤에서, 총 참조 카운트와 사용된 메모리 블록의 수를 출력합니다. 이것은 디버그 빌드에서만 작동합니다.

-X tracemalloc 은 tracemalloc 모듈을 사용하여 파이썬 메모리 할당 추적을 시작합니다. 기본적으로, 가장 최근 프레임만 추적의 트레이스백에 저장됩니다. NFRAME 프레임의 트레이스백 한도로 추적을 시작하려면 -X tracemalloc=NFRAME 을 사용하십시오. 자세한 정보는 tracemalloc.start() 를 참조하십시오.

-X showalloccount 은 프로그램이 끝날 때 형별로 할당된 객체의 총수를 출력합니다. 이것은 파이썬이 COUNT_ALLOCS 이 정의 된 상태로 빌드되었을 때만 작동합니다.

-X int_max_str_digits configures the integer string conversion length limitation. See also PYTHONINTMAXSTRDIGITS.

-X importtime 은 각 임포트가 얼마나 오래 걸렸는지 보여줍니다. 모듈 이름, 누적 시간(중첩된 임포트 포함), 자체 시간(중첩 임포트 제외)을 표시합니다. 다중 스레드 응용 프로그램에서 출력이 깨질 수 있음에 유의하십시오. 일반적인 사용법은 python3 -X importtime -c 'import asyncio' 입니다. PYTHONPROFILEIMPORTTIME 도 참조하십시오.

-X dev: CPython의 “개발 모드”를 활성화해서, 기본적으로 활성화하기에는 너무 비싼 추가적인 실행시간 검사를 도입합니다. 코드가 올바르면 기본값보다 더 상세하지는 않아야 합니다: 문제가 감지되었을 때만 새로운 경고가 발생합니다. 개발자 모드의 효과는 다음과 같습니다:

-W default 처럼, default 경고 필터를 추가합니다.

메모리 할당자에 디버그 훅을 설치합니다: PyMem_SetupDebugHooks() C 함수를 참조하십시오.

충돌 시에 파이썬 트레이스백을 덤프하도록 faulthandler 모듈을 활성화합니다.

asyncio 디버그 모드 를 활성화합니다.

Set the dev_mode attribute of sys.flags to True.

-X utf8 은 운영 체제 인터페이스를 위한 UTF-8 모드를 활성화하여, 기본 로케일 인식 모드를 대체합니다. -X utf8=0 은 명시적으로 UTF-8 모드를 비활성화합니다 (그렇지 않으면 자동으로 활성화될 때조차). 자세한 내용은 PYTHONUTF8 을 참조하십시오.

또한 sys._xoptions 딕셔너리를 통해 임의의 값을 전달하고 조회할 수 있도록 합니다.

버전 3.2에서 변경: -X 옵션이 추가되었습니다.

버전 3.3에 추가: -X faulthandler 옵션.

버전 3.4에 추가: -X showrefcount 와 -X tracemalloc 옵션.

버전 3.6에 추가: -X showalloccount 옵션.

버전 3.7에 추가: -X importtime, -X dev, -X utf8 옵션.

버전 3.7.14에 추가: The -X int_max_str_digits option.

1.1.4. 사용해서는 안 되는 옵션

-J

Jython [http://www.jython.org/] 이 사용하기 위해 예약되었습니다.

1.2. 환경 변수

이 환경 변수들은 파이썬의 동작에 영향을 주며, -E와 -I 이외의 명령 줄 스위치보다 먼저 처리됩니다. 충돌하면 명령 줄 스위치가 환경 변수에 우선하는 것이 관례입니다.

PYTHONHOME

표준 파이썬 라이브러리의 위치를 변경합니다. 기본적으로, 라이브러리는 prefix/lib/pythonversion과 exec_prefix/lib/pythonversion에서 검색되는데, prefix 와 exec_prefix 는 설치 의존적인 디렉터리이고, 둘 다 기본값은 /usr/local 입니다.

PYTHONHOME 이 하나의 디렉터리로 설정되면, 그 값은 prefix 와 exec_prefix 를 모두 대체합니다. 이들에 대해 다른 값을 지정하려면, PYTHONHOME 을 prefix:exec_prefix 로 설정하십시오.

PYTHONPATH

모듈 파일의 기본 검색 경로를 보강합니다. 형식은 셸의 PATH 와 같습니다: 하나 이상의 디렉터리 경로명이 os.pathsep (예를 들어, 유닉스에서는 콜론, 윈도우에서는 세미콜론) 로 구분됩니다. 존재하지 않는 디렉터리는 조용히 무시됩니다.

일반 디렉터리 외에도, 개별 PYTHONPATH 엔트리는 순수 파이썬 모듈(소스 또는 컴파일된 형식)을 포함하는 zip 파일을 가리킬 수 있습니다. 확장 모듈은 zip 파일에서 임포트될 수 없습니다.

기본 검색 경로는 설치 의존적이지만, 일반적으로 prefix/lib/pythonversion으로 시작합니다 (위의 PYTHONHOME 을 참조하세요). 항상 PYTHONPATH 에 추가됩니다.

위에서 설명한 대로 인터페이스 옵션 하에서는 PYTHONPATH 앞에 검색 경로에 추가 디렉터리가 삽입됩니다. 검색 경로는 파이썬 프로그램 내에서 sys.path 변수로 조작할 수 있습니다.

PYTHONSTARTUP

이것이 읽을 수 있는 파일의 이름이면, 첫 번째 프롬프트가 대화형 모드에 표시되기 전에, 해당 파일의 파이썬 명령이 실행됩니다. 이 파일은 대화형 명령이 실행되는 것과 같은 이름 공간에서 실행되므로, 여기에서 정의되거나 임포트 한 객체를 대화형 세션에서 그대로 사용할 수 있습니다. 이 파일에서 프롬프트 sys.ps1 과 sys.ps2 와 훅 sys.__interactivehook__ 도 바꿀 수 있습니다.

PYTHONOPTIMIZE

비어 있지 않은 문자열로 설정하면 -O 옵션을 지정하는 것과 같습니다. 정수로 설정하면, -O를 여러 번 지정하는 것과 같습니다.

PYTHONBREAKPOINT

설정되면, 점으로 구분된 경로 표기법을 사용하여 콜러블의 이름을 지정합니다. 콜러블을 포함하는 모듈이 임포트 된 후에 콜러블은, 내장 breakpoint() 에 의해 호출되는 sys.breakpointhook() 의 기본 구현이 실행합니다. 설정되지 않았거나 빈 문자열로 설정하면, 값 “pdb.set_trace”와 동등합니다. 문자열 “0”으로 설정하면, sys.breakpointhook() 의 기본 구현은 아무것도 하지 않고 즉시 반환합니다.

버전 3.7에 추가.

PYTHONDEBUG

비어 있지 않은 문자열로 설정하면, -d 옵션을 지정하는 것과 같습니다. 정수로 설정하면, -d를 여러 번 지정하는 것과 같습니다.

PYTHONINSPECT

비어 있지 않은 문자열로 설정하면, -i 옵션을 지정하는 것과 같습니다.

이 변수는 프로그램 종료 시 검사 모드를 강제하기 위해, os.environ 을 사용해서 파이썬 코드에 의해 수정될 수도 있습니다.

PYTHONUNBUFFERED

비어 있지 않은 문자열로 설정하면, -u 옵션을 지정하는 것과 같습니다.

PYTHONVERBOSE

비어 있지 않은 문자열로 설정하면, -v 옵션을 지정하는 것과 같습니다. 정수로 설정하면 -v를 여러 번 지정하는 것과 같습니다.

PYTHONCASEOK

설정되면, 파이썬은 import 문에서 대소 문자를 무시합니다. 이것은 윈도우와 OS X에서만 작동합니다.

PYTHONDONTWRITEBYTECODE

비어 있지 않은 문자열로 설정되면, 파이썬은 소스 모듈을 임포트 할 때 .pyc 파일을 쓰지 않습니다. 이는 -B 옵션을 지정하는 것과 같습니다.

PYTHONHASHSEED

이 변수가 설정되어 있지 않거나 random 으로 설정되면, str, bytes, datetime 객체의 해시 시드에 난수가 사용됩니다.

PYTHONHASHSEED 가 정숫값으로 설정되면, 해시 무작위화가 적용되는 형의 hash()를 생성하기 위한 고정 시드로 사용됩니다.

목적은 인터프리터 자체에 대한 셀프 테스트와 같은 이유로 반복 가능한 해싱을 허용하거나, 파이썬 프로세스 클러스터가 해시값을 공유하도록 허용하는 것입니다.

정수는 [0,4294967295] 범위의 십진수여야 합니다. 값 0을 지정하면 해시 무작위화가 비활성화됩니다.

버전 3.2.3에 추가.

PYTHONINTMAXSTRDIGITS

If this variable is set to an integer, it is used to configure the interpreter’s global integer string conversion length limitation.

버전 3.7.14에 추가.

PYTHONIOENCODING

인터프리터를 실행하기 전에 이것이 설정되면, stdin/stdout/stderr에 사용되는 인코딩을 대체합니다. 문법은 encodingname:errorhandler 형식입니다. encodingname 과 :errorhandler 부분은 모두 선택 사항이며 str.encode() 에서와 같은 의미입니다.

stderr의 경우, :errorhandler 부분은 무시됩니다; 처리기는 항상 'backslashreplace' 입니다.

버전 3.4에서 변경: encodingname 부분은 이제 선택적입니다.

버전 3.6에서 변경: Windows에서, PYTHONLEGACYWINDOWSSTDIO 도 지정하지 않는 한, 대화형 콘솔 버퍼에서 이 변수로 지정된 인코딩이 무시됩니다. 표준 스트림을 통해 리디렉션 된 파일과 파이프는 영향을 받지 않습니다.

PYTHONNOUSERSITE

설정되면, 파이썬은 사용자 site-packages 디렉터리 를 sys.path 에 추가하지 않습니다.

더 보기

PEP 370 [https://www.python.org/dev/peps/pep-0370] – 사용자별 site-packages 디렉터리

PYTHONUSERBASE

python setup.py install --user 에서 사용자 site-packages 디렉터리 의 경로와 Distutils 설치 경로 를 계산하기 위해 사용되는 사용자 베이스 디렉터리 를 정의합니다.

더 보기

PEP 370 [https://www.python.org/dev/peps/pep-0370] – 사용자별 site-packages 디렉터리

PYTHONEXECUTABLE

이 환경 변수가 설정되면, sys.argv[0] 는 C 런타임을 통해 얻은 값 대신에 이 값으로 설정됩니다. 맥 OS X에서만 작동합니다.

PYTHONWARNINGS

-W 옵션과 동등합니다. 쉼표로 구분된 문자열로 설정하면, -W를 여러 번 지정하는 것과 같습니다. 목록의 뒷부분에 있는 필터는 목록의 이전 필터보다 우선합니다.

가장 단순한 설정은 프로세스가 만드는 모든 경고에 무조건 특정 액션을 적용합니다 (그렇지 않으면 기본적으로 무시되는 경고조차도):

PYTHONWARNINGS=default  # Warn once per call location
PYTHONWARNINGS=error    # Convert to exceptions
PYTHONWARNINGS=always   # Warn every time
PYTHONWARNINGS=module   # Warn once per calling module
PYTHONWARNINGS=once     # Warn once per Python process
PYTHONWARNINGS=ignore   # Never warn

자세한 내용은 The Warnings Filter와 Describing Warning Filters를 참조하십시오.

PYTHONFAULTHANDLER

이 환경 변수가 비어 있지 않은 문자열로 설정되면, faulthandler.enable() 이 시작 시에 호출됩니다: 파이썬 트레이스백을 덤프하는 SIGSEGV, SIGFPE, SIGABRT, SIGBUS 그리고 SIGILL 시그널 처리기를 설치합니다. 이는 -X faulthandler 옵션과 동등합니다.

버전 3.3에 추가.

PYTHONTRACEMALLOC

이 환경 변수가 비어 있지 않은 문자열로 설정되면, tracemalloc 모듈을 사용하여 파이썬 메모리 할당 추적을 시작합니다. 변수의 값은 추적의 트레이스백에 저장되는 최대 프레임 수입니다. 예를 들어, PYTHONTRACEMALLOC=1 은 가장 최근의 프레임만을 저장합니다. 자세한 정보는 tracemalloc.start() 를 참조하십시오.

버전 3.4에 추가.

PYTHONPROFILEIMPORTTIME

이 환경 변수가 비어 있지 않은 문자열로 설정되면, 파이썬은 각 임포트에 걸리는 시간을 보여줍니다. 이는 명령 줄에서 -X importtime 을 설정하는 것과 정확히 같습니다.

버전 3.7에 추가.

PYTHONASYNCIODEBUG

이 환경 변수가 비어 있지 않은 문자열로 설정되면, asyncio 모듈의 디버그 모드 를 활성화합니다.

버전 3.4에 추가.

PYTHONMALLOC

파이썬 메모리 할당자를 설정하거나 디버그 훅을 설치합니다.

파이썬이 사용하는 메모리 할당자를 설정합니다:

default: 기본 메모리 할당자 를 사용합니다.

malloc: 모든 영역(PYMEM_DOMAIN_RAW, PYMEM_DOMAIN_MEM, PYMEM_DOMAIN_OBJ)에서 C 라이브러리의 malloc() 함수를 사용합니다.

pymalloc: PYMEM_DOMAIN_MEM과 PYMEM_DOMAIN_OBJ 영역에서 pymalloc 할당자 를 사용하고, PYMEM_DOMAIN_RAW 영역에서 malloc() 함수를 사용합니다.

디버그 훅을 설치합니다:

debug: 기본 메모리 할당자 위에 디버그 훅을 설치합니다.

malloc_debug: same as malloc but also install debug hooks.

pymalloc_debug: same as pymalloc but also install debug hooks.

기본 메모리 할당자 와 PyMem_SetupDebugHooks() 함수(파이썬 메모리 할당자에 디버그 훅을 설치합니다)도 참조하세요.

버전 3.7에서 변경: "default" 할당자를 추가했습니다.

버전 3.6에 추가.

PYTHONMALLOCSTATS

비어 있지 않은 문자열로 설정되면, 파이썬은 새로운 pymalloc 객체 영역이 생성될 때마다, 그리고 종료할 때 pymalloc 메모리 할당자 의 통계를 인쇄합니다.

PYTHONMALLOC 환경 변수를 사용하여 C 라이브러리의 malloc() 할당자를 강제로 사용하거나, pymalloc 지원 없이 파이썬을 구성하면, 이 변수는 무시됩니다.

버전 3.6에서 변경: 이 변수는 이제 배포 모드로 컴파일된 파이썬에서도 사용할 수 있습니다. 이제 빈 문자열로 설정하면 효과가 없습니다.

PYTHONLEGACYWINDOWSFSENCODING

비어 있지 않은 문자열로 설정하면, 기본 파일 시스템 인코딩과 에러 모드를 3.6 이전의 값인 ‘mbcs’와 ‘replace’로 각각 되돌립니다. 그렇지 않으면, 새 기본값 ‘utf-8’과 ‘surrogatepass’가 사용됩니다.

이것은 또한 실행 시간에 sys._enablelegacywindowsfsencoding() 으로 활성화 될 수 있습니다.

가용성: 윈도우.

버전 3.6에 추가: 자세한 내용은 PEP 529 [https://www.python.org/dev/peps/pep-0529]를 참조하십시오.

PYTHONLEGACYWINDOWSSTDIO

비어 있지 않은 문자열로 설정하면, 새 콘솔 입력기와 출력기를 사용하지 않습니다. 이것은 유니코드 문자가 utf-8을 사용하는 대신 활성 콘솔 코드 페이지에 따라 인코딩됨을 의미합니다.

이 변수는 표준 스트림이 콘솔 버퍼를 참조하는 대신 리디렉트 된 (파일 또는 파이프로) 경우 무시됩니다.

가용성: 윈도우.

버전 3.6에 추가.

PYTHONCOERCECLOCALE

값 0 으로 설정하면, 주 파이썬 명령 줄 응용 프로그램이 레거시 ASCII 기반 C와 POSIX 로케일을 보다 유능한 UTF-8 기반 대안으로 강제 변환하지 않습니다.

이 변수가 설정되지 않고 (또는 0 이외의 값으로 설정되고), 환경 변수에 우선하는 LC_ALL 로케일도 설정되지 않고, LC_CTYPE 범주에 대해 보고되는 현재 로케일이 기본 C 로케일이거나 명시적인 ASCII 기반의 POSIX 로케일이면, 파이썬 CLI는 인터프리터 런타임을 로드하기 전에 LC_CTYPE 범주에 대해 다음 로케일을 나열된 순서대로 구성하려고 시도합니다:

C.UTF-8

C.utf8

UTF-8

이러한 로케일 범주 중 하나를 설정하는 데 성공하면, 파이썬 런타임이 초기화되기 전에 LC_CTYPE 환경 변수도 현재 프로세스 환경에서 적절히 설정됩니다. 이렇게 하면 인터프리터 자신과 같은 프로세스에서 실행되는 다른 로케일 인식 구성 요소(가령 GNU readline 라이브러리)가 볼 수 있는 것에 더해, 갱신된 설정을 현재 C 로케일이 아닌 환경을 조회하는 연산(가령 파이썬 자체의 locale.getdefaultlocale())뿐만 아니라, 자식 프로세스에서도 (이 프로세스가 파이썬 인터프리터를 실행하는지에 관계없이) 볼 수 있습니다.

이러한 로케일 중 하나를 구성하면 (명시적으로나 위의 묵시적 로케일 강제 변경을 통해) sys.stdin 과 sys.stdout 에 대해 surrogateescape 에러 처리기 를 자동으로 활성화합니다 (sys.stderr 는 다른 로케일에서처럼 backslashreplace 를 계속 사용합니다). 이 스트림 처리 동작은 평소처럼 PYTHONIOENCODING을 사용하여 대체할 수 있습니다.

디버깅을 위해, PYTHONCOERCECLOCALE=warn 을 설정하면, 로케일 강제 변경이 일어나거나, 그렇지 않고 강제 변경을 유발할 로케일이 파이썬 런타임이 초기화될 때 여전히 활성 상태면 파이썬은 stderr 로 경고 메시지를 보냅니다.

또한, 로케일 강제 변환이 비활성화되거나 적절한 대상 로케일을 찾지 못할 때도, 레거시 ASCII 기반 로케일에서 PYTHONUTF8 은 기본적으로 활성화됨에 유의하십시오. 인터프리터가 시스템 인터페이스에 대해 UTF-8 대신에 ASCII 를 사용하게 하려면, 두 가지 기능을 모두 비활성화시켜야 합니다.

가용성: 유닉스.

버전 3.7에 추가: 자세한 내용은 PEP 538 [https://www.python.org/dev/peps/pep-0538]을 참조하십시오.

PYTHONDEVMODE

이 환경 변수가 비어 있지 않은 문자열로 설정되면, CPython “개발 모드”를 활성화합니다. -X dev 옵션을 보십시오.

버전 3.7에 추가.

PYTHONUTF8

1 로 설정하면, 인터프리터의 UTF-8 모드가 활성화됩니다. 이 모드에서는 현재 로케일 설정에 상관없이, 시스템 인터페이스의 텍스트 인코딩으로 UTF-8 이 사용됩니다.

이는 다음을 의미합니다:

sys.getfilesystemencoding() 은 'UTF-8' 을 반환합니다 (로케일 인코딩은 무시됩니다).

locale.getpreferredencoding() 은 'UTF-8' 을 반환합니다 (로케일 인코딩은 무시되고, 함수의 do_setlocale 매개 변수는 아무런 효과가 없습니다).

sys.stdin, sys.stdout, sys.stderr 모두 텍스트 인코딩으로 UTF-8을 사용하고, sys.stdin 과 sys.stdout 은 surrogateescape 에러 처리기 가 활성화됩니다 (sys.stderr 은 기본 로케일 인식 모드와 같이 backslashreplace 를 계속 사용합니다)

이러한 하위 수준 API의 변경으로 인해, 다른 상위 수준 API도 다른 기본 동작을 수행합니다:

명령 줄 인자, 환경 변수 및 파일명은 UTF-8 인코딩을 사용하여 텍스트로 디코딩됩니다.

os.fsdecode()와 os.fsencode() 는 UTF-8 인코딩을 사용합니다.

open(), io.open(), codecs.open() 은 기본적으로 UTF-8 인코딩을 사용합니다. 그러나, 이들은 기본적으로 여전히 strict 에러 처리기를 사용하므로, 바이너리 파일을 텍스트 모드로 열려고 하면 말도 안 되는 데이터가 생성되는 대신 예외가 발생합니다.

UTF-8 모드에서 표준 스트림 설정은 PYTHONIOENCODING 의해 대체될 수 있습니다 (기본 로케일 인식 모드에서와 마찬가지로).

0 으로 설정하면, 인터프리터는 기본 로케일 인식 모드로 실행됩니다.

다른 모든 비어 있지 않은 문자열로 설정하면, 인터프리터를 초기화하는 동안 에러가 발생합니다.

이 환경 변수가 전혀 설정되지 않으면, 인터프리터는 현재 로케일이 레거시 ASCII 기반 로케일(PYTHONCOERCECLOCALE 에서 설명하는 것처럼)로 식별되고, 로케일 강제 변경이 비활성화되거나 실패하지 지 않는 한, 인터프리터는 현재 로케일 설정을 사용합니다. 이러한 레거시 로케일에서, 명시적으로 그렇게 하지 말라고 지시하지 않는 한, 인터프리터는 기본적으로 UTF-8 모드를 활성화합니다.

-X utf8 옵션으로도 사용 가능합니다.

버전 3.7에 추가: 자세한 내용은 PEP 540 [https://www.python.org/dev/peps/pep-0540]을 참조하십시오.

1.2.1. 디버그 모드 변수

이 변수들을 설정하는 것은 파이썬의 디버그 빌드에서만 효과가 있습니다. 즉, 파이썬이 --with-pydebug 빌드 옵션으로 구성되었어야 합니다.

PYTHONTHREADDEBUG

설정되면, 파이썬은 스레딩 디버그 정보를 인쇄합니다.

PYTHONDUMPREFS

설정되면, 파이썬은 인터프리터를 종료한 후에도 살아있는 객체와 참조 카운트를 덤프합니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 설정 및 사용법 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 설정 및 사용법 »

|

2. 유닉스 플랫폼에서 파이썬 사용하기

2.1. 최신 버전의 파이썬 내려받기와 설치

2.1.1. 리눅스

파이썬은 대부분 리눅스 배포판에 사전 설치되어 있으며, 다른 모든 곳에서 패키지로 사용할 수 있습니다. 그러나 배포판 패키지에 없는 어떤 기능을 사용하고 싶을 수 있습니다. 소스에서 최신 버전의 파이썬을 쉽게 컴파일할 수 있습니다.

파이썬이 미리 설치되어 있지 않고 저장소에도 없으면, 여러분 자신의 배포를 위한 패키지를 쉽게 만들 수 있습니다. 다음 링크를 살펴보십시오:

더 보기

https://www.debian.org/doc/manuals/maint-guide/first.en.html

데비안 사용자용

https://en.opensuse.org/Portal:Packaging

OpenSuse 사용자용

https://docs-old.fedoraproject.org/en-US/Fedora_Draft_Documentation/0.1/html/RPM_Guide/ch-creating-rpms.html

Fedora 사용자용

http://www.slackbook.org/html/package-management-making-packages.html

Slackware 사용자용

2.1.2. FreeBSD와 OpenBSD

FreeBSD 사용자, 패키지를 추가하려면 이렇게 하십시오:

pkg install python3

OpenBSD 사용자, 패키지를 추가하려면 이렇게 하십시오:

pkg_add -r python

pkg_add ftp://ftp.openbsd.org/pub/OpenBSD/4.2/packages/<insert your architecture here>/python-<version>.tgz

예를 들어 i386 사용자는 이렇게 파이썬 2.5.1 버전을 얻습니다:

pkg_add ftp://ftp.openbsd.org/pub/OpenBSD/4.2/packages/i386/python-2.5.1p2.tgz

2.1.3. OpenSolaris

OpenCSW [https://www.opencsw.org/]에서 파이썬을 얻을 수 있습니다. 다양한 버전의 파이썬이 있으며, 예를 들어 pkgutil -i python27로 설치할 수 있습니다.

2.2. 파이썬 빌드하기

CPython을 직접 컴파일하려면, 먼저 소스 [https://www.python.org/downloads/source/]를 얻습니다. 최신 버전의 소스를 내려받거나 새로 clone [https://devguide.python.org/setup/#getting-the-source-code] 할 수 있습니다. (패치에 이바지하려면 clone이 필요합니다.)

빌드 프로세스는 일반적으로 다음과 같은 호출로 구성됩니다

./configure
make
make install

특정 유닉스 플랫폼에 대한 구성 옵션과 주의 사항은 파이썬 소스 트리의 루트에 있는 README.rst [https://github.com/python/cpython/tree/3.7/README.rst] 파일에 광범위하게 설명되어있습니다.

경고

make install은 python3 바이너리를 덮어쓰거나 가장 할 수 있습니다. 따라서 make altinstall을 make install 대신 권장하는데, exec_prefix/bin/pythonversion 만 설치하기 때문입니다.

2.3. 파이썬 관련 경로와 파일

이는 지역 설치 규칙에 따라 달라질 수 있습니다; prefix (${prefix}) 와 exec_prefix (${exec_prefix})는 설치에 따라 다르며 GNU 소프트웨어처럼 해석되어야 합니다; 이것들은 같을 수도 있습니다.

예를 들어, 대부분 리눅스 시스템에서, 기본값은 모두 /usr입니다.

파일/디렉터리

의미

exec_prefix/bin/python3

인터프리터의 권장 위치.

prefix/lib/pythonversion, exec_prefix/lib/pythonversion

표준 모듈을 포함하는 디렉터리의 권장 위치.

prefix/include/pythonversion, exec_prefix/include/pythonversion

파이썬 확장을 개발하고 인터프리터를 내장하는 데 필요한 인클루드 파일을 포함하는 디렉터리의 권장 위치.

2.4. 잡동사니

유닉스에서 파이썬 스크립트를 쉽게 사용하려면, 실행 파일로 만들어야 합니다. 예를 들어, 이렇게

$ chmod +x script

그리고, 스크립트의 상단에 적절한 셔뱅(Shebang) 줄을 넣습니다. 좋은 선택은 대개 이렇습니다

#!/usr/bin/env python3

이것은 PATH 전체에서 파이썬 인터프리터를 검색합니다. 그러나, 일부 유닉스에는 env 명령이 없을 수 있으므로, 인터프리터 경로로 /usr/bin/python3를 하드 코딩해야 할 수 있습니다.

파이썬 스크립트에서 셸 명령을 사용하려면, subprocess 모듈을 보십시오.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 설정 및 사용법 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 설정 및 사용법 »

|

3. Using Python on Windows

This document aims to give an overview of Windows-specific behaviour you should know about when using Python on Microsoft Windows.

Unlike most Unix systems and services, Windows does not include a system supported installation of Python. To make Python available, the CPython team has compiled Windows installers (MSI packages) with every release [https://www.python.org/download/releases/] for many years. These installers are primarily intended to add a per-user installation of Python, with the core interpreter and library being used by a single user. The installer is also able to install for all users of a single machine, and a separate ZIP file is available for application-local distributions.

As specified in PEP 11 [https://www.python.org/dev/peps/pep-0011], a Python release only supports a Windows platform while Microsoft considers the platform under extended support. This means that Python 3.7 supports Windows Vista and newer. If you require Windows XP support then please install Python 3.4.

There are a number of different installers available for Windows, each with certain benefits and downsides.

The full installer contains all components and is the best option for developers using Python for any kind of project.

The Microsoft Store package is a simple installation of Python that is suitable for running scripts and packages, and using IDLE or other development environments. It requires Windows 10, but can be safely installed without corrupting other programs. It also provides many convenient commands for launching Python and its tools.

The nuget.org packages are lightweight installations intended for continuous integration systems. It can be used to build Python packages or run scripts, but is not updateable and has no user interface tools.

The embeddable package is a minimal package of Python suitable for embedding into a larger application.

3.1. The full installer

3.1.1. Installation steps

Four Python 3.7 installers are available for download - two each for the 32-bit and 64-bit versions of the interpreter. The web installer is a small initial download, and it will automatically download the required components as necessary. The offline installer includes the components necessary for a default installation and only requires an internet connection for optional features. See Installing Without Downloading for other ways to avoid downloading during installation.

After starting the installer, one of two options may be selected:

If you select “Install Now”:

You will not need to be an administrator (unless a system update for the C Runtime Library is required or you install the Python Launcher for Windows for all users)

Python will be installed into your user directory

The Python Launcher for Windows will be installed according to the option at the bottom of the first page

The standard library, test suite, launcher and pip will be installed

If selected, the install directory will be added to your PATH

Shortcuts will only be visible for the current user

Selecting “Customize installation” will allow you to select the features to install, the installation location and other options or post-install actions. To install debugging symbols or binaries, you will need to use this option.

To perform an all-users installation, you should select “Customize installation”. In this case:

You may be required to provide administrative credentials or approval

Python will be installed into the Program Files directory

The Python Launcher for Windows will be installed into the Windows directory

Optional features may be selected during installation

The standard library can be pre-compiled to bytecode

If selected, the install directory will be added to the system PATH

Shortcuts are available for all users

3.1.2. Removing the MAX_PATH Limitation

Windows historically has limited path lengths to 260 characters. This meant that paths longer than this would not resolve and errors would result.

In the latest versions of Windows, this limitation can be expanded to approximately 32,000 characters. Your administrator will need to activate the “Enable Win32 long paths” group policy, or set the registry value HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\FileSystem@LongPathsEnabled to 1.

This allows the open() function, the os module and most other path functionality to accept and return paths longer than 260 characters.

After changing the above option, no further configuration is required.

버전 3.6에서 변경: Support for long paths was enabled in Python.

3.1.3. Installing Without UI

All of the options available in the installer UI can also be specified from the command line, allowing scripted installers to replicate an installation on many machines without user interaction. These options may also be set without suppressing the UI in order to change some of the defaults.

To completely hide the installer UI and install Python silently, pass the /quiet option. To skip past the user interaction but still display progress and errors, pass the /passive option. The /uninstall option may be passed to immediately begin removing Python - no prompt will be displayed.

All other options are passed as name=value, where the value is usually 0 to disable a feature, 1 to enable a feature, or a path. The full list of available options is shown below.

Name

Description

Default

InstallAllUsers

Perform a system-wide installation.

0

TargetDir

The installation directory

Selected based on InstallAllUsers

DefaultAllUsersTargetDir

The default installation directory for all-user installs

%ProgramFiles%\Python X.Y or %ProgramFiles(x86)%\Python X.Y

DefaultJustForMeTargetDir

The default install directory for just-for-me installs

%LocalAppData%\Programs\PythonXY or %LocalAppData%\Programs\PythonXY-32 or %LocalAppData%\Programs\PythonXY-64

DefaultCustomTargetDir

The default custom install directory displayed in the UI

(empty)

AssociateFiles

Create file associations if the launcher is also installed.

1

CompileAll

Compile all .py files to .pyc.

0

PrependPath

Add install and Scripts directories to PATH and .PY to PATHEXT

0

Shortcuts

Create shortcuts for the interpreter, documentation and IDLE if installed.

1

Include_doc

Install Python manual

1

Include_debug

Install debug binaries

0

Include_dev

Install developer headers and libraries

1

Include_exe

Install python.exe and related files

1

Include_launcher

Install Python Launcher for Windows.

1

InstallLauncherAllUsers

Installs Python Launcher for Windows for all users.

1

Include_lib

Install standard library and extension modules

1

Include_pip

Install bundled pip and setuptools

1

Include_symbols

Install debugging symbols (*.pdb)

0

Include_tcltk

Install Tcl/Tk support and IDLE

1

Include_test

Install standard library test suite

1

Include_tools

Install utility scripts

1

LauncherOnly

Only installs the launcher. This will override most other options.

0

SimpleInstall

Disable most install UI

0

SimpleInstallDescription

A custom message to display when the simplified install UI is used.

(empty)

For example, to silently install a default, system-wide Python installation, you could use the following command (from an elevated command prompt):

python-3.7.0.exe /quiet InstallAllUsers=1 PrependPath=1 Include_test=0

To allow users to easily install a personal copy of Python without the test suite, you could provide a shortcut with the following command. This will display a simplified initial page and disallow customization:

python-3.7.0.exe InstallAllUsers=0 Include_launcher=0 Include_test=0
    SimpleInstall=1 SimpleInstallDescription="Just for me, no test suite."

(Note that omitting the launcher also omits file associations, and is only recommended for per-user installs when there is also a system-wide installation that included the launcher.)

The options listed above can also be provided in a file named unattend.xml alongside the executable. This file specifies a list of options and values. When a value is provided as an attribute, it will be converted to a number if possible. Values provided as element text are always left as strings. This example file sets the same options as the previous example:

<Options>
    <Option Name="InstallAllUsers" Value="no" />
    <Option Name="Include_launcher" Value="0" />
    <Option Name="Include_test" Value="no" />
    <Option Name="SimpleInstall" Value="yes" />
    <Option Name="SimpleInstallDescription">Just for me, no test suite</Option>
</Options>

3.1.4. Installing Without Downloading

As some features of Python are not included in the initial installer download, selecting those features may require an internet connection. To avoid this need, all possible components may be downloaded on-demand to create a complete layout that will no longer require an internet connection regardless of the selected features. Note that this download may be bigger than required, but where a large number of installations are going to be performed it is very useful to have a locally cached copy.

Execute the following command from Command Prompt to download all possible required files. Remember to substitute python-3.7.0.exe for the actual name of your installer, and to create layouts in their own directories to avoid collisions between files with the same name.

python-3.7.0.exe /layout [optional target directory]

You may also specify the /quiet option to hide the progress display.

3.1.5. Modifying an install

Once Python has been installed, you can add or remove features through the Programs and Features tool that is part of Windows. Select the Python entry and choose “Uninstall/Change” to open the installer in maintenance mode.

“Modify” allows you to add or remove features by modifying the checkboxes - unchanged checkboxes will not install or remove anything. Some options cannot be changed in this mode, such as the install directory; to modify these, you will need to remove and then reinstall Python completely.

“Repair” will verify all the files that should be installed using the current settings and replace any that have been removed or modified.

“Uninstall” will remove Python entirely, with the exception of the Python Launcher for Windows, which has its own entry in Programs and Features.

3.2. The Microsoft Store package

버전 3.7.2에 추가.

참고

The Microsoft Store package is currently considered unstable while its interactions with other tools and other copies of Python are evaluated. While Python itself is stable, this installation method may change its behavior and capabilities during Python 3.7 releases.

The Microsoft Store package is an easily installable Python interpreter that is intended mainly for interactive use, for example, by students.

To install the package, ensure you have the latest Windows 10 updates and search the Microsoft Store app for “Python 3.7”. Ensure that the app you select is published by the Python Software Foundation, and install it.

경고

Python will always be available for free on the Microsoft Store. If you are asked to pay for it, you have not selected the correct package.

After installation, Python may be launched by finding it in Start. Alternatively, it will be available from any Command Prompt or PowerShell session by typing python. Further, pip and IDLE may be used by typing pip or idle. IDLE can also be found in Start.

All three commands are also available with version number suffixes, for example, as python3.exe and python3.x.exe as well as python.exe (where 3.x is the specific version you want to launch, such as 3.7).

Virtual environments can be created with python -m venv and activated and used as normal.

If you have installed another version of Python and added it to your PATH variable, it will be available as python.exe rather than the one from the Microsoft Store. To access the new installation, use python3.exe or python3.x.exe.

To remove Python, open Settings and use Apps and Features, or else find Python in Start and right-click to select Uninstall. Uninstalling will remove all packages you installed directly into this Python installation, but will not remove any virtual environments

3.2.1. Known Issues

Currently, the py.exe launcher cannot be used to start Python when it has been installed from the Microsoft Store.

Because of restrictions on Microsoft Store apps, Python scripts may not have full write access to shared locations such as TEMP and the registry. Instead, it will write to a private copy. If your scripts must modify the shared locations, you will need to install the full installer.

3.3. The nuget.org packages

버전 3.5.2에 추가.

The nuget.org package is a reduced size Python environment intended for use on continuous integration and build systems that do not have a system-wide install of Python. While nuget is “the package manager for .NET”, it also works perfectly fine for packages containing build-time tools.

Visit nuget.org [https://www.nuget.org/] for the most up-to-date information on using nuget. What follows is a summary that is sufficient for Python developers.

The nuget.exe command line tool may be downloaded directly from https://aka.ms/nugetclidl, for example, using curl or PowerShell. With the tool, the latest version of Python for 64-bit or 32-bit machines is installed using:

nuget.exe install python -ExcludeVersion -OutputDirectory .
nuget.exe install pythonx86 -ExcludeVersion -OutputDirectory .

To select a particular version, add a -Version 3.x.y. The output directory may be changed from ., and the package will be installed into a subdirectory. By default, the subdirectory is named the same as the package, and without the -ExcludeVersion option this name will include the specific version installed. Inside the subdirectory is a tools directory that contains the Python installation:

# Without -ExcludeVersion
> .\python.3.5.2\tools\python.exe -V
Python 3.5.2

# With -ExcludeVersion
> .\python\tools\python.exe -V
Python 3.5.2

In general, nuget packages are not upgradeable, and newer versions should be installed side-by-side and referenced using the full path. Alternatively, delete the package directory manually and install it again. Many CI systems will do this automatically if they do not preserve files between builds.

Alongside the tools directory is a build\native directory. This contains a MSBuild properties file python.props that can be used in a C++ project to reference the Python install. Including the settings will automatically use the headers and import libraries in your build.

The package information pages on nuget.org are www.nuget.org/packages/python [https://www.nuget.org/packages/python] for the 64-bit version and www.nuget.org/packages/pythonx86 [https://www.nuget.org/packages/pythonx86] for the 32-bit version.

3.4. The embeddable package

버전 3.5에 추가.

The embedded distribution is a ZIP file containing a minimal Python environment. It is intended for acting as part of another application, rather than being directly accessed by end-users.

When extracted, the embedded distribution is (almost) fully isolated from the user’s system, including environment variables, system registry settings, and installed packages. The standard library is included as pre-compiled and optimized .pyc files in a ZIP, and python3.dll, python37.dll, python.exe and pythonw.exe are all provided. Tcl/tk (including all dependants, such as Idle), pip and the Python documentation are not included.

참고

The embedded distribution does not include the Microsoft C Runtime [https://www.microsoft.com/en-us/download/details.aspx?id=48145] and it is the responsibility of the application installer to provide this. The runtime may have already been installed on a user’s system previously or automatically via Windows Update, and can be detected by finding ucrtbase.dll in the system directory.

Third-party packages should be installed by the application installer alongside the embedded distribution. Using pip to manage dependencies as for a regular Python installation is not supported with this distribution, though with some care it may be possible to include and use pip for automatic updates. In general, third-party packages should be treated as part of the application (“vendoring”) so that the developer can ensure compatibility with newer versions before providing updates to users.

The two recommended use cases for this distribution are described below.

3.4.1. Python Application

An application written in Python does not necessarily require users to be aware of that fact. The embedded distribution may be used in this case to include a private version of Python in an install package. Depending on how transparent it should be (or conversely, how professional it should appear), there are two options.

Using a specialized executable as a launcher requires some coding, but provides the most transparent experience for users. With a customized launcher, there are no obvious indications that the program is running on Python: icons can be customized, company and version information can be specified, and file associations behave properly. In most cases, a custom launcher should simply be able to call Py_Main with a hard-coded command line.

The simpler approach is to provide a batch file or generated shortcut that directly calls the python.exe or pythonw.exe with the required command-line arguments. In this case, the application will appear to be Python and not its actual name, and users may have trouble distinguishing it from other running Python processes or file associations.

With the latter approach, packages should be installed as directories alongside the Python executable to ensure they are available on the path. With the specialized launcher, packages can be located in other locations as there is an opportunity to specify the search path before launching the application.

3.4.2. Embedding Python

Applications written in native code often require some form of scripting language, and the embedded Python distribution can be used for this purpose. In general, the majority of the application is in native code, and some part will either invoke python.exe or directly use python3.dll. For either case, extracting the embedded distribution to a subdirectory of the application installation is sufficient to provide a loadable Python interpreter.

As with the application use, packages can be installed to any location as there is an opportunity to specify search paths before initializing the interpreter. Otherwise, there is no fundamental differences between using the embedded distribution and a regular installation.

3.5. Alternative bundles

Besides the standard CPython distribution, there are modified packages including additional functionality. The following is a list of popular versions and their key features:

ActivePython [https://www.activestate.com/activepython/]

Installer with multi-platform compatibility, documentation, PyWin32

Anaconda [https://www.anaconda.com/download/]

Popular scientific modules (such as numpy, scipy and pandas) and the conda package manager.

Canopy [https://www.enthought.com/product/canopy/]

A “comprehensive Python analysis environment” with editors and other development tools.

WinPython [https://winpython.github.io/]

Windows-specific distribution with prebuilt scientific packages and tools for building packages.

Note that these packages may not include the latest versions of Python or other libraries, and are not maintained or supported by the core Python team.

3.6. Configuring Python

To run Python conveniently from a command prompt, you might consider changing some default environment variables in Windows. While the installer provides an option to configure the PATH and PATHEXT variables for you, this is only reliable for a single, system-wide installation. If you regularly use multiple versions of Python, consider using the Python Launcher for Windows.

3.6.1. Excursus: Setting environment variables

Windows allows environment variables to be configured permanently at both the User level and the System level, or temporarily in a command prompt.

To temporarily set environment variables, open Command Prompt and use the set command:

C:\>set PATH=C:\Program Files\Python 3.7;%PATH%
C:\>set PYTHONPATH=%PYTHONPATH%;C:\My_python_lib
C:\>python

These changes will apply to any further commands executed in that console, and will be inherited by any applications started from the console.

Including the variable name within percent signs will expand to the existing value, allowing you to add your new value at either the start or the end. Modifying PATH by adding the directory containing python.exe to the start is a common way to ensure the correct version of Python is launched.

To permanently modify the default environment variables, click Start and search for ‘edit environment variables’, or open System properties, Advanced system settings and click the Environment Variables button. In this dialog, you can add or modify User and System variables. To change System variables, you need non-restricted access to your machine (i.e. Administrator rights).

참고

Windows will concatenate User variables after System variables, which may cause unexpected results when modifying PATH.

The PYTHONPATH variable is used by all versions of Python 2 and Python 3, so you should not permanently configure this variable unless it only includes code that is compatible with all of your installed Python versions.

더 보기

https://www.microsoft.com/en-us/wdsi/help/folder-variables

Environment variables in Windows NT

https://technet.microsoft.com/en-us/library/cc754250.aspx

The SET command, for temporarily modifying environment variables

https://technet.microsoft.com/en-us/library/cc755104.aspx

The SETX command, for permanently modifying environment variables

https://support.microsoft.com/en-us/help/310519/how-to-manage-environment-variables-in-windows-xp

How To Manage Environment Variables in Windows XP

https://www.chem.gla.ac.uk/~louis/software/faq/q1.html

Setting Environment variables, Louis J. Farrugia

3.6.2. Finding the Python executable

버전 3.5에서 변경.

Besides using the automatically created start menu entry for the Python interpreter, you might want to start Python in the command prompt. The installer has an option to set that up for you.

On the first page of the installer, an option labelled “Add Python to PATH” may be selected to have the installer add the install location into the PATH. The location of the Scripts\ folder is also added. This allows you to type python to run the interpreter, and pip for the package installer. Thus, you can also execute your scripts with command line options, see 명령 줄 documentation.

If you don’t enable this option at install time, you can always re-run the installer, select Modify, and enable it. Alternatively, you can manually modify the PATH using the directions in Excursus: Setting environment variables. You need to set your PATH environment variable to include the directory of your Python installation, delimited by a semicolon from other entries. An example variable could look like this (assuming the first two entries already existed):

C:\WINDOWS\system32;C:\WINDOWS;C:\Program Files\Python 3.7

3.7. UTF-8 mode

버전 3.7에 추가.

Windows still uses legacy encodings for the system encoding (the ANSI Code Page). Python uses it for the default encoding of text files (e.g. locale.getpreferredencoding()).

This may cause issues because UTF-8 is widely used on the internet and most Unix systems, including WSL (Windows Subsystem for Linux).

You can use UTF-8 mode to change the default text encoding to UTF-8. You can enable UTF-8 mode via the -X utf8 command line option, or the PYTHONUTF8=1 environment variable. See PYTHONUTF8 for enabling UTF-8 mode, and Excursus: Setting environment variables for how to modify environment variables.

When UTF-8 mode is enabled:

locale.getpreferredencoding() returns 'UTF-8' instead of the system encoding. This function is used for the default text encoding in many places, including open(), Popen, Path.read_text(), etc.

sys.stdin, sys.stdout, and sys.stderr all use UTF-8 as their text encoding.

You can still use the system encoding via the “mbcs” codec.

Note that adding PYTHONUTF8=1 to the default environment variables will affect all Python 3.7+ applications on your system. If you have any Python 3.7+ applications which rely on the legacy system encoding, it is recommended to set the environment variable temporarily or use the -X utf8 command line option.

참고

Even when UTF-8 mode is disabled, Python uses UTF-8 by default on Windows for:

Console I/O including standard I/O (see PEP 528 [https://www.python.org/dev/peps/pep-0528] for details).

The filesystem encoding (see PEP 529 [https://www.python.org/dev/peps/pep-0529] for details).

3.8. Python Launcher for Windows

버전 3.3에 추가.

The Python launcher for Windows is a utility which aids in locating and executing of different Python versions. It allows scripts (or the command-line) to indicate a preference for a specific Python version, and will locate and execute that version.

Unlike the PATH variable, the launcher will correctly select the most appropriate version of Python. It will prefer per-user installations over system-wide ones, and orders by language version rather than using the most recently installed version.

The launcher was originally specified in PEP 397 [https://www.python.org/dev/peps/pep-0397].

3.8.1. Getting started

3.8.1.1. From the command-line

버전 3.6에서 변경.

System-wide installations of Python 3.3 and later will put the launcher on your PATH. The launcher is compatible with all available versions of Python, so it does not matter which version is installed. To check that the launcher is available, execute the following command in Command Prompt:

py

You should find that the latest version of Python you have installed is started - it can be exited as normal, and any additional command-line arguments specified will be sent directly to Python.

If you have multiple versions of Python installed (e.g., 2.7 and 3.7) you will have noticed that Python 3.7 was started - to launch Python 2.7, try the command:

py -2.7

If you want the latest version of Python 2.x you have installed, try the command:

py -2

You should find the latest version of Python 2.x starts.

If you see the following error, you do not have the launcher installed:

'py' is not recognized as an internal or external command,
operable program or batch file.

Per-user installations of Python do not add the launcher to PATH unless the option was selected on installation.

3.8.1.2. Virtual environments

버전 3.5에 추가.

If the launcher is run with no explicit Python version specification, and a virtual environment (created with the standard library venv module or the external virtualenv tool) active, the launcher will run the virtual environment’s interpreter rather than the global one. To run the global interpreter, either deactivate the virtual environment, or explicitly specify the global Python version.

3.8.1.3. From a script

Let’s create a test Python script - create a file called hello.py with the following contents

#! python
import sys
sys.stdout.write("hello from Python %s\n" % (sys.version,))

From the directory in which hello.py lives, execute the command:

py hello.py

You should notice the version number of your latest Python 2.x installation is printed. Now try changing the first line to be:

#! python3

Re-executing the command should now print the latest Python 3.x information. As with the above command-line examples, you can specify a more explicit version qualifier. Assuming you have Python 2.6 installed, try changing the first line to #! python2.6 and you should find the 2.6 version information printed.

Note that unlike interactive use, a bare “python” will use the latest version of Python 2.x that you have installed. This is for backward compatibility and for compatibility with Unix, where the command python typically refers to Python 2.

3.8.1.4. From file associations

The launcher should have been associated with Python files (i.e. .py, .pyw, .pyc files) when it was installed. This means that when you double-click on one of these files from Windows explorer the launcher will be used, and therefore you can use the same facilities described above to have the script specify the version which should be used.

The key benefit of this is that a single launcher can support multiple Python versions at the same time depending on the contents of the first line.

3.8.2. Shebang Lines

If the first line of a script file starts with #!, it is known as a “shebang” line. Linux and other Unix like operating systems have native support for such lines and they are commonly used on such systems to indicate how a script should be executed. This launcher allows the same facilities to be used with Python scripts on Windows and the examples above demonstrate their use.

To allow shebang lines in Python scripts to be portable between Unix and Windows, this launcher supports a number of ‘virtual’ commands to specify which interpreter to use. The supported virtual commands are:

/usr/bin/env python

/usr/bin/python

/usr/local/bin/python

python

For example, if the first line of your script starts with

#! /usr/bin/python

The default Python will be located and used. As many Python scripts written to work on Unix will already have this line, you should find these scripts can be used by the launcher without modification. If you are writing a new script on Windows which you hope will be useful on Unix, you should use one of the shebang lines starting with /usr.

Any of the above virtual commands can be suffixed with an explicit version (either just the major version, or the major and minor version). Furthermore the 32-bit version can be requested by adding “-32” after the minor version. I.e. /usr/bin/python2.7-32 will request usage of the 32-bit python 2.7.

버전 3.7에 추가: Beginning with python launcher 3.7 it is possible to request 64-bit version by the “-64” suffix. Furthermore it is possible to specify a major and architecture without minor (i.e. /usr/bin/python3-64).

The /usr/bin/env form of shebang line has one further special property. Before looking for installed Python interpreters, this form will search the executable PATH for a Python executable. This corresponds to the behaviour of the Unix env program, which performs a PATH search.

3.8.3. Arguments in shebang lines

The shebang lines can also specify additional options to be passed to the Python interpreter. For example, if you have a shebang line:

#! /usr/bin/python -v

Then Python will be started with the -v option

3.8.4. Customization

3.8.4.1. Customization via INI files

Two .ini files will be searched by the launcher - py.ini in the current user’s “application data” directory (i.e. the directory returned by calling the Windows function SHGetFolderPath with CSIDL_LOCAL_APPDATA) and py.ini in the same directory as the launcher. The same .ini files are used for both the ‘console’ version of the launcher (i.e. py.exe) and for the ‘windows’ version (i.e. pyw.exe).

Customization specified in the “application directory” will have precedence over the one next to the executable, so a user, who may not have write access to the .ini file next to the launcher, can override commands in that global .ini file.

3.8.4.2. Customizing default Python versions

In some cases, a version qualifier can be included in a command to dictate which version of Python will be used by the command. A version qualifier starts with a major version number and can optionally be followed by a period (‘.’) and a minor version specifier. Furthermore it is possible to specifiy if a 32 or 64 bit implementation shall be requested by adding “-32” or “-64”.

For example, a shebang line of #!python has no version qualifier, while #!python3 has a version qualifier which specifies only a major version.

If no version qualifiers are found in a command, the environment variable PY_PYTHON can be set to specify the default version qualifier. If it is not set, the default is “3”. The variable can specify any value that may be passed on the command line, such as “3”, “3.7”, “3.7-32” or “3.7-64”. (Note that the “-64” option is only available with the launcher included with Python 3.7 or newer.)

If no minor version qualifiers are found, the environment variable PY_PYTHON{major} (where {major} is the current major version qualifier as determined above) can be set to specify the full version. If no such option is found, the launcher will enumerate the installed Python versions and use the latest minor release found for the major version, which is likely, although not guaranteed, to be the most recently installed version in that family.

On 64-bit Windows with both 32-bit and 64-bit implementations of the same (major.minor) Python version installed, the 64-bit version will always be preferred. This will be true for both 32-bit and 64-bit implementations of the launcher - a 32-bit launcher will prefer to execute a 64-bit Python installation of the specified version if available. This is so the behavior of the launcher can be predicted knowing only what versions are installed on the PC and without regard to the order in which they were installed (i.e., without knowing whether a 32 or 64-bit version of Python and corresponding launcher was installed last). As noted above, an optional “-32” or “-64” suffix can be used on a version specifier to change this behaviour.

Examples:

If no relevant options are set, the commands python and python2 will use the latest Python 2.x version installed and the command python3 will use the latest Python 3.x installed.

The commands python3.1 and python2.7 will not consult any options at all as the versions are fully specified.

If PY_PYTHON=3, the commands python and python3 will both use the latest installed Python 3 version.

If PY_PYTHON=3.1-32, the command python will use the 32-bit implementation of 3.1 whereas the command python3 will use the latest installed Python (PY_PYTHON was not considered at all as a major version was specified.)

If PY_PYTHON=3 and PY_PYTHON3=3.1, the commands python and python3 will both use specifically 3.1

In addition to environment variables, the same settings can be configured in the .INI file used by the launcher. The section in the INI file is called [defaults] and the key name will be the same as the environment variables without the leading PY_ prefix (and note that the key names in the INI file are case insensitive.) The contents of an environment variable will override things specified in the INI file.

For example:

Setting PY_PYTHON=3.1 is equivalent to the INI file containing:

[defaults]
python=3.1

Setting PY_PYTHON=3 and PY_PYTHON3=3.1 is equivalent to the INI file containing:

[defaults]
python=3
python3=3.1

3.8.5. Diagnostics

If an environment variable PYLAUNCH_DEBUG is set (to any value), the launcher will print diagnostic information to stderr (i.e. to the console). While this information manages to be simultaneously verbose and terse, it should allow you to see what versions of Python were located, why a particular version was chosen and the exact command-line used to execute the target Python.

3.9. Finding modules

Python usually stores its library (and thereby your site-packages folder) in the installation directory. So, if you had installed Python to C:\Python\, the default library would reside in C:\Python\Lib\ and third-party modules should be stored in C:\Python\Lib\site-packages\.

To completely override sys.path, create a ._pth file with the same name as the DLL (python37._pth) or the executable (python._pth) and specify one line for each path to add to sys.path. The file based on the DLL name overrides the one based on the executable, which allows paths to be restricted for any program loading the runtime if desired.

When the file exists, all registry and environment variables are ignored, isolated mode is enabled, and site is not imported unless one line in the file specifies import site. Blank paths and lines starting with # are ignored. Each path may be absolute or relative to the location of the file. Import statements other than to site are not permitted, and arbitrary code cannot be specified.

Note that .pth files (without leading underscore) will be processed normally by the site module when import site has been specified.

When no ._pth file is found, this is how sys.path is populated on Windows:

An empty entry is added at the start, which corresponds to the current directory.

If the environment variable PYTHONPATH exists, as described in 환경 변수, its entries are added next. Note that on Windows, paths in this variable must be separated by semicolons, to distinguish them from the colon used in drive identifiers (C:\ etc.).

Additional “application paths” can be added in the registry as subkeys of \SOFTWARE\Python\PythonCore{version}\PythonPath under both the HKEY_CURRENT_USER and HKEY_LOCAL_MACHINE hives. Subkeys which have semicolon-delimited path strings as their default value will cause each path to be added to sys.path. (Note that all known installers only use HKLM, so HKCU is typically empty.)

If the environment variable PYTHONHOME is set, it is assumed as “Python Home”. Otherwise, the path of the main Python executable is used to locate a “landmark file” (either Lib\os.py or pythonXY.zip) to deduce the “Python Home”. If a Python home is found, the relevant sub-directories added to sys.path (Lib, plat-win, etc) are based on that folder. Otherwise, the core Python path is constructed from the PythonPath stored in the registry.

If the Python Home cannot be located, no PYTHONPATH is specified in the environment, and no registry entries can be found, a default path with relative entries is used (e.g. .\Lib;.\plat-win, etc).

If a pyvenv.cfg file is found alongside the main executable or in the directory one level above the executable, the following variations apply:

If home is an absolute path and PYTHONHOME is not set, this path is used instead of the path to the main executable when deducing the home location.

The end result of all this is:

When running python.exe, or any other .exe in the main Python directory (either an installed version, or directly from the PCbuild directory), the core path is deduced, and the core paths in the registry are ignored. Other “application paths” in the registry are always read.

When Python is hosted in another .exe (different directory, embedded via COM, etc), the “Python Home” will not be deduced, so the core path from the registry is used. Other “application paths” in the registry are always read.

If Python can’t find its home and there are no registry value (frozen .exe, some very strange installation setup) you get a path with some default, but relative, paths.

For those who want to bundle Python into their application or distribution, the following advice will prevent conflicts with other installations:

Include a ._pth file alongside your executable containing the directories to include. This will ignore paths listed in the registry and environment variables, and also ignore site unless import site is listed.

If you are loading python3.dll or python37.dll in your own executable, explicitly call Py_SetPath() or (at least) Py_SetProgramName() before Py_Initialize().

Clear and/or overwrite PYTHONPATH and set PYTHONHOME before launching python.exe from your application.

If you cannot use the previous suggestions (for example, you are a distribution that allows people to run python.exe directly), ensure that the landmark file (Lib\os.py) exists in your install directory. (Note that it will not be detected inside a ZIP file, but a correctly named ZIP file will be detected instead.)

These will ensure that the files in a system-wide installation will not take precedence over the copy of the standard library bundled with your application. Otherwise, your users may experience problems using your application. Note that the first suggestion is the best, as the others may still be susceptible to non-standard paths in the registry and user site-packages.

버전 3.6에서 변경:

Adds ._pth file support and removes applocal option from pyvenv.cfg.

Adds pythonXX.zip as a potential landmark when directly adjacent to the executable.

버전 3.6부터 폐지:

Modules specified in the registry under Modules (not PythonPath) may be imported by importlib.machinery.WindowsRegistryFinder. This finder is enabled on Windows in 3.6.0 and earlier, but may need to be explicitly added to sys.meta_path in the future.

3.10. Additional modules

Even though Python aims to be portable among all platforms, there are features that are unique to Windows. A couple of modules, both in the standard library and external, and snippets exist to use these features.

The Windows-specific standard modules are documented in MS 윈도우 특정 서비스.

3.10.1. PyWin32

The PyWin32 [https://pypi.org/project/pywin32] module by Mark Hammond is a collection of modules for advanced Windows-specific support. This includes utilities for:

Component Object Model [https://docs.microsoft.com/en-us/windows/desktop/com/component-object-model--com--portal] (COM)

Win32 API calls

Registry

Event log

Microsoft Foundation Classes [https://msdn.microsoft.com/en-us/library/fe1cf721%28VS.80%29.aspx] (MFC) user interfaces

PythonWin [https://web.archive.org/web/20060524042422/https://www.python.org/windows/pythonwin/] is a sample MFC application shipped with PyWin32. It is an embeddable IDE with a built-in debugger.

더 보기

Win32 How Do I…? [http://timgolden.me.uk/python/win32_how_do_i.html]

by Tim Golden

Python and COM [http://www.boddie.org.uk/python/COM.html]

by David and Paul Boddie

3.10.2. cx_Freeze

cx_Freeze [https://anthony-tuininga.github.io/cx_Freeze/] is a distutils extension (see Distutils 확장하기) which wraps Python scripts into executable Windows programs (*.exe files). When you have done this, you can distribute your application without requiring your users to install Python.

3.10.3. WConio

Since Python’s advanced terminal handling layer, curses, is restricted to Unix-like systems, there is a library exclusive to Windows as well: Windows Console I/O for Python.

WConio [http://newcenturycomputers.net/projects/wconio.html] is a wrapper for Turbo-C’s CONIO.H, used to create text user interfaces.

3.11. Compiling Python on Windows

If you want to compile CPython yourself, first thing you should do is get the source [https://www.python.org/downloads/source/]. You can download either the latest release’s source or just grab a fresh checkout [https://devguide.python.org/setup/#getting-the-source-code].

The source tree contains a build solution and project files for Microsoft Visual Studio 2015, which is the compiler used to build the official Python releases. These files are in the PCbuild directory.

Check PCbuild/readme.txt for general information on the build process.

For extension modules, consult 윈도우에서 C와 C++ 확장 빌드하기.

더 보기

Python + Windows + distutils + SWIG + gcc MinGW [http://sebsauvage.net/python/mingw.html]

or “Creating Python extensions in C/C++ with SWIG and compiling them with MinGW gcc under Windows” or “Installing Python extension with distutils and without Microsoft Visual C++” by Sébastien Sauvage, 2003

MingW – Python extensions [http://www.mingw.org/wiki/FAQ#toc14]

3.12. Other Platforms

With ongoing development of Python, some platforms that used to be supported earlier are no longer supported (due to the lack of users or developers). Check PEP 11 [https://www.python.org/dev/peps/pep-0011] for details on all unsupported platforms.

Windows CE [http://pythonce.sourceforge.net/] is still supported.

The Cygwin [https://cygwin.com/] installer offers to install the Python interpreter as well (cf. Cygwin package source [ftp://ftp.uni-erlangen.de/pub/pc/gnuwin32/cygwin/mirrors/cygnus/release/python], Maintainer releases [http://www.tishler.net/jason/software/python/])

See Python for Windows [https://www.python.org/downloads/windows/] for detailed information about platforms with pre-compiled installers.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 설정 및 사용법 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 설정 및 사용법 »

|

4. 매킨토시에서 파이썬 사용하기

저자

Bob Savage <bobsavage@mac.com>

Mac OS X을 실행하는 매킨토시 상의 파이썬은 원칙적으로 다른 모든 유닉스 플랫폼에 있는 파이썬과 매우 유사하지만, IDE와 패키지 관리자와 같은 언급할 만한 많은 추가 기능들이 있습니다.

4.1. MacPython을 구하고 설치하기

Mac OS X 10.8은 애플이 사전 설치한 파이썬 2.7을 제공합니다. 원한다면, 파이썬 웹 사이트 (https://www.python.org)에서 파이썬 3의 최신 버전을 설치하도록 초대합니다. 맥의 새로운 인텔과 레거시 PPC CPU에서 그대로 실행되는 최신 “유니버설 바이너리” 파이썬 빌드를 사용할 수 있습니다.

설치 후 얻을 수 있는 것은 여러 가지가 있습니다:

A Python 3.7 folder in your Applications folder. In here you find IDLE, the development environment that is a standard part of official Python distributions; and PythonLauncher, which handles double-clicking Python scripts from the Finder.

파이썬 실행 파일과 라이브러리를 포함하는 프레임워크 /Library/Frameworks/Python.framework. 설치기는 이 위치를 셸 경로에 추가합니다. MacPython을 제거하려면, 이 세 가지를 지우면 됩니다. 파이썬 실행 파일에 대한 심볼릭 링크는 /usr/local/bin/에 있습니다.

애플에서 제공한 파이썬 빌드는 /System/Library/Frameworks/Python.framework와 /usr/bin/python에 각각 설치됩니다. 애플에서 제어하고 애플이나 제삼자 소프트웨어에서 사용하므로, 절대로 수정하거나 삭제해서는 안 됩니다. Python.org에서 최신 파이썬 버전을 설치했다면, 컴퓨터에 서로 다르지만 동작하는 두 개의 파이썬 설치를 갖게 된다는 것을 기억하십시오, 경로와 사용이 여러분이 원하는 것과 일치하는 것이 중요합니다.

IDLE에는 파이썬 설명서에 액세스할 수 있는 도움말 메뉴가 포함되어 있습니다. 파이썬을 완전히 처음 접한다면, 이 설명서에서 자습서 소개를 읽는 것으로 시작해야 합니다.

다른 유닉스 플랫폼에서 파이썬에 익숙하다면 유닉스 셸에서 파이썬 스크립트를 실행하는 부분을 읽어야 합니다.

4.1.1. 파이썬 스크립트를 실행하는 방법

Mac OS X에서 파이썬을 시작하는 가장 좋은 방법은 IDLE 통합 개발 환경을 사용하는 것입니다, IDE 절을 참조하고, IDE가 실행 중일 때 도움말 메뉴를 사용하십시오.

터미널 창 명령 줄이나 Finder에서 파이썬 스크립트를 실행하려면 먼저 스크립트를 만들 편집기가 필요합니다. Mac OS X에는 여러 표준 유닉스 명령 줄 편집기, 그중에서도 vim과 emacs가 함께 제공됩니다. 좀 더 Mac 다운 편집기가 필요하다면, Bare Bones Software의 BBEdit나 TextWrangler(http://www.barebones.com/products/bbedit/index.html 을 참조하십시오)와 TextMate(https://macromates.com/ 을 참조하십시오)는 좋은 선택입니다. 다른 편집기로는 Gvim(http://macvim-dev.github.io/macvim/)과 Aquamacs(http://aquamacs.org/)가 있습니다.

터미널 창에서 스크립트를 실행하려면 /usr/local/bin이 셸 검색 경로에 있도록 해야 합니다.

Finder에서 스크립트를 실행하려면 두 가지 옵션이 있습니다:

스크립트를 PythonLauncher로 드래그하십시오.

Finder 정보 창을 통해 여러분의 스크립트(또는 모든 .py 스크립트)를 여는 기본 응용 프로그램으로 PythonLauncher를 선택하고 스크립트를 더블 클릭하십시오. PythonLauncher에는 스크립트를 시작하는 방법을 제어하는 다양한 설정이 있습니다. Option-드래그하면 하나의 호출에 대해 이를 변경할 수 있으며, 환경 설정 메뉴를 사용하여 전역적으로 변경할 수 있습니다.

4.1.2. GUI로 스크립트 실행하기

이전 버전의 파이썬에는, 여러분이 신경 써야 할 Mac OS X의 단점이 하나 있습니다: Aqua 창 관리자와 대화하는 프로그램(즉, GUI가 있는 프로그램)은 특별한 방법으로 실행해야 합니다. 이러한 스크립트를 시작하려면 python 대신 pythonw를 사용하십시오.

With Python 3.7, you can use either python or pythonw.

4.1.3. 구성

OS X의 파이썬은 PYTHONPATH와 같은 표준 유닉스 환경 변수를 모두 준수하지만, Finder에서 시작된 프로그램에 대해 이러한 변수를 설정하는 것은 비표준인데, 시작 시 Finder가 여러분의 .profile이나 .cshrc를 읽지 않기 때문입니다. ~/.MacOSX/environment.plist 파일을 만들 필요가 있습니다. 자세한 내용은 애플의 기술 문서 QA1067을 참조하십시오.

MacPython의 파이썬 패키지 설치에 대한 자세한 내용은, 추가 파이썬 패키지 설치하기 절을 참조하십시오.

4.2. IDE

MacPython에는 표준 IDLE 개발 환경이 따라옵니다. IDLE 사용에 대한 좋은 소개는 http://www.hashcollision.org/hkn/python/idle_intro/index.html 에서 찾을 수 있습니다.

4.3. 추가 파이썬 패키지 설치하기

추가 파이썬 패키지를 설치하는 몇 가지 방법이 있습니다:

패키지는 표준 파이썬 distutils 모드를 통해 설치할 수 있습니다 (python setup.py install).

많은 패키지는 setuptools 확장이나 pip 래퍼를 통해 설치할 수도 있습니다, https://pip.pypa.io/ 를 참조하십시오.

4.4. Mac에서의 GUI 프로그래밍

Mac에서 파이썬으로 GUI 응용 프로그램을 작성하기 위한 몇 가지 옵션이 있습니다.

PyObjC는 애플의 Objective-C/Cocoa 프레임워크에 대한 파이썬 바인딩입니다. 이 프레임워크는 가장 현대적인 Mac 개발의 기초입니다. PyObjC에 대한 정보는 https://pypi.org/project/pyobjc/ 에서 얻을 수 있습니다.

표준 파이썬 GUI 툴킷은 크로스 플랫폼 Tk 툴킷(https://www.tcl.tk)을 기반으로 하는 tkinter입니다. Tk의 Aqua-네이티브 버전은 애플에 의해 OS X에 번들로 제공되며, 최신 버전은 https://www.activestate.com 에서 내려받아 설치할 수 있습니다; 소스에서 빌드할 수도 있습니다.

wxPython은 Mac OS X에서 네이티브하게 실행되는 다른 인기 있는 크로스 플랫폼 GUI 툴킷입니다. 패키지와 설명서는 https://www.wxpython.org 에서 제공됩니다.

PyQt는 Mac OS X에서 네이티브하게 실행되는 다른 인기 있는 크로스 플랫폼 GUI 툴킷입니다. 자세한 정보는 https://riverbankcomputing.com/software/pyqt/intro 에서 찾을 수 있습니다.

4.5. Mac에서 파이썬 응용 프로그램 배포하기

Mac에서 독립형 파이썬 응용 프로그램을 배포하기 위한 표준 도구는 py2app입니다. py2app의 설치와 사용에 대한 자세한 정보는 http://undefined.org/python/#py2app 에서 확인할 수 있습니다.

4.6. 기타 자원

MacPython 메일링리스트는 Mac 파이썬 사용자와 개발자를 위한 훌륭한 지원 자원입니다:

https://www.python.org/community/sigs/current/pythonmac-sig/

또 다른 유용한 자원은 MacPython 위키입니다:

https://wiki.python.org/moin/MacPython

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 설정 및 사용법 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 설정 및 사용법 »

|

5. Editors and IDEs

There are a number of IDEs that support Python programming language. Many editors and IDEs provide syntax highlighting, debugging tools, and PEP 8 [https://www.python.org/dev/peps/pep-0008] checks.

Please go to Python Editors [https://wiki.python.org/moin/PythonEditors] and Integrated Development Environments [https://wiki.python.org/moin/IntegratedDevelopmentEnvironments] for a comprehensive list.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 설정 및 사용법 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

|

파이썬 언어 레퍼런스

이 참조 설명서는 언어의 문법과 “중심 개념들(core semantics)”을 설명합니다. 딱딱하더라도 정확하고 완전해지려고 합니다. 중심에서 벗어난 내장형, 내장 함수, 모듈들의 개념들은 파이썬 표준 라이브러리 에 기술되어 있습니다. 언어에 대한 비형식적인 소개는 파이썬 자습서 에서 제공됩니다. C와 C++ 프로그래머를 위해서는 두 개의 설명서가 따로 제공됩니다: 파이썬 인터프리터 확장 및 내장 는 파이썬 확장 모듈을 작성하는 방법에 대한 큰 그림을 설명하고, 파이썬/C API 레퍼런스 설명서 은 C/C++ 프로그래머에게 제공되는 인터페이스들을 상세하게 기술합니다.

1. 개요

1.1. 대안 구현들

1.2. 표기법

2. 어휘 분석

2.1. 줄 구조(Line structure)

2.2. 다른 토큰들

2.3. 식별자와 키워드

2.4. 리터럴

2.5. 연산자

2.6. 구분자

3. 데이터 모델

3.1. 객체, 값, 형

3.2. 표준형 계층

3.3. 특수 메서드 이름들

3.4. 코루틴(Coroutines)

4. 실행 모델

4.1. 프로그램의 구조

4.2. 이름과 연결(binding)

4.3. 예외

5. 임포트 시스템

5.1. importlib

5.2. 패키지(package)

5.3. 검색

5.4. 로딩(loading)

5.5. 경로 기반 파인더

5.6. 표준 임포트 시스템 교체하기

5.7. 패키지 상대 임포트

5.8. __main__ 에 대한 특별한 고려

5.9. 열린 이슈들

5.10. 참고문헌

6. 표현식

6.1. 산술 변환

6.2. 아톰 (Atoms)

6.3. 프라이머리

6.4. 어웨이트 표현식

6.5. 거듭제곱 연산자

6.6. 일 항 산술과 비트 연산

6.7. 이항 산술 연산

6.8. 시프트 연산

6.9. 이항 비트 연산

6.10. 비교

6.11. 논리 연산(Boolean operations)

6.12. 조건 표현식(Conditional expressions)

6.13. 람다(Lambdas)

6.14. 표현식 목록(Expression lists)

6.15. 값을 구하는 순서

6.16. 연산자 우선순위

7. 단순문(Simple statements)

7.1. 표현식 문

7.2. 대입문

7.3. assert 문

7.4. pass 문

7.5. del 문

7.6. return 문

7.7. yield 문

7.8. raise 문

7.9. break 문

7.10. continue 문

7.11. 임포트(import) 문

7.12. global 문

7.13. nonlocal 문

8. 복합문(Compound statements)

8.1. if 문

8.2. while 문

8.3. for 문

8.4. try 문

8.5. with 문

8.6. 함수 정의

8.7. 클래스 정의

8.8. 코루틴

9. 최상위 요소들

9.1. 완전한 파이썬 프로그램

9.2. 파일 입력

9.3. 대화형 입력

9.4. 표현식 입력

10. 전체 문법 규격

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 언어 레퍼런스 »

|

1. 개요

이 레퍼런스 설명서는 파이썬 프로그래밍 언어를 설명합니다. 자습서를 목표로 하고 있지 않습니다.

가능한 한 정확하려고 노력하고 있지만, 문법과 어휘 분석 이외의 모든 것에는 형식 규격보다는 자연어를 사용합니다. 이 선택이 평균적인 독자들이 문서를 좀 더 잘 이해하도록 만들지만, 동시에 모호해질 가능성 역시 만듭니다. 결과적으로, 만약 여러분이 화성에서 왔고 이 문서만으로 파이썬을 다시 구현하려고 하면, 아마도 여러 가지를 짐작해야 할 것이고 결국 많이 다른 언어를 만드는 것으로 끝날 것입니다. 반면에, 여러분이 파이썬을 사용하고 있고 언어의 특정 영역에 대한 정확한 규칙에 대해 궁금해하고 있다면 거의 확실히 이곳에서 답을 찾을 수 있습니다. 좀 더 형식화된 정의를 보고 싶다면, 아마도 여러분의 시간을 기부하는 편이 좋습니다 — 그렇지 않으면 클로닝 기계를 발명하거나 :-).

참조 문서에 너무 많은 구현 세부 사항을 넣는 것은 위험합니다. 구현은 변경될 것이고 같은 언어의 다른 구현도 좀 다른 방식으로 동작할 수 있습니다. 반면에 (대안 구현이 점차 지지도를 높여가고 있기는 하지만) CPython 은 가장 널리 사용되는 파이썬 구현이고, 그것의 특별한 경우 들은 때로 언급할 가치가 있습니다. 구현이 추가의 제약을 내포하고 있는 경우는 특히 그렇습니다. 그래서, 텍스트 중간중간 짧은 “구현 노트” 가 튀어나오는 것을 보게 될 것입니다.

모든 파이썬 구현에는 많은 내장 표준 모듈들이 따라옵니다. 이것들은 파이썬 표준 라이브러리 에 기술되어 있습니다. 언어 정의에 주목할 만한 방식으로 관계될 경우 몇몇 내장 모듈들은 따로 언급됩니다.

1.1. 대안 구현들

눈에 띄게 널리 사용되는 파이썬 구현이 존재하기는 하지만, 특정한 관심사를 가진 대상들에게 호소력을 가진 여러 대안 구현들이 존재합니다.

알려진 구현들은:

CPython

원조이기도 하고 가장 잘 관리되고 있는 C로 작성된 파이썬 구현입니다. 언어의 새로운 기능은 보통 여기에서 처음 등장합니다.

Jython

파이썬 자바구현. 이 구현은 자바 응용 프로그램을 위한 스크립트 언어로 사용되거나, 자바 클래스 라이브러리를 활용하는 응용 프로그램을 만드는데 사용될 수 있습니다. 종종 자바 라이브러리의 테스트를 만드는 데 사용되기도 합니다. 더 자세한 정보는 Jython 웹사이트 [http://www.jython.org/] 에서 찾을 수 있습니다.

Python for .NET

이 구현은 실제로는 CPython 구현을 사용하지만, 매니지드(managed) .NET 응용 프로그램이고 .NET 라이브러리를 제공합니다. Bryan Lloyd가 만들었습니다다. 더 자세한 정보는 Python for .NET 홈페이지 [https://pythonnet.github.io/] 에서 제공됩니다.

IronPython

.NET을 위한 대안 파이썬. Python.NET 과는 달리 이것은 IL을 생성하고, 파이썬 코드를 .NET 어셈블리로 직접 컴파일하는 완전한 파이썬 구현입니다. Jim Hugunin 이 만들었는데, Jython 의 원저자이기도 합니다. 자세한 정보는 IronPython 웹사이트 [http://ironpython.net/] 에서 얻을 수 있습니다.

PyPy

완전히 파이썬으로 작성된 파이썬 구현. 스택 리스(stackless) 지원이나 JIT 컴파일러와 같이 다른 구현에서는 찾을 수 없는 고급 기능을 제공합니다. 이 프로젝트의 목표 중 하나는 (파이썬으로 쓰였기 때문에) 인터프리터 수정을 쉽게 만들어서 언어 자체에 대한 실험을 북돋는 것입니다. 자세한 정보는 PyPy 프로젝트의 홈페이지 [http://pypy.org/] 에서 찾을 수 있습니다.

각 구현은 이 설명서에서 설명되는 언어와 조금씩 각기 다른 방법으로 벗어나거나, 표준 파이썬 문서에서 다루는 범위 밖의 특별한 정보들을 소개합니다. 여러분이 사용 중인 구현에 대해 어떤 것을 더 알아야 하는지 판단하기 위해서는 구현 별로 제공되는 문서를 참조할 필요가 있습니다.

1.2. 표기법

어휘 분석과 문법의 기술은 수정된 BNF 문법 표기법을 사용합니다. 이것은 다음과 같은 정의 스타일을 사용합니다.

name      ::=  lc_letter (lc_letter | "_")*
lc_letter ::=  "a"..."z"

첫 줄은 name 이 lc_letter 로 시작하고, 없거나 하나 이상의 lc_letter 나 밑줄이 뒤따르는 형태로 구성된다고 말합니다. 한편 lc_letter 는 'a' 와 'z' 사이의 문자 하나입니다. (사실 이 규칙은 이 문서에서 어휘와 문법 규칙에서 정의되는 이름들에 대한 규칙입니다.)

개별 규칙은 이름 (위 규칙에 등장하는 name)과 ::= 로 시작합니다. 세로막대(|)는 대안들을 분리하는 데 사용됩니다; 이 표기법에서 우선순위가 가장 낮은 연산자입니다. 별표(*)는 앞에 나오는 항목이 생략되거나 한 번 이상 반복될 수 있다는 의미입니다; 비슷하게, 더하기(+)는 한 번 이상 반복될 수 있지만 생략할 수는 없다는 뜻이고, 대괄호([])로 둘러싸인 것은 최대 한 번 나올 수 있고, 생략 가능하다는 뜻입니다. * 와 + 연산자는 최대한 엄격하게 연결됩니다; 우선순위가 가장 높습니다; 괄호는 덩어리로 묶는 데 사용됩니다. 문자열 리터럴은 따옴표로 둘러싸입니다. 공백은 토큰을 분리하는 용도로만 사용됩니다. 규칙은 보통 한 줄로 표현됩니다; 대안이 많은 규칙은 여러 줄로 표현될 수도 있는데, 뒤따르는 줄들이 세로막대로 시작되게 만듭니다.

어휘 정의 (위에서 든 예와 같이) 에서는, 두 가지 추가 관례가 사용됩니다: 두 개의 리터럴 문자가 세 개의 점으로 분리되어 있으면 주어진 (끝의 두 문자 모두 포함하는) 범위의 ASCII 문자 중 어느 하나라는 뜻입니다. 홑화살괄호(<...>) 안에 들어있는 구문은, 정의되는 기호에 대한 비형식적 설명을 제공합니다. 즉 필요한 경우 ‘제어 문자’를 설명하는데 사용될 수 있습니다.

사용되는 표기법이 거의 같다고 하더라도, 어휘와 문법 정의 간에는 커다란 차이가 있습니다: 어휘 정의는 입력의 개별 문자에 적용되는 반면, 문법 정의는 어휘 분석기가 만들어내는 토큰들에 적용됩니다. 다음 장 (“어휘 분석(Lexical Analysis)”)에서 사용되는 모든 BNF는 어휘 정의입니다; 그 이후의 장에서는 문법 정의입니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 언어 레퍼런스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 언어 레퍼런스 »

|

2. 어휘 분석

파이썬 프로그램은 파서(parser) 에 의해 읽힙니다. 파서의 입력은 어휘 분석기(lexical analyzer) 가 만들어내는 토큰(token) 들의 스트림입니다. 이 장에서는 어휘 분석기가 어떻게 파일을 토큰들로 분해하는지 설명합니다.

파이썬은 프로그램 텍스트를 유니코드 코드값으로 읽습니다; 소스 파일의 인코딩은 인코딩 선언을 통해 지정될 수 있고, 기본값은 UTF-8입니다. 자세한 내용은 PEP 3120 [https://www.python.org/dev/peps/pep-3120] 에 나옵니다. 소스 파일을 디코딩할 수 없을 때는 SyntaxError 가 발생합니다.

2.1. 줄 구조(Line structure)

파이썬 프로그램은 여러 개의 논리적인 줄(logical lines) 들로 나뉩니다.

2.1.1. 논리적인 줄

논리적인 줄의 끝은 NEWLINE 토큰으로 표현됩니다. 문법이 허락하지 않는 이상 (예를 들어 복합문에서 문장들 사이) 문장은 논리적인 줄 간의 경계를 가로지를 수 없습니다. 논리적인 줄은 명시적이거나 묵시적인 줄 결합(line joining) 규칙에 따라 하나 이상의 물리적인 줄(physical lines) 들로 구성됩니다.

2.1.2. 물리적인 줄

물리적인 줄은 줄의 끝을 나타내는 시퀀스로 끝나는 문자들의 시퀀스입니다. 소스 파일과 문자열에는 플랫폼들의 표준 줄 종료 시퀀스들이 모두 사용될 수 있습니다 - ASCII LF (개행문자)를 사용하는 유닉스 형, ASCII 시퀀스 CR LF(캐리지 리턴 다음에 오는 개행 문자)를 사용하는 윈도우 형, ASCII CR(캐리지 리턴)을 사용하는 예전의 매킨토시 형. 이 형태들은 플랫폼의 종류와 관계없이 동등하게 사용할 수 있습니다. 입력의 끝은 마지막 물리적인 줄의 묵시적 종결자 역할을 합니다.

파이썬을 내장할 때는, 소스 코드 문자열은 반드시 줄 종료 문자에 표준 C 관행(ASCII LF를 표현하는 \n 문자로 줄이 종료됩니다)을 적용해서 파이썬 API로 전달되어야 합니다.

2.1.3. 주석

주석은 문자열 리터럴에 포함되지 않는 해시 문자(#)로 시작하고 물리적인 줄의 끝에서 끝납니다. 묵시적인 줄 결합 규칙이 유효하지 않은 이상, 주석은 논리적인 줄을 종료시킵니다. 주석은 문법이 무시합니다.

2.1.4. 인코딩 선언

파이썬 스크립트의 첫 번 째나 두 번째 줄에 있는 주석이 정규식 coding[=:]\s*([-\w.]+) 과 매치되면, 이 주석은 인코딩 선언으로 처리됩니다. 이 정규식의 첫 번째 그룹은 소스 코드 파일의 인코딩 이름을 지정합니다. 인코딩 선언은 줄 전체에 홀로 나와야 합니다. 만약 두 번째 줄이라면, 첫 번째 줄 역시 주석만 있어야 합니다. 인코딩 선언의 권장 형태는 두 개입니다. 하나는

# -*- coding: <encoding-name> -*-

인데 GNU Emacs에서도 인식됩니다. 다른 하나는

# vim:fileencoding=<encoding-name>

인데 Bram Moolenaar 의 VIM에서 인식됩니다.

인코딩 선언이 발견되지 않으면 기본 인코딩은 UTF-8입니다. 여기에 더해, 파일의 처음이 UTF-8 BOM (b'\xef\xbb\xbf')이면 파일 인코딩이 UTF-8으로 선언된 것으로 봅니다. (이 방식은 마이크로소프트의 notepad 에서 지원됩니다.)

인코딩이 선언되면, 인코딩 이름은 파이썬이 인식할 수 있어야 합니다. 인코딩은 문자열 리터럴, 주석, 식별자를 포함한 모든 어휘 분석에서 모두 사용됩니다.

2.1.5. 명시적인 줄 결합

둘 이상의 물리적인 줄은 역 슬래시 문자(\)를 사용해서 논리적인 줄로 결합할 수 있습니다: 물리적인 줄이 문자열 리터럴이나 주석의 일부가 아닌 역 슬래시 문자로 끝나면, 역 슬래시와 뒤따르는 개행 문자가 제거된 채로, 현재 만들어지고 있는 논리적인 줄에 합쳐집니다. 예를 들어:

if 1900 < year < 2100 and 1 <= month <= 12 \
   and 1 <= day <= 31 and 0 <= hour < 24 \
   and 0 <= minute < 60 and 0 <= second < 60:   # Looks like a valid date
        return 1

역 슬래시로 끝나는 줄은 주석이 포함될 수 없습니다. 역 슬래시는 주석을 결합하지 못합니다. 역 슬래시는 문자열 리터럴을 제외한 어떤 토큰도 결합하지 못합니다 (즉, 문자열 리터럴 이외의 어떤 토큰도 역 슬래시를 사용해서 두 줄에 나누어 기록할 수 없습니다.). 문자열 리터럴 밖에 있는 역 슬래시가 앞에서 언급한 장소 이외의 곳에 등장하는 것은 문법에 어긋납니다.

2.1.6. 묵시적인 줄 결합

괄호(()), 대괄호([]), 중괄호({})가 사용되는 표현은 역 슬래시 없이도 여러 개의 물리적인 줄로 나눌 수 있습니다. 예를 들어:

month_names = ['Januari', 'Februari', 'Maart',      # These are the
               'April',   'Mei',      'Juni',       # Dutch names
               'Juli',    'Augustus', 'September',  # for the months
               'Oktober', 'November', 'December']   # of the year

묵시적으로 이어지는 줄들은 주석을 포함할 수 있습니다. 이어지는 줄들의 들여쓰기는 중요하지 않습니다. 중간에 빈 줄이 들어가도 됩니다. 묵시적으로 줄 결합하는 줄 들 간에는 NEWLINE 토큰이 만들어지지 않습니다. 묵시적으로 이어지는 줄들은 삼중 따옴표 된 문자열들에서도 등장할 수 있는데 (아래를 보라), 이 경우는 주석이 포함될 수 없습니다.

2.1.7. 빈 줄

스페이스, 탭, 폼 피드(formfeed) 와 주석만으로 구성된 논리적인 줄은 무시됩니다. (즉 NEWLINE 토큰이 만들어지지 않습니다.) 대화형으로 문장이 입력되는 도중에는 빈 줄의 처리가 REPL 구현에 따라 달라질 수 있습니다. 표준 대화형 인터프리터에서는, 완전히 빈 줄(즉 공백이나 주석조차 없는 것)은 다중 행 문장을 종료시킵니다.

2.1.8. 들여쓰기

논리적인 줄의 제일 앞에 오는 공백(스페이스와 탭)은 줄의 들여쓰기 수준을 계산하는 데 사용되고, 이는 다시 문장들의 묶음을 결정하는 데 사용되게 됩니다.

탭은 (왼쪽에서 오른쪽으로) 1~8개의 스페이스로 변환되는데, 치환된 후의 총 스페이스 문자 수가 8의 배수가 되도록 맞춥니다. (유닉스에서 사용되는 규칙에 맞추려는 것입니다.) 첫 번째 비 공백 문자 앞에 나오는 공백의 총수가 줄의 들여쓰기를 결정합니다. 들여쓰기는 역 슬래시를 사용해서 여러 개의 물리적인 줄로 나눠질 수 없습니다; 첫 번째 역 슬래시 이전의 공백이 들여쓰기를 결정합니다.

소스 파일이 탭과 스페이스를 섞어 쓰는 경우, 탭이 몇 개의 스페이스에 해당하는지에 따라 다르게 해석될 수 있으면 TabError 를 일으킵니다.

크로스-플랫폼 호환성 유의 사항: UNIX 이외의 플랫폼에서 편집기들이 동작하는 방식 때문에, 하나의 파일 내에서 들여쓰기를 위해 탭과 스페이스를 섞어 쓰는 것은 현명한 선택이 아닙니다. 다른 플랫폼들에서는 최대 들여쓰기 수준에 제한이 있을 수도 있다는 점도 주의해야 합니다.

폼 피드 문자는 줄의 처음에 나올 수 있습니다; 앞서 설명한 들여쓰기 수준 계산에서는 무시됩니다. 페이지 넘김 문자 앞에 공백이나 탭이 있는 경우는 정의되지 않은 효과를 줄 수 있습니다 (가령, 스페이스 수가 0으로 초기화될 수 있습니다).

연속된 줄의 들여쓰기 수준은, 스택을 사용해서, 다음과 같은 방법으로 INDENT와 DEDENT 토큰을 만드는 데 사용됩니다.

파일의 첫 줄을 읽기 전에 0하나를 스택에 넣습니다(push); 이 값은 다시 꺼내는(pop) 일이 없습니다. 스택에 넣는 값은 항상 스택의 아래에서 위로 올라갈 때 단조 증가합니다. 각 논리적인 줄의 처음에서 줄의 들여쓰기 수준이 스택의 가장 위에 있는 값과 비교됩니다. 같다면 아무런 일도 일어나지 않습니다. 더 크다면 그 값을 스택에 넣고 하나의 INDENT 토큰을 만듭니다. 더 작다면 이 값은 스택에 있는 값 중 하나여야만 합니다. 이 값보다 큰 모든 스택의 값들을 꺼내고(pop), 꺼낸 횟수만큼의 DEDENT 토큰을 만듭니다. 파일의 끝에서, 스택에 남아있는 0보다 큰 값의 개수만큼 DEDENT 토큰을 만듭니다.

여기에 (혼란스럽다 할지라도) 올바르게 들여쓰기 된 파이썬 코드 조각이 있습니다:

def perm(l):
        # Compute the list of all permutations of l
    if len(l) <= 1:
                  return [l]
    r = []
    for i in range(len(l)):
             s = l[:i] + l[i+1:]
             p = perm(s)
             for x in p:
              r.append(l[i:i+1] + x)
    return r

다음 예는 여러 가지 들여쓰기 에러를 보여줍니다:

 def perm(l):                       # error: first line indented
for i in range(len(l)):             # error: not indented
    s = l[:i] + l[i+1:]
        p = perm(l[:i] + l[i+1:])   # error: unexpected indent
        for x in p:
                r.append(l[i:i+1] + x)
            return r                # error: inconsistent dedent

(사실, 처음 세 개의 에러는 파서가 감지합니다. 단지 마지막 에러만 어휘 분석기가 감지합니다. — return r 의 들여쓰기가 스택에 있는 값과 일치하지 않습니다.)

2.1.9. 토큰 사이의 공백

논리적인 줄의 처음과 문자열 리터럴을 제외하고, 공백 문자인 스페이스, 탭, 폼 피드는 토큰을 분리하기 위해 섞어 쓸 수 있습니다. 두 토큰을 붙여 쓸 때 다른 토큰으로 해석될 수 있는 경우만 토큰 사이에 공백이 필요합니다. (예를 들어, ab 는 하나의 토큰이지만, a b 는 두 개의 토큰입니다.)

2.2. 다른 토큰들

NEWLINE, INDENT, DEDENT 와는 별도로, 다음과 같은 유형의 토큰들이 존재합니다: 식별자(identifier), 키워드(keyword), 리터럴(literal), 연산자(operator), 구분자(delimiter). (앞에서 살펴본 줄 종료 이외의) 공백 문자들은 토큰이 아니지만, 토큰을 분리하는 역할을 담당합니다. 모호할 경우, 왼쪽에서 오른쪽으로 읽을 때, 하나의 토큰은 올바르고 가능한 한 최대 길이의 문자열로 구성되는 것을 선호합니다.

2.3. 식별자와 키워드

식별자 (이름(name) 이라고도 합니다) 은 다음과 같은 어휘 정의로 기술됩니다.

파이썬에서 식별자의 문법은 유니코드 표준 부속서 UAX-31 에 기반을 두는데, 여기에 덧붙이거나 바꾼 내용은 아래에서 정의합니다. 좀 더 상세한 내용은 PEP 3131 [https://www.python.org/dev/peps/pep-3131] 에서 찾을 수 있습니다.

ASCII 범위 (U+0001..U+007F) 내에서, 올바른 식별자 문자는 파이썬 2.x 와 같습니다: A 에서 Z 범위의 대문자와 소문자, 밑줄 _, 첫 문자를 제외하고, 숫자 0 에서 9.

파이썬 3.0은 ASCII 범위 밖의 문자들을 도입합니다 (PEP 3131 [https://www.python.org/dev/peps/pep-3131] 참조). 이 문자들의 경우, unicodedata 모듈에 포함된 버전의 유니코드 문자 데이터베이스에 따라 분류됩니다.

식별자는 길이에 제한이 없고, 케이스(case)는 구분됩니다.

identifier   ::=  xid_start xid_continue*
id_start     ::=  <all characters in general categories Lu, Ll, Lt, Lm, Lo, Nl, the underscore, and characters with the Other_ID_Start property>
id_continue  ::=  <all characters in id_start, plus characters in the categories Mn, Mc, Nd, Pc and others with the Other_ID_Continue property>
xid_start    ::=  <all characters in id_start whose NFKC normalization is in "id_start xid_continue*">
xid_continue ::=  <all characters in id_continue whose NFKC normalization is in "id_continue*">

위에서 언급한 유니코드 카테고리 코드들의 의미는 이렇습니다:

Lu - uppercase letters

Ll - lowercase letters

Lt - titlecase letters

Lm - modifier letters

Lo - other letters

Nl - letter numbers

Mn - nonspacing marks

Mc - spacing combining marks

Nd - decimal numbers

Pc - connector punctuations

Other_ID_Start - 하위 호환성 지원을 위해 PropList.txt [http://www.unicode.org/Public/11.0.0/ucd/PropList.txt] 에서 명시적으로 나열된 문자들

Other_ID_Continue - 마찬가지

모든 식별자는 파서에 의해 NFKC 정규화 형식으로 변환되고, 식별자의 비교는 NFKC 에 기반을 둡니다.

A non-normative HTML file listing all valid identifier characters for Unicode 4.1 can be found at https://www.unicode.org/Public/13.0.0/ucd/DerivedCoreProperties.txt

2.3.1. 키워드

다음 식별자들은 예약어, 또는 언어의 키워드, 로 사용되고, 일반적인 식별자로 사용될 수 없습니다. 여기 쓰여 있는 것과 정확히 같게 사용되어야 합니다:

False      await      else       import     pass
None       break      except     in         raise
True       class      finally    is         return
and        continue   for        lambda     try
as         def        from       nonlocal   while
assert     del        global     not        with
async      elif       if         or         yield

2.3.2. 식별자의 예약 영역

(키워드와는 별개로) 어떤 부류의 식별자들은 특별한 의미가 있습니다. 이 부류의 식별자들은 시작과 끝의 밑줄 문자 패턴으로 구분됩니다:

_*

from module import * 에 의해 임포트되지 않습니다. 특별한 식별자 _ 는 대화형 인터프리터에서 마지막에 실행한 결과의 값을 저장하는 용도로 사용됩니다; builtins 모듈에 저장됩니다. 대화형 모드가 아닐 경우 _ 는 특별한 의미가 없고, 정의되지도 않습니다. 임포트(import) 문 섹션을 보세요.

참고

이름 _ 은 종종 국제화(internationalization)와 관련되어 사용됩니다. 이 관례에 관해서는 gettext 모듈의 문서를 참조하십시오.

__*__

System-defined names, informally known as “dunder” names. These names are defined by the interpreter and its implementation (including the standard library). Current system names are discussed in the 특수 메서드 이름들 section and elsewhere. More will likely be defined in future versions of Python. Any use of __*__ names, in any context, that does not follow explicitly documented use, is subject to breakage without warning.

__*

클래스-비공개 이름. 이 부류의 이름들을 클래스 정의 문맥에서 사용하면 뒤섞인 형태로 변형됩니다. 부모 클래스와 자식 클래스의 “비공개(private)” 어트리뷰트 간의 이름 충돌을 피하기 위함입니다. 식별자 (이름) 섹션을 보세요.

2.4. 리터럴

리터럴(literal)은 몇몇 내장형들의 상숫값을 위한 표기법입니다.

2.4.1. 문자열과 바이트열 리터럴

문자열 리터럴은 다음과 같은 어휘 정의로 기술됩니다:

stringliteral   ::=  [stringprefix](shortstring | longstring)
stringprefix    ::=  "r" | "u" | "R" | "U" | "f" | "F"
                     | "fr" | "Fr" | "fR" | "FR" | "rf" | "rF" | "Rf" | "RF"
shortstring     ::=  "'" shortstringitem* "'" | '"' shortstringitem* '"'
longstring      ::=  "'''" longstringitem* "'''" | '"""' longstringitem* '"""'
shortstringitem ::=  shortstringchar | stringescapeseq
longstringitem  ::=  longstringchar | stringescapeseq
shortstringchar ::=  <any source character except "\" or newline or the quote>
longstringchar  ::=  <any source character except "\">
stringescapeseq ::=  "\" <any source character>

bytesliteral   ::=  bytesprefix(shortbytes | longbytes)
bytesprefix    ::=  "b" | "B" | "br" | "Br" | "bR" | "BR" | "rb" | "rB" | "Rb" | "RB"
shortbytes     ::=  "'" shortbytesitem* "'" | '"' shortbytesitem* '"'
longbytes      ::=  "'''" longbytesitem* "'''" | '"""' longbytesitem* '"""'
shortbytesitem ::=  shortbyteschar | bytesescapeseq
longbytesitem  ::=  longbyteschar | bytesescapeseq
shortbyteschar ::=  <any ASCII character except "\" or newline or the quote>
longbyteschar  ::=  <any ASCII character except "\">
bytesescapeseq ::=  "\" <any ASCII character>

이 생성 규칙이 보여주지 못하는 한 가지 문법적 제약은 stringprefix 나 bytesprefix 와 리터럴의 나머지 부분 사이에 공백이 허락되지 않는다는 것입니다. 소스 문자 집합은 인코딩 선언으로 정의됩니다; 소스 파일에 인코딩 선언이 없으면 UTF-8입니다. 인코딩 선언 섹션을 보세요.

쉬운 말로 하자면, 두 가지 리터럴은 한 쌍의 작은따옴표(') 나 큰따옴표(")로 둘러싸일 수 있습니다. 또한, 둘 다 한 쌍의 삼중 작은따옴표나 큰따옴표로 둘러싸일 수도 있습니다 (이것들은 보통 삼중 따옴표 된 문자열 이라고 불립니다). 역 슬래시(\) 문자는 홀로 쓰이면 특별한 의미가 있는 문자들을 이스케이핑할 때 사용되는데, 개행문자, 역 슬래시 자신, 따옴표 문자가 그것입니다.

바이트열(bytes) 리터럴은 항상 'b' 나 'B' 를 앞에 붙입니다; str 형의 인스턴스 대신 bytes 형의 인스턴스를 만듭니다. 오직 ASCII 문자들만 포함할 수 있습니다. 코드값이 128보다 크거나 같은 값들은 반드시 이스케이핑으로 표현되어야 합니다.

문자열과 바이트열 리터럴 모두 선택적으로 'r' 이나 'R' 문자를 앞에 붙일 수 있습니다. 이런 문자열을 날 문자열(raw strings) 이라고 하는데, 역 슬래시를 평범한 문자로 취급합니다. 결과적으로, 문자열 리터럴에서, 날 문자열에 있는 '\U' 와 '\u' 이스케이프는 특별하게 처리되지 않습니다. 파이썬 2.x의 날 유니코드 리터럴이 파이썬 3.x와 다르게 동작합니다는 것을 고려해서, 'ur' 문법은 지원되지 않습니다.

버전 3.3에 추가: 날 바이트열 리터럴의 'br' 와 같은 의미가 있는 'rb' 접두어가 추가되었습니다.

버전 3.3에 추가: 파이썬 2.x 와 3.x 에서 동시에 지원하는 코드들의 유지보수를 단순화하기 위해 예전에 사용되던 유니코드 리터럴 (u'value')이 다시 도입되었습니다. 자세한 정보는 PEP 414 [https://www.python.org/dev/peps/pep-0414] 에 나옵니다.

'f' 나 'F' 를 접두어로 갖는 문자열 리터럴은 포맷 문자열 리터럴(formatted string literal)입니다; 포맷 문자열 리터럴 을 보세요. 'f' 는 'r' 과 결합할 수 있습니다, 하지만, 'b' 나 'u' 와는 결합할 수 없습니다. 따라서 날 포맷 문자열은 가능하지만, 포맷 바이트열 리터럴은 불가능합니다.

삼중 따옴표 된 리터럴에서, 세 개의 이스케이핑 되지 않은 개행 문자와 따옴표가 허락됩니다 (그리고 유지됩니다). 예외는 한 줄에 세 개의 이스케이핑 되지 않은 따옴표가 나오는 것인데, 리터럴을 종료시킵니다. (“따옴표”는 리터럴을 시작하는데 사용한 문자입니다. 즉, ' 나 ")

'r' 나 'R' 접두어가 붙지 않은 이상, 문자열과 바이트열 리터럴에 포함된 이스케이프 시퀀스는 표준 C에서 사용된 것과 비슷한 규칙으로 해석됩니다. 인식되는 이스케이프 시퀀스는 이렇습니다:

이스케이프 시퀀스

의미

유의 사항

\newline

역 슬래시와 개행 문자가 무시됩니다

\\

역 슬래시 (\)

\'

작은따옴표 (')

\"

큰따옴표 (")

\a

ASCII 벨 (BEL)

\b

ASCII 백스페이스 (BS)

\f

ASCII 폼 피드 (FF)

\n

ASCII 라인 피드 (LF)

\r

ASCII 캐리지 리턴 (CR)

\t

ASCII 가로 탭 (TAB)

\v

ASCII 세로 탭 (VT)

\ooo

8진수 ooo 로 지정된 문자

(1,3)

\xhh

16진수 hh 로 지정된 문자

(2,3)

문자열 리터럴에서만 인식되는 이스케이프 시퀀스는:

이스케이프 시퀀스

의미

유의 사항

\N{name}

유니코드 데이터베이스에서 name 이라고 이름 붙여진 문자

(4)

\uxxxx

16-bit 16진수 xxxx 로 지정된 문자

(5)

\Uxxxxxxxx

32-bit 16진수 xxxxxxxx 로 지정된 문자

(6)

유의 사항:

표준 C와 마찬가지로, 최대 세 개의 8진수가 허용됩니다.

표준 C와는 달리, 정확히 두 개의 16진수가 제공되어야 합니다.

바이트열 리터럴에서, 16진수와 8진수 이스케이프는 지정된 값의 바이트를 표현합니다. 문자열 리터럴에서는, 이 이스케이프는 지정된 값의 유니코드 문자를 표현합니다.

버전 3.3에서 변경: 별칭 1 지원이 추가되었습니다

정확히 4개의 16진수를 필요로 합니다.

이 방법으로 모든 유니코드를 인코딩할 수 있습니다. 정확히 8개의 16진수가 필요합니다.

표준 C와는 달리, 인식되지 않는 모든 이스케이프 시퀀스는 문자열에 변경되지 않은 상태로 남게 됩니다. 즉, 역 슬래시가 결과에 남게 됩니다. (이 동작은 디버깅할 때 쓸모가 있습니다. 이스케이프 시퀀스가 잘못 입력되었을 때, 최종 결과에서 잘못된 부분을 쉽게 인지할 수 있습니다.) 문자열 리터럴에서만 인식되는 이스케이프 시퀀스가, 바이트열 리터럴에서는 인식되지 않는 부류임에 주목하십시오.

버전 3.6에서 변경: 인식되지 않는 이스케이프 시퀀스는 DeprecationWarning 을 만듭니다. 언젠가 파이썬의 미래 버전에서는 SyntaxError 로 취급될 것입니다.

날 리터럴에서 조차, 따옴표는 역 슬래시로 이스케이프 됩니다. 하지만 역 슬래시가 결과에 남게 됩니다; 예를 들어, r"\"" 는 올바른 문자열 리터럴인데, 두 개의 문자가 들어있습니다: 역 슬래시와 큰따옴표; r"\" 는 올바른 문자열 리터럴이 아닙니다 (날 문자열조차 홀수개의 역 슬래시로 끝날 수 없습니다.). 좀 더 명확하게 말하자면, 날 리터럴은 하나의 역 슬래시로 끝날 수 없습니다(역 슬래시가 뒤에 오는 따옴표를 이스케이프 시키기 때문입니다). 역 슬래시와 바로 뒤에 오는 개행문자는 줄 결합이 아니라 리터럴에 포함되는 두 개의 문자로 인식됨에 주의해야 합니다.

2.4.2. 문자열 리터럴 이어붙이기

여러 개의 문자열이나 바이트열 리터럴을 (공백으로 분리해서) 여러 개 인접해서 나열하는 것이 허락되고, 그 의미는 이어붙인 것과 같습니다. 각 리터럴이 서로 다른 따옴표를 사용해도 됩니다. 그래서, "hello" 'world' 는 "helloworld" 와 동등합니다. 이 기능은 긴 문자열을 편의상 여러 줄로 나눌 때 필요한 역 슬래시를 줄여줍니다. 각 문자열 단위마다 주석을 붙이는 것도 가능합니다. 예를 들어:

re.compile("[A-Za-z_]"       # letter or underscore
           "[A-Za-z0-9_]*"   # letter, digit or underscore
          )

이 기능이 문법 수준에서 정의되고는 있지만, 컴파일 시점에 구현됨에 주의해야 합니다. 실행 시간에 문자열 표현을 이어붙이기 위해서는 ‘+’ 연산자를 사용해야 합니다. 리터럴 이어붙이기가 요소별로 다른 따옴표를 사용할 수 있고 (날 문자열과 삼중 따옴표 문자열을 이어붙이는 것조차 가능합니다), 포맷 문자열 리터럴을 보통 문자열 리터럴과 이어붙일 수 있음에 유의해야 합니다.

2.4.3. 포맷 문자열 리터럴

버전 3.6에 추가.

포맷 문자열 리터럴(formatted string literal) 또는 f-문자열 (f-string) 은 'f' 나 'F' 를 앞에 붙인 문자열 리터럴입니다. 이 문자열은 치환 필드를 포함할 수 있는데, 중괄호 {} 로 구분되는 표현식입니다. 다른 문자열 리터럴이 항상 상숫값을 갖지만, 포맷 문자열 리터럴은 실행시간에 계산되는 표현식입니다.

이스케이프 시퀀스는 일반 문자열 리터럴처럼 디코딩됩니다 (동시에 날 문자열인 경우는 예외입니다). 디코딩 후에 문자열의 내용은 다음과 같은 문법을 따릅니다:

f_string          ::=  (literal_char | "{{" | "}}" | replacement_field)*
replacement_field ::=  "{" f_expression ["!" conversion] [":" format_spec] "}"
f_expression      ::=  (conditional_expression | "*" or_expr)
                         ("," conditional_expression | "," "*" or_expr)* [","]
                       | yield_expression
conversion        ::=  "s" | "r" | "a"
format_spec       ::=  (literal_char | NULL | replacement_field)*
literal_char      ::=  <any code point except "{", "}" or NULL>

중괄호 바깥 부분은 일반 리터럴처럼 취급되는데, 이중 중괄호 '{{' 나 '}}' 가 대응하는 단일 중괄호로 치환된다는 점만 예외입니다. 하나의 여는 중괄호 '{' 는 치환 필드를 시작시키는데, 파이썬 표현식이 뒤따릅니다. 표현식 뒤로는 변환(conversion) 필드가 올 수 있는데, 느낌표 '!' 로 시작합니다. 포맷 지정자(format specifier)도 덧붙일 수 있는데, 콜론 ':' 으로 시작합니다. 치환 필드는 닫는 중괄호 '}' 로 끝납니다.

포맷 문자열 리터럴의 표현식은 괄호로 둘러싸인 일반적인 파이썬 표현식으로 취급되는데, 몇 가지 예외가 있습니다. 빈 표현식은 허락되지 않고, lambda 표현식은 명시적인 괄호로 둘러싸야 합니다. 치환 표현식은 개행문자를 포함할 수 있으나 (예를 들어, 삼중 따옴표 된 문자열) 주석은 포함할 수 없습니다. 각 표현식은 포맷 문자열 리터럴이 등장한 지점의 문맥에서 왼쪽에서 오른쪽으로 계산됩니다.

버전 3.7에서 변경: Prior to Python 3.7, an await expression and comprehensions containing an async for clause were illegal in the expressions in formatted string literals due to a problem with the implementation.

변환(conversion)이 지정되면, 표현식의 결과가 포매팅 전에 변환됩니다. 변환 '!s' 는 결과에 str() 을 호출하고, '!r' 은 repr() 을 호출하고, '!a' 은 ascii() 를 호출합니다.

결과는 format() 프로토콜로 포매팅합니다. 포맷 지정자는 표현식이나 변환 결과의 __format__() 메서드 로 전달됩니다. 포맷 지정자가 생략되면 빈 문자열이 전달됩니다. 이제 포맷된 결과가 최종 문자열에 삽입됩니다.

최상위 포맷 지정자는 중첩된 치환 필드들을 포함할 수 있습니다. 이 중첩된 필드들은 그들 자신의 변환 필드와 포맷 지정자를 포함할 수 있지만, 깊이 중첩된 치환 필드들을 포함할 수는 없습니다. 포맷 지정자 간이 언어는 문자열 .format() 메서드에서 사용되는 것과 같습니다.

포맷 문자열 리터럴을 이어붙일 수는 있지만, 치환 필드가 여러 리터럴로 쪼개질 수는 없습니다.

포맷 문자열 리터럴의 예를 들면:

>>> name = "Fred"
>>> f"He said his name is {name!r}."
"He said his name is 'Fred'."
>>> f"He said his name is {repr(name)}."  # repr() is equivalent to !r
"He said his name is 'Fred'."
>>> width = 10
>>> precision = 4
>>> value = decimal.Decimal("12.34567")
>>> f"result: {value:{width}.{precision}}"  # nested fields
'result:      12.35'
>>> today = datetime(year=2017, month=1, day=27)
>>> f"{today:%B %d, %Y}"  # using date format specifier
'January 27, 2017'
>>> number = 1024
>>> f"{number:#0x}"  # using integer format specifier
'0x400'

일반적인 문자열 리터럴과 같은 문법을 공유하는 것으로 인한 결과는 치환 필드에 사용되는 문자들이 포맷 문자열 리터럴을 감싸는 따옴표와 충돌하지 않아야 한다는 것입니다:

f"abc {a["x"]} def"    # error: outer string literal ended prematurely
f"abc {a['x']} def"    # workaround: use different quoting

포맷 표현식에는 역 슬래시를 사용할 수 없고, 사용하면 에러가 발생합니다:

f"newline: {ord('\n')}"  # raises SyntaxError

역 슬래시 이스케이프가 필요한 값을 포함하려면, 임시 변수를 만들면 됩니다.

>>> newline = ord('\n')
>>> f"newline: {newline}"
'newline: 10'

포맷 문자열 리터럴은 독스트링(docstring)으로 사용될 수 없습니다. 표현식이 전혀 없더라도 마찬가집니다.

>>> def foo():
...     f"Not a docstring"
...
>>> foo.__doc__ is None
True

포맷 문자열 리터럴 추가에 대한 제안은 PEP 498 [https://www.python.org/dev/peps/pep-0498] 을 참조하고, 관련된 포맷 문자열 메커니즘을 사용하는 str.format() 도 살펴보는 것이 좋습니다.

2.4.4. 숫자 리터럴

숫자 리터럴에는 세 가지 종류가 있습니다: 정수, 실수, 허수. 복소수 리터럴 같은 것은 없습니다 (복소수는 실수와 허수를 더해서 만들어집니다.)

숫자 리터럴이 부호를 포함하지 않는 것에 주의해야 합니다; -1 과 같은 구문은 일 항 연산자 ‘-’ 과 리터럴 1 로 구성된 표현식입니다.

2.4.5. 정수 리터럴

정수 리터럴은 다음과 같은 어휘 정의로 표현됩니다:

integer      ::=  decinteger | bininteger | octinteger | hexinteger
decinteger   ::=  nonzerodigit (["_"] digit)* | "0"+ (["_"] "0")*
bininteger   ::=  "0" ("b" | "B") (["_"] bindigit)+
octinteger   ::=  "0" ("o" | "O") (["_"] octdigit)+
hexinteger   ::=  "0" ("x" | "X") (["_"] hexdigit)+
nonzerodigit ::=  "1"..."9"
digit        ::=  "0"..."9"
bindigit     ::=  "0" | "1"
octdigit     ::=  "0"..."7"
hexdigit     ::=  digit | "a"..."f" | "A"..."F"

가용한 메모리에 저장될 수 있는지와는 별개로 정수 리터럴의 길이에 제한은 없습니다.

밑줄은 리터럴의 숫자 값을 결정할 때 고려되지 않습니다. 가독성을 높이기 위해 숫자들을 무리 지을 때 쓸모가 있습니다. 밑줄은 숫자 사이나 0x 와 같은 진수 지정자(base specifier) 다음에 나올 수 있는데, 한 번에 하나만 사용될 수 있습니다.

0 이 아닌 10진수가 0으로 시작할 수 없음에 주의해야 합니다. 3.0 버전 이전의 파이썬에서 사용한 C 스타일의 8진수 리터럴과 혼동되는 것을 막기 위함입니다.

정수 리터럴의 예를 들면:

7     2147483647                        0o177    0b100110111
3     79228162514264337593543950336     0o377    0xdeadbeef
      100_000_000_000                   0b_1110_0101

버전 3.6에서 변경: 리터럴에서 숫자들의 그룹을 표현할 목적으로 밑줄을 허락합니다.

2.4.6. 실수 리터럴

실수 리터럴은 다음과 같은 어휘 정의로 표현됩니다:

floatnumber   ::=  pointfloat | exponentfloat
pointfloat    ::=  [digitpart] fraction | digitpart "."
exponentfloat ::=  (digitpart | pointfloat) exponent
digitpart     ::=  digit (["_"] digit)*
fraction      ::=  "." digitpart
exponent      ::=  ("e" | "E") ["+" | "-"] digitpart

정수부와 지수부는 항상 10진법으로 해석된다는 것에 주의해야 합니다. 예를 들어, 077e010 는 올바른 표현이고, 77e10 과 같은 숫자를 표현합니다. 실수 리터럴의 허락된 범위는 구현 세부 사항입니다. 정수 리터럴에서와 마찬가지로 밑줄로 숫자들의 묶음을 만드는 것도 지원됩니다.

실수 리터럴의 몇 가지 예를 듭니다:

3.14    10.    .001    1e100    3.14e-10    0e0    3.14_15_93

버전 3.6에서 변경: 리터럴에서 숫자들의 그룹을 표현할 목적으로 밑줄을 허락합니다.

2.4.7. 허수 리터럴

허수 리터럴은 다음과 같은 어휘 정의로 표현됩니다:

imagnumber ::=  (floatnumber | digitpart) ("j" | "J")

허수 리터럴은 실수부가 0.0인 복소수를 만듭니다. 복소수는 실수와 같은 범위 제약이 적용되는 한 쌍의 실수로 표현됩니다. 0이 아닌 실수부를 갖는 복소수를 만들려면, 실수를 더하면 됩니다. 예를 들어, (3+4j). 허수 리터럴의 몇 가지 예를 듭니다:

3.14j   10.j    10j     .001j   1e100j   3.14e-10j   3.14_15_93j

2.5. 연산자

다음과 같은 토큰들은 연산자입니다:

+       -       *       **      /       //      %      @
<<      >>      &       |       ^       ~
<       >       <=      >=      ==      !=

2.6. 구분자

다음 토큰들은 문법에서 구분자(delimiter)로 기능합니다:

(       )       [       ]       {       }
,       :       .       ;       @       =       ->
+=      -=      *=      /=      //=     %=      @=
&=      |=      ^=      >>=     <<=     **=

마침표는 실수와 허수 리터럴에서도 등장할 수 있습니다. 연속된 마침표 세 개는 생략부호 리터럴(ellipsis literal)이라는 특별한 의미가 있습니다. 목록 후반의 증분 대입 연산자(augmented assignment operator)들은 어휘적으로는 구분자로 기능하지만, 동시에 연산을 수행합니다.

다음의 인쇄되는 ASCII 문자들은 다른 토큰들 일부로서 특별한 의미가 있거나, 그렇지 않으면 어휘 분석기에 유의미합니다:

'       "       #       \

다음의 인쇄되는 ASCII 문자들은 파이썬에서 사용되지 않습니다. 문자열 리터럴과 주석 이외의 곳에서 사용되는 것은 조건 없는 에러입니다:

$       ?       `

각주

1

http://www.unicode.org/Public/11.0.0/ucd/NameAliases.txt

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 언어 레퍼런스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 언어 레퍼런스 »

|

3. 데이터 모델

3.1. 객체, 값, 형

Objects are Python’s abstraction for data. All data in a Python program is represented by objects or by relations between objects. (In a sense, and in conformance to Von Neumann’s model of a “stored program computer”, code is also represented by objects.)

모든 객체는 아이덴티티(identity), 형(type), 값(value)을 갖습니다. 객체의 아이덴티티 는 한 번 만들어진 후에는 변경되지 않습니다. 메모리상에서의 객체의 주소로 생각해도 좋습니다. ‘is’ 연산자는 두 객체의 아이덴티티를 비교합니다; id() 함수는 아이덴티티를 정수로 표현한 값을 돌려줍니다.

CPython implementation detail: CPython 의 경우, id(x) 는 x 가 저장된 메모리의 주소입니다.

객체의 형은 객체가 지원하는 연산들을 정의하고 (예를 들어, “길이를 갖고 있나?”) 그 형의 객체들이 가질 수 있는 가능한 값들을 정의합니다. type() 함수는 객체의 형(이것 역시 객체다)을 돌려줍니다. 아이덴티티와 마찬가지로, 객체의 형 (type) 역시 변경되지 않습니다. 1

어떤 객체들의 값 은 변경할 수 있습니다. 값을 변경할 수 있는 객체들을 가변(mutable) 이라고 합니다. 일단 만들어진 후에 값을 변경할 수 없는 객체들을 불변(immutable) 이라고 합니다. (가변 객체에 대한 참조를 저장하고 있는 불변 컨테이너의 값은 가변 객체의 값이 변할 때 변경된다고 볼 수도 있습니다; 하지만 저장하고 있는 객체들의 집합이 바뀔 수 없으므로 컨테이너는 여전히 불변이라고 여겨집니다. 따라서 불변성은 엄밀하게는 변경 불가능한 값을 갖는 것과는 다릅니다. 좀 더 미묘합니다.) 객체의 가변성(mutability)은 그것의 형에 의해 결정됩니다; 예를 들어 숫자, 문자열, 튜플(tuple)은 불변이지만, 딕셔너리(dictionary) 와 리스트(list)는 가변입니다.

객체는 결코 명시적으로 파괴되지 않습니다; 더 참조되지 않을 때(unreachable) 가비지 수거(garbage collect)됩니다. 구현이 가비지 수거를 지연시키거나 아예 생략하는 것이 허락됩니다 — 아직 참조되는 객체들을 수거하지 않는 이상 가비지 수거가 어떤 식으로 구현되는지는 구현의 품질 문제입니다.

CPython implementation detail: CPython 은 현재 참조 횟수 계산(reference-counting) 방식을 사용하는데, (선택 사항으로) 순환적으로 연결된 가비지의 지연된 감지가 추가됩니다. 이 방법으로 대부분 객체를 참조가 제거되자마자 수거할 수 있습니다. 하지만 순환 참조가 있는 가비지들을 수거한다는 보장은 없습니다. 순환적 가비지 수거의 제어에 관한 정보는 gc 모듈 문서를 참조하면 됩니다. 다른 구현들은 다른 식으로 동작하고, CPython 도 변경될 수 있습니다. 참조가 제거될 때 즉각적으로 파이널리제이션(finalization)되는 것에 의존하지 말아야 합니다 (그래서 항상 파일을 명시적으로 닫아주어야 합니다).

구현이 제공하는 추적이나 디버깅 장치의 사용은 그렇지 않으면 수거될 수 있는 객체들을 살아있도록 만들 수 있음에 주의해야 합니다. 또한 ‘try…except’ 문으로 예외를 잡는 것도 객체를 살아있게 만들 수 있습니다.

어떤 객체들은 열린 파일이나 창 같은 “외부(external)” 자원들에 대한 참조를 포함합니다. 이 자원들은 객체가 가비지 수거될 때 반납된다고 이해되지만, 가비지 수거는 보장되는 것이 아니므로, 그런 객체들은 외부자원을 반납하는 명시적인 방법 또한 제공합니다. 보통 close() 메서드다. 프로그램을 작성할 때는 그러한 객체들을 항상 명시적으로 닫아야(close) 합니다. ‘try…finally’ 문과 ‘with’ 문은 이렇게 하는 편리한 방법을 제공합니다.

어떤 객체들은 다른 객체에 대한 참조를 포함하고 있습니다. 이런 것들을 컨테이너(container) 라고 부릅니다. 튜플, 리스트, 딕셔너리등이 컨테이너의 예입니다. 이 참조들은 컨테이너의 값의 일부입니다. 대부분은, 우리가 컨테이너의 값을 논할 때는, 들어있는 객체들의 아이덴티티 보다는 값을 따집니다. 하지만, 컨테이너의 가변성에 대해 논할 때는 직접 가진 객체들의 아이덴티티만을 따집니다. 그래서, (튜플 같은) 불변 컨테이너가 가변 객체로의 참조를 하고 있다면, 그 가변 객체가 변경되면 컨테이너의 값도 변경됩니다.

형은 거의 모든 측면에서 객체가 동작하는 방법에 영향을 줍니다. 객체의 아이덴티디가 갖는 중요성조차도 어떤 면에서는 영향을 받습니다: 불변형의 경우, 새 값을 만드는 연산은 실제로는 이미 존재하는 객체 중에서 같은 형과 값을 갖는 것을 돌려줄 수 있습니다. 반면에 가변 객체에서는 이런 것이 허용되지 않습니다. 예를 들어, a = 1; b = 1 후에, a 와 b 는 값 1을 갖는 같은 객체일 수도 있고, 아닐 수도 있습니다. 하지만 c = []; d = [] 후에, c 와 d 는 두 개의 서로 다르고, 독립적이고, 새로 만들어진 빈 리스트임이 보장됩니다. (c = d = [] 는 객은 객체를 c 와 d 에 대입합니다.)

3.2. 표준형 계층

아래에 파이썬에 내장된 형들의 목록이 있습니다. (구현에 따라 C 나 자바나 다른 언어로 작성된) 확장 모듈들은 추가의 형을 정의할 수 있습니다. 파이썬의 미래 버전 역시 형 계층에 형을 더할 수 있는데 (예를 들어, 유리수, 효율적으로 저장된 정수 배열 등등), 표준 라이브러리를 통해 추가될 가능성이 더 크기는 합니다.

아래에 나오는 몇몇 형에 대한 설명은 ‘특수 어트리뷰트(special attribute)’ 를 나열하는 문단을 포함합니다. 이것들은 구현에 접근할 방법을 제공하는데, 일반적인 사용을 위한 것이 아닙니다. 정의는 앞으로 변경될 수 있습니다.

None

이 형은 하나의 값만을 갖습니다. 이 값을 갖는 하나의 객체가 존재합니다. 이 객체에는 내장된 이름 None 을 통해 접근합니다. 여러 가지 상황에서 값의 부재를 알리는 데 사용됩니다. 예를 들어, 명시적으로 뭔가를 돌려주지 않는 함수의 반환 값입니다. 논리값은 거짓입니다.

NotImplemented

이 형은 하나의 값만을 갖습니다. 이 값을 갖는 하나의 객체가 존재합니다. 이 객체에는 내장된 이름 NotImplemented 을 통해 접근합니다. 숫자 메서드(numeric method)와 비교(rich comparison) 메서드는 제공된 피연산자에 대해 연산이 구현되지 않으면 이 값을 돌려줘야 합니다. (그러면 인터프리터는 연산자에 따라 뒤집힌 연산이나, 어떤 다른 대안을 시도합니다.) 논리값은 참입니다.

더 자세한 내용은 산술 연산 구현 을 참고하십시오.

Ellipsis

이 형은 하나의 값만을 갖습니다. 이 값을 갖는 하나의 객체가 존재합니다. 이 객체에는 리터럴 ... 이나 내장된 이름 Ellipsis 을 통해 접근합니다. 논리값은 참입니다.

numbers.Number

이것들은 숫자 리터럴에 의해 만들어지고, 산순 연산과 내장 산술 함수들이 결과로 돌려줍니다. 숫자 객체는 불변입니다; 한 번 값이 만들어지면 절대 변하지 않습니다. 파이썬의 숫자는 당연히 수학적인 숫자들과 밀접하게 관련되어 있습니다, 하지만 컴퓨터의 숫자 표현상의 제약을 받고 있습니다.

파이썬은 정수, 실수, 복소수를 구분합니다:

numbers.Integral

이것들은 수학적인 정수 집합(양과 음)에 속하는 요소들을 나타냅니다.

두 가지 종류의 정수가 있습니다:

정수 (int)

이것은 (가상) 메모리가 허락하는 한, 제약 없는 범위의 숫자를 표현합니다. 시프트(shift)와 마스크(mask) 연산이 목적일 때는 이진 표현이 가정되고, 음수는 일종의 2의 보수(2’s complement)로 표현되는데, 부호 비트가 왼쪽으로 무한히 확장된 것과 같은 효과를 줍니다.

불린 (bool)

이것은 논리값 거짓과 참을 나타냅니다. False 와 True 두 객체만 불린 형 객체입니다. 불린 형은 int 형의 자식형(subtype)이고, 대부분 상황에서 각기 0과1처럼 동작합니다. 예외는 문자열로 변환되는 경우인데, 각기 문자열 "False" 와 "True" 가 반환됩니다.

정수 표현 규칙은 음수가 포함된 시프트와 마스크 연산에 가장 의미 있는 해석을 제공하기 위한 것입니다.

numbers.Real (float)

이것들은 기계 수준의 배정도(double precision) 부동 소수점 수를 나타냅니다. 허락되는 값의 범위와 오버플로의 처리에 관해서는 하부 기계의 설계(와 C 나 자바 구현)에 따르는 수밖에 없습니다. 파이썬은 단정도(single precision) 부동 소수점 수를 지원하지 않습니다; 이것들을 사용하는 이유가 되는 프로세서와 메모리의 절감은 파이썬에서 객체를 사용하는데 들어가는 비용과 상쇄되어 미미해집니다. 그 때문에 두 가지 종류의 부동 소수점 수로 언어를 복잡하게 만들만한 가치가 없습니다.

numbers.Complex (complex)

이것들은 기계 수준 배정도 부동 소수점 수의 쌍으로 복소수를 나타냅니다. 부동 소수점 수와 한계와 문제점을 공유합니다. 복소수 z 의 실수부와 허수부는, 읽기 전용 어트리뷰트 z.real 와 z.imag 로 꺼낼 수 있습니다.

시퀀스들

음이 아닌 정수로 인덱싱(indexing)될 수 있는 유한한 길이의 순서 있는 집합을 나타냅니다. 내장함수 len() 은 시퀀스가 가진 항목들의 개수를 돌려줍니다. 시퀀스의 길이가 n 일 때, 인덱스(index) 집합은 숫자 0, 1, …, n-1을 포함합니다. 시퀀스 a 의 항목 i 는 a[i] 로 선택됩니다.

시퀀스는 슬라이싱도 지원합니다: a[i:j] 는 i <= k < j 를 만족하는 모든 항목 k 를 선택합니다. 표현식에서 사용될 때, 슬라이스는 같은 형의 시퀀스입니다. 인덱스 집합은 0에서 시작되도록 다시 번호 매겨집니다.

어떤 시퀀스는 세 번째 “스텝(step)” 매개변수를 사용하는 “확장 슬라이싱(extended slicing)”도 지원합니다: a[i:j:k] 는 x = i + n*k, n >= 0, i <= x < j 를 만족하는 모든 항목 x 를 선택합니다.

시퀀스는 불변성에 따라 구분됩니다

불변 시퀀스

불변 시퀀스 형의 객체는 일단 만들어진 후에는 변경될 수 없습니다. (만약 다른 객체로의 참조를 포함하면, 그 객체는 가변일 수 있고, 변경될 수 있습니다; 하지만, 불변 객체로부터 참조되는 객체의 집합 자체는 변경될 수 없습니다.)

다음과 같은 형들은 불변 시퀀스입니다:

문자열(Strings)

문자열은 유니코드 코드 포인트(Unicode code point)들을 표현하는 값들의 시퀀스입니다. U+0000 - U+10FFFF 범위의 모든 코드 포인트들은 문자열로 표현될 수 있습니다. 파이썬에는 char 형이 없습니다. 대신에 문자열에 있는 각 코드 포인트는 길이 1 인 문자열 객체로 표현됩니다. 내장 함수 ord() 는 코드 포인트를 문자열 형식에서 0 - 10FFFF 범위의 정수로 변환합니다; chr() 은 범위 0 - 10FFFF 의 정수를 해당하는 길이 1 의 문자열 객체로 변환합니다. str.encode() 는 주어진 텍스트 인코딩을 사용해서 str 을 bytes 로 변환하고, bytes.decode() 는 그 반대 작업을 수행합니다.

튜플(Tuples)

튜플의 항목은 임의의 파이썬 객체입니다. 두 개 이상의 항목으로 구성되는 튜플은 콤마로 분리된 표현식의 목록으로 만들 수 있습니다. 하나의 항목으로 구성된 튜플(싱글턴,singleton)은 표현식에 콤마를 붙여서 만들 수 있습니다(괄호로 표현식을 묶을 수 있으므로, 표현식 만으로는 튜플을 만들지 않습니다). 빈 튜플은 한 쌍의 빈 괄호로 만들 수 있습니다.

바이트열(Bytes)

바이트열(bytes) 객체는 불변 배열입니다. 항목은 8-비트 바이트인데, 0 <= x < 256 범위의 정수로 표현됩니다. 바이트 객체를 만들 때는 바이트열 리터럴(b'abc' 와 같은) 과 내장 bytes() 생성자(constructor)를 사용할 수 있습니다. 또한, 바이트열 객체는 decode() 메서드를 통해 문자열로 디코딩될 수 있습니다.

가변 시퀀스

가변 시퀀스는 만들어진 후에 변경될 수 있습니다. 서브스크립션(subscription)과 슬라이싱은 대입문과 del (삭제) 문의 대상으로 사용될 수 있습니다.

현재 두 개의 내장 가변 시퀀스형이 있습니다:

리스트(Lists)

리스트의 항목은 임의의 파이썬 객체입니다. 리스트는 콤마로 분리된 표현식을 대괄호 안에 넣어서 만들 수 있습니다. (길이 0이나 1의 리스트를 만드는데 별도의 규칙이 필요 없습니다.)

바이트 배열(Byte Arrays)

바이트 배열(bytearray) 객체는 가변 배열입니다. 내장 bytearray() 생성자로 만들어집니다. 가변이라는 것(그래서 해싱 불가능하다는 것)을 제외하고, 바이트 배열은 불변 바이트열( bytes) 객체와 같은 인터페이스와 기능을 제공합니다.

확장 모듈 array 는 추가의 가변 시퀀스 형을 제공하는데, collections 모듈 역시 마찬가지입니다.

집합 형들(Set types)

이것들은 중복 없는 불변 객체들의 순서 없고 유한한 집합을 나타냅니다. 인덱싱할 수 없습니다. 하지만 이터레이트할 수 있고, 내장 함수 len() 은 집합 안에 있는 항목들의 개수를 돌려줍니다. 집합의 일반적인 용도는 빠른 멤버십 검사(fast membership testing), 시퀀스에서 중복된 항목 제거, 교집합(intersection), 합집합(union), 차집합(difference), 대칭차집합(symmetric difference)과 같은 집합 연산을 계산하는 것입니다.

집합의 원소들에는 딕셔너리 키와 같은 불변성 규칙이 적용됩니다. 숫자 형의 경우는 숫자 비교에 관한 일반 원칙이 적용된다는 점에 주의해야 합니다: 만약 두 숫자가 같다고 비교되면(예를 들어, 1 과 1.0), 그중 하나만 집합에 들어갈 수 있습니다.

현재 두 개의 내장 집합 형이 있습니다:

집합(Sets)

이것들은 가변 집합을 나타냅니다. 내장 set() 생성자로 만들 수 있고, add() 같은 메서드들을 사용해서 나중에 수정할 수 있습니다.

불변 집합(Frozen sets)

이것들은 불변 집합을 나타냅니다. 내장 frozenset() 생성자로 만들 수 있습니다. 불변 집합(frozenset)은 불변이고 해시 가능 하므로, 다른 집합의 원소나, 딕셔너리의 키로 사용될 수 있습니다.

매핑(Mappings)

이것들은 임의의 인덱스 집합으로 인덱싱되는 객체들의 유한한 집합을 나타냅니다. 인덱스 표기법(subscript notation) a[k] 는 매핑 a 에서 k 로 인덱스 되는 항목을 선택합니다; 이것은 표현식에 사용될 수도 있고, 대입이나 del 문장의 대상이 될 수도 있습니다. 내장 함수 len() 은 매핑에 포함된 항목들의 개수를 돌려줍니다.

현재 한 개의 내장 매핑 형이 있습니다:

딕셔너리(Dictionaries)

이것들은 거의 임의의 인덱스 집합으로 인덱싱되는 객체들의 유한한 집합을 나타냅니다. 키로 사용할 수 없는 것들은 리스트, 딕셔너리나 그 외의 가변형 중에서 아이덴티티가 아니라 값으로 비교되는 것들뿐입니다. 딕셔너리의 효율적인 구현이, 키의 해시값이 도중에 변경되지 않고 계속 같은 값으로 유지되도록 요구하고 있기 때문입니다. 키로 사용되는 숫자 형의 경우는 숫자 비교에 관한 일반 원칙이 적용됩니다: 만약 두 숫자가 같다고 비교되면(예를 들어, 1 과 1.0), 둘 다 같은 딕셔너리 항목을 인덱싱하는데 사용될 수 있습니다.

Dictionaries preserve insertion order, meaning that keys will be produced in the same order they were added sequentially over the dictionary. Replacing an existing key does not change the order, however removing a key and re-inserting it will add it to the end instead of keeping its old place.

딕셔너리는 가변입니다; {...} 표기법으로 만들 수 있습니다 (딕셔너리 디스플레이 섹션을 참고하십시오).

확장 모듈 dbm.ndbm 과 dbm.gnu 는 추가의 매핑 형을 제공하는데, collections 모듈 역시 마찬가지입니다.

버전 3.7에서 변경: Dictionaries did not preserve insertion order in versions of Python before 3.6. In CPython 3.6, insertion order was preserved, but it was considered an implementation detail at that time rather than a language guarantee.

콜러블(Callable types)

이것들은 함수 호출 연산(호출 섹션 참고)이 적용될 수 있는 형들입니다:

사용자 정의 함수

사용자 정의 함수 객체는 함수 정의를 통해 만들어집니다 (함수 정의 섹션 참고). 함수의 형식 매개변수(formal parameter) 목록과 같은 개수의 항목을 포함하는 인자(argument) 목록으로 호출되어야 합니다.

특수 어트리뷰트들(Special attributes):

어트리뷰트

의미

__doc__

함수를 설명하는 문자열 또는 없는 경우 None; 서브 클래스로 상속되지 않습니다.

쓰기 가능

__name__

함수의 이름.

쓰기 가능

__qualname__

함수의 정규화된 이름.

버전 3.3에 추가.

쓰기 가능

__module__

함수가 정의된 모듈의 이름 또는 (없는 경우) None

쓰기 가능

__defaults__

인자의 기본값 또는 (없는 경우) None 으로 만들어진 튜플.

쓰기 가능

__code__

컴파일된 함수의 바디(body) 를 나타내는 코드 객체

쓰기 가능

__globals__

함수의 전역 변수들을 가진 딕셔너리에 대한 참조 — 함수가 정의된 모듈의 전역 이름 공간(namespace)

읽기 전용

__dict__

임의의 함수 어트리뷰트를 지원하는 이름 공간.

쓰기 가능

__closure__

None 또는 함수의 자유 변수(free variable)들에 대한 연결을 가진 셀(cell)들의 튜플. cell_contents 어트리뷰트에 대한 정보는 아래를 보십시오.

읽기 전용

__annotations__

매개변수의 어노테이션을 가진 dict. dict의 키는 매개변수의 이름인데, 반환 값 어노테이션이 있다면 'return' 을 키로 사용합니다.

쓰기 가능

__kwdefaults__

키워드 형태로만 전달 가능한 매개변수들의 기본값을 가진 dict.

쓰기 가능

“쓰기 가능” 하다고 표시된 대부분의 어트리뷰트들은 값이 대입될 때 형을 검사합니다.

함수 객체는 임의의 어트리뷰트를 읽고 쓸 수 있도록 지원하는데, 예를 들어 함수에 메타데이터(metadata)를 붙이는데 사용될 수 있습니다. 어트리뷰트를 읽거나 쓸 때는 일반적인 점 표현법(dot-notation)이 사용됩니다. 현재 구현은 오직 사용자 정의 함수만 함수 어트리뷰트를 지원함에 주의해야 합니다. 내장 함수의 함수 어트리뷰트는 미래에 지원될 수 있습니다.

셀 객체는 cell_contents 어트리뷰트를 가지고 있습니다. 셀의 값을 읽을 뿐만 아니라 값을 설정하는 데도 사용할 수 있습니다.

함수 정의에 관한 추가적인 정보를 코드 객체로부터 얻을 수 있습니다. 아래에 나오는 내부 형의 기술을 참고하십시오.

인스턴스 메서드(Instance methods)

인스턴스 메서드는 클래스, 클래스 인스턴스와 모든 콜러블 객체 (보통 사용자 정의 함수)을 결합합니다.

특수 읽기 전용 어트리뷰트들: __self__ 는 클래스 인스턴스 객체, __func__ 는 함수 객체; __doc__ 은 메서드의 설명 (__func__.__doc__ 과 같습니다); __name__ 은 메서드의 이름 (__func__.__name__ 과 같습니다); __module__ 은 메서드가 정의된 모듈의 이름이거나 없는 경우 None.

메서드는 기반 함수의 모든 함수 어트리뷰트들을 읽을 수 있도록 지원합니다(하지만 쓰기는 지원하지 않습니다).

어트리뷰트가 사용자 정의 함수 객체이거나 클래스 메서드 객체면, 사용자 정의 메서드 객체는 클래스의 어트리뷰트를 읽을 때 만들어질 수 있습니다 (아마도 그 클래스의 인스턴스를 통해서).

인스턴스 메서드 객체가 클래스 인스턴스를 통해 클래스의 사용자 정의 함수 객체를 읽음으로써 만들어질 때, __self__ 어트리뷰트는 인스턴스이고, 메서드 객체는 결합(bound)하였다고 말합니다. 새 메서드의 __func__ 어트리뷰트는 원래의 함수 객체입니다.

클래스나 인스턴스로부터 다른 메서드 객체를 읽음으로써 사용자 정의 메서드 객체가 만들어질 때, 새 인스턴스의 __func__ 어트리뷰트가 원래의 메서드 객체가 아니라, 그것의 __func__ 어트리뷰트라는 점만 제외하고는 함수 객체의 경우와 같은 방식으로 동작합니다.

인스턴스 메서드 객체가 클래스나 인스턴스로부터 클래스 메서드 객체를 읽음으로써 만들어질 때, __self__ 어트리뷰트는 클래스 자신이고, __func__ 어트리뷰트는 클래스 메서드가 기반을 두는 함수 객체입니다.

인스턴스 메서드 객체가 호출될 때, 기반을 두는 함수 (__func__) 가 호출되는데, 인자 목록의 앞에 클래스 인스턴스 (__self__) 가 삽입됩니다. 예를 들어, C 가 함수 f() 의 정의를 포함하는 클래스이고, x 가 C 의 인스턴스일 때, x.f(1) 를 호출하는 것은 C.f(x, 1) 을 호출하는 것과 같습니다.

인스턴스 메서드 객체가 클래스 메서드 객체로부터 올 때, __self__ 에 저장된 “클래스 인스턴스” 는 실제로는 클래스 자신입니다. 그래서 x.f(1) 이나 C.f(1) 을 호출하는 것은 f(C,1) 를 호출하는 것과 같습니다 (f 는 기반 함수입니다).

함수 객체에서 인스턴스 객체로의 변환은 인스턴스로부터 어트리뷰트를 읽을 때마다 일어남에 주의해야 합니다. 어떤 경우에, 어트리뷰트를 지역 변수에 대입하고, 그 지역 변수를 호출하는 것이 효과적인 최적화가 됩니다. 또한, 이 변환이 사용자 정의 함수에 대해서만 발생함에 주의해야 합니다; 다른 콜러블 객체 (그리고 콜러블이 아닌 모든 객체)는 변환 없이 읽힙니다. 클래스 인스턴스의 어트리뷰트인 사용자 정의 함수는 결합한 메서드로 변환되지 않는다는 것도 중요합니다; 이 변환은 함수가 클래스 어트리뷰트일 때만 일어납니다.

제너레이터 함수(Generator functions)

yield 문(yield 문 절 참조)을 사용하는 함수나 메서드를 제너레이터 함수 (generator function) 라고 부릅니다. 이런 함수를 호출하면 항상 이터레이터(iterator) 객체를 돌려주는데, 함수의 바디(body)를 실행하는 데 사용됩니다: 이터레이터의 iterator.__next__() 메서드를 호출하면 yield 문이 값을 제공할 때까지 함수가 실행됩니다. 함수가 return 문을 실행하거나 끝에 도달하면 StopIteration 예외를 일으키고, 이터레이터는 반환하는 값들의 끝에 도달하게 됩니다.

코루틴 함수(Coroutine functions)

async def 를 사용해서 정의되는 함수나 메서드를 코루틴 함수 (coroutine function) 라고 부릅니다. 이런 함수를 호출하면 코루틴 객체를 돌려줍니다. await 표현식을 비롯해, async with 와 async for 문을 사용할 수 있습니다. 코루틴 객체(Coroutine Objects) 섹션을 참조하십시오.

비동기 제너레이터 함수(Asynchronous generator functions)

async def 를 사용해서 정의되는 함수가 yield 문을 사용하면 비동기 제너레이터 함수 (asynchronous generator function) 라고 부릅니다. 이런 함수를 호출하면 항상 비동기 이터레이터(asynchronous iterator) 객체를 돌려주는데, 함수의 바디(body)를 실행하기 위해 async for 문에서 사용됩니다.

비동기 이터레이터의 aiterator.__anext__() 메서드를 호출하면 어웨이터블 을 돌려주는데, await 할 때 yield 문이 값을 제공할 때까지 함수가 실행됩니다. 함수가 빈 return 문을 실행하거나 끝에 도달하면 StopAsyncIteration 예외를 일으키고, 비동기 이터레이터는 반환하는 값들의 끝에 도달하게 됩니다.

내장 함수(Built-in functions)

내장 함수 객체는 C 함수를 둘러싸고 있습니다(wrapper). 내장 함수의 예로는 len() 과 math.sin() (math 는 표준 내장 모듈입니다) 가 있습니다. 인자의 개수와 형은 C 함수에 의해 결정됩니다. 특수 읽기 전용 어트리뷰트들: __doc__ 은 함수의 설명 문자열 또는 없는 경우 None 입니다; __name__ 은 함수의 이름입니다; __self__ 는 None 으로 설정됩니다 (하지만 다음 항목을 보십시오); __module__ 은 함수가 정의된 모듈의 이름이거나 없는 경우 None 입니다.

내장 메서드(Built-in methods)

이것은 사실 내장 함수의 다른 모습입니다. 이번에는 묵시적인 추가의 인자로 C 함수에 전달되는 객체를 갖고 있습니다. 내장 메서드의 예로는 alist.append() 가 있는데, alist 는 리스트 객체입니다. 이 경우에, 특수 읽기 전용 어트리뷰트 __self__ 는 alist 로 표현된 객체로 설정됩니다.

클래스(Classes)

클래스는 콜러블입니다. 이 객체들은 보통 자신의 새로운 인스턴스를 만드는 팩토리(factory)로 동작하는데, __new__() 메서드를 재정의(override)하는 클래스 형에서는 달라질 수도 있습니다. 호출 인자는 __new__() 로 전달되고, 일반적으로, 새 인스턴스를 초기화하기 위해 __init__() 로도 전달됩니다.

클래스 인스턴스(Class Instances)

클래스에서 __call__() 메서드를 정의함으로써, 클래스 인스턴스를 콜러블로 만들 수 있습니다.

모듈(Modules)

모듈은 파이썬 코드의 기본적인 조직화 단위이고, import 문이나, importlib.import_module() 과 내장 __import__() 함수를 호출해서 구동할 수 있는 임포트 시스템 에 의해 만들어집니다. 모듈 객체는 딕셔너리 객체로 구현되는 이름 공간을 갖습니다(이 딕셔너리 객체는 모듈에서 정의되는 함수들의 __globals__ 어트리뷰트로 참조됩니다). 어트리뷰트 참조는 이 딕셔너리에 대한 조회로 변환됩니다. 예를 들어, m.x 는 m.__dict__["x"] 와 같습니다. 모듈 객체는 모듈을 초기화하는데 사용된 코드 객체를 갖고 있지 않습니다 (일단 초기화가 끝나면 필요 없으므로).

어트리뷰트 대입은 모듈의 이름 공간 딕셔너리를 갱신합니다. 예를 들어, m.x = 1 은 m.__dict__["x"] = 1 과 같습니다.

미리 정의된 (쓰기 가능한) 어트리뷰트들: __name__ 은 모듈의 이름입니다; __doc__ 은 모듈의 설명 문자열 또는 없는 경우 None 입니다; (없을 수도 있는) __annotations__ 는 모듈의 바디를 실행하면서 수집된 변수 어노테이션 들을 담은 딕셔너리입니다; __file__ 은 모듈이 로드된 파일의 경로명입니다. 인터프리터에 정적으로 연결된 C 모듈과 같은 어떤 종류의 모듈들에서는 __file__ 어트리뷰트가 제공되지 않습니다; 공유 라이브러리(shared library)로부터 동적으로 로딩되는 확장 모듈의 경우 공유 라이브러리의 경로명이 제공됩니다.

특수 읽기 전용 어트리뷰트들: __dict__ 는 딕셔너리로 표현되는 모듈의 이름 공간입니다.

CPython implementation detail: CPython 이 모듈 딕셔너리를 비우는 방법 때문에, 딕셔너리에 대한 참조가 남아있더라도, 모듈이 스코프를 벗어나면 모듈 딕셔너리는 비워집니다. 이것을 피하려면, 딕셔너리를 복사하거나 딕셔너리를 직접 이용하는 동안은 모듈을 잡아두어야 합니다.

사용자 정의 클래스(Custom classes)

사용자 정의 클래스 형들은 보통 클래스 정의 때문에 만들어집니다 (클래스 정의 섹션 참조). 클래스는 딕셔너리로 구현된 이름 공간을 갖습니다. 클래스 어트리뷰트 참조는 이 딕셔너리에 대한 조회로 변환됩니다. 예를 들어, C.x 는 C.__dict__["x"] 로 변환됩니다 (하지만 어트리뷰트에 접근하는 다른 방법들을 허락하는 여러 가지 훅(hook)이 있습니다.). 거기에서 어트리뷰트 이름이 발견되지 않으면, 어트리뷰트 검색은 부모 클래스들에서 계속됩니다. 이 부모 클래스 검색은 C3 메서드 결정 순서(method resolution order)를 사용하는데, 다중 상속이 같은 부모 클래스로 모이는 ‘다이아몬드(diamond)’ 계승 구조가 존재해도 올바르게 동작합니다. 파이썬이 사용하는 C3 MRO에 관한 좀 더 자세한 내용은 2.3 배포에 첨부된 문서 https://www.python.org/download/releases/2.3/mro/ 에서 찾아볼 수 있습니다.

클래스 어트리뷰트 참조가 (클래스 C 라고 하자) 클래스 메서드 객체로 귀결될 때는, __self__ 어트리뷰트가 C 인 인스턴스 메서드 객체로 변환됩니다. 스태틱 메서드로 귀결될 때는, 스태틱 메서드 객체가 감싸고 있는 객체로 변환됩니다. 클래스로부터 얻은 어트리뷰트가 __dict__ 에 저장된 값과 달라지도록 만드는 다른 방법이 디스크립터 구현하기 섹션에 나옵니다.

클래스 어트리뷰트 대입은 클래스의 딕셔너리를 갱신할 뿐, 어떤 경우도 부모 클래스의 딕셔너리를 건드리지는 않습니다.

클래스 객체는 클래스 인스턴스를 돌려주도록(아래를 보십시오) 호출될 수 있습니다(위를 보십시오).

특수 어트리뷰트들:__name__ 은 클래스의 이름입니다. __module__ 은 클래스가 정의된 모듈의 이름입니다. __dict__ 는 클래스의 이름 공간을 저장하는 딕셔너리입니다; __bases__ 는 부모 클래스들을 저장하는 튜플입니다; 부모 클래스 목록에 나타나는 순서를 유지합니다; __doc__ 은 클래스의 설명 문자열 이거나 정의되지 않으면 None 입니다; (없을 수 있는) __annotations__ 는 클래스의 바디를 실행하면서 수집된 변수 어노테이션 들을 담은 딕셔너리입니다.

클래스 인스턴스(Class instances)

클래스 인스턴스는 클래스 객체를 호출해서 (위를 보십시오) 만들어집니다. 클래스 인스턴스는 딕셔너리로 구현되는 이름 공간을 갖는데, 어트리뷰트를 참조할 때 가장 먼저 검색되는 곳입니다. 그곳에서 어트리뷰트가 발견되지 않고, 인스턴스의 클래스가 그 이름의 어트리뷰트를 갖고 있으면, 클래스 어트리뷰트로 검색이 계속됩니다. 만약 발견된 클래스 어트리뷰트가 사용자 정의 함수면, __self__ 어트리뷰트가 인스턴스인 인스턴스 메서드로 변환됩니다. 스태틱 메서드와 클래스 메서드 객체 또한 변환됩니다. 위의 “사용자 정의 클래스(Custom Classes)” 부분을 보십시오. 클래스로부터 얻은 어트리뷰트가 클래스의 __dict__ 에 저장된 값과 달라지도록 만드는 다른 방법이 디스크립터 구현하기 섹션에 나옵니다. 만약 클래스 어트리뷰트도 발견되지 않고, 클래스가 __getattr__() 메서드를 가지면, 조회를 만족시키기 위해 그 메서드를 호출합니다.

어트리뷰트 대입과 삭제는 인스턴스의 딕셔너리를 갱신할 뿐, 결코 클래스의 딕셔너리를 건드리지 않습니다. 만약 클래스가 __setattr__() 이나 __delattr__() 메서드를 가지면, 인스턴스의 딕셔너리를 갱신하는 대신에 그 메서드들을 호출합니다.

어떤 특별한 이름들의 메서드들을 가지면, 클래스 인스턴스는 숫자, 시퀀스, 매핑인 척할 수 있습니다. 특수 메서드 이름들 섹션을 보십시오.

특수 어트리뷰트들: __dict__ 는 어트리뷰트 딕셔너리입니다; __class__ 는 인스턴스의 클래스입니다.

I/O 객체 (파일 객체라고도 알려져 있습니다)

파일 객체 는 열린 파일을 나타냅니다. 파일 객체를 만드는 여러 가지 단축법이 있습니다: open() 내장 함수, os.popen(), os.fdopen() 과 소켓 객체의 makefile() 메서드 (그리고, 아마도 확장 모듈들이 제공하는 다른 함수들이나 메서드들).

sys.stdin, sys.stdout, sys.stderr 는 인터프리터의 표준 입력, 출력, 에러 스트림으로 초기화된 파일 객체들입니다; 모두 텍스트 모드로 열려서 io.TextIOBase 추상 클래스에 의해 정의된 인터페이스를 따릅니다.

내부 형(Internal types)

인터프리터가 내부적으로 사용하는 몇몇 형들은 사용자에게 노출됩니다. 인터프리터의 미래 버전에서 이들의 정의는 변경될 수 있지만, 완전함을 위해 여기서 언급합니다.

코드 객체(Code objects)

코드 객체는 바이트로 컴파일된(byte-compiled) 실행 가능한 파이썬 코드를 나타내는데, 그냥 바이트 코드 라고도 부릅니다. 코드 객체와 함수 객체 간에는 차이가 있습니다; 함수 객체는 함수의 전역 공간(globals) (함수가 정의된 모듈)을 명시적으로 참조하고 있지만, 코드 객체는 어떤 문맥(context)도 갖고 있지 않습니다; 또한 기본 인자값들이 함수 객체에 저장되어 있지만 코드 객체에는 들어있지 않습니다 (실행 시간에 계산되는 값들을 나타내기 때문입니다). 함수 객체와는 달리, 코드 객체는 불변이고 가변 객체들에 대한 어떤 참조도 (직접 혹은 간접적으로도) 갖고 있지 않습니다.

Special read-only attributes: co_name gives the function name; co_argcount is the number of positional arguments (including arguments with default values); co_nlocals is the number of local variables used by the function (including arguments); co_varnames is a tuple containing the names of the local variables (starting with the argument names); co_cellvars is a tuple containing the names of local variables that are referenced by nested functions; co_freevars is a tuple containing the names of free variables; co_code is a string representing the sequence of bytecode instructions; co_consts is a tuple containing the literals used by the bytecode; co_names is a tuple containing the names used by the bytecode; co_filename is the filename from which the code was compiled; co_firstlineno is the first line number of the function; co_lnotab is a string encoding the mapping from bytecode offsets to line numbers (for details see the source code of the interpreter); co_stacksize is the required stack size; co_flags is an integer encoding a number of flags for the interpreter.

다음과 같은 값들이 co_flags 를 위해 정의되어 있습니다: 함수가 가변 개수의 위치 인자를 받아들이기 위해 사용되는 *arguments 문법을 사용하면 비트 0x04 가 1이 됩니다; 임의의 키워드 인자를 받아들이기 위해 사용하는 **keywords 문법을 사용하면 비트 0x08 이 1이 됩니다; 비트 0x20 은 함수가 제너레이터일 때 설정됩니다.

퓨처 기능 선언 (from __future__ import division) 또한 코드 객체가 특정 기능이 활성화된 상태에서 컴파일되었는지를 나타내기 위해 co_flags 의 비트들을 사용합니다: 함수가 퓨처 division이 활성화된 상태에서 컴파일되었으면 비트 0x2000 이 설정됩니다; 비트 0x10 과 0x1000 는 예전 버전의 파이썬에서 사용되었습니다.

co_flags 의 다른 비트들은 내부 사용을 위해 예약되어 있습니다.

만약 코드 객체가 함수를 나타낸다면, co_consts 의 첫 번째 항목은 설명 문자열이거나 정의되지 않으면 None 입니다.

프레임 객체(Frame objects)

프레임 객체는 실행 프레임(execution frame)을 나타냅니다. 트레이스백 객체에 등장할 수 있고 (아래를 보십시오), 등록된 추적 함수로도 전달됩니다.

특수 읽기 전용 어트리뷰트들: f_back 은 이전 스택 프레임 (호출자 방향으로)을 가리키거나, 이게 스택의 바닥이라면 None; f_code 는 이 프레임에서 실행되는 코드 객체; f_locals 는 지역 변수를 조회하는데 사용되는 딕셔너리; f_globals 는 전역 변수에 사용됩니다; f_builtins 는 내장된(intrinsic) 이름들에 사용됩니다; f_lasti 는 정확한 바이트 코드 명령(instruction)을 제공합니다 (코드 객체의 바이트 코드 문자열에 대한 인덱스입니다).

특수 쓰기 가능 어트리뷰트들: f_trace 는, None 이 아니면, 코드 실행 중의 여러 이벤트로 인해 호출되는 함수입니다 (디버거에서 사용됩니다). 보통 이벤트는 각 새 소스 줄에서 발생합니다 - f_trace_lines를 False로 설정하면 이것을 비활성화할 수 있습니다.

구현은 f_trace_opcodes를 True로 설정하는 것으로 요청되는 옵코드(opcode) 당 이벤트를 허용할 수 있습니다. 추적 함수에 의해 발생 된 예외가 추적되는 함수로 빠져나오면 정의되지 않은 인터프리터 동작을 유발할 수 있음에 주의해야 합니다.

f_lineno 는 프레임의 현재 줄 번호입니다 — 트레이스 함수(f_trace)에서 이 값을 쓰면 해당 줄로 점프합니다 (오직 가장 바닥 프레임에서만 가능합니다). 디버거는 f_lineno 를 쓰기 위한 점프 명령을 구현할 수 있습니다 (소위 Set Next Statement).

프레임 객체는 한가지 메서드를 지원합니다:

frame.clear()

이 메서드는 프레임이 잡은 지역 변수들에 대한 모든 참조를 제거합니다. 또한, 만약 프레임이 제너레이터에 속하면, 제너레이터가 종료됩니다(finalize). 이것은 프레임 객체가 관련된 참조 순환을 깨는 데 도움을 줍니다 (예를 들어, 예외를 잡아서 트레이스백을 추후 사용을 위해 저장할 때).

만약 프레임이 현재 실행 중이면 RuntimeError 예외가 발생합니다.

버전 3.4에 추가.

트레이스백 객체(Traceback objects)

트레이스백 객체는 예외의 스택 트레이스를 나타냅니다. 트레이스백 객체는 예외가 발생할 때 만들어지고, types.TracebackType 를 호출해서 명시적으로 만들 수도 있습니다.

묵시적으로 만들어진 트레이스백의 경우, 예외 처리기를 찾아서 실행 스택을 되감을 때, 각각 되감기 단계마다 현재 트레이스백의 앞에 트레이스백 객체를 삽입합니다. 예외 처리기에 들어가면, 스택 트레이스를 프로그램이 사용할 수 있습니다. (try 문 섹션 참조.) sys.exc_info() 가 돌려주는 튜플의 세 번째 항목이나 잡힌 예외의 __traceback__ 어트리뷰트로 액세스할 수 있습니다.

프로그램이 적절한 처리기를 제공하지 않는 경우, 스택 트레이스는 표준 에러 스트림으로 (보기 좋게 포맷되어) 출력됩니다; 만약 인터프리터가 대화형이면, sys.last_traceback 으로 사용자에게 제공합니다.

명시적으로 생성된 트레이스백의 경우, tb_next 어트리뷰트를 어떻게 연결하여 전체 스택 트레이스를 형성해야 하는지를 결정하는 것은 트레이스백을 만드는 주체에게 달려 있습니다.

특수 읽기 전용 어트리뷰트들: tb_frame 은 현 단계에서의 실행 프레임입니다; tb_lineno 는 예외가 발생한 줄의 번호를 줍니다; tb_lasti 정확한 바이트 코드 명령을 가리킵니다. 만약 예외가 except 절이나 finally 절이 없는 try 문에서 발생하면, 줄 번호와 트레이스백의 마지막 명령(last instruction)은 프레임 객체의 줄 번호와 다를 수 있습니다.

특수 쓰기 가능 어트리뷰트: tb_next 는 스택 트레이스의 다음 단계 (예외가 발생한 프레임 방향으로)이거나 다음 단계가 없으면 None 입니다.

버전 3.7에서 변경: 트레이스백 객체는 이제 파이썬 코드에서 명시적으로 인스턴스를 만들 수 있으며 기존 인스턴스의 tb_next 어트리뷰트를 변경할 수 있습니다.

슬라이스 객체(Slice objects)

슬라이스 객체는 __getitem__() 메서드를 위한 슬라이스를 나타냅니다. 내장 함수 slice() 로 만들 수도 있습니다.

특수 읽기 전용 어트리뷰트들: start 는 하한(lower bound) 입니다; stop 은 상한(upper bound) 입니다; step 은 스텝 값입니다; 각 값은 생략될 경우 None 입니다. 이 어트리뷰트들은 임의의 형이 될 수 있습니다.

슬라이스 객체는 하나의 메서드를 지원합니다.

slice.indices(self, length)

이 메서드는 하나의 정수 인자 length 를 받아서 슬라이스 객체가 길이 length 인 시퀀스에 적용되었을 때 그 슬라이스에 대한 정보를 계산합니다. 세 개의 정수로 구성된 튜플을 돌려줍니다: 이것들은 각각 start 와 stop 인덱스와, step 또는 슬라이스의 스트라이드(stride) 길이입니다. 생략되었거나 범위를 벗어난 인덱스들은 일반적인 슬라이스와 같은 방법으로 다뤄집니다.

스태틱 메서드 객체(Static method objects)

스태틱 메서드 객체는 위에서 설명한 함수 객체를 메서드 객체로 변환하는 과정을 방지하는 방법을 제공합니다. 스태틱 메서드 객체는 다른 임의의 객체, 보통 사용자 정의 메서드를 둘러쌉니다. 스태틱 메서드가 클래스나 클래스 인스턴스로부터 읽힐 때 객체가 실제로 돌려주는 것은 둘러싸여 있던 객체인데, 다른 어떤 변환도 적용되지 않은 상태입니다. 둘러싸는 객체는 그렇더라도, 스태틱 메서드 객체 자체는 콜러블이 아닙니다. 스태틱 메서드 객체는 내장 staticmethod() 생성자로 만듭니다.

클래스 메서드 객체(Class method objects)

스태틱 메서드 객체처럼, 클래스 메서드 객체 역시 다른 객체를 둘러싸는데, 클래스와 클래스 인스턴스로부터 그 객체를 꺼내는 방식에 변화를 줍니다. 그런 조회에서 클래스 메서드 객체가 동작하는 방식에 대해서는 위 “사용자 정의 메서드(User-defined methods)” 에서 설명했습니다. 클래스 메서드 객체는 내장 classmethod() 생성자로 만듭니다.

3.3. 특수 메서드 이름들

클래스는 특별한 이름의 메서드들을 정의함으로써 특별한 문법 (산술 연산이나 인덱싱이나 슬라이딩 같은)에 의해 시작되는 어떤 연산들을 구현할 수 있습니다. 이것이 연산자 오버 로딩 (operator overloading)에 대한 파이썬의 접근법인데, 클래스가 언어의 연산자에 대해 자기 자신의 동작을 정의할 수 있도록 합니다. 예를 들어, 클래스가 __getitem__() 이라는 이름의 메서드를 정의하고, x 가 이 클래스의 인스턴스라면, x[i] 는 대략 type(x).__getitem__(x, i) 와 동등합니다. 언급된 경우를 제외하고, 적절한 메서드가 정의되지 않았을 때 연산은 예외를 일으킵니다 (보통 AttributeError 나 TypeError).

특수 메서드를 None 으로 설정하는 것은 해당 연산이 제공되지 않는다는 것을 가리킵니다. 예를 들어, 만약 클래스가 __iter__() 를 None 으로 설정하면, 클래스는 이터러블이 아닙니다. 따라서 이 인스턴스에 iter() 를 호출하면 TypeError 가 발생합니다. (__getitem__() 을 대안으로 시도하지 않습니다.) 2

내장형을 흉내 내는 클래스를 구현할 때, 모방은 모형화하는 객체에 말이 되는 수준까지만 구현하는 것이 중요합니다. 예를 들어, 어떤 시퀀스는 개별 항목들을 꺼내는 것만으로도 잘 동작할 수 있습니다. 하지만 슬라이스를 꺼내는 것은 말이 안 될 수 있습니다. (이런 한가지 예는 W3C의 Document Object Model의 NodeList 인터페이스입니다.)

3.3.1. 기본적인 커스터마이제이션

object.__new__(cls[, ...])

클래스 cls 의 새 인스턴스를 만들기 위해 호출됩니다. __new__() 는 스태틱 메서드입니다 (그렇게 선언하지 않아도 되는 특별한 경우입니다)인데, 첫 번째 인자로 만들려고 하는 인스턴스의 클래스가 전달됩니다. 나머지 인자들은 객체 생성자 표현(클래스 호출)에 전달된 것들입니다. __new__() 의 반환 값은 새 객체 인스턴스이어야 합니다 (보통 cls 의 인스턴스).

일반적인 구현은 super().__new__(cls[, ...]) 에 적절한 인자들을 전달하는 방법으로 슈퍼 클래스의 __new__() 를 호출해서 새 인스턴스를 만든 후에, 돌려주기 전에 필요한 수정을 가합니다.

만약 __new__() 가 cls 의 인스턴스를 돌려준다면, 새 인스턴스의 __init__() 메서드가 __init__(self[, ...]) 처럼 호출되는데, self 는 새 인스턴스이고, 나머지 인자들은 __new__() 로 전달된 것들과 같습니다.

만약 __new__() 가 cls 의 인스턴스를 돌려주지 않으면, 새 인스턴스의 __init__() 는 호출되지 않습니다.

__new__() 는 주로 불변형(int, str, tuple과 같은)의 서브 클래스가 인스턴스 생성을 커스터마이즈할 수 있도록 하는 데 사용됩니다. 또한, 사용자 정의 메타 클래스에서 클래스 생성을 커스터마이즈하기 위해 자주 사용됩니다.

object.__init__(self[, ...])

(__new__() 에 의해) 인스턴스가 만들어진 후에, 하지만 호출자에게 돌려주기 전에 호출됩니다. 인자들은 클래스 생성자 표현으로 전달된 것들입니다. 만약 베이스 클래스가 __init__() 메서드를 갖고 있다면, 서브 클래스의 __init__() 메서드는, 있다면, 인스턴스에서 베이스 클래스가 차지하는 부분이 올바르게 초기화됨을 확실히 하기 위해 명시적으로 호출해주어야 합니다; 예를 들어: super().__init__([args...]).

객체를 만드는데 __new__() 와 __init__() 가 협력하고 있으므로 (__new__() 는 만들고, __init__() 는 그것을 커스터마이즈합니다), __init__() 가 None 이외의 값을 돌려주면 실행시간에 TypeError 를 일으킵니다.

object.__del__(self)

인스턴스가 파괴되기 직전에 호출됩니다. 파이널라이저 또는 (부적절하게) 파괴자라고 불립니다. 만약 베이스 클래스가 __del__() 메서드를 갖고 있다면, 자식 클래스의 __del__() 메서드는, 정의되어 있다면, 인스턴스에서 베이스 클래스가 차지하는 부분을 적절하게 삭제하기 위해, 명시적으로 베이스 클래스의 메서드를 호출해야 합니다.

(권장하지는 않지만!) __del__() 메서드는 인스턴스에 대한 새로운 참조를 만듦으로써 인스턴스의 파괴를 지연시킬 수 있습니다. 이것을 객체 부활 이라고 부릅니다. 부활한 객체가 파괴될 때 __del__() 이 두 번째로 호출될지는 구현에 따라 다릅니다; 현재 CPython 구현은 오직 한 번만 호출합니다.

인터프리터가 종료할 때 아직 남아있는 객체들에 대해서는 __del__() 메서드의 호출이 보장되지 않습니다.

참고

del x 는 직접 x.__del__() 를 호출하지 않습니다 — 앞에 있는 것은 x 의 참조 횟수(reference count)를 하나 감소시키고, 뒤에 있는 것은 x 의 참조 횟수가 0 이 될 때 호출됩니다.

CPython implementation detail: It is possible for a reference cycle to prevent the reference count of an object from going to zero. In this case, the cycle will be later detected and deleted by the cyclic garbage collector. A common cause of reference cycles is when an exception has been caught in a local variable. The frame’s locals then reference the exception, which references its own traceback, which references the locals of all frames caught in the traceback.

더 보기

gc 모듈에 대한 문서.

경고

__del__() 이 호출되는 불안정한 상황 때문에, 이것이 실행 중에 발생시키는 예외는 무시되고, 대신에 sys.stderr 로 경고가 출력됩니다. 특히:

__del__() 은 (임의의 스레드에서) 임의의 코드가 실행되는 동안 호출될 수 있습니다. __del__() 이 록을 얻어야 하거나 다른 블로킹 자원을 호출하면, __del__() 을 실행하기 위해 중단된 코드가 자원을 이미 차지했을 수 있으므로 교착 상태에 빠질 수 있습니다.

__del__() 은 인터프리터를 종료할 때 실행될 수 있습니다. 결과적으로, 액세스해야 하는 전역 변수(다른 모듈 포함)가 이미 삭제되었거나 None 으로 설정되었을 수 있습니다. 파이썬은 이름이 하나의 밑줄로 시작하는 전역 객체가 다른 전역 객체들보다 먼저 삭제됨을 보장합니다; 이것은, 만약 그 전역 객체들에 대한 다른 참조가 존재하지 않는다면, __del__() 메서드가 호출되는 시점에, 임포트된 모듈들이 남아있도록 확실히 하는 데 도움이 될 수 있습니다.

object.__repr__(self)

repr() 내장 함수에 의해 호출되어 객체의 “형식적인(official)” 문자열 표현을 계산합니다. 만약 가능하다면, 이것은 같은 (적절한 환경이 주어질 때) 값을 갖는 객체를 새로 만들 수 있는 올바른 파이썬 표현식처럼 보여야 합니다. 가능하지 않다면, <...쓸모있는 설명...> 형태의 문자열을 돌려줘야 합니다. 반환 값은 반드시 문자열이어야 합니다. 만약 클래스가 __str__() 없이 __repr__() 만 정의한다면, __repr__() 은 그 클래스 인스턴스의 “비형식적인(informal)” 문자열 표현이 요구될 때 사용될 수 있습니다.

이것은 디버깅에 사용되기 때문에, 표현이 풍부한 정보를 담고 모호하지 않게 하는 것이 중요합니다.

object.__str__(self)

str(object) 와 내장 함수 format(), print() 에 의해 호출되어 객체의 “비형식적인(informal)” 또는 보기 좋게 인쇄 가능한 문자열 표현을 계산합니다. 반환 값은 반드시 문자열 객체여야 합니다.

이 메서드는 __str__() 이 올바른 파이썬 표현식을 돌려줄 것이라고 기대되지 않는다는 점에서 object.__repr__() 과 다릅니다: 더 편리하고 간결한 표현이 사용될 수 있습니다.

내장형 object 에 정의된 기본 구현은 object.__repr__() 을 호출합니다.

object.__bytes__(self)

bytes 에 의해 호출되어 객체의 바이트열 표현을 계산합니다. 반환 값은 반드시 bytes 객체여야 합니다.

object.__format__(self, format_spec)

format() 내장 함수, 확대하면, 포맷 문자열 리터럴(formatted string literals) 의 계산과 str.format() 메서드에 의해 호출되어, 객체의 “포맷된” 문자열 표현을 만들어냅니다. format_spec 인자는 요구되는 포맷 옵션들을 포함하는 문자열입니다. format_spec 인자의 해석은 __format__() 을 구현하는 형에 달려있으나, 대부분 클래스는 포매팅을 내향형들의 하나로 위임하거나, 비슷한 포맷 옵션 문법을 사용합니다.

표준 포매팅 문법에 대해서는 포맷 명세 미니 언어 를 참고하면 됩니다.

반환 값은 반드시 문자열이어야 합니다.

버전 3.4에서 변경: object 의 __format__ 메서드 자신은, 빈 문자열이 아닌 인자가 전달되면 TypeError 를 발생시킵니다.

버전 3.7에서 변경: 이제 object.__format__(x, '') 는 format(str(self), '') 가 아니라 str(x) 와 동등합니다.

object.__lt__(self, other)

object.__le__(self, other)

object.__eq__(self, other)

object.__ne__(self, other)

object.__gt__(self, other)

object.__ge__(self, other)

이것들은 소위 “풍부한 비교(rich comparison)” 메서드입니다. 연산자 기호와 메서드 이름 간의 관계는 다음과 같습니다: x<y 는 x.__lt__(y) 를 호출합니다, x<=y 는 x.__le__(y) 를 호출합니다, x==y 는 x.__eq__(y) 를 호출합니다, x!=y 는 x.__ne__(y) 를 호출합니다, x>y 는 x.__gt__(y) 를 호출합니다, x>=y 는 x.__ge__(y) 를 호출합니다.

풍부한 비교 메서드는 주어진 한 쌍의 인자에게 해당 연산을 구현하지 않는 경우 단일자(singleton) NotImplemented 를 돌려줄 수 있습니다. 관례상, 성공적인 비교면 False 나 True 를 돌려줍니다. 하지만, 이 메서드는 어떤 형의 값이건 돌려줄 수 있습니다, 그래서 비교 연산자가 논리 문맥(Boolean context) (예를 들어 if 문의 조건)에서 사용되면, 파이썬은 결과의 참 거짓을 파악하기 위해 값에 대해 bool() 을 호출합니다.

기본적으로, __ne__() 는 __eq__() 를 호출한 후 NotImplemented 가 아니라면 그 결과를 뒤집습니다. 비교 연산자 간의 다른 암시적인 관계는 없습니다. 예를 들어, (x<y or x==y) 가 참이라고 해서 x<=y 가 참일 필요는 없습니다. 하나의 기본 연산으로부터 대소관계 연산을 자동으로 만들어내려면 functools.total_ordering() 를 보면 됩니다.

사용자 정의 비교 연산자를 지원하고 딕셔너리 키로 사용될 수 있는 해시 가능 객체를 만드는 것에 관한 몇 가지 중요한 내용이 __hash__() 에 관한 문단에 나옵니다.

이 메서드들에 대한 (왼편의 인자는 연산을 지원하지 않지만, 오른편 인자가 지원할 때 사용되는) 뒤집힌 버전은 따로 없습니다; 대신에 __lt__() 와 __gt__() 는 서로의 뒤집힌 연산입니다; __le__() 와 __ge__() 는 서로의 뒤집힌 연산입니다; __eq__() 와 __ne__() 는 서로의 뒤집힌 연산입니다; 만약 피연산자가 서로 다른 형이고, 오른편 피연산자의 형이 왼편 피연산자의 형의 직간접적인 서브 클래스면, 오른편 피연산자의 뒤집힌 버전이 우선순위가 높습니다; 그렇지 않으면 왼편 피연산자의 메서드가 우선순위가 높습니다. 가상 서브클래싱(virtual subclassing)은 고려되지 않습니다.

object.__hash__(self)

내장 함수 hash() 와 set, frozenset, dict 와 같은 해시형 컬렉션의 멤버에 대한 연산에서 호출됩니다. __hash__() 는 정수를 돌려줘야 합니다. 같다고 비교되는 객체들이 같은 해시값을 가져야 한다는 성질만 요구됩니다. 객체의 비교에 사용되는 요소들로 튜플을 구성하고, 그 튜플의 해시값을 취함으로써 요소들의 해시값을 섞는 것을 권합니다. 예를 들면:

def __hash__(self):
    return hash((self.name, self.nick, self.color))

참고

hash() 는 객체가 정의한 __hash__() 메서드가 돌려주는 값을 Py_ssize_t 의 크기로 자릅니다(truncate). 이것은 보통 64-bit 빌드에서는 8바이트고, 32-bit 빌드에서는 4바이트입니다. 만약 객체의 __hash__() 가 서로 다른 비트 크기를 갖는 빌드들 사이에서 함께 사용되어야 한다면, 모든 지원할 빌드들에서의 폭을 검사해야 합니다. 이렇게 하는 쉬운 방법은 python -c "import sys; print(sys.hash_info.width)" 입니다.

만약 클래스가 __eq__() 를 정의하지 않으면 __hash__() 역시 정의하지 말아야 합니다. 만약 __eq__() 를 정의하지만 __hash__() 를 정의하지 않는다면, 그것의 인스턴스는 해시 가능 컬렉션에서 사용될 수 없습니다. 만약 클래스가 가변형 객체를 정의하고 있고 __eq__() 를 구현한다면, __hash__() 를 구현하지 말아야 하는데, 해시 가능 컬렉션들의 구현이 키의 해시값이 불변이도록 요구하고 있기 때문입니다(만약 객체의 해시값이 변하면, 잘못된 해시 버킷(hash bucket)에 있게 됩니다).

사용자 정의 클래스는 기본적으로 __eq__() 와 __hash__() 메서드를 갖습니다; 모든 객체는 (자기 자신을 제외하고) 같지 않다고 비교되고, x.__hash__() 는 적절한 값을 돌려주어, x == y 일 때 x is y 와 hash(x) == hash(y) 가 동시에 성립할 수 있도록 합니다.

__eq__() 를 재정의하고 __hash__() 를 정의하지 않는 클래스는 __hash__() 가 None 으로 설정됩니다. 클래스의 __hash__() 메서드가 None 이면, 클래스의 인스턴스는 프로그램이 해시값을 얻으려 시도할 때 TypeError 를 일으키고, isinstance(obj, collections.abc.Hashable) 로 검사할 때 해시 가능하지 않다고 올바로 감지됩니다.

만약 __eq__() 를 재정의하는 클래스가 부모 클래스로부터 __hash__() 의 구현을 물려받고 싶으면 인터프리터에게 명시적으로 이렇게 지정해주어야 합니다: __hash__ = <ParentClass>.__hash__.

만약 __eq__() 를 재정의하지 않는 클래스가 해시 지원을 멈추고 싶으면, 클래스 정의에 __hash__ = None 을 포함해야 합니다. 자신의 __hash__() 을 정의한 후에 직접 TypeError 를 일으키는 경우는 isinstance(obj, collections.abc.Hashable) 호출이 해시 가능하다고 잘못 인식합니다.

참고

기본적으로, str, bytes, datetime 객체들의 __hash__() 값은 예측할 수 없는 난수값으로 “솔트되어(salted)” 있습니다. 개별 파이썬 프로세스 내에서는 변하지 않는 값으로 유지되지만, 파이썬을 반복적으로 실행할 때는 예측할 수 없게 됩니다.

이것은 dict 삽입의 최악의 경우 성능(worst case performance), O(n^2) 복잡도, 을 활용하기 위해 주의 깊게 선택한 입력에 의한 서비스 거부(denial-of-service) 공격에 대한 방어를 제공하기 위한 목적입니다. 자세한 내용은 http://www.ocert.org/advisories/ocert-2011-003.html 에 있습니다.

해시값의 변경은 집합의 이터레이션 순서에 영향을 줍니다, 파이썬은 이 순서에 대해 어떤 보장도 하지 않습니다 (그리고 보통 32-bit 와 64-bit 빌드 사이에서도 다릅니다).

PYTHONHASHSEED 를 참고하십시오.

버전 3.3에서 변경: 해시 난수 화는 기본적으로 활성화됩니다.

object.__bool__(self)

논리값 검사와 내장 연산 bool() 구현을 위해 호출됩니다; False 나 True 를 돌려줘야 합니다. 이 메서드가 정의되지 않는 경우, 정의되어 있다면 __len__() 이 호출되어, 값이 0 이 아니면 참으로 인식합니다. 만약 클래스가 __len__() 과 __bool__() 모두 정의하지 않는다면, 모든 인스턴스는 참으로 취급됩니다.

3.3.2. 어트리뷰트 액세스 커스터마이제이션

클래스 인스턴스의 어트리뷰트 참조(읽기, 대입하기, x.name 을 삭제하기)의 의미를 변경하기 위해 다음과 같은 메서드들이 정의될 수 있습니다.

object.__getattr__(self, name)

기본 어트리뷰트 액세스가 AttributeError 로 실패할 때 호출됩니다 (name 이 인스턴스 어트리뷰트 또는 self 의 클래스 트리에 있는 어트리뷰트가 아니라서 __getattribute__() 가 AttributeError 를 일으키거나; name 프로퍼티의 __get__() 이 AttributeError 를 일으킬 때). 이 메서드는 (계산된) 어트리뷰트 값을 반환하거나 AttributeError 예외를 일으켜야 합니다.

일반적인 메커니즘을 통해 어트리뷰트가 발견되면 __getattr__() 이 호출되지 않음에 주의해야 합니다 (이것은 __getattr__() 과 __setattr__() 간의 의도된 비대칭입니다). 이렇게 하는 이유는 효율 때문이기도 하고, 그렇게 하지 않으면 __getattr__() 가 인스턴스의 다른 어트리뷰트에 접근할 방법이 없기 때문이기도 합니다. 적어도 인스턴스 변수의 경우, 어떤 값도 인스턴스 어트리뷰트 딕셔너리에 넣지 않음으로써 (대신에 그것들을 다른 객체에 넣습니다) 완전한 제어인 것처럼 조작할 수 있습니다. 어트리뷰트 액세스를 실제로 완전히 조작하는 방법에 대해서는 아래에 나오는 __getattribute__() 에서 다룹니다.

object.__getattribute__(self, name)

클래스 인스턴스의 어트리뷰트 액세스를 구현하기 위해 조건 없이 호출됩니다. 만약 클래스가 __getattr__() 도 함께 구현하면, __getattribute__() 가 명시적으로 호출하거나 AttributeError 를 일으키지 않는 이상 __getattr__ 는 호출되지 않습니다. 이 메서드는 어트리뷰트의 (계산된) 값을 돌려주거나 AttributeError 예외를 일으켜야 합니다. 이 메서드에서 무한 재귀(infinite recursion)가 발생하는 것을 막기 위해, 구현은 언제나 필요한 어트리뷰트에 접근하기 위해 같은 이름의 베이스 클래스의 메서드를 호출해야 합니다. 예를 들어, object.__getattribute__(self, name).

참고

언어 문법이나 내장 함수에 의한 묵시적인 호출이 결과로 특수 메서드를 참조하는 경우에는 이 메서드를 거치지 않을 수 있습니다. 자세한 내용은 특수 메서드 조회 에서 다룹니다.

object.__setattr__(self, name, value)

어트리뷰트 대입이 시도될 때 호출됩니다. 일반적인 메커니즘(즉 인스턴스 딕셔너리에 값을 저장하는 것) 대신에 이것이 호출됩니다. name 은 어트리뷰트 이름이고, value 는 그것에 대입하려는 값입니다.

__setattr__() 에서 인스턴스 어트리뷰트에 대입하려고 할 때는, 같은 이름의 베이스 클래스의 메서드를 호출해야 합니다. 예를 들어 object.__setattr__(self, name, value)

object.__delattr__(self, name)

__setattr__() 과 비슷하지만 어트리뷰트를 대입하는 대신에 삭제합니다. 이것은 del obj.name 이 객체에 의미가 있는 경우에만 구현되어야 합니다.

object.__dir__(self)

객체에 dir() 이 호출될 때 호출됩니다. 시퀀스를 돌려줘야 합니다. dir() 은 돌려준 시퀀스를 리스트로 변환한 후 정렬합니다.

3.3.2.1. 모듈 어트리뷰트 액세스 커스터마이제이션

특수한 이름 __getattr__ 과 __dir__ 는 모듈 어트리뷰트에 대한 접근을 사용자 정의하는 데 사용될 수도 있습니다. 모듈 수준의 __getattr__ 함수는 하나의 인자로 어트리뷰트의 이름을 받아서 계산된 값을 돌려주거나 AttributeError 를 발생시켜야 합니다. 일반적인 조회(즉 object.__getattribute__())를 통해 어트리뷰트가 모듈 객체에서 발견되지 않으면, AttributeError 를 일으키기 전에 모듈 __dict__ 에서 __getattr__ 을 검색합니다. 발견되면, 어트리뷰트 이름으로 그 함수를 호출하고 결과를 돌려줍니다.

The __dir__ function should accept no arguments, and return a sequence of strings that represents the names accessible on module. If present, this function overrides the standard dir() search on a module.

모듈 동작(어트리뷰트 설정, 프로퍼티 등)을 보다 세밀하게 사용자 정의하려면, 모듈 객체의 __class__ 어트리뷰트를 types.ModuleType 의 서브 클래스로 설정할 수 있습니다. 예를 들면:

import sys
from types import ModuleType

class VerboseModule(ModuleType):
    def __repr__(self):
        return f'Verbose {self.__name__}'

    def __setattr__(self, attr, value):
        print(f'Setting {attr}...')
        super().__setattr__(attr, value)

sys.modules[__name__].__class__ = VerboseModule

참고

모듈 __getattr__ 정의와 모듈 __class__ 설정은 어트리뷰트 액세스 구문을 사용하는 조회에만 영향을 미칩니다 – 모듈 전역에 대한 직접적인 액세스(모듈 내의 코드에 의한 액세스이거나 모듈의 전역 딕셔너리에 대한 참조를 거치거나)는 영향받지 않습니다.

버전 3.5에서 변경: 이제 __class__ 모듈 어트리뷰트가 쓰기 가능합니다.

버전 3.7에 추가: __getattr__ 과 __dir__ 모듈 어트리뷰트.

더 보기

PEP 562 [https://www.python.org/dev/peps/pep-0562] - 모듈 __getattr__ 과 __dir__

모듈에 대한 __getattr__ 과 __dir__ 함수를 설명합니다.

3.3.2.2. 디스크립터 구현하기

다음에 오는 메서드들은 메서드를 가진 클래스(소위 디스크립터(descriptor) 클래스)의 인스턴스가 소유자(owner) 클래스에 등장할 때만 적용됩니다(디스크립터는 소유자 클래스의 딕셔너리나 그 부모 클래스 중 하나의 딕셔너리에 있어야 합니다). 아래의 예에서, “어트리뷰트” 는 이름이 소유자 클래스의 __dict__ 의 키로 사용되고 있는 어트리뷰트를 가리킵니다.

object.__get__(self, instance, owner)

소유자 클래스(클래스 어트리뷰트 액세스) 나 그 클래스의 인스턴스(인스턴스 어트리뷰트 액세스)의 어트리뷰트를 취하려고 할 때 호출됩니다. owner 는 항상 소유자 클래스입니다. 반면에 instance 는 어트리뷰트 참조가 일어나고 있는 인스턴스이거나, 어트리뷰트가 owner 를 통해 액세스 되는 경우 None 입니다. 이 메서드는 (계산된) 어트리뷰트 값을 돌려주거나 AttributeError 예외를 일으켜야 합니다.

object.__set__(self, instance, value)

소유자 클래스의 인스턴스 instance 의 어트리뷰트를 새 값 value 로 설정할 때 호출됩니다.

object.__delete__(self, instance)

소유자 클래스의 인스턴스 instance 의 어트리뷰트를 삭제할 때 호출됩니다.

object.__set_name__(self, owner, name)

소유자 클래스 owner 가 만들어질 때 호출됩니다. 이 디스크립터가 name 에 대입되었습니다.

참고

__set_name__() is only called implicitly as part of the type constructor, so it will need to be called explicitly with the appropriate parameters when a descriptor is added to a class after initial creation:

class A:
   pass
descr = custom_descriptor()
A.attr = descr
descr.__set_name__(A, 'attr')

See 클래스 객체 만들기 for more details.

버전 3.6에 추가.

어트리뷰트 __objclass__ 는 inspect 모듈에 의해 이 객체가 정의된 클래스를 지정하는 것으로 해석됩니다(이 값을 적절히 설정하면 동적인 클래스 어트리뷰트의 실행시간 인트로스펙션(introspection)을 지원할 수 있습니다). 콜러블의 경우, 첫 번째 위치 인자에, 주어진 형(또는 서브 클래스)의 인스턴스가 기대되거나 요구됨을 가리킬 수 있습니다(예를 들어, CPython 은 C로 구현된 연결되지 않은 메서드(unbound method)에 이 어트리뷰트를 설정합니다).

3.3.2.3. 디스크립터 호출하기

일반적으로, 디스크립터는 “결합한 동작(binding behavior)”을 가진 객체 어트리뷰트입니다. 어트리뷰트 액세스가 디스크립터 프로토콜(descriptor protocol)의 메서드들에 의해 재정의됩니다: __get__(), __set__(), __delete__(). 이 메서드들 중 하나라도 정의되어 있으면, 디스크립터라고 부릅니다.

어트리뷰트 액세스의 기본 동작은 객체의 딕셔너리에서 어트리뷰트를 읽고, 쓰고, 삭제하는 것입니다. 예를 들어 a.x 는 a.__dict__['x'] 에서 시작해서 type(a).__dict__['x'] 를 거쳐 type(a) 의 메타 클래스를 제외한 베이스 클래스들을 거쳐 가는 일련의 조회로 구성됩니다.

그러나, 만약 조회한 값이 디스크립터 메서드를 구현한 객체면, 파이썬은 기본 동작 대신에 디스크립터 메서드를 호출할 수 있습니다. 우선순위 목록의 어느 위치에서 이런 일이 일어나는지는 어떤 디스크립터 메서드가 정의되어 있고 어떤 식으로 호출되는지에 따라 다릅니다.

디스크립터 호출의 시작점은 결합(binding)입니다, a.x. 어떻게 인자들이 조합되는지는 a 에 따라 다릅니다:

직접 호출

가장 간단하면서도 가장 덜 사용되는 호출은 사용자의 코드가 디스크립터 메서드를 직접 호출할 때입니다: x.__get__(a)

인스턴스 결합

객체 인스턴스에 결합하면, a.x 는 이런 호출로 변환됩니다: type(a).__dict__['x'].__get__(a, type(a)).

클래스 결합

클래스에 결합하면, A.x 는 이런 호출로 변환됩니다: A.__dict__['x'].__get__(None, A).

Super 결합

super 의 인스턴스에 결합하면, 결합 super(B, obj).m() 은 obj.__class__.__mro__ 를 검색해서 B 바로 다음에 나오는 베이스 클래스 A 를 찾은 후에 이렇게 디스크립터를 호출합니다: A.__dict__['m'].__get__(obj, obj.__class__).

인스턴스 결합의 경우, 디스크립터 호출의 우선순위는 어떤 디스크립터 메서드가 정의되어있는지에 따라 다릅니다. 디스크립터는 __get__(), __set__(), __delete__() 를 어떤 조합으로도 정의할 수 있습니다. 만약 __get__() 를 정의하지 않는다면, 어트리뷰트 액세스는, 객체의 인스턴스 딕셔너리에 값이 있지 않은 이상 디스크립터 객체 자신을 돌려줍니다. 만약 디스크립터가 __set__() 이나 __delete__() 중 어느 하나나 둘 다 정의하면, 데이터 디스크립터(data descriptor)입니다. 둘 다 정의하지 않는다면 비데이터 디스크립터(non-data descriptor)입니다. 보통, 데이터 디스크립터가 __get__() 과 __set__() 을 모두 정의하는 반면, 비데이터 디스크립터는 __get__() 메서드만 정의합니다. __set__() 과 __get__() 이 있는 데이터 디스크립터는 인스턴스 딕셔너리에 있는 값에 우선합니다. 반면에 비데이터 디스크립터는 인스턴스보다 우선순위가 낮습니다.

파이썬 메서드 (staticmethod() 와 classmethod() 를 포함해서) 는 비데이터 디스크립터로 구현됩니다. 이 때문에, 인스턴스는 메서드를 새로 정의하거나 덮어쓸 수 있습니다. 이것은 개별 인스턴스가 같은 클래스의 다른 인스턴스들과는 다른 동작을 얻을 수 있도록 만듭니다.

property() 함수는 데이터 디스크립터로 구현됩니다. 이 때문에, 인스턴스는 프로퍼티(property)의 동작을 변경할 수 없습니다.

3.3.2.4. __slots__

__slots__ 은 (프로퍼티처럼) 데이터 멤버를 명시적으로 선언하고 (__slots__ 에 명시적으로 선언하거나 부모로부터 물려받지 않는 한) __dict__ 와 __weakref__ 생성을 거부할 수 있도록 합니다.

__dict__ 를 사용할 때에 비교해 절약되는 공간은 상당할 수 있습니다. 어트리뷰트 조회 속도도 크게 개선할 수 있습니다.

object.__slots__

이 클래스 변수에는 인스턴스에 의해 사용되는 변수들의 이름을 제공하는 문자열, 이터러블(iterable), 문자열의 시퀀스가 대입될 수 있습니다. __slots__ 은 선언된 변수들을 위한 공간을 예약하고, 간 인스턴스마다 __dict__ 와 __weakref__ 가 만들어지는 것을 막습니다.

3.3.2.4.1. __slots__ 사용에 관한 노트

__slots__ 가 없는 클래스를 계승할 때, 인스턴스의 __dict__ 와 __weakref__ 어트리뷰트는 항상 제공됩니다.

__dict__ 변수가 없으므로 인스턴스는 __slots__ 정의에 나열되지 않은 새 변수를 대입할 수 없습니다. 나열되지 않은 변수명으로 대입하려고 하면 AttributeError 를 일으킵니다. 만약 동적으로 새 변수를 대입하는 것이 필요하다면, __slots__ 선언의 문자열 시퀀스에 '__dict__' 를 추가합니다.

인스턴스마다 __weakref__ 변수가 없으므로, __slots__ 를 정의하는 클래스는 인스턴스에 대한 약한 참조(weak reference)를 지원하지 않습니다. 만약 약한 참조 지원이 필요하다면, __slots__ 선언의 문자열 시퀀스에 '__weakref__' 를 추가합니다.

__slots__ 는 각 변수 이름마다 디스크립터를 만드는 방식으로 클래스 수준에서 구현됩니다(디스크립터 구현하기). 결과적으로, 클래스 어트리뷰트는 __slots__ 로 정의된 인스턴스 변수들을 위한 기본값을 제공할 목적으로 사용될 수 없습니다. 클래스 어트리뷰트는 디스크립터 대입을 무효로 합니다.

__slots__ 선언으로 인한 효과는 그것이 정의된 클래스로 한정되지 않습니다. 부모가 선언한 __slots__ 은 자식 클래스에 제공됩니다. 하지만, 자식 서브 클래스가 자신의 __slots__ (새로 추가되는 변수들만 포함해야 합니다) 을 정의하지 않는다면 __dict__ 와 __weakref__ 를 갖게 됩니다.

클래스가 베이스 클래스의 __slots__ 에 정의된 이름과 같은 이름의 변수를 __slots__ 에 선언한다면, 베이스 클래스가 정의한 변수는 액세스할 수 없는 상태가 됩니다(베이스 클래스로부터 디스크립터를 직접 조회하는 경우는 예외다). 이것은 프로그램을 정의되지 않은 상태로 보내게 됩니다. 미래에는, 이를 방지하기 위한 검사가 추가될 것입니다.

int, bytes, tuple과 같은 “가변 길이(valiable-length)” 의 내장형들을 계승하는 클래스에서는 오직 빈 __slots__ 만 지원됩니다.

__slots__ 에는 문자열 이외의 이터러블을 대입할 수 있습니다. 매핑도 역시 사용할 수 있습니다. 하지만, 미래에, 각 키에 대응하는 값들의 의미가 부여될 수 있습니다.

두 클래스가 같은 __slots__ 을 갖는 경우만 __class__ 대입이 동작합니다.

슬롯을 사용하는 여러 부모 클래스들을 다중 상속할 수 있지만, 오직 하나의 부모만 슬롯으로 만들어진 어트리뷰트를 가질 수 있습니다 (다른 베이스들은 빈 슬롯을 가져야만 합니다) - 이를 어기면 TypeError 를 일으킵니다.

If an iterator is used for __slots__ then a descriptor is created for each of the iterator’s values. However, the __slots__ attribute will be an empty iterator.

3.3.3. 클래스 생성 커스터마이제이션

클래스가 다른 클래스를 상속할 때, 그 클래스의 __init_subclass__ 가 호출됩니다. 이 방법으로, 서브 클래스의 동작을 변경하는 클래스를 쓰는 것이 가능합니다. 이런 용도는 클래스 데코레이터와도 밀접히 관련되어 있습니다. 하지만 클래스 데코레이터는 그들을 사용하는 특정한 클래스에만 작용하지만, __init_subclass__ 단독으로 그 메서드를 정의하는 클래스의 미래 서브 클래스 모두에게 작용합니다.

classmethod object.__init_subclass__(cls)

이 메서드는 포함하는 클래스의 서브 클래스가 만들어질 때마다 호출됩니다. cls 는 새 서브 클래스입니다. 만약 일반적인 인스턴스 메서드로 정의되면, 이 메서드는 묵시적으로 클래스 메서드로 변경됩니다.

새 클래스에 주어진 키워드 인자들은 부모 클래스의 __init_subclass__ 로 전달됩니다. __init_subclass__ 를 사용하는 다른 클래스들과의 호환성을 위해, 필요한 키워드 인자들을 꺼낸 후에 다른 것들을 베이스 클래스로 전달해야 합니다. 이런 식입니다:

class Philosopher:
    def __init_subclass__(cls, default_name, **kwargs):
        super().__init_subclass__(**kwargs)
        cls.default_name = default_name

class AustralianPhilosopher(Philosopher, default_name="Bruce"):
    pass

기본 구현 object.__init_subclass__ 는 아무 일도 하지 않지만, 인자가 포함되어 호출되면 예외를 발생시킵니다.

참고

메타 클래스 힌트 metaclass 는 나머지 형 절차에 의해 소비되고, __init_subclass__ 로 전달되지 않습니다. 실제 메타 클래스 (명시적인 힌트 대신에) 는 type(cls) 로 액세스할 수 있습니다.

버전 3.6에 추가.

3.3.3.1. 메타 클래스

기본적으로, 클래스는 type() 을 사용해서 만들어집니다. 클래스의 바디는 새 이름 공간에서 실행되고, 클래스 이름은 type(name, bases, namespace) 의 결과에 지역적으로 연결됩니다.

클래스를 만드는 과정은 클래스 정의 줄에 metaclass 키워드 인자를 전달하거나, 그런 인자를 포함한 이미 존재하는 클래스를 계승함으로써 커스터마이즈될 수 있습니다. 다음 예에서, MyClass 와 MySubclass 는 모두 Meta 의 인스턴스입니다.

class Meta(type):
    pass

class MyClass(metaclass=Meta):
    pass

class MySubclass(MyClass):
    pass

클래스 정의에서 지정된 다른 키워드 인자들은 아래에서 설명되는 모든 메타 클래스 연산들로 전달됩니다.

클래스 정의가 실행될 때, 다음과 같은 단계가 수행됩니다.:

MRO 항목이 결정됩니다;

적절한 메타 클래스가 결정됩니다;

클래스 이름 공간이 준비됩니다;

클래스 바디가 실행됩니다;

클래스 객체가 만들어집니다.

3.3.3.2. MRO 항목 결정하기

클래스 정의에 나타나는 베이스 클래스가 type 의 인스턴스가 아닌 경우, 거기에서 __mro_entries__ 메서드를 검색합니다. 발견되면, 원래의 베이스 튜플로 호출됩니다. 이 메서드는 이 베이스 대신에 사용될 클래스의 튜플을 돌려줘야 합니다. 튜플은 비어있을 수 있습니다. 이 경우 원래 베이스는 무시됩니다.

더 보기

PEP 560 [https://www.python.org/dev/peps/pep-0560] - typing 모듈과 제네릭 형에 대한 코어 지원

3.3.3.3. 적절한 메타 클래스 선택하기

클래스 정의의 적절한 메타 클래스는 다음과 같이 결정됩니다:

베이스와 명시적인 메타 클래스를 주지 않는 경우 type() 이 사용됩니다;

명시적인 메타 클래스가 지정되고, 그것이 type() 의 인스턴스가 아니면, 그것을 메타 클래스로 사용합니다;

type() 의 인스턴스가 명시적인 메타 클래스로 주어지거나, 베이스가 정의되었으면, 가장 많이 파생된 메타 클래스가 사용됩니다.

가장 많이 파생된 메타 클래스는 명시적으로 지정된 메타 클래스(있다면)와 지정된 모든 베이스 클래스들의 메타 클래스들(즉, type(cls)) 중에서 선택됩니다. 가장 많이 파생된 메타 클래스는 이들 모두 의 서브 타입(subtype)입니다. 만약 어느 것도 이 조건을 만족하지 못한다면, 클래스 정의는 TypeError 를 발생시키며 실패합니다.

3.3.3.4. 클래스 이름 공간 준비하기

Once the appropriate metaclass has been identified, then the class namespace is prepared. If the metaclass has a __prepare__ attribute, it is called as namespace = metaclass.__prepare__(name, bases, **kwds) (where the additional keyword arguments, if any, come from the class definition). The __prepare__ method should be implemented as a classmethod(). The namespace returned by __prepare__ is passed in to __new__, but when the final class object is created the namespace is copied into a new dict.

만약 메타 클래스에 __prepare__ 어트리뷰트가 없다면, 클래스 이름 공간은 빈 순서 있는 매핑(ordered mapping) 으로 초기화됩니다.

더 보기

PEP 3115 [https://www.python.org/dev/peps/pep-3115] - 파이썬 3000 에서의 메타 클래스

__prepare__ 이름 공간 훅을 도입했습니다

3.3.3.5. 클래스 바디 실행하기

클래스 바디는 (대략) exec(body, globals(), namespace) 과같이 실행됩니다. 일반적인 exec() 호출과 주된 차이점은 클래스 정의가 함수 내부에서 이루어질 때 어휘 스코핑(lexical scoping) 이 클래스 바디(모든 메서드들을 포함해서)로 하여금 현재와 외부 스코프에 있는 이름들을 참조하도록 허락한다는 것입니다.

하지만, 클래스 정의가 함수 내부에서 이루어질 때조차도, 클래스 내부에서 정의된 메서드들은 클래스 스코프에서 정의된 이름들을 볼 수 없습니다. 클래스 변수는 인스턴스나 클래스 메서드의 첫 번째 매개변수를 통해 액세스하거나 다음 섹션에서 설명하는 묵시적으로 어휘 스코핑된 __class__ 참조를 통해야 합니다.

3.3.3.6. 클래스 객체 만들기

일단 클래스 이름 공간이 클래스 바디를 실행함으로써 채워지면, 클래스 객체가 metaclass(name, bases, namespace, **kwds) 을 통해 만들어집니다(여기에서 전달되는 추가적인 키워드 인자들은 __prepare__ 에 전달된 것들과 같습니다).

이 클래스 객체는 super() 에 인자를 주지 않는 경우 참조되는 것입니다. __class__ 는 클래스 바디의 메서드들 중 어느 하나라도 __class__ 나 super 를 참조할 경우 컴파일러에 의해 만들어지는 묵시적인 클로저(closure) 참조입니다. 이것은 인자 없는 형태의 super() 가 어휘 스코핑 기반으로 현재 정의되고 있는 클래스를 올바르게 찾을 수 있도록 합니다. 반면에 현재의 호출에 사용된 클래스나 인스턴스는 메서드로 전달된 첫 번째 인자에 기초해서 식별됩니다.

CPython implementation detail: CPython 3.6 이상에서, __class__ 셀(cell)은 클래스 이름 공간의 __classcell__ 엔트리로 메타 클래스에 전달됩니다. 만약 존재한다면, 이것은 클래스가 올바르게 초기화되기 위해 type.__new__ 호출까지 거슬러서 전파되어야 합니다. 이렇게 하지 못하면 파이썬 3.6 에서는 DeprecationWarning으로, 파이썬 3.8 에서는 RuntimeError로 이어질 것입니다.

기본 메타 클래스 type 을 사용할 때나 다른 메타 클래스가 결국 type.__new__ 를 호출할 때, 클래스 객체를 만든 후에, 다음과 같은 추가의 커스터마이제이션 단계가 실행됩니다:

첫째로, type.__new__ 는 __set_name__() 을 정의하는 클래스 이름 공간의 모든 디스크립터들을 수집합니다;

둘째로, 이렇게 수집된 모든 __set_name__ 을 호출하는데, 정의되고 있는 클래스와 디스크립터에 주어진 이름을 인자로 전달합니다;

마지막으로, 메서드 결정 순서에 따라 가장 가까운 부모에 대해 __init_subclass__() 훅이 호출됩니다.

클래스 객체가 만들어진 후에, 클래스 정의에 포함된 클래스 데코레이터들에게 (있다면) 클래스를 전달하고, 그 결과를 클래스가 정의되는 지역 이름 공간에 연결합니다.

type.__new__ 로 새 클래스가 만들어질 때, 이름 공간 매개변수로 제공되는 객체는 새로 만든 순서 있는 매핑으로 복사되고, 원래의 객체는 버립니다. 새 사본은 읽기 전용 프락시(read-only proxy)로 둘러싸이는데, 이것이 클래스 객체의 __dict__ 어트리뷰트가 됩니다.

더 보기

PEP 3135 [https://www.python.org/dev/peps/pep-3135] - 새 super

묵시적인 __class__ 클로저 참조를 설명합니다

3.3.3.7. 메타 클래스의 용도

메타 클래스의 잠재적인 용도에는 한계가 없습니다. 탐색 된 몇 가지 아이디어들에는 enum, 로깅, 인터페이스 검사, 자동화된 위임(automatic delegation), 자동화된 프로퍼티(properety) 생성, 프락시(proxy), 프레임웍(framework), 자동화된 자원 로킹/동기화(automatic resource locking/synchronization) 등이 있습니다.

3.3.4. 인스턴스 및 서브 클래스 검사 커스터마이제이션

다음 메서드들은 isinstance() 와 issubclass() 내장 함수들의 기본 동작을 재정의하는 데 사용됩니다.

특히, 메타 클래스 abc.ABCMeta 는 추상 베이스 클래스(Abstract Base Class, ABC)를 다른 ABC를 포함한 임의의 클래스나 형(내장형을 포함합니다)에 “가상 베이스 클래스(virtual base class)”로 추가할 수 있게 하려고 이 메서드들을 구현합니다.

class.__instancecheck__(self, instance)

instance 가 (직접적이거나 간접적으로) class 의 인스턴스로 취급될 수 있으면 참을 돌려줍니다. 만약 정의되면, isinstance(instance, class) 를 구현하기 위해 호출됩니다.

class.__subclasscheck__(self, subclass)

subclass 가 (직접적이거나 간접적으로) class 의 서브 클래스로 취급될 수 있으면 참을 돌려줍니다. 만약 정의되면, issubclass(subclass, class) 를 구현하기 위해 호출됩니다.

이 메서드들은 클래스의 형(메타 클래스)에서 조회된다는 것에 주의해야 합니다. 실제 클래스에서 클래스 메서드로 정의될 수 없습니다. 이것은 인스턴스에 대해 호출되는 특수 메서드들의 조회와 일관성 있습니다. 이 경우 인스턴스는 클래스 자체다.

더 보기

PEP 3119 [https://www.python.org/dev/peps/pep-3119] - 추상 베이스 클래스의 도입

__instancecheck__() 와 __subclasscheck__() 를 통해 isinstance() 와 issubclass() 의 동작을 커스터마이징하는 데 필요한 규약을 포함하는데, 이 기능의 동기는 언어에 추상 베이스 클래스 (abc 모듈을 보십시오)를 추가하고자 하는 데 있습니다.

3.3.5. 제네릭 형 흉내 내기

특수 메서드를 정의함으로써 PEP 484 [https://www.python.org/dev/peps/pep-0484]에서 지정된 제네릭 클래스 문법(예를 들면 List[int])을 구현할 수 있습니다:

classmethod object.__class_getitem__(cls, key)

key 에 있는 형 인자에 의한 제네릭 클래스의 특수화를 나타내는 객체를 돌려줍니다.

이 메서드는 클래스 개체 자체에서 조회되며, 클래스 바디에 정의된 경우, 이 메서드는 묵시적으로 클래스 메서드입니다. 이 메커니즘은 주로 정적 형 힌트와 함께 사용하기 위해 예약되어 있습니다. 다른 용도는 권장하지 않습니다.

더 보기

PEP 560 [https://www.python.org/dev/peps/pep-0560] - typing 모듈과 제네릭 형에 대한 코어 지원

3.3.6. 콜러블 객체 흉내 내기

object.__call__(self[, args...])

인스턴스가 함수처럼 “호출될” 때 호출됩니다; 이 메서드가 정의되면, x(arg1, arg2, ...) 는 x.__call__(arg1, arg2, ...) 의 줄인 표현입니다.

3.3.7. 컨테이너형 흉내 내기

The following methods can be defined to implement container objects. Containers usually are sequences (such as lists or tuples) or mappings (like dictionaries), but can represent other containers as well. The first set of methods is used either to emulate a sequence or to emulate a mapping; the difference is that for a sequence, the allowable keys should be the integers k for which 0 <= k < N where N is the length of the sequence, or slice objects, which define a range of items. It is also recommended that mappings provide the methods keys(), values(), items(), get(), clear(), setdefault(), pop(), popitem(), copy(), and update() behaving similar to those for Python’s standard dictionary objects. The collections.abc module provides a MutableMapping abstract base class to help create those methods from a base set of __getitem__(), __setitem__(), __delitem__(), and keys(). Mutable sequences should provide methods append(), count(), index(), extend(), insert(), pop(), remove(), reverse() and sort(), like Python standard list objects. Finally, sequence types should implement addition (meaning concatenation) and multiplication (meaning repetition) by defining the methods __add__(), __radd__(), __iadd__(), __mul__(), __rmul__() and __imul__() described below; they should not define other numerical operators. It is recommended that both mappings and sequences implement the __contains__() method to allow efficient use of the in operator; for mappings, in should search the mapping’s keys; for sequences, it should search through the values. It is further recommended that both mappings and sequences implement the __iter__() method to allow efficient iteration through the container; for mappings, __iter__() should iterate through the object’s keys; for sequences, it should iterate through the values.

object.__len__(self)

내장함수 len() 를 구현하기 위해 호출됩니다. 객체의 길이를 돌려줘야 하는데, >= 0인 정수입니다. 또한 __bool__() 메서드를 정의하지 않은 객체의 __len__() 이 0을 돌려주면 논리 문맥에서 거짓으로 취급됩니다.

CPython implementation detail: CPython 에서, 길이는 최대 sys.maxsize 일 것이 요구됩니다. 만약 길이가 sys.maxsize 보다 크면, 어떤 기능들 (len() 과 같은)은 OverflowError 를 일으킬 수 있습니다. 참 거짓 검사에서 OverflowError 가 일어나는 것을 막기 위해, 객체는 __bool__() 를 정의해야 합니다.

object.__length_hint__(self)

Called to implement operator.length_hint(). Should return an estimated length for the object (which may be greater or less than the actual length). The length must be an integer >= 0. The return value may also be NotImplemented, which is treated the same as if the __length_hint__ method didn’t exist at all. This method is purely an optimization and is never required for correctness.

버전 3.4에 추가.

참고

슬라이싱은 전적으로 다음에 나오는 세 메서드들에의해 수행됩니다

a[1:2] = b

과 같은 호출은

a[slice(1, 2, None)] = b

로 번역되고, 다른 형태도 마찬가지입니다. 빠진 슬라이스 항목은 항상 None 으로 채워집니다.

object.__getitem__(self, key)

self[key] 의 값을 구하기 위해 호출됩니다. 시퀀스형의 경우, 정수와 슬라이스 객체만 키로 허용됩니다. 음수 인덱스(만약 클래스가 시퀀스 형을 흉내 내길 원한다면)의 특별한 해석은 __getitem__() 메서드에 달려있음에 주의해야 합니다. 만약 key 가 적절하지 않은 형인 경우, TypeError 가 발생할 수 있습니다; 만약 시퀀스의 인덱스 범위를 벗어나면(음수에 대한 특별한 해석 후에), IndexError 를 일으켜야 합니다. 매핑 형의 경우, key 가 (컨테이너에) 없으면, KeyError 를 일으켜야 합니다.

참고

for 루프는 시퀀스의 끝을 올바로 감지하기 위해, 잘못된 인덱스에 대해 IndexError 가 일어날 것으로 기대하고 있습니다.

object.__setitem__(self, key, value)

self[key] 로의 대입을 구현하기 위해 호출됩니다. __getitem__() 과 같은 주의가 필요합니다. 매핑의 경우에는, 객체가 키에 대해 값의 변경이나 새 키의 추가를 허락할 경우, 시퀀스의 경우는 항목이 교체될 수 있을 때만 구현되어야 합니다. 잘못된 key 값의 경우는 __getitem__() 에서와 같은 예외를 일으켜야 합니다.

object.__delitem__(self, key)

self[key] 의 삭제를 구현하기 위해 호출됩니다. __getitem__() 과 같은 주의가 필요합니다. 매핑의 경우에는, 객체가 키의 삭제를 허락할 경우, 시퀀스의 경우는 항목이 시퀀스로부터 제거될 수 있을 때만 구현되어야 합니다. 잘못된 key 값의 경우는 __getitem__() 에서와 같은 예외를 일으켜야 합니다.

object.__missing__(self, key)

dict.__getitem__() 이 dict 서브 클래스에서 키가 딕셔너리에 없으면 self[key] 를 구현하기 위해 호출합니다.

object.__iter__(self)

컨테이너의 이터레이터가 필요할 때 이 메서드가 호출됩니다. 이 메서드는 컨테이너에 포함된 모든 객체를 이터레이트할 수 있는 이터레이터 객체를 돌려줘야 합니다. 매핑의 경우, 컨테이너의 키를 이터레이트해야 합니다.

이터레이터 객체 역시 이 메서드를 구현할 필요가 있습니다; 자기 자신을 돌려줘야 합니다. 이터레이터 객체에 대한 추가의 정보는 이터레이터 형 에 있습니다.

object.__reversed__(self)

reversed() 내장 함수가 역 이터레이션(reverse iteration)을 구현하기 위해 (있다면) 호출합니다. 컨테이너에 있는 객체들을 역 순으로 탐색하는 새 이터레이터 객체를 돌려줘야 합니다.

__reversed__() 메서드가 제공되지 않으면, reversed() 내장함수는 시퀀스 프로토콜(__len__() 과 __getitem__())을 대안으로 사용합니다. 시퀀스 프로토콜을 지원하는 객체들은 reversed() 가 제공하는 것보다 더 효율적인 구현을 제공할 수 있을 때만 __reversed__() 를 제공해야 합니다.

The membership test operators (in and not in) are normally implemented as an iteration through a container. However, container objects can supply the following special method with a more efficient implementation, which also does not require the object be iterable.

object.__contains__(self, item)

멤버십 검사 연산자를 구현하기 위해 호출됩니다. item 이 self 에 있으면 참을, 그렇지 않으면 거짓을 돌려줘야 합니다. 매핑 객체의 경우, 키-값 쌍이 아니라 매핑의 키가 고려되어야 합니다.

__contains__() 를 정의하지 않는 객체의 경우, 멤버십 검사는 먼저 __iter__() 를 통한 이터레이션을 시도한 후, __getitem__() 을 통한 낡은 시퀀스 이터레이션 프로토콜을 시도합니다. membership-test-details 섹션을 참고하십시오.

3.3.8. 숫자 형 흉내 내기

숫자 형을 흉내 내기 위해 다음과 같은 메서드들을 정의할 수 있습니다. 구현되는 특별한 종류의 숫자에 의해 지원되지 않는 연산들(예를 들어, 정수가 아닌 숫자들에 대한 비트 연산들)에 대응하는 메서드들을 정의되지 않은 채로 남겨두어야 합니다.

object.__add__(self, other)

object.__sub__(self, other)

object.__mul__(self, other)

object.__matmul__(self, other)

object.__truediv__(self, other)

object.__floordiv__(self, other)

object.__mod__(self, other)

object.__divmod__(self, other)

object.__pow__(self, other[, modulo])

object.__lshift__(self, other)

object.__rshift__(self, other)

object.__and__(self, other)

object.__xor__(self, other)

object.__or__(self, other)

이 메서드들은 이항 산술 연산들(+, -, *, @, /, //, %, divmod(), pow(), **, <<, >>, &, ^, |)을 구현하기 위해 호출됩니다. 예를 들어, x 가 __add__() 메서드를 가진 클래스의 인스턴스일 때, 표현식 x + y 의 값을 구하기 위해, x.__add__(y) 가 호출됩니다. __divmod__() 메서드는 __floordiv__() 와 __mod__() 를 사용하는 것과 동등해야 합니다; __truediv__() 와 연관되지 않아야 합니다; 내장 pow() 함수의 삼 항 버전이 지원되기 위해서는, __pow__() 메서드가 생략할 수 있는 세 번째 인자를 받도록 정의되어야 함에 주의해야 합니다.

만약 이 메서드들 중 하나가 제공된 인자에 대해 연산을 지원하지 않으면, NotImplemented 를 돌려줘야 합니다.

object.__radd__(self, other)

object.__rsub__(self, other)

object.__rmul__(self, other)

object.__rmatmul__(self, other)

object.__rtruediv__(self, other)

object.__rfloordiv__(self, other)

object.__rmod__(self, other)

object.__rdivmod__(self, other)

object.__rpow__(self, other[, modulo])

object.__rlshift__(self, other)

object.__rrshift__(self, other)

object.__rand__(self, other)

object.__rxor__(self, other)

object.__ror__(self, other)

이 메서드들은 뒤집힌 피연산자들에 대해 이항 산술 연산들(+, -, *, @, /, //, %, divmod(), pow(), **, <<, >>, &, ^, |)을 구현하기 위해 호출됩니다. 이 함수들은 왼쪽의 피연산자가 해당 연산을 지원하지 않고 3, 피연산자들이 서로 다른 형일 때만 호출됩니다. 4 예를 들어, 표현식 x - y 의 값을 구하려고 할 때, y 가 __rsub__() 를 갖는 클래스의 인스턴스이고, x.__sub__(y) 가 NotImplemented 를 돌려주면 y.__rsub__(x) 가 호출됩니다.

삼 항 pow() 는 __rpow__() 를 호출하려고 시도하지 않음에 주의해야 합니다 (그렇게 하려면 코어션 규칙이 너무 복잡해집니다).

참고

만약 오른쪽 피연산자의 형이 왼쪽 피연산자의 형의 서브 클래스이고, 그 서브 클래스가 연산의 뒤집힌 메서드들 제공하면, 이 메서드가 왼쪽 연산자의 뒤집히지 않은 메서드보다 먼저 호출됩니다. 이 동작은 서브 클래스가 조상들의 연산을 재정의할 수 있도록 합니다.

object.__iadd__(self, other)

object.__isub__(self, other)

object.__imul__(self, other)

object.__imatmul__(self, other)

object.__itruediv__(self, other)

object.__ifloordiv__(self, other)

object.__imod__(self, other)

object.__ipow__(self, other[, modulo])

object.__ilshift__(self, other)

object.__irshift__(self, other)

object.__iand__(self, other)

object.__ixor__(self, other)

object.__ior__(self, other)

이 메서드들은 증분 산술 대입(+=, -=, *=, @=, /=, //=, %=, **=, <<=, >>=, &=, ^=, |=)을 구현하기 위해 호출됩니다. 이 메서드는 연산을 제자리에서(self 를 수정해서) 하도록 시도해야 하고, 결과(반드시 그래야 하는 것은 아니지만 self 일 수 있습니다)를 돌려줘야 합니다. 만약 특정 메서드가 정의되지 않으면, 중분 대입은 일반적인 메서드들을 대신 사용합니다. 예를 들어, x 가 __iadd__() 메서드를 갖는 클래스의 인스턴스면, x += y 는 x = x.__iadd__(y) 와 동등합니다. 그렇지 않으면, x + y 의 값을 구할 때처럼, x.__add__(y) 와 y.__radd__(x) 가 고려됩니다. 어떤 상황에서, 증분 대입은 예상치 못한 에러로 이어질 수 있습니다. (Why does a_tuple[i] += [‘item’] raise an exception when the addition works? 를 보십시오). 하지만 이 동작은 사실 데이터 모델의 일부입니다.

object.__neg__(self)

object.__pos__(self)

object.__abs__(self)

object.__invert__(self)

일 항 산술 연산(-, +, abs(), ~)을 구현하기 위해 호출됩니다.

object.__complex__(self)

object.__int__(self)

object.__float__(self)

내장 함수 complex(), int(), float()를 구현하기 위해 호출됩니다. 적절한 형의 값을 돌려줘야 합니다.

object.__index__(self)

operator.index() 를 구현하기 위해 호출되고, 파이썬이 숫자 객체를 정수 객체로 손실 없이 변환해야 할 때(슬라이싱이나 내장 bin(), hex(), oct() 함수들에서와같이)마다 호출됩니다. 이 메서드의 존재는 숫자 객체가 정수 형임을 가리킵니다. 반드시 정수를 돌려줘야 합니다.

참고

일관성 있는 정수형 클래스를 가지려고, __index__() 가 정의될 때는 __int__() 역시 정의되어야 하고, 둘 다 같은 값을 돌려줘야 합니다.

object.__round__(self[, ndigits])

object.__trunc__(self)

object.__floor__(self)

object.__ceil__(self)

내장 함수 round()와 math 함수 trunc(), floor(), ceil() 을 구현하기 위해 호출됩니다. ndigits 가 __round__() 로 전달되지 않는 한, 이 메서드들은 모두 Integral (보통 int) 로 잘린 객체의 값을 돌려줘야 합니다.

__int__() 가 정의되어 있지 않으면, 내장 함수 int() 는 __trunc__() 를 사용합니다.

3.3.9. with 문 컨텍스트 관리자

컨텍스트 관리자 (context manager) 는 with 문을 실행할 때 자리 잡는 실행 컨텍스트(context)를 정의하는 객체입니다. 코드 블록의 실행을 위해, 컨텍스트 관리자는 원하는 실행시간 컨텍스트로의 진입과 탈출을 처리합니다. 컨텍스트 관리자는 보통 with 문(with 문 섹션에서 설명합니다)으로 시작되지만, 그들의 메서드를 호출해서 직접 사용할 수도 있습니다.

컨텍스트 관리자의 전형적인 용도에는 다양한 종류의 전역 상태(global state)를 보관하고 복구하는 것, 자원을 로킹(locking)하고 언로킹(unlocking)하는 것, 열린 파일을 닫는 것 등이 있습니다.

컨텍스트 관리자에 대한 더 자세한 정보는 컨텍스트 관리자 형 에 나옵니다.

object.__enter__(self)

이 객체와 연관된 실행시간 컨텍스트에 진입합니다. with 문은 as 절로 지정된 대상이 있다면, 이 메서드의 반환 값을 연결합니다.

object.__exit__(self, exc_type, exc_value, traceback)

이 객체와 연관된 실행시간 컨텍스트를 종료합니다. 매개변수들은 컨텍스트에서 벗어나게 만든 예외를 기술합니다. 만약 컨텍스트가 예외 없이 종료한다면, 세 인자 모두 None 이 됩니다.

만약 예외가 제공되고, 메서드가 예외를 중지시키고 싶으면 (즉 확산하는 것을 막으려면) 참(true)을 돌려줘야 합니다. 그렇지 않으면 예외는 이 메서드가 종료한 후에 계속 진행됩니다.

__exit__() 메서드가 전달된 예외를 다시 일으키지(reraise) 않도록 주의해야 합니다; 이것은 호출자(caller)의 책임입니다.

더 보기

PEP 343 [https://www.python.org/dev/peps/pep-0343] - “with” 문

파이썬 with 문에 대한 규격, 배경, 예.

3.3.10. 특수 메서드 조회

사용자 정의 클래스의 경우, 묵시적인 특수 메서드의 호출은 객체의 인스턴스 딕셔너리가 아닌 객체의 형에 정의되어 있을 때만 올바르게 동작함이 보장됩니다. 이런 동작은 다음과 같은 코드가 예외를 일으키는 원인입니다:

>>> class C:
...     pass
...
>>> c = C()
>>> c.__len__ = lambda: 5
>>> len(c)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: object of type 'C' has no len()

이런 동작의 배경에 깔린 논리는, 모든 객체(형 객체를 포함해서)에 의해 구현되는 __hash__() 나 __repr__() 과 같은 많은 특수 메서드들과 관련이 있습니다. 만약 이 메서드들에 대한 묵시적인 조회가 일반적인 조회 프로세스를 거친다면, 형 객체 자체에 대해 호출되었을 때 실패하게 됩니다:

>>> 1 .__hash__() == hash(1)
True
>>> int.__hash__() == hash(int)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: descriptor '__hash__' of 'int' object needs an argument

클래스의 연결되지 않은 메서드를 호출하려는 이런 식의 잘못된 시도는 종종 ‘메타 클래스 혼란(metaclass confusion)’ 이라고 불리고, 특수 메서드를 조회할 때 인스턴스를 우회하는 방법으로 피할 수 있습니다.

>>> type(1).__hash__(1) == hash(1)
True
>>> type(int).__hash__(int) == hash(int)
True

올바름을 추구하기 위해 인스턴스 어트리뷰트들을 우회하는 것에 더해, 묵시적인 특수 메서드 조회는 객체의 메타 클래스의 __getattribute__() 메서드 조차도 우회합니다:

>>> class Meta(type):
...     def __getattribute__(*args):
...         print("Metaclass getattribute invoked")
...         return type.__getattribute__(*args)
...
>>> class C(object, metaclass=Meta):
...     def __len__(self):
...         return 10
...     def __getattribute__(*args):
...         print("Class getattribute invoked")
...         return object.__getattribute__(*args)
...
>>> c = C()
>>> c.__len__()                 # Explicit lookup via instance
Class getattribute invoked
10
>>> type(c).__len__(c)          # Explicit lookup via type
Metaclass getattribute invoked
10
>>> len(c)                      # Implicit lookup
10

이런 식으로 __getattribute__() 절차를 우회하는 것은 특수 메서드 처리의 유연함을 일부 포기하는 대신(특수 메서드가 인터프리터에 의해 일관성 있게 호출되기 위해서는 반드시 클래스 객체에 설정되어야 합니다), 인터프리터 내부에서의 속도 최적화를 위한 상당한 기회를 제공합니다.

3.4. 코루틴(Coroutines)

3.4.1. 어웨이터블 객체(Awaitable Objects)

어웨이터블 객체는 일반적으로 __await__() 메서드를 구현합니다. async def 함수가 돌려주는 코루틴 객체는 어웨이터블입니다.

참고

types.coroutine() 이나 asyncio.coroutine() 로 데코레이션된 제너레이터가 돌려주는 제너레이터 이터레이터 객체 또한 어웨이터블이지만 __await__() 를 구현하지 않습니다.

object.__await__(self)

이터레이터 를 돌려줘야 합니다. 어웨이터블 객체를 구현하기 위해 사용되어야 합니다. 예를 들어, asyncio.Future 는 await 표현식과 호환되기 위해 이 메서드를 구현합니다.

버전 3.5에 추가.

더 보기

PEP 492 [https://www.python.org/dev/peps/pep-0492] 가 어웨이터블 객체에 대한 더 자세한 정보를 포함하고 있습니다.

3.4.2. 코루틴 객체(Coroutine Objects)

코루틴 객체는 어웨이터블 객체입니다. 코루틴의 실행은 __await__() 를 호출하고 그 결과를 이터레이트하는 방법으로 제어될 수 있습니다. 코루틴이 실행을 완료하고 복귀할 때, 이터레이터는 StopIteration 을 일으키고, 예외의 value 어트리뷰트가 반환 값을 갖고 있습니다. 만약 코루틴이 예외를 일으키면, 이터레이터에 의해 퍼집니다. 코루틴이 직접 잡히지 않은 StopIteration 예외를 일으키지는 말아야 합니다.

코루틴은 다음에 나열하는 메서드들 또한 갖고 있는데, 제너레이터(제너레이터-이터레이터 메서드 를 보십시오)의 것들과 닮았습니다. 하지만, 제너레이터와는 달리, 코루틴은 이터레이션을 직접 지원하지는 않습니다.

버전 3.5.2에서 변경: 코루틴을 두 번 await 하면 RuntimeError 를 일으킵니다.

coroutine.send(value)

코루틴의 실행을 시작하거나 재개합니다. value 가 None 이면, __await__() 가 돌려준 이터레이터를 전진시키는 것과 같습니다. value 가 None 이 아니면, 이 메서드는 코루틴이 일시 중지되도록 한 이터레이터의 send() 메서드로 위임합니다. 결과(반환 값, StopIteration 이나 다른 예외)는 위에서 설명한 __await__() 의 반환 값을 이터레이트할 때와 같습니다.

coroutine.throw(type[, value[, traceback]])

코루틴에서 지정한 예외가 발생하도록 합니다. 이 메서드는 코루틴이 일시 중지되도록 한 이터레이터의 throw() 메서드로 위임합니다(그런 메서드를 가지는 경우). 그렇지 않으면, 일시 중지지점에서 예외가 발생합니다. 결과(반환 값, StopIteration 이나 다른 예외)는 위에서 설명한 __await__() 의 반환 값을 이터레이트할 때와 같습니다. 만약 예외가 코루틴에서 잡히지 않는다면 호출자에게 되돌아 전파됩니다.

coroutine.close()

코루틴이 자신을 정리하고 종료하도록 만듭니다. 만약 코루틴이 일시 중지 중이면, 이 메서드는 먼저 코루틴이 일시 중지되도록 한 이터레이터의 close() 메서드로 위임합니다(그런 메서드를 가지는 경우). 그런 다음 일시 중지지점에서 GeneratorExit 를 발생시키는데, 코루틴이 즉시 자신을 정리하도록 만듭니다. 마지막으로 코루틴에 실행을 종료했다고 표시하는데, 아직 시작하지조차 않았을 때도 그렇다.

코루틴 객체가 파괴될 때는 위의 프로세스에 따라 자동으로 닫힙니다(closed).

3.4.3. 비동기 이터레이터(Asynchronous Iterators)

비동기 이터레이터 는 자신의 __anext__ 메서드에서 비동기 코드를 호출할 수 있습니다.

비동기 이터레이터는 async for 문에서 사용될 수 있습니다.

object.__aiter__(self)

비동기 이터레이터 객체를 돌려줘야 합니다.

object.__anext__(self)

이터레이터의 다음 값을 주는 어웨이터블 을 돌려줘야 합니다. 이터레이션이 끝나면 StopAsyncIteration 에러를 일으켜야 합니다.

비동기 이터러블 객체의 예:

class Reader:
    async def readline(self):
        ...

    def __aiter__(self):
        return self

    async def __anext__(self):
        val = await self.readline()
        if val == b'':
            raise StopAsyncIteration
        return val

버전 3.5에 추가.

버전 3.7에서 변경: 파이썬 3.7 이전에, __aiter__ 는 비동기 이터레이터 로 결정될 어웨이터블 을 반환 할 수 있었습니다.

파이썬 3.7부터, __aiter__ 는 반드시 비동기 이터레이터 객체를 돌려줘야 합니다. 다른 것을 돌려주면 TypeError 에러가 발생합니다.

3.4.4. 비동기 컨텍스트 관리자

비동기 컨텍스트 관리자(asynchronous context manager) 는 __aenter__ 와 __aexit__ 메서드에서 실행을 일시 중지할 수 있는 컨텍스트 관리자 입니다.

비동기 컨텍스트 관리자는 async with 문에서 사용될 수 있습니다.

object.__aenter__(self)

이 메서드는 __enter__() 메서드와 의미상으로 유사한데, 유일한 차이점은 어웨이터블 을 돌려줘야 한다는 것입니다.

object.__aexit__(self, exc_type, exc_value, traceback)

이 메서드는 __exit__() 메서드와 의미상으로 유사한데, 유일한 차이점은 어웨이터블 을 돌려줘야 한다는 것입니다.

비동기 컨텍스트 관리자 클래스의 예:

class AsyncContextManager:
    async def __aenter__(self):
        await log('entering context')

    async def __aexit__(self, exc_type, exc, tb):
        await log('exiting context')

버전 3.5에 추가.

각주

1

어떤 제한된 조건으로, 어떤 경우에 객체의 형을 변경하는 것이 가능합니다. 하지만 잘못 다뤄지면 아주 괴상한 결과로 이어질 수 있으므로 일반적으로 좋은 생각이 아닙니다.

2

__hash__(), __iter__(), __reversed__(), __contains__() 메서드들이 이런 경우에 대한 특별한 처리를 포함하고 있습니다; 다른 것들도 여전히 TypeError 을 일으키지만, 단지 None 이 콜러블이 아니므로 그런 것뿐입니다.

3

여기서 “지원하지 않는다” 는 클래스가 그런 메서드를 갖지 않거나, 메서드가 NotImplemented 를 돌려줌을 뜻합니다. 오른쪽 피연산자의 뒤집힌 메서드를 사용하는 대안이 시도되도록 하려면 메서드를 None 으로 설정하지 말아야 합니다 - 그렇게 하는 것은 그런 대안을 명시적으로 금지하는 반대 효과를 줍니다.

4

피연산자들이 같은 형이면, 뒤집히지 않은 메서드(__add__() 같은)가 실패하면 그 연산이 지원되지 않는 것으로 간주합니다. 이것이 뒤집힌 메서드가 호출되지 않는 이유입니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 언어 레퍼런스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 언어 레퍼런스 »

|

4. 실행 모델

4.1. 프로그램의 구조

파이썬 프로그램은 코드 블록으로 만들어집니다. 블록 (block) 은 한 단위로 실행되는 한 조각의 파이썬 프로그램 텍스트입니다. 다음과 같은 것들이 블록입니다: 모듈, 함수 바디, 클래스 정의. 대화형으로 입력되는 각 명령은 블록입니다. 스크립트 파일(표준 입력을 통해 인터프리터로 제공되는 파일이나 인터프리터에 명령행 인자로 지정된 파일)은 코드 블록입니다. 스크립트 명령(-c 옵션으로 인터프리터 명령행에 지정된 명령)은 코드 블록입니다. 내장함수 eval() 과 exec() 로 전달되는 문자열 인자도 코드 블록입니다.

코드 블록은 실행 프레임 (execution frame) 에서 실행됩니다. 프레임은 몇몇 관리를 위한 정보(디버깅에 사용됩니다)를 포함하고, 코드 블록의 실행이 끝난 후에 어디서 어떻게 실행을 계속할 것인지를 결정합니다.

4.2. 이름과 연결(binding)

4.2.1. 이름의 연결

이름 (Names) 은 객체를 가리킵니다. 이름은 이름 연결 연산 때문에 만들어집니다.

다음과 같은 것들이 이름을 연결합니다: 함수로 전달되는 형식 매개변수, import 문, 클래스와 함수 정의(이것들은 클래스나 함수 이름을 정의하고 있는 블록에 연결합니다), 그리고 다음과 같은 것들에 등장하는 식별자 대상들: 대입, for 루프 헤더, with 문이나 except 절의 as 뒤. from ... import * 형태의 import 문은 임포트되는 모듈에 정의된 모든 이름을 연결합니다, 밑줄로 시작하는 이름들은 예외입니다. 이 형태는 모듈 수준에서만 사용될 수 있습니다.

del 문에 나오는 대상 역시 이 목적에서 연결된 것으로 간주합니다(실제 의미가 이름을 연결 해제하는 것이기는 해도).

각 대입이나 임포트 문은 클래스나 함수 정의 때문에 정의되는 블록 내에 등장할 수 있고, 모듈 수준(최상위 코드 블록)에서 등장할 수도 있습니다.

만약 이름이 블록 내에서 연결되면, nonlocal 이나 global 로 선언되지 않는 이상, 그 블록의 지역 변수입니다. 만약 이름이 모듈 수준에서 연결되면, 전역 변수입니다. (모듈 코드 블록의 변수들 지역이면서 전역입니다.) 만약 변수가 코드 블록에서 사용되지만, 거기에서 정의되지 않았으면 자유 변수 (free variable) 입니다.

프로그램 텍스트에 등장하는 각각의 이름들은 다음에 나오는 이름 검색(name resolution) 규칙에 따라 확정되는 이름의 연결 (binding) 을 가리킵니다.

4.2.2. 이름의 검색(resolution)

스코프 (scope) 는 블록 내에서 이름의 가시성(visibility)을 정의합니다. 지역 변수가 블록에서 정의되면, 그것의 스코프는 그 블록을 포함합니다. 만약 정의가 함수 블록에서 이루어지면, 포함된 블록이 그 이름에 대해 다른 결합을 만들지 않는 이상, 스코프는 정의하고 있는 것 안에 포함된 모든 블록으로 확대됩니다.

이름이 코드 블록 내에서 사용될 때, 가장 가깝게 둘러싸고 있는 스코프에 있는 것으로 검색됩니다. 코드 블록이 볼 수 있는 모든 스코프의 집합을 블록의 환경 (environment) 이라고 부릅니다.

이름이 어디에서도 발견되지 않으면 NameError 예외가 발생합니다. 만약 현재 스코프가 함수 스코프이고, 그 이름이 사용되는 시점에 아직 연결되지 않은 지역 변수면 UnboundLocalError 예외가 발생합니다. UnboundLocalError 는 NameError 의 서브 클래스입니다.

만약 이름 연결 연산이 코드 블록 내의 어디에서 건 일어난다면, 그 블록 내에서 그 이름의 모든 사용은 현재 블록을 가리키는 것으로 취급됩니다. 이것은 연결되기 전에 블록에서 사용될 때 에러로 이어질 수 있습니다. 이 규칙은 미묘합니다. 파이썬에는 선언(declaration)이 없고, 이름 연결 연산이 코드 블록 내의 어디에서나 일어날 수 있도록 허락합니다. 코드 블록의 지역 변수는 블록의 텍스트 전체에서 이름 연결 연산을 찾아야 결정될 수 있습니다.

만약 global 문이 블록 내에서 나오면, 문장에서 지정한 이름의 모든 사용은 최상위 이름 공간(top-level namespace)에 연결된 것을 가리키게 됩니다. 최상위 이름 공간에서 이름을 검색한다는 것은, 전역 이름 공간, 즉 코드 블록을 포함하는 모듈의 이름 공간, 과 내장 이름 공간, 모듈 builtins 의 이름 공간, 을 검색한다는 뜻입니다. 전역 이름 공간이 먼저 검색됩니다. 거기에서 이름이 발견되지 않으면, 내장 이름 공간을 검색합니다. global 문은 그 이름을 사용하기 전에 나와야 합니다.

global 문은 같은 블록의 이름 연결 연산과 같은 스코프를 갖습니다. 자유 변수의 경우 가장 가까이서 둘러싸는 스코프가 global 문을 포함한다면, 그 자유 변수는 전역으로 취급됩니다.

nonlocal 문은 대응하는 이름이 가장 가까이서 둘러싸는 함수 스코프에서 이미 연결된 이름을 가리키도록 만듭니다. 만약 주어진 이름이 둘러싸는 함수 스코프 어디에도 없다면 컴파일 시점에 SyntaxError 를 일으킵니다.

모듈의 이름 공간은 모듈이 처음 임포트될 때 자동으로 만들어집니다. 스크립트의 메인 모듈은 항상 __main__ 이라고 불립니다.

클래스 정의 블록과 exec() 와 eval() 로 전달되는 인자는 특별한 이름 검색 문맥을 갖습니다. 클래스 정의는 이름을 사용하고 정의할 수 있는 실행 가능한 문장입니다. 이 참조들은 연결되지 않은 지역 변수를 전역 이름 공간에서 찾는다는 점을 제외하고는 이름 검색의 일반적인 규칙을 따릅니다. 클래스 정의의 이름 공간은 클래스의 어트리뷰트 딕셔너리가 됩니다. 클래스 블록에서 정의된 이름들의 스코프는 클래스 블록으로 제한됩니다; 메서드들의 코드 블록으로 확대되지 않습니다 – 이것은 컴프리헨션과 제너레이터 표현을 포함하는데 이것들이 함수 스코프를 사용해서 구현되기 때문입니다. 이것은 다음과 같은 것이 실패한다는 뜻입니다:

class A:
    a = 42
    b = list(a + i for i in range(10))

4.2.3. builtins 와 제한된 실행

CPython implementation detail: 사용자는 __builtins__ 를 건드리지 말아야 합니다; 이것은 구현 세부사항입니다. 내장 이름 공간의 값을 변경하고 싶은 사용자는 builtins 모듈을 import 하고 그것의 어트리뷰트를 적절하게 수정해야 합니다.

코드 블록의 실행과 연관된 내장 이름 공간은, 사실 전역 이름 공간의 이름 __builtins__ 를 조회함으로써 발견됩니다. 이것은 딕셔너리나 모듈이어야 합니다(후자의 경우 모듈의 딕셔너리가 사용됩니다). 기본적으로, __main__ 모듈에 있을 때는 __builtins__ 가 내장 모듈 builtins 이고, 다른 모듈에 있을 때는 __builtins__ 는 builtins 모듈의 딕셔너리에 대한 별칭입니다.

4.2.4. 동적 기능과의 상호작용

자유 변수에 대해 이름 검색은 컴파일 시점이 아니라 실행 시점에 이루어집니다. 이것은 다음과 같은 코드가 42를 출력한다는 것을 뜻합니다:

i = 10
def f():
    print(i)
i = 42
f()

eval() 과 exec() 함수는 이름 검색을 위한 완전한 환경에 대한 접근권이 없습니다. 이름은 호출자의 지역과 전역 이름 공간에서 검색될 수 있습니다. 자유 변수는 가장 가까이 둘러싼 이름 공간이 아니라 전역 이름 공간에서 검색됩니다. 1 exec() 과 eval() 함수에는 전역과 지역 이름 공간을 재정의할 수 있는 생략 가능한 인자가 있습니다. 만약 단지 한 이름 공간만 주어지면, 그것이 두 가지 모두로 사용됩니다.

4.3. 예외

예외는 에러나 예외적인 조건을 처리하기 위해 코드 블록의 일반적인 제어 흐름을 깨는 수단입니다. 에러가 감지된 지점에서 예외를 일으킵니다(raised); 둘러싼 코드 블록이나 직접적 혹은 간접적으로 에러가 발생한 코드 블록을 호출한 어떤 코드 블록에서건 예외는 처리될 수 있습니다.

파이썬 인터프리터는 실행 시간 에러(0으로 나누는 것 같은)를 감지할 때 예외를 일으킵니다. 파이썬 프로그램은 raise 문을 사용해서 명시적으로 예외를 일으킬 수 있습니다. 예외 처리기는 try … except 문으로 지정됩니다. 그런 문장에서 finally 구는 정리(cleanup) 코드를 지정하는 데 사용되는데, 예외를 처리하는 것이 아니라 앞선 코드에서 예외가 발생하건 그렇지 않건 실행됩니다.

파이썬은 에러 처리에 “종결 (termination)” 모델을 사용합니다; 예외 처리기가 뭐가 발생했는지 발견할 수 있고, 바깥 단계에서 실행을 계속할 수는 있지만, 에러의 원인을 제거한 후에 실패한 연산을 재시도할 수는 없습니다(문제의 코드 조각을 처음부터 다시 시작시키는 것은 예외입니다).

예외가 어디서도 처리되지 않을 때, 인터프리터는 프로그램의 실행을 종료하거나, 대화형 메인 루프로 돌아갑니다. 두 경우 모두, 예외가 SystemExit 인 경우를 제외하고, 스택 트레이스백을 인쇄합니다.

예외는 클래스 인스턴스로 구분됩니다. except 절은 인스턴스의 클래스에 따라 선택됩니다: 인스턴스의 클래스나 그것의 베이스 클래스를 가리켜야 합니다. 인스턴스는 핸들러가 수신할 수 있고 예외적인 조건에 대한 추가적인 정보를 포함할 수 있습니다.

참고

예외 메시지는 파이썬 API 일부가 아닙니다. 그 내용은 파이썬의 버전이 바뀔 때 경고 없이 변경될 수 있고, 코드는 여러 버전의 인터프리터에서 실행될 수 있는 코드는 이것에 의존하지 말아야 합니다.

섹션 try 문 에서 try 문, raise 문 에서 raise 문에 대한 설명이 제공됩니다.

각주

1

이 한계는 이 연산들 때문에 실행되는 코드가 모듈이 컴파일되는 시점에는 존재하지 않았기 때문입니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 언어 레퍼런스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 언어 레퍼런스 »

|

5. 임포트 시스템

한 모듈 에 있는 파이썬 코드는 임포팅 이라는 프로세스를 통해 다른 모듈에 있는 코드들에 대한 접근권을 얻습니다. import 문은 임포트 절차를 일으키는 가장 흔한 방법이지만, 유일한 방법은 아닙니다. importlib.import_module() 같은 함수나 내장 __import__() 도 임포트 절차를 일으키는데 사용될 수 있습니다.

import 문은 두 가지 연산을 합친 것입니다; 먼저 이름이 가리키는 모듈을 찾은 후에, 그 검색의 결과를 지역 스코프의 이름에 연결합니다. import 문의 검색 연산은 적절한 인자들로 __import__() 함수를 호출하는 것으로 정의됩니다. __import__() 의 반환 값은 import 문의 이름 연결 연산을 수행하는 데 사용됩니다. 이 이름 연결 연산의 정확한 세부사항에 대해서는 import 문을 보세요.

__import__() 의 직접 호출은 모듈을 찾고, 발견된다면, 모듈을 만드는 연산만을 수행합니다. 부모 패키지를 임포트하거나 여러 캐시(sys.modules 를 포함합니다)를 갱신하는 것과 같은 부수적인 효과들이 일어날 수 있기는 하지만, 오직 import 문만이 이름 연결 연산을 수행합니다.

import 문이 실행될 때, 표준 내장 __import__() 가 호출됩니다. 임포트 시스템을 호출하는 다른 메커니즘 (importlib.import_module() 같은)은 __import__() 를 사용하지 않고 임포트 개념을 구현하기 위한 자신의 방법을 사용할 수 있습니다.

모듈이 처음 임포트 될 때, 파이썬은 모듈을 검색하고, 발견된다면, 모듈 객체를 만들고 1, 초기화합니다. 만약 그 이름의 모듈을 발견할 수 없다면, ModuleNotFoundError 를 일으킵니다. 파이썬은 임포트 절차가 호출될 때 이름 붙여진 모듈을 찾는 다양한 전략을 구현합니다. 이 전략들은 다음 섹션에서 설명하는 여러 가지 훅을 통해 수정되고 확장될 수 있습니다.

버전 3.3에서 변경: 임포트 시스템은 PEP 302 [https://www.python.org/dev/peps/pep-0302] 의 두 번째 단계를 완전히 구현하도록 개정되었습니다. 이제 묵시적인 임포트 절차는 없습니다 - 전체 임포트 시스템이 sys.meta_path 을 통해 노출됩니다. 여기에 더해, 네이티브(native) 이름 공간 패키지의 지원이 구현되었습니다 (PEP 420 [https://www.python.org/dev/peps/pep-0420] 을 보세요).

5.1. importlib

importlib 모듈은 임포트 시스템과 상호 작용하기 위한 풍부한 API를 제공합니다. 예를 들어, importlib.import_module() 는 임포트 절차를 구동하는 데 있어 내장 __import__() 에 비해 권장되고, 더 간단한 API를 제공합니다. 더 상세한 내용은 importlib 라이브러리 설명서를 참조하십시오.

5.2. 패키지(package)

파이썬은 한 가지 종류의 모듈 객체만 갖고 있고, 모든 모듈은 모듈이 파이썬이나 C나 그 밖의 다른 어떤 방법으로 구현되었는지와 상관없이 이 형입니다. 모듈을 조직화하고 이름 계층구조를 제공하기 위해, 파이썬은 패키지 라는 개념을 갖고 있습니다.

패키지를 파일 시스템에 있는 디렉터리라고 생각할 수 있지만, 패키지와 모듈이 파일시스템으로부터 올 필요는 없으므로 이 비유를 너무 문자 그대로 해석하지 말아야 합니다. 이 문서의 목적상, 디렉터리와 파일이라는 비유를 사용할 것입니다. 파일 시스템 디렉터리처럼, 패키지는 계층적으로 조직화하고, 패키지는 보통 모듈뿐만 아니라 서브 패키지도 포함할 수 있습니다.

모든 패키지가 모듈이라는 것을 기억하는 것이 중요합니다. 하지만 모든 모듈이 패키지인 것은 아닙니다. 다른 식으로 표현하면, 패키지는 특별한 종류의 모듈입니다. 구체적으로, __path__ 어트리뷰트를 포함하는 모든 모듈은 패키지로 취급됩니다.

모든 모듈은 이름이 있습니다. 서브 패키지 이름은 파이썬의 표준 어트리뷰트 액세스 문법을 따라, 부모 패키지 이름과 점(dot)으로 구분됩니다. 그래서 sys 라고 불리는 모듈과 email 이라고 불리는 패키지가 있을 수 있습니다. email 은 다시 서브 패키지 email.mime 을 갖고, 이 서브 패키지 내에 모듈 email.mime.text 가 있을 수 있습니다.

5.2.1. 정규 패키지

파이썬은 두 가지 종류의 패키지를 정의합니다, 정규 패키지 와 이름 공간 패키지. 정규 패키지는 파이썬 3.2와 그 이전에 존재하던 전통적인 패키지입니다. 정규 패키지는 보통 __init__.py 파일을 가진 디렉터리로 구현됩니다. 정규 패키지가 임포트될 때, 이 __init__.py 파일이 묵시적으로 실행되고, 그것이 정의하는 객체들이 패키지의 이름 공간의 이름들도 연결됩니다. __init__.py 파일은 다른 모듈들이 가질 수 있는 것과 같은 파이썬 코드를 포함할 수 있고, 파이썬은 임포트될 때 모듈에 몇 가지 어트리뷰트를 추가합니다.

예를 들어, 다음과 같은 파일시스템 배치는 최상위 parent 패키지와 세 개의 서브 패키지를 정의합니다:

parent/
    __init__.py
    one/
        __init__.py
    two/
        __init__.py
    three/
        __init__.py

parent.one 을 임포트하면 parent/__init__.py 과 parent/one/__init__.py 을 묵시적으로 실행합니다. 뒤이은 parent.two 와 parent.three 의 임포트는 각각 parent/two/__init__.py 와 parent/three/__init__.py 를 실행합니다.

5.2.2. 이름 공간 패키지

이름 공간 패키지는 여러 가지 포션 들의 복합체인데, 각 포션들은 부모 패키지의 서브 패키지로 이바지합니다. 포션들은 파일시스템의 다른 위치에 놓일 수 있습니다. 포션들은 zip 파일이나 네트워크나 파이썬이 임포트 할 때 검색하는 어떤 다른 장소에서 발견될 수 있습니다. 이름 공간 패키지는 파일시스템의 객체와 직접적인 상관관계가 있을 수도 있고 그렇지 않을 수도 있습니다; 구체적인 형태가 없는 가상 모듈일 수도 있습니다.

이름 공간 패키지는 __path__ 어트리뷰트로 일반적인 리스트를 사용하지 않습니다. 대신에 특별한 이터러블 형을 사용하는데, 그 패키지 내의 다음 임포트 시도에서 그것의 부모 패키지(또는 최상위 패키지의 경우 sys.path) 의 경로가 변했으면 패키지 포션에 대한 새 검색을 자동으로 수행하게 됩니다.

이름 공간 패키지의 경우, parent/__init__.py 파일이 없습니다. 사실, 임포트 검색 동안 여러 개의 parent` 디렉터리가 발견될 수 있고, 각각의 것은 다른 포션들에 의해 제공됩니다. 그래서 ``parent/one 은 물리적으로 parent/two 옆에 위치하지 않을 수 있습니다. 이 경우, 파이썬은 자신 또는 서브 패키지 중 어느 하나가 임포트 될 때마다 최상위 parent 패키지를 위한 이름 공간 패키지를 만듭니다.

이름 공간 패키지의 규격은 PEP 420 [https://www.python.org/dev/peps/pep-0420] 을 참조하세요.

5.3. 검색

검색을 시작하기 위해, 파이썬은 임포트될 모듈(또는 패키지, 하지만 이 논의에서 차이점은 중요하지 않다)의 완전히 정규화된 이름 을 필요로 합니다. 이 이름은 import 문으로 제공된 여러 인자나, importlib.import_module() 나 __import__() 함수로 전달된 매개변수들로부터 옵니다.

이 이름은 임포트 검색의 여러 단계에서 사용되는데, 서브 모듈로 가는 점으로 구분된 경로일 수 있습니다, 예를 들어 foo.bar.baz. 이 경우에, 파이썬은 먼저 foo 를, 그다음에 foo.bar 를, 마지막으로 foo.bar.baz 를 임포트하려고 시도합니다. 만약 중간 임포트가 어느 하나라도 실패한다면 ModuleNotFoundError 가 발생합니다.

5.3.1. 모듈 캐시

임포트 검색 도중 처음으로 검사되는 장소는 sys.modules 입니다. 이 매핑은 중간 경로들을 포함해서 전에 임포트 된 모든 모듈의 캐시로 기능합니다. 그래서 만약 foo.bar.baz 가 앞서 임포트 되었다면, sys.modules 는 foo, foo.bar, foo.bar.baz 항목들을 포함합니다. 각 키에 대응하는 값들은 모듈 객체입니다.

임포트하는 동안, 모듈 이름을 sys.modules 에서 찾고, 만약 있다면 해당 값이 임포트를 만족하는 모듈이고, 프로세스는 완료됩니다. 하지만 값이 None 이면, ModuleNotFoundError 를 일으킵니다. 만약 모듈 이름이 없다면, 파이썬은 모듈 검색을 계속 진행합니다.

sys.modules 은 쓰기가 허락됩니다. 키를 삭제해도 해당 모듈을 파괴하지는 않지만(다른 모듈들이 아직 그 모듈에 대한 참조를 유지하고 있을 수 있으므로), 해당 이름의 모듈에 대한 캐시를 무효화해서, 다음 임포트때 파이썬으로 하여금 그 모듈을 다시 찾도록 만듭니다. 키에는 None 을 대입할 수도 있는데, 다음 임포트 때 ModuleNotFoundError 가 일어나도록 만듭니다.

모듈 객체에 대한 참조를 유지한다면, sys.modules 의 캐시 항목을 무효로 한 후 다시 임포트하면 두 모듈 객체는 같은 것이 아니게 됨에 주의해야 합니다. 반면에 importlib.reload() 는 같은 모듈 객체를 재사용하고, 간단하게 모듈의 코드를 다시 실행해서 모듈의 내용을 다시 초기화합니다.

5.3.2. 파인더(finder)와 로더(loader)

모듈이 sys.modules 에서 발견되지 않으면, 모듈을 찾아서 로드하기 위해 파이썬의 임포트 프로토콜이 구동됩니다. 이 프로토콜은 두 개의 개념적 객체들로 구성되어 있습니다, 파인더 와 로더. 파인더의 일은 자신이 알고 있는 전략을 사용해, 주어진 이름의 모듈을 찾을 수 있는지 결정하는 것입니다. 두 인터페이스 모두를 구현한 객체들을 임포터라고 부릅니다 - 요청한 모듈을 로딩할 수 있다고 판단할 때 자신을 돌려줍니다.

파이썬은 여러 가지 기본 파인더들과 임포터들을 포함하고 있습니다. 첫 번째 것은 내장 모듈들의 위치를 찾을 수 있고, 두 번째 것은 프로즌 모듈(frozen module)의 위치를 찾을 수 있고, 세 번째 것은 모듈을 임포트 경로 에서 검색합니다. 임포트 경로 는 파일 시스템의 경로나 zip 파일을 가리키는 위치들의 목록입니다. 그것은 URL로 식별될 수 있는 것들처럼, 위치가 지정될 수 있는 자원들을 검색하도록 확장될 수 있습니다.

임포트 절차는 확장 가능해서, 모듈 검색의 범위를 확대하기 위해 새 파인더를 추가할 수 있습니다.

파인더는 실제로 모듈을 로드하지는 않습니다. 주어진 이름의 모듈을 찾으면 임포트와 관련된 정보들을 요약한 모듈 스펙 (module spec) 을 돌려주는데, 임포트 절차는 모듈을 로딩할 때 이것을 사용하게 됩니다.

다음 섹션은 파인더와 로더의 프로토콜에 대해 좀 더 자세히 설명하는데, 임포트 절차를 확장하기 위해 어떻게 새로운 것들을 만들고 등록하는지를 포함합니다.

버전 3.4에서 변경: 이전 버전의 파이썬에서, 파인더가 로더 를 직접 돌려주었지만, 이제는 로더를 포함하고 있는 모듈 스펙을 돌려줍니다. 임포트 도중 로더가 아직 사용되기는 하지만 그 역할은 축소되었습니다.

5.3.3. 임포트 훅(import hooks)

임포트 절차는 확장할 수 있도록 설계되었습니다; 일차적인 메커니즘은 임포트 훅(import hook) 입니다. 두 가지 종류의 임포트 훅이 있습니다: 메타 훅(meta hook) 과 임포트 경로 훅(import path hook).

메타 훅은 임포트 처리의 처음에, sys.modules 캐시 조회를 제외한 다른 임포트 처리들이 시작되기 전에 호출됩니다. 이것은 메타 훅이 sys.path 처리, 프로즌 모듈, 내장 모듈들을 재정의할 수 있게 합니다. 다음에 설명하듯이, 메타 훅은 sys.meta_path 에 새 파인더 객체를 추가하는 방법으로 등록할 수 있습니다.

임포트 경로 훅은 sys.path (혹은 package.__path__) 처리 일부로, 관련된 경로 항목을 만나는 시점에 호출됩니다. 다음에 설명하듯이, 임포트 경로 훅은 sys.path_hooks 에 새 콜러블을 추가하는 방법으로 등록할 수 있습니다.

5.3.4. 메타 경로(meta path)

주어진 이름의 모듈을 sys.modules 에서 찾을 수 없을 때, 파이썬은 sys.meta_path 를 검색하는데, 메타 경로 파인더 객체들의 목록을 포함하고 있습니다. 이 파인더들이 주어진 이름의 모듈을 처리하는 방법을 알고 있는지 확인하도록 요청합니다. 메타 경로 파인더들은 find_spec() 라는 이름의 메서드를 구현해야만 하는데, 세 개의 인자를 받아들입니다: 이름, 임포트 경로, (생략 가능한) 타깃(target) 모듈. 메타 경로 파인더는 주어진 이름의 모듈을 처리할 수 있는지를 결정하기 위해 어떤 전략이건 사용할 수 있습니다.

만약 메타 경로 파인더가 주어진 이름의 모듈을 처리하는 법을 안다면, 스펙 객체를 돌려줍니다. 그럴 수 없다면 None 을 돌려줍니다. 만약 sys.meta_path 처리가 스펙을 돌려주지 못하고 목록의 끝에 도달하면, ModuleNotFoundError 를 일으킵니다. 발생하는 다른 예외들은 그냥 확산시키고, 임포트 프로세스를 중단합니다.

메타 경로 파인더의 find_spec() 메서드는 두 개나 세 개의 인자로 호출됩니다. 첫 번째 인자는 모듈의 완전히 정규화된 이름(fully qualified name)입니다, 예를 들어 foo.bar.baz. 두 번째 인자는 모듈 검색에 사용할 경로 엔트리입니다. 최상위 모듈이 경우 두 번째 인자는 None 이지만, 서브 모듈이나 서브 패키지의 경우 두 번째 인자는 부모 패키지의 __path__ 어트리뷰트 값입니다. 만약 적절한 __path__ 어트리뷰트를 참조할 수 없으면 ModuleNotFoundError 를 일으킵니다. 세 번째 인자는 이미 존재하는 모듈 객체인데, 뒤에서 로딩할 대상이 됩니다. 임포트 시스템은 다시 로드(reload)할 때만 타깃을 전달합니다.

메타 경로는 한 번의 임포트 요청에 대해 여러 번 탐색 될 수 있습니다. 예를 들어, 대상 모듈들이 아무것도 캐싱 되지 않았다고 할 때, foo.bar.baz 를 임포트 하려면, 먼저 각 메타 경로 파인더 (mpf)들에 대해 mpf.find_spec("foo", None, None) 를 호출해서 최상위 임포트를 수행합니다. foo 가 임포트 된 후에, 메타 경로를 두 번째 탐색해서 foo.bar 를 임포트 하는데, mpf.find_spec("foo.bar", foo.__path__, None) 를 호출합니다. 일단 foo.bar 가 임포트 되면, 마지막 탐색은 mpf.find_spec("foo.bar.baz", foo.bar.__path__, None) 를 호출합니다.

어떤 메타 경로 파인더들은 오직 최상위 임포트만 지원합니다. 이런 임포터들은 두 번째 인자로 None 이 아닌 것이 오면 항상 None 을 돌려줍니다.

파이썬의 기본 sys.meta_path 는 세 개의 메타 경로 파인더를 갖고 있습니다. 하나는 내장 모듈을 임포트하는 법을 알고, 하나는 프로즌 모듈을 임포트하는 법을 알고, 하나는 임포트 경로 에서 모듈을 임포트하는 법을 압니다(즉 경로 기반 파인더).

버전 3.4에서 변경: 메타 경로 파인더의 find_spec() 메서드가 이제 폐지된 find_module() 을 대체합니다. 변경 없이도 동작하기는 하지만, 임포트 절차는 파인더가 find_spec() 을 구현하지 않았을 때만 find_module() 을 사용합니다.

5.4. 로딩(loading)

모듈 스펙이 발견되면, 임포트 절차는 모듈을 로딩할 때 그것(그것이 가진 로더도)을 사용합니다. 여기에 임포트의 로딩 과정 동안 일어나는 일에 대한 대략적인 그림이 있습니다:

module = None
if spec.loader is not None and hasattr(spec.loader, 'create_module'):
    # It is assumed 'exec_module' will also be defined on the loader.
    module = spec.loader.create_module(spec)
if module is None:
    module = ModuleType(spec.name)
# The import-related module attributes get set here:
_init_module_attrs(spec, module)

if spec.loader is None:
    if spec.submodule_search_locations is not None:
        # namespace package
        sys.modules[spec.name] = module
    else:
        # unsupported
        raise ImportError
elif not hasattr(spec.loader, 'exec_module'):
    module = spec.loader.load_module(spec.name)
    # Set __loader__ and __package__ if missing.
else:
    sys.modules[spec.name] = module
    try:
        spec.loader.exec_module(module)
    except BaseException:
        try:
            del sys.modules[spec.name]
        except KeyError:
            pass
        raise
return sys.modules[spec.name]

다음과 같은 세부 사항에 주의해야 합니다:

만약 주어진 이름의 모듈이 sys.modules 에 있다면, 임포트는 이미 그걸 돌려줄 겁니다.

로더가 모듈을 실행하기 전에 모듈은 sys.modules 에 자리를 잡습니다. 이것은 필수적인데 모듈이 (직접적 혹은 간접적으로) 자신을 임포트 할 수 있기 때문입니다; 먼저 sys.modules 에 추가함으로써 최악의 상황에 제한 없는 재귀(recursion)를 방지하고, 최선의 상황에 여러 번 로딩되는 것을 막습니다.

로딩이 실패하면, 실패한 모듈(오직 실패한 모듈만)은 sys.modules 에서 삭제됩니다. sys.modules 캐시에 이미 있는 모듈과 부수적 효과로 성공적으로 로딩된 모듈들은 캐시에 남아있어야만 합니다. 이는 실패한 모듈조차 sys.modules 에 남아있게 되는 리로딩과 대비됩니다.

모듈이 만들어졌지만, 아직 실행되기 전에, 뒤의 섹션 에서 요약되듯이, 임포트 절차는 임포트 관련 모듈 어트리뷰트들을 설정합니다(위의 의사 코드 예에서 “_init_module_attrs”).

모듈 실행은 로딩에서 모듈의 이름 공간이 채워지는 결정적 순간입니다. 실행은 전적으로 로더에 위임되는데, 로더가 어떤 것이 어떻게 채워져야 하는지 결정합니다.

로딩 동안 만들어지고 exec_module() 로 전달되는 모듈은 임포트의 끝에 반환되는 것이 아닐 수 있습니다 2.

버전 3.4에서 변경: 임포트 시스템이 기초 공사에 대한 로더의 책임을 들고 갔습니다. 이것들은 전에는 importlib.abc.Loader.load_module() 메서드에서 수행되었습니다.

5.4.1. 로더

모듈 로더는 로딩의 결정적인 기능을 제공합니다: 모듈 실행. 임포트 절차는 하나의 인자로 importlib.abc.Loader.exec_module() 메서드를 호출하는데, 실행할 모듈 객체가 전달됩니다. exec_module() 이 돌려주는 값은 무시됩니다.

로더는 다음과 같은 요구 조건들을 만족해야 합니다:

만약 모듈이 파이썬 모듈(내장 모듈이나 동적으로 로딩되는 확장이 아니라)이면, 로더는 모듈의 코드를 모듈의 전역 이름 공간(module.__dict__)에서 실행해야 합니다.

만약 로더가 모듈을 실행하지 못하면, ImportError 를 일으켜야 합니다. 하지만 exec_module() 동안 발생하는 다른 예외도 전파됩니다.

많은 경우에, 파인더와 로더는 같은 객체입니다; 그런 경우 find_spec() 메서드는 로더가 self 로 설정된 스펙을 돌려줍니다.

모듈 로더는 create_module() 메서드를 구현함으로써 로딩하는 동안 모듈 객체를 만드는 일에 개입할 수 있습니다. 하나의 인자, 모듈 스펙, 을 받아들이고 로딩 중 사용할 모듈 객체를 돌려줍니다. create_module() 은 모듈 객체의 어트리뷰트를 설정할 필요는 없습니다. 만약 메서드가 None 을 돌려주면, 임포트 절차는 새 모듈을 스스로 만듭니다.

버전 3.4에 추가: 로더의 create_module() 메서드.

버전 3.4에서 변경: load_module() 메서드는 exec_module() 로 대체되었고, 임포트 절차가 로딩의 공통 코드(boilerplate)에 대한 책임을 집니다.

이미 존재하는 로더들과의 호환을 위해, 임포트 절차는 load_module() 메서드가 존재하고, exec_module() 을 구현하지 않았으면 load_module() 을 사용합니다. 하지만 load_module() 은 폐지되었습니다. 로더는 대신 exec_module() 를 구현해야 합니다.

load_module() 메서드는 모듈을 실행하는 것 외에 위에서 언급한 모든 공통(boilerplate) 로딩 기능을 구현해야만 합니다. 같은 제약들이 모두 적용되는데, 추가적인 설명을 붙여보면:

만약 sys.modules 에 주어진 이름의 모듈 객체가 이미 존재하면, 로더는 반드시 그 객체를 사용해야 합니다. (그렇지 않으면, importlib.reload() 이 올바로 동작하지 않게 됩니다.) 만약 sys.modules 에 주어진 이름의 모듈이 없으면, 로더는 새 모듈객체를 만들고 sys.modules 에 추가해야 합니다.

제한 없는 재귀와 여러 번 로딩되는 것을 방지하기 위해, 로더가 모듈 코드를 실행하기 전에 모듈이 sys.modules 에 존재해야 합니다.

만약 로딩이 실패하면, 로더는 sys.modules 에 삽입한 모듈들을 제거해야 하는데, 실패한 모듈만을 제거해야 하고, 로더가 그 모듈을 직접 명시적으로 로드한 경우에만 그래야 합니다.

버전 3.5에서 변경: exec_module() 이 정의되었지만 create_module() 이 정의되지 않으면 DeprecationWarning 이 발생합니다.

버전 3.6에서 변경: exec_module() 이 정의되었지만 create_module() 이 정의되지 않으면 ImportError 를 일으킵니다.

5.4.2. 서브 모듈

어떤 메커니즘으로든 (예를 들어, importlib API들, import 나 import-from 문, 내장 __import__()) 서브 모듈이 로드될 때, 서브 모듈 객체로의 연결은 부모 모듈의 이름 공간에 이루어집니다. 예를 들어, 패키지 spam 이 서브 모듈 foo 를 가지면, spam.foo 를 임포트 한 후에는 spam 이 서브 모듈에 연결된 어트리뷰트 foo 를 갖게 됩니다. 다음과 같은 디렉터리 구조로 되어 있다고 합시다:

spam/
    __init__.py
    foo.py
    bar.py

그리고 spam/__init__.py 가 다음과 같은 줄들을 포함한다고 합시다:

from .foo import Foo
from .bar import Bar

그러면 다음과 같이 실행하면 spam 모듈에 foo 와 bar 에 대한 이름 연결이 일어납니다.

>>> import spam
>>> spam.foo
<module 'spam.foo' from '/tmp/imports/spam/foo.py'>
>>> spam.bar
<module 'spam.bar' from '/tmp/imports/spam/bar.py'>

파이썬의 익숙한 이름 연결 규칙에서 볼 때 의외의 결과로 보일 수 있습니다. 하지만 실제로는 임포트 시스템의 근본적인 기능입니다. 불변의 규칙은 이렇습니다: 만약 sys.modules['spam'] 과 sys.modules['spam.foo'] 가 있다면 (위의 임포트 이후의 상태가 그러합니다), 뒤에 있는 것은 반드시 앞에 있는 것의 foo 어트리뷰트가 되어야 합니다.

5.4.3. 모듈 스펙

임포트 절차는 임포트 동안 각 모듈에 대한 다양한 정보들을 사용합니다, 특히 로딩 전에. 대부분 정보는 모든 모듈의 공통이다. 모듈 스펙의 목적은 이 임포트 관련 정보를 모듈별로 요약하는 것입니다.

임포트 동안 스펙을 사용하면 상태가 임포트 시스템의 구성 요소들로 전달될 수 있습니다, 예를 들어 모듈 스펙을 만드는 파인더와 그것을 실행하는 로더 간에. 가장 중요한 것은, 임포트 절차가 로딩의 공통 연산(boilerplate operation)을 수행할 수 있도록 하는 것입니다. 모듈 스펙이 없다면 로더가 모든 책임을 지게 됩니다.

모듈의 스펙은 모듈 객체의 __spec__ 어트리뷰트로 노출됩니다. 모듈 스펙의 내용에 대한 세부 사항은 ModuleSpec 을 보세요.

버전 3.4에 추가.

5.4.4. 임포트 관련 모듈 어트리뷰트

임포트 절차는 로딩하는 동안 로더가 모듈을 실행하기 전에 모듈의 스팩에 기초해서 각 모듈 객체에 이 어트리뷰트들을 채워 넣습니다.

__name__

__name__ 어트리뷰트는 모듈의 완전히 정규화된(fully-qualified) 이름으로 설정되어야 합니다. 이 이름은 임포트 시스템이 모듈을 유일하게(uniquely) 식별하는 데 사용됩니다.

__loader__

__loader__ 어트리뷰트는 모듈을 로드할 때 임포트 절차가 사용한 로더 객체로 설정되어야 합니다. 이것은 주로 인트로스펙션(introspection)을 위한 것이지만, 추가적인 로더에 국한된 기능들을 위한 것이기도 합니다, 예를 들어 로더와 결합한 데이터를 얻는 것이 있습니다.

__package__

모듈의 __package__ 어트리뷰트는 반드시 설정되어야 합니다. 값은 문자열이어야 하는데, __name__ 과 같은 값일 수 있습니다. 모듈이 패키지일 때, __package__ 값은 __name__ 으로 설정되어야 합니다. 모듈이 패키지가 아닐 때, 최상위 모듈이면 빈 문자열로 설정되고, 서브 모듈이면 부모 패키지의 이름으로 설정되어야 합니다. 더 상세한 내용은 PEP 366 [https://www.python.org/dev/peps/pep-0366] 을 참조하세요.

PEP 366 [https://www.python.org/dev/peps/pep-0366] 에 정의되어 있듯이, 메인 모듈에서 명시적인 상대 임포트를 계산할 때, __name__ 대신, 이 어트리뷰트가 사용됩니다. __spec__.parent 과 같은 값일 것으로 기대됩니다.

버전 3.6에서 변경: __package__ 의 값이 __spec__.parent 과 같을 것으로 기대됩니다.

__spec__

__spec__ 어트리뷰트는 모듈을 임포트 할 때 사용한 모듈 스펙으로 설정되어야 합니다. __spec__ 을 적절히 설정하는 것은 인터프리터가 구동되는 동안 초기화되는 모듈들 에도 마찬가지로 적용됩니다. 한가지 예외는 __main__ 인데, 어떤 경우에 __spec__ 이 어떤 경우에 None 으로 설정됩니다.

__package__ 가 정의되지 않으면, 대체물로 __spec__.parent 가 사용됩니다.

버전 3.4에 추가.

버전 3.6에서 변경: __package__ 가 정의되지 않으면, 대체물로 __spec__.parent 가 사용됩니다.

__path__

모듈이 패키지면 (정규 또는 이름 공간), 모듈 객체의 __path__ 어트리뷰트가 반드시 설정되어야 합니다. 값은 이터러블이어야 하는데, __path__ 가 더는 의미가 없으면 빈 이터러블일 수 있습니다. 만약 __path__ 가 비어있지 않다면, 탐색할 때 문자열을 제공해야 합니다. __path__ 의 의미에 관한 자세한 내용은 아래에 나옵니다.

패키지가 아닌 모듈은 __path__ 어트리뷰트가 없어야 합니다.

__file__

__cached__

__file__ 은 생략될 수 있다. 만약 설정되면, 이 어트리뷰트의 값은 문자열이어야 합니다. 임포트 시스템은 의미가 없을 때(예를 들어 데이터베이스에서 로드된 모듈) __file__ 을 설정하지 않을 수 있습니다.

만약 __file__ 이 설정되면, __cached__ 역시 설정하는 것이 적절할 수 있는데, 코드의 컴파일된 버전(예를 들어, 바이트 컴파일된 파일)을 가리키는 경로입니다. 이 어트리뷰트를 설정하기 위해 파일이 꼭 존재해야 할 필요는 없습니다; 경로는 단순히 컴파일된 파일이 있어야 할 곳을 가리킬 수 있습니다(PEP 3147 [https://www.python.org/dev/peps/pep-3147] 을 보세요).

__file__ 이 설정되지 않을 때도, __cached__ 를 설정하는 것이 적절할 수 있습니다. 하지만, 그런 시나리오는 아주 예외적입니다. 궁극적으로, 로더가 __file__ 이나 __cached__ 혹은 둘 모두를 사용합니다. 그래서 로더가 캐싱된 모듈을 로드할 수는 있지만, 파일로부터 직접 로드할 수 없다면, 예외적인 시나리오가 적절할 수 있습니다.

5.4.5. module.__path__

정의에 따르면, 모듈에 __path__ 어트리뷰트가 있으면, 이 모듈은 패키지입니다.

패키지의 __path__ 어트리뷰트는 서브 패키지를 로딩할 때 사용합니다. 임포트 절차 내에서, 임포트하는 동안 모듈을 검색할 위치들의 목록을 제공한다는 점에서 sys.path 와 같은 기능을 갖습니다. 하지만 __path__ 는 보통 sys.path 보다 제약 조건이 많습니다.

__path__ 는 문자열의 이터러블이지만, 비어있을 수 있습니다. sys.path 과 같은 규칙이 패키지의 __path__ 에도 적용되고, 패키지의 __path__ 를 탐색하는 동안 sys.path_hooks (아래에서 설명한다)에게 의견을 묻습니다.

패키지의 __init__.py 파일은 패키지의 __path__ 어트리뷰트를 설정하거나 변경할 수 있고, 이것이 PEP 420 [https://www.python.org/dev/peps/pep-0420] 이전에 이름 공간 패키지를 구현하는 방법으로 사용됐습니다. PEP 420 [https://www.python.org/dev/peps/pep-0420] 의 도입으로 인해, 이름 공간 패키지가 __path__ 조작 코드만을 포함하는 __init__.py 파일을 제공할 필요가 없어졌습니다; 임포트 절차가 자동으로 이름 공간 패키지를 위한 __path__ 를 설정합니다.

5.4.6. 모듈 repr

기본적으로, 모든 모듈은 사용할만한 repr 을 갖고 있습니다. 하지만 위의 어트리뷰트들과 모듈 스펙에 있는 것들에 따라, 모듈 객체의 repr 을 좀 더 명시적으로 제어할 수 있습니다.

모듈이 스펙(__spec__)을 가지면, 임포트 절차는 그것으로부터 repr 을 만들려고 시도합니다. 그것이 실패하거나 스펙이 없으면, 임포트 시스템은 모듈에서 제공되는 것들로 기본 repr 을 구성합니다. module.__name__, module.__file__, module.__loader__ 을 repr 의 입력으로 사용하려고 시도하는데, 빠진 정보는 기본값으로 채웁니다.

사용되고 있는 정확한 규칙은 이렇습니다:

모듈이 __spec__ 어트리뷰트를 가지면, 스펙에 있는 정보로 repr 을 생성합니다. “name”, “loader”, “origin”, “has_location” 어트리뷰트들이 사용됩니다.

모듈이 __file__ 어트리뷰트를 가지면, 모듈의 repr 의 일부로 사용됩니다.

모듈이 __file__ 어트리뷰트를 갖지 않지만 None 이 아닌 __loader__ 를 가지면, 로더의 repr 이 모듈의 repr 의 일부로 사용됩니다.

그렇지 않으면, repr 에 모듈의 __name__ 을 사용합니다.

버전 3.4에서 변경: loader.module_repr() 의 사용이 폐지되었고 이제 모듈 repr 를 만드는데 임포트 절차에 의해 모듈 스펙이 사용됩니다.

파이썬 3.3과의 과거 호환성을 위해, 위에서 설명한 방법들을 시도하기 전에, 만약 정의되어 있으면, 로더의 module_repr() 메서드를 호출해서 모듈 repr 을 만듭니다. 하지만, 그 메서드는 폐지되었습니다.

5.4.7. 캐시된 바이트 코드 무효화

Before Python loads cached bytecode from .pyc file, it checks whether the cache is up-to-date with the source .py file. By default, Python does this by storing the source’s last-modified timestamp and size in the cache file when writing it. At runtime, the import system then validates the cache file by checking the stored metadata in the cache file against the source’s metadata.

파이썬은 또한 “해시 기반” 캐시 파일을 지원하는데, 캐시 파일은 메타 데이터 대신에 소스 파일의 내용 해시를 저장합니다. 해시 기반 .pyc 파일에는 두 가지 변종이 있습니다: 검사형(checked)과 비검사형(unchecked). 검사형 해시 기반 .pyc 파일의 경우, 파이썬은 소스 파일을 해시하고 결과 해시를 캐시 파일의 해시와 비교하여 캐시 파일의 유효성을 검사합니다. 검사형 해시 기반 캐시 파일이 유효하지 않은 것으로 판명되면, 파이썬은 캐시 파일을 다시 생성하고 새로운 검사형 해시 기반 캐시 파일을 만듭니다. 비검사형 해시 기반 .pyc 파일의 경우, 파이썬은 단순히 캐시 파일이 존재할 경우 유효하다고 가정합니다. 해시 기반 .pyc 파일 유효성 검사 동작은 --check-hash-based-pycs 플래그로 재정의될 수 있습니다.

버전 3.7에서 변경: 해시 기반 .pyc 파일을 추가했습니다. 이전에는, 파이썬은 바이트 코드 캐시의 타임스탬프 기반 무효화만 지원했습니다.

5.5. 경로 기반 파인더

앞에서 언급했듯이, 파이썬은 여러 기본 메타 경로 파인더들을 갖고 있습니다. 이 중 하나는, 경로 기반 파인더 (PathFinder) 로 불리는데, 경로 엔트리 들의 목록을 담고 있는 임포트 경로 를 검색합니다. 각 경로 엔트리는 모듈을 찾을 곳을 가리킵니다.

경로 기반 파인더 자신은 뭔가를 임포트하는 법에 대해서는 아는 것이 없습니다. 대신에, 각 경로 엔트리를 탐색하면서, 각각을 구체적인 경로 엔트리를 다루는 법을 아는 경로 엔트리 파인더와 관련시킵니다.

경로 엔트리 파인더의 기본 집합은 파일 시스템에서 모듈을 찾는데 필요한 모든 개념을 구현하는데, 파이썬 소스 코드(.py 파일들), 파이썬 바이트 코드(.pyc 파일들), 공유 라이브러리(예를 들어 .so 파일들)와 같은 특수 파일형들을 처리합니다. 표준라이브러리의 zipimport 모듈의 지원을 받으면, 기본 경로 엔트리 파인더는 이 모든 파일(공유 라이브러리를 제외한 것들)을 zip 파일들로부터 로딩합니다.

경로 엔트리가 파일 시스템의 위치로 제한될 필요는 없습니다. URL이나 데이터베이스 조회나 문자열로 지정될 수 있는 어떤 위치도 가능합니다.

경로 기반 파인더는 검색 가능한 경로 엔트리의 유형을 확장하고 커스터마이즈할 수 있도록 하는 추가의 훅과 프로토콜을 제공합니다. 예를 들어, 네트워크 URL을 경로 엔트리로 지원하고 싶다면, 웹에서 모듈을 찾는 HTTP 개념을 구현하는 훅을 작성할 수 있습니다. 이 훅 (콜러블)은 아래에서 설명하는 프로토콜을 지원하는 경로 엔트리 파인더 를 돌려주는데, 웹에 있는 모듈을 위한 로더를 얻는 데 사용됩니다.

경고의 글: 이 섹션과 앞에 나온 것들은 모두 파인더라는 용어를 사용하는데, 메타 경로 파인더 와 경로 엔트리 파인더 라는 용어를 사용해서 구분합니다. 이 두 종류의 파인더는 매우 유사해서 비슷한 프로토콜을 지원하고 임포트 절차에서 비슷한 방식으로 기능합니다. 하지만 이것들이 미묘하게 다르다는 것을 기억하는 것이 중요합니다. 특히, 메타 경로 파인더는 임포트 절차의 처음에 개입하는데, sys.meta_path 탐색을 통해 들어옵니다.

반면에, 경로 엔트리 파인더는 경로 기반 파인더의 구현 상세인데, 사실 경로 기반 파인더가 sys.meta_path 로 부터 제거되면, 경로 엔트리 파인더의 개념은 일절 호출되지 않습니다.

5.5.1. 경로 엔트리 파인더

경로 기반 파인더 는 위치가 문자열 경로 엔트리 로 지정된 파이썬 모듈과 패키지를 찾고 로드하는 책임을 집니다. 대부분의 경로 엔트리는 파일 시스템의 위치를 가리키지만, 이것으로 한정될 필요는 없습니다.

메타 경로 파인더로서, 경로 기반 파인더 는 앞에서 설명한 find_spec() 프로토콜을 구현합니다. 하지만 모듈이 임포트 경로 에서 어떻게 발견되고 로드되는지는 커스터마이즈하는데 사용될 수 있는 추가의 훅을 제공합니다.

경로 기반 파인더 는 세 개의 변수를 사용합니다, sys.path, sys.path_hooks, sys.path_importer_cache. 패키지 객체의 __path__ 어트리뷰트 또한 사용된다. 이것들은 임포트 절차를 커스터마이즈할 수 있는 추가의 방법을 제공합니다.

sys.path 는 모듈과 패키지의 검색 위치를 제공하는 문자열의 목록을 포함합니다. PYTHONPATH 환경 변수와 여러 가지 설치와 구현 특정 기본값들로부터 초기화됩니다. sys.path 에 있는 엔트리들은 파일 시스템의 디렉터리와 zip 파일을 가리키고, 그밖에 잠재적으로 모듈 검색에 사용될 수 있는 “장소들”(site 모듈을 보라)을 가리킬 수 있는데, URL이나 데이터베이스 조회 같은 것들입니다. sys.path 에는 문자열과 바이트열만 있어야 합니다; 다른 모든 형은 무시됩니다. 바이트열의 인코딩은 개별 경로 엔트리 파인더 들에 의해 결정됩니다.

경로 기반 파인더 는 메타 경로 파인더 이기 때문에, 앞에서 설명했듯이 임포트 절차는 경로 기반 파인더의 find_spec() 메서드를 호출하는 것으로 임포트 경로 검색을 시작합니다. find_spec() 에 제공되는 path 인자는 탐색할 문자열 경로들의 리스트입니다 - 보통 패키지 내에서 임포트 하면 패키지의 __path__ 어트리뷰트. path 인자가 None 이면, 최상위 임포트를 뜻하고 sys.path 가 사용됩니다.

경로 기반 파인더는 검색 경로의 모든 엔트리를 탐색하고, 개별 엔트리마다 적절한 경로 엔트리 파인더 (PathEntryFinder)를 찾습니다. 이것은 비용이 많이 드는 연산일 수 있으므로(예를 들어, 이 검색을 위해 stat() 호출로 인한 부하가 있을 수 있습니다), 경로 기반 파인더는 경로 엔트리를 경로 엔트리 파인더로 매핑하는 캐시를 관리합니다. 이 캐시는 sys.path_importer_cache 에 유지됩니다 (이름에도 불구하고, 이 캐시는 임포터 객체로 제한되지 않고 실제로는 파인더 객체를 저장합니다). 이런 방법으로, 특정 경로 엔트리 위치의 경로 엔트리 파인더 의 비싼 검색은 오직 한 번만 수행됩니다. 사용자 코드가 sys.path_importer_cache 의 캐시 엔트리를 삭제해서 경로 기반 파인더가 그 경로 엔트리를 다시 검색하도록 하는 것이 허락됩니다 3.

경로 엔트리가 캐시에 없으면, 경로 기반 파인더는 sys.path_hooks 에 있는 모든 콜러블들을 탐색합니다. 이 목록의 각 경로 엔트리 훅 은 검색할 경로 엔트리 인자 한 개를 사용해서 호출됩니다. 이 콜러블은 경로 엔트리를 다룰 수 있는 경로 엔트리 파인더 를 돌려주거나, ImportError 를 발생시킬 수 있습니다. ImportError 는 경로 기반 파인더가 어떤 훅이 주어진 경로 엔트리 를 위한 경로 엔트리 파인더 를 발견할 수 없음을 알리는 데 사용합니다. 이 예외는 무시되고 임포트 경로 탐색은 계속됩니다. 훅은 문자열이나 바이트열을 기대해야 합니다; 바이트열의 인코딩은 훅이 결정하고(예를 들어, 파일 시스템 인코딩이나 UTF-8 이나 그 밖의 다른 것일 수 있습니다), 만약 훅이 인자를 디코딩할 수 없으면 ImportError 를 일으켜야 합니다.

만약 sys.path_hooks 탐색이 아무런 경로 엔트리 파인더 를 돌려주지 못하면, 경로 기반 파인더의 find_spec() 메서드는 sys.path_importer_cache 에 None 을 저장하고(이 경로 엔트리를 위한 파인더가 없음을 가리키기 위해), None 을 돌려줘서 이 메타 경로 파인더 가 모듈을 찾을 수 없음을 알립니다.

만약 sys.path_hooks 에 있는 어느 하나의 경로 엔트리 훅 콜러블이 경로 엔트리 파인더 를 돌려주면, 파인더에 모듈 스펙을 요청하기 위해 다음에 나오는 프로토콜이 사용됩니다. 모듈 스펙은 모듈을 로딩할 때 사용됩니다.

현재 작업 디렉터리(current working directory) – 빈 문자열로 표현된다 – 는 sys.path 에 있는 다른 엔트리들과 약간 다르게 취급됩니다. 첫째로, 현재 작업 디렉터리가 존재하지 않음이 발견되면 sys.path_importer_cache 에는 아무런 값도 저장되지 않습니다. 둘째로, 현재 작업 디렉터리는 각 모듈 조회 때마다 다시 확인됩니다. 셋째로, sys.path_importer_cache 에 사용되는 경로와 importlib.machinery.PathFinder.find_spec() 가 돌려주는 경로는 빈 문자열이 아니라 실제 현재 작업 디렉터리가 됩니다.

5.5.2. 경로 엔트리 파인더 프로토콜

모듈과 초기화된 패키지의 임포트를 지원하고 이름 공간 패키지에 포션으로 이바지하기 위해, 경로 엔트리 파인더는 find_spec() 메서드를 구현해야 합니다.

find_spec() takes two arguments: the fully qualified name of the module being imported, and the (optional) target module. find_spec() returns a fully populated spec for the module. This spec will always have “loader” set (with one exception).

To indicate to the import machinery that the spec represents a namespace portion, the path entry finder sets “loader” on the spec to None and “submodule_search_locations” to a list containing the portion.

버전 3.4에서 변경: find_spec() 이 find_loader() 와 find_module() 를 대체하는데, 둘 다 이제 폐지되었습니다, find_spec() 이 정의되지 않으면 이것들을 사용합니다.

예전의 경로 엔트리 파인더는 find_spec() 대신에 이 두 개의 폐지된 메서드들을 구현할 수 있습니다. 이 메서드들은 과거 호환성 때문에 아직도 사용됩니다. 하지만, find_spec() 이 경로 엔트리 파인더에 구현되면, 예전 메서드들은 무시됩니다.

find_loader() 는 하나의 인자를 받아들입니다, 임포트되는 모듈의 완전히 정규화된 이름. find_loader() 는 2-튜플을 돌려주는데, 첫 번째 항목은 로더이고 두 번째 항목은 이름 공간 포션 입니다. 첫 번째 항목(즉 로더)이 None 이면, 경로 엔트리 파인더가 주어진 이름의 모듈에 대한 로더를 제공하지는 못하지만, 경로 엔트리가 주어진 이름의 모듈에 대한 이름 공간 포션에 이바지함을 안다는 뜻입니다. 이것은 거의 항상, 파이썬이 파일 시스템에 물리적으로 존재하지 않는 이름 공간 패키지를 임포트하도록 요구되는 경우입니다. 경로 엔트리 파인더가 로더로 None 을 돌려줄 때, 2-튜플의 두 번째 항목은 시퀀스여야 하는데 비어있을 수도 있습니다.

find_loader() 가 None 이 아닌 로더 값을 돌려주면, 그 포션은 무시되고 경로 기반 파인더가 로더를 돌려주며 경로 엔트리 검색을 종료합니다.

임포트 프로토콜의 다른 구현들과의 과거 호환성을 위해, 많은 경로 엔트리 파인더들은 메타 경로 파인더가 지원하는 것과 같고 전통적인 find_module() 메서드 또한 지원합니다. 하지만 경로 엔트리 파인더 find_module() 메서드는 결코 path 인자로 호출되지 않습니다 (그것들은 경로 훅의 최초 호출 때 적절한 경로 정보를 기록해둘 것으로 기대됩니다).

경로 엔트리 파인더의 find_module() 메서드는 경로 엔트리 파인더가 이름 공간 패키지에 포션으로 이바지하는 것을 허락하지 않기 때문에 폐지되었습니다. 만약 경로 엔트리 파인더에 find_loader() 와 find_module() 이 모두 존재하면, 임포트 시스템은 항상 find_module() 대신 find_loader() 를 호출합니다.

5.6. 표준 임포트 시스템 교체하기

임포트 시스템 전체를 교체하기 위한 가장 신뢰성 있는 메커니즘은 sys.meta_path 의 기본값들을 모두 삭제하고, 새로 만든 메타 경로 훅들로 채우는 것입니다.

만약 임포트 시스템을 액세스하는 다른 API들에 영향을 주지 않고, 단지 임포트 문의 동작만을 변경해도 좋다면, 내장 __import__() 함수를 교체하는 것으로 충분할 수도 있습니다. 이 기법은 특정 모듈 내에서의 임포트 문의 동작만을 변경하도록 모듈 수준에서 적용될 수도 있습니다.

To selectively prevent the import of some modules from a hook early on the meta path (rather than disabling the standard import system entirely), it is sufficient to raise ModuleNotFoundError directly from find_spec() instead of returning None. The latter indicates that the meta path search should continue, while raising an exception terminates it immediately.

5.7. 패키지 상대 임포트

상대 임포트는 선행 점을 사용합니다. 단일 선행 점은 현재 패키지에서 시작하는 상대 임포트를 나타냅니다. 두 개 이상의 선행 점은 현재 패키지의 부모(들)에 대한 상대 임포트를 나타내며, 첫 번째 점 다음의 점 하나당 하나의 수준을 나타냅니다. 예를 들어, 다음과 같은 패키지 배치가 제공될 때:

package/
    __init__.py
    subpackage1/
        __init__.py
        moduleX.py
        moduleY.py
    subpackage2/
        __init__.py
        moduleZ.py
    moduleA.py

subpackage1/moduleX.py나 subpackage1/__init__.py 모두에서, 다음은 유효한 상대 임포트입니다:

from .moduleY import spam
from .moduleY import spam as ham
from . import moduleY
from ..subpackage1 import moduleY
from ..subpackage2.moduleZ import eggs
from ..moduleA import foo

절대 임포트는 import <> 또는 from <> import <> 문법을 사용할 수 있지만, 상대 임포트는 두 번째 형식만 사용할 수 있습니다; 그 이유는:

import XXX.YYY.ZZZ

가 XXX.YYY.ZZZ를 사용할 수 있는 표현식으로 노출하지만, .moduleY는 유효한 표현식이 아니기 때문입니다.

5.8. __main__ 에 대한 특별한 고려

__main__ 모듈은 파이썬의 임포트 시스템에서 특별한 경우입니다. 다른 곳에서 언급했듯이, __main__ 모듈은 sys 와 builtins 처럼 인터프리터 시작 때 직접 초기화됩니다. 하지만, 이 두 개와는 다르게, 이것은 엄밀하게 내장 모듈로 취급되지 않습니다. 이것은 __main__ 이 초기화되는 방식이 인터프리터를 실행할 때 주는 플래그와 다른 옵션들에 영향을 받기 때문입니다.

5.8.1. __main__.__spec__

__main__ 이 어떻게 초기화되는지에 따라, __main__.__spec__ 은 적절히 설정되기도 하고 None 으로 설정되기도 합니다.

파이썬이 -m 옵션으로 시작하면, __spec__ 은 해당하는 모듈이나 패키지의 모듈 스팩으로 설정됩니다. 또한 __spec__ 은 __main__ 모듈이 디렉터리나 zip 파일이나 다른 sys.path 엔트리를 실행하는 일부로 로드될 때 그 내용이 채워집니다.

나머지 경우 에는 __main__.__spec__ 은 None 으로 설정되는데, __main__ 을 채우는데 사용된 코드가 임포트 가능한 모듈에 직접 대응하지 않기 때문입니다:

대화형 프롬프트

-c 옵션

표준 입력으로 실행

소스 파일이나 바이트 코드 파일로부터 직접 실행

마지막 경우에 __main__.__spec__ 이 항상 None 임에 주의해야 합니다. 설사 그 파일이 기술적으로 모듈로 임포트 될 수 있어도 그렇습니다. __main__ 에 올바른 모듈 메타데이터가 필요하다면 -m 스위치를 사용해야 합니다.

또한 __main__ 이 임포트 가능한 모듈에 대응되고, __main__.__spec__ 이 적절히 설정되었다 하더라도, 이 둘은 여전히 다른 모듈로 취급됨에 주의해야 합니다. 이것은 if __name__ == "__main__": 검사로 둘러싸인 블록이 모듈이 __main__ 이름 공간을 채울 때만 실행되고, 일반적인 임포트 때는 실행되지 않는다는 사실 때문입니다.

5.9. 열린 이슈들

XXX 도표가 있으면 정말 좋겠다.

XXX * (import_machinery.rst) 모듈과 패키지의 어트리뷰트들에만 할당된 섹션은 어떨까? 아마도 데이터 모델 레퍼런스 페이지에 있는 관련 항목들을 확장하거나 대체해야 할 것이다.

XXX 라이브러리 설명서의 runpy, pkgutil 등등은 새 임포트 시스템 섹션으로 가는 “See Also” 링크를 처음에 붙여야만 한다.

XXX __main__ 이 초기화되는 다른 방법들에 대한 설명을 더 붙여야 하나?

XXX __main__ 의 까다로움/어려움에 대한 정보를 추가하자 (즉 PEP 395 [https://www.python.org/dev/peps/pep-0395] 의 사본)

5.10. 참고문헌

임포트 절차는 파이썬의 초창기부터 상당히 변해왔습니다. 문서를 작성한 이후에 약간의 세부사항이 변경되었기는 하지만, 최초의 패키지 규격 [https://www.python.org/doc/essays/packages/] 은 아직 읽을 수 있도록 남아있습니다.

sys.meta_path 의 최초 규격은 PEP 302 [https://www.python.org/dev/peps/pep-0302] 이고, 뒤이은 확장은 PEP 420 [https://www.python.org/dev/peps/pep-0420] 입니다.

PEP 420 [https://www.python.org/dev/peps/pep-0420] 은 파이썬 3.3 에 이름 공간 패키지 를 도입했습니다. PEP 420은 find_module() 의 대안으로 find_loader() 프로토콜 역시 도입했습니다.

PEP 366 [https://www.python.org/dev/peps/pep-0366] 은 메인 모듈에서의 명시적인 상태 임포트를 위한 __package__ 어트리뷰트의 추가에 관해 설명하고 있습니다.

PEP 328 [https://www.python.org/dev/peps/pep-0328] 은 절대와 명시적인 상대 임포트들 도입하고 PEP 366 [https://www.python.org/dev/peps/pep-0366] 이 결국 __package__ 를 지정하게 되는 개념을 초기에 __name__ 으로 제안했습니다.

PEP 338 [https://www.python.org/dev/peps/pep-0338] 은 모듈을 스크립트로 실행하는 것을 정의합니다.

PEP 451 [https://www.python.org/dev/peps/pep-0451] 은 스팩 객체에 모듈별 임포트 상태를 요약하는 것을 추가합니다. 로더들에 주어졌던 대부분의 공통 코드 책임들을 임포트 절차로 옮기기도 했습니다. 이 변경은 임포트 시스템의 여러 API 들을 폐지하도록 만들었고, 파인더와 로더에 새 메서드들을 추가하기도 했습니다.

각주

1

types.ModuleType 을 보세요.

2

importlib 구현은 반환 값을 직접 사용하지 않습니다. 대신에, sys.modules 에서 모듈 이름을 조회해서 모듈을 얻습니다. 이것의 간접적인 효과는 임포트되는 모듈이 sys.modules 에 있는 자신을 바꿀 수 있다는 것입니다. 이것은 구현 상세 동작이고 다른 파이썬 구현에서 동작한다고 보장되지 않습니다.

3

예전 코드에서, sys.path_importer_cache 에서 imp.NullImporter 의 인스턴스를 찾는 것이 가능합니다. 코드가 대신 None 을 사용하도록 변경할 것을 권고합니다. 더 자세한 내용은 Porting Python code 를 참조하세요.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 언어 레퍼런스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 언어 레퍼런스 »

|

6. 표현식

이 장은 파이썬에서 사용되는 표현식 요소들의 의미를 설명합니다.

문법 유의 사항: 여기와 이어지는 장에서는, 어휘 분석이 아니라 문법을 설명하기 위해 확장 BNF 표기법을 사용합니다. 문법 규칙이 다음과 같은 형태를 가지고,

name ::=  othername

뜻(semantics)을 주지 않으면, 이 형태의 name 의 뜻은 othername 과 같습니다.

6.1. 산술 변환

When a description of an arithmetic operator below uses the phrase “the numeric arguments are converted to a common type”, this means that the operator implementation for built-in types works as follows:

어느 한 인자가 복소수면 다른 하나는 복소수로 변환됩니다;

그렇지 않고, 어느 한 인자가 실수면, 다른 하나는 실수로 변환됩니다;

그렇지 않으면, 두 인자는 모두 정수여야 하고, 변환은 필요 없습니다.

어떤 연산자들(예를 들어, ‘%’ 연산자의 왼쪽 인자로 주어지는 문자열)에 대해서는 몇 가지 추가의 규칙이 적용됩니다. 확장(extension)은 그들 자신의 변환 규칙을 정의해야 합니다.

6.2. 아톰 (Atoms)

아톰은 표현식의 가장 기본적인 요소입니다. 가장 간단한 아톰은 식별자와 리터럴입니다. 괄호, 대괄호, 중괄호로 둘러싸인 형태도 문법적으로 아톰으로 분류됩니다. 아톰의 문법은 이렇습니다:

atom      ::=  identifier | literal | enclosure
enclosure ::=  parenth_form | list_display | dict_display | set_display
               | generator_expression | yield_atom

6.2.1. 식별자 (이름)

아톰으로 등장하는 식별자는 이름입니다. 어휘 정의에 대해서는 식별자와 키워드 섹션을, 이름과 연결에 대한 문서는 이름과 연결(binding) 섹션을 보세요.

이름이 객체에 연결될 때, 아톰의 값을 구하면 객체가 나옵니다. 이름이 연결되지 않았을 때, 값을 구하려고 하면 NameError 예외가 일어납니다.

비공개 이름 뒤섞기(private name mangling): 클래스 정의에 등장하는 식별자가 두 개나 그 이상의 밑줄로 시작하고, 두 개나 그 이상의 밑줄로 끝나지 않으면, 그 클래스의 비공개 이름(private name) 으로 간주합니다. 비공개 이름은 그 들을 위한 코드가 만들어지기 전에 더 긴 형태로 변환됩니다. 이 변환은 그 이름의 앞에 클래스 이름을 삽입하는데, 클래스 이름의 처음에 오는 모든 밑줄을 제거한 후, 하나의 밑줄을 추가합니다. 예를 들어, Ham 이라는 이름의 클래스에 식별자 __spam 이 등장하면, _Ham__spam 으로 변환됩니다. 이 변환은 식별자가 사용되는 문법적인 문맥에 무관합니다. 변환된 이름이 극단적으로 길면(255자보다 길면), 구현이 정의한 잘라내기가 발생할 수 있습니다. 클래스 이름이 밑줄로만 구성되어 있으면, 변환은 일어나지 않습니다.

6.2.2. 리터럴 (Literals)

파이썬은 문자열과 바이트열 리터럴과 여러 가지 숫자 리터럴들을 지원합니다:

literal ::=  stringliteral | bytesliteral
             | integer | floatnumber | imagnumber

리터럴의 값을 구하면 주어진 형(문자열, 바이트열, 정수, 실수, 복소수)과 주어진 값을 갖는 객체가 나옵니다. 실수와 복소수의 경우는 근삿값일 수 있습니다. 자세한 내용은 리터럴 섹션을 보세요.

모든 리터럴은 불변 데이터형에 대응하기 때문에, 객체의 아이덴티티는 값 보다 덜 중요합니다. 같은 값의 리터럴에 대해 반복적으로 값을 구하면 (프로그램 텍스트의 같은 장소에 있거나 다른 장소에 있을 때) 같은 객체를 얻을 수도 있고, 같은 값의 다른 객체를 얻을 수도 있습니다.

6.2.3. 괄호 안에 넣은 형

괄호 안에 넣은 형은, 괄호로 둘러싸인 생략 가능한 표현식 목록입니다:

parenth_form ::=  "(" [starred_expression] ")"

괄호 안에 넣은 표현식 목록은, 무엇이건 그 표현식 목록이 산출하는 것이 됩니다: 목록이 적어도 하나의 쉼표를 포함하면, 튜플이 됩니다; 그렇지 않으면 표현식 목록을 구성한 단일 표현식이 됩니다.

빈 괄호 쌍은 빈 튜플 객체를 만듭니다. 튜플은 불변이기 때문에 리터럴에서와 같은 규칙이 적용됩니다 (즉, 두 개의 빈 튜플은 같은 객체일 수도 있고 그렇지 않을 수도 있습니다).

튜플이 괄호에 의해 만들어지는 것이 아니라, 쉼표 연산자의 사용 때문이라는 것에 주의해야 합니다. 예외는 빈 튜플인데, 괄호가 필요합니다 — 표현식에서 괄호 없는 “없음(nothing)”을 허락하는 것은 모호함을 유발하고 자주 발생하는 오타들이 잡히지 않은 채로 남게 할 것입니다.

6.2.4. 리스트, 집합, 딕셔너리의 디스플레이(display)

리스트, 집합, 딕셔너리를 구성하기 위해, 파이썬은 “디스플레이(displays)”라고 부르는 특별한 문법을 각기 두 가지 스타일로 제공합니다:

컨테이너의 내용을 명시적으로 나열하거나,

일련의 루프와 필터링 지시들을 통해 계산되는데, 컴프리헨션 (comprehension) 이라고 불립니다.

컴프리헨션의 공통 문법 요소들은 이렇습니다:

comprehension ::=  expression comp_for
comp_for      ::=  ["async"] "for" target_list "in" or_test [comp_iter]
comp_iter     ::=  comp_for | comp_if
comp_if       ::=  "if" expression_nocond [comp_iter]

컴프리헨션은 하나의 표현식과 그 뒤를 따르는 최소한 하나의 for 절과 없거나 여러 개의 for 또는 if 절로 구성됩니다. 이 경우, 새 컨테이너의 요소들은 각 for 또는 if 절이 왼쪽에서 오른쪽으로 중첩된 블록을 이루고, 가장 안쪽에 있는 블록에서 표현식의 값을 구해서 만들어낸 것들입니다.

하지만, 가장 왼쪽의 for 절에 있는 이터러블 표현식을 제외하고는, 컴프리헨션은 묵시적으로 중첩된 스코프에서 실행됩니다. 이렇게 해서 target_list 에서 대입되는 이름이 둘러싸는 스코프로 “누수” 되지 않도록 합니다.

가장 왼쪽의 for 절의 이터러블 표현식은, 둘러싸는 스코프에서 직접 평가된 다음, 묵시적으로 중첩된 스코프로 인자로 전달됩니다. 뒤따르는 for 절과 가장 왼쪽 for 절의 모든 필터 조건은, 가장 왼쪽 이터러블에서 얻은 값에 따라 달라질 수 있으므로 둘러싸는 스코프에서 평가할 수 없습니다. 예를 들면, [x*y for x in range(10) for y in range(x, x+10)].

컴프리헨션이 항상 적절한 형의 컨테이너가 되게 하려고, 묵시적으로 중첩된 스코프에서 yield 와 yield from 표현식은 금지됩니다 (Python 3.7에서, 이러한 표현식은 컴파일될 때 DeprecationWarning 을 발생시킵니다. 파이썬 3.8+ 에서는 SyntaxError 를 일으킬 것입니다).

파이썬 3.6부터, async def 함수에서는, 비동기 이터레이터 를 탐색하기 위해 async for 를 사용할 수 있습니다. async def 함수에 있는 컴프리헨션은 처음에 나오는 표현식 뒤에 for 나 async for 절이 올 수 있고, 추가의 for 나 async for 절이 올 수 있고, await 표현식 또한 사용할 수 있습니다. 컴프리헨션이 async for 절이나 await 표현식을 포함하면 비동기 컴프리헨션 (asynchronous comprehension) 이라고 불립니다. 비동기 컴프리헨션은 그것이 등장한 코루틴 함수의 실행을 일시 중지시킬 수 있습니다. PEP 530 [https://www.python.org/dev/peps/pep-0530] 를 참조하세요.

버전 3.6에 추가: 비동기 컴프리헨션이 도입되었습니다.

버전 3.7부터 폐지: yield 와 yield from 은 묵시적으로 중첩된 스코프에서 폐지되었습니다.

6.2.5. 리스트 디스플레이

리스트 디스플레이는 대괄호(square brackets)로 둘러싸인 표현식의 나열인데 비어있을 수 있습니다:

list_display ::=  "[" [starred_list | comprehension] "]"

리스트 디스플레이는 리스트 객체를 만드는데, 그 내용은 표현식의 목록이나 컴프리헨션으로 지정할 수 있습니다. 쉼표로 분리된 표현식의 목록이 제공될 때, 그 요소들은 왼쪽에서 오른쪽으로 값이 구해지고, 그 순서대로 리스트 객체에 삽입됩니다. 컴프리헨션이 제공될 때, 리스트는 컴프리헨션으로 만들어지는 요소들로 구성됩니다.

6.2.6. 집합 디스플레이

집합 디스플레이는 중괄호(curly braces)로 표시되고, 키와 값을 분리하는 콜론(colon)이 없는 것으로 딕셔너리 디스플레이와 구분될 수 있습니다.

set_display ::=  "{" (starred_list | comprehension) "}"

집합 디스플레이는 새 가변 집합 객체를 만드는데, 그 내용은 표현식의 시퀀스나 컴프리헨션으로 지정됩니다. 쉼표로 분리된 표현식의 목록이 제공될 때, 그 요소들은 왼쪽에서 오른쪽으로 값이 구해지고, 집합 객체에 더해집니다. 컴프리헨션이 제공될 때, 집합은 컴프리헨션으로 만들어지는 요소들로 구성됩니다.

빈 집합은 {} 으로 만들어질 수 없습니다; 이 리터럴은 빈 딕셔너리를 만듭니다.

6.2.7. 딕셔너리 디스플레이

딕셔너리 디스플레이는 중괄호(curly braces)로 둘러싸인 키/데이터 쌍의 나열인데 비어있을 수 있습니다:

dict_display       ::=  "{" [key_datum_list | dict_comprehension] "}"
key_datum_list     ::=  key_datum ("," key_datum)* [","]
key_datum          ::=  expression ":" expression | "**" or_expr
dict_comprehension ::=  expression ":" expression comp_for

딕셔너리 디스플레이는 새 딕셔너리 객체를 만듭니다.

쉼표로 분리된 키/데이터 쌍의 시퀀스가 주어질 때, 그것들은 왼쪽에서 오른쪽으로 값이 구해지고 딕셔너리의 엔트리들을 정의합니다: 각 키 객체는 딕셔너리에 대응하는 데이터를 저장하는 데 키로 사용됩니다. 이것은 키/값 목록에서 같은 키를 여러 번 지정할 수 있다는 뜻인데, 그 키의 최종 딕셔너리 값은 마지막에 주어진 것이 됩니다.

두 개의 애스터리스크(asterisk) ** 는 딕셔너리 언 패킹(dictionary unpacking) 를 나타냅니다. 피연산자는 매핑 이어야만 합니다. 각 매핑 항목은 새 딕셔너리에 추가됩니다. 뒤에 오는 값들이 앞의 키/데이터 쌍이나 앞의 딕셔너리 언 패킹 때문에 설정된 값들을 교체합니다.

버전 3.5에 추가: PEP 448 [https://www.python.org/dev/peps/pep-0448] 에서 처음 제안된 딕셔너리 디스플레이로의 언 패킹.

딕셔너리 컴프리헨션은, 리스트와 집합 컴프리헨션에 대비해서, 일반적인 “for” 와 “if” 절 앞에 콜론으로 분리된 두 개의 표현식을 필요로 합니다. 컴프리헨션이 실행될 때, 만들어지는 키와 값 요소들이 만들어지는 순서대로 딕셔너리에 삽입됩니다.

킷값의 형에 대한 제약은 앞의 섹션 표준형 계층 에서 나열되었습니다. (요약하자면, 키 형은 해시 가능 해야 하는데, 모든 가변 객체들이 제외됩니다.) 중복된 키 간의 충돌은 감지되지 않습니다; 주어진 키에 대해 저장된 마지막 (구문상으로 디스플레이의 가장 오른쪽에 있는) 데이터가 우선합니다.

6.2.8. 제너레이터 표현식 (Generator expressions)

제너레이터 표현식은 괄호로 둘러싸인 간결한 제너레이터 표기법입니다.

generator_expression ::=  "(" expression comp_for ")"

제너레이터 표현식은 새 제너레이터 객체를 만듭니다. 문법은 대괄호나 중괄호 대신 괄호로 둘러싸인다는 점만 제외하면 컴프리헨션과 같습니다.

제너레이터 표현식에 사용되는 변수들은 제너레이터 객체의 __next__() 메서드가 호출될 때 느긋하게(lazily) 값이 구해집니다 (일반 제너레이터와 마찬가지입니다). 그러나 가장 왼쪽의 for 절에 있는 이터러블 표현식은 즉시 값이 구해져서, 그것으로 인해 발생하는 에러는 첫 번째 값이 검색되는 지점이 아니라 제너레이터 표현식이 정의된 지점에서 발생합니다. 후속 for 절과 가장 왼쪽 for 절의 모든 필터 조건은, 가장 왼쪽 이터러블에서 가져온 값에 따라 달라질 수 있으므로 둘러싸는 스코프에서 평가할 수 없습니다. 예를 들어: (x*y for x in range(10) for y in range(x, x+10)).

단지 하나의 인자만 갖는 호출에서는 괄호를 생략할 수 있습니다. 자세한 내용은 호출 섹션을 보세요.

제너레이터 표현식 자체의 기대되는 연산을 방해하지 않기 위해, 묵시적으로 정의된 제너레이터에서 yield 와 yield from 표현식은 금지됩니다 (Python 3.7에서, 이러한 표현식은 컴파일될 때 DeprecationWarning 을 발생시킵니다. 파이썬 3.8+ 에서는 SyntaxError 를 일으킬 것입니다).

제너레이터 표현식이 async for 절이나 await 표현식을 포함하면 비동기 제너레이터 표현식 (asynchronous generator expression) 이라고 불립니다. 비동기 제너레이터 표현식은 새 비동기 제너레이터 객체를 돌려주는데 이것은 비동기 이터레이터입니다 (비동기 이터레이터(Asynchronous Iterators) 를 참조하세요).

버전 3.6에 추가: 비동기식 제너레이터 표현식이 도입되었습니다.

버전 3.7에서 변경: 파이썬 3.7 이전에는, 비동기 제너레이터 표현식이 async def 코루틴에만 나타날 수 있었습니다. 3.7부터는, 모든 함수가 비동기식 제너레이터 표현식을 사용할 수 있습니다.

버전 3.7부터 폐지: yield 와 yield from 은 묵시적으로 중첩된 스코프에서 폐지되었습니다.

6.2.9. 일드 표현식(Yield expressions)

yield_atom       ::=  "(" yield_expression ")"
yield_expression ::=  "yield" [expression_list | "from" expression]

일드 표현식은 제너레이터 함수나 비동기 제너레이터 함수를 정의할 때 사용되고, 그래서 함수 정의의 바디에서만 사용될 수 있습니다. 함수의 바디에서 일드 표현식을 사용하는 것은 함수를 제너레이터로 만들고, async def 함수의 바디에서 사용하는 것은 그 코루틴 함수를 비동기 제너레이터로 만듭니다. 예를 들어:

def gen():  # defines a generator function
    yield 123

async def agen(): # defines an asynchronous generator function
    yield 123

둘러싸는 스코프에 대한 부작용으로 인해, yield 표현식은 컴프리헨션과 제너레이터 표현식을 구현하는 데 사용되는 묵시적으로 정의된 스코프에 사용될 수 없습니다 (Python 3.7에서, 이러한 표현식은 컴파일될 때 DeprecationWarning 을 발생시킵니다. 파이썬 3.8+ 에서는 SyntaxError 를 일으킬 것입니다).

버전 3.7부터 폐지: 일드 표현식은 컴프리헨션과 제너레이터 표현식을 구현하는 데 사용되는 묵시적으로 정의된 스코프에서 폐지되었습니다.

제너레이터 함수는 다음에서 설명합니다. 반면에 비동기 제너레이터 함수는 비동기 제너레이터 함수 섹션에서 별도로 설명합니다.

제너레이터 함수가 호출될 때, 제너레이터로 알려진 이터레이터를 돌려줍니다. 그러면 그 제너레이터가 제너레이터 함수의 실행을 제어합니다. 제너레이터의 메서드들 중 하나가 호출될 때 실행이 시작됩니다. 그 시점에, 실행은 첫 번째 일드 표현식까지 진행한 후, 거기에서 다시 일시 중지(suspend)하고 제너레이터의 호출자에게 expression_list 의 값을 돌려줍니다. 일시 중지된다는 것은, 모든 지역 상태가 보존된다는 뜻인데, 지역 변수들의 현재 연결들, 명령 포인터(instruction pointer), 내부 연산 스택(internal evaluation stack), 모든 예외 처리 상태가 포함됩니다. 제너레이터의 메서드들 중 하나를 호출해서 실행이 재개될 때, 함수는 마치 일드 표현식이 단지 또 하나의 외부 호출인 것처럼 진행할 수 있습니다. 재개된 후에 일드 표현식의 값은 실행을 재개하도록 만든 메서드에 달려있습니다. (보통 for 나 next() 내장을 통해) __next__() 가 사용되었다면 결과는 None 입니다. 그렇지 않고, send() 가 사용되었다면, 결과는 그 메서드로 전달된 값입니다.

이 모든 것들은 제너레이터 함수를 코루틴과 아주 비슷하게 만듭니다; 여러 번 결과를 만들고, 하나 이상의 진입 지점을 갖고 있으며, 실행이 일시 중지될 수 있습니다. 유일한 차이점은 제너레이터 함수는 yield 한 후에 실행이 어디에서 계속되어야 하는지를 제어할 수 없다는 점입니다; 제어는 항상 제너레이터의 호출자로 전달됩니다.

일드 표현식은 try 구조물의 어디에서건 허락됩니다. 제너레이터가 (참조 횟수가 0이 되거나 가비지 수거됨으로써) 파이널라이즈(finalize)되기 전에 재개되지 않으면, 제너레이터-이터레이터의 close() 메서드가 호출되어, 대기 중인 finally 절이 실행되도록 허락합니다.

yield from <expr> 이 사용될 때, 제공된 표현식을 서브 이터레이터(subiterator)로 취급합니다. 서브 이터레이터가 만드는 모든 값은 현재 제너레이터 메서드의 호출자에게 바로 전달됩니다. send() 로 전달된 모든 값과 throw() 로 전달된 모든 예외는 밑에 있는(underlying) 이터레이터가 해당 메서드를 갖고 있다면 그곳으로 전달됩니다. 그렇지 않다면, send() 는 AttributeError 나 TypeError 를 일으키지만, throw() 는 전달된 예외를 즉시 일으킨다.

밑에 있는 이러레이터가 완료될 때, 발생하는 StopIteration 인스턴스의 value 어트리뷰트는 일드 표현식의 값이 됩니다. StopIteration 를 일으킬 때 명시적으로 설정되거나, 서브 이터레이터가 제너레이터일 경우는 자동으로 이루어집니다 (서브 제너레이터가 값을 돌려(return)줌으로써).

버전 3.3에서 변경: 서브 이터레이터로 제어 흐름을 위임하는 yield from <expr> 를 추가했습니다.

일드 표현식이 대입문의 우변에 홀로 나온다면 괄호를 생략할 수 있습니다.

더 보기

PEP 255 [https://www.python.org/dev/peps/pep-0255] - 간단한 제너레이터

파이썬에 제너레이터와 yield 문을 추가하는 제안.

PEP 342 [https://www.python.org/dev/peps/pep-0342] - 개선된 제너레이터를 통한 코루틴

제너레이터의 API와 문법을 개선해서, 간단한 코루틴으로 사용할 수 있도록 만드는 제안.

PEP 380 [https://www.python.org/dev/peps/pep-0380] - 서브 제너레이터로 위임하는 문법

yield_from 문법을 도입해서, 서브 제너레이터로의 위임을 쉽게 만드는 제안.

PEP 525 [https://www.python.org/dev/peps/pep-0525] - 비동기 제너레이터

코루틴 함수에 제너레이터 기능을 추가하여 PEP 492 [https://www.python.org/dev/peps/pep-0492]을 확장한 제안.

6.2.9.1. 제너레이터-이터레이터 메서드

이 서브섹션은 제너레이터 이터레이터의 메서드들을 설명합니다. 제너레이터 함수의 실행을 제어하는데 사용될 수 있습니다.

제너레이터가 이미 실행 중일 때 아래에 나오는 메서드들을 호출하면 ValueError 예외를 일으키는 것에 주의해야 합니다.

generator.__next__()

제너레이터 함수의 실행을 시작하거나 마지막으로 실행된 일드 표현식에서 재개합니다. 제너레이터 함수가 __next__() 메서드로 재개될 때, 현재의 일드 표현식은 항상 None 값을 갖는다. 실행은 다음 일드 표현식까지 이어지는데, 그곳에서 제너레이터는 다시 일시 중지되고, expression_list 의 값을 __next__() 의 호출자에게 돌려줍니다. 제너레이터가 다른 값을 yield 하지 않고 종료되면 StopIteration 예외가 발생합니다.

이 메서드는 보통 묵시적으로 호출됩니다, 예를 들어, for 루프나 내장 next() 함수에 의해.

generator.send(value)

실행을 재개하고 제너레이터 함수로 값을 “보냅니다(send)”. value 인자는 현재 일드 표현식의 값이 됩니다. send() 메서드는 제너레이터가 yield 하는 다음 값을 돌려주거나, 제너레이터가 다른 값을 yield 하지 않고 종료하면 StopIteration 을 일으킵니다. send() 가 제너레이터를 시작시키도록 호출될 때, 값을 받을 일드 표현식이 없으므로, 인자로는 반드시 None 을 전달해야 합니다.

generator.throw(type[, value[, traceback]])

제너레이터가 일시 정지한 지점에서 type 형의 예외를 일으키고, 제너레이터 함수가 yield 하는 다음 값을 돌려줍니다. 제너레이터가 다른 값을 yield 하지 않고 종료하면 StopIteration 을 일으킵니다. 제너레이터가 전달된 예외를 잡지 않거나, 다른 예외를 일으키면, 그 예외는 호출자로 퍼집니다.

generator.close()

제너레이터가 일시 정지한 지점에서 GeneratorExit 를 일으킵니다. 그런 다음 제너레이터 함수가 우아하게(gracefully) 종료하거나, 이미 닫혔거나, (그 예외를 잡지 않음으로써) GeneratorExit 를 일으키면 close는 호출자로 돌아갑니다. 제너레이터가 값을 yield 하면 RuntimeError 가 발생합니다. 제너레이터가 다른 예외를 일으키면, 호출자로 퍼집니다. 제너레이터가 예외나 정상 종료로 인해 이미 종료되었다면, close() 는 아무런 일도 하지 않습니다.

6.2.9.2. 사용 예

여기에 제너레이터와 제너레이터 함수의 동작을 시연하는 간단한 예가 있습니다:

>>> def echo(value=None):
...     print("Execution starts when 'next()' is called for the first time.")
...     try:
...         while True:
...             try:
...                 value = (yield value)
...             except Exception as e:
...                 value = e
...     finally:
...         print("Don't forget to clean up when 'close()' is called.")
...
>>> generator = echo(1)
>>> print(next(generator))
Execution starts when 'next()' is called for the first time.
1
>>> print(next(generator))
None
>>> print(generator.send(2))
2
>>> generator.throw(TypeError, "spam")
TypeError('spam',)
>>> generator.close()
Don't forget to clean up when 'close()' is called.

yield from 을 사용하는 예는, “What’s New in Python.” 에 있는 PEP 380: Syntax for Delegating to a Subgenerator 을 보세요.

6.2.9.3. 비동기 제너레이터 함수

async def 를 사용한 함수나 메서드에서 일드 표현식의 존재는 그 함수를 비동기 제너레이터 함수로 정의합니다.

비동기 제너레이터 함수가 호출되면, 비동기 제너레이터 객체로 알려진 비동기 이터레이터를 돌려줍니다. 그런 다음 그 객체는 제너레이터 함수의 실행을 제어합니다. 비동기 제너레이터 객체는 보통 코루틴 함수의 async for 문에서 사용되는데, 제너레이터 객체가 for 문에서 사용되는 방식과 유사합니다.

비동기 제너레이터의 메서드들 중 하나를 호출하면 어웨이터블 객체를 돌려주고, 이 객체를 await 할 때 실행이 시작됩니다. 그 시점에, 실행은 첫 번째 일드 표현식까지 진행한 후, 거기에서 다시 일시 중지(suspend)하고 await 중인 코루틴에게 expression_list 의 값을 돌려줍니다. 제너레이터에서처럼, 일시 중지된다는 것은, 모든 지역 상태가 보존된다는 뜻인데, 지역 변수들의 현재 연결들, 명령 포인터(instruction pointer), 내부 연산 스택(internal evaluation stack), 모든 예외 처리 상태가 포함됩니다. 비동기 제너레이터의 메서드가 돌려준 다음 객체를 await 해서 실행이 재개될 때, 함수는 마치 일드 표현식이 단지 또 하나의 외부 호출인 것처럼 진행할 수 있습니다. 재개된 후에 일드 표현식의 값은 실행을 재개하도록 만든 메서드에 달려있습니다. __anext__() 가 사용되었다면 결과는 None 입니다. 그렇지 않고, asend() 가 사용되었다면, 결과는 그 메서드로 전달된 값입니다.

비동기 제너레이터 함수에서, 일드 표현식은 try 구조물의 어디에서건 허락됩니다. 하지만, 비동기 제너레이터가 (참조 횟수가 0이 되거나 가비지 수거됨으로써) 파이널라이즈(finalize)되기 전에 재개되지 않으면, try 구조물 내의 일드 표현식은 대기 중인 finally 절을 실행하는 데 실패할 수 있습니다. 이 경우에, 비동기 제너레이터-이터레이터의 aclose() 를 호출하고, 그 결과로 오는 코루틴 객체를 실행해서, 대기 중인 finally 절이 실행되도록 하는 책임은, 비동기 제너레이터를 실행하는 이벤트 루프(event loop)나 스케줄러(scheduler)에게 있습니다.

파이널리제이션을 처리하기 위해, 이벤트 루프는 파이널라이저(finalizer) 함수를 정의해야 하는데 비동기 제너레이터-이터레이터를 받아서 아마도 aclose() 를 호출하고 그 코루틴을 실행합니다. 이 파이널라이저 는 sys.set_asyncgen_hooks() 을 호출해서 등록할 수 있습니다. 처음 탐색 될 때, 비동기 제너레이터-이터레이터는 파이널리제이션때 호출될 등록된 파이널라이저 를 저장할 것입니다. 파이널라이저 메서드의 참조할만한 예는 Lib/asyncio/base_events.py [https://github.com/python/cpython/tree/3.7/Lib/asyncio/base_events.py] 에 있는 asyncio.Loop.shutdown_asyncgens 구현을 보세요.

표현식 yield from <expr> 를 비동기 제너레이터 함수에서 사용하는 것은 문법 에러다.

6.2.9.4. 비동기 제너레이터-이터레이터 메서드

이 서브섹션은 비동기 제너레이터 이터레이터의 메서드를 설명하는데, 제너레이터 함수의 실행을 제어하는 데 사용됩니다.

coroutine agen.__anext__()

어웨이터블을 돌려주는데, 실행하면 비동기 제너레이터 함수의 실행을 시작하거나 마지막으로 실행된 일드 표현식에서 재개합니다. 비동기 제너레이터 함수가 __anext__() 메서드로 재개될 때, 반환된 어웨이터블에서 현재의 일드 표현식은 항상 None 값을 갖고 반환된 어웨이터블을 실행하면 다음 일드 표현식까지 이어집니다. 일드 표현식의 expression_list 의 값은 종료하는 코루틴이 일으킨 StopIteration 의 값입니다. 비동기 제너레이터가 다른 값을 yield 하지 않고 종료되면, 비동기 탐색의 종료를 알리기 위해 어웨이터블이 대신 StopAsyncIteration 예외를 일으킵니다.

이 메서드는 보통 async for 루프에 의해 묵시적으로 호출됩니다.

coroutine agen.asend(value)

어웨이터블을 돌려주는데, 실행하면 비동기 제너레이터의 실행을 재개합니다. 제너레이터의 send() 메서드 처럼, 이것은 값을 비동기 제너레이터 함수로 “보내(send)”고, value 인자는 현재 일드 표현식의 결과가 됩니다. asend() 메서드가 돌려주는 어웨이터블은 제너레이터가 yield 하는 다음 값을 발생시킨 StopIteration 의 값으로 돌려주거나, 비동기 제너레이터가 다른 값을 yield 하지 않고 종료하면 StopAsyncIteration 를 일으킵니다. 비동기 제너레이터를 시작시키도록 asend() 가 호출될 때, 값을 받을 일드 표현식이 없으므로 인자를 None 으로 호출해야 합니다.

coroutine agen.athrow(value)

coroutine agen.athrow(type[, value[, traceback]])

어웨이터블을 돌려주는데, 비동기 제너레이터가 일시 중지한 지점에 type 형의 예외를 일으키고, 제너레이터 함수가 yield 한 다음 값을 발생하는 StopIteration 예외의 값으로 돌려줍니다. 비동기 제너레이터가 다른 값을 yield 하지 않고 종료하면, 어웨이터블에 의해 StopAsyncIteration 예외가 일어납니다. 제너레이터 함수가 전달된 예외를 잡지 않거나, 다른 예외를 일으키면, 어웨이터블을 실행할 때 그 예외가 어웨이터블의 호출자에게 퍼집니다.

coroutine agen.aclose()

어웨이터블을 돌려주는데, 실행하면, 비동기 제너레이터 함수가 일시 정지한 지점으로 GeneratorExit 를 던집니다. 만약 그 이후에 비동기 제너레이터 함수가 우아하게 (gracefully) 종료하거나, 이미 닫혔거나, (그 예외를 잡지 않음으로써) GeneratorExit 를 일으키면, 돌려준 어웨이터블은 StopIteration 예외를 일으킵니다. 이어지는 비동기 제너레이터 호출이 돌려주는 추가의 어웨이터블들은 StopAsyncIteration 예외를 일으킵니다. 만약 비동기 제너레이터가 값을 yield 하면 어웨이터블에 의해 RuntimeError 가 발생합니다. 만약 비동기 제너레이터가 그 밖의 다른 예외를 일으키면, 어웨이터블의 호출자로 퍼집니다. 만약 비동기 제너레이터가 예외나 정상 종료로 이미 종료했으면, 더 이어지는 aclose() 호출은 아무것도 하지 않는 어웨이터블을 돌려줍니다.

6.3. 프라이머리

프라이머리는 언어에서 가장 강하게 결합하는 연산들을 나타냅니다. 문법은 이렇습니다:

primary ::=  atom | attributeref | subscription | slicing | call

6.3.1. 어트리뷰트 참조

어트리뷰트 참조는 마침표(period)와 이름이 뒤에 붙은 프라이머리다:

attributeref ::=  primary "." identifier

프라이머리는 값을 구했을 때 어트리뷰트 참조를 지원하는 형의 객체가 나와야 하는데, 대부분 객체가 이 상황에 해당합니다. 이 객체는 그 이름을 식별자로 하는 어트리뷰트를 생산하도록 요청받습니다. 이 생산은 __getattr__() 메서드를 재정의해서 커스터마이즈 할 수 있습니다. 이 어트리뷰트가 없으면, AttributeError 을 일으킵니다. 그렇지 않으면, 생산된 객체의 형과 값은 그 객체에 의해 결정됩니다. 같은 어트리뷰트 참조의 값을 여러 번 구하면 각기 다른 객체가 얻어질 수 있습니다.

6.3.2. 서브스크립션(Subscriptions)

서브스크립션은 시퀀스(문자열, 튜플, 리스트)나 매핑 (딕셔너리) 객체의 항목을 선택합니다:

subscription ::=  primary "[" expression_list "]"

프라이머리는 값을 구했을 때 서브스크립션을 지원하는 객체가 나와야 합니다 (예를 들어, 리스트나 딕셔너리). 사용자 정의 객체들은 __getitem__() 메서드를 구현해서 서브스크립션을 지원할 수 있습니다.

내장 객체들의 경우, 서브스크립션을 지원하는 두 가지 종류의 객체들이 있습니다:

프라이머리가 매핑이면, 표현식 목록은 값을 구했을 때 매핑의 키 중 하나가 되어야 하고, 서브스크립션은 매핑에서 그 키에 대응하는 값을 선택합니다. (표현식 목록은 정확히 하나의 항목을 가지는 경우만을 제외하고는 튜플입니다.)

프라이머리가 시퀀스면, 표현식 목록은 값을 구했을 때 정수나 슬라이스(slice) (다음 섹션에서 논의합니다)가 나와야 합니다.

형식 문법은 시퀀스에서 음수 인덱스에 대해 특별히 규정하지 않습니다; 하지만, 내장 시퀀스들은 모두 인덱스에 시퀀스의 길이를 더하는 것으로 음의 인덱스를 해석하는 __getitem__() 메서드를 제공합니다 (그래서 x[-1] 은 x 의 마지막 항목을 선택합니다). 결괏값은 반드시 시퀀스에 있는 항목들의 개수보다 작은 음이 아닌 정수가 되어야 하고, 서브스크립션은 인덱스가 그 값이 되는 항목을 선택합니다 (0에서 부 터 센다). 음의 인덱스와 슬라이싱에 대한 지원이 객체의 __getitem__() 메서드에서 이루어지기 때문에, 이 메서드를 재정의하는 서브 클래스는 그 지원을 명시적으로 추가할 필요가 있습니다.

문자열의 항목은 문자입니다. 문자는 별도의 데이터형이 아니고, 하나의 문자만을 가진 문자열입니다.

6.3.3. 슬라이싱(Slicings)

슬라이싱은 시퀀스 객체 (예를 들어, 문자열 튜플 리스트)에서 어떤 범위의 항목들을 선택합니다. 슬라이싱은 표현식이나 대입의 타깃이나 del 문에 사용될 수 있습니다. 슬라이싱의 문법은 이렇습니다:

slicing      ::=  primary "[" slice_list "]"
slice_list   ::=  slice_item ("," slice_item)* [","]
slice_item   ::=  expression | proper_slice
proper_slice ::=  [lower_bound] ":" [upper_bound] [ ":" [stride] ]
lower_bound  ::=  expression
upper_bound  ::=  expression
stride       ::=  expression

이 형식 문법에는 모호함이 있습니다: 표현식 목록처럼 보이는 것들은 모두 슬라이스 목록으로 보이기도 해서, 모든 서브스크립션이 슬라이싱으로 해석될 수도 있습니다. 문법을 더 복잡하게 만드는 대신, 이 경우에 서브스크립션으로 해석하는 것이 슬라이싱으로 해석하는 것에 우선한다고 정의하는 것으로 애매함을 제거합니다 (이 경우는 슬라이스 목록이 고유한 슬라이스(proper slice) 를 하나도 포함하지 않을 때입니다).

슬라이싱의 의미는 다음과 같습니다. 프라이머리가 (일반 서브스크립션과 같은 __getitem__() 메서드를 사용해서) 다음과 같이 슬라이스 목록으로부터 만들어지는 키로 인덱싱됩니다. 슬라이스 목록이 적어도 하나의 쉼표를 갖는다면, 키는 슬라이스 항목들의 변환을 포함하는 튜플입니다; 그렇지 않으면 슬라이스 항목 하나의 변환이 키입니다. 표현식인 슬라이스 항목의 변환은 그 표현식입니다. 고유한 슬라이스(proper slice)의 변환은 슬라이스 객체 (섹션 표준형 계층 를 보라)인데, start, stop, step 어트리뷰트가 각각 lower_bound, upper_bound, stride 로 주어진 표현식이고, 빠진 표현식들을 None 으로 채웁니다.

6.3.4. 호출

호출은 콜러블 객체 (예를 들어, 함수) 를 빌 수도 있는 인자 들의 목록으로 호출합니다.

call                 ::=  primary "(" [argument_list [","] | comprehension] ")"
argument_list        ::=  positional_arguments ["," starred_and_keywords]
                            ["," keywords_arguments]
                          | starred_and_keywords ["," keywords_arguments]
                          | keywords_arguments
positional_arguments ::=  ["*"] expression ("," ["*"] expression)*
starred_and_keywords ::=  ("*" expression | keyword_item)
                          ("," "*" expression | "," keyword_item)*
keywords_arguments   ::=  (keyword_item | "**" expression)
                          ("," keyword_item | "," "**" expression)*
keyword_item         ::=  identifier "=" expression

생략할 수 있는 마지막 쉼표가 위치나 키워드 인자 뒤에 나타날 수 있지만, 의미를 바꾸지 않습니다.

프라이머리의 값을 구하면 콜러블 객체 (사용자 정의 함수, 내장 함수, 내장 객체들의 메서드, 클래스 객체, 클래스 인스턴스의 메서드, __call__() 메서드를 갖는 모든 객체가 콜러블입니다) 가 나와야 합니다. 모든 인자 표현식들은 호출을 시도하기 전에 값이 구해집니다. 형식 매개변수 목록의 문법은 함수 정의 섹션을 참고하면 됩니다.

키워드 인자가 있으면, 먼저 다음과 같이 위치 인자로 변환됩니다. 먼저 형식 매개변수들의 채워지지 않은 슬롯들의 목록이 만들어집니다. N 개의 위치 인자들이 있다면, 처음 N 개의 슬롯에 넣습니다. 그다음, 각 키워드 인자마다, 식별자가 대응하는 슬롯을 결정하는 데 사용됩니다 (식별자가 첫 번째 형식 매개변수의 이름과 같으면, 첫 번째 슬롯은 사용되고, 이런 식으로 계속합니다). 슬롯이 이미 채워졌으면, TypeError 예외를 일으킵니다. 그렇지 않으면 그 인자의 값을 슬롯에 채워 넣습니다 (표현식이 None 이라 할지라도, 슬롯을 채우게 됩니다). 모든 인자가 처리되었을 때, 아직 채워지지 않은 슬롯들을 함수 정의로부터 오는 대응하는 기본값들로 채웁니다. (기본값들은 함수가 정의될 때 한 번만 값을 구합니다; 그래서, 리스트나 딕셔너리 같은 가변객체들이 기본값으로 사용되면 해당 슬롯에 인자값을 지정하지 않은 모든 호출에서 공유됩니다; 보통 이런 상황은 피해야 할 일입니다.) 만약 기본값이 지정되지 않고, 아직도 비어있는 슬롯이 남아있다면, TypeError 예외가 발생합니다. 그렇지 않으면, 채워진 슬롯의 목록이 호출의 인자 목록으로 사용됩니다.

CPython implementation detail: 구현은 위치 매개변수가 이름을 갖지 않아서, 설사 문서화의 목적으로 이름이 붙여졌다 하더라도, 키워드로 공급될 수 없는 내장 함수들을 제공할 수 있습니다. CPython 에서, 인자들을 파싱하기 위해 PyArg_ParseTuple() 를 사용하는 C로 구현된 함수들이 이 경우입니다.

형식 매개변수 슬롯들보다 많은 위치 인자들이 있으면, *identifier 문법을 사용하는 형식 매개변수가 있지 않은 한, TypeError 예외를 일으킵니다; 이 경우, 그 형식 매개변수는 남는 위치 인자들을 포함하는 튜플을 전달받습니다 (또는 남는 위치 인자들이 없으면 빈 튜플).

키워드 인자가 형식 매개변수 이름에 대응하지 않으면, **identifier 문법을 사용하는 형식 매개변수가 있지 않은 한, TypeError 예외를 일으킵니다; 이 경우, 그 형식 매개변수는 남는 키워드 인자들을 포함하는 딕셔너리나, 남는 위치기반 인자들이 없으면 빈 (새) 딕셔너리를 전달받습니다.

문법 *expression 이 함수 호출에 등장하면, expression 의 값은 이터러블 이 되어야 합니다. 이 이터러블의 요소들은, 그것들이 추가의 위치 인자들인 것처럼 취급됩니다. 호출 f(x1, x2, *y, x3, x4) 의 경우, y 의 값을 구할 때 시퀀스 y1, …, yM 이 나온다면, 이것은 M+4개의 위치 인자들 x1, x2, y1, …, yM, x3, x4 로 호출하는 것과 동등합니다.

이로 인한 결과는 설사 *expression 문법이 명시적인 키워드 인자 뒤에 나올 수는 있어도, 키워드 인자 (그리고 모든 **expression 인자들 – 아래를 보라) 전에 처리된다는 것입니다. 그래서:

>>> def f(a, b):
...     print(a, b)
...
>>> f(b=1, *(2,))
2 1
>>> f(a=1, *(2,))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: f() got multiple values for keyword argument 'a'
>>> f(1, *(2,))
1 2

같은 호출에서 키워드 인자와 *expression 문법을 모두 사용하는 것은 일반적이지 않기 때문에, 실제로는 이런 혼란이 일어나지 않습니다.

문법 **expression 이 함수 호출에 등장하면, expression 의 값은 매핑 이 되어야 합니다, 그 내용이 추가의 키워드 인자인 것처럼 취급됩니다. 키워드가 (명시적인 키워드 인자나 다른 언 패킹으로부터) 이미 존재한다면 TypeError 예외가 발생합니다.

문법 *identifier 이나 **identifier 를 사용하는 형식 매개변수들은 위치 인자 슬롯이나 키워드 인자 아름들로 사용될 수 없습니다.

버전 3.5에서 변경: 함수 호출은 임의의 개수의 * and ** 언 패킹을 받아들이고, 위치 인자들이 이터러블 언 패킹 (*) 뒤에 올 수 있고, 키워드 인자가 딕셔너리 언 패킹 (**) 뒤에 올 수 있습니다. 최초로 PEP 448 [https://www.python.org/dev/peps/pep-0448] 에서 제안되었습니다.

호출은 예외를 일으키지 않는 한, 항상 어떤 값을 돌려줍니다, None 일 수 있습니다. 이 값이 어떻게 계산되는지는 콜러블 객체의 형에 달려있습니다.

만약 그것이—

사용자 정의 함수면:

인자 목록을 전달해서 함수의 코드 블록이 실행됩니다. 코드 블록이 처음으로 하는 일은 형식 매개변수들을 인자에 결합하는 것입니다; 이것은 섹션 함수 정의 에서 설명합니다. 코드 블록이 return 문을 실행하면, 함수 호출의 반환 값을 지정하게 됩니다.

내장 함수나 메서드면:

결과는 인터프리터에 달려있습니다; 내장 함수와 메서드들에 대한 설명은 내장 함수 를 보세요.

클래스 객체면:

그 클래스의 새 인스턴스가 반환됩니다.

클래스 인스턴스 메서드면:

대응하는 사용자 정의 함수가 호출되는데, 그 인스턴스가 첫 번째 인자가 되는 하나만큼 더 긴 인자 목록이 전달됩니다.

클래스 인스턴스면:

그 클래스는 __call__() 메서드를 정의해야 합니다; 그 효과는 그 메서드가 호출되는 것과 같습니다.

6.4. 어웨이트 표현식

어웨이터블 에서 코루틴 의 실행을 일시 중지합니다. 오직 코루틴 함수 에서만 사용할 수 있습니다.

await_expr ::=  "await" primary

버전 3.5에 추가.

6.5. 거듭제곱 연산자

거듭제곱 연산자는 그것의 왼쪽에 붙는 일 항 연산자보다 더 강하게 결합합니다; 그것의 오른쪽에 붙는 일 항 연산자보다는 약하게 결합합니다. 문법은 이렇습니다:

power ::=  (await_expr | primary) ["**" u_expr]

그래서, 괄호가 없는 거듭제곱과 일 항 연산자의 시퀀스에서, 연산자는 오른쪽에서 왼쪽으로 값이 구해집니다 (이것이 피연산자의 값을 구하는 순서를 제약하는 것은 아닙니다): -1**2 은 -1 이 됩니다.

거듭제곱 연산자는 내장 pow() 함수가 두 개의 인자로 호출될 때와 같은 의미가 있습니다: 왼쪽 인자를 오른쪽 인자만큼 거듭제곱한 값을 줍니다. 숫자 인자는 먼저 공통 형으로 변환되고, 결과는 그 형입니다.

int 피연산자의 경우, 두 번째 인자가 음수가 아닌 이상 결과는 피연산자들과 같은 형을 갖습니다; 두 번째 인자가 음수면, 모든 인자는 float로 변환되고, float 결과가 전달됩니다. 예를 들어, 10**2 는 100 를 돌려주지만, 10**-2 는 0.01 를 돌려줍니다.

0.0 를 음수로 거듭제곱하면 ZeroDivisionError 를 일으킵니다. 음수를 분수로 거듭제곱하면 복소수(complex)가 나옵니다. (예전 버전에서는 ValueError 를 일으켰습니다.)

6.6. 일 항 산술과 비트 연산

모든 일 항 산술과 비트 연산자는 같은 우선순위를 갖습니다.

u_expr ::=  power | "-" u_expr | "+" u_expr | "~" u_expr

일 항 - (마이너스) 연산자는 그 숫자 인자의 음의 값을 줍니다.

일 항 + (플러스) 연산자는 그 숫자 인자의 값을 변경 없이 줍니다.

일 항 ~ (인버트) 연산자는 그 정수 인자의 비트 반전된 값을 줍니다. x 의 비트 반전은 -(x+1) 로 정의됩니다. 오직 정수에만 적용됩니다.

세 가지 경우 모두, 인자가 올바른 형을 갖지 않는다면, TypeError 예외가 발생합니다.

6.7. 이항 산술 연산

이항 산술 연산자는 관습적인 우선순위를 갖습니다. 이 연산자 중 일부는 일부 비 숫자 형에도 적용됨에 주의해야 합니다. 거듭제곱 연산자와는 별개로, 오직 두 가지 수준만 있는데, 하나는 곱셈형 연산자들이고, 하나는 덧셈형 연산자들입니다.

m_expr ::=  u_expr | m_expr "*" u_expr | m_expr "@" m_expr |
            m_expr "//" u_expr | m_expr "/" u_expr |
            m_expr "%" u_expr
a_expr ::=  m_expr | a_expr "+" m_expr | a_expr "-" m_expr

* (곱셈) 연산자는 인자들의 곱을 줍니다. 인자들은 모두 숫자거나, 한 인자는 정수고 다른 인자는 시퀀스여야 합니다. 앞의 경우에, 숫자들은 공통 형으로 변환된 후 곱해집니다. 후자의 경우, 시퀀스의 반복이 수행됩니다; 음의 반복 값은 빈 시퀀스를 만듭니다.

@ (at) 연산자는 행렬 곱셈에 사용하려는 것입니다. 파이썬의 내장형들 어느 것도 이 연산자를 구현하지 않습니다.

버전 3.5에 추가.

/ (나눗셈)과 // (정수 나눗셈, floor division) 연산자들은 그 인자들의 몫(quotient)을 줍니다. 숫자 인자들은 먼저 공통형으로 변환됩니다. 정수들의 나눗셈은 실수를 만드는 반면, 정수들의 정수 나눗셈은 정숫값을 줍니다; 그 결과는 수학적인 나눗셈의 결과에 ‘floor’ 함수를 적용한 것입니다. 0으로 나누는 것은 ZeroDivisionError 예외를 일으킵니다.

% (모듈로, modulo) 연산자는 첫 번째 인자를 두 번째 인자로 나눈 나머지를 줍니다. 숫자 인자들은 먼저 공통형으로 변환됩니다. 오른쪽 인자가 0이면 ZeroDivisionError 예외를 일으킵니다. 인자들은 실수가 될 수 있습니다, 예를 들어, 3.14%0.7 는 0.34 와 같습니다 (3.14 가 4*0.7 + 0.34 와 같으므로.) 모듈로 연산자는 항상 두 번째 피연산자와 같은 부호를 갖는 결과를 줍니다 (또는 0입니다); 결과의 절댓값은 두 번째 피연산자의 절댓값보다 작습니다 1.

정수 나눗셈과 모듈로 연산자는 다음과 같은 항등식으로 연결되어 있습니다: x == (x//y)*y + (x%y). 정수 나눗셈과 모듈로는 내장 함수 divmod() 와도 연결되어 있습니다: divmod(x, y) == (x//y, x%y). 2.

숫자들에 대해 모듈로 연산을 수행하는 것에 더해, % 연산자는 예전 스타일의 문자열 포매팅 (인터폴레이션이라고도 알려져 있습니다)을 수행하기 위해 문자열 객체에 의해 다시 정의됩니다. 문자열 포매팅의 문법은 파이썬 라이브러리 레퍼런스의 섹션 printf 스타일 문자열 포매팅 에서 설명합니다.

정수 나눗셈 연산자, 모듈로 연산자, divmod() 함수는 복소수에 대해서는 정의되어 있지 않습니다. 대신, 적절하다면, abs() 함수를 사용해서 실수로 변환하십시오.

+ (덧셈) 연산자는 그 인자들의 합을 줍니다. 인자들은 둘 다 숫자거나, 둘 다 같은 형의 시퀀스여야 합니다. 앞의 경우, 숫자들은 먼저 공통형으로 변환된 후, 함께 합쳐집니다. 후자의 경우 시퀀스는 이어붙이게 됩니다.

- (빼기) 연산자는 그 인자들의 차를 줍니다. 숫자 인자들은 먼저 공통형으로 변환됩니다.

6.8. 시프트 연산

시프트 연산은 산술 연산보다 낮은 우선순위를 갖습니다.

shift_expr ::=  a_expr | shift_expr ("<<" | ">>") a_expr

이 연산들은 정수들을 인자로 받아들입니다. 첫 번째 인자를 두 번째 인자로 주어진 비트 수만큼 왼쪽이나 오른쪽으로 밉니다(shift).

오른쪽으로 n 비트 시프트 하는 것은 pow(2,n) 로 정수 나눗셈하는 것으로 정의됩니다. 왼쪽으로 n 비트 시프트 하는 것은 pow(2,n) 를 곱하는 것으로 정의됩니다.

6.9. 이항 비트 연산

세 개의 비트 연산은 각기 다른 우선순위를 갖습니다:

and_expr ::=  shift_expr | and_expr "&" shift_expr
xor_expr ::=  and_expr | xor_expr "^" and_expr
or_expr  ::=  xor_expr | or_expr "|" xor_expr

& 연산자는 그 인자들의 비트별 AND를 주는데, 인자들은 정수여야 합니다.

^ 연산자는 그 인자들의 비트별 XOR (배타적 OR)를 주는데, 인자들은 정수여야 합니다.

| 연산자는 그 인자들의 비트별 (포함적, inclusive) OR를 주는데, 인자들은 정수여야 합니다.

6.10. 비교

C와는 달리, 파이썬에서 모든 비교 연산은 같은 우선순위를 갖는데, 산술, 시프팅, 비트 연산들보다 낮습니다. 또한, C와는 달리, a < b < c 와 같은 표현식이 수학에서와 같은 방식으로 해석됩니다.

comparison    ::=  or_expr (comp_operator or_expr)*
comp_operator ::=  "<" | ">" | "==" | ">=" | "<=" | "!="
                   | "is" ["not"] | ["not"] "in"

비교는 논리값을 줍니다: True 또는 False

비교는 자유롭게 연결될 수 있습니다, 예를 들어, x < y <= z 는 x < y and y <= z 와 동등한데, 차이점은 y 의 값을 오직 한 번만 구한다는 것입니다 (하지만 두 경우 모두 x < y 가 거짓이면 z 의 값은 구하지 않습니다).

형식적으로, a, b, c, …, y, z 가 표현식이고, op1, op2, …, opN 가 비교 연산자면, a op1 b op2 c ... y opN z 는 각 표현식의 값을 최대 한 번만 구한다는 점을 제외하고는 a op1 b and b op2 c and ... y opN z 와 동등합니다.

a op1 b op2 c 가 a 와 c 간의 어떤 종류의 비교도 암시하지 않기 때문에, 예를 들어, x < y > z 이 완벽하게 (아마 이쁘지는 않더라도) 올바르다는 것에 주의해야 합니다.

6.10.1. 값 비교

연산자 <, >, ==, >=, <=, != 는 두 객체의 값을 비교합니다. 객체들이 같은 형일 필요는 없습니다.

객체, 값, 형 장은 객체들이 (형과 아이덴티티에 더해) 값을 갖는다고 말하고 있습니다. 파이썬에서 객체의 값은 좀 추상적인 개념입니다: 예를 들어, 객체의 값에 대한 규범적인(canonical) 액세스 방법은 없습니다. 또한, 객체의 값이 특별한 방식(예를 들어, 모든 데이터 어트리뷰트로 구성되는 것)으로 구성되어야 한다는 요구 사항도 없습니다. 비교 연산자는 객체의 값이 무엇인지에 대한 특정한 종류의 개념을 구현합니다. 객체의 값을 비교를 통해 간접적으로 정의한다고 생각해도 좋습니다.

모든 형은 (직접적 혹은 간접적으로) object 의 서브 형이기 때문에, 그들은 object 로 부터 기본 비교 동작을 계승합니다. 형들은 __lt__() 와 같은 풍부한 비교 메서드(rich comparison methods) 를 구현해서 자신의 비교 동작을 커스터마이즈할 수 있는데, 기본적인 커스터마이제이션 에서 설명됩니다.

동등 비교 (== 와 !=) 의 기본 동작은 객체의 아이덴티티에 기반을 둡니다. 그래서, 같은 아이덴티티를 갖는 인스턴스 간의 동등 비교는 같음을 주고, 다른 아이덴티티를 갖는 인스턴스 간의 동등 비교는 다름을 줍니다. 이 기본 동작의 동기는 모든 객체가 반사적(reflexive) (즉, x is y 는 x == y 를 암시합니다) 이도록 만들고자 하는 욕구입니다.

기본 대소 비교(order comparison) (<, >, <=, >=) 는 제공되지 않습니다; 시도하면 TypeError 를 일으킵니다. 이 기본 동작의 동기는 동등함과 유사한 항등 관계가 없다는 것입니다.

다른 아이덴티티를 갖는 인스턴스들이 항상 서로 다르다는, 기본 동등 비교의 동작은, 객체의 값과 값 기반의 동등함에 대한 나름의 정의를 가진 형들이 필요로 하는 것과는 크게 다를 수 있습니다. 그런 형들은 자신의 비교 동작을 커스터마이즈 할 필요가 있고, 사실 많은 내장형이 그렇게 하고 있습니다.

다음 목록은 가장 중요한 내장형들의 비교 동작을 기술합니다.

내장 숫자 형 ((숫자 형 — int, float, complex)) 과 표준 라이브러리 형 fractions.Fraction 과 decimal.Decimal 에 속하는 숫자들은, 복소수가 대소 비교를 지원하지 않는다는 제약 사항만 빼고는, 같거나 다른 형들 간의 비교가 가능합니다. 관련된 형들의 한계 안에서, 정밀도의 손실 없이 수학적으로 (알고리즘 적으로) 올바르게 비교합니다.

The not-a-number values float('NaN') and decimal.Decimal('NaN') are special. Any ordered comparison of a number to a not-a-number value is false. A counter-intuitive implication is that not-a-number values are not equal to themselves. For example, if x = float('NaN'), 3 < x, x < 3 and x == x are all false, while x != x is true. This behavior is compliant with IEEE 754.

바이너리 시퀀스들 (bytes 나 bytearray 의 인스턴스들)은 형을 건너 상호 비교될 수 있습니다. 이것들은 요소들의 숫자 값을 사용해서 사전식으로(lexicographically) 비교합니다.

문자열들 (str 의 인스턴스들) 은 문자들의 유니코드 코드 포인트(Unicode code points) (내장 함수 ord() 의 결과)를 사용해서 사전식으로 비교합니다. 3

문자열과 바이너리 시퀀스는 직접 비교할 수 없습니다.

시퀀스들 (tuple, list, range 의 인스턴스들)은 같은 형끼리 비교될 수 있는데, range는 대소 비교를 지원하지 않습니다. 서로 다른 형들 간의 동등 비교는 다름을 주고, 서로 다른 형들 간의 대소 비교는 TypeError 를 일으킵니다.

시퀀스는 대응하는 요소 간의 비교를 사용해서 사전적으로 비교하는데, 요소들의 반사성(reflexivity)이 강제됩니다.

요소들의 반사성을 강제한다는 것은, 컬렉션의 비교가 컬렉션 요소 x 에 대해, x == x 가 항상 참이라고 가정한다는 것입니다. 그 가정에 기반을 둬서, 요소들의 아이덴티티가 먼저 비교된 후에, 이것이 다를 때만 요소 간의 동등 비교가 수행됩니다. 비교되는 요소들이 반사적일 때, 이런 접근법은 엄밀한 요소 간 비교와 같은 결과를 줍니다. 비 반사적인 요소의 경우, 결과가 엄밀한 요소 비교와 달라질 수 있고, 놀랄 수 있습니다: 예를 들어, 비 반사적인 NaN이 리스트에서 사용될 때 다음과 같은 비교 동작을 보입니다:

>>> nan = float('NaN')
>>> nan is nan
True
>>> nan == nan
False                 <-- the defined non-reflexive behavior of NaN
>>> [nan] == [nan]
True                  <-- list enforces reflexivity and tests identity first

내장 컬렉션들의 사전적인 비교는 다음과 같이 이루어집니다:

두 컬렉션이 같다고 비교되기 위해서는, 같은 형이고, 길이가 같고, 대응하는 요소들의 각 쌍이 같다고 비교되어야 합니다 (예를 들어, [1,2] == (1,2) 는 거짓인데, 형이 다르기 때문입니다).

대소 비교를 지원하는 컬렉션들은 첫 번째로 다른 요소들과 같은 순서를 줍니다 (예를 들어, [1,2,x] <= [1,2,y] 는 x <= y 와 같은 값입니다). 대응하는 요소가 없는 경우 더 짧은 컬렉션이 작다고 비교됩니다 (예를 들어, [1,2] < [1,2,3] 은 참입니다).

매핑들 (dict 의 인스턴스들) 은 같은 (key, value) 쌍들을 가질 때, 그리고 오직 이 경우만 같다고 비교됩니다. 키와 값의 동등 비교는 반사성을 강제합니다.

대소 비교 (<, >, <=, >=) 는 TypeError 를 일으킵니다.

집합들 (set 이나 frozenset 의 인스턴스들)은 같은 형들과 서로 다른 형들 간에 비교될 수 있습니다.

이것들은 부분집합(subset)과 상위집합(superset)을 뜻하는 대소비교 연산자들을 정의합니다. 이 관계는 전 순서(total ordering)를 정의하지 않습니다 (예를 들어, 두 집합 {1,2} 와 {2,3} 는 다르면서도, 하나가 다른 하나의 부분집합이지도, 하나가 다른 하나의 상위집합이지도 않습니다). 따라서, 전 순서에 의존하는 함수의 인자로는 적합하지 않습니다 (예를 들어, min(), max(), sorted() 에 입력으로 집합의 리스트를 제공하면 정의되지 않은 결과를 줍니다).

집합의 비교는 그 요소들의 반사성을 강제합니다.

대부분의 다른 내장형들은 비교 메서드들을 구현하지 않기 때문에, 기본 비교 동작을 계승합니다.

비교 동작을 커스터마이즈하는 사용자 정의 클래스들은 가능하다면 몇 가지 일관성 규칙을 준수해야 합니다:

동등 비교는 반사적(reflexive)이어야 합니다. 다른 말로 표현하면, 아이덴티티가 같은 객체는 같다고 비교되어야 합니다:

x is y 면 x == y 다.

비교는 대칭적(symmetric)이어야 합니다. 다른 말로 표현하면, 다음과 같은 표현식은 같은 결과를 주어야 합니다:

x == y 와 y == x

x != y 와 y != x

x < y 와 y > x

x <= y 와 y >= x

비교는 추이적(transitive)이어야 합니다. 다음 (철저하지 않은) 예들이 이것을 예증합니다:

x > y and y > z 면 x > z 다

x < y and y <= z`` 면 x < z 다

역 비교는 논리적 부정이 되어야 합니다. 다른 말로 표현하면, 다음 표현식들이 같은 값을 주어야 합니다:

x == y 와 not x != y

x < y 와 not x >= y (전 순서의 경우)

x > y 와 not x <= y (전 순서의 경우)

마지막 두 표현식은 전 순서 컬렉션에 적용됩니다 (예를 들어, 시퀀스에는 적용되지만, 집합과 매핑은 그렇지 않습니다). total_ordering() 데코레이터도 보십시오.

hash() 결과는 동등성과 일관성을 유지해야 합니다. 같은 객체들은 같은 해시값을 같거나 해시 불가능으로 지정되어야 합니다.

파이썬은 이 일관성 규칙들을 강제하지 않습니다. 사실 NaN 값들은 이 규칙을 따르지 않는 예입니다.

6.10.2. 멤버십 검사 연산

연산자 in 과 not in 은 멤버십을 검사합니다. x in s 는 x 가 s 의 멤버일 때 True 를, 그렇지 않을 때 False 를 줍니다. x not in s 은 x in s 의 부정을 줍니다. 딕셔너리 뿐만 아니라 모든 내장 시퀀스들과 집합 형들이 이것을 지원하는데, 딕셔너리의 경우는 in 이 딕셔너리에 주어진 키가 있는지 검사합니다. list, tuple, set, frozenset, dict, collections.deque 와 같은 컨테이너형들의 경우, 표현식 x in y 는 any(x is e or x == e for e in y) 와 동등합니다.

문자열과 바이트열 형의 경우, x in y 는 x 가 y 의 부분 문자열(substring)인 경우, 그리고 오직 그 경우만 True 입니다. 동등한 검사는 y.find(x) != -1 입니다. 빈 문자열은 항상 다른 문자열들의 부분 문자열로 취급되기 때문에, "" in "abc" 은 True 를 돌려줍니다.

__contains__() 메서드를 정의하는 사용자 정의 클래스의 경우, x in y 는 y.__contains__(x) 가 참을 줄 때 True 를, 그렇지 않으면 False 를 돌려줍니다.

__contains__() 를 정의하지 않지만 __iter__() 를 정의하는 사용자 정의 클래스의 경우, y 를 이터레이트할 때 표현식 x is z or x == z 를 참이 되게 하는 어떤 값 z 가 만들어지면 x in y 는 True 입니다. 탐색하는 동안 예외가 발생하면 in 이 그 예외를 일으킨 것으로 취급됩니다.

마지막으로, 올드스타일(old-style) 이터레이션 프로토콜을 시도합니다: 클래스가 __getitem__() 를 정의하면, x in y 는 x is y[i] or x == y[i] 를 만족하는 음이 아닌 정수 인덱스 i 가 존재하고, 그보다 작은 모든 정수 인덱스들에 대해 IndexError 예외를 일으키지 않는 경우, 그리고 오직 그 경우만 True 가 됩니다. (그 밖의 예외가 발생하면 in 이 그 예외를 일으킨 것으로 취급됩니다.

연산자 not in 은 in 의 논리적 부정으로 정의됩니다.

6.10.3. 아이덴티티 비교

연산자 is 와 is not 은 객체의 아이덴티티를 검사합니다: x is y 는 x 와 y 가 아이덴티티가 같은 객체일 때, 그리고 오직 그 경우만 참입니다. 객체의 아이덴티티는 id() 함수를 사용해서 결정됩니다. x is not y 은 논리적 부정 값을 줍니다. 4

6.11. 논리 연산(Boolean operations)

or_test  ::=  and_test | or_test "or" and_test
and_test ::=  not_test | and_test "and" not_test
not_test ::=  comparison | "not" not_test

논리 연산의 문맥에서, 그리고 표현식이 제어 흐름 문(control flow statements)에서 사용될 때, 다음 값들은 거짓으로 해석됩니다: False, None, 모든 형의 숫자 0, 빈 문자열과 컨테이너(문자열, 튜플, 리스트, 딕셔너리, 집합, 불변 집합(frozenset)들을 포함합니다). 그 밖의 모든 값은 참으로 해석됩니다. 사용자 정의 객체들은 __bool__() 메서드를 제공해서 자신의 논리값(truth value)을 커스터마이즈 할 수 있습니다.

연산자 not 은 그 인자가 거짓이면 True 를, 그렇지 않으면 False 를 줍니다.

표현식 x and y 는 먼저 x 의 값을 구합니다; x 가 거짓이면 그 값을 돌려줍니다; 그렇지 않으면 y 의 값을 구한 후에 그 결과를 돌려줍니다.

표현식 x or y 는 먼저 x 의 값을 구합니다; x 가 참이면 그 값을 돌려줍니다. 그렇지 않으면 y 의 값을 구한 후에 그 결과를 돌려줍니다.

and 와 or 어느 것도 반환 값이나 그 형을 False 와 True 로 제한하지 않고, 대신 마지막에 값이 구해진 인자를 돌려줌에 주의해야 합니다. 이것은 때로 쓸모가 있습니다, 예를 들어 s 가 문자열이고 비어 있으면 기본값으로 대체되어야 한다면, 표현식 s or 'foo' 는 원하는 값을 제공합니다. not 은 새 값을 만들어야 하므로, 그 인자의 형과 관계없이 논리값(boolean value)을 돌려줍니다 (예를 들어, not 'foo' 는 '' 가 아니라 False 를 만듭니다.)

6.12. 조건 표현식(Conditional expressions)

conditional_expression ::=  or_test ["if" or_test "else" expression]
expression             ::=  conditional_expression | lambda_expr
expression_nocond      ::=  or_test | lambda_expr_nocond

조건 표현식은 (때로 “삼 항 연산자(ternary operator)”라고 불립니다) 모든 파이썬 연산에서 가장 낮은 우선순위를 갖습니다.

표현식 x if C else y 은 먼저 x 대신에 조건 C 의 값을 구합니다. C 가 참이면, x 의 값이 구해지고 그 값을 돌려줍니다; 그렇지 않으면, y 의 값을 구한 후에 그 결과를 돌려줍니다.

조건 표현식에 대한 더 자세한 내용은 PEP 308 [https://www.python.org/dev/peps/pep-0308] 를 참조하세요.

6.13. 람다(Lambdas)

lambda_expr        ::=  "lambda" [parameter_list] ":" expression
lambda_expr_nocond ::=  "lambda" [parameter_list] ":" expression_nocond

람다 표현식은 (때로 람다 형식(lambda forms)이라고 불립니다) 이름 없는 함수를 만드는 데 사용됩니다. 표현식 lambda parameters: expression 는 함수 객체를 줍니다. 이 이름 없는 객체는 이렇게 정의된 함수 객체처럼 동작합니다:

def <lambda>(parameters):
    return expression

매개변수 목록의 문법은 함수 정의 섹션을 보세요. 람다 표현식으로 만들어진 함수는 문장(statements)이나 어노테이션(annotations)을 포함할 수 없음에 주의해야 합니다.

6.14. 표현식 목록(Expression lists)

expression_list    ::=  expression ("," expression)* [","]
starred_list       ::=  starred_item ("," starred_item)* [","]
starred_expression ::=  expression | (starred_item ",")* [starred_item]
starred_item       ::=  expression | "*" or_expr

리스트나 집합 디스플레이의 일부일 때를 제외하고, 최소한 하나의 쉼표를 포함하는 표현식 목록은 튜플을 줍니다. 튜플의 길이는 목록에 있는 표현식의 개수입니다. 표현식들은 왼쪽에서 오른쪽으로 값이 구해집니다.

애스터리스크(asterisk) * 는 이터러블 언 패킹(iterable unpacking)을 나타냅니다. 피연산자는 반드시 이터러블 이어야 합니다. 그 이터러블이 항목들의 시퀀스로 확장되어서, 언 패킹 지점에서 새 튜플, 리스트, 집합에 포함됩니다.

버전 3.5에 추가: 표현식 목록에서의 이터러블 언 패킹, PEP 448 [https://www.python.org/dev/peps/pep-0448] 에서 최초로 제안되었습니다.

끝에 붙는 쉼표는 단일 튜플(single tuple) (소위, 싱글톤(singleton)) 을 만들 때만 필수입니다; 다른 모든 경우에는 생략할 수 있습니다. 끝에 붙는 쉼표가 없는 단일 표현식은 튜플을 만들지 않고, 그 표현식의 값을 줍니다. (빈 튜플을 만들려면, 빈 괄호 쌍을 사용하십시오: ().)

6.15. 값을 구하는 순서

파이썬은 왼쪽에서 오른쪽으로 표현식의 값을 구합니다. 대입의 값을 구하는 동안, 우변의 값이 좌변보다 먼저 구해짐에 주목하십시오.

다음 줄들에서, 표현식은 그들의 끝에 붙은 숫자들의 순서대로 값이 구해집니다:

expr1, expr2, expr3, expr4
(expr1, expr2, expr3, expr4)
{expr1: expr2, expr3: expr4}
expr1 + expr2 * (expr3 - expr4)
expr1(expr2, expr3, *expr4, **expr5)
expr3, expr4 = expr1, expr2

6.16. 연산자 우선순위

다음 표는 파이썬 에서의 연산자 우선순위를 가장 낮은 것 (least binding)에서 가장 높은 것 (most binding) 순으로 요약합니다. 같은 상자에 들어있는 연산자들은 같은 우선순위를 갖습니다. 문법이 명시적으로 주어지지 않는 이상, 연산자들은 이항(binary)입니다. 같은 상자에 있는 연산자들은 왼쪽에서 오른쪽으로 그룹 지어집니다 (거듭제곱은 예외인데, 오른쪽에서 왼쪽으로 그룹 지어집니다).

비교, 멤버십 검사, 아이덴티티 검사들은 모두 같은 우선순위를 갖고 비교 섹션에서 설명한 것처럼 왼쪽에서 오른쪽으로 이어붙이기(chaining) 하는 기능을 갖습니다.

연산자

설명

lambda

람다 표현식

if – else

조건 표현식

or

논리 OR

and

논리 AND

not x

논리 NOT

in, not in, is, is not, <, <=, >, >=, !=, ==

비교, 멤버십 검사와 아이덴티티 검사를 포함합니다

|

비트 OR

^

비트 XOR

&

비트 AND

<<, >>

시프트

+, -

덧셈과 뺄셈

*, @, /, //, %

곱셈, 행렬 곱셈, 나눗셈, 정수 나눗셈, 나머지 5

+x, -x, ~x

양, 음, 비트 NOT

**

거듭제곱 6

await x

어웨이트 표현식

x[index], x[index:index], x(arguments...), x.attribute

서브스크립션, 슬라이싱, 호출, 어트리뷰트 참조

(expressions...),

[expressions...], {key: value...}, {expressions...}

Binding or parenthesized expression, list display, dictionary display, set display

각주

1

abs(x%y) < abs(y) 이 수학적으로는 참이지만, float의 경우에는 소수점 자름(roundoff) 때문에 수치적으로 참이 아닐 수 있습니다. 예를 들어, 파이썬 float가 IEEE 754 배정도 숫자인 플랫폼을 가정할 때, -1e-100 % 1e100 가 1e100 와 같은 부호를 가지기 위해, 계산된 결과는 -1e-100 + 1e100 인데, 수치적으로는 1e100 과 정확히 같은 값입니다. 함수 math.fmod() 는 부호가 첫 번째 인자의 부호에 맞춰진 결과를 주기 때문에, 이 경우 -1e-100 을 돌려줍니다. 어떤 접근법이 더 적절한지는 응용 프로그램에 달려있습니다.

2

x가 y의 정확한 정수배와 아주 가까우면, 라운딩(rounding) 때문에 x//y 는 (x-x%y)//y 보다 1 클 수 있습니다. 그런 경우, divmod(x,y)[0] * y + x % y 가 x 와 아주 가깝도록 유지하기 위해, 파이썬은 뒤의 결과를 돌려줍니다.

3

유니코드 표준은 코드 포인트(code points) (예를 들어, U+0041) 와 추상 문자(abstract characters) (예를 들어, “LATIN CAPITAL LETTER A”) 를 구분합니다. 유니코드에 있는 대부분의 추상 문자들이 오직 하나의 코드 포인트만으로 표현되지만, 추가로 하나 이상의 코드 포인트의 시퀀스로 표현될 수 있는 추상 문자들이 많이 있습니다. 예를 들어, 추상 문자 “LATIN CAPITAL LETTER C WITH CEDILLA” 는 코드 위치 U+00C7 에 있는 한 개의 복합 문자(precomposed character) 나 코드 위치 U+0043 (LATIN CAPITAL LETTER C) 에 있는 기본 문자(base character) 와 뒤따르는 코드 위치 U+0327 (COMBINING CEDILLA) 에 있는 결합 문자(combining character) 의 시퀀스로 표현될 수 있습니다.

문자열의 비교 연산자는 유니코드 코드 포인트 수준에서 비교합니다. 이것은 사람에게 반 직관적일 수 있습니다. 예를 들어, "\u00C7" == "\u0043\u0327" 는 거짓입니다, 설사 두 문자열이 같은 추상 문자 “LATIN CAPITAL LETTER C WITH CEDILLA”를 표현할지라도 그렇습니다.

문자열을 추상 문자 수준에서 비교하려면 (즉, 사람에게 직관적인 방법으로), unicodedata.normalize() 를 사용하십시오.

4

자동 가비지-수거(automatic garbage-collection)와 자유 목록(free lists)과 디스크립터(descriptor)의 동적인 성격 때문에, is 연산자를 인스턴스 메서드들이나 상수들을 비교하는 것과 같은 특정한 방식으로 사용할 때, 겉으로 보기에 이상한 동작을 감지할 수 있습니다. 더 자세한 정보는 그들의 문서를 확인하십시오.

5

% 연산자는 문자열 포매팅에도 사용됩니다; 같은 우선순위가 적용됩니다.

6

거듭제곱 연산자 ** 는 오른쪽에 오는 산술이나 비트 일 항 연산자보다 약하게 결합합니다, 즉, 2**-1 는 0.5 입니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 언어 레퍼런스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 언어 레퍼런스 »

|

7. 단순문(Simple statements)

단순문은 하나의 논리적인 줄 안에 구성됩니다. 여러 개의 단순문이 세미콜론으로 분리되어 하나의 줄에 나올 수 있습니다. 단순문의 문법은 이렇습니다:

simple_stmt ::=  expression_stmt
                 | assert_stmt
                 | assignment_stmt
                 | augmented_assignment_stmt
                 | annotated_assignment_stmt
                 | pass_stmt
                 | del_stmt
                 | return_stmt
                 | yield_stmt
                 | raise_stmt
                 | break_stmt
                 | continue_stmt
                 | import_stmt
                 | future_stmt
                 | global_stmt
                 | nonlocal_stmt

7.1. 표현식 문

표현식 문은 값을 계산하고 출력하거나, (보통) 프로시저(procedure) (의미 없는 결과를 돌려주는 함수; 파이썬에서 프로시저는 None 값을 돌려줍니다)를 호출하기 위해 (대부분 대화형으로) 사용됩니다. 표현식 문의 다른 사용도 허락되고 때때로 쓸모가 있습니다.

expression_stmt ::=  starred_expression

표현식 문은 (하나의 표현식일 수 있는) 표현식 목록의 값을 구합니다.

대화형 모드에서, 값이 None 이 아니면, 내장 repr() 함수를 사용해 문자열로 변환되고, 그렇게 나온 문자열을 별도의 줄에 표준 출력으로 보냅니다 (결과가 None 일 때는 그렇지 않아서, 프로시저 호출은 어떤 출력도 만들지 않습니다.),

7.2. 대입문

대입문은 이름을 값에 (재)연결하고 가변 객체의 어트리뷰트나 항목들을 수정합니다.

assignment_stmt ::=  (target_list "=")+ (starred_expression | yield_expression)
target_list     ::=  target ("," target)* [","]
target          ::=  identifier
                     | "(" [target_list] ")"
                     | "[" [target_list] "]"
                     | attributeref
                     | subscription
                     | slicing
                     | "*" target

(attributeref, subscription, slicing 의 문법 정의는 프라이머리 섹션을 보십시오.)

대입문은 표현식 목록 (이것이 하나의 표현식일 수도, 쉼표로 분리된 목록일 수도 있는데, 후자의 경우는 튜플이 만들어진다는 것을 기억하십시오) 의 값을 구하고, 왼쪽에서 오른쪽으로, 하나의 결과 객체를 타깃 목록의 각각에 대입합니다.

대입은 타깃 (목록)의 형태에 따라 재귀적으로 정의됩니다. 타깃이 가변 객체의 일부 (어트리뷰트 참조나 서브스크립션이나 슬라이싱) 면, 가변 객체가 최종적으로 대입을 수행해야만 하고, 그것이 올바른지 아닌지를 결정하고, 대입이 받아들여 질 수 없으면 예외를 일으킬 수 있습니다. 다양한 형들이 주시하는 규칙들과 발생하는 예외들은 그 객체 형의 정의에서 주어진다 (표준형 계층 섹션을 보십시오).

객체를 타깃 목록, 괄호나 대괄호로 둘러싸일 수 있는데 생략할 수 있습니다, 에 대입하는 것은 다음과 같이 재귀적으로 정의됩니다.

타깃 목록이 (선택적으로 괄호에 들어있는) 뒤따르는 쉼표가 없는 하나의 타깃이면 객체는 타깃에 대입됩니다.

그렇지 않으면: 객체는 타깃 목록에 나오는 타깃의 수와 같은 수의 항목들을 제공하는 이터러블이어야 하고, 항목들은, 왼쪽에서 오른쪽으로, 대응하는 타깃들에 대입됩니다.

타깃 목록이 애스터리스크(asterisk)를 앞에 붙인 타깃, “스타드(starred)” 타깃이라고 불립니다, 하나를 포함하면: 객체는 적어도 타깃 목록에 나오는 타깃의 수보다 하나 작은 개수의 항목을 제공하는 이터러블이어야 합니다. 이터러블의 처음 항목들은, 왼쪽에서 오른쪽으로, 스타드 타깃 앞에 나오는 타깃들에 대입됩니다. 이터러블의 마지막 항목들은 스타드 타깃 뒤에 나오는 타깃들에 대입됩니다. 이터러블의 나머지 항목들로 구성된 리스트가 스타드 타깃에 대입됩니다 (이 리스트는 비어있을 수 있습니다).

그렇지 않으면: 객체는 타깃 목록에 나오는 타깃의 수와 같은 수의 항목들을 제공하는 이터러블이어야 하고, 항목들은, 왼쪽에서 오른쪽으로, 대응하는 타깃들에 대입됩니다.

하나의 타깃에 대한 객체의 대입은 다음과 같이 재귀적으로 정의됩니다.

타깃이 식별자 (이름) 면:

그 이름이 현재 코드 블록에 있는 global 나 nonlocal 문에 등장하지 않으면: 그 이름은 현재 지역 이름 공간에서 객체에 연결됩니다.

그렇지 않으면: 그 이름은 각각 전역 이름 공간이나 nonlocal 에 의해 결정되는 외부 이름 공간에서 객체에 연결됩니다.

그 이름이 이미 연결되어 있으면 재연결됩니다. 이것은 기존에 연결되어 있던 객체의 참조 횟수가 0이 되도록 만들어서, 객체가 점유하던 메모리가 반납되고 파괴자(destructor) (갖고 있다면) 가 호출되도록 만들 수 있습니다.

타깃이 어트리뷰트 참조면: 참조의 프라이머리 표현식의 값을 구합니다. 이것은 대입 가능한 어트리뷰트를 가진 객체를 주어야 하는데, 그렇지 않으면 TypeError 가 일어납니다. 그에 그 객체에 주어진 어트리뷰트로 객체를 대입하도록 요청합니다; 대입을 수행할 수 없다면 예외 (보통 AttributeError 이지만, 꼭 그럴 필요는 없다) 를 일으킵니다.

주의 사항: 객체가 클래스 인스턴스이고 어트리뷰트 참조가 대입 연산자의 양쪽에서 모두 등장하면, RHS 표현식, a.x 는 인스턴스 어트리뷰트나 (인스턴스 어트리뷰트가 없다면) 클래스 어트리뷰트를 액세스할 수 있습니다. LHS 타깃 a.x 는 항상 필요하면 만들어서라도 항상 인스턴스 어트리뷰트를 설정합니다. 그래서, 두 a.x 가 같은 어트리뷰트를 가리키는 것은 필요조건이 아닙니다: RHS 표현식이 클래스 어트리뷰트를 가리킨다면, LHS 는 대입의 타깃으로 새 인스턴스 어트리뷰트를 만듭니다:

class Cls:
    x = 3             # class variable
inst = Cls()
inst.x = inst.x + 1   # writes inst.x as 4 leaving Cls.x as 3

이 설명이 property() 로 만들어진 프로퍼티(property)와 같은 디스크립터 어트리뷰트에 적용될 필요는 없습니다.

타깃이 서브스크립션이면: 참조에 있는 프라이머리 표현식의 값을 구합니다. (리스트 같은) 가변 시퀀스 객체나 (딕셔너리 같은) 매핑 객체가 나와야 합니다. 그런 다음, 서브 스크립트 표현식의 값을 구합니다.

프라이머리가 (리스트 같은) 가변 시퀀스 객체면, 서브 스크립트는 정수가 나와야 합니다. 음수면, 시퀀스의 길이가 더해집니다. 결괏값은 시퀀스의 길이보다 작은 음이 아닌 정수여야 하고, 시퀀스에 그 인덱스를 가진 항목에 객체를 대입하라고 요청합니다. 인덱스가 범위를 벗어나면, IndexError 를 일으킵니다 (서브 스크립트 된 시퀀스에 대한 대입은 리스트에 새 항목을 추가할 수 없습니다).

프라이머리가 (딕셔너리 같은) 매핑 객체면, 서브 스크립트는 매핑의 키 형과 호환되는 형이어야 하고, 매핑에 그 서브 스크립트를 객체에 매핑하는 키/데이터 쌍을 만들도록 요청합니다. 이때 같은 킷값을 갖는 기존의 키/값 쌍을 대체할 수도 있고, (같은 값의 키가 존재하지 않는 경우) 새 키/값 쌍을 삽입할 수도 있습니다.

사용자 정의 객체의 경우는, 적절한 인자로 __setitem__() 메서드가 호출됩니다.

타깃이 슬라이싱이면: 참조의 프라이머리 표현식의 값을 구합니다. (리스트 같은) 가변 시퀀스 객체가 나와야 합니다. 대입되는 객체는 같은 형의 시퀀스 객체야 합니다. 그런 다음, 존재한다면 하한과 상한 표현식의 값을 구합니다; 기본값은 0과 시퀀스의 길이다. 경곗값은 정수가 되어야 합니다. 둘 중 어느 것이건 음수가 나오면, 시퀀스의 길이를 더합니다. 그렇게 얻어진 경곗값들을 0과 시퀀스의 길이나 그 사이에 들어가는 값이 되도록 자릅니다. 마지막으로 시퀀스 객체에 슬라이스를 대입되는 시퀀스로 변경하도록 요청합니다. 타깃 시퀀스가 허락한다면, 슬라이스의 길이는 대입되는 시퀀스의 길이와 다를 수 있습니다.

CPython implementation detail: 현재 구현에서, 타깃의 문법은 표현식과 같게 유지되고, 잘못된 문법은 코드 생성 단계에서 거부되기 때문에 에러 메시지가 덜 상세해지는 결과를 낳고 있습니다.

설사 대입의 정의가 좌변과 우변 간의 중첩이 ‘동시적(simultaneous)’임을 (예를 들어, a, b = b, a 는 두 변수를 교환합니다) 암시해도, 대입되는 변수들의 컬렉션 안 에서의 중첩은 왼쪽에서 오른쪽으로 일어나서, 때로 혼동할 수 있는 결과를 낳습니다. 예를 들어, 다음과 같은 프로그램은 [0, 2] 를 인쇄합니다:

x = [0, 1]
i = 0
i, x[i] = 1, 2         # i is updated, then x[i] is updated
print(x)

더 보기

PEP 3132 [https://www.python.org/dev/peps/pep-3132] - 확장 이터러블 언 패킹

*target 기능에 대한 규격

7.2.1. 증분 대입문(Augmented assignment statements)

증분 대입문은 한 문장에서 이항 연산과 대입문을 합치는 것입니다:

augmented_assignment_stmt ::=  augtarget augop (expression_list | yield_expression)
augtarget                 ::=  identifier | attributeref | subscription | slicing
augop                     ::=  "+=" | "-=" | "*=" | "@=" | "/=" | "//=" | "%=" | "**="
                               | ">>=" | "<<=" | "&=" | "^=" | "|="

(마지막 세 기호의 문법 정의는 프라이머리 섹션을 보십시오.)

증분 대입은 타깃 (일반 대입문과는 달리 언 패킹이 될 수 없습니다) 과 표현식 목록의 값을 구하고, 둘을 피연산자로 삼아 대입의 형에 맞는 이항 연산을 수행한 후, 원래의 타깃에 그 결과를 대입합니다. 타깃은 오직 한 번만 값이 구해집니다.

x += 1 과 같은 증분 대입 표현은 x = x + 1 처럼 다시 쓸 수 있는데, 정확히 같은 효과는 아니지만 비슷한 결과를 줍니다. 증분 버전에서는, x 의 값을 오직 한 번만 구합니다. 또한, 가능할 때, 실제 연산은 제자리(in-place) 에서 수행되는데, 새 객체를 만들고 그것을 타깃에 대입하기보다는, 예전 객체를 수정한다는 의미입니다.

일반 대입과는 달리, 증분 대입은 우변의 값을 구하기 이전에 좌변의 값을 구합니다. 예를 들어, a[i] += f(x) 는 처음에 a[i] 를 조회한 다음, f(x) 의 값을 구하고, 덧셈을 수행하고, 마지막으로 그 결과를 a[i] 에 다시 씁니다.

하나의 문장에서 튜플과 다중 타깃으로 대입하는 것을 예외로 하면, 증분 대입문에 의한 대입은 일반 대입과 같은 방법으로 처리됩니다. 마찬가지로, 제자리 동작의 가능성을 예외로 하면, 증분 대입 때문에 수행되는 이진 연산은 일반 이진 연산과 같습니다.

어트리뷰트 참조인 타깃의 경우, 일반 대입처럼 클래스와 인스턴스 어트리뷰트에 관한 경고 가 적용됩니다.

7.2.2. 어노테이트된 대입문(Annotated assignment statements)

어노테이션 대입은, 한 문장에서, 변수나 어트리뷰트 어노테이션과 생략할 수 있는 대입문을 합치는 것입니다.

annotated_assignment_stmt ::=  augtarget ":" expression ["=" expression]

일반 대입문 과의 차이점은 오직 하나의 타깃과 오직 하나의 우변 값만 허락된다는 것입니다.

대인 타깃에 단순한 이름을 쓰는 경우, 클래스나 모듈 스코프에 있으면, 어노테이션은 값이 구해진 후 특별한 클래스나 모듈의 어트리뷰트 __annotations__ 에 저장되는데, 이 어트리뷰트는 (만약 비공개면 뒤섞인) 변수 이름을 어노테이션의 값으로 대응시키는 딕셔너리 매핑입니다. 이 어트리뷰트는 쓰기가 허락되고, 클래스나 모듈의 실행을 시작할 때 어노테이션이 정적으로 발견되면 만들어집니다.

대입 타깃으로 표현식을 쓸 때, 어노테이션은 클래스나 모듈 스코프에 있는 것처럼 값이 구해지지만 저장되지는 않습니다.

이름이 함수 스코프에서 어노테이트되면, 이 이름은 그 스코프에 지역적(local)입니다. 함수 스코프에서 어노테이션은 값이 구해지거나 저장되지 않습니다.

우변이 존재하면, 어노테이트된 대입은 (적절한 곳에서) 어노테이션의 값을 구하기 전에 실제 대입을 수행합니다. 표현식 타깃의 경우 우변이 존재하지 않으면, 인터프리터는 티깃의 값을 구하는데, 마지막 __setitem__() 이나 __setattr__() 호출은 생략합니다.

더 보기

PEP 526 [https://www.python.org/dev/peps/pep-0526] - 변수 어노테이션 문법

주석을 통해 표현하는 대신, 변수(클래스 변수와 인스턴스 변수 포함)의 형을 어노테이트 하는 문법을 추가하는 제안.

PEP 484 [https://www.python.org/dev/peps/pep-0484] - 형 힌트

정적 분석 도구와 IDE에서 사용할 수 있는 형 어노테이션에 대한 표준 문법을 제공하기 위해 typing 모듈을 추가하는 제안.

7.3. assert 문

assert 문은 프로그램에 디버깅 어서션(debugging assertion)을 삽입하는 편리한 방법입니다:

assert_stmt ::=  "assert" expression ["," expression]

간단한 형태, assert expression 은 다음과 동등합니다

if __debug__:
    if not expression: raise AssertionError

확장된 형태, assert expression1, expression2 는 다음과 동등합니다

if __debug__:
    if not expression1: raise AssertionError(expression2)

이 동등성 들은 __debug__ 과 AssertionError 가 같은 이름의 내장 변수들을 가리킨다고 가정합니다. 현재 구현에서, 내장 변수 __debug__ 은 일반적인 상황에서 True 이고, 최적화가 요청되었을 때 (명령행 옵션 -O) False 입니다. 현재의 코드 생성기는 컴파일 시점에 최적화가 요청되면 assert 문을 위한 코드를 만들지 않습니다. 에러 메시지에 실패한 표현식의 소스 코드를 포함할 필요가 없음에 주의하십시오; 그것은 스택 트레이스의 일부로 출력됩니다.

__debug__ 에 대한 대입은 허락되지 않습니다. 이 내장 변수의 값은 인터프리터가 시작할 때 결정됩니다.

7.4. pass 문

pass_stmt ::=  "pass"

pass 는 널(null) 연산입니다 — 실행될 때, 아무런 일도 일어나지 않습니다. 문법적으로 문장이 필요하기는 하지만 할 일은 없을 때, 자리를 채우는 용도로 쓸모가 있습니다, 예를 들어:

def f(arg): pass    # a function that does nothing (yet)

class C: pass       # a class with no methods (yet)

7.5. del 문

del_stmt ::=  "del" target_list

삭제는 대입이 정의된 방식과 아주 비슷하게 재귀적으로 정의됩니다. 전체 세부 사항들을 나열하는 대신, 여기 몇 가지 힌트가 있습니다.

타깃 목록의 삭제는 각 타깃을 왼쪽에서 오른쪽으로 재귀적으로 삭제합니다.

이름의 삭제는 같은 코드 블록에 있는 global 문에 그 이름이 등장하는지에 따라 지역이나 전역 이름 공간에서 이름의 연결을 제거합니다. 이름이 연결되어 있지 않으면, NameError 예외가 일어납니다.

어트리뷰트 참조, 서브스크립션, 슬라이싱의 삭제는 관련된 프라이머리 객체로 전달됩니다; 슬라이싱의 삭제는 일반적으로 우변 형의 빈 슬라이스를 대입하는 것과 동등합니다 (하지만 이것조차 슬라이싱 되는 객체가 판단합니다).

버전 3.2에서 변경: 예전에는 이름이 중첩된 블록에서 자유 변수로 등장하는 경우 지역 이름 공간에서 삭제하는 것이 허락되지 않았습니다.

7.6. return 문

return_stmt ::=  "return" [expression_list]

return 은 문법적으로 클래스 정의에 중첩된 경우가 아니라, 함수 정의에만 중첩되어 나타날 수 있습니다.

표현식 목록이 있으면 값을 구하고, 그렇지 않으면 None 으로 치환됩니다.

return 은 표현식 목록 (또는 None)을 반환 값으로 해서, 현재의 함수 호출을 떠납니다.

return 이 finally 절을 가진 try 문에서 제어가 벗어나도록 만드는 경우, 함수로부터 진짜로 벗어나기 전에 그 finally 절이 실행됩니다.

제너레이터 함수에서, return 문은 제너레이터가 끝났음을 가리키고, StopIteration 예외를 일으킵니다. return 문에 제공되는 값은 (있다면) StopIteration 의 생성자에 인자로 전달되어 StopIteration.value 어트리뷰트가 됩니다.

비동기 제너레이터 함수에서, 빈 return 문은 비동기 제너레이터가 끝났음을 알리고, StopAsyncIteration 예외를 일으킵니다. 비동기 제너레이터 함수에서, 비어있지 않은 return 은 문법 에러입니다.

7.7. yield 문

yield_stmt ::=  yield_expression

yield 문은 yield 표현식 과 같은 의미가 있습니다. 동등한 yield 표현식에서 필요로 하는 괄호를 생략하기 위해 yield 문을 사용합니다. 예를 들어, yield 문

yield <expr>
yield from <expr>

은 다음과 같은 yield 표현식 문장들과 동등합니다

(yield <expr>)
(yield from <expr>)

yield 표현식과 문장은 제너레이터 함수를 정의할 때만 사용되고, 제너레이터 함수의 바디에서만 사용됩니다. 함수 정의가 일반 함수 대신 제너레이터 함수를 만들도록 하는 데는 yield를 사용하는 것만으로 충분합니다.

yield 의 뜻에 대한 전체 세부 사항들은 일드 표현식(Yield expressions) 섹션을 참고하면 됩니다.

7.8. raise 문

raise_stmt ::=  "raise" [expression ["from" expression]]

표현식이 주어지지 않으면, raise 는 현재 스코프에서 활성화된 마지막 예외를 다시 일으킵니다. 현재 스코프에 활성화된 예외가 없다면, 이것이 에러라는 것을 알리기 위해 RuntimeError 예외를 일으킵니다.

그렇지 않으면, raise 는 예외 객체로, 첫 번째 표현식의 값을 구합니다. BaseException 의 서브 클래스나 인스턴스여야 합니다. 클래스면, 예외 인스턴스는 필요할 때 인자 없이 클래스의 인스턴스를 만들어서 사용됩니다.

예외의 형(type)은 예외 인스턴스의 클래스고, 값(value)은 인스턴스 자신입니다.

트레이스백 객체는 보통 예외가 일어날 때 자동으로 만들어지고 쓰기 가능한 __traceback__ 어트리뷰트로 첨부됩니다. 다음과 같이, with_traceback() 예외 메서드를 사용하면, 예외를 만들고 트레이스백을 직접 설정하는 것을 한 번에 할 수 있습니다 (같은 예외 인스턴스를 돌려주는데, 그 인자값으로 트레이스백을 설정해줍니다):

raise Exception("foo occurred").with_traceback(tracebackobj)

from 절은 예외 연쇄(exception chaining)에 사용됩니다. 주어진다면, 두 번째 표현식(expression) 은 또 하나의 예외 클래스나 인스턴스야 되는데, 발생한 예외에 (쓰기 가능한) __cause__ 어트리뷰트로 첨부됩니다. 발생한 예외가 처리되지 않으면, 두 예외가 모두 인쇄됩니다:

>>> try:
...     print(1 / 0)
... except Exception as exc:
...     raise RuntimeError("Something bad happened") from exc
...
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
ZeroDivisionError: division by zero

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
RuntimeError: Something bad happened

예외 처리기나 finally 절에서 예외가 발생하면 비슷한 메커니즘이 묵시적으로 적용됩니다: 앞선 예외가 새 예외의 __context__ 어트리뷰트로 첨부됩니다.

>>> try:
...     print(1 / 0)
... except:
...     raise RuntimeError("Something bad happened")
...
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
ZeroDivisionError: division by zero

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
RuntimeError: Something bad happened

예외 연쇄는 from 절에 None 을 지정해서 명시적으로 중지시킬 수 있습니다:

>>> try:
...     print(1 / 0)
... except:
...     raise RuntimeError("Something bad happened") from None
...
Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
RuntimeError: Something bad happened

예외에 대한 더 많은 정보를 예외 섹션에서 발견할 수 있고, 예외를 처리하는 것에 대한 정보는 try 문 섹션에 있습니다.

버전 3.3에서 변경: 이제 raise X from Y 에서 Y 로 None 이 허락됩니다.

버전 3.3에 추가: 예외 문맥(exception context)의 자동 출력을 제한할 수 있는 __suppress_context__ 어트리뷰트

7.9. break 문

break_stmt ::=  "break"

break 는 문법적으로 for 나 while 루프에 중첩되어서만 나타날 수 있습니다. 하지만 그 루프 안의 함수나 클래스 정의에 중첩되지는 않습니다.

가장 가까이서 둘러싸고 있는 루프를 종료하고, 그 루프가 else 절을 갖고 있다면 건너뜁니다(skip).

for 루프가 break 로 종료되면, 루프 제어 타깃은 현재값을 유지합니다.

break 가 finally 절을 가 try 문에서 제어가 벗어나도록 만드는 경우, 루프로부터 진짜로 벗어나기 전에 그 finally 절이 실행됩니다.

7.10. continue 문

continue_stmt ::=  "continue"

continue 는 문법적으로 for 나 while 루프에 중첩되어서만 나타날 수 있습니다. 하지만 그 루프 안의 함수나 클래스 정의 또는 그 루프 내의 finally 에 중첩되지는 않습니다. 가장 가까이서 둘러싸고 있는 루프가 다음 사이클로 넘어가도록 만듭니다.

continue 가 finally 절을 가진 try 문에서 제어가 벗어나도록 만드는 경우, 다음 루트 사이클을 시작하기 전에 그 finally 절이 실행됩니다.

7.11. 임포트(import) 문

import_stmt     ::=  "import" module ["as" identifier] ("," module ["as" identifier])*
                     | "from" relative_module "import" identifier ["as" identifier]
                     ("," identifier ["as" identifier])*
                     | "from" relative_module "import" "(" identifier ["as" identifier]
                     ("," identifier ["as" identifier])* [","] ")"
                     | "from" module "import" "*"
module          ::=  (identifier ".")* identifier
relative_module ::=  "."* module | "."+

(from 절이 없는) 기본 임포트 문은 두 단계로 실행됩니다:

모듈을 찾고, 로드하고, 필요하면 초기화합니다

임포트(import) 문이 등장한 스코프의 지역 이름 공간에 이름이나 이름들을 정의합니다.

문장이 (쉼표로 분리된) 여러 개의 절을 포함하면, 마치 각 절이 별도의 임포트 문에 의해 분리된 것처럼, 두 단계는 절마다 별도로 수행됩니다.

첫 번째 단계, 모듈을 찾고 로드하는 것의 세부 사항은 임포트 시스템 에 있는 섹션에서 아주 상세하게 설명하는데, 임포트될 수 있는 여러 종류의 패키지와 모듈들과 임포트 시스템을 커스터마이즈하는데 사용될 수 있는 모든 훅에 관해서도 설명하고 있습니다.

요청된 모듈이 성공적으로 읽어 들여지면, 세 가지 중 한 방법으로 지역 이름 공간에 소개됩니다:

모듈 이름 뒤에 as 가 오면, as 뒤에 오는 이름이 임포트된 모듈에 직접 연결됩니다.

다른 이름이 지정되지 않고, 임포트되는 모듈이 최상위 모듈이면, 모듈의 이름이 임포트되는 모듈에 대한 참조로 지역 이름 공간에 연결됩니다.

임포트되는 모듈이 최상이 모듈이 아니 라면, 그 모듈을 포함하는 최상위 패키지의 이름이 최상위 패키지에 대한 참조로 지역 이름 공간에 연결됩니다. 임포트된 모듈은 직접적이기보다는 완전히 정규화된 이름(full qualified name)을 통해 액세스 되어야 합니다.

from 형은 약간 더 복잡한 절차를 사용합니다:

from 절에 지정된 모듈을 찾고, 로드하고, 필요하면 초기화합니다

import 절에 지정된 식별자들 각각에 대해:

임포트된 모듈이 그 이름의 어트리뷰트를 가졌는지 검사합니다

없으면, 그 이름의 서브 모듈을 임포트하는 것을 시도한 다음 임포트된 모듈에서 그 어트리뷰트를 다시 검사합니다

어트리뷰트가 발견되지 않으면 ImportError 를 일으킵니다.

그렇지 않으면, 그 값에 대한 참조가 지역 이름 공간에 저장되는데, as 절이 존재하면 거기에서 지정된 이름을 사용하고, 그렇지 않으면 어트리뷰트 이름을 사용합니다

사용 예:

import foo                 # foo imported and bound locally
import foo.bar.baz         # foo.bar.baz imported, foo bound locally
import foo.bar.baz as fbb  # foo.bar.baz imported and bound as fbb
from foo.bar import baz    # foo.bar.baz imported and bound as baz
from foo import attr       # foo imported and foo.attr bound as attr

식별자들의 목록을 스타 ('*') 로 바꾸면, 모듈에 정의된 모든 공개 이름들이 import 문이 등장한 스코프의 지역 이름 공간에 연결됩니다.

모듈에 정의된 공개 이름(public names) 은 모듈의 이름 공간에서 __all__ 이라는 이름의 변수를 검사해서 결정됩니다; 정의되어 있다면, 문자열의 시퀀스여야 하는데, 그 모듈이 정의하거나 임포트하는 이름들입니다. __all__ 에서 지정한 이름들은 모두 공개로 취급되고 반드시 존재해야 합니다. __all__ 이 정의되지 않으면, 모듈의 이름 공간에서 발견되는 이름 중, 밑줄 문자 ('_')로 시작하지 않는 모든 이름이 공개로 취급됩니다. __all__ 는 공개 API 전체를 포함해야 합니다. 이것의 목적은 의도치 않게 API 일부가 아닌 항목들을 노출하는 것을 방지하는 것입니다 (가령 그 모듈이 임포트하고 사용하는 라이브러리 모듈).

임포트의 와일드카드 형태 — from module import * — 는 모듈 수준에서만 허락됩니다. 클래스나 함수 정의에서 사용하려는 시도는 SyntaxError 를 일으킵니다.

임포트할 모듈을 지정할 때 모듈의 절대 이름(absolute name)을 지정할 필요는 없습니다. 모듈이나 패키지가 다른 패키지 안에 포함될 때, 같은 상위 패키지 내에서는 그 패키지 이름을 언급할 필요 없이 상대 임포트(relative import)를 할 수 있습니다. from 뒤에 지정되는 패키지나 모듈 앞에 붙이는 점으로, 정확한 이름을 지정하지 않고도 현재 패키지 계층을 얼마나 거슬러 올라가야 하는지 지정할 수 있습니다. 하나의 점은 이 임포트를 하는 모듈이 존재하는 현재 패키지를 뜻합니다. 두 개의 점은 한 패키지 수준을 거슬러 올라가는 것을 뜻합니다. 세 개의 점은 두 개의 수준을, 등등입니다. 그래서 pkg 패키지에 있는 모듈에서 from . import mod 를 실행하면, pkg.mod 를 임포트하게 됩니다. pkg.subpkg1 안에서 from ..subpkg2 import mod 를 실행하면 pkg.subpkg2.mod 를 임포트하게 됩니다. 상대 임포트에 대한 규격은 패키지 상대 임포트 절에 들어있습니다.

로드할 모듈들을 동적으로 결정하는 응용 프로그램들을 지원하기 위해 importlib.import_module() 이 제공됩니다.

7.11.1. 퓨처 문

퓨처 문(future statement)은 컴파일러가 특정한 모듈을 특별한 문법이나 개념을 사용해서 컴파일하도록 만드는 지시어(directive)인데, 그 기능은 미래에 출시되는 파이썬에서 표준이 되는 것입니다.

퓨처 문의 목적은 언어에 호환되지 않는 변경이 도입된 미래 버전의 파이썬으로 옮겨가는 것을 쉽게 만드는 것입니다. 그 기능이 표준이 되는 배포 이전에 모듈 단위로 새 기능을 사용할 수 있도록 만듭니다.

future_stmt ::=  "from" "__future__" "import" feature ["as" identifier]
                 ("," feature ["as" identifier])*
                 | "from" "__future__" "import" "(" feature ["as" identifier]
                 ("," feature ["as" identifier])* [","] ")"
feature     ::=  identifier

퓨처 문은 모듈의 거의 처음에 나와야 합니다. 퓨처 문 앞에 나올 수 있는 줄들은:

모듈 독스트링(docstring) (있다면),

주석

빈 줄, 그리고

다른 퓨처 문들

파이썬 3.7에서 퓨처 문을 사용해야 하는 유일한 기능은 annotations 입니다.

과거에 퓨처 문을 통해 활성화되던 기능들은 여전히 파이썬 3에 의해 인식됩니다. 이 목록에는 absolute_import, division, generators, generator_stop, unicode_literals, print_function, nested_scopes 및 with_statement 가 포함됩니다. 이것들은 잉여물인데 항상 활성화되고, 오직 과거 호환성을 위해 유지되고 있기 때문입니다.

퓨처 문은 구체적으로는 컴파일 시점에 인식되고 다뤄집니다: 핵심 구성물들의 의미에 대한 변경은 종종 다른 코드 생성을 통해 구현됩니다. 새 기능이 호환되지 않는 (새로운 예약어처럼) 새로운 문법을 도입하는 경우조차 가능한데, 이 경우는 컴파일러가 모듈을 다르게 파싱할 수 있습니다. 그런 결정들은 실행 시점으로 미뤄질 수 없습니다..

배포마다, 컴파일러는 어떤 기능 이름들이 정의되어 있는지 알고, 만약 퓨처 문이 알지 못하는 기능을 포함하고 있으면 컴파일 시점 에러를 일으킵니다.

직접적인 실행 시점의 개념은 다른 임포트 문들과 같습니다: 표준 모듈 __future__, 후에 설명합니다, 다 있고, 퓨처 문이 실행되는 시점에 일반적인 방법으로 임포트됩니다.

흥미로운 실행 시점의 개념들은 퓨처 문에 의해 활성화되는 구체적인 기능들에 달려있습니다.

이런 문장에는 아무것도 특별한 것이 없음에 주의해야 합니다:

import __future__ [as name]

이것은 퓨처 문이 아닙니다; 아무런 특별한 개념이나 문법적인 제약이 없는 평범한 임포트 문일 뿐입니다.

퓨처 문을 포함하는 모듈 M 에 등장하는 내장 함수 exec() 와 compile() 를 호출해서 컴파일되는 코드는, 기본적으로는, 퓨처 문이 지정하는 새 문법과 개념을 사용합니다. 이것은 compile() 에 주는 생략 가능한 인자로 제어될 수 있습니다 — 자세한 내용은 그 함수의 문서를 보십시오.

대화형 인터프리터 프롬프트에서 입력된 퓨처 문은 인터프리터 세션의 남은 기간 효과를 발생시킵니다. 인터프리터가 -i, 실행할 스크립트 이름이 전달됩니다, 옵션으로 시작하고, 그 스크립트가 퓨처 문을 포함하면, 스크립트가 실행된 이후에 시작되는 대화형 세션에서도 효과를 유지합니다.

더 보기

PEP 236 [https://www.python.org/dev/peps/pep-0236] - 백 투 더 __future__

__future__ 메커니즘에 대한 최초의 제안.

7.12. global 문

global_stmt ::=  "global" identifier ("," identifier)*

global 문은 현재 코드 블록 전체에 적용되는 선언입니다. 나열된 식별자들이 전역으로 해석되어야 한다는 뜻입니다. global 선언 없이 자유 변수들이 전역을 가리킬 수 있기는 하지만, global 없이 전역 변수에 값을 대입하는 것은 불가능합니다.

global 문에 나열된 이름들은 같은 코드 블록에서 global 문 앞에 등장할 수 없습니다.

global 문에 나열된 이름들은 형식 매개변수나 for 루프 제어 타깃, 클래스(class) 정의, 함수 정의, 임포트(import) 문, 변수 어노테이션으로 정의되지 않아야 합니다.

CPython implementation detail: 현재 구현이 이 제약들의 일부를 강제하지 않지만, 프로그램은 이 자유를 남용하지 말아야 하는데, 미래의 구현은 그것들을 강제하거나 프로그램의 의미를 예고 없이 변경할 수 있기 때문입니다.

프로그래머의 주의 사향: global 은 파서에 주는 지시자(directive)입니다. global 문과 같은 시점에 파싱되는 코드에만 적용됩니다. 특히, 내장 exec() 함수로 공급되는 문자열이나 코드 객체에 포함된 global 문은 그 함수 호출을 포함하는 코드 블록에는 영향을 주지 않고, 그런 문자열에 포함된 코드 역시 함수 호출을 포함하는 코드에 있는 global 문에 영향을 받지 않습니다. eval() 과 compile() 함수들도 마찬가지입니다.

7.13. nonlocal 문

nonlocal_stmt ::=  "nonlocal" identifier ("," identifier)*

nonlocal 문은 나열된 식별자들이 전역을 제외하고 가장 가까이서 둘러싸는 스코프에서 이미 연결된 변수를 가리키도록 만듭니다. 이것은 중요한데, 연결의 기본 동작이 지역 이름 공간을 먼저 검색하는 것이기 때문입니다. 이 문장은 캡슐화된 코드가 전역 (모듈) 스코프 외에 지역 스코프 밖의 변수들에 재연결할 수 있도록 합니다.

nonlocal 문에 나열된 이름들은, global 문에 나열된 것들과는 달리, 둘러싼 스코프에서 이미 존재하는 연결들을 가리켜야만 합니다 (새 연결이 어떤 스코프에 만들어져야만 하는지 명확하게 결정할 수 없습니다).

nonlocal 문에 나열되는 이름들은 지역 스코프에 이미 존재하는 연결들과 겹치지 않아야 합니다.

더 보기

PEP 3104 [https://www.python.org/dev/peps/pep-3104] - 바깥 스코프에 있는 이름들에 대한 액세스

nonlocal 문의 규격.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 언어 레퍼런스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 언어 레퍼런스 »

|

8. 복합문(Compound statements)

복합문은 다른 문장들(의 그룹들)을 포함합니다; 어떤 방법으로 그 다른 문장들의 실행에 영향을 주거나 제어합니다. 간단하게 표현할 때, 전체 복합문을 한 줄로 쓸 수 있기는 하지만, 일반적으로 복합문은 여러 줄에 걸칩니다.

if, while, for 문장은 전통적인 제어 흐름 구조를 구현합니다. 문장들의 그룹에 대해 try 는 예외 처리기나 정리(cleanup) 코드 또는 그 둘 모두를 지정하는 반면, with 문은 코드 블록 주변으로 초기화와 파이널리제이션 코드를 실행할 수 있도록 합니다. 함수와 클래스 정의 또한 문법적으로 복합문입니다.

복합문은 하나나 그 이상의 ‘절’로 구성됩니다. 절은 헤더와 ‘스위트(suite)’로 구성됩니다. 특정 복합문의 절 헤더들은 모두 같은 들여쓰기 수준을 갖습니다. 각 절 헤더는 특별하게 식별되는 키워드로 시작하고 콜론으로 끝납니다. 스위트는 절에 의해 제어되는 문장들의 그룹입니다. 스위트는 헤더의 콜론 뒤에서 같은 줄에 세미콜론으로 분리된 하나나 그 이상의 단순문일 수 있습니다. 또는 그다음 줄에 들여쓰기 된 하나나 그 이상의 문장들일 수도 있습니다. 오직 후자의 형태만 중첩된 복합문을 포함할 수 있습니다; 다음과 같은 것은 올바르지 않은데, 대체로 뒤따르는 else 절이 있다면 어떤 if 절에 속하는지 명확하지 않기 때문입니다.

if test1: if test2: print(x)

또한, 이 문맥에서 세미콜론이 콜론보다 더 강하게 결합해서, 다음과 같은 예에서, print() 호출들은 모두 실행되거나 어느 하나도 실행되지 않습니다는 것에 주의해야 합니다:

if x < y < z: print(x); print(y); print(z)

요약하면:

compound_stmt ::=  if_stmt
                   | while_stmt
                   | for_stmt
                   | try_stmt
                   | with_stmt
                   | funcdef
                   | classdef
                   | async_with_stmt
                   | async_for_stmt
                   | async_funcdef
suite         ::=  stmt_list NEWLINE | NEWLINE INDENT statement+ DEDENT
statement     ::=  stmt_list NEWLINE | compound_stmt
stmt_list     ::=  simple_stmt (";" simple_stmt)* [";"]

문장들이 항상 NEWLINE 으로 끝나고 DEDENT 가 그 뒤를 따를 수 있음에 주목해야 합니다. 또한, 생략 가능한 연결 절들이 항상 문장을 시작시킬 수 없는 키워드로 시작하기 때문에, 모호함이 없다는 것도 주목하세요 (파이썬에서는 중첩된 if 문이 들여쓰기 되는 것을 요구함으로써 ‘매달린(dangling) else’ 문제를 해결합니다).

명확함을 위해 다음에 오는 절들에서 나오는 문법 규칙들은 각 절을 별도의 줄에 놓도록 포매팅합니다.

8.1. if 문

if 문은 조건부 실행에 사용됩니다:

if_stmt ::=  "if" expression ":" suite
             ("elif" expression ":" suite)*
             ["else" ":" suite]

참이 되는 것을 발견할 때까지 표현식들의 값을 하나씩 차례대로 구해서 정확히 하나의 스위트를 선택합니다 (참과 거짓의 정의는 논리 연산(Boolean operations) 섹션을 보세요); 그런 다음 그 스위트를 실행합니다 (그리고는 if 문의 다른 어떤 부분도 실행되거나 값이 구해지지 않습니다). 모든 표현식들이 거짓이면 else 절의 스위트가 (있다면) 실행됩니다.

8.2. while 문

while 문은 표현식이 참인 동안 실행을 반복하는 데 사용됩니다:

while_stmt ::=  "while" expression ":" suite
                ["else" ":" suite]

이것은 표현식을 반복적으로 검사하고, 참이면, 첫 번째 스위트를 실행합니다; 표현식이 거짓이면 (처음부터 거짓일 수도 있습니다) else 절의 스위트가 (있다면) 실행되고 루프를 종료합니다.

첫 번째 스위트에서 실행되는 break 문은 else 절을 실행하지 않고 루프를 종료합니다. 첫 번째 스위트에서 실행되는 continue 문은 스위트의 나머지 부분을 건너뛰고 표현식의 검사로 돌아갑니다.

8.3. for 문

for 문은 (문자열, 튜플, 리스트 같은) 시퀀스 나 다른 이터러블 객체의 요소들을 이터레이트하는데 사용됩니다:

for_stmt ::=  "for" target_list "in" expression_list ":" suite
              ["else" ":" suite]

표현식 목록은 한 번만 값이 구해집니다; 이터러블 객체가 나와야 합니다. expression_list 의 결과로 이터레이터가 만들어집니다. 그런 다음 이터레이터가 제공하는 항목마다, 이터레이터가 돌려주는 순서대로, 스위트가 한 번씩 실행됩니다. 순환마다 각 항목이 대입의 표준 규칙 (대입문 을 보세요) 으로 타깃 목록에 대입된 다음, 스위트가 실행됩니다. 항목들이 소진되었을 때 (이터레이터가 StopIteration 예외를 일으킬 때나 빈 시퀀스인 경우는 즉시 발생합니다), the else 절의 스위트가 (있다면) 실행되고 루프를 종료합니다.

첫 번째 스위트에서 실행되는 break 문은 else 절을 실행하지 않고 루프를 종료합니다. 첫 번째 스위트에서 실행되는 continue 문은 스위트의 나머지 부분을 건너뛰고 다음 항목으로 넘어가거나, 다음 항목이 없으면 else 절로 갑니다.

for-루프는 타깃 목록의 변수들에 대입합니다. for-루프의 스위트에서 이루어진 것들도 포함해서, 그 변수에 앞서 대입된 값들을 모두 덮어씁니다:

for i in range(10):
    print(i)
    i = 5             # this will not affect the for-loop
                      # because i will be overwritten with the next
                      # index in the range

타깃 목록의 이름들은 루프가 종료될 때 삭제되지 않지만, 시퀀스가 비어있다면, 루프에 의해 전혀 대입이 일어나지 않을 수도 있습니다. 힌트: 내장 함수 range() 는 파스칼의 for i := a to b do 의 효과를 흉내 내는데 적합한 정수의 이터레이터를 돌려줍니다; 예를 들어, list(range(3)) 는 리스트 [0, 1, 2] 를 돌려줍니다.

참고

시퀀스가 루프에 의해 수정될 때는 미묘한 점이 있습니다 (이것은 오직 가변 시퀀스에서만 일어납니다, 가령 리스트). 다음에 어떤 항목이 사용될지를 추적하는 내부 카운터가 사용되고, 각 이터레이션마다 증가합니다. 이 카운터가 시퀀스의 길이에 도달하면 루프가 종료됩니다. 이것은 만약 스위트가 시퀀스에서 현재 (또는 그 이전의) 항목을 삭제하면, 다음 항목을 건너뛰게 된다는 뜻입니다 (다음 항목이 이미 다뤄진 현재 항목의 인덱스를 갖게 되기 때문입니다). 마찬가지로, 스위트가 현재 항목 앞으로 시퀀스에 항목을 삽입하면, 현재 항목은 루프의 다음 순환에서 현재 항목이 한 번 더 다뤄지게 됩니다. 이것은 고약한 버그로 이어질 수 있는데, 전체 시퀀스의 슬라이스로 임시 사본을 만듦으로써 피할 수 있습니다, 예를 들어

for x in a[:]:
    if x < 0: a.remove(x)

8.4. try 문

try 문은 문장 그룹에 대한 예외 처리기나 정리(cleanup) 코드 또는 그 둘 모두를 지정하는 데 사용됩니다.

try_stmt  ::=  try1_stmt | try2_stmt
try1_stmt ::=  "try" ":" suite
               ("except" [expression ["as" identifier]] ":" suite)+
               ["else" ":" suite]
               ["finally" ":" suite]
try2_stmt ::=  "try" ":" suite
               "finally" ":" suite

except 절(들)은 하나나 그 이상의 예외 처리기를 지정합니다. try 절에서 예외가 발생하지 않으면 아무런 예외 처리기도 실행되지 않습니다. try 스위트에서 예외가 발생할 때, 예외 처리기 검색이 시작됩니다. 이 검색은 그 예외에 매치되는 것을 발견할 때까지 except 절을 차례대로 들여다봅니다. 표현식이 없는 except 절이 있다면 가장 마지막에 와야 합니다; 모든 예외와 매치됩니다. 표현식이 있는 except 절의 경우, 표현식의 값을 구하고, 결과 객체가 예외와 “호환” 되면 그 절이 예외에 매치됩니다. 객체는 예외 객체의 클래스나 베이스 클래스일 때, 또는 예외와 호환되는 항목을 포함한 튜플일 때 예외와 호환됩니다.

except 절 중 어느 것도 예외와 매치되지 않으면, 예외 처리기 검색은 둘러싼 코드와 호출 스택에서 계속됩니다. 1

만약 except 절의 헤더에 있는 표현식의 값을 구할 때 예외가 발생하면, 원래의 처리기 검색은 취소되고 둘러싼 코드와 호출 스택에서 새 예외에 대해 검사가 시작됩니다 (try 문 전체가 예외를 일으킨 것으로 취급됩니다).

매치되는 except 절이 발견되면, 예외는 그 except 절에 있는 as 키워드 (가 있다면) 뒤에 지정된 타깃에 대입되고, except 절의 스위트가 실행됩니다. 모든 except 절은 실행 가능한 블록을 가져야 합니다. 블록의 끝에 도달하면, try 문 전체의 뒤에서 일반적인 실행이 계속됩니다. (이것은 같은 예외에 대해 두 개의 중첩된 처리기가 있고, 예외가 안쪽 처리기의 try 절에서 발생했다면, 바깥 처리기는 예외를 처리하지 않게 된다는 뜻이 됩니다.)

예외가 as target 을 사용해서 대입될 때, except 절 끝에서 삭제됩니다. 이것은 마치

except E as N:
    foo

가 이렇게 변환되는 것과 같습니다

except E as N:
    try:
        foo
    finally:
        del N

이것은 except 절 후에 참조하려면 예외를 다른 이름에 대입해야 한다는 뜻입니다. 예외를 제거하는 이유는, 그것에 첨부된 트레이스백으로 인해, 스택 프레임과 참조 순환을 형성해서 다음 가비지 수거가 일어나기 전까지 그 프레임의 모든 지역 변수들을 잡아두기 때문입니다.

except 절의 스위트가 실행되기 전에, 예외의 상세 내용이 sys 모듈에 저장되는데, sys.exc_info() 를 통해 액세스할 수 있습니다. sys.exc_info() 는 예외 클래스, 예외 인스턴스, 예외가 프로그램의 어디에서 발생했는지를 알려주는 트레이스백 객체 (표준형 계층 를 보세요) 로 이루어진 3-튜플을 돌려줍니다. sys.exc_info() 값들은 예외를 처리한 함수로부터 복귀할 때 이전 값으로 복구됩니다.

생략 가능한 else 절은 제어 흐름이 try 스위트를 빠져나가고, 예외가 발생하지 않았고, return, continue 또는 break 문이 실행되지 않으면 실행됩니다. else 절에서 발생하는 예외는 앞에 나오는 except 절에서 처리되지 않습니다.

finally 가 있으면, ‘정리(cleanup)’ 처리기를 지정합니다. except 와 else 절을 포함해서, 먼저 try 절이 실행됩니다. 이 절들의 어디에서건 예외가 일어나면, 예외는 임시 저장됩니다. finally 절이 실행됩니다. 만약 저장된 예외가 있으면, finally 절의 끝에서 다시 발생시킨다. finally 절이 다른 예외를 일으키면, 저장된 예외는 새 예외의 컨텍스트(context) 로 설정됩니다. finally 절이 return 이나 break 문을 실행하면, 저장된 예외는 버립니다.

>>> def f():
...     try:
...         1/0
...     finally:
...         return 42
...
>>> f()
42

finally 절을 실행하는 동안 예외 정보는 프로그램에 제공되지 않습니다.

try…finally 문의 try 스위트에서 return, break, continue 문이 실행될 때, finally 절도 ‘나가는 길에’ 실행됩니다. finally 절에서는 continue 문을 사용할 수 없습니다. (그 이유는 현재 구현에 있는 문제 때문입니다 — 이 제약은 미래에 제거될 수 있습니다).

함수의 반환 값은 마지막에 실행된 return 문으로 결정됩니다. finally 절이 항상 실행되기 때문에, finally 절에서 실행되는 return 문이 항상 마지막에 실행되는 것이 됩니다:

>>> def foo():
...     try:
...         return 'try'
...     finally:
...         return 'finally'
...
>>> foo()
'finally'

예외에 관한 추가의 정보는 예외 섹션에서 찾을 수 있고, 예외를 일으키기 위해 raise 문을 사용하는 것에 관한 정보는 raise 문 섹션에서 찾을 수 있습니다.

8.5. with 문

with 문은 블록의 실행을 컨텍스트 관리자 (with 문 컨텍스트 관리자 섹션을 보세요) 가 정의한 메서드들로 감싸는 데 사용됩니다. 이것은 흔한 try…except…finally 사용 패턴을 편리하게 재사용할 수 있도록 캡슐화할 수 있도록 합니다.

with_stmt ::=  "with" with_item ("," with_item)* ":" suite
with_item ::=  expression ["as" target]

하나의 “item” 을 사용하는 with 문의 실행은 다음과 같이 진행됩니다:

컨텍스트 관리자를 얻기 위해 컨텍스트 표현식 (with_item 에 주어진 expression) 의 값을 구합니다.

나중에 사용하기 위해 컨텍스트 관리자의 __exit__() 가 로드됩니다.

컨텍스트 관리자의 __enter__() 메서드를 호출합니다.

with 문에 타깃이 포함되었으면, 그것에 __enter__() 의 반환 값을 대입합니다.

참고

with 문은 __enter__() 메서드가 에러 없이 돌아왔을 때, __exit__() 가 항상 호출됨을 보장합니다. 그래서, 타깃에 대입하는 동안 에러가 발생하면, 스위트 안에서 에러가 발생한 것과 같이 취급됩니다. 아래의 6단계를 보세요.

스위트가 실행됩니다.

컨텍스트 관리자의 __exit__() 메서드를 호출합니다. 예외가 스위트를 종료되도록 만들었다면, 그것의 형, 값, 트레이스백이 __exit__() 의 인자로 전달됩니다. 그렇지 않으면 세 개의 None 이 인자로 공급됩니다.

스위트가 예외 때문에 종료되었고, __exit__() 메서드의 반환 값이 거짓이면, 그 예외를 다시 일으킨다. 반환 값이 참이면, 예외를 억누르고, with 문 뒤에 오는 문장으로 실행을 계속합니다.

스위트가 예외 이외의 이유로 종료되면, __exit__() 의 반환 값은 무시되고, 해당 종료의 종류에 맞는 위치에서 실행을 계속합니다.

하나 보다 많은 항목을 주면, 컨텍스트 관리자는 with 문이 중첩된 것처럼 진행합니다:

with A() as a, B() as b:
    suite

는 다음과 동등합니다

with A() as a:
    with B() as b:
        suite

버전 3.1에서 변경: 다중 컨텍스트 표현식의 지원

더 보기

PEP 343 [https://www.python.org/dev/peps/pep-0343] - “with” 문

파이썬 with 문의 규격, 배경, 예.

8.6. 함수 정의

함수 정의는 사용자 정의 함수 객체 (표준형 계층 섹션을 보세요) 를 정의합니다:

funcdef                 ::=  [decorators] "def" funcname "(" [parameter_list] ")"
                             ["->" expression] ":" suite
decorators              ::=  decorator+
decorator               ::=  "@" dotted_name ["(" [argument_list [","]] ")"] NEWLINE
dotted_name             ::=  identifier ("." identifier)*
parameter_list          ::=  defparameter ("," defparameter)* ["," [parameter_list_starargs]]
                             | parameter_list_starargs
parameter_list_starargs ::=  "*" [parameter] ("," defparameter)* ["," ["**" parameter [","]]]
                             | "**" parameter [","]
parameter               ::=  identifier [":" expression]
defparameter            ::=  parameter ["=" expression]
funcname                ::=  identifier

함수 정의는 실행할 수 있는 문장입니다. 실행하면 현재 지역 이름 공간의 함수 이름을 함수 객체 (함수의 실행 가능한 코드를 둘러싼 래퍼(wrapper)). 이 함수 객체는 현재의 이름 공간에 대한 참조를 포함하는데, 함수가 호출될 때 전역 이름 공간으로 사용됩니다.

함수 정의는 함수의 바디를 실행하지 않습니다. 함수가 호출될 때 실행됩니다. 2

함수 정의는 하나나 그 이상의 데코레이터 표현식으로 감싸질 수 있습니다. 데코레이터 표현식은 함수가 정의될 때, 함수 정의를 포함하는 스코프에서 값을 구합니다. 그 결과는 콜러블이어야 하는데, 함수 객체만을 인자로 사용해서 호출됩니다. 반환 값이 함수 객체 대신 함수의 이름에 연결됩니다. 여러 개의 데코레이터는 중첩되는 방식으로 적용됩니다. 예를 들어, 다음과 같은 코드

@f1(arg)
@f2
def func(): pass

는 대략 다음과 동등합니다

def func(): pass
func = f1(arg)(f2(func))

원래의 함수가 임시로 이름 func 에 연결되지 않는다는 점만 다릅니다.

하나나 그 이상의 매개변수 들이 parameter = expression 형태를 가질 때, 함수가 “기본 매개변수 값”을 갖는다고 말합니다. 기본값이 있는 매개변수의 경우, 호출할 때 대응하는 인자 를 생략할 수 있고, 그럴 때 매개변수의 기본값이 적용됩니다. 만약 매개변수가 기본값을 가지면, “*” 까지 그 뒤를 따르는 모든 매개변수도 기본값을 가져야 합니다 — 이것은 문법 규칙에서 표현되지 않는 문법적 제약입니다.

함수 정의가 실행될 때, 기본 매개변수 값은 왼쪽에서 오른쪽으로 값이 구해집니다. 이것은 표현식이 함수가 정의될 때 한 번 값이 구해지고, 호출마다 같은 “미리 계산된” 값이 사용된다는 것을 뜻합니다. 이것을 이해하는 것은 특히 기본값이 리스트나 딕셔너리와 같은 가변 객체일 때 중요합니다: 만약 함수가 그 객체를 수정하면 (가령, 리스트에 항목을 추가합니다), 그 결과 기본값이 수정됩니다. 이것은 일반적으로 의도하고 있는 것이 아니다. 이 문제를 회피하는 방법은 기본값으로 None 을 사용하고, 함수 바디에서 명시적으로 검사하는 것입니다, 예를 들어:

def whats_on_the_telly(penguin=None):
    if penguin is None:
        penguin = []
    penguin.append("property of the zoo")
    return penguin

함수 호출의 의미는 섹션 호출 에서 더 자세히 설명됩니다. 함수 호출은 항상 매개변수 목록에서 언급하는 모든 매개변수에 값을 대입하는데, 위치 인자들에서 올 수도, 키워드 인자들에서 올 수도, 기본값에서 올 수도 있습니다. “*identifier” 형태가 존재하면, 남는 위치 매개변수들을 받는 튜플로 초기화됩니다. 기본값은 빈 튜플입니다. “**identifier” 형태가 존재하면, 남는 키워드 인자들을 받는 순서 있는 매핑으로 초기화됩니다. 기본값은 빈 매핑입니다. “*” 나 “*identifier” 뒤에 오는 매개변수들은 키워드 전용 매개변수들이고, 키워드 인자로만 전달될 수 있습니다.

매개변수들은 매개변수 이름 뒤에 오는 “: expression” 형태의 어노테이션을 가질 수 있습니다. 모든 매개변수는 어노테이션을 가질 수 있는데, *identifier 나 **identifier 형태조차 그렇습니다. 함수는 매개변수 목록 뒤에 오는 “-> expression” 형태의 반환(“return”) 어노테이션을 가질 수 있습니다. 이 어노테이션들은 올바른 파이썬 표현식이면 어떤 것이건 될 수 있습니다. 어노테이션의 존재는 함수의 의미를 바꾸지 않습니다. 어노테이션 값들은 함수 객체의 __annotations__ 어트리뷰트에서 매개변수의 이름을 키로 하는 딕셔너리의 값으로 제공됩니다. __future__ 에서 annotations 을 임포트하면, 지연된 평가가 활성화되어 어노테이션은 실행시간에 문자열로 보존됩니다. 그렇지 않으면 함수 정의가 실행될 때 평가됩니다. 이 경우 어노테이션은 소스 코드에 나오는 순서와 다른 순서로 평가될 수 있습니다.

표현식에서 즉시 사용하기 위해, 이름 없는 함수(이름에 연결되지 않은 함수)를 만드는 것도 가능합니다. 이것은 람다 표현식을 사용하는데, 람다(Lambdas) 섹션에서 설명합니다. 람다 표현식은 단순화된 함수 정의를 위한 줄임 표현에 지나지 않는다는 것에 주의하세요; “def” 문장에서 정의된 함수는 람다 표현식으로 정의된 함수처럼 전달되거나 다른 이름에 대입될 수 있습니다. 여러 개의 문장을 실행하는 것과 어노테이션을 허락하기 때문에, “def” 형태가 사실 더 강력합니다.

프로그래머 유의 사항: 함수는 퍼스트 클래스(first-class) 객체다. 함수 정의 안에서 실행되는 “def” 문은 돌려주거나 전달할 수 있는 지역 함수를 정의합니다. 중첩된 함수에서 사용되는 자유 변수들은 그 def 를 포함하는 함수의 지역 변수들을 액세스할 수 있습니다. 더 자세한 내용은 이름과 연결(binding) 섹션을 보세요.

더 보기

PEP 3107 [https://www.python.org/dev/peps/pep-3107] - 함수 어노테이션

함수 어노테이션의 최초 규격.

PEP 484 [https://www.python.org/dev/peps/pep-0484] - 형 힌트

어노테이션에 대한 표준 의미 정의: 형 힌트.

PEP 526 [https://www.python.org/dev/peps/pep-0526] - 변수 어노테이션 문법

클래스 변수 및 인스턴스 변수를 포함하는 변수 선언에 형 힌트를 줄 수 있는 기능

PEP 563 [https://www.python.org/dev/peps/pep-0563] - 어노테이션의 지연된 평가

즉시 평가하는 대신 실행시간에 어노테이션을 문자열 형식으로 보존하여 어노테이션 내에서의 전방 참조를 지원합니다.

8.7. 클래스 정의

클래스 정의는 클래스 객체(표준형 계층 섹션을 보세요)를 정의합니다:

classdef    ::=  [decorators] "class" classname [inheritance] ":" suite
inheritance ::=  "(" [argument_list] ")"
classname   ::=  identifier

클래스 정의는 실행 가능한 문장입니다. 계승(inheritance) 목록은 보통 베이스 클래스들의 목록을 제공하는데 (더 고급 사용에 대해서는 메타 클래스 를 보세요), 목록의 각 항목은 값을 구할 때 서브클래싱을 허락하는 클래스 객체가 되어야 합니다. 계승 목록이 없는 클래스는, 기본적으로, 베이스 클래스 object 를 계승합니다; 그래서

class Foo:
    pass

는 다음과 동등합니다

class Foo(object):
    pass

클래스의 스위트는 새로 만들어진 지역 이름 공간과 원래의 전역 이름 공간을 사용하는 새 실행 프레임 (이름과 연결(binding) 을 보세요)에서 실행됩니다. (보통, 스위트는 대부분 함수 정의들을 포함합니다.) 클래스의 스위트가 실행을 마치면, 실행 프레임은 파기하지만, 그것의 지역 이름 공간은 보존합니다. 3 그런 다음, 계승 목록을 베이스 클래스들로, 보존된 지역 이름 공간을 어트리뷰트 딕셔너리로 사용해서 새 클래스 객체를 만듭니다. 클래스의 이름은 원래의 지역 이름 공간에서 이 클래스 객체와 연결됩니다.

클래스 바디에서 어트리뷰트가 정의되는 순서는, 새 클래스의 __dict__ 에 보존됩니다. 이것은 클래스가 만들어진 직후에, 정의 문법을 사용해서 정의되는 클래스들에서만 신뢰할 수 있다는 것에 주의해야 합니다.

클래스 생성은 메타 클래스 를 사용해서 심하게 커스터마이즈할 수 있습니다.

클래스 역시 함수를 데코레이팅할 때처럼 테코레이트할 수 있습니다,

@f1(arg)
@f2
class Foo: pass

는 대략 다음과 동등합니다

class Foo: pass
Foo = f1(arg)(f2(Foo))

데코레이터 표현식의 값을 구하는 규칙은 함수 데코레이터와 같습니다. 그런 다음 그 결과가 클래스 이름에 연결됩니다.

프로그래머 유의 사항: 클래스 정의에서 정의되는 변수들은 클래스 어트리뷰트입니다; 이것들은 인스턴스 간에 공유됩니다. 인스턴스 어트리뷰트는 메서드에서 self.name = value 로 설정될 수 있습니다. 클래스와 인스턴스 어트리뷰트 모두 “self.name” 표기법으로 액세스할 수 있고, 이런 식으로 액세스할 때 인스턴스 어트리뷰트는 같은 이름의 클래스 어트리뷰트를 가립니다. 클래스 어트리뷰트는 인스턴스 어트리뷰트의 기본값으로 사용될 수 있지만, 가변 값을 사용하는 것은 예상하지 않은 결과를 줄 수 있습니다. 디스크립터 를 다른 구현 상세를 갖는 인스턴스 변수를 만드는데 사용할 수 있습니다.

더 보기

PEP 3115 [https://www.python.org/dev/peps/pep-3115] - 파이썬 3000의 메타 클래스

메타 클래스 선언을 현재 문법으로 변경하고, 메타 클래스가 있는 클래스를 구성하는 방법의 의미를 변경하는 제안.

PEP 3129 [https://www.python.org/dev/peps/pep-3129] - 클래스 데코레이터

클래스 데코레이터를 추가하는 제안. 함수와 메서드 데코레이터는 PEP 318 [https://www.python.org/dev/peps/pep-0318]에서 도입되었습니다.

8.8. 코루틴

버전 3.5에 추가.

8.8.1. 코루틴 함수 정의

async_funcdef ::=  [decorators] "async" "def" funcname "(" [parameter_list] ")"
                   ["->" expression] ":" suite

파이썬 코루틴의 실행은 여러 지점에서 일시 중지되거나 재개될 수 있습니다 (코루틴 을 보세요.). 코루틴의 바디 안에서, await 와 async 식별자는 예약 키워드가 됩니다; 어웨이트(await) 표현식, async for, async with 는 코루틴 바디에서만 사용할 수 있습니다.

async def 문법으로 정의된 함수는 항상 코루틴 함수인데, await 나 async 키워드를 포함하지 않는 경우도 그렇습니다.

코루틴 함수의 바디 안에서 yield from 표현식을 사용하는 것은 SyntaxError 입니다.

코루틴 함수의 예:

async def func(param1, param2):
    do_stuff()
    await some_coroutine()

8.8.2. async for 문

async_for_stmt ::=  "async" for_stmt

비동기 이터러블 은 iter 구현에서 비동기 코드를 호출할 수 있고, 비동기 이터레이터 는 next 메서드에서 비동기 코드를 호출할 수 있습니다.

async for 문은 비동기 이터레이터에 대한 편리한 이터레이션을 허락합니다.

다음과 같은 코드는:

async for TARGET in ITER:
    BLOCK
else:
    BLOCK2

의미상으로 다음과 동등합니다:

iter = (ITER)
iter = type(iter).__aiter__(iter)
running = True
while running:
    try:
        TARGET = await type(iter).__anext__(iter)
    except StopAsyncIteration:
        running = False
    else:
        BLOCK
else:
    BLOCK2

더 자세한 내용은 __aiter__() 를 __anext__() 보면 됩니다.

코루틴 함수의 바디 밖에서 async for 문을 사용하는 것은 SyntaxError 입니다.

8.8.3. async with 문

async_with_stmt ::=  "async" with_stmt

비동기 컨텍스트 관리자 는 enter 와 exit 메서드에서 실행을 일시 중지할 수 있는 컨텍스트 관리자 입니다.

다음과 같은 코드는:

async with EXPR as VAR:
    BLOCK

의미상으로 다음과 동등합니다:

mgr = (EXPR)
aexit = type(mgr).__aexit__
aenter = type(mgr).__aenter__(mgr)

VAR = await aenter
try:
    BLOCK
except:
    if not await aexit(mgr, *sys.exc_info()):
        raise
else:
    await aexit(mgr, None, None, None)

더 자세한 내용은 __aenter__() 와 __aexit__() 를 보면 됩니다.

코루틴 함수의 바디 밖에서 async with 문을 사용하는 것은 SyntaxError 입니다.

더 보기

PEP 492 [https://www.python.org/dev/peps/pep-0492] - async 와 await 문법을 사용하는 코루틴

코루틴을 파이썬에서 적절한 독립적인 개념으로 만들고, 문법 지원을 추가한 제안.

각주

1

다른 예외를 일으키는 finally 절이 있지 않은 한 예외는 호출 스택으로 퍼집니다. 그 새 예외는 예전의 것을 잃어버리게 만듭니다.

2

함수 바디의 첫 번째 문장으로 등장하는 문자열 리터럴은 함수의 __doc__ 어트리뷰트로 변환되어 함수의 독스트링 이 됩니다.

3

클래스 바디의 첫 번째 문장으로 등장하는 문자열 리터럴은 그 이름 공간의 __doc__ 항목으로 변환되어 클래스의 독스트링 이 됩니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 언어 레퍼런스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 언어 레퍼런스 »

|

9. 최상위 요소들

파이썬 인터프리터는 여러 가지 출처로부터 입력을 얻을 수 있습니다: 표준 입력이나 프로그램 인자로 전달된 스크립트, 대화형으로 입력된 것, 모듈 소스 파일 등등. 이 장은 이 경우들에 사용되는 문법을 제공합니다.

9.1. 완전한 파이썬 프로그램

언어 규격이 어떤 식으로 언어 인터프리터가 실행되는지를 미리 규정할 필요는 없지만, 완전한 파이썬 프로그램이라는 개념을 갖는 것은 쓸모가 있습니다. 완전한 파이썬 프로그램은 최소한으로 초기화된 환경에서 실행됩니다: 모든 내장과 표준 모듈이 제공되지만, sys (각종 시스템 서비스들)와 builtins (내장 함수들, 예외들, None)과 __main__ 이외의 어느 것도 초기화되지 않았습니다. 마지막 것은 완전한 프로그램의 실행을 위한 지역과 전역 이름 공간을 제공하는 데 사용됩니다.

완전한 파이썬 프로그램의 문법은 다음 섹션에서 설명되는 파일 입력의 경우입니다.

인터프리터는 대화형으로 실행될 수도 있습니다; 이 경우, 완전한 프로그램을 읽어서 실행하지 않고, 한 번에 한 문장 (복합문도 가능하다) 씩 읽어서 실행합니다. 초기 환경은 완전한 프로그램과 같습니다; 각 문장은 __main__ 의 이름 공간에서 실행됩니다.

완전한 프로그램은 세 가지 형태로 인터프리터에게 전달될 수 있습니다: -c string 명령행 옵션으로, 첫 번째 명령행 인자로 전달된 파일로, 표준 입력으로. 파일이나 표준입력이 tty 장치면, 인터프리터는 대화형 모드로 돌입합니다; 그렇지 않으면 그 파일을 완전한 프로그램으로 실행합니다.

9.2. 파일 입력

비대화형 파일로부터 읽힌 모든 입력은 같은 형태를 취합니다:

file_input ::=  (NEWLINE | statement)*

이 문법은 다음과 같은 상황에서 사용됩니다:

(파일이나 문자열로부터 온) 완전한 파이썬 프로그램을 파싱할 때;

모듈을 파싱할 때;

exec() 함수로 전달된 문자열을 파싱할 때;

9.3. 대화형 입력

대화형 모드에서의 입력은 다음과 같은 문법 규칙을 사용합니다:

interactive_input ::=  [stmt_list] NEWLINE | compound_stmt NEWLINE

(최상위) 복합문은 대화형 모드에서 빈 줄을 붙여줘야 함에 유념해야 합니다; 파서가 입력의 끝을 감지하는 데 필요합니다.

9.4. 표현식 입력

표현식 입력을 위해 eval() 이 사용됩니다. 앞에 오는 공백을 무시합니다. eval() 의 문자열 인자는 다음과 같은 형식을 취해야 합니다:

eval_input ::=  expression_list NEWLINE*

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 언어 레퍼런스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 언어 레퍼런스 »

|

10. 전체 문법 규격

이것이 파서 제너레이터가 읽고, 파이썬 소스 파일을 파싱하는데 사용되는 전체 파이썬 문법 규칙입니다:

# Grammar for Python

# NOTE WELL: You should also follow all the steps listed at
# https://devguide.python.org/grammar/

# Start symbols for the grammar:
#       single_input is a single interactive statement;
#       file_input is a module or sequence of commands read from an input file;
#       eval_input is the input for the eval() functions.
# NB: compound_stmt in single_input is followed by extra NEWLINE!
single_input: NEWLINE | simple_stmt | compound_stmt NEWLINE
file_input: (NEWLINE | stmt)* ENDMARKER
eval_input: testlist NEWLINE* ENDMARKER

decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE
decorators: decorator+
decorated: decorators (classdef | funcdef | async_funcdef)

async_funcdef: 'async' funcdef
funcdef: 'def' NAME parameters ['->' test] ':' suite

parameters: '(' [typedargslist] ')'
typedargslist: (tfpdef ['=' test] (',' tfpdef ['=' test])* [',' [
        '*' [tfpdef] (',' tfpdef ['=' test])* [',' ['**' tfpdef [',']]]
      | '**' tfpdef [',']]]
  | '*' [tfpdef] (',' tfpdef ['=' test])* [',' ['**' tfpdef [',']]]
  | '**' tfpdef [','])
tfpdef: NAME [':' test]
varargslist: (vfpdef ['=' test] (',' vfpdef ['=' test])* [',' [
        '*' [vfpdef] (',' vfpdef ['=' test])* [',' ['**' vfpdef [',']]]
      | '**' vfpdef [',']]]
  | '*' [vfpdef] (',' vfpdef ['=' test])* [',' ['**' vfpdef [',']]]
  | '**' vfpdef [',']
)
vfpdef: NAME

stmt: simple_stmt | compound_stmt
simple_stmt: small_stmt (';' small_stmt)* [';'] NEWLINE
small_stmt: (expr_stmt | del_stmt | pass_stmt | flow_stmt |
             import_stmt | global_stmt | nonlocal_stmt | assert_stmt)
expr_stmt: testlist_star_expr (annassign | augassign (yield_expr|testlist) |
                     ('=' (yield_expr|testlist_star_expr))*)
annassign: ':' test ['=' test]
testlist_star_expr: (test|star_expr) (',' (test|star_expr))* [',']
augassign: ('+=' | '-=' | '*=' | '@=' | '/=' | '%=' | '&=' | '|=' | '^=' |
            '<<=' | '>>=' | '**=' | '//=')
# For normal and annotated assignments, additional restrictions enforced by the interpreter
del_stmt: 'del' exprlist
pass_stmt: 'pass'
flow_stmt: break_stmt | continue_stmt | return_stmt | raise_stmt | yield_stmt
break_stmt: 'break'
continue_stmt: 'continue'
return_stmt: 'return' [testlist]
yield_stmt: yield_expr
raise_stmt: 'raise' [test ['from' test]]
import_stmt: import_name | import_from
import_name: 'import' dotted_as_names
# note below: the ('.' | '...') is necessary because '...' is tokenized as ELLIPSIS
import_from: ('from' (('.' | '...')* dotted_name | ('.' | '...')+)
              'import' ('*' | '(' import_as_names ')' | import_as_names))
import_as_name: NAME ['as' NAME]
dotted_as_name: dotted_name ['as' NAME]
import_as_names: import_as_name (',' import_as_name)* [',']
dotted_as_names: dotted_as_name (',' dotted_as_name)*
dotted_name: NAME ('.' NAME)*
global_stmt: 'global' NAME (',' NAME)*
nonlocal_stmt: 'nonlocal' NAME (',' NAME)*
assert_stmt: 'assert' test [',' test]

compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | with_stmt | funcdef | classdef | decorated | async_stmt
async_stmt: 'async' (funcdef | with_stmt | for_stmt)
if_stmt: 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite]
while_stmt: 'while' test ':' suite ['else' ':' suite]
for_stmt: 'for' exprlist 'in' testlist ':' suite ['else' ':' suite]
try_stmt: ('try' ':' suite
           ((except_clause ':' suite)+
            ['else' ':' suite]
            ['finally' ':' suite] |
           'finally' ':' suite))
with_stmt: 'with' with_item (',' with_item)*  ':' suite
with_item: test ['as' expr]
# NB compile.c makes sure that the default except clause is last
except_clause: 'except' [test ['as' NAME]]
suite: simple_stmt | NEWLINE INDENT stmt+ DEDENT

test: or_test ['if' or_test 'else' test] | lambdef
test_nocond: or_test | lambdef_nocond
lambdef: 'lambda' [varargslist] ':' test
lambdef_nocond: 'lambda' [varargslist] ':' test_nocond
or_test: and_test ('or' and_test)*
and_test: not_test ('and' not_test)*
not_test: 'not' not_test | comparison
comparison: expr (comp_op expr)*
# <> isn't actually a valid comparison operator in Python. It's here for the
# sake of a __future__ import described in PEP 401 (which really works :-)
comp_op: '<'|'>'|'=='|'>='|'<='|'<>'|'!='|'in'|'not' 'in'|'is'|'is' 'not'
star_expr: '*' expr
expr: xor_expr ('|' xor_expr)*
xor_expr: and_expr ('^' and_expr)*
and_expr: shift_expr ('&' shift_expr)*
shift_expr: arith_expr (('<<'|'>>') arith_expr)*
arith_expr: term (('+'|'-') term)*
term: factor (('*'|'@'|'/'|'%'|'//') factor)*
factor: ('+'|'-'|'~') factor | power
power: atom_expr ['**' factor]
atom_expr: ['await'] atom trailer*
atom: ('(' [yield_expr|testlist_comp] ')' |
       '[' [testlist_comp] ']' |
       '{' [dictorsetmaker] '}' |
       NAME | NUMBER | STRING+ | '...' | 'None' | 'True' | 'False')
testlist_comp: (test|star_expr) ( comp_for | (',' (test|star_expr))* [','] )
trailer: '(' [arglist] ')' | '[' subscriptlist ']' | '.' NAME
subscriptlist: subscript (',' subscript)* [',']
subscript: test | [test] ':' [test] [sliceop]
sliceop: ':' [test]
exprlist: (expr|star_expr) (',' (expr|star_expr))* [',']
testlist: test (',' test)* [',']
dictorsetmaker: ( ((test ':' test | '**' expr)
                   (comp_for | (',' (test ':' test | '**' expr))* [','])) |
                  ((test | star_expr)
                   (comp_for | (',' (test | star_expr))* [','])) )

classdef: 'class' NAME ['(' [arglist] ')'] ':' suite

arglist: argument (',' argument)*  [',']

# The reason that keywords are test nodes instead of NAME is that using NAME
# results in an ambiguity. ast.c makes sure it's a NAME.
# "test '=' test" is really "keyword '=' test", but we have no such token.
# These need to be in a single rule to avoid grammar that is ambiguous
# to our LL(1) parser. Even though 'test' includes '*expr' in star_expr,
# we explicitly match '*' here, too, to give it proper precedence.
# Illegal combinations and orderings are blocked in ast.c:
# multiple (test comp_for) arguments are blocked; keyword unpackings
# that precede iterable unpackings are blocked; etc.
argument: ( test [comp_for] |
            test '=' test |
            '**' test |
            '*' test )

comp_iter: comp_for | comp_if
sync_comp_for: 'for' exprlist 'in' or_test [comp_iter]
comp_for: ['async'] sync_comp_for
comp_if: 'if' test_nocond [comp_iter]

# not used in grammar, but may appear in "node" passed from Parser to Compiler
encoding_decl: NAME

yield_expr: 'yield' [yield_arg]
yield_arg: 'from' test | testlist

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 언어 레퍼런스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

|

파이썬 표준 라이브러리

파이썬 언어 레퍼런스 는 파이썬 언어의 정확한 문법과 의미를 설명하고 있지만, 이 라이브러리 레퍼런스 설명서는 파이썬과 함께 배포되는 표준 라이브러리를 설명합니다. 또한, 파이썬 배포판에 일반적으로 포함되어있는 선택적 구성 요소 중 일부를 설명합니다.

파이썬의 표준 라이브러리는 매우 광범위하며, 아래 나열된 긴 목차에 표시된 대로 다양한 기능을 제공합니다. 라이브러리에는 일상적인 프로그래밍에서 발생하는 많은 문제에 대한 표준적인 해결책을 제공하는 파이썬으로 작성된 모듈뿐만 아니라, 파일 I/O와 같은 시스템 기능에 액세스하는 (C로 작성된) 내장 모듈들이 포함됩니다 (이 모듈들이 없다면 파이썬 프로그래머가 액세스할 방법은 없습니다). 이 모듈 중 일부는 플랫폼 관련 사항을 플랫폼 중립적인 API들로 추상화시킴으로써, 파이썬 프로그램의 이식성을 권장하고 개선하도록 명시적으로 설계되었습니다.

윈도우 플랫폼용 파이썬 설치 프로그램은 일반적으로 전체 표준 라이브러리를 포함하며 종종 많은 추가 구성 요소도 포함합니다. 유닉스와 같은 운영체제의 경우, 파이썬은 일반적으로 패키지 모음으로 제공되기 때문에, 운영 체제와 함께 제공되는 패키지 도구를 사용하여 선택적 구성 요소의 일부 또는 전부를 구해야 할 수 있습니다.

표준 라이브러리 외에도, 수천 가지 컴포넌트(개별 프로그램과 모듈부터 패키지 및 전체 응용 프로그램 개발 프레임워크까지)가 늘어나고 있는데, 파이썬 패키지 색인 [https://pypi.org] 에서 얻을 수 있습니다.

소개

가용성에 대한 참고 사항

내장 함수

내장 상수

site 모듈에 의해 추가된 상수들

내장형

논리값 검사

논리 연산 — and, or, not

비교

숫자 형 — int, float, complex

이터레이터 형

시퀀스 형 — list, tuple, range

텍스트 시퀀스 형 — str

바이너리 시퀀스 형 — bytes, bytearray, memoryview

집합 형 — set, frozenset

매핑 형 — dict

컨텍스트 관리자 형

기타 내장형

특수 어트리뷰트

Integer string conversion length limitation

내장 예외

베이스 클래스

구체적인 예외

경고

예외 계층 구조

텍스트 처리 서비스

string — 일반적인 문자열 연산

re — Regular expression operations

difflib — 델타 계산을 위한 도우미

textwrap — 텍스트 래핑과 채우기

unicodedata — 유니코드 데이터베이스

stringprep — 인터넷 문자열 준비

readline — GNU readline 인터페이스

rlcompleter — GNU readline을 위한 완성 함수

바이너리 데이터 서비스

struct — Interpret bytes as packed binary data

codecs — Codec registry and base classes

데이터형

datetime — 기본 날짜와 시간 형

calendar — General calendar-related functions

collections — Container datatypes

collections.abc — 컨테이너의 추상 베이스 클래스

heapq — Heap queue algorithm

bisect — 배열 이진 분할 알고리즘

array — 효율적인 숫자 배열

weakref — Weak references

types — 동적 형 생성과 내장형 이름

copy — 얕은 복사와 깊은 복사 연산

pprint — 예쁜 데이터 인쇄기

reprlib — 대안 repr() 구현

enum — Support for enumerations

숫자와 수학 모듈

numbers — 숫자 추상 베이스 클래스

math — Mathematical functions

cmath — 복소수를 위한 수학 함수

decimal — 십진 고정 소수점 및 부동 소수점 산술

fractions — 유리수

random — Generate pseudo-random numbers

statistics — Mathematical statistics functions

함수형 프로그래밍 모듈

itertools — Functions creating iterators for efficient looping

functools — Higher-order functions and operations on callable objects

operator — 함수로서의 표준 연산자

파일과 디렉터리 액세스

pathlib — Object-oriented filesystem paths

os.path — Common pathname manipulations

fileinput — Iterate over lines from multiple input streams

stat — stat() 결과 해석하기

filecmp — 파일과 디렉터리 비교

tempfile — Generate temporary files and directories

glob — 유닉스 스타일 경로명 패턴 확장

fnmatch — 유닉스 파일명 패턴 일치

linecache — 텍스트 줄에 대한 무작위 액세스

shutil — High-level file operations

macpath — Mac OS 9 path manipulation functions

데이터 지속성

pickle — 파이썬 객체 직렬화

copyreg — pickle 지원 함수 등록

shelve — 파이썬 객체 지속성

marshal — 내부 파이썬 객체 직렬화

dbm — 유닉스 “데이터베이스” 인터페이스

sqlite3 — SQLite 데이터베이스용 DB-API 2.0 인터페이스

데이터 압축 및 보관

zlib — Compression compatible with gzip

gzip — gzip 파일 지원

bz2 — bzip2 압축 지원

lzma — Compression using the LZMA algorithm

zipfile — Work with ZIP archives

tarfile — Read and write tar archive files

파일 형식

csv — CSV 파일 읽기와 쓰기

configparser — Configuration file parser

netrc — netrc 파일 처리

xdrlib — XDR 데이터 인코딩과 디코딩

plistlib — 맥 OS X .plist 파일 생성과 구문 분석

암호화 서비스

hashlib — Secure hashes and message digests

hmac — 메시지 인증을 위한 키 해싱

secrets — 비밀 관리를 위한 안전한 난수 생성

일반 운영 체제 서비스

os — 기타 운영 체제 인터페이스

io — Core tools for working with streams

time — Time access and conversions

argparse — 명령행 옵션, 인자와 부속 명령을 위한 파서

getopt — 명령 줄 옵션용 C 스타일 구문 분석기

logging — 파이썬 로깅 시설

logging.config — 로깅 구성

logging.handlers — 로깅 처리기

getpass — 이식성 있는 암호 입력

curses — Terminal handling for character-cell displays

curses.textpad — Text input widget for curses programs

curses.ascii — Utilities for ASCII characters

curses.panel — curses 용 패널 스택 확장

platform — 하부 플랫폼의 식별 데이터에 대한 액세스

errno — 표준 errno 시스템 기호

ctypes — 파이썬용 외부 함수 라이브러리

동시 실행

threading — Thread-based parallelism

multiprocessing — 프로세스 기반 병렬 처리

concurrent 패키지

concurrent.futures — 병렬 작업 실행하기

subprocess — Subprocess management

sched — 이벤트 스케줄러

queue — 동기화된 큐 클래스

_thread — 저수준 스레드 API

_dummy_thread — Drop-in replacement for the _thread module

dummy_threading — Drop-in replacement for the threading module

contextvars — 컨텍스트 변수

컨텍스트 변수

수동 컨텍스트 관리

asyncio 지원

네트워킹과 프로세스 간 통신

asyncio — 비동기 I/O

socket — 저수준 네트워킹 인터페이스

ssl — 소켓 객체용 TLS/SSL 래퍼

select — Waiting for I/O completion

selectors — 고수준 I/O 다중화

asyncore — Asynchronous socket handler

asynchat — Asynchronous socket command/response handler

signal — Set handlers for asynchronous events

mmap — 메모리 맵 파일 지원

인터넷 데이터 처리

email — 전자 메일과 MIME 처리 패키지

json — JSON 인코더와 디코더

mailcap — Mailcap 파일 처리

mailbox — Manipulate mailboxes in various formats

mimetypes — 파일명을 MIME 유형에 매핑

base64 — Base16, Base32, Base64, Base85 데이터 인코딩

binhex — binhex4 파일 인코딩과 디코딩

binascii — 바이너리와 ASCII 간의 변환

quopri — MIME quoted-printable 데이터 인코딩과 디코딩

uu — uuencode 파일 인코딩과 디코딩

구조화된 마크업 처리 도구

html — 하이퍼텍스트 마크업 언어 지원

html.parser — 간단한 HTML과 XHTML 구문 분석기

html.entities — HTML 일반 엔티티의 정의

XML 처리 모듈

xml.etree.ElementTree — The ElementTree XML API

xml.dom — 문서 객체 모델 API

xml.dom.minidom — 최소 DOM 구현

xml.dom.pulldom — 부분 DOM 트리 구축 지원

xml.sax — SAX2 구문 분석기 지원

xml.sax.handler — Base classes for SAX handlers

xml.sax.saxutils — SAX 유틸리티

xml.sax.xmlreader — XML 구문 분석기 인터페이스

xml.parsers.expat — Fast XML parsing using Expat

인터넷 프로토콜과 지원

webbrowser — 편리한 웹 브라우저 제어기

cgi — Common Gateway Interface support

cgitb — CGI 스크립트를 위한 트레이스백 관리자

wsgiref — WSGI 유틸리티와 참조 구현

urllib — URL 처리 모듈

urllib.request — Extensible library for opening URLs

urllib.response — Response classes used by urllib

urllib.parse — Parse URLs into components

urllib.error — urllib.request에 의해 발생하는 예외 클래스

urllib.robotparser — robots.txt 구문 분석기

http — HTTP 모듈

http.client — HTTP protocol client

ftplib — FTP protocol client

poplib — POP3 프로토콜 클라이언트

imaplib — IMAP4 protocol client

nntplib — NNTP protocol client

smtplib — SMTP protocol client

smtpd — SMTP Server

telnetlib — 텔넷 클라이언트

uuid — RFC 4122 에 따른 UUID 객체

socketserver — A framework for network servers

http.server — HTTP servers

http.cookies — HTTP 상태 관리

http.cookiejar — Cookie handling for HTTP clients

xmlrpc — XMLRPC 서버와 클라이언트 모듈

xmlrpc.client — XML-RPC client access

xmlrpc.server — 기본 XML-RPC 서버

ipaddress — IPv4/IPv6 manipulation library

멀티미디어 서비스

audioop — Manipulate raw audio data

aifc — AIFF와 AIFC 파일 읽고 쓰기

sunau — Sun AU 파일 읽고 쓰기

wave — WAV 파일 읽고 쓰기

chunk — IFF 청크된 데이터 읽기

colorsys — 색 체계 간의 변환

imghdr — 이미지 유형 판단

sndhdr — 음향 파일 유형 판단

ossaudiodev — Access to OSS-compatible audio devices

국제화

gettext — Multilingual internationalization services

locale — Internationalization services

프로그램 프레임워크

turtle — Turtle graphics

cmd — 줄 지향 명령 인터프리터 지원

shlex — Simple lexical analysis

Tk를 사용한 그래픽 사용자 인터페이스

tkinter — Tcl/Tk 파이썬 인터페이스

tkinter.ttk — Tk themed widgets

tkinter.tix — Extension widgets for Tk

tkinter.scrolledtext — 스크롤 되는 Text 위젯

IDLE

기타 그래픽 사용자 인터페이스 패키지

개발 도구

typing — Support for type hints

pydoc — 설명서 생성과 온라인 도움말 시스템

doctest — 대화형 파이썬 예제 테스트

unittest — 단위 테스트 프레임워크

unittest.mock — mock object library

unittest.mock — getting started

2to3 - 파이썬 2에서 파이썬 3으로 자동 코드 변환

test — Regression tests package for Python

test.support — Utilities for the Python test suite

test.support.script_helper — Utilities for the Python execution tests

디버깅과 프로파일링

bdb — Debugger framework

faulthandler — 파이썬 트레이스백 덤프

pdb — 파이썬 디버거

The Python Profilers

timeit — 작은 코드 조각의 실행 시간 측정

trace — 파이썬 문장 실행 추적

tracemalloc — Trace memory allocations

소프트웨어 패키징 및 배포

distutils — 파이썬 모듈 빌드와 설치

ensurepip — pip 설치 프로그램 부트스트랩

venv — 가상 환경 생성

zipapp — Manage executable Python zip archives

파이썬 실행시간 서비스

sys — System-specific parameters and functions

sysconfig — 파이썬의 구성 정보에 접근하기

builtins — 내장 객체

__main__ — 최상위 스크립트 환경

warnings — Warning control

dataclasses — 데이터 클래스

contextlib — Utilities for with-statement contexts

abc — 추상 베이스 클래스

atexit — 종료 처리기

traceback — 스택 트레이스백 인쇄와 조회

__future__ — 퓨처 문 정의

gc — 가비지 수거기 인터페이스

inspect — Inspect live objects

site — 사이트별 구성 훅

사용자 정의 파이썬 인터프리터

code — 인터프리터 베이스 클래스

codeop — 파이썬 코드 컴파일

모듈 임포트 하기

zipimport — Zip 저장소에서 모듈 임포트

pkgutil — 패키지 확장 유틸리티

modulefinder — 스크립트에서 사용되는 모듈 찾기

runpy — 파이썬 모듈 찾기와 실행

importlib — The implementation of import

파이썬 언어 서비스

parser — Access Python parse trees

ast — Abstract Syntax Trees

symtable — 컴파일러 심볼 테이블 액세스

symbol — 파이썬 구문 분석 트리에 사용되는 상수

token — 파이썬 구문 분석 트리에 사용되는 상수

keyword — 파이썬 키워드 검사

tokenize — 파이썬 소스를 위한 토크나이저

tabnanny — 모호한 들여쓰기 감지

pyclbr — Python module browser support

py_compile — 파이썬 소스 파일 컴파일

compileall — 파이썬 라이브러리 바이트 컴파일하기

dis — Disassembler for Python bytecode

pickletools — 피클 개발자를 위한 도구

기타 서비스

formatter — Generic output formatting

MS 윈도우 특정 서비스

msilib — Read and write Microsoft Installer files

msvcrt — MS VC++ 런타임의 유용한 루틴

winreg — Windows registry access

winsound — 윈도우용 소리 재생 인터페이스

유닉스 특정 서비스

posix — 가장 일반적인 POSIX 시스템 호출

pwd — 암호 데이터베이스

spwd — 섀도 암호 데이터베이스

grp — 그룹 데이터베이스

crypt — 유닉스 비밀번호 확인 함수

termios — POSIX 스타일 tty 제어

tty — 터미널 제어 함수

pty — 의사 터미널 유틸리티

fcntl — fcntl과 ioctl 시스템 호출

pipes — 셸 파이프라인에 대한 인터페이스

resource — 자원 사용 정보

nis — Sun의 NIS(옐로 페이지)에 대한 인터페이스

syslog — 유닉스 syslog 라이브러리 루틴

대체된 모듈

optparse — Parser for command line options

imp — Access the import internals

문서로 만들어지지 않은 모듈

플랫폼 특정 모듈

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

|

소개

“파이썬 라이브러리”에는 여러 가지 구성 요소가 포함되어 있습니다.

여기에는 일반적으로 숫자 및 리스트와 같이 언어의 “핵심” 부분으로 간주하는 데이터형이 포함됩니다. 이러한 형의 경우, 파이썬 언어 핵심은 리터럴의 형식을 정의하고 그 의미에 몇 가지 제약을 가하지만, 의미를 완전히 정의하지는 않습니다. (반면에, 언어 핵심은 연산자의 철자법과 우선순위와 같은 문법적 속성을 정의합니다.)

라이브러리는 또한 내장 함수와 예외를 포함합니다 — import 문을 쓰지 않고도 모든 파이썬 코드에서 사용할 수 있는 객체들입니다. 이들 중 일부는 언어 핵심에 의해 정의되지만, 핵심 의미에 필수적인 것은 아니며 여기에서 설명합니다.

그러나 라이브러리 대부분은 모듈 컬렉션으로 구성됩니다. 이 컬렉션을 나누는 데는 여러 가지 방법이 있습니다. 일부 모듈은 C로 작성되고 파이썬 인터프리터에 내장되어 있습니다; 다른 것은 파이썬으로 작성되고 소스 형식으로 임포트 됩니다. 일부 모듈은 스택 추적 인쇄와 같이 파이썬에 매우 특정한 인터페이스를 제공합니다; 일부는 특정 하드웨어에 대한 액세스와 같이 운영 체제에 특정한 인터페이스를 제공합니다; 다른 것은 월드 와이드 웹과 같은 응용 프로그램 영역에 특정한 인터페이스를 제공합니다. 일부 모듈은 파이썬의 모든 버전과 이식에서 사용할 수 있습니다; 다른 것은 하위 시스템이 지원하거나 요구할 때만 사용할 수 있습니다; 그러나 다른 것들은 파이썬이 컴파일되고 설치될 때 특정 설정 옵션이 선택되었을 때만 사용할 수 있습니다.

이 설명서는 “안쪽에서부터 밖으로” 구성되어 있습니다. 먼저 내장 함수, 데이터형 및 예외, 마지막으로 관련 모듈의 장으로 그룹화된 모듈들을 설명합니다.

즉, 처음부터 이 설명서를 읽고, 지루할 때 다음 장으로 건너뛰면, 파이썬 라이브러리가 지원하는 사용 가능한 모듈과 응용 프로그램 영역에 대한 적당한 개요를 얻게 됩니다. 물론 소설처럼 읽을 필요는 없습니다. (설명서 앞에 있는) 목차를 검색하거나, (뒤에 있는) 색인에서 특정 함수, 모듈 또는 용어를 찾을 수도 있습니다. 그리고 마지막으로, 무작위 주제에 대해 배우는 것을 즐긴다면, 임의의 페이지 번호 (모듈 random 참조)를 선택하고 한두 섹션을 읽으면 됩니다. 이 설명서의 섹션을 읽는 순서와 관계없이, 내장 함수 장에서 시작하는 것이 도움이 되는데, 설명서의 나머지 부분은 이 내용에 익숙하다고 가정하기 때문입니다.

쇼를 시작합시다!

가용성에 대한 참고 사항

“가용성: 유닉스” 참고 사항은 이 기능이 유닉스 시스템에서 일반적으로 발견된다는 것을 뜻합니다. 특정 운영 체제에 이 기능이 존재하는지에 관한 어떠한 주장도 하지 않습니다.

별도로 언급되지 않은 경우, “가용성: 유닉스”를 주장하는 모든 기능은 유닉스 코어를 기반으로 하는 맥 OS X에서 지원됩니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

|

내장 함수

파이썬 인터프리터에는 항상 사용할 수 있는 많은 함수와 형이 내장되어 있습니다. 여기에서 알파벳 순으로 나열합니다.

내장 함수

abs()

delattr()

hash()

memoryview()

set()

all()

dict()

help()

min()

setattr()

any()

dir()

hex()

next()

slice()

ascii()

divmod()

id()

object()

sorted()

bin()

enumerate()

input()

oct()

staticmethod()

bool()

eval()

int()

open()

str()

breakpoint()

exec()

isinstance()

ord()

sum()

bytearray()

filter()

issubclass()

pow()

super()

bytes()

float()

iter()

print()

tuple()

callable()

format()

len()

property()

type()

chr()

frozenset()

list()

range()

vars()

classmethod()

getattr()

locals()

repr()

zip()

compile()

globals()

map()

reversed()

__import__()

complex()

hasattr()

max()

round()

abs(x)

숫자의 절댓값을 돌려줍니다. 인자는 정수 또는 실수입니다. 인자가 복소수면 그 크기가 반환됩니다.

all(iterable)

iterable 의 모든 요소가 참이면 (또는 iterable 이 비어있으면) True 를 돌려줍니다. 다음과 동등합니다:

def all(iterable):
    for element in iterable:
        if not element:
            return False
    return True

any(iterable)

iterable 의 요소 중 어느 하나라도 참이면 True 를 돌려줍니다. iterable이 비어 있으면 False 를 돌려줍니다. 다음과 동등합니다:

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False

ascii(object)

repr() 처럼, 객체의 인쇄 가능한 표현을 포함하는 문자열을 반환하지만, \x 나 \u 또는 \U 이스케이프를 사용하여 repr() 이 돌려주는 문자열에 포함된 비 ASCII 문자를 이스케이프 합니다. 이것은 파이썬 2의 repr() 이 돌려주는 것과 비슷한 문자열을 만듭니다.

bin(x)

정수를 “0b” 가 앞에 붙은 이진 문자열로 변환합니다. 결과는 올바른 파이썬 표현식입니다. x 가 파이썬 int 객체가 아니라면, 정수를 돌려주는 __index__() 메서드를 정의해야 합니다. 몇 가지 예를 들면:

>>> bin(3)
'0b11'
>>> bin(-10)
'-0b1010'

접두어 “0b” 가 필요할 수도, 필요 없을 수도 있다면, 다음 방법의 하나를 사용할 수 있습니다.

>>> format(14, '#b'), format(14, 'b')
('0b1110', '1110')
>>> f'{14:#b}', f'{14:b}'
('0b1110', '1110')

자세한 내용은 format()을 보세요.

class bool([x])

논리값, 즉 True 또는 False 중 하나를 돌려줍니다. x 표준 논리값 검사 절차 를 사용하여 변환됩니다. x 가 거짓이거나 생략되면 False 를 돌려줍니다. 그렇지 않으면``True`` 를 돌려줍니다. bool 클래스는 int (숫자 형 — int, float, complex 참조)의 서브 클래스입니다. 서브 클래스를 더 만들 수 없습니다. 이것의 유일한 인스턴스는 False 와``True`` 입니다 (논리값를 보세요).

버전 3.7에서 변경: x는 이제 위치 전용 매개 변수입니다.

breakpoint(*args, **kws)

이 함수는 호출 지점에서 디버거로 진입하게 만듭니다. 특히 sys.breakpointhook() 을 호출하고 args 와 kws 를 그대로 전달합니다. 기본적으로, sys.breakpointhook() 은 인자를 기대하지 않고 pdb.set_trace()를 호출합니다. 이 경우, 이것은 순전히 편의 기능이므로 pdb를 명시적으로 임포트하거나 디버거에 들어가기 위해 많은 코드를 입력할 필요가 없습니다. 그러나, sys.breakpointhook() 은 다른 함수로 설정될 수 있고, breakpoint() 는 그것을 자동으로 호출하여, 선택한 디버거에 들어갈 수 있도록 합니다.

버전 3.7에 추가.

class bytearray([source[, encoding[, errors]]])

새로운 바이트 배열을 돌려줍니다. bytearray 클래스는 0 <= x < 256 범위에 있는 정수의 가변 시퀀스입니다. bytes 형이 가진 대부분의 메서드뿐만 아니라 (바이트열 과 바이트 배열 연산 를 보세요), 가변 시퀀스 형 에 기술된 가변 시퀀스의 일반적인 메서드 대부분을 갖고 있습니다.

선택적 source 매개변수는 몇 가지 다른 방법으로 배열을 초기화하는 데 사용할 수 있습니다:

문자열 이면, 반드시 encoding 매개변수도 제공해야 합니다 (그리고 선택적으로 errors 도); 그러면 bytearray() 는 str.encode() 를 사용하여 문자열을 바이트로 변환합니다.

정수 면, 배열은 그 크기를 갖고, 널 바이트로 초기화됩니다.

버퍼(buffer) 인터페이스를 제공하는 객체면, 객체의 읽기 전용 버퍼가 바이트 배열을 초기화하는 데 사용됩니다.

이터러블 이면, 범위 0 <= x < 256 의 정수를 제공하는 이터러블이어야 하고, 그 값들이 배열의 초기 내용물로 사용됩니다.

인자가 없으면 크기 0의 배열이 만들어집니다.

바이너리 시퀀스 형 — bytes, bytearray, memoryview와 바이트 배열 객체 도 보세요.

class bytes([source[, encoding[, errors]]])

새로운 “바이트열” 객체를 돌려줍니다. 이 객체는 0 <= x < 256 범위에 있는 정수의 불변 시퀀스입니다. bytes 는 bytearray 의 불변 버전입니다 – 같은 불변 메서드와 같은 인덱싱 및 슬라이싱 동작을 갖습니다.

따라서 생성자 인자는 bytearray() 와 같이 해석됩니다.

바이트열 객체는 리터럴을 사용하여 만들 수도 있습니다 (문자열과 바이트열 리터럴 를 보세요).

바이너리 시퀀스 형 — bytes, bytearray, memoryview, 바이트열 객체 및 바이트열 과 바이트 배열 연산 도 보세요.

callable(object)

Return True if the object argument appears callable, False if not. If this returns True, it is still possible that a call fails, but if it is False, calling object will never succeed. Note that classes are callable (calling a class returns a new instance); instances are callable if their class has a __call__() method.

버전 3.2에 추가: 이 함수는 파이썬 3.0에서 먼저 제거된 다음 파이썬 3.2에서 다시 도입했습니다.

chr(i)

유니코드 코드 포인트가 정수 i 인 문자를 나타내는 문자열을 돌려줍니다. 예를 들어, chr(97) 은 문자열 'a' 를 돌려주고, chr(8364) 는 문자열 '€' 를 돌려줍니다. 이 것은 ord() 의 반대입니다.

인자의 유효 범위는 0에서 1,114,111(16진수로 0x10FFFF)까지입니다. i 가 이 범위 밖에 있을 때 ValueError 가 발생합니다.

@classmethod

메서드를 클래스 메서드로 변환합니다.

인스턴스 메서드가 인스턴스를 받는 것처럼, 클래스 메서드는 클래스를 묵시적인 첫 번째 인자로 받습니다. 클래스 메서드를 선언하려면 이 관용구를 사용합니다:

class C:
    @classmethod
    def f(cls, arg1, arg2, ...): ...

@classmethod 형식은 함수 데코레이터 입니다 – 자세한 내용은 함수 정의를 보세요.

클래스 메서드는 클래스 (C.f() 처럼) 또는 인스턴스 (C().f() 처럼) 를 통해 호출할 수 있습니다. 인스턴스는 클래스만 참조하고 무시됩니다. 파생 클래스에 대해 클래스 메서드가 호출되면, 파생 클래스 객체가 묵시적인 첫 번째 인자로 전달됩니다.

클래스 메서드는 C++ 또는 자바의 정적 메서드와 다릅니다. 그것들을 원하면, staticmethod()를 보세요.

클래스 메서드에 대한 더 자세한 정보를 원하면, 표준형 계층을 참고하세요.

compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1)

source 를 코드 또는 AST 객체로 컴파일합니다. 코드 객체는 exec() 또는 eval() 로 실행할 수 있습니다. source 는 일반 문자열, 바이트열 또는 AST 객체 일 수 있습니다. AST 객체로 작업하는 방법에 대한 정보는 ast 모듈 문서를 참조하세요.

filename 인자는 코드를 읽은 파일을 제공해야 합니다; 파일에서 읽지 않으면 인식 가능한 값을 전달합니다 ('<string>' 이 일반적으로 사용됩니다).

mode 인자는 컴파일해야 하는 코드 종류를 지정합니다; source 가 문장의 시퀀스로 구성되어 있다면 exec, 단일 표현식으로 구성되어 있다면 'eval', 단일 대화형 문장으로 구성되면 'single' 이 될 수 있습니다 (마지막의 경우 None 이외의 값으로 구해지는 표현식 문은 인쇄됩니다).

선택적 인자 flags 와 dont_inherit 는 어떤 퓨처 문이 source 의 컴파일에 영향을 미칠지 제어합니다. 둘 다 제공되지 않는 경우 (또는 둘 다 0의 경우), 코드는 compile() 을 호출하는 코드에 적용되고 있는 퓨처 문으로 컴파일됩니다. flags 인자가 주어지고, dont_inherit 가 없으면 (또는 0) 원래 사용될 것에 더해 flags 인자로 지정된 퓨처 문이 사용됩니다. dont_inherit 가 0이 아닌 정수면 flags 인자가 사용됩니다 – compile을 호출하는 코드에 적용되는 퓨처 문은 무시됩니다.

퓨처 문은 여러 개의 문장을 지정하기 위해 비트 OR 될 수 있는 비트에 의해 지정됩니다. 주어진 기능을 지정하는 데 필요한 비트 필드는 __future__ 모듈의 _Feature 인스턴스에서 compiler_flag 어트리뷰트로 찾을 수 있습니다.

인자 optimize 는 컴파일러의 최적화 수준을 지정합니다; 기본값 -1 은 -O 옵션에 의해 주어진 인터프리터의 최적화 수준을 선택합니다. 명시적 수준은 0 (최적화 없음, __debug__ 이 참입니다), 1 (assert가 제거됩니다, __debug__ 이 거짓입니다) 또는 2 다 (독스트링도 제거됩니다).

이 함수는 컴파일된 소스가 올바르지 않으면 SyntaxError 를 일으키고, 소스에 널 바이트가 들어있는 경우 ValueError 를 일으킵니다.

파이썬 코드를 AST 표현으로 파싱하려면, ast.parse() 를 보세요.

참고

'single' 또는 'eval' mode로 여러 줄 코드를 가진 문자열을 컴파일할 때, 적어도 하나의 개행 문자로 입력을 끝내야 합니다. 이것은 code 모듈에서 문장이 불완전한지 완전한지를 쉽게 탐지하게 하기 위함입니다.

경고

파이썬의 AST 컴파일러에서 스택 깊이 제한으로 인해, AST 객체로 컴파일할 때 충분히 크고 복잡한 문자열로 파이썬 인터프리터가 크래시를 일으키도록 만들 수 있습니다.

버전 3.2에서 변경: 윈도우 및 맥의 줄 바꿈을 사용할 수 있습니다. 또한, 이제는 'exec' mode에서 입력이 줄 넘김 문자로 끝나지 않아도 됩니다. optimize 매개변수가 추가되었습니다.

버전 3.5에서 변경: 이전에는, source 에서 널 바이트가 발견될 때 TypeError 가 발생했습니다.

class complex([real[, imag]])

real + imag*1j 값을 가진 복소수를 돌려주거나 문자열 또는 숫자를 복소수로 변환합니다. 첫 번째 매개변수가 문자열이면 복소수로 해석되며, 두 번째 매개변수 없이 함수를 호출해야 합니다. 두 번째 매개변수는 결코 문자열 일 수 없습니다. 각 인자는 모든 (복소수를 포함한) 숫자 형이 될 수 있습니다. imag 가 생략되면 기본값은 0이고, 생성자는 int 와 float와 같은 숫자 변환으로 사용됩니다. 두 인자가 모두 생략되면 0j 를 돌려줍니다.

참고

문자열을 변환할 때, 문자열은 중앙의 + 또는 - 연산자 주위에 공백을 포함해서는 안 됩니다. 예를 들어, complex('1+2j') 는 괜찮지만 complex('1 + 2j') 는 ValueError 를 일으킵니다.

복소수 형은 숫자 형 — int, float, complex 에서 설명합니다.

버전 3.6에서 변경: 코드 리터럴 처럼 숫자를 밑줄로 그룹화할 수 있습니다.

delattr(object, name)

이것은 setattr() 의 친척뻘입니다. 인자는 객체와 문자열입니다. 문자열은 객체의 어트리뷰트 중 하나의 이름이어야 합니다. 이 함수는 객체가 허용하는 경우 명명된 어트리뷰트를 삭제합니다. 예를 들어, delattr(x, 'foobar') 는 del x.foobar 와 동등합니다.

class dict(**kwarg)

class dict(mapping, **kwarg)

class dict(iterable, **kwarg)

새 딕셔너리를 만듭니다. dict 객체는 딕셔너리 클래스입니다. 이 클래스에 대한 설명서는 dict 및 매핑 형 — dict 을 보세요.

다른 컨테이너의 경우 list, set 및 tuple 클래스와 collections 모듈을 보세요.

dir([object])

인자가 없으면, 현재 지역 스코프에 있는 이름들의 리스트를 돌려줍니다. 인자가 있으면, 해당 객체에 유효한 어트리뷰트들의 리스트를 돌려주려고 시도합니다.

객체에 __dir__() 메서드가 있으면, 이 메서드가 호출되는데, 반드시 어트리뷰트 리스트를 돌려줘야 합니다. 이렇게 하면 커스텀 __getattr__() 또는 __getattribute__() 함수를 구현하는 객체가 dir() 이 어트리뷰트들을 보고하는 방법을 커스터마이즈할 수 있습니다.

객체가 __dir__() 을 제공하지 않으면, 함수는 (정의되었다면) 객체의 __ dict__ 어트리뷰트와 형 객체로부터 정보를 수집하기 위해 최선을 다합니다. 결과로 얻어지는 리스트는 반드시 완전하지는 않으며, 객체가 커스텀 __getattr__() 을 가질 때 부정확할 수도 있습니다.

기본 dir() 메커니즘은 다른 형의 객체에 대해서 다르게 동작하는데, 완전한 정보보다는 가장 적절한 정보를 만들려고 시도하기 때문입니다:

객체가 모듈 객체면, 리스트에는 모듈 어트리뷰트의 이름이 포함됩니다.

객체가 형 또는 클래스 객체면, 리스트에는 그것의 어트리뷰트 이름과 베이스의 어트리뷰트 이름들이 재귀적으로 포함됩니다.

그 밖의 경우, 리스트에는 객체의 어트리뷰트 이름, 해당 클래스의 어트리뷰트 이름 및 해당 클래스의 베이스 클래스들의 어트리뷰트 이름을 재귀적으로 포함합니다.

결과 리스트는 알파벳 순으로 정렬됩니다. 예를 들어:

>>> import struct
>>> dir()   # show the names in the module namespace
['__builtins__', '__name__', 'struct']
>>> dir(struct)   # show the names in the struct module
['Struct', '__all__', '__builtins__', '__cached__', '__doc__', '__file__',
 '__initializing__', '__loader__', '__name__', '__package__',
 '_clearcache', 'calcsize', 'error', 'pack', 'pack_into',
 'unpack', 'unpack_from']
>>> class Shape:
...     def __dir__(self):
...         return ['area', 'perimeter', 'location']
>>> s = Shape()
>>> dir(s)
['area', 'location', 'perimeter']

참고

dir() 은 주로 대화형 프롬프트에서의 사용 편의를 위해 제공되기 때문에, 엄격하거나 일관되게 정의된 이름 집합을 제공하기보다 흥미로운 이름 집합을 제공하려고 시도하며, 상세한 동작은 배포마다 변경될 수 있습니다. 예를 들어, 인자가 클래스면 메타 클래스 어트리뷰트는 결과 리스트에 없습니다.

divmod(a, b)

두 개의 (복소수가 아닌) 숫자를 인자로 취하고 정수 나누기를 사용할 때의 몫과 나머지로 구성된 한 쌍의 숫자를 돌려줍니다. 두 인자의 형이 다른 경우, 이 항 산술 연산자에 대한 규칙이 적용됩니다. 정수의 경우, 결과는 (a // b, a % b) 와 같습니다. 부동 소수점 숫자의 경우 결과는 (q, a % b) 인데, q 는 보통 math.floor(a / b) 이지만, 이보다 1작을 수 있습니다. 어떤 경우건 q * b + a % b 는 a 에 매우 가깝습니다. a % b 는 0이 아닐 때 b 와 같은 부호를 가지며, 0 <= abs(a % b) < abs(b) 가 성립합니다.

enumerate(iterable, start=0)

열거 객체를 돌려줍니다. iterable 은 시퀀스, 이터레이터 또는 이터레이션을 지원하는 다른 객체여야 합니다. enumerate() 에 의해 반환된 이터레이터의 __next__() 메서드는 카운트 (기본값 0을 갖는 start 부터)와 iterable 을 이터레이션 해서 얻어지는 값을 포함하는 튜플을 돌려줍니다.

>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1))
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]

다음과 동등합니다:

def enumerate(sequence, start=0):
    n = start
    for elem in sequence:
        yield n, elem
        n += 1

eval(expression[, globals[, locals]])

인자는 문자열 및 선택적 globals 및 locals다. 제공된 경우, globals 는 딕셔너리여야 합니다. 제공되는 경우, locals 는 모든 매핑 객체가 될 수 있습니다.

expression 인자는 전역 및 지역 이름 공간으로 globals 및 locals 딕셔너리를 사용하여 파이썬 표현식(기술적으로 말하면, 조건 목록)으로 파싱 되고 값이 구해집니다. globals 사전이 제공되고 키 ‘__builtins__’의 값을 담고 있지 않으면, expression를 구문 분석하기 전에 내장 모듈 builtins의 딕셔너리에 대한 참조를 그 키로 삽입합니다. 이는 expression 이 일반적으로 표준 builtins 모듈에 대한 모든 액세스 권한을 가지며 제한된 환경이 전파됨을 뜻합니다. locals 딕셔너리를 생략하면 기본적으로 globals 딕셔너리가 사용됩니다. 두 딕셔너리가 모두 생략되면, 표현식은 eval() 이 호출되는 환경에서 실행됩니다. 반환 값은 계산된 표현식의 결과입니다. 문법 에러는 예외로 보고됩니다. 예:

>>> x = 1
>>> eval('x+1')
2

이 함수는 임의의 코드 객체 (compile()로 만든 것과 같은)를 실행하는 데에도 사용할 수 있습니다. 이 경우 문자열 대신 코드 객체를 전달합니다. 코드 객체가 mode 인자 'exec' 로 컴파일되었다면, eval() 의 반환 값은 None 입니다.

힌트: 문장의 동적 실행은 exec() 함수에 의해 지원됩니다. globals()와 locals() 함수는 각각 현재의 전역과 지역 딕셔너리를 반환하는데, eval() 또는 exec() 에 전달하는 데 유용합니다.

리터럴 만 포함 된 표현식의 값을 안전하게 구할 수 있는 함수 ast.literal_eval() 를 보세요.

exec(object[, globals[, locals]])

이 함수는 파이썬 코드의 동적 실행을 지원합니다. object 는 문자열 또는 코드 객체여야 합니다. 문자열이면 문자열은 파이썬 문장들의 스위트로 파싱된 후 (문법 에러가 발생하지 않는 한) 실행됩니다. 1 코드 객체면, 단순히 실행됩니다. 모든 경우에, 실행되는 코드는 파일 입력으로 올바를 것이 기대됩니다 (레퍼런스 설명서의 “파일 입력” 섹션을 보세요). return과 yield 문은 exec() 함수에 전달 된 코드 문맥 안에서조차도 함수 정의 밖에서 사용될 수 없음에 유의하세요. 반환 값은 None 입니다.

모든 경우에, 선택적 부분을 생략하면, 현재 스코프에서 코드가 실행됩니다. globals 만 제공된 경우, 사전이어야 하며, 전역과 지역 변수 모두에 사용됩니다. globals 및 locals 가 주어지면, 전역과 지역 변수에 각각 사용됩니다. 제공되는 경우, locals 는 모든 매핑 객체가 될 수 있습니다. 모듈 수준에서, 전역과 지역은 같은 딕셔너리임을 기억하세요. exec 가 globals 와 locals 로 별도의 객체를 받으면, 코드는 클래스 정의에 포함된 것처럼 실행됩니다.

globals 딕셔너리가 __builtins__ 를 키로 하는 값을 갖고 있지 않으면, 그 키로 내장 모듈 builtins 에 대한 참조가 삽입됩니다. 이런 식으로 exec() 에 전달하기 전에 globals 에 여러분 자신의 __builtins__ 딕셔너리를 삽입함으로써, 실행되는 코드에 어떤 내장 객체들이 제공될지를 제어할 수 있습니다.

참고

내장 함수 globals()와 locals() 는 각각 현재 전역 및 지역 딕셔너리를 돌려주는데, exec() 로 전달되는 두 번째 및 세 번째 인자로 사용하는 데 유용합니다.

참고

기본 locals 는 아래 함수 locals() 에 설명된 대로 작동합니다: 기본 locals 사전에 대해 수정이 시도되어서는 안 됩니다. 함수 exec() 가 돌아온 후에 locals 에 코드가 만든 효과를 보려면 명시적으로 locals 딕셔너리를 전달해야 합니다.

filter(function, iterable)

function 이 참을 돌려주는 iterable 의 요소들로 이터레이터를 구축합니다. iterable 은 시퀀스, 이터레이션을 지원하는 컨테이너 또는 이터레이터 일 수 있습니다. function 이 None 이면, 항등함수가 가정됩니다, 즉, 거짓인 iterable 의 모든 요소가 제거됩니다.

filter(function, iterable) 는 function이 None 이 아닐 때 제너레이터 표현식 (item for item in iterable if function(item)) 과, None 일 때 (item for item in iterable if item) 와 동등함에 유의하세요.

function 이 거짓을 돌려주는 iterable 의 요소들을 돌려주는 상보적인 함수는 itertools.filterfalse() 를 보세요.

class float([x])

숫자 또는 문자열 x 로 부터 실수를 만들어 돌려줍니다.

인자가 문자열이면, 십진수를 포함해야 하고, 선택적으로 부호가 앞에 오며 선택적으로 공백으로 둘러싸일 수 있습니다. 선택적 부호는 '+' 또는 '-' 일 수 있습니다; '+' 부호는 생성되는 값에 아무런 영향을 주지 않습니다. 인자는 NaN (not-a-number) 또는 양 또는 음의 무한대를 나타내는 문자열 일 수도 있습니다. 더욱 정확하게, 입력은 앞과 뒤의 공백 문자를 제거한 후 다음 문법을 따라야 합니다:

sign           ::=  "+" | "-"
infinity       ::=  "Infinity" | "inf"
nan            ::=  "nan"
numeric_value  ::=  floatnumber | infinity | nan
numeric_string ::=  [sign] numeric_value

여기서 floatnumber 는 실수 리터럴 에 설명된 파이썬 실수 리터럴의 형식입니다. 대/소문자는 중요하지 않아서, 예를 들면, “inf”, “Inf”, “INFINITY” 및 “iNfINity”는 모두 양의 무한대에 대해 허용되는 철자입니다.

그렇지 않으면, 인자가 정수 또는 실수면 (파이썬의 부동 소수점 정밀도 내에서) 같은 값을 가진 실수가 반환됩니다. 인자가 파이썬 float 범위를 벗어나면, OverflowError 가 발생합니다.

일반적인 파이썬 객체 x 의 경우, float (x) 는 x .__ float __ () 로 위임합니다.

인자가 주어지지 않으면, 0.0 을 돌려줍니다.

예:

>>> float('+1.23')
1.23
>>> float('   -12345\n')
-12345.0
>>> float('1e-003')
0.001
>>> float('+1E6')
1000000.0
>>> float('-Infinity')
-inf

float 형은 숫자 형 — int, float, complex 에 설명되어 있습니다.

버전 3.6에서 변경: 코드 리터럴 처럼 숫자를 밑줄로 그룹화할 수 있습니다.

버전 3.7에서 변경: x는 이제 위치 전용 매개 변수입니다.

format(value[, format_spec])

format_spec 의 제어에 따라, value 를 “포맷된” 표현으로 변환합니다. format_spec 의 해석은 value 인자의 형에 의존하지만, 대부분의 내장형에 의해 사용되는 표준 포매팅 문법이 있습니다: 포맷 명세 미니 언어.

기본 format_spec 은 빈 문자열이며 일반적으로 str(value) 를 호출하는 것과 같은 효과를 줍니다.

format(value, format_spec) 에 대한 호출은 type(value).__format__(value, format_spec) 로 번역되는데, value의 __format__() 메서드를 검색할 때 인스턴스 딕셔너리를 건너뜁니다. 메서드 검색이 object 에 도달하고 format_spec 이 비어 있지 않거나, format_spec 또는 반환 값이 문자열이 아닌 경우 TypeError 예외가 발생합니다.

버전 3.4에서 변경: object().__format__(format_spec) 은 format_spec 이 빈 문자열이 아닌 경우 TypeError 를 일으킵니다.

class frozenset([iterable])

새 frozenset 객체를 돌려주는데, 선택적으로 iterable 에서 가져온 요소를 포함합니다. frozenset 은 내장 클래스입니다. 이 클래스에 대한 설명서는 frozenset 과 집합 형 — set, frozenset을 보세요.

다른 컨테이너의 경우 set, list, tuple 및 dict 클래스와 collections 모듈을 보세요.

getattr(object, name[, default])

주어진 이름의 object 어트리뷰트를 돌려줍니다. name 은 문자열이어야 합니다. 문자열이 객체의 어트리뷰트 중 하나의 이름이면, 결과는 그 어트리뷰트의 값입니다. 예를 들어, getattr(x, 'foobar') 는 x.foobar 와 동등합니다. 명명된 어트리뷰트가 없으면, default 가 제공되는 경우 그 값이 반환되고, 그렇지 않으면 AttributeError 가 발생합니다.

globals()

현재 전역 심볼 테이블을 나타내는 딕셔너리를 돌려줍니다. 이것은 항상 현재 모듈의 딕셔너리입니다 (함수 또는 메서드 내에서, 이 모듈은 그것들을 호출하는 모듈이 아니라, 그것들이 정의된 모듈입니다).

hasattr(object, name)

인자는 객체와 문자열입니다. 문자열이 객체의 속성 중 하나의 이름이면 결과는``True` 이고, 그렇지 않으면 False 가 됩니다. (이것은 getattr(object, name) 을 호출하고 AttributeError 를 발생시키는지를 보는 식으로 구현됩니다.)

hash(object)

객체의 해시값을 돌려줍니다 (해시가 있는 경우). 해시값은 정수다. 딕셔너리 조회 중에 딕셔너리 키를 빨리 비교하는 데 사용됩니다. 같다고 비교되는 숫자 값은 같은 해시값을 갖습니다 (1과 1.0의 경우와 같이 형이 다른 경우조차도 그렇습니다).

참고

커스텀 __hash__() 메서드를 가진 객체의 경우, hash() 는 호스트 기계의 비트 폭을 기준으로 반환 값을 잘라 버리는 것에 주의하세요. 자세한 내용은 __hash__() 를 보세요.

help([object])

내장 도움말 시스템을 호출합니다. (이 함수는 대화형 사용을 위한 것입니다.) 인자가 제공되지 않으면, 인터프리터 콘솔에서 대화형 도움말 시스템이 시작됩니다. 인자가 문자열이면 문자열은 모듈, 함수, 클래스, 메서드, 키워드 또는 설명서 주제의 이름으로 조회되고, 도움말 페이지가 콘솔에 인쇄됩니다. 인자가 다른 종류의 객체면, 객체에 대한 도움말 페이지가 만들어집니다.

help()를 호출할 때, 함수의 매개 변수 목록에 슬래시(/)가 표시되면, 슬래시 이전 매개 변수는 위치 전용이라는 것을 의미합니다. 자세한 내용은, 위치 전용 매개 변수에 대한 FAQ 항목을 참조하십시오.

이 함수는 site 모듈에 의해 내장 이름 공간에 추가됩니다.

버전 3.4에서 변경: pydoc 과 inspect 의 변경 사항은 콜러블의 시그니처가 이제 더 포괄적이고 일관성이 있음을 의미합니다.

hex(x)

정수를 “0x” 접두사가 붙은 소문자 16진수 문자열로 변환합니다. x 가 파이썬 int 객체가 아니면, 정수를 돌려주는 __index__() 메서드를 정의해야 합니다. 몇 가지 예:

>>> hex(255)
'0xff'
>>> hex(-42)
'-0x2a'

정수를 대문자 또는 소문자 16진수로, 접두사가 있거나 없는 형태로 변환하려면 다음 방법의 하나를 사용할 수 있습니다:

>>> '%#x' % 255, '%x' % 255, '%X' % 255
('0xff', 'ff', 'FF')
>>> format(255, '#x'), format(255, 'x'), format(255, 'X')
('0xff', 'ff', 'FF')
>>> f'{255:#x}', f'{255:x}', f'{255:X}'
('0xff', 'ff', 'FF')

자세한 내용은 format()을 보세요.

16진수 문자열을 진수 16을 사용해서 정수로 변환하려면 int() 도 보세요.

참고

float에 대한 16진수 문자열 표현을 얻으려면, float.hex() 메서드를 사용하세요.

id(object)

객체의 “아이덴티티”를 돌려준다. 이것은 객체의 수명 동안 유일하고 바뀌지 않음이 보장되는 정수입니다. 수명이 겹치지 않는 두 개의 객체는 같은 id() 값을 가질 수 있습니다.

CPython implementation detail: This is the address of the object in memory.

input([prompt])

prompt 인자가 있으면, 끝에 개행 문자를 붙이지 않고 표준 출력에 씁니다. 그런 다음 함수는 입력에서 한 줄을 읽고, 문자열로 변환해서 (줄 끝의 줄 바꿈 문자를 제거한다) 돌려줍니다. EOF를 읽으면 EOFError 를 일으킵니다. 예:

>>> s = input('--> ')
--> Monty Python's Flying Circus
>>> s
"Monty Python's Flying Circus"

readline 모듈이 로드되었다면, input() 은 그것을 사용하여 정교한 줄 편집과 히스토리 기능을 제공합니다.

class int([x])

class int(x, base=10)

숫자 나 문자열 x 로 부터 만들어진 정수 객체를 돌려줍니다. 인자가 주어지지 않으면 0 을 돌려줍니다. x 가 __int__() 를 정의하면, int(x) 는 x.__int__() 를 돌려줍니다. x 가 __trunc__() 를 정의하면, x.__trunc__() 를 돌려줍니다. 실수의 경우 이 함수는 0 향해 자릅니다.

x 가 숫자가 아니거나 base 가 주어지면, x 는 문자열, bytes, 또는 bytearray 인스턴스여야 하는데, 진수 base 의 integer literal 을 나타내야 합니다. 선택적으로, 리터럴은 (사이에 공백 없이) + 또는 - 를 앞에 붙일 수 있고, 앞뒤로 공백에 둘러싸일 수 있습니다. 진수-n 리터럴은 0에서 n-1까지의 숫자로 구성되며, a 에서 z (또는 A 에서 Z) 가 10에서 35 사이의 값을 가집니다. 기본 base 는 10입니다. 허용되는 값은 0과 2–36입니다. 코드에서의 리터럴 처럼, 진수-2, -8 및 -16 리터럴에는 선택적으로 0b/0B, 0o/0O 또는 0x/0X 접두사가 붙을 수 있습니다. base 0은 코드 리터럴과 똑같이 해석하라는 뜻이기 때문에, 실제 진수는 2, 8, 10 또는 16이고, 그래서 int('010', 0) 는 올바르지 않지만 int('010', 8) 뿐만 아니라 int('010') 도 올바릅니다.

정수 형은 숫자 형 — int, float, complex 에 설명되어 있습니다.

버전 3.4에서 변경: base 가 int 의 인스턴스가 아니고 base 객체가 base.__index__ 메서드를 가지면, 그 진수로 쓸 정수를 얻기 위해 그 메서드를 호출합니다. 예전 버전에서는 base.__index__ 대신에 base.__int__ 가 사용되었습니다.

버전 3.6에서 변경: 코드 리터럴 처럼 숫자를 밑줄로 그룹화할 수 있습니다.

버전 3.7에서 변경: x는 이제 위치 전용 매개 변수입니다.

버전 3.7.14에서 변경: int string inputs and string representations can be limited to help avoid denial of service attacks. A ValueError is raised when the limit is exceeded while converting a string x to an int or when converting an int into a string would exceed the limit. See the integer string conversion length limitation documentation.

isinstance(object, classinfo)

Return True if the object argument is an instance of the classinfo argument, or of a (direct, indirect or virtual) subclass thereof. If object is not an object of the given type, the function always returns False. If classinfo is a tuple of type objects (or recursively, other such tuples), return True if object is an instance of any of the types. If classinfo is not a type or tuple of types and such tuples, a TypeError exception is raised.

issubclass(class, classinfo)

Return True if class is a subclass (direct, indirect or virtual) of classinfo. A class is considered a subclass of itself. classinfo may be a tuple of class objects, in which case every entry in classinfo will be checked. In any other case, a TypeError exception is raised.

iter(object[, sentinel])

이터레이터 객체를 돌려줍니다. 첫 번째 인자는 두 번째 인자의 존재 여부에 따라 매우 다르게 해석됩니다. 두 번째 인자가 없으면, object 는 이터레이션 프로토콜 (__iter__() 메서드)을 지원하는 컬렉션 객체이거나 시퀀스 프로토콜 (0에서 시작하는 정수 인자를 받는 __getitem__() 메서드)을 지원해야 합니다. 이러한 프로토콜 중 아무것도 지원하지 않으면 TypeError 가 일어납니다. 두 번째 인자 sentinel 이 주어지면, object 는 콜러블이어야 합니다. 이 경우 만들어지는 이터레이터는 __next__() 메서드가 호출될 때마다 인자 없이 object 를 호출합니다; 반환된 값이 sentinel 과 같으면, StopIteration 을 일으키고, 그렇지 않으면 값을 돌려줍니다.

이터레이터 형 도 보세요.

두 번째 형태의 iter() 의 한가지 유용한 응용은 블록 리더를 만드는 것입니다. 예를 들어, 바이너리 데이터베이스 파일에서 파일의 끝까지 고정 폭 블록 읽기입니다:

from functools import partial
with open('mydata.db', 'rb') as f:
    for block in iter(partial(f.read, 64), b''):
        process_block(block)

len(s)

객체의 길이 (항목 수)를 돌려줍니다. 인자는 시퀀스 (문자열, 바이트열, 튜플, 리스트 또는 range 같은) 또는 컬렉션 (딕셔너리, 집합 또는 불변 집합 같은) 일 수 있습니다.

class list([iterable])

함수이기보다, 리스트 와 시퀀스 형 — list, tuple, range 에 문서화 된 것처럼, list 는 실제로는 가변 시퀀스 형입니다.

locals()

현재 지역 심볼 테이블을 나타내는 딕셔너리를 갱신하고 돌려줍니다. locals() 이 함수 블록에서 호출될 때 자유 변수를 돌려주지만, 클래스 블록에서 호출할 때는 그렇지 않습니다. 모듈 수준에서 locals()와 globals()는 같은 딕셔너리임에 유의하십시오.

참고

이 딕셔너리의 내용은 수정해서는 안 됩니다. 변경 사항은 인터프리터가 사용하는 지역 및 자유 변수의 값에 영향을 미치지 않을 수 있습니다.

map(function, iterable, ...)

iterable 의 모든 항목에 function 을 적용한 후 그 결과를 돌려주는 이터레이터를 돌려줍니다. 추가 iterable 인자가 전달되면, function 은 그 수 만큼의 인자를 받아들여야 하고 모든 이터러블에서 병렬로 제공되는 항목들에 적용됩니다. 다중 이터러블의 경우, 이터레이터는 가장 짧은 이터러블이 모두 소모되면 멈춥니다. 함수 입력이 이미 인자 튜플로 배치된 경우에는, itertools.starmap() 를 보세요.

max(iterable, *[, key, default])

max(arg1, arg2, *args[, key])

iterable 에서 가장 큰 항목이나 두 개 이상의 인자 중 가장 큰 것을 돌려줍니다.

하나의 위치 인자가 제공되면, 그것은 이터러블 이어야 합니다. iterable에서 가장 큰 항목을 돌려줍니다. 두 개 이상의 위치 인자가 제공되면, 위치 인자 중 가장 큰 것을 돌려줍니다.

선택적 키워드-전용 인자가 두 개 있습니다. key 인자는 list.sort() 에 사용되는 것처럼 단일 인자 순서 함수를 지정합니다. default 인자는 제공된 iterable이 비어있는 경우 돌려줄 객체를 지정합니다. iterable이 비어 있고 default 가 제공되지 않으면 ValueError 가 발생합니다.

여러 항목이 최댓값이면, 함수는 처음 만난 항목을 돌려줍니다. 이것은 sorted(iterable, key=keyfunc, reverse=True)[0] 와 heapq.nlargest(1, iterable, key=keyfunc) 같은 다른 정렬 안정성 보존 도구와 일관성을 유지합니다.

버전 3.4에 추가: default 키워드-전용 인자.

class memoryview(obj)

지정된 인자로부터 만들어진 “메모리 뷰” 객체를 돌려줍니다. 자세한 정보는 메모리 뷰 를 보세요.

min(iterable, *[, key, default])

min(arg1, arg2, *args[, key])

iterable 에서 가장 작은 항목이나 두 개 이상의 인자 중 가장 작은 것을 돌려줍니다.

하나의 위치 인자가 제공되면, 그것은 이터러블 이어야 합니다. iterable에서 가장 작은 항목을 돌려줍니다. 두 개 이상의 위치 인자가 제공되면, 위치 인자 중 가장 작은 것을 돌려줍니다.

선택적 키워드-전용 인자가 두 개 있습니다. key 인자는 list.sort() 에 사용되는 것처럼 단일 인자 순서 함수를 지정합니다. default 인자는 제공된 iterable이 비어있는 경우 돌려줄 객체를 지정합니다. iterable이 비어 있고 default 가 제공되지 않으면 ValueError 가 발생합니다.

여러 항목이 최솟값이면, 함수는 처음 만난 항목을 돌려줍니다. 이것은 sorted(iterable, key=keyfunc)[0] 와 heapq.nsmallest(1, iterable, key=keyfunc) 같은 다른 정렬 안정성 보존 도구와 일관성을 유지합니다.

버전 3.4에 추가: default 키워드-전용 인자.

next(iterator[, default])

__next__() 메서드를 호출하여 iterator 에서 다음 항목을 꺼냅니다. default 가 주어지면, iterator가 고갈될 때 돌려주고, 그렇지 않으면 StopIteration 을 일으킵니다.

class object

새 기능 없는 객체를 돌려줍니다. object 는 모든 클래스의 베이스 클래스입니다. 모든 파이썬 클래스의 인스턴스에 공통적인 메서드를 가지고 있습니다. 이 함수는 인자를 받아들이지 않습니다.

참고

object 는 __dict__ 을 가지지 않습니다. 그래서, object 클래스의 인스턴스에 임의의 어트리뷰트를 대입할 수 없습니다.

oct(x)

정수를 “0o”로 시작하는 8진수 문자열로 변환합니다. 결과는 올바른 파이썬 표현식입니다. x 가 파이썬 int 객체가 아니면, 정수를 돌려주는 __index__() 메서드를 정의해야 합니다. 예를 들어:

>>> oct(8)
'0o10'
>>> oct(-56)
'-0o70'

정수를 접두사 “0o”가 있거나 없는 형태의 8진수 문자열로 변환하려면, 다음 방법의 하나를 사용할 수 있습니다.

>>> '%#o' % 10, '%o' % 10
('0o12', '12')
>>> format(10, '#o'), format(10, 'o')
('0o12', '12')
>>> f'{10:#o}', f'{10:o}'
('0o12', '12')

자세한 내용은 format()을 보세요.

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

file 을 열고 해당 파일 객체 를 돌려줍니다. 파일을 열 수 없으면, OSError 가 발생합니다.

file 은 열 파일의 경로명(절대 혹은 현재 작업 디렉터리에 상대적인)을 주는 경로류 객체 거나, 감쌀 파일의 정수 파일 디스크립터입니다. (파일 디스크립터가 주어지면, closefd 가 False 가 아닌 한, 반환된 I/O 객체가 닫힐 때 닫힙니다.)

mode 는 파일이 열리는 모드를 지정하는 선택적 문자열입니다. 기본값은 'r' 인데, 텍스트 모드로 읽기 위해 여는 것을 뜻합니다. 다른 일반적인 값은 쓰기 위한 'w' (파일이 이미 존재하는 경우 파일을 자릅니다), 독점적 파일 만들기를 위한 'x' 및 덧붙이기를 위한 'a' (일부 유닉스 시스템에서, 현재 위치와 관계없이 모든 쓰기가 파일의 끝에 덧붙여짐을 뜻합니다) 입니다. 텍스트 모드에서, encoding 을 지정하지 않으면 사용되는 인코딩은 플랫폼에 따라 다릅니다: 현재 로케일 인코딩을 얻기 위해 locale.getpreferredencoding(False) 가 호출됩니다. (날 바이트열을 읽고 쓰려면 바이너리 모드를 사용하고 encoding 을 지정하지 않습니다.) 사용 가능한 모드는 다음과 같습니다:

문자

의미

'r'

읽기용으로 엽니다 (기본값)

'w'

쓰기용으로 엽니다, 파일을 먼저 자릅니다.

'x'

독점적인 파일 만들기용으로 엽니다, 이미 존재하는 경우에는 실패합니다.

'a'

쓰기용으로 엽니다, 파일이 존재하는 경우는 파일의 끝에 덧붙입니다

'b'

바이너리 모드

't'

텍스트 모드 (기본값)

'+'

갱신(읽기 및 쓰기)용으로 디스크 파일을 엽니다

기본 모드는 'r' 입니다 (텍스트를 읽는 용으로 엽니다, 'rt' 의 동의어). 바이너리 읽기-쓰기 액세스의 경우는, 모드 'w+b' 는 파일을 열면서 0바이트로 자릅니다. 'r+b' 는 자르지 않고 파일을 엽니다.

Overview 에서 언급했듯이, 파이썬은 바이너리와 텍스트 I/O를 구별합니다. 바이너리 모드 (mode 인자에 'b' 를 포함합니다)로 열린 파일은 내용을 디코딩 없이 bytes 객체로 돌려줍니다. 텍스트 모드 (기본값, 또는 mode 인자에 't' 가 포함될 때)에서는, 파일의 내용이 str로 반환되는데, 바이트열이 플랫폼 의존적인 인코딩이나 주어진 encoding 을 사용해서 먼저 디코드 됩니다.

허용된 추가의 모드 문자 'U'가 있습니다. 이것은 더는 아무런 효과가 없으며, 폐지된 것으로 간주합니다. 이전에는 텍스트 모드에서 유니버설 줄 넘김을 활성화했는데, 파이썬 3.0에서 기본 동작이 되었습니다. 자세한 내용은 newline 매개 변수의 설명서를 참조하십시오.

참고

파이썬은 하위 운영 체제의 텍스트 파일 개념에 의존하지 않습니다. 모든 처리는 파이썬 자체에 의해 수행되므로 플랫폼에 독립적입니다.

buffering 은 버퍼링 정책을 설정하는 데 사용되는 선택적 정수입니다. 버퍼링을 끄려면 (바이너리 모드에서만 허용) 0을 전달하고, 줄 버퍼링 (텍스트 모드에서만 사용 가능)을 선택하려면 1을, 고정 크기 청크 버퍼를 선택하려면 그 크기를 바이트 단위로 표시한 정수 > 1을 전달합니다. buffering 인자가 제공되지 않을 때, 기본 버퍼링 정책은 다음과 같이 작동합니다:

바이너리 파일은 고정 크기 청크로 버퍼링 됩니다. 버퍼의 크기는 하부 장치의 “블록 크기”를 파악하려고 시도하는 경험적인 방법을 사용해서 선택되고 io.DEFAULT_BUFFER_SIZE로 폴 백 됩니다. 많은 시스템에서, 버퍼는 일반적으로 4096 또는 8192바이트 길이입니다.

“대화형” 텍스트 파일 (isatty() 가 True 를 돌려주는 파일)은 줄 버퍼링을 사용합니다. 다른 텍스트 파일은 바이너리 파일에 대해 위에서 설명한 정책을 사용합니다.

encoding 은 파일을 디코딩하거나 인코딩하는 데 사용되는 인코딩의 이름입니다. 텍스트 모드에서만 사용해야 합니다. 기본 인코딩은 플랫폼에 따라 다르지만 (locale.getpreferredencoding() 이 돌려주는 값), 파이썬에서 지원하는 텍스트 인코딩 은 모두 사용할 수 있습니다. 지원되는 인코딩 목록은 codecs 모듈을 보면 됩니다.

errors 는 인코딩 및 디코딩 에러를 처리하는 방법을 지정하는 선택적 문자열입니다. 바이너리 모드에서는 사용할 수 없습니다. 다양한 표준 에러 처리기가 제공됩니다 (Error Handlers 에 나열됩니다). 하지만, codecs.register_error()로 등록된 에러 처리기 이름 역시 사용할 수 있습니다. 표준 이름은 다음과 같습니다:

'strict' 는 인코딩 에러가 있는 경우 ValueError 예외를 발생시킵니다. 기본값 None 은 같은 효과를 냅니다.

'ignore' 는 에러를 무시합니다. 인코딩 에러를 무시하면 데이터가 손실될 수 있음에 주의하세요.

'replace' 는 잘못된 데이터가 있는 자리에 대체 마커('?' 와 같은)를 삽입합니다.

'surrogateescape' 는 U+DC80에서 U+DCFF까지의 유니코드 개인 사용 영역의 코드 포인트로 잘못된 바이트를 나타냅니다. 데이터를 쓸 때 surrogateescape 에러 처리기가 사용되면, 이 개인 코드 포인트들은 원래의 바이트로 되돌아갑니다. 알 수 없는 인코딩의 파일을 처리할 때 유용합니다.

'xmlcharrefreplace' 는 파일에 쓸 때만 지원됩니다. 인코딩이 지원하지 않는 문자는 적절한 XML 문자 참조 &#nnn; 로 대체됩니다.

'backslashreplace' 는 잘못된 데이터를 파이썬의 역 슬래시 이스케이프 시퀀스로 대체합니다.

'namereplace' (역시 파일에 쓸 때만 지원됩니다)는 지원되지 않는 문자를 \N{...} 이스케이프 시퀀스로 대체합니다.

newline 은 유니버설 줄 넘김 모드가 작동하는 방식을 제어합니다 (텍스트 모드에만 적용됩니다). None, '', '\n', '\r' 및 `` '\r\n' 일 수 있습니다. 다음과 같이 작동합니다:

스트림에서 입력을 읽을 때, newline 이 None 이면, 유니버설 줄 넘김 모드가 활성화됩니다. 입력에 있는 줄은 '\n', '\r' 또는 '\r\n' 로 끝날 수 있으며, 호출자에게 돌려주기 전에 모두 '\n' 로 변환됩니다. 그것이 '' 이면, 유니버설 줄 넘김 모드가 활성화되지만, 줄 끝은 변환되지 않은 채로 호출자에게 반환됩니다. 다른 유효한 값이면, 입력 줄은 주어진 문자열로만 끝나며, 줄 끝은 변환되지 않은 채로 호출자에게 돌려줍니다.

스트림에 출력을 쓸 때, newline 이 None 이면, 모든 '\n' 문자는 시스템 기본 줄 구분자인 os.linesep 로 변환됩니다. newline 이 '' 또는 '\n' 이면, 변환이 이루어지지 않습니다. newline 이 다른 유효한 값이면, 쓰이는 모든 '\n' 문자는 주어진 문자열로 변환됩니다.

closefd 가 False 이고 파일명 대신 파일 디스크립터가 주어지면, 파일이 닫힐 때 하위 파일 디스크립터가 열려있게 됩니다. 파일명이 주어지면 closefd 는 True (기본값) 여야 합니다. 그렇지 않으면 에러가 발생합니다.

콜러블을 opener 로 전달하여 커스텀 오프너를 사용할 수 있습니다. 파일 객체를 위한 하위 파일 디스크립터는 opener 를 (file, flags) 로 호출해서 얻습니다. opener 는 열린 파일 디스크립터를 반환해야 합니다 (opener 에 os.open 을 전달하는 것은 None 을 전달하는 것과 비슷한 기능을 수행하게 됩니다).

새로 만들어진 파일은 상속 불가능 합니다.

다음 예는 주어진 디렉터리에 상대적인 파일을 열기 위해 os.open() 함수의 dir_fd 매개변수를 사용합니다:

>>> import os
>>> dir_fd = os.open('somedir', os.O_RDONLY)
>>> def opener(path, flags):
...     return os.open(path, flags, dir_fd=dir_fd)
...
>>> with open('spamspam.txt', 'w', opener=opener) as f:
...     print('This will be written to somedir/spamspam.txt', file=f)
...
>>> os.close(dir_fd)  # don't leak a file descriptor

open() 함수에 의해 반환된 파일 객체 의 형은 모드에 의존합니다. open() 이 텍스트 모드('w', 'r', 'wt', 'rt', 등)로 파일을 여는 데 사용되면, io.TextIOBase 의 서브 클래스를 돌려줍니다 (구체적으로 io.TextIOWrapper). 버퍼링과 함께 바이너리 모드로 파일을 여는 데 사용되는 경우, 반환되는 클래스는 io.BufferedIOBase 의 서브 클래스입니다. 정확한 클래스는 다양합니다: 읽기 바이너리 모드에서는, io.BufferedReader 를 돌려줍니다; 쓰기 바이너리와 덧붙이기 바이너리 모드에서는, io.BufferedWriter 를 돌려주고, 읽기/쓰기 모드에서는, io.BufferedRandom 을 돌려줍니다. 버퍼링을 끄면, 날 스트림, io.RawIOBase 의 서브 클래스, io.FileIO, 을 돌려줍니다.

fileinput, io (open() 이 선언된 곳), os, os.path, tempfile, 그리고 shutil 와 같은 파일 처리 모듈들도 보세요.

버전 3.3에서 변경:

opener 매개변수가 추가되었습니다.

'x' 모드가 추가되었습니다.

IOError 를 일으켜왔습니다. 이제는 OSError 의 별칭입니다.

독점적 파일 만들기 모드('x')로 여는 파일이 이미 존재하면, 이제 FileExistsError 를 일으킵니다.

버전 3.4에서 변경:

파일은 이제 상속 불가능합니다.

Deprecated since version 3.4, will be removed in version 3.9: 'U' 모드.

버전 3.5에서 변경:

시스템 호출이 인터럽트 되고 시그널 처리기가 예외를 발생시키지 않으면, 이 함수는 이제 InterruptedError 예외를 일으키는 대신 시스템 호출을 재시도합니다 (이유는 PEP 475 [https://www.python.org/dev/peps/pep-0475] 를 보세요).

'namereplace' 오류 처리기가 추가되었습니다.

버전 3.6에서 변경:

os.PathLike 를 구현하는 객체를 받아들이도록 지원이 추가되었습니다.

윈도우에서, 콘솔 버퍼를 열면 io.FileIO 가 아닌 io.RawIOBase 의 서브 클래스가 반환될 수 있습니다.

ord(c)

하나의 유니코드 문자를 나타내는 문자열이 주어지면 해당 문자의 유니코드 코드 포인트를 나타내는 정수를 돌려줍니다. 예를 들어, ord('a') 는 정수 97 을 반환하고 ord('€') (유로 기호)는 8364 를 반환합니다. 이것은 chr() 의 반대입니다.

pow(x, y[, z])

x 의 y 거듭제곱을 돌려줍니다; z 가 있는 경우, x 의 y 거듭제곱의 모듈로 z 를 돌려줍니다 (pow(x, y) % z 보다 더 빠르게 계산됩니다). 두 개의 인자 형식인 pow (x, y) 는 거듭제곱 연산자를 사용하는 것과 동등합니다: x ** y.

인자는 숫자 형이어야 합니다. 피연산자들의 형이 다를 경우, 이 항 산술 연산자에 대한 코어션 규칙이 적용됩니다. int 피연산자들의 경우, 결과는 두 번째 인자가 음수가 아닌 한 피연산자와 같은 형(코어션 후에)이 됩니다; 두 번째 인자가 음수면 모든 인자가 float로 변환되고 float 결과가 전달됩니다. 예를 들어, 10**2 는 100 을 반환하지만, 10**-2``는 ``0.01 을 반환합니다. 두 번째 인자가 음수면 세 번째 인수는 생략해야 합니다. z 가 있는 경우, x 및 y 는 정수형이어야 하고, y 는 음수가 아니어야 합니다.

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

objects 를 텍스트 스트림 file 로 인쇄하는데, sep 로 구분되고 end 를 뒤에 붙입니다. 있다면, sep, end, file 및 flush 는 반드시 키워드 인자로 제공해야 합니다.

모든 비 키워드 인자는 str() 이 하듯이 문자열로 변환된 후 스트림에 쓰이는데, sep 로 구분되고 end 를 뒤에 붙입니다. sep 과 end 는 모두 문자열이어야 합니다; None 일 수도 있는데, 기본값을 사용한다는 뜻입니다. objects 가 주어지지 않으면 print() 는 end 만 씁니다.

file 인자는 write(string) 메서드를 가진 객체여야 합니다; 존재하지 않거나 None 이면, sys.stdout 이 사용됩니다. 인쇄된 인자는 텍스트 문자열로 변환되기 때문에, print() 는 바이너리 모드 파일 객체와 함께 사용할 수 없습니다. 이를 위해서는. 대신 file.write(...) 를 사용합니다.

출력의 버퍼링 여부는 일반적으로 file 에 의해 결정되지만, flush 키워드 인자가 참이면 스트림이 강제로 플러시 됩니다.

버전 3.3에서 변경: flush 키워드 인자가 추가되었습니다.

class property(fget=None, fset=None, fdel=None, doc=None)

프로퍼티 어트리뷰트를 돌려줍니다.

fget 은 어트리뷰트 값을 얻는 함수입니다. fset 은 어트리뷰트 값을 설정하는 함수입니다. fdel 은 어트리뷰트 값을 삭제하는 함수입니다. 그리고 doc 은 어트리뷰트의 독스트링을 만듭니다.

전형적인 사용은 관리되는 어트리뷰트 x 를 정의하는 것입니다:

class C:
    def __init__(self):
        self._x = None

    def getx(self):
        return self._x

    def setx(self, value):
        self._x = value

    def delx(self):
        del self._x

    x = property(getx, setx, delx, "I'm the 'x' property.")

c 가 C 의 인스턴스면, c.x 는 게터(getter)를 호출하고, c.x = value 는 세터(setter)를 호출하고, del c.x 는 딜리터(deleter)를 호출합니다.

주어진 경우, doc 은 프로퍼티 어트리뷰트의 독스트링이 됩니다. 그렇지 않으면, fget 의 독스트링(있는 경우)이 복사됩니다. 이렇게 하면 property() 를 데코레이터 로 사용하여 읽기 전용 프로퍼티를 쉽게 만들 수 있습니다:

class Parrot:
    def __init__(self):
        self._voltage = 100000

    @property
    def voltage(self):
        """Get the current voltage."""
        return self._voltage

@property 데코레이터는 voltage() 메서드를 같은 이름의 읽기 전용 어트리뷰트에 대한 “게터”로 바꾸고, voltage 에 대한 독스트링을 “Get the current voltage.” 로 설정합니다.

프로퍼티 객체는 데코레이터로 사용할 수 있는 getter, setter 및 deleter 메서드를 갖는데, 해당 접근자 함수를 데코레이트 된 함수로 설정한 프로퍼티의 사본을 만듭니다. 이것은 예제로 가장 잘 설명됩니다:

class C:
    def __init__(self):
        self._x = None

    @property
    def x(self):
        """I'm the 'x' property."""
        return self._x

    @x.setter
    def x(self, value):
        self._x = value

    @x.deleter
    def x(self):
        del self._x

이 코드는 첫 번째 예제와 정확히 동등합니다. 추가적인 함수들에 원래 프로퍼티(이 경우 x)와 같은 이름을 사용해야 합니다.

반환된 프로퍼티 객체는 생성자 인자에 해당하는 fget, fset 및 fdel 어트리뷰트를 가집니다.

버전 3.5에서 변경: 이제 프로퍼티 개체의 독스트링이 쓰기 가능합니다.

class range(stop)

class range(start, stop[, step])

함수라기보다, range 는 실제로는 범위 와 시퀀스 형 — list, tuple, range 에 설명된 대로 불변 시퀀스 형입니다.

repr(object)

객체의 인쇄 가능한 표현을 포함한 문자열을 돌려줍니다. 많은 형에서, 이 함수는 eval() 에 전달 될 때 같은 값을 가진 객체를 생성하는 문자열을 반환하려고 시도합니다, 그렇지 않으면 표현은 객체의 형의 이름과 종종 객체의 이름과 주소를 포함하는 추가의 정보를 화살괄호로 묶은 문자열입니다. 클래스는 __repr__() 메서드를 정의하여 이 함수가 인스턴스에 대해 돌려주는 것을 제어할 수 있습니다.

reversed(seq)

역 이터레이터 를 돌려줍니다. seq 는 __reversed__() 메서드를 가졌거나 시퀀스 프로토콜(__len__() 메서드와 0 에서 시작하는 정수 인자를 받는 __getitem__() 메서드)을 지원하는 객체여야 합니다.

round(number[, ndigits])

number 를 소수점 다음에 ndigits 정밀도로 반올림한 값을 돌려줍니다. ndigits 가 생략되거나 None 이면, 입력에 가장 가까운 정수를 돌려줍니다.

round() 를 지원하는 내장형의 경우, 값은 10의 -ndigits 거듭제곱의 가장 가까운 배수로 반올림됩니다; 두 배수가 똑같이 가깝다면, 반올림은 짝수를 선택합니다 (예를 들어, round(0.5) 와 round(-0.5) 는 모두 0 이고, round(1.5) 는 2 입니다). 모든 정숫값은 ndigits 에 유효합니다 (양수, 0 또는 음수). ndigits 가 생략되거나 None 이면, 반환 값은 정수입니다. 그렇지 않으면 반환 값은 number 와 같은 형입니다.

일반적인 파이썬 객체 number 의 경우, round 는 number.__round__ 에 위임합니다.

참고

float에 대한 round() 의 동작은 예상과 다를 수 있습니다: 예를 들어, round(2.675, 2) 는 2.68 대신에 2.67 을 제공합니다. 이것은 버그가 아닙니다: 대부분의 십진 소수가 float로 정확히 표현될 수 없다는 사실로부터 오는 결과입니다. 자세한 정보는 부동 소수점 산술: 문제점 및 한계 를 보세요.

class set([iterable])

새 set 객체를 돌려줍니다. 선택적으로 iterable 에서 가져온 요소를 갖습니다. set 은 내장 클래스입니다. 이 클래스에 대한 설명서는 set 및 집합 형 — set, frozenset 을 보세요.

다른 컨테이너의 경우 내장 frozenset, list, tuple 및 dict 클래스와 collections 모듈을 보세요.

setattr(object, name, value)

이것은 getattr() 과 한 쌍입니다. 인자는 객체, 문자열 및 임의의 값입니다. 문자열은 기존 어트리뷰트 또는 새 어트리뷰트의 이름을 지정할 수 있습니다. 이 함수는 객체가 허용하는 경우 값을 어트리뷰트에 대입합니다. 예를 들어, setattr(x, 'foobar', 123) 는 x.foobar = 123 과 동등합니다.

class slice(stop)

class slice(start, stop[, step])

range(start, stop, step) 에 의해 지정된 인덱스 세트를 나타내는 슬라이스 객체를 돌려줍니다. start 및 step 인자의 기본값은 None 입니다. 슬라이스 객체는 단지 인자 값 (또는 기본값)을 돌려주는 start, stop 및 step 의 읽기 전용 데이터 어트리뷰트를 갖습니다. 다른 명시적 기능은 없습니다; 그러나 Numerical Python과 다른 제삼자 확장이 사용합니다. 슬라이스 객체는 확장 인덱싱 문법을 사용할 때도 만들어집니다. 예를 들어: a[start:stop:step] 또는 a[start:stop, i]. 이터레이터를 돌려주는 대안 버전은 itertools.islice() 를 보세요.

sorted(iterable, *, key=None, reverse=False)

iterable 의 항목들로 새 정렬된 리스트를 돌려줍니다.

키워드 인자로만 지정해야 하는 두 개의 선택적 인자가 있습니다.

key 는 하나의 인자를 받는 함수를 지정하는데, iterable의 각 요소들로부터 비교 키를 추출하는 데 사용됩니다 (예를 들어, key = str.lower). 기본값은 None 입니다 (요소를 직접 비교합니다).

reverse 는 논리값입니다. True 로 설정되면, 각 비교가 뒤집힌 것처럼 리스트 요소들이 정렬됩니다.

예전 스타일의 cmp 함수를 key 함수로 변환하려면 functools.cmp_to_key() 를 사용하세요.

내장 sorted() 함수는 안정적(stable)임이 보장됩니다. 정렬은 같다고 비교되는 요소의 상대적 순서를 변경하지 않으면 안정적입니다 — 이는 여러 번 정렬할 때 유용합니다 (예를 들어, 부서별로 정렬한 후에 급여 등급별로 정렬하기).

정렬 예제와 간단한 정렬 자습서는 정렬 HOW TO 를 보세요.

@staticmethod

메서드를 정적 메서드로 변환합니다.

정적 메서드는 묵시적인 첫 번째 인자를 받지 않습니다. 정적 메서드를 선언하려면, 이 관용구를 사용하세요:

class C:
    @staticmethod
    def f(arg1, arg2, ...): ...

@staticmethod 형식은 함수 데코레이터 입니다 – 자세한 내용은 함수 정의를 보세요.

정적 메서드는 클래스 (C.f() 처럼) 또는 인스턴스 (C().f() 처럼)에 대해 호출할 수 있습니다.

파이썬의 정적 메서드는 자바 또는 C++ 에서 발견되는 정적 메서드와 비슷합니다. 대체 클래스 생성자를 만드는 데 유용한 변형을 보려면 classmethod() 도 보세요.

모든 데코레이터와 마찬가지로, staticmethod 를 정규 함수로 호출하여 그 결과로 어떤 일을 할 수도 있습니다. 이것은 클래스 바디에서 함수에 대한 참조가 필요하고 인스턴스 메서드로 자동 변환되는 것을 피하고자 할 때 필요합니다. 이 경우 다음 관용구를 사용하세요:

class C:
    builtin_open = staticmethod(open)

정적 메서드에 대한 더 자세한 정보는, 표준형 계층을 참조하세요.

class str(object='')

class str(object=b'', encoding='utf-8', errors='strict')

object 의 str 버전을 돌려줍니다. 자세한 내용은 str() 을 보세요.

str 은 내장 문자열 클래스 입니다. 문자열에 대한 일반적인 정보는 텍스트 시퀀스 형 — str 를 보세요.

sum(iterable[, start])

start 및 iterable 의 항목들을 왼쪽에서 오른쪽으로 합하고 합계를 돌려줍니다. start 의 기본값은 0 입니다. iterable 의 항목은 일반적으로 숫자며 시작 값은 문자열이 될 수 없습니다.

어떤 경우에는 sum() 에 대한 좋은 대안이 있습니다. 문자열의 시퀀스를 연결하는 가장 선호되고 빠른 방법은 ''.join(sequence) 를 호출하는 것입니다. 확장된 정밀도로 부동 소수점 값을 더하려면 math.fsum() 를 보세요. 일련의 이터러블들을 연결하려면 itertools.chain() 를 고려해보세요.

super([type[, object-or-type]])

메서드 호출을 type 의 부모나 형제 클래스에 위임하는 프락시 객체를 돌려줍니다. 이는 클래스에서 재정의된 상속 된 메서드를 액세스할 때 유용합니다. 검색 순서는 type 자체를 건너뛰는 것을 제외하면, getattr() 에 의해 사용된 순서와 같습니다.

type 의 __mro__ 어트리뷰트는 메서드 결정 검색 순서를 나열하는데 getattr() 과 super() 에서 사용됩니다. 이 어트리뷰트는 동적이며 상속 계층 구조가 변경될 때마다 바뀔 수 있습니다.

두 번째 인자가 생략되면, 반환되는 슈퍼 객체는 연결되지 않았습니다(unbound). 두 번째 인자가 객체면, isinstance(obj, type) 는 참이어야 합니다. 두 번째 인자가 형이면, issubclass(type2, type) 는 참이어야 합니다 (이것은 클래스 메서드에 유용합니다).

super 에는 두 가지 일반적인 사용 사례가 있습니다. 단일 상속 클래스 계층 구조에서는, super 를 사용하여 명시적으로 이름을 지정하지 않고 부모 클래스를 참조할 수 있으므로, 코드를 더 유지 관리하기 쉽게 만들 수 있습니다. 이 사용은 다른 프로그래밍 언어에서 super 를 쓰는 것과 매우 유사합니다.

두 번째 사용 사례는 동적 실행 환경에서 협력적 다중 상속을 지원하는 것입니다. 이 사례는 파이썬에 고유하며 정적으로 컴파일되는 언어 또는 단일 상속만 지원하는 언어에서는 찾을 수 없습니다. 이것은 여러 베이스 클래스가 같은 메서드를 구현하는 “다이아몬드 다이어그램”을 구현할 수 있게 합니다. 좋은 설계는 모든 경우에 이 메서드가 같은 호출 시그니처를 갖도록 하는 것입니다 (호출 순서는 실행 시간에 결정되기 때문에, 그 순서가 클래스 계층 구조의 변경에 적응하기 때문에, 그리고 그 순서가 실행 시간 전에 미리 알려지지 않은 형제 클래스를 포함할 수 있으므로).

두 경우 모두, 일반적인 슈퍼 클래스 호출은 이런 식입니다:

class C(B):
    def method(self, arg):
        super().method(arg)    # This does the same thing as:
                               # super(C, self).method(arg)

In addition to method lookups, super() also works for attribute lookups. One possible use case for this is calling descriptors in a parent or sibling class.

super() 는 super().__getitem__(name) 과 같은 명시적인 점으로 구분된 어트리뷰트 조회를 위한 연결 절차의 일부로 구현됨에 주의하세요. 이것은 협력적인 다중 상속을 지원하는 예측 가능한 순서로 클래스를 검색하기 위해 자체 __getattribute__() 메서드를 구현함으로써 그렇게 합니다. 따라서, super() 는 super()[name] 과같이 문장이나 연산자를 사용하는 묵시적 조회에 대해서는 정의되지 않았습니다.

또한, 인자가 없는 형식을 제외하고는, super() 는 메서드 내부에서만 사용하도록 제한되지 않는다는 점에 유의하세요. 두 개의 인자 형식은 인자를 정확하게 지정하고 적절한 참조를 만듭니다. 인자가 없는 형식은 클래스 정의 내에서만 작동하는데, 컴파일러가 정의되고 있는 클래스를 올바르게 가져오고 일반 메서드에서 현재 인스턴스에 액세스하는 데 필요한 세부 정보를 채우기 때문입니다.

super()를 사용하여 협력적 클래스를 설계하는 방법에 대한 실용적인 제안은 super() 사용 안내 [https://rhettinger.wordpress.com/2011/05/26/super-considered-super/] 를 보세요.

class tuple([iterable])

함수이기보다, tuple 은 실제로 튜플 과 시퀀스 형 — list, tuple, range 에 문서화 된 것처럼 불변 시퀀스 형입니다.

class type(object)

class type(name, bases, dict)

인자 하나의 경우, object 의 형을 돌려줍니다. 반환 값은 형 객체며 일반적으로 object.__class__ 가 돌려주는 것과 같은 객체입니다.

객체의 형을 검사하는 데는 isinstance() 내장 함수가 권장되는데, 서브 클래스를 고려하기 때문입니다.

세 개의 인자를 주는 경우, 새 형 객체를 돌려줍니다. 이것은 본래 class 문의 동적인 형태입니다. name 문자열은 클래스 이름이고 __name__ 어트리뷰트가 됩니다; bases 튜플은 베이스 클래스들을 항목화하고 __bases__ 어트리뷰트가 됩니다; dict 딕셔너리는 클래스 바디의 정의들이 들어있는 이름 공간이며 __dict__ 어트리뷰트가 되도록 표준 딕셔너리에 복사됩니다. 예를 들어, 다음 두 문장은 같은 type 객체를 만듭니다:

>>> class X:
...     a = 1
...
>>> X = type('X', (object,), dict(a=1))

형 객체를 보세요.

버전 3.6에서 변경: type.__new__ 를 재정의하지 않는 type 의 서브 클래스는 이제 객체의 형을 얻기 위해 하나의 인자 형식을 사용할 수 없습니다.

vars([object])

모듈, 클래스, 인스턴스 또는 __dict__ 어트리뷰트가 있는 다른 객체의 __dict__ 어트리뷰트를 돌려줍니다.

모듈 및 인스턴스와 같은 객체는 업데이트 가능한 __dict__ 어트리뷰트를 갖습니다; 그러나, 다른 객체는 __dict__ 어트리뷰트에 쓰기 제한을 가질 수 있습니다 (예를 들어, 클래스는 직접적인 딕셔너리 갱신을 방지하기 위해 types.MappingProxyType 를 사용합니다).

인자가 없으면, vars() 는 locals() 처럼 동작합니다. locals 딕셔너리에 대한 변경이 무시되기 때문에 locals 딕셔너리는 읽기에만 유용하다는 것에 주의하세요.

zip(*iterables)

각 iterables 의 요소들을 모으는 이터레이터를 만듭니다.

튜플의 이터레이터를 돌려주는데, i 번째 튜플은 각 인자로 전달된 시퀀스나 이터러블의 i 번째 요소를 포함합니다. 이터레이터는 가장 짧은 입력 이터러블이 모두 소모되면 멈춥니다. 하나의 이터러블 인자를 사용하면, 1-튜플의 이터레이터를 돌려줍니다. 인자가 없으면, 빈 이터레이터를 돌려줍니다. 다음과 동등합니다:

def zip(*iterables):
    # zip('ABCD', 'xy') --> Ax By
    sentinel = object()
    iterators = [iter(it) for it in iterables]
    while iterators:
        result = []
        for it in iterators:
            elem = next(it, sentinel)
            if elem is sentinel:
                return
            result.append(elem)
        yield tuple(result)

iterables 를 왼쪽에서 오른쪽으로 값을 구하는 순서가 보장됩니다. 이것은 zip(*[iter(s)]*n) 을 사용하여 데이터 시리즈를 길이 n인 그룹으로 클러스터링하는 관용구를 가능하게 만듭니다. 이것은 같은 이터레이터를 n 번 반복해서, 각 출력 튜플이 이터레이터를 n 번 호출한 결과를 갖게 됩니다. 입력을 길이 n인 묶음으로 나누는 효과를 줍니다.

zip() 에 길이가 같지 않은 입력들을 제공하는 것은, 끝부분에서 매치되지 않고 남는 더 긴 이터러블들의 값들에 신경 쓰지 않는 경우로 제한해야 합니다. 그 값들이 중요하다면, 대신 itertools.zip_longest() 를 사용하세요.

zip()을 * 연산자와 함께 쓰면 리스트를 unzip 할 수 있습니다:

>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> zipped = zip(x, y)
>>> list(zipped)
[(1, 4), (2, 5), (3, 6)]
>>> x2, y2 = zip(*zip(x, y))
>>> x == list(x2) and y == list(y2)
True

__import__(name, globals=None, locals=None, fromlist=(), level=0)

참고

이것은 importlib.import_module() 과 달리 일상적인 파이썬 프로그래밍에서는 필요하지 않은 고급 함수입니다.

이 함수는 import 문에 의해 호출됩니다. import 문의 의미를 변경하기 위해 대체할 수 있습니다 (builtins 모듈을 임포트하고 builtins .__ import__ 에 대입합니다). 그러나 그렇게 하지 말 것을 강하게 권고하는데, 보통 같은 목적을 달성하는데 임포트 훅(PEP 302 [https://www.python.org/dev/peps/pep-0302] 를 보세요)을 사용하는 것이 더 간단하고 기본 임포트 구현이 사용될 것이라고 가정하는 코드들과 문제를 일으키지 않기 때문입니다. __import__() 의 직접 사용 역시 피하고 importlib.import_module() 을 사용할 것을 권합니다.

함수는 모듈 name 을 임포트 하는데, 잠재적으로 패키지 문맥에서 이름을 해석하는 방법을 결정하는데 주어진 globals 와 locals 를 사용합니다. fromlist 는 name 에 의해 주어진 모듈로부터 임포트 되어야 하는 객체 또는 서브 모듈의 이름을 제공합니다. 표준 구현은 locals 인자를 전혀 사용하지 않고, import 문의 패키지 문맥을 결정할 때만 globals 를 사용합니다.

level 은 절대 또는 상대 임포트를 사용할지를 지정합니다. 0 (기본값)은 오직 절대 임포트를 수행한다는 것을 의미합니다. 양수 값 level 은 __import__() 를 호출하는 모듈 디렉터리에 상대적으로 검색할 상위 디렉터리들의 개수를 가리킵니다 (자세한 내용은 PEP 328 [https://www.python.org/dev/peps/pep-0328]을 보세요).

name 변수가 package.module 형식일 때, 일반적으로 name 에 의해 명명된 모듈이 아니라, 최상위 패키지(첫 번째 점까지의 이름)가 반환됩니다. 그러나 비어 있지 않은 fromlist 인자가 주어지면 name 에 의해 명명된 모듈이 반환됩니다.

예를 들어, 문장 import spam 은 다음 코드를 닮은 바이트 코드를 생성합니다:

spam = __import__('spam', globals(), locals(), [], 0)

문장 import spam.ham 은 이런 호출로 이어집니다:

spam = __import__('spam.ham', globals(), locals(), [], 0)

여기에서 __import__() 가 최상위 모듈을 돌려주는 것에 주목하세요. 이것이 import 문에 의해 이름에 연결되는 객체이기 때문입니다.

반면에, 문장 from spam.ham import eggs, sausage as saus 는 이런 결과를 줍니다:

_temp = __import__('spam.ham', globals(), locals(), ['eggs', 'sausage'], 0)
eggs = _temp.eggs
saus = _temp.sausage

여기서 spam.ham 모듈이 __import__() 에서 반환됩니다. 이 객체로부터, 임포트할 이름들을 가져온 후 해당 이름들로 대입됩니다.

단순히 이름으로 모듈을 임포트 하기 원한다면 (잠재적으로 패키지 내에서), importlib.import_module() 을 사용하세요.

버전 3.3에서 변경: 음수 level 은 더 지원되지 않습니다 (기본값도 0으로 변경합니다).

각주

1

파서는 유닉스 스타일의 줄 종료 규칙만 받아들이는 것에 주의하세요. 파일에서 코드를 읽는 경우, 줄 넘김 변환 모드를 사용해서 윈도우나 맥 스타일 줄 넘김을 변환해야 합니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

|

내장 상수

작은 개수의 상수가 내장 이름 공간에 있습니다. 그것들은:

False

bool 형의 거짓 값. False 에 대입할 수 없고 SyntaxError 를 일으킵니다.

True

bool 형의 참값. True 에 대입할 수 없고 SyntaxError 를 일으킵니다.

None

NoneType 형의 유일한 값. None 은 기본 인자가 함수에 전달되지 않을 때처럼, 값의 부재를 나타내는 데 자주 사용됩니다. None 에 대입할 수 없고 SyntaxError 를 일으킵니다.

NotImplemented

연산이 다른 형에 대해 구현되지 않았음을 나타내기 위해, 이 항 특수 메서드(예를 들어, __eq__(), __lt__(), __add__(), __rsub__() 등)가 돌려줘야 하는 특별한 값; 같은 목적으로 증분 이 항 특수 메서드(예를 들어, __imul__(), __iand__() 등)가 반환할 수 있습니다. 논릿값은 참입니다.

참고

이 항 (또는 증분) 메서드가 NotImplemented 를 반환하면 인터프리터는 다른 형(또는 연산자에 따라 다른 폴백)에서 뒤집힌 연산을 시도합니다. 모든 시도가 NotImplemented 를 반환하면, 인터프리터는 적절한 예외를 발생시킵니다. 부정확하게 NotImplemented 를 반환하면 오해의 소지가 있는 에러 메시지가 나오거나 파이썬 코드에 NotImplemented 값이 반환됩니다.

예는 산술 연산 구현을 보세요.

참고

NotImplementedError 와 NotImplemented 는 비슷한 이름과 목적이 있지만, 바꿔쓸 수 없습니다. 언제 사용하는지 자세히 알고 싶다면 NotImplementedError를 보세요.

Ellipsis

Ellipsis 리터럴 “...” 와 같습니다. 주로 사용자 정의 컨테이너 데이터형에 대한 확장 슬라이스 문법과 함께 사용되는 특수 값.

__debug__

이 상수는 파이썬이 -O 옵션으로 시작되지 않았다면 참이 됩니다. assert 문도 볼 필요가 있습니다.

참고

None, False, True 그리고 __debug__ 은 다시 대입할 수 없습니다 (이것들을 대입하면, 설사 어트리뷰트 이름으로 사용해도, SyntaxError 를 일으킵니다). 그래서 이것들은 “진짜” 상수로 간주 될 수 있습니다.

site 모듈에 의해 추가된 상수들

site 모듈(-S 명령행 옵션이 주어진 경우를 제외하고는, 시작할 때 자동으로 임포트 됩니다)은 내장 이름 공간에 여러 상수를 추가합니다. 대화형 인터프리터 셸에 유용하고 프로그램에서 사용해서는 안 됩니다.

quit(code=None)

exit(code=None)

인쇄될 때, “Use quit() or Ctrl-D (i.e. EOF) to exit”과 같은 메시지를 인쇄하고, 호출될 때, 지정된 종료 코드로 SystemExit 를 일으키는 객체.

copyright

credits

인쇄하거나 호출할 때, 각각 저작권 또는 크레딧 텍스트를 인쇄하는 객체입니다.

license

인쇄될 때 “Type license() to see the full license text”와 같은 메시지를 인쇄하고, 호출될 때 전체 라이센스 텍스트를 페이지 생성기와 같은 방식(한 번에 한 화면씩)으로 표시하는 객체입니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

|

내장형

다음 섹션에서는 인터프리터에 내장된 표준형에 관해 설명합니다.

기본 내장 유형은 숫자, 시퀀스, 매핑, 클래스, 인스턴스 및 예외입니다.

일부 컬렉션 클래스는 가변입니다. 제자리에서 멤버를 추가, 삭제 또는 재배치하고 특정 항목을 반환하지 않는 메서드는 컬렉션 인스턴스 자체를 반환하지 않고 None 을 반환합니다.

일부 연산들은 여러 객체 형에서 지원됩니다; 특히 사실상 모든 객체를 비교하고, 논리값을 검사하고, (repr() 함수 또는 약간 다른 str() 함수를 사용해서) 문자열로 변환할 수 있습니다. 두 번째 함수는 print() 함수로 객체를 쓸 때 묵시적으로 사용됩니다.

논리값 검사

모든 객체는 논리값을 검사할 수 있는데, if 또는 while 조건 또는 다음에 나오는 논리 연산의 피연산자로 사용될 수 있도록 합니다.

기본적으로 객체는 클래스가 그 객체에 대해 호출될 때 False 를 돌려주는 __bool__() 메서드나 0을 돌려주는 __len__() 메서드를 정의하지 않는 한 참으로 간주합니다. 1 여기에 거짓으로 간주하는 대부분의 내장 객체들이 있습니다:

거짓으로 정의된 상수: None 과 False.

모든 숫자 형들의 영: 0, 0.0, 0j, Decimal(0), Fraction(0, 1)

빈 시퀀스와 컬렉션: '', (), [], {}, set(), range(0)

논리값을 돌려주는 연산과 내장 함수는 달리 명시하지 않는 한 항상 거짓의 경우 0 이나 False 를, 참이면 1 이나 True 를 돌려줍니다. (중요한 예외: 논리 연산 or 와 and 는 항상 피연산자 중 하나를 돌려줍니다.)

논리 연산 — and, or, not

이것들은 우선순위에 따라 오름차순으로 정렬된 논리 연산들입니다:

연산

결과

노트

x or y

x 가 거짓이면 y, 그렇지 않으면 x

(1)

x and y

x*가 거짓이면 *x, 그렇지 않으면 y

(2)

not x

x 가 거짓이면 True, 그렇지 않으면 False

(3)

노트:

이것은 단락-회로 연산자이므로 첫 번째 인자가 거짓일 때만 두 번째의 값을 구합니다.

이것은 단락-회로 연산자이므로 첫 번째 인자가 참일 때만 두 번째의 값을 구합니다.

not 은 비논리 연산자들보다 낮은 우선순위를 갖습니다. 그래서, not a == b 는 not (a == b) 로 해석되고, a == not b 는 문법 오류입니다.

비교

파이썬에는 8가지 비교 연산이 있습니다. 이들 모두는 같은 우선순위를 가집니다 (논리 연산보다는 높습니다). 비교는 임의로 연결될 수 있습니다; 예를 들어 x < y <= z 는 y 의 값을 한 번만 구한다는 점을 제외하고는 x < y and y <= z 와 동등합니다 (하지만 두 경우 모두 x < y 가 거짓으로 밝혀지면 z 의 값을 구하지 않습니다).

이 표는 비교 연산을 요약합니다:

연산

뜻

<

엄격히 작다

<=

작거나 같다

>

엄격히 크다

>=

크거나 같다

==

같다

!=

같지 않다

is

객체 아이덴티티

is not

부정된 객체 아이덴티티

서로 다른 숫자 형을 제외하고는 서로 다른 형의 객체들은 같다고 비교되지 않습니다. 더 나아가, 어떤 형들은 (예를 들어, 함수 객체) 그 형의 모든 두 객체가 다르다고 비교되는 비교의 축약적인 개념만을 지원합니다. <, <=, >, >= 연산자들은 복소수를 다른 내장 숫자 형과 비교할 때, 객체들이 비교될 수 없는 다른 형일 때, 정의된 순서가 없을 때 TypeError 예외를 일으킵니다.

클래스의 같지 않은 인스턴스들은 그 클래스가 __eq__() 메서드를 정의하지 않는 이상 보통 같지 않다고 비교됩니다.

클래스가 __lt__(), __le__(), __gt__(), __ge__() 메서드들을 충분히 정의하지 않는 이상, 클래스의 인스턴스들은 같은 클래스의 다른 인스턴스나 다른 형의 객체와의 순서가 정해지지 않습니다 (일반적으로, 여러분이 비교 연산자의 관습적인 의미를 원한다면 __lt__() 와 __eq__() 만으로 충분합니다).

is 와 is not 연산자의 동작은 사용자 정의할 수 없습니다; 또한 임의의 두 객체에 적용할 수 있으며 예외를 발생시키지 않습니다.

같은 문법적 우선순위를 갖는 두 개의 연산, in 과 not in, 은 이터러블이거나 __contains__() 메서드를 구현하는 형에서 지원됩니다.

숫자 형 — int, float, complex

세 가지 다른 숫자 형이 있습니다: 정수 (integers), 실수 (floating point numbers), 복소수 (complex numbers). 또한 논리형은 정수의 하위 유형입니다. 정수는 무제한의 정밀도를 갖습니다. 실수는 보통 C의 double을 사용해서 구현됩니다; 프로그램이 실행되고 있는 기계의 부동 소수점 숫자의 정밀도와 내부 표현에 관한 정보는 sys.float_info에서 얻을 수 있습니다. 복소수는 각각 실수로 표현되는 실수부와 허수부를 가집니다. 복소수 z 에서 이들 부분을 추출하려면 z.real 과 z.imag 를 사용하십시오. (표준 라이브러리는 추가적인 숫자 형들을 포함하는데, fractions는 유리수를, decimal 은 사용자가 정의할 수 있는 정밀도로 부동 소수점 숫자를 다룹니다.)

숫자는 숫자 리터럴 또는 내장 함수와 연산자의 결과로 만들어집니다. 꾸밈없는 정수 리터럴(16진수, 8진수, 2진수 포함)은 정수를 만듭니다. 소수점 또는 지수 기호가 포함된 숫자 리터럴은 실수를 만듭니다. 숫자 리터럴에 'j' 나 'J' 를 덧붙이면 허수 (실수부가 0인 복소수) 가 만들어지는데, 정수나 실수에 더해서 실수부와 허수부가 있는 복소수를 만들 수 있습니다.

Python fully supports mixed arithmetic: when a binary arithmetic operator has operands of different numeric types, the operand with the “narrower” type is widened to that of the other, where integer is narrower than floating point, which is narrower than complex. A comparison between numbers of different types behaves as though the exact values of those numbers were being compared. 2

The constructors int(), float(), and complex() can be used to produce numbers of a specific type.

All numeric types (except complex) support the following operations (for priorities of the operations, see 연산자 우선순위):

연산

결과

노트

전체 문서

x + y

x 와 y 의 합

x - y

x 와 y 의 차

x * y

x 와 y 의 곱

x / y

x 와 y 의 몫

x // y

x 와 y 의 정수로 내림한 몫

(1)

x % y

x / y 의 나머지

(2)

-x

음의 x

+x

x 그대로

abs(x)

x 의 절댓값 또는 크기

abs()

int(x)

정수로 변환된 x

(3)(6)

int()

float(x)

실수로 변환된 x

(4)(6)

float()

complex(re, im)

실수부 re 와 허수부 im 으로 구성된 복소수. im 의 기본값은 0입니다.

(6)

complex()

c.conjugate()

복소수 c 의 켤레

divmod(x, y)

쌍 (x // y, x % y)

(2)

divmod()

pow(x, y)

x 의 y 거듭제곱

(5)

pow()

x ** y

x 의 y 거듭제곱

(5)

노트:

정수 나눗셈이라고 도합니다. 결괏값의 형이 꼭 int 일 필요는 없지만, 결괏값은 항상 정수입니다. 결과는 항상 음의 무한대를 향해 내림 됩니다: 1//2 는 0, (-1)//2 는 -1, 1//(-2) 는 -1, (-1)//(-2) 는 0 입니다.

복소수에는 사용할 수 없습니다. 적절한 경우 abs()를 사용하여 실수로 변환하십시오.

실수에서 정수로의 변환은 C에서처럼 반올림이나 자름이 발생할 수 있습니다; 잘 정의된 변환을 위해서는 math.floor() 와 math.ceil() 함수를 보십시오.

float는 또한 숫자가 아님(NaN)과 양 또는 음의 무한대를 나타내는 문자열 “nan”과 접두사 “+” 나 “-” 가 선택적으로 붙을 수 있는 “inf”를 받아들입니다.

파이썬은 프로그래밍 언어들에서 흔히 그렇듯이, 있는 것처럼 pow(0, 0) 와 0 ** 0 이 1 이 되도록 정의합니다.

받아들여지는 숫자 리터럴은 0 에서 9 까지 또는 모든 동등한 유니코드들을 (Nd 속성을 가진 코드 포인트들) 포함합니다.

Nd 속성을 가진 코드 포인트의 전체 목록을 보려면 http://www.unicode.org/Public/10.0.0/ucd/extracted/DerivedNumericType.txt 를 보십시오.

모든 numbers.Real 형 (int 와 float) 은 또한 다음과 같은 연산들을 포함합니다:

연산

결과

math.trunc(x)

x 는 Integral 로 잘립니다

round(x[, n])

x 를 n 자리로 반올림하는데, 절반 값은 짝수로 반올림합니다. n 을 생략하면 기본값은 0입니다.

math.floor(x)

가장 큰 Integral <= x

math.ceil(x)

가장 작은 Integral >= x

추가적인 숫자 연산은 math와 cmath 모듈을 보십시오.

정수 형에 대한 비트 연산

비트 연산은 정수에 대해서만 의미가 있습니다. 비트 연산의 결과는 무한한 부호 비트를 갖는 2의 보수로 수행되는 것처럼 계산됩니다.

이진 비트 연산의 우선순위는 모두 숫자 연산보다 낮고 비교보다 높습니다; 일항 연산 ~ 은 다른 일항 연산들 (+ 와 -) 과 같은 우선순위를 가집니다.

이 표는 비트 연산을 나열하는데, 우선순위에 따라 오름차순으로 정렬되어 있습니다:

연산

결과

노트

x | y

x 와 y 의 비트별 or

(4)

x ^ y

x 와 y 의 비트별 배타적 or (exclusive or)

(4)

x & y

x 와 y 의 비트별 and

(4)

x << n

x 를 n 비트만큼 왼쪽으로 시프트

(1)(2)

x >> n

x 를 n 비트만큼 오른쪽으로 시프트

(1)(3)

~x

x 의 비트 반전

노트:

음의 시프트 수는 허락되지 않고 ValueError 를 일으킵니다.

A left shift by n bits is equivalent to multiplication by pow(2, n).

A right shift by n bits is equivalent to floor division by pow(2, n).

무한한 부호 비트가 있는 것과 같은 결과를 얻으려면, 유한한 2의 보수 표현으로 적어도 하나의 추가적인 부호 확장 비트를 사용하여 (1 + max(x.bit_length(), y.bit_length()) 이상의 작업 비트 폭) 이러한 계산을 수행하는 것으로 충분합니다.

정수 형에 대한 추가 메서드

int 형은 numbers.Integral 추상 베이스 클래스 를 구현합니다. 또한, 몇 가지 메서드를 더 제공합니다:

int.bit_length()

부호와 선행 0을 제외하고, 이진수로 정수를 나타내는 데 필요한 비트 수를 돌려줍니다:

>>> n = -37
>>> bin(n)
'-0b100101'
>>> n.bit_length()
6

좀 더 정확하게 말하자면, x 가 0이 아니면, x.bit_length() 는 2**(k-1) <= abs(x) < 2**k 를 만족하는 유일한 양의 정수 k 입니다. 동등하게, abs(x) 가 정확하게 반올림된 로그값을 가질 만큼 아주 작으면, k = 1 + int(log(abs(x), 2)) 가 됩니다. x 가 0이면, x.bit_length() 는 0 을 돌려줍니다.

다음 코드와 동등합니다:

def bit_length(self):
    s = bin(self)       # binary representation:  bin(-37) --> '-0b100101'
    s = s.lstrip('-0b') # remove leading zeros and minus sign
    return len(s)       # len('100101') --> 6

버전 3.1에 추가.

int.to_bytes(length, byteorder, *, signed=False)

정수를 나타내는 바이트의 배열을 돌려줍니다.

>>> (1024).to_bytes(2, byteorder='big')
b'\x04\x00'
>>> (1024).to_bytes(10, byteorder='big')
b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00'
>>> (-1024).to_bytes(10, byteorder='big', signed=True)
b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00'
>>> x = 1000
>>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little')
b'\xe8\x03'

정수는 length 바이트를 사용하여 표현됩니다. 정수가 주어진 바이트 수로 표현할 수 없는 경우 An OverflowError 를 일으킵니다.

byteorder 인자는 정수를 나타내는 데 사용되는 바이트 순서를 결정합니다. byteorder 가 "big" 인 경우, 최상위 바이트는 바이트 배열의 처음에 있습니다. byteorder 가 "little" 인 경우, 최상위 바이트는 바이트 배열의 끝에 있습니다. 호스트 시스템의 기본 바이트 순서를 요청하려면 바이트 순서 값으로 sys.byteorder 를 사용하십시오.

signed 인자는 정수를 표현하는데 2의 보수가 사용되는지를 결정합니다. signed 가 False 이고 음의 정수가 주어지면, OverflowError 가 일어납니다. signed 의 기본값은 False 입니다.

버전 3.2에 추가.

classmethod int.from_bytes(bytes, byteorder, *, signed=False)

주어진 바이트 배열로 표현되는 정수를 돌려줍니다.

>>> int.from_bytes(b'\x00\x10', byteorder='big')
16
>>> int.from_bytes(b'\x00\x10', byteorder='little')
4096
>>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True)
-1024
>>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False)
64512
>>> int.from_bytes([255, 0, 0], byteorder='big')
16711680

인자 bytes 는 바이트열류 객체 이거나 바이트를 생성하는 이터러블이어야 합니다.

byteorder 인자는 정수를 나타내는 데 사용되는 바이트 순서를 결정합니다. byteorder 가 "big" 인 경우, 최상위 바이트는 바이트 배열의 처음에 있습니다. byteorder 가 "little" 인 경우, 최상위 바이트는 바이트 배열의 끝에 있습니다. 호스트 시스템의 기본 바이트 순서를 요청하려면 바이트 순서 값으로 sys.byteorder 를 사용하십시오.

signed 인자는 정수를 표현하는데 2의 보수가 사용되는지를 나타냅니다.

버전 3.2에 추가.

실수에 대한 추가 메서드

float 형은 numbers.Real 추상 베이스 클래스 를 구현합니다. 또한, float는 다음과 같은 추가 메서드를 갖습니다.

float.as_integer_ratio()

비율이 원래 float와 정확히 같고 양의 분모를 갖는 정수 쌍을 돌려줍니다. 무한대에는 OverflowError 를, NaN 에는 a ValueError 를 일으킵니다.

float.is_integer()

float 인스턴스가 정숫값을 가진 유한이면 True 를, 그렇지 않으면 False 를 돌려줍니다:

>>> (-2.0).is_integer()
True
>>> (3.2).is_integer()
False

두 가지 메서드가 16진수 문자열과의 변환을 지원합니다. 파이썬의 float는 내부적으로 이진수로 저장되기 때문에 float를 십진수 문자열로 또는 그 반대로 변환하는 것은 보통 반올림 오류를 수반합니다. 이에 반해, 16진수 문자열은 부동 소수점 숫자의 정확한 표현과 지정을 가능하게 합니다. 이것은 디버깅 및 수치 작업에 유용할 수 있습니다.

float.hex()

부동 소수점의 16진수 문자열 표현을 돌려줍니다. 유한 부동 소수점의 경우, 이 표현은 항상 선행하는 0x 와 후행하는 p 와 지수를 포함합니다.

classmethod float.fromhex(s)

16진수 문자열 s 로 표현되는 float를 돌려주는 클래스 메서드. 문자열 s 는 앞뒤 공백을 가질 수 있습니다.

float.hex() 는 인스턴스 메서드인 반면, float.fromhex() 는 클래스 메서드임에 주의하세요.

16진수 문자열은 다음과 같은 형식을 취합니다:

[sign] ['0x'] integer ['.' fraction] ['p' exponent]

선택적인 sign 은 + 나 - 가 될 수 있고, integer 와 fraction 은 16진수 문자열이고, exponent 는 선택적인 선행 부호가 붙을 수 있는 십진수입니다. 대소 문자는 중요하지 않으며 integer 나 fraction 중 어느 하나에 적어도 하나의 16진수가 있어야 합니다. 이 문법은 C99 표준의 6.4.4.2 절에 지정된 문법과 비슷하며, 자바 1.5 이상에서 사용되는 문법과도 비슷합니다. 특히, float.hex() 의 출력은 C 또는 자바 코드에서 16진수의 부동 소수점 리터럴로 사용할 수 있으며, C의 %a 포맷 문자나 자바의 Double.toHexString 가 만들어내는 16진수 문자열은 float.fromhex() 가 받아들입니다.

지수는 16진수가 아닌 십진수로 쓰이고, 숫자에 곱해지는 2의 거듭제곱을 제공한다는 점에 유의하십시오. 예를 들어, 16진수 문자열 0x3.a7p10 는 부동 소수점 숫자 (3 + 10./16 + 7./16**2) * 2.0**10 또는 3740.0 를 나타냅니다:

>>> float.fromhex('0x3.a7p10')
3740.0

3740.0 에 역변환을 적용하면 같은 숫자를 나타내는 다른 16진수 문자열을 얻을 수 있습니다:

>>> float.hex(3740.0)
'0x1.d380000000000p+11'

숫자 형의 해싱

숫자 x 와 y, 서로 다른 형이어도 됩니다, 에 대하여, x == y 면 항상 hash(x) == hash(y) 일 것이 요구됩니다 (자세한 내용은 __hash__() 메서드 설명서를 보세요). 다양한 숫자 형(int, float, decimal.Decimal, fractions.Fraction 포함)들의 구현의 편의성과 효율 때문에, 파이썬의 숫자 형의 해시는 단일한 수학 함수에 기반을 두고 있고, 이 함수는 임의의 유리수에 대해 정의되어서 int 와 fractions.Fraction 의 모든 인스턴스, float와 decimal.Decimal 의 모든 유한 인스턴스에 적용됩니다. 본질에서, 이 함수는 고정 소수 P 에 대해 모듈로 P 환원(reduction modulo P)으로 주어집니다. P 의 값은 sys.hash_info 의 modulus 어트리뷰트로 파이썬에 제공됩니다.

CPython implementation detail: 현재, 사용되는 소수는 32-비트 C long을 가진 기계에서는 P = 2**31 - 1 이고, 64-비트 C long을 가진 기계에서는 P = 2**61 - 1 입니다.

다음은 규칙에 대한 세부 사항입니다:

x = m / n 이 음이 아닌 유리수이고 n 이 P 로 나뉘지 않는다면, hash(x) 를 m * invmod(n, P) % P 로 정의합니다. 여기서 invmod(n, P) 는 n 의 모듈로 P 역수를 줍니다.

x = m / n 이 음이 아닌 유리수이고 n 이 P 나뉘면 (하지만 m 은 나뉘지 않으면) n 은 모듈로 P 역수를 가지지 않고 위의 규칙은 적용되지 않습니다; 이 경우 hash(x) 를 상숫값 sys.hash_info.inf 로 정의합니다.

x = m / n 이 음의 유리수이면 hash(x) 를 -hash(-x) 로 정의합니다. 얻어진 해시가 -1 이면 -2 로 바꿉니다.

특별한 값 sys.hash_info.inf, -sys.hash_info.inf, sys.hash_info.nan 은 각각 무한대, 음의 무한대, nan 으로 사용됩니다. (모든 해시 가능 nan 은 같은 해시값을 가집니다.)

복소수(complex) z 의 경우, hash(z.real) + sys.hash_info.imag * hash(z.imag) 를 계산하여 실수부와 허수부의 해시값을 결합하는데, 2**sys.hash_info.width 의 모듈로로 환원해서 range(-2**(sys.hash_info.width - 1), 2**(sys.hash_info.width - 1)) 범위에 들어가도록 만듭니다. 다시 한번, 결과가 -1 이라면 -2 로 바꿉니다.

위의 규칙을 명확히 하기 위해, 여기에 유리수, float, complex 의 해시를 계산하는, 내장 해시와 동등한, 파이썬 코드를 예시합니다:

import sys, math

def hash_fraction(m, n):
    """Compute the hash of a rational number m / n.

    Assumes m and n are integers, with n positive.
    Equivalent to hash(fractions.Fraction(m, n)).

    """
    P = sys.hash_info.modulus
    # Remove common factors of P.  (Unnecessary if m and n already coprime.)
    while m % P == n % P == 0:
        m, n = m // P, n // P

    if n % P == 0:
        hash_value = sys.hash_info.inf
    else:
        # Fermat's Little Theorem: pow(n, P-1, P) is 1, so
        # pow(n, P-2, P) gives the inverse of n modulo P.
        hash_value = (abs(m) % P) * pow(n, P - 2, P) % P
    if m < 0:
        hash_value = -hash_value
    if hash_value == -1:
        hash_value = -2
    return hash_value

def hash_float(x):
    """Compute the hash of a float x."""

    if math.isnan(x):
        return sys.hash_info.nan
    elif math.isinf(x):
        return sys.hash_info.inf if x > 0 else -sys.hash_info.inf
    else:
        return hash_fraction(*x.as_integer_ratio())

def hash_complex(z):
    """Compute the hash of a complex number z."""

    hash_value = hash_float(z.real) + sys.hash_info.imag * hash_float(z.imag)
    # do a signed reduction modulo 2**sys.hash_info.width
    M = 2**(sys.hash_info.width - 1)
    hash_value = (hash_value & (M - 1)) - (hash_value & M)
    if hash_value == -1:
        hash_value = -2
    return hash_value

이터레이터 형

파이썬은 컨테이너에 대한 이터레이션 개념을 지원합니다. 이것은 두 개의 메서드를 사용해서 구현됩니다; 이것들은 사용자 정의 클래스가 이터레이션을 지원할 수 있도록 하는 데 사용됩니다. 아래에서 더 자세히 설명할 시퀀스는 항상 이터레이션 메서드를 지원합니다.

컨테이너 객체가 이터레이션 지원을 제공하려면 한가지 메서드를 정의할 필요가 있습니다.:

container.__iter__()

이터레이터 객체를 돌려줍니다. 이 객체는 아래에서 설명하는 이터레이터 프로토콜을 지원해야 합니다. 컨테이너가 여러 유형의 이터레이션을 지원하는 경우, 이터레이션 유형에 대한 이터레이터를 구체적으로 요구하는 추가 메서드를 제공할 수 있습니다. (여러 형태의 이터레이션을 지원하는 객체의 예로 너비 우선과 깊이 우선 탐색을 모두 지원하는 트리 구조를 들 수 있습니다.) 이 메서드는 파이썬/C API에서 파이썬 객체를 위한 구조체의 tp_iter 슬롯에 대응합니다.

이터레이터 객체 자체는 다음과 같은 두 가지 메서드를 지원해야 하는데, 둘이 함께 이터레이터 프로토콜 (iterator protocol) 를 이룹니다.:

iterator.__iter__()

이터레이터 객체 자신을 돌려줍니다. 이는 for 와 in 문에 컨테이너와 이터레이터 모두 사용될 수 있게 하는 데 필요합니다. 이 메서드는 파이썬/C API에서 파이썬 객체를 위한 구조체의 tp_iter 슬롯에 대응합니다.

iterator.__next__()

컨테이너의 다음 항목을 돌려줍니다. 더 항목이 없으면 StopIteration 예외를 일으킵니다. 이 메서드는 파이썬/C API에서 파이썬 객체를 위한 구조체의 tp_iternext 슬롯에 대응합니다.

파이썬은 일반적이거나 특정한 시퀀스 형, 딕셔너리, 기타 더 특화된 형태에 대한 이터레이션을 지원하기 위해 여러 이터레이터 객체를 정의합니다. 이터레이터 프로토콜의 구현을 넘어서 개별적인 형이 중요하지는 않습니다.

일단 이터레이터의 __next__() 메서드가 StopIteration 를 일으키면, 그 이후의 호출에 대해서도 같이 동작해야 합니다. 이 속성을 따르지 않는 구현은 망가진 것으로 간주합니다.

제너레이터 형

파이썬의 제너레이터 는 이터레이터 프로토콜을 구현하는 편리한 방법을 제공합니다. 컨테이너 객체의 __iter__() 메서드가 제너레이터로 구현되면, __iter__() 와 __next__() 메서드를 제공하는 이터레이터 객체(기술적으로, 제너레이터 객체)를 자동으로 돌려줍니다. 제너레이터에 대한 더 자세한 정보는 일드 표현식 설명서 에서 찾을 수 있습니다.

시퀀스 형 — list, tuple, range

세 가지 기본 시퀀스 형이 있습니다: 리스트, 튜플, 범위 객체. 바이너리 데이터 와 텍스트 문자열 의 처리를 위해 추가된 시퀀스 형들은 별도의 섹션에서 설명합니다.

공통 시퀀스 연산

다음 표의 연산들은 대부분의 가변과 불변 시퀀스에서 지원됩니다. 사용자 정의 시퀀스에서 이 연산들을 올바르게 구현하기 쉽게 하려고 collections.abc.Sequence ABC가 제공됩니다.

이 표는 우선순위에 따라 오름차순으로 시퀀스 연산들을 나열합니다. 표에서, s 와 t 는 같은 형의 시퀀스고, n, i, j, k 는 정수이고, x 는 s 가 요구하는 형과 값 제한을 만족하는 임의의 객체입니다.

in 과 not in 연산은 비교 연산과 우선순위가 같습니다. + (이어 붙이기)와 * (반복) 연산은 대응하는 숫자 연산과 같은 우선순위를 갖습니다. 3

연산

결과

노트

x in s

s 의 항목 중 하나가 x 와 같으면 True, 그렇지 않으면 False

(1)

x not in s

s 의 항목 중 하나가 x 와 같으면 False, 그렇지 않으면 True

(1)

s + t

s 와 t 의 이어 붙이기

(6)(7)

s * n 또는 n * s

s 를 그 자신에 n 번 더하는 것과 같습니다

(2)(7)

s[i]

s 의 i 번째 항목, 0에서 시작합니다

(3)

s[i:j]

s 의 i 에서 j 까지의 슬라이스

(3)(4)

s[i:j:k]

s 의 i 에서 j 까지 스텝 k 의 슬라이스

(3)(5)

len(s)

s 의 길이

min(s)

s 의 가장 작은 항목

max(s)

s 의 가장 큰 항목

s.index(x[, i[, j]])

(인덱스 i 또는 그 이후에, 인덱스 j 전에 등장하는) s 의 첫 번째 x 의 인덱스

(8)

s.count(x)

s 등장하는 x 의 총수

같은 형의 시퀀스는 비교를 지원합니다. 특히, 튜플과 리스트는 대응하는 항목들을 사전적으로 비교합니다. 이것은 같다고 비교되기 위해서는, 모든 항목이 같다고 비교되고, 두 시퀀스의 형과 길이가 같아야 함을 의미합니다. (자세한 내용은 언어 레퍼런스의 비교를 참조하십시오.)

노트:

in 과 not in 연산은 일반적으로 단순한 포함 검사를 위해서만 사용되지만, 몇몇 특수한 시퀀스 (str, bytes, bytearray 같은) 들은 서브 시퀀스 검사에 사용하기도 합니다:

>>> "gg" in "eggs"
True

n 의 값이 0 보다 작으면 0 으로 처리됩니다 (s 와 같은 형의 빈 시퀀스가 됩니다). 시퀀스 s 의 항목들이 복사되지 않음에 주의해야 합니다; 그들은 여러 번 참조됩니다. 이것은 종종 새 파이썬 프로그래머들을 괴롭힙니다; 이 코드를 살펴보세요:

>>> lists = [[]] * 3
>>> lists
[[], [], []]
>>> lists[0].append(3)
>>> lists
[[3], [3], [3]]

무슨 일이 일어났는가 하면, [[]] 는 빈 리스트를 포함하는 길이 1인 리스트인데, [[]] * 3 의 세 항목은 모두 같은 빈 리스트를 참조합니다. lists 의 어느 항목을 수정하더라도 이 하나의 리스트를 수정하게 됩니다. 서로 다른 리스트들을 포함하는 리스트는 이런 식으로 만들 수 있습니다:

>>> lists = [[] for i in range(3)]
>>> lists[0].append(3)
>>> lists[1].append(5)
>>> lists[2].append(7)
>>> lists
[[3], [5], [7]]

더 자세한 설명은 FAQ 항목 How do I create a multidimensional list?에서 얻을 수 있습니다.

i 또는 j 가 음수인 경우, 인덱스는 시퀀스 s 의 끝에 상대적입니다: len(s) + i 이나 len(s) + j 로 치환됩니다. 하지만 -0 은 여전히 0 입니다.

i 에서 j 까지의 s 의 슬라이스는 i <= k < j 를 만족하는 인덱스 k 의 항목들로 구성된 시퀀스로 정의됩니다. i 또는 j 가 len(s) 보다 크면 len(s) 을 사용합니다. i 가 생략되거나 None 이라면 0 을 사용합니다. j 가 생략되거나 None 이면 len(s) 을 사용합니다. i 가 j 보다 크거나 같으면 빈 슬라이스가 됩니다.

스텝 k 가 있는 i 에서 j 까지의 슬라이스는 0 <= n < (j-i)/k 를 만족하는 인덱스 x = i + n*k 의 항목들로 구성된 시퀀스로 정의됩니다. 다시 말하면, 인덱스는 i, i+k, i+2*k, i+3*k 등이며 j 에 도달할 때 멈춥니다 (하지만 절대 j 를 포함하지는 않습니다). k 가 양수면 i 와 j 는 더 큰 경우 len(s) 로 줄어듭니다. k 가 음수면, i 와 j 는 더 큰 경우 len(s) - 1 로 줄어듭니다. i 또는 j 가 생략되거나 None 이면, 그것들은 “끝” 값이 됩니다 (끝은 k 의 부호에 따라 달라집니다). k 는 0일 수 없음에 주의하세요. k 가 None 이면 1 로 취급됩니다.

불변 시퀀스를 이어 붙이면 항상 새로운 객체가 생성됩니다. 이것은 반복적으로 이어붙이기를 해서 시퀀스를 만들 때 실행 시간이 시퀀스의 총 길이의 제곱에 비례한다는 뜻입니다. 선형 실행 시간 비용을 얻으려면 아래 대안 중 하나로 전환해야 합니다:

str 객체를 이어붙이기를 한다면, 리스트를 만들고 마지막에 str.join() 을 사용하거나 io.StringIO 인스턴스에 쓰고 완료될 때 값을 꺼낼 수 있습니다

bytes 객체를 연결하는 경우 비슷하게 bytes.join() 또는 io.BytesIO 를 사용하거나, bytearray 객체를 사용하여 제자리에서 이어붙이기를 할 수 있습니다. bytearray 객체는 가변이고 효율적인 과할당(overallocation) 메커니즘을 가지고 있습니다.

tuple 객체를 이어붙이기를 한다면, 대신 list를 extend 하십시오.

다른 형의 경우 관련 클래스 문서를 조사하십시오.

일부 시퀀스 형 (예를 들어 range)은 특정 패턴을 따르는 항목 시퀀스 만 지원하기 때문에 시퀀스 이어붙이기나 반복을 지원하지 않습니다.

s 에 x 가 없을 때 index 는 ValueError 를 일으킵니다. 모든 구현이 추가 인자 i 및 j 전달을 지원하지는 않습니다. 이러한 인자를 사용하면 시퀀스의 부분을 효율적으로 검색할 수 있습니다. 추가 인자를 전달하는 것은 대략 s[i:j].index(x) 를 사용하는 것과 비슷한데, 데이터를 복사하지 않고 반환된 인덱스가 슬라이스의 시작이 아닌 시퀀스의 시작을 기준으로 삼습니다.

불변 시퀀스 형

불변 시퀀스 형이 일반적으로 구현하지만, 가변 시퀀스 형에서는 구현되지 않는 연산은 내장 hash() 에 대한 지원입니다.

이 지원은 tuple 인스턴스와 같은 불변 시퀀스를 dict 키로 사용하고 set 및 frozenset 인스턴스에 저장할 수 있도록 합니다.

해시 불가능 값을 포함하는 불변 시퀀스를 해시 하려고 하면 TypeError 를 일으킵니다.

가변 시퀀스 형

다음 표의 연산들은 가변 시퀀스 형에 정의되어 있습니다. 사용자 정의 시퀀스에서 이 연산들을 올바르게 구현하기 쉽게 하려고 collections.abc.MutableSequence ABC가 제공됩니다.

표에서 s 는 가변 시퀀스 형의 인스턴스이고, t 는 임의의 이터러블 객체이며, x 는 s 가 요구하는 형 및 값 제한을 충족시키는 임의의 객체입니다 (예를 들어, bytearray 는 값 제한 0 <= x <= 255 를 만족하는 정수만 받아들입니다.

연산

결과

노트

s[i] = x

s 의 항목 i 를 x 로 대체합니다

s[i:j] = t

i 에서 j 까지의 s 슬라이스가 이터러블 t 의 내용으로 대체됩니다

del s[i:j]

s[i:j] = [] 와 같습니다

s[i:j:k] = t

s[i:j:k] 의 항목들이 t 의 항목들로 대체됩니다

(1)

del s[i:j:k]

리스트에서 s[i:j:k] 의 항목들을 제거합니다

s.append(x)

시퀀스의 끝에 x 를 추가합니다 (s[len(s):len(s)] = [x] 와 같습니다)

s.clear()

s 에서 모든 항목을 제거합니다 (del s[:] 와 같습니다)

(5)

s.copy()

s 의 얕은 복사본을 만듭니다 (s[:] 와 같습니다)

(5)

s.extend(t) 또는 s += t

t 의 내용으로 s 를 확장합니다 (대부분 s[len(s):len(s)] = t 와 같습니다)

s *= n

내용이 n 번 반복되도록 s 를 갱신합니다

(6)

s.insert(i, x)

x 를 s 의 i 로 주어진 인덱스에 삽입합니다 (s[i:i] = [x] 와 같습니다)

s.pop([i])

i 에 있는 항목을 꺼냄과 동시에 s 에서 제거합니다

(2)

s.remove(x)

s[i] 가 x 와 같은 첫 번째 항목을 s 에서 제거합니다

(3)

s.reverse()

제자리에서 s 의 항목들의 순서를 뒤집습니다

(4)

노트:

t 는 교체할 슬라이스와 길이가 같아야 합니다.

선택적 인자 i 의 기본값은 -1 입니다. 그래서 기본적으로 마지막 항목이 제거되면서 반환됩니다.

x 가 s 에서 발견되지 않으면 remove 는 ValueError 를 일으킵니다.

큰 시퀀스를 뒤집을 때 공간 절약을 위해 reverse() 메서드는 제자리에서 시퀀스를 수정합니다. 부작용으로 작동한다는 것을 사용자에게 상기시키기 위해 뒤집힌 시퀀스를 돌려주지 않습니다.

clear()와 copy() 는 슬라이싱 연산을 지원하지 않는 (dict 와 set 같은) 가변 컨테이너들의 인터페이스와 일관성을 유지하기 위해 포함됩니다

버전 3.3에 추가: clear()와 copy() 메서드.

n 값은 정수이거나, __index__() 를 구현하는 객체입니다. n 이 0 이거나 음수면 시퀀스를 지웁니다. 시퀀스의 항목들은 복사되지 않습니다; 공통 시퀀스 연산에서 s * n 를 위해 설명한 것처럼 여러 번 참조됩니다.

리스트

리스트는 가변 시퀀스로, 일반적으로 등질 항목들의 모음을 저장하는 데 사용됩니다 (정확한 유사도는 응용 프로그램마다 다를 수 있습니다).

class list([iterable])

리스트는 여러 가지 방법으로 만들 수 있습니다:

대괄호를 사용하여 빈 리스트를 표시하기: []

대괄호를 사용하여 쉼표로 항목 구분하기: [a], [a, b, c]

리스트 컴프리헨션 사용하기: [x for x in iterable]

형 생성자를 사용하기: list() 또는 list(iterable)

생성자는 항목들과 그 순서가 iterable 과 같은 리스트를 만듭니다. iterable 은 시퀀스, 이터레이션을 지원하는 컨테이너, 이터레이터 객체가 될 수 있습니다. iterable 이 이미 리스트라면, iterable[:] 과 비슷하게 복사본을 만들어서 반환합니다. 예를 들어, list('abc') 는 ['a', 'b', 'c'] 를 반환하고 list( (1, 2, 3) ) 는 [1, 2, 3] 를 반환합니다. 인자가 주어지지 않으면, 생성자는 새로운 빈 리스트인 [] 을 만듭니다.

다른 많은 연산도 리스트를 만드는데, 내장 sorted() 도 그런 것 중 하나다.

리스트는 공통 과 가변 시퀀스 연산들을 모두 구현합니다. 또한, 리스트는 다음과 같은 추가 메서드를 제공합니다:

sort(*, key=None, reverse=False)

이 메서드는 항목 간의 < 비교만 사용하여 리스트를 제자리에서 정렬합니다. 예외는 억제되지 않습니다 - 비교 연산이 실패하면 전체 정렬 연산이 실패합니다 (리스트는 부분적으로 수정된 상태로 남아있게 됩니다).

sort() 는 키워드로만 전달할 수 있는 두 개의 인자를 받아들입니다 (키워드-전용 인자):

key 는 인자 하나를 받아들이는 함수를 지정하는데, 각 리스트 요소에서 비교 키를 추출하는 데 사용됩니다 (예들 들어, key=str.lower). 리스트의 각 항목에 해당하는 키는 한 번만 계산된 후 전체 정렬 프로세스에 사용됩니다. 기본값 None 은 리스트 항목들이 별도의 키값을 계산하지 않고 직접 정렬된다는 것을 의미합니다.

functools.cmp_to_key() 유틸리티는 2.x 스타일 cmp 함수를 key 함수로 변환하는 데 사용할 수 있습니다.

reverse 는 논리값입니다. True 로 설정되면, 각 비교가 역전된 것처럼 리스트 요소들이 정렬됩니다.

이 메서드는 큰 시퀀스를 정렬할 때 공간 절약을 위해 시퀀스를 제자리에서 수정합니다. 부작용으로 작동한다는 것을 사용자에게 상기시키기 위해 정렬된 시퀀스를 돌려주지 않습니다 (새 정렬 된 리스트 인스턴스를 명시적으로 요청하려면 sorted()를 사용하십시오).

sort() 메서드는 안정적임이 보장됩니다. 정렬은 같다고 비교되는 요소들의 상대적 순서를 변경하지 않으면 안정적입니다 — 이는 여러 번 정렬하는 데 유용합니다 (예를 들어, 부서별로 정렬한 후에 급여 등급으로 정렬).

CPython implementation detail: 리스트가 정렬되는 동안, 리스트를 변경하려고 할 때의, 또는 관찰하려고 할 때조차, 효과는 정의되지 않습니다. 파이썬의 C 구현은 그동안 리스트를 비어있는 것으로 보이게 하고, 정렬 중에 리스트가 변경되었음을 감지할 수 있다면 ValueError 를 일으킵니다.

튜플

튜플은 불변 시퀀스인데, 보통 이질적인 데이터의 모음을 저장하는 데 사용됩니다 (예를 들어, 내장 enumerate() 가 만드는 2-튜플). 튜플은 등질적인 데이터의 불변 시퀀스가 필요한 경우에도 사용됩니다 (예를 들어, set 이나 dict 인스턴스에 저장하고자 하는 경우).

class tuple([iterable])

튜플은 여러 가지 방법으로 만들 수 있습니다:

괄호를 사용하여 빈 튜플을 나타내기: ()

단일 항목 튜플을 위해 끝에 쉼표를 붙이기: a, 또는 (a,)

항목을 쉼표로 구분하기: a, b, c 또는``(a, b, c)``

내장 tuple() 사용하기: tuple() 또는 tuple(iterable)

생성자는 항목들과 그 순서가 iterable 과 같은 튜플을 만듭니다. iterable 은 시퀀스, 이터레이션을 지원하는 컨테이너, 이터레이터 객체가 될 수 있습니다. iterable 이 이미 튜플이라면 변경되지 않은 상태로 반환됩니다. 예를 들어 tuple('abc') 는 ('a', 'b', 'c') 를 반환하고, tuple( [1, 2, 3] ) 는 (1, 2, 3) 을 반환합니다. 인자가 주어지지 않으면, 생성자는 새로운 빈 튜플인 () 을 만듭니다.

튜플을 만드는 것은 실제로는 괄호가 아닌 쉼표임에 유의하십시오. 괄호는 빈 튜플의 경우를 제외하고는 선택적이거나 문법상의 모호함을 피하고자 필요합니다. 예를 들어, f(a, b, c) 는 3개의 인자를 가진 함수 호출이지만, f((a, b, c)) 는 하나의 인자로 3-튜플을 갖는 함수 호출입니다.

튜플은 공통 시퀀스 연산을 모두 구현합니다.

이름에 의한 액세스가 인덱스에 의한 액세스보다 더 명확한 이질적 데이터 컬렉션의 경우, collections.namedtuple() 이 단순한 튜플 객체보다 더 적절한 선택일 수 있습니다.

범위

range 형은 숫자의 불변 시퀀스를 나타내며 for 루프에서 특정 횟수만큼 반복하는 데 흔히 사용됩니다.

class range(stop)

class range(start, stop[, step])

범위 생성자에 대해 인자는 정수여야 합니다 (내장 int 또는 __index__ 특수 메서드를 구현하는 임의의 객체). step 인자가 생략되면 기본값 1 이 사용됩니다. start 인자가 생략되면 기본값 0 이 사용됩니다. step 이 0이면 ValueError 를 일으킵니다.

양수 step 의 경우, 범위 r 의 내용은 식 r[i] = start + step*i 에 의해 결정됩니다. 이때 i >= 0 이고 r[i] < stop 입니다.

음수 step 의 경우, 범위의 내용은 여전히 식 r[i] = start + step*i 에 의해 결정되지만, 제약 조건은 i >= 0 과 r[i] > stop 이 됩니다.

r[0] 제약 조건을 만족시키지 않으면 범위 객체는 비게 됩니다. 범위는 음의 인덱스를 지원하지만, 이는 시퀀스의 끝에서부터 양의 인덱스만큼 떨어진 인덱스로 해석됩니다.

sys.maxsize 보다 큰 절댓값을 포함하는 범위는 허용되지만, (len() 과 같은) 일부 기능은 OverflowError 를 발생시킬 수 있습니다.

범위 예제:

>>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(range(1, 11))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> list(range(0, 30, 5))
[0, 5, 10, 15, 20, 25]
>>> list(range(0, 10, 3))
[0, 3, 6, 9]
>>> list(range(0, -10, -1))
[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
>>> list(range(0))
[]
>>> list(range(1, 0))
[]

범위는 이어 붙이기와 반복을 제외한 공통 시퀀스 연산을 모두 구현합니다 (범위 객체는 엄격한 패턴을 따르는 시퀀스 만 나타낼 수 있는데 반복과 이어 붙이기는 보통 그 패턴을 위반한다는 사실에 기인합니다).

start

start 매개변수의 값 (또는 매개변수가 제공되지 않으면 0)

stop

stop 매개변수의 값

step

step 매개변수의 값 (또는 매개변수가 제공되지 않으면 1)

정규 list 나 tuple 에 비해 range 형의 장점은 range 객체는 표현하는 범위의 크기에 무관하게 항상 같은 (작은) 양의 메모리를 사용한다는 것입니다 (start, stop, step 값만을 저장하고, 필요에 따라 개별 항목과 하위 범위를 계산하기 때문입니다).

범위 객체는 collections.abc.Sequence ABC를 구현하고, 포함 검사, 요소 인덱스 검색, 슬라이싱, 음수 인덱스 지원과 같은 기능을 제공합니다 (시퀀스 형 — list, tuple, range 를 보세요):

>>> r = range(0, 20, 2)
>>> r
range(0, 20, 2)
>>> 11 in r
False
>>> 10 in r
True
>>> r.index(10)
5
>>> r[5]
10
>>> r[:5]
range(0, 10, 2)
>>> r[-1]
18

== 나 != 로 범위 객체가 같은지 검사하면 시퀀스처럼 비교합니다. 즉, 두 범위 객체가 같은 시퀀스의 값을 나타낼 때 같다고 취급됩니다. (같다고 비교되는 두 개의 범위 객체가 서로 다른 start, stop, step 어트리뷰트를 가질 수 있음에 주의하세요. 예를 들어, range(0) == range(2, 1, 3) 또는 range(0, 3, 2) == range(0, 4, 2).)

버전 3.2에서 변경: 시퀀스 ABC를 구현합니다. int 객체의 포함 검사는 모든 항목을 이터레이트하는 대신 상수 시간으로 수행됩니다.

버전 3.3에서 변경: (객체 아이덴티티에 기반을 두는 대신) 범위 객체가 정의하는 값들의 시퀀스에 기반을 둔 비교를 위해 ‘==’ 와 ‘!=’ 를 정의합니다.

버전 3.3에 추가: start, stop, step 어트리뷰트.

더 보기

linspace recipe [http://code.activestate.com/recipes/579000/] 에서는 부동 소수점 응용 프로그램에 적합한 범위의 지연된 버전을 구현하는 방법을 보여줍니다.

텍스트 시퀀스 형 — str

파이썬의 텍스트 데이터는 str, 또는 문자열 (strings), 객체를 사용하여 처리됩니다. 문자열은 유니코드 코드 포인트의 불변 시퀀스 입니다. 문자열 리터럴은 다양한 방법으로 작성됩니다:

작은따옴표: '"큰" 따옴표를 담을 수 있습니다'

큰따옴표: "'작은' 따옴표를 담을 수 있습니다".

삼중 따옴표: '''세 개의 작은따옴표''', """세 개의 큰따옴표"""

삼중 따옴표로 묶인 문자열은 여러 줄에 걸쳐있을 수 있습니다 - 연관된 모든 공백이 문자열 리터럴에 포함됩니다.

단일 표현식의 일부이고 그 들 사이에 공백만 있는 문자열 리터럴은 묵시적으로 단일 문자열 리터럴로 변환됩니다. 즉, ("spam " "eggs") == "spam eggs".

지원되는 이스케이프 시퀀스와 대부분의 이스케이프 시퀀스 처리를 비활성화하는 r (“날”) 접두어를 포함하여 문자열 리터럴의 다양한 형식에 대한 자세한 내용은 문자열과 바이트열 리터럴 을 참조하십시오.

문자열은 str 생성자를 사용하여 다른 객체로부터 만들어질 수도 있습니다.

별도의 “문자” 형이 없으므로 문자열을 인덱싱하면 길이가 1인 문자열이 생성됩니다. 즉, 비어 있지 않은 문자열 s 의 경우, s[0] == s[0:1] 입니다.

또한, 가변 문자열형은 없지만, 여러 단편으로부터 문자열을 효율적으로 구성하는데 str.join() 또는 io.StringIO 를 사용할 수 있습니다.

버전 3.3에서 변경: 파이썬 2시리즈와의 하위 호환성을 위해서, u 접두어가 문자열 리터럴에 다시 한번 허용됩니다. 문자열 리터럴의 의미에 영향을 미치지 않으며 r 접두사와 결합 될 수 없습니다.

class str(object='')

class str(object=b'', encoding='utf-8', errors='strict')

object 의 문자열 버전을 돌려줍니다. object 가 제공되지 않으면, 빈 문자열을 돌려줍니다. 그렇지 않으면, str() 의 동작은 encoding 또는 errors 가 주어졌는지에 따라 달라지는데, 다음과 같습니다.

encoding 과 errors 모두 주어지지 않으면, str(object) 는 object.__str__() 를 돌려주는데, object 의 “비형식적” 또는 멋지게 인쇄 가능한 문자열 표현입니다. 문자열 객체의 경우, 이것은 문자열 자신입니다. 만약 object 가 __str__() 메서드를 가지고 있지 않다면, str()은 대신 repr(object) 를 돌려줍니다.

encoding 또는 errors 중 적어도 하나가 주어지면, object 는 bytes-like object (예, bytes 또는 bytearray) 이어야 합니다. 이 경우, object 가 bytes (또는 bytearray) 객체이면, str(bytes, encoding, errors) 는 bytes.decode(encoding, errors) 와 동등합니다. 그 이외의 경우, bytes.decode() 호출 전에 버퍼 객체의 하부 바이트열 객체를 얻습니다. 버퍼 객체에 대한 정보는 바이너리 시퀀스 형 — bytes, bytearray, memoryview와 버퍼 프로토콜 를 보십시오.

encoding 또는 errors 인자 없이 bytes 객체를 str() 에 전달하는 것은 비형식적 문자열 표현을 반환하는 첫 번째 상황에 해당합니다 (파이썬 명령행 옵션 -b 도 보십시오). 예를 들면:

>>> str(b'Zoot!')
"b'Zoot!'"

str 클래스와 그 메서드에 대한 더 자세한 정보는 텍스트 시퀀스 형 — str와 아래의 문자열 메서드 섹션을 보십시오. 포맷된 문자열을 출력하려면 포맷 문자열 리터럴 및 포맷 문자열 문법 섹션을 참조하십시오. 또한, 텍스트 처리 서비스 섹션을 보십시오.

문자열 메서드

문자열은 공통 시퀀스 연산들을 모두 구현하고, 아래에 기술된 추가적인 메서드도 구현합니다.

문자열은 또한 두 가지 스타일의 문자열 포매팅을 지원합니다. 하나는 큰 폭의 유연성과 사용자 지정을 제공하고 (참조 str.format(), 포맷 문자열 문법, 사용자 지정 문자열 포매팅을 참조하세요) 다른 하나는 C printf 스타일에 기반을 두는데, 더 좁은 범위의 형을 처리하고 올바르게 사용하기는 다소 어렵지만, 처리할 수 있는 경우에는 종종 더 빠릅니다 (printf 스타일 문자열 포매팅).

표준 라이브러리의 텍스트 처리 서비스 섹션은 다양한 텍스트 관련 유틸리티를 (re 모듈의 정규식 지원을 포함합니다) 제공하는 많은 다른 모듈들을 다룹니다.

str.capitalize()

첫 문자가 대문자이고 나머지가 소문자인 문자열의 복사본을 돌려줍니다.

str.casefold()

케이스 폴딩 된 문자열을 반환합니다. 케이스 폴딩 된 문자열은 대소문자를 무시한 매칭에 사용될 수 있습니다.

케이스 폴딩은 소문자로 변환하는 것과 비슷하지만 문자열의 모든 케이스 구분을 제거하기 때문에 보다 공격적입니다. 예를 들어, 독일어 소문자 'ß' 는 "ss" 와 동등합니다. 이미 소문자이므로 lower() 는 'ß' 에 아무런 영향을 미치지 않습니다; casefold() 는 "ss" 로 변환합니다.

케이스 폴딩 알고리즘은 유니코드 표준의 섹션 3.13 에 설명되어 있습니다.

버전 3.3에 추가.

str.center(width[, fillchar])

길이 width 인 문자열의 가운데에 정렬한 값을 돌려줍니다. 지정된 fillchar (기본값은 ASCII 스페이스)을 사용하여 채웁니다. width 가 len(s) 보다 작거나 같은 경우 원래 문자열이 반환됩니다.

str.count(sub[, start[, end]])

범위 [start, end] 에서 부분 문자열 sub 가 중첩되지 않고 등장하는 횟수를 돌려줍니다. 선택적 인자 start 와 end 는 슬라이스 표기법으로 해석됩니다.

str.encode(encoding="utf-8", errors="strict")

문자열의 바이트열 객체로 인코딩된 버전을 돌려줍니다. 기본 인코딩은 'utf-8' 입니다. errors 는 다른 오류 처리 방식을 설정하기 위해 제공될 수 있습니다. errors 의 기본값은 'strict' 인데, 인코딩 오류가 있으면 UnicodeError 를 일으키라는 뜻입니다. 다른 가능한 값은 'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace' 와 codecs.register_error() 를 통해 등록된 다른 이름들입니다. Error Handlers를 보세요. 가능한 인코딩의 목록을 보려면 Standard Encodings 섹션을 참조하십시오.

버전 3.1에서 변경: 키워드 인자 지원이 추가되었습니다.

str.endswith(suffix[, start[, end]])

문자열이 지정된 suffix 로 끝나면 True 를 돌려주고, 그렇지 않으면 False 를 돌려줍니다. suffix 는 찾고자 하는 접미사들의 튜플이 될 수도 있습니다. 선택적 start 가 제공되면 그 위치에서 검사를 시작합니다. 선택적 end 를 사용하면 해당 위치에서 비교를 중단합니다.

str.expandtabs(tabsize=8)

모든 탭 문자들을 현재의 열과 주어진 탭 크기에 따라 하나나 그 이상의 스페이스로 치환한 문자열의 복사본을 돌려줍니다. 탭 위치는 tabsize 문자마다 발생합니다 (기본값은 8이고, 열 0, 8, 16 등에 탭 위치를 지정합니다). 문자열을 확장하기 위해 현재 열이 0으로 설정되고 문자열을 문자 단위로 검사합니다. 문자가 탭 (\t) 이면, 현재 열이 다음 탭 위치와 같아질 때까지 하나 이상의 스페이스 문자가 삽입됩니다. (탭 문자 자체는 복사되지 않습니다.) 문자가 개행 문자 (\n) 또는 캐리지 리턴 (\r) 이면 복사되고 현재 열은 0으로 재설정됩니다. 다른 문자는 변경되지 않고 복사되고 현재 열은 인쇄할 때 문자가 어떻게 표시되는지에 관계없이 1씩 증가합니다.

>>> '01\t012\t0123\t01234'.expandtabs()
'01      012     0123    01234'
>>> '01\t012\t0123\t01234'.expandtabs(4)
'01  012 0123    01234'

str.find(sub[, start[, end]])

부분 문자열 sub 가 슬라이스 s[start:end] 내에 등장하는 가장 작은 문자열의 인덱스를 돌려줍니다. 선택적 인자 start 와 end 는 슬라이스 표기법으로 해석됩니다. sub 가 없으면 -1 을 돌려줍니다.

참고

find() 메서드는 sub 의 위치를 알아야 할 경우에만 사용해야 합니다. sub 가 부분 문자열인지 확인하려면 in 연산자를 사용하십시오:

>>> 'Py' in 'Python'
True

str.format(*args, **kwargs)

문자열 포맷 연산을 수행합니다. 이 메서드가 호출되는 문자열은 리터럴 텍스트나 중괄호 {} 로 구분된 치환 필드를 포함할 수 있습니다. 각 치환 필드는 위치 인자의 숫자 인덱스나 키워드 인자의 이름을 가질 수 있습니다. 각 치환 필드를 해당 인자의 문자열 값으로 치환한 문자열의 사본을 돌려줍니다.

>>> "The sum of 1 + 2 is {0}".format(1+2)
'The sum of 1 + 2 is 3'

포맷 문자열에 지정할 수 있는 다양한 포맷 옵션에 대한 설명은 포맷 문자열 문법 을 참조하십시오.

참고

숫자(int, float, complex, decimal.Decimal와 서브 클래스)를 n 형식으로 포매팅할 때 (예: '{:n}'.format(1234)), 이 함수는 일시적으로 LC_CTYPE 로케일을 LC_NUMERIC 로케일로 설정하여 localeconv() 의 decimal_point 와 thousands_sep 필드를 디코드하는데, 이 필드들이 ASCII가 아니거나 1바이트보다 길고, LC_NUMERIC 로케일이 LC_CTYPE 로케일과 다를 때만 그렇게 합니다. 이 임시 변경은 다른 스레드에 영향을 줍니다.

버전 3.7에서 변경: 숫자를 n 형식으로 포매팅할 때, 이 함수는 어떤 경우에 일시적으로 LC_CTYPE 로케일을 LC_NUMERIC 로케일로 설정합니다.

str.format_map(mapping)

str.format(**mapping) 과 비슷하지만, dict로 복사되지 않고 mapping 을 직접 사용합니다. 예를 들어 mapping 이 dict 서브 클래스면 유용합니다:

>>> class Default(dict):
...     def __missing__(self, key):
...         return key
...
>>> '{name} was born in {country}'.format_map(Default(name='Guido'))
'Guido was born in country'

버전 3.2에 추가.

str.index(sub[, start[, end]])

find() 과 비슷하지만, 부분 문자열을 찾을 수 없는 경우 ValueError 를 일으킵니다.

str.isalnum()

Return True if all characters in the string are alphanumeric and there is at least one character, False otherwise. A character c is alphanumeric if one of the following returns True: c.isalpha(), c.isdecimal(), c.isdigit(), or c.isnumeric().

str.isalpha()

Return True if all characters in the string are alphabetic and there is at least one character, False otherwise. Alphabetic characters are those characters defined in the Unicode character database as “Letter”, i.e., those with general category property being one of “Lm”, “Lt”, “Lu”, “Ll”, or “Lo”. Note that this is different from the “Alphabetic” property defined in the Unicode Standard.

str.isascii()

Return True if the string is empty or all characters in the string are ASCII, False otherwise. ASCII characters have code points in the range U+0000-U+007F.

버전 3.7에 추가.

str.isdecimal()

Return True if all characters in the string are decimal characters and there is at least one character, False otherwise. Decimal characters are those that can be used to form numbers in base 10, e.g. U+0660, ARABIC-INDIC DIGIT ZERO. Formally a decimal character is a character in the Unicode General Category “Nd”.

str.isdigit()

Return True if all characters in the string are digits and there is at least one character, False otherwise. Digits include decimal characters and digits that need special handling, such as the compatibility superscript digits. This covers digits which cannot be used to form numbers in base 10, like the Kharosthi numbers. Formally, a digit is a character that has the property value Numeric_Type=Digit or Numeric_Type=Decimal.

str.isidentifier()

Return True if the string is a valid identifier according to the language definition, section 식별자와 키워드.

def 나 class와 같은 예약 식별자를 검사하려면 keyword.iskeyword() 를 사용하십시오.

str.islower()

Return True if all cased characters 4 in the string are lowercase and there is at least one cased character, False otherwise.

str.isnumeric()

Return True if all characters in the string are numeric characters, and there is at least one character, False otherwise. Numeric characters include digit characters, and all characters that have the Unicode numeric value property, e.g. U+2155, VULGAR FRACTION ONE FIFTH. Formally, numeric characters are those with the property value Numeric_Type=Digit, Numeric_Type=Decimal or Numeric_Type=Numeric.

str.isprintable()

Return True if all characters in the string are printable or the string is empty, False otherwise. Nonprintable characters are those characters defined in the Unicode character database as “Other” or “Separator”, excepting the ASCII space (0x20) which is considered printable. (Note that printable characters in this context are those which should not be escaped when repr() is invoked on a string. It has no bearing on the handling of strings written to sys.stdout or sys.stderr.)

str.isspace()

Return True if there are only whitespace characters in the string and there is at least one character, False otherwise.

A character is whitespace if in the Unicode character database (see unicodedata), either its general category is Zs (“Separator, space”), or its bidirectional class is one of WS, B, or S.

str.istitle()

Return True if the string is a titlecased string and there is at least one character, for example uppercase characters may only follow uncased characters and lowercase characters only cased ones. Return False otherwise.

str.isupper()

Return True if all cased characters 4 in the string are uppercase and there is at least one cased character, False otherwise.

str.join(iterable)

iterable 의 문자열들을 이어 붙인 문자열을 돌려줍니다. iterable 에 bytes 객체나 기타 문자열이 아닌 값이 있으면 TypeError 를 일으킵니다. 요소들 사이의 구분자는 이 메서드를 제공하는 문자열입니다.

str.ljust(width[, fillchar])

왼쪽으로 정렬된 문자열을 길이 width 인 문자열로 돌려줍니다. 지정된 fillchar (기본값은 ASCII 스페이스)을 사용하여 채웁니다. width 가 len(s) 보다 작거나 같은 경우 원래 문자열이 반환됩니다.

str.lower()

모든 케이스 문자 4 가 소문자로 변환된 문자열의 복사본을 돌려줍니다.

사용되는 소문자 변환 알고리즘은 유니코드 표준의 섹션 3.13에 설명되어 있습니다.

str.lstrip([chars])

선행 문자가 제거된 문자열의 복사본을 돌려줍니다. chars 인자는 제거할 문자 집합을 지정하는 문자열입니다. 생략되거나 None 이라면, chars 인자의 기본값은 공백을 제거하도록 합니다. chars 인자는 접두사가 아닙니다; 모든 값 조합이 제거됩니다:

>>> '   spacious   '.lstrip()
'spacious   '
>>> 'www.example.com'.lstrip('cmowz.')
'example.com'

static str.maketrans(x[, y[, z]])

이 정적 메서드는 str.translate() 에 사용할 수 있는 변환표를 돌려줍니다.

인자가 하나만 있으면 유니코드 포인트 (정수) 또는 문자 (길이가 1인 문자열)를 유니코드 포인트, 문자열 (임의 길이) 또는 None 으로 매핑하는 딕셔너리여야 합니다. 문자 키는 유니코드 포인트로 변환됩니다.

인자가 두 개면 길이가 같은 문자열이어야 하며, 결과 딕셔너리에서, x의 각 문자는 y의 같은 위치에 있는 문자로 대응됩니다. 세 번째의 인자가 있는 경우, 문자열이어야 하는데 각 문자가 None 으로 대응되는 결과를 줍니다.

str.partition(sep)

sep 가 처음 나타나는 위치에서 문자열을 나누고, 구분자 앞에 있는 부분, 구분자 자체, 구분자 뒤에 오는 부분으로 구성된 3-튜플을 돌려줍니다. 구분자가 발견되지 않으면, 문자열 자신과 그 뒤를 따르는 두 개의 빈 문자열로 구성된 3-튜플을 돌려줍니다.

str.replace(old, new[, count])

모든 부분 문자열 old 가 new 로 치환된 문자열의 복사본을 돌려줍니다. 선택적 인자 count 가 주어지면, 앞의 count 개만 치환됩니다.

str.rfind(sub[, start[, end]])

부분 문자열 sub 가 s[start:end] 내에 등장하는 가장 큰 문자열의 인덱스를 돌려줍니다. 선택적 인자 start 와 end 는 슬라이스 표기법으로 해석됩니다. 실패하면 -1 을 돌려줍니다.

str.rindex(sub[, start[, end]])

rfind()와 비슷하지만, 부분 문자열 sub 를 찾을 수 없는 경우 ValueError 를 일으킵니다.

str.rjust(width[, fillchar])

오른쪽으로 정렬된 문자열을 길이 width 인 문자열로 돌려줍니다. 지정된 fillchar (기본값은 ASCII 스페이스)을 사용하여 채웁니다. width 가 len(s) 보다 작거나 같은 경우 원래 문자열이 반환됩니다.

str.rpartition(sep)

sep 가 마지막으로 나타나는 위치에서 문자열을 나누고, 구분자 앞에 있는 부분, 구분자 자체, 구분자 뒤에 오는 부분으로 구성된 3-튜플을 돌려줍니다. 구분자가 발견되지 않으면, 두 개의 빈 문자열과 그 뒤를 따르는 문자열 자신으로 구성된 3-튜플을 돌려줍니다.

str.rsplit(sep=None, maxsplit=-1)

sep 를 구분자 문자열로 사용하여 문자열에 있는 단어들의 리스트를 돌려줍니다. maxsplit 이 주어지면 가장 오른쪽에서 최대 maxsplit 번의 분할이 수행됩니다. sep 이 지정되지 않거나 None 이면, 구분자로 모든 공백 문자가 사용됩니다. 오른쪽에서 분리하는 것을 제외하면, rsplit()는 아래에서 자세히 설명될 split()처럼 동작합니다.

str.rstrip([chars])

후행 문자가 제거된 문자열의 복사본을 돌려줍니다. chars 인자는 제거할 문자 집합을 지정하는 문자열입니다. 생략되거나 None 이라면, chars 인자의 기본값은 공백을 제거하도록 합니다. chars 인자는 접미사가 아닙니다; 모든 값 조합이 제거됩니다:

>>> '   spacious   '.rstrip()
'   spacious'
>>> 'mississippi'.rstrip('ipz')
'mississ'

str.split(sep=None, maxsplit=-1)

sep 를 구분자 문자열로 사용하여 문자열에 있는 단어들의 리스트를 돌려줍니다. maxsplit 이 주어지면 최대 maxsplit 번의 분할이 수행됩니다 (따라서, 리스트는 최대 maxsplit+1 개의 요소를 가지게 됩니다). maxsplit 이 지정되지 않았거나 -1 이라면 분할 수에 제한이 없습니다 (가능한 모든 분할이 만들어집니다).

sep 이 주어지면, 연속된 구분자는 묶이지 않고 빈 문자열을 구분하는 것으로 간주합니다 (예를 들어, '1,,2'.split(',') 는 ['1', '', '2'] 를 돌려줍니다). sep 인자는 여러 문자로 구성될 수 있습니다 (예를 들어, '1<>2<>3'.split('<>') 는 ['1', '2', '3'] 를 돌려줍니다). 지정된 구분자로 빈 문자열을 나누면 [''] 를 돌려줍니다.

예를 들면:

>>> '1,2,3'.split(',')
['1', '2', '3']
>>> '1,2,3'.split(',', maxsplit=1)
['1', '2,3']
>>> '1,2,,3,'.split(',')
['1', '2', '', '3', '']

sep 이 지정되지 않거나 None 이면, 다른 분할 알고리즘이 적용됩니다: 연속된 공백 문자는 단일한 구분자로 간주하고, 문자열이 선행이나 후행 공백을 포함해도 결과는 시작과 끝에 빈 문자열을 포함하지 않습니다. 결과적으로, 빈 문자열이나 공백만으로 구성된 문자열을 None 구분자로 나누면 [] 를 돌려줍니다.

예를 들면:

>>> '1 2 3'.split()
['1', '2', '3']
>>> '1 2 3'.split(maxsplit=1)
['1', '2 3']
>>> '   1   2   3   '.split()
['1', '2', '3']

str.splitlines([keepends])

줄 경계에서 나눈 문자열의 줄 리스트를 돌려줍니다. keepends 가 참으로 주어지지 않는 한 결과 리스트에 줄 바꿈은 포함되지 않습니다.

이 메서드는 다음 줄 경계에서 나눕니다. 특히, 경계는 유니버설 줄 넘김 을 포함합니다.

표현

설명

\n

줄 넘김

\r

캐리지 리턴

\r\n

캐리지 리턴 + 줄 넘김

\v 또는 \x0b

수직 탭

\f 또는 \x0c

폼 피드

\x1c

파일 구분자

\x1d

그룹 구분자

\x1e

레코드 구분자

\x85

다음 줄 (C1 제어 코드)

\u2028

줄 구분자

\u2029

문단 구분자

버전 3.2에서 변경: \v 와 \f 를 줄 경계 목록에 추가했습니다.

예를 들면:

>>> 'ab c\n\nde fg\rkl\r\n'.splitlines()
['ab c', '', 'de fg', 'kl']
>>> 'ab c\n\nde fg\rkl\r\n'.splitlines(keepends=True)
['ab c\n', '\n', 'de fg\r', 'kl\r\n']

구분자 문자열 sep 이 주어졌을 때 split() 와 달리, 이 메서드는 빈 문자열에 대해서 빈 리스트를 돌려주고, 마지막 줄 바꿈은 새 줄을 만들지 않습니다:

>>> "".splitlines()
[]
>>> "One line\n".splitlines()
['One line']

비교해 보면, split('\n') 는 이렇게 됩니다:

>>> ''.split('\n')
['']
>>> 'Two lines\n'.split('\n')
['Two lines', '']

str.startswith(prefix[, start[, end]])

문자열이 지정된 prefix 로 시작하면 True 를 돌려주고, 그렇지 않으면 False 를 돌려줍니다. prefix 는 찾고자 하는 접두사들의 튜플이 될 수도 있습니다. 선택적 start 가 제공되면 그 위치에서 검사를 시작합니다. 선택적 end 를 사용하면 해당 위치에서 비교를 중단합니다.

str.strip([chars])

선행과 후행 문자가 제거된 문자열의 복사본을 돌려줍니다. chars 인자는 제거할 문자 집합을 지정하는 문자열입니다. 생략되거나 None 이라면, chars 인자의 기본값은 공백을 제거하도록 합니다. chars 인자는 접두사나 접미사가 아닙니다; 모든 값 조합이 제거됩니다:

>>> '   spacious   '.strip()
'spacious'
>>> 'www.example.com'.strip('cmowz.')
'example'

가장 바깥쪽의 선행 또는 후행 chars 인자 값들이 문자열에서 제거됩니다. 문자는 chars 에 있는 문자 집합에 포함되지 않은 문자에 도달할 때까지 맨 앞에서 제거됩니다. 끝에서도 유사한 동작이 수행됩니다. 예를 들면:

>>> comment_string = '#....... Section 3.2.1 Issue #32 .......'
>>> comment_string.strip('.#! ')
'Section 3.2.1 Issue #32'

str.swapcase()

대문자를 소문자로, 그 반대로 마찬가지로 변환 한 문자열의 복사본을 돌려줍니다. s.swapcase().swapcase() == s 가 반드시 성립하지 않음에 주의하십시오.

str.title()

단어가 대문자로 시작하고 나머지 문자는 소문자가 되도록 문자열의 제목 케이스 버전을 돌려줍니다.

예를 들면:

>>> 'Hello world'.title()
'Hello World'

이 알고리즘은 단어를 글자들의 연속으로 보는 간단한 언어 독립적 정의를 사용합니다. 이 정의는 여러 상황에서 작동하지만, 축약과 소유의 아포스트로피가 단어 경계를 형성한다는 것을 의미하고, 이는 원하는 결과가 아닐 수도 있습니다:

>>> "they're bill's friends from the UK".title()
"They'Re Bill'S Friends From The Uk"

정규식을 사용하여 아포스트로피에 대한 해결 방법을 구성할 수 있습니다:

>>> import re
>>> def titlecase(s):
...     return re.sub(r"[A-Za-z]+('[A-Za-z]+)?",
...                   lambda mo: mo.group(0)[0].upper() +
...                              mo.group(0)[1:].lower(),
...                   s)
...
>>> titlecase("they're bill's friends.")
"They're Bill's Friends."

str.translate(table)

각 문자를 지정된 변환표를 사용해 매핑한 문자열의 복사본을 돌려줍니다. table은 __getitem__() 을 통한 인덱싱을 구현하는 객체여야 하는데, 보통 매핑 이나 시퀀스 입니다. 유니코드 포인트 (정수)로 인덱싱할 때, table 객체는 다음 중 하나를 수행할 수 있습니다: 그 문자를 하나 이상의 다른 문자들로 매핑하기 위해 유니코드 포인트나 문자열을 돌려줍니다; 결과 문자열에서 그 문자를 제거하기 위해 None 을 돌려줍니다; 그 문자를 자기 자신으로 매핑하기 위해 LookupError 예외를 일으킵니다.

str.maketrans() 를 사용하여 다른 형식의 문자 대 문자 매핑으로 부터 변환 맵을 만들 수 있습니다.

커스텀 문자 매핑에 대한 보다 유연한 접근법은 codecs 모듈을 참고하십시오.

str.upper()

모든 케이스 문자 4 가 대문자로 변환된 문자열의 복사본을 돌려줍니다. s 가 케이스 없는 문자를 포함하거나 결과 문자의 유니코드 범주가 “Lu” (Letter, 대문자) 가 아닌 경우, 예를 들어 “Lt” (Letter, 제목 케이스), s.upper().isupper() 가 False 일 수 있음에 주의하십시오.

사용되는 대문자 변환 알고리즘은 유니코드 표준의 섹션 3.13에 설명되어 있습니다.

str.zfill(width)

길이가 width 인 문자열을 만들기 위해 ASCII '0' 문자를 왼쪽에 채운 문자열의 복사본을 돌려줍니다. 선행 부호 접두어('+'/'-')는 부호 문자의 앞이 아니라 뒤 에 채워 넣는 것으로 처리됩니다. width 가 len(s) 보다 작거나 같은 경우 원래 문자열을 돌려줍니다.

예를 들면:

>>> "42".zfill(5)
'00042'
>>> "-42".zfill(5)
'-0042'

printf 스타일 문자열 포매팅

참고

여기에 설명된 포맷 연산은 여러 가지 일반적인 오류를 (예를 들어 튜플과 딕셔너리를 올바르게 표시하지 못하는 것) 유발하는 다양한 문제점들이 있습니다. 새 포맷 문자열 리터럴 나 str.format() 인터페이스 혹은 템플릿 문자열 을 사용하면 이러한 오류를 피할 수 있습니다. 이 대안들은 또한 텍스트 포매팅에 더욱 강력하고 유연하며 확장 가능한 접근법을 제공합니다.

문자열 객체는 한가지 고유한 내장 연산을 갖고 있습니다: % 연산자 (모듈로). 이것은 문자열 포매팅 또는 치환 연산자라고도 합니다. format % values 가 주어질 때 (format 은 문자열입니다), format 내부의 % 변환 명세는 0개 이상의 values 의 요소로 대체됩니다. 이 효과는 C 언어에서 sprintf()를 사용하는 것과 비슷합니다.

format 이 하나의 인자를 요구하면, values 는 하나의 비 튜플 객체 일 수 있습니다. 5 그렇지 않으면, values 는 format 문자열이 지정하는 항목의 수와 같은 튜플이거나 단일 매핑 객체 (예를 들어, 딕셔너리) 이어야 합니다.

변환 명세는 두 개 이상의 문자를 포함하며 다음과 같은 구성 요소들을 포함하는데, 반드시 이 순서대로 나와야 합니다:

'%' 문자: 명세의 시작을 나타냅니다.

매핑 키 (선택 사항): 괄호로 둘러싸인 문자들의 시퀀스로 구성됩니다 (예를 들어, (somename)).

변환 플래그 (선택 사항): 일부 변환 유형의 결과에 영향을 줍니다.

최소 필드 폭 (선택 사항): '*' (애스터리스크) 로 지정하면, 실제 폭은 values 튜플의 다음 요소에서 읽히고, 변환할 객체는 최소 필드 폭과 선택적 정밀도 뒤에 옵니다.

정밀도 (선택 사항): '.' (점) 다음에 정밀도가 옵니다. '*' (애스터리스크) 로 지정하면, 실제 정밀도는 values 튜플의 다음 요소에서 읽히고, 변환할 값은 정밀도 뒤에 옵니다.

길이 수정자 (선택 사항).

변환 유형.

오른쪽 인자가 딕셔너리 (또는 다른 매핑 형) 인 경우, 문자열에 있는 변환 명세는 반드시 '%' 문자 바로 뒤에 그 딕셔너리의 매핑 키를 괄호로 둘러싼 형태로 포함해야 합니다. 매핑 키는 포맷할 값을 매핑으로 부터 선택합니다. 예를 들어:

>>> print('%(language)s has %(number)03d quote types.' %
...       {'language': "Python", "number": 2})
Python has 002 quote types.

이 경우 * 지정자를 사용할 수 없습니다 (순차적인 매개변수 목록이 필요하기 때문입니다).

변환 플래그 문자는 다음과 같습니다:

플래그

뜻

'#'

값 변환에 “대체 형식” (아래에 정의되어있습니다) 을 사용합니다.

'0'

변환은 숫자 값의 경우 0으로 채웁니다.

'-'

변환된 값은 왼쪽으로 정렬됩니다 (둘 다 주어지면 '0' 변환보다 우선 합니다).

' '

(스페이스) 부호 있는 변환 때문에 만들어진 양수 앞에 빈칸을 남겨둡니다 (음수면 빈 문자열입니다).

'+'

부호 문자 ('+' or '-') 가 변환 앞에 놓입니다 (' ' 플래그에 우선합니다).

길이 수정자 (h, l, L) 를 제공할 수는 있지만, 파이썬에서 필요하지 않기 때문에 무시됩니다 – 예를 들어 %ld 는 %d 와 같습니다.

변환 유형은 다음과 같습니다:

변환

뜻

노트

'd'

부호 있는 정수 십진 표기.

'i'

부호 있는 정수 십진 표기.

'o'

부호 있는 8진수 값.

(1)

'u'

쓸데없는 유형 – 'd' 와 같습니다.

(6)

'x'

부호 있는 16진수 (소문자).

(2)

'X'

부호 있는 16진수 (대문자).

(2)

'e'

부동 소수점 지수 형식 (소문자).

(3)

'E'

부동 소수점 지수 형식 (대문자).

(3)

'f'

부동 소수점 십진수 형식.

(3)

'F'

부동 소수점 십진수 형식.

(3)

'g'

부동 소수점 형식. 지수가 -4보다 작거나 정밀도 보다 작지 않으면 소문자 지수형식을 사용하고, 그렇지 않으면 십진수 형식을 사용합니다.

(4)

'G'

부동 소수점 형식. 지수가 -4보다 작거나 정밀도 보다 작지 않으면 대문자 지수형식을 사용하고, 그렇지 않으면 십진수 형식을 사용합니다.

(4)

'c'

단일 문자 (정수 또는 길이 1인 문자열을 허용합니다).

'r'

문자열 (repr()을 사용하여 파이썬 객체를 변환합니다).

(5)

's'

문자열 (str() 을 사용하여 파이썬 객체를 변환합니다).

(5)

'a'

문자열 (ascii() 를 사용하여 파이썬 객체를 변환합니다).

(5)

'%'

인자는 변환되지 않고, 결과에 '%' 문자가 표시됩니다.

노트:

대체 형식은 첫 번째 숫자 앞에 선행 8진수 지정자 ('0o')를 삽입합니다.

대체 형식은 첫 번째 숫자 앞에 선행 '0x' 또는 '0X' ('x' 나 'X' 유형 중 어느 것을 사용하느냐에 따라 달라집니다) 를 삽입합니다.

대체 형식은 그 뒤에 숫자가 나오지 않더라도 항상 소수점을 포함합니다.

정밀도는 소수점 이하 자릿수를 결정하며 기본값은 6입니다.

대체 형식은 결과에 항상 소수점을 포함하고 뒤에 오는 0은 제거되지 않습니다.

정밀도는 소수점 앞뒤의 유효 자릿수를 결정하며 기본값은 6입니다.

정밀도가 N 이라면, 출력은 N 문자로 잘립니다.

PEP 237 [https://www.python.org/dev/peps/pep-0237]을 참조하세요.

파이썬 문자열은 명시적인 길이를 가지고 있으므로, %s 변환은 문자열의 끝이 '\0' 이라고 가정하지 않습니다.

버전 3.1에서 변경: 절댓값이 1e50 을 넘는 숫자에 대한 %f 변환은 더는 %g 변환으로 대체되지 않습니다.

바이너리 시퀀스 형 — bytes, bytearray, memoryview

바이너리 데이터를 조작하기 위한 핵심 내장형은 bytes 와 bytearray 입니다. 이것들은 memoryview 에 의해 지원되는데, 다른 바이너리 객체들의 메모리에 복사 없이 접근하기 위해 버퍼 프로토콜 을 사용합니다.

array 모듈은 32-비트 정수와 IEEE754 배정도 부동 소수점 같은 기본 데이터형의 효율적인 저장을 지원합니다.

바이트열 객체

바이트열 객체는 단일 바이트들의 불변 시퀀스입니다. 많은 주요 바이너리 프로토콜이 ASCII 텍스트 인코딩을 기반으로 하므로, 바이트열 객체는 ASCII 호환 데이터로 작업 할 때만 유효한 여러 가지 메서드를 제공하며 다양한 다른 방법으로 문자열 객체와 밀접한 관련이 있습니다.

class bytes([source[, encoding[, errors]]])

첫째로, 바이트열 리터럴의 문법은 문자열 리터럴과 거의 같지만 b 접두사가 추가된다는 점이 다릅니다.:

작은따옴표: b'still allows embedded "double" quotes'

큰따옴표: b"still allows embedded 'single' quotes".

삼중 따옴표: b'''3 single quotes''', b"""3 double quotes"""

바이트열 리터럴에는 ASCII 문자만 허용됩니다 (선언된 소스 코드 인코딩과 관계없습니다). 127 보다 큰 바이너리 값은 적절한 이스케이프 시퀀스를 사용하여 바이트열 리터럴에 입력해야 합니다.

문자열 리터럴의 경우와 마찬가지로 바이트열 리터럴은 이스케이프 시퀀스 처리를 비활성화하기 위해 r 접두사를 사용할 수도 있습니다. 지원되는 이스케이프 시퀀스를 포함하여 바이트열 리터럴의 다양한 형식에 대한 자세한 내용은 문자열과 바이트열 리터럴 을 참조하십시오.

바이트열 리터럴과 그 표현은 ASCII 텍스트를 기반으로 하지만, 바이트열 객체는 실제로는 정수의 불변 시퀀스처럼 동작하고, 시퀀스의 각 값은 0 <= x < 256 이 되도록 제한됩니다 (이 제한을 위반하려고 시도하면 ValueError 를 일으킵니다). 이것은 많은 바이너리 형식이 ASCII 기반 요소를 포함하고 일부 텍스트 지향 알고리즘으로 유용하게 조작될 수 있지만, 임의의 바이너리 데이터에 일반적으로 적용될 수는 없음을 강조하기 위한 것입니다 (텍스트 처리 알고리즘을 맹목적으로 ASCII 호환이 아닌 바이너리 데이터 형식에 적용하면 대개 데이터 손상으로 이어집니다).

리터럴 형식 외에도, 바이트열 객체는 여러 가지 다른 방법으로 만들 수 있습니다.:

지정된 길이의 0으로 채워진 바이트열 객체: bytes(10)

정수의 이터러블로부터: bytes(range(20))

버퍼 프로토콜을 통해 기존 바이너리 데이터 복사: bytes(obj)

내장 bytes 도 참조하세요.

2개의 16진수는 정확히 하나의 바이트에 대응하기 때문에 16진수는 바이너리 데이터를 설명하는 데 일반적으로 사용되는 형식입니다. 따라서, 바이트열 형은 그 형식의 데이터를 읽는 추가의 클래스 메서드를 갖습니다:

classmethod fromhex(string)

이 bytes 클래스 메서드는 주어진 문자열 객체를 디코딩해서 바이트열 객체를 돌려줍니다. 문자열은 바이트 당 두 개의 16진수가 포함되어야 하며 ASCII 공백은 무시됩니다.

>>> bytes.fromhex('2Ef0 F1f2  ')
b'.\xf0\xf1\xf2'

버전 3.7에서 변경: 이제 bytes.fromhex() 는 스페이스뿐만 아니라 문자열에 있는 모든 ASCII 공백을 건너뜁니다.

바이트열 객체를 16진수 표현으로 변환하기 위한 역변환 함수가 있습니다.

hex()

인스턴스의 바이트마다 2 자릿수의 16진수로 표현한 문자열 객체를 돌려줍니다.

>>> b'\xf0\xf1\xf2'.hex()
'f0f1f2'

버전 3.5에 추가.

바이트열 객체는 정수의 시퀀스(튜플과 유사)이기 때문에, 바이트열 객체 b 에 대해서, b[0] 는 정수가 됩니다. 반면, b[0:1] 는 길이 1인 바이트열 객체가 됩니다. (이것은 인덱싱과 슬라이싱 모두 길이 1인 문자열을 생성하는 텍스트 문자열과 대조됩니다)

바이트열 객체의 표현은 리터럴 형식 (b'...') 을 사용하는데, 종종 bytes([46, 46, 46]) 보다 유용하기 때문입니다. list(b) 를 사용하면 바이트열 객체를 항상 정수 리스트로 변환할 수 있습니다.

참고

파이썬 2.x 사용자에게: 파이썬 2.x 시리즈에서는 8-비트 문자열(2.x가 내장 바이너리 데이터형에 제공하는 가장 가까운 것)과 유니코드 문자열 간의 다양한 묵시적 변환이 허용되었습니다. 이는 파이썬이 원래 8-비트 텍스트만 지원했으며 유니코드 텍스트는 나중에 추가된 사실을 반영하는 하위 호환성 해결책입니다. 파이썬 3.x 에서, 이러한 묵시적 변환은 사라졌습니다 - 8-비트 바이너리 데이터와 유니코드 텍스트 간의 변환은 반드시 명시적이어야 하며 바이트열과 문자열 객체는 항상 다르다고 비교됩니다.

바이트 배열 객체

bytearray 객체는 bytes 객체의 가변형입니다.

class bytearray([source[, encoding[, errors]]])

바이트 배열 객체에 대한 전용 리터럴 문법은 없으며 항상 생성자를 호출하여 만듭니다:

빈 인스턴스 만들기: bytearray()

주어진 길이의 0으로 채워진 인스턴스 만들기: bytearray(10)

정수의 이터러블로부터: bytearray(range(20))

버퍼 프로토콜을 통해 기존 바이너리 데이터 복사: bytearray(b'Hi!')

바이트 배열 객체는 가변이기 때문에, 바이트열 과 바이트 배열 연산 에 설명되어있는 공통 바이트열과 바이트 배열 연산에 더해, 가변 시퀀스 연산도 지원합니다.

내장 bytearray 도 참조하세요.

2개의 16진수는 정확히 하나의 바이트에 대응하기 때문에 16진수는 바이너리 데이터를 설명하는 데 일반적으로 사용되는 형식입니다. 따라서, 바이트 배열형은 그 형식의 데이터를 읽는 추가의 클래스 메서드를 갖습니다:

classmethod fromhex(string)

이 bytearray 클래스 메서드는 주어진 문자열 객체를 디코딩해서 바이트 배열 객체를 돌려줍니다. 문자열은 바이트 당 두 개의 16진수가 포함되어야 하며 ASCII 공백은 무시됩니다.

>>> bytearray.fromhex('2Ef0 F1f2  ')
bytearray(b'.\xf0\xf1\xf2')

버전 3.7에서 변경: 이제 bytearray.fromhex() 는 스페이스뿐만 아니라 문자열에 있는 모든 ASCII 공백을 건너뜁니다.

바이트 배열 객체를 16진수 표현으로 변환하기 위한 역변환 함수가 있습니다.

hex()

인스턴스의 바이트마다 2 자릿수의 16진수로 표현한 문자열 객체를 돌려줍니다.

>>> bytearray(b'\xf0\xf1\xf2').hex()
'f0f1f2'

버전 3.5에 추가.

바이트 배열 객체는 정수의 시퀀스(리스트와 유사)이기 때문에, 바이트 배열 객체 b 에 대해서, b[0] 는 정수가 됩니다. 반면, b[0:1] 는 길이 1인 바이트 배열 객체가 됩니다. (이것은 인덱싱과 슬라이싱 모두 길이 1인 문자열을 생성하는 텍스트 문자열과 대조됩니다)

바이트 배열 객체의 표현은 바이트열 리터럴 형식 (bytearray(b'...')) 을 사용하는데, 종종 bytearray([46, 46, 46]) 보다 유용하기 때문입니다. list(b) 를 사용하면 바이트 배열 객체를 항상 정수 리스트로 변환할 수 있습니다.

바이트열 과 바이트 배열 연산

바이트열와 바이트 배열 객체는 공통 시퀀스 연산을 지원합니다. 이것들은 같은 형의 피연산자뿐만 아니라 모든 bytes-like object와 상호 운용됩니다. 이러한 유연성으로 인해, 오류 없이 작업을 자유롭게 혼합할 수 있습니다. 그러나, 결과의 반환형은 피연산자의 순서에 따라 달라질 수 있습니다.

참고

바이트열 및 바이트 배열 객체의 메서드는 인자로 문자열을 받아들이지 않습니다, 문자열의 메서드가 바이트열을 인자로 허용하지 않는 것과 마찬가지입니다. 예를 들어, 다음과 같이 작성해야 합니다:

a = "abc"
b = a.replace("a", "f")

그리고:

a = b"abc"
b = a.replace(b"a", b"f")

일부 바이트열 및 바이트 배열 연산은 ASCII 호환 바이너리 형식을 가정하므로, 임의의 바이너리 데이터로 작업 할 때는 피해야 합니다. 이러한 제한 사항은 아래에서 다룹니다.

참고

이러한 ASCII 기반 연산을 사용하여 ASCII 기반 형식으로 저장되지 않은 바이너리 데이터를 조작하면 데이터가 손상될 수 있습니다.

바이트열 및 바이트 배열 객체에 대한 다음 메서드는 임의의 바이너리 데이터와 함께 사용할 수 있습니다.

bytes.count(sub[, start[, end]])

bytearray.count(sub[, start[, end]])

범위 [start, end] 에서 서브 시퀀스 sub 가 중첩되지 않고 등장하는 횟수를 돌려줍니다. 선택적 인자 start 와 end 는 슬라이스 표기법으로 해석됩니다.

검색할 서브 시퀀스는 임의의 bytes-like object 또는 0에서 255 사이의 정수일 수 있습니다.

버전 3.3에서 변경: 서브 시퀀스로 0에서 255 사이의 정수도 허용합니다.

bytes.decode(encoding="utf-8", errors="strict")

bytearray.decode(encoding="utf-8", errors="strict")

주어진 바이트열로부터 디코딩된 문자열을 돌려줍니다. 기본 인코딩은 'utf-8' 입니다. errors 는 다른 오류 처리 방식을 설정하기 위해 제공될 수 있습니다. errors 의 기본값은 'strict' 인데, 인코딩 오류가 있으면 UnicodeError 를 일으키라는 뜻입니다. 다른 가능한 값은 'ignore', 'replace' 와 codecs.register_error() 를 통해 등록된 다른 이름들입니다. Error Handlers를 보세요. 가능한 인코딩의 목록을 보려면 Standard Encodings 섹션을 참조하십시오.

참고

encoding 인자를 str 에 전달하면 임시 바이트열이나 바이트 배열 객체를 만들 필요 없이 임의의 bytes-like object 를 직접 디코딩할 수 있습니다.

버전 3.1에서 변경: 키워드 인자 지원이 추가되었습니다.

bytes.endswith(suffix[, start[, end]])

bytearray.endswith(suffix[, start[, end]])

바이너리 데이터가 지정된 suffix 로 끝나면 True 를 돌려주고, 그렇지 않으면 False 를 돌려줍니다. suffix 는 찾고자 하는 접미사들의 튜플이 될 수도 있습니다. 선택적 start 가 제공되면 그 위치에서 검사를 시작합니다. 선택적 end 를 사용하면 해당 위치에서 비교를 중단합니다.

검색할 접미사(들)는 임의의 bytes-like object 일 수 있습니다.

bytes.find(sub[, start[, end]])

bytearray.find(sub[, start[, end]])

서브 시퀀스 sub 가 슬라이스 s[start:end] 내에 등장하는 가장 작은 데이터의 인덱스를 돌려줍니다. 선택적 인자 start 와 end 는 슬라이스 표기법으로 해석됩니다. sub 가 없으면 -1 을 돌려줍니다.

검색할 서브 시퀀스는 임의의 bytes-like object 또는 0에서 255 사이의 정수일 수 있습니다.

참고

find() 메서드는 sub 의 위치를 알아야 할 경우에만 사용해야 합니다. sub 가 부분 문자열인지 여부를 확인하려면 in 연산자를 사용하십시오:

>>> b'Py' in b'Python'
True

버전 3.3에서 변경: 서브 시퀀스로 0에서 255 사이의 정수도 허용합니다.

bytes.index(sub[, start[, end]])

bytearray.index(sub[, start[, end]])

find() 과 비슷하지만, 서브 시퀀스를 찾을 수 없는 경우 ValueError 를 일으킵니다.

검색할 서브 시퀀스는 임의의 bytes-like object 또는 0에서 255 사이의 정수일 수 있습니다.

버전 3.3에서 변경: 서브 시퀀스로 0에서 255 사이의 정수도 허용합니다.

bytes.join(iterable)

bytearray.join(iterable)

iterable 의 바이너리 데이터 시퀀스들을 이어 붙이기 한 바이트열 또는 바이트 배열 객체를 돌려줍니다. iterable 에 str 객체나 기타 bytes-like object 가 아닌 값이 있으면 TypeError 를 일으킵니다. 요소들 사이의 구분자는 이 메서드를 제공하는 바이트열 이나 바이트 배열 객체입니다.

static bytes.maketrans(from, to)

static bytearray.maketrans(from, to)

이 정적 메서드는 bytes.translate() 에 사용할 수 있는 변환표를 돌려주는데, from 에 있는 문자를 to 의 같은 위치에 있는 문자로 매핑합니다; from 과 to 는 모두 bytes-like object 여야 하고 길이가 같아야 합니다.

버전 3.1에 추가.

bytes.partition(sep)

bytearray.partition(sep)

sep 가 처음 나타나는 위치에서 시퀀스를 나누고, 구분자 앞에 있는 부분, 구분자 자체, 구분자 뒤에 오는 부분으로 구성된 3-튜플을 돌려줍니다. 구분자가 발견되지 않으면, 원래 시퀀스의 복사본과 그 뒤를 따르는 두 개의 빈 바이트열 또는 바이트 배열 객체로 구성된 3-튜플을 돌려줍니다.

검색할 구분자는 임의의 bytes-like object 일 수 있습니다.

bytes.replace(old, new[, count])

bytearray.replace(old, new[, count])

모든 서브 시퀀스 old 가 new 로 치환된 시퀀스의 복사본을 돌려줍니다. 선택적 인자 count 가 주어지면, 앞의 count 개만 치환됩니다.

검색할 서브 시퀀스와 그 대체물은 임의의 bytes-like object 일 수 있습니다.

참고

이 메서드의 바이트 배열 버전은 제자리에서 동작하지 않습니다 - 변경되지 않는 경우조차 항상 새 객체를 만듭니다.

bytes.rfind(sub[, start[, end]])

bytearray.rfind(sub[, start[, end]])

서브 시퀀스 sub 가 s[start:end] 내에 등장하는 가장 큰 시퀀스의 인덱스를 돌려줍니다. 선택적 인자 start 와 end 는 슬라이스 표기법으로 해석됩니다. 실패하면 -1 을 돌려줍니다.

검색할 서브 시퀀스는 임의의 bytes-like object 또는 0에서 255 사이의 정수일 수 있습니다.

버전 3.3에서 변경: 서브 시퀀스로 0에서 255 사이의 정수도 허용합니다.

bytes.rindex(sub[, start[, end]])

bytearray.rindex(sub[, start[, end]])

rfind() 와 비슷하지만, 서브 시퀀스 sub 를 찾을 수 없는 경우 ValueError 를 일으킵니다.

검색할 서브 시퀀스는 임의의 bytes-like object 또는 0에서 255 사이의 정수일 수 있습니다.

버전 3.3에서 변경: 서브 시퀀스로 0에서 255 사이의 정수도 허용합니다.

bytes.rpartition(sep)

bytearray.rpartition(sep)

sep 가 마지막으로 나타나는 위치에서 시퀀스를 나누고, 구분자 앞에 있는 부분, 구분자 자체, 구분자 뒤에 오는 부분으로 구성된 3-튜플을 돌려줍니다. 구분자가 발견되지 않으면, 두 개의 빈 바이트열 또는 바이트 배열 객체와 그 뒤를 따르는 원래 시퀀스의 복사본으로 구성된 3-튜플을 돌려줍니다.

검색할 구분자는 임의의 bytes-like object 일 수 있습니다.

bytes.startswith(prefix[, start[, end]])

bytearray.startswith(prefix[, start[, end]])

바이너리 데이터가 지정된 prefix 로 시작하면 True 를 돌려주고, 그렇지 않으면 False 를 돌려줍니다. prefix 는 찾고자 하는 접두사들의 튜플이 될 수도 있습니다. 선택적 start 가 제공되면 그 위치에서 검사를 시작합니다. 선택적 end 를 사용하면 해당 위치에서 비교를 중단합니다.

검색할 접두사(들)는 임의의 bytes-like object 일 수 있습니다.

bytes.translate(table, delete=b'')

bytearray.translate(table, delete=b'')

생략 가능한 인자 delete 의 모든 바이트를 제거하고, 나머지 바이트들을 주어진 변환표로 매핑한 바이트열이나 바이트 배열 객체의 복사본을 돌려줍니다. table은 길이 256인 바이트열 객체이어야 합니다.

bytes.maketrans() 메서드를 사용하여 변환표를 만들 수 있습니다.

문자를 지우기만 하는 변환에는 table 인자를 None 으로 설정하십시오:

>>> b'read this short text'.translate(None, b'aeiou')
b'rd ths shrt txt'

버전 3.6에서 변경: 이제 delete 는 키워드 인자로 지원됩니다.

바이트열 및 바이트 배열 객체에 대한 다음 메서드는 ASCII 호환 바이너리 형식의 사용을 가정하는 기본 동작을 갖지만, 적절한 인자를 전달하여 임의의 바이너리 데이터와 함께 사용할 수 있습니다. 이 섹션의 바이트 배열 메서드는 모두 제자리에서 작동하지 않고 대신 새로운 객체를 생성함에 주의하십시오.

bytes.center(width[, fillbyte])

bytearray.center(width[, fillbyte])

길이 width 인 시퀀스의 가운데에 정렬한 객체의 복사본을 돌려줍니다. 지정된 fillbyte (기본값은 ASCII 스페이스)를 사용하여 채웁니다. bytes 객체의 경우, width 가 len(s) 보다 작거나 같은 경우 원래 시퀀스가 반환됩니다.

참고

이 메서드의 바이트 배열 버전은 제자리에서 동작하지 않습니다 - 변경되지 않는 경우조차 항상 새 객체를 만듭니다.

bytes.ljust(width[, fillbyte])

bytearray.ljust(width[, fillbyte])

왼쪽으로 정렬된 객체의 복사본을 길이 width 인 시퀀스로 돌려줍니다. 지정된 fillbyte (기본값은 ASCII 스페이스)을 사용하여 채웁니다. bytes 객체의 경우, width 가 len(s) 보다 작거나 같은 경우 원래 시퀀스가 반환됩니다.

참고

이 메서드의 바이트 배열 버전은 제자리에서 동작하지 않습니다 - 변경되지 않는 경우조차 항상 새 객체를 만듭니다.

bytes.lstrip([chars])

bytearray.lstrip([chars])

선행 바이트가 제거된 시퀀스의 복사본을 돌려줍니다. chars 인자는 제거할 바이트 집합을 지정하는 바이너리 시퀀스입니다 - 이름은 이 메서드가 보통 ASCII 문자와 사용된다는 사실을 반영합니다. 생략되거나 None 이라면, chars 인자의 기본값은 ASCII 공백을 제거하도록 합니다. chars 인자는 접두사가 아닙니다; 모든 값 조합이 제거됩니다:

>>> b'   spacious   '.lstrip()
b'spacious   '
>>> b'www.example.com'.lstrip(b'cmowz.')
b'example.com'

제거할 바이트 값의 바이너리 시퀀스는 임의의 bytes-like object 일 수 있습니다.

참고

이 메서드의 바이트 배열 버전은 제자리에서 동작하지 않습니다 - 변경되지 않는 경우조차 항상 새 객체를 만듭니다.

bytes.rjust(width[, fillbyte])

bytearray.rjust(width[, fillbyte])

오른쪽으로 정렬된 객체의 복사본을 길이 width 인 시퀀스로 돌려줍니다. 지정된 fillbyte (기본값은 ASCII 스페이스)를 사용하여 채웁니다. bytes 객체의 경우, width 가 len(s) 보다 작거나 같은 경우 원래 시퀀스가 반환됩니다.

참고

이 메서드의 바이트 배열 버전은 제자리에서 동작하지 않습니다 - 변경되지 않는 경우조차 항상 새 객체를 만듭니다.

bytes.rsplit(sep=None, maxsplit=-1)

bytearray.rsplit(sep=None, maxsplit=-1)

sep 을 구분자 시퀀스로 사용하여 바이너리 시퀀스를 같은 형의 서브 시퀀스로 나눕니다. maxsplit 이 주어지면 가장 오른쪽에서 최대 maxsplit 번의 분할이 수행됩니다. sep 이 지정되지 않거나 None 이면, ASCII 공백 문자만으로 이루어진 모든 서브 시퀀스는 구분자입니다. 오른쪽에서 분리하는 것을 제외하면, rsplit()는 아래에서 자세히 설명될 split()처럼 동작합니다.

bytes.rstrip([chars])

bytearray.rstrip([chars])

지정된 후행 바이트가 제거된 시퀀스의 복사본을 돌려줍니다. chars 인자는 제거할 바이트 집합을 지정하는 바이너리 시퀀스입니다 - 이름은 이 메서드가 보통 ASCII 문자와 사용된다는 사실을 반영합니다. 생략되거나 None 이라면, chars 인자의 기본값은 ASCII 공백을 제거하도록 합니다. chars 인자는 접미사가 아닙니다; 모든 값 조합이 제거됩니다:

>>> b'   spacious   '.rstrip()
b'   spacious'
>>> b'mississippi'.rstrip(b'ipz')
b'mississ'

제거할 바이트 값의 바이너리 시퀀스는 임의의 bytes-like object 일 수 있습니다.

참고

이 메서드의 바이트 배열 버전은 제자리에서 동작하지 않습니다 - 변경되지 않는 경우조차 항상 새 객체를 만듭니다.

bytes.split(sep=None, maxsplit=-1)

bytearray.split(sep=None, maxsplit=-1)

sep 를 구분자 시퀀스로 사용하여 바이너리 시퀀스를 같은 형의 서브 시퀀스로 나눕니다. maxsplit 이 지정되고 음수가 아닌 경우, 최대 maxsplit 분할이 수행됩니다 (따라서, 리스트는 최대 maxsplit+1 개의 요소를 가지게 됩니다). maxsplit 이 지정되지 않았거나 -1 이라면 분할 수에 제한이 없습니다 (가능한 모든 분할이 만들어집니다).

sep 이 주어지면, 연속된 구분자는 묶이지 않고 빈 서브 시퀀스를 구분하는 것으로 간주합니다 (예를 들어, b'1,,2'.split(b',') 는 [b'1', b'', b'2'] 를 돌려줍니다). sep 인자는 멀티바이트 시퀀스로 구성될 수 있습니다 (예를 들어, b'1<>2<>3'.split(b'<>') 는 [b'1', b'2', b'3'] 를 돌려줍니다). 지정된 구분자로 빈 시퀀스를 나누면, 나누는 객체의 형에 따라 [b''] 나 [bytearray(b'')] 를 돌려줍니다. sep 인자는 임의의 bytes-like object 일 수 있습니다.

예를 들면:

>>> b'1,2,3'.split(b',')
[b'1', b'2', b'3']
>>> b'1,2,3'.split(b',', maxsplit=1)
[b'1', b'2,3']
>>> b'1,2,,3,'.split(b',')
[b'1', b'2', b'', b'3', b'']

sep 이 지정되지 않거나 None 이면, 다른 분할 알고리즘이 적용됩니다: 연속된 ASCII 공백 문자는 단일한 구분자로 간주하고, 시퀀스가 선행이나 후행 공백을 포함해도 결과는 시작과 끝에 빈 시퀀스를 포함하지 않습니다. 결과적으로, 빈 시퀀스나 ASCII 공백만으로 구성된 시퀀스를 None 구분자로 나누면 [] 를 돌려줍니다.

예를 들면:

>>> b'1 2 3'.split()
[b'1', b'2', b'3']
>>> b'1 2 3'.split(maxsplit=1)
[b'1', b'2 3']
>>> b'   1   2   3   '.split()
[b'1', b'2', b'3']

bytes.strip([chars])

bytearray.strip([chars])

선행과 후행 바이트가 제거된 시퀀스의 복사본을 돌려줍니다. chars 인자는 제거할 바이트 집합을 지정하는 바이너리 시퀀스입니다 - 이름은 이 메서드가 보통 ASCII 문자와 사용된다는 사실을 반영합니다. 생략되거나 None 이라면, chars 인자의 기본값은 ASCII 공백을 제거하도록 합니다. chars 인자는 접두사나 접미사가 아닙니다; 모든 값 조합이 제거됩니다:

>>> b'   spacious   '.strip()
b'spacious'
>>> b'www.example.com'.strip(b'cmowz.')
b'example'

제거할 바이트 값의 바이너리 시퀀스는 임의의 bytes-like object 일 수 있습니다.

참고

이 메서드의 바이트 배열 버전은 제자리에서 동작하지 않습니다 - 변경되지 않는 경우조차 항상 새 객체를 만듭니다.

바이트열 및 바이트 배열 객체에 대한 다음 메서드는 ASCII 호환 바이너리 형식의 사용을 가정하며 임의의 바이너리 데이터에 적용하면 안 됩니다. 이 섹션의 바이트 배열 메서드는 모두 제자리에서 작동하지 않고 대신 새로운 객체를 생성합니다.

bytes.capitalize()

bytearray.capitalize()

각 바이트가 ASCII 문자로 해석되고 첫 번째 바이트는 대문자로, 나머지는 소문자로 만든 시퀀스의 복사본을 돌려줍니다. ASCII 바이트가 아닌 값들은 변경되지 않고 전달됩니다.

참고

이 메서드의 바이트 배열 버전은 제자리에서 동작하지 않습니다 - 변경되지 않는 경우조차 항상 새 객체를 만듭니다.

bytes.expandtabs(tabsize=8)

bytearray.expandtabs(tabsize=8)

모든 ASCII 탭 문자들을 현재의 열과 주어진 탭 크기에 따라 하나나 그 이상의 ASCII 스페이스로 치환한 시퀀스의 복사본을 돌려줍니다. 탭 위치는 tabsize 바이트마다 발생합니다 (기본값은 8이고, 열 0, 8, 16 등에 탭 위치를 지정합니다). 시퀀스를 확장하기 위해 현재 열이 0으로 설정되고 시퀀스를 바이트 단위로 검사합니다. 바이트가 ASCII 탭 문자 (b'\t') 이면, 현재 열이 다음 탭 위치와 같아질 때까지 하나 이상의 스페이스 문자가 삽입됩니다. (탭 문자 자체는 복사되지 않습니다.) 현재 바이트가 ASCII 개행 문자 (b'\n') 또는 캐리지 리턴 (b'\r') 이면 복사되고 현재 열은 0으로 재설정됩니다. 다른 바이트는 변경되지 않고 복사되고 현재 열은 인쇄할 때 바이트가 어떻게 표시되는지에 관계없이 1씩 증가합니다.

>>> b'01\t012\t0123\t01234'.expandtabs()
b'01      012     0123    01234'
>>> b'01\t012\t0123\t01234'.expandtabs(4)
b'01  012 0123    01234'

참고

이 메서드의 바이트 배열 버전은 제자리에서 동작하지 않습니다 - 변경되지 않는 경우조차 항상 새 객체를 만듭니다.

bytes.isalnum()

bytearray.isalnum()

Return True if all bytes in the sequence are alphabetical ASCII characters or ASCII decimal digits and the sequence is not empty, False otherwise. Alphabetic ASCII characters are those byte values in the sequence b'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'. ASCII decimal digits are those byte values in the sequence b'0123456789'.

예를 들면:

>>> b'ABCabc1'.isalnum()
True
>>> b'ABC abc1'.isalnum()
False

bytes.isalpha()

bytearray.isalpha()

Return True if all bytes in the sequence are alphabetic ASCII characters and the sequence is not empty, False otherwise. Alphabetic ASCII characters are those byte values in the sequence b'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.

예를 들면:

>>> b'ABCabc'.isalpha()
True
>>> b'ABCabc1'.isalpha()
False

bytes.isascii()

bytearray.isascii()

Return True if the sequence is empty or all bytes in the sequence are ASCII, False otherwise. ASCII bytes are in the range 0-0x7F.

버전 3.7에 추가.

bytes.isdigit()

bytearray.isdigit()

Return True if all bytes in the sequence are ASCII decimal digits and the sequence is not empty, False otherwise. ASCII decimal digits are those byte values in the sequence b'0123456789'.

예를 들면:

>>> b'1234'.isdigit()
True
>>> b'1.23'.isdigit()
False

bytes.islower()

bytearray.islower()

Return True if there is at least one lowercase ASCII character in the sequence and no uppercase ASCII characters, False otherwise.

예를 들면:

>>> b'hello world'.islower()
True
>>> b'Hello world'.islower()
False

ASCII 소문자는 시퀀스 b'abcdefghijklmnopqrstuvwxyz' 에 있는 바이트 값입니다. ASCII 대문자는, 시퀀스 b'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 에 있는 바이트 값입니다.

bytes.isspace()

bytearray.isspace()

Return True if all bytes in the sequence are ASCII whitespace and the sequence is not empty, False otherwise. ASCII whitespace characters are those byte values in the sequence b' \t\n\r\x0b\f' (space, tab, newline, carriage return, vertical tab, form feed).

bytes.istitle()

bytearray.istitle()

Return True if the sequence is ASCII titlecase and the sequence is not empty, False otherwise. See bytes.title() for more details on the definition of “titlecase”.

예를 들면:

>>> b'Hello World'.istitle()
True
>>> b'Hello world'.istitle()
False

bytes.isupper()

bytearray.isupper()

Return True if there is at least one uppercase alphabetic ASCII character in the sequence and no lowercase ASCII characters, False otherwise.

예를 들면:

>>> b'HELLO WORLD'.isupper()
True
>>> b'Hello world'.isupper()
False

ASCII 소문자는 시퀀스 b'abcdefghijklmnopqrstuvwxyz' 에 있는 바이트 값입니다. ASCII 대문자는, 시퀀스 b'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 에 있는 바이트 값입니다.

bytes.lower()

bytearray.lower()

모든 ASCII 대문자를 해당 소문자로 변환한 시퀀스의 복사본을 돌려줍니다.

예를 들면:

>>> b'Hello World'.lower()
b'hello world'

ASCII 소문자는 시퀀스 b'abcdefghijklmnopqrstuvwxyz' 에 있는 바이트 값입니다. ASCII 대문자는, 시퀀스 b'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 에 있는 바이트 값입니다.

참고

이 메서드의 바이트 배열 버전은 제자리에서 동작하지 않습니다 - 변경되지 않는 경우조차 항상 새 객체를 만듭니다.

bytes.splitlines(keepends=False)

bytearray.splitlines(keepends=False)

ASCII 줄 경계에서 나눈 바이너리 시퀀스의 줄 리스트를 돌려줍니다. 이 메서드는 줄을 나누는데 universal newlines 접근법을 사용합니다. keepends 가 참으로 주어지지 않는 한 결과 리스트에 줄 바꿈은 포함되지 않습니다.

예를 들면:

>>> b'ab c\n\nde fg\rkl\r\n'.splitlines()
[b'ab c', b'', b'de fg', b'kl']
>>> b'ab c\n\nde fg\rkl\r\n'.splitlines(keepends=True)
[b'ab c\n', b'\n', b'de fg\r', b'kl\r\n']

구분자 시퀀스 sep 이 주어졌을 때 split() 와 달리, 이 메서드는 빈 시퀀스에 대해서 빈 리스트를 돌려주고, 마지막 줄 바꿈은 새 줄을 만들지 않습니다:

>>> b"".split(b'\n'), b"Two lines\n".split(b'\n')
([b''], [b'Two lines', b''])
>>> b"".splitlines(), b"One line\n".splitlines()
([], [b'One line'])

bytes.swapcase()

bytearray.swapcase()

모든 ASCII 소문자를 해당 대문자로, 그 반대도 마찬가지로 변환한 시퀀스의 복사본을 돌려줍니다.

예를 들면:

>>> b'Hello World'.swapcase()
b'hELLO wORLD'

ASCII 소문자는 시퀀스 b'abcdefghijklmnopqrstuvwxyz' 에 있는 바이트 값입니다. ASCII 대문자는, 시퀀스 b'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 에 있는 바이트 값입니다.

str.swapcase() 와는 달리 바이너리 버전의 경우 항상 bin.swapcase().swapcase() == bin 이 성립합니다. 임의의 유니코드 포인트에서 일반적으로 성립하지는 않지만, ASCII에서 케이스 변환은 대칭적입니다.

참고

이 메서드의 바이트 배열 버전은 제자리에서 동작하지 않습니다 - 변경되지 않는 경우조차 항상 새 객체를 만듭니다.

bytes.title()

bytearray.title()

단어가 ASCII 대문자로 시작하고 나머지 문자들은 소문자인 제목 케이스 버전의 바이너리 시퀀스를 돌려줍니다. 케이스 없는 바이트 값은 수정되지 않은 상태로 남습니다.

예를 들면:

>>> b'Hello world'.title()
b'Hello World'

ASCII 소문자는 시퀀스 b'abcdefghijklmnopqrstuvwxyz' 에 있는 바이트 값입니다. ASCII 대문자는 시퀀스 b'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 에 있는 바이트 값입니다. 다른 모든 바이트 값은 케이스가 없습니다.

이 알고리즘은 단어를 글자들의 연속으로 보는 간단한 언어 독립적 정의를 사용합니다. 이 정의는 여러 상황에서 작동하지만, 축약과 소유의 아포스트로피가 단어 경계를 형성한다는 것을 의미하고, 이는 원하는 결과가 아닐 수도 있습니다:

>>> b"they're bill's friends from the UK".title()
b"They'Re Bill'S Friends From The Uk"

정규식을 사용하여 아포스트로피에 대한 해결 방법을 구성할 수 있습니다:

>>> import re
>>> def titlecase(s):
...     return re.sub(rb"[A-Za-z]+('[A-Za-z]+)?",
...                   lambda mo: mo.group(0)[0:1].upper() +
...                              mo.group(0)[1:].lower(),
...                   s)
...
>>> titlecase(b"they're bill's friends.")
b"They're Bill's Friends."

참고

이 메서드의 바이트 배열 버전은 제자리에서 동작하지 않습니다 - 변경되지 않는 경우조차 항상 새 객체를 만듭니다.

bytes.upper()

bytearray.upper()

모든 ASCII 소문자를 해당 대문자로 변환한 시퀀스의 복사본을 돌려줍니다.

예를 들면:

>>> b'Hello World'.upper()
b'HELLO WORLD'

ASCII 소문자는 시퀀스 b'abcdefghijklmnopqrstuvwxyz' 에 있는 바이트 값입니다. ASCII 대문자는, 시퀀스 b'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 에 있는 바이트 값입니다.

참고

이 메서드의 바이트 배열 버전은 제자리에서 동작하지 않습니다 - 변경되지 않는 경우조차 항상 새 객체를 만듭니다.

bytes.zfill(width)

bytearray.zfill(width)

길이가 width 인 시퀀스를 만들기 위해 ASCII b'0' 문자를 왼쪽에 채운 시퀀스의 복사본을 돌려줍니다. 선행 부호 접두어(b'+'/b'-')는 부호 문자의 앞이 아니라 뒤 에 채우는 것으로 처리됩니다. bytes 객체의 경우, width 가 len(s) 보다 작거나 같은 경우 원래 시퀀스를 돌려줍니다.

예를 들면:

>>> b"42".zfill(5)
b'00042'
>>> b"-42".zfill(5)
b'-0042'

참고

이 메서드의 바이트 배열 버전은 제자리에서 동작하지 않습니다 - 변경되지 않는 경우조차 항상 새 객체를 만듭니다.

printf 스타일 바이너리 포매팅

참고

여기에 설명된 포맷 연산은 여러 가지 일반적인 오류를 (예를 들어 튜플과 딕셔너리를 올바르게 표시하지 못하는 것) 유발하는 다양한 문제점들이 있습니다. 인쇄될 값이 튜플 또는 딕셔너리일 경우 튜플로 감싸야 합니다.

바이너리 시퀀스 객체는 한가지 고유한 내장 연산을 갖고 있습니다: % 연산자 (모듈로). 이것은 바이너리 포매팅 또는 치환 연산자라고도 합니다. format % values 가 주어질 때 (format 은 바이너리 시퀀스입니다), format 내부의 % 변환 명세는 0개 이상의 values 의 요소로 대체됩니다. 이 효과는 C 언어에서 sprintf()를 사용하는 것과 비슷합니다.

format 이 하나의 인자를 요구하면, values 는 하나의 비 튜플 객체 일 수 있습니다. 5 그렇지 않으면, values 는 format 바이너리 시퀀스 객체가 지정하는 항목의 수와 같은 튜플이거나 단일 매핑 객체 (예를 들어, 딕셔너리) 여야 합니다.

변환 명세는 두 개 이상의 문자를 포함하며 다음과 같은 구성 요소들을 포함하는데, 반드시 이 순서대로 나와야 합니다:

'%' 문자: 명세의 시작을 나타냅니다.

매핑 키 (선택 사항): 괄호로 둘러싸인 문자들의 시퀀스로 구성됩니다 (예를 들어, (somename)).

변환 플래그 (선택 사항): 일부 변환 유형의 결과에 영향을 줍니다.

최소 필드 폭 (선택 사항): '*' (애스터리스크) 로 지정하면, 실제 폭은 values 튜플의 다음 요소에서 읽히고, 변환할 객체는 최소 필드 폭과 선택적 정밀도 뒤에 옵니다.

정밀도 (선택 사항): '.' (점) 다음에 정밀도가 옵니다. '*' (애스터리스크) 로 지정하면, 실제 정밀도는 values 튜플의 다음 요소에서 읽히고, 변환할 값은 정밀도 뒤에 옵니다.

길이 수정자 (선택 사항).

변환 유형.

오른쪽 인자가 딕셔너리 (또는 다른 매핑 형) 인 경우, 바이너리 시퀀스 객체에 있는 변환 명세는 반드시 '%' 문자 바로 뒤에 그 딕셔너리의 매핑 키를 괄호로 둘러싼 형태로 포함해야 합니다. 매핑 키는 포맷할 값을 매핑으로 부터 선택합니다. 예를 들어:

>>> print(b'%(language)s has %(number)03d quote types.' %
...       {b'language': b"Python", b"number": 2})
b'Python has 002 quote types.'

이 경우 * 지정자를 사용할 수 없습니다 (순차적인 매개변수 목록이 필요하기 때문입니다).

변환 플래그 문자는 다음과 같습니다:

플래그

뜻

'#'

값 변환에 “대체 형식” (아래에 정의되어있습니다) 을 사용합니다.

'0'

변환은 숫자 값의 경우 0으로 채웁니다.

'-'

변환된 값은 왼쪽으로 정렬됩니다 (둘 다 주어지면 '0' 변환보다 우선 합니다).

' '

(스페이스) 부호 있는 변환 때문에 만들어진 양수 앞에 빈칸을 남겨둡니다 (음수면 빈 문자열입니다).

'+'

부호 문자 ('+' or '-') 가 변환 앞에 놓입니다 (' ' 플래그에 우선합니다).

길이 수정자 (h, l, L) 를 제공할 수는 있지만, 파이썬에서 필요하지 않기 때문에 무시됩니다 – 예를 들어 %ld 는 %d 와 같습니다.

변환 유형은 다음과 같습니다:

변환

뜻

노트

'd'

부호 있는 정수 십진 표기.

'i'

부호 있는 정수 십진 표기.

'o'

부호 있는 8진수 값.

(1)

'u'

쓸데없는 유형 – 'd' 와 같습니다.

(8)

'x'

부호 있는 16진수 (소문자).

(2)

'X'

부호 있는 16진수 (대문자).

(2)

'e'

부동 소수점 지수 형식 (소문자).

(3)

'E'

부동 소수점 지수 형식 (대문자).

(3)

'f'

부동 소수점 십진수 형식.

(3)

'F'

부동 소수점 십진수 형식.

(3)

'g'

부동 소수점 형식. 지수가 -4보다 작거나 정밀도 보다 작지 않으면 소문자 지수형식을 사용하고, 그렇지 않으면 십진수 형식을 사용합니다.

(4)

'G'

부동 소수점 형식. 지수가 -4보다 작거나 정밀도 보다 작지 않으면 대문자 지수형식을 사용하고, 그렇지 않으면 십진수 형식을 사용합니다.

(4)

'c'

단일 바이트 (정수 또는 길이 1인 바이너리 시퀀스를 허용합니다).

`b`

바이너리 시퀀스 ( 버퍼 프로토콜 을 따르거나 __bytes__() 가 있는 모든 객체).

(5)

's'

's' 는 'b' 의 별칭이고 파이썬 2/3에서만 사용되어야 합니다.

(6)

'a'

바이트열 (repr(obj).encode('ascii','backslashreplace) 를 사용하여 모든 파이썬 객체를 변환합니다).

(5)

'r'

'r' 는 'a' 의 별칭이고 파이썬 2/3에서만 사용되어야 합니다.

(7)

'%'

인자는 변환되지 않고, 결과에 '%' 문자가 표시됩니다.

노트:

대체 형식은 첫 번째 숫자 앞에 선행 8진수 지정자 ('0o')를 삽입합니다.

대체 형식은 첫 번째 숫자 앞에 선행 '0x' 또는 '0X' ('x' 나 'X' 유형 중 어느 것을 사용하느냐에 따라 달라집니다) 를 삽입합니다.

대체 형식은 그 뒤에 숫자가 나오지 않더라도 항상 소수점을 포함합니다.

정밀도는 소수점 이하 자릿수를 결정하며 기본값은 6입니다.

대체 형식은 결과에 항상 소수점을 포함하고 뒤에 오는 0은 제거되지 않습니다.

정밀도는 소수점 앞뒤의 유효 자릿수를 결정하며 기본값은 6입니다.

정밀도가 N 이라면, 출력은 N 문자로 잘립니다.

b'%s' 는 폐지되었습니다. 하지만 3.x 시리즈에서는 제거되지 않습니다.

b'%r' 는 폐지되었습니다. 하지만 3.x 시리즈에서는 제거되지 않습니다.

PEP 237 [https://www.python.org/dev/peps/pep-0237]을 참조하세요.

참고

이 메서드의 바이트 배열 버전은 제자리에서 동작하지 않습니다 - 변경되지 않는 경우조차 항상 새 객체를 만듭니다.

더 보기

PEP 461 [https://www.python.org/dev/peps/pep-0461] - bytes와 bytearray에 % 포매팅 추가

버전 3.5에 추가.

메모리 뷰

memoryview 객체는 파이썬 코드가 버퍼 프로토콜 을 지원하는 객체의 내부 데이터에 복사 없이 접근할 수 있게 합니다.

class memoryview(obj)

obj 를 참조하는 memoryview 를 만듭니다. obj 는 버퍼 프로토콜을 지원해야 합니다. 버퍼 프로토콜을 지원하는 내장 객체에는 bytes 와 bytearray 가 있습니다.

A memoryview 는 요소 라는 개념을 갖는데, 원래 객체 obj 에 의해 처리되는 원자 적 메모리 단위입니다. bytes 와 bytearray 와 같은 많은 간단한 형의 경우 요소는 하나의 바이트이지만, array.array 와 같은 다른 형들은 더 큰 요소를 가질 수 있습니다.

len(view) 는 tolist 의 길이와 같습니다. view.ndim = 0 이면 길이는 1입니다. view.ndim = 1 이면 길이는 뷰에 있는 요소의 개수와 같습니다. 고차원의 경우, 길이는 뷰의 중첩된 리스트 표현의 길이와 같습니다. itemsize 어트리뷰트는 단일 요소의 바이트 수를 알려줍니다.

memoryview 는 슬라이싱과 인덱싱을 지원하여 데이터를 노출합니다. 일차원 슬라이스는 서브 뷰를 만듭니다:

>>> v = memoryview(b'abcefg')
>>> v[1]
98
>>> v[-1]
103
>>> v[1:4]
<memory at 0x7f3ddc9f4350>
>>> bytes(v[1:4])
b'bce'

format 이 struct 모듈의 네이티브 형식 지정자 중 하나인 경우, 정수 또는 정수의 튜플을 사용하는 인덱싱도 지원되며 올바른 형으로 하나의 요소를 돌려줍니다. 일차원 메모리 뷰는 정수 또는 하나의 정수를 갖는 튜플로 인덱싱 할 수 있습니다. 다차원 메모리 뷰는 정확히 ndim 개의 정수를 갖는 튜플로 인덱싱할 수 있습니다. 여기서 ndim 은 차원 수입니다. 영차원 메모리 뷰는 빈 튜플로 인덱싱할 수 있습니다.

다음은 바이트가 아닌 형식의 예입니다:

>>> import array
>>> a = array.array('l', [-11111111, 22222222, -33333333, 44444444])
>>> m = memoryview(a)
>>> m[0]
-11111111
>>> m[-1]
44444444
>>> m[::2].tolist()
[-11111111, -33333333]

하부 객체가 쓰기 가능하면, 메모리 뷰는 일차원 슬라이스 대입을 지원합니다. 크기 변경은 허용되지 않습니다:

>>> data = bytearray(b'abcefg')
>>> v = memoryview(data)
>>> v.readonly
False
>>> v[0] = ord(b'z')
>>> data
bytearray(b'zbcefg')
>>> v[1:4] = b'123'
>>> data
bytearray(b'z123fg')
>>> v[2:3] = b'spam'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: memoryview assignment: lvalue and rvalue have different structures
>>> v[2:6] = b'spam'
>>> data
bytearray(b'z1spam')

‘B’, ‘b’ ‘c’ 형식의 해시 가능 (읽기 전용) 형의 일차원 메모리 뷰는 역시 해시 가능합니다. 해시는 hash(m) == hash(m.tobytes()) 로 정의됩니다:

>>> v = memoryview(b'abcefg')
>>> hash(v) == hash(b'abcefg')
True
>>> hash(v[2:4]) == hash(b'ce')
True
>>> hash(v[::-2]) == hash(b'abcefg'[::-2])
True

버전 3.3에서 변경: 이제 일차원 메모리 뷰를 슬라이스할 수 있습니다. 이제 형식이 ‘B’, ‘b’, ‘c’ 인 일차원 메모리 뷰는 해시 가능합니다.

버전 3.4에서 변경: 이제 메모리 뷰는 자동으로 collections.abc.Sequence 로 등록됩니다

버전 3.5에서 변경: 이제 메모리 뷰는 정수의 튜플로 인덱싱될 수 있습니다.

memoryview 는 몇 가지 메서드를 가지고 있습니다:

__eq__(exporter)

메모리 뷰와 PEP 3118 [https://www.python.org/dev/peps/pep-3118] 제공자(exporter)는 다음과 같은 조건을 만족할 때 같다고 비교됩니다: 모양이 동등하고 피연산자의 각 형식 코드가 struct 문법을 사용하여 해석될 때 모든 해당 값이 같다.

현재 tolist() 가 지원하는 struct 형식 문자열의 부분 집합의 경우, v.tolist() == w.tolist() 면 v 와 w 는 같습니다:

>>> import array
>>> a = array.array('I', [1, 2, 3, 4, 5])
>>> b = array.array('d', [1.0, 2.0, 3.0, 4.0, 5.0])
>>> c = array.array('b', [5, 3, 1])
>>> x = memoryview(a)
>>> y = memoryview(b)
>>> x == a == y == b
True
>>> x.tolist() == a.tolist() == y.tolist() == b.tolist()
True
>>> z = y[::-2]
>>> z == c
True
>>> z.tolist() == c.tolist()
True

형식 문자열이 struct 모듈에서 지원되지 않으면 객체는 항상 같지 않다고 비교됩니다 (형식 문자열과 버퍼 내용이 같더라도 그렇습니다):

>>> from ctypes import BigEndianStructure, c_long
>>> class BEPoint(BigEndianStructure):
...     _fields_ = [("x", c_long), ("y", c_long)]
...
>>> point = BEPoint(100, 200)
>>> a = memoryview(point)
>>> b = memoryview(point)
>>> a == point
False
>>> a == b
False

부동 소수점 숫자와 마찬가지로, 메모리 뷰 객체의 경우 v is w 일 때도 v == w 가 성립하지 않을 수 있습니다.

버전 3.3에서 변경: 이전 버전에서는 항목 형식과 논리 배열 구조를 무시하고 원시 메모리를 비교했습니다.

tobytes()

버퍼의 데이터를 바이트열로 돌려줍니다. 이는 메모리 뷰에 bytes 생성자를 호출하는 것과 동등합니다.

>>> m = memoryview(b"abc")
>>> m.tobytes()
b'abc'
>>> bytes(m)
b'abc'

불연속 배열의 경우 결과는 모든 요소를 바이트로 변환하여 평평한 리스트로 만든 것과 같습니다. tobytes() 는 struct 모듈 문법에 없는 것을 포함하여 모든 형식 문자열을 지원합니다.

hex()

버퍼 내의 각 바이트를 두 개의 16진수로 표현한 문자열 객체를 돌려줍니다.

>>> m = memoryview(b"abc")
>>> m.hex()
'616263'

버전 3.5에 추가.

tolist()

버퍼 내의 데이터를 요소들의 리스트로 돌려줍니다.

>>> memoryview(b'abc').tolist()
[97, 98, 99]
>>> import array
>>> a = array.array('d', [1.1, 2.2, 3.3])
>>> m = memoryview(a)
>>> m.tolist()
[1.1, 2.2, 3.3]

버전 3.3에서 변경: tolist() 는 이제 struct 모듈 문법의 모든 단일 문자 네이티브 형식과 다차원 표현을 지원합니다.

release()

메모리 뷰 객체에 의해 노출된 하부 버퍼를 해제합니다. 많은 객체는 뷰가 그 객체에 연결될 때 특별한 조처를 합니다 (예를 들어, bytearray 는 일시적으로 크기 조절을 금지합니다); 따라서, release()를 호출하면 가능한 한 빨리 이 제한 사항을 제거하고 붙잡힌 자원을 해제할 수 있습니다.

이 메서드가 호출된 후, 뷰에 대한 더 이상의 연산은 ValueError 를 일으킵니다 (여러 번 호출 될 수 있는 release() 자신은 예외입니다):

>>> m = memoryview(b'abc')
>>> m.release()
>>> m[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: operation forbidden on released memoryview object

with 문을 사용한 컨텍스트 관리 프로토콜은 비슷한 효과를 낼 수 있습니다:

>>> with memoryview(b'abc') as m:
...     m[0]
...
97
>>> m[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: operation forbidden on released memoryview object

버전 3.2에 추가.

cast(format[, shape])

메모리 뷰를 새로운 형식이나 모양으로 캐스팅합니다. shape 의 기본값은 [byte_length//new_itemsize] 인데, 결과 뷰가 일차원이 된다는 의미입니다. 반환 값은 새로운 메모리 뷰이지만 버퍼 자체는 복사되지 않습니다. 지원되는 캐스팅은 1D -> C-연속 과 C-연속 -> 1D입니다.

목적 형식은 struct 문법의 단일 요소 네이티브 형식으로 제한됩니다. 형식 중 하나는 바이트 형식(‘B’, ‘b’, ‘c’)이어야 합니다. 결과의 바이트 길이는 원래 길이와 같아야 합니다.

1D/long 을 1D/unsigned bytes 로 캐스트:

>>> import array
>>> a = array.array('l', [1,2,3])
>>> x = memoryview(a)
>>> x.format
'l'
>>> x.itemsize
8
>>> len(x)
3
>>> x.nbytes
24
>>> y = x.cast('B')
>>> y.format
'B'
>>> y.itemsize
1
>>> len(y)
24
>>> y.nbytes
24

1D/unsigned bytes 를 1D/char 로 캐스트:

>>> b = bytearray(b'zyz')
>>> x = memoryview(b)
>>> x[0] = b'a'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: memoryview: invalid value for format "B"
>>> y = x.cast('c')
>>> y[0] = b'a'
>>> b
bytearray(b'ayz')

1D/bytes 를 3D/ints 로 캐스트 한 후 다시 1D/signed char 로 캐스트:

>>> import struct
>>> buf = struct.pack("i"*12, *list(range(12)))
>>> x = memoryview(buf)
>>> y = x.cast('i', shape=[2,2,3])
>>> y.tolist()
[[[0, 1, 2], [3, 4, 5]], [[6, 7, 8], [9, 10, 11]]]
>>> y.format
'i'
>>> y.itemsize
4
>>> len(y)
2
>>> y.nbytes
48
>>> z = y.cast('b')
>>> z.format
'b'
>>> z.itemsize
1
>>> len(z)
48
>>> z.nbytes
48

Cast 1D/unsigned long to 2D/unsigned long:

>>> buf = struct.pack("L"*6, *list(range(6)))
>>> x = memoryview(buf)
>>> y = x.cast('L', shape=[2,3])
>>> len(y)
2
>>> y.nbytes
48
>>> y.tolist()
[[0, 1, 2], [3, 4, 5]]

버전 3.3에 추가.

버전 3.5에서 변경: 바이트 형식으로 변환할 때 소스 형식이 더는 제한되지 않습니다.

몇 가지 읽기 전용 어트리뷰트도 사용할 수 있습니다:

obj

메모리 뷰의 하부 객체:

>>> b  = bytearray(b'xyz')
>>> m = memoryview(b)
>>> m.obj is b
True

버전 3.3에 추가.

nbytes

nbytes == product(shape) * itemsize == len(m.tobytes()). 배열이 연속적일 때 차지하게 될 바이트 수입니다. 꼭 len(m)과 같을 필요는 없습니다:

>>> import array
>>> a = array.array('i', [1,2,3,4,5])
>>> m = memoryview(a)
>>> len(m)
5
>>> m.nbytes
20
>>> y = m[::2]
>>> len(y)
3
>>> y.nbytes
12
>>> len(y.tobytes())
12

다차원 배열:

>>> import struct
>>> buf = struct.pack("d"*12, *[1.5*x for x in range(12)])
>>> x = memoryview(buf)
>>> y = x.cast('d', shape=[3,4])
>>> y.tolist()
[[0.0, 1.5, 3.0, 4.5], [6.0, 7.5, 9.0, 10.5], [12.0, 13.5, 15.0, 16.5]]
>>> len(y)
3
>>> y.nbytes
96

버전 3.3에 추가.

readonly

메모리가 읽기 전용인지 여부를 나타내는 논리값.

format

뷰의 각 요소에 대한 형식(struct 모듈 스타일)을 포함하는 문자열입니다. 메모리 뷰는 제공자로부터 임의의 형식 문자열로 만들어질 수 있지만, 일부 메서드(예, tolist())는 원시 네이티브 단일 요소 형식으로 제한됩니다.

버전 3.3에서 변경: 'B' 형식은 이제 struct 모듈 문법에 따라 처리됩니다. 이것은 memoryview(b'abc')[0] == b'abc'[0] == 97 이 됨을 의미합니다.

itemsize

메모리 뷰 각 요소의 크기 (바이트):

>>> import array, struct
>>> m = memoryview(array.array('H', [32000, 32001, 32002]))
>>> m.itemsize
2
>>> m[0]
32000
>>> struct.calcsize('H') == m.itemsize
True

ndim

메모리가 나타내는 다차원 배열의 차원 수를 나타내는 정수.

shape

N-차원 배열로서의 메모리의 모양을 가리키는, 길이 ndim 인 정수의 튜플입니다.

버전 3.3에서 변경: ndim = 0 일 때 None 대신 빈 튜플을 제공합니다.

strides

배열의 각 차원에 대해 각 요소를 참조하는데 필요한 바이트 수를 제공하는, 길이 ndim 인 정수의 튜플입니다.

버전 3.3에서 변경: ndim = 0 일 때 None 대신 빈 튜플을 제공합니다.

suboffsets

PIL 스타일 배열에 내부적으로 사용됩니다. 값은 정보 제공용입니다.

c_contiguous

메모리가 C-연속 인지를 나타내는 논리값.

버전 3.3에 추가.

f_contiguous

메모리가 포트란 연속 인지를 나타내는 논리값.

버전 3.3에 추가.

contiguous

메모리가 연속 인지를 나타내는 논리값.

버전 3.3에 추가.

집합 형 — set, frozenset

집합 (set) 객체는 서로 다른 해시 가능 객체의 순서 없는 컬렉션입니다. 일반적인 용도는 멤버십 검사, 시퀀스에서 중복 제거와 교집합, 합집합, 차집합, 대칭 차집합과 같은 수학 연산을 계산하는 것입니다. (다른 컨테이너들은 내장 dict, list, tuple 클래스 및 collections 모듈을 참조하십시오.)

다른 컬렉션과 마찬가지로, 집합은 x in set,``len(set)``, for x in set 을 지원합니다. 순서가 없는 컬렉션이므로, 집합은 원소의 위치나 삽입 순서를 기록하지 않습니다. 따라서 집합은 인덱싱, 슬라이싱 또는 기타 시퀀스와 유사한 동작을 지원하지 않습니다.

현재 두 가지 내장형이 있습니다, set과 frozenset. set 형은 가변입니다 — 내용을 add() 나 remove() 와 같은 메서드를 사용하여 변경할 수 있습니다. 가변이기 때문에, 해시값이 없으며 딕셔너리 키 또는 다른 집합의 원소로 사용할 수 없습니다. frozenset 형은 불변이고 해시 가능 합니다 — 만들어진 후에는 내용을 바꿀 수 없습니다; 따라서 딕셔너리 키 또는 다른 집합의 원소로 사용할 수 있습니다.

비어 있지 않은 set은 (frozenset 은 아닙니다) set 생성자뿐만 아니라 중괄호 안에 쉼표로 구분된 원소 목록을 넣어서 만들 수 있습니다, 예를 들어: {'jack', 'sjoerd'}.

두 클래스의 생성자는 같게 작동합니다:

class set([iterable])

class frozenset([iterable])

iterable 에서 요소를 취하는 새 set 또는 frozenset 객체를 돌려줍니다. 집합의 원소는 반드시 해시 가능 해야 합니다. 집합의 집합을 표현하려면, 포함되는 집합은 반드시 frozenset 객체여야 합니다. iterable 을 지정하지 않으면 새 빈 집합을 돌려줍니다.

set과 frozenset 의 인스턴스는 다음과 같은 연산을 제공합니다:

len(s)

집합 s 의 원소 수(s 의 크기)를 돌려줍니다.

x in s

s 에 대해 x 의 멤버십을 검사합니다.

x not in s

s 에 대해 x 의 비 멤버십을 검사합니다.

isdisjoint(other)

집합이 other 와 공통 원소를 갖지 않는 경우 True 을 돌려줍니다. 집합은 교집합이 공집합일 때, 그리고 그때만 서로소(disjoint)라고 합니다.

issubset(other)

set <= other

집합의 모든 원소가 other 에 포함되는지 검사합니다.

set < other

집합이 other 의 진부분집합인지 검사합니다, 즉, set <= other and set != other.

issuperset(other)

set >= other

other 의 모든 원소가 집합에 포함되는지 검사합니다.

set > other

집합이 other 의 진상위집합인지 검사합니다, 즉, set >= other and set != other.

union(*others)

set | other | ...

집합과 모든 others에 있는 원소들로 구성된 새 집합을 돌려줍니다.

intersection(*others)

set & other & ...

집합과 모든 others의 공통 원소들로 구성된 새 집합을 돌려줍니다.

difference(*others)

set - other - ...

집합에는 포함되었으나 others에는 포함되지 않은 원소들로 구성된 새 집합을 돌려줍니다.

symmetric_difference(other)

set ^ other

집합이나 other에 포함되어 있으나 둘 모두에 포함되지는 않은 원소들로 구성된 새 집합을 돌려줍니다.

copy()

집합의 얕은 복사본을 돌려줍니다.

참고로, 연산자가 아닌 버전의 union(), intersection(), difference(), symmetric_difference(), issubset(), issuperset() 메서드는 임의의 이터러블을 인자로 받아들입니다. 대조적으로, 연산자를 기반으로 하는 대응 연산들은 인자가 집합일 것을 요구합니다. 이것은 오류가 발생하기 쉬운 set('abc') & 'cbs' 와 같은 구성을 배제하고 더 읽기 쉬운 set('abc').intersection('cbs') 를 선호합니다.

set과 frozenset 모두 집합 간의 비교를 지원합니다. 두 집합은 각 집합의 모든 원소가 다른 집합에 포함되어있는 경우에만 같습니다 (서로 다른 집합의 부분집합입니다). 집합이 다른 집합의 진부분집합(부분집합이지만 같지는 않은 경우)일 때만 첫 번째 집합이 두 번째 집합보다 작습니다. 집합이 다른 집합의 진상위집합(상위집합이지만 같지는 않은 경우)일 때만 첫 번째 집합이 두 번째 집합보다 큽니다.

set 의 인스턴스는 그 원소를 기반으로 frozenset 의 인스턴스와 비교됩니다. 예를 들어, set('abc') == frozenset('abc') 는 True 를 돌려주고 set('abc') in set([frozenset('abc')]) 도 마찬가지입니다.

부분 집합 및 동등 비교는 전 순서(total ordering) 함수로 일반화되지 않습니다. 예를 들어, 비어 있지 않은 두 개의 서로소인 집합은 같지 않고 서로의 부분 집합이 아닙니다, 그래서 다음은 모두 False 를 돌려줍니다: a<b, a==b, a>b.

집합은 부분 순서(부분 집합 관계)만 정의하기 때문에, 집합의 리스트에 대한 list.sort() 메서드의 결과는 정의되지 않습니다.

딕셔너리 키처럼, 집합의 원소는 반드시 해시 가능 해야 합니다.

set 인스턴스와 frozenset 을 혼합 한 이항 연산은 첫 번째 피연산자의 형을 돌려줍니다. 예를 들어: frozenset('ab') | set('bc') 는 frozenset 의 인스턴스를 돌려줍니다.

다음 표는 frozenset 의 불변 인스턴스에는 적용되지 않고 set 에서만 사용할 수 있는 연산들을 나열합니다:

update(*others)

set |= other | ...

집합을 갱신해서, 모든 others의 원소들을 더합니다.

intersection_update(*others)

set &= other & ...

집합을 갱신해서, 그 집합과 others에 공통으로 포함된 원소들만 남깁니다.

difference_update(*others)

set -= other | ...

집합을 갱신해서, others에 있는 원소들을 제거합니다.

symmetric_difference_update(other)

set ^= other

집합을 갱신해서, 두 집합의 어느 한 곳에만 포함된 원소들만 남깁니다.

add(elem)

원소 elem 을 집합에 추가합니다.

remove(elem)

원소 elem 을 집합에서 제거합니다. elem 가 집합에 포함되어 있지 않으면 KeyError 를 일으킵니다.

discard(elem)

원소 elem 이 집합에 포함되어 있으면 제거합니다.

pop()

집합으로부터 임의의 원소를 제거해 돌려줍니다. 집합이 비어있는 경우 KeyError 를 일으킵니다.

clear()

집합의 모든 원소를 제거합니다.

참고로, update(), intersection_update(), difference_update(), symmetric_difference_update() 메서드의 비 연산자 버전은 임의의 이터러블을 인자로 받아들입니다.

참고로, __contains__(), remove(), discard() 메서드로 제공되는 elem 인자는 set 일 수 있습니다. 동등한 frozenset 검색을 지원하기 위해, elem 으로 임시 frozenset 을 만듭니다.

매핑 형 — dict

매핑 객체는 해시 가능 값을 임의의 객체에 대응합니다. 매핑은 가변 객체입니다. 현재 오직 하나의 표준 매핑 형이 있습니다, 딕셔너리 (dictionary). (다른 컨테이너들은 내장 list, set, tuple 클래스 및 collections 모듈을 참조하십시오.)

딕셔너리의 키는 거의 임의의 값입니다. 해시 가능 하지 않은 값들, 즉, 리스트, 딕셔너리 또는 다른 가변형 (객체 아이덴티티 대신 값으로 비교됩니다) 은 키로 사용할 수 없습니다. 키에 사용되는 숫자 형은 숫자 비교를 위한 일반적인 규칙을 따릅니다: 두 숫자가 같다고 비교되는 경우 (1 과 1.0 처럼) 같은 딕셔너리 항목을 인덱싱하는데 서로 교환하여 사용할 수 있습니다. (그러나 컴퓨터는 부동 소수점 숫자를 근삿값으로 저장하므로 이것들을 딕셔너리 키로 사용하는 것은 현명하지 않습니다.)

딕셔너리는 dict 생성자뿐만 아니라 중괄호 안에 쉼표로 구분된 key: value 쌍을 나열해서 만들 수 있습니다, 예를 들어: {'jack': 4098, 'sjoerd': 4127} 또는 {4098: 'jack', 4127: 'sjoerd'}.

class dict(**kwarg)

class dict(mapping, **kwarg)

class dict(iterable, **kwarg)

선택적 위치 인자와 (비어있을 수 있는) 키워드 인자들의 집합으로부터 초기화된 새 딕셔너리를 돌려줍니다.

위치 인자가 제공되지 않으면 빈 딕셔너리가 만들어집니다. 위치 인자가 지정되고 매핑 객체인 경우, 매핑 객체와 같은 키-값 쌍을 갖는 딕셔너리가 만들어집니다. 그렇지 않으면, 위치 인자는 이터러블 객체여야 합니다. 이터러블의 각 항목은 그 자체로 정확하게 두 개의 객체가 있는 이터러블이어야 합니다. 각 항목의 첫 번째 객체는 새 딕셔너리의 키가 되고, 두 번째 객체는 해당 값이 됩니다. 키가 두 번 이상 나타나면, 그 키의 마지막 값이 새 딕셔너리의 해당 값이 됩니다.

키워드 인자가 제공되면, 키워드 인자와 해당 값이 위치 인자로부터 만들어진 딕셔너리에 추가됩니다. 추가되는 키가 이미 존재하면, 키워드 인자에서 온 값이 위치 인자에게서 온 값을 대체합니다.

예를 들어, 다음 예제는 모두 {"one": 1, "two": 2, "three": 3} 와 같은 딕셔너리를 돌려줍니다:

>>> a = dict(one=1, two=2, three=3)
>>> b = {'one': 1, 'two': 2, 'three': 3}
>>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
>>> d = dict([('two', 2), ('one', 1), ('three', 3)])
>>> e = dict({'three': 3, 'one': 1, 'two': 2})
>>> a == b == c == d == e
True

첫 번째 예제에서와같이 키워드 인자는 유효한 파이썬 식별자인 키에 대해서만 작동합니다. 그 외의 경우는 모든 유효한 키를 사용할 수 있습니다.

이것들은 딕셔너리가 지원하는 연산들입니다 (그러므로, 사용자 정의 매핑 형도 지원해야 합니다):

list(d)

Return a list of all the keys used in the dictionary d.

len(d)

딕셔너리 d 에 있는 항목의 수를 돌려줍니다.

d[key]

키 key 인 d 의 항목을 돌려줍니다. key 가 매핑에 없는 경우 KeyError 를 일으킵니다.

dict 의 서브 클래스가 method __missing__() 을 정의하고 key 가 존재하지 않는다면, d[key] 연산은 키 key 를 인자로 하여 그 메서드를 호출합니다. 그런 다음 d[key] 연산은 __missing__(key) 호출이 반환한 값이나 일으킨 예외를 그대로 반환하거나 일으킵니다. 다른 연산이나 메서드는 __missing__() 을 호출하지 않습니다. __missing__() 이 정의되어 있지 않으면 KeyError 를 일으킵니다. __missing__() 은 메서드 여야 합니다; 인스턴스 변수가 될 수 없습니다:

>>> class Counter(dict):
...     def __missing__(self, key):
...         return 0
>>> c = Counter()
>>> c['red']
0
>>> c['red'] += 1
>>> c['red']
1

위의 예는 collections.Counter 구현 일부를 보여줍니다. 다른 __missing__ 메서드가 collections.defaultdict 에서 사용됩니다.

d[key] = value

d[key] 를 value 로 설정합니다.

del d[key]

d 에서 d[key] 를 제거합니다. key 가 매핑에 없는 경우 KeyError 를 일으킵니다.

key in d

d 에 키 key 가 있으면 True 를, 그렇지 않으면 False 를 돌려줍니다.

key not in d

not key in d 와 동등합니다.

iter(d)

딕셔너리의 키에 대한 이터레이터를 돌려줍니다. 이것은 iter(d.keys()) 의 단축입니다.

clear()

딕셔너리에서 모든 항목을 제거합니다.

copy()

딕셔너리의 얕은 복사본을 돌려줍니다.

classmethod fromkeys(iterable[, value])

iterable 이 제공하는 값들을 키로 사용하고 모든 값을 value 로 설정한 새 딕셔러리를 돌려줍니다.

fromkeys() 는 새로운 딕셔너리를 돌려주는 클래스 메서드입니다. value 의 기본값은 None 입니다.

get(key[, default])

key 가 딕셔너리에 있는 경우 key 에 대응하는 값을 돌려주고, 그렇지 않으면 default 를 돌려줍니다. default 가 주어지지 않으면 기본값 None 이 사용됩니다. 그래서 이 메서드는 절대로 KeyError 를 일으키지 않습니다.

items()

딕셔너리 항목들((key, value) 쌍들)의 새 뷰를 돌려줍니다. 뷰 객체의 설명서 을 참조하세요.

keys()

딕셔너리 키들의 새 뷰를 돌려줍니다. 뷰 객체의 설명서 을 참조하세요.

pop(key[, default])

key 가 딕셔너리에 있으면 제거하고 그 값을 돌려줍니다. 그렇지 않으면 default 를 돌려줍니다. default 가 주어지지 않고 key 가 딕셔너리에 없으면 KeyError 를 일으킵니다.

popitem()

딕셔너리에서 (key, value) 쌍을 제거하고 돌려줍니다. 쌍은 LIFO 순서로 반환됩니다.

popitem() 은 집합 알고리즘에서 종종 사용되듯이 딕셔너리를 파괴적으로 이터레이션 하는 데 유용합니다. 딕셔너리가 비어 있으면 popitem() 호출은 KeyError 를 일으킵니다.

버전 3.7에서 변경: 이제 LIFO 순서가 보장됩니다. 이전 버전에서는, popitem()가 임의의 키/값 쌍을 반환합니다.

setdefault(key[, default])

key 가 딕셔너리에 있으면 해당 값을 돌려줍니다. 그렇지 않으면, default 값을 갖는 key 를 삽입한 후 default 를 돌려줍니다. default 의 기본값은 None 입니다.

update([other])

other 가 제공하는 키/값 쌍으로 사전을 갱신합니다. 기존 키는 덮어씁니다. None 을 돌려줍니다.

update() 는 다른 딕셔너리 객체 나 키/값 쌍(길이 2인 튜플이나 다른 이터러블)을 주는 이터레이터를 모두 받아들입니다. 키워드 인자가 지정되면, 딕셔너리는 그 키/값 쌍으로 갱신됩니다: d.update(red=1, blue=2).

values()

딕셔너리 값들의 새 뷰를 돌려줍니다. 뷰 객체의 설명서 을 참조하세요.

An equality comparison between one dict.values() view and another will always return False. This also applies when comparing dict.values() to itself:

>>> d = {'a': 1}
>>> d.values() == d.values()
False

Dictionaries compare equal if and only if they have the same (key, value) pairs (regardless of ordering). Order comparisons (‘<’, ‘<=’, ‘>=’, ‘>’) raise TypeError.

딕셔너리는 삽입 순서를 유지합니다. 키를 갱신해도 순서에는 영향을 미치지 않습니다. 삭제 후에 추가된 키는 끝에 삽입됩니다.:

>>> d = {"one": 1, "two": 2, "three": 3, "four": 4}
>>> d
{'one': 1, 'two': 2, 'three': 3, 'four': 4}
>>> list(d)
['one', 'two', 'three', 'four']
>>> list(d.values())
[1, 2, 3, 4]
>>> d["one"] = 42
>>> d
{'one': 42, 'two': 2, 'three': 3, 'four': 4}
>>> del d["two"]
>>> d["two"] = None
>>> d
{'one': 42, 'three': 3, 'four': 4, 'two': None}

버전 3.7에서 변경: 딕셔너리 순서는 삽입 순서임이 보장됩니다. 이 동작은 3.6부터 CPython의 구현 세부 사항입니다.

더 보기

types.MappingProxyType 를 dict 의 읽기 전용 뷰를 만드는 데 사용할 수 있습니다.

딕셔너리 뷰 객체

dict.keys(), dict.values(), dict.items() 가 돌려주는 객체는 뷰 객체 입니다. 딕셔너리의 항목들에 대한 동적 뷰를 제공합니다. 즉, 딕셔너리가 변경되면 뷰는 이러한 변경 사항을 반영합니다.

딕셔너리 뷰는 이터레이션을 통해 각각의 데이터를 산출할 수 있고, 멤버십 검사를 지원합니다:

len(dictview)

딕셔너리에 있는 항목 수를 돌려줍니다.

iter(dictview)

딕셔너리에서 키, 값, 항목((key, value) 튜플로 표현됩니다)에 대한 이터레이터를 돌려줍니다.

키와 값은 삽입 순서로 이터레이션 됩니다. 이 때문에 zip()을 사용해서 (value, key) 쌍을 만들 수 있습니다: pairs = zip(d.values(), d.keys()). 같은 리스트를 만드는 다른 방법은 pairs = [(v, k) for (k, v) in d.items()] 입니다.

딕셔너리에 항목을 추가하거나 삭제하는 동안 뷰를 이터레이션 하면 RuntimeError 를 일으키거나 모든 항목을 이터레이션 하지 못할 수 있습니다.

버전 3.7에서 변경: 딕셔너리의 순서가 삽입 순서임이 보장됩니다.

x in dictview

x 가 하부 딕셔너리의 키, 갑, 항목에 있는 경우 True 를 돌려줍니다 (마지막의 경우 x 는 (key, value) 튜플이어야 합니다).

키 뷰는 항목이 고유하고 해시 가능하므로 집합과 유사합니다. 모든 값이 해시 가능해서 (key, value) 쌍들이 고유하고 해시 가능하다면, 항목 뷰 역시 집합과 유사합니다. (값 뷰는 항목이 일반적으로 고유하지 않기 때문에 집합과 같이 취급되지 않습니다.) 집합과 유사한 뷰의 경우 추상 베이스 클래스 collections.abc.Set 에 정의된 모든 연산을 사용할 수 있습니다 (예를 들어, ==, <, ^).

딕셔너리 뷰 사용의 예:

>>> dishes = {'eggs': 2, 'sausage': 1, 'bacon': 1, 'spam': 500}
>>> keys = dishes.keys()
>>> values = dishes.values()

>>> # iteration
>>> n = 0
>>> for val in values:
...     n += val
>>> print(n)
504

>>> # keys and values are iterated over in the same order (insertion order)
>>> list(keys)
['eggs', 'sausage', 'bacon', 'spam']
>>> list(values)
[2, 1, 1, 500]

>>> # view objects are dynamic and reflect dict changes
>>> del dishes['eggs']
>>> del dishes['sausage']
>>> list(keys)
['bacon', 'spam']

>>> # set operations
>>> keys & {'eggs', 'bacon', 'salad'}
{'bacon'}
>>> keys ^ {'sausage', 'juice'}
{'juice', 'sausage', 'bacon', 'spam'}

컨텍스트 관리자 형

파이썬의 with 문은 컨텍스트 관리자가 정의한 실행 시간 컨텍스트 개념을 지원합니다. 이는 한 쌍의 메서드를 사용해서 구현되는데, 사용자 정의 클래스가 문장 바디가 실행되기 전에 진입하고, 문장이 끝날 때 탈출하는 실행 시간 컨텍스트를 정의할 수 있게 합니다:

contextmanager.__enter__()

실행시간 컨텍스트에 진입하고 이 객체 자신이나 실행 시간 컨텍스트와 관련된 다른 객체를 돌려줍니다. 이 메서드가 돌려주는 값은, 이 컨텍스트 관리자를 사용하는 with 문의 as 절의 식별자에 연결됩니다.

자신을 돌려주는 컨텍스트 관리자의 예는 파일 객체 입니다. 파일 객체는 __enter__() 에서 자기 자신을 돌려주는데 with 문의 컨텍스트 표현식으로 open() 을 사용할 수 있도록 하기 위함입니다.

관련 객체를 돌려주는 컨텍스트 관리자의 예는 decimal.localcontext() 가 돌려주는 것입니다. 이 관리자들은 활성 십진 소수 컨텍스트를 원래 십진 소수 컨텍스트의 복사본으로 설정한 다음 복사본을 돌려줍니다. 이것은 with 문 바깥의 코드에 영향을 주지 않으면서 with 문 바디에 있는 현재 십진 소수 컨텍스트를 변경할 수 있게 합니다.

contextmanager.__exit__(exc_type, exc_val, exc_tb)

실행 시간 컨텍스트를 탈출하고 발생한 예외를 막아야 하는지를 가리키는 논리 플래그를 돌려줍니다. with 문의 바디를 실행하는 동안 예외가 발생하면, 인자에 예외 형, 값 및 추적 정보가 포함됩니다. 그렇지 않으면, 세 가지 인자 모두 None 입니다.

이 메서드에서 참 값을 돌려주면 with 문이 예외를 막고 with 문 바로 뒤에 오는 문장에서 계속 실행됩니다. 그 이외의 경우, 이 메서드의 실행이 완료된 후에 예외는 계속 퍼집니다. 이 메서드의 실행 중에 발생하는 예외는 with 문의 바디에서 발생한 모든 예외를 대체합니다.

전달 된 예외를 명시적으로 다시 일으켜서는 안 됩니다 - 대신, 이 메서드가 성공적으로 완료되었으며 발생 된 예외를 막지 않겠다는 의미의 거짓을 돌려주어야 합니다. 이렇게 하면 컨텍스트 관리 코드가 __exit__() 메서드가 실제로 실패했는지를 쉽게 감지할 수 있습니다.

파이썬은 쉬운 스레드 동기화, 파일이나 다른 객체의 신속한 닫기, 그리고 활성 십진 소수 산술 컨텍스트의 보다 간단한 조작을 지원하기 위해 몇 가지 컨텍스트 관리자를 정의합니다. 컨텍스트 관리 프로토콜의 구현을 넘어 구체적인 형은 특별히 취급되지 않습니다. 몇 가지 예제는 contextlib 모듈을 보십시오.

파이썬의 제너레이터s들과 contextlib.contextmanager 데코레이터는 이 프로토콜을 구현하는 편리한 방법을 제공합니다. 제너레이터 함수가 contextlib.contextmanager 데코레이터로 데코레이팅 되면, 데코레이팅 되지 않은 제너레이터 함수가 만드는 이터레이터 대신에 필요한 __enter__() 와 __exit__() 메서드를 구현하는 컨텍스트 관리자를 돌려줍니다.

파이썬/C API의 파이썬 객체에 대한 형 구조체에는 이러한 메서드들을 위해 준비된 슬롯이 없다는 점에 유의하십시오. 이러한 메서드를 정의하고자 하는 확장형은 일반적인 파이썬 액세스가 가능한 메서드로 제공해야 합니다. 실행 시간 컨텍스트를 설정하는 오버헤드와 비교할 때 한 번의 클래스 딕셔너리 조회의 오버헤드는 무시할 수 있습니다.

기타 내장형

인터프리터는 여러 가지 다른 객체를 지원합니다. 이것들 대부분은 한두 가지 연산만 지원합니다.

모듈

모듈에 대한 유일한 특별한 연산은 어트리뷰트 액세스입니다: m.name. 여기서 m 은 모듈이고 name 은 m 의 심볼 테이블에 정의된 이름에 액세스합니다. 모듈 어트리뷰트는 대입할 수 있습니다. (import 문은 엄밀히 말하면 모듈 객체에 대한 연산이 아닙니다; import foo 는 foo 라는 이름의 모듈 객체가 존재할 것을 요구하지 않고, 어딘가에 있는 foo 라는 이름의 (외부) 정의 를 요구합니다.

모든 모듈의 특수 어트리뷰트는 __dict__ 입니다. 이것은 모듈의 심볼 테이블을 저장하는 딕셔너리입니다. 이 딕셔너리를 수정하면 모듈의 심볼 테이블이 실제로 변경되지만, __dict__ 어트리뷰트에 대한 직접 대입은 불가능합니다 (m.__dict__['a'] = 1 라고 쓸 수 있고, m.a 가 1 이 되지만, m.__dict__ = {} 라고 쓸 수는 없습니다). __dict__ 의 직접적인 수정은 추천하지 않습니다.

인터프리터에 내장된 모듈은 다음과 같이 쓰입니다: <module 'sys' (built-in)>. 파일에서 로드되면, <module 'os' from '/usr/local/lib/pythonX.Y/os.pyc'> 처럼 쓰입니다.

클래스와 클래스 인스턴스

여기에 대해서는 객체, 값, 형와 클래스 정의를 참조하세요.

함수

함수 객체는 함수 정의로 만들어집니다. 함수 객체에 대한 유일한 연산은 호출하는 것입니다: func(argument-list).

함수 객체에는 내장 함수와 사용자 정의 함수라는 두 가지 종류가 있습니다. 두 함수 모두 같은 연산(함수 호출)을 지원하지만, 구현이 다르므로 서로 다른 객체 형입니다.

자세한 정보는 함수 정의을 보십시오.

메서드

메서드는 어트리뷰트 표기법을 사용하여 호출되는 함수입니다. 두 가지 종류가 있습니다: 내장 메서드(리스트의 append() 같은 것들)와 클래스 인스턴스 메서드. 내장 메서드는 이를 지원하는 형에서 설명됩니다.

인스턴스를 통해 메서드(클래스 이름 공간에 정의 된 함수)에 액세스하면, 특별한 객체인 연결된 메서드 (bound method) (인스턴스 메서드 (instance method) 라고도 부릅니다) 객체를 얻게 됩니다. 호출되면 인자 목록에 self 인자를 추가합니다. 연결된 메서드는 두 가지 특수한 읽기 전용 어트리뷰트를 가지고 있습니다: m.__self__ 는 메서드가 작동하는 객체이고, m.__func__ 는 메서드를 구현하는 함수입니다. m(arg-1, arg-2, ..., arg-n) 을 호출하는 것은 m.__func__(m.__self__, arg-1, arg-2, ..., arg-n) 를 호출하는 것과 완전히 같습니다.

함수 객체와 같이, 연결된 메서드 객체는 임의 어트리뷰트를 읽는 것을 지원합니다. 그러나 메서드 어트리뷰트는 실제로 하부 함수 객체(meth.__func__)에 저장되기 때문에, 연결된 메서드에 메서드 어트리뷰트를 설정하는 것은 허용되지 않습니다. 메서드 어트리뷰트를 설정하려고 하면 AttributeError 를 일으킵니다. 메서드 어트리뷰트를 설정하려면, 명시적으로 하부 함수 객체에 설정해야 합니다:

>>> class C:
...     def method(self):
...         pass
...
>>> c = C()
>>> c.method.whoami = 'my name is method'  # can't set on the method
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'method' object has no attribute 'whoami'
>>> c.method.__func__.whoami = 'my name is method'
>>> c.method.whoami
'my name is method'

자세한 정보는 표준형 계층를 보십시오.

코드 객체

코드 객체는 함수 바디와 같은 “의사 컴파일된” 실행 가능한 파이썬 코드를 표현하기 위해 구현에서 사용됩니다. 전역 실행 환경에 대한 참조가 없으므로 함수 객체와 다릅니다. 코드 객체는 내장 compile() 함수가 돌려주고, 함수 객체들로부터 __code__ 어트리뷰트를 통해 추출할 수 있습니다. code 모듈도 참고하십시오.

코드 객체는 exec() 또는 eval() 내장 함수에 (소스 문자열 대신) 전달하여 실행하거나 값을 구할 수 있습니다.

자세한 정보는 표준형 계층를 보십시오.

형 객체

형 객체는 다양한 객체 형을 나타냅니다. 객체의 형은 내장 함수 type()으로 액세스할 수 있습니다. 형에는 특별한 연산이 없습니다. 표준 모듈 types 는 모든 표준 내장형의 이름을 정의합니다.

형은 다음과 같이 쓰입니다: <class 'int'>.

널 객체

이 객체는 명시적으로 값을 돌려주지 않는 함수에 의해 반환됩니다. 특별한 연산을 지원하지 않습니다. 정확하게 하나의 널 객체가 있으며, 이름은 None``(내장 이름)입니다. ``type(None)() 은 같은 싱글톤을 만듭니다.

None 이라고 쓰입니다.

Ellipsis 객체

이 객체는 일반적으로 슬라이싱에 사용됩니다 (슬라이싱(Slicings) 를 참조하세요). 특별한 연산을 지원하지 않습니다. 정확하게 하나의 Ellipsis 객체가 있으며, 이름은 Ellipsis`(내장 이름)입니다. ``type(Ellipsis)()` 는 Ellipsis 싱글톤을 만듭니다.

Ellipsis 나 ... 로 쓰입니다.

NotImplemented 객체

이 객체는 비교와 이항 연산이 지원하지 않는 형에 대한 요청을 받았을 때 돌려줍니다. 자세한 정보는 비교를 보십시오. 정확하게 하나의 NotImplemented 객체가 있습니다. type(NotImplemented)() 는 싱글톤 인스턴스를 만듭니다.

NotImplemented 로 쓰입니다.

논리값

논리값은 두 개의 상수 객체인 False 와 True 입니다. 이것들은 논리값을 나타내기 위해 사용됩니다 (하지만 다른 값도 거짓 또는 참으로 간주 될 수 있습니다). 숫자 컨텍스트(예를 들어, 산술 연산자의 인자로 사용될 때)에서는 각각 정수 0과 1처럼 작동합니다. 내장 함수 bool() 은 값이 논리값으로 해석될 수 있는 경우 모든 값을 논리값으로 변환하는 데 사용할 수 있습니다 (위의 논리값 검사 절을 참조하세요).

각각 False 과 True 로 쓰입니다.

내부 객체

여기에 관한 정보는 표준형 계층를 참조하십시오. 스택 프레임 객체, 트레이스백 객체 및 슬라이스 객체에 관해 설명합니다.

특수 어트리뷰트

관련성이 있을 때, 구현은 몇 가지 객체 유형에 몇 가지 특수 읽기 전용 어트리뷰트를 추가합니다. 이 중 일부는 dir() 내장 함수에 의해 보고되지 않습니다.

object.__dict__

객체의 (쓰기 가능한) 어트리뷰트를 저장하는 데 사용되는 딕셔너리나 또는 기타 매핑 객체.

instance.__class__

클래스 인스턴스가 속한 클래스.

class.__bases__

클래스 객체의 베이스 클래스들의 튜플.

definition.__name__

클래스, 함수, 메서드, 디스크립터 또는 제너레이터 인스턴스의 이름.

definition.__qualname__

클래스, 함수, 메서드, 디스크립터 또는 제너레이터 인스턴스의 정규화된 이름.

버전 3.3에 추가.

class.__mro__

이 어트리뷰트는 메서드 결정 중에 베이스 클래스를 찾을 때 고려되는 클래스들의 튜플입니다.

class.mro()

이 메서드는 인스턴스의 메서드 결정 순서를 사용자 정의하기 위해 메타 클래스가 재정의할 수 있습니다. 클래스 인스턴스를 만들 때 호출되며 그 결과는 __mro__ 에 저장됩니다.

class.__subclasses__()

각 클래스는 직계 서브 클래스에 대한 약한 참조의 리스트를 유지합니다. 이 메서드는 아직 살아있는 모든 참조의 리스트를 돌려줍니다. 예:

>>> int.__subclasses__()
[<class 'bool'>]

Integer string conversion length limitation

CPython has a global limit for converting between int and str to mitigate denial of service attacks. This limit only applies to decimal or other non-power-of-two number bases. Hexadecimal, octal, and binary conversions are unlimited. The limit can be configured.

The int type in CPython is an arbitrary length number stored in binary form (commonly known as a “bignum”). There exists no algorithm that can convert a string to a binary integer or a binary integer to a string in linear time, unless the base is a power of 2. Even the best known algorithms for base 10 have sub-quadratic complexity. Converting a large value such as int('1' * 500_000) can take over a second on a fast CPU.

Limiting conversion size offers a practical way to avoid CVE-2020-10735 [https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2020-10735].

The limit is applied to the number of digit characters in the input or output string when a non-linear conversion algorithm would be involved. Underscores and the sign are not counted towards the limit.

When an operation would exceed the limit, a ValueError is raised:

>>> import sys
>>> sys.set_int_max_str_digits(4300)  # Illustrative, this is the default.
>>> _ = int('2' * 5432)
Traceback (most recent call last):
...
ValueError: Exceeds the limit (4300) for integer string conversion: value has 5432 digits; use sys.set_int_max_str_digits() to increase the limit.
>>> i = int('2' * 4300)
>>> len(str(i))
4300
>>> i_squared = i*i
>>> len(str(i_squared))
Traceback (most recent call last):
...
ValueError: Exceeds the limit (4300) for integer string conversion: value has 8599 digits; use sys.set_int_max_str_digits() to increase the limit.
>>> len(hex(i_squared))
7144
>>> assert int(hex(i_squared), base=16) == i*i  # Hexadecimal is unlimited.

The default limit is 4300 digits as provided in sys.int_info.default_max_str_digits. The lowest limit that can be configured is 640 digits as provided in sys.int_info.str_digits_check_threshold.

Verification:

>>> import sys
>>> assert sys.int_info.default_max_str_digits == 4300, sys.int_info
>>> assert sys.int_info.str_digits_check_threshold == 640, sys.int_info
>>> msg = int('578966293710682886880994035146873798396722250538762761564'
...           '9252925514383915483333812743580549779436104706260696366600'
...           '571186405732').to_bytes(53, 'big')
...

버전 3.7.14에 추가.

Affected APIs

The limitation only applies to potentially slow conversions between int and str or bytes:

int(string) with default base 10.

int(string, base) for all bases that are not a power of 2.

str(integer).

repr(integer).

any other string conversion to base 10, for example f"{integer}", "{}".format(integer), or b"%d" % integer.

The limitations do not apply to functions with a linear algorithm:

int(string, base) with base 2, 4, 8, 16, or 32.

int.from_bytes() and int.to_bytes().

hex(), oct(), bin().

포맷 명세 미니 언어 for hex, octal, and binary numbers.

str to float.

str to decimal.Decimal.

Configuring the limit

Before Python starts up you can use an environment variable or an interpreter command line flag to configure the limit:

PYTHONINTMAXSTRDIGITS, e.g. PYTHONINTMAXSTRDIGITS=640 python3 to set the limit to 640 or PYTHONINTMAXSTRDIGITS=0 python3 to disable the limitation.

-X int_max_str_digits, e.g. python3 -X int_max_str_digits=640

sys.flags.int_max_str_digits contains the value of PYTHONINTMAXSTRDIGITS or -X int_max_str_digits. If both the env var and the -X option are set, the -X option takes precedence. A value of -1 indicates that both were unset, thus a value of sys.int_info.default_max_str_digits was used during initialization.

From code, you can inspect the current limit and set a new one using these sys APIs:

sys.get_int_max_str_digits() and sys.set_int_max_str_digits() are a getter and setter for the interpreter-wide limit. Subinterpreters have their own limit.

Information about the default and minimum can be found in sys.int_info:

sys.int_info.default_max_str_digits is the compiled-in default limit.

sys.int_info.str_digits_check_threshold is the lowest accepted value for the limit (other than 0 which disables it).

버전 3.7.14에 추가.

조심

Setting a low limit can lead to problems. While rare, code exists that contains integer constants in decimal in their source that exceed the minimum threshold. A consequence of setting the limit is that Python source code containing decimal integer literals longer than the limit will encounter an error during parsing, usually at startup time or import time or even at installation time - anytime an up to date .pyc does not already exist for the code. A workaround for source that contains such large constants is to convert them to 0x hexadecimal form as it has no limit.

Test your application thoroughly if you use a low limit. Ensure your tests run with the limit set early via the environment or flag so that it applies during startup and even during any installation step that may invoke Python to precompile .py sources to .pyc files.

Recommended configuration

The default sys.int_info.default_max_str_digits is expected to be reasonable for most applications. If your application requires a different limit, set it from your main entry point using Python version agnostic code as these APIs were added in security patch releases in versions before 3.11.

Example:

>>> import sys
>>> if hasattr(sys, "set_int_max_str_digits"):
...     upper_bound = 68000
...     lower_bound = 4004
...     current_limit = sys.get_int_max_str_digits()
...     if current_limit == 0 or current_limit > upper_bound:
...         sys.set_int_max_str_digits(upper_bound)
...     elif current_limit < lower_bound:
...         sys.set_int_max_str_digits(lower_bound)

If you need to disable it entirely, set it to 0.

각주

1

이 특수 메서드에 대한 추가 정보는 파이썬 레퍼런스 설명서(기본적인 커스터마이제이션)에서 찾을 수 있습니다.

2

결과적으로, 리스트 [1, 2] 는 [1.0, 2.0] 과 같다고 취급되고, 튜플도 마찬가지입니다.

3

파서가 피연산자 유형을 알 수 없으므로 그럴 수밖에 없습니다.

4(1,2,3,4)

케이스 문자는 일반 범주 속성이 “Lu” (Letter, 대문자), “Ll” (Letter, 소문자), “Lt” (Letter, 제목 문자) 중 한 가지인 경우입니다.

5(1,2)

그래서, 튜플만을 포매팅하려면 포맷할 튜플 하나만을 포함하는 1-튜플을 제공해야 합니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

|

내장 예외

파이썬에서, 모든 예외는 BaseException 에서 파생된 클래스의 인스턴스여야 합니다. 특정 클래스를 언급하는 except 절을 갖는 try 문에서, 그 절은 그 클래스에서 파생된 모든 예외 클래스를 처리합니다 (하지만 그것 이 계승하는 예외 클래스는 처리하지 않습니다). 서브 클래싱을 통해 관련되지 않은 두 개의 예외 클래스는 같은 이름을 갖는다 할지라도 결코 등등하게 취급되지 않습니다.

아래 나열된 내장 예외는 인터프리터나 내장 함수에 의해 생성될 수 있습니다. 따로 언급된 경우를 제외하고는, 에러의 자세한 원인을 나타내는 “연관된 값”을 갖습니다. 이것은 여러 항목의 정보 (예, 에러 코드와 그 코드를 설명하는 문자열)를 담은 문자열이나 튜플 일 수 있습니다. 연관된 값은 보통 예외 클래스의 생성자에 인자로 전달됩니다.

사용자 코드는 내장 예외를 일으킬 수 있습니다. 이것은 예외 처리기를 검사하거나 인터프리터가 같은 예외를 발생시키는 상황과 “같은” 에러 조건을 보고하는 데 사용할 수 있습니다. 그러나 사용자 코드가 부적절한 에러를 발생시키는 것을 막을 방법이 없음을 유의하십시오.

내장 예외 클래스는 새 예외를 정의하기 위해 서브 클래싱 될 수 있습니다. BaseException 이 아니라 Exception 클래스 나 그 서브 클래스 중 하나에서 새로운 예외를 파생시킬 것을 권장합니다. 예외 정의에 대한 더 많은 정보는 파이썬 자습서의 사용자 정의 예외 에 있습니다.

except 또는 finally 절에서 예외를 일으킬 때 (또는 다시 일으킬 때), __context__ 는 자동으로 마지막으로 잡힌 예외로 설정됩니다; 이 새 예외가 처리되지 않으면, 결국 표시되는 트레이스백은 원래 예외와 최종 예외를 포함합니다.

(현재 처리 중인 예외를 다시 발생시키기 위해 raise만 사용하는 대신) 새 예외를 일으킬 때, 묵시적인 예외 컨텍스트는 암시적인 예외 상황은 명시적 원인으로 보충될 수 있는데, raise와 from을 사용합니다:

raise new_exc from original_exc

from 다음의 표현식은 예외이거나 None 이어야 합니다. 이 표현식을 새로 일으키는 예외의 __cause__ 로 설정합니다. __cause__ 를 설정하면, 묵시적으로 __suppress_context__ 를 True 로 설정합니다. 그래서, raise new_exc from None 을 사용하면 표시의 목적상 이전 예외를 새로운 것으로 대체 하는 효과를 주면서 (예를 들어 KeyError 를 AttributeError 로), 디버깅할 때 검사할 수 있도록 이전의 예외를 __context__ 에 남겨둡니다.

기본 트레이스백 표시 코드는 예외 자체의 트레이스백 뿐만 아니라 이러한 연결된 예외를 보여줍니다. __cause__ 에 명시적으로 연결된 예외는 있으면 항상 표시됩니다. __context__ 에 묵시적으로 연결된 예외는 __cause__ 가 None 이고 __suppress_context__ 가 거짓인 경우에만 표시됩니다.

두 경우 모두, 예외 자신은 항상 연결된 예외 뒤에 표시되어서, 트레이스백의 마지막 줄은 항상 마지막에 발생한 예외를 보여줍니다.

베이스 클래스

다음 예외는 주로 다른 예외의 베이스 클래스로 사용됩니다.

exception BaseException

모든 내장 예외의 베이스 클래스입니다. 사용자 정의 클래스에 의해 직접 상속되는 것이 아닙니다 (그런 목적으로는 Exception을 사용하세요). 이 클래스의 인스턴스에 대해 str() 이 호출되면, 인스턴스로 전달된 인자(들)의 표현을 돌려줍니다. 인자가 없는 경우는 빈 문자열을 돌려줍니다.

args

예외 생성자에 주어진 인자들의 튜플. 일부 내장 예외(예, OSError)는 특정 수의 인자를 기대하고 이 튜플의 요소에 특별한 의미를 할당하는 반면, 다른 것들은 보통 오류 메시지를 제공하는 단일 문자열로만 호출됩니다.

with_traceback(tb)

이 메서드는 tb 를 예외의 새 트레이스백으로 설정하고 예외 객체를 돌려줍니다. 일반적으로 다음과 같은 예외 처리 코드에서 사용됩니다:

try:
    ...
except SomeException:
    tb = sys.exc_info()[2]
    raise OtherException(...).with_traceback(tb)

exception Exception

모든 시스템 종료 외의 내장 예외는 이 클래스 파생됩니다. 모든 사용자 정의 예외도 이 클래스에서 파생되어야 합니다.

exception ArithmeticError

다양한 산술 에러가 일으키는 내장 예외들의 베이스 클래스: OverflowError, ZeroDivisionError, FloatingPointError.

exception BufferError

버퍼 관련 연산을 수행할 수 없을 때 발생합니다.

exception LookupError

매핑 또는 시퀀스에 사용된 키 나 인덱스가 잘못되었을 때 발생하는 예외의 베이스 클래스: IndexError, KeyError. codecs.lookup() 은 이 예외를 직접 일으킬 수 있습니다.

구체적인 예외

다음 예외는 일반적으로 직접 일으키는데 사용하는 예외입니다.

exception AssertionError

assert 문이 실패할 때 발생합니다.

exception AttributeError

어트리뷰트 참조(어트리뷰트 참조를 보세요)나 대입이 실패할 때 발생합니다. (객체가 어트리뷰트 참조나 어트리뷰트 대입을 아예 지원하지 않으면 TypeError 가 발생합니다.)

exception EOFError

input() 함수가 데이터를 읽지 못한 상태에서 EOF (end-of-file) 조건을 만날 때 발생합니다. (주의하세요: io.IOBase.read() 와 io.IOBase.readline() 메서드는 EOF를 만날 때 빈 문자열을 돌려줍니다.)

exception FloatingPointError

현재 사용되지 않습니다.

exception GeneratorExit

제너레이터 또는 코루틴 이 닫힐 때 발생합니다; generator.close() 와 coroutine.close() 를 보십시오. 기술적으로 에러가 아니므로 Exception 대신에 BaseException 을 직접 계승합니다.

exception ImportError

import 문이 모듈을 로드하는 데 문제가 있을 때 발생합니다. 또한 from ... import 에서 임포트 하려는 이름을 찾을 수 없을 때도 발생합니다.

name과 path 어트리뷰트는 생성자에 키워드 전용 인자를 사용하여 설정할 수 있습니다. 설정된 경우, 각각 임포트하려고 시도한 모듈의 이름과 예외를 유발한 파일의 경로를 나타냅니다.

버전 3.3에서 변경: name과 path 어트리뷰트를 추가했습니다.

exception ModuleNotFoundError

ImportError 의 서브 클래스인데, 모듈을 찾을 수 없을 때 import 가 일으킵니다. sys.modules 에서 None 이 발견될 때도 발생합니다.

버전 3.6에 추가.

exception IndexError

시퀀스 인덱스가 범위를 벗어날 때 발생합니다. (슬라이스 인덱스는 허용된 범위 내에 들어가도록 자동으로 잘립니다; 인덱스가 정수가 아니면 TypeError 가 발생합니다.)

exception KeyError

매핑 (딕셔너리) 키가 기존 키 집합에서 발견되지 않을 때 발생합니다.

exception KeyboardInterrupt

사용자가 인터럽트 키(일반적으로 Control-C 또는 Delete)를 누를 때 발생합니다. 실행 중에 인터럽트 검사가 정기적으로 수행됩니다. Exception을 잡는 코드에 의해 우연히 잡혀서, 인터프리터가 종료하는 것을 막지 못하도록 BaseException 를 계승합니다.

exception MemoryError

작업에 메모리가 부족하지만, 상황이 여전히 (일부 객체를 삭제해서) 복구될 수 있는 경우 발생합니다. 연관된 값은 어떤 종류의 (내부) 연산이 메모리를 다 써 버렸는지를 나타내는 문자열입니다. 하부 메모리 관리 아키텍처(C의 malloc() 함수)때문에, 인터프리터가 항상 이 상황을 완벽하게 복구할 수 있는 것은 아닙니다; 그런데도 통제를 벗어난 프로그램이 원인인 경우를 위해, 스택 트레이스백을 인쇄할 수 있도록 예외를 일으킵니다.

exception NameError

지역 또는 전역 이름을 찾을 수 없을 때 발생합니다. 이는 정규화되지 않은 이름에만 적용됩니다. 연관된 값은 찾을 수 없는 이름을 포함하는 에러 메시지입니다.

exception NotImplementedError

이 예외는 RuntimeError 에서 파생됩니다. 사용자 정의 베이스 클래스에서, 파생 클래스가 재정의하도록 요구하는 추상 메서드나, 클래스가 개발되는 도중에 실제 구현이 추가될 필요가 있음을 나타낼 때 이 예외를 발생시켜야 합니다.

참고

연산자 나 메서드가 아예 지원되지 않는다는 것을 나타내는 데 사용해서는 안 됩니다 – 그 경우는 연산자 / 메서드를 정의하지 않거나, 서브 클래스면 None 으로 설정하십시오.

참고

NotImplementedError 와 NotImplemented 는 비슷한 이름과 목적이 있습니다만, 바꿔쓸 수 없습니다. 언제 사용하는지에 대한 자세한 내용은 NotImplemented 를 참조하세요.

exception OSError([arg])

exception OSError(errno, strerror[, filename[, winerror[, filename2]]])

이 예외는 시스템 함수가 시스템 관련 에러를 돌려줄 때 발생하는데, “파일을 찾을 수 없습니다(file not found)” 나 “디스크가 꽉 찼습니다(disk full)” 와 같은 (잘못된 인자형이나 다른 부수적인 에러가 아닌) 입출력 실패를 포함합니다.

생성자의 두 번째 형식은 아래에 설명된 해당 어트리뷰트를 설정합니다. 어트리뷰트를 지정하지 않으면 기본적으로 None 이 됩니다. 이전 버전과의 호환성을 위해, 세 개의 인자가 전달되면, args 어트리뷰트는 처음 두 생성자 인자의 2-튜플만 포함합니다.

아래의 OS 예외 에서 설명하는 것처럼, 생성자는 종종 OSError 의 서브 클래스를 돌려줍니다. 구체적인 서브 클래스는 최종 errno 값에 따라 다릅니다. 이 동작은 OSError 를 직접 혹은 별칭을 통해 생성할 때만 일어나고, 서브클래싱할 때는 상속되지 않습니다.

errno

C 변수 errno 로부터 온 숫자 에러 코드.

winerror

윈도우에서, 네이티브 윈도우 에러 코드를 제공합니다. errno 어트리뷰트는 이 네이티브 에러 코드를 POSIX 코드로 대략 변환한 것입니다.

윈도우에서, winerror 생성자 인자가 정수인 경우, errno 어트리뷰트는 윈도우 에러 코드에서 결정되며 errno 인자는 무시됩니다. 다른 플랫폼에서는 winerror 인자가 무시되고 winerror 어트리뷰트가 없습니다.

strerror

운영 체제에서 제공하는 해당 에러 메시지. POSIX에서는 C 함수 perror() 로, 윈도우에서는 FormatMessage() 로 포맷합니다.

filename

filename2

(open() 또는 os.unlink() 와 같은) 파일 시스템 경로와 관련된 예외의 경우, filename 은 함수에 전달 된 파일 이름입니다. (os.rename()처럼) 두 개의 파일 시스템 경로를 수반하는 함수의 경우, filename2 는 두 번째 파일 이름에 해당합니다.

버전 3.3에서 변경: EnvironmentError, IOError, WindowsError, socket.error, select.error, mmap.error 가 OSError 로 병합되었고, 생성자는 서브 클래스를 반환할 수 있습니다.

버전 3.4에서 변경: filename 속성은 이제 파일 시스템 인코딩으로 인코딩되거나 디코딩된 이름 대신 함수에 전달 된 원래 파일 이름입니다. 또한 filename2 생성자 인자 및 어트리뷰트가 추가되었습니다.

exception OverflowError

산술 연산의 결과가 너무 커서 표현할 수 없을 때 발생합니다. 정수에서는 발생하지 않습니다 (포기하기보다는 MemoryError 를 일으키게 될 겁니다). 그러나, 역사적인 이유로, 때로 OverflowError는 요구되는 범위를 벗어난 정수의 경우도 발생합니다. C에서 부동 소수점 예외 처리의 표준화가 부족하므로, 대부분의 부동 소수점 연산은 검사되지 않습니다.

exception RecursionError

이 예외는 RuntimeError 에서 파생됩니다. 인터프리터가 최대 재귀 깊이(sys.getrecursionlimit() 참조)가 초과하였음을 감지할 때 발생합니다.

버전 3.5에 추가: 이전에는 평범한 RuntimeError 가 발생했습니다.

exception ReferenceError

이 예외는 weakref.proxy() 함수가 만든 약한 참조 프락시가 이미 가비지 수집된 참조 대상의 어트리뷰트를 액세스하는 데 사용될 때 발생합니다. 약한 참조에 대한 더 자세한 정보는 weakref 모듈을 보십시오.

exception RuntimeError

다른 범주에 속하지 않는 에러가 감지될 때 발생합니다. 연관된 값은 정확히 무엇이 잘못되었는지를 나타내는 문자열입니다.

exception StopIteration

이터레이터에 의해 생성된 항목이 더 없다는 것을 알려주기 위해, 내장 함수 next()와 이터레이터의 __next__() 메서드가 일으킵니다.

예외 객체는 value라는 하나의 어트리뷰트를 가지고 있습니다. 이 어트리뷰트는 예외를 생성할 때 인자로 주어지며, 기본값은 None 입니다.

제너레이터 나 코루틴 함수가 복귀할 때, 새 StopIteration 인스턴스를 발생시키고, 함수가 돌려주는 값을 예외 생성자의 value 매개변수로 사용합니다.

제너레이터 코드가 직간접적으로 StopIteration 를 일으키면, RuntimeError 로 변환됩니다 (StopIteration 은 새 예외의 원인(__cause__)으로 남겨둡니다).

버전 3.3에서 변경: value 어트리뷰트와 제너레이터 함수가 이 값을 돌려주는 기능을 추가했습니다.

버전 3.5에서 변경: from __future__ import generator_stop 를 통한 RuntimeError 변환을 도입했습니다. PEP 479 [https://www.python.org/dev/peps/pep-0479]를 참조하세요.

버전 3.7에서 변경: 기본적으로 모든 코드에서 PEP 479 [https://www.python.org/dev/peps/pep-0479]를 활성화합니다: 제너레이터에서 발생한 StopIteration 에러는 RuntimeError 로 변환됩니다.

exception StopAsyncIteration

반드시 비동기 이터레이터 객체의 __anext__() 메서드가 이터레이션을 멈추고자 할 때 발생시켜야 합니다.

버전 3.5에 추가.

exception SyntaxError

파서가 문법 오류를 만날 때 발생합니다. import 문에서, 내장 함수 exec() 나 eval() 호출에서, 초기 스크립트나 (대화형으로) 표준 입력을 읽을 때 발생할 수 있습니다.

세부 사항을 쉽게 확인할 수 있도록, 이 클래스의 인스턴스에는 filename, lineno, offset 및 text 어트리뷰트가 있습니다. 예외 인스턴스의 str()은 메시지만 돌려줍니다.

exception IndentationError

잘못된 들여쓰기와 관련된 문법 오류의 베이스 클래스입니다. SyntaxError 의 서브 클래스입니다.

exception TabError

들여쓰기가 일관성없는 탭과 스페이스 사용을 포함하는 경우 발생합니다. IndentationError 의 서브 클래스입니다.

exception SystemError

인터프리터가 내부 에러를 발견했지만, 모든 희망을 포기할 만큼 상황이 심각해 보이지는 않을 때 발생합니다. 연관된 값은 무엇이 잘못되었는지 (저수준의 용어로) 나타내는 문자열입니다.

이것을 파이썬 인터프리터의 저자 또는 관리자에게 알려야 합니다. 파이썬 인터프리터의 버전 (sys.version; 대화식 파이썬 세션의 시작 부분에도 출력됩니다), 정확한 에러 메시지 (예외의 연관된 값) 그리고 가능하다면 에러를 일으킨 프로그램의 소스를 제공해 주십시오.

exception SystemExit

이 예외는 sys.exit() 함수가 일으킵니다. Exception을 잡는 코드에 의해 우연히 잡히지 않도록, Exception 대신에 BaseException 을 상속합니다. 이렇게 하면 예외가 올바르게 전파되어 인터프리터가 종료됩니다. 처리되지 않으면, 파이썬 인터프리터가 종료됩니다; 스택 트레이스백은 인쇄되지 않습니다. 생성자는 sys.exit() 에 전달된 것과 같은 선택적 인자를 받아들입니다. 값이 정수이면 시스템 종료 상태를 지정합니다 (C의 exit() 함수에 전달됩니다); None 이면 종료 상태는 0입니다; 다른 형(가령 문자열)이면 객체의 값이 인쇄되고 종료 상태는 1입니다.

sys.exit() 에 대한 호출은 예외로 변환되어 뒷정리 처리기 (try 문의 finally 절) 가 실행될 수 있도록 합니다. 그래서 디버거는 제어권을 잃을 위험 없이 스크립트를 실행할 수 있습니다. 즉시 종료가 절대적으로 필요한 경우에는 os._exit() 함수를 사용할 수 있습니다 (예를 들어, os.fork() 호출 후의 자식 프로세스에서).

code

생성자에 전달되는 종료 상태 또는 에러 메시지입니다. (기본값은 None 입니다.)

exception TypeError

연산이나 함수가 부적절한 형의 객체에 적용될 때 발생합니다. 연관된 값은 형 불일치에 대한 세부 정보를 제공하는 문자열입니다.

이 예외는 객체에 시도된 연산이 지원되지 않으며 그럴 의도도 없음을 나타내기 위해 사용자 코드가 발생시킬 수 있습니다. 만약 객체가 주어진 연산을 지원할 의사는 있지만, 아직 구현을 제공하지 않는 경우라면, NotImplementedError 를 발생시키는 것이 적합합니다.

잘못된 형의 인자를 전달하면 (가령 int 를 기대하는데 list를 전달하기), TypeError 를 일으켜야 합니다. 하지만 잘못된 값을 갖는 인자를 전달하면 (가령 범위를 넘어서는 숫자) ValueError 를 일으켜야 합니다.

exception UnboundLocalError

함수 나 메서드에서 지역 변수를 참조하지만, 해당 변수에 값이 연결되지 않으면 발생합니다. 이것은 NameError 의 서브 클래스입니다.

exception UnicodeError

유니코드 관련 인코딩 또는 디코딩 에러가 일어날 때 발생합니다. ValueError 의 서브 클래스입니다.

UnicodeError 는 인코딩이나 디코딩 에러를 설명하는 어트리뷰트를 가지고 있습니다. 예를 들어, err.object[err.start:err.end] 는 코덱이 실패한 잘못된 입력을 제공합니다.

encoding

에러를 발생시킨 인코딩의 이름입니다.

reason

구체적인 코덱 오류를 설명하는 문자열입니다.

object

코덱이 인코딩 또는 디코딩하려고 시도한 객체입니다.

start

object 에 있는 잘못된 데이터의 최초 인덱스입니다.

end

object 에 있는 마지막으로 잘못된 데이터의 바로 다음 인덱스입니다.

exception UnicodeEncodeError

인코딩 중에 유니코드 관련 에러가 일어나면 발생합니다. UnicodeError 의 서브 클래스입니다.

exception UnicodeDecodeError

디코딩 중에 유니코드 관련 에러가 일어나면 발생합니다. UnicodeError 의 서브 클래스입니다.

exception UnicodeTranslateError

번역 중에 유니코드 관련 에러가 일어나면 발생합니다. UnicodeError 의 서브 클래스입니다.

exception ValueError

연산이나 함수가 올바른 형이지만 부적절한 값을 가진 인자를 받았고, 상황이 IndexError 처럼 더 구체적인 예외로 설명되지 않는 경우 발생합니다.

exception ZeroDivisionError

나누기 또는 모듈로 연산의 두 번째 인자가 0일 때 발생합니다. 연관된 값은 피연산자의 형과 연산을 나타내는 문자열입니다.

다음 예외는 이전 버전과의 호환성을 위해 유지됩니다; 파이썬 3.3부터는 OSError 의 별칭입니다.

exception EnvironmentError

exception IOError

exception WindowsError

윈도우에서만 사용할 수 있습니다.

OS 예외

다음의 예외는 OSError 의 서브 클래스이며, 시스템 에러 코드에 따라 발생합니다.

exception BlockingIOError

비 블록 동작으로 설정된 객체(가령 소켓)에 블록이 필요한 연산이 수행되면 발생합니다. errno EAGAIN, EALREADY, EWOULDBLOCK, EINPROGRESS 에 해당합니다.

OSError 의 것 외에도, BlockingIOError 는 어트리뷰트를 하나 더 가질 수 있습니다:

characters_written

블록 되기 전에 스트림에 쓴 문자 수를 포함하는 정수. 이 어트리뷰트는 io 모듈에서 버퍼링 된 입출력 클래스를 사용할 때 쓸 수 있습니다.

exception ChildProcessError

자식 프로세스에 대한 작업이 실패할 때 발생합니다. errno ECHILD 에 해당합니다.

exception ConnectionError

연결 관련 문제에 대한 베이스 클래스입니다.

서브 클래스는 BrokenPipeError, ConnectionAbortedError, ConnectionRefusedError 및 ConnectionResetError 입니다.

exception BrokenPipeError

ConnectionError 의 서브 클래스로서, 다른 쪽 끝이 닫힌 파이프에 쓰려고 하거나, 쓰기가 종료된 소켓에 쓰려고 할 때 발생합니다. errno EPIPE 와 ESHUTDOWN 에 해당합니다.

exception ConnectionAbortedError

ConnectionError 의 서브 클래스로서, 연결 시도가 상대방에 의해 중단(abort)될 때 발생합니다. errno ECONNABORTED 에 해당합니다.

exception ConnectionRefusedError

ConnectionError 의 서브 클래스로서, 연결 시도가 상대방에 의해 거부(refuse)될 때 발생합니다. errno ECONNREFUSED 에 해당합니다.

exception ConnectionResetError

ConnectionError 의 서브 클래스로서, 연결이 상대방에 의해 강제 종료(reset)될 때 발생합니다. errno ECONNRESET 에 해당합니다.

exception FileExistsError

이미 존재하는 파일이나 디렉터리를 만들려고 할 때 발생합니다. errno EEXIST 에 해당합니다.

exception FileNotFoundError

파일이나 디렉터리가 요청되었지만 존재하지 않을 때 발생합니다. errno ENOENT 에 해당합니다.

exception InterruptedError

시스템 호출이 들어오는 시그널에 의해 중단될 때 발생합니다. errno EINTR 에 해당합니다.

버전 3.5에서 변경: 이제 파이썬은 시스템 호출이 시그널에 의해 중단될 때, 시그널 처리기가 예외를 일으키는 경우를 제외하고 (이유는 PEP 475 [https://www.python.org/dev/peps/pep-0475] 를 참조하세요), InterruptedError 를 일으키는 대신 시스템 호출을 재시도합니다.

exception IsADirectoryError

디렉터리에 파일 연산(가령 os.remove())이 요청되었을 때 발생합니다. errno EISDIR 에 해당합니다.

exception NotADirectoryError

디렉터리가 아닌 것에 디렉터리 연산(가령 os.listdir())이 요청되었을 때 발생합니다. errno ENOTDIR 에 해당합니다.

exception PermissionError

적절한 접근권 (가령 파일 시스템 권한) 없이 연산을 실행하려고 할 때 발생합니다. errno EACCES 와 EPERM 에 해당합니다.

exception ProcessLookupError

주어진 프로세스가 존재하지 않을 때 발생합니다. errno ESRCH 에 해당합니다.

exception TimeoutError

시스템 함수가 시스템 수준에서 시간 초과 될 때 발생합니다. errno ETIMEDOUT 에 해당합니다.

버전 3.3에 추가: 위의 모든 OSError 서브 클래스가 추가되었습니다.

더 보기

PEP 3151 [https://www.python.org/dev/peps/pep-3151] - OS 및 IO 예외 계층 구조 재작업

경고

다음 예외는 경고 범주로 사용됩니다; 자세한 정보는 Warning Categories 설명서를 보십시오.

exception Warning

경고 범주의 베이스 클래스입니다.

exception UserWarning

사용자 코드에 의해 만들어지는 경고의 베이스 클래스입니다.

exception DeprecationWarning

폐지된 기능에 대한 경고의 베이스 클래스인데, 그 경고가 다른 파이썬 개발자를 대상으로 하는 경우입니다.

exception PendingDeprecationWarning

더는 사용되지 않고 장래에 폐지될 예정이지만, 지금 당장 폐지되지는 않은 기능에 관한 경고의 베이스 클래스입니다.

앞으로 있을 수도 있는 폐지에 관한 경고는 일반적이지 않기 때문에, 이 클래스는 거의 사용되지 않습니다. 이미 활성화된 폐지에는 DeprecationWarning을 선호합니다.

exception SyntaxWarning

모호한 문법에 대한 경고의 베이스 클래스입니다.

exception RuntimeWarning

모호한 실행 시간 동작에 대한 경고의 베이스 클래스입니다.

exception FutureWarning

폐지된 기능에 대한 경고의 베이스 클래스인데, 그 경고가 파이썬으로 작성된 응용 프로그램의 최종 사용자를 대상으로 하는 경우입니다.

exception ImportWarning

모듈 임포트에 있을 수 있는 실수에 대한 경고의 베이스 클래스입니다.

exception UnicodeWarning

유니코드와 관련된 경고의 베이스 클래스입니다.

exception BytesWarning

bytes 및 bytearray 와 관련된 경고의 베이스 클래스입니다.

exception ResourceWarning

자원 사용과 관련된 경고의 베이스 클래스입니다. 기본 경고 필터에 의해 무시됩니다.

버전 3.2에 추가.

예외 계층 구조

내장 예외의 클래스 계층 구조는 다음과 같습니다:

BaseException
 +-- SystemExit
 +-- KeyboardInterrupt
 +-- GeneratorExit
 +-- Exception
      +-- StopIteration
      +-- StopAsyncIteration
      +-- ArithmeticError
      |    +-- FloatingPointError
      |    +-- OverflowError
      |    +-- ZeroDivisionError
      +-- AssertionError
      +-- AttributeError
      +-- BufferError
      +-- EOFError
      +-- ImportError
      |    +-- ModuleNotFoundError
      +-- LookupError
      |    +-- IndexError
      |    +-- KeyError
      +-- MemoryError
      +-- NameError
      |    +-- UnboundLocalError
      +-- OSError
      |    +-- BlockingIOError
      |    +-- ChildProcessError
      |    +-- ConnectionError
      |    |    +-- BrokenPipeError
      |    |    +-- ConnectionAbortedError
      |    |    +-- ConnectionRefusedError
      |    |    +-- ConnectionResetError
      |    +-- FileExistsError
      |    +-- FileNotFoundError
      |    +-- InterruptedError
      |    +-- IsADirectoryError
      |    +-- NotADirectoryError
      |    +-- PermissionError
      |    +-- ProcessLookupError
      |    +-- TimeoutError
      +-- ReferenceError
      +-- RuntimeError
      |    +-- NotImplementedError
      |    +-- RecursionError
      +-- SyntaxError
      |    +-- IndentationError
      |         +-- TabError
      +-- SystemError
      +-- TypeError
      +-- ValueError
      |    +-- UnicodeError
      |         +-- UnicodeDecodeError
      |         +-- UnicodeEncodeError
      |         +-- UnicodeTranslateError
      +-- Warning
           +-- DeprecationWarning
           +-- PendingDeprecationWarning
           +-- RuntimeWarning
           +-- SyntaxWarning
           +-- UserWarning
           +-- FutureWarning
           +-- ImportWarning
           +-- UnicodeWarning
           +-- BytesWarning
           +-- ResourceWarning

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

|

텍스트 처리 서비스

이 장에서 설명하는 모듈은 광범위한 문자열 조작 연산과 기타 텍스트 처리 서비스를 제공합니다.

바이너리 데이터 서비스 에 기술되어 있는 codecs 모듈 또한 텍스트 처리와 밀접한 관련이 있습니다. 또한, 텍스트 시퀀스 형 — str 에 있는 파이썬의 내장 문자열형에 대한 설명서를 참조하십시오.

string — 일반적인 문자열 연산

문자열 상수

사용자 지정 문자열 포매팅

포맷 문자열 문법

포맷 명세 미니 언어

포맷 예제

템플릿 문자열

도움 함수

re — Regular expression operations

Regular Expression Syntax

Module Contents

Regular Expression Objects

Match Objects

Regular Expression Examples

Checking for a Pair

Simulating scanf()

search() vs. match()

Making a Phonebook

Text Munging

Finding all Adverbs

Finding all Adverbs and their Positions

Raw String Notation

Writing a Tokenizer

difflib — 델타 계산을 위한 도우미

SequenceMatcher 객체

SequenceMatcher 예제

Differ 객체

Differ 예제

difflib의 명령 줄 인터페이스

textwrap — 텍스트 래핑과 채우기

unicodedata — 유니코드 데이터베이스

stringprep — 인터넷 문자열 준비

readline — GNU readline 인터페이스

초기화 파일

줄 버퍼

히스토리 파일

히스토리 목록

시동 훅

완성

예제

rlcompleter — GNU readline을 위한 완성 함수

Completer 객체

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

텍스트 처리 서비스 »

|

string — 일반적인 문자열 연산

소스 코드: Lib/string.py [https://github.com/python/cpython/tree/3.7/Lib/string.py]

더 보기

텍스트 시퀀스 형 — str

문자열 메서드

문자열 상수

이 모듈에 정의된 상수는 다음과 같습니다:

string.ascii_letters

아래에 나오는 ascii_lowercase와 ascii_uppercase 상수를 이어붙인 것입니다. 이 값은 로케일에 의존적이지 않습니다.

string.ascii_lowercase

소문자 'abcdefghijklmnopqrstuvwxyz'. 이 값은 로케일에 의존적이지 않고 변경되지 않습니다.

string.ascii_uppercase

대문자 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'. 이 값은 로케일에 의존적이지 않고 변경되지 않습니다.

string.digits

문자열 '0123456789'.

string.hexdigits

문자열 '0123456789abcdefABCDEF'.

string.octdigits

문자열 '01234567'.

string.punctuation

C 로케일에서 구두점 문자로 간주하는 ASCII 문자의 문자열.

string.printable

인쇄 가능한 것으로 간주하는 ASCII 문자의 문자열. digits, ascii_letters, punctuation, whitespace 의 조합입니다.

string.whitespace

공백으로 간주하는 모든 ASCII 문자를 포함하는 문자열. 여기에는 스페이스, 탭, 줄 바꿈, 캐리지 리턴, 세로 탭 및 폼 피드 문자가 포함됩니다.

사용자 지정 문자열 포매팅

내장 문자열 클래스는 PEP 3101 [https://www.python.org/dev/peps/pep-3101] 에 설명된 format() 메서드를 통해 복잡한 변수 치환 및 값 포매팅을 수행할 수 있는 기능을 제공합니다. string 모듈의 Formatter 클래스는 내장 format() 메서드와 같은 구현을 사용하여 자신만의 문자열 포매팅 동작을 만들고 사용자 정의할 수 있게 합니다.

class string.Formatter

Formatter 클래스에는 다음과 같은 공개 메서드가 있습니다:

format(format_string, *args, **kwargs)

기본 API 메서드입니다. 포맷 문자열과 임의의 위치 및 키워드 인자의 집합을 받아들입니다. 이것은 vformat() 을 호출하는 래퍼일 뿐입니다.

버전 3.7에서 변경: 포맷 문자열 인자는 이제 위치 전용입니다.

vformat(format_string, args, kwargs)

이 함수는 실제 포맷 작업을 수행합니다. *args 와 **kwargs 문법을 사용하여 딕셔너리를 개별적인 인자로 언 패킹한 후 다시 패킹하는 대신 미리 정의된 인자 딕셔너리를 전달하고자 하는 경우를 위해 별도의 함수로 노출합니다. vformat() 은 포맷 문자열을 문자 데이터와 치환 필드로 분리하는 작업을 수행합니다. 아래에 설명된 다양한 메서드를 호출합니다.

이에 더해, Formatter 는 서브 클래스에 의해 대체될 목적으로 많은 메서드를 정의합니다:

parse(format_string)

format_string을 루핑하면서 튜플 (literal_text, field_name, format_spec, conversion) 의 이터러블을 반환합니다. 이것은 vformat() 이 문자열을 리터럴 텍스트와 치환 필드로 나누는 데 사용합니다.

튜플의 값은 개념적으로 리터럴 텍스트와 그 뒤를 따르는 하나의 치환 필드의 범위를 나타냅니다. 리터럴 텍스트가 없는 경우 (두 개의 치환 필드가 연속적으로 나타나는 경우 발생할 수 있습니다), literal_text 는 길이가 0인 문자열입니다. 치환 필드가 없는 경우 field_name, format_spec 및 conversion 값은 None 입니다.

get_field(field_name, args, kwargs)

parse() 가 반환한 field_name 을 (위를 보세요) 포맷될 객체로 변환합니다. 튜플 (obj, used_key) 를 반환합니다. 기본 버전은 “0[name]” 이나 “label.title”과 같이 PEP 3101 [https://www.python.org/dev/peps/pep-3101] 에 정의된 형식의 문자열을 받아들입니다. args 와 kwargs 는 vformat() 에 전달된 것과 같습니다. 반환 값 used_key 는 get_value() 의 key 매개 변수와 같은 의미가 있습니다.

get_value(key, args, kwargs)

지정된 필드의 값을 가져옵니다. key 인자는 정수 또는 문자열입니다. 정수의 경우, args 에 있는 위치 인자의 인덱스를 나타냅니다; 문자열인 경우, kwargs 에 있는 이름있는 인자를 나타냅니다.

args 매개 변수는 vformat() 의 위치 인자 목록으로 설정되고, kwargs 매개 변수는 키워드 인자 딕셔너리로 설정됩니다.

복합 필드 이름의 경우, 이러한 함수는 필드 이름의 첫 번째 구성 요소에 대해서만 호출됩니다; 후속 구성 요소는 일반 어트리뷰트 및 인덱싱 연산을 통해 처리됩니다.

그래서 예를 들어, 필드 표현식 ‘0.name’ 은 get_value() 가 key 인자 0으로 호출되도록 합니다. name 어트리뷰트는 get_value() 가 반환한 후에 내장 getattr() 함수를 호출하여 조회합니다.

인덱스 또는 키워드가 존재하지 않는 항목을 참조하면, IndexError 나 KeyError 가 발생합니다.

check_unused_args(used_args, args, kwargs)

원하는 경우 사용하지 않는 인자를 검사하도록 구현합니다. 이 함수에 대한 인자는 포맷 문자열에서 참조되는 모든 인자 키의 집합과 (위치 인자의 경우 정수, 이름있는 인자의 경우 문자열), vformat 으로 전달된 args 와 kwargs 에 대한 참조입니다. 사용되지 않은 인자의 집합은 이 매개 변수들로 계산할 수 있습니다. check_unused_args() 는 검사가 실패할 경우 예외를 발생시킬 것으로 가정합니다.

format_field(value, format_spec)

format_field() 는 단순히 전역 format() 내장 함수를 호출합니다. 서브 클래스가 재정의할 수 있도록 메서드가 제공됩니다.

convert_field(value, conversion)

(get_field() 가 반환한) 값(value)을 (parse() 메서드가 반환하는 튜플에 있는 것과 같은) 주어진 변환 유형(conversion)으로 변환합니다. 기본 버전은 ‘s’ (str), ‘r’ (repr) 및 ‘a’ (ascii) 변환 유형을 인식합니다.

포맷 문자열 문법

str.format() 메서드와 Formatter 클래스는 포맷 문자열에 대해서 같은 문법을 공유합니다 (Formatter 의 경우, 서브 클래스는 그들 자신의 포맷 문자열 문법을 정의 할 수 있습니다). 문법은 포맷 문자열 리터럴 과 관련 있지만, 차이점이 있습니다.

포맷 문자열에는 중괄호 {} 로 둘러싸인 “치환 필드” 가 들어 있습니다. 중괄호 안에 포함되지 않은 것은 리터럴 텍스트로 간주하며 변경되지 않고 그대로 출력으로 복사됩니다. 리터럴 텍스트에 중괄호를 포함해야 하는 경우, 중복으로 이스케이프 할 수 있습니다: {{ 와 }}.

치환 필드의 문법은 다음과 같습니다:

replacement_field ::=  "{" [field_name] ["!" conversion] [":" format_spec] "}"
field_name        ::=  arg_name ("." attribute_name | "[" element_index "]")*
arg_name          ::=  [identifier | digit+]
attribute_name    ::=  identifier
element_index     ::=  digit+ | index_string
index_string      ::=  <any source character except "]"> +
conversion        ::=  "r" | "s" | "a"
format_spec       ::=  <described in the next section>

덜 형식적인 용어로, 치환 필드는 field_name 으로 시작할 수 있는데, 값이 포맷되어 출력에 치환 필드 대신 삽입될 객체를 지정합니다. field_name 다음에는 선택적으로 느낌표 '!' 가 앞에 오는 conversion 필드와 콜론 ':' 이 앞에 오는 format_spec 이 옵니다. 이 값은 치환 값에 대해 기본값이 아닌 포맷을 지정합니다.

포맷 명세 미니 언어 섹션을 참고하십시오.

field_name 자체는 숫자나 키워드인 arg_name 으로 시작합니다. 숫자면 위치 인자를 나타내고, 키워드면 이름이 있는 키워드 인자를 나타냅니다. 포맷 문자열의 숫자 arg_name이 0, 1, 2, … 순으로 나열되는 경우, (일부가 아니라) 전부 생략 할 수 있으며 숫자 0, 1, 2, …이 순서대로 자동 삽입됩니다. arg_name 이 따옴표로 분리되어 있지 않기 때문에, 포맷 문자열 내에서 임의의 딕셔너리 키(예를 들어, '10' 이나 ':-]')를 지정할 수 없습니다. arg_name 다음에는 제한 없는 개수의 인덱스나 어트리뷰트 표현식이 올 수 있습니다. '.name' 형태의 표현식은 getattr()을 사용하여 이름있는 어트리뷰트를 선택하는 반면, '[index]' 형태의 표현식은 __getitem__() 을 사용해서 인덱스 조회를 합니다.

버전 3.1에서 변경: 위치 인자 지정자는 str.format() 에서 생략 할 수 있습니다. 그래서, '{} {}'.format(a, b) 는 '{0} {1}'.format(a, b) 과 동등합니다.

버전 3.4에서 변경: 위치 인자 지정자는 Formatter에서 생략 할 수 있습니다.

몇 가지 간단한 포맷 문자열 예제:

"First, thou shalt count to {0}"  # References first positional argument
"Bring me a {}"                   # Implicitly references the first positional argument
"From {} to {}"                   # Same as "From {0} to {1}"
"My quest is {name}"              # References keyword argument 'name'
"Weight in tons {0.weight}"       # 'weight' attribute of first positional arg
"Units destroyed: {players[0]}"   # First element of keyword argument 'players'.

conversion 필드는 포매팅 전에 형 코어션을 일으킵니다. 보통은, 값을 포매팅하는 작업은 값 자체의 __format__() 메서드에 의해 수행됩니다. 그러나 어떤 경우에는 형 자신의 포매팅 정의를 무시하고 문자열로 포맷되도록 강제할 필요가 있습니다. __format__() 을 호출하기 전에 값을 문자열로 변환하면, 일반적인 포매팅 논리가 무시됩니다.

현재 세 가지 변환 플래그가 지원됩니다: '!s' 는 값에 str() 을 호출하고, '!r' 은 값에 repr() 을 호출하고, '!a' 는 값에 ascii() 를 호출합니다.

몇 가지 예:

"Harold's a clever {0!s}"        # Calls str() on the argument first
"Bring out the holy {name!r}"    # Calls repr() on the argument first
"More {!a}"                      # Calls ascii() on the argument first

format_spec 필드에는 값을 표시하는 방법에 대한 명세가 포함되어 있는데, 필드 너비, 정렬, 채움, 십진 정밀도 등이 포함됩니다. 각 값 형은 자체 “포매팅 미니 언어” 또는 format_spec 의 해석을 정의 할 수 있습니다.

대부분의 내장형은 다음 절에서 설명하는 공통 포매팅 미니 언어를 지원합니다.

A format_spec 필드는 그 안에 중첩된 치환 필드를 포함할 수도 있습니다. 이러한 중첩 된 치환 필드에는 필드 이름, 변환 플래그 및 포맷 명세가 포함될 수 있지만, 더 깊은 중첩은 허용되지 않습니다. format_spec 내의 치환 필드는 format_spec 문자열이 해석되기 전에 치환됩니다. 이렇게 해서 값의 포매팅을 동적으로 지정할 수 있게 합니다.

몇 가지 예제는 포맷 예제 섹션을 보십시오.

포맷 명세 미니 언어

“포맷 명세” 는 포맷 문자열에 포함된 치환 필드 내에서 개별 값의 표시 방법을 정의하는 데 사용됩니다 (포맷 문자열 문법 과 포맷 문자열 리터럴을 보세요). 이것들은 내장 format() 함수에 직접 전달될 수도 있습니다. 각 포맷 가능한 형은 포맷 명세를 해석하는 방법을 정의 할 수 있습니다.

대부분의 내장형은 포맷 명세에 대해 다음 옵션을 구현하지만, 일부 포맷 옵션은 숫자 형에서만 지원됩니다.

A general convention is that an empty format specification produces the same result as if you had called str() on the value. A non-empty format specification typically modifies the result.

표준 포맷 지정자 의 일반적인 형식은 다음과 같습니다:

format_spec     ::=  [[fill]align][sign][#][0][width][grouping_option][.precision][type]
fill            ::=  <any character>
align           ::=  "<" | ">" | "=" | "^"
sign            ::=  "+" | "-" | " "
width           ::=  digit+
grouping_option ::=  "_" | ","
precision       ::=  digit+
type            ::=  "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"

유효한 align 값이 지정되면, fill 문자가 앞에 나올 수 있는데 임의의 문자가 될 수 있고, 생략된 경우에는 스페이스가 기본값으로 사용됩니다. 포맷 문자열 리터럴 에서나 str.format() 메서드를 사용할 때는, 리터럴 중괄호(”{” 또는 “}”)를 fill 문자로 사용할 수 없습니다. 그러나, 중첩된 치환 필드로 중괄호를 삽입 할 수 있습니다. 이 제한은 format() 함수에는 영향을 미치지 않습니다.

다양한 정렬 옵션의 의미는 다음과 같습니다:

옵션

의미

'<'

사용 가능한 공간 내에서 필드가 왼쪽 정렬되도록 합니다 (대부분 객체에서 이것이 기본값입니다).

'>'

사용 가능한 공간 내에서 필드가 오른쪽 정렬되도록 합니다 (숫자에서 이것이 기본값입니다).

'='

채움이 부호 (있다면) 뒤에, 숫자 앞에 오도록 강제합니다. 이것은 ‘+000000120’ 형식으로 필드를 인쇄하는 데 사용됩니다. 이 정렬 옵션은 숫자 형에게만 유효합니다. 이것은 필드 너비 바로 앞에 ‘0’ 이 있으면 기본값이 됩니다.

'^'

사용 가능한 공간 내에서 필드를 가운데에 배치합니다.

최소 필드 너비가 정의되지 않으면, 필드 너비는 항상 필드를 채울 데이터와 같은 크기이므로, 정렬 옵션은 이 경우 의미가 없습니다.

sign 옵션은 숫자 형에게만 유효하며, 다음 중 하나일 수 있습니다:

옵션

의미

'+'

음수뿐만 아니라 양수에도 부호를 사용해야 함을 나타냅니다.

'-'

음수에 대해서만 부호를 사용해야 함을 나타냅니다 (이것이 기본 동작입니다).

스페이스

양수에는 선행 스페이스를 사용하고, 음수에는 마이너스 부호를 사용해야 함을 나타냅니다.

'#' 옵션은 변환에 “대안 형식” 이 사용되도록 만듭니다. 대안 형식은 형별로 다르게 정의됩니다. 이 옵션은 정수, 실수, 복소수와 Decimal 형에게만 유효합니다. 정수의 경우, 이진수, 8진수 또는 16진수 출력이 사용될 때, 이 옵션은 출력값에 각각 접두사 '0b', '0o' 또는 '0x' 를 추가합니다. 실수, 복소수 및 Decimal의 경우, 대안 형식은 변환 결과의 소수점 아래 숫자가 없어도 항상 소수점 문자가 포함되게 합니다. 보통은, 소수점 문자는 그 뒤에 숫자가 있는 경우에만 변환 결과에 나타납니다. 이에 더해, 'g' 및 'G' 변환의 경우 끝에 붙는 0이 결과에서 제거되지 않습니다.

',' 옵션은 천 단위 구분 기호에 쉼표를 사용하도록 알립니다. 로케일을 고려하는 구분자의 경우, 대신 'n' 정수 표시 유형을 사용하십시오.

버전 3.1에서 변경: ',' 옵션을 추가했습니다 (PEP 378 [https://www.python.org/dev/peps/pep-0378] 도 보세요).

'_' 옵션은 부동 소수점 표시 유형 및 정수 표시 유형 'd' 에 대해 천 단위 구분 기호에 밑줄을 사용하도록 알립니다. 정수 표시 유형 'b', 'o', 'x' 및 'X' 의 경우 밑줄이 4자리마다 삽입됩니다. 다른 표시 유형의 경우, 이 옵션을 지정하면 에러가 발생합니다.

버전 3.6에서 변경: '_' 옵션을 추가했습니다 (PEP 515 [https://www.python.org/dev/peps/pep-0515] 도 보세요).

width is a decimal integer defining the minimum total field width, including any prefixes, separators, and other formatting characters. If not specified, then the field width will be determined by the content.

명시적 정렬이 주어지지 않을 때, width 필드 앞에 '0' 문자를 붙이면 숫자 형에 대해 부호를 고려하는 0 채움을 사용할 수 있습니다. 이것은 '0' 의 fill 문자와 '=' 의 alignment 유형을 갖는 것과 동등합니다.

precision 는 'f' 및 'F' 로 포맷된 부동 소수점 값의 소수점 이하 또는 'g' 또는 'G' 로 포맷된 부동 소수점 값의 소수점 앞, 뒤로 표시할 숫자의 개수를 나타내는 십진수입니다. 숫자가 아닌 유형의 경우 필드는 최대 필드 크기를 나타냅니다 - 즉, 필드 내용에서 몇 개의 문자가 사용되는지 나타냅니다. 정숫값에는 precision 이 허용되지 않습니다.

마지막으로 type 은 데이터를 표시하는 방법을 결정합니다.

사용 가능한 문자열 표시 유형은 다음과 같습니다:

유형

의미

's'

문자열 포맷. 이것은 문자열의 기본 유형이고 생략될 수 있습니다.

없음

's' 와 같습니다.

사용 가능한 정수 표시 유형은 다음과 같습니다:

유형

의미

'b'

이진 형식. 이진법으로 숫자를 출력합니다.

'c'

문자. 인쇄하기 전에 정수를 해당 유니코드 문자로 변환합니다.

'd'

십진 정수. 십진법으로 숫자를 출력합니다.

'o'

8진 형식. 8진법으로 숫자를 출력합니다.

'x'

16진 형식. 9보다 큰 숫자의 경우 소문자를 사용하여 16진법으로 숫자를 출력합니다.

'X'

16진 형식. 9보다 큰 숫자의 경우 대문자를 사용하여 16진법으로 숫자를 출력합니다.

'n'

숫자. 이는 현재 로케일 설정을 사용하여 적절한 숫자 구분 문자를 삽입한다는 점을 제외하고는 'd' 와 같습니다.

없음

'd' 와 같습니다.

위의 표시 유형에 더해, 정수는 아래에 나열된 부동 소수점 표시 유형으로 포맷될 수 있습니다 ('n' 및 없음 제외). 그렇게 할 때, 포매팅 전에 정수를 부동 소수점 숫자로 변환하기 위해 float() 가 사용됩니다.

부동 소수점 및 Decimal 값에 사용할 수 있는 표시 유형은 다음과 같습니다:

유형

의미

'e'

지수 표기법. 지수를 나타내는 문자 ‘e’를 사용하여 과학 표기법으로 숫자를 인쇄합니다. 기본 정밀도는 6 입니다.

'E'

지수 표기법. 구분 문자로 대문자 ‘E’를 사용한다는 것을 제외하고 'e' 와 같습니다.

'f'

고정 소수점 표기법. 숫자를 고정 소수점 숫자로 표시합니다. 기본 정밀도는 6 입니다.

'F'

고정 소수점 표기법. 'f' 와 같지만, nan 을 NAN 으로, inf 를 INF 로 변환합니다.

'g'

범용 형식. 주어진 정밀도 p >= 1 에 대해, 숫자를 유효 숫자 p 로 자리 올림 한 다음, 결과를 크기에 따라 고정 소수점 형식이나 과학 표기법으로 포맷합니다.

The precise rules are as follows: suppose that the result formatted with presentation type 'e' and precision p-1 would have exponent exp. Then if -4 <= exp < p, the number is formatted with presentation type 'f' and precision p-1-exp. Otherwise, the number is formatted with presentation type 'e' and precision p-1. In both cases insignificant trailing zeros are removed from the significand, and the decimal point is also removed if there are no remaining digits following it, unless the '#' option is used.

양과 음의 무한대, 양과 음의 0, nans는 정밀도와 무관하게 각각 inf, -inf, 0, -0, nan 으로 포맷됩니다.

0 의 정밀도는 1 의 정밀도로 처리됩니다. 기본 정밀도는 6 입니다.

'G'

범용 형식. 숫자가 너무 커지면 'E' 로 전환하는 것을 제외하고 'g' 와 같습니다. 무한과 NaN 의 표현도 대문자로 바뀝니다.

'n'

숫자. 현재 로케일 설정을 사용하여 적절한 숫자 구분 문자를 삽입한다는 점을 제외하면 'g' 와 같습니다.

'%'

백분율. 숫자에 100을 곱해서 고정 ('f') 형식으로 표시한 다음 백분율 기호를 붙입니다.

없음

고정 소수점 표기법이 선택될 때, 소수점 이하로 적어도 하나의 자리가 있다는 점을 제외하면 'g' 와 비슷합니다. 기본 정밀도는 특정 값을 나타내는 데 필요한 만큼 높습니다. 전체적인 효과는 str() 의 출력을 다른 포맷 수정자에 의해 변경된 것처럼 만드는 것입니다.

포맷 예제

이 절은 str.format() 문법의 예와 예전 %-포매팅과의 비교를 포함합니다.

대부분은 문법이 예전의 %-포매팅과 유사하며, {} 가 추가되고 % 대신 및 : 이 사용됩니다. 예를 들어, '%03.2f' 는 '{:03.2f}' 로 번역될 수 있습니다.

새 포맷 문법은 다음 예제에 보이는 것과 같이 새롭고 다양한 옵션도 지원합니다.

위치로 인자 액세스:

>>> '{0}, {1}, {2}'.format('a', 'b', 'c')
'a, b, c'
>>> '{}, {}, {}'.format('a', 'b', 'c')  # 3.1+ only
'a, b, c'
>>> '{2}, {1}, {0}'.format('a', 'b', 'c')
'c, b, a'
>>> '{2}, {1}, {0}'.format(*'abc')      # unpacking argument sequence
'c, b, a'
>>> '{0}{1}{0}'.format('abra', 'cad')   # arguments' indices can be repeated
'abracadabra'

이름으로 인자 액세스:

>>> 'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W')
'Coordinates: 37.24N, -115.81W'
>>> coord = {'latitude': '37.24N', 'longitude': '-115.81W'}
>>> 'Coordinates: {latitude}, {longitude}'.format(**coord)
'Coordinates: 37.24N, -115.81W'

인자의 어트리뷰트 액세스:

>>> c = 3-5j
>>> ('The complex number {0} is formed from the real part {0.real} '
...  'and the imaginary part {0.imag}.').format(c)
'The complex number (3-5j) is formed from the real part 3.0 and the imaginary part -5.0.'
>>> class Point:
...     def __init__(self, x, y):
...         self.x, self.y = x, y
...     def __str__(self):
...         return 'Point({self.x}, {self.y})'.format(self=self)
...
>>> str(Point(4, 2))
'Point(4, 2)'

인자의 항목 액세스:

>>> coord = (3, 5)
>>> 'X: {0[0]};  Y: {0[1]}'.format(coord)
'X: 3;  Y: 5'

%s 과 %r 대체:

>>> "repr() shows quotes: {!r}; str() doesn't: {!s}".format('test1', 'test2')
"repr() shows quotes: 'test1'; str() doesn't: test2"

텍스트 정렬과 너비 지정:

>>> '{:<30}'.format('left aligned')
'left aligned                  '
>>> '{:>30}'.format('right aligned')
'                 right aligned'
>>> '{:^30}'.format('centered')
'           centered           '
>>> '{:*^30}'.format('centered')  # use '*' as a fill char
'***********centered***********'

%+f, %-f, % f 대체와 부호 지정:

>>> '{:+f}; {:+f}'.format(3.14, -3.14)  # show it always
'+3.140000; -3.140000'
>>> '{: f}; {: f}'.format(3.14, -3.14)  # show a space for positive numbers
' 3.140000; -3.140000'
>>> '{:-f}; {:-f}'.format(3.14, -3.14)  # show only the minus -- same as '{:f}; {:f}'
'3.140000; -3.140000'

%x, %o 대체와 다른 진법으로 값 변환:

>>> # format also supports binary numbers
>>> "int: {0:d};  hex: {0:x};  oct: {0:o};  bin: {0:b}".format(42)
'int: 42;  hex: 2a;  oct: 52;  bin: 101010'
>>> # with 0x, 0o, or 0b as prefix:
>>> "int: {0:d};  hex: {0:#x};  oct: {0:#o};  bin: {0:#b}".format(42)
'int: 42;  hex: 0x2a;  oct: 0o52;  bin: 0b101010'

쉼표를 천 단위 구분자로 사용:

>>> '{:,}'.format(1234567890)
'1,234,567,890'

백분율 표현:

>>> points = 19
>>> total = 22
>>> 'Correct answers: {:.2%}'.format(points/total)
'Correct answers: 86.36%'

형별 포매팅 사용:

>>> import datetime
>>> d = datetime.datetime(2010, 7, 4, 12, 15, 58)
>>> '{:%Y-%m-%d %H:%M:%S}'.format(d)
'2010-07-04 12:15:58'

인자 중첩과 보다 복잡한 예제:

>>> for align, text in zip('<^>', ['left', 'center', 'right']):
...     '{0:{fill}{align}16}'.format(text, fill=align, align=align)
...
'left<<<<<<<<<<<<'
'^^^^^center^^^^^'
'>>>>>>>>>>>right'
>>>
>>> octets = [192, 168, 0, 1]
>>> '{:02X}{:02X}{:02X}{:02X}'.format(*octets)
'C0A80001'
>>> int(_, 16)
3232235521
>>>
>>> width = 5
>>> for num in range(5,12):
...     for base in 'dXob':
...         print('{0:{width}{base}}'.format(num, base=base, width=width), end=' ')
...     print()
...
    5     5     5   101
    6     6     6   110
    7     7     7   111
    8     8    10  1000
    9     9    11  1001
   10     A    12  1010
   11     B    13  1011

템플릿 문자열

템플릿 문자열은 PEP 292 [https://www.python.org/dev/peps/pep-0292] 에 설명된 대로 더 간단한 문자열 치환을 제공합니다. 템플릿 문자열의 주요 사례는 국제화(i18n)입니다. 이 문맥에서, 더 간단한 문법과 기능은 파이썬의 다른 내장 문자열 포매팅 기능보다 번역하기 쉽게 만들기 때문입니다. i18n을 위해 템플릿 문자열을 기반으로 구축된 라이브러리의 예는 flufl.i18n [http://flufli18n.readthedocs.io/en/latest/] 패키지를 보십시오.

템플릿 문자열은 다음 규칙을 사용하여 $-기반 치환을 지원합니다:

$$ 는 이스케이프입니다. 이것은 하나의 $ 로 치환됩니다.

$identifier 는 매핑 키 "identifier" 와 일치하는 치환 자리 표시자를 지정합니다. 기본적으로, "identifier" 는 밑줄이나 ASCII 알파벳으로 시작하는 대소문자 구분 없는 ASCII 영숫자(밑줄 포함) 문자열로 제한됩니다. $ 문자 뒤의 첫 번째 비 식별자 문자는 이 자리 표시자 명세를 종료합니다.

${identifier} 는 $identifier 와 동등합니다. 유효한 식별자 문자가 자리 표시자 뒤에 오지만, 자리 표시자의 일부가 아니면 필요합니다, 가령 "${noun}ification".

문자열에 다른 방식으로 $ 이 등장하면 ValueError 가 발생합니다.

string 모듈은 이 규칙들을 구현하는 Template 클래스를 제공합니다. Template 의 메서드는 다음과 같습니다:

class string.Template(template)

생성자는 템플릿 문자열 하나를 받아들입니다.

substitute(mapping, **kwds)

템플릿 치환을 수행하고, 새 문자열을 반환합니다. mapping 은 템플릿의 자리 표시자와 일치하는 키를 가진 임의의 딕셔너리류 객체입니다. 또는, 키워드가 자리 표시자인 키워드 인자를 제공 할 수 있습니다. mapping 및 kwds 가 모두 제공되고 중복이 있는 경우, kwds 의 자리 표시자가 우선합니다.

safe_substitute(mapping, **kwds)

substitute()와 비슷하지만, mapping 과 kwds 에 자리 표시자가 없는 경우, KeyError 예외를 발생시키지 않고 원래 자리 표시자가 결과 문자열에 그대로 나타납니다. 또한 substitute() 와는 달리, $ 가 잘못 사용되는 경우 ValueError 를 일으키는 대신 단순히 $ 를 반환합니다.

다른 예외가 여전히 발생할 수 있지만, 이 메서드가 항상 예외를 발생시키는 대신 사용 가능한 문자열을 반환하려고 시도하기 때문에 “안전(safe)” 하다고 합니다. 다른 의미에서, safe_substitute() 는 안전하다고 할 수 없습니다. 길 잃은(dangling) 구분 기호, 쌍을 이루지 않는 중괄호, 유효한 파이썬 식별자가 아닌 자리 표시자를 포함하는 잘못된 템플릿을 조용히 무시하기 때문입니다.

Template 인스턴스는 공개 데이터 어트리뷰트도 하나 제공합니다:

template

이것은 생성자의 template 인자로 전달된 객체입니다. 일반적으로, 변경해서는 안 되지만, 읽기 전용 액세스가 강제되지는 않습니다.

다음은 Template 사용 방법의 예입니다:

>>> from string import Template
>>> s = Template('$who likes $what')
>>> s.substitute(who='tim', what='kung pao')
'tim likes kung pao'
>>> d = dict(who='tim')
>>> Template('Give $who $100').substitute(d)
Traceback (most recent call last):
...
ValueError: Invalid placeholder in string: line 1, col 11
>>> Template('$who likes $what').substitute(d)
Traceback (most recent call last):
...
KeyError: 'what'
>>> Template('$who likes $what').safe_substitute(d)
'tim likes $what'

고급 사용법: Template 의 서브 클래스를 파생하여, 자리 표시자 문법, 구분 기호 문자 또는 템플릿 문자열을 파싱하는데 사용되는 전체 정규식을 사용자 정의 할 수 있습니다. 이렇게 하려면, 다음 클래스 어트리뷰트를 재정의할 수 있습니다:

delimiter – 자리 표시자를 도입하는 구분자를 나타내는 리터럴 문자열입니다. 기본값은 $ 입니다. 구현체는 필요할 때 이 문자열에 re.escape() 를 호출하므로, 이 문자열은 정규식이 아니어야 합니다. 또한, 클래스 생성 후에 구분자를 변경할 수 없습니다 (즉, 다른 구분자는 반드시 서브 클래스의 클래스 이름 공간에 설정해야 합니다).

idpattern – 중괄호로 둘러싸지 않은 자리 표시자의 패턴을 설명하는 정규식입니다. 기본값은 정규식 (?a:[_a-z][_a-z0-9]*) 입니다. braceidpattern 이 None 인 경우, 이 패턴은 중괄호가 있는 자리 표시자에게도 적용됩니다.

참고

기본 flags 가 re.IGNORECASE 이기 때문에, 패턴 [a-z] 는 비 ASCII 문자와 일치 할 수 있습니다. 이 때문에 정규식에 a 플래그를 사용했습니다.

버전 3.7에서 변경: braceidpattern 은 중괄호로 싸여있을 때와 그렇지 않을 때 사용되는 별도의 패턴을 정의하는데 사용할 수 있습니다.

braceidpattern – idpattern 과 유사하지만, 중괄호로 싸인 자리 표시자에 대한 패턴을 설명합니다. 기본값은 None 인데, idpattern 을 사용하는 것을 의미합니다 (즉, 같은 패턴이 중괄호가 있을 때와 없을 때 모두 사용됩니다). 이 값을 주면, 중괄호가 있을 때와 없을 때의 자리 표시자에 서로 다른 패턴을 정의 할 수 있습니다.

버전 3.7에 추가.

flags – 치환 인식에 사용되는 정규식을 컴파일할 때 적용될 정규식 플래그입니다. 기본값은 re.IGNORECASE 입니다. re.VERBOSE 가 항상 플래그에 추가되므로, 사용자 정의 idpattern 은 상세한 정규식의 규칙을 따라야 합니다.

버전 3.2에 추가.

또는, 클래스 어트리뷰트 pattern 을 재정의하여 전체 정규식 패턴을 제공 할 수 있습니다. 이렇게 하는 경우, 값은 네 개의 이름있는 캡처 그룹이 있는 정규식 객체여야 합니다. 캡처 그룹은 위에 제공된 규칙과 함께 유효하지 않은 자리 표시자 규칙에 해당합니다:

escaped – 이 그룹은 이스케이프 시퀀스를 일치시킵니다, 예를 들어 기본 패턴에서 $$.

named – 이 그룹은 중괄호가 없는 자리 표시자 이름을 일치합니다; 캡처 그룹에 구분자를 포함해서는 안 됩니다.

braced – 이 그룹은 중괄호로 묶인 자리 표시자 이름을 일치시킵니다; 캡처 그룹에 구분자나 중괄호를 포함해서는 안 됩니다.

invalid – 이 그룹은 그 외의 구분자 패턴(일반적으로 단일 구분자)을 일치시키고, 정규식의 마지막에 나타나야 합니다.

도움 함수

string.capwords(s, sep=None)

인자를 str.split() 을 사용하여 단어로 나누고, str.capitalize() 를 사용하여 각 단어의 첫 글자를 대문자로 만들고, 이렇게 만들어진 단어들을 str.join() 을 사용하여 결합합니다. 선택적 두 번째 인자 sep 가 없거나 None 이면, 연속된 공백 문자는 단일 스페이스로 바뀌고 앞뒤 공백이 제거됩니다. 그렇지 않으면 sep 가 단어를 나누고 합치는 데 사용됩니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

텍스트 처리 서비스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

텍스트 처리 서비스 »

|

re — Regular expression operations

Source code: Lib/re.py [https://github.com/python/cpython/tree/3.7/Lib/re.py]

This module provides regular expression matching operations similar to those found in Perl.

Both patterns and strings to be searched can be Unicode strings (str) as well as 8-bit strings (bytes). However, Unicode strings and 8-bit strings cannot be mixed: that is, you cannot match a Unicode string with a byte pattern or vice-versa; similarly, when asking for a substitution, the replacement string must be of the same type as both the pattern and the search string.

Regular expressions use the backslash character ('\') to indicate special forms or to allow special characters to be used without invoking their special meaning. This collides with Python’s usage of the same character for the same purpose in string literals; for example, to match a literal backslash, one might have to write '\\\\' as the pattern string, because the regular expression must be \\, and each backslash must be expressed as \\ inside a regular Python string literal.

The solution is to use Python’s raw string notation for regular expression patterns; backslashes are not handled in any special way in a string literal prefixed with 'r'. So r"\n" is a two-character string containing '\' and 'n', while "\n" is a one-character string containing a newline. Usually patterns will be expressed in Python code using this raw string notation.

It is important to note that most regular expression operations are available as module-level functions and methods on compiled regular expressions. The functions are shortcuts that don’t require you to compile a regex object first, but miss some fine-tuning parameters.

더 보기

The third-party regex [https://pypi.org/project/regex/] module, which has an API compatible with the standard library re module, but offers additional functionality and a more thorough Unicode support.

Regular Expression Syntax

A regular expression (or RE) specifies a set of strings that matches it; the functions in this module let you check if a particular string matches a given regular expression (or if a given regular expression matches a particular string, which comes down to the same thing).

Regular expressions can be concatenated to form new regular expressions; if A and B are both regular expressions, then AB is also a regular expression. In general, if a string p matches A and another string q matches B, the string pq will match AB. This holds unless A or B contain low precedence operations; boundary conditions between A and B; or have numbered group references. Thus, complex expressions can easily be constructed from simpler primitive expressions like the ones described here. For details of the theory and implementation of regular expressions, consult the Friedl book [Frie09], or almost any textbook about compiler construction.

A brief explanation of the format of regular expressions follows. For further information and a gentler presentation, consult the Regular Expression HOWTO.

Regular expressions can contain both special and ordinary characters. Most ordinary characters, like 'A', 'a', or '0', are the simplest regular expressions; they simply match themselves. You can concatenate ordinary characters, so last matches the string 'last'. (In the rest of this section, we’ll write RE’s in this special style, usually without quotes, and strings to be matched 'in single quotes'.)

Some characters, like '|' or '(', are special. Special characters either stand for classes of ordinary characters, or affect how the regular expressions around them are interpreted.

Repetition qualifiers (*, +, ?, {m,n}, etc) cannot be directly nested. This avoids ambiguity with the non-greedy modifier suffix ?, and with other modifiers in other implementations. To apply a second repetition to an inner repetition, parentheses may be used. For example, the expression (?:a{6})* matches any multiple of six 'a' characters.

The special characters are:

.

(Dot.) In the default mode, this matches any character except a newline. If the DOTALL flag has been specified, this matches any character including a newline.

^

(Caret.) Matches the start of the string, and in MULTILINE mode also matches immediately after each newline.

$

Matches the end of the string or just before the newline at the end of the string, and in MULTILINE mode also matches before a newline. foo matches both ‘foo’ and ‘foobar’, while the regular expression foo$ matches only ‘foo’. More interestingly, searching for foo.$ in 'foo1\nfoo2\n' matches ‘foo2’ normally, but ‘foo1’ in MULTILINE mode; searching for a single $ in 'foo\n' will find two (empty) matches: one just before the newline, and one at the end of the string.

*

Causes the resulting RE to match 0 or more repetitions of the preceding RE, as many repetitions as are possible. ab* will match ‘a’, ‘ab’, or ‘a’ followed by any number of ‘b’s.

+

Causes the resulting RE to match 1 or more repetitions of the preceding RE. ab+ will match ‘a’ followed by any non-zero number of ‘b’s; it will not match just ‘a’.

?

Causes the resulting RE to match 0 or 1 repetitions of the preceding RE. ab? will match either ‘a’ or ‘ab’.

*?, +?, ??

The '*', '+', and '?' qualifiers are all greedy; they match as much text as possible. Sometimes this behaviour isn’t desired; if the RE <.*> is matched against '<a> b <c>', it will match the entire string, and not just '<a>'. Adding ? after the qualifier makes it perform the match in non-greedy or minimal fashion; as few characters as possible will be matched. Using the RE <.*?> will match only '<a>'.

{m}

Specifies that exactly m copies of the previous RE should be matched; fewer matches cause the entire RE not to match. For example, a{6} will match exactly six 'a' characters, but not five.

{m,n}

Causes the resulting RE to match from m to n repetitions of the preceding RE, attempting to match as many repetitions as possible. For example, a{3,5} will match from 3 to 5 'a' characters. Omitting m specifies a lower bound of zero, and omitting n specifies an infinite upper bound. As an example, a{4,}b will match 'aaaab' or a thousand 'a' characters followed by a 'b', but not 'aaab'. The comma may not be omitted or the modifier would be confused with the previously described form.

{m,n}?

Causes the resulting RE to match from m to n repetitions of the preceding RE, attempting to match as few repetitions as possible. This is the non-greedy version of the previous qualifier. For example, on the 6-character string 'aaaaaa', a{3,5} will match 5 'a' characters, while a{3,5}? will only match 3 characters.

\

Either escapes special characters (permitting you to match characters like '*', '?', and so forth), or signals a special sequence; special sequences are discussed below.

If you’re not using a raw string to express the pattern, remember that Python also uses the backslash as an escape sequence in string literals; if the escape sequence isn’t recognized by Python’s parser, the backslash and subsequent character are included in the resulting string. However, if Python would recognize the resulting sequence, the backslash should be repeated twice. This is complicated and hard to understand, so it’s highly recommended that you use raw strings for all but the simplest expressions.

[]

Used to indicate a set of characters. In a set:

Characters can be listed individually, e.g. [amk] will match 'a', 'm', or 'k'.

Ranges of characters can be indicated by giving two characters and separating them by a '-', for example [a-z] will match any lowercase ASCII letter, [0-5][0-9] will match all the two-digits numbers from 00 to 59, and [0-9A-Fa-f] will match any hexadecimal digit. If - is escaped (e.g. [a\-z]) or if it’s placed as the first or last character (e.g. [-a] or [a-]), it will match a literal '-'.

Special characters lose their special meaning inside sets. For example, [(+*)] will match any of the literal characters '(', '+', '*', or ')'.

Character classes such as \w or \S (defined below) are also accepted inside a set, although the characters they match depends on whether ASCII or LOCALE mode is in force.

Characters that are not within a range can be matched by complementing the set. If the first character of the set is '^', all the characters that are not in the set will be matched. For example, [^5] will match any character except '5', and [^^] will match any character except '^'. ^ has no special meaning if it’s not the first character in the set.

To match a literal ']' inside a set, precede it with a backslash, or place it at the beginning of the set. For example, both [()[\]{}] and []()[{}] will both match a parenthesis.

Support of nested sets and set operations as in Unicode Technical Standard #18 [https://unicode.org/reports/tr18/] might be added in the future. This would change the syntax, so to facilitate this change a FutureWarning will be raised in ambiguous cases for the time being. That includes sets starting with a literal '[' or containing literal character sequences '--', '&&', '~~', and '||'. To avoid a warning escape them with a backslash.

버전 3.7에서 변경: FutureWarning is raised if a character set contains constructs that will change semantically in the future.

|

A|B, where A and B can be arbitrary REs, creates a regular expression that will match either A or B. An arbitrary number of REs can be separated by the '|' in this way. This can be used inside groups (see below) as well. As the target string is scanned, REs separated by '|' are tried from left to right. When one pattern completely matches, that branch is accepted. This means that once A matches, B will not be tested further, even if it would produce a longer overall match. In other words, the '|' operator is never greedy. To match a literal '|', use \|, or enclose it inside a character class, as in [|].

(...)

Matches whatever regular expression is inside the parentheses, and indicates the start and end of a group; the contents of a group can be retrieved after a match has been performed, and can be matched later in the string with the \number special sequence, described below. To match the literals '(' or ')', use \( or \), or enclose them inside a character class: [(], [)].

(?...)

This is an extension notation (a '?' following a '(' is not meaningful otherwise). The first character after the '?' determines what the meaning and further syntax of the construct is. Extensions usually do not create a new group; (?P<name>...) is the only exception to this rule. Following are the currently supported extensions.

(?aiLmsux)

(One or more letters from the set 'a', 'i', 'L', 'm', 's', 'u', 'x'.) The group matches the empty string; the letters set the corresponding flags: re.A (ASCII-only matching), re.I (ignore case), re.L (locale dependent), re.M (multi-line), re.S (dot matches all), re.U (Unicode matching), and re.X (verbose), for the entire regular expression. (The flags are described in Module Contents.) This is useful if you wish to include the flags as part of the regular expression, instead of passing a flag argument to the re.compile() function. Flags should be used first in the expression string.

(?:...)

A non-capturing version of regular parentheses. Matches whatever regular expression is inside the parentheses, but the substring matched by the group cannot be retrieved after performing a match or referenced later in the pattern.

(?aiLmsux-imsx:...)

(Zero or more letters from the set 'a', 'i', 'L', 'm', 's', 'u', 'x', optionally followed by '-' followed by one or more letters from the 'i', 'm', 's', 'x'.) The letters set or remove the corresponding flags: re.A (ASCII-only matching), re.I (ignore case), re.L (locale dependent), re.M (multi-line), re.S (dot matches all), re.U (Unicode matching), and re.X (verbose), for the part of the expression. (The flags are described in Module Contents.)

The letters 'a', 'L' and 'u' are mutually exclusive when used as inline flags, so they can’t be combined or follow '-'. Instead, when one of them appears in an inline group, it overrides the matching mode in the enclosing group. In Unicode patterns (?a:...) switches to ASCII-only matching, and (?u:...) switches to Unicode matching (default). In byte pattern (?L:...) switches to locale depending matching, and (?a:...) switches to ASCII-only matching (default). This override is only in effect for the narrow inline group, and the original matching mode is restored outside of the group.

버전 3.6에 추가.

버전 3.7에서 변경: The letters 'a', 'L' and 'u' also can be used in a group.

(?P<name>...)

Similar to regular parentheses, but the substring matched by the group is accessible via the symbolic group name name. Group names must be valid Python identifiers, and each group name must be defined only once within a regular expression. A symbolic group is also a numbered group, just as if the group were not named.

Named groups can be referenced in three contexts. If the pattern is (?P<quote>['"]).*?(?P=quote) (i.e. matching a string quoted with either single or double quotes):

Context of reference to group “quote”

Ways to reference it

in the same pattern itself

(?P=quote) (as shown)

\1

when processing match object m

m.group('quote')

m.end('quote') (etc.)

in a string passed to the repl argument of re.sub()

\g<quote>

\g<1>

\1

(?P=name)

A backreference to a named group; it matches whatever text was matched by the earlier group named name.

(?#...)

A comment; the contents of the parentheses are simply ignored.

(?=...)

Matches if ... matches next, but doesn’t consume any of the string. This is called a lookahead assertion. For example, Isaac (?=Asimov) will match 'Isaac ' only if it’s followed by 'Asimov'.

(?!...)

Matches if ... doesn’t match next. This is a negative lookahead assertion. For example, Isaac (?!Asimov) will match 'Isaac ' only if it’s not followed by 'Asimov'.

(?<=...)

Matches if the current position in the string is preceded by a match for ... that ends at the current position. This is called a positive lookbehind assertion. (?<=abc)def will find a match in 'abcdef', since the lookbehind will back up 3 characters and check if the contained pattern matches. The contained pattern must only match strings of some fixed length, meaning that abc or a|b are allowed, but a* and a{3,4} are not. Note that patterns which start with positive lookbehind assertions will not match at the beginning of the string being searched; you will most likely want to use the search() function rather than the match() function:

>>> import re
>>> m = re.search('(?<=abc)def', 'abcdef')
>>> m.group(0)
'def'

This example looks for a word following a hyphen:

>>> m = re.search(r'(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'

버전 3.5에서 변경: Added support for group references of fixed length.

(?<!...)

Matches if the current position in the string is not preceded by a match for .... This is called a negative lookbehind assertion. Similar to positive lookbehind assertions, the contained pattern must only match strings of some fixed length. Patterns which start with negative lookbehind assertions may match at the beginning of the string being searched.

(?(id/name)yes-pattern|no-pattern)

Will try to match with yes-pattern if the group with given id or name exists, and with no-pattern if it doesn’t. no-pattern is optional and can be omitted. For example, (<)?(\w+@\w+(?:\.\w+)+)(?(1)>|$) is a poor email matching pattern, which will match with '<user@host.com>' as well as 'user@host.com', but not with '<user@host.com' nor 'user@host.com>'.

The special sequences consist of '\' and a character from the list below. If the ordinary character is not an ASCII digit or an ASCII letter, then the resulting RE will match the second character. For example, \$ matches the character '$'.

\number

Matches the contents of the group of the same number. Groups are numbered starting from 1. For example, (.+) \1 matches 'the the' or '55 55', but not 'thethe' (note the space after the group). This special sequence can only be used to match one of the first 99 groups. If the first digit of number is 0, or number is 3 octal digits long, it will not be interpreted as a group match, but as the character with octal value number. Inside the '[' and ']' of a character class, all numeric escapes are treated as characters.

\A

Matches only at the start of the string.

\b

Matches the empty string, but only at the beginning or end of a word. A word is defined as a sequence of word characters. Note that formally, \b is defined as the boundary between a \w and a \W character (or vice versa), or between \w and the beginning/end of the string. This means that r'\bfoo\b' matches 'foo', 'foo.', '(foo)', 'bar foo baz' but not 'foobar' or 'foo3'.

By default Unicode alphanumerics are the ones used in Unicode patterns, but this can be changed by using the ASCII flag. Word boundaries are determined by the current locale if the LOCALE flag is used. Inside a character range, \b represents the backspace character, for compatibility with Python’s string literals.

\B

Matches the empty string, but only when it is not at the beginning or end of a word. This means that r'py\B' matches 'python', 'py3', 'py2', but not 'py', 'py.', or 'py!'. \B is just the opposite of \b, so word characters in Unicode patterns are Unicode alphanumerics or the underscore, although this can be changed by using the ASCII flag. Word boundaries are determined by the current locale if the LOCALE flag is used.

\d

For Unicode (str) patterns:

Matches any Unicode decimal digit (that is, any character in Unicode character category [Nd]). This includes [0-9], and also many other digit characters. If the ASCII flag is used only [0-9] is matched.

For 8-bit (bytes) patterns:

Matches any decimal digit; this is equivalent to [0-9].

\D

Matches any character which is not a decimal digit. This is the opposite of \d. If the ASCII flag is used this becomes the equivalent of [^0-9].

\s

For Unicode (str) patterns:

Matches Unicode whitespace characters (which includes [ \t\n\r\f\v], and also many other characters, for example the non-breaking spaces mandated by typography rules in many languages). If the ASCII flag is used, only [ \t\n\r\f\v] is matched.

For 8-bit (bytes) patterns:

Matches characters considered whitespace in the ASCII character set; this is equivalent to [ \t\n\r\f\v].

\S

Matches any character which is not a whitespace character. This is the opposite of \s. If the ASCII flag is used this becomes the equivalent of [^ \t\n\r\f\v].

\w

For Unicode (str) patterns:

Matches Unicode word characters; this includes most characters that can be part of a word in any language, as well as numbers and the underscore. If the ASCII flag is used, only [a-zA-Z0-9_] is matched.

For 8-bit (bytes) patterns:

Matches characters considered alphanumeric in the ASCII character set; this is equivalent to [a-zA-Z0-9_]. If the LOCALE flag is used, matches characters considered alphanumeric in the current locale and the underscore.

\W

Matches any character which is not a word character. This is the opposite of \w. If the ASCII flag is used this becomes the equivalent of [^a-zA-Z0-9_]. If the LOCALE flag is used, matches characters which are neither alphanumeric in the current locale nor the underscore.

\Z

Matches only at the end of the string.

Most of the standard escapes supported by Python string literals are also accepted by the regular expression parser:

\a      \b      \f      \n
\r      \t      \u      \U
\v      \x      \\

(Note that \b is used to represent word boundaries, and means “backspace” only inside character classes.)

'\u' and '\U' escape sequences are only recognized in Unicode patterns. In bytes patterns they are errors. Unknown escapes of ASCII letters are reserved for future use and treated as errors.

Octal escapes are included in a limited form. If the first digit is a 0, or if there are three octal digits, it is considered an octal escape. Otherwise, it is a group reference. As for string literals, octal escapes are always at most three digits in length.

버전 3.3에서 변경: The '\u' and '\U' escape sequences have been added.

버전 3.6에서 변경: Unknown escapes consisting of '\' and an ASCII letter now are errors.

Module Contents

The module defines several functions, constants, and an exception. Some of the functions are simplified versions of the full featured methods for compiled regular expressions. Most non-trivial applications always use the compiled form.

버전 3.6에서 변경: Flag constants are now instances of RegexFlag, which is a subclass of enum.IntFlag.

re.compile(pattern, flags=0)

Compile a regular expression pattern into a regular expression object, which can be used for matching using its match(), search() and other methods, described below.

The expression’s behaviour can be modified by specifying a flags value. Values can be any of the following variables, combined using bitwise OR (the | operator).

The sequence

prog = re.compile(pattern)
result = prog.match(string)

is equivalent to

result = re.match(pattern, string)

but using re.compile() and saving the resulting regular expression object for reuse is more efficient when the expression will be used several times in a single program.

참고

The compiled versions of the most recent patterns passed to re.compile() and the module-level matching functions are cached, so programs that use only a few regular expressions at a time needn’t worry about compiling regular expressions.

re.A

re.ASCII

Make \w, \W, \b, \B, \d, \D, \s and \S perform ASCII-only matching instead of full Unicode matching. This is only meaningful for Unicode patterns, and is ignored for byte patterns. Corresponds to the inline flag (?a).

Note that for backward compatibility, the re.U flag still exists (as well as its synonym re.UNICODE and its embedded counterpart (?u)), but these are redundant in Python 3 since matches are Unicode by default for strings (and Unicode matching isn’t allowed for bytes).

re.DEBUG

Display debug information about compiled expression. No corresponding inline flag.

re.I

re.IGNORECASE

Perform case-insensitive matching; expressions like [A-Z] will also match lowercase letters. Full Unicode matching (such as Ü matching ü) also works unless the re.ASCII flag is used to disable non-ASCII matches. The current locale does not change the effect of this flag unless the re.LOCALE flag is also used. Corresponds to the inline flag (?i).

Note that when the Unicode patterns [a-z] or [A-Z] are used in combination with the IGNORECASE flag, they will match the 52 ASCII letters and 4 additional non-ASCII letters: ‘İ’ (U+0130, Latin capital letter I with dot above), ‘ı’ (U+0131, Latin small letter dotless i), ‘ſ’ (U+017F, Latin small letter long s) and ‘K’ (U+212A, Kelvin sign). If the ASCII flag is used, only letters ‘a’ to ‘z’ and ‘A’ to ‘Z’ are matched.

re.L

re.LOCALE

Make \w, \W, \b, \B and case-insensitive matching dependent on the current locale. This flag can be used only with bytes patterns. The use of this flag is discouraged as the locale mechanism is very unreliable, it only handles one “culture” at a time, and it only works with 8-bit locales. Unicode matching is already enabled by default in Python 3 for Unicode (str) patterns, and it is able to handle different locales/languages. Corresponds to the inline flag (?L).

버전 3.6에서 변경: re.LOCALE can be used only with bytes patterns and is not compatible with re.ASCII.

버전 3.7에서 변경: Compiled regular expression objects with the re.LOCALE flag no longer depend on the locale at compile time. Only the locale at matching time affects the result of matching.

re.M

re.MULTILINE

When specified, the pattern character '^' matches at the beginning of the string and at the beginning of each line (immediately following each newline); and the pattern character '$' matches at the end of the string and at the end of each line (immediately preceding each newline). By default, '^' matches only at the beginning of the string, and '$' only at the end of the string and immediately before the newline (if any) at the end of the string. Corresponds to the inline flag (?m).

re.S

re.DOTALL

Make the '.' special character match any character at all, including a newline; without this flag, '.' will match anything except a newline. Corresponds to the inline flag (?s).

re.X

re.VERBOSE

This flag allows you to write regular expressions that look nicer and are more readable by allowing you to visually separate logical sections of the pattern and add comments. Whitespace within the pattern is ignored, except when in a character class, or when preceded by an unescaped backslash, or within tokens like *?, (?: or (?P<...>. When a line contains a # that is not in a character class and is not preceded by an unescaped backslash, all characters from the leftmost such # through the end of the line are ignored.

This means that the two following regular expression objects that match a decimal number are functionally equal:

a = re.compile(r"""\d +  # the integral part
                   \.    # the decimal point
                   \d *  # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")

Corresponds to the inline flag (?x).

re.search(pattern, string, flags=0)

Scan through string looking for the first location where the regular expression pattern produces a match, and return a corresponding match object. Return None if no position in the string matches the pattern; note that this is different from finding a zero-length match at some point in the string.

re.match(pattern, string, flags=0)

If zero or more characters at the beginning of string match the regular expression pattern, return a corresponding match object. Return None if the string does not match the pattern; note that this is different from a zero-length match.

Note that even in MULTILINE mode, re.match() will only match at the beginning of the string and not at the beginning of each line.

If you want to locate a match anywhere in string, use search() instead (see also search() vs. match()).

re.fullmatch(pattern, string, flags=0)

If the whole string matches the regular expression pattern, return a corresponding match object. Return None if the string does not match the pattern; note that this is different from a zero-length match.

버전 3.4에 추가.

re.split(pattern, string, maxsplit=0, flags=0)

Split string by the occurrences of pattern. If capturing parentheses are used in pattern, then the text of all groups in the pattern are also returned as part of the resulting list. If maxsplit is nonzero, at most maxsplit splits occur, and the remainder of the string is returned as the final element of the list.

>>> re.split(r'\W+', 'Words, words, words.')
['Words', 'words', 'words', '']
>>> re.split(r'(\W+)', 'Words, words, words.')
['Words', ', ', 'words', ', ', 'words', '.', '']
>>> re.split(r'\W+', 'Words, words, words.', 1)
['Words', 'words, words.']
>>> re.split('[a-f]+', '0a3B9', flags=re.IGNORECASE)
['0', '3', '9']

If there are capturing groups in the separator and it matches at the start of the string, the result will start with an empty string. The same holds for the end of the string:

>>> re.split(r'(\W+)', '...words, words...')
['', '...', 'words', ', ', 'words', '...', '']

That way, separator components are always found at the same relative indices within the result list.

Empty matches for the pattern split the string only when not adjacent to a previous empty match.

>>> re.split(r'\b', 'Words, words, words.')
['', 'Words', ', ', 'words', ', ', 'words', '.']
>>> re.split(r'\W*', '...words...')
['', '', 'w', 'o', 'r', 'd', 's', '', '']
>>> re.split(r'(\W*)', '...words...')
['', '...', '', '', 'w', '', 'o', '', 'r', '', 'd', '', 's', '...', '', '', '']

버전 3.1에서 변경: Added the optional flags argument.

버전 3.7에서 변경: Added support of splitting on a pattern that could match an empty string.

re.findall(pattern, string, flags=0)

Return all non-overlapping matches of pattern in string, as a list of strings. The string is scanned left-to-right, and matches are returned in the order found. If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result.

버전 3.7에서 변경: Non-empty matches can now start just after a previous empty match.

re.finditer(pattern, string, flags=0)

Return an iterator yielding match objects over all non-overlapping matches for the RE pattern in string. The string is scanned left-to-right, and matches are returned in the order found. Empty matches are included in the result.

버전 3.7에서 변경: Non-empty matches can now start just after a previous empty match.

re.sub(pattern, repl, string, count=0, flags=0)

Return the string obtained by replacing the leftmost non-overlapping occurrences of pattern in string by the replacement repl. If the pattern isn’t found, string is returned unchanged. repl can be a string or a function; if it is a string, any backslash escapes in it are processed. That is, \n is converted to a single newline character, \r is converted to a carriage return, and so forth. Unknown escapes of ASCII letters are reserved for future use and treated as errors. Other unknown escapes such as \& are left alone. Backreferences, such as \6, are replaced with the substring matched by group 6 in the pattern. For example:

>>> re.sub(r'def\s+([a-zA-Z_][a-zA-Z_0-9]*)\s*\(\s*\):',
...        r'static PyObject*\npy_\1(void)\n{',
...        'def myfunc():')
'static PyObject*\npy_myfunc(void)\n{'

If repl is a function, it is called for every non-overlapping occurrence of pattern. The function takes a single match object argument, and returns the replacement string. For example:

>>> def dashrepl(matchobj):
...     if matchobj.group(0) == '-': return ' '
...     else: return '-'
>>> re.sub('-{1,2}', dashrepl, 'pro----gram-files')
'pro--gram files'
>>> re.sub(r'\sAND\s', ' & ', 'Baked Beans And Spam', flags=re.IGNORECASE)
'Baked Beans & Spam'

The pattern may be a string or a pattern object.

The optional argument count is the maximum number of pattern occurrences to be replaced; count must be a non-negative integer. If omitted or zero, all occurrences will be replaced. Empty matches for the pattern are replaced only when not adjacent to a previous empty match, so sub('x*', '-', 'abxd') returns '-a-b--d-'.

In string-type repl arguments, in addition to the character escapes and backreferences described above, \g<name> will use the substring matched by the group named name, as defined by the (?P<name>...) syntax. \g<number> uses the corresponding group number; \g<2> is therefore equivalent to \2, but isn’t ambiguous in a replacement such as \g<2>0. \20 would be interpreted as a reference to group 20, not a reference to group 2 followed by the literal character '0'. The backreference \g<0> substitutes in the entire substring matched by the RE.

버전 3.1에서 변경: Added the optional flags argument.

버전 3.5에서 변경: Unmatched groups are replaced with an empty string.

버전 3.6에서 변경: Unknown escapes in pattern consisting of '\' and an ASCII letter now are errors.

버전 3.7에서 변경: Unknown escapes in repl consisting of '\' and an ASCII letter now are errors.

버전 3.7에서 변경: Empty matches for the pattern are replaced when adjacent to a previous non-empty match.

re.subn(pattern, repl, string, count=0, flags=0)

Perform the same operation as sub(), but return a tuple (new_string, number_of_subs_made).

버전 3.1에서 변경: Added the optional flags argument.

버전 3.5에서 변경: Unmatched groups are replaced with an empty string.

re.escape(pattern)

Escape special characters in pattern. This is useful if you want to match an arbitrary literal string that may have regular expression metacharacters in it. For example:

>>> print(re.escape('http://www.python.org'))
http://www\.python\.org

>>> legal_chars = string.ascii_lowercase + string.digits + "!#$%&'*+-.^_`|~:"
>>> print('[%s]+' % re.escape(legal_chars))
[abcdefghijklmnopqrstuvwxyz0123456789!\#\$%\&'\*\+\-\.\^_`\|\~:]+

>>> operators = ['+', '-', '*', '/', '**']
>>> print('|'.join(map(re.escape, sorted(operators, reverse=True))))
/|\-|\+|\*\*|\*

This function must not be used for the replacement string in sub() and subn(), only backslashes should be escaped. For example:

>>> digits_re = r'\d+'
>>> sample = '/usr/sbin/sendmail - 0 errors, 12 warnings'
>>> print(re.sub(digits_re, digits_re.replace('\\', r'\\'), sample))
/usr/sbin/sendmail - \d+ errors, \d+ warnings

버전 3.3에서 변경: The '_' character is no longer escaped.

버전 3.7에서 변경: Only characters that can have special meaning in a regular expression are escaped. As a result, '!', '"', '%', "'", ',', '/', ':', ';', '<', '=', '>', '@', and "`" are no longer escaped.

re.purge()

Clear the regular expression cache.

exception re.error(msg, pattern=None, pos=None)

Exception raised when a string passed to one of the functions here is not a valid regular expression (for example, it might contain unmatched parentheses) or when some other error occurs during compilation or matching. It is never an error if a string contains no match for a pattern. The error instance has the following additional attributes:

msg

The unformatted error message.

pattern

The regular expression pattern.

pos

The index in pattern where compilation failed (may be None).

lineno

The line corresponding to pos (may be None).

colno

The column corresponding to pos (may be None).

버전 3.5에서 변경: Added additional attributes.

Regular Expression Objects

Compiled regular expression objects support the following methods and attributes:

Pattern.search(string[, pos[, endpos]])

Scan through string looking for the first location where this regular expression produces a match, and return a corresponding match object. Return None if no position in the string matches the pattern; note that this is different from finding a zero-length match at some point in the string.

The optional second parameter pos gives an index in the string where the search is to start; it defaults to 0. This is not completely equivalent to slicing the string; the '^' pattern character matches at the real beginning of the string and at positions just after a newline, but not necessarily at the index where the search is to start.

The optional parameter endpos limits how far the string will be searched; it will be as if the string is endpos characters long, so only the characters from pos to endpos - 1 will be searched for a match. If endpos is less than pos, no match will be found; otherwise, if rx is a compiled regular expression object, rx.search(string, 0, 50) is equivalent to rx.search(string[:50], 0).

>>> pattern = re.compile("d")
>>> pattern.search("dog")     # Match at index 0
<re.Match object; span=(0, 1), match='d'>
>>> pattern.search("dog", 1)  # No match; search doesn't include the "d"

Pattern.match(string[, pos[, endpos]])

If zero or more characters at the beginning of string match this regular expression, return a corresponding match object. Return None if the string does not match the pattern; note that this is different from a zero-length match.

The optional pos and endpos parameters have the same meaning as for the search() method.

>>> pattern = re.compile("o")
>>> pattern.match("dog")      # No match as "o" is not at the start of "dog".
>>> pattern.match("dog", 1)   # Match as "o" is the 2nd character of "dog".
<re.Match object; span=(1, 2), match='o'>

If you want to locate a match anywhere in string, use search() instead (see also search() vs. match()).

Pattern.fullmatch(string[, pos[, endpos]])

If the whole string matches this regular expression, return a corresponding match object. Return None if the string does not match the pattern; note that this is different from a zero-length match.

The optional pos and endpos parameters have the same meaning as for the search() method.

>>> pattern = re.compile("o[gh]")
>>> pattern.fullmatch("dog")      # No match as "o" is not at the start of "dog".
>>> pattern.fullmatch("ogre")     # No match as not the full string matches.
>>> pattern.fullmatch("doggie", 1, 3)   # Matches within given limits.
<re.Match object; span=(1, 3), match='og'>

버전 3.4에 추가.

Pattern.split(string, maxsplit=0)

Identical to the split() function, using the compiled pattern.

Pattern.findall(string[, pos[, endpos]])

Similar to the findall() function, using the compiled pattern, but also accepts optional pos and endpos parameters that limit the search region like for search().

Pattern.finditer(string[, pos[, endpos]])

Similar to the finditer() function, using the compiled pattern, but also accepts optional pos and endpos parameters that limit the search region like for search().

Pattern.sub(repl, string, count=0)

Identical to the sub() function, using the compiled pattern.

Pattern.subn(repl, string, count=0)

Identical to the subn() function, using the compiled pattern.

Pattern.flags

The regex matching flags. This is a combination of the flags given to compile(), any (?...) inline flags in the pattern, and implicit flags such as UNICODE if the pattern is a Unicode string.

Pattern.groups

The number of capturing groups in the pattern.

Pattern.groupindex

A dictionary mapping any symbolic group names defined by (?P<id>) to group numbers. The dictionary is empty if no symbolic groups were used in the pattern.

Pattern.pattern

The pattern string from which the pattern object was compiled.

버전 3.7에서 변경: Added support of copy.copy() and copy.deepcopy(). Compiled regular expression objects are considered atomic.

Match Objects

Match objects always have a boolean value of True. Since match() and search() return None when there is no match, you can test whether there was a match with a simple if statement:

match = re.search(pattern, string)
if match:
    process(match)

Match objects support the following methods and attributes:

Match.expand(template)

Return the string obtained by doing backslash substitution on the template string template, as done by the sub() method. Escapes such as \n are converted to the appropriate characters, and numeric backreferences (\1, \2) and named backreferences (\g<1>, \g<name>) are replaced by the contents of the corresponding group.

버전 3.5에서 변경: Unmatched groups are replaced with an empty string.

Match.group([group1, ...])

Returns one or more subgroups of the match. If there is a single argument, the result is a single string; if there are multiple arguments, the result is a tuple with one item per argument. Without arguments, group1 defaults to zero (the whole match is returned). If a groupN argument is zero, the corresponding return value is the entire matching string; if it is in the inclusive range [1..99], it is the string matching the corresponding parenthesized group. If a group number is negative or larger than the number of groups defined in the pattern, an IndexError exception is raised. If a group is contained in a part of the pattern that did not match, the corresponding result is None. If a group is contained in a part of the pattern that matched multiple times, the last match is returned.

>>> m = re.match(r"(\w+) (\w+)", "Isaac Newton, physicist")
>>> m.group(0)       # The entire match
'Isaac Newton'
>>> m.group(1)       # The first parenthesized subgroup.
'Isaac'
>>> m.group(2)       # The second parenthesized subgroup.
'Newton'
>>> m.group(1, 2)    # Multiple arguments give us a tuple.
('Isaac', 'Newton')

If the regular expression uses the (?P<name>...) syntax, the groupN arguments may also be strings identifying groups by their group name. If a string argument is not used as a group name in the pattern, an IndexError exception is raised.

A moderately complicated example:

>>> m = re.match(r"(?P<first_name>\w+) (?P<last_name>\w+)", "Malcolm Reynolds")
>>> m.group('first_name')
'Malcolm'
>>> m.group('last_name')
'Reynolds'

Named groups can also be referred to by their index:

>>> m.group(1)
'Malcolm'
>>> m.group(2)
'Reynolds'

If a group matches multiple times, only the last match is accessible:

>>> m = re.match(r"(..)+", "a1b2c3")  # Matches 3 times.
>>> m.group(1)                        # Returns only the last match.
'c3'

Match.__getitem__(g)

This is identical to m.group(g). This allows easier access to an individual group from a match:

>>> m = re.match(r"(\w+) (\w+)", "Isaac Newton, physicist")
>>> m[0]       # The entire match
'Isaac Newton'
>>> m[1]       # The first parenthesized subgroup.
'Isaac'
>>> m[2]       # The second parenthesized subgroup.
'Newton'

버전 3.6에 추가.

Match.groups(default=None)

Return a tuple containing all the subgroups of the match, from 1 up to however many groups are in the pattern. The default argument is used for groups that did not participate in the match; it defaults to None.

For example:

>>> m = re.match(r"(\d+)\.(\d+)", "24.1632")
>>> m.groups()
('24', '1632')

If we make the decimal place and everything after it optional, not all groups might participate in the match. These groups will default to None unless the default argument is given:

>>> m = re.match(r"(\d+)\.?(\d+)?", "24")
>>> m.groups()      # Second group defaults to None.
('24', None)
>>> m.groups('0')   # Now, the second group defaults to '0'.
('24', '0')

Match.groupdict(default=None)

Return a dictionary containing all the named subgroups of the match, keyed by the subgroup name. The default argument is used for groups that did not participate in the match; it defaults to None. For example:

>>> m = re.match(r"(?P<first_name>\w+) (?P<last_name>\w+)", "Malcolm Reynolds")
>>> m.groupdict()
{'first_name': 'Malcolm', 'last_name': 'Reynolds'}

Match.start([group])

Match.end([group])

Return the indices of the start and end of the substring matched by group; group defaults to zero (meaning the whole matched substring). Return -1 if group exists but did not contribute to the match. For a match object m, and a group g that did contribute to the match, the substring matched by group g (equivalent to m.group(g)) is

m.string[m.start(g):m.end(g)]

Note that m.start(group) will equal m.end(group) if group matched a null string. For example, after m = re.search('b(c?)', 'cba'), m.start(0) is 1, m.end(0) is 2, m.start(1) and m.end(1) are both 2, and m.start(2) raises an IndexError exception.

An example that will remove remove_this from email addresses:

>>> email = "tony@tiremove_thisger.net"
>>> m = re.search("remove_this", email)
>>> email[:m.start()] + email[m.end():]
'tony@tiger.net'

Match.span([group])

For a match m, return the 2-tuple (m.start(group), m.end(group)). Note that if group did not contribute to the match, this is (-1, -1). group defaults to zero, the entire match.

Match.pos

The value of pos which was passed to the search() or match() method of a regex object. This is the index into the string at which the RE engine started looking for a match.

Match.endpos

The value of endpos which was passed to the search() or match() method of a regex object. This is the index into the string beyond which the RE engine will not go.

Match.lastindex

The integer index of the last matched capturing group, or None if no group was matched at all. For example, the expressions (a)b, ((a)(b)), and ((ab)) will have lastindex == 1 if applied to the string 'ab', while the expression (a)(b) will have lastindex == 2, if applied to the same string.

Match.lastgroup

The name of the last matched capturing group, or None if the group didn’t have a name, or if no group was matched at all.

Match.re

The regular expression object whose match() or search() method produced this match instance.

Match.string

The string passed to match() or search().

버전 3.7에서 변경: Added support of copy.copy() and copy.deepcopy(). Match objects are considered atomic.

Regular Expression Examples

Checking for a Pair

In this example, we’ll use the following helper function to display match objects a little more gracefully:

def displaymatch(match):
    if match is None:
        return None
    return '<Match: %r, groups=%r>' % (match.group(), match.groups())

Suppose you are writing a poker program where a player’s hand is represented as a 5-character string with each character representing a card, “a” for ace, “k” for king, “q” for queen, “j” for jack, “t” for 10, and “2” through “9” representing the card with that value.

To see if a given string is a valid hand, one could do the following:

>>> valid = re.compile(r"^[a2-9tjqk]{5}$")
>>> displaymatch(valid.match("akt5q"))  # Valid.
"<Match: 'akt5q', groups=()>"
>>> displaymatch(valid.match("akt5e"))  # Invalid.
>>> displaymatch(valid.match("akt"))    # Invalid.
>>> displaymatch(valid.match("727ak"))  # Valid.
"<Match: '727ak', groups=()>"

That last hand, "727ak", contained a pair, or two of the same valued cards. To match this with a regular expression, one could use backreferences as such:

>>> pair = re.compile(r".*(.).*\1")
>>> displaymatch(pair.match("717ak"))     # Pair of 7s.
"<Match: '717', groups=('7',)>"
>>> displaymatch(pair.match("718ak"))     # No pairs.
>>> displaymatch(pair.match("354aa"))     # Pair of aces.
"<Match: '354aa', groups=('a',)>"

To find out what card the pair consists of, one could use the group() method of the match object in the following manner:

>>> pair.match("717ak").group(1)
'7'

# Error because re.match() returns None, which doesn't have a group() method:
>>> pair.match("718ak").group(1)
Traceback (most recent call last):
  File "<pyshell#23>", line 1, in <module>
    re.match(r".*(.).*\1", "718ak").group(1)
AttributeError: 'NoneType' object has no attribute 'group'

>>> pair.match("354aa").group(1)
'a'

Simulating scanf()

Python does not currently have an equivalent to scanf(). Regular expressions are generally more powerful, though also more verbose, than scanf() format strings. The table below offers some more-or-less equivalent mappings between scanf() format tokens and regular expressions.

scanf() Token

Regular Expression

%c

.

%5c

.{5}

%d

[-+]?\d+

%e, %E, %f, %g

[-+]?(\d+(\.\d*)?|\.\d+)([eE][-+]?\d+)?

%i

[-+]?(0[xX][\dA-Fa-f]+|0[0-7]*|\d+)

%o

[-+]?[0-7]+

%s

\S+

%u

\d+

%x, %X

[-+]?(0[xX])?[\dA-Fa-f]+

To extract the filename and numbers from a string like

/usr/sbin/sendmail - 0 errors, 4 warnings

you would use a scanf() format like

%s - %d errors, %d warnings

The equivalent regular expression would be

(\S+) - (\d+) errors, (\d+) warnings

search() vs. match()

Python offers two different primitive operations based on regular expressions: re.match() checks for a match only at the beginning of the string, while re.search() checks for a match anywhere in the string (this is what Perl does by default).

For example:

>>> re.match("c", "abcdef")    # No match
>>> re.search("c", "abcdef")   # Match
<re.Match object; span=(2, 3), match='c'>

Regular expressions beginning with '^' can be used with search() to restrict the match at the beginning of the string:

>>> re.match("c", "abcdef")    # No match
>>> re.search("^c", "abcdef")  # No match
>>> re.search("^a", "abcdef")  # Match
<re.Match object; span=(0, 1), match='a'>

Note however that in MULTILINE mode match() only matches at the beginning of the string, whereas using search() with a regular expression beginning with '^' will match at the beginning of each line.

>>> re.match('X', 'A\nB\nX', re.MULTILINE)  # No match
>>> re.search('^X', 'A\nB\nX', re.MULTILINE)  # Match
<re.Match object; span=(4, 5), match='X'>

Making a Phonebook

split() splits a string into a list delimited by the passed pattern. The method is invaluable for converting textual data into data structures that can be easily read and modified by Python as demonstrated in the following example that creates a phonebook.

First, here is the input. Normally it may come from a file, here we are using triple-quoted string syntax:

>>> text = """Ross McFluff: 834.345.1254 155 Elm Street
...
... Ronald Heathmore: 892.345.3428 436 Finley Avenue
... Frank Burger: 925.541.7625 662 South Dogwood Way
...
...
... Heather Albrecht: 548.326.4584 919 Park Place"""

The entries are separated by one or more newlines. Now we convert the string into a list with each nonempty line having its own entry:

>>> entries = re.split("\n+", text)
>>> entries
['Ross McFluff: 834.345.1254 155 Elm Street',
'Ronald Heathmore: 892.345.3428 436 Finley Avenue',
'Frank Burger: 925.541.7625 662 South Dogwood Way',
'Heather Albrecht: 548.326.4584 919 Park Place']

Finally, split each entry into a list with first name, last name, telephone number, and address. We use the maxsplit parameter of split() because the address has spaces, our splitting pattern, in it:

>>> [re.split(":? ", entry, 3) for entry in entries]
[['Ross', 'McFluff', '834.345.1254', '155 Elm Street'],
['Ronald', 'Heathmore', '892.345.3428', '436 Finley Avenue'],
['Frank', 'Burger', '925.541.7625', '662 South Dogwood Way'],
['Heather', 'Albrecht', '548.326.4584', '919 Park Place']]

The :? pattern matches the colon after the last name, so that it does not occur in the result list. With a maxsplit of 4, we could separate the house number from the street name:

>>> [re.split(":? ", entry, 4) for entry in entries]
[['Ross', 'McFluff', '834.345.1254', '155', 'Elm Street'],
['Ronald', 'Heathmore', '892.345.3428', '436', 'Finley Avenue'],
['Frank', 'Burger', '925.541.7625', '662', 'South Dogwood Way'],
['Heather', 'Albrecht', '548.326.4584', '919', 'Park Place']]

Text Munging

sub() replaces every occurrence of a pattern with a string or the result of a function. This example demonstrates using sub() with a function to “munge” text, or randomize the order of all the characters in each word of a sentence except for the first and last characters:

>>> def repl(m):
...     inner_word = list(m.group(2))
...     random.shuffle(inner_word)
...     return m.group(1) + "".join(inner_word) + m.group(3)
>>> text = "Professor Abdolmalek, please report your absences promptly."
>>> re.sub(r"(\w)(\w+)(\w)", repl, text)
'Poefsrosr Aealmlobdk, pslaee reorpt your abnseces plmrptoy.'
>>> re.sub(r"(\w)(\w+)(\w)", repl, text)
'Pofsroser Aodlambelk, plasee reoprt yuor asnebces potlmrpy.'

Finding all Adverbs

findall() matches all occurrences of a pattern, not just the first one as search() does. For example, if a writer wanted to find all of the adverbs in some text, they might use findall() in the following manner:

>>> text = "He was carefully disguised but captured quickly by police."
>>> re.findall(r"\w+ly", text)
['carefully', 'quickly']

Finding all Adverbs and their Positions

If one wants more information about all matches of a pattern than the matched text, finditer() is useful as it provides match objects instead of strings. Continuing with the previous example, if a writer wanted to find all of the adverbs and their positions in some text, they would use finditer() in the following manner:

>>> text = "He was carefully disguised but captured quickly by police."
>>> for m in re.finditer(r"\w+ly", text):
...     print('%02d-%02d: %s' % (m.start(), m.end(), m.group(0)))
07-16: carefully
40-47: quickly

Raw String Notation

Raw string notation (r"text") keeps regular expressions sane. Without it, every backslash ('\') in a regular expression would have to be prefixed with another one to escape it. For example, the two following lines of code are functionally identical:

>>> re.match(r"\W(.)\1\W", " ff ")
<re.Match object; span=(0, 4), match=' ff '>
>>> re.match("\\W(.)\\1\\W", " ff ")
<re.Match object; span=(0, 4), match=' ff '>

When one wants to match a literal backslash, it must be escaped in the regular expression. With raw string notation, this means r"\\". Without raw string notation, one must use "\\\\", making the following lines of code functionally identical:

>>> re.match(r"\\", r"\\")
<re.Match object; span=(0, 1), match='\\'>
>>> re.match("\\\\", r"\\")
<re.Match object; span=(0, 1), match='\\'>

Writing a Tokenizer

A tokenizer or scanner [https://en.wikipedia.org/wiki/Lexical_analysis] analyzes a string to categorize groups of characters. This is a useful first step in writing a compiler or interpreter.

The text categories are specified with regular expressions. The technique is to combine those into a single master regular expression and to loop over successive matches:

import collections
import re

Token = collections.namedtuple('Token', ['type', 'value', 'line', 'column'])

def tokenize(code):
    keywords = {'IF', 'THEN', 'ENDIF', 'FOR', 'NEXT', 'GOSUB', 'RETURN'}
    token_specification = [
        ('NUMBER',   r'\d+(\.\d*)?'),  # Integer or decimal number
        ('ASSIGN',   r':='),           # Assignment operator
        ('END',      r';'),            # Statement terminator
        ('ID',       r'[A-Za-z]+'),    # Identifiers
        ('OP',       r'[+\-*/]'),      # Arithmetic operators
        ('NEWLINE',  r'\n'),           # Line endings
        ('SKIP',     r'[ \t]+'),       # Skip over spaces and tabs
        ('MISMATCH', r'.'),            # Any other character
    ]
    tok_regex = '|'.join('(?P<%s>%s)' % pair for pair in token_specification)
    line_num = 1
    line_start = 0
    for mo in re.finditer(tok_regex, code):
        kind = mo.lastgroup
        value = mo.group()
        column = mo.start() - line_start
        if kind == 'NUMBER':
            value = float(value) if '.' in value else int(value)
        elif kind == 'ID' and value in keywords:
            kind = value
        elif kind == 'NEWLINE':
            line_start = mo.end()
            line_num += 1
            continue
        elif kind == 'SKIP':
            continue
        elif kind == 'MISMATCH':
            raise RuntimeError(f'{value!r} unexpected on line {line_num}')
        yield Token(kind, value, line_num, column)

statements = '''
    IF quantity THEN
        total := total + price * quantity;
        tax := price * 0.05;
    ENDIF;
'''

for token in tokenize(statements):
    print(token)

The tokenizer produces the following output:

Token(type='IF', value='IF', line=2, column=4)
Token(type='ID', value='quantity', line=2, column=7)
Token(type='THEN', value='THEN', line=2, column=16)
Token(type='ID', value='total', line=3, column=8)
Token(type='ASSIGN', value=':=', line=3, column=14)
Token(type='ID', value='total', line=3, column=17)
Token(type='OP', value='+', line=3, column=23)
Token(type='ID', value='price', line=3, column=25)
Token(type='OP', value='*', line=3, column=31)
Token(type='ID', value='quantity', line=3, column=33)
Token(type='END', value=';', line=3, column=41)
Token(type='ID', value='tax', line=4, column=8)
Token(type='ASSIGN', value=':=', line=4, column=12)
Token(type='ID', value='price', line=4, column=15)
Token(type='OP', value='*', line=4, column=21)
Token(type='NUMBER', value=0.05, line=4, column=23)
Token(type='END', value=';', line=4, column=27)
Token(type='ENDIF', value='ENDIF', line=5, column=4)
Token(type='END', value=';', line=5, column=9)

Frie09

Friedl, Jeffrey. Mastering Regular Expressions. 3rd ed., O’Reilly Media, 2009. The third edition of the book no longer covers Python at all, but the first edition covered writing good regular expression patterns in great detail.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

텍스트 처리 서비스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

텍스트 처리 서비스 »

|

difflib — 델타 계산을 위한 도우미

소스 코드: Lib/difflib.py [https://github.com/python/cpython/tree/3.7/Lib/difflib.py]

이 모듈은 시퀀스 비교를 위한 클래스와 함수를 제공합니다. 예를 들어 파일을 비교하는 데 사용할 수 있으며, HTML 및 문맥(context)과 통합(unified) diff를 비롯한 다양한 형식의 차이 정보를 생성할 수 있습니다. 디렉터리와 파일을 비교하려면, filecmp 모듈을 참조하십시오.

class difflib.SequenceMatcher

이것은 시퀀스 요소가 해시 가능이기만 하다면, 모든 형의 시퀀스 쌍을 비교할 수 있는 유연한 클래스입니다. 기본 알고리즘은 1980년대 후반에 Ratcliff와 Obershelp가 ‘게슈탈트 패턴 매칭(gestalt pattern matching)’이라는 과장된 이름으로 발표한 알고리즘까지 거슬러 올라가는데, 그보다는 약간 더 공을 들였습니다. 아이디어는 “정크” 요소가 없는 가장 긴 연속적으로 일치하는 서브 시퀀스를 찾는 것입니다; 이러한 “정크” 요소는 빈 줄이나 공백과 같은 어떤 의미에서는 흥미롭지 않은 요소들입니다. (정크 처리는 Ratcliff와 Obershelp 알고리즘의 확장입니다.) 그런 다음 같은 아이디어를 일치하는 서브 시퀀스의 왼쪽과 오른쪽에 있는 시퀀스 조각에 재귀적으로 적용합니다. 이것이 최소 편집 시퀀스를 산출하지는 않지만, 사람들에게 “그럴듯해 보이는” 일치를 산출하는 경향이 있습니다.

타이밍: 기본 Ratcliff-Obershelp 알고리즘은 최악의 상황(worst case)에 세제곱 시간이고, 평균적으로(expected case) 제곱 시간입니다. SequenceMatcher는 최악의 상황에 제곱 시간이며, 평균적인 동작은 시퀀스에 공통으로 포함된 요소의 수에 따라 복잡한 방식으로 달라집니다; 최상의 경우(best cast)는 선형 시간입니다.

자동 정크 휴리스틱: SequenceMatcher는 특정 시퀀스 항목을 자동으로 정크로 처리하는 경험적 방법을 지원합니다. 경험적 방법은 개별 항목이 시퀀스에 나타나는 횟수를 계산합니다. (첫 번째 항목 이후의) 중복된 항목이 시퀀스의 1% 이상을 차지하고 시퀀스의 길이가 최소 200항목 이상이면, 이 항목은 “흔한” 것으로 표시되고 시퀀스 일치를 위해 정크로 처리됩니다. 이 경험적 방법은 SequenceMatcher를 만들 때 autojunk 인자를 False로 설정하여 끌 수 있습니다.

버전 3.2에 추가: autojunk 매개 변수.

class difflib.Differ

이것은 텍스트 줄의 시퀀스를 비교하고, 사람이 읽을 수 있는 차이 또는 델타를 생성하는 클래스입니다. Differ는 줄의 시퀀스를 비교하고, 유사한 (거의 일치하는) 줄 내의 문자 시퀀스를 비교하는데 SequenceMatcher를 사용합니다.

Differ 델타의 각 줄은 2자 코드로 시작합니다:

코드

뜻

'- '

시퀀스 1에만 있는 줄

'+ '

시퀀스 2에만 있는 줄

'  '

두 시퀀스에 공통인 줄

'? '

두 입력 시퀀스에 없는 줄

‘?’로 시작하는 줄은, 시선을 줄 내의 차이로 유도하려고 시도하며, 두 입력 시퀀스 어디에도 나타나지 않습니다. 이 줄은 시퀀스에 탭 문자가 포함되면 혼동을 줄 수 있습니다.

class difflib.HtmlDiff

이 클래스는 HTML 표를 (또는 표를 포함하는 완전한 HTML 파일을) 만드는 데 사용할 수 있습니다. 이 HTML은 줄 간과 줄 내의 변경을 강조하면서, 텍스트를 나란히 줄 단위로 비교하여 보여줍니다. 표는 전체 또는 문맥 차이 모드로 생성될 수 있습니다.

이 클래스의 생성자는 다음과 같습니다:

__init__(tabsize=8, wrapcolumn=None, linejunk=None, charjunk=IS_CHARACTER_JUNK)

HtmlDiff의 인스턴스를 초기화합니다.

tabsize는 탭 간격을 지정하는 선택적 키워드 인자이며 기본값은 8입니다.

wrapcolumn는 줄이 자동 줄 넘김 되는 열 번호를 지정하는 선택적 키워드로, 줄을 자동 줄 넘김 하지 않는 None이 기본값입니다.

linejunk 와 charjunk는 ndiff()(HtmlDiff가 나란히 배치된 HTML 차이를 만드는 데 사용됩니다)로 전달되는 선택적 키워드 인자입니다. 인자 기본값과 설명은 ndiff() 설명서를 참조하십시오.

다음과 같은 메서드가 공개됩니다:

make_file(fromlines, tolines, fromdesc='', todesc='', context=False, numlines=5, *, charset='utf-8')

fromlines 와 tolines(문자열의 리스트)를 비교하고, 줄 간 및 줄 내부의 변경을 강조하면서, 줄 단위로 차이를 보여주는 표를 포함하는 완전한 HTML 파일을 문자열로 반환합니다.

fromdesc 와 todesc는 from/to 파일 열 헤더 문자열을 지정하는 선택적 키워드 인자입니다 (기본값은 모두 빈 문자열입니다).

context 와 numlines는 모두 선택적 키워드 인자입니다. 문맥 차이를 표시하려면 context를 True로 설정하십시오, 그렇지 않으면 기본값은 전체 파일을 표시하는 False입니다. numlines의 기본값은 5입니다. context가 True 일 때, numlines는 차이 하이라이트를 둘러싸는 문맥 줄의 수를 제어합니다. context가 False면 numlines는 “next” 하이퍼 링크를 사용할 때 차이 하이라이트 앞에 표시되는 줄 수를 제어합니다 (0으로 설정하면 “next” 하이퍼 링크가 다음 차이 하이라이트를 아무런 선행 문맥 줄 없이 브라우저의 맨 위에 놓도록 합니다).

버전 3.5에서 변경: charset 키워드 전용 인자가 추가되었습니다. HTML 문서의 기본 문자 집합이 'ISO-8859-1'에서 'utf-8'로 변경되었습니다.

make_table(fromlines, tolines, fromdesc='', todesc='', context=False, numlines=5)

fromlines 와 tolines(문자열의 리스트)를 비교하고, 줄 간 및 줄 내부의 변경을 강조하면서, 줄 단위로 차이를 보여주는 완전한 HTML 표를 문자열로 반환합니다.

이 메서드의 인자는 make_file() 메서드의 인자와 같습니다.

Tools/scripts/diff.py는 이 클래스의 명령 줄 프런트엔드며, 좋은 사용 예를 담고 있습니다.

difflib.context_diff(a, b, fromfile='', tofile='', fromfiledate='', tofiledate='', n=3, lineterm='\n')

a와 b(문자열의 리스트)를 비교합니다; 델타(델타 줄을 생성하는 제너레이터)를 문맥 diff 형식으로 반환합니다.

문맥 diff는 단지 변경된 줄과 몇 줄의 문맥만을 더해서 표시하는 간결한 방법입니다. 변경 사항은 이전/이후 스타일로 표시됩니다. 문맥 줄의 수는 n에 의해 설정되며 기본값은 3입니다.

기본적으로, diff 제어 줄(***나 ---가 포함된 것)은 끝에 줄 넘김을 붙여 만들어집니다. 이것은 io.IOBase.readlines()로 만들어진 입력이 io.IOBase.writelines()와 함께 사용하기에 적합한 diff를 생성하도록 하는 데 유용합니다. 왜냐하면, 입력과 출력 모두 끝에 줄 넘김이 있기 때문입니다.

끝에 줄 넘김이 없는 입력이면, lineterm 인자를 ""로 설정해서 출력에 일관되게 줄 넘김이 포함되지 않게 하십시오.

문맥 diff 형식에는 일반적으로 파일명과 수정 시간에 대한 헤더가 있습니다. 이들 중 일부 또는 전부는 fromfile, tofile, fromfiledate 및 tofiledate에 문자열을 사용하여 지정될 수 있습니다. 수정 시간은 일반적으로 ISO 8601 형식으로 표현됩니다. 지정하지 않으면, 문자열들의 기본값은 빈 문자열입니다.

>>> s1 = ['bacon\n', 'eggs\n', 'ham\n', 'guido\n']
>>> s2 = ['python\n', 'eggy\n', 'hamster\n', 'guido\n']
>>> sys.stdout.writelines(context_diff(s1, s2, fromfile='before.py', tofile='after.py'))
*** before.py
--- after.py
***************
*** 1,4 ****
! bacon
! eggs
! ham
  guido
--- 1,4 ----
! python
! eggy
! hamster
  guido

더욱 자세한 예제는 difflib의 명령 줄 인터페이스를 참조하십시오.

difflib.get_close_matches(word, possibilities, n=3, cutoff=0.6)

최상의 “충분히 좋은” 일치의 리스트를 반환합니다. word는 근접 일치가 목표로 하는 시퀀스(일반적으로 문자열)며, possibilities는 word와 일치시킬 시퀀스의 리스트입니다 (일반적으로 문자열의 리스트).

선택적 인자 n(기본값 3)은 반환할 근접 일치의 최대 개수입니다; n는 0보다 커야 합니다.

선택적 인자 cutoff(기본값 0.6)는 [0, 1] 범위의 float입니다. word와의 유사성 점수가 이 값보다 적은 possibilities는 무시됩니다.

possibilities 중에서 가장 좋은 (최대 n 개의) 일치가 리스트로 반환되는데, 유사성 점수로 정렬되어 있고 가장 유사한 것이 먼저 나옵니다.

>>> get_close_matches('appel', ['ape', 'apple', 'peach', 'puppy'])
['apple', 'ape']
>>> import keyword
>>> get_close_matches('wheel', keyword.kwlist)
['while']
>>> get_close_matches('pineapple', keyword.kwlist)
[]
>>> get_close_matches('accept', keyword.kwlist)
['except']

difflib.ndiff(a, b, linejunk=None, charjunk=IS_CHARACTER_JUNK)

a와 b(문자열의 리스트)를 비교합니다; Differ-스타일 델타(델타 줄을 생성하는 제너레이터)를 반환합니다.

선택적 키워드 매개 변수 linejunk 와 charjunk는 필터링 함수(또는 None)입니다:

linejunk: 단일 문자열 인자를 받아들이고 문자열이 정크면 참을 반환하고, 그렇지 않으면 거짓을 반환하는 함수입니다. 기본값은 None입니다. 모듈 수준의 함수 IS_LINE_JUNK()도 있는데, 최대로 한 개의 파운드 문자('#')를 제외하고 눈에 보이는 문자가 없는 줄을 걸러냅니다 – 하지만 하부 SequenceMatcher 클래스는 어떤 줄이 잡음으로 볼만큼 자주 등장하는지 동적으로 분석하고, 이것이 보통 이 함수를 사용하는 것보다 효과적입니다.

charjunk: 문자(길이 1의 문자열)를 받아들이고, 문자가 정크면 참을 반환하고, 그렇지 않으면 거짓을 반환하는 함수입니다. 기본값은 모듈 수준의 함수 IS_CHARACTER_JUNK()인데, 공백 문자(스페이스나 탭; 줄 넘김 문자를 포함하는 것은 좋은 생각이 아닙니다)를 걸러냅니다.

Tools/scripts/ndiff.py는 이 함수에 대한 명령 줄 프런트엔드 입니다.

>>> diff = ndiff('one\ntwo\nthree\n'.splitlines(keepends=True),
...              'ore\ntree\nemu\n'.splitlines(keepends=True))
>>> print(''.join(diff), end="")
- one
?  ^
+ ore
?  ^
- two
- three
?  -
+ tree
+ emu

difflib.restore(sequence, which)

델타를 만든 두 시퀀스 중 하나를 반환합니다.

Differ.compare() 나 ndiff()로 만들어진 sequence가 주어지면, 파일 1이나 2(매개 변수 which)에서 원래 제공되었던 줄을 추출하고, 줄 접두어를 제거합니다.

예:

>>> diff = ndiff('one\ntwo\nthree\n'.splitlines(keepends=True),
...              'ore\ntree\nemu\n'.splitlines(keepends=True))
>>> diff = list(diff) # materialize the generated delta into a list
>>> print(''.join(restore(diff, 1)), end="")
one
two
three
>>> print(''.join(restore(diff, 2)), end="")
ore
tree
emu

difflib.unified_diff(a, b, fromfile='', tofile='', fromfiledate='', tofiledate='', n=3, lineterm='\n')

a와 b(문자열의 리스트)를 비교합니다; 델타(델타 줄을 생성하는 제너레이터)를 통합 diff 형식으로 반환합니다.

통합(unified) diff는 단지 변경된 줄과 몇 줄의 문맥만을 더해서 표시하는 간결한 방법입니다. 변경 사항은 (별도의 이전/이후 블록 대신) 인라인 스타일로 표시됩니다. 문맥 줄의 수는 n에 의해 설정되며 기본값은 3입니다.

기본적으로, diff 제어 줄(---, +++ 또는 @@가 포함된 것)은 끝에 줄 넘김을 붙여 만들어집니다. 이것은 io.IOBase.readlines()로 만들어진 입력이 io.IOBase.writelines()와 함께 사용하기에 적합한 diff를 생성하도록 하는 데 유용합니다. 왜냐하면, 입력과 출력 모두 끝에 줄 넘김이 있기 때문입니다.

끝에 줄 넘김이 없는 입력이면, lineterm 인자를 ""로 설정해서 출력에 일관되게 줄 넘김이 포함되지 않게 하십시오.

문맥 diff 형식에는 일반적으로 파일명과 수정 시간에 대한 헤더가 있습니다. 이들 중 일부 또는 전부는 fromfile, tofile, fromfiledate 및 tofiledate에 문자열을 사용하여 지정될 수 있습니다. 수정 시간은 일반적으로 ISO 8601 형식으로 표현됩니다. 지정하지 않으면, 문자열들의 기본값은 빈 문자열입니다.

>>> s1 = ['bacon\n', 'eggs\n', 'ham\n', 'guido\n']
>>> s2 = ['python\n', 'eggy\n', 'hamster\n', 'guido\n']
>>> sys.stdout.writelines(unified_diff(s1, s2, fromfile='before.py', tofile='after.py'))
--- before.py
+++ after.py
@@ -1,4 +1,4 @@
-bacon
-eggs
-ham
+python
+eggy
+hamster
 guido

더욱 자세한 예제는 difflib의 명령 줄 인터페이스를 참조하십시오.

difflib.diff_bytes(dfunc, a, b, fromfile=b'', tofile=b'', fromfiledate=b'', tofiledate=b'', n=3, lineterm=b'\n')

a와 b(바이트열 객체의 리스트)를 dfunc를 사용하여 비교합니다; dfunc가 반환하는 형식으로 델타 줄(역시 바이트열)의 시퀀스를 산출합니다. dfunc는 콜러블이어야하며, 보통 unified_diff() 나 context_diff()입니다.

알 수 없거나 일관성 없는 인코딩의 데이터를 비교할 수 있게 합니다. n를 제외한 모든 입력은 바이트열 객체여야 합니다, str이 아닙니다. 모든 입력(n 제외)을 str로 무손실 변환하고, dfunc(a, b, fromfile, tofile, fromfiledate, tofiledate, n, lineterm)를 호출하는 방식으로 작동합니다. dfunc의 출력은 다시 바이트로 변환되므로, 여러분이 얻는 델타 줄은 a와 b 처럼 알 수 없고/일관성 없는 인코딩을 갖습니다.

버전 3.5에 추가.

difflib.IS_LINE_JUNK(line)

Return True for ignorable lines. The line line is ignorable if line is blank or contains a single '#', otherwise it is not ignorable. Used as a default for parameter linejunk in ndiff() in older versions.

difflib.IS_CHARACTER_JUNK(ch)

Return True for ignorable characters. The character ch is ignorable if ch is a space or tab, otherwise it is not ignorable. Used as a default for parameter charjunk in ndiff().

더 보기

Pattern Matching: The Gestalt Approach [http://www.drdobbs.com/database/pattern-matching-the-gestalt-approach/184407970]

John W. Ratcliff와 D. E. Metzener의 비슷한 알고리즘에 관한 토론. 이것은 1988년 7월 Dr. Dobb’s Journal [http://www.drdobbs.com/]에 출판되었습니다.

SequenceMatcher 객체

SequenceMatcher 클래스는 다음과 같은 생성자를 갖습니다:

class difflib.SequenceMatcher(isjunk=None, a='', b='', autojunk=True)

Optional argument isjunk must be None (the default) or a one-argument function that takes a sequence element and returns true if and only if the element is “junk” and should be ignored. Passing None for isjunk is equivalent to passing lambda x: False; in other words, no elements are ignored. For example, pass:

lambda x: x in " \t"

줄을 문자의 시퀀스로 비교하고, 스페이스와 탭을 무시하고 싶으면, 위와 같은 것을 전달하면 됩니다.

선택적 인자 a 와 b는 비교할 시퀀스입니다; 둘 다 빈 문자열이 기본값입니다. 두 시퀀스의 요소는 모두 해시 가능해야 합니다.

선택적 인자 autojunk는 자동 정크 휴리스틱을 비활성화하는 데 사용할 수 있습니다.

버전 3.2에 추가: autojunk 매개 변수.

SequenceMatcher 객체는 세 개의 데이터 어트리뷰트를 갖습니다: bjunk는 isjunk가 True 인 b 요소의 집합입니다; bpopular는 휴리스틱(비활성화하지 않았다면)에서 흔하다고 판단되는 정크가 아닌 요소의 집합입니다; b2j는 b의 나머지 요소를 그들이 나타난 위치의 리스트로 매핑하는 dict입니다. b가 set_seqs() 나 set_seq2()로 재설정 될 때마다 세 개 모두 재설정됩니다.

버전 3.2에 추가: bjunk 및 bpopular 어트리뷰트

SequenceMatcher 객체에는 다음과 같은 메서드가 있습니다:

set_seqs(a, b)

비교할 두 시퀀스를 설정합니다.

SequenceMatcher는 두 번째 시퀀스에 대한 자세한 정보를 계산하고 캐시 하므로, 많은 시퀀스에 대해 하나의 시퀀스를 비교하려면, set_seq2()를 사용하여 자주 사용되는 시퀀스를 한 번 설정하고, set_seq1()를 다른 시퀀스 각각에 대해 한 번 반복적으로 호출하십시오.

set_seq1(a)

비교할 첫 번째 시퀀스를 설정합니다. 비교할 두 번째 시퀀스는 변경되지 않습니다.

set_seq2(b)

비교할 두 번째 시퀀스를 설정합니다. 비교할 첫 번째 시퀀스는 변경되지 않습니다.

find_longest_match(alo, ahi, blo, bhi)

a[alo:ahi] 와 b[blo:bhi]에서 가장 긴 일치 블록을 찾습니다.

isjunk가 생략되거나 None 이면, find_longest_match()는 a[i:i+k]가 b[j:j+k]와 같은 (i, j, k)를 반환하는데, 여기서 alo <= i <= i+k <= ahi 이고 blo <= j <= j+k <= bhi 입니다. 이 조건을 만족시키는 모든 (i', j', k')에 대해, 추가 조건 k >= k', i <= i' 와 i == i' 면 j <= j' 도 만족합니다. 즉, 모든 최대 일치 블록 중에서 a에서 가장 먼저 시작하는 블록을 반환하고, a에서 가장 먼저 시작하는 모든 최대 일치 블록 중에서 b에서 가장 먼저 시작하는 블록을 반환합니다.

>>> s = SequenceMatcher(None, " abcd", "abcd abcd")
>>> s.find_longest_match(0, 5, 0, 9)
Match(a=0, b=4, size=5)

isjunk가 제공되면, 먼저 가장 긴 일치 블록이 상기와 같이 결정되지만, 정크 요소가 블록에 나타나지 않아야 한다는 추가 제약이 있습니다. 그런 다음 그 블록의 좌우에서 정크 요소만 일치시켜 가능한 한 최대로 확장합니다. 그래서 결과 블록은 흥미로운 일치와 인접하게 같은 정크가 등장할 때를 제외하고는, 정크와 일치하지 않습니다.

여기에 이전과 같은 예가 있지만, 스페이스를 정크로 간주합니다. 이렇게 하면 ' abcd'가 두 번째 시퀀스의 끝에 있는 ' abcd'와 직접 일치하지 않게 됩니다. 대신 'abcd' 만 일치 할 수 있으며, 두 번째 시퀀스에서 가장 왼쪽의 'abcd'와 일치합니다:

>>> s = SequenceMatcher(lambda x: x==" ", " abcd", "abcd abcd")
>>> s.find_longest_match(0, 5, 0, 9)
Match(a=1, b=0, size=4)

일치하는 블록이 없으면 (alo, blo, 0)를 반환합니다.

이 메서드는 네임드 튜플 Match(a, b, size)를 반환합니다.

get_matching_blocks()

중첩하지 않는 일치하는 서브 시퀀스를 기술하는 3-튜플의 리스트를 반환합니다. 각 3-튜플은 (i, j, n) 형식이며, a[i:i+n] == b[j:j+n]를 뜻합니다. 3-튜플은 i와 j에 대해 단조 증가합니다.

마지막 3-튜플은 더미이며, (len(a), len(b), 0) 값을 가집니다. n == 0 인 유일한 3-튜플입니다. (i, j, n)와 (i', j', n')가 리스트에서 인접한 3-튜플이고, 두 번째가 리스트의 마지막 3-튜플이 아니면 i+n < i' 또는 j+n < j'입니다; 즉, 인접 3-튜플은 항상 인접하지 않은 같은 블록을 나타냅니다.

>>> s = SequenceMatcher(None, "abxcd", "abcd")
>>> s.get_matching_blocks()
[Match(a=0, b=0, size=2), Match(a=3, b=2, size=2), Match(a=5, b=4, size=0)]

get_opcodes()

a를 b로 변환하는 방법을 설명하는 5-튜플의 리스트를 반환합니다. 각 튜플은 (tag, i1, i2, j1, j2) 형식입니다. 첫 번째 튜플은 i1 == j1 == 0 이고, 나머지 튜플에서는 i1이 이전 튜플의 i2와 같고, 마찬가지로 j1은 이전 j2와 같습니다.

tag 값은 문자열이고, 이런 의미입니다:

값

뜻

'replace'

a[i1:i2]를 b[j1:j2]로 치환해야 합니다.

'delete'

a[i1:i2]를 삭제해야 합니다. 이때 j1 == j2 임을 유의하십시오.

'insert'

b[j1:j2]을 a[i1:i1]에 삽입해야 합니다. 이때 i1 == i2 임을 유의하십시오.

'equal'

a[i1:i2] == b[j1:j2] (서브 시퀀스가 같습니다).

예를 들면:

>>> a = "qabxcd"
>>> b = "abycdf"
>>> s = SequenceMatcher(None, a, b)
>>> for tag, i1, i2, j1, j2 in s.get_opcodes():
...     print('{:7}   a[{}:{}] --> b[{}:{}] {!r:>8} --> {!r}'.format(
...         tag, i1, i2, j1, j2, a[i1:i2], b[j1:j2]))
delete    a[0:1] --> b[0:0]      'q' --> ''
equal     a[1:3] --> b[0:2]     'ab' --> 'ab'
replace   a[3:4] --> b[2:3]      'x' --> 'y'
equal     a[4:6] --> b[3:5]     'cd' --> 'cd'
insert    a[6:6] --> b[5:6]       '' --> 'f'

get_grouped_opcodes(n=3)

최대 n 줄의 문맥을 갖는 그룹의 제너레이터를 반환합니다.

get_opcodes()에서 반환된 그룹으로 출발해서, 이 메서드는 더 작은 변경 클러스터로 나누고, 변경 사항이 없는 중간 범위를 제거합니다.

그룹은 get_opcodes()와 같은 형식으로 반환됩니다.

ratio()

[0, 1]의 범위의 float로 시퀀스 유사성 척도를 돌려줍니다.

T가 두 시퀀스의 요소의 총 개수이고, M은 일치 개수일 때, 척도는 2.0*M / T입니다. 시퀀스가 같으면 1.0이고, 공통 요소가 없으면 0.0입니다.

get_matching_blocks() 나 get_opcodes()가 아직 호출되지 않았으면, 계산하는 데 비용이 많이 듭니다. 이럴 때, quick_ratio() 나 real_quick_ratio()를 먼저 시도하여 상한값을 얻을 수 있습니다.

참고

Caution: The result of a ratio() call may depend on the order of the arguments. For instance:

>>> SequenceMatcher(None, 'tide', 'diet').ratio()
0.25
>>> SequenceMatcher(None, 'diet', 'tide').ratio()
0.5

quick_ratio()

비교적 빨리 ratio()의 상한을 반환합니다.

real_quick_ratio()

아주 빨리 ratio()의 상한을 반환합니다.

총 문자 수에 대한 일치 비율을 반환하는 세 가지 메서드는 서로 다른 수준의 근삿값 때문에 다른 결과를 줄 수 있습니다. 하지만 quick_ratio() 와 real_quick_ratio()는 항상 최소한 ratio()만큼 큰 값을 줍니다:

>>> s = SequenceMatcher(None, "abcd", "bcde")
>>> s.ratio()
0.75
>>> s.quick_ratio()
0.75
>>> s.real_quick_ratio()
1.0

SequenceMatcher 예제

이 예제에서는 공백을 “정크”로 간주하여, 두 문자열을 비교합니다:

>>> s = SequenceMatcher(lambda x: x == " ",
...                     "private Thread currentThread;",
...                     "private volatile Thread currentThread;")

ratio()는 [0, 1] 범위의 float를 반환하여, 시퀀스의 유사성을 측정합니다. 경험적으로, ratio() 값이 0.6 이상이면 시퀀스가 근접하게 일치함을 뜻합니다:

>>> print(round(s.ratio(), 3))
0.866

시퀀스가 일치하는 부분에만 관심이 있다면, get_matching_blocks()가 유용합니다:

>>> for block in s.get_matching_blocks():
...     print("a[%d] and b[%d] match for %d elements" % block)
a[0] and b[0] match for 8 elements
a[8] and b[17] match for 21 elements
a[29] and b[38] match for 0 elements

get_matching_blocks()에 의해 반환된 마지막 튜플은 항상 더미인 (len(a), len(b), 0)이며, 이는 마지막 튜플 요소(일치하는 요소의 수)가 0 인 유일한 경우입니다.

첫 번째 시퀀스를 두 번째 시퀀스로 변경하는 방법을 알고 싶다면, get_opcodes()를 사용하십시오:

>>> for opcode in s.get_opcodes():
...     print("%6s a[%d:%d] b[%d:%d]" % opcode)
 equal a[0:8] b[0:8]
insert a[8:8] b[8:17]
 equal a[8:29] b[17:38]

더 보기

이 모듈의 get_close_matches() 함수는 SequenceMatcher를 사용한 간단한 코드 작성을 통해 유용한 작업을 수행하는 방법을 보여줍니다.

SequenceMatcher로 만들어진 작은 응용 프로그램을 위한 간단한 버전 관리 조리법 [https://code.activestate.com/recipes/576729/].

Differ 객체

Differ가 만든 델타는 최소 diff라고 주장하지 않음에 유의하십시오. 반대로, 최소 diff는 종종 반 직관적인데, 가능한 모든 곳에서 일치를 취하기 때문입니다. 때로 우발적으로 100페이지가 떨어진 곳에서 일치시키기도 합니다. 동기화 지점을 인접한 일치로 제한하면 가끔 더 긴 diff를 만드는 대신 일종의 지역성을 보존합니다.

Differ 클래스에는 다음과 같은 생성자가 있습니다:

class difflib.Differ(linejunk=None, charjunk=None)

선택적 키워드 매개 변수 linejunk 와 charjunk는 필터 함수(또는 None)를 위한 것입니다:

linejunk: 단일 문자열 인자를 받아들이고 문자열이 정크면 참을 반환하는 함수입니다. 기본값은 None이며, 이는 어떤 줄도 정크로 간주하지 않음을 의미합니다.

charjunk: 문자(길이 1의 문자열)를 받아들이고, 문자가 정크면 참을 반환하는 함수입니다. 기본값은 None이며, 이는 어떤 문자도 정크로 간주하지 않음을 의미합니다.

이러한 정크 필터링 함수는 차이점을 찾기 위한 일치 속도를 높이고 차이가 나는 줄이나 문자를 무시하지 않습니다. 설명이 필요하면 find_longest_match() 메서드의 isjunk 매개 변수에 대한 설명을 읽으십시오.

Differ 객체는 단일 메서드를 통해 사용됩니다 (델타가 만들어집니다):

compare(a, b)

줄의 시퀀스 두 개를 비교하고, 델타(줄의 시퀀스)를 만듭니다.

각 시퀀스는 줄 넘김으로 끝나는 개별 단일 줄 문자열을 포함해야 합니다. 이러한 시퀀스는 파일류 객체의 readlines() 메서드로 얻을 수 있습니다. 생성된 델타 역시 파일류 객체의 writelines() 메서드를 통해 그대로 인쇄될 수 있도록 줄 넘김으로 끝나는 문자열로 구성됩니다.

Differ 예제

이 예제는 두 개의 텍스트를 비교합니다. 먼저 텍스트를 설정하는데, 줄 넘김 문자로 끝나는 개별 단일 줄 문자열의 시퀀스입니다 (이러한 시퀀스는 파일류 객체의 readlines() 메서드로도 얻을 수 있습니다):

>>> text1 = '''  1. Beautiful is better than ugly.
...   2. Explicit is better than implicit.
...   3. Simple is better than complex.
...   4. Complex is better than complicated.
... '''.splitlines(keepends=True)
>>> len(text1)
4
>>> text1[0][-1]
'\n'
>>> text2 = '''  1. Beautiful is better than ugly.
...   3.   Simple is better than complex.
...   4. Complicated is better than complex.
...   5. Flat is better than nested.
... '''.splitlines(keepends=True)

다음으로 Differ 객체의 인스턴스를 만듭니다:

>>> d = Differ()

Differ 객체의 인스턴스를 만들 때, 줄과 문자 “정크”를 필터링하는 함수를 전달할 수 있음에 유의하십시오. 자세한 내용은 Differ() 생성자를 참조하십시오.

마지막으로, 두 개를 비교합니다:

>>> result = list(d.compare(text1, text2))

result는 문자열의 리스트이므로, 예쁜 인쇄를 해봅시다:

>>> from pprint import pprint
>>> pprint(result)
['    1. Beautiful is better than ugly.\n',
 '-   2. Explicit is better than implicit.\n',
 '-   3. Simple is better than complex.\n',
 '+   3.   Simple is better than complex.\n',
 '?     ++\n',
 '-   4. Complex is better than complicated.\n',
 '?            ^                     ---- ^\n',
 '+   4. Complicated is better than complex.\n',
 '?           ++++ ^                      ^\n',
 '+   5. Flat is better than nested.\n']

여러 줄이 포함된 하나의 문자열로 만들면 이렇게 보입니다:

>>> import sys
>>> sys.stdout.writelines(result)
    1. Beautiful is better than ugly.
-   2. Explicit is better than implicit.
-   3. Simple is better than complex.
+   3.   Simple is better than complex.
?     ++
-   4. Complex is better than complicated.
?            ^                     ---- ^
+   4. Complicated is better than complex.
?           ++++ ^                      ^
+   5. Flat is better than nested.

difflib의 명령 줄 인터페이스

이 예제는 difflib를 사용하여 diff와 유사한 유틸리티를 만드는 방법을 보여줍니다. 이것은 파이썬 소스 배포판에 Tools/scripts/diff.py로 포함되어 있습니다.

#!/usr/bin/env python3
""" Command line interface to difflib.py providing diffs in four formats:

* ndiff:    lists every line and highlights interline changes.
* context:  highlights clusters of changes in a before/after format.
* unified:  highlights clusters of changes in an inline format.
* html:     generates side by side comparison with change highlights.

"""

import sys, os, difflib, argparse
from datetime import datetime, timezone

def file_mtime(path):
    t = datetime.fromtimestamp(os.stat(path).st_mtime,
                               timezone.utc)
    return t.astimezone().isoformat()

def main():

    parser = argparse.ArgumentParser()
    parser.add_argument('-c', action='store_true', default=False,
                        help='Produce a context format diff (default)')
    parser.add_argument('-u', action='store_true', default=False,
                        help='Produce a unified format diff')
    parser.add_argument('-m', action='store_true', default=False,
                        help='Produce HTML side by side diff '
                             '(can use -c and -l in conjunction)')
    parser.add_argument('-n', action='store_true', default=False,
                        help='Produce a ndiff format diff')
    parser.add_argument('-l', '--lines', type=int, default=3,
                        help='Set number of context lines (default 3)')
    parser.add_argument('fromfile')
    parser.add_argument('tofile')
    options = parser.parse_args()

    n = options.lines
    fromfile = options.fromfile
    tofile = options.tofile

    fromdate = file_mtime(fromfile)
    todate = file_mtime(tofile)
    with open(fromfile) as ff:
        fromlines = ff.readlines()
    with open(tofile) as tf:
        tolines = tf.readlines()

    if options.u:
        diff = difflib.unified_diff(fromlines, tolines, fromfile, tofile, fromdate, todate, n=n)
    elif options.n:
        diff = difflib.ndiff(fromlines, tolines)
    elif options.m:
        diff = difflib.HtmlDiff().make_file(fromlines,tolines,fromfile,tofile,context=options.c,numlines=n)
    else:
        diff = difflib.context_diff(fromlines, tolines, fromfile, tofile, fromdate, todate, n=n)

    sys.stdout.writelines(diff)

if __name__ == '__main__':
    main()

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

텍스트 처리 서비스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

텍스트 처리 서비스 »

|

textwrap — 텍스트 래핑과 채우기

소스 코드: Lib/textwrap.py [https://github.com/python/cpython/tree/3.7/Lib/textwrap.py]

textwrap 모듈은 모든 작업을 수행하는 클래스인 TextWrapper뿐만 아니라 몇 가지 편리 함수도 제공합니다. 한두 개의 텍스트 문자열을 래핑(wrapping)하거나 채운(filling)다면, 편리 함수로도 충분해야 합니다; 그렇지 않으면 효율을 위해 TextWrapper 인스턴스를 사용해야 합니다.

textwrap.wrap(text, width=70, **kwargs)

text(문자열)에 있는 단일 문단을 래핑해서 모든 줄의 길이가 최대 width 자가 되도록 합니다. 최종 줄 바꿈이 없는 출력 줄의 리스트를 반환합니다.

선택적 키워드 인자는 아래에 설명된 TextWrapper의 인스턴스 어트리뷰트에 해당합니다. width의 기본값은 70입니다.

wrap() 작동 방식에 대한 자세한 내용은 TextWrapper.wrap() 메서드를 참조하십시오.

textwrap.fill(text, width=70, **kwargs)

text에 있는 단일 문단을 래핑하고, 래핑 된 문단을 포함하는 단일 문자열을 반환합니다. fill()은 다음의 줄임 표현입니다

"\n".join(wrap(text, ...))

특히, fill()은 wrap()과 같은 키워드 인자를 받아들입니다.

textwrap.shorten(text, width, **kwargs)

주어진 width에 맞게 주어진 text를 축약하거나 자릅니다.

먼저 text에 있는 공백이 축약됩니다 (모든 공백이 단일 스페이스로 치환됩니다). 결과가 width에 맞으면 반환됩니다. 그렇지 않으면, 나머지 단어와 placeholder가 width 내에 맞도록 충분한 단어가 끝에서 삭제됩니다:

>>> textwrap.shorten("Hello  world!", width=12)
'Hello world!'
>>> textwrap.shorten("Hello  world!", width=11)
'Hello [...]'
>>> textwrap.shorten("Hello world", width=10, placeholder="...")
'Hello...'

선택적 키워드 인자는 아래에 설명된 TextWrapper의 인스턴스 어트리뷰트에 해당합니다. 텍스트가 TextWrapper fill() 함수에 전달되기 전에 공백이 축약되므로, tabsize, expand_tabs, drop_whitespace 및 replace_whitespace 값을 변경하는 것은 아무 효과가 없음에 유의하십시오.

버전 3.4에 추가.

textwrap.dedent(text)

text의 모든 줄에서 같은 선행 공백을 제거합니다.

이것은 삼중 따옴표로 묶은 문자열을 소스 코드에서 여전히 들여쓰기 된 형태로 제시하면서, 디스플레이의 왼쪽 가장자리에 맞추는 데 사용할 수 있습니다.

탭과 공백은 모두 공백으로 처리되지만, 이들이 같지 않음에 유의하십시오: "  hello"와 "\thello" 줄에는 공통 선행 공백이 없는 것으로 간주합니다.

Lines containing only whitespace are ignored in the input and normalized to a single newline character in the output.

예를 들면:

def test():
    # end first line with \ to avoid the empty line!
    s = '''\
    hello
      world
    '''
    print(repr(s))          # prints '    hello\n      world\n    '
    print(repr(dedent(s)))  # prints 'hello\n  world\n'

textwrap.indent(text, prefix, predicate=None)

text에서 선택된 줄의 시작 부분에 prefix를 추가합니다.

text.splitlines(True)를 호출하여 줄을 분할합니다.

기본적으로, prefix는 공백으로만 구성되지 않는 모든 줄(마지막 줄 포함)에 추가됩니다.

예를 들면:

>>> s = 'hello\n\n \nworld'
>>> indent(s, '  ')
'  hello\n\n \n  world'

선택적 predicate 인자는 어떤 줄을 들여쓰기할지 제어하는 데 사용될 수 있습니다. 예를 들어, 빈 줄과 공백만 있는 줄에도 prefix를 추가하기는 쉽습니다:

>>> print(indent(s, '+ ', lambda line: True))
+ hello
+
+
+ world

버전 3.3에 추가.

wrap(), fill() 및 shorten()은 TextWrapper 인스턴스를 만들고 그것의 단일 메서드를 호출하여 작동합니다. 이 인스턴스는 재사용되지 않기 때문에, wrap() 및/또는 fill()을 사용하여 많은 텍스트 문자열을 처리하는 응용 프로그램의 경우, 여러분 자신의 TextWrapper 객체를 만드는 것이 더 효율적일 수 있습니다.

텍스트는 공백과 하이픈이 있는 단어의 하이픈 바로 뒤에서 래핑하는 것을 선호합니다; TextWrapper.break_long_words가 거짓으로 설정되어 있지 않으면 그 후에만 긴 단어를 분할합니다.

class textwrap.TextWrapper(**kwargs)

TextWrapper 생성자는 여러 개의 선택적 키워드 인자를 받아들입니다. 각 키워드 인자는 인스턴스 어트리뷰트에 해당합니다, 그래서 예를 들면

wrapper = TextWrapper(initial_indent="* ")

는 다음과 같습니다

wrapper = TextWrapper()
wrapper.initial_indent = "* "

같은 TextWrapper 객체를 여러 번 재사용 할 수 있으며, 사용 도중 인스턴스 어트리뷰트에 직접 대입하여 옵션을 변경할 수 있습니다.

TextWrapper 인스턴스 어트리뷰트(와 생성자에 대한 키워드 인자)는 다음과 같습니다:

width

(기본값: 70) 래핑 된 줄의 최대 길이. 입력 텍스트에 width보다 긴 개별 단어가 없는 한, TextWrapper는 width 문자보다 긴 출력 줄이 없음을 보장합니다.

expand_tabs

(기본값: True) 참이면, text의 모든 탭 문자가 text의 expandtabs() 메서드를 사용하여 스페이스로 확장됩니다.

tabsize

(기본값: 8) expand_tabs가 참이면, text의 모든 탭 문자는 현재 열과 주어진 탭 크기에 따라 0개 이상의 스페이스로 확장됩니다.

버전 3.3에 추가.

replace_whitespace

(기본값: True) 참이면, 탭 확장 후 래핑 전에, wrap() 메서드는 각 공백 문자를 단일 스페이스로 치환합니다. 치환되는 공백 문자는 다음과 같습니다: 탭, 줄 바꿈, 세로 탭, 폼 피드 및 캐리지 리턴 ('\t\n\v\f\r').

참고

expand_tabs가 거짓이고 replace_whitespace가 참이면, 각 탭 문자는 단일 스페이스로 치환되는데, 탭 확장과는 다릅니다.

참고

replace_whitespace가 거짓이면, 줄 중간에 줄 바꿈이 나타나서 이상한 결과가 발생할 수 있습니다. 이러한 이유로, 텍스트는 (str.splitlines()나 유사한 것을 사용해서) 문단으로 분할한 후에 별도로 래핑해야 합니다.

drop_whitespace

(기본값: True) 참이면, 모든 줄의 처음과 끝의 공백(래핑 이후 들여쓰기 전)이 삭제됩니다. 문단 시작 부분의 공백은 공백이 아닌 것이 뒤에 오면 삭제되지 않습니다. 삭제되는 공백이 줄 전체를 차지하면, 줄 전체가 삭제됩니다.

initial_indent

(기본값: '') 래핑 된 출력의 첫 번째 줄 앞에 추가될 문자열입니다. 첫 번째 줄의 길이 계산에 포함됩니다. 빈 문자열은 들여 쓰지 않습니다.

subsequent_indent

(기본값: '') 첫 줄을 제외한 래핑 된 출력의 모든 줄 앞에 추가될 문자열입니다. 첫 번째 줄을 제외한 각 줄의 길이 계산에 포함됩니다.

fix_sentence_endings

(기본값: False) 참이면, TextWrapper는 문장의 끝을 감지하고 문장이 항상 정확히 두 개의 스페이스로 분리되도록 만들려고 합니다. 이것은 일반적으로 고정 폭 글꼴의 텍스트에 적합합니다. 그러나, 문장 감지 알고리즘은 불완전합니다: 문장 끝은 '.', '!' 또는 '?' 중 하나가 뒤에 오고, '"'나 "'" 중 하나가 뒤따르는 것도 가능, 그 뒤에 스페이스가 오는 소문자로 구성된다고 가정합니다. 이 알고리즘의 한가지 문제는 다음에 나오는 “Dr.” 와

[...] Dr. Frankenstein's monster [...]

다음에 나오는 “Spot.” 사이의 차이점을 탐지할 수 없다는 것입니다

[...] See Spot. See Spot run [...]

fix_sentence_endings는 기본적으로 거짓입니다.

Since the sentence detection algorithm relies on string.lowercase for the definition of “lowercase letter”, and a convention of using two spaces after a period to separate sentences on the same line, it is specific to English-language texts.

break_long_words

(기본값: True) 참이면, width보다 긴 줄이 없도록 하기 위해, width보다 긴 단어를 분할합니다. 거짓이면, 긴 단어가 깨지지 않으며, 일부 줄이 width보다 길 수 있습니다. (width를 초과하는 양을 최소화하기 위해 긴 단어는 독립된 줄에 넣습니다.)

break_on_hyphens

(기본값: True) 참이면, 래핑이, 영어에서의 관례대로, 공백과 복합 단어의 하이픈 바로 뒤에서 발생합니다. 거짓이면, 공백만을 줄 바꿈을 위한 좋은 장소로 간주하지만, 진정한 분할되지 않는 단어를 원한다면 break_long_words를 거짓으로 설정해야 합니다. 이전 버전의 기본 동작은 항상 하이픈으로 연결된 단어를 분리 할 수 있게 하는 것이었습니다.

max_lines

(기본값: None) None이 아니면, 출력은 최대 max_lines 줄을 포함하고, placeholder가 출력 끝에 나타납니다.

버전 3.4에 추가.

placeholder

(기본값: ' [...]') 잘렸을 때 출력 텍스트의 끝에 표시할 문자열.

버전 3.4에 추가.

TextWrapper는 모듈 수준 편리 함수와 유사한 몇 가지 공용 메서드도 제공합니다:

wrap(text)

text(문자열)에 있는 한 문단을 모든 줄의 길이가 최대 width 자가 되도록 래핑합니다. 모든 래핑 옵션은 TextWrapper 인스턴스의 인스턴스 어트리뷰트에서 가져옵니다. 최종 줄 바꿈이 없는 출력 줄의 리스트를 반환합니다. 래핑 된 출력에 내용이 없으면 반환된 리스트는 비어 있습니다.

fill(text)

text에 있는 단일 문단을 래핑하고, 래핑 된 문단을 포함하는 단일 문자열을 반환합니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

텍스트 처리 서비스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

텍스트 처리 서비스 »

|

unicodedata — 유니코드 데이터베이스

이 모듈은 모든 유니코드 문자에 대한 문자 속성을 정의하는 유니코드 문자 데이터베이스(UCD – Unicode Character Database)에 대한 액세스를 제공합니다. 이 데이터베이스에 포함된 데이터는 UCD 버전 11.0.0 [http://www.unicode.org/Public/11.0.0/ucd]으로 컴파일됩니다.

The module uses the same names and symbols as defined by Unicode Standard Annex #44, “Unicode Character Database” [https://www.unicode.org/reports/tr44/]. It defines the following functions:

unicodedata.lookup(name)

이름으로 문자를 조회합니다. 지정된 이름의 문자가 발견되면, 대응하는 문자를 돌려줍니다. 발견되지 않으면, KeyError가 발생합니다.

버전 3.3에서 변경: 이름 별칭 1 과 명명된 시퀀스 2 가 추가되었습니다.

unicodedata.name(chr[, default])

chr 문자에 할당된 이름을 문자열로 반환합니다. 이름이 정의되지 않으면, default가 반환되거나, 지정되지 않으면 ValueError가 발생합니다.

unicodedata.decimal(chr[, default])

chr 문자에 할당된 10진수 값을 정수로 반환합니다. 그러한 값이 정의되어 있지 않으면 default가 반환되거나, 지정되지 않으면 ValueError가 발생합니다.

unicodedata.digit(chr[, default])

chr 문자에 할당된 숫자(digit) 값을 정수로 반환합니다. 그러한 값이 정의되어 있지 않으면 default가 반환되거나, 지정되지 않으면 ValueError가 발생합니다.

unicodedata.numeric(chr[, default])

chr 문자에 할당된 수치(numeric value)를 float로 반환합니다. 그러한 값이 정의되어 있지 않으면 default가 반환되거나, 지정되지 않으면 ValueError가 발생합니다.

unicodedata.category(chr)

chr 문자에 할당된 일반 범주(general category)를 문자열로 반환합니다.

unicodedata.bidirectional(chr)

chr 문자에 할당된 양방향 클래스(bidirectional class)를 문자열로 반환합니다. 그러한 값이 정의되어 있지 않으면, 빈 문자열이 반환됩니다.

unicodedata.combining(chr)

chr 문자에 할당된 정준 결합 클래스(canonical combining class)를 정수로 반환합니다. 결합 클래스가 정의되지 않으면 0을 반환합니다.

unicodedata.east_asian_width(chr)

문자 chr에 할당된 동아시아 폭(east asian width)을 문자열로 반환합니다.

unicodedata.mirrored(chr)

문자 chr에 할당된 거울상 속성(mirrored property)을 정수로 반환합니다. 문자가 양방향 텍스트에서 “거울상” 문자로 식별되면 1을 반환하고, 그렇지 않으면 0을 반환합니다.

unicodedata.decomposition(chr)

문자 chr에 할당된 문자 분해 매핑(character decomposition mapping)을 문자열로 반환합니다. 그러한 매핑이 정의되어 있지 않으면 빈 문자열이 반환됩니다.

unicodedata.normalize(form, unistr)

유니코드 문자열 unistr에 대한 정규화 형식(normal form) form을 반환합니다. form의 유효한 값은 ‘NFC’, ‘NFKC’, ‘NFD’ 및 ‘NFKD’ 입니다.

유니코드 표준은 정준 동등성(canonical equivalence) 및 호환 동등성(compatibility equivalence)의 정의를 기반으로, 유니코드 문자열의 다양한 정규화 형식을 정의합니다. 유니코드에서, 여러 문자를 다양한 방법으로 표현할 수 있습니다. 예를 들어, U+00C7 (LATIN CAPITAL LETTER C WITH CEDILLA) 은 시퀀스 U+0043 (LATIN CAPITAL LETTER C) U+0327 (COMBINING CEDILLA) 로도 표현할 수 있습니다.

각 문자에는, 두 개의 정규화 형식이 있습니다: 정규화 형식 C와 정규화 형식 D. 정규화 형식 D(NFD)는 정준 분해라고도 하며, 각 문자를 분해된 형식으로 변환합니다. 정규화 형식 C(NFC)는 먼저 정준 분해를 적용한 다음, 미리 결합한 문자로 다시 조합합니다.

이 두 형식 외에도, 호환 등가성을 기반으로 하는 두 가지 추가 정규화 형식이 있습니다. 유니코드에서는, 일반적으로 다른 문자와 통합되는 특정 문자가 지원됩니다. 예를 들어, U+2160 (ROMAN NUMERAL ONE) 은 U+0049 (LATIN CAPITAL LETTER I) 과 실제로 같습니다. 하지만, 기존 문자 집합(예를 들어, gb2312)과의 호환성을 위해 유니코드에서 지원됩니다.

정규화 형식 KD(NFKD)는 호환 분해를 적용합니다. 즉, 모든 호환 문자를 동등한 것으로 치환합니다. 정규화 형식 KC(NFKC)는 먼저 호환 분해를 적용한 다음, 정준 결합을 적용합니다.

두 개의 유니코드 문자열이 정규화되고, 사람이 보기에 같아 보여도, 하나가 결합한 문자를 갖고 다른 것은 그렇지 않으면, 같다고 비교되지 않을 수 있습니다.

또한, 이 모듈은 다음 상수를 노출합니다:

unicodedata.unidata_version

이 모듈에 사용된 유니코드 데이터베이스의 버전.

unicodedata.ucd_3_2_0

이것은 전체 모듈과 같은 메서드를 가지고 있는 객체이지만, 유니코드 데이터베이스 버전 3.2를 대신 사용합니다. 이 특정 버전의 유니코드 데이터베이스가 필요한 응용 프로그램(가령 IDNA)을 위한 것입니다.

예제:

>>> import unicodedata
>>> unicodedata.lookup('LEFT CURLY BRACKET')
'{'
>>> unicodedata.name('/')
'SOLIDUS'
>>> unicodedata.decimal('9')
9
>>> unicodedata.decimal('a')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: not a decimal
>>> unicodedata.category('A')  # 'L'etter, 'u'ppercase
'Lu'
>>> unicodedata.bidirectional('\u0660') # 'A'rabic, 'N'umber
'AN'

각주

1

http://www.unicode.org/Public/11.0.0/ucd/NameAliases.txt

2

http://www.unicode.org/Public/11.0.0/ucd/NamedSequences.txt

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

텍스트 처리 서비스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

텍스트 처리 서비스 »

|

stringprep — 인터넷 문자열 준비

소스 코드: Lib/stringprep.py [https://github.com/python/cpython/tree/3.7/Lib/stringprep.py]

인터넷에서 무언가(가령 호스트 이름)를 식별할 때, 종종 그러한 식별에 대해 “동등” 비교할 필요가 있습니다. 이 비교가 실행되는 정확한 방법은 응용 프로그램 도메인에 따라 달라질 수 있습니다, 예를 들어 대/소문자를 구분하는지 그렇지 않은지. 또한 “인쇄 가능” 문자로만 구성된 식별만 허용하기 위해, 가능한 식별을 제한해야 할 수도 있습니다.

RFC 3454 [https://tools.ietf.org/html/rfc3454.html]는 인터넷 프로토콜에서 유니코드 문자열을 “준비” 하는 절차를 정의합니다. 문자열을 전선에 전달하기 전에, 준비 절차를 통해 문자열을 처리해서 어떤 정규화된 형식을 갖도록 만듭니다. RFC는 프로파일로 결합할 수 있는 테이블 집합을 정의합니다. 각 프로파일은 사용하는 테이블과 stringprep 절차의 어떤 선택적 부분이 프로파일 일부인지 정의해야 합니다. stringprep 프로파일의 한 가지 예는 국제화된 도메인 이름에 사용되는 nameprep입니다.

stringprep 모듈은 RFC 3454 [https://tools.ietf.org/html/rfc3454.html]의 테이블만 노출합니다. 이러한 테이블은 딕셔너리나 리스트로 표현하기에 매우 크기 때문에, 모듈은 내부적으로 유니코드 문자 데이터베이스를 사용합니다. 모듈 소스 코드 자체는 mkstringprep.py 유틸리티를 사용하여 생성되었습니다.

As a result, these tables are exposed as functions, not as data structures. There are two kinds of tables in the RFC: sets and mappings. For a set, stringprep provides the “characteristic function”, i.e. a function that returns True if the parameter is part of the set. For mappings, it provides the mapping function: given the key, it returns the associated value. Below is a list of all functions available in the module.

stringprep.in_table_a1(code)

code가 tableA.1(유니코드 3.2에서 지정되지 않은 코드 포인트)에 있는지 판별합니다.

stringprep.in_table_b1(code)

code가 tableB.1(일반적으로 아무것도 매핑되지 않습니다)에 있는지 판별합니다.

stringprep.map_table_b2(code)

tableB.2(NFKC와 함께 사용되는 케이스 폴딩용 매핑)에 따라 code의 매핑 된 값을 반환합니다.

stringprep.map_table_b3(code)

tableB.3(정규화가 없는 케이스 폴딩용 매핑)에 따라 code의 매핑 된 값을 반환합니다.

stringprep.in_table_c11(code)

code가 tableC.1.1(ASCII 스페이스 문자)에 있는지 판별합니다.

stringprep.in_table_c12(code)

code가 tableC.1.2(비 ASCII 스페이스 문자)에 있는지 판별합니다.

stringprep.in_table_c11_c12(code)

code가 tableC.1(스페이스 문자, C.1.1과 C.1.2의 합집합)에 있는지 판별합니다.

stringprep.in_table_c21(code)

code가 tableC.2.1(ASCII 제어 문자)에 있는지 판별합니다.

stringprep.in_table_c22(code)

code가 tableC.2.2(비 ASCII 제어 문자)에 있는지 판별합니다.

stringprep.in_table_c21_c22(code)

code가 tableC.2(제어 문자, C.2.1과 C.2.2의 합집합)에 있는지 판별합니다.

stringprep.in_table_c3(code)

code가 tableC.3(개인 사용)에 있는지 판별합니다.

stringprep.in_table_c4(code)

code가 tableC.4(비문자 코드 포인트)에 있는지 판별합니다.

stringprep.in_table_c5(code)

code가 tableC.5(대리 코드)에 있는지 판별합니다.

stringprep.in_table_c6(code)

code가 tableC.6(일반 텍스트에는 부적절)에 있는지 판별합니다.

stringprep.in_table_c7(code)

code가 tableC.7(규범적 표현에는 부적절)에 있는지 판별합니다.

stringprep.in_table_c8(code)

code가 tableC.8(표시 특성 변경 또는 폐지)에 있는지 판별합니다.

stringprep.in_table_c9(code)

code가 tableC.9(문자 태깅)에 있는지 판별합니다.

stringprep.in_table_d1(code)

code가 tableD.1(양방향 특성이 “R”이나 “AL”인 문자)에 있는지 판별합니다.

stringprep.in_table_d2(code)

code가 tableD.2(양방향 특성이 “L”인 문자)에 있는지 판별합니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

텍스트 처리 서비스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

텍스트 처리 서비스 »

|

readline — GNU readline 인터페이스

readline 모듈은 파이썬 인터프리터에서 완성(completion)과 히스토리 파일의 읽기/쓰기를 용이하게 하는 여러 함수를 정의합니다. 이 모듈은 직접 사용하거나, 대화식 프롬프트에서 파이썬 식별자 완성을 지원하는 rlcompleter 모듈을 통해 사용할 수 있습니다. 이 모듈을 사용하여 설정한 내용은 인터프리터의 대화식 프롬프트와 내장 input() 함수가 제공하는 프롬프트의 동작에 영향을 줍니다.

Readline 키 바인딩은 초기화 파일을 통해 구성할 수 있습니다, 일반적으로 홈 디렉터리의 .inputrc. 이 파일의 형식과 허용되는 구성 및 Readline 라이브러리의 기능에 대한 일반적인 정보는 GNU Readline 매뉴얼의 Readline Init File [https://tiswww.cwru.edu/php/chet/readline/rluserman.html#SEC9]을 참조하십시오.

참고

하부 Readline 라이브러리 API는 GNU readline 대신 libedit 라이브러리로 구현될 수 있습니다. macOS에서 readline 모듈은 실행 시간에 사용 중인 라이브러리를 감지합니다.

libedit의 구성 파일은 GNU readline의 구성 파일과 다릅니다. 프로그래밍 방식으로 구성 문자열을 로드하는 경우 readline.__doc__에서 “libedit” 텍스트를 확인하여 GNU readline과 libedit를 구별할 수 있습니다.

macOS에서 editline/libedit readline 에뮬레이션을 사용하는 경우, 홈 디렉터리에 있는 초기화 파일의 이름은 .editrc입니다. 예를 들어, ~/.editrc의 다음 내용은 vi 키 바인딩과 TAB 완성을 켭니다:

python:bind -v
python:bind ^I rl_complete

초기화 파일

다음 함수는 초기화 파일 및 사용자 구성과 관련이 있습니다:

readline.parse_and_bind(string)

string 인자에 제공된 초기화 줄을 실행합니다. 하부 라이브러리에서 rl_parse_and_bind()를 호출합니다.

readline.read_init_file([filename])

readline 초기화 파일을 실행합니다. 기본 파일 이름은 마지막으로 사용한 파일 이름입니다. 하부 라이브러리에서 rl_read_init_file()을 호출합니다.

줄 버퍼

다음 함수는 라인 버퍼에 대해 작용합니다:

readline.get_line_buffer()

줄 버퍼의 현재 내용(하부 라이브러리의 rl_line_buffer)을 반환합니다.

readline.insert_text(string)

줄 버퍼의 커서 위치에 텍스트를 삽입합니다. 하부 라이브러리에서 rl_insert_text()를 호출하지만, 반환 값은 무시합니다.

readline.redisplay()

줄 버퍼의 현재 내용을 반영하도록 화면에 표시되는 내용을 변경합니다. 하부 라이브러리에서 rl_redisplay()를 호출합니다.

히스토리 파일

다음 함수는 히스토리 파일에 대해 작용합니다:

readline.read_history_file([filename])

readline 히스토리 파일을 로드하고, 히스토리 목록에 추가합니다. 기본 파일명은 ~/.history입니다. 하부 라이브러리에서 read_history()를 호출합니다.

readline.write_history_file([filename])

히스토리 목록을 readline 히스토리 파일에 저장하여, 기존 파일을 덮어씁니다. 기본 파일명은 ~/.history입니다. 하부 라이브러리에서 write_history()를 호출합니다.

readline.append_history_file(nelements[, filename])

히스토리의 마지막 nelements 항목을 파일에 추가합니다. 기본 파일명은 ~/.history입니다. 파일이 이미 존재해야 합니다. 하부 라이브러리에서 append_history()를 호출합니다. 이 함수는 파이썬이 이를 지원하는 라이브러리 버전으로 컴파일된 경우에만 존재합니다.

버전 3.5에 추가.

readline.get_history_length()

readline.set_history_length(length)

히스토리 파일에 저장하기 원하는 줄 수를 설정하거나 반환합니다. write_history_file() 함수는 이 값을 사용하여, 하부 라이브러리에서 history_truncate_file()을 호출하여 히스토리 파일을 자릅니다. 음수 값은 제한 없는 히스토리 파일 크기를 의미합니다.

히스토리 목록

다음 함수는 전역 히스토리 목록에 대해 작용합니다:

readline.clear_history()

현재 히스토리를 지웁니다. 하부 라이브러리에서 clear_history()를 호출합니다. 파이썬 함수는 파이썬이 이를 지원하는 라이브러리 버전으로 컴파일된 경우에만 존재합니다.

readline.get_current_history_length()

현재 히스토리에 있는 항목 수를 반환합니다. (이것은 히스토리 파일에 기록될 최대 줄 수를 반환하는 get_history_length()와 다릅니다.)

readline.get_history_item(index)

index에 있는 히스토리 항목의 현재 내용을 반환합니다. 항목 인덱스는 1부터 시작합니다. 하부 라이브러리에서 history_get()을 호출합니다.

readline.remove_history_item(pos)

히스토리에서 위치(pos)로 지정된 히스토리 항목을 제거합니다. 위치는 0부터 시작합니다. 하부 라이브러리에서 remove_history()를 호출합니다.

readline.replace_history_item(pos, line)

위치(pos)로 지정된 히스토리 항목을 line으로 교체합니다. 위치는 0부터 시작합니다. 하부 라이브러리에서 replace_history_entry()를 호출합니다.

readline.add_history(line)

마지막 줄이 입력된 것처럼 히스토리 버퍼에 line을 추가합니다. 하부 라이브러리에서 add_history()를 호출합니다.

readline.set_auto_history(enabled)

readline을 통해 입력을 읽을 때 add_history()에 대한 자동 호출을 활성화 또는 비활성화합니다. enabled 인자는 참일 때 자동 히스토리를 활성화하고, 거짓일 때 자동 기록을 비활성화하는 불리언 값이어야 합니다.

버전 3.6에 추가.

CPython implementation detail: Auto history is enabled by default, and changes to this do not persist across multiple sessions.

시동 훅

readline.set_startup_hook([function])

하부 라이브러리의 rl_startup_hook 콜백에 의해 호출되는 함수를 설정하거나 제거합니다. function이 지정되면 새 훅(hook) 함수로 사용됩니다; 생략되거나 None이면, 이미 설치된 함수가 제거됩니다. 이 훅은 readline이 첫 번째 프롬프트를 인쇄하기 직전에 인자 없이 호출됩니다.

readline.set_pre_input_hook([function])

하부 라이브러리의 rl_pre_input_hook 콜백에 의해 호출되는 함수를 설정하거나 제거합니다. function이 지정되면, 새 훅 함수로 사용됩니다; 생략되거나 None이면, 이미 설치된 함수가 제거됩니다. 이 훅은 첫 번째 프롬프트가 인쇄된 후 readline이 입력 문자를 읽기 시작하기 직전에 인자 없이 호출됩니다. 이 함수는 파이썬이 이를 지원하는 라이브러리 버전으로 컴파일된 경우에만 존재합니다.

완성

다음 함수는 사용자 정의 단어 완성 기능 구현과 관련이 있습니다. 이것은 일반적으로 Tab 키로 작동하며, 입력되는 단어를 제안하고 자동으로 완성할 수 있습니다. 기본적으로, Readline은 대화식 인터프리터를 위해 파이썬 식별자를 완성하는 rlcompleter에서 사용하도록 설정되어 있습니다. readline 모듈을 사용자 정의 완성기와 함께 사용하려면, 다른 단어 구분자 집합을 설정해야 합니다.

readline.set_completer([function])

완성 함수를 설정하거나 제거합니다. function이 지정되면 새 완성 함수로 사용됩니다; 생략하거나 None이면, 이미 설치된 완성 함수가 제거됩니다. 완성 함수는 문자열이 아닌 값을 반환할 때까지 0, 1, 2 등의 state에 대해 function(text, state)로 호출됩니다. text로 시작하는 다음으로 가능한 완성을 반환해야 합니다.

설치된 완성 함수는 하부 라이브러리의 rl_completion_matches()로 전달된 entry_func 콜백에 의해 호출됩니다. text 문자열은 하부 라이브러리의 rl_attempted_completion_function 콜백의 첫 번째 매개 변수로부터 옵니다.

readline.get_completer()

완성 함수나, 완성 함수가 설정되지 않았으면 None을 얻습니다.

readline.get_completion_type()

시도 중인 완성 유형을 가져옵니다. 하부 라이브러리의 rl_completion_type 변수를 정수로 반환합니다.

readline.get_begidx()

readline.get_endidx()

완성 범위(completion scope)의 시작이나 끝 인덱스를 가져옵니다. 이 인덱스는 하부 라이브러리의 rl_attempted_completion_function 콜백에 전달된 start와 end 인자입니다.

readline.set_completer_delims(string)

readline.get_completer_delims()

완성을 위한 단어 구분자를 설정하거나 가져옵니다. 이것들은 완성을 위해 고려할 단어의 시작(완성 범위)을 결정합니다. 이 함수는 하부 라이브러리의 rl_completer_word_break_characters 변수를 액세스합니다.

readline.set_completion_display_matches_hook([function])

완성 표시 함수를 설정하거나 제거합니다. function이 지정되면, 새로운 완성 표시 함수로 사용됩니다; 생략하거나 None이면, 이미 설치된 완성 표시 함수가 제거됩니다. 하부 라이브러리에서 rl_completion_display_matches_hook 콜백을 설정하거나 지웁니다. 완성 표시 함수는 일치를 표시해야 할 때마다 한 번 function(substitution, [matches], longest_match_length)로 호출됩니다.

예제

다음 예는 readline 모듈의 히스토리 읽기와 쓰기 함수를 사용하여 사용자의 홈 디렉터리에서 .python_history라는 이름의 히스토리 파일을 자동으로 로드하고 저장하는 방법을 보여줍니다. 아래 코드는 일반적으로 사용자의 PYTHONSTARTUP 파일에서 대화식 세션 중에 자동으로 실행됩니다.

import atexit
import os
import readline

histfile = os.path.join(os.path.expanduser("~"), ".python_history")
try:
    readline.read_history_file(histfile)
    # default history len is -1 (infinite), which may grow unruly
    readline.set_history_length(1000)
except FileNotFoundError:
    pass

atexit.register(readline.write_history_file, histfile)

이 코드는 실제로 파이썬이 대화형 모드로 실행될 때 자동으로 실행됩니다 (Readline 구성을 참조하십시오).

다음 예는 같은 목표를 달성하지만 새 히스토리를 덧붙이기만 해서 동시적인(concurrent) 대화형 세션을 지원합니다.

import atexit
import os
import readline
histfile = os.path.join(os.path.expanduser("~"), ".python_history")

try:
    readline.read_history_file(histfile)
    h_len = readline.get_current_history_length()
except FileNotFoundError:
    open(histfile, 'wb').close()
    h_len = 0

def save(prev_h_len, histfile):
    new_h_len = readline.get_current_history_length()
    readline.set_history_length(1000)
    readline.append_history_file(new_h_len - prev_h_len, histfile)
atexit.register(save, h_len, histfile)

다음 예는 히스토리 저장/복원을 지원하도록 code.InteractiveConsole 클래스를 확장합니다.

import atexit
import code
import os
import readline

class HistoryConsole(code.InteractiveConsole):
    def __init__(self, locals=None, filename="<console>",
                 histfile=os.path.expanduser("~/.console-history")):
        code.InteractiveConsole.__init__(self, locals, filename)
        self.init_history(histfile)

    def init_history(self, histfile):
        readline.parse_and_bind("tab: complete")
        if hasattr(readline, "read_history_file"):
            try:
                readline.read_history_file(histfile)
            except FileNotFoundError:
                pass
            atexit.register(self.save_history, histfile)

    def save_history(self, histfile):
        readline.set_history_length(1000)
        readline.write_history_file(histfile)

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

텍스트 처리 서비스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

텍스트 처리 서비스 »

|

rlcompleter — GNU readline을 위한 완성 함수

소스 코드: Lib/rlcompleter.py [https://github.com/python/cpython/tree/3.7/Lib/rlcompleter.py]

rlcompleter 모듈은 유효한 파이썬 식별자와 키워드를 완성함으로써 readline 모듈에 적합한 완성 함수를 정의합니다.

readline 모듈을 사용할 수 있는 유닉스 플랫폼에서 이 모듈이 임포트될 때, Completer 클래스의 인스턴스가 자동으로 만들어지고, complete() 메서드가 readline 완성기(completer)로 설정됩니다.

예제:

>>> import rlcompleter
>>> import readline
>>> readline.parse_and_bind("tab: complete")
>>> readline. <TAB PRESSED>
readline.__doc__          readline.get_line_buffer(  readline.read_init_file(
readline.__file__         readline.insert_text(      readline.set_completer(
readline.__name__         readline.parse_and_bind(
>>> readline.

rlcompleter 모듈은 파이썬의 대화형 모드와 함께 사용하도록 설계되었습니다. 파이썬이 -S 옵션으로 실행되지 않는 한, 모듈은 자동으로 임포트되고 구성됩니다 (Readline 구성를 보세요).

readline이 없는 플랫폼에서, 이 모듈이 정의하는 Completer 클래스는 여전히 사용자 정의 목적에 사용될 수 있습니다.

Completer 객체

Completer 객체는 다음과 같은 메서드를 가집니다:

Completer.complete(text, state)

text에 대한 state 번째 완성을 반환합니다.

마침표('.')가 포함되지 않은 text로 호출되면, __main__, builtins 및 키워드(keyword 모듈에서 정의한 대로)에 현재 정의된 이름으로 완성됩니다.

점으로 구분된 이름으로 호출하면, 명백한 부작용(함수는 평가되지 않지만 __getattr__()에 대한 호출을 만들 수 있습니다)없이 마지막 부분까지 평가하려고 시도하고, 나머지는 dir() 함수를 통해 일치하는 것을 찾습니다. 표현식을 평가하는 동안 발생하는 모든 예외는 잡히고, 억제하며 None을 반환합니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

텍스트 처리 서비스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

|

바이너리 데이터 서비스

이 장에서 설명하는 모듈은 바이너리 데이터를 다루기 위한 기본 서비스 연산을 제공합니다. 파일 포맷, 네트워크 프로토콜과 관련 있는 바이너리 데이터에 대한 연산은 관련 절에서 설명합니다.

텍스트 처리 서비스에서 설명한 일부 라이브러리는 ASCII 호환 바이너리 형식 (예를 들면, re) 또는 모든 바이너리 데이터 (예를 들면, difflib)에 사용할 수 있습니다.

또한, 파이썬 내장 바이너리 데이터형에 대한 설명은 바이너리 시퀀스 형 — bytes, bytearray, memoryview 문서를 참고하세요.

struct — Interpret bytes as packed binary data

Functions and Exceptions

Format Strings

Byte Order, Size, and Alignment

Format Characters

Examples

Classes

codecs — Codec registry and base classes

Codec Base Classes

Error Handlers

Stateless Encoding and Decoding

Incremental Encoding and Decoding

IncrementalEncoder Objects

IncrementalDecoder Objects

Stream Encoding and Decoding

StreamWriter Objects

StreamReader Objects

StreamReaderWriter Objects

StreamRecoder Objects

Encodings and Unicode

Standard Encodings

Python Specific Encodings

Text Encodings

Binary Transforms

Text Transforms

encodings.idna — Internationalized Domain Names in Applications

encodings.mbcs — Windows ANSI codepage

encodings.utf_8_sig — UTF-8 codec with BOM signature

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

바이너리 데이터 서비스 »

|

struct — Interpret bytes as packed binary data

Source code: Lib/struct.py [https://github.com/python/cpython/tree/3.7/Lib/struct.py]

This module performs conversions between Python values and C structs represented as Python bytes objects. This can be used in handling binary data stored in files or from network connections, among other sources. It uses Format Strings as compact descriptions of the layout of the C structs and the intended conversion to/from Python values.

참고

By default, the result of packing a given C struct includes pad bytes in order to maintain proper alignment for the C types involved; similarly, alignment is taken into account when unpacking. This behavior is chosen so that the bytes of a packed struct correspond exactly to the layout in memory of the corresponding C struct. To handle platform-independent data formats or omit implicit pad bytes, use standard size and alignment instead of native size and alignment: see Byte Order, Size, and Alignment for details.

Several struct functions (and methods of Struct) take a buffer argument. This refers to objects that implement the 버퍼 프로토콜 and provide either a readable or read-writable buffer. The most common types used for that purpose are bytes and bytearray, but many other types that can be viewed as an array of bytes implement the buffer protocol, so that they can be read/filled without additional copying from a bytes object.

Functions and Exceptions

The module defines the following exception and functions:

exception struct.error

Exception raised on various occasions; argument is a string describing what is wrong.

struct.pack(format, v1, v2, ...)

Return a bytes object containing the values v1, v2, … packed according to the format string format. The arguments must match the values required by the format exactly.

struct.pack_into(format, buffer, offset, v1, v2, ...)

Pack the values v1, v2, … according to the format string format and write the packed bytes into the writable buffer buffer starting at position offset. Note that offset is a required argument.

struct.unpack(format, buffer)

Unpack from the buffer buffer (presumably packed by pack(format, ...)) according to the format string format. The result is a tuple even if it contains exactly one item. The buffer’s size in bytes must match the size required by the format, as reflected by calcsize().

struct.unpack_from(format, buffer, offset=0)

Unpack from buffer starting at position offset, according to the format string format. The result is a tuple even if it contains exactly one item. The buffer’s size in bytes, minus offset, must be at least the size required by the format, as reflected by calcsize().

struct.iter_unpack(format, buffer)

Iteratively unpack from the buffer buffer according to the format string format. This function returns an iterator which will read equally-sized chunks from the buffer until all its contents have been consumed. The buffer’s size in bytes must be a multiple of the size required by the format, as reflected by calcsize().

Each iteration yields a tuple as specified by the format string.

버전 3.4에 추가.

struct.calcsize(format)

Return the size of the struct (and hence of the bytes object produced by pack(format, ...)) corresponding to the format string format.

Format Strings

Format strings are the mechanism used to specify the expected layout when packing and unpacking data. They are built up from Format Characters, which specify the type of data being packed/unpacked. In addition, there are special characters for controlling the Byte Order, Size, and Alignment.

Byte Order, Size, and Alignment

By default, C types are represented in the machine’s native format and byte order, and properly aligned by skipping pad bytes if necessary (according to the rules used by the C compiler).

Alternatively, the first character of the format string can be used to indicate the byte order, size and alignment of the packed data, according to the following table:

Character

Byte order

Size

Alignment

@

native

native

native

=

native

standard

none

<

little-endian

standard

none

>

big-endian

standard

none

!

network (= big-endian)

standard

none

If the first character is not one of these, '@' is assumed.

Native byte order is big-endian or little-endian, depending on the host system. For example, Intel x86 and AMD64 (x86-64) are little-endian; Motorola 68000 and PowerPC G5 are big-endian; ARM and Intel Itanium feature switchable endianness (bi-endian). Use sys.byteorder to check the endianness of your system.

Native size and alignment are determined using the C compiler’s sizeof expression. This is always combined with native byte order.

Standard size depends only on the format character; see the table in the Format Characters section.

Note the difference between '@' and '=': both use native byte order, but the size and alignment of the latter is standardized.

The form '!' is available for those poor souls who claim they can’t remember whether network byte order is big-endian or little-endian.

There is no way to indicate non-native byte order (force byte-swapping); use the appropriate choice of '<' or '>'.

Notes:

Padding is only automatically added between successive structure members. No padding is added at the beginning or the end of the encoded struct.

No padding is added when using non-native size and alignment, e.g. with ‘<’, ‘>’, ‘=’, and ‘!’.

To align the end of a structure to the alignment requirement of a particular type, end the format with the code for that type with a repeat count of zero. See Examples.

Format Characters

Format characters have the following meaning; the conversion between C and Python values should be obvious given their types. The ‘Standard size’ column refers to the size of the packed value in bytes when using standard size; that is, when the format string starts with one of '<', '>', '!' or '='. When using native size, the size of the packed value is platform-dependent.

Format

C Type

Python type

Standard size

Notes

x

pad byte

no value

c

char

bytes of length 1

1

b

signed char

integer

1

(1), (2)

B

unsigned char

integer

1

(2)

?

_Bool

bool

1

(1)

h

short

integer

2

(2)

H

unsigned short

integer

2

(2)

i

int

integer

4

(2)

I

unsigned int

integer

4

(2)

l

long

integer

4

(2)

L

unsigned long

integer

4

(2)

q

long long

integer

8

(2)

Q

unsigned long long

integer

8

(2)

n

ssize_t

integer

(3)

N

size_t

integer

(3)

e

(6)

float

2

(4)

f

float

float

4

(4)

d

double

float

8

(4)

s

char[]

bytes

p

char[]

bytes

P

void *

integer

(5)

버전 3.3에서 변경: Added support for the 'n' and 'N' formats.

버전 3.6에서 변경: Added support for the 'e' format.

Notes:

The '?' conversion code corresponds to the _Bool type defined by C99. If this type is not available, it is simulated using a char. In standard mode, it is always represented by one byte.

When attempting to pack a non-integer using any of the integer conversion codes, if the non-integer has a __index__() method then that method is called to convert the argument to an integer before packing.

버전 3.2에서 변경: Use of the __index__() method for non-integers is new in 3.2.

The 'n' and 'N' conversion codes are only available for the native size (selected as the default or with the '@' byte order character). For the standard size, you can use whichever of the other integer formats fits your application.

For the 'f', 'd' and 'e' conversion codes, the packed representation uses the IEEE 754 binary32, binary64 or binary16 format (for 'f', 'd' or 'e' respectively), regardless of the floating-point format used by the platform.

The 'P' format character is only available for the native byte ordering (selected as the default or with the '@' byte order character). The byte order character '=' chooses to use little- or big-endian ordering based on the host system. The struct module does not interpret this as native ordering, so the 'P' format is not available.

The IEEE 754 binary16 “half precision” type was introduced in the 2008 revision of the IEEE 754 standard [https://en.wikipedia.org/wiki/IEEE_floating_point#IEEE_754-2008]. It has a sign bit, a 5-bit exponent and 11-bit precision (with 10 bits explicitly stored), and can represent numbers between approximately 6.1e-05 and 6.5e+04 at full precision. This type is not widely supported by C compilers: on a typical machine, an unsigned short can be used for storage, but not for math operations. See the Wikipedia page on the half-precision floating-point format [https://en.wikipedia.org/wiki/Half-precision_floating-point_format] for more information.

A format character may be preceded by an integral repeat count. For example, the format string '4h' means exactly the same as 'hhhh'.

Whitespace characters between formats are ignored; a count and its format must not contain whitespace though.

For the 's' format character, the count is interpreted as the length of the bytes, not a repeat count like for the other format characters; for example, '10s' means a single 10-byte string, while '10c' means 10 characters. If a count is not given, it defaults to 1. For packing, the string is truncated or padded with null bytes as appropriate to make it fit. For unpacking, the resulting bytes object always has exactly the specified number of bytes. As a special case, '0s' means a single, empty string (while '0c' means 0 characters).

When packing a value x using one of the integer formats ('b', 'B', 'h', 'H', 'i', 'I', 'l', 'L', 'q', 'Q'), if x is outside the valid range for that format then struct.error is raised.

버전 3.1에서 변경: In 3.0, some of the integer formats wrapped out-of-range values and raised DeprecationWarning instead of struct.error.

The 'p' format character encodes a “Pascal string”, meaning a short variable-length string stored in a fixed number of bytes, given by the count. The first byte stored is the length of the string, or 255, whichever is smaller. The bytes of the string follow. If the string passed in to pack() is too long (longer than the count minus 1), only the leading count-1 bytes of the string are stored. If the string is shorter than count-1, it is padded with null bytes so that exactly count bytes in all are used. Note that for unpack(), the 'p' format character consumes count bytes, but that the string returned can never contain more than 255 bytes.

For the '?' format character, the return value is either True or False. When packing, the truth value of the argument object is used. Either 0 or 1 in the native or standard bool representation will be packed, and any non-zero value will be True when unpacking.

Examples

참고

All examples assume a native byte order, size, and alignment with a big-endian machine.

A basic example of packing/unpacking three integers:

>>> from struct import *
>>> pack('hhl', 1, 2, 3)
b'\x00\x01\x00\x02\x00\x00\x00\x03'
>>> unpack('hhl', b'\x00\x01\x00\x02\x00\x00\x00\x03')
(1, 2, 3)
>>> calcsize('hhl')
8

Unpacked fields can be named by assigning them to variables or by wrapping the result in a named tuple:

>>> record = b'raymond   \x32\x12\x08\x01\x08'
>>> name, serialnum, school, gradelevel = unpack('<10sHHb', record)

>>> from collections import namedtuple
>>> Student = namedtuple('Student', 'name serialnum school gradelevel')
>>> Student._make(unpack('<10sHHb', record))
Student(name=b'raymond   ', serialnum=4658, school=264, gradelevel=8)

The ordering of format characters may have an impact on size since the padding needed to satisfy alignment requirements is different:

>>> pack('ci', b'*', 0x12131415)
b'*\x00\x00\x00\x12\x13\x14\x15'
>>> pack('ic', 0x12131415, b'*')
b'\x12\x13\x14\x15*'
>>> calcsize('ci')
8
>>> calcsize('ic')
5

The following format 'llh0l' specifies two pad bytes at the end, assuming longs are aligned on 4-byte boundaries:

>>> pack('llh0l', 1, 2, 3)
b'\x00\x00\x00\x01\x00\x00\x00\x02\x00\x03\x00\x00'

This only works when native size and alignment are in effect; standard size and alignment does not enforce any alignment.

더 보기

Module array

Packed binary storage of homogeneous data.

Module xdrlib

Packing and unpacking of XDR data.

Classes

The struct module also defines the following type:

class struct.Struct(format)

Return a new Struct object which writes and reads binary data according to the format string format. Creating a Struct object once and calling its methods is more efficient than calling the struct functions with the same format since the format string only needs to be compiled once.

참고

The compiled versions of the most recent format strings passed to Struct and the module-level functions are cached, so programs that use only a few format strings needn’t worry about reusing a single Struct instance.

Compiled Struct objects support the following methods and attributes:

pack(v1, v2, ...)

Identical to the pack() function, using the compiled format. (len(result) will equal size.)

pack_into(buffer, offset, v1, v2, ...)

Identical to the pack_into() function, using the compiled format.

unpack(buffer)

Identical to the unpack() function, using the compiled format. The buffer’s size in bytes must equal size.

unpack_from(buffer, offset=0)

Identical to the unpack_from() function, using the compiled format. The buffer’s size in bytes, minus offset, must be at least size.

iter_unpack(buffer)

Identical to the iter_unpack() function, using the compiled format. The buffer’s size in bytes must be a multiple of size.

버전 3.4에 추가.

format

The format string used to construct this Struct object.

버전 3.7에서 변경: The format string type is now str instead of bytes.

size

The calculated size of the struct (and hence of the bytes object produced by the pack() method) corresponding to format.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

바이너리 데이터 서비스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

바이너리 데이터 서비스 »

|

codecs — Codec registry and base classes

Source code: Lib/codecs.py [https://github.com/python/cpython/tree/3.7/Lib/codecs.py]

This module defines base classes for standard Python codecs (encoders and decoders) and provides access to the internal Python codec registry, which manages the codec and error handling lookup process. Most standard codecs are text encodings, which encode text to bytes, but there are also codecs provided that encode text to text, and bytes to bytes. Custom codecs may encode and decode between arbitrary types, but some module features are restricted to use specifically with text encodings, or with codecs that encode to bytes.

The module defines the following functions for encoding and decoding with any codec:

codecs.encode(obj, encoding='utf-8', errors='strict')

Encodes obj using the codec registered for encoding.

Errors may be given to set the desired error handling scheme. The default error handler is 'strict' meaning that encoding errors raise ValueError (or a more codec specific subclass, such as UnicodeEncodeError). Refer to Codec Base Classes for more information on codec error handling.

codecs.decode(obj, encoding='utf-8', errors='strict')

Decodes obj using the codec registered for encoding.

Errors may be given to set the desired error handling scheme. The default error handler is 'strict' meaning that decoding errors raise ValueError (or a more codec specific subclass, such as UnicodeDecodeError). Refer to Codec Base Classes for more information on codec error handling.

The full details for each codec can also be looked up directly:

codecs.lookup(encoding)

Looks up the codec info in the Python codec registry and returns a CodecInfo object as defined below.

Encodings are first looked up in the registry’s cache. If not found, the list of registered search functions is scanned. If no CodecInfo object is found, a LookupError is raised. Otherwise, the CodecInfo object is stored in the cache and returned to the caller.

class codecs.CodecInfo(encode, decode, streamreader=None, streamwriter=None, incrementalencoder=None, incrementaldecoder=None, name=None)

Codec details when looking up the codec registry. The constructor arguments are stored in attributes of the same name:

name

The name of the encoding.

encode

decode

The stateless encoding and decoding functions. These must be functions or methods which have the same interface as the encode() and decode() methods of Codec instances (see Codec Interface). The functions or methods are expected to work in a stateless mode.

incrementalencoder

incrementaldecoder

Incremental encoder and decoder classes or factory functions. These have to provide the interface defined by the base classes IncrementalEncoder and IncrementalDecoder, respectively. Incremental codecs can maintain state.

streamwriter

streamreader

Stream writer and reader classes or factory functions. These have to provide the interface defined by the base classes StreamWriter and StreamReader, respectively. Stream codecs can maintain state.

To simplify access to the various codec components, the module provides these additional functions which use lookup() for the codec lookup:

codecs.getencoder(encoding)

Look up the codec for the given encoding and return its encoder function.

Raises a LookupError in case the encoding cannot be found.

codecs.getdecoder(encoding)

Look up the codec for the given encoding and return its decoder function.

Raises a LookupError in case the encoding cannot be found.

codecs.getincrementalencoder(encoding)

Look up the codec for the given encoding and return its incremental encoder class or factory function.

Raises a LookupError in case the encoding cannot be found or the codec doesn’t support an incremental encoder.

codecs.getincrementaldecoder(encoding)

Look up the codec for the given encoding and return its incremental decoder class or factory function.

Raises a LookupError in case the encoding cannot be found or the codec doesn’t support an incremental decoder.

codecs.getreader(encoding)

Look up the codec for the given encoding and return its StreamReader class or factory function.

Raises a LookupError in case the encoding cannot be found.

codecs.getwriter(encoding)

Look up the codec for the given encoding and return its StreamWriter class or factory function.

Raises a LookupError in case the encoding cannot be found.

Custom codecs are made available by registering a suitable codec search function:

codecs.register(search_function)

Register a codec search function. Search functions are expected to take one argument, being the encoding name in all lower case letters, and return a CodecInfo object. In case a search function cannot find a given encoding, it should return None.

참고

Search function registration is not currently reversible, which may cause problems in some cases, such as unit testing or module reloading.

While the builtin open() and the associated io module are the recommended approach for working with encoded text files, this module provides additional utility functions and classes that allow the use of a wider range of codecs when working with binary files:

codecs.open(filename, mode='r', encoding=None, errors='strict', buffering=1)

Open an encoded file using the given mode and return an instance of StreamReaderWriter, providing transparent encoding/decoding. The default file mode is 'r', meaning to open the file in read mode.

참고

Underlying encoded files are always opened in binary mode. No automatic conversion of '\n' is done on reading and writing. The mode argument may be any binary mode acceptable to the built-in open() function; the 'b' is automatically added.

encoding specifies the encoding which is to be used for the file. Any encoding that encodes to and decodes from bytes is allowed, and the data types supported by the file methods depend on the codec used.

errors may be given to define the error handling. It defaults to 'strict' which causes a ValueError to be raised in case an encoding error occurs.

buffering has the same meaning as for the built-in open() function. It defaults to line buffered.

codecs.EncodedFile(file, data_encoding, file_encoding=None, errors='strict')

Return a StreamRecoder instance, a wrapped version of file which provides transparent transcoding. The original file is closed when the wrapped version is closed.

Data written to the wrapped file is decoded according to the given data_encoding and then written to the original file as bytes using file_encoding. Bytes read from the original file are decoded according to file_encoding, and the result is encoded using data_encoding.

If file_encoding is not given, it defaults to data_encoding.

errors may be given to define the error handling. It defaults to 'strict', which causes ValueError to be raised in case an encoding error occurs.

codecs.iterencode(iterator, encoding, errors='strict', **kwargs)

Uses an incremental encoder to iteratively encode the input provided by iterator. This function is a generator. The errors argument (as well as any other keyword argument) is passed through to the incremental encoder.

This function requires that the codec accept text str objects to encode. Therefore it does not support bytes-to-bytes encoders such as base64_codec.

codecs.iterdecode(iterator, encoding, errors='strict', **kwargs)

Uses an incremental decoder to iteratively decode the input provided by iterator. This function is a generator. The errors argument (as well as any other keyword argument) is passed through to the incremental decoder.

This function requires that the codec accept bytes objects to decode. Therefore it does not support text-to-text encoders such as rot_13, although rot_13 may be used equivalently with iterencode().

The module also provides the following constants which are useful for reading and writing to platform dependent files:

codecs.BOM

codecs.BOM_BE

codecs.BOM_LE

codecs.BOM_UTF8

codecs.BOM_UTF16

codecs.BOM_UTF16_BE

codecs.BOM_UTF16_LE

codecs.BOM_UTF32

codecs.BOM_UTF32_BE

codecs.BOM_UTF32_LE

These constants define various byte sequences, being Unicode byte order marks (BOMs) for several encodings. They are used in UTF-16 and UTF-32 data streams to indicate the byte order used, and in UTF-8 as a Unicode signature. BOM_UTF16 is either BOM_UTF16_BE or BOM_UTF16_LE depending on the platform’s native byte order, BOM is an alias for BOM_UTF16, BOM_LE for BOM_UTF16_LE and BOM_BE for BOM_UTF16_BE. The others represent the BOM in UTF-8 and UTF-32 encodings.

Codec Base Classes

The codecs module defines a set of base classes which define the interfaces for working with codec objects, and can also be used as the basis for custom codec implementations.

Each codec has to define four interfaces to make it usable as codec in Python: stateless encoder, stateless decoder, stream reader and stream writer. The stream reader and writers typically reuse the stateless encoder/decoder to implement the file protocols. Codec authors also need to define how the codec will handle encoding and decoding errors.

Error Handlers

To simplify and standardize error handling, codecs may implement different error handling schemes by accepting the errors string argument. The following string values are defined and implemented by all standard Python codecs:

Value

Meaning

'strict'

Raise UnicodeError (or a subclass); this is the default. Implemented in strict_errors().

'ignore'

Ignore the malformed data and continue without further notice. Implemented in ignore_errors().

The following error handlers are only applicable to text encodings:

Value

Meaning

'replace'

Replace with a suitable replacement marker; Python will use the official U+FFFD REPLACEMENT CHARACTER for the built-in codecs on decoding, and ‘?’ on encoding. Implemented in replace_errors().

'xmlcharrefreplace'

Replace with the appropriate XML character reference (only for encoding). Implemented in xmlcharrefreplace_errors().

'backslashreplace'

Replace with backslashed escape sequences. Implemented in backslashreplace_errors().

'namereplace'

Replace with \N{...} escape sequences (only for encoding). Implemented in namereplace_errors().

'surrogateescape'

On decoding, replace byte with individual surrogate code ranging from U+DC80 to U+DCFF. This code will then be turned back into the same byte when the 'surrogateescape' error handler is used when encoding the data. (See PEP 383 [https://www.python.org/dev/peps/pep-0383] for more.)

In addition, the following error handler is specific to the given codecs:

Value

Codecs

Meaning

'surrogatepass'

utf-8, utf-16, utf-32, utf-16-be, utf-16-le, utf-32-be, utf-32-le

Allow encoding and decoding of surrogate codes. These codecs normally treat the presence of surrogates as an error.

버전 3.1에 추가: The 'surrogateescape' and 'surrogatepass' error handlers.

버전 3.4에서 변경: The 'surrogatepass' error handlers now works with utf-16* and utf-32* codecs.

버전 3.5에 추가: The 'namereplace' error handler.

버전 3.5에서 변경: The 'backslashreplace' error handlers now works with decoding and translating.

The set of allowed values can be extended by registering a new named error handler:

codecs.register_error(name, error_handler)

Register the error handling function error_handler under the name name. The error_handler argument will be called during encoding and decoding in case of an error, when name is specified as the errors parameter.

For encoding, error_handler will be called with a UnicodeEncodeError instance, which contains information about the location of the error. The error handler must either raise this or a different exception, or return a tuple with a replacement for the unencodable part of the input and a position where encoding should continue. The replacement may be either str or bytes. If the replacement is bytes, the encoder will simply copy them into the output buffer. If the replacement is a string, the encoder will encode the replacement. Encoding continues on original input at the specified position. Negative position values will be treated as being relative to the end of the input string. If the resulting position is out of bound an IndexError will be raised.

Decoding and translating works similarly, except UnicodeDecodeError or UnicodeTranslateError will be passed to the handler and that the replacement from the error handler will be put into the output directly.

Previously registered error handlers (including the standard error handlers) can be looked up by name:

codecs.lookup_error(name)

Return the error handler previously registered under the name name.

Raises a LookupError in case the handler cannot be found.

The following standard error handlers are also made available as module level functions:

codecs.strict_errors(exception)

Implements the 'strict' error handling: each encoding or decoding error raises a UnicodeError.

codecs.replace_errors(exception)

Implements the 'replace' error handling (for text encodings only): substitutes '?' for encoding errors (to be encoded by the codec), and '\ufffd' (the Unicode replacement character) for decoding errors.

codecs.ignore_errors(exception)

Implements the 'ignore' error handling: malformed data is ignored and encoding or decoding is continued without further notice.

codecs.xmlcharrefreplace_errors(exception)

Implements the 'xmlcharrefreplace' error handling (for encoding with text encodings only): the unencodable character is replaced by an appropriate XML character reference.

codecs.backslashreplace_errors(exception)

Implements the 'backslashreplace' error handling (for text encodings only): malformed data is replaced by a backslashed escape sequence.

codecs.namereplace_errors(exception)

Implements the 'namereplace' error handling (for encoding with text encodings only): the unencodable character is replaced by a \N{...} escape sequence.

버전 3.5에 추가.

Stateless Encoding and Decoding

The base Codec class defines these methods which also define the function interfaces of the stateless encoder and decoder:

Codec.encode(input[, errors])

Encodes the object input and returns a tuple (output object, length consumed). For instance, text encoding converts a string object to a bytes object using a particular character set encoding (e.g., cp1252 or iso-8859-1).

The errors argument defines the error handling to apply. It defaults to 'strict' handling.

The method may not store state in the Codec instance. Use StreamWriter for codecs which have to keep state in order to make encoding efficient.

The encoder must be able to handle zero length input and return an empty object of the output object type in this situation.

Codec.decode(input[, errors])

Decodes the object input and returns a tuple (output object, length consumed). For instance, for a text encoding, decoding converts a bytes object encoded using a particular character set encoding to a string object.

For text encodings and bytes-to-bytes codecs, input must be a bytes object or one which provides the read-only buffer interface – for example, buffer objects and memory mapped files.

The errors argument defines the error handling to apply. It defaults to 'strict' handling.

The method may not store state in the Codec instance. Use StreamReader for codecs which have to keep state in order to make decoding efficient.

The decoder must be able to handle zero length input and return an empty object of the output object type in this situation.

Incremental Encoding and Decoding

The IncrementalEncoder and IncrementalDecoder classes provide the basic interface for incremental encoding and decoding. Encoding/decoding the input isn’t done with one call to the stateless encoder/decoder function, but with multiple calls to the encode()/decode() method of the incremental encoder/decoder. The incremental encoder/decoder keeps track of the encoding/decoding process during method calls.

The joined output of calls to the encode()/decode() method is the same as if all the single inputs were joined into one, and this input was encoded/decoded with the stateless encoder/decoder.

IncrementalEncoder Objects

The IncrementalEncoder class is used for encoding an input in multiple steps. It defines the following methods which every incremental encoder must define in order to be compatible with the Python codec registry.

class codecs.IncrementalEncoder(errors='strict')

Constructor for an IncrementalEncoder instance.

All incremental encoders must provide this constructor interface. They are free to add additional keyword arguments, but only the ones defined here are used by the Python codec registry.

The IncrementalEncoder may implement different error handling schemes by providing the errors keyword argument. See Error Handlers for possible values.

The errors argument will be assigned to an attribute of the same name. Assigning to this attribute makes it possible to switch between different error handling strategies during the lifetime of the IncrementalEncoder object.

encode(object[, final])

Encodes object (taking the current state of the encoder into account) and returns the resulting encoded object. If this is the last call to encode() final must be true (the default is false).

reset()

Reset the encoder to the initial state. The output is discarded: call .encode(object, final=True), passing an empty byte or text string if necessary, to reset the encoder and to get the output.

getstate()

Return the current state of the encoder which must be an integer. The implementation should make sure that 0 is the most common state. (States that are more complicated than integers can be converted into an integer by marshaling/pickling the state and encoding the bytes of the resulting string into an integer.)

setstate(state)

Set the state of the encoder to state. state must be an encoder state returned by getstate().

IncrementalDecoder Objects

The IncrementalDecoder class is used for decoding an input in multiple steps. It defines the following methods which every incremental decoder must define in order to be compatible with the Python codec registry.

class codecs.IncrementalDecoder(errors='strict')

Constructor for an IncrementalDecoder instance.

All incremental decoders must provide this constructor interface. They are free to add additional keyword arguments, but only the ones defined here are used by the Python codec registry.

The IncrementalDecoder may implement different error handling schemes by providing the errors keyword argument. See Error Handlers for possible values.

The errors argument will be assigned to an attribute of the same name. Assigning to this attribute makes it possible to switch between different error handling strategies during the lifetime of the IncrementalDecoder object.

decode(object[, final])

Decodes object (taking the current state of the decoder into account) and returns the resulting decoded object. If this is the last call to decode() final must be true (the default is false). If final is true the decoder must decode the input completely and must flush all buffers. If this isn’t possible (e.g. because of incomplete byte sequences at the end of the input) it must initiate error handling just like in the stateless case (which might raise an exception).

reset()

Reset the decoder to the initial state.

getstate()

Return the current state of the decoder. This must be a tuple with two items, the first must be the buffer containing the still undecoded input. The second must be an integer and can be additional state info. (The implementation should make sure that 0 is the most common additional state info.) If this additional state info is 0 it must be possible to set the decoder to the state which has no input buffered and 0 as the additional state info, so that feeding the previously buffered input to the decoder returns it to the previous state without producing any output. (Additional state info that is more complicated than integers can be converted into an integer by marshaling/pickling the info and encoding the bytes of the resulting string into an integer.)

setstate(state)

Set the state of the decoder to state. state must be a decoder state returned by getstate().

Stream Encoding and Decoding

The StreamWriter and StreamReader classes provide generic working interfaces which can be used to implement new encoding submodules very easily. See encodings.utf_8 for an example of how this is done.

StreamWriter Objects

The StreamWriter class is a subclass of Codec and defines the following methods which every stream writer must define in order to be compatible with the Python codec registry.

class codecs.StreamWriter(stream, errors='strict')

Constructor for a StreamWriter instance.

All stream writers must provide this constructor interface. They are free to add additional keyword arguments, but only the ones defined here are used by the Python codec registry.

The stream argument must be a file-like object open for writing text or binary data, as appropriate for the specific codec.

The StreamWriter may implement different error handling schemes by providing the errors keyword argument. See Error Handlers for the standard error handlers the underlying stream codec may support.

The errors argument will be assigned to an attribute of the same name. Assigning to this attribute makes it possible to switch between different error handling strategies during the lifetime of the StreamWriter object.

write(object)

Writes the object’s contents encoded to the stream.

writelines(list)

Writes the concatenated list of strings to the stream (possibly by reusing the write() method). The standard bytes-to-bytes codecs do not support this method.

reset()

Flushes and resets the codec buffers used for keeping state.

Calling this method should ensure that the data on the output is put into a clean state that allows appending of new fresh data without having to rescan the whole stream to recover state.

In addition to the above methods, the StreamWriter must also inherit all other methods and attributes from the underlying stream.

StreamReader Objects

The StreamReader class is a subclass of Codec and defines the following methods which every stream reader must define in order to be compatible with the Python codec registry.

class codecs.StreamReader(stream, errors='strict')

Constructor for a StreamReader instance.

All stream readers must provide this constructor interface. They are free to add additional keyword arguments, but only the ones defined here are used by the Python codec registry.

The stream argument must be a file-like object open for reading text or binary data, as appropriate for the specific codec.

The StreamReader may implement different error handling schemes by providing the errors keyword argument. See Error Handlers for the standard error handlers the underlying stream codec may support.

The errors argument will be assigned to an attribute of the same name. Assigning to this attribute makes it possible to switch between different error handling strategies during the lifetime of the StreamReader object.

The set of allowed values for the errors argument can be extended with register_error().

read([size[, chars[, firstline]]])

Decodes data from the stream and returns the resulting object.

The chars argument indicates the number of decoded code points or bytes to return. The read() method will never return more data than requested, but it might return less, if there is not enough available.

The size argument indicates the approximate maximum number of encoded bytes or code points to read for decoding. The decoder can modify this setting as appropriate. The default value -1 indicates to read and decode as much as possible. This parameter is intended to prevent having to decode huge files in one step.

The firstline flag indicates that it would be sufficient to only return the first line, if there are decoding errors on later lines.

The method should use a greedy read strategy meaning that it should read as much data as is allowed within the definition of the encoding and the given size, e.g. if optional encoding endings or state markers are available on the stream, these should be read too.

readline([size[, keepends]])

Read one line from the input stream and return the decoded data.

size, if given, is passed as size argument to the stream’s read() method.

If keepends is false line-endings will be stripped from the lines returned.

readlines([sizehint[, keepends]])

Read all lines available on the input stream and return them as a list of lines.

Line-endings are implemented using the codec’s decode() method and are included in the list entries if keepends is true.

sizehint, if given, is passed as the size argument to the stream’s read() method.

reset()

Resets the codec buffers used for keeping state.

Note that no stream repositioning should take place. This method is primarily intended to be able to recover from decoding errors.

In addition to the above methods, the StreamReader must also inherit all other methods and attributes from the underlying stream.

StreamReaderWriter Objects

The StreamReaderWriter is a convenience class that allows wrapping streams which work in both read and write modes.

The design is such that one can use the factory functions returned by the lookup() function to construct the instance.

class codecs.StreamReaderWriter(stream, Reader, Writer, errors='strict')

Creates a StreamReaderWriter instance. stream must be a file-like object. Reader and Writer must be factory functions or classes providing the StreamReader and StreamWriter interface resp. Error handling is done in the same way as defined for the stream readers and writers.

StreamReaderWriter instances define the combined interfaces of StreamReader and StreamWriter classes. They inherit all other methods and attributes from the underlying stream.

StreamRecoder Objects

The StreamRecoder translates data from one encoding to another, which is sometimes useful when dealing with different encoding environments.

The design is such that one can use the factory functions returned by the lookup() function to construct the instance.

class codecs.StreamRecoder(stream, encode, decode, Reader, Writer, errors='strict')

Creates a StreamRecoder instance which implements a two-way conversion: encode and decode work on the frontend — the data visible to code calling read() and write(), while Reader and Writer work on the backend — the data in stream.

You can use these objects to do transparent transcodings, e.g., from Latin-1 to UTF-8 and back.

The stream argument must be a file-like object.

The encode and decode arguments must adhere to the Codec interface. Reader and Writer must be factory functions or classes providing objects of the StreamReader and StreamWriter interface respectively.

Error handling is done in the same way as defined for the stream readers and writers.

StreamRecoder instances define the combined interfaces of StreamReader and StreamWriter classes. They inherit all other methods and attributes from the underlying stream.

Encodings and Unicode

Strings are stored internally as sequences of code points in range 0x0–0x10FFFF. (See PEP 393 [https://www.python.org/dev/peps/pep-0393] for more details about the implementation.) Once a string object is used outside of CPU and memory, endianness and how these arrays are stored as bytes become an issue. As with other codecs, serialising a string into a sequence of bytes is known as encoding, and recreating the string from the sequence of bytes is known as decoding. There are a variety of different text serialisation codecs, which are collectivity referred to as text encodings.

The simplest text encoding (called 'latin-1' or 'iso-8859-1') maps the code points 0–255 to the bytes 0x0–0xff, which means that a string object that contains code points above U+00FF can’t be encoded with this codec. Doing so will raise a UnicodeEncodeError that looks like the following (although the details of the error message may differ): UnicodeEncodeError: 'latin-1' codec can't encode character '\u1234' in position 3: ordinal not in range(256).

There’s another group of encodings (the so called charmap encodings) that choose a different subset of all Unicode code points and how these code points are mapped to the bytes 0x0–0xff. To see how this is done simply open e.g. encodings/cp1252.py (which is an encoding that is used primarily on Windows). There’s a string constant with 256 characters that shows you which character is mapped to which byte value.

All of these encodings can only encode 256 of the 1114112 code points defined in Unicode. A simple and straightforward way that can store each Unicode code point, is to store each code point as four consecutive bytes. There are two possibilities: store the bytes in big endian or in little endian order. These two encodings are called UTF-32-BE and UTF-32-LE respectively. Their disadvantage is that if e.g. you use UTF-32-BE on a little endian machine you will always have to swap bytes on encoding and decoding. UTF-32 avoids this problem: bytes will always be in natural endianness. When these bytes are read by a CPU with a different endianness, then bytes have to be swapped though. To be able to detect the endianness of a UTF-16 or UTF-32 byte sequence, there’s the so called BOM (“Byte Order Mark”). This is the Unicode character U+FEFF. This character can be prepended to every UTF-16 or UTF-32 byte sequence. The byte swapped version of this character (0xFFFE) is an illegal character that may not appear in a Unicode text. So when the first character in an UTF-16 or UTF-32 byte sequence appears to be a U+FFFE the bytes have to be swapped on decoding. Unfortunately the character U+FEFF had a second purpose as a ZERO WIDTH NO-BREAK SPACE: a character that has no width and doesn’t allow a word to be split. It can e.g. be used to give hints to a ligature algorithm. With Unicode 4.0 using U+FEFF as a ZERO WIDTH NO-BREAK SPACE has been deprecated (with U+2060 (WORD JOINER) assuming this role). Nevertheless Unicode software still must be able to handle U+FEFF in both roles: as a BOM it’s a device to determine the storage layout of the encoded bytes, and vanishes once the byte sequence has been decoded into a string; as a ZERO WIDTH NO-BREAK SPACE it’s a normal character that will be decoded like any other.

There’s another encoding that is able to encoding the full range of Unicode characters: UTF-8. UTF-8 is an 8-bit encoding, which means there are no issues with byte order in UTF-8. Each byte in a UTF-8 byte sequence consists of two parts: marker bits (the most significant bits) and payload bits. The marker bits are a sequence of zero to four 1 bits followed by a 0 bit. Unicode characters are encoded like this (with x being payload bits, which when concatenated give the Unicode character):

Range

Encoding

U-00000000 … U-0000007F

0xxxxxxx

U-00000080 … U-000007FF

110xxxxx 10xxxxxx

U-00000800 … U-0000FFFF

1110xxxx 10xxxxxx 10xxxxxx

U-00010000 … U-0010FFFF

11110xxx 10xxxxxx 10xxxxxx 10xxxxxx

The least significant bit of the Unicode character is the rightmost x bit.

As UTF-8 is an 8-bit encoding no BOM is required and any U+FEFF character in the decoded string (even if it’s the first character) is treated as a ZERO WIDTH NO-BREAK SPACE.

Without external information it’s impossible to reliably determine which encoding was used for encoding a string. Each charmap encoding can decode any random byte sequence. However that’s not possible with UTF-8, as UTF-8 byte sequences have a structure that doesn’t allow arbitrary byte sequences. To increase the reliability with which a UTF-8 encoding can be detected, Microsoft invented a variant of UTF-8 (that Python 2.5 calls "utf-8-sig") for its Notepad program: Before any of the Unicode characters is written to the file, a UTF-8 encoded BOM (which looks like this as a byte sequence: 0xef, 0xbb, 0xbf) is written. As it’s rather improbable that any charmap encoded file starts with these byte values (which would e.g. map to

LATIN SMALL LETTER I WITH DIAERESIS

RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK

INVERTED QUESTION MARK

in iso-8859-1), this increases the probability that a utf-8-sig encoding can be correctly guessed from the byte sequence. So here the BOM is not used to be able to determine the byte order used for generating the byte sequence, but as a signature that helps in guessing the encoding. On encoding the utf-8-sig codec will write 0xef, 0xbb, 0xbf as the first three bytes to the file. On decoding utf-8-sig will skip those three bytes if they appear as the first three bytes in the file. In UTF-8, the use of the BOM is discouraged and should generally be avoided.

Standard Encodings

Python comes with a number of codecs built-in, either implemented as C functions or with dictionaries as mapping tables. The following table lists the codecs by name, together with a few common aliases, and the languages for which the encoding is likely used. Neither the list of aliases nor the list of languages is meant to be exhaustive. Notice that spelling alternatives that only differ in case or use a hyphen instead of an underscore are also valid aliases; therefore, e.g. 'utf-8' is a valid alias for the 'utf_8' codec.

CPython implementation detail: Some common encodings can bypass the codecs lookup machinery to improve performance. These optimization opportunities are only recognized by CPython for a limited set of (case insensitive) aliases: utf-8, utf8, latin-1, latin1, iso-8859-1, iso8859-1, mbcs (Windows only), ascii, us-ascii, utf-16, utf16, utf-32, utf32, and the same using underscores instead of dashes. Using alternative aliases for these encodings may result in slower execution.

버전 3.6에서 변경: Optimization opportunity recognized for us-ascii.

Many of the character sets support the same languages. They vary in individual characters (e.g. whether the EURO SIGN is supported or not), and in the assignment of characters to code positions. For the European languages in particular, the following variants typically exist:

an ISO 8859 codeset

a Microsoft Windows code page, which is typically derived from an 8859 codeset, but replaces control characters with additional graphic characters

an IBM EBCDIC code page

an IBM PC code page, which is ASCII compatible

Codec

Aliases

Languages

ascii

646, us-ascii

English

big5

big5-tw, csbig5

Traditional Chinese

big5hkscs

big5-hkscs, hkscs

Traditional Chinese

cp037

IBM037, IBM039

English

cp273

273, IBM273, csIBM273

German

버전 3.4에 추가.

cp424

EBCDIC-CP-HE, IBM424

Hebrew

cp437

437, IBM437

English

cp500

EBCDIC-CP-BE, EBCDIC-CP-CH, IBM500

Western Europe

cp720

Arabic

cp737

Greek

cp775

IBM775

Baltic languages

cp850

850, IBM850

Western Europe

cp852

852, IBM852

Central and Eastern Europe

cp855

855, IBM855

Bulgarian, Byelorussian, Macedonian, Russian, Serbian

cp856

Hebrew

cp857

857, IBM857

Turkish

cp858

858, IBM858

Western Europe

cp860

860, IBM860

Portuguese

cp861

861, CP-IS, IBM861

Icelandic

cp862

862, IBM862

Hebrew

cp863

863, IBM863

Canadian

cp864

IBM864

Arabic

cp865

865, IBM865

Danish, Norwegian

cp866

866, IBM866

Russian

cp869

869, CP-GR, IBM869

Greek

cp874

Thai

cp875

Greek

cp932

932, ms932, mskanji, ms-kanji

Japanese

cp949

949, ms949, uhc

Korean

cp950

950, ms950

Traditional Chinese

cp1006

Urdu

cp1026

ibm1026

Turkish

cp1125

1125, ibm1125, cp866u, ruscii

Ukrainian

버전 3.4에 추가.

cp1140

ibm1140

Western Europe

cp1250

windows-1250

Central and Eastern Europe

cp1251

windows-1251

Bulgarian, Byelorussian, Macedonian, Russian, Serbian

cp1252

windows-1252

Western Europe

cp1253

windows-1253

Greek

cp1254

windows-1254

Turkish

cp1255

windows-1255

Hebrew

cp1256

windows-1256

Arabic

cp1257

windows-1257

Baltic languages

cp1258

windows-1258

Vietnamese

cp65001

Windows only: Windows UTF-8 (CP_UTF8)

버전 3.3에 추가.

euc_jp

eucjp, ujis, u-jis

Japanese

euc_jis_2004

jisx0213, eucjis2004

Japanese

euc_jisx0213

eucjisx0213

Japanese

euc_kr

euckr, korean, ksc5601, ks_c-5601, ks_c-5601-1987, ksx1001, ks_x-1001

Korean

gb2312

chinese, csiso58gb231280, euc-cn, euccn, eucgb2312-cn, gb2312-1980, gb2312-80, iso-ir-58

Simplified Chinese

gbk

936, cp936, ms936

Unified Chinese

gb18030

gb18030-2000

Unified Chinese

hz

hzgb, hz-gb, hz-gb-2312

Simplified Chinese

iso2022_jp

csiso2022jp, iso2022jp, iso-2022-jp

Japanese

iso2022_jp_1

iso2022jp-1, iso-2022-jp-1

Japanese

iso2022_jp_2

iso2022jp-2, iso-2022-jp-2

Japanese, Korean, Simplified Chinese, Western Europe, Greek

iso2022_jp_2004

iso2022jp-2004, iso-2022-jp-2004

Japanese

iso2022_jp_3

iso2022jp-3, iso-2022-jp-3

Japanese

iso2022_jp_ext

iso2022jp-ext, iso-2022-jp-ext

Japanese

iso2022_kr

csiso2022kr, iso2022kr, iso-2022-kr

Korean

latin_1

iso-8859-1, iso8859-1, 8859, cp819, latin, latin1, L1

Western Europe

iso8859_2

iso-8859-2, latin2, L2

Central and Eastern Europe

iso8859_3

iso-8859-3, latin3, L3

Esperanto, Maltese

iso8859_4

iso-8859-4, latin4, L4

Baltic languages

iso8859_5

iso-8859-5, cyrillic

Bulgarian, Byelorussian, Macedonian, Russian, Serbian

iso8859_6

iso-8859-6, arabic

Arabic

iso8859_7

iso-8859-7, greek, greek8

Greek

iso8859_8

iso-8859-8, hebrew

Hebrew

iso8859_9

iso-8859-9, latin5, L5

Turkish

iso8859_10

iso-8859-10, latin6, L6

Nordic languages

iso8859_11

iso-8859-11, thai

Thai languages

iso8859_13

iso-8859-13, latin7, L7

Baltic languages

iso8859_14

iso-8859-14, latin8, L8

Celtic languages

iso8859_15

iso-8859-15, latin9, L9

Western Europe

iso8859_16

iso-8859-16, latin10, L10

South-Eastern Europe

johab

cp1361, ms1361

Korean

koi8_r

Russian

koi8_t

Tajik

버전 3.5에 추가.

koi8_u

Ukrainian

kz1048

kz_1048, strk1048_2002, rk1048

Kazakh

버전 3.5에 추가.

mac_cyrillic

maccyrillic

Bulgarian, Byelorussian, Macedonian, Russian, Serbian

mac_greek

macgreek

Greek

mac_iceland

maciceland

Icelandic

mac_latin2

maclatin2, maccentraleurope

Central and Eastern Europe

mac_roman

macroman, macintosh

Western Europe

mac_turkish

macturkish

Turkish

ptcp154

csptcp154, pt154, cp154, cyrillic-asian

Kazakh

shift_jis

csshiftjis, shiftjis, sjis, s_jis

Japanese

shift_jis_2004

shiftjis2004, sjis_2004, sjis2004

Japanese

shift_jisx0213

shiftjisx0213, sjisx0213, s_jisx0213

Japanese

utf_32

U32, utf32

all languages

utf_32_be

UTF-32BE

all languages

utf_32_le

UTF-32LE

all languages

utf_16

U16, utf16

all languages

utf_16_be

UTF-16BE

all languages

utf_16_le

UTF-16LE

all languages

utf_7

U7, unicode-1-1-utf-7

all languages

utf_8

U8, UTF, utf8

all languages

utf_8_sig

all languages

버전 3.4에서 변경: The utf-16* and utf-32* encoders no longer allow surrogate code points (U+D800–U+DFFF) to be encoded. The utf-32* decoders no longer decode byte sequences that correspond to surrogate code points.

Python Specific Encodings

A number of predefined codecs are specific to Python, so their codec names have no meaning outside Python. These are listed in the tables below based on the expected input and output types (note that while text encodings are the most common use case for codecs, the underlying codec infrastructure supports arbitrary data transforms rather than just text encodings). For asymmetric codecs, the stated meaning describes the encoding direction.

Text Encodings

The following codecs provide str to bytes encoding and bytes-like object to str decoding, similar to the Unicode text encodings.

Codec

Aliases

Meaning

idna

Implement RFC 3490 [https://tools.ietf.org/html/rfc3490.html], see also encodings.idna. Only errors='strict' is supported.

mbcs

ansi, dbcs

Windows only: Encode the operand according to the ANSI codepage (CP_ACP).

oem

Windows only: Encode the operand according to the OEM codepage (CP_OEMCP).

버전 3.6에 추가.

palmos

Encoding of PalmOS 3.5.

punycode

Implement RFC 3492 [https://tools.ietf.org/html/rfc3492.html]. Stateful codecs are not supported.

raw_unicode_escape

Latin-1 encoding with \uXXXX and \UXXXXXXXX for other code points. Existing backslashes are not escaped in any way. It is used in the Python pickle protocol.

undefined

Raise an exception for all conversions, even empty strings. The error handler is ignored.

unicode_escape

Encoding suitable as the contents of a Unicode literal in ASCII-encoded Python source code, except that quotes are not escaped. Decode from Latin-1 source code. Beware that Python source code actually uses UTF-8 by default.

unicode_internal

Return the internal representation of the operand. Stateful codecs are not supported.

버전 3.3부터 폐지: This representation is obsoleted by PEP 393 [https://www.python.org/dev/peps/pep-0393].

Binary Transforms

The following codecs provide binary transforms: bytes-like object to bytes mappings. They are not supported by bytes.decode() (which only produces str output).

Codec

Aliases

Meaning

Encoder / decoder

base64_codec 1

base64, base_64

Convert the operand to multiline MIME base64 (the result always includes a trailing '\n').

버전 3.4에서 변경: accepts any bytes-like object as input for encoding and decoding

base64.encodebytes() / base64.decodebytes()

bz2_codec

bz2

Compress the operand using bz2.

bz2.compress() / bz2.decompress()

hex_codec

hex

Convert the operand to hexadecimal representation, with two digits per byte.

binascii.b2a_hex() / binascii.a2b_hex()

quopri_codec

quopri, quotedprintable, quoted_printable

Convert the operand to MIME quoted printable.

quopri.encode() with quotetabs=True / quopri.decode()

uu_codec

uu

Convert the operand using uuencode.

uu.encode() / uu.decode()

zlib_codec

zip, zlib

Compress the operand using gzip.

zlib.compress() / zlib.decompress()

1

In addition to bytes-like objects, 'base64_codec' also accepts ASCII-only instances of str for decoding

버전 3.2에 추가: Restoration of the binary transforms.

버전 3.4에서 변경: Restoration of the aliases for the binary transforms.

Text Transforms

The following codec provides a text transform: a str to str mapping. It is not supported by str.encode() (which only produces bytes output).

Codec

Aliases

Meaning

rot_13

rot13

Return the Caesar-cypher encryption of the operand.

버전 3.2에 추가: Restoration of the rot_13 text transform.

버전 3.4에서 변경: Restoration of the rot13 alias.

encodings.idna — Internationalized Domain Names in Applications

This module implements RFC 3490 [https://tools.ietf.org/html/rfc3490.html] (Internationalized Domain Names in Applications) and RFC 3492 [https://tools.ietf.org/html/rfc3492.html] (Nameprep: A Stringprep Profile for Internationalized Domain Names (IDN)). It builds upon the punycode encoding and stringprep.

These RFCs together define a protocol to support non-ASCII characters in domain names. A domain name containing non-ASCII characters (such as www.Alliancefrançaise.nu) is converted into an ASCII-compatible encoding (ACE, such as www.xn--alliancefranaise-npb.nu). The ACE form of the domain name is then used in all places where arbitrary characters are not allowed by the protocol, such as DNS queries, HTTP Host fields, and so on. This conversion is carried out in the application; if possible invisible to the user: The application should transparently convert Unicode domain labels to IDNA on the wire, and convert back ACE labels to Unicode before presenting them to the user.

Python supports this conversion in several ways: the idna codec performs conversion between Unicode and ACE, separating an input string into labels based on the separator characters defined in section 3.1 of RFC 3490 [https://tools.ietf.org/html/rfc3490.html#section-3.1] and converting each label to ACE as required, and conversely separating an input byte string into labels based on the . separator and converting any ACE labels found into unicode. Furthermore, the socket module transparently converts Unicode host names to ACE, so that applications need not be concerned about converting host names themselves when they pass them to the socket module. On top of that, modules that have host names as function parameters, such as http.client and ftplib, accept Unicode host names (http.client then also transparently sends an IDNA hostname in the Host field if it sends that field at all).

When receiving host names from the wire (such as in reverse name lookup), no automatic conversion to Unicode is performed: applications wishing to present such host names to the user should decode them to Unicode.

The module encodings.idna also implements the nameprep procedure, which performs certain normalizations on host names, to achieve case-insensitivity of international domain names, and to unify similar characters. The nameprep functions can be used directly if desired.

encodings.idna.nameprep(label)

Return the nameprepped version of label. The implementation currently assumes query strings, so AllowUnassigned is true.

encodings.idna.ToASCII(label)

Convert a label to ASCII, as specified in RFC 3490 [https://tools.ietf.org/html/rfc3490.html]. UseSTD3ASCIIRules is assumed to be false.

encodings.idna.ToUnicode(label)

Convert a label to Unicode, as specified in RFC 3490 [https://tools.ietf.org/html/rfc3490.html].

encodings.mbcs — Windows ANSI codepage

This module implements the ANSI codepage (CP_ACP).

Availability: Windows only.

버전 3.3에서 변경: Support any error handler.

버전 3.2에서 변경: Before 3.2, the errors argument was ignored; 'replace' was always used to encode, and 'ignore' to decode.

encodings.utf_8_sig — UTF-8 codec with BOM signature

This module implements a variant of the UTF-8 codec. On encoding, a UTF-8 encoded BOM will be prepended to the UTF-8 encoded bytes. For the stateful encoder this is only done once (on the first write to the byte stream). On decoding, an optional UTF-8 encoded BOM at the start of the data will be skipped.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

바이너리 데이터 서비스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

|

데이터형

The modules described in this chapter provide a variety of specialized data types such as dates and times, fixed-type arrays, heap queues, double-ended queues, and enumerations.

Python also provides some built-in data types, in particular, dict, list, set and frozenset, and tuple. The str class is used to hold Unicode strings, and the bytes and bytearray classes are used to hold binary data.

이 장에서는 다음 모듈에 관해 설명합니다:

datetime — 기본 날짜와 시간 형

사용 가능한 형

timedelta 객체

date 객체

datetime 객체

time 객체

tzinfo 객체

timezone 객체

strftime()과 strptime() 동작

calendar — General calendar-related functions

collections — Container datatypes

ChainMap objects

ChainMap Examples and Recipes

Counter objects

deque objects

deque Recipes

defaultdict objects

defaultdict Examples

namedtuple() Factory Function for Tuples with Named Fields

OrderedDict objects

OrderedDict Examples and Recipes

UserDict objects

UserList objects

UserString objects

collections.abc — 컨테이너의 추상 베이스 클래스

Collections 추상 베이스 클래스

heapq — Heap queue algorithm

Basic Examples

Priority Queue Implementation Notes

Theory

bisect — 배열 이진 분할 알고리즘

정렬된 리스트 검색하기

다른 예제

array — 효율적인 숫자 배열

weakref — Weak references

Weak Reference Objects

Example

Finalizer Objects

Comparing finalizers with __del__() methods

types — 동적 형 생성과 내장형 이름

동적 형 생성

표준 인터프리터 형

추가 유틸리티 클래스와 함수

코루틴 유틸리티 함수

copy — 얕은 복사와 깊은 복사 연산

pprint — 예쁜 데이터 인쇄기

PrettyPrinter 객체

예제

reprlib — 대안 repr() 구현

Repr 객체

Repr 객체 서브클래싱

enum — Support for enumerations

Module Contents

Creating an Enum

Programmatic access to enumeration members and their attributes

Duplicating enum members and values

Ensuring unique enumeration values

Using automatic values

Iteration

Comparisons

Allowed members and attributes of enumerations

Restricted Enum subclassing

Pickling

Functional API

Derived Enumerations

IntEnum

IntFlag

Flag

Others

Interesting examples

Omitting values

Using auto

Using object

Using a descriptive string

Using a custom __new__()

OrderedEnum

DuplicateFreeEnum

Planet

TimePeriod

How are Enums different?

Enum Classes

Enum Members (aka instances)

Finer Points

Supported __dunder__ names

Supported _sunder_ names

Enum member type

Boolean value of Enum classes and members

Enum classes with methods

Combining members of Flag

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

데이터형 »

|

datetime — 기본 날짜와 시간 형

소스 코드: Lib/datetime.py [https://github.com/python/cpython/tree/3.7/Lib/datetime.py]

datetime 모듈은 날짜와 시간을 간단하거나 복잡한 방법으로 조작하는 클래스를 제공합니다. 날짜와 시간 산술이 지원되지만, 구현의 초점은 출력 포매팅과 조작을 위한 효율적인 어트리뷰트 추출입니다. 관련 기능에 대해서는, time과 calendar 모듈도 참조하십시오.

날짜와 시간 객체에는 두 가지 종류가 있습니다: “나이브(naive)”와 “어웨어(aware)”.

어웨어 객체는 다른 어웨어 객체와의 상대적인 위치를 파악하기 위한, 시간대와 일광 절약 시간 정보와 같은 적용 가능한 알고리즘과 정치적 시간 조정에 대한 충분한 지식을 갖추고 있습니다. 어웨어 객체는 자의적으로 해석할 여지 없는 특정 시간을 나타내기 위해 사용됩니다 1.

나이브 객체는 모호하지 않게 자신과 다른 날짜/시간 객체의 상대적인 위치를 파악할 수 있는 충분한 정보를 포함하지 않습니다. 나이브 객체가 UTC(Coordinated Universal Time), 지역 시간 또는 다른 시간대의 시간 중 어느 것을 나타내는지는 순전히 프로그램에 달려있습니다. 특정 숫자가 미터, 마일 또는 질량 중 어는 것을 나타내는지가 프로그램에 달린 것과 마찬가지입니다. 나이브 객체는 이해하기 쉽고 작업하기 쉽지만, 현실의 일부 측면을 무시하는 대가를 치릅니다.

어웨어 객체가 필요한 응용 프로그램을 위해, datetime 과 time 객체에는 추상 tzinfo 클래스의 서브 클래스 인스턴스로 설정할 수 있는 선택적 시간대 정보 어트리뷰트인 tzinfo가 있습니다. 이러한 tzinfo 객체는 UTC 시간으로부터의 오프셋, 시간대 이름 및 일광 절약 시간이 적용되는지에 대한 정보를 보관합니다. datetime 모듈에서는 오직 하나의 구상 tzinfo 클래스, timezone 클래스만 제공됨에 유의하십시오. timezone 클래스는 UTC 자체나 북미 EST와 EDT 시간대와 같은 UTC로부터 고정 오프셋을 갖는 간단한 시간대를 나타낼 수 있습니다. 더욱 세부적인 수준의 시간대 지원은 응용 프로그램에 달려 있습니다. 전 세계의 시간 조정에 대한 규칙은 합리적이라기보다 정치적이고, 자주 변경되며, UTC 이외에 모든 응용 프로그램에 적합한 표준은 없습니다.

datetime 모듈은 다음 상수를 내보냅니다:

datetime.MINYEAR

date나 datetime 객체에서 허용되는 가장 작은 연도 번호. MINYEAR는 1입니다.

datetime.MAXYEAR

date나 datetime 객체에서 허용되는 가장 큰 연도 번호. MAXYEAR는 9999입니다.

더 보기

모듈 calendar

일반 달력 관련 함수들.

모듈 time

시간 액세스와 변환.

사용 가능한 형

class datetime.date

현재의 그레고리력이 언제나 적용되어왔고, 앞으로도 그럴 것이라는 가정하에 이상적인 나이브 날짜. 어트리뷰트: year, month 및 day.

class datetime.time

특정 날짜와 관계없이, 하루가 정확히 24*60*60초를 갖는다는 가정하에 이상적인 시간 (여기에는 “윤초”라는 개념이 없습니다). 어트리뷰트: hour, minute, second, microsecond 및 tzinfo.

class datetime.datetime

날짜와 시간의 조합. 어트리뷰트: year, month, day, hour, minute, second, microsecond 및 tzinfo.

class datetime.timedelta

두 date, time 또는 datetime 인스턴스 간의 차이를 마이크로초 해상도로 나타내는 기간.

class datetime.tzinfo

시간대 정보 객체의 추상 베이스 클래스. 이것들은 datetime과 time 클래스에서 사용자 정의할 수 있는 시간 조정 개념(예를 들어, 시간대와/나 일광 절약 시간을 다루는 것)을 제공하기 위해 사용됩니다.

class datetime.timezone

tzinfo 추상 베이스 클래스를 구현하는 클래스로, UTC로부터의 고정 오프셋을 나타냅니다.

버전 3.2에 추가.

이러한 형의 객체는 불변입니다.

date 형의 객체는 항상 나이브합니다.

time나 datetime 형의 객체는 나이브하거나 어웨어할 수 있습니다. datetime 객체 d는 d.tzinfo가 None이 아니고, d.tzinfo.utcoffset(d)가 None을 반환하지 않으면 어웨어합니다. d.tzinfo가 None이거나, d.tzinfo는 None이 아니지만 d.tzinfo.utcoffset(d)가 None을 반환하면 d는 나이브합니다. time 객체 t는 t.tzinfo``가 ``None이 아니고 t.tzinfo.utcoffset(None)이 None을 반환하지 않으면 어웨어합니다. 그렇지 않으면, t는 나이브합니다.

나이브와 어웨어 간의 차이점은 timedelta 객체에는 적용되지 않습니다.

서브 클래스 관계:

object
    timedelta
    tzinfo
        timezone
    time
    date
        datetime

timedelta 객체

timedelta 객체는 두 날짜나 시간의 차이인 기간을 나타냅니다.

class datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)

모든 인자는 선택적이며 기본값은 0입니다. 인자는 정수나 부동 소수점 수일 수 있으며, 양수나 음수일 수 있습니다.

days, seconds 및 microseconds만 내부적으로 저장됩니다. 인자는 이 단위로 변환됩니다:

밀리 초는 1000마이크로초로 변환됩니다.

분은 60초로 변환됩니다.

시간은 3600초로 변환됩니다.

주는 7일로 변환됩니다.

그런 다음 days, seconds 및 microseconds를 다음처럼 정규화하여 표현이 고유하도록 만듭니다

0 <= microseconds < 1000000

0 <= seconds < 3600*24 (하루 내의 초 수)

-999999999 <= days <= 999999999

인자가 float이고 부분 마이크로초가 있으면, 모든 인자의 남은 부분 마이크로초가 합쳐지고, 그 합은 동률일 때 짝수로 반올림하는 방식으로 가장 가까운 마이크로초로 반올림됩니다. float 인자가 없으면, 변환과 정규화 프로세스는 정확합니다 (정보가 손실되지 않습니다).

정규화된 days 값이 표시된 범위를 벗어나면, OverflowError가 발생합니다.

음수 값의 정규화는 처음 보면 놀라울 수 있습니다. 예를 들어,

>>> from datetime import timedelta
>>> d = timedelta(microseconds=-1)
>>> (d.days, d.seconds, d.microseconds)
(-1, 86399, 999999)

클래스 어트리뷰트는 다음과 같습니다:

timedelta.min

가장 음수인 timedelta 객체, timedelta(-999999999).

timedelta.max

가장 양수인 timedelta 객체, timedelta(days=999999999, hours=23, minutes=59, seconds=59, microseconds=999999).

timedelta.resolution

같지 않은 timedelta 객체 간의 가능한 가장 작은 차이, timedelta(microseconds=1).

정규화로 인해, timedelta.max > -timedelta.min입니다. -timedelta.max는 timedelta 객체로 표현할 수 없습니다.

인스턴스 어트리뷰트 (읽기 전용):

어트리뷰트

값

days

-999999999와 999999999 사이, 경계 포함

seconds

0과 86399 사이, 경계 포함

microseconds

0과 999999 사이, 경계 포함

지원되는 연산:

연산

결과

t1 = t2 + t3

t2와 t3의 합. 이후에는 t1-t2 == t3 과 t1-t3 == t2가 참입니다. (1)

t1 = t2 - t3

t2와 t3의 차이. 이후에는 t1 == t2 - t3 과 t2 == t1 + t3가 참입니다. (1)(6)

t1 = t2 * i 또는 t1 = i * t2

델타에 정수를 곱합니다. 이후에는 i != 0일 때, t1 // i == t2가 참입니다.

일반적으로, t1 * i == t1 * (i-1) + t1은 참입니다. (1)

t1 = t2 * f 또는 t1 = f * t2

델타에 float를 곱합니다. 결과는 동률일 때 짝수로 반올림하는 방식으로 timedelta.resolution의 가장 가까운 배수로 자리 올림 됩니다.

f = t2 / t3

전체 기간 t2를 구간 단위 t3으로 나누기 (3). float 객체를 반환합니다.

t1 = t2 / f 또는 t1 = t2 / i

델타를 float나 int로 나눈 값. 결과는 동률일 때 짝수로 반올림하는 방식으로 timedelta.resolution의 가장 가까운 배수로 자리 올림 됩니다.

t1 = t2 // i 또는 t1 = t2 // t3

floor가 계산되고 나머지(있다면)를 버립니다. 두 번째 경우에는, 정수가 반환됩니다. (3)

t1 = t2 % t3

나머지가 timedelta 객체로 계산됩니다. (3)

q, r = divmod(t1, t2)

몫과 나머지를 계산합니다: q = t1 // t2 (3) 과 r = t1 % t2. q는 정수고 r은 timedelta 객체입니다.

+t1

같은 값을 갖는 timedelta 객체를 반환합니다. (2)

-t1

timedelta(-t1.days, -t1.seconds, -t1.microseconds) 와 t1* -1과 동등합니다. (1)(4)

abs(t)

t.days >= 0 일 때 +t 와 t.days < 0 일 때 -t와 동등합니다. (2)

str(t)

[D day[s], ][H]H:MM:SS[.UUUUUU] 형식의 문자열을 반환합니다. 여기서 D는 음의 t일 때 음수입니다. (5)

repr(t)

규범적 어트리뷰트 값을 가진 생성자 호출로 표현한 timedelta 객체의 문자열 표현을 반환합니다.

노트:

이것은 정확하지만, 오버플로 할 수 있습니다.

이것은 정확하고, 오버플로 할 수 없습니다.

0으로 나누면 ZeroDivisionError가 발생합니다.

-timedelta.max는 timedelta 객체로 표현할 수 없습니다.

timedelta 객체의 문자열 표현은 내부 표현과 유사하게 정규화됩니다. 이것은 음의 timedelta가 다소 이상하게 표현되는 결과로 이어집니다. 예를 들어:

>>> timedelta(hours=-5)
datetime.timedelta(days=-1, seconds=68400)
>>> print(_)
-1 day, 19:00:00

t2 - t3 표현식은 항상 t2 + (-t3) 표현식과 같아지는데, t3이 timedelta.max일 때만 예외입니다; 이때는 앞에 있는 것은 결과를 만들지만, 뒤에 있는 것은 오버플로를 일으킵니다.

위에 나열된 연산 외에도 timedelta 객체는 date와 datetime 객체와의 어떤 합과 차를 지원합니다 (아래를 참조하세요).

버전 3.2에서 변경: 나머지 연산과 divmod() 함수와 마찬가지로, timedelta 객체를 다른 timedelta 객체로 정수 나누기(floor division)와 실수 나누기(true division)가 이제 지원됩니다. timedelta 객체를 float 객체로 실수 나누기와 곱셈도 이제 이제 지원됩니다.

timedelta 객체의 비교가 지원되는데, 더 짧은 기간을 나타내는 timedelta 객체를 더 작은 것으로 간주합니다. 혼합형 비교가 객체 주소 기반의 기본 비교로 떨어지는 것을 막기 위해, timedelta 객체가 다른 형의 객체와 비교될 때, 비교가 == 이나 !=가 아니면 TypeError가 발생합니다. 두 상황에 해당하면 각각 False 나 True를 반환합니다.

timedelta 객체는 해시 가능(딕셔너리 키로 사용 가능)하고, 효율적인 피클링을 지원하며, 불리언 문맥에서 timedelta 객체는 timedelta(0)와 같지 않을 때만 참으로 간주합니다.

인스턴스 메서드:

timedelta.total_seconds()

기간에 포함된 총 시간을 초(seconds)로 반환합니다. td / timedelta(seconds=1)와 동등합니다. 초 이외의 구간 단위에는, 나누기 형식을 직접 사용하십시오 (예를 들어, td / timedelta(microseconds=1)).

매우 큰 시간 구간에서는 (대부분 플랫폼에서 270년 이상), 이 메서드는 마이크로초의 정확도를 잃게 됩니다.

버전 3.2에 추가.

사용 예:

>>> from datetime import timedelta
>>> year = timedelta(days=365)
>>> another_year = timedelta(weeks=40, days=84, hours=23,
...                          minutes=50, seconds=600)  # adds up to 365 days
>>> year.total_seconds()
31536000.0
>>> year == another_year
True
>>> ten_years = 10 * year
>>> ten_years, ten_years.days // 365
(datetime.timedelta(days=3650), 10)
>>> nine_years = ten_years - year
>>> nine_years, nine_years.days // 365
(datetime.timedelta(days=3285), 9)
>>> three_years = nine_years // 3
>>> three_years, three_years.days // 365
(datetime.timedelta(days=1095), 3)
>>> abs(three_years - ten_years) == 2 * three_years + year
True

date 객체

date 객체는 현재의 그레고리력을 무한히 양방향으로 확장한, 이상적인 달력에서의 날짜(년, 월, 일)를 나타냅니다. 1년 1월 1일을 날 번호 1, 1년 1월 2일을 날 번호 2라고 부릅니다. 이것은 Dershowitz와 Reingold의 책 Calendrical Calculations에 나오는 “역산 그레고리(proleptic Gregorian)” 달력의 정의와 일치합니다. 이 달력은 모든 계산의 기본 달력입니다. 역산 그레고리력 서수(ordinal)와 다른 많은 달력 시스템 사이의 변환을 위한 알고리즘에 관해서는 이 책을 참조하십시오.

class datetime.date(year, month, day)

All arguments are required. Arguments must be integers in the following ranges:

MINYEAR <= year <= MAXYEAR

1 <= month <= 12

1 <= day <= 주어진 month와 year에서의 날 수

이 범위를 벗어나는 인자가 주어지면, ValueError가 발생합니다.

다른 생성자, 모든 클래스 메서드:

classmethod date.today()

현재 지역 날짜를 반환합니다. 이것은 date.fromtimestamp(time.time())와 동등합니다.

classmethod date.fromtimestamp(timestamp)

time.time()에 의해 반환된 것과 같은 POSIX 타임스탬프에 해당하는 지역 날짜를 반환합니다. 타임스탬프가 플랫폼 C localtime() 함수에서 지원하는 값 범위를 벗어나면 OverflowError가 발생하고, localtime() 실패 시 OSError가 발생합니다. 이것이 1970년에서 2038년으로 제한되는 것이 일반적입니다. 타임스탬프라는 개념에 윤초를 포함하는 POSIX가 아닌 시스템에서는, 윤초가 fromtimestamp()에서 무시됨에 유의하십시오.

버전 3.3에서 변경: timestamp가 플랫폼 C localtime() 함수에서 지원하는 값 범위를 벗어나면 ValueError 대신 OverflowError를 발생시킵니다. localtime() 실패 시 ValueError 대신 OSError를 발생시킵니다.

classmethod date.fromordinal(ordinal)

역산 그레고리력 서수에 해당하는 date를 반환합니다. 1년 1월 1일이 서수 1입니다. 1 <= ordinal <= date.max.toordinal()이 아니면 ValueError가 발생합니다. 모든 date d에 대해, date.fromordinal(d.toordinal()) == d입니다.

classmethod date.fromisoformat(date_string)

date.isoformat()으로 만든 형식의 date_string에 해당하는 date를 반환합니다. 구체적으로, 이 함수는 YYYY-MM-DD 형식의 문자열을 지원합니다.

조심

이것은 임의의 ISO 8601 문자열을 구문 분석하는 것을 지원하지 않습니다 - 이것은 date.isoformat()의 역연산이고자 할 뿐입니다.

버전 3.7에 추가.

클래스 어트리뷰트:

date.min

표현 가능한 가장 이른 date, date(MINYEAR, 1, 1).

date.max

표현 가능한 가장 늦은 date, date(MAXYEAR, 12, 31).

date.resolution

같지 않은 date 객체 간의 가능한 가장 작은 차이, timedelta(days=1).

인스턴스 어트리뷰트 (읽기 전용):

date.year

MINYEAR와 MAXYEAR 사이, 경계 포함.

date.month

1과 12 사이, 경계 포함.

date.day

1과 주어진 year의 주어진 month의 날 수 사이.

지원되는 연산:

연산

결과

date2 = date1 + timedelta

date2는 date1에서 timedelta.days 일 이동한 날짜입니다. (1)

date2 = date1 - timedelta

date2 + timedelta == date1가 성립하는 date2를 계산합니다. (2)

timedelta = date1 - date2

(3)

date1 < date2

date1이 date2에 앞서면 date1는 date2보다 작은 것으로 간주합니다. (4)

노트:

date2는 timedelta.days > 0이면 미래로, timedelta.days < 0이면 과거로 이동합니다. 결국 date2 - date1 == timedelta.days이 됩니다. timedelta.seconds와 timedelta.microseconds는 무시됩니다. date2.year가 MINYEAR보다 작거나 MAXYEAR보다 크게 되려고 하면 OverflowError가 발생합니다.

timedelta.seconds와 timedelta.microseconds는 무시됩니다.

이것은 정확하고, 오버플로 할 수 없습니다. timedelta.seconds와 timedelta.microseconds는 0이고, 이후에 date2 + timedelta == date1 이 됩니다.

즉, 오직 date1.toordinal() < date2.toordinal()일 때만 date1 < date2입니다. 비교 대상이 date 객체가 아니면 날짜 비교는 TypeError를 발생시킵니다. 그러나, 비교 대상에 timetuple() 어트리뷰트가 있으면, 대신 NotImplemented가 반환됩니다. 이 훅은 다른 형의 날짜 객체가 혼합형 비교를 구현할 기회를 제공합니다. 그렇지 않으면, date 객체가 다른 형의 객체와 비교될 때, 비교가 ==나 !=가 아니면 TypeError가 발생합니다. 두 상황에 해당하면 각각 False 나 True를 반환합니다

날짜는 딕셔너리 키로 사용할 수 있습니다. 불리언 문맥에서, 모든 date 객체는 참으로 간주합니다.

인스턴스 메서드:

date.replace(year=self.year, month=self.month, day=self.day)

키워드 인자로 새로운 값이 주어진 매개 변수들을 제외하고, 같은 값을 가진 date를 반환합니다. 예를 들어, d == date(2002, 12, 31)이면, d.replace(day=26) == date(2002, 12, 26)입니다.

date.timetuple()

time.localtime()이 반환하는 것과 같은 time.struct_time을 반환합니다. 시, 분 및 초는 0이고, DST 플래그는 -1입니다. d.timetuple()은 time.struct_time((d.year, d.month, d.day, 0, 0, 0, d.weekday(), yday, -1))와 동등합니다. 여기서 yday = d.toordinal() - date(d.year, 1, 1).toordinal() + 1은 1월 1일에 1로 시작하는 현재 연도의 날짜 번호입니다.

date.toordinal()

역산 그레고리력 서수를 돌려줍니다. 1년 1월 1일의 서수는 1입니다. 임의의 date 객체 d에 대해 date.fromordinal(d.toordinal()) == d입니다.

date.weekday()

정수로 요일을 반환합니다. 월요일은 0이고 일요일은 6입니다. 예를 들어, date(2002, 12, 4).weekday() == 2, 수요일. isoweekday()도 참조하십시오.

date.isoweekday()

정수로 요일을 반환합니다. 월요일은 1이고 일요일은 7입니다. 예를 들어, date(2002, 12, 4).isoweekday() == 3, 수요일. weekday(), isocalendar()도 참조하십시오.

date.isocalendar()

3-튜플 (ISO 연도, ISO 주 번호, ISO 요일)을 반환합니다.

ISO 달력은 그레고리력의 널리 사용되는 변형입니다. https://www.staff.science.uu.nl/~gent0113/calendar/isocalendar.htm 에 잘 설명되어 있습니다.

ISO 연도는 52나 53개의 완전한 주로 구성되고, 주는 월요일에 시작하여 일요일에 끝납니다. ISO 연도의 첫 번째 주는 그 해의 (그레고리) 달력에서 목요일이 들어있는 첫 번째 주입니다. 이것을 주 번호 1이라고 하며, 그 목요일의 ISO 연도는 그레고리 연도와 같습니다.

예를 들어, 2004년은 목요일에 시작되므로, ISO 연도 2004의 첫 주는 월요일, 2003년 12월 29일에 시작하고, 일요일, 2004년 1월 4일에 끝납니다. 그래서 date(2003, 12, 29).isocalendar() == (2004, 1, 1)이고 date(2004, 1, 4).isocalendar() == (2004, 1, 7)입니다.

date.isoformat()

ISO 8601 형식으로 날짜를 나타내는 문자열을 반환합니다, ‘YYYY-MM-DD’. 예를 들어, date(2002, 12, 4).isoformat() == '2002-12-04'.

date.__str__()

날짜 d에 대해, str(d)는 d.isoformat()와 동등합니다.

date.ctime()

날짜를 나타내는 문자열을 반환합니다, 예를 들어 date(2002, 12, 4).ctime() == 'Wed Dec 4 00:00:00 2002'. d.ctime()은 네이티브 C ctime() 함수(time.ctime()은 호출하지만 date.ctime()은 호출하지 않습니다)가 C 표준을 준수하는 플랫폼에서 time.ctime(time.mktime(d.timetuple()))와 동등합니다.

date.strftime(format)

명시적인 포맷 문자열로 제어되는, 날짜를 나타내는 문자열을 반환합니다. 시, 분 또는 초를 나타내는 포맷 코드는 0 값을 보게 됩니다. 포매팅 지시자의 전체 목록은, strftime()과 strptime() 동작를 참조하십시오.

date.__format__(format)

date.strftime()과 같습니다. 이것이 포맷 문자열 리터럴과 str.format()을 사용할 때 date 객체를 위한 포맷 문자열을 지정할 수 있도록 합니다. 포매팅 지시자의 전체 목록은 strftime()과 strptime() 동작를 참조하십시오.

이벤트까지 남은 날 수 계산 예:

>>> import time
>>> from datetime import date
>>> today = date.today()
>>> today
datetime.date(2007, 12, 5)
>>> today == date.fromtimestamp(time.time())
True
>>> my_birthday = date(today.year, 6, 24)
>>> if my_birthday < today:
...     my_birthday = my_birthday.replace(year=today.year + 1)
>>> my_birthday
datetime.date(2008, 6, 24)
>>> time_to_birthday = abs(my_birthday - today)
>>> time_to_birthday.days
202

date로 작업하는 예:

>>> from datetime import date
>>> d = date.fromordinal(730920) # 730920th day after 1. 1. 0001
>>> d
datetime.date(2002, 3, 11)
>>> t = d.timetuple()
>>> for i in t:
...     print(i)
2002                # year
3                   # month
11                  # day
0
0
0
0                   # weekday (0 = Monday)
70                  # 70th day in the year
-1
>>> ic = d.isocalendar()
>>> for i in ic:
...     print(i)
2002                # ISO year
11                  # ISO week number
1                   # ISO day number ( 1 = Monday )
>>> d.isoformat()
'2002-03-11'
>>> d.strftime("%d/%m/%y")
'11/03/02'
>>> d.strftime("%A %d. %B %Y")
'Monday 11. March 2002'
>>> 'The {1} is {0:%d}, the {2} is {0:%B}.'.format(d, "day", "month")
'The day is 11, the month is March.'

datetime 객체

datetime 객체는 date 객체와 time 객체의 모든 정보를 포함하는 단일 객체입니다. date 객체와 마찬가지로, datetime은 현재의 그레고리력을 양방향으로 확장한다고 가정합니다; time 객체와 마찬가지로, datetime은 하루가 정확히 3600*24초인 것으로 가정합니다.

생성자:

class datetime.datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0)

The year, month and day arguments are required. tzinfo may be None, or an instance of a tzinfo subclass. The remaining arguments must be integers in the following ranges:

MINYEAR <= year <= MAXYEAR,

1 <= month <= 12,

1 <= day <= 주어진 month와 year에서의 날 수,

0 <= hour < 24,

0 <= minute < 60,

0 <= second < 60,

0 <= microsecond < 1000000,

fold in [0, 1].

이 범위를 벗어나는 인자가 주어지면, ValueError가 발생합니다.

버전 3.6에 추가: fold 인자가 추가되었습니다.

다른 생성자, 모든 클래스 메서드:

classmethod datetime.today()

tzinfo가 None인 현재 지역 datetime을 반환합니다. 이것은 datetime.fromtimestamp(time.time())과 동등합니다. now(), fromtimestamp()를 참조하십시오.

classmethod datetime.now(tz=None)

현재의 지역 날짜와 시간을 반환합니다. 선택적 인자 tz가 None이거나 지정되지 않으면, today()와 유사합니다. 하지만, 가능하면 time.time() 타임스탬프를 통해 얻을 수 있는 것보다 더 높은 정밀도를 제공합니다 (예를 들어, C gettimeofday() 함수를 제공하는 플랫폼에서 가능합니다).

tz가 None이 아니면, tzinfo 서브 클래스의 인스턴스여야 하며, 현재 날짜와 시간이 tz의 시간대로 변환됩니다. 이때 결과는 tz.fromutc(datetime.utcnow().replace(tzinfo=tz))와 동등합니다. today(), utcnow()도 참조하십시오.

classmethod datetime.utcnow()

tzinfo가 None인 현재 UTC 날짜와 시간을 반환합니다. 이것은 now()와 비슷하지만, 현재의 UTC 날짜와 시간을 나이브 datetime 객체로 반환합니다. 현재 어웨어 UTC datetime은 datetime.now(timezone.utc)를 호출하여 얻을 수 있습니다. now()도 참조하십시오.

classmethod datetime.fromtimestamp(timestamp, tz=None)

time.time()가 반환하는 것과 같은, POSIX timestamp에 해당하는 지역 날짜와 시간을 반환합니다. 선택적 인자 tz가 None이거나 지정되지 않으면 timestamp는 플랫폼의 지역 날짜와 시간으로 변환되며, 반환된 datetime 객체는 나이브합니다.

tz가 None이 아니면, tzinfo 서브 클래스의 인스턴스여야 하며, timestamp는 tz의 시간대로 변환됩니다. 이때 결과는 tz.fromutc(datetime.utcfromtimestamp(timestamp).replace(tzinfo=tz))와 동등합니다.

timestamp가 플랫폼 C localtime() 이나 gmtime() 함수에서 지원하는 값 범위를 벗어나면 fromtimestamp()가 OverflowError를 발생시킬 수 있고, localtime() 이나 gmtime()이 실패하면 OSError를 발생시킬 수 있습니다. 1970년에서 2038년까지로 제한되는 것이 일반적입니다. 타임스탬프에 윤초 개념을 포함하는 비 POSIX 시스템에서, fromtimestamp()는 윤초를 무시하므로, 1초 차이가 나는 두 개의 타임스탬프가 같은 datetime 객체를 산출할 수 있습니다. utcfromtimestamp()도 참조하십시오.

버전 3.3에서 변경: timestamp가 플랫폼 C localtime() 이나 gmtime() 함수에서 지원하는 값 범위를 벗어나면 ValueError 대신 OverflowError를 발생시킵니다. localtime() 이나 gmtime()이 실패하면 ValueError 대신 OSError를 발생시킵니다.

버전 3.6에서 변경: fromtimestamp()는 fold가 1로 설정된 인스턴스를 반환할 수 있습니다.

classmethod datetime.utcfromtimestamp(timestamp)

tzinfo가 None인 POSIX timestamp에 해당하는 UTC datetime을 반환합니다. timestamp가 플랫폼 C gmtime() 함수에서 지원하는 값 범위를 벗어나면 OverflowError가 발생하고, gmtime()이 실패하면 OSError가 발생합니다. 1970년에서 2038년까지로 제한되는 것이 일반적입니다.

어웨어 datetime 객체를 얻으려며, fromtimestamp()를 호출하십시오:

datetime.fromtimestamp(timestamp, timezone.utc)

POSIX 호환 플랫폼에서, 다음 표현식과 동등합니다:

datetime(1970, 1, 1, tzinfo=timezone.utc) + timedelta(seconds=timestamp)

단, 후자의 식은 항상 전체 연도 범위를 지원합니다: MINYEAR와 MAXYEAR 사이, 경계 포함.

버전 3.3에서 변경: timestamp가 플랫폼 C gmtime() 함수에서 지원하는 값 범위를 벗어나면 ValueError 대신 OverflowError를 발생시킵니다. gmtime()이 실패하면 ValueError 대신 OSError를 발생시킵니다.

classmethod datetime.fromordinal(ordinal)

역산 그레고리력 서수(ordinal)에 해당하는 datetime을 반환합니다. 1년 1월 1일이 서수 1입니다. 1 <= ordinal <= datetime.max.toordinal()이 아니면 ValueError가 발생합니다. 결과의 hour, minute, second 및 microsecond는 모두 0이고, tzinfo는 None입니다.

classmethod datetime.combine(date, time, tzinfo=self.tzinfo)

지정된 date 객체와 같은 날짜 구성 요소와 지정된 time 객체와 같은 시간 구성 요소를 갖는 새 datetime 객체를 반환합니다. tzinfo 인자가 제공되면, 그 값은 결과의 tzinfo 어트리뷰트를 설정하는 데 사용되며, 그렇지 않으면 time 인자의 tzinfo 어트리뷰트가 사용됩니다.

모든 datetime 객체 d에 대해, d == datetime.combine(d.date(), d.time(), d.tzinfo)가 성립합니다. date가 datetime 객체면, 그것의 시간 구성 요소와 tzinfo 어트리뷰트가 무시됩니다.

버전 3.6에서 변경: tzinfo 인자가 추가되었습니다.

classmethod datetime.fromisoformat(date_string)

date.isoformat()과 datetime.isoformat()이 출력하는 형식 중 하나인 date_string에 해당하는 datetime을 반환합니다. 구체적으로, 이 함수는 YYYY-MM-DD[*HH[:MM[:SS[.fff[fff]]]][+HH:MM[:SS[.ffffff]]]] 형식의 문자열을 지원합니다. 여기서 *는 임의의 단일 문자와 일치 할 수 있습니다.

조심

This does not support parsing arbitrary ISO 8601 strings - it is only intended as the inverse operation of datetime.isoformat(). A more full-featured ISO 8601 parser, dateutil.parser.isoparse is available in the third-party package dateutil [https://dateutil.readthedocs.io/en/stable/parser.html#dateutil.parser.isoparse].

버전 3.7에 추가.

classmethod datetime.strptime(date_string, format)

format에 따라 구문 분석된, date_string에 해당하는 datetime를 반환합니다. 이것은 datetime(*(time.strptime(date_string, format)[0:6]))과 동등합니다. date_string과 format을 time.strptime()로 구문 분석할 수 없거나, 시간 튜플이 아닌 값을 반환하면 ValueError가 발생합니다. 포매팅 지시자의 전체 목록은 strftime()과 strptime() 동작을 참조하십시오.

클래스 어트리뷰트:

datetime.min

표현 가능한 가장 이른 datetime, datetime(MINYEAR, 1, 1, tzinfo=None).

datetime.max

표현 가능한 가장 늦은 datetime, datetime(MAXYEAR, 12, 31, 23, 59, 59, 999999, tzinfo=None).

datetime.resolution

같지 않은 datetime 객체 간의 가능한 가장 작은 차이, timedelta(microseconds=1).

인스턴스 어트리뷰트 (읽기 전용):

datetime.year

MINYEAR와 MAXYEAR 사이, 경계 포함.

datetime.month

1과 12 사이, 경계 포함.

datetime.day

1과 주어진 year의 주어진 month의 날 수 사이.

datetime.hour

범위 range(24).

datetime.minute

범위 range(60).

datetime.second

범위 range(60).

datetime.microsecond

범위 range(1000000).

datetime.tzinfo

datetime 생성자에 tzinfo 인자로 전달된 객체이거나, 전달되지 않았으면 None입니다.

datetime.fold

[0, 1] 범위입니다. 반복되는 구간 동안 벽 시간(wall time)의 모호함을 제거하는 데 사용됩니다. 반복되는 구간은 일광 절약 시간이 끝날 때나 현재 지역의 UTC 오프셋이 정치적인 이유로 줄어들어 시계를 되돌릴 때 발생합니다. 값 0(1)은 같은 벽 시간을 나타내는 두 순간 중 이전(이후)을 나타냅니다.

버전 3.6에 추가.

지원되는 연산:

연산

결과

datetime2 = datetime1 + timedelta

(1)

datetime2 = datetime1 - timedelta

(2)

timedelta = datetime1 - datetime2

(3)

datetime1 < datetime2

datetime과 datetime을 비교합니다. (4)

datetime2는 datetime1에서 timedelta 기간만큼 이동한 시간이며, timedelta.days > 0이면 미래로, timedelta.days < 0이면 과거로 이동합니다. 결과는 입력 datetime과 같은 tzinfo 어트리뷰트를 가지고, 이후에 datetime2 - datetime1 == timedelta 입니다. datetime2.year가 MINYEAR보다 작거나 MAXYEAR보다 커지려고 하면 OverflowError가 발생합니다. 입력이 어웨어 객체일 때도 시간대 조정이 수행되지 않음에 유의하십시오.

datetime2 + timedelta == datetime1 을 만족하는 datetime2를 계산합니다. 덧셈과 마찬가지로, 결과는 입력 datetime과 같은 tzinfo 어트리뷰트를 가지며 입력이 어웨어일 때도 시간대 조정이 수행되지 않습니다.

datetime에서 datetime을 빼는 것은 두 피연산자 모두 나이브하거나, 모두 어웨어할 때만 정의됩니다. 하나가 어웨어이고 다른 하나가 나이브면, TypeError가 발생합니다.

둘 다 나이브하거나 둘 다 어웨어하고 같은 tzinfo 어트리뷰트를 가지면, tzinfo 어트리뷰트는 무시되고 결과는 datetime2 + t == datetime1 이 되도록 하는 timedelta 객체 t입니다. 이때 시간대 조정이 수행되지 않습니다.

둘 다 어웨어하고 tzinfo 어트리뷰트가 다르면, a-b는 a와 b가 먼저 나이브 UTC datetime으로 먼저 변환된 것처럼 작동합니다. 구현이 절대 오버플로 하지 않는다는 것을 제외하면 결과는 (a.replace(tzinfo=None) - a.utcoffset()) - (b.replace(tzinfo=None) - b.utcoffset())입니다.

datetime1이 datetime2에 앞서면 datetime1은 datetime2보다 작은 것으로 간주합니다.

하나의 비교 피연산자가 나이브하고 다른 하나는 어웨어하면, 순서 비교가 시도될 때 TypeError가 발생합니다. 동등(equality) 비교에서는, 나이브 인스턴스는 절대 어웨어 인스턴스와 같지 않습니다.

비교 피연산자가 모두 어웨어하고, 같은 tzinfo 어트리뷰트를 가지면, 공통 tzinfo 어트리뷰트가 무시되고 기본 datetime이 비교됩니다. 두 비교 피연산자가 모두 어웨어하고 다른 tzinfo 어트리뷰트를 가지면, 비교 피연산자들은 먼저 그들의 UTC 오프셋 (self.utcoffset() 에서 얻습니다)을 뺀 값으로 조정됩니다.

버전 3.3에서 변경: 나이브와 어웨어 datetime 인스턴스 간의 동등 비교는 TypeError를 발생시키지 않습니다.

참고

비교가 객체 주소 기반의 기본 비교 체계로 떨어지는 것을 막기 위해, datetime 비교는 다른 비교 피연산자가 datetime 객체가 아니면 일반적으로 TypeError를 발생시킵니다. 그러나, 다른 비교 피연산자에 timetuple() 어트리뷰트가 있으면 NotImplemented가 대신 반환됩니다. 이 훅은 다른 형의 날짜 객체에 혼합형 비교를 구현할 기회를 제공합니다. 그렇지 않으면, datetime 객체가 다른 형의 객체와 비교될 때, 비교가 == 나 !=가 아니면 TypeError가 발생합니다. 두 상황에 해당하면 각각 False 나 True를 반환합니다.

datetime 객체는 딕셔너리 키로 사용할 수 있습니다. 불리언 문맥에서, 모든 datetime 객체는 참으로 간주합니다.

인스턴스 메서드:

datetime.date()

같은 year, month, day의 date 객체를 반환합니다.

datetime.time()

같은 hour, minute, second, microsecond 및 fold의 time 객체를 반환합니다. tzinfo는 None입니다. 메서드 timetz()도 참조하십시오.

버전 3.6에서 변경: fold 값은 반환된 time 객체에 복사됩니다.

datetime.timetz()

같은 hour, minute, second, microsecond, fold 및 tzinfo 어트리뷰트의 time 객체를 반환합니다. 메서드 time()도 참조하십시오.

버전 3.6에서 변경: fold 값은 반환된 time 객체에 복사됩니다.

datetime.replace(year=self.year, month=self.month, day=self.day, hour=self.hour, minute=self.minute, second=self.second, microsecond=self.microsecond, tzinfo=self.tzinfo, * fold=0)

키워드 인자로 새로운 값이 주어진 어트리뷰트를 제외하고, 같은 어트리뷰트를 가진 datetime을 반환합니다. tzinfo=None을 지정하면 날짜와 시간 데이터의 변환 없이 어웨어 datetime에서 나이브 datetime을 만들 수 있습니다.

버전 3.6에 추가: fold 인자가 추가되었습니다.

datetime.astimezone(tz=None)

새로운 tzinfo 어트리뷰트 tz를 갖는 datetime 객체를 반환하는데, 결과가 self와 같은 UTC 시간이지만 tz의 지역 시간이 되도록 날짜와 시간 데이터를 조정합니다.

제공된다면 tz는 tzinfo 서브 클래스의 인스턴스여야 하며, utcoffset()과 dst() 메서드는 None을 반환하지 않아야 합니다. self가 나이브하면, 시스템 시간대의 시간을 나타내는 것으로 가정합니다.

인자 없이 (또는 tz=None으로) 호출되면 대상 시간대는 시스템 시간대로 간주합니다. 변환된 datetime 인스턴스의 .tzinfo 어트리뷰트는 OS에서 얻은 시간대 이름과 오프셋을 사용하는 timezone의 인스턴스로 설정됩니다.

self.tzinfo가 tz면, self.astimezone(tz)는 self와 같습니다: 날짜나 시간 데이터 조정이 수행되지 않습니다. 그렇지 않으면 결과는 self와 같은 UTC 시간을 나타내는 tz 시간대의 지역 시간입니다: astz = dt.astimezone(tz) 후에, astz - astz.utcoffset()는 dt - dt.utcoffset()과 같은 날짜와 시간 데이터를 갖습니다.

날짜와 시간 데이터를 조정하지 않고 시간대 객체 tz를 datetime dt에 연결하기만 하려면, dt.replace(tzinfo=tz)를 사용하십시오. 날짜와 시간 데이터를 변환하지 않고 어웨어 datetime dt에서 시간대 객체를 제거하려면, dt.replace(tzinfo=None)를 사용하십시오.

기본 tzinfo.fromutc() 메서드는 astimezone()에 의해 반환된 결과에 영향을 주도록 tzinfo 서브 클래스에서 재정의할 수 있습니다. 에러가 발생하는 경우를 무시하고, astimezone()는 다음과 같이 작동합니다:

def astimezone(self, tz):
    if self.tzinfo is tz:
        return self
    # Convert self to UTC, and attach the new time zone object.
    utc = (self - self.utcoffset()).replace(tzinfo=tz)
    # Convert from UTC to tz's local time.
    return tz.fromutc(utc)

버전 3.3에서 변경: 이제 tz를 생략할 수 있습니다.

버전 3.6에서 변경: 이제 astimezone() 메서드는 이제 나이브 인스턴스에서 호출될 수 있는데, 시스템 지역 시간을 나타내는 것으로 간주합니다.

datetime.utcoffset()

tzinfo가 None이면, None을 반환하고, 그렇지 않으면 self.tzinfo.utcoffset(self)를 반환하고, 후자가 None이나 하루 미만의 크기를 가진 timedelta 객체를 반환하지 않으면 예외를 발생시킵니다.

버전 3.7에서 변경: UTC 오프셋은 분 단위로 제한되지 않습니다.

datetime.dst()

tzinfo가 None이면, None을 반환하고, 그렇지 않으면 self.tzinfo.dst(self)를 반환하고, 후자가 None이나 하루 미만의 크기를 가진 timedelta 객체를 반환하지 않으면 예외를 발생시킵니다.

버전 3.7에서 변경: DST 오프셋은 분 단위로 제한되지 않습니다.

datetime.tzname()

tzinfo가 None이면, None을 반환하고, 그렇지 않으면 self.tzinfo.tzname(self)를 반환하고, 후자가 None이나 문자열 객체를 반환하지 않으면 예외를 발생시킵니다.

datetime.timetuple()

time.localtime()이 반환하는 것과 같은 time.struct_time을 반환합니다. d.timetuple()은 time.struct_time((d.year, d.month, d.day, d.hour, d.minute, d.second, d.weekday(), yday, dst))와 동등합니다. 여기서 yday = d.toordinal() - date(d.year, 1, 1).toordinal() + 1 은 1월 1일에 1로 시작하는 현재 연도의 날짜 번호입니다. 결과의 tm_isdst 플래그는 dst() 메서드에 따라 설정됩니다: tzinfo가 None이거나 dst()가 None을 반환하면, tm_isdst는 -1로 설정됩니다; 그렇지 않고 dst()가 0이 아닌 값을 반환하면, tm_isdst는 1로 설정됩니다; 그렇지 않으면 tm_isdst는 0으로 설정됩니다.

datetime.utctimetuple()

datetime 인스턴스 d가 나이브하면, 이것은 d.dst()가 무엇을 반환하는지와 관계없이 tm_isdst가 강제로 0이 된다는 점만 제외하면, d.timetuple()과 같습니다. DST는 UTC 시간에는 적용되지 않습니다.

d가 어웨어하면, d는 d.utcoffset()을 빼서 UTC 시간으로 정규화되고, 정규화된 시간의 time.struct_time이 반환됩니다. tm_isdst는 강제로 0이 됩니다. d.year가 MINYEAR나 MAXYEAR고 UTC 조정이 연도 경계를 넘어가면 OverflowError가 발생할 수 있습니다.

datetime.toordinal()

날짜의 역산 그레고리력 서수를 반환합니다. self.date().toordinal()과 같습니다.

datetime.timestamp()

datetime 인스턴스에 해당하는 POSIX 타임스탬프를 반환합니다. 반환 값은 time.time()이 반환하는 것과 비슷한 float입니다.

나이브 datetime 인스턴스는 지역 시간을 나타내는 것으로 간주하며 이 메서드는 변환을 수행하기 위해 플랫폼 C mktime() 함수에 의존합니다. datetime는 많은 플랫폼에서 mktime()보다 더 넓은 범위의 값을 지원하기 때문에, 이 메서드는 먼 과거나 먼 미래의 시간에 대해 OverflowError를 발생시킬 수 있습니다.

어웨어 datetime 인스턴스의 경우, 반환 값은 다음과 같이 계산됩니다:

(dt - datetime(1970, 1, 1, tzinfo=timezone.utc)).total_seconds()

버전 3.3에 추가.

버전 3.6에서 변경: timestamp() 메서드는 fold 어트리뷰트를 사용하여 반복되는 구간의 시간을 구분합니다.

참고

UTC 시간을 나타내는 나이브 datetime 인스턴스에서 직접 POSIX 타임스탬프를 얻는 메서드는 없습니다. 응용 프로그램에서 이 관례를 사용하고 시스템 시간대가 UTC로 설정되어 있지 않으면, tzinfo=timezone.utc를 제공하여 POSIX 타임스탬프를 얻을 수 있습니다:

timestamp = dt.replace(tzinfo=timezone.utc).timestamp()

또는 직접 타임스탬프를 계산할 수 있습니다:

timestamp = (dt - datetime(1970, 1, 1)) / timedelta(seconds=1)

datetime.weekday()

정수로 요일을 반환합니다. 월요일은 0이고 일요일은 6입니다. self.date().weekday()와 같습니다. isoweekday()도 참조하십시오.

datetime.isoweekday()

정수로 요일을 반환합니다. 월요일은 1이고 일요일은 7입니다. self.date().isoweekday() 와 같습니다. weekday(), isocalendar()도 참조하십시오.

datetime.isocalendar()

3-튜플 (ISO 연도, ISO 주 번호, ISO 요일)을 반환합니다. self.date().isocalendar()와 같습니다.

datetime.isoformat(sep='T', timespec='auto')

ISO 8601 형식으로 날짜와 시간을 나타내는 문자열을 반환합니다, YYYY-MM-DDTHH:MM:SS.ffffff, 또는 microsecond가 0이면, YYYY-MM-DDTHH:MM:SS

utcoffset()이 None을 반환하지 않으면, UTC 오프셋을 제공하는 문자열을 덧붙입니다: YYYY-MM-DDTHH:MM:SS.ffffff+HH:MM[:SS[.ffffff]], 또는 microsecond가 0이면, YYYY-MM-DDTHH:MM:SS+HH:MM[:SS[.ffffff]].

선택적 인자 sep(기본값 'T')은 한 문자 구분자로, 결과의 날짜와 시간 부분 사이에 배치됩니다. 예를 들어,

>>> from datetime import tzinfo, timedelta, datetime
>>> class TZ(tzinfo):
...     def utcoffset(self, dt): return timedelta(minutes=-399)
...
>>> datetime(2002, 12, 25, tzinfo=TZ()).isoformat(' ')
'2002-12-25 00:00:00-06:39'

선택적 인자 timespec은 포함할 시간의 추가 구성 요소 수를 지정합니다 (기본값은 'auto'입니다). 다음 중 하나일 수 있습니다:

'auto': microsecond가 0이면 'seconds'와 같고, 그렇지 않으면 'microseconds'와 같습니다.

'hours': hour를 두 자리 숫자 HH 형식으로 포함합니다.

'minutes': hour와 minute를 HH:MM 형식으로 포함합니다.

'seconds': hour, minute 및 second를 HH:MM:SS 형식으로 포함합니다.

'milliseconds': 전체 시간을 포함하지만, 초 미만은 밀리초 단위로 자릅니다. HH:MM:SS.sss 형식입니다.

'microseconds': 전체 시간을 HH:MM:SS.ffffff 형식으로 포함합니다.

참고

제외된 시간 구성 요소는 반올림되지 않고 잘립니다.

잘못된 timespec 인자는 ValueError를 발생시킵니다.

>>> from datetime import datetime
>>> datetime.now().isoformat(timespec='minutes')
'2002-12-25T00:00'
>>> dt = datetime(2015, 1, 1, 12, 30, 59, 0)
>>> dt.isoformat(timespec='microseconds')
'2015-01-01T12:30:59.000000'

버전 3.6에 추가: timespec 인자가 추가되었습니다.

datetime.__str__()

datetime 인스턴스 d에 대해, str(d)는 d.isoformat(' ')과 동등합니다.

datetime.ctime()

날짜와 시간을 나타내는 문자열을 반환합니다, 예를 들어 datetime(2002, 12, 4, 20, 30, 40).ctime() == 'Wed Dec  4 20:30:40 2002'. d.ctime()은 네이티브 C ctime() 함수(time.ctime()이 호출하지만, datetime.ctime()은 호출하지 않습니다)가 C 표준을 준수하는 플랫폼에서 time.ctime(time.mktime(d.timetuple()))과 동등합니다.

datetime.strftime(format)

명시적인 포맷 문자열에 의해 제어되는 날짜와 시간을 나타내는 문자열을 반환합니다. 포매팅 지시자의 전체 목록은 strftime()과 strptime() 동작을 참조하십시오.

datetime.__format__(format)

datetime.strftime()과 같습니다. 이것이 포맷 문자열 리터럴과 str.format()을 사용할 때 datetime 객체를 위한 포맷 문자열을 지정할 수 있도록 합니다. 포매팅 지시자의 전체 목록은 strftime()과 strptime() 동작을 참조하십시오.

datetime 객체로 작업하는 예제:

>>> from datetime import datetime, date, time
>>> # Using datetime.combine()
>>> d = date(2005, 7, 14)
>>> t = time(12, 30)
>>> datetime.combine(d, t)
datetime.datetime(2005, 7, 14, 12, 30)
>>> # Using datetime.now() or datetime.utcnow()
>>> datetime.now()
datetime.datetime(2007, 12, 6, 16, 29, 43, 79043)   # GMT +1
>>> datetime.utcnow()
datetime.datetime(2007, 12, 6, 15, 29, 43, 79060)
>>> # Using datetime.strptime()
>>> dt = datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M")
>>> dt
datetime.datetime(2006, 11, 21, 16, 30)
>>> # Using datetime.timetuple() to get tuple of all attributes
>>> tt = dt.timetuple()
>>> for it in tt:
...     print(it)
...
2006    # year
11      # month
21      # day
16      # hour
30      # minute
0       # second
1       # weekday (0 = Monday)
325     # number of days since 1st January
-1      # dst - method tzinfo.dst() returned None
>>> # Date in ISO format
>>> ic = dt.isocalendar()
>>> for it in ic:
...     print(it)
...
2006    # ISO year
47      # ISO week
2       # ISO weekday
>>> # Formatting datetime
>>> dt.strftime("%A, %d. %B %Y %I:%M%p")
'Tuesday, 21. November 2006 04:30PM'
>>> 'The {1} is {0:%d}, the {2} is {0:%B}, the {3} is {0:%I:%M%p}.'.format(dt, "day", "month", "time")
'The day is 21, the month is November, the time is 04:30PM.'

tzinfo와 함께 datetime 사용하기:

>>> from datetime import timedelta, datetime, tzinfo, timezone
>>> class KabulTz(tzinfo):
...     # Kabul used +4 until 1945, when they moved to +4:30
...     UTC_MOVE_DATE = datetime(1944, 12, 31, 20, tzinfo=timezone.utc)
...     def utcoffset(self, dt):
...         if dt.year < 1945:
...             return timedelta(hours=4)
...         elif (1945, 1, 1, 0, 0) <= dt.timetuple()[:5] < (1945, 1, 1, 0, 30):
...             # If dt falls in the imaginary range, use fold to decide how
...             # to resolve. See PEP495
...             return timedelta(hours=4, minutes=(30 if dt.fold else 0))
...         else:
...             return timedelta(hours=4, minutes=30)
...
...     def fromutc(self, dt):
...         # A custom implementation is required for fromutc as
...         # the input to this function is a datetime with utc values
...         # but with a tzinfo set to self
...         # See datetime.astimezone or fromtimestamp
...
...         # Follow same validations as in datetime.tzinfo
...         if not isinstance(dt, datetime):
...             raise TypeError("fromutc() requires a datetime argument")
...         if dt.tzinfo is not self:
...             raise ValueError("dt.tzinfo is not self")
...
...         if dt.replace(tzinfo=timezone.utc) >= self.UTC_MOVE_DATE:
...             return dt + timedelta(hours=4, minutes=30)
...         else:
...             return dt + timedelta(hours=4)
...
...     def dst(self, dt):
...         return timedelta(0)
...
...     def tzname(self, dt):
...         if dt >= self.UTC_MOVE_DATE:
...             return "+04:30"
...         else:
...             return "+04"
...
...     def  __repr__(self):
...         return f"{self.__class__.__name__}()"
...
>>> tz1 = KabulTz()
>>> # Datetime before the change
>>> dt1 = datetime(1900, 11, 21, 16, 30, tzinfo=tz1)
>>> print(dt1.utcoffset())
4:00:00
>>> # Datetime after the change
>>> dt2 = datetime(2006, 6, 14, 13, 0, tzinfo=tz1)
>>> print(dt2.utcoffset())
4:30:00
>>> # Convert datetime to another time zone
>>> dt3 = dt2.astimezone(timezone.utc)
>>> dt3
datetime.datetime(2006, 6, 14, 8, 30, tzinfo=datetime.timezone.utc)
>>> dt2
datetime.datetime(2006, 6, 14, 13, 0, tzinfo=KabulTz())
>>> dt2.utctimetuple() == dt3.utctimetuple()
True

time 객체

time 객체는 특정 날짜와 관계없는 (지역) 시간을 나타내며, tzinfo 객체를 통해 조정할 수 있습니다.

class datetime.time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0)

All arguments are optional. tzinfo may be None, or an instance of a tzinfo subclass. The remaining arguments must be integers in the following ranges:

0 <= hour < 24,

0 <= minute < 60,

0 <= second < 60,

0 <= microsecond < 1000000,

fold in [0, 1].

이 범위를 벗어나는 인자가 주어지면, ValueError가 발생합니다. tzinfo의 기본값은 None이고, 그 외의 모든 기본값은 0입니다.

클래스 어트리뷰트:

time.min

표현 가능한 가장 이른 time, time(0, 0, 0, 0).

time.max

표현 가능한 가장 늦은 time, time(23, 59, 59, 999999).

time.resolution

같지 않은 time 객체 간의 가능한 가장 작은 차이, timedelta(microseconds=1), 하지만 time 객체에 대한 산술은 지원되지 않습니다.

인스턴스 어트리뷰트 (읽기 전용):

time.hour

범위 range(24).

time.minute

범위 range(60).

time.second

범위 range(60).

time.microsecond

범위 range(1000000).

time.tzinfo

time 생성자에 tzinfo 인자로 전달된 객체이거나, 전달되지 않았으면 None입니다.

time.fold

[0, 1] 범위입니다. 반복되는 구간 동안 벽 시간(wall time)의 모호함을 제거하는 데 사용됩니다. 반복되는 구간은 일광 절약 시간이 끝날 때나 현재 지역의 UTC 오프셋이 정치적인 이유로 줄어들어 시계를 되돌릴 때 발생합니다. 값 0(1)은 같은 벽 시간을 나타내는 두 순간 중 이전(이후)을 나타냅니다.

버전 3.6에 추가.

지원되는 연산:

time과 time의 비교, 이때 a가 b에 앞서면 a가 b보다 작은 것으로 간주합니다. 하나의 비교 피연산자가 나이브하고 다른 하나는 어웨어하면, 순서 비교가 시도될 때 TypeError가 발생합니다. 동등(equality) 비교에서는, 나이브 인스턴스는 절대 어웨어 인스턴스와 같지 않습니다.

비교 피연산자가 모두 어웨어하고, 같은 tzinfo 어트리뷰트를 가지면, 공통 tzinfo 어트리뷰트가 무시되고 기본 time이 비교됩니다. 두 비교 피연산자가 모두 어웨어하고 다른 tzinfo 어트리뷰트를 가지면, 비교 피연산자들은 먼저 그들의 UTC 오프셋 (self.utcoffset()에서 얻습니다)을 뺀 값으로 조정됩니다. 혼합형 비교가 객체 주소 기반의 기본 비교로 떨어지는 것을 막기 위해, time 객체가 다른 형의 객체와 비교될 때, 비교가 == 이나 !=가 아니면 TypeError가 발생합니다. 두 상황에 해당하면 각각 False 나 True를 반환합니다.

버전 3.3에서 변경: 나이브와 어웨어 time 인스턴스 간의 동등 비교는 TypeError를 발생시키지 않습니다.

hash, 딕셔너리 키로 사용

효율적인 피클링

불리언 문맥에서, time 객체는 항상 참으로 간주합니다.

버전 3.5에서 변경: 파이썬 3.5 이전에, time 객체는 UTC 자정을 나타낼 때 거짓으로 간주했습니다. 이 동작은 애매하고 에러가 발생하기 쉬운 것으로 간주하여 파이썬 3.5에서 제거되었습니다. 자세한 내용은 bpo-13936 [https://bugs.python.org/issue?@action=redirect&bpo=13936]을 참조하십시오.

기타 생성자:

classmethod time.fromisoformat(time_string)

time.isoformat()이 출력하는 형식 중 하나인 time_string에 해당하는 time을 반환합니다. 구체적으로, 이 함수는 HH[:MM[:SS[.fff[fff]]]][+HH:MM[:SS[.ffffff]]] 형식의 문자열을 지원합니다.

조심

이것은 임의의 ISO 8601 문자열을 구문 분석하는 것을 지원하지 않습니다 - 이것은 time.isoformat()의 역연산이고자 할 뿐입니다.

버전 3.7에 추가.

인스턴스 메서드:

time.replace(hour=self.hour, minute=self.minute, second=self.second, microsecond=self.microsecond, tzinfo=self.tzinfo, * fold=0)

키워드 인자로 새로운 값이 주어진 어트리뷰트를 제외하고, 같은 값을 가진 time을 반환합니다. tzinfo=None을 지정하면 시간 데이터의 변환 없이 어웨어 time에서 나이브 time을 만들 수 있습니다.

버전 3.6에 추가: fold 인자가 추가되었습니다.

time.isoformat(timespec='auto')

ISO 8601 형식으로 시간을 나타내는 문자열을 반환합니다, HH:MM:SS.ffffff, 또는 microsecond가 0이면, HH:MM:SS utcoffset()이 None을 반환하지 않으면, UTC 오프셋을 제공하는 문자열을 덧붙입니다: HH:MM:SS.ffffff+HH:MM[:SS[.ffffff]], 또는 self.microsecond가 0이면, HH:MM:SS+HH:MM[:SS[.ffffff]].

선택적 인자 timespec은 포함할 시간의 추가 구성 요소 수를 지정합니다 (기본값은 'auto'입니다). 다음 중 하나일 수 있습니다:

'auto': microsecond가 0이면 'seconds'와 같고, 그렇지 않으면 'microseconds'와 같습니다.

'hours': hour를 두 자리 숫자 HH 형식으로 포함합니다.

'minutes': hour와 minute를 HH:MM 형식으로 포함합니다.

'seconds': hour, minute 및 second를 HH:MM:SS 형식으로 포함합니다.

'milliseconds': 전체 시간을 포함하지만, 초 미만은 밀리초 단위로 자릅니다. HH:MM:SS.sss 형식입니다.

'microseconds': 전체 시간을 HH:MM:SS.ffffff 형식으로 포함합니다.

참고

제외된 시간 구성 요소는 반올림되지 않고 잘립니다.

잘못된 timespec 인자는 ValueError를 발생시킵니다.

>>> from datetime import time
>>> time(hour=12, minute=34, second=56, microsecond=123456).isoformat(timespec='minutes')
'12:34'
>>> dt = time(hour=12, minute=34, second=56, microsecond=0)
>>> dt.isoformat(timespec='microseconds')
'12:34:56.000000'
>>> dt.isoformat(timespec='auto')
'12:34:56'

버전 3.6에 추가: timespec 인자가 추가되었습니다.

time.__str__()

time t에 대해, str(t)는 t.isoformat()과 동등합니다.

time.strftime(format)

명시적인 포맷 문자열로 제어되는, 시간을 나타내는 문자열을 반환합니다. 포매팅 지시자의 전체 목록은, strftime()과 strptime() 동작을 참조하십시오.

time.__format__(format)

time.strftime()과 같습니다. 이것이 포맷 문자열 리터럴과 str.format()을 사용할 때 time 객체를 위한 포맷 문자열을 지정할 수 있도록 합니다. 포매팅 지시자의 전체 목록은 strftime()과 strptime() 동작을 참조하십시오.

time.utcoffset()

tzinfo가 None이면, None을 반환하고, 그렇지 않으면 self.tzinfo.utcoffset(None)를 반환하고, 후자가 None이나 하루 미만의 크기를 가진 timedelta 객체를 반환하지 않으면 예외를 발생시킵니다.

버전 3.7에서 변경: UTC 오프셋은 분 단위로 제한되지 않습니다.

time.dst()

tzinfo가 None이면, None을 반환하고, 그렇지 않으면 self.tzinfo.dst(None)를 반환하고, 후자가 None이나 하루 미만의 크기를 가진 timedelta 객체를 반환하지 않으면 예외를 발생시킵니다.

버전 3.7에서 변경: DST 오프셋은 분 단위로 제한되지 않습니다.

time.tzname()

tzinfo가 None이면, None을 반환하고, 그렇지 않으면 self.tzinfo.tzname(None)를 반환하고, 후자가 None이나 문자열 객체를 반환하지 않으면 예외를 발생시킵니다.

예제:

>>> from datetime import time, tzinfo, timedelta
>>> class TZ1(tzinfo):
...     def utcoffset(self, dt):
...         return timedelta(hours=1)
...     def dst(self, dt):
...         return timedelta(0)
...     def tzname(self,dt):
...         return "+01:00"
...     def  __repr__(self):
...         return f"{self.__class__.__name__}()"
...
>>> t = time(12, 10, 30, tzinfo=TZ1())
>>> t
datetime.time(12, 10, 30, tzinfo=TZ1())
>>> t.isoformat()
'12:10:30+01:00'
>>> t.dst()
datetime.timedelta(0)
>>> t.tzname()
'+01:00'
>>> t.strftime("%H:%M:%S %Z")
'12:10:30 +01:00'
>>> 'The {} is {:%H:%M}.'.format("time", t)
'The time is 12:10.'

tzinfo 객체

class datetime.tzinfo

이것은 추상 베이스 클래스입니다. 즉, 이 클래스를 직접 인스턴스로 만들면 안 됩니다. 여러분은 구상(concrete) 서브 클래스를 파생시킬 필요가 있고, (적어도) 여러분이 사용하는 datetime 메서드에 필요한 표준 tzinfo 메서드의 구현을 제공해야 합니다. datetime 모듈은 간단한 tzinfo의 구상 서브 클래스 timezone를 제공하는데, UTC 자체나 북미 EST, EDT와 같은 UTC로부터의 고정 오프셋을 갖는 시간대를 나타낼 수 있습니다.

tzinfo의 (구상 서브 클래스의) 인스턴스는 datetime과 time 객체의 생성자에 전달될 수 있습니다. 이 객체들은 자신의 어트리뷰트를 지역 시간으로 간주하며, tzinfo 객체는 지역 시간의 UTC로부터의 오프셋, 시간대 이름 및 DST 오프셋을 모두 전달된 날짜나 시간 객체에 상대적으로 얻는 메서드들을 지원합니다.

피클링을 위한 특별한 요구 사항: tzinfo 서브 클래스는 인자 없이 호출할 수 있는 __init__() 메서드를 가져야 합니다. 그렇지 않으면 피클 될 수는 있지만, 다시 역 피클 될 수는 없습니다. 이것은 기술적 요구사항으로, 미래에 완화될 수 있습니다.

tzinfo의 구상 서브 클래스는 다음 메서드를 구현해야 할 수도 있습니다. 정확히 어떤 메서드가 필요한지는 어웨어 datetime 객체를 사용하는 방법에 따라 다릅니다. 확실하지 않으면, 그냥 모두 구현하십시오.

tzinfo.utcoffset(dt)

지역 시간의 UTC로부터의 오프셋을 UTC의 동쪽에 있을 때 양의 값을 갖는 timedelta 객체로 반환합니다. 지역 시간이 UTC의 서쪽이면 이 값은 음수여야 합니다. 이 값은 UTC로부터의 총 오프셋입니다: 예를 들어, tzinfo 객체가 시간대와 DST 조정을 모두 나타내면, utcoffset()은 그들의 합계를 반환해야 합니다. UTC 오프셋을 알 수 없으면, None을 반환합니다. 그렇지 않으면 반환되는 값은 반드시 -timedelta(hours=24)와 timedelta(hours=24) 사이의 timedelta 객체여야 합니다 (오프셋의 크기는 하루 미만이어야 합니다). utcoffset()의 대부분 구현은 아마도 이 두 가지 중 하나일 것입니다:

return CONSTANT                 # fixed-offset class
return CONSTANT + self.dst(dt)  # daylight-aware class

utcoffset()이 None을 반환하지 않으면, dst()도 None을 반환하지 않아야 합니다.

utcoffset()의 기본 구현은 NotImplementedError를 발생시킵니다.

버전 3.7에서 변경: UTC 오프셋은 분 단위로 제한되지 않습니다.

tzinfo.dst(dt)

일광 절약 시간 (DST) 조정을 timedelta 객체로, 또는 DST 정보를 모르면 None을 반환합니다. DST가 적용되고 있지 않으면, timedelta(0)를 반환합니다. DST가 적용 중이면, 오프셋을 timedelta 객체로 반환합니다 (자세한 내용은 utcoffset()을 참조하십시오). 해당하면, DST 오프셋이 utcoffset()에서 반환된 UTC 오프셋에 이미 추가되어 있으므로, 따로 DST 정보를 얻는 데 관심이 없다면 dst()를 확인할 필요가 없습니다. 예를 들어, datetime.timetuple()은 tzinfo 어트리뷰트의 dst() 메서드를 호출하여 tm_isdst 플래그를 어떻게 설정할지를 결정하고, tzinfo.fromutc()는 시간대를 가로지를 때 DST 변경을 고려하기 위해 dst()를 호출합니다.

표준과 일광 절약 시간을 모두 모형화하는 tzinfo 서브 클래스의 인스턴스 tz는 다음과 같은 의미에서 일관되어야 합니다:

tz.utcoffset(dt) - tz.dst(dt)

는 dt.tzinfo == tz인 모든 datetime dt에 대해 같은 결과를 반환해야 합니다. 정상적인 tzinfo 서브 클래스에서, 이 표현식은 시간대의 “표준 오프셋”을 산출하는데, 이것은 날짜나 시간에 의존하지 않고, 지리적 위치에만 의존해야 합니다. datetime.astimezone() 구현은 이 일관성에 의존하지만, 위반을 감지할 수는 없습니다; 이를 보장하는 것은 프로그래머의 책임입니다. tzinfo 서브 클래스가 이를 보장 할 수 없으면, astimezone()와 상관없이 올바르게 작동하도록 tzinfo.fromutc()의 기본 구현을 재정의할 수 있습니다.

dst()의 대부분 구현은 아마도 이 두 가지 중 하나일 것입니다:

def dst(self, dt):
    # a fixed-offset class:  doesn't account for DST
    return timedelta(0)

또는

def dst(self, dt):
    # Code to set dston and dstoff to the time zone's DST
    # transition times based on the input dt.year, and expressed
    # in standard local time.  Then

    if dston <= dt.replace(tzinfo=None) < dstoff:
        return timedelta(hours=1)
    else:
        return timedelta(0)

dst()의 기본 구현은 NotImplementedError를 발생시킵니다.

버전 3.7에서 변경: DST 오프셋은 분 단위로 제한되지 않습니다.

tzinfo.tzname(dt)

datetime 객체 dt에 해당하는 시간대 이름을 문자열로 반환합니다. 문자열 이름에 관한 어떤 것도 datetime 모듈에 의해 정의되지 않으며, 특별히 어떤 것을 의미해야 한다는 요구 사항이 없습니다. 예를 들어, “GMT”, “UTC”, “-500”, “-5:00”, “EDT”, “US/Eastern”, “America/New York”은 모두 유효한 응답입니다. 문자열 이름을 모르면 None을 반환합니다. 이것은 고정된 문자열이기보다 메서드인데, 주로 어떤 tzinfo 서브 클래스가 전달된 dt의 특정 값에 따라 다른 이름을 반환하기를 원하기 때문입니다. 특히 tzinfo 클래스가 일광 절약 시간을 고려할 때 그렇습니다.

tzname()의 기본 구현은 NotImplementedError를 발생시킵니다.

이 메서드들은 datetime나 time 객체에서 같은 이름의 메서드에 대한 응답으로 호출됩니다. datetime 객체는 자신을 인자로 전달하고, time 객체는 인자로 None을 전달합니다. 따라서 tzinfo 서브 클래스의 메서드는 None이나 datetime 클래스의 dt 인자를 받아들일 준비가 되어 있어야 합니다.

None이 전달되면, 최선의 응답을 결정하는 것은 클래스 설계자에게 달려있습니다. 예를 들어, 클래스가 tzinfo 프로토콜에 time 객체가 참여하지 않는다고 말하고 싶다면 None을 반환하는 것이 적절합니다. 표준 오프셋을 발견하는 다른 규칙이 없으므로, utcoffset(None)이 표준 UTC 오프셋을 반환하는 것이 더 유용할 수 있습니다.

datetime 메서드에 대한 응답으로 datetime 객체가 전달되면, dt.tzinfo는 self와 같은 객체입니다. 사용자 코드가 tzinfo 메서드를 직접 호출하지 않는 한, tzinfo 메서드는 이것에 의존할 수 있습니다. tzinfo 메서드가 dt를 지역 시간으로 해석하고, 다른 시간대의 객체를 걱정할 필요가 없도록 하려는 의도입니다.

서브 클래스가 재정의할 수 있는 tzinfo 메서드가 하나 더 있습니다:

tzinfo.fromutc(dt)

이것은 기본 datetime.astimezone() 구현에서 호출됩니다. 거기에서 호출되면, dt.tzinfo는 self이고, dt의 날짜와 시간 데이터는 UTC 시간으로 표시된 것으로 봅니다. fromutc()의 목적은 날짜와 시간 데이터를 조정하여, self의 지역 시간으로 동등한 datetime을 반환하는 것입니다.

대부분 tzinfo 서브 클래스는 문제없이 기본 fromutc() 구현을 상속할 수 있어야 합니다. 고정 오프셋 시간대와 표준과 일광 절약 시간을 모두 고려하는 시간대를, 해마다 DST 전환 시간이 다를 때도 일광 절약 시간을 처리할 수 있을 만큼 강력합니다. 기본 fromutc() 구현이 모든 경우에 올바르게 처리하지 못할 수 있는 시간대의 예는 (정치적 이유로 인해 발생할 수 있는) 특정 날짜와 시간에 따라 (UTC로부터의) 표준 오프셋이 달라지는 것입니다. 결과가 표준 오프셋이 변경되는 순간에 걸치는 시간 중 하나일 때, astimezone()과 fromutc()의 기본 구현은 여러분이 원하는 결과를 생성하지 못할 수 있습니다.

에러가 발생하는 경우를 위한 코드를 생략하면, 기본 fromutc() 구현은 다음과 같이 동작합니다:

def fromutc(self, dt):
    # raise ValueError error if dt.tzinfo is not self
    dtoff = dt.utcoffset()
    dtdst = dt.dst()
    # raise ValueError if dtoff is None or dtdst is None
    delta = dtoff - dtdst  # this is self's standard offset
    if delta:
        dt += delta   # convert to standard local time
        dtdst = dt.dst()
        # raise ValueError if dtdst is None
    if dtdst:
        return dt + dtdst
    else:
        return dt

다음 tzinfo_examples.py 파일에는 tzinfo 클래스의 몇 가지 예가 나와 있습니다:

from datetime import tzinfo, timedelta, datetime

ZERO = timedelta(0)
HOUR = timedelta(hours=1)
SECOND = timedelta(seconds=1)

# A class capturing the platform's idea of local time.
# (May result in wrong values on historical times in
#  timezones where UTC offset and/or the DST rules had
#  changed in the past.)
import time as _time

STDOFFSET = timedelta(seconds = -_time.timezone)
if _time.daylight:
    DSTOFFSET = timedelta(seconds = -_time.altzone)
else:
    DSTOFFSET = STDOFFSET

DSTDIFF = DSTOFFSET - STDOFFSET

class LocalTimezone(tzinfo):

    def fromutc(self, dt):
        assert dt.tzinfo is self
        stamp = (dt - datetime(1970, 1, 1, tzinfo=self)) // SECOND
        args = _time.localtime(stamp)[:6]
        dst_diff = DSTDIFF // SECOND
        # Detect fold
        fold = (args == _time.localtime(stamp - dst_diff))
        return datetime(*args, microsecond=dt.microsecond,
                        tzinfo=self, fold=fold)

    def utcoffset(self, dt):
        if self._isdst(dt):
            return DSTOFFSET
        else:
            return STDOFFSET

    def dst(self, dt):
        if self._isdst(dt):
            return DSTDIFF
        else:
            return ZERO

    def tzname(self, dt):
        return _time.tzname[self._isdst(dt)]

    def _isdst(self, dt):
        tt = (dt.year, dt.month, dt.day,
              dt.hour, dt.minute, dt.second,
              dt.weekday(), 0, 0)
        stamp = _time.mktime(tt)
        tt = _time.localtime(stamp)
        return tt.tm_isdst > 0

Local = LocalTimezone()

# A complete implementation of current DST rules for major US time zones.

def first_sunday_on_or_after(dt):
    days_to_go = 6 - dt.weekday()
    if days_to_go:
        dt += timedelta(days_to_go)
    return dt

# US DST Rules
#
# This is a simplified (i.e., wrong for a few cases) set of rules for US
# DST start and end times. For a complete and up-to-date set of DST rules
# and timezone definitions, visit the Olson Database (or try pytz):
# http://www.twinsun.com/tz/tz-link.htm
# http://sourceforge.net/projects/pytz/ (might not be up-to-date)
#
# In the US, since 2007, DST starts at 2am (standard time) on the second
# Sunday in March, which is the first Sunday on or after Mar 8.
DSTSTART_2007 = datetime(1, 3, 8, 2)
# and ends at 2am (DST time) on the first Sunday of Nov.
DSTEND_2007 = datetime(1, 11, 1, 2)
# From 1987 to 2006, DST used to start at 2am (standard time) on the first
# Sunday in April and to end at 2am (DST time) on the last
# Sunday of October, which is the first Sunday on or after Oct 25.
DSTSTART_1987_2006 = datetime(1, 4, 1, 2)
DSTEND_1987_2006 = datetime(1, 10, 25, 2)
# From 1967 to 1986, DST used to start at 2am (standard time) on the last
# Sunday in April (the one on or after April 24) and to end at 2am (DST time)
# on the last Sunday of October, which is the first Sunday
# on or after Oct 25.
DSTSTART_1967_1986 = datetime(1, 4, 24, 2)
DSTEND_1967_1986 = DSTEND_1987_2006

def us_dst_range(year):
    # Find start and end times for US DST. For years before 1967, return
    # start = end for no DST.
    if 2006 < year:
        dststart, dstend = DSTSTART_2007, DSTEND_2007
    elif 1986 < year < 2007:
        dststart, dstend = DSTSTART_1987_2006, DSTEND_1987_2006
    elif 1966 < year < 1987:
        dststart, dstend = DSTSTART_1967_1986, DSTEND_1967_1986
    else:
        return (datetime(year, 1, 1), ) * 2

    start = first_sunday_on_or_after(dststart.replace(year=year))
    end = first_sunday_on_or_after(dstend.replace(year=year))
    return start, end

class USTimeZone(tzinfo):

    def __init__(self, hours, reprname, stdname, dstname):
        self.stdoffset = timedelta(hours=hours)
        self.reprname = reprname
        self.stdname = stdname
        self.dstname = dstname

    def __repr__(self):
        return self.reprname

    def tzname(self, dt):
        if self.dst(dt):
            return self.dstname
        else:
            return self.stdname

    def utcoffset(self, dt):
        return self.stdoffset + self.dst(dt)

    def dst(self, dt):
        if dt is None or dt.tzinfo is None:
            # An exception may be sensible here, in one or both cases.
            # It depends on how you want to treat them.  The default
            # fromutc() implementation (called by the default astimezone()
            # implementation) passes a datetime with dt.tzinfo is self.
            return ZERO
        assert dt.tzinfo is self
        start, end = us_dst_range(dt.year)
        # Can't compare naive to aware objects, so strip the timezone from
        # dt first.
        dt = dt.replace(tzinfo=None)
        if start + HOUR <= dt < end - HOUR:
            # DST is in effect.
            return HOUR
        if end - HOUR <= dt < end:
            # Fold (an ambiguous hour): use dt.fold to disambiguate.
            return ZERO if dt.fold else HOUR
        if start <= dt < start + HOUR:
            # Gap (a non-existent hour): reverse the fold rule.
            return HOUR if dt.fold else ZERO
        # DST is off.
        return ZERO

    def fromutc(self, dt):
        assert dt.tzinfo is self
        start, end = us_dst_range(dt.year)
        start = start.replace(tzinfo=self)
        end = end.replace(tzinfo=self)
        std_time = dt + self.stdoffset
        dst_time = std_time + HOUR
        if end <= dst_time < end + HOUR:
            # Repeated hour
            return std_time.replace(fold=1)
        if std_time < start or dst_time >= end:
            # Standard time
            return std_time
        if start <= std_time < end - HOUR:
            # Daylight saving time
            return dst_time

Eastern  = USTimeZone(-5, "Eastern",  "EST", "EDT")
Central  = USTimeZone(-6, "Central",  "CST", "CDT")
Mountain = USTimeZone(-7, "Mountain", "MST", "MDT")
Pacific  = USTimeZone(-8, "Pacific",  "PST", "PDT")

DST 전환점에서 표준 시간과 일광 절약 시간을 모두 고려하는 tzinfo 서브 클래스에는 일 년에 두 번 불가피한 미묘함이 있음에 유의하십시오. 구체적으로, 3월 두 번째 일요일의 1:59 (EST) 다음 분에 시작하고, 11월 첫 번째 일요일 1:59 (EDT) 다음 분에 끝나는 미국 Eastern(UTC -0500)을 고려하십시오:

  UTC   3:MM  4:MM  5:MM  6:MM  7:MM  8:MM
  EST  22:MM 23:MM  0:MM  1:MM  2:MM  3:MM
  EDT  23:MM  0:MM  1:MM  2:MM  3:MM  4:MM

start  22:MM 23:MM  0:MM  1:MM  3:MM  4:MM

  end  23:MM  0:MM  1:MM  1:MM  2:MM  3:MM

DST가 시작할 때 (“start” 줄), 지역 벽시계는 1:59에서 3:00로 도약합니다. 그날에는 2:MM 형식의 벽 시간은 실질적인 의미가 없으므로, astimezone(Eastern)은 DST가 시작하는 날에 hour == 2인 결과를 전달하지 않습니다. 예를 들어, 2016년 봄의 전진 전환(forward transition)에서, 다음과 같은 결과를 얻습니다

>>> from datetime import datetime, timezone
>>> from tzinfo_examples import HOUR, Eastern
>>> u0 = datetime(2016, 3, 13, 5, tzinfo=timezone.utc)
>>> for i in range(4):
...     u = u0 + i*HOUR
...     t = u.astimezone(Eastern)
...     print(u.time(), 'UTC =', t.time(), t.tzname())
...
05:00:00 UTC = 00:00:00 EST
06:00:00 UTC = 01:00:00 EST
07:00:00 UTC = 03:00:00 EDT
08:00:00 UTC = 04:00:00 EDT

DST가 끝날 때 (“end” 줄), 잠재적으로 더 나쁜 문제가 있습니다: 지역 시간으로 명확하게 말할 수 없는 시(hour)가 있습니다: 일광 절약 시간의 마지막 한 시간. Eastern에서, 이것은 일광 절약 시간제가 끝나는 날의 5:MM UTC 형식의 시간입니다. 지역 벽시계는 1:59(일광 절약 시간)에서 다시 1:00(표준 시간)으로 도약합니다. 1:MM 형식의 지역 시간은 모호합니다. astimezone()은 두 개의 인접한 UTC 시(hour)를 같은 지역 시(hour)로 매핑하여 지역 시계 동작을 모방합니다. Eastern 예제에서, 5:MM과 6:MM 형식의 UTC 시간은 모두 Eastern으로 변환될 때 1:MM으로 매핑되지만, 이전 시간은 fold 어트리뷰트가 0으로 설정되고 이후 시간은 1로 설정됩니다. 예를 들어, 2016년 가을의 역 전환( back transition)에서, 다음과 같은 결과를 얻습니다

>>> u0 = datetime(2016, 11, 6, 4, tzinfo=timezone.utc)
>>> for i in range(4):
...     u = u0 + i*HOUR
...     t = u.astimezone(Eastern)
...     print(u.time(), 'UTC =', t.time(), t.tzname(), t.fold)
...
04:00:00 UTC = 00:00:00 EDT 0
05:00:00 UTC = 01:00:00 EDT 0
06:00:00 UTC = 01:00:00 EST 1
07:00:00 UTC = 02:00:00 EST 0

fold 어트리뷰트의 값만 다른 datetime 인스턴스는 비교에서 같다고 간주하는 것에 유의하십시오.

벽 시간 모호성을 견딜 수 없는 응용 프로그램은 명시적으로 fold 어트리뷰트 값을 확인하거나 하이브리드 tzinfo 서브 클래스를 사용하지 않아야 합니다; timezone이나 기타 고정 오프셋 tzinfo 서브 클래스(가령 오직 EST(고정 오프셋 -5시간)와 EDT(고정 오프셋 -4시간) 중 어느 한 가지만 나타내는 클래스)를 사용할 때는 모호함이 없습니다.

더 보기

dateutil.tz [https://dateutil.readthedocs.io/en/stable/tz.html]

표준 라이브러리에는 UTC로부터의 임의의 고정 오프셋을 처리하기 위한 timezone 클래스와 UTC timezone 인스턴스로 timezone.utc가 있습니다.

dateutil.tz 라이브러리는 IANA 시간대 데이터베이스 (Olson 데이터베이스라고도 합니다)를 파이썬으로 가져옵니다. 사용을 권장합니다.

IANA timezone database [https://www.iana.org/time-zones]

시간대 데이터베이스 (종종 tz, tzdata 또는 zoneinfo라고 합니다)에는 전 세계 여러 지역에서 지역 시간의 히스토리를 표현하는 코드와 데이터가 포함되어 있습니다. 정치 단체가 변경 한 시간대 경계, UTC 오프셋 및 일광 절약 시간 규칙을 반영하기 위해 주기적으로 갱신됩니다.

timezone 객체

timezone 클래스는 tzinfo의 서브 클래스이며, 각 인스턴스는 UTC로부터의 고정 오프셋으로 정의된 시간대를 나타냅니다. 이 클래스의 객체는 일 년 중 어떤 날에는 다른 오프셋이 사용되거나 민간 시간이 역사적으로 변해온 지역의 시간대 정보를 나타내는데 사용할 수 없음에 유의하십시오.

class datetime.timezone(offset, name=None)

offset 인자는 지역 시간과 UTC 간의 차이를 나타내는 timedelta 객체로 지정해야 합니다. 엄격히(경계를 포함하지 않는) -timedelta(hours=24)와 timedelta(hours=24) 사이여야 합니다. 그렇지 않으면 ValueError가 발생합니다.

name 인자는 선택적입니다. 지정되면 datetime.tzname() 메서드가 반환하는 값으로 사용될 문자열이어야 합니다.

버전 3.2에 추가.

버전 3.7에서 변경: UTC 오프셋은 분 단위로 제한되지 않습니다.

timezone.utcoffset(dt)

timezone 인스턴스가 구축될 때 지정된 고정값을 반환합니다. dt 인자는 무시됩니다. 반환 값은 지역 시간과 UTC 간의 차이와 같은 timedelta 인스턴스입니다.

버전 3.7에서 변경: UTC 오프셋은 분 단위로 제한되지 않습니다.

timezone.tzname(dt)

timezone 인스턴스가 구축될 때 지정된 고정값을 반환합니다. name을 생성자에 제공하지 않았으면, tzname(dt)에 의해 반환되는 이름은 다음과 같이 offset 값으로부터 생성됩니다. offset이 timedelta(0)이면, 이름은 “UTC”이고, 그렇지 않으면 문자열 ‘UTC±HH:MM’입니다. 여기서 ±는 offset의 부호이고, HH와 MM은 각각 offset.hours와 offset.minutes의 두 자리 숫자입니다.

버전 3.6에서 변경: offset=timedelta(0)에서 생성된 이름은 이제 ‘UTC+00:00’이 아니라 단순한 ‘UTC’입니다.

timezone.dst(dt)

항상 None을 반환합니다.

timezone.fromutc(dt)

dt + offset을 반환합니다. dt 인자는 tzinfo가 self로 설정된 어웨어 datetime 인스턴스여야 합니다.

클래스 어트리뷰트:

timezone.utc

UTC 시간대, timezone(timedelta(0)).

strftime()과 strptime() 동작

date, datetime 및 time 객체는 모두 strftime(format) 메서드를 지원하여, 명시적 포맷 문자열로 제어된 시간을 나타내는 문자열을 만듭니다. 대체로 말하자면, 모든 객체가 timetuple() 메서드를 지원하는 것은 아니지만, d.strftime(fmt)는 time 모듈의 time.strftime(fmt, d.timetuple())처럼 작동합니다.

반대로, datetime.strptime() 클래스 메서드는 날짜와 시간을 나타내는 문자열과 해당 포맷 문자열로 datetime 객체를 만듭니다. datetime.strptime(date_string, format)은 format에 초 미만의 성분이나 시간대 오프셋 정보가 포함된 경우를 제외하고는 datetime(*(time.strptime(date_string, format)[0:6]))과 동등합니다. 이것들은 datetime.strptime에서는 지원되지만 time.strptime에서는 버려집니다.

time 객체의 경우, time 객체에 해당 값이 없으므로, 연(year), 월(month) 및 일(day)의 포맷 코드는 사용하지 않아야 합니다. 어쨌든 사용되면, 1900이 해당 연도로, 1이 해당 월과 일로 대체됩니다.

date 객체의 경우, date 객체에 해당 값이 없으므로, 시(hour), 분(minute), 초(second) 및 마이크로초(microsecond)의 포맷 코드는 사용하지 않아야 합니다. 어쨌든 사용되면, 0으로 대체됩니다.

datetime.strptime() 클래스 메서드의 경우, 기본값은 1900-01-01T00:00:00.000입니다: 포맷 문자열에 지정되지 않은 구성 요소는 기본값에서 가져옵니다. 2

파이썬이 플랫폼 C 라이브러리의 strftime() 함수를 호출하고, 플랫폼 변형이 일반적이기 때문에, 지원되는 전체 포맷 코드 집합은 플랫폼에 따라 다릅니다. 여러분의 플랫폼에서 지원되는 모든 포맷 코드를 보려면, strftime(3) 설명서를 참조하십시오.

같은 이유로, 현재 로케일의 문자 집합으로는 표현할 수 없는 유니코드 코드 포인트를 포함하는 포맷 문자열의 처리도 플랫폼에 따라 다릅니다. 일부 플랫폼에서는 이러한 코드 포인트가 그대로 출력에 보존되지만, 다른 곳에서는 strftime이 UnicodeError를 발생시키거나 대신 빈 문자열을 반환할 수 있습니다.

다음은 C 표준(1989 버전)이 요구하는 모든 포맷 코드 목록이며, 표준 C 구현이 있는 모든 플랫폼에서 작동합니다. C 표준의 1999 버전에는 추가 형식 코드가 추가되었음에 유의하십시오.

지시자

의미

예

노트

%a

요일을 로케일의 축약된 이름으로.

Sun, Mon, …, Sat (en_US);

So, Mo, …, Sa (de_DE)

(1)

%A

요일을 로케일의 전체 이름으로.

Sunday, Monday, …, Saturday (en_US);

Sonntag, Montag, …, Samstag (de_DE)

(1)

%w

요일을 10진수로, 0은 일요일이고 6은 토요일입니다.

0, 1, …, 6

%d

월중 일(day of the month)을 0으로 채워진 10진수로.

01, 02, …, 31

(9)

%b

월을 로케일의 축약된 이름으로.

Jan, Feb, …, Dec (en_US);

Jan, Feb, …, Dez (de_DE)

(1)

%B

월을 로케일의 전체 이름으로.

January, February, …, December (en_US);

Januar, Februar, …, Dezember (de_DE)

(1)

%m

월을 0으로 채워진 10진수로.

01, 02, …, 12

(9)

%y

세기가 없는 해(year)를 0으로 채워진 10진수로.

00, 01, …, 99

(9)

%Y

세기가 있는 해(year)를 10진수로.

0001, 0002, …, 2013, 2014, …, 9998, 9999

(2)

%H

시(24시간제)를 0으로 채워진 십진수로.

00, 01, …, 23

(9)

%I

시(12시간제)를 0으로 채워진 십진수로.

01, 02, …, 12

(9)

%p

로케일의 오전이나 오후에 해당하는 것.

AM, PM (en_US);

am, pm (de_DE)

(1), (3)

%M

분을 0으로 채워진 십진수로.

00, 01, …, 59

(9)

%S

초를 0으로 채워진 10진수로.

00, 01, …, 59

(4), (9)

%f

마이크로초를 왼쪽에 0으로 채워진 십진수로.

000000, 000001, …, 999999

(5)

%z

±HHMM[SS[.ffffff]] 형태의 UTC 오프셋 (객체가 나이브하면 빈 문자열).

(비어 있음), +0000, -0400, +1030, +063415, -030712.345216

(6)

%Z

시간대 이름 (객체가 나이브하면 빈 문자열).

(비어 있음), UTC, EST, CST

%j

연중 일(day of the year)을 0으로 채워진 십진수로.

001, 002, …, 366

(9)

%U

연중 주 번호(일요일이 주의 시작)를 0으로 채워진 10진수로. 첫 번째 일요일에 선행하는 새해의 모든 날은 주 0으로 간주합니다.

00, 01, …, 53

(7), (9)

%W

연중 주 번호(월요일이 주의 시작)를 십진수로. 첫 번째 월요일에 선행하는 새해의 모든 말은 주 0으로 간주합니다.

00, 01, …, 53

(7), (9)

%c

로케일의 적절한 날짜와 시간 표현.

Tue Aug 16 21:30:00 1988 (en_US);

Di 16 Aug 21:30:00 1988 (de_DE)

(1)

%x

로케일의 적절한 날짜 표현.

08/16/88 (None);

08/16/1988 (en_US);

16.08.1988 (de_DE)

(1)

%X

로케일의 적절한 시간 표현.

21:30:00 (en_US);

21:30:00 (de_DE)

(1)

%%

리터럴 '%' 문자.

%

C89 표준에서 요구하지 않는 몇 가지 추가 지시자가 편의상 포함되어 있습니다. 이 파라미터들은 모두 ISO 8601 날짜 값에 해당합니다. strftime() 메서드와 함께 사용될 때 모든 플랫폼에서 사용할 수 있는 것은 아닙니다. ISO 8601 연도와 ISO 8601 주 지시자는 위의 연도 및 주 번호 지시자와 교환할 수 없습니다. 불완전하거나 모호한 ISO 8601 지시자로 strptime()을 호출하면 ValueError가 발생합니다.

지시자

의미

예

노트

%G

ISO 주(%V)의 더 큰 부분을 포함하는 연도를 나타내는 세기가 있는 ISO 8601 연도.

0001, 0002, …, 2013, 2014, …, 9998, 9999

(8)

%u

ISO 8601 요일을 10진수로, 1은 월요일입니다.

1, 2, …, 7

%V

ISO 8601 주를 월요일을 주의 시작으로 하는 십진수로. 주 01은 1월 4일을 포함하는 주입니다.

01, 02, …, 53

(8), (9)

버전 3.6에 추가: %G, %u 및 %V가 추가되었습니다.

노트:

포맷이 현재 로케일에 따라 다르므로, 출력값에 대해 가정을 할 때 주의해야 합니다. 필드 순서가 달라지며 (예를 들어, “월/일/년” 과 “일/월/년”), 출력에는 로케일의 기본 인코딩을 사용하여 인코딩된 유니코드 문자가 포함될 수 있습니다 (예를 들어, 현재 로케일이 ja_JP이면, 기본 인코딩은 eucJP, SJIS 또는 utf-8 중 하나일 수 있습니다; 현재 로케일의 인코딩을 결정하려면 locale.getlocale()을 사용하십시오).

strptime() 메서드는 전체 [1, 9999] 범위에서 연도를 구문 분석할 수 있지만, 1000보다 작은 연도는 4자리 너비가 되도록 0으로 채워야 합니다.

버전 3.2에서 변경: 이전 버전에서 strftime() 메서드는 1900년 이상으로 제한되었습니다.

버전 3.3에서 변경: 버전 3.2에서, strftime() 메서드는 연도를 1000 이상으로 제한했습니다.

strptime() 메서드와 함께 사용할 때, %p 지시자는 시간을 구문 분석하는 데 %I 지시문을 사용할 때만 출력 시간 필드에 영향을 줍니다.

time 모듈과 달리, datetime 모듈은 윤초를 지원하지 않습니다.

strptime() 메서드와 함께 사용할 때, %f 지시자는 하나에서 여섯 자리 숫자와 오른쪽의 0-채움을 받아들입니다. %f는 C 표준의 포맷 문자 집합에 대한 확장입니다 (하지만 datetime 객체에서 별도로 구현되므로 항상 사용할 수 있습니다).

나이브 객체의 경우, %z 와 %Z 포맷 코드는 빈 문자열로 치환됩니다.

어웨어 객체의 경우:

%z

utcoffset()이 ±HHMM[SS[.ffffff]] 형식의 문자열로 변환됩니다. 여기서 HH는 UTC 오프셋 시간(hour)의 수를 나타내는 두 자리 숫자 문자열이고, MM은 UTC 오프셋 분의 수를 나타내는 두 자리 숫자 문자열이며, SS는 UTC 오프셋 초의 수를 나타내는 두 자리 숫자 문자열이며, ffffff는 UTC 오프셋 마이크로초의 수를 나타내는 6자리 숫자 문자열입니다. 오프셋이 딱 떨어지는 초면 ffffff 부분은 생략되며, offset이 딱 떨어지는 분이면 ffffff와 SS 부분이 모두 생략됩니다. 예를 들어, utcoffset()이 timedelta(hours=-3, minutes=-30)를 반환하면, %z는 '-0330' 문자열로 치환됩니다.

버전 3.7에서 변경: UTC 오프셋은 분 단위로 제한되지 않습니다.

버전 3.7에서 변경: %z 지시자가 strptime() 메서드에 제공될 때, UTC 오프셋에는 콜론이 시, 분 및 초 사이의 구분 기호로 사용될 수 있습니다. 예를 들어, '+01:00:00'은 1시간의 오프셋으로 구문 분석됩니다. 또한, 'Z'를 제공하는 것은 '+00:00'과 같습니다.

%Z

tzname()이 None을 반환하면, %Z는 빈 문자열로 치환됩니다. 그렇지 않으면 %Z는 문자열이어야 하는 반환 값으로 치환됩니다.

버전 3.2에서 변경: %z 지시자가 strptime() 메서드에 제공될 때, 어웨어 datetime 객체가 생성됩니다. 결과의 tzinfo는 timezone 인스턴스로 설정됩니다.

strptime() 메서드와 함께 사용될 때, %U 와 %W는 요일과 달력 연도(%Y)가 지정되었을 때만 계산에 사용됩니다.

%U 와 %W와 비슷하게, %V는 요일과 ISO 연도(%G)가 strptime() 포맷 문자열에 지정되었을 때만 계산에 사용됩니다. 또한 %G와 %Y를 상호 교환할 수 없음에 유의하십시오.

strptime() 메서드와 함께 사용할 때, 선행 0은 %d, %m, %H, %I, %M, %S, %J, %U, %W 및 %V 포맷에서 선택적입니다. 포맷 %y에는 선행 0이 필요합니다.

각주

1

즉, 상대론적 효과를 무시한다면

2

1900이 윤년이 아니므로 datetime.strptime('Feb 29', '%b %d')를 전달하는 것은 실패합니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

데이터형 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

데이터형 »

|

calendar — General calendar-related functions

Source code: Lib/calendar.py [https://github.com/python/cpython/tree/3.7/Lib/calendar.py]

This module allows you to output calendars like the Unix cal program, and provides additional useful functions related to the calendar. By default, these calendars have Monday as the first day of the week, and Sunday as the last (the European convention). Use setfirstweekday() to set the first day of the week to Sunday (6) or to any other weekday. Parameters that specify dates are given as integers. For related functionality, see also the datetime and time modules.

The functions and classes defined in this module use an idealized calendar, the current Gregorian calendar extended indefinitely in both directions. This matches the definition of the “proleptic Gregorian” calendar in Dershowitz and Reingold’s book “Calendrical Calculations”, where it’s the base calendar for all computations. Zero and negative years are interpreted as prescribed by the ISO 8601 standard. Year 0 is 1 BC, year -1 is 2 BC, and so on.

class calendar.Calendar(firstweekday=0)

Creates a Calendar object. firstweekday is an integer specifying the first day of the week. 0 is Monday (the default), 6 is Sunday.

A Calendar object provides several methods that can be used for preparing the calendar data for formatting. This class doesn’t do any formatting itself. This is the job of subclasses.

Calendar instances have the following methods:

iterweekdays()

Return an iterator for the week day numbers that will be used for one week. The first value from the iterator will be the same as the value of the firstweekday property.

itermonthdates(year, month)

Return an iterator for the month month (1–12) in the year year. This iterator will return all days (as datetime.date objects) for the month and all days before the start of the month or after the end of the month that are required to get a complete week.

itermonthdays(year, month)

Return an iterator for the month month in the year year similar to itermonthdates(), but not restricted by the datetime.date range. Days returned will simply be day of the month numbers. For the days outside of the specified month, the day number is 0.

itermonthdays2(year, month)

Return an iterator for the month month in the year year similar to itermonthdates(), but not restricted by the datetime.date range. Days returned will be tuples consisting of a day of the month number and a week day number.

itermonthdays3(year, month)

Return an iterator for the month month in the year year similar to itermonthdates(), but not restricted by the datetime.date range. Days returned will be tuples consisting of a year, a month and a day of the month numbers.

버전 3.7에 추가.

itermonthdays4(year, month)

Return an iterator for the month month in the year year similar to itermonthdates(), but not restricted by the datetime.date range. Days returned will be tuples consisting of a year, a month, a day of the month, and a day of the week numbers.

버전 3.7에 추가.

monthdatescalendar(year, month)

Return a list of the weeks in the month month of the year as full weeks. Weeks are lists of seven datetime.date objects.

monthdays2calendar(year, month)

Return a list of the weeks in the month month of the year as full weeks. Weeks are lists of seven tuples of day numbers and weekday numbers.

monthdayscalendar(year, month)

Return a list of the weeks in the month month of the year as full weeks. Weeks are lists of seven day numbers.

yeardatescalendar(year, width=3)

Return the data for the specified year ready for formatting. The return value is a list of month rows. Each month row contains up to width months (defaulting to 3). Each month contains between 4 and 6 weeks and each week contains 1–7 days. Days are datetime.date objects.

yeardays2calendar(year, width=3)

Return the data for the specified year ready for formatting (similar to yeardatescalendar()). Entries in the week lists are tuples of day numbers and weekday numbers. Day numbers outside this month are zero.

yeardayscalendar(year, width=3)

Return the data for the specified year ready for formatting (similar to yeardatescalendar()). Entries in the week lists are day numbers. Day numbers outside this month are zero.

class calendar.TextCalendar(firstweekday=0)

This class can be used to generate plain text calendars.

TextCalendar instances have the following methods:

formatmonth(theyear, themonth, w=0, l=0)

Return a month’s calendar in a multi-line string. If w is provided, it specifies the width of the date columns, which are centered. If l is given, it specifies the number of lines that each week will use. Depends on the first weekday as specified in the constructor or set by the setfirstweekday() method.

prmonth(theyear, themonth, w=0, l=0)

Print a month’s calendar as returned by formatmonth().

formatyear(theyear, w=2, l=1, c=6, m=3)

Return a m-column calendar for an entire year as a multi-line string. Optional parameters w, l, and c are for date column width, lines per week, and number of spaces between month columns, respectively. Depends on the first weekday as specified in the constructor or set by the setfirstweekday() method. The earliest year for which a calendar can be generated is platform-dependent.

pryear(theyear, w=2, l=1, c=6, m=3)

Print the calendar for an entire year as returned by formatyear().

class calendar.HTMLCalendar(firstweekday=0)

This class can be used to generate HTML calendars.

HTMLCalendar instances have the following methods:

formatmonth(theyear, themonth, withyear=True)

Return a month’s calendar as an HTML table. If withyear is true the year will be included in the header, otherwise just the month name will be used.

formatyear(theyear, width=3)

Return a year’s calendar as an HTML table. width (defaulting to 3) specifies the number of months per row.

formatyearpage(theyear, width=3, css='calendar.css', encoding=None)

Return a year’s calendar as a complete HTML page. width (defaulting to 3) specifies the number of months per row. css is the name for the cascading style sheet to be used. None can be passed if no style sheet should be used. encoding specifies the encoding to be used for the output (defaulting to the system default encoding).

HTMLCalendar has the following attributes you can override to customize the CSS classes used by the calendar:

cssclasses

A list of CSS classes used for each weekday. The default class list is:

cssclasses = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"]

more styles can be added for each day:

cssclasses = ["mon text-bold", "tue", "wed", "thu", "fri", "sat", "sun red"]

Note that the length of this list must be seven items.

cssclass_noday

The CSS class for a weekday occurring in the previous or coming month.

버전 3.7에 추가.

cssclasses_weekday_head

A list of CSS classes used for weekday names in the header row. The default is the same as cssclasses.

버전 3.7에 추가.

cssclass_month_head

The month’s head CSS class (used by formatmonthname()). The default value is "month".

버전 3.7에 추가.

cssclass_month

The CSS class for the whole month’s table (used by formatmonth()). The default value is "month".

버전 3.7에 추가.

cssclass_year

The CSS class for the whole year’s table of tables (used by formatyear()). The default value is "year".

버전 3.7에 추가.

cssclass_year_head

The CSS class for the table head for the whole year (used by formatyear()). The default value is "year".

버전 3.7에 추가.

Note that although the naming for the above described class attributes is singular (e.g. cssclass_month cssclass_noday), one can replace the single CSS class with a space separated list of CSS classes, for example:

"text-bold text-red"

Here is an example how HTMLCalendar can be customized:

class CustomHTMLCal(calendar.HTMLCalendar):
    cssclasses = [style + " text-nowrap" for style in
                  calendar.HTMLCalendar.cssclasses]
    cssclass_month_head = "text-center month-head"
    cssclass_month = "text-center month"
    cssclass_year = "text-italic lead"

class calendar.LocaleTextCalendar(firstweekday=0, locale=None)

This subclass of TextCalendar can be passed a locale name in the constructor and will return month and weekday names in the specified locale. If this locale includes an encoding all strings containing month and weekday names will be returned as unicode.

class calendar.LocaleHTMLCalendar(firstweekday=0, locale=None)

This subclass of HTMLCalendar can be passed a locale name in the constructor and will return month and weekday names in the specified locale. If this locale includes an encoding all strings containing month and weekday names will be returned as unicode.

참고

The formatweekday() and formatmonthname() methods of these two classes temporarily change the current locale to the given locale. Because the current locale is a process-wide setting, they are not thread-safe.

For simple text calendars this module provides the following functions.

calendar.setfirstweekday(weekday)

Sets the weekday (0 is Monday, 6 is Sunday) to start each week. The values MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, and SUNDAY are provided for convenience. For example, to set the first weekday to Sunday:

import calendar
calendar.setfirstweekday(calendar.SUNDAY)

calendar.firstweekday()

Returns the current setting for the weekday to start each week.

calendar.isleap(year)

Returns True if year is a leap year, otherwise False.

calendar.leapdays(y1, y2)

Returns the number of leap years in the range from y1 to y2 (exclusive), where y1 and y2 are years.

This function works for ranges spanning a century change.

calendar.weekday(year, month, day)

Returns the day of the week (0 is Monday) for year (1970–…), month (1–12), day (1–31).

calendar.weekheader(n)

Return a header containing abbreviated weekday names. n specifies the width in characters for one weekday.

calendar.monthrange(year, month)

Returns weekday of first day of the month and number of days in month, for the specified year and month.

calendar.monthcalendar(year, month)

Returns a matrix representing a month’s calendar. Each row represents a week; days outside of the month a represented by zeros. Each week begins with Monday unless set by setfirstweekday().

calendar.prmonth(theyear, themonth, w=0, l=0)

Prints a month’s calendar as returned by month().

calendar.month(theyear, themonth, w=0, l=0)

Returns a month’s calendar in a multi-line string using the formatmonth() of the TextCalendar class.

calendar.prcal(year, w=0, l=0, c=6, m=3)

Prints the calendar for an entire year as returned by calendar().

calendar.calendar(year, w=2, l=1, c=6, m=3)

Returns a 3-column calendar for an entire year as a multi-line string using the formatyear() of the TextCalendar class.

calendar.timegm(tuple)

An unrelated but handy function that takes a time tuple such as returned by the gmtime() function in the time module, and returns the corresponding Unix timestamp value, assuming an epoch of 1970, and the POSIX encoding. In fact, time.gmtime() and timegm() are each others’ inverse.

The calendar module exports the following data attributes:

calendar.day_name

An array that represents the days of the week in the current locale.

calendar.day_abbr

An array that represents the abbreviated days of the week in the current locale.

calendar.month_name

An array that represents the months of the year in the current locale. This follows normal convention of January being month number 1, so it has a length of 13 and month_name[0] is the empty string.

calendar.month_abbr

An array that represents the abbreviated months of the year in the current locale. This follows normal convention of January being month number 1, so it has a length of 13 and month_abbr[0] is the empty string.

더 보기

Module datetime

Object-oriented interface to dates and times with similar functionality to the time module.

Module time

Low-level time related functions.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

데이터형 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

데이터형 »

|

collections — Container datatypes

Source code: Lib/collections/__init__.py [https://github.com/python/cpython/tree/3.7/Lib/collections/__init__.py]

This module implements specialized container datatypes providing alternatives to Python’s general purpose built-in containers, dict, list, set, and tuple.

namedtuple()

factory function for creating tuple subclasses with named fields

deque

list-like container with fast appends and pops on either end

ChainMap

dict-like class for creating a single view of multiple mappings

Counter

dict subclass for counting hashable objects

OrderedDict

dict subclass that remembers the order entries were added

defaultdict

dict subclass that calls a factory function to supply missing values

UserDict

wrapper around dictionary objects for easier dict subclassing

UserList

wrapper around list objects for easier list subclassing

UserString

wrapper around string objects for easier string subclassing

Deprecated since version 3.3, will be removed in version 3.9: Moved Collections 추상 베이스 클래스 to the collections.abc module. For backwards compatibility, they continue to be visible in this module through Python 3.8.

ChainMap objects

버전 3.3에 추가.

A ChainMap class is provided for quickly linking a number of mappings so they can be treated as a single unit. It is often much faster than creating a new dictionary and running multiple update() calls.

The class can be used to simulate nested scopes and is useful in templating.

class collections.ChainMap(*maps)

A ChainMap groups multiple dicts or other mappings together to create a single, updateable view. If no maps are specified, a single empty dictionary is provided so that a new chain always has at least one mapping.

The underlying mappings are stored in a list. That list is public and can be accessed or updated using the maps attribute. There is no other state.

Lookups search the underlying mappings successively until a key is found. In contrast, writes, updates, and deletions only operate on the first mapping.

A ChainMap incorporates the underlying mappings by reference. So, if one of the underlying mappings gets updated, those changes will be reflected in ChainMap.

All of the usual dictionary methods are supported. In addition, there is a maps attribute, a method for creating new subcontexts, and a property for accessing all but the first mapping:

maps

A user updateable list of mappings. The list is ordered from first-searched to last-searched. It is the only stored state and can be modified to change which mappings are searched. The list should always contain at least one mapping.

new_child(m=None)

Returns a new ChainMap containing a new map followed by all of the maps in the current instance. If m is specified, it becomes the new map at the front of the list of mappings; if not specified, an empty dict is used, so that a call to d.new_child() is equivalent to: ChainMap({}, *d.maps). This method is used for creating subcontexts that can be updated without altering values in any of the parent mappings.

버전 3.4에서 변경: The optional m parameter was added.

parents

Property returning a new ChainMap containing all of the maps in the current instance except the first one. This is useful for skipping the first map in the search. Use cases are similar to those for the nonlocal keyword used in nested scopes. The use cases also parallel those for the built-in super() function. A reference to d.parents is equivalent to: ChainMap(*d.maps[1:]).

Note, the iteration order of a ChainMap() is determined by scanning the mappings last to first:

>>> baseline = {'music': 'bach', 'art': 'rembrandt'}
>>> adjustments = {'art': 'van gogh', 'opera': 'carmen'}
>>> list(ChainMap(adjustments, baseline))
['music', 'art', 'opera']

This gives the same ordering as a series of dict.update() calls starting with the last mapping:

>>> combined = baseline.copy()
>>> combined.update(adjustments)
>>> list(combined)
['music', 'art', 'opera']

더 보기

The MultiContext class [https://github.com/enthought/codetools/blob/4.0.0/codetools/contexts/multi_context.py] in the Enthought CodeTools package [https://github.com/enthought/codetools] has options to support writing to any mapping in the chain.

Django’s Context class [https://github.com/django/django/blob/master/django/template/context.py] for templating is a read-only chain of mappings. It also features pushing and popping of contexts similar to the new_child() method and the parents property.

The Nested Contexts recipe [https://code.activestate.com/recipes/577434/] has options to control whether writes and other mutations apply only to the first mapping or to any mapping in the chain.

A greatly simplified read-only version of Chainmap [https://code.activestate.com/recipes/305268/].

ChainMap Examples and Recipes

This section shows various approaches to working with chained maps.

Example of simulating Python’s internal lookup chain:

import builtins
pylookup = ChainMap(locals(), globals(), vars(builtins))

Example of letting user specified command-line arguments take precedence over environment variables which in turn take precedence over default values:

import os, argparse

defaults = {'color': 'red', 'user': 'guest'}

parser = argparse.ArgumentParser()
parser.add_argument('-u', '--user')
parser.add_argument('-c', '--color')
namespace = parser.parse_args()
command_line_args = {k: v for k, v in vars(namespace).items() if v is not None}

combined = ChainMap(command_line_args, os.environ, defaults)
print(combined['color'])
print(combined['user'])

Example patterns for using the ChainMap class to simulate nested contexts:

c = ChainMap()        # Create root context
d = c.new_child()     # Create nested child context
e = c.new_child()     # Child of c, independent from d
e.maps[0]             # Current context dictionary -- like Python's locals()
e.maps[-1]            # Root context -- like Python's globals()
e.parents             # Enclosing context chain -- like Python's nonlocals

d['x'] = 1            # Set value in current context
d['x']                # Get first key in the chain of contexts
del d['x']            # Delete from current context
list(d)               # All nested values
k in d                # Check all nested values
len(d)                # Number of nested values
d.items()             # All nested items
dict(d)               # Flatten into a regular dictionary

The ChainMap class only makes updates (writes and deletions) to the first mapping in the chain while lookups will search the full chain. However, if deep writes and deletions are desired, it is easy to make a subclass that updates keys found deeper in the chain:

class DeepChainMap(ChainMap):
    'Variant of ChainMap that allows direct updates to inner scopes'

    def __setitem__(self, key, value):
        for mapping in self.maps:
            if key in mapping:
                mapping[key] = value
                return
        self.maps[0][key] = value

    def __delitem__(self, key):
        for mapping in self.maps:
            if key in mapping:
                del mapping[key]
                return
        raise KeyError(key)

>>> d = DeepChainMap({'zebra': 'black'}, {'elephant': 'blue'}, {'lion': 'yellow'})
>>> d['lion'] = 'orange'         # update an existing key two levels down
>>> d['snake'] = 'red'           # new keys get added to the topmost dict
>>> del d['elephant']            # remove an existing key one level down
>>> d                            # display result
DeepChainMap({'zebra': 'black', 'snake': 'red'}, {}, {'lion': 'orange'})

Counter objects

A counter tool is provided to support convenient and rapid tallies. For example:

>>> # Tally occurrences of words in a list
>>> cnt = Counter()
>>> for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']:
...     cnt[word] += 1
>>> cnt
Counter({'blue': 3, 'red': 2, 'green': 1})

>>> # Find the ten most common words in Hamlet
>>> import re
>>> words = re.findall(r'\w+', open('hamlet.txt').read().lower())
>>> Counter(words).most_common(10)
[('the', 1143), ('and', 966), ('to', 762), ('of', 669), ('i', 631),
 ('you', 554),  ('a', 546), ('my', 514), ('hamlet', 471), ('in', 451)]

class collections.Counter([iterable-or-mapping])

A Counter is a dict subclass for counting hashable objects. It is a collection where elements are stored as dictionary keys and their counts are stored as dictionary values. Counts are allowed to be any integer value including zero or negative counts. The Counter class is similar to bags or multisets in other languages.

Elements are counted from an iterable or initialized from another mapping (or counter):

>>> c = Counter()                           # a new, empty counter
>>> c = Counter('gallahad')                 # a new counter from an iterable
>>> c = Counter({'red': 4, 'blue': 2})      # a new counter from a mapping
>>> c = Counter(cats=4, dogs=8)             # a new counter from keyword args

Counter objects have a dictionary interface except that they return a zero count for missing items instead of raising a KeyError:

>>> c = Counter(['eggs', 'ham'])
>>> c['bacon']                              # count of a missing element is zero
0

Setting a count to zero does not remove an element from a counter. Use del to remove it entirely:

>>> c['sausage'] = 0                        # counter entry with a zero count
>>> del c['sausage']                        # del actually removes the entry

버전 3.1에 추가.

Counter objects support three methods beyond those available for all dictionaries:

elements()

Return an iterator over elements repeating each as many times as its count. Elements are returned in arbitrary order. If an element’s count is less than one, elements() will ignore it.

>>> c = Counter(a=4, b=2, c=0, d=-2)
>>> sorted(c.elements())
['a', 'a', 'a', 'a', 'b', 'b']

most_common([n])

Return a list of the n most common elements and their counts from the most common to the least. If n is omitted or None, most_common() returns all elements in the counter. Elements with equal counts are ordered arbitrarily:

>>> Counter('abracadabra').most_common(3)
[('a', 5), ('r', 2), ('b', 2)]

subtract([iterable-or-mapping])

Elements are subtracted from an iterable or from another mapping (or counter). Like dict.update() but subtracts counts instead of replacing them. Both inputs and outputs may be zero or negative.

>>> c = Counter(a=4, b=2, c=0, d=-2)
>>> d = Counter(a=1, b=2, c=3, d=4)
>>> c.subtract(d)
>>> c
Counter({'a': 3, 'b': 0, 'c': -3, 'd': -6})

버전 3.2에 추가.

The usual dictionary methods are available for Counter objects except for two which work differently for counters.

fromkeys(iterable)

This class method is not implemented for Counter objects.

update([iterable-or-mapping])

Elements are counted from an iterable or added-in from another mapping (or counter). Like dict.update() but adds counts instead of replacing them. Also, the iterable is expected to be a sequence of elements, not a sequence of (key, value) pairs.

Common patterns for working with Counter objects:

sum(c.values())                 # total of all counts
c.clear()                       # reset all counts
list(c)                         # list unique elements
set(c)                          # convert to a set
dict(c)                         # convert to a regular dictionary
c.items()                       # convert to a list of (elem, cnt) pairs
Counter(dict(list_of_pairs))    # convert from a list of (elem, cnt) pairs
c.most_common()[:-n-1:-1]       # n least common elements
+c                              # remove zero and negative counts

Several mathematical operations are provided for combining Counter objects to produce multisets (counters that have counts greater than zero). Addition and subtraction combine counters by adding or subtracting the counts of corresponding elements. Intersection and union return the minimum and maximum of corresponding counts. Each operation can accept inputs with signed counts, but the output will exclude results with counts of zero or less.

>>> c = Counter(a=3, b=1)
>>> d = Counter(a=1, b=2)
>>> c + d                       # add two counters together:  c[x] + d[x]
Counter({'a': 4, 'b': 3})
>>> c - d                       # subtract (keeping only positive counts)
Counter({'a': 2})
>>> c & d                       # intersection:  min(c[x], d[x])
Counter({'a': 1, 'b': 1})
>>> c | d                       # union:  max(c[x], d[x])
Counter({'a': 3, 'b': 2})

Unary addition and subtraction are shortcuts for adding an empty counter or subtracting from an empty counter.

>>> c = Counter(a=2, b=-4)
>>> +c
Counter({'a': 2})
>>> -c
Counter({'b': 4})

버전 3.3에 추가: Added support for unary plus, unary minus, and in-place multiset operations.

참고

Counters were primarily designed to work with positive integers to represent running counts; however, care was taken to not unnecessarily preclude use cases needing other types or negative values. To help with those use cases, this section documents the minimum range and type restrictions.

The Counter class itself is a dictionary subclass with no restrictions on its keys and values. The values are intended to be numbers representing counts, but you could store anything in the value field.

The most_common() method requires only that the values be orderable.

For in-place operations such as c[key] += 1, the value type need only support addition and subtraction. So fractions, floats, and decimals would work and negative values are supported. The same is also true for update() and subtract() which allow negative and zero values for both inputs and outputs.

The multiset methods are designed only for use cases with positive values. The inputs may be negative or zero, but only outputs with positive values are created. There are no type restrictions, but the value type needs to support addition, subtraction, and comparison.

The elements() method requires integer counts. It ignores zero and negative counts.

더 보기

Bag class [https://www.gnu.org/software/smalltalk/manual-base/html_node/Bag.html] in Smalltalk.

Wikipedia entry for Multisets [https://en.wikipedia.org/wiki/Multiset].

C++ multisets [http://www.java2s.com/Tutorial/Cpp/0380__set-multiset/Catalog0380__set-multiset.htm] tutorial with examples.

For mathematical operations on multisets and their use cases, see Knuth, Donald. The Art of Computer Programming Volume II, Section 4.6.3, Exercise 19.

To enumerate all distinct multisets of a given size over a given set of elements, see itertools.combinations_with_replacement():

map(Counter, combinations_with_replacement('ABC', 2)) # --> AA AB AC BB BC CC

deque objects

class collections.deque([iterable[, maxlen]])

Returns a new deque object initialized left-to-right (using append()) with data from iterable. If iterable is not specified, the new deque is empty.

Deques are a generalization of stacks and queues (the name is pronounced “deck” and is short for “double-ended queue”). Deques support thread-safe, memory efficient appends and pops from either side of the deque with approximately the same O(1) performance in either direction.

Though list objects support similar operations, they are optimized for fast fixed-length operations and incur O(n) memory movement costs for pop(0) and insert(0, v) operations which change both the size and position of the underlying data representation.

If maxlen is not specified or is None, deques may grow to an arbitrary length. Otherwise, the deque is bounded to the specified maximum length. Once a bounded length deque is full, when new items are added, a corresponding number of items are discarded from the opposite end. Bounded length deques provide functionality similar to the tail filter in Unix. They are also useful for tracking transactions and other pools of data where only the most recent activity is of interest.

Deque objects support the following methods:

append(x)

Add x to the right side of the deque.

appendleft(x)

Add x to the left side of the deque.

clear()

Remove all elements from the deque leaving it with length 0.

copy()

Create a shallow copy of the deque.

버전 3.5에 추가.

count(x)

Count the number of deque elements equal to x.

버전 3.2에 추가.

extend(iterable)

Extend the right side of the deque by appending elements from the iterable argument.

extendleft(iterable)

Extend the left side of the deque by appending elements from iterable. Note, the series of left appends results in reversing the order of elements in the iterable argument.

index(x[, start[, stop]])

Return the position of x in the deque (at or after index start and before index stop). Returns the first match or raises ValueError if not found.

버전 3.5에 추가.

insert(i, x)

Insert x into the deque at position i.

If the insertion would cause a bounded deque to grow beyond maxlen, an IndexError is raised.

버전 3.5에 추가.

pop()

Remove and return an element from the right side of the deque. If no elements are present, raises an IndexError.

popleft()

Remove and return an element from the left side of the deque. If no elements are present, raises an IndexError.

remove(value)

Remove the first occurrence of value. If not found, raises a ValueError.

reverse()

Reverse the elements of the deque in-place and then return None.

버전 3.2에 추가.

rotate(n=1)

Rotate the deque n steps to the right. If n is negative, rotate to the left.

When the deque is not empty, rotating one step to the right is equivalent to d.appendleft(d.pop()), and rotating one step to the left is equivalent to d.append(d.popleft()).

Deque objects also provide one read-only attribute:

maxlen

Maximum size of a deque or None if unbounded.

버전 3.1에 추가.

In addition to the above, deques support iteration, pickling, len(d), reversed(d), copy.copy(d), copy.deepcopy(d), membership testing with the in operator, and subscript references such as d[-1]. Indexed access is O(1) at both ends but slows to O(n) in the middle. For fast random access, use lists instead.

Starting in version 3.5, deques support __add__(), __mul__(), and __imul__().

Example:

>>> from collections import deque
>>> d = deque('ghi')                 # make a new deque with three items
>>> for elem in d:                   # iterate over the deque's elements
...     print(elem.upper())
G
H
I

>>> d.append('j')                    # add a new entry to the right side
>>> d.appendleft('f')                # add a new entry to the left side
>>> d                                # show the representation of the deque
deque(['f', 'g', 'h', 'i', 'j'])

>>> d.pop()                          # return and remove the rightmost item
'j'
>>> d.popleft()                      # return and remove the leftmost item
'f'
>>> list(d)                          # list the contents of the deque
['g', 'h', 'i']
>>> d[0]                             # peek at leftmost item
'g'
>>> d[-1]                            # peek at rightmost item
'i'

>>> list(reversed(d))                # list the contents of a deque in reverse
['i', 'h', 'g']
>>> 'h' in d                         # search the deque
True
>>> d.extend('jkl')                  # add multiple elements at once
>>> d
deque(['g', 'h', 'i', 'j', 'k', 'l'])
>>> d.rotate(1)                      # right rotation
>>> d
deque(['l', 'g', 'h', 'i', 'j', 'k'])
>>> d.rotate(-1)                     # left rotation
>>> d
deque(['g', 'h', 'i', 'j', 'k', 'l'])

>>> deque(reversed(d))               # make a new deque in reverse order
deque(['l', 'k', 'j', 'i', 'h', 'g'])
>>> d.clear()                        # empty the deque
>>> d.pop()                          # cannot pop from an empty deque
Traceback (most recent call last):
    File "<pyshell#6>", line 1, in -toplevel-
        d.pop()
IndexError: pop from an empty deque

>>> d.extendleft('abc')              # extendleft() reverses the input order
>>> d
deque(['c', 'b', 'a'])

deque Recipes

This section shows various approaches to working with deques.

Bounded length deques provide functionality similar to the tail filter in Unix:

def tail(filename, n=10):
    'Return the last n lines of a file'
    with open(filename) as f:
        return deque(f, n)

Another approach to using deques is to maintain a sequence of recently added elements by appending to the right and popping to the left:

def moving_average(iterable, n=3):
    # moving_average([40, 30, 50, 46, 39, 44]) --> 40.0 42.0 45.0 43.0
    # http://en.wikipedia.org/wiki/Moving_average
    it = iter(iterable)
    d = deque(itertools.islice(it, n-1))
    d.appendleft(0)
    s = sum(d)
    for elem in it:
        s += elem - d.popleft()
        d.append(elem)
        yield s / n

A round-robin scheduler [https://en.wikipedia.org/wiki/Round-robin_scheduling] can be implemented with input iterators stored in a deque. Values are yielded from the active iterator in position zero. If that iterator is exhausted, it can be removed with popleft(); otherwise, it can be cycled back to the end with the rotate() method:

def roundrobin(*iterables):
    "roundrobin('ABC', 'D', 'EF') --> A D E B F C"
    iterators = deque(map(iter, iterables))
    while iterators:
        try:
            while True:
                yield next(iterators[0])
                iterators.rotate(-1)
        except StopIteration:
            # Remove an exhausted iterator.
            iterators.popleft()

The rotate() method provides a way to implement deque slicing and deletion. For example, a pure Python implementation of del d[n] relies on the rotate() method to position elements to be popped:

def delete_nth(d, n):
    d.rotate(-n)
    d.popleft()
    d.rotate(n)

To implement deque slicing, use a similar approach applying rotate() to bring a target element to the left side of the deque. Remove old entries with popleft(), add new entries with extend(), and then reverse the rotation. With minor variations on that approach, it is easy to implement Forth style stack manipulations such as dup, drop, swap, over, pick, rot, and roll.

defaultdict objects

class collections.defaultdict([default_factory[, ...]])

Returns a new dictionary-like object. defaultdict is a subclass of the built-in dict class. It overrides one method and adds one writable instance variable. The remaining functionality is the same as for the dict class and is not documented here.

The first argument provides the initial value for the default_factory attribute; it defaults to None. All remaining arguments are treated the same as if they were passed to the dict constructor, including keyword arguments.

defaultdict objects support the following method in addition to the standard dict operations:

__missing__(key)

If the default_factory attribute is None, this raises a KeyError exception with the key as argument.

If default_factory is not None, it is called without arguments to provide a default value for the given key, this value is inserted in the dictionary for the key, and returned.

If calling default_factory raises an exception this exception is propagated unchanged.

This method is called by the __getitem__() method of the dict class when the requested key is not found; whatever it returns or raises is then returned or raised by __getitem__().

Note that __missing__() is not called for any operations besides __getitem__(). This means that get() will, like normal dictionaries, return None as a default rather than using default_factory.

defaultdict objects support the following instance variable:

default_factory

This attribute is used by the __missing__() method; it is initialized from the first argument to the constructor, if present, or to None, if absent.

defaultdict Examples

Using list as the default_factory, it is easy to group a sequence of key-value pairs into a dictionary of lists:

>>> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
>>> d = defaultdict(list)
>>> for k, v in s:
...     d[k].append(v)
...
>>> sorted(d.items())
[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]

When each key is encountered for the first time, it is not already in the mapping; so an entry is automatically created using the default_factory function which returns an empty list. The list.append() operation then attaches the value to the new list. When keys are encountered again, the look-up proceeds normally (returning the list for that key) and the list.append() operation adds another value to the list. This technique is simpler and faster than an equivalent technique using dict.setdefault():

>>> d = {}
>>> for k, v in s:
...     d.setdefault(k, []).append(v)
...
>>> sorted(d.items())
[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]

Setting the default_factory to int makes the defaultdict useful for counting (like a bag or multiset in other languages):

>>> s = 'mississippi'
>>> d = defaultdict(int)
>>> for k in s:
...     d[k] += 1
...
>>> sorted(d.items())
[('i', 4), ('m', 1), ('p', 2), ('s', 4)]

When a letter is first encountered, it is missing from the mapping, so the default_factory function calls int() to supply a default count of zero. The increment operation then builds up the count for each letter.

The function int() which always returns zero is just a special case of constant functions. A faster and more flexible way to create constant functions is to use a lambda function which can supply any constant value (not just zero):

>>> def constant_factory(value):
...     return lambda: value
>>> d = defaultdict(constant_factory('<missing>'))
>>> d.update(name='John', action='ran')
>>> '%(name)s %(action)s to %(object)s' % d
'John ran to <missing>'

Setting the default_factory to set makes the defaultdict useful for building a dictionary of sets:

>>> s = [('red', 1), ('blue', 2), ('red', 3), ('blue', 4), ('red', 1), ('blue', 4)]
>>> d = defaultdict(set)
>>> for k, v in s:
...     d[k].add(v)
...
>>> sorted(d.items())
[('blue', {2, 4}), ('red', {1, 3})]

namedtuple() Factory Function for Tuples with Named Fields

Named tuples assign meaning to each position in a tuple and allow for more readable, self-documenting code. They can be used wherever regular tuples are used, and they add the ability to access fields by name instead of position index.

collections.namedtuple(typename, field_names, *, rename=False, defaults=None, module=None)

Returns a new tuple subclass named typename. The new subclass is used to create tuple-like objects that have fields accessible by attribute lookup as well as being indexable and iterable. Instances of the subclass also have a helpful docstring (with typename and field_names) and a helpful __repr__() method which lists the tuple contents in a name=value format.

The field_names are a sequence of strings such as ['x', 'y']. Alternatively, field_names can be a single string with each fieldname separated by whitespace and/or commas, for example 'x y' or 'x, y'.

Any valid Python identifier may be used for a fieldname except for names starting with an underscore. Valid identifiers consist of letters, digits, and underscores but do not start with a digit or underscore and cannot be a keyword such as class, for, return, global, pass, or raise.

If rename is true, invalid fieldnames are automatically replaced with positional names. For example, ['abc', 'def', 'ghi', 'abc'] is converted to ['abc', '_1', 'ghi', '_3'], eliminating the keyword def and the duplicate fieldname abc.

defaults can be None or an iterable of default values. Since fields with a default value must come after any fields without a default, the defaults are applied to the rightmost parameters. For example, if the fieldnames are ['x', 'y', 'z'] and the defaults are (1, 2), then x will be a required argument, y will default to 1, and z will default to 2.

If module is defined, the __module__ attribute of the named tuple is set to that value.

Named tuple instances do not have per-instance dictionaries, so they are lightweight and require no more memory than regular tuples.

버전 3.1에서 변경: Added support for rename.

버전 3.6에서 변경: The verbose and rename parameters became keyword-only arguments.

버전 3.6에서 변경: Added the module parameter.

버전 3.7에서 변경: Remove the verbose parameter and the _source attribute.

버전 3.7에서 변경: Added the defaults parameter and the _field_defaults attribute.

>>> # Basic example
>>> Point = namedtuple('Point', ['x', 'y'])
>>> p = Point(11, y=22)     # instantiate with positional or keyword arguments
>>> p[0] + p[1]             # indexable like the plain tuple (11, 22)
33
>>> x, y = p                # unpack like a regular tuple
>>> x, y
(11, 22)
>>> p.x + p.y               # fields also accessible by name
33
>>> p                       # readable __repr__ with a name=value style
Point(x=11, y=22)

Named tuples are especially useful for assigning field names to result tuples returned by the csv or sqlite3 modules:

EmployeeRecord = namedtuple('EmployeeRecord', 'name, age, title, department, paygrade')

import csv
for emp in map(EmployeeRecord._make, csv.reader(open("employees.csv", "rb"))):
    print(emp.name, emp.title)

import sqlite3
conn = sqlite3.connect('/companydata')
cursor = conn.cursor()
cursor.execute('SELECT name, age, title, department, paygrade FROM employees')
for emp in map(EmployeeRecord._make, cursor.fetchall()):
    print(emp.name, emp.title)

In addition to the methods inherited from tuples, named tuples support three additional methods and two attributes. To prevent conflicts with field names, the method and attribute names start with an underscore.

classmethod somenamedtuple._make(iterable)

Class method that makes a new instance from an existing sequence or iterable.

>>> t = [11, 22]
>>> Point._make(t)
Point(x=11, y=22)

somenamedtuple._asdict()

Return a new dict which maps field names to their corresponding values:

>>> p = Point(x=11, y=22)
>>> p._asdict()
OrderedDict([('x', 11), ('y', 22)])

버전 3.1에서 변경: Returns an OrderedDict instead of a regular dict.

somenamedtuple._replace(**kwargs)

Return a new instance of the named tuple replacing specified fields with new values:

>>> p = Point(x=11, y=22)
>>> p._replace(x=33)
Point(x=33, y=22)

>>> for partnum, record in inventory.items():
...     inventory[partnum] = record._replace(price=newprices[partnum], timestamp=time.now())

somenamedtuple._fields

Tuple of strings listing the field names. Useful for introspection and for creating new named tuple types from existing named tuples.

>>> p._fields            # view the field names
('x', 'y')

>>> Color = namedtuple('Color', 'red green blue')
>>> Pixel = namedtuple('Pixel', Point._fields + Color._fields)
>>> Pixel(11, 22, 128, 255, 0)
Pixel(x=11, y=22, red=128, green=255, blue=0)

somenamedtuple._field_defaults

Dictionary mapping field names to default values.

>>> Account = namedtuple('Account', ['type', 'balance'], defaults=[0])
>>> Account._field_defaults
{'balance': 0}
>>> Account('premium')
Account(type='premium', balance=0)

To retrieve a field whose name is stored in a string, use the getattr() function:

>>> getattr(p, 'x')
11

To convert a dictionary to a named tuple, use the ** operator (as described in 인자 목록 언 패킹):

>>> d = {'x': 11, 'y': 22}
>>> Point(**d)
Point(x=11, y=22)

Since a named tuple is a regular Python class, it is easy to add or change functionality with a subclass. Here is how to add a calculated field and a fixed-width print format:

>>> class Point(namedtuple('Point', ['x', 'y'])):
...     __slots__ = ()
...     @property
...     def hypot(self):
...         return (self.x ** 2 + self.y ** 2) ** 0.5
...     def __str__(self):
...         return 'Point: x=%6.3f  y=%6.3f  hypot=%6.3f' % (self.x, self.y, self.hypot)

>>> for p in Point(3, 4), Point(14, 5/7):
...     print(p)
Point: x= 3.000  y= 4.000  hypot= 5.000
Point: x=14.000  y= 0.714  hypot=14.018

The subclass shown above sets __slots__ to an empty tuple. This helps keep memory requirements low by preventing the creation of instance dictionaries.

Subclassing is not useful for adding new, stored fields. Instead, simply create a new named tuple type from the _fields attribute:

>>> Point3D = namedtuple('Point3D', Point._fields + ('z',))

Docstrings can be customized by making direct assignments to the __doc__ fields:

>>> Book = namedtuple('Book', ['id', 'title', 'authors'])
>>> Book.__doc__ += ': Hardcover book in active collection'
>>> Book.id.__doc__ = '13-digit ISBN'
>>> Book.title.__doc__ = 'Title of first printing'
>>> Book.authors.__doc__ = 'List of authors sorted by last name'

버전 3.5에서 변경: Property docstrings became writeable.

Default values can be implemented by using _replace() to customize a prototype instance:

>>> Account = namedtuple('Account', 'owner balance transaction_count')
>>> default_account = Account('<owner name>', 0.0, 0)
>>> johns_account = default_account._replace(owner='John')
>>> janes_account = default_account._replace(owner='Jane')

더 보기

See typing.NamedTuple for a way to add type hints for named tuples. It also provides an elegant notation using the class keyword:

class Component(NamedTuple):
    part_number: int
    weight: float
    description: Optional[str] = None

See types.SimpleNamespace() for a mutable namespace based on an underlying dictionary instead of a tuple.

The dataclasses module provides a decorator and functions for automatically adding generated special methods to user-defined classes.

OrderedDict objects

Ordered dictionaries are just like regular dictionaries but have some extra capabilities relating to ordering operations. They have become less important now that the built-in dict class gained the ability to remember insertion order (this new behavior became guaranteed in Python 3.7).

Some differences from dict still remain:

The regular dict was designed to be very good at mapping operations. Tracking insertion order was secondary.

The OrderedDict was designed to be good at reordering operations. Space efficiency, iteration speed, and the performance of update operations were secondary.

Algorithmically, OrderedDict can handle frequent reordering operations better than dict. This makes it suitable for tracking recent accesses (for example in an LRU cache [https://medium.com/@krishankantsinghal/my-first-blog-on-medium-583159139237]).

The equality operation for OrderedDict checks for matching order.

The popitem() method of OrderedDict has a different signature. It accepts an optional argument to specify which item is popped.

OrderedDict has a move_to_end() method to efficiently reposition an element to an endpoint.

Until Python 3.8, dict lacked a __reversed__() method.

class collections.OrderedDict([items])

Return an instance of a dict subclass that has methods specialized for rearranging dictionary order.

버전 3.1에 추가.

popitem(last=True)

The popitem() method for ordered dictionaries returns and removes a (key, value) pair. The pairs are returned in LIFO order if last is true or FIFO order if false.

move_to_end(key, last=True)

Move an existing key to either end of an ordered dictionary. The item is moved to the right end if last is true (the default) or to the beginning if last is false. Raises KeyError if the key does not exist:

>>> d = OrderedDict.fromkeys('abcde')
>>> d.move_to_end('b')
>>> ''.join(d.keys())
'acdeb'
>>> d.move_to_end('b', last=False)
>>> ''.join(d.keys())
'bacde'

버전 3.2에 추가.

In addition to the usual mapping methods, ordered dictionaries also support reverse iteration using reversed().

Equality tests between OrderedDict objects are order-sensitive and are implemented as list(od1.items())==list(od2.items()). Equality tests between OrderedDict objects and other Mapping objects are order-insensitive like regular dictionaries. This allows OrderedDict objects to be substituted anywhere a regular dictionary is used.

버전 3.5에서 변경: The items, keys, and values views of OrderedDict now support reverse iteration using reversed().

버전 3.6에서 변경: With the acceptance of PEP 468 [https://www.python.org/dev/peps/pep-0468], order is retained for keyword arguments passed to the OrderedDict constructor and its update() method.

OrderedDict Examples and Recipes

It is straightforward to create an ordered dictionary variant that remembers the order the keys were last inserted. If a new entry overwrites an existing entry, the original insertion position is changed and moved to the end:

class LastUpdatedOrderedDict(OrderedDict):
    'Store items in the order the keys were last added'

    def __setitem__(self, key, value):
        super().__setitem__(key, value)
        super().move_to_end(key)

An OrderedDict would also be useful for implementing variants of functools.lru_cache():

class LRU(OrderedDict):
    'Limit size, evicting the least recently looked-up key when full'

    def __init__(self, maxsize=128, *args, **kwds):
        self.maxsize = maxsize
        super().__init__(*args, **kwds)

    def __getitem__(self, key):
        value = super().__getitem__(key)
        self.move_to_end(key)
        return value

    def __setitem__(self, key, value):
        super().__setitem__(key, value)
        if len(self) > self.maxsize:
            oldest = next(iter(self))
            del self[oldest]

UserDict objects

The class, UserDict acts as a wrapper around dictionary objects. The need for this class has been partially supplanted by the ability to subclass directly from dict; however, this class can be easier to work with because the underlying dictionary is accessible as an attribute.

class collections.UserDict([initialdata])

Class that simulates a dictionary. The instance’s contents are kept in a regular dictionary, which is accessible via the data attribute of UserDict instances. If initialdata is provided, data is initialized with its contents; note that a reference to initialdata will not be kept, allowing it be used for other purposes.

In addition to supporting the methods and operations of mappings, UserDict instances provide the following attribute:

data

A real dictionary used to store the contents of the UserDict class.

UserList objects

This class acts as a wrapper around list objects. It is a useful base class for your own list-like classes which can inherit from them and override existing methods or add new ones. In this way, one can add new behaviors to lists.

The need for this class has been partially supplanted by the ability to subclass directly from list; however, this class can be easier to work with because the underlying list is accessible as an attribute.

class collections.UserList([list])

Class that simulates a list. The instance’s contents are kept in a regular list, which is accessible via the data attribute of UserList instances. The instance’s contents are initially set to a copy of list, defaulting to the empty list []. list can be any iterable, for example a real Python list or a UserList object.

In addition to supporting the methods and operations of mutable sequences, UserList instances provide the following attribute:

data

A real list object used to store the contents of the UserList class.

Subclassing requirements: Subclasses of UserList are expected to offer a constructor which can be called with either no arguments or one argument. List operations which return a new sequence attempt to create an instance of the actual implementation class. To do so, it assumes that the constructor can be called with a single parameter, which is a sequence object used as a data source.

If a derived class does not wish to comply with this requirement, all of the special methods supported by this class will need to be overridden; please consult the sources for information about the methods which need to be provided in that case.

UserString objects

The class, UserString acts as a wrapper around string objects. The need for this class has been partially supplanted by the ability to subclass directly from str; however, this class can be easier to work with because the underlying string is accessible as an attribute.

class collections.UserString(seq)

Class that simulates a string object. The instance’s content is kept in a regular string object, which is accessible via the data attribute of UserString instances. The instance’s contents are initially set to a copy of seq. The seq argument can be any object which can be converted into a string using the built-in str() function.

In addition to supporting the methods and operations of strings, UserString instances provide the following attribute:

data

A real str object used to store the contents of the UserString class.

버전 3.5에서 변경: New methods __getnewargs__, __rmod__, casefold, format_map, isprintable, and maketrans.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

데이터형 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

데이터형 »

|

collections.abc — 컨테이너의 추상 베이스 클래스

버전 3.3에 추가: 이전에는, 이 모듈이 collections 모듈의 일부였습니다.

소스 코드: Lib/_collections_abc.py [https://github.com/python/cpython/tree/3.7/Lib/_collections_abc.py]

이 모듈은 클래스가 특정 인터페이스를 제공하는지를 검사하는 데 사용할 수 있는 추상 베이스 클래스를 제공합니다; 예를 들어, 해시 가능한지 또는 매핑인지입니다.

Collections 추상 베이스 클래스

collections 모듈은 다음과 같은 ABC를 제공합니다:

ABC

상속

추상 메서드

믹스인 메서드

Container

__contains__

Hashable

__hash__

Iterable

__iter__

Iterator

Iterable

__next__

__iter__

Reversible

Iterable

__reversed__

Generator

Iterator

send, throw

close, __iter__, __next__

Sized

__len__

Callable

__call__

Collection

Sized, Iterable, Container

__contains__, __iter__, __len__

Sequence

Reversible, Collection

__getitem__, __len__

__contains__, __iter__, __reversed__, index 및 count

MutableSequence

Sequence

__getitem__, __setitem__, __delitem__, __len__, insert

상속된 Sequence 메서드와 append, reverse, extend, pop, remove 및 __iadd__

ByteString

Sequence

__getitem__, __len__

상속된 Sequence 메서드

Set

Collection

__contains__, __iter__, __len__

__le__, __lt__, __eq__, __ne__, __gt__, __ge__, __and__, __or__, __sub__, __xor__ 및 isdisjoint

MutableSet

Set

__contains__, __iter__, __len__, add, discard

상속된 Set 메서드와 clear, pop, remove, __ior__, __iand__, __ixor__ 및 __isub__

Mapping

Collection

__getitem__, __iter__, __len__

__contains__, keys, items, values, get, __eq__ 및 __ne__

MutableMapping

Mapping

__getitem__, __setitem__, __delitem__, __iter__, __len__

상속된 Mapping 메서드와 pop, popitem, clear, update 및 setdefault

MappingView

Sized

__len__

ItemsView

MappingView, Set

__contains__, __iter__

KeysView

MappingView, Set

__contains__, __iter__

ValuesView

MappingView, Collection

__contains__, __iter__

Awaitable

__await__

Coroutine

Awaitable

send, throw

close

AsyncIterable

__aiter__

AsyncIterator

AsyncIterable

__anext__

__aiter__

AsyncGenerator

AsyncIterator

asend, athrow

aclose, __aiter__, __anext__

class collections.abc.Container

class collections.abc.Hashable

class collections.abc.Sized

class collections.abc.Callable

각각 메서드 __contains__(), __hash__(), __len__() 및 __call__()을 제공하는 클래스의 ABC.

class collections.abc.Iterable

__iter__() 메서드를 제공하는 클래스의 ABC.

isinstance(obj, Iterable)를 검사하면 Iterable로 등록되었거나 __iter__() 메서드가 있는 클래스를 감지하지만, __getitem__() 메서드로 이터레이트 하는 클래스는 감지하지 않습니다. 객체가 이터러블인지를 확인하는 유일하게 신뢰성 있는 방법은 iter(obj)를 호출하는 것입니다.

class collections.abc.Collection

길이가 있는 이터러블 컨테이너 클래스의 ABC.

버전 3.6에 추가.

class collections.abc.Iterator

__iter__() 와 __next__() 메서드를 제공하는 클래스의 ABC. 이터레이터의 정의도 참조하십시오.

class collections.abc.Reversible

__reversed__() 메서드도 제공하는 이터러블 클래스의 ABC.

버전 3.6에 추가.

class collections.abc.Generator

send(), throw() 및 close() 메서드로 이터레이터를 확장하는 PEP 342 [https://www.python.org/dev/peps/pep-0342]에 정의된 프로토콜을 구현하는 제너레이터 클래스의 ABC. 제너레이터의 정의도 참조하십시오.

버전 3.5에 추가.

class collections.abc.Sequence

class collections.abc.MutableSequence

class collections.abc.ByteString

읽기 전용과 가변 시퀀스의 ABC.

구현 참고 사항: __iter__(), __reversed__() 및 index()와 같은 일부 믹스인(mixin) 메서드는 하부 __getitem__() 메서드를 반복적으로 호출합니다. 따라서, __getitem__()이 상수 액세스 속도로 구현되면 믹스인 메서드는 선형 성능을 갖습니다; 그러나 하부 메서드가 선형이면 (링크드 리스트에서처럼), 믹스인은 2차 함수 성능을 가지므로 재정의해야 할 수 있습니다.

버전 3.5에서 변경: index() 메서드는 stop과 start 인자에 대한 지원을 추가했습니다.

class collections.abc.Set

class collections.abc.MutableSet

읽기 전용과 가변 집합의 ABC.

class collections.abc.Mapping

class collections.abc.MutableMapping

읽기 전용과 가변 매핑의 ABC.

class collections.abc.MappingView

class collections.abc.ItemsView

class collections.abc.KeysView

class collections.abc.ValuesView

매핑, 항목, 키 및 값 뷰의 ABC.

class collections.abc.Awaitable

await 표현식에서 사용할 수 있는 어웨이터블 객체의 ABC. 사용자 정의 구현은 __await__() 메서드를 제공해야 합니다.

코루틴 객체와 Coroutine ABC의 인스턴스는 모두 이 ABC의 인스턴스입니다.

참고

CPython에서, 제너레이터 기반 코루틴(types.coroutine()이나 asyncio.coroutine()으로 데코레이트 된 제너레이터)은, __await__() 메서드가 없어도 어웨이터블 입니다. 이들에 대해 isinstance(gencoro, Awaitable)를 사용하면 False가 반환됩니다. 이들을 감지하려면 inspect.isawaitable()을 사용하십시오.

버전 3.5에 추가.

class collections.abc.Coroutine

코루틴 호환 클래스의 ABC. 코루틴 객체(Coroutine Objects)에 정의된 다음 메서드를 구현합니다: send(), throw() 및 close(). 사용자 정의 구현은 __await__()도 구현해야 합니다. 모든 Coroutine 인스턴스는 Awaitable의 인스턴스이기도 합니다. 코루틴의 정의도 참조하십시오.

참고

CPython에서, 제너레이터 기반 코루틴(types.coroutine()이나 asyncio.coroutine()으로 데코레이트 된 제너레이터)은, __await__() 메서드가 없어도 어웨이터블 입니다. 이들에 대해 isinstance(gencoro, Coroutine)을 사용하면 False가 반환됩니다. 이들을 감지하려면 inspect.isawaitable()을 사용하십시오.

버전 3.5에 추가.

class collections.abc.AsyncIterable

__aiter__ 메서드를 제공하는 클래스의 ABC. 비동기 이터러블의 정의도 참조하십시오.

버전 3.5에 추가.

class collections.abc.AsyncIterator

__aiter__ 와 __anext__ 메서드를 제공하는 클래스의 ABC. 비동기 이터레이터의 정의도 참조하십시오.

버전 3.5에 추가.

class collections.abc.AsyncGenerator

PEP 525 [https://www.python.org/dev/peps/pep-0525]와 PEP 492 [https://www.python.org/dev/peps/pep-0492]에 정의된 프로토콜을 구현하는 비동기 제너레이터 클래스의 ABC.

버전 3.6에 추가.

이러한 ABC들은 클래스나 인스턴스가 특정 기능을 제공하는지 묻는 것을 허용합니다, 예를 들어:

size = None
if isinstance(myvar, collections.abc.Sized):
    size = len(myvar)

ABC 중 일부는 믹스인으로도 유용하여 컨테이너 API를 지원하는 클래스를 쉽게 개발할 수 있게 합니다. 예를 들어, 전체 Set API를 지원하는 클래스를 작성하려면, __contains__(), __iter__() 및 __len__()의 세 가지 하부 추상 메서드 만 제공하면 됩니다. ABC는 __and__()와 isdisjoint()와 같은 나머지 메서드를 제공합니다:

class ListBasedSet(collections.abc.Set):
    ''' Alternate set implementation favoring space over speed
        and not requiring the set elements to be hashable. '''
    def __init__(self, iterable):
        self.elements = lst = []
        for value in iterable:
            if value not in lst:
                lst.append(value)

    def __iter__(self):
        return iter(self.elements)

    def __contains__(self, value):
        return value in self.elements

    def __len__(self):
        return len(self.elements)

s1 = ListBasedSet('abcdef')
s2 = ListBasedSet('defghi')
overlap = s1 & s2            # The __and__() method is supported automatically

Set과 MutableSet을 믹스인으로 사용할 때의 주의 사항:

일부 집합 연산은 새로운 집합을 만들기 때문에, 기본 믹스인 메서드는 이터러블로부터 새 인스턴스를 만드는 방법이 필요합니다. 클래스 생성자가 ClassName(iterable) 형식의 서명을 가진 것으로 가정합니다. 이 가정은 새로운 집합을 생성하기 위해 cls(iterable)를 호출하는 _from_iterable()이라는 내부 클래스 메서드로 분리되었습니다. Set 믹스인이 다른 생성자 서명을 갖는 클래스에서 사용되고 있으면, 이터러블 인자로부터 새 인스턴스를 생성할 수 있는 클래스 메서드로 _from_iterable()을 재정의해야 합니다.

비교를 재정의하려면 (의미는 고정되었으므로, 아마도 속도 때문에), __le__()와 __ge__()를 재정의하십시오, 그러면 다른 연산은 자동으로 맞춰집니다.

Set 믹스인은 집합의 해시값을 계산하는 _hash() 메서드를 제공합니다; 그러나 모든 집합이 해시 가능하거나 불변이지는 않기 때문에 __hash__()는 정의되지 않습니다. 믹스인을 사용하여 집합 해시 가능성을 추가하려면, Set()와 Hashable()을 모두 상속한 다음, __hash__ = Set._hash를 정의하십시오.

더 보기

MutableSet으로 구축한 예제 OrderedSet 조리법 [https://code.activestate.com/recipes/576694/].

ABC에 대한 자세한 내용은, abc 모듈과 PEP 3119 [https://www.python.org/dev/peps/pep-3119]를 참조하십시오.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

데이터형 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

데이터형 »

|

heapq — Heap queue algorithm

Source code: Lib/heapq.py [https://github.com/python/cpython/tree/3.7/Lib/heapq.py]

This module provides an implementation of the heap queue algorithm, also known as the priority queue algorithm.

Heaps are binary trees for which every parent node has a value less than or equal to any of its children. This implementation uses arrays for which heap[k] <= heap[2*k+1] and heap[k] <= heap[2*k+2] for all k, counting elements from zero. For the sake of comparison, non-existing elements are considered to be infinite. The interesting property of a heap is that its smallest element is always the root, heap[0].

The API below differs from textbook heap algorithms in two aspects: (a) We use zero-based indexing. This makes the relationship between the index for a node and the indexes for its children slightly less obvious, but is more suitable since Python uses zero-based indexing. (b) Our pop method returns the smallest item, not the largest (called a “min heap” in textbooks; a “max heap” is more common in texts because of its suitability for in-place sorting).

These two make it possible to view the heap as a regular Python list without surprises: heap[0] is the smallest item, and heap.sort() maintains the heap invariant!

To create a heap, use a list initialized to [], or you can transform a populated list into a heap via function heapify().

The following functions are provided:

heapq.heappush(heap, item)

Push the value item onto the heap, maintaining the heap invariant.

heapq.heappop(heap)

Pop and return the smallest item from the heap, maintaining the heap invariant. If the heap is empty, IndexError is raised. To access the smallest item without popping it, use heap[0].

heapq.heappushpop(heap, item)

Push item on the heap, then pop and return the smallest item from the heap. The combined action runs more efficiently than heappush() followed by a separate call to heappop().

heapq.heapify(x)

Transform list x into a heap, in-place, in linear time.

heapq.heapreplace(heap, item)

Pop and return the smallest item from the heap, and also push the new item. The heap size doesn’t change. If the heap is empty, IndexError is raised.

This one step operation is more efficient than a heappop() followed by heappush() and can be more appropriate when using a fixed-size heap. The pop/push combination always returns an element from the heap and replaces it with item.

The value returned may be larger than the item added. If that isn’t desired, consider using heappushpop() instead. Its push/pop combination returns the smaller of the two values, leaving the larger value on the heap.

The module also offers three general purpose functions based on heaps.

heapq.merge(*iterables, key=None, reverse=False)

Merge multiple sorted inputs into a single sorted output (for example, merge timestamped entries from multiple log files). Returns an iterator over the sorted values.

Similar to sorted(itertools.chain(*iterables)) but returns an iterable, does not pull the data into memory all at once, and assumes that each of the input streams is already sorted (smallest to largest).

Has two optional arguments which must be specified as keyword arguments.

key specifies a key function of one argument that is used to extract a comparison key from each input element. The default value is None (compare the elements directly).

reverse is a boolean value. If set to True, then the input elements are merged as if each comparison were reversed. To achieve behavior similar to sorted(itertools.chain(*iterables), reverse=True), all iterables must be sorted from largest to smallest.

버전 3.5에서 변경: Added the optional key and reverse parameters.

heapq.nlargest(n, iterable, key=None)

Return a list with the n largest elements from the dataset defined by iterable. key, if provided, specifies a function of one argument that is used to extract a comparison key from each element in iterable (for example, key=str.lower). Equivalent to: sorted(iterable, key=key, reverse=True)[:n].

heapq.nsmallest(n, iterable, key=None)

Return a list with the n smallest elements from the dataset defined by iterable. key, if provided, specifies a function of one argument that is used to extract a comparison key from each element in iterable (for example, key=str.lower). Equivalent to: sorted(iterable, key=key)[:n].

The latter two functions perform best for smaller values of n. For larger values, it is more efficient to use the sorted() function. Also, when n==1, it is more efficient to use the built-in min() and max() functions. If repeated usage of these functions is required, consider turning the iterable into an actual heap.

Basic Examples

A heapsort [https://en.wikipedia.org/wiki/Heapsort] can be implemented by pushing all values onto a heap and then popping off the smallest values one at a time:

>>> def heapsort(iterable):
...     h = []
...     for value in iterable:
...         heappush(h, value)
...     return [heappop(h) for i in range(len(h))]
...
>>> heapsort([1, 3, 5, 7, 9, 2, 4, 6, 8, 0])
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

This is similar to sorted(iterable), but unlike sorted(), this implementation is not stable.

Heap elements can be tuples. This is useful for assigning comparison values (such as task priorities) alongside the main record being tracked:

>>> h = []
>>> heappush(h, (5, 'write code'))
>>> heappush(h, (7, 'release product'))
>>> heappush(h, (1, 'write spec'))
>>> heappush(h, (3, 'create tests'))
>>> heappop(h)
(1, 'write spec')

Priority Queue Implementation Notes

A priority queue [https://en.wikipedia.org/wiki/Priority_queue] is common use for a heap, and it presents several implementation challenges:

Sort stability: how do you get two tasks with equal priorities to be returned in the order they were originally added?

Tuple comparison breaks for (priority, task) pairs if the priorities are equal and the tasks do not have a default comparison order.

If the priority of a task changes, how do you move it to a new position in the heap?

Or if a pending task needs to be deleted, how do you find it and remove it from the queue?

A solution to the first two challenges is to store entries as 3-element list including the priority, an entry count, and the task. The entry count serves as a tie-breaker so that two tasks with the same priority are returned in the order they were added. And since no two entry counts are the same, the tuple comparison will never attempt to directly compare two tasks.

Another solution to the problem of non-comparable tasks is to create a wrapper class that ignores the task item and only compares the priority field:

from dataclasses import dataclass, field
from typing import Any

@dataclass(order=True)
class PrioritizedItem:
    priority: int
    item: Any=field(compare=False)

The remaining challenges revolve around finding a pending task and making changes to its priority or removing it entirely. Finding a task can be done with a dictionary pointing to an entry in the queue.

Removing the entry or changing its priority is more difficult because it would break the heap structure invariants. So, a possible solution is to mark the entry as removed and add a new entry with the revised priority:

pq = []                         # list of entries arranged in a heap
entry_finder = {}               # mapping of tasks to entries
REMOVED = '<removed-task>'      # placeholder for a removed task
counter = itertools.count()     # unique sequence count

def add_task(task, priority=0):
    'Add a new task or update the priority of an existing task'
    if task in entry_finder:
        remove_task(task)
    count = next(counter)
    entry = [priority, count, task]
    entry_finder[task] = entry
    heappush(pq, entry)

def remove_task(task):
    'Mark an existing task as REMOVED.  Raise KeyError if not found.'
    entry = entry_finder.pop(task)
    entry[-1] = REMOVED

def pop_task():
    'Remove and return the lowest priority task. Raise KeyError if empty.'
    while pq:
        priority, count, task = heappop(pq)
        if task is not REMOVED:
            del entry_finder[task]
            return task
    raise KeyError('pop from an empty priority queue')

Theory

Heaps are arrays for which a[k] <= a[2*k+1] and a[k] <= a[2*k+2] for all k, counting elements from 0. For the sake of comparison, non-existing elements are considered to be infinite. The interesting property of a heap is that a[0] is always its smallest element.

The strange invariant above is meant to be an efficient memory representation for a tournament. The numbers below are k, not a[k]:

                               0

              1                                 2

      3               4                5               6

  7       8       9       10      11      12      13      14

15 16   17 18   19 20   21 22   23 24   25 26   27 28   29 30

In the tree above, each cell k is topping 2*k+1 and 2*k+2. In a usual binary tournament we see in sports, each cell is the winner over the two cells it tops, and we can trace the winner down the tree to see all opponents s/he had. However, in many computer applications of such tournaments, we do not need to trace the history of a winner. To be more memory efficient, when a winner is promoted, we try to replace it by something else at a lower level, and the rule becomes that a cell and the two cells it tops contain three different items, but the top cell “wins” over the two topped cells.

If this heap invariant is protected at all time, index 0 is clearly the overall winner. The simplest algorithmic way to remove it and find the “next” winner is to move some loser (let’s say cell 30 in the diagram above) into the 0 position, and then percolate this new 0 down the tree, exchanging values, until the invariant is re-established. This is clearly logarithmic on the total number of items in the tree. By iterating over all items, you get an O(n log n) sort.

A nice feature of this sort is that you can efficiently insert new items while the sort is going on, provided that the inserted items are not “better” than the last 0’th element you extracted. This is especially useful in simulation contexts, where the tree holds all incoming events, and the “win” condition means the smallest scheduled time. When an event schedules other events for execution, they are scheduled into the future, so they can easily go into the heap. So, a heap is a good structure for implementing schedulers (this is what I used for my MIDI sequencer :-).

Various structures for implementing schedulers have been extensively studied, and heaps are good for this, as they are reasonably speedy, the speed is almost constant, and the worst case is not much different than the average case. However, there are other representations which are more efficient overall, yet the worst cases might be terrible.

Heaps are also very useful in big disk sorts. You most probably all know that a big sort implies producing “runs” (which are pre-sorted sequences, whose size is usually related to the amount of CPU memory), followed by a merging passes for these runs, which merging is often very cleverly organised 1. It is very important that the initial sort produces the longest runs possible. Tournaments are a good way to achieve that. If, using all the memory available to hold a tournament, you replace and percolate items that happen to fit the current run, you’ll produce runs which are twice the size of the memory for random input, and much better for input fuzzily ordered.

Moreover, if you output the 0’th item on disk and get an input which may not fit in the current tournament (because the value “wins” over the last output value), it cannot fit in the heap, so the size of the heap decreases. The freed memory could be cleverly reused immediately for progressively building a second heap, which grows at exactly the same rate the first heap is melting. When the first heap completely vanishes, you switch heaps and start a new run. Clever and quite effective!

In a word, heaps are useful memory structures to know. I use them in a few applications, and I think it is good to keep a ‘heap’ module around. :-)

Footnotes

1

The disk balancing algorithms which are current, nowadays, are more annoying than clever, and this is a consequence of the seeking capabilities of the disks. On devices which cannot seek, like big tape drives, the story was quite different, and one had to be very clever to ensure (far in advance) that each tape movement will be the most effective possible (that is, will best participate at “progressing” the merge). Some tapes were even able to read backwards, and this was also used to avoid the rewinding time. Believe me, real good tape sorts were quite spectacular to watch! From all times, sorting has always been a Great Art! :-)

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

데이터형 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

데이터형 »

|

bisect — 배열 이진 분할 알고리즘

소스 코드: Lib/bisect.py [https://github.com/python/cpython/tree/3.7/Lib/bisect.py]

이 모듈은 정렬된 리스트를 삽입 후에 다시 정렬할 필요 없도록 관리할 수 있도록 지원합니다. 값비싼 비교 연산이 포함된 항목의 긴 리스트의 경우, 이는 일반적인 방법에 비해 개선된 것입니다. 이 모듈은 기본적인 이진 분할 알고리즘을 사용하기 때문에 bisect라고 불립니다. 소스 코드는 알고리즘의 실제 예로서 가장 유용할 수 있습니다 (경계 조건은 이미 옳습니다!).

다음과 같은 함수가 제공됩니다:

bisect.bisect_left(a, x, lo=0, hi=len(a))

정렬된 순서를 유지하도록 a에 x를 삽입할 위치를 찾습니다. 매개 변수 lo 와 hi는 고려해야 할 리스트의 부분집합을 지정하는 데 사용될 수 있습니다; 기본적으로 전체 리스트가 사용됩니다. x가 a에 이미 있으면, 삽입 위치는 기존 항목 앞(왼쪽)이 됩니다. 반환 값은 a가 이미 정렬되었다고 가정할 때 list.insert()의 첫 번째 매개 변수로 사용하기에 적합합니다.

반환된 삽입 위치 i는 배열 a를 이분하여, 왼쪽은 all(val < x for val in a[lo:i]), 오른쪽은 all(val >= x for val in a[i:hi])이 되도록 만듭니다.

bisect.bisect_right(a, x, lo=0, hi=len(a))

bisect.bisect(a, x, lo=0, hi=len(a))

bisect_left()와 비슷하지만, a에 있는 x의 기존 항목 뒤(오른쪽)에 오는 삽입 위치를 반환합니다.

반환된 삽입 위치 i는 배열 a를 이분하여, 왼쪽은 all(val <= x for val in a[lo:i]), 오른쪽은 all(val > x for val in a[i:hi])이 되도록 만듭니다.

bisect.insort_left(a, x, lo=0, hi=len(a))

a에 x를 정렬된 순서로 삽입합니다. a가 이미 정렬되었다고 가정할 때 a.insert(bisect.bisect_left(a, x, lo, hi), x)와 동등합니다. O(log n) 검색이 느린 O(n) 삽입 단계에 가려짐에 유념하십시오.

bisect.insort_right(a, x, lo=0, hi=len(a))

bisect.insort(a, x, lo=0, hi=len(a))

insort_left()와 비슷하지만, a에 x를 x의 기존 항목 다음에 삽입합니다.

더 보기

bisect를 사용하여 직접적인 검색 메서드와 키 함수 지원을 포함하는 완전한 기능을 갖춘 컬렉션 클래스를 만드는 SortedCollection recipe [https://code.activestate.com/recipes/577197-sortedcollection/]. 검색 중에 불필요한 키 함수 호출을 피하고자 키는 미리 계산됩니다.

정렬된 리스트 검색하기

위의 bisect() 함수는 삽입 위치를 찾는 데 유용하지만, 일반적인 검색 작업에 사용하기가 까다롭거나 어색할 수 있습니다. 다음 다섯 함수는 정렬된 리스트에 대한 표준 조회로 변환하는 방법을 보여줍니다:

def index(a, x):
    'Locate the leftmost value exactly equal to x'
    i = bisect_left(a, x)
    if i != len(a) and a[i] == x:
        return i
    raise ValueError

def find_lt(a, x):
    'Find rightmost value less than x'
    i = bisect_left(a, x)
    if i:
        return a[i-1]
    raise ValueError

def find_le(a, x):
    'Find rightmost value less than or equal to x'
    i = bisect_right(a, x)
    if i:
        return a[i-1]
    raise ValueError

def find_gt(a, x):
    'Find leftmost value greater than x'
    i = bisect_right(a, x)
    if i != len(a):
        return a[i]
    raise ValueError

def find_ge(a, x):
    'Find leftmost item greater than or equal to x'
    i = bisect_left(a, x)
    if i != len(a):
        return a[i]
    raise ValueError

다른 예제

bisect() 함수는 숫자 테이블 조회에 유용할 수 있습니다. 이 예제는 bisect()를 사용하여 (가령) 시험 점수에 대한 문자 등급을 조회하는데, 정렬된 숫자 경계점 집합에 기반합니다: 90 이상은 ‘A’, 80에서 89는 ‘B’ 등입니다:

>>> def grade(score, breakpoints=[60, 70, 80, 90], grades='FDCBA'):
...     i = bisect(breakpoints, score)
...     return grades[i]
...
>>> [grade(score) for score in [33, 99, 77, 70, 89, 90, 100]]
['F', 'A', 'C', 'C', 'B', 'A', 'A']

sorted() 함수와 달리, bisect() 함수는 key 나 reversed 인자를 갖는 것은 의미가 없는데, 비효율적인 설계 (연속적인 bisect 함수 호출이 이전의 모든 키 조회를 “기억”하지 못합니다)를 초래하기 때문입니다.

대신, 해당 레코드의 인덱스를 찾기 위해 미리 계산된 키 리스트를 검색하는 것이 좋습니다:

>>> data = [('red', 5), ('blue', 1), ('yellow', 8), ('black', 0)]
>>> data.sort(key=lambda r: r[1])
>>> keys = [r[1] for r in data]         # precomputed list of keys
>>> data[bisect_left(keys, 0)]
('black', 0)
>>> data[bisect_left(keys, 1)]
('blue', 1)
>>> data[bisect_left(keys, 5)]
('red', 5)
>>> data[bisect_left(keys, 8)]
('yellow', 8)

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

데이터형 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

데이터형 »

|

array — 효율적인 숫자 배열

이 모듈은 문자, 정수, 부동 소수점 숫자와 같은 기본적인 값의 배열을 간결하게 표현할 수 있는 객체 형을 정의합니다. 배열은 시퀀스 형이며 리스트와 매우 비슷하게 행동합니다만, 그곳에 저장되는 객체의 형이 제약된다는 점이 다릅니다. 형은 객체 생성 시에 단일 문자인 형 코드(type code)를 사용하여 지정됩니다. 다음 형 코드가 정의됩니다:

형 코드

C 형

파이썬 형

최소 크기(바이트)

노트

'b'

signed char

int

1

'B'

unsigned char

int

1

'u'

Py_UNICODE

유니코드 문자

2

(1)

'h'

signed short

int

2

'H'

unsigned short

int

2

'i'

signed int

int

2

'I'

unsigned int

int

2

'l'

signed long

int

4

'L'

unsigned long

int

4

'q'

signed long long

int

8

'Q'

unsigned long long

int

8

'f'

float

float

4

'd'

double

float

8

노트:

'u' 형 코드는 파이썬의 구식 유니코드 문자(Py_UNICODE, 이것은 wchar_t입니다)에 해당합니다. 플랫폼에 따라, 16비트나 32비트가 될 수 있습니다.

'u'는 나머지 Py_UNICODE API와 함께 제거될 것입니다.

Deprecated since version 3.3, will be removed in version 4.0.

값의 실제 표현은 기계 아키텍처에 의해(엄격히 말하자면 C 구현에 의해) 결정됩니다. 실제 크기는 itemsize 어트리뷰트를 통해 액세스할 수 있습니다.

모듈은 다음 형을 정의합니다:

class array.array(typecode[, initializer])

항목이 typecode에 의해 제한되는 새 배열, 선택적인 initializer 값으로 초기화되는데, 리스트, 바이트열류 객체 또는 적절한 형의 요소에 대한 이터러블이어야 합니다.

리스트나 문자열이 주어지면, initializer는 새 배열의 fromlist(), frombytes() 또는 fromunicode() 메서드(아래를 참조하세요)에 전달되어 배열에 초기 항목을 추가합니다. 그렇지 않으면 이터러블 initializer가 extend() 메서드에 전달됩니다.

array.typecodes

사용 가능한 모든 형 코드가 있는 문자열.

배열 객체는 인덱싱, 슬라이싱, 이어붙이기 및 곱셈과 같은 일반적인 시퀀스 연산을 지원합니다. 슬라이스 대입을 사용할 때, 대입되는 값은 같은 형 코드의 배열 객체여야 합니다; 다른 모든 경우에는, TypeError가 발생합니다. 배열 객체는 버퍼 인터페이스도 구현하며, 바이트열류 객체가 지원되는 곳이면 어디에서나 사용될 수 있습니다.

다음 데이터 항목과 메서드도 지원됩니다:

array.typecode

배열을 만드는 데 사용된 typecode 문자.

array.itemsize

내부 표현에서 하나의 배열 항목의 길이 (바이트).

array.append(x)

배열의 끝에 값 x로 새 항목을 추가합니다.

array.buffer_info()

배열의 내용을 담는 데 사용된 버퍼의 현재 메모리 주소와 요소의 수로 표현한 길이를 제공하는 튜플 (address, length)를 반환합니다. 바이트 단위의 메모리 버퍼 크기는 array.buffer_info()[1] * array.itemsize로 계산할 수 있습니다. 이것은 특정 ioctl() 연산과 같은 메모리 주소가 필요한 저수준(그리고 근본적으로 안전하지 않은) I/O 인터페이스로 작업할 때 간혹 유용합니다. 반환된 숫자는 배열이 존재하고 길이 변경 연산이 적용되지 않는 한 유효합니다.

참고

C나 C++로 작성된 코드(이 정보를 효율적으로 사용하는 유일한 방법)에서 배열 객체를 사용할 때, 배열 객체가 지원하는 버퍼 인터페이스를 사용하는 것이 좋습니다. 이 메서드는 이전 버전과의 호환성을 위해 유지되며 새 코드에서는 사용하지 않아야 합니다. 버퍼 인터페이스는 버퍼 프로토콜에 설명되어 있습니다.

array.byteswap()

배열의 모든 항목을 “바이트 스와프(byteswap)” 합니다. 1, 2, 4 또는 8바이트 크기의 값에 대해서만 지원됩니다; 다른 형의 값이면 RuntimeError가 발생합니다. 바이트 순서가 다른 컴퓨터에서 작성된 파일에서 데이터를 읽을 때 유용합니다.

array.count(x)

배열 내에서 x가 등장하는 횟수를 반환합니다.

array.extend(iterable)

iterable의 항목을 배열의 끝에 추가합니다. iterable이 다른 배열이면, 정확히 같은 형 코드를 가져야 합니다; 그렇지 않으면, TypeError가 발생합니다. iterable이 배열이 아니면, 이터러블이어야 하며 요소는 배열에 추가할 올바른 형이어야 합니다.

array.frombytes(s)

문자열에서 항목을 추가합니다. 문자열을 기곗값(machine value)의 배열로 해석합니다 (마치 fromfile() 메서드를 사용하여 파일에서 읽은 것처럼).

버전 3.2에 추가: fromstring()은 명확하게 하려고 frombytes()로 이름을 바꿨습니다.

array.fromfile(f, n)

파일 객체 f에서 (기곗값으로) n 항목을 읽고 배열의 끝에 추가합니다. n 미만의 항목만 사용할 수 있으면 EOFError가 발생하지만, 사용 가능한 항목은 여전히 배열에 삽입됩니다. f는 실제 내장 파일 객체여야 합니다; read() 메서드를 가진 다른 것은 작동하지 않습니다.

array.fromlist(list)

리스트에서 항목을 추가합니다. 이것은 형 에러가 있으면 배열이 변경되지 않는다는 점만 제외하면 for x in list: a.append(x)와 동등합니다.

array.fromstring()

frombytes()의 폐지된 별칭.

Deprecated since version 3.2, will be removed in version 3.9.

array.fromunicode(s)

주어진 유니코드 문자열의 데이터로 이 배열을 확장합니다. 배열은 'u' 형의 배열이어야 합니다; 그렇지 않으면 ValueError가 발생합니다. 다른 형의 배열에 유니코드 데이터를 추가하려면 array.frombytes(unicodestring.encode(enc))를 사용하십시오.

array.index(x)

i가 배열에서 x가 처음 나타나는 인덱스가 되도록 가장 작은 i를 반환합니다.

array.insert(i, x)

i 위치 앞에 값이 x인 새 항목을 배열에 삽입합니다. 음수 값은 배열 끝에 상대적인 값으로 처리됩니다.

array.pop([i])

배열에서 인덱스 i에 있는 항목을 제거하고 이를 반환합니다. 선택적 인자의 기본값은 -1이므로, 기본적으로 마지막 항목이 제거되고 반환됩니다.

array.remove(x)

배열에서 첫 번째 x를 제거합니다.

array.reverse()

배열의 항목 순서를 뒤집습니다.

array.tobytes()

배열을 기곗값 배열로 변환하고 바이트열 표현(tofile() 메서드로 파일에 기록될 바이트 시퀀스와 같습니다)을 반환합니다.

버전 3.2에 추가: tostring()은 명확하게 하려고 tobytes()로 이름을 바꿨습니다.

array.tofile(f)

모든 항목을 (기곗값으로) 파일 객체 f에 씁니다.

array.tolist()

배열을 같은 항목이 있는 일반 리스트로 변환합니다.

array.tostring()

tobytes()의 폐지된 별칭.

Deprecated since version 3.2, will be removed in version 3.9.

array.tounicode()

배열을 유니코드 문자열로 변환합니다. 배열은 'u' 형의 배열이어야 합니다; 그렇지 않으면 ValueError가 발생합니다. 다른 형의 배열로부터 유니코드 문자열을 얻으려면 array.tobytes().decode(enc)를 사용하십시오.

배열 객체가 인쇄되거나 문자열로 변환될 때, array(typecode, initializer)로 표현됩니다. 배열이 비어 있으면 initializer가 생략되고, 그렇지 않으면 typecode가 'u' 인 경우 문자열이 되고, 그렇지 않으면 숫자 리스트가 됩니다. 문자열은 eval()을 사용하여 같은 형과 값을 갖는 배열로 다시 변환될 수 있음이 보장됩니다. 단 from array import array를 사용하여 array 클래스를 임포트 한다고 가정합니다. 예:

array('l')
array('u', 'hello \u2641')
array('l', [1, 2, 3, 4, 5])
array('d', [1.0, 2.0, 3.14])

더 보기

모듈 struct

이질적인(heterogeneous) 바이너리 데이터의 패킹과 언 패킹.

모듈 xdrlib

일부 원격 프로시저 호출 시스템에서 사용되는 XDR(External Data Representation) 데이터의 패킹과 언 패킹.

The Numerical Python Documentation [https://docs.scipy.org/doc/]

Numeric Python 확장(NumPy)은 다른 배열형을 정의합니다; Numerical Python에 대한 더 자세한 정보는 http://www.numpy.org/ 를 참조하십시오.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

데이터형 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

데이터형 »

|

weakref — Weak references

Source code: Lib/weakref.py [https://github.com/python/cpython/tree/3.7/Lib/weakref.py]

The weakref module allows the Python programmer to create weak references to objects.

In the following, the term referent means the object which is referred to by a weak reference.

A weak reference to an object is not enough to keep the object alive: when the only remaining references to a referent are weak references, garbage collection is free to destroy the referent and reuse its memory for something else. However, until the object is actually destroyed the weak reference may return the object even if there are no strong references to it.

A primary use for weak references is to implement caches or mappings holding large objects, where it’s desired that a large object not be kept alive solely because it appears in a cache or mapping.

For example, if you have a number of large binary image objects, you may wish to associate a name with each. If you used a Python dictionary to map names to images, or images to names, the image objects would remain alive just because they appeared as values or keys in the dictionaries. The WeakKeyDictionary and WeakValueDictionary classes supplied by the weakref module are an alternative, using weak references to construct mappings that don’t keep objects alive solely because they appear in the mapping objects. If, for example, an image object is a value in a WeakValueDictionary, then when the last remaining references to that image object are the weak references held by weak mappings, garbage collection can reclaim the object, and its corresponding entries in weak mappings are simply deleted.

WeakKeyDictionary and WeakValueDictionary use weak references in their implementation, setting up callback functions on the weak references that notify the weak dictionaries when a key or value has been reclaimed by garbage collection. WeakSet implements the set interface, but keeps weak references to its elements, just like a WeakKeyDictionary does.

finalize provides a straight forward way to register a cleanup function to be called when an object is garbage collected. This is simpler to use than setting up a callback function on a raw weak reference, since the module automatically ensures that the finalizer remains alive until the object is collected.

Most programs should find that using one of these weak container types or finalize is all they need – it’s not usually necessary to create your own weak references directly. The low-level machinery is exposed by the weakref module for the benefit of advanced uses.

Not all objects can be weakly referenced; those objects which can include class instances, functions written in Python (but not in C), instance methods, sets, frozensets, some file objects, generators, type objects, sockets, arrays, deques, regular expression pattern objects, and code objects.

버전 3.2에서 변경: Added support for thread.lock, threading.Lock, and code objects.

Several built-in types such as list and dict do not directly support weak references but can add support through subclassing:

class Dict(dict):
    pass

obj = Dict(red=1, green=2, blue=3)   # this object is weak referenceable

CPython implementation detail: Other built-in types such as tuple and int do not support weak references even when subclassed.

Extension types can easily be made to support weak references; see Weak Reference Support.

class weakref.ref(object[, callback])

Return a weak reference to object. The original object can be retrieved by calling the reference object if the referent is still alive; if the referent is no longer alive, calling the reference object will cause None to be returned. If callback is provided and not None, and the returned weakref object is still alive, the callback will be called when the object is about to be finalized; the weak reference object will be passed as the only parameter to the callback; the referent will no longer be available.

It is allowable for many weak references to be constructed for the same object. Callbacks registered for each weak reference will be called from the most recently registered callback to the oldest registered callback.

Exceptions raised by the callback will be noted on the standard error output, but cannot be propagated; they are handled in exactly the same way as exceptions raised from an object’s __del__() method.

Weak references are hashable if the object is hashable. They will maintain their hash value even after the object was deleted. If hash() is called the first time only after the object was deleted, the call will raise TypeError.

Weak references support tests for equality, but not ordering. If the referents are still alive, two references have the same equality relationship as their referents (regardless of the callback). If either referent has been deleted, the references are equal only if the reference objects are the same object.

This is a subclassable type rather than a factory function.

__callback__

This read-only attribute returns the callback currently associated to the weakref. If there is no callback or if the referent of the weakref is no longer alive then this attribute will have value None.

버전 3.4에서 변경: Added the __callback__ attribute.

weakref.proxy(object[, callback])

Return a proxy to object which uses a weak reference. This supports use of the proxy in most contexts instead of requiring the explicit dereferencing used with weak reference objects. The returned object will have a type of either ProxyType or CallableProxyType, depending on whether object is callable. Proxy objects are not hashable regardless of the referent; this avoids a number of problems related to their fundamentally mutable nature, and prevent their use as dictionary keys. callback is the same as the parameter of the same name to the ref() function.

weakref.getweakrefcount(object)

Return the number of weak references and proxies which refer to object.

weakref.getweakrefs(object)

Return a list of all weak reference and proxy objects which refer to object.

class weakref.WeakKeyDictionary([dict])

Mapping class that references keys weakly. Entries in the dictionary will be discarded when there is no longer a strong reference to the key. This can be used to associate additional data with an object owned by other parts of an application without adding attributes to those objects. This can be especially useful with objects that override attribute accesses.

WeakKeyDictionary objects have an additional method that exposes the internal references directly. The references are not guaranteed to be “live” at the time they are used, so the result of calling the references needs to be checked before being used. This can be used to avoid creating references that will cause the garbage collector to keep the keys around longer than needed.

WeakKeyDictionary.keyrefs()

Return an iterable of the weak references to the keys.

class weakref.WeakValueDictionary([dict])

Mapping class that references values weakly. Entries in the dictionary will be discarded when no strong reference to the value exists any more.

WeakValueDictionary objects have an additional method that has the same issues as the keyrefs() method of WeakKeyDictionary objects.

WeakValueDictionary.valuerefs()

Return an iterable of the weak references to the values.

class weakref.WeakSet([elements])

Set class that keeps weak references to its elements. An element will be discarded when no strong reference to it exists any more.

class weakref.WeakMethod(method)

A custom ref subclass which simulates a weak reference to a bound method (i.e., a method defined on a class and looked up on an instance). Since a bound method is ephemeral, a standard weak reference cannot keep hold of it. WeakMethod has special code to recreate the bound method until either the object or the original function dies:

>>> class C:
...     def method(self):
...         print("method called!")
...
>>> c = C()
>>> r = weakref.ref(c.method)
>>> r()
>>> r = weakref.WeakMethod(c.method)
>>> r()
<bound method C.method of <__main__.C object at 0x7fc859830220>>
>>> r()()
method called!
>>> del c
>>> gc.collect()
0
>>> r()
>>>

버전 3.4에 추가.

class weakref.finalize(obj, func, *args, **kwargs)

Return a callable finalizer object which will be called when obj is garbage collected. Unlike an ordinary weak reference, a finalizer will always survive until the reference object is collected, greatly simplifying lifecycle management.

A finalizer is considered alive until it is called (either explicitly or at garbage collection), and after that it is dead. Calling a live finalizer returns the result of evaluating func(*arg, **kwargs), whereas calling a dead finalizer returns None.

Exceptions raised by finalizer callbacks during garbage collection will be shown on the standard error output, but cannot be propagated. They are handled in the same way as exceptions raised from an object’s __del__() method or a weak reference’s callback.

When the program exits, each remaining live finalizer is called unless its atexit attribute has been set to false. They are called in reverse order of creation.

A finalizer will never invoke its callback during the later part of the interpreter shutdown when module globals are liable to have been replaced by None.

__call__()

If self is alive then mark it as dead and return the result of calling func(*args, **kwargs). If self is dead then return None.

detach()

If self is alive then mark it as dead and return the tuple (obj, func, args, kwargs). If self is dead then return None.

peek()

If self is alive then return the tuple (obj, func, args, kwargs). If self is dead then return None.

alive

Property which is true if the finalizer is alive, false otherwise.

atexit

A writable boolean property which by default is true. When the program exits, it calls all remaining live finalizers for which atexit is true. They are called in reverse order of creation.

참고

It is important to ensure that func, args and kwargs do not own any references to obj, either directly or indirectly, since otherwise obj will never be garbage collected. In particular, func should not be a bound method of obj.

버전 3.4에 추가.

weakref.ReferenceType

The type object for weak references objects.

weakref.ProxyType

The type object for proxies of objects which are not callable.

weakref.CallableProxyType

The type object for proxies of callable objects.

weakref.ProxyTypes

Sequence containing all the type objects for proxies. This can make it simpler to test if an object is a proxy without being dependent on naming both proxy types.

더 보기

PEP 205 [https://www.python.org/dev/peps/pep-0205] - Weak References

The proposal and rationale for this feature, including links to earlier implementations and information about similar features in other languages.

Weak Reference Objects

Weak reference objects have no methods and no attributes besides ref.__callback__. A weak reference object allows the referent to be obtained, if it still exists, by calling it:

>>> import weakref
>>> class Object:
...     pass
...
>>> o = Object()
>>> r = weakref.ref(o)
>>> o2 = r()
>>> o is o2
True

If the referent no longer exists, calling the reference object returns None:

>>> del o, o2
>>> print(r())
None

Testing that a weak reference object is still live should be done using the expression ref() is not None. Normally, application code that needs to use a reference object should follow this pattern:

# r is a weak reference object
o = r()
if o is None:
    # referent has been garbage collected
    print("Object has been deallocated; can't frobnicate.")
else:
    print("Object is still live!")
    o.do_something_useful()

Using a separate test for “liveness” creates race conditions in threaded applications; another thread can cause a weak reference to become invalidated before the weak reference is called; the idiom shown above is safe in threaded applications as well as single-threaded applications.

Specialized versions of ref objects can be created through subclassing. This is used in the implementation of the WeakValueDictionary to reduce the memory overhead for each entry in the mapping. This may be most useful to associate additional information with a reference, but could also be used to insert additional processing on calls to retrieve the referent.

This example shows how a subclass of ref can be used to store additional information about an object and affect the value that’s returned when the referent is accessed:

import weakref

class ExtendedRef(weakref.ref):
    def __init__(self, ob, callback=None, **annotations):
        super(ExtendedRef, self).__init__(ob, callback)
        self.__counter = 0
        for k, v in annotations.items():
            setattr(self, k, v)

    def __call__(self):
        """Return a pair containing the referent and the number of
        times the reference has been called.
        """
        ob = super(ExtendedRef, self).__call__()
        if ob is not None:
            self.__counter += 1
            ob = (ob, self.__counter)
        return ob

Example

This simple example shows how an application can use object IDs to retrieve objects that it has seen before. The IDs of the objects can then be used in other data structures without forcing the objects to remain alive, but the objects can still be retrieved by ID if they do.

import weakref

_id2obj_dict = weakref.WeakValueDictionary()

def remember(obj):
    oid = id(obj)
    _id2obj_dict[oid] = obj
    return oid

def id2obj(oid):
    return _id2obj_dict[oid]

Finalizer Objects

The main benefit of using finalize is that it makes it simple to register a callback without needing to preserve the returned finalizer object. For instance

>>> import weakref
>>> class Object:
...     pass
...
>>> kenny = Object()
>>> weakref.finalize(kenny, print, "You killed Kenny!")
<finalize object at ...; for 'Object' at ...>
>>> del kenny
You killed Kenny!

The finalizer can be called directly as well. However the finalizer will invoke the callback at most once.

>>> def callback(x, y, z):
...     print("CALLBACK")
...     return x + y + z
...
>>> obj = Object()
>>> f = weakref.finalize(obj, callback, 1, 2, z=3)
>>> assert f.alive
>>> assert f() == 6
CALLBACK
>>> assert not f.alive
>>> f()                     # callback not called because finalizer dead
>>> del obj                 # callback not called because finalizer dead

You can unregister a finalizer using its detach() method. This kills the finalizer and returns the arguments passed to the constructor when it was created.

>>> obj = Object()
>>> f = weakref.finalize(obj, callback, 1, 2, z=3)
>>> f.detach()
(<...Object object ...>, <function callback ...>, (1, 2), {'z': 3})
>>> newobj, func, args, kwargs = _
>>> assert not f.alive
>>> assert newobj is obj
>>> assert func(*args, **kwargs) == 6
CALLBACK

Unless you set the atexit attribute to False, a finalizer will be called when the program exits if it is still alive. For instance

>>> obj = Object()
>>> weakref.finalize(obj, print, "obj dead or exiting")
<finalize object at ...; for 'Object' at ...>
>>> exit()
obj dead or exiting

Comparing finalizers with __del__() methods

Suppose we want to create a class whose instances represent temporary directories. The directories should be deleted with their contents when the first of the following events occurs:

the object is garbage collected,

the object’s remove() method is called, or

the program exits.

We might try to implement the class using a __del__() method as follows:

class TempDir:
    def __init__(self):
        self.name = tempfile.mkdtemp()

    def remove(self):
        if self.name is not None:
            shutil.rmtree(self.name)
            self.name = None

    @property
    def removed(self):
        return self.name is None

    def __del__(self):
        self.remove()

Starting with Python 3.4, __del__() methods no longer prevent reference cycles from being garbage collected, and module globals are no longer forced to None during interpreter shutdown. So this code should work without any issues on CPython.

However, handling of __del__() methods is notoriously implementation specific, since it depends on internal details of the interpreter’s garbage collector implementation.

A more robust alternative can be to define a finalizer which only references the specific functions and objects that it needs, rather than having access to the full state of the object:

class TempDir:
    def __init__(self):
        self.name = tempfile.mkdtemp()
        self._finalizer = weakref.finalize(self, shutil.rmtree, self.name)

    def remove(self):
        self._finalizer()

    @property
    def removed(self):
        return not self._finalizer.alive

Defined like this, our finalizer only receives a reference to the details it needs to clean up the directory appropriately. If the object never gets garbage collected the finalizer will still be called at exit.

The other advantage of weakref based finalizers is that they can be used to register finalizers for classes where the definition is controlled by a third party, such as running code when a module is unloaded:

import weakref, sys
def unloading_module():
    # implicit reference to the module globals from the function body
weakref.finalize(sys.modules[__name__], unloading_module)

참고

If you create a finalizer object in a daemonic thread just as the program exits then there is the possibility that the finalizer does not get called at exit. However, in a daemonic thread atexit.register(), try: ... finally: ... and with: ... do not guarantee that cleanup occurs either.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

데이터형 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

데이터형 »

|

types — 동적 형 생성과 내장형 이름

소스 코드: Lib/types.py [https://github.com/python/cpython/tree/3.7/Lib/types.py]

이 모듈은 새로운 형의 동적 생성을 지원하는 유틸리티 함수를 정의합니다.

표준 파이썬 인터프리터가 사용하지만, int나 str처럼 내장으로 노출되지 않는 일부 객체 형의 이름도 정의합니다.

마지막으로, 내장되기에 충분히 기본적이지 않은 몇 가지 추가 형 관련 유틸리티 클래스와 함수를 제공합니다.

동적 형 생성

types.new_class(name, bases=(), kwds=None, exec_body=None)

적절한 메타 클래스를 사용하여 동적으로 클래스 객체를 만듭니다.

처음 세 개의 인자는 클래스 정의 헤더를 구성하는 요소들입니다: 클래스 이름, 베이스 클래스 (순서대로), 키워드 인자 (가령 metaclass).

exec_body 인자는 새로 만들어진 클래스 이름 공간을 채우는 데 사용되는 콜백입니다. 클래스 이름 공간을 유일한 인자로 받아들이고 클래스 내용으로 이름 공간을 직접 갱신해야 합니다. 콜백이 제공되지 않으면, lambda ns: ns를 전달하는 것과 같은 효과가 있습니다.

버전 3.3에 추가.

types.prepare_class(name, bases=(), kwds=None)

적절한 메타 클래스를 계산하고 클래스 이름 공간을 만듭니다.

인자는 클래스 정의 헤더를 구성하는 요소들입니다: 클래스 이름, 베이스 클래스 (순서대로) 및 키워드 인자 (가령 metaclass).

반환 값은 3-튜플입니다: metaclass, namespace, kwds

metaclass는 적절한 메타 클래스이고, namespace는 준비된 클래스 이름 공간이며 kwds는 'metaclass' 항목이 제거된 전달된 kwds 인자의 갱신된 사본입니다. kwds 인자가 전달되지 않으면, 빈 딕셔너리가 됩니다.

버전 3.3에 추가.

버전 3.6에서 변경: 반환된 튜플의 namespace 요소의 기본값이 변경되었습니다. 이제 메타 클래스에 __prepare__ 메서드가 없으면 삽입 순서 보존 맵핑이 사용됩니다.

더 보기

메타 클래스

이 함수들이 지원하는 클래스 생성 절차에 대한 자세한 내용

PEP 3115 [https://www.python.org/dev/peps/pep-3115] - 파이썬 3000의 메타 클래스

__prepare__ 이름 공간 훅을 도입했습니다

types.resolve_bases(bases)

PEP 560 [https://www.python.org/dev/peps/pep-0560]의 명세에 따라 MRO 항목을 동적으로 결정합니다.

이 함수는 type의 인스턴스가 아닌 항목들을 bases에서 찾고, __mro_entries__ 메서드가 있는 각 객체가 이 메서드 호출의 언패킹 된 결과로 대체된 튜플을 반환합니다. bases 항목이 type의 인스턴스이거나, __mro_entries__ 메서드가 없으면, 반환 튜플에 변경되지 않은 상태로 포함됩니다.

버전 3.7에 추가.

더 보기

PEP 560 [https://www.python.org/dev/peps/pep-0560] - typing 모듈과 제네릭 형에 대한 코어 지원

표준 인터프리터 형

이 모듈은 파이썬 인터프리터를 구현하는 데 필요한 많은 형의 이름을 제공합니다. listiterator 형과 같이 처리 중에 우연히 발생하는 일부 형은 의도적으로 포함하지 않았습니다.

이러한 이름의 일반적인 용도는 isinstance()나 issubclass() 검사입니다.

다음과 같은 형들에 대해 표준 이름이 정의됩니다:

types.FunctionType

types.LambdaType

사용자 정의 함수와 lambda 표현식이 만든 함수의 형.

types.GeneratorType

제너레이터 함수가 만든, 제너레이터-이터레이터 객체의 형.

types.CoroutineType

async def 함수가 만든 코루틴 객체의 형.

버전 3.5에 추가.

types.AsyncGeneratorType

비동기 제너레이터 함수가 만든, 비동기 제너레이터-이터레이터 객체의 형.

버전 3.6에 추가.

types.CodeType

compile()이 반환하는 것과 같은 코드 객체의 형.

types.MethodType

사용자 정의 클래스 인스턴스의 메서드 형.

types.BuiltinFunctionType

types.BuiltinMethodType

len()이나 sys.exit() 와 같은 내장 함수와 내장 클래스의 메서드의 형. (여기서, “내장”이라는 용어는 “C로 작성된”을 의미합니다.)

types.WrapperDescriptorType

object.__init__()나 object.__lt__()와 같은, 일부 내장 데이터형과 베이스 클래스의 메서드의 형.

버전 3.7에 추가.

types.MethodWrapperType

일부 내장 데이터형과 베이스 클래스의 연결된(bound) 메서드의 형. 예를 들어 object().__str__의 형입니다.

버전 3.7에 추가.

types.MethodDescriptorType

str.join()과 같은 일부 내장 데이터형의 메서드의 형.

버전 3.7에 추가.

types.ClassMethodDescriptorType

dict.__dict__['fromkeys']와 같은 일부 내장 데이터형의 연결되지 않은(unbound) 클래스 메서드의 형.

버전 3.7에 추가.

class types.ModuleType(name, doc=None)

모듈의 형. 생성자는 만들 모듈의 이름과 선택적으로 독스트링을 취합니다.

참고

다양한 임포트 제어 어트리뷰트를 설정하려면 importlib.util.module_from_spec()을 사용하여 새 모듈을 만드십시오.

__doc__

모듈의 독스트링. 기본값은 None.

__loader__

모듈을 로드한 로더. 기본값은 None.

버전 3.4에서 변경: 기본값은 None. 이전에는 어트리뷰트가 선택적이었습니다.

__name__

모듈의 이름

__package__

모듈이 속한 패키지. 모듈이 최상위 수준이면 (즉, 특정 패키지의 일부가 아니면) 어트리뷰트를 ''로 설정해야 하며, 그렇지 않으면 패키지 이름으로 설정해야 합니다 (모듈이 패키지 자체이면 __name__ 일 수 있습니다). 기본값은 None.

버전 3.4에서 변경: 기본값은 None. 이전에는 어트리뷰트가 선택적이었습니다.

class types.TracebackType(tb_next, tb_frame, tb_lasti, tb_lineno)

sys.exc_info()[2]에서 발견되는 것과 같은 트레이스백 객체의 형.

사용 가능한 어트리뷰트와 연산에 대한 세부 사항 및 동적으로 트레이스백을 만드는 것에 대한 지침은 언어 레퍼런스를 참조하십시오.

types.FrameType

tb가 트레이스백 객체일 때 tb.tb_frame에서 발견되는 것과 같은 프레임 객체의 형.

사용 가능한 어트리뷰트와 연산에 대한 자세한 내용은 언어 레퍼런스를 참조하십시오.

types.GetSetDescriptorType

FrameType.f_locals나 array.array.typecode와 같은, PyGetSetDef가 있는 확장 모듈에서 정의된 객체의 형. 이 형은 객체 어트리뷰트에 대한 디스크립터로 사용됩니다. property 형과 같은 목적을 갖지만, 확장 모듈에 정의된 클래스에 사용됩니다.

types.MemberDescriptorType

datetime.timedelta.days와 같은, PyMemberDef가 있는 확장 모듈에서 정의된 객체의 형. 이 형은 표준 변환 함수를 사용하는 간단한 C 데이터 멤버의 디스크립터로 사용됩니다; property 형과 같은 목적을 갖지만, 확장 모듈에 정의된 클래스를 위한 것입니다.

CPython implementation detail: 파이썬의 다른 구현에서, 이 형은 GetSetDescriptorType과 같을 수 있습니다.

class types.MappingProxyType(mapping)

매핑의 읽기 전용 프락시. 매핑 항목에 대한 동적 뷰를 제공하는데, 매핑이 변경될 때 뷰가 이러한 변경 사항을 반영함을 의미합니다.

버전 3.3에 추가.

key in proxy

하부 매핑에 키 key가 있으면 True를, 그렇지 않으면 False를 반환합니다.

proxy[key]

키 key를 사용하여 하부 매핑의 항목을 반환합니다. key가 하부 매핑에 없으면 KeyError를 발생시킵니다.

iter(proxy)

하부 매핑의 키에 대한 이터레이터를 반환합니다. 이것은 iter(proxy.keys())의 줄임 표현입니다.

len(proxy)

하부 매핑의 항목 수를 반환합니다.

copy()

하부 매핑의 얕은 사본을 반환합니다.

get(key[, default])

key가 하부 매핑에 있으면 key의 값을, 그렇지 않으면 default를 반환합니다. default를 지정하지 않으면, 기본적으로 None으로 설정되므로, 이 메서드는 절대 KeyError를 발생시키지 않습니다.

items()

하부 매핑의 항목(items)((key, value) 쌍)의 새 뷰를 반환합니다.

keys()

하부 매핑의 키(keys)의 새로운 뷰를 반환합니다.

values()

하부 매핑의 값(values)의 새 뷰를 반환합니다.

추가 유틸리티 클래스와 함수

class types.SimpleNamespace

이름 공간에 대한 어트리뷰트 액세스와 의미 있는 repr을 제공하는 간단한 object 서브 클래스.

object와 달리, SimpleNamespace를 사용하면 어트리뷰트를 추가하고 제거할 수 있습니다. SimpleNamespace 객체가 키워드 인자로 초기화되면, 하부 이름 공간에 직접 추가됩니다.

형은 다음 코드와 대략 동등합니다:

class SimpleNamespace:
    def __init__(self, **kwargs):
        self.__dict__.update(kwargs)

    def __repr__(self):
        keys = sorted(self.__dict__)
        items = ("{}={!r}".format(k, self.__dict__[k]) for k in keys)
        return "{}({})".format(type(self).__name__, ", ".join(items))

    def __eq__(self, other):
        return self.__dict__ == other.__dict__

SimpleNamespace는 class NS: pass의 대체품으로 유용할 수 있습니다. 하지만, 구조화된 레코드형에는 namedtuple()을 대신 사용하십시오.

버전 3.3에 추가.

types.DynamicClassAttribute(fget=None, fset=None, fdel=None, doc=None)

클래스의 어트리뷰트 액세스를 __getattr__ 로 보냅니다.

디스크립터이며, 인스턴스와 클래스를 통해 액세스할 때 다르게 작동하는 어트리뷰트를 정의하는 데 사용됩니다. 인스턴스 액세스는 정상적으로 유지되지만, 클래스를 통한 어트리뷰트 액세스는 클래스의 __getattr__ 메서드로 보냅니다; 이는 AttributeError를 발생 시켜 수행됩니다.

이를 통해 인스턴스에서 활성화된 프로퍼티를 가짐과 동시에, 클래스에서 같은 이름을 가진 가상 어트리뷰트를 가질 수 있습니다 (예제는 Enum을 참조하십시오).

버전 3.4에 추가.

코루틴 유틸리티 함수

types.coroutine(gen_func)

이 함수는 제너레이터 함수를 제너레이터 기반 코루틴을 반환하는 코루틴 함수로 변환합니다. 제너레이터 기반 코루틴은 여전히 제너레이터 이터레이터이지만, 코루틴 객체로도 간주하며 어웨이터블입니다. 그러나, 반드시 __await__() 메서드를 구현할 필요는 없습니다.

gen_func가 제너레이터 함수면 제자리(in-place)에서 수정됩니다.

gen_func가 제너레이터 함수가 아니면, 래핑 됩니다. collections.abc.Generator의 인스턴스를 반환하면, 인스턴스는 어웨이터블 프락시 객체로 래핑 됩니다. 다른 모든 형의 객체는 그대로 반환됩니다.

버전 3.5에 추가.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

데이터형 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

데이터형 »

|

copy — 얕은 복사와 깊은 복사 연산

소스 코드: Lib/copy.py [https://github.com/python/cpython/tree/3.7/Lib/copy.py]

파이썬에서 대입문은 객체를 복사하지 않고, 대상과 객체 사이에 바인딩을 만듭니다.가변(mutable) 컬렉션 또는 가변(mutable) 항목들을 포함한 컬렉션의 경우때로 컬렉션을 변경하지 않고 사본을 변경하기 위해 복사가 필요합니다.이 모듈은 일반적인 얕은 복사와 깊은 복사 연산을 제공합니다. (아래 설명 참고)

인터페이스 요약:

copy.copy(x)

x의 얕은 사본을 반환합니다.

copy.deepcopy(x[, memo])

x의 깊은 사본을 반환합니다.

exception copy.error

모듈 특정 에러의 경우 발생됩니다.

얕은 복사와 깊은 복사의 차이점은복합 객체(리스트 또는 클래스 인스턴스들과 같은 다른 객체를 포함한 객체)에만 유효합니다.

얕은 복사는 새로운 복합 객체를 만들고,(가능한 범위까지) 원본 객체를 가리키는 참조를 새로운 복합 객체에 삽입합니다.

깊은 복사는 새로운 복합 객체를 만들고,재귀적으로 원본 객체의 사본을 새로 만든 복합 객체에 삽입합니다.

깊은 복사 연산은 얕은 복사 연산에는 없는 두 가지 문제가 있습니다:

재귀 객체(직접적 또는 간접적으로 자신에 대한 참조를 포함하는 복합 객체)는 순환 루프의 원인이 될 수 있습니다.

깊은 복사는 모든 것을 복사하기 때문에, 지나치게 많이 복사할 수 있습니다. 가령, 복사본 간에 공유할 의도가 있는 것까지도.

deepcopy() 함수는 다음과 같은 방법으로 이 문제들을 피합니다:

현재 복사 패스 중에 이미 복사된 객체의 memo 딕셔너리를 가지고 있습니다; 그리고

사용자 정의 클래스가 복사 연산 또는 복사된 구성요소 집합을 재정의하도록 합니다.

이 모듈은 모듈, 메서드, 스택 트레이스, 스택 프레임, 파일, 소켓, 윈도우, 배열과 같은 유형들은 복사하지 않습니다.원래 객체를 변화시키지 않고 반환함으로써 함수와 클래스를 (얕고 깊게) “복사” 합니다;이것은 pickle 모듈로 처리되는 방식과 호환됩니다.

딕셔너리의 얕은 복사는 dict.copy()를 사용하여 복사할 수 있습니다.그리고 리스트의 얕은 복사는 예를 들어 copied_list = original_list[:] 처럼전체 리스트의 슬라이스를 대입하여 리스트를 복사할 수도 있습니다.

클래스는 피클링을 제어하기 위해 사용하는 것과 같은 인터페이스를 사용하여 복사를 제어할 수 있습니다.이러한 메서드들의 정보는 pickle 모듈 설명을 참고하세요.실제로 copy 모듈은 copyreg 모듈에 등록된 피클 함수를 사용합니다.

클래스가 자체적으로 복사 구현을 정의하기 위해선, __copy__() 와 __deepcopy__() 같은 특수 메서드를 정의할 수 있습니다.전자는 얕은 복사 연산을 실행하기 위해 호출됩니다; 추가적인 인자를 전달 하지 않습니다.후자는 깊은 복사 연산을 실행하기 위해 호출됩니다; memo 딕셔너리가 하나의 인자로 전달됩니다. __deepcopy__() 구현에서 구성요소의 깊은 복사를 만들기 위해선,구성요소를 첫 번째 인자로 하고 memo 딕셔너리를 두 번째 인자로 하여 deepcopy() 함수를 호출해야 합니다.

더 보기

모듈 pickle

객체 상태 조회와 복원을 지원하는데 사용되는 특수 메서드에 관한 논의

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

데이터형 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

데이터형 »

|

pprint — 예쁜 데이터 인쇄기

소스 코드: Lib/pprint.py [https://github.com/python/cpython/tree/3.7/Lib/pprint.py]

pprint 모듈은 임의의 파이썬 데이터 구조를 인터프리터의 입력으로 사용할 수 있는 형태로 “예쁘게 인쇄”할 수 있는 기능을 제공합니다. 포맷된 구조에 기본 파이썬 형이 아닌 객체가 포함되면, 표현은 로드되지 않을 수 있습니다. 파일, 소켓 또는 클래스와 같은 객체뿐만 아니라 파이썬 리터럴로 표현할 수 없는 다른 많은 객체가 포함된 경우입니다.

포맷된 표현은 할 수 있다면 객체를 한 줄에 유지하고, 허용된 너비에 맞지 않으면 여러 줄로 나눕니다. 너비 제한을 조정해야 하면 PrettyPrinter 객체를 명시적으로 만드십시오.

딕셔너리는 디스플레이를 계산하기 전에 키로 정렬됩니다.

pprint 모듈은 하나의 클래스를 정의합니다:

class pprint.PrettyPrinter(indent=1, width=80, depth=None, stream=None, *, compact=False)

PrettyPrinter 인스턴스를 만듭니다. 이 생성자는 여러 키워드 매개 변수를 인식합니다. 출력 스트림은 stream 키워드를 사용하여 설정할 수 있습니다; 스트림 객체에서 사용되는 유일한 메서드는 파일 프로토콜의 write() 메서드입니다. 지정하지 않으면, PrettyPrinter는 sys.stdout을 사용합니다. 각 재귀 수준에 대해 들여쓰기하는 양은 indent로 지정합니다; 기본값은 1입니다. 다른 값은 출력이 약간 이상하게 보일 수 있지만, 중첩을 쉽게 알아낼 수 있습니다. 인쇄될 수 있는 수준의 수는 depth로 제어합니다; 인쇄 중인 데이터 구조가 너무 깊으면, 다음에 포함된 수준은 ...로 대체됩니다. 기본적으로, 포맷되는 객체의 깊이에는 제한이 없습니다. 원하는 출력 폭은 width 매개 변수를 사용하여 제한합니다; 기본값은 80자입니다. 제한된 너비 내에서 구조를 포맷할 수 없으면, 최선의 노력을 기울입니다. compact가 거짓(기본값)이면, 긴 시퀀스의 각 항목이 별도의 줄로 포맷됩니다. compact가 참이면 width 내에 들어갈 수 있는 최대한 많은 항목을 각 출력할 줄에 포맷합니다.

버전 3.4에서 변경: compact 매개 변수가 추가되었습니다.

>>> import pprint
>>> stuff = ['spam', 'eggs', 'lumberjack', 'knights', 'ni']
>>> stuff.insert(0, stuff[:])
>>> pp = pprint.PrettyPrinter(indent=4)
>>> pp.pprint(stuff)
[   ['spam', 'eggs', 'lumberjack', 'knights', 'ni'],
    'spam',
    'eggs',
    'lumberjack',
    'knights',
    'ni']
>>> pp = pprint.PrettyPrinter(width=41, compact=True)
>>> pp.pprint(stuff)
[['spam', 'eggs', 'lumberjack',
  'knights', 'ni'],
 'spam', 'eggs', 'lumberjack', 'knights',
 'ni']
>>> tup = ('spam', ('eggs', ('lumberjack', ('knights', ('ni', ('dead',
... ('parrot', ('fresh fruit',))))))))
>>> pp = pprint.PrettyPrinter(depth=6)
>>> pp.pprint(tup)
('spam', ('eggs', ('lumberjack', ('knights', ('ni', ('dead', (...)))))))

pprint 모듈은 몇 가지 단축 함수도 제공합니다:

pprint.pformat(object, indent=1, width=80, depth=None, *, compact=False)

object의 포맷된 표현을 문자열로 반환합니다. indent, width, depth 및 compact는 포매팅 매개 변수로 PrettyPrinter 생성자에 전달됩니다.

버전 3.4에서 변경: compact 매개 변수가 추가되었습니다.

pprint.pprint(object, stream=None, indent=1, width=80, depth=None, *, compact=False)

object의 포맷된 표현에 줄 바꿈을 추가해서 stream에 인쇄합니다. stream이 None이면, sys.stdout이 사용됩니다. 이것은 print() 함수 대신 대화형 인터프리터에서 값을 검사하는 데 사용할 수 있습니다 (스코프 내에서 사용하기 위해 print = pprint.pprint를 다시 대입할 수도 있습니다). indent, width, depth 및 compact는 포매팅 매개 변수로 PrettyPrinter 생성자에 전달됩니다.

버전 3.4에서 변경: compact 매개 변수가 추가되었습니다.

>>> import pprint
>>> stuff = ['spam', 'eggs', 'lumberjack', 'knights', 'ni']
>>> stuff.insert(0, stuff)
>>> pprint.pprint(stuff)
[<Recursion on list with id=...>,
 'spam',
 'eggs',
 'lumberjack',
 'knights',
 'ni']

pprint.isreadable(object)

Determine if the formatted representation of object is “readable”, or can be used to reconstruct the value using eval(). This always returns False for recursive objects.

>>> pprint.isreadable(stuff)
False

pprint.isrecursive(object)

object가 재귀적 표현을 요구하는지 판단합니다.

또 하나의 지원 함수가 정의됩니다:

pprint.saferepr(object)

재귀적 데이터 구조에 대해 보호되는, object의 문자열 표현을 반환합니다. object의 표현이 재귀적 항목을 노출하면, 재귀적 참조는 <Recursion on typename with id=number>로 표시됩니다. 표현에는 이외의 다른 포매팅이 적용되지 않습니다.

>>> pprint.saferepr(stuff)
"[<Recursion on list with id=...>, 'spam', 'eggs', 'lumberjack', 'knights', 'ni']"

PrettyPrinter 객체

PrettyPrinter 인스턴스에는 다음과 같은 메서드가 있습니다:

PrettyPrinter.pformat(object)

object의 포맷된 표현을 반환합니다. PrettyPrinter 생성자에 전달된 옵션을 고려합니다.

PrettyPrinter.pprint(object)

구성된 스트림에 object의 포맷된 표현과 불 넘김을 인쇄합니다.

다음 메서드는 같은 이름의 해당 함수에 대한 구현을 제공합니다. 새로운 PrettyPrinter 객체를 만들 필요가 없으므로, 인스턴스에서 이러한 메서드를 사용하는 것이 약간 더 효율적입니다.

PrettyPrinter.isreadable(object)

object의 포맷된 표현이 “읽을 수 있는”지, 즉 eval()을 사용하여 값을 재구성하는 데 사용할 수 있는지 판단합니다. 재귀 객체에 대해 False를 반환함에 유의하십시오. PrettyPrinter의 depth 매개 변수가 설정되고 객체가 허용된 것보다 더 깊으면, False를 반환합니다.

PrettyPrinter.isrecursive(object)

object가 재귀적 표현을 요구하는지 판단합니다.

이 메서드는 서브 클래스가 객체가 문자열로 변환되는 방식을 수정할 수 있도록 하는 훅으로 제공됩니다. 기본 구현은 saferepr() 구현의 내부를 사용합니다.

PrettyPrinter.format(object, context, maxlevels, level)

세 가지 값을 반환합니다: 포맷된 버전의 object를 문자열로, 결과가 읽을 수 있는지를 나타내는 플래그와 재귀가 감지되었는지를 나타내는 플래그. 첫 번째 인자는 표시할 객체입니다. 두 번째는 현재 표현 컨텍스트(표현에 영향을 주는 object의 직접 및 간접 컨테이너)의 일부인 객체의 id()를 키로 포함하는 딕셔너리입니다; 이미 context에 표현된 객체가 표현되어야 할 필요가 있으면, 세 번째 반환 값은 True이어야 합니다. format() 메서드에 대한 재귀 호출은 컨테이너에 대한 추가 항목을 이 딕셔너리에 추가해야 합니다. 세 번째 인자 maxlevels는 재귀에 요청된 제한을 줍니다; 요청된 제한이 없으면 0입니다. 이 인자는 재귀 호출에 수정되지 않은 채 전달되어야 합니다. 네 번째 인자 level은 현재 수준을 제공합니다; 재귀 호출은 현재 호출보다 작은 값으로 전달되어야 합니다.

예제

pprint() 함수와 매개 변수의 여러 용도를 예시하기 위해, PyPI [https://pypi.org]에서 프로젝트에 대한 정보를 가져옵시다:

>>> import json
>>> import pprint
>>> from urllib.request import urlopen
>>> with urlopen('https://pypi.org/pypi/sampleproject/json') as resp:
...     project_info = json.load(resp)['info']

기본적인 형태에서, pprint()는 전체 객체를 보여줍니다:

>>> pprint.pprint(project_info)
{'author': 'The Python Packaging Authority',
 'author_email': 'pypa-dev@googlegroups.com',
 'bugtrack_url': None,
 'classifiers': ['Development Status :: 3 - Alpha',
                 'Intended Audience :: Developers',
                 'License :: OSI Approved :: MIT License',
                 'Programming Language :: Python :: 2',
                 'Programming Language :: Python :: 2.6',
                 'Programming Language :: Python :: 2.7',
                 'Programming Language :: Python :: 3',
                 'Programming Language :: Python :: 3.2',
                 'Programming Language :: Python :: 3.3',
                 'Programming Language :: Python :: 3.4',
                 'Topic :: Software Development :: Build Tools'],
 'description': 'A sample Python project\n'
                '=======================\n'
                '\n'
                'This is the description file for the project.\n'
                '\n'
                'The file should use UTF-8 encoding and be written using '
                'ReStructured Text. It\n'
                'will be used to generate the project webpage on PyPI, and '
                'should be written for\n'
                'that purpose.\n'
                '\n'
                'Typical contents for this file would include an overview of '
                'the project, basic\n'
                'usage examples, etc. Generally, including the project '
                'changelog in here is not\n'
                'a good idea, although a simple "What\'s New" section for the '
                'most recent version\n'
                'may be appropriate.',
 'description_content_type': None,
 'docs_url': None,
 'download_url': 'UNKNOWN',
 'downloads': {'last_day': -1, 'last_month': -1, 'last_week': -1},
 'home_page': 'https://github.com/pypa/sampleproject',
 'keywords': 'sample setuptools development',
 'license': 'MIT',
 'maintainer': None,
 'maintainer_email': None,
 'name': 'sampleproject',
 'package_url': 'https://pypi.org/project/sampleproject/',
 'platform': 'UNKNOWN',
 'project_url': 'https://pypi.org/project/sampleproject/',
 'project_urls': {'Download': 'UNKNOWN',
                  'Homepage': 'https://github.com/pypa/sampleproject'},
 'release_url': 'https://pypi.org/project/sampleproject/1.2.0/',
 'requires_dist': None,
 'requires_python': None,
 'summary': 'A sample Python project',
 'version': '1.2.0'}

결과는 특정 depth로 제한될 수 있습니다 (더 깊은 내용에는 줄임표가 사용됩니다):

>>> pprint.pprint(project_info, depth=1)
{'author': 'The Python Packaging Authority',
 'author_email': 'pypa-dev@googlegroups.com',
 'bugtrack_url': None,
 'classifiers': [...],
 'description': 'A sample Python project\n'
                '=======================\n'
                '\n'
                'This is the description file for the project.\n'
                '\n'
                'The file should use UTF-8 encoding and be written using '
                'ReStructured Text. It\n'
                'will be used to generate the project webpage on PyPI, and '
                'should be written for\n'
                'that purpose.\n'
                '\n'
                'Typical contents for this file would include an overview of '
                'the project, basic\n'
                'usage examples, etc. Generally, including the project '
                'changelog in here is not\n'
                'a good idea, although a simple "What\'s New" section for the '
                'most recent version\n'
                'may be appropriate.',
 'description_content_type': None,
 'docs_url': None,
 'download_url': 'UNKNOWN',
 'downloads': {...},
 'home_page': 'https://github.com/pypa/sampleproject',
 'keywords': 'sample setuptools development',
 'license': 'MIT',
 'maintainer': None,
 'maintainer_email': None,
 'name': 'sampleproject',
 'package_url': 'https://pypi.org/project/sampleproject/',
 'platform': 'UNKNOWN',
 'project_url': 'https://pypi.org/project/sampleproject/',
 'project_urls': {...},
 'release_url': 'https://pypi.org/project/sampleproject/1.2.0/',
 'requires_dist': None,
 'requires_python': None,
 'summary': 'A sample Python project',
 'version': '1.2.0'}

또한, 최대 문자 width를 제안할 수 있습니다. 긴 객체를 분할 할 수 없으면, 지정된 너비를 초과합니다:

>>> pprint.pprint(project_info, depth=1, width=60)
{'author': 'The Python Packaging Authority',
 'author_email': 'pypa-dev@googlegroups.com',
 'bugtrack_url': None,
 'classifiers': [...],
 'description': 'A sample Python project\n'
                '=======================\n'
                '\n'
                'This is the description file for the '
                'project.\n'
                '\n'
                'The file should use UTF-8 encoding and be '
                'written using ReStructured Text. It\n'
                'will be used to generate the project '
                'webpage on PyPI, and should be written '
                'for\n'
                'that purpose.\n'
                '\n'
                'Typical contents for this file would '
                'include an overview of the project, '
                'basic\n'
                'usage examples, etc. Generally, including '
                'the project changelog in here is not\n'
                'a good idea, although a simple "What\'s '
                'New" section for the most recent version\n'
                'may be appropriate.',
 'description_content_type': None,
 'docs_url': None,
 'download_url': 'UNKNOWN',
 'downloads': {...},
 'home_page': 'https://github.com/pypa/sampleproject',
 'keywords': 'sample setuptools development',
 'license': 'MIT',
 'maintainer': None,
 'maintainer_email': None,
 'name': 'sampleproject',
 'package_url': 'https://pypi.org/project/sampleproject/',
 'platform': 'UNKNOWN',
 'project_url': 'https://pypi.org/project/sampleproject/',
 'project_urls': {...},
 'release_url': 'https://pypi.org/project/sampleproject/1.2.0/',
 'requires_dist': None,
 'requires_python': None,
 'summary': 'A sample Python project',
 'version': '1.2.0'}

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

데이터형 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

데이터형 »

|

reprlib — 대안 repr() 구현

소스 코드: Lib/reprlib.py [https://github.com/python/cpython/tree/3.7/Lib/reprlib.py]

reprlib 모듈은 결과 문자열의 크기에 제한이 있는 객체 표현을 생성하는 수단을 제공합니다. 파이썬 디버거에서 사용되며 다른 문맥에서도 유용할 수 있습니다.

이 모듈은 클래스, 인스턴스 및 함수를 제공합니다.:

class reprlib.Repr

내장 repr()과 유사한 함수를 구현하는 데 유용한 포매팅 서비스를 제공하는 클래스; 과도하게 긴 표현의 생성을 피하고자 객체 형별로 크기 제한이 추가됩니다.

reprlib.aRepr

아래에 설명된 repr()로 함수를 제공하는 데 사용되는 Repr의 인스턴스입니다. 이 객체의 어트리뷰트를 변경하면 repr()과 파이썬 디버거에서 사용되는 크기 제한에 영향을 줍니다.

reprlib.repr(obj)

aRepr의 repr() 메서드입니다. 같은 이름의 내장 함수에 의해 반환된 것과 비슷한 문자열을 반환하지만, 대부분의 크기에는 제한이 있습니다.

크기 제한 도구 외에도, 모듈은 __repr__()에 대한 재귀 호출을 감지하고 대신 자리 표시자 문자열을 치환하는 데코레이터를 제공합니다.

@reprlib.recursive_repr(fillvalue="...")

같은 스레드 내에서의 재귀 호출을 감지하는 __repr__() 메서드용 데코레이터. 재귀 호출이 이루어지면, fillvalue가 반환되고, 그렇지 않으면 평상시의 __repr__() 호출이 수행됩니다. 예를 들어:

>>> from reprlib import recursive_repr
>>> class MyList(list):
...     @recursive_repr()
...     def __repr__(self):
...         return '<' + '|'.join(map(repr, self)) + '>'
...
>>> m = MyList('abc')
>>> m.append(m)
>>> m.append('x')
>>> print(m)
<'a'|'b'|'c'|...|'x'>

버전 3.2에 추가.

Repr 객체

Repr 인스턴스는 여러 객체 형의 표현에 대한 크기 제한과 특정 객체 형을 포맷하는 메서드를 제공하는데 사용될 수 있습니다.

Repr.maxlevel

재귀적 표현의 생성에 대한 심도 한계. 기본값은 6입니다.

Repr.maxdict

Repr.maxlist

Repr.maxtuple

Repr.maxset

Repr.maxfrozenset

Repr.maxdeque

Repr.maxarray

명명된 객체 형을 표현하는 항목 수 제한. 기본값은 maxdict은 4, maxarray는 5 이고 그 외는 6입니다.

Repr.maxlong

정수 표현의 최대 문자 수입니다. 숫자는 가운데에서 삭제됩니다. 기본값은 40입니다.

Repr.maxstring

문자열 표현의 문자 수 제한. 문자열의 “통상” 표현이 문자 소스로써 사용되는 것에 주의해 주세요: 표현에 이스케이프 시퀀스가 필요하면, 표현이 짧아질 때 이것이 망가질 수 있습니다. 기본값은 30입니다.

Repr.maxother

이 제한은 Repr 객체에서 구체적인 포맷 메서드를 사용할 수 없는 객체 형의 크기를 제어하는 데 사용됩니다. maxstring과 비슷한 방식으로 적용됩니다. 기본값은 20입니다.

Repr.repr(obj)

인스턴스에 의해 부과된 포매팅을 사용하는 내장 repr()와 등등합니다.

Repr.repr1(obj, level)

repr()에서 사용되는 재귀적 구현. obj의 형을 사용하여 호출할 포매팅 메서드를 결정하고, obj 와 level을 전달합니다. 형별 메서드는 재귀적 포매팅을 수행하기 위해 repr1()을 호출해야 하는데, 재귀 호출에서 level 값으로 level - 1을 사용합니다.

Repr.repr_TYPE(obj, level)

특정 형의 포매팅 메서드는 형 이름에 기반하는 이름의 메서드로 구현됩니다. 메서드 이름에서, TYPE 은 '_'.join(type(obj).__name__.split())으로 치환됩니다. 이 메서드로의 디스패치는 repr1()에 의해 처리됩니다. 재귀적으로 값을 포맷해야 하는 형별 메서드는 self.repr1(subobj, level - 1)을 호출해야 합니다.

Repr 객체 서브클래싱

Repr.repr1()에 의한 동적 디스패치의 사용은 Repr의 서브 클래스가 추가 내장 객체 형에 대한 지원을 추가하거나 이미 지원되는 형의 처리를 수정할 수 있도록 합니다. 이 예제는 파일 객체에 대한 특별한 지원이 어떻게 추가될 수 있는지 보여줍니다:

import reprlib
import sys

class MyRepr(reprlib.Repr):

    def repr_TextIOWrapper(self, obj, level):
        if obj.name in {'<stdin>', '<stdout>', '<stderr>'}:
            return obj.name
        return repr(obj)

aRepr = MyRepr()
print(aRepr.repr(sys.stdin))         # prints '<stdin>'

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

데이터형 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

데이터형 »

|

enum — Support for enumerations

버전 3.4에 추가.

Source code: Lib/enum.py [https://github.com/python/cpython/tree/3.7/Lib/enum.py]

An enumeration is a set of symbolic names (members) bound to unique, constant values. Within an enumeration, the members can be compared by identity, and the enumeration itself can be iterated over.

Module Contents

This module defines four enumeration classes that can be used to define unique sets of names and values: Enum, IntEnum, Flag, and IntFlag. It also defines one decorator, unique(), and one helper, auto.

class enum.Enum

Base class for creating enumerated constants. See section Functional API for an alternate construction syntax.

class enum.IntEnum

Base class for creating enumerated constants that are also subclasses of int.

class enum.IntFlag

Base class for creating enumerated constants that can be combined using the bitwise operators without losing their IntFlag membership. IntFlag members are also subclasses of int.

class enum.Flag

Base class for creating enumerated constants that can be combined using the bitwise operations without losing their Flag membership.

enum.unique()

Enum class decorator that ensures only one name is bound to any one value.

class enum.auto

Instances are replaced with an appropriate value for Enum members. Initial value starts at 1.

버전 3.6에 추가: Flag, IntFlag, auto

Creating an Enum

Enumerations are created using the class syntax, which makes them easy to read and write. An alternative creation method is described in Functional API. To define an enumeration, subclass Enum as follows:

>>> from enum import Enum
>>> class Color(Enum):
...     RED = 1
...     GREEN = 2
...     BLUE = 3
...

참고

Enum member values

Member values can be anything: int, str, etc.. If the exact value is unimportant you may use auto instances and an appropriate value will be chosen for you. Care must be taken if you mix auto with other values.

참고

Nomenclature

The class Color is an enumeration (or enum)

The attributes Color.RED, Color.GREEN, etc., are enumeration members (or enum members) and are functionally constants.

The enum members have names and values (the name of Color.RED is RED, the value of Color.BLUE is 3, etc.)

참고

Even though we use the class syntax to create Enums, Enums are not normal Python classes. See How are Enums different? for more details.

Enumeration members have human readable string representations:

>>> print(Color.RED)
Color.RED

…while their repr has more information:

>>> print(repr(Color.RED))
<Color.RED: 1>

The type of an enumeration member is the enumeration it belongs to:

>>> type(Color.RED)
<enum 'Color'>
>>> isinstance(Color.GREEN, Color)
True
>>>

Enum members also have a property that contains just their item name:

>>> print(Color.RED.name)
RED

Enumerations support iteration, in definition order:

>>> class Shake(Enum):
...     VANILLA = 7
...     CHOCOLATE = 4
...     COOKIES = 9
...     MINT = 3
...
>>> for shake in Shake:
...     print(shake)
...
Shake.VANILLA
Shake.CHOCOLATE
Shake.COOKIES
Shake.MINT

Enumeration members are hashable, so they can be used in dictionaries and sets:

>>> apples = {}
>>> apples[Color.RED] = 'red delicious'
>>> apples[Color.GREEN] = 'granny smith'
>>> apples == {Color.RED: 'red delicious', Color.GREEN: 'granny smith'}
True

Programmatic access to enumeration members and their attributes

Sometimes it’s useful to access members in enumerations programmatically (i.e. situations where Color.RED won’t do because the exact color is not known at program-writing time). Enum allows such access:

>>> Color(1)
<Color.RED: 1>
>>> Color(3)
<Color.BLUE: 3>

If you want to access enum members by name, use item access:

>>> Color['RED']
<Color.RED: 1>
>>> Color['GREEN']
<Color.GREEN: 2>

If you have an enum member and need its name or value:

>>> member = Color.RED
>>> member.name
'RED'
>>> member.value
1

Duplicating enum members and values

Having two enum members with the same name is invalid:

>>> class Shape(Enum):
...     SQUARE = 2
...     SQUARE = 3
...
Traceback (most recent call last):
...
TypeError: Attempted to reuse key: 'SQUARE'

However, two enum members are allowed to have the same value. Given two members A and B with the same value (and A defined first), B is an alias to A. By-value lookup of the value of A and B will return A. By-name lookup of B will also return A:

>>> class Shape(Enum):
...     SQUARE = 2
...     DIAMOND = 1
...     CIRCLE = 3
...     ALIAS_FOR_SQUARE = 2
...
>>> Shape.SQUARE
<Shape.SQUARE: 2>
>>> Shape.ALIAS_FOR_SQUARE
<Shape.SQUARE: 2>
>>> Shape(2)
<Shape.SQUARE: 2>

참고

Attempting to create a member with the same name as an already defined attribute (another member, a method, etc.) or attempting to create an attribute with the same name as a member is not allowed.

Ensuring unique enumeration values

By default, enumerations allow multiple names as aliases for the same value. When this behavior isn’t desired, the following decorator can be used to ensure each value is used only once in the enumeration:

@enum.unique

A class decorator specifically for enumerations. It searches an enumeration’s __members__ gathering any aliases it finds; if any are found ValueError is raised with the details:

>>> from enum import Enum, unique
>>> @unique
... class Mistake(Enum):
...     ONE = 1
...     TWO = 2
...     THREE = 3
...     FOUR = 3
...
Traceback (most recent call last):
...
ValueError: duplicate values found in <enum 'Mistake'>: FOUR -> THREE

Using automatic values

If the exact value is unimportant you can use auto:

>>> from enum import Enum, auto
>>> class Color(Enum):
...     RED = auto()
...     BLUE = auto()
...     GREEN = auto()
...
>>> list(Color)
[<Color.RED: 1>, <Color.BLUE: 2>, <Color.GREEN: 3>]

The values are chosen by _generate_next_value_(), which can be overridden:

>>> class AutoName(Enum):
...     def _generate_next_value_(name, start, count, last_values):
...         return name
...
>>> class Ordinal(AutoName):
...     NORTH = auto()
...     SOUTH = auto()
...     EAST = auto()
...     WEST = auto()
...
>>> list(Ordinal)
[<Ordinal.NORTH: 'NORTH'>, <Ordinal.SOUTH: 'SOUTH'>, <Ordinal.EAST: 'EAST'>, <Ordinal.WEST: 'WEST'>]

참고

The goal of the default _generate_next_value_() methods is to provide the next int in sequence with the last int provided, but the way it does this is an implementation detail and may change.

참고

The _generate_next_value_() method must be defined before any members.

Iteration

Iterating over the members of an enum does not provide the aliases:

>>> list(Shape)
[<Shape.SQUARE: 2>, <Shape.DIAMOND: 1>, <Shape.CIRCLE: 3>]

The special attribute __members__ is an ordered dictionary mapping names to members. It includes all names defined in the enumeration, including the aliases:

>>> for name, member in Shape.__members__.items():
...     name, member
...
('SQUARE', <Shape.SQUARE: 2>)
('DIAMOND', <Shape.DIAMOND: 1>)
('CIRCLE', <Shape.CIRCLE: 3>)
('ALIAS_FOR_SQUARE', <Shape.SQUARE: 2>)

The __members__ attribute can be used for detailed programmatic access to the enumeration members. For example, finding all the aliases:

>>> [name for name, member in Shape.__members__.items() if member.name != name]
['ALIAS_FOR_SQUARE']

Comparisons

Enumeration members are compared by identity:

>>> Color.RED is Color.RED
True
>>> Color.RED is Color.BLUE
False
>>> Color.RED is not Color.BLUE
True

Ordered comparisons between enumeration values are not supported. Enum members are not integers (but see IntEnum below):

>>> Color.RED < Color.BLUE
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: '<' not supported between instances of 'Color' and 'Color'

Equality comparisons are defined though:

>>> Color.BLUE == Color.RED
False
>>> Color.BLUE != Color.RED
True
>>> Color.BLUE == Color.BLUE
True

Comparisons against non-enumeration values will always compare not equal (again, IntEnum was explicitly designed to behave differently, see below):

>>> Color.BLUE == 2
False

Allowed members and attributes of enumerations

The examples above use integers for enumeration values. Using integers is short and handy (and provided by default by the Functional API), but not strictly enforced. In the vast majority of use-cases, one doesn’t care what the actual value of an enumeration is. But if the value is important, enumerations can have arbitrary values.

Enumerations are Python classes, and can have methods and special methods as usual. If we have this enumeration:

>>> class Mood(Enum):
...     FUNKY = 1
...     HAPPY = 3
...
...     def describe(self):
...         # self is the member here
...         return self.name, self.value
...
...     def __str__(self):
...         return 'my custom str! {0}'.format(self.value)
...
...     @classmethod
...     def favorite_mood(cls):
...         # cls here is the enumeration
...         return cls.HAPPY
...

Then:

>>> Mood.favorite_mood()
<Mood.HAPPY: 3>
>>> Mood.HAPPY.describe()
('HAPPY', 3)
>>> str(Mood.FUNKY)
'my custom str! 1'

The rules for what is allowed are as follows: names that start and end with a single underscore are reserved by enum and cannot be used; all other attributes defined within an enumeration will become members of this enumeration, with the exception of special methods (__str__(), __add__(), etc.), descriptors (methods are also descriptors), and variable names listed in _ignore_.

Note: if your enumeration defines __new__() and/or __init__() then whatever value(s) were given to the enum member will be passed into those methods. See Planet for an example.

Restricted Enum subclassing

A new Enum class must have one base Enum class, up to one concrete data type, and as many object-based mixin classes as needed. The order of these base classes is:

class EnumName([mix-in, ...,] [data-type,] base-enum):
    pass

Also, subclassing an enumeration is allowed only if the enumeration does not define any members. So this is forbidden:

>>> class MoreColor(Color):
...     PINK = 17
...
Traceback (most recent call last):
...
TypeError: Cannot extend enumerations

But this is allowed:

>>> class Foo(Enum):
...     def some_behavior(self):
...         pass
...
>>> class Bar(Foo):
...     HAPPY = 1
...     SAD = 2
...

Allowing subclassing of enums that define members would lead to a violation of some important invariants of types and instances. On the other hand, it makes sense to allow sharing some common behavior between a group of enumerations. (See OrderedEnum for an example.)

Pickling

Enumerations can be pickled and unpickled:

>>> from test.test_enum import Fruit
>>> from pickle import dumps, loads
>>> Fruit.TOMATO is loads(dumps(Fruit.TOMATO))
True

The usual restrictions for pickling apply: picklable enums must be defined in the top level of a module, since unpickling requires them to be importable from that module.

참고

With pickle protocol version 4 it is possible to easily pickle enums nested in other classes.

It is possible to modify how Enum members are pickled/unpickled by defining __reduce_ex__() in the enumeration class.

Functional API

The Enum class is callable, providing the following functional API:

>>> Animal = Enum('Animal', 'ANT BEE CAT DOG')
>>> Animal
<enum 'Animal'>
>>> Animal.ANT
<Animal.ANT: 1>
>>> Animal.ANT.value
1
>>> list(Animal)
[<Animal.ANT: 1>, <Animal.BEE: 2>, <Animal.CAT: 3>, <Animal.DOG: 4>]

The semantics of this API resemble namedtuple. The first argument of the call to Enum is the name of the enumeration.

The second argument is the source of enumeration member names. It can be a whitespace-separated string of names, a sequence of names, a sequence of 2-tuples with key/value pairs, or a mapping (e.g. dictionary) of names to values. The last two options enable assigning arbitrary values to enumerations; the others auto-assign increasing integers starting with 1 (use the start parameter to specify a different starting value). A new class derived from Enum is returned. In other words, the above assignment to Animal is equivalent to:

>>> class Animal(Enum):
...     ANT = 1
...     BEE = 2
...     CAT = 3
...     DOG = 4
...

The reason for defaulting to 1 as the starting number and not 0 is that 0 is False in a boolean sense, but enum members all evaluate to True.

Pickling enums created with the functional API can be tricky as frame stack implementation details are used to try and figure out which module the enumeration is being created in (e.g. it will fail if you use a utility function in separate module, and also may not work on IronPython or Jython). The solution is to specify the module name explicitly as follows:

>>> Animal = Enum('Animal', 'ANT BEE CAT DOG', module=__name__)

경고

If module is not supplied, and Enum cannot determine what it is, the new Enum members will not be unpicklable; to keep errors closer to the source, pickling will be disabled.

The new pickle protocol 4 also, in some circumstances, relies on __qualname__ being set to the location where pickle will be able to find the class. For example, if the class was made available in class SomeData in the global scope:

>>> Animal = Enum('Animal', 'ANT BEE CAT DOG', qualname='SomeData.Animal')

The complete signature is:

Enum(value='NewEnumName', names=<...>, *, module='...', qualname='...', type=<mixed-in class>, start=1)

value

What the new Enum class will record as its name.

names

The Enum members. This can be a whitespace or comma separated string (values will start at 1 unless otherwise specified):

'RED GREEN BLUE' | 'RED,GREEN,BLUE' | 'RED, GREEN, BLUE'

or an iterator of names:

['RED', 'GREEN', 'BLUE']

or an iterator of (name, value) pairs:

[('CYAN', 4), ('MAGENTA', 5), ('YELLOW', 6)]

or a mapping:

{'CHARTREUSE': 7, 'SEA_GREEN': 11, 'ROSEMARY': 42}

module

name of module where new Enum class can be found.

qualname

where in module new Enum class can be found.

type

type to mix in to new Enum class.

start

number to start counting at if only names are passed in.

버전 3.5에서 변경: The start parameter was added.

Derived Enumerations

IntEnum

The first variation of Enum that is provided is also a subclass of int. Members of an IntEnum can be compared to integers; by extension, integer enumerations of different types can also be compared to each other:

>>> from enum import IntEnum
>>> class Shape(IntEnum):
...     CIRCLE = 1
...     SQUARE = 2
...
>>> class Request(IntEnum):
...     POST = 1
...     GET = 2
...
>>> Shape == 1
False
>>> Shape.CIRCLE == 1
True
>>> Shape.CIRCLE == Request.POST
True

However, they still can’t be compared to standard Enum enumerations:

>>> class Shape(IntEnum):
...     CIRCLE = 1
...     SQUARE = 2
...
>>> class Color(Enum):
...     RED = 1
...     GREEN = 2
...
>>> Shape.CIRCLE == Color.RED
False

IntEnum values behave like integers in other ways you’d expect:

>>> int(Shape.CIRCLE)
1
>>> ['a', 'b', 'c'][Shape.CIRCLE]
'b'
>>> [i for i in range(Shape.SQUARE)]
[0, 1]

IntFlag

The next variation of Enum provided, IntFlag, is also based on int. The difference being IntFlag members can be combined using the bitwise operators (&, |, ^, ~) and the result is still an IntFlag member. However, as the name implies, IntFlag members also subclass int and can be used wherever an int is used. Any operation on an IntFlag member besides the bit-wise operations will lose the IntFlag membership.

버전 3.6에 추가.

Sample IntFlag class:

>>> from enum import IntFlag
>>> class Perm(IntFlag):
...     R = 4
...     W = 2
...     X = 1
...
>>> Perm.R | Perm.W
<Perm.R|W: 6>
>>> Perm.R + Perm.W
6
>>> RW = Perm.R | Perm.W
>>> Perm.R in RW
True

It is also possible to name the combinations:

>>> class Perm(IntFlag):
...     R = 4
...     W = 2
...     X = 1
...     RWX = 7
>>> Perm.RWX
<Perm.RWX: 7>
>>> ~Perm.RWX
<Perm.-8: -8>

Another important difference between IntFlag and Enum is that if no flags are set (the value is 0), its boolean evaluation is False:

>>> Perm.R & Perm.X
<Perm.0: 0>
>>> bool(Perm.R & Perm.X)
False

Because IntFlag members are also subclasses of int they can be combined with them:

>>> Perm.X | 8
<Perm.8|X: 9>

Flag

The last variation is Flag. Like IntFlag, Flag members can be combined using the bitwise operators (&, |, ^, ~). Unlike IntFlag, they cannot be combined with, nor compared against, any other Flag enumeration, nor int. While it is possible to specify the values directly it is recommended to use auto as the value and let Flag select an appropriate value.

버전 3.6에 추가.

Like IntFlag, if a combination of Flag members results in no flags being set, the boolean evaluation is False:

>>> from enum import Flag, auto
>>> class Color(Flag):
...     RED = auto()
...     BLUE = auto()
...     GREEN = auto()
...
>>> Color.RED & Color.GREEN
<Color.0: 0>
>>> bool(Color.RED & Color.GREEN)
False

Individual flags should have values that are powers of two (1, 2, 4, 8, …), while combinations of flags won’t:

>>> class Color(Flag):
...     RED = auto()
...     BLUE = auto()
...     GREEN = auto()
...     WHITE = RED | BLUE | GREEN
...
>>> Color.WHITE
<Color.WHITE: 7>

Giving a name to the “no flags set” condition does not change its boolean value:

>>> class Color(Flag):
...     BLACK = 0
...     RED = auto()
...     BLUE = auto()
...     GREEN = auto()
...
>>> Color.BLACK
<Color.BLACK: 0>
>>> bool(Color.BLACK)
False

참고

For the majority of new code, Enum and Flag are strongly recommended, since IntEnum and IntFlag break some semantic promises of an enumeration (by being comparable to integers, and thus by transitivity to other unrelated enumerations). IntEnum and IntFlag should be used only in cases where Enum and Flag will not do; for example, when integer constants are replaced with enumerations, or for interoperability with other systems.

Others

While IntEnum is part of the enum module, it would be very simple to implement independently:

class IntEnum(int, Enum):
    pass

This demonstrates how similar derived enumerations can be defined; for example a StrEnum that mixes in str instead of int.

Some rules:

When subclassing Enum, mix-in types must appear before Enum itself in the sequence of bases, as in the IntEnum example above.

While Enum can have members of any type, once you mix in an additional type, all the members must have values of that type, e.g. int above. This restriction does not apply to mix-ins which only add methods and don’t specify another data type such as int or str.

When another data type is mixed in, the value attribute is not the same as the enum member itself, although it is equivalent and will compare equal.

%-style formatting: %s and %r call the Enum class’s __str__() and __repr__() respectively; other codes (such as %i or %h for IntEnum) treat the enum member as its mixed-in type.

Formatted string literals, str.format(), and format() will use the mixed-in type’s __format__(). If the Enum class’s str() or repr() is desired, use the !s or !r format codes.

Interesting examples

While Enum, IntEnum, IntFlag, and Flag are expected to cover the majority of use-cases, they cannot cover them all. Here are recipes for some different types of enumerations that can be used directly, or as examples for creating one’s own.

Omitting values

In many use-cases one doesn’t care what the actual value of an enumeration is. There are several ways to define this type of simple enumeration:

use instances of auto for the value

use instances of object as the value

use a descriptive string as the value

use a tuple as the value and a custom __new__() to replace the tuple with an int value

Using any of these methods signifies to the user that these values are not important, and also enables one to add, remove, or reorder members without having to renumber the remaining members.

Whichever method you choose, you should provide a repr() that also hides the (unimportant) value:

>>> class NoValue(Enum):
...     def __repr__(self):
...         return '<%s.%s>' % (self.__class__.__name__, self.name)
...

Using auto

Using auto would look like:

>>> class Color(NoValue):
...     RED = auto()
...     BLUE = auto()
...     GREEN = auto()
...
>>> Color.GREEN
<Color.GREEN>

Using object

Using object would look like:

>>> class Color(NoValue):
...     RED = object()
...     GREEN = object()
...     BLUE = object()
...
>>> Color.GREEN
<Color.GREEN>

Using a descriptive string

Using a string as the value would look like:

>>> class Color(NoValue):
...     RED = 'stop'
...     GREEN = 'go'
...     BLUE = 'too fast!'
...
>>> Color.GREEN
<Color.GREEN>
>>> Color.GREEN.value
'go'

Using a custom __new__()

Using an auto-numbering __new__() would look like:

>>> class AutoNumber(NoValue):
...     def __new__(cls):
...         value = len(cls.__members__) + 1
...         obj = object.__new__(cls)
...         obj._value_ = value
...         return obj
...
>>> class Color(AutoNumber):
...     RED = ()
...     GREEN = ()
...     BLUE = ()
...
>>> Color.GREEN
<Color.GREEN>
>>> Color.GREEN.value
2

참고

The __new__() method, if defined, is used during creation of the Enum members; it is then replaced by Enum’s __new__() which is used after class creation for lookup of existing members.

OrderedEnum

An ordered enumeration that is not based on IntEnum and so maintains the normal Enum invariants (such as not being comparable to other enumerations):

>>> class OrderedEnum(Enum):
...     def __ge__(self, other):
...         if self.__class__ is other.__class__:
...             return self.value >= other.value
...         return NotImplemented
...     def __gt__(self, other):
...         if self.__class__ is other.__class__:
...             return self.value > other.value
...         return NotImplemented
...     def __le__(self, other):
...         if self.__class__ is other.__class__:
...             return self.value <= other.value
...         return NotImplemented
...     def __lt__(self, other):
...         if self.__class__ is other.__class__:
...             return self.value < other.value
...         return NotImplemented
...
>>> class Grade(OrderedEnum):
...     A = 5
...     B = 4
...     C = 3
...     D = 2
...     F = 1
...
>>> Grade.C < Grade.A
True

DuplicateFreeEnum

Raises an error if a duplicate member name is found instead of creating an alias:

>>> class DuplicateFreeEnum(Enum):
...     def __init__(self, *args):
...         cls = self.__class__
...         if any(self.value == e.value for e in cls):
...             a = self.name
...             e = cls(self.value).name
...             raise ValueError(
...                 "aliases not allowed in DuplicateFreeEnum:  %r --> %r"
...                 % (a, e))
...
>>> class Color(DuplicateFreeEnum):
...     RED = 1
...     GREEN = 2
...     BLUE = 3
...     GRENE = 2
...
Traceback (most recent call last):
...
ValueError: aliases not allowed in DuplicateFreeEnum:  'GRENE' --> 'GREEN'

참고

This is a useful example for subclassing Enum to add or change other behaviors as well as disallowing aliases. If the only desired change is disallowing aliases, the unique() decorator can be used instead.

Planet

If __new__() or __init__() is defined the value of the enum member will be passed to those methods:

>>> class Planet(Enum):
...     MERCURY = (3.303e+23, 2.4397e6)
...     VENUS   = (4.869e+24, 6.0518e6)
...     EARTH   = (5.976e+24, 6.37814e6)
...     MARS    = (6.421e+23, 3.3972e6)
...     JUPITER = (1.9e+27,   7.1492e7)
...     SATURN  = (5.688e+26, 6.0268e7)
...     URANUS  = (8.686e+25, 2.5559e7)
...     NEPTUNE = (1.024e+26, 2.4746e7)
...     def __init__(self, mass, radius):
...         self.mass = mass       # in kilograms
...         self.radius = radius   # in meters
...     @property
...     def surface_gravity(self):
...         # universal gravitational constant  (m3 kg-1 s-2)
...         G = 6.67300E-11
...         return G * self.mass / (self.radius * self.radius)
...
>>> Planet.EARTH.value
(5.976e+24, 6378140.0)
>>> Planet.EARTH.surface_gravity
9.802652743337129

TimePeriod

An example to show the _ignore_ attribute in use:

>>> from datetime import timedelta
>>> class Period(timedelta, Enum):
...     "different lengths of time"
...     _ignore_ = 'Period i'
...     Period = vars()
...     for i in range(367):
...         Period['day_%d' % i] = i
...
>>> list(Period)[:2]
[<Period.day_0: datetime.timedelta(0)>, <Period.day_1: datetime.timedelta(days=1)>]
>>> list(Period)[-2:]
[<Period.day_365: datetime.timedelta(days=365)>, <Period.day_366: datetime.timedelta(days=366)>]

How are Enums different?

Enums have a custom metaclass that affects many aspects of both derived Enum classes and their instances (members).

Enum Classes

The EnumMeta metaclass is responsible for providing the __contains__(), __dir__(), __iter__() and other methods that allow one to do things with an Enum class that fail on a typical class, such as list(Color) or some_enum_var in Color. EnumMeta is responsible for ensuring that various other methods on the final Enum class are correct (such as __new__(), __getnewargs__(), __str__() and __repr__()).

Enum Members (aka instances)

The most interesting thing about Enum members is that they are singletons. EnumMeta creates them all while it is creating the Enum class itself, and then puts a custom __new__() in place to ensure that no new ones are ever instantiated by returning only the existing member instances.

Finer Points

Supported __dunder__ names

__members__ is an OrderedDict of member_name:member items. It is only available on the class.

__new__(), if specified, must create and return the enum members; it is also a very good idea to set the member’s _value_ appropriately. Once all the members are created it is no longer used.

Supported _sunder_ names

_name_ – name of the member

_value_ – value of the member; can be set / modified in __new__

_missing_ – a lookup function used when a value is not found; may be overridden

_ignore_ – a list of names, either as a list() or a str(), that will not be transformed into members, and will be removed from the final class

_order_ – used in Python 2/3 code to ensure member order is consistent (class attribute, removed during class creation)

_generate_next_value_ – used by the Functional API and by auto to get an appropriate value for an enum member; may be overridden

버전 3.6에 추가: _missing_, _order_, _generate_next_value_

버전 3.7에 추가: _ignore_

To help keep Python 2 / Python 3 code in sync an _order_ attribute can be provided. It will be checked against the actual order of the enumeration and raise an error if the two do not match:

>>> class Color(Enum):
...     _order_ = 'RED GREEN BLUE'
...     RED = 1
...     BLUE = 3
...     GREEN = 2
...
Traceback (most recent call last):
...
TypeError: member order does not match _order_

참고

In Python 2 code the _order_ attribute is necessary as definition order is lost before it can be recorded.

Enum member type

Enum members are instances of their Enum class, and are normally accessed as EnumClass.member. Under certain circumstances they can also be accessed as EnumClass.member.member, but you should never do this as that lookup may fail or, worse, return something besides the Enum member you are looking for (this is another good reason to use all-uppercase names for members):

>>> class FieldTypes(Enum):
...     name = 0
...     value = 1
...     size = 2
...
>>> FieldTypes.value.size
<FieldTypes.size: 2>
>>> FieldTypes.size.value
2

버전 3.5에서 변경.

Boolean value of Enum classes and members

Enum members that are mixed with non-Enum types (such as int, str, etc.) are evaluated according to the mixed-in type’s rules; otherwise, all members evaluate as True. To make your own Enum’s boolean evaluation depend on the member’s value add the following to your class:

def __bool__(self):
    return bool(self.value)

Enum classes always evaluate as True.

Enum classes with methods

If you give your Enum subclass extra methods, like the Planet class above, those methods will show up in a dir() of the member, but not of the class:

>>> dir(Planet)
['EARTH', 'JUPITER', 'MARS', 'MERCURY', 'NEPTUNE', 'SATURN', 'URANUS', 'VENUS', '__class__', '__doc__', '__members__', '__module__']
>>> dir(Planet.EARTH)
['__class__', '__doc__', '__module__', 'name', 'surface_gravity', 'value']

Combining members of Flag

If a combination of Flag members is not named, the repr() will include all named flags and all named combinations of flags that are in the value:

>>> class Color(Flag):
...     RED = auto()
...     GREEN = auto()
...     BLUE = auto()
...     MAGENTA = RED | BLUE
...     YELLOW = RED | GREEN
...     CYAN = GREEN | BLUE
...
>>> Color(3)  # named combination
<Color.YELLOW: 3>
>>> Color(7)      # not named combination
<Color.CYAN|MAGENTA|BLUE|YELLOW|GREEN|RED: 7>

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

데이터형 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

|

숫자와 수학 모듈

이 장에 나와있는 모듈들은 숫자와 수학에 관련된 함수와 데이터 타입을 제공합니다. numbers 모듈은 숫자 데이터 타입을 위한 추상 계층 구조를 정의합니다. math 와 cmath 모듈은 부동소수와 복소수를 위한 여러 수학 함수를 가지고 있습니다. decimal 모듈은 임의의 정밀도 계산을 사용하여 정확한 10진수 표현을 지원합니다.

이 장에는 다음과 같은 모듈이 설명되어 있습니다:

numbers — 숫자 추상 베이스 클래스

숫자 계층

형 구현을 위한 주의 사항

더 많은 숫자 추상 베이스 클래스(ABC) 추가

산술 연산 구현

math — Mathematical functions

Number-theoretic and representation functions

Power and logarithmic functions

Trigonometric functions

Angular conversion

Hyperbolic functions

Special functions

Constants

cmath — 복소수를 위한 수학 함수

극좌표 변환

거듭제곱과 로그 함수

삼각 함수

쌍곡선(hyperbolic) 함수

분류 함수

상수

decimal — 십진 고정 소수점 및 부동 소수점 산술

빠른 시작 자습서

Decimal 객체

논리적 피연산자

Context 객체

상수

자리 올림 모드

신호

부동 소수점 노트

증가시킨 정밀도로 자리 올림 오차 줄이기

특수 값

스레드로 작업하기

조리법

Decimal FAQ

fractions — 유리수

random — Generate pseudo-random numbers

Bookkeeping functions

Functions for integers

Functions for sequences

Real-valued distributions

Alternative Generator

Notes on Reproducibility

Examples and Recipes

statistics — Mathematical statistics functions

Averages and measures of central location

Measures of spread

Function details

Exceptions

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

숫자와 수학 모듈 »

|

numbers — 숫자 추상 베이스 클래스

소스 코드: Lib/numbers.py [https://github.com/python/cpython/tree/3.7/Lib/numbers.py]

numbers 모듈(PEP 3141 [https://www.python.org/dev/peps/pep-3141])은 숫자에 대한 추상 베이스 클래스 의 계층 구조를 정의합니다. 계층 구조가 깊어질수록 더 많은 연산이 정의되어 있습니다. 이 모듈에 정의된 모든 형은 인스턴스로 만들 수 없습니다.

class numbers.Number

숫자 계층의 최상위 클래스입니다. 형에 상관없이 인자 x 가 숫자인지 확인하려면 isinstance(x, Number) 를 사용하세요.

숫자 계층

class numbers.Complex

이 서브 클래스는 복소수를 표현하고 내장 complex 형에 사용되는 연산을 포함합니다. 여기에는 complex 와 bool 형으로의 변환과 real, imag, +, -, *, /, abs(), conjugate(), ==, != 이 포함됩니다. - 와 != 를 제외하고는 모두 추상입니다.

real

추상. 복소수의 실수부를 반환합니다.

imag

추상. 복소수의 허수부를 반환합니다.

abstractmethod conjugate()

추상 메서드. 켤레 복소수를 반환합니다. 예를 들어 (1+3j).conjugate() == (1-3j) 입니다.

class numbers.Real

Real 클래스는 Complex 클래스에 실수 연산을 추가합니다.

요약하면 float 로의 변환과 math.trunc(), round(), math.floor(), math.ceil(), divmod(), //, %, <, <=, >, >= 가 포함됩니다.

이 클래스는 또한 complex(), real, imag, conjugate() 를 위한 기본값을 제공합니다.

class numbers.Rational

Real 의 하위 형이고 numerator 와 denominator 프로퍼티가 추가됩니다. 이 프로퍼티는 기약 분수의 값이어야 합니다. 또한 float() 함수를 위한 기본값으로 사용됩니다.

numerator

프로퍼티(추상 메서드)

denominator

프로퍼티(추상 메서드)

class numbers.Integral

Rational 의 하위 형이고 int 클래스로 변환 기능이 추가됩니다. float(), numerator, denominator 를 위한 기본값을 제공합니다. ** 를 위한 메서드와 비트 연산 <<, >>, &, ^, |, ~ 를 추가합니다.

형 구현을 위한 주의 사항

구현자는 동일한 숫자가 같게 취급되고 같은 값으로 해싱되도록 해야 합니다. 만약 종류가 다른 실수의 하위 형이 있는 경우 조금 까다로울 수 있습니다. 예를 들어 fractions.Fraction 클래스는 hash() 함수를 다음과 같이 구현합니다:

def __hash__(self):
    if self.denominator == 1:
        # Get integers right.
        return hash(self.numerator)
    # Expensive check, but definitely correct.
    if self == float(self):
        return hash(float(self))
    else:
        # Use tuple's hash to avoid a high collision rate on
        # simple fractions.
        return hash((self.numerator, self.denominator))

더 많은 숫자 추상 베이스 클래스(ABC) 추가

물론 숫자를 위한 ABC를 추가하는 것이 가능합니다. 그렇지 않으면 엉망으로 상속 계층이 구현될 것입니다. Complex 와 Real 사이에 다음과 같이 MyFoo 를 추가할 수 있습니다:

class MyFoo(Complex): ...
MyFoo.register(Real)

산술 연산 구현

다른 형에 대한 연산은 두 인자의 형에 관해 알고 있는 구현을 호출하거나 두 인자를 가장 비슷한 내장형으로 변환하여 연산하도록 산술 연산을 구현하는 것이 좋습니다. Integral 클래스의 하위 형일 경우에 __add__() 와 __radd__() 메서드는 다음과 같이 정의되어야 함을 의미합니다:

class MyIntegral(Integral):

    def __add__(self, other):
        if isinstance(other, MyIntegral):
            return do_my_adding_stuff(self, other)
        elif isinstance(other, OtherTypeIKnowAbout):
            return do_my_other_adding_stuff(self, other)
        else:
            return NotImplemented

    def __radd__(self, other):
        if isinstance(other, MyIntegral):
            return do_my_adding_stuff(other, self)
        elif isinstance(other, OtherTypeIKnowAbout):
            return do_my_other_adding_stuff(other, self)
        elif isinstance(other, Integral):
            return int(other) + int(self)
        elif isinstance(other, Real):
            return float(other) + float(self)
        elif isinstance(other, Complex):
            return complex(other) + complex(self)
        else:
            return NotImplemented

Complex 클래스의 서브클래스에는 다섯 가지의 서로 다른 혼합형 연산이 있습니다. 위의 코드에서 MyIntegral 와 OtherTypeIKnowAbout 를 제외한 나머지를 기본구조라고 하겠습니다. a 는 Complex 의 하위 형인 A 의 인스턴스입니다(즉 a : A <: Complex 입니다). 비슷하게 b : B <: Complex 입니다. a + b 인 경우를 생각해 보겠습니다:

만약 A 가 b 를 받는 __add__() 메서드를 정의했다면 모든 것이 문제없이 처리됩니다.

A 가 기본구조 코드로 진입하고 __add__()로 부터 어떤 값을 반환한다면 B 가 똑똑하게 정의한 __radd__() 메서드를 놓칠 수 있습니다. 이를 피하려면 기본구조는 __add__() 에서 NotImplemented 를 반환해야 합니다. (또는 A 가 __add__() 메서드를 전혀 구현하지 않을 수도 있습니다.)

그다음 B 의 __radd__() 메서드가 기회를 얻습니다. 이 메서드가 a 를 받을 수 있다면 모든 것이 문제없이 처리됩니다.

기본구조 코드로 돌아온다면 더 시도해 볼 수 있는 메서드가 없으므로 기본적으로 수행될 구현을 작성해야 합니다.

만약 B <: A 라면 파이썬은 A.__add__ 메서드 전에 B.__radd__ 를 시도합니다. A 에 대해서 알고 B 가 구현되었기 때문에 이런 행동은 문제없습니다. 따라서 Complex 에 위임하기 전에 이 인스턴스를 처리할 수 있습니다.

만약 어떤 것도 공유하지 않는 A <: Complex 와 B <: Real 라면 적절한 공유 연산(shared operation)은 내장 complex 클래스에 연관된 것입니다. 양쪽의 __radd__() 메서드가 여기에 해당하므로 a+b == b+a 가 됩니다.

대부분 주어진 어떤 형에 대한 연산은 매우 비슷하므로, 주어진 연산자의 정방향(forward) 인스턴스와 역방향(reverse) 인스턴스를 생성하는 헬퍼 함수를 정의하는 것이 유용합니다. 예를 들어 fractions.Fraction 클래스는 다음과 같이 사용합니다:

def _operator_fallbacks(monomorphic_operator, fallback_operator):
    def forward(a, b):
        if isinstance(b, (int, Fraction)):
            return monomorphic_operator(a, b)
        elif isinstance(b, float):
            return fallback_operator(float(a), b)
        elif isinstance(b, complex):
            return fallback_operator(complex(a), b)
        else:
            return NotImplemented
    forward.__name__ = '__' + fallback_operator.__name__ + '__'
    forward.__doc__ = monomorphic_operator.__doc__

    def reverse(b, a):
        if isinstance(a, Rational):
            # Includes ints.
            return monomorphic_operator(a, b)
        elif isinstance(a, numbers.Real):
            return fallback_operator(float(a), float(b))
        elif isinstance(a, numbers.Complex):
            return fallback_operator(complex(a), complex(b))
        else:
            return NotImplemented
    reverse.__name__ = '__r' + fallback_operator.__name__ + '__'
    reverse.__doc__ = monomorphic_operator.__doc__

    return forward, reverse

def _add(a, b):
    """a + b"""
    return Fraction(a.numerator * b.denominator +
                    b.numerator * a.denominator,
                    a.denominator * b.denominator)

__add__, __radd__ = _operator_fallbacks(_add, operator.add)

# ...

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

숫자와 수학 모듈 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

숫자와 수학 모듈 »

|

math — Mathematical functions

This module provides access to the mathematical functions defined by the C standard.

These functions cannot be used with complex numbers; use the functions of the same name from the cmath module if you require support for complex numbers. The distinction between functions which support complex numbers and those which don’t is made since most users do not want to learn quite as much mathematics as required to understand complex numbers. Receiving an exception instead of a complex result allows earlier detection of the unexpected complex number used as a parameter, so that the programmer can determine how and why it was generated in the first place.

The following functions are provided by this module. Except when explicitly noted otherwise, all return values are floats.

Number-theoretic and representation functions

math.ceil(x)

Return the ceiling of x, the smallest integer greater than or equal to x. If x is not a float, delegates to x.__ceil__(), which should return an Integral value.

math.copysign(x, y)

Return a float with the magnitude (absolute value) of x but the sign of y. On platforms that support signed zeros, copysign(1.0, -0.0) returns -1.0.

math.fabs(x)

Return the absolute value of x.

math.factorial(x)

Return x factorial as an integer. Raises ValueError if x is not integral or is negative.

math.floor(x)

Return the floor of x, the largest integer less than or equal to x. If x is not a float, delegates to x.__floor__(), which should return an Integral value.

math.fmod(x, y)

Return fmod(x, y), as defined by the platform C library. Note that the Python expression x % y may not return the same result. The intent of the C standard is that fmod(x, y) be exactly (mathematically; to infinite precision) equal to x - n*y for some integer n such that the result has the same sign as x and magnitude less than abs(y). Python’s x % y returns a result with the sign of y instead, and may not be exactly computable for float arguments. For example, fmod(-1e-100, 1e100) is -1e-100, but the result of Python’s -1e-100 % 1e100 is 1e100-1e-100, which cannot be represented exactly as a float, and rounds to the surprising 1e100. For this reason, function fmod() is generally preferred when working with floats, while Python’s x % y is preferred when working with integers.

math.frexp(x)

Return the mantissa and exponent of x as the pair (m, e). m is a float and e is an integer such that x == m * 2**e exactly. If x is zero, returns (0.0, 0), otherwise 0.5 <= abs(m) < 1. This is used to “pick apart” the internal representation of a float in a portable way.

math.fsum(iterable)

Return an accurate floating point sum of values in the iterable. Avoids loss of precision by tracking multiple intermediate partial sums:

>>> sum([.1, .1, .1, .1, .1, .1, .1, .1, .1, .1])
0.9999999999999999
>>> fsum([.1, .1, .1, .1, .1, .1, .1, .1, .1, .1])
1.0

The algorithm’s accuracy depends on IEEE-754 arithmetic guarantees and the typical case where the rounding mode is half-even. On some non-Windows builds, the underlying C library uses extended precision addition and may occasionally double-round an intermediate sum causing it to be off in its least significant bit.

For further discussion and two alternative approaches, see the ASPN cookbook recipes for accurate floating point summation [https://code.activestate.com/recipes/393090/].

math.gcd(a, b)

Return the greatest common divisor of the integers a and b. If either a or b is nonzero, then the value of gcd(a, b) is the largest positive integer that divides both a and b. gcd(0, 0) returns 0.

버전 3.5에 추가.

math.isclose(a, b, *, rel_tol=1e-09, abs_tol=0.0)

Return True if the values a and b are close to each other and False otherwise.

Whether or not two values are considered close is determined according to given absolute and relative tolerances.

rel_tol is the relative tolerance – it is the maximum allowed difference between a and b, relative to the larger absolute value of a or b. For example, to set a tolerance of 5%, pass rel_tol=0.05. The default tolerance is 1e-09, which assures that the two values are the same within about 9 decimal digits. rel_tol must be greater than zero.

abs_tol is the minimum absolute tolerance – useful for comparisons near zero. abs_tol must be at least zero.

If no errors occur, the result will be: abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol).

The IEEE 754 special values of NaN, inf, and -inf will be handled according to IEEE rules. Specifically, NaN is not considered close to any other value, including NaN. inf and -inf are only considered close to themselves.

버전 3.5에 추가.

더 보기

PEP 485 [https://www.python.org/dev/peps/pep-0485] – A function for testing approximate equality

math.isfinite(x)

Return True if x is neither an infinity nor a NaN, and False otherwise. (Note that 0.0 is considered finite.)

버전 3.2에 추가.

math.isinf(x)

Return True if x is a positive or negative infinity, and False otherwise.

math.isnan(x)

Return True if x is a NaN (not a number), and False otherwise.

math.ldexp(x, i)

Return x * (2**i). This is essentially the inverse of function frexp().

math.modf(x)

Return the fractional and integer parts of x. Both results carry the sign of x and are floats.

math.remainder(x, y)

Return the IEEE 754-style remainder of x with respect to y. For finite x and finite nonzero y, this is the difference x - n*y, where n is the closest integer to the exact value of the quotient x / y. If x / y is exactly halfway between two consecutive integers, the nearest even integer is used for n. The remainder r = remainder(x, y) thus always satisfies abs(r) <= 0.5 * abs(y).

Special cases follow IEEE 754: in particular, remainder(x, math.inf) is x for any finite x, and remainder(x, 0) and remainder(math.inf, x) raise ValueError for any non-NaN x. If the result of the remainder operation is zero, that zero will have the same sign as x.

On platforms using IEEE 754 binary floating-point, the result of this operation is always exactly representable: no rounding error is introduced.

버전 3.7에 추가.

math.trunc(x)

Return the Real value x truncated to an Integral (usually an integer). Delegates to x.__trunc__().

Note that frexp() and modf() have a different call/return pattern than their C equivalents: they take a single argument and return a pair of values, rather than returning their second return value through an ‘output parameter’ (there is no such thing in Python).

For the ceil(), floor(), and modf() functions, note that all floating-point numbers of sufficiently large magnitude are exact integers. Python floats typically carry no more than 53 bits of precision (the same as the platform C double type), in which case any float x with abs(x) >= 2**52 necessarily has no fractional bits.

Power and logarithmic functions

math.exp(x)

Return e raised to the power x, where e = 2.718281… is the base of natural logarithms. This is usually more accurate than math.e ** x or pow(math.e, x).

math.expm1(x)

Return e raised to the power x, minus 1. Here e is the base of natural logarithms. For small floats x, the subtraction in exp(x) - 1 can result in a significant loss of precision [https://en.wikipedia.org/wiki/Loss_of_significance]; the expm1() function provides a way to compute this quantity to full precision:

>>> from math import exp, expm1
>>> exp(1e-5) - 1  # gives result accurate to 11 places
1.0000050000069649e-05
>>> expm1(1e-5)    # result accurate to full precision
1.0000050000166668e-05

버전 3.2에 추가.

math.log(x[, base])

With one argument, return the natural logarithm of x (to base e).

With two arguments, return the logarithm of x to the given base, calculated as log(x)/log(base).

math.log1p(x)

Return the natural logarithm of 1+x (base e). The result is calculated in a way which is accurate for x near zero.

math.log2(x)

Return the base-2 logarithm of x. This is usually more accurate than log(x, 2).

버전 3.3에 추가.

더 보기

int.bit_length() returns the number of bits necessary to represent an integer in binary, excluding the sign and leading zeros.

math.log10(x)

Return the base-10 logarithm of x. This is usually more accurate than log(x, 10).

math.pow(x, y)

Return x raised to the power y. Exceptional cases follow Annex ‘F’ of the C99 standard as far as possible. In particular, pow(1.0, x) and pow(x, 0.0) always return 1.0, even when x is a zero or a NaN. If both x and y are finite, x is negative, and y is not an integer then pow(x, y) is undefined, and raises ValueError.

Unlike the built-in ** operator, math.pow() converts both its arguments to type float. Use ** or the built-in pow() function for computing exact integer powers.

math.sqrt(x)

Return the square root of x.

Trigonometric functions

math.acos(x)

Return the arc cosine of x, in radians.

math.asin(x)

Return the arc sine of x, in radians.

math.atan(x)

Return the arc tangent of x, in radians.

math.atan2(y, x)

Return atan(y / x), in radians. The result is between -pi and pi. The vector in the plane from the origin to point (x, y) makes this angle with the positive X axis. The point of atan2() is that the signs of both inputs are known to it, so it can compute the correct quadrant for the angle. For example, atan(1) and atan2(1, 1) are both pi/4, but atan2(-1, -1) is -3*pi/4.

math.cos(x)

Return the cosine of x radians.

math.hypot(x, y)

Return the Euclidean norm, sqrt(x*x + y*y). This is the length of the vector from the origin to point (x, y).

math.sin(x)

Return the sine of x radians.

math.tan(x)

Return the tangent of x radians.

Angular conversion

math.degrees(x)

Convert angle x from radians to degrees.

math.radians(x)

Convert angle x from degrees to radians.

Hyperbolic functions

Hyperbolic functions [https://en.wikipedia.org/wiki/Hyperbolic_function] are analogs of trigonometric functions that are based on hyperbolas instead of circles.

math.acosh(x)

Return the inverse hyperbolic cosine of x.

math.asinh(x)

Return the inverse hyperbolic sine of x.

math.atanh(x)

Return the inverse hyperbolic tangent of x.

math.cosh(x)

Return the hyperbolic cosine of x.

math.sinh(x)

Return the hyperbolic sine of x.

math.tanh(x)

Return the hyperbolic tangent of x.

Special functions

math.erf(x)

Return the error function [https://en.wikipedia.org/wiki/Error_function] at x.

The erf() function can be used to compute traditional statistical functions such as the cumulative standard normal distribution [https://en.wikipedia.org/wiki/Normal_distribution#Cumulative_distribution_function]:

def phi(x):
    'Cumulative distribution function for the standard normal distribution'
    return (1.0 + erf(x / sqrt(2.0))) / 2.0

버전 3.2에 추가.

math.erfc(x)

Return the complementary error function at x. The complementary error function [https://en.wikipedia.org/wiki/Error_function] is defined as 1.0 - erf(x). It is used for large values of x where a subtraction from one would cause a loss of significance [https://en.wikipedia.org/wiki/Loss_of_significance].

버전 3.2에 추가.

math.gamma(x)

Return the Gamma function [https://en.wikipedia.org/wiki/Gamma_function] at x.

버전 3.2에 추가.

math.lgamma(x)

Return the natural logarithm of the absolute value of the Gamma function at x.

버전 3.2에 추가.

Constants

math.pi

The mathematical constant π = 3.141592…, to available precision.

math.e

The mathematical constant e = 2.718281…, to available precision.

math.tau

The mathematical constant τ = 6.283185…, to available precision. Tau is a circle constant equal to 2π, the ratio of a circle’s circumference to its radius. To learn more about Tau, check out Vi Hart’s video Pi is (still) Wrong [https://www.youtube.com/watch?v=jG7vhMMXagQ], and start celebrating Tau day [https://tauday.com/] by eating twice as much pie!

버전 3.6에 추가.

math.inf

A floating-point positive infinity. (For negative infinity, use -math.inf.) Equivalent to the output of float('inf').

버전 3.5에 추가.

math.nan

A floating-point “not a number” (NaN) value. Equivalent to the output of float('nan').

버전 3.5에 추가.

CPython implementation detail: The math module consists mostly of thin wrappers around the platform C math library functions. Behavior in exceptional cases follows Annex F of the C99 standard where appropriate. The current implementation will raise ValueError for invalid operations like sqrt(-1.0) or log(0.0) (where C99 Annex F recommends signaling invalid operation or divide-by-zero), and OverflowError for results that overflow (for example, exp(1000.0)). A NaN will not be returned from any of the functions above unless one or more of the input arguments was a NaN; in that case, most functions will return a NaN, but (again following C99 Annex F) there are some exceptions to this rule, for example pow(float('nan'), 0.0) or hypot(float('nan'), float('inf')).

Note that Python makes no effort to distinguish signaling NaNs from quiet NaNs, and behavior for signaling NaNs remains unspecified. Typical behavior is to treat all NaNs as though they were quiet.

더 보기

Module cmath

Complex number versions of many of these functions.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

숫자와 수학 모듈 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

숫자와 수학 모듈 »

|

cmath — 복소수를 위한 수학 함수

이 모듈은 복소수를 위한 수학 함수에 대한 액세스를 제공합니다. 이 모듈의 함수는 정수, 부동 소수점 수 또는 복소수를 인자로 받아들입니다. 이들은 또한 __complex__()나 __float__() 메서드를 가진 임의의 파이썬 객체를 받아들일 것입니다: 이 메서드는 객체를 각각 복소수나 부동 소수점 수로 변환하기 위해 사용되며, 함수는 변환 결과에 적용됩니다.

참고

부호 있는 0에 대한 하드웨어와 시스템 수준 지원이 있는 플랫폼에서, 분지 절단(branch cut)을 수반하는 함수는 분지 절단의 양 면에서 연속입니다: 0의 부호는 분지 절단의 한 면을 다른 면과 구별합니다. 부호 있는 0을 지원하지 않는 플랫폼에서 연속성은 아래에 지정된 것과 같습니다.

극좌표 변환

파이썬 복소수 z는 직교 혹은 데카르트 좌표를 사용하여 내부적으로 저장됩니다. 실수부 z.real과 허수부 z.imag에 의해 완전히 결정됩니다. 다시 말해:

z == z.real + z.imag*1j

극좌표(polar coordinates)는 복소수를 나타내는 다른 방법을 제공합니다. 극좌표에서, 복소수 z는 모듈러스(modulus) r과 위상 각(phase angle) phi로 정의됩니다. 모듈러스 r은 z에서 원점까지의 거리이며, 위상 phi는 양의 x축에서 원점과 z를 잇는 선분으로의 라디안(radian)으로 측정한 반 시계 방향 각도입니다.

네이티브 직교 좌표와 극좌표 간의 변환에 다음 함수를 사용할 수 있습니다.

cmath.phase(x)

x의 위상(x의 편각(argument)이라고도 합니다)을 float로 반환합니다. phase(x)는 math.atan2(x.imag, x.real)과 동등합니다. 결과는 [-π, π] 범위에 놓이고, 이 작업의 분지 절단은 음의 실수 축에 놓이고, 위로부터 연속입니다. 부호 있는 0을 지원하는 시스템(현재 사용 중인 대부분의 시스템을 포함합니다)에서, 이는 결과의 부호가 x.imag가 0일 때도 x.imag의 부호와 같음을 의미합니다:

>>> phase(complex(-1.0, 0.0))
3.141592653589793
>>> phase(complex(-1.0, -0.0))
-3.141592653589793

참고

복소수 x의 모듈러스(절댓값)는 내장 abs() 함수를 사용하여 계산할 수 있습니다. 이 연산을 위한 별도의 cmath 모듈 함수는 없습니다.

cmath.polar(x)

x 표현을 극좌표로 반환합니다. 쌍 (r, phi)를 반환합니다. 여기서 r은 x의 모듈러스이고 phi는 x의 위상입니다. polar(x)는 (abs(x), phase(x))와 동등합니다.

cmath.rect(r, phi)

극좌표 r과 phi를 가지는 복소수 x를 반환합니다. r * (math.cos(phi) + math.sin(phi)*1j)와 동등합니다.

거듭제곱과 로그 함수

cmath.exp(x)

e의 x 거듭제곱을 반환합니다. 여기서 e는 자연로그(natural logarithms)의 밑입니다.

cmath.log(x[, base])

주어진 밑(base)에 대한 x의 로그를 반환합니다. base가 지정되지 않으면, x의 자연로그를 반환합니다. 음의 실수 축을 따라 0에서부터 -∞ 까지 가고, 위로부터 연속인 하나의 분지 절단이 있습니다.

cmath.log10(x)

x의 밑이 10인 로그를 반환합니다. 이것은 log()와 같은 분지 절단을 가집니다.

cmath.sqrt(x)

x의 제곱근을 반환합니다. 이것은 log()와 같은 분지 절단을 가집니다.

삼각 함수

cmath.acos(x)

x의 아크 코사인을 반환합니다. 두 개의 분지 절단이 있습니다: 하나는 실수 축을 따라 1에서 오른쪽으로 ∞까지 확장하고, 아래로부터 연속입니다. 다른 하나는 실수 축을 따라 -1에서 왼쪽으로 -∞까지 확장되고, 위에서부터 연속입니다.

cmath.asin(x)

x의 아크 사인을 반환합니다. 이것은 acos()와 같은 분지 절단을 가집니다.

cmath.atan(x)

x의 아크 탄젠트를 반환합니다. 두 개의 분지 절단이 있습니다: 하나는 허수 축을 따라 1j에서 ∞j까지 확장되며, 오른쪽으로부터 연속입니다. 다른 하나는 허수 축을 따라 -1j에서 -∞j까지 확장되며, 왼쪽으로부터 연속입니다.

cmath.cos(x)

x의 코사인을 반환합니다.

cmath.sin(x)

x의 사인을 반환합니다.

cmath.tan(x)

x의 탄젠트를 반환합니다.

쌍곡선(hyperbolic) 함수

cmath.acosh(x)

x의 역 쌍곡선 코사인을 반환합니다. 하나의 분지 절단이 있습니다, 실수 축을 따라 1에서 왼쪽으로 -∞까지 확장되며 위로부터 연속입니다.

cmath.asinh(x)

x의 역 쌍곡선 사인을 반환합니다. 두 개의 분지 절단이 있습니다: 하나는 허수 축을 따라 1j에서 ∞j까지 확장되며, 오른쪽으로부터 연속입니다. 다른 하나는 허수 축을 따라 -1j에서 -∞j까지 확장되며, 왼쪽으로부터 연속입니다.

cmath.atanh(x)

x의 역 쌍곡선 탄젠트를 반환합니다. 두 개의 분지 절단이 있습니다: 하나는 실수 축을 따라 1에서 ∞까지 확장되며, 아래로부터 연속입니다. 다른 하나는 실수 축을 따라 -1에서 -∞까지 확장되며, 위로부터 연속입니다.

cmath.cosh(x)

x의 쌍곡선 코사인을 반환합니다.

cmath.sinh(x)

x의 쌍곡선 사인을 반환합니다.

cmath.tanh(x)

x의 쌍곡선 탄젠트를 반환합니다.

분류 함수

cmath.isfinite(x)

x의 실수부와 허수부가 모두 유한이면 True를 반환하고, 그렇지 않으면 False를 반환합니다.

버전 3.2에 추가.

cmath.isinf(x)

x의 실수부나 허수부 중 하나가 무한이면 True를 반환하고, 그렇지 않으면 False를 반환합니다.

cmath.isnan(x)

x의 실수부나 허수부 중 하나가 NaN이면 True를 반환하고, 그렇지 않으면 False를 반환합니다.

cmath.isclose(a, b, *, rel_tol=1e-09, abs_tol=0.0)

a와 b 값이 서로 가까우면 True를 반환하고, 그렇지 않으면 False를 반환합니다.

두 값을 가까운 것으로 간주하는지는 주어진 절대와 상대 허용 오차에 따라 결정됩니다.

rel_tol은 상대 허용 오차입니다 – a와 b 사이의 최대 허용 차이이고, a나 b의 절댓값 중 더 큰 값에 상대적입니다. 예를 들어, 5%의 허용 오차를 설정하려면, rel_tol=0.05를 전달하십시오. 기본 허용 오차는 1e-09이며, 이는 두 값이 약 9자리 십진 숫자 내에서 같음을 보장합니다. rel_tol은 0보다 커야 합니다.

abs_tol은 최소 절대 허용 오차입니다 – 0에 가까운 비교에 유용합니다. abs_tol은 최소한 0이어야 합니다.

에러가 발생하지 않으면, 결과는 다음과 같습니다: abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol).

IEEE 754 특수 값 NaN, inf 및 -inf는 IEEE 규칙에 따라 처리됩니다. 특히, NaN은 NaN을 포함한 다른 모는 값과 가깝다고 간주하지 않습니다. inf와 -inf는 그들 자신하고만 가깝다고 간주합니다.

버전 3.5에 추가.

더 보기

PEP 485 [https://www.python.org/dev/peps/pep-0485] – 근사 동등을 검사하는 함수.

상수

cmath.pi

수학 상수 π의 float 값.

cmath.e

수학 상수 e의 float 값.

cmath.tau

수학 상수 τ의 float 값.

버전 3.6에 추가.

cmath.inf

부동 소수점 양의 무한대. float('inf')와 동등합니다.

버전 3.6에 추가.

cmath.infj

0 실수부와 양의 무한대 허수부를 갖는 복소수. complex(0.0, float('inf'))와 동등합니다.

버전 3.6에 추가.

cmath.nan

부동 소수점 “not a number” (NaN) 값. float('nan')과 동등합니다.

버전 3.6에 추가.

cmath.nanj

0 실수부와 NaN 허수부를 갖는 복소수. complex(0.0, float('nan'))과 동등합니다.

버전 3.6에 추가.

함수 선택은 모듈 math에서와 유사하지만 동일하지는 않습니다. 두 개의 모듈이 있는 이유는 일부 사용자가 복소수에 관심이 없고, 어쩌면 복소수가 무엇인지 모를 수도 있기 때문입니다. 그들에게는 math.sqrt(-1)이 복소수를 반환하기보다 예외를 발생시키는 것이 좋습니다. 또한, cmath에 정의된 함수는, 결과를 실수로 표현할 수 있을 때도 항상 복소수를 반환합니다 (이때 복소수의 허수부는 0입니다).

분지 절단에 대한 참고 사항: 주어진 함수가 연속적이지 않은 점을 지나는 곡선입니다. 이것들은 많은 복소수 기능에서 필요한 기능입니다. 복소수 함수로 계산해야 할 때, 분지 절단에 대해 이해가 필요하다고 가정합니다. 이해를 위해서는 복소 변수에 관한 (너무 기초적이지 않은) 아무 책이나 참고하면 됩니다. 수치 계산의 목적으로 분지 절단을 적절히 선택하는 방법에 대한 정보에 대해서는, 다음과 같은 좋은 참고 문헌이 있습니다:

더 보기

Kahan, W: Branch cuts for complex elementary functions; or, Much ado about nothing’s sign bit. Iserles, A., and Powell, M. (eds.), The state of the art in numerical analysis. Clarendon Press (1987) pp165–211.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

숫자와 수학 모듈 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

숫자와 수학 모듈 »

|

decimal — 십진 고정 소수점 및 부동 소수점 산술

소스 코드: Lib/decimal.py [https://github.com/python/cpython/tree/3.7/Lib/decimal.py]

decimal 모듈은 빠르고 정확하게 자리 올림 하는 십진 부동 소수 산술을 지원합니다. float 데이터형보다 다음과 같은 몇 가지 장점을 제공합니다:

Decimal “은 사람을 염두에 두고 설계된 부동 소수점 모델에 기반하고, 필연적으로 최고 원리를 갖습니다 – 컴퓨터는 사람들이 학교에서 배우는 산술과 같은 방식으로 동작하는 산술을 반드시 제공해야 한다.” – 십진 산술 명세에서 발췌.

Decimal 수는 정확하게 표현할 수 있습니다. 반면에, 1.1과 2.2와 같은 수는, 이진 부동 소수점으로 정확히 표현할 수 없습니다. 최종 사용자는 일반적으로 이진 부동 소수점에서 그러하듯이 1.1 + 2.2 가 3.3000000000000003처럼 표시되는 것을 기대하지 않을 것입니다.

정확성은 산술에서도 유지됩니다. 십진 부동 소수점에서, 0.1 + 0.1 + 0.1 - 0.3 는 정확하게 0과 같습니다. 이진 부동 소수점에서, 결과는 5.5511151231257827e-017 입니다. 0에 가깝지만, 차이가 신뢰할 수 있는 동등성 검사를 방해하고, 차이는 누적 될 수 있습니다. 이러한 이유로, 강한 동등성 불변 조건을 갖는 회계 응용 프로그램에서는 decimal이 선호됩니다.

decimal 모듈은 유효 자릿수의 개념을 포함하고 있으므로 1.30 + 1.20 은 2.50 입니다. 후행 0은 유효성을 나타내기 위해 유지됩니다. 이것은 화폐 응용에서는 관례적인 표현입니다. 곱셈의 경우, “교과서” 접근법은 피승수의 모든 숫자를 사용합니다. 예를 들어 1.3 * 1.2 는 1.56 이고, 1.30 * 1.20 은 1.5600 입니다.

하드웨어 기반 이진 부동 소수점과는 달리, decimal 모듈은 사용자가 변경할 수 있는 정밀도(기본값은 28자리)를 가지며, 주어진 문제에 따라 필요한 만큼 커질 수 있습니다:

>>> from decimal import *
>>> getcontext().prec = 6
>>> Decimal(1) / Decimal(7)
Decimal('0.142857')
>>> getcontext().prec = 28
>>> Decimal(1) / Decimal(7)
Decimal('0.1428571428571428571428571429')

이진 및 십진 부동 소수점 모두 출판된 표준에 따라 구현됩니다. 내장 float 형이 기능의 적당한 부분만을 드러내지만, decimal 모듈은 표준의 모든 필수 부분을 노출합니다. 필요한 경우, 프로그래머는 자리 올림(rounding) 및 신호(signal) 처리를 완전히 제어할 수 있습니다. 여기에는 정확하지 않은 연산을 차단하기 위한 예외를 사용하여 정확한 산술을 강제하는 옵션이 포함됩니다.

decimal 모듈은 “편견 없이, (때로 고정 소수점 산술이라고도 불리는) 정확한 자리 올림 없는 십진 산술과 자리 올림 있는 부동 소수점 산술을 모두” 지원하도록 설계되었습니다. – 십진 산술 명세에서 발췌.

모듈 설계의 중심 개념은 세 가지입니다: 십진수, 산술을 위한 컨텍스트, 신호(signal).

decimal 수는 불변입니다. 부호(sign), 계수(coefficient digits) 및 지수(exponent)로 구성됩니다. 유효성을 유지하기 위해, 계수는 후행 0을 자르지 않습니다. Decimal은 또한 Infinity, -Infinity, NaN 과 같은 특별한 값을 포함합니다. 표준은 또한 -0을 +0과 구별합니다.

산술 컨텍스트는 정밀도, 자리 올림 규칙, 지수에 대한 제한, 연산 결과를 나타내는 플래그 및 신호가 예외로 처리될지를 결정하는 트랩 활성화기(trap enabler)를 지정하는 환경입니다. 자리 올림 옵션에는 ROUND_CEILING, ROUND_DOWN, ROUND_FLOOR, ROUND_HALF_DOWN, ROUND_HALF_EVEN, ROUND_HALF_UP, ROUND_UP 및 ROUND_05UP 가 있습니다.

신호는 계산 과정에서 발생하는 예외적인 조건의 그룹입니다. 응용 프로그램의 필요에 따라, 신호가 무시되거나, 정보로 간주하거나, 예외로 처리될 수 있습니다. decimal 모듈의 신호는 Clamped, InvalidOperation, DivisionByZero, Inexact, Rounded, Subnormal, Overflow, Underflow, FloatOperation 입니다.

각 신호에는 플래그와 트랩 활성화기가 있습니다. 신호와 만났을 때, 플래그가 1로 설정되고 트랩 활성화기가 1로 설정된 경우, 예외가 발생합니다. 플래그는 상태가 유지되므로(sticky) 계산을 감시하기 전에 재설정할 필요가 있습니다.

더 보기

IBM의 일반 십진 산술 명세, The General Decimal Arithmetic Specification [http://speleotrove.com/decimal/decarith.html].

빠른 시작 자습서

decimal을 사용하는 일반적인 시작은 모듈을 임포트하고, getcontext() 로 현재 컨텍스트를 보고, 필요하다면 정밀도, 자리 올림 또는 활성화된 트랩에 대해 새 값을 설정하는 것입니다:

>>> from decimal import *
>>> getcontext()
Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999,
        capitals=1, clamp=0, flags=[], traps=[Overflow, DivisionByZero,
        InvalidOperation])

>>> getcontext().prec = 7       # Set a new precision

Decimal 인스턴스는 정수, 문자열, 실수(float) 또는 튜플로 만들 수 있습니다. 정수 나 실수로 만들면 해당 정수 또는 실수의 정확한 값 변환이 일어납니다. Decimal 수는 “숫자가 아님(Not a number)”을 나타내는 NaN, 양과 음의 Infinity 및 -0과 같은 특수한 값을 포함합니다:

>>> getcontext().prec = 28
>>> Decimal(10)
Decimal('10')
>>> Decimal('3.14')
Decimal('3.14')
>>> Decimal(3.14)
Decimal('3.140000000000000124344978758017532527446746826171875')
>>> Decimal((0, (3, 1, 4), -2))
Decimal('3.14')
>>> Decimal(str(2.0 ** 0.5))
Decimal('1.4142135623730951')
>>> Decimal(2) ** Decimal('0.5')
Decimal('1.414213562373095048801688724')
>>> Decimal('NaN')
Decimal('NaN')
>>> Decimal('-Infinity')
Decimal('-Infinity')

FloatOperation 신호를 트랩 하는 경우, 실수로 생성자나 대소비교에서 Decimal 수와 실수(float)를 혼합하면 예외가 발생합니다:

>>> c = getcontext()
>>> c.traps[FloatOperation] = True
>>> Decimal(3.14)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
decimal.FloatOperation: [<class 'decimal.FloatOperation'>]
>>> Decimal('3.5') < 3.7
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
decimal.FloatOperation: [<class 'decimal.FloatOperation'>]
>>> Decimal('3.5') == 3.5
True

버전 3.3에 추가.

새로운 Decimal의 유효 숫자는 입력된 숫자의 개수에 의해서만 결정됩니다. 컨텍스트 정밀도 및 자리 올림은 오직 산술 연산 중에만 작용합니다.

>>> getcontext().prec = 6
>>> Decimal('3.0')
Decimal('3.0')
>>> Decimal('3.1415926535')
Decimal('3.1415926535')
>>> Decimal('3.1415926535') + Decimal('2.7182818285')
Decimal('5.85987')
>>> getcontext().rounding = ROUND_UP
>>> Decimal('3.1415926535') + Decimal('2.7182818285')
Decimal('5.85988')

C 버전의 내부 제한을 초과하면, Decimal 을 만들 때 InvalidOperation 를 일으킵니다:

>>> Decimal("1e9999999999999999999")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
decimal.InvalidOperation: [<class 'decimal.InvalidOperation'>]

버전 3.3에서 변경.

Decimal은 파이썬의 다른 부분들과 잘 어울립니다. 다음은 십진 부동 소수점으로 부린 작은 묘기입니다:

>>> data = list(map(Decimal, '1.34 1.87 3.45 2.35 1.00 0.03 9.25'.split()))
>>> max(data)
Decimal('9.25')
>>> min(data)
Decimal('0.03')
>>> sorted(data)
[Decimal('0.03'), Decimal('1.00'), Decimal('1.34'), Decimal('1.87'),
 Decimal('2.35'), Decimal('3.45'), Decimal('9.25')]
>>> sum(data)
Decimal('19.29')
>>> a,b,c = data[:3]
>>> str(a)
'1.34'
>>> float(a)
1.34
>>> round(a, 1)
Decimal('1.3')
>>> int(a)
1
>>> a * 5
Decimal('6.70')
>>> a * b
Decimal('2.5058')
>>> c % a
Decimal('0.77')

그리고 Decimal에는 몇 가지 수학 함수도 있습니다:

>>> getcontext().prec = 28
>>> Decimal(2).sqrt()
Decimal('1.414213562373095048801688724')
>>> Decimal(1).exp()
Decimal('2.718281828459045235360287471')
>>> Decimal('10').ln()
Decimal('2.302585092994045684017991455')
>>> Decimal('10').log10()
Decimal('1')

quantize() 메서드는 숫자를 고정된 지수로 자리 올림 합니다. 이 방법은 종종 결과를 고정된 자릿수로 자리 올림 하는 화폐 응용에 유용합니다.:

>>> Decimal('7.325').quantize(Decimal('.01'), rounding=ROUND_DOWN)
Decimal('7.32')
>>> Decimal('7.325').quantize(Decimal('1.'), rounding=ROUND_UP)
Decimal('8')

위에서 보듯이, getcontext() 함수는 현재 컨텍스트에 액세스하고 설정을 변경할 수 있게 합니다. 이 방법은 대부분 응용 프로그램의 요구를 충족시킵니다.

고급 작업을 위해, Context() 생성자를 사용하여 대체 컨텍스트를 만드는 것이 유용할 수 있습니다. 대체 컨텍스트를 활성화하려면, setcontext() 함수를 사용하십시오.

표준에 따라, decimal 모듈은 당장 사용할 수 있는 두 개의 표준 컨텍스트 BasicContext 와 ExtendedContext 를 제공합니다. 특히 전자는 많은 트랩이 활성화되어있어 디버깅에 유용합니다:

>>> myothercontext = Context(prec=60, rounding=ROUND_HALF_DOWN)
>>> setcontext(myothercontext)
>>> Decimal(1) / Decimal(7)
Decimal('0.142857142857142857142857142857142857142857142857142857142857')

>>> ExtendedContext
Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999,
        capitals=1, clamp=0, flags=[], traps=[])
>>> setcontext(ExtendedContext)
>>> Decimal(1) / Decimal(7)
Decimal('0.142857143')
>>> Decimal(42) / Decimal(0)
Decimal('Infinity')

>>> setcontext(BasicContext)
>>> Decimal(42) / Decimal(0)
Traceback (most recent call last):
  File "<pyshell#143>", line 1, in -toplevel-
    Decimal(42) / Decimal(0)
DivisionByZero: x / 0

컨텍스트에는 계산 중에 발생하는 예외 조건을 감시하기 위한 신호 플래그도 있습니다. 플래그는 명시적으로 지워질 때까지 설정된 상태로 유지되므로, clear_flags() 메서드를 사용하여 모니터링되는 각 계산 집합 앞에서 플래그를 지우는 것이 가장 좋습니다.

>>> setcontext(ExtendedContext)
>>> getcontext().clear_flags()
>>> Decimal(355) / Decimal(113)
Decimal('3.14159292')
>>> getcontext()
Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999,
        capitals=1, clamp=0, flags=[Inexact, Rounded], traps=[])

flags 엔트리는 Pi 에 대한 유리수 근삿값이 자리 올림 되었고 (컨텍스트 정밀도 이상의 숫자가 버려졌습니다) 결과가 부정확하다는 (폐기된 숫자 일부는 0이 아닙니다) 것을 보여줍니다.

개별 트랩은 컨텍스트의 traps 필드에 있는 딕셔너리를 사용해서 설정합니다.:

>>> setcontext(ExtendedContext)
>>> Decimal(1) / Decimal(0)
Decimal('Infinity')
>>> getcontext().traps[DivisionByZero] = 1
>>> Decimal(1) / Decimal(0)
Traceback (most recent call last):
  File "<pyshell#112>", line 1, in -toplevel-
    Decimal(1) / Decimal(0)
DivisionByZero: x / 0

대부분 프로그램은 프로그램 시작 시에 한 번만 현재 컨텍스트를 조정합니다. 그리고, 많은 응용 프로그램에서, 데이터는 루프 내에서 단일형변환으로 Decimal로 변환되어, 프로그램 대부분은 다른 파이썬 숫자 형과 별로 다르지 않게 데이터를 조작합니다.

Decimal 객체

class decimal.Decimal(value="0", context=None)

value 를 기반으로 새 Decimal 객체를 만듭니다.

value 는 정수, 문자열, 튜플, float 또는 다른 Decimal 객체일 수 있습니다. value 가 주어지지 않으면, Decimal('0') 을 반환합니다. value 가 문자열이면, 앞뒤의 공백 문자 및 밑줄이 제거된 후 십진수 문자열 문법에 맞아야 합니다:

sign           ::=  '+' | '-'
digit          ::=  '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9'
indicator      ::=  'e' | 'E'
digits         ::=  digit [digit]...
decimal-part   ::=  digits '.' [digits] | ['.'] digits
exponent-part  ::=  indicator [sign] digits
infinity       ::=  'Infinity' | 'Inf'
nan            ::=  'NaN' [digits] | 'sNaN' [digits]
numeric-value  ::=  decimal-part [exponent-part] | infinity
numeric-string ::=  [sign] numeric-value | [sign] nan

위의 digit 가 나타나는 곳에는 다른 유니코드 십진수도 허용됩니다. 여기에는 다양한 다른 알파벳(예를 들어, 인도-아라비아와 데바나가리 숫자)의 십진수와 전각 숫자 '\uff10' 에서 '\uff19' 까지 포함됩니다.

value 가 tuple 이면, 세 개의 항목으로 구성되어야 합니다, 부호 (0 은 양수, 1 은 음수), 숫자의 tuple, 정수 지수. 예를 들어, Decimal((0, (1, 4, 1, 4), -3)) 은 Decimal('1.414') 를 반환합니다.

value 가 float 면, 이진 부동 소수점 값은 손실 없이 정확한 십진수로 변환됩니다. 이 변환에는 종종 53자리 이상의 정밀도가 필요할 수 있습니다. 예를 들어, Decimal(float('1.1')) 은 Decimal('1.100000000000000088817841970012523233890533447265625') 로 변환됩니다.

context 정밀도는 저장되는 자릿수에 영향을 주지 않습니다. 저장되는 자릿수는 value 의 자릿수만으로 결정됩니다. 예를 들어 Decimal('3.00000') 은 컨텍스트 정밀도가 단지 3이라도 5개의 모든 0을 기록합니다.

context 인자의 목적은 value 가 잘못된 문자열인 경우 어떻게 해야할지를 결정하는 것입니다. 컨텍스트가 InvalidOperation 을 트랩하면, 예외가 발생합니다; 그렇지 않으면, 생성자는 NaN 의 값을 갖는 새 Decimal을 반환합니다.

일단 만들어지면, Decimal 객체는 불변입니다.

버전 3.2에서 변경: 생성자에 대한 인자는 이제 float 인스턴스가 될 수 있습니다.

버전 3.3에서 변경: float 인자는 FloatOperation 트랩이 설정되면 예외를 발생시킵니다. 기본적으로 트랩은 꺼져 있습니다.

버전 3.6에서 변경: 코드에서의 정수와 부동 소수점 리터럴과 마찬가지로, 밑줄로 무리 지을 수 있습니다.

십진 부동 소수점 객체는 float나 int와 같은 다른 내장 숫자 형과 많은 성질을 공유합니다. 일반적인 수학 연산과 특수 메서드가 모두 적용됩니다. 마찬가지로, 십진 객체는 복사, 피클, 인쇄, 딕셔너리 키로 사용, 집합 원소로 사용, 비교, 정렬 및 다른 형(가령 float 또는 int)으로 코어션될 수 있습니다.

Decimal 객체에 대한 산술과 정수 및 실수에 대한 산술에는 약간의 차이가 있습니다. Decimal 객체에 나머지 연산자 % 가 적용될 때, 결과의 부호는 제수의 부호가 아닌 피제수의 부호가 됩니다:

>>> (-7) % 4
1
>>> Decimal(-7) % Decimal(4)
Decimal('-3')

정수 나눗셈 연산자 // 의 동작 역시 비슷한 차이를 보입니다. 즉, 가장 가까운 정수로 내림하는 대신 실제 몫의 정수 부(0을 향해 자르기)를 돌려줍니다. 그래서 일반적인 항등식 x == (x // y) * y + x % y 를 유지합니다:

>>> -7 // 4
-2
>>> Decimal(-7) // Decimal(4)
Decimal('-1')

% 와 // 연산자는 명세에 설명된 대로 각각 remainder 와 divide-integer 연산을 구현합니다.

Decimal 객체는 일반적으로 산술 연산에서 float 나 fractions.Fraction 인스턴스와 결합 할 수 없습니다: 예를 들어, float 에 a Decimal을 더하려고 하면 TypeError 를 일으킵니다. 그러나, 파이썬의 비교 연산자를 사용하여 Decimal 인스턴스 x 와 다른 숫자 y 를 비교할 수 있습니다. 이렇게 해서 서로 다른 형의 숫자 간에 동등 비교를 할 때 혼란스러운 결과를 피합니다.

버전 3.2에서 변경: Decimal 인스턴스와 다른 숫자 형 사이의 혼합형 비교가 이제 완전히 지원됩니다.

표준 숫자 속성에 더해, 십진 부동 소수점 객체에는 여러 가지 특별한 메서드가 있습니다:

adjusted()

최상위 숫자만 남을 때까지 계수의 가장 오른쪽 숫자들을 밀어내도록 조정된 지수를 반환합니다. Decimal('321e+5').adjusted() 는 7을 반환합니다. 소수점으로부터의 최상위 유효 숫자의 위치를 결정하는 데 사용됩니다.

as_integer_ratio()

주어진 Decimal 인스턴스를, 분모가 양수인 기약 분수로 나타내는 정수의 쌍 (n, d) 을 돌려줍니다:

>>> Decimal('-3.14').as_integer_ratio()
(-157, 50)

변환은 정확합니다. 무한대는 OverflowError를, NaN 은 ValueError를 일으킵니다.

버전 3.6에 추가.

as_tuple()

숫자의 네임드 튜플 표현을 반환합니다: DecimalTuple(sign, digits, exponent).

canonical()

인자의 규범적인 인코딩을 돌려줍니다. 현재 Decimal 인스턴스의 인코딩은 항상 규범적이므로, 이 연산은 인자를 변경하지 않고 반환합니다.

compare(other, context=None)

두 Decimal 인스턴스의 값을 비교합니다. compare() 는 Decimal 인스턴스를 반환하고, 피연산자 중 하나가 NaN이면 결과는 NaN입니다:

a or b is a NaN  ==> Decimal('NaN')
a < b            ==> Decimal('-1')
a == b           ==> Decimal('0')
a > b            ==> Decimal('1')

compare_signal(other, context=None)

이 연산은, 모든 NaN 이 신호를 준다는 것을 제외하면 compare() 메서드와 같습니다. 즉, 피연산자가 모두 신호를 주는 NaN이 아니면, 모든 조용한 NaN 피연산자가 마치 신호를 주는 NaN 인 것처럼 처리됩니다.

compare_total(other, context=None)

두 개의 피연산자를 숫자 값 대신 추상 표현을 사용하여 비교합니다. compare() 메서드와 비슷하지만, 결과는 Decimal 인스턴스에 대해 전 순서(total ordering)를 부여합니다. 같은 숫자 값을 갖지만 다른 표현의 두 Decimal 인스턴스는 이 순서에 의해 다른 것으로 비교됩니다:

>>> Decimal('12.0').compare_total(Decimal('12'))
Decimal('-1')

조용한 NaN과 신호를 주는 NaN도 전 순서에 포함됩니다. 이 함수의 결과는, 두 피연산자가 같은 표현을 가질 때 Decimal('0'), 첫 번째 피연산자가 전 순서에서 두 번째 피연산자보다 낮으면 Decimal('-1'), 첫 번째 피연산자가 전 순서에서 두 번째 피연산자보다 높으면 Decimal('1') 입니다. 전 순서에 대한 세부 사항은 명세를 참조하십시오.

이 연산은 컨텍스트의 영향을 받지 않고, 조용합니다: 어떤 플래그도 변경되지 않고, 어떤 자리 올림도 수행되지 않습니다. 예외적으로, 두 번째 피연산자를 정확하게 변환할 수 없으면 C 버전은 InvalidOperation을 발생시킬 수 있습니다.

compare_total_mag(other, context=None)

compare_total()처럼 두 개의 피연산자를 숫자 값 대신 추상 표현을 사용하여 비교하지만, 각 피연산자의 부호를 무시합니다. x.compare_total_mag(y) 는 x.copy_abs().compare_total(y.copy_abs()) 와 동등합니다.

이 연산은 컨텍스트의 영향을 받지 않고, 조용합니다: 어떤 플래그도 변경되지 않고, 어떤 자리 올림도 수행되지 않습니다. 예외적으로, 두 번째 피연산자를 정확하게 변환할 수 없으면 C 버전은 InvalidOperation을 발생시킬 수 있습니다.

conjugate()

그냥 self를 돌려줍니다. 이 메서드는 Decimal 명세를 준수하기 위한 것뿐입니다.

copy_abs()

인자의 절댓값을 반환합니다. 이 연산은 컨텍스트의 영향을 받지 않고, 조용합니다: 어떤 플래그도 변경되지 않고, 어떤 자리 올림도 수행되지 않습니다.

copy_negate()

인자의 음의 부정을 돌려줍니다. 이 연산은 컨텍스트의 영향을 받지 않고, 조용합니다: 어떤 플래그도 변경되지 않고, 어떤 자리 올림도 수행되지 않습니다.

copy_sign(other, context=None)

두 번째 피연산자의 부호와 같은 부호로 설정된 첫 번째 피연산자의 복사본을 반환합니다. 예를 들어:

>>> Decimal('2.3').copy_sign(Decimal('-1.5'))
Decimal('-2.3')

이 연산은 컨텍스트의 영향을 받지 않고, 조용합니다: 어떤 플래그도 변경되지 않고, 어떤 자리 올림도 수행되지 않습니다. 예외적으로, 두 번째 피연산자를 정확하게 변환할 수 없으면 C 버전은 InvalidOperation을 발생시킬 수 있습니다.

exp(context=None)

주어진 숫자에 대한 (자연) 지수 함수 e**x 의 값을 반환합니다. 결과는 ROUND_HALF_EVEN 자리 올림 모드를 사용하여 올바르게 자리 올림 됩니다.

>>> Decimal(1).exp()
Decimal('2.718281828459045235360287471')
>>> Decimal(321).exp()
Decimal('2.561702493119680037517373933E+139')

from_float(f)

float를 십진수로 정확하게 변환하는 클래스 메서드.

Decimal.from_float(0.1) 은 Decimal(‘0.1’)과 같지 않음에 유의하십시오. 0.1은 이진 부동 소수점에서 정확하게 표현할 수 없으므로, 값은 가장 가까운 표현 가능 값인 0x1.999999999999ap-4로 저장됩니다. 십진수로 표시된 해당 값은 0.1000000000000000055511151231257827021181583404541015625 입니다.

참고

파이썬 3.2 이후부터는, Decimal 인스턴스를 float에서 직접 생성할 수 있습니다.

>>> Decimal.from_float(0.1)
Decimal('0.1000000000000000055511151231257827021181583404541015625')
>>> Decimal.from_float(float('nan'))
Decimal('NaN')
>>> Decimal.from_float(float('inf'))
Decimal('Infinity')
>>> Decimal.from_float(float('-inf'))
Decimal('-Infinity')

버전 3.1에 추가.

fma(other, third, context=None)

합성된 곱셈-덧셈(fused multiply-add). 중간값 self*other의 자리 올림 없이 self*other+third를 반환합니다.

>>> Decimal(2).fma(3, 5)
Decimal('11')

is_canonical()

인자가 규범적이면 True를 반환하고, 그렇지 않으면 False를 반환합니다. 현재 Decimal 인스턴스는 항상 규범적이므로 이 연산은 항상 True를 반환합니다.

is_finite()

인자가 유한 수이면 True를 반환하고, 인자가 무한대나 NaN 이면 False를 반환합니다.

is_infinite()

인자가 양이나 음의 무한대면 True를 반환하고, 그렇지 않으면 False를 반환합니다.

is_nan()

인자가 (조용한 또는 신호를 주는) NaN이면 True를 반환하고, 그렇지 않으면 False를 반환합니다.

is_normal(context=None)

인자가 정상(normal) 유한 수이면 True를 반환합니다. 인자가 0, 비정상(subnormal), 무한대 또는 NaN 이면 False를 반환합니다.

is_qnan()

인자가 조용한 NaN이면 True를 반환하고, 그렇지 않으면 False를 반환합니다.

is_signed()

인자가 음의 부호를 가지면 True를 반환하고, 그렇지 않으면 False를 반환합니다. 0과 NaN 모두 부호를 가질 수 있다는 것에 유의하세요.

is_snan()

인자가 신호를 주는 NaN이면 True를 반환하고, 그렇지 않으면 False를 반환합니다.

is_subnormal(context=None)

인자가 비정상(subnormal)이면 True를 반환하고, 그렇지 않으면 False를 반환합니다.

is_zero()

인자가 (양 또는 음의) 0이면 True를 반환하고, 그렇지 않으면 False를 반환합니다.

ln(context=None)

피연산자의 자연로그(밑 e)를 반환합니다. 결과는 ROUND_HALF_EVEN 자리 올림 모드를 사용하여 올바르게 반올림됩니다.

log10(context=None)

피연산자의 상용로그를 반환합니다. 결과는 ROUND_HALF_EVEN 자리 올림 모드를 사용하여 올바르게 반올림됩니다.

logb(context=None)

0이 아닌 수의 경우, 피연산자의 조정된 지수를 Decimal 인스턴스로 반환합니다. 피연산자가 0이면 Decimal('-Infinity') 가 반환되고 DivisionByZero 플래그가 발생합니다. 피연산자가 무한대면 Decimal('Infinity') 가 반환됩니다.

logical_and(other, context=None)

logical_and() 는 두 개의 논리적 피연산자(논리적 피연산자를 보세요)를 취하는 논리적 연산입니다. 결과는 두 피연산자의 자릿수별 and 입니다.

logical_invert(context=None)

logical_invert() 는 논리적 연산입니다. 결과는 피연산자의 자릿수별 반전입니다.

logical_or(other, context=None)

logical_or() 는 두 개의 논리적 피연산자(논리적 피연산자를 보세요)를 취하는 논리적 연산입니다. 결과는 두 피연산자의 자릿수별 or 입니다.

logical_xor(other, context=None)

logical_xor()은 두 개의 논리적 피연산자(논리적 피연산자를 보세요)를 취하는 논리적 연산입니다. 결과는 두 피연산자의 자릿수별 배타적 or입니다.

max(other, context=None)

컨텍스트 자리 올림 규칙이 반환되기 전에 적용되고 NaN 값이 (컨텍스트와 신호를 주는지 조용한지에 따라) 신호를 주거나 무시되는 것을 제외하고 max(self, other) 와 같습니다.

max_mag(other, context=None)

max()와 비슷하지만, 피연산자의 절댓값을 사용하여 비교가 이루어집니다.

min(other, context=None)

컨텍스트 자리 올림 규칙이 반환되기 전에 적용되고 NaN 값이 (컨텍스트와 신호를 주는지 조용한지에 따라) 신호를 주거나 무시되는 것을 제외하고 min(self, other) 와 같습니다.

min_mag(other, context=None)

min()과 비슷하지만, 피연산자의 절댓값을 사용하여 비교가 이루어집니다.

next_minus(context=None)

주어진 피연산자보다 작고, 주어진 컨텍스트(또는 context가 주어지지 않으면 현재 스레드의 컨텍스트)에서 표현 가능한 가장 큰 수를 돌려줍니다.

next_plus(context=None)

주어진 피연산자보다 크고, 주어진 컨텍스트(또는 context가 주어지지 않으면 현재 스레드의 컨텍스트)에서 표현 가능한 가장 작은 수를 돌려줍니다.

next_toward(other, context=None)

두 피연산자가 같지 않으면, 두 번째 피연산자의 방향으로 첫 번째 피연산자에 가장 가까운 숫자를 반환합니다. 두 피연산자가 수치로 같으면, 첫 번째 피연산자의 복사본을 반환하는데, 부호를 두 번째 피연산자의 것으로 설정합니다.

normalize(context=None)

가장 오른쪽 끝에 오는 0을 제거하고 결과를 Decimal('0')과 같은 모든 결과를 Decimal('0e0')으로 변환하여 숫자를 정규화합니다. 등가 클래스의 어트리뷰트에 대한 규범적인 값을 만드는 데 사용됩니다. 예를 들어, Decimal('32.100') 과 Decimal('0.321000e+2') 는 모두 같은 값인 Decimal('32.1') 로 정규화됩니다.

number_class(context=None)

피연산자의 클래스 를 설명하는 문자열을 반환합니다. 반환 값은 다음 10개의 문자열 중 하나입니다.

"-Infinity", 피연산자가 음의 무한대임을 나타냅니다.

"-Normal", 피연산자가 음의 정상 수임을 나타냅니다.

"-Subnormal", 피연산자가 음의 비정상 수임을 나타냅니다.

"-Zero", 피연산자가 음의 0임을 나타냅니다.

"+Zero", 피연산자가 양의 0임을 나타냅니다.

"+Subnormal", 피연산자가 양의 비정상 수임을 나타냅니다.

"+Normal", 피연산자가 양의 정상 수임을 나타냅니다.

"+Infinity", 피연산자가 양의 무한대임을 나타냅니다.

"NaN", 피연산자가 조용한 NaN(Not a Number)임을 나타냅니다.

"sNaN", 피연산자가 신호를 주는 NaN임을 나타냅니다.

quantize(exp, rounding=None, context=None)

자리 올림 후에 첫 번째 피연산자와 같고 두 번째 피연산자의 지수를 갖는 값을 반환합니다.

>>> Decimal('1.41421356').quantize(Decimal('1.000'))
Decimal('1.414')

다른 연산과 달리, quantize 연산 후의 계수의 길이가 정밀도보다 크면, InvalidOperation 신호를 줍니다. 이는, 에러 조건이 없으면, quantize 된 지수가 항상 오른쪽 피연산자의 지수와 같음을 보장합니다.

또한, 다른 연산과는 달리, 결과가 비정상(subnormal)이고 부정확한 경우조차도, quantize는 결코 Underflow 신호를 보내지 않습니다.

두 번째 피연산자의 지수가 첫 번째 피연산자의 지수보다 크면 자리 올림이 필요할 수 있습니다. 이 경우, 자리 올림 모드는 (주어지면) rounding 인자에 의해 결정됩니다. 그렇지 않으면 주어진 context 인자에 의해 결정됩니다; 두 인자 모두 주어지지 않으면, 현재 스레드의 컨텍스트의 자리 올림 모드가 사용됩니다.

결과 지수가 Emax 보다 크거나 Etiny 보다 작을 때마다 에러가 반환됩니다.

radix()

Decimal 클래스가 모든 산술을 수행하는 진수(기수)인 Decimal(10) 을 반환합니다. 명세와의 호환성을 위해 포함됩니다.

remainder_near(other, context=None)

self 를 other 로 나눈 나머지를 반환합니다. 이것은 나머지의 절댓값을 최소화하기 위해 나머지의 부호가 선택된다는 점에서 self % other 와 다릅니다. 좀 더 정확히 말하면, 반환 값은 self - n * other 인데, 여기서 n 은 self / other 의 정확한 값에 가장 가까운 정수이고, 두 개의 정수와의 거리가 같으면 짝수가 선택됩니다.

결과가 0이면 그 부호는 self 의 부호가 됩니다.

>>> Decimal(18).remainder_near(Decimal(10))
Decimal('-2')
>>> Decimal(25).remainder_near(Decimal(10))
Decimal('5')
>>> Decimal(35).remainder_near(Decimal(10))
Decimal('-5')

rotate(other, context=None)

첫 번째 피연산자의 계수를 두 번째 피연산자로 지정된 양만큼 회전한 결과를 반환합니다. 두 번째 피연산자는 -precision에서 precision 범위의 정수여야 합니다. 두 번째 피연산자의 절댓값은 회전할 자리의 수를 나타냅니다. 두 번째 피연산자가 양수면 왼쪽으로 회전합니다; 그렇지 않으면 오른쪽으로 회전합니다. 필요하면 정밀도에 맞추기 위해 첫 번째 피연산자의 계수에 0이 왼쪽에 채워집니다. 첫 번째 피연산자의 부호와 지수는 변경되지 않습니다.

same_quantum(other, context=None)

self와 other가 같은 지수를 가졌는지 또는 둘 다 NaN 인지 검사합니다.

이 연산은 컨텍스트의 영향을 받지 않고, 조용합니다: 어떤 플래그도 변경되지 않고, 어떤 자리 올림도 수행되지 않습니다. 예외적으로, 두 번째 피연산자를 정확하게 변환할 수 없으면 C 버전은 InvalidOperation을 발생시킬 수 있습니다.

scaleb(other, context=None)

첫 번째 피연산자의 지수를 두 번째 피연산자만큼 조정한 값을 반환합니다. 달리 표현하면, 첫 번째 피연산자에 10**other 를 곱한 값을 반환합니다. 두 번째 피연산자는 정수여야 합니다.

shift(other, context=None)

첫 번째 피연산자의 계수를 두 번째 피연산자로 지정된 양만큼 이동한 결과를 반환합니다. 두 번째 피연산자는 -precision에서 precision 범위의 정수여야 합니다. 두 번째 피연산자의 절댓값은 이동할 자리의 수를 나타냅니다. 두 번째 피연산자가 양수면 왼쪽으로 이동합니다; 그렇지 않으면 오른쪽으로 이동합니다. 이동으로 인해 계수에 들어오는 숫자는 0입니다. 첫 번째 피연산자의 부호와 지수는 변경되지 않습니다.

sqrt(context=None)

인자의 제곱근을 완전한 정밀도로 반환합니다.

to_eng_string(context=None)

문자열로 변환합니다. 지수가 필요하면 공학 표기법을 사용합니다.

공학 표기법의 지수는 3의 배수입니다. 이렇게 하면 소수점 왼쪽에 최대 3자리를 남기게 되고, 하나나 두 개의 후행 0을 추가해야 할 수 있습니다.

예를 들어, 이 메서드는 Decimal('123E+1') 을 Decimal('1.23E+3') 으로 변환합니다.

to_integral(rounding=None, context=None)

to_integral_value() 메서드와 같습니다. to_integral 이름은 이전 버전과의 호환성을 위해 유지되었습니다.

to_integral_exact(rounding=None, context=None)

Inexact 나 Rounded 신호를 주면서 가장 가까운 정수로 자리 올림 합니다. 자리 올림 모드는 (주어지면) rounding 매개 변수에 의해, 그렇지 않으면 그렇지 않으면 context 에 의해 결정됩니다. 두 매개 변수 모두 지정되지 않으면, 현재 컨텍스트의 자리 올림 모드가 사용됩니다.

to_integral_value(rounding=None, context=None)

Inexact 나 Rounded 신호를 주지 않고 가장 가까운 정수로 자리 올림 합니다. 주어지면, rounding 을 적용합니다; 그렇지 않으면, 제공된 context 나 현재 컨텍스트의 자리 올림 방법을 사용합니다.

논리적 피연산자

logical_and(), logical_invert(), logical_or()와 logical_xor() 메서드는 인자가 논리적 피연산자 이길 기대합니다. 논리적 피연산자 는 지수와 부호가 모두 0이고 숫자는 모두 0 또는 1 인 Decimal 인스턴스입니다.

Context 객체

컨텍스트는 산술 연산을 위한 환경입니다. 정밀도를 제어하고, 자리 올림 규칙을 설정하며, 어떤 신호가 예외로 처리되는지 결정하고, 지수의 범위를 제한합니다.

각 스레드는 자신만의 현재 컨텍스트를 가지는데, getcontext() 와 setcontext() 함수를 사용하여 액세스하거나 변경합니다:

decimal.getcontext()

활성 스레드의 현재 컨텍스트를 돌려줍니다.

decimal.setcontext(c)

활성 스레드의 현재 컨텍스트를 c 로 설정합니다.

또한 with 문과 localcontext() 함수를 사용하여 활성 컨텍스트를 일시적으로 변경할 수 있습니다.

decimal.localcontext(ctx=None)

with-문으로 진입할 때 활성 스레드의 현재 컨텍스트를 ctx 의 복사본으로 설정하고, with-문을 빠져나올 때 이전의 컨텍스트를 복원하는 컨텍스트 관리자를 돌려줍니다. 컨텍스트를 지정하지 않으면 현재 컨텍스트의 복사본이 사용됩니다.

예를 들어, 다음 코드는 현재 십진 정밀도를 42자리로 설정하고, 계산을 수행한 다음, 이전 컨텍스트를 자동으로 복원합니다:

from decimal import localcontext

with localcontext() as ctx:
    ctx.prec = 42   # Perform a high precision calculation
    s = calculate_something()
s = +s  # Round the final result back to the default precision

아래에 설명된 Context 생성자를 사용하여 새로운 컨텍스트를 만들 수도 있습니다. 또한, 이 모듈은 세 가지 미리 만들어진 컨텍스트를 제공합니다:

class decimal.BasicContext

이것은 일반 십진 산술 명세에서 정의된 표준 컨텍스트입니다. 정밀도는 9로 설정됩니다. 자리 올림은 ROUND_HALF_UP으로 설정됩니다. 모든 플래그가 지워집니다. 모든 트랩은 Inexact, Rounded, Subnormal을 제외하고는 활성화됩니다 (예외로 처리됩니다).

많은 트랩이 활성화되었으므로, 이 컨텍스트는 디버깅에 유용합니다.

class decimal.ExtendedContext

이것은 일반 십진 산술 명세에서 정의된 표준 컨텍스트입니다. 정밀도는 9로 설정됩니다. 자리 올림은 ROUND_HALF_EVEN으로 설정됩니다. 모든 플래그가 지워집니다. 아무 트랩도 활성화되지 않습니다 (그래서 계산 중에 예외가 발생하지 않습니다).

트랩이 비활성화되었으므로, 이 컨텍스트는 예외를 발생시키기보다 NaN 이나 Infinity 의 결괏값을 선호하는 응용 프로그램에 유용합니다. 이는 응용 프로그램이 그렇지 않으면 프로그램을 중단시킬 수 있는 조건이 있는 경우에도 실행을 완료할 수 있도록 합니다.

class decimal.DefaultContext

이 컨텍스트는 새로운 컨텍스트의 프로토타입으로 Context 생성자에 의해 사용됩니다. 필드(가령 정밀도)를 변경하면 Context 생성자에 의해 생성된 새로운 컨텍스트에 대한 기본값을 변경하는 효과가 있습니다.

이 컨텍스트는 다중 스레드 환경에서 가장 유용합니다. 스레드가 시작되기 전에 필드 중 하나를 변경하면 시스템 전체의 기본값을 설정하는 효과가 있습니다. 스레드가 시작된 후에 필드를 변경하는 것은. 스레드 동기화를 통해 경쟁 조건을 방지해야 하므로 권장되지 않습니다.

단일 스레드 환경에서는, 이 컨텍스트를 아예 사용하지 않는 것이 좋습니다. 대신, 아래에 설명된 대로 명시적으로 컨텍스트를 만드십시오.

기본값은 prec=28, rounding=ROUND_HALF_EVEN 이고 Overflow, InvalidOperation, DivisionByZero 트랩이 활성화됩니다.

3개의 제공된 컨텍스트 외에도, 새로운 컨텍스트를 Context 생성자를 사용하여 만들 수 있습니다.

class decimal.Context(prec=None, rounding=None, Emin=None, Emax=None, capitals=None, clamp=None, flags=None, traps=None)

새로운 컨텍스트를 만듭니다. 필드가 지정되지 않았거나 None 이면, 기본값은 DefaultContext 에서 복사됩니다. flags 필드가 지정되지 않았거나 None 이면, 모든 플래그가 지워집니다.

prec 는 컨텍스트에서 산술 연산의 정밀도를 설정하는 [1, MAX_PREC] 범위의 정수입니다.

rounding 옵션은 자리 올림 모드 섹션에 나열된 상수 중 하나입니다.

traps 과 flags 필드는 설정할 신호를 나열합니다. 일반적으로, 새 컨텍스트는 트랩만 설정하고 플래그는 지워진 채로 두어야 합니다.

Emin 과 Emax 필드는 지수에 허용되는 한계를 지정하는 정수입니다. Emin 은 [MIN_EMIN, 0], Emax 는 [0, MAX_EMAX] 범위 내에 있어야 합니다.

capitals 필드는 0 또는 1(기본값)입니다. 1로 설정하면, 지수는 대문자 E와 함께 인쇄됩니다; 그렇지 않으면 소문자 e 가 사용됩니다: Decimal('6.02e+23').

clamp 필드는 0 (기본값) 또는 1 입니다. 1로 설정하면, 이 컨텍스트에서 표현할 수 있는 Decimal 인스턴스의 지수 e 는 Emin - prec + 1 <= e <= Emax - prec + 1 입니다. clamp 가 0 이면 더 약한 조건이 유지됩니다: Decimal 인스턴스의 조정된 최대 Emax 입니다. clamp 가 1 일 때, 큰 정상 수는, 가능할 때, 지수 제약 조건을 맞추기 위해 지수가 감소하고 해당 숫자만큼의 0이 계수에 더해집니다; 이것은 수의 값을 보존하지만 유효한 후미 0에 대한 정보를 잃어버립니다. 예를 들면:

>>> Context(prec=6, Emax=999, clamp=1).create_decimal('1.23e999')
Decimal('1.23000E+999')

1 의 clamp 값은 IEEE 754에 명시된 고정 폭 십진수 교환 형식과 호환되도록 합니다.

Context 클래스는 주어진 컨텍스트에서 직접 산술을 하는데 필요한 다수의 메서드뿐만 아니라 여러 가지 범용 메서드를 정의합니다. 이에 더해, 위에서 설명한 Decimal 메서드마다 (adjusted()와 as_tuple() 메서드는 예외입니다) 대응하는 Context 메서드가 있습니다. 예를 들어, Context 인스턴스 C 와 Decimal 인스턴스 x 에 대해서, C.exp(x) 는 x.exp(context=C) 와 동등합니다. 각각 Context 메서드는 Decimal 인스턴스가 받아들여지는 곳 어디에서나 파이썬 정수(int 의 인스턴스)를 받아들입니다.

clear_flags()

모든 플래그를 0으로 재설정합니다.

clear_traps()

모든 트랩을 0으로 재설정합니다.

버전 3.3에 추가.

copy()

컨텍스트의 복사본을 돌려줍니다.

copy_decimal(num)

Decimal 인스턴스 num의 복사본을 반환합니다.

create_decimal(num)

self 를 컨텍스트로 사용해서, num 으로 새 Decimal 인스턴스를 만듭니다. Decimal 생성자와 달리, 컨텍스트 정밀도, 자리 올림 방법, 플래그 및 트랩이 변환에 적용됩니다.

이는 상수가 보통 응용 프로그램에 필요한 것보다 더 큰 정밀도로 제공되기 때문에 유용합니다. 또 다른 이점은 자리 올림이 현재 정밀도를 초과하는 자릿수로 인한 의도하지 않은 결과를 즉시 제거한다는 것입니다. 다음 예제에서, 자리 올림 되지 않은 입력을 사용한다는 것은 합계에 0을 추가하면 결과가 달라질 수 있음을 의미합니다.:

>>> getcontext().prec = 3
>>> Decimal('3.4445') + Decimal('1.0023')
Decimal('4.45')
>>> Decimal('3.4445') + Decimal(0) + Decimal('1.0023')
Decimal('4.44')

이 메서드는 IBM 명세의 to-number 연산을 구현합니다. 인자가 문자열이면, 선행 또는 후행 공백이나 밑줄이 허용되지 않습니다.

create_decimal_from_float(f)

float f 로 새 Decimal 인스턴스를 만들지만, self 를 컨텍스트로 사용하여 자리 올림 합니다. Decimal.from_float() 클래스 메서드와는 달리, 컨텍스트 정밀도, 자리 올림 방법, 플래그 및 트랩이 변환에 적용됩니다.

>>> context = Context(prec=5, rounding=ROUND_DOWN)
>>> context.create_decimal_from_float(math.pi)
Decimal('3.1415')
>>> context = Context(prec=5, traps=[Inexact])
>>> context.create_decimal_from_float(math.pi)
Traceback (most recent call last):
    ...
decimal.Inexact: None

버전 3.1에 추가.

Etiny()

비정상 결과에 대한 최소 지수 값인 Emin - prec + 1 과 같은 값을 반환합니다. 언더 플로우가 발생하면, 지수는 Etiny 로 설정됩니다.

Etop()

Emax - prec + 1 과 같은 값을 반환합니다.

십진수로 작업하는 일반적인 접근법은 Decimal 인스턴스를 생성한 다음 활성 스레드의 현재 컨텍스트 내에서 진행되는 산술 연산을 적용하는 것입니다. 다른 방법은 특정 컨텍스트 내에서 계산하기 위해 컨텍스트 메서드를 사용하는 것입니다. 메서드는 Decimal 클래스의 메서드와 비슷하며 여기에서는 간단히 설명합니다.

abs(x)

x 의 절댓값을 돌려줍니다.

add(x, y)

x 와 y 의 합을 돌려줍니다.

canonical(x)

같은 Decimal 객체 x 를 반환합니다.

compare(x, y)

x 와 y 를 수치로 비교합니다.

compare_signal(x, y)

두 피연산자의 값을 수치로 비교합니다.

compare_total(x, y)

추상 표현을 사용하여 두 피연산자를 비교합니다.

compare_total_mag(x, y)

부호를 무시하고, 추상 표현을 사용하여 두 피연산자를 비교합니다.

copy_abs(x)

부호가 0으로 설정되어있는 x 의 복사본을 돌려줍니다.

copy_negate(x)

부호가 반전된 x 복사본을 반환합니다.

copy_sign(x, y)

y 에서 x 로 부호를 복사합니다.

divide(x, y)

x 를 y 로 나눈 값을 반환합니다.

divide_int(x, y)

x 를 y 로 나눈 후 정수로 잘라낸 값을 반환합니다.

divmod(x, y)

두 숫자를 나누고 결과의 정수 부분을 반환합니다.

exp(x)

e ** x를 반환합니다.

fma(x, y, z)

x 에 y 를 곱한 후 z 를 더한 값을 반환합니다.

is_canonical(x)

x 가 규범적일 경우 True를 반환합니다; 그렇지 않으면 False를 반환합니다.

is_finite(x)

x 가 유한이면 True를 반환합니다; 그렇지 않으면 False를 반환합니다.

is_infinite(x)

x 가 무한대면 True를 반환합니다; 그렇지 않으면 False를 반환합니다.

is_nan(x)

x 가 qNaN 이나 sNaN 이면 True를 반환합니다; 그렇지 않으면 False를 반환합니다.

is_normal(x)

x 가 정상 수면 True를 반환합니다; 그렇지 않으면 False를 반환합니다.

is_qnan(x)

x 가 조용한 NaN이면 True를 반환합니다; 그렇지 않으면 False를 반환합니다.

is_signed(x)

x 가 음수면 True를 반환합니다; 그렇지 않으면 False를 반환합니다.

is_snan(x)

x 가 신호를 주는 NaN 이면 True를 반환합니다; 그렇지 않으면 False를 반환합니다.

is_subnormal(x)

x 가 비정상이면 True를 반환합니다; 그렇지 않으면 False를 반환합니다.

is_zero(x)

x 가 0이면 True를 반환합니다; 그렇지 않으면 False를 반환합니다.

ln(x)

x 의 자연로그(밑 e)를 반환합니다.

log10(x)

x 의 상용로그를 반환합니다.

logb(x)

피연산자의 최상위 유효 숫자의 크기의 지수를 반환합니다.

logical_and(x, y)

각 피연산자의 자릿수별로 논리적 연산 and 를 적용합니다.

logical_invert(x)

x 의 모든 자릿수를 반전합니다.

logical_or(x, y)

각 피연산자의 자릿수별로 논리적 연산 or 를 적용합니다.

logical_xor(x, y)

각 피연산자의 자릿수별로 논리적 연산 xor 를 적용합니다.

max(x, y)

두 값을 수치로 비교해, 최댓값을 돌려줍니다.

max_mag(x, y)

부호를 무시하고 값을 수치로 비교합니다.

min(x, y)

두 값을 수치로 비교해, 최솟값을 돌려줍니다.

min_mag(x, y)

부호를 무시하고 값을 수치로 비교합니다.

minus(x)

minus는 파이썬에서 단항 접두사 빼기 연산자에 해당합니다.

multiply(x, y)

x 와 y 의 곱을 반환합니다.

next_minus(x)

x 보다 작고 표현 가능한 가장 큰 수를 반환합니다.

next_plus(x)

x 보다 크고 표현 가능한 가장 작은 수를 반환합니다.

next_toward(x, y)

y 방향으로 x 에 가장 가까운 숫자를 반환합니다.

normalize(x)

x 를 가장 간단한 형태로 환원합니다.

number_class(x)

x 의 클래스를 가리키는 문자열을 돌려줍니다.

plus(x)

plus는 파이썬에서 단항 접두사 더하기 연산자에 해당합니다. 이 연산은 컨텍스트 정밀도와 자리 올림을 적용하므로 항등 연산이 아닙니다.

power(x, y, modulo=None)

x 의 y 거듭제곱을 돌려줍니다. 주어지면 modulo 모듈로로 환원합니다.

두 인자로는 x**y 를 계산합니다. x 가 음수면 y 는 정수여야 합니다. y 가 정수이고 결과가 유한하고 ‘precision’ 자릿수로 정확하게 표현될 수 있지 않은 이상 결과는 부정확합니다. 컨텍스트의 자리 올림 모드가 사용됩니다. 결과는 항상 파이썬 버전에서 정확하게 자리 올림 됩니다.

버전 3.3에서 변경: C 모듈은 올바르게 자리 올림 된 exp()와 ln() 함수로 power()를 계산합니다. 결과는 잘 정의되어 있지만 “거의 항상 올바르게 자리 올림 될” 뿐입니다.

세 인자로는 (x**y) % modulo 를 계산합니다. 세 인자 형식의 경우, 인자에 다음과 같은 제한이 있습니다:

세 인자는 모두 정수여야 합니다.

y 는 음수가 아니어야 합니다.

x 나 y 중 적어도 하나는 0이 아니어야 합니다

modulo 는 0이 아니고 최대 ‘precision’ 자릿수를 가져야 합니다

Context.power(x, y, modulo) 의 결괏값은 무한 정밀도로 (x**y) % modulo 를 계산할 때 얻을 수 있는 값과 같지만, 더 효율적으로 계산됩니다. 결과의 지수는 x, y 및 modulo 의 지수와 관계없이 0입니다. 결과는 항상 정확합니다.

quantize(x, y)

y 의 지수를 가지는 (자리 올림 된) x 와 같은 값을 반환합니다.

radix()

Decimal이기 때문에 단지 10을 반환합니다, :)

remainder(x, y)

정수 나눗셈의 나머지를 반환합니다.

결과가 0이 아닐 때, 결과의 부호는 원래의 피제수와 같습니다.

remainder_near(x, y)

x - y * n 을 반환하는데, n 은 x / y 의 정확한 값에 가장 가까운 정수입니다 (결과가 0이면 그 부호는 x 의 부호가 됩니다).

rotate(x, y)

x 를 y 번 회전한 복사본을 반환합니다.

same_quantum(x, y)

두 피연산자의 지수가 같으면 True를 반환합니다.

scaleb(x, y)

첫 번째 피연산자의 지수에 두 번째 값을 더해서 반환합니다.

shift(x, y)

x 를 y 번 이동한 복사본을 반환합니다.

sqrt(x)

음이 아닌 수의 제곱근을 컨텍스트의 정밀도로 반환합니다.

subtract(x, y)

x 와 y 의 차를 돌려줍니다.

to_eng_string(x)

문자열로 변환합니다. 지수가 필요하면 공학 표기법을 사용합니다.

공학 표기법의 지수는 3의 배수입니다. 이렇게 하면 소수점 왼쪽에 최대 3자리를 남기게 되고, 하나나 두 개의 후행 0을 추가해야 할 수 있습니다.

to_integral_exact(x)

정수로 자리 올림 합니다.

to_sci_string(x)

과학 표기법을 사용하여 숫자를 문자열로 변환합니다.

상수

이 절의 상수는 C 모듈에서만 의미가 있습니다. 호환성을 위해 순수 파이썬 버전에도 포함되어 있습니다.

32-비트

64-비트

decimal.MAX_PREC

425000000

999999999999999999

decimal.MAX_EMAX

425000000

999999999999999999

decimal.MIN_EMIN

-425000000

-999999999999999999

decimal.MIN_ETINY

-849999999

-1999999999999999997

decimal.HAVE_THREADS

The value is True. Deprecated, because Python now always has threads.

버전 3.9부터 폐지.

decimal.HAVE_CONTEXTVAR

The default value is True. If Python is compiled --without-decimal-contextvar, the C version uses a thread-local rather than a coroutine-local context and the value is False. This is slightly faster in some nested context scenarios.

버전 3.9에 추가: backported to 3.7 and 3.8

자리 올림 모드

decimal.ROUND_CEILING

Infinity를 향해 올립니다.

decimal.ROUND_DOWN

0을 향해 자리 올림 합니다.

decimal.ROUND_FLOOR

-Infinity를 향해 내립니다.

decimal.ROUND_HALF_DOWN

가장 가까운 값으로 반올림하고, 동률이면 0에서 가까운 것을 선택합니다.

decimal.ROUND_HALF_EVEN

가장 가까운 값으로 반올림하고, 동률이면 짝수를 선택합니다.

decimal.ROUND_HALF_UP

가장 가까운 값으로 반올림하고, 동률이면 0에서 먼 것을 선택합니다.

decimal.ROUND_UP

0에서 먼 쪽으로 자리 올림 합니다.

decimal.ROUND_05UP

0을 향해 자리 올림 했을 때 마지막 숫자가 0이나 5면 0에서 먼 쪽으로 자리 올림 합니다. 그렇지 않으면 0을 향해 자리 올림 합니다.

신호

신호는 계산 중 발생하는 조건을 나타냅니다. 각각은 하나의 컨텍스트 플래그와 하나의 컨텍스트 트랩 활성화기에 대응합니다.

컨텍스트 플래그는 조건이 발생할 때마다 설정됩니다. 계산 후에, 플래그는 정보를 얻기 위한 목적으로 확인될 수 있습니다 (예를 들어, 계산이 정확한지를 판별하기 위해). 플래그를 확인한 후 다음 계산을 시작하기 전에 모든 플래그를 지우십시오.

컨텍스트의 트랩 활성화기가 신호에 대해 설정되면, 조건은 파이썬 예외를 일으킵니다. 예를 들어, DivisionByZero 트랩이 설정되면, 이 조건을 만날 때 DivisionByZero 예외가 발생합니다.

class decimal.Clamped

표현 제약 조건에 맞도록 지수를 변경했습니다.

일반적으로, 지수가 컨텍스트의 Emin과 Emax 한계를 벗어날 때 클램핑이 발생합니다. 가능하면, 계수에 0을 추가하여 지수를 줄입니다.

class decimal.DecimalException

다른 신호의 베이스 클래스이고 ArithmeticError 의 서브 클래스입니다.

class decimal.DivisionByZero

무한대가 아닌 숫자를 0으로 나눴다는 신호를 줍니다.

나눗셈, 모듈로 나눗셈 또는 음수로 숫자를 거듭제곱할 때 발생할 수 있습니다. 이 신호가 트랩 되지 않으면, 계산에 제공된 입력의 부호에 따라 Infinity 나 -Infinity를 돌려줍니다.

class decimal.Inexact

자리 올림이 발생했고 결과가 정확하지 않음을 나타냅니다.

자리 올림 도중 0이 아닌 숫자가 삭제된 경우 신호를 줍니다. 자리 올림 된 결과가 반환됩니다. 신호 플래그나 트랩은 결과가 정확하지 않을 때를 감지하는 데 사용됩니다.

class decimal.InvalidOperation

유효하지 않은 연산이 수행되었습니다.

의미가 없는 연산이 요청되었음을 나타냅니다. 트랩 되지 않으면, NaN 을 반환합니다. 가능한 원인은 다음과 같습니다:

Infinity - Infinity
0 * Infinity
Infinity / Infinity
x % 0
Infinity % x
sqrt(-x) and x > 0
0 ** 0
x ** (non-integer)
x ** Infinity

class decimal.Overflow

수치적 오버플로.

자리 올림 후에 지수가 Emax 보다 큼을 나타냅니다. 트랩 되지 않으면, 결과는 자리 올림 모드에 따라 달라지는데, 가장 큰 표현 가능한 유한 수로 안쪽으로 당기거나 Infinity를 향해 바깥쪽으로 자리 올림 됩니다. 두 경우 모두 Inexact와 Rounded 신호도 줍니다.

class decimal.Rounded

정보가 손실되지는 않았지만 자리 올림이 발생했습니다.

자리 올림이 자릿수를 버릴 때마다 신호를 줍니다; 그 자릿수가 0일 때도 그렇습니다 (가령 5.00을 5.0으로 자리 올림). 트랩 되지 않으면, 결과를 그대로 반환합니다. 이 신호는 유효숫자의 손실을 감지하는 데 사용됩니다.

class decimal.Subnormal

자리 올림 전에 지수가 Emin 보다 작습니다.

연산 결과가 비정상(지수가 너무 작음)일 때 발생합니다. 트랩 되지 않으면, 결과를 그대로 반환합니다.

class decimal.Underflow

결과가 0으로 자리 올림 되는 수치적 언더플로.

자리 올림에 의해 비정상 결과가 0으로 밀릴 때 발생합니다. Inexact와 Subnormal 신호도 줍니다.

class decimal.FloatOperation

float와 Decimal을 혼합하는 데 더 엄격한 의미를 사용합니다.

신호가 트랩되지 않으면 (기본값), Decimal 생성자, create_decimal() 및 모든 비교 연산자에서 float와 Decimal을 혼합 할 수 있습니다. 변환과 비교 모두 정확합니다. 복합 연산의 발생은 컨텍스트 플래그에 FloatOperation 을 설정하여 조용히 기록됩니다. from_float() 나 create_decimal_from_float() 를 사용한 명시적 변환은 플래그를 설정하지 않습니다.

그렇지 않으면 (신호가 트랩되면), 같음 비교와 명시적 변환만 조용히 수행됩니다. 다른 모든 혼합된 연산은 FloatOperation 을 발생시킵니다.

다음 표는 신호의 계층 구조를 요약한 것입니다:

exceptions.ArithmeticError(exceptions.Exception)
    DecimalException
        Clamped
        DivisionByZero(DecimalException, exceptions.ZeroDivisionError)
        Inexact
            Overflow(Inexact, Rounded)
            Underflow(Inexact, Rounded, Subnormal)
        InvalidOperation
        Rounded
        Subnormal
        FloatOperation(DecimalException, exceptions.TypeError)

부동 소수점 노트

증가시킨 정밀도로 자리 올림 오차 줄이기

십진 부동 소수점을 사용하면 십진수 표현 오차가 없어집니다 (0.1을 정확히 나타낼 수 있습니다); 그러나 0이 아닌 숫자가 고정된 정밀도를 초과할 때 일부 연산은 여전히 자리 올림 오차를 일으킬 수 있습니다.

자리 올림 오차의 효과는 거의 상쇄되는 양을 더하거나 빼는 것에 의해 증폭되어 유효숫자의 손실로 이어질 수 있습니다. Knuth는 불충분한 정밀도로 자리 올림 된 부동 소수점 산술로 인해 덧셈의 결합 법칙과 배분 법칙이 파괴되는 두 가지 사례를 제공합니다:

# Examples from Seminumerical Algorithms, Section 4.2.2.
>>> from decimal import Decimal, getcontext
>>> getcontext().prec = 8

>>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')
>>> (u + v) + w
Decimal('9.5111111')
>>> u + (v + w)
Decimal('10')

>>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')
>>> (u*v) + (u*w)
Decimal('0.01')
>>> u * (v+w)
Decimal('0.0060000')

decimal 모듈은 유효숫자의 손실을 피할 수 있을 만큼 정밀도를 확장함으로써 항등 관계를 복구할 수 있게 합니다 :

>>> getcontext().prec = 20
>>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')
>>> (u + v) + w
Decimal('9.51111111')
>>> u + (v + w)
Decimal('9.51111111')
>>>
>>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')
>>> (u*v) + (u*w)
Decimal('0.0060000')
>>> u * (v+w)
Decimal('0.0060000')

특수 값

decimal 모듈의 수 체계는 NaN, sNaN, -Infinity, Infinity와 두 개의 0 +0과 -0을 포함하는 특수 값을 제공합니다.

무한대는 다음과 같이 직접 생성될 수 있습니다: Decimal('Infinity'). 또한, DivisionByZero 신호가 트랩 되지 않을 때 0으로 나눠서 발생할 수 있습니다. 마찬가지로, Overflow 신호가 트랩 되지 않을 때, 무한대는 표현 가능한 가장 큰 수의 한계를 넘어서 자리 올림 된 결과가 될 수 있습니다.

무한대는 부호가 있고 (아핀) 산술 연산에 사용될 수 있는데, 매우 크고 불확정적(indeterminate)인 숫자로 취급됩니다. 예를 들어, 무한대에 상수를 더하면 또 다른 무한대를 줍니다.

어떤 연산은 불확정적이고, NaN 을 반환하거나, InvalidOperation 신호가 트랩 되면, 예외를 발생시킵니다. 예를 들어, 0/0 은 “숫자가 아님(not a number)”을 의미하는 NaN 을 반환합니다. 이 종류의 NaN 은 조용하고, 한 번 만들어지면 다른 연산에 포함될 때 항상 다른 NaN 을 생성합니다. 이 동작은 때때로 빠진 입력이 있는 일련의 계산에 유용할 수 있습니다 — 특정 결과를 잘못된 것으로 표시하면서 계산을 진행할 수 있도록 합니다.

다른 종류는 sNaN 인데, 모든 연산 후에 조용히 남아 있는 대신 신호를 줍니다. 이것은 유효하지 않은 결과가 특수한 처리를 위해 계산을 중단시켜야 할 때 유용한 반환 값입니다.

파이썬의 비교 연산자의 동작은 NaN 이 관련되어있을 때 약간 의외일 수 있습니다. 피연산자 중 하나가 조용하거나 신호를 주는 NaN 일 때, 같음 검사는 항상 False를 반환하고 (심지어 Decimal('NaN')==Decimal('NaN') 조차도), 다름 검사는 항상 True를 반환합니다. <, <=, > 또는 >= 연산자 중 하나를 사용하여 두 Decimal을 비교하려는 시도는 피연산자 중 어느 것이 든 NaN 이면 InvalidOperation 신호를 발생시킵니다. 이 신호가 트랩 되지 않으면 False를 반환합니다. 일반 십진 산술 명세는 직접 비교의 동작을 명시하지 않습니다; NaN 을 포함하는 비교를 위한 이러한 규칙은 IEEE 854 표준(섹션 5.7의 표 3을 보세요)에서 가져온 것입니다. 엄격한 표준 준수를 위해서는, 대신 compare() 및 compare-signal() 메서드를 사용하십시오.

부호 있는 0은 언더플로 하는 계산의 결과일 수 있습니다. 계산을 더 정밀하게 수행한다면 얻게 될 결과의 기호를 유지합니다. 크기가 0이기 때문에, 양과 음의 0은 같다고 취급되며 부호는 정보 용입니다.

서로 다른 부호를 갖는 부호 있는 0이 같은 것에 더해, 여전히 동등한 값이지만 다른 정밀도를 갖는 여러 표현이 존재합니다. 익숙해지는데 약간 시간이 필요합니다. 정규화된 부동 소수점 표현에 익숙한 사람들에게는, 다음 계산이 0과 같은 값을 반환한다는 것이 즉시 명백하지는 않습니다:

>>> 1 / Decimal('Infinity')
Decimal('0E-1000026')

스레드로 작업하기

getcontext() 함수는 스레드마다 다른 Context 객체에 접근합니다. 별도의 스레드 컨텍스트를 갖는다는 것은 스레드가 다른 스레드를 방해하지 않고 변경할 수 있음을 의미합니다 (가령 getcontext().prec=10).

마찬가지로, setcontext() 함수는 자동으로 대상을 현재 스레드에 할당합니다.

setcontext() 가 getcontext() 전에 호출되지 않았다면, getcontext() 는 현재 스레드에서 사용할 새로운 컨텍스트를 자동으로 생성합니다.

새 컨텍스트는 DefaultContext 라는 프로토타입 컨텍스트에서 복사됩니다. 각 스레드가 응용 프로그램 전체에서 같은 값을 사용하도록 기본값을 제어하려면, DefaultContext 객체를 직접 수정하십시오. getcontext() 를 호출하는 스레드 사이에 경쟁 조건이 없도록, 어떤 스레드가 시작되기 전에 수행되어야 합니다. 예를 들면:

# Set applicationwide defaults for all threads about to be launched
DefaultContext.prec = 12
DefaultContext.rounding = ROUND_DOWN
DefaultContext.traps = ExtendedContext.traps.copy()
DefaultContext.traps[InvalidOperation] = 1
setcontext(DefaultContext)

# Afterwards, the threads can be started
t1.start()
t2.start()
t3.start()
 . . .

조리법

다음은 유틸리티 함수로 사용되고 Decimal 클래스로 작업하는 방법을 보여주는 몇 가지 조리법입니다:

def moneyfmt(value, places=2, curr='', sep=',', dp='.',
             pos='', neg='-', trailneg=''):
    """Convert Decimal to a money formatted string.

    places:  required number of places after the decimal point
    curr:    optional currency symbol before the sign (may be blank)
    sep:     optional grouping separator (comma, period, space, or blank)
    dp:      decimal point indicator (comma or period)
             only specify as blank when places is zero
    pos:     optional sign for positive numbers: '+', space or blank
    neg:     optional sign for negative numbers: '-', '(', space or blank
    trailneg:optional trailing minus indicator:  '-', ')', space or blank

    >>> d = Decimal('-1234567.8901')
    >>> moneyfmt(d, curr='$')
    '-$1,234,567.89'
    >>> moneyfmt(d, places=0, sep='.', dp='', neg='', trailneg='-')
    '1.234.568-'
    >>> moneyfmt(d, curr='$', neg='(', trailneg=')')
    '($1,234,567.89)'
    >>> moneyfmt(Decimal(123456789), sep=' ')
    '123 456 789.00'
    >>> moneyfmt(Decimal('-0.02'), neg='<', trailneg='>')
    '<0.02>'

    """
    q = Decimal(10) ** -places      # 2 places --> '0.01'
    sign, digits, exp = value.quantize(q).as_tuple()
    result = []
    digits = list(map(str, digits))
    build, next = result.append, digits.pop
    if sign:
        build(trailneg)
    for i in range(places):
        build(next() if digits else '0')
    if places:
        build(dp)
    if not digits:
        build('0')
    i = 0
    while digits:
        build(next())
        i += 1
        if i == 3 and digits:
            i = 0
            build(sep)
    build(curr)
    build(neg if sign else pos)
    return ''.join(reversed(result))

def pi():
    """Compute Pi to the current precision.

    >>> print(pi())
    3.141592653589793238462643383

    """
    getcontext().prec += 2  # extra digits for intermediate steps
    three = Decimal(3)      # substitute "three=3.0" for regular floats
    lasts, t, s, n, na, d, da = 0, three, 3, 1, 0, 0, 24
    while s != lasts:
        lasts = s
        n, na = n+na, na+8
        d, da = d+da, da+32
        t = (t * n) / d
        s += t
    getcontext().prec -= 2
    return +s               # unary plus applies the new precision

def exp(x):
    """Return e raised to the power of x.  Result type matches input type.

    >>> print(exp(Decimal(1)))
    2.718281828459045235360287471
    >>> print(exp(Decimal(2)))
    7.389056098930650227230427461
    >>> print(exp(2.0))
    7.38905609893
    >>> print(exp(2+0j))
    (7.38905609893+0j)

    """
    getcontext().prec += 2
    i, lasts, s, fact, num = 0, 0, 1, 1, 1
    while s != lasts:
        lasts = s
        i += 1
        fact *= i
        num *= x
        s += num / fact
    getcontext().prec -= 2
    return +s

def cos(x):
    """Return the cosine of x as measured in radians.

    The Taylor series approximation works best for a small value of x.
    For larger values, first compute x = x % (2 * pi).

    >>> print(cos(Decimal('0.5')))
    0.8775825618903727161162815826
    >>> print(cos(0.5))
    0.87758256189
    >>> print(cos(0.5+0j))
    (0.87758256189+0j)

    """
    getcontext().prec += 2
    i, lasts, s, fact, num, sign = 0, 0, 1, 1, 1, 1
    while s != lasts:
        lasts = s
        i += 2
        fact *= i * (i-1)
        num *= x * x
        sign *= -1
        s += num / fact * sign
    getcontext().prec -= 2
    return +s

def sin(x):
    """Return the sine of x as measured in radians.

    The Taylor series approximation works best for a small value of x.
    For larger values, first compute x = x % (2 * pi).

    >>> print(sin(Decimal('0.5')))
    0.4794255386042030002732879352
    >>> print(sin(0.5))
    0.479425538604
    >>> print(sin(0.5+0j))
    (0.479425538604+0j)

    """
    getcontext().prec += 2
    i, lasts, s, fact, num, sign = 1, 0, x, 1, x, 1
    while s != lasts:
        lasts = s
        i += 2
        fact *= i * (i-1)
        num *= x * x
        sign *= -1
        s += num / fact * sign
    getcontext().prec -= 2
    return +s

Decimal FAQ

Q. decimal.Decimal('1234.5') 라고 입력하는 것은 귀찮은 일입니다. 대화형 인터프리터를 사용할 때 타자를 최소화할 방법이 있습니까?

A. 일부 사용자는 생성자를 하나의 문자로 축약합니다:

>>> D = decimal.Decimal
>>> D('1.23') + D('3.45')
Decimal('4.68')

Q. 소수점 두 자리의 고정 소수점 응용 프로그램에서, 일부 입력에 여러 자리가 있고 자리 올림 해야 합니다. 어떤 것은 여분의 자릿수가 없다고 가정되지만, 유효성 검사가 필요합니다. 어떤 방법을 사용해야 합니까?

A. quantize() 메서드는 고정된 소수 자릿수로 자리 올림 합니다. Inexact 트랩이 설정되면, 유효성 검사에도 유용합니다:

>>> TWOPLACES = Decimal(10) ** -2       # same as Decimal('0.01')

>>> # Round to two places
>>> Decimal('3.214').quantize(TWOPLACES)
Decimal('3.21')

>>> # Validate that a number does not exceed two places
>>> Decimal('3.21').quantize(TWOPLACES, context=Context(traps=[Inexact]))
Decimal('3.21')

>>> Decimal('3.214').quantize(TWOPLACES, context=Context(traps=[Inexact]))
Traceback (most recent call last):
   ...
Inexact: None

Q. 일단 유효한 두 자리 입력이 있으면, 응용 프로그램 전체에서 해당 불변성을 어떻게 유지합니까?

A. 정수로 더하기, 빼기 및 곱하기와 같은 일부 연산은 고정 소수점을 자동으로 보존합니다. 나눗셈과 정수가 아닌 수로 곱하는 것과 같은 다른 연산은, 소수점 이하 자릿수를 바꿀 것이고, 뒤에 quantize() 단계를 적용할 필요가 있습니다:

>>> a = Decimal('102.72')           # Initial fixed-point values
>>> b = Decimal('3.17')
>>> a + b                           # Addition preserves fixed-point
Decimal('105.89')
>>> a - b
Decimal('99.55')
>>> a * 42                          # So does integer multiplication
Decimal('4314.24')
>>> (a * b).quantize(TWOPLACES)     # Must quantize non-integer multiplication
Decimal('325.62')
>>> (b / a).quantize(TWOPLACES)     # And quantize division
Decimal('0.03')

고정 소수점 응용 프로그램을 개발할 때, quantize() 단계를 처리하는 함수를 정의하는 것이 편리합니다:

>>> def mul(x, y, fp=TWOPLACES):
...     return (x * y).quantize(fp)
>>> def div(x, y, fp=TWOPLACES):
...     return (x / y).quantize(fp)

>>> mul(a, b)                       # Automatically preserve fixed-point
Decimal('325.62')
>>> div(b, a)
Decimal('0.03')

Q. 같은 값을 표현하는 여러 가지 방법이 있습니다. 숫자 200, 200.000, 2E2, 그리고 02E+4 는 모두 다양한 정밀도로 같은 값을 가집니다. 이것들은 단일하게 인식할 수 있는 표준적인 값으로 변환할 방법이 있습니까?

A. the normalize() 메서드는 모든 해당 값을 단일 표현으로 매핑합니다:

>>> values = map(Decimal, '200 200.000 2E2 .02E+4'.split())
>>> [v.normalize() for v in values]
[Decimal('2E+2'), Decimal('2E+2'), Decimal('2E+2'), Decimal('2E+2')]

Q. 일부 십진수 값은 항상 지수 표기법으로 인쇄됩니다. 지수가 아닌 표현을 얻을 방법이 있습니까?

A. 일부 값의 경우, 지수 표기법만이 계수에 있는 유효 숫자를 나타낼 수 있습니다. 예를 들어 5.0E+3을 5000으로 표현하면 값은 일정하게 유지되지만, 원본의 두 자리 유효숫자를 표시할 수 없습니다.

응용 프로그램이 유효 숫자를 추적하는 데 신경 쓰지 않으면, 지수 및 후행 0을 제거하고 유효숫자를 잃지만, 값이 바뀌지 않도록 하기는 쉽습니다:

>>> def remove_exponent(d):
...     return d.quantize(Decimal(1)) if d == d.to_integral() else d.normalize()

>>> remove_exponent(Decimal('5E+3'))
Decimal('5000')

Q. 일반 float를 Decimal로 변환하는 방법이 있습니까?

A. 그렇습니다. 모든 이진 부동 소수점은 Decimal로 정확히 표현될 수 있습니다. 하지만 정확한 변환이 취하는 정밀도는 직관이 제안하는 것보다 더 클 수 있습니다:

>>> Decimal(math.pi)
Decimal('3.141592653589793115997963468544185161590576171875')

Q. 복잡한 계산에서, 정밀도가 부족하거나 자리 올림 이상이 발생하여 엉터리 결과를 얻지는 않았는지 확인하려면 어떻게 해야 합니까?

A. decimal 모듈은 결과를 쉽게 테스트할 수 있게 합니다. 가장 좋은 방법은 더 높은 정밀도와 다양한 자리 올림 모드를 사용하여 계산을 다시 실행하는 것입니다. 크게 다른 결과는 정밀도 부족, 자리 올림 모드 문제, 부적절한 입력 또는 수치가 불안정한 알고리즘을 나타냅니다.

컨텍스트 정밀도가 입력이 아닌 연산 결과에 적용된다는 사실을 확인했습니다. 다른 정밀도의 값을 혼합할 때 주의해야 할 것이 있습니까?

A. 그렇습니다. 원칙은 모든 값이 정확한 것으로 간주하므로 해당 값에 대한 산술도 마찬가지라는 것입니다. 결과 만 자리 올림 됩니다. 입력에 대한 이점은 “입력하는 것이 얻는 것”이라는 것입니다. 단점은 입력값을 자리 올림 하는 것을 잊어버리면 결과가 이상하게 보일 수 있다는 점입니다:

>>> getcontext().prec = 3
>>> Decimal('3.104') + Decimal('2.104')
Decimal('5.21')
>>> Decimal('3.104') + Decimal('0.000') + Decimal('2.104')
Decimal('5.20')

해법은 정밀도를 높이거나 단항 플러스 연산을 사용하여 입력의 자리 올림을 강제 수행하는 것입니다:

>>> getcontext().prec = 3
>>> +Decimal('1.23456789')      # unary plus triggers rounding
Decimal('1.23')

다른 방법으로, 입력은 Context.create_decimal() 메서드를 사용하여 생성 시에 자리 올림 될 수 있습니다:

>>> Context(prec=5, rounding=ROUND_DOWN).create_decimal('1.2345678')
Decimal('1.2345')

Q. CPython 구현은 커다란 수에서 빠릅니까?

A. 예. CPython 과 PyPy3 구현에서, decimal 모듈의 C/CFFI 버전은 임의의 정밀도로 올바르게 자리 올림 되는 십진 부동 소수점 산술을 위한 고속 libmpdec [https://www.bytereef.org/mpdecimal/doc/libmpdec/index.html] 라이브러리를 통합합니다. libmpdec는 중간 크기의 숫자에는 카라추바 곱셈(Karatsuba multiplication) [https://en.wikipedia.org/wiki/Karatsuba_algorithm]을 사용하고 매우 큰 숫자에는 수론적 변환(Number Theoretic Transform) [https://en.wikipedia.org/wiki/Discrete_Fourier_transform_(general)#Number-theoretic_transform]을 사용합니다. 하지만, 이 성능 향상을 실현하려면, 컨텍스트를 자리 올림 없는 계산으로 설정 해야 합니다.

>>> c = getcontext()
>>> c.prec = MAX_PREC
>>> c.Emax = MAX_EMAX
>>> c.Emin = MIN_EMIN

버전 3.3에 추가.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

숫자와 수학 모듈 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

숫자와 수학 모듈 »

|

fractions — 유리수

소스 코드: Lib/fractions.py [https://github.com/python/cpython/tree/3.7/Lib/fractions.py]

fractions 모듈은 유리수 산술을 지원합니다.

Fraction 인스턴스는 한 쌍의 정수, 다른 유리수 또는 문자열로 만들 수 있습니다.

class fractions.Fraction(numerator=0, denominator=1)

class fractions.Fraction(other_fraction)

class fractions.Fraction(float)

class fractions.Fraction(decimal)

class fractions.Fraction(string)

첫 번째 버전에서는 numerator 와 denominator가 numbers.Rational의 인스턴스이고, numerator/denominator 값의 새 Fraction 인스턴스를 반환합니다. denominator가 0이면, ZeroDivisionError를 발생시킵니다. 두 번째 버전에서는 other_fraction이 numbers.Rational의 인스턴스이고, 같은 값을 가진 Fraction 인스턴스를 반환합니다. 다음 두 버전은 float 나 decimal.Decimal 인스턴스를 받아들이고, 정확히 같은 값의 Fraction 인스턴스를 반환합니다. 이진 부동 소수점(부동 소수점 산술: 문제점 및 한계 참조)의 일반적인 문제로 인해, Fraction(1.1)에 대한 인자가 정확히 11/10이 아니므로, Fraction(1.1)는 흔히 기대하듯이 Fraction(11, 10)를 반환하지 않습니다. (그러나 아래의 limit_denominator() 메서드에 대한 설명서를 참조하십시오.) 생성자의 마지막 버전은 문자열이나 유니코드 인스턴스를 기대합니다. 이 인스턴스의 일반적인 형식은 다음과 같습니다:

[sign] numerator ['/' denominator]

이때, 선택적 sign은 ‘+’ 나 ‘-‘일 수 있으며 numerator 와 denominator(있다면)는 십진수 문자열입니다. 또한, 유한한 값을 나타내고 float 생성자에서 허용하는 모든 문자열은 Fraction 생성자에서도 허용됩니다. 모든 형식에서, 입력 문자열에는 선행과/이나 후행 공백이 있을 수도 있습니다. 여기 예제가 있습니다:

>>> from fractions import Fraction
>>> Fraction(16, -10)
Fraction(-8, 5)
>>> Fraction(123)
Fraction(123, 1)
>>> Fraction()
Fraction(0, 1)
>>> Fraction('3/7')
Fraction(3, 7)
>>> Fraction(' -3/7 ')
Fraction(-3, 7)
>>> Fraction('1.414213 \t\n')
Fraction(1414213, 1000000)
>>> Fraction('-.125')
Fraction(-1, 8)
>>> Fraction('7e-6')
Fraction(7, 1000000)
>>> Fraction(2.25)
Fraction(9, 4)
>>> Fraction(1.1)
Fraction(2476979795053773, 2251799813685248)
>>> from decimal import Decimal
>>> Fraction(Decimal('1.1'))
Fraction(11, 10)

Fraction 클래스는 추상 베이스 클래스 numbers.Rational를 상속하며, 그 클래스의 모든 메서드와 연산을 구현합니다. Fraction 인스턴스는 해시 가능하고, 불변으로 취급해야 합니다. 또한, Fraction에는 다음과 같은 프로퍼티와 메서드가 있습니다:

버전 3.2에서 변경: Fraction 생성자는 이제 float와 decimal.Decimal 인스턴스를 받아들입니다.

numerator

기약 분수로 나타낼 때 Fraction의 분자.

denominator

기약 분수로 나타낼 때 Fraction의 분모.

from_float(flt)

이 클래스 메서드는 float flt의 정확한 값을 나타내는 Fraction을 생성합니다. Fraction.from_float(0.3)가 Fraction(3, 10)와 같은 값이 아니라는 점에 유의하십시오.

참고

파이썬 3.2 이상에서는, float에서 직접 Fraction 인스턴스를 생성할 수도 있습니다.

from_decimal(dec)

이 클래스 메서드는 decimal.Decimal 인스턴스 dec의 정확한 값을 나타내는 Fraction을 생성합니다.

참고

파이썬 3.2 이상에서는, decimal.Decimal 인스턴스에서 직접 Fraction 인스턴스를 생성할 수도 있습니다.

limit_denominator(max_denominator=1000000)

분모가 최대 max_denominator인 self에 가장 가까운 Fraction을 찾아서 반환합니다. 이 메서드는 주어진 부동 소수점 수에 대한 유리한 근사를 찾는 데 유용합니다:

>>> from fractions import Fraction
>>> Fraction('3.1415926535897932').limit_denominator(1000)
Fraction(355, 113)

또는 float로 표현된 유리수를 복구할 때 유용합니다:

>>> from math import pi, cos
>>> Fraction(cos(pi/3))
Fraction(4503599627370497, 9007199254740992)
>>> Fraction(cos(pi/3)).limit_denominator()
Fraction(1, 2)
>>> Fraction(1.1).limit_denominator()
Fraction(11, 10)

__floor__()

가장 큰 int <= self를 반환합니다. 이 메서드는 math.floor() 함수를 통해 액세스할 수도 있습니다:

>>> from math import floor
>>> floor(Fraction(355, 113))
3

__ceil__()

가장 작은 int >= self를 반환합니다. 이 메서드는 math.ceil() 함수를 통해 액세스할 수도 있습니다.

__round__()

__round__(ndigits)

첫 번째 버전은 self에 가장 가까운 int를 반환하는데, 절반은 짝수로 자리 올림 합니다. 두 번째 버전은 self를 가장 가까운 Fraction(1, 10**ndigits)의 배수로 자리 올림 하는데 (ndigits가 음수면 논리적으로), 역시 짝수로 자리 올림 합니다. 이 메서드는 round() 함수를 통해 액세스할 수도 있습니다.

fractions.gcd(a, b)

정수 a와 b의 최대 공약수를 반환합니다. a 나 b가 0이 아니면, gcd(a, b)의 절댓값은 a와 b를 모두 나누는 가장 큰 정수입니다. b가 0이 아니면, gcd(a,b)는 b와 같은 부호를 가집니다; 그렇지 않으면 a의 부호를 취합니다. gcd(0, 0)는 0을 반환합니다.

버전 3.5부터 폐지: 대신 math.gcd()를 사용하십시오.

더 보기

모듈 numbers

숫자 계층을 구성하는 추상 베이스 클래스.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

숫자와 수학 모듈 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

숫자와 수학 모듈 »

|

random — Generate pseudo-random numbers

Source code: Lib/random.py [https://github.com/python/cpython/tree/3.7/Lib/random.py]

This module implements pseudo-random number generators for various distributions.

For integers, there is uniform selection from a range. For sequences, there is uniform selection of a random element, a function to generate a random permutation of a list in-place, and a function for random sampling without replacement.

On the real line, there are functions to compute uniform, normal (Gaussian), lognormal, negative exponential, gamma, and beta distributions. For generating distributions of angles, the von Mises distribution is available.

Almost all module functions depend on the basic function random(), which generates a random float uniformly in the semi-open range [0.0, 1.0). Python uses the Mersenne Twister as the core generator. It produces 53-bit precision floats and has a period of 2**19937-1. The underlying implementation in C is both fast and threadsafe. The Mersenne Twister is one of the most extensively tested random number generators in existence. However, being completely deterministic, it is not suitable for all purposes, and is completely unsuitable for cryptographic purposes.

The functions supplied by this module are actually bound methods of a hidden instance of the random.Random class. You can instantiate your own instances of Random to get generators that don’t share state.

Class Random can also be subclassed if you want to use a different basic generator of your own devising: in that case, override the random(), seed(), getstate(), and setstate() methods. Optionally, a new generator can supply a getrandbits() method — this allows randrange() to produce selections over an arbitrarily large range.

The random module also provides the SystemRandom class which uses the system function os.urandom() to generate random numbers from sources provided by the operating system.

경고

The pseudo-random generators of this module should not be used for security purposes. For security or cryptographic uses, see the secrets module.

더 보기

M. Matsumoto and T. Nishimura, “Mersenne Twister: A 623-dimensionally equidistributed uniform pseudorandom number generator”, ACM Transactions on Modeling and Computer Simulation Vol. 8, No. 1, January pp.3–30 1998.

Complementary-Multiply-with-Carry recipe [https://code.activestate.com/recipes/576707/] for a compatible alternative random number generator with a long period and comparatively simple update operations.

Bookkeeping functions

random.seed(a=None, version=2)

Initialize the random number generator.

If a is omitted or None, the current system time is used. If randomness sources are provided by the operating system, they are used instead of the system time (see the os.urandom() function for details on availability).

If a is an int, it is used directly.

With version 2 (the default), a str, bytes, or bytearray object gets converted to an int and all of its bits are used.

With version 1 (provided for reproducing random sequences from older versions of Python), the algorithm for str and bytes generates a narrower range of seeds.

버전 3.2에서 변경: Moved to the version 2 scheme which uses all of the bits in a string seed.

random.getstate()

Return an object capturing the current internal state of the generator. This object can be passed to setstate() to restore the state.

random.setstate(state)

state should have been obtained from a previous call to getstate(), and setstate() restores the internal state of the generator to what it was at the time getstate() was called.

random.getrandbits(k)

Returns a Python integer with k random bits. This method is supplied with the MersenneTwister generator and some other generators may also provide it as an optional part of the API. When available, getrandbits() enables randrange() to handle arbitrarily large ranges.

Functions for integers

random.randrange(stop)

random.randrange(start, stop[, step])

Return a randomly selected element from range(start, stop, step). This is equivalent to choice(range(start, stop, step)), but doesn’t actually build a range object.

The positional argument pattern matches that of range(). Keyword arguments should not be used because the function may use them in unexpected ways.

버전 3.2에서 변경: randrange() is more sophisticated about producing equally distributed values. Formerly it used a style like int(random()*n) which could produce slightly uneven distributions.

random.randint(a, b)

Return a random integer N such that a <= N <= b. Alias for randrange(a, b+1).

Functions for sequences

random.choice(seq)

Return a random element from the non-empty sequence seq. If seq is empty, raises IndexError.

random.choices(population, weights=None, *, cum_weights=None, k=1)

Return a k sized list of elements chosen from the population with replacement. If the population is empty, raises IndexError.

If a weights sequence is specified, selections are made according to the relative weights. Alternatively, if a cum_weights sequence is given, the selections are made according to the cumulative weights (perhaps computed using itertools.accumulate()). For example, the relative weights [10, 5, 30, 5] are equivalent to the cumulative weights [10, 15, 45, 50]. Internally, the relative weights are converted to cumulative weights before making selections, so supplying the cumulative weights saves work.

If neither weights nor cum_weights are specified, selections are made with equal probability. If a weights sequence is supplied, it must be the same length as the population sequence. It is a TypeError to specify both weights and cum_weights.

The weights or cum_weights can use any numeric type that interoperates with the float values returned by random() (that includes integers, floats, and fractions but excludes decimals).

For a given seed, the choices() function with equal weighting typically produces a different sequence than repeated calls to choice(). The algorithm used by choices() uses floating point arithmetic for internal consistency and speed. The algorithm used by choice() defaults to integer arithmetic with repeated selections to avoid small biases from round-off error.

버전 3.6에 추가.

random.shuffle(x[, random])

Shuffle the sequence x in place.

The optional argument random is a 0-argument function returning a random float in [0.0, 1.0); by default, this is the function random().

To shuffle an immutable sequence and return a new shuffled list, use sample(x, k=len(x)) instead.

Note that even for small len(x), the total number of permutations of x can quickly grow larger than the period of most random number generators. This implies that most permutations of a long sequence can never be generated. For example, a sequence of length 2080 is the largest that can fit within the period of the Mersenne Twister random number generator.

random.sample(population, k)

Return a k length list of unique elements chosen from the population sequence or set. Used for random sampling without replacement.

Returns a new list containing elements from the population while leaving the original population unchanged. The resulting list is in selection order so that all sub-slices will also be valid random samples. This allows raffle winners (the sample) to be partitioned into grand prize and second place winners (the subslices).

Members of the population need not be hashable or unique. If the population contains repeats, then each occurrence is a possible selection in the sample.

To choose a sample from a range of integers, use a range() object as an argument. This is especially fast and space efficient for sampling from a large population: sample(range(10000000), k=60).

If the sample size is larger than the population size, a ValueError is raised.

Real-valued distributions

The following functions generate specific real-valued distributions. Function parameters are named after the corresponding variables in the distribution’s equation, as used in common mathematical practice; most of these equations can be found in any statistics text.

random.random()

Return the next random floating point number in the range [0.0, 1.0).

random.uniform(a, b)

Return a random floating point number N such that a <= N <= b for a <= b and b <= N <= a for b < a.

The end-point value b may or may not be included in the range depending on floating-point rounding in the equation a + (b-a) * random().

random.triangular(low, high, mode)

Return a random floating point number N such that low <= N <= high and with the specified mode between those bounds. The low and high bounds default to zero and one. The mode argument defaults to the midpoint between the bounds, giving a symmetric distribution.

random.betavariate(alpha, beta)

Beta distribution. Conditions on the parameters are alpha > 0 and beta > 0. Returned values range between 0 and 1.

random.expovariate(lambd)

Exponential distribution. lambd is 1.0 divided by the desired mean. It should be nonzero. (The parameter would be called “lambda”, but that is a reserved word in Python.) Returned values range from 0 to positive infinity if lambd is positive, and from negative infinity to 0 if lambd is negative.

random.gammavariate(alpha, beta)

Gamma distribution. (Not the gamma function!) Conditions on the parameters are alpha > 0 and beta > 0.

The probability distribution function is:

          x ** (alpha - 1) * math.exp(-x / beta)
pdf(x) =  --------------------------------------
            math.gamma(alpha) * beta ** alpha

random.gauss(mu, sigma)

Gaussian distribution. mu is the mean, and sigma is the standard deviation. This is slightly faster than the normalvariate() function defined below.

random.lognormvariate(mu, sigma)

Log normal distribution. If you take the natural logarithm of this distribution, you’ll get a normal distribution with mean mu and standard deviation sigma. mu can have any value, and sigma must be greater than zero.

random.normalvariate(mu, sigma)

Normal distribution. mu is the mean, and sigma is the standard deviation.

random.vonmisesvariate(mu, kappa)

mu is the mean angle, expressed in radians between 0 and 2*pi, and kappa is the concentration parameter, which must be greater than or equal to zero. If kappa is equal to zero, this distribution reduces to a uniform random angle over the range 0 to 2*pi.

random.paretovariate(alpha)

Pareto distribution. alpha is the shape parameter.

random.weibullvariate(alpha, beta)

Weibull distribution. alpha is the scale parameter and beta is the shape parameter.

Alternative Generator

class random.Random([seed])

Class that implements the default pseudo-random number generator used by the random module.

class random.SystemRandom([seed])

Class that uses the os.urandom() function for generating random numbers from sources provided by the operating system. Not available on all systems. Does not rely on software state, and sequences are not reproducible. Accordingly, the seed() method has no effect and is ignored. The getstate() and setstate() methods raise NotImplementedError if called.

Notes on Reproducibility

Sometimes it is useful to be able to reproduce the sequences given by a pseudo random number generator. By re-using a seed value, the same sequence should be reproducible from run to run as long as multiple threads are not running.

Most of the random module’s algorithms and seeding functions are subject to change across Python versions, but two aspects are guaranteed not to change:

If a new seeding method is added, then a backward compatible seeder will be offered.

The generator’s random() method will continue to produce the same sequence when the compatible seeder is given the same seed.

Examples and Recipes

Basic examples:

>>> random()                             # Random float:  0.0 <= x < 1.0
0.37444887175646646

>>> uniform(2.5, 10.0)                   # Random float:  2.5 <= x < 10.0
3.1800146073117523

>>> expovariate(1 / 5)                   # Interval between arrivals averaging 5 seconds
5.148957571865031

>>> randrange(10)                        # Integer from 0 to 9 inclusive
7

>>> randrange(0, 101, 2)                 # Even integer from 0 to 100 inclusive
26

>>> choice(['win', 'lose', 'draw'])      # Single random element from a sequence
'draw'

>>> deck = 'ace two three four'.split()
>>> shuffle(deck)                        # Shuffle a list
>>> deck
['four', 'two', 'ace', 'three']

>>> sample([10, 20, 30, 40, 50], k=4)    # Four samples without replacement
[40, 10, 50, 30]

Simulations:

>>> # Six roulette wheel spins (weighted sampling with replacement)
>>> choices(['red', 'black', 'green'], [18, 18, 2], k=6)
['red', 'green', 'black', 'black', 'red', 'black']

>>> # Deal 20 cards without replacement from a deck of 52 playing cards
>>> # and determine the proportion of cards with a ten-value
>>> # (a ten, jack, queen, or king).
>>> deck = collections.Counter(tens=16, low_cards=36)
>>> seen = sample(list(deck.elements()), k=20)
>>> seen.count('tens') / 20
0.15

>>> # Estimate the probability of getting 5 or more heads from 7 spins
>>> # of a biased coin that settles on heads 60% of the time.
>>> def trial():
...     return choices('HT', cum_weights=(0.60, 1.00), k=7).count('H') >= 5
...
>>> sum(trial() for i in range(10000)) / 10000
0.4169

>>> # Probability of the median of 5 samples being in middle two quartiles
>>> def trial():
...     return 2500 <= sorted(choices(range(10000), k=5))[2] < 7500
...
>>> sum(trial() for i in range(10000)) / 10000
0.7958

Example of statistical bootstrapping [https://en.wikipedia.org/wiki/Bootstrapping_(statistics)] using resampling with replacement to estimate a confidence interval for the mean of a sample of size five:

# http://statistics.about.com/od/Applications/a/Example-Of-Bootstrapping.htm
from statistics import mean
from random import choices

data = 1, 2, 4, 4, 10
means = sorted(mean(choices(data, k=5)) for i in range(20))
print(f'The sample mean of {mean(data):.1f} has a 90% confidence '
      f'interval from {means[1]:.1f} to {means[-2]:.1f}')

Example of a resampling permutation test [https://en.wikipedia.org/wiki/Resampling_(statistics)#Permutation_tests] to determine the statistical significance or p-value [https://en.wikipedia.org/wiki/P-value] of an observed difference between the effects of a drug versus a placebo:

# Example from "Statistics is Easy" by Dennis Shasha and Manda Wilson
from statistics import mean
from random import shuffle

drug = [54, 73, 53, 70, 73, 68, 52, 65, 65]
placebo = [54, 51, 58, 44, 55, 52, 42, 47, 58, 46]
observed_diff = mean(drug) - mean(placebo)

n = 10000
count = 0
combined = drug + placebo
for i in range(n):
    shuffle(combined)
    new_diff = mean(combined[:len(drug)]) - mean(combined[len(drug):])
    count += (new_diff >= observed_diff)

print(f'{n} label reshufflings produced only {count} instances with a difference')
print(f'at least as extreme as the observed difference of {observed_diff:.1f}.')
print(f'The one-sided p-value of {count / n:.4f} leads us to reject the null')
print(f'hypothesis that there is no difference between the drug and the placebo.')

Simulation of arrival times and service deliveries in a single server queue:

from random import expovariate, gauss
from statistics import mean, median, stdev

average_arrival_interval = 5.6
average_service_time = 5.0
stdev_service_time = 0.5

num_waiting = 0
arrivals = []
starts = []
arrival = service_end = 0.0
for i in range(20000):
    if arrival <= service_end:
        num_waiting += 1
        arrival += expovariate(1.0 / average_arrival_interval)
        arrivals.append(arrival)
    else:
        num_waiting -= 1
        service_start = service_end if num_waiting else arrival
        service_time = gauss(average_service_time, stdev_service_time)
        service_end = service_start + service_time
        starts.append(service_start)

waits = [start - arrival for arrival, start in zip(arrivals, starts)]
print(f'Mean wait: {mean(waits):.1f}.  Stdev wait: {stdev(waits):.1f}.')
print(f'Median wait: {median(waits):.1f}.  Max wait: {max(waits):.1f}.')

더 보기

Statistics for Hackers [https://www.youtube.com/watch?v=Iq9DzN6mvYA] a video tutorial by Jake Vanderplas [https://us.pycon.org/2016/speaker/profile/295/] on statistical analysis using just a few fundamental concepts including simulation, sampling, shuffling, and cross-validation.

Economics Simulation [http://nbviewer.jupyter.org/url/norvig.com/ipython/Economics.ipynb] a simulation of a marketplace by Peter Norvig [http://norvig.com/bio.html] that shows effective use of many of the tools and distributions provided by this module (gauss, uniform, sample, betavariate, choice, triangular, and randrange).

A Concrete Introduction to Probability (using Python) [http://nbviewer.jupyter.org/url/norvig.com/ipython/Probability.ipynb] a tutorial by Peter Norvig [http://norvig.com/bio.html] covering the basics of probability theory, how to write simulations, and how to perform data analysis using Python.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

숫자와 수학 모듈 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

숫자와 수학 모듈 »

|

statistics — Mathematical statistics functions

버전 3.4에 추가.

Source code: Lib/statistics.py [https://github.com/python/cpython/tree/3.7/Lib/statistics.py]

This module provides functions for calculating mathematical statistics of numeric (Real-valued) data.

참고

Unless explicitly noted otherwise, these functions support int, float, decimal.Decimal and fractions.Fraction. Behaviour with other types (whether in the numeric tower or not) is currently unsupported. Mixed types are also undefined and implementation-dependent. If your input data consists of mixed types, you may be able to use map() to ensure a consistent result, e.g. map(float, input_data).

Averages and measures of central location

These functions calculate an average or typical value from a population or sample.

mean()

Arithmetic mean (“average”) of data.

harmonic_mean()

Harmonic mean of data.

median()

Median (middle value) of data.

median_low()

Low median of data.

median_high()

High median of data.

median_grouped()

Median, or 50th percentile, of grouped data.

mode()

Mode (most common value) of discrete data.

Measures of spread

These functions calculate a measure of how much the population or sample tends to deviate from the typical or average values.

pstdev()

Population standard deviation of data.

pvariance()

Population variance of data.

stdev()

Sample standard deviation of data.

variance()

Sample variance of data.

Function details

Note: The functions do not require the data given to them to be sorted. However, for reading convenience, most of the examples show sorted sequences.

statistics.mean(data)

Return the sample arithmetic mean of data which can be a sequence or iterator.

The arithmetic mean is the sum of the data divided by the number of data points. It is commonly called “the average”, although it is only one of many different mathematical averages. It is a measure of the central location of the data.

If data is empty, StatisticsError will be raised.

Some examples of use:

>>> mean([1, 2, 3, 4, 4])
2.8
>>> mean([-1.0, 2.5, 3.25, 5.75])
2.625

>>> from fractions import Fraction as F
>>> mean([F(3, 7), F(1, 21), F(5, 3), F(1, 3)])
Fraction(13, 21)

>>> from decimal import Decimal as D
>>> mean([D("0.5"), D("0.75"), D("0.625"), D("0.375")])
Decimal('0.5625')

참고

The mean is strongly affected by outliers and is not a robust estimator for central location: the mean is not necessarily a typical example of the data points. For more robust, although less efficient, measures of central location, see median() and mode(). (In this case, “efficient” refers to statistical efficiency rather than computational efficiency.)

The sample mean gives an unbiased estimate of the true population mean, which means that, taken on average over all the possible samples, mean(sample) converges on the true mean of the entire population. If data represents the entire population rather than a sample, then mean(data) is equivalent to calculating the true population mean μ.

statistics.harmonic_mean(data)

Return the harmonic mean of data, a sequence or iterator of real-valued numbers.

The harmonic mean, sometimes called the subcontrary mean, is the reciprocal of the arithmetic mean() of the reciprocals of the data. For example, the harmonic mean of three values a, b and c will be equivalent to 3/(1/a + 1/b + 1/c).

The harmonic mean is a type of average, a measure of the central location of the data. It is often appropriate when averaging quantities which are rates or ratios, for example speeds. For example:

Suppose an investor purchases an equal value of shares in each of three companies, with P/E (price/earning) ratios of 2.5, 3 and 10. What is the average P/E ratio for the investor’s portfolio?

>>> harmonic_mean([2.5, 3, 10])  # For an equal investment portfolio.
3.6

Using the arithmetic mean would give an average of about 5.167, which is too high.

StatisticsError is raised if data is empty, or any element is less than zero.

버전 3.6에 추가.

statistics.median(data)

Return the median (middle value) of numeric data, using the common “mean of middle two” method. If data is empty, StatisticsError is raised. data can be a sequence or iterator.

The median is a robust measure of central location, and is less affected by the presence of outliers in your data. When the number of data points is odd, the middle data point is returned:

>>> median([1, 3, 5])
3

When the number of data points is even, the median is interpolated by taking the average of the two middle values:

>>> median([1, 3, 5, 7])
4.0

This is suited for when your data is discrete, and you don’t mind that the median may not be an actual data point.

If your data is ordinal (supports order operations) but not numeric (doesn’t support addition), you should use median_low() or median_high() instead.

더 보기

median_low(), median_high(), median_grouped()

statistics.median_low(data)

Return the low median of numeric data. If data is empty, StatisticsError is raised. data can be a sequence or iterator.

The low median is always a member of the data set. When the number of data points is odd, the middle value is returned. When it is even, the smaller of the two middle values is returned.

>>> median_low([1, 3, 5])
3
>>> median_low([1, 3, 5, 7])
3

Use the low median when your data are discrete and you prefer the median to be an actual data point rather than interpolated.

statistics.median_high(data)

Return the high median of data. If data is empty, StatisticsError is raised. data can be a sequence or iterator.

The high median is always a member of the data set. When the number of data points is odd, the middle value is returned. When it is even, the larger of the two middle values is returned.

>>> median_high([1, 3, 5])
3
>>> median_high([1, 3, 5, 7])
5

Use the high median when your data are discrete and you prefer the median to be an actual data point rather than interpolated.

statistics.median_grouped(data, interval=1)

Return the median of grouped continuous data, calculated as the 50th percentile, using interpolation. If data is empty, StatisticsError is raised. data can be a sequence or iterator.

>>> median_grouped([52, 52, 53, 54])
52.5

In the following example, the data are rounded, so that each value represents the midpoint of data classes, e.g. 1 is the midpoint of the class 0.5–1.5, 2 is the midpoint of 1.5–2.5, 3 is the midpoint of 2.5–3.5, etc. With the data given, the middle value falls somewhere in the class 3.5–4.5, and interpolation is used to estimate it:

>>> median_grouped([1, 2, 2, 3, 4, 4, 4, 4, 4, 5])
3.7

Optional argument interval represents the class interval, and defaults to 1. Changing the class interval naturally will change the interpolation:

>>> median_grouped([1, 3, 3, 5, 7], interval=1)
3.25
>>> median_grouped([1, 3, 3, 5, 7], interval=2)
3.5

This function does not check whether the data points are at least interval apart.

CPython implementation detail: Under some circumstances, median_grouped() may coerce data points to floats. This behaviour is likely to change in the future.

더 보기

“Statistics for the Behavioral Sciences”, Frederick J Gravetter and Larry B Wallnau (8th Edition).

The SSMEDIAN [https://help.gnome.org/users/gnumeric/stable/gnumeric.html#gnumeric-function-SSMEDIAN] function in the Gnome Gnumeric spreadsheet, including this discussion [https://mail.gnome.org/archives/gnumeric-list/2011-April/msg00018.html].

statistics.mode(data)

Return the most common data point from discrete or nominal data. The mode (when it exists) is the most typical value, and is a robust measure of central location.

If data is empty, or if there is not exactly one most common value, StatisticsError is raised.

mode assumes discrete data, and returns a single value. This is the standard treatment of the mode as commonly taught in schools:

>>> mode([1, 1, 2, 3, 3, 3, 3, 4])
3

The mode is unique in that it is the only statistic which also applies to nominal (non-numeric) data:

>>> mode(["red", "blue", "blue", "red", "green", "red", "red"])
'red'

statistics.pstdev(data, mu=None)

Return the population standard deviation (the square root of the population variance). See pvariance() for arguments and other details.

>>> pstdev([1.5, 2.5, 2.5, 2.75, 3.25, 4.75])
0.986893273527251

statistics.pvariance(data, mu=None)

Return the population variance of data, a non-empty iterable of real-valued numbers. Variance, or second moment about the mean, is a measure of the variability (spread or dispersion) of data. A large variance indicates that the data is spread out; a small variance indicates it is clustered closely around the mean.

If the optional second argument mu is given, it should be the mean of data. If it is missing or None (the default), the mean is automatically calculated.

Use this function to calculate the variance from the entire population. To estimate the variance from a sample, the variance() function is usually a better choice.

Raises StatisticsError if data is empty.

Examples:

>>> data = [0.0, 0.25, 0.25, 1.25, 1.5, 1.75, 2.75, 3.25]
>>> pvariance(data)
1.25

If you have already calculated the mean of your data, you can pass it as the optional second argument mu to avoid recalculation:

>>> mu = mean(data)
>>> pvariance(data, mu)
1.25

This function does not attempt to verify that you have passed the actual mean as mu. Using arbitrary values for mu may lead to invalid or impossible results.

Decimals and Fractions are supported:

>>> from decimal import Decimal as D
>>> pvariance([D("27.5"), D("30.25"), D("30.25"), D("34.5"), D("41.75")])
Decimal('24.815')

>>> from fractions import Fraction as F
>>> pvariance([F(1, 4), F(5, 4), F(1, 2)])
Fraction(13, 72)

참고

When called with the entire population, this gives the population variance σ². When called on a sample instead, this is the biased sample variance s², also known as variance with N degrees of freedom.

If you somehow know the true population mean μ, you may use this function to calculate the variance of a sample, giving the known population mean as the second argument. Provided the data points are representative (e.g. independent and identically distributed), the result will be an unbiased estimate of the population variance.

statistics.stdev(data, xbar=None)

Return the sample standard deviation (the square root of the sample variance). See variance() for arguments and other details.

>>> stdev([1.5, 2.5, 2.5, 2.75, 3.25, 4.75])
1.0810874155219827

statistics.variance(data, xbar=None)

Return the sample variance of data, an iterable of at least two real-valued numbers. Variance, or second moment about the mean, is a measure of the variability (spread or dispersion) of data. A large variance indicates that the data is spread out; a small variance indicates it is clustered closely around the mean.

If the optional second argument xbar is given, it should be the mean of data. If it is missing or None (the default), the mean is automatically calculated.

Use this function when your data is a sample from a population. To calculate the variance from the entire population, see pvariance().

Raises StatisticsError if data has fewer than two values.

Examples:

>>> data = [2.75, 1.75, 1.25, 0.25, 0.5, 1.25, 3.5]
>>> variance(data)
1.3720238095238095

If you have already calculated the mean of your data, you can pass it as the optional second argument xbar to avoid recalculation:

>>> m = mean(data)
>>> variance(data, m)
1.3720238095238095

This function does not attempt to verify that you have passed the actual mean as xbar. Using arbitrary values for xbar can lead to invalid or impossible results.

Decimal and Fraction values are supported:

>>> from decimal import Decimal as D
>>> variance([D("27.5"), D("30.25"), D("30.25"), D("34.5"), D("41.75")])
Decimal('31.01875')

>>> from fractions import Fraction as F
>>> variance([F(1, 6), F(1, 2), F(5, 3)])
Fraction(67, 108)

참고

This is the sample variance s² with Bessel’s correction, also known as variance with N-1 degrees of freedom. Provided that the data points are representative (e.g. independent and identically distributed), the result should be an unbiased estimate of the true population variance.

If you somehow know the actual population mean μ you should pass it to the pvariance() function as the mu parameter to get the variance of a sample.

Exceptions

A single exception is defined:

exception statistics.StatisticsError

Subclass of ValueError for statistics-related exceptions.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

숫자와 수학 모듈 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

|

함수형 프로그래밍 모듈

이 장에서 설명하는 모듈은 함수형 프로그래밍 스타일을 지원하는 함수 및 클래스와 콜러블에 대한 일반 연산을 제공합니다.

이 장에서는 다음 모듈에 관해 설명합니다:

itertools — Functions creating iterators for efficient looping

Itertool functions

Itertools Recipes

functools — Higher-order functions and operations on callable objects

partial Objects

operator — 함수로서의 표준 연산자

연산자를 함수에 매핑하기

제자리 연산자

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

함수형 프로그래밍 모듈 »

|

itertools — Functions creating iterators for efficient looping

This module implements a number of iterator building blocks inspired by constructs from APL, Haskell, and SML. Each has been recast in a form suitable for Python.

The module standardizes a core set of fast, memory efficient tools that are useful by themselves or in combination. Together, they form an “iterator algebra” making it possible to construct specialized tools succinctly and efficiently in pure Python.

For instance, SML provides a tabulation tool: tabulate(f) which produces a sequence f(0), f(1), .... The same effect can be achieved in Python by combining map() and count() to form map(f, count()).

These tools and their built-in counterparts also work well with the high-speed functions in the operator module. For example, the multiplication operator can be mapped across two vectors to form an efficient dot-product: sum(map(operator.mul, vector1, vector2)).

Infinite iterators:

Iterator

Arguments

Results

Example

count()

start, [step]

start, start+step, start+2*step, …

count(10) --> 10 11 12 13 14 ...

cycle()

p

p0, p1, … plast, p0, p1, …

cycle('ABCD') --> A B C D A B C D ...

repeat()

elem [,n]

elem, elem, elem, … endlessly or up to n times

repeat(10, 3) --> 10 10 10

Iterators terminating on the shortest input sequence:

Iterator

Arguments

Results

Example

accumulate()

p [,func]

p0, p0+p1, p0+p1+p2, …

accumulate([1,2,3,4,5]) --> 1 3 6 10 15

chain()

p, q, …

p0, p1, … plast, q0, q1, …

chain('ABC', 'DEF') --> A B C D E F

chain.from_iterable()

iterable

p0, p1, … plast, q0, q1, …

chain.from_iterable(['ABC', 'DEF']) --> A B C D E F

compress()

data, selectors

(d[0] if s[0]), (d[1] if s[1]), …

compress('ABCDEF', [1,0,1,0,1,1]) --> A C E F

dropwhile()

pred, seq

seq[n], seq[n+1], starting when pred fails

dropwhile(lambda x: x<5, [1,4,6,4,1]) --> 6 4 1

filterfalse()

pred, seq

elements of seq where pred(elem) is false

filterfalse(lambda x: x%2, range(10)) --> 0 2 4 6 8

groupby()

iterable[, key]

sub-iterators grouped by value of key(v)

islice()

seq, [start,] stop [, step]

elements from seq[start:stop:step]

islice('ABCDEFG', 2, None) --> C D E F G

starmap()

func, seq

func(*seq[0]), func(*seq[1]), …

starmap(pow, [(2,5), (3,2), (10,3)]) --> 32 9 1000

takewhile()

pred, seq

seq[0], seq[1], until pred fails

takewhile(lambda x: x<5, [1,4,6,4,1]) --> 1 4

tee()

it, n

it1, it2, … itn splits one iterator into n

zip_longest()

p, q, …

(p[0], q[0]), (p[1], q[1]), …

zip_longest('ABCD', 'xy', fillvalue='-') --> Ax By C- D-

Combinatoric iterators:

Iterator

Arguments

Results

product()

p, q, … [repeat=1]

cartesian product, equivalent to a nested for-loop

permutations()

p[, r]

r-length tuples, all possible orderings, no repeated elements

combinations()

p, r

r-length tuples, in sorted order, no repeated elements

combinations_with_replacement()

p, r

r-length tuples, in sorted order, with repeated elements

product('ABCD', repeat=2)

AA AB AC AD BA BB BC BD CA CB CC CD DA DB DC DD

permutations('ABCD', 2)

AB AC AD BA BC BD CA CB CD DA DB DC

combinations('ABCD', 2)

AB AC AD BC BD CD

combinations_with_replacement('ABCD', 2)

AA AB AC AD BB BC BD CC CD DD

Itertool functions

The following module functions all construct and return iterators. Some provide streams of infinite length, so they should only be accessed by functions or loops that truncate the stream.

itertools.accumulate(iterable[, func])

Make an iterator that returns accumulated sums, or accumulated results of other binary functions (specified via the optional func argument). If func is supplied, it should be a function of two arguments. Elements of the input iterable may be any type that can be accepted as arguments to func. (For example, with the default operation of addition, elements may be any addable type including Decimal or Fraction.) If the input iterable is empty, the output iterable will also be empty.

Roughly equivalent to:

def accumulate(iterable, func=operator.add):
    'Return running totals'
    # accumulate([1,2,3,4,5]) --> 1 3 6 10 15
    # accumulate([1,2,3,4,5], operator.mul) --> 1 2 6 24 120
    it = iter(iterable)
    try:
        total = next(it)
    except StopIteration:
        return
    yield total
    for element in it:
        total = func(total, element)
        yield total

There are a number of uses for the func argument. It can be set to min() for a running minimum, max() for a running maximum, or operator.mul() for a running product. Amortization tables can be built by accumulating interest and applying payments. First-order recurrence relations [https://en.wikipedia.org/wiki/Recurrence_relation] can be modeled by supplying the initial value in the iterable and using only the accumulated total in func argument:

>>> data = [3, 4, 6, 2, 1, 9, 0, 7, 5, 8]
>>> list(accumulate(data, operator.mul))     # running product
[3, 12, 72, 144, 144, 1296, 0, 0, 0, 0]
>>> list(accumulate(data, max))              # running maximum
[3, 4, 6, 6, 6, 9, 9, 9, 9, 9]

# Amortize a 5% loan of 1000 with 4 annual payments of 90
>>> cashflows = [1000, -90, -90, -90, -90]
>>> list(accumulate(cashflows, lambda bal, pmt: bal*1.05 + pmt))
[1000, 960.0, 918.0, 873.9000000000001, 827.5950000000001]

# Chaotic recurrence relation https://en.wikipedia.org/wiki/Logistic_map
>>> logistic_map = lambda x, _:  r * x * (1 - x)
>>> r = 3.8
>>> x0 = 0.4
>>> inputs = repeat(x0, 36)     # only the initial value is used
>>> [format(x, '.2f') for x in accumulate(inputs, logistic_map)]
['0.40', '0.91', '0.30', '0.81', '0.60', '0.92', '0.29', '0.79', '0.63',
 '0.88', '0.39', '0.90', '0.33', '0.84', '0.52', '0.95', '0.18', '0.57',
 '0.93', '0.25', '0.71', '0.79', '0.63', '0.88', '0.39', '0.91', '0.32',
 '0.83', '0.54', '0.95', '0.20', '0.60', '0.91', '0.30', '0.80', '0.60']

See functools.reduce() for a similar function that returns only the final accumulated value.

버전 3.2에 추가.

버전 3.3에서 변경: Added the optional func parameter.

itertools.chain(*iterables)

Make an iterator that returns elements from the first iterable until it is exhausted, then proceeds to the next iterable, until all of the iterables are exhausted. Used for treating consecutive sequences as a single sequence. Roughly equivalent to:

def chain(*iterables):
    # chain('ABC', 'DEF') --> A B C D E F
    for it in iterables:
        for element in it:
            yield element

classmethod chain.from_iterable(iterable)

Alternate constructor for chain(). Gets chained inputs from a single iterable argument that is evaluated lazily. Roughly equivalent to:

def from_iterable(iterables):
    # chain.from_iterable(['ABC', 'DEF']) --> A B C D E F
    for it in iterables:
        for element in it:
            yield element

itertools.combinations(iterable, r)

Return r length subsequences of elements from the input iterable.

Combinations are emitted in lexicographic sort order. So, if the input iterable is sorted, the combination tuples will be produced in sorted order.

Elements are treated as unique based on their position, not on their value. So if the input elements are unique, there will be no repeat values in each combination.

Roughly equivalent to:

def combinations(iterable, r):
    # combinations('ABCD', 2) --> AB AC AD BC BD CD
    # combinations(range(4), 3) --> 012 013 023 123
    pool = tuple(iterable)
    n = len(pool)
    if r > n:
        return
    indices = list(range(r))
    yield tuple(pool[i] for i in indices)
    while True:
        for i in reversed(range(r)):
            if indices[i] != i + n - r:
                break
        else:
            return
        indices[i] += 1
        for j in range(i+1, r):
            indices[j] = indices[j-1] + 1
        yield tuple(pool[i] for i in indices)

The code for combinations() can be also expressed as a subsequence of permutations() after filtering entries where the elements are not in sorted order (according to their position in the input pool):

def combinations(iterable, r):
    pool = tuple(iterable)
    n = len(pool)
    for indices in permutations(range(n), r):
        if sorted(indices) == list(indices):
            yield tuple(pool[i] for i in indices)

The number of items returned is n! / r! / (n-r)! when 0 <= r <= n or zero when r > n.

itertools.combinations_with_replacement(iterable, r)

Return r length subsequences of elements from the input iterable allowing individual elements to be repeated more than once.

Combinations are emitted in lexicographic sort order. So, if the input iterable is sorted, the combination tuples will be produced in sorted order.

Elements are treated as unique based on their position, not on their value. So if the input elements are unique, the generated combinations will also be unique.

Roughly equivalent to:

def combinations_with_replacement(iterable, r):
    # combinations_with_replacement('ABC', 2) --> AA AB AC BB BC CC
    pool = tuple(iterable)
    n = len(pool)
    if not n and r:
        return
    indices = [0] * r
    yield tuple(pool[i] for i in indices)
    while True:
        for i in reversed(range(r)):
            if indices[i] != n - 1:
                break
        else:
            return
        indices[i:] = [indices[i] + 1] * (r - i)
        yield tuple(pool[i] for i in indices)

The code for combinations_with_replacement() can be also expressed as a subsequence of product() after filtering entries where the elements are not in sorted order (according to their position in the input pool):

def combinations_with_replacement(iterable, r):
    pool = tuple(iterable)
    n = len(pool)
    for indices in product(range(n), repeat=r):
        if sorted(indices) == list(indices):
            yield tuple(pool[i] for i in indices)

The number of items returned is (n+r-1)! / r! / (n-1)! when n > 0.

버전 3.1에 추가.

itertools.compress(data, selectors)

Make an iterator that filters elements from data returning only those that have a corresponding element in selectors that evaluates to True. Stops when either the data or selectors iterables has been exhausted. Roughly equivalent to:

def compress(data, selectors):
    # compress('ABCDEF', [1,0,1,0,1,1]) --> A C E F
    return (d for d, s in zip(data, selectors) if s)

버전 3.1에 추가.

itertools.count(start=0, step=1)

Make an iterator that returns evenly spaced values starting with number start. Often used as an argument to map() to generate consecutive data points. Also, used with zip() to add sequence numbers. Roughly equivalent to:

def count(start=0, step=1):
    # count(10) --> 10 11 12 13 14 ...
    # count(2.5, 0.5) -> 2.5 3.0 3.5 ...
    n = start
    while True:
        yield n
        n += step

When counting with floating point numbers, better accuracy can sometimes be achieved by substituting multiplicative code such as: (start + step * i for i in count()).

버전 3.1에서 변경: Added step argument and allowed non-integer arguments.

itertools.cycle(iterable)

Make an iterator returning elements from the iterable and saving a copy of each. When the iterable is exhausted, return elements from the saved copy. Repeats indefinitely. Roughly equivalent to:

def cycle(iterable):
    # cycle('ABCD') --> A B C D A B C D A B C D ...
    saved = []
    for element in iterable:
        yield element
        saved.append(element)
    while saved:
        for element in saved:
              yield element

Note, this member of the toolkit may require significant auxiliary storage (depending on the length of the iterable).

itertools.dropwhile(predicate, iterable)

Make an iterator that drops elements from the iterable as long as the predicate is true; afterwards, returns every element. Note, the iterator does not produce any output until the predicate first becomes false, so it may have a lengthy start-up time. Roughly equivalent to:

def dropwhile(predicate, iterable):
    # dropwhile(lambda x: x<5, [1,4,6,4,1]) --> 6 4 1
    iterable = iter(iterable)
    for x in iterable:
        if not predicate(x):
            yield x
            break
    for x in iterable:
        yield x

itertools.filterfalse(predicate, iterable)

Make an iterator that filters elements from iterable returning only those for which the predicate is False. If predicate is None, return the items that are false. Roughly equivalent to:

def filterfalse(predicate, iterable):
    # filterfalse(lambda x: x%2, range(10)) --> 0 2 4 6 8
    if predicate is None:
        predicate = bool
    for x in iterable:
        if not predicate(x):
            yield x

itertools.groupby(iterable, key=None)

Make an iterator that returns consecutive keys and groups from the iterable. The key is a function computing a key value for each element. If not specified or is None, key defaults to an identity function and returns the element unchanged. Generally, the iterable needs to already be sorted on the same key function.

The operation of groupby() is similar to the uniq filter in Unix. It generates a break or new group every time the value of the key function changes (which is why it is usually necessary to have sorted the data using the same key function). That behavior differs from SQL’s GROUP BY which aggregates common elements regardless of their input order.

The returned group is itself an iterator that shares the underlying iterable with groupby(). Because the source is shared, when the groupby() object is advanced, the previous group is no longer visible. So, if that data is needed later, it should be stored as a list:

groups = []
uniquekeys = []
data = sorted(data, key=keyfunc)
for k, g in groupby(data, keyfunc):
    groups.append(list(g))      # Store group iterator as a list
    uniquekeys.append(k)

groupby() is roughly equivalent to:

class groupby:
    # [k for k, g in groupby('AAAABBBCCDAABBB')] --> A B C D A B
    # [list(g) for k, g in groupby('AAAABBBCCD')] --> AAAA BBB CC D
    def __init__(self, iterable, key=None):
        if key is None:
            key = lambda x: x
        self.keyfunc = key
        self.it = iter(iterable)
        self.tgtkey = self.currkey = self.currvalue = object()
    def __iter__(self):
        return self
    def __next__(self):
        self.id = object()
        while self.currkey == self.tgtkey:
            self.currvalue = next(self.it)    # Exit on StopIteration
            self.currkey = self.keyfunc(self.currvalue)
        self.tgtkey = self.currkey
        return (self.currkey, self._grouper(self.tgtkey, self.id))
    def _grouper(self, tgtkey, id):
        while self.id is id and self.currkey == tgtkey:
            yield self.currvalue
            try:
                self.currvalue = next(self.it)
            except StopIteration:
                return
            self.currkey = self.keyfunc(self.currvalue)

itertools.islice(iterable, stop)

itertools.islice(iterable, start, stop[, step])

Make an iterator that returns selected elements from the iterable. If start is non-zero, then elements from the iterable are skipped until start is reached. Afterward, elements are returned consecutively unless step is set higher than one which results in items being skipped. If stop is None, then iteration continues until the iterator is exhausted, if at all; otherwise, it stops at the specified position. Unlike regular slicing, islice() does not support negative values for start, stop, or step. Can be used to extract related fields from data where the internal structure has been flattened (for example, a multi-line report may list a name field on every third line). Roughly equivalent to:

def islice(iterable, *args):
    # islice('ABCDEFG', 2) --> A B
    # islice('ABCDEFG', 2, 4) --> C D
    # islice('ABCDEFG', 2, None) --> C D E F G
    # islice('ABCDEFG', 0, None, 2) --> A C E G
    s = slice(*args)
    start, stop, step = s.start or 0, s.stop or sys.maxsize, s.step or 1
    it = iter(range(start, stop, step))
    try:
        nexti = next(it)
    except StopIteration:
        # Consume *iterable* up to the *start* position.
        for i, element in zip(range(start), iterable):
            pass
        return
    try:
        for i, element in enumerate(iterable):
            if i == nexti:
                yield element
                nexti = next(it)
    except StopIteration:
        # Consume to *stop*.
        for i, element in zip(range(i + 1, stop), iterable):
            pass

If start is None, then iteration starts at zero. If step is None, then the step defaults to one.

itertools.permutations(iterable, r=None)

Return successive r length permutations of elements in the iterable.

If r is not specified or is None, then r defaults to the length of the iterable and all possible full-length permutations are generated.

Permutations are emitted in lexicographic sort order. So, if the input iterable is sorted, the permutation tuples will be produced in sorted order.

Elements are treated as unique based on their position, not on their value. So if the input elements are unique, there will be no repeat values in each permutation.

Roughly equivalent to:

def permutations(iterable, r=None):
    # permutations('ABCD', 2) --> AB AC AD BA BC BD CA CB CD DA DB DC
    # permutations(range(3)) --> 012 021 102 120 201 210
    pool = tuple(iterable)
    n = len(pool)
    r = n if r is None else r
    if r > n:
        return
    indices = list(range(n))
    cycles = list(range(n, n-r, -1))
    yield tuple(pool[i] for i in indices[:r])
    while n:
        for i in reversed(range(r)):
            cycles[i] -= 1
            if cycles[i] == 0:
                indices[i:] = indices[i+1:] + indices[i:i+1]
                cycles[i] = n - i
            else:
                j = cycles[i]
                indices[i], indices[-j] = indices[-j], indices[i]
                yield tuple(pool[i] for i in indices[:r])
                break
        else:
            return

The code for permutations() can be also expressed as a subsequence of product(), filtered to exclude entries with repeated elements (those from the same position in the input pool):

def permutations(iterable, r=None):
    pool = tuple(iterable)
    n = len(pool)
    r = n if r is None else r
    for indices in product(range(n), repeat=r):
        if len(set(indices)) == r:
            yield tuple(pool[i] for i in indices)

The number of items returned is n! / (n-r)! when 0 <= r <= n or zero when r > n.

itertools.product(*iterables, repeat=1)

Cartesian product of input iterables.

Roughly equivalent to nested for-loops in a generator expression. For example, product(A, B) returns the same as ((x,y) for x in A for y in B).

The nested loops cycle like an odometer with the rightmost element advancing on every iteration. This pattern creates a lexicographic ordering so that if the input’s iterables are sorted, the product tuples are emitted in sorted order.

To compute the product of an iterable with itself, specify the number of repetitions with the optional repeat keyword argument. For example, product(A, repeat=4) means the same as product(A, A, A, A).

This function is roughly equivalent to the following code, except that the actual implementation does not build up intermediate results in memory:

def product(*args, repeat=1):
    # product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
    # product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
    pools = [tuple(pool) for pool in args] * repeat
    result = [[]]
    for pool in pools:
        result = [x+[y] for x in result for y in pool]
    for prod in result:
        yield tuple(prod)

itertools.repeat(object[, times])

Make an iterator that returns object over and over again. Runs indefinitely unless the times argument is specified. Used as argument to map() for invariant parameters to the called function. Also used with zip() to create an invariant part of a tuple record.

Roughly equivalent to:

def repeat(object, times=None):
    # repeat(10, 3) --> 10 10 10
    if times is None:
        while True:
            yield object
    else:
        for i in range(times):
            yield object

A common use for repeat is to supply a stream of constant values to map or zip:

>>> list(map(pow, range(10), repeat(2)))
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

itertools.starmap(function, iterable)

Make an iterator that computes the function using arguments obtained from the iterable. Used instead of map() when argument parameters are already grouped in tuples from a single iterable (the data has been “pre-zipped”). The difference between map() and starmap() parallels the distinction between function(a,b) and function(*c). Roughly equivalent to:

def starmap(function, iterable):
    # starmap(pow, [(2,5), (3,2), (10,3)]) --> 32 9 1000
    for args in iterable:
        yield function(*args)

itertools.takewhile(predicate, iterable)

Make an iterator that returns elements from the iterable as long as the predicate is true. Roughly equivalent to:

def takewhile(predicate, iterable):
    # takewhile(lambda x: x<5, [1,4,6,4,1]) --> 1 4
    for x in iterable:
        if predicate(x):
            yield x
        else:
            break

itertools.tee(iterable, n=2)

Return n independent iterators from a single iterable.

The following Python code helps explain what tee does (although the actual implementation is more complex and uses only a single underlying FIFO queue).

Roughly equivalent to:

def tee(iterable, n=2):
    it = iter(iterable)
    deques = [collections.deque() for i in range(n)]
    def gen(mydeque):
        while True:
            if not mydeque:             # when the local deque is empty
                try:
                    newval = next(it)   # fetch a new value and
                except StopIteration:
                    return
                for d in deques:        # load it to all the deques
                    d.append(newval)
            yield mydeque.popleft()
    return tuple(gen(d) for d in deques)

Once tee() has made a split, the original iterable should not be used anywhere else; otherwise, the iterable could get advanced without the tee objects being informed.

tee iterators are not threadsafe. A RuntimeError may be raised when using simultaneously iterators returned by the same tee() call, even if the original iterable is threadsafe.

This itertool may require significant auxiliary storage (depending on how much temporary data needs to be stored). In general, if one iterator uses most or all of the data before another iterator starts, it is faster to use list() instead of tee().

itertools.zip_longest(*iterables, fillvalue=None)

Make an iterator that aggregates elements from each of the iterables. If the iterables are of uneven length, missing values are filled-in with fillvalue. Iteration continues until the longest iterable is exhausted. Roughly equivalent to:

def zip_longest(*args, fillvalue=None):
    # zip_longest('ABCD', 'xy', fillvalue='-') --> Ax By C- D-
    iterators = [iter(it) for it in args]
    num_active = len(iterators)
    if not num_active:
        return
    while True:
        values = []
        for i, it in enumerate(iterators):
            try:
                value = next(it)
            except StopIteration:
                num_active -= 1
                if not num_active:
                    return
                iterators[i] = repeat(fillvalue)
                value = fillvalue
            values.append(value)
        yield tuple(values)

If one of the iterables is potentially infinite, then the zip_longest() function should be wrapped with something that limits the number of calls (for example islice() or takewhile()). If not specified, fillvalue defaults to None.

Itertools Recipes

This section shows recipes for creating an extended toolset using the existing itertools as building blocks.

The extended tools offer the same high performance as the underlying toolset. The superior memory performance is kept by processing elements one at a time rather than bringing the whole iterable into memory all at once. Code volume is kept small by linking the tools together in a functional style which helps eliminate temporary variables. High speed is retained by preferring “vectorized” building blocks over the use of for-loops and generators which incur interpreter overhead.

def take(n, iterable):
    "Return first n items of the iterable as a list"
    return list(islice(iterable, n))

def prepend(value, iterator):
    "Prepend a single value in front of an iterator"
    # prepend(1, [2, 3, 4]) -> 1 2 3 4
    return chain([value], iterator)

def tabulate(function, start=0):
    "Return function(0), function(1), ..."
    return map(function, count(start))

def tail(n, iterable):
    "Return an iterator over the last n items"
    # tail(3, 'ABCDEFG') --> E F G
    return iter(collections.deque(iterable, maxlen=n))

def consume(iterator, n=None):
    "Advance the iterator n-steps ahead. If n is None, consume entirely."
    # Use functions that consume iterators at C speed.
    if n is None:
        # feed the entire iterator into a zero-length deque
        collections.deque(iterator, maxlen=0)
    else:
        # advance to the empty slice starting at position n
        next(islice(iterator, n, n), None)

def nth(iterable, n, default=None):
    "Returns the nth item or a default value"
    return next(islice(iterable, n, None), default)

def all_equal(iterable):
    "Returns True if all the elements are equal to each other"
    g = groupby(iterable)
    return next(g, True) and not next(g, False)

def quantify(iterable, pred=bool):
    "Count how many times the predicate is true"
    return sum(map(pred, iterable))

def padnone(iterable):
    """Returns the sequence elements and then returns None indefinitely.

    Useful for emulating the behavior of the built-in map() function.
    """
    return chain(iterable, repeat(None))

def ncycles(iterable, n):
    "Returns the sequence elements n times"
    return chain.from_iterable(repeat(tuple(iterable), n))

def dotproduct(vec1, vec2):
    return sum(map(operator.mul, vec1, vec2))

def flatten(listOfLists):
    "Flatten one level of nesting"
    return chain.from_iterable(listOfLists)

def repeatfunc(func, times=None, *args):
    """Repeat calls to func with specified arguments.

    Example:  repeatfunc(random.random)
    """
    if times is None:
        return starmap(func, repeat(args))
    return starmap(func, repeat(args, times))

def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return zip(a, b)

def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return zip_longest(*args, fillvalue=fillvalue)

def roundrobin(*iterables):
    "roundrobin('ABC', 'D', 'EF') --> A D E B F C"
    # Recipe credited to George Sakkis
    num_active = len(iterables)
    nexts = cycle(iter(it).__next__ for it in iterables)
    while num_active:
        try:
            for next in nexts:
                yield next()
        except StopIteration:
            # Remove the iterator we just exhausted from the cycle.
            num_active -= 1
            nexts = cycle(islice(nexts, num_active))

def partition(pred, iterable):
    'Use a predicate to partition entries into false entries and true entries'
    # partition(is_odd, range(10)) --> 0 2 4 6 8   and  1 3 5 7 9
    t1, t2 = tee(iterable)
    return filterfalse(pred, t1), filter(pred, t2)

def powerset(iterable):
    "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
    s = list(iterable)
    return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))

def unique_everseen(iterable, key=None):
    "List unique elements, preserving order. Remember all elements ever seen."
    # unique_everseen('AAAABBBCCDAABBB') --> A B C D
    # unique_everseen('ABBCcAD', str.lower) --> A B C D
    seen = set()
    seen_add = seen.add
    if key is None:
        for element in filterfalse(seen.__contains__, iterable):
            seen_add(element)
            yield element
    else:
        for element in iterable:
            k = key(element)
            if k not in seen:
                seen_add(k)
                yield element

def unique_justseen(iterable, key=None):
    "List unique elements, preserving order. Remember only the element just seen."
    # unique_justseen('AAAABBBCCDAABBB') --> A B C D A B
    # unique_justseen('ABBCcAD', str.lower) --> A B C A D
    return map(next, map(itemgetter(1), groupby(iterable, key)))

def iter_except(func, exception, first=None):
    """ Call a function repeatedly until an exception is raised.

    Converts a call-until-exception interface to an iterator interface.
    Like builtins.iter(func, sentinel) but uses an exception instead
    of a sentinel to end the loop.

    Examples:
        iter_except(functools.partial(heappop, h), IndexError)   # priority queue iterator
        iter_except(d.popitem, KeyError)                         # non-blocking dict iterator
        iter_except(d.popleft, IndexError)                       # non-blocking deque iterator
        iter_except(q.get_nowait, Queue.Empty)                   # loop over a producer Queue
        iter_except(s.pop, KeyError)                             # non-blocking set iterator

    """
    try:
        if first is not None:
            yield first()            # For database APIs needing an initial cast to db.first()
        while True:
            yield func()
    except exception:
        pass

def first_true(iterable, default=False, pred=None):
    """Returns the first true value in the iterable.

    If no true value is found, returns *default*

    If *pred* is not None, returns the first item
    for which pred(item) is true.

    """
    # first_true([a,b,c], x) --> a or b or c or x
    # first_true([a,b], x, f) --> a if f(a) else b if f(b) else x
    return next(filter(pred, iterable), default)

def random_product(*args, repeat=1):
    "Random selection from itertools.product(*args, **kwds)"
    pools = [tuple(pool) for pool in args] * repeat
    return tuple(random.choice(pool) for pool in pools)

def random_permutation(iterable, r=None):
    "Random selection from itertools.permutations(iterable, r)"
    pool = tuple(iterable)
    r = len(pool) if r is None else r
    return tuple(random.sample(pool, r))

def random_combination(iterable, r):
    "Random selection from itertools.combinations(iterable, r)"
    pool = tuple(iterable)
    n = len(pool)
    indices = sorted(random.sample(range(n), r))
    return tuple(pool[i] for i in indices)

def random_combination_with_replacement(iterable, r):
    "Random selection from itertools.combinations_with_replacement(iterable, r)"
    pool = tuple(iterable)
    n = len(pool)
    indices = sorted(random.randrange(n) for i in range(r))
    return tuple(pool[i] for i in indices)

def nth_combination(iterable, r, index):
    'Equivalent to list(combinations(iterable, r))[index]'
    pool = tuple(iterable)
    n = len(pool)
    if r < 0 or r > n:
        raise ValueError
    c = 1
    k = min(r, n-r)
    for i in range(1, k+1):
        c = c * (n - k + i) // i
    if index < 0:
        index += c
    if index < 0 or index >= c:
        raise IndexError
    result = []
    while r:
        c, n, r = c*r//n, n-1, r-1
        while index >= c:
            index -= c
            c, n = c*(n-r)//n, n-1
        result.append(pool[-1-n])
    return tuple(result)

Note, many of the above recipes can be optimized by replacing global lookups with local variables defined as default values. For example, the dotproduct recipe can be written as:

def dotproduct(vec1, vec2, sum=sum, map=map, mul=operator.mul):
    return sum(map(mul, vec1, vec2))

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

함수형 프로그래밍 모듈 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

함수형 프로그래밍 모듈 »

|

functools — Higher-order functions and operations on callable objects

Source code: Lib/functools.py [https://github.com/python/cpython/tree/3.7/Lib/functools.py]

The functools module is for higher-order functions: functions that act on or return other functions. In general, any callable object can be treated as a function for the purposes of this module.

The functools module defines the following functions:

functools.cmp_to_key(func)

Transform an old-style comparison function to a key function. Used with tools that accept key functions (such as sorted(), min(), max(), heapq.nlargest(), heapq.nsmallest(), itertools.groupby()). This function is primarily used as a transition tool for programs being converted from Python 2 which supported the use of comparison functions.

A comparison function is any callable that accept two arguments, compares them, and returns a negative number for less-than, zero for equality, or a positive number for greater-than. A key function is a callable that accepts one argument and returns another value to be used as the sort key.

Example:

sorted(iterable, key=cmp_to_key(locale.strcoll))  # locale-aware sort order

For sorting examples and a brief sorting tutorial, see 정렬 HOW TO.

버전 3.2에 추가.

@functools.lru_cache(maxsize=128, typed=False)

Decorator to wrap a function with a memoizing callable that saves up to the maxsize most recent calls. It can save time when an expensive or I/O bound function is periodically called with the same arguments.

Since a dictionary is used to cache results, the positional and keyword arguments to the function must be hashable.

Distinct argument patterns may be considered to be distinct calls with separate cache entries. For example, f(a=1, b=2) and f(b=2, a=1) differ in their keyword argument order and may have two separate cache entries.

If maxsize is set to None, the LRU feature is disabled and the cache can grow without bound. The LRU feature performs best when maxsize is a power-of-two.

If typed is set to true, function arguments of different types will be cached separately. For example, f(3) and f(3.0) will be treated as distinct calls with distinct results.

To help measure the effectiveness of the cache and tune the maxsize parameter, the wrapped function is instrumented with a cache_info() function that returns a named tuple showing hits, misses, maxsize and currsize. In a multi-threaded environment, the hits and misses are approximate.

The decorator also provides a cache_clear() function for clearing or invalidating the cache.

The original underlying function is accessible through the __wrapped__ attribute. This is useful for introspection, for bypassing the cache, or for rewrapping the function with a different cache.

An LRU (least recently used) cache [https://en.wikipedia.org/wiki/Cache_algorithms#Examples] works best when the most recent calls are the best predictors of upcoming calls (for example, the most popular articles on a news server tend to change each day). The cache’s size limit assures that the cache does not grow without bound on long-running processes such as web servers.

In general, the LRU cache should only be used when you want to reuse previously computed values. Accordingly, it doesn’t make sense to cache functions with side-effects, functions that need to create distinct mutable objects on each call, or impure functions such as time() or random().

Example of an LRU cache for static web content:

@lru_cache(maxsize=32)
def get_pep(num):
    'Retrieve text of a Python Enhancement Proposal'
    resource = 'http://www.python.org/dev/peps/pep-%04d/' % num
    try:
        with urllib.request.urlopen(resource) as s:
            return s.read()
    except urllib.error.HTTPError:
        return 'Not Found'

>>> for n in 8, 290, 308, 320, 8, 218, 320, 279, 289, 320, 9991:
...     pep = get_pep(n)
...     print(n, len(pep))

>>> get_pep.cache_info()
CacheInfo(hits=3, misses=8, maxsize=32, currsize=8)

Example of efficiently computing Fibonacci numbers [https://en.wikipedia.org/wiki/Fibonacci_number] using a cache to implement a dynamic programming [https://en.wikipedia.org/wiki/Dynamic_programming] technique:

@lru_cache(maxsize=None)
def fib(n):
    if n < 2:
        return n
    return fib(n-1) + fib(n-2)

>>> [fib(n) for n in range(16)]
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610]

>>> fib.cache_info()
CacheInfo(hits=28, misses=16, maxsize=None, currsize=16)

버전 3.2에 추가.

버전 3.3에서 변경: Added the typed option.

@functools.total_ordering

Given a class defining one or more rich comparison ordering methods, this class decorator supplies the rest. This simplifies the effort involved in specifying all of the possible rich comparison operations:

The class must define one of __lt__(), __le__(), __gt__(), or __ge__(). In addition, the class should supply an __eq__() method.

For example:

@total_ordering
class Student:
    def _is_valid_operand(self, other):
        return (hasattr(other, "lastname") and
                hasattr(other, "firstname"))
    def __eq__(self, other):
        if not self._is_valid_operand(other):
            return NotImplemented
        return ((self.lastname.lower(), self.firstname.lower()) ==
                (other.lastname.lower(), other.firstname.lower()))
    def __lt__(self, other):
        if not self._is_valid_operand(other):
            return NotImplemented
        return ((self.lastname.lower(), self.firstname.lower()) <
                (other.lastname.lower(), other.firstname.lower()))

참고

While this decorator makes it easy to create well behaved totally ordered types, it does come at the cost of slower execution and more complex stack traces for the derived comparison methods. If performance benchmarking indicates this is a bottleneck for a given application, implementing all six rich comparison methods instead is likely to provide an easy speed boost.

버전 3.2에 추가.

버전 3.4에서 변경: Returning NotImplemented from the underlying comparison function for unrecognised types is now supported.

functools.partial(func, *args, **keywords)

Return a new partial object which when called will behave like func called with the positional arguments args and keyword arguments keywords. If more arguments are supplied to the call, they are appended to args. If additional keyword arguments are supplied, they extend and override keywords. Roughly equivalent to:

def partial(func, *args, **keywords):
    def newfunc(*fargs, **fkeywords):
        newkeywords = keywords.copy()
        newkeywords.update(fkeywords)
        return func(*args, *fargs, **newkeywords)
    newfunc.func = func
    newfunc.args = args
    newfunc.keywords = keywords
    return newfunc

The partial() is used for partial function application which “freezes” some portion of a function’s arguments and/or keywords resulting in a new object with a simplified signature. For example, partial() can be used to create a callable that behaves like the int() function where the base argument defaults to two:

>>> from functools import partial
>>> basetwo = partial(int, base=2)
>>> basetwo.__doc__ = 'Convert base 2 string to an int.'
>>> basetwo('10010')
18

class functools.partialmethod(func, *args, **keywords)

Return a new partialmethod descriptor which behaves like partial except that it is designed to be used as a method definition rather than being directly callable.

func must be a descriptor or a callable (objects which are both, like normal functions, are handled as descriptors).

When func is a descriptor (such as a normal Python function, classmethod(), staticmethod(), abstractmethod() or another instance of partialmethod), calls to __get__ are delegated to the underlying descriptor, and an appropriate partial object returned as the result.

When func is a non-descriptor callable, an appropriate bound method is created dynamically. This behaves like a normal Python function when used as a method: the self argument will be inserted as the first positional argument, even before the args and keywords supplied to the partialmethod constructor.

Example:

>>> class Cell(object):
...     def __init__(self):
...         self._alive = False
...     @property
...     def alive(self):
...         return self._alive
...     def set_state(self, state):
...         self._alive = bool(state)
...     set_alive = partialmethod(set_state, True)
...     set_dead = partialmethod(set_state, False)
...
>>> c = Cell()
>>> c.alive
False
>>> c.set_alive()
>>> c.alive
True

버전 3.4에 추가.

functools.reduce(function, iterable[, initializer])

Apply function of two arguments cumulatively to the items of sequence, from left to right, so as to reduce the sequence to a single value. For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5). The left argument, x, is the accumulated value and the right argument, y, is the update value from the sequence. If the optional initializer is present, it is placed before the items of the sequence in the calculation, and serves as a default when the sequence is empty. If initializer is not given and sequence contains only one item, the first item is returned.

Roughly equivalent to:

def reduce(function, iterable, initializer=None):
    it = iter(iterable)
    if initializer is None:
        value = next(it)
    else:
        value = initializer
    for element in it:
        value = function(value, element)
    return value

@functools.singledispatch

Transform a function into a single-dispatch generic function.

To define a generic function, decorate it with the @singledispatch decorator. Note that the dispatch happens on the type of the first argument, create your function accordingly:

>>> from functools import singledispatch
>>> @singledispatch
... def fun(arg, verbose=False):
...     if verbose:
...         print("Let me just say,", end=" ")
...     print(arg)

To add overloaded implementations to the function, use the register() attribute of the generic function. It is a decorator. For functions annotated with types, the decorator will infer the type of the first argument automatically:

>>> @fun.register
... def _(arg: int, verbose=False):
...     if verbose:
...         print("Strength in numbers, eh?", end=" ")
...     print(arg)
...
>>> @fun.register
... def _(arg: list, verbose=False):
...     if verbose:
...         print("Enumerate this:")
...     for i, elem in enumerate(arg):
...         print(i, elem)

For code which doesn’t use type annotations, the appropriate type argument can be passed explicitly to the decorator itself:

>>> @fun.register(complex)
... def _(arg, verbose=False):
...     if verbose:
...         print("Better than complicated.", end=" ")
...     print(arg.real, arg.imag)
...

To enable registering lambdas and pre-existing functions, the register() attribute can be used in a functional form:

>>> def nothing(arg, verbose=False):
...     print("Nothing.")
...
>>> fun.register(type(None), nothing)

The register() attribute returns the undecorated function which enables decorator stacking, pickling, as well as creating unit tests for each variant independently:

>>> @fun.register(float)
... @fun.register(Decimal)
... def fun_num(arg, verbose=False):
...     if verbose:
...         print("Half of your number:", end=" ")
...     print(arg / 2)
...
>>> fun_num is fun
False

When called, the generic function dispatches on the type of the first argument:

>>> fun("Hello, world.")
Hello, world.
>>> fun("test.", verbose=True)
Let me just say, test.
>>> fun(42, verbose=True)
Strength in numbers, eh? 42
>>> fun(['spam', 'spam', 'eggs', 'spam'], verbose=True)
Enumerate this:
0 spam
1 spam
2 eggs
3 spam
>>> fun(None)
Nothing.
>>> fun(1.23)
0.615

Where there is no registered implementation for a specific type, its method resolution order is used to find a more generic implementation. The original function decorated with @singledispatch is registered for the base object type, which means it is used if no better implementation is found.

To check which implementation will the generic function choose for a given type, use the dispatch() attribute:

>>> fun.dispatch(float)
<function fun_num at 0x1035a2840>
>>> fun.dispatch(dict)    # note: default implementation
<function fun at 0x103fe0000>

To access all registered implementations, use the read-only registry attribute:

>>> fun.registry.keys()
dict_keys([<class 'NoneType'>, <class 'int'>, <class 'object'>,
          <class 'decimal.Decimal'>, <class 'list'>,
          <class 'float'>])
>>> fun.registry[float]
<function fun_num at 0x1035a2840>
>>> fun.registry[object]
<function fun at 0x103fe0000>

버전 3.4에 추가.

버전 3.7에서 변경: The register() attribute supports using type annotations.

functools.update_wrapper(wrapper, wrapped, assigned=WRAPPER_ASSIGNMENTS, updated=WRAPPER_UPDATES)

Update a wrapper function to look like the wrapped function. The optional arguments are tuples to specify which attributes of the original function are assigned directly to the matching attributes on the wrapper function and which attributes of the wrapper function are updated with the corresponding attributes from the original function. The default values for these arguments are the module level constants WRAPPER_ASSIGNMENTS (which assigns to the wrapper function’s __module__, __name__, __qualname__, __annotations__ and __doc__, the documentation string) and WRAPPER_UPDATES (which updates the wrapper function’s __dict__, i.e. the instance dictionary).

To allow access to the original function for introspection and other purposes (e.g. bypassing a caching decorator such as lru_cache()), this function automatically adds a __wrapped__ attribute to the wrapper that refers to the function being wrapped.

The main intended use for this function is in decorator functions which wrap the decorated function and return the wrapper. If the wrapper function is not updated, the metadata of the returned function will reflect the wrapper definition rather than the original function definition, which is typically less than helpful.

update_wrapper() may be used with callables other than functions. Any attributes named in assigned or updated that are missing from the object being wrapped are ignored (i.e. this function will not attempt to set them on the wrapper function). AttributeError is still raised if the wrapper function itself is missing any attributes named in updated.

버전 3.2에 추가: Automatic addition of the __wrapped__ attribute.

버전 3.2에 추가: Copying of the __annotations__ attribute by default.

버전 3.2에서 변경: Missing attributes no longer trigger an AttributeError.

버전 3.4에서 변경: The __wrapped__ attribute now always refers to the wrapped function, even if that function defined a __wrapped__ attribute. (see bpo-17482 [https://bugs.python.org/issue?@action=redirect&bpo=17482])

@functools.wraps(wrapped, assigned=WRAPPER_ASSIGNMENTS, updated=WRAPPER_UPDATES)

This is a convenience function for invoking update_wrapper() as a function decorator when defining a wrapper function. It is equivalent to partial(update_wrapper, wrapped=wrapped, assigned=assigned, updated=updated). For example:

>>> from functools import wraps
>>> def my_decorator(f):
...     @wraps(f)
...     def wrapper(*args, **kwds):
...         print('Calling decorated function')
...         return f(*args, **kwds)
...     return wrapper
...
>>> @my_decorator
... def example():
...     """Docstring"""
...     print('Called example function')
...
>>> example()
Calling decorated function
Called example function
>>> example.__name__
'example'
>>> example.__doc__
'Docstring'

Without the use of this decorator factory, the name of the example function would have been 'wrapper', and the docstring of the original example() would have been lost.

partial Objects

partial objects are callable objects created by partial(). They have three read-only attributes:

partial.func

A callable object or function. Calls to the partial object will be forwarded to func with new arguments and keywords.

partial.args

The leftmost positional arguments that will be prepended to the positional arguments provided to a partial object call.

partial.keywords

The keyword arguments that will be supplied when the partial object is called.

partial objects are like function objects in that they are callable, weak referencable, and can have attributes. There are some important differences. For instance, the __name__ and __doc__ attributes are not created automatically. Also, partial objects defined in classes behave like static methods and do not transform into bound methods during instance attribute look-up.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

함수형 프로그래밍 모듈 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

함수형 프로그래밍 모듈 »

|

operator — 함수로서의 표준 연산자

소스 코드: Lib/operator.py [https://github.com/python/cpython/tree/3.7/Lib/operator.py]

operator 모듈은 파이썬의 내장 연산자에 해당하는 효율적인 함수 집합을 내보냅니다. 예를 들어, operator.add(x, y)는 x+y 표현식과 동등합니다. 많은 함수 이름은 특수 메서드에 사용되는 이름인데, 이중 밑줄이 없습니다. 이전 버전과의 호환성을 위해, 이들 중 많은 것은 이중 밑줄이 있는 변형을 가집니다. 이중 밑줄이 없는 변형이 명확성을 위해 선호됩니다.

함수는 객체 비교, 논리 연산, 수학 연산 및 시퀀스 연산을 수행하는 범주로 분류됩니다.

객체 비교 함수는 모든 객체에 유용하며, 이들이 지원하는 풍부한 비교(rich comparison) 연산자의 이름을 따릅니다:

operator.lt(a, b)

operator.le(a, b)

operator.eq(a, b)

operator.ne(a, b)

operator.ge(a, b)

operator.gt(a, b)

operator.__lt__(a, b)

operator.__le__(a, b)

operator.__eq__(a, b)

operator.__ne__(a, b)

operator.__ge__(a, b)

operator.__gt__(a, b)

a와 b 사이에 “풍부한 비교(rich comparisons)”를 수행합니다. 구체적으로, lt(a, b)는 a < b와 동등하고, le(a, b)는 a <= b와 동등하고, eq(a, b)는 a == b와 동등하고, ne(a, b)는 a != b와 동등하고, gt(a, b)는 a > b와 동등하고, ge(a, b)는 a >= b와 동등합니다. 이러한 함수는 불리언 값으로 해석 할 수도 있고, 그렇지 않을 수도 있는 임의의 값을 반환 할 수 있음에 유의하십시오. 풍부한 비교에 대한 자세한 정보는 비교를 참조하십시오.

논리 연산도 일반적으로 모든 객체에 적용 할 수 있으며, 진릿값 검사, 아이덴티티 검사 및 불리언 연산을 지원합니다:

operator.not_(obj)

operator.__not__(obj)

not obj의 결과를 반환합니다. (객체 인스턴스에는 __not__() 메서드가 없음에 유의하십시오; 인터프리터의 코어만이 이 연산을 정의합니다. 결과는 __bool__()과 __len__() 메서드의 영향을 받습니다.)

operator.truth(obj)

obj가 참이면 True를 반환하고, 그렇지 않으면 False를 반환합니다. 이것은 bool 생성자를 사용하는 것과 동등합니다.

operator.is_(a, b)

a is b를 반환합니다. 객체 아이덴티티를 검사합니다.

operator.is_not(a, b)

a is not b를 반환합니다. 객체 아이덴티티를 검사합니다.

수학적 및 비트별 연산이 가장 많습니다:

operator.abs(obj)

operator.__abs__(obj)

obj의 절댓값을 반환합니다.

operator.add(a, b)

operator.__add__(a, b)

a와 b 숫자에 대해, a + b를 반환합니다.

operator.and_(a, b)

operator.__and__(a, b)

a와 b의 비트별 논리곱(and)을 반환합니다.

operator.floordiv(a, b)

operator.__floordiv__(a, b)

a // b를 반환합니다.

operator.index(a)

operator.__index__(a)

정수로 변환된 a를 반환합니다. a.__index__()와 동등합니다.

operator.inv(obj)

operator.invert(obj)

operator.__inv__(obj)

operator.__invert__(obj)

숫자 obj의 비트별 반전을 반환합니다. 이것은 ~obj와 동등합니다.

operator.lshift(a, b)

operator.__lshift__(a, b)

a를 b만큼 왼쪽으로 시프트 한 값을 반환합니다.

operator.mod(a, b)

operator.__mod__(a, b)

a % b를 반환합니다.

operator.mul(a, b)

operator.__mul__(a, b)

a와 b 숫자에 대해, a * b를 반환합니다.

operator.matmul(a, b)

operator.__matmul__(a, b)

a @ b를 반환합니다.

버전 3.5에 추가.

operator.neg(obj)

operator.__neg__(obj)

obj의 부정(-obj)을 반환합니다.

operator.or_(a, b)

operator.__or__(a, b)

a와 b의 비트별 논리합(or)을 반환합니다.

operator.pos(obj)

operator.__pos__(obj)

양의 obj(+obj)를 반환합니다.

operator.pow(a, b)

operator.__pow__(a, b)

a와 b 숫자에 대해, a ** b를 반환합니다.

operator.rshift(a, b)

operator.__rshift__(a, b)

a를 b만큼 오른쪽으로 시프트 한 값을 반환합니다.

operator.sub(a, b)

operator.__sub__(a, b)

a - b를 반환합니다.

operator.truediv(a, b)

operator.__truediv__(a, b)

a / b를 반환합니다. 여기서 2/3는 0이 아니라 .66입니다. 이것은 “실수(true)” 나누기라고 도합니다.

operator.xor(a, b)

operator.__xor__(a, b)

a와 b의 비트별 배타적 논리합을 반환합니다.

시퀀스에 적용되는 연산(일부는 매핑에도 적용됩니다)은 다음과 같습니다:

operator.concat(a, b)

operator.__concat__(a, b)

a와 b 시퀀스에 대해 a + b를 반환합니다.

operator.contains(a, b)

operator.__contains__(a, b)

b in a 검사의 결과를 반환합니다. 피연산자가 뒤집혀 있음에 유의하십시오.

operator.countOf(a, b)

a에서 b가 발생하는 횟수를 반환합니다.

operator.delitem(a, b)

operator.__delitem__(a, b)

a의 값을 인덱스 b에서 제거합니다.

operator.getitem(a, b)

operator.__getitem__(a, b)

인덱스 b에 있는 a의 값을 반환합니다.

operator.indexOf(a, b)

a에서 b가 처음으로 발견되는 인덱스를 반환합니다.

operator.setitem(a, b, c)

operator.__setitem__(a, b, c)

인덱스 b의 a의 값을 c로 설정합니다.

operator.length_hint(obj, default=0)

o 객체의 추정된 길이를 반환합니다. 먼저 실제 길이를 반환하려고 시도한 다음, object.__length_hint__()를 사용하여 추정치를 반환하려고 하고, 마지막으로 default 값을 반환합니다.

버전 3.4에 추가.

operator 모듈은 일반화된 어트리뷰트와 항목 조회를 위한 도구도 정의합니다. 이것은 map(), sorted(), itertools.groupby() 또는 함수 인자를 기대하는 다른 함수의 인자로 사용될 고속 필드 추출기를 만드는 데 유용합니다.

operator.attrgetter(attr)

operator.attrgetter(*attrs)

피연산자에서 attr을 꺼내는 콜러블 객체를 반환합니다. 둘 이상의 어트리뷰트가 요청되면, 어트리뷰트의 튜플을 반환합니다. 어트리뷰트 이름은 점을 포함할 수도 있습니다. 예를 들어:

f = attrgetter('name') 다음에, f(b) 호출은 b.name을 반환합니다.

f = attrgetter('name', 'date') 다음에, f(b) 호출은 (b.name, b.date)를 반환합니다.

f = attrgetter('name.first', 'name.last') 다음에, f(b) 호출은 (b.name.first, b.name.last)를 반환합니다.

다음과 동등합니다:

def attrgetter(*items):
    if any(not isinstance(item, str) for item in items):
        raise TypeError('attribute name must be a string')
    if len(items) == 1:
        attr = items[0]
        def g(obj):
            return resolve_attr(obj, attr)
    else:
        def g(obj):
            return tuple(resolve_attr(obj, attr) for attr in items)
    return g

def resolve_attr(obj, attr):
    for name in attr.split("."):
        obj = getattr(obj, name)
    return obj

operator.itemgetter(item)

operator.itemgetter(*items)

피연산자의 __getitem__() 메서드를 사용하여 피연산자에서 item을 꺼내는 콜러블 객체를 반환합니다. 여러 항목이 지정되면, 조회 값의 튜플을 반환합니다. 예를 들어:

f = itemgetter(2) 다음에, f(r) 호출은 r[2]를 반환합니다.

g = itemgetter(2, 5, 3) 다음에, g(r) 호출은 (r[2], r[5], r[3])을 반환합니다.

다음과 동등합니다:

def itemgetter(*items):
    if len(items) == 1:
        item = items[0]
        def g(obj):
            return obj[item]
    else:
        def g(obj):
            return tuple(obj[item] for item in items)
    return g

항목은 피연산자의 __getitem__() 메서드에서 허용되는 모든 형이 될 수 있습니다. 딕셔너리는 모든 해시 가능 값을 허용합니다. 리스트, 튜플 및 문자열은 인덱스나 슬라이스를 허용합니다:

>>> itemgetter(1)('ABCDEFG')
'B'
>>> itemgetter(1,3,5)('ABCDEFG')
('B', 'D', 'F')
>>> itemgetter(slice(2,None))('ABCDEFG')
'CDEFG'

>>> soldier = dict(rank='captain', name='dotterbart')
>>> itemgetter('rank')(soldier)
'captain'

튜플 레코드에서 특정 필드를 꺼내기 위해 itemgetter()를 사용하는 예:

>>> inventory = [('apple', 3), ('banana', 2), ('pear', 5), ('orange', 1)]
>>> getcount = itemgetter(1)
>>> list(map(getcount, inventory))
[3, 2, 5, 1]
>>> sorted(inventory, key=getcount)
[('orange', 1), ('banana', 2), ('apple', 3), ('pear', 5)]

operator.methodcaller(name[, args...])

피연산자에서 name 메서드를 호출하는 콜러블 객체를 반환합니다. 추가 인자 및/또는 키워드 인자가 주어지면, 해당 인자도 메서드에 제공됩니다. 예를 들어:

f = methodcaller('name') 다음에, f(b) 호출은 b.name()을 반환합니다.

f = methodcaller('name', 'foo', bar=1) 다음에, f(b) 호출은 b.name('foo', bar=1)을 반환합니다.

다음과 동등합니다:

def methodcaller(name, *args, **kwargs):
    def caller(obj):
        return getattr(obj, name)(*args, **kwargs)
    return caller

연산자를 함수에 매핑하기

이 표는 추상 연산이 파이썬 문법의 연산자 기호와 operator 모듈의 함수로 어떻게 대응되는지를 보여줍니다.

연산

문법

함수

더하기(Addition)

a + b

add(a, b)

이어붙이기(Concatenation)

seq1 + seq2

concat(seq1, seq2)

포함 검사(Containment Test)

obj in seq

contains(seq, obj)

나누기(Division)

a / b

truediv(a, b)

나누기(Division)

a // b

floordiv(a, b)

비트별 논리곱(Bitwise And)

a & b

and_(a, b)

비트별 배타적 논리합(Bitwise Exclusive Or)

a ^ b

xor(a, b)

비트별 반전(Bitwise Inversion)

~ a

invert(a)

비트별 논리합(Bitwise Or)

a | b

or_(a, b)

거듭제곱(Exponentiation)

a ** b

pow(a, b)

아이덴티티(Identity)

a is b

is_(a, b)

아이덴티티(Identity)

a is not b

is_not(a, b)

인덱싱된 대입(Indexed Assignment)

obj[k] = v

setitem(obj, k, v)

인덱싱된 삭제(Indexed Deletion)

del obj[k]

delitem(obj, k)

인덱싱(Indexing)

obj[k]

getitem(obj, k)

왼쪽으로 시프트(Left Shift)

a << b

lshift(a, b)

모듈로(Modulo)

a % b

mod(a, b)

곱하기(Multiplication)

a * b

mul(a, b)

행렬 곱하기(Matrix Multiplication)

a @ b

matmul(a, b)

부정 (산술)(Negation (Arithmetic))

- a

neg(a)

부정 (논리)(Negation (Logical))

not a

not_(a)

양(Positive)

+ a

pos(a)

오른쪽으로 시프트(Right Shift)

a >> b

rshift(a, b)

슬라이스 대입(Slice Assignment)

seq[i:j] = values

setitem(seq, slice(i, j), values)

슬라이스 삭제(Slice Deletion)

del seq[i:j]

delitem(seq, slice(i, j))

슬라이싱(Slicing)

seq[i:j]

getitem(seq, slice(i, j))

문자열 포매팅(String Formatting)

s % obj

mod(s, obj)

빼기(Subtraction)

a - b

sub(a, b)

진릿값 검사(Truth Test)

obj

truth(obj)

대소비교(Ordering)

a < b

lt(a, b)

대소비교(Ordering)

a <= b

le(a, b)

동등성(Equality)

a == b

eq(a, b)

다름(Difference)

a != b

ne(a, b)

대소비교(Ordering)

a >= b

ge(a, b)

대소비교(Ordering)

a > b

gt(a, b)

제자리 연산자

많은 연산에는 “제자리(in-place)” 버전이 있습니다. 아래에 나열된 것들은 일반적인 문법보다 제자리 연산자에 대한 더 기본적인 액세스를 제공하는 함수입니다; 예를 들어, 문장 x += y는 x = operator.iadd(x, y)와 동등합니다. 또 다른 식으로는, z = operator.iadd(x, y)가 복합문 z = x; z += y와 동등하다고 말하는 것입니다.

이 예제들에서, 제자리 메서드가 호출될 때, 계산과 대입이 두 개의 분리된 단계에서 수행된다는 점에 유의하십시오. 아래 나열된 제자리 함수는 제자리 메서드를 호출하는 첫 번째 단계만 수행합니다. 두 번째 단계인 대입은 처리되지 않습니다.

문자열, 숫자 및 튜플과 같은 불변 대상의 경우, 갱신된 값이 계산되지만, 입력 변수에 다시 할당되지 않습니다:

>>> a = 'hello'
>>> iadd(a, ' world')
'hello world'
>>> a
'hello'

리스트와 딕셔너리 같은 가변 대상의 경우, 제자리 메서드가 갱신을 수행하므로, 이후 대입이 필요하지 않습니다:

>>> s = ['h', 'e', 'l', 'l', 'o']
>>> iadd(s, [' ', 'w', 'o', 'r', 'l', 'd'])
['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
>>> s
['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']

operator.iadd(a, b)

operator.__iadd__(a, b)

a = iadd(a, b)는 a += b와 동등합니다.

operator.iand(a, b)

operator.__iand__(a, b)

a = iand(a, b)는 a &= b와 동등합니다.

operator.iconcat(a, b)

operator.__iconcat__(a, b)

a와 b 시퀀스에 대해, a = iconcat(a, b)는 a += b와 동등합니다.

operator.ifloordiv(a, b)

operator.__ifloordiv__(a, b)

a = ifloordiv(a, b)는 a //= b와 동등합니다.

operator.ilshift(a, b)

operator.__ilshift__(a, b)

a = ilshift(a, b)는 a <<= b와 동등합니다.

operator.imod(a, b)

operator.__imod__(a, b)

a = imod(a, b)는 a %= b와 동등합니다.

operator.imul(a, b)

operator.__imul__(a, b)

a = imul(a, b)는 a *= b와 동등합니다.

operator.imatmul(a, b)

operator.__imatmul__(a, b)

a = imatmul(a, b)는 a @= b와 동등합니다.

버전 3.5에 추가.

operator.ior(a, b)

operator.__ior__(a, b)

a = ior(a, b)는 a |= b와 동등합니다.

operator.ipow(a, b)

operator.__ipow__(a, b)

a = ipow(a, b)는 a **= b와 동등합니다.

operator.irshift(a, b)

operator.__irshift__(a, b)

a = irshift(a, b)는 a >>= b와 동등합니다.

operator.isub(a, b)

operator.__isub__(a, b)

a = isub(a, b)는 a -= b와 동등합니다.

operator.itruediv(a, b)

operator.__itruediv__(a, b)

a = itruediv(a, b)는 a /= b와 동등합니다.

operator.ixor(a, b)

operator.__ixor__(a, b)

a = ixor(a, b)는 a ^= b와 동등합니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

함수형 프로그래밍 모듈 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

|

파일과 디렉터리 액세스

이 장에서 설명하는 모듈은 디스크 파일과 디렉터리를 다룹니다. 예를 들어, 파일의 속성을 읽고, 이식성 있는 방식으로 경로를 조작하고, 임시 파일을 만드는 모듈이 있습니다. 이 장의 전체 모듈 목록은 다음과 같습니다:

pathlib — Object-oriented filesystem paths

Basic use

Pure paths

General properties

Operators

Accessing individual parts

Methods and properties

Concrete paths

Methods

Correspondence to tools in the os module

os.path — Common pathname manipulations

fileinput — Iterate over lines from multiple input streams

stat — stat() 결과 해석하기

filecmp — 파일과 디렉터리 비교

dircmp 클래스

tempfile — Generate temporary files and directories

Examples

Deprecated functions and variables

glob — 유닉스 스타일 경로명 패턴 확장

fnmatch — 유닉스 파일명 패턴 일치

linecache — 텍스트 줄에 대한 무작위 액세스

shutil — High-level file operations

Directory and files operations

copytree example

rmtree example

Archiving operations

Archiving example

Archiving example with base_dir

Querying the size of the output terminal

macpath — Mac OS 9 path manipulation functions

더 보기

모듈 os

운영 체제 인터페이스. 파이썬 파일 객체보다 저수준으로 파일을 다루는 함수를 포함합니다.

모듈 io

파이썬의 내장 I/O 라이브러리. 추상 클래스와 파일 I/O와 같은 구상 클래스를 모두 포함합니다.

내장 함수 open()

파이썬으로 읽고 쓰기 위해 파일을 여는 표준 방법.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

파일과 디렉터리 액세스 »

|

pathlib — Object-oriented filesystem paths

버전 3.4에 추가.

Source code: Lib/pathlib.py [https://github.com/python/cpython/tree/3.7/Lib/pathlib.py]

This module offers classes representing filesystem paths with semantics appropriate for different operating systems. Path classes are divided between pure paths, which provide purely computational operations without I/O, and concrete paths, which inherit from pure paths but also provide I/O operations.

If you’ve never used this module before or just aren’t sure which class is right for your task, Path is most likely what you need. It instantiates a concrete path for the platform the code is running on.

Pure paths are useful in some special cases; for example:

If you want to manipulate Windows paths on a Unix machine (or vice versa). You cannot instantiate a WindowsPath when running on Unix, but you can instantiate PureWindowsPath.

You want to make sure that your code only manipulates paths without actually accessing the OS. In this case, instantiating one of the pure classes may be useful since those simply don’t have any OS-accessing operations.

더 보기

PEP 428 [https://www.python.org/dev/peps/pep-0428]: The pathlib module – object-oriented filesystem paths.

더 보기

For low-level path manipulation on strings, you can also use the os.path module.

Basic use

Importing the main class:

>>> from pathlib import Path

Listing subdirectories:

>>> p = Path('.')
>>> [x for x in p.iterdir() if x.is_dir()]
[PosixPath('.hg'), PosixPath('docs'), PosixPath('dist'),
 PosixPath('__pycache__'), PosixPath('build')]

Listing Python source files in this directory tree:

>>> list(p.glob('**/*.py'))
[PosixPath('test_pathlib.py'), PosixPath('setup.py'),
 PosixPath('pathlib.py'), PosixPath('docs/conf.py'),
 PosixPath('build/lib/pathlib.py')]

Navigating inside a directory tree:

>>> p = Path('/etc')
>>> q = p / 'init.d' / 'reboot'
>>> q
PosixPath('/etc/init.d/reboot')
>>> q.resolve()
PosixPath('/etc/rc.d/init.d/halt')

Querying path properties:

>>> q.exists()
True
>>> q.is_dir()
False

Opening a file:

>>> with q.open() as f: f.readline()
...
'#!/bin/bash\n'

Pure paths

Pure path objects provide path-handling operations which don’t actually access a filesystem. There are three ways to access these classes, which we also call flavours:

class pathlib.PurePath(*pathsegments)

A generic class that represents the system’s path flavour (instantiating it creates either a PurePosixPath or a PureWindowsPath):

>>> PurePath('setup.py')      # Running on a Unix machine
PurePosixPath('setup.py')

Each element of pathsegments can be either a string representing a path segment, an object implementing the os.PathLike interface which returns a string, or another path object:

>>> PurePath('foo', 'some/path', 'bar')
PurePosixPath('foo/some/path/bar')
>>> PurePath(Path('foo'), Path('bar'))
PurePosixPath('foo/bar')

When pathsegments is empty, the current directory is assumed:

>>> PurePath()
PurePosixPath('.')

When several absolute paths are given, the last is taken as an anchor (mimicking os.path.join()’s behaviour):

>>> PurePath('/etc', '/usr', 'lib64')
PurePosixPath('/usr/lib64')
>>> PureWindowsPath('c:/Windows', 'd:bar')
PureWindowsPath('d:bar')

However, in a Windows path, changing the local root doesn’t discard the previous drive setting:

>>> PureWindowsPath('c:/Windows', '/Program Files')
PureWindowsPath('c:/Program Files')

Spurious slashes and single dots are collapsed, but double dots ('..') are not, since this would change the meaning of a path in the face of symbolic links:

>>> PurePath('foo//bar')
PurePosixPath('foo/bar')
>>> PurePath('foo/./bar')
PurePosixPath('foo/bar')
>>> PurePath('foo/../bar')
PurePosixPath('foo/../bar')

(a naïve approach would make PurePosixPath('foo/../bar') equivalent to PurePosixPath('bar'), which is wrong if foo is a symbolic link to another directory)

Pure path objects implement the os.PathLike interface, allowing them to be used anywhere the interface is accepted.

버전 3.6에서 변경: Added support for the os.PathLike interface.

class pathlib.PurePosixPath(*pathsegments)

A subclass of PurePath, this path flavour represents non-Windows filesystem paths:

>>> PurePosixPath('/etc')
PurePosixPath('/etc')

pathsegments is specified similarly to PurePath.

class pathlib.PureWindowsPath(*pathsegments)

A subclass of PurePath, this path flavour represents Windows filesystem paths:

>>> PureWindowsPath('c:/Program Files/')
PureWindowsPath('c:/Program Files')

pathsegments is specified similarly to PurePath.

Regardless of the system you’re running on, you can instantiate all of these classes, since they don’t provide any operation that does system calls.

General properties

Paths are immutable and hashable. Paths of a same flavour are comparable and orderable. These properties respect the flavour’s case-folding semantics:

>>> PurePosixPath('foo') == PurePosixPath('FOO')
False
>>> PureWindowsPath('foo') == PureWindowsPath('FOO')
True
>>> PureWindowsPath('FOO') in { PureWindowsPath('foo') }
True
>>> PureWindowsPath('C:') < PureWindowsPath('d:')
True

Paths of a different flavour compare unequal and cannot be ordered:

>>> PureWindowsPath('foo') == PurePosixPath('foo')
False
>>> PureWindowsPath('foo') < PurePosixPath('foo')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: '<' not supported between instances of 'PureWindowsPath' and 'PurePosixPath'

Operators

The slash operator helps create child paths, similarly to os.path.join():

>>> p = PurePath('/etc')
>>> p
PurePosixPath('/etc')
>>> p / 'init.d' / 'apache2'
PurePosixPath('/etc/init.d/apache2')
>>> q = PurePath('bin')
>>> '/usr' / q
PurePosixPath('/usr/bin')

A path object can be used anywhere an object implementing os.PathLike is accepted:

>>> import os
>>> p = PurePath('/etc')
>>> os.fspath(p)
'/etc'

The string representation of a path is the raw filesystem path itself (in native form, e.g. with backslashes under Windows), which you can pass to any function taking a file path as a string:

>>> p = PurePath('/etc')
>>> str(p)
'/etc'
>>> p = PureWindowsPath('c:/Program Files')
>>> str(p)
'c:\\Program Files'

Similarly, calling bytes on a path gives the raw filesystem path as a bytes object, as encoded by os.fsencode():

>>> bytes(p)
b'/etc'

참고

Calling bytes is only recommended under Unix. Under Windows, the unicode form is the canonical representation of filesystem paths.

Accessing individual parts

To access the individual “parts” (components) of a path, use the following property:

PurePath.parts

A tuple giving access to the path’s various components:

>>> p = PurePath('/usr/bin/python3')
>>> p.parts
('/', 'usr', 'bin', 'python3')

>>> p = PureWindowsPath('c:/Program Files/PSF')
>>> p.parts
('c:\\', 'Program Files', 'PSF')

(note how the drive and local root are regrouped in a single part)

Methods and properties

Pure paths provide the following methods and properties:

PurePath.drive

A string representing the drive letter or name, if any:

>>> PureWindowsPath('c:/Program Files/').drive
'c:'
>>> PureWindowsPath('/Program Files/').drive
''
>>> PurePosixPath('/etc').drive
''

UNC shares are also considered drives:

>>> PureWindowsPath('//host/share/foo.txt').drive
'\\\\host\\share'

PurePath.root

A string representing the (local or global) root, if any:

>>> PureWindowsPath('c:/Program Files/').root
'\\'
>>> PureWindowsPath('c:Program Files/').root
''
>>> PurePosixPath('/etc').root
'/'

UNC shares always have a root:

>>> PureWindowsPath('//host/share').root
'\\'

PurePath.anchor

The concatenation of the drive and root:

>>> PureWindowsPath('c:/Program Files/').anchor
'c:\\'
>>> PureWindowsPath('c:Program Files/').anchor
'c:'
>>> PurePosixPath('/etc').anchor
'/'
>>> PureWindowsPath('//host/share').anchor
'\\\\host\\share\\'

PurePath.parents

An immutable sequence providing access to the logical ancestors of the path:

>>> p = PureWindowsPath('c:/foo/bar/setup.py')
>>> p.parents[0]
PureWindowsPath('c:/foo/bar')
>>> p.parents[1]
PureWindowsPath('c:/foo')
>>> p.parents[2]
PureWindowsPath('c:/')

PurePath.parent

The logical parent of the path:

>>> p = PurePosixPath('/a/b/c/d')
>>> p.parent
PurePosixPath('/a/b/c')

You cannot go past an anchor, or empty path:

>>> p = PurePosixPath('/')
>>> p.parent
PurePosixPath('/')
>>> p = PurePosixPath('.')
>>> p.parent
PurePosixPath('.')

참고

This is a purely lexical operation, hence the following behaviour:

>>> p = PurePosixPath('foo/..')
>>> p.parent
PurePosixPath('foo')

If you want to walk an arbitrary filesystem path upwards, it is recommended to first call Path.resolve() so as to resolve symlinks and eliminate “..” components.

PurePath.name

A string representing the final path component, excluding the drive and root, if any:

>>> PurePosixPath('my/library/setup.py').name
'setup.py'

UNC drive names are not considered:

>>> PureWindowsPath('//some/share/setup.py').name
'setup.py'
>>> PureWindowsPath('//some/share').name
''

PurePath.suffix

The file extension of the final component, if any:

>>> PurePosixPath('my/library/setup.py').suffix
'.py'
>>> PurePosixPath('my/library.tar.gz').suffix
'.gz'
>>> PurePosixPath('my/library').suffix
''

PurePath.suffixes

A list of the path’s file extensions:

>>> PurePosixPath('my/library.tar.gar').suffixes
['.tar', '.gar']
>>> PurePosixPath('my/library.tar.gz').suffixes
['.tar', '.gz']
>>> PurePosixPath('my/library').suffixes
[]

PurePath.stem

The final path component, without its suffix:

>>> PurePosixPath('my/library.tar.gz').stem
'library.tar'
>>> PurePosixPath('my/library.tar').stem
'library'
>>> PurePosixPath('my/library').stem
'library'

PurePath.as_posix()

Return a string representation of the path with forward slashes (/):

>>> p = PureWindowsPath('c:\\windows')
>>> str(p)
'c:\\windows'
>>> p.as_posix()
'c:/windows'

PurePath.as_uri()

Represent the path as a file URI. ValueError is raised if the path isn’t absolute.

>>> p = PurePosixPath('/etc/passwd')
>>> p.as_uri()
'file:///etc/passwd'
>>> p = PureWindowsPath('c:/Windows')
>>> p.as_uri()
'file:///c:/Windows'

PurePath.is_absolute()

Return whether the path is absolute or not. A path is considered absolute if it has both a root and (if the flavour allows) a drive:

>>> PurePosixPath('/a/b').is_absolute()
True
>>> PurePosixPath('a/b').is_absolute()
False

>>> PureWindowsPath('c:/a/b').is_absolute()
True
>>> PureWindowsPath('/a/b').is_absolute()
False
>>> PureWindowsPath('c:').is_absolute()
False
>>> PureWindowsPath('//some/share').is_absolute()
True

PurePath.is_reserved()

With PureWindowsPath, return True if the path is considered reserved under Windows, False otherwise. With PurePosixPath, False is always returned.

>>> PureWindowsPath('nul').is_reserved()
True
>>> PurePosixPath('nul').is_reserved()
False

File system calls on reserved paths can fail mysteriously or have unintended effects.

PurePath.joinpath(*other)

Calling this method is equivalent to combining the path with each of the other arguments in turn:

>>> PurePosixPath('/etc').joinpath('passwd')
PurePosixPath('/etc/passwd')
>>> PurePosixPath('/etc').joinpath(PurePosixPath('passwd'))
PurePosixPath('/etc/passwd')
>>> PurePosixPath('/etc').joinpath('init.d', 'apache2')
PurePosixPath('/etc/init.d/apache2')
>>> PureWindowsPath('c:').joinpath('/Program Files')
PureWindowsPath('c:/Program Files')

PurePath.match(pattern)

Match this path against the provided glob-style pattern. Return True if matching is successful, False otherwise.

If pattern is relative, the path can be either relative or absolute, and matching is done from the right:

>>> PurePath('a/b.py').match('*.py')
True
>>> PurePath('/a/b/c.py').match('b/*.py')
True
>>> PurePath('/a/b/c.py').match('a/*.py')
False

If pattern is absolute, the path must be absolute, and the whole path must match:

>>> PurePath('/a.py').match('/*.py')
True
>>> PurePath('a/b.py').match('/*.py')
False

As with other methods, case-sensitivity follows platform defaults:

>>> PurePosixPath('b.py').match('*.PY')
False
>>> PureWindowsPath('b.py').match('*.PY')
True

PurePath.relative_to(*other)

Compute a version of this path relative to the path represented by other. If it’s impossible, ValueError is raised:

>>> p = PurePosixPath('/etc/passwd')
>>> p.relative_to('/')
PurePosixPath('etc/passwd')
>>> p.relative_to('/etc')
PurePosixPath('passwd')
>>> p.relative_to('/usr')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "pathlib.py", line 694, in relative_to
    .format(str(self), str(formatted)))
ValueError: '/etc/passwd' does not start with '/usr'

PurePath.with_name(name)

Return a new path with the name changed. If the original path doesn’t have a name, ValueError is raised:

>>> p = PureWindowsPath('c:/Downloads/pathlib.tar.gz')
>>> p.with_name('setup.py')
PureWindowsPath('c:/Downloads/setup.py')
>>> p = PureWindowsPath('c:/')
>>> p.with_name('setup.py')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/antoine/cpython/default/Lib/pathlib.py", line 751, in with_name
    raise ValueError("%r has an empty name" % (self,))
ValueError: PureWindowsPath('c:/') has an empty name

PurePath.with_suffix(suffix)

Return a new path with the suffix changed. If the original path doesn’t have a suffix, the new suffix is appended instead. If the suffix is an empty string, the original suffix is removed:

>>> p = PureWindowsPath('c:/Downloads/pathlib.tar.gz')
>>> p.with_suffix('.bz2')
PureWindowsPath('c:/Downloads/pathlib.tar.bz2')
>>> p = PureWindowsPath('README')
>>> p.with_suffix('.txt')
PureWindowsPath('README.txt')
>>> p = PureWindowsPath('README.txt')
>>> p.with_suffix('')
PureWindowsPath('README')

Concrete paths

Concrete paths are subclasses of the pure path classes. In addition to operations provided by the latter, they also provide methods to do system calls on path objects. There are three ways to instantiate concrete paths:

class pathlib.Path(*pathsegments)

A subclass of PurePath, this class represents concrete paths of the system’s path flavour (instantiating it creates either a PosixPath or a WindowsPath):

>>> Path('setup.py')
PosixPath('setup.py')

pathsegments is specified similarly to PurePath.

class pathlib.PosixPath(*pathsegments)

A subclass of Path and PurePosixPath, this class represents concrete non-Windows filesystem paths:

>>> PosixPath('/etc')
PosixPath('/etc')

pathsegments is specified similarly to PurePath.

class pathlib.WindowsPath(*pathsegments)

A subclass of Path and PureWindowsPath, this class represents concrete Windows filesystem paths:

>>> WindowsPath('c:/Program Files/')
WindowsPath('c:/Program Files')

pathsegments is specified similarly to PurePath.

You can only instantiate the class flavour that corresponds to your system (allowing system calls on non-compatible path flavours could lead to bugs or failures in your application):

>>> import os
>>> os.name
'posix'
>>> Path('setup.py')
PosixPath('setup.py')
>>> PosixPath('setup.py')
PosixPath('setup.py')
>>> WindowsPath('setup.py')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "pathlib.py", line 798, in __new__
    % (cls.__name__,))
NotImplementedError: cannot instantiate 'WindowsPath' on your system

Methods

Concrete paths provide the following methods in addition to pure paths methods. Many of these methods can raise an OSError if a system call fails (for example because the path doesn’t exist):

classmethod Path.cwd()

Return a new path object representing the current directory (as returned by os.getcwd()):

>>> Path.cwd()
PosixPath('/home/antoine/pathlib')

classmethod Path.home()

Return a new path object representing the user’s home directory (as returned by os.path.expanduser() with ~ construct):

>>> Path.home()
PosixPath('/home/antoine')

버전 3.5에 추가.

Path.stat()

Return a os.stat_result object containing information about this path, like os.stat(). The result is looked up at each call to this method.

>>> p = Path('setup.py')
>>> p.stat().st_size
956
>>> p.stat().st_mtime
1327883547.852554

Path.chmod(mode)

Change the file mode and permissions, like os.chmod():

>>> p = Path('setup.py')
>>> p.stat().st_mode
33277
>>> p.chmod(0o444)
>>> p.stat().st_mode
33060

Path.exists()

Whether the path points to an existing file or directory:

>>> Path('.').exists()
True
>>> Path('setup.py').exists()
True
>>> Path('/etc').exists()
True
>>> Path('nonexistentfile').exists()
False

참고

If the path points to a symlink, exists() returns whether the symlink points to an existing file or directory.

Path.expanduser()

Return a new path with expanded ~ and ~user constructs, as returned by os.path.expanduser():

>>> p = PosixPath('~/films/Monty Python')
>>> p.expanduser()
PosixPath('/home/eric/films/Monty Python')

버전 3.5에 추가.

Path.glob(pattern)

Glob the given relative pattern in the directory represented by this path, yielding all matching files (of any kind):

>>> sorted(Path('.').glob('*.py'))
[PosixPath('pathlib.py'), PosixPath('setup.py'), PosixPath('test_pathlib.py')]
>>> sorted(Path('.').glob('*/*.py'))
[PosixPath('docs/conf.py')]

The “**” pattern means “this directory and all subdirectories, recursively”. In other words, it enables recursive globbing:

>>> sorted(Path('.').glob('**/*.py'))
[PosixPath('build/lib/pathlib.py'),
 PosixPath('docs/conf.py'),
 PosixPath('pathlib.py'),
 PosixPath('setup.py'),
 PosixPath('test_pathlib.py')]

참고

Using the “**” pattern in large directory trees may consume an inordinate amount of time.

Path.group()

Return the name of the group owning the file. KeyError is raised if the file’s gid isn’t found in the system database.

Path.is_dir()

Return True if the path points to a directory (or a symbolic link pointing to a directory), False if it points to another kind of file.

False is also returned if the path doesn’t exist or is a broken symlink; other errors (such as permission errors) are propagated.

Path.is_file()

Return True if the path points to a regular file (or a symbolic link pointing to a regular file), False if it points to another kind of file.

False is also returned if the path doesn’t exist or is a broken symlink; other errors (such as permission errors) are propagated.

Path.is_mount()

Return True if the path is a mount point: a point in a file system where a different file system has been mounted. On POSIX, the function checks whether path’s parent, path/.., is on a different device than path, or whether path/.. and path point to the same i-node on the same device — this should detect mount points for all Unix and POSIX variants. Not implemented on Windows.

버전 3.7에 추가.

Path.is_symlink()

Return True if the path points to a symbolic link, False otherwise.

False is also returned if the path doesn’t exist; other errors (such as permission errors) are propagated.

Path.is_socket()

Return True if the path points to a Unix socket (or a symbolic link pointing to a Unix socket), False if it points to another kind of file.

False is also returned if the path doesn’t exist or is a broken symlink; other errors (such as permission errors) are propagated.

Path.is_fifo()

Return True if the path points to a FIFO (or a symbolic link pointing to a FIFO), False if it points to another kind of file.

False is also returned if the path doesn’t exist or is a broken symlink; other errors (such as permission errors) are propagated.

Path.is_block_device()

Return True if the path points to a block device (or a symbolic link pointing to a block device), False if it points to another kind of file.

False is also returned if the path doesn’t exist or is a broken symlink; other errors (such as permission errors) are propagated.

Path.is_char_device()

Return True if the path points to a character device (or a symbolic link pointing to a character device), False if it points to another kind of file.

False is also returned if the path doesn’t exist or is a broken symlink; other errors (such as permission errors) are propagated.

Path.iterdir()

When the path points to a directory, yield path objects of the directory contents:

>>> p = Path('docs')
>>> for child in p.iterdir(): child
...
PosixPath('docs/conf.py')
PosixPath('docs/_templates')
PosixPath('docs/make.bat')
PosixPath('docs/index.rst')
PosixPath('docs/_build')
PosixPath('docs/_static')
PosixPath('docs/Makefile')

Path.lchmod(mode)

Like Path.chmod() but, if the path points to a symbolic link, the symbolic link’s mode is changed rather than its target’s.

Path.lstat()

Like Path.stat() but, if the path points to a symbolic link, return the symbolic link’s information rather than its target’s.

Path.mkdir(mode=0o777, parents=False, exist_ok=False)

Create a new directory at this given path. If mode is given, it is combined with the process’ umask value to determine the file mode and access flags. If the path already exists, FileExistsError is raised.

If parents is true, any missing parents of this path are created as needed; they are created with the default permissions without taking mode into account (mimicking the POSIX mkdir -p command).

If parents is false (the default), a missing parent raises FileNotFoundError.

If exist_ok is false (the default), FileExistsError is raised if the target directory already exists.

If exist_ok is true, FileExistsError exceptions will be ignored (same behavior as the POSIX mkdir -p command), but only if the last path component is not an existing non-directory file.

버전 3.5에서 변경: The exist_ok parameter was added.

Path.open(mode='r', buffering=-1, encoding=None, errors=None, newline=None)

Open the file pointed to by the path, like the built-in open() function does:

>>> p = Path('setup.py')
>>> with p.open() as f:
...     f.readline()
...
'#!/usr/bin/env python3\n'

Path.owner()

Return the name of the user owning the file. KeyError is raised if the file’s uid isn’t found in the system database.

Path.read_bytes()

Return the binary contents of the pointed-to file as a bytes object:

>>> p = Path('my_binary_file')
>>> p.write_bytes(b'Binary file contents')
20
>>> p.read_bytes()
b'Binary file contents'

버전 3.5에 추가.

Path.read_text(encoding=None, errors=None)

Return the decoded contents of the pointed-to file as a string:

>>> p = Path('my_text_file')
>>> p.write_text('Text file contents')
18
>>> p.read_text()
'Text file contents'

The file is opened and then closed. The optional parameters have the same meaning as in open().

버전 3.5에 추가.

Path.rename(target)

Rename this file or directory to the given target. On Unix, if target exists and is a file, it will be replaced silently if the user has permission. target can be either a string or another path object:

>>> p = Path('foo')
>>> p.open('w').write('some text')
9
>>> target = Path('bar')
>>> p.rename(target)
>>> target.open().read()
'some text'

Path.replace(target)

Rename this file or directory to the given target. If target points to an existing file or directory, it will be unconditionally replaced.

Path.resolve(strict=False)

Make the path absolute, resolving any symlinks. A new path object is returned:

>>> p = Path()
>>> p
PosixPath('.')
>>> p.resolve()
PosixPath('/home/antoine/pathlib')

“..” components are also eliminated (this is the only method to do so):

>>> p = Path('docs/../setup.py')
>>> p.resolve()
PosixPath('/home/antoine/pathlib/setup.py')

If the path doesn’t exist and strict is True, FileNotFoundError is raised. If strict is False, the path is resolved as far as possible and any remainder is appended without checking whether it exists. If an infinite loop is encountered along the resolution path, RuntimeError is raised.

버전 3.6에 추가: The strict argument (pre-3.6 behavior is strict).

Path.rglob(pattern)

This is like calling Path.glob() with “**/” added in front of the given relative pattern:

>>> sorted(Path().rglob("*.py"))
[PosixPath('build/lib/pathlib.py'),
 PosixPath('docs/conf.py'),
 PosixPath('pathlib.py'),
 PosixPath('setup.py'),
 PosixPath('test_pathlib.py')]

Path.rmdir()

Remove this directory. The directory must be empty.

Path.samefile(other_path)

Return whether this path points to the same file as other_path, which can be either a Path object, or a string. The semantics are similar to os.path.samefile() and os.path.samestat().

An OSError can be raised if either file cannot be accessed for some reason.

>>> p = Path('spam')
>>> q = Path('eggs')
>>> p.samefile(q)
False
>>> p.samefile('spam')
True

버전 3.5에 추가.

Path.symlink_to(target, target_is_directory=False)

Make this path a symbolic link to target. Under Windows, target_is_directory must be true (default False) if the link’s target is a directory. Under POSIX, target_is_directory’s value is ignored.

>>> p = Path('mylink')
>>> p.symlink_to('setup.py')
>>> p.resolve()
PosixPath('/home/antoine/pathlib/setup.py')
>>> p.stat().st_size
956
>>> p.lstat().st_size
8

참고

The order of arguments (link, target) is the reverse of os.symlink()’s.

Path.touch(mode=0o666, exist_ok=True)

Create a file at this given path. If mode is given, it is combined with the process’ umask value to determine the file mode and access flags. If the file already exists, the function succeeds if exist_ok is true (and its modification time is updated to the current time), otherwise FileExistsError is raised.

Path.unlink()

Remove this file or symbolic link. If the path points to a directory, use Path.rmdir() instead.

Path.write_bytes(data)

Open the file pointed to in bytes mode, write data to it, and close the file:

>>> p = Path('my_binary_file')
>>> p.write_bytes(b'Binary file contents')
20
>>> p.read_bytes()
b'Binary file contents'

An existing file of the same name is overwritten.

버전 3.5에 추가.

Path.write_text(data, encoding=None, errors=None)

Open the file pointed to in text mode, write data to it, and close the file:

>>> p = Path('my_text_file')
>>> p.write_text('Text file contents')
18
>>> p.read_text()
'Text file contents'

버전 3.5에 추가.

Correspondence to tools in the os module

Below is a table mapping various os functions to their corresponding PurePath/Path equivalent.

참고

Although os.path.relpath() and PurePath.relative_to() have some overlapping use-cases, their semantics differ enough to warrant not considering them equivalent.

os and os.path

pathlib

os.path.abspath()

Path.resolve()

os.chmod()

Path.chmod()

os.mkdir()

Path.mkdir()

os.rename()

Path.rename()

os.replace()

Path.replace()

os.rmdir()

Path.rmdir()

os.remove(), os.unlink()

Path.unlink()

os.getcwd()

Path.cwd()

os.path.exists()

Path.exists()

os.path.expanduser()

Path.expanduser() and Path.home()

os.path.isdir()

Path.is_dir()

os.path.isfile()

Path.is_file()

os.path.islink()

Path.is_symlink()

os.stat()

Path.stat(), Path.owner(), Path.group()

os.path.isabs()

PurePath.is_absolute()

os.path.join()

PurePath.joinpath()

os.path.basename()

PurePath.name

os.path.dirname()

PurePath.parent

os.path.samefile()

Path.samefile()

os.path.splitext()

PurePath.suffix

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

파일과 디렉터리 액세스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

파일과 디렉터리 액세스 »

|

os.path — Common pathname manipulations

Source code: Lib/posixpath.py [https://github.com/python/cpython/tree/3.7/Lib/posixpath.py] (for POSIX), Lib/ntpath.py [https://github.com/python/cpython/tree/3.7/Lib/ntpath.py] (for Windows NT), and Lib/macpath.py [https://github.com/python/cpython/tree/3.7/Lib/macpath.py] (for Macintosh)

This module implements some useful functions on pathnames. To read or write files see open(), and for accessing the filesystem see the os module. The path parameters can be passed as either strings, or bytes. Applications are encouraged to represent file names as (Unicode) character strings. Unfortunately, some file names may not be representable as strings on Unix, so applications that need to support arbitrary file names on Unix should use bytes objects to represent path names. Vice versa, using bytes objects cannot represent all file names on Windows (in the standard mbcs encoding), hence Windows applications should use string objects to access all files.

Unlike a unix shell, Python does not do any automatic path expansions. Functions such as expanduser() and expandvars() can be invoked explicitly when an application desires shell-like path expansion. (See also the glob module.)

더 보기

The pathlib module offers high-level path objects.

참고

All of these functions accept either only bytes or only string objects as their parameters. The result is an object of the same type, if a path or file name is returned.

참고

Since different operating systems have different path name conventions, there are several versions of this module in the standard library. The os.path module is always the path module suitable for the operating system Python is running on, and therefore usable for local paths. However, you can also import and use the individual modules if you want to manipulate a path that is always in one of the different formats. They all have the same interface:

posixpath for UNIX-style paths

ntpath for Windows paths

macpath for old-style MacOS paths

os.path.abspath(path)

Return a normalized absolutized version of the pathname path. On most platforms, this is equivalent to calling the function normpath() as follows: normpath(join(os.getcwd(), path)).

버전 3.6에서 변경: Accepts a path-like object.

os.path.basename(path)

Return the base name of pathname path. This is the second element of the pair returned by passing path to the function split(). Note that the result of this function is different from the Unix basename program; where basename for '/foo/bar/' returns 'bar', the basename() function returns an empty string ('').

버전 3.6에서 변경: Accepts a path-like object.

os.path.commonpath(paths)

Return the longest common sub-path of each pathname in the sequence paths. Raise ValueError if paths contains both absolute and relative pathnames, or if paths is empty. Unlike commonprefix(), this returns a valid path.

Availability: Unix, Windows.

버전 3.5에 추가.

버전 3.6에서 변경: Accepts a sequence of path-like objects.

os.path.commonprefix(list)

Return the longest path prefix (taken character-by-character) that is a prefix of all paths in list. If list is empty, return the empty string ('').

참고

This function may return invalid paths because it works a character at a time. To obtain a valid path, see commonpath().

>>> os.path.commonprefix(['/usr/lib', '/usr/local/lib'])
'/usr/l'

>>> os.path.commonpath(['/usr/lib', '/usr/local/lib'])
'/usr'

버전 3.6에서 변경: Accepts a path-like object.

os.path.dirname(path)

Return the directory name of pathname path. This is the first element of the pair returned by passing path to the function split().

버전 3.6에서 변경: Accepts a path-like object.

os.path.exists(path)

Return True if path refers to an existing path or an open file descriptor. Returns False for broken symbolic links. On some platforms, this function may return False if permission is not granted to execute os.stat() on the requested file, even if the path physically exists.

버전 3.3에서 변경: path can now be an integer: True is returned if it is an open file descriptor, False otherwise.

버전 3.6에서 변경: Accepts a path-like object.

os.path.lexists(path)

Return True if path refers to an existing path. Returns True for broken symbolic links. Equivalent to exists() on platforms lacking os.lstat().

버전 3.6에서 변경: Accepts a path-like object.

os.path.expanduser(path)

On Unix and Windows, return the argument with an initial component of ~ or ~user replaced by that user’s home directory.

On Unix, an initial ~ is replaced by the environment variable HOME if it is set; otherwise the current user’s home directory is looked up in the password directory through the built-in module pwd. An initial ~user is looked up directly in the password directory.

On Windows, HOME and USERPROFILE will be used if set, otherwise a combination of HOMEPATH and HOMEDRIVE will be used. An initial ~user is handled by stripping the last directory component from the created user path derived above.

If the expansion fails or if the path does not begin with a tilde, the path is returned unchanged.

버전 3.6에서 변경: Accepts a path-like object.

os.path.expandvars(path)

Return the argument with environment variables expanded. Substrings of the form $name or ${name} are replaced by the value of environment variable name. Malformed variable names and references to non-existing variables are left unchanged.

On Windows, %name% expansions are supported in addition to $name and ${name}.

버전 3.6에서 변경: Accepts a path-like object.

os.path.getatime(path)

Return the time of last access of path. The return value is a floating point number giving the number of seconds since the epoch (see the time module). Raise OSError if the file does not exist or is inaccessible.

os.path.getmtime(path)

Return the time of last modification of path. The return value is a floating point number giving the number of seconds since the epoch (see the time module). Raise OSError if the file does not exist or is inaccessible.

버전 3.6에서 변경: Accepts a path-like object.

os.path.getctime(path)

Return the system’s ctime which, on some systems (like Unix) is the time of the last metadata change, and, on others (like Windows), is the creation time for path. The return value is a number giving the number of seconds since the epoch (see the time module). Raise OSError if the file does not exist or is inaccessible.

버전 3.6에서 변경: Accepts a path-like object.

os.path.getsize(path)

Return the size, in bytes, of path. Raise OSError if the file does not exist or is inaccessible.

버전 3.6에서 변경: Accepts a path-like object.

os.path.isabs(path)

Return True if path is an absolute pathname. On Unix, that means it begins with a slash, on Windows that it begins with a (back)slash after chopping off a potential drive letter.

버전 3.6에서 변경: Accepts a path-like object.

os.path.isfile(path)

Return True if path is an existing regular file. This follows symbolic links, so both islink() and isfile() can be true for the same path.

버전 3.6에서 변경: Accepts a path-like object.

os.path.isdir(path)

Return True if path is an existing directory. This follows symbolic links, so both islink() and isdir() can be true for the same path.

버전 3.6에서 변경: Accepts a path-like object.

os.path.islink(path)

Return True if path refers to an existing directory entry that is a symbolic link. Always False if symbolic links are not supported by the Python runtime.

버전 3.6에서 변경: Accepts a path-like object.

os.path.ismount(path)

Return True if pathname path is a mount point: a point in a file system where a different file system has been mounted. On POSIX, the function checks whether path’s parent, path/.., is on a different device than path, or whether path/.. and path point to the same i-node on the same device — this should detect mount points for all Unix and POSIX variants. It is not able to reliably detect bind mounts on the same filesystem. On Windows, a drive letter root and a share UNC are always mount points, and for any other path GetVolumePathName is called to see if it is different from the input path.

버전 3.4에 추가: Support for detecting non-root mount points on Windows.

버전 3.6에서 변경: Accepts a path-like object.

os.path.join(path, *paths)

Join one or more path components intelligently. The return value is the concatenation of path and any members of *paths with exactly one directory separator (os.sep) following each non-empty part except the last, meaning that the result will only end in a separator if the last part is empty. If a component is an absolute path, all previous components are thrown away and joining continues from the absolute path component.

On Windows, the drive letter is not reset when an absolute path component (e.g., r'\foo') is encountered. If a component contains a drive letter, all previous components are thrown away and the drive letter is reset. Note that since there is a current directory for each drive, os.path.join("c:", "foo") represents a path relative to the current directory on drive C: (c:foo), not c:\foo.

버전 3.6에서 변경: Accepts a path-like object for path and paths.

os.path.normcase(path)

Normalize the case of a pathname. On Windows, convert all characters in the pathname to lowercase, and also convert forward slashes to backward slashes. On other operating systems, return the path unchanged. Raise a TypeError if the type of path is not str or bytes (directly or indirectly through the os.PathLike interface).

버전 3.6에서 변경: Accepts a path-like object.

os.path.normpath(path)

Normalize a pathname by collapsing redundant separators and up-level references so that A//B, A/B/, A/./B and A/foo/../B all become A/B. This string manipulation may change the meaning of a path that contains symbolic links. On Windows, it converts forward slashes to backward slashes. To normalize case, use normcase().

버전 3.6에서 변경: Accepts a path-like object.

os.path.realpath(path)

Return the canonical path of the specified filename, eliminating any symbolic links encountered in the path (if they are supported by the operating system).

버전 3.6에서 변경: Accepts a path-like object.

os.path.relpath(path, start=os.curdir)

Return a relative filepath to path either from the current directory or from an optional start directory. This is a path computation: the filesystem is not accessed to confirm the existence or nature of path or start.

start defaults to os.curdir.

Availability: Unix, Windows.

버전 3.6에서 변경: Accepts a path-like object.

os.path.samefile(path1, path2)

Return True if both pathname arguments refer to the same file or directory. This is determined by the device number and i-node number and raises an exception if an os.stat() call on either pathname fails.

Availability: Unix, Windows.

버전 3.2에서 변경: Added Windows support.

버전 3.4에서 변경: Windows now uses the same implementation as all other platforms.

버전 3.6에서 변경: Accepts a path-like object.

os.path.sameopenfile(fp1, fp2)

Return True if the file descriptors fp1 and fp2 refer to the same file.

Availability: Unix, Windows.

버전 3.2에서 변경: Added Windows support.

버전 3.6에서 변경: Accepts a path-like object.

os.path.samestat(stat1, stat2)

Return True if the stat tuples stat1 and stat2 refer to the same file. These structures may have been returned by os.fstat(), os.lstat(), or os.stat(). This function implements the underlying comparison used by samefile() and sameopenfile().

Availability: Unix, Windows.

버전 3.4에서 변경: Added Windows support.

버전 3.6에서 변경: Accepts a path-like object.

os.path.split(path)

Split the pathname path into a pair, (head, tail) where tail is the last pathname component and head is everything leading up to that. The tail part will never contain a slash; if path ends in a slash, tail will be empty. If there is no slash in path, head will be empty. If path is empty, both head and tail are empty. Trailing slashes are stripped from head unless it is the root (one or more slashes only). In all cases, join(head, tail) returns a path to the same location as path (but the strings may differ). Also see the functions dirname() and basename().

버전 3.6에서 변경: Accepts a path-like object.

os.path.splitdrive(path)

Split the pathname path into a pair (drive, tail) where drive is either a mount point or the empty string. On systems which do not use drive specifications, drive will always be the empty string. In all cases, drive + tail will be the same as path.

On Windows, splits a pathname into drive/UNC sharepoint and relative path.

If the path contains a drive letter, drive will contain everything up to and including the colon. e.g. splitdrive("c:/dir") returns ("c:", "/dir")

If the path contains a UNC path, drive will contain the host name and share, up to but not including the fourth separator. e.g. splitdrive("//host/computer/dir") returns ("//host/computer", "/dir")

버전 3.6에서 변경: Accepts a path-like object.

os.path.splitext(path)

Split the pathname path into a pair (root, ext) such that root + ext == path, and ext is empty or begins with a period and contains at most one period. Leading periods on the basename are ignored; splitext('.cshrc') returns ('.cshrc', '').

버전 3.6에서 변경: Accepts a path-like object.

os.path.supports_unicode_filenames

True if arbitrary Unicode strings can be used as file names (within limitations imposed by the file system).

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

파일과 디렉터리 액세스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

파일과 디렉터리 액세스 »

|

fileinput — Iterate over lines from multiple input streams

Source code: Lib/fileinput.py [https://github.com/python/cpython/tree/3.7/Lib/fileinput.py]

This module implements a helper class and functions to quickly write a loop over standard input or a list of files. If you just want to read or write one file see open().

The typical use is:

import fileinput
for line in fileinput.input():
    process(line)

This iterates over the lines of all files listed in sys.argv[1:], defaulting to sys.stdin if the list is empty. If a filename is '-', it is also replaced by sys.stdin and the optional arguments mode and openhook are ignored. To specify an alternative list of filenames, pass it as the first argument to input(). A single file name is also allowed.

All files are opened in text mode by default, but you can override this by specifying the mode parameter in the call to input() or FileInput. If an I/O error occurs during opening or reading a file, OSError is raised.

버전 3.3에서 변경: IOError used to be raised; it is now an alias of OSError.

If sys.stdin is used more than once, the second and further use will return no lines, except perhaps for interactive use, or if it has been explicitly reset (e.g. using sys.stdin.seek(0)).

Empty files are opened and immediately closed; the only time their presence in the list of filenames is noticeable at all is when the last file opened is empty.

Lines are returned with any newlines intact, which means that the last line in a file may not have one.

You can control how files are opened by providing an opening hook via the openhook parameter to fileinput.input() or FileInput(). The hook must be a function that takes two arguments, filename and mode, and returns an accordingly opened file-like object. Two useful hooks are already provided by this module.

The following function is the primary interface of this module:

fileinput.input(files=None, inplace=False, backup='', bufsize=0, mode='r', openhook=None)

Create an instance of the FileInput class. The instance will be used as global state for the functions of this module, and is also returned to use during iteration. The parameters to this function will be passed along to the constructor of the FileInput class.

The FileInput instance can be used as a context manager in the with statement. In this example, input is closed after the with statement is exited, even if an exception occurs:

with fileinput.input(files=('spam.txt', 'eggs.txt')) as f:
    for line in f:
        process(line)

버전 3.2에서 변경: Can be used as a context manager.

Deprecated since version 3.6, will be removed in version 3.8: The bufsize parameter.

The following functions use the global state created by fileinput.input(); if there is no active state, RuntimeError is raised.

fileinput.filename()

Return the name of the file currently being read. Before the first line has been read, returns None.

fileinput.fileno()

Return the integer “file descriptor” for the current file. When no file is opened (before the first line and between files), returns -1.

fileinput.lineno()

Return the cumulative line number of the line that has just been read. Before the first line has been read, returns 0. After the last line of the last file has been read, returns the line number of that line.

fileinput.filelineno()

Return the line number in the current file. Before the first line has been read, returns 0. After the last line of the last file has been read, returns the line number of that line within the file.

fileinput.isfirstline()

Return True if the line just read is the first line of its file, otherwise return False.

fileinput.isstdin()

Return True if the last line was read from sys.stdin, otherwise return False.

fileinput.nextfile()

Close the current file so that the next iteration will read the first line from the next file (if any); lines not read from the file will not count towards the cumulative line count. The filename is not changed until after the first line of the next file has been read. Before the first line has been read, this function has no effect; it cannot be used to skip the first file. After the last line of the last file has been read, this function has no effect.

fileinput.close()

Close the sequence.

The class which implements the sequence behavior provided by the module is available for subclassing as well:

class fileinput.FileInput(files=None, inplace=False, backup='', bufsize=0, mode='r', openhook=None)

Class FileInput is the implementation; its methods filename(), fileno(), lineno(), filelineno(), isfirstline(), isstdin(), nextfile() and close() correspond to the functions of the same name in the module. In addition it has a readline() method which returns the next input line, and a __getitem__() method which implements the sequence behavior. The sequence must be accessed in strictly sequential order; random access and readline() cannot be mixed.

With mode you can specify which file mode will be passed to open(). It must be one of 'r', 'rU', 'U' and 'rb'.

The openhook, when given, must be a function that takes two arguments, filename and mode, and returns an accordingly opened file-like object. You cannot use inplace and openhook together.

A FileInput instance can be used as a context manager in the with statement. In this example, input is closed after the with statement is exited, even if an exception occurs:

with FileInput(files=('spam.txt', 'eggs.txt')) as input:
    process(input)

버전 3.2에서 변경: Can be used as a context manager.

버전 3.4부터 폐지: The 'rU' and 'U' modes.

Deprecated since version 3.6, will be removed in version 3.8: The bufsize parameter.

Optional in-place filtering: if the keyword argument inplace=True is passed to fileinput.input() or to the FileInput constructor, the file is moved to a backup file and standard output is directed to the input file (if a file of the same name as the backup file already exists, it will be replaced silently). This makes it possible to write a filter that rewrites its input file in place. If the backup parameter is given (typically as backup='.<some extension>'), it specifies the extension for the backup file, and the backup file remains around; by default, the extension is '.bak' and it is deleted when the output file is closed. In-place filtering is disabled when standard input is read.

The two following opening hooks are provided by this module:

fileinput.hook_compressed(filename, mode)

Transparently opens files compressed with gzip and bzip2 (recognized by the extensions '.gz' and '.bz2') using the gzip and bz2 modules. If the filename extension is not '.gz' or '.bz2', the file is opened normally (ie, using open() without any decompression).

Usage example: fi = fileinput.FileInput(openhook=fileinput.hook_compressed)

fileinput.hook_encoded(encoding, errors=None)

Returns a hook which opens each file with open(), using the given encoding and errors to read the file.

Usage example: fi = fileinput.FileInput(openhook=fileinput.hook_encoded("utf-8", "surrogateescape"))

버전 3.6에서 변경: Added the optional errors parameter.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

파일과 디렉터리 액세스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

파일과 디렉터리 액세스 »

|

stat — stat() 결과 해석하기

소스 코드: Lib/stat.py [https://github.com/python/cpython/tree/3.7/Lib/stat.py]

stat 모듈은 os.stat(), os.fstat() 및 os.lstat()의 (이들이 존재한다면) 결과를 해석하기 위한 상수와 함수를 정의합니다. stat(), fstat() 및 lstat() 호출에 대한 자세한 내용은 여러분의 시스템 설명서를 참조하십시오.

버전 3.4에서 변경: stat 모듈은 C 구현으로 지원됩니다.

stat 모듈은 특정 파일 유형을 검사하기 위해 다음 함수를 정의합니다:

stat.S_ISDIR(mode)

mode가 디렉터리로부터 왔으면 0이 아닌 값을 반환합니다.

stat.S_ISCHR(mode)

mode가 문자 특수 장치(character special device) 파일로부터 왔으면 0이 아닌 값을 반환합니다.

stat.S_ISBLK(mode)

mode가 블록 특수 장치(block special device) 파일로부터 왔으면 0이 아닌 값을 반환합니다.

stat.S_ISREG(mode)

mode가 일반 파일로부터 왔으면 0이 아닌 값을 반환합니다.

stat.S_ISFIFO(mode)

mode가 FIFO(네임드 파이프)로부터 왔으면 0이 아닌 값을 반환합니다.

stat.S_ISLNK(mode)

mode가 심볼릭 링크로부터 왔으면 0이 아닌 값을 반환합니다.

stat.S_ISSOCK(mode)

mode가 소켓으로부터 왔으면 0이 아닌 값을 반환합니다.

stat.S_ISDOOR(mode)

mode가 door로부터 왔으면 0이 아닌 값을 반환합니다.

버전 3.4에 추가.

stat.S_ISPORT(mode)

mode가 이벤트 포트(event port)로부터 왔으면 0이 아닌 값을 반환합니다.

버전 3.4에 추가.

stat.S_ISWHT(mode)

mode가 화이트 아웃(whiteout)으로부터 왔으면 0이 아닌 값을 반환합니다.

버전 3.4에 추가.

파일의 모드(mode)를 보다 일반적으로 조작하기 위한 두 가지 추가 함수가 정의됩니다:

stat.S_IMODE(mode)

os.chmod()로 설정할 수 있는 파일 모드 부분을 반환합니다 —즉, 파일의 권한(permission) 비트, 끈끈한(sticky) 비트, set-group-id 및 set-user-id 비트 (지원하는 시스템에서).

stat.S_IFMT(mode)

파일 유형을 기술하는 파일 모드 부분을 반환합니다 (위의 S_IS*() 함수에서 사용됩니다).

일반적으로, 파일 유형을 검사하는 데 os.path.is*() 함수를 사용합니다; 이 함수들은 같은 파일에 대해 여러 개의 검사를 수행하고, 검사마다 stat() 시스템 호출 하는 오버헤드를 피하려고 할 때 유용합니다. 또한, 블록과 문자 장치 검사와 같이, os.path에서 처리되지 않는 파일에 대한 정보를 확인할 때 유용합니다.

예제:

import os, sys
from stat import *

def walktree(top, callback):
    '''recursively descend the directory tree rooted at top,
       calling the callback function for each regular file'''

    for f in os.listdir(top):
        pathname = os.path.join(top, f)
        mode = os.stat(pathname).st_mode
        if S_ISDIR(mode):
            # It's a directory, recurse into it
            walktree(pathname, callback)
        elif S_ISREG(mode):
            # It's a file, call the callback function
            callback(pathname)
        else:
            # Unknown file type, print a message
            print('Skipping %s' % pathname)

def visitfile(file):
    print('visiting', file)

if __name__ == '__main__':
    walktree(sys.argv[1], visitfile)

파일의 모드를 사람이 읽을 수 있는 문자열로 변환하기 위한 추가 유틸리티 함수가 제공됩니다:

stat.filemode(mode)

파일의 mode를 ‘-rwxrwxrwx’ 형식의 문자열로 변환합니다.

버전 3.3에 추가.

버전 3.4에서 변경: 이 함수는 S_IFDOOR, S_IFPORT 및 S_IFWHT를 지원합니다.

아래의 모든 변수는 단순히 os.stat(), os.fstat() 또는 os.lstat()에 의해 반환된 10-튜플에 대한 기호 인덱스입니다.

stat.ST_MODE

아이 노드(inode) 보호 모드.

stat.ST_INO

아이 노드(inode) 번호.

stat.ST_DEV

아이 노드(inode)가 위치한 장치.

stat.ST_NLINK

아이 노드(inode)에 대한 링크 수.

stat.ST_UID

소유자의 사용자 id.

stat.ST_GID

소유자의 그룹 id.

stat.ST_SIZE

일반 파일의 크기(바이트); 일부 특수 파일에서는 대기중인 데이터의 양.

stat.ST_ATIME

마지막 액세스 시간.

stat.ST_MTIME

마지막 수정 시간.

stat.ST_CTIME

운영 체제에서 보고한 “ctime”. (유닉스와 같은) 일부 시스템에서는 마지막 메타 데이터 변경 시간이고, (윈도우와 같은) 다른 시스템에서는 생성 시간입니다 (자세한 내용은 플랫폼 설명서를 참조하십시오).

“파일 크기”의 해석은 파일 유형에 따라 달라집니다. 일반 파일에서는 바이트로 표현한 파일의 크기입니다. 대부분의 유닉스(특히 리눅스를 포함하는)의 FIFO와 소켓에서, “크기”는 os.stat(), os.fstat() 또는 os.lstat()를 호출한 시점에 읽기 대기 중인 바이트 수입니다; 이것은 때때로, 특히 비 블로킹으로 연 후에 이러한 특수 파일 중 하나를 폴링할 때 유용할 수 있습니다. 다른 문자와 블록 장치에서 크기 필드의 의미는 하부 시스템 호출의 구현에 따라 더 다양합니다.

아래의 변수는 ST_MODE 필드에서 사용되는 플래그를 정의합니다.

첫 번째 플래그 집합을 사용하는 것보다 위의 함수를 사용하는 것이 더 이식성 있습니다:

stat.S_IFSOCK

소켓.

stat.S_IFLNK

심볼릭 링크.

stat.S_IFREG

일반 파일.

stat.S_IFBLK

블록 장치.

stat.S_IFDIR

디렉터리.

stat.S_IFCHR

문자 장치.

stat.S_IFIFO

FIFO.

stat.S_IFDOOR

Door.

버전 3.4에 추가.

stat.S_IFPORT

이벤트 포트.

버전 3.4에 추가.

stat.S_IFWHT

화이트 아웃(whiteout).

버전 3.4에 추가.

참고

플랫폼이 파일 유형을 지원하지 않으면, S_IFDOOR, S_IFPORT 또는 S_IFWHT는 0으로 정의됩니다.

다음 플래그는 os.chmod()의 mode 인자에서도 사용할 수 있습니다:

stat.S_ISUID

Set-user-ID 비트.

stat.S_ISGID

Set-group-ID 비트. 이 비트는 몇 가지 특별한 용도로 사용됩니다. 디렉터리에서는 그 디렉터리가 BSD의 의미가 있음을 나타냅니다: 여기에 만들어진 파일은 만드는 프로세스의 유효 그룹 ID가 아니라 디렉터리에서 그룹 ID를 상속받고, S_ISGID 비트 설정도 얻습니다. 그룹 실행 비트(S_IXGRP)가 설정되지 않은 파일의 경우, set-group-ID 비트는 필수 파일/레코드 잠금을 나타냅니다 (S_ENFMT도 참조하십시오).

stat.S_ISVTX

끈끈한(sticky) 비트. 이 비트가 디렉터리에 설정되면, 해당 디렉터리의 파일은 파일의 소유자, 디렉터리의 소유자 또는 권한 있는(privileged) 프로세스에 의해서만 이름이 바뀌거나 삭제될 수 있음을 의미합니다.

stat.S_IRWXU

파일 소유자 권한(permission) 마스크.

stat.S_IRUSR

소유자에게 읽기 권한이 있습니다.

stat.S_IWUSR

소유자에게 쓰기 권한이 있습니다.

stat.S_IXUSR

소유자에게 실행 권한이 있습니다.

stat.S_IRWXG

그룹 권한 마스크.

stat.S_IRGRP

그룹에 읽기 권한이 있습니다.

stat.S_IWGRP

그룹에 쓰기 권한이 있습니다.

stat.S_IXGRP

그룹에 실행 권한이 있습니다.

stat.S_IRWXO

다른 사용자(그룹에 없는)에 대한 권한 마스크.

stat.S_IROTH

다른 사용자에게 읽기 권한이 있습니다.

stat.S_IWOTH

다른 사용자에게 쓰기 권한이 있습니다.

stat.S_IXOTH

다른 사용자에게 실행 권한이 있습니다.

stat.S_ENFMT

System V 파일 잠금 강제. 이 플래그는 S_ISGID와 공유됩니다: 파일/레코드 잠금이 그룹 실행 비트(S_IXGRP)가 설정되지 않은 파일에 적용됩니다.

stat.S_IREAD

S_IRUSR에 대한 유닉스 V7 동의어.

stat.S_IWRITE

S_IWUSR에 대한 유닉스 V7 동의어.

stat.S_IEXEC

S_IXUSR에 대한 유닉스 V7 동의어.

다음 플래그는 os.chflags()의 flags 인자에서 사용될 수 있습니다:

stat.UF_NODUMP

파일을 덤프하지 마십시오.

stat.UF_IMMUTABLE

파일을 변경할 수 없습니다.

stat.UF_APPEND

파일은 덧붙이기만 할 수 있습니다.

stat.UF_OPAQUE

디렉터리는 유니언 스택(union stack)을 통해 볼 때 불투명합니다.

stat.UF_NOUNLINK

파일의 이름을 변경하거나 삭제할 수 없습니다.

stat.UF_COMPRESSED

파일은 압축되어 저장됩니다 (맥 OS X 10.6+).

stat.UF_HIDDEN

파일을 GUI에 표시하면 안 됩니다 (맥 OS X 10.5+).

stat.SF_ARCHIVED

파일을 보관(archive)할 수 있습니다.

stat.SF_IMMUTABLE

파일을 변경할 수 없습니다.

stat.SF_APPEND

파일은 덧붙이기만 할 수 있습니다.

stat.SF_NOUNLINK

파일의 이름을 변경하거나 삭제할 수 없습니다.

stat.SF_SNAPSHOT

파일은 스냅숏(snapshot) 파일입니다.

자세한 정보는 *BSD나 맥 OS 시스템 매뉴얼 페이지 chflags(2)를 참조하십시오.

윈도우에서 os.stat()에 의해 반환된 st_file_attributes 멤버의 비트를 검사할 때 다음 파일 어트리뷰트 상수를 사용할 수 있습니다. 이러한 상수의 의미에 대한 자세한 내용은 Windows API documentation [https://msdn.microsoft.com/en-us/library/windows/desktop/gg258117.aspx]을 참조하십시오.

stat.FILE_ATTRIBUTE_ARCHIVE

stat.FILE_ATTRIBUTE_COMPRESSED

stat.FILE_ATTRIBUTE_DEVICE

stat.FILE_ATTRIBUTE_DIRECTORY

stat.FILE_ATTRIBUTE_ENCRYPTED

stat.FILE_ATTRIBUTE_HIDDEN

stat.FILE_ATTRIBUTE_INTEGRITY_STREAM

stat.FILE_ATTRIBUTE_NORMAL

stat.FILE_ATTRIBUTE_NOT_CONTENT_INDEXED

stat.FILE_ATTRIBUTE_NO_SCRUB_DATA

stat.FILE_ATTRIBUTE_OFFLINE

stat.FILE_ATTRIBUTE_READONLY

stat.FILE_ATTRIBUTE_REPARSE_POINT

stat.FILE_ATTRIBUTE_SPARSE_FILE

stat.FILE_ATTRIBUTE_SYSTEM

stat.FILE_ATTRIBUTE_TEMPORARY

stat.FILE_ATTRIBUTE_VIRTUAL

버전 3.5에 추가.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

파일과 디렉터리 액세스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

파일과 디렉터리 액세스 »

|

filecmp — 파일과 디렉터리 비교

소스 코드: Lib/filecmp.py [https://github.com/python/cpython/tree/3.7/Lib/filecmp.py]

filecmp 모듈은 다양한 선택적 시간/정확도 절충을 통해 파일과 디렉터리를 비교하는 함수를 정의합니다. 파일 비교에 대해서는, difflib 모듈을 참조하십시오.

filecmp 모듈은 다음 함수를 정의합니다:

filecmp.cmp(f1, f2, shallow=True)

f1와 f2로 이름이 지정된 파일을 비교하여, 같아 보이면 True를 반환하고, 그렇지 않으면 False를 반환합니다.

shallow가 참이면 같은 os.stat() 서명을 갖는 파일을 같다고 취급합니다. 그렇지 않으면 파일의 내용을 비교합니다.

이 함수는 외부 프로그램을 호출하지 않으므로 이식성과 효율성을 제공합니다.

이 함수는 과거 비교와 결과에 대해 캐시를 사용합니다. 파일에 대한 os.stat() 정보가 변경되면 캐시 항목이 무효화 됩니다. 전체 캐시는 clear_cache()를 사용하여 지울 수 있습니다.

filecmp.cmpfiles(dir1, dir2, common, shallow=True)

두 디렉터리 dir1 과 dir2에 있는 이름이 common으로 지정된 파일들을 비교합니다.

파일 이름의 세 가지 리스트를 반환합니다: match, mismatch, errors. match는 일치하는 파일 리스트를 포함하고, mismatch는 일치하지 않는 파일의 이름을 포함하며, errors는 비교할 수 없는 파일의 이름을 나열합니다. 파일이 디렉터리 중 하나에 없거나, 사용자가 읽을 수 있는 권한이 없거나, 다른 이유로 인해 비교를 수행할 수 없으면 파일은 errors에 나열됩니다.

shallow 매개 변수는 filecmp.cmp()와 같은 의미와 기본값을 가집니다.

예를 들어, cmpfiles('a', 'b', ['c', 'd/e'])는 a/c와 b/c, a/d/e와 b/d/e를 비교합니다. 'c' 와 'd/e'는 각각 반환된 세 개의 리스트 중 하나에 포함됩니다.

filecmp.clear_cache()

filecmp 캐시를 지웁니다. 파일이 수정된 후 너무 빨리 비교되어 하부 파일 시스템의 mtime 해상도 내에 있을 때 유용합니다.

버전 3.4에 추가.

dircmp 클래스

class filecmp.dircmp(a, b, ignore=None, hide=None)

a와 b 디렉터리를 비교하기 위한, 새로운 디렉터리 비교 객체를 만듭니다. ignore는 무시할 이름 리스트며, 기본값은 filecmp.DEFAULT_IGNORES입니다. hide는 숨길 이름 리스트며 기본값은 [os.curdir, os.pardir]입니다.

dircmp 클래스는 filecmp.cmp()에서 설명한 대로 얕은(shallow) 비교를 수행하여 파일을 비교합니다.

dircmp 클래스는 다음 메서드를 제공합니다:

report()

a와 b 사이의 비교를 (sys.stdout로) 인쇄합니다.

report_partial_closure()

a와 b 및 공통 직접 하위 디렉터리 사이의 비교를 인쇄합니다.

report_full_closure()

a와 b 및 공통 하위 디렉터리 (재귀적으로) 사이의 비교를 인쇄합니다.

dircmp 클래스는 비교되는 디렉터리 트리에 대한 다양한 정보 비트를 얻는 데 사용될 수 있는 여러 가지 흥미로운 어트리뷰트를 제공합니다.

__getattr__() 훅을 통해, 모든 어트리뷰트가 느긋하게(lazily) 계산되므로, 계산하기가 가벼운 어트리뷰트만 사용하면 속도가 저하되지 않습니다.

left

디렉터리 a.

right

디렉터리 b.

left_list

hide 와 ignore로 필터링 된, a의 파일과 하위 디렉터리.

right_list

hide 와 ignore로 필터링 된, b의 파일과 하위 디렉터리.

common

a 와 b의 공통 파일과 하위 디렉터리.

left_only

a에만 있는 파일과 하위 디렉터리.

right_only

b에만 있는 파일과 하위 디렉터리.

common_dirs

a 및 b의 공통 하위 디렉터리.

common_files

a 와 b의 공통 파일.

common_funny

a와 b의 공통 이름으로, 디렉터리 간에 유형이 다르거나, os.stat()가 에러를 보고하는 이름.

same_files

a 와 b에 모두 있고, 클래스의 파일 비교 연산자를 사용할 때 같은 파일.

diff_files

a 및 b에 모두 있고, 클래스의 파일 비교 연산자를 사용할 때 내용이 다른 파일.

funny_files

a 및 b에 모두 있지만, 비교할 수 없는 파일.

subdirs

common_dirs의 이름을 dircmp 객체로 매핑하는 딕셔너리.

filecmp.DEFAULT_IGNORES

버전 3.4에 추가.

dircmp에 의해 기본적으로 무시되는 디렉터리 리스트.

다음은 이름이 같지만, 내용이 다른 파일을 표시하기 위해, subdirs 어트리뷰트로 두 개의 디렉터리를 재귀적으로 검색하는 간단한 예제입니다:

>>> from filecmp import dircmp
>>> def print_diff_files(dcmp):
...     for name in dcmp.diff_files:
...         print("diff_file %s found in %s and %s" % (name, dcmp.left,
...               dcmp.right))
...     for sub_dcmp in dcmp.subdirs.values():
...         print_diff_files(sub_dcmp)
...
>>> dcmp = dircmp('dir1', 'dir2')
>>> print_diff_files(dcmp)

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

파일과 디렉터리 액세스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

파일과 디렉터리 액세스 »

|

tempfile — Generate temporary files and directories

Source code: Lib/tempfile.py [https://github.com/python/cpython/tree/3.7/Lib/tempfile.py]

This module creates temporary files and directories. It works on all supported platforms. TemporaryFile, NamedTemporaryFile, TemporaryDirectory, and SpooledTemporaryFile are high-level interfaces which provide automatic cleanup and can be used as context managers. mkstemp() and mkdtemp() are lower-level functions which require manual cleanup.

All the user-callable functions and constructors take additional arguments which allow direct control over the location and name of temporary files and directories. Files names used by this module include a string of random characters which allows those files to be securely created in shared temporary directories. To maintain backward compatibility, the argument order is somewhat odd; it is recommended to use keyword arguments for clarity.

The module defines the following user-callable items:

tempfile.TemporaryFile(mode='w+b', buffering=None, encoding=None, newline=None, suffix=None, prefix=None, dir=None)

Return a file-like object that can be used as a temporary storage area. The file is created securely, using the same rules as mkstemp(). It will be destroyed as soon as it is closed (including an implicit close when the object is garbage collected). Under Unix, the directory entry for the file is either not created at all or is removed immediately after the file is created. Other platforms do not support this; your code should not rely on a temporary file created using this function having or not having a visible name in the file system.

The resulting object can be used as a context manager (see Examples). On completion of the context or destruction of the file object the temporary file will be removed from the filesystem.

The mode parameter defaults to 'w+b' so that the file created can be read and written without being closed. Binary mode is used so that it behaves consistently on all platforms without regard for the data that is stored. buffering, encoding and newline are interpreted as for open().

The dir, prefix and suffix parameters have the same meaning and defaults as with mkstemp().

The returned object is a true file object on POSIX platforms. On other platforms, it is a file-like object whose file attribute is the underlying true file object.

The os.O_TMPFILE flag is used if it is available and works (Linux-specific, requires Linux kernel 3.11 or later).

버전 3.5에서 변경: The os.O_TMPFILE flag is now used if available.

tempfile.NamedTemporaryFile(mode='w+b', buffering=None, encoding=None, newline=None, suffix=None, prefix=None, dir=None, delete=True)

This function operates exactly as TemporaryFile() does, except that the file is guaranteed to have a visible name in the file system (on Unix, the directory entry is not unlinked). That name can be retrieved from the name attribute of the returned file-like object. Whether the name can be used to open the file a second time, while the named temporary file is still open, varies across platforms (it can be so used on Unix; it cannot on Windows NT or later). If delete is true (the default), the file is deleted as soon as it is closed. The returned object is always a file-like object whose file attribute is the underlying true file object. This file-like object can be used in a with statement, just like a normal file.

tempfile.SpooledTemporaryFile(max_size=0, mode='w+b', buffering=None, encoding=None, newline=None, suffix=None, prefix=None, dir=None)

This function operates exactly as TemporaryFile() does, except that data is spooled in memory until the file size exceeds max_size, or until the file’s fileno() method is called, at which point the contents are written to disk and operation proceeds as with TemporaryFile().

The resulting file has one additional method, rollover(), which causes the file to roll over to an on-disk file regardless of its size.

The returned object is a file-like object whose _file attribute is either an io.BytesIO or io.TextIOWrapper object (depending on whether binary or text mode was specified) or a true file object, depending on whether rollover() has been called. This file-like object can be used in a with statement, just like a normal file.

버전 3.3에서 변경: the truncate method now accepts a size argument.

tempfile.TemporaryDirectory(suffix=None, prefix=None, dir=None)

This function securely creates a temporary directory using the same rules as mkdtemp(). The resulting object can be used as a context manager (see Examples). On completion of the context or destruction of the temporary directory object the newly created temporary directory and all its contents are removed from the filesystem.

The directory name can be retrieved from the name attribute of the returned object. When the returned object is used as a context manager, the name will be assigned to the target of the as clause in the with statement, if there is one.

The directory can be explicitly cleaned up by calling the cleanup() method.

버전 3.2에 추가.

tempfile.mkstemp(suffix=None, prefix=None, dir=None, text=False)

Creates a temporary file in the most secure manner possible. There are no race conditions in the file’s creation, assuming that the platform properly implements the os.O_EXCL flag for os.open(). The file is readable and writable only by the creating user ID. If the platform uses permission bits to indicate whether a file is executable, the file is executable by no one. The file descriptor is not inherited by child processes.

Unlike TemporaryFile(), the user of mkstemp() is responsible for deleting the temporary file when done with it.

If suffix is not None, the file name will end with that suffix, otherwise there will be no suffix. mkstemp() does not put a dot between the file name and the suffix; if you need one, put it at the beginning of suffix.

If prefix is not None, the file name will begin with that prefix; otherwise, a default prefix is used. The default is the return value of gettempprefix() or gettempprefixb(), as appropriate.

If dir is not None, the file will be created in that directory; otherwise, a default directory is used. The default directory is chosen from a platform-dependent list, but the user of the application can control the directory location by setting the TMPDIR, TEMP or TMP environment variables. There is thus no guarantee that the generated filename will have any nice properties, such as not requiring quoting when passed to external commands via os.popen().

If any of suffix, prefix, and dir are not None, they must be the same type. If they are bytes, the returned name will be bytes instead of str. If you want to force a bytes return value with otherwise default behavior, pass suffix=b''.

If text is specified, it indicates whether to open the file in binary mode (the default) or text mode. On some platforms, this makes no difference.

mkstemp() returns a tuple containing an OS-level handle to an open file (as would be returned by os.open()) and the absolute pathname of that file, in that order.

버전 3.5에서 변경: suffix, prefix, and dir may now be supplied in bytes in order to obtain a bytes return value. Prior to this, only str was allowed. suffix and prefix now accept and default to None to cause an appropriate default value to be used.

버전 3.6에서 변경: The dir parameter now accepts a path-like object.

tempfile.mkdtemp(suffix=None, prefix=None, dir=None)

Creates a temporary directory in the most secure manner possible. There are no race conditions in the directory’s creation. The directory is readable, writable, and searchable only by the creating user ID.

The user of mkdtemp() is responsible for deleting the temporary directory and its contents when done with it.

The prefix, suffix, and dir arguments are the same as for mkstemp().

mkdtemp() returns the absolute pathname of the new directory.

버전 3.5에서 변경: suffix, prefix, and dir may now be supplied in bytes in order to obtain a bytes return value. Prior to this, only str was allowed. suffix and prefix now accept and default to None to cause an appropriate default value to be used.

버전 3.6에서 변경: The dir parameter now accepts a path-like object.

tempfile.gettempdir()

Return the name of the directory used for temporary files. This defines the default value for the dir argument to all functions in this module.

Python searches a standard list of directories to find one which the calling user can create files in. The list is:

The directory named by the TMPDIR environment variable.

The directory named by the TEMP environment variable.

The directory named by the TMP environment variable.

A platform-specific location:

On Windows, the directories C:\TEMP, C:\TMP, \TEMP, and \TMP, in that order.

On all other platforms, the directories /tmp, /var/tmp, and /usr/tmp, in that order.

As a last resort, the current working directory.

The result of this search is cached, see the description of tempdir below.

tempfile.gettempdirb()

Same as gettempdir() but the return value is in bytes.

버전 3.5에 추가.

tempfile.gettempprefix()

Return the filename prefix used to create temporary files. This does not contain the directory component.

tempfile.gettempprefixb()

Same as gettempprefix() but the return value is in bytes.

버전 3.5에 추가.

The module uses a global variable to store the name of the directory used for temporary files returned by gettempdir(). It can be set directly to override the selection process, but this is discouraged. All functions in this module take a dir argument which can be used to specify the directory and this is the recommended approach.

tempfile.tempdir

When set to a value other than None, this variable defines the default value for the dir argument to the functions defined in this module.

If tempdir is None (the default) at any call to any of the above functions except gettempprefix() it is initialized following the algorithm described in gettempdir().

Examples

Here are some examples of typical usage of the tempfile module:

>>> import tempfile

# create a temporary file and write some data to it
>>> fp = tempfile.TemporaryFile()
>>> fp.write(b'Hello world!')
# read data from file
>>> fp.seek(0)
>>> fp.read()
b'Hello world!'
# close the file, it will be removed
>>> fp.close()

# create a temporary file using a context manager
>>> with tempfile.TemporaryFile() as fp:
...     fp.write(b'Hello world!')
...     fp.seek(0)
...     fp.read()
b'Hello world!'
>>>
# file is now closed and removed

# create a temporary directory using the context manager
>>> with tempfile.TemporaryDirectory() as tmpdirname:
...     print('created temporary directory', tmpdirname)
>>>
# directory and contents have been removed

Deprecated functions and variables

A historical way to create temporary files was to first generate a file name with the mktemp() function and then create a file using this name. Unfortunately this is not secure, because a different process may create a file with this name in the time between the call to mktemp() and the subsequent attempt to create the file by the first process. The solution is to combine the two steps and create the file immediately. This approach is used by mkstemp() and the other functions described above.

tempfile.mktemp(suffix='', prefix='tmp', dir=None)

버전 2.3부터 폐지: Use mkstemp() instead.

Return an absolute pathname of a file that did not exist at the time the call is made. The prefix, suffix, and dir arguments are similar to those of mkstemp(), except that bytes file names, suffix=None and prefix=None are not supported.

경고

Use of this function may introduce a security hole in your program. By the time you get around to doing anything with the file name it returns, someone else may have beaten you to the punch. mktemp() usage can be replaced easily with NamedTemporaryFile(), passing it the delete=False parameter:

>>> f = NamedTemporaryFile(delete=False)
>>> f.name
'/tmp/tmptjujjt'
>>> f.write(b"Hello World!\n")
13
>>> f.close()
>>> os.unlink(f.name)
>>> os.path.exists(f.name)
False

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

파일과 디렉터리 액세스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

파일과 디렉터리 액세스 »

|

glob — 유닉스 스타일 경로명 패턴 확장

소스 코드: Lib/glob.py [https://github.com/python/cpython/tree/3.7/Lib/glob.py]

glob 모듈은 유닉스 셸이 사용하는 규칙에 따라 지정된 패턴과 일치하는 모든 경로명을 찾습니다. 하지만 결과는 임의의 순서로 반환됩니다. 물결표(tilde) 확장은 수행되지 않지만, *, ? 및 []로 표시되는 문자 범위는 올바르게 일치합니다. 이는 서브 셸을 실제로 호출하지 않고 os.scandir() 과 fnmatch.fnmatch() 함수를 사용하여 수행됩니다. fnmatch.fnmatch()와 달리, glob은 점(.)으로 시작하는 파일 이름을 특수한 경우로 취급합니다. (물결표와 셸 변수 확장은 os.path.expanduser() 와 os.path.expandvars()를 사용하십시오.)

리터럴 일치를 위해서는, 대괄호 안에 메타 문자를 넣습니다. 예를 들어, '[?]'는 '?' 문자와 일치합니다.

더 보기

pathlib 모듈은 고수준의 경로 객체를 제공합니다.

glob.glob(pathname, *, recursive=False)

경로 지정을 포함하는 문자열인 pathname에 일치하는 경로 이름의 비어있을 수 있는 리스트를 반환합니다. pathname은 절대(/usr/src/Python-1.5/Makefile처럼)나 상대(../../Tools/*/*.gif처럼)일 수 있으며, 셸 스타일 와일드카드를 포함할 수 있습니다. 깨진 심볼릭 링크가 결과에 포함됩니다 (셸과 마찬가지로).

If recursive is true, the pattern “**” will match any files and zero or more directories, subdirectories and symbolic links to directories. If the pattern is followed by an os.sep or os.altsep then files will not match.

참고

커다란 디렉터리 트리에서 “**” 패턴을 사용하면 과도한 시간이 걸릴 수 있습니다.

버전 3.5에서 변경: “**” 를 사용하는 재귀적 glob 지원.

glob.iglob(pathname, *, recursive=False)

실제로 동시에 저장하지 않고 glob()과 같은 값을 산출하는 이터레이터를 반환합니다.

glob.escape(pathname)

모든 특수 문자('?', '*' 및 '[')를 이스케이프 처리합니다. 이것은 특수 문자가 들어있을 수 있는 임의의 리터럴 문자열을 일치시키려는 경우에 유용합니다. 드라이브/UNC 셰어 포인트의 특수 문자는 이스케이프 되지 않습니다, 예를 들어, 윈도우에서 escape('//?/c:/Quo vadis?.txt')는 '//?/c:/Quo vadis[?].txt'를 반환합니다.

버전 3.4에 추가.

예를 들어, 다음과 같은 파일을 포함하는 디렉터리를 고려하십시오: 1.gif, 2.txt, card.gif 및 3.txt 파일 만 포함하는 서브 디렉터리 sub. glob()은 다음과 같은 결과를 산출합니다. 경로의 선행 구성 요소가 보존되는 방법에 유의하십시오.

>>> import glob
>>> glob.glob('./[0-9].*')
['./1.gif', './2.txt']
>>> glob.glob('*.gif')
['1.gif', 'card.gif']
>>> glob.glob('?.gif')
['1.gif']
>>> glob.glob('**/*.txt', recursive=True)
['2.txt', 'sub/3.txt']
>>> glob.glob('./**/', recursive=True)
['./', './sub/']

디렉터리에 .으로 시작하는 파일이 있으면, 기본적으로 일치하지 않습니다. 예를 들어, card.gif 와 .card.gif를 포함하는 디렉터리를 고려하십시오:

>>> import glob
>>> glob.glob('*.gif')
['card.gif']
>>> glob.glob('.c*')
['.card.gif']

더 보기

모듈 fnmatch

셸 스타일 파일명 (경로가 아님) 확장

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

파일과 디렉터리 액세스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

파일과 디렉터리 액세스 »

|

fnmatch — 유닉스 파일명 패턴 일치

소스 코드: Lib/fnmatch.py [https://github.com/python/cpython/tree/3.7/Lib/fnmatch.py]

이 모듈은 유닉스 셸 스타일의 와일드카드를 지원하며, 이는 정규식(re 모듈에서 설명합니다)과는 다릅니다. 셸 스타일 와일드카드에 사용되는 특수 문자는 다음과 같습니다:

패턴

의미

*

모든 것과 일치합니다

?

모든 단일 문자와 일치합니다

[seq]

seq의 모든 문자와 일치합니다.

[!seq]

seq에 없는 모든 문자와 일치합니다

리터럴 일치의 경우, 대괄호 안에 메타 문자를 넣습니다. 예를 들어, '[?]'는 '?' 문자와 일치합니다.

파일명 분리 기호(유닉스에서 '/')는 이 모듈에서 특수하지 않습니다. 경로명 확장은 모듈 glob을 참조하십시오 (glob은 경로명 세그먼트와 일치시키기 위해 filter()를 사용합니다). 마찬가지로, 마침표로 시작하는 파일명은 이 모듈에서 특수하지 않으며, * 및 ? 패턴과 일치합니다.

fnmatch.fnmatch(filename, pattern)

filename 문자열이 pattern 문자열과 일치하는지를 검사하여, True 나 False를 반환합니다. 두 매개 변수는 모두 os.path.normcase()를 사용하여 대소 문자를 정규화합니다. fnmatchcase()는 운영 체제의 표준인지에 관계없이, 대소문자를 구분하는 비교를 수행하는 데 사용할 수 있습니다.

이 예제는 현재 디렉터리의 확장자 .txt 인 모든 파일 이름을 인쇄합니다:

import fnmatch
import os

for file in os.listdir('.'):
    if fnmatch.fnmatch(file, '*.txt'):
        print(file)

fnmatch.fnmatchcase(filename, pattern)

filename이 pattern과 일치하는지를 검사하여, True 나 False를 반환합니다; 비교는 대소 문자를 구분하며, os.path.normcase()를 적용하지 않습니다.

fnmatch.filter(names, pattern)

pattern에 일치하는 names 리스트의 부분 집합을 반환합니다. [n for n in names if fnmatch(n, pattern)]과 같지만, 더 효율적으로 구현됩니다.

fnmatch.translate(pattern)

셸 스타일의 pattern을 re.match()에서 사용하기 위해 정규식으로 변환한 값을 반환합니다.

예제:

>>> import fnmatch, re
>>>
>>> regex = fnmatch.translate('*.txt')
>>> regex
'(?s:.*\\.txt)\\Z'
>>> reobj = re.compile(regex)
>>> reobj.match('foobar.txt')
<re.Match object; span=(0, 10), match='foobar.txt'>

더 보기

모듈 glob

유닉스 셸 스타일 경로 확장.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

파일과 디렉터리 액세스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

파일과 디렉터리 액세스 »

|

linecache — 텍스트 줄에 대한 무작위 액세스

소스 코드: Lib/linecache.py [https://github.com/python/cpython/tree/3.7/Lib/linecache.py]

linecache 모듈은 파이썬 소스 파일에서 임의의 줄을 가져올 수 있도록 하는데, 캐시를 사용하여 단일 파일에서 여러 줄을 읽는 일반적인 상황을 내부적으로 최적화하려고 시도합니다. 이것은 traceback 모듈에서 포맷된 트레이스백에 포함할 소스 줄을 가져오는 데 사용됩니다.

tokenize.open() 함수가 파일을 여는 데 사용됩니다. 이 함수는 tokenize.detect_encoding()를 사용하여 파일의 인코딩을 가져옵니다; 인코딩 토큰이 없으면, 파일 인코딩의 기본값은 UTF-8입니다.

linecache 모듈은 다음 함수를 정의합니다:

linecache.getline(filename, lineno, module_globals=None)

filename 파일에서 lineno 줄을 가져옵니다. 이 함수는 절대 예외를 발생시키지 않을 것입니다 — 에러 시 ''를 반환합니다 (발견된 줄의 줄 바꿈 문자는 포함됩니다).

filename이라는 파일이 없으면, 이 함수는 먼저 module_globals에서 PEP 302 [https://www.python.org/dev/peps/pep-0302] __loader__를 먼저 확인한 후(zip 파일이나 기타 파일 시스템 이외의 임포트 소스에서 모듈이 임포트 됩니다) 모듈 검색 경로, sys.path, 에서 파일을 찾습니다.

linecache.clearcache()

캐시를 지웁니다. 이전에 getline()를 사용하여 읽은 파일의 줄이 더는 필요하지 않으면 이 함수를 사용하십시오.

linecache.checkcache(filename=None)

캐시의 유효성을 확인합니다. 캐시의 파일이 디스크에서 변경되었을 수 있고, 갱신된 버전이 필요하면 이 함수를 사용하십시오. filename이 생략되면, 캐시의 모든 항목을 검사합니다.

linecache.lazycache(filename, module_globals)

이후 호출에서 module_globals가 None이더라도 getline()을 통해 나중에 해당 줄을 가져올 수 있도록, 파일 기반이 아닌 모듈에 대한 충분한 정보를 캡처합니다. 이렇게 하면 라인이 실제로 필요할 때까지 모듈 전역을 무기한으로 들고 있지 않고도 I/O를 회피합니다.

버전 3.5에 추가.

예제:

>>> import linecache
>>> linecache.getline(linecache.__file__, 8)
'import sys\n'

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

파일과 디렉터리 액세스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

파일과 디렉터리 액세스 »

|

shutil — High-level file operations

Source code: Lib/shutil.py [https://github.com/python/cpython/tree/3.7/Lib/shutil.py]

The shutil module offers a number of high-level operations on files and collections of files. In particular, functions are provided which support file copying and removal. For operations on individual files, see also the os module.

경고

Even the higher-level file copying functions (shutil.copy(), shutil.copy2()) cannot copy all file metadata.

On POSIX platforms, this means that file owner and group are lost as well as ACLs. On Mac OS, the resource fork and other metadata are not used. This means that resources will be lost and file type and creator codes will not be correct. On Windows, file owners, ACLs and alternate data streams are not copied.

Directory and files operations

shutil.copyfileobj(fsrc, fdst[, length])

Copy the contents of the file-like object fsrc to the file-like object fdst. The integer length, if given, is the buffer size. In particular, a negative length value means to copy the data without looping over the source data in chunks; by default the data is read in chunks to avoid uncontrolled memory consumption. Note that if the current file position of the fsrc object is not 0, only the contents from the current file position to the end of the file will be copied.

shutil.copyfile(src, dst, *, follow_symlinks=True)

Copy the contents (no metadata) of the file named src to a file named dst and return dst. src and dst are path names given as strings. dst must be the complete target file name; look at shutil.copy() for a copy that accepts a target directory path. If src and dst specify the same file, SameFileError is raised.

The destination location must be writable; otherwise, an OSError exception will be raised. If dst already exists, it will be replaced. Special files such as character or block devices and pipes cannot be copied with this function.

If follow_symlinks is false and src is a symbolic link, a new symbolic link will be created instead of copying the file src points to.

버전 3.3에서 변경: IOError used to be raised instead of OSError. Added follow_symlinks argument. Now returns dst.

버전 3.4에서 변경: Raise SameFileError instead of Error. Since the former is a subclass of the latter, this change is backward compatible.

exception shutil.SameFileError

This exception is raised if source and destination in copyfile() are the same file.

버전 3.4에 추가.

shutil.copymode(src, dst, *, follow_symlinks=True)

Copy the permission bits from src to dst. The file contents, owner, and group are unaffected. src and dst are path names given as strings. If follow_symlinks is false, and both src and dst are symbolic links, copymode() will attempt to modify the mode of dst itself (rather than the file it points to). This functionality is not available on every platform; please see copystat() for more information. If copymode() cannot modify symbolic links on the local platform, and it is asked to do so, it will do nothing and return.

버전 3.3에서 변경: Added follow_symlinks argument.

shutil.copystat(src, dst, *, follow_symlinks=True)

Copy the permission bits, last access time, last modification time, and flags from src to dst. On Linux, copystat() also copies the “extended attributes” where possible. The file contents, owner, and group are unaffected. src and dst are path names given as strings.

If follow_symlinks is false, and src and dst both refer to symbolic links, copystat() will operate on the symbolic links themselves rather than the files the symbolic links refer to—reading the information from the src symbolic link, and writing the information to the dst symbolic link.

참고

Not all platforms provide the ability to examine and modify symbolic links. Python itself can tell you what functionality is locally available.

If os.chmod in os.supports_follow_symlinks is True, copystat() can modify the permission bits of a symbolic link.

If os.utime in os.supports_follow_symlinks is True, copystat() can modify the last access and modification times of a symbolic link.

If os.chflags in os.supports_follow_symlinks is True, copystat() can modify the flags of a symbolic link. (os.chflags is not available on all platforms.)

On platforms where some or all of this functionality is unavailable, when asked to modify a symbolic link, copystat() will copy everything it can. copystat() never returns failure.

Please see os.supports_follow_symlinks for more information.

버전 3.3에서 변경: Added follow_symlinks argument and support for Linux extended attributes.

shutil.copy(src, dst, *, follow_symlinks=True)

Copies the file src to the file or directory dst. src and dst should be strings. If dst specifies a directory, the file will be copied into dst using the base filename from src. Returns the path to the newly created file.

If follow_symlinks is false, and src is a symbolic link, dst will be created as a symbolic link. If follow_symlinks is true and src is a symbolic link, dst will be a copy of the file src refers to.

copy() copies the file data and the file’s permission mode (see os.chmod()). Other metadata, like the file’s creation and modification times, is not preserved. To preserve all file metadata from the original, use copy2() instead.

버전 3.3에서 변경: Added follow_symlinks argument. Now returns path to the newly created file.

shutil.copy2(src, dst, *, follow_symlinks=True)

Identical to copy() except that copy2() also attempts to preserve file metadata.

When follow_symlinks is false, and src is a symbolic link, copy2() attempts to copy all metadata from the src symbolic link to the newly-created dst symbolic link. However, this functionality is not available on all platforms. On platforms where some or all of this functionality is unavailable, copy2() will preserve all the metadata it can; copy2() never returns failure.

copy2() uses copystat() to copy the file metadata. Please see copystat() for more information about platform support for modifying symbolic link metadata.

버전 3.3에서 변경: Added follow_symlinks argument, try to copy extended file system attributes too (currently Linux only). Now returns path to the newly created file.

shutil.ignore_patterns(*patterns)

This factory function creates a function that can be used as a callable for copytree()’s ignore argument, ignoring files and directories that match one of the glob-style patterns provided. See the example below.

shutil.copytree(src, dst, symlinks=False, ignore=None, copy_function=copy2, ignore_dangling_symlinks=False)

Recursively copy an entire directory tree rooted at src, returning the destination directory. The destination directory, named by dst, must not already exist; it will be created as well as missing parent directories. Permissions and times of directories are copied with copystat(), individual files are copied using shutil.copy2().

If symlinks is true, symbolic links in the source tree are represented as symbolic links in the new tree and the metadata of the original links will be copied as far as the platform allows; if false or omitted, the contents and metadata of the linked files are copied to the new tree.

When symlinks is false, if the file pointed by the symlink doesn’t exist, an exception will be added in the list of errors raised in an Error exception at the end of the copy process. You can set the optional ignore_dangling_symlinks flag to true if you want to silence this exception. Notice that this option has no effect on platforms that don’t support os.symlink().

If ignore is given, it must be a callable that will receive as its arguments the directory being visited by copytree(), and a list of its contents, as returned by os.listdir(). Since copytree() is called recursively, the ignore callable will be called once for each directory that is copied. The callable must return a sequence of directory and file names relative to the current directory (i.e. a subset of the items in its second argument); these names will then be ignored in the copy process. ignore_patterns() can be used to create such a callable that ignores names based on glob-style patterns.

If exception(s) occur, an Error is raised with a list of reasons.

If copy_function is given, it must be a callable that will be used to copy each file. It will be called with the source path and the destination path as arguments. By default, shutil.copy2() is used, but any function that supports the same signature (like shutil.copy()) can be used.

버전 3.3에서 변경: Copy metadata when symlinks is false. Now returns dst.

버전 3.2에서 변경: Added the copy_function argument to be able to provide a custom copy function. Added the ignore_dangling_symlinks argument to silent dangling symlinks errors when symlinks is false.

shutil.rmtree(path, ignore_errors=False, onerror=None)

Delete an entire directory tree; path must point to a directory (but not a symbolic link to a directory). If ignore_errors is true, errors resulting from failed removals will be ignored; if false or omitted, such errors are handled by calling a handler specified by onerror or, if that is omitted, they raise an exception.

참고

On platforms that support the necessary fd-based functions a symlink attack resistant version of rmtree() is used by default. On other platforms, the rmtree() implementation is susceptible to a symlink attack: given proper timing and circumstances, attackers can manipulate symlinks on the filesystem to delete files they wouldn’t be able to access otherwise. Applications can use the rmtree.avoids_symlink_attacks function attribute to determine which case applies.

If onerror is provided, it must be a callable that accepts three parameters: function, path, and excinfo.

The first parameter, function, is the function which raised the exception; it depends on the platform and implementation. The second parameter, path, will be the path name passed to function. The third parameter, excinfo, will be the exception information returned by sys.exc_info(). Exceptions raised by onerror will not be caught.

버전 3.3에서 변경: Added a symlink attack resistant version that is used automatically if platform supports fd-based functions.

rmtree.avoids_symlink_attacks

Indicates whether the current platform and implementation provides a symlink attack resistant version of rmtree(). Currently this is only true for platforms supporting fd-based directory access functions.

버전 3.3에 추가.

shutil.move(src, dst, copy_function=copy2)

Recursively move a file or directory (src) to another location (dst) and return the destination.

If the destination is an existing directory, then src is moved inside that directory. If the destination already exists but is not a directory, it may be overwritten depending on os.rename() semantics.

If the destination is on the current filesystem, then os.rename() is used. Otherwise, src is copied to dst using copy_function and then removed. In case of symlinks, a new symlink pointing to the target of src will be created in or as dst and src will be removed.

If copy_function is given, it must be a callable that takes two arguments src and dst, and will be used to copy src to dest if os.rename() cannot be used. If the source is a directory, copytree() is called, passing it the copy_function(). The default copy_function is copy2(). Using copy() as the copy_function allows the move to succeed when it is not possible to also copy the metadata, at the expense of not copying any of the metadata.

버전 3.3에서 변경: Added explicit symlink handling for foreign filesystems, thus adapting it to the behavior of GNU’s mv. Now returns dst.

버전 3.5에서 변경: Added the copy_function keyword argument.

shutil.disk_usage(path)

Return disk usage statistics about the given path as a named tuple with the attributes total, used and free, which are the amount of total, used and free space, in bytes. On Windows, path must be a directory; on Unix, it can be a file or directory.

버전 3.3에 추가.

Availability: Unix, Windows.

shutil.chown(path, user=None, group=None)

Change owner user and/or group of the given path.

user can be a system user name or a uid; the same applies to group. At least one argument is required.

See also os.chown(), the underlying function.

Availability: Unix.

버전 3.3에 추가.

shutil.which(cmd, mode=os.F_OK | os.X_OK, path=None)

Return the path to an executable which would be run if the given cmd was called. If no cmd would be called, return None.

mode is a permission mask passed to os.access(), by default determining if the file exists and executable.

When no path is specified, the results of os.environ() are used, returning either the “PATH” value or a fallback of os.defpath.

On Windows, the current directory is always prepended to the path whether or not you use the default or provide your own, which is the behavior the command shell uses when finding executables. Additionally, when finding the cmd in the path, the PATHEXT environment variable is checked. For example, if you call shutil.which("python"), which() will search PATHEXT to know that it should look for python.exe within the path directories. For example, on Windows:

>>> shutil.which("python")
'C:\\Python33\\python.EXE'

버전 3.3에 추가.

exception shutil.Error

This exception collects exceptions that are raised during a multi-file operation. For copytree(), the exception argument is a list of 3-tuples (srcname, dstname, exception).

copytree example

This example is the implementation of the copytree() function, described above, with the docstring omitted. It demonstrates many of the other functions provided by this module.

def copytree(src, dst, symlinks=False):
    names = os.listdir(src)
    os.makedirs(dst)
    errors = []
    for name in names:
        srcname = os.path.join(src, name)
        dstname = os.path.join(dst, name)
        try:
            if symlinks and os.path.islink(srcname):
                linkto = os.readlink(srcname)
                os.symlink(linkto, dstname)
            elif os.path.isdir(srcname):
                copytree(srcname, dstname, symlinks)
            else:
                copy2(srcname, dstname)
            # XXX What about devices, sockets etc.?
        except OSError as why:
            errors.append((srcname, dstname, str(why)))
        # catch the Error from the recursive copytree so that we can
        # continue with other files
        except Error as err:
            errors.extend(err.args[0])
    try:
        copystat(src, dst)
    except OSError as why:
        # can't copy file access times on Windows
        if why.winerror is None:
            errors.extend((src, dst, str(why)))
    if errors:
        raise Error(errors)

Another example that uses the ignore_patterns() helper:

from shutil import copytree, ignore_patterns

copytree(source, destination, ignore=ignore_patterns('*.pyc', 'tmp*'))

This will copy everything except .pyc files and files or directories whose name starts with tmp.

Another example that uses the ignore argument to add a logging call:

from shutil import copytree
import logging

def _logpath(path, names):
    logging.info('Working in %s', path)
    return []   # nothing will be ignored

copytree(source, destination, ignore=_logpath)

rmtree example

This example shows how to remove a directory tree on Windows where some of the files have their read-only bit set. It uses the onerror callback to clear the readonly bit and reattempt the remove. Any subsequent failure will propagate.

import os, stat
import shutil

def remove_readonly(func, path, _):
    "Clear the readonly bit and reattempt the removal"
    os.chmod(path, stat.S_IWRITE)
    func(path)

shutil.rmtree(directory, onerror=remove_readonly)

Archiving operations

버전 3.2에 추가.

버전 3.5에서 변경: Added support for the xztar format.

High-level utilities to create and read compressed and archived files are also provided. They rely on the zipfile and tarfile modules.

shutil.make_archive(base_name, format[, root_dir[, base_dir[, verbose[, dry_run[, owner[, group[, logger]]]]]]])

Create an archive file (such as zip or tar) and return its name.

base_name is the name of the file to create, including the path, minus any format-specific extension. format is the archive format: one of “zip” (if the zlib module is available), “tar”, “gztar” (if the zlib module is available), “bztar” (if the bz2 module is available), or “xztar” (if the lzma module is available).

root_dir is a directory that will be the root directory of the archive, all paths in the archive will be relative to it; for example, we typically chdir into root_dir before creating the archive.

base_dir is the directory where we start archiving from; i.e. base_dir will be the common prefix of all files and directories in the archive. base_dir must be given relative to root_dir. See Archiving example with base_dir for how to use base_dir and root_dir together.

root_dir and base_dir both default to the current directory.

If dry_run is true, no archive is created, but the operations that would be executed are logged to logger.

owner and group are used when creating a tar archive. By default, uses the current owner and group.

logger must be an object compatible with PEP 282 [https://www.python.org/dev/peps/pep-0282], usually an instance of logging.Logger.

The verbose argument is unused and deprecated.

shutil.get_archive_formats()

Return a list of supported formats for archiving. Each element of the returned sequence is a tuple (name, description).

By default shutil provides these formats:

zip: ZIP file (if the zlib module is available).

tar: uncompressed tar file.

gztar: gzip’ed tar-file (if the zlib module is available).

bztar: bzip2’ed tar-file (if the bz2 module is available).

xztar: xz’ed tar-file (if the lzma module is available).

You can register new formats or provide your own archiver for any existing formats, by using register_archive_format().

shutil.register_archive_format(name, function[, extra_args[, description]])

Register an archiver for the format name.

function is the callable that will be used to unpack archives. The callable will receive the base_name of the file to create, followed by the base_dir (which defaults to os.curdir) to start archiving from. Further arguments are passed as keyword arguments: owner, group, dry_run and logger (as passed in make_archive()).

If given, extra_args is a sequence of (name, value) pairs that will be used as extra keywords arguments when the archiver callable is used.

description is used by get_archive_formats() which returns the list of archivers. Defaults to an empty string.

shutil.unregister_archive_format(name)

Remove the archive format name from the list of supported formats.

shutil.unpack_archive(filename[, extract_dir[, format]])

Unpack an archive. filename is the full path of the archive.

extract_dir is the name of the target directory where the archive is unpacked. If not provided, the current working directory is used.

format is the archive format: one of “zip”, “tar”, “gztar”, “bztar”, or “xztar”. Or any other format registered with register_unpack_format(). If not provided, unpack_archive() will use the archive file name extension and see if an unpacker was registered for that extension. In case none is found, a ValueError is raised.

버전 3.7에서 변경: Accepts a path-like object for filename and extract_dir.

shutil.register_unpack_format(name, extensions, function[, extra_args[, description]])

Registers an unpack format. name is the name of the format and extensions is a list of extensions corresponding to the format, like .zip for Zip files.

function is the callable that will be used to unpack archives. The callable will receive the path of the archive, followed by the directory the archive must be extracted to.

When provided, extra_args is a sequence of (name, value) tuples that will be passed as keywords arguments to the callable.

description can be provided to describe the format, and will be returned by the get_unpack_formats() function.

shutil.unregister_unpack_format(name)

Unregister an unpack format. name is the name of the format.

shutil.get_unpack_formats()

Return a list of all registered formats for unpacking. Each element of the returned sequence is a tuple (name, extensions, description).

By default shutil provides these formats:

zip: ZIP file (unpacking compressed files works only if the corresponding module is available).

tar: uncompressed tar file.

gztar: gzip’ed tar-file (if the zlib module is available).

bztar: bzip2’ed tar-file (if the bz2 module is available).

xztar: xz’ed tar-file (if the lzma module is available).

You can register new formats or provide your own unpacker for any existing formats, by using register_unpack_format().

Archiving example

In this example, we create a gzip’ed tar-file archive containing all files found in the .ssh directory of the user:

>>> from shutil import make_archive
>>> import os
>>> archive_name = os.path.expanduser(os.path.join('~', 'myarchive'))
>>> root_dir = os.path.expanduser(os.path.join('~', '.ssh'))
>>> make_archive(archive_name, 'gztar', root_dir)
'/Users/tarek/myarchive.tar.gz'

The resulting archive contains:

$ tar -tzvf /Users/tarek/myarchive.tar.gz
drwx------ tarek/staff       0 2010-02-01 16:23:40 ./
-rw-r--r-- tarek/staff     609 2008-06-09 13:26:54 ./authorized_keys
-rwxr-xr-x tarek/staff      65 2008-06-09 13:26:54 ./config
-rwx------ tarek/staff     668 2008-06-09 13:26:54 ./id_dsa
-rwxr-xr-x tarek/staff     609 2008-06-09 13:26:54 ./id_dsa.pub
-rw------- tarek/staff    1675 2008-06-09 13:26:54 ./id_rsa
-rw-r--r-- tarek/staff     397 2008-06-09 13:26:54 ./id_rsa.pub
-rw-r--r-- tarek/staff   37192 2010-02-06 18:23:10 ./known_hosts

Archiving example with base_dir

In this example, similar to the one above, we show how to use make_archive(), but this time with the usage of base_dir. We now have the following directory structure:

$ tree tmp
tmp
└── root
    └── structure
        ├── content
            └── please_add.txt
        └── do_not_add.txt

In the final archive, please_add.txt should be included, but do_not_add.txt should not. Therefore we use the following:

>>> from shutil import make_archive
>>> import os
>>> archive_name = os.path.expanduser(os.path.join('~', 'myarchive'))
>>> make_archive(
...     archive_name,
...     'tar',
...     root_dir='tmp/root',
...     base_dir='structure/content',
... )
'/Users/tarek/my_archive.tar'

Listing the files in the resulting archive gives us:

$ python -m tarfile -l /Users/tarek/myarchive.tar
structure/content/
structure/content/please_add.txt

Querying the size of the output terminal

shutil.get_terminal_size(fallback=(columns, lines))

Get the size of the terminal window.

For each of the two dimensions, the environment variable, COLUMNS and LINES respectively, is checked. If the variable is defined and the value is a positive integer, it is used.

When COLUMNS or LINES is not defined, which is the common case, the terminal connected to sys.__stdout__ is queried by invoking os.get_terminal_size().

If the terminal size cannot be successfully queried, either because the system doesn’t support querying, or because we are not connected to a terminal, the value given in fallback parameter is used. fallback defaults to (80, 24) which is the default size used by many terminal emulators.

The value returned is a named tuple of type os.terminal_size.

See also: The Single UNIX Specification, Version 2, Other Environment Variables [http://pubs.opengroup.org/onlinepubs/7908799/xbd/envvar.html#tag_002_003].

버전 3.3에 추가.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

파일과 디렉터리 액세스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

파일과 디렉터리 액세스 »

|

macpath — Mac OS 9 path manipulation functions

Source code: Lib/macpath.py [https://github.com/python/cpython/tree/3.7/Lib/macpath.py]

Deprecated since version 3.7, will be removed in version 3.8.

This module is the Mac OS 9 (and earlier) implementation of the os.path module. It can be used to manipulate old-style Macintosh pathnames on Mac OS X (or any other platform).

The following functions are available in this module: normcase(), normpath(), isabs(), join(), split(), isdir(), isfile(), walk(), exists(). For other functions available in os.path dummy counterparts are available.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

파일과 디렉터리 액세스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

|

데이터 지속성

이 장에서 설명하는 모듈은 파이썬 데이터를 디스크에 지속적인 형태로 저장하는 것을 지원합니다. pickle과 marshal 모듈은 많은 파이썬 데이터형을 바이트 스트림으로 바꿀 수 있고 그 바이트열로부터 객체를 재생성할 수 있습니다. 다양한 DBM 관련 모듈은 문자열에서 다른 문자열로의 매핑을 저장하는 일군의 해시 기반 파일 형식을 지원합니다.

이 장에서 설명하는 모듈 목록은 다음과 같습니다:

pickle — 파이썬 객체 직렬화

다른 파이썬 모듈과의 관계

marshal 과의 비교

json 과의 비교

데이터 스트림 형식

모듈 인터페이스

어떤 것이 피클 되고 역 피클 될 수 있을까요?

클래스 인스턴스 피클링

외부 객체의 지속성

디스패치 테이블

상태 저장 객체 처리

전역 제한하기

성능

예제

copyreg — pickle 지원 함수 등록

예제

shelve — 파이썬 객체 지속성

제약 사항

예제

marshal — 내부 파이썬 객체 직렬화

dbm — 유닉스 “데이터베이스” 인터페이스

dbm.gnu — GNU의 dbm 재해석

dbm.ndbm — ndbm 기반 인터페이스

dbm.dumb — 이식성 있는 DBM 구현

sqlite3 — SQLite 데이터베이스용 DB-API 2.0 인터페이스

모듈 함수와 상수

Connection 객체

Cursor 객체

Row 객체

예외

SQLite 와 파이썬 형

소개

어댑터를 사용하여 SQLite 데이터베이스에 추가 파이썬 형을 저장하기

객체가 스스로 어댑트하도록 하기

어댑터 콜러블 등록하기

SQLite 값을 사용자 정의 파이썬 형으로 변환하기

기본 어댑터와 변환기

트랜잭션 제어

효율적으로 sqlite3 사용하기

바로 가기 메서드 사용하기

인덱스 대신 이름으로 열 액세스하기

컨텍스트 관리자로 연결 사용하기

일반적인 문제

다중 스레드

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

데이터 지속성 »

|

pickle — 파이썬 객체 직렬화

소스 코드: Lib/pickle.py [https://github.com/python/cpython/tree/3.7/Lib/pickle.py]

pickle 모듈은 파이썬 객체 구조의 직렬화와 역 직렬화를 위한 바이너리 프로토콜을 구현합니다. “피클링(pickling)”은 파이썬 객체 계층 구조가 바이트 스트림으로 변환되는 절차이며, “역 피클링(unpickling)”은 반대 연산으로, (바이너리 파일 이나 바이트열류 객체로 부터의) 바이트 스트림을 객체 계층 구조로 복원합니다. 피클링(그리고 역 피클링)은 “직렬화(serialization)”, “마샬링(marshalling)” 1 또는 “평탄화(flattening)” 라고도 합니다; 그러나, 혼란을 피하고자, 여기에서 사용된 용어는 “피클링” 과 “역 피클링” 입니다.

경고

pickle 모듈은 잘못되었거나 악의적으로 생성된 데이터에 대해 안전하지 않습니다. 신뢰할 수 없거나 인증되지 않은 출처에서 받은 데이터를 절대로 역 피클 하지 마십시오.

다른 파이썬 모듈과의 관계

marshal 과의 비교

파이썬이 marshal 이라 불리는 좀 더 원시적인 직렬화 모듈을 가지고 있지만, 일반적으로 pickle 은 항상 파이썬 객체를 직렬화하기 위해 선호되는 방법이어야 합니다. marshal 은 주로 파이썬의 .pyc 파일을 지원하기 위해 존재합니다.

pickle 모듈은 marshal과 몇 가지 중요한 점에서 다릅니다:

pickle 모듈은 이미 직렬화된 객체를 추적하므로 나중에 같은 객체에 대한 참조가 다시 직렬화되지 않습니다. marshal 은 이렇게 하지 않습니다.

이는 재귀 객체와 객체 공유에 모두 관련이 있습니다. 재귀 객체는 자신에 대한 참조를 포함하는 객체입니다. 이것은 마샬에 의해 처리되지 않으며, 실제로 재귀 객체를 마샬 하려고 하면 파이썬 인터프리터가 충돌합니다. 객체 공유는 직렬화되는 객체 계층의 다른 위치에서 같은 객체에 대한 다중 참조가 있을 때 발생합니다. pickle 은 그러한 객체를 한 번만 저장하고, 다른 모든 참조가 마스터 복사본을 가리키도록 만듭니다. 공유 객체는 공유된 상태로 유지되는데, 가변 객체의 경우 매우 중요할 수 있습니다.

marshal은 사용자 정의 클래스와 인스턴스를 직렬화하는 데 사용할 수 없습니다. pickle 은 클래스 인스턴스를 투명하게 저장하고 복원할 수 있지만, 클래스 정의는 객체를 저장할 때와 같은 모듈에 존재하고 임포트 할 수 있어야 합니다.

marshal 직렬화 형식은 파이썬 버전 간에 이식성이 보장되지 않습니다. 가장 중요한 일은 .pyc 파일을 지원하는 것이므로, 파이썬 구현자는 필요할 때 직렬화 형식을 과거 호환되지 않는 방식으로 변경할 권리를 갖습니다. pickle 직렬화 형식은, 호환성 있는 피클 프로토콜이 선택되고 여러분의 데이터가 파이썬 2와 파이썬 3의 호환되지 않는 언어 경계를 가로지를 때 피클링과 역 피클링 코드가 두 파이썬 형의 차이점을 다루는 한, 파이썬 배포 간의 과거 호환성을 보장합니다.

json 과의 비교

pickle 프로토콜과 JSON (JavaScript Object Notation) [http://json.org] 간에는 근본적인 차이가 있습니다:

JSON은 텍스트 직렬화 형식(유니코드 텍스트를 출력하지만, 대개는 utf-8 으로 인코딩됩니다)인 반면, pickle은 바이너리 직렬화 형식입니다.

JSON은 사람이 읽을 수 있지만, 피클은 그렇지 않습니다.

JSON은 상호 운용이 가능하며 파이썬 생태계 외부에서 널리 사용되는 반면, 피클은 파이썬으로만 한정됩니다.

JSON은, 기본적으로, 파이썬 내장형 일부만 표시할 수 있으며 사용자 정의 클래스는 표시할 수 없습니다; 피클은 매우 많은 수의 파이썬 형을 나타낼 수 있습니다 (그중 많은 것들은 파이썬의 인트로스펙션 기능을 영리하게 사용하여 자동으로; 복잡한 경우는 특정 객체 API 를 구현해서 해결할 수 있습니다).

더 보기

json 모듈: JSON 직렬화와 역 직렬화를 가능하게 하는 표준 라이브러리 모듈.

데이터 스트림 형식

pickle 이 사용하는 데이터 형식은 파이썬에 고유합니다. 이것은 JSON 또는 XDR (포인터 공유를 나타낼 수 없음)과 같은 외부 표준에 의해 부과된 제약이 없다는 장점이 있습니다. 그러나 비 파이썬 프로그램은 피클 된 파이썬 객체를 재구성할 수 없다는 것을 의미합니다.

기본적으로, pickle 데이터 포맷은 상대적으로 간결한 바이너리 표현을 사용합니다. 최적의 크기 특성이 필요하다면, 피클 된 데이터를 효율적으로 압축 할 수 있습니다.

모듈 pickletools 에는 pickle 에 의해 생성된 데이터 스트림을 분석하는 도구가 있습니다. pickletools 소스 코드에는 피클 프로토콜에서 사용되는 옵코드(opcode)에 대한 광범위한 주석이 있습니다.

현재 피클링에 쓸 수 있는 5가지 프로토콜이 있습니다. 사용된 프로토콜이 높을수록, 생성된 피클을 읽으려면 더 최신 파이썬 버전이 필요합니다.

프로토콜 버전 0은 최초의 “사람이 읽을 수 있는” 프로토콜이며 이전 버전의 파이썬과 과거 호환됩니다.

프로토콜 버전 1은 역시 이전 버전의 파이썬과 호환되는 오래된 바이너리 형식입니다.

프로토콜 버전 2는 파이썬 2.3에서 소개되었습니다. 그것은 훨씬 더 효율적인 뉴스타일 클래스의 피클링을 제공합니다. 프로토콜 2에 의해 개선된 사항에 대한 정보는 PEP 307 [https://www.python.org/dev/peps/pep-0307]을 참조하십시오.

프로토콜 버전 3은 파이썬 3.0에서 추가되었습니다. 명시적으로 bytes 객체를 지원하며 파이썬 2.x에서 역 피클 될 수 없습니다. 이것은 기본 프로토콜이며, 다른 파이썬 3 버전과의 호환성이 필요한 경우 권장되는 프로토콜입니다.

프로토콜 버전 4가 파이썬 3.4에 추가되었습니다. 매우 큰 객체, 더 많은 종류의 객체에 대한 피클링, 일부 데이터 형식 최적화에 대한 지원을 추가합니다. 프로토콜 4에 의해 개선된 사항에 대한 정보는 PEP 3154 [https://www.python.org/dev/peps/pep-3154]를 참조하십시오.

참고

직렬화는 지속성보다 더 원시적인 개념입니다; pickle 이 파일 객체를 읽거나 쓰기는 하지만, 지속적인 객체의 이름 지정도 (더 복잡한) 지속적인 객체에 대한 동시 액세스 문제도 처리하지 않습니다. pickle 모듈은 복잡한 객체를 바이트 스트림으로 변환할 수 있고 바이트 스트림을 같은 내부 구조를 가진 객체로 변환할 수 있습니다. 아마도 이러한 바이트 스트림으로 할 가장 분명한 작업은 파일에 쓰는 것이겠지만, 네트워크를 통해 보내거나 데이터베이스에 저장하는 것도 고려할 수 있습니다. shelve 모듈은 DBM 스타일의 데이터베이스 파일에 객체를 피클/역 피클 하는 간단한 인터페이스를 제공합니다.

모듈 인터페이스

객체 계층 구조를 직렬화하려면, 단순히 dumps() 함수를 호출하면 됩니다. 마찬가지로, 데이터 스트림을 역 직렬화하려면 loads() 함수를 호출합니다. 그러나, 직렬화와 역 직렬화에 대한 더 많은 제어를 원하면, 각각 Pickler 나 Unpickler 객체를 만들 수 있습니다.

pickle 모듈은 다음과 같은 상수를 제공합니다:

pickle.HIGHEST_PROTOCOL

정수, 사용 가능한 가장 높은 프로토콜 버전. 이 값은 함수 dump()와 dumps() 그리고 Pickler 생성자에 protocol 값으로 전달될 수 있습니다.

pickle.DEFAULT_PROTOCOL

정수, 피클링에 사용되는 기본 프로토콜 버전. HIGHEST_PROTOCOL 보다 작을 수 있습니다. 현재 기본 프로토콜은 3인데, 파이썬 3 용으로 설계된 새로운 프로토콜입니다.

pickle 모듈은 피클링 절차를 보다 편리하게 하려고 다음과 같은 함수를 제공합니다:

pickle.dump(obj, file, protocol=None, *, fix_imports=True)

Write the pickled representation of the object obj to the open file object file. This is equivalent to Pickler(file, protocol).dump(obj).

선택적 protocol 인자(정수)는 피클러가 주어진 프로토콜을 사용하도록 지시합니다; 지원되는 프로토콜은 0부터 HIGHEST_PROTOCOL 입니다. 지정하지 않으면 기본값은 DEFAULT_PROTOCOL 입니다. 음수가 지정되면, HIGHEST_PROTOCOL 이 선택됩니다.

file 인자에는 단일 바이트열 인자를 받아들이는 write() 메서드가 있어야 합니다. 따라서 바이너리 쓰기를 위해 열린 디스크 상의 파일, io.BytesIO 인스턴스 또는 이 인터페이스를 충족시키는 다른 사용자 정의 객체일 수 있습니다.

fix_imports 가 참이고 protocol 이 3보다 작으면, pickle은 새로운 파이썬 3 이름을 파이썬 2에서 사용된 이전 모듈 이름에 매핑하려고 시도하여, 파이썬 2에서 피클 데이터 스트림을 읽을 수 있도록 합니다.

pickle.dumps(obj, protocol=None, *, fix_imports=True)

Return the pickled representation of the object obj as a bytes object, instead of writing it to a file.

인자 protocol 과 fix_imports 는 dump()와 같은 의미입니다.

pickle.load(file, *, fix_imports=True, encoding="ASCII", errors="strict")

Read the pickled representation of an object from the open file object file and return the reconstituted object hierarchy specified therein. This is equivalent to Unpickler(file).load().

The protocol version of the pickle is detected automatically, so no protocol argument is needed. Bytes past the pickled representation of the object are ignored.

인자 file 에는 두 가지 메서드가 있어야 합니다, 정수 인자를 받아들이는 read() 메서드와 인자가 없는 readline() 메서드. 두 메서드 모두 바이트열를 반환해야 합니다. 따라서 file 은 바이너리 읽기를 위해 열린 디스크 상의 파일, io.BytesIO 객체 또는 이 인터페이스를 만족하는 다른 사용자 정의 객체일 수 있습니다.

선택적 키워드 인자는 fix_imports, encoding 및 errors 인데, 파이썬 2에서 생성된 피클 스트림에 대한 호환성 지원을 제어하는 데 사용됩니다. fix_imports 가 참이면, pickle은 이전 파이썬 2 이름을 파이썬 3에서 사용된 새로운 이름으로 매핑하려고 합니다. encoding 과 errors 는 파이썬 2에 의해 피클 된 8비트 문자열 인스턴스를 디코딩하는 방법을 pickle에게 알려줍니다. 기본값은 각각 ‘ASCII’와 ‘strict’ 입니다. encoding 은 ‘bytes’ 가 될 수 있는데, 8비트 문자열 인스턴스를 바이트열 객체로 읽습니다. NumPy 배열과 파이썬 2에서 피클 된 datetime, date 및 time 인스턴스를 역 피클링하려면 encoding='latin1'을 사용해야 합니다.

pickle.loads(data, *, fix_imports=True, encoding="ASCII", errors="strict")

Return the reconstituted object hierarchy of the pickled representation data of an object. data must be a bytes-like object.

The protocol version of the pickle is detected automatically, so no protocol argument is needed. Bytes past the pickled representation of the object are ignored.

선택적 키워드 인자는 fix_imports, encoding 및 errors 인데, 파이썬 2에서 생성된 피클 스트림에 대한 호환성 지원을 제어하는 데 사용됩니다. fix_imports 가 참이면, pickle은 이전 파이썬 2 이름을 파이썬 3에서 사용된 새로운 이름으로 매핑하려고 합니다. encoding 과 errors 는 파이썬 2에 의해 피클 된 8비트 문자열 인스턴스를 디코딩하는 방법을 pickle에게 알려줍니다. 기본값은 각각 ‘ASCII’와 ‘strict’ 입니다. encoding 은 ‘bytes’ 가 될 수 있는데, 8비트 문자열 인스턴스를 바이트열 객체로 읽습니다. NumPy 배열과 파이썬 2에서 피클 된 datetime, date 및 time 인스턴스를 역 피클링하려면 encoding='latin1'을 사용해야 합니다.

pickle 모듈은 세 가지 예외를 정의합니다:

exception pickle.PickleError

다른 피클링 예외의 공통 베이스 클래스입니다. Exception을 상속합니다.

exception pickle.PicklingError

Pickler 가 피클 가능하지 않은 객체를 만날 때 발생하는 에러. PickleError 를 상속합니다.

어떤 종류의 객체가 피클 될 수 있는지 배우려면 어떤 것이 피클 되고 역 피클 될 수 있을까요?를 참조하십시오.

exception pickle.UnpicklingError

데이터 손상 또는 보안 위반과 같이 객체를 역 피클 할 때 문제가 있으면 발생하는 에러. PickleError 를 상속합니다.

역 피클링 중에 다른 예외도 발생할 수 있음에 유의하십시오. AttributeError, EOFError, ImportError, IndexError 등이 발생할 수 있지만, 이에 국한되지는 않습니다.

pickle 모듈은 두 개의 클래스를 노출합니다, Pickler와 Unpickler:

class pickle.Pickler(file, protocol=None, *, fix_imports=True)

피클 데이터 스트림을 쓸 바이너리 파일을 받아들입니다.

선택적 protocol 인자(정수)는 피클러가 주어진 프로토콜을 사용하도록 지시합니다; 지원되는 프로토콜은 0부터 HIGHEST_PROTOCOL 입니다. 지정하지 않으면 기본값은 DEFAULT_PROTOCOL 입니다. 음수가 지정되면, HIGHEST_PROTOCOL 이 선택됩니다.

file 인자에는 단일 바이트열 인자를 받아들이는 write() 메서드가 있어야 합니다. 따라서 바이너리 쓰기를 위해 열린 디스크 상의 파일, io.BytesIO 인스턴스 또는 이 인터페이스를 충족시키는 다른 사용자 정의 객체일 수 있습니다.

fix_imports 가 참이고 protocol 이 3보다 작으면, pickle은 새로운 파이썬 3 이름을 파이썬 2에서 사용된 이전 모듈 이름에 매핑하려고 시도하여, 파이썬 2에서 피클 데이터 스트림을 읽을 수 있도록 합니다.

dump(obj)

Write the pickled representation of obj to the open file object given in the constructor.

persistent_id(obj)

기본적으로 아무것도 하지 않습니다. 이것은 서브 클래스가 재정의할 수 있게 하려고 존재합니다.

persistent_id() 가 None 을 반환하면, obj 는 보통 때처럼 피클 됩니다. 다른 값은 Pickler 가 obj 의 지속성(persistent) ID로 반환 값을 출력하도록 합니다. 이 지속성 ID의 의미는 Unpickler.persistent_load() 에 의해 정의되어야 합니다. persistent_id() 에 의해 반환된 값 자체는 지속성 ID를 가질 수 없음에 유의하십시오.

자세한 내용과 사용 예는 외부 객체의 지속성를 참조하십시오.

dispatch_table

피클러 객체의 디스패치 테이블은 copyreg.pickle() 을 사용하여 선언할 수 있는 환원 함수(reduction functions) 의 등록소입니다. 키가 클래스이고 값이 환원 함수인 매핑입니다. 환원 함수는 관련 클래스의 단일 인자를 취하며 __reduce__() 메서드와 같은 인터페이스를 따라야 합니다.

기본적으로, 피클러 객체는 dispatch_table 어트리뷰트를 가지지 않을 것이고, 대신 copyreg 모듈에 의해 관리되는 전역 디스패치 테이블을 사용할 것입니다. 그러나 특정 피클러 객체의 피클링을 사용자 정의하기 위해서 dispatch_table 어트리뷰트를 딕셔너리류 객체로 설정할 수 있습니다. 또는, Pickler 의 서브 클래스가 dispatch_table 어트리뷰트를 가지고 있다면, 이 클래스의 인스턴스를 위한 기본 디스패치 테이블로 사용됩니다.

사용 예는 디스패치 테이블을 참조하십시오.

버전 3.3에 추가.

fast

폐지되었습니다. 참값으로 설정된 경우 빠른 모드를 활성화합니다. 빠른 모드는 메모 사용을 비활성화하므로, 불필요한 PUT 옵코드를 생성하지 않아 피클링 절차의 속도를 높입니다. 자신을 참조하는 객체에 사용되면 안 됩니다. 그렇지 않으면 Pickler 가 무한 재귀에 빠집니다.

더 간결한 피클이 필요하면 pickletools.optimize() 를 사용하십시오.

class pickle.Unpickler(file, *, fix_imports=True, encoding="ASCII", errors="strict")

피클 데이터 스트림을 읽는 데 사용될 바이너리 파일을 받아들입니다.

피클의 프로토콜 버전이 자동으로 감지되므로 프로토콜 인자가 필요하지 않습니다.

인자 file 에는 두 가지 메서드가 있어야 합니다, 정수 인자를 받아들이는 read() 메서드와 인자가 없는 readline() 메서드. 두 메서드 모두 바이트열을 반환해야 합니다. 따라서 file 은 바이너리 읽기를 위해 열린 디스크 상의 파일 객체, io.BytesIO 객체 또는 이 인터페이스를 만족하는 다른 사용자 정의 객체일 수 있습니다.

선택적 키워드 인자는 fix_imports, encoding 및 errors 인데, 파이썬 2에서 생성된 피클 스트림에 대한 호환성 지원을 제어하는 데 사용됩니다. fix_imports 가 참이면, pickle은 이전 파이썬 2 이름을 파이썬 3에서 사용된 새로운 이름으로 매핑하려고 합니다. encoding 과 errors 는 파이썬 2에 의해 피클 된 8비트 문자열 인스턴스를 디코딩하는 방법을 pickle에게 알려줍니다. 기본값은 각각 ‘ASCII’와 ‘strict’ 입니다. encoding 은 ‘bytes’ 가 될 수 있는데, 8비트 문자열 인스턴스를 바이트열 객체로 읽습니다.

load()

Read the pickled representation of an object from the open file object given in the constructor, and return the reconstituted object hierarchy specified therein. Bytes past the pickled representation of the object are ignored.

persistent_load(pid)

기본적으로 UnpicklingError를 발생시킵니다.

정의되면, persistent_load() 는 지속성 ID pid 로 지정된 객체를 반환해야 합니다. 유효하지 않은 지속성 ID가 발견되면 UnpicklingError를 일으켜야 합니다.

자세한 내용과 사용 예는 외부 객체의 지속성를 참조하십시오.

find_class(module, name)

필요하면 module 을 임포트하고 거기에서 name 이라는 객체를 반환합니다. 여기서 module 및 name 인자는 str 객체입니다. 그 이름이 제시하는 것과는 달리, find_class() 는 함수를 찾는 데에도 사용됨에 유의하십시오.

로드되는 객체의 형과 로드 방법을 제어하기 위해 서브 클래스는 이것을 재정의할 수 있고, 잠재적으로 보안 위험을 감소시킵니다. 자세한 내용은 전역 제한하기를 참조하십시오.

어떤 것이 피클 되고 역 피클 될 수 있을까요?

다음 형을 피클 할 수 있습니다:

None, True 와 False

정수, 실수, 복소수

문자열, 바이트열, 바이트 배열(bytearray)

피클 가능한 객체만 포함하는 튜플, 리스트, 집합과 딕셔너리

모듈의 최상위 수준에서 정의된 함수 (lambda 가 아니라 def 를 사용하는)

모듈의 최상위 수준에서 정의된 내장 함수

모듈의 최상위 수준에서 정의된 클래스

그런 클래스의 인스턴스 중에서 __dict__ 나 __getstate__() 를 호출한 결과가 피클 가능한 것들 (자세한 내용은 클래스 인스턴스 피클링 절을 참조하세요).

피클 가능하지 않은 객체를 피클 하려고 하면 PicklingError 예외가 발생합니다; 이런 일이 일어났을 때, 특정할 수 없는 길이의 바이트열이 하부 파일에 이미 기록되었을 수 있습니다. 매우 재귀적인 데이터 구조를 피클 하려고 하면 최대 재귀 깊이를 초과할 수 있고, 이때 RecursionError 가 발생합니다. sys.setrecursionlimit() 을 사용하여 이 제한을 조심스럽게 올릴 수 있습니다.

함수(내장 및 사용자 정의)는 값이 아니라 “완전히 정규화된” 이름 참조로 피클 됨에 유의하십시오. 2 이것은 함수가 정의된 모듈의 이름과 함께 함수의 이름만 피클 된다는 것을 의미합니다. 함수의 코드도 함수 어트리뷰트도 피클 되지 않습니다. 따라서 정의하는 모듈은 역 피클 환경에서 임포트 가능해야 하며, 모듈에는 그 이름의 객체가 있어야 합니다. 그렇지 않으면 예외가 발생합니다. 3

마찬가지로, 클래스는 이름 참조로 피클 되므로 역 피클링 환경에서 같은 제한이 적용됩니다. 클래스의 코드 나 데이터가 피클 되지 않음에 유의하세요. 그래서 다음 예제에서 클래스 어트리뷰트 attr 은 역 피클링 환경에서 복원되지 않습니다:

class Foo:
    attr = 'A class attribute'

picklestring = pickle.dumps(Foo)

이러한 제한이 피클 가능한 함수와 클래스가 모듈의 최상위 수준에서 정의되어야 하는 이유입니다.

마찬가지로, 클래스 인스턴스가 피클 될 때, 클래스의 코드와 데이터는 함께 피클 되지 않습니다. 인스턴스 데이터만 피클 됩니다. 이는 의도한 것으로, 클래스의 버그를 수정하거나 클래스에 메서드를 추가할 수 있고, 이전 버전의 클래스로 만들어진 객체를 여전히 로드 할 수 있습니다. 여러 버전의 클래스에 걸치는 수명이 긴 객체를 만들 계획이라면, 클래스의 __setstate__() 메서드로 적절한 변환을 할 수 있도록 객체에 버전 번호를 넣는 것이 좋습니다.

클래스 인스턴스 피클링

이 절에서는 클래스 인스턴스를 피클 및 역 피클 하는 방법을 정의, 사용자 정의 및 제어할 수 있는 일반적인 메커니즘을 설명합니다.

대부분은, 인스턴스를 피클 가능하게 만드는 데 추가 코드가 필요하지 않습니다. 기본적으로, pickle은 인트로스펙션을 통해 인스턴스의 클래스와 어트리뷰트를 조회합니다. 클래스 인스턴스가 역 피클 될 때, __init__() 메서드는 보통 호출되지 않습니다. 기본 동작은, 먼저 초기화되지 않은 인스턴스를 만든 다음 저장된 어트리뷰트를 복원합니다. 다음 코드는 이 동작의 구현을 보여줍니다:

def save(obj):
    return (obj.__class__, obj.__dict__)

def load(cls, attributes):
    obj = cls.__new__(cls)
    obj.__dict__.update(attributes)
    return obj

클래스는 다음과 같은 하나 이상의 특수 메서드를 제공하여 기본 동작을 변경할 수 있습니다:

object.__getnewargs_ex__()

프로토콜 2 이상에서, __getnewargs_ex__() 메서드를 구현하는 클래스는 역 피클링 때 __new__() 메서드에 전달되는 값을 지시할 수 있습니다. 이 메서드는 (args, kwargs) 쌍을 반환해야 합니다. args 는 위치 인자의 튜플이고 kwargs 는 이름있는 인자의 딕셔너리인데, 객체를 구성하는 데 사용됩니다. 그것들은 역 피클링 때 __new__() 메서드로 전달될 것입니다.

클래스의 __new__() 메서드에 키워드 전용 인자가 필요하면 이 메서드를 구현해야 합니다. 그렇지 않으면 호환성을 위해 __getnewargs__() 를 구현하는 것이 좋습니다.

버전 3.6에서 변경: __getnewargs_ex__() 는 이제 프로토콜 2와 3에서 사용됩니다.

object.__getnewargs__()

이 메서드는 __getnewargs_ex__() 와 비슷한 목적을 수행하지만, 위치 인자만 지원합니다. 역 피클링 때 __new__() 메서드에 전달될 인자의 튜플 args 를 반환해야 합니다.

__getnewargs_ex__() 가 정의되면 __getnewargs__() 는 호출되지 않습니다.

버전 3.6에서 변경: 파이썬 3.6 이전에는, 프로토콜 2와 3에서 __getnewargs_ex__() 대신 __getnewargs__() 가 호출되었습니다.

object.__getstate__()

클래스는 인스턴스가 피클 되는 방식에 더 많은 영향을 줄 수 있습니다; 클래스가 메서드 __getstate__() 를 정의하면, 인스턴스의 딕셔너리 내용 대신, 이 메서드가 호출되고 반환된 객체를 인스턴스의 내용으로 피클 합니다. __getstate__() 메서드가 없다면, 인스턴스의 __dict__ 가 평소와 같이 피클 됩니다.

object.__setstate__(state)

역 피클링 때, 클래스가 __setstate__() 를 정의하면, 그것은 역 피클 된 상태(state)로 호출됩니다. 이 경우 상태 객체가 딕셔너리일 필요는 없습니다. 그렇지 않으면, 피클 된 상태는 딕셔너리 여야하고 그 항목이 새 인스턴스의 딕셔너리에 삽입됩니다.

참고

__getstate__() 가 거짓 값을 반환하면, __setstate__() 메서드가 역 피클링 때 호출되지 않습니다.

__getstate__() 와 __setstate__() 메서드를 사용하는 방법에 대한 더 자세한 정보는 상태 저장 객체 처리 절을 참조하십시오.

참고

At unpickling time, some methods like __getattr__(), __getattribute__(), or __setattr__() may be called upon the instance. In case those methods rely on some internal invariant being true, the type should implement __new__() to establish such an invariant, as __init__() is not called when unpickling an instance.

앞으로 살펴보겠지만, 피클은 위에서 설명한 메서드를 직접 사용하지 않습니다. 사실, 이 메서드들은 __reduce__() 특수 메서드를 구현하는 복사 프로토콜의 일부입니다. 복사 프로토콜은 객체를 피클 하고 복사하는 데 필요한 데이터를 조회하기 위한 통일된 인터페이스를 제공합니다. 4

강력하기는 하지만, 여러분의 클래스에서 직접 __reduce__() 를 구현하면 잘못되기 쉽습니다. 이런 이유로, 클래스 설계자는 가능하면 고수준 인터페이스(즉, __getnewargs_ex__(), __getstate__() 및 __setstate__())를 사용해야 합니다. 하지만, 우리는 __reduce__() 를 사용하는 것이 유일한 옵션이거나 더 효율적인 피클링을 제공하거나 혹은 둘 다인 경우를 보여줄 것입니다.

object.__reduce__()

인터페이스는 현재 다음과 같이 정의됩니다. __reduce__() 메서드는 아무런 인자도 받아들이지 않으며 문자열이나 바람직하게는 튜플을 반환합니다 (반환된 객체는 흔히 “환원 값(reduce value)”이라고 불립니다).

문자열이 반환되면, 문자열은 전역 변수의 이름으로 해석되어야 합니다. 모듈에 상대적인 객체의 지역 이름이어야 합니다; pickle 모듈은 객체의 모듈을 결정하기 위해 모듈 이름 공간을 검색합니다. 이 동작은 일반적으로 싱글톤에 유용합니다.

튜플이 반환될 때는, 길이가 2나 5가 되어야 합니다. 선택적인 항목은 생략되거나 None 이 값으로 제공될 수 있습니다. 각 항목의 의미는 순서대로 다음과 같습니다:

객체의 초기 버전을 만들기 위해 호출할 콜러블 객체.

콜러블 객체에 대한 인자의 튜플. 콜러블 객체가 인자를 받아들이지 않으면 빈 튜플을 제공해야 합니다.

선택적으로, 객체의 상태. 앞에서 설명한 대로 객체의 __setstate__() 메서드에 전달됩니다. 객체에 그런 메서드가 없다면, 그 값은 딕셔너리 여야 하며 객체의 __dict__ 어트리뷰트에 추가됩니다.

선택적으로, 연속적인 항목을 생성하는 이터레이터(시퀀스가 아닙니다). 이 항목들은 obj.append(item) 을 사용하거나 한꺼번에 obj.extend(list_of_items) 를 사용하여 객체에 추가될 것입니다. 이것은 주로 리스트 서브 클래스에 사용되지만, 적절한 서명을 갖는 append()와 extend() 메서드가 있는 한 다른 클래스에서 사용될 수 있습니다. (append() 나 extend() 중 어느 것이 사용되는지는 어떤 피클 프로토콜 버전이 사용되는가와 추가 할 항목의 수에 따라 달려있으므로 둘 다 지원되어야 합니다.)

선택적으로, 연속적인 키-값 쌍을 생성하는 이터레이터(시퀀스가 아닙니다). 이 항목들은 obj[key] = value 를 사용하여 객체에 저장됩니다. 이것은 주로 딕셔너리 서브 클래스에 사용되지만, __setitem__() 을 구현하는 한 다른 클래스에서 사용될 수 있습니다.

object.__reduce_ex__(protocol)

또는, __reduce_ex__() 메서드를 정의할 수 있습니다. 유일한 차이점은 이 메서드가 프로토콜 버전인 단일 정수 인자를 받아들여야 한다는 것입니다. 정의되면, pickle은 __reduce__() 메서드보다 선호합니다. 또한, __reduce__() 는 자동으로 확장 버전의 동의어가 됩니다. 이 메서드의 주된 용도는 구형 파이썬 배포를 위해 과거 호환성 있는 환원 값을 제공하는 것입니다.

외부 객체의 지속성

객체 지속성의 효용을 위해, pickle 모듈은 피클 된 데이터 스트림 밖의 객체에 대한 참조 개념을 지원합니다. 이러한 객체는 지속성 ID에 의해 참조되며, 영숫자 문자열(프로토콜 0의 경우) 5 또는 임의의 객체(모든 최신 프로토콜의 경우)여야 합니다.

The resolution of such persistent IDs is not defined by the pickle module; it will delegate this resolution to the user-defined methods on the pickler and unpickler, persistent_id() and persistent_load() respectively.

To pickle objects that have an external persistent ID, the pickler must have a custom persistent_id() method that takes an object as an argument and returns either None or the persistent ID for that object. When None is returned, the pickler simply pickles the object as normal. When a persistent ID string is returned, the pickler will pickle that object, along with a marker so that the unpickler will recognize it as a persistent ID.

외부 객체를 역 피클 하려면, 역 피클러는 지속성 ID 객체를 받아들여 참조된 객체를 반환하는 사용자 정의 persistent_load() 메서드를 가져야 합니다.

다음은 지속성 ID를 외부 객체를 참조로 피클 하는데 사용하는 방법을 보여주는 포괄적인 예입니다.

# Simple example presenting how persistent ID can be used to pickle
# external objects by reference.

import pickle
import sqlite3
from collections import namedtuple

# Simple class representing a record in our database.
MemoRecord = namedtuple("MemoRecord", "key, task")

class DBPickler(pickle.Pickler):

    def persistent_id(self, obj):
        # Instead of pickling MemoRecord as a regular class instance, we emit a
        # persistent ID.
        if isinstance(obj, MemoRecord):
            # Here, our persistent ID is simply a tuple, containing a tag and a
            # key, which refers to a specific record in the database.
            return ("MemoRecord", obj.key)
        else:
            # If obj does not have a persistent ID, return None. This means obj
            # needs to be pickled as usual.
            return None

class DBUnpickler(pickle.Unpickler):

    def __init__(self, file, connection):
        super().__init__(file)
        self.connection = connection

    def persistent_load(self, pid):
        # This method is invoked whenever a persistent ID is encountered.
        # Here, pid is the tuple returned by DBPickler.
        cursor = self.connection.cursor()
        type_tag, key_id = pid
        if type_tag == "MemoRecord":
            # Fetch the referenced record from the database and return it.
            cursor.execute("SELECT * FROM memos WHERE key=?", (str(key_id),))
            key, task = cursor.fetchone()
            return MemoRecord(key, task)
        else:
            # Always raises an error if you cannot return the correct object.
            # Otherwise, the unpickler will think None is the object referenced
            # by the persistent ID.
            raise pickle.UnpicklingError("unsupported persistent object")

def main():
    import io
    import pprint

    # Initialize and populate our database.
    conn = sqlite3.connect(":memory:")
    cursor = conn.cursor()
    cursor.execute("CREATE TABLE memos(key INTEGER PRIMARY KEY, task TEXT)")
    tasks = (
        'give food to fish',
        'prepare group meeting',
        'fight with a zebra',
        )
    for task in tasks:
        cursor.execute("INSERT INTO memos VALUES(NULL, ?)", (task,))

    # Fetch the records to be pickled.
    cursor.execute("SELECT * FROM memos")
    memos = [MemoRecord(key, task) for key, task in cursor]
    # Save the records using our custom DBPickler.
    file = io.BytesIO()
    DBPickler(file).dump(memos)

    print("Pickled records:")
    pprint.pprint(memos)

    # Update a record, just for good measure.
    cursor.execute("UPDATE memos SET task='learn italian' WHERE key=1")

    # Load the records from the pickle data stream.
    file.seek(0)
    memos = DBUnpickler(file, conn).load()

    print("Unpickled records:")
    pprint.pprint(memos)

if __name__ == '__main__':
    main()

디스패치 테이블

피클링에 의존하는 다른 코드를 방해하지 않고 일부 클래스의 피클링을 사용자 정의하려면, 사설 디스패치 테이블을 갖는 피클러를 만들 수 있습니다.

copyreg 모듈에 의해 관리되는 전역 디스패치 테이블은 copyreg.dispatch_table로 사용 가능합니다. 그러므로, 사설 디스패치 테이블로 copyreg.dispatch_table 의 수정된 복사본을 사용할 수 있습니다.

예를 들면

f = io.BytesIO()
p = pickle.Pickler(f)
p.dispatch_table = copyreg.dispatch_table.copy()
p.dispatch_table[SomeClass] = reduce_SomeClass

는 SomeClass 클래스를 특별히 처리하는 사설 디스패치 테이블을 갖는 pickle.Pickler 의 인스턴스를 생성합니다. 또는, 코드

class MyPickler(pickle.Pickler):
    dispatch_table = copyreg.dispatch_table.copy()
    dispatch_table[SomeClass] = reduce_SomeClass
f = io.BytesIO()
p = MyPickler(f)

가 같은 일을 하지만, MyPickler 의 모든 인스턴스는 기본적으로 같은 디스패치 테이블을 공유합니다. copyreg 모듈을 사용하는 동등한 코드는 다음과 같습니다

copyreg.pickle(SomeClass, reduce_SomeClass)
f = io.BytesIO()
p = pickle.Pickler(f)

상태 저장 객체 처리

다음은 클래스의 피클 동작을 수정하는 방법을 보여주는 예제입니다. TextReader 클래스는 텍스트 파일을 열고, readline() 메서드가 호출될 때마다 줄 번호와 줄 내용을 반환합니다. TextReader 인스턴스가 피클 되면, 파일 객체 멤버를 제외한 모든 어트리뷰트가 저장됩니다. 인스턴스가 역 피클 될 때, 파일이 다시 열리고, 마지막 위치에서 읽기가 다시 시작됩니다. __setstate__() 와 __getstate__() 메서드가 이 행동을 구현하는 데 사용됩니다.

class TextReader:
    """Print and number lines in a text file."""

    def __init__(self, filename):
        self.filename = filename
        self.file = open(filename)
        self.lineno = 0

    def readline(self):
        self.lineno += 1
        line = self.file.readline()
        if not line:
            return None
        if line.endswith('\n'):
            line = line[:-1]
        return "%i: %s" % (self.lineno, line)

    def __getstate__(self):
        # Copy the object's state from self.__dict__ which contains
        # all our instance attributes. Always use the dict.copy()
        # method to avoid modifying the original state.
        state = self.__dict__.copy()
        # Remove the unpicklable entries.
        del state['file']
        return state

    def __setstate__(self, state):
        # Restore instance attributes (i.e., filename and lineno).
        self.__dict__.update(state)
        # Restore the previously opened file's state. To do so, we need to
        # reopen it and read from it until the line count is restored.
        file = open(self.filename)
        for _ in range(self.lineno):
            file.readline()
        # Finally, save the file.
        self.file = file

사용 예는 다음과 같은 식입니다:

>>> reader = TextReader("hello.txt")
>>> reader.readline()
'1: Hello world!'
>>> reader.readline()
'2: I am line number two.'
>>> new_reader = pickle.loads(pickle.dumps(reader))
>>> new_reader.readline()
'3: Goodbye!'

전역 제한하기

기본적으로, 역 피클링은 피클 데이터에서 찾은 모든 클래스나 함수를 임포트 합니다. 많은 응용 프로그램에서는, 역 피클러가 임의 코드를 임포트하고 호출할 수 있으므로, 이 동작을 받아들일 수 없습니다. 이 손으로 만든 피클 데이터 스트림이 로드될 때 하는 일을 생각해보십시오:

>>> import pickle
>>> pickle.loads(b"cos\nsystem\n(S'echo hello world'\ntR.")
hello world
0

이 예제에서, 역 피클러는 os.system() 함수를 임포트하고 문자열 인자 “echo hello world”를 적용합니다. 이 예제가 공격적이지는 않지만, 어떤 것들은 시스템을 손상할 수 있다고 상상하기 어렵지 않습니다.

이런 이유로, 여러분은 Unpickler.find_class()를 사용자 정의하여 언 피클 되는 것을 제어하고 싶을 수 있습니다. 이름이 제안하는 것과는 달리, Unpickler.find_class() 는 전역(즉, 클래스나 함수)이 요청될 때마다 호출됩니다. 따라서 전역을 완전히 금지하거나 안전한 부분집합으로 제한할 수 있습니다.

다음은 builtins 모듈에서 몇 가지 안전한 클래스만 로드되도록 허용하는 역 피클러의 예입니다:

import builtins
import io
import pickle

safe_builtins = {
    'range',
    'complex',
    'set',
    'frozenset',
    'slice',
}

class RestrictedUnpickler(pickle.Unpickler):

    def find_class(self, module, name):
        # Only allow safe classes from builtins.
        if module == "builtins" and name in safe_builtins:
            return getattr(builtins, name)
        # Forbid everything else.
        raise pickle.UnpicklingError("global '%s.%s' is forbidden" %
                                     (module, name))

def restricted_loads(s):
    """Helper function analogous to pickle.loads()."""
    return RestrictedUnpickler(io.BytesIO(s)).load()

우리의 역 피클러 작업이 의도한 사용 예:

>>> restricted_loads(pickle.dumps([1, 2, range(15)]))
[1, 2, range(0, 15)]
>>> restricted_loads(b"cos\nsystem\n(S'echo hello world'\ntR.")
Traceback (most recent call last):
  ...
pickle.UnpicklingError: global 'os.system' is forbidden
>>> restricted_loads(b'cbuiltins\neval\n'
...                  b'(S\'getattr(__import__("os"), "system")'
...                  b'("echo hello world")\'\ntR.')
Traceback (most recent call last):
  ...
pickle.UnpicklingError: global 'builtins.eval' is forbidden

예를 통해 알 수 있듯이, 역 피클을 허락하는 것에 주의를 기울여야 합니다. 따라서 보안이 중요하다면, xmlrpc.client 나 제삼자 솔루션의 마샬링 API 같은 대안을 고려할 수 있습니다.

성능

최신 버전의 피클 프로토콜(프로토콜 2 이상)은 몇 가지 공통 기능 및 내장형에 대한 효율적인 바이너리 인코딩을 제공합니다. 또한, pickle 모듈은 C로 작성된 투명한 최적화기를 가지고 있습니다.

예제

가장 간단한 코드로, dump()와 load() 함수를 사용하십시오.

import pickle

# An arbitrary collection of objects supported by pickle.
data = {
    'a': [1, 2.0, 3, 4+6j],
    'b': ("character string", b"byte string"),
    'c': {None, True, False}
}

with open('data.pickle', 'wb') as f:
    # Pickle the 'data' dictionary using the highest protocol available.
    pickle.dump(data, f, pickle.HIGHEST_PROTOCOL)

다음 예제는 결과로 나온 피클 데이터를 읽습니다.

import pickle

with open('data.pickle', 'rb') as f:
    # The protocol version used is detected automatically, so we do not
    # have to specify it.
    data = pickle.load(f)

더 보기

모듈 copyreg

확장형에 대한 피클 인터페이스 생성자 등록

모듈 pickletools

피클 된 데이터로 작업하고 분석하는 도구.

모듈 shelve

객체의 인덱싱 된 데이터베이스; pickle을 사용합니다.

모듈 copy

얕거나 깊은 객체 복사.

모듈 marshal

내장형의 고성능 직렬화.

각주

1

이것을 marshal 모듈과 혼동하지 마십시오.

2

이것이 lambda 함수가 pickle 될 수 없는 이유입니다: 모든 lambda 함수는 같은 이름을 공유합니다: <lambda>.

3

발생하는 예외는 ImportError 나 AttributeError 일 가능성이 크지만, 그 밖의 다른 것일 수 있습니다.

4

copy 모듈은 얕거나 깊은 복사 연산에 이 프로토콜을 사용합니다.

5

영숫자 문자의 제한은 프로토콜 0에서 지속성 ID가 개행 문자로 구분되기 때문입니다. 따라서 지속성 ID에 개행 문자가 포함되면 결과 피클을 읽을 수 없게 됩니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

데이터 지속성 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

데이터 지속성 »

|

copyreg — pickle 지원 함수 등록

소스 코드: Lib/copyreg.py [https://github.com/python/cpython/tree/3.7/Lib/copyreg.py]

copyreg 모듈은 특정 객체를 피클 하는 동안 사용되는 함수를 정의하는 방법을 제공합니다. pickle과 copy 모듈은 해당 객체를 피클/복사할 때 이 함수를 사용합니다. 이 모듈은 클래스가 아닌 객체 생성자에 대한 구성 정보를 제공합니다. 이러한 생성자는 팩토리 함수나 클래스 인스턴스일 수 있습니다.

copyreg.constructor(object)

object를 유효한 생성자로 선언합니다. object가 콜러블이 아니면 (따라서 생성자로 유효하지 않으면), TypeError가 발생합니다.

copyreg.pickle(type, function, constructor=None)

function이 type 형의 객체에 대한 “환원” 함수로 사용되어야 한다고 선언합니다. function는 문자열이나 두 개 또는 세 개의 요소를 포함하는 튜플을 반환해야 합니다.

선택적 constructor 매개 변수가 제공되면, 콜러블 객체이며, 피클 할 때 function에 의해 반환된 인자의 튜플로 호출될 때 객체를 재구성하는 데 사용할 수 있습니다. object가 클래스이거나 constructor가 콜러블이 아니면 TypeError가 발생합니다.

function 과 constructor에서 기대되는 인터페이스에 대한 자세한 내용은 pickle 모듈을 참조하십시오. 피클러 객체나 pickle.Pickler의 서브 클래스의 dispatch_table 어트리뷰트도 환원 함수를 선언하는 데 사용될 수 있습니다.

예제

아래 예제는 피클 함수를 등록하는 방법과 사용법을 보여줍니다.:

>>> import copyreg, copy, pickle
>>> class C(object):
...     def __init__(self, a):
...         self.a = a
...
>>> def pickle_c(c):
...     print("pickling a C instance...")
...     return C, (c.a,)
...
>>> copyreg.pickle(C, pickle_c)
>>> c = C(1)
>>> d = copy.copy(c)
pickling a C instance...
>>> p = pickle.dumps(c)
pickling a C instance...

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

데이터 지속성 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

데이터 지속성 »

|

shelve — 파이썬 객체 지속성

소스 코드: Lib/shelve.py [https://github.com/python/cpython/tree/3.7/Lib/shelve.py]

“쉘프(shelf)”는 영속적인(persistent) 딕셔너리류 객체입니다. “dbm” 데이터베이스와의 차이점은 쉘프의 값(키가 아닙니다!)이 사실상 임의의 파이썬 객체일 수 있다는 것입니다 — pickle 모듈에서 처리할 수 있는 모든 것입니다. 여기에는 대부분의 클래스 인스턴스, 재귀적 데이터형 및 많은 공유 서브 객체를 포함하는 객체가 포함됩니다. 키는 일반 문자열입니다.

shelve.open(filename, flag='c', protocol=None, writeback=False)

영속적 딕셔너리를 엽니다. 지정된 filename은 하부 데이터베이스의 기본 파일명입니다. 부작용으로, 확장명이 파일명에 추가될 수 있으며 여러 개의 파일이 만들어질 수 있습니다. 기본적으로, 하부 데이터베이스 파일은 읽기와 쓰기 용으로 열립니다. 선택적 flag 매개 변수는 dbm.open()의 flag 매개 변수와 같게 해석됩니다.

기본적으로, 값을 직렬화하는 데 버전 3 피클이 사용됩니다. 피클 프로토콜의 버전은 protocol 매개 변수로 지정할 수 있습니다.

파이썬 의미론 때문에, 쉘프는 가변 영속 딕셔너리 항목이 언제 수정되는지 알 수 없습니다. 기본적으로 수정된 객체는 쉘프에 대입될 때만 기록됩니다 (예제를 참조하십시오). 선택적인 writeback 매개 변수가 True로 설정되면, 액세스 된 모든 항목도 메모리에 캐시 되고, sync()와 close()가 호출될 때 다시 기록됩니다; 이것은 영속 딕셔너리의 가변 항목을 변경하는 것을 더 수월하게 만들지만, 많은 항목이 액세스 되면, 캐시를 위해 막대한 양의 메모리를 소비할 수 있으며, 액세스 된 모든 항목을 다시 기록하기 때문에 닫기 연산이 매우 느려질 수 있습니다 (어떤 액세스 된 항목이 가변인지, 어떤 것이 실제로 변경되었는지를 판별할 방법이 없습니다).

참고

쉘프가 자동으로 닫히는 것에 의지하지 마십시오; 더는 필요 없을 때 close()를 명시적으로 호출하거나, shelve.open()을 컨텍스트 관리자로 사용하십시오:

with shelve.open('spam') as db:
    db['eggs'] = 'eggs'

경고

shelve 모듈은 pickle로 뒷받침되기 때문에, 신뢰할 수 없는 소스에서 쉘프를 로드하는 것은 안전하지 않습니다. 피클과 마찬가지로, 쉘프를 로드하면 임의의 코드를 실행할 수 있습니다.

쉘프 객체는 딕셔너리에서 지원하는 모든 메서드를 지원합니다. 이것은 딕셔너리 기반 스크립트에서 영속적인 저장소를 요구하는 것으로의 전환을 쉽게 만듭니다.

두 가지 추가 메서드가 지원됩니다:

Shelf.sync()

writeback을 True로 설정하여 쉘프를 열었으면, 캐시의 모든 항목을 다시 기록합니다. 또한, 적절하다면, 캐시를 비우고 디스크 상의 영속 딕셔너리를 동기화합니다. close()로 쉘프를 닫을 때 자동으로 호출됩니다.

Shelf.close()

영구 딕셔너리 객체를 동기화하고 닫습니다. 닫힌 쉘프에 대한 연산은 ValueError로 실패합니다.

더 보기

널리 지원되는 저장 형식과 기본 딕셔너리의 속도를 갖춘 Persistent dictionary recipe [https://code.activestate.com/recipes/576642/]

제약 사항

사용되는 데이터베이스 패키지의 선택(가령 dbm.ndbm이나 dbm.gnu)은 어떤 인터페이스가 사용 가능한지에 따라 다릅니다. 따라서 dbm을 사용하여 데이터베이스를 직접 여는 것은 안전하지 않습니다. 또한, 데이터베이스는 (불행히도) dbm이 사용된다면 그것의 제약이 적용됩니다 — 이것은 데이터베이스에 저장되는 객체(의 피클 된 표현이)가 상당히 작아야 하며, 드물긴 하지만 키 충돌로 인해 데이터베이스가 업데이트를 거부할 수 있음을 뜻합니다.

shelve 모듈은 쉘브된 객체에 대한 동시성(concurrent) 읽기/쓰기 액세스를 지원하지 않습니다. (여러 동시적인 읽기 액세스는 안전합니다.) 어떤 프로그램이 쓰기 용으로 쉘프를 열고 있으면, 다른 어떤 프로그램도 읽기나 쓰기 용으로 열지 않아야 합니다. 유닉스 파일 잠금을 이 문제를 해결하는 데 사용할 수 있지만, 이것은 유닉스 버전마다 다르며 사용된 데이터베이스 구현에 대한 지식이 필요합니다.

class shelve.Shelf(dict, protocol=None, writeback=False, keyencoding='utf-8')

dict 객체에 피클 된 값을 저장하는 collections.abc.MutableMapping의 서브 클래스.

기본적으로, 값을 직렬화하는 데 버전 3 피클이 사용됩니다. 피클 프로토콜의 버전은 protocol 매개 변수로 지정할 수 있습니다. 피클 프로토콜에 대한 설명은 pickle 설명서를 참조하십시오.

writeback 매개 변수가 True이면, 객체는 액세스 된 모든 항목의 캐시를 보유하고 sync와 close 할 때 dict에 다시 씁니다. 이것은 가변 항목에 대한 자연스러운 연산을 허락하지만, 더 많은 메모리를 소비하고 sync와 close 연산이 오래 걸릴 수 있습니다.

keyencoding 매개 변수는 하부 dict에 사용되기 전에 키를 인코딩하는 데 사용되는 인코딩입니다.

Shelf 객체는 컨텍스트 관리자로 사용할 수도 있습니다. 이 경우 with 블록이 끝날 때 자동으로 닫힙니다.

버전 3.2에서 변경: keyencoding 매개 변수가 추가되었습니다; 이전에는 키가 항상 UTF-8으로 인코딩되었습니다.

버전 3.4에서 변경: 컨텍스트 관리자 지원 추가.

class shelve.BsdDbShelf(dict, protocol=None, writeback=False, keyencoding='utf-8')

pybsddb [https://www.jcea.es/programacion/pybsddb.htm]의 제삼자 bsddb 모듈에서는 사용할 수 있지만 다른 데이터베이스 모듈에서는 사용할 수 없는 first(), next(), previous(), last() 및 set_location()을 노출하는 Shelf의 서브 클래스. 생성자에 전달된 dict 객체는 이러한 메서드를 지원해야 합니다. 이것은 일반적으로 bsddb.hashopen(), bsddb.btopen() 또는 bsddb.rnopen() 중 하나를 호출하여 수행됩니다. 선택적 protocol, writeback 및 keyencoding 매개 변수는 Shelf 클래스와 같게 해석됩니다.

class shelve.DbfilenameShelf(filename, flag='c', protocol=None, writeback=False)

딕셔너리류 객체 대신에 filename을 받아들이는 Shelf의 서브 클래스. 하부 파일은 dbm.open()을 사용하여 열립니다. 기본적으로, 파일은 읽기와 쓰기가 가능하도록 만들어지고 열립니다. 선택적 flag 매개 변수는 open() 기능과 같게 해석됩니다. 선택적 protocol과 writeback 매개 변수는 Shelf 클래스와 같게 해석됩니다.

예제

인터페이스를 요약하면 (key는 문자열입니다, data는 임의의 객체입니다):

import shelve

d = shelve.open(filename)  # open -- file may get suffix added by low-level
                           # library

d[key] = data              # store data at key (overwrites old data if
                           # using an existing key)
data = d[key]              # retrieve a COPY of data at key (raise KeyError
                           # if no such key)
del d[key]                 # delete data stored at key (raises KeyError
                           # if no such key)

flag = key in d            # true if the key exists
klist = list(d.keys())     # a list of all existing keys (slow!)

# as d was opened WITHOUT writeback=True, beware:
d['xx'] = [0, 1, 2]        # this works as expected, but...
d['xx'].append(3)          # *this doesn't!* -- d['xx'] is STILL [0, 1, 2]!

# having opened d without writeback=True, you need to code carefully:
temp = d['xx']             # extracts the copy
temp.append(5)             # mutates the copy
d['xx'] = temp             # stores the copy right back, to persist it

# or, d=shelve.open(filename,writeback=True) would let you just code
# d['xx'].append(5) and have it work as expected, BUT it would also
# consume more memory and make the d.close() operation slower.

d.close()                  # close it

더 보기

모듈 dbm

dbm 스타일 데이터베이스에 대한 범용 인터페이스.

모듈 pickle

shelve에 의해 사용되는 객체 직렬화.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

데이터 지속성 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

데이터 지속성 »

|

marshal — 내부 파이썬 객체 직렬화

이 모듈은 바이너리 형식으로 파이썬 값을 읽고 쓸 수 있는 함수를 포함합니다. 형식은 파이썬에만 국한되지만, 기계 아키텍처 문제에는 독립적입니다 (예를 들어, 파이썬 값을 PC의 파일에 기록하고 파일을 Sun으로 보낸 다음, 그곳에서 다시 읽을 수 있습니다). 형식의 세부 사항은 의도적으로 설명하지 않습니다; 파이썬 버전 간에 변경될 수 있습니다 (드물긴 하지만). 1

이것은 범용 “지속성” 모듈이 아닙니다. 범용 지속성과 RPC 호출을 통한 파이썬 객체의 전송에 대해서는, pickle과 shelve 모듈을 참조하십시오. marshal 모듈은 주로 .pyc 파일의 파이썬 모듈에 대한 “의사 컴파일된” 코드 읽기와 쓰기를 지원하기 위해 존재합니다. 따라서, 파이썬 관리자는 필요에 따라 이전 버전과 호환되지 않는 방식으로 마샬 형식을 수정할 수 있는 권한을 갖습니다. 파이썬 객체를 직렬화하고 역 직렬화하는 데는, 대신 pickle 모듈을 사용하십시오 – 성능은 비슷하고, 버전 독립성이 보장되며, pickle은 marshal보다 훨씬 넓은 범위의 객체를 지원합니다.

경고

marshal 모듈은 잘못되었거나 악의적으로 구성된 데이터에 대해 보안성을 갖추려는 것이 아닙니다. 신뢰할 수 없거나 인증되지 않은 출처에서 받은 데이터를 역 마샬 하지 마십시오.

모든 파이썬 객체 형이 지원되는 것은 아닙니다; 일반적으로, 파이썬의 특정 실행에 무관한 값을 가진 객체만 이 모듈에서 쓰고 읽을 수 있습니다. 다음 형이 지원됩니다: 논릿값, 정수, 부동 소수점 수, 복소수, 문자열, 바이트열, 바이트 배열, 튜플, 리스트, 집합, frozenset, 딕셔너리 및 코드 객체, 여기서 튜플, 리스트, 집합, frozenset 및 딕셔너리는 포함된 값이 자체적으로 지원될 때만 지원됩니다. 싱글톤 None, Ellipsis 및 StopIteration도 마샬과 역 마샬 될 수 있습니다. 형식 version이 3보다 작으면, 재귀적인 리스트, 집합 및 딕셔너리를 기록할 수 없습니다 (아래를 참조하십시오).

파일을 읽고 쓰는 함수는 물론 바이트열류 객체에서 작동하는 함수도 있습니다.

모듈은 다음 함수를 정의합니다:

marshal.dump(value, file[, version])

열린 파일에 값을 기록합니다. value는 지원되는 형이어야 합니다. 파일은 쓰기 가능한 바이너리 파일 이어야 합니다.

value가 지원되지 않는 형이면 (또는 지원되지 않는 형의 객체를 담고 있다면) ValueError 예외가 발생합니다 — 하지만, 찌꺼기 데이터도 파일에 기록됩니다. load()로 객체를 제대로 읽을 수 없습니다.

version 인자는 dump가 사용해야 하는 데이터 형식을 나타냅니다 (아래를 참조하십시오).

marshal.load(file)

열린 파일에서 하나의 값을 읽고 그것을 반환합니다. 유효한 값을 읽히지 않으면 (예를 들어, 데이터가 다른 파이썬 버전의 호환되지 않는 마샬 형식이라서) EOFError, ValueError 또는 TypeError를 발생시킵니다. 파일은 읽을 수 있는 바이너리 파일 이어야 합니다.

참고

지원하지 않는 형을 포함하는 객체가 dump()로 마샬 되었으면, load()는 역 마샬이 불가능한 형을 None으로 치환합니다.

marshal.dumps(value[, version])

dump(value, file)에 의해 파일에 기록될 바이트열 객체를 반환합니다. value는 지원되는 형이어야 합니다. value가 지원되지 않는 형이면 (또는 지원되지 않는 형의 객체를 담고 있다면) ValueError 예외를 발생시킵니다.

version 인자는 dumps가 사용해야 하는 데이터 형식을 나타냅니다 (아래를 참조하십시오).

marshal.loads(bytes)

바이트열류 객체를 값으로 변환합니다. 유효한 값이 없으면 EOFError, ValueError 또는 TypeError를 발생시킵니다. 입력의 여분의 바이트는 무시됩니다.

또한, 다음 상수가 정의됩니다:

marshal.version

모듈이 사용하는 형식을 나타냅니다. 버전 0은 역사적인 형식이고, 버전 1은 인턴 된 문자열을 공유하고, 버전 2는 부동 소수점 숫자에 바이너리 형식을 사용합니다. 버전 3에서는 객체 인스턴스 화와 재귀에 대한 지원이 추가되었습니다. 현재 버전은 4입니다.

각주

1

이 모듈의 이름은 (다른 것 중에서도) Modula-3의 설계자가 사용하는 약간의 용어에서 유래합니다. 이들은 자급적(self-contained) 형식으로 데이터를 전달하는 데 “마샬링(marshalling)”이라는 용어를 사용합니다. 엄밀히 말하면, “마샬”은 내부의 어떤 데이터를 외부 형식(예를 들어 RPC 버퍼에)으로 변환하는 것을, “역 마샬”은 그 반대 절차를 뜻합니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

데이터 지속성 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

데이터 지속성 »

|

dbm — 유닉스 “데이터베이스” 인터페이스

소스 코드: Lib/dbm/__init__.py [https://github.com/python/cpython/tree/3.7/Lib/dbm/__init__.py]

dbm은 DBM 데이터베이스 변형에 대한 일반 인터페이스입니다 — dbm.gnu 또는 dbm.ndbm. 이러한 모듈이 설치되어 있지 않으면, dbm.dumb 모듈에 있는 느리지만 간단한 구현이 사용됩니다. 오라클 Berkeley DB에 대한 제삼자 인터페이스 [https://www.jcea.es/programacion/pybsddb.htm]가 있습니다.

exception dbm.error

지원되는 각 모듈에 의해 발생할 수 있는 예외를 포함하는 튜플. 역시 dbm.error라고 이름 붙인 고유한 예외를 첫 번째 항목으로 갖고 있습니다 — dbm.error가 발생할 때 이것이 사용됩니다.

dbm.whichdb(filename)

이 함수는 사용 가능한 몇 가지 간단한 데이터베이스 모듈 — dbm.gnu, dbm.ndbm 또는 dbm.dumb — 중 어느 것을 사용하여 주어진 파일을 열어야 하는지 추측합니다.

다음 값 중 하나를 반환합니다: 읽을 수 없거나 존재하지 않아 파일을 열 수 없으면 None; 파일 형식을 추측할 수 없으면 빈 문자열(''); 또는 필요한 모듈 이름을 포함하는 문자열, 가령 'dbm.ndbm'이나 'dbm.gnu'.

dbm.open(file, flag='r', mode=0o666)

데이터베이스 파일 file을 열고 해당 객체를 반환합니다.

데이터베이스 파일이 이미 존재하면, whichdb() 함수를 사용하여 유형을 판별하고 적절한 모듈이 사용됩니다; 존재하지 않으면, 위에 나열된 것 중 임포트 할 수 있는 첫 번째 모듈이 사용됩니다.

선택적 flag 인자는 다음과 같은 것이 될 수 있습니다:

값

의미

'r'

읽기 전용으로 기존 데이터베이스 열기 (기본값)

'w'

읽고 쓰기 위해 기존 데이터베이스 열기

'c'

읽고 쓰기 위해 데이터베이스를 열고, 존재하지 않으면 만들기

'n'

읽고 쓰기 위해 항상 새로운 빈 데이터베이스를 만들기

선택적 mode 인자는 파일의 유닉스 모드이며, 데이터베이스를 만들 때만 사용됩니다. 기본값은 8진수 0o666입니다 (그리고 현재 umask에 의해 수정됩니다).

open()이 반환한 객체는 딕셔너리와 같은 기본 기능을 지원합니다; 키와 해당 값을 저장, 조회 및 삭제할 수 있으며, get()과 setdefault()뿐만 아니라 in 연산자와 keys() 메서드도 사용할 수 있습니다.

버전 3.2에서 변경: 이제 모든 데이터베이스 모듈에서 get()과 setdefault()를 사용할 수 있습니다.

키와 값은 항상 바이트열로 저장됩니다. 이는 문자열이 사용될 때 저장되기 전에 기본 인코딩으로 묵시적으로 변환됨을 의미합니다.

이 객체는 with 문에서도 사용되도록 지원해서, 완료될 때 자동으로 닫힙니다.

버전 3.4에서 변경: open()이 반환한 객체에 컨텍스트 관리 프로토콜에 대한 기본 지원을 추가했습니다.

다음 예제는 일부 호스트 명과 해당 제목을 기록한 다음, 데이터베이스의 내용을 인쇄합니다:

import dbm

# Open database, creating it if necessary.
with dbm.open('cache', 'c') as db:

    # Record some values
    db[b'hello'] = b'there'
    db['www.python.org'] = 'Python Website'
    db['www.cnn.com'] = 'Cable News Network'

    # Note that the keys are considered bytes now.
    assert db[b'www.python.org'] == b'Python Website'
    # Notice how the value is now in bytes.
    assert db['www.cnn.com'] == b'Cable News Network'

    # Often-used methods of the dict interface work too.
    print(db.get('python.org', b'not present'))

    # Storing a non-string key or value will raise an exception (most
    # likely a TypeError).
    db['www.yahoo.com'] = 4

# db is automatically closed when leaving the with statement.

더 보기

모듈 shelve

문자열이 아닌 데이터를 저장하는 지속성 모듈.

개별 서브 모듈은 다음 섹션에서 설명합니다.

dbm.gnu — GNU의 dbm 재해석

소스 코드: Lib/dbm/gnu.py [https://github.com/python/cpython/tree/3.7/Lib/dbm/gnu.py]

이 모듈은 dbm 모듈과 매우 유사하지만, GNU 라이브러리 gdbm을 대신 사용하여 추가 기능을 제공합니다. dbm.gnu와 dbm.ndbm으로 만든 파일 형식은 서로 호환되지 않음에 유의하십시오.

dbm.gnu 모듈은 GNU DBM 라이브러리에 대한 인터페이스를 제공합니다. dbm.gnu.gdbm 객체는 키와 값이 저장되기 전에 항상 바이트열로 변환된다는 점을 제외하고는 매핑(딕셔너리)처럼 동작합니다. gdbm 객체를 인쇄해도 키와 값이 인쇄되지 않으며, items()와 values() 메서드는 지원되지 않습니다.

exception dbm.gnu.error

I/O 에러와 같은 dbm.gnu 특정 에러에서 발생합니다. 잘못된 키 지정과 같은 일반적인 매핑 에러에 대해서는 KeyError가 발생합니다.

dbm.gnu.open(filename[, flag[, mode]])

gdbm 데이터베이스를 열고 gdbm 객체를 반환합니다. filename 인자는 데이터베이스 파일의 이름입니다.

선택적 flag 인자는 다음과 같은 것이 될 수 있습니다:

값

의미

'r'

읽기 전용으로 기존 데이터베이스 열기 (기본값)

'w'

읽고 쓰기 위해 기존 데이터베이스 열기

'c'

읽고 쓰기 위해 데이터베이스를 열고, 존재하지 않으면 만들기

'n'

읽고 쓰기 위해 항상 새로운 빈 데이터베이스를 만들기

데이터베이스를 여는 방법을 제어하기 위해 다음과 같은 추가 문자가 flag에 추가될 수 있습니다:

값

의미

'f'

데이터베이스를 빠른 모드로 엽니다. 데이터베이스로의 쓰기는 동기화되지 않습니다.

's'

동기화 모드. 이것은 데이터베이스 변경 사항이 파일에 즉시 기록되도록 합니다.

'u'

데이터베이스를 잠그지 않습니다.

모든 플래그가 모든 버전의 gdbm에서 유효한 것은 아닙니다. 모듈 상수 open_flags는 지원되는 플래그 문자의 문자열입니다. 유효하지 않은 플래그가 지정되면 error 예외가 발생합니다.

선택적 mode 인자는 파일의 유닉스 모드이며, 데이터베이스를 만들어야 할 때만 사용됩니다. 기본값은 8진수 0o666입니다.

딕셔너리와 유사한 메서드 외에도, gdbm 객체에는 다음과 같은 메서드가 있습니다:

gdbm.firstkey()

이 메서드와 nextkey() 메서드를 사용하여 데이터베이스의 모든 키를 순회할 수 있습니다. 순회는 gdbm의 내부 해시값 순이며, 키의 값으로 정렬되지 않습니다. 이 메서드는 시작 키를 반환합니다.

gdbm.nextkey(key)

순회에서 key 뒤에 오는 키를 반환합니다. 다음 코드는 메모리에 모든 키를 포함하는 리스트를 만들지 않고, 데이터베이스 db의 모든 키를 인쇄합니다:

k = db.firstkey()
while k != None:
    print(k)
    k = db.nextkey(k)

gdbm.reorganize()

많은 삭제를 수행한 후에, gdbm 파일이 사용하는 공간을 줄이려면, 이 루틴이 데이터베이스를 재구성합니다. gdbm 객체는 이 재구성을 사용할 때 외에는 데이터베이스 파일의 길이를 줄이지 않습니다; 그렇지 않으면, 삭제된 파일 공간이 유지되고 새 (키, 값) 쌍이 추가될 때 재사용됩니다.

gdbm.sync()

데이터베이스가 빠른 모드로 열렸을 때, 이 메서드를 사용하면 기록되지 않은 데이터가 디스크에 기록됩니다.

gdbm.close()

gdbm 데이터베이스를 닫습니다.

dbm.ndbm — ndbm 기반 인터페이스

소스 코드: Lib/dbm/ndbm.py [https://github.com/python/cpython/tree/3.7/Lib/dbm/ndbm.py]

dbm.ndbm 모듈은 유닉스 “(n) dbm” 라이브러리에 대한 인터페이스를 제공합니다. Dbm 객체는 키와 값이 항상 바이트열로 저장된다는 점을 제외하고는, 매핑(딕셔너리)처럼 동작합니다. dbm 객체를 인쇄해도 키와 값이 인쇄되지 않으며, items()와 values() 메서드는 지원되지 않습니다.

이 모듈은 “고전적인” ndbm 인터페이스나 GNU GDBM 호환 인터페이스로 사용할 수 있습니다. 유닉스에서, configure 스크립트는 이 모듈 빌드를 단순화하기 위해 적절한 헤더 파일을 찾습니다.

exception dbm.ndbm.error

I/O 에러와 같은 dbm.ndbm 특정 에러에서 발생합니다. 잘못된 키 지정과 같은 일반적인 매핑 에러에 대해서는 KeyError가 발생합니다.

dbm.ndbm.library

사용된 ndbm 구현 라이브러리의 이름.

dbm.ndbm.open(filename[, flag[, mode]])

dbm 데이터베이스를 열고 ndbm 객체를 반환합니다. filename 인자는 데이터베이스 파일의 이름입니다 (.dir이나 .pag 확장자는 없습니다).

선택적 flag 인자는 다음 값 중 하나여야 합니다:

값

의미

'r'

읽기 전용으로 기존 데이터베이스 열기 (기본값)

'w'

읽고 쓰기 위해 기존 데이터베이스 열기

'c'

읽고 쓰기 위해 데이터베이스를 열고, 존재하지 않으면 만들기

'n'

읽고 쓰기 위해 항상 새로운 빈 데이터베이스를 만들기

선택적 mode 인자는 파일의 유닉스 모드이며, 데이터베이스를 만들 때만 사용됩니다. 기본값은 8진수 0o666입니다 (그리고 현재 umask에 의해 수정됩니다).

딕셔너리와 유사한 메서드 외에도, ndbm 객체는 다음 메서드를 제공합니다:

ndbm.close()

ndbm 데이터베이스를 닫습니다.

dbm.dumb — 이식성 있는 DBM 구현

소스 코드: Lib/dbm/dumb.py [https://github.com/python/cpython/tree/3.7/Lib/dbm/dumb.py]

참고

dbm.dumb 모듈은 더욱 강인한 모듈을 사용할 수 없을 때 dbm 모듈에 대한 최후의 대체 폴백으로 사용됩니다. dbm.dumb 모듈은 속도를 위해 작성되지 않았으며 다른 데이터베이스 모듈만큼 많이 사용되지는 않습니다.

dbm.dumb 모듈은 완전히 파이썬으로 작성된 지속적인(persistent) 딕셔너리와 유사한 인터페이스를 제공합니다. dbm.gnu와 같은 다른 모듈과 달리, 외부 라이브러리가 필요하지 않습니다. 다른 지속성 매핑처럼, 키와 값은 항상 바이트열로 저장됩니다.

모듈은 다음과 같은 것들을 정의합니다:

exception dbm.dumb.error

I/O 에러와 같은 dbm.dumb 특정 에러에서 발생합니다. 잘못된 키 지정과 같은 일반적인 매핑 에러에 대해서는 KeyError가 발생합니다.

dbm.dumb.open(filename[, flag[, mode]])

dumbdbm 데이터베이스를 열고 dumbdbm 객체를 반환합니다. filename 인자는 데이터베이스 파일의 베이스 이름입니다 (특정 확장자는 없습니다). dumbdbm 데이터베이스가 만들어질 때, .dat와 .dir 확장자를 가진 파일이 만들어집니다.

The optional flag argument supports only the semantics of 'c' and 'n' values. Other values will default to database being always opened for update, and will be created if it does not exist.

선택적 mode 인자는 파일의 유닉스 모드이며, 데이터베이스를 만들 때만 사용됩니다. 기본값은 8진수 0o666입니다 (그리고 현재 umask에 의해 수정됩니다).

경고

파이썬 AST 컴파일러의 스택 깊이 제한으로 인해, 충분히 큰/복잡한 항목이 있는 데이터베이스를 로드할 때 파이썬 인터프리터가 충돌할 수 있습니다.

버전 3.5에서 변경: flag에 'n' 값이 있으면, open()은 항상 새 데이터베이스를 만듭니다.

Deprecated since version 3.6, will be removed in version 3.8: Creating database in 'r' and 'w' modes. Modifying database in 'r' mode.

collections.abc.MutableMapping 클래스가 제공하는 메서드 외에도, dumbdbm 객체는 다음 메서드를 제공합니다:

dumbdbm.sync()

디스크 상의 디렉터리와 데이터 파일을 동기화합니다. 이 메서드는 Shelve.sync() 메서드에 의해 호출됩니다.

dumbdbm.close()

dumbdbm 데이터베이스를 닫습니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

데이터 지속성 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

데이터 지속성 »

|

sqlite3 — SQLite 데이터베이스용 DB-API 2.0 인터페이스

소스 코드: Lib/sqlite3/ [https://github.com/python/cpython/tree/3.7/Lib/sqlite3/]

SQLite는 별도의 서버 프로세스가 필요 없고 SQL 질의 언어의 비표준 변형을 사용하여 데이터베이스에 액세스할 수 있는 경량 디스크 기반 데이터베이스를 제공하는 C 라이브러리입니다. 일부 응용 프로그램은 내부 데이터 저장을 위해 SQLite를 사용할 수 있습니다. SQLite를 사용하여 응용 프로그램을 프로토타입 한 다음 PostgreSQL 이나 Oracle과 같은 더 큰 데이터베이스로 코드를 이식할 수도 있습니다.

sqlite3 모듈은 Gerhard Häring이 썼습니다. PEP 249 [https://www.python.org/dev/peps/pep-0249]에서 설명하는 DB-API 2.0 명세를 준수하는 SQL 인터페이스를 제공합니다.

모듈을 사용하려면, 먼저 데이터베이스를 나타내는 Connection 객체를 만들어야 합니다. 여기서 데이터는 example.db 파일에 저장됩니다

import sqlite3
conn = sqlite3.connect('example.db')

특수 이름 :memory:를 제공하여 램에 데이터베이스를 만들 수도 있습니다.

일단 Connection를 얻으면, Cursor 객체를 만들고 execute() 메서드를 호출하여 SQL 명령을 수행할 수 있습니다.:

c = conn.cursor()

# Create table
c.execute('''CREATE TABLE stocks
             (date text, trans text, symbol text, qty real, price real)''')

# Insert a row of data
c.execute("INSERT INTO stocks VALUES ('2006-01-05','BUY','RHAT',100,35.14)")

# Save (commit) the changes
conn.commit()

# We can also close the connection if we are done with it.
# Just be sure any changes have been committed or they will be lost.
conn.close()

저장한 데이터는 영구적이며 이후 세션에서 사용할 수 있습니다:

import sqlite3
conn = sqlite3.connect('example.db')
c = conn.cursor()

일반적으로 SQL 연산은 파이썬 변수의 값을 사용해야 합니다. 파이썬의 문자열 연산을 사용하여 질의를 조합해서는 안 됩니다. 그렇게 하는 것은 안전하지 않기 때문입니다; 프로그램이 SQL 인젝션 공격에 취약하게 만듭니다 (잘못될 수 있는 유머러스한 예를 보려면 https://xkcd.com/327/ 를 참조하십시오).

대신 DB-API의 매개 변수 치환을 사용하십시오. 값을 사용하고자 할 때마다 ?를 자리 표시자로 넣은 다음, 커서의 execute() 메서드에 두 번째 인자로 값들의 튜플을 제공하십시오. (다른 데이터베이스 모듈은 다른 자리 표시자를 사용할 수 있습니다, 가령 %s 나 :1.) 예를 들면:

# Never do this -- insecure!
symbol = 'RHAT'
c.execute("SELECT * FROM stocks WHERE symbol = '%s'" % symbol)

# Do this instead
t = ('RHAT',)
c.execute('SELECT * FROM stocks WHERE symbol=?', t)
print(c.fetchone())

# Larger example that inserts many records at a time
purchases = [('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
             ('2006-04-05', 'BUY', 'MSFT', 1000, 72.00),
             ('2006-04-06', 'SELL', 'IBM', 500, 53.00),
            ]
c.executemany('INSERT INTO stocks VALUES (?,?,?,?,?)', purchases)

SELECT 문을 실행한 후 데이터를 꺼내려면, 커서를 이터레이터로 취급하거나, 커서의 fetchone() 메서드를 호출하여 일치하는 단일 행을 꺼내거나, fetchall()를 호출하여 일치하는 행의 리스트를 가져올 수 있습니다.

이 예제는 이터레이터 방식을 사용합니다:

>>> for row in c.execute('SELECT * FROM stocks ORDER BY price'):
        print(row)

('2006-01-05', 'BUY', 'RHAT', 100, 35.14)
('2006-03-28', 'BUY', 'IBM', 1000, 45.0)
('2006-04-06', 'SELL', 'IBM', 500, 53.0)
('2006-04-05', 'BUY', 'MSFT', 1000, 72.0)

더 보기

https://github.com/ghaering/pysqlite

pysqlite 웹 페이지 – sqlite3은 “pysqlite”라는 이름으로 외부에서 개발되었습니다.

https://www.sqlite.org

SQLite 웹 페이지; 설명서는 지원되는 SQL 언어에 대한 문법과 사용 가능한 데이터형을 설명합니다.

https://www.w3schools.com/sql/

SQL 문법 학습을 위한 자습서, 레퍼런스 및 예제

PEP 249 [https://www.python.org/dev/peps/pep-0249] - 데이터베이스 API 명세 2.0

Marc-André Lemburg가 작성한 PEP.

모듈 함수와 상수

sqlite3.version

이 모듈의 버전 번호(문자열). SQLite 라이브러리의 버전이 아닙니다.

sqlite3.version_info

이 모듈의 버전 번호(정수들의 튜플). SQLite 라이브러리의 버전이 아닙니다.

sqlite3.sqlite_version

런타임 SQLite 라이브러리의 버전 번호(문자열).

sqlite3.sqlite_version_info

런타임 SQLite 라이브러리의 버전 번호(정수들의 튜플).

sqlite3.PARSE_DECLTYPES

이 상수는 connect() 함수의 detect_types 매개 변수에 사용됩니다.

이것을 설정하면 sqlite3 모듈은 반환되는 각 열에 대해 선언된 형을 구문 분석합니다. 선언된 형의 첫 번째 단어를 구문 분석합니다, 즉 “integer primary key”에서는 “integer”를, “number (10)”에서는 “number”를 구문 분석합니다. 그런 다음 해당 열에 대해, 변환기 딕셔너리를 조사하고 그 형에 대해 등록된 변환기 함수를 사용합니다.

sqlite3.PARSE_COLNAMES

이 상수는 connect() 함수의 detect_types 매개 변수에 사용됩니다.

Setting this makes the SQLite interface parse the column name for each column it returns. It will look for a string formed [mytype] in there, and then decide that ‘mytype’ is the type of the column. It will try to find an entry of ‘mytype’ in the converters dictionary and then use the converter function found there to return the value. The column name found in Cursor.description does not include the type, i. e. if you use something like 'as "Expiration date [datetime]"' in your SQL, then we will parse out everything until the first '[' for the column name and strip the preceeding space: the column name would simply be “Expiration date”.

sqlite3.connect(database[, timeout, detect_types, isolation_level, check_same_thread, factory, cached_statements, uri])

SQLite 데이터베이스 파일 database에 대한 연결을 엽니다. 사용자 정의 factory가 주어지지 않는 한, 기본적으로 Connection 객체를 반환합니다.

database는 열릴 데이터베이스 파일의 경로명(절대 혹은 현재 작업 디렉터리에 대한 상대)을 제공하는 경로류 객체입니다. ":memory:"를 사용하여 디스크 대신 램(RAM)에 있는 데이터베이스에 대한 데이터베이스 연결을 열 수 있습니다.

데이터베이스가 여러 연결을 통해 액세스 되고, 프로세스 중 하나가 데이터베이스를 수정할 때, 해당 트랜잭션이 커밋될 때까지 SQLite 데이터베이스가 잠깁니다. timeout 매개 변수는 예외를 일으키기 전에 잠금이 해제되기를 연결이 기다려야 하는 시간을 지정합니다. timeout 매개 변수의 기본값은 5.0(5초)입니다.

isolation_level 매개 변수는 Connection 객체의 isolation_level 프로퍼티를 참조하십시오.

SQLite는 기본적으로 TEXT, INTEGER, REAL, BLOB 및 NULL 형만 지원합니다. 다른 형을 사용하려면 직접 지원을 추가해야 합니다. detect_types 매개 변수와 모듈 수준 register_converter() 함수로 등록된 사용자 정의 변환기를 사용하면 쉽게 할 수 있습니다.

detect_types의 기본값은 0입니다 (즉, 형 감지가 없습니다). PARSE_DECLTYPES와 PARSE_COLNAMES의 조합으로 설정하여 형 감지를 켤 수 있습니다.

기본적으로 check_same_thread는 True며, 만들고 있는 스레드 만 이 연결을 사용할 수 있습니다. False로 설정하면 반환된 연결을 여러 스레드에서 공유할 수 있습니다. 여러 스레드에서 같은 연결을 사용할 때, 데이터 손상을 피하려면 쓰기 연산을 사용자가 직렬화해야 합니다.

기본적으로, sqlite3 모듈은 connect 호출에 Connection 클래스를 사용합니다. 그러나, Connection 클래스의 서브 클래스를 만들고 factory 매개 변수에 클래스를 제공하면 connect()가 그 클래스를 사용하게 할 수 있습니다.

자세한 내용은 이 설명서의 섹션 SQLite 와 파이썬 형을 참조하십시오.

sqlite3 모듈은 내부적으로 SQL 구문 분석 오버헤드를 피하고자 명령문 캐시를 사용합니다. 연결에 대해 캐시 되는 명령문의 수를 명시적으로 설정하려면, cached_statements 매개 변수를 설정할 수 있습니다. 현재 구현된 기본값은 100개의 명령문을 캐시 하는 것입니다.

uri가 참이면 database는 URI로 해석됩니다. 이렇게 하면 옵션을 지정할 수 있습니다. 예를 들어, 읽기 전용 모드로 데이터베이스를 열려면 다음과 같이 할 수 있습니다:

db = sqlite3.connect('file:path/to/database?mode=ro', uri=True)

인식되는 옵션 목록을 포함하여, 이 기능에 대한 자세한 내용은 SQLite URI documentation [https://www.sqlite.org/uri.html]에서 찾을 수 있습니다.

버전 3.4에서 변경: uri 매개 변수가 추가되었습니다.

버전 3.7에서 변경: database는 이제 문자열뿐만 아니라 경로류 객체 일 수도 있습니다.

sqlite3.register_converter(typename, callable)

데이터베이스의 바이트열을 사용자 정의 파이썬 형으로 변환할 수 있는 콜러블을 등록합니다. 콜러블은 형 typename 인 모든 데이터베이스 값에 대해 호출됩니다. 형 감지 작동 방식에 대해서는 connect() 함수의 매개 변수 detect_types를 참고하십시오. typename과 질의의 형 이름은 대/소문자를 구분하지 않고 일치시킴에 유의하십시오.

sqlite3.register_adapter(type, callable)

사용자 정의 파이썬 형 type을 SQLite의 지원되는 형 중 하나로 변환할 수 있는 콜러블을 등록합니다. 콜러블 callable은 단일 매개 변수로 파이썬 값을 받아들이고 다음 형들의 값을 반환해야 합니다: int, float, str 또는 bytes.

sqlite3.complete_statement(sql)

문자열 sql에 세미콜론으로 끝나는 하나 이상의 완전한 SQL 문이 포함되어 있으면 True를 반환합니다. SQL이 문법적으로 올바른지 확인하지는 않습니다. 닫히지 않은 문자열 리터럴이 없고 명령문이 세미콜론으로 끝나는지만 확인합니다.

이것은 다음 예제와 같이, SQLite 용 셸을 만드는데 사용할 수 있습니다:

# A minimal SQLite shell for experiments

import sqlite3

con = sqlite3.connect(":memory:")
con.isolation_level = None
cur = con.cursor()

buffer = ""

print("Enter your SQL commands to execute in sqlite3.")
print("Enter a blank line to exit.")

while True:
    line = input()
    if line == "":
        break
    buffer += line
    if sqlite3.complete_statement(buffer):
        try:
            buffer = buffer.strip()
            cur.execute(buffer)

            if buffer.lstrip().upper().startswith("SELECT"):
                print(cur.fetchall())
        except sqlite3.Error as e:
            print("An error occurred:", e.args[0])
        buffer = ""

con.close()

sqlite3.enable_callback_tracebacks(flag)

기본적으로 사용자 정의 함수, 집계(aggregates), 변환기, 인가(authorizer) 콜백 등에서는 트레이스백을 얻지 못합니다. 디버깅하려면 flag를 True로 설정하여 이 함수를 호출할 수 있습니다. 그러면, sys.stderr로 콜백의 트레이스백을 얻게 됩니다. 기능을 다시 비활성화하려면 False를 사용하십시오.

Connection 객체

class sqlite3.Connection

SQLite 데이터베이스 연결에는 다음과 같은 어트리뷰트와 메서드가 있습니다:

isolation_level

현재의 기본 격리 수준을 가져오거나 설정합니다. 자동 커밋 모드를 뜻하는 None 이나 “DEFERRED”, “IMMEDIATE” 또는 “EXCLUSIVE” 중 하나입니다. 자세한 설명은 트랜잭션 제어 절을 참조하십시오.

in_transaction

트랜잭션이 활성화 상태면(커밋되지 않은 변경 사항이 있으면) True, 그렇지 않으면 False. 읽기 전용 어트리뷰트.

버전 3.2에 추가.

cursor(factory=Cursor)

cursor 메서드는 단일 선택적 매개 변수 factory를 받아들입니다. 제공되면, 이것은 Cursor 나 그 서브 클래스의 인스턴스를 반환하는 콜러블이어야 합니다.

commit()

이 메서드는 현재 트랜잭션을 커밋합니다. 이 메서드를 호출하지 않으면, 마지막 commit() 호출 이후에 수행한 작업은 다른 데이터베이스 연결에서 볼 수 없습니다. 데이터베이스에 기록한 데이터가 왜 보이지 않는지 궁금하면, 이 메서드를 호출하는 것을 잊지 않았는지 확인하십시오.

rollback()

이 메서드는 마지막 commit() 호출 이후의 데이터베이스에 대한 모든 변경 사항을 되돌립니다.

close()

데이터베이스 연결을 닫습니다. 자동으로 commit()을 호출하지 않음에 유의하십시오. commit()를 먼저 호출하지 않고 데이터베이스 연결을 닫으면 변경 사항이 손실됩니다!

execute(sql[, parameters])

이것은 비표준 바로 가기인데, cursor() 메서드를 호출하여 커서 객체를 만들고, 지정된 parameters를 사용하여 커서의 execute() 메서드를 호출한 다음, 커서를 반환합니다.

executemany(sql[, parameters])

이것은 비표준 바로 가기인데, cursor() 메서드를 호출하여 커서 객체를 만들고, 지정된 parameters를 사용하여 커서의 executemany() 메서드를 호출한 다음, 커서를 반환합니다.

executescript(sql_script)

이것은 비표준 바로 가기인데, cursor() 메서드를 호출하여 커서 객체를 만들고, 지정된 sql_script를 사용하여 커서의 executescript() 메서드를 호출한 다음, 커서를 반환합니다.

create_function(name, num_params, func)

나중에 함수 이름 name으로 SQL 문에서 사용할 수 있는 사용자 정의 함수를 만듭니다. num_params는 함수가 받아들이는 매개 변수의 수입니다 (num_params가 -1이면 함수는 임의의 인자를 취할 수 있습니다). func는 SQL 함수로 호출되는 파이썬 콜러블입니다.

함수는 SQLite가 지원하는 모든 형을 반환할 수 있습니다: bytes, str, int, float 및 None.

예:

import sqlite3
import hashlib

def md5sum(t):
    return hashlib.md5(t).hexdigest()

con = sqlite3.connect(":memory:")
con.create_function("md5", 1, md5sum)
cur = con.cursor()
cur.execute("select md5(?)", (b"foo",))
print(cur.fetchone()[0])

con.close()

create_aggregate(name, num_params, aggregate_class)

사용자 정의 집계(aggregate) 함수를 만듭니다.

매개 변수의 수 num_params(num_params가 -1이면 함수는 임의의 인자를 취할 수 있습니다)를 받아들이며, 집계 클래스는 step 메서드와 집계의 최종 결과를 반환하는 finalize 메서드를 구현해야 합니다.

finalize 메서드는 SQLite가 지원하는 모든 형을 반환할 수 있습니다: bytes, str, int, float 및 None.

예:

import sqlite3

class MySum:
    def __init__(self):
        self.count = 0

    def step(self, value):
        self.count += value

    def finalize(self):
        return self.count

con = sqlite3.connect(":memory:")
con.create_aggregate("mysum", 1, MySum)
cur = con.cursor()
cur.execute("create table test(i)")
cur.execute("insert into test(i) values (1)")
cur.execute("insert into test(i) values (2)")
cur.execute("select mysum(i) from test")
print(cur.fetchone()[0])

con.close()

create_collation(name, callable)

지정된 name 과 callable로 정렬법(collation)을 만듭니다. 콜러블에는 두 개의 문자열 인자가 전달됩니다. 첫째가 둘째보다 작은 순서면 -1, 같은 순서면 0, 첫째가 둘째보다 큰 순서면 1을 반환 해야 합니다. 이것은 정렬(SQL의 ORDER BY)을 제어하므로, 여러분의 비교는 다른 SQL 연산에 영향을 주지 않습니다.

콜러블 객체는 보통 UTF-8로 인코딩된 파이썬 바이트열로 매개 변수를 가져옵니다.

다음 예제는 “잘못된 방법”으로 정렬하는 사용자 정의 정렬법을 보여줍니다:

import sqlite3

def collate_reverse(string1, string2):
    if string1 == string2:
        return 0
    elif string1 < string2:
        return 1
    else:
        return -1

con = sqlite3.connect(":memory:")
con.create_collation("reverse", collate_reverse)

cur = con.cursor()
cur.execute("create table test(x)")
cur.executemany("insert into test(x) values (?)", [("a",), ("b",)])
cur.execute("select x from test order by x collate reverse")
for row in cur:
    print(row)
con.close()

정렬법을 제거하려면 callable에 None을 사용해서 create_collation를 호출하십시오:

con.create_collation("reverse", None)

interrupt()

연결에서 실행 중일 수 있는 모든 질의를 중단하려면, 이 메서드를 다른 스레드에서 호출할 수 있습니다. 그러면 질의가 중단되고 호출자는 예외를 받습니다.

set_authorizer(authorizer_callback)

이 루틴은 콜백을 등록합니다. 콜백은 데이터베이스의 테이블 열에 액세스할 때마다 호출됩니다. 콜백은 액세스가 허용되면 SQLITE_OK를 반환하고, 전체 SQL 문을 에러를 일으키며 중단해야 하면 SQLITE_DENY를, 열을 NULL 값으로 처리하려면 SQLITE_IGNORE를 반환해야 합니다. 이 상수들은 sqlite3 모듈에 있습니다.

콜백의 첫 번째 인자는 어떤 종류의 연산이 인가받으려 하는지를 나타냅니다. 두 번째와 세 번째 인자는 첫 번째 인자에 따라 인자이거나 None이 됩니다. 네 번째 인자는 해당하면 데이터베이스 이름(“main”, “temp” 등)입니다. 다섯 번째 인자는 액세스 시도를 담당하는 가장 안쪽의 트리거나 뷰의 이름이거나, 이 액세스 시도가 입력 SQL 코드에서 직접 발생했으면 None입니다.

첫 번째 인자에 가능한 값과 첫 번째 인자에 의존하는 두 번째 및 세 번째 인자의 의미에 대해서는 SQLite 문서를 참조하십시오. 필요한 모든 상수는 sqlite3 모듈에 있습니다.

set_progress_handler(handler, n)

이 루틴은 콜백을 등록합니다. 콜백은 SQLite 가상 머신의 매 n개의 명령어마다 호출됩니다. 장시간 실행되는 작업 중에 SQLite로부터 호출되기를 원할 때 유용합니다, 예를 들어 GUI를 갱신하는데 사용할 수 있습니다.

이전에 설치된 모든 진행 처리기를 지우려면 handler로 None을 사용하여 메서드를 호출하십시오.

처리기 함수에서 0이 아닌 값을 반환하면 현재 실행 중인 질의가 종료되고 OperationalError 예외가 발생합니다.

set_trace_callback(trace_callback)

SQLite 백 엔드가 실제로 실행하는 각 SQL 문마다 호출할 trace_callback을 등록합니다.

콜백에 전달되는 유일한 인자는 실행 중인 문장(문자열)입니다. 콜백의 반환 값은 무시됩니다. 백 엔드는 Cursor.execute() 메서드에 전달된 명령문만 실행하는 것은 아님에 유의하시기 바랍니다. 다른 소스로는 파이썬 모듈의 트랜잭션 관리와 현재 데이터베이스에 정의된 트리거의 실행이 있습니다.

None을 trace_callback로 전달하면 추적 콜백을 비활성화합니다.

버전 3.3에 추가.

enable_load_extension(enabled)

이 루틴은 SQLite 엔진이 공유 라이브러리에서 SQLite 확장을 로드하는 것을 허용/불허합니다. SQLite 확장은 새 함수, 집계 또는 완전히 새로운 가상 테이블 구현을 정의할 수 있습니다. 잘 알려진 확장 중 하나는 SQLite와 함께 배포되는 전체 텍스트 검색 확장입니다.

로드 가능한 확장은 기본적으로 비활성화되어 있습니다. 1를 보세요.

버전 3.2에 추가.

import sqlite3

con = sqlite3.connect(":memory:")

# enable extension loading
con.enable_load_extension(True)

# Load the fulltext search extension
con.execute("select load_extension('./fts3.so')")

# alternatively you can load the extension using an API call:
# con.load_extension("./fts3.so")

# disable extension loading again
con.enable_load_extension(False)

# example from SQLite wiki
con.execute("create virtual table recipe using fts3(name, ingredients)")
con.executescript("""
    insert into recipe (name, ingredients) values ('broccoli stew', 'broccoli peppers cheese tomatoes');
    insert into recipe (name, ingredients) values ('pumpkin stew', 'pumpkin onions garlic celery');
    insert into recipe (name, ingredients) values ('broccoli pie', 'broccoli cheese onions flour');
    insert into recipe (name, ingredients) values ('pumpkin pie', 'pumpkin sugar flour butter');
    """)
for row in con.execute("select rowid, name, ingredients from recipe where name match 'pie'"):
    print(row)

con.close()

load_extension(path)

이 루틴은 공유 라이브러리에서 SQLite 확장을 로드합니다. 이 루틴을 사용하려면 먼저 enable_load_extension()로 확장 로드를 활성화해야 합니다.

로드 가능한 확장은 기본적으로 비활성화되어 있습니다. 1를 보세요.

버전 3.2에 추가.

row_factory

이 어트리뷰트를 커서와 원본 행을 튜플로 받아들이고 실제 결과 행을 반환하는 콜러블로 변경할 수 있습니다. 이렇게 하면, 이름으로 열을 액세스할 수 있는 객체를 반환하는 것과 같이, 결과를 반환하는 더 고급 방식을 구현할 수 있습니다.

예:

import sqlite3

def dict_factory(cursor, row):
    d = {}
    for idx, col in enumerate(cursor.description):
        d[col[0]] = row[idx]
    return d

con = sqlite3.connect(":memory:")
con.row_factory = dict_factory
cur = con.cursor()
cur.execute("select 1 as a")
print(cur.fetchone()["a"])

con.close()

튜플을 반환하는 것으로 충분하지 않고 열에 대한 이름 기반 액세스를 원하면, row_factory를 고도로 최적화된 sqlite3.Row 형으로 설정하는 것을 고려해야 합니다. Row는 메모리 오버헤드가 거의 없이 열에 대해 인덱스 기반과 대소 문자를 구분하지 않는 이름 기반 액세스를 제공합니다. 아마도 여러분 자신의 사용자 정의 딕셔너리 기반 접근법이나 심지어 db_row 기반 해법보다 더 좋을 것입니다.

text_factory

이 어트리뷰트를 사용하면 TEXT 데이터형에 대해 반환되는 객체를 제어할 수 있습니다. 기본적으로, 이 어트리뷰트는 str로 설정되고 sqlite3 모듈은 TEXT에 대해 유니코드 객체를 반환합니다. 대신 바이트열을 반환하려면, bytes로 설정할 수 있습니다.

하나의 바이트열 매개 변수를 받아들이고 결과 객체를 반환하는 다른 콜러블 객체로 설정할 수도 있습니다.

예시를 위해 다음 예제 코드를 참조하십시오:

import sqlite3

con = sqlite3.connect(":memory:")
cur = con.cursor()

AUSTRIA = "\xd6sterreich"

# by default, rows are returned as Unicode
cur.execute("select ?", (AUSTRIA,))
row = cur.fetchone()
assert row[0] == AUSTRIA

# but we can make sqlite3 always return bytestrings ...
con.text_factory = bytes
cur.execute("select ?", (AUSTRIA,))
row = cur.fetchone()
assert type(row[0]) is bytes
# the bytestrings will be encoded in UTF-8, unless you stored garbage in the
# database ...
assert row[0] == AUSTRIA.encode("utf-8")

# we can also implement a custom text_factory ...
# here we implement one that appends "foo" to all strings
con.text_factory = lambda x: x.decode("utf-8") + "foo"
cur.execute("select ?", ("bar",))
row = cur.fetchone()
assert row[0] == "barfoo"

con.close()

total_changes

데이터베이스 연결이 열린 후 수정, 삽입 또는 삭제된 데이터베이스 행의 총수를 반환합니다.

iterdump()

SQL 텍스트 형식으로 데이터베이스를 덤프하는 이터레이터를 반환합니다. 나중에 복원할 수 있도록 메모리 데이터베이스를 저장할 때 유용합니다. 이 함수는 sqlite3 셸의 .dump 명령과 같은 기능을 제공합니다.

예:

# Convert file existing_db.db to SQL dump file dump.sql
import sqlite3

con = sqlite3.connect('existing_db.db')
with open('dump.sql', 'w') as f:
    for line in con.iterdump():
        f.write('%s\n' % line)
con.close()

backup(target, *, pages=0, progress=None, name="main", sleep=0.250)

이 메서드는 SQLite 데이터베이스의 백업을 만드는데, 다른 클라이언트가 액세스하고 있거나 같은 연결로 동시에 액세스하고 있어도 됩니다. 복사본은 필수 인자 target에 기록되며, 이것은 다른 Connection 인스턴스여야 합니다.

기본적으로, 또는 pages가 0 이나 음의 정수이면, 전체 데이터베이스가 단일 단계로 복사됩니다; 그렇지 않으면 이 메서드는 한 번에 최대 pages 페이지만큼 복사하는 루프를 수행합니다.

progress가 지정되면, None 또는 매 이터레이션마다 세 개의 정수 인자로 실행되는 콜러블 객체여야 합니다. 세 인자는 각각 직전 이터레이션의 상태(status), 아직 복사해야 할 남은(remaining) 페이지 수, 전체(total) 페이지 수입니다.

name 인자는 복사할 데이터베이스 이름을 지정합니다: main 데이터베이스를 나타내는 "main", 기본값, 임시 데이터베이스를 나타내는 "temp" 또는 첨부된 데이터베이스를 위한 ATTACH DATABASE 문에서 AS 키워드 뒤에 지정된 이름을 포함하는 문자열이어야 합니다.

sleep 인자는 남은 페이지를 백업하는 연속적인 시도 사이에서 잠잘 시간을 초 단위로 지정하며, 정수 또는 부동 소수점 값으로 지정할 수 있습니다.

예제 1, 기존 데이터베이스를 다른 데이터베이스로 복사:

import sqlite3

def progress(status, remaining, total):
    print(f'Copied {total-remaining} of {total} pages...')

con = sqlite3.connect('existing_db.db')
bck = sqlite3.connect('backup.db')
with bck:
    con.backup(bck, pages=1, progress=progress)
bck.close()
con.close()

예제 2, 기존 데이터베이스를 임시 복사본으로 복사:

import sqlite3

source = sqlite3.connect('existing_db.db')
dest = sqlite3.connect(':memory:')
source.backup(dest)

가용성: SQLite 3.6.11 이상

버전 3.7에 추가.

Cursor 객체

class sqlite3.Cursor

Cursor 인스턴스에는 다음과 같은 어트리뷰트와 메서드가 있습니다.

execute(sql[, parameters])

SQL 문을 실행합니다. SQL 문을 매개 변수화(즉, SQL 리터럴 대신 자리 표시자)할 수 있습니다. sqlite3 모듈은 두 가지 자리 표시자를 지원합니다: 물음표(qmark 스타일)와 이름있는 자리 표시자(named 스타일).

다음은 두 스타일의 예입니다:

import sqlite3

con = sqlite3.connect(":memory:")
cur = con.cursor()
cur.execute("create table people (name_last, age)")

who = "Yeltsin"
age = 72

# This is the qmark style:
cur.execute("insert into people values (?, ?)", (who, age))

# And this is the named style:
cur.execute("select * from people where name_last=:who and age=:age", {"who": who, "age": age})

print(cur.fetchone())

con.close()

execute()는 단일 SQL 문만 실행합니다. 하나 이상의 명령문을 실행하려고 하면 Warning이 발생합니다. 하나의 호출로 여러 SQL 문을 실행하려면 executescript()를 사용하십시오.

executemany(sql, seq_of_parameters)

시퀀스 seq_of_parameters에 있는 모든 매개 변수 시퀀스나 매핑에 대해 SQL 명령을 실행합니다. sqlite3 모듈은 시퀀스 대신 매개 변수를 산출하는 이터레이터도 허용합니다.

import sqlite3

class IterChars:
    def __init__(self):
        self.count = ord('a')

    def __iter__(self):
        return self

    def __next__(self):
        if self.count > ord('z'):
            raise StopIteration
        self.count += 1
        return (chr(self.count - 1),) # this is a 1-tuple

con = sqlite3.connect(":memory:")
cur = con.cursor()
cur.execute("create table characters(c)")

theIter = IterChars()
cur.executemany("insert into characters(c) values (?)", theIter)

cur.execute("select c from characters")
print(cur.fetchall())

con.close()

다음은 제너레이터를 사용하는 간단한 예입니다:

import sqlite3
import string

def char_generator():
    for c in string.ascii_lowercase:
        yield (c,)

con = sqlite3.connect(":memory:")
cur = con.cursor()
cur.execute("create table characters(c)")

cur.executemany("insert into characters(c) values (?)", char_generator())

cur.execute("select c from characters")
print(cur.fetchall())

con.close()

executescript(sql_script)

이것은 한 번에 여러 SQL 문을 실행하기 위한 비표준 편의 메서드입니다. 먼저 COMMIT 문을 실행한 다음, 매개 변수로 가져온 SQL 스크립트를 실행합니다.

sql_script는 str의 인스턴스가 될 수 있습니다.

예:

import sqlite3

con = sqlite3.connect(":memory:")
cur = con.cursor()
cur.executescript("""
    create table person(
        firstname,
        lastname,
        age
    );

    create table book(
        title,
        author,
        published
    );

    insert into book(title, author, published)
    values (
        'Dirk Gently''s Holistic Detective Agency',
        'Douglas Adams',
        1987
    );
    """)
con.close()

fetchone()

질의 결과 집합의 다음 행을 가져옵니다. 단일 시퀀스를 반환하거나, 데이터가 더 없을 때 None을 반환합니다.

fetchmany(size=cursor.arraysize)

질의 결과의 다음 행 집합을 가져와서, 리스트를 반환합니다. 행이 더 없으면 빈 목록이 반환됩니다.

호출 당 가져오는 행의 수는 size 매개 변수로 지정됩니다. 지정되어 않으면, 커서의 arraysize가 가져올 행의 수를 결정합니다. 이 메서드는 size 매개 변수가 나타내는 수만큼의 행을 가져오려고 해야 합니다. 지정된 수의 행이 없어서 이것이 가능하지 않다면, 더 적은 행이 반환될 수 있습니다.

size 매개 변수와 관련된 성능 고려 사항이 있습니다. 최적의 성능을 위해서, 일반적으로 arraysize 어트리뷰트를 사용하는 것이 가장 좋습니다. size 매개 변수가 사용되면, fetchmany() 호출마다 같은 값을 유지하는 것이 가장 좋습니다.

fetchall()

질의 결과의 모든 (남은) 행을 가져와서 리스트를 반환합니다. 커서의 arraysize 어트리뷰트는 이 연산의 성능에 영향을 줄 수 있습니다. 행이 없으면 빈 리스트가 반환됩니다.

close()

(__del__이 호출 될 때가 아니라) 지금 커서를 닫습니다.

이 시점부터는 커서를 사용할 수 없습니다; 커서로 어떤 연산이건 시도하면 ProgrammingError 예외가 발생합니다.

rowcount

sqlite3 모듈의 Cursor 클래스가 이 어트리뷰트를 구현하지만, “영향을 받는 행”/”선택된 행”의 판단을 위한 데이터베이스 엔진 자체 지원은 기이합니다.

executemany() 문에서, 수정 횟수는 rowcount에 합산됩니다.

파이썬 DB API 스펙에 따라, rowcount 어트리뷰트는 커서에서 executeXX()가 수행되지 않았거나 마지막 연산의 행 개수가 인터페이스에 의해 결정되지 않는 경우 -1입니다. 이런 경우는 SELECT 문을 포함하는데, 모든 행을 가져올 때까지 질의가 생성 한 행 수를 결정할 수 없기 때문입니다.

3.6.5 이전의 SQLite 버전에서는, 조건 없이 DELETE FROM table을 하면 rowcount가 0으로 설정됩니다.

lastrowid

이 읽기 전용 어트리뷰트는 마지막으로 수정된 행의 rowid를 제공합니다. execute() 메서드를 사용하여 INSERT 나 REPLACE 문을 실행했을 때만 설정됩니다. INSERT 나 REPLACE 이외의 연산이나 executemany()가 호출될 때, lastrowid는 None으로 설정됩니다.

INSERT 나 REPLACE 문이 삽입에 실패하면, 이전의 성공적인 rowid가 반환됩니다.

버전 3.6에서 변경: REPLACE 문에 대한 지원이 추가되었습니다.

arraysize

fetchmany()에 의해 반환되는 행의 수를 제어하는 읽기/쓰기 어트리뷰트. 기본값은 1입니다. 이는 호출 당 하나의 행을 가져오는 것을 뜻합니다.

description

이 읽기 전용 어트리뷰트는 마지막 질의의 열 이름을 제공합니다. 파이썬 DB API와의 호환성을 유지하기 위해, 각 열마다 7-튜플을 반환하는데, 각 튜플의 마지막 6개 항목은 None 입니다.

일치하는 행이 없는 SELECT 문에도 설정됩니다.

connection

이 읽기 전용 어트리뷰트는 Cursor 객체가 사용하는 SQLite 데이터베이스 Connection을 제공합니다. con.cursor()를 호출하여 생성된 Cursor 객체는 con을 참조하는 connection 어트리뷰트를 가집니다:

>>> con = sqlite3.connect(":memory:")
>>> cur = con.cursor()
>>> cur.connection == con
True

Row 객체

class sqlite3.Row

Row 인스턴스는 Connection 객체에 대해 고도로 최적화된 row_factory 역할을 합니다. 대부분 기능에서 튜플을 모방하려고 합니다.

열 이름과 인덱스에 의한 매핑 액세스와, 이터레이션, 표현(repr), 동등성 검사 및 len()을 지원합니다.

두 개의 Row 객체가 정확히 같은 열을 갖고 그 구성원이 같으면 같다고 비교됩니다.

keys()

이 메서드는 열 이름 리스트를 반환합니다. 질의 직후, Cursor.description에 있는 각 튜플의 첫 번째 멤버입니다.

버전 3.5에서 변경: 슬라이싱 지원이 추가되었습니다.

위에서 주어진 예제에서처럼 테이블을 초기화한다고 가정해 봅시다:

conn = sqlite3.connect(":memory:")
c = conn.cursor()
c.execute('''create table stocks
(date text, trans text, symbol text,
 qty real, price real)''')
c.execute("""insert into stocks
          values ('2006-01-05','BUY','RHAT',100,35.14)""")
conn.commit()
c.close()

이제 우리는 Row를 연결합니다:

>>> conn.row_factory = sqlite3.Row
>>> c = conn.cursor()
>>> c.execute('select * from stocks')
<sqlite3.Cursor object at 0x7f4e7dd8fa80>
>>> r = c.fetchone()
>>> type(r)
<class 'sqlite3.Row'>
>>> tuple(r)
('2006-01-05', 'BUY', 'RHAT', 100.0, 35.14)
>>> len(r)
5
>>> r[2]
'RHAT'
>>> r.keys()
['date', 'trans', 'symbol', 'qty', 'price']
>>> r['qty']
100.0
>>> for member in r:
...     print(member)
...
2006-01-05
BUY
RHAT
100.0
35.14

예외

exception sqlite3.Warning

Exception의 서브 클래스.

exception sqlite3.Error

이 모듈에 있는 다른 예외의 베이스 클래스. Exception의 서브 클래스입니다.

exception sqlite3.DatabaseError

데이터베이스와 관련된 에러에 대해 발생하는 예외.

exception sqlite3.IntegrityError

데이터베이스의 관계형 무결성이 영향을 받을 때 발생하는 예외. 예를 들어, 외부 키(foreign key) 검사가 실패할 때. DatabaseError의 서브 클래스입니다.

exception sqlite3.ProgrammingError

프로그래밍 에러에 대한 예외, 예를 들어, 테이블을 찾을 수 없거나 이미 존재 함, SQL 문의 문법 에러, 지정된 매개 변수 개수가 잘못됨 등. DatabaseError의 서브 클래스입니다.

exception sqlite3.OperationalError

데이터베이스 연산과 관련되고 프로그래머의 제어하에 있지 않은 에러에 관한 오류. 예를 들어, 예기치 않은 단절이 발생하거나, 데이터 소스 이름을 찾을 수 없거나, 트랜잭션이 진행될 수 없을 때 등. DatabaseError의 서브 클래스입니다.

exception sqlite3.NotSupportedError

데이터베이스에서 지원하지 않는 메서드나 데이터베이스 API가 사용될 때 발생하는 예외. 예를 들어, 트랜잭션을 지원하지 않는 연결에서 rollback() 메서드를 호출할 때. DatabaseError의 서브 클래스입니다.

SQLite 와 파이썬 형

소개

SQLite는 기본적으로 다음 형을 지원합니다: NULL, INTEGER, REAL, TEXT, BLOB.

따라서 다음과 같은 파이썬 형을 아무 문제 없이 SQLite로 보낼 수 있습니다:

파이썬 형

SQLite 형

None

NULL

int

INTEGER

float

REAL

str

TEXT

bytes

BLOB

이것은 SQLite 형이 기본적으로 파이썬 형으로 변환되는 방법입니다:

SQLite 형

파이썬 형

NULL

None

INTEGER

int

REAL

float

TEXT

text_factory에 따라 다릅니다, 기본적으로 str.

BLOB

bytes

sqlite3 모듈의 형 시스템은 두 가지 방식으로 확장 가능합니다: 객체 어댑터를 통해 SQLite 데이터베이스에 추가 파이썬 형을 저장할 수 있으며 변환기를 통해 sqlite3 모듈에서 SQLite 형을 다른 파이썬 형으로 변환할 수 있습니다.

어댑터를 사용하여 SQLite 데이터베이스에 추가 파이썬 형을 저장하기

앞에서 설명한 것처럼, SQLite는 기본적으로 제한된 형 집합만 지원합니다. SQLite에 다른 파이썬 형을 사용하려면, SQLite에 대해 sqlite3 모듈이 지원하는 형 중 하나로 어댑트 해야 합니다: NoneType, int, float, str, bytes 중 하나.

sqlite3 모듈이 사용자 정의 파이썬 형을, 지원되는 형 중 하나로 어댑트하도록 만드는 두 가지 방법이 있습니다.

객체가 스스로 어댑트하도록 하기

여러분이 스스로 클래스를 작성한다면 이것이 좋은 접근법입니다. 다음과 같은 클래스가 있다고 가정해 봅시다:

class Point:
    def __init__(self, x, y):
        self.x, self.y = x, y

이제 Point를 단일 SQLite 열에 저장하려고 합니다. 먼저 포인트를 나타내는데 사용할 지원되는 형 중 하나를 선택해야 합니다. str을 사용하고 좌표를 세미콜론으로 분리하기로 합시다. 그런 다음 여러분의 클래스에 변환된 값을 반환하는 __conform__(self, protocol) 메서드를 제공해야 합니다. 매개 변수 protocol은 PrepareProtocol이 됩니다.

import sqlite3

class Point:
    def __init__(self, x, y):
        self.x, self.y = x, y

    def __conform__(self, protocol):
        if protocol is sqlite3.PrepareProtocol:
            return "%f;%f" % (self.x, self.y)

con = sqlite3.connect(":memory:")
cur = con.cursor()

p = Point(4.0, -3.2)
cur.execute("select ?", (p,))
print(cur.fetchone()[0])

con.close()

어댑터 콜러블 등록하기

또 다른 가능성은 형을 문자열 표현으로 변환하는 함수를 만들고. 그 함수를 register_adapter()로 등록하는 것입니다.

import sqlite3

class Point:
    def __init__(self, x, y):
        self.x, self.y = x, y

def adapt_point(point):
    return "%f;%f" % (point.x, point.y)

sqlite3.register_adapter(Point, adapt_point)

con = sqlite3.connect(":memory:")
cur = con.cursor()

p = Point(4.0, -3.2)
cur.execute("select ?", (p,))
print(cur.fetchone()[0])

con.close()

sqlite3 모듈에는 파이썬의 내장 datetime.date 와 datetime.datetime 형에 대한 두 개의 기본 어댑터가 있습니다. 이제 datetime.datetime 객체를 ISO 표현이 아닌 유닉스 타임스탬프로 저장하려고 한다고 가정해 봅시다.

import sqlite3
import datetime
import time

def adapt_datetime(ts):
    return time.mktime(ts.timetuple())

sqlite3.register_adapter(datetime.datetime, adapt_datetime)

con = sqlite3.connect(":memory:")
cur = con.cursor()

now = datetime.datetime.now()
cur.execute("select ?", (now,))
print(cur.fetchone()[0])

con.close()

SQLite 값을 사용자 정의 파이썬 형으로 변환하기

어댑터를 작성하면 사용자 정의 파이썬 형을 SQLite로 보낼 수 있습니다. 그러나 실제로 유용하게 사용하려면 파이썬에서 SQLite를 거쳐 다시 파이썬으로 돌아오는 순환이 동작하게 할 필요가 있습니다.

변환기를 사용하십시오.

Point 클래스로 돌아갑시다. 세미콜론으로 분리된 x와 y 좌표를 SQLite에 문자열로 저장했습니다.

먼저, 문자열을 매개 변수로 받아들이고 이것으로부터 Point 객체를 만드는 변환기 함수를 정의합니다.

참고

변환기 함수는 항상 SQLite로 보낸 값의 데이터형에 상관없이 bytes 객체로 호출됩니다.

def convert_point(s):
    x, y = map(float, s.split(b";"))
    return Point(x, y)

이제 sqlite3 모듈이 데이터베이스에서 select 한 것이 실제로 Point임을 알게 해야 합니다. 이렇게 하는 두 가지 방법이 있습니다:

선언된 형을 통해 묵시적으로

열 이름을 통해 명시적으로

두 가지 방법은 섹션 모듈 함수와 상수 의 상수 PARSE_DECLTYPES 와 PARSE_COLNAMES에 대한 항목에서 설명합니다.

다음 예는 두 가지 접근법을 보여줍니다.

import sqlite3

class Point:
    def __init__(self, x, y):
        self.x, self.y = x, y

    def __repr__(self):
        return "(%f;%f)" % (self.x, self.y)

def adapt_point(point):
    return ("%f;%f" % (point.x, point.y)).encode('ascii')

def convert_point(s):
    x, y = list(map(float, s.split(b";")))
    return Point(x, y)

# Register the adapter
sqlite3.register_adapter(Point, adapt_point)

# Register the converter
sqlite3.register_converter("point", convert_point)

p = Point(4.0, -3.2)

#########################
# 1) Using declared types
con = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_DECLTYPES)
cur = con.cursor()
cur.execute("create table test(p point)")

cur.execute("insert into test(p) values (?)", (p,))
cur.execute("select p from test")
print("with declared types:", cur.fetchone()[0])
cur.close()
con.close()

#######################
# 1) Using column names
con = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_COLNAMES)
cur = con.cursor()
cur.execute("create table test(p)")

cur.execute("insert into test(p) values (?)", (p,))
cur.execute('select p as "p [point]" from test')
print("with column names:", cur.fetchone()[0])
cur.close()
con.close()

기본 어댑터와 변환기

datetime 모듈의 date와 datetime 형에 대한 기본 어댑터가 있습니다. 이것들은 ISO 날짜/ISO 타임스탬프로 SQLite로 보내집니다.

기본 변환기는 datetime.date는 “date”라는 이름으로, datetime.datetime은 “timestamp”라는 이름으로 등록됩니다.

이런 방법으로, 대부분 추가 작업 없이 파이썬의 날짜/타임스탬프를 사용할 수 있습니다. 어댑터의 형식은 실험적인 SQLite 날짜/시간 함수와도 호환됩니다.

다음 예제는 이를 보여줍니다.

import sqlite3
import datetime

con = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES)
cur = con.cursor()
cur.execute("create table test(d date, ts timestamp)")

today = datetime.date.today()
now = datetime.datetime.now()

cur.execute("insert into test(d, ts) values (?, ?)", (today, now))
cur.execute("select d, ts from test")
row = cur.fetchone()
print(today, "=>", row[0], type(row[0]))
print(now, "=>", row[1], type(row[1]))

cur.execute('select current_date as "d [date]", current_timestamp as "ts [timestamp]"')
row = cur.fetchone()
print("current_date", row[0], type(row[0]))
print("current_timestamp", row[1], type(row[1]))

con.close()

SQLite에 저장된 타임스탬프가 6자리보다 긴 소수부가 있으면, 그 값은 타임스탬프 변환기에 의해 마이크로초 정밀도로 잘립니다.

트랜잭션 제어

하부 sqlite3 라이브러리는 기본적으로 autocommit 모드로 작동하지만, 파이썬 sqlite3 모듈은 기본적으로 그렇지 않습니다.

autocommit 모드는 데이터베이스를 수정하는 명령문이 즉시 적용됨을 뜻합니다. BEGIN 이나 SAVEPOINT 문은 autocommit 모드를 비활성화하고, 가장 바깥쪽 트랜잭션을 끝내는 COMMIT, ROLLBACK 또는 RELEASE는 autocommit 모드를 다시 켭니다.

기본적으로 파이썬 sqlite3 모듈은 데이터 조작 언어(DML - Data Modification Language) 문 (즉, INSERT/UPDATE/DELETE/REPLACE) 앞에 암묵적으로 BEGIN 문을 넣습니다.

connect() 호출의 isolation_level 매개 변수를 통해, 또는 연결의 isolation_level 프로퍼티를 통해, sqlite3가 묵시적으로 실행하는 BEGIN 문의 종류를 제어할 수 있습니다. isolation_level을 지정하지 않으면, 단순한 BEGIN이 사용되며, 이는 DEFERRED를 지정하는 것과 같습니다. 가능한 다른 값은 IMMEDIATE 와 EXCLUSIVE입니다.

isolation_level를 None로 설정하여 sqlite3 모듈의 묵시적 트랜잭션 관리를 비활성화할 수 있습니다. 그러면 하부 sqlite3 라이브러리가 autocommit 모드로 작동합니다. 그런 다음 코드에서 BEGIN, ROLLBACK, SAVEPOINT 및 RELEASE 문을 명시적으로 실행하여 트랜잭션 상태를 완전히 제어할 수 있습니다.

버전 3.6에서 변경: sqlite3는 DDL 문 앞에서 열린 트랜잭션을 묵시적으로 커밋했습니다. 더는 그렇지 않습니다.

효율적으로 sqlite3 사용하기

바로 가기 메서드 사용하기

Connection 객체의 비표준 execute(), executemany() 및 executescript() 메서드를 사용하면, (종종 불필요한) Cursor 객체를 명시적으로 만들 필요가 없으므로, 코드를 더 간결하게 작성할 수 있습니다. 대신, Cursor 객체가 묵시적으로 만들어지며 이러한 바로 가기 메서드는 커서 객체를 반환합니다. 이런 방법으로, Connection 객체에 대한 단일 호출만 사용하여 SELECT 문을 실행하고 직접 이터레이트할 수 있습니다.

import sqlite3

persons = [
    ("Hugo", "Boss"),
    ("Calvin", "Klein")
    ]

con = sqlite3.connect(":memory:")

# Create the table
con.execute("create table person(firstname, lastname)")

# Fill the table
con.executemany("insert into person(firstname, lastname) values (?, ?)", persons)

# Print the table contents
for row in con.execute("select firstname, lastname from person"):
    print(row)

print("I just deleted", con.execute("delete from person").rowcount, "rows")

# close is not a shortcut method and it's not called automatically,
# so the connection object should be closed manually
con.close()

인덱스 대신 이름으로 열 액세스하기

sqlite3 모듈의 유용한 기능 중 하나는 행 팩토리로 사용하도록 설계된 내장 sqlite3.Row 클래스입니다.

이 클래스로 감싼 행은 인덱스(튜플처럼)와 대소 문자를 구분하지 않는 이름으로 액세스할 수 있습니다:

import sqlite3

con = sqlite3.connect(":memory:")
con.row_factory = sqlite3.Row

cur = con.cursor()
cur.execute("select 'John' as name, 42 as age")
for row in cur:
    assert row[0] == row["name"]
    assert row["name"] == row["nAmE"]
    assert row[1] == row["age"]
    assert row[1] == row["AgE"]

con.close()

컨텍스트 관리자로 연결 사용하기

연결 객체는 트랜잭션을 자동으로 커밋하거나 롤백하는 컨텍스트 관리자로 사용할 수 있습니다. 예외가 발생하면, 트랜잭션이 롤백 됩니다; 그렇지 않으면 트랜잭션이 커밋 됩니다:

import sqlite3

con = sqlite3.connect(":memory:")
con.execute("create table person (id integer primary key, firstname varchar unique)")

# Successful, con.commit() is called automatically afterwards
with con:
    con.execute("insert into person(firstname) values (?)", ("Joe",))

# con.rollback() is called after the with block finishes with an exception, the
# exception is still raised and must be caught
try:
    with con:
        con.execute("insert into person(firstname) values (?)", ("Joe",))
except sqlite3.IntegrityError:
    print("couldn't add Joe twice")

# Connection object used as context manager only commits or rollbacks transactions,
# so the connection object should be closed manually
con.close()

일반적인 문제

다중 스레드

이전 SQLite 버전에서는 스레드 간에 연결을 공유하는 데 문제가 있었습니다. 이것이 파이썬 모듈이 스레드 간에 연결과 커서를 공유하도록 허용하지 않는 이유입니다. 여전히 그렇게 하려고 하면 실행 시간에 예외가 발생합니다.

유일한 예외는 interrupt() 메서드를 호출하는 것입니다. 이 메서드는 다른 스레드에서 호출해야만 합니다.

각주

1(1,2)

기본적으로 sqlite3 모듈은 로드 가능한 확장을 지원하도록 빌드되지 않습니다. 일부 플랫폼(특히 맥 OS X)에는 이 기능 없이 컴파일된 SQLite 라이브러리가 있기 때문입니다. 로드 가능한 확장 지원을 받으려면, configure에 –enable-loadable-sqlite-extensions를 전달해야 합니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

데이터 지속성 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

|

데이터 압축 및 보관

이 장에서 설명하는 모듈은 zlib, gzip, bzip2 및 lzma 알고리즘을 사용한 데이터 압축과 ZIP- 및 tar- 형식 저장소 생성을 지원합니다. shutil 모듈에서 제공하는 Archiving operations도 참조하십시오.

zlib — Compression compatible with gzip

gzip — gzip 파일 지원

사용 예

bz2 — bzip2 압축 지원

파일 압축(해제)

증분 압축(해제)

일괄 압축(해제)

사용 예

lzma — Compression using the LZMA algorithm

Reading and writing compressed files

Compressing and decompressing data in memory

Miscellaneous

Specifying custom filter chains

Examples

zipfile — Work with ZIP archives

ZipFile Objects

PyZipFile Objects

ZipInfo Objects

Command-Line Interface

Command-line options

tarfile — Read and write tar archive files

TarFile Objects

TarInfo Objects

Command-Line Interface

Command-line options

Examples

Supported tar formats

Unicode issues

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

데이터 압축 및 보관 »

|

zlib — Compression compatible with gzip

For applications that require data compression, the functions in this module allow compression and decompression, using the zlib library. The zlib library has its own home page at http://www.zlib.net. There are known incompatibilities between the Python module and versions of the zlib library earlier than 1.1.3; 1.1.3 has a security vulnerability, so we recommend using 1.1.4 or later.

zlib’s functions have many options and often need to be used in a particular order. This documentation doesn’t attempt to cover all of the permutations; consult the zlib manual at http://www.zlib.net/manual.html for authoritative information.

For reading and writing .gz files see the gzip module.

The available exception and functions in this module are:

exception zlib.error

Exception raised on compression and decompression errors.

zlib.adler32(data[, value])

Computes an Adler-32 checksum of data. (An Adler-32 checksum is almost as reliable as a CRC32 but can be computed much more quickly.) The result is an unsigned 32-bit integer. If value is present, it is used as the starting value of the checksum; otherwise, a default value of 1 is used. Passing in value allows computing a running checksum over the concatenation of several inputs. The algorithm is not cryptographically strong, and should not be used for authentication or digital signatures. Since the algorithm is designed for use as a checksum algorithm, it is not suitable for use as a general hash algorithm.

버전 3.0에서 변경: Always returns an unsigned value. To generate the same numeric value across all Python versions and platforms, use adler32(data) & 0xffffffff.

zlib.compress(data, level=-1)

Compresses the bytes in data, returning a bytes object containing compressed data. level is an integer from 0 to 9 or -1 controlling the level of compression; 1 (Z_BEST_SPEED) is fastest and produces the least compression, 9 (Z_BEST_COMPRESSION) is slowest and produces the most. 0 (Z_NO_COMPRESSION) is no compression. The default value is -1 (Z_DEFAULT_COMPRESSION). Z_DEFAULT_COMPRESSION represents a default compromise between speed and compression (currently equivalent to level 6). Raises the error exception if any error occurs.

버전 3.6에서 변경: level can now be used as a keyword parameter.

zlib.compressobj(level=-1, method=DEFLATED, wbits=MAX_WBITS, memLevel=DEF_MEM_LEVEL, strategy=Z_DEFAULT_STRATEGY[, zdict])

Returns a compression object, to be used for compressing data streams that won’t fit into memory at once.

level is the compression level – an integer from 0 to 9 or -1. A value of 1 (Z_BEST_SPEED) is fastest and produces the least compression, while a value of 9 (Z_BEST_COMPRESSION) is slowest and produces the most. 0 (Z_NO_COMPRESSION) is no compression. The default value is -1 (Z_DEFAULT_COMPRESSION). Z_DEFAULT_COMPRESSION represents a default compromise between speed and compression (currently equivalent to level 6).

method is the compression algorithm. Currently, the only supported value is DEFLATED.

The wbits argument controls the size of the history buffer (or the “window size”) used when compressing data, and whether a header and trailer is included in the output. It can take several ranges of values, defaulting to 15 (MAX_WBITS):

+9 to +15: The base-two logarithm of the window size, which therefore ranges between 512 and 32768. Larger values produce better compression at the expense of greater memory usage. The resulting output will include a zlib-specific header and trailer.

−9 to −15: Uses the absolute value of wbits as the window size logarithm, while producing a raw output stream with no header or trailing checksum.

+25 to +31 = 16 + (9 to 15): Uses the low 4 bits of the value as the window size logarithm, while including a basic gzip header and trailing checksum in the output.

The memLevel argument controls the amount of memory used for the internal compression state. Valid values range from 1 to 9. Higher values use more memory, but are faster and produce smaller output.

strategy is used to tune the compression algorithm. Possible values are Z_DEFAULT_STRATEGY, Z_FILTERED, Z_HUFFMAN_ONLY, Z_RLE (zlib 1.2.0.1) and Z_FIXED (zlib 1.2.2.2).

zdict is a predefined compression dictionary. This is a sequence of bytes (such as a bytes object) containing subsequences that are expected to occur frequently in the data that is to be compressed. Those subsequences that are expected to be most common should come at the end of the dictionary.

버전 3.3에서 변경: Added the zdict parameter and keyword argument support.

zlib.crc32(data[, value])

Computes a CRC (Cyclic Redundancy Check) checksum of data. The result is an unsigned 32-bit integer. If value is present, it is used as the starting value of the checksum; otherwise, a default value of 0 is used. Passing in value allows computing a running checksum over the concatenation of several inputs. The algorithm is not cryptographically strong, and should not be used for authentication or digital signatures. Since the algorithm is designed for use as a checksum algorithm, it is not suitable for use as a general hash algorithm.

버전 3.0에서 변경: Always returns an unsigned value. To generate the same numeric value across all Python versions and platforms, use crc32(data) & 0xffffffff.

zlib.decompress(data, wbits=MAX_WBITS, bufsize=DEF_BUF_SIZE)

Decompresses the bytes in data, returning a bytes object containing the uncompressed data. The wbits parameter depends on the format of data, and is discussed further below. If bufsize is given, it is used as the initial size of the output buffer. Raises the error exception if any error occurs.

The wbits parameter controls the size of the history buffer (or “window size”), and what header and trailer format is expected. It is similar to the parameter for compressobj(), but accepts more ranges of values:

+8 to +15: The base-two logarithm of the window size. The input must include a zlib header and trailer.

0: Automatically determine the window size from the zlib header. Only supported since zlib 1.2.3.5.

−8 to −15: Uses the absolute value of wbits as the window size logarithm. The input must be a raw stream with no header or trailer.

+24 to +31 = 16 + (8 to 15): Uses the low 4 bits of the value as the window size logarithm. The input must include a gzip header and trailer.

+40 to +47 = 32 + (8 to 15): Uses the low 4 bits of the value as the window size logarithm, and automatically accepts either the zlib or gzip format.

When decompressing a stream, the window size must not be smaller than the size originally used to compress the stream; using a too-small value may result in an error exception. The default wbits value corresponds to the largest window size and requires a zlib header and trailer to be included.

bufsize is the initial size of the buffer used to hold decompressed data. If more space is required, the buffer size will be increased as needed, so you don’t have to get this value exactly right; tuning it will only save a few calls to malloc().

버전 3.6에서 변경: wbits and bufsize can be used as keyword arguments.

zlib.decompressobj(wbits=MAX_WBITS[, zdict])

Returns a decompression object, to be used for decompressing data streams that won’t fit into memory at once.

The wbits parameter controls the size of the history buffer (or the “window size”), and what header and trailer format is expected. It has the same meaning as described for decompress().

The zdict parameter specifies a predefined compression dictionary. If provided, this must be the same dictionary as was used by the compressor that produced the data that is to be decompressed.

참고

If zdict is a mutable object (such as a bytearray), you must not modify its contents between the call to decompressobj() and the first call to the decompressor’s decompress() method.

버전 3.3에서 변경: Added the zdict parameter.

Compression objects support the following methods:

Compress.compress(data)

Compress data, returning a bytes object containing compressed data for at least part of the data in data. This data should be concatenated to the output produced by any preceding calls to the compress() method. Some input may be kept in internal buffers for later processing.

Compress.flush([mode])

All pending input is processed, and a bytes object containing the remaining compressed output is returned. mode can be selected from the constants Z_NO_FLUSH, Z_PARTIAL_FLUSH, Z_SYNC_FLUSH, Z_FULL_FLUSH, Z_BLOCK (zlib 1.2.3.4), or Z_FINISH, defaulting to Z_FINISH. Except Z_FINISH, all constants allow compressing further bytestrings of data, while Z_FINISH finishes the compressed stream and prevents compressing any more data. After calling flush() with mode set to Z_FINISH, the compress() method cannot be called again; the only realistic action is to delete the object.

Compress.copy()

Returns a copy of the compression object. This can be used to efficiently compress a set of data that share a common initial prefix.

Decompression objects support the following methods and attributes:

Decompress.unused_data

A bytes object which contains any bytes past the end of the compressed data. That is, this remains b"" until the last byte that contains compression data is available. If the whole bytestring turned out to contain compressed data, this is b"", an empty bytes object.

Decompress.unconsumed_tail

A bytes object that contains any data that was not consumed by the last decompress() call because it exceeded the limit for the uncompressed data buffer. This data has not yet been seen by the zlib machinery, so you must feed it (possibly with further data concatenated to it) back to a subsequent decompress() method call in order to get correct output.

Decompress.eof

A boolean indicating whether the end of the compressed data stream has been reached.

This makes it possible to distinguish between a properly-formed compressed stream, and an incomplete or truncated one.

버전 3.3에 추가.

Decompress.decompress(data, max_length=0)

Decompress data, returning a bytes object containing the uncompressed data corresponding to at least part of the data in string. This data should be concatenated to the output produced by any preceding calls to the decompress() method. Some of the input data may be preserved in internal buffers for later processing.

If the optional parameter max_length is non-zero then the return value will be no longer than max_length. This may mean that not all of the compressed input can be processed; and unconsumed data will be stored in the attribute unconsumed_tail. This bytestring must be passed to a subsequent call to decompress() if decompression is to continue. If max_length is zero then the whole input is decompressed, and unconsumed_tail is empty.

버전 3.6에서 변경: max_length can be used as a keyword argument.

Decompress.flush([length])

All pending input is processed, and a bytes object containing the remaining uncompressed output is returned. After calling flush(), the decompress() method cannot be called again; the only realistic action is to delete the object.

The optional parameter length sets the initial size of the output buffer.

Decompress.copy()

Returns a copy of the decompression object. This can be used to save the state of the decompressor midway through the data stream in order to speed up random seeks into the stream at a future point.

Information about the version of the zlib library in use is available through the following constants:

zlib.ZLIB_VERSION

The version string of the zlib library that was used for building the module. This may be different from the zlib library actually used at runtime, which is available as ZLIB_RUNTIME_VERSION.

zlib.ZLIB_RUNTIME_VERSION

The version string of the zlib library actually loaded by the interpreter.

버전 3.3에 추가.

더 보기

Module gzip

Reading and writing gzip-format files.

http://www.zlib.net

The zlib library home page.

http://www.zlib.net/manual.html

The zlib manual explains the semantics and usage of the library’s many functions.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

데이터 압축 및 보관 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

데이터 압축 및 보관 »

|

gzip — gzip 파일 지원

소스 코드: Lib/gzip.py [https://github.com/python/cpython/tree/3.7/Lib/gzip.py]

이 모듈은 GNU 프로그램 gzip과 gunzip처럼 파일을 압축하고 압축을 푸는 간단한 인터페이스를 제공합니다.

데이터 압축은 zlib 모듈에 의해 제공됩니다.

gzip 모듈은 open(), compress() 및 decompress() 편리 함수뿐만 아니라 GzipFile 클래스도 제공합니다. GzipFile 클래스는 gzip-형식 파일을 읽고 쓰는데, 자동으로 데이터를 압축하거나 압축을 풀어서 일반적인 파일 객체처럼 보이게 합니다.

compress와 pack 프로그램에서 생성된 것과 같은, gzip과 gunzip 프로그램으로 압축을 풀 수 있는 추가 파일 형식은 이 모듈에서 지원하지 않습니다.

이 모듈은 다음 항목을 정의합니다:

gzip.open(filename, mode='rb', compresslevel=9, encoding=None, errors=None, newline=None)

바이너리나 텍스트 모드로 gzip으로 압축된 파일을 열고, 파일 객체를 반환합니다.

filename 인자는 실제 파일명(str이나 bytes 객체)이나, 읽거나 쓸 기존 파일 객체가 될 수 있습니다.

mode 인자는 바이너리 모드의 경우 'r', 'rb', 'a', 'ab', 'w', 'wb', 'x' 또는 'xb', 또는 텍스트 모드의 경우 'rt', 'at', 'wt' 또는 'xt' 중 하나일 수 있습니다. 기본값은 'rb'입니다.

compresslevel 인자는 GzipFile 생성자와 마찬가지로 0에서 9 사이의 정수입니다.

바이너리 모드의 경우, 이 함수는 GzipFile 생성자 GzipFile(filename, mode, compresslevel)와 동등합니다. 이 경우, encoding, errors 및 newline 인자를 제공하면 안 됩니다.

텍스트 모드의 경우, GzipFile 객체가 만들어지고, 지정된 인코딩, 에러 처리 동작 및 줄 종료를 갖는 io.TextIOWrapper 인스턴스로 감싸집니다.

버전 3.3에서 변경: 파일 객체인 filename 지원, 텍스트 모드 지원 및 encoding, errors 및 newline 인자가 추가되었습니다.

버전 3.4에서 변경: 'x', 'xb' 및 'xt' 모드에 대한 지원이 추가되었습니다.

버전 3.6에서 변경: 경로류 객체를 받아들입니다.

class gzip.GzipFile(filename=None, mode=None, compresslevel=9, fileobj=None, mtime=None)

truncate() 메서드를 제외하고, 대부분 파일 객체 메서드를 흉내 내는 GzipFile 클래스의 생성자입니다. fileobj와 filename 중 적어도 하나는 의미 있는 값을 부여해야 합니다.

새 클래스 인스턴스는 fileobj를 기반으로 하는데, 일반 파일, io.BytesIO 객체 또는 파일을 흉내 내는 다른 객체가 될 수 있습니다. 기본값은 None이며, 이 경우 파일 객체를 제공하기 위해 filename이 열립니다.

fileobj가 None이 아닐 때, filename 인자는 gzip 파일 헤더에 포함되는 데만 사용되며, 이 헤더에는 압축되지 않은 파일의 원래 파일명이 포함될 수 있습니다. 보고 알 수 있다면, fileobj의 파일명을 기본값으로 사용합니다; 그렇지 않으면, 기본값은 빈 문자열이며, 이 경우 원래 파일명은 헤더에 포함되지 않습니다.

mode 인자는 파일을 읽을지 쓸지에 따라 'r', 'rb', 'a', 'ab', 'w', 'wb', 'x' 또는 'xb' 중 하나일 수 있습니다. 보고 알 수 있다면, 기본값은 fileobj의 모드입니다; 그렇지 않으면, 기본값은 'rb'입니다.

파일이 항상 바이너리 모드로 열림에 유의하십시오. 텍스트 모드로 압축 파일을 열려면, open()을 사용하십시오 (또는 GzipFile을 io.TextIOWrapper로 감싸십시오).

compresslevel 인자는 압축 수준을 제어하는 0에서 9까지의 정수입니다; 1은 가장 빠르고 압축률이 가장 낮으며, 9는 가장 느리고 압축률이 가장 높습니다. 0은 압축하지 않습니다. 기본값은 9입니다.

mtime 인자는 압축할 때 스트림의 마지막 수정 시간 필드에 기록되는 선택적 숫자 타임스탬프입니다. 압축 모드에서만 제공해야 합니다. 생략되거나 None이면, 현재 시각이 사용됩니다. 자세한 내용은 mtime 어트리뷰트를 참조하십시오.

GzipFile 객체의 close() 메서드를 호출해도 fileobj를 닫지 않습니다, 압축된 데이터 뒤에 뭔가 추가하기를 원할 수 있기 때문입니다. 또한, 이는 fileobj로 쓰기 위해 열린 io.BytesIO 객체를 전달하고, io.BytesIO 객체의 getvalue() 메서드를 사용하여 결과 메모리 버퍼를 얻을 수 있도록 합니다.

GzipFile은 이터레이션과 with 문을 포함하여 io.BufferedIOBase 인터페이스를 지원합니다. truncate() 메서드 만 구현되지 않습니다.

GzipFile은 다음 메서드와 어트리뷰트도 제공합니다:

peek(n)

파일 위치를 전진시키지 않고 압축되지 않은 n 바이트를 읽습니다. 호출을 만족시키기 위해 압축된 스트림에 대해 최대 한 번의 읽기가 수행됩니다. 반환된 바이트 수는 요청한 것보다 많거나 적을 수 있습니다.

참고

peek()를 호출할 때 GzipFile의 파일 위치가 변경되지는 않지만, 하부 파일 객체의 위치는 변경될 수 있습니다 (예를 들어, GzipFile이 fileobj 매개 변수로 생성된 경우).

버전 3.2에 추가.

mtime

압축을 풀 때, 가장 최근에 읽은 헤더의 마지막 수정 시간 필드의 값을 이 어트리뷰트에서 정수로 읽을 수 있습니다. 헤더를 읽기 전의 초깃값은 None입니다.

모든 gzip 압축 스트림에는 이 타임스탬프 필드가 있어야 합니다. gunzip과 같은 일부 프로그램은 타임스탬프를 사용합니다. 형식은 time.time()의 반환 값과 os.stat()에 의해 반환된 객체의 st_mtime 어트리뷰트와 같습니다.

버전 3.1에서 변경: mtime 생성자 인자와 mtime 어트리뷰트와 함께 with 문에 대한 지원이 추가되었습니다.

버전 3.2에서 변경: 제로 패딩(zero-padded)된 파일과 위치 변경할 수 없는(unseekable) 파일에 대한 지원이 추가되었습니다.

버전 3.3에서 변경: io.BufferedIOBase.read1() 메서드가 이제 구현됩니다.

버전 3.4에서 변경: 'x' 및 'xb' 모드에 대한 지원이 추가되었습니다.

버전 3.5에서 변경: 임의의 바이트열류 객체를 쓰는 지원이 추가되었습니다. 이제 read() 메서드는 None 인자를 받아들입니다.

버전 3.6에서 변경: 경로류 객체를 받아들입니다.

gzip.compress(data, compresslevel=9)

data를 압축하여, 압축된 데이터가 포함된 bytes 객체를 반환합니다. compresslevel은 위의 GzipFile 생성자와 같은 의미입니다.

버전 3.2에 추가.

gzip.decompress(data)

data의 압축을 풀어서, 압축되지 않은 데이터가 포함된 bytes 객체를 반환합니다.

버전 3.2에 추가.

사용 예

압축된 파일을 읽는 방법의 예:

import gzip
with gzip.open('/home/joe/file.txt.gz', 'rb') as f:
    file_content = f.read()

압축된 GZIP 파일을 만드는 방법의 예:

import gzip
content = b"Lots of content here"
with gzip.open('/home/joe/file.txt.gz', 'wb') as f:
    f.write(content)

기존 파일을 GZIP 압축하는 방법의 예:

import gzip
import shutil
with open('/home/joe/file.txt', 'rb') as f_in:
    with gzip.open('/home/joe/file.txt.gz', 'wb') as f_out:
        shutil.copyfileobj(f_in, f_out)

바이너리 문자열을 GZIP 압축하는 방법의 예:

import gzip
s_in = b"Lots of content here"
s_out = gzip.compress(s_in)

더 보기

모듈 zlib

gzip 파일 형식을 지원하는 데 필요한 기본 데이터 압축 모듈.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

데이터 압축 및 보관 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

데이터 압축 및 보관 »

|

bz2 — bzip2 압축 지원

소스 코드: Lib/bz2.py [https://github.com/python/cpython/tree/3.7/Lib/bz2.py]

이 모듈은 bzip2 압축 알고리즘을 사용하여 데이터 압축과 압축 해제를 위한 포괄적인 인터페이스를 제공합니다.

bz2 모듈에는 다음이 포함됩니다:

압축된 파일을 읽고 쓰기 위한 open() 함수와 BZ2File 클래스.

증분 압축(해제)을 위한 BZ2Compressor와 BZ2Decompressor 클래스.

일괄 압축(해제)을 위한 compress()와 decompress() 함수.

이 모듈의 모든 클래스는 다중 스레드에서 안전하게 액세스할 수 있습니다.

파일 압축(해제)

bz2.open(filename, mode='r', compresslevel=9, encoding=None, errors=None, newline=None)

바이너리나 텍스트 모드로 bzip2 압축된 파일을 열고, 파일 객체를 반환합니다.

BZ2File의 생성자와 마찬가지로, filename 인자는 실제 파일명(str이나 bytes 객체)이거나, 읽거나 쓸 기존 파일 객체가 될 수 있습니다.

mode 인자는 바이너리 모드의 경우 'r', 'rb', 'w', 'wb', 'x', 'xb', 'a' 또는 'ab', 또는 텍스트 모드의 경우 'rt', 'wt', 'xt' 또는 'at' 중 하나일 수 있습니다. 기본값은 'rb'입니다.

compresslevel 인자는 BZ2File 생성자와 마찬가지로 1에서 9 사이의 정수입니다.

바이너리 모드의 경우, 이 함수는 BZ2File 생성자 BZ2File(filename, mode, compresslevel=compresslevel)와 동등합니다. 이 경우, encoding, errors 및 newline 인자를 제공하면 안 됩니다.

텍스트 모드의 경우, BZ2File 객체가 만들어지고, 지정된 인코딩, 에러 처리 동작 및 줄 종료를 갖는 io.TextIOWrapper 인스턴스로 감싸집니다.

버전 3.3에 추가.

버전 3.4에서 변경: 'x' (배타적 생성) 모드가 추가되었습니다.

버전 3.6에서 변경: 경로류 객체를 받아들입니다.

class bz2.BZ2File(filename, mode='r', buffering=None, compresslevel=9)

바이너리 모드로 bzip2 압축된 파일을 엽니다.

filename이 str이나 bytes 객체면, 명명된 파일을 직접 엽니다. 그렇지 않으면, filename은 파일 객체 여야 하며, 압축된 데이터를 읽거나 쓰는 데 사용됩니다.

mode 인자는 읽기를 위한 'r' (기본값), 덮어쓰기를 위한 'w', 배타적 생성을 위한 'x' 또는 덧붙이기를 위한 'a' 중 하나일 수 있습니다. 이들은 각각 'rb', 'wb', 'xb' 및 'ab'로 주어지는 것과 동등합니다.

filename이 (실제 파일 이름 대신) 파일 객체면, 'w' 모드는 파일을 자르지 않으며, 대신 'a'와 동등합니다.

buffering 인자는 무시됩니다. 이것의 사용은 폐지되었습니다.

mode가 'w'나 'a'이면, compresslevel은 압축 수준을 지정하는 1과 9 사이의 정수일 수 있습니다: 1은 압축률이 가장 낮고, 9(기본값)는 압축률이 가장 높습니다.

mode가 'r'이면, 입력 파일은 여러 개의 압축된 스트림을 이어 붙인 것일 수 있습니다.

BZ2File은 detach()와 truncate()를 제외하고, io.BufferedIOBase가 지정하는 모든 멤버를 제공합니다. 이터레이션과 with 문이 지원됩니다.

BZ2File는 다음 메서드도 제공합니다:

peek([n])

파일 위치를 전진시키지 않고 버퍼링 된 데이터를 반환합니다. (EOF에 있지 않은 한) 적어도 1바이트의 데이터가 반환됩니다. 반환되는 정확한 바이트 수는 지정되지 않습니다.

참고

peek()를 호출할 때 BZ2File의 파일 위치가 변경되지는 않지만, 하부 파일 객체의 위치는 변경될 수 있습니다 (예를 들어, BZ2File이 filename에 파일 객체를 전달하여 생성된 경우).

버전 3.3에 추가.

버전 3.1에서 변경: with 문에 대한 지원이 추가되었습니다.

버전 3.3에서 변경: fileno(), readable(), seekable(), writable(), read1() 및 readinto() 메서드가 추가되었습니다.

버전 3.3에서 변경: 실제 파일명 대신 파일 객체 인 filename에 대한 지원이 추가되었습니다.

버전 3.3에서 변경: 다중 스트림 파일 읽기 지원과 함께, 'a' (덧붙이기) 모드가 추가되었습니다.

버전 3.4에서 변경: 'x' (배타적 생성) 모드가 추가되었습니다.

버전 3.5에서 변경: read() 메서드는 이제 None 인자를 받아들입니다.

버전 3.6에서 변경: 경로류 객체를 받아들입니다.

증분 압축(해제)

class bz2.BZ2Compressor(compresslevel=9)

새로운 압축기 객체를 만듭니다. 이 객체는 증분 적으로(incrementally) 데이터를 압축하는 데 사용될 수 있습니다. 일괄(one-shot) 압축에는, 대신 compress() 함수를 사용하십시오.

주어진다면, compresslevel은 1과 9 사이의 정수여야 합니다. 기본값은 9입니다.

compress(data)

압축기 객체에 데이터를 제공합니다. 가능하면 압축된 데이터 청크를 반환하고, 그렇지 않으면 빈 바이트열을 반환합니다.

압축기에 데이터 제공이 끝나면, flush() 메서드를 호출하여 압축 공정을 마무리하십시오.

flush()

압축 공정을 마칩니다. 내부 버퍼에 남아있는 압축된 데이터를 반환합니다.

이 메서드가 호출된 후에는, 압축기 객체를 사용할 수 없습니다.

class bz2.BZ2Decompressor

새로운 압축 해제기 객체를 만듭니다. 이 객체는 데이터를 증분 적으로 압축 해제하는 데 사용될 수 있습니다. 일괄 압축에는, 대신 decompress() 함수를 사용하십시오.

참고

이 클래스는 decompress()와 BZ2File과 달리 다중 압축 스트림을 포함하는 입력을 투명하게 처리하지 않습니다. BZ2Decompressor로 다중 스트림 입력의 압축을 풀어야 한다면, 각 스트림 마다 새 압축 해제기를 사용해야 합니다.

decompress(data, max_length=-1)

data(바이트열류 객체)의 압축을 풀고, 압축되지 않은 데이터를 바이트열로 반환합니다. 일부 data는 나중에 decompress()를 호출할 때 사용할 수 있도록 내부에 버퍼링 됩니다. 반환된 데이터는 decompress()에 대한 이전 호출의 출력에 이어붙여야 합니다.

max_length가 음수가 아니면, 최대 max_length 바이트의 압축 해제된 데이터를 반환합니다. 이 제한에 도달했고, 추가 출력을 생성할 수 없으면, needs_input 어트리뷰트는 False로 설정됩니다. 이때, decompress()에 대한 다음 호출은 출력을 더 얻기 위해 data를 b''로 제공할 수 있습니다.

입력 데이터가 모두 압축 해제되고 반환되었으면 (max_length 바이트 미만이거나 max_length가 음수라서), needs_input 어트리뷰트가 True로 설정됩니다.

스트림의 끝에 도달한 이후에 데이터의 압축을 풀려고 하면, EOFError가 발생합니다. 스트림의 끝 이후에 발견된 모든 데이터는 무시되고, unused_data 어트리뷰트에 저장됩니다.

버전 3.5에서 변경: max_length 매개 변수가 추가되었습니다.

eof

스트림의 끝(end-of-stream) 마커에 도달했으면 True.

버전 3.3에 추가.

unused_data

압축된 스트림의 끝 이후에 발견된 데이터.

스트림의 끝에 도달하기 전에 이 어트리뷰트를 액세스하면, 값은 b''가 됩니다.

needs_input

decompress() 메서드가 새로운 압축된 입력을 요구하기 전에 압축 해제된 데이터를 더 제공할 수 있으면 False.

버전 3.5에 추가.

일괄 압축(해제)

bz2.compress(data, compresslevel=9)

비이트열류 객체, data를 압축합니다.

주어진다면, compresslevel은 1과 9 사이의 정수여야 합니다. 기본값은 9입니다.

증분 압축에는, 대신 BZ2Compressor를 사용하십시오.

bz2.decompress(data)

비이트열류 객체, data를 압축 해제합니다.

data가 다중 압축 스트림을 이어붙인 것이면, 모든 스트림의 압축을 풉니다.

증분 압축 해제에는, 대신 BZ2Decompressor를 사용하십시오.

버전 3.3에서 변경: 다중 스트림 입력에 대한 지원이 추가되었습니다.

사용 예

다음은 bz2 모듈의 일반적인 사용법에 대한 몇 가지 예입니다.

왕복 압축을 시연하기 위해 compress()와 decompress() 사용하기:

>>> import bz2

>>> data = b"""\
... Donec rhoncus quis sapien sit amet molestie. Fusce scelerisque vel augue
... nec ullamcorper. Nam rutrum pretium placerat. Aliquam vel tristique lorem,
... sit amet cursus ante. In interdum laoreet mi, sit amet ultrices purus
... pulvinar a. Nam gravida euismod magna, non varius justo tincidunt feugiat.
... Aliquam pharetra lacus non risus vehicula rutrum. Maecenas aliquam leo
... felis. Pellentesque semper nunc sit amet nibh ullamcorper, ac elementum
... dolor luctus. Curabitur lacinia mi ornare consectetur vestibulum."""

>>> c = bz2.compress(data)
>>> len(data) / len(c)  # Data compression ratio
1.513595166163142

>>> d = bz2.decompress(c)
>>> data == d  # Check equality to original object after round-trip
True

증분 압축을 위한 BZ2Compressor 사용하기:

>>> import bz2

>>> def gen_data(chunks=10, chunksize=1000):
...     """Yield incremental blocks of chunksize bytes."""
...     for _ in range(chunks):
...         yield b"z" * chunksize
...
>>> comp = bz2.BZ2Compressor()
>>> out = b""
>>> for chunk in gen_data():
...     # Provide data to the compressor object
...     out = out + comp.compress(chunk)
...
>>> # Finish the compression process.  Call this once you have
>>> # finished providing data to the compressor.
>>> out = out + comp.flush()

위의 예제는 매우 “무작위적이지 않은” 데이터 스트림(b”z” 청크의 스트림)을 사용합니다. 무작위 데이터는 압축이 잘되지 않지만, 반복적인 데이터는 일반적으로 높은 압축률을 산출합니다.

바이너리 모드로 bzip2 압축된 파일을 쓰고 읽기:

>>> import bz2

>>> data = b"""\
... Donec rhoncus quis sapien sit amet molestie. Fusce scelerisque vel augue
... nec ullamcorper. Nam rutrum pretium placerat. Aliquam vel tristique lorem,
... sit amet cursus ante. In interdum laoreet mi, sit amet ultrices purus
... pulvinar a. Nam gravida euismod magna, non varius justo tincidunt feugiat.
... Aliquam pharetra lacus non risus vehicula rutrum. Maecenas aliquam leo
... felis. Pellentesque semper nunc sit amet nibh ullamcorper, ac elementum
... dolor luctus. Curabitur lacinia mi ornare consectetur vestibulum."""

>>> with bz2.open("myfile.bz2", "wb") as f:
...     # Write compressed data to file
...     unused = f.write(data)

>>> with bz2.open("myfile.bz2", "rb") as f:
...     # Decompress data from file
...     content = f.read()

>>> content == data  # Check equality to original object after round-trip
True

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

데이터 압축 및 보관 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

데이터 압축 및 보관 »

|

lzma — Compression using the LZMA algorithm

버전 3.3에 추가.

Source code: Lib/lzma.py [https://github.com/python/cpython/tree/3.7/Lib/lzma.py]

This module provides classes and convenience functions for compressing and decompressing data using the LZMA compression algorithm. Also included is a file interface supporting the .xz and legacy .lzma file formats used by the xz utility, as well as raw compressed streams.

The interface provided by this module is very similar to that of the bz2 module. However, note that LZMAFile is not thread-safe, unlike bz2.BZ2File, so if you need to use a single LZMAFile instance from multiple threads, it is necessary to protect it with a lock.

exception lzma.LZMAError

This exception is raised when an error occurs during compression or decompression, or while initializing the compressor/decompressor state.

Reading and writing compressed files

lzma.open(filename, mode="rb", *, format=None, check=-1, preset=None, filters=None, encoding=None, errors=None, newline=None)

Open an LZMA-compressed file in binary or text mode, returning a file object.

The filename argument can be either an actual file name (given as a str, bytes or path-like object), in which case the named file is opened, or it can be an existing file object to read from or write to.

The mode argument can be any of "r", "rb", "w", "wb", "x", "xb", "a" or "ab" for binary mode, or "rt", "wt", "xt", or "at" for text mode. The default is "rb".

When opening a file for reading, the format and filters arguments have the same meanings as for LZMADecompressor. In this case, the check and preset arguments should not be used.

When opening a file for writing, the format, check, preset and filters arguments have the same meanings as for LZMACompressor.

For binary mode, this function is equivalent to the LZMAFile constructor: LZMAFile(filename, mode, ...). In this case, the encoding, errors and newline arguments must not be provided.

For text mode, a LZMAFile object is created, and wrapped in an io.TextIOWrapper instance with the specified encoding, error handling behavior, and line ending(s).

버전 3.4에서 변경: Added support for the "x", "xb" and "xt" modes.

버전 3.6에서 변경: Accepts a path-like object.

class lzma.LZMAFile(filename=None, mode="r", *, format=None, check=-1, preset=None, filters=None)

Open an LZMA-compressed file in binary mode.

An LZMAFile can wrap an already-open file object, or operate directly on a named file. The filename argument specifies either the file object to wrap, or the name of the file to open (as a str, bytes or path-like object). When wrapping an existing file object, the wrapped file will not be closed when the LZMAFile is closed.

The mode argument can be either "r" for reading (default), "w" for overwriting, "x" for exclusive creation, or "a" for appending. These can equivalently be given as "rb", "wb", "xb" and "ab" respectively.

If filename is a file object (rather than an actual file name), a mode of "w" does not truncate the file, and is instead equivalent to "a".

When opening a file for reading, the input file may be the concatenation of multiple separate compressed streams. These are transparently decoded as a single logical stream.

When opening a file for reading, the format and filters arguments have the same meanings as for LZMADecompressor. In this case, the check and preset arguments should not be used.

When opening a file for writing, the format, check, preset and filters arguments have the same meanings as for LZMACompressor.

LZMAFile supports all the members specified by io.BufferedIOBase, except for detach() and truncate(). Iteration and the with statement are supported.

The following method is also provided:

peek(size=-1)

Return buffered data without advancing the file position. At least one byte of data will be returned, unless EOF has been reached. The exact number of bytes returned is unspecified (the size argument is ignored).

참고

While calling peek() does not change the file position of the LZMAFile, it may change the position of the underlying file object (e.g. if the LZMAFile was constructed by passing a file object for filename).

버전 3.4에서 변경: Added support for the "x" and "xb" modes.

버전 3.5에서 변경: The read() method now accepts an argument of None.

버전 3.6에서 변경: Accepts a path-like object.

Compressing and decompressing data in memory

class lzma.LZMACompressor(format=FORMAT_XZ, check=-1, preset=None, filters=None)

Create a compressor object, which can be used to compress data incrementally.

For a more convenient way of compressing a single chunk of data, see compress().

The format argument specifies what container format should be used. Possible values are:

FORMAT_XZ: The .xz container format.

This is the default format.

FORMAT_ALONE: The legacy .lzma container format.

This format is more limited than .xz – it does not support integrity checks or multiple filters.

FORMAT_RAW: A raw data stream, not using any container format.

This format specifier does not support integrity checks, and requires that you always specify a custom filter chain (for both compression and decompression). Additionally, data compressed in this manner cannot be decompressed using FORMAT_AUTO (see LZMADecompressor).

The check argument specifies the type of integrity check to include in the compressed data. This check is used when decompressing, to ensure that the data has not been corrupted. Possible values are:

CHECK_NONE: No integrity check. This is the default (and the only acceptable value) for FORMAT_ALONE and FORMAT_RAW.

CHECK_CRC32: 32-bit Cyclic Redundancy Check.

CHECK_CRC64: 64-bit Cyclic Redundancy Check. This is the default for FORMAT_XZ.

CHECK_SHA256: 256-bit Secure Hash Algorithm.

If the specified check is not supported, an LZMAError is raised.

The compression settings can be specified either as a preset compression level (with the preset argument), or in detail as a custom filter chain (with the filters argument).

The preset argument (if provided) should be an integer between 0 and 9 (inclusive), optionally OR-ed with the constant PRESET_EXTREME. If neither preset nor filters are given, the default behavior is to use PRESET_DEFAULT (preset level 6). Higher presets produce smaller output, but make the compression process slower.

참고

In addition to being more CPU-intensive, compression with higher presets also requires much more memory (and produces output that needs more memory to decompress). With preset 9 for example, the overhead for an LZMACompressor object can be as high as 800 MiB. For this reason, it is generally best to stick with the default preset.

The filters argument (if provided) should be a filter chain specifier. See Specifying custom filter chains for details.

compress(data)

Compress data (a bytes object), returning a bytes object containing compressed data for at least part of the input. Some of data may be buffered internally, for use in later calls to compress() and flush(). The returned data should be concatenated with the output of any previous calls to compress().

flush()

Finish the compression process, returning a bytes object containing any data stored in the compressor’s internal buffers.

The compressor cannot be used after this method has been called.

class lzma.LZMADecompressor(format=FORMAT_AUTO, memlimit=None, filters=None)

Create a decompressor object, which can be used to decompress data incrementally.

For a more convenient way of decompressing an entire compressed stream at once, see decompress().

The format argument specifies the container format that should be used. The default is FORMAT_AUTO, which can decompress both .xz and .lzma files. Other possible values are FORMAT_XZ, FORMAT_ALONE, and FORMAT_RAW.

The memlimit argument specifies a limit (in bytes) on the amount of memory that the decompressor can use. When this argument is used, decompression will fail with an LZMAError if it is not possible to decompress the input within the given memory limit.

The filters argument specifies the filter chain that was used to create the stream being decompressed. This argument is required if format is FORMAT_RAW, but should not be used for other formats. See Specifying custom filter chains for more information about filter chains.

참고

This class does not transparently handle inputs containing multiple compressed streams, unlike decompress() and LZMAFile. To decompress a multi-stream input with LZMADecompressor, you must create a new decompressor for each stream.

decompress(data, max_length=-1)

Decompress data (a bytes-like object), returning uncompressed data as bytes. Some of data may be buffered internally, for use in later calls to decompress(). The returned data should be concatenated with the output of any previous calls to decompress().

If max_length is nonnegative, returns at most max_length bytes of decompressed data. If this limit is reached and further output can be produced, the needs_input attribute will be set to False. In this case, the next call to decompress() may provide data as b'' to obtain more of the output.

If all of the input data was decompressed and returned (either because this was less than max_length bytes, or because max_length was negative), the needs_input attribute will be set to True.

Attempting to decompress data after the end of stream is reached raises an EOFError. Any data found after the end of the stream is ignored and saved in the unused_data attribute.

버전 3.5에서 변경: Added the max_length parameter.

check

The ID of the integrity check used by the input stream. This may be CHECK_UNKNOWN until enough of the input has been decoded to determine what integrity check it uses.

eof

True if the end-of-stream marker has been reached.

unused_data

Data found after the end of the compressed stream.

Before the end of the stream is reached, this will be b"".

needs_input

False if the decompress() method can provide more decompressed data before requiring new uncompressed input.

버전 3.5에 추가.

lzma.compress(data, format=FORMAT_XZ, check=-1, preset=None, filters=None)

Compress data (a bytes object), returning the compressed data as a bytes object.

See LZMACompressor above for a description of the format, check, preset and filters arguments.

lzma.decompress(data, format=FORMAT_AUTO, memlimit=None, filters=None)

Decompress data (a bytes object), returning the uncompressed data as a bytes object.

If data is the concatenation of multiple distinct compressed streams, decompress all of these streams, and return the concatenation of the results.

See LZMADecompressor above for a description of the format, memlimit and filters arguments.

Miscellaneous

lzma.is_check_supported(check)

Return True if the given integrity check is supported on this system.

CHECK_NONE and CHECK_CRC32 are always supported. CHECK_CRC64 and CHECK_SHA256 may be unavailable if you are using a version of liblzma that was compiled with a limited feature set.

Specifying custom filter chains

A filter chain specifier is a sequence of dictionaries, where each dictionary contains the ID and options for a single filter. Each dictionary must contain the key "id", and may contain additional keys to specify filter-dependent options. Valid filter IDs are as follows:

Compression filters:

FILTER_LZMA1 (for use with FORMAT_ALONE)

FILTER_LZMA2 (for use with FORMAT_XZ and FORMAT_RAW)

Delta filter:

FILTER_DELTA

Branch-Call-Jump (BCJ) filters:

FILTER_X86

FILTER_IA64

FILTER_ARM

FILTER_ARMTHUMB

FILTER_POWERPC

FILTER_SPARC

A filter chain can consist of up to 4 filters, and cannot be empty. The last filter in the chain must be a compression filter, and any other filters must be delta or BCJ filters.

Compression filters support the following options (specified as additional entries in the dictionary representing the filter):

preset: A compression preset to use as a source of default values for options that are not specified explicitly.

dict_size: Dictionary size in bytes. This should be between 4 KiB and 1.5 GiB (inclusive).

lc: Number of literal context bits.

lp: Number of literal position bits. The sum lc + lp must be at most 4.

pb: Number of position bits; must be at most 4.

mode: MODE_FAST or MODE_NORMAL.

nice_len: What should be considered a “nice length” for a match. This should be 273 or less.

mf: What match finder to use – MF_HC3, MF_HC4, MF_BT2, MF_BT3, or MF_BT4.

depth: Maximum search depth used by match finder. 0 (default) means to select automatically based on other filter options.

The delta filter stores the differences between bytes, producing more repetitive input for the compressor in certain circumstances. It supports one option, dist. This indicates the distance between bytes to be subtracted. The default is 1, i.e. take the differences between adjacent bytes.

The BCJ filters are intended to be applied to machine code. They convert relative branches, calls and jumps in the code to use absolute addressing, with the aim of increasing the redundancy that can be exploited by the compressor. These filters support one option, start_offset. This specifies the address that should be mapped to the beginning of the input data. The default is 0.

Examples

Reading in a compressed file:

import lzma
with lzma.open("file.xz") as f:
    file_content = f.read()

Creating a compressed file:

import lzma
data = b"Insert Data Here"
with lzma.open("file.xz", "w") as f:
    f.write(data)

Compressing data in memory:

import lzma
data_in = b"Insert Data Here"
data_out = lzma.compress(data_in)

Incremental compression:

import lzma
lzc = lzma.LZMACompressor()
out1 = lzc.compress(b"Some data\n")
out2 = lzc.compress(b"Another piece of data\n")
out3 = lzc.compress(b"Even more data\n")
out4 = lzc.flush()
# Concatenate all the partial results:
result = b"".join([out1, out2, out3, out4])

Writing compressed data to an already-open file:

import lzma
with open("file.xz", "wb") as f:
    f.write(b"This data will not be compressed\n")
    with lzma.open(f, "w") as lzf:
        lzf.write(b"This *will* be compressed\n")
    f.write(b"Not compressed\n")

Creating a compressed file using a custom filter chain:

import lzma
my_filters = [
    {"id": lzma.FILTER_DELTA, "dist": 5},
    {"id": lzma.FILTER_LZMA2, "preset": 7 | lzma.PRESET_EXTREME},
]
with lzma.open("file.xz", "w", filters=my_filters) as f:
    f.write(b"blah blah blah")

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

데이터 압축 및 보관 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

데이터 압축 및 보관 »

|

zipfile — Work with ZIP archives

Source code: Lib/zipfile.py [https://github.com/python/cpython/tree/3.7/Lib/zipfile.py]

The ZIP file format is a common archive and compression standard. This module provides tools to create, read, write, append, and list a ZIP file. Any advanced use of this module will require an understanding of the format, as defined in PKZIP Application Note [https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT].

This module does not currently handle multi-disk ZIP files. It can handle ZIP files that use the ZIP64 extensions (that is ZIP files that are more than 4 GiB in size). It supports decryption of encrypted files in ZIP archives, but it currently cannot create an encrypted file. Decryption is extremely slow as it is implemented in native Python rather than C.

The module defines the following items:

exception zipfile.BadZipFile

The error raised for bad ZIP files.

버전 3.2에 추가.

exception zipfile.BadZipfile

Alias of BadZipFile, for compatibility with older Python versions.

버전 3.2부터 폐지.

exception zipfile.LargeZipFile

The error raised when a ZIP file would require ZIP64 functionality but that has not been enabled.

class zipfile.ZipFile

The class for reading and writing ZIP files. See section ZipFile Objects for constructor details.

class zipfile.PyZipFile

Class for creating ZIP archives containing Python libraries.

class zipfile.ZipInfo(filename='NoName', date_time=(1980, 1, 1, 0, 0, 0))

Class used to represent information about a member of an archive. Instances of this class are returned by the getinfo() and infolist() methods of ZipFile objects. Most users of the zipfile module will not need to create these, but only use those created by this module. filename should be the full name of the archive member, and date_time should be a tuple containing six fields which describe the time of the last modification to the file; the fields are described in section ZipInfo Objects.

zipfile.is_zipfile(filename)

Returns True if filename is a valid ZIP file based on its magic number, otherwise returns False. filename may be a file or file-like object too.

버전 3.1에서 변경: Support for file and file-like objects.

zipfile.ZIP_STORED

The numeric constant for an uncompressed archive member.

zipfile.ZIP_DEFLATED

The numeric constant for the usual ZIP compression method. This requires the zlib module.

zipfile.ZIP_BZIP2

The numeric constant for the BZIP2 compression method. This requires the bz2 module.

버전 3.3에 추가.

zipfile.ZIP_LZMA

The numeric constant for the LZMA compression method. This requires the lzma module.

버전 3.3에 추가.

참고

The ZIP file format specification has included support for bzip2 compression since 2001, and for LZMA compression since 2006. However, some tools (including older Python releases) do not support these compression methods, and may either refuse to process the ZIP file altogether, or fail to extract individual files.

더 보기

PKZIP Application Note [https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT]

Documentation on the ZIP file format by Phil Katz, the creator of the format and algorithms used.

Info-ZIP Home Page [http://www.info-zip.org/]

Information about the Info-ZIP project’s ZIP archive programs and development libraries.

ZipFile Objects

class zipfile.ZipFile(file, mode='r', compression=ZIP_STORED, allowZip64=True, compresslevel=None)

Open a ZIP file, where file can be a path to a file (a string), a file-like object or a path-like object.

The mode parameter should be 'r' to read an existing file, 'w' to truncate and write a new file, 'a' to append to an existing file, or 'x' to exclusively create and write a new file. If mode is 'x' and file refers to an existing file, a FileExistsError will be raised. If mode is 'a' and file refers to an existing ZIP file, then additional files are added to it. If file does not refer to a ZIP file, then a new ZIP archive is appended to the file. This is meant for adding a ZIP archive to another file (such as python.exe). If mode is 'a' and the file does not exist at all, it is created. If mode is 'r' or 'a', the file should be seekable.

compression is the ZIP compression method to use when writing the archive, and should be ZIP_STORED, ZIP_DEFLATED, ZIP_BZIP2 or ZIP_LZMA; unrecognized values will cause NotImplementedError to be raised. If ZIP_DEFLATED, ZIP_BZIP2 or ZIP_LZMA is specified but the corresponding module (zlib, bz2 or lzma) is not available, RuntimeError is raised. The default is ZIP_STORED.

If allowZip64 is True (the default) zipfile will create ZIP files that use the ZIP64 extensions when the zipfile is larger than 4 GiB. If it is false zipfile will raise an exception when the ZIP file would require ZIP64 extensions.

The compresslevel parameter controls the compression level to use when writing files to the archive. When using ZIP_STORED or ZIP_LZMA it has no effect. When using ZIP_DEFLATED integers 0 through 9 are accepted (see zlib for more information). When using ZIP_BZIP2 integers 1 through 9 are accepted (see bz2 for more information).

If the file is created with mode 'w', 'x' or 'a' and then closed without adding any files to the archive, the appropriate ZIP structures for an empty archive will be written to the file.

ZipFile is also a context manager and therefore supports the with statement. In the example, myzip is closed after the with statement’s suite is finished—even if an exception occurs:

with ZipFile('spam.zip', 'w') as myzip:
    myzip.write('eggs.txt')

버전 3.2에 추가: Added the ability to use ZipFile as a context manager.

버전 3.3에서 변경: Added support for bzip2 and lzma compression.

버전 3.4에서 변경: ZIP64 extensions are enabled by default.

버전 3.5에서 변경: Added support for writing to unseekable streams. Added support for the 'x' mode.

버전 3.6에서 변경: Previously, a plain RuntimeError was raised for unrecognized compression values.

버전 3.6.2에서 변경: The file parameter accepts a path-like object.

버전 3.7에서 변경: Add the compresslevel parameter.

ZipFile.close()

Close the archive file. You must call close() before exiting your program or essential records will not be written.

ZipFile.getinfo(name)

Return a ZipInfo object with information about the archive member name. Calling getinfo() for a name not currently contained in the archive will raise a KeyError.

ZipFile.infolist()

Return a list containing a ZipInfo object for each member of the archive. The objects are in the same order as their entries in the actual ZIP file on disk if an existing archive was opened.

ZipFile.namelist()

Return a list of archive members by name.

ZipFile.open(name, mode='r', pwd=None, *, force_zip64=False)

Access a member of the archive as a binary file-like object. name can be either the name of a file within the archive or a ZipInfo object. The mode parameter, if included, must be 'r' (the default) or 'w'. pwd is the password used to decrypt encrypted ZIP files.

open() is also a context manager and therefore supports the with statement:

with ZipFile('spam.zip') as myzip:
    with myzip.open('eggs.txt') as myfile:
        print(myfile.read())

With mode 'r' the file-like object (ZipExtFile) is read-only and provides the following methods: read(), readline(), readlines(), seek(), tell(), __iter__(), __next__(). These objects can operate independently of the ZipFile.

With mode='w', a writable file handle is returned, which supports the write() method. While a writable file handle is open, attempting to read or write other files in the ZIP file will raise a ValueError.

When writing a file, if the file size is not known in advance but may exceed 2 GiB, pass force_zip64=True to ensure that the header format is capable of supporting large files. If the file size is known in advance, construct a ZipInfo object with file_size set, and use that as the name parameter.

참고

The open(), read() and extract() methods can take a filename or a ZipInfo object. You will appreciate this when trying to read a ZIP file that contains members with duplicate names.

버전 3.6에서 변경: Removed support of mode='U'. Use io.TextIOWrapper for reading compressed text files in universal newlines mode.

버전 3.6에서 변경: open() can now be used to write files into the archive with the mode='w' option.

버전 3.6에서 변경: Calling open() on a closed ZipFile will raise a ValueError. Previously, a RuntimeError was raised.

ZipFile.extract(member, path=None, pwd=None)

Extract a member from the archive to the current working directory; member must be its full name or a ZipInfo object. Its file information is extracted as accurately as possible. path specifies a different directory to extract to. member can be a filename or a ZipInfo object. pwd is the password used for encrypted files.

Returns the normalized path created (a directory or new file).

참고

If a member filename is an absolute path, a drive/UNC sharepoint and leading (back)slashes will be stripped, e.g.: ///foo/bar becomes foo/bar on Unix, and C:\foo\bar becomes foo\bar on Windows. And all ".." components in a member filename will be removed, e.g.: ../../foo../../ba..r becomes foo../ba..r. On Windows illegal characters (:, <, >, |, ", ?, and *) replaced by underscore (_).

버전 3.6에서 변경: Calling extract() on a closed ZipFile will raise a ValueError. Previously, a RuntimeError was raised.

버전 3.6.2에서 변경: The path parameter accepts a path-like object.

ZipFile.extractall(path=None, members=None, pwd=None)

Extract all members from the archive to the current working directory. path specifies a different directory to extract to. members is optional and must be a subset of the list returned by namelist(). pwd is the password used for encrypted files.

경고

Never extract archives from untrusted sources without prior inspection. It is possible that files are created outside of path, e.g. members that have absolute filenames starting with "/" or filenames with two dots "..". This module attempts to prevent that. See extract() note.

버전 3.6에서 변경: Calling extractall() on a closed ZipFile will raise a ValueError. Previously, a RuntimeError was raised.

버전 3.6.2에서 변경: The path parameter accepts a path-like object.

ZipFile.printdir()

Print a table of contents for the archive to sys.stdout.

ZipFile.setpassword(pwd)

Set pwd as default password to extract encrypted files.

ZipFile.read(name, pwd=None)

Return the bytes of the file name in the archive. name is the name of the file in the archive, or a ZipInfo object. The archive must be open for read or append. pwd is the password used for encrypted files and, if specified, it will override the default password set with setpassword(). Calling read() on a ZipFile that uses a compression method other than ZIP_STORED, ZIP_DEFLATED, ZIP_BZIP2 or ZIP_LZMA will raise a NotImplementedError. An error will also be raised if the corresponding compression module is not available.

버전 3.6에서 변경: Calling read() on a closed ZipFile will raise a ValueError. Previously, a RuntimeError was raised.

ZipFile.testzip()

Read all the files in the archive and check their CRC’s and file headers. Return the name of the first bad file, or else return None.

버전 3.6에서 변경: Calling testzip() on a closed ZipFile will raise a ValueError. Previously, a RuntimeError was raised.

ZipFile.write(filename, arcname=None, compress_type=None, compresslevel=None)

Write the file named filename to the archive, giving it the archive name arcname (by default, this will be the same as filename, but without a drive letter and with leading path separators removed). If given, compress_type overrides the value given for the compression parameter to the constructor for the new entry. Similarly, compresslevel will override the constructor if given. The archive must be open with mode 'w', 'x' or 'a'.

참고

Archive names should be relative to the archive root, that is, they should not start with a path separator.

참고

If arcname (or filename, if arcname is not given) contains a null byte, the name of the file in the archive will be truncated at the null byte.

버전 3.6에서 변경: Calling write() on a ZipFile created with mode 'r' or a closed ZipFile will raise a ValueError. Previously, a RuntimeError was raised.

ZipFile.writestr(zinfo_or_arcname, data, compress_type=None, compresslevel=None)

Write a file into the archive. The contents is data, which may be either a str or a bytes instance; if it is a str, it is encoded as UTF-8 first. zinfo_or_arcname is either the file name it will be given in the archive, or a ZipInfo instance. If it’s an instance, at least the filename, date, and time must be given. If it’s a name, the date and time is set to the current date and time. The archive must be opened with mode 'w', 'x' or 'a'.

If given, compress_type overrides the value given for the compression parameter to the constructor for the new entry, or in the zinfo_or_arcname (if that is a ZipInfo instance). Similarly, compresslevel will override the constructor if given.

참고

When passing a ZipInfo instance as the zinfo_or_arcname parameter, the compression method used will be that specified in the compress_type member of the given ZipInfo instance. By default, the ZipInfo constructor sets this member to ZIP_STORED.

버전 3.2에서 변경: The compress_type argument.

버전 3.6에서 변경: Calling writestr() on a ZipFile created with mode 'r' or a closed ZipFile will raise a ValueError. Previously, a RuntimeError was raised.

The following data attributes are also available:

ZipFile.filename

Name of the ZIP file.

ZipFile.debug

The level of debug output to use. This may be set from 0 (the default, no output) to 3 (the most output). Debugging information is written to sys.stdout.

ZipFile.comment

The comment associated with the ZIP file as a bytes object. If assigning a comment to a ZipFile instance created with mode 'w', 'x' or 'a', it should be no longer than 65535 bytes. Comments longer than this will be truncated.

PyZipFile Objects

The PyZipFile constructor takes the same parameters as the ZipFile constructor, and one additional parameter, optimize.

class zipfile.PyZipFile(file, mode='r', compression=ZIP_STORED, allowZip64=True, optimize=-1)

버전 3.2에 추가: The optimize parameter.

버전 3.4에서 변경: ZIP64 extensions are enabled by default.

Instances have one method in addition to those of ZipFile objects:

writepy(pathname, basename='', filterfunc=None)

Search for files *.py and add the corresponding file to the archive.

If the optimize parameter to PyZipFile was not given or -1, the corresponding file is a *.pyc file, compiling if necessary.

If the optimize parameter to PyZipFile was 0, 1 or 2, only files with that optimization level (see compile()) are added to the archive, compiling if necessary.

If pathname is a file, the filename must end with .py, and just the (corresponding *.pyc) file is added at the top level (no path information). If pathname is a file that does not end with .py, a RuntimeError will be raised. If it is a directory, and the directory is not a package directory, then all the files *.pyc are added at the top level. If the directory is a package directory, then all *.pyc are added under the package name as a file path, and if any subdirectories are package directories, all of these are added recursively in sorted order.

basename is intended for internal use only.

filterfunc, if given, must be a function taking a single string argument. It will be passed each path (including each individual full file path) before it is added to the archive. If filterfunc returns a false value, the path will not be added, and if it is a directory its contents will be ignored. For example, if our test files are all either in test directories or start with the string test_, we can use a filterfunc to exclude them:

>>> zf = PyZipFile('myprog.zip')
>>> def notests(s):
...     fn = os.path.basename(s)
...     return (not (fn == 'test' or fn.startswith('test_')))
>>> zf.writepy('myprog', filterfunc=notests)

The writepy() method makes archives with file names like this:

string.pyc                   # Top level name
test/__init__.pyc            # Package directory
test/testall.pyc             # Module test.testall
test/bogus/__init__.pyc      # Subpackage directory
test/bogus/myfile.pyc        # Submodule test.bogus.myfile

버전 3.4에 추가: The filterfunc parameter.

버전 3.6.2에서 변경: The pathname parameter accepts a path-like object.

버전 3.7에서 변경: Recursion sorts directory entries.

ZipInfo Objects

Instances of the ZipInfo class are returned by the getinfo() and infolist() methods of ZipFile objects. Each object stores information about a single member of the ZIP archive.

There is one classmethod to make a ZipInfo instance for a filesystem file:

classmethod ZipInfo.from_file(filename, arcname=None)

Construct a ZipInfo instance for a file on the filesystem, in preparation for adding it to a zip file.

filename should be the path to a file or directory on the filesystem.

If arcname is specified, it is used as the name within the archive. If arcname is not specified, the name will be the same as filename, but with any drive letter and leading path separators removed.

버전 3.6에 추가.

버전 3.6.2에서 변경: The filename parameter accepts a path-like object.

Instances have the following methods and attributes:

ZipInfo.is_dir()

Return True if this archive member is a directory.

This uses the entry’s name: directories should always end with /.

버전 3.6에 추가.

ZipInfo.filename

Name of the file in the archive.

ZipInfo.date_time

The time and date of the last modification to the archive member. This is a tuple of six values:

Index

Value

0

Year (>= 1980)

1

Month (one-based)

2

Day of month (one-based)

3

Hours (zero-based)

4

Minutes (zero-based)

5

Seconds (zero-based)

참고

The ZIP file format does not support timestamps before 1980.

ZipInfo.compress_type

Type of compression for the archive member.

ZipInfo.comment

Comment for the individual archive member as a bytes object.

ZipInfo.extra

Expansion field data. The PKZIP Application Note [https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT] contains some comments on the internal structure of the data contained in this bytes object.

ZipInfo.create_system

System which created ZIP archive.

ZipInfo.create_version

PKZIP version which created ZIP archive.

ZipInfo.extract_version

PKZIP version needed to extract archive.

ZipInfo.reserved

Must be zero.

ZipInfo.flag_bits

ZIP flag bits.

ZipInfo.volume

Volume number of file header.

ZipInfo.internal_attr

Internal attributes.

ZipInfo.external_attr

External file attributes.

ZipInfo.header_offset

Byte offset to the file header.

ZipInfo.CRC

CRC-32 of the uncompressed file.

ZipInfo.compress_size

Size of the compressed data.

ZipInfo.file_size

Size of the uncompressed file.

Command-Line Interface

The zipfile module provides a simple command-line interface to interact with ZIP archives.

If you want to create a new ZIP archive, specify its name after the -c option and then list the filename(s) that should be included:

$ python -m zipfile -c monty.zip spam.txt eggs.txt

Passing a directory is also acceptable:

$ python -m zipfile -c monty.zip life-of-brian_1979/

If you want to extract a ZIP archive into the specified directory, use the -e option:

$ python -m zipfile -e monty.zip target-dir/

For a list of the files in a ZIP archive, use the -l option:

$ python -m zipfile -l monty.zip

Command-line options

-l <zipfile>

--list <zipfile>

List files in a zipfile.

-c <zipfile> <source1> ... <sourceN>

--create <zipfile> <source1> ... <sourceN>

Create zipfile from source files.

-e <zipfile> <output_dir>

--extract <zipfile> <output_dir>

Extract zipfile into target directory.

-t <zipfile>

--test <zipfile>

Test whether the zipfile is valid or not.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

데이터 압축 및 보관 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

데이터 압축 및 보관 »

|

tarfile — Read and write tar archive files

Source code: Lib/tarfile.py [https://github.com/python/cpython/tree/3.7/Lib/tarfile.py]

The tarfile module makes it possible to read and write tar archives, including those using gzip, bz2 and lzma compression. Use the zipfile module to read or write .zip files, or the higher-level functions in shutil.

Some facts and figures:

reads and writes gzip, bz2 and lzma compressed archives if the respective modules are available.

read/write support for the POSIX.1-1988 (ustar) format.

read/write support for the GNU tar format including longname and longlink extensions, read-only support for all variants of the sparse extension including restoration of sparse files.

read/write support for the POSIX.1-2001 (pax) format.

handles directories, regular files, hardlinks, symbolic links, fifos, character devices and block devices and is able to acquire and restore file information like timestamp, access permissions and owner.

버전 3.3에서 변경: Added support for lzma compression.

tarfile.open(name=None, mode='r', fileobj=None, bufsize=10240, **kwargs)

Return a TarFile object for the pathname name. For detailed information on TarFile objects and the keyword arguments that are allowed, see TarFile Objects.

mode has to be a string of the form 'filemode[:compression]', it defaults to 'r'. Here is a full list of mode combinations:

mode

action

'r' or 'r:*'

Open for reading with transparent compression (recommended).

'r:'

Open for reading exclusively without compression.

'r:gz'

Open for reading with gzip compression.

'r:bz2'

Open for reading with bzip2 compression.

'r:xz'

Open for reading with lzma compression.

'x' or 'x:'

Create a tarfile exclusively without compression. Raise an FileExistsError exception if it already exists.

'x:gz'

Create a tarfile with gzip compression. Raise an FileExistsError exception if it already exists.

'x:bz2'

Create a tarfile with bzip2 compression. Raise an FileExistsError exception if it already exists.

'x:xz'

Create a tarfile with lzma compression. Raise an FileExistsError exception if it already exists.

'a' or 'a:'

Open for appending with no compression. The file is created if it does not exist.

'w' or 'w:'

Open for uncompressed writing.

'w:gz'

Open for gzip compressed writing.

'w:bz2'

Open for bzip2 compressed writing.

'w:xz'

Open for lzma compressed writing.

Note that 'a:gz', 'a:bz2' or 'a:xz' is not possible. If mode is not suitable to open a certain (compressed) file for reading, ReadError is raised. Use mode 'r' to avoid this. If a compression method is not supported, CompressionError is raised.

If fileobj is specified, it is used as an alternative to a file object opened in binary mode for name. It is supposed to be at position 0.

For modes 'w:gz', 'r:gz', 'w:bz2', 'r:bz2', 'x:gz', 'x:bz2', tarfile.open() accepts the keyword argument compresslevel (default 9) to specify the compression level of the file.

For special purposes, there is a second format for mode: 'filemode|[compression]'. tarfile.open() will return a TarFile object that processes its data as a stream of blocks. No random seeking will be done on the file. If given, fileobj may be any object that has a read() or write() method (depending on the mode). bufsize specifies the blocksize and defaults to 20 * 512 bytes. Use this variant in combination with e.g. sys.stdin, a socket file object or a tape device. However, such a TarFile object is limited in that it does not allow random access, see Examples. The currently possible modes:

Mode

Action

'r|*'

Open a stream of tar blocks for reading with transparent compression.

'r|'

Open a stream of uncompressed tar blocks for reading.

'r|gz'

Open a gzip compressed stream for reading.

'r|bz2'

Open a bzip2 compressed stream for reading.

'r|xz'

Open an lzma compressed stream for reading.

'w|'

Open an uncompressed stream for writing.

'w|gz'

Open a gzip compressed stream for writing.

'w|bz2'

Open a bzip2 compressed stream for writing.

'w|xz'

Open an lzma compressed stream for writing.

버전 3.5에서 변경: The 'x' (exclusive creation) mode was added.

버전 3.6에서 변경: The name parameter accepts a path-like object.

class tarfile.TarFile

Class for reading and writing tar archives. Do not use this class directly: use tarfile.open() instead. See TarFile Objects.

tarfile.is_tarfile(name)

Return True if name is a tar archive file, that the tarfile module can read.

The tarfile module defines the following exceptions:

exception tarfile.TarError

Base class for all tarfile exceptions.

exception tarfile.ReadError

Is raised when a tar archive is opened, that either cannot be handled by the tarfile module or is somehow invalid.

exception tarfile.CompressionError

Is raised when a compression method is not supported or when the data cannot be decoded properly.

exception tarfile.StreamError

Is raised for the limitations that are typical for stream-like TarFile objects.

exception tarfile.ExtractError

Is raised for non-fatal errors when using TarFile.extract(), but only if TarFile.errorlevel== 2.

exception tarfile.HeaderError

Is raised by TarInfo.frombuf() if the buffer it gets is invalid.

The following constants are available at the module level:

tarfile.ENCODING

The default character encoding: 'utf-8' on Windows, the value returned by sys.getfilesystemencoding() otherwise.

Each of the following constants defines a tar archive format that the tarfile module is able to create. See section Supported tar formats for details.

tarfile.USTAR_FORMAT

POSIX.1-1988 (ustar) format.

tarfile.GNU_FORMAT

GNU tar format.

tarfile.PAX_FORMAT

POSIX.1-2001 (pax) format.

tarfile.DEFAULT_FORMAT

The default format for creating archives. This is currently GNU_FORMAT.

더 보기

Module zipfile

Documentation of the zipfile standard module.

Archiving operations

Documentation of the higher-level archiving facilities provided by the standard shutil module.

GNU tar manual, Basic Tar Format [https://www.gnu.org/software/tar/manual/html_node/Standard.html]

Documentation for tar archive files, including GNU tar extensions.

TarFile Objects

The TarFile object provides an interface to a tar archive. A tar archive is a sequence of blocks. An archive member (a stored file) is made up of a header block followed by data blocks. It is possible to store a file in a tar archive several times. Each archive member is represented by a TarInfo object, see TarInfo Objects for details.

A TarFile object can be used as a context manager in a with statement. It will automatically be closed when the block is completed. Please note that in the event of an exception an archive opened for writing will not be finalized; only the internally used file object will be closed. See the Examples section for a use case.

버전 3.2에 추가: Added support for the context management protocol.

class tarfile.TarFile(name=None, mode='r', fileobj=None, format=DEFAULT_FORMAT, tarinfo=TarInfo, dereference=False, ignore_zeros=False, encoding=ENCODING, errors='surrogateescape', pax_headers=None, debug=0, errorlevel=1)

All following arguments are optional and can be accessed as instance attributes as well.

name is the pathname of the archive. name may be a path-like object. It can be omitted if fileobj is given. In this case, the file object’s name attribute is used if it exists.

mode is either 'r' to read from an existing archive, 'a' to append data to an existing file, 'w' to create a new file overwriting an existing one, or 'x' to create a new file only if it does not already exist.

If fileobj is given, it is used for reading or writing data. If it can be determined, mode is overridden by fileobj’s mode. fileobj will be used from position 0.

참고

fileobj is not closed, when TarFile is closed.

format controls the archive format. It must be one of the constants USTAR_FORMAT, GNU_FORMAT or PAX_FORMAT that are defined at module level.

The tarinfo argument can be used to replace the default TarInfo class with a different one.

If dereference is False, add symbolic and hard links to the archive. If it is True, add the content of the target files to the archive. This has no effect on systems that do not support symbolic links.

If ignore_zeros is False, treat an empty block as the end of the archive. If it is True, skip empty (and invalid) blocks and try to get as many members as possible. This is only useful for reading concatenated or damaged archives.

debug can be set from 0 (no debug messages) up to 3 (all debug messages). The messages are written to sys.stderr.

If errorlevel is 0, all errors are ignored when using TarFile.extract(). Nevertheless, they appear as error messages in the debug output, when debugging is enabled. If 1, all fatal errors are raised as OSError exceptions. If 2, all non-fatal errors are raised as TarError exceptions as well.

The encoding and errors arguments define the character encoding to be used for reading or writing the archive and how conversion errors are going to be handled. The default settings will work for most users. See section Unicode issues for in-depth information.

The pax_headers argument is an optional dictionary of strings which will be added as a pax global header if format is PAX_FORMAT.

버전 3.2에서 변경: Use 'surrogateescape' as the default for the errors argument.

버전 3.5에서 변경: The 'x' (exclusive creation) mode was added.

버전 3.6에서 변경: The name parameter accepts a path-like object.

classmethod TarFile.open(...)

Alternative constructor. The tarfile.open() function is actually a shortcut to this classmethod.

TarFile.getmember(name)

Return a TarInfo object for member name. If name can not be found in the archive, KeyError is raised.

참고

If a member occurs more than once in the archive, its last occurrence is assumed to be the most up-to-date version.

TarFile.getmembers()

Return the members of the archive as a list of TarInfo objects. The list has the same order as the members in the archive.

TarFile.getnames()

Return the members as a list of their names. It has the same order as the list returned by getmembers().

TarFile.list(verbose=True, *, members=None)

Print a table of contents to sys.stdout. If verbose is False, only the names of the members are printed. If it is True, output similar to that of ls -l is produced. If optional members is given, it must be a subset of the list returned by getmembers().

버전 3.5에서 변경: Added the members parameter.

TarFile.next()

Return the next member of the archive as a TarInfo object, when TarFile is opened for reading. Return None if there is no more available.

TarFile.extractall(path=".", members=None, *, numeric_owner=False)

Extract all members from the archive to the current working directory or directory path. If optional members is given, it must be a subset of the list returned by getmembers(). Directory information like owner, modification time and permissions are set after all members have been extracted. This is done to work around two problems: A directory’s modification time is reset each time a file is created in it. And, if a directory’s permissions do not allow writing, extracting files to it will fail.

If numeric_owner is True, the uid and gid numbers from the tarfile are used to set the owner/group for the extracted files. Otherwise, the named values from the tarfile are used.

경고

Never extract archives from untrusted sources without prior inspection. It is possible that files are created outside of path, e.g. members that have absolute filenames starting with "/" or filenames with two dots "..".

버전 3.5에서 변경: Added the numeric_owner parameter.

버전 3.6에서 변경: The path parameter accepts a path-like object.

TarFile.extract(member, path="", set_attrs=True, *, numeric_owner=False)

Extract a member from the archive to the current working directory, using its full name. Its file information is extracted as accurately as possible. member may be a filename or a TarInfo object. You can specify a different directory using path. path may be a path-like object. File attributes (owner, mtime, mode) are set unless set_attrs is false.

If numeric_owner is True, the uid and gid numbers from the tarfile are used to set the owner/group for the extracted files. Otherwise, the named values from the tarfile are used.

참고

The extract() method does not take care of several extraction issues. In most cases you should consider using the extractall() method.

경고

See the warning for extractall().

버전 3.2에서 변경: Added the set_attrs parameter.

버전 3.5에서 변경: Added the numeric_owner parameter.

버전 3.6에서 변경: The path parameter accepts a path-like object.

TarFile.extractfile(member)

Extract a member from the archive as a file object. member may be a filename or a TarInfo object. If member is a regular file or a link, an io.BufferedReader object is returned. Otherwise, None is returned.

버전 3.3에서 변경: Return an io.BufferedReader object.

TarFile.add(name, arcname=None, recursive=True, *, filter=None)

Add the file name to the archive. name may be any type of file (directory, fifo, symbolic link, etc.). If given, arcname specifies an alternative name for the file in the archive. Directories are added recursively by default. This can be avoided by setting recursive to False. Recursion adds entries in sorted order. If filter is given, it should be a function that takes a TarInfo object argument and returns the changed TarInfo object. If it instead returns None the TarInfo object will be excluded from the archive. See Examples for an example.

버전 3.2에서 변경: Added the filter parameter.

버전 3.7에서 변경: Recursion adds entries in sorted order.

TarFile.addfile(tarinfo, fileobj=None)

Add the TarInfo object tarinfo to the archive. If fileobj is given, it should be a binary file, and tarinfo.size bytes are read from it and added to the archive. You can create TarInfo objects directly, or by using gettarinfo().

TarFile.gettarinfo(name=None, arcname=None, fileobj=None)

Create a TarInfo object from the result of os.stat() or equivalent on an existing file. The file is either named by name, or specified as a file object fileobj with a file descriptor. name may be a path-like object. If given, arcname specifies an alternative name for the file in the archive, otherwise, the name is taken from fileobj’s name attribute, or the name argument. The name should be a text string.

You can modify some of the TarInfo’s attributes before you add it using addfile(). If the file object is not an ordinary file object positioned at the beginning of the file, attributes such as size may need modifying. This is the case for objects such as GzipFile. The name may also be modified, in which case arcname could be a dummy string.

버전 3.6에서 변경: The name parameter accepts a path-like object.

TarFile.close()

Close the TarFile. In write mode, two finishing zero blocks are appended to the archive.

TarFile.pax_headers

A dictionary containing key-value pairs of pax global headers.

TarInfo Objects

A TarInfo object represents one member in a TarFile. Aside from storing all required attributes of a file (like file type, size, time, permissions, owner etc.), it provides some useful methods to determine its type. It does not contain the file’s data itself.

TarInfo objects are returned by TarFile’s methods getmember(), getmembers() and gettarinfo().

class tarfile.TarInfo(name="")

Create a TarInfo object.

classmethod TarInfo.frombuf(buf, encoding, errors)

Create and return a TarInfo object from string buffer buf.

Raises HeaderError if the buffer is invalid.

classmethod TarInfo.fromtarfile(tarfile)

Read the next member from the TarFile object tarfile and return it as a TarInfo object.

TarInfo.tobuf(format=DEFAULT_FORMAT, encoding=ENCODING, errors='surrogateescape')

Create a string buffer from a TarInfo object. For information on the arguments see the constructor of the TarFile class.

버전 3.2에서 변경: Use 'surrogateescape' as the default for the errors argument.

A TarInfo object has the following public data attributes:

TarInfo.name

Name of the archive member.

TarInfo.size

Size in bytes.

TarInfo.mtime

Time of last modification.

TarInfo.mode

Permission bits.

TarInfo.type

File type. type is usually one of these constants: REGTYPE, AREGTYPE, LNKTYPE, SYMTYPE, DIRTYPE, FIFOTYPE, CONTTYPE, CHRTYPE, BLKTYPE, GNUTYPE_SPARSE. To determine the type of a TarInfo object more conveniently, use the is*() methods below.

TarInfo.linkname

Name of the target file name, which is only present in TarInfo objects of type LNKTYPE and SYMTYPE.

TarInfo.uid

User ID of the user who originally stored this member.

TarInfo.gid

Group ID of the user who originally stored this member.

TarInfo.uname

User name.

TarInfo.gname

Group name.

TarInfo.pax_headers

A dictionary containing key-value pairs of an associated pax extended header.

A TarInfo object also provides some convenient query methods:

TarInfo.isfile()

Return True if the Tarinfo object is a regular file.

TarInfo.isreg()

Same as isfile().

TarInfo.isdir()

Return True if it is a directory.

TarInfo.issym()

Return True if it is a symbolic link.

TarInfo.islnk()

Return True if it is a hard link.

TarInfo.ischr()

Return True if it is a character device.

TarInfo.isblk()

Return True if it is a block device.

TarInfo.isfifo()

Return True if it is a FIFO.

TarInfo.isdev()

Return True if it is one of character device, block device or FIFO.

Command-Line Interface

버전 3.4에 추가.

The tarfile module provides a simple command-line interface to interact with tar archives.

If you want to create a new tar archive, specify its name after the -c option and then list the filename(s) that should be included:

$ python -m tarfile -c monty.tar  spam.txt eggs.txt

Passing a directory is also acceptable:

$ python -m tarfile -c monty.tar life-of-brian_1979/

If you want to extract a tar archive into the current directory, use the -e option:

$ python -m tarfile -e monty.tar

You can also extract a tar archive into a different directory by passing the directory’s name:

$ python -m tarfile -e monty.tar  other-dir/

For a list of the files in a tar archive, use the -l option:

$ python -m tarfile -l monty.tar

Command-line options

-l <tarfile>

--list <tarfile>

List files in a tarfile.

-c <tarfile> <source1> ... <sourceN>

--create <tarfile> <source1> ... <sourceN>

Create tarfile from source files.

-e <tarfile> [<output_dir>]

--extract <tarfile> [<output_dir>]

Extract tarfile into the current directory if output_dir is not specified.

-t <tarfile>

--test <tarfile>

Test whether the tarfile is valid or not.

-v, --verbose

Verbose output.

Examples

How to extract an entire tar archive to the current working directory:

import tarfile
tar = tarfile.open("sample.tar.gz")
tar.extractall()
tar.close()

How to extract a subset of a tar archive with TarFile.extractall() using a generator function instead of a list:

import os
import tarfile

def py_files(members):
    for tarinfo in members:
        if os.path.splitext(tarinfo.name)[1] == ".py":
            yield tarinfo

tar = tarfile.open("sample.tar.gz")
tar.extractall(members=py_files(tar))
tar.close()

How to create an uncompressed tar archive from a list of filenames:

import tarfile
tar = tarfile.open("sample.tar", "w")
for name in ["foo", "bar", "quux"]:
    tar.add(name)
tar.close()

The same example using the with statement:

import tarfile
with tarfile.open("sample.tar", "w") as tar:
    for name in ["foo", "bar", "quux"]:
        tar.add(name)

How to read a gzip compressed tar archive and display some member information:

import tarfile
tar = tarfile.open("sample.tar.gz", "r:gz")
for tarinfo in tar:
    print(tarinfo.name, "is", tarinfo.size, "bytes in size and is ", end="")
    if tarinfo.isreg():
        print("a regular file.")
    elif tarinfo.isdir():
        print("a directory.")
    else:
        print("something else.")
tar.close()

How to create an archive and reset the user information using the filter parameter in TarFile.add():

import tarfile
def reset(tarinfo):
    tarinfo.uid = tarinfo.gid = 0
    tarinfo.uname = tarinfo.gname = "root"
    return tarinfo
tar = tarfile.open("sample.tar.gz", "w:gz")
tar.add("foo", filter=reset)
tar.close()

Supported tar formats

There are three tar formats that can be created with the tarfile module:

The POSIX.1-1988 ustar format (USTAR_FORMAT). It supports filenames up to a length of at best 256 characters and linknames up to 100 characters. The maximum file size is 8 GiB. This is an old and limited but widely supported format.

The GNU tar format (GNU_FORMAT). It supports long filenames and linknames, files bigger than 8 GiB and sparse files. It is the de facto standard on GNU/Linux systems. tarfile fully supports the GNU tar extensions for long names, sparse file support is read-only.

The POSIX.1-2001 pax format (PAX_FORMAT). It is the most flexible format with virtually no limits. It supports long filenames and linknames, large files and stores pathnames in a portable way. However, not all tar implementations today are able to handle pax archives properly.

The pax format is an extension to the existing ustar format. It uses extra headers for information that cannot be stored otherwise. There are two flavours of pax headers: Extended headers only affect the subsequent file header, global headers are valid for the complete archive and affect all following files. All the data in a pax header is encoded in UTF-8 for portability reasons.

There are some more variants of the tar format which can be read, but not created:

The ancient V7 format. This is the first tar format from Unix Seventh Edition, storing only regular files and directories. Names must not be longer than 100 characters, there is no user/group name information. Some archives have miscalculated header checksums in case of fields with non-ASCII characters.

The SunOS tar extended format. This format is a variant of the POSIX.1-2001 pax format, but is not compatible.

Unicode issues

The tar format was originally conceived to make backups on tape drives with the main focus on preserving file system information. Nowadays tar archives are commonly used for file distribution and exchanging archives over networks. One problem of the original format (which is the basis of all other formats) is that there is no concept of supporting different character encodings. For example, an ordinary tar archive created on a UTF-8 system cannot be read correctly on a Latin-1 system if it contains non-ASCII characters. Textual metadata (like filenames, linknames, user/group names) will appear damaged. Unfortunately, there is no way to autodetect the encoding of an archive. The pax format was designed to solve this problem. It stores non-ASCII metadata using the universal character encoding UTF-8.

The details of character conversion in tarfile are controlled by the encoding and errors keyword arguments of the TarFile class.

encoding defines the character encoding to use for the metadata in the archive. The default value is sys.getfilesystemencoding() or 'ascii' as a fallback. Depending on whether the archive is read or written, the metadata must be either decoded or encoded. If encoding is not set appropriately, this conversion may fail.

The errors argument defines how characters are treated that cannot be converted. Possible values are listed in section Error Handlers. The default scheme is 'surrogateescape' which Python also uses for its file system calls, see 파일명, 명령 줄 인자 및 환경 변수.

In case of PAX_FORMAT archives, encoding is generally not needed because all the metadata is stored using UTF-8. encoding is only used in the rare cases when binary pax headers are decoded or when strings with surrogate characters are stored.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

데이터 압축 및 보관 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

|

파일 형식

이 장에서 설명하는 모듈들은 마크업 언어가 아니고 전자 메일과 무관한 다양한 파일 형식을 구문 분석합니다.

csv — CSV 파일 읽기와 쓰기

모듈 내용

방언과 포매팅 파라미터

판독기 객체

기록기 객체

예제

configparser — Configuration file parser

Quick Start

Supported Datatypes

Fallback Values

Supported INI File Structure

Interpolation of values

Mapping Protocol Access

Customizing Parser Behaviour

Legacy API Examples

ConfigParser Objects

RawConfigParser Objects

Exceptions

netrc — netrc 파일 처리

netrc 객체

xdrlib — XDR 데이터 인코딩과 디코딩

Packer 객체

Unpacker 객체

예외

plistlib — 맥 OS X .plist 파일 생성과 구문 분석

예제

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

파일 형식 »

|

csv — CSV 파일 읽기와 쓰기

소스 코드: Lib/csv.py [https://github.com/python/cpython/tree/3.7/Lib/csv.py]

소위 CSV (Comma Separated Values – 쉼표로 구분된 값) 형식은 스프레드시트와 데이터베이스에 대한 가장 일반적인 가져오기 및 내보내기 형식입니다. CSV 형식은 RFC 4180 [https://tools.ietf.org/html/rfc4180.html]에서 표준화된 방식으로 형식을 기술하기 전에 여러 해 동안 사용되었습니다. 잘 정의된 표준이 없다는 것은 다른 애플리케이션에 의해 생성되고 소비되는 데이터에 미묘한 차이가 존재한다는 것을 의미합니다. 이러한 차이로 인해 여러 소스의 CSV 파일을 처리하는 것이 번거로울 수 있습니다. 그러나 분리 문자와 인용 문자가 다양하기는 해도, 전체 형식은 유사하여 프로그래머에게 데이터 읽기와 쓰기 세부 사항을 숨기면서도 이러한 데이터를 효율적으로 조작할 수 있는 단일 모듈을 작성하는 것이 가능합니다.

csv 모듈은 CSV 형식의 표 형식 데이터를 읽고 쓰는 클래스를 구현합니다. 이 모듈은 프로그래머가 Excel에서 사용하는 CSV 형식에 대한 자세한 내용을 알지 못해도, “Excel에서 선호하는 형식으로 이 데이터를 쓰세요”나 “Excel에서 생성된 이 파일의 데이터를 읽으세요”라고 말할 수 있도록 합니다. 프로그래머는 다른 응용 프로그램에서 이해할 수 있는 CSV 형식을 기술하거나 자신만의 특수 용도 CSV 형식을 정의할 수 있습니다.

csv 모듈의 reader와 writer 객체는 시퀀스를 읽고 씁니다. 프로그래머는 DictReader와 DictWriter 클래스를 사용하여 딕셔너리 형식으로 데이터를 읽고 쓸 수 있습니다.

더 보기

PEP 305 [https://www.python.org/dev/peps/pep-0305] - CSV File API

파이썬에 이 모듈의 추가를 제안한 파이썬 개선 제안.

모듈 내용

csv 모듈은 다음 함수를 정의합니다:

csv.reader(csvfile, dialect='excel', **fmtparams)

지정된 csvfile의 줄을 이터레이트 하는 판독기(reader) 객체를 반환합니다. csvfile은 이터레이터 프로토콜을 지원하고 __next__() 메서드가 호출될 때마다 문자열을 반환하는 객체여야 합니다 — 파일 객체와 리스트 객체 모두 적합합니다. csvfile가 파일 객체이면, newline=''로 열렸어야 합니다. 1 특정 CSV 방언(dialect)에만 적용되는 파라미터 집합을 정의하는 데 사용되는 선택적 dialect 매개 변수를 지정할 수 있습니다. Dialect 클래스의 서브 클래스의 인스턴스이거나 list_dialects() 함수가 반환하는 문자열 중 하나일 수 있습니다. 다른 선택적 fmtparams 키워드 인자는 현재 방언의 개별 포매팅 파라미터를 대체 할 수 있습니다. 방언과 포매팅 파라미터에 대한 자세한 내용은 방언과 포매팅 파라미터 절을 참조하십시오.

csv 파일에서 읽은 각 행(row)은 문자열 리스트로 반환됩니다. QUOTE_NONNUMERIC 포맷 옵션을 지정하지 않으면 아무런 자동 데이터형 변환도 수행되지 않습니다 (지정하면 인용되지 않은 필드는 float로 변환됩니다).

간단한 사용 예:

>>> import csv
>>> with open('eggs.csv', newline='') as csvfile:
...     spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
...     for row in spamreader:
...         print(', '.join(row))
Spam, Spam, Spam, Spam, Spam, Baked Beans
Spam, Lovely Spam, Wonderful Spam

csv.writer(csvfile, dialect='excel', **fmtparams)

지정된 파일류 객체에 분리된 문자열로 사용자의 데이터를 변환하는 기록기(writer) 객체를 반환합니다. csvfile은 write() 메서드가 있는 모든 객체일 수 있습니다. csvfile이 파일 객체면, newline=''으로 열렸어야 합니다 1. 특정 CSV 방언(dialect)에만 적용되는 파라미터 집합을 정의하는 데 사용되는 선택적 dialect 매개 변수를 지정할 수 있습니다. Dialect 클래스의 서브 클래스의 인스턴스이거나 list_dialects() 함수가 반환하는 문자열 중 하나일 수 있습니다. 다른 선택적 fmtparams 키워드 인자는 현재 방언의 개별 포매팅 파라미터를 대체 할 수 있습니다. 방언과 포매팅 파라미터에 대한 자세한 내용은 방언과 포매팅 파라미터 절을 참조하십시오. DB API를 구현하는 모듈과 가능한 한 쉽게 인터페이스 하기 위해, 값 None은 빈 문자열로 기록됩니다. 이것은 가역 변환이 아니지만, cursor.fetch* 호출에서 반환된 데이터를 전처리하지 않고도, SQL NULL 데이터값을 CSV 파일로 쉽게 덤프할 수 있습니다. 다른 모든 비 문자열 데이터는 기록 전에 str()로 문자열화 됩니다.

간단한 사용 예:

import csv
with open('eggs.csv', 'w', newline='') as csvfile:
    spamwriter = csv.writer(csvfile, delimiter=' ',
                            quotechar='|', quoting=csv.QUOTE_MINIMAL)
    spamwriter.writerow(['Spam'] * 5 + ['Baked Beans'])
    spamwriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])

csv.register_dialect(name[, dialect[, **fmtparams]])

dialect를 name과 연관시킵니다. name은 문자열이어야 합니다. 방언은 Dialect의 서브 클래스 전달, fmtparams 키워드 인자 또는 둘 모두를 사용하여 지정할 수 있는데, 키워드 인자가 dialect의 매개 변수보다 우선합니다. 방언과 포매팅 파라미터에 대한 자세한 내용은 방언과 포매팅 파라미터 절을 참조하십시오.

csv.unregister_dialect(name)

방언(dialect) 등록소에서 name과 관련된 연관된 방언을 삭제합니다. name이 등록된 방언 이름이 아니면 Error가 발생합니다.

csv.get_dialect(name)

name과 연관된 방언을 반환합니다. name이 등록된 방언 이름이 아니면 Error가 발생합니다. 이 함수는 불변 Dialect를 반환합니다.

csv.list_dialects()

등록된 모든 방언의 이름을 반환합니다.

csv.field_size_limit([new_limit])

구문 분석기가 허락하는 현재의 최대 필드 크기를 반환합니다. new_limit가 주어지면, 이것이 새로운 한계가 됩니다.

csv 모듈은 다음 클래스를 정의합니다:

class csv.DictReader(f, fieldnames=None, restkey=None, restval=None, dialect='excel', *args, **kwds)

일반 판독기처럼 작동하지만 각 행(row)의 정보를 키가 선택적 fieldnames 매개 변수로 지정된 OrderedDict로 매핑하는 객체를 만듭니다.

fieldnames 매개 변수는 시퀀스입니다. fieldnames를 생략하면, 파일 f의 첫 번째 행에 있는 값들을 fieldnames로 사용합니다. 필드 이름이 어떻게 결정되는지와 관계없이, 순서 있는 딕셔너리는 원래 순서를 유지합니다.

If a row has more fields than fieldnames, the remaining data is put in a list and stored with the fieldname specified by restkey (which defaults to None). If a non-blank row has fewer fields than fieldnames, the missing values are filled-in with the value of restval (which defaults to None).

다른 모든 선택적 또는 키워드 인자는 하부 reader 인스턴스에 전달됩니다.

버전 3.6에서 변경: 반환된 행은 이제 OrderedDict 형입니다.

간단한 사용 예:

>>> import csv
>>> with open('names.csv', newline='') as csvfile:
...     reader = csv.DictReader(csvfile)
...     for row in reader:
...         print(row['first_name'], row['last_name'])
...
Eric Idle
John Cleese

>>> print(row)
OrderedDict([('first_name', 'John'), ('last_name', 'Cleese')])

class csv.DictWriter(f, fieldnames, restval='', extrasaction='raise', dialect='excel', *args, **kwds)

일반 기록기처럼 작동하지만 딕셔너리를 출력 행에 매핑하는 객체를 만듭니다. fieldnames 매개 변수는 키의 시퀀스인데, writerow() 메서드에 전달된 딕셔너리의 값이 f 파일에 기록되는 순서를 식별합니다. 선택적 restval 매개 변수는 딕셔너리에 fieldnames의 키가 빠졌을 때 기록될 값을 지정합니다. writerow() 메서드에 전달된 딕셔너리에 fieldnames에 없는 키가 포함되어 있으면, 선택적 extrasaction 매개 변수가 수행할 작업을 지시합니다. 기본값인 'raise'로 설정되면, ValueError가 발생합니다. 'ignore'로 설정하면, 딕셔너리의 추가 값이 무시됩니다. 다른 선택적 또는 키워드 인자는 하부 writer 인스턴스에 전달됩니다.

DictReader 클래스와 달리 DictWriter 클래스의 fieldnames 매개 변수는 선택 사항이 아닙니다.

간단한 사용 예:

import csv

with open('names.csv', 'w', newline='') as csvfile:
    fieldnames = ['first_name', 'last_name']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)

    writer.writeheader()
    writer.writerow({'first_name': 'Baked', 'last_name': 'Beans'})
    writer.writerow({'first_name': 'Lovely', 'last_name': 'Spam'})
    writer.writerow({'first_name': 'Wonderful', 'last_name': 'Spam'})

class csv.Dialect

Dialect 클래스는 어트리뷰트에 주로 의존하는 컨테이너 클래스인데, 특정 reader나 writer 인스턴스에 대한 파라미터를 정의하는 데 사용됩니다.

class csv.excel

excel 클래스는 Excel에서 생성한 CSV 파일의 일반적인 속성을 정의합니다. 방언 이름 'excel'로 등록됩니다.

class csv.excel_tab

excel_tab 클래스는 Excel에서 생성된 TAB 구분 파일의 일반적인 속성을 정의합니다. 방언 이름 'excel-tab'으로 등록됩니다.

class csv.unix_dialect

unix_dialect 클래스는 유닉스 시스템에서 생성된 CSV 파일의 일반적인 속성을 정의합니다. 즉, '\n'을 줄 종결자로 사용하고 모든 필드를 인용 처리합니다. 방언 이름 'unix'로 등록됩니다.

버전 3.2에 추가.

class csv.Sniffer

Sniffer 클래스는 CSV 파일의 형식을 추론하는 데 사용됩니다.

Sniffer 클래스는 두 가지 메서드를 제공합니다:

sniff(sample, delimiters=None)

지정된 sample을 분석하고 발견된 파라미터를 반영하는 Dialect 서브 클래스를 반환합니다. 선택적인 delimiters 매개 변수를 주면, 가능한 유효한 구분 문자를 포함하는 문자열로 해석됩니다.

has_header(sample)

sample 텍스트(CSV 형식으로 추정합니다)를 분석하고, 첫 번째 행이 일련의 열 머리글로 보이면 True를 반환합니다.

Sniffer 사용 예:

with open('example.csv', newline='') as csvfile:
    dialect = csv.Sniffer().sniff(csvfile.read(1024))
    csvfile.seek(0)
    reader = csv.reader(csvfile, dialect)
    # ... process CSV file contents here ...

csv 모듈은 다음 상수를 정의합니다:

csv.QUOTE_ALL

writer 객체에 모든 필드를 인용 처리하도록 지시합니다.

csv.QUOTE_MINIMAL

writer 객체에 delimiter, quotechar 또는 lineterminator에 들어있는 모든 문자와 같은 특수 문자를 포함하는 필드만 인용 처리하도록 지시합니다.

csv.QUOTE_NONNUMERIC

writer 객체에 모든 숫자가 아닌 필드를 인용 처리하도록 지시합니다.

판독기에 인용 처리되지 않은 모든 필드를 float 형으로 변환하도록 지시합니다.

csv.QUOTE_NONE

writer 객체에 필드를 절대 인용 처리하지 않도록 지시합니다. 출력 데이터에 현재 delimiter가 등장하면, 현재 escapechar 문자를 앞에 붙입니다. escapechar가 설정되지 않았을 때 작성기는 이스케이프 해야 하는 문자가 있으면 Error를 발생시킵니다.

reader에게 인용 문자의 특별한 처리를 수행하지 않도록 지시합니다.

csv 모듈은 다음 예외를 정의합니다:

exception csv.Error

에러가 감지될 때 모든 함수가 발생시킵니다.

방언과 포매팅 파라미터

입력과 출력 레코드의 형식을 더 쉽게 지정할 수 있도록, 특정 포매팅 파라미터가 함께 방언으로 묶입니다. 방언(dialect)은 특정 메서드 집합과 단일 validate() 메서드가 있는 Dialect 클래스의 서브 클래스입니다. reader나 writer 객체를 만들 때, 프로그래머는 문자열이나 Dialect 클래스의 서브 클래스를 dialect 매개 변수로 지정할 수 있습니다. dialect 매개 변수에 추가하여, 또는 대신에, 프로그래머는 아래에서 Dialect 클래스에 대해 정의된 어트리뷰트와 같은 이름을 갖는 개별 포매팅 매개 변수를 지정할 수 있습니다.

방언은 다음 어트리뷰트를 지원합니다:

Dialect.delimiter

필드를 구분하는 데 사용되는 한 문자로 된 문자열. 기본값은 ','입니다.

Dialect.doublequote

필드 안에 나타나는 quotechar의 인스턴스를 인용 처리하는 방법을 제어합니다. True일 때, 문자를 두 개로 늘립니다. False일 때, escapechar를 quotechar의 접두어로 사용합니다. 기본값은 True입니다.

출력 시, doublequote가 False이고 아무런 escapechar가 설정되지 않았으면, 필드에 quotechar가 있으면 Error가 발생합니다.

Dialect.escapechar

quoting이 QUOTE_NONE으로 설정되었을 때 delimiter를, doublequote가 False일 때 quotechar를 이스케이프 하는데 기록기가 사용하는 한 문자로 된 문자열. 판독 시에, escapechar는 뒤따르는 문자에서 특별한 의미를 제거합니다. 기본값은 None이며, 이스케이핑을 비활성화합니다.

Dialect.lineterminator

writer에 의해 생성된 행을 종료하는 데 사용되는 문자열. 기본값은 '\r\n'입니다.

참고

reader는 '\r'이나 '\n'을 줄 종료로 인식하도록 하드 코딩되어 있으며, lineterminator를 무시합니다. 이 동작은 앞으로 변경될 수 있습니다.

Dialect.quotechar

delimiter나 quotechar와 같은 특수 문자를 포함하거나 개행 문자를 포함하는 필드를 인용 처리하는 데 사용되는 한 문자라도 된 문자열. 기본값은 '"'입니다.

Dialect.quoting

언제 인용 기호를 기록기가 생성하고 판독기가 인식해야 하는지를 제어합니다. QUOTE_* 상수 (모듈 내용 절을 참조하십시오) 중 하나를 취할 수 있으며 기본값은 QUOTE_MINIMAL입니다.

Dialect.skipinitialspace

True일 때, delimiter 바로 뒤에 오는 공백은 무시됩니다. 기본값은 False입니다.

Dialect.strict

True일 때, 잘못된 CSV 입력에서 예외 Error를 발생시킵니다. 기본값은 False입니다.

판독기 객체

판독기 객체(DictReader 인스턴스와 reader() 함수에서 반환한 객체)에는 다음과 같은 공용 메서드가 있습니다:

csvreader.__next__()

판독기의 이터러블 객체의 다음 행을 현재 방언에 따라 구문 분석하여 리스트(객체가 reader()에서 반환된 경우)나 딕셔너리(DictReader 인스턴스인 경우)로 반환합니다. 보통 이것을 next(reader)처럼 호출합니다.

판독기 객체에는 다음과 같은 공용 어트리뷰트가 있습니다:

csvreader.dialect

구문 분석기가 사용 중인 방언의 읽기 전용 설명.

csvreader.line_num

소스 이터레이터에서 읽은 줄 수. 레코드가 여러 줄에 걸쳐 있을 수 있으므로, 이것은 반환된 레코드 수와 같지 않습니다.

DictReader 객체에는 다음과 같은 공용 어트리뷰트가 있습니다:

csvreader.fieldnames

객체를 만들 때 매개 변수로 전달되지 않았으면, 이 어트리뷰트는 첫 번째 액세스 시나 파일에서 첫 번째 레코드를 읽을 때 초기화됩니다.

기록기 객체

Writer 객체(DictWriter 인스턴스와 writer() 함수에서 반환한 객체)에는 다음과 같은 공용 메서드가 있습니다. row는 Writer 객체의 경우 문자열이나 숫자의 이터러블이어야 하며, DictWriter 객체의 경우 fieldnames를 (str()을 먼저 통과시킴으로써) 문자열이나 숫자로 매핑하는 딕셔너리이어야 합니다. 복소수는 괄호로 둘러싸여 기록됨에 유의하십시오. 이것은 CSV 파일을 읽는 다른 프로그램에서 문제를 일으킬 수 있습니다 (복소수를 지원한다고 가정할 때).

csvwriter.writerow(row)

row 매개 변수를 현재 방언에 따라 포매팅해서, 기록기의 파일 객체에 씁니다.

버전 3.5에서 변경: 임의의 이터러블 지원 추가.

csvwriter.writerows(rows)

rows(위에서 설명한 row 객체의 이터러블)에 있는 모든 요소를 현재 방언에 따라 포매팅해서, 기록기의 파일 객체에 씁니다.

기록기 객체에는 다음과 같은 공용 어트리뷰트가 있습니다:

csvwriter.dialect

기록기가 사용 중인 방언의 읽기 전용 설명.

DictWriter 객체의 공용 메서드는 다음과 같습니다:

DictWriter.writeheader()

(생성자에 지정된 대로) 필드 이름을 담은 행을 기록합니다.

버전 3.2에 추가.

예제

CSV 파일을 읽는 가장 간단한 예:

import csv
with open('some.csv', newline='') as f:
    reader = csv.reader(f)
    for row in reader:
        print(row)

다른 형식의 파일 읽기:

import csv
with open('passwd', newline='') as f:
    reader = csv.reader(f, delimiter=':', quoting=csv.QUOTE_NONE)
    for row in reader:
        print(row)

대응하는 가장 간단한 쓰기 예는 다음과 같습니다:

import csv
with open('some.csv', 'w', newline='') as f:
    writer = csv.writer(f)
    writer.writerows(someiterable)

CSV 파일을 읽기로 여는 데 open()이 사용되므로, 파일은 기본적으로 시스템 기본 인코딩(locale.getpreferredencoding()를 참조하세요)을 사용하여 유니코드로 디코딩됩니다. 다른 인코딩을 사용하여 파일을 디코딩하려면 open의 encoding 인자를 사용하십시오:

import csv
with open('some.csv', newline='', encoding='utf-8') as f:
    reader = csv.reader(f)
    for row in reader:
        print(row)

시스템 기본 인코딩 이외의 다른 것으로 쓸 때도 마찬가지입니다: 출력 파일을 열 때 encoding 인자를 지정하십시오.

새로운 방언 등록하기:

import csv
csv.register_dialect('unixpwd', delimiter=':', quoting=csv.QUOTE_NONE)
with open('passwd', newline='') as f:
    reader = csv.reader(f, 'unixpwd')

판독기의 약간 더 고급 사용 — 에러 잡기와 보고:

import csv, sys
filename = 'some.csv'
with open(filename, newline='') as f:
    reader = csv.reader(f)
    try:
        for row in reader:
            print(row)
    except csv.Error as e:
        sys.exit('file {}, line {}: {}'.format(filename, reader.line_num, e))

또한, 모듈이 문자열 구문 분석을 직접 지원하지는 않지만, 쉽게 수행할 수 있습니다:

import csv
for row in csv.reader(['one,two,three']):
    print(row)

각주

1(1,2)

newline=''을 지정하지 않으면, 따옴표 처리된 필드에 포함된 줄 넘김 문자가 올바르게 해석되지 않으며, 줄 끝 표시에 \r\n을 사용하는 플랫폼에서 쓸 때 여분의 \r이 추가됩니다. csv 모듈은 자체 (유니버설) 줄 넘김 처리를 하므로, newline=''을 지정하는 것은 항상 안전합니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

파일 형식 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

파일 형식 »

|

configparser — Configuration file parser

Source code: Lib/configparser.py [https://github.com/python/cpython/tree/3.7/Lib/configparser.py]

This module provides the ConfigParser class which implements a basic configuration language which provides a structure similar to what’s found in Microsoft Windows INI files. You can use this to write Python programs which can be customized by end users easily.

참고

This library does not interpret or write the value-type prefixes used in the Windows Registry extended version of INI syntax.

더 보기

Module shlex

Support for creating Unix shell-like mini-languages which can be used as an alternate format for application configuration files.

Module json

The json module implements a subset of JavaScript syntax which can also be used for this purpose.

Quick Start

Let’s take a very basic configuration file that looks like this:

[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes

[bitbucket.org]
User = hg

[topsecret.server.com]
Port = 50022
ForwardX11 = no

The structure of INI files is described in the following section. Essentially, the file consists of sections, each of which contains keys with values. configparser classes can read and write such files. Let’s start by creating the above configuration file programmatically.

>>> import configparser
>>> config = configparser.ConfigParser()
>>> config['DEFAULT'] = {'ServerAliveInterval': '45',
...                      'Compression': 'yes',
...                      'CompressionLevel': '9'}
>>> config['bitbucket.org'] = {}
>>> config['bitbucket.org']['User'] = 'hg'
>>> config['topsecret.server.com'] = {}
>>> topsecret = config['topsecret.server.com']
>>> topsecret['Port'] = '50022'     # mutates the parser
>>> topsecret['ForwardX11'] = 'no'  # same here
>>> config['DEFAULT']['ForwardX11'] = 'yes'
>>> with open('example.ini', 'w') as configfile:
...   config.write(configfile)
...

As you can see, we can treat a config parser much like a dictionary. There are differences, outlined later, but the behavior is very close to what you would expect from a dictionary.

Now that we have created and saved a configuration file, let’s read it back and explore the data it holds.

>>> config = configparser.ConfigParser()
>>> config.sections()
[]
>>> config.read('example.ini')
['example.ini']
>>> config.sections()
['bitbucket.org', 'topsecret.server.com']
>>> 'bitbucket.org' in config
True
>>> 'bytebong.com' in config
False
>>> config['bitbucket.org']['User']
'hg'
>>> config['DEFAULT']['Compression']
'yes'
>>> topsecret = config['topsecret.server.com']
>>> topsecret['ForwardX11']
'no'
>>> topsecret['Port']
'50022'
>>> for key in config['bitbucket.org']:
...     print(key)
user
compressionlevel
serveraliveinterval
compression
forwardx11
>>> config['bitbucket.org']['ForwardX11']
'yes'

As we can see above, the API is pretty straightforward. The only bit of magic involves the DEFAULT section which provides default values for all other sections 1. Note also that keys in sections are case-insensitive and stored in lowercase 1.

Supported Datatypes

Config parsers do not guess datatypes of values in configuration files, always storing them internally as strings. This means that if you need other datatypes, you should convert on your own:

>>> int(topsecret['Port'])
50022
>>> float(topsecret['CompressionLevel'])
9.0

Since this task is so common, config parsers provide a range of handy getter methods to handle integers, floats and booleans. The last one is the most interesting because simply passing the value to bool() would do no good since bool('False') is still True. This is why config parsers also provide getboolean(). This method is case-insensitive and recognizes Boolean values from 'yes'/'no', 'on'/'off', 'true'/'false' and '1'/'0' 1. For example:

>>> topsecret.getboolean('ForwardX11')
False
>>> config['bitbucket.org'].getboolean('ForwardX11')
True
>>> config.getboolean('bitbucket.org', 'Compression')
True

Apart from getboolean(), config parsers also provide equivalent getint() and getfloat() methods. You can register your own converters and customize the provided ones. 1

Fallback Values

As with a dictionary, you can use a section’s get() method to provide fallback values:

>>> topsecret.get('Port')
'50022'
>>> topsecret.get('CompressionLevel')
'9'
>>> topsecret.get('Cipher')
>>> topsecret.get('Cipher', '3des-cbc')
'3des-cbc'

Please note that default values have precedence over fallback values. For instance, in our example the 'CompressionLevel' key was specified only in the 'DEFAULT' section. If we try to get it from the section 'topsecret.server.com', we will always get the default, even if we specify a fallback:

>>> topsecret.get('CompressionLevel', '3')
'9'

One more thing to be aware of is that the parser-level get() method provides a custom, more complex interface, maintained for backwards compatibility. When using this method, a fallback value can be provided via the fallback keyword-only argument:

>>> config.get('bitbucket.org', 'monster',
...            fallback='No such things as monsters')
'No such things as monsters'

The same fallback argument can be used with the getint(), getfloat() and getboolean() methods, for example:

>>> 'BatchMode' in topsecret
False
>>> topsecret.getboolean('BatchMode', fallback=True)
True
>>> config['DEFAULT']['BatchMode'] = 'no'
>>> topsecret.getboolean('BatchMode', fallback=True)
False

Supported INI File Structure

A configuration file consists of sections, each led by a [section] header, followed by key/value entries separated by a specific string (= or : by default 1). By default, section names are case sensitive but keys are not 1. Leading and trailing whitespace is removed from keys and values. Values can be omitted, in which case the key/value delimiter may also be left out. Values can also span multiple lines, as long as they are indented deeper than the first line of the value. Depending on the parser’s mode, blank lines may be treated as parts of multiline values or ignored.

Configuration files may include comments, prefixed by specific characters (# and ; by default 1). Comments may appear on their own on an otherwise empty line, possibly indented. 1

For example:

[Simple Values]
key=value
spaces in keys=allowed
spaces in values=allowed as well
spaces around the delimiter = obviously
you can also use : to delimit keys from values

[All Values Are Strings]
values like this: 1000000
or this: 3.14159265359
are they treated as numbers? : no
integers, floats and booleans are held as: strings
can use the API to get converted values directly: true

[Multiline Values]
chorus: I'm a lumberjack, and I'm okay
    I sleep all night and I work all day

[No Values]
key_without_value
empty string value here =

[You can use comments]
# like this
; or this

# By default only in an empty line.
# Inline comments can be harmful because they prevent users
# from using the delimiting characters as parts of values.
# That being said, this can be customized.

    [Sections Can Be Indented]
        can_values_be_as_well = True
        does_that_mean_anything_special = False
        purpose = formatting for readability
        multiline_values = are
            handled just fine as
            long as they are indented
            deeper than the first line
            of a value
        # Did I mention we can indent comments, too?

Interpolation of values

On top of the core functionality, ConfigParser supports interpolation. This means values can be preprocessed before returning them from get() calls.

class configparser.BasicInterpolation

The default implementation used by ConfigParser. It enables values to contain format strings which refer to other values in the same section, or values in the special default section 1. Additional default values can be provided on initialization.

For example:

[Paths]
home_dir: /Users
my_dir: %(home_dir)s/lumberjack
my_pictures: %(my_dir)s/Pictures

[Escape]
gain: 80%%  # use a %% to escape the % sign (% is the only character that needs to be escaped)

In the example above, ConfigParser with interpolation set to BasicInterpolation() would resolve %(home_dir)s to the value of home_dir (/Users in this case). %(my_dir)s in effect would resolve to /Users/lumberjack. All interpolations are done on demand so keys used in the chain of references do not have to be specified in any specific order in the configuration file.

With interpolation set to None, the parser would simply return %(my_dir)s/Pictures as the value of my_pictures and %(home_dir)s/lumberjack as the value of my_dir.

class configparser.ExtendedInterpolation

An alternative handler for interpolation which implements a more advanced syntax, used for instance in zc.buildout. Extended interpolation is using ${section:option} to denote a value from a foreign section. Interpolation can span multiple levels. For convenience, if the section: part is omitted, interpolation defaults to the current section (and possibly the default values from the special section).

For example, the configuration specified above with basic interpolation, would look like this with extended interpolation:

[Paths]
home_dir: /Users
my_dir: ${home_dir}/lumberjack
my_pictures: ${my_dir}/Pictures

[Escape]
cost: $$80  # use a $$ to escape the $ sign ($ is the only character that needs to be escaped)

Values from other sections can be fetched as well:

[Common]
home_dir: /Users
library_dir: /Library
system_dir: /System
macports_dir: /opt/local

[Frameworks]
Python: 3.2
path: ${Common:system_dir}/Library/Frameworks/

[Arthur]
nickname: Two Sheds
last_name: Jackson
my_dir: ${Common:home_dir}/twosheds
my_pictures: ${my_dir}/Pictures
python_dir: ${Frameworks:path}/Python/Versions/${Frameworks:Python}

Mapping Protocol Access

버전 3.2에 추가.

Mapping protocol access is a generic name for functionality that enables using custom objects as if they were dictionaries. In case of configparser, the mapping interface implementation is using the parser['section']['option'] notation.

parser['section'] in particular returns a proxy for the section’s data in the parser. This means that the values are not copied but they are taken from the original parser on demand. What’s even more important is that when values are changed on a section proxy, they are actually mutated in the original parser.

configparser objects behave as close to actual dictionaries as possible. The mapping interface is complete and adheres to the MutableMapping ABC. However, there are a few differences that should be taken into account:

By default, all keys in sections are accessible in a case-insensitive manner 1. E.g. for option in parser["section"] yields only optionxform’ed option key names. This means lowercased keys by default. At the same time, for a section that holds the key 'a', both expressions return True:

"a" in parser["section"]
"A" in parser["section"]

All sections include DEFAULTSECT values as well which means that .clear() on a section may not leave the section visibly empty. This is because default values cannot be deleted from the section (because technically they are not there). If they are overridden in the section, deleting causes the default value to be visible again. Trying to delete a default value causes a KeyError.

DEFAULTSECT cannot be removed from the parser:

trying to delete it raises ValueError,

parser.clear() leaves it intact,

parser.popitem() never returns it.

parser.get(section, option, **kwargs) - the second argument is not a fallback value. Note however that the section-level get() methods are compatible both with the mapping protocol and the classic configparser API.

parser.items() is compatible with the mapping protocol (returns a list of section_name, section_proxy pairs including the DEFAULTSECT). However, this method can also be invoked with arguments: parser.items(section, raw, vars). The latter call returns a list of option, value pairs for a specified section, with all interpolations expanded (unless raw=True is provided).

The mapping protocol is implemented on top of the existing legacy API so that subclasses overriding the original interface still should have mappings working as expected.

Customizing Parser Behaviour

There are nearly as many INI format variants as there are applications using it. configparser goes a long way to provide support for the largest sensible set of INI styles available. The default functionality is mainly dictated by historical background and it’s very likely that you will want to customize some of the features.

The most common way to change the way a specific config parser works is to use the __init__() options:

defaults, default value: None

This option accepts a dictionary of key-value pairs which will be initially put in the DEFAULT section. This makes for an elegant way to support concise configuration files that don’t specify values which are the same as the documented default.

Hint: if you want to specify default values for a specific section, use read_dict() before you read the actual file.

dict_type, default value: collections.OrderedDict

This option has a major impact on how the mapping protocol will behave and how the written configuration files look. With the default ordered dictionary, every section is stored in the order they were added to the parser. Same goes for options within sections.

An alternative dictionary type can be used for example to sort sections and options on write-back. You can also use a regular dictionary for performance reasons.

Please note: there are ways to add a set of key-value pairs in a single operation. When you use a regular dictionary in those operations, the order of the keys will be ordered because dict preserves order from Python 3.7. For example:

>>> parser = configparser.ConfigParser()
>>> parser.read_dict({'section1': {'key1': 'value1',
...                                'key2': 'value2',
...                                'key3': 'value3'},
...                   'section2': {'keyA': 'valueA',
...                                'keyB': 'valueB',
...                                'keyC': 'valueC'},
...                   'section3': {'foo': 'x',
...                                'bar': 'y',
...                                'baz': 'z'}
... })
>>> parser.sections()
['section1', 'section2', 'section3']
>>> [option for option in parser['section3']]
['foo', 'bar', 'baz']

allow_no_value, default value: False

Some configuration files are known to include settings without values, but which otherwise conform to the syntax supported by configparser. The allow_no_value parameter to the constructor can be used to indicate that such values should be accepted:

>>> import configparser

>>> sample_config = """
... [mysqld]
...   user = mysql
...   pid-file = /var/run/mysqld/mysqld.pid
...   skip-external-locking
...   old_passwords = 1
...   skip-bdb
...   # we don't need ACID today
...   skip-innodb
... """
>>> config = configparser.ConfigParser(allow_no_value=True)
>>> config.read_string(sample_config)

>>> # Settings with values are treated as before:
>>> config["mysqld"]["user"]
'mysql'

>>> # Settings without values provide None:
>>> config["mysqld"]["skip-bdb"]

>>> # Settings which aren't specified still raise an error:
>>> config["mysqld"]["does-not-exist"]
Traceback (most recent call last):
  ...
KeyError: 'does-not-exist'

delimiters, default value: ('=', ':')

Delimiters are substrings that delimit keys from values within a section. The first occurrence of a delimiting substring on a line is considered a delimiter. This means values (but not keys) can contain the delimiters.

See also the space_around_delimiters argument to ConfigParser.write().

comment_prefixes, default value: ('#', ';')

inline_comment_prefixes, default value: None

Comment prefixes are strings that indicate the start of a valid comment within a config file. comment_prefixes are used only on otherwise empty lines (optionally indented) whereas inline_comment_prefixes can be used after every valid value (e.g. section names, options and empty lines as well). By default inline comments are disabled and '#' and ';' are used as prefixes for whole line comments.

버전 3.2에서 변경: In previous versions of configparser behaviour matched comment_prefixes=('#',';') and inline_comment_prefixes=(';',).

Please note that config parsers don’t support escaping of comment prefixes so using inline_comment_prefixes may prevent users from specifying option values with characters used as comment prefixes. When in doubt, avoid setting inline_comment_prefixes. In any circumstances, the only way of storing comment prefix characters at the beginning of a line in multiline values is to interpolate the prefix, for example:

>>> from configparser import ConfigParser, ExtendedInterpolation
>>> parser = ConfigParser(interpolation=ExtendedInterpolation())
>>> # the default BasicInterpolation could be used as well
>>> parser.read_string("""
... [DEFAULT]
... hash = #
...
... [hashes]
... shebang =
...   ${hash}!/usr/bin/env python
...   ${hash} -*- coding: utf-8 -*-
...
... extensions =
...   enabled_extension
...   another_extension
...   #disabled_by_comment
...   yet_another_extension
...
... interpolation not necessary = if # is not at line start
... even in multiline values = line #1
...   line #2
...   line #3
... """)
>>> print(parser['hashes']['shebang'])

#!/usr/bin/env python
# -*- coding: utf-8 -*-
>>> print(parser['hashes']['extensions'])

enabled_extension
another_extension
yet_another_extension
>>> print(parser['hashes']['interpolation not necessary'])
if # is not at line start
>>> print(parser['hashes']['even in multiline values'])
line #1
line #2
line #3

strict, default value: True

When set to True, the parser will not allow for any section or option duplicates while reading from a single source (using read_file(), read_string() or read_dict()). It is recommended to use strict parsers in new applications.

버전 3.2에서 변경: In previous versions of configparser behaviour matched strict=False.

empty_lines_in_values, default value: True

In config parsers, values can span multiple lines as long as they are indented more than the key that holds them. By default parsers also let empty lines to be parts of values. At the same time, keys can be arbitrarily indented themselves to improve readability. In consequence, when configuration files get big and complex, it is easy for the user to lose track of the file structure. Take for instance:

[Section]
key = multiline
  value with a gotcha

 this = is still a part of the multiline value of 'key'

This can be especially problematic for the user to see if she’s using a proportional font to edit the file. That is why when your application does not need values with empty lines, you should consider disallowing them. This will make empty lines split keys every time. In the example above, it would produce two keys, key and this.

default_section, default value: configparser.DEFAULTSECT (that is: "DEFAULT")

The convention of allowing a special section of default values for other sections or interpolation purposes is a powerful concept of this library, letting users create complex declarative configurations. This section is normally called "DEFAULT" but this can be customized to point to any other valid section name. Some typical values include: "general" or "common". The name provided is used for recognizing default sections when reading from any source and is used when writing configuration back to a file. Its current value can be retrieved using the parser_instance.default_section attribute and may be modified at runtime (i.e. to convert files from one format to another).

interpolation, default value: configparser.BasicInterpolation

Interpolation behaviour may be customized by providing a custom handler through the interpolation argument. None can be used to turn off interpolation completely, ExtendedInterpolation() provides a more advanced variant inspired by zc.buildout. More on the subject in the dedicated documentation section. RawConfigParser has a default value of None.

converters, default value: not set

Config parsers provide option value getters that perform type conversion. By default getint(), getfloat(), and getboolean() are implemented. Should other getters be desirable, users may define them in a subclass or pass a dictionary where each key is a name of the converter and each value is a callable implementing said conversion. For instance, passing {'decimal': decimal.Decimal} would add getdecimal() on both the parser object and all section proxies. In other words, it will be possible to write both parser_instance.getdecimal('section', 'key', fallback=0) and parser_instance['section'].getdecimal('key', 0).

If the converter needs to access the state of the parser, it can be implemented as a method on a config parser subclass. If the name of this method starts with get, it will be available on all section proxies, in the dict-compatible form (see the getdecimal() example above).

More advanced customization may be achieved by overriding default values of these parser attributes. The defaults are defined on the classes, so they may be overridden by subclasses or by attribute assignment.

ConfigParser.BOOLEAN_STATES

By default when using getboolean(), config parsers consider the following values True: '1', 'yes', 'true', 'on' and the following values False: '0', 'no', 'false', 'off'. You can override this by specifying a custom dictionary of strings and their Boolean outcomes. For example:

>>> custom = configparser.ConfigParser()
>>> custom['section1'] = {'funky': 'nope'}
>>> custom['section1'].getboolean('funky')
Traceback (most recent call last):
...
ValueError: Not a boolean: nope
>>> custom.BOOLEAN_STATES = {'sure': True, 'nope': False}
>>> custom['section1'].getboolean('funky')
False

Other typical Boolean pairs include accept/reject or enabled/disabled.

ConfigParser.optionxform(option)

This method transforms option names on every read, get, or set operation. The default converts the name to lowercase. This also means that when a configuration file gets written, all keys will be lowercase. Override this method if that’s unsuitable. For example:

>>> config = """
... [Section1]
... Key = Value
...
... [Section2]
... AnotherKey = Value
... """
>>> typical = configparser.ConfigParser()
>>> typical.read_string(config)
>>> list(typical['Section1'].keys())
['key']
>>> list(typical['Section2'].keys())
['anotherkey']
>>> custom = configparser.RawConfigParser()
>>> custom.optionxform = lambda option: option
>>> custom.read_string(config)
>>> list(custom['Section1'].keys())
['Key']
>>> list(custom['Section2'].keys())
['AnotherKey']

참고

The optionxform function transforms option names to a canonical form. This should be an idempotent function: if the name is already in canonical form, it should be returned unchanged.

ConfigParser.SECTCRE

A compiled regular expression used to parse section headers. The default matches [section] to the name "section". Whitespace is considered part of the section name, thus [  larch  ] will be read as a section of name "  larch  ". Override this attribute if that’s unsuitable. For example:

>>> import re
>>> config = """
... [Section 1]
... option = value
...
... [  Section 2  ]
... another = val
... """
>>> typical = configparser.ConfigParser()
>>> typical.read_string(config)
>>> typical.sections()
['Section 1', '  Section 2  ']
>>> custom = configparser.ConfigParser()
>>> custom.SECTCRE = re.compile(r"\[ *(?P<header>[^]]+?) *\]")
>>> custom.read_string(config)
>>> custom.sections()
['Section 1', 'Section 2']

참고

While ConfigParser objects also use an OPTCRE attribute for recognizing option lines, it’s not recommended to override it because that would interfere with constructor options allow_no_value and delimiters.

Legacy API Examples

Mainly because of backwards compatibility concerns, configparser provides also a legacy API with explicit get/set methods. While there are valid use cases for the methods outlined below, mapping protocol access is preferred for new projects. The legacy API is at times more advanced, low-level and downright counterintuitive.

An example of writing to a configuration file:

import configparser

config = configparser.RawConfigParser()

# Please note that using RawConfigParser's set functions, you can assign
# non-string values to keys internally, but will receive an error when
# attempting to write to a file or when you get it in non-raw mode. Setting
# values using the mapping protocol or ConfigParser's set() does not allow
# such assignments to take place.
config.add_section('Section1')
config.set('Section1', 'an_int', '15')
config.set('Section1', 'a_bool', 'true')
config.set('Section1', 'a_float', '3.1415')
config.set('Section1', 'baz', 'fun')
config.set('Section1', 'bar', 'Python')
config.set('Section1', 'foo', '%(bar)s is %(baz)s!')

# Writing our configuration file to 'example.cfg'
with open('example.cfg', 'w') as configfile:
    config.write(configfile)

An example of reading the configuration file again:

import configparser

config = configparser.RawConfigParser()
config.read('example.cfg')

# getfloat() raises an exception if the value is not a float
# getint() and getboolean() also do this for their respective types
a_float = config.getfloat('Section1', 'a_float')
an_int = config.getint('Section1', 'an_int')
print(a_float + an_int)

# Notice that the next output does not interpolate '%(bar)s' or '%(baz)s'.
# This is because we are using a RawConfigParser().
if config.getboolean('Section1', 'a_bool'):
    print(config.get('Section1', 'foo'))

To get interpolation, use ConfigParser:

import configparser

cfg = configparser.ConfigParser()
cfg.read('example.cfg')

# Set the optional *raw* argument of get() to True if you wish to disable
# interpolation in a single get operation.
print(cfg.get('Section1', 'foo', raw=False))  # -> "Python is fun!"
print(cfg.get('Section1', 'foo', raw=True))   # -> "%(bar)s is %(baz)s!"

# The optional *vars* argument is a dict with members that will take
# precedence in interpolation.
print(cfg.get('Section1', 'foo', vars={'bar': 'Documentation',
                                       'baz': 'evil'}))

# The optional *fallback* argument can be used to provide a fallback value
print(cfg.get('Section1', 'foo'))
      # -> "Python is fun!"

print(cfg.get('Section1', 'foo', fallback='Monty is not.'))
      # -> "Python is fun!"

print(cfg.get('Section1', 'monster', fallback='No such things as monsters.'))
      # -> "No such things as monsters."

# A bare print(cfg.get('Section1', 'monster')) would raise NoOptionError
# but we can also use:

print(cfg.get('Section1', 'monster', fallback=None))
      # -> None

Default values are available in both types of ConfigParsers. They are used in interpolation if an option used is not defined elsewhere.

import configparser

# New instance with 'bar' and 'baz' defaulting to 'Life' and 'hard' each
config = configparser.ConfigParser({'bar': 'Life', 'baz': 'hard'})
config.read('example.cfg')

print(config.get('Section1', 'foo'))     # -> "Python is fun!"
config.remove_option('Section1', 'bar')
config.remove_option('Section1', 'baz')
print(config.get('Section1', 'foo'))     # -> "Life is hard!"

ConfigParser Objects

class configparser.ConfigParser(defaults=None, dict_type=collections.OrderedDict, allow_no_value=False, delimiters=('=', ':'), comment_prefixes=('#', ';'), inline_comment_prefixes=None, strict=True, empty_lines_in_values=True, default_section=configparser.DEFAULTSECT, interpolation=BasicInterpolation(), converters={})

The main configuration parser. When defaults is given, it is initialized into the dictionary of intrinsic defaults. When dict_type is given, it will be used to create the dictionary objects for the list of sections, for the options within a section, and for the default values.

When delimiters is given, it is used as the set of substrings that divide keys from values. When comment_prefixes is given, it will be used as the set of substrings that prefix comments in otherwise empty lines. Comments can be indented. When inline_comment_prefixes is given, it will be used as the set of substrings that prefix comments in non-empty lines.

When strict is True (the default), the parser won’t allow for any section or option duplicates while reading from a single source (file, string or dictionary), raising DuplicateSectionError or DuplicateOptionError. When empty_lines_in_values is False (default: True), each empty line marks the end of an option. Otherwise, internal empty lines of a multiline option are kept as part of the value. When allow_no_value is True (default: False), options without values are accepted; the value held for these is None and they are serialized without the trailing delimiter.

When default_section is given, it specifies the name for the special section holding default values for other sections and interpolation purposes (normally named "DEFAULT"). This value can be retrieved and changed on runtime using the default_section instance attribute.

Interpolation behaviour may be customized by providing a custom handler through the interpolation argument. None can be used to turn off interpolation completely, ExtendedInterpolation() provides a more advanced variant inspired by zc.buildout. More on the subject in the dedicated documentation section.

All option names used in interpolation will be passed through the optionxform() method just like any other option name reference. For example, using the default implementation of optionxform() (which converts option names to lower case), the values foo %(bar)s and foo %(BAR)s are equivalent.

When converters is given, it should be a dictionary where each key represents the name of a type converter and each value is a callable implementing the conversion from string to the desired datatype. Every converter gets its own corresponding get*() method on the parser object and section proxies.

버전 3.1에서 변경: The default dict_type is collections.OrderedDict.

버전 3.2에서 변경: allow_no_value, delimiters, comment_prefixes, strict, empty_lines_in_values, default_section and interpolation were added.

버전 3.5에서 변경: The converters argument was added.

버전 3.7에서 변경: The defaults argument is read with read_dict(), providing consistent behavior across the parser: non-string keys and values are implicitly converted to strings.

defaults()

Return a dictionary containing the instance-wide defaults.

sections()

Return a list of the sections available; the default section is not included in the list.

add_section(section)

Add a section named section to the instance. If a section by the given name already exists, DuplicateSectionError is raised. If the default section name is passed, ValueError is raised. The name of the section must be a string; if not, TypeError is raised.

버전 3.2에서 변경: Non-string section names raise TypeError.

has_section(section)

Indicates whether the named section is present in the configuration. The default section is not acknowledged.

options(section)

Return a list of options available in the specified section.

has_option(section, option)

If the given section exists, and contains the given option, return True; otherwise return False. If the specified section is None or an empty string, DEFAULT is assumed.

read(filenames, encoding=None)

Attempt to read and parse an iterable of filenames, returning a list of filenames which were successfully parsed.

If filenames is a string, a bytes object or a path-like object, it is treated as a single filename. If a file named in filenames cannot be opened, that file will be ignored. This is designed so that you can specify an iterable of potential configuration file locations (for example, the current directory, the user’s home directory, and some system-wide directory), and all existing configuration files in the iterable will be read.

If none of the named files exist, the ConfigParser instance will contain an empty dataset. An application which requires initial values to be loaded from a file should load the required file or files using read_file() before calling read() for any optional files:

import configparser, os

config = configparser.ConfigParser()
config.read_file(open('defaults.cfg'))
config.read(['site.cfg', os.path.expanduser('~/.myapp.cfg')],
            encoding='cp1250')

버전 3.2에 추가: The encoding parameter. Previously, all files were read using the default encoding for open().

버전 3.6.1에 추가: The filenames parameter accepts a path-like object.

버전 3.7에 추가: The filenames parameter accepts a bytes object.

read_file(f, source=None)

Read and parse configuration data from f which must be an iterable yielding Unicode strings (for example files opened in text mode).

Optional argument source specifies the name of the file being read. If not given and f has a name attribute, that is used for source; the default is '<???>'.

버전 3.2에 추가: Replaces readfp().

read_string(string, source='<string>')

Parse configuration data from a string.

Optional argument source specifies a context-specific name of the string passed. If not given, '<string>' is used. This should commonly be a filesystem path or a URL.

버전 3.2에 추가.

read_dict(dictionary, source='<dict>')

Load configuration from any object that provides a dict-like items() method. Keys are section names, values are dictionaries with keys and values that should be present in the section. If the used dictionary type preserves order, sections and their keys will be added in order. Values are automatically converted to strings.

Optional argument source specifies a context-specific name of the dictionary passed. If not given, <dict> is used.

This method can be used to copy state between parsers.

버전 3.2에 추가.

get(section, option, *, raw=False, vars=None[, fallback])

Get an option value for the named section. If vars is provided, it must be a dictionary. The option is looked up in vars (if provided), section, and in DEFAULTSECT in that order. If the key is not found and fallback is provided, it is used as a fallback value. None can be provided as a fallback value.

All the '%' interpolations are expanded in the return values, unless the raw argument is true. Values for interpolation keys are looked up in the same manner as the option.

버전 3.2에서 변경: Arguments raw, vars and fallback are keyword only to protect users from trying to use the third argument as the fallback fallback (especially when using the mapping protocol).

getint(section, option, *, raw=False, vars=None[, fallback])

A convenience method which coerces the option in the specified section to an integer. See get() for explanation of raw, vars and fallback.

getfloat(section, option, *, raw=False, vars=None[, fallback])

A convenience method which coerces the option in the specified section to a floating point number. See get() for explanation of raw, vars and fallback.

getboolean(section, option, *, raw=False, vars=None[, fallback])

A convenience method which coerces the option in the specified section to a Boolean value. Note that the accepted values for the option are '1', 'yes', 'true', and 'on', which cause this method to return True, and '0', 'no', 'false', and 'off', which cause it to return False. These string values are checked in a case-insensitive manner. Any other value will cause it to raise ValueError. See get() for explanation of raw, vars and fallback.

items(raw=False, vars=None)

items(section, raw=False, vars=None)

When section is not given, return a list of section_name, section_proxy pairs, including DEFAULTSECT.

Otherwise, return a list of name, value pairs for the options in the given section. Optional arguments have the same meaning as for the get() method.

set(section, option, value)

If the given section exists, set the given option to the specified value; otherwise raise NoSectionError. option and value must be strings; if not, TypeError is raised.

write(fileobject, space_around_delimiters=True)

Write a representation of the configuration to the specified file object, which must be opened in text mode (accepting strings). This representation can be parsed by a future read() call. If space_around_delimiters is true, delimiters between keys and values are surrounded by spaces.

remove_option(section, option)

Remove the specified option from the specified section. If the section does not exist, raise NoSectionError. If the option existed to be removed, return True; otherwise return False.

remove_section(section)

Remove the specified section from the configuration. If the section in fact existed, return True. Otherwise return False.

optionxform(option)

Transforms the option name option as found in an input file or as passed in by client code to the form that should be used in the internal structures. The default implementation returns a lower-case version of option; subclasses may override this or client code can set an attribute of this name on instances to affect this behavior.

You don’t need to subclass the parser to use this method, you can also set it on an instance, to a function that takes a string argument and returns a string. Setting it to str, for example, would make option names case sensitive:

cfgparser = ConfigParser()
cfgparser.optionxform = str

Note that when reading configuration files, whitespace around the option names is stripped before optionxform() is called.

readfp(fp, filename=None)

버전 3.2부터 폐지: Use read_file() instead.

버전 3.2에서 변경: readfp() now iterates on fp instead of calling fp.readline().

For existing code calling readfp() with arguments which don’t support iteration, the following generator may be used as a wrapper around the file-like object:

def readline_generator(fp):
    line = fp.readline()
    while line:
        yield line
        line = fp.readline()

Instead of parser.readfp(fp) use parser.read_file(readline_generator(fp)).

configparser.MAX_INTERPOLATION_DEPTH

The maximum depth for recursive interpolation for get() when the raw parameter is false. This is relevant only when the default interpolation is used.

RawConfigParser Objects

class configparser.RawConfigParser(defaults=None, dict_type=collections.OrderedDict, allow_no_value=False, *, delimiters=('=', ':'), comment_prefixes=('#', ';'), inline_comment_prefixes=None, strict=True, empty_lines_in_values=True, default_section=configparser.DEFAULTSECT[, interpolation])

Legacy variant of the ConfigParser. It has interpolation disabled by default and allows for non-string section names, option names, and values via its unsafe add_section and set methods, as well as the legacy defaults= keyword argument handling.

참고

Consider using ConfigParser instead which checks types of the values to be stored internally. If you don’t want interpolation, you can use ConfigParser(interpolation=None).

add_section(section)

Add a section named section to the instance. If a section by the given name already exists, DuplicateSectionError is raised. If the default section name is passed, ValueError is raised.

Type of section is not checked which lets users create non-string named sections. This behaviour is unsupported and may cause internal errors.

set(section, option, value)

If the given section exists, set the given option to the specified value; otherwise raise NoSectionError. While it is possible to use RawConfigParser (or ConfigParser with raw parameters set to true) for internal storage of non-string values, full functionality (including interpolation and output to files) can only be achieved using string values.

This method lets users assign non-string values to keys internally. This behaviour is unsupported and will cause errors when attempting to write to a file or get it in non-raw mode. Use the mapping protocol API which does not allow such assignments to take place.

Exceptions

exception configparser.Error

Base class for all other configparser exceptions.

exception configparser.NoSectionError

Exception raised when a specified section is not found.

exception configparser.DuplicateSectionError

Exception raised if add_section() is called with the name of a section that is already present or in strict parsers when a section if found more than once in a single input file, string or dictionary.

버전 3.2에 추가: Optional source and lineno attributes and arguments to __init__() were added.

exception configparser.DuplicateOptionError

Exception raised by strict parsers if a single option appears twice during reading from a single file, string or dictionary. This catches misspellings and case sensitivity-related errors, e.g. a dictionary may have two keys representing the same case-insensitive configuration key.

exception configparser.NoOptionError

Exception raised when a specified option is not found in the specified section.

exception configparser.InterpolationError

Base class for exceptions raised when problems occur performing string interpolation.

exception configparser.InterpolationDepthError

Exception raised when string interpolation cannot be completed because the number of iterations exceeds MAX_INTERPOLATION_DEPTH. Subclass of InterpolationError.

exception configparser.InterpolationMissingOptionError

Exception raised when an option referenced from a value does not exist. Subclass of InterpolationError.

exception configparser.InterpolationSyntaxError

Exception raised when the source text into which substitutions are made does not conform to the required syntax. Subclass of InterpolationError.

exception configparser.MissingSectionHeaderError

Exception raised when attempting to parse a file which has no section headers.

exception configparser.ParsingError

Exception raised when errors occur attempting to parse a file.

버전 3.2에서 변경: The filename attribute and __init__() argument were renamed to source for consistency.

Footnotes

1(1,2,3,4,5,6,7,8,9,10)

Config parsers allow for heavy customization. If you are interested in changing the behaviour outlined by the footnote reference, consult the Customizing Parser Behaviour section.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

파일 형식 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

파일 형식 »

|

netrc — netrc 파일 처리

소스 코드: Lib/netrc.py [https://github.com/python/cpython/tree/3.7/Lib/netrc.py]

netrc 클래스는 유닉스 ftp 프로그램과 다른 FTP 클라이언트가 사용하는 netrc 파일 형식을 구문 분석하고 캡슐화합니다.

class netrc.netrc([file])

netrc 인스턴스나 서브 클래스 인스턴스는 netrc 파일의 데이터를 캡슐화합니다. 초기화 인자가 있으면 구문 분석할 파일을 지정합니다. 인자를 지정하지 않으면, os.path.expanduser()에 의해 결정된 사용자 홈 디렉터리에 있는 파일 .netrc를 읽습니다. 그렇지 않으면, FileNotFoundError 예외가 발생합니다. 구문 분석 에러는 파일 이름, 줄 번호 및 종료 토큰을 포함하는 진단 정보로 NetrcParseError를 발생시킵니다. POSIX 시스템에서 인자가 지정되지 않을 때, 파일 소유권이나 권한이 안전하지 않으면 (프로세스를 실행하는 사용자가 아닌 다른 사용자가 소유하거나 다른 모든 사용자가 읽기 또는 쓰기로 액세스할 수 있는 경우), .netrc 파일에 암호가 존재하면 NetrcParseError가 발생합니다. 이것은 ftp와 .netrc를 사용하는 다른 프로그램과 동등한 보안 행동을 구현합니다.

버전 3.4에서 변경: POSIX 권한 검사를 추가했습니다.

버전 3.7에서 변경: file이 인자로 전달되지 않으면 os.path.expanduser()가 .netrc 파일의 위치를 찾는 데 사용됩니다.

exception netrc.NetrcParseError

소스 텍스트에 문법적인 에러가 있을 때 netrc 클래스에서 발생하는 예외. 이 예외 인스턴스는 세 가지 흥미로운 어트리뷰트를 제공합니다. msg는 에러의 텍스트 설명이고, filename은 소스 파일의 이름이며, lineno는 에러가 발견된 줄 번호입니다.

netrc 객체

netrc 인스턴스에는 다음과 같은 메서드가 있습니다:

netrc.authenticators(host)

host에 대한 인증 자의 3-tuple (login, account, password)를 반환합니다. netrc 파일에 주어진 호스트에 대한 항목이 없으면 ‘default’ 항목과 연관된 튜플을 반환합니다. 일치하는 호스트도 기본 항목도 사용할 수 없으면 None을 반환합니다.

netrc.__repr__()

클래스 데이터를 netrc 파일의 형식의 문자열로 덤프합니다. (이것은 주석을 버리고 엔트리를 재정렬할 수 있습니다.)

netrc의 인스턴스에는 공개 인스턴스 변수가 있습니다:

netrc.hosts

호스트 이름을 (login, account, password) 튜플에 매핑하는 딕셔너리. ‘default’ 항목이 있으면 그 이름의 의사 호스트로 표시됩니다.

netrc.macros

매크로 이름을 문자열 리스트에 매핑하는 딕셔너리.

참고

암호는 ASCII 문자 집합의 부분집합으로 제한됩니다. 모든 ASCII 구두점을 암호에 사용할 수 있지만, 공백과 인쇄 할 수 없는 문자는 암호에 사용할 수 없습니다. 이것은 .netrc 파일이 구문 분석되는 방식으로 인한 제한 사항이며 향후 제거될 수 있습니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

파일 형식 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

파일 형식 »

|

xdrlib — XDR 데이터 인코딩과 디코딩

소스 코드: Lib/xdrlib.py [https://github.com/python/cpython/tree/3.7/Lib/xdrlib.py]

xdrlib 모듈은 1987년 6월에 Sun Microsystems, Inc.가 작성한 RFC 1014 [https://tools.ietf.org/html/rfc1014.html]에 설명된 외부 데이터 표현 표준(External Data Representation Standard)을 지원합니다. 이 모듈은 RFC에 설명된 대부분의 데이터형을 지원합니다.

xdrlib 모듈은 두 개의 클래스를 정의합니다. 하나는 변수를 XDR 표현으로 패킹하고, 다른 하나는 XDR 표현으로부터 언패킹합니다. 또한, 두 가지 예외 클래스가 있습니다.

class xdrlib.Packer

Packer는 데이터를 XDR 표현으로 패킹하는 클래스입니다. Packer 클래스는 인자 없이 인스턴스화됩니다.

class xdrlib.Unpacker(data)

Unpacker는 문자열 버퍼에서 XDR 데이터값을 언패킹하는 반대 클래스입니다. 입력 버퍼는 data로 주어집니다.

더 보기

RFC 1014 [https://tools.ietf.org/html/rfc1014.html] - XDR: External Data Representation Standard

이 RFC는 이 모듈이 처음 작성되었을 당시에 XDR이었던 데이터의 인코딩을 정의합니다. RFC 1832 [https://tools.ietf.org/html/rfc1832.html]로 개정되었습니다.

RFC 1832 [https://tools.ietf.org/html/rfc1832.html] - XDR: External Data Representation Standard

XDR의 개정된 정의를 제공하는 최신 RFC

Packer 객체

Packer 인스턴스에는 다음과 같은 메서드가 있습니다:

Packer.get_buffer()

현재의 팩 버퍼를 문자열로 반환합니다.

Packer.reset()

팩 버퍼를 빈 문자열로 재설정합니다.

일반적으로, 적절한 pack_type() 메서드를 호출하여 가장 자주 쓰이는 XDR 데이터형을 팩할 수 있습니다. 각 메서드는 팩할 값인 단일 인자를 취합니다. 다음과 같은 간단한 데이터형의 패킹 메서드가 지원됩니다: pack_uint(), pack_int(), pack_enum(), pack_bool(), pack_uhyper() 및 pack_hyper().

Packer.pack_float(value)

단정밀도 부동 소수점 숫자 value를 팩합니다.

Packer.pack_double(value)

배정밀도 부동 소수점 숫자 value를 팩합니다.

다음 메서드는 문자열, 바이트열 및 불투명 데이터의 패킹을 지원합니다:

Packer.pack_fstring(n, s)

고정 길이 문자열 s를 팩합니다. n는 문자열의 길이이지만 데이터 버퍼에 팩 되지는 않습니다. 4바이트 정렬을 보장하는 데 필요하면 문자열에 null 바이트가 채워집니다.

Packer.pack_fopaque(n, data)

pack_fstring()과 유사하게, 고정 길이의 불투명한 데이터 스트림을 팩합니다.

Packer.pack_string(s)

가변 길이 문자열 s를 팩합니다. 문자열의 길이를 먼저 부호 없는 정수로 팩하고, 문자열 데이터는 pack_fstring()으로 팩합니다.

Packer.pack_opaque(data)

pack_string()과 유사하게, 가변 길이 불투명 데이터 문자열을 팩합니다.

Packer.pack_bytes(bytes)

pack_string()과 유사하게, 가변 길이 바이트 스트림을 팩합니다.

다음 메서드는 배열과 리스트의 패킹을 지원합니다:

Packer.pack_list(list, pack_item)

균질한 항목의 list를 팩합니다. 이 메서드는 크기가 결정되지 않은 리스트에 유용합니다; 즉, 전체 리스트를 검사해볼 때까지 크기를 알 수 없습니다. 리스트의 각 항목에 대해 부호 없는 정수 1이 먼저 팩 되고, 그다음에 리스트로부터의 데이터값이 옵니다. pack_item은 개별 항목을 팩하려고 호출되는 함수입니다. 리스트의 끝에서 부호 없는 정수 0이 팩 됩니다.

예를 들어, 정수 리스트를 팩하려면, 이런 코드를 사용할 수 있습니다:

import xdrlib
p = xdrlib.Packer()
p.pack_list([1, 2, 3], p.pack_int)

Packer.pack_farray(n, array, pack_item)

균질한 항목의 고정 길이 리스트(array)를 팩합니다. n은 리스트의 길이입니다; 버퍼에 팩 되지 않지만, len(array)가 n과 같지 않으면 ValueError 예외가 발생합니다. 위와 같이, pack_item은 각 요소를 팩하는 데 사용되는 함수입니다.

Packer.pack_array(list, pack_item)

균질한 항목의 가변 길이 list를 팩합니다. 먼저, 리스트의 길이가 부호 없는 정수로 팩 되고, 각 요소는 위의 pack_farray()와 같이 팩 됩니다.

Unpacker 객체

Unpacker 클래스는 다음과 같은 메서드를 제공합니다:

Unpacker.reset(data)

지정된 data로 문자열 버퍼를 재설정합니다.

Unpacker.get_position()

데이터 버퍼의 현재의 언팩 위치를 반환합니다.

Unpacker.set_position(position)

데이터 버퍼 언팩 위치를 position으로 설정합니다. get_position()과 set_position() 사용 시 주의해야 합니다.

Unpacker.get_buffer()

현재의 언팩 데이터 버퍼를 문자열로 반환합니다.

Unpacker.done()

언팩 완료를 나타냅니다. 모든 데이터가 언팩 되지 않았으면 Error 예외를 발생시킵니다.

또한, Packer로 팩할 수 있는 모든 데이터형은 Unpacker로 언팩할 수 있습니다. 언패킹 메서드는 unpack_type() 형식이며 인자를 받아들이지 않습니다. 이것들은 언팩 된 객체를 반환합니다.

Unpacker.unpack_float()

단정밀도 부동 소수점 숫자를 언팩합니다.

Unpacker.unpack_double()

unpack_float()와 유사하게, 배정밀도 부동 소수점 숫자를 언팩합니다.

또한, 다음 메서드는 문자열, 바이트열 및 불투명 데이터를 언팩합니다:

Unpacker.unpack_fstring(n)

고정 길이 문자열을 언팩하고 반환합니다. n는 예상 문자 수입니다. 4바이트의 정렬을 보장하기 위해서, null 바이트로 채워졌다고 가정합니다.

Unpacker.unpack_fopaque(n)

unpack_fstring()과 유사하게, 고정 길이 불투명 데이터 스트림을 언팩하고 반환합니다.

Unpacker.unpack_string()

가변 길이 문자열을 언팩하고 반환합니다. 문자열의 길이를 먼저 부호 없는 정수로 언팩한 다음, 문자열 데이터를 unpack_fstring()으로 언팩합니다.

Unpacker.unpack_opaque()

unpack_string()과 유사하게, 가변 길이 불투명 데이터 문자열을 언팩하고 반환합니다.

Unpacker.unpack_bytes()

unpack_string()과 유사하게, 가변 길이 바이트 스트림을 언팩하고 반환합니다.

다음 메서드는 배열과 리스트의 언패킹을 지원합니다:

Unpacker.unpack_list(unpack_item)

균질한 항목의 리스트를 언팩하고 반환합니다. 리스트는 한 번에 한 요소씩 먼저 부호 없는 정수 플래그를 언팩해서 언팩합니다. 플래그가 1이면, 항목이 언팩되어 리스트에 추가됩니다. 0 플래그는 리스트의 끝을 나타냅니다. unpack_item은 항목을 언팩하는 함수입니다.

Unpacker.unpack_farray(n, unpack_item)

균질한 항목의 고정 길이 배열을 언팩하고 (리스트로) 반환합니다. n은 버퍼에서 예상되는 리스트 요소의 수입니다. 위와 같이, unpack_item은 각 요소를 언팩하는 데 사용되는 함수입니다.

Unpacker.unpack_array(unpack_item)

균질한 항목의 가변 길이 list를 언팩하고 반환합니다. 먼저, 리스트의 길이를 부호 없는 정수로 언팩하고, 각 요소는 위의 unpack_farray()처럼 언팩됩니다.

예외

이 모듈의 예외는 클래스 인스턴스로 코딩됩니다:

exception xdrlib.Error

베이스 예외 클래스. Error에는 에러에 대한 설명을 포함하는 공용 어트리뷰트 msg가 하나 있습니다.

exception xdrlib.ConversionError

Error에서 파생된 클래스. 추가 인스턴스 변수가 없습니다.

다음은 이러한 예외 중 하나를 잡는 방법의 예입니다:

import xdrlib
p = xdrlib.Packer()
try:
    p.pack_double(8.01)
except xdrlib.ConversionError as instance:
    print('packing the double failed:', instance.msg)

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

파일 형식 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

파일 형식 »

|

plistlib — 맥 OS X .plist 파일 생성과 구문 분석

소스 코드: Lib/plistlib.py [https://github.com/python/cpython/tree/3.7/Lib/plistlib.py]

이 모듈은 주로 Mac OS X에서 사용되는 “프로퍼티 리스트(property list)” 파일을 읽고 쓰는 인터페이스를 제공하며 바이너리와 XML plist 파일을 모두 지원합니다.

프로퍼티 리스트 (.plist) 파일 형식은 딕셔너리, 리스트, 숫자 및 문자열과 같은 기본 객체 형을 지원하는 간단한 직렬화입니다. 일반적으로 최상위 객체는 딕셔너리입니다.

plist 파일을 쓰고 구문 분석하려면, dump()와 load() 함수를 사용하십시오.

plist 데이터를 바이트열 객체로 작업하려면, dumps()와 loads()를 사용하십시오.

값은 문자열, 정수, 부동 소수점, 논릿값, 튜플, 리스트, 딕셔너리 (단, 문자열 키만 가능), Data, bytes, bytesarray 또는 datetime.datetime 객체일 수 있습니다.

버전 3.4에서 변경: 새 API, 이전 API는 폐지되었습니다. 바이너리 형식 plist에 대한 지원이 추가되었습니다.

더 보기

PList manual page [https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/PropertyLists/]

애플의 파일 형식 설명서.

이 모듈은 다음 함수를 정의합니다:

plistlib.load(fp, *, fmt=None, use_builtin_types=True, dict_type=dict)

plist 파일을 읽습니다. fp는 읽을 수 있는 바이너리 파일 객체여야 합니다. 해독된 루트 객체를 반환합니다 (일반적으로 딕셔너리입니다).

fmt는 파일의 형식이며 다음 값이 유효합니다:

None: 파일 형식을 자동 감지

FMT_XML: XML 파일 형식

FMT_BINARY: 바이너리 plist 형식

use_builtin_types가 참(기본값)이면 바이너리 데이터가 bytes의 인스턴스로 반환되고, 그렇지 않으면 Data의 인스턴스로 반환됩니다.

dict_type은 plist 파일에서 읽은 딕셔너리에 사용되는 형입니다.

FMT_XML 형식의 XML 데이터는 xml.parsers.expat 의 Expat 구문 분석기로 구문 분석됩니다 – 잘못된 형식의 XML로 인한 예외에 대해서는 해당 설명서를 참조하십시오. 알 수 없는 엘리먼트는 plist 구문분석기에서 단순히 무시됩니다.

바이너리 형식의 구문 분석기는 파일을 구문 분석할 수 없을 때 InvalidFileException를 발생시킵니다.

버전 3.4에 추가.

plistlib.loads(data, *, fmt=None, use_builtin_types=True, dict_type=dict)

바이트열 객체에서 plist를 로드합니다. 키워드 인자에 대한 설명은 load()를 참조하십시오.

버전 3.4에 추가.

plistlib.dump(value, fp, *, fmt=FMT_XML, sort_keys=True, skipkeys=False)

plist 파일에 value를 씁니다. Fp는 쓰기 가능한 바이너리 파일 객체여야 합니다.

fmt 인자는 plist 파일의 형식을 지정하며 다음 값 중 하나일 수 있습니다:

FMT_XML: XML 형식의 plist 파일

FMT_BINARY: 바이너리 형식의 plist 파일

sort_keys가 참(기본값)이면 딕셔너리의 키가 정렬된 순서로 plist에 기록되고, 그렇지 않으면 딕셔너리의 이터레이션 순서로 기록됩니다.

skipkeys가 거짓(기본값)일 때, 딕셔너리의 키가 문자열이 아니면 함수는 TypeError를 발생시킵니다. 그렇지 않으면 해당 키를 건너뜁니다.

객체가 지원되지 않는 형이거나 지원되지 않는 형의 객체를 포함하는 컨테이너면 TypeError가 발생합니다.

(바이너리) plist 파일에서 표현할 수 없는 정숫값은 OverflowError를 발생시킵니다.

버전 3.4에 추가.

plistlib.dumps(value, *, fmt=FMT_XML, sort_keys=True, skipkeys=False)

plist 형식의 바이트열 객체로 value를 반환합니다. 이 함수의 키워드 인자에 대한 설명은 dump() 설명서를 참조하십시오.

버전 3.4에 추가.

다음 함수는 폐지되었습니다:

plistlib.readPlist(pathOrFile)

plist 파일을 읽습니다. pathOrFile은 파일 이름이나 (읽기 가능한 바이너리) 파일 객체일 수 있습니다. 해독된 루트 객체를 반환합니다 (일반적으로 딕셔너리입니다).

이 함수는 load()를 호출하여 실제 작업을 수행합니다. 키워드 인자에 대한 설명은 그 함수 문서를 참조하십시오.

버전 3.4부터 폐지: 대신 load()를 사용하십시오.

버전 3.7에서 변경: 결과의 딕셔너리 값은 이제 평범한 dict입니다. 더는 이 딕셔너리의 항목을 액세스하기 위해 어트리뷰트 액세스를 사용할 수 없습니다.

plistlib.writePlist(rootObject, pathOrFile)

XML plist 파일에 rootObject를 씁니다. pathOrFile는 파일 이름이나 (쓰기 가능한 바이너리) 파일 객체일 수 있습니다

버전 3.4부터 폐지: 대신 dump()를 사용하십시오.

plistlib.readPlistFromBytes(data)

바이트열 객체에서 plist 데이터를 읽습니다. 루트 객체를 반환합니다.

키워드 인자에 대한 설명은 load()를 참조하십시오.

버전 3.4부터 폐지: 대신 loads()를 사용하십시오.

버전 3.7에서 변경: 결과의 딕셔너리 값은 이제 평범한 dict입니다. 더는 이 딕셔너리의 항목을 액세스하기 위해 어트리뷰트 액세스를 사용할 수 없습니다.

plistlib.writePlistToBytes(rootObject)

rootObject를 XML plist 형식의 바이트열 객체로 반환합니다.

버전 3.4부터 폐지: 대신 dumps()를 사용하십시오.

다음 클래스를 사용할 수 있습니다:

class plistlib.Data(data)

바이트열 객체 data를 감싸는 “데이터” 래퍼 객체를 반환합니다. plist 와 상호 변환하는 함수에서 plist에서 사용할 수 있는 <data> 형을 나타내기 위해 사용됩니다.

하나의 어트리뷰트 data가 있는데, 저장된 파이썬 바이트열 객체를 조회하는 데 사용될 수 있습니다.

버전 3.4부터 폐지: 대신 bytes 객체를 사용하십시오.

다음 상수를 사용할 수 있습니다:

plistlib.FMT_XML

plist 파일의 XML 형식.

버전 3.4에 추가.

plistlib.FMT_BINARY

plist 파일의 바이너리 형식

버전 3.4에 추가.

예제

plist 만들기:

pl = dict(
    aString = "Doodah",
    aList = ["A", "B", 12, 32.1, [1, 2, 3]],
    aFloat = 0.1,
    anInt = 728,
    aDict = dict(
        anotherString = "<hello & hi there!>",
        aThirdString = "M\xe4ssig, Ma\xdf",
        aTrueValue = True,
        aFalseValue = False,
    ),
    someData = b"<binary gunk>",
    someMoreData = b"<lots of binary gunk>" * 10,
    aDate = datetime.datetime.fromtimestamp(time.mktime(time.gmtime())),
)
with open(fileName, 'wb') as fp:
    dump(pl, fp)

plist 구문 분석하기:

with open(fileName, 'rb') as fp:
    pl = load(fp)
print(pl["aKey"])

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

파일 형식 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

|

암호화 서비스

이 장에서 설명하는 모듈은 다양한 암호화 알고리즘을 구현합니다. 가용성은 설치에 달려있습니다. 유닉스 시스템에서는 crypt 모듈을 사용할 수도 있습니다. 다음은 개요입니다:

hashlib — Secure hashes and message digests

Hash algorithms

SHAKE variable length digests

Key derivation

BLAKE2

Creating hash objects

Constants

Examples

Simple hashing

Using different digest sizes

Keyed hashing

Randomized hashing

Personalization

Tree mode

Credits

hmac — 메시지 인증을 위한 키 해싱

secrets — 비밀 관리를 위한 안전한 난수 생성

난수

토큰 생성

토큰은 몇 바이트를 사용해야 합니까?

기타 함수

조리법과 모범 사례

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

암호화 서비스 »

|

hashlib — Secure hashes and message digests

Source code: Lib/hashlib.py [https://github.com/python/cpython/tree/3.7/Lib/hashlib.py]

This module implements a common interface to many different secure hash and message digest algorithms. Included are the FIPS secure hash algorithms SHA1, SHA224, SHA256, SHA384, and SHA512 (defined in FIPS 180-2) as well as RSA’s MD5 algorithm (defined in Internet RFC 1321 [https://tools.ietf.org/html/rfc1321.html]). The terms “secure hash” and “message digest” are interchangeable. Older algorithms were called message digests. The modern term is secure hash.

참고

If you want the adler32 or crc32 hash functions, they are available in the zlib module.

경고

Some algorithms have known hash collision weaknesses, refer to the “See also” section at the end.

Hash algorithms

There is one constructor method named for each type of hash. All return a hash object with the same simple interface. For example: use sha256() to create a SHA-256 hash object. You can now feed this object with bytes-like objects (normally bytes) using the update() method. At any point you can ask it for the digest of the concatenation of the data fed to it so far using the digest() or hexdigest() methods.

참고

For better multithreading performance, the Python GIL is released for data larger than 2047 bytes at object creation or on update.

참고

Feeding string objects into update() is not supported, as hashes work on bytes, not on characters.

Constructors for hash algorithms that are always present in this module are sha1(), sha224(), sha256(), sha384(), sha512(), blake2b(), and blake2s(). md5() is normally available as well, though it may be missing if you are using a rare “FIPS compliant” build of Python. Additional algorithms may also be available depending upon the OpenSSL library that Python uses on your platform. On most platforms the sha3_224(), sha3_256(), sha3_384(), sha3_512(), shake_128(), shake_256() are also available.

버전 3.6에 추가: SHA3 (Keccak) and SHAKE constructors sha3_224(), sha3_256(), sha3_384(), sha3_512(), shake_128(), shake_256().

버전 3.6에 추가: blake2b() and blake2s() were added.

For example, to obtain the digest of the byte string b'Nobody inspects the spammish repetition':

>>> import hashlib
>>> m = hashlib.sha256()
>>> m.update(b"Nobody inspects")
>>> m.update(b" the spammish repetition")
>>> m.digest()
b'\x03\x1e\xdd}Ae\x15\x93\xc5\xfe\\\x00o\xa5u+7\xfd\xdf\xf7\xbcN\x84:\xa6\xaf\x0c\x95\x0fK\x94\x06'
>>> m.digest_size
32
>>> m.block_size
64

More condensed:

>>> hashlib.sha224(b"Nobody inspects the spammish repetition").hexdigest()
'a4337bc45a8fc544c03f52dc550cd6e1e87021bc896588bd79e901e2'

hashlib.new(name[, data])

Is a generic constructor that takes the string name of the desired algorithm as its first parameter. It also exists to allow access to the above listed hashes as well as any other algorithms that your OpenSSL library may offer. The named constructors are much faster than new() and should be preferred.

Using new() with an algorithm provided by OpenSSL:

>>> h = hashlib.new('ripemd160')
>>> h.update(b"Nobody inspects the spammish repetition")
>>> h.hexdigest()
'cc4a5ce1b3df48aec5d22d1f16b894a0b894eccc'

Hashlib provides the following constant attributes:

hashlib.algorithms_guaranteed

A set containing the names of the hash algorithms guaranteed to be supported by this module on all platforms. Note that ‘md5’ is in this list despite some upstream vendors offering an odd “FIPS compliant” Python build that excludes it.

버전 3.2에 추가.

hashlib.algorithms_available

A set containing the names of the hash algorithms that are available in the running Python interpreter. These names will be recognized when passed to new(). algorithms_guaranteed will always be a subset. The same algorithm may appear multiple times in this set under different names (thanks to OpenSSL).

버전 3.2에 추가.

The following values are provided as constant attributes of the hash objects returned by the constructors:

hash.digest_size

The size of the resulting hash in bytes.

hash.block_size

The internal block size of the hash algorithm in bytes.

A hash object has the following attributes:

hash.name

The canonical name of this hash, always lowercase and always suitable as a parameter to new() to create another hash of this type.

버전 3.4에서 변경: The name attribute has been present in CPython since its inception, but until Python 3.4 was not formally specified, so may not exist on some platforms.

A hash object has the following methods:

hash.update(data)

Update the hash object with the bytes-like object. Repeated calls are equivalent to a single call with the concatenation of all the arguments: m.update(a); m.update(b) is equivalent to m.update(a+b).

버전 3.1에서 변경: The Python GIL is released to allow other threads to run while hash updates on data larger than 2047 bytes is taking place when using hash algorithms supplied by OpenSSL.

hash.digest()

Return the digest of the data passed to the update() method so far. This is a bytes object of size digest_size which may contain bytes in the whole range from 0 to 255.

hash.hexdigest()

Like digest() except the digest is returned as a string object of double length, containing only hexadecimal digits. This may be used to exchange the value safely in email or other non-binary environments.

hash.copy()

Return a copy (“clone”) of the hash object. This can be used to efficiently compute the digests of data sharing a common initial substring.

SHAKE variable length digests

The shake_128() and shake_256() algorithms provide variable length digests with length_in_bits//2 up to 128 or 256 bits of security. As such, their digest methods require a length. Maximum length is not limited by the SHAKE algorithm.

shake.digest(length)

Return the digest of the data passed to the update() method so far. This is a bytes object of size length which may contain bytes in the whole range from 0 to 255.

shake.hexdigest(length)

Like digest() except the digest is returned as a string object of double length, containing only hexadecimal digits. This may be used to exchange the value safely in email or other non-binary environments.

Key derivation

Key derivation and key stretching algorithms are designed for secure password hashing. Naive algorithms such as sha1(password) are not resistant against brute-force attacks. A good password hashing function must be tunable, slow, and include a salt [https://en.wikipedia.org/wiki/Salt_%28cryptography%29].

hashlib.pbkdf2_hmac(hash_name, password, salt, iterations, dklen=None)

The function provides PKCS#5 password-based key derivation function 2. It uses HMAC as pseudorandom function.

The string hash_name is the desired name of the hash digest algorithm for HMAC, e.g. ‘sha1’ or ‘sha256’. password and salt are interpreted as buffers of bytes. Applications and libraries should limit password to a sensible length (e.g. 1024). salt should be about 16 or more bytes from a proper source, e.g. os.urandom().

The number of iterations should be chosen based on the hash algorithm and computing power. As of 2013, at least 100,000 iterations of SHA-256 are suggested.

dklen is the length of the derived key. If dklen is None then the digest size of the hash algorithm hash_name is used, e.g. 64 for SHA-512.

>>> import hashlib, binascii
>>> dk = hashlib.pbkdf2_hmac('sha256', b'password', b'salt', 100000)
>>> binascii.hexlify(dk)
b'0394a2ede332c9a13eb82e9b24631604c31df978b4e2f0fbd2c549944f9d79a5'

버전 3.4에 추가.

참고

A fast implementation of pbkdf2_hmac is available with OpenSSL. The Python implementation uses an inline version of hmac. It is about three times slower and doesn’t release the GIL.

hashlib.scrypt(password, *, salt, n, r, p, maxmem=0, dklen=64)

The function provides scrypt password-based key derivation function as defined in RFC 7914 [https://tools.ietf.org/html/rfc7914.html].

password and salt must be bytes-like objects. Applications and libraries should limit password to a sensible length (e.g. 1024). salt should be about 16 or more bytes from a proper source, e.g. os.urandom().

n is the CPU/Memory cost factor, r the block size, p parallelization factor and maxmem limits memory (OpenSSL 1.1.0 defaults to 32 MiB). dklen is the length of the derived key.

Availability: OpenSSL 1.1+.

버전 3.6에 추가.

BLAKE2

BLAKE2 [https://blake2.net] is a cryptographic hash function defined in RFC 7693 [https://tools.ietf.org/html/rfc7693.html] that comes in two flavors:

BLAKE2b, optimized for 64-bit platforms and produces digests of any size between 1 and 64 bytes,

BLAKE2s, optimized for 8- to 32-bit platforms and produces digests of any size between 1 and 32 bytes.

BLAKE2 supports keyed mode (a faster and simpler replacement for HMAC [https://en.wikipedia.org/wiki/Hash-based_message_authentication_code]), salted hashing, personalization, and tree hashing.

Hash objects from this module follow the API of standard library’s hashlib objects.

Creating hash objects

New hash objects are created by calling constructor functions:

hashlib.blake2b(data=b'', *, digest_size=64, key=b'', salt=b'', person=b'', fanout=1, depth=1, leaf_size=0, node_offset=0, node_depth=0, inner_size=0, last_node=False)

hashlib.blake2s(data=b'', *, digest_size=32, key=b'', salt=b'', person=b'', fanout=1, depth=1, leaf_size=0, node_offset=0, node_depth=0, inner_size=0, last_node=False)

These functions return the corresponding hash objects for calculating BLAKE2b or BLAKE2s. They optionally take these general parameters:

data: initial chunk of data to hash, which must be bytes-like object. It can be passed only as positional argument.

digest_size: size of output digest in bytes.

key: key for keyed hashing (up to 64 bytes for BLAKE2b, up to 32 bytes for BLAKE2s).

salt: salt for randomized hashing (up to 16 bytes for BLAKE2b, up to 8 bytes for BLAKE2s).

person: personalization string (up to 16 bytes for BLAKE2b, up to 8 bytes for BLAKE2s).

The following table shows limits for general parameters (in bytes):

Hash

digest_size

len(key)

len(salt)

len(person)

BLAKE2b

64

64

16

16

BLAKE2s

32

32

8

8

참고

BLAKE2 specification defines constant lengths for salt and personalization parameters, however, for convenience, this implementation accepts byte strings of any size up to the specified length. If the length of the parameter is less than specified, it is padded with zeros, thus, for example, b'salt' and b'salt\x00' is the same value. (This is not the case for key.)

These sizes are available as module constants described below.

Constructor functions also accept the following tree hashing parameters:

fanout: fanout (0 to 255, 0 if unlimited, 1 in sequential mode).

depth: maximal depth of tree (1 to 255, 255 if unlimited, 1 in sequential mode).

leaf_size: maximal byte length of leaf (0 to 2**32-1, 0 if unlimited or in sequential mode).

node_offset: node offset (0 to 2**64-1 for BLAKE2b, 0 to 2**48-1 for BLAKE2s, 0 for the first, leftmost, leaf, or in sequential mode).

node_depth: node depth (0 to 255, 0 for leaves, or in sequential mode).

inner_size: inner digest size (0 to 64 for BLAKE2b, 0 to 32 for BLAKE2s, 0 in sequential mode).

last_node: boolean indicating whether the processed node is the last one (False for sequential mode).

See section 2.10 in BLAKE2 specification [https://blake2.net/blake2_20130129.pdf] for comprehensive review of tree hashing.

Constants

blake2b.SALT_SIZE

blake2s.SALT_SIZE

Salt length (maximum length accepted by constructors).

blake2b.PERSON_SIZE

blake2s.PERSON_SIZE

Personalization string length (maximum length accepted by constructors).

blake2b.MAX_KEY_SIZE

blake2s.MAX_KEY_SIZE

Maximum key size.

blake2b.MAX_DIGEST_SIZE

blake2s.MAX_DIGEST_SIZE

Maximum digest size that the hash function can output.

Examples

Simple hashing

To calculate hash of some data, you should first construct a hash object by calling the appropriate constructor function (blake2b() or blake2s()), then update it with the data by calling update() on the object, and, finally, get the digest out of the object by calling digest() (or hexdigest() for hex-encoded string).

>>> from hashlib import blake2b
>>> h = blake2b()
>>> h.update(b'Hello world')
>>> h.hexdigest()
'6ff843ba685842aa82031d3f53c48b66326df7639a63d128974c5c14f31a0f33343a8c65551134ed1ae0f2b0dd2bb495dc81039e3eeb0aa1bb0388bbeac29183'

As a shortcut, you can pass the first chunk of data to update directly to the constructor as the positional argument:

>>> from hashlib import blake2b
>>> blake2b(b'Hello world').hexdigest()
'6ff843ba685842aa82031d3f53c48b66326df7639a63d128974c5c14f31a0f33343a8c65551134ed1ae0f2b0dd2bb495dc81039e3eeb0aa1bb0388bbeac29183'

You can call hash.update() as many times as you need to iteratively update the hash:

>>> from hashlib import blake2b
>>> items = [b'Hello', b' ', b'world']
>>> h = blake2b()
>>> for item in items:
...     h.update(item)
>>> h.hexdigest()
'6ff843ba685842aa82031d3f53c48b66326df7639a63d128974c5c14f31a0f33343a8c65551134ed1ae0f2b0dd2bb495dc81039e3eeb0aa1bb0388bbeac29183'

Using different digest sizes

BLAKE2 has configurable size of digests up to 64 bytes for BLAKE2b and up to 32 bytes for BLAKE2s. For example, to replace SHA-1 with BLAKE2b without changing the size of output, we can tell BLAKE2b to produce 20-byte digests:

>>> from hashlib import blake2b
>>> h = blake2b(digest_size=20)
>>> h.update(b'Replacing SHA1 with the more secure function')
>>> h.hexdigest()
'd24f26cf8de66472d58d4e1b1774b4c9158b1f4c'
>>> h.digest_size
20
>>> len(h.digest())
20

Hash objects with different digest sizes have completely different outputs (shorter hashes are not prefixes of longer hashes); BLAKE2b and BLAKE2s produce different outputs even if the output length is the same:

>>> from hashlib import blake2b, blake2s
>>> blake2b(digest_size=10).hexdigest()
'6fa1d8fcfd719046d762'
>>> blake2b(digest_size=11).hexdigest()
'eb6ec15daf9546254f0809'
>>> blake2s(digest_size=10).hexdigest()
'1bf21a98c78a1c376ae9'
>>> blake2s(digest_size=11).hexdigest()
'567004bf96e4a25773ebf4'

Keyed hashing

Keyed hashing can be used for authentication as a faster and simpler replacement for Hash-based message authentication code [https://en.wikipedia.org/wiki/Hash-based_message_authentication_code] (HMAC). BLAKE2 can be securely used in prefix-MAC mode thanks to the indifferentiability property inherited from BLAKE.

This example shows how to get a (hex-encoded) 128-bit authentication code for message b'message data' with key b'pseudorandom key':

>>> from hashlib import blake2b
>>> h = blake2b(key=b'pseudorandom key', digest_size=16)
>>> h.update(b'message data')
>>> h.hexdigest()
'3d363ff7401e02026f4a4687d4863ced'

As a practical example, a web application can symmetrically sign cookies sent to users and later verify them to make sure they weren’t tampered with:

>>> from hashlib import blake2b
>>> from hmac import compare_digest
>>>
>>> SECRET_KEY = b'pseudorandomly generated server secret key'
>>> AUTH_SIZE = 16
>>>
>>> def sign(cookie):
...     h = blake2b(digest_size=AUTH_SIZE, key=SECRET_KEY)
...     h.update(cookie)
...     return h.hexdigest().encode('utf-8')
>>>
>>> def verify(cookie, sig):
...     good_sig = sign(cookie)
...     return compare_digest(good_sig, sig)
>>>
>>> cookie = b'user-alice'
>>> sig = sign(cookie)
>>> print("{0},{1}".format(cookie.decode('utf-8'), sig))
user-alice,b'43b3c982cf697e0c5ab22172d1ca7421'
>>> verify(cookie, sig)
True
>>> verify(b'user-bob', sig)
False
>>> verify(cookie, b'0102030405060708090a0b0c0d0e0f00')
False

Even though there’s a native keyed hashing mode, BLAKE2 can, of course, be used in HMAC construction with hmac module:

>>> import hmac, hashlib
>>> m = hmac.new(b'secret key', digestmod=hashlib.blake2s)
>>> m.update(b'message')
>>> m.hexdigest()
'e3c8102868d28b5ff85fc35dda07329970d1a01e273c37481326fe0c861c8142'

Randomized hashing

By setting salt parameter users can introduce randomization to the hash function. Randomized hashing is useful for protecting against collision attacks on the hash function used in digital signatures.

Randomized hashing is designed for situations where one party, the message preparer, generates all or part of a message to be signed by a second party, the message signer. If the message preparer is able to find cryptographic hash function collisions (i.e., two messages producing the same hash value), then they might prepare meaningful versions of the message that would produce the same hash value and digital signature, but with different results (e.g., transferring $1,000,000 to an account, rather than $10). Cryptographic hash functions have been designed with collision resistance as a major goal, but the current concentration on attacking cryptographic hash functions may result in a given cryptographic hash function providing less collision resistance than expected. Randomized hashing offers the signer additional protection by reducing the likelihood that a preparer can generate two or more messages that ultimately yield the same hash value during the digital signature generation process — even if it is practical to find collisions for the hash function. However, the use of randomized hashing may reduce the amount of security provided by a digital signature when all portions of the message are prepared by the signer.

(NIST SP-800-106 “Randomized Hashing for Digital Signatures” [https://csrc.nist.gov/publications/detail/sp/800-106/final])

In BLAKE2 the salt is processed as a one-time input to the hash function during initialization, rather than as an input to each compression function.

경고

Salted hashing (or just hashing) with BLAKE2 or any other general-purpose cryptographic hash function, such as SHA-256, is not suitable for hashing passwords. See BLAKE2 FAQ [https://blake2.net/#qa] for more information.

>>> import os
>>> from hashlib import blake2b
>>> msg = b'some message'
>>> # Calculate the first hash with a random salt.
>>> salt1 = os.urandom(blake2b.SALT_SIZE)
>>> h1 = blake2b(salt=salt1)
>>> h1.update(msg)
>>> # Calculate the second hash with a different random salt.
>>> salt2 = os.urandom(blake2b.SALT_SIZE)
>>> h2 = blake2b(salt=salt2)
>>> h2.update(msg)
>>> # The digests are different.
>>> h1.digest() != h2.digest()
True

Personalization

Sometimes it is useful to force hash function to produce different digests for the same input for different purposes. Quoting the authors of the Skein hash function:

We recommend that all application designers seriously consider doing this; we have seen many protocols where a hash that is computed in one part of the protocol can be used in an entirely different part because two hash computations were done on similar or related data, and the attacker can force the application to make the hash inputs the same. Personalizing each hash function used in the protocol summarily stops this type of attack.

(The Skein Hash Function Family [http://www.skein-hash.info/sites/default/files/skein1.3.pdf], p. 21)

BLAKE2 can be personalized by passing bytes to the person argument:

>>> from hashlib import blake2b
>>> FILES_HASH_PERSON = b'MyApp Files Hash'
>>> BLOCK_HASH_PERSON = b'MyApp Block Hash'
>>> h = blake2b(digest_size=32, person=FILES_HASH_PERSON)
>>> h.update(b'the same content')
>>> h.hexdigest()
'20d9cd024d4fb086aae819a1432dd2466de12947831b75c5a30cf2676095d3b4'
>>> h = blake2b(digest_size=32, person=BLOCK_HASH_PERSON)
>>> h.update(b'the same content')
>>> h.hexdigest()
'cf68fb5761b9c44e7878bfb2c4c9aea52264a80b75005e65619778de59f383a3'

Personalization together with the keyed mode can also be used to derive different keys from a single one.

>>> from hashlib import blake2s
>>> from base64 import b64decode, b64encode
>>> orig_key = b64decode(b'Rm5EPJai72qcK3RGBpW3vPNfZy5OZothY+kHY6h21KM=')
>>> enc_key = blake2s(key=orig_key, person=b'kEncrypt').digest()
>>> mac_key = blake2s(key=orig_key, person=b'kMAC').digest()
>>> print(b64encode(enc_key).decode('utf-8'))
rbPb15S/Z9t+agffno5wuhB77VbRi6F9Iv2qIxU7WHw=
>>> print(b64encode(mac_key).decode('utf-8'))
G9GtHFE1YluXY1zWPlYk1e/nWfu0WSEb0KRcjhDeP/o=

Tree mode

Here’s an example of hashing a minimal tree with two leaf nodes:

  10
 /  \
00  01

This example uses 64-byte internal digests, and returns the 32-byte final digest:

>>> from hashlib import blake2b
>>>
>>> FANOUT = 2
>>> DEPTH = 2
>>> LEAF_SIZE = 4096
>>> INNER_SIZE = 64
>>>
>>> buf = bytearray(6000)
>>>
>>> # Left leaf
... h00 = blake2b(buf[0:LEAF_SIZE], fanout=FANOUT, depth=DEPTH,
...               leaf_size=LEAF_SIZE, inner_size=INNER_SIZE,
...               node_offset=0, node_depth=0, last_node=False)
>>> # Right leaf
... h01 = blake2b(buf[LEAF_SIZE:], fanout=FANOUT, depth=DEPTH,
...               leaf_size=LEAF_SIZE, inner_size=INNER_SIZE,
...               node_offset=1, node_depth=0, last_node=True)
>>> # Root node
... h10 = blake2b(digest_size=32, fanout=FANOUT, depth=DEPTH,
...               leaf_size=LEAF_SIZE, inner_size=INNER_SIZE,
...               node_offset=0, node_depth=1, last_node=True)
>>> h10.update(h00.digest())
>>> h10.update(h01.digest())
>>> h10.hexdigest()
'3ad2a9b37c6070e374c7a8c508fe20ca86b6ed54e286e93a0318e95e881db5aa'

Credits

BLAKE2 [https://blake2.net] was designed by Jean-Philippe Aumasson, Samuel Neves, Zooko Wilcox-O’Hearn, and Christian Winnerlein based on SHA-3 [https://en.wikipedia.org/wiki/NIST_hash_function_competition] finalist BLAKE [https://131002.net/blake/] created by Jean-Philippe Aumasson, Luca Henzen, Willi Meier, and Raphael C.-W. Phan.

It uses core algorithm from ChaCha [https://cr.yp.to/chacha.html] cipher designed by Daniel J. Bernstein.

The stdlib implementation is based on pyblake2 [https://pythonhosted.org/pyblake2/] module. It was written by Dmitry Chestnykh based on C implementation written by Samuel Neves. The documentation was copied from pyblake2 [https://pythonhosted.org/pyblake2/] and written by Dmitry Chestnykh.

The C code was partly rewritten for Python by Christian Heimes.

The following public domain dedication applies for both C hash function implementation, extension code, and this documentation:

To the extent possible under law, the author(s) have dedicated all copyright and related and neighboring rights to this software to the public domain worldwide. This software is distributed without any warranty.

You should have received a copy of the CC0 Public Domain Dedication along with this software. If not, see https://creativecommons.org/publicdomain/zero/1.0/.

The following people have helped with development or contributed their changes to the project and the public domain according to the Creative Commons Public Domain Dedication 1.0 Universal:

Alexandr Sokolovskiy

더 보기

Module hmac

A module to generate message authentication codes using hashes.

Module base64

Another way to encode binary hashes for non-binary environments.

https://blake2.net

Official BLAKE2 website.

https://csrc.nist.gov/csrc/media/publications/fips/180/2/archive/2002-08-01/documents/fips180-2.pdf

The FIPS 180-2 publication on Secure Hash Algorithms.

https://en.wikipedia.org/wiki/Cryptographic_hash_function#Cryptographic_hash_algorithms

Wikipedia article with information on which algorithms have known issues and what that means regarding their use.

https://www.ietf.org/rfc/rfc2898.txt

PKCS #5: Password-Based Cryptography Specification Version 2.0

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

암호화 서비스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

암호화 서비스 »

|

hmac — 메시지 인증을 위한 키 해싱

소스 코드: Lib/hmac.py [https://github.com/python/cpython/tree/3.7/Lib/hmac.py]

이 모듈은 RFC 2104 [https://tools.ietf.org/html/rfc2104.html]에서 설명한 대로 HMAC 알고리즘을 구현합니다.

hmac.new(key, msg=None, digestmod=None)

새로운 hmac 객체를 반환합니다. key는 비밀 키를 제공하는 바이트열이나 바이트 배열(bytearray) 객체입니다. msg가 있으면, update(msg) 메서드 호출이 수행됩니다. digestmod는 다이제스트 이름, 다이제스트 생성자 또는 HMAC 객체가 사용할 모듈입니다. hashlib.new()에 적합한 모든 이름을 지원하며 기본값은 hashlib.md5 생성자입니다.

버전 3.4에서 변경: 매개 변수 key는 바이트열 또는 바이트 배열 객체일 수 있습니다. 매개 변수 msg는 hashlib가 지원하는 모든 형이 될 수 있습니다. 매개 변수 digestmod는 해시 알고리즘의 이름이 될 수 있습니다.

Deprecated since version 3.4, will be removed in version 3.8: digestmod에 대한 묵시적 기본 다이제스트로서의 MD5는 폐지되었습니다.

hmac.digest(key, msg, digest)

주어진 비밀 key 와 digest로 msg의 다이제스트를 반환합니다. 이 함수는 HMAC(key, msg, digest).digest()와 동등하지만, 최적화된 C 나 인라인 구현을 사용해서, 메모리에 맞는 메시지에는 더 빠릅니다. 매개 변수 key, msg 및 digest는 new()에서와 같은 뜻입니다.

CPython 구현 세부 사항, 최적화된 C 구현은 digest가 문자열이고 OpenSSL에서 지원하는 다이제스트 알고리즘의 이름일 때만 사용됩니다.

버전 3.7에 추가.

HMAC 객체에는 다음과 같은 메서드가 있습니다:

HMAC.update(msg)

hmac 객체를 msg로 갱신합니다. 반복되는 호출은 모든 인자를 이어붙인 단일 호출과 동등합니다: m.update(a); m.update(b)는 m.update(a + b)와 동등합니다.

버전 3.4에서 변경: 매개 변수 msg는 hashlib가 지원하는 모든 형이 될 수 있습니다.

HMAC.digest()

지금까지 update() 메서드로 전달된 바이트들의 다이제스트를 반환합니다. 이 바이트열 객체는 생성자에게 주어진 다이제스트의 digest_size와 길이가 같습니다. NUL 바이트를 포함하여 비 ASCII 바이트를 포함할 수 있습니다.

경고

검증 루틴에서 digest()의 출력을 외부에서 제공되는 다이제스트와 비교할 때, == 연산자 대신 compare_digest() 함수를 사용하여 타이밍 공격의 취약점을 줄이는 것이 좋습니다.

HMAC.hexdigest()

다이제스트가 16진수만 포함하는 길이가 두 배인 문자열로 반환된다는 점을 제외하고는 digest()와 같습니다. 이것은 전자 메일이나 기타 비 바이너리 환경에서 값을 안전하게 교환하는 데 사용될 수 있습니다.

경고

검증 루틴에서 hexdigest()의 출력을 외부에서 제공되는 다이제스트와 비교할 때, == 연산자 대신 compare_digest() 함수를 사용하여 타이밍 공격의 취약점을 줄이는 것이 좋습니다.

HMAC.copy()

hmac 객체의 복사본(“클론”)을 반환합니다. 이것은 공통 초기 부분 문자열을 공유하는 문자열들의 다이제스트를 효율적으로 계산하는 데 사용할 수 있습니다.

hmac 객체에는 다음과 같은 어트리뷰트가 있습니다:

HMAC.digest_size

결과 HMAC 다이제스트의 크기(바이트).

HMAC.block_size

해시 알고리즘의 내부 블록 크기(바이트).

버전 3.4에 추가.

HMAC.name

이 HMAC의 규범적 이름, 항상 소문자, 예를 들어 hmac-md5.

버전 3.4에 추가.

이 모듈은 또한 다음 도우미 함수를 제공합니다:

hmac.compare_digest(a, b)

a == b를 반환합니다. 이 함수는 내용 기반의 단락(short circuiting) 동작을 피함으로써 타이밍 분석을 방지하도록 설계된 접근법을 사용해서 암호화에 적합하게 만듭니다. a와 b는 모두 같은 형이어야 합니다: str (ASCII만, 예를 들어 HMAC.hexdigest()에 의해 반환된 것과 같은 것) 이나 바이트열류 객체.

참고

a와 b의 길이가 다르거나 에러가 발생하면, 타이밍 공격이 이론적으로는 a 와 b의 형과 길이에 관한 정보를 드러낼 수 있습니다 - 하지만 그 값은 아닙니다.

버전 3.3에 추가.

더 보기

모듈 hashlib

안전한 해시 함수를 제공하는 파이썬 모듈.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

암호화 서비스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

암호화 서비스 »

|

secrets — 비밀 관리를 위한 안전한 난수 생성

버전 3.6에 추가.

소스 코드: Lib/secrets.py [https://github.com/python/cpython/tree/3.7/Lib/secrets.py]

secrets 모듈은 암호, 계정 인증, 보안 토큰 및 관련 비밀과 같은 데이터를 관리하는 데 적합한 암호학적으로 강력한 난수를 생성하는 데 사용됩니다.

특히, secrets는 보안이나 암호화가 아닌 모델링과 시뮬레이션용으로 설계된 random 모듈의 기본 의사 난수 생성기보다 먼저 사용해야 합니다.

더 보기

PEP 506 [https://www.python.org/dev/peps/pep-0506]

난수

secrets 모듈은 운영 체제가 제공하는 가장 안전한 무작위 소스에 대한 액세스를 제공합니다.

class secrets.SystemRandom

운영 체제에서 제공하는 최고 품질의 소스를 사용하여 난수를 생성하는 클래스. 자세한 내용은 random.SystemRandom를 참조하십시오.

secrets.choice(sequence)

비어있지 않은 시퀀스로부터 무작위로 선택된 요소를 돌려줍니다.

secrets.randbelow(n)

범위 [0, n)에서 무작위 int를 돌려줍니다.

secrets.randbits(k)

k 무작위 비트를 가지는 int를 돌려줍니다.

토큰 생성

secrets 모듈은 암호 재설정, 추측하기 어려운 URL 등과 같은 응용에 적합한 보안 토큰을 생성하는 함수를 제공합니다.

secrets.token_bytes([nbytes=None])

nbytes 바이트를 포함하는 임의의 바이트열을 반환합니다. nbytes가 None이거나 제공되지 않으면, 적절한 기본값이 사용됩니다.

>>> token_bytes(16)
b'\xebr\x17D*t\xae\xd4\xe3S\xb6\xe2\xebP1\x8b'

secrets.token_hex([nbytes=None])

무작위 16진수 텍스트 문자열을 돌려줍니다. 이 문자열에는 nbytes 무작위 바이트가 있으며, 각 바이트는 두 자리 16진수로 변환됩니다. nbytes가 None이거나 제공되지 않으면, 적절한 기본값이 사용됩니다.

>>> token_hex(16)
'f9bf78b9a18ce6d46a0cd2b0b86df9da'

secrets.token_urlsafe([nbytes=None])

nbytes의 무작위 바이트를 포함한, URL 안전한 무작위 텍스트 문자열을 돌려줍니다. 텍스트는 Base64로 인코딩되어 있으므로, 평균적으로 각 바이트는 약 1.3 문자가 됩니다. nbytes가 None이거나 제공되지 않으면, 적절한 기본값이 사용됩니다.

>>> token_urlsafe(16)
'Drmhze6EPcv0fN_81Bj-nA'

토큰은 몇 바이트를 사용해야 합니까?

무차별 공격 [https://en.wikipedia.org/wiki/Brute-force_attack]으로부터 안전하려면, 토큰에 충분한 무작위성이 있어야 합니다. 불행하게도, 컴퓨터가 더 강력해지고 더 짧은 기간에 더 많은 추측을 할 수 있게 됨에 따라, 충분하다고 여겨지는 것은 필연적으로 증가합니다. 2015년 현재, secrets 모듈로 예상되는 일반적인 사용 사례에는 32바이트(256비트)의 무작위성으로 충분하다고 여겨집니다.

자신의 토큰 길이를 관리하려는 사용자는, 여러 token_* 함수에 int 인자를 제공하여 토큰에 사용되는 무작위성의 양을 명시적으로 지정할 수 있습니다. 이 인자는 사용할 무작위성의 바이트 수로 사용됩니다.

그렇지 않으면, 인자가 제공되지 않거나 인자가 None 이면, token_* 함수는 적절한 기본값을 대신 사용합니다.

참고

이 기본값은 유지 보수 배포를 포함하여 언제든지 변경될 수 있습니다.

기타 함수

secrets.compare_digest(a, b)

문자열 a와 b가 같으면 True를, 그렇지 않으면 False를 반환하는데, 타이밍 공격 [https://codahale.com/a-lesson-in-timing-attacks/]의 위험을 줄이는 방식을 사용합니다. 자세한 내용은 hmac.compare_digest()를 참조하십시오.

조리법과 모범 사례

이 절에서는 secrets를 사용하여 기본 보안 수준을 관리하는 조리법과 모범 사례를 보여줍니다.

8문자 영숫자 암호 생성합니다:

import string
alphabet = string.ascii_letters + string.digits
password = ''.join(choice(alphabet) for i in range(8))

참고

응용 프로그램은 평문인지 암호문인지 관계없이, 암호를 복원 가능한 형식으로 저장 [http://cwe.mitre.org/data/definitions/257.html]해서는 안 됩니다. 이들은 암호학적으로 강력한 단방향(비가역적) 해시 함수를 사용하여 솔트되고 해시 되어야 합니다.

적어도 하나의 소문자, 적어도 하나의 대문자 및 적어도 3개의 숫자가 있는 10자의 영숫자 암호를 생성합니다:

import string
alphabet = string.ascii_letters + string.digits
while True:
    password = ''.join(choice(alphabet) for i in range(10))
    if (any(c.islower() for c in password)
            and any(c.isupper() for c in password)
            and sum(c.isdigit() for c in password) >= 3):
        break

XKCD-스타일 암호문 [https://xkcd.com/936/]을 생성합니다:

# On standard Linux systems, use a convenient dictionary file.
# Other platforms may need to provide their own word-list.
with open('/usr/share/dict/words') as f:
    words = [word.strip() for word in f]
    password = ' '.join(choice(words) for i in range(4))

암호 복구 응용에 적합한 보안 토큰을 포함하는 추측하기 어려운 임시 URL을 생성합니다:

url = 'https://mydomain.com/reset=' + token_urlsafe()

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

암호화 서비스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

|

일반 운영 체제 서비스

이 장에서 설명하는 모듈은 파일 및 시계와 같은 (거의) 모든 운영 체제에서 사용할 수 있는 운영 체제 기능에 대한 인터페이스를 제공합니다. 인터페이스는 일반적으로 유닉스 또는 C 인터페이스를 모델로 하지만, 대부분의 다른 시스템에서도 사용할 수 있습니다. 다음은 개요입니다:

os — 기타 운영 체제 인터페이스

파일명, 명령 줄 인자 및 환경 변수

프로세스 매개 변수

파일 객체 생성

파일 기술자 연산

터미널의 크기 조회하기

파일 기술자의 상속

파일과 디렉터리

리눅스 확장 어트리뷰트

프로세스 관리

스케줄러에 대한 인터페이스

기타 시스템 정보

난수

io — Core tools for working with streams

Overview

Text I/O

Binary I/O

Raw I/O

High-level Module Interface

In-memory streams

Class hierarchy

I/O Base Classes

Raw File I/O

Buffered Streams

Text I/O

Performance

Binary I/O

Text I/O

Multi-threading

Reentrancy

time — Time access and conversions

Functions

Clock ID Constants

Timezone Constants

argparse — 명령행 옵션, 인자와 부속 명령을 위한 파서

예

파서 만들기

인자 추가하기

인자 파싱하기

ArgumentParser 객체

prog

usage

description

epilog

parents

formatter_class

prefix_chars

fromfile_prefix_chars

argument_default

allow_abbrev

conflict_handler

add_help

add_argument() 메서드

name or flags

action

nargs

const

default

type

choices

required

help

metavar

dest

Action 클래스

parse_args() 메서드

옵션값 문법

잘못된 인자

- 를 포함하는 인자들

인자 약어 (접두사 일치)

sys.argv 너머

Namespace 객체

기타 유틸리티

부속 명령

FileType 객체

인자 그룹

상호 배제

파서 기본값

도움말 인쇄

부분 파싱

파일 파싱 사용자 정의

종료 메서드

혼합 파싱

optparse 코드 업그레이드

getopt — 명령 줄 옵션용 C 스타일 구문 분석기

logging — 파이썬 로깅 시설

Logger 객체

로깅 수준

Handler 객체

Formatter 객체

Filter 객체

LogRecord 객체

LogRecord 어트리뷰트

LoggerAdapter 객체

스레드 안전성

모듈 수준 함수

모듈 수준 어트리뷰트

warnings 모듈과의 통합

logging.config — 로깅 구성

구성 함수

구성 딕셔너리 스키마

딕셔너리 스키마 세부사항

증분 구성

객체 연결

사용자 정의 객체

외부 객체에 대한 액세스

내부 객체에 대한 액세스

임포트 결정과 사용자 정의 임포터

구성 파일 형식

logging.handlers — 로깅 처리기

StreamHandler

FileHandler

NullHandler

WatchedFileHandler

BaseRotatingHandler

RotatingFileHandler

TimedRotatingFileHandler

SocketHandler

DatagramHandler

SysLogHandler

NTEventLogHandler

SMTPHandler

MemoryHandler

HTTPHandler

QueueHandler

QueueListener

getpass — 이식성 있는 암호 입력

curses — Terminal handling for character-cell displays

Functions

Window Objects

Constants

curses.textpad — Text input widget for curses programs

Textbox objects

curses.ascii — Utilities for ASCII characters

curses.panel — curses 용 패널 스택 확장

함수

Panel 객체

platform — 하부 플랫폼의 식별 데이터에 대한 액세스

크로스 플랫폼

자바 플랫폼

윈도우 플랫폼

Win95/98 specific

Mac OS 플랫폼

유닉스 플랫폼

errno — 표준 errno 시스템 기호

ctypes — 파이썬용 외부 함수 라이브러리

ctypes 자습서

동적 링크 라이브러리 로드하기

로드된 dll에서 함수에 액세스하기

함수 호출하기

기본 데이터형

함수 호출하기, 계속

사용자 정의 데이터형을 사용하여 함수 호출하기

필수 인자 형 (함수 프로토타입) 지정하기

반환형

포인터 전달하기 (또는: 참조로 매개 변수 전달하기)

구조체와 공용체

구조체/공용체 정렬과 바이트 순서

구조체와 공용체의 비트 필드

배열

포인터

형 변환

불완전한 형

콜백 함수

dll에서 내 보낸 값을 액세스하기

의외의 것들

가변 크기 데이터형

ctypes 레퍼런스

공유 라이브러리 찾기

공유 라이브러리 로드하기

외부 함수

함수 프로토타입

유틸리티 함수

데이터형

기본 데이터형

구조화된 데이터형

배열과 포인터

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

일반 운영 체제 서비스 »

|

os — 기타 운영 체제 인터페이스

소스 코드: Lib/os.py [https://github.com/python/cpython/tree/3.7/Lib/os.py]

이 모듈은 운영 체제 종속 기능을 사용하는 이식성 있는 방법을 제공합니다. 파일을 읽거나 쓰고 싶으면 open()을 보세요, 경로를 조작하려면 os.path 모듈을 보시고, 명령 줄에서 주어진 모든 파일의 모든 줄을 읽으려면 fileinput 모듈을 보십시오. 임시 파일과 디렉터리를 만들려면 tempfile 모듈을 보시고, 고수준의 파일과 디렉터리 처리는 shutil 모듈을 보십시오.

이러한 기능의 가용성에 대한 참고 사항:

내장된 모든 운영 체제 종속적인 파이썬 모듈의 설계는, 같은 기능을 사용할 수 있는 한, 같은 인터페이스를 사용합니다; 예를 들어, 함수 os.stat(path)는 path 에 대한 stat 정보를 같은 (POSIX 인터페이스에서 기원한) 형식으로 반환합니다.

특정 운영 체제에 고유한 확장도 os 모듈을 통해서 사용할 수 있지만, 이러한 기능을 사용하는 것은 물론 이식성에 대한 위협입니다.

경로 또는 파일명을 받아들이는 모든 함수는 바이트열과 문자열 객체를 모두 허용하며, 경로나 파일명이 반환되면 같은 형의 객체를 반환합니다.

참고

All functions in this module raise OSError (or subclasses thereof) in the case of invalid or inaccessible file names and paths, or other arguments that have the correct type, but are not accepted by the operating system.

exception os.error

내장 OSError 예외의 별칭.

os.name

임포트 된 운영 체제 종속 모듈의 이름. 다음과 같은 이름이 현재 등록되어있습니다: 'posix', 'nt', 'java'.

더 보기

sys.platform는 더 세분되어 있습니다. os.uname()은 시스템 종속 버전 정보를 제공합니다.

platform 모듈은 시스템의 아이덴티티에 대한 자세한 검사를 제공합니다.

파일명, 명령 줄 인자 및 환경 변수

파이썬에서는, 파일명, 명령 줄 인자 및 환경 변수가 문자열형을 사용하여 표시됩니다. 일부 시스템에서는, 운영 체제에 전달하기 전에 이러한 문자열을 바이트열로 인코딩하는 것이 필요합니다. 파이썬은 파일 시스템 인코딩을 사용하여 이 변환을 수행합니다 (sys.getfilesystemencoding()을 참조하세요).

버전 3.1에서 변경: 일부 시스템에서는, 파일 시스템 인코딩을 사용한 변환이 실패할 수 있습니다. 이때, 파이썬은 surrogateescape 인코딩 에러 처리기를 사용하는데, 디코딩할 때 디코딩 할 수 없는 바이트가 유니코드 문자 U+DCxx로 치환되고, 다시 인코딩할 때 원래 바이트로 변환됩니다.

파일 시스템 인코딩은 128보다 작은 모든 바이트를 성공적으로 디코딩함을 보장해야 합니다. 파일 시스템 인코딩이 이 보장을 제공하지 못하면, API 함수가 UnicodeError를 발생시킬 수 있습니다.

프로세스 매개 변수

이 함수들과 데이터 항목은 현재 프로세스와 사용자에 관한 정보와 관련 연산을 제공합니다.

os.ctermid()

프로세스의 제어 터미널에 해당하는 파일명을 반환합니다.

가용성: 유닉스.

os.environ

문자열 환경을 나타내는 매핑 객체입니다. 예를 들어, environ['HOME']은 홈 디렉터리의 경로명이며 (일부 플랫폼에서), C의 getenv("HOME")과 같습니다.

이 매핑은 os 모듈을 처음으로 임포트 할 때, 일반적으로 파이썬을 시작할 때 site.py를 처리하는 과정에서, 캡처됩니다. 이 시각 이후 변경된 환경은 os.environ을 직접 수정하여 변경한 경우를 제외하고는 os.environ에 반영되지 않습니다.

플랫폼이 putenv() 함수를 지원하면, 이 매핑은 환경을 조회하는 것뿐 아니라 환경을 수정하는 데도 사용될 수 있습니다. 매핑이 수정될 때 putenv()가 자동으로 호출됩니다.

유닉스에서, 키와 값은 sys.getfilesystemencoding() 과 'surrogateescape' 에러 처리기를 사용합니다. 다른 인코딩을 사용하려면 environb를 사용하십시오.

참고

putenv()를 직접 호출해도 os.environ은 변경되지 않으므로, os.environ을 수정하는 것이 좋습니다.

참고

FreeBSD 및 맥 OS X를 포함한 일부 플랫폼에서, environ을 설정하면 메모리 누수가 발생할 수 있습니다. putenv()에 대한 시스템 설명서를 참조하십시오.

putenv()가 제공되지 않으면, 이 매핑의 수정된 복사본을 적절한 프로세스 생성 함수에 전달하여 자식 프로세스가 수정된 환경을 사용하게 할 수 있습니다.

플랫폼이 unsetenv() 기능을 지원하면, 이 매핑의 항목을 삭제하여 환경 변수를 삭제할 수 있습니다. 항목이 os.environ에서 삭제되거나, pop() 또는 clear() 메서드 중 하나가 호출되면 unsetenv()가 자동으로 호출됩니다.

os.environb

environ의 바이트열 버전: 환경을 바이트열로 나타내는 매핑 객체입니다. environ과 environb는 동기화됩니다 (environb를 수정하면 environ이 갱신되고, 그 반대도 마찬가지입니다).

environb is only available if supports_bytes_environ is True.

버전 3.2에 추가.

os.chdir(path)

os.fchdir(fd)

os.getcwd()

이 함수는 파일과 디렉터리에 설명되어 있습니다.

os.fsencode(filename)

'surrogateescape' 에러 처리기를, 또는 윈도우에서는 'strict'를, 사용하여 파일 시스템 인코딩으로 경로류 filename 을 인코딩합니다; bytes를 변경하지 않고 반환합니다.

fsdecode()는 역 함수입니다.

버전 3.2에 추가.

버전 3.6에서 변경: os.PathLike 인터페이스를 구현하는 객체를 받아들이도록 지원이 추가되었습니다.

os.fsdecode(filename)

'surrogateescape' 에러 처리기를, 또는 윈도우에서는 'strict'를, 사용하여 파일 시스템 인코딩으로 경로류 filename 을 디코딩합니다; str을 변경하지 않고 반환합니다.

fsencode()는 역 함수입니다.

버전 3.2에 추가.

버전 3.6에서 변경: os.PathLike 인터페이스를 구현하는 객체를 받아들이도록 지원이 추가되었습니다.

os.fspath(path)

경로의 파일 시스템 표현을 돌려줍니다.

str이나 bytes가 전달되면, 변경되지 않은 상태로 반환됩니다. 그렇지 않으면 __fspath__()가 호출되고, 해당 값이 str이나 bytes 객체인 한 그 값이 반환됩니다. 다른 모든 경우에는 TypeError가 발생합니다.

버전 3.6에 추가.

class os.PathLike

파일 시스템 경로를 나타내는 객체(예를 들어 pathlib.PurePath)의 추상 베이스 클래스입니다.

버전 3.6에 추가.

abstractmethod __fspath__()

객체의 파일 시스템 경로 표현을 돌려줍니다.

이 메서드는 str이나 bytes 객체만 반환해야 하며, str을 선호합니다.

os.getenv(key, default=None)

존재하면 환경 변수 key 의 값을 반환하고, 그렇지 않으면 default 를 반환합니다. key, default 및 결과는 str입니다.

유닉스에서, 키와 값은 sys.getfilesystemencoding() 과 'surrogateescape' 에러 처리기로 디코딩됩니다. 다른 인코딩을 사용하려면 os.getenvb()를 사용하십시오.

가용성: 대부분의 유닉스, 윈도우.

os.getenvb(key, default=None)

존재하면 환경 변수 key 의 값을 반환하고, 그렇지 않으면 default 를 반환합니다. key, default 및 결과는 bytes입니다.

getenvb() is only available if supports_bytes_environ is True.

가용성: 대부분의 유닉스.

버전 3.2에 추가.

os.get_exec_path(env=None)

셸과 비슷하게, 프로세스를 시작할 때 지정된 이름의 실행 파일을 검색할 디렉터리 리스트를 반환합니다. (지정된다면) env 는 PATH를 조회할 환경 변수 딕셔너리 여야 합니다. 기본적으로, env 가 None이면, environ이 사용됩니다.

버전 3.2에 추가.

os.getegid()

현재 프로세스의 유효(effective) 그룹 ID를 반환합니다. 이것은 현재 프로세스에서 실행 중인 파일의 “set id” 비트에 해당합니다.

가용성: 유닉스.

os.geteuid()

현재 프로세스의 유효(effective) 사용자 ID를 반환합니다.

가용성: 유닉스.

os.getgid()

현재 프로세스의 실제(real) 그룹 ID를 반환합니다.

가용성: 유닉스.

os.getgrouplist(user, group)

user가 속한 그룹 ID의 목록을 돌려줍니다. group 이 목록에 없으면 포함됩니다; 일반적으로 group 은 user 의 암호 레코드에서 그룹 ID 필드로 지정됩니다.

가용성: 유닉스.

버전 3.3에 추가.

os.getgroups()

현재 프로세스와 관련된 보충(supplemental) 그룹 ID 목록을 반환합니다.

가용성: 유닉스.

참고

맥 OS X에서, getgroups() 동작은 다른 유닉스 플랫폼과 약간 다릅니다. 파이썬 인터프리터가 10.5 또는 이전 버전의 배포 대상으로 빌드되면, getgroups()는 현재 사용자 프로세스와 관련된 유효 그룹 ID 목록을 반환합니다; 이 목록은 시스템 정의된 항목 수(일반적으로 16)로 제한되며, 적절하게 권한이 부여된 경우 setgroups()를 호출하여 수정할 수 있습니다. 10.5보다 큰 배포 대상으로 빌드되면, getgroups()는 프로세스의 유효 사용자 ID와 연관된 사용자에 대한 현재 그룹 액세스 목록을 반환합니다; 그룹 액세스 목록은 프로세스 수명 동안 변경될 수 있으며, setgroups() 호출의 영향을 받지 않고, 길이도 16개로 제한되지 않습니다. 배포 대상 값(MACOSX_DEPLOYMENT_TARGET)은 sysconfig.get_config_var()를 통해 얻을 수 있습니다.

os.getlogin()

프로세스의 제어 터미널에 로그인한 사용자의 이름을 반환합니다. 대부분 목적에서, getpass.getuser()를 사용하는 것이 더 유용한데, 이 함수는 환경 변수 LOGNAME 이나 USERNAME을 검사하여 사용자가 누구인지 알아내고, 현재 실제 사용자 ID의 로그인 이름을 얻기 위해 pwd.getpwuid(os.getuid())[0]로 폴백 하기 때문입니다.

가용성: 유닉스, 윈도우.

os.getpgid(pid)

프로세스 ID pid 를 갖는 프로세스의 프로세스 그룹 ID를 반환합니다. pid 가 0이면, 현재 프로세스의 프로세스 그룹 id가 반환됩니다.

가용성: 유닉스.

os.getpgrp()

현재 프로세스 그룹의 ID를 반환합니다.

가용성: 유닉스.

os.getpid()

현재의 프로세스 ID를 반환합니다.

os.getppid()

부모의 프로세스 ID를 반환합니다. 부모 프로세스가 종료했으면, 유닉스에서 반환된 id는 init 프로세스 (1) 중 하나이며, 윈도우에서는 여전히 같은 id인데, 다른 프로세스에서 이미 재사용했을 수 있습니다.

가용성: 유닉스, 윈도우.

버전 3.2에서 변경: 윈도우에 대한 지원이 추가되었습니다.

os.getpriority(which, who)

프로그램 스케줄 우선순위를 얻습니다. which 값은 PRIO_PROCESS, PRIO_PGRP 또는 PRIO_USER 중 하나이고, who는 which 에 상대적으로 해석됩니다 (PRIO_PROCESS 면 프로세스 식별자, PRIO_PGRP 면 프로세스 그룹 식별자, PRIO_USER 면 사용자 ID). 0 값의 who는 (각각) 호출하는 프로세스, 호출하는 프로세스의 프로세스 그룹, 호출하는 프로세스의 실제 사용자 ID를 나타냅니다.

가용성: 유닉스.

버전 3.3에 추가.

os.PRIO_PROCESS

os.PRIO_PGRP

os.PRIO_USER

getpriority() 와 setpriority() 함수의 매개 변숫값

가용성: 유닉스.

버전 3.3에 추가.

os.getresuid()

현재 프로세스의 실제(real), 유효(effective) 및 저장된(saved) 사용자 ID를 나타내는 튜플 (ruid, euid, suid)를 반환합니다.

가용성: 유닉스.

버전 3.2에 추가.

os.getresgid()

현재 프로세스의 실제(real), 유효(effective) 및 저장된(saved) 그룹 ID를 나타내는 튜플 (rgid, egid, sgid)를 반환합니다.

가용성: 유닉스.

버전 3.2에 추가.

os.getuid()

현재 프로세스의 실제(real) 사용자 ID를 반환합니다.

가용성: 유닉스.

os.initgroups(username, gid)

지정된 사용자 이름이 구성원인 모든 그룹과 지정된 그룹 ID로 구성된 그룹 액세스 목록을 초기화하기 위해 시스템 initgroups()를 호출합니다.

가용성: 유닉스.

버전 3.2에 추가.

os.putenv(key, value)

key 라는 환경 변수를 문자열 value 로 설정합니다. 이러한 환경의 변화는 os.system(), popen() 또는 fork() 및 execv()로 시작된 자식 프로세스에 영향을 줍니다.

가용성: 대부분의 유닉스, 윈도우.

참고

FreeBSD 및 맥 OS X를 포함한 일부 플랫폼에서, environ를 설정하면 메모리 누수가 발생할 수 있습니다. putenv에 관한 시스템 설명서를 참조하십시오.

putenv()가 지원되면, os.environ의 항목에 대한 대입이 putenv()에 대한 해당 호출로 자동 변환됩니다. 그러나, putenv()에 대한 호출은 os.environ을 갱신하지 않으므로, 실제로는 os.environ 항목에 대입하는 것이 좋습니다.

os.setegid(egid)

현재 프로세스의 유효 그룹 ID를 설정합니다.

가용성: 유닉스.

os.seteuid(euid)

현재 프로세스의 유효 사용자 ID를 설정합니다.

가용성: 유닉스.

os.setgid(gid)

현재 프로세스의 그룹 ID를 설정합니다.

가용성: 유닉스.

os.setgroups(groups)

현재 프로세스와 연관된 보충(supplemental) 그룹 ID의 목록을 groups로 설정합니다. groups 는 시퀀스 여야 하며, 각 요소는 그룹을 식별하는 정수여야 합니다. 이 연산은 대개 슈퍼 유저만 사용할 수 있습니다.

가용성: 유닉스.

참고

맥 OS X에서 groups 의 길이는 시스템이 정의한 최대 유효 그룹 ID 수(일반적으로 16)를 초과할 수 없습니다. setgroups()를 호출해서 설정한 것과 같은 그룹 목록을 반환하지 않는 경우에 관해서는 getgroups() 설명서를 참조하십시오.

os.setpgrp()

구현된 (있기는 하다면) 버전에 따라 시스템 호출 setpgrp() 나 setpgrp(0, 0)을 호출합니다. 의미에 대해서는 유닉스 매뉴얼을 참조하십시오.

가용성: 유닉스.

os.setpgid(pid, pgrp)

프로세스 ID가 pid 인 프로세스의 프로세스 그룹 ID를 pgrp 로 설정하기 위해 시스템 호출 setpgid()를 호출합니다. 의미에 대해서는 유닉스 매뉴얼을 참조하십시오.

가용성: 유닉스.

os.setpriority(which, who, priority)

프로그램 스케줄 우선순위를 설정합니다. which 값은 PRIO_PROCESS, PRIO_PGRP 또는 PRIO_USER 중 하나이고, who는 which 에 상대적으로 해석됩니다 (PRIO_PROCESS 면 프로세스 식별자, PRIO_PGRP 면 프로세스 그룹 식별자, PRIO_USER 면 사용자 ID). 0 값의 who는 (각각) 호출하는 프로세스, 호출하는 프로세스의 프로세스 그룹, 호출하는 프로세스의 실제 사용자 ID를 나타냅니다. priority 는 -20에서 19 사이의 값입니다. 기본 우선순위는 0입니다; 우선순위가 낮으면 더 유리하게 스케줄 됩니다.

가용성: 유닉스.

버전 3.3에 추가.

os.setregid(rgid, egid)

현재 프로세스의 실제(real) 및 유효한(effective) 그룹 ID를 설정합니다.

가용성: 유닉스.

os.setresgid(rgid, egid, sgid)

현재 프로세스의 실제(real), 유효(effective) 및 저장된(saved) 그룹 ID를 설정합니다.

가용성: 유닉스.

버전 3.2에 추가.

os.setresuid(ruid, euid, suid)

현재 프로세스의 실제(real), 유효(effective) 및 저장된(saved) 사용자 ID를 설정합니다.

가용성: 유닉스.

버전 3.2에 추가.

os.setreuid(ruid, euid)

현재 프로세스의 실제(real) 및 유효(effective) 사용자 ID를 설정합니다.

가용성: 유닉스.

os.getsid(pid)

시스템 호출 getsid()를 호출합니다. 의미에 대해서는 유닉스 매뉴얼을 참조하십시오.

가용성: 유닉스.

os.setsid()

시스템 호출 setsid()를 호출합니다. 의미에 대해서는 유닉스 매뉴얼을 참조하십시오.

가용성: 유닉스.

os.setuid(uid)

현재 프로세스의 사용자 ID를 설정합니다.

가용성: 유닉스.

os.strerror(code)

에러 코드 code에 해당하는 에러 메시지를 반환합니다. 알 수 없는 에러 코드가 주어질 때 strerror()가 NULL을 반환하는 플랫폼에서, ValueError가 발생합니다.

os.supports_bytes_environ

환경의 원시 OS 형이 바이트열이면 True (예를 들어, 윈도우에서는 False).

버전 3.2에 추가.

os.umask(mask)

현재 숫자 umask를 설정하고 이전 umask를 반환합니다.

os.uname()

현재 운영 체제를 식별하는 정보를 반환합니다. 반환 값은 5가지 어트리뷰트를 가진 객체입니다:

sysname - 운영 체제 이름

nodename - 네트워크상의 기계 이름 (구현이 정의)

release - 운영 체제 릴리스

version - 운영 체제 버전

machine - 하드웨어 식별자

하위 호환성을 위해, 이 객체는 이터러블이기도 해서, sysname, nodename, release, version 및 machine이 이 순서로 포함된 5-튜플처럼 작동합니다.

일부 시스템에서는 nodename을 8자나 선행 구성 요소로 자릅니다; 호스트 이름을 얻는 더 좋은 방법은 socket.gethostname() 또는 더 나아가 socket.gethostbyaddr(socket.gethostname())입니다.

가용성: 최근 유닉스.

버전 3.3에서 변경: 반환형이 튜플에서 이름이 지정된 어트리뷰트를 가진 튜플류 객체로 변경되었습니다.

os.unsetenv(key)

key 라는 이름의 환경 변수를 삭제합니다. 이러한 환경 변화는 os.system(), popen() 또는 fork() 및 execv()로 시작된 자식 프로세스에 영향을 줍니다.

unsetenv()가 지원되면, os.environ의 항목 삭제가 자동으로 unsetenv()에 대한 해당 호출로 변환됩니다. 그러나 unsetenv()에 대한 호출은 os.environ을 갱신하지 않으므로, 실제로는 os.environ 항목을 삭제하는 것이 좋습니다.

가용성: 대부분의 유닉스.

파일 객체 생성

이 함수는 새로운 파일 객체를 만듭니다. (파일 기술자를 여는 것에 관해서는 open()를 참조하십시오.)

os.fdopen(fd, *args, **kwargs)

파일 기술자 fd에 연결된 열린 파일 객체를 반환합니다. 이것은 open() 내장 함수의 별칭이며 같은 인자를 받아들입니다. 유일한 차이점은 fdopen()의 첫 번째 인자는 항상 정수여야 한다는 것입니다.

파일 기술자 연산

이 함수들은 파일 기술자를 사용하여 참조된 I/O 스트림에 작용합니다.

파일 기술자는 현재 프로세스에 의해 열린 파일에 대응하는 작은 정수입니다. 예를 들어, 표준 입력은 보통 파일 기술자 0이고, 표준 출력은 1이며, 표준 에러는 2입니다. 프로세스에 의해 열린 추가 파일은 3, 4, 5 등으로 지정됩니다. “파일 기술자”라는 이름은 약간 기만적입니다; 유닉스 플랫폼에서, 소켓과 파이프도 파일 기술자에 의해 참조됩니다.

fileno() 메서드는 필요할 때 파일 객체와 연관된 파일 기술자를 얻는 데 사용될 수 있습니다. 파일 기술자를 직접 사용하면 파일 객체 메서드를 거치지 않아서, 데이터의 내부 버퍼링과 같은 측면을 무시하게 되는 것에 유의하십시오.

os.close(fd)

파일 기술자 fd를 닫습니다.

참고

이 함수는 저수준 I/O를 위한 것이며, os.open() 또는 pipe()에 의해 반환된 파일 기술자에 적용되어야 합니다. 내장 함수 open() 나 popen() 또는 fdopen()에 의해 반환된 “파일 객체”를 닫으려면, close() 메서드를 사용하십시오.

os.closerange(fd_low, fd_high)

에러는 무시하면서, fd_low(포함)부터 fd_high(제외)까지 모든 파일 기술자를 닫습니다. 다음과 동등합니다 (하지만 훨씬 빠릅니다):

for fd in range(fd_low, fd_high):
    try:
        os.close(fd)
    except OSError:
        pass

os.device_encoding(fd)

fd 와 연관된 장치가 터미널에 연결되어 있을 때 인코딩을 설명하는 문자열을 반환합니다; 그렇지 않으면 None을 반환합니다.

os.dup(fd)

파일 기술자 fd 의 복사본을 반환합니다. 새 파일 기술자는 상속 불가능합니다.

윈도우에서는, 표준 스트림(0: stdin, 1: stdout, 2: stderr)을 복제할 때, 새 파일 기술자가 상속 가능합니다.

버전 3.4에서 변경: 새로운 파일 기술자는 이제 상속 불가능합니다.

os.dup2(fd, fd2, inheritable=True)

파일 기술자 fd 를 fd2에 복제하고, 필요하면 먼저 후자를 닫습니다. fd2를 반환합니다. 새로운 파일 기술자는 기본적으로 상속 가능하고, inheritable 이 False면 상속 불가능합니다.

버전 3.4에서 변경: 선택적 inheritable 매개 변수를 추가했습니다.

버전 3.7에서 변경: 성공하면 fd2 를 반환합니다. 이전에는 항상 None을 반환했습니다.

os.fchmod(fd, mode)

fd 에 의해 주어진 파일의 모드를 숫자 mode 로 변경합니다. mode의 가능한 값은 chmod() 문서를 참조하십시오. 파이썬 3.3부터는, os.chmod(fd, mode)와 같습니다.

가용성: 유닉스.

os.fchown(fd, uid, gid)

fd 에 의해 주어진 파일의 소유자와 그룹 id를 숫자 uid 와 gid로 변경합니다. ID 중 하나를 변경하지 않으려면, 그것을 -1로 설정하십시오. chown()를 참조하십시오. 파이썬 3.3부터는, os.chown(fd, uid, gid)와 같습니다.

가용성: 유닉스.

os.fdatasync(fd)

파일 기술자 fd 로 주어진 파일을 디스크에 쓰도록 강제합니다. 메타 데이터를 갱신하도록 강제하지 않습니다.

가용성: 유닉스.

참고

이 함수는 MacOS에서는 사용할 수 없습니다.

os.fpathconf(fd, name)

열린 파일과 관련된 시스템 구성 정보를 반환합니다. name 은 조회할 구성 값을 지정합니다; 정의된 시스템 값의 이름인 문자열일 수 있습니다; 이 이름은 여러 표준(POSIX.1, 유닉스 95, 유닉스 98 및 기타)에서 지정됩니다. 일부 플랫폼은 추가 이름도 정의합니다. 호스트 운영 체제에 알려진 이름은 pathconf_names 딕셔너리에서 제공됩니다. 이 매핑에 포함되지 않은 구성 변수의 경우, name에 정수를 전달하는 것도 허용됩니다.

name 이 문자열이고 알 수 없으면, ValueError가 발생합니다. name에 대한 특정 값이 호스트 시스템에서 지원되지 않으면, pathconf_names에 포함되어 있어도, 에러 번호가 errno.EINVAL인 OSError가 발생합니다.

파이썬 3.3부터, os.pathconf(fd, name)과 같습니다.

가용성: 유닉스.

os.fstat(fd)

파일 기술자 fd 의 상태를 가져옵니다. stat_result 객체를 반환합니다.

파이썬 3.3부터는, os.stat(fd)와 같습니다.

더 보기

stat() 함수.

os.fstatvfs(fd)

statvfs() 처럼, 파일 기술자 fd 와 연관된 파일을 포함하는 파일 시스템에 대한 정보를 반환합니다. 파이썬 3.3부터는, os.statvfs(fd)와 같습니다.

가용성: 유닉스.

os.fsync(fd)

파일 기술자 fd 의 파일을 디스크에 쓰도록 강제합니다. 유닉스에서는, 네이티브 fsync() 함수를 호출합니다; 윈도우에서는, MS _commit() 함수.

버퍼링 된 파이썬 파일 객체 f로 시작하는 경우, f 와 연관된 모든 내부 버퍼가 디스크에 기록되게 하려면, 먼저 f.flush()를 수행한 다음 os.fsync(f.fileno())를 하십시오.

가용성: 유닉스, 윈도우.

os.ftruncate(fd, length)

파일 기술자 fd에 해당하는 파일을 잘라내어 최대 length 바이트가 되도록 만듭니다. 파이썬 3.3부터는, os.truncate(fd, length)와 같습니다.

가용성: 유닉스, 윈도우.

버전 3.5에서 변경: 윈도우 지원 추가

os.get_blocking(fd)

파일 기술자의 블로킹 모드를 얻어옵니다: O_NONBLOCK 플래그가 설정되었으면 False, 플래그가 지워졌으면 True.

set_blocking() 및 socket.socket.setblocking()도 참조하십시오.

가용성: 유닉스.

버전 3.5에 추가.

os.isatty(fd)

파일 기술자 fd 가 열려 있고 tty(류의) 장치에 연결되어 있으면 True를 반환하고, 그렇지 않으면 False를 반환합니다.

os.lockf(fd, cmd, len)

열린 파일 기술자에 POSIX 록을 적용, 검사 또는 제거합니다. fd 는 열린 파일 기술자입니다. cmd 는 사용할 명령을 지정합니다 - F_LOCK, F_TLOCK, F_ULOCK 또는 F_TEST 중 하나. len 은 잠글 파일의 영역을 지정합니다.

가용성: 유닉스.

버전 3.3에 추가.

os.F_LOCK

os.F_TLOCK

os.F_ULOCK

os.F_TEST

lockf()가 취할 조치를 지정하는 플래그.

가용성: 유닉스.

버전 3.3에 추가.

os.lseek(fd, pos, how)

파일 기술자 fd 의 현재 위치를 how 에 따라 달리 해석되는 위치 pos로 설정합니다: SEEK_SET 이나 0 이면 파일의 시작 부분을 기준으로 위치를 설정합니다; SEEK_CUR이나 1 이면 현재 위치를 기준으로 설정합니다; SEEK_END 나 2 면 파일의 끝을 기준으로 설정합니다. 새 커서 위치를 파일의 시작에서 따진 바이트로 반환합니다.

os.SEEK_SET

os.SEEK_CUR

os.SEEK_END

lseek() 함수의 매개 변수. 값은 각각 0, 1, 2입니다.

버전 3.3에 추가: 일부 운영 체제는 os.SEEK_HOLE 이나 os.SEEK_DATA와 같은 추가 값을 지원할 수 있습니다.

os.open(path, flags, mode=0o777, *, dir_fd=None)

파일 path를 열고 flags 에 따른 다양한 플래그와 때로 mode 따른 모드를 설정합니다. mode를 계산할 때, 현재 umask 값으로 먼저 마스킹합니다. 새롭게 열린 파일의 파일 기술자를 돌려줍니다. 새 파일 기술자는 상속 불가능합니다.

플래그와 모드 값에 대한 설명은, C 런타임 설명서를 참조하십시오; 플래그 상수(O_RDONLY 와 O_WRONLY와 같은)는 os 모듈에 정의되어 있습니다. 특히, 윈도우에서 바이너리 모드로 파일을 열려면 O_BINARY를 추가해야 합니다.

이 함수는 dir_fd 매개 변수로 디렉터리 기술자에 상대적인 경로를 지원할 수 있습니다.

버전 3.4에서 변경: 새로운 파일 기술자는 이제 상속 불가능합니다.

참고

이 함수는 저수준 I/O를 위한 것입니다. 일반적인 사용을 위해서는 내장 함수 open()을 사용하십시오, 이 함수는 read() 및 write() 메서드(와 더 많은 메서드)가있는 파일 객체를 반환합니다. 파일 기술자를 파일 객체로 싸려면, fdopen()을 사용하십시오.

버전 3.3에 추가: dir_fd 인자

버전 3.5에서 변경: 시스템 호출이 인터럽트 되고 시그널 처리기가 예외를 발생시키지 않으면, 함수는 이제 InterruptedError 예외를 일으키는 대신 시스템 호출을 재시도합니다 (이유는 PEP 475 [https://www.python.org/dev/peps/pep-0475]를 참조하세요).

버전 3.6에서 변경: 경로류 객체를 받아들입니다.

다음 상수는 open() 함수에 대한 flags 매개 변수의 옵션입니다. 비트별 OR 연산자 |를 사용하여 결합할 수 있습니다. 일부는 모든 플랫폼에서 사용할 수는 없습니다. 가용성과 사용에 대한 설명은 유닉스의 open(2) 매뉴얼 페이지 또는 윈도우의 MSDN [https://msdn.microsoft.com/en-us/library/z0kc8e3z.aspx]을 참조하십시오.

os.O_RDONLY

os.O_WRONLY

os.O_RDWR

os.O_APPEND

os.O_CREAT

os.O_EXCL

os.O_TRUNC

위의 상수는 유닉스 및 윈도우에서 사용할 수 있습니다.

os.O_DSYNC

os.O_RSYNC

os.O_SYNC

os.O_NDELAY

os.O_NONBLOCK

os.O_NOCTTY

os.O_CLOEXEC

위의 상수는 유닉스에서만 사용할 수 있습니다.

버전 3.3에서 변경: O_CLOEXEC 상수를 추가합니다.

os.O_BINARY

os.O_NOINHERIT

os.O_SHORT_LIVED

os.O_TEMPORARY

os.O_RANDOM

os.O_SEQUENTIAL

os.O_TEXT

위의 상수는 윈도우에서만 사용할 수 있습니다.

os.O_ASYNC

os.O_DIRECT

os.O_DIRECTORY

os.O_NOFOLLOW

os.O_NOATIME

os.O_PATH

os.O_TMPFILE

os.O_SHLOCK

os.O_EXLOCK

위의 상수는 확장이며 C 라이브러리에서 정의하지 않으면 존재하지 않습니다.

버전 3.4에서 변경: 지원하는 시스템에 O_PATH를 추가합니다. 리눅스 커널 3.11 이상에서만 사용 가능한 O_TMPFILE를 추가합니다.

os.openpty()

새로운 가상 터미널 쌍을 엽니다. 파일 기술자의 쌍 (master, slave) 를 반환하는데, 각각 pty와 tty 입니다. 새 파일 기술자는 상속 불가능합니다. (약간) 더 이식성 있는 접근 방식을 사용하려면, pty 모듈을 사용하십시오.

가용성: 일부 유닉스.

버전 3.4에서 변경: 새로운 파일 기술자는 이제 상속 불가능합니다.

os.pipe()

파이프를 만듭니다. 파일 기술자 쌍 (r, w) 를 반환하는데, 각각 읽기와 쓰기에 사용할 수 있습니다. 새 파일 기술자는 상속 불가능합니다.

가용성: 유닉스, 윈도우.

버전 3.4에서 변경: 새로운 파일 기술자는 이제 상속 불가능합니다.

os.pipe2(flags)

flags 가 원자적으로 설정된 파이프를 만듭니다. flags 는 다음과 같은 값들을 하나 이상 OR 해서 만들 수 있습니다: O_NONBLOCK, O_CLOEXEC. 파일 기술자 쌍 (r, w) 를 반환하는데, 각각 읽기와 쓰기에 사용할 수 있습니다.

가용성: 일부 유닉스.

버전 3.3에 추가.

os.posix_fallocate(fd, offset, len)

fd로 지정된 파일이 offset 에서 시작하여 len 바이트 동안 계속되도록 충분한 디스크 공간을 할당합니다.

가용성: 유닉스.

버전 3.3에 추가.

os.posix_fadvise(fd, offset, len, advice)

특정 패턴으로 데이터에 액세스하려는 의도를 알려 커널이 최적화할 수 있도록 합니다. 조언(advice)은 fd에 의해 지정된 파일의 offset 에서 시작하여 len 바이트 동안 계속되는 영역에 적용됩니다. advice는 POSIX_FADV_NORMAL, POSIX_FADV_SEQUENTIAL, POSIX_FADV_RANDOM, POSIX_FADV_NOREUSE, POSIX_FADV_WILLNEED 또는 POSIX_FADV_DONTNEED 중 하나입니다.

가용성: 유닉스.

버전 3.3에 추가.

os.POSIX_FADV_NORMAL

os.POSIX_FADV_SEQUENTIAL

os.POSIX_FADV_RANDOM

os.POSIX_FADV_NOREUSE

os.POSIX_FADV_WILLNEED

os.POSIX_FADV_DONTNEED

사용 가능성이 큰 액세스 패턴을 지정하는 posix_fadvise()의 advice 에 사용될 수 있는 플래그.

가용성: 유닉스.

버전 3.3에 추가.

os.pread(fd, n, offset)

파일 기술자 fd에서 offset 의 위치부터 최대 n 바이트를 읽어 들이고, 파일 오프셋은 변경되지 않은 채로 남겨 둡니다.

읽어 들인 바이트를 포함하는 바이트열을 돌려줍니다. fd 에 의해 참조된 파일의 끝에 도달하면, 빈 바이트열 객체가 반환됩니다.

가용성: 유닉스.

버전 3.3에 추가.

os.preadv(fd, buffers, offset, flags=0)

파일 기술자 fd에서 offset 위치부터 가변 바이트열류 객체들 buffers 로 읽어 들이고, 파일 오프셋은 변경되지 않은 채로 남겨 둡니다. 데이터가 가득 찰 때까지 각 버퍼로 데이터를 전송한 다음 나머지 데이터를 보관하기 위해 시퀀스의 다음 버퍼로 이동합니다.

flags 인자는 다음 플래그 중 0개 이상의 비트별 OR를 포함합니다:

RWF_HIPRI

RWF_NOWAIT

실제로 읽힌 총 바이트 수를 반환합니다. 이 값은 모든 객체의 총 용량보다 작을 수 있습니다.

운영 체제는 사용할 수 있는 버퍼 수에 한계(sysconf() 값 'SC_IOV_MAX')를 설정할 수 있습니다.

os.readv() 와 os.pread()의 기능을 결합합니다.

가용성: 리눅스 2.6.30 이상, FreeBSD 6.0 이상, OpenBSD 2.7 이상. flags를 사용하려면 리눅스 4.6 이상이 필요합니다.

버전 3.7에 추가.

os.RWF_NOWAIT

즉시 사용할 수 없는 데이터를 기다리지 않습니다. 이 플래그를 지정하면, 하부 저장 장치에서 데이터를 읽어야 하거나 록을 기다려야 할 때 즉시 시스템 호출이 반환됩니다.

일부 데이터가 성공적으로 읽히면, 읽은 바이트 수를 반환합니다. 읽은 바이트가 없으면, -1을 반환하고 errno를 errno.EAGAIN로 설정합니다.

가용성: 리눅스 4.14 이상.

버전 3.7에 추가.

os.RWF_HIPRI

우선순위가 높은 읽기/쓰기. 블록 기반 파일 시스템이 장치의 폴링을 사용할 수 있게 하여, 지연은 짧아 지지만, 추가 자원을 사용할 수 있습니다.

현재, 리눅스에서, 이 기능은 O_DIRECT 플래그를 사용하여 열린 파일 기술자에만 사용할 수 있습니다.

가용성: 리눅스 4.6 이상.

버전 3.7에 추가.

os.pwrite(fd, str, offset)

파일 기술자 fd의 offset 위치에 str 바이트열을 쓰고, 파일 오프셋은 변경되지 않은 채로 남겨 둡니다.

실제로 쓴 바이트 수를 반환합니다.

가용성: 유닉스.

버전 3.3에 추가.

os.pwritev(fd, buffers, offset, flags=0)

buffers 내용을 파일 기술자 fd의 오프셋 offset 에 쓰고, 파일 오프셋은 변경되지 않은 채로 남겨 둡니다. buffers 는 바이트열류 객체의 시퀀스 여야 합니다. 버퍼는 배열 순서로 처리됩니다. 첫 번째 버퍼의 전체 내용은 두 번째 버퍼로 진행하기 전에 기록되고, 같은 식으로 계속 진행합니다.

flags 인자는 다음 플래그 중 0개 이상의 비트별 OR를 포함합니다:

RWF_DSYNC

RWF_SYNC

실제로 쓴 총 바이트 수를 반환합니다.

운영 체제는 사용할 수 있는 버퍼 수에 한계(sysconf() 값 'SC_IOV_MAX')를 설정할 수 있습니다.

os.writev() 와 os.pwrite()의 기능을 결합합니다.

가용성: 리눅스 2.6.30 이상, FreeBSD 6.0 이상, OpenBSD 2.7 이상. flags를 사용하려면 리눅스 4.7 이상이 필요합니다.

버전 3.7에 추가.

os.RWF_DSYNC

O_DSYNC open(2) 플래그의 쓰기마다 지정할 수 있는 버전을 제공합니다. 이 플래그 효과는 시스템 호출로 기록된 데이터 범위에만 적용됩니다.

가용성: 리눅스 4.7 이상.

버전 3.7에 추가.

os.RWF_SYNC

O_SYNC open(2) 플래그의 쓰기마다 지정할 수 있는 버전을 제공합니다. 이 플래그 효과는 시스템 호출로 기록된 데이터 범위에만 적용됩니다.

가용성: 리눅스 4.7 이상.

버전 3.7에 추가.

os.read(fd, n)

파일 기술자 fd에서 최대 n 바이트를 읽습니다.

읽어 들인 바이트를 포함하는 바이트열을 돌려줍니다. fd 에 의해 참조된 파일의 끝에 도달하면, 빈 바이트열 객체가 반환됩니다.

참고

이 함수는 저수준 I/O를 위한 것이며 os.open() 이나 pipe()에 의해 반환된 파일 기술자에 적용되어야 합니다. 내장 함수 open() 이나 popen() 또는 fdopen()에 의해 반환된 “파일 객체”나 sys.stdin을 읽으려면, 그것의 read() 나 readline() 메서드를 사용하십시오.

버전 3.5에서 변경: 시스템 호출이 인터럽트 되고 시그널 처리기가 예외를 발생시키지 않으면, 함수는 이제 InterruptedError 예외를 일으키는 대신 시스템 호출을 재시도합니다 (이유는 PEP 475 [https://www.python.org/dev/peps/pep-0475]를 참조하세요).

os.sendfile(out, in, offset, count)

os.sendfile(out, in, offset, count, [headers, ][trailers, ]flags=0)

파일 기술자 in에서 파일 기술자 out 으로 offset에서 시작하여 count 바이트를 복사합니다. 전송된 바이트 수를 반환합니다. EOF에 도달하면 0을 반환합니다.

첫 번째 함수 서명은 sendfile()를 정의하는 모든 플랫폼에서 지원됩니다.

리눅스에서, offset이 None으로 주어지면, in의 현재 위치에서 바이트를 읽고 in의 위치가 갱신됩니다.

두 번째 경우는 맥 OS X와 FreeBSD 에 사용될 수 있는데, headers 와 trailers 는 in 의 데이터가 기록되는 전후에 기록되는 버퍼의 임의의 시퀀스입니다. 첫 번째 경우와 같은 결과를 반환합니다.

맥 OS X 및 FreeBSD 에서, count 의 값 0은 in 의 끝에 도달할 때까지 보내도록 지정합니다.

모든 플랫폼은 out 파일 기술자로 소켓을 지원하고, 일부 플랫폼은 다른 유형(예를 들어 일반 파일, 파이프)들도 허락합니다.

이기종 플랫폼 응용 프로그램은 headers, trailers 및 flags 인자를 사용해서는 안 됩니다.

가용성: 유닉스.

참고

sendfile()의 고수준 래퍼는, socket.socket.sendfile()을 보십시오.

버전 3.3에 추가.

os.set_blocking(fd, blocking)

지정된 파일 기술자의 블로킹 모드를 설정합니다. blocking이 False면 O_NONBLOCK 플래그를 설정하고, 그렇지 않으면 플래그를 지웁니다.

get_blocking()과 socket.socket.setblocking()도 참조하십시오.

가용성: 유닉스.

버전 3.5에 추가.

os.SF_NODISKIO

os.SF_MNOWAIT

os.SF_SYNC

구현이 지원하는 경우, sendfile() 함수에 대한 매개 변수입니다.

가용성: 유닉스.

버전 3.3에 추가.

os.readv(fd, buffers)

파일 기술자 fd에서 여러 가변 바이트열류 객체 buffers로 읽어 들입니다. 데이터가 가득 찰 때까지 각 버퍼로 데이터를 전송한 다음 나머지 데이터를 보관하기 위해 시퀀스의 다음 버퍼로 이동합니다.

실제로 읽힌 총 바이트 수를 반환합니다. 이 값은 모든 객체의 총 용량보다 작을 수 있습니다.

운영 체제는 사용할 수 있는 버퍼 수에 한계(sysconf() 값 'SC_IOV_MAX')를 설정할 수 있습니다.

가용성: 유닉스.

버전 3.3에 추가.

os.tcgetpgrp(fd)

fd(os.open()에 의해 반환된 것과 같은 열린 파일 기술자)에 의해 주어진 터미널과 관련된 프로세스 그룹을 반환합니다.

가용성: 유닉스.

os.tcsetpgrp(fd, pg)

fd(os.open()에 의해 반환된 것과 같은 열린 파일 기술자)에 의해 주어진 터미널과 관련된 프로세스 그룹을 pg로 설정합니다.

가용성: 유닉스.

os.ttyname(fd)

파일 기술자 fd와 관련된 터미널 장치를 나타내는 문자열을 돌려줍니다. fd 가 터미널 장치와 연관되어 있지 않으면, 예외가 발생합니다.

가용성: 유닉스.

os.write(fd, str)

str 바이트열을 파일 기술자 fd 에 씁니다.

실제로 쓴 바이트 수를 반환합니다.

참고

이 함수는 저수준 I/O를 위한 것이며 os.open() 이나 pipe()에 의해 반환된 파일 기술자에 적용되어야 합니다. 내장 함수 open() 이나 popen() 또는 fdopen()에 의해 반환된 “파일 객체”나 sys.stdout 또는 sys.stderr에 쓰려면, 그것의 write() 메서드를 사용하십시오.

버전 3.5에서 변경: 시스템 호출이 인터럽트 되고 시그널 처리기가 예외를 발생시키지 않으면, 함수는 이제 InterruptedError 예외를 일으키는 대신 시스템 호출을 재시도합니다 (이유는 PEP 475 [https://www.python.org/dev/peps/pep-0475]를 참조하세요).

os.writev(fd, buffers)

buffers 내용을 파일 기술자 fd에 씁니다. buffers 는 바이트열류 객체의 시퀀스 여야 합니다. 버퍼는 배열 순서로 처리됩니다. 첫 번째 버퍼의 전체 내용은 두 번째 버퍼로 진행하기 전에 기록되고, 같은 식으로 계속 진행합니다.

실제로 쓴 총 바이트 수를 반환합니다.

운영 체제는 사용할 수 있는 버퍼 수에 한계(sysconf() 값 'SC_IOV_MAX')를 설정할 수 있습니다.

가용성: 유닉스.

버전 3.3에 추가.

터미널의 크기 조회하기

버전 3.3에 추가.

os.get_terminal_size(fd=STDOUT_FILENO)

터미널 창의 크기를 (columns, lines) 로 반환하는데, terminal_size 형의 튜플입니다.

선택적 인자 fd(기본값 STDOUT_FILENO, 즉 표준 출력)는 조회할 파일 기술자를 지정합니다.

파일 기술자가 터미널에 연결되어 있지 않으면, OSError가 발생합니다.

shutil.get_terminal_size()가 일반적으로 사용해야 하는 고수준 함수이며, os.get_terminal_size는 저수준 구현입니다.

가용성: 유닉스, 윈도우.

class os.terminal_size

터미널 창 크기 (columns, lines)를 저장하는 튜플의 서브 클래스.

columns

문자 단위의 터미널 창의 너비.

lines

문자 단위의 터미널 창의 높이.

파일 기술자의 상속

버전 3.4에 추가.

파일 기술자는 자식 프로세스가 파일 기술자를 상속받을 수 있는지를 나타내는 “상속 가능” 플래그를 가지고 있습니다. 파이썬 3.4부터, 파이썬에 의해 생성된 파일 기술자는 기본적으로 상속 불가능합니다.

유닉스에서는, 상속 불가능한 파일 기술자는 새 프로그램 실행 시 자식 프로세스에서 닫히고, 다른 파일 기술자는 상속됩니다.

윈도우에서는, 항상 상속되는 표준 스트림(파일 기술자 0, 1, 2: stdin, stdout, stderr)을 제외하고, 상속 불가능한 핸들 및 파일 기술자는 자식 프로세스에서 닫힙니다. spawn* 함수를 사용하면, 상속 가능한 모든 핸들과 상속 가능한 모든 파일 기술자가 상속됩니다. subprocess 모듈을 사용하면, 표준 스트림을 제외한 모든 파일 기술자가 닫히고, 상속 가능한 핸들은 close_fds 매개 변수가 False 일 때만 상속됩니다.

os.get_inheritable(fd)

지정된 파일 기술자의 “상속 가능” 플래그를 가져옵니다 (논릿값).

os.set_inheritable(fd, inheritable)

지정된 파일 기술자의 “상속 가능(inheritable)” 플래그를 설정합니다.

os.get_handle_inheritable(handle)

지정된 핸들의 “상속 가능” 플래그를 가져옵니다 (논릿값).

가용성: 윈도우.

os.set_handle_inheritable(handle, inheritable)

지정된 핸들의 “상속 가능(inheritable)” 플래그를 설정합니다.

가용성: 윈도우.

파일과 디렉터리

일부 유닉스 플랫폼에서, 이 함수 중 많은 것들이 다음 기능 중 하나 이상을 지원합니다:

파일 기술자 지정: 일부 함수의 경우, path 인자는 경로명을 제공하는 문자열뿐만 아니라 파일 기술자일 수도 있습니다. 그러면 그 함수는 기술자가 참조하는 파일에서 작동합니다. (POSIX 시스템에서, 파이썬은 함수의 f... 버전을 호출합니다.)

os.supports_fd를 사용하여, 플랫폼에서 파일 기술자로 path를 지정할 수 있는지를 확인할 수 있습니다. 사용할 수 없을 때, 사용하면 NotImplementedError를 발생시킵니다.

함수가 dir_fd 나 follow_symlinks 인자도 지원하면, path 에 파일 기술자를 제공할 때, 이 중 하나를 지정하는 것은 에러입니다.

디렉터리 기술자에 상대적인 경로: dir_fd 가 None이 아니면, 디렉터리를 가리키는 파일 기술자여야 하며, 대상 경로는 상대 경로여야 합니다; 그러면 경로는 그 디렉터리에 상대적입니다. 절대 경로이면, dir_fd 는 무시됩니다. (POSIX 시스템에서, 파이썬은 함수의 ...at 또는 f...at 버전을 호출합니다.)

os.supports_dir_fd를 사용하여, 플랫폼에서 dir_fd가 지원되는지를 확인할 수 있습니다. 사용할 수 없을 때, 사용하면 NotImplementedError를 발생시킵니다.

심볼릭 링크를 따르지 않음: follow_symlinks 가 False고, 대상 경로의 마지막 요소가 심볼릭 링크면, 함수는 링크가 가리키는 파일 대신 심볼릭 링크 자체에 대해 작동합니다. (POSIX 시스템에서, 파이썬은 함수의 l... 버전을 호출합니다.)

os.supports_follow_symlinks를 사용하여, 플랫폼에서 follow_symlinks가 지원되는지를 확인할 수 있습니다. 사용할 수 없을 때, 사용하면 NotImplementedError를 발생시킵니다.

os.access(path, mode, *, dir_fd=None, effective_ids=False, follow_symlinks=True)

실제(real) uid/gid를 사용해서 path를 액세스할 수 있는지 검사합니다. 대부분의 연산은 유효한(effective) uid/gid를 사용할 것이므로, 이 함수는 suid/sgid 환경에서 호출하는 사용자가 지정된 path 에 대한 액세스 권한이 있는지 검사하는데 사용할 수 있습니다. path가 존재하는지를 검사하려면 mode 는 F_OK 여야 하며, 권한을 검사하려면 하나 이상의 R_OK, W_OK 및 X_OK를 OR 값일 수 있습니다. 액세스가 허용되면 True를 반환하고, 그렇지 않으면 False를 반환합니다. 더 자세한 정보는 유닉스 매뉴얼 페이지 access(2)를 참조하십시오.

이 함수는 디렉터리 기술자에 상대적인 경로 와 심볼릭 링크를 따르지 않음을 지원할 수 있습니다.

effective_ids 가 True면, access()는 실제(real) uid/gid 대신 유효한(effective) uid/gid를 사용하여 액세스 검사를 수행합니다. effective_ids 는 플랫폼에서 지원되지 않을 수 있습니다; os.supports_effective_ids를 사용하여, 사용할 수 있는지를 확인할 수 있습니다. 사용할 수 없을 때, 사용하면 NotImplementedError를 발생시킵니다.

참고

예를 들어, 실제로 open()를 사용하여 파일을 열기 전에, access()를 사용하여 파일을 여는 권한이 있는지 확인하는 것은 보안 구멍을 만듭니다. 사용자가 파일을 확인하고 조작을 위해 열기 사이의 짧은 시간 간격을 악용할 수 있기 때문입니다. EAFP 기법을 사용하는 것이 좋습니다. 예를 들면:

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"

는 다음과 같이 쓰는 것이 더 좋습니다:

try:
    fp = open("myfile")
except PermissionError:
    return "some default data"
else:
    with fp:
        return fp.read()

참고

access()가 성공할 것임을 알릴 때도, I/O 연산이 실패할 수 있습니다. 특히 일반적인 POSIX 권한 비트 모델을 넘어서는 권한 의미가 있을 수 있는 네트워크 파일 시스템에 대한 연산에서 그럴 수 있습니다.

버전 3.3에서 변경: dir_fd, effective_ids 및 follow_symlinks 매개 변수를 추가했습니다.

버전 3.6에서 변경: 경로류 객체를 받아들입니다.

os.F_OK

os.R_OK

os.W_OK

os.X_OK

path 의 존재 여부, 읽기 가능성, 쓰기 가능성 및 실행 가능성을 검사하기 위해, access()의 mode 매개 변수로 전달할 값입니다.

os.chdir(path)

현재 작업 디렉터리를 path로 변경합니다.

이 함수는 파일 기술자 지정을 지원할 수 있습니다. 기술자는 열려있는 파일이 아니라, 열려있는 디렉터리를 참조해야 합니다.

This function can raise OSError and subclasses such as FileNotFoundError, PermissionError, and NotADirectoryError.

버전 3.3에 추가: 일부 플랫폼에서 path 를 파일 기술자로 지정하는 지원이 추가되었습니다.

버전 3.6에서 변경: 경로류 객체를 받아들입니다.

os.chflags(path, flags, *, follow_symlinks=True)

path 의 플래그를 숫자 flags로 설정합니다. flags는 다음 값들(stat 모듈에 정의된 대로)의 조합(비트별 OR)을 취할 수 있습니다:

stat.UF_NODUMP

stat.UF_IMMUTABLE

stat.UF_APPEND

stat.UF_OPAQUE

stat.UF_NOUNLINK

stat.UF_COMPRESSED

stat.UF_HIDDEN

stat.SF_ARCHIVED

stat.SF_IMMUTABLE

stat.SF_APPEND

stat.SF_NOUNLINK

stat.SF_SNAPSHOT

이 함수는 심볼릭 링크를 따르지 않음을 지원할 수 있습니다.

가용성: 유닉스.

버전 3.3에 추가: follow_symlinks 인자.

버전 3.6에서 변경: 경로류 객체를 받아들입니다.

os.chmod(path, mode, *, dir_fd=None, follow_symlinks=True)

path의 모드를 숫자 mode로 변경합니다. mode 는 다음 값들(stat 모듈에 정의된 대로)이나 이들의 비트별 OR 조합을 취할 수 있습니다:

stat.S_ISUID

stat.S_ISGID

stat.S_ENFMT

stat.S_ISVTX

stat.S_IREAD

stat.S_IWRITE

stat.S_IEXEC

stat.S_IRWXU

stat.S_IRUSR

stat.S_IWUSR

stat.S_IXUSR

stat.S_IRWXG

stat.S_IRGRP

stat.S_IWGRP

stat.S_IXGRP

stat.S_IRWXO

stat.S_IROTH

stat.S_IWOTH

stat.S_IXOTH

이 함수는 파일 기술자 지정, 디렉터리 기술자에 상대적인 경로 및 심볼릭 링크를 따르지 않음을 지원할 수 있습니다.

참고

윈도우가 chmod()를 지원하더라도, (stat.S_IWRITE 와 stat.S_IREAD 상수나 해당 정숫값을 통해) 파일의 읽기 전용 플래그만 설정할 수 있습니다. 다른 모든 비트는 무시됩니다.

버전 3.3에 추가: path를 열린 파일 기술자로 지정하는 지원과 dir_fd 및 follow_symlinks 인자가 추가되었습니다.

버전 3.6에서 변경: 경로류 객체를 받아들입니다.

os.chown(path, uid, gid, *, dir_fd=None, follow_symlinks=True)

path 의 소유자와 그룹 ID를 숫자 uid 와 gid로 변경합니다. ID 중 하나를 변경하지 않으려면, 그것을 -1로 설정하십시오.

이 함수는 파일 기술자 지정, 디렉터리 기술자에 상대적인 경로 및 심볼릭 링크를 따르지 않음을 지원할 수 있습니다.

숫자 ID 이외에 이름을 허용하는 고수준 함수는 shutil.chown()를 참조하십시오.

가용성: 유닉스.

버전 3.3에 추가: path 에 열린 파일 기술자를 지정하는 것과 dir_fd 및 follow_symlinks 인자에 대한 지원이 추가되었습니다.

버전 3.6에서 변경: 경로류 객체를 지원합니다.

os.chroot(path)

현재 프로세스의 루트 디렉터리를 path로 변경합니다.

가용성: 유닉스.

버전 3.6에서 변경: 경로류 객체를 받아들입니다.

os.fchdir(fd)

현재 작업 디렉터리를 파일 기술자 fd가 나타내는 디렉터리로 변경합니다. 기술자는 열려있는 파일이 아니라 열려있는 디렉터리를 참조해야 합니다. 파이썬 3.3부터는, os.chdir(fd)와 같습니다.

가용성: 유닉스.

os.getcwd()

현재 작업 디렉터리를 나타내는 문자열을 반환합니다.

os.getcwdb()

현재 작업 디렉터리를 나타내는 바이트열을 반환합니다.

os.lchflags(path, flags)

path 의 플래그를, chflags() 처럼, 숫자 flags로 설정하지만, 심볼릭 링크를 따르지 않습니다. 파이썬 3.3부터는, os.chflags(path, flags, follow_symlinks=False)와 같습니다.

가용성: 유닉스.

버전 3.6에서 변경: 경로류 객체를 받아들입니다.

os.lchmod(path, mode)

path 모드를 숫자 mode로 변경합니다. path가 심볼릭 링크면, 이 함수는 타깃이 아닌 심볼릭 링크에 영향을 미칩니다. mode의 가능한 값은 chmod() 문서를 참조하십시오. 파이썬 3.3부터는, os.chmod(path, mode, follow_symlinks=False)와 같습니다.

가용성: 유닉스.

버전 3.6에서 변경: 경로류 객체를 받아들입니다.

os.lchown(path, uid, gid)

path 의 소유자와 그룹 ID를 숫자 uid 와 gid로 변경합니다. 이 함수는 심볼릭 링크를 따르지 않습니다. 파이썬 3.3부터는, os.chown(path, uid, gid, follow_symlinks=False)와 같습니다.

가용성: 유닉스.

버전 3.6에서 변경: 경로류 객체를 받아들입니다.

os.link(src, dst, *, src_dir_fd=None, dst_dir_fd=None, follow_symlinks=True)

src를 가리키는 dst 라는 이름의 하드 링크를 만듭니다.

이 함수는 디렉터리 기술자에 상대적인 경로를 제공하기 위해 src_dir_fd 와/나 dst_dir_fd 를 지정하는 것과, 심볼릭 링크를 따르지 않음을 지원할 수 있습니다.

가용성: 유닉스, 윈도우.

버전 3.2에서 변경: 윈도우 지원이 추가되었습니다.

버전 3.3에 추가: src_dir_fd , dst_dir_fd 및 follow_symlinks 인자를 추가했습니다.

버전 3.6에서 변경: src 및 dst로 경로류 객체를 받아들입니다.

os.listdir(path='.')

path에 의해 주어진 디렉터리에 있는 항목들의 이름을 담고 있는 리스트를 반환합니다. 리스트는 임의의 순서로 나열되며, 디렉터리에 존재하더라도 특수 항목 '.' 과 '..'는 포함하지 않습니다.

path는 경로류 객체 일 수 있습니다. path 가 bytes 형이면 (직접 또는 PathLike 인터페이스를 통해 간접적으로), 반환되는 파일명도 bytes 형입니다; 다른 모든 상황에서는 형 str이 됩니다.

이 함수는 또한 파일 기술자 지정을 지원할 수 있습니다; 파일 기술자는 디렉터리를 참조해야 합니다.

참고

str 파일명을 bytes로 인코딩하려면, fsencode()를 사용하십시오.

더 보기

scandir() 함수는 파일 어트리뷰트 정보와 함께 디렉터리 항목을 반환하므로, 많은 일반적인 사용 사례에서 더 나은 성능을 제공합니다.

버전 3.2에서 변경: path 매개 변수는 선택 사항이 되었습니다.

버전 3.3에 추가: path에 열린 파일 기술자를 지정하는 지원이 추가되었습니다.

버전 3.6에서 변경: 경로류 객체를 받아들입니다.

os.lstat(path, *, dir_fd=None)

주어진 경로에 대해 lstat() 시스템 호출과 동등한 작업을 수행합니다. stat()와 유사하지만, 심볼릭 링크를 따르지 않습니다. stat_result 객체를 반환합니다.

심볼릭 링크를 지원하지 않는 플랫폼에서, 이 함수는 stat()의 별칭입니다.

파이썬 3.3부터는, os.stat(path, dir_fd=dir_fd, follow_symlinks=False)와 같습니다.

이 기능은 디렉터리 기술자에 상대적인 경로도 지원할 수 있습니다.

더 보기

stat() 함수.

버전 3.2에서 변경: 윈도우 6.0 (Vista) 심볼릭 링크에 대한 지원이 추가되었습니다.

버전 3.3에서 변경: dir_fd 매개 변수가 추가되었습니다.

버전 3.6에서 변경: src 및 dst로 경로류 객체를 받아들입니다.

os.mkdir(path, mode=0o777, *, dir_fd=None)

숫자 모드 mode로 path 라는 디렉터리를 만듭니다.

디렉터리가 이미 존재하면, FileExistsError가 발생합니다.

일부 시스템에서는, mode가 무시됩니다. 모드가 사용될 때, 현재 umask 값으로 먼저 마스킹합니다. 마지막 9비트 (즉, mode 의 8진 표현의 마지막 3자리 수) 이외의 비트가 설정되면, 그 의미는 플랫폼에 따라 다릅니다. 일부 플랫폼에서는, 이것들이 무시되며, 설정하려면 명시적으로 chmod()를 호출해야 합니다.

이 기능은 디렉터리 기술자에 상대적인 경로도 지원할 수 있습니다.

임시 디렉터리를 만들 수도 있습니다; tempfile 모듈의 tempfile.mkdtemp() 함수를 참조하십시오.

버전 3.3에 추가: dir_fd 인자

버전 3.6에서 변경: 경로류 객체를 받아들입니다.

os.makedirs(name, mode=0o777, exist_ok=False)

재귀적 디렉터리 생성 함수. mkdir()와 비슷하지만, 말단 디렉터리를 포함하는 데 필요한 모든 중간 수준 디렉터리들을 만듭니다.

mode 매개 변수는 말단 디렉터리를 만들기 위해 mkdir()로 전달됩니다; 이것이 어떻게 해석되는지는 mkdir() 설명을 보십시오. 새로 만들어지는 부모 디렉터리들의 파일 권한 비트를 설정하려면, makedirs()를 호출하기 전에 umask를 설정할 수 있습니다. 이미 존재하는 부모 디렉터리의 파일 권한 비트는 변경되지 않습니다.

If exist_ok is False (the default), an FileExistsError is raised if the target directory already exists.

참고

makedirs()는 생성할 경로 요소에 pardir(예를 들어, 유닉스 시스템의 경우 “..”)이 포함되어 있으면 혼란해 할 수 있습니다.

이 함수는 UNC 경로를 올바르게 처리합니다.

버전 3.2에 추가: exist_ok 매개 변수.

버전 3.4.1에서 변경: 파이썬 3.4.1 이전에는, exist_ok 가 True이고 디렉터리가 존재한다면, mode 가 기존 디렉터리의 모드와 일치하지 않을 때, makedirs()는 여전히 에러를 발생시킵니다. 이 동작은 안전하게 구현할 수 없으므로, 파이썬 3.4.1에서 제거되었습니다. bpo-21082 [https://bugs.python.org/issue?@action=redirect&bpo=21082]를 참조하십시오.

버전 3.6에서 변경: 경로류 객체를 받아들입니다.

버전 3.7에서 변경: mode 인자는 더는 새로 만들어지는 중간 수준 디렉터리의 파일 권한 비트에 영향을 주지 않습니다.

os.mkfifo(path, mode=0o666, *, dir_fd=None)

숫자 모드 mode로 path 라는 이름의 FIFO(이름있는 파이프)를 만듭니다. 현재 umask 값으로 먼저 모드를 마스킹합니다.

이 기능은 디렉터리 기술자에 상대적인 경로도 지원할 수 있습니다.

FIFO는 일반 파일처럼 액세스할 수 있는 파이프입니다. FIFO는 삭제될 때까지 존재합니다 (예를 들어 os.unlink()로). 일반적으로, FIFO는 “클라이언트”와 “서버” 유형 프로세스 사이에서 랑데부로 사용됩니다: 서버는 FIFO를 읽기 용도로 열고, 클라이언트는 쓰기 용도로 엽니다. mkfifo()가 FIFO를 열지는 않는다는 점에 유의하십시오 — 단지 랑데부 포인트를 생성합니다.

가용성: 유닉스.

버전 3.3에 추가: dir_fd 인자

버전 3.6에서 변경: 경로류 객체를 받아들입니다.

os.mknod(path, mode=0o600, device=0, *, dir_fd=None)

path 라는 이름의 파일 시스템 노드(파일, 장치 특수 파일 또는 이름있는 파이프)를 만듭니다. mode 는 사용 권한과 생성될 노드의 유형을 모두 지정하며, stat.S_IFREG, stat.S_IFCHR, stat.S_IFBLK 및 stat.S_IFIFO 중 하나와 결합(비트별 OR)합니다 (이 상수들은 stat에 있습니다). stat.S_IFCHR와 stat.S_IFBLK의 경우, device 는 새로 만들어지는 장치 특수 파일(아마도 os.makedev()를 사용해서)을 정의합니다, 그렇지 않으면 무시됩니다.

이 기능은 디렉터리 기술자에 상대적인 경로도 지원할 수 있습니다.

가용성: 유닉스.

버전 3.3에 추가: dir_fd 인자

버전 3.6에서 변경: 경로류 객체를 받아들입니다.

os.major(device)

원시 장치 번호(보통 stat의 st_dev 이나 st_rdev 어트리뷰트)에서 장치 주 번호를 추출합니다.

os.minor(device)

원시 장치 번호(보통 stat의 st_dev 이나 st_rdev 어트리뷰트)에서 장치 부 번호를 추출합니다.

os.makedev(major, minor)

주 장치 번호와 부 장치 번호로 원시 장치 번호를 조립합니다.

os.pathconf(path, name)

이름있는 파일과 관련된 시스템 구성 정보를 반환합니다. name 은 조회할 구성 값을 지정합니다; 정의된 시스템 값의 이름인 문자열일 수 있습니다; 이 이름은 여러 표준(POSIX.1, 유닉스 95, 유닉스 98 및 기타)에서 지정됩니다. 일부 플랫폼은 추가적인 이름도 정의합니다. 호스트 운영 체제에 알려진 이름은 pathconf_names 딕셔너리에서 제공됩니다. 이 매핑에 포함되지 않은 구성 변수를 위해, name에 정수를 전달하는 것도 허용됩니다.

name 이 문자열이고 알 수 없으면, ValueError가 발생합니다. name에 대한 특정 값이 호스트 시스템에서 지원되지 않으면, pathconf_names에 포함되어 있어도, 에러 번호가 errno.EINVAL인 OSError가 발생합니다.

이 함수는 파일 기술자 지정을 지원할 수 있습니다.

가용성: 유닉스.

버전 3.6에서 변경: 경로류 객체를 받아들입니다.

os.pathconf_names

pathconf()와 fpathconf()가 받아들이는 이름을 호스트 운영 체제에서 해당 이름에 대해 정의된 정숫값으로 매핑하는 딕셔너리. 이것은 시스템에 알려진 이름 집합을 판별하는 데 사용될 수 있습니다.

가용성: 유닉스.

os.readlink(path, *, dir_fd=None)

심볼릭 링크가 가리키는 경로를 나타내는 문자열을 반환합니다. 결과는 절대 또는 상대 경로명일 수 있습니다; 상대 경로이면 os.path.join(os.path.dirname(path), result)를 사용하여 절대 경로명으로 변환할 수 있습니다.

path 가 (직접 또는 PathLike 인터페이스를 통해 간접적으로) 문자열 객체면, 결과도 문자열 객체가 되고, 호출은 UnicodeDecodeError를 발생시킬 수 있습니다. path 가 (직접 또는 간접적으로) 바이트열 객체면, 결과는 바이트열 객체가 됩니다.

이 기능은 디렉터리 기술자에 상대적인 경로도 지원할 수 있습니다.

가용성: 유닉스, 윈도우.

버전 3.2에서 변경: 윈도우 6.0 (Vista) 심볼릭 링크에 대한 지원이 추가되었습니다.

버전 3.3에 추가: dir_fd 인자

버전 3.6에서 변경: 경로류 객체를 받아들입니다.

os.remove(path, *, dir_fd=None)

Remove (delete) the file path. If path is a directory, an IsADirectoryError is raised. Use rmdir() to remove directories.

이 함수는 디렉터리 기술자에 상대적인 경로를 지원할 수 있습니다.

윈도우에서, 사용 중인 파일을 제거하려고 시도하면 예외가 발생합니다; 유닉스에서는 디렉터리 항목이 제거되지만, 원본 파일이 더는 사용되지 않을 때까지 파일에 할당된 저장 공간을 사용할 수 없습니다.

이 함수는 의미 적으로 unlink()와 같습니다.

버전 3.3에 추가: dir_fd 인자

버전 3.6에서 변경: 경로류 객체를 받아들입니다.

os.removedirs(name)

재귀적으로 디렉터리를 제거합니다. rmdir() 처럼 동작하는데 다음과 같은 차이가 있습니다. 말단 디렉터리가 성공적으로 제거되면, removedirs()는 에러가 발생할 때까지 path에 언급된 모든 상위 디렉터리를 연속적으로 제거하려고 합니다 (에러는 무시되는데, 이는 일반적으로 부모 디렉터리가 비어 있음을 뜻하기 때문입니다). 예를 들어, os.removedirs('foo/bar/baz')는 먼저 'foo/bar/baz' 디렉터리를 제거한 다음, 'foo/bar' 및 'foo'가 비어 있으면 제거합니다. 말단 디렉터리를 성공적으로 제거할 수 없으면, OSError를 발생시킵니다.

버전 3.6에서 변경: 경로류 객체를 받아들입니다.

os.rename(src, dst, *, src_dir_fd=None, dst_dir_fd=None)

Rename the file or directory src to dst. If dst exists, the operation will fail with an OSError subclass in a number of cases:

On Windows, if dst exists a FileExistsError is always raised.

On Unix, if src is a file and dst is a directory or vice-versa, an IsADirectoryError or a NotADirectoryError will be raised respectively. If both are directories and dst is empty, dst will be silently replaced. If dst is a non-empty directory, an OSError is raised. If both are files, dst it will be replaced silently if the user has permission. The operation may fail on some Unix flavors if src and dst are on different filesystems. If successful, the renaming will be an atomic operation (this is a POSIX requirement).

이 함수는 디렉터리 기술자에 상대적인 경로를 제공하도록 src_dir_fd 와/나 dst_dir_fd 를 지정하는 것을 지원할 수 있습니다.

플랫폼에 무관하게 대상을 덮어쓰길 원하면, replace()를 사용하십시오.

버전 3.3에 추가: src_dir_fd 및 dst_dir_fd 인자

버전 3.6에서 변경: src 및 dst로 경로류 객체를 받아들입니다.

os.renames(old, new)

재귀적 디렉터리 또는 파일 이름 바꾸기 함수. rename()처럼 작동하지만, 새 경로명이 유효하도록 만들기 위해 먼저 필요한 중간 디렉터리를 만드는 점이 다릅니다. 이름을 변경한 후에는, 이전 이름의 가장 오른쪽 경로 세그먼트에 해당하는 디렉터리를 removedirs()를 사용하여 제거합니다.

참고

이 함수는 말단 디렉터리나 파일을 제거하는 데 필요한 권한이 없을 때, 새 디렉터리 구조를 만든 상태에서 실패할 수 있습니다.

버전 3.6에서 변경: old 와 new 에 경로류 객체를 받아들입니다.

os.replace(src, dst, *, src_dir_fd=None, dst_dir_fd=None)

파일 또는 디렉터리 src의 이름을 dst로 바꿉니다. dst 가 디렉터리면, OSError가 발생합니다. dst 가 존재하고 파일이면, 사용자에게 권한이 있을 때 자동으로 대체됩니다. src 와 dst 가 다른 파일 시스템에 있으면, 작업이 실패할 수 있습니다. 성공하면, 이름 바꾸기는 원자적 연산이 됩니다 (이것은 POSIX 요구 사항입니다).

이 함수는 디렉터리 기술자에 상대적인 경로를 제공하도록 src_dir_fd 와/나 dst_dir_fd 를 지정하는 것을 지원할 수 있습니다.

버전 3.3에 추가.

버전 3.6에서 변경: src 및 dst로 경로류 객체를 받아들입니다.

os.rmdir(path, *, dir_fd=None)

Remove (delete) the directory path. If the directory does not exist or is not empty, an FileNotFoundError or an OSError is raised respectively. In order to remove whole directory trees, shutil.rmtree() can be used.

이 함수는 디렉터리 기술자에 상대적인 경로를 지원할 수 있습니다.

버전 3.3에 추가: dir_fd 매개 변수

버전 3.6에서 변경: 경로류 객체를 받아들입니다.

os.scandir(path='.')

path로 지정된 디렉터리 내의 항목에 대응하는 os.DirEntry 객체의 이터레이터를 돌려줍니다. 항목은 임의의 순서로 제공되며, 특수 항목 '.' 및 '..'는 포함되지 않습니다.

listdir() 대신 scandir()를 사용하면, 디렉터리를 검색할 때 운영 체제가 제공한다면 os.DirEntry 객체가 파일 유형과 파일 어트리뷰트 정보를 제공하기 때문에, 이것들이 필요한 코드의 성능을 크게 개선할 수 있습니다. 모든 os.DirEntry 메서드가 시스템 호출을 수행할 수 있지만, 일반적으로 is_dir() 및 is_file()는 심볼릭 링크에 대해서만 시스템 호출을 요구합니다; os.DirEntry.stat()는 유닉스에서 항상 시스템 호출을 요구하지만 윈도우에서는 심볼릭 링크에 대해서만 시스템 호출을 요구합니다.

path 는 경로류 객체 일 수 있습니다. path 가 (직접 또는 PathLike 인터페이스를 통해 간접적으로) bytes 형이면, 각 os.DirEntry의 name 및 path 어트리뷰트의 형은 bytes입니다. 다른 모든 상황에서는 형 str이 됩니다.

이 함수는 또한 파일 기술자 지정을 지원할 수 있습니다; 파일 기술자는 디렉터리를 참조해야 합니다.

scandir() 이터레이터는 컨텍스트 관리자 프로토콜을 지원하고 다음과 같은 메서드를 제공합니다:

scandir.close()

이터레이터를 닫고 확보한 자원을 반납합니다.

이터레이터가 소진되거나 가비지 수집될 때 또는 이터레이션 중에 에러가 발생하면 자동으로 호출됩니다. 하지만 명시적으로 호출하거나 with 문을 사용하는 것이 좋습니다.

버전 3.6에 추가.

다음 예제는 주어진 path의 '.'로 시작하지 않는 모든 파일(디렉터리 제외)을 표시하기 위한 scandir()의 간단한 사용을 보여줍니다. entry.is_file() 호출은 일반적으로 추가 시스템 호출을 하지 않습니다:

with os.scandir(path) as it:
    for entry in it:
        if not entry.name.startswith('.') and entry.is_file():
            print(entry.name)

참고

유닉스 기반 시스템에서, scandir()은 시스템의 opendir() [http://pubs.opengroup.org/onlinepubs/009695399/functions/opendir.html] 과 readdir() [http://pubs.opengroup.org/onlinepubs/009695399/functions/readdir_r.html] 함수를 사용합니다. 윈도우에서는, Win32 FindFirstFileW [https://msdn.microsoft.com/en-us/library/windows/desktop/aa364418(v=vs.85).aspx] 와 FindNextFileW [https://msdn.microsoft.com/en-us/library/windows/desktop/aa364428(v=vs.85).aspx] 함수를 사용합니다.

버전 3.5에 추가.

버전 3.6에 추가: 컨텍스트 관리자 프로토콜과 close() 메서드 대한 지원이 추가되었습니다. scandir() 이터레이터가 모두 소진되거나 명시적으로 닫히지 않으면 ResourceWarning가 파괴자에서 방출됩니다.

이 함수는 경로류 객체를 받아들입니다.

버전 3.7에서 변경: 유닉스에서 파일 기술자에 대한 지원이 추가되었습니다.

class os.DirEntry

디렉터리 항목의 파일 경로와 다른 파일 어트리뷰트를 노출하기 위해 scandir()에 의해 산출되는 객체.

scandir()는 추가 시스템 호출 없이 가능한 많은 정보를 제공합니다. stat() 또는 lstat() 시스템 호출이 이루어지면, os.DirEntry 객체는 결과를 캐시 합니다.

os.DirEntry 인스턴스는 수명이 긴 데이터 구조에 저장하는 용도가 아닙니다; 파일 메타 데이터가 변경되었거나 scandir()를 호출한 후 오랜 시간이 지났음을 안다면, os.stat(entry.path)를 호출하여 최신 정보를 가져오십시오.

os.DirEntry 메서드는 운영 체제 시스템 호출을 할 수 있으므로, OSError를 일으킬 수도 있습니다. 에러에 대해 매우 세부적인 제어가 필요하면, os.DirEntry 메서드 중 하나를 호출할 때 OSError를 잡은 후 적절하게 처리할 수 있습니다.

경로류 객체로 직접 사용할 수 있도록, os.DirEntry는 PathLike 인터페이스를 구현합니다.

os.DirEntry 인스턴스의 어트리뷰트 및 메서드는 다음과 같습니다:

name

scandir() path 인자에 상대적인, 항목의 기본(base) 파일명.

name 어트리뷰트는 scandir() path 인자가 bytes 형이면 bytes 고, 그렇지 않으면 str 입니다. 바이트열 파일명을 디코딩하려면 fsdecode()를 사용하십시오.

path

항목의 전체 경로명: os.path.join(scandir_path, entry.name)과 같습니다. 여기서 scandir_path 는 scandir() path 인자입니다. 경로는 scandir() path 인자가 절대 경로일 때만 절대 경로입니다. scandir() path 인자가 파일 기술자면, path 어트리뷰트는 name 어트리뷰트와 같습니다.

path 어트리뷰트는 scandir() path 인자가 bytes 형이면 bytes고, 그렇지 않으면 str 입니다. 바이트열 파일명을 디코딩하려면 fsdecode()를 사용하십시오.

inode()

항목의 아이노드(inode) 번호를 반환합니다.

결과는 os.DirEntry 객체에 캐시 됩니다. 최신 정보를 가져오려면 os.stat(entry.path, follow_symlinks=False).st_ino를 사용하십시오.

최초의 캐시 되지 않은 호출에서, 윈도우 에서는 시스템 호출이 필요하지만, 유닉스에서는 그렇지 않습니다.

is_dir(*, follow_symlinks=True)

이 항목이 디렉터리 또는 디렉터리를 가리키는 심볼릭 링크면 True를 반환합니다; 항목이 다른 종류의 파일이거나 다른 종류의 파일을 가리키면, 또는 더는 존재하지 않으면 False를 반환합니다.

follow_symlinks 가 False면, 이 항목이 디렉터리일 때만 (심볼릭 링크를 따르지 않고) True를 반환합니다; 항목이 다른 종류의 파일이거나 더는 존재하지 않으면 False를 반환합니다.

결과는 follow_symlinks 가 True 및 False일 때에 대해 별도로 os.DirEntry 객체에 캐시 됩니다. 최신 정보를 가져오려면, stat.S_ISDIR()로 os.stat()을 호출하십시오.

최초의 캐시 되지 않은 호출에서, 대부분 시스템 호출이 필요하지 않습니다. 특히, 심볼릭 링크가 아니면, 윈도우나 유닉스 모두 시스템 호출이 필요하지 않은데, 네트워크 파일 시스템과 같이 dirent.d_type == DT_UNKNOWN를 반환하는 특정 유닉스 파일 시스템은 예외입니다. 항목이 심볼릭 링크면, follow_symlinks 가 False가 아닌 이상, 심볼릭 링크를 따르기 위해 시스템 호출이 필요합니다.

이 메서드는, PermissionError와 같은, OSError를 발생시킬 수 있지만, FileNotFoundError는 잡혀서 발생하지 않습니다.

is_file(*, follow_symlinks=True)

이 항목이 파일이나 파일을 가리키는 심볼릭 링크면 True를 반환합니다; 항목이 디렉터리 또는 다른 비 파일 항목이거나, 그런 것을 가리키거나, 더는 존재하지 않으면 False를 반환합니다.

follow_symlinks 가 False면, 이 항목이 파일일 때만 (심볼릭 링크를 따르지 않고) True를 반환합니다; 항목이 디렉터리 나 다른 비 파일 항목이거나 더는 존재하지 않으면 False를 반환합니다.

결과는 os.DirEntry 객체에 캐시 됩니다. 캐싱, 시스템 호출, 예외 발생은 is_dir()과 같습니다.

is_symlink()

이 항목이 심볼릭 링크면 (망가졌다 하더라도) True를 반환합니다; 항목이 디렉터리 나 어떤 종류의 파일이거나 더는 존재하지 않으면 False를 반환합니다.

결과는 os.DirEntry 객체에 캐시 됩니다. 최신 정보를 가져오려면 os.path.islink()를 호출하십시오.

첫 번째, 캐시 되지 않은 호출에서는 시스템 호출이 필요하지 않습니다. 특히 윈도우 나 유닉스는 dirent.d_type == DT_UNKNOWN를 반환하는 특정 유닉스 파일 시스템 (예 : 네트워크 파일 시스템)을 제외하고는 시스템 호출이 필요하지 않습니다.

이 메서드는, PermissionError와 같은, OSError를 발생시킬 수 있지만, FileNotFoundError는 잡혀서 발생하지 않습니다.

stat(*, follow_symlinks=True)

이 항목의 stat_result 객체를 돌려줍니다. 이 메서드는 기본적으로 심볼릭 링크를 따릅니다; 심볼릭 링크를 stat 하려면, follow_symlinks=False 인자를 추가하십시오.

유닉스에서, 이 메서드는 항상 시스템 호출을 요구합니다. 윈도우에서, follow_symlinks 가 True이고 항목이 심볼릭 링크일 때만 시스템 호출이 필요합니다.

윈도우에서, stat_result의 st_ino, st_dev 및 st_nlink 어트리뷰트는 항상 0으로 설정됩니다. 이러한 어트리뷰트를 얻으려면 os.stat()을 호출하십시오.

결과는 follow_symlinks 가 True 및 False일 때에 대해 별도로 os.DirEntry 객체에 캐시 됩니다. 최신 정보를 가져오려면, os.stat()을 호출하십시오.

os.DirEntry와 pathlib.Path의 여러 어트리뷰트와 메서드 사이에는 좋은 일치가 있음에 유의하십시오. 특히, name 어트리뷰트는 is_dir(), is_file(), is_symlink() 및 stat() 메서드와 같은 의미가 있습니다.

버전 3.5에 추가.

버전 3.6에서 변경: PathLike 인터페이스에 대한 지원이 추가되었습니다. 윈도우에서 bytes 경로에 대한 지원이 추가되었습니다.

os.stat(path, *, dir_fd=None, follow_symlinks=True)

파일 또는 파일 기술자의 상태를 가져옵니다. 주어진 경로에 대해 stat() 시스템 호출과 같은 작업을 수행합니다. path 는 문자열이나 바이트열 – 직접 또는 PathLike 인터페이스를 통해 간접적으로 – 또는 열린 파일 기술자로 지정될 수 있습니다. stat_result 객체를 반환합니다.

이 함수는 일반적으로 심볼릭 링크를 따릅니다; 심볼릭 링크를 stat 하려면, 인자 follow_symlinks=False를 추가하거나 lstat()를 사용하십시오.

이 함수는 파일 기술자 지정 및 심볼릭 링크를 따르지 않음을 지원할 수 있습니다.

예:

>>> import os
>>> statinfo = os.stat('somefile.txt')
>>> statinfo
os.stat_result(st_mode=33188, st_ino=7876932, st_dev=234881026,
st_nlink=1, st_uid=501, st_gid=501, st_size=264, st_atime=1297230295,
st_mtime=1297230027, st_ctime=1297230027)
>>> statinfo.st_size
264

더 보기

fstat() 및 lstat() 함수.

버전 3.3에 추가: dir_fd 및 follow_symlinks 인자와 경로 대신 파일 기술자를 지정하는 것을 추가했습니다.

버전 3.6에서 변경: 경로류 객체를 받아들입니다.

class os.stat_result

어트리뷰트가 stat 구조체의 멤버와 대략 일치하는 객체. os.stat(), os.fstat() 및 os.lstat()의 결과로 사용됩니다.

어트리뷰트:

st_mode

파일 모드: 파일 유형 및 파일 모드 비트 (사용 권한).

st_ino

플랫폼에 따라 다르지만, 0이 아니면, 지정된 값의 st_dev은 파일을 고유하게 식별합니다. 일반적으로:

유닉스의 아이노드 번호,

윈도우의 파일 인덱스 [https://msdn.microsoft.com/en-us/library/aa363788]

st_dev

이 파일이 있는 장치의 식별자.

st_nlink

하드 링크 수.

st_uid

파일 소유자의 사용자 식별자.

st_gid

파일 소유자의 그룹 식별자.

st_size

일반 파일 또는 심볼릭 링크면, 바이트 단위의 파일의 크기. 심볼릭 링크의 크기는 포함하고 있는 경로명의 길이이며, 끝나는 널 바이트는 포함하지 않습니다.

타임스탬프:

st_atime

초 단위의 가장 최근의 액세스 시간.

st_mtime

초 단위의 가장 최근의 내용 수정 시간.

st_ctime

플랫폼에 따라 다릅니다:

유닉스에서 가장 최근의 메타 데이터 변경 시간,

윈도우에서 생성 시간, 단위는 초.

st_atime_ns

나노초 정수 단위의 가장 최근의 액세스 시간.

st_mtime_ns

나노초 정수 단위의 가장 최근의 내용 수정 시간.

st_ctime_ns

플랫폼에 따라 다릅니다:

유닉스에서 가장 최근의 메타 데이터 변경 시간,

윈도우에서 생성 시간, 단위는 나노초 정수.

참고

st_atime, st_mtime 및 st_ctime 어트리뷰트의 정확한 의미와 해상도는 운영 체제와 파일 시스템에 따라 다릅니다. 예를 들어, FAT 또는 FAT32 파일 시스템을 사용하는 윈도우 시스템에서, st_mtime은 2초 해상도를, st_atime는 단지 1일 해상도를 갖습니다. 자세한 내용은 운영 체제 설명서를 참조하십시오.

마찬가지로, st_atime_ns, st_mtime_ns 및 st_ctime_ns가 항상 나노초 단위로 표시되지만, 많은 시스템은 나노초 정밀도를 제공하지 않습니다. 나노초 정밀도를 제공하는 시스템에서, st_atime, st_mtime 및 st_ctime를 저장하는 데 사용되는 부동 소수점 객체는, 이 값을 모두 보존할 수 없으므로, 약간 부정확합니다. 정확한 타임스탬프가 필요하면, 항상 st_atime_ns, st_mtime_ns 및 st_ctime_ns를 사용해야 합니다.

(리눅스와 같은) 일부 유닉스 시스템에서는, 다음 어트리뷰트도 사용할 수 있습니다:

st_blocks

파일에 할당된 512-바이트 블록 수. 파일에 구멍이 있으면 st_size/512보다 작을 수 있습니다.

st_blksize

효율적인 파일 시스템 I/O를 위해 “선호되는” 블록 크기. 더 작은 크기로 파일에 기록하면 비효율적인 읽기-수정-다시 쓰기가 발생할 수 있습니다.

st_rdev

아이노드 장치면 장치 유형.

st_flags

파일에 대한 사용자 정의 플래그.

(FreeBSD와 같은) 다른 유닉스 시스템에서는, 다음 어트리뷰트를 사용할 수 있습니다 (그러나 root가 사용하려고 할 때만 채워질 수 있습니다):

st_gen

파일 생성 번호.

st_birthtime

파일 생성 시간.

Solaris 및 파생 상품에서, 다음 어트리뷰트도 사용할 수 있습니다:

st_fstype

파일을 포함하는 파일 시스템의 유형을 고유하게 식별하는 문자열.

맥 OS 시스템에서는, 다음 어트리뷰트도 사용할 수 있습니다:

st_rsize

파일의 실제 크기.

st_creator

파일의 생성자.

st_type

파일 유형.

윈도우 시스템에서는, 다음 어트리뷰트도 사용할 수도 있습니다:

st_file_attributes

윈도우 파일 어트리뷰트: GetFileInformationByHandle()에 의해 반환된 BY_HANDLE_FILE_INFORMATION 구조체의 dwFileAttributes 멤버. stat 모듈의 FILE_ATTRIBUTE_* 상수를 참조하십시오.

표준 모듈 stat는 stat 구조체에서 정보를 추출하는 데 유용한 함수와 상수를 정의합니다. (윈도우에서는, 일부 항목에 더미 값이 채워집니다.)

이전 버전과의 호환성을 위해, stat_result 인스턴스는 stat 구조체의 가장 중요한 (그리고 이식성 있는) 멤버를 제공하는 최소 10개의 정수로 구성된 튜플로 액세스할 수도 있는데, st_mode, st_ino, st_dev, st_nlink, st_uid, st_gid, st_size, st_atime, st_mtime, st_ctime 순서입니다. 일부 구현에서는 끝에 더 많은 항목을 추가 할 수 있습니다. 이전 버전의 파이썬과의 호환성을 위해, stat_result에 튜플로 액세스하면 항상 정수가 반환됩니다.

버전 3.3에 추가: st_atime_ns, st_mtime_ns 및 st_ctime_ns 멤버가 추가되었습니다.

버전 3.5에 추가: 윈도우에서 st_file_attributes 멤버를 추가했습니다.

버전 3.5에서 변경: 윈도우는 이제 사용 가능할 때 파일 인덱스를 st_ino로 반환합니다.

버전 3.7에 추가: Solaris/파생 제품에 st_fstype 멤버를 추가했습니다.

os.statvfs(path)

주어진 경로에 대해 statvfs() 시스템 호출을 수행합니다. 반환 값은 주어진 경로의 파일 시스템을 설명하는 객체인데, 어트리뷰트가 statvfs 구조체의 멤버인 f_bsize, f_frsize, f_blocks, f_bfree, f_bavail, f_files, f_ffree, f_favail, f_flag, f_namemax, f_fsid에 해당합니다.

f_flag 어트리뷰트의 비트 플래그에 대해 두 개의 모듈 수준 상수가 정의됩니다: ST_RDONLY가 설정되면, 파일 시스템은 읽기 전용으로 마운트되었고, ST_NOSUID가 설정되면, setuid/setgid 비트의 의미가 비활성화되었거나 지원되지 않습니다.

추가적인 모듈 수준 상수가 GNU/glibc 기반 시스템에 대해 정의됩니다. 이들은 ST_NODEV (장치 특수 파일에 대한 액세스 금지), ST_NOEXEC (프로그램 실행 금지), ST_SYNCHRONOUS (한 번에 쓰기 동기화), ST_MANDLOCK (FS에 필수 잠금 허용), ST_WRITE (파일/디렉터리/심볼릭 링크 쓰기), ST_APPEND (덧붙이기 전용 파일), ST_IMMUTABLE (불변 파일), ST_NOATIME (액세스 시간을 갱신하지 않음), ST_NODIRATIME (디렉터리 액세스 시간을 갱신하지 않음), ST_RELATIME (mtime/ctime에 상대적으로 atime을 갱신).

이 함수는 파일 기술자 지정을 지원할 수 있습니다.

가용성: 유닉스.

버전 3.2에서 변경: ST_RDONLY 및 ST_NOSUID 상수가 추가되었습니다.

버전 3.3에 추가: path에 열린 파일 기술자를 지정하는 지원이 추가되었습니다.

버전 3.4에서 변경: ST_NODEV, ST_NOEXEC, ST_SYNCHRONOUS, ST_MANDLOCK, ST_WRITE, ST_APPEND, ST_IMMUTABLE, ST_NOATIME, ST_NODIRATIME 및 ST_RELATIME 상수가 추가되었습니다.

버전 3.6에서 변경: 경로류 객체를 받아들입니다.

버전 3.7에 추가: f_fsid 추가.

os.supports_dir_fd

os 모듈의 어떤 함수가 dir_fd 매개 변수의 사용을 허용하는지를 나타내는 Set 객체입니다. 플랫폼마다 다른 기능을 제공하며, 한 플랫폼에서 작동할 수 있는 옵션은 다른 플랫폼에서 지원되지 않을 수 있습니다. 일관성을 위해, dir_fd 를 지원하는 함수는 항상 매개 변수를 지정할 수 있도록 하지만, 기능을 실제로 사용할 수 없으면 예외를 발생시킵니다.

특정 함수가 dir_fd 매개 변수의 사용을 허용하는지를 확인하려면, supports_dir_fd에 in 연산자를 사용하십시오. 예를 들어, 이 표현식은 os.stat()의 dir_fd 매개 변수가 로컬에서 사용 가능한지를 판별합니다:

os.stat in os.supports_dir_fd

현재 dir_fd 매개 변수는 유닉스 플랫폼에서만 작동합니다; 어느 것도 윈도우에서 작동하지 않습니다.

버전 3.3에 추가.

os.supports_effective_ids

os 모듈의 어떤 함수가 os.access()의 effective_ids 매개 변수의 사용을 허용하지를 나타내는 Set 객체입니다. 로컬 플랫폼이 지원하면, 컬렉션에 os.access()가 포함되고, 그렇지 않으면 비어있게 됩니다.

os.access()에 effective_ids 매개 변수를 사용할 수 있는지 확인하려면, supports_effective_ids에 in 연산자를 사용하십시오. 예를 들면 다음과 같습니다:

os.access in os.supports_effective_ids

현재 effective_ids 는 유닉스 플랫폼에서만 작동합니다; 윈도우에서는 작동하지 않습니다.

버전 3.3에 추가.

os.supports_fd

os 모듈의 어떤 함수가 자신의 path 매개 변수에 열린 파일 기술자를 지정하는 것을 허용하는지를 나타내는 Set 객체입니다. 플랫폼마다 다른 기능을 제공하며, 한 플랫폼에서 작동할 수 있는 옵션은 다른 플랫폼에서 지원되지 않을 수 있습니다. 일관성을 위해, fd 를 지원하는 함수는 항상 매개 변수를 지정할 수 있도록 하지만, 기능을 실제로 사용할 수 없으면 예외를 발생시킵니다.

특정 함수가 path 매개 변수에 열린 파일 기술자를 지정할 수 있도록 허용하는지를 확인하려면, supports_fd에 in 연산자를 사용하십시오. 예를 들어, 이 표현식은 로컬 플랫폼에서 os.chdir()가 호출될 때 열린 파일 기술자를 받아들이는지를 판별합니다:

os.chdir in os.supports_fd

버전 3.3에 추가.

os.supports_follow_symlinks

os 모듈의 어떤 함수가 follow_symlinks 매개 변수의 사용을 허용하는지를 나타내는 Set 객체입니다. 플랫폼마다 다른 기능을 제공하며, 한 플랫폼에서 작동할 수 있는 옵션은 다른 플랫폼에서 지원되지 않을 수 있습니다. 일관성을 위해, follow_symlinks 를 지원하는 함수는 항상 매개 변수를 지정할 수 있도록 하지만, 기능을 실제로 사용할 수 없으면 예외를 발생시킵니다.

특정 함수가 follow_symlinks 매개 변수의 사용을 허용하는지를 확인하려면, supports_follow_symlinks에 in 연산자를 사용하십시오. 예를 들어, 이 표현식은 os.stat()의 follow_symlinks 매개 변수가 로컬에서 사용 가능한지를 판별합니다:

os.stat in os.supports_follow_symlinks

버전 3.3에 추가.

os.symlink(src, dst, target_is_directory=False, *, dir_fd=None)

src를 가리키는 dst 라는 이름의 심볼릭 링크를 만듭니다.

윈도우에서, 심볼릭 링크는 파일이나 디렉터리를 나타내며, 동적으로 대상에 맞춰 변형되지 않습니다. 대상이 있으면, 일치하도록 심볼릭 링크의 유형이 만들어집니다. 그렇지 않으면, target_is_directory 가 True 면 심볼릭 링크가 디렉터리로 만들어지고, 그렇지 않으면 파일 심볼릭 링크(기본값)가 만들어집니다. 비 윈도우 플랫폼에서는 target_is_directory 가 무시됩니다.

심볼릭 링크 지원은 윈도우 6.0(Vista)에서 소개되었습니다. symlink()는 6.0 이전의 윈도우 버전에서 NotImplementedError를 발생시킵니다.

이 함수는 디렉터리 기술자에 상대적인 경로를 지원할 수 있습니다.

참고

윈도우에서, 심볼릭 링크를 성공적으로 만들려면 SeCreateSymbolicLinkPrivilege 가 필요합니다. 이 권한은 보통 일반 사용자에게는 부여되지 않지만, 관리자 수준으로 권한을 상승시킬 수 있는 계정에서는 사용할 수 있습니다. 권한을 얻거나 응용 프로그램을 관리자로 실행하는 것은 심볼릭 링크를 성공적으로 만들 방법입니다.

권한이 없는 사용자가 함수를 호출하면 OSError가 발생합니다.

가용성: 유닉스, 윈도우.

버전 3.2에서 변경: 윈도우 6.0 (Vista) 심볼릭 링크에 대한 지원이 추가되었습니다.

버전 3.3에 추가: dir_fd 인자를 추가했으며, 이제 비 윈도우 플랫폼에서 target_is_directory 를 허용합니다.

버전 3.6에서 변경: src 및 dst로 경로류 객체를 받아들입니다.

os.sync()

디스크에 모든 것을 쓰도록 강제합니다.

가용성: 유닉스.

버전 3.3에 추가.

os.truncate(path, length)

최대 length 바이트가 되도록 path에 해당하는 파일을 자릅니다.

이 함수는 파일 기술자 지정을 지원할 수 있습니다.

가용성: 유닉스, 윈도우.

버전 3.3에 추가.

버전 3.5에서 변경: 윈도우 지원 추가

버전 3.6에서 변경: 경로류 객체를 받아들입니다.

os.unlink(path, *, dir_fd=None)

파일 path를 제거(삭제)합니다. 이 함수는 의미상 remove()와 같습니다; unlink 라는 이름은 전통적인 유닉스 이름입니다. 자세한 내용은 remove() 설명서를 참조하십시오.

버전 3.3에 추가: dir_fd 매개 변수

버전 3.6에서 변경: 경로류 객체를 받아들입니다.

os.utime(path, times=None, *, [ns, ]dir_fd=None, follow_symlinks=True)

path로 지정된 파일의 액세스 및 수정 시간을 설정합니다.

utime()은 times 과 ns 라는 두 개의 선택적 매개 변수를 취합니다. path에 설정할 시간을 지정하며 다음과 같이 사용됩니다:

ns 가 지정되면, (atime_ns, mtime_ns) 형식의 2-튜플이어야 하며, 각 멤버는 나노초를 나타내는 int입니다.

times 가 None이 아니면, (atime, mtime) 형식의 2-튜플이어야 하며, 각 멤버는 초를 나타내는 int 또는 float입니다.

times 가 None이고 ns 가 지정되지 않으면, ns=(atime_ns, mtime_ns)를 지정하는 것과 같은데, 두 시간 모두 현재 시각입니다.

times 와 ns에 모두 튜플을 지정하는 것은 에러입니다.

디렉터리가 path 로 제공될 수 있는지는 운영 체제가 디렉터리를 파일로 구현하는지에 따라 다릅니다 (예를 들어, 윈도우는 그렇지 않습니다). 여기서 설정한 정확한 시간은 운영 체제가 액세스 및 수정 시간을 기록하는 해상도에 따라 뒤따르는 stat() 호출에서 반환되지 않을 수 있음에 주의해야 합니다; stat()를 참조하세요. 정확한 시간을 보존하는 가장 좋은 방법은 utime 의 ns 매개 변수에 os.stat() 결과 객체의 st_atime_ns 및 st_mtime_ns 필드를 사용하는 것입니다.

이 함수는 파일 기술자 지정, 디렉터리 기술자에 상대적인 경로 및 심볼릭 링크를 따르지 않음을 지원할 수 있습니다.

버전 3.3에 추가: path에 열린 파일 기술자를 지정하는 것과 dir_fd , follow_symlinks 및 ns 매개 변수 지원이 추가되었습니다.

버전 3.6에서 변경: 경로류 객체를 받아들입니다.

os.walk(top, topdown=True, onerror=None, followlinks=False)

트리를 하향식 또는 상향식으로 탐색하여 디렉터리 트리에 있는 파일명을 생성합니다. 디렉터리 top을 루트로 하는 트리의 디렉터리(top 자체를 포함합니다)마다, 3-튜플 (dirpath, dirnames, filenames)를 산출합니다.

dirpath 는 디렉터리 경로인 문자열입니다. dirnames 는 dirpath 의 하위 디렉터리 이름 리스트입니다 ('.' 및 '..' 제외). filenames 는 dirpath에 있는 디렉터리가 아닌 파일의 이름 리스트입니다. 리스트에 들어있는 이름에는 경로 구성 요소가 들어 있지 않음에 유의하십시오. dirpath 에 있는 파일이나 디렉터리에 대한 전체 경로(top으로 시작하는)를 얻으려면, os.path.join(dirpath, name)을 수행하십시오.

선택적 인자 topdown 이 True이거나 지정되지 않으면, 디렉터리에 대한 3-튜플은 하위 디렉터리에 대한 3-튜플이 생성되기 전에 생성됩니다 (디렉터리는 하향식으로 생성됩니다). topdown 이 False면, 모든 하위 디렉터리에 대한 3-튜플 다음에 디렉터리에 대한 3-튜플이 생성됩니다 (디렉터리가 상향식으로 생성됨). topdown 의 값에 상관없이, 디렉터리와 해당 하위 디렉터리의 튜플이 생성되기 전에 하위 디렉터리 목록이 조회됩니다.

topdown 이 True 일 때, 호출자는 (아마도 del 또는 슬라이스 대입을 사용하여) dirnames 리스트를 수정할 수 있으며, walk()는 이름이 dirnames 남아있는 하위 디렉터리로만 재귀합니다; 검색을 가지치기하거나, 특정 방문 순서를 지정하거나, 심지어 walk()가 다시 시작하기 전에 호출자가 새로 만들거나 이름을 바꾼 디렉터리에 대해 walk()에 알릴 때도 사용할 수 있습니다. topdown 이 False일 때 dirnames를 수정하는 것은 walk의 동작에 영향을 주지 못하는데, 상향식 모드에서 dirnames의 디렉터리는 dirpath 자체가 생성되기 전에 생성되기 때문입니다.

기본적으로, scandir() 호출의 에러는 무시됩니다. 선택적 인자 onerror 가 지정되면, 함수여야 합니다; 하나의 인자 OSError 인스턴스로 호출됩니다. 에러를 보고하고 walk를 계속하도록 하거나, 예외를 발생시켜 walk를 중단할 수 있습니다. 파일명은 예외 객체의 filename 어트리뷰트로 제공됩니다.

기본적으로, walk()는 디렉터리로 해석되는 심볼릭 링크로 이동하지 않습니다. 지원하는 시스템에서, 심볼릭 링크가 가리키는 디렉터리를 방문하려면, followlinks를 True로 설정하십시오.

참고

심볼릭 링크가 자신의 부모 디렉터리를 가리킬 때, followlinks를 True로 설정하면 무한 재귀가 발생할 수 있음에 주의해야 합니다. walk()는 이미 방문한 디렉터리를 추적하지 않습니다.

참고

상대 경로명을 전달할 때는, walk()가 실행되는 도중 현재 작업 디렉터리를 변경하지 마십시오. walk()는 현재 디렉터리를 절대로 변경하지 않으며, 호출자도 마찬가지라고 가정합니다.

이 예는 시작 디렉터리 아래의 각 디렉터리에 있는 비 디렉터리 파일이 차지한 바이트 수를 표시합니다. 단, CVS 하위 디렉터리 아래는 보지 않습니다:

import os
from os.path import join, getsize
for root, dirs, files in os.walk('python/Lib/email'):
    print(root, "consumes", end=" ")
    print(sum(getsize(join(root, name)) for name in files), end=" ")
    print("bytes in", len(files), "non-directory files")
    if 'CVS' in dirs:
        dirs.remove('CVS')  # don't visit CVS directories

다음 예(shutil.rmtree()의 간단한 구현)에서는, 트리를 상향식으로 탐색하는 것이 필수적입니다, rmdir()는 비어 있지 않은 디렉터리를 삭제할 수 없습니다:

# Delete everything reachable from the directory named in "top",
# assuming there are no symbolic links.
# CAUTION:  This is dangerous!  For example, if top == '/', it
# could delete all your disk files.
import os
for root, dirs, files in os.walk(top, topdown=False):
    for name in files:
        os.remove(os.path.join(root, name))
    for name in dirs:
        os.rmdir(os.path.join(root, name))

버전 3.5에서 변경: 이 함수는 이제 os.listdir() 대신 os.scandir()를 호출하기 때문에, os.stat() 호출 수를 줄여 더 빨라졌습니다.

버전 3.6에서 변경: 경로류 객체를 받아들입니다.

os.fwalk(top='.', topdown=True, onerror=None, *, follow_symlinks=False, dir_fd=None)

이 함수는 walk()와 똑같이 동작합니다. 단, 4-튜플 (dirpath, dirnames, filenames, dirfd)를 산출하고 dir_fd를 지원합니다.

dirpath , dirnames 및 filenames 은 walk() 출력과 같고, dirfd 는 dirpath 디렉터리를 가리키는 파일 기술자입니다.

이 함수는 항상 디렉터리 기술자에 상대적인 경로 및 심볼릭 링크를 따르지 않음을 지원합니다. 하지만, 다른 함수와는 달리, follow_symlinks에 대한 fwalk()의 기본값은 False임에 주의하십시오.

참고

fwalk()는 다음 이터레이션 단계까지만 유효한 파일 기술자를 산출하기 때문에, 더 오래 유지하려면 복제해야 합니다 (예를 들어, dup()로).

이 예는 시작 디렉터리 아래의 각 디렉터리에 있는 비 디렉터리 파일이 차지한 바이트 수를 표시합니다. 단, CVS 하위 디렉터리 아래는 보지 않습니다:

import os
for root, dirs, files, rootfd in os.fwalk('python/Lib/email'):
    print(root, "consumes", end="")
    print(sum([os.stat(name, dir_fd=rootfd).st_size for name in files]),
          end="")
    print("bytes in", len(files), "non-directory files")
    if 'CVS' in dirs:
        dirs.remove('CVS')  # don't visit CVS directories

다음 예에서는, 트리를 상향식으로 탐색하는 것이 필수적입니다: rmdir()는 비어 있지 않은 디렉터리를 삭제할 수 없습니다:

# Delete everything reachable from the directory named in "top",
# assuming there are no symbolic links.
# CAUTION:  This is dangerous!  For example, if top == '/', it
# could delete all your disk files.
import os
for root, dirs, files, rootfd in os.fwalk(top, topdown=False):
    for name in files:
        os.unlink(name, dir_fd=rootfd)
    for name in dirs:
        os.rmdir(name, dir_fd=rootfd)

가용성: 유닉스.

버전 3.3에 추가.

버전 3.6에서 변경: 경로류 객체를 받아들입니다.

버전 3.7에서 변경: bytes 경로에 대한 지원이 추가되었습니다.

리눅스 확장 어트리뷰트

버전 3.3에 추가.

이 함수들은 모두 리눅스에서만 사용 가능합니다.

os.getxattr(path, attribute, *, follow_symlinks=True)

path의 확장 파일 시스템 어트리뷰트 attribute의 값을 반환합니다. attribute 는 bytes 또는 str(직접 또는 PathLike 인터페이스를 통해 간접적으로)일 수 있습니다. str이면, 파일 시스템 인코딩으로 인코딩됩니다.

이 함수는 파일 기술자 지정 및 심볼릭 링크를 따르지 않음을 지원할 수 있습니다.

버전 3.6에서 변경: path 및 attribute에 대해 경로류 객체를 받아들입니다.

os.listxattr(path=None, *, follow_symlinks=True)

path 의 확장 파일 시스템 어트리뷰트 목록을 반환합니다. 목록의 어트리뷰트는 파일 시스템 인코딩으로 디코딩된 문자열로 표시됩니다. path 가 None이면, listxattr()는 현재 디렉터리를 검사합니다.

이 함수는 파일 기술자 지정 및 심볼릭 링크를 따르지 않음을 지원할 수 있습니다.

버전 3.6에서 변경: 경로류 객체를 받아들입니다.

os.removexattr(path, attribute, *, follow_symlinks=True)

path 에서 확장 파일 시스템 어트리뷰트 attribute 을 제거합니다. attribute 는 bytes 또는 str(직접 또는 PathLike 인터페이스를 통해 간접적으로)이어야합니다. 문자열이면, 파일 시스템 인코딩으로 인코딩됩니다.

이 함수는 파일 기술자 지정 및 심볼릭 링크를 따르지 않음을 지원할 수 있습니다.

버전 3.6에서 변경: path 및 attribute에 대해 경로류 객체를 받아들입니다.

os.setxattr(path, attribute, value, flags=0, *, follow_symlinks=True)

path 에 있는 확장 파일 시스템 어트리뷰트 attribute를 value로 설정합니다. attribute 는 내장된 NUL이 없는 bytes 또는 str(직접 또는 PathLike 인터페이스를 통해 간접적으로)이어야 합니다. str이면, 파일 시스템 인코딩으로 인코딩됩니다. flags 는 XATTR_REPLACE 또는 XATTR_CREATE 일 수 있습니다. XATTR_REPLACE가 주어지고 어트리뷰트가 존재하지 않으면, EEXISTS가 발생합니다. XATTR_CREATE가 주어지고 어트리뷰트가 이미 존재하면, 어트리뷰트는 만들어지지 않고 ENODATA가 발생합니다.

이 함수는 파일 기술자 지정 및 심볼릭 링크를 따르지 않음을 지원할 수 있습니다.

참고

리눅스 커널 버전 2.6.39 미만의 버그로 인해 flags 인자가 일부 파일 시스템에서 무시되었습니다.

버전 3.6에서 변경: path 및 attribute에 대해 경로류 객체를 받아들입니다.

os.XATTR_SIZE_MAX

확장 어트리뷰트 값의 최대 크기입니다. 현재, 리눅스에서 64 KiB입니다.

os.XATTR_CREATE

이것은 setxattr()의 flags 인자를 위한 값입니다. 연산이 반드시 어트리뷰트를 새로 만들어야 함을 나타냅니다.

os.XATTR_REPLACE

이것은 setxattr()의 flags 인자를 위한 값입니다. 연산이 반드시 기존 어트리뷰트를 대체해야 함을 나타냅니다.

프로세스 관리

이 함수들은 프로세스를 만들고 관리하는데 사용될 수 있습니다.

다양한 exec* 함수는 프로세스로 로드되는 새 프로그램에 대한 인자 목록을 받아들입니다. 각각의 경우에, 첫 번째 인자는 사용자가 명령 줄에 입력할 수 있는 인자가 아닌 프로그램 자체의 이름으로 새 프로그램에 전달됩니다. C 프로그래머에게, 이것은 프로그램의 main()에 전달된 argv[0]입니다. 예를 들어, os.execv('/bin/echo', ['foo', 'bar'])는 표준 출력에 bar만 인쇄합니다; foo는 무시되는 것처럼 보이게 됩니다.

os.abort()

현재 프로세스에 SIGABRT 시그널을 생성합니다. 유닉스에서, 기본 동작은 코어 덤프를 생성하는 것입니다; 윈도우에서, 프로세스는 즉시 종료 코드 3을 반환합니다. 이 함수를 호출하면 signal.signal()를 사용하여 SIGABRT에 등록된 파이썬 시그널 처리기를 호출하지 않게 됨에 주의하시기 바랍니다.

os.execl(path, arg0, arg1, ...)

os.execle(path, arg0, arg1, ..., env)

os.execlp(file, arg0, arg1, ...)

os.execlpe(file, arg0, arg1, ..., env)

os.execv(path, args)

os.execve(path, args, env)

os.execvp(file, args)

os.execvpe(file, args, env)

이 함수들은 모두 현재 프로세스를 대체해서 새로운 프로그램을 실행합니다; 반환되지 않습니다. 유닉스에서, 새로운 실행 파일이 현재 프로세스에 로드되고, 호출자와 같은 프로세스 ID를 갖게 됩니다. 에러는 OSError 예외로 보고됩니다.

현재 프로세스가 즉시 교체됩니다. 열린 파일 객체와 기술자는 플러시 되지 않으므로, 이러한 열린 파일에 버퍼링 된 데이터가 있으면, exec* 함수를 호출하기 전에 sys.stdout.flush() 또는 os.fsync()를 사용하여 플러시 해야 합니다.

exec* 함수의 “l” 및 “v” 변형은 명령 줄 인자가 전달되는 방식이 다릅니다. “l” 변형은 아마도 코드가 작성될 때 매개 변수의 수가 고정되어 있다면 가장 작업하기 쉬운 것입니다; 개별 매개 변수는 단순히 execl*() 함수에 대한 추가 매개 변수가 됩니다. “v” 변형은 매개 변수의 개수가 가변적일 때 좋으며, 리스트나 튜플에 들어있는 인자가 args 매개 변수로 전달됩니다. 두 경우 모두, 자식 프로세스에 대한 인자는 실행 중인 명령의 이름으로 시작해야 하지만, 강제되지는 않습니다.

끝 근처에 “p”가 포함된 변형(execlp(), execlpe(), execvp() 및 execvpe())은 PATH 환경 변수를 사용하여 프로그램 file 을 찾습니다. 환경이 대체 될 때 (다음 단락에서 설명할 exec*e 변형 중 하나를 사용하여), 새 환경이 PATH 변수의 소스로 사용됩니다. 다른 변형 execl(), execle(), execv() 및 execve()는 PATH 변수를 사용하여 실행 파일을 찾지 않습니다; path 에는 반드시 적절한 절대 또는 상대 경로가 있어야 합니다.

execle(), execlpe(), execve(), execvpe()의 경우 (모두 “e”로 끝납니다), env 매개 변수는 새 프로세스의 환경 변수를 정의하는 데 사용되는 매핑이어야 합니다 (이것이 현재 프로세스의 환경 대신 사용됩니다); 함수 execl(), execlp(), execv() 및 execvp()는 모두 새 프로세스가 현재 프로세스의 환경을 상속하게 합니다.

일부 플랫폼에서 execve()의 경우, path 는 열린 파일 기술자로도 지정될 수 있습니다. 이 기능은 여러분의 플랫폼에서 지원되지 않을 수 있습니다; os.supports_fd를 사용하여 사용할 수 있는지를 확인할 수 있습니다. 사용할 수 없을 때, 이를 사용하면 NotImplementedError가 발생합니다.

가용성: 유닉스, 윈도우.

버전 3.3에 추가: execve()의 path에 열린 파일 기술자를 지정하는 지원이 추가되었습니다.

버전 3.6에서 변경: 경로류 객체를 받아들입니다.

os._exit(n)

상태 n으로 프로세스를 종료합니다. 클린업 처리기를 호출하거나, stdio 버퍼를 플러시 하거나 등등은 수행하지 않습니다.

참고

종료하는 표준 방법은 sys.exit(n)입니다. _exit()는 일반적으로 fork() 이후의 자식 프로세스에서만 사용해야 합니다.

필수 조건은 아니지만, 다음 종료 코드가 정의되어 있으며 _exit()와 함께 사용할 수 있습니다. 이것은 메일 서버의 외부 명령 배달 프로그램과 같이 파이썬으로 작성된 시스템 프로그램에서 일반적으로 사용됩니다.

참고

약간의 차이점이 있어서, 이들 중 일부는 모든 유닉스 플랫폼에서 사용하지는 못할 수 있습니다. 이 상수는 하부 플랫폼에서 정의될 때만 정의됩니다.

os.EX_OK

에러가 발생하지 않았음을 나타내는 종료 코드.

가용성: 유닉스.

os.EX_USAGE

잘못된 개수의 인자가 제공된 경우처럼, 명령이 잘못 사용되었음을 나타내는 종료 코드.

가용성: 유닉스.

os.EX_DATAERR

입력 데이터가 잘못되었음을 나타내는 종료 코드.

가용성: 유닉스.

os.EX_NOINPUT

입력 파일이 없거나 읽을 수 없음을 나타내는 종료 코드.

가용성: 유닉스.

os.EX_NOUSER

지정된 사용자가 존재하지 않음을 나타내는 종료 코드.

가용성: 유닉스.

os.EX_NOHOST

지정된 호스트가 존재하지 않음을 나타내는 종료 코드.

가용성: 유닉스.

os.EX_UNAVAILABLE

필수 서비스를 사용할 수 없음을 나타내는 종료 코드.

가용성: 유닉스.

os.EX_SOFTWARE

내부 소프트웨어 에러가 감지되었음을 나타내는 종료 코드.

가용성: 유닉스.

os.EX_OSERR

포크 하거나 파이프를 만들 수 없는 등, 운영 체제 에러가 감지되었음을 나타내는 종료 코드.

가용성: 유닉스.

os.EX_OSFILE

일부 시스템 파일이 없거나, 열 수 없거나, 다른 에러가 있음을 나타내는 종료 코드.

가용성: 유닉스.

os.EX_CANTCREAT

사용자가 지정한 출력 파일을 만들 수 없음을 나타내는 종료 코드.

가용성: 유닉스.

os.EX_IOERR

일부 파일에서 I/O를 수행하는 동안 에러가 발생했음을 나타내는 종료 코드.

가용성: 유닉스.

os.EX_TEMPFAIL

임시 에러가 발생했음을 나타내는 종료 코드. 이는 재시도 가능한 작업 중에 만들 수 없었던 네트워크 연결과 같이 실제로는 에러가 아닐 수 있는 것을 나타냅니다.

가용성: 유닉스.

os.EX_PROTOCOL

프로토콜 교환이 불법이거나 유효하지 않거나 이해되지 않았음을 나타내는 종료 코드.

가용성: 유닉스.

os.EX_NOPERM

작업을 수행할 수 있는 권한이 충분하지 않음을 나타내는 종료 코드 (파일 시스템 문제에는 사용하지 않습니다).

가용성: 유닉스.

os.EX_CONFIG

어떤 종류의 구성 에러가 발생했음을 나타내는 종료 코드.

가용성: 유닉스.

os.EX_NOTFOUND

“항목을 찾을 수 없습니다” 와 같은 것을 의미하는 종료 코드.

가용성: 유닉스.

os.fork()

자식 프로세스를 포크 합니다. 자식에서는 0을 반환하고, 부모에서는 자식의 프로세스 ID를 반환합니다. 에러가 발생하면 OSError를 일으킵니다.

FreeBSD <= 6.3 및 Cygwin을 포함한 일부 플랫폼은 스레드에서 fork()를 사용할 때 알려진 문제점이 있습니다.

경고

fork()와 함께 SSL 모듈을 사용하는 응용 프로그램의 경우 ssl를 참조하십시오.

가용성: 유닉스.

os.forkpty()

새 의사 터미널을 자식의 제어 터미널로 사용하여 자식 프로세스를 포크 합니다. (pid, fd) 쌍을 반환하는데, 여기서 pid 는 자식에서 0이고, 부모에서는 새 자식의 프로세스 ID이고, fd 는 의사 터미널의 마스터 단의 파일 기술자입니다. 좀 더 이식성 있는 접근법을 사용하려면, pty 모듈을 사용하십시오. 에러가 발생하면 OSError를 일으킵니다.

가용성: 일부 유닉스.

os.kill(pid, sig)

프로세스 pid에 시그널 sig를 보냅니다. 호스트 플랫폼에서 사용할 수 있는 구체적인 시그널에 대한 상수는 signal 모듈에 정의되어 있습니다.

윈도우: signal.CTRL_C_EVENT 및 signal.CTRL_BREAK_EVENT 시그널은 같은 콘솔 창을 공유하는 콘솔 프로세스(예를 들어, 일부 자식 프로세스)로만 보낼 수 있는 특수 시그널입니다. sig에 대한 다른 값은, 프로세스가 TerminateProcess API에 의해 무조건 종료되게 하고, 종료 코드는 sig 로 설정됩니다. 윈도우 버전의 kill()은 종료시킬 프로세스 핸들도 받아들입니다.

signal.pthread_kill()도 참조하십시오.

버전 3.2에 추가: 윈도우 지원.

os.killpg(pgid, sig)

시그널 sig 를 프로세스 그룹 pgid 로 보냅니다.

가용성: 유닉스.

os.nice(increment)

프로세스의 “우선도(niceness)”에 increment 을 추가합니다. 새로운 우선도를 반환합니다.

가용성: 유닉스.

os.plock(op)

프로그램 세그먼트를 메모리에 잠급니다. (<sys/lock.h>에서 정의된) op 값은 잠기는 세그먼트를 판별합니다.

가용성: 유닉스.

os.popen(cmd, mode='r', buffering=-1)

명령 cmd와의 파이프 연결을 엽니다. 반환 값은 파이프에 연결된 열린 파일 객체이며, mode 가 'r'``(기본값)인지 ``'w'인지에 따라 읽거나 쓸 수 있습니다. buffering 인자는 내장 open() 함수에서와 같은 의미가 있습니다. 반환된 파일 객체는 바이트열이 아닌 텍스트 문자열을 읽거나 씁니다.

close 메서드는 자식 프로세스가 성공적으로 종료되면 None을 반환하고, 에러가 있으면 자식 프로세스가 반환한 코드를 반환합니다. POSIX 시스템에서, 반환 코드가 양수면, 프로세스의 반환 값을 1바이트 왼쪽으로 시프트 한 값을 나타냅니다. 반환 코드가 음수면, 음의 반환 코드로 주어진 시그널에 의해 강제 종료된 것입니다. 예를 들어, 자식 프로세스가 죽었을(kill) 때 반환 값은 - signal.SIGKILL 일 수 있습니다. 윈도우 시스템에서, 반환 값은 자식 프로세스의 부호 있는 정수 반환 코드를 포함합니다.

이것은 subprocess.Popen를 사용하여 구현됩니다; 자식 프로세스를 관리하고 통신하는 보다 강력한 방법에 대해서는 이 클래스의 설명서를 참조하십시오.

os.register_at_fork(*, before=None, after_in_parent=None, after_in_child=None)

os.fork() 또는 유사한 프로세스 복제 API를 사용하여 새 자식 프로세스가 포크 될 때 실행될 콜러블들을 등록합니다. 매개 변수는 선택적이며 키워드 전용입니다. 각각은 다른 호출 지점을 지정합니다.

before 는 자식 프로세스를 포크 하기 전에 호출되는 함수입니다.

after_in_parent 는 자식 프로세스를 포크 한 후에 부모 프로세스에서 호출되는 함수입니다.

after_in_child 는 자식 프로세스에서 호출되는 함수입니다.

이러한 호출은 제거가 파이썬 인터프리터로 반환될 것으로 예상되는 경우에만 수행됩니다. 일반적인 subprocess 실행은 자식이 인터프리터로 재진입하지 않기 때문에, 이 호출들이 일어나지 않습니다.

포크 이전에 실행되도록 등록된 함수는 등록 역순으로 실행됩니다. 포크 후에 실행되도록 등록된 함수(부모나 자식 모두)는 등록 순서로 호출됩니다.

제삼자 C 코드에 의한 fork() 호출은, 그것이 명시적으로 PyOS_BeforeFork(), PyOS_AfterFork_Parent() 및 PyOS_AfterFork_Child()를 호출하지 않는 한, 이 함수들을 호출하지 않습니다.

함수 등록을 취소할 방법은 없습니다.

가용성: 유닉스.

버전 3.7에 추가.

os.spawnl(mode, path, ...)

os.spawnle(mode, path, ..., env)

os.spawnlp(mode, file, ...)

os.spawnlpe(mode, file, ..., env)

os.spawnv(mode, path, args)

os.spawnve(mode, path, args, env)

os.spawnvp(mode, file, args)

os.spawnvpe(mode, file, args, env)

새 프로세스에서 프로그램 path 를 실행합니다.

(subprocess 모듈은 새 프로세스를 생성하고 결과를 조회하는데, 더욱 강력한 기능을 제공합니다; 이 모듈을 사용하는 것이 이 함수들을 사용하는 것보다 더 바람직합니다. 특히 Replacing Older Functions with the subprocess Module 섹션을 확인하십시오.)

mode 가 P_NOWAIT면, 이 함수는 새 프로세스의 프로세스 ID를 반환합니다; mode가 P_WAIT면, 종료 코드(정상적으로 종료했을 때)나 -signal(signal은 프로세스를 죽인 시그널입니다)을 반환합니다. 윈도우에서, 프로세스 ID는 실제로 프로세스 핸들이므로, waitpid() 함수에 사용할 수 있습니다.

spawn* 함수의 “l” 및 “v” 변형은 명령 줄 인자가 전달되는 방식이 다릅니다. “l” 변형은 아마도 코드가 작성될 때 매개 변수의 수가 고정되어 있다면 가장 작업하기 쉬운 것입니다; 개별 매개 변수는 단순히 spawnl*() 함수에 대한 추가 매개 변수가 됩니다. “v” 변형은 매개 변수의 개수가 가변적일 때 좋으며, 리스트나 튜플에 들어있는 인자가 args 매개 변수로 전달됩니다. 두 경우 모두, 자식 프로세스에 대한 인자는 반드시 실행 중인 명령의 이름으로 시작해야 합니다.

끝 근처에 두 번째 “p”가 포함된 변형(spawnlp(), spawnlpe(), spawnvp() 및 spawnvpe())은 PATH 환경 변수를 사용하여 프로그램 file 을 찾습니다. 환경이 대체 될 때 (다음 단락에서 설명할 spawn*e 변형 중 하나를 사용하여), 새 환경이 PATH 변수의 소스로 사용됩니다. 다른 변형 spawnl(), spawnle(), spawnv() 및 spawnve()는 PATH 변수를 사용하여 실행 파일을 찾지 않습니다; path 에는 반드시 적절한 절대 또는 상대 경로가 있어야 합니다.

spawnle(), spawnlpe(), spawnve() 및 spawnvpe()의 경우 (모두 “e”로 끝납니다), env 매개 변수는 새 프로세스의 환경 변수를 정의하는 데 사용되는 매핑이어야 합니다 (이것이 현재 프로세스의 환경 대신 사용됩니다); 함수 spawnl(), spawnlp(), spawnv() 및 spawnvp()는 모두 새 프로세스가 현재 프로세스의 환경을 상속하게 합니다. env 딕셔너리의 키와 값은 반드시 문자열이어야 함에 주의하십시오; 잘못된 키나 값은 반환 값 127로 함수가 실패하게 합니다.

예를 들어, spawnlp() 및 spawnvpe()에 대한 다음 호출은 동등합니다:

import os
os.spawnlp(os.P_WAIT, 'cp', 'cp', 'index.html', '/dev/null')

L = ['cp', 'index.html', '/dev/null']
os.spawnvpe(os.P_WAIT, 'cp', L, os.environ)

가용성: 유닉스, 윈도우. spawnlp(), spawnlpe(), spawnvp(), spawnvpe()는 윈도우에서 사용할 수 없습니다. spawnle()와 spawnve()는 윈도우에서 스레드 안전하지 않습니다; 대신 subprocess 모듈을 사용하도록 권고합니다.

버전 3.6에서 변경: 경로류 객체를 받아들입니다.

os.P_NOWAIT

os.P_NOWAITO

spawn* 계열 함수의 mode 매개 변수에 사용할 수 있는 값. 이 값 중 하나가 주어지면, spawn*() 함수는 새로운 프로세스가 생성되자마자 프로세스 ID를 반환 값으로 사용하여 반환됩니다.

가용성: 유닉스, 윈도우.

os.P_WAIT

spawn* 계열 함수의 mode 매개 변수에 사용할 수 있는 값. 이것이 mode 로 주어지면, spawn*() 함수는 새 프로세스가 완료될 때까지 반환되지 않고, 실행이 성공한 프로세스의 종료 코드를 반환하거나, 시그널이 프로세스를 죽이면 -signal을 반환합니다.

가용성: 유닉스, 윈도우.

os.P_DETACH

os.P_OVERLAY

spawn* 계열 함수의 mode 매개 변수에 사용할 수 있는 값. 이들은 위에 나열된 것보다 이식성이 낮습니다. P_DETACH는 P_NOWAIT와 비슷하지만, 새 프로세스는 호출 프로세스의 콘솔에서 분리됩니다. P_OVERLAY가 사용되면, 현재 프로세스가 대체됩니다; spawn* 함수가 반환되지 않습니다.

가용성: 윈도우.

os.startfile(path[, operation])

연관된 응용 프로그램으로 파일을 시작합니다.

operation 이 지정되지 않았거나 'open'이면, 윈도우 탐색기에서 파일을 두 번 클릭하거나, 대화형 명령 셸에서 start 명령에 인자로 파일명을 지정하는 것과 같은 역할을 합니다: 파일의 확장자와 연관된 (있다면) 응용 프로그램으로 파일이 열립니다.

다른 operation 이 주어지면, 파일로 수행해야 할 작업을 지정하는 “명령 동사”여야 합니다. 마이크로소프트에서 문서화 한 일반적인 동사는 'print' 와 'edit' (파일에 사용됨) 및 'explore' 와 'find' (디렉터리에 사용됨)입니다.

startfile()는 연관된 응용 프로그램이 시작되자마자 반환합니다. 응용 프로그램이 닫히기를 기다리는 옵션과 응용 프로그램의 종료 상태를 검색할 방법이 없습니다. path 매개 변수는 현재 디렉터리에 상대적입니다. 절대 경로를 사용하려면 첫 번째 문자가 슬래시 ('/')가 아닌지 확인하십시오; 하부 Win32 ShellExecute() 함수는 첫 번째 문자가 슬래시면 작동하지 않습니다. os.path.normpath() 함수를 사용하여 경로가 Win32 용으로 올바르게 인코딩되도록 하십시오.

인터프리터 시작 오버헤드를 줄이기 위해, Win32 ShellExecute() 함수는 이 함수가 처음 호출될 때까지 결정(resolve)되지 않습니다. 함수를 결정할 수 없으면 NotImplementedError가 발생합니다.

가용성: 윈도우.

os.system(command)

서브 셸에서 명령(문자열)을 실행합니다. 이것은 표준 C 함수 system()를 호출하여 구현되며, 같은 제한이 있습니다. sys.stdin 등의 변경 사항은 실행된 명령의 환경에 반영되지 않습니다. command가 출력을 생성하면, 인터프리터 표준 출력 스트림으로 전송됩니다.

유닉스에서, 반환 값은 wait()에 지정된 형식으로 인코딩된 프로세스의 종료 상태입니다. POSIX는 C system() 함수의 반환 값의 의미를 지정하지 않으므로, 파이썬 함수의 반환 값은 시스템 종속적입니다.

윈도우에서, 반환 값은 command를 실행한 후 시스템 셸에서 반환한 값입니다. 셸은 윈도우 환경 변수 COMSPEC에 의해 제공됩니다: 보통 cmd.exe인데, 명령 실행의 종료 상태를 반환합니다; 기본이 아닌 셸을 사용하는 시스템에서는 셸 설명서를 참조하십시오.

subprocess 모듈은 새 프로세스를 생성하고 결과를 조회하는데, 더욱 강력한 기능을 제공합니다; 이 모듈을 사용하는 것이 이 함수들을 사용하는 것보다 더 바람직합니다. subprocess 설명서의 Replacing Older Functions with the subprocess Module 섹션에서 유용한 조리법을 확인하십시오.

가용성: 유닉스, 윈도우.

os.times()

현재 전역 프로세스 시간을 반환합니다. 반환 값은 5가지 어트리뷰트를 가진 객체입니다:

user - 사용자 시간

system - 시스템 시간

children_user - 모든 자식 프로세스의 사용자 시간

children_system - 모든 자식 프로세스의 시스템 시간

elapsed - 과거의 고정된 시점 이후 실제 경과 시간

과거 호환성을 위해, 이 객체는 user, system, children_user, children_system 및 elapsed가 이 순서로 포함된 5-튜플처럼 작동합니다.

See the Unix manual page times(2) and times(3) manual page on Unix or the GetProcessTimes MSDN [https://docs.microsoft.com/windows/win32/api/processthreadsapi/nf-processthreadsapi-getprocesstimes] on Windows. On Windows, only user and system are known; the other attributes are zero.

가용성: 유닉스, 윈도우.

버전 3.3에서 변경: 반환형이 튜플에서 이름이 지정된 어트리뷰트를 가진 튜플류 객체로 변경되었습니다.

os.wait()

자식 프로세스가 완료될 때까지 기다렸다가, pid 및 종료 상태 표시를 포함하는 튜플을 반환합니다: 종료 상태 표시는 16비트 숫자인데, 하위 바이트가 프로세스를 죽인 시그널 번호이고, 상위 바이트가 종료 상태(시그널 번호가 0이면)입니다; 코어 파일이 생성되면 하위 바이트의 상위 비트가 설정됩니다.

가용성: 유닉스.

os.waitid(idtype, id, options)

하나 이상의 자식 프로세스가 완료될 때까지 기다립니다. idtype 은 P_PID, P_PGID 또는 P_ALL이 될 수 있습니다. id 는 기다릴 pid를 지정합니다. options는 하나 이상의 WEXITED, WSTOPPED 또는 WCONTINUED의 OR로 구성되며, 추가로 WNOHANG 또는 WNOWAIT와 OR 될 수 있습니다. 반환 값은 siginfo_t 구조체에 포함된 데이터(즉, si_pid, si_uid, si_signo, si_status, si_code)를 나타내는 객체이거나, WNOHANG가 지정되고 대기 가능한 상태의 자식이 없으면 None입니다.

가용성: 유닉스.

버전 3.3에 추가.

os.P_PID

os.P_PGID

os.P_ALL

이것들은 waitid()의 idtype 에 사용 가능한 값입니다. id 가 어떻게 해석되는지에 영향을 미칩니다.

가용성: 유닉스.

버전 3.3에 추가.

os.WEXITED

os.WSTOPPED

os.WNOWAIT

기다릴 자식 시그널을 지정하는, waitid()의 options 에서 사용할 수 있는 플래그.

가용성: 유닉스.

버전 3.3에 추가.

os.CLD_EXITED

os.CLD_DUMPED

os.CLD_TRAPPED

os.CLD_CONTINUED

이것은 waitid()에 의해 반환된 결과에서 si_code의 가능한 값입니다.

가용성: 유닉스.

버전 3.3에 추가.

os.waitpid(pid, options)

이 함수의 세부 사항은 유닉스 및 윈도우에서 다릅니다.

유닉스에서: 프로세스 ID pid에 의해 주어진 자식 프로세스의 완료를 기다리고, 프로세스 ID와 종료 상태 표시(wait()처럼 인코딩됨)를 포함하는 튜플을 반환합니다. 호출의 의미는 정수 options 의 값에 영향을 받는데, 일반 작업의 경우 0 이어야 합니다.

pid 가 0보다 크면, waitpid()는 해당 프로세스에 대한 상태 정보를 요청합니다. pid 가 0이면, 현재 프로세스의 프로세스 그룹에 있는 모든 자식의 상태를 요청합니다. pid 가 -1이면, 현재 프로세스의 모든 자식의 상태를 요청합니다. pid 가 -1보다 작으면, 프로세스 그룹 -pid(pid 의 절댓값)에 있는 모든 프로세스의 상태를 요청합니다.

시스템 호출이 -1을 반환하면, OSError가 errno 값으로 발생합니다.

윈도우에서: 프로세스 핸들 pid로 지정된 프로세스가 완료될 때까지 기다리고, pid와 종료 상태를 8비트 왼쪽으로 시프트 한 값을 포함하는 튜플을 반환합니다 (시프팅이 함수를 더 이식성 있게 만듭니다). 0보다 작거나 같은 pid 는 윈도우에서 특별한 의미가 없고 예외가 발생합니다. 정수 options 의 값은 아무 효과가 없습니다. pid 는 id가 알려진 모든 프로세스를 가리킬 수 있습니다, 반드시 자식 프로세스일 필요는 없습니다. P_NOWAIT로 호출된 spawn* 함수는 적절한 프로세스 핸들을 반환합니다.

버전 3.5에서 변경: 시스템 호출이 인터럽트 되고 시그널 처리기가 예외를 발생시키지 않으면, 함수는 이제 InterruptedError 예외를 일으키는 대신 시스템 호출을 재시도합니다 (이유는 PEP 475 [https://www.python.org/dev/peps/pep-0475]를 참조하세요).

os.wait3(options)

waitpid()와 비슷하지만, 프로세스 ID 인자가 제공되지 않고 자식 프로세스 ID, 종료 상태 표시 및 자원 사용 정보가 포함된 3-요소 튜플이 반환된다는 점이 다릅니다. 자원 사용 정보에 대한 자세한 내용은 resource.getrusage()를 참조하십시오. 옵션 인자는 waitpid() 및 wait4()에 제공된 인자와 같습니다.

가용성: 유닉스.

os.wait4(pid, options)

waitpid()와 비슷하지만, 자식 프로세스 ID, 종료 상태 표시 및 자원 사용 정보가 포함된 3-요소 튜플이 반환된다는 점이 다릅니다. 자원 사용 정보에 대한 자세한 내용은 resource.getrusage()를 참조하십시오. wait4()의 인자는 waitpid()와 같습니다.

가용성: 유닉스.

os.WNOHANG

자식 프로세스 상태를 즉시 사용할 수 없으면, waitpid()가 즉시 반환하는 옵션입니다. 이 경우 이 함수는 (0, 0)를 반환합니다.

가용성: 유닉스.

os.WCONTINUED

이 옵션은 자식 프로세스의 상태가 마지막으로 보고된 이후에 작업 제어 중지에서 재개한 경우 보고되도록 합니다.

가용성: 일부 유닉스 시스템.

os.WUNTRACED

이 옵션은 자식 프로세스가 중지되었지만, 현재 상태가 중지된 이후 보고되지 않았으면 보고되게 합니다.

가용성: 유닉스.

다음 함수들은 system(), wait() 또는 waitpid()에 의해 반환된 프로세스 상태 코드를 매개 변수로 받아들입니다. 이것들은 프로세스의 처리를 결정하는 데 사용될 수 있습니다.

os.WCOREDUMP(status)

프로세스에 대해 코어 덤프가 생성되었으면 True를 반환하고, 그렇지 않으면 False를 반환합니다.

This function should be employed only if WIFSIGNALED() is true.

가용성: 유닉스.

os.WIFCONTINUED(status)

Return True if a stopped child has been resumed by delivery of SIGCONT (if the process has been continued from a job control stop), otherwise return False.

See WCONTINUED option.

가용성: 유닉스.

os.WIFSTOPPED(status)

Return True if the process was stopped by delivery of a signal, otherwise return False.

WIFSTOPPED() only returns True if the waitpid() call was done using WUNTRACED option or when the process is being traced (see ptrace(2)).

가용성: 유닉스.

os.WIFSIGNALED(status)

Return True if the process was terminated by a signal, otherwise return False.

가용성: 유닉스.

os.WIFEXITED(status)

Return True if the process exited terminated normally, that is, by calling exit() or _exit(), or by returning from main(); otherwise return False.

가용성: 유닉스.

os.WEXITSTATUS(status)

Return the process exit status.

This function should be employed only if WIFEXITED() is true.

가용성: 유닉스.

os.WSTOPSIG(status)

프로세스를 멈추게 한 시그널을 반환합니다.

This function should be employed only if WIFSTOPPED() is true.

가용성: 유닉스.

os.WTERMSIG(status)

Return the number of the signal that caused the process to terminate.

This function should be employed only if WIFSIGNALED() is true.

가용성: 유닉스.

스케줄러에 대한 인터페이스

이 함수들은 운영 체제가 프로세스에 CPU 시간을 할당하는 방법을 제어합니다. 일부 유닉스 플랫폼에서만 사용할 수 있습니다. 자세한 내용은 유닉스 매뉴얼 페이지를 참조하십시오.

버전 3.3에 추가.

다음 스케줄 정책은 운영 체제에서 지원하는 경우 공개됩니다.

os.SCHED_OTHER

기본 스케줄 정책.

os.SCHED_BATCH

컴퓨터의 나머지 부분에서 반응성을 유지하려고 하는 CPU 집약적인 프로세스를 위한 스케줄 정책.

os.SCHED_IDLE

매우 낮은 우선순위의 배경 작업에 대한 스케줄 정책.

os.SCHED_SPORADIC

간헐적인 서버 프로그램을 위한 스케줄 정책.

os.SCHED_FIFO

선입 선출 (First In First Out) 스케줄 정책.

os.SCHED_RR

라운드 로빈 스케줄 정책.

os.SCHED_RESET_ON_FORK

이 플래그는 다른 스케줄 정책과 OR 될 수 있습니다. 이 플래그가 설정되어있는 프로세스가 포크 할 때, 자식의 스케줄링 정책 및 우선순위가 기본값으로 재설정됩니다.

class os.sched_param(sched_priority)

이 클래스는 sched_setparam(), sched_setscheduler(), 및 sched_getparam()에서 사용되는 튜닝 가능한 스케줄 파라미터를 나타냅니다. 불변입니다.

현재, 가능한 매개 변수는 하나뿐입니다:

sched_priority

스케줄 정책의 스케줄 우선순위.

os.sched_get_priority_min(policy)

policy의 최소 우선순위 값을 가져옵니다. policy 는 위의 스케줄 정책 상수 중 하나입니다.

os.sched_get_priority_max(policy)

policy의 최대 우선순위 값을 가져옵니다. policy 는 위의 스케줄 정책 상수 중 하나입니다.

os.sched_setscheduler(pid, policy, param)

PID가 pid인 프로세스의 스케줄 정책을 설정합니다. pid 가 0이면, 호출하는 프로세스를 의미합니다. policy 는 위의 스케줄 정책 상수 중 하나입니다. param 은 sched_param 인스턴스입니다.

os.sched_getscheduler(pid)

PID가 pid인 프로세스의 스케줄 정책을 반환합니다. pid 가 0이면, 호출하는 프로세스를 의미합니다. 결과는 위의 스케줄 정책 상수 중 하나입니다.

os.sched_setparam(pid, param)

PID가 pid인 프로세스의 스케줄 매개 변수를 설정합니다. pid 가 0이면 호출하는 프로세스를 의미합니다. param 은 sched_param 인스턴스입니다.

os.sched_getparam(pid)

PID가 pid인 프로세스의 스케줄 매개 변수를 sched_param 인스턴스로 반환합니다. pid 가 0이면 호출하는 프로세스를 의미합니다.

os.sched_rr_get_interval(pid)

PID가 pid인 프로세스의 라운드 로빈 퀀텀을 초 단위로 반환합니다. pid 가 0이면 호출하는 프로세스를 의미합니다.

os.sched_yield()

자발적으로 CPU를 양도합니다.

os.sched_setaffinity(pid, mask)

PID가 pid인 프로세스(또는 0이면 현재 프로세스)를 CPU 집합으로 제한합니다. mask 는 프로세스가 제한되어야 하는 CPU 집합을 나타내는 정수의 이터러블입니다.

os.sched_getaffinity(pid)

PID가 pid인 프로세스(또는 0이면 현재 프로세스)가 제한되는 CPU 집합을 반환합니다.

기타 시스템 정보

os.confstr(name)

문자열 값 시스템 구성 값을 반환합니다. name 은 조회할 구성 값을 지정합니다; 정의된 시스템 값의 이름인 문자열일 수 있습니다; 이 이름은 여러 표준(POSIX, 유닉스 95, 유닉스 98 및 기타)에서 지정됩니다. 일부 플랫폼은 추가 이름도 정의합니다. 호스트 운영 체제에 알려진 이름은 confstr_names 딕셔너리의 키로 제공됩니다. 해당 매핑에 포함되지 않은 구성 변수를 위해, name에 정수를 전달하는 것도 허용됩니다.

name 으로 지정된 구성 값이 정의되어 있지 않으면, None이 반환됩니다.

name 이 문자열이고 알 수 없으면, ValueError가 발생합니다. name에 대한 특정 값이 호스트 시스템에서 지원되지 않으면, confstr_names에 포함되어 있어도, 에러 번호 errno.EINVAL로 OSError가 발생합니다.

가용성: 유닉스.

os.confstr_names

confstr()에서 허용하는 이름을 호스트 운영 체제가 해당 이름에 대해 정의한 정숫값으로 매핑하는 딕셔너리입니다. 이것은 시스템에 알려진 이름 집합을 판별하는 데 사용될 수 있습니다.

가용성: 유닉스.

os.cpu_count()

시스템의 CPU 수를 반환합니다. 파악할 수 없으면, None을 반환합니다.

이 숫자는 현재 프로세스에서 사용할 수 있는 CPU 수와 같지 않습니다. 사용 가능한 CPU 수는 len(os.sched_getaffinity(0))로 얻을 수 있습니다.

버전 3.4에 추가.

os.getloadavg()

마지막 1, 5, 15분에 걸쳐 평균한 시스템 실행 대기열의 프로세스 수를 반환하거나, 로드 평균을 얻을 수 없으면, OSError를 발생시킵니다.

가용성: 유닉스.

os.sysconf(name)

정숫값 시스템 구성 값을 반환합니다. name 으로 지정된 구성 값이 정의되어 있지 않으면, -1이 반환됩니다. confstr()의 name 매개 변수에 관한 주석은 여기에도 적용됩니다; 알려진 이름에 대한 정보를 제공하는 딕셔너리는 sysconf_names에 의해 제공됩니다.

가용성: 유닉스.

os.sysconf_names

sysconf()에서 허용하는 이름을 호스트 운영 체제가 해당 이름에 대해 정의한 정숫값으로 매핑하는 딕셔너리입니다. 이것은 시스템에 알려진 이름 집합을 판별하는 데 사용될 수 있습니다.

가용성: 유닉스.

다음 데이터값들은 경로 조작 연산을 지원하는 데 사용됩니다. 이는 모든 플랫폼에서 정의됩니다.

경로명에 대한 고수준 연산은 os.path 모듈에서 정의됩니다.

os.curdir

현재 디렉터리를 가리키기 위해 운영 체제에서 사용하는 상수 문자열. 이것은 윈도우 및 POSIX의 경우 '.'입니다. os.path를 통해서도 제공됩니다.

os.pardir

부모 디렉터리를 가리키기 위해 운영 체제에서 사용하는 상수 문자열입니다. 이것은 윈도우 및 POSIX의 경우 '..'입니다. os.path를 통해서도 제공됩니다.

os.sep

경로명 구성 요소를 분리하기 위해 운영 체제에서 사용하는 문자. 이것은 POSIX의 경우 '/'이고, 윈도우의 경우 '\\'입니다. 이것을 아는 것만으로는 경로명을 구문 분석하거나 이어붙일 수는 없습니다만 — os.path.split()와 os.path.join()를 사용하세요 — 가끔 유용합니다. os.path를 통해서도 제공됩니다.

os.altsep

경로명 구성 요소를 분리하기 위해 운영 체제에서 사용하는 대체 문자이거나, 단 하나의 구분 문자만 있는 경우 None입니다. sep가 백 슬래시인 윈도우 시스템에서는 '/'로 설정됩니다. os.path를 통해서도 제공됩니다.

os.extsep

기본 파일명과 확장자를 구분하는 문자; 예를 들어, os.py에서 '.'. os.path를 통해서도 제공됩니다.

os.pathsep

검색 경로 구성 요소(PATH에서와 같이)를 분리하기 위해 운영 체제에서 관습적으로 사용하는 문자, 가령 POSIX의 ':' 또는 윈도우의 ';'. os.path를 통해서도 제공됩니다.

os.defpath

환경에 'PATH' 키가 없을 때, exec*p* 및 spawn*p*에서 사용하는 기본 검색 경로. os.path를 통해서도 제공됩니다.

os.linesep

현재 플랫폼에서 행을 분리(또는 종료)하는 데 사용되는 문자열. 이는 POSIX의 '\n'와 같은 단일 문자이거나, 윈도우의 '\r\n'와 같은 여러 문자일 수 있습니다. 텍스트 모드로 열린(기본값) 파일에 쓸 때 줄 종결자로 os.linesep를 사용하지 마십시오; 대신 모든 플랫폼에서 단일 '\n'를 사용하십시오.

os.devnull

널(null) 장치의 파일 경로. 예를 들어: POSIX의 경우 '/dev/null', 윈도우의 경우 'nul'. os.path를 통해서도 제공됩니다.

os.RTLD_LAZY

os.RTLD_NOW

os.RTLD_GLOBAL

os.RTLD_LOCAL

os.RTLD_NODELETE

os.RTLD_NOLOAD

os.RTLD_DEEPBIND

setdlopenflags() 및 getdlopenflags() 함수에 사용하는 플래그. 각 플래그가 의미하는 바는 유닉스 매뉴얼 페이지 dlopen(3)를 참조하십시오.

버전 3.3에 추가.

난수

os.getrandom(size, flags=0)

최대 size 크기의 난수 바이트열을 업습니다. 이 함수는 요청한 것보다 짧은 바이트열를 반환할 수 있습니다.

이 바이트열은 사용자 공간 난수 발생기를 시드 하거나 암호화 목적으로 사용할 수 있습니다.

getrandom()는 장치 드라이버 및 기타 환경 소음원에서 수집한 엔트로피에 의존합니다. 대량의 데이터를 불필요하게 읽는 것은 /dev/random 및 /dev/urandom 장치의 다른 사용자에게 부정적인 영향을 미칩니다.

flags 인자는 다음 값 중 0개 이상의 값들과 함께 OR 될 수 있는 비트 마스크입니다: os.GRND_RANDOM 및 GRND_NONBLOCK.

리눅스 getrandom() 매뉴얼 페이지 [http://man7.org/linux/man-pages/man2/getrandom.2.html]도 참조하십시오.

가용성: 리눅스 3.17 이상.

버전 3.6에 추가.

os.urandom(size)

암호화에 적합한 size 크기의 난수 바이트열을 돌려줍니다.

이 함수는 OS 종속적인 임의성 소스에서 난수 바이트열을 반환합니다. 반환된 데이터는 암호화 응용에 충분하도록 예측할 수 없어야 하지만, 정확한 품질은 OS 구현에 따라 달라집니다.

리눅스에서, getrandom() 시스템 호출을 사용할 수 있으면, 블로킹 모드로 사용됩니다: 시스템의 urandom 엔트로피 풀이 초기화될 때까지 블록 됩니다 (커널이 128비트의 엔트로피를 수집합니다). 이유는 PEP 524 [https://www.python.org/dev/peps/pep-0524]를 참조하십시오. 리눅스에서, getrandom() 함수는 (GRND_NONBLOCK 플래그를 사용하여) 비 블로킹 모드로 난수 바이트열을 얻거나, 시스템 urandom 엔트로피 풀이 초기화될 때까지 폴링 할 수 있습니다.

유닉스류 시스템에서, /dev/urandom 장치에서 난수 바이트열을 읽습니다. /dev/urandom 장치를 사용할 수 없거나 읽을 수 없으면, NotImplementedError 예외가 발생합니다.

윈도우에서, CryptGenRandom()을 사용합니다.

더 보기

secrets 모듈은 고수준 함수를 제공합니다. 플랫폼에서 제공되는 난수 발생기에 대한 사용하기 쉬운 인터페이스는 random.SystemRandom를 참조하십시오.

버전 3.6.0에서 변경: 리눅스에서, getrandom()은 이제 보안을 강화하기 위해 블로킹 모드로 사용됩니다.

버전 3.5.2에서 변경: 리눅스에서, getrandom() 시스템 호출이 블록 하면 (urandom 엔트로피 풀이 아직 초기화되지 않았으면), /dev/urandom을 읽는 것으로 대체됩니다.

버전 3.5에서 변경: 리눅스 3.17 및 이후 버전에서, 이제 getrandom() 시스템 호출을 사용할 수 있으면 사용합니다. OpenBSD 5.6 이상에서, C getentropy() 함수가 이제 사용됩니다. 이 함수들은 내부 파일 기술자의 사용을 피합니다.

os.GRND_NONBLOCK

기본적으로, /dev/random에서 읽을 때, getrandom()는 사용할 수 있는 난수 바이트열이 없으면 블록 하고, /dev/urandom에서 읽을 때는, 엔트로피 풀이 아직 초기화되지 않았으면 블록 합니다.

GRND_NONBLOCK 플래그가 설정되면, getrandom()는 이럴 때 블록 하지 않고, 대신 즉시 BlockingIOError를 발생시킵니다.

버전 3.6에 추가.

os.GRND_RANDOM

이 비트가 설정되면, /dev/urandom 풀 대신 /dev/random 풀에서 난수 바이트열을 얻습니다.

버전 3.6에 추가.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

일반 운영 체제 서비스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

일반 운영 체제 서비스 »

|

io — Core tools for working with streams

Source code: Lib/io.py [https://github.com/python/cpython/tree/3.7/Lib/io.py]

Overview

The io module provides Python’s main facilities for dealing with various types of I/O. There are three main types of I/O: text I/O, binary I/O and raw I/O. These are generic categories, and various backing stores can be used for each of them. A concrete object belonging to any of these categories is called a file object. Other common terms are stream and file-like object.

Independent of its category, each concrete stream object will also have various capabilities: it can be read-only, write-only, or read-write. It can also allow arbitrary random access (seeking forwards or backwards to any location), or only sequential access (for example in the case of a socket or pipe).

All streams are careful about the type of data you give to them. For example giving a str object to the write() method of a binary stream will raise a TypeError. So will giving a bytes object to the write() method of a text stream.

버전 3.3에서 변경: Operations that used to raise IOError now raise OSError, since IOError is now an alias of OSError.

Text I/O

Text I/O expects and produces str objects. This means that whenever the backing store is natively made of bytes (such as in the case of a file), encoding and decoding of data is made transparently as well as optional translation of platform-specific newline characters.

The easiest way to create a text stream is with open(), optionally specifying an encoding:

f = open("myfile.txt", "r", encoding="utf-8")

In-memory text streams are also available as StringIO objects:

f = io.StringIO("some initial text data")

The text stream API is described in detail in the documentation of TextIOBase.

Binary I/O

Binary I/O (also called buffered I/O) expects bytes-like objects and produces bytes objects. No encoding, decoding, or newline translation is performed. This category of streams can be used for all kinds of non-text data, and also when manual control over the handling of text data is desired.

The easiest way to create a binary stream is with open() with 'b' in the mode string:

f = open("myfile.jpg", "rb")

In-memory binary streams are also available as BytesIO objects:

f = io.BytesIO(b"some initial binary data: \x00\x01")

The binary stream API is described in detail in the docs of BufferedIOBase.

Other library modules may provide additional ways to create text or binary streams. See socket.socket.makefile() for example.

Raw I/O

Raw I/O (also called unbuffered I/O) is generally used as a low-level building-block for binary and text streams; it is rarely useful to directly manipulate a raw stream from user code. Nevertheless, you can create a raw stream by opening a file in binary mode with buffering disabled:

f = open("myfile.jpg", "rb", buffering=0)

The raw stream API is described in detail in the docs of RawIOBase.

High-level Module Interface

io.DEFAULT_BUFFER_SIZE

An int containing the default buffer size used by the module’s buffered I/O classes. open() uses the file’s blksize (as obtained by os.stat()) if possible.

io.open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

This is an alias for the builtin open() function.

exception io.BlockingIOError

This is a compatibility alias for the builtin BlockingIOError exception.

exception io.UnsupportedOperation

An exception inheriting OSError and ValueError that is raised when an unsupported operation is called on a stream.

In-memory streams

It is also possible to use a str or bytes-like object as a file for both reading and writing. For strings StringIO can be used like a file opened in text mode. BytesIO can be used like a file opened in binary mode. Both provide full read-write capabilities with random access.

더 보기

sys

contains the standard IO streams: sys.stdin, sys.stdout, and sys.stderr.

Class hierarchy

The implementation of I/O streams is organized as a hierarchy of classes. First abstract base classes (ABCs), which are used to specify the various categories of streams, then concrete classes providing the standard stream implementations.

참고

The abstract base classes also provide default implementations of some methods in order to help implementation of concrete stream classes. For example, BufferedIOBase provides unoptimized implementations of readinto() and readline().

At the top of the I/O hierarchy is the abstract base class IOBase. It defines the basic interface to a stream. Note, however, that there is no separation between reading and writing to streams; implementations are allowed to raise UnsupportedOperation if they do not support a given operation.

The RawIOBase ABC extends IOBase. It deals with the reading and writing of bytes to a stream. FileIO subclasses RawIOBase to provide an interface to files in the machine’s file system.

The BufferedIOBase ABC deals with buffering on a raw byte stream (RawIOBase). Its subclasses, BufferedWriter, BufferedReader, and BufferedRWPair buffer streams that are readable, writable, and both readable and writable. BufferedRandom provides a buffered interface to random access streams. Another BufferedIOBase subclass, BytesIO, is a stream of in-memory bytes.

The TextIOBase ABC, another subclass of IOBase, deals with streams whose bytes represent text, and handles encoding and decoding to and from strings. TextIOWrapper, which extends it, is a buffered text interface to a buffered raw stream (BufferedIOBase). Finally, StringIO is an in-memory stream for text.

Argument names are not part of the specification, and only the arguments of open() are intended to be used as keyword arguments.

The following table summarizes the ABCs provided by the io module:

ABC

Inherits

Stub Methods

Mixin Methods and Properties

IOBase

fileno, seek, and truncate

close, closed, __enter__, __exit__, flush, isatty, __iter__, __next__, readable, readline, readlines, seekable, tell, writable, and writelines

RawIOBase

IOBase

readinto and write

Inherited IOBase methods, read, and readall

BufferedIOBase

IOBase

detach, read, read1, and write

Inherited IOBase methods, readinto, and readinto1

TextIOBase

IOBase

detach, read, readline, and write

Inherited IOBase methods, encoding, errors, and newlines

I/O Base Classes

class io.IOBase

The abstract base class for all I/O classes, acting on streams of bytes. There is no public constructor.

This class provides empty abstract implementations for many methods that derived classes can override selectively; the default implementations represent a file that cannot be read, written or seeked.

Even though IOBase does not declare read() or write() because their signatures will vary, implementations and clients should consider those methods part of the interface. Also, implementations may raise a ValueError (or UnsupportedOperation) when operations they do not support are called.

The basic type used for binary data read from or written to a file is bytes. Other bytes-like objects are accepted as method arguments too. Text I/O classes work with str data.

Note that calling any method (even inquiries) on a closed stream is undefined. Implementations may raise ValueError in this case.

IOBase (and its subclasses) supports the iterator protocol, meaning that an IOBase object can be iterated over yielding the lines in a stream. Lines are defined slightly differently depending on whether the stream is a binary stream (yielding bytes), or a text stream (yielding character strings). See readline() below.

IOBase is also a context manager and therefore supports the with statement. In this example, file is closed after the with statement’s suite is finished—even if an exception occurs:

with open('spam.txt', 'w') as file:
    file.write('Spam and eggs!')

IOBase provides these data attributes and methods:

close()

Flush and close this stream. This method has no effect if the file is already closed. Once the file is closed, any operation on the file (e.g. reading or writing) will raise a ValueError.

As a convenience, it is allowed to call this method more than once; only the first call, however, will have an effect.

closed

True if the stream is closed.

fileno()

Return the underlying file descriptor (an integer) of the stream if it exists. An OSError is raised if the IO object does not use a file descriptor.

flush()

Flush the write buffers of the stream if applicable. This does nothing for read-only and non-blocking streams.

isatty()

Return True if the stream is interactive (i.e., connected to a terminal/tty device).

readable()

Return True if the stream can be read from. If False, read() will raise OSError.

readline(size=-1)

Read and return one line from the stream. If size is specified, at most size bytes will be read.

The line terminator is always b'\n' for binary files; for text files, the newline argument to open() can be used to select the line terminator(s) recognized.

readlines(hint=-1)

Read and return a list of lines from the stream. hint can be specified to control the number of lines read: no more lines will be read if the total size (in bytes/characters) of all lines so far exceeds hint.

Note that it’s already possible to iterate on file objects using for line in file: ... without calling file.readlines().

seek(offset, whence=SEEK_SET)

Change the stream position to the given byte offset. offset is interpreted relative to the position indicated by whence. The default value for whence is SEEK_SET. Values for whence are:

SEEK_SET or 0 – start of the stream (the default); offset should be zero or positive

SEEK_CUR or 1 – current stream position; offset may be negative

SEEK_END or 2 – end of the stream; offset is usually negative

Return the new absolute position.

버전 3.1에 추가: The SEEK_* constants.

버전 3.3에 추가: Some operating systems could support additional values, like os.SEEK_HOLE or os.SEEK_DATA. The valid values for a file could depend on it being open in text or binary mode.

seekable()

Return True if the stream supports random access. If False, seek(), tell() and truncate() will raise OSError.

tell()

Return the current stream position.

truncate(size=None)

Resize the stream to the given size in bytes (or the current position if size is not specified). The current stream position isn’t changed. This resizing can extend or reduce the current file size. In case of extension, the contents of the new file area depend on the platform (on most systems, additional bytes are zero-filled). The new file size is returned.

버전 3.5에서 변경: Windows will now zero-fill files when extending.

writable()

Return True if the stream supports writing. If False, write() and truncate() will raise OSError.

writelines(lines)

Write a list of lines to the stream. Line separators are not added, so it is usual for each of the lines provided to have a line separator at the end.

__del__()

Prepare for object destruction. IOBase provides a default implementation of this method that calls the instance’s close() method.

class io.RawIOBase

Base class for raw binary I/O. It inherits IOBase. There is no public constructor.

Raw binary I/O typically provides low-level access to an underlying OS device or API, and does not try to encapsulate it in high-level primitives (this is left to Buffered I/O and Text I/O, described later in this page).

In addition to the attributes and methods from IOBase, RawIOBase provides the following methods:

read(size=-1)

Read up to size bytes from the object and return them. As a convenience, if size is unspecified or -1, all bytes until EOF are returned. Otherwise, only one system call is ever made. Fewer than size bytes may be returned if the operating system call returns fewer than size bytes.

If 0 bytes are returned, and size was not 0, this indicates end of file. If the object is in non-blocking mode and no bytes are available, None is returned.

The default implementation defers to readall() and readinto().

readall()

Read and return all the bytes from the stream until EOF, using multiple calls to the stream if necessary.

readinto(b)

Read bytes into a pre-allocated, writable bytes-like object b, and return the number of bytes read. For example, b might be a bytearray. If the object is in non-blocking mode and no bytes are available, None is returned.

write(b)

Write the given bytes-like object, b, to the underlying raw stream, and return the number of bytes written. This can be less than the length of b in bytes, depending on specifics of the underlying raw stream, and especially if it is in non-blocking mode. None is returned if the raw stream is set not to block and no single byte could be readily written to it. The caller may release or mutate b after this method returns, so the implementation should only access b during the method call.

class io.BufferedIOBase

Base class for binary streams that support some kind of buffering. It inherits IOBase. There is no public constructor.

The main difference with RawIOBase is that methods read(), readinto() and write() will try (respectively) to read as much input as requested or to consume all given output, at the expense of making perhaps more than one system call.

In addition, those methods can raise BlockingIOError if the underlying raw stream is in non-blocking mode and cannot take or give enough data; unlike their RawIOBase counterparts, they will never return None.

Besides, the read() method does not have a default implementation that defers to readinto().

A typical BufferedIOBase implementation should not inherit from a RawIOBase implementation, but wrap one, like BufferedWriter and BufferedReader do.

BufferedIOBase provides or overrides these methods and attribute in addition to those from IOBase:

raw

The underlying raw stream (a RawIOBase instance) that BufferedIOBase deals with. This is not part of the BufferedIOBase API and may not exist on some implementations.

detach()

Separate the underlying raw stream from the buffer and return it.

After the raw stream has been detached, the buffer is in an unusable state.

Some buffers, like BytesIO, do not have the concept of a single raw stream to return from this method. They raise UnsupportedOperation.

버전 3.1에 추가.

read(size=-1)

Read and return up to size bytes. If the argument is omitted, None, or negative, data is read and returned until EOF is reached. An empty bytes object is returned if the stream is already at EOF.

If the argument is positive, and the underlying raw stream is not interactive, multiple raw reads may be issued to satisfy the byte count (unless EOF is reached first). But for interactive raw streams, at most one raw read will be issued, and a short result does not imply that EOF is imminent.

A BlockingIOError is raised if the underlying raw stream is in non blocking-mode, and has no data available at the moment.

read1([size])

Read and return up to size bytes, with at most one call to the underlying raw stream’s read() (or readinto()) method. This can be useful if you are implementing your own buffering on top of a BufferedIOBase object.

If size is -1 (the default), an arbitrary number of bytes are returned (more than zero unless EOF is reached).

readinto(b)

Read bytes into a pre-allocated, writable bytes-like object b and return the number of bytes read. For example, b might be a bytearray.

Like read(), multiple reads may be issued to the underlying raw stream, unless the latter is interactive.

A BlockingIOError is raised if the underlying raw stream is in non blocking-mode, and has no data available at the moment.

readinto1(b)

Read bytes into a pre-allocated, writable bytes-like object b, using at most one call to the underlying raw stream’s read() (or readinto()) method. Return the number of bytes read.

A BlockingIOError is raised if the underlying raw stream is in non blocking-mode, and has no data available at the moment.

버전 3.5에 추가.

write(b)

Write the given bytes-like object, b, and return the number of bytes written (always equal to the length of b in bytes, since if the write fails an OSError will be raised). Depending on the actual implementation, these bytes may be readily written to the underlying stream, or held in a buffer for performance and latency reasons.

When in non-blocking mode, a BlockingIOError is raised if the data needed to be written to the raw stream but it couldn’t accept all the data without blocking.

The caller may release or mutate b after this method returns, so the implementation should only access b during the method call.

Raw File I/O

class io.FileIO(name, mode='r', closefd=True, opener=None)

FileIO represents an OS-level file containing bytes data. It implements the RawIOBase interface (and therefore the IOBase interface, too).

The name can be one of two things:

a character string or bytes object representing the path to the file which will be opened. In this case closefd must be True (the default) otherwise an error will be raised.

an integer representing the number of an existing OS-level file descriptor to which the resulting FileIO object will give access. When the FileIO object is closed this fd will be closed as well, unless closefd is set to False.

The mode can be 'r', 'w', 'x' or 'a' for reading (default), writing, exclusive creation or appending. The file will be created if it doesn’t exist when opened for writing or appending; it will be truncated when opened for writing. FileExistsError will be raised if it already exists when opened for creating. Opening a file for creating implies writing, so this mode behaves in a similar way to 'w'. Add a '+' to the mode to allow simultaneous reading and writing.

The read() (when called with a positive argument), readinto() and write() methods on this class will only make one system call.

A custom opener can be used by passing a callable as opener. The underlying file descriptor for the file object is then obtained by calling opener with (name, flags). opener must return an open file descriptor (passing os.open as opener results in functionality similar to passing None).

The newly created file is non-inheritable.

See the open() built-in function for examples on using the opener parameter.

버전 3.3에서 변경: The opener parameter was added. The 'x' mode was added.

버전 3.4에서 변경: The file is now non-inheritable.

In addition to the attributes and methods from IOBase and RawIOBase, FileIO provides the following data attributes:

mode

The mode as given in the constructor.

name

The file name. This is the file descriptor of the file when no name is given in the constructor.

Buffered Streams

Buffered I/O streams provide a higher-level interface to an I/O device than raw I/O does.

class io.BytesIO([initial_bytes])

A stream implementation using an in-memory bytes buffer. It inherits BufferedIOBase. The buffer is discarded when the close() method is called.

The optional argument initial_bytes is a bytes-like object that contains initial data.

BytesIO provides or overrides these methods in addition to those from BufferedIOBase and IOBase:

getbuffer()

Return a readable and writable view over the contents of the buffer without copying them. Also, mutating the view will transparently update the contents of the buffer:

>>> b = io.BytesIO(b"abcdef")
>>> view = b.getbuffer()
>>> view[2:4] = b"56"
>>> b.getvalue()
b'ab56ef'

참고

As long as the view exists, the BytesIO object cannot be resized or closed.

버전 3.2에 추가.

getvalue()

Return bytes containing the entire contents of the buffer.

read1([size])

In BytesIO, this is the same as read().

버전 3.7에서 변경: The size argument is now optional.

readinto1(b)

In BytesIO, this is the same as readinto().

버전 3.5에 추가.

class io.BufferedReader(raw, buffer_size=DEFAULT_BUFFER_SIZE)

A buffer providing higher-level access to a readable, sequential RawIOBase object. It inherits BufferedIOBase. When reading data from this object, a larger amount of data may be requested from the underlying raw stream, and kept in an internal buffer. The buffered data can then be returned directly on subsequent reads.

The constructor creates a BufferedReader for the given readable raw stream and buffer_size. If buffer_size is omitted, DEFAULT_BUFFER_SIZE is used.

BufferedReader provides or overrides these methods in addition to those from BufferedIOBase and IOBase:

peek([size])

Return bytes from the stream without advancing the position. At most one single read on the raw stream is done to satisfy the call. The number of bytes returned may be less or more than requested.

read([size])

Read and return size bytes, or if size is not given or negative, until EOF or if the read call would block in non-blocking mode.

read1([size])

Read and return up to size bytes with only one call on the raw stream. If at least one byte is buffered, only buffered bytes are returned. Otherwise, one raw stream read call is made.

버전 3.7에서 변경: The size argument is now optional.

class io.BufferedWriter(raw, buffer_size=DEFAULT_BUFFER_SIZE)

A buffer providing higher-level access to a writeable, sequential RawIOBase object. It inherits BufferedIOBase. When writing to this object, data is normally placed into an internal buffer. The buffer will be written out to the underlying RawIOBase object under various conditions, including:

when the buffer gets too small for all pending data;

when flush() is called;

when a seek() is requested (for BufferedRandom objects);

when the BufferedWriter object is closed or destroyed.

The constructor creates a BufferedWriter for the given writeable raw stream. If the buffer_size is not given, it defaults to DEFAULT_BUFFER_SIZE.

BufferedWriter provides or overrides these methods in addition to those from BufferedIOBase and IOBase:

flush()

Force bytes held in the buffer into the raw stream. A BlockingIOError should be raised if the raw stream blocks.

write(b)

Write the bytes-like object, b, and return the number of bytes written. When in non-blocking mode, a BlockingIOError is raised if the buffer needs to be written out but the raw stream blocks.

class io.BufferedRandom(raw, buffer_size=DEFAULT_BUFFER_SIZE)

A buffered interface to random access streams. It inherits BufferedReader and BufferedWriter, and further supports seek() and tell() functionality.

The constructor creates a reader and writer for a seekable raw stream, given in the first argument. If the buffer_size is omitted it defaults to DEFAULT_BUFFER_SIZE.

BufferedRandom is capable of anything BufferedReader or BufferedWriter can do.

class io.BufferedRWPair(reader, writer, buffer_size=DEFAULT_BUFFER_SIZE)

A buffered I/O object combining two unidirectional RawIOBase objects – one readable, the other writeable – into a single bidirectional endpoint. It inherits BufferedIOBase.

reader and writer are RawIOBase objects that are readable and writeable respectively. If the buffer_size is omitted it defaults to DEFAULT_BUFFER_SIZE.

BufferedRWPair implements all of BufferedIOBase’s methods except for detach(), which raises UnsupportedOperation.

경고

BufferedRWPair does not attempt to synchronize accesses to its underlying raw streams. You should not pass it the same object as reader and writer; use BufferedRandom instead.

Text I/O

class io.TextIOBase

Base class for text streams. This class provides a character and line based interface to stream I/O. It inherits IOBase. There is no public constructor.

TextIOBase provides or overrides these data attributes and methods in addition to those from IOBase:

encoding

The name of the encoding used to decode the stream’s bytes into strings, and to encode strings into bytes.

errors

The error setting of the decoder or encoder.

newlines

A string, a tuple of strings, or None, indicating the newlines translated so far. Depending on the implementation and the initial constructor flags, this may not be available.

buffer

The underlying binary buffer (a BufferedIOBase instance) that TextIOBase deals with. This is not part of the TextIOBase API and may not exist in some implementations.

detach()

Separate the underlying binary buffer from the TextIOBase and return it.

After the underlying buffer has been detached, the TextIOBase is in an unusable state.

Some TextIOBase implementations, like StringIO, may not have the concept of an underlying buffer and calling this method will raise UnsupportedOperation.

버전 3.1에 추가.

read(size=-1)

Read and return at most size characters from the stream as a single str. If size is negative or None, reads until EOF.

readline(size=-1)

Read until newline or EOF and return a single str. If the stream is already at EOF, an empty string is returned.

If size is specified, at most size characters will be read.

seek(offset, whence=SEEK_SET)

Change the stream position to the given offset. Behaviour depends on the whence parameter. The default value for whence is SEEK_SET.

SEEK_SET or 0: seek from the start of the stream (the default); offset must either be a number returned by TextIOBase.tell(), or zero. Any other offset value produces undefined behaviour.

SEEK_CUR or 1: “seek” to the current position; offset must be zero, which is a no-operation (all other values are unsupported).

SEEK_END or 2: seek to the end of the stream; offset must be zero (all other values are unsupported).

Return the new absolute position as an opaque number.

버전 3.1에 추가: The SEEK_* constants.

tell()

Return the current stream position as an opaque number. The number does not usually represent a number of bytes in the underlying binary storage.

write(s)

Write the string s to the stream and return the number of characters written.

class io.TextIOWrapper(buffer, encoding=None, errors=None, newline=None, line_buffering=False, write_through=False)

A buffered text stream over a BufferedIOBase binary stream. It inherits TextIOBase.

encoding gives the name of the encoding that the stream will be decoded or encoded with. It defaults to locale.getpreferredencoding(False).

errors is an optional string that specifies how encoding and decoding errors are to be handled. Pass 'strict' to raise a ValueError exception if there is an encoding error (the default of None has the same effect), or pass 'ignore' to ignore errors. (Note that ignoring encoding errors can lead to data loss.) 'replace' causes a replacement marker (such as '?') to be inserted where there is malformed data. 'backslashreplace' causes malformed data to be replaced by a backslashed escape sequence. When writing, 'xmlcharrefreplace' (replace with the appropriate XML character reference) or 'namereplace' (replace with \N{...} escape sequences) can be used. Any other error handling name that has been registered with codecs.register_error() is also valid.

newline controls how line endings are handled. It can be None, '', '\n', '\r', and '\r\n'. It works as follows:

When reading input from the stream, if newline is None, universal newlines mode is enabled. Lines in the input can end in '\n', '\r', or '\r\n', and these are translated into '\n' before being returned to the caller. If it is '', universal newlines mode is enabled, but line endings are returned to the caller untranslated. If it has any of the other legal values, input lines are only terminated by the given string, and the line ending is returned to the caller untranslated.

When writing output to the stream, if newline is None, any '\n' characters written are translated to the system default line separator, os.linesep. If newline is '' or '\n', no translation takes place. If newline is any of the other legal values, any '\n' characters written are translated to the given string.

If line_buffering is True, flush() is implied when a call to write contains a newline character or a carriage return.

If write_through is True, calls to write() are guaranteed not to be buffered: any data written on the TextIOWrapper object is immediately handled to its underlying binary buffer.

버전 3.3에서 변경: The write_through argument has been added.

버전 3.3에서 변경: The default encoding is now locale.getpreferredencoding(False) instead of locale.getpreferredencoding(). Don’t change temporary the locale encoding using locale.setlocale(), use the current locale encoding instead of the user preferred encoding.

TextIOWrapper provides these members in addition to those of TextIOBase and its parents:

line_buffering

Whether line buffering is enabled.

write_through

Whether writes are passed immediately to the underlying binary buffer.

버전 3.7에 추가.

reconfigure(*[, encoding][, errors][, newline][, line_buffering][, write_through])

Reconfigure this text stream using new settings for encoding, errors, newline, line_buffering and write_through.

Parameters not specified keep current settings, except errors='strict' is used when encoding is specified but errors is not specified.

It is not possible to change the encoding or newline if some data has already been read from the stream. On the other hand, changing encoding after write is possible.

This method does an implicit stream flush before setting the new parameters.

버전 3.7에 추가.

class io.StringIO(initial_value='', newline='\n')

An in-memory stream for text I/O. The text buffer is discarded when the close() method is called.

The initial value of the buffer can be set by providing initial_value. If newline translation is enabled, newlines will be encoded as if by write(). The stream is positioned at the start of the buffer.

The newline argument works like that of TextIOWrapper. The default is to consider only \n characters as ends of lines and to do no newline translation. If newline is set to None, newlines are written as \n on all platforms, but universal newline decoding is still performed when reading.

StringIO provides this method in addition to those from TextIOBase and its parents:

getvalue()

Return a str containing the entire contents of the buffer. Newlines are decoded as if by read(), although the stream position is not changed.

Example usage:

import io

output = io.StringIO()
output.write('First line.\n')
print('Second line.', file=output)

# Retrieve file contents -- this will be
# 'First line.\nSecond line.\n'
contents = output.getvalue()

# Close object and discard memory buffer --
# .getvalue() will now raise an exception.
output.close()

class io.IncrementalNewlineDecoder

A helper codec that decodes newlines for universal newlines mode. It inherits codecs.IncrementalDecoder.

Performance

This section discusses the performance of the provided concrete I/O implementations.

Binary I/O

By reading and writing only large chunks of data even when the user asks for a single byte, buffered I/O hides any inefficiency in calling and executing the operating system’s unbuffered I/O routines. The gain depends on the OS and the kind of I/O which is performed. For example, on some modern OSes such as Linux, unbuffered disk I/O can be as fast as buffered I/O. The bottom line, however, is that buffered I/O offers predictable performance regardless of the platform and the backing device. Therefore, it is almost always preferable to use buffered I/O rather than unbuffered I/O for binary data.

Text I/O

Text I/O over a binary storage (such as a file) is significantly slower than binary I/O over the same storage, because it requires conversions between unicode and binary data using a character codec. This can become noticeable handling huge amounts of text data like large log files. Also, TextIOWrapper.tell() and TextIOWrapper.seek() are both quite slow due to the reconstruction algorithm used.

StringIO, however, is a native in-memory unicode container and will exhibit similar speed to BytesIO.

Multi-threading

FileIO objects are thread-safe to the extent that the operating system calls (such as read(2) under Unix) they wrap are thread-safe too.

Binary buffered objects (instances of BufferedReader, BufferedWriter, BufferedRandom and BufferedRWPair) protect their internal structures using a lock; it is therefore safe to call them from multiple threads at once.

TextIOWrapper objects are not thread-safe.

Reentrancy

Binary buffered objects (instances of BufferedReader, BufferedWriter, BufferedRandom and BufferedRWPair) are not reentrant. While reentrant calls will not happen in normal situations, they can arise from doing I/O in a signal handler. If a thread tries to re-enter a buffered object which it is already accessing, a RuntimeError is raised. Note this doesn’t prohibit a different thread from entering the buffered object.

The above implicitly extends to text files, since the open() function will wrap a buffered object inside a TextIOWrapper. This includes standard streams and therefore affects the built-in function print() as well.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

일반 운영 체제 서비스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

일반 운영 체제 서비스 »

|

time — Time access and conversions

This module provides various time-related functions. For related functionality, see also the datetime and calendar modules.

Although this module is always available, not all functions are available on all platforms. Most of the functions defined in this module call platform C library functions with the same name. It may sometimes be helpful to consult the platform documentation, because the semantics of these functions varies among platforms.

An explanation of some terminology and conventions is in order.

The epoch is the point where the time starts, and is platform dependent. For Unix, the epoch is January 1, 1970, 00:00:00 (UTC). To find out what the epoch is on a given platform, look at time.gmtime(0).

The term seconds since the epoch refers to the total number of elapsed seconds since the epoch, typically excluding leap seconds [https://en.wikipedia.org/wiki/Leap_second]. Leap seconds are excluded from this total on all POSIX-compliant platforms.

The functions in this module may not handle dates and times before the epoch or far in the future. The cut-off point in the future is determined by the C library; for 32-bit systems, it is typically in 2038.

Function strptime() can parse 2-digit years when given %y format code. When 2-digit years are parsed, they are converted according to the POSIX and ISO C standards: values 69–99 are mapped to 1969–1999, and values 0–68 are mapped to 2000–2068.

UTC is Coordinated Universal Time (formerly known as Greenwich Mean Time, or GMT). The acronym UTC is not a mistake but a compromise between English and French.

DST is Daylight Saving Time, an adjustment of the timezone by (usually) one hour during part of the year. DST rules are magic (determined by local law) and can change from year to year. The C library has a table containing the local rules (often it is read from a system file for flexibility) and is the only source of True Wisdom in this respect.

The precision of the various real-time functions may be less than suggested by the units in which their value or argument is expressed. E.g. on most Unix systems, the clock “ticks” only 50 or 100 times a second.

On the other hand, the precision of time() and sleep() is better than their Unix equivalents: times are expressed as floating point numbers, time() returns the most accurate time available (using Unix gettimeofday() where available), and sleep() will accept a time with a nonzero fraction (Unix select() is used to implement this, where available).

The time value as returned by gmtime(), localtime(), and strptime(), and accepted by asctime(), mktime() and strftime(), is a sequence of 9 integers. The return values of gmtime(), localtime(), and strptime() also offer attribute names for individual fields.

See struct_time for a description of these objects.

버전 3.3에서 변경: The struct_time type was extended to provide the tm_gmtoff and tm_zone attributes when platform supports corresponding struct tm members.

버전 3.6에서 변경: The struct_time attributes tm_gmtoff and tm_zone are now available on all platforms.

Use the following functions to convert between time representations:

From

To

Use

seconds since the epoch

struct_time in UTC

gmtime()

seconds since the epoch

struct_time in local time

localtime()

struct_time in UTC

seconds since the epoch

calendar.timegm()

struct_time in local time

seconds since the epoch

mktime()

Functions

time.asctime([t])

Convert a tuple or struct_time representing a time as returned by gmtime() or localtime() to a string of the following form: 'Sun Jun 20 23:21:05 1993'. If t is not provided, the current time as returned by localtime() is used. Locale information is not used by asctime().

참고

Unlike the C function of the same name, asctime() does not add a trailing newline.

time.clock()

On Unix, return the current processor time as a floating point number expressed in seconds. The precision, and in fact the very definition of the meaning of “processor time”, depends on that of the C function of the same name.

On Windows, this function returns wall-clock seconds elapsed since the first call to this function, as a floating point number, based on the Win32 function QueryPerformanceCounter(). The resolution is typically better than one microsecond.

Deprecated since version 3.3, will be removed in version 3.8: The behaviour of this function depends on the platform: use perf_counter() or process_time() instead, depending on your requirements, to have a well defined behaviour.

time.pthread_getcpuclockid(thread_id)

Return the clk_id of the thread-specific CPU-time clock for the specified thread_id.

Use threading.get_ident() or the ident attribute of threading.Thread objects to get a suitable value for thread_id.

경고

Passing an invalid or expired thread_id may result in undefined behavior, such as segmentation fault.

Availability: Unix (see the man page for pthread_getcpuclockid(3) for further information).

버전 3.7에 추가.

time.clock_getres(clk_id)

Return the resolution (precision) of the specified clock clk_id. Refer to Clock ID Constants for a list of accepted values for clk_id.

Availability: Unix.

버전 3.3에 추가.

time.clock_gettime(clk_id) → float

Return the time of the specified clock clk_id. Refer to Clock ID Constants for a list of accepted values for clk_id.

Availability: Unix.

버전 3.3에 추가.

time.clock_gettime_ns(clk_id) → int

Similar to clock_gettime() but return time as nanoseconds.

Availability: Unix.

버전 3.7에 추가.

time.clock_settime(clk_id, time: float)

Set the time of the specified clock clk_id. Currently, CLOCK_REALTIME is the only accepted value for clk_id.

Availability: Unix.

버전 3.3에 추가.

time.clock_settime_ns(clk_id, time: int)

Similar to clock_settime() but set time with nanoseconds.

Availability: Unix.

버전 3.7에 추가.

time.ctime([secs])

Convert a time expressed in seconds since the epoch to a string representing local time. If secs is not provided or None, the current time as returned by time() is used. ctime(secs) is equivalent to asctime(localtime(secs)). Locale information is not used by ctime().

time.get_clock_info(name)

Get information on the specified clock as a namespace object. Supported clock names and the corresponding functions to read their value are:

'clock': time.clock()

'monotonic': time.monotonic()

'perf_counter': time.perf_counter()

'process_time': time.process_time()

'thread_time': time.thread_time()

'time': time.time()

The result has the following attributes:

adjustable: True if the clock can be changed automatically (e.g. by a NTP daemon) or manually by the system administrator, False otherwise

implementation: The name of the underlying C function used to get the clock value. Refer to Clock ID Constants for possible values.

monotonic: True if the clock cannot go backward, False otherwise

resolution: The resolution of the clock in seconds (float)

버전 3.3에 추가.

time.gmtime([secs])

Convert a time expressed in seconds since the epoch to a struct_time in UTC in which the dst flag is always zero. If secs is not provided or None, the current time as returned by time() is used. Fractions of a second are ignored. See above for a description of the struct_time object. See calendar.timegm() for the inverse of this function.

time.localtime([secs])

Like gmtime() but converts to local time. If secs is not provided or None, the current time as returned by time() is used. The dst flag is set to 1 when DST applies to the given time.

time.mktime(t)

This is the inverse function of localtime(). Its argument is the struct_time or full 9-tuple (since the dst flag is needed; use -1 as the dst flag if it is unknown) which expresses the time in local time, not UTC. It returns a floating point number, for compatibility with time(). If the input value cannot be represented as a valid time, either OverflowError or ValueError will be raised (which depends on whether the invalid value is caught by Python or the underlying C libraries). The earliest date for which it can generate a time is platform-dependent.

time.monotonic() → float

Return the value (in fractional seconds) of a monotonic clock, i.e. a clock that cannot go backwards. The clock is not affected by system clock updates. The reference point of the returned value is undefined, so that only the difference between the results of consecutive calls is valid.

버전 3.3에 추가.

버전 3.5에서 변경: The function is now always available and always system-wide.

time.monotonic_ns() → int

Similar to monotonic(), but return time as nanoseconds.

버전 3.7에 추가.

time.perf_counter() → float

Return the value (in fractional seconds) of a performance counter, i.e. a clock with the highest available resolution to measure a short duration. It does include time elapsed during sleep and is system-wide. The reference point of the returned value is undefined, so that only the difference between the results of consecutive calls is valid.

버전 3.3에 추가.

time.perf_counter_ns() → int

Similar to perf_counter(), but return time as nanoseconds.

버전 3.7에 추가.

time.process_time() → float

Return the value (in fractional seconds) of the sum of the system and user CPU time of the current process. It does not include time elapsed during sleep. It is process-wide by definition. The reference point of the returned value is undefined, so that only the difference between the results of consecutive calls is valid.

버전 3.3에 추가.

time.process_time_ns() → int

Similar to process_time() but return time as nanoseconds.

버전 3.7에 추가.

time.sleep(secs)

Suspend execution of the calling thread for the given number of seconds. The argument may be a floating point number to indicate a more precise sleep time. The actual suspension time may be less than that requested because any caught signal will terminate the sleep() following execution of that signal’s catching routine. Also, the suspension time may be longer than requested by an arbitrary amount because of the scheduling of other activity in the system.

버전 3.5에서 변경: The function now sleeps at least secs even if the sleep is interrupted by a signal, except if the signal handler raises an exception (see PEP 475 [https://www.python.org/dev/peps/pep-0475] for the rationale).

time.strftime(format[, t])

Convert a tuple or struct_time representing a time as returned by gmtime() or localtime() to a string as specified by the format argument. If t is not provided, the current time as returned by localtime() is used. format must be a string. ValueError is raised if any field in t is outside of the allowed range.

0 is a legal argument for any position in the time tuple; if it is normally illegal the value is forced to a correct one.

The following directives can be embedded in the format string. They are shown without the optional field width and precision specification, and are replaced by the indicated characters in the strftime() result:

Directive

Meaning

Notes

%a

Locale’s abbreviated weekday name.

%A

Locale’s full weekday name.

%b

Locale’s abbreviated month name.

%B

Locale’s full month name.

%c

Locale’s appropriate date and time representation.

%d

Day of the month as a decimal number [01,31].

%H

Hour (24-hour clock) as a decimal number [00,23].

%I

Hour (12-hour clock) as a decimal number [01,12].

%j

Day of the year as a decimal number [001,366].

%m

Month as a decimal number [01,12].

%M

Minute as a decimal number [00,59].

%p

Locale’s equivalent of either AM or PM.

(1)

%S

Second as a decimal number [00,61].

(2)

%U

Week number of the year (Sunday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Sunday are considered to be in week 0.

(3)

%w

Weekday as a decimal number [0(Sunday),6].

%W

Week number of the year (Monday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Monday are considered to be in week 0.

(3)

%x

Locale’s appropriate date representation.

%X

Locale’s appropriate time representation.

%y

Year without century as a decimal number [00,99].

%Y

Year with century as a decimal number.

%z

Time zone offset indicating a positive or negative time difference from UTC/GMT of the form +HHMM or -HHMM, where H represents decimal hour digits and M represents decimal minute digits [-23:59, +23:59].

%Z

Time zone name (no characters if no time zone exists).

%%

A literal '%' character.

Notes:

When used with the strptime() function, the %p directive only affects the output hour field if the %I directive is used to parse the hour.

The range really is 0 to 61; value 60 is valid in timestamps representing leap seconds [https://en.wikipedia.org/wiki/Leap_second] and value 61 is supported for historical reasons.

When used with the strptime() function, %U and %W are only used in calculations when the day of the week and the year are specified.

Here is an example, a format for dates compatible with that specified in the RFC 2822 [https://tools.ietf.org/html/rfc2822.html] Internet email standard. 1

>>> from time import gmtime, strftime
>>> strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime())
'Thu, 28 Jun 2001 14:17:15 +0000'

Additional directives may be supported on certain platforms, but only the ones listed here have a meaning standardized by ANSI C. To see the full set of format codes supported on your platform, consult the strftime(3) documentation.

On some platforms, an optional field width and precision specification can immediately follow the initial '%' of a directive in the following order; this is also not portable. The field width is normally 2 except for %j where it is 3.

time.strptime(string[, format])

Parse a string representing a time according to a format. The return value is a struct_time as returned by gmtime() or localtime().

The format parameter uses the same directives as those used by strftime(); it defaults to "%a %b %d %H:%M:%S %Y" which matches the formatting returned by ctime(). If string cannot be parsed according to format, or if it has excess data after parsing, ValueError is raised. The default values used to fill in any missing data when more accurate values cannot be inferred are (1900, 1, 1, 0, 0, 0, 0, 1, -1). Both string and format must be strings.

For example:

>>> import time
>>> time.strptime("30 Nov 00", "%d %b %y")
time.struct_time(tm_year=2000, tm_mon=11, tm_mday=30, tm_hour=0, tm_min=0,
                 tm_sec=0, tm_wday=3, tm_yday=335, tm_isdst=-1)

Support for the %Z directive is based on the values contained in tzname and whether daylight is true. Because of this, it is platform-specific except for recognizing UTC and GMT which are always known (and are considered to be non-daylight savings timezones).

Only the directives specified in the documentation are supported. Because strftime() is implemented per platform it can sometimes offer more directives than those listed. But strptime() is independent of any platform and thus does not necessarily support all directives available that are not documented as supported.

class time.struct_time

The type of the time value sequence returned by gmtime(), localtime(), and strptime(). It is an object with a named tuple interface: values can be accessed by index and by attribute name. The following values are present:

Index

Attribute

Values

0

tm_year

(for example, 1993)

1

tm_mon

range [1, 12]

2

tm_mday

range [1, 31]

3

tm_hour

range [0, 23]

4

tm_min

range [0, 59]

5

tm_sec

range [0, 61]; see (2) in strftime() description

6

tm_wday

range [0, 6], Monday is 0

7

tm_yday

range [1, 366]

8

tm_isdst

0, 1 or -1; see below

N/A

tm_zone

abbreviation of timezone name

N/A

tm_gmtoff

offset east of UTC in seconds

Note that unlike the C structure, the month value is a range of [1, 12], not [0, 11].

In calls to mktime(), tm_isdst may be set to 1 when daylight savings time is in effect, and 0 when it is not. A value of -1 indicates that this is not known, and will usually result in the correct state being filled in.

When a tuple with an incorrect length is passed to a function expecting a struct_time, or having elements of the wrong type, a TypeError is raised.

time.time() → float

Return the time in seconds since the epoch as a floating point number. The specific date of the epoch and the handling of leap seconds [https://en.wikipedia.org/wiki/Leap_second] is platform dependent. On Windows and most Unix systems, the epoch is January 1, 1970, 00:00:00 (UTC) and leap seconds are not counted towards the time in seconds since the epoch. This is commonly referred to as Unix time [https://en.wikipedia.org/wiki/Unix_time]. To find out what the epoch is on a given platform, look at gmtime(0).

Note that even though the time is always returned as a floating point number, not all systems provide time with a better precision than 1 second. While this function normally returns non-decreasing values, it can return a lower value than a previous call if the system clock has been set back between the two calls.

The number returned by time() may be converted into a more common time format (i.e. year, month, day, hour, etc…) in UTC by passing it to gmtime() function or in local time by passing it to the localtime() function. In both cases a struct_time object is returned, from which the components of the calendar date may be accessed as attributes.

time.thread_time() → float

Return the value (in fractional seconds) of the sum of the system and user CPU time of the current thread. It does not include time elapsed during sleep. It is thread-specific by definition. The reference point of the returned value is undefined, so that only the difference between the results of consecutive calls in the same thread is valid.

Availability: Windows, Linux, Unix systems supporting CLOCK_THREAD_CPUTIME_ID.

버전 3.7에 추가.

time.thread_time_ns() → int

Similar to thread_time() but return time as nanoseconds.

버전 3.7에 추가.

time.time_ns() → int

Similar to time() but returns time as an integer number of nanoseconds since the epoch.

버전 3.7에 추가.

time.tzset()

Reset the time conversion rules used by the library routines. The environment variable TZ specifies how this is done. It will also set the variables tzname (from the TZ environment variable), timezone (non-DST seconds West of UTC), altzone (DST seconds west of UTC) and daylight (to 0 if this timezone does not have any daylight saving time rules, or to nonzero if there is a time, past, present or future when daylight saving time applies).

Availability: Unix.

참고

Although in many cases, changing the TZ environment variable may affect the output of functions like localtime() without calling tzset(), this behavior should not be relied on.

The TZ environment variable should contain no whitespace.

The standard format of the TZ environment variable is (whitespace added for clarity):

std offset [dst [offset [,start[/time], end[/time]]]]

Where the components are:

std and dst

Three or more alphanumerics giving the timezone abbreviations. These will be propagated into time.tzname

offset

The offset has the form: ± hh[:mm[:ss]]. This indicates the value added the local time to arrive at UTC. If preceded by a ‘-’, the timezone is east of the Prime Meridian; otherwise, it is west. If no offset follows dst, summer time is assumed to be one hour ahead of standard time.

start[/time], end[/time]

Indicates when to change to and back from DST. The format of the start and end dates are one of the following:

Jn

The Julian day n (1 <= n <= 365). Leap days are not counted, so in all years February 28 is day 59 and March 1 is day 60.

n

The zero-based Julian day (0 <= n <= 365). Leap days are counted, and it is possible to refer to February 29.

Mm.n.d

The d’th day (0 <= d <= 6) of week n of month m of the year (1 <= n <= 5, 1 <= m <= 12, where week 5 means “the last d day in month m” which may occur in either the fourth or the fifth week). Week 1 is the first week in which the d’th day occurs. Day zero is a Sunday.

time has the same format as offset except that no leading sign (‘-’ or ‘+’) is allowed. The default, if time is not given, is 02:00:00.

>>> os.environ['TZ'] = 'EST+05EDT,M4.1.0,M10.5.0'
>>> time.tzset()
>>> time.strftime('%X %x %Z')
'02:07:36 05/08/03 EDT'
>>> os.environ['TZ'] = 'AEST-10AEDT-11,M10.5.0,M3.5.0'
>>> time.tzset()
>>> time.strftime('%X %x %Z')
'16:08:12 05/08/03 AEST'

On many Unix systems (including *BSD, Linux, Solaris, and Darwin), it is more convenient to use the system’s zoneinfo (tzfile(5)) database to specify the timezone rules. To do this, set the TZ environment variable to the path of the required timezone datafile, relative to the root of the systems ‘zoneinfo’ timezone database, usually located at /usr/share/zoneinfo. For example, 'US/Eastern', 'Australia/Melbourne', 'Egypt' or 'Europe/Amsterdam'.

>>> os.environ['TZ'] = 'US/Eastern'
>>> time.tzset()
>>> time.tzname
('EST', 'EDT')
>>> os.environ['TZ'] = 'Egypt'
>>> time.tzset()
>>> time.tzname
('EET', 'EEST')

Clock ID Constants

These constants are used as parameters for clock_getres() and clock_gettime().

time.CLOCK_BOOTTIME

Identical to CLOCK_MONOTONIC, except it also includes any time that the system is suspended.

This allows applications to get a suspend-aware monotonic clock without having to deal with the complications of CLOCK_REALTIME, which may have discontinuities if the time is changed using settimeofday() or similar.

Availability: Linux 2.6.39 or later.

버전 3.7에 추가.

time.CLOCK_HIGHRES

The Solaris OS has a CLOCK_HIGHRES timer that attempts to use an optimal hardware source, and may give close to nanosecond resolution. CLOCK_HIGHRES is the nonadjustable, high-resolution clock.

Availability: Solaris.

버전 3.3에 추가.

time.CLOCK_MONOTONIC

Clock that cannot be set and represents monotonic time since some unspecified starting point.

Availability: Unix.

버전 3.3에 추가.

time.CLOCK_MONOTONIC_RAW

Similar to CLOCK_MONOTONIC, but provides access to a raw hardware-based time that is not subject to NTP adjustments.

Availability: Linux 2.6.28 and newer, macOS 10.12 and newer.

버전 3.3에 추가.

time.CLOCK_PROCESS_CPUTIME_ID

High-resolution per-process timer from the CPU.

Availability: Unix.

버전 3.3에 추가.

time.CLOCK_PROF

High-resolution per-process timer from the CPU.

Availability: FreeBSD, NetBSD 7 or later, OpenBSD.

버전 3.7에 추가.

time.CLOCK_THREAD_CPUTIME_ID

Thread-specific CPU-time clock.

Availability: Unix.

버전 3.3에 추가.

time.CLOCK_UPTIME

Time whose absolute value is the time the system has been running and not suspended, providing accurate uptime measurement, both absolute and interval.

Availability: FreeBSD, OpenBSD 5.5 or later.

버전 3.7에 추가.

The following constant is the only parameter that can be sent to clock_settime().

time.CLOCK_REALTIME

System-wide real-time clock. Setting this clock requires appropriate privileges.

Availability: Unix.

버전 3.3에 추가.

Timezone Constants

time.altzone

The offset of the local DST timezone, in seconds west of UTC, if one is defined. This is negative if the local DST timezone is east of UTC (as in Western Europe, including the UK). Only use this if daylight is nonzero. See note below.

time.daylight

Nonzero if a DST timezone is defined. See note below.

time.timezone

The offset of the local (non-DST) timezone, in seconds west of UTC (negative in most of Western Europe, positive in the US, zero in the UK). See note below.

time.tzname

A tuple of two strings: the first is the name of the local non-DST timezone, the second is the name of the local DST timezone. If no DST timezone is defined, the second string should not be used. See note below.

참고

For the above Timezone constants (altzone, daylight, timezone, and tzname), the value is determined by the timezone rules in effect at module load time or the last time tzset() is called and may be incorrect for times in the past. It is recommended to use the tm_gmtoff and tm_zone results from localtime() to obtain timezone information.

더 보기

Module datetime

More object-oriented interface to dates and times.

Module locale

Internationalization services. The locale setting affects the interpretation of many format specifiers in strftime() and strptime().

Module calendar

General calendar-related functions. timegm() is the inverse of gmtime() from this module.

Footnotes

1

The use of %Z is now deprecated, but the %z escape that expands to the preferred hour/minute offset is not supported by all ANSI C libraries. Also, a strict reading of the original 1982 RFC 822 [https://tools.ietf.org/html/rfc822.html] standard calls for a two-digit year (%y rather than %Y), but practice moved to 4-digit years long before the year 2000. After that, RFC 822 [https://tools.ietf.org/html/rfc822.html] became obsolete and the 4-digit year has been first recommended by RFC 1123 [https://tools.ietf.org/html/rfc1123.html] and then mandated by RFC 2822 [https://tools.ietf.org/html/rfc2822.html].

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

일반 운영 체제 서비스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

일반 운영 체제 서비스 »

|

argparse — 명령행 옵션, 인자와 부속 명령을 위한 파서

버전 3.2에 추가.

소스 코드: Lib/argparse.py [https://github.com/python/cpython/tree/3.7/Lib/argparse.py]

자습서

이 페이지는 API 레퍼런스 정보를 담고 있습니다. 파이썬 명령행 파싱에 대한 더 친절한 소개를 원하시면, argparse 자습서 를 보십시오.

argparse 모듈은 사용자 친화적인 명령행 인터페이스를 쉽게 작성하도록 합니다. 프로그램이 필요한 인자를 정의하면, argparse 는 sys.argv 를 어떻게 파싱할지 파악합니다. 또한 argparse 모듈은 도움말과 사용법 메시지를 자동 생성하고, 사용자가 프로그램에 잘못된 인자를 줄 때 에러를 발생시킵니다.

예

다음 코드는 정수 목록을 받아 합계 또는 최댓값을 출력하는 파이썬 프로그램입니다:

import argparse

parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+',
                    help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
                    const=sum, default=max,
                    help='sum the integers (default: find the max)')

args = parser.parse_args()
print(args.accumulate(args.integers))

위의 파이썬 코드가 prog.py 라는 파일에 저장되었다고 가정할 때, 명령행에서 실행되고 유용한 도움말 메시지를 제공할 수 있습니다:

$ python prog.py -h
usage: prog.py [-h] [--sum] N [N ...]

Process some integers.

positional arguments:
 N           an integer for the accumulator

optional arguments:
 -h, --help  show this help message and exit
 --sum       sum the integers (default: find the max)

적절한 인자로 실행하면 명령행 정수의 합계 또는 최댓값을 인쇄합니다.:

$ python prog.py 1 2 3 4
4

$ python prog.py 1 2 3 4 --sum
10

잘못된 인자가 전달되면 에러가 발생합니다:

$ python prog.py a b c
usage: prog.py [-h] [--sum] N [N ...]
prog.py: error: argument N: invalid int value: 'a'

다음 절에서 이 예제를 자세히 살펴봅니다.

파서 만들기

argparse를 사용하는 첫 번째 단계는 ArgumentParser 객체를 생성하는 것입니다:

>>> parser = argparse.ArgumentParser(description='Process some integers.')

ArgumentParser 객체는 명령행을 파이썬 데이터형으로 파싱하는데 필요한 모든 정보를 담고 있습니다.

인자 추가하기

ArgumentParser 에 프로그램 인자에 대한 정보를 채우려면 add_argument() 메서드를 호출하면 됩니다. 일반적으로 이 호출은 ArgumentParser 에게 명령행의 문자열을 객체로 변환하는 방법을 알려줍니다. 이 정보는 저장되고, parse_args() 가 호출될 때 사용됩니다. 예를 들면:

>>> parser.add_argument('integers', metavar='N', type=int, nargs='+',
...                     help='an integer for the accumulator')
>>> parser.add_argument('--sum', dest='accumulate', action='store_const',
...                     const=sum, default=max,
...                     help='sum the integers (default: find the max)')

나중에, parse_args() 를 호출하면 두 가지 어트리뷰트, integers 와 accumulate 를 가진 객체를 반환합니다. integers 어트리뷰트는 하나 이상의 int로 구성된 리스트가 될 것이고, accumulate 어트리뷰트는 명령행에 --sum 가 지정되었을 경우 sum() 함수가 되고, 그렇지 않으면 max() 함수가 될 것입니다.

인자 파싱하기

ArgumentParser 는 parse_args() 메서드를 통해 인자를 파싱합니다. 이 메서드는 명령행을 검사하고 각 인자를 적절한 형으로 변환 한 다음 적절한 액션을 호출합니다. 대부분은, 이것은 간단한 Namespace 객체가 명령행에서 파싱 된 어트리뷰트들로 만들어진다는 것을 뜻합니다:

>>> parser.parse_args(['--sum', '7', '-1', '42'])
Namespace(accumulate=<built-in function sum>, integers=[7, -1, 42])

스크립트에서, parse_args() 는 일반적으로 인자 없이 호출되고, ArgumentParser 는 sys.argv 에서 자동으로 명령행 인자를 결정합니다.

ArgumentParser 객체

class argparse.ArgumentParser(prog=None, usage=None, description=None, epilog=None, parents=[], formatter_class=argparse.HelpFormatter, prefix_chars='-', fromfile_prefix_chars=None, argument_default=None, conflict_handler='error', add_help=True, allow_abbrev=True)

새로운 ArgumentParser 객체를 만듭니다. 모든 매개 변수는 키워드 인자로 전달되어야 합니다. 매개 변수마다 아래에서 더 자세히 설명되지만, 요약하면 다음과 같습니다:

prog - 프로그램의 이름 (기본값: sys.argv[0])

usage - 프로그램 사용법을 설명하는 문자열 (기본값: 파서에 추가된 인자로부터 만들어지는 값)

description - 인자 도움말 전에 표시할 텍스트 (기본값: none)

epilog - 인자 도움말 후에 표시할 텍스트 (기본값: none)

parents - ArgumentParser 객체들의 리스트이고, 이 들의 인자들도 포함된다

formatter_class - 도움말 출력을 사용자 정의하기 위한 클래스

prefix_chars - 선택 인자 앞에 붙는 문자 집합 (기본값: ‘-‘).

fromfile_prefix_chars - 추가 인자를 읽어야 하는 파일 앞에 붙는 문자 집합 (기본값: None).

argument_default - 인자의 전역 기본값 (기본값: None)

conflict_handler - 충돌하는 선택 사항을 해결하기 위한 전략 (일반적으로 불필요함)

add_help - 파서에 -h/--help 옵션을 추가합니다 (기본값: True)

allow_abbrev - 약어가 모호하지 않으면 긴 옵션을 축약할 수 있도록 합니다. (기본값: True)

버전 3.5에서 변경: allow_abbrev 매개 변수가 추가되었습니다.

다음 절에서는 이들 각각의 사용 방법에 관해 설명합니다.

prog

기본적으로, ArgumentParser 객체는 sys.argv[0] 을 사용하여 도움말 메시지에 프로그램의 이름을 표시하는 방법을 결정합니다. 이 기본값은 명령행에서 프로그램이 호출된 방법과 도움말 메시지를 일치시키기 때문에 거의 항상 바람직합니다. 예를 들어, 다음 코드가 들어있는 myprogram.py 라는 파일을 생각해보십시오:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--foo', help='foo help')
args = parser.parse_args()

이 프로그램의 도움말은 (프로그램이 어디에서 호출되었는지에 관계없이) 프로그램 이름으로 myprogram.py 를 표시합니다:

$ python myprogram.py --help
usage: myprogram.py [-h] [--foo FOO]

optional arguments:
 -h, --help  show this help message and exit
 --foo FOO   foo help
$ cd ..
$ python subdir/myprogram.py --help
usage: myprogram.py [-h] [--foo FOO]

optional arguments:
 -h, --help  show this help message and exit
 --foo FOO   foo help

이 기본 동작을 변경하려면, prog= 인자를 ArgumentParser 에 사용하여 다른 값을 제공 할 수 있습니다:

>>> parser = argparse.ArgumentParser(prog='myprogram')
>>> parser.print_help()
usage: myprogram [-h]

optional arguments:
 -h, --help  show this help message and exit

프로그램 이름은 %(prog)s 포맷 지정자를 사용해서 도움말에 쓸 수 있습니다. sys.argv[0] 나 prog= 인자 중 어떤 것으로부터 결정되든 상관없습니다.

>>> parser = argparse.ArgumentParser(prog='myprogram')
>>> parser.add_argument('--foo', help='foo of the %(prog)s program')
>>> parser.print_help()
usage: myprogram [-h] [--foo FOO]

optional arguments:
 -h, --help  show this help message and exit
 --foo FOO   foo of the myprogram program

usage

기본적으로, ArgumentParser 는 포함 된 인자로부터 사용법 메시지를 계산합니다:

>>> parser = argparse.ArgumentParser(prog='PROG')
>>> parser.add_argument('--foo', nargs='?', help='foo help')
>>> parser.add_argument('bar', nargs='+', help='bar help')
>>> parser.print_help()
usage: PROG [-h] [--foo [FOO]] bar [bar ...]

positional arguments:
 bar          bar help

optional arguments:
 -h, --help   show this help message and exit
 --foo [FOO]  foo help

기본 메시지는 usage= 키워드 인자로 재정의될 수 있습니다:

>>> parser = argparse.ArgumentParser(prog='PROG', usage='%(prog)s [options]')
>>> parser.add_argument('--foo', nargs='?', help='foo help')
>>> parser.add_argument('bar', nargs='+', help='bar help')
>>> parser.print_help()
usage: PROG [options]

positional arguments:
 bar          bar help

optional arguments:
 -h, --help   show this help message and exit
 --foo [FOO]  foo help

%(prog)s 포맷 지정자는 사용법 메시지에서 프로그램 이름을 채울 때 사용할 수 있습니다.

description

ArgumentParser 생성자에 대한 대부분의 호출은 description= 키워드 인자를 사용할 것입니다. 이 인자는 프로그램의 기능과 작동 방식에 대한 간략한 설명을 제공합니다. 도움말 메시지에서, 설명은 명령행 사용 문자열과 다양한 인자에 대한 도움말 메시지 사이에 표시됩니다:

>>> parser = argparse.ArgumentParser(description='A foo that bars')
>>> parser.print_help()
usage: argparse.py [-h]

A foo that bars

optional arguments:
 -h, --help  show this help message and exit

기본적으로, 설명은 주어진 공간에 맞도록 줄 바꿈 됩니다. 이 동작을 변경하려면 formatter_class 인자를 참조하십시오.

epilog

일부 프로그램은 인자에 대한 설명 뒤에 프로그램에 대한 추가 설명을 표시하려고 합니다. 이러한 텍스트는 epilog= 에 대한 인자를 ArgumentParser 에 사용하여 지정할 수 있습니다:

>>> parser = argparse.ArgumentParser(
...     description='A foo that bars',
...     epilog="And that's how you'd foo a bar")
>>> parser.print_help()
usage: argparse.py [-h]

A foo that bars

optional arguments:
 -h, --help  show this help message and exit

And that's how you'd foo a bar

description 인자와 마찬가지로, epilog= 텍스트가 기본적으로 줄 바꿈 됩니다만, 이 동작은 formatter_class 인자를 ArgumentParser 에 제공해서 조정할 수 있습니다.

parents

때로는 여러 파서가 공통 인자 집합을 공유하는 경우가 있습니다. 이러한 인자의 정의를 반복하는 대신, 모든 공유 인자를 갖는 파서를 ArgumentParser 에 parents= 인자로 전달할 수 있습니다. parents= 인자는 ArgumentParser 객체의 리스트를 취하여, 그것들로부터 모든 위치와 선택 액션을 수집해서 새로 만들어지는 ArgumentParser 객체에 추가합니다:

>>> parent_parser = argparse.ArgumentParser(add_help=False)
>>> parent_parser.add_argument('--parent', type=int)

>>> foo_parser = argparse.ArgumentParser(parents=[parent_parser])
>>> foo_parser.add_argument('foo')
>>> foo_parser.parse_args(['--parent', '2', 'XXX'])
Namespace(foo='XXX', parent=2)

>>> bar_parser = argparse.ArgumentParser(parents=[parent_parser])
>>> bar_parser.add_argument('--bar')
>>> bar_parser.parse_args(['--bar', 'YYY'])
Namespace(bar='YYY', parent=None)

대부분의 부모 파서는 add_help=False 를 지정합니다. 그렇지 않으면, ArgumentParser 는 (하나는 부모에, 하나는 자식에 있는) 두 개의 -h/--help 옵션을 보게 될 것이고, 에러를 발생시킵니다.

참고

parents= 를 통해 전달하기 전에 파서를 완전히 초기화해야 합니다. 자식 파서 다음에 부모 파서를 변경하면 자식에 반영되지 않습니다.

formatter_class

ArgumentParser 객체는 대체 포매팅 클래스를 지정함으로써 도움말 포매팅을 사용자 정의 할 수 있도록 합니다. 현재 네 가지 클래스가 있습니다:

class argparse.RawDescriptionHelpFormatter

class argparse.RawTextHelpFormatter

class argparse.ArgumentDefaultsHelpFormatter

class argparse.MetavarTypeHelpFormatter

RawDescriptionHelpFormatter 와 RawTextHelpFormatter 는 텍스트 설명이 표시되는 방법을 더 제어할 수 있도록 합니다. 기본적으로, ArgumentParser 객체는 명령행 도움말 메시지에서 description 및 epilog 텍스트를 줄 바꿈 합니다.:

>>> parser = argparse.ArgumentParser(
...     prog='PROG',
...     description='''this description
...         was indented weird
...             but that is okay''',
...     epilog='''
...             likewise for this epilog whose whitespace will
...         be cleaned up and whose words will be wrapped
...         across a couple lines''')
>>> parser.print_help()
usage: PROG [-h]

this description was indented weird but that is okay

optional arguments:
 -h, --help  show this help message and exit

likewise for this epilog whose whitespace will be cleaned up and whose words
will be wrapped across a couple lines

RawDescriptionHelpFormatter 를 formatter_class= 로 전달하는 것은 description 과 epilog 가 이미 올바르게 포맷되어 있어서 줄 바꿈 되어서는 안 된다는 것을 가리킵니다:

>>> parser = argparse.ArgumentParser(
...     prog='PROG',
...     formatter_class=argparse.RawDescriptionHelpFormatter,
...     description=textwrap.dedent('''\
...         Please do not mess up this text!
...         --------------------------------
...             I have indented it
...             exactly the way
...             I want it
...         '''))
>>> parser.print_help()
usage: PROG [-h]

Please do not mess up this text!
--------------------------------
   I have indented it
   exactly the way
   I want it

optional arguments:
 -h, --help  show this help message and exit

RawTextHelpFormatter 는 인자 설명을 포함하여 모든 종류의 도움말 텍스트에 있는 공백을 유지합니다. 그러나 여러 개의 줄 넘김은 하나로 치환됩니다. 여러 개의 빈 줄을 유지하려면, 줄 바꿈 사이에 스페이스를 추가하십시오.

ArgumentDefaultsHelpFormatter 는 기본값에 대한 정보를 각각의 인자 도움말 메시지에 자동으로 추가합니다:

>>> parser = argparse.ArgumentParser(
...     prog='PROG',
...     formatter_class=argparse.ArgumentDefaultsHelpFormatter)
>>> parser.add_argument('--foo', type=int, default=42, help='FOO!')
>>> parser.add_argument('bar', nargs='*', default=[1, 2, 3], help='BAR!')
>>> parser.print_help()
usage: PROG [-h] [--foo FOO] [bar [bar ...]]

positional arguments:
 bar         BAR! (default: [1, 2, 3])

optional arguments:
 -h, --help  show this help message and exit
 --foo FOO   FOO! (default: 42)

MetavarTypeHelpFormatter 는 각 인자 값의 표시 이름으로 (일반 포매터처럼 dest 를 사용하는 대신에) type 인자의 이름을 사용합니다:

>>> parser = argparse.ArgumentParser(
...     prog='PROG',
...     formatter_class=argparse.MetavarTypeHelpFormatter)
>>> parser.add_argument('--foo', type=int)
>>> parser.add_argument('bar', type=float)
>>> parser.print_help()
usage: PROG [-h] [--foo int] float

positional arguments:
  float

optional arguments:
  -h, --help  show this help message and exit
  --foo int

prefix_chars

대부분의 명령행 옵션은 -f/--foo 처럼 - 를 접두어로 사용합니다. +f 나 /foo 같은 옵션과 같이, 다른 접두어 문자를 지원해야 하는 파서는 ArgumentParser 생성자에 prefix_chars= 인자를 사용하여 지정할 수 있습니다:

>>> parser = argparse.ArgumentParser(prog='PROG', prefix_chars='-+')
>>> parser.add_argument('+f')
>>> parser.add_argument('++bar')
>>> parser.parse_args('+f X ++bar Y'.split())
Namespace(bar='Y', f='X')

prefix_chars= 인자의 기본값은 '-' 입니다. - 를 포함하지 않는 문자 집합을 제공하면 -f/--foo 옵션이 허용되지 않게 됩니다.

fromfile_prefix_chars

때로는, 예를 들어 특히 긴 인자 목록을 다룰 때, 인자 목록을 명령행에 입력하는 대신 파일에 보관하는 것이 좋습니다. fromfile_prefix_chars= 인자가 ArgumentParser 생성자에 주어지면, 지정된 문자로 시작하는 인자는 파일로 간주하고 파일에 포함된 인자로 대체됩니다. 예를 들면:

>>> with open('args.txt', 'w') as fp:
...     fp.write('-f\nbar')
>>> parser = argparse.ArgumentParser(fromfile_prefix_chars='@')
>>> parser.add_argument('-f')
>>> parser.parse_args(['-f', 'foo', '@args.txt'])
Namespace(f='bar')

파일에서 읽은 인자는 기본적으로 한 줄에 하나씩 있어야 하고 (하지만 convert_arg_line_to_args() 도 참조하십시오), 명령행에서 원래 파일을 참조하는 인자와 같은 위치에 있는 것처럼 처리됩니다. 위의 예에서 표현식 ['-f', 'foo', '@args.txt'] 는 ['-f', 'foo', '-f', 'bar'] 와 동등하게 취급됩니다.

fromfile_prefix_chars= 인자의 기본값은 None 입니다. 이것은 인자가 절대로 파일 참조로 취급되지 않는다는 것을 의미합니다.

argument_default

일반적으로 인자의 기본값은 add_argument() 에 기본값을 전달하거나 특정 이름-값 쌍 집합을 사용하여 set_defaults() 메서드를 호출하여 지정됩니다. 그러나 때로는, 파서 전체에 적용되는 단일 기본값을 지정하는 것이 유용 할 수 있습니다. 이것은 argument_default= 키워드 인자를 ArgumentParser 에 전달함으로써 이루어질 수 있습니다. 예를 들어, parse_args() 호출에서 어트리뷰트 생성을 전역적으로 억제하려면, argument_default=SUPPRESS 를 제공합니다:

>>> parser = argparse.ArgumentParser(argument_default=argparse.SUPPRESS)
>>> parser.add_argument('--foo')
>>> parser.add_argument('bar', nargs='?')
>>> parser.parse_args(['--foo', '1', 'BAR'])
Namespace(bar='BAR', foo='1')
>>> parser.parse_args([])
Namespace()

allow_abbrev

일반적으로 ArgumentParser 의 parse_args() 메서드에 인자 리스트를 건네주면 긴 옵션의 약어를 인식합니다.

allow_abbrev 를 False 로 설정하면 이 기능을 비활성화 할 수 있습니다:

>>> parser = argparse.ArgumentParser(prog='PROG', allow_abbrev=False)
>>> parser.add_argument('--foobar', action='store_true')
>>> parser.add_argument('--foonley', action='store_false')
>>> parser.parse_args(['--foon'])
usage: PROG [-h] [--foobar] [--foonley]
PROG: error: unrecognized arguments: --foon

버전 3.5에 추가.

conflict_handler

ArgumentParser 객체는 같은 옵션 문자열을 가진 두 개의 액션을 허용하지 않습니다. 기본적으로 ArgumentParser 객체는 이미 사용 중인 옵션 문자열로 인자를 만들려고 시도하면 예외를 발생시킵니다

>>> parser = argparse.ArgumentParser(prog='PROG')
>>> parser.add_argument('-f', '--foo', help='old foo help')
>>> parser.add_argument('--foo', help='new foo help')
Traceback (most recent call last):
 ..
ArgumentError: argument --foo: conflicting option string(s): --foo

때로는 (예를 들어 parents 를 사용하는 경우) 같은 옵션 문자열을 갖는 예전의 인자들을 간단히 대체하는 것이 유용 할 수 있습니다. 이 동작을 얻으려면, ArgumentParser 의 conflict_handler= 인자에 'resolve' 값을 제공합니다:

>>> parser = argparse.ArgumentParser(prog='PROG', conflict_handler='resolve')
>>> parser.add_argument('-f', '--foo', help='old foo help')
>>> parser.add_argument('--foo', help='new foo help')
>>> parser.print_help()
usage: PROG [-h] [-f FOO] [--foo FOO]

optional arguments:
 -h, --help  show this help message and exit
 -f FOO      old foo help
 --foo FOO   new foo help

ArgumentParser 객체는 모든 옵션 문자열이 재정의된 경우에만 액션을 제거합니다. 위의 예에서, 이전의 -f/--foo 액션은 --foo 옵션 문자열만 재정의되었기 때문에 -f 액션으로 유지됩니다.

add_help

기본적으로, ArgumentParser 객체는 파서의 도움말 메시지를 표시하는 옵션을 추가합니다. 예를 들어, 다음 코드를 포함하는 myprogram.py 파일을 생각해보십시오:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--foo', help='foo help')
args = parser.parse_args()

명령행에서 -h 또는 --help 가 제공되면, ArgumentParser 도움말이 출력됩니다 :

$ python myprogram.py --help
usage: myprogram.py [-h] [--foo FOO]

optional arguments:
 -h, --help  show this help message and exit
 --foo FOO   foo help

때에 따라, 이 도움말 옵션을 추가하지 않도록 설정하는 것이 유용 할 수 있습니다. add_help= 인자를 False 로 ArgumentParser 에 전달하면 됩니다:

>>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
>>> parser.add_argument('--foo', help='foo help')
>>> parser.print_help()
usage: PROG [--foo FOO]

optional arguments:
 --foo FOO  foo help

도움말 옵션은 일반적으로 -h/--help 입니다. 예외는 prefix_chars= 가 지정되고 - 을 포함하지 않는 경우입니다. 이 경우 -h 와 --help 는 유효한 옵션이 아닙니다. 이 경우, prefix_chars 의 첫 번째 문자가 도움말 옵션 접두어로 사용됩니다:

>>> parser = argparse.ArgumentParser(prog='PROG', prefix_chars='+/')
>>> parser.print_help()
usage: PROG [+h]

optional arguments:
  +h, ++help  show this help message and exit

add_argument() 메서드

ArgumentParser.add_argument(name or flags...[, action][, nargs][, const][, default][, type][, choices][, required][, help][, metavar][, dest])

단일 명령행 인자를 구문 분석하는 방법을 정의합니다. 매개 변수마다 아래에서 더 자세히 설명되지만, 요약하면 다음과 같습니다:

name or flags - 옵션 문자열의 이름이나 리스트, 예를 들어 foo 또는 -f, --foo.

action - 명령행에서 이 인자가 발견될 때 수행 할 액션의 기본형.

nargs - 소비되어야 하는 명령행 인자의 수.

const - 일부 action 및 nargs 를 선택할 때 필요한 상숫값.

default - 인자가 명령행에 없는 경우 생성되는 값.

type - 명령행 인자가 변환되어야 할 형.

choices - 인자로 허용되는 값의 컨테이너.

required - 명령행 옵션을 생략 할 수 있는지 아닌지 (선택적일 때만).

help - 인자가 하는 일에 대한 간단한 설명.

metavar - 사용 메시지에 사용되는 인자의 이름.

dest - parse_args() 가 반환하는 객체에 추가될 어트리뷰트의 이름.

다음 절에서는 이들 각각의 사용 방법에 관해 설명합니다.

name or flags

add_argument() 메서드는 -f 나 --foo 와 같은 선택 인자가 필요한지, 파일 이름의 리스트와 같은 위치 인자가 필요한지 알아야 합니다. 따라서 add_argument() 에 전달되는 첫 번째 인자는 일련의 플래그이거나 간단한 인자 이름이어야 합니다. 예를 들어 선택 인자는 이렇게 만들어질 수 있습니다:

>>> parser.add_argument('-f', '--foo')

반면에 위치 인자는 이렇게 만들어집니다:

>>> parser.add_argument('bar')

parse_args() 가 호출되면, 선택 인자는 - 접두사로 식별되고, 그 밖의 인자는 위치 인자로 간주합니다:

>>> parser = argparse.ArgumentParser(prog='PROG')
>>> parser.add_argument('-f', '--foo')
>>> parser.add_argument('bar')
>>> parser.parse_args(['BAR'])
Namespace(bar='BAR', foo=None)
>>> parser.parse_args(['BAR', '--foo', 'FOO'])
Namespace(bar='BAR', foo='FOO')
>>> parser.parse_args(['--foo', 'FOO'])
usage: PROG [-h] [-f FOO] bar
PROG: error: the following arguments are required: bar

action

ArgumentParser 객체는 명령행 인자를 액션과 연관시킵니다. 대부분의 액션은 단순히 parse_args() 에 의해 반환된 객체에 어트리뷰트를 추가하기만 하지만, 액션은 관련된 명령행 인자로 무엇이든 할 수 있습니다. action 키워드 인자는 명령행 인자의 처리 방법을 지정합니다. 제공되는 액션은 다음과 같습니다:

'store' - 인자 값을 저장합니다. 이것이 기본 액션입니다. 예를 들면:

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo')
>>> parser.parse_args('--foo 1'.split())
Namespace(foo='1')

'store_const' - const 키워드 인자에 의해 지정된 값을 저장합니다. 'store_const' 액션은 어떤 종류의 플래그를 지정하는 선택 인자와 함께 사용하는 것이 가장 일반적입니다. 예를 들면:

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', action='store_const', const=42)
>>> parser.parse_args(['--foo'])
Namespace(foo=42)

'store_true' 와 'store_false' - 각각 True 와 False 값을 저장하는 'store_const' 의 특별한 경우입니다. 또한, 각각 기본값 False 와 True 를 생성합니다. 예를 들면:

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', action='store_true')
>>> parser.add_argument('--bar', action='store_false')
>>> parser.add_argument('--baz', action='store_false')
>>> parser.parse_args('--foo --bar'.split())
Namespace(foo=True, bar=False, baz=True)

'append' - 리스트를 저장하고 각 인자 값을 리스트에 추가합니다. 옵션을 여러 번 지정할 수 있도록 하는 데 유용합니다. 사용 예:

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', action='append')
>>> parser.parse_args('--foo 1 --foo 2'.split())
Namespace(foo=['1', '2'])

'append_const' - 리스트를 저장하고 const 키워드 인자로 지정된 값을 리스트에 추가합니다. (const 키워드의 기본값은 None 입니다.) 'append_const' 액션은 여러 개의 인자가 같은 리스트에 상수를 저장해야 할 때 유용합니다. 예를 들면:

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--str', dest='types', action='append_const', const=str)
>>> parser.add_argument('--int', dest='types', action='append_const', const=int)
>>> parser.parse_args('--str --int'.split())
Namespace(types=[<class 'str'>, <class 'int'>])

'count' - 키워드 인자가 등장한 횟수를 계산합니다. 예를 들어, 상세도를 높이는 데 유용합니다:

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--verbose', '-v', action='count', default=0)
>>> parser.parse_args(['-vvv'])
Namespace(verbose=3)

Note, the default will be None unless explicitly set to 0.

'help' - 현재 파서의 모든 옵션에 대한 완전한 도움말 메시지를 출력하고 종료합니다. 기본적으로 help 액션은 자동으로 파서에 추가됩니다. 출력이 만들어지는 방법에 대한 자세한 내용은 ArgumentParser 를 보세요.

'version' - add_argument() 호출에서 version= 키워드 인자를 기대하고, 호출되면 버전 정보를 출력하고 종료합니다:

>>> import argparse
>>> parser = argparse.ArgumentParser(prog='PROG')
>>> parser.add_argument('--version', action='version', version='%(prog)s 2.0')
>>> parser.parse_args(['--version'])
PROG 2.0

Action 서브 클래스나 같은 인터페이스를 구현하는 다른 객체를 전달하여 임의의 액션을 지정할 수도 있습니다. 권장하는 방법은 Action 을 확장하여 __call__ 메서드와 선택적으로 __init__ 메서드를 재정의하는 것입니다.

사용자 정의 액션의 예:

>>> class FooAction(argparse.Action):
...     def __init__(self, option_strings, dest, nargs=None, **kwargs):
...         if nargs is not None:
...             raise ValueError("nargs not allowed")
...         super(FooAction, self).__init__(option_strings, dest, **kwargs)
...     def __call__(self, parser, namespace, values, option_string=None):
...         print('%r %r %r' % (namespace, values, option_string))
...         setattr(namespace, self.dest, values)
...
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', action=FooAction)
>>> parser.add_argument('bar', action=FooAction)
>>> args = parser.parse_args('1 --foo 2'.split())
Namespace(bar=None, foo=None) '1' None
Namespace(bar='1', foo=None) '2' '--foo'
>>> args
Namespace(bar='1', foo='2')

자세한 내용은 Action 을 참조하십시오.

nargs

ArgumentParser 객체는 일반적으로 하나의 명령행 인자를 하나의 액션과 결합합니다. nargs 키워드 인자는 다른 수의 명령행 인자를 하나의 액션으로 연결합니다. 지원되는 값은 다음과 같습니다:

N (정수). 명령행에서 N 개의 인자를 함께 모아서 리스트에 넣습니다. 예를 들면:

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', nargs=2)
>>> parser.add_argument('bar', nargs=1)
>>> parser.parse_args('c --foo a b'.split())
Namespace(bar=['c'], foo=['a', 'b'])

nargs=1 은 하나의 항목을 갖는 리스트를 생성합니다. 이는 항목 그대로 생성되는 기본값과 다릅니다.

'?'. 가능하다면 한 인자가 명령행에서 소비되고 단일 항목으로 생성됩니다. 명령행 인자가 없으면 default 의 값이 생성됩니다. 선택 인자의 경우 추가적인 경우가 있습니다 - 옵션 문자열은 있지만, 명령행 인자가 따라붙지 않는 경우입니다. 이 경우 const 의 값이 생성됩니다. 이것을 보여주기 위해 몇 가지 예를 듭니다:

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', nargs='?', const='c', default='d')
>>> parser.add_argument('bar', nargs='?', default='d')
>>> parser.parse_args(['XX', '--foo', 'YY'])
Namespace(bar='XX', foo='YY')
>>> parser.parse_args(['XX', '--foo'])
Namespace(bar='XX', foo='c')
>>> parser.parse_args([])
Namespace(bar='d', foo='d')

nargs='?' 의 흔한 사용법 중 하나는 선택적 입출력 파일을 허용하는 것입니다:

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('infile', nargs='?', type=argparse.FileType('r'),
...                     default=sys.stdin)
>>> parser.add_argument('outfile', nargs='?', type=argparse.FileType('w'),
...                     default=sys.stdout)
>>> parser.parse_args(['input.txt', 'output.txt'])
Namespace(infile=<_io.TextIOWrapper name='input.txt' encoding='UTF-8'>,
          outfile=<_io.TextIOWrapper name='output.txt' encoding='UTF-8'>)
>>> parser.parse_args([])
Namespace(infile=<_io.TextIOWrapper name='<stdin>' encoding='UTF-8'>,
          outfile=<_io.TextIOWrapper name='<stdout>' encoding='UTF-8'>)

'*'. 모든 명령행 인자를 리스트로 수집합니다. 일반적으로 두 개 이상의 위치 인자에 대해 nargs='*' 를 사용하는 것은 별로 의미가 없지만, nargs='*' 를 갖는 여러 개의 선택 인자는 가능합니다. 예를 들면:

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', nargs='*')
>>> parser.add_argument('--bar', nargs='*')
>>> parser.add_argument('baz', nargs='*')
>>> parser.parse_args('a b --foo x y --bar 1 2'.split())
Namespace(bar=['1', '2'], baz=['a', 'b'], foo=['x', 'y'])

'+'. '*' 와 같이, 존재하는 모든 명령행 인자를 리스트로 모읍니다. 또한, 적어도 하나의 명령행 인자가 제공되지 않으면 에러 메시지가 만들어집니다. 예를 들면:

>>> parser = argparse.ArgumentParser(prog='PROG')
>>> parser.add_argument('foo', nargs='+')
>>> parser.parse_args(['a', 'b'])
Namespace(foo=['a', 'b'])
>>> parser.parse_args([])
usage: PROG [-h] foo [foo ...]
PROG: error: the following arguments are required: foo

argparse.REMAINDER. 남은 모든 명령행 인자를 리스트로 수집합니다. 이것은 일반적으로 다른 명령행 유틸리티를 호출하는 명령행 유틸리티에 유용합니다:

>>> parser = argparse.ArgumentParser(prog='PROG')
>>> parser.add_argument('--foo')
>>> parser.add_argument('command')
>>> parser.add_argument('args', nargs=argparse.REMAINDER)
>>> print(parser.parse_args('--foo B cmd --arg1 XX ZZ'.split()))
Namespace(args=['--arg1', 'XX', 'ZZ'], command='cmd', foo='B')

nargs 키워드 인자가 제공되지 않으면, 소비되는 인자의 개수는 action 에 의해 결정됩니다. 일반적으로 이는 하나의 명령행 인자가 소비되고 하나의 항목(리스트가 아닙니다)이 생성됨을 의미합니다.

const

add_argument() 의 const 인자는 명령행에서 읽지는 않지만 다양한 ArgumentParser 액션에 필요한 상숫값을 저장하는 데 사용됩니다. 가장 흔한 두 가지 용도는 다음과 같습니다:

add_argument() 가 action='store_const' 또는 action='append_const' 로 호출될 때. 이 액션은 parse_args() 에 의해 반환된 객체의 어트리뷰트 중 하나에 const 값을 추가합니다. 예제는 action 설명을 참조하십시오.

add_argument() 가 옵션 문자열(-f 또는 --foo 와 같은)과 nargs='?' 로 호출될 때. 이것은 0 또는 하나의 명령행 인자가 뒤따르는 선택 인자를 만듭니다. 명령행을 파싱할 때 옵션 문자열 뒤에 명령행 인자가 없으면 const 값이 대신 가정됩니다. 예제는 nargs 설명을 참조하십시오.

'store_const' 와 'append_const' 액션을 사용할 때는 const 키워드 인자를 반드시 주어야 합니다. 다른 액션의 경우, 기본값은 None 입니다.

default

모든 선택 인자와 일부 위치 인자는 명령행에서 생략될 수 있습니다. add_argument() 의 default 키워드 인자는, 기본값은 None 입니다, 명령행 인자가 없을 때 어떤 값을 사용해야 하는지를 지정합니다. 선택 인자의 경우, 옵션 문자열이 명령행에 없을 때 default 값이 사용됩니다:

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', default=42)
>>> parser.parse_args(['--foo', '2'])
Namespace(foo='2')
>>> parser.parse_args([])
Namespace(foo=42)

default 값이 문자열이면, 파서는 마치 명령행 인자인 것처럼 파싱합니다. 특히, 파서는 Namespace 반환 값에 어트리뷰트를 설정하기 전에, 제공된 모든 type 변환 인자를 적용합니다. 그렇지 않은 경우, 파서는 값을 있는 그대로 사용합니다:

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--length', default='10', type=int)
>>> parser.add_argument('--width', default=10.5, type=int)
>>> parser.parse_args()
Namespace(length=10, width=10.5)

nargs 가 ? 또는 * 인 위치 인자의 경우, 명령행 인자가 없을 때 default 값이 사용됩니다:

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('foo', nargs='?', default=42)
>>> parser.parse_args(['a'])
Namespace(foo='a')
>>> parser.parse_args([])
Namespace(foo=42)

default=argparse.SUPPRESS 를 지정하면 명령행 인자가 없는 경우 어트리뷰트가 추가되지 않습니다:

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', default=argparse.SUPPRESS)
>>> parser.parse_args([])
Namespace()
>>> parser.parse_args(['--foo', '1'])
Namespace(foo='1')

type

기본적으로 ArgumentParser 객체는 명령행 인자를 간단한 문자열로 읽습니다. 그러나 꽤 자주 명령행 문자열은 float 또는 int와 같은 다른 형으로 해석되어야 합니다. add_argument() 의 type 키워드 인자는 필요한 형 검사와 형 변환이 수행되도록 합니다. 일반적인 내장형과 함수는 type 인자의 값으로 직접 사용될 수 있습니다:

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('foo', type=int)
>>> parser.add_argument('bar', type=open)
>>> parser.parse_args('2 temp.txt'.split())
Namespace(bar=<_io.TextIOWrapper name='temp.txt' encoding='UTF-8'>, foo=2)

언제 type 인자가 기본 인자에 적용되는지에 대한 정보는 default 키워드 인자 절을 참조하십시오.

다양한 형태의 파일을 사용하기 쉽게 하려고, argparse 모듈은 open() 함수의 mode=, bufsize=, encoding=, errors= 인자를 취하는 팩토리 FileType 을 제공합니다. 예를 들어, FileType('w') 은 쓰기 가능한 파일을 만드는 데 사용할 수 있습니다

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('bar', type=argparse.FileType('w'))
>>> parser.parse_args(['out.txt'])
Namespace(bar=<_io.TextIOWrapper name='out.txt' encoding='UTF-8'>)

type= 는 단일 문자열 인자를 취하고 변환된 값을 돌려주는 모든 콜러블을 받아들입니다:

>>> def perfect_square(string):
...     value = int(string)
...     sqrt = math.sqrt(value)
...     if sqrt != int(sqrt):
...         msg = "%r is not a perfect square" % string
...         raise argparse.ArgumentTypeError(msg)
...     return value
...
>>> parser = argparse.ArgumentParser(prog='PROG')
>>> parser.add_argument('foo', type=perfect_square)
>>> parser.parse_args(['9'])
Namespace(foo=9)
>>> parser.parse_args(['7'])
usage: PROG [-h] foo
PROG: error: argument foo: '7' is not a perfect square

단순히 값의 범위를 검사하는 형 검사기로는 choices 키워드 인자가 더 편리할 수 있습니다:

>>> parser = argparse.ArgumentParser(prog='PROG')
>>> parser.add_argument('foo', type=int, choices=range(5, 10))
>>> parser.parse_args(['7'])
Namespace(foo=7)
>>> parser.parse_args(['11'])
usage: PROG [-h] {5,6,7,8,9}
PROG: error: argument foo: invalid choice: 11 (choose from 5, 6, 7, 8, 9)

자세한 내용은 choices 섹션을 참조하십시오.

choices

일부 명령행 인자는 제한된 값 집합에서 선택되어야 합니다. add_argument() 에 컨테이너 객체를 choices 키워드 인자로 전달하여 처리할 수 있습니다. 명령행을 파싱할 때, 인자의 값을 검사하고, 인자가 받아들일 수 없는 값이 아닌 경우 에러 메시지가 표시됩니다:

>>> parser = argparse.ArgumentParser(prog='game.py')
>>> parser.add_argument('move', choices=['rock', 'paper', 'scissors'])
>>> parser.parse_args(['rock'])
Namespace(move='rock')
>>> parser.parse_args(['fire'])
usage: game.py [-h] {rock,paper,scissors}
game.py: error: argument move: invalid choice: 'fire' (choose from 'rock',
'paper', 'scissors')

choices 컨테이너에 포함되는지는 type 변환이 수행된 후에 검사하므로, choices 컨테이너에 있는 객체의 형은 지정된 type 과 일치해야 합니다:

>>> parser = argparse.ArgumentParser(prog='doors.py')
>>> parser.add_argument('door', type=int, choices=range(1, 4))
>>> print(parser.parse_args(['3']))
Namespace(door=3)
>>> parser.parse_args(['4'])
usage: doors.py [-h] {1,2,3}
doors.py: error: argument door: invalid choice: 4 (choose from 1, 2, 3)

in 연산자를 지원하는 모든 객체는 choices 값으로 전달될 수 있으므로, dict 객체, set 객체, 사용자 정의 컨테이너 등이 모두 지원됩니다.

required

일반적으로 argparse 모듈은 -f 와 --bar 같은 플래그가 명령행에서 생략될 수 있는 선택적 인자를 가리킨다고 가정합니다. 옵션을 필수로 만들기 위해, add_argument() 의 required= 키워드 인자에 True 를 지정할 수 있습니다:

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', required=True)
>>> parser.parse_args(['--foo', 'BAR'])
Namespace(foo='BAR')
>>> parser.parse_args([])
usage: argparse.py [-h] [--foo FOO]
argparse.py: error: option --foo is required

예에서 보듯이, 옵션이 required 로 표시되면, parse_args() 는 그 옵션이 명령행에 없을 때 에러를 보고합니다.

참고

필수 옵션은 사용자가 옵션 이 선택적 일 것으로 기대하기 때문에 일반적으로 나쁜 형식으로 간주하므로 가능하면 피해야 합니다.

help

help 값은 인자의 간단한 설명이 들어있는 문자열입니다. 사용자가 도움말을 요청하면 (보통 명령행에서 -h 또는 --help 를 사용합니다), help 설명이 각 인자와 함께 표시됩니다:

>>> parser = argparse.ArgumentParser(prog='frobble')
>>> parser.add_argument('--foo', action='store_true',
...                     help='foo the bars before frobbling')
>>> parser.add_argument('bar', nargs='+',
...                     help='one of the bars to be frobbled')
>>> parser.parse_args(['-h'])
usage: frobble [-h] [--foo] bar [bar ...]

positional arguments:
 bar     one of the bars to be frobbled

optional arguments:
 -h, --help  show this help message and exit
 --foo   foo the bars before frobbling

help 문자열은 프로그램 이름이나 인자 default 와 같은 것들의 반복을 피하고자 다양한 포맷 지정자를 포함 할 수 있습니다. 사용할 수 있는 지정자는 프로그램 이름, %(prog)s 와 add_argument() 의 대부분의 키워드 인자, %(default)s, %(type)s 등을 포함합니다.:

>>> parser = argparse.ArgumentParser(prog='frobble')
>>> parser.add_argument('bar', nargs='?', type=int, default=42,
...                     help='the bar to %(prog)s (default: %(default)s)')
>>> parser.print_help()
usage: frobble [-h] [bar]

positional arguments:
 bar     the bar to frobble (default: 42)

optional arguments:
 -h, --help  show this help message and exit

도움말 문자열이 %-포매팅을 지원하기 때문에, 도움말 문자열에 리터럴 % 을 표시하려면, %% 로 이스케이프 처리해야 합니다.

argparse 는 help 값을 argparse.SUPPRESS 로 설정함으로써 특정 옵션에 대한 도움말 엔트리를 감추는 것을 지원합니다:

>>> parser = argparse.ArgumentParser(prog='frobble')
>>> parser.add_argument('--foo', help=argparse.SUPPRESS)
>>> parser.print_help()
usage: frobble [-h]

optional arguments:
  -h, --help  show this help message and exit

metavar

ArgumentParser 가 도움말 메시지를 생성할 때, 기대되는 각 인자를 가리킬 방법이 필요합니다. 기본적으로 ArgumentParser 객체는 dest 값을 각 객체의 “이름”으로 사용합니다. 기본적으로 위치 인자 액션의 경우 dest 값이 직접 사용되고, 선택 인자 액션의 경우 dest 값의 대문자가 사용됩니다. 그래서, dest='bar' 인 단일 위치 인자는 bar 로 지칭됩니다. 하나의 명령행 인자가 따라와야 하는 단일 선택 인자 --foo 는 FOO 라고 표시됩니다. 예:

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo')
>>> parser.add_argument('bar')
>>> parser.parse_args('X --foo Y'.split())
Namespace(bar='X', foo='Y')
>>> parser.print_help()
usage:  [-h] [--foo FOO] bar

positional arguments:
 bar

optional arguments:
 -h, --help  show this help message and exit
 --foo FOO

다른 이름은 metavar 로 지정할 수 있습니다:

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', metavar='YYY')
>>> parser.add_argument('bar', metavar='XXX')
>>> parser.parse_args('X --foo Y'.split())
Namespace(bar='X', foo='Y')
>>> parser.print_help()
usage:  [-h] [--foo YYY] XXX

positional arguments:
 XXX

optional arguments:
 -h, --help  show this help message and exit
 --foo YYY

metavar 는 표시되는 이름 만 변경합니다 - parse_args() 객체의 어트리뷰트 이름은 여전히 dest 값에 의해 결정됩니다.

nargs 값이 다르면 metavar 가 여러 번 사용될 수 있습니다. metavar 에 튜플을 제공하면 인자마다 다른 디스플레이가 지정됩니다:

>>> parser = argparse.ArgumentParser(prog='PROG')
>>> parser.add_argument('-x', nargs=2)
>>> parser.add_argument('--foo', nargs=2, metavar=('bar', 'baz'))
>>> parser.print_help()
usage: PROG [-h] [-x X X] [--foo bar baz]

optional arguments:
 -h, --help     show this help message and exit
 -x X X
 --foo bar baz

dest

대부분 ArgumentParser 액션은 parse_args() 에 의해 반환된 객체의 어트리뷰트로 어떤 값을 추가합니다. 이 어트리뷰트의 이름은 add_argument() 의 dest 키워드 인자에 의해 결정됩니다. 위치 인자 액션의 경우, dest 는 일반적으로 add_argument() 에 첫 번째 인자로 제공됩니다.:

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('bar')
>>> parser.parse_args(['XXX'])
Namespace(bar='XXX')

선택 인자 액션의 경우, dest 의 값은 보통 옵션 문자열에서 유추됩니다. ArgumentParser 는 첫 번째 긴 옵션 문자열을 취하고 앞의 -- 문자열을 제거하여 dest 의 값을 만듭니다. 긴 옵션 문자열이 제공되지 않았다면 dest 는 첫 번째 짧은 옵션 문자열에서 앞의 - 문자를 제거하여 만듭니다. 문자열이 항상 유효한 어트리뷰트 이름이 되도록 만들기 위해 중간에 나오는 - 문자는 _ 문자로 변환됩니다. 아래 예제는 이 동작을 보여줍니다:

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('-f', '--foo-bar', '--foo')
>>> parser.add_argument('-x', '-y')
>>> parser.parse_args('-f 1 -x 2'.split())
Namespace(foo_bar='1', x='2')
>>> parser.parse_args('--foo 1 -y 2'.split())
Namespace(foo_bar='1', x='2')

dest 는 사용자 정의 어트리뷰트 이름을 지정할 수 있게 합니다:

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', dest='bar')
>>> parser.parse_args('--foo XXX'.split())
Namespace(bar='XXX')

Action 클래스

Action 클래스는 액션 API를 구현합니다. 액션 API는 명령행에서 인자를 처리하는 콜러블을 반환하는 콜러블 객체입니다. 이 API를 따르는 모든 객체는 add_argument() 의 action 매개 변수로 전달될 수 있습니다.

class argparse.Action(option_strings, dest, nargs=None, const=None, default=None, type=None, choices=None, required=False, help=None, metavar=None)

Action 객체는 ArgumentParser에서 명령행의 하나 이상의 문자열에서 단일 인자를 파싱하는 데 필요한 정보를 나타내기 위해 사용됩니다. Action 클래스는 두 개의 위치 인자와 ArgumentParser.add_argument() 에 전달된 action 자신을 제외한 모든 키워드 인자들을 받아들여야 합니다.

Action 인스턴스(또는 action 매개 변수로 전달된 콜러블의 반환 값)는 “dest”, “option_strings”, “default”, “type”, “required”, “help” 등의 어트리뷰트가 정의되어야 합니다. 이러한 어트리뷰트를 정의하는 가장 쉬운 방법은 Action.__init__ 를 호출하는 것입니다.

Action 인스턴스는 콜러블이어야 하므로, 서브 클래스는 네 개의 매개 변수를 받아들이는 __call__ 메서드를 재정의해야 합니다:

parser - 이 액션을 포함하는 ArgumentParser 객체.

namespace - parse_args() 에 의해 반환될 Namespace 객체. 대부분의 액션은 setattr() 을 사용하여 이 객체에 어트리뷰트를 추가합니다.

values - 형 변환이 적용된 연관된 명령행 인자. 형 변환은 add_argument() 에 전달된 type 키워드 인자로 지정됩니다.

option_string - 이 액션을 호출하는 데 사용된 옵션 문자열. option_string 인자는 선택적이며, 액션이 위치 인자와 관련되어 있으면 생략됩니다.

__call__ 메서드는 임의의 액션을 수행 할 수 있습니다만, 일반적으로 dest 와 values 에 기반하여 namespace 에 어트리뷰트를 설정합니다.

parse_args() 메서드

ArgumentParser.parse_args(args=None, namespace=None)

인자 문자열을 객체로 변환하고 namespace의 어트리뷰트로 설정합니다. 값들이 설정된 namespace를 돌려줍니다.

이전의 add_argument() 호출이 어떤 객체를 만들고 어떤 식으로 대입할지를 결정합니다. 자세한 내용은 add_argument() 설명서를 참조하십시오.

args - 구문 분석할 문자열 리스트. 기본값은 sys.argv 에서 취합니다.

namespace - 어트리뷰트가 대입될 객체. 기본값은 새로 만들어지는 빈 Namespace 객체입니다.

옵션값 문법

parse_args() 메서드는 (취할 것이 있다면) 옵션의 값을 지정하는 몇 가지 방법을 지원합니다. 가장 단순한 경우, 옵션과 그 값은 두 개의 독립적인 인자로 전달됩니다:

>>> parser = argparse.ArgumentParser(prog='PROG')
>>> parser.add_argument('-x')
>>> parser.add_argument('--foo')
>>> parser.parse_args(['-x', 'X'])
Namespace(foo=None, x='X')
>>> parser.parse_args(['--foo', 'FOO'])
Namespace(foo='FOO', x=None)

긴 옵션(단일 문자보다 긴 이름을 가진 옵션)의 경우, 옵션과 값을 = 로 구분하여 단일 명령행 인자로 전달할 수도 있습니다:

>>> parser.parse_args(['--foo=FOO'])
Namespace(foo='FOO', x=None)

짧은 옵션(한 문자 길이의 옵션)의 경우, 옵션과 해당 값을 이어붙일 수 있습니다:

>>> parser.parse_args(['-xX'])
Namespace(foo=None, x='X')

여러 개의 짧은 옵션은 마지막 옵션만 값을 요구하는 한 (또는 그들 중 아무것도 값을 요구하지 않거나), 하나의 - 접두어를 사용하여 함께 결합 할 수 있습니다:

>>> parser = argparse.ArgumentParser(prog='PROG')
>>> parser.add_argument('-x', action='store_true')
>>> parser.add_argument('-y', action='store_true')
>>> parser.add_argument('-z')
>>> parser.parse_args(['-xyzZ'])
Namespace(x=True, y=True, z='Z')

잘못된 인자

명령행을 파싱할 때, parse_args() 는 모호한 옵션, 유효하지 않은 형, 유효하지 않은 옵션, 잘못된 위치 인자의 수 등을 포함한 다양한 에러를 검사합니다. 이런 에러가 발생하면, 사용 메시지와 함께 에러를 인쇄합니다:

>>> parser = argparse.ArgumentParser(prog='PROG')
>>> parser.add_argument('--foo', type=int)
>>> parser.add_argument('bar', nargs='?')

>>> # invalid type
>>> parser.parse_args(['--foo', 'spam'])
usage: PROG [-h] [--foo FOO] [bar]
PROG: error: argument --foo: invalid int value: 'spam'

>>> # invalid option
>>> parser.parse_args(['--bar'])
usage: PROG [-h] [--foo FOO] [bar]
PROG: error: no such option: --bar

>>> # wrong number of arguments
>>> parser.parse_args(['spam', 'badger'])
usage: PROG [-h] [--foo FOO] [bar]
PROG: error: extra arguments found: badger

- 를 포함하는 인자들

parse_args() 메서드는 사용자가 분명히 실수했을 때마다 에러를 주려고 하지만, 어떤 상황은 본질에서 모호합니다. 예를 들어, 명령행 인자 -1 은 옵션을 지정하려는 시도이거나 위치 인자를 제공하려는 시도일 수 있습니다. parse_args() 메서드는 이럴 때 신중합니다: 위치 인자는 음수처럼 보이고 파서에 음수처럼 보이는 옵션이 없을 때만 - 로 시작할 수 있습니다:

>>> parser = argparse.ArgumentParser(prog='PROG')
>>> parser.add_argument('-x')
>>> parser.add_argument('foo', nargs='?')

>>> # no negative number options, so -1 is a positional argument
>>> parser.parse_args(['-x', '-1'])
Namespace(foo=None, x='-1')

>>> # no negative number options, so -1 and -5 are positional arguments
>>> parser.parse_args(['-x', '-1', '-5'])
Namespace(foo='-5', x='-1')

>>> parser = argparse.ArgumentParser(prog='PROG')
>>> parser.add_argument('-1', dest='one')
>>> parser.add_argument('foo', nargs='?')

>>> # negative number options present, so -1 is an option
>>> parser.parse_args(['-1', 'X'])
Namespace(foo=None, one='X')

>>> # negative number options present, so -2 is an option
>>> parser.parse_args(['-2'])
usage: PROG [-h] [-1 ONE] [foo]
PROG: error: no such option: -2

>>> # negative number options present, so both -1s are options
>>> parser.parse_args(['-1', '-1'])
usage: PROG [-h] [-1 ONE] [foo]
PROG: error: argument -1: expected one argument

- 로 시작해야 하고, 음수처럼 보이지 않는 위치 인자가 있는 경우, parse_args() 에 다음과 같은 의사 인자 '--' 를 삽입 할 수 있습니다. 그 이후의 모든 것은 위치 인자입니다:

>>> parser.parse_args(['--', '-f'])
Namespace(foo='-f', one=None)

인자 약어 (접두사 일치)

parse_args() 메서드는 기본적으로 약어가 모호하지 않으면 (접두사가 오직 하나의 옵션과 일치합니다) 긴 옵션을 접두사로 축약 할 수 있도록 합니다:

>>> parser = argparse.ArgumentParser(prog='PROG')
>>> parser.add_argument('-bacon')
>>> parser.add_argument('-badger')
>>> parser.parse_args('-bac MMM'.split())
Namespace(bacon='MMM', badger=None)
>>> parser.parse_args('-bad WOOD'.split())
Namespace(bacon=None, badger='WOOD')
>>> parser.parse_args('-ba BA'.split())
usage: PROG [-h] [-bacon BACON] [-badger BADGER]
PROG: error: ambiguous option: -ba could match -badger, -bacon

둘 이상의 옵션과 일치하는 인자는 에러를 일으킵니다. 이 기능은 allow_abbrev를 False 로 설정함으로써 비활성화시킬 수 있습니다.

sys.argv 너머

때로는 ArgumentParser가 sys.argv 의 인자가 아닌 다른 인자를 파싱하는 것이 유용 할 수 있습니다. 문자열 리스트를 parse_args() 에 전달하면 됩니다. 대화식 프롬프트에서 테스트할 때 유용합니다:

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument(
...     'integers', metavar='int', type=int, choices=range(10),
...     nargs='+', help='an integer in the range 0..9')
>>> parser.add_argument(
...     '--sum', dest='accumulate', action='store_const', const=sum,
...     default=max, help='sum the integers (default: find the max)')
>>> parser.parse_args(['1', '2', '3', '4'])
Namespace(accumulate=<built-in function max>, integers=[1, 2, 3, 4])
>>> parser.parse_args(['1', '2', '3', '4', '--sum'])
Namespace(accumulate=<built-in function sum>, integers=[1, 2, 3, 4])

Namespace 객체

class argparse.Namespace

parse_args() 가 어트리뷰트를 저장하고 반환할 객체를 만드는 데 기본적으로 사용하는 간단한 클래스.

이 클래스는 의도적으로 단순한데, 단지 가독성 있는 문자열 표현을 갖는 object 의 서브 클래스입니다. 어트리뷰트를 딕셔너리처럼 보기 원한다면, 표준 파이썬 관용구를 사용할 수 있습니다, vars():

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo')
>>> args = parser.parse_args(['--foo', 'BAR'])
>>> vars(args)
{'foo': 'BAR'}

ArgumentParser 가 새 Namespace 객체가 아니라 이미 존재하는 객체에 어트리뷰트를 대입하는 것이 유용 할 수 있습니다. namespace= 키워드 인자를 지정하면 됩니다:

>>> class C:
...     pass
...
>>> c = C()
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo')
>>> parser.parse_args(args=['--foo', 'BAR'], namespace=c)
>>> c.foo
'BAR'

기타 유틸리티

부속 명령

ArgumentParser.add_subparsers([title][, description][, prog][, parser_class][, action][, option_string][, dest][, required][, help][, metavar])

많은 프로그램은 그 기능을 여러 개의 부속 명령으로 나눕니다. 예를 들어, svn 프로그램은 svn checkout, svn update, svn commit 과 같은 부속 명령을 호출 할 수 있습니다. 이런 식으로 기능을 나누는 것은, 프로그램이 다른 명령행 인자를 요구하는 여러 가지 다른 기능을 수행할 때 특히 좋은 생각일 수 있습니다. ArgumentParser 는 add_subparsers() 메서드로 그러한 부속 명령의 생성을 지원합니다. add_subparsers() 메서드는 보통 인자 없이 호출되고 특별한 액션 객체를 돌려줍니다. 이 객체에는 add_parser()라는 하나의 메서드가 있습니다. 이 메서드는 명령 이름과 ArgumentParser 생성자 인자를 받고 평소와 같이 수정할 수 있는 ArgumentParser 객체를 반환합니다.

매개 변수 설명:

title - 도움말 출력의 부속 파서 그룹 제목; description이 제공되면 기본적으로 “subcommands”, 그렇지 않으면 위치 인자를 위한 제목을 사용합니다

description - 도움말 출력의 부속 파서 그룹에 대한 설명. 기본값은 None 입니다.

prog - 부속 명령 도움말과 함께 표시될 사용 정보. 기본적으로 프로그램 이름 및 부속 파서 인자 앞에 오는 위치 인자

parser_class - 부속 파서 인스턴스를 만들 때 사용할 클래스. 기본적으로, 현재 파서의 클래스 (예를 들어 ArgumentParser)

action - 이 인자를 명령행에서 만날 때 수행 할 액션의 기본형

dest - 부속 명령 이름을 저장하는 어트리뷰트의 이름. 기본적으로 None 이며 값은 저장되지 않습니다.

required - Whether or not a subcommand must be provided, by default False (added in 3.7)

help - 도움말 출력의 부속 파서 그룹 도움말, 기본적으로 None

metavar - 도움말에서 사용 가능한 부속 명령을 표시하는 문자열. 기본적으로 None 이며 {cmd1, cmd2, ..} 형식으로 부속 명령을 표시합니다.

몇 가지 사용 예:

>>> # create the top-level parser
>>> parser = argparse.ArgumentParser(prog='PROG')
>>> parser.add_argument('--foo', action='store_true', help='foo help')
>>> subparsers = parser.add_subparsers(help='sub-command help')
>>>
>>> # create the parser for the "a" command
>>> parser_a = subparsers.add_parser('a', help='a help')
>>> parser_a.add_argument('bar', type=int, help='bar help')
>>>
>>> # create the parser for the "b" command
>>> parser_b = subparsers.add_parser('b', help='b help')
>>> parser_b.add_argument('--baz', choices='XYZ', help='baz help')
>>>
>>> # parse some argument lists
>>> parser.parse_args(['a', '12'])
Namespace(bar=12, foo=False)
>>> parser.parse_args(['--foo', 'b', '--baz', 'Z'])
Namespace(baz='Z', foo=True)

parse_args() 에 의해 반환된 객체는 주 파서와 명령행에 의해 선택된 부속 파서(다른 부속 파서는 아님)의 어트리뷰트만을 포함한다는 것에 주의하십시오. 그래서 위의 예에서, a 명령이 지정되면 foo 와 bar 어트리뷰트 만 존재하고, b 명령이 지정되면 foo 와 baz 어트리뷰트만 존재합니다.

마찬가지로, 도움말 메시지가 부속 파서에서 요청되면 해당 파서에 대한 도움말만 인쇄됩니다. 도움말 메시지에는 상위 파서나 형제 파서 메시지는 포함되지 않습니다. (하지만 각 부속 파서 명령에 대한 도움말 메시지는 위와 같이 add_parser() 에 help= 인자를 주어 지정할 수 있습니다.)

>>> parser.parse_args(['--help'])
usage: PROG [-h] [--foo] {a,b} ...

positional arguments:
  {a,b}   sub-command help
    a     a help
    b     b help

optional arguments:
  -h, --help  show this help message and exit
  --foo   foo help

>>> parser.parse_args(['a', '--help'])
usage: PROG a [-h] bar

positional arguments:
  bar     bar help

optional arguments:
  -h, --help  show this help message and exit

>>> parser.parse_args(['b', '--help'])
usage: PROG b [-h] [--baz {X,Y,Z}]

optional arguments:
  -h, --help     show this help message and exit
  --baz {X,Y,Z}  baz help

add_subparsers() 메서드는 또한 title 과 description 키워드 인자를 지원합니다. 둘 중 하나가 있으면 부속 파서의 명령이 도움말 출력에서 자체 그룹으로 나타납니다. 예를 들면:

>>> parser = argparse.ArgumentParser()
>>> subparsers = parser.add_subparsers(title='subcommands',
...                                    description='valid subcommands',
...                                    help='additional help')
>>> subparsers.add_parser('foo')
>>> subparsers.add_parser('bar')
>>> parser.parse_args(['-h'])
usage:  [-h] {foo,bar} ...

optional arguments:
  -h, --help  show this help message and exit

subcommands:
  valid subcommands

  {foo,bar}   additional help

게다가, add_parser 는 aliases 인자를 추가로 지원하는데, 여러 개의 문자열이 같은 부속 파서를 참조 할 수 있게 해줍니다. 이 예는 svn 와 마찬가지로 checkout 의 약자로 co 라는 별칭을 만듭니다:

>>> parser = argparse.ArgumentParser()
>>> subparsers = parser.add_subparsers()
>>> checkout = subparsers.add_parser('checkout', aliases=['co'])
>>> checkout.add_argument('foo')
>>> parser.parse_args(['co', 'bar'])
Namespace(foo='bar')

부속 명령을 처리하는 특히 효과적인 방법의 하나는, add_subparsers() 메서드를 set_defaults() 호출과 결합하여, 각 부속 파서가 어떤 파이썬 함수를 실행해야 하는지 알 수 있도록 하는 것입니다. 예를 들면:

>>> # sub-command functions
>>> def foo(args):
...     print(args.x * args.y)
...
>>> def bar(args):
...     print('((%s))' % args.z)
...
>>> # create the top-level parser
>>> parser = argparse.ArgumentParser()
>>> subparsers = parser.add_subparsers()
>>>
>>> # create the parser for the "foo" command
>>> parser_foo = subparsers.add_parser('foo')
>>> parser_foo.add_argument('-x', type=int, default=1)
>>> parser_foo.add_argument('y', type=float)
>>> parser_foo.set_defaults(func=foo)
>>>
>>> # create the parser for the "bar" command
>>> parser_bar = subparsers.add_parser('bar')
>>> parser_bar.add_argument('z')
>>> parser_bar.set_defaults(func=bar)
>>>
>>> # parse the args and call whatever function was selected
>>> args = parser.parse_args('foo 1 -x 2'.split())
>>> args.func(args)
2.0
>>>
>>> # parse the args and call whatever function was selected
>>> args = parser.parse_args('bar XYZYX'.split())
>>> args.func(args)
((XYZYX))

이렇게 하면 parse_args() 가 파싱이 완료된 후 적절한 함수를 호출하게 할 수 있습니다. 이처럼 액션과 함수를 연결하는 것이, 일반적으로 각 부속 파서가 서로 다른 액션을 처리하도록 하는 가장 쉬운 방법입니다. 그러나 호출된 부속 파서의 이름을 확인해야 하는 경우 add_subparsers() 호출에 dest 키워드 인자를 제공합니다:

>>> parser = argparse.ArgumentParser()
>>> subparsers = parser.add_subparsers(dest='subparser_name')
>>> subparser1 = subparsers.add_parser('1')
>>> subparser1.add_argument('-x')
>>> subparser2 = subparsers.add_parser('2')
>>> subparser2.add_argument('y')
>>> parser.parse_args(['2', 'frobble'])
Namespace(subparser_name='2', y='frobble')

버전 3.7에서 변경: New required keyword argument.

FileType 객체

class argparse.FileType(mode='r', bufsize=-1, encoding=None, errors=None)

FileType 팩토리는 ArgumentParser.add_argument() 의 type 인자로 전달될 수 있는 객체를 만듭니다. type으로 FileType 객체를 사용하는 인자는 명령행 인자를 요청된 모드, 버퍼 크기, 인코딩 및 오류 처리의 파일로 엽니다 (자세한 내용은 open() 함수를 참조하세요):

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--raw', type=argparse.FileType('wb', 0))
>>> parser.add_argument('out', type=argparse.FileType('w', encoding='UTF-8'))
>>> parser.parse_args(['--raw', 'raw.dat', 'file.txt'])
Namespace(out=<_io.TextIOWrapper name='file.txt' mode='w' encoding='UTF-8'>, raw=<_io.FileIO name='raw.dat' mode='wb'>)

FileType 객체는 의사 인자 '-' 를 이해하고, 읽기 위한 FileType 객체는 sys.stdin 으로, 쓰기 위한 FileType 객체는 sys.stdout 으로 자동 변환합니다:

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('infile', type=argparse.FileType('r'))
>>> parser.parse_args(['-'])
Namespace(infile=<_io.TextIOWrapper name='<stdin>' encoding='UTF-8'>)

버전 3.4에 추가: encodings 및 errors 키워드 인자

인자 그룹

ArgumentParser.add_argument_group(title=None, description=None)

기본적으로 ArgumentParser 는 도움말 메시지를 표시할 때 “positional arguments”(위치 인자)와 “optional arguments”(선택 인자)로 명령행 인자를 그룹화합니다. 이 기본 그룹보다 더 나은 개념적 인자 그룹이 있는 경우, add_argument_group() 메서드를 사용하여 적절한 그룹을 만들 수 있습니다.:

>>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
>>> group = parser.add_argument_group('group')
>>> group.add_argument('--foo', help='foo help')
>>> group.add_argument('bar', help='bar help')
>>> parser.print_help()
usage: PROG [--foo FOO] bar

group:
  bar    bar help
  --foo FOO  foo help

add_argument_group() 메서드는 ArgumentParser 처럼 add_argument() 메서드를 가진 인자 그룹 객체를 반환합니다. 인자가 그룹에 추가될 때, 파서는 일반 인자처럼 취급하지만, 도움말 메시지는 별도의 그룹에 인자를 표시합니다. add_argument_group() 메서드는 이 표시를 사용자 정의하는데 사용할 수 있는 title 과 description 인자를 받아들입니다:

>>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
>>> group1 = parser.add_argument_group('group1', 'group1 description')
>>> group1.add_argument('foo', help='foo help')
>>> group2 = parser.add_argument_group('group2', 'group2 description')
>>> group2.add_argument('--bar', help='bar help')
>>> parser.print_help()
usage: PROG [--bar BAR] foo

group1:
  group1 description

  foo    foo help

group2:
  group2 description

  --bar BAR  bar help

사용자 정의 그룹에 없는 인자는 일반적인 “positional arguments” 및 “optional arguments” 섹션으로 들어갑니다.

상호 배제

ArgumentParser.add_mutually_exclusive_group(required=False)

상호 배타적인 그룹을 만듭니다. argparse 는 상호 배타적인 그룹에서 오직 하나의 인자만 명령행에 존재하는지 확인합니다:

>>> parser = argparse.ArgumentParser(prog='PROG')
>>> group = parser.add_mutually_exclusive_group()
>>> group.add_argument('--foo', action='store_true')
>>> group.add_argument('--bar', action='store_false')
>>> parser.parse_args(['--foo'])
Namespace(bar=True, foo=True)
>>> parser.parse_args(['--bar'])
Namespace(bar=False, foo=False)
>>> parser.parse_args(['--foo', '--bar'])
usage: PROG [-h] [--foo | --bar]
PROG: error: argument --bar: not allowed with argument --foo

add_mutually_exclusive_group() 메서드는 상호 배타적 인자 중 적어도 하나가 필요하다는 것을 나타내기 위한 required 인자도 받아들입니다:

>>> parser = argparse.ArgumentParser(prog='PROG')
>>> group = parser.add_mutually_exclusive_group(required=True)
>>> group.add_argument('--foo', action='store_true')
>>> group.add_argument('--bar', action='store_false')
>>> parser.parse_args([])
usage: PROG [-h] (--foo | --bar)
PROG: error: one of the arguments --foo --bar is required

현재, 상호 배타적인 인자 그룹은 add_argument_group() 의 title 및 description 인자를 지원하지 않습니다.

파서 기본값

ArgumentParser.set_defaults(**kwargs)

대부분은, parse_args() 에 의해 반환된 객체의 어트리뷰트는 명령행 인자와 인자 액션을 검사하여 완전히 결정됩니다. set_defaults() 는 명령행을 검사하지 않고 결정되는 몇 가지 추가적인 어트리뷰트를 추가할 수 있도록 합니다:

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('foo', type=int)
>>> parser.set_defaults(bar=42, baz='badger')
>>> parser.parse_args(['736'])
Namespace(bar=42, baz='badger', foo=736)

파서 수준의 기본값은 항상 인자 수준의 기본값보다 우선합니다:

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', default='bar')
>>> parser.set_defaults(foo='spam')
>>> parser.parse_args([])
Namespace(foo='spam')

파서 수준의 기본값은 여러 파서로 작업 할 때 특히 유용 할 수 있습니다. 이 유형의 예제는 add_subparsers() 메서드를 참조하십시오.

ArgumentParser.get_default(dest)

add_argument() 또는 set_defaults() 에 의해 설정된 이름 공간 어트리뷰트의 기본값을 가져옵니다:

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', default='badger')
>>> parser.get_default('foo')
'badger'

도움말 인쇄

대부분의 일반적인 응용 프로그램에서 parse_args() 가 사용법이나 오류 메시지를 포매팅하고 인쇄하는 것을 담당합니다. 그러나 여러 가지 포매팅 방법이 제공됩니다:

ArgumentParser.print_usage(file=None)

ArgumentParser 가 어떻게 명령행에서 호출되어야 하는지에 대한 간단한 설명을 인쇄합니다. file 이 None 이면, sys.stdout 이 가정됩니다.

ArgumentParser.print_help(file=None)

프로그램 사용법과 ArgumentParser 에 등록된 인자에 대한 정보를 포함하는 도움말 메시지를 출력합니다. file 이 None 이면, sys.stdout 이 가정됩니다.

인쇄하는 대신 단순히 문자열을 반환하는, 이러한 메서드의 변형도 있습니다:

ArgumentParser.format_usage()

ArgumentParser 가 어떻게 명령행에서 호출되어야 하는지에 대한 간단한 설명을 담은 문자열을 반환합니다.

ArgumentParser.format_help()

프로그램 사용법과 ArgumentParser 에 등록된 인자에 대한 정보를 포함하는 도움말 메시지를 담은 문자열을 반환합니다.

부분 파싱

ArgumentParser.parse_known_args(args=None, namespace=None)

때에 따라 스크립트는 명령행 인자 중 일부만 파싱하고 나머지 인자를 다른 스크립트 나 프로그램에 전달할 수 있습니다. 이 경우 parse_known_args() 메서드가 유용 할 수 있습니다. parse_args() 와 매우 유사하게 작동하는데, 여분의 인자가 있을 때 에러를 발생시키지 않는 점이 다릅니다. 대신, 채워진 이름 공간과 여분의 인자 문자열 리스트를 포함하는 두 항목 튜플을 반환합니다.

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', action='store_true')
>>> parser.add_argument('bar')
>>> parser.parse_known_args(['--foo', '--badger', 'BAR', 'spam'])
(Namespace(bar='BAR', foo=True), ['--badger', 'spam'])

경고

접두사 일치 규칙은 parse_known_args() 에 적용됩니다. 파서는 알려진 옵션 중 하나의 접두사 일지라도 여분의 인자 목록에 남기지 않고 옵션을 소비할 수 있습니다.

파일 파싱 사용자 정의

ArgumentParser.convert_arg_line_to_args(arg_line)

파일에서 읽은 인자는 (ArgumentParser 생성자의 fromfile_prefix_chars 키워드 인자를 참조하세요) 한 줄에 하나의 인자로 읽습니다. 이 동작을 변경하려면 convert_arg_line_to_args() 를 재정의합니다.

이 메서드는 하나의 인자 arg_line 를 받아들이는데, 인자 파일에서 읽어 들인 문자열입니다. 이 문자열에서 파싱된 인자 리스트를 반환합니다. 메서드는 인자 파일에서 읽어 들이는 대로 한 줄에 한 번씩 순서대로 호출됩니다.

이 메서드의 재정의하는 유용한 경우는 스페이스로 분리된 각 단어를 인자로 처리하는 것입니다. 다음 예제는 이렇게 하는 방법을 보여줍니다:

class MyArgumentParser(argparse.ArgumentParser):
    def convert_arg_line_to_args(self, arg_line):
        return arg_line.split()

종료 메서드

ArgumentParser.exit(status=0, message=None)

이 메서드는 지정된 status 상태 코드로 프로그램을 종료하고, message 가 주어지면 그 전에 인쇄합니다.

ArgumentParser.error(message)

이 메서드는 message 를 포함하는 사용법 메시지를 표준 에러에 인쇄하고, 상태 코드 2로 프로그램을 종료합니다.

혼합 파싱

ArgumentParser.parse_intermixed_args(args=None, namespace=None)

ArgumentParser.parse_known_intermixed_args(args=None, namespace=None)

많은 유닉스 명령은 사용자가 선택 인자와 위치 인자를 섞을 수 있도록 합니다. parse_intermixed_args() 와 parse_known_intermixed_args() 메서드는 이런 파싱 스타일을 지원합니다.

이 파서들은 argparse 기능을 모두 지원하지는 않으며 지원되지 않는 기능이 사용되는 경우 예외를 발생시킵니다. 특히 부속 파서, argparse.REMAINDER, 그리고 옵션과 위치를 모두 포함하는 상호 배타적인 그룹은 지원되지 않습니다.

다음 예제는 parse_known_args() 와 parse_intermixed_args() 의 차이점을 보여줍니다: 전자는 여분의 인자로 ['2', '3'] 을 반환하는 반면, 후자는 모든 위치 인자를 rest 로 모읍니다.

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo')
>>> parser.add_argument('cmd')
>>> parser.add_argument('rest', nargs='*', type=int)
>>> parser.parse_known_args('doit 1 --foo bar 2 3'.split())
(Namespace(cmd='doit', foo='bar', rest=[1]), ['2', '3'])
>>> parser.parse_intermixed_args('doit 1 --foo bar 2 3'.split())
Namespace(cmd='doit', foo='bar', rest=[1, 2, 3])

parse_known_intermixed_args() 는 채워진 이름 공간과 잔여 인자 문자열의 리스트를 포함하는 두 항목 튜플을 반환합니다. parse_intermixed_args() 는 파싱되지 않은 인자 문자열이 남아 있으면 에러를 발생시킵니다.

버전 3.7에 추가.

optparse 코드 업그레이드

원래, argparse 모듈은 optparse 와의 호환성을 유지하려고 시도했습니다. 그러나, optparse 는 투명하게 확장하기 어려운데, 특히 새로운 nargs= 지정자와 더 나은 사용법 메시지를 지원하는 데 필요한 변경에서 그렇습니다. optparse 에 있는 대부분이 복사-붙여넣기 되었거나 몽키 패치되었을 때, 더 하위 호환성을 유지하려고 노력하는 것이 실용적으로 보이지 않게 되었습니다.

argparse 모듈은 표준 라이브러리 optparse 모듈을 다음과 같은 여러 가지 방식으로 개선합니다:

위치 인자 처리.

부속 명령 지원.

+ 와 / 와 같은 다른 옵션 접두사 허용.

0개 이상 및 1개 이상 스타일의 인자 처리.

더욱 유익한 사용법 메시지 생성.

사용자 정의 type 과 action 을 위한 훨씬 간단한 인터페이스 제공.

optparse 에서 argparse 로의 부분적인 업그레이드 경로:

모든 optparse.OptionParser.add_option() 호출을 ArgumentParser.add_argument() 호출로 대체하십시오.

(options, args) = parser.parse_args() 를 args = parser.parse_args() 로 대체하고, 위치 인자에 대한 ArgumentParser.add_argument() 호출을 추가하십시오. 이전에 options 라고 불렀던 것이 이제 argparse 문맥에서 args 라는 것을 명심하십시오.

optparse.OptionParser.disable_interspersed_args() 를 parse_args() 대신 parse_intermixed_args() 를 사용하여 대체하십시오.

콜백 액션과 callback_* 키워드 인자를 type 또는 action 인자로 대체하십시오.

type 키워드 인자를 위한 문자열 이름을 해당 type 객체(예를 들어, int, float, complex 등)로 대체하십시오.

optparse.Values 를 Namespace 로, optparse.OptionError 와 optparse.OptionValueError 를 ArgumentError 로 대체하십시오.

%default 나 %prog 와 같은 묵시적인 인자를 포함하는 문자열을, 문자열 포맷에 딕셔너리를 사용하는 표준 파이썬 문법 대체하십시오, 즉 %(default)s 와 %(prog)s.

OptionParser 생성자의 version 인자를 parser.add_argument('--version', action='version', version='<the version>') 호출로 대체하십시오.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

일반 운영 체제 서비스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

일반 운영 체제 서비스 »

|

getopt — 명령 줄 옵션용 C 스타일 구문 분석기

소스 코드: Lib/getopt.py [https://github.com/python/cpython/tree/3.7/Lib/getopt.py]

참고

getopt 모듈은 API가 C getopt() 함수의 사용자에게 익숙하도록 설계된 명령 줄 옵션용 파서입니다. C getopt() 함수에 익숙하지 않거나, 더 적은 코드를 작성하고 더 나은 도움말과 에러 메시지를 얻으려는 사용자는 대신 argparse 모듈 사용을 고려해야 합니다.

이 모듈은 스크립트가 sys.argv에 있는 명령 줄 인자를 구문 분석하는 데 도움이 됩니다. 유닉스 getopt() 함수와 같은 규칙을 지원합니다 (’-’ 와 ‘--’ 형식의 인자의 특수한 의미를 포함합니다). 선택적인 세 번째 인자를 통해 GNU 소프트웨어가 지원하는 것과 유사한 긴 옵션을 사용할 수 있습니다.

이 모듈은 두 가지 함수와 예외를 제공합니다:

getopt.getopt(args, shortopts, longopts=[])

명령 줄 옵션과 매개 변수 목록을 구문 분석합니다. args는 실행 중인 프로그램에 대한 앞머리 참조를 포함하지 않는, 구문 분석할 인자 리스트입니다. 일반적으로, 이는 sys.argv[1:]를 의미합니다. shortopts는 스크립트가 인식하고자 하는 옵션 문자의 문자열이며, 인자를 요구하는 옵션은 뒤에 콜론(':'; 즉, 유닉스 getopt()가 사용하는 것과 같은 형식)이 필요합니다.

참고

GNU getopt()와는 달리, 옵션이 아닌 인자 다음에 오는 모든 인자는 옵션이 아닌 것으로 간주합니다. 이는 비 GNU 유닉스 시스템이 작동하는 방식과 비슷합니다.

지정되면, longopts는 지원되어야 하는 긴 옵션의 이름을 가진 문자열 리스트여야 합니다. 선행 '--' 문자는 옵션 이름에 포함되지 않아야 합니다. 인자가 필요한 긴 옵션 뒤에는 등호('=')가 와야 합니다. 선택적 인자는 지원되지 않습니다. 긴 옵션만 허용하려면, shortopts는 빈 문자열이어야 합니다. 명령 줄에서 긴 옵션은 허용된 옵션 중 하나와 정확히 일치하는 옵션 이름의 접두사를 제공하는 한 인식 할 수 있습니다. 예를 들어, longopts가 ['foo', 'frob'] 면 --fo 옵션은 --foo로 일치하지만, --f는 유일하게 일치하지 않으므로 GetoptError가 발생합니다.

반환 값은 두 요소로 구성됩니다: 첫 번째는 (option, value) 쌍의 리스트입니다; 두 번째는 옵션 리스트가 제거된 후 남겨진 프로그램 인자 리스트입니다 (이것은 args의 후행 슬라이스입니다). 반환된 각 옵션-값 쌍은 첫 번째 요소로 옵션을 가지며, 짧은 옵션(예를 들어, '-x')은 하이픈이, 긴 옵션(예를 들어, '--long-option')은 두 개의 하이픈이 접두사로 붙고, 두 번째 요소는 옵션 인자나 옵션에 인자가 없으면 빈 문자열입니다. 옵션은 발견된 순서와 같은 순서로 리스트에 나타나므로, 여러 번 나오는 것을 허용합니다. 긴 옵션과 짧은 옵션은 혼합될 수 있습니다.

getopt.gnu_getopt(args, shortopts, longopts=[])

이 함수는 기본적으로 GNU 스타일 스캔 모드가 사용된다는 점을 제외하고는 getopt()처럼 작동합니다. 이것은 옵션과 옵션이 아닌 인자가 섞일 수 있음을 뜻합니다. getopt() 함수는 옵션이 아닌 인자가 발견되자마자 옵션 처리를 중지합니다.

옵션 문자열의 첫 번째 문자가 '+' 이거나, 환경 변수 POSIXLY_CORRECT가 설정되면, 옵션이 아닌 인자를 만나자마자 옵션 처리가 중지됩니다.

exception getopt.GetoptError

인자 목록에 인식할 수 없는 옵션이 있거나 인자가 필요한 옵션에 아무것도 주어지지 않으면 발생합니다. 예외에 대한 인자는 에러의 원인을 나타내는 문자열입니다. 긴 옵션의 경우, 인자를 요구하지 않는 옵션에 인자가 주어질 때도 이 예외를 발생시킵니다. 어트리뷰트 msg 와 opt는 에러 메시지와 관련 옵션을 제공합니다; 예외와 관련된 특정 옵션이 없으면 opt는 빈 문자열입니다.

exception getopt.error

GetoptError의 별칭; 과거 호환성을 위한 것입니다.

유닉스 스타일 옵션만 사용하는 예제:

>>> import getopt
>>> args = '-a -b -cfoo -d bar a1 a2'.split()
>>> args
['-a', '-b', '-cfoo', '-d', 'bar', 'a1', 'a2']
>>> optlist, args = getopt.getopt(args, 'abc:d:')
>>> optlist
[('-a', ''), ('-b', ''), ('-c', 'foo'), ('-d', 'bar')]
>>> args
['a1', 'a2']

긴 옵션 이름을 사용하는 것도 똑같이 간단합니다:

>>> s = '--condition=foo --testing --output-file abc.def -x a1 a2'
>>> args = s.split()
>>> args
['--condition=foo', '--testing', '--output-file', 'abc.def', '-x', 'a1', 'a2']
>>> optlist, args = getopt.getopt(args, 'x', [
...     'condition=', 'output-file=', 'testing'])
>>> optlist
[('--condition', 'foo'), ('--testing', ''), ('--output-file', 'abc.def'), ('-x', '')]
>>> args
['a1', 'a2']

스크립트에서, 일반적인 사용법은 다음과 같습니다:

import getopt, sys

def main():
    try:
        opts, args = getopt.getopt(sys.argv[1:], "ho:v", ["help", "output="])
    except getopt.GetoptError as err:
        # print help information and exit:
        print(err)  # will print something like "option -a not recognized"
        usage()
        sys.exit(2)
    output = None
    verbose = False
    for o, a in opts:
        if o == "-v":
            verbose = True
        elif o in ("-h", "--help"):
            usage()
            sys.exit()
        elif o in ("-o", "--output"):
            output = a
        else:
            assert False, "unhandled option"
    # ...

if __name__ == "__main__":
    main()

argparse 모듈을 사용하면 더 적은 코드로, 더욱 유용한 도움말과 에러 메시지를 제공하는 동등한 명령 줄 인터페이스를 만들 수 있습니다:

import argparse

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('-o', '--output')
    parser.add_argument('-v', dest='verbose', action='store_true')
    args = parser.parse_args()
    # ... do something with args.output ...
    # ... do something with args.verbose ..

더 보기

모듈 argparse

대안 명령 줄 옵션과 인자 구문 분석 라이브러리.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

일반 운영 체제 서비스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

일반 운영 체제 서비스 »

|

logging — 파이썬 로깅 시설

소스 코드: Lib/logging/__init__.py [https://github.com/python/cpython/tree/3.7/Lib/logging/__init__.py]

Important

이 페이지는 API 레퍼런스 정보를 담고 있습니다. 자습서 정보 및 고급 주제에 대한 설명은 다음을 참조하십시오.

기초 자습서

고급 자습서

로깅 요리책

이 모듈은 응용 프로그램과 라이브러리를 위한 유연한 이벤트 로깅 시스템을 구현하는 함수와 클래스를 정의합니다.

표준 라이브러리 모듈로 로깅 API를 제공하는 것의 주요 이점은, 모든 파이썬 모듈이 로깅에 참여할 수 있어서, 응용 프로그램 로그에 여러분 자신의 메시지를 제삼자 모듈의 메시지와 통합할 수 있다는 것입니다.

이 모듈은 많은 기능과 유연성을 제공합니다. 로깅에 익숙하지 않다면, 감을 잡는 가장 좋은 방법은 자습서를 보는 것입니다 (오른쪽 링크를 참조하세요).

모듈에 의해 정의된 기본 클래스와 그 기능은 다음과 같습니다.

로거는 응용 프로그램 코드가 직접 사용하는 인터페이스를 노출합니다.

처리기는 (로거가 만든) 로그 레코드를 적절한 목적지로 보냅니다.

필터는 출력할 로그 레코드를 결정하기 위한 더 세분된 기능을 제공합니다.

포매터는 최종 출력에서 로그 레코드의 배치를 지정합니다.

Logger 객체

Loggers have the following attributes and methods. Note that Loggers should NEVER be instantiated directly, but always through the module-level function logging.getLogger(name). Multiple calls to getLogger() with the same name will always return a reference to the same Logger object.

name 은 잠재적으로 foo.bar.baz 와 같이 마침표로 구분된 계층적 값입니다 (하지만 그냥 간단한 foo 도 가능합니다). 계층적 목록에서 더 아래쪽에 있는 로거는 목록에서 상위에 있는 로거의 자식입니다. 예를 들어, 이름이 foo 인 로거가 주어지면, foo.bar, foo.bar.baz, 그리고 foo.bam 의 이름을 가진 로거는 모두 foo 의 자손입니다. 로거 이름 계층 구조는 파이썬 패키지 계층 구조와 비슷하며, logging.getLogger(__name__) 를 사용하여 모듈 단위로 로거를 구성하는 경우는 패키지 계층 구조와 같아집니다. 왜냐하면, 모듈에서, __name__ 은 파이썬 패키지 이름 공간의 모듈 이름이기 때문입니다.

class logging.Logger

propagate

이 어트리뷰트가 참으로 평가되면, 이 로거에 로그 된 이벤트는 이 로거에 첨부된 처리기뿐 아니라 상위 계층 (조상) 로거의 처리기로 전달됩니다. 메시지는 조상 로거의 처리기에 직접 전달됩니다 - 조상 로거의 수준이나 필터는 고려하지 않습니다.

이 값이 거짓으로 평가되면, 로깅 메시지가 조상 로거의 처리기로 전달되지 않습니다.

생성자는 이 어트리뷰트를 True 로 설정합니다.

참고

로거 와 하나 이상의 조상에 처리기를 중복해서 연결하면, 같은 레코드를 여러 번 출력할 수 있습니다. 일반적으로, 하나 이상의 로거에 처리기를 붙일 필요는 없습니다. 로거 계층에서 가장 높은 적절한 로거에 처리기를 연결하면, propagate 설정이 True 로 남아있는 모든 자식 로거들이 로그 하는 모든 이벤트를 보게 됩니다. 일반적인 시나리오는 루트 로거에만 처리기를 연결하고, 전파가 나머지를 처리하도록 하는 것입니다.

setLevel(level)

이 로거의 수준 경계를 level 로 설정합니다. level 보다 덜 심각한 로깅 메시지는 무시됩니다; 심각도 level 이상의 로깅 메시지는, 처리기 수준이 level 보다 높은 심각도 수준으로 설정되지 않는 한, 이 로거에 연결된 처리기가 출력합니다.

로거가 만들어질 때, 수준은 NOTSET (로거가 루트 로거 일 때는 모든 메시지를 처리하게 하고, 로거가 루트 로거가 아니면 모든 메시지를 부모에게 위임하도록 합니다) 으로 설정됩니다. 루트 로거는 수준 WARNING으로 만들어짐에 유의하세요.

‘부모에게 위임’이라는 말은, 로거 수준이 NOTSET 인 경우, NOTSET 이외의 수준을 갖는 조상이 발견되거나 루트에 도달할 때까지 조상 로거 체인을 탐색함을 의미합니다.

NOTSET 이외의 수준을 갖는 조상이 발견되면, 그 조상의 수준을 조상 검색이 시작된 로거의 유효 수준으로 간주하여, 로깅 이벤트를 처리할지를 결정하는 데 사용됩니다.

루트에 도달하면, 그리고 루트가 NOTSET 수준을 갖고 있으면, 모든 메시지가 처리됩니다. 그렇지 않으면 루트 수준이 유효 수준으로 사용됩니다.

수준의 목록은 로깅 수준를 보세요.

버전 3.2에서 변경: level 매개 변수는 이제 INFO와 같은 정수 상수 대신 ‘INFO’와 같은 수준의 문자열 표현을 허용합니다. 그러나 수준은 내부적으로 정수로 저장되며, getEffectiveLevel() 및 isEnabledFor()와 같은 메서드는 정수를 반환하거나 정수가 전달되기를 기대합니다.

isEnabledFor(level)

Indicates if a message of severity level would be processed by this logger. This method checks first the module-level level set by logging.disable(level) and then the logger’s effective level as determined by getEffectiveLevel().

getEffectiveLevel()

이 로거의 유효 수준을 알려줍니다. setLevel() 을 사용하여 NOTSET 이외의 값이 설정되면, 그 값이 반환됩니다. 그렇지 않으면, NOTSET 이외의 값이 발견될 때까지 루트를 향해 계층 구조를 탐색하고, 그 값이 반환됩니다. 반환되는 값은 정수이며, 일반적으로 logging.DEBUG, logging.INFO 등 중 하나입니다.

getChild(suffix)

접미사에 의해 결정되는, 이 로거의 자손 로거를 반환합니다. 그러므로, logging.getLogger('abc').getChild('def.ghi') 는 logging.getLogger('abc.def.ghi') 와 같은 로거를 반환합니다. 이것은 편의 메서드인데, 부모 로거가 리터럴 문자열이 아닌 이름(가령 __name__)을 사용하여 명명될 때 유용합니다.

버전 3.2에 추가.

debug(msg, *args, **kwargs)

이 로거에 수준 DEBUG 메시지를 로그 합니다. msg 는 메시지 포맷 문자열이고, args 는 문자열 포매팅 연산자를 사용하여 msg 에 병합되는 인자입니다. (이는 포맷 문자열에 키워드를 사용하고, 인자로 하나의 딕셔너리를 전달할 수 있음을 의미합니다.)

kwargs 에서 검사되는 세 개의 키워드 인자가 있습니다: exc_info, stack_info 및 extra.

exc_info 가 거짓으로 평가되지 않으면, 로깅 메시지에 예외 정보가 추가됩니다. 예외 튜플 (sys.exc_info() 에 의해 반환되는 형식) 또는 예외 인스턴스가 제공되면 사용됩니다; 그렇지 않으면 예외 정보를 얻기 위해 sys.exc_info() 를 호출합니다.

두 번째 선택적 키워드 인자는 stack_info 이며, 기본값은 False 입니다. 참이면, 실제 로깅 호출을 포함하는 스택 정보가 로깅 메시지에 추가됩니다. 이것은 exc_info 를 지정할 때 표시되는 것과 같은 스택 정보가 아닙니다: 전자(stack_info)는 스택의 맨 아래에서 현재 스레드의 로깅 호출까지의 스택 프레임이며, 후자(exc_info)는 예외가 일어난 후에 예외 처리기를 찾으면서 되감은 스택 프레임에 대한 정보입니다.

exc_info 와는 독립적으로 stack_info 를 지정할 수 있습니다. 예를 들어 예외가 발생하지 않은 경우에도 코드의 특정 지점에 어떻게 도달했는지 보여줄 수 있습니다. 스택 프레임은 다음과 같은 헤더 행 다음에 인쇄됩니다:

Stack (most recent call last):

예외 프레임을 표시할 때 사용되는 Traceback (most recent call last): 을 흉내 내고 있습니다.

세 번째 키워드 인자는 extra 로, 로깅 이벤트용으로 만들어진 LogRecord의 __dict__ 를 사용자 정의 어트리뷰트로 채우는 데 사용되는 딕셔너리를 전달할 수 있습니다. 이러한 사용자 정의 어트리뷰트는 원하는 대로 사용할 수 있습니다. 예를 들어, 로그 메시지에 포함할 수 있습니다. 예를 들면:

FORMAT = '%(asctime)-15s %(clientip)s %(user)-8s %(message)s'
logging.basicConfig(format=FORMAT)
d = {'clientip': '192.168.0.1', 'user': 'fbloggs'}
logger = logging.getLogger('tcpserver')
logger.warning('Protocol problem: %s', 'connection reset', extra=d)

는 이렇게 인쇄할 것입니다

2006-02-08 22:20:02,165 192.168.0.1 fbloggs  Protocol problem: connection reset

extra 에 전달된 딕셔너리의 키가, 로깅 시스템에서 사용하는 키와 충돌해서는 안 됩니다. (어떤 키가 로깅 시스템에 의해 사용되는지에 대한 더 많은 정보는 Formatter 문서를 보십시오.)

로그 된 메시지에서 이러한 어트리뷰트를 사용하려면 몇 가지 주의를 기울여야 합니다. 위의 예에서, 예를 들어, Formatter 에 설정한 포맷 문자열은 LogRecord의 어트리뷰트 딕셔너리에 ‘clientip’ 과 ‘user’ 가 있을 것으로 기대하고 있습니다. 이것들이 없는 경우 문자열 포매팅 예외가 발생하기 때문에 메시지가 기록되지 않습니다. 따라서 이 경우, 항상 이 키를 포함하는 extra 딕셔너리를 전달해야 합니다.

성가신 일입니다만, 이 기능은 여러 문맥에서 같은 코드가 실행되고 관심 있는 조건들(가령 원격 클라이언트 IP 주소와 인증된 사용자 이름)이 문맥에 따라 발생하는 다중 스레드 서버와 같은 특수한 상황을 위한 것입니다. 이런 상황에서는, 특수한 Formatter 가 특정한 Handler와 함께 사용될 가능성이 큽니다.

버전 3.2에 추가: stack_info 매개 변수가 추가되었습니다.

버전 3.5에서 변경: exc_info 매개 변수는 이제 예외 인스턴스를 받아들입니다.

info(msg, *args, **kwargs)

이 로거에 수준 INFO 메시지를 로그 합니다. 인자는 debug()처럼 해석됩니다.

warning(msg, *args, **kwargs)

이 로거에 수준 WARNING 메시지를 로그 합니다. 인자는 debug()처럼 해석됩니다.

참고

기능적으로 warning 와 같은, 구식의 warn 메서드가 있습니다. warn 은 폐지되었으므로 사용하지 마십시오 - 대신 warning 을 사용하십시오.

error(msg, *args, **kwargs)

이 로거에 수준 ERROR 메시지를 로그 합니다. 인자는 debug()처럼 해석됩니다.

critical(msg, *args, **kwargs)

이 로거에 수준 CRITICAL 메시지를 로그 합니다. 인자는 debug()처럼 해석됩니다.

log(level, msg, *args, **kwargs)

Logs a message with integer level level on this logger. The other arguments are interpreted as for debug().

exception(msg, *args, **kwargs)

이 로거에 수준 ERROR 메시지를 로그 합니다. 인자는 debug()처럼 해석됩니다. 예외 정보가 로깅 메시지에 추가됩니다. 이 메서드는 예외 처리기에서만 호출해야 합니다.

addFilter(filter)

지정된 필터 filter 를 이 로거에 추가합니다.

removeFilter(filter)

이 로거에서 지정된 필터 filter 를 제거합니다.

filter(record)

Apply this logger’s filters to the record and return True if the record is to be processed. The filters are consulted in turn, until one of them returns a false value. If none of them return a false value, the record will be processed (passed to handlers). If one returns a false value, no further processing of the record occurs.

addHandler(hdlr)

지정된 처리기 hdlr 를 이 로거에 추가합니다.

removeHandler(hdlr)

이 로거에서 지정된 처리기 hdlr 을 제거합니다.

findCaller(stack_info=False)

호출자의 소스 파일 이름과 행 번호를 찾습니다. 파일 이름, 행 번호, 함수 이름 및 스택 정보를 4-요소 튜플로 반환합니다. 스택 정보는 stack_info 가 True 가 아니면 None 으로 반환됩니다.

handle(record)

이 로거와 그 조상(거짓 값의 propagate 가 발견될 때까지)과 연관된 모든 처리기에 레코드를 전달하여 레코드를 처리합니다. 이 메서드는 로컬에서 만든 레코드뿐만 아니라 소켓에서 받아서 언피클된 레코드를 처리하는 데 사용됩니다. filter() 를 사용하여 로거 수준 필터링을 적용합니다.

makeRecord(name, level, fn, lno, msg, args, exc_info, func=None, extra=None, sinfo=None)

이 메서드는 특수한 LogRecord 인스턴스를 만들기 위해 서브 클래스에서 재정의할 수 있는 팩토리 메서드입니다.

hasHandlers()

이 로거에 처리기가 구성되어 있는지 확인합니다. 이 로거의 처리기와 로거 계층의 부모를 찾습니다. 처리기가 발견되면 True 를 반환하고, 그렇지 않으면 False 를 반환합니다. 이 메서드는 ‘propagate’ 어트리뷰트가 거짓으로 설정된 로거가 발견될 때 계층 구조 검색을 중지합니다 - 그 로거가 처리기가 있는지 검사하는 마지막 로거가 됩니다.

버전 3.2에 추가.

버전 3.7에서 변경: 이제 로거는 피클 되고 언피클 될 수 있습니다.

로깅 수준

로깅 수준의 숫자 값은 다음 표에 나와 있습니다. 여러분 자신의 수준을 정의하고, 미리 정의된 수준과 상대적인 특정 값을 갖도록 하려는 경우 필요합니다. 같은 숫자 값을 가진 수준을 정의하면 미리 정의된 값을 덮어씁니다; 미리 정의된 이름이 유실됩니다.

수준

숫자 값

CRITICAL

50

ERROR

40

WARNING

30

INFO

20

DEBUG

10

NOTSET

0

Handler 객체

처리기에는 다음과 같은 어트리뷰트와 메서드가 있습니다. Handler 는 절대로 직접 인스턴스로 만들어지지 않음에 주의하세요; 이 클래스는 더욱 유용한 서브 클래스의 베이스가 됩니다. 그러나, 서브 클래스의 __init__() 메서드는 Handler.__init__() 을 호출해야 합니다.

class logging.Handler

__init__(level=NOTSET)

수준을 설정하고, 필터 목록을 빈 리스트로 설정하고, I/O 메커니즘에 대한 액세스를 직렬화하기 위해 (createLock() 을 사용하여) 록을 생성함으로써 Handler 인스턴스를 초기화합니다.

createLock()

스레드 안전하지 않은 하부 I/O 기능에 대한 액세스를 직렬화하는 데 사용할 수 있는 스레드 록을 초기화합니다.

acquire()

createLock() 로 생성된 스레드 록을 확보합니다.

release()

acquire()로 확보한 스레드 록을 반납합니다.

setLevel(level)

이 처리기의 수준 경계를 level 로 설정합니다. level 보다 덜 심각한 로깅 메시지는 무시됩니다. 처리기가 만들어질 때, 수준은 NOTSET (모든 메시지가 처리되게 합니다) 으로 설정됩니다.

수준의 목록은 로깅 수준를 보세요.

버전 3.2에서 변경: level 매개 변수는 이제 INFO와 같은 정수 상수 대신 ‘INFO’와 같은 수준 문자열 표현을 허용합니다.

setFormatter(fmt)

이 처리기의 Formatter를 fmt 로 설정합니다.

addFilter(filter)

지정된 필터 filter 를 이 처리기에 추가합니다.

removeFilter(filter)

이 처리기에서 지정된 필터 filter 를 제거합니다.

filter(record)

Apply this handler’s filters to the record and return True if the record is to be processed. The filters are consulted in turn, until one of them returns a false value. If none of them return a false value, the record will be emitted. If one returns a false value, the handler will not emit the record.

flush()

모든 로그 출력이 플러시 되었음을 확실히 합니다. 이 버전은 아무것도 하지 않으며, 서브 클래스에 의해 구현됩니다.

close()

처리기가 사용하는 자원을 정리합니다. 이 버전은 출력하지 않지만, shutdown() 이 호출 될 때 닫히는 처리기의 내부 목록에서 처리기를 제거합니다. 서브 클래스는 이것이 재정의된 close() 메서드에서 이 메서드를 호출해야 합니다.

handle(record)

처리기에 추가된 필터에 따라 조건부로, 지정된 로깅 레코드를 출력합니다. 레코드의 실제 출력을 I/O 스레드 록의 확보/해제로 둘러쌉니다.

handleError(record)

이 메서드는 emit() 호출 중에 예외가 발생할 때 처리기에서 호출됩니다. 모듈 수준 어트리뷰트 raiseExceptions 가 False 인 경우 예외는 조용히 무시됩니다. 이 동작은 대부분 로깅 시스템에서 원하는 방식입니다 - 대부분 사용자는 로깅 시스템 자체의 에러에 관심이 없고, 응용 프로그램 에러에 더 관심이 있습니다. 그러나 원하는 경우, 사용자 정의 처리기로 바꿀 수 있습니다. 지정된 레코드는 예외가 발생할 때 처리되고 있던 레코드입니다. (raiseExceptions 의 기본값은 True 입니다. 개발 중에 더 유용합니다).

format(record)

레코드를 포맷합니다 - 포매터가 설정된 경우 사용합니다. 그렇지 않으면 모듈의 기본 포매터를 사용합니다.

emit(record)

지정된 로깅 레코드를 실제로 로그 하는 데 필요한 작업을 수행합니다. 이 버전은 서브 클래스에 의해 구현될 것으로 보고 NotImplementedError를 발생시킵니다.

표준으로 포함된 처리기 목록은 logging.handlers 를 참조하십시오.

Formatter 객체

Formatter 객체는 다음과 같은 어트리뷰트와 메서드를 가지고 있습니다. 이들은 LogRecord 를 (보통) 사람이나 외부 시스템이 해석 할 수 있는 문자열로 변환하는 역할을 합니다. 베이스 Formatter 는 포매팅 문자열을 지정할 수 있게 합니다. 아무것도 지정하지 않으면, '%(message)s' 이 기본값으로 사용되는데, 단지 로깅 호출에서 제공된 메시지만 포함됩니다. 포맷된 출력에 추가 정보(가령 타임스탬프)를 넣으려면 계속 읽으십시오.

포매터는 LogRecord 어트리뷰트에 포함된 정보를 사용하는 포맷 문자열로 초기화될 수 있습니다 - 위에서 언급 한 기본값은 사용자의 메시지와 인자가 LogRecord 의 message 어트리뷰트로 미리 포맷된다는 사실을 활용합니다. 이 포맷 문자열은 표준 파이썬 %-스타일 매핑 키를 포함합니다. 문자열 포매팅에 대해서 더 많은 정보가 필요하면 printf 스타일 문자열 포매팅를 보세요.

LogRecord 에 있는 유용한 매핑 키는 LogRecord 어트리뷰트 섹션에 있습니다.

class logging.Formatter(fmt=None, datefmt=None, style='%')

Formatter 클래스의 새로운 인스턴스를 반환합니다. 인스턴스는 전체 메시지의 포맷 문자열과 메시지의 날짜/시간 부분에 대한 포맷 문자열로 초기화됩니다. fmt 가 지정되지 않으면 '%(message)s' 가 사용됩니다. datefmt 가 지정되지 않으면 formatTime() 설명서에 기술된 포맷이 사용됩니다.

style 매개 변수는 ‘%’, ‘{’ 또는 ‘$’ 중 하나일 수 있으며, 포맷 문자열이 데이터와 병합되는 방식을 결정합니다: %-포매팅, str.format() 또는 string.Template 중 하나를 사용합니다. 로그 메시지에 {- 와 $-포매팅을 사용하는 방법에 대한 자세한 내용은 응용 프로그램 전체에서 특정 포맷 스타일 사용하기을 참조하십시오.

버전 3.2에서 변경: style 매개 변수가 추가되었습니다.

format(record)

레코드의 어트리뷰트 딕셔너리가 문자열 포매팅 연산의 피연산자로 사용됩니다. 결과 문자열을 반환합니다. 딕셔너리를 포맷하기 전에 몇 가지 준비 단계가 수행됩니다. 레코드의 message 어트리뷰트를 msg % args 를 사용하여 계산합니다. 포매팅 문자열에 '(asctime)' 이 들어 있으면, formatTime() 이 호출되어 이벤트 시간을 포매팅합니다. 예외 정보가 있는 경우, formatException() 을 사용하여 포매팅 되고 메시지에 덧붙입니다. 포맷된 예외 정보는 exc_text 어트리뷰트에 캐시 됩니다. 예외 정보를 피클 해서 네트워크를 통해 전송할 수 있으므로 유용합니다만, 예외 정보의 포매팅을 사용자 정의하는 Formatter 서브 클래스가 두 개 이상 있는 경우 주의해야 합니다. 이 경우, 한 포매터가 포매팅을 완료한 후 캐시 된 값을 지워서 그 이벤트를 처리하는 다음 포매터가 캐시 된 값을 사용하지 않고 새로 계산할 수 있도록 해야 합니다.

스택 정보가 있는 경우, 예외 정보 뒤에 덧붙입니다. 필요할 경우 formatStack() 을 사용하여 변환합니다.

formatTime(record, datefmt=None)

이 메서드는 포맷된 시간을 사용하려는 포매터에 의해 format()에서 호출되어야 합니다. 이 메서드는 특정 요구 사항을 제공하기 위해 포매터에서 재정의될 수 있지만, 기본 동작은 다음과 같습니다: datefmt(문자열)이 지정된 경우, time.strftime() 를 사용하여 레코드 생성 시간을 포매팅합니다. 그렇지 않으면 ‘%Y-%m-%d %H:%M:%S,uuu’ 포맷이 사용됩니다. 여기서 uuu 부분은 밀리 초 값이고, 다른 문자들은 time.strftime() 설명서를 따릅니다. 이 포맷의 표현된 시간의 예는 2003-01-23 00:29:50,411 입니다. 결과 문자열이 반환됩니다.

이 함수는 사용자가 구성할 수 있는 함수를 사용하여 생성 시간을 튜플로 변환합니다. 기본적으로 time.localtime() 이 사용됩니다; 특정 포매터 인스턴스에서 이를 변경하려면, converter 어트리뷰트를 time.localtime() 또는 time.gmtime() 과 같은 서명을 가진 함수로 설정하십시오. 모든 포매터를 변경하려면, 예를 들어 모든 로깅 시간을 GMT로 표시하려면, Formatter 클래스의 converter 어트리뷰트를 설정하십시오.

버전 3.3에서 변경: 예전에는, 기본 포맷이 다음과 같이 하드 코딩되었습니다: 2010-09-06 22:38:15,292. 쉼표 앞에 있는 부분은 strptime 포맷 문자열('%Y-%m-%d %H:%M:%S')이며, 쉼표 뒤의 부분은 밀리 초 값입니다. strptime에 밀리 초 포맷 표시자가 없으므로, 밀리 초 값은 다른 포맷 문자열 '%s,%03d' 을 사용하여 추가됩니다 — 이 두 포맷 문자열 모두 이 메서드에 하드 코드 되었습니다. 이 변경으로, 이 문자열들은 클래스 수준 어트리뷰트로 정의되었고, 원하는 경우 인스턴스 수준에서 재정의할 수 있습니다. 어트리뷰트 이름은 default_time_format(strptime 포맷 문자열)과 default_msec_format(밀리 초 값 추가용)입니다.

formatException(exc_info)

지정된 예외 정보(sys.exc_info() 에 의해 반환되는 표준 예외 튜플)를 문자열로 포맷합니다. 이 기본 구현은 traceback.print_exception()을 사용합니다. 결과 문자열이 반환됩니다.

formatStack(stack_info)

지정된 스택 정보(traceback.print_stack() 에 의해 반환된 문자열이지만 마지막 줄 바꿈이 제거됩니다)을 문자열로 포맷합니다. 이 기본 구현은 입력 값을 그대로 반환합니다.

Filter 객체

Filter 는 수준을 통해 제공되는 것보다 더 정교한 필터링을 위해 Handler 와 Logger 에 의해 사용될 수 있습니다. 베이스 필터 클래스는 로거 계층 구조의 특정 지점 아래에 있는 이벤트만 허용합니다. 예를 들어 ‘A.B’로 초기화된 필터는, 로거 ‘A.B’, ‘A.B.C’, ‘A.B.C.D’, ‘A.B.D’ 등이 로그 한 이벤트를 허용하지만, ‘A.BB’, ‘B.A.B’ 등은 허용하지 않습니다. 빈 문자열을 사용하면 모든 이벤트를 통과시킵니다.

class logging.Filter(name='')

Filter 클래스의 인스턴스를 반환합니다. name 을 제공하면, 필터를 통과하도록 허용할 로거(그 자식들도 포함합니다)의 이름을 지정합니다. name 이 빈 문자열이면, 모든 이벤트를 허용합니다.

filter(record)

지정된 레코드가 로그 됩니까? 아니라면 0을 반환하고, 그렇다면 0이 아닌 값을 반환합니다. 적절하다고 판단되면, 이 메서드는 해당 레코드를 수정할 수 있습니다.

처리기에 첨부된 필터는 이벤트를 처리기가 출력하기 전에 호출되는 반면, 로거에 첨부된 필터는 이벤트가 로깅될 때마다 (debug(), info() 등) 처리기로 이벤트를 보내기 전에 호출됩니다. 이는 자손 로거가 만든 이벤트들은, 같은 필터가 자손들에게도 적용되지 않는 한, 로거의 필터 설정으로 필터링 되지 않는다는 것을 뜻합니다.

실제로 Filter 의 서브 클래스를 만들 필요는 없습니다: 같은 의미가 있는 filter 메서드를 가진 인스턴스는 무엇이건 전달할 수 있습니다.

버전 3.2에서 변경: 특수한 Filter 클래스를 만들거나 filter 메서드를 가진 다른 클래스를 사용할 필요가 없습니다: 함수(또는 다른 콜러블)를 필터로 사용할 수 있습니다. 필터링 로직은 필터 객체가 filter 어트리뷰트를 가졌는지 확인합니다: 만약 있다면 Filter 라고 가정하고 filter() 메서드를 호출합니다. 그렇지 않으면 콜러블이라고 가정하고 레코드를 단일 매개 변수로 호출합니다. 반환된 값은 filter() 가 반환하는 값과 같은 의미를 지녀야 합니다.

필터는 수준보다 정교한 기준에 따라 레코드를 필터링하는 데 주로 사용되지만, 필터가 첨부되는 처리기나 로거에서 처리되는 모든 레코드를 볼 수 있습니다: 이 특성은, 특정 로거나 처리기가 얼마나 많은 레코드를 처리하는지 센다거나, 처리 중인 LogRecord에 어트리뷰트를 추가, 변경, 삭제하려고 할 때 유용합니다. 당연히, LogRecord를 변경하는 것은 주의를 필요로 하는 일이지만, 로그에 문맥 정보를 주입하는 것을 허용합니다 (문맥 정보 전달에 필터 사용하기를 보세요).

LogRecord 객체

LogRecord 인스턴스는 뭔가 로깅 될 때마다 Logger 에 의해 자동으로 생성되며, makeLogRecord()를 통해 수동으로 생성될 수 있습니다 (예를 들어, 네트워크에서 수신된 피클 된 이벤트의 경우).

class logging.LogRecord(name, level, pathname, lineno, msg, args, exc_info, func=None, sinfo=None)

로그 되는 이벤트와 관련된 모든 정보를 담고 있습니다.

주요 정보는 msg와 args 로 전달되며, msg % args 를 사용하여 병합되어 레코드의 message 필드를 만듭니다.

매개변수

name – 이 LogRecord가 나타내는 이벤트를 로그 하는데 사용된 로거의 이름. 이 이름은 다른 (조상) 로거에 첨부된 처리기가 출력하더라도 항상 이 값을 갖습니다.

level – 로깅 이벤트의 숫자 수준 (DEBUG, INFO 등). 이 값은 LogRecord의 두 어트리뷰트로 변환됩니다: 숫자 값을 위한 levelno 와 해당 수준 이름을 위한 levelname.

pathname – 로깅 호출이 발생한 소스 파일의 전체 경로명.

lineno – 로깅 호출이 발생한 소스 파일의 행 번호.

msg – 이벤트 설명 메시지. 변수 데이터를 위한 자리 표시자가 있는 포맷 문자열일 수 있습니다.

args – 이벤트 설명을 얻기 위해 msg 인자에 병합할 변수 데이터.

exc_info – 현재의 예외 정보를 가지는 예외 튜플. 예외 정보가 없는 경우는 None 입니다.

func – 로깅 호출을 호출한 함수 또는 메서드의 이름.

sinfo – 현재 스레드에서 스택의 바닥부터 로깅 호출까지의 스택 정보를 나타내는 텍스트 문자열.

getMessage()

사용자가 제공 한 인자를 메시지와 병합한 후, 이 LogRecord 인스턴스에 대한 메시지를 반환합니다. 로깅 호출에 제공된 사용자 제공 메시지 인자가 문자열이 아닌 경우, str() 이 호출되어 문자열로 변환됩니다. 이렇게 해서 사용자 정의 클래스를 메시지로 사용할 수 있도록 하는데, 그 클래스의 __str__ 메서드는 사용할 실제 포맷 문자열을 반환 할 수 있습니다.

버전 3.2에서 변경: 레코드를 생성하는 데 사용되는 팩토리를 제공함으로써, LogRecord 의 생성을 더 구성할 수 있게 만들었습니다. 팩토리는 getLogRecordFactory()와 setLogRecordFactory() (팩토리의 서명은 이곳을 참조하십시오) 를 사용하여 설정할 수 있습니다.

이 기능은 LogRecord 생성 시에 여러분 자신의 값을 주입하는데 사용할 수 있습니다. 다음과 같은 패턴을 사용할 수 있습니다:

old_factory = logging.getLogRecordFactory()

def record_factory(*args, **kwargs):
    record = old_factory(*args, **kwargs)
    record.custom_attribute = 0xdecafbad
    return record

logging.setLogRecordFactory(record_factory)

이 패턴을 사용하면 여러 팩토리를 체인으로 묶을 수 있으며, 서로의 어트리뷰트를 덮어쓰거나 위에 나열된 표준 어트리뷰트를 실수로 덮어쓰지 않는 한 놀랄만한 일이 일어나지는 않아야 합니다.

LogRecord 어트리뷰트

LogRecord에는 많은 어트리뷰트가 있으며, 대부분 어트리뷰트는 생성자의 매개 변수에서 옵니다. (LogRecord 생성자 매개 변수와 LogRecord 어트리뷰트의 이름이 항상 정확하게 일치하는 것은 아닙니다.) 이러한 어트리뷰트를 사용하여 레코드의 데이터를 포맷 문자열로 병합 할 수 있습니다. 다음 표는 어트리뷰트 이름, 의미와 해당 자리 표시자를 %-스타일 포맷 문자열로 (알파벳 순서로) 나열합니다.

{}-포매팅(str.format())을 사용한다면, {attrname} 을 포맷 문자열의 자리 표시자로 사용할 수 있습니다. $-포매팅(string.Template)을 사용하고 있다면, ${attrname} 형식을 사용하십시오. 두 경우 모두, 물론, attrname 을 사용하려는 실제 어트리뷰트 이름으로 대체하십시오.

{}-포매팅의 경우, 어트리뷰트 이름 다음에 콜론(:)으로 구분하여 포매팅 플래그를 지정할 수 있습니다. 예를 들어, {msecs:03d} 자리 표시자는 밀리 초 값 4 를 004 로 포맷합니다. 사용할 수 있는 옵션에 대한 자세한 내용은 str.format() 설명서를 참조하십시오.

어트리뷰트 이름

포맷

설명

args

직접 포맷할 필요는 없습니다.

message 를 생성하기 위해 msg 에 병합되는 인자의 튜플. 또는 (인자가 하나뿐이고 딕셔너리일 때) 병합을 위해 값이 사용되는 딕셔너리.

asctime

%(asctime)s

사람이 읽을 수 있는, LogRecord 가 생성된 시간. 기본적으로 ‘2003-07-08 16:49:45,896’ 형식입니다 (쉼표 뒤의 숫자는 밀리 초 부분입니다).

created

%(created)f

LogRecord 가 생성된 시간 (time.time() 이 반환하는 시간).

exc_info

직접 포맷할 필요는 없습니다.

예외 튜플 (sys.exc_info 에서 제공) 또는, 예외가 발생하지 않았다면, None.

filename

%(filename)s

pathname 의 파일명 부분.

funcName

%(funcName)s

로깅 호출을 포함하는 함수의 이름.

levelname

%(levelname)s

메시지의 텍스트 로깅 수준 ('DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL').

levelno

%(levelno)s

메시지의 숫자 로깅 수준 (DEBUG, INFO, WARNING, ERROR, CRITICAL).

lineno

%(lineno)d

로깅 호출이 일어난 소스 행 번호 (사용 가능한 경우).

message

%(message)s

로그 된 메시지. msg % args 로 계산됩니다. Formatter.format() 이 호출 될 때 설정됩니다.

module

%(module)s

모듈 (filename 의 이름 부분).

msecs

%(msecs)d

LogRecord 가 생성된 시간의 밀리 초 부분.

msg

직접 포맷할 필요는 없습니다.

원래 로깅 호출에서 전달된 포맷 문자열. args 와 병합하여 message 를 만듭니다. 또는 임의의 객체 (임의의 객체를 메시지로 사용하기 를 보세요).

name

%(name)s

로깅 호출에 사용된 로거의 이름.

pathname

%(pathname)s

로깅 호출이 일어난 소스 파일의 전체 경로명 (사용 가능한 경우).

process

%(process)d

프로세스 ID (사용 가능한 경우).

processName

%(processName)s

프로세스 이름 (사용 가능한 경우).

relativeCreated

%(relativeCreated)d

logging 모듈이 로드된 시간을 기준으로 LogRecord가 생성된 시간 (밀리 초).

stack_info

직접 포맷할 필요는 없습니다.

현재 스레드의 스택 바닥에서 이 레코드를 생성한 로깅 호출의 스택 프레임까지의 스택 프레임 정보 (사용 가능한 경우).

thread

%(thread)d

스레드 ID (사용 가능한 경우).

threadName

%(threadName)s

스레드 이름 (사용 가능한 경우).

버전 3.1에서 변경: processName 이 추가되었습니다.

LoggerAdapter 객체

LoggerAdapter 인스턴스는 문맥 정보를 로깅 호출에 편리하게 전달하는 데 사용됩니다. 사용 예는, 로그 출력에 문맥 정보 추가 섹션을 참조하십시오.

class logging.LoggerAdapter(logger, extra)

하부 Logger 인스턴스와 딕셔너리 류 객체로 초기화된 LoggerAdapter 의 인스턴스를 반환합니다.

process(msg, kwargs)

문맥 정보를 삽입하기 위해 로깅 호출에 전달된 메시지 와 키워드 인자를 수정합니다. 이 구현은 생성자에 extra 로 전달된 객체를 가져와서 ‘extra’ 키를 사용하여 kwargs 에 추가합니다. 반환 값은 전달된 인자의 (수정된) 버전을 담은 (msg, kwargs) 튜플입니다.

위의 것에 더해, LoggerAdapter 는 다음과 같은 Logger 의 메서드를 지원합니다: debug(), info(), warning(), error(), exception(), critical(), log(), isEnabledFor(), getEffectiveLevel(), setLevel(), hasHandlers(). 이 메서드들은 Logger 에 있는 것과 똑같은 서명을 가지므로, 두 형의 인스턴스를 바꿔쓸 수 있습니다.

버전 3.2에서 변경: isEnabledFor(), getEffectiveLevel(), setLevel() 그리고 hasHandlers() 메서드가 LoggerAdapter 에 추가되었습니다. 이 메서드는 하부 로거로 위임합니다.

스레드 안전성

로깅 모듈은 클라이언트가 특별한 주의를 기울이지 않아도 스레드 안전하도록 만들어졌습니다. 이렇게 하려고 threading 록을 사용합니다; 모듈의 공유 데이터에 대한 액세스를 직렬화하는 록이 하나 있고, 각 처리기 또한 하부 I/O에 대한 액세스를 직렬화하는 록을 만듭니다.

signal 모듈을 사용하여 비동기 시그널 처리기를 구현한다면, 그 처리기 내에서는 logging을 사용할 수 없을 수도 있습니다. 이는 threading 모듈의 록 구현이 언제나 재진입할 수 있지는 않아서 그러한 시그널 처리기에서 호출할 수 없기 때문입니다.

모듈 수준 함수

위에서 설명한 클래스 외에도 많은 모듈 수준 함수가 있습니다.

logging.getLogger(name=None)

지정된 이름(name)의 로거를 돌려주거나, name이 None 인 경우, 계층의 루트 로거인 로거를 돌려줍니다. 지정된 경우, name은 일반적으로 ‘a’, ‘a.b’ 또는 ‘a.b.c.d’ 와 같이 점으로 구분된 계층적 이름입니다. 이 이름의 선택은 전적으로 logging을 사용하는 개발자에게 달려 있습니다.

같은 이름으로 이 함수를 여러 번 호출하면 모두 같은 로거 인스턴스를 반환합니다. 이것은 응용 프로그램의 다른 부분 간에 로거 인스턴스를 전달할 필요가 없다는 것을 뜻합니다.

logging.getLoggerClass()

표준 Logger 클래스를 반환하거나, setLoggerClass() 에 전달된 마지막 클래스를 반환합니다. 이 함수는 새 클래스 정의 내에서 호출하여, 사용자 정의 Logger 클래스를 설치할 때 다른 코드가 이미 적용한 사용자 정의를 취소하지 않도록 할 수 있습니다. 예를 들면:

class MyLogger(logging.getLoggerClass()):
    # ... override behaviour here

logging.getLogRecordFactory()

LogRecord 를 생성하는 데 사용되는 콜러블을 반환합니다.

버전 3.2에 추가: 이 함수는 setLogRecordFactory()와 함께 제공되어, 개발자가 로깅 이벤트를 나타내는 LogRecord 가 만들어지는 방법을 더욱 잘 제어 할 수 있도록 합니다.

팩토리가 어떻게 호출되는지에 대한 더 자세한 정보는 setLogRecordFactory()를 보세요.

logging.debug(msg, *args, **kwargs)

루트 로거에 수준 DEBUG 메시지를 로그 합니다. msg 는 메시지 포맷 문자열이고, args 는 문자열 포매팅 연산자를 사용하여 msg 에 병합되는 인자입니다. (이는 포맷 문자열에 키워드를 사용하고, 인자로 하나의 딕셔너리를 전달할 수 있음을 의미합니다.)

kwargs 에서 검사되는 세 개의 키워드 인자가 있습니다: exc_info 가 거짓으로 평가되지 않으면, 로깅 메시지에 예외 정보가 추가됩니다. 예외 튜플(sys.exc_info() 에 의해 반환되는 형식)이나 예외 인스턴스가 제공되면 사용됩니다; 그렇지 않으면 예외 정보를 얻기 위해 sys.exc_info() 를 호출합니다.

두 번째 선택적 키워드 인자는 stack_info 이며, 기본값은 False 입니다. 참이면, 실제 로깅 호출을 포함하는 스택 정보가 로깅 메시지에 추가됩니다. 이것은 exc_info 를 지정할 때 표시되는 것과 같은 스택 정보가 아닙니다: 전자(stack_info)는 스택의 맨 아래에서 현재 스레드의 로깅 호출까지의 스택 프레임이며, 후자(exc_info)는 예외가 일어난 후에 예외 처리기를 찾으면서 되감은 스택 프레임에 대한 정보입니다.

exc_info 와는 독립적으로 stack_info 를 지정할 수 있습니다. 예를 들어 예외가 발생하지 않은 경우에도 코드의 특정 지점에 어떻게 도달했는지 보여줄 수 있습니다. 스택 프레임은 다음과 같은 헤더 행 다음에 인쇄됩니다:

Stack (most recent call last):

예외 프레임을 표시할 때 사용되는 Traceback (most recent call last): 을 흉내 내고 있습니다.

세 번째 선택적 키워드 인자는 extra 로, 로깅 이벤트용으로 만들어진 LogRecord의 __dict__ 를 사용자 정의 어트리뷰트로 채우는 데 사용되는 딕셔너리를 전달할 수 있습니다. 이러한 사용자 정의 어트리뷰트는 원하는 대로 사용할 수 있습니다. 예를 들어, 로그 메시지에 포함할 수 있습니다. 예를 들면:

FORMAT = '%(asctime)-15s %(clientip)s %(user)-8s %(message)s'
logging.basicConfig(format=FORMAT)
d = {'clientip': '192.168.0.1', 'user': 'fbloggs'}
logging.warning('Protocol problem: %s', 'connection reset', extra=d)

는 이렇게 인쇄할 것입니다:

2006-02-08 22:20:02,165 192.168.0.1 fbloggs  Protocol problem: connection reset

extra 에 전달된 딕셔너리의 키가, 로깅 시스템에서 사용하는 키와 충돌해서는 안 됩니다. (어떤 키가 로깅 시스템에 의해 사용되는지에 대한 더 많은 정보는 Formatter 문서를 보십시오.)

로그 된 메시지에서 이러한 어트리뷰트를 사용하려면 몇 가지 주의를 기울여야 합니다. 위의 예에서, 예를 들어, Formatter 에 설정한 포맷 문자열은 LogRecord의 어트리뷰트 딕셔너리에 ‘clientip’ 과 ‘user’ 가 있을 것으로 기대하고 있습니다. 이것들이 없는 경우 문자열 포매팅 예외가 발생하기 때문에 메시지가 기록되지 않습니다. 따라서 이 경우, 항상 이 키를 포함하는 extra 딕셔너리를 전달해야 합니다.

성가신 일입니다만, 이 기능은 여러 문맥에서 같은 코드가 실행되고 관심 있는 조건들(가령 원격 클라이언트 IP 주소와 인증된 사용자 이름)이 문맥에 따라 발생하는 다중 스레드 서버와 같은 특수한 상황을 위한 것입니다. 이런 상황에서는, 특수한 Formatter 가 특정한 Handler와 함께 사용될 가능성이 큽니다.

버전 3.2에 추가: stack_info 매개 변수가 추가되었습니다.

logging.info(msg, *args, **kwargs)

루트 로거에 수준 INFO 메시지를 로그 합니다. 인자는 debug()처럼 해석됩니다.

logging.warning(msg, *args, **kwargs)

루트 로거에 수준 WARNING 메시지를 로그 합니다. 인자는 debug()처럼 해석됩니다.

참고

기능적으로 warning 와 같은, 구식의 warn 함수가 있습니다. warn 은 폐지되었으므로 사용하지 마십시오 - 대신 warning 을 사용하십시오.

logging.error(msg, *args, **kwargs)

루트 로거에 수준 ERROR 메시지를 로그 합니다. 인자는 debug()처럼 해석됩니다.

logging.critical(msg, *args, **kwargs)

루트 로거에 수준 CRITICAL 메시지를 로그 합니다. 인자는 debug()처럼 해석됩니다.

logging.exception(msg, *args, **kwargs)

루트 로거에 수준 ERROR 메시지를 로그 합니다. 인자는 debug()처럼 해석됩니다. 예외 정보가 로깅 메시지에 추가됩니다. 이 메서드는 예외 처리기에서만 호출해야 합니다.

logging.log(level, msg, *args, **kwargs)

루트 로거에 수준 level 의 메시지를 로그 합니다. 다른 인자는 debug()처럼 해석됩니다.

참고

위의 루트 로거에 위임하는 모듈 수준 편리 함수는 적어도 하나의 처리기를 사용할 수 있도록 basicConfig()를 호출합니다. 이 때문에, 스레드가 시작되기 전에 적어도 하나의 처리기가 루트 로거에 추가되지 않는 한, 2.7.1 및 3.2 이전의 파이썬 버전에서는 스레드에서 이 함수들을 사용하지 않아야 합니다. 이전 버전의 파이썬에서는, basicConfig() 의 스레드 안전성 결함으로 인해 (드물긴 하지만) 처리기가 루트 로거에 여러 번 추가될 수 있으며, 같은 이벤트가 여러 번 기록되는 것으로 이어질 수 있습니다.

logging.disable(level=CRITICAL)

Provides an overriding level level for all loggers which takes precedence over the logger’s own level. When the need arises to temporarily throttle logging output down across the whole application, this function can be useful. Its effect is to disable all logging calls of severity level and below, so that if you call it with a value of INFO, then all INFO and DEBUG events would be discarded, whereas those of severity WARNING and above would be processed according to the logger’s effective level. If logging.disable(logging.NOTSET) is called, it effectively removes this overriding level, so that logging output again depends on the effective levels of individual loggers.

Note that if you have defined any custom logging level higher than CRITICAL (this is not recommended), you won’t be able to rely on the default value for the level parameter, but will have to explicitly supply a suitable value.

버전 3.7에서 변경: The level parameter was defaulted to level CRITICAL. See Issue #28524 for more information about this change.

logging.addLevelName(level, levelName)

Associates level level with text levelName in an internal dictionary, which is used to map numeric levels to a textual representation, for example when a Formatter formats a message. This function can also be used to define your own levels. The only constraints are that all levels used must be registered using this function, levels should be positive integers and they should increase in increasing order of severity.

참고

자신만의 수준을 정의할 생각이라면 사용자 정의 수준 섹션을 보십시오.

logging.getLevelName(level)

Returns the textual representation of logging level level. If the level is one of the predefined levels CRITICAL, ERROR, WARNING, INFO or DEBUG then you get the corresponding string. If you have associated levels with names using addLevelName() then the name you have associated with level is returned. If a numeric value corresponding to one of the defined levels is passed in, the corresponding string representation is returned. Otherwise, the string ‘Level %s’ % level is returned.

참고

수준은 (로깅 로직에서 비교해야 하므로) 내부적으로 정수입니다. 이 함수는 장수 수준과 %(levelname)s 포맷 지정자(LogRecord 어트리뷰트를 보세요)로 포맷된 로그 출력에 표시된 이름 간의 변환에 사용됩니다.

버전 3.4에서 변경: 3.4 이전의 파이썬 버전에서, 이 함수로 텍스트 수준을 전달할 수 있고, 해당 수준의 숫자 값을 반환합니다. 이 문서로 만들어지지 않은 동작은 실수로 간주하여, 파이썬 3.4에서 제거되었습니다. 하지만 이전 버전과의 호환성을 유지하기 위해 3.4.2에서 복원되었습니다.

logging.makeLogRecord(attrdict)

어트리뷰트가 attrdict 로 정의된 새로운 LogRecord 인스턴스를 만들어서 반환합니다. 이 함수는 피클 된 LogRecord 어트리뷰트 딕셔너리를 소켓으로 보내고, 수신 단에서 LogRecord 인스턴스로 재구성할 때 유용합니다.

logging.basicConfig(**kwargs)

기본 Formatter로 StreamHandler 를 생성하고 루트 로거에 추가하여 로깅 시스템의 기본 구성을 수행합니다. 함수 debug(), info(), warning(), error() 그리고 critical()은 루트 로거에 처리기가 정의되어 있지 않으면 자동으로 basicConfig()를 호출합니다.

이 함수는 루트 로거에 이미 처리기가 구성되어있는 경우 아무 작업도 수행하지 않습니다.

참고

이 함수는 다른 스레드가 시작되기 전에 메인 스레드에서 호출되어야 합니다. 2.7.1과 3.2 이전의 파이썬 버전에서, 이 함수를 여러 스레드에서 호출하면, (드문 경우지만) 처리기가 두 번 이상 루트 로거에 추가되어, 로그에 메시지가 중복되는 것과 같은 예기치 않은 결과가 발생할 수 있습니다.

다음 키워드 인자가 지원됩니다.

포맷

설명

filename

StreamHandler 대신 지정된 파일명을 사용해 FileHandler를 만들도록 지정합니다.

filemode

filename 이 지정되었으면, 이 모드 로 파일을 엽니다. 기본값은 'a' 입니다.

format

처리기에 지정된 포맷 문자열을 사용합니다.

datefmt

time.strftime() 에서 허용하는 방식대로 지정된 날짜/시간 포맷을 사용합니다.

style

format 을 지정하면, 포맷 문자열에 이 스타일을 사용합니다. '%', '{', '$' 중 하나인데 각각 printf 스타일, str.format(), string.Template 에 대응됩니다. 기본값은 '%' 입니다.

level

루트 로거의 수준을 지정된 수준 으로 설정합니다.

stream

StreamHandler의 초기화에 지정된 스트림을 사용합니다. 이 인자는 filename 과 호환되지 않습니다 - 둘 다 있으면 ValueError 가 발생합니다.

handlers

지정된 경우, 루트 로거에 추가할 이미 만들어진 처리기의 이터러블이어야 합니다. 아직 포매터 세트가 없는 처리기에는 이 함수에서 만들어진 기본 포매터가 지정됩니다. 이 인자는 filename 또는 stream 과 호환되지 않습니다 - 둘 다 있으면 ValueError 가 발생합니다.

버전 3.2에서 변경: style 인자가 추가되었습니다.

버전 3.3에서 변경: handlers 인자가 추가되었습니다. 호환되지 않는 인자(예를 들어, handlers 를 stream 이나 filename 과 함께 쓰거나, stream 을 filename 과 함께 쓰는 경우)가 있는 상황을 파악하기 위한 검사가 추가되었습니다.

logging.shutdown()

로깅 시스템에 모든 처리기를 플러시하고 닫아서 순차적인 종료를 수행하도록 알립니다. 응용 프로그램 종료 시 호출되어야 하고, 이 호출 후에는 로깅 시스템을 더는 사용하지 않아야 합니다.

logging.setLoggerClass(klass)

Tells the logging system to use the class klass when instantiating a logger. The class should define __init__() such that only a name argument is required, and the __init__() should call Logger.__init__(). This function is typically called before any loggers are instantiated by applications which need to use custom logger behavior. After this call, as at any other time, do not instantiate loggers directly using the subclass: continue to use the logging.getLogger() API to get your loggers.

logging.setLogRecordFactory(factory)

LogRecord 를 만드는데 사용되는 콜러블을 설정합니다.

매개변수

factory – 로그 레코드의 인스턴스를 만드는데 사용되는 팩토리 콜러블.

버전 3.2에 추가: 이 함수는 getLogRecordFactory()와 함께 제공되어, 개발자가 로깅 이벤트를 나타내는 LogRecord 가 만들어지는 방법을 더욱 잘 제어 할 수 있도록 합니다.

팩토리의 서명은 다음과 같습니다:

factory(name, level, fn, lno, msg, args, exc_info, func=None, sinfo=None, **kwargs)

name

로거 이름.

level

로깅 수준 (숫자).

fn

로깅 호출이 이루어진 파일의 전체 경로명.

lno

로깅 호출이 이루어진 파일의 행 번호.

msg

로깅 메시지

args

로깅 메시지에 대한 인자.

exc_info

예외 튜플 또는 None.

func

로깅 호출을 호출한 함수 또는 메서드의 이름

sinfo

traceback.print_stack() 가 제공하는 것과 같은 스택 트레이스백. 호출 계층 구조를 보여줍니다.

kwargs

추가 키워드 인자.

모듈 수준 어트리뷰트

logging.lastResort

“최후 수단 처리기” 는 이 어트리뷰트를 통해 제공됩니다. 이것은 WARNING 수준으로 sys.stderr 에 쓰는 StreamHandler 이고, 로깅 구성이 없을 때 로깅 이벤트를 처리하는 데 사용됩니다. 최종 결과는 sys.stderr 에 메시지를 출력하기만 하는 것입니다. 이것이 예전의 “no handlers could be found for logger XYZ” 라는 에러 메시지를 대체합니다. 어떤 이유로 이전 동작이 필요하면 lastResort 를 None 으로 설정할 수 있습니다.

버전 3.2에 추가.

warnings 모듈과의 통합

captureWarnings() 함수는 logging을 warnings 모듈과 통합하는데 사용될 수 있습니다.

logging.captureWarnings(capture)

이 함수는 logging 이 경고를 캡처하는 것을 켜고 끄는 데 사용됩니다.

capture 가 True 면, warnings 모듈에 의해 발행된 경고는 로깅 시스템으로 리디렉션됩니다. 특히, 경고는 warnings.formatwarning() 을 사용하여 포맷되고, 결과 문자열을 'py.warnings' 라는 이름의 로거에 심각도 WARNING으로 로그 합니다.

capture 가 False 면, 로깅 시스템으로의 경고 리디렉션은 멈추고, 경고는 원래 목적지(즉, captureWarnings(True) 가 호출되기 전에 적용되던 곳)로 리디렉션됩니다.

더 보기

모듈 logging.config

logging 모듈용 구성 API.

모듈 logging.handlers

logging 모듈에 포함된 유용한 처리기.

PEP 282 [https://www.python.org/dev/peps/pep-0282] - 로깅 시스템

파이썬 표준 라이브러리에 포함하기 위해 이 기능을 설명한 제안.

원본 파이썬 로깅 패키지 [https://www.red-dove.com/python_logging.html]

logging 패키지의 원래 소스입니다. 이 사이트에서 제공되는 패키지 버전은 표준 라이브러리에 logging 패키지를 포함하지 않는 파이썬 1.5.2, 2.1.x 및 2.2.x에서 사용하기에 적합합니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

일반 운영 체제 서비스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

일반 운영 체제 서비스 »

|

logging.config — 로깅 구성

소스 코드: Lib/logging/config.py [https://github.com/python/cpython/tree/3.7/Lib/logging/config.py]

Important

이 페이지에는 레퍼런스 정보만 있습니다. 자습서는 다음을 참조하십시오

기초 자습서

고급 자습서

로깅 요리책

이 절에서는 logging 모듈을 구성하기 위한 API에 관해 설명합니다.

구성 함수

다음 함수는 logging 모듈을 구성합니다. logging.config 모듈에 있습니다. 사용은 선택 사항입니다 — 이 함수들을 사용하거나 (logging 자체에서 정의된) 주 API를 호출하고 logging이나 logging.handlers에서 선언된 처리기를 정의해서 logging 모듈을 구성할 수 있습니다.

logging.config.dictConfig(config)

딕셔너리로 로깅 구성을 받습니다. 이 딕셔너리의 내용은 아래의 구성 딕셔너리 스키마에 설명되어 있습니다.

구성 중에 에러를 만나면, 이 함수는 적절하게 설명하는 메시지와 함께 ValueError, TypeError, AttributeError 또는 ImportError를 발생시킵니다. 다음은 에러를 발생시킬 수 있는 (불완전한) 조건 목록입니다:

문자열이 아니거나 실제 로깅 수준과 일치하지 않는 문자열인 level.

불리언이 아닌 propagate 값.

해당 대상이 없는 id.

증분(incremental) 호출 중에 발견된 존재하지 않는 처리기 id.

잘못된 로거 이름.

결정할 수 없는 내부나 외부 객체.

구문 분석은 DictConfigurator 클래스에 의해 수행되며, 생성자로는 구성에 사용되는 딕셔너리가 전달되고, 객체는 configure() 메서드를 가집니다. logging.config 모듈에는 초기에 DictConfigurator로 설정된 콜러블 어트리뷰트 dictConfigClass가 있습니다. 여러분 자신의 적절한 구현으로 dictConfigClass의 값을 바꿀 수 있습니다.

dictConfig()는 dictConfigClass를 호출해서 지정된 딕셔너리를 전달한 다음, 반환된 객체의 configure() 메서드를 호출하여 구성을 적용합니다:

def dictConfig(config):
    dictConfigClass(config).configure()

예를 들어, DictConfigurator의 서브 클래스는 자체 __init__()에서 DictConfigurator.__init__()를 호출한 다음, 후속 configure() 호출에서 사용할 수 있는 사용자 정의 접두사를 설정할 수 있습니다. dictConfigClass는 이 새 서브 클래스에 연결되고, dictConfig()는 기본, 사용자 정의되지 않은 상태에서와 똑같이 호출될 수 있습니다.

버전 3.2에 추가.

logging.config.fileConfig(fname, defaults=None, disable_existing_loggers=True)

configparser-형식 파일에서 로깅 구성을 읽습니다. 파일 형식은 구성 파일 형식에 설명된 것과 같아야 합니다. 이 함수는 응용 프로그램에서 여러 번 호출 할 수 있어서, 최종 사용자가 여러 가지 미리 준비된 구성 중에서 선택할 수 있도록 합니다 (개발자가 선택 사항을 표시하고 선택한 구성을 로드하는 메커니즘을 제공한다면).

매개변수

fname – 파일명, 또는 파일류 객체, 또는 RawConfigParser에서 파생된 인스턴스. RawConfigParser-파생 인스턴스가 전달되면, 그대로 사용됩니다. 그렇지 않으면, Configparser의 인스턴스가 만들어지고, 이것으로 fname으로 전달된 객체로부터 구성을 읽습니다. readline() 메서드가 있으면, 파일류 객체라고 가정하고, read_file()을 사용하여 읽습니다; 그렇지 않으면, 파일명으로 간주하고 read()로 전달됩니다.

defaults – ConfigParser로 전달되는 기본값을 이 인자로 지정할 수 있습니다.

disable_existing_loggers – False로 지정되면, 이 호출이 이루어졌을 때 존재하는 로거는 활성화된 상태로 남습니다. 기본값은 True이므로, 과거 호환성을 유지하도록 이전 동작을 활성화합니다. 이 동작은 이미 존재하는 비 루트 로거를 그들이나 그들의 조상이 로깅 구성에서 명시적으로 명명되지 않으면 비활성화하는 것입니다.

버전 3.4에서 변경: RawConfigParser의 서브 클래스의 인스턴스가 이제 fname에 대한 값으로 허용됩니다. 이것은 다음을 쉽게 합니다:

로깅 구성이 전체 응용 프로그램 구성의 일부인 구성 파일의 사용.

파일에서 읽어 들인 다음 fileConfig로 전달되기 전에 사용하는 응용 프로그램이 (예를 들어, 명령 줄 매개 변수나 실행 시간 환경의 다른 측면에 기반하여) 수정하는 구성의 사용.

logging.config.listen(port=DEFAULT_LOGGING_CONFIG_PORT, verify=None)

지정된 포트에서 소켓 서버를 시작하고, 새 구성을 수신 대기합니다. 포트를 지정하지 않으면, 모듈의 기본 DEFAULT_LOGGING_CONFIG_PORT가 사용됩니다. 로깅 구성은 dictConfig()나 fileConfig()로 처리하기에 적합한 파일로 전송됩니다. 서버를 시작하기 위해 start()를 호출할 수 있는 Thread 인스턴스를 반환하고, 적절할 때 join()할 수 있습니다. 서버를 중지하려면, stopListening()을 호출하십시오.

verify 인자가 지정되면, 소켓을 통해 수신된 바이트열이 유효하고 처리되어야 하는지를 확인하는 콜러블이어야 합니다. 소켓을 통해 전송되는 것을 암호화 및/또는 서명하고, verify 콜러블이 서명 확인 및/또는 암호 해독을 수행할 수 있습니다. verify 콜러블은 단일 인자(소켓을 통해 수신된 바이트열)로 호출되며, 처리할 바이트열이나 바이트열을 버려야 함을 나타내기 위해 None을 반환합니다. 반환된 바이트열은 전달된 바이트열과 같을 수 있고 (예를 들어, 확인만 수행될 때), 또는 완전히 다를 수 있습니다 (아마도 암호 해독이 수행될 때).

소켓으로 구성을 보내려면, 구성 파일을 읽어서 소켓에 struct.pack('>L', n)를 사용하여 바이너리로 만든 4바이트의 길이를 앞에 붙인 바이트 시퀀스를 보냅니다.

참고

구성 일부가 eval()로 전달되므로, 이 함수를 사용하면 사용자를 보안 위험에 노출할 수 있습니다. 이 함수는 소켓을 localhost에만 바인드하고, 원격 기계의 연결은 허용하지 않지만, 신뢰할 수 없는 코드가 listen()을 호출하는 프로세스의 계정으로 실행될 수 있는 시나리오가 있습니다. 특히, listen()을 호출하는 프로세스가 사용자가 서로를 신뢰할 수 없는 다중 사용자 시스템에서 실행되는 경우, 악의적인 사용자는 피해자의 listen() 소켓에 연결하여 공격자가 피해자의 프로세스에서 실행하고자 하는 코드를 실행하는 구성을 보내는 것만으로도, 피해 사용자의 프로세스에서 사실상 임의의 코드를 실행할 수 있습니다. 이것은 기본 포트를 사용하는 경우 특히 쉽게 수행할 수 있지만, 다른 포트가 사용되는 경우에도 어렵지는 않습니다. 이러한 일이 발생할 위험을 피하려면, listen()에 verify 인자를 사용하여 인식되지 않은 구성이 적용되지 않도록 하십시오.

버전 3.4에서 변경: verify 인자가 추가되었습니다.

참고

리스너에 기존 로거를 비활성화하지 않는 구성을 보내려면, dictConfig()를 사용하도록 구성에 JSON 형식을 사용해야 합니다. 이 방법은 보내는 구성에서 disable_existing_loggers를 False로 지정할 수 있도록 합니다.

logging.config.stopListening()

listen()에 대한 호출로 만들어진 리스닝 서버를 중지합니다. 이것은 일반적으로 listen()의 반환 값에 대해 join()을 호출하기 전에 호출됩니다.

구성 딕셔너리 스키마

로깅 구성을 기술하려면 만들려는 다양한 객체와 그들 간의 연결을 나열해야 합니다; 예를 들어, ‘console’이라는 처리기를 만든 다음 ‘startup’이라는 로거가 ‘console’ 처리기에 메시지를 보낼 것이라고 말할 수 있습니다. 사용자 자신의 포매터나 처리기 클래스를 작성할 수 있으므로, 이러한 객체가 logging 모듈에서 제공하는 객체로만 제한되지는 않습니다. 이러한 클래스의 매개 변수는 sys.stderr과 같은 외부 객체를 포함할 수도 있습니다. 이러한 객체와 연결을 기술하는 문법은 아래의 객체 연결에 정의되어 있습니다.

딕셔너리 스키마 세부사항

dictConfig()에 전달되는 딕셔너리에는 반드시 다음 키가 있어야 합니다:

version - 스키마 버전을 나타내는 정숫값으로 설정됩니다. 현재 유효한 유일한 값은 1이지만, 이 키를 사용하면 과거 호환성을 유지하면서 스키마를 발전시킬 수 있습니다.

다른 모든 키는 선택 사항이지만, 있으면 아래에 설명된 대로 해석됩니다. 아래에서 ‘구성 딕셔너리(configuring dict)’가 언급되는 모든 경우에, 특수한 '()' 키를 검사해서 사용자 정의 인스턴스화가 필요한지를 확인합니다. 있다면, 아래의 사용자 정의 객체에 설명된 메커니즘을 사용하여 인스턴스를 만듭니다; 그렇지 않다면, 어떤 인스턴스를 만들지를 결정하는데 문맥이 사용됩니다.

formatters - 해당 값은 딕셔너리인데, 각 키는 포매터 id이고, 각 값은 해당 Formatter 인스턴스를 구성하는 방법을 설명하는 딕셔너리입니다.

구성 딕셔너리는 키 format과 datefmt(기본값은 None)으로 검색되며 이들은 Formatter 인스턴스를 만드는 데 사용됩니다.

filters - 해당 값은 딕셔너리인데, 각 키가 필터 id이고 각 값은 해당 Filter 인스턴스를 구성하는 방법을 설명하는 딕셔너리입니다.

구성 딕셔너리는 키 name(기본값은 빈 문자열)으로 검색되며, 이는 logging.Filter 인스턴스를 만드는 데 사용됩니다.

handlers - 해당 값은 딕셔너리인데, 각 키가 처리기 id이고 각 값은 해당 Handler 인스턴스를 구성하는 방법을 설명하는 딕셔너리입니다.

구성 딕셔너리는 다음 키에서 검색합니다:

class (필수). 이것은 처리기 클래스의 완전히 정규화된 이름입니다.

level (선택). 처리기의 수준.

formatter (선택). 이 처리기의 포매터의 id.

filters (선택). 이 처리기의 필터의 id의 리스트.

모든 다른 키는, 처리기의 생성자에 키워드 인자로 전달됩니다. 예를 들어, 다음과 같이 주어진 조각에서:

handlers:
  console:
    class : logging.StreamHandler
    formatter: brief
    level   : INFO
    filters: [allow_foo]
    stream  : ext://sys.stdout
  file:
    class : logging.handlers.RotatingFileHandler
    formatter: precise
    filename: logconfig.log
    maxBytes: 1024
    backupCount: 3

id가 console 인 처리기는 sys.stdout를 하부 스트림으로 사용하는 logging.StreamHandler로 인스턴스가 만들어집니다. id가 file 인 처리기는 키워드 인자 filename='logconfig.log', maxBytes=1024, backupCount=3를 사용하여 logging.handlers.RotatingFileHandler로 인스턴스가 만들어집니다.

loggers - 해당 값은 딕셔너리인데, 각 키가 로거 이름이고 각 값은 해당 Logger 인스턴스를 구성하는 방법을 설명하는 딕셔너리입니다.

구성 딕셔너리는 다음 키에서 검색합니다:

level (선택). 로거의 수준.

propagate (선택). 로거의 전파(propagation) 설정.

filters (선택). 이 로거의 필터의 id의 리스트

handlers (선택). 이 로거의 처리기의 id의 리스트.

지정된 로거는 지정된 수준, 전파, 필터와 처리기에 따라 구성됩니다.

root - 루트 로거에 대한 구성입니다. propagate 설정을 적용할 수 없다는 점을 제외하고 구성 처리는 모든 로거와 같습니다.

incremental - 구성을 기존 구성의 증분으로 해석할지 여부. 이 값의 기본값은 False이며, 이는 지정된 구성이 기존 구성을 기존 fileConfig() API에서 사용된 것과 같은 의미로 대체 함을 뜻합니다.

지정된 값이 True이면, 증분 구성 절에서 설명하는 대로 구성이 처리됩니다.

disable_existing_loggers - 기존의 루트가 아닌 로거를 비활성화할지 여부. 이 설정은 fileConfig()의 같은 이름의 매개 변수를 반영합니다. 없으면, 이 매개 변수의 기본값은 True입니다. incremental이 True이면 이 값은 무시됩니다.

증분 구성

증분 구성에 완벽한 유연성을 제공하기는 어렵습니다. 예를 들어, 필터와 포매터와 같은 객체는 익명이므로, 일단 구성이 설정되면, 이러한 익명 객체를 참조하여 구성을 보강할 수 없습니다.

또한, 일단 구성이 설정되면, 실행 시간에 로거, 처리기, 필터, 포매터의 객체 그래프를 임의로 변경해야 할 강력한 사례는 없습니다; 로거와 처리기의 상세도는 단지 수준(과, loggers에서는 전파 플래그)을 설정하여 제어할 수 있습니다. 객체 그래프를 임의로 안전하게 변경하는 것은 다중 스레드 환경에서 문제가 됩니다; 불가능하지는 않지만, 구현에 추가되는 복잡성을 상쇄할만한 가치가 없습니다.

따라서, 구성 딕셔너리의 incremental 키가 있고 True이면, 시스템은 formatters와 filters 항목을 완전히 무시하고 handlers 항목의 level 설정과 loggers와 root 항목의 level과 propagate 설정만 처리합니다.

구성 딕셔너리의 값을 사용하면 구성을 피클 된 딕셔너리의 형태로 네트워크를 통해 소켓 리스너로 전송할 수 있습니다. 따라서, 장기 실행 응용 프로그램의 로깅 상세도는 응용 프로그램을 중지하고 다시 시작할 필요 없이 도중에 변경될 수 있습니다.

객체 연결

스키마는 객체 그래프에서 서로 연결된 로깅 객체 집합(로거, 처리기, 포매터, 필터)을 기술합니다. 따라서, 스키마는 객체 간의 연결을 표현할 필요가 있습니다. 예를 들어, 일단 구성되면, 특정 로거가 특정 처리기에 연결된다고 합시다. 이 토론의 목적을 위해, 둘 간의 연결에서 로거는 소스를, 처리기는 대상(destination)을 나타낸다고 할 수 있습니다. 물론 구성된 객체에서 이것은 처리기에 대한 참조를 갖는 로거로 표현됩니다. 구성 딕셔너리에서, 각 대상 객체에 명확하게 식별하는 id를 부여한 다음, 소스 객체의 구성에서 그 id를 사용하여, 소스와 그 id를 갖는 대상 객체 사이에 연결이 있음을 나타냅니다.

그래서, 예를 들어, 다음 YAML 조각을 고려해보십시오:

formatters:
  brief:
    # configuration for formatter with id 'brief' goes here
  precise:
    # configuration for formatter with id 'precise' goes here
handlers:
  h1: #This is an id
   # configuration of handler with id 'h1' goes here
   formatter: brief
  h2: #This is another id
   # configuration of handler with id 'h2' goes here
   formatter: precise
loggers:
  foo.bar.baz:
    # other configuration for logger 'foo.bar.baz'
    handlers: [h1, h2]

(참고: 딕셔너리에 해당하는 파이썬 소스 형식보다 약간 더 읽기 쉬우므로 여기에서 YAML을 사용했습니다.)

로거의 id는 로거로의 참조를 얻기 위해서 프로그램적으로 사용되는 로거 이름입니다, 예를 들어 foo.bar.baz. 포매터와 필터의 id는 임의의 문자열 값(가령 위의 brief, precise)이 될 수 있으며, 일시적이므로 구성 딕셔너리 처리에만 의미가 있고 객체 간의 연결을 결정하는 데 사용되며, 구성 호출이 완료된 후에는 어디에도 남아있지 않습니다.

위의 조각은 foo.bar.baz라는 로거에 두 개의 처리기가 연결되어 있어야 하며, 이 처리기들은 처리기 id h1과 h2``에 의해 기술됩니다. ``h1의 포매터는 id brief로 기술되는 것이고, h2의 포매터는 id precise로 기술되는 것입니다.

사용자 정의 객체

스키마는 처리기, 필터 및 포매터에 대한 사용자 정의 객체를 지원합니다. (로거에는 인스턴스마다 다른 형이 필요하지 않으므로, 이 구성 스키마에는 사용자 정의 로거 클래스에 대한 지원이 없습니다.)

구성할 객체는 구성을 자세히 설명하는 딕셔너리로 시술됩니다. 어떤 곳에서는, 로깅 시스템이 객체를 어떻게 인스턴스화할지 문맥으로부터 추측할 수 있지만, 사용자 정의 객체를 인스턴스화 해야 할 때, 시스템은 이를 수행하는 방법을 알 수 없습니다. 사용자 정의 객체 인스턴스화를 위한 완벽한 유연성을 제공하기 위해, 사용자는 ‘팩토리’를 제공해야 하는데, 구성 딕셔너리로 호출되고 인스턴스화 된 객체를 반환하는 콜러블입니다. 이것은 특수키 '()'로 제공되는 팩토리로의 절대적 임포트 경로로 표시됩니다. 다음은 구체적인 예입니다:

formatters:
  brief:
    format: '%(message)s'
  default:
    format: '%(asctime)s %(levelname)-8s %(name)-15s %(message)s'
    datefmt: '%Y-%m-%d %H:%M:%S'
  custom:
      (): my.package.customFormatterFactory
      bar: baz
      spam: 99.9
      answer: 42

위의 YAML 조각은 세 가지 포매터를 정의합니다. 첫 번째(id brief)는 지정된 포맷 문자열을 갖는 표준 logging.Formatter 인스턴스입니다. 두 번째(id default)는 더 긴 포맷을 가지며 명시적으로 시간 포맷을 정의하기도 하고, 이 두 포맷 문자열로 초기화된 logging.Formatter가 됩니다. 파이썬 소스 형식으로 표시하면, brief와 default 포매터는 각각 다음과 같은 구성 서브 딕셔너리를 갖습니다:

{
  'format' : '%(message)s'
}

그리고:

{
  'format' : '%(asctime)s %(levelname)-8s %(name)-15s %(message)s',
  'datefmt' : '%Y-%m-%d %H:%M:%S'
}

그리고, 이 딕셔너리에는 특수키 '()'가 포함되어 있지 않으므로, 문맥에서 인스턴스가 추론됩니다: 결과적으로, 표준 logging.Formatter 인스턴스가 만들어집니다. 세 번째 포매터(id custom)에 대한 구성 서브 딕셔너리는 다음과 같습니다:

{
  '()' : 'my.package.customFormatterFactory',
  'bar' : 'baz',
  'spam' : 99.9,
  'answer' : 42
}

여기에는 특수키 '()'가 포함되어 있는데, 사용자 정의 인스턴스가 필요하다는 뜻입니다. 이때, 지정된 팩토리 콜러블이 사용됩니다. 그것이 실제 콜러블이면 직접 사용됩니다 - 그렇지 않고, (예에서와같이) 문자열을 지정하면 일반적인 임포트 메커니즘을 사용하여 실제 콜러블을 얻습니다. 콜러블은 구성 서브 딕셔너리의 나머지 항목을 키워드 인자로 호출됩니다. 위의 예제에서, id가 custom인 포매터는 다음과 같은 호출이 반환한다고 가정합니다:

my.package.customFormatterFactory(bar='baz', spam=99.9, answer=42)

'()' 키가 유효한 키워드 매개 변수 이름이 아니라서 특수키로 사용되었습니다. 그러므로 호출에 사용되는 키워드 인자의 이름과 충돌하지 않습니다. '()'는 해당 값이 콜러블이라는 표시로도 기능합니다.

외부 객체에 대한 액세스

구성에서 구성 외부의 객체를 참조해야 하는 경우가 있습니다, 예를 들어 sys.stderr. 구성 딕셔너리가 파이썬 코드를 사용하여 만들어질 때는 간단하지만, 구성이 텍스트 파일(예를 들어, JSON, YAML)을 통해 제공될 때 문제가 발생합니다. 텍스트 파일에서는, sys.stderr를 리터럴 문자열 'sys.stderr'과 구별하는 표준 방법이 없습니다. 이 구별을 쉽게 하기 위해, 구성 시스템은 문자열 값에서 특정 접두사를 찾아 특수하게 처리합니다. 예를 들어, 리터럴 문자열 'ext://sys.stderr'이 구성에서 값으로 제공되면, ext://는 제거되고 값의 나머지 부분을 일반 임포트 메커니즘을 사용하여 처리합니다.

이러한 접두사의 처리는 프로토콜 처리와 유사한 방식으로 수행됩니다: 정규식 ^(?P<prefix>[a-z]+)://(?P<suffix>.*)$와 일치하는 접두사를 찾는 일반 메커니즘이 있습니다. prefix가 인식되면 suffix는 접두사 종속적 방식으로 처리되고 처리 결과가 문자열 값을 대체합니다. 접두사가 인식되지 않으면, 문자열 값은 그대로 남습니다.

내부 객체에 대한 액세스

외부 객체뿐만 아니라, 때로 구성에 있는 객체를 참조할 필요도 있습니다. 이것은 구성 시스템이 알고 있는 것들에 대해 묵시적으로 수행됩니다. 예를 들어, 로거나 처리기의 level에 대한 문자열 값 'DEBUG'은 자동으로 값 logging.DEBUG으로 변환되고, handlers, filters 및 formatter 항목은 객체 id를 받아서 적절한 대상 객체로 결정합니다.

하지만, logging 모듈에 알려지지 않은 사용자 정의 객체에는 더욱 일반적인 메커니즘이 필요합니다. 예를 들어, 위임할 다른 처리기인 target 인자를 취하는 logging.handlers.MemoryHandler를 고려해봅시다. 시스템이 이미 이 클래스에 대해 알고 있으므로, 구성에서, 주어진 target은 단지 관련 target 처리기의 객체 id이기만 하면 되며, 시스템은 id로부터 처리기를 결정합니다. 그러나 사용자가 alternate 처리기를 갖는 my.package.MyHandler를 정의하면, 구성 시스템은 alternate가 처리기를 참조한다는 것을 알 수 없습니다. 이 문제를 해결하기 위해, 일반 결정 시스템은 사용자가 다음과 같이 지정할 수 있게 합니다:

handlers:
  file:
    # configuration of file handler goes here

  custom:
    (): my.package.MyHandler
    alternate: cfg://handlers.file

리터럴 문자열 'cfg://handlers.file'은 ext:// 접두사가 있는 문자열과 비슷하게 결정되지만, 임포트 이름 공간이 아닌 구성 자체를 조회합니다. 이 메커니즘은 str.format에서 제공하는 것과 유사한 방식으로 점이나 인덱스로 액세스하는 것을 허락합니다. 따라서, 구성에서 다음과 같은 조각이 주어질 때:

handlers:
  email:
    class: logging.handlers.SMTPHandler
    mailhost: localhost
    fromaddr: my_app@domain.tld
    toaddrs:
      - support_team@domain.tld
      - dev_team@domain.tld
    subject: Houston, we have a problem.

문자열 'cfg://handlers'는 키 handlers의 딕셔너리로 결정되고, 문자열 'cfg://handlers.email은 handlers 딕셔너리에 있는 키 email의 딕셔너리로 결정됩니다, 등등. 문자열 'cfg://handlers.email.toaddrs[1]은 'dev_team.domain.tld'로 결정되고 문자열 'cfg://handlers.email.toaddrs[0]'은 값 'support_team@domain.tld'로 결정됩니다. subject 값은 'cfg://handlers.email.subject'나 동등하게 'cfg://handlers.email[subject]'를 사용하여 액세스할 수 있습니다. 후자의 형식은 키에 공백이나 영숫자가 아닌 문자가 포함되어있을 때만 필요합니다. 인덱스값이 십진수로만 구성되면, 해당 정숫값을 사용하여 액세스가 시도되고, 필요하면 문자열 값으로 다시 시도합니다.

문자열 cfg://handlers.myhandler.mykey.123이 주어지면, config_dict['handlers']['myhandler']['mykey']['123']으로 변환됩니다. 문자열이 cfg://handlers.myhandler.mykey[123]로 지정되면, 시스템은 config_dict['handlers']['myhandler']['mykey'][123]에서 값을 가져오려고 시도하고, 실패하면 config_dict['handlers']['myhandler']['mykey']['123']으로 폴백합니다.

임포트 결정과 사용자 정의 임포터

임포트 결정은, 기본적으로, 임포트 하는데 내장 __import__() 함수를 사용합니다. 이것을 자신의 임포트 메커니즘으로 바꾸고 싶을 수 있습니다: 그렇다면, DictConfigurator나 그것의 슈퍼 클래스(BaseConfigurator 클래스)의 importer 어트리뷰트를 바꿀 수 있습니다. 그러나, 함수가 클래스에서 디스크립터를 통해 액세스 되는 방식 때문에 주의해야 합니다. 파이썬 콜러블을 사용하여 임포트를 수행하려고 하고, 인스턴스 수준이 아닌 클래스 수준에서 정의하려고 한다면, staticmethod()로 감쌀 필요가 있습니다. 예를 들면:

from importlib import import_module
from logging.config import BaseConfigurator

BaseConfigurator.importer = staticmethod(import_module)

구성자 instance에서 임포트 콜러블을 설정한다면, staticmethod()로 감쌀 필요가 없습니다.

구성 파일 형식

fileConfig()이 이해하는 구성 파일 형식은 configparser 기능을 기반으로 합니다. 파일에는 [loggers], [handlers] 및 [formatters]라는 섹션이 있어야 하며, 이 섹션에서는 파일에 정의된 각 유형의 엔티티를 이름으로 식별합니다. 이러한 엔티티마다 해당 엔티티 구성 방법을 식별하는 별도의 섹션이 있습니다. 따라서, [loggers] 섹션에서 log01이라고 이름 붙은 로거에 대해, 관련 구성 세부 사항은 [logger_log01] 섹션에 담깁니다. 마찬가지로, [handlers] 섹션에서 hand01이라고 부르는 처리기는 [handler_hand01]이라는 섹션에 구성이 담기고, [formatters] 섹션에서 form01이라고 부르는 포매터는 [formatter_form01]이라는 섹션에서 구성이 지정됩니다. 루트 로거 구성은 [logger_root]라는 섹션에서 지정해야 합니다.

참고

fileConfig() API는 dictConfig() API보다 오래되었으며 로깅의 특정 측면을 다루는 기능을 제공하지 않습니다. 예를 들어, fileConfig()를 사용해서는 간단한 정수 수준을 넘어서는 메시지 필터링을 제공하는 Filter 객체를 구성할 수 없습니다. 로깅 구성에 Filter 인스턴스가 필요하면, dictConfig()를 사용해야 합니다. 향후 구성 기능의 개선은 dictConfig()에 추가될 것임에 유의하십시오. 따라서, 편리할 때 이 새로운 API로 전환하는 것을 고려해 볼 가치가 있습니다.

파일에 있는 이 절의 예는 아래에 나와 있습니다.

[loggers]
keys=root,log02,log03,log04,log05,log06,log07

[handlers]
keys=hand01,hand02,hand03,hand04,hand05,hand06,hand07,hand08,hand09

[formatters]
keys=form01,form02,form03,form04,form05,form06,form07,form08,form09

루트 로거는 수준과 처리기 목록을 지정해야 합니다. 루트 로거 섹션의 예가 아래에 나와 있습니다.

[logger_root]
level=NOTSET
handlers=hand01

level 항목은 DEBUG, INFO, WARNING, ERROR, CRITICAL 또는 NOTSET 중 하나일 수 있습니다. 루트 로거에서만, NOTSET는 모든 메시지가 로그 됨을 의미합니다. 수준 값은 logging 패키지의 이름 공간 컨텍스트에서 eval()됩니다.

handlers 항목은 [handlers] 섹션에 나타나야 하는 처리기 이름의 쉼표로 구분된 목록입니다. 이 이름들은 [handlers] 섹션에 나타나야 하며, 구성 파일에 해당 섹션이 있어야 합니다.

루트 로거가 아닌 로거의 경우, 몇 가지 추가 정보가 필요합니다. 이것은 다음 예제가 보여줍니다.

[logger_parser]
level=DEBUG
handlers=hand01
propagate=1
qualname=compiler.parser

level과 handlers 항목은 루트 로거에서처럼 해석됩니다. 단, 루트가 아닌 로거의 수준이 NOTSET로 지정되면, 시스템은 로거의 유효 수준을 판별하기 위해 상위 계층 로거를 참조합니다. propagate 항목은 메시지가 이 로거로부터 더 높은 로거 계층의 처리기로 전파되어야 함을 나타내려면 1로 설정되고, 메시지가 계층 위의 처리기로 전달되지 않음을 나타내려면 0으로 설정됩니다. qualname 항목은 로거의 계층적 채널 이름, 즉 응용 프로그램에서 로거를 가져오는 데 사용되는 이름입니다.

처리기 구성을 지정하는 섹션은 다음과 같이 예시됩니다.

[handler_hand01]
class=StreamHandler
level=NOTSET
formatter=form01
args=(sys.stdout,)

class 항목은 (logging 패키지의 이름 공간에서 eval()로 결정되는) 처리기의 클래스를 나타냅니다. level은 로거에서처럼 해석되며, NOTSET은 ‘모든 것을 로깅’을 의미합니다.

formatter 항목은 이 처리기의 포매터의 키 이름을 나타냅니다. 비어 있으면, 기본 포매터(logging._defaultFormatter)가 사용됩니다. 이름이 지정되면, [formatters] 섹션에 나타나야 하며 구성 파일에 해당 섹션이 있어야 합니다.

args 항목은, logging 패키지의 이름 공간 컨텍스트에서 eval()될 때, 처리기 클래스의 생성자에 대한 인자 목록입니다. 일반적인 항목 작성 방법을 보려면, 관련 처리기의 생성자나 아래 예제를 참조하십시오. 제공되지 않으면, 기본값은 ()입니다.

선택적 kwargs 항목은, logging 패키지의 이름 공간 컨텍스트에서 eval()될 때, 처리기 클래스의 생성자에 대한 키워드 인자 딕셔너리입니다. 제공되지 않으면, 기본값은 {}입니다.

[handler_hand02]
class=FileHandler
level=DEBUG
formatter=form02
args=('python.log', 'w')

[handler_hand03]
class=handlers.SocketHandler
level=INFO
formatter=form03
args=('localhost', handlers.DEFAULT_TCP_LOGGING_PORT)

[handler_hand04]
class=handlers.DatagramHandler
level=WARN
formatter=form04
args=('localhost', handlers.DEFAULT_UDP_LOGGING_PORT)

[handler_hand05]
class=handlers.SysLogHandler
level=ERROR
formatter=form05
args=(('localhost', handlers.SYSLOG_UDP_PORT), handlers.SysLogHandler.LOG_USER)

[handler_hand06]
class=handlers.NTEventLogHandler
level=CRITICAL
formatter=form06
args=('Python Application', '', 'Application')

[handler_hand07]
class=handlers.SMTPHandler
level=WARN
formatter=form07
args=('localhost', 'from@abc', ['user1@abc', 'user2@xyz'], 'Logger Subject')
kwargs={'timeout': 10.0}

[handler_hand08]
class=handlers.MemoryHandler
level=NOTSET
formatter=form08
target=
args=(10, ERROR)

[handler_hand09]
class=handlers.HTTPHandler
level=NOTSET
formatter=form09
args=('localhost:9022', '/log', 'GET')
kwargs={'secure': True}

포매터 구성을 지정하는 섹션은 다음과 같이 예시됩니다.

[formatter_form01]
format=F1 %(asctime)s %(levelname)s %(message)s
datefmt=
class=logging.Formatter

format 항목은 전체 포맷 문자열이고, datefmt 항목은 strftime() 호환 날짜/시간 포맷 문자열입니다. 비어있으면, 패키지는 날짜 포맷 문자열 '%Y-%m-%d %H:%M:%S'를 지정하는 것과 거의 동등한 것으로 대체합니다. 이 포맷은 밀리 초도 지정하는데, 위의 포맷 문자열을 사용한 결과에 쉼표 구분 기호와 함께 추가됩니다. 이 포맷의 예제 시간은 2003-01-23 00:29:50,411입니다.

class 항목은 선택적입니다. 포매터 클래스의 이름을 나타냅니다 (점으로 구분된 모듈과 클래스 이름). 이 옵션은 Formatter 서브 클래스를 인스턴스화하는 데 유용합니다. Formatter의 서브 클래스는 확장 또는 압축 형식으로 예외 트래이스백을 표시할 수 있습니다.

참고

위에서 설명한 대로 eval()를 사용하기 때문에, listen()을 사용하여 소켓을 통해 구성을 보내고 받을 때 발생할 수 있는 잠재적인 보안 위험이 있습니다. 위험은 상호 신뢰가 없는 여러 사용자가 같은 기계에서 코드를 실행할 때로 제한됩니다; 자세한 내용은 listen() 설명서를 참조하십시오.

더 보기

모듈 logging

logging 모듈에 관한 API 레퍼런스.

모듈 logging.handlers

logging 모듈에 포함된 유용한 처리기.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

일반 운영 체제 서비스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

일반 운영 체제 서비스 »

|

logging.handlers — 로깅 처리기

소스 코드: Lib/logging/handlers.py [https://github.com/python/cpython/tree/3.7/Lib/logging/handlers.py]

Important

이 페이지에는 레퍼런스 정보만 있습니다. 자습서는 다음을 참조하십시오

기초 자습서

고급 자습서

로깅 요리책

다음과 같은 유용한 처리기가 패키지에서 제공됩니다. 3개의 처리기(StreamHandler, FileHandler, NullHandler)는 실제로는 logging 모듈 자체에 정의되어 있지만, 다른 처리기들과 함께 여기에서 설명합니다.

StreamHandler

핵심 logging 패키지에 있는 StreamHandler 클래스는 sys.stdout, sys.stderr 또는 임의의 파일류 객체(또는 더 정확하게, write()와 flush() 메서드를 지원하는 모든 객체)와 같은 스트림으로 로깅 출력을 보냅니다.

class logging.StreamHandler(stream=None)

StreamHandler 클래스의 새로운 인스턴스를 반환합니다. stream 이 지정되면, 인스턴스는 그것을 로그 출력용으로 사용합니다; 그렇지 않으면, sys.stderr 이 사용됩니다.

emit(record)

포매터가 지정되면, 레코드를 포맷하는 데 사용됩니다. 그런 다음 레코드는 종결자(terminator)와 함께 스트림에 기록됩니다. 예외 정보가 있으면, traceback.print_exception()을 사용하여 포맷한 후 스트림에 덧붙입니다.

flush()

스트림의 flush() 메서드를 호출해서 플러시 합니다. close() 메서드는 Handler 에서 상속되고, 출력이 없으므로, 명시적 flush() 호출이 필요할 수도 있습니다.

setStream(stream)

지정한 값이 현재 값과 다르면, 인스턴스의 스트림을 지정된 값으로 설정합니다. 새 스트림이 설정되기 전에 이전 스트림이 플러시 됩니다.

매개변수

stream – 처리기가 사용할 스트림.

반환값

스트림이 변경되면 이전 스트림, 그렇지 않으면 None.

버전 3.7에 추가.

버전 3.2에서 변경: StreamHandler 클래스는 이제 포맷된 레코드를 스트림에 쓸 때 종결자로 사용되는 terminator 어트리뷰트(기본 값 '\n')를 갖습니다. 이 개행 문자 종료를 원하지 않는다면, 처리기 인스턴스의 terminator 어트리뷰트를 빈 문자열로 설정할 수 있습니다. 이전 버전에서는, 종결자가 '\n' 로 하드 코딩되었습니다.

FileHandler

핵심 logging 패키지에 있는 FileHandler 클래스는 로깅 출력을 디스크 파일로 보냅니다. StreamHandler 에서 출력 기능을 상속받습니다.

class logging.FileHandler(filename, mode='a', encoding=None, delay=False)

FileHandler 클래스의 새로운 인스턴스를 반환합니다. 지정된 파일이 열리고 로깅을 위한 스트림으로 사용됩니다. mode 가 지정되지 않으면, 'a' 가 사용됩니다. encoding 이 None 이 아니면, encoding을 사용하여 파일을 엽니다. delay 가 참이면, 파일 열기는 emit()의 첫 번째 호출이 있을 때까지 연기됩니다. 기본적으로, 파일은 제한 없이 커집니다.

버전 3.6에서 변경: 문자열 값뿐만 아니라, Path 객체도 filename 인자로 허용됩니다.

close()

파일을 닫습니다.

emit(record)

레코드를 파일에 출력합니다.

NullHandler

버전 3.1에 추가.

핵심 logging 패키지에 있는 NullHandler 클래스는 포맷이나 출력을 일절 하지 않습니다. 기본적으로 라이브러리 개발자가 사용하는 ‘no-op’ 처리기입니다.

class logging.NullHandler

NullHandler 클래스의 새로운 인스턴스를 반환합니다.

emit(record)

이 메서드는 아무것도 하지 않습니다.

handle(record)

이 메서드는 아무것도 하지 않습니다.

createLock()

액세스를 직렬화해야 하는 하부 I/O가 없으므로, 이 메서드는 록으로 None 을 반환합니다.

NullHandler 사용법에 대한 더 많은 정보는 라이브러리 로깅 구성를 참조하세요.

WatchedFileHandler

logging.handlers 모듈에 있는 WatchedFileHandler 클래스는 로깅 중인 파일을 감시하는 FileHandler 입니다. 파일이 변경되면, 닫은 후에 같은 이름의 파일을 다시 엽니다.

로그 파일 회전을 수행하는 newsyslog 나 logrotate 와 같은 프로그램의 사용으로 인해 파일이 변경될 수 있습니다. 유닉스/리눅스에서 사용하기 위한 이 처리기는 마지막 출력 이후에 파일이 변경되었는지 감시합니다. (파일의 장치나 inode가 변경되면 파일이 변경된 것으로 간주합니다.) 파일이 변경되면, 이전 파일 스트림이 닫히고, 새 스트림을 얻기 위해 파일을 엽니다.

이 처리기는 윈도우에서 사용하기에 적합하지 않습니다. 윈도우에서는 열린 로그 파일을 이동하거나 이름을 변경할 수 없어서 - logging은 파일을 배타적 록으로 엽니다 - 이런 처리기가 필요하지 않기 때문입니다. 또한 ST_INO 는 윈도우에서 지원되지 않습니다; stat()는 항상 이 값에 대해 0을 반환합니다.

class logging.handlers.WatchedFileHandler(filename, mode='a', encoding=None, delay=False)

WatchedFileHandler 클래스의 새 인스턴스를 반환합니다. 지정된 파일이 열리고 로깅을 위한 스트림으로 사용됩니다. mode 가 지정되지 않으면, 'a' 가 사용됩니다. encoding 이 None 이 아니면, encoding을 사용하여 파일을 엽니다. delay 가 참이면, 파일 열기는 emit()의 첫 번째 호출이 있을 때까지 연기됩니다. 기본적으로, 파일은 제한 없이 커집니다.

버전 3.6에서 변경: 문자열 값뿐만 아니라, Path 객체도 filename 인자로 허용됩니다.

reopenIfNeeded()

파일이 변경되었는지 확인합니다. 그렇다면, 기존 스트림을 플러시 한 후 닫고, 파일을 다시 엽니다. 일반적으로 레코드를 파일로 출력하기 전에 수행합니다.

버전 3.6에 추가.

emit(record)

레코드를 파일에 출력하지만, 파일이 변경되었을 때 다시 열기 위해 reopenIfNeeded()를 먼저 호출합니다.

BaseRotatingHandler

logging.handlers 모듈에 있는 BaseRotatingHandler 클래스는 회전하는 파일 처리기들(RotatingFileHandler와 TimedRotatingFileHandler)의 베이스 클래스입니다. 이 클래스의 인스턴스를 만들 필요는 없지만, 재정의가 필요할 수 있는 어트리뷰트와 메서드가 있습니다.

class logging.handlers.BaseRotatingHandler(filename, mode, encoding=None, delay=False)

매개 변수는 FileHandler 와 같습니다. 어트리뷰트는 다음과 같습니다:

namer

이 어트리뷰트가 콜러블로 설정되면, rotation_filename() 메서드는 이 콜러블에 위임합니다. 콜러블로 전달되는 매개 변수는 rotation_filename()로 전달되는 것입니다.

참고

namer 함수는 롤오버 중에 꽤 자주 호출되므로, 가능한 한 간단하고 빨라야 합니다. 또한, 주어진 입력에 대해 매번 같은 출력을 반환해야 합니다, 그렇지 않으면 롤오버 동작이 예상대로 작동하지 않을 수 있습니다.

버전 3.3에 추가.

rotator

이 어트리뷰트가 콜러블로 설정되면, rotate() 메서드는 이 콜러블에 위임합니다. 콜러블로 전달되는 매개 변수는 rotate()로 전달되는 것입니다.

버전 3.3에 추가.

rotation_filename(default_name)

회전할 때 로그 파일의 파일명을 수정합니다.

사용자 정의 파일명을 제공할 수 있게 하려고 제공됩니다.

기본 구현은 처리기의 ‘namer’ 어트리뷰트를(콜러블이라면) 호출하는데, 기본 이름을 전달합니다. 어트리뷰트가 콜러블이 아니면 (기본값은 None 입니다), 이름은 변경되지 않고 반환됩니다.

매개변수

default_name – 로그 파일의 기본 이름.

버전 3.3에 추가.

rotate(source, dest)

회전할 때, 현재 로그를 회전합니다.

기본 구현은 처리기의 ‘rotator’ 어트리뷰트를(콜러블이라면) 호출하는데, source와 dest 인자를 전달합니다. 어트리뷰트가 콜러블이 아니면 (기본값은 None 입니다), source를 dest 로 단순히 이름을 바꿉니다.

매개변수

source – 소스 파일명. 이것은 일반적으로 기본 파일명입니다, 예를 들어 ‘test.log’.

dest – 대상 파일명. 이것은 일반적으로 소스가 회전되는 곳입니다, 예를 들어 ‘test.log.1’.

버전 3.3에 추가.

어트리뷰트가 존재하는 이유는 서브 클래싱해야 할 필요를 줄이는 것입니다 - RotatingFileHandler와 TimedRotatingFileHandler 의 인스턴스에 같은 콜러블을 사용할 수 있습니다. namer 나 rotator 콜러블이 예외를 발생시키면, emit() 동안 발생하는 다른 예외와 같은 방식으로 처리됩니다, 즉 처리기의 handleError() 메서드를 통해.

회전 처리를 더 크게 변경해야 하면, 메서드를 재정의할 수 있습니다.

예는 rotator와 namer를 사용해서 로그 회전 처리하기를 보십시오.

RotatingFileHandler

logging.handlers 모듈에 있는 RotatingFileHandler 클래스는 디스크 로그 파일 회전을 지원합니다.

class logging.handlers.RotatingFileHandler(filename, mode='a', maxBytes=0, backupCount=0, encoding=None, delay=False)

RotatingFileHandler 클래스의 새로운 인스턴스를 반환합니다. 지정된 파일이 열리고 로깅을 위한 스트림으로 사용됩니다. mode 가 지정되지 않으면, 'a' 가 사용됩니다. encoding 이 None 이 아니면, encoding을 사용하여 파일을 엽니다. delay 가 참이면, 파일 열기는 emit()의 첫 번째 호출이 있을 때까지 연기됩니다. 기본적으로, 파일은 제한 없이 커집니다.

미리 결정된 크기에서 파일을 롤오버 (rollover) 하기 위해 maxBytes 와 backupCount 값을 사용할 수 있습니다. 크기가 초과하려고 할 때, 파일이 닫히고 출력을 위해 새 파일이 조용히 열립니다. 롤오버는 현재 로그 파일이 거의 maxBytes 길이일 때마다 발생합니다; 그러나 maxBytes 나 backupCount 가 0이면 롤오버가 발생하지 않으므로, 일반적으로 backupCount 를 1 이상으로 설정하고, 0이 아닌 maxBytes를 사용하기를 원할 겁니다. backupCount 가 0이 아니면, 시스템은 파일명에 확장자 ‘.1’, ‘.2’ 등을 추가하여 지난 로그 파일을 저장합니다. 예를 들어, backupCount 가 5이고 기본 파일명이 app.log 면, app.log, app.log.1, app.log.2부터 app.log.5 까지의 파일을 얻게 됩니다. 기록되는 파일은 항상 app.log 입니다. 이 파일이 채워지면, 닫히고 app.log.1 로 이름이 변경됩니다, 그리고 파일 app.log.1, app.log.2 등이 존재하면, 이것들도 각기 app.log.2, app.log.3 등으로 이름이 변경됩니다.

버전 3.6에서 변경: 문자열 값뿐만 아니라, Path 객체도 filename 인자로 허용됩니다.

doRollover()

위에서 설명한 대로 롤오버를 수행합니다.

emit(record)

앞에서 설명한 대로 롤오버를 처리하면서, 파일에 레코드를 출력합니다.

TimedRotatingFileHandler

logging.handlers 모듈에 있는 TimedRotatingFileHandler 클래스는 특정 시간 간격의 디스크 로그 파일 회전을 지원합니다.

class logging.handlers.TimedRotatingFileHandler(filename, when='h', interval=1, backupCount=0, encoding=None, delay=False, utc=False, atTime=None)

TimedRotatingFileHandler 클래스의 새로운 인스턴스를 반환합니다. 지정된 파일이 열리고 로깅을 위한 스트림으로 사용됩니다. 회전 시 파일명 접미사도 설정합니다. when 과 interval 에 따라 회전이 일어납니다.

when 을 사용하여 interval 의 유형을 지정할 수 있습니다. 가능한 값의 목록은 아래와 같습니다. 대소 문자를 구분하지 않는다는 것에 유의하세요.

값

interval의 유형

atTime 이 사용되는지와 사용되는 방식

'S'

초

무시됩니다

'M'

분

무시됩니다

'H'

시간

무시됩니다

'D'

일

무시됩니다

'W0'-'W6'

요일 (0=월요일)

최초 롤오버 시간을 계산하는 데 사용됩니다

'midnight'

atTime 을 지정하지 않으면 자정에, 그렇지 않으면 atTime 에 롤오버 합니다

최초 롤오버 시간을 계산하는 데 사용됩니다

요일 기반 회전을 사용할 때, 월요일은 ‘W0’, 화요일은 ‘W1’, 등등 일요일은 ‘W6’까지 지정하십시오. 이 경우, interval 에 전달된 값은 사용되지 않습니다.

시스템은 파일명에 확장자를 추가하여 지난 로그 파일을 저장합니다. 확장자는 날짜와 시간 기반이며, 롤오버 간격에 따라 strftime 형식 %Y-%m-%d_%H-%M-%S 이나 그 앞부분을 사용합니다.

다음 롤오버 시간을 처음 계산할 때 (처리기가 만들어질 때), 기존 로그 파일의 마지막 수정 시간 또는 (없으면) 현재 시각이 다음 회전이 발생할 때를 계산하는 데 사용됩니다.

utc 인자가 참이면, UTC 시간이 사용됩니다; 그렇지 않으면 현지 시간이 사용됩니다.

backupCount 가 0이 아니면, 최대 backupCount 개의 파일이 보관되고, 롤오버가 발생할 때 더 많은 파일이 생성되면 가장 오래된 파일이 삭제됩니다. 삭제 논리는 interval을 사용하여 삭제할 파일을 결정하므로, interval을 변경하면 오래된 파일이 남아있을 수 있습니다.

delay 가 참이면, 파일 열기는 emit()에 대한 첫 번째 호출까지 지연됩니다.

atTime 이 None 이 아니면, 반드시 datetime.time 인스턴스여야 하는데, 롤오버가 “자정에” 또는 “특정 요일에” 발생하도록 설정된 경우에 롤오버가 발생하는 시간을 지정합니다. 이 경우, atTime 값은 최초 롤오버를 계산하는 데 사용되며, 이후 롤오버는 일반적인 간격 계산을 통해 계산됩니다.

참고

최초 롤오버 시간의 계산은 처리기가 초기화될 때 수행됩니다. 후속 롤오버 시간 계산은 롤오버가 발생하는 경우에만 수행되며, 롤오버는 출력을 내보낼 때만 발생합니다. 이것을 명심하지 않으면, 혼란이 생길 수 있습니다. 예를 들어, “매분” 간격을 설정하면, 이것이 항상 1분 간격의 (파일명을 갖는) 로그 파일들을 보게 된다는 것을 뜻하지는 않습니다; 응용 프로그램을 실행하는 동안, 로그 출력이 1분당 한 번보다 더 자주 발생하면, 1분 간격의 로그 파일을 볼 것으로 예상할 수 있습니다. 반면, (가령) 로깅 메시지가 5분마다 한 번만 출력되면, 출력이 없는 (따라서 롤오버가 없는) 분에 해당하는 파일 시간의 틈이 생깁니다.

버전 3.4에서 변경: atTime 매개 변수가 추가되었습니다.

버전 3.6에서 변경: 문자열 값뿐만 아니라, Path 객체도 filename 인자로 허용됩니다.

doRollover()

위에서 설명한 대로 롤오버를 수행합니다.

emit(record)

위에서 설명한 대로 롤오버를 처리하면서, 파일에 레코드를 출력합니다.

SocketHandler

logging.handlers 모듈에 있는 SocketHandler 클래스는 로깅 출력을 네트워크 소켓에 보냅니다. 베이스 클래스는 TCP 소켓을 사용합니다.

class logging.handlers.SocketHandler(host, port)

host 와 port로 주어진 주소의 원격 기계와 통신하기 위한, SocketHandler 클래스의 새로운 인스턴스를 반환합니다.

버전 3.4에서 변경: port가 None으로 지정되면, host의 값을 사용하여 유닉스 도메인 소켓이 만들어집니다 - 그렇지 않으면 TCP 소켓이 만들어집니다.

close()

소켓을 닫습니다.

emit()

레코드의 어트리뷰트 딕셔너리를 피클하고 바이너리 형식으로 소켓에 씁니다. 소켓에 에러가 있으면 조용히 패킷을 버립니다. 이전에 연결이 끊어졌으면, 연결을 다시 맺습니다. 수신 단에서 레코드를 LogRecord로 역 피클 하려면, makeLogRecord() 함수를 사용하십시오.

handleError()

emit() 중에 발생한 에러를 처리합니다. 가장 큰 원인은 연결이 끊어지는 것입니다. 다음 이벤트에서 다시 시도할 수 있도록 소켓을 닫습니다.

makeSocket()

이것은 서브 클래스가 원하는 소켓의 정확한 유형을 정의 할 수 있게 하는 팩토리 메서드입니다. 기본 구현은 TCP 소켓(socket.SOCK_STREAM)을 만듭니다.

makePickle(record)

Pickles the record’s attribute dictionary in binary format with a length prefix, and returns it ready for transmission across the socket. The details of this operation are equivalent to:

data = pickle.dumps(record_attr_dict, 1)
datalen = struct.pack('>L', len(data))
return datalen + data

피클은 완전히 안전하지 않습니다. 보안이 염려되면, 이 메서드를 재정의하여 더욱 안전한 메커니즘을 구현할 수 있습니다. 예를 들어, HMAC를 사용하여 피클에 서명한 다음 수신 단에서 확인하거나, 수신 단에서 전역 객체의 역 피클링을 비활성화할 수 있습니다.

send(packet)

Send a pickled byte-string packet to the socket. The format of the sent byte-string is as described in the documentation for makePickle().

This function allows for partial sends, which can happen when the network is busy.

createSocket()

소켓을 만들려고 합니다; 실패 시, 지수 백 오프 알고리즘을 사용합니다. 최초 실패 시 처리기는 보내려는 메시지를 버립니다. 후속 메시지가 같은 인스턴스에 의해 처리될 때, 일정한 시간이 지날 때까지 연결을 시도하지 않습니다. 기본 파라미터를 쓸 때, 최초 지연은 1초이고, 지연 후에도 연결을 만들 수 없으면, 처리기가 최대 30초가 될 때까지 매번 지연 시간을 두 배로 늘립니다.

이 동작은 다음 처리기 어트리뷰트에 의해 제어됩니다:

retryStart (최초 지연, 기본값은 1.0 초).

retryFactor (배율, 기본값은 2.0).

retryMax (최대 지연, 기본값은 30.0 초).

이것은, 처리기가 사용된 후에 원격 수신기가 시작되면, 메시지가 손실될 수 있음을 뜻합니다 (처리기가 지연이 경과 할 때까지 연결을 시도하지조차 않고, 지연 기간에 메시지를 조용히 버리기 때문입니다).

DatagramHandler

logging.handlers 모듈에 있는 DatagramHandler 클래스는 UDP 소켓을 통해 로깅 메시지를 보낼 수 있도록 SocketHandler를 상속합니다.

class logging.handlers.DatagramHandler(host, port)

host 와 port로 주어진 주소의 원격 기계와 통신하기 위한, DatagramHandler 클래스의 새로운 인스턴스를 반환합니다.

버전 3.4에서 변경: port가 None으로 지정되면, host의 값을 사용하여 유닉스 도메인 소켓이 만들어집니다 - 그렇지 않으면 UDP 소켓이 만들어집니다.

emit()

레코드의 어트리뷰트 딕셔너리를 피클하고 바이너리 형식으로 소켓에 씁니다. 소켓에 에러가 있으면 조용히 패킷을 버립니다. 수신 단에서 레코드를 LogRecord로 역 피클 하려면, makeLogRecord() 함수를 사용하십시오.

makeSocket()

UDP 소켓(socket.SOCK_DGRAM)을 만들기 위해 SocketHandler의 팩토리 메서드가 여기에서 재정의되었습니다.

send(s)

Send a pickled byte-string to a socket. The format of the sent byte-string is as described in the documentation for SocketHandler.makePickle().

SysLogHandler

logging.handlers 모듈에 있는 SysLogHandler 클래스는 원격 또는 로컬 유닉스 syslog로 로깅 메시지를 보내는 것을 지원합니다.

class logging.handlers.SysLogHandler(address=('localhost', SYSLOG_UDP_PORT), facility=LOG_USER, socktype=socket.SOCK_DGRAM)

(host, port) 튜플 형태의 address로 주어진 주소의 원격 유닉스 기계와 통신하기 위한 SysLogHandler 클래스의 새 인스턴스를 돌려줍니다. address 를 지정하지 않으면 ('localhost', 514)가 사용됩니다. 주소는 소켓을 여는 데 사용됩니다. (host, port) 튜플을 제공하는 대신, 주소를 문자열로 제공할 수 있습니다, 예를 들어 ‘/dev/log’. 이 경우, 메시지를 syslog로 보내는데 유닉스 도메인 소켓이 사용됩니다. facility 가 지정되지 않으면, LOG_USER가 사용됩니다. 열리는 소켓의 유형은 socktype 인자에 따라 달라지며, 기본값은 socket.SOCK_DGRAM이고, 따라서 UDP 소켓이 열립니다. TCP 소켓을 열려면 (rsyslog와 같은 최신 syslog 데몬을 사용할 때), socket.SOCK_STREAM 값을 지정하십시오.

서버가 UDP 포트 514에서 수신을 기다리지 않으면, SysLogHandler가 작동하지 않는 것처럼 보일 수 있습니다. 이 경우, 도메인 소켓에 대해 사용해야 하는 주소를 확인하십시오 - 이는 시스템에 따라 다릅니다. 예를 들어 리눅스에서는 보통 ‘/dev/log’ 이지만 OS/X에서는 ‘/var/run/syslog’ 입니다. 플랫폼을 확인하고 적절한 주소를 사용해야 합니다 (응용 프로그램을 여러 플랫폼에서 실행해야 하는 경우 실행 시간에 검사를 수행해야 할 수도 있습니다). 윈도우에서는, UDP 옵션을 사용해야 합니다.

버전 3.2에서 변경: socktype 이 추가되었습니다.

close()

원격 호스트로의 소켓을 닫습니다.

emit(record)

레코드가 포맷된 다음, syslog 서버로 전송됩니다. 예외 정보가 있으면, 서버로 보내 지지 않습니다.

버전 3.2.1에서 변경: (bpo-12168 [https://bugs.python.org/issue?@action=redirect&bpo=12168]를 보세요.) 이전 버전에서, syslog 데몬으로 보낸 메시지는 NUL 바이트로 항상 종료되었는데, 이전 버전의 데몬에서 관련 사양(RFC 5424 [https://tools.ietf.org/html/rfc5424.html])에 없는데도 불구하고 NUL 종료 메시지를 요구했기 때문입니다. 최신 버전의 데몬은 NUL 바이트를 기대하지는 않지만, 있는 경우 이를 제거하고, 더 최근의 (RFC 5424와 더 가깝게 일치하는) 데몬은 NUL 바이트를 메시지 일부로 전달합니다.

이러한 모든 다른 데몬 동작에 직면하여 syslog 메시지를 더욱 쉽게 처리할 수 있도록, NUL 바이트를 추가하는 작업은 클래스 수준 어트리뷰트 append_nul을 사용하여 구성할 수 있게 만들었습니다. 기본값은 True(기존 동작 유지)이지만, 특정 인스턴스가 NUL 종결자를 추가하지 않도록 SysLogHandler 인스턴스에서 False로 설정할 수 있습니다.

버전 3.3에서 변경: (bpo-12419 [https://bugs.python.org/issue?@action=redirect&bpo=12419]를 보세요.) 이전 버전에서는, 메시지 소스를 식별하는 “ident” 나 “tag” 접두사를 위한 기능이 없었습니다. 이제는 클래스 수준의 어트리뷰트를 사용하여 지정할 수 있습니다, ""을 기본값으로 사용하여 기존 동작을 유지하지만, SysLogHandler 인스턴스에서 재정의하여 해당 인스턴스가 처리하는 모든 메시지에 ident를 추가하도록 할 수 있습니다. 제공된 ident는 바이트열이 아닌 텍스트여야 하며 그대로 메시지 앞에 추가됩니다.

encodePriority(facility, priority)

시설(facility)과 우선순위를 정수로 인코딩합니다. 문자열이나 정수를 전달할 수 있습니다 - 문자열이 전달되면, 내부 매핑 딕셔너리를 사용하여 정수로 변환합니다.

LOG_ 기호 값은 SysLogHandler에 정의되고 sys/syslog.h 헤더 파일에 정의된 값을 그대로 옮깁니다.

우선순위

이름 (문자열)

기호 값

alert

LOG_ALERT

crit 또는 critical

LOG_CRIT

debug

LOG_DEBUG

emerg 또는 panic

LOG_EMERG

err 또는 error

LOG_ERR

info

LOG_INFO

notice

LOG_NOTICE

warn 또는 warning

LOG_WARNING

시설

이름 (문자열)

기호 값

auth

LOG_AUTH

authpriv

LOG_AUTHPRIV

cron

LOG_CRON

daemon

LOG_DAEMON

ftp

LOG_FTP

kern

LOG_KERN

lpr

LOG_LPR

mail

LOG_MAIL

news

LOG_NEWS

syslog

LOG_SYSLOG

user

LOG_USER

uucp

LOG_UUCP

local0

LOG_LOCAL0

local1

LOG_LOCAL1

local2

LOG_LOCAL2

local3

LOG_LOCAL3

local4

LOG_LOCAL4

local5

LOG_LOCAL5

local6

LOG_LOCAL6

local7

LOG_LOCAL7

mapPriority(levelname)

로깅 수준 이름을 syslog 우선순위 이름으로 매핑합니다. 사용자 정의 수준을 사용하거나 기본 알고리즘이 여러분의 요구에 적합하지 않으면, 이 값을 재정의해야 할 수 있습니다. 기본 알고리즘은 DEBUG, INFO, WARNING, ERROR 및 CRITICAL을 동등한 syslog 이름으로 매핑하고, 다른 모든 수준 이름은 ‘warning’으로 매핑합니다.

NTEventLogHandler

logging.handlers 모듈에 있는 NTEventLogHandler 클래스는 로깅 메시지를 로컬 윈도우 NT, 윈도우 2000 또는 윈도우 XP 이벤트 로그로 보내는 것을 지원합니다. 사용할 수 있으려면 먼저 Mark Hammond의 파이썬 용 Win32 확장이 설치되어 있어야 합니다.

class logging.handlers.NTEventLogHandler(appname, dllname=None, logtype='Application')

NTEventLogHandler 클래스의 새 인스턴스를 반환합니다. appname 은 이벤트 로그에 나타나는 응용 프로그램 이름을 정의하는 데 사용됩니다. 이 이름을 사용하여 적절한 레지스트리 항목이 만들어집니다. dllname 은 로그에 보관할 메시지 정의를 포함하는 .dll 또는 .exe의 완전히 정규화된 경로명을 제공해야 합니다 (지정되지 않으면, 'win32service.pyd'이 사용됩니다 - 이것은 Win32 확장과 함께 설치되며 몇 가지 기본 자리 표시자 메시지 정의를 포함합니다. 이 자리 표시자를 사용하면 전체 메시지 소스가 로그에 보관되므로 이벤트 로그가 커진다는 것에 유의하십시오. 간략한 로그를 원하면, 이벤트 로그에서 사용할 원하는 메시지 정의가 포함된 .dll 또는 .exe의 이름을 전달해야 합니다). logtype 은 'Application', 'System' 또는 'Security' 중 하나이며, 기본값은 'Application'입니다.

close()

이 시점에서, 이벤트 로그 항목의 소스로서의 응용 프로그램 이름을 레지스트리에서 제거할 수 있습니다. 그러나, 이렇게 하면, 이벤트 로그 뷰어에서 의도한 대로 이벤트를 볼 수 없게 됩니다 - 이벤트 로그 뷰어는 .dll 이름을 가져오기 위해 레지스트리에 액세스할 수 있어야 합니다. 현재 버전은 그렇게 하지 않습니다.

emit(record)

메시지 ID, 이벤트 범주 및 이벤트 유형을 결정한 다음, 메시지를 NT 이벤트 로그에 기록합니다.

getEventCategory(record)

레코드의 이벤트 범주를 반환합니다. 여러분 자신의 범주를 지정하려면, 이것을 재정의하십시오. 이 버전은 0을 반환합니다.

getEventType(record)

레코드의 이벤트 유형을 반환합니다. 여러분 자신의 유형을 지정하려면, 이것을 재정의하십시오. 이 버전은 처리기의 typemap 어트리뷰트를 사용하여 매핑하는데, __init__()에서 DEBUG, INFO, WARNING, ERROR 및 CRITICAL에 대한 매핑이 포함된 딕셔너리로 설정됩니다. 여러분 자신의 수준을 사용한다면, 이 메서드를 재정의하거나 처리기의 typemap 어트리뷰트에 적절한 딕셔너리를 배치해야 합니다.

getMessageID(record)

레코드의 메시지 ID를 반환합니다. 여러분 자신의 메시지를 사용한다면, 로거에 전달된 msg를 포맷 문자열이 아닌 ID로 사용할 수 있습니다. 그런 다음 여기에서 딕셔너리 조회를 사용하여 메시지 ID를 가져올 수 있습니다. 이 버전은 win32service.pyd의 기본 메시지 ID인 1을 반환합니다.

SMTPHandler

logging.handlers 모듈에 있는 SMTPHandler 클래스는 SMTP를 통해 전자 메일 주소로 로깅 메시지를 보내는 것을 지원합니다.

class logging.handlers.SMTPHandler(mailhost, fromaddr, toaddrs, subject, credentials=None, secure=None, timeout=1.0)

SMTPHandler 클래스의 새 인스턴스를 반환합니다. 인스턴스는 전자 메일의 보내는 주소, 받는 주소와 제목 줄을 사용하여 초기화됩니다. toaddrs 는 문자열 리스트여야 합니다. 비표준 SMTP 포트를 지정하려면, mailhost 인자에 (host, port) 튜플 형식을 사용하십시오. 문자열을 사용하면 표준 SMTP 포트가 사용됩니다. SMTP 서버가 인증을 요구하면, credentials 인자에 (username, password) 튜플을 지정할 수 있습니다.

보안 프로토콜(TLS)의 사용을 지정하려면, secure 인자에 튜플을 전달하십시오. 이것은 인증 자격 증명(credentials)이 제공될 때만 사용됩니다. 튜플은 빈 튜플이거나, 키 파일 이름을 가진 단일 값 튜플이거나, 키 파일과 인증서 파일의 이름을 가진 2-튜플이어야 합니다. (이 튜플은 smtplib.SMTP.starttls() 메서드에 전달됩니다.)

timeout 인자를 사용하여 SMTP 서버와의 통신에 시간제한을 지정할 수 있습니다.

버전 3.3에 추가: timeout 인자가 추가되었습니다.

emit(record)

레코드를 포맷하고 지정된 주소로 보냅니다.

getSubject(record)

레코드에 종속적인 제목 줄을 지정하려면, 이 메서드를 재정의하십시오.

MemoryHandler

logging.handlers 모듈에 있는 MemoryHandler 클래스는 메모리에 로깅 레코드를 버퍼링하고, 주기적으로 대상 (target) 처리기로 플러시 하는 것을 지원합니다. 플러시는 버퍼가 꽉 찼거나 특정 심각도 이상의 이벤트가 발생할 때마다 발생합니다.

MemoryHandler는 추상 클래스이면서, 더 일반적인 BufferingHandler의 서브 클래스입니다. 이것은 레코드 로깅을 메모리에 버퍼링합니다. 각 레코드가 버퍼에 추가될 때마다, shouldFlush()를 호출하여 버퍼를 플러시 할지 확인합니다. 필요하면, flush()가 플러시를 수행할 것으로 기대합니다.

class logging.handlers.BufferingHandler(capacity)

Initializes the handler with a buffer of the specified capacity. Here, capacity means the number of logging records buffered.

emit(record)

Append the record to the buffer. If shouldFlush() returns true, call flush() to process the buffer.

flush()

사용자 정의 플러시 동작을 구현하기 위해 재정의할 수 있습니다. 이 버전은 버퍼를 비우기만 합니다.

shouldFlush(record)

Return True if the buffer is up to capacity. This method can be overridden to implement custom flushing strategies.

class logging.handlers.MemoryHandler(capacity, flushLevel=ERROR, target=None, flushOnClose=True)

Returns a new instance of the MemoryHandler class. The instance is initialized with a buffer size of capacity (number of records buffered). If flushLevel is not specified, ERROR is used. If no target is specified, the target will need to be set using setTarget() before this handler does anything useful. If flushOnClose is specified as False, then the buffer is not flushed when the handler is closed. If not specified or specified as True, the previous behaviour of flushing the buffer will occur when the handler is closed.

버전 3.6에서 변경: flushOnClose 매개 변수가 추가되었습니다.

close()

flush()를 호출하고, 대상(target)을 None으로 설정하고, 버퍼를 비웁니다.

flush()

MemoryHandler의 경우, 플러시는 버퍼링 된 레코드가 있다면 대상으로 보내는 것을 뜻합니다. 이때 버퍼도 지워집니다. 다른 행동을 원하면 재정의하십시오.

setTarget(target)

이 처리기의 대상 처리기를 설정합니다.

shouldFlush(record)

버퍼 가득 참이나 레코드가 flushLevel 이상을 만드는지 확인합니다.

HTTPHandler

logging.handlers 모듈에 있는 HTTPHandler 클래스는 GET 또는 POST 를 사용해서 로깅 메시지를 웹 서버로 보내는 것을 지원합니다.

class logging.handlers.HTTPHandler(host, url, method='GET', secure=False, credentials=None, context=None)

HTTPHandler 클래스의 새 인스턴스를 반환합니다. host 는 특정 포트 번호를 사용해야 하면 host:port 형식일 수 있습니다. method 를 지정하지 않으면 GET이 사용됩니다. secure 가 참이면, HTTPS 연결이 사용됩니다. context 매개 변수는 ssl.SSLContext 인스턴스로 설정되어, HTTPS 연결에 사용되는 SSL 설정을 구성할 수 있습니다. credentials 가 지정되면, 기본 인증을 사용하여 HTTP ‘Authorization’ 헤더에 배치되는 사용자 ID와 암호로 구성된 2-튜플이어야 합니다. credentials를 지정하면, 사용자 ID와 암호가 단순 텍스트로 전달되지 않도록 secure=True를 지정해야 합니다.

버전 3.5에서 변경: context 매개 변수가 추가되었습니다.

mapLogRecord(record)

URL 인코딩되어 웹 서버로 전송되는, record에 기반한 딕셔너리를 제공합니다. 기본 구현은 record.__dict__를 반환합니다. 이 메서드는 재정의할 수 있는데, 예를 들어 LogRecord의 일부만 웹 서버로 보내지거나, 서버로 보내는 내용에 대한 보다 구체적인 사용자 정의가 필요한 경우입니다.

emit(record)

URL 인코딩된 딕셔너리로 웹 서버에 레코드를 보냅니다. mapLogRecord() 메서드가 레코드를 전송할 딕셔너리로 변환하는 데 사용됩니다.

참고

웹 서버로 보내기 위해 레코드를 준비하는 것은, 일반 포매팅 연산과 같지 않으므로, setFormatter()를 사용해서 HTTPHandler의 Formatter를 지정하는 것은 효과가 없습니다. format()을 호출하는 대신, 이 처리기는 mapLogRecord()를 호출한 다음, urllib.parse.urlencode()를 호출하여 웹 서버로 보내기에 적합한 형식으로 딕셔너리를 인코딩합니다.

QueueHandler

버전 3.2에 추가.

logging.handlers 모듈에 있는 QueueHandler 클래스는, queue 나 multiprocessing 모듈에 구현된 것과 같은 큐에 로깅 메시지를 보내는 것을 지원합니다.

QueueListener 클래스와 함께, QueueHandler를 사용하여 처리기가 로깅을 수행하는 스레드와 다른 스레드에서 작업을 수행하도록 할 수 있습니다. 이는 클라이언트를 처리하는 스레드가 가능한 한 신속하게 응답하고, 느린 작업(가령 SMTPHandler를 통해 전자 메일 보내기)은 별도의 스레드에서 수행되어야 하는 웹 응용 프로그램과 다른 서비스 응용 프로그램에서 중요합니다.

class logging.handlers.QueueHandler(queue)

Returns a new instance of the QueueHandler class. The instance is initialized with the queue to send messages to. The queue can be any queue-like object; it’s used as-is by the enqueue() method, which needs to know how to send messages to it. The queue is not required to have the task tracking API, which means that you can use SimpleQueue instances for queue.

emit(record)

Enqueues the result of preparing the LogRecord. Should an exception occur (e.g. because a bounded queue has filled up), the handleError() method is called to handle the error. This can result in the record silently being dropped (if logging.raiseExceptions is False) or a message printed to sys.stderr (if logging.raiseExceptions is True).

prepare(record)

큐에 넣기 위해 레코드를 준비합니다. 이 메서드에 의해 반환된 객체는 큐에 들어갑니다.

기본 구현은 메시지, 인자와 있다면 예외 정보를 병합하도록 레코드를 포맷합니다. 또한, 역 피클 할 수 없는 항목들을 레코드에서 직접(in-place) 제거합니다.

레코드를 dict 나 JSON 문자열로 변환하거나, 원본을 그대로 두고 레코드의 수정 된 복사본을 보내길 원한다면 이 메서드를 재정의할 수 있습니다.

enqueue(record)

put_nowait()를 사용하여 큐에 레코드를 넣습니다; 블로킹 동작이나 시간제한이나, 사용자 정의 큐 구현을 사용하려면 이 메서드를 재정의할 수 있습니다.

QueueListener

버전 3.2에 추가.

logging.handlers 모듈에 있는 QueueListener 클래스는 queue 나 multiprocessing 모듈에 구현된 것과 같은 큐에서 로깅 메시지를 수신하는 것을 지원합니다. 메시지는 내부 스레드의 큐에서 수신되고 처리를 위해 같은 스레드에서 하나 이상의 처리기로 전달됩니다. QueueListener 자체는 처리기가 아니지만, QueueHandler 와 함께 사용되기 때문에 여기에 설명되어 있습니다.

QueueHandler 클래스와 함께, QueueListener를 사용하여 처리기가 로깅을 수행하는 스레드와 다른 스레드에서 작업을 수행하도록 할 수 있습니다. 이는 클라이언트를 처리하는 스레드가 가능한 한 신속하게 응답하고, 느린 작업(가령 SMTPHandler를 통해 전자 메일 보내기)은 별도의 스레드에서 수행되어야 하는 웹 응용 프로그램과 다른 서비스 응용 프로그램에서 중요합니다.

class logging.handlers.QueueListener(queue, *handlers, respect_handler_level=False)

Returns a new instance of the QueueListener class. The instance is initialized with the queue to send messages to and a list of handlers which will handle entries placed on the queue. The queue can be any queue-like object; it’s passed as-is to the dequeue() method, which needs to know how to get messages from it. The queue is not required to have the task tracking API (though it’s used if available), which means that you can use SimpleQueue instances for queue.

If respect_handler_level is True, a handler’s level is respected (compared with the level for the message) when deciding whether to pass messages to that handler; otherwise, the behaviour is as in previous Python versions - to always pass each message to each handler.

버전 3.5에서 변경: The respect_handler_level argument was added.

dequeue(block)

레코드를 큐에서 꺼내 반환합니다. 선택적으로 블록 됩니다.

기본 구현은 get()을 사용합니다. 시간제한을 사용하거나 사용자 정의 큐 구현을 사용하려면 이 메서드를 재정의할 수 있습니다.

prepare(record)

처리를 위해 레코드를 준비합니다.

이 구현은 단지 전달된 레코드를 반환합니다. 사용자 정의 직렬화를 수행하거나 처리기에 전달하기 전에 레코드를 조작해야 하면, 이 메서드를 재정의할 수 있습니다.

handle(record)

레코드를 처리합니다.

이것은 단지 모든 처리기로 레코드를 제공합니다. 처리기에 전달되는 실제 객체는 prepare()에서 반환된 객체입니다.

start()

수신기를 시작합니다.

이것은 처리하기 위해 큐에서 LogRecord를 관찰하는 배경 스레드를 시작합니다.

stop()

수신기를 정지합니다.

스레드가 종료하도록 요청한 다음, 스레드가 종료할 때까지 대기합니다. 응용 프로그램이 종료되기 전에 이 함수를 호출하지 않으면, 레코드가 큐에 남아있을 수 있고, 이것들은 처리되지 않습니다.

enqueue_sentinel()

수신자에게 종료하도록 알리기 위해 큐에 종료 신호(sentinel)를 씁니다. 이 구현은 put_nowait()를 사용합니다. 시간제한을 사용하거나 사용자 정의 큐 구현을 사용하려면 이 메서드를 재정의할 수 있습니다.

버전 3.3에 추가.

더 보기

모듈 logging

logging 모듈에 관한 API 레퍼런스.

모듈 logging.config

logging 모듈용 구성 API.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

일반 운영 체제 서비스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

일반 운영 체제 서비스 »

|

getpass — 이식성 있는 암호 입력

소스 코드: Lib/getpass.py [https://github.com/python/cpython/tree/3.7/Lib/getpass.py]

getpass 모듈은 두 함수를 제공합니다:

getpass.getpass(prompt='Password: ', stream=None)

에코 없이 사용자에게 암호를 묻습니다. 사용자는 prompt 문자열을 사용하여 프롬프트 됩니다. 기본값은 'Password: '입니다. 유닉스에서 프롬프트는 필요하다면 replace 에러 처리기를 사용하여 파일류 객체 stream에 기록됩니다. stream는 제어 터미널(/dev/tty)이나 사용할 수 없으면 sys.stderr를 기본값으로 사용합니다 (이 인자는 윈도우에서 무시됩니다).

에코가 없는 입력을 사용할 수 없으면, getpass()는 stream에 경고 메시지를 인쇄하고, sys.stdin에서 읽고, GetPassWarning을 방출하는 것으로 돌아갑니다.

참고

IDLE 내에서 getpass를 호출하면, 대기 중인 창 자체가 아닌 IDLE을 시작한 터미널에서 입력이 수행될 수 있습니다.

exception getpass.GetPassWarning

패스워드 입력이 에코 될 때 방출되는 UserWarning 서브 클래스.

getpass.getuser()

사용자의 “로그인 이름”을 반환합니다.

이 함수는 환경 변수 LOGNAME, USER, LNAME 및 USERNAME를 순서대로 검사하고, 비어 있지 않은 문자열로 설정된 첫 번째 값을 반환합니다. 아무것도 설정되지 않았으면, pwd 모듈을 지원하는 시스템에서는 암호 데이터베이스의 로그인 이름이 반환되고, 그렇지 않으면 예외가 발생합니다.

일반적으로, 이 함수는 os.getlogin()보다 선호됩니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

일반 운영 체제 서비스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

일반 운영 체제 서비스 »

|

curses — Terminal handling for character-cell displays

The curses module provides an interface to the curses library, the de-facto standard for portable advanced terminal handling.

While curses is most widely used in the Unix environment, versions are available for Windows, DOS, and possibly other systems as well. This extension module is designed to match the API of ncurses, an open-source curses library hosted on Linux and the BSD variants of Unix.

참고

Whenever the documentation mentions a character it can be specified as an integer, a one-character Unicode string or a one-byte byte string.

Whenever the documentation mentions a character string it can be specified as a Unicode string or a byte string.

참고

Since version 5.4, the ncurses library decides how to interpret non-ASCII data using the nl_langinfo function. That means that you have to call locale.setlocale() in the application and encode Unicode strings using one of the system’s available encodings. This example uses the system’s default encoding:

import locale
locale.setlocale(locale.LC_ALL, '')
code = locale.getpreferredencoding()

Then use code as the encoding for str.encode() calls.

더 보기

Module curses.ascii

Utilities for working with ASCII characters, regardless of your locale settings.

Module curses.panel

A panel stack extension that adds depth to curses windows.

Module curses.textpad

Editable text widget for curses supporting Emacs-like bindings.

Curses Programming with Python

Tutorial material on using curses with Python, by Andrew Kuchling and Eric Raymond.

The Tools/demo/ [https://github.com/python/cpython/tree/3.7/Tools/demo/] directory in the Python source distribution contains some example programs using the curses bindings provided by this module.

Functions

The module curses defines the following exception:

exception curses.error

Exception raised when a curses library function returns an error.

참고

Whenever x or y arguments to a function or a method are optional, they default to the current cursor location. Whenever attr is optional, it defaults to A_NORMAL.

The module curses defines the following functions:

curses.baudrate()

Return the output speed of the terminal in bits per second. On software terminal emulators it will have a fixed high value. Included for historical reasons; in former times, it was used to write output loops for time delays and occasionally to change interfaces depending on the line speed.

curses.beep()

Emit a short attention sound.

curses.can_change_color()

Return True or False, depending on whether the programmer can change the colors displayed by the terminal.

curses.cbreak()

Enter cbreak mode. In cbreak mode (sometimes called “rare” mode) normal tty line buffering is turned off and characters are available to be read one by one. However, unlike raw mode, special characters (interrupt, quit, suspend, and flow control) retain their effects on the tty driver and calling program. Calling first raw() then cbreak() leaves the terminal in cbreak mode.

curses.color_content(color_number)

Return the intensity of the red, green, and blue (RGB) components in the color color_number, which must be between 0 and COLORS. Return a 3-tuple, containing the R,G,B values for the given color, which will be between 0 (no component) and 1000 (maximum amount of component).

curses.color_pair(color_number)

Return the attribute value for displaying text in the specified color. This attribute value can be combined with A_STANDOUT, A_REVERSE, and the other A_* attributes. pair_number() is the counterpart to this function.

curses.curs_set(visibility)

Set the cursor state. visibility can be set to 0, 1, or 2, for invisible, normal, or very visible. If the terminal supports the visibility requested, return the previous cursor state; otherwise raise an exception. On many terminals, the “visible” mode is an underline cursor and the “very visible” mode is a block cursor.

curses.def_prog_mode()

Save the current terminal mode as the “program” mode, the mode when the running program is using curses. (Its counterpart is the “shell” mode, for when the program is not in curses.) Subsequent calls to reset_prog_mode() will restore this mode.

curses.def_shell_mode()

Save the current terminal mode as the “shell” mode, the mode when the running program is not using curses. (Its counterpart is the “program” mode, when the program is using curses capabilities.) Subsequent calls to reset_shell_mode() will restore this mode.

curses.delay_output(ms)

Insert an ms millisecond pause in output.

curses.doupdate()

Update the physical screen. The curses library keeps two data structures, one representing the current physical screen contents and a virtual screen representing the desired next state. The doupdate() ground updates the physical screen to match the virtual screen.

The virtual screen may be updated by a noutrefresh() call after write operations such as addstr() have been performed on a window. The normal refresh() call is simply noutrefresh() followed by doupdate(); if you have to update multiple windows, you can speed performance and perhaps reduce screen flicker by issuing noutrefresh() calls on all windows, followed by a single doupdate().

curses.echo()

Enter echo mode. In echo mode, each character input is echoed to the screen as it is entered.

curses.endwin()

De-initialize the library, and return terminal to normal status.

curses.erasechar()

Return the user’s current erase character as a one-byte bytes object. Under Unix operating systems this is a property of the controlling tty of the curses program, and is not set by the curses library itself.

curses.filter()

The filter() routine, if used, must be called before initscr() is called. The effect is that, during those calls, LINES is set to 1; the capabilities clear, cup, cud, cud1, cuu1, cuu, vpa are disabled; and the home string is set to the value of cr. The effect is that the cursor is confined to the current line, and so are screen updates. This may be used for enabling character-at-a-time line editing without touching the rest of the screen.

curses.flash()

Flash the screen. That is, change it to reverse-video and then change it back in a short interval. Some people prefer such as ‘visible bell’ to the audible attention signal produced by beep().

curses.flushinp()

Flush all input buffers. This throws away any typeahead that has been typed by the user and has not yet been processed by the program.

curses.getmouse()

After getch() returns KEY_MOUSE to signal a mouse event, this method should be call to retrieve the queued mouse event, represented as a 5-tuple (id, x, y, z, bstate). id is an ID value used to distinguish multiple devices, and x, y, z are the event’s coordinates. (z is currently unused.) bstate is an integer value whose bits will be set to indicate the type of event, and will be the bitwise OR of one or more of the following constants, where n is the button number from 1 to 4: BUTTONn_PRESSED, BUTTONn_RELEASED, BUTTONn_CLICKED, BUTTONn_DOUBLE_CLICKED, BUTTONn_TRIPLE_CLICKED, BUTTON_SHIFT, BUTTON_CTRL, BUTTON_ALT.

curses.getsyx()

Return the current coordinates of the virtual screen cursor as a tuple (y, x). If leaveok is currently True, then return (-1, -1).

curses.getwin(file)

Read window related data stored in the file by an earlier putwin() call. The routine then creates and initializes a new window using that data, returning the new window object.

curses.has_colors()

Return True if the terminal can display colors; otherwise, return False.

curses.has_ic()

Return True if the terminal has insert- and delete-character capabilities. This function is included for historical reasons only, as all modern software terminal emulators have such capabilities.

curses.has_il()

Return True if the terminal has insert- and delete-line capabilities, or can simulate them using scrolling regions. This function is included for historical reasons only, as all modern software terminal emulators have such capabilities.

curses.has_key(ch)

Take a key value ch, and return True if the current terminal type recognizes a key with that value.

curses.halfdelay(tenths)

Used for half-delay mode, which is similar to cbreak mode in that characters typed by the user are immediately available to the program. However, after blocking for tenths tenths of seconds, raise an exception if nothing has been typed. The value of tenths must be a number between 1 and 255. Use nocbreak() to leave half-delay mode.

curses.init_color(color_number, r, g, b)

Change the definition of a color, taking the number of the color to be changed followed by three RGB values (for the amounts of red, green, and blue components). The value of color_number must be between 0 and COLORS. Each of r, g, b, must be a value between 0 and 1000. When init_color() is used, all occurrences of that color on the screen immediately change to the new definition. This function is a no-op on most terminals; it is active only if can_change_color() returns True.

curses.init_pair(pair_number, fg, bg)

Change the definition of a color-pair. It takes three arguments: the number of the color-pair to be changed, the foreground color number, and the background color number. The value of pair_number must be between 1 and COLOR_PAIRS - 1 (the 0 color pair is wired to white on black and cannot be changed). The value of fg and bg arguments must be between 0 and COLORS. If the color-pair was previously initialized, the screen is refreshed and all occurrences of that color-pair are changed to the new definition.

curses.initscr()

Initialize the library. Return a window object which represents the whole screen.

참고

If there is an error opening the terminal, the underlying curses library may cause the interpreter to exit.

curses.is_term_resized(nlines, ncols)

Return True if resize_term() would modify the window structure, False otherwise.

curses.isendwin()

Return True if endwin() has been called (that is, the curses library has been deinitialized).

curses.keyname(k)

Return the name of the key numbered k as a bytes object. The name of a key generating printable ASCII character is the key’s character. The name of a control-key combination is a two-byte bytes object consisting of a caret (b'^') followed by the corresponding printable ASCII character. The name of an alt-key combination (128–255) is a bytes object consisting of the prefix b'M-' followed by the name of the corresponding ASCII character.

curses.killchar()

Return the user’s current line kill character as a one-byte bytes object. Under Unix operating systems this is a property of the controlling tty of the curses program, and is not set by the curses library itself.

curses.longname()

Return a bytes object containing the terminfo long name field describing the current terminal. The maximum length of a verbose description is 128 characters. It is defined only after the call to initscr().

curses.meta(flag)

If flag is True, allow 8-bit characters to be input. If flag is False, allow only 7-bit chars.

curses.mouseinterval(interval)

Set the maximum time in milliseconds that can elapse between press and release events in order for them to be recognized as a click, and return the previous interval value. The default value is 200 msec, or one fifth of a second.

curses.mousemask(mousemask)

Set the mouse events to be reported, and return a tuple (availmask, oldmask). availmask indicates which of the specified mouse events can be reported; on complete failure it returns 0. oldmask is the previous value of the given window’s mouse event mask. If this function is never called, no mouse events are ever reported.

curses.napms(ms)

Sleep for ms milliseconds.

curses.newpad(nlines, ncols)

Create and return a pointer to a new pad data structure with the given number of lines and columns. Return a pad as a window object.

A pad is like a window, except that it is not restricted by the screen size, and is not necessarily associated with a particular part of the screen. Pads can be used when a large window is needed, and only a part of the window will be on the screen at one time. Automatic refreshes of pads (such as from scrolling or echoing of input) do not occur. The refresh() and noutrefresh() methods of a pad require 6 arguments to specify the part of the pad to be displayed and the location on the screen to be used for the display. The arguments are pminrow, pmincol, sminrow, smincol, smaxrow, smaxcol; the p arguments refer to the upper left corner of the pad region to be displayed and the s arguments define a clipping box on the screen within which the pad region is to be displayed.

curses.newwin(nlines, ncols)

curses.newwin(nlines, ncols, begin_y, begin_x)

Return a new window, whose left-upper corner is at (begin_y, begin_x), and whose height/width is nlines/ncols.

By default, the window will extend from the specified position to the lower right corner of the screen.

curses.nl()

Enter newline mode. This mode translates the return key into newline on input, and translates newline into return and line-feed on output. Newline mode is initially on.

curses.nocbreak()

Leave cbreak mode. Return to normal “cooked” mode with line buffering.

curses.noecho()

Leave echo mode. Echoing of input characters is turned off.

curses.nonl()

Leave newline mode. Disable translation of return into newline on input, and disable low-level translation of newline into newline/return on output (but this does not change the behavior of addch('\n'), which always does the equivalent of return and line feed on the virtual screen). With translation off, curses can sometimes speed up vertical motion a little; also, it will be able to detect the return key on input.

curses.noqiflush()

When the noqiflush() routine is used, normal flush of input and output queues associated with the INTR, QUIT and SUSP characters will not be done. You may want to call noqiflush() in a signal handler if you want output to continue as though the interrupt had not occurred, after the handler exits.

curses.noraw()

Leave raw mode. Return to normal “cooked” mode with line buffering.

curses.pair_content(pair_number)

Return a tuple (fg, bg) containing the colors for the requested color pair. The value of pair_number must be between 1 and COLOR_PAIRS - 1.

curses.pair_number(attr)

Return the number of the color-pair set by the attribute value attr. color_pair() is the counterpart to this function.

curses.putp(str)

Equivalent to tputs(str, 1, putchar); emit the value of a specified terminfo capability for the current terminal. Note that the output of putp() always goes to standard output.

curses.qiflush([flag])

If flag is False, the effect is the same as calling noqiflush(). If flag is True, or no argument is provided, the queues will be flushed when these control characters are read.

curses.raw()

Enter raw mode. In raw mode, normal line buffering and processing of interrupt, quit, suspend, and flow control keys are turned off; characters are presented to curses input functions one by one.

curses.reset_prog_mode()

Restore the terminal to “program” mode, as previously saved by def_prog_mode().

curses.reset_shell_mode()

Restore the terminal to “shell” mode, as previously saved by def_shell_mode().

curses.resetty()

Restore the state of the terminal modes to what it was at the last call to savetty().

curses.resize_term(nlines, ncols)

Backend function used by resizeterm(), performing most of the work; when resizing the windows, resize_term() blank-fills the areas that are extended. The calling application should fill in these areas with appropriate data. The resize_term() function attempts to resize all windows. However, due to the calling convention of pads, it is not possible to resize these without additional interaction with the application.

curses.resizeterm(nlines, ncols)

Resize the standard and current windows to the specified dimensions, and adjusts other bookkeeping data used by the curses library that record the window dimensions (in particular the SIGWINCH handler).

curses.savetty()

Save the current state of the terminal modes in a buffer, usable by resetty().

curses.setsyx(y, x)

Set the virtual screen cursor to y, x. If y and x are both -1, then leaveok is set True.

curses.setupterm(term=None, fd=-1)

Initialize the terminal. term is a string giving the terminal name, or None; if omitted or None, the value of the TERM environment variable will be used. fd is the file descriptor to which any initialization sequences will be sent; if not supplied or -1, the file descriptor for sys.stdout will be used.

curses.start_color()

Must be called if the programmer wants to use colors, and before any other color manipulation routine is called. It is good practice to call this routine right after initscr().

start_color() initializes eight basic colors (black, red, green, yellow, blue, magenta, cyan, and white), and two global variables in the curses module, COLORS and COLOR_PAIRS, containing the maximum number of colors and color-pairs the terminal can support. It also restores the colors on the terminal to the values they had when the terminal was just turned on.

curses.termattrs()

Return a logical OR of all video attributes supported by the terminal. This information is useful when a curses program needs complete control over the appearance of the screen.

curses.termname()

Return the value of the environment variable TERM, as a bytes object, truncated to 14 characters.

curses.tigetflag(capname)

Return the value of the Boolean capability corresponding to the terminfo capability name capname as an integer. Return the value -1 if capname is not a Boolean capability, or 0 if it is canceled or absent from the terminal description.

curses.tigetnum(capname)

Return the value of the numeric capability corresponding to the terminfo capability name capname as an integer. Return the value -2 if capname is not a numeric capability, or -1 if it is canceled or absent from the terminal description.

curses.tigetstr(capname)

Return the value of the string capability corresponding to the terminfo capability name capname as a bytes object. Return None if capname is not a terminfo “string capability”, or is canceled or absent from the terminal description.

curses.tparm(str[, ...])

Instantiate the bytes object str with the supplied parameters, where str should be a parameterized string obtained from the terminfo database. E.g. tparm(tigetstr("cup"), 5, 3) could result in b'\033[6;4H', the exact result depending on terminal type.

curses.typeahead(fd)

Specify that the file descriptor fd be used for typeahead checking. If fd is -1, then no typeahead checking is done.

The curses library does “line-breakout optimization” by looking for typeahead periodically while updating the screen. If input is found, and it is coming from a tty, the current update is postponed until refresh or doupdate is called again, allowing faster response to commands typed in advance. This function allows specifying a different file descriptor for typeahead checking.

curses.unctrl(ch)

Return a bytes object which is a printable representation of the character ch. Control characters are represented as a caret followed by the character, for example as b'^C'. Printing characters are left as they are.

curses.ungetch(ch)

Push ch so the next getch() will return it.

참고

Only one ch can be pushed before getch() is called.

curses.update_lines_cols()

Update LINES and COLS. Useful for detecting manual screen resize.

버전 3.5에 추가.

curses.unget_wch(ch)

Push ch so the next get_wch() will return it.

참고

Only one ch can be pushed before get_wch() is called.

버전 3.3에 추가.

curses.ungetmouse(id, x, y, z, bstate)

Push a KEY_MOUSE event onto the input queue, associating the given state data with it.

curses.use_env(flag)

If used, this function should be called before initscr() or newterm are called. When flag is False, the values of lines and columns specified in the terminfo database will be used, even if environment variables LINES and COLUMNS (used by default) are set, or if curses is running in a window (in which case default behavior would be to use the window size if LINES and COLUMNS are not set).

curses.use_default_colors()

Allow use of default values for colors on terminals supporting this feature. Use this to support transparency in your application. The default color is assigned to the color number -1. After calling this function, init_pair(x, curses.COLOR_RED, -1) initializes, for instance, color pair x to a red foreground color on the default background.

curses.wrapper(func, ...)

Initialize curses and call another callable object, func, which should be the rest of your curses-using application. If the application raises an exception, this function will restore the terminal to a sane state before re-raising the exception and generating a traceback. The callable object func is then passed the main window ‘stdscr’ as its first argument, followed by any other arguments passed to wrapper(). Before calling func, wrapper() turns on cbreak mode, turns off echo, enables the terminal keypad, and initializes colors if the terminal has color support. On exit (whether normally or by exception) it restores cooked mode, turns on echo, and disables the terminal keypad.

Window Objects

Window objects, as returned by initscr() and newwin() above, have the following methods and attributes:

window.addch(ch[, attr])

window.addch(y, x, ch[, attr])

Paint character ch at (y, x) with attributes attr, overwriting any character previously painter at that location. By default, the character position and attributes are the current settings for the window object.

참고

Writing outside the window, subwindow, or pad raises a curses.error. Attempting to write to the lower right corner of a window, subwindow, or pad will cause an exception to be raised after the character is printed.

window.addnstr(str, n[, attr])

window.addnstr(y, x, str, n[, attr])

Paint at most n characters of the character string str at (y, x) with attributes attr, overwriting anything previously on the display.

window.addstr(str[, attr])

window.addstr(y, x, str[, attr])

Paint the character string str at (y, x) with attributes attr, overwriting anything previously on the display.

참고

Writing outside the window, subwindow, or pad raises curses.error. Attempting to write to the lower right corner of a window, subwindow, or pad will cause an exception to be raised after the string is printed.

window.attroff(attr)

Remove attribute attr from the “background” set applied to all writes to the current window.

window.attron(attr)

Add attribute attr from the “background” set applied to all writes to the current window.

window.attrset(attr)

Set the “background” set of attributes to attr. This set is initially 0 (no attributes).

window.bkgd(ch[, attr])

Set the background property of the window to the character ch, with attributes attr. The change is then applied to every character position in that window:

The attribute of every character in the window is changed to the new background attribute.

Wherever the former background character appears, it is changed to the new background character.

window.bkgdset(ch[, attr])

Set the window’s background. A window’s background consists of a character and any combination of attributes. The attribute part of the background is combined (OR’ed) with all non-blank characters that are written into the window. Both the character and attribute parts of the background are combined with the blank characters. The background becomes a property of the character and moves with the character through any scrolling and insert/delete line/character operations.

window.border([ls[, rs[, ts[, bs[, tl[, tr[, bl[, br]]]]]]]])

Draw a border around the edges of the window. Each parameter specifies the character to use for a specific part of the border; see the table below for more details.

참고

A 0 value for any parameter will cause the default character to be used for that parameter. Keyword parameters can not be used. The defaults are listed in this table:

Parameter

Description

Default value

ls

Left side

ACS_VLINE

rs

Right side

ACS_VLINE

ts

Top

ACS_HLINE

bs

Bottom

ACS_HLINE

tl

Upper-left corner

ACS_ULCORNER

tr

Upper-right corner

ACS_URCORNER

bl

Bottom-left corner

ACS_LLCORNER

br

Bottom-right corner

ACS_LRCORNER

window.box([vertch, horch])

Similar to border(), but both ls and rs are vertch and both ts and bs are horch. The default corner characters are always used by this function.

window.chgat(attr)

window.chgat(num, attr)

window.chgat(y, x, attr)

window.chgat(y, x, num, attr)

Set the attributes of num characters at the current cursor position, or at position (y, x) if supplied. If num is not given or is -1, the attribute will be set on all the characters to the end of the line. This function moves cursor to position (y, x) if supplied. The changed line will be touched using the touchline() method so that the contents will be redisplayed by the next window refresh.

window.clear()

Like erase(), but also cause the whole window to be repainted upon next call to refresh().

window.clearok(flag)

If flag is True, the next call to refresh() will clear the window completely.

window.clrtobot()

Erase from cursor to the end of the window: all lines below the cursor are deleted, and then the equivalent of clrtoeol() is performed.

window.clrtoeol()

Erase from cursor to the end of the line.

window.cursyncup()

Update the current cursor position of all the ancestors of the window to reflect the current cursor position of the window.

window.delch([y, x])

Delete any character at (y, x).

window.deleteln()

Delete the line under the cursor. All following lines are moved up by one line.

window.derwin(begin_y, begin_x)

window.derwin(nlines, ncols, begin_y, begin_x)

An abbreviation for “derive window”, derwin() is the same as calling subwin(), except that begin_y and begin_x are relative to the origin of the window, rather than relative to the entire screen. Return a window object for the derived window.

window.echochar(ch[, attr])

Add character ch with attribute attr, and immediately call refresh() on the window.

window.enclose(y, x)

Test whether the given pair of screen-relative character-cell coordinates are enclosed by the given window, returning True or False. It is useful for determining what subset of the screen windows enclose the location of a mouse event.

window.encoding

Encoding used to encode method arguments (Unicode strings and characters). The encoding attribute is inherited from the parent window when a subwindow is created, for example with window.subwin(). By default, the locale encoding is used (see locale.getpreferredencoding()).

버전 3.3에 추가.

window.erase()

Clear the window.

window.getbegyx()

Return a tuple (y, x) of co-ordinates of upper-left corner.

window.getbkgd()

Return the given window’s current background character/attribute pair.

window.getch([y, x])

Get a character. Note that the integer returned does not have to be in ASCII range: function keys, keypad keys and so on are represented by numbers higher than 255. In no-delay mode, return -1 if there is no input, otherwise wait until a key is pressed.

window.get_wch([y, x])

Get a wide character. Return a character for most keys, or an integer for function keys, keypad keys, and other special keys. In no-delay mode, raise an exception if there is no input.

버전 3.3에 추가.

window.getkey([y, x])

Get a character, returning a string instead of an integer, as getch() does. Function keys, keypad keys and other special keys return a multibyte string containing the key name. In no-delay mode, raise an exception if there is no input.

window.getmaxyx()

Return a tuple (y, x) of the height and width of the window.

window.getparyx()

Return the beginning coordinates of this window relative to its parent window as a tuple (y, x). Return (-1, -1) if this window has no parent.

window.getstr()

window.getstr(n)

window.getstr(y, x)

window.getstr(y, x, n)

Read a bytes object from the user, with primitive line editing capacity.

window.getyx()

Return a tuple (y, x) of current cursor position relative to the window’s upper-left corner.

window.hline(ch, n)

window.hline(y, x, ch, n)

Display a horizontal line starting at (y, x) with length n consisting of the character ch.

window.idcok(flag)

If flag is False, curses no longer considers using the hardware insert/delete character feature of the terminal; if flag is True, use of character insertion and deletion is enabled. When curses is first initialized, use of character insert/delete is enabled by default.

window.idlok(flag)

If flag is True, curses will try and use hardware line editing facilities. Otherwise, line insertion/deletion are disabled.

window.immedok(flag)

If flag is True, any change in the window image automatically causes the window to be refreshed; you no longer have to call refresh() yourself. However, it may degrade performance considerably, due to repeated calls to wrefresh. This option is disabled by default.

window.inch([y, x])

Return the character at the given position in the window. The bottom 8 bits are the character proper, and upper bits are the attributes.

window.insch(ch[, attr])

window.insch(y, x, ch[, attr])

Paint character ch at (y, x) with attributes attr, moving the line from position x right by one character.

window.insdelln(nlines)

Insert nlines lines into the specified window above the current line. The nlines bottom lines are lost. For negative nlines, delete nlines lines starting with the one under the cursor, and move the remaining lines up. The bottom nlines lines are cleared. The current cursor position remains the same.

window.insertln()

Insert a blank line under the cursor. All following lines are moved down by one line.

window.insnstr(str, n[, attr])

window.insnstr(y, x, str, n[, attr])

Insert a character string (as many characters as will fit on the line) before the character under the cursor, up to n characters. If n is zero or negative, the entire string is inserted. All characters to the right of the cursor are shifted right, with the rightmost characters on the line being lost. The cursor position does not change (after moving to y, x, if specified).

window.insstr(str[, attr])

window.insstr(y, x, str[, attr])

Insert a character string (as many characters as will fit on the line) before the character under the cursor. All characters to the right of the cursor are shifted right, with the rightmost characters on the line being lost. The cursor position does not change (after moving to y, x, if specified).

window.instr([n])

window.instr(y, x[, n])

Return a bytes object of characters, extracted from the window starting at the current cursor position, or at y, x if specified. Attributes are stripped from the characters. If n is specified, instr() returns a string at most n characters long (exclusive of the trailing NUL).

window.is_linetouched(line)

Return True if the specified line was modified since the last call to refresh(); otherwise return False. Raise a curses.error exception if line is not valid for the given window.

window.is_wintouched()

Return True if the specified window was modified since the last call to refresh(); otherwise return False.

window.keypad(flag)

If flag is True, escape sequences generated by some keys (keypad, function keys) will be interpreted by curses. If flag is False, escape sequences will be left as is in the input stream.

window.leaveok(flag)

If flag is True, cursor is left where it is on update, instead of being at “cursor position.” This reduces cursor movement where possible. If possible the cursor will be made invisible.

If flag is False, cursor will always be at “cursor position” after an update.

window.move(new_y, new_x)

Move cursor to (new_y, new_x).

window.mvderwin(y, x)

Move the window inside its parent window. The screen-relative parameters of the window are not changed. This routine is used to display different parts of the parent window at the same physical position on the screen.

window.mvwin(new_y, new_x)

Move the window so its upper-left corner is at (new_y, new_x).

window.nodelay(flag)

If flag is True, getch() will be non-blocking.

window.notimeout(flag)

If flag is True, escape sequences will not be timed out.

If flag is False, after a few milliseconds, an escape sequence will not be interpreted, and will be left in the input stream as is.

window.noutrefresh()

Mark for refresh but wait. This function updates the data structure representing the desired state of the window, but does not force an update of the physical screen. To accomplish that, call doupdate().

window.overlay(destwin[, sminrow, smincol, dminrow, dmincol, dmaxrow, dmaxcol])

Overlay the window on top of destwin. The windows need not be the same size, only the overlapping region is copied. This copy is non-destructive, which means that the current background character does not overwrite the old contents of destwin.

To get fine-grained control over the copied region, the second form of overlay() can be used. sminrow and smincol are the upper-left coordinates of the source window, and the other variables mark a rectangle in the destination window.

window.overwrite(destwin[, sminrow, smincol, dminrow, dmincol, dmaxrow, dmaxcol])

Overwrite the window on top of destwin. The windows need not be the same size, in which case only the overlapping region is copied. This copy is destructive, which means that the current background character overwrites the old contents of destwin.

To get fine-grained control over the copied region, the second form of overwrite() can be used. sminrow and smincol are the upper-left coordinates of the source window, the other variables mark a rectangle in the destination window.

window.putwin(file)

Write all data associated with the window into the provided file object. This information can be later retrieved using the getwin() function.

window.redrawln(beg, num)

Indicate that the num screen lines, starting at line beg, are corrupted and should be completely redrawn on the next refresh() call.

window.redrawwin()

Touch the entire window, causing it to be completely redrawn on the next refresh() call.

window.refresh([pminrow, pmincol, sminrow, smincol, smaxrow, smaxcol])

Update the display immediately (sync actual screen with previous drawing/deleting methods).

The 6 optional arguments can only be specified when the window is a pad created with newpad(). The additional parameters are needed to indicate what part of the pad and screen are involved. pminrow and pmincol specify the upper left-hand corner of the rectangle to be displayed in the pad. sminrow, smincol, smaxrow, and smaxcol specify the edges of the rectangle to be displayed on the screen. The lower right-hand corner of the rectangle to be displayed in the pad is calculated from the screen coordinates, since the rectangles must be the same size. Both rectangles must be entirely contained within their respective structures. Negative values of pminrow, pmincol, sminrow, or smincol are treated as if they were zero.

window.resize(nlines, ncols)

Reallocate storage for a curses window to adjust its dimensions to the specified values. If either dimension is larger than the current values, the window’s data is filled with blanks that have the current background rendition (as set by bkgdset()) merged into them.

window.scroll([lines=1])

Scroll the screen or scrolling region upward by lines lines.

window.scrollok(flag)

Control what happens when the cursor of a window is moved off the edge of the window or scrolling region, either as a result of a newline action on the bottom line, or typing the last character of the last line. If flag is False, the cursor is left on the bottom line. If flag is True, the window is scrolled up one line. Note that in order to get the physical scrolling effect on the terminal, it is also necessary to call idlok().

window.setscrreg(top, bottom)

Set the scrolling region from line top to line bottom. All scrolling actions will take place in this region.

window.standend()

Turn off the standout attribute. On some terminals this has the side effect of turning off all attributes.

window.standout()

Turn on attribute A_STANDOUT.

window.subpad(begin_y, begin_x)

window.subpad(nlines, ncols, begin_y, begin_x)

Return a sub-window, whose upper-left corner is at (begin_y, begin_x), and whose width/height is ncols/nlines.

window.subwin(begin_y, begin_x)

window.subwin(nlines, ncols, begin_y, begin_x)

Return a sub-window, whose upper-left corner is at (begin_y, begin_x), and whose width/height is ncols/nlines.

By default, the sub-window will extend from the specified position to the lower right corner of the window.

window.syncdown()

Touch each location in the window that has been touched in any of its ancestor windows. This routine is called by refresh(), so it should almost never be necessary to call it manually.

window.syncok(flag)

If flag is True, then syncup() is called automatically whenever there is a change in the window.

window.syncup()

Touch all locations in ancestors of the window that have been changed in the window.

window.timeout(delay)

Set blocking or non-blocking read behavior for the window. If delay is negative, blocking read is used (which will wait indefinitely for input). If delay is zero, then non-blocking read is used, and getch() will return -1 if no input is waiting. If delay is positive, then getch() will block for delay milliseconds, and return -1 if there is still no input at the end of that time.

window.touchline(start, count[, changed])

Pretend count lines have been changed, starting with line start. If changed is supplied, it specifies whether the affected lines are marked as having been changed (changed=True) or unchanged (changed=False).

window.touchwin()

Pretend the whole window has been changed, for purposes of drawing optimizations.

window.untouchwin()

Mark all lines in the window as unchanged since the last call to refresh().

window.vline(ch, n)

window.vline(y, x, ch, n)

Display a vertical line starting at (y, x) with length n consisting of the character ch.

Constants

The curses module defines the following data members:

curses.ERR

Some curses routines that return an integer, such as getch(), return ERR upon failure.

curses.OK

Some curses routines that return an integer, such as napms(), return OK upon success.

curses.version

A bytes object representing the current version of the module. Also available as __version__.

Some constants are available to specify character cell attributes. The exact constants available are system dependent.

Attribute

Meaning

A_ALTCHARSET

Alternate character set mode

A_BLINK

Blink mode

A_BOLD

Bold mode

A_DIM

Dim mode

A_INVIS

Invisible or blank mode

A_ITALIC

Italic mode

A_NORMAL

Normal attribute

A_PROTECT

Protected mode

A_REVERSE

Reverse background and foreground colors

A_STANDOUT

Standout mode

A_UNDERLINE

Underline mode

A_HORIZONTAL

Horizontal highlight

A_LEFT

Left highlight

A_LOW

Low highlight

A_RIGHT

Right highlight

A_TOP

Top highlight

A_VERTICAL

Vertical highlight

A_CHARTEXT

Bit-mask to extract a character

버전 3.7에 추가: A_ITALIC was added.

Several constants are available to extract corresponding attributes returned by some methods.

Bit-mask

Meaning

A_ATTRIBUTES

Bit-mask to extract attributes

A_CHARTEXT

Bit-mask to extract a character

A_COLOR

Bit-mask to extract color-pair field information

Keys are referred to by integer constants with names starting with KEY_. The exact keycaps available are system dependent.

Key constant

Key

KEY_MIN

Minimum key value

KEY_BREAK

Break key (unreliable)

KEY_DOWN

Down-arrow

KEY_UP

Up-arrow

KEY_LEFT

Left-arrow

KEY_RIGHT

Right-arrow

KEY_HOME

Home key (upward+left arrow)

KEY_BACKSPACE

Backspace (unreliable)

KEY_F0

Function keys. Up to 64 function keys are supported.

KEY_Fn

Value of function key n

KEY_DL

Delete line

KEY_IL

Insert line

KEY_DC

Delete character

KEY_IC

Insert char or enter insert mode

KEY_EIC

Exit insert char mode

KEY_CLEAR

Clear screen

KEY_EOS

Clear to end of screen

KEY_EOL

Clear to end of line

KEY_SF

Scroll 1 line forward

KEY_SR

Scroll 1 line backward (reverse)

KEY_NPAGE

Next page

KEY_PPAGE

Previous page

KEY_STAB

Set tab

KEY_CTAB

Clear tab

KEY_CATAB

Clear all tabs

KEY_ENTER

Enter or send (unreliable)

KEY_SRESET

Soft (partial) reset (unreliable)

KEY_RESET

Reset or hard reset (unreliable)

KEY_PRINT

Print

KEY_LL

Home down or bottom (lower left)

KEY_A1

Upper left of keypad

KEY_A3

Upper right of keypad

KEY_B2

Center of keypad

KEY_C1

Lower left of keypad

KEY_C3

Lower right of keypad

KEY_BTAB

Back tab

KEY_BEG

Beg (beginning)

KEY_CANCEL

Cancel

KEY_CLOSE

Close

KEY_COMMAND

Cmd (command)

KEY_COPY

Copy

KEY_CREATE

Create

KEY_END

End

KEY_EXIT

Exit

KEY_FIND

Find

KEY_HELP

Help

KEY_MARK

Mark

KEY_MESSAGE

Message

KEY_MOVE

Move

KEY_NEXT

Next

KEY_OPEN

Open

KEY_OPTIONS

Options

KEY_PREVIOUS

Prev (previous)

KEY_REDO

Redo

KEY_REFERENCE

Ref (reference)

KEY_REFRESH

Refresh

KEY_REPLACE

Replace

KEY_RESTART

Restart

KEY_RESUME

Resume

KEY_SAVE

Save

KEY_SBEG

Shifted Beg (beginning)

KEY_SCANCEL

Shifted Cancel

KEY_SCOMMAND

Shifted Command

KEY_SCOPY

Shifted Copy

KEY_SCREATE

Shifted Create

KEY_SDC

Shifted Delete char

KEY_SDL

Shifted Delete line

KEY_SELECT

Select

KEY_SEND

Shifted End

KEY_SEOL

Shifted Clear line

KEY_SEXIT

Shifted Exit

KEY_SFIND

Shifted Find

KEY_SHELP

Shifted Help

KEY_SHOME

Shifted Home

KEY_SIC

Shifted Input

KEY_SLEFT

Shifted Left arrow

KEY_SMESSAGE

Shifted Message

KEY_SMOVE

Shifted Move

KEY_SNEXT

Shifted Next

KEY_SOPTIONS

Shifted Options

KEY_SPREVIOUS

Shifted Prev

KEY_SPRINT

Shifted Print

KEY_SREDO

Shifted Redo

KEY_SREPLACE

Shifted Replace

KEY_SRIGHT

Shifted Right arrow

KEY_SRSUME

Shifted Resume

KEY_SSAVE

Shifted Save

KEY_SSUSPEND

Shifted Suspend

KEY_SUNDO

Shifted Undo

KEY_SUSPEND

Suspend

KEY_UNDO

Undo

KEY_MOUSE

Mouse event has occurred

KEY_RESIZE

Terminal resize event

KEY_MAX

Maximum key value

On VT100s and their software emulations, such as X terminal emulators, there are normally at least four function keys (KEY_F1, KEY_F2, KEY_F3, KEY_F4) available, and the arrow keys mapped to KEY_UP, KEY_DOWN, KEY_LEFT and KEY_RIGHT in the obvious way. If your machine has a PC keyboard, it is safe to expect arrow keys and twelve function keys (older PC keyboards may have only ten function keys); also, the following keypad mappings are standard:

Keycap

Constant

Insert

KEY_IC

Delete

KEY_DC

Home

KEY_HOME

End

KEY_END

Page Up

KEY_PPAGE

Page Down

KEY_NPAGE

The following table lists characters from the alternate character set. These are inherited from the VT100 terminal, and will generally be available on software emulations such as X terminals. When there is no graphic available, curses falls back on a crude printable ASCII approximation.

참고

These are available only after initscr() has been called.

ACS code

Meaning

ACS_BBSS

alternate name for upper right corner

ACS_BLOCK

solid square block

ACS_BOARD

board of squares

ACS_BSBS

alternate name for horizontal line

ACS_BSSB

alternate name for upper left corner

ACS_BSSS

alternate name for top tee

ACS_BTEE

bottom tee

ACS_BULLET

bullet

ACS_CKBOARD

checker board (stipple)

ACS_DARROW

arrow pointing down

ACS_DEGREE

degree symbol

ACS_DIAMOND

diamond

ACS_GEQUAL

greater-than-or-equal-to

ACS_HLINE

horizontal line

ACS_LANTERN

lantern symbol

ACS_LARROW

left arrow

ACS_LEQUAL

less-than-or-equal-to

ACS_LLCORNER

lower left-hand corner

ACS_LRCORNER

lower right-hand corner

ACS_LTEE

left tee

ACS_NEQUAL

not-equal sign

ACS_PI

letter pi

ACS_PLMINUS

plus-or-minus sign

ACS_PLUS

big plus sign

ACS_RARROW

right arrow

ACS_RTEE

right tee

ACS_S1

scan line 1

ACS_S3

scan line 3

ACS_S7

scan line 7

ACS_S9

scan line 9

ACS_SBBS

alternate name for lower right corner

ACS_SBSB

alternate name for vertical line

ACS_SBSS

alternate name for right tee

ACS_SSBB

alternate name for lower left corner

ACS_SSBS

alternate name for bottom tee

ACS_SSSB

alternate name for left tee

ACS_SSSS

alternate name for crossover or big plus

ACS_STERLING

pound sterling

ACS_TTEE

top tee

ACS_UARROW

up arrow

ACS_ULCORNER

upper left corner

ACS_URCORNER

upper right corner

ACS_VLINE

vertical line

The following table lists the predefined colors:

Constant

Color

COLOR_BLACK

Black

COLOR_BLUE

Blue

COLOR_CYAN

Cyan (light greenish blue)

COLOR_GREEN

Green

COLOR_MAGENTA

Magenta (purplish red)

COLOR_RED

Red

COLOR_WHITE

White

COLOR_YELLOW

Yellow

curses.textpad — Text input widget for curses programs

The curses.textpad module provides a Textbox class that handles elementary text editing in a curses window, supporting a set of keybindings resembling those of Emacs (thus, also of Netscape Navigator, BBedit 6.x, FrameMaker, and many other programs). The module also provides a rectangle-drawing function useful for framing text boxes or for other purposes.

The module curses.textpad defines the following function:

curses.textpad.rectangle(win, uly, ulx, lry, lrx)

Draw a rectangle. The first argument must be a window object; the remaining arguments are coordinates relative to that window. The second and third arguments are the y and x coordinates of the upper left hand corner of the rectangle to be drawn; the fourth and fifth arguments are the y and x coordinates of the lower right hand corner. The rectangle will be drawn using VT100/IBM PC forms characters on terminals that make this possible (including xterm and most other software terminal emulators). Otherwise it will be drawn with ASCII dashes, vertical bars, and plus signs.

Textbox objects

You can instantiate a Textbox object as follows:

class curses.textpad.Textbox(win)

Return a textbox widget object. The win argument should be a curses window object in which the textbox is to be contained. The edit cursor of the textbox is initially located at the upper left hand corner of the containing window, with coordinates (0, 0). The instance’s stripspaces flag is initially on.

Textbox objects have the following methods:

edit([validator])

This is the entry point you will normally use. It accepts editing keystrokes until one of the termination keystrokes is entered. If validator is supplied, it must be a function. It will be called for each keystroke entered with the keystroke as a parameter; command dispatch is done on the result. This method returns the window contents as a string; whether blanks in the window are included is affected by the stripspaces attribute.

do_command(ch)

Process a single command keystroke. Here are the supported special keystrokes:

Keystroke

Action

Control-A

Go to left edge of window.

Control-B

Cursor left, wrapping to previous line if appropriate.

Control-D

Delete character under cursor.

Control-E

Go to right edge (stripspaces off) or end of line (stripspaces on).

Control-F

Cursor right, wrapping to next line when appropriate.

Control-G

Terminate, returning the window contents.

Control-H

Delete character backward.

Control-J

Terminate if the window is 1 line, otherwise insert newline.

Control-K

If line is blank, delete it, otherwise clear to end of line.

Control-L

Refresh screen.

Control-N

Cursor down; move down one line.

Control-O

Insert a blank line at cursor location.

Control-P

Cursor up; move up one line.

Move operations do nothing if the cursor is at an edge where the movement is not possible. The following synonyms are supported where possible:

Constant

Keystroke

KEY_LEFT

Control-B

KEY_RIGHT

Control-F

KEY_UP

Control-P

KEY_DOWN

Control-N

KEY_BACKSPACE

Control-h

All other keystrokes are treated as a command to insert the given character and move right (with line wrapping).

gather()

Return the window contents as a string; whether blanks in the window are included is affected by the stripspaces member.

stripspaces

This attribute is a flag which controls the interpretation of blanks in the window. When it is on, trailing blanks on each line are ignored; any cursor motion that would land the cursor on a trailing blank goes to the end of that line instead, and trailing blanks are stripped when the window contents are gathered.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

일반 운영 체제 서비스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

일반 운영 체제 서비스 »

|

curses.ascii — Utilities for ASCII characters

The curses.ascii module supplies name constants for ASCII characters and functions to test membership in various ASCII character classes. The constants supplied are names for control characters as follows:

Name

Meaning

NUL

SOH

Start of heading, console interrupt

STX

Start of text

ETX

End of text

EOT

End of transmission

ENQ

Enquiry, goes with ACK flow control

ACK

Acknowledgement

BEL

Bell

BS

Backspace

TAB

Tab

HT

Alias for TAB: “Horizontal tab”

LF

Line feed

NL

Alias for LF: “New line”

VT

Vertical tab

FF

Form feed

CR

Carriage return

SO

Shift-out, begin alternate character set

SI

Shift-in, resume default character set

DLE

Data-link escape

DC1

XON, for flow control

DC2

Device control 2, block-mode flow control

DC3

XOFF, for flow control

DC4

Device control 4

NAK

Negative acknowledgement

SYN

Synchronous idle

ETB

End transmission block

CAN

Cancel

EM

End of medium

SUB

Substitute

ESC

Escape

FS

File separator

GS

Group separator

RS

Record separator, block-mode terminator

US

Unit separator

SP

Space

DEL

Delete

Note that many of these have little practical significance in modern usage. The mnemonics derive from teleprinter conventions that predate digital computers.

The module supplies the following functions, patterned on those in the standard C library:

curses.ascii.isalnum(c)

Checks for an ASCII alphanumeric character; it is equivalent to isalpha(c) or isdigit(c).

curses.ascii.isalpha(c)

Checks for an ASCII alphabetic character; it is equivalent to isupper(c) or islower(c).

curses.ascii.isascii(c)

Checks for a character value that fits in the 7-bit ASCII set.

curses.ascii.isblank(c)

Checks for an ASCII whitespace character; space or horizontal tab.

curses.ascii.iscntrl(c)

Checks for an ASCII control character (in the range 0x00 to 0x1f or 0x7f).

curses.ascii.isdigit(c)

Checks for an ASCII decimal digit, '0' through '9'. This is equivalent to c in string.digits.

curses.ascii.isgraph(c)

Checks for ASCII any printable character except space.

curses.ascii.islower(c)

Checks for an ASCII lower-case character.

curses.ascii.isprint(c)

Checks for any ASCII printable character including space.

curses.ascii.ispunct(c)

Checks for any printable ASCII character which is not a space or an alphanumeric character.

curses.ascii.isspace(c)

Checks for ASCII white-space characters; space, line feed, carriage return, form feed, horizontal tab, vertical tab.

curses.ascii.isupper(c)

Checks for an ASCII uppercase letter.

curses.ascii.isxdigit(c)

Checks for an ASCII hexadecimal digit. This is equivalent to c in string.hexdigits.

curses.ascii.isctrl(c)

Checks for an ASCII control character (ordinal values 0 to 31).

curses.ascii.ismeta(c)

Checks for a non-ASCII character (ordinal values 0x80 and above).

These functions accept either integers or single-character strings; when the argument is a string, it is first converted using the built-in function ord().

Note that all these functions check ordinal bit values derived from the character of the string you pass in; they do not actually know anything about the host machine’s character encoding.

The following two functions take either a single-character string or integer byte value; they return a value of the same type.

curses.ascii.ascii(c)

Return the ASCII value corresponding to the low 7 bits of c.

curses.ascii.ctrl(c)

Return the control character corresponding to the given character (the character bit value is bitwise-anded with 0x1f).

curses.ascii.alt(c)

Return the 8-bit character corresponding to the given ASCII character (the character bit value is bitwise-ored with 0x80).

The following function takes either a single-character string or integer value; it returns a string.

curses.ascii.unctrl(c)

Return a string representation of the ASCII character c. If c is printable, this string is the character itself. If the character is a control character (0x00–0x1f) the string consists of a caret ('^') followed by the corresponding uppercase letter. If the character is an ASCII delete (0x7f) the string is '^?'. If the character has its meta bit (0x80) set, the meta bit is stripped, the preceding rules applied, and '!' prepended to the result.

curses.ascii.controlnames

A 33-element string array that contains the ASCII mnemonics for the thirty-two ASCII control characters from 0 (NUL) to 0x1f (US), in order, plus the mnemonic SP for the space character.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

일반 운영 체제 서비스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

일반 운영 체제 서비스 »

|

curses.panel — curses 용 패널 스택 확장

패널은 깊이 기능이 추가된 창이라서, 서로의 위에 쌓을 수 있으며, 각 창의 보이는 부분만 표시됩니다. 패널을 추가하고, 스택에서 위나 아래로 옮기고, 제거할 수 있습니다.

함수

curses.panel 모듈은 다음 함수를 정의합니다:

curses.panel.bottom_panel()

패널 스택에서 최하단 패널을 반환합니다.

curses.panel.new_panel(win)

주어진 창 win과 연관 지어진 패널 객체를 반환합니다. 반환된 패널 객체가 명시적으로 참조되도록 유지해야 합니다. 그렇지 않으면 패널 객체는 가비지 수집되어 패널 스택에서 제거됩니다.

curses.panel.top_panel()

패널 스택의 최상단 패널을 반환합니다.

curses.panel.update_panels()

패널 스택이 변경된 후 가상 화면을 갱신합니다. 이것은 curses.doupdate()를 호출하지 않아서, 여러분이 직접 해야 합니다.

Panel 객체

위의 new_panel()에 의해 반환된 패널 객체는 쌓인 순서가 있는 창입니다. 패널과 연관된 창이 항상 있고, 창이 내용을 결정합니다. 패널 메서드는 패널 스택에서 창의 깊이를 담당합니다.

패널 객체에는 다음과 같은 메서드가 있습니다:

Panel.above()

현재 패널 위의 패널을 반환합니다.

Panel.below()

현재 패널 아래의 패널을 반환합니다.

Panel.bottom()

패널을 스택 맨 아래로 밉니다.”

Panel.hidden()

패널이 숨겨져 있으면 (보이지 않으면) True를, 그렇지 않으면 False를 반환합니다.

Panel.hide()

패널을 숨깁니다. 이것은 객체를 삭제하지 않고, 화면의 창을 보이지 않게 합니다.

Panel.move(y, x)

패널을 화면 좌표 (y, x)로 이동합니다.

Panel.replace(win)

패널과 연관된 창을 창 win으로 변경합니다.

Panel.set_userptr(obj)

패널의 사용자 포인터를 obj로 설정합니다. 이것은 임의의 데이터를 패널과 연관시키는 데 사용되며, 임의의 파이썬 객체가 될 수 있습니다.

Panel.show()

(숨겼을 수도 있는) 패널을 표시합니다.

Panel.top()

패널을 스택 맨 위로 밉니다.

Panel.userptr()

패널의 사용자 포인터를 반환합니다. 이것은 임의의 파이썬 객체일 수 있습니다.

Panel.window()

패널과 연관된 창 객체를 반환합니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

일반 운영 체제 서비스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

일반 운영 체제 서비스 »

|

platform — 하부 플랫폼의 식별 데이터에 대한 액세스

소스 코드: Lib/platform.py [https://github.com/python/cpython/tree/3.7/Lib/platform.py]

참고

각 플랫폼은 알파벳순으로 나열되고, 리눅스는 유닉스 절에 포함됩니다.

크로스 플랫폼

platform.architecture(executable=sys.executable, bits='', linkage='')

다양한 아키텍처 정보에 대해 주어진 실행 파일(기본값은 파이썬 인터프리터 바이너리)을 조회합니다.

실행 파일에 사용된 비트 아키텍처와 링크 형식에 대한 정보가 들어있는 튜플 (bits, linkage)를 반환합니다. 두 값은 모두 문자열로 반환됩니다.

결정할 수 없는 값은 매개 변수 사전 설정에 따라 반환됩니다. bits가 ''로 주어지면, sizeof(pointer)(또는 파이썬 버전 < 1.5.2 에서는 sizeof(long))가 지원되는 포인터 크기를 나타내는 데 사용됩니다.

함수는 시스템의 file 명령을 사용하여 실제 작업을 수행합니다. 이것은 대부분(전부가 아니라면)의 유닉스 플랫폼과 일부 유닉스가 아닌 플랫폼에서 가능하며 실행 파일이 파이썬 인터프리터를 가리키는 경우에만 가능합니다. 위의 요구가 충족되지 않으면 합리적인 기본값이 사용됩니다.

참고

Mac OS X(그리고 아마도 다른 플랫폼에서도)에서, 실행 파일은 다중 아키텍처를 포함하는 유니버설 파일일 수 있습니다.

현재 인터프리터가 “64-비트” 인지를 판단하려면, sys.maxsize 어트리뷰트를 조회하는 것이 더 신뢰성 있습니다.:

is_64bits = sys.maxsize > 2**32

platform.machine()

기계 유형을 반환합니다, 예를 들어 'i386'. 값을 판별할 수 없으면 빈 문자열이 반환됩니다.

platform.node()

컴퓨터의 네트워크 이름을 반환합니다 (완전히 정규화되지 않았을 수 있습니다!). 값을 판별할 수 없으면 빈 문자열이 반환됩니다.

platform.platform(aliased=0, terse=0)

하부 플랫폼을 식별하는 가능한 한 많은 유용한 정보를 포함하는 단일 문자열을 반환합니다.

출력은 기계가 구문 분석하기보다는 사람이 읽을 수 있도록 합니다. 다른 플랫폼에서는 다르게 보일 수 있는데, 이는 의도 된 것입니다.

aliased가 참이면, 함수는 일반 이름과 다른 시스템 이름을 보고하는 다양한 플랫폼에 대해 별칭을 사용합니다, 예를 들어 SunOS는 Solaris로 보고됩니다. 이를 구현하는 데 system_alias() 함수가 사용됩니다.

terse를 참으로 설정하면 함수가 플랫폼을 식별하는 데 필요한 절대적으로 최소한의 정보만 반환합니다.

platform.processor()

(실제) 프로세서 이름을 반환합니다, 예를 들어 'amdk6'.

값을 판별할 수 없으면 빈 문자열이 반환됩니다. 많은 플랫폼이 이 정보를 제공하지 않거나 단순히 machine()과 같은 값을 반환함에 유의하십시오. NetBSD가 그렇습니다.

platform.python_build()

파이썬 빌드 번호와 날짜를 문자열로 나타내는 튜플 (buildno, builddate)를 반환합니다.

platform.python_compiler()

파이썬 컴파일에 사용된 컴파일러를 식별하는 문자열을 반환합니다.

platform.python_branch()

파이썬 구현 SCM 브랜치를 식별하는 문자열을 반환합니다.

platform.python_implementation()

파이썬 구현을 식별하는 문자열을 반환합니다. 가능한 반환 값은 이렇습니다: ‘CPython’, ‘IronPython’, ‘Jython’, ‘PyPy’.

platform.python_revision()

파이썬 구현 SCM 리비전을 식별하는 문자열을 반환합니다.

platform.python_version()

파이썬 버전을 문자열 'major.minor.patchlevel'로 반환합니다.

파이썬 sys.version과 달리, 반환 값은 항상 patchlevel을 포함함에 유의하십시오 (기본값은 0입니다).

platform.python_version_tuple()

파이썬 버전을 문자열의 튜플 (major, minor, patchlevel)로 반환합니다.

파이썬 sys.version과 달리, 반환 값은 항상 patchlevel을 포함함에 유의하십시오 (기본값은 '0'입니다).

platform.release()

시스템의 릴리스를 반환합니다, 예를 들어 '2.2.0'이나 'NT'. 값을 판별할 수 없으면 빈 문자열이 반환됩니다.

platform.system()

Returns the system/OS name, such as 'Linux', 'Darwin', 'Java', 'Windows'. An empty string is returned if the value cannot be determined.

platform.system_alias(system, release, version)

일부 시스템에서 사용되는 상용 마케팅 이름으로 별칭 된 (system, release, version)을 반환합니다. 혼동을 일으킬 수 있는 일부 경우에 정보의 순서를 변경하기도 합니다.

platform.version()

시스템의 릴리스 버전을 반환합니다, 예를 들어 '#3 on degas'. 값을 판별할 수 없으면 빈 문자열이 반환됩니다.

platform.uname()

꽤 이식성 있는 uname 인터페이스. system, node, release, version, machine, processor의 6개의 어트리뷰트를 포함한 namedtuple()를 반환합니다.

이것이 os.uname() 결과에 없는 여섯 번째 어트리뷰트(processor)를 추가한다는 것에 유의하십시오. 또한, 어트리뷰트 이름은 처음 두 어트리뷰트에서 다릅니다; os.uname()의 이름은 sysname과 nodename입니다.

결정할 수 없는 항목은 ''로 설정됩니다.

버전 3.3에서 변경: 결과가 튜플에서 네임드 튜플로 변경되었습니다.

자바 플랫폼

platform.java_ver(release='', vendor='', vminfo=('', '', ''), osinfo=('', '', ''))

Jython의 버전 인터페이스.

튜플 (release, vendor, vminfo, osinfo)를 반환하는데, vminfo는 튜플 (vm_name, vm_release, vm_vendor)이고, osinfo는 튜플 (os_name, os_version, os_arch)입니다. 결정할 수 없는 값은 매개 변수로 지정된 기본값으로 설정됩니다 (기본값은 모두 ''입니다).

윈도우 플랫폼

platform.win32_ver(release='', version='', csd='', ptype='')

윈도우 레지스트리에서 추가 버전 정보를 얻고 OS 릴리스, 버전 번호, CSD 수준 (서비스 팩) 및 OS 유형(다중/단일 프로세서)을 가리키는 튜플 (release, version, csd, ptype)를 반환합니다.

힌트: ptype은 단일 프로세서 NT 기계에서는 'Uniprocessor Free'이고 다중 프로세서 기계에서는 'Multiprocessor Free'입니다. ‘Free’는 디버깅 코드가 없는 OS 버전을 나타냅니다. 또한 ‘Checked’를 언급할 수 있는데, OS 버전이 디버깅 코드, 즉 인자, 범위 등을 검사하는 코드를 사용한다는 것을 뜻합니다.

참고

이 함수는 Mark Hammond의 win32all 패키지가 설치되었을 때 가장 잘 작동하지만, 파이썬 2.3 이상에서도 작동합니다 (파이썬 2.6에서 이 지원이 추가되었습니다). 당연히 Win32 호환 플랫폼에서만 실행됩니다.

Win95/98 specific

platform.popen(cmd, mode='r', bufsize=-1)

Portable popen() interface. Find a working popen implementation preferring win32pipe.popen(). On Windows NT, win32pipe.popen() should work; on Windows 9x it hangs due to bugs in the MS C library.

버전 3.3부터 폐지: This function is obsolete. Use the subprocess module. Check especially the Replacing Older Functions with the subprocess Module section.

Mac OS 플랫폼

platform.mac_ver(release='', versioninfo=('', '', ''), machine='')

Mac OS 버전 정보를 얻고 튜플 (release, versioninfo, machine)으로 반환하는데, versioninfo는 튜플 (version, dev_stage, non_release_version)입니다.

결정할 수 없는 항목은 ''로 설정됩니다. 모든 튜플 항목은 문자열입니다.

유닉스 플랫폼

platform.dist(distname='', version='', id='', supported_dists=('SuSE', 'debian', 'redhat', 'mandrake', ...))

This is another name for linux_distribution().

Deprecated since version 3.5, will be removed in version 3.8: See alternative like the distro [https://pypi.org/project/distro] package.

platform.linux_distribution(distname='', version='', id='', supported_dists=('SuSE', 'debian', 'redhat', 'mandrake', ...), full_distribution_name=1)

Tries to determine the name of the Linux OS distribution name.

supported_dists may be given to define the set of Linux distributions to look for. It defaults to a list of currently supported Linux distributions identified by their release file name.

If full_distribution_name is true (default), the full distribution read from the OS is returned. Otherwise the short name taken from supported_dists is used.

Returns a tuple (distname,version,id) which defaults to the args given as parameters. id is the item in parentheses after the version number. It is usually the version codename.

Deprecated since version 3.5, will be removed in version 3.8: See alternative like the distro [https://pypi.org/project/distro] package.

platform.libc_ver(executable=sys.executable, lib='', version='', chunksize=16384)

파일 executable(기본값은 파이썬 인터프리터입니다)이 링크된 libc 버전을 확인하려고 시도합니다. 문자열의 튜플 (lib, version)을 반환하는데, 조회가 실패하면 지정된 매개 변수를 기본값으로 사용합니다.

다른 libc 버전이 실행 파일에 심볼을 추가하는 방법에 대해 이 함수가 가진 지식은 아마도 gcc로 컴파일된 실행 파일에서만 사용 가능하다는 것에 유의하십시오.

파일은 chunksize 바이트의 청크 단위로 읽고 스캔됩니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

일반 운영 체제 서비스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

일반 운영 체제 서비스 »

|

errno — 표준 errno 시스템 기호

이 모듈은 표준 errno 시스템 기호를 제공합니다. 각 기호의 값은 해당 정숫값입니다. 이름과 설명은 linux/include/errno.h에서 빌려 왔는데, 꽤 포괄적이어야 합니다.

errno.errorcode

errno 값에서 하부 시스템의 문자열 이름으로의 매핑을 제공하는 딕셔너리입니다. 예를 들어, errno.errorcode[errno.EPERM]는 'EPERM'로 매핑됩니다.

숫자 에러 코드를 에러 메시지로 변환하려면, os.strerror()를 사용하십시오.

다음 목록에서, 현재 플랫폼에서 사용되지 않는 기호는 모듈에서 정의하지 않습니다. 정의된 기호의 구체적인 목록은 errno.errorcode.keys()로 사용 가능합니다. 사용할 수 있는 기호는 다음과 같습니다:

errno.EPERM

Operation not permitted – 연산이 허용되지 않습니다

errno.ENOENT

No such file or directory – 그런 파일이나 디렉터리가 없습니다

errno.ESRCH

No such process – 그런 프로세스가 없습니다

errno.EINTR

Interrupted system call – 중단된 시스템 호출

더 보기

이 에러는 예외 InterruptedError로 매핑됩니다.

errno.EIO

I/O error – I/O 에러

errno.ENXIO

No such device or address – 그런 장치나 주소가 없습니다.

errno.E2BIG

Arg list too long – 인자 목록이 너무 깁니다.

errno.ENOEXEC

Exec format error – Exec 포맷 에러

errno.EBADF

Bad file number – 잘못된 파일 번호

errno.ECHILD

No child processes – 그런 자식 프로세스가 없습니다

errno.EAGAIN

Try again – 다시 시도하십시오

errno.ENOMEM

Out of memory – 메모리 부족

errno.EACCES

Permission denied – 사용 권한이 거부되었습니다

errno.EFAULT

Bad address – 잘못된 주소

errno.ENOTBLK

Block device required – 블록 장치가 필요합니다

errno.EBUSY

Device or resource busy – 장치나 자원이 사용 중입니다

errno.EEXIST

File exists – 파일이 존재합니다

errno.EXDEV

Cross-device link – 장치 간 링크

errno.ENODEV

No such device – 그런 장치가 없습니다

errno.ENOTDIR

Not a directory – 디렉터리가 아닙니다

errno.EISDIR

Is a directory – 디렉터리입니다

errno.EINVAL

Invalid argument – 잘못된 인자

errno.ENFILE

File table overflow – 파일 테이블 오버플로

errno.EMFILE

Too many open files – 열려있는 파일이 너무 많습니다

errno.ENOTTY

Not a typewriter – 타자기가 아닙니다

errno.ETXTBSY

Text file busy – 텍스트 파일이 사용 중입니다

errno.EFBIG

File too large – 파일이 너무 큽니다

errno.ENOSPC

No space left on device – 장치에 남은 공간이 없습니다.

errno.ESPIPE

Illegal seek – 잘못된 탐색

errno.EROFS

Read-only file system – 읽기 전용 파일 시스템

errno.EMLINK

Too many links – 링크가 너무 많습니다

errno.EPIPE

Broken pipe – 깨진 파이프

errno.EDOM

Math argument out of domain of func – 함수의 범위를 벗어난 수학 인자

errno.ERANGE

Math result not representable – 수학 결과를 표현할 수 없습니다

errno.EDEADLK

Resource deadlock would occur – 자원 교착 상태가 발생합니다

errno.ENAMETOOLONG

File name too long – 파일 이름이 너무 깁니다

errno.ENOLCK

No record locks available – 사용 가능한 레코드 록이 없습니다

errno.ENOSYS

Function not implemented – 기능이 구현되지 않았습니다

errno.ENOTEMPTY

Directory not empty – 디렉터리가 비어 있지 않습니다

errno.ELOOP

Too many symbolic links encountered – 마주친 심볼릭 링크가 너무 많습니다

errno.EWOULDBLOCK

Operation would block – 연산이 블록 됩니다

errno.ENOMSG

No message of desired type – 원하는 유형의 메시지가 없습니다

errno.EIDRM

Identifier removed – 식별자가 삭제되었습니다

errno.ECHRNG

Channel number out of range – 채널 번호가 범위를 벗어났습니다

errno.EL2NSYNC

Level 2 not synchronized – 수준 2가 동기화되지 않았습니다

errno.EL3HLT

Level 3 halted – 수준 3이 정지되었습니다

errno.EL3RST

Level 3 reset – 수준 3이 재설정되었습니다

errno.ELNRNG

Link number out of range – 링크 번호가 범위를 벗어났습니다

errno.EUNATCH

Protocol driver not attached – 프로토콜 드라이버가 연결되지 않았습니다

errno.ENOCSI

No CSI structure available – 사용 가능한 CSI 구조가 없습니다

errno.EL2HLT

Level 2 halted – 수준 2가 중지되었습니다

errno.EBADE

Invalid exchange – 잘못된 교환

errno.EBADR

Invalid request descriptor – 잘못된 요청 기술자

errno.EXFULL

Exchange full – 교환 포화

errno.ENOANO

No anode – anode가 없습니다

errno.EBADRQC

Invalid request code – 유효하지 않은 요청 코드

errno.EBADSLT

Invalid slot – 유효하지 않은 슬롯

errno.EDEADLOCK

File locking deadlock error – 파일 잠금 교착 상태 에러

errno.EBFONT

Bad font file format – 잘못된 글꼴 파일 형식

errno.ENOSTR

Device not a stream – 장치가 스트림이 아닙니다

errno.ENODATA

No data available – 데이터가 없습니다

errno.ETIME

Timer expired – 타이머가 만료되었습니다

errno.ENOSR

Out of streams resources – 스트림 자원 부족

errno.ENONET

Machine is not on the network – 기계가 네트워크에 없습니다.

errno.ENOPKG

Package not installed – 패키지가 설치되지 않았습니다

errno.EREMOTE

Object is remote – 객체가 원격입니다

errno.ENOLINK

Link has been severed – 링크가 절단되었습니다

errno.EADV

Advertise error – 광고 에러

errno.ESRMNT

Srmount error – srmount 에러

errno.ECOMM

Communication error on send – 전송 시 통신 에러

errno.EPROTO

Protocol error – 프로토콜 에러

errno.EMULTIHOP

Multihop attempted – 다중 홉을 시도했습니다

errno.EDOTDOT

RFS specific error – RFS 특정 에러

errno.EBADMSG

Not a data message – 데이터 메시지가 아닙니다

errno.EOVERFLOW

Value too large for defined data type – 정의된 데이터형에 비해 값이 너무 큽니다

errno.ENOTUNIQ

Name not unique on network – 이름이 네트워크에서 고유하지 않습니다

errno.EBADFD

File descriptor in bad state – 잘못된 상태의 파일 기술자

errno.EREMCHG

Remote address changed – 원격 주소가 변경되었습니다

errno.ELIBACC

Can not access a needed shared library – 필요한 공유 라이브러리에 액세스할 수 없습니다.

errno.ELIBBAD

Accessing a corrupted shared library – 손상된 공유 라이브러리 액세스

errno.ELIBSCN

.lib section in a.out corrupted – 손상된 a.out의 .lib 섹션

errno.ELIBMAX

Attempting to link in too many shared libraries – 너무 많은 공유 라이브러리 연결 시도

errno.ELIBEXEC

Cannot exec a shared library directly – 공유 라이브러리를 직접 실행할 수 없습니다

errno.EILSEQ

Illegal byte sequence – 잘못된 바이트 시퀀스

errno.ERESTART

Interrupted system call should be restarted – 중단된 시스템 호출을 다시 시작해야 합니다

errno.ESTRPIPE

Streams pipe error – 스트림 파이프 에러

errno.EUSERS

Too many users – 사용자가 너무 많습니다

errno.ENOTSOCK

Socket operation on non-socket – 비 소켓에 대한 소켓 연산

errno.EDESTADDRREQ

Destination address required – 목적지 주소가 필요합니다

errno.EMSGSIZE

Message too long – 메시지가 너무 깁니다

errno.EPROTOTYPE

Protocol wrong type for socket – 소켓에 대한 프로토콜 유형이 잘못되었습니다

errno.ENOPROTOOPT

Protocol not available – 프로토콜을 사용할 수 없습니다

errno.EPROTONOSUPPORT

Protocol not supported – 지원되지 않는 프로토콜

errno.ESOCKTNOSUPPORT

Socket type not supported – 지원되지 않는 소켓 유형

errno.EOPNOTSUPP

Operation not supported on transport endpoint – 트랜스포트 끝점에서 지원되지 않는 연산

errno.EPFNOSUPPORT

Protocol family not supported – 지원되지 않는 프로토콜 패밀리

errno.EAFNOSUPPORT

Address family not supported by protocol – 프로토콜이 지원하지 않는 주소 패밀리

errno.EADDRINUSE

Address already in use – 이미 사용 중인 주소

errno.EADDRNOTAVAIL

Cannot assign requested address – 요청된 주소를 할당할 수 없습니다.

errno.ENETDOWN

Network is down – 네트워크가 다운되었습니다

errno.ENETUNREACH

Network is unreachable – 네트워크에 도달할 수 없습니다

errno.ENETRESET

Network dropped connection because of reset – 재설정으로 인해 네트워크 연결이 끊겼습니다

errno.ECONNABORTED

Software caused connection abort – 소프트웨어로 인해 연결이 중단되었습니다

errno.ECONNRESET

Connection reset by peer – 피어에 의한 연결 재설정

errno.ENOBUFS

No buffer space available – 사용 가능한 버퍼 공간이 없습니다.

errno.EISCONN

Transport endpoint is already connected – 트랜스포트 끝점이 이미 연결되어 있습니다.

errno.ENOTCONN

Transport endpoint is not connected – 트랜스포트 끝점이 연결되어 있지 않습니다.

errno.ESHUTDOWN

Cannot send after transport endpoint shutdown – 트랜스포트 끝점 종료 후에 보낼 수 없습니다.

errno.ETOOMANYREFS

Too many references: cannot splice – 참조가 너무 많습니다: 연결할 수 없습니다

errno.ETIMEDOUT

Connection timed out – 연결 시간이 초과하였습니다

errno.ECONNREFUSED

Connection refused – 연결이 거부되었습니다

errno.EHOSTDOWN

Host is down – 호스트가 다운되었습니다

errno.EHOSTUNREACH

No route to host – 호스트로 가는 길이 없습니다

errno.EALREADY

Operation already in progress – 이미 진행 중인 연산

errno.EINPROGRESS

Operation now in progress – 이제 연산이 진행 중입니다

errno.ESTALE

Stale NFS file handle – 오래된 NFS 파일 핸들

errno.EUCLEAN

Structure needs cleaning – 구조 청소 필요

errno.ENOTNAM

Not a XENIX named type file – XENIX 이름 붙은 형식 파일이 아닙니다

errno.ENAVAIL

No XENIX semaphores available – 사용할 수 있는 XENIX 세마포어가 없습니다

errno.EISNAM

Is a named type file – 이름 붙은 형식 파일입니다

errno.EREMOTEIO

Remote I/O error – 원격 I/O 에러

errno.EDQUOT

Quota exceeded – 할당량 초과

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

일반 운영 체제 서비스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

일반 운영 체제 서비스 »

|

ctypes — 파이썬용 외부 함수 라이브러리

ctypes는 파이썬용 외부 함수(foreign function) 라이브러리입니다. C 호환 데이터형을 제공하며, DLL 또는 공유 라이브러리에 있는 함수를 호출할 수 있습니다. 이 라이브러리들을 순수 파이썬으로 감싸는 데 사용할 수 있습니다.

ctypes 자습서

참고: 이 자습서의 코드 예제는 doctest를 사용하여 실제로 작동하는지 확인합니다. 일부 코드 예제는 리눅스, 윈도우 또는 맥 OS X에서 다르게 동작하므로, 주석에 doctest 지시문이 포함되어 있습니다.

참고: 일부 코드 예제는 ctypes c_int 형을 참조합니다. sizeof(long) == sizeof(int)인 플랫폼에서, 이는 c_long의 별칭입니다. 따라서 c_int를 기대할 때 c_long가 인쇄되더라도 혼란스러워하지 않아도 됩니다 — 이것들은 실제로 같은 형입니다.

동적 링크 라이브러리 로드하기

ctypes는 동적 링크 라이브러리 로드를 위해 cdll을, 그리고 윈도우에서는 windll 및 oledll 객체를, 노출합니다.

이 객체의 어트리뷰트를 액세스하여 라이브러리를 로드합니다. cdll은 표준 cdecl 호출 규칙을 사용하는 함수를 내보내는 라이브러리를 로드하는 반면, windll 라이브러리는 stdcall 호출 규칙을 사용하여 함수를 호출합니다. oledll 또한 stdcall 호출 규칙을 사용하고, 함수가 윈도우 HRESULT 에러 코드를 반환한다고 가정합니다. 에러 코드는 함수 호출이 실패할 때 OSError 예외를 자동으로 발생시키는 데 사용됩니다.

버전 3.3에서 변경: 윈도우 에러는 WindowsError를 일으켜왔습니다. 이제는 OSError의 별칭입니다.

다음은 윈도우 용 예제입니다. msvcrt는 대부분 표준 C 함수가 포함된 MS 표준 C 라이브러리며, cdecl 호출 규칙을 사용합니다:

>>> from ctypes import *
>>> print(windll.kernel32)
<WinDLL 'kernel32', handle ... at ...>
>>> print(cdll.msvcrt)
<CDLL 'msvcrt', handle ... at ...>
>>> libc = cdll.msvcrt
>>>

윈도우는 일반적인 .dll 파일 접미사를 자동으로 추가합니다.

참고

cdll.msvcrt를 통해 표준 C 라이브러리에 액세스하면 파이썬에서 사용되는 라이브러리와 호환되지 않는 오래된 라이브러리 버전이 사용됩니다. 가능하면 파이썬 자체의 기능을 사용하거나, msvcrt 모듈을 임포트 해서 사용하십시오.

리눅스에서, 라이브러리를 로드하기 위해서는 확장자를 포함하는 파일명을 지정해야 하므로, 어트리뷰트 액세스를 사용하여 라이브러리를 로드 할 수 없습니다. dll 로더의 LoadLibrary() 메서드를 사용하거나 CDLL의 생성자를 호출하여 인스턴스를 만들어 라이브러리를 로드해야 합니다:

>>> cdll.LoadLibrary("libc.so.6")
<CDLL 'libc.so.6', handle ... at ...>
>>> libc = CDLL("libc.so.6")
>>> libc
<CDLL 'libc.so.6', handle ... at ...>
>>>

로드된 dll에서 함수에 액세스하기

함수는 dll 객체의 어트리뷰트로 액세스 됩니다:

>>> from ctypes import *
>>> libc.printf
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.GetModuleHandleA)
<_FuncPtr object at 0x...>
>>> print(windll.kernel32.MyOwnFunction)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "ctypes.py", line 239, in __getattr__
    func = _StdcallFuncPtr(name, self)
AttributeError: function 'MyOwnFunction' not found
>>>

kernel32 와 user32와 같은 win32 시스템 dll은 종종 ANSI뿐만 아니라 UNICODE 버전의 함수를 내보냅니다. UNICODE 버전은 이름에 W가 추가된 상태로 내보내지고, ANSI 버전은 이름에 A가 추가되어 내보내 집니다. 지정된 모듈 이름의 모듈 핸들을 반환하는 win32 GetModuleHandle 함수는, 다음과 같은 C 프로토타입을 가지며, UNICODE가 정의되어 있는지에 따라 그중 하나를 GetModuleHandle로 노출하기 위해 매크로가 사용됩니다:

/* ANSI version */
HMODULE GetModuleHandleA(LPCSTR lpModuleName);
/* UNICODE version */
HMODULE GetModuleHandleW(LPCWSTR lpModuleName);

windll는 마술적으로 이 중 하나를 선택하려고 하지 않으므로, GetModuleHandleA 나 GetModuleHandleW를 명시적으로 지정하여 필요한 버전에 액세스해야 하고, 그런 다음 각각 바이트열이나 문자열 객체로 호출해야 합니다.

때때로, dll은 "??2@YAPAXI@Z"와 같은 유효한 파이썬 식별자가 아닌 이름으로 함수를 내보냅니다. 이때는 getattr()를 사용하여 함수를 조회해야 합니다:

>>> getattr(cdll.msvcrt, "??2@YAPAXI@Z")
<_FuncPtr object at 0x...>
>>>

윈도우에서, 일부 dll은 이름이 아니라 서수(ordinal)로 함수를 내보냅니다. 이 함수는 서수로 dll 객체를 인덱싱하여 액세스할 수 있습니다:

>>> cdll.kernel32[1]
<_FuncPtr object at 0x...>
>>> cdll.kernel32[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "ctypes.py", line 310, in __getitem__
    func = _StdcallFuncPtr(name, self)
AttributeError: function ordinal 0 not found
>>>

함수 호출하기

다른 파이썬 콜러블처럼 이 함수를 호출할 수 있습니다. 이 예제에서는 시스템 시간을 유닉스 에포크부터의 초로 반환하는 time() 함수와 win32 모듈 핸들을 반환하는 GetModuleHandleA() 함수를 사용합니다.

This example calls both functions with a NULL pointer (None should be used as the NULL pointer):

>>> print(libc.time(None))
1150640792
>>> print(hex(windll.kernel32.GetModuleHandleA(None)))
0x1d000000
>>>

cdecl 호출 규칙을 사용하여 stdcall 함수를 호출하면 ValueError가 발생하고, 그 반대도 마찬가지입니다:

>>> cdll.kernel32.GetModuleHandleA(None)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: Procedure probably called with not enough arguments (4 bytes missing)
>>>

>>> windll.msvcrt.printf(b"spam")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: Procedure probably called with too many arguments (4 bytes in excess)
>>>

올바른 호출 규칙을 찾으려면 C 헤더 파일이나 호출할 함수에 대한 설명서를 살펴봐야 합니다.

윈도우에서, ctypes는 함수가 유효하지 않은 인자 값을 사용하여 호출될 때, 일반적인 보호 오류로 인한 충돌을 방지하기 위해 win32 구조적 예외 처리를 사용합니다:

>>> windll.kernel32.GetModuleHandleA(32)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OSError: exception: access violation reading 0x00000020
>>>

그러나, ctypes로 파이썬을 충돌시킬 방법이 많으므로, 어쨌든 주의해야 합니다. faulthandler 모듈은 충돌을 디버깅하는 데 도움이 될 수 있습니다 (예를 들어, 오류가 있는 C 라이브러리 호출로 인한 세그먼트 오류).

None, 정수, 바이트열 객체 및 (유니코드) 문자열은 이러한 함수 호출에서 매개 변수로 직접 사용할 수 있는 유일한 파이썬 자체의 객체입니다. None는 C NULL 포인터로 전달되고, 바이트열 객체와 문자열은 데이터가 저장된 메모리 블록에 대한 포인터로 전달됩니다 (char * 이나 wchar_t *). 파이썬 정수는 플랫폼의 기본 C int 형으로 전달되며, 그 값은 C 형에 맞게 마스크 됩니다.

다른 매개 변수 형으로 함수를 호출하기 전에, ctypes 데이터형에 대해 더 알아야 합니다.

기본 데이터형

ctypes는 많은 기본적인 C 호환 데이터형을 정의합니다.:

ctypes 형

C 형

파이썬 형

c_bool

_Bool

bool (1)

c_char

char

1-문자 바이트열 객체

c_wchar

wchar_t

1-문자 문자열

c_byte

char

int

c_ubyte

unsigned char

int

c_short

short

int

c_ushort

unsigned short

int

c_int

int

int

c_uint

unsigned int

int

c_long

long

int

c_ulong

unsigned long

int

c_longlong

__int64 나 long long

int

c_ulonglong

unsigned __int64 나 unsigned long long

int

c_size_t

size_t

int

c_ssize_t

ssize_t 나 Py_ssize_t

int

c_float

float

float

c_double

double

float

c_longdouble

long double

float

c_char_p

char * (NUL 종료됨)

바이트열 객체나 None

c_wchar_p

wchar_t * (NUL 종료됨)

문자열이나 None

c_void_p

void *

int 나 None

생성자는 논릿값을 가진 모든 객체를 받아들입니다.

이 모든 형은 올바른 형과 값의 선택적 초기화자로 호출해서 만들어질 수 있습니다:

>>> c_int()
c_long(0)
>>> c_wchar_p("Hello, World")
c_wchar_p(140018365411392)
>>> c_ushort(-3)
c_ushort(65533)
>>>

이러한 형은 가변이므로, 값을 나중에 변경할 수도 있습니다:

>>> i = c_int(42)
>>> print(i)
c_long(42)
>>> print(i.value)
42
>>> i.value = -99
>>> print(i.value)
-99
>>>

c_char_p, c_wchar_p 및 c_void_p 포인터형의 인스턴스에 새 값을 대입하면 포인터가 가리키는 메모리 위치가 변경됩니다, 메모리 블록의 내용이 아닙니다 (당연히 아닙니다, 파이썬 바이트열 객체는 불변입니다):

>>> s = "Hello, World"
>>> c_s = c_wchar_p(s)
>>> print(c_s)
c_wchar_p(139966785747344)
>>> print(c_s.value)
Hello World
>>> c_s.value = "Hi, there"
>>> print(c_s)              # the memory location has changed
c_wchar_p(139966783348904)
>>> print(c_s.value)
Hi, there
>>> print(s)                # first object is unchanged
Hello, World
>>>

그러나, 이것들을 가변 메모리에 대한 포인터를 예상하는 함수에 전달하지 않도록 주의해야 합니다. 가변 메모리 블록이 필요하다면, ctypes에는 다양한 방법으로 이를 만드는 create_string_buffer() 함수가 있습니다. 현재 메모리 블록 내용은 raw 프로퍼티를 사용하여 액세스(또는 변경)할 수 있습니다; NUL 종료 문자열로 액세스하려면 value 프로퍼티를 사용하십시오:

>>> from ctypes import *
>>> p = create_string_buffer(3)            # create a 3 byte buffer, initialized to NUL bytes
>>> print(sizeof(p), repr(p.raw))
3 b'\x00\x00\x00'
>>> p = create_string_buffer(b"Hello")     # create a buffer containing a NUL terminated string
>>> print(sizeof(p), repr(p.raw))
6 b'Hello\x00'
>>> print(repr(p.value))
b'Hello'
>>> p = create_string_buffer(b"Hello", 10) # create a 10 byte buffer
>>> print(sizeof(p), repr(p.raw))
10 b'Hello\x00\x00\x00\x00\x00'
>>> p.value = b"Hi"
>>> print(sizeof(p), repr(p.raw))
10 b'Hi\x00lo\x00\x00\x00\x00\x00'
>>>

create_string_buffer() 함수는 이전 ctypes 배포에 있는 c_string() 함수뿐만 아니라 c_buffer() 함수(아직 별칭으로 사용할 수 있습니다)를 대체합니다. C 형 wchar_t의 유니코드 문자를 포함하는 가변 메모리 블록을 생성하려면 create_unicode_buffer() 함수를 사용하십시오.

함수 호출하기, 계속

printf는 sys.stdout이 아니라 실제 표준 출력으로 인쇄하므로, 이 예제는 콘솔 프롬프트에서만 작동하고 IDLE 이나 PythonWin에서는 작동하지 않음에 유의하십시오:

>>> printf = libc.printf
>>> printf(b"Hello, %s\n", b"World!")
Hello, World!
14
>>> printf(b"Hello, %S\n", "World!")
Hello, World!
14
>>> printf(b"%d bottles of beer\n", 42)
42 bottles of beer
19
>>> printf(b"%f bottles of beer\n", 42.5)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ArgumentError: argument 2: exceptions.TypeError: Don't know how to convert parameter 2
>>>

이전에 언급했듯이, 정수, 문자열 및 바이트열 객체를 제외한 모든 파이썬 형은 필요한 C 데이터형으로 변환될 수 있도록 해당하는 ctypes 형으로 래핑 되어야 합니다:

>>> printf(b"An int %d, a double %f\n", 1234, c_double(3.14))
An int 1234, a double 3.140000
31
>>>

사용자 정의 데이터형을 사용하여 함수 호출하기

또한 ctypes 인자 변환을 사용자 정의하여 사용자 고유 클래스의 인스턴스를 함수 인자로 사용할 수 있습니다. ctypes는 _as_parameter_ 어트리뷰트를 찾고, 이를 함수 인자로 사용합니다. 물론 정수, 문자열 또는 바이트열 중 하나여야 합니다:

>>> class Bottles:
...     def __init__(self, number):
...         self._as_parameter_ = number
...
>>> bottles = Bottles(42)
>>> printf(b"%d bottles of beer\n", bottles)
42 bottles of beer
19
>>>

_as_parameter_ 인스턴스 변수에 인스턴스의 데이터를 저장하지 않으려면, property를 정의하여 요청 시 어트리뷰트를 사용할 수 있게 할 수 있습니다.

필수 인자 형 (함수 프로토타입) 지정하기

argtypes 어트리뷰트를 설정하여 DLL에서 내보낸 함수의 필수 인자 형을 지정할 수 있습니다.

argtypes는 C 데이터형의 시퀀스 여야 합니다 (printf 함수는 포맷 문자열에 따라 개수와 형이 다른 매개 변수를 받아들이기 때문에, 여기서는 좋은 예가 아닐 수 있습니다. 반면에 이 기능을 실험하기에 매우 편리하기도 합니다):

>>> printf.argtypes = [c_char_p, c_char_p, c_int, c_double]
>>> printf(b"String '%s', Int %d, Double %f\n", b"Hi", 10, 2.2)
String 'Hi', Int 10, Double 2.200000
37
>>>

포맷을 지정하면 호환되지 않는 인자 형으로부터 보호하고(C 함수의 프로토타입처럼), 유효한 형으로 인자를 변환하려고 시도합니다:

>>> printf(b"%d %d %d", 1, 2, 3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ArgumentError: argument 2: exceptions.TypeError: wrong type
>>> printf(b"%s %d %f\n", b"X", 2, 3)
X 2 3.000000
13
>>>

함수 호출에 전달하는 여러분 자신의 클래스를 정의했으면, argtypes 시퀀스에서 해당 클래스를 사용할 수 있도록, from_param() 클래스 메서드를 구현해야 합니다. from_param() 클래스 메서드는 함수 호출에 전달된 파이썬 객체를 받습니다. 형 검사나 이 객체가 수용 가능한지 확인하는 데 필요한 모든 작업을 수행한 다음, 객체 자체나 _as_parameter_ 어트리뷰트나 무엇이건 이 경우에 C 함수 인자로 전달되길 원하는 것을 반환해야 합니다. 다시 말하지만, 결과는 정수, 문자열, 바이트열, ctypes 인스턴스 또는 _as_parameter_ 어트리뷰트가 있는 객체여야 합니다.

반환형

기본적으로 함수는 C int 형을 반환한다고 가정합니다. 다른 반환형은 함수 객체의 restype 어트리뷰트를 설정하여 지정할 수 있습니다.

다음은 더 고급 예제입니다. strchr 함수를 사용하는데, 문자열 포인터와 char을 기대하고, 문자열에 대한 포인터를 반환합니다:

>>> strchr = libc.strchr
>>> strchr(b"abcdef", ord("d"))
8059983
>>> strchr.restype = c_char_p    # c_char_p is a pointer to a string
>>> strchr(b"abcdef", ord("d"))
b'def'
>>> print(strchr(b"abcdef", ord("x")))
None
>>>

위의 ord("x") 호출을 피하려면, argtypes 어트리뷰트를 설정할 수 있으며, 두 번째 인자는 한 글자 파이썬 바이트열 객체에서 C char로 변환됩니다:

>>> strchr.restype = c_char_p
>>> strchr.argtypes = [c_char_p, c_char]
>>> strchr(b"abcdef", b"d")
'def'
>>> strchr(b"abcdef", b"def")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ArgumentError: argument 2: exceptions.TypeError: one character string expected
>>> print(strchr(b"abcdef", b"x"))
None
>>> strchr(b"abcdef", b"d")
'def'
>>>

외부 함수가 정수를 반환하면, 콜러블 파이썬 객체(예를 들어, 함수나 클래스)를 restype 어트리뷰트로 사용할 수도 있습니다. 콜러블은 C 함수가 돌려주는 정수로 호출되며, 이 호출의 결과는 함수 호출의 결과로 사용됩니다. 이것은 에러 반환 값을 검사하고 자동으로 예외를 발생시키는 데 유용합니다:

>>> GetModuleHandle = windll.kernel32.GetModuleHandleA
>>> def ValidHandle(value):
...     if value == 0:
...         raise WinError()
...     return value
...
>>>
>>> GetModuleHandle.restype = ValidHandle
>>> GetModuleHandle(None)
486539264
>>> GetModuleHandle("something silly")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in ValidHandle
OSError: [Errno 126] The specified module could not be found.
>>>

WinError는 윈도우 FormatMessage() api를 호출하여 에러 코드의 문자열 표현을 가져오고, 예외를 반환하는 함수입니다. WinError는 선택적 에러 코드 매개 변수를 취합니다, 제공하지 않으면 GetLastError()를 호출하여 에러 코드를 가져옵니다.

훨씬 더 강력한 에러 검사 메커니즘을 errcheck 어트리뷰트를 통해 사용할 수 있음에 유의하십시오; 자세한 내용은 레퍼런스 설명서를 참조하십시오.

포인터 전달하기 (또는: 참조로 매개 변수 전달하기)

때때로 C api 함수는 매개 변수로 데이터형을 가리키는 포인터를 기대합니다, 아마도 해당 위치에 쓰기 위해서, 또는 데이터가 너무 커서 값으로 전달할 수 없어서. 이것은 참조로 매개 변수 전달하기로 알려져 있기도 합니다.

ctypes는 매개 변수를 참조로 전달하는 데 사용되는 byref() 함수를 내보냅니다. 같은 효과를 pointer() 함수로도 얻을 수 있습니다. 하지만 pointer()는 실제 포인터 객체를 생성하기 때문에 더 많은 작업을 수행하므로, 파이썬 자체에서 포인터 객체가 필요하지 않으면 byref()를 사용하는 것이 더 빠릅니다.:

>>> i = c_int()
>>> f = c_float()
>>> s = create_string_buffer(b'\000' * 32)
>>> print(i.value, f.value, repr(s.value))
0 0.0 b''
>>> libc.sscanf(b"1 3.14 Hello", b"%d %f %s",
...             byref(i), byref(f), s)
3
>>> print(i.value, f.value, repr(s.value))
1 3.1400001049 b'Hello'
>>>

구조체와 공용체

구조체와 공용체는 ctypes 모듈에 정의된 Structure와 Union 베이스 클래스에서 파생되어야 합니다. 각 서브 클래스는 _fields_ 어트리뷰트를 정의해야 합니다. _fields_는 필드 이름 과 필드형을 포함하는 2-튜플의 리스트여야 합니다.

필드형은 c_int와 같은 ctypes 형이거나 다른 파생된 ctypes 형(구조체, 공용체, 배열, 포인터)이어야 합니다.

다음은 x 및 y라는 두 개의 정수가 포함된 POINT 구조체의 간단한 예제이며, 생성자에서 구조체를 초기화하는 방법도 보여줍니다:

>>> from ctypes import *
>>> class POINT(Structure):
...     _fields_ = [("x", c_int),
...                 ("y", c_int)]
...
>>> point = POINT(10, 20)
>>> print(point.x, point.y)
10 20
>>> point = POINT(y=5)
>>> print(point.x, point.y)
0 5
>>> POINT(1, 2, 3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: too many initializers
>>>

그러나, 훨씬 복잡한 구조를 만들 수 있습니다. 구조체는 필드형으로 구조체를 사용하여 다른 구조체를 포함할 수 있습니다.

다음은 upperleft 및 lowerright라는 두 개의 POINT를 포함하는 RECT 구조체입니다:

>>> class RECT(Structure):
...     _fields_ = [("upperleft", POINT),
...                 ("lowerright", POINT)]
...
>>> rc = RECT(point)
>>> print(rc.upperleft.x, rc.upperleft.y)
0 5
>>> print(rc.lowerright.x, rc.lowerright.y)
0 0
>>>

중첩된 구조체는 여러 가지 방법으로 생성자에서 초기화할 수 있습니다:

>>> r = RECT(POINT(1, 2), POINT(3, 4))
>>> r = RECT((1, 2), (3, 4))

필드 디스크립터는 클래스에서 조회할 수 있습니다. 유용한 정보를 제공할 수 있으므로 디버깅에 유용합니다:

>>> print(POINT.x)
<Field type=c_long, ofs=0, size=4>
>>> print(POINT.y)
<Field type=c_long, ofs=4, size=4>
>>>

경고

ctypes는 비트 필드가 있는 공용체나 구조체를 값으로 함수에 전달할 수 없습니다. 32비트 x86에서 작동할 수 있지만, 일반적으로 작동은 라이브러리가 보증하지 않습니다. 비트 필드가 있는 공용체와 구조체는 항상 포인터로 함수에 전달되어야 합니다.

구조체/공용체 정렬과 바이트 순서

By default, Structure and Union fields are aligned in the same way the C compiler does it. It is possible to override this behavior by specifying a _pack_ class attribute in the subclass definition. This must be set to a positive integer and specifies the maximum alignment for the fields. This is what #pragma pack(n) also does in MSVC.

ctypes는 구조체와 공용체에 기본(native) 바이트 순서를 사용합니다. 기본이 아닌 바이트 순서로 구조체를 만들려면 BigEndianStructure, LittleEndianStructure, BigEndianUnion 및 LittleEndianUnion 베이스 클래스 중 하나를 사용할 수 있습니다. 이러한 클래스들은 포인터 필드를 포함할 수 없습니다.

구조체와 공용체의 비트 필드

비트 필드를 포함하는 구조체와 공용체를 만드는 것이 가능합니다. 비트 필드는 정수 필드에만 가능하며, 비트 폭은 _fields_ 튜플의 세 번째 항목으로 지정됩니다:

>>> class Int(Structure):
...     _fields_ = [("first_16", c_int, 16),
...                 ("second_16", c_int, 16)]
...
>>> print(Int.first_16)
<Field type=c_long, ofs=0:0, bits=16>
>>> print(Int.second_16)
<Field type=c_long, ofs=0:16, bits=16>
>>>

배열

배열은 같은 형의 고정 된 수의 인스턴스를 포함하는 시퀀스입니다.

배열형을 만드는 데 권장되는 방법은 데이터형에 양의 정수를 곱하는 것입니다:

TenPointsArrayType = POINT * 10

다음은 다소 인공적인 데이터형의 예입니다. 다른 항목들과 함께 4개의 POINT를 포함하는 구조체입니다:

>>> from ctypes import *
>>> class POINT(Structure):
...     _fields_ = ("x", c_int), ("y", c_int)
...
>>> class MyStruct(Structure):
...     _fields_ = [("a", c_int),
...                 ("b", c_float),
...                 ("point_array", POINT * 4)]
>>>
>>> print(len(MyStruct().point_array))
4
>>>

인스턴스는 클래스를 호출하는 일반적인 방법으로 만들어집니다:

arr = TenPointsArrayType()
for pt in arr:
    print(pt.x, pt.y)

위 코드는 배열 내용이 0으로 초기화되기 때문에, 일련의 0 0 줄을 인쇄합니다.

올바른 형의 초기화자를 지정할 수도 있습니다:

>>> from ctypes import *
>>> TenIntegers = c_int * 10
>>> ii = TenIntegers(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
>>> print(ii)
<c_long_Array_10 object at 0x...>
>>> for i in ii: print(i, end=" ")
...
1 2 3 4 5 6 7 8 9 10
>>>

포인터

포인터 인스턴스는 ctypes 형에 pointer() 함수를 호출해서 만듭니다:

>>> from ctypes import *
>>> i = c_int(42)
>>> pi = pointer(i)
>>>

포인터 인스턴스는 포인터가 가리키는 객체(위에서는 i 객체)를 반환하는 contents 어트리뷰트를 가집니다:

>>> pi.contents
c_long(42)
>>>

ctypes에는 OOR(원래 객체 반환, original object return)이 없다는 것에 유의하십시오. 어트리뷰트를 가져올 때마다 (동등하지만) 새로운 객체를 만듭니다:

>>> pi.contents is i
False
>>> pi.contents is pi.contents
False
>>>

다른 c_int 인스턴스를 포인터의 contents 어트리뷰트에 대입하면 포인터는 이 인스턴스가 저장되어있는 메모리 위치를 가리키게 됩니다:

>>> i = c_int(99)
>>> pi.contents = i
>>> pi.contents
c_long(99)
>>>

포인터 인스턴스는 정수로도 인덱싱할 수 있습니다.:

>>> pi[0]
99
>>>

정수 인덱스에 대입하면 가리키고 있는 값이 바뀝니다:

>>> print(i)
c_long(99)
>>> pi[0] = 22
>>> print(i)
c_long(22)
>>>

0이 아닌 인덱스를 사용할 수도 있지만, C에서와 마찬가지로 자신이 하는 일을 알아야 합니다: 임의의 메모리 위치를 액세스하거나 변경할 수 있습니다. 일반적으로 C 함수에서 포인터를 받고, 포인터가 실제로 단일 항목 대신 배열을 가리키는 것을 알 때만 이 기능을 사용합니다.

장막 뒤에서, pointer() 함수는 단순히 포인터 인스턴스를 만드는 것 이상을 수행합니다. 먼저 포인터 형을 만들어야 합니다. 이것은 임의의 ctypes 형을 받아들이고, 새로운 형을 반환하는 POINTER() 함수로 수행됩니다:

>>> PI = POINTER(c_int)
>>> PI
<class 'ctypes.LP_c_long'>
>>> PI(42)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: expected c_long instead of int
>>> PI(c_int(42))
<ctypes.LP_c_long object at 0x...>
>>>

인자 없이 포인터형을 호출하면 NULL 포인터가 만들어집니다. NULL 포인터는 False 논릿값을 갖습니다:

>>> null_ptr = POINTER(c_int)()
>>> print(bool(null_ptr))
False
>>>

ctypes는 포인터를 역참조(dereference)할 때 NULL인지 확인합니다 (하지만 NULL이 아닌 잘못된 포인터를 역참조하면 파이썬을 충돌시킵니다):

>>> null_ptr[0]
Traceback (most recent call last):
    ....
ValueError: NULL pointer access
>>>

>>> null_ptr[0] = 1234
Traceback (most recent call last):
    ....
ValueError: NULL pointer access
>>>

형 변환

일반적으로, ctypes는 엄격한 형 검사를 수행합니다. 이는 함수의 argtypes 목록에 POINTER(c_int)가 있거나, 구조체 멤버 필드의 형이 그런 형이라면, 정확히 같은 형의 인스턴스만 허용됨을 뜻합니다. 이 규칙에는 ctypes가 다른 객체를 허용하는 몇 가지 예외가 있습니다. 예를 들어, 포인터형 대신 호환 가능한 배열 인스턴스를 전달할 수 있습니다. 따라서 POINTER(c_int)의 경우, ctype은 c_int 배열을 허용합니다:

>>> class Bar(Structure):
...     _fields_ = [("count", c_int), ("values", POINTER(c_int))]
...
>>> bar = Bar()
>>> bar.values = (c_int * 3)(1, 2, 3)
>>> bar.count = 3
>>> for i in range(bar.count):
...     print(bar.values[i])
...
1
2
3
>>>

또한, 함수 인자가 argtypes에 포인터형(가령 POINTER(c_int))으로 명시적으로 선언되면, 대상형(이 경우 c_int)의 객체를 함수에 전달할 수 있습니다. 이때 ctypes는 필요한 byref() 변환을 자동으로 적용합니다.

POINTER 형 필드를 NULL로 설정하려면, None을 대입할 수 있습니다:

>>> bar.values = None
>>>

때에 따라 호환되지 않는 형의 인스턴스가 있을 수 있습니다. C에서는, 한 형을 다른 형으로 강제 변환(cast)할 수 있습니다. ctypes는 같은 방식으로 사용할 수 있는 cast() 함수를 제공합니다. 위에 정의된 Bar 구조체는 values 필드에 대해 POINTER(c_int) 포인터나 c_int 배열을 받아들이지만 다른 형의 인스턴스는 허용하지 않습니다:

>>> bar.values = (c_byte * 4)()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: incompatible types, c_byte_Array_4 instance instead of LP_c_long instance
>>>

이럴 때, cast() 함수가 편리합니다.

cast() 함수는 ctypes 인스턴스를 다른 ctypes 데이터형에 대한 포인터로 변환하는 데 사용할 수 있습니다. cast()는 두 개의 매개 변수, 어떤 종류의 포인터로 변환될 수 있는 ctypes 객체와 ctypes 포인터형을 받아들입니다. 첫 번째 인자와 같은 메모리 블록을 참조하는 두 번째 인자의 인스턴스를 반환합니다:

>>> a = (c_byte * 4)()
>>> cast(a, POINTER(c_int))
<ctypes.LP_c_long object at ...>
>>>

따라서, cast()는 Bar 구조체의 values 필드에 대입하는 데 사용할 수 있습니다:

>>> bar = Bar()
>>> bar.values = cast((c_byte * 4)(), POINTER(c_int))
>>> print(bar.values[0])
0
>>>

불완전한 형

불완전한 형은 멤버가 아직 지정되지 않은 구조체, 공용체 또는 배열입니다. C에서, 이것들은 나중에 정의되는 전방 선언(forward declaration)으로 지정됩니다:

struct cell; /* forward declaration */

struct cell {
    char *name;
    struct cell *next;
};

ctypes 코드로 그대로 옮기면 이렇게 되지만, 작동하지는 않습니다:

>>> class cell(Structure):
...     _fields_ = [("name", c_char_p),
...                 ("next", POINTER(cell))]
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in cell
NameError: name 'cell' is not defined
>>>

새 class cell은 클래스 문 자체에서 사용할 수 없기 때문입니다. ctypes에서는, cell 클래스를 정의한 다음, class 문 뒤에서 _fields_ 어트리뷰트를 설정할 수 있습니다:

>>> from ctypes import *
>>> class cell(Structure):
...     pass
...
>>> cell._fields_ = [("name", c_char_p),
...                  ("next", POINTER(cell))]
>>>

Let’s try it. We create two instances of cell, and let them point to each other, and finally follow the pointer chain a few times:

>>> c1 = cell()
>>> c1.name = "foo"
>>> c2 = cell()
>>> c2.name = "bar"
>>> c1.next = pointer(c2)
>>> c2.next = pointer(c1)
>>> p = c1
>>> for i in range(8):
...     print(p.name, end=" ")
...     p = p.next[0]
...
foo bar foo bar foo bar foo bar
>>>

콜백 함수

ctypes는 파이썬 콜러블로부터 C에서 호출 가능한 함수 포인터를 만들 수 있습니다. 이들은 때로 콜백 함수(callback functions)라고 불립니다.

먼저, 콜백 함수를 위한 클래스를 만들어야 합니다. 클래스는 호출 규칙, 반환형 및 이 함수가 받는 인자의 수와 형을 알고 있습니다.

CFUNCTYPE() 팩토리 함수는 cdecl 호출 규칙을 사용하여 콜백 함수의 형을 만듭니다. 윈도우에서, WINFUNCTYPE() 팩토리 함수는 stdcall 호출 규칙을 사용하여 콜백 함수 형을 만듭니다.

이러한 팩토리 함수는 모두 첫 번째 인자로 결과 형을, 나머지 인자로 콜백 함수가 기대하는 인자 형들로 호출됩니다.

콜백 함수의 도움을 받아 항목을 정렬하는 데 사용되는 표준 C 라이브러리의 qsort() 함수를 사용하는 예제를 제시합니다. qsort()는 정수 배열을 정렬하는 데 사용될 것입니다:

>>> IntArray5 = c_int * 5
>>> ia = IntArray5(5, 1, 7, 33, 99)
>>> qsort = libc.qsort
>>> qsort.restype = None
>>>

qsort()는 정렬 할 데이터에 대한 포인터, 데이터 배열의 항목 수, 항목 하나의 크기 및 비교 함수에 대한 포인터인 콜백으로 호출해야 합니다. 콜백은 항목에 대한 두 개의 포인터로 호출되며, 첫 번째 항목이 두 번째 항목보다 작으면 음의 정수를, 같으면 0을, 그렇지 않으면 양수 정수를 반환해야 합니다.

따라서 콜백 함수는 정수에 대한 포인터들을 받고 정수를 반환해야 합니다. 먼저 콜백 함수를 위한 형을 만듭니다:

>>> CMPFUNC = CFUNCTYPE(c_int, POINTER(c_int), POINTER(c_int))
>>>

시작하기 위해, 전달된 값을 보여주는 간단한 콜백이 있습니다:

>>> def py_cmp_func(a, b):
...     print("py_cmp_func", a[0], b[0])
...     return 0
...
>>> cmp_func = CMPFUNC(py_cmp_func)
>>>

결과:

>>> qsort(ia, len(ia), sizeof(c_int), cmp_func)
py_cmp_func 5 1
py_cmp_func 33 99
py_cmp_func 7 33
py_cmp_func 5 7
py_cmp_func 1 7
>>>

이제 실제로 두 항목을 비교하여 유용한 결과를 반환할 수 있습니다:

>>> def py_cmp_func(a, b):
...     print("py_cmp_func", a[0], b[0])
...     return a[0] - b[0]
...
>>>
>>> qsort(ia, len(ia), sizeof(c_int), CMPFUNC(py_cmp_func))
py_cmp_func 5 1
py_cmp_func 33 99
py_cmp_func 7 33
py_cmp_func 1 7
py_cmp_func 5 7
>>>

쉽게 확인할 수 있듯이, 배열은 이제 정렬되었습니다:

>>> for i in ia: print(i, end=" ")
...
1 5 7 33 99
>>>

함수 팩토리는 데코레이터 팩토리로 사용할 수 있으므로, 다음과 같이 작성할 수도 있습니다:

>>> @CFUNCTYPE(c_int, POINTER(c_int), POINTER(c_int))
... def py_cmp_func(a, b):
...     print("py_cmp_func", a[0], b[0])
...     return a[0] - b[0]
...
>>> qsort(ia, len(ia), sizeof(c_int), py_cmp_func)
py_cmp_func 5 1
py_cmp_func 33 99
py_cmp_func 7 33
py_cmp_func 1 7
py_cmp_func 5 7
>>>

참고

C 코드에서 사용되는 동안 CFUNCTYPE() 객체에 대한 참조를 유지해야 합니다. ctypes가 참조를 유지하지는 않으며, 여러분이 하지 않는다면 가비지 수집되어, 콜백이 발생할 때 프로그램이 충돌할 수 있습니다.

또한, 콜백 함수가 파이썬 제어 바깥에서 만들어진 스레드(예를 들어, 콜백을 호출하는 외부 코드)에서 호출되면, ctypes는 모든 호출에 대해 새로운 더미 파이썬 스레드를 만듭니다. 이 동작은 대부분 적합하지만, threading.local에 저장된 값은, 같은 C 스레드에서 호출되는 여러 콜백에서 살아남을 수 없음을 뜻합니다.

dll에서 내 보낸 값을 액세스하기

일부 공유 라이브러리는 함수를 내보낼 뿐만 아니라 변수도 내보냅니다. 파이썬 라이브러리 자체에 있는 예는 Py_OptimizeFlag 인데, 시작 시 주어진 -O나 -OO 플래그에 따라, 0, 1 또는 2로 설정된 정수입니다.

ctypes는 형의 in_dll() 클래스 메서드를 사용하여 이와 같은 값을 액세스할 수 있습니다. pythonapi는 파이썬 C API에 대한 액세스를 제공하는 미리 정의된 심볼입니다:

>>> opt_flag = c_int.in_dll(pythonapi, "Py_OptimizeFlag")
>>> print(opt_flag)
c_long(0)
>>>

인터프리터가 -O로 시작되면, 예는 c_long(1)를, -OO가 지정되면 c_long(2)를 인쇄합니다.

포인터의 사용법도 보여주는 확장 예제는 파이썬이 내 보낸 PyImport_FrozenModules 포인터에 액세스합니다.

해당 값에 대한 문서를 인용하면:

This pointer is initialized to point to an array of struct _frozen records, terminated by one whose members are all NULL or zero. When a frozen module is imported, it is searched in this table. Third-party code could play tricks with this to provide a dynamically created collection of frozen modules.

따라서, 이 포인터를 조작하는 것이 유용할 수도 있습니다. 예제 크기를 제한하기 위해, ctypes로 이 테이블을 읽는 방법만 보여줍니다:

>>> from ctypes import *
>>>
>>> class struct_frozen(Structure):
...     _fields_ = [("name", c_char_p),
...                 ("code", POINTER(c_ubyte)),
...                 ("size", c_int)]
...
>>>

struct _frozen 데이터형을 정의했으므로, 테이블에 대한 포인터를 얻을 수 있습니다:

>>> FrozenTable = POINTER(struct_frozen)
>>> table = FrozenTable.in_dll(pythonapi, "PyImport_FrozenModules")
>>>

Since table is a pointer to the array of struct_frozen records, we can iterate over it, but we just have to make sure that our loop terminates, because pointers have no size. Sooner or later it would probably crash with an access violation or whatever, so it’s better to break out of the loop when we hit the NULL entry:

>>> for item in table:
...     if item.name is None:
...         break
...     print(item.name.decode("ascii"), item.size)
...
_frozen_importlib 31764
_frozen_importlib_external 41499
__hello__ 161
__phello__ -161
__phello__.spam 161
>>>

The fact that standard Python has a frozen module and a frozen package (indicated by the negative size member) is not well known, it is only used for testing. Try it out with import __hello__ for example.

의외의 것들

ctypes에는 여러분이 기대하는 것과 실제로 일어나는 것이 다른 가장자리가 있습니다.

다음 예제를 고려해보십시오:

>>> from ctypes import *
>>> class POINT(Structure):
...     _fields_ = ("x", c_int), ("y", c_int)
...
>>> class RECT(Structure):
...     _fields_ = ("a", POINT), ("b", POINT)
...
>>> p1 = POINT(1, 2)
>>> p2 = POINT(3, 4)
>>> rc = RECT(p1, p2)
>>> print(rc.a.x, rc.a.y, rc.b.x, rc.b.y)
1 2 3 4
>>> # now swap the two points
>>> rc.a, rc.b = rc.b, rc.a
>>> print(rc.a.x, rc.a.y, rc.b.x, rc.b.y)
3 4 3 4
>>>

흠. 아마도 마지막 문장이 3 4 1 2를 인쇄할 것으로 기대했을 겁니다. 어떻게 된 걸까요? 위의 rc.a, rc.b = rc.b, rc.a 줄의 단계는 다음과 같습니다:

>>> temp0, temp1 = rc.b, rc.a
>>> rc.a = temp0
>>> rc.b = temp1
>>>

temp0 과 temp1은 여전히 위의 rc 객체의 내부 버퍼를 사용하는 객체입니다. 따라서 rc.a = temp0를 실행하면 temp0의 버퍼 내용이 rc의 버퍼로 복사됩니다. 이것은, 결과적으로 temp1의 내용을 변경합니다. 따라서 마지막 대입인 rc.b = temp1은 기대하는 효과를 주지 못합니다.

Structure, Union 및 Array에서 서브 객체를 가져오는 것은 서브 객체를 복사하지 않고, 대신 루트 객체의 하부 버퍼에 액세스하는 래퍼 객체를 가져온다는 점에 유의하십시오.

Another example that may behave differently from what one would expect is this:

>>> s = c_char_p()
>>> s.value = b"abc def ghi"
>>> s.value
b'abc def ghi'
>>> s.value is s.value
False
>>>

참고

Objects instantiated from c_char_p can only have their value set to bytes or integers.

False를 인쇄하는 이유는 무엇일까요? ctypes 인스턴스는 메모리 블록과 메모리 내용에 액세스하는 어떤 디스크립터를 포함하는 객체입니다. 메모리 블록에 파이썬 객체를 저장하면 객체 자체를 저장하지 않고, 대신 객체의 내용을 저장합니다. 내용에 다시 액세스하면 매번 새로운 파이썬 객체가 생성됩니다!

가변 크기 데이터형

ctypes는 가변 크기 배열과 구조체에 대한 일부 지원을 제공합니다.

resize() 함수는 기존 ctypes 객체의 메모리 버퍼 크기를 바꾸는 데 사용할 수 있습니다. 이 함수는 객체를 첫 번째 인자로 가져오고, 바이트 단위의 요청 된 크기를 두 번째 인자로 가져옵니다. 메모리 블록을 객체 형이 지정하는 원래 메모리 블록보다 작게 만들 수 없습니다. 시도하면 ValueError가 발생합니다:

>>> short_array = (c_short * 4)()
>>> print(sizeof(short_array))
8
>>> resize(short_array, 4)
Traceback (most recent call last):
    ...
ValueError: minimum size is 8
>>> resize(short_array, 32)
>>> sizeof(short_array)
32
>>> sizeof(type(short_array))
8
>>>

훌륭합니다, 하지만 이 배열에 포함된 추가 요소에 어떻게 액세스할 수 있습니까? 형은 여전히 4개의 요소만 알고 있으므로, 다른 요소에 액세스하면 에러가 발생합니다:

>>> short_array[:]
[0, 0, 0, 0]
>>> short_array[7]
Traceback (most recent call last):
    ...
IndexError: invalid index
>>>

ctypes에서 가변 크기 데이터형을 사용하는 또 다른 방법은, 파이썬의 동적 특성을 사용하고 필요한 크기가 이미 알려진 후 매번 데이터형을 (재) 정의하는 것입니다.

ctypes 레퍼런스

공유 라이브러리 찾기

컴파일 언어로 프로그래밍할 때, 공유 라이브러리는 프로그램을 컴파일/링크할 때와 프로그램을 실행할 때 액세스 됩니다.

find_library() 함수의 목적은 컴파일러나 실행 시간 로더가 하는 것과 비슷한 방식으로 라이브러리를 찾는 것입니다 (여러 버전의 공유 라이브러리가 있는 플랫폼에서는 가장 최근의 것을 로드해야 합니다). 반면에 ctypes 라이브러리 로더는 프로그램이 실행될 때처럼 동작하고, 실행 시간 로더를 직접 호출합니다.

ctypes.util 모듈은 로드할 라이브러리를 판별하는 데 도움이 되는 함수를 제공합니다.

ctypes.util.find_library(name)

라이브러리를 찾아서 경로명을 반환하려고 시도합니다. name은 lib 같은 접두사, .so, .dylib 또는 버전 번호와 같은 접미사가 없는 라이브러리 이름입니다 (이것은 posix 링커 옵션 -l에 사용되는 양식입니다). 라이브러리를 찾을 수 없으면 None을 반환합니다.

정확한 기능은 시스템에 따라 다릅니다.

리눅스에서, find_library()는 외부 프로그램(/sbin/ldconfig, gcc, objdump 및 ld)을 실행하여 라이브러리 파일을 찾으려고 합니다. 라이브러리 파일의 파일명을 반환합니다.

버전 3.6에서 변경: 리눅스에서, 다른 수단으로 라이브러리를 찾을 수 없으면, 라이브러리 검색 시 환경 변수 LD_LIBRARY_PATH의 값이 사용됩니다.

여기 예제가 있습니다:

>>> from ctypes.util import find_library
>>> find_library("m")
'libm.so.6'
>>> find_library("c")
'libc.so.6'
>>> find_library("bz2")
'libbz2.so.1.0'
>>>

OS X에서, find_library()는 라이브러리를 찾기 위해 미리 정의된 몇 가지 명명 체계와 경로를 시도하고 성공하면 전체 경로명을 반환합니다:

>>> from ctypes.util import find_library
>>> find_library("c")
'/usr/lib/libc.dylib'
>>> find_library("m")
'/usr/lib/libm.dylib'
>>> find_library("bz2")
'/usr/lib/libbz2.dylib'
>>> find_library("AGL")
'/System/Library/Frameworks/AGL.framework/AGL'
>>>

윈도우에서, find_library()는 시스템 검색 경로를 따라 검색하고 전체 경로명을 반환하지만, 미리 정의된 명명 체계가 없으므로 find_library("c")와 같은 호출은 실패하고 None을 반환합니다.

공유 라이브러리를 ctypes로 래핑하려면, 실행 시간에 라이브러리를 찾기 위해 find_library()를 사용하기보다, 개발 시점에 공유 라이브러리 이름을 확인하고 래퍼 모듈에 하드 코딩 하는 것이 더 좋을 수 있습니다.

공유 라이브러리 로드하기

공유 라이브러리를 파이썬 프로세스에 로드하는 방법에는 여러 가지가 있습니다. 한 가지 방법은 다음 클래스 중 하나의 인스턴스를 만드는 것입니다:

class ctypes.CDLL(name, mode=DEFAULT_MODE, handle=None, use_errno=False, use_last_error=False)

이 클래스의 인스턴스는 로드된 공유 라이브러리를 나타냅니다. 이 라이브러리의 함수는 표준 C 호출 규칙을 사용하며, int를 반환한다고 가정합니다.

class ctypes.OleDLL(name, mode=DEFAULT_MODE, handle=None, use_errno=False, use_last_error=False)

윈도우 전용: 이 클래스의 인스턴스는 로드된 공유 라이브러리를 나타내며, 이 라이브러리의 함수는 stdcall 호출 규칙을 사용하고, 윈도우 특정 HRESULT 코드를 반환한다고 가정합니다. HRESULT 값에는 함수 호출이 실패했는지 또는 성공했는지와 추가 에러 코드를 지정하는 정보가 들어 있습니다. 반환 값이 실패를 알리면, OSError가 자동으로 발생합니다.

버전 3.3에서 변경: WindowsError를 발생시켰었습니다.

class ctypes.WinDLL(name, mode=DEFAULT_MODE, handle=None, use_errno=False, use_last_error=False)

윈도우 전용: 이 클래스의 인스턴스는 로드된 공유 라이브러리를 나타내며, 이 라이브러리의 함수는 stdcall 호출 규칙을 사용하고, 기본적으로 int를 반환한다고 가정합니다.

윈도우 CE에서는 오직 표준 호출 규칙만 사용됩니다. 편의상 WinDLL 와 OleDLL은, 이 플랫폼에서 표준 호출 규칙을 사용합니다.

파이썬 전역 인터프리터 록은, 이 라이브러리들이 내보낸 함수를 호출하기 전에 해제되고 나중에 다시 획득됩니다.

class ctypes.PyDLL(name, mode=DEFAULT_MODE, handle=None)

이 클래스의 인스턴스는 CDLL 인스턴스처럼 동작합니다. 단, 파이썬 GIL이 함수 호출 중에 릴리스 되지 않고, 함수 실행 후 파이썬 에러 플래그가 확인된다는 점만 다릅니다. 에러 플래그가 설정되면 파이썬 예외가 발생합니다.

따라서, 이것은 파이썬 C API 함수를 직접 호출하는 경우에만 유용합니다.

이러한 모든 클래스는 공유 라이브러리의 경로명인 적어도 하나의 인자를 사용하여 인스턴스를 만들 수 있습니다. 이미 로드된 공유 라이브러리에 대한 기존 핸들이 있으면, 이를 handle 이라고 이름 붙은 매개 변수로 전달할 수 있습니다. 그렇지 않으면 하부 플랫폼의 dlopen 이나 LoadLibrary 함수를 사용하여 라이브러리를 프로세스에 로드하고 이에 대한 핸들을 확보합니다.

mode 매개 변수는 라이브러리가 로드되는 방법을 지정하는 데 사용될 수 있습니다. 자세한 내용은, dlopen(3) 매뉴얼 페이지를 참조하십시오. 윈도우에서는, mode가 무시됩니다. posix 시스템에서는 RTLD_NOW가 항상 추가되며 구성할 수 없습니다.

use_errno 매개 변수를 참으로 설정하면 시스템 errno 에러 번호에 안전하게 액세스할 수 있는 ctypes 메커니즘을 활성화합니다. ctypes는 시스템 errno 변수의 스레드 로컬 사본을 유지합니다; use_errno=True로 만든 외부 함수를 호출하면 함수 호출 전에 errno 값이 ctypes 내부 복사본과 스와프되며 함수 호출 직후에도 마찬가지 작업을 합니다.

ctypes.get_errno() 함수는 ctypes 내부 사본의 값을 반환하고, ctypes.set_errno() 함수는 ctypes 내부 사본을 새 값으로 변경하고 이전 값을 반환합니다.

use_last_error 매개 변수를 참으로 설정하면, GetLastError() 와 SetLastError() 윈도우 API 함수에서 관리하는 윈도우 에러 코드에 대해 같은 메커니즘을 활성화합니다. ctypes.get_last_error()와 ctypes.set_last_error()는 윈도우 에러 코드의 ctypes 내부 사본을 요청하고 변경하는 데 사용됩니다.

ctypes.RTLD_GLOBAL

mode 매개 변수에 사용하는 플래그. 이 플래그를 사용할 수 없는 플랫폼에서는, 정수 0으로 정의됩니다.

ctypes.RTLD_LOCAL

mode 매개 변수에 사용하는 플래그. 이 플래그를 사용할 수 없는 플랫폼에서는, RTLD_GLOBAL과 같습니다.

ctypes.DEFAULT_MODE

공유 라이브러리를 로드하는 데 사용되는 기본 모드. OSX 10.3에서는 RTLD_GLOBAL이고, 그렇지 않으면 RTLD_LOCAL과 같습니다.

이 클래스들의 인스턴스는 공개 메서드가 없습니다. 공유 라이브러리가 내보낸 함수는 어트리뷰트나 인덱스로 액세스할 수 있습니다. 어트리뷰트를 통해 함수에 액세스하면 결과가 캐시 되므로 반복적으로 액세스할 때 매번 같은 객체가 반환됨에 유의하십시오. 반면에 인덱스를 통해 액세스하면 매번 새로운 객체가 반환됩니다:

>>> from ctypes import CDLL
>>> libc = CDLL("libc.so.6")  # On Linux
>>> libc.time == libc.time
True
>>> libc['time'] == libc['time']
False

다음 공개 어트리뷰트를 사용할 수 있습니다. 내보낸 함수 이름과의 충돌을 피하고자 이름은 밑줄로 시작합니다:

PyDLL._handle

라이브러리에 액세스하는 데 사용되는 시스템 핸들.

PyDLL._name

생성자에서 전달된 라이브러리의 이름.

공유 라이브러리는 LibraryLoader 클래스의 인스턴스인 사전 작성된 객체 중 하나를 사용하여 로드 할 수도 있습니다. 로더의 LoadLibrary() 메서드를 호출하거나 로더 인스턴스의 어트리뷰트로 라이브러리를 조회합니다.

class ctypes.LibraryLoader(dlltype)

공유 라이브러리를 로드하는 클래스. dlltype은 CDLL, PyDLL, WinDLL 또는 OleDLL 형 중 하나여야 합니다.

__getattr__()에는 특수한 동작이 있습니다: 라이브러리 로더 인스턴스의 어트리뷰트를 액세스하여 공유 라이브러리를 로드 할 수 있게 합니다. 결과는 캐시 되므로 반복되는 어트리뷰트 액세스는 매번 같은 라이브러리를 반환합니다.

LoadLibrary(name)

공유 라이브러리를 프로세스에 로드하고 반환합니다. 이 메서드는 항상 라이브러리의 새 인스턴스를 반환합니다.

다음과 같은 사전 작성된 로더를 사용할 수 있습니다:

ctypes.cdll

CDLL 인스턴스를 만듭니다.

ctypes.windll

윈도우 전용: WinDLL 인스턴스를 만듭니다.

ctypes.oledll

윈도우 전용: OleDLL 인스턴스를 만듭니다.

ctypes.pydll

PyDLL 인스턴스를 만듭니다.

C 파이썬 API에 직접 액세스하기 위해, 바로 사용할 수 있는 파이썬 공유 라이브러리 객체가 제공됩니다:

ctypes.pythonapi

파이썬 C API 함수를 어트리뷰트로 노출하는 PyDLL의 인스턴스. 이 모든 함수는 C int를 반환한다고 가정하는데, 물론 항상 옳지는 않습니다. 그런 함수를 사용하려면 올바른 restype 어트리뷰트를 대입해야 합니다.

외부 함수

이전 섹션에서 설명한 것처럼, 외부 함수는 로드된 공유 라이브러리의 어트리뷰트로 액세스할 수 있습니다. 이런 방식으로 만들어진 함수 객체는 기본적으로 임의의 개수 인자를 허용하고, 임의의 ctypes 데이터 인스턴스를 인자로 받아들이고, 라이브러리 로더에 의해 지정된 기본 결과형을 반환합니다. 이것들은 내부 클래스의 인스턴스입니다:

class ctypes._FuncPtr

C 호출 가능한 외부 함수의 베이스 클래스.

외부 함수의 인스턴스는 C 호환 데이터형이기도 합니다; C 함수 포인터를 나타냅니다.

이 동작은 외부 함수 객체의 특수 어트리뷰트에 대입하여 사용자 정의할 수 있습니다.

restype

ctypes 형을 대입하여 외부 함수의 결과형을 지정합니다. 아무것도 반환하지 않는 함수인 void는 None를 사용하십시오.

ctypes 형이 아닌 콜러블 파이썬 객체를 대입할 수 있습니다. 이때 함수는 C int를 반환한다고 가정하고, 이 콜러블 객체는 이 정수로 호출되어, 사후 처리나 에러 검사를 허용합니다. 이 기능을 사용하는 것은 폐지되었습니다. 더 유연한 사후 처리나 에러 검사를 위해, ctypes 데이터형을 restype로 사용하고, 콜러블을 errcheck 어트리뷰트에 대입하십시오.

argtypes

ctypes 형의 튜플을 대입하여 함수가 받아들이는 인자 형을 지정합니다. stdcall 호출 규칙을 사용하는 함수는 이 튜플의 길이와 같은 수의 인자로만 호출할 수 있습니다; C 호출 규칙을 사용하는 함수는 추가적인 지정되지 않은 인자도 허용합니다.

외부 함수가 호출될 때, 각 실제 인자는 argtypes 튜플의 항목의 from_param() 클래스 메서드에 전달됩니다. 이 메서드는 실제 인자를 외부 함수가 받아들이는 객체에 맞출 수 있습니다. 예를 들어, argtypes 튜플의 c_char_p 항목은 ctypes 변환 규칙을 사용하여 인자로 전달된 문자열을 바이트열 객체로 변환합니다.

새로운 기능: 이제 ctypes 형이 아닌 항목을 argtypes에 넣을 수 있습니다. 하지만 각 항목에는 인자로 사용할 수 있는 값(정수, 문자열, ctypes 인스턴스)을 반환하는 from_param() 메서드가 있어야 합니다. 이를 통해 사용자 정의 객체를 함수 매개 변수로 맞출 수 있는 어댑터를 정의 할 수 있습니다.

errcheck

이 어트리뷰트에 파이썬 함수나 다른 콜러블을 대입합니다. 콜러블은 3개 이상의 인자로 호출됩니다:

callable(result, func, arguments)

result는 restype 어트리뷰트에 지정된 대로 외부 함수가 반환하는 것입니다.

func는 외부 함수 객체 자체이며, 같은 콜러블 객체를 재사용하여 여러 함수의 결과를 확인하거나 사후 처리할 수 있도록 합니다.

arguments는 원래 함수 호출에 전달된 매개 변수를 포함하는 튜플입니다. 사용된 인자에 따라 동작을 특수화할 수 있도록 합니다.

이 함수가 반환하는 객체는 외부 함수 호출에서 반환되지만, 결괏값을 확인하고 외부 함수 호출이 실패하면 예외를 발생시킬 수도 있습니다.

exception ctypes.ArgumentError

외부 함수 호출이 전달된 인자 중 하나를 변환할 수 없을 때 발생하는 예외.

함수 프로토타입

함수 프로토타입의 인스턴스를 만들어서 외부 함수를 만들 수도 있습니다. 함수 프로토타입은 C의 함수 프로토타입과 비슷합니다; 구현을 정의하지 않고 함수(반환형, 인자형, 호출 규칙)를 설명합니다. 팩토리 함수는 원하는 결과형과 함수의 인자형들로 호출되어야 하며, 데코레이터 팩토리로 사용되어 @wrapper 문법을 통해 함수에 적용될 수 있습니다. 예제는 콜백 함수를 참조하십시오.

ctypes.CFUNCTYPE(restype, *argtypes, use_errno=False, use_last_error=False)

반환된 함수 프로토타입은 표준 C 호출 규칙을 사용하는 함수를 만듭니다. 이 함수는 호출 중에 GIL을 해제합니다. use_errno를 참으로 설정하면, 시스템 errno 변수의 ctypes 내부 복사본이 호출 전후에 실제 errno 값과 교환됩니다; use_last_error는 윈도우 에러 코드에 대해 같은 일을 합니다.

ctypes.WINFUNCTYPE(restype, *argtypes, use_errno=False, use_last_error=False)

윈도우 전용: 반환된 함수 프로토타입은 stdcall 호출 규칙을 사용하는 함수를 만듭니다. 단 WINFUNCTYPE()이 CFUNCTYPE()과 같은 윈도우 CE는 예외입니다. 이 함수는 호출 중에 GIL을 해제합니다. use_errno 와 use_last_error는 위에서와 같은 의미가 있습니다.

ctypes.PYFUNCTYPE(restype, *argtypes)

반환된 함수 프로토타입은 파이썬 호출 규칙을 사용하는 함수를 만듭니다. 이 함수는 호출 도중 GIL을 해제하지 않습니다.

이러한 팩토리 함수로 만들어진 함수 프로토타입은 호출의 매개 변수 형과 수에 따라 다른 방법으로 인스턴스를 만들 수 있습니다:

prototype(address)

지정된 정수 주소에 있는 외부 함수를 반환합니다.

prototype(callable)

파이썬 callable로 C 호출 가능 함수(콜백 함수)를 만듭니다.

prototype(func_spec[, paramflags])

공유 라이브러리가 내보낸 외부 함수를 반환합니다. func_spec은 2-튜플 (name_or_ordinal, library) 여야 합니다. 첫 번째 항목은 내보낸 함수의 문자열 이름이거나, 작은 정수로 표현된 내보낸 함수의 서수(ordinal)입니다. 두 번째 항목은 공유 라이브러리 인스턴스입니다.

prototype(vtbl_index, name[, paramflags[, iid]])

COM 메서드를 호출할 외부 함수를 반환합니다. vtbl_index는 가상 함수 테이블에 대한 인덱스이며, 작은 음이 아닌 정수입니다. name은 COM 메서드의 이름입니다. iid는 확장 에러 보고에 사용되는 인터페이스 식별자를 가리키는 선택적 포인터입니다.

COM 메서드는 특별한 호출 규칙을 사용합니다: argtypes 튜플에 지정된 매개 변수 외에, 첫 번째 인자로 COM 인터페이스에 대한 포인터가 필요합니다.

선택적 paramflags 매개 변수는 위에 설명된 기능보다 훨씬 많은 기능을 갖는 외부 함수 래퍼를 만듭니다.

paramflags는 argtypes와 같은 길이의 튜플이어야 합니다.

이 튜플의 각 항목에는 매개 변수에 대한 추가 정보가 들어 있으며, 한 개, 두 개 또는 세 개의 항목이 들어있는 튜플이어야 합니다.

첫 번째 항목은 매개 변수의 방향 플래그 조합을 포함하는 정수입니다:

1

함수에 대한 입력 매개 변수를 지정합니다.

2

출력 매개 변수. 외부 함수가 값을 채웁니다.

4

기본값이 정수 0인 입력 매개 변수.

선택적인 두 번째 항목은 문자열 매개 변수 이름입니다. 이것이 지정되면, 이름있는 매개 변수로 외부 함수를 호출할 수 있습니다.

선택적 세 번째 항목은 이 매개 변수의 기본값입니다.

이 예제는 기본값이 있는 매개 변수와 이름있는 인자를 지원하도록 윈도우 MessageBoxW 함수를 래핑하는 방법을 보여줍니다. 윈도우 헤더 파일의 C 선언은 다음과 같습니다:

WINUSERAPI int WINAPI
MessageBoxW(
    HWND hWnd,
    LPCWSTR lpText,
    LPCWSTR lpCaption,
    UINT uType);

다음은 ctypes로 래핑하는 방법입니다:

>>> from ctypes import c_int, WINFUNCTYPE, windll
>>> from ctypes.wintypes import HWND, LPCWSTR, UINT
>>> prototype = WINFUNCTYPE(c_int, HWND, LPCWSTR, LPCWSTR, UINT)
>>> paramflags = (1, "hwnd", 0), (1, "text", "Hi"), (1, "caption", "Hello from ctypes"), (1, "flags", 0)
>>> MessageBox = prototype(("MessageBoxW", windll.user32), paramflags)

이제 MessageBox 외부 함수를 다음과 같이 호출할 수 있습니다.:

>>> MessageBox()
>>> MessageBox(text="Spam, spam, spam")
>>> MessageBox(flags=2, text="foo bar")

두 번째 예제는 출력 매개 변수를 보여줍니다. win32 GetWindowRect 함수는 지정된 창의 크기를 조회하는데, 호출자가 제공해야 하는 RECT 구조체로 복사합니다. 다음은 C 선언입니다:

WINUSERAPI BOOL WINAPI
GetWindowRect(
     HWND hWnd,
     LPRECT lpRect);

다음은 ctypes로 래핑하는 방법입니다:

>>> from ctypes import POINTER, WINFUNCTYPE, windll, WinError
>>> from ctypes.wintypes import BOOL, HWND, RECT
>>> prototype = WINFUNCTYPE(BOOL, HWND, POINTER(RECT))
>>> paramflags = (1, "hwnd"), (2, "lprect")
>>> GetWindowRect = prototype(("GetWindowRect", windll.user32), paramflags)
>>>

출력 매개 변수가 있는 함수는, 하나뿐이면 자동으로 출력 매개 변숫값을 반환하고, 여러 개면 출력 매개 변숫값을 포함하는 튜플을 반환하므로, GetWindowRect 함수는 이제 호출되면 RECT 인스턴스를 반환합니다.

출력 매개 변수는 errcheck 프로토콜과 결합하여 추가적인 출력 처리와 에러 검사를 수행할 수 있습니다. win32 GetWindowRect api 함수는 성공이나 실패를 알리기 위해 BOOL을 반환하므로, 이 함수는 에러 검사를 수행하고 API 호출이 실패했을 때 예외를 발생시킬 수 있습니다:

>>> def errcheck(result, func, args):
...     if not result:
...         raise WinError()
...     return args
...
>>> GetWindowRect.errcheck = errcheck
>>>

errcheck 함수가 수신한 인자 튜플을 변경 없이 반환하면, ctypes는 출력 매개 변수에 수행하는 일반 처리를 계속합니다. RECT 인스턴스 대신 창 좌표의 튜플을 반환하려면, 함수에서 필드를 조회해서 대신 반환하면 됩니다, 이때는 일반 처리가 더는 수행되지 않습니다:

>>> def errcheck(result, func, args):
...     if not result:
...         raise WinError()
...     rc = args[1]
...     return rc.left, rc.top, rc.bottom, rc.right
...
>>> GetWindowRect.errcheck = errcheck
>>>

유틸리티 함수

ctypes.addressof(obj)

메모리 버퍼의 주소를 정수로 반환합니다. obj는 ctypes 형의 인스턴스여야 합니다.

ctypes.alignment(obj_or_type)

ctypes 형의 정렬 요구 사항을 반환합니다. obj_or_type는 ctypes 형이나 인스턴스여야 합니다.

ctypes.byref(obj[, offset])

obj에 대한 경량 포인터를 반환합니다. obj는 ctypes 형의 인스턴스여야 합니다. offset의 기본값은 0이며, 내부 포인터 값에 더해질 정수여야 합니다.

byref(obj, offset)는 이 C 코드에 해당합니다:

(((char *)&obj) + offset)

반환된 객체는 외부 함수 호출 매개 변수로만 사용할 수 있습니다. pointer(obj)와 비슷하게 동작하지만, 훨씬 빨리 만들어집니다.

ctypes.cast(obj, type)

이 함수는 C의 형 변환 연산자와 유사합니다. obj와 같은 메모리 블록을 가리키는 type 형의 새 인스턴스를 반환합니다. type은 포인터형이어야 하며, obj는 포인터로 해석될 수 있는 객체여야 합니다.

ctypes.create_string_buffer(init_or_size, size=None)

이 함수는 가변 문자 버퍼를 만듭니다. 반환된 객체는 c_char의 ctypes 배열입니다.

init_or_size는 배열의 크기를 지정하는 정수거나 배열 항목을 초기화하는 데 사용될 바이트열 객체여야 합니다.

바이트열 객체가 첫 번째 인자로 지정되면, 버퍼의 길이는 이 객체의 길이보다 한 항목만큼 길어져서, 배열의 마지막 요소가 NUL 종료 문자가 됩니다. 두 번째 인자로 정수를 전달하면 바이트열의 길이를 사용하지 않고 배열의 크기를 지정할 수 있습니다.

ctypes.create_unicode_buffer(init_or_size, size=None)

이 함수는 가변 유니코드 문자 버퍼를 만듭니다. 반환된 객체는 c_wchar의 ctypes 배열입니다.

init_or_size는 배열의 크기를 지정하는 정수거나 배열 항목을 초기화하는 데 사용될 문자열이어야 합니다.

문자열이 첫 번째 인자로 지정되면, 버퍼의 길이는 문자열의 길이보다 한 항목만큼 길어져서, 배열의 마지막 요소가 NUL 종료 문자가 됩니다. 두 번째 인자로 정수를 전달하면 문자열의 길이를 사용하지 않고 배열의 크기를 지정할 수 있습니다.

ctypes.DllCanUnloadNow()

윈도우 전용: 이 함수는 ctypes로 프로세스 내부(in-process) COM 서버를 구현하게 하는 훅입니다. _ctypes 확장 dll이 내보내는 DllCanUnloadNow 함수에서 호출됩니다.

ctypes.DllGetClassObject()

윈도우 전용: 이 함수는 ctypes로 프로세스 내부(in-process) COM 서버를 구현하게 하는 훅입니다. _ctypes 확장 dll이 내보내는 DllGetClassObject 함수에서 호출됩니다.

ctypes.util.find_library(name)

라이브러리를 찾아서 경로명을 반환하려고 시도합니다. name은 lib 같은 접두사, .so, .dylib 또는 버전 번호와 같은 접미사가 없는 라이브러리 이름입니다 (이것은 posix 링커 옵션 -l에 사용되는 양식입니다). 라이브러리를 찾을 수 없으면 None을 반환합니다.

정확한 기능은 시스템에 따라 다릅니다.

ctypes.util.find_msvcrt()

윈도우 전용: 파이썬과 확장 모듈이 사용하는 VC 런타임 라이브러리의 파일명을 반환합니다. 라이브러리의 이름을 판별할 수 없으면 None이 반환됩니다.

예를 들어, free(void *)에 대한 호출로 확장 모듈에 의해 할당된 메모리를 해제해야 하면, 메모리를 할당한 것과 같은 라이브러리에 있는 함수를 사용하는 것이 중요합니다.

ctypes.FormatError([code])

윈도우 전용: 에러 코드 code의 텍스트 설명을 반환합니다. 에러 코드를 지정하지 않으면 윈도우 API 함수 GetLastError를 호출하여 마지막 에러 코드가 사용됩니다.

ctypes.GetLastError()

윈도우 전용: 호출 스레드에서 윈도우가 설정한 마지막 에러 코드를 반환합니다. 이 함수는 윈도우 GetLastError() 함수를 직접 호출합니다. 에러 코드의 ctypes 내부 복사본을 반환하지 않습니다.

ctypes.get_errno()

호출하는 스레드에서 시스템 errno 변수의 ctypes 내부 복사본의 현재 값을 반환합니다.

ctypes.get_last_error()

윈도우 전용: 호출 중인 스레드에서 시스템 LastError 변수의 ctypes 내부 복사본의 현재 값을 반환합니다.

ctypes.memmove(dst, src, count)

표준 C memmove 라이브러리 함수와 같습니다: count 바이트를 src에서 dst로 복사합니다. dst 와 src는 정수이거나 포인터로 변환할 수 있는 ctypes 인스턴스여야 합니다.

ctypes.memset(dst, c, count)

표준 C memset 라이브러리 함수와 같습니다: 주소 dst의 메모리 블록을 값 c의 count 바이트로 채웁니다. dst는 주소를 지정하는 정수거나 ctypes 인스턴스여야 합니다.

ctypes.POINTER(type)

이 팩토리 함수는 새로운 ctypes 포인터형을 만들고 반환합니다. 포인터형은 캐시 되고 내부적으로 재사용되므로, 이 함수를 반복적으로 호출하는 것은 저렴합니다. type는 ctypes 형이어야 합니다.

ctypes.pointer(obj)

이 함수는 obj를 가리키는 새 포인터 인스턴스를 만듭니다. 반환된 객체는 형 POINTER(type(obj))입니다.

참고 사항: 객체에 대한 포인터를 단지 외부 함수 호출로 전달하려면 훨씬 빠른 byref(obj)를 사용해야 합니다.

ctypes.resize(obj, size)

이 함수는 obj의 내부 메모리 버퍼의 크기를 조정합니다. obj는 ctypes 형의 인스턴스여야 합니다. sizeof(type(obj))로 주어지는 객체 형의 원래 크기보다 버퍼를 작게 만들 수는 없지만, 버퍼를 확대할 수 있습니다.

ctypes.set_errno(value)

호출 중인 스레드의 시스템 errno 변수의 ctypes 내부 복사본의 현재 값을 value로 설정하고 이전 값을 반환합니다.

ctypes.set_last_error(value)

윈도우 전용: 호출 중인 스레드의 시스템 LastError 변수의 ctypes 내부 복사본의 현재 값을 value로 설정하고 이전 값을 반환합니다.

ctypes.sizeof(obj_or_type)

ctypes 형이나 인스턴스 메모리 버퍼의 크기를 바이트 단위로 반환합니다. C sizeof 연산자와 같은 일을 합니다.

ctypes.string_at(address, size=-1)

이 함수는 메모리 주소 address에서 시작하는 C 문자열을 바이트열 객체로 반환합니다. size가 지정되면 크기로 사용되며, 그렇지 않으면 문자열은 0으로 종료된다고 가정합니다.

ctypes.WinError(code=None, descr=None)

윈도우 전용: 이 함수는 아마도 ctypes에서 가장 이름을 잘못 붙인 것입니다. OSError의 인스턴스를 만듭니다. code를 지정하지 않으면, 에러 코드를 판별하기 위해 GetLastError가 호출됩니다. descr가 지정되지 않으면, 에러에 대한 텍스트 설명을 얻기 위해 FormatError()가 호출됩니다.

버전 3.3에서 변경: WindowsError의 인스턴스를 만들어왔습니다.

ctypes.wstring_at(address, size=-1)

이 함수는 메모리 주소 address에서 시작하는 광폭(wide) 문자열을 문자열로 반환합니다. size가 지정되면, 문자열의 문자 수로 사용되며, 그렇지 않으면 문자열은 0으로 종료된다고 가정합니다.

데이터형

class ctypes._CData

이 비공개 클래스는 모든 ctypes 데이터형의 공통 베이스 클래스입니다. 무엇보다도, 모든 ctypes 형 인스턴스에는 C 호환 데이터를 보관하는 메모리 블록이 포함됩니다; 메모리 블록의 주소는 addressof() 도우미 함수에 의해 반환됩니다. 다른 인스턴스 변수는 _objects로 노출됩니다; 여기에는 메모리 블록에 포인터가 포함되어있을 때, 살려둘 필요가 있는 다른 파이썬 객체가 포함되어 있습니다.

ctypes 데이터형의 공통 메서드, 이것들은 모두 클래스 메서드입니다 (정확히 말하면, 메타 클래스의 메서드입니다):

from_buffer(source[, offset])

이 메서드는 source 객체의 버퍼를 공유하는 ctypes 인스턴스를 반환합니다. source 객체는 쓰기 가능한 버퍼 인터페이스를 지원해야 합니다. 선택적 offset 매개 변수는 source 버퍼의 오프셋을 바이트 단위로 지정합니다; 기본값은 0입니다. source 버퍼가 충분히 크지 않으면 ValueError가 발생합니다.

from_buffer_copy(source[, offset])

이 메서드는 읽을 수 있어야 하는 source 객체 버퍼에서 버퍼를 복사하여 ctypes 인스턴스를 만듭니다. 선택적 offset 매개 변수는 원본 버퍼의 오프셋을 바이트 단위로 지정합니다. 기본값은 0입니다. 소스 버퍼가 충분히 크지 않으면 ValueError가 발생합니다.

from_address(address)

이 메서드는 정수 address로 지정된 메모리를 사용하여 ctypes 형 인스턴스를 반환합니다.

from_param(obj)

이 메서드는 obj를 ctypes 형에게 맞게 조정합니다. 형이 외부 함수의 argtypes 튜플에 존재할 때, 외부 함수 호출에 사용된 실제 객체로 호출됩니다; 함수 호출 매개 변수로 사용할 수 있는 객체를 반환 해야 합니다.

모든 ctypes 데이터형은 이 클래스 메서드의 기본 구현을 갖는데, obj 가 이 형의 인스턴스면 obj 를 반환합니다. 일부 형은 다른 객체도 허용합니다.

in_dll(library, name)

이 메서드는 공유 라이브러리가 내보낸 ctypes 형 인스턴스를 반환합니다. name은 데이터를 내보내는 심볼의 이름이고, library는 로드된 공유 라이브러리입니다.

ctypes 데이터형의 공통 인스턴스 변수:

_b_base_

때로 ctypes 데이터 인스턴스는 포함하는 메모리 블록을 소유하지 않고, 베이스 객체의 메모리 블록의 일부를 공유합니다. _b_base_ 읽기 전용 멤버는 메모리 블록을 소유한 루트 ctypes 객체입니다.

_b_needsfree_

이 읽기 전용 변수는 ctypes 데이터 인스턴스가 메모리 블록을 스스로 할당했을 때 참이고, 그렇지 않으면 거짓입니다.

_objects

이 멤버는 None 이거나 메모리 블록 내용이 계속 유효하도록 유지되어야 하는 파이썬 객체를 포함하는 딕셔너리입니다. 이 객체는 디버깅을 위해서만 노출됩니다; 이 딕셔너리의 내용을 수정하지 마십시오.

기본 데이터형

class ctypes._SimpleCData

이 비공개 클래스는 모든 기본 ctypes 데이터형의 베이스 클래스입니다. 여기에는 기본 ctypes 데이터형의 공통 어트리뷰트가 들어 있으므로 여기에서 언급합니다. _SimpleCData는 _CData의 서브 클래스이므로, 메서드와 어트리뷰트를 상속받습니다. 포인터가 아니고 포인터를 포함하지 않는 ctypes 데이터형을 이제 피클 할 수 있습니다.

인스턴스에는 어트리뷰트가 하나 있습니다:

value

이 어트리뷰트는 인스턴스의 실제 값을 포함합니다. 정수형과 포인터형에서는 정수고, 문자형에서는 단일 문자 바이트열 객체나 문자열이고, 문자 포인터형에서는 파이썬 바이트열 객체나 문자열입니다.

ctypes 인스턴스에서 value 어트리뷰트를 조회하면, 대개 매번 새 객체가 반환됩니다. ctypes는 원래의 객체 반환을 구현하지 않습니다. 항상 새로운 객체가 만들어집니다. 다른 모든 ctypes 객체 인스턴스에서도 마찬가지입니다.

기본 데이터형은, 외부 함수 호출 결과로 반환되거나 (예를 들어) 구조체 필드 멤버나 배열 항목을 꺼낼 때, 원시(native) 파이썬 형으로 투명하게 변환됩니다. 즉, 외부 함수가 c_char_p인 restype을 가지면, 항상 c_char_p 인스턴스가 아니라 파이썬 바이트열 객체를 받습니다.

기본 데이터형의 서브 클래스는 이 동작을 상속하지 않습니다. 따라서 외부 함수의 restype가 c_void_p의 서브 클래스면, 함수 호출에서 이 서브 클래스의 인스턴스를 받게 됩니다. 물론, value 어트리뷰트에 액세스해서 포인터 값을 가져올 수 있습니다.

다음은 기본 ctypes 데이터형입니다:

class ctypes.c_byte

C signed char 데이터형을 나타내고, 값을 작은 정수로 해석합니다. 생성자는 선택적 정수 초기화자를 받아들입니다; 오버플로 검사는 수행되지 않습니다.

class ctypes.c_char

C char 데이터형을 나타내고, 값을 단일 문자로 해석합니다. 생성자는 선택적 문자열 초기화자를 받아들입니다, 문자열의 길이는 정확히 한 문자여야 합니다.

class ctypes.c_char_p

0으로 끝나는 문자열을 가리킬 때, C char * 데이터형을 나타냅니다. 바이너리 데이터를 가리킬 수도 있는 일반 문자 포인터를 위해서는, POINTER(c_char)를 사용해야 합니다. 생성자는 정수 주소나 바이트열 객체를 받아들입니다.

class ctypes.c_double

C double 데이터형을 나타냅니다. 생성자는 선택적 float 초기화자를 받아들입니다.

class ctypes.c_longdouble

C long double 데이터형을 나타냅니다. 생성자는 선택적 float 초기화자를 받아들입니다. sizeof(long double) == sizeof(double)인 플랫폼에서 c_double의 별칭입니다.

class ctypes.c_float

C float 데이터형을 나타냅니다. 생성자는 선택적 float 초기화자를 받아들입니다.

class ctypes.c_int

C signed int 데이터형을 나타냅니다. 생성자는 선택적 정수 초기화자를 받아들입니다. 오버플로 검사는 수행되지 않습니다. sizeof(int) == sizeof(long)인 플랫폼에서 c_long의 별칭입니다.

class ctypes.c_int8

C 8비트 signed int 데이터형을 나타냅니다. 보통 c_byte의 별칭입니다.

class ctypes.c_int16

C 16비트 signed int 데이터형을 나타냅니다. 보통 c_short의 별칭입니다.

class ctypes.c_int32

C 32비트 signed int 데이터형을 나타냅니다. 보통 c_int의 별칭입니다.

class ctypes.c_int64

C 64비트 signed int 데이터형을 나타냅니다. 보통 c_longlong의 별칭입니다.

class ctypes.c_long

C signed long 데이터형을 나타냅니다. 생성자는 선택적 정수 초기화자를 받아들입니다; 오버플로 검사는 수행되지 않습니다.

class ctypes.c_longlong

C signed long long 데이터형을 나타냅니다. 생성자는 선택적 정수 초기화자를 받아들입니다; 오버플로 검사는 수행되지 않습니다.

class ctypes.c_short

C signed short 데이터형을 나타냅니다. 생성자는 선택적 정수 초기화자를 받아들입니다; 오버플로 검사는 수행되지 않습니다.

class ctypes.c_size_t

C size_t 데이터형을 나타냅니다.

class ctypes.c_ssize_t

C ssize_t 데이터형을 나타냅니다.

버전 3.2에 추가.

class ctypes.c_ubyte

C unsigned char 데이터형을 나타내고, 값을 작은 정수로 해석합니다. 생성자는 선택적 정수 초기화자를 받아들입니다; 오버플로 검사는 수행되지 않습니다.

class ctypes.c_uint

C unsigned int 데이터형을 나타냅니다. 생성자는 선택적 정수 초기화자를 받아들입니다; 오버플로 검사는 수행되지 않습니다. sizeof(int) == sizeof(long)인 플랫폼에서 c_ulong의 별칭입니다.

class ctypes.c_uint8

C 8비트 unsigned int 데이터형을 나타냅니다. 보통 c_ubyte의 별칭입니다.

class ctypes.c_uint16

C 16비트 unsigned int 데이터형을 나타냅니다. 보통 c_ushort의 별칭입니다.

class ctypes.c_uint32

C 32비트 unsigned int 데이터형을 나타냅니다. 보통 c_uint의 별칭입니다.

class ctypes.c_uint64

C 64비트 unsigned int 데이터형을 나타냅니다. 보통 c_ulonglong의 별칭입니다.

class ctypes.c_ulong

C unsigned long 데이터형을 나타냅니다. 생성자는 선택적 정수 초기화자를 받아들입니다; 오버플로 검사는 수행되지 않습니다.

class ctypes.c_ulonglong

C unsigned long long 데이터형을 나타냅니다. 생성자는 선택적 정수 초기화자를 받아들입니다; 오버플로 검사는 수행되지 않습니다.

class ctypes.c_ushort

C unsigned short 데이터형을 나타냅니다. 생성자는 선택적 정수 초기화자를 받아들입니다; 오버플로 검사는 수행되지 않습니다.

class ctypes.c_void_p

C void * 형을 나타냅니다. 값은 정수로 표시됩니다. 생성자는 선택적 정수 초기화자를 받아들입니다.

class ctypes.c_wchar

C wchar_t 데이터형을 나타내고, 값을 단일 문자 유니코드 문자열로 해석합니다. 생성자는 선택적 문자열 초기화자를 받아들입니다, 문자열의 길이는 정확히 한 문자여야 합니다.

class ctypes.c_wchar_p

0으로 끝나는 광폭 문자 문자열을 가리키는 포인터여야 하는 C wchar_t * 데이터형을 나타냅니다. 생성자는 정수 주소나 문자열을 받아들입니다.

class ctypes.c_bool

C bool 데이터형을 나타냅니다 (더욱 정확하게, C99의 _Bool). 이 값은 True나 False 일 수 있고, 생성자는 논릿값이 있는 임의의 객체를 받아들입니다.

class ctypes.HRESULT

윈도우 전용: 함수 또는 메서드 호출에 대한 성공 또는 에러 정보가 들어있는, HRESULT 값을 나타냅니다.

class ctypes.py_object

C PyObject * 데이터형을 나타냅니다. 인자 없이 이것을 호출하면 NULL PyObject * 포인터가 만들어집니다.

ctypes.wintypes 모듈은 다른 윈도우 특정 데이터형을 제공합니다, 예를 들어, HWND, WPARAM 또는 DWORD. MSG나 RECT와 같은 유용한 구조체도 정의됩니다.

구조화된 데이터형

class ctypes.Union(*args, **kw)

네이티브 바이트 순서의 공용체를 위한 추상 베이스 클래스.

class ctypes.BigEndianStructure(*args, **kw)

빅엔디안(big endian) 바이트 순서의 구조체를 위한 추상 베이스 클래스.

class ctypes.LittleEndianStructure(*args, **kw)

리틀엔디안(little endian) 바이트 순서로의 구조체를 위한 추상 베이스 클래스.

네이티브가 아닌 바이트 순서를 갖는 구조체는 포인터형 필드나 포인터형 필드를 포함하는 다른 데이터형을 포함할 수 없습니다.

class ctypes.Structure(*args, **kw)

네이티브 바이트 순서의 구조체를 위한 추상 베이스 클래스.

구상 구조체와 공용체 형은 이 형 중 하나를 서브 클래싱하고 적어도 _fields_ 클래스 변수를 정의해서 만들어야 합니다. ctypes는 직접 어트리뷰트 액세스로 필드를 읽고 쓸 수 있는 디스크립터를 만듭니다. 이것들은

_fields_

구조체 필드를 정의하는 시퀀스. 항목은 2-튜플이나 3-튜플이어야 합니다. 첫 번째 항목은 필드의 이름이고, 두 번째 항목은 필드의 형을 지정합니다; 모든 ctypes 데이터형이 될 수 있습니다.

c_int와 같은 정수형 필드에서는, 세 번째 선택적 항목을 지정할 수 있습니다. 필드의 비트 폭을 정의하는 작은 양의 정수여야 합니다.

필드 이름은 하나의 구조체나 공용체 내에서 고유해야 합니다. 이것은 검사되지 않습니다, 이름이 중복되면 하나의 필드만 액세스할 수 있습니다.

_fields_ 클래스 변수를, Structure 서브 클래스를 정의하는 클래스 문 뒤에서 정의할 수 있습니다. 직접 또는 간접적으로 자신을 참조하는 데이터형을 만들 수 있게 합니다:

class List(Structure):
    pass
List._fields_ = [("pnext", POINTER(List)),
                 ...
                ]

하지만, 형이 처음 사용되기 전에 _fields_ 클래스 변수를 정의해야 합니다 (인스턴스가 만들어지고, sizeof()가 호출되는 등의 일이 일어납니다). 나중에 _fields_ 클래스 변수에 대입하면 AttributeError가 발생합니다.

구조체 형의 서브-서브 클래스를 정의할 수 있습니다. 베이스 클래스의 필드를 상속하고, 여기에 서브-서브 클래스에 정의된 _fields_의 필드가 추가됩니다.

_pack_

인스턴스의 구조체 필드 정렬을 재정의할 수 있는 선택적 작은 정수입니다. _fields_가 대입될 때 _pack_는 이미 정의되어 있어야 합니다. 그렇지 않으면 아무 효과가 없습니다.

_anonymous_

이름 없는(익명) 필드의 이름을 나열하는 선택적 시퀀스. _fields_가 대입될 때 _anonymous_는 이미 정의되어 있어야 합니다. 그렇지 않으면 아무 효과가 없습니다.

이 변수에 나열된 필드는 구조체나 공용체 형 필드여야 합니다. ctypes는 구조체나 공용체 필드를 만들 필요 없이, 중첩된 필드에 직접 액세스할 수 있는 디스크립터를 구조체 형에 만듭니다.

다음은 예제 형입니다 (윈도우):

class _U(Union):
    _fields_ = [("lptdesc", POINTER(TYPEDESC)),
                ("lpadesc", POINTER(ARRAYDESC)),
                ("hreftype", HREFTYPE)]

class TYPEDESC(Structure):
    _anonymous_ = ("u",)
    _fields_ = [("u", _U),
                ("vt", VARTYPE)]

TYPEDESC 구조체는 COM 데이터형을 설명합니다. vt 필드는 공용체 필드 중 어느 것이 유효한지 지정합니다. u 필드가 익명 필드로 정의되었으므로, 이제 TYPEDESC 인스턴스에서 멤버에 직접 액세스할 수 있습니다. td.lptdesc와 td.u.lptdesc는 동등하지만, 앞에 있는 것이 임시 공용체 인스턴스를 만들 필요가 없으므로 더 빠릅니다:

td = TYPEDESC()
td.vt = VT_PTR
td.lptdesc = POINTER(some_type)
td.u.lptdesc = POINTER(some_type)

구조체 형의 서브-서브 클래스를 정의할 수 있으며, 베이스 클래스의 필드를 상속합니다. 서브 클래스 정의에 별도의 _fields_ 변수가 있으면, 여기에 지정된 필드가 베이스 클래스의 필드에 추가됩니다.

구조체와 공용체 생성자는 위치와 키워드 인자를 모두 받아들입니다. 위치 인자는 _fields_에 나타나는 순서대로 멤버 필드를 초기화하는 데 사용됩니다. 생성자의 키워드 인자는 어트리뷰트 대입으로 해석되므로, _fields_를 같은 이름으로 초기화하거나, _fields_에 없는 이름에 대한 새 어트리뷰트를 만듭니다.

배열과 포인터

class ctypes.Array(*args)

배열의 추상 베이스 클래스.

구상 배열형을 만드는 데 권장되는 방법은, 임의의 ctypes 데이터형에 양의 정수를 곱하는 것입니다. 또는, 이 형의 서브 클래스를 만들고, _length_ 와 _type_ 클래스 변수를 정의할 수 있습니다. 배열 요소는 표준 서브 스크립트나 슬라이스 액세스를 사용해서 읽고 쓸 수 있습니다; 슬라이스 읽기의 경우, 결과 객체는 Array가 아닙니다.

_length_

배열의 요소 수를 지정하는 양의 정수. 범위를 벗어나는 서브 스크립트는 IndexError를 일으킵니다. len()에 의해 반환됩니다.

_type_

배열의 각 요소 형을 지정합니다.

Array 서브 클래스 생성자는 요소를 순서대로 초기화하는 데 사용되는 위치 인자를 받아들입니다.

class ctypes._Pointer

포인터를 위한 내부 추상 베이스 클래스.

구상 포인터형은 가리킬 형으로 POINTER()를 호출해서 만들어집니다; 이것은 pointer()에 의해 자동으로 수행됩니다.

포인터가 배열을 가리키면, 그것의 요소는 표준 서브 스크립트 및 슬라이스 액세스를 사용하여 읽고 쓸 수 있습니다. 포인터 객체는 크기가 없으므로, len()는 TypeError를 발생시킵니다. 음수 서브 스크립트는 (C처럼) 포인터 앞의 메모리를 읽을 것이고, 범위를 벗어나는 서브 스크립트는 (운이 좋다면) 액세스 위반으로 인해 충돌을 일으킬 것입니다.

_type_

가리키는 형을 지정합니다.

contents

포인터가 가리키는 객체를 반환합니다. 이 어트리뷰트에 대입하면 대입된 객체를 가리키도록 포인터가 변경됩니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

일반 운영 체제 서비스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

|

동시 실행

이 장에서 설명하는 모듈은 코드의 동시 실행을 지원합니다. 적절한 도구 선택은 실행할 작업(CPU 병목 대 IO 병목)과 선호하는 개발 스타일(이벤트 구동 협력적 다중작업 대 선점적 다중작업)에 따라 달라집니다. 다음은 개요입니다:

threading — Thread-based parallelism

Thread-Local Data

Thread Objects

Lock Objects

RLock Objects

Condition Objects

Semaphore Objects

Semaphore Example

Event Objects

Timer Objects

Barrier Objects

Using locks, conditions, and semaphores in the with statement

multiprocessing — 프로세스 기반 병렬 처리

소개

Process 클래스

컨텍스트 및 시작 방법

프로세스 간 객체 교환

프로세스 간 동기화

프로세스 간 상태 공유

작업자 풀 사용

레퍼런스

Process와 예외

파이프와 큐

잡동사니

Connection 객체

동기화 프리미티브

공유 ctypes 객체

multiprocessing.sharedctypes 모듈

관리자

사용자 정의 관리자

원격 관리자 사용하기

프락시 객체

정리

프로세스 풀

리스너와 클라이언트

주소 형식

인증 키

로깅

multiprocessing.dummy 모듈

프로그래밍 지침

모든 시작 방법

spawn 과 forkserver 시작 방법

예제

concurrent 패키지

concurrent.futures — 병렬 작업 실행하기

Executor 객체

ThreadPoolExecutor

ThreadPoolExecutor 예제

ProcessPoolExecutor

ProcessPoolExecutor 예제

Future 객체

모듈 함수

예외 클래스

subprocess — Subprocess management

Using the subprocess Module

Frequently Used Arguments

Popen Constructor

Exceptions

Security Considerations

Popen Objects

Windows Popen Helpers

Windows Constants

Older high-level API

Replacing Older Functions with the subprocess Module

Replacing /bin/sh shell backquote

Replacing shell pipeline

Replacing os.system()

Replacing the os.spawn family

Replacing os.popen(), os.popen2(), os.popen3()

Replacing functions from the popen2 module

Legacy Shell Invocation Functions

Notes

Converting an argument sequence to a string on Windows

sched — 이벤트 스케줄러

스케줄러 객체

queue — 동기화된 큐 클래스

큐 객체

SimpleQueue 객체

다음은 위 서비스 중 일부에 대한 지원 모듈입니다:

_thread — 저수준 스레드 API

_dummy_thread — Drop-in replacement for the _thread module

dummy_threading — Drop-in replacement for the threading module

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

동시 실행 »

|

threading — Thread-based parallelism

Source code: Lib/threading.py [https://github.com/python/cpython/tree/3.7/Lib/threading.py]

This module constructs higher-level threading interfaces on top of the lower level _thread module. See also the queue module.

버전 3.7에서 변경: This module used to be optional, it is now always available.

참고

While they are not listed below, the camelCase names used for some methods and functions in this module in the Python 2.x series are still supported by this module.

CPython implementation detail: In CPython, due to the Global Interpreter Lock, only one thread can execute Python code at once (even though certain performance-oriented libraries might overcome this limitation). If you want your application to make better use of the computational resources of multi-core machines, you are advised to use multiprocessing or concurrent.futures.ProcessPoolExecutor. However, threading is still an appropriate model if you want to run multiple I/O-bound tasks simultaneously.

This module defines the following functions:

threading.active_count()

Return the number of Thread objects currently alive. The returned count is equal to the length of the list returned by enumerate().

threading.current_thread()

Return the current Thread object, corresponding to the caller’s thread of control. If the caller’s thread of control was not created through the threading module, a dummy thread object with limited functionality is returned.

threading.get_ident()

Return the ‘thread identifier’ of the current thread. This is a nonzero integer. Its value has no direct meaning; it is intended as a magic cookie to be used e.g. to index a dictionary of thread-specific data. Thread identifiers may be recycled when a thread exits and another thread is created.

버전 3.3에 추가.

threading.enumerate()

Return a list of all Thread objects currently alive. The list includes daemonic threads, dummy thread objects created by current_thread(), and the main thread. It excludes terminated threads and threads that have not yet been started.

threading.main_thread()

Return the main Thread object. In normal conditions, the main thread is the thread from which the Python interpreter was started.

버전 3.4에 추가.

threading.settrace(func)

Set a trace function for all threads started from the threading module. The func will be passed to sys.settrace() for each thread, before its run() method is called.

threading.setprofile(func)

Set a profile function for all threads started from the threading module. The func will be passed to sys.setprofile() for each thread, before its run() method is called.

threading.stack_size([size])

Return the thread stack size used when creating new threads. The optional size argument specifies the stack size to be used for subsequently created threads, and must be 0 (use platform or configured default) or a positive integer value of at least 32,768 (32 KiB). If size is not specified, 0 is used. If changing the thread stack size is unsupported, a RuntimeError is raised. If the specified stack size is invalid, a ValueError is raised and the stack size is unmodified. 32 KiB is currently the minimum supported stack size value to guarantee sufficient stack space for the interpreter itself. Note that some platforms may have particular restrictions on values for the stack size, such as requiring a minimum stack size > 32 KiB or requiring allocation in multiples of the system memory page size - platform documentation should be referred to for more information (4 KiB pages are common; using multiples of 4096 for the stack size is the suggested approach in the absence of more specific information).

Availability: Windows, systems with POSIX threads.

This module also defines the following constant:

threading.TIMEOUT_MAX

The maximum value allowed for the timeout parameter of blocking functions (Lock.acquire(), RLock.acquire(), Condition.wait(), etc.). Specifying a timeout greater than this value will raise an OverflowError.

버전 3.2에 추가.

This module defines a number of classes, which are detailed in the sections below.

The design of this module is loosely based on Java’s threading model. However, where Java makes locks and condition variables basic behavior of every object, they are separate objects in Python. Python’s Thread class supports a subset of the behavior of Java’s Thread class; currently, there are no priorities, no thread groups, and threads cannot be destroyed, stopped, suspended, resumed, or interrupted. The static methods of Java’s Thread class, when implemented, are mapped to module-level functions.

All of the methods described below are executed atomically.

Thread-Local Data

Thread-local data is data whose values are thread specific. To manage thread-local data, just create an instance of local (or a subclass) and store attributes on it:

mydata = threading.local()
mydata.x = 1

The instance’s values will be different for separate threads.

class threading.local

A class that represents thread-local data.

For more details and extensive examples, see the documentation string of the _threading_local module.

Thread Objects

The Thread class represents an activity that is run in a separate thread of control. There are two ways to specify the activity: by passing a callable object to the constructor, or by overriding the run() method in a subclass. No other methods (except for the constructor) should be overridden in a subclass. In other words, only override the __init__() and run() methods of this class.

Once a thread object is created, its activity must be started by calling the thread’s start() method. This invokes the run() method in a separate thread of control.

Once the thread’s activity is started, the thread is considered ‘alive’. It stops being alive when its run() method terminates – either normally, or by raising an unhandled exception. The is_alive() method tests whether the thread is alive.

Other threads can call a thread’s join() method. This blocks the calling thread until the thread whose join() method is called is terminated.

A thread has a name. The name can be passed to the constructor, and read or changed through the name attribute.

A thread can be flagged as a “daemon thread”. The significance of this flag is that the entire Python program exits when only daemon threads are left. The initial value is inherited from the creating thread. The flag can be set through the daemon property or the daemon constructor argument.

참고

Daemon threads are abruptly stopped at shutdown. Their resources (such as open files, database transactions, etc.) may not be released properly. If you want your threads to stop gracefully, make them non-daemonic and use a suitable signalling mechanism such as an Event.

There is a “main thread” object; this corresponds to the initial thread of control in the Python program. It is not a daemon thread.

There is the possibility that “dummy thread objects” are created. These are thread objects corresponding to “alien threads”, which are threads of control started outside the threading module, such as directly from C code. Dummy thread objects have limited functionality; they are always considered alive and daemonic, and cannot be join()ed. They are never deleted, since it is impossible to detect the termination of alien threads.

class threading.Thread(group=None, target=None, name=None, args=(), kwargs={}, *, daemon=None)

This constructor should always be called with keyword arguments. Arguments are:

group should be None; reserved for future extension when a ThreadGroup class is implemented.

target is the callable object to be invoked by the run() method. Defaults to None, meaning nothing is called.

name is the thread name. By default, a unique name is constructed of the form “Thread-N” where N is a small decimal number.

args is the argument tuple for the target invocation. Defaults to ().

kwargs is a dictionary of keyword arguments for the target invocation. Defaults to {}.

If not None, daemon explicitly sets whether the thread is daemonic. If None (the default), the daemonic property is inherited from the current thread.

If the subclass overrides the constructor, it must make sure to invoke the base class constructor (Thread.__init__()) before doing anything else to the thread.

버전 3.3에서 변경: Added the daemon argument.

start()

Start the thread’s activity.

It must be called at most once per thread object. It arranges for the object’s run() method to be invoked in a separate thread of control.

This method will raise a RuntimeError if called more than once on the same thread object.

run()

Method representing the thread’s activity.

You may override this method in a subclass. The standard run() method invokes the callable object passed to the object’s constructor as the target argument, if any, with positional and keyword arguments taken from the args and kwargs arguments, respectively.

join(timeout=None)

Wait until the thread terminates. This blocks the calling thread until the thread whose join() method is called terminates – either normally or through an unhandled exception – or until the optional timeout occurs.

When the timeout argument is present and not None, it should be a floating point number specifying a timeout for the operation in seconds (or fractions thereof). As join() always returns None, you must call is_alive() after join() to decide whether a timeout happened – if the thread is still alive, the join() call timed out.

When the timeout argument is not present or None, the operation will block until the thread terminates.

A thread can be join()ed many times.

join() raises a RuntimeError if an attempt is made to join the current thread as that would cause a deadlock. It is also an error to join() a thread before it has been started and attempts to do so raise the same exception.

name

A string used for identification purposes only. It has no semantics. Multiple threads may be given the same name. The initial name is set by the constructor.

getName()

setName()

Old getter/setter API for name; use it directly as a property instead.

ident

The ‘thread identifier’ of this thread or None if the thread has not been started. This is a nonzero integer. See the get_ident() function. Thread identifiers may be recycled when a thread exits and another thread is created. The identifier is available even after the thread has exited.

is_alive()

Return whether the thread is alive.

This method returns True just before the run() method starts until just after the run() method terminates. The module function enumerate() returns a list of all alive threads.

daemon

A boolean value indicating whether this thread is a daemon thread (True) or not (False). This must be set before start() is called, otherwise RuntimeError is raised. Its initial value is inherited from the creating thread; the main thread is not a daemon thread and therefore all threads created in the main thread default to daemon = False.

The entire Python program exits when no alive non-daemon threads are left.

isDaemon()

setDaemon()

Old getter/setter API for daemon; use it directly as a property instead.

Lock Objects

A primitive lock is a synchronization primitive that is not owned by a particular thread when locked. In Python, it is currently the lowest level synchronization primitive available, implemented directly by the _thread extension module.

A primitive lock is in one of two states, “locked” or “unlocked”. It is created in the unlocked state. It has two basic methods, acquire() and release(). When the state is unlocked, acquire() changes the state to locked and returns immediately. When the state is locked, acquire() blocks until a call to release() in another thread changes it to unlocked, then the acquire() call resets it to locked and returns. The release() method should only be called in the locked state; it changes the state to unlocked and returns immediately. If an attempt is made to release an unlocked lock, a RuntimeError will be raised.

Locks also support the context management protocol.

When more than one thread is blocked in acquire() waiting for the state to turn to unlocked, only one thread proceeds when a release() call resets the state to unlocked; which one of the waiting threads proceeds is not defined, and may vary across implementations.

All methods are executed atomically.

class threading.Lock

The class implementing primitive lock objects. Once a thread has acquired a lock, subsequent attempts to acquire it block, until it is released; any thread may release it.

Note that Lock is actually a factory function which returns an instance of the most efficient version of the concrete Lock class that is supported by the platform.

acquire(blocking=True, timeout=-1)

Acquire a lock, blocking or non-blocking.

When invoked with the blocking argument set to True (the default), block until the lock is unlocked, then set it to locked and return True.

When invoked with the blocking argument set to False, do not block. If a call with blocking set to True would block, return False immediately; otherwise, set the lock to locked and return True.

When invoked with the floating-point timeout argument set to a positive value, block for at most the number of seconds specified by timeout and as long as the lock cannot be acquired. A timeout argument of -1 specifies an unbounded wait. It is forbidden to specify a timeout when blocking is false.

The return value is True if the lock is acquired successfully, False if not (for example if the timeout expired).

버전 3.2에서 변경: The timeout parameter is new.

버전 3.2에서 변경: Lock acquisition can now be interrupted by signals on POSIX if the underlying threading implementation supports it.

release()

Release a lock. This can be called from any thread, not only the thread which has acquired the lock.

When the lock is locked, reset it to unlocked, and return. If any other threads are blocked waiting for the lock to become unlocked, allow exactly one of them to proceed.

When invoked on an unlocked lock, a RuntimeError is raised.

There is no return value.

locked()

Return true if the lock is acquired.

RLock Objects

A reentrant lock is a synchronization primitive that may be acquired multiple times by the same thread. Internally, it uses the concepts of “owning thread” and “recursion level” in addition to the locked/unlocked state used by primitive locks. In the locked state, some thread owns the lock; in the unlocked state, no thread owns it.

To lock the lock, a thread calls its acquire() method; this returns once the thread owns the lock. To unlock the lock, a thread calls its release() method. acquire()/release() call pairs may be nested; only the final release() (the release() of the outermost pair) resets the lock to unlocked and allows another thread blocked in acquire() to proceed.

Reentrant locks also support the context management protocol.

class threading.RLock

This class implements reentrant lock objects. A reentrant lock must be released by the thread that acquired it. Once a thread has acquired a reentrant lock, the same thread may acquire it again without blocking; the thread must release it once for each time it has acquired it.

Note that RLock is actually a factory function which returns an instance of the most efficient version of the concrete RLock class that is supported by the platform.

acquire(blocking=True, timeout=-1)

Acquire a lock, blocking or non-blocking.

When invoked without arguments: if this thread already owns the lock, increment the recursion level by one, and return immediately. Otherwise, if another thread owns the lock, block until the lock is unlocked. Once the lock is unlocked (not owned by any thread), then grab ownership, set the recursion level to one, and return. If more than one thread is blocked waiting until the lock is unlocked, only one at a time will be able to grab ownership of the lock. There is no return value in this case.

When invoked with the blocking argument set to true, do the same thing as when called without arguments, and return True.

When invoked with the blocking argument set to false, do not block. If a call without an argument would block, return False immediately; otherwise, do the same thing as when called without arguments, and return True.

When invoked with the floating-point timeout argument set to a positive value, block for at most the number of seconds specified by timeout and as long as the lock cannot be acquired. Return True if the lock has been acquired, false if the timeout has elapsed.

버전 3.2에서 변경: The timeout parameter is new.

release()

Release a lock, decrementing the recursion level. If after the decrement it is zero, reset the lock to unlocked (not owned by any thread), and if any other threads are blocked waiting for the lock to become unlocked, allow exactly one of them to proceed. If after the decrement the recursion level is still nonzero, the lock remains locked and owned by the calling thread.

Only call this method when the calling thread owns the lock. A RuntimeError is raised if this method is called when the lock is unlocked.

There is no return value.

Condition Objects

A condition variable is always associated with some kind of lock; this can be passed in or one will be created by default. Passing one in is useful when several condition variables must share the same lock. The lock is part of the condition object: you don’t have to track it separately.

A condition variable obeys the context management protocol: using the with statement acquires the associated lock for the duration of the enclosed block. The acquire() and release() methods also call the corresponding methods of the associated lock.

Other methods must be called with the associated lock held. The wait() method releases the lock, and then blocks until another thread awakens it by calling notify() or notify_all(). Once awakened, wait() re-acquires the lock and returns. It is also possible to specify a timeout.

The notify() method wakes up one of the threads waiting for the condition variable, if any are waiting. The notify_all() method wakes up all threads waiting for the condition variable.

Note: the notify() and notify_all() methods don’t release the lock; this means that the thread or threads awakened will not return from their wait() call immediately, but only when the thread that called notify() or notify_all() finally relinquishes ownership of the lock.

The typical programming style using condition variables uses the lock to synchronize access to some shared state; threads that are interested in a particular change of state call wait() repeatedly until they see the desired state, while threads that modify the state call notify() or notify_all() when they change the state in such a way that it could possibly be a desired state for one of the waiters. For example, the following code is a generic producer-consumer situation with unlimited buffer capacity:

# Consume one item
with cv:
    while not an_item_is_available():
        cv.wait()
    get_an_available_item()

# Produce one item
with cv:
    make_an_item_available()
    cv.notify()

The while loop checking for the application’s condition is necessary because wait() can return after an arbitrary long time, and the condition which prompted the notify() call may no longer hold true. This is inherent to multi-threaded programming. The wait_for() method can be used to automate the condition checking, and eases the computation of timeouts:

# Consume an item
with cv:
    cv.wait_for(an_item_is_available)
    get_an_available_item()

To choose between notify() and notify_all(), consider whether one state change can be interesting for only one or several waiting threads. E.g. in a typical producer-consumer situation, adding one item to the buffer only needs to wake up one consumer thread.

class threading.Condition(lock=None)

This class implements condition variable objects. A condition variable allows one or more threads to wait until they are notified by another thread.

If the lock argument is given and not None, it must be a Lock or RLock object, and it is used as the underlying lock. Otherwise, a new RLock object is created and used as the underlying lock.

버전 3.3에서 변경: changed from a factory function to a class.

acquire(*args)

Acquire the underlying lock. This method calls the corresponding method on the underlying lock; the return value is whatever that method returns.

release()

Release the underlying lock. This method calls the corresponding method on the underlying lock; there is no return value.

wait(timeout=None)

Wait until notified or until a timeout occurs. If the calling thread has not acquired the lock when this method is called, a RuntimeError is raised.

This method releases the underlying lock, and then blocks until it is awakened by a notify() or notify_all() call for the same condition variable in another thread, or until the optional timeout occurs. Once awakened or timed out, it re-acquires the lock and returns.

When the timeout argument is present and not None, it should be a floating point number specifying a timeout for the operation in seconds (or fractions thereof).

When the underlying lock is an RLock, it is not released using its release() method, since this may not actually unlock the lock when it was acquired multiple times recursively. Instead, an internal interface of the RLock class is used, which really unlocks it even when it has been recursively acquired several times. Another internal interface is then used to restore the recursion level when the lock is reacquired.

The return value is True unless a given timeout expired, in which case it is False.

버전 3.2에서 변경: Previously, the method always returned None.

wait_for(predicate, timeout=None)

Wait until a condition evaluates to true. predicate should be a callable which result will be interpreted as a boolean value. A timeout may be provided giving the maximum time to wait.

This utility method may call wait() repeatedly until the predicate is satisfied, or until a timeout occurs. The return value is the last return value of the predicate and will evaluate to False if the method timed out.

Ignoring the timeout feature, calling this method is roughly equivalent to writing:

while not predicate():
    cv.wait()

Therefore, the same rules apply as with wait(): The lock must be held when called and is re-acquired on return. The predicate is evaluated with the lock held.

버전 3.2에 추가.

notify(n=1)

By default, wake up one thread waiting on this condition, if any. If the calling thread has not acquired the lock when this method is called, a RuntimeError is raised.

This method wakes up at most n of the threads waiting for the condition variable; it is a no-op if no threads are waiting.

The current implementation wakes up exactly n threads, if at least n threads are waiting. However, it’s not safe to rely on this behavior. A future, optimized implementation may occasionally wake up more than n threads.

Note: an awakened thread does not actually return from its wait() call until it can reacquire the lock. Since notify() does not release the lock, its caller should.

notify_all()

Wake up all threads waiting on this condition. This method acts like notify(), but wakes up all waiting threads instead of one. If the calling thread has not acquired the lock when this method is called, a RuntimeError is raised.

Semaphore Objects

This is one of the oldest synchronization primitives in the history of computer science, invented by the early Dutch computer scientist Edsger W. Dijkstra (he used the names P() and V() instead of acquire() and release()).

A semaphore manages an internal counter which is decremented by each acquire() call and incremented by each release() call. The counter can never go below zero; when acquire() finds that it is zero, it blocks, waiting until some other thread calls release().

Semaphores also support the context management protocol.

class threading.Semaphore(value=1)

This class implements semaphore objects. A semaphore manages an atomic counter representing the number of release() calls minus the number of acquire() calls, plus an initial value. The acquire() method blocks if necessary until it can return without making the counter negative. If not given, value defaults to 1.

The optional argument gives the initial value for the internal counter; it defaults to 1. If the value given is less than 0, ValueError is raised.

버전 3.3에서 변경: changed from a factory function to a class.

acquire(blocking=True, timeout=None)

Acquire a semaphore.

When invoked without arguments:

If the internal counter is larger than zero on entry, decrement it by one and return True immediately.

If the internal counter is zero on entry, block until awoken by a call to release(). Once awoken (and the counter is greater than 0), decrement the counter by 1 and return True. Exactly one thread will be awoken by each call to release(). The order in which threads are awoken should not be relied on.

When invoked with blocking set to false, do not block. If a call without an argument would block, return False immediately; otherwise, do the same thing as when called without arguments, and return True.

When invoked with a timeout other than None, it will block for at most timeout seconds. If acquire does not complete successfully in that interval, return False. Return True otherwise.

버전 3.2에서 변경: The timeout parameter is new.

release()

Release a semaphore, incrementing the internal counter by one. When it was zero on entry and another thread is waiting for it to become larger than zero again, wake up that thread.

class threading.BoundedSemaphore(value=1)

Class implementing bounded semaphore objects. A bounded semaphore checks to make sure its current value doesn’t exceed its initial value. If it does, ValueError is raised. In most situations semaphores are used to guard resources with limited capacity. If the semaphore is released too many times it’s a sign of a bug. If not given, value defaults to 1.

버전 3.3에서 변경: changed from a factory function to a class.

Semaphore Example

Semaphores are often used to guard resources with limited capacity, for example, a database server. In any situation where the size of the resource is fixed, you should use a bounded semaphore. Before spawning any worker threads, your main thread would initialize the semaphore:

maxconnections = 5
# ...
pool_sema = BoundedSemaphore(value=maxconnections)

Once spawned, worker threads call the semaphore’s acquire and release methods when they need to connect to the server:

with pool_sema:
    conn = connectdb()
    try:
        # ... use connection ...
    finally:
        conn.close()

The use of a bounded semaphore reduces the chance that a programming error which causes the semaphore to be released more than it’s acquired will go undetected.

Event Objects

This is one of the simplest mechanisms for communication between threads: one thread signals an event and other threads wait for it.

An event object manages an internal flag that can be set to true with the set() method and reset to false with the clear() method. The wait() method blocks until the flag is true.

class threading.Event

Class implementing event objects. An event manages a flag that can be set to true with the set() method and reset to false with the clear() method. The wait() method blocks until the flag is true. The flag is initially false.

버전 3.3에서 변경: changed from a factory function to a class.

is_set()

Return True if and only if the internal flag is true.

set()

Set the internal flag to true. All threads waiting for it to become true are awakened. Threads that call wait() once the flag is true will not block at all.

clear()

Reset the internal flag to false. Subsequently, threads calling wait() will block until set() is called to set the internal flag to true again.

wait(timeout=None)

Block until the internal flag is true. If the internal flag is true on entry, return immediately. Otherwise, block until another thread calls set() to set the flag to true, or until the optional timeout occurs.

When the timeout argument is present and not None, it should be a floating point number specifying a timeout for the operation in seconds (or fractions thereof).

This method returns True if and only if the internal flag has been set to true, either before the wait call or after the wait starts, so it will always return True except if a timeout is given and the operation times out.

버전 3.1에서 변경: Previously, the method always returned None.

Timer Objects

This class represents an action that should be run only after a certain amount of time has passed — a timer. Timer is a subclass of Thread and as such also functions as an example of creating custom threads.

Timers are started, as with threads, by calling their start() method. The timer can be stopped (before its action has begun) by calling the cancel() method. The interval the timer will wait before executing its action may not be exactly the same as the interval specified by the user.

For example:

def hello():
    print("hello, world")

t = Timer(30.0, hello)
t.start()  # after 30 seconds, "hello, world" will be printed

class threading.Timer(interval, function, args=None, kwargs=None)

Create a timer that will run function with arguments args and keyword arguments kwargs, after interval seconds have passed. If args is None (the default) then an empty list will be used. If kwargs is None (the default) then an empty dict will be used.

버전 3.3에서 변경: changed from a factory function to a class.

cancel()

Stop the timer, and cancel the execution of the timer’s action. This will only work if the timer is still in its waiting stage.

Barrier Objects

버전 3.2에 추가.

This class provides a simple synchronization primitive for use by a fixed number of threads that need to wait for each other. Each of the threads tries to pass the barrier by calling the wait() method and will block until all of the threads have made their wait() calls. At this point, the threads are released simultaneously.

The barrier can be reused any number of times for the same number of threads.

As an example, here is a simple way to synchronize a client and server thread:

b = Barrier(2, timeout=5)

def server():
    start_server()
    b.wait()
    while True:
        connection = accept_connection()
        process_server_connection(connection)

def client():
    b.wait()
    while True:
        connection = make_connection()
        process_client_connection(connection)

class threading.Barrier(parties, action=None, timeout=None)

Create a barrier object for parties number of threads. An action, when provided, is a callable to be called by one of the threads when they are released. timeout is the default timeout value if none is specified for the wait() method.

wait(timeout=None)

Pass the barrier. When all the threads party to the barrier have called this function, they are all released simultaneously. If a timeout is provided, it is used in preference to any that was supplied to the class constructor.

The return value is an integer in the range 0 to parties – 1, different for each thread. This can be used to select a thread to do some special housekeeping, e.g.:

i = barrier.wait()
if i == 0:
    # Only one thread needs to print this
    print("passed the barrier")

If an action was provided to the constructor, one of the threads will have called it prior to being released. Should this call raise an error, the barrier is put into the broken state.

If the call times out, the barrier is put into the broken state.

This method may raise a BrokenBarrierError exception if the barrier is broken or reset while a thread is waiting.

reset()

Return the barrier to the default, empty state. Any threads waiting on it will receive the BrokenBarrierError exception.

Note that using this function may can require some external synchronization if there are other threads whose state is unknown. If a barrier is broken it may be better to just leave it and create a new one.

abort()

Put the barrier into a broken state. This causes any active or future calls to wait() to fail with the BrokenBarrierError. Use this for example if one of the needs to abort, to avoid deadlocking the application.

It may be preferable to simply create the barrier with a sensible timeout value to automatically guard against one of the threads going awry.

parties

The number of threads required to pass the barrier.

n_waiting

The number of threads currently waiting in the barrier.

broken

A boolean that is True if the barrier is in the broken state.

exception threading.BrokenBarrierError

This exception, a subclass of RuntimeError, is raised when the Barrier object is reset or broken.

Using locks, conditions, and semaphores in the with statement

All of the objects provided by this module that have acquire() and release() methods can be used as context managers for a with statement. The acquire() method will be called when the block is entered, and release() will be called when the block is exited. Hence, the following snippet:

with some_lock:
    # do something...

is equivalent to:

some_lock.acquire()
try:
    # do something...
finally:
    some_lock.release()

Currently, Lock, RLock, Condition, Semaphore, and BoundedSemaphore objects may be used as with statement context managers.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

동시 실행 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

동시 실행 »

|

multiprocessing — 프로세스 기반 병렬 처리

소스 코드: Lib/multiprocessing/ [https://github.com/python/cpython/tree/3.7/Lib/multiprocessing/]

소개

multiprocessing 은 threading 모듈과 유사한 API를 사용하여 프로세스 스포닝(spawning)을 지원하는 패키지입니다. multiprocessing 패키지는 지역과 원격 동시성을 모두 제공하며 스레드 대신 서브 프로세스를 사용하여 전역 인터프리터 록 을 효과적으로 피합니다. 이것 때문에, multiprocessing 모듈은 프로그래머가 주어진 기계에서 다중 프로세서를 최대한 활용할 수 있게 합니다. 유닉스와 윈도우에서 모두 실행됩니다.

multiprocessing 모듈은 threading 모듈에 대응 물이 없는 API도 제공합니다. 이것의 대표적인 예가 Pool 객체입니다. 이 객체는 여러 입력 값에 걸쳐 함수의 실행을 병렬 처리하고 입력 데이터를 프로세스에 분산시키는 편리한 방법을 제공합니다(데이터 병렬 처리). 다음 예제는 자식 프로세스가 해당 모듈을 성공적으로 임포트 할 수 있도록, 모듈에서 이러한 함수를 정의하는 일반적인 방법을 보여줍니다. 다음은 Pool 를 사용하는 데이터 병렬 처리의 기본 예제입니다:

from multiprocessing import Pool

def f(x):
    return x*x

if __name__ == '__main__':
    with Pool(5) as p:
        print(p.map(f, [1, 2, 3]))

표준 출력으로 다음과 같은 것을 인쇄합니다

[1, 4, 9]

Process 클래스

multiprocessing에서, 프로세스는 Process 객체를 생성한 후 start() 메서드를 호출해서 스폰합니다. Process 는 threading.Thread 의 API를 따릅니다. 다중 프로세스 프로그램의 간단한 예는 다음과 같습니다

from multiprocessing import Process

def f(name):
    print('hello', name)

if __name__ == '__main__':
    p = Process(target=f, args=('bob',))
    p.start()
    p.join()

이 과정에 참여하는 개별 프로세스의 ID를 보기 위해, 이렇게 예제를 확장합니다:

from multiprocessing import Process
import os

def info(title):
    print(title)
    print('module name:', __name__)
    print('parent process:', os.getppid())
    print('process id:', os.getpid())

def f(name):
    info('function f')
    print('hello', name)

if __name__ == '__main__':
    info('main line')
    p = Process(target=f, args=('bob',))
    p.start()
    p.join()

if __name__ == '__main__' 부분이 필요한 이유에 대한 설명은 프로그래밍 지침을 보십시오.

컨텍스트 및 시작 방법

플랫폼에 따라, multiprocessing은 프로세스를 시작하는 세 가지 방법을 지원합니다. 이러한 시작 방법 은

spawn

부모 프로세스는 깨끗한 새 파이썬 인터프리터 프로세스를 시작합니다. 자식 프로세스는 프로세스 객체의 run() 메서드를 실행하는데 필요한 자원만 상속받습니다. 특히, 부모 프로세스의 불필요한 파일 기술자와 핸들은 상속되지 않습니다. 이 방법을 사용하여 프로세스를 시작하는 것은 fork 나 forkserver 를 사용하는 것에 비해 다소 느립니다.

유닉스 및 윈도우에서 사용 가능합니다. 윈도우의 기본값.

fork

부모 프로세스는 os.fork() 를 사용하여 파이썬 인터프리터를 포크 합니다. 자식 프로세스는, 시작될 때, 부모 프로세스와 실질적으로 같습니다. 부모의 모든 자원이 자식 프로세스에 의해 상속됩니다. 다중 스레드 프로세스를 안전하게 포크 하기 어렵다는 점에 주의하십시오.

유닉스에서만 사용 가능합니다. 유닉스의 기본값.

forkserver

프로그램이 시작되고 forkserver 시작 방법을 선택하면, 서버 프로세스가 시작됩니다. 그 이후부터, 새로운 프로세스가 필요할 때마다, 부모 프로세스는 서버에 연결하여 새로운 프로세스를 포크 하도록 요청합니다. 포크 서버 프로세스는 단일 스레드이므로 os.fork() 를 사용하는 것이 안전합니다. 불필요한 자원은 상속되지 않습니다.

유닉스 파이프를 통해 파일 기술자를 전달할 수 있는 유닉스 플랫폼에서 사용할 수 있습니다.

버전 3.4에서 변경: 모든 유닉스 플랫폼에 spawn 이 추가되었고, 일부 유닉스 플랫폼에는 forkserver 가 추가되었습니다. 윈도우에서 자식 프로세스는 상속 가능한 모든 부모 핸들을 더는 상속하지 않습니다.

유닉스에서 spawn 또는 forkserver 시작 방법을 사용하면 세마포어 추적기 프로세스 역시 시작되는데, 프로그램의 프로세스들이 만든 삭제되지 않은 이름있는 세마포어를 추적합니다. 모든 프로세스가 종료된 후 세마포어 추적기는 남아있는 세마포어를 제거합니다. 일반적으로 아무것도 남아 있지 않아야 하지만, 프로세스가 시그널에 의해 죽으면 “누수된” 세마포어가 있을 수 있습니다. (이름있는 세마포어의 제거는 심각한 문제인데, 시스템이 제한된 수만 허용하고 다음 재부팅 때까지 자동으로 제거되지 않기 때문입니다.)

시작 방법을 선택하려면 메인 모듈의 if __name__ == '__main__' 절에서 set_start_method()를 사용하십시오. 예를 들면:

import multiprocessing as mp

def foo(q):
    q.put('hello')

if __name__ == '__main__':
    mp.set_start_method('spawn')
    q = mp.Queue()
    p = mp.Process(target=foo, args=(q,))
    p.start()
    print(q.get())
    p.join()

set_start_method() 는 프로그램에서 한 번만 사용되어야 합니다.

또는, get_context()를 사용하여 컨텍스트 객체를 얻을 수 있습니다. 컨텍스트 객체는 multiprocessing 모듈과 같은 API를 제공하므로 한 프로그램에서 여러 시작 방법을 사용할 수 있습니다.

import multiprocessing as mp

def foo(q):
    q.put('hello')

if __name__ == '__main__':
    ctx = mp.get_context('spawn')
    q = ctx.Queue()
    p = ctx.Process(target=foo, args=(q,))
    p.start()
    print(q.get())
    p.join()

한 컨텍스트와 관련된 객체는 다른 컨텍스트의 프로세스와 호환되지 않을 수 있음에 주의하십시오. 특히 fork 컨텍스트를 사용하여 생성된 록은 spawn 또는 forkserver 시작 방법을 사용하여 시작된 프로세스로 전달될 수 없습니다.

특정 시작 방법을 사용하고자 하는 라이브러리는 아마도 get_context()를 사용하여 라이브러리 사용자의 선택을 방해하지 않아야 합니다.

경고

'spawn' 과 'forkserver' 시작 방법은 현재 유닉스에서 “고정된(frozen)” 실행 파일(즉, PyInstaller와 cx_Freeze와 같은 패키지로 만든 바이너리)과 함께 사용할 수 없습니다. 'fork' 시작 방법은 작동합니다.

프로세스 간 객체 교환

multiprocessing 은 두 가지 유형의 프로세스 간 통신 채널을 지원합니다:

큐

Queue 클래스는 queue.Queue 의 클론에 가깝습니다. 예를 들면:

from multiprocessing import Process, Queue

def f(q):
    q.put([42, None, 'hello'])

if __name__ == '__main__':
    q = Queue()
    p = Process(target=f, args=(q,))
    p.start()
    print(q.get())    # prints "[42, None, 'hello']"
    p.join()

큐는 스레드와 프로세스에 안전합니다.

파이프

Pipe() 함수는 파이프로 연결된 한 쌍의 연결 객체를 돌려주는데 기본적으로 양방향(duplex)입니다. 예를 들면:

from multiprocessing import Process, Pipe

def f(conn):
    conn.send([42, None, 'hello'])
    conn.close()

if __name__ == '__main__':
    parent_conn, child_conn = Pipe()
    p = Process(target=f, args=(child_conn,))
    p.start()
    print(parent_conn.recv())   # prints "[42, None, 'hello']"
    p.join()

Pipe() 가 반환하는 두 개의 연결 객체는 파이프의 두 끝을 나타냅니다. 각 연결 객체에는 (다른 것도 있지만) send() 및 recv() 메서드가 있습니다. 두 프로세스 (또는 스레드)가 파이프의 같은 끝에서 동시에 읽거나 쓰려고 하면 파이프의 데이터가 손상될 수 있습니다. 물론 파이프의 다른 끝을 동시에 사용하는 프로세스로 인해 손상될 위험은 없습니다.

프로세스 간 동기화

multiprocessing 은 threading 에 있는 모든 동기화 프리미티브의 등가물을 포함합니다. 예를 들어 한 번에 하나의 프로세스만 표준 출력으로 인쇄하도록 록을 사용할 수 있습니다:

from multiprocessing import Process, Lock

def f(l, i):
    l.acquire()
    try:
        print('hello world', i)
    finally:
        l.release()

if __name__ == '__main__':
    lock = Lock()

    for num in range(10):
        Process(target=f, args=(lock, num)).start()

록을 사용하지 않으면 다른 프로세스의 출력들이 모두 섞일 수 있습니다.

프로세스 간 상태 공유

위에서 언급했듯이, 동시성 프로그래밍을 할 때 보통 가능한 한 공유된 상태를 사용하지 않는 것이 최선입니다. 여러 프로세스를 사용할 때 특히 그렇습니다.

그러나, 정말로 공유 데이터를 사용해야 한다면 multiprocessing 이 몇 가지 방법을 제공합니다.

공유 메모리

데이터는 Value 또는 Array를 사용하여 공유 메모리 맵에 저장 될 수 있습니다. 예를 들어, 다음 코드는

from multiprocessing import Process, Value, Array

def f(n, a):
    n.value = 3.1415927
    for i in range(len(a)):
        a[i] = -a[i]

if __name__ == '__main__':
    num = Value('d', 0.0)
    arr = Array('i', range(10))

    p = Process(target=f, args=(num, arr))
    p.start()
    p.join()

    print(num.value)
    print(arr[:])

를 인쇄할 것입니다

3.1415927
[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]

num 과 arr 을 만들 때 사용되는 'd' 와 'i' 인자는 array 모듈에서 사용되는 종류의 타입 코드입니다: 'd' 는 배정밀도 부동 소수점을 나타내고, 'i' 는 부호 있는 정수를 나타냅니다. 이러한 공유 객체는 프로세스 및 스레드에 안전합니다.

공유 메모리를 더 유연하게 사용하려면, 공유 메모리에 할당된 임의의 ctypes 객체 생성을 지원하는 multiprocessing.sharedctypes 모듈을 사용할 수 있습니다.

서버 프로세스

Manager() 가 반환한 관리자 객체는 파이썬 객체를 유지하고 다른 프로세스가 프락시를 사용하여 이 객체를 조작할 수 있게 하는 서버 프로세스를 제어합니다.

Manager() 가 반환한 관리자는 list, dict, Namespace, Lock, RLock, Semaphore, BoundedSemaphore, Condition, Event, Barrier, Queue, Value 그리고 Array 형을 지원합니다. 예를 들어, 다음 코드는

from multiprocessing import Process, Manager

def f(d, l):
    d[1] = '1'
    d['2'] = 2
    d[0.25] = None
    l.reverse()

if __name__ == '__main__':
    with Manager() as manager:
        d = manager.dict()
        l = manager.list(range(10))

        p = Process(target=f, args=(d, l))
        p.start()
        p.join()

        print(d)
        print(l)

를 인쇄할 것입니다

{0.25: None, 1: '1', '2': 2}
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

서버 프로세스 관리자는 임의의 객체 형을 지원하도록 만들 수 있으므로 공유 메모리 객체를 사용하는 것보다 융통성이 있습니다. 또한, 단일 관리자를 네트워크를 통해 서로 다른 컴퓨터의 프로세스에서 공유 할 수 있습니다. 그러나 공유 메모리를 사용할 때보다 느립니다.

작업자 풀 사용

Pool 클래스는 작업자 프로세스 풀을 나타냅니다. 여기에는 몇 가지 다른 방법으로 작업을 작업자 프로세스로 넘길 수 있는 메서드가 있습니다.

예를 들면:

from multiprocessing import Pool, TimeoutError
import time
import os

def f(x):
    return x*x

if __name__ == '__main__':
    # start 4 worker processes
    with Pool(processes=4) as pool:

        # print "[0, 1, 4,..., 81]"
        print(pool.map(f, range(10)))

        # print same numbers in arbitrary order
        for i in pool.imap_unordered(f, range(10)):
            print(i)

        # evaluate "f(20)" asynchronously
        res = pool.apply_async(f, (20,))      # runs in *only* one process
        print(res.get(timeout=1))             # prints "400"

        # evaluate "os.getpid()" asynchronously
        res = pool.apply_async(os.getpid, ()) # runs in *only* one process
        print(res.get(timeout=1))             # prints the PID of that process

        # launching multiple evaluations asynchronously *may* use more processes
        multiple_results = [pool.apply_async(os.getpid, ()) for i in range(4)]
        print([res.get(timeout=1) for res in multiple_results])

        # make a single worker sleep for 10 secs
        res = pool.apply_async(time.sleep, (10,))
        try:
            print(res.get(timeout=1))
        except TimeoutError:
            print("We lacked patience and got a multiprocessing.TimeoutError")

        print("For the moment, the pool remains available for more work")

    # exiting the 'with'-block has stopped the pool
    print("Now the pool is closed and no longer available")

풀의 메서드는 풀을 만든 프로세스에서만 사용되어야 함에 유의하세요.

참고

이 패키지 내의 기능을 사용하려면 __main__ 모듈을 자식이 임포트 할 수 있어야 합니다. 이것은 프로그래밍 지침에서 다루지만, 여기에서 지적할 가치가 있습니다. 이것은 몇몇 예제, 가령 multiprocessing.pool.Pool 예제가 대화형 인터프리터에서 동작하지 않음을 의미합니다. 예를 들면:

>>> from multiprocessing import Pool
>>> p = Pool(5)
>>> def f(x):
...     return x*x
...
>>> with p:
...   p.map(f, [1,2,3])
Process PoolWorker-1:
Process PoolWorker-2:
Process PoolWorker-3:
Traceback (most recent call last):
AttributeError: 'module' object has no attribute 'f'
AttributeError: 'module' object has no attribute 'f'
AttributeError: 'module' object has no attribute 'f'

(이것을 시도해 보면 실제로 세 개의 전체 트레이스백이 어느 정도 임의로 번갈아 출력됩니다. 그런 다음 마스터 프로세스를 중지시켜야 할 수도 있습니다.)

레퍼런스

multiprocessing 패키지는 대부분 threading 모듈의 API를 복제합니다.

Process와 예외

class multiprocessing.Process(group=None, target=None, name=None, args=(), kwargs={}, *, daemon=None)

프로세스 객체는 별도의 프로세스에서 실행되는 작업을 나타냅니다. Process 클래스는 threading.Thread 의 모든 메서드와 같은 메서드를 갖습니다.

생성자는 항상 키워드 인자로 호출해야 합니다. group 은 항상 None 이어야 합니다; 이것은 threading.Thread 와의 호환성을 위해서만 존재합니다. target 은 run() 메서드에 의해 호출될 콜러블 객체입니다. 기본값은 None 인데, 아무것도 호출되지 않음을 의미합니다. name 은 프로세스 이름입니다 (자세한 내용은 name 참조). args 는 target 호출을 위한 인자 튜플입니다. kwargs 는 target 호출을 위한 키워드 인자 딕셔너리입니다. 제공되는 경우, 키워드 전용 daemon 인자는 프로세스 daemon 플래그를 True 또는 False 로 설정합니다. None (기본값) 이면, 이 플래그는 만드는 프로세스로부터 상속됩니다.

기본적으로, 아무 인자도 target 에 전달되지 않습니다.

서브 클래스가 생성자를 재정의하면, 프로세스에 다른 작업을 하기 전에 베이스 클래스 생성자(Process.__init__())를 호출해야 합니다.

버전 3.3에서 변경: daemon 인자가 추가되었습니다.

run()

프로세스의 활동을 나타내는 메서드.

서브 클래스에서 이 메서드를 재정의할 수 있습니다. 표준 run() 메서드는 객체의 생성자에 target 인자로 전달된 콜러블 객체를 호출하는데 (있다면) args 와 kwargs 인자를 각각 위치 인자와 키워드 인자로 사용합니다.

start()

프로세스의 활동을 시작합니다.

이것은 프로세스 객체 당 최대 한 번 호출되어야 합니다. 객체의 run() 메서드가 별도의 프로세스에서 호출되도록 합니다.

join([timeout])

선택적 인자 timeout 이 None (기본값) 인 경우, 메서드는 join() 메서드가 호출된 프로세스가 종료될 때까지 블록 됩니다. timeout 이 양수면 최대 timeout 초 동안 블록 됩니다. 이 메서드는 프로세스가 종료되거나 메서드가 시간 초과 되면 None 을 돌려줌에 주의해야 합니다. 프로세스의 exitcode 를 검사하여 종료되었는지 확인하십시오.

프로세스는 여러 번 조인할 수 있습니다.

교착 상태를 유발할 수 있으므로 프로세스는 자신을 조인할 수 없습니다. 프로세스가 시작되기 전에 프로세스에 조인하려고 하면 에러가 발생합니다.

name

프로세스의 이름. 이름은 식별 목적으로만 사용되는 문자열입니다. 다른 의미는 없습니다. 여러 프로세스에 같은 이름이 주어질 수 있습니다.

초기 이름은 생성자에 의해 설정됩니다. 명시적 이름이 생성자에 제공되지 않으면, ‘Process-N₁:N₂:…:Nk’ 형식의 이름이 만들어지는데, 각각의 Nk 는 부모의 N 번째 자식입니다.

is_alive()

프로세스가 살아있는지 아닌지를 반환합니다.

대략, 프로세스 객체는 start() 메서드가 반환하는 순간부터 자식 프로세스가 종료될 때까지 살아있습니다.

daemon

프로세스의 데몬 플래그, 논리값. start() 가 호출되기 전에 설정되어야 합니다.

초깃값은 생성 프로세스에서 상속됩니다.

프로세스가 종료할 때, 모든 데몬 자식 프로세스를 강제 종료시키려고(terminate) 시도합니다.

데몬 프로세스는 하위 프로세스를 만들 수 없음에 유의하십시오. 그렇지 않으면 부모 프로세스가 종료될 때 데몬 프로세스가 강제 종료되어, 데몬 프로세스가 자식 프로세스를 고아로 남기게 됩니다. 또한, 이들은 유닉스 데몬이나 서비스가 아닙니다, 데몬이 아닌 프로세스들이 종료되면 강제 종료되는 (그리고 조인되지 않는) 일반 프로세스입니다.

threading.Thread API 외에도 Process 객체는 다음 어트리뷰트와 메서드도 지원합니다 :

pid

프로세스 ID를 돌려줍니다. 프로세스가 스폰 되기 전에는 None 입니다.

exitcode

자식의 종료 코드. 프로세스가 아직 종료되지 않았으면 None 이 됩니다. 음수 값 -N 은 자식이 시그널 N 에 의해 강제 종료되었음을 나타냅니다.

authkey

프로세스의 인증 키 (바이트열) 입니다.

multiprocessing 이 초기화될 때, 메인 프로세스는 os.urandom() 을 사용하여 임의의 문자열을 할당받습니다.

Process 객체가 생성될 때, 부모 프로세스의 인증 키를 상속받습니다. authkey 를 다른 바이트열로 설정하여 변경할 수 있습니다.

인증 키를 참조하세요.

sentinel

프로세스가 끝나면 “준비(ready)” 될 시스템 객체의 숫자 핸들.

multiprocessing.connection.wait() 를 사용해서 한 번에 여러 이벤트를 기다리고 싶다면, 이 값을 사용할 수 있습니다. 그렇지 않으면 join()을 호출하는 것이 더 간단합니다.

윈도우에서, 이것은 WaitForSingleObject 및 WaitForMultipleObjects 계열의 API 호출에서 사용할 수 있는 OS 핸들입니다. 유닉스에서, 이것은 select 모듈의 프리미티브들에서 사용할 수 있는 파일 기술자입니다.

버전 3.3에 추가.

terminate()

프로세스를 강제 종료합니다. 유닉스에서는 SIGTERM 시그널을 사용합니다; 윈도우에서는 TerminateProcess() 가 사용됩니다. 종료 처리기(exit handler)와 finally 절 등이 실행되지 않음에 주의하십시오.

프로세스의 자손 프로세스들은 강제 종료되지 않을 것입니다 – 단순히 고아가 될 것입니다.

경고

연결된 프로세스가 파이프 또는 큐를 사용할 때 이 메서드를 사용하면, 파이프 또는 큐가 손상되어 다른 프로세스에서 사용할 수 없게 될 수 있습니다. 마찬가지로, 프로세스가 록이나 세마포어 등을 획득한 경우 강제 종료하면 다른 프로세스가 교착 상태가 될 수 있습니다.

kill()

terminate()와 같지만, 유닉스에서 SIGKILL 시그널을 사용합니다.

버전 3.7에 추가.

close()

Process 객체를 닫아, 그것과 관련된 모든 자원을 해제합니다. 하부 프로세스가 여전히 실행 중이면 ValueError 가 발생합니다. 일단 close() 가 성공적으로 반환되면, Process 객체의 다른 대부분의 메서드와 어트리뷰트는 ValueError 를 발생시킵니다.

버전 3.7에 추가.

start(), join(), is_alive(), terminate() 및 exitcode 메서드는 프로세스 객체를 생성한 프로세스에 의해서만 호출되어야 합니다.

Process 의 몇몇 메서드를 사용하는 예제:

>>> import multiprocessing, time, signal
>>> p = multiprocessing.Process(target=time.sleep, args=(1000,))
>>> print(p, p.is_alive())
<Process(Process-1, initial)> False
>>> p.start()
>>> print(p, p.is_alive())
<Process(Process-1, started)> True
>>> p.terminate()
>>> time.sleep(0.1)
>>> print(p, p.is_alive())
<Process(Process-1, stopped[SIGTERM])> False
>>> p.exitcode == -signal.SIGTERM
True

exception multiprocessing.ProcessError

모든 multiprocessing 예외의 베이스 클래스입니다.

exception multiprocessing.BufferTooShort

Connection.recv_bytes_into() 가, 제공된 버퍼 객체가 읽은 메시지에 비해 너무 작을 때 일으키는 예외.

e 가 BufferTooShort 의 인스턴스라면, e.args[0] 는 메시지를 바이트열로 줍니다.

exception multiprocessing.AuthenticationError

인증 에러가 일어날 때 발생합니다.

exception multiprocessing.TimeoutError

시간제한이 초과하였을 때 시간제한을 건 메서드에 의해 발생합니다.

파이프와 큐

여러 프로세스를 사용할 때, 일반적으로 프로세스 간 통신을 위해 메시지 전달을 사용하고 록과 같은 동기화 프리미티브 사용을 피합니다.

메시지를 전달하기 위해 Pipe() (두 프로세스 간의 연결) 또는 큐(여러 생산자와 소비자를 허용합니다)를 사용할 수 있습니다.

Queue, SimpleQueue 그리고 JoinableQueue 형은, 표준 라이브러리의 queue.Queue 클래스에 따라 모델링 된, 다중 생산자, 다중 소비자 FIFO 큐입니다. 이것들은 파이썬 2.5의 queue.Queue 클래스에서 도입된 task_done()과 join() 메서드가 Queue 에 없다는 점에서 다릅니다.

JoinableQueue를 사용하면, 큐에서 제거된 작업마다 JoinableQueue.task_done()을 호출해야 합니다. 그렇지 않으면 완료되지 않은 작업의 수를 세는 데 사용되는 세마포어가 결국 오버플로 되어 예외를 일으킵니다.

관리자 객체를 사용하여 공유 큐를 생성할 수도 있습니다 – 관리자를 보세요.

참고

multiprocessing 은 제한 시간 초과 신호를 보내기 위해 보통 queue.Empty 와 queue.Full 예외를 사용합니다. multiprocessing 이름 공간에는 없으므로 queue에서 임포트 해야 합니다.

참고

객체를 큐에 넣으면, 객체는 피클 되고 배경 스레드가 나중에 피클 된 데이터를 하부 파이프로 플러시 합니다. 이것은 다소 의외의 결과로 이어지지만, 실제적인 어려움을 일으키지는 않아야 합니다 – 이것이 여러분을 정말로 신경 쓰이게 한다면, 대신 관리자 로 만든 큐를 사용할 수 있습니다.

빈 큐에 객체를 넣은 후에, empty() 메서드가 False를 반환하고 get_nowait()가 queue.Empty 를 일으키지 않고 반환할 수 있기 전까지 극히 작은 지연이 있을 수 있습니다.

여러 프로세스가 객체를 큐에 넣는 경우, 반대편에서 객체가 다른 순서로 수신될 수 있습니다. 그러나, 같은 프로세스에 의해 큐에 들어간 객체들은 항상 상대적인 순서가 유지됩니다.

경고

Queue를 사용하려고 하는 동안 Process.terminate() 또는 os.kill() 을 사용하여 프로세스를 죽이면, 큐의 데이터가 손상될 수 있습니다. 이로 인해 나중에 다른 프로세스가 큐를 사용하려고 할 때 예외가 발생할 수 있습니다.

경고

위에서 언급했듯이, 자식 프로세스가 항목을 큐에 넣었을 때 (그리고 JoinableQueue.cancel_join_thread 를 사용하지 않았다면), 버퍼링 된 모든 항목이 파이프로 플러시 될 때까지 해당 프로세스가 종료되지 않습니다.

이것은, 여러분이 그 자식 프로세스를 조인하려고 하면, 큐에 넣은 모든 항목을 소진하지 않는 한 교착 상태가 발생할 수 있다는 뜻입니다. 마찬가지로, 그 자식 프로세스가 데몬이 아니면 부모 프로세스가 종료 시점에 데몬이 아닌 모든 자식을 조인하려고 할 때 정지될 수 있습니다.

관리자를 사용하여 생성된 큐에는 이 문제가 없습니다. 프로그래밍 지침을 참조하세요.

프로세스 간 통신을 위해 큐를 사용하는 예는 예제을 참조하십시오.

multiprocessing.Pipe([duplex])

파이프의 끝을 나타내는 Connection 객체 쌍 (conn1, conn2) 를 반환합니다.

duplex 가 True (기본값) 면 파이프는 양방향입니다. duplex 가 False 인 경우 파이프는 단방향입니다: conn1 은 메시지를 받는 데에만 사용할 수 있고, conn2 는 메시지를 보낼 때만 사용할 수 있습니다.

class multiprocessing.Queue([maxsize])

파이프와 몇 개의 록/세마포어를 사용하여 구현된 프로세스 공유 큐를 반환합니다. 프로세스가 처음으로 항목을 큐에 넣으면 버퍼에서 파이프로 객체를 전송하는 피더 스레드가 시작됩니다.

제한 시간 초과를 알리기 위해 표준 라이브러리의 queue 모듈에서 정의되는 queue.Empty 와 queue.Full 예외를 일으킵니다.

Queue 는 task_done()과 join() 을 제외한 queue.Queue 의 모든 메서드를 구현합니다.

qsize()

큐의 대략의 크기를 돌려줍니다. 다중 스레딩/다중 프로세싱 특성을 타기 때문에 이 숫자는 신뢰할 수 없습니다.

이것은 sem_getvalue() 가 구현되지 않은 Mac OS X와 같은 유닉스 플랫폼에서 NotImplementedError를 발생시킬 수 있습니다.

empty()

큐가 비어 있다면 True 를, 그렇지 않으면 False 를 반환합니다. 다중 스레딩/다중 프로세싱 특성을 타기 때문에 신뢰할 수 없습니다.

full()

큐가 가득 차면 True 를, 그렇지 않으면 False 를 반환합니다. 다중 스레딩/다중 프로세싱 특성을 타기 때문에 신뢰할 수 없습니다.

put(obj[, block[, timeout]])

obj를 큐에 넣습니다. 선택적 인자 block 이 True (기본값)이고 timeout 이 None (기본값) 이면, 빈 슬롯이 생길 때까지 필요한 경우 블록합니다. timeout 이 양수인 경우, 최대 timeout 초만큼 블록하고 그 시간 내에 사용 가능 슬롯이 생기지 않으면 queue.Full 예외를 발생시킵니다. 그렇지 않으면 (block 이 False) 빈 슬롯을 즉시 사용할 수 있으면 큐에 항목을 넣고, 그렇지 않으면 queue.Full 예외를 발생시킵니다 (이 경우 timeout 은 무시됩니다).

put_nowait(obj)

put(obj, False) 와 같습니다.

get([block[, timeout]])

큐에서 항목을 제거하고 반환합니다. 선택적 인자 block 이 True (기본값)이고 timeout 이 None (기본값) 이면, 항목이 들어올 때까지 필요한 경우 블록합니다. timeout 이 양수인 경우, 최대 timeout 초만큼 블록하고 그 시간 내에 항목이 들어오지 않으면 queue.Empty 예외를 발생시킵니다. 그렇지 않으면 (block이 False) 즉시 사용할 수 있는 항목이 있으면 반환하고, 그렇지 않으면 queue.Empty 예외를 발생시킵니다 (이 경우 timeout 은 무시됩니다).

get_nowait()

get(False) 와 같습니다.

multiprocessing.Queue 에는 queue.Queue 에서 찾을 수 없는 몇 가지 추가 메서드가 있습니다. 일반적으로 이러한 메서드는 대부분 코드에서 필요하지 않습니다:

close()

현재 프로세스가 이 큐에 더는 데이터를 넣지 않을 것을 나타냅니다. 버퍼에 저장된 모든 데이터를 파이프로 플러시 하면 배경 스레드가 종료됩니다. 큐가 가비지 수집될 때 자동으로 호출됩니다.

join_thread()

배경 스레드에 조인합니다. close() 가 호출된 후에만 사용할 수 있습니다. 배경 스레드가 종료될 때까지 블록해서 버퍼의 모든 데이터가 파이프로 플러시 되었음을 보증합니다.

기본적으로 프로세스가 큐를 만든 주체가 아니면 종료할 때 큐의 배경 스레드를 조인하려고 합니다. 프로세스는 cancel_join_thread()를 호출하여 join_thread() 가 아무것도 하지 않게 할 수 있습니다.

cancel_join_thread()

join_thread() 의 블록을 방지합니다. 특히, 프로세스가 종료할 때 배경 스레드를 자동으로 조인하는 것을 막습니다 – join_thread()를 보십시오.

이 메서드의 더 좋은 이름은 allow_exit_without_flush() 일 것입니다. 큐에 포함된 데이터가 유실될 가능성이 크며, 거의 확실히 사용할 필요가 없을 겁니다. 현재 프로세스가 하부 파이프로 대기 중인 데이터를 플러시 할 때까지 기다리지 않고 즉시 종료해야 하고 데이터 손실에 대해서는 신경 쓰지 않을 때만을 위한 것입니다.

참고

이 클래스의 기능은 호스트 운영 체제의 작동하는 공유 세마포어 구현을 요구합니다. 그런 것이 없으면, 클래스의 기능이 비활성화되고, Queue 의 인스턴스를 만들려고 하면 ImportError 를 일으킵니다. 자세한 내용은 bpo-3770 [https://bugs.python.org/issue?@action=redirect&bpo=3770]을 참조하십시오. 아래에 나열된 특수 큐 형들도 마찬가지입니다.

class multiprocessing.SimpleQueue

이것은 단순화된 Queue 형으로, 록이 걸린 Pipe 에 매우 가깝습니다.

empty()

큐가 비어 있다면 True 를, 그렇지 않으면 False 를 반환합니다.

get()

큐에서 항목을 제거하고 반환합니다.

put(item)

item 을 큐에 넣습니다.

class multiprocessing.JoinableQueue([maxsize])

Queue 서브 클래스 JoinableQueue 는 추가로 task_done()과 join() 메서드를 가진 큐입니다.

task_done()

앞서 큐에 넣은 작업이 완료되었음을 나타냅니다. 큐 소비자가 사용합니다. 작업을 가져오는데 사용된 각 get() 마다, 뒤따르는 task_done() 호출은 작업에 대한 처리가 완료되었음을 큐에 알립니다.

만약 join() 이 현재 블록하고 있다면, 모든 항목이 처리될 때 재개될 것입니다 (put() 으로 큐에 넣은 모든 항목에 대해 task_done() 호출을 수신했다는 뜻입니다).

큐에 있는 항목보다 많이 호출되면 ValueError 를 발생시킵니다.

join()

큐의 모든 항목을 가져가서 처리할 때까지 블록합니다.

항목이 큐에 추가될 때마다 완료되지 않은 작업의 수는 올라갑니다. 소비자가 그 항목을 꺼냈고 그에 대한 모든 작업을 완료했음을 알리기 위해 task_done()을 호출할 때마다 숫자는 줄어듭니다. 완료되지 않은 작업의 수가 0으로 떨어지면 join() 이 블록으로부터 풀려납니다.

잡동사니

multiprocessing.active_children()

현재 프로세스의 모든 살아있는 자식 리스트를 반환합니다.

이것을 호출하면 이미 완료된 프로세스에 “조인” 하는 부작용이 있습니다.

multiprocessing.cpu_count()

시스템의 CPU 수를 반환합니다.

이 숫자는 현재 프로세스에서 사용할 수 있는 CPU 수와 같지 않습니다. 사용 가능한 CPU 수는 len(os.sched_getaffinity(0)) 로 얻을 수 있습니다.

NotImplementedError를 일으킬 수 있습니다.

더 보기

os.cpu_count()

multiprocessing.current_process()

현재 프로세스에 해당하는 Process 객체를 반환합니다.

threading.current_thread()와 유사한 기능을 제공합니다.

multiprocessing.freeze_support()

multiprocessing을 사용하는 프로그램이 고정되어(frozen) 윈도우 실행 파일을 생성할 때를 위한 지원을 추가합니다. (py2exe, PyInstaller 및 cx_Freeze 에서 테스트 되었습니다.)

메인 모듈의 if __name__ == '__main__' 줄 바로 뒤에서 이 함수를 호출해야 합니다. 예를 들면:

from multiprocessing import Process, freeze_support

def f():
    print('hello world!')

if __name__ == '__main__':
    freeze_support()
    Process(target=f).start()

freeze_support() 줄이 생략된 경우 고정된 실행 파일을 실행하려고 하면 RuntimeError 가 발생합니다.

freeze_support() 호출은 윈도우가 아닌 다른 운영 체제에서 실행될 때는 아무런 영향을 미치지 않습니다. 또한, 모듈이 윈도우상의 파이썬 인터프리터에 의해 정상적으로 실행되는 경우 (프로그램이 고정되지 않은 경우)에도 freeze_support() 는 아무 효과가 없습니다.

multiprocessing.get_all_start_methods()

지원되는 시작 방법의 리스트를 반환하는데, 그 중 첫 번째가 기본값입니다. 가능한 시작 방법은 'fork', 'spawn' 및 'forkserver' 입니다. 윈도우에서는 'spawn' 만 사용할 수 있습니다. 유닉스에서는 'fork' 와 'spawn' 이 항상 지원되며 'fork' 가 기본값입니다.

버전 3.4에 추가.

multiprocessing.get_context(method=None)

multiprocessing 모듈과 같은 어트리뷰트를 가진 컨텍스트 객체를 반환합니다.

method 가 None 이면 기본 컨텍스트가 반환됩니다. 그렇지 않으면 method 는 'fork', 'spawn', 'forkserver' 이어야 합니다. 지정된 시작 방법을 사용할 수 없는 경우 ValueError 가 발생합니다.

버전 3.4에 추가.

multiprocessing.get_start_method(allow_none=False)

프로세스를 기동하기 위해서 사용되는 시작 방법의 이름을 돌려줍니다.

시작 방법이 고정되지 않았고 allow_none 이 거짓이면, 시작 방법이 기본값으로 고정되고 이름이 반환됩니다. 시작 방법이 고정되지 않았고 allow_none이 참이면, None 이 반환됩니다.

반환 값은 'fork', 'spawn', 'forkserver' 또는 None 입니다. 유닉스에서는 'fork' 가 기본값이고, 윈도우에서는 'spawn' 이 기본값입니다.

버전 3.4에 추가.

multiprocessing.set_executable()

자식 프로세스를 시작할 때 사용할 파이썬 인터프리터의 경로를 설정합니다. (기본적으로 sys.executable 이 사용됩니다). 파이썬은 내장하는 사람들은 아마도 다음과 같이 할 필요가 있습니다

set_executable(os.path.join(sys.exec_prefix, 'pythonw.exe'))

자식 프로세스를 만들기 전에 해야 합니다.

버전 3.4에서 변경: 이제 'spawn' 시작 방법을 사용할 때 유닉스에서 지원됩니다.

multiprocessing.set_start_method(method)

자식 프로세스를 시작하는 데 사용해야 하는 방법을 설정합니다. method 는 'fork', 'spawn' 또는 'forkserver' 일 수 있습니다.

이것은 한 번만 호출해야 하며, 메인 모듈의 if __name__ == '__main__' 절 내에서 보호되어야 합니다.

버전 3.4에 추가.

참고

multiprocessing 에는 threading.active_count(), threading.enumerate(), threading.settrace(), threading.setprofile(), threading.Timer 또는 threading.local 의 대응 물이 없습니다.

Connection 객체

연결 객체를 사용하면 피클 가능한 객체나 문자열을 보내고 받을 수 있습니다. 메시지 지향 연결된 소켓으로 생각할 수 있습니다.

연결 객체는 보통 Pipe 를 사용해서 만들어집니다 – 리스너와 클라이언트 도 참고하세요.

class multiprocessing.connection.Connection

send(obj)

연결의 반대편 끝에서 recv()를 사용하여 읽을 객체를 보냅니다.

객체는 피클 가능해야 합니다. 매우 큰 피클(약 32 MiB+, OS에 따라 다릅니다)은 ValueError 예외를 발생시킬 수 있습니다.

recv()

연결의 반대편 끝에서 send()로 보낸 객체를 반환합니다. 뭔가 수신할 때까지 블록합니다. 수신할 내용이 없고 반대편 끝이 닫혔으면 EOFError를 발생시킵니다.

fileno()

연결이 사용하는 파일 기술자나 핸들을 돌려줍니다.

close()

연결을 닫습니다.

연결이 가비지 수집될 때 자동으로 호출됩니다.

poll([timeout])

읽어 들일 데이터가 있는지를 돌려줍니다.

timeout 을 지정하지 않으면 즉시 반환됩니다. timeout 이 숫자면 블록할 최대 시간(초)을 지정합니다. timeout 이 None 이면 시간제한이 없습니다.

여러 개의 연결 객체를 multiprocessing.connection.wait() 을 사용하여 한 번에 폴링 할 수 있습니다.

send_bytes(buffer[, offset[, size]])

바이트열류 객체 의 바이트 데이터를 하나의 완전한 메시지로 보냅니다.

offset 이 주어지면 buffer 의 해당 위치부터 데이터를 읽습니다. size 가 주어지면 그만큼의 바이트를 버퍼에서 읽습니다. 매우 큰 버퍼(약 32 MiB+, OS에 따라 다릅니다)는 ValueError 예외를 발생시킬 수 있습니다

recv_bytes([maxlength])

접속의 반대편 끝에서 송신된 바이트 데이터의 완전한 메시지를 문자열로 돌려줍니다. 뭔가 수신할 때까지 블록합니다. 수신할 내용이 없고 반대편 끝이 닫혔으면 EOFError를 발생시킵니다.

maxlength 가 지정되고 메시지가 maxlength 보다 길면 OSError 가 발생하고 연결은 더는 읽을 수 없게 됩니다.

버전 3.3에서 변경: 이 함수는 IOError 를 발생시켜왔는데, 이제는 OSError 의 별칭입니다.

recv_bytes_into(buffer[, offset])

연결의 반대편 끝에서 보낸 바이트 데이터의 전체 메시지를 buffer 로 읽어 들이고, 메시지의 바이트 수를 반환합니다. 뭔가 수신할 때까지 블록합니다. 수신할 내용이 없고 반대편 끝이 닫혔으면 EOFError를 발생시킵니다.

buffer 는 쓰기 가능한 바이트열류 객체 여야 합니다. offset 이 지정되면, 버퍼의 그 위치로부터 메시지를 씁니다. offset은 buffer 길이보다 작은 음수가 아닌 정수여야 합니다 (바이트 단위).

버퍼가 너무 작으면 BufferTooShort 예외가 발생하고, 완전한 메시지는 e.args[0] 으로 제공되는데, 여기서 e 는 예외 인스턴스입니다.

버전 3.3에서 변경: 이제 연결 객체 자체를 Connection.send() 와 Connection.recv() 를 사용하여 프로세스 간에 전송할 수 있습니다.

버전 3.3에 추가: 이제 연결 객체는 컨텍스트 관리 프로토콜을 지원합니다 – 컨텍스트 관리자 형를 보세요. __enter__() 는 연결 객체를 반환하고, __exit__() 는 close()를 호출합니다.

예를 들어:

>>> from multiprocessing import Pipe
>>> a, b = Pipe()
>>> a.send([1, 'hello', None])
>>> b.recv()
[1, 'hello', None]
>>> b.send_bytes(b'thank you')
>>> a.recv_bytes()
b'thank you'
>>> import array
>>> arr1 = array.array('i', range(5))
>>> arr2 = array.array('i', [0] * 10)
>>> a.send_bytes(arr1)
>>> count = b.recv_bytes_into(arr2)
>>> assert count == len(arr1) * arr1.itemsize
>>> arr2
array('i', [0, 1, 2, 3, 4, 0, 0, 0, 0, 0])

경고

Connection.recv() 메서드는 수신한 데이터를 자동으로 언 피클 합니다. 메시지를 보낸 프로세스를 신뢰할 수 없다면 보안상 위험 할 수 있습니다.

따라서, 연결 객체가 Pipe()를 사용하여 생성되지 않았다면, 일종의 인증을 수행한 후에만 recv() 및 send() 메서드를 사용해야 합니다. 인증 키를 참조하세요.

경고

프로세스가 파이프에 읽거나 쓰려고 할 때 죽으면, 파이프의 데이터가 손상될 가능성이 있습니다. 메시지 경계가 어디에 있는지 확신할 수 없는 상태가 될 가능성이 있기 때문입니다.

동기화 프리미티브

일반적으로 다중 프로세스 프로그램에서는 동기화 프리미티브가 다중 스레드 프로그램에서만큼 필요하지는 않습니다. threading 모듈에 대한 설명서를 참조하십시오.

관리자 객체를 사용하여 동기화 프리미티브를 생성할 수도 있습니다 – 관리자를 참조하세요.

class multiprocessing.Barrier(parties[, action[, timeout]])

배리어(barrier) 객체: threading.Barrier 의 복제본.

버전 3.3에 추가.

class multiprocessing.BoundedSemaphore([value])

제한된 세마포어 객체: threading.BoundedSemaphore 과 유사한 대응 물.

대응 물과 한 가지 차이가 있습니다: acquire 메서드의 첫 번째 인자에 block 이라는 이름을 사용해서 Lock.acquire() 와의 일관성을 유지합니다.

참고

Mac OS X에서, sem_getvalue() 가 해당 플랫폼에 구현되어 있지 않기 때문에 Semaphore와 구별되지 않습니다.

class multiprocessing.Condition([lock])

조건 변수: threading.Condition 의 별칭.

lock 을 지정할 때는 multiprocessing 의 Lock 이나 RLock 객체여야 합니다.

버전 3.3에서 변경: wait_for() 메서드가 추가되었습니다.

class multiprocessing.Event

threading.Event 의 복제본.

class multiprocessing.Lock

비 재귀적 록 객체: threading.Lock 과 유사한 대응 물. 일단 프로세스 또는 스레드가 록을 획득하면, 프로세스 또는 스레드에서 록을 획득하려는 후속 시도는 록이 해제될 때까지 블록 됩니다; 모든 프로세스 또는 스레드가 이를 해제할 수 있습니다. 스레드에 적용되는 threading.Lock 의 개념과 동작은, 명시된 경우를 제외하고, multiprocessing.Lock 를 통해 프로세스나 스레드에 그대로 적용됩니다.

Lock 은 실제로 기본 컨텍스트로 초기화된 multiprocessing.synchronize.Lock 의 인스턴스를 반환하는 팩토리 함수입니다.

Lock 은 컨텍스트 관리자 프로토콜을 지원하므로 with 문에서 사용될 수 있습니다.

acquire(block=True, timeout=None)

블록하거나 블록하지 않는 방식으로 록을 획득합니다.

block 인자가 True (기본값) 로 설정되면, 메서드 호출은 록이 해제 상태가 될 때까지 블록 한 다음, 잠금 상태로 만들고 True 를 반환합니다. 이 첫 번째 인자의 이름은 threading.Lock.acquire() 와 다르다는 것에 유의하세요.

block 인자가 False 로 설정되면, 메서드 호출은 블록 되지 않습니다. 록이 현재 잠금 상태면 False 를 반환합니다. 그렇지 않으면 록을 잠금 상태로 설정하고 True 를 반환합니다.

timeout 에 대해 양의 부동 소수점 값을 사용하여 호출하는 경우, 록을 얻을 수 없는 한 최대 timeout 으로 지정된 시간(초) 동안 블록합니다. timeout 을 음수 값으로 호출하는 것은 timeout 에 0을 주는 것과 같습니다. timeout 값이 None (기본값) 인 호출은 제한 시간을 무한대로 설정합니다. timeout 에 대한 음수와 None 값의 처리는 threading.Lock.acquire() 에서 구현된 동작과 다르다는 것에 주의하십시오. timeout 인자는 block 인자가 False 로 설정되면 실제적인 의미는 없고 무시됩니다. 록이 획득되면 True 를 돌려주고, 제한 시간 초과가 발생하면 False 를 돌려줍니다.

release()

록을 해제합니다. 이것은 원래 록을 획득한 프로세스나 스레드뿐만 아니라 모든 프로세스나 스레드에서 호출 할 수 있습니다.

동작은 threading.Lock.release() 와 같지만, 해제된 록에서 호출될 때 ValueError 가 발생한다는 점만 다릅니다.

class multiprocessing.RLock

재귀적 록 객체: threading.RLock 과 유사한 대응 물. 재귀적 록은 획득한 프로세스 또는 스레드에 의해 해제되어야 합니다. 일단 프로세스나 스레드가 재귀적 록을 획득하면, 같은 프로세스나 스레드가 블록 없이 다시 획득할 수 있습니다; 해당 프로세스나 스레드는 획득할 때마다 한 번 해제해야 합니다.

RLock 은 실제로 기본 컨텍스트로 초기화된 multiprocessing.synchronize.RLock 의 인스턴스를 반환하는 팩토리 함수입니다.

RLock 은 컨텍스트 관리자 프로토콜을 지원하므로 with 문에서 사용될 수 있습니다.

acquire(block=True, timeout=None)

블록하거나 블록하지 않는 방식으로 록을 획득합니다.

block 인자를 True 로 설정해서 호출하면, 록이 현재 프로세스나 스레드가 이미 획득한 상태가 아니면 록이 (어떤 프로세스나 스레드도 획득하지 않은) 록 해제 상태가 될 때까지 블록합니다. 이후에 현재 프로세스나 스레드가 (소유권이 아직 없는 경우) 록 소유권을 얻게 되며 록 내 재귀 수준이 1 증가하고 True 를 반환합니다. 이 첫 번째 인자의 동작에는, 인자의 이름부터 시작해서 threading.RLock.acquire() 구현과 비교되는 몇 가지 차이점이 있습니다.

block 인자를 False 로 설정해서 호출하면 블록하지 않습니다. 록이 이미 다른 프로세스나 스레드에 의해 획득되었으면 (그래서 소유하고 있으면), 현재 프로세스나 스레드는 소유권을 갖지 않으며 록 내 재귀 수준은 변경되지 않고 False 를 반환합니다. 록이 해제 상태에 있으면, 현재 프로세스 또는 스레드가 소유권을 가져오며 재귀 수준이 증가하고 True 를 반환합니다.

timeout 인자의 사용법과 동작은 Lock.acquire() 와 같습니다. timeout 의 이러한 동작 중 일부는 threading.RLock.acquire() 에서 구현된 동작과 다르다는 것에 주의하십시오.

release()

재귀 수준을 감소시키면서 록을 해제합니다. 감소 후에 재귀 수준이 0이면, 록을 해제 상태(어떤 프로세스나 스레드에도 소유되지 않음)로 재설정하고, 다른 프로세스나 스레드가 록이 해제될 때까지 기다리며 블록하고 있는 경우 해당 프로세스나 스레드 중 정확히 하나가 계속 진행하도록 허용합니다. 감소 후에 재귀 수준이 여전히 0이 아닌 경우, 록은 획득된 상태로 남고 호출한 프로세스나 스레드에 의해 소유됩니다.

호출한 프로세스나 스레드가 록을 소유하고 있을 때만 이 메서드를 호출하십시오. 이 메서드가 소유자가 아닌 프로세스나 스레드에 의해 호출되거나, 록이 해제 (소유되지 않은) 상태면 AssertionError 가 발생합니다. 이 상황에서 발생하는 예외 형은 threading.RLock.release() 에서 구현된 동작과 다릅니다.

class multiprocessing.Semaphore([value])

세마포어 객체: threading.Semaphore 와 유사한 대응 물.

대응 물과 한 가지 차이가 있습니다: acquire 메서드의 첫 번째 인자에 block 이라는 이름을 사용해서 Lock.acquire() 와의 일관성을 유지합니다.

참고

Mac OS X에서, sem_timedwait 가 지원되지 않기 때문에, acquire() 를 시간제한 있게 호출하면 잠자는 루프를 사용하여 해당 함수의 동작을 흉내 냅니다.

참고

메인 스레드가 BoundedSemaphore.acquire(), Lock.acquire(), RLock.acquire(), Semaphore.acquire(), Condition.acquire() 또는 Condition.wait() 호출 때문에 블록 된 동안, Ctrl-C 에 의해 만들어진 SIGINT 시그널이 도착하면, 호출이 즉시 중단되고 KeyboardInterrupt 가 발생합니다.

이것은 threading 의 동작과는 다른데, SIGINT는 해당 블로킹 호출이 진행되는 동안 무시됩니다.

참고

이 패키지의 기능 중 일부는 호스트 운영 체제의 작동하는 공유 세마포어 구현을 요구합니다. 그런 것이 없으면, multiprocessing.synchronize 모듈이 비활성화되고, 임포트하려고 하면 ImportError 를 일으킵니다. 자세한 내용은 bpo-3770 [https://bugs.python.org/issue?@action=redirect&bpo=3770]을 참조하십시오.

공유 ctypes 객체

자식 프로세스가 상속할 수 있는 공유 메모리를 사용하여 공유 객체를 만들 수 있습니다.

multiprocessing.Value(typecode_or_type, *args, lock=True)

공유 메모리에 할당된 ctypes 객체를 반환합니다. 기본적으로 반환 값은, 사실 객체에 대한 동기화 된 래퍼입니다. 객체 자체는 Value 의 value 어트리뷰트를 통해 접근 할 수 있습니다.

typecode_or_type 은 반환된 객체의 형을 결정합니다: ctypes 형이거나 array 모듈에 의해 사용되는 종류의 한 문자 typecode입니다. *args 는 형의 생성자로 전달됩니다.

lock 이 True (기본값) 면 값에 대한 액세스를 동기화하기 위해 새 재귀적 록 객체가 생성됩니다. lock 이 Lock 또는 RLock 객체인 경우, 이 값이 값에 대한 액세스를 동기화하는 데 사용됩니다. lock 이 False 면, 반환된 객체에 대한 액세스는 록에 의해 자동으로 보호되지 않으므로 “프로세스 안전” 하지 않습니다.

읽기와 쓰기를 포함하는 += 와 같은 연산은 원자 적(atomic)이지 않습니다. 따라서, 예를 들어, 공유 값을 원자 적으로 증가시키려면, 다음과 같이 하는 것으로는 충분하지 않습니다:

counter.value += 1

연관된 록이 재귀적이라고 가정하면 (기본적으로 그렇습니다), 대신 다음과 같이 할 수 있습니다

with counter.get_lock():
    counter.value += 1

lock 은 키워드 전용 인자입니다.

multiprocessing.Array(typecode_or_type, size_or_initializer, *, lock=True)

공유 메모리에서 할당된 ctypes 배열을 반환합니다. 기본적으로 반환 값은, 사실 배열에 대한 동기화 된 래퍼입니다.

typecode_or_type 은 반환된 배열의 요소의 형을 결정합니다: ctypes 형이거나 array 모듈에 의해 사용되는 종류의 한 문자 typecode입니다. size_or_initializer 가 정수면, 배열의 길이를 결정하고 배열은 0으로 초기화됩니다. 그렇지 않으면, size_or_initializer 는 배열을 초기화하는 데 사용되는 시퀀스고, 길이는 배열의 길이를 결정합니다.

lock 이 True (기본값) 면 값에 대한 액세스를 동기화하기 위해 새 록 객체가 생성됩니다. lock 이 Lock 또는 RLock 객체인 경우, 이 값이 값에 대한 액세스를 동기화하는 데 사용됩니다. lock 이 False 면, 반환된 객체에 대한 액세스는 록에 의해 자동으로 보호되지 않으므로 “프로세스 안전” 하지 않습니다.

lock 은 키워드 전용 인자입니다.

ctypes.c_char 의 배열은 value 와 raw 어트리뷰트를 가지고 있습니다. 이 어트리뷰트를 사용하여 문자열을 저장하고 꺼낼 수 있습니다.

multiprocessing.sharedctypes 모듈

multiprocessing.sharedctypes 모듈은 자식 프로세스에 의해 상속될 수 있는 공유 메모리에 ctypes 객체를 할당하는 기능을 제공합니다.

참고

공유 메모리에 포인터를 저장할 수는 있지만, 특정 프로세스의 주소 공간에 있는 위치를 참조하게 됩니다. 그러나 포인터는 두 번째 프로세스의 컨텍스트에서는 유효하지 않을 가능성이 커서, 두 번째 프로세스에서 포인터를 역 참조하려고 하면 충돌이 일어날 수 있습니다.

multiprocessing.sharedctypes.RawArray(typecode_or_type, size_or_initializer)

공유 메모리에 할당된 ctypes 배열을 반환합니다.

typecode_or_type 은 반환된 배열의 요소의 형을 결정합니다: ctypes 형이거나 array 모듈에 의해 사용되는 종류의 한 문자 typecode입니다. size_or_initializer 가 정수면, 배열의 길이를 결정하고 배열은 0으로 초기화됩니다. 그렇지 않으면, size_or_initializer 는 배열을 초기화하는 데 사용되는 시퀀스고, 길이는 배열의 길이를 결정합니다.

요소를 쓰고 읽는 것은 잠재적으로 원자 적이지 않습니다 – 액세스가 록을 사용하여 자동으로 동기화되기 원하면 Array()를 대신 사용하세요.

multiprocessing.sharedctypes.RawValue(typecode_or_type, *args)

공유 메모리에 할당된 ctypes 객체를 반환합니다.

typecode_or_type 은 반환된 객체의 형을 결정합니다: ctypes 형이거나 array 모듈에 의해 사용되는 종류의 한 문자 typecode입니다. *args 는 형의 생성자로 전달됩니다.

값을 쓰고 읽는 것은 잠재적으로 원자 적이지 않습니다 – 액세스가 록을 사용하여 자동으로 동기화되기 원하면 Value()를 대신 사용하세요.

ctypes.c_char 의 배열은 value 와 raw 어트리뷰트를 가지고 있습니다. 이 어트리뷰트를 사용하여 문자열을 저장하고 꺼낼 수 있습니다 – ctypes 설명서를 보십시오.

multiprocessing.sharedctypes.Array(typecode_or_type, size_or_initializer, *, lock=True)

lock 값에 따라, 날 ctypes 배열 대신 프로세스 안전한 동기화 래퍼가 반환될 수 있다는 것을 제외하고는 RawArray() 와 같습니다.

lock 이 True (기본값) 면 값에 대한 액세스를 동기화하기 위해 새 록 객체가 생성됩니다. lock 이 Lock 또는 RLock 객체인 경우, 이 값이 값에 대한 액세스를 동기화하는 데 사용됩니다. lock 이 False 면, 반환된 객체에 대한 액세스는 록에 의해 자동으로 보호되지 않으므로 “프로세스 안전” 하지 않습니다.

lock 은 키워드 전용 인자입니다.

multiprocessing.sharedctypes.Value(typecode_or_type, *args, lock=True)

lock 값에 따라, 날 ctypes 객체 대신 프로세스 안전한 동기화 래퍼가 반환될 수 있다는 것을 제외하고는 RawValue() 와 같습니다.

lock 이 True (기본값) 면 값에 대한 액세스를 동기화하기 위해 새 록 객체가 생성됩니다. lock 이 Lock 또는 RLock 객체인 경우, 이 값이 값에 대한 액세스를 동기화하는 데 사용됩니다. lock 이 False 면, 반환된 객체에 대한 액세스는 록에 의해 자동으로 보호되지 않으므로 “프로세스 안전” 하지 않습니다.

lock 은 키워드 전용 인자입니다.

multiprocessing.sharedctypes.copy(obj)

공유 메모리에서 할당된 ctypes 객체를 반환합니다. 이 객체는 ctypes 객체 obj 의 복사본입니다.

multiprocessing.sharedctypes.synchronized(obj[, lock])

lock 을 사용하여 액세스를 동기화하는 ctypes 객체에 대한 프로세스 안전한 래퍼 객체를 반환합니다. lock 이 None (기본값)이면 multiprocessing.RLock 객체가 자동으로 생성됩니다.

동기화 래퍼는 래핑 된 객체의 메서드 외에도 두 개의 메서드를 더 갖습니다: get_obj() 는 래핑 된 객체를 반환하고, get_lock() 은 동기화에 사용되는 록 객체를 반환합니다.

래퍼를 통해 ctypes 객체에 액세스하는 것은, 날 ctypes 객체에 액세스하는 것보다 훨씬 느릴 수 있습니다.

버전 3.5에서 변경: 동기화된 객체는 컨텍스트 관리자 프로토콜을 지원합니다.

아래 표는 공유 메모리에 공유 ctypes 객체를 만드는 문법과 일반적인 ctypes 문법을 비교합니다. (표에서 MyStruct 는 ctypes.Structure 의 서브 클래스입니다.)

ctypes

type을 사용하는 공유 ctypes

typecode를 사용하는 공유 ctypes

c_double(2.4)

RawValue(c_double, 2.4)

RawValue(‘d’, 2.4)

MyStruct(4, 6)

RawValue(MyStruct, 4, 6)

(c_short * 7)()

RawArray(c_short, 7)

RawArray(‘h’, 7)

(c_int * 3)(9, 2, 8)

RawArray(c_int, (9, 2, 8))

RawArray(‘i’, (9, 2, 8))

다음은 자식 프로세스가 여러 ctypes 객체를 수정하는 예입니다:

from multiprocessing import Process, Lock
from multiprocessing.sharedctypes import Value, Array
from ctypes import Structure, c_double

class Point(Structure):
    _fields_ = [('x', c_double), ('y', c_double)]

def modify(n, x, s, A):
    n.value **= 2
    x.value **= 2
    s.value = s.value.upper()
    for a in A:
        a.x **= 2
        a.y **= 2

if __name__ == '__main__':
    lock = Lock()

    n = Value('i', 7)
    x = Value(c_double, 1.0/3.0, lock=False)
    s = Array('c', b'hello world', lock=lock)
    A = Array(Point, [(1.875,-6.25), (-5.75,2.0), (2.375,9.5)], lock=lock)

    p = Process(target=modify, args=(n, x, s, A))
    p.start()
    p.join()

    print(n.value)
    print(x.value)
    print(s.value)
    print([(a.x, a.y) for a in A])

인쇄되는 결과는 이렇습니다

49
0.1111111111111111
HELLO WORLD
[(3.515625, 39.0625), (33.0625, 4.0), (5.640625, 90.25)]

관리자

관리자는 서로 다른 컴퓨터에서 실행되는 프로세스 간에 네트워크를 통해 공유하는 것을 포함하여 서로 다른 프로세스 간에 공유할 수 있는 데이터를 만드는 방법을 제공합니다. 관리자 객체는 공유 객체 를 관리하는 서버 프로세스를 제어합니다. 다른 프로세스는 프락시를 사용하여 공유 객체에 액세스 할 수 있습니다.

multiprocessing.Manager()

프로세스 간에 객체를 공유하는 데 사용할 수 있는 시작된 SyncManager 객체를 반환합니다. 반환된 관리자 객체는 생성된 자식 프로세스에 해당하며 공유 객체를 만들고 해당 프락시를 반환하는 메서드가 있습니다.

관리자 프로세스는 가비지 수집되거나 상위 프로세스가 종료되자마자 종료됩니다. 관리자 클래스는 multiprocessing.managers 모듈에 정의되어 있습니다 :

class multiprocessing.managers.BaseManager([address[, authkey]])

BaseManager 객체를 만듭니다.

일단 생성되면 관리자 객체가 시작된 관리자 프로세스를 참조하게 하려고 start() 또는 get_server().serve_forever() 를 호출해야 합니다.

address 는 관리자 프로세스가 새 연결을 리슨하는 주소입니다. address 가 None 이면 임의의 것이 선택됩니다.

authkey 는 서버 프로세스로 들어오는 연결의 유효성을 검사하는 데 사용되는 인증 키입니다. authkey 가 None 이면 current_process().authkey 가 사용됩니다. 그렇지 않으면 authkey 가 사용되며 바이트열이어야 합니다.

start([initializer[, initargs]])

관리자를 시작시키기 위해 서브 프로세스를 시작합니다. initializer 가 None 이 아닌 경우, 서브 프로세스는 시작할 때 initializer(*initargs) 를 호출합니다.

get_server()

Manager의 제어를 받는 실제 서버를 나타내는 Server 객체를 반환합니다. Server 객체는 serve_forever() 메서드를 지원합니다:

>>> from multiprocessing.managers import BaseManager
>>> manager = BaseManager(address=('', 50000), authkey=b'abc')
>>> server = manager.get_server()
>>> server.serve_forever()

Server 는 추가로 address 어트리뷰트를 가지고 있습니다.

connect()

지역 관리자 객체를 원격 관리자 프로세스에 연결합니다:

>>> from multiprocessing.managers import BaseManager
>>> m = BaseManager(address=('127.0.0.1', 50000), authkey=b'abc')
>>> m.connect()

shutdown()

관리자가 사용하는 프로세스를 중지합니다. start()를 사용하여 서버 프로세스를 시작한 경우에만 사용할 수 있습니다.

여러 번 호출 될 수 있습니다.

register(typeid[, callable[, proxytype[, exposed[, method_to_typeid[, create_method]]]]])

관리자 클래스에 형이나 콜러블을 등록하는데 사용할 수 있는 클래스 메서드.

typeid 는 특정 형의 공유 객체를 식별하는 데 사용되는 “형 식별자” 입니다. 문자열이어야 합니다.

callable 은 이 형 식별자에 대한 객체를 만드는 데 사용되는 콜러블 객체입니다. 관리자 인스턴스가 connect() 메서드를 사용하여 서버에 연결되거나, create_method 인자가 False 면 None 으로 남겨 둘 수 있습니다.

proxytype 은, 이 typeid 의 공유 객체의 프락시를 만드는 데 사용되는 BaseProxy 의 서브 클래스입니다. None 이면 프락시 클래스가 자동으로 생성됩니다.

exposed 는 이 typeid에 대한 프락시가 BaseProxy._callmethod() 를 사용하여 액세스 할 수 있도록 허용해야 하는 메서드 이름의 시퀀스를 지정하는 데 사용됩니다. (만약 exposed 가 None 이면, 존재하는 경우, proxytype._exposed_ 가 대신 사용됩니다.) exposed 리스트가 지정되지 않은 경우, 공유 객체의 모든 “공용 메서드” 에 액세스 할 수 있습니다. (여기서 “공용 메서드” 는 __call__() 메서드가 있고 그 이름이 '_' 로 시작하지 않는 어트리뷰트를 의미합니다.)

method_to_typeid 는 프락시를 반환해야 하는 노출된 메서드의 반환형을 지정하는 데 사용되는 매핑입니다. 메서드 이름을 typeid 문자열로 매핑합니다. (만일 method_to_typeid 가 None 이면, 존재한다면, proxytype._method_to_typeid_ 가 대신 사용됩니다.) 메서드의 이름이 이 매핑의 키가 아니거나 매핑이 None 이면, 메서드에 의해 반환된 객체는 값으로 복사됩니다.

create_method 는 이름이 typeid 인 메서드를 만들어야 하는지를 결정합니다. 이 메서드는 서버 프로세스에 새 공유 객체를 만들고 프락시를 반환하도록 지시하는 데 사용될 수 있습니다. 기본적으로 True 입니다.

BaseManager 인스턴스는 읽기 전용 프로퍼티를 하나 가지고 있습니다:

address

관리자가 사용하는 주소.

버전 3.3에서 변경: 관리자 객체는 컨텍스트 관리 프로토콜을 지원합니다 – 컨텍스트 관리자 형를 보세요. __enter__() 는 서버 프로세스를 시작하고 (아직 시작하지 않았다면), 관리자 객체를 반환합니다. __exit__() 는 shutdown()을 호출합니다.

이전 버전에서 __enter__() 는 관리자의 서버 프로세스가 아직 시작되지 않았을 때 시작시키지 않았습니다.

class multiprocessing.managers.SyncManager

프로세스의 동기화에 사용할 수 있는 BaseManager 의 서브 클래스입니다. 이 형의 객체는 multiprocessing.Manager() 에 의해 반환됩니다.

이 클래스의 메서드는 여러 프로세스에서 동기화 할 수 있도록 일반적으로 사용되는 많은 데이터형을 생성하고 프락시 객체를 반환합니다. 특히 공유 리스트와 딕셔너리가 포함됩니다.

Barrier(parties[, action[, timeout]])

공유 threading.Barrier 객체를 생성하고 프락시를 반환합니다.

버전 3.3에 추가.

BoundedSemaphore([value])

공유 threading.BoundedSemaphore 객체를 생성하고 프락시를 반환합니다.

Condition([lock])

공유 threading.Condition 객체를 생성하고 프락시를 반환합니다.

lock 이 제공되면 threading.Lock 또는 threading.RLock 객체에 대한 프락시여야 합니다.

버전 3.3에서 변경: wait_for() 메서드가 추가되었습니다.

Event()

공유 threading.Event 객체를 생성하고 프락시를 반환합니다.

Lock()

공유 threading.Lock 객체를 생성하고 프락시를 반환합니다.

Namespace()

공유 Namespace 객체를 생성하고 프락시를 반환합니다.

Queue([maxsize])

공유 queue.Queue 객체를 생성하고 프락시를 반환합니다.

RLock()

공유 threading.RLock 객체를 생성하고 프락시를 반환합니다.

Semaphore([value])

공유 threading.Semaphore 객체를 생성하고 프락시를 반환합니다.

Array(typecode, sequence)

배열을 만들고 프락시를 반환합니다.

Value(typecode, value)

쓰기 가능한 value 어트리뷰트를 가진 객체를 생성하고 프락시를 반환합니다.

dict()

dict(mapping)

dict(sequence)

공유 dict 객체를 생성하고 프락시를 반환합니다.

list()

list(sequence)

공유 list 객체를 생성하고 프락시를 반환합니다.

버전 3.6에서 변경: 공유 객체는 중첩될 수 있습니다. 예를 들어, 공유 리스트와 같은 공유 컨테이너 객체는, SyncManager 에 의해 모두 관리되고 동기화되는 다른 공유 객체를 포함 할 수 있습니다.

class multiprocessing.managers.Namespace

SyncManager 로 등록 할 수 있는 형입니다.

이름 공간 객체에는 공용 메서드가 없지만, 쓰기 가능한 어트리뷰트가 있습니다. repr 은 그것의 어트리뷰트 값을 보여줍니다.

그러나, 이름 공간 객체의 프락시를 사용할 때, '_' 로 시작하는 어트리뷰트는 프락시의 어트리뷰트가 되며 참조 대상의 어트리뷰트가 아닙니다:

>>> manager = multiprocessing.Manager()
>>> Global = manager.Namespace()
>>> Global.x = 10
>>> Global.y = 'hello'
>>> Global._z = 12.3    # this is an attribute of the proxy
>>> print(Global)
Namespace(x=10, y='hello')

사용자 정의 관리자

자신만의 관리자를 만들려면, BaseManager 의 서브 클래스를 만들고 register() 클래스 메서드를 사용하여 새로운 형이나 콜러블을 관리자 클래스에 등록합니다. 예를 들면:

from multiprocessing.managers import BaseManager

class MathsClass:
    def add(self, x, y):
        return x + y
    def mul(self, x, y):
        return x * y

class MyManager(BaseManager):
    pass

MyManager.register('Maths', MathsClass)

if __name__ == '__main__':
    with MyManager() as manager:
        maths = manager.Maths()
        print(maths.add(4, 3))         # prints 7
        print(maths.mul(7, 8))         # prints 56

원격 관리자 사용하기

한 기계에서 관리자 서버를 실행하고 다른 기계의 클라이언트가 관리자 서버를 사용하도록 할 수 있습니다 (관련된 방화벽이 허용한다고 가정합니다).

다음 명령을 실행하면 원격 클라이언트가 액세스 할 수 있는 단일 공유 큐를 위한 서버가 만들어집니다:

>>> from multiprocessing.managers import BaseManager
>>> from queue import Queue
>>> queue = Queue()
>>> class QueueManager(BaseManager): pass
>>> QueueManager.register('get_queue', callable=lambda:queue)
>>> m = QueueManager(address=('', 50000), authkey=b'abracadabra')
>>> s = m.get_server()
>>> s.serve_forever()

한 클라이언트는 다음과 같이 서버에 액세스 할 수 있습니다:

>>> from multiprocessing.managers import BaseManager
>>> class QueueManager(BaseManager): pass
>>> QueueManager.register('get_queue')
>>> m = QueueManager(address=('foo.bar.org', 50000), authkey=b'abracadabra')
>>> m.connect()
>>> queue = m.get_queue()
>>> queue.put('hello')

또 다른 클라이언트도 사용할 수 있습니다:

>>> from multiprocessing.managers import BaseManager
>>> class QueueManager(BaseManager): pass
>>> QueueManager.register('get_queue')
>>> m = QueueManager(address=('foo.bar.org', 50000), authkey=b'abracadabra')
>>> m.connect()
>>> queue = m.get_queue()
>>> queue.get()
'hello'

지역 프로세스 역시, 위의 클라이언트가 원격으로 액세스하는 코드를 사용하여 같은 큐에 액세스 할 수 있습니다:

>>> from multiprocessing import Process, Queue
>>> from multiprocessing.managers import BaseManager
>>> class Worker(Process):
...     def __init__(self, q):
...         self.q = q
...         super(Worker, self).__init__()
...     def run(self):
...         self.q.put('local hello')
...
>>> queue = Queue()
>>> w = Worker(queue)
>>> w.start()
>>> class QueueManager(BaseManager): pass
...
>>> QueueManager.register('get_queue', callable=lambda: queue)
>>> m = QueueManager(address=('', 50000), authkey=b'abracadabra')
>>> s = m.get_server()
>>> s.serve_forever()

프락시 객체

프락시는 (아마도) 다른 프로세스에 있는 공유 객체를 가리키는 객체입니다. 공유 객체는 프락시의 지시 대상 이라고 합니다. 여러 프락시 객체는 같은 지시 대상을 가질 수 있습니다.

프락시 객체에는 지시 대상의 해당 메서드를 호출하는 메서드가 있습니다 (그러나 지시 대상의 모든 메서드가 반드시 프락시를 통해 사용할 수 있는 것은 아닙니다). 이런 식으로, 프락시는 지시 대상처럼 사용될 수 있습니다:

>>> from multiprocessing import Manager
>>> manager = Manager()
>>> l = manager.list([i*i for i in range(10)])
>>> print(l)
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> print(repr(l))
<ListProxy object, typeid 'list' at 0x...>
>>> l[4]
16
>>> l[2:5]
[4, 9, 16]

프락시에 str() 을 적용하면 지시 대상의 표현이 반환되는 반면, repr() 을 적용하면 프락시의 표현이 반환됩니다.

프락시 객체의 중요한 특징은, 피클 가능해서 프로세스 간에 전달될 수 있다는 것입니다. 지시 대상은 프락시 객체를 포함 할 수 있습니다. 이것은 관리된 리스트, 딕셔너리 및 다른 프락시 객체 의 중첩을 허용합니다:

>>> a = manager.list()
>>> b = manager.list()
>>> a.append(b)         # referent of a now contains referent of b
>>> print(a, b)
[<ListProxy object, typeid 'list' at ...>] []
>>> b.append('hello')
>>> print(a[0], b)
['hello'] ['hello']

비슷하게, 딕셔너리와 리스트 프락시는 서로 중첩될 수 있습니다:

>>> l_outer = manager.list([ manager.dict() for i in range(2) ])
>>> d_first_inner = l_outer[0]
>>> d_first_inner['a'] = 1
>>> d_first_inner['b'] = 2
>>> l_outer[1]['c'] = 3
>>> l_outer[1]['z'] = 26
>>> print(l_outer[0])
{'a': 1, 'b': 2}
>>> print(l_outer[1])
{'c': 3, 'z': 26}

(프락시가 아닌) 표준 list 또는 dict 객체가 지시 대상에 포함되어있는 경우, 이 가변 값들에 대한 수정은 관리자를 통해 전파되지 않습니다. 포함된 값이 언제 수정되는지 프락시가 알 방법이 없기 때문입니다. 그러나 컨테이너 프락시에 값을 저장하는 것(프락시 객체의 __setitem__ 을 호출합니다)은 관리자를 통해 전파되므로, 그 항목을 효과적으로 수정하기 위해, 수정된 값을 컨테이너 프락시에 다시 대입할 수 있습니다:

# create a list proxy and append a mutable object (a dictionary)
lproxy = manager.list()
lproxy.append({})
# now mutate the dictionary
d = lproxy[0]
d['a'] = 1
d['b'] = 2
# at this point, the changes to d are not yet synced, but by
# updating the dictionary, the proxy is notified of the change
lproxy[0] = d

이 접근법은 아마도 대부분의 사용 사례에서 중첩된 프락시 객체를 사용하는 것보다 불편하지만, 동기화에 대한 제어 수준을 보여줍니다.

참고

multiprocessing 의 프락시 형은 값으로 비교하는 것을 지원하지 않습니다. 그래서, 예를 들어, 이런 결과를 얻습니다:

>>> manager.list([1,2,3]) == [1,2,3]
False

비교할 때는 지시 대상의 사본을 대신 사용해야 합니다.

class multiprocessing.managers.BaseProxy

프락시 객체는 BaseProxy 의 서브 클래스의 인스턴스입니다.

_callmethod(methodname[, args[, kwds]])

프락시의 지시 대상 메서드를 호출하고 결과를 반환합니다.

proxy 가 프락시이고, 그 지시 대상이 obj 면, 표현식

proxy._callmethod(methodname, args, kwds)

은 표현식

getattr(obj, methodname)(*args, **kwds)

을 관리자 프로세스에서 평가합니다.

반환된 값은 호출 결과의 복사본이거나 새 공유 객체에 대한 프락시입니다 – BaseManager.register() 의 method_to_typeid 인자에 대한 설명서를 보십시오.

호출 때문에 예외가 발생하면, _callmethod() 가 다시 일으킵니다. 관리자 프로세스에서 다른 예외가 발생하면 RemoteError 예외로 변환되어 _callmethod() 가 일으킵니다.

특히, methodname 이 노출되지 않았으면 예외가 발생합니다.

_callmethod() 사용법의 예:

>>> l = manager.list(range(10))
>>> l._callmethod('__len__')
10
>>> l._callmethod('__getitem__', (slice(2, 7),)) # equivalent to l[2:7]
[2, 3, 4, 5, 6]
>>> l._callmethod('__getitem__', (20,))          # equivalent to l[20]
Traceback (most recent call last):
...
IndexError: list index out of range

_getvalue()

지시 대상의 복사본을 반환합니다.

지시 대상이 피클 가능하지 않으면 예외가 발생합니다.

__repr__()

프락시 객체의 표현을 반환합니다.

__str__()

지시 대상의 표현을 반환합니다.

정리

프락시 객체는 weakref 콜백을 사용해서 가비지 수집 시 자신의 지시 대상을 소유한 관리자에서 자신을 등록 취소합니다.

더는 참조하는 프락시가 없는 경우 공유 객체는 관리자 프로세스에서 삭제됩니다.

프로세스 풀

Pool 클래스를 사용하여, 제출된 작업을 수행할 프로세스 풀을 만들 수 있습니다.

class multiprocessing.pool.Pool([processes[, initializer[, initargs[, maxtasksperchild[, context]]]]])

작업을 제출할 수 있는 작업자 프로세스 풀을 제어하는 프로세스 풀 객체. 제한 시간과 콜백을 사용하는 비동기 결과를 지원하고 병렬 map 구현을 제공합니다.

processes 는 사용할 작업자 프로세스 수입니다. processes 가 None 이면 os.cpu_count() 에 의해 반환되는 수가 사용됩니다.

initializer 가 None 이 아니면, 각 작업자 프로세스는 시작할 때 initializer(*initargs) 를 호출합니다.

maxtasksperchild 는, 사용되지 않는 자원을 해제할 수 있도록, 작업 프로세스가 종료되고 새 작업 프로세스로 교체되기 전에 완료할 수 있는 작업 수입니다. 기본 maxtasksperchild 는 None 입니다. 이는 작업자 프로세스가 풀만큼 오래감을 의미합니다.

context 는 작업자 프로세스를 시작하는 데 사용되는 컨텍스트를 지정하는 데 사용할 수 있습니다. 보통 풀은 multiprocessing.Pool() 또는 컨텍스트 객체의 Pool() 메서드를 사용하여 생성됩니다. 두 경우 모두 context 가 적절하게 설정됩니다.

풀 객체의 메서드는 풀을 생성한 프로세스에 의해서만 호출되어야 합니다.

경고

multiprocessing.pool objects have internal resources that need to be properly managed (like any other resource) by using the pool as a context manager or by calling close() and terminate() manually. Failure to do this can lead to the process hanging on finalization.

Note that is not correct to rely on the garbage colletor to destroy the pool as CPython does not assure that the finalizer of the pool will be called (see object.__del__() for more information).

버전 3.2에 추가: maxtasksperchild

버전 3.4에 추가: context

참고

Pool 내의 작업자 프로세스는 일반적으로 Pool의 작업 큐의 전체 지속 기간 지속합니다. 작업자가 잡은 자원을 해제하기 위해 다른 시스템 (가령 Apache, mod_wsgi 등)에서 흔히 사용되는 패턴은, 풀 내에 있는 작업자가 종료되고 새 프로세스가 스폰 되어 예전 것을 교체하기 전에 일정한 분량의 작업만 완료하도록 하는 것입니다. Pool 의 maxtasksperchild 인자는 이 기능을 일반 사용자에게 노출합니다.

apply(func[, args[, kwds]])

인자 args 및 키워드 인자 kwds 를 사용하여 func 를 호출합니다. 결과가 준비될 때까지 블록 됩니다. 이 블록 때문에, apply_async() 가 병렬로 작업을 수행하는 데 더 적합합니다. 또한 func 는 풀의 작업자 중 하나에서만 실행됩니다.

apply_async(func[, args[, kwds[, callback[, error_callback]]]])

결과 객체를 반환하는 apply() 메서드의 변형입니다.

callback 이 지정되면 단일 인자를 받아들이는 콜러블이어야 합니다. 결과가 준비되면 callback 을 이 결과를 인자로 호출합니다. 실패한 결과면 error_callback 이 대신 적용됩니다.

error_callback 이 지정되면 단일 인자를 허용하는 콜러블이어야 합니다. 대상 함수가 실패하면, error_callback 이 예외 인스턴스를 인자로 호출됩니다.

콜백은 즉시 완료되어야 합니다. 그렇지 않으면 결과를 처리하는 스레드가 블록 됩니다.

map(func, iterable[, chunksize])

A parallel equivalent of the map() built-in function (it supports only one iterable argument though, for multiple iterables see starmap()). It blocks until the result is ready.

이 메서드는 iterable을 여러 묶음으로 잘라서 별도의 작업으로 프로세스 풀에 제출합니다. 이러한 묶음의 (대략적인) 크기는 chunksize 를 양의 정수로 설정하여 지정할 수 있습니다.

매우 긴 이터러블은 높은 메모리 사용을 유발할 수 있습니다. 더 나은 효율성을 위해, 명시적인 chunksize 옵션으로 imap()이나 imap_unordered()를 사용하는 것을 고려하십시오.

map_async(func, iterable[, chunksize[, callback[, error_callback]]])

결과 객체를 반환하는 map() 메서드의 변형입니다.

callback 이 지정되면 단일 인자를 받아들이는 콜러블이어야 합니다. 결과가 준비되면 callback 을 이 결과를 인자로 호출합니다. 실패한 결과면 error_callback 이 대신 적용됩니다.

error_callback 이 지정되면 단일 인자를 허용하는 콜러블이어야 합니다. 대상 함수가 실패하면, error_callback 이 예외 인스턴스를 인자로 호출됩니다.

콜백은 즉시 완료되어야 합니다. 그렇지 않으면 결과를 처리하는 스레드가 블록 됩니다.

imap(func, iterable[, chunksize])

map() 의 느긋한 버전.

chunksize 인자는 map() 메서드에서 사용된 인자와 같습니다. 매우 긴 iterable의 경우 chunksize 에 큰 값을 사용하면 기본값 1 을 사용하는 것보다 작업을 많이 빠르게 완료 할 수 있습니다.

또한 chunksize 가 1 이면 imap() 메서드에 의해 반환된 이터레이터의 next() 메서드는 선택적 timeout 매개 변수를 가집니다: next(timeout) 은 결과가 timeout 초 내에 반환될 수 없는 경우 multiprocessing.TimeoutError 를 발생시킵니다.

imap_unordered(func, iterable[, chunksize])

imap()과 같지만, 반환된 이터레이터가 제공하는 결과의 순서가 임의적인 것으로 간주하여야 합니다. (단 하나의 작업자 프로세스가 있는 경우에만 순서가 “올바름” 이 보장됩니다.

starmap(func, iterable[, chunksize])

map()과 같지만, iterable 의 요소가 인자로 언팩 될 이터러블일 것으로 기대합니다.

따라서 iterable 이 [(1,2), (3, 4)] 미면 결과는 [func(1,2), func(3,4)] 가 됩니다.

버전 3.3에 추가.

starmap_async(func, iterable[, chunksize[, callback[, error_callback]]])

starmap() 과 map_async() 의 조합으로 이터러블의 iterable 을 이터레이트하고 이터러블을 언팩해서 func 를 호출합니다. 결과 객체를 반환합니다.

버전 3.3에 추가.

close()

더는 작업이 풀에 제출되지 않도록 합니다. 모든 작업이 완료되면 작업자 프로세스가 종료됩니다.

terminate()

계류 중인 작업을 완료하지 않고 즉시 작업자 프로세스를 중지합니다. 풀 객체가 가비지 수집될 때 terminate() 가 즉시 호출됩니다.

join()

작업자 프로세스가 종료될 때까지 기다립니다. join() 호출 전에 반드시 close() 나 terminate()를 호출해야합니다 .

버전 3.3에 추가: 풀 객체는 이제 컨텍스트 관리 프로토콜을 지원합니다 – 컨텍스트 관리자 형를 보십시오. __enter__() 는 풀 객체를 반환하고, __exit__() 는 terminate()를 호출합니다.

class multiprocessing.pool.AsyncResult

Pool.apply_async()와 Pool.map_async() 에 의해 반환되는 결과의 클래스.

get([timeout])

결과가 도착할 때 반환합니다. timeout 이 None 이 아니고 결과가 timeout 초 내에 도착하지 않으면 multiprocessing.TimeoutError 가 발생합니다. 원격 호출이 예외를 발생시키는 경우 해당 예외는 get() 에 의해 다시 발생합니다.

wait([timeout])

결과가 사용 가능할 때까지 또는 timeout 초가 지날 때까지 기다립니다.

ready()

호출이 완료했는지를 돌려줍니다.

successful()

Return whether the call completed without raising an exception. Will raise ValueError if the result is not ready.

다음 예제는 풀 사용 방법을 보여줍니다.:

from multiprocessing import Pool
import time

def f(x):
    return x*x

if __name__ == '__main__':
    with Pool(processes=4) as pool:         # start 4 worker processes
        result = pool.apply_async(f, (10,)) # evaluate "f(10)" asynchronously in a single process
        print(result.get(timeout=1))        # prints "100" unless your computer is *very* slow

        print(pool.map(f, range(10)))       # prints "[0, 1, 4,..., 81]"

        it = pool.imap(f, range(10))
        print(next(it))                     # prints "0"
        print(next(it))                     # prints "1"
        print(it.next(timeout=1))           # prints "4" unless your computer is *very* slow

        result = pool.apply_async(time.sleep, (10,))
        print(result.get(timeout=1))        # raises multiprocessing.TimeoutError

리스너와 클라이언트

보통 프로세스 간 메시지 전달은 큐를 사용하거나 Pipe() 가 반환하는 Connection 객체를 사용하여 수행됩니다.

그러나, multiprocessing.connection 모듈은 약간의 추가적인 유연성을 허용합니다. 기본적으로 소켓이나 윈도우의 이름있는 파이프를 다루는 높은 수준의 메시지 지향 API를 제공합니다. 또한 hmac 모듈을 사용한 다이제스트 인증 과 다중 연결을 동시에 폴링하는 방법을 지원합니다.

multiprocessing.connection.deliver_challenge(connection, authkey)

무작위로 생성된 메시지를 연결의 다른 쪽 끝으로 보내고 응답을 기다립니다.

응답이 authkey 를 키로 사용하는 메시지의 다이제스트와 일치하면 환영 메시지가 연결의 다른 끝으로 전송됩니다. 그렇지 않으면 AuthenticationError 가 발생합니다.

multiprocessing.connection.answer_challenge(connection, authkey)

메시지를 수신하고, authkey 를 키로 사용하여 메시지의 다이제스트를 계산한 다음, 다이제스트를 다시 보냅니다.

환영 메시지가 수신되지 않으면, AuthenticationError 가 발생합니다.

multiprocessing.connection.Client(address[, family[, authkey]])

주소 address 를 사용하는 리스너에 대한 연결을 설정하려고 시도하고, Connection을 반환합니다.

연결 유형은 family 인자에 의해 결정되지만, 일반적으로 address 형식에서 유추 할 수 있으므로 일반적으로 생략 할 수 있습니다. (주소 형식를 참조하세요)

authkey 가 주어지고 None이 아니라면, 바이트열이어야 하며 HMAC 기반 인증 챌린지의 비밀 키로 사용됩니다. authkey 가 None이면, 인증이 수행되지 않습니다. 인증이 실패하면 AuthenticationError 가 발생합니다. 인증 키를 보세요.

class multiprocessing.connection.Listener([address[, family[, backlog[, authkey]]]])

연결을 ‘리스닝’ 하는 바인드된 소켓이나 윈도우의 이름있는 파이프에 대한 래퍼입니다.

address 는 리스너 객체의 바인드된 소켓이나 이름있는 파이프가 사용할 주소입니다.

참고

주소가 ‘0.0.0.0’ 인 경우, 주소는 윈도우에서 연결 가능한 끝점이 아닙니다. 연결할 수 있는 끝점이 필요한 경우, ‘127.0.0.1’을 사용해야 합니다.

family 는 사용할 소켓(또는 이름있는 파이프)의 유형입니다. 문자열 'AF_INET' (TCP 소켓), 'AF_UNIX' (유닉스 도메인 소켓), 'AF_PIPE' (윈도우 이름있는 파이프) 중 하나일 수 있습니다. 이 중 오직 첫 번째 것만 항상 사용할 수 있음이 보장됩니다. family 가 None 이면, address 의 형식으로부터 유추됩니다. address 역시 None 이면, 기본값이 선택됩니다. 이 기본값은 사용 가능한 것 중 가장 빠른 것으로 기대되는 것입니다. 주소 형식를 참조하세요. family 가 'AF_UNIX' 이고 주소가 None 이면, 소켓은 tempfile.mkstemp() 를 사용하여 만들어진 비공개 임시 디렉터리에 생성됩니다.

리스너 객체가 소켓을 사용하면, backlog (기본적으로 1) 는 소켓이 바인드되면 소켓의 listen() 메서드에 전달됩니다.

authkey 가 주어지고 None이 아니라면, 바이트열이어야 하며 HMAC 기반 인증 챌린지의 비밀 키로 사용됩니다. authkey 가 None이면, 인증이 수행되지 않습니다. 인증이 실패하면 AuthenticationError 가 발생합니다. 인증 키를 보세요.

accept()

리스너 객체의 바인드된 소켓 또는 이름있는 파이프에 대한 연결을 수락하고 Connection 객체를 반환합니다. 인증이 시도되고 실패하면 AuthenticationError 가 발생합니다.

close()

리스너 객체의 바운드된 소켓 또는 이름있는 파이프를 닫습니다. 리스너가 가비지 수집될 때 자동으로 호출됩니다. 그러나 명시적으로 호출하는 것이 좋습니다.

리스너 객체는 다음과 같은 읽기 전용 프로퍼티를 가집니다:

address

리스너 객체에서 사용 중인 주소.

last_accepted

마지막으로 수락한 연결이 온 주소. 없으면 None 입니다.

버전 3.3에 추가: 리스너 객체는 컨텍스트 관리 프로토콜을 지원합니다 – 컨텍스트 관리자 형를 보세요. __enter__() 는 리스너 객체를 반환하고, __exit__() 는 close()를 호출합니다.

multiprocessing.connection.wait(object_list, timeout=None)

object_list 에 있는 객체가 준비될 때까지 기다립니다. object_list 에 있는 객체 중 준비된 것들의 리스트를 반환합니다. timeout 이 float면, 호출이 최대 지정된 초만큼 블록 됩니다. timeout 이 None 이면, 시간제한 없이 블록 됩니다. 음수 timeout은 0과 같습니다.

유닉스와 윈도우에서 모두, object_list 에 등장할 수 있는 객체는 다음과 같습니다.

읽기 가능한 Connection 객체;

연결되고 읽기 가능한 socket.socket 객체; 또는

Process 객체의 sentinel 어트리뷰트.

연결이나 소켓 객체는 읽을 수 있는 데이터가 있거나 반대편 끝이 닫히면 준비가 됩니다.

유닉스: wait(object_list, timeout) 은 select.select(object_list, [], [], timeout)과 거의 동등합니다. 차이점은, select.select() 가 시그널에 의해 인터럽트 되면, 에러 번호 EINTR 로 OSError 를 일으키지만, wait() 는 예외를 일으키지 않는다는 것입니다.

윈도우: object_list 의 항목은 (Win32 함수 WaitForMultipleObjects() 의 설명서에서 사용된 정의에 따라) 대기 가능한 정수 핸들이거나, 소켓 핸들이나 파이프 핸들을 반환하는 fileno() 메서드가 있는 개체입니다. (파이프 핸들과 소켓 핸들은 대기 가능한 핸들이 아님 에 유의하십시오.)

버전 3.3에 추가.

예제

다음 서버 코드는 인증 키로 'secret password' 를 사용하는 리스너를 만듭니다. 그런 다음 연결을 기다리고 어떤 데이터를 클라이언트로 보냅니다.:

from multiprocessing.connection import Listener
from array import array

address = ('localhost', 6000)     # family is deduced to be 'AF_INET'

with Listener(address, authkey=b'secret password') as listener:
    with listener.accept() as conn:
        print('connection accepted from', listener.last_accepted)

        conn.send([2.25, None, 'junk', float])

        conn.send_bytes(b'hello')

        conn.send_bytes(array('i', [42, 1729]))

다음 코드는 서버에 연결하고 서버로부터 어떤 데이터를 받습니다:

from multiprocessing.connection import Client
from array import array

address = ('localhost', 6000)

with Client(address, authkey=b'secret password') as conn:
    print(conn.recv())                  # => [2.25, None, 'junk', float]

    print(conn.recv_bytes())            # => 'hello'

    arr = array('i', [0, 0, 0, 0, 0])
    print(conn.recv_bytes_into(arr))    # => 8
    print(arr)                          # => array('i', [42, 1729, 0, 0, 0])

다음 코드는 wait() 을 사용하여 여러 프로세스로부터 오는 메시지를 한 번에 기다립니다:

import time, random
from multiprocessing import Process, Pipe, current_process
from multiprocessing.connection import wait

def foo(w):
    for i in range(10):
        w.send((i, current_process().name))
    w.close()

if __name__ == '__main__':
    readers = []

    for i in range(4):
        r, w = Pipe(duplex=False)
        readers.append(r)
        p = Process(target=foo, args=(w,))
        p.start()
        # We close the writable end of the pipe now to be sure that
        # p is the only process which owns a handle for it.  This
        # ensures that when p closes its handle for the writable end,
        # wait() will promptly report the readable end as being ready.
        w.close()

    while readers:
        for r in wait(readers):
            try:
                msg = r.recv()
            except EOFError:
                readers.remove(r)
            else:
                print(msg)

주소 형식

'AF_INET' 주소는 (hostname, port) 형식의 튜플입니다. hostname 은 문자열이고, port 는 정수입니다.

'AF_UNIX' 주소는 파일 시스템의 파일 이름을 나타내는 문자열입니다.

'AF_PIPE' 주소는 형식

r'\.\pipe{PipeName}' 의 문자열입니다. Client() 를 사용하여 ServerName 이라는 원격 컴퓨터의 이름있는 파이프에 연결하려면, 대신 r'\ServerName\pipe{PipeName}' 형식의 주소를 사용해야 합니다.

두 개의 역 슬래시로 시작하는 문자열은 기본적으로 'AF_UNIX' 주소가 아니라 'AF_PIPE' 주소로 간주합니다.

인증 키

Connection.recv 를 사용할 때, 수신된 데이터는 자동으로 언 피클 됩니다. 안타깝게도, 신뢰할 수 없는 출처의 데이터를 언 피클 하는 것은 보안상의 위험입니다. 때문에 Listener와 Client() 는 hmac 모듈을 사용하여 다이제스트 인증을 제공합니다.

인증 키는 암호로 여겨질 수 있는 바이트열입니다: 일단 연결이 이루어지면 양 끝은 다른 쪽이 인증 키를 알고 있음을 증명하도록 요구합니다. (양쪽 끝이 같은 키를 사용하고 있음을 증명하는 데는 연결을 통해 키를 보내는 것을 수반하지 않습니다.)

인증이 요청되었지만 인증 키가 지정되지 않으면, current_process().authkey 의 반환 값이 사용됩니다 (Process 를 보세요). 이 값은 현재 프로세스가 생성하는 Process 객체에 의해 자동으로 상속됩니다. 이것은 다중 프로세스 프로그램의 모든 프로세스는 (기본적으로) 자신들 간의 연결을 설정할 때 사용할 수 있는 하나의 인증 키를 공유한다는 것을 뜻합니다.

적절한 인증 키는 os.urandom() 을 사용하여 생성할 수도 있습니다.

로깅

로깅에 대한 일부 지원이 제공됩니다. 그러나, logging 패키지는 프로세스 공유 록을 사용하지 않으므로 (처리기형에 따라) 다른 프로세스의 메시지가 뒤섞일 가능성이 있습니다.

multiprocessing.get_logger()

multiprocessing에서 사용되는 로거를 반환합니다. 필요하다면, 새로운 것이 만들어집니다.

로거가 처음 생성되면 수준 logging.NOTSET 을 가지며 기본 처리기가 없습니다. 이 로거로 보낸 메시지는 기본적으로 루트 로거에 전파되지 않습니다.

윈도우에서 자식 프로세스는 부모 프로세스의 로거의 수준만 상속받습니다 – 그 밖의 다른 로거 사용자 지정은 상속되지 않습니다.

multiprocessing.log_to_stderr()

이 함수는 get_logger()를 호출하지만, get_logger에 의해 생성된 로거를 반환하는 것 외에, '[%(levelname)s/%(processName)s] %(message)s' 포맷을 사용하여 sys.stderr 에 출력을 전송하는 처리기를 추가합니다.

다음은 로깅이 켜져 있는 예제 세션입니다:

>>> import multiprocessing, logging
>>> logger = multiprocessing.log_to_stderr()
>>> logger.setLevel(logging.INFO)
>>> logger.warning('doomed')
[WARNING/MainProcess] doomed
>>> m = multiprocessing.Manager()
[INFO/SyncManager-...] child process calling self.run()
[INFO/SyncManager-...] created temp directory /.../pymp-...
[INFO/SyncManager-...] manager serving at '/.../listener-...'
>>> del m
[INFO/MainProcess] sending shutdown message to manager
[INFO/SyncManager-...] manager exiting with exitcode 0

로깅 수준의 전체 표는 logging 모듈을 참조하십시오.

multiprocessing.dummy 모듈

multiprocessing.dummy 는 multiprocessing 의 API를 복제하지만 threading 모듈에 대한 래퍼일 뿐입니다.

In particular, the Pool function provided by multiprocessing.dummy returns an instance of ThreadPool, which is a subclass of Pool that supports all the same method calls but uses a pool of worker threads rather than worker processes.

class multiprocessing.pool.ThreadPool([processes[, initializer[, initargs]]])

A thread pool object which controls a pool of worker threads to which jobs can be submitted. ThreadPool instances are fully interface compatible with Pool instances, and their resources must also be properly managed, either by using the pool as a context manager or by calling close() and terminate() manually.

processes is the number of worker threads to use. If processes is None then the number returned by os.cpu_count() is used.

initializer 가 None 이 아니면, 각 작업자 프로세스는 시작할 때 initializer(*initargs) 를 호출합니다.

Unlike Pool, maxtasksperchild and context cannot be provided.

참고

A ThreadPool shares the same interface as Pool, which is designed around a pool of processes and predates the introduction of the concurrent.futures module. As such, it inherits some operations that don’t make sense for a pool backed by threads, and it has its own type for representing the status of asynchronous jobs, AsyncResult, that is not understood by any other libraries.

Users should generally prefer to use concurrent.futures.ThreadPoolExecutor, which has a simpler interface that was designed around threads from the start, and which returns concurrent.futures.Future instances that are compatible with many other libraries, including asyncio.

프로그래밍 지침

multiprocessing를 사용할 때 준수해야 할 지침과 관용구가 있습니다.

모든 시작 방법

다음은 모든 시작 방법에 적용됩니다.

공유 상태를 피하세요

가능한 한 프로세스 간에 많은 양의 데이터가 이동하지 않도록 해야 합니다.

저수준 동기화 프리미티브를 사용하기보다, 프로세스 간 통신을 위해 큐나 파이프를 사용하는 것이 아마도 최선입니다.

피클 가능성

프락시 메서드에 대한 인자가 피클 가능한지 확인하십시오.

프락시의 스레드 안전성

록으로 보호하지 않는 한 둘 이상의 스레드에서 프락시 객체를 사용하지 마십시오.

(여러 프로세스가 같은 프락시를 사용하는 문제는 존재하지 않습니다.)

좀비 프로세스 조인하기

유닉스에서 프로세스가 끝났지만 조인되지 않으면 좀비가 됩니다. 너무 많이 생기지는 않아야 하는데, 새로운 프로세스가 시작될 때마다 (또는 active_children() 이 호출 되면) 아직 조인되지 않은 모든 완료된 프로세스를 조인하기 때문입니다. 또한, 완료된 프로세스의 Process.is_alive 를 호출하면 조인합니다. 그렇다고 하더라도 여러분이 시작시키는 모든 프로세스를 명시적으로 조인하는 것이 좋습니다.

피클/언 피클보다 상속하는 것이 더 좋습니다.

spawn 이나 forkserver 시작 방법을 사용할 때, multiprocessing 의 여러 형은 자식 프로세스가 사용할 수 있도록 피클 가능할 필요가 있습니다. 그러나, 일반적으로 파이프나 큐를 사용하여 공유 객체를 다른 프로세스로 보내는 것을 피해야 합니다. 대신 다른 곳에 만들어진 공유 자원에 접근해야 하는 프로세스가 조상 프로세스에서 그것들을 상속받을 수 있도록 프로그램을 배치해야 합니다.

프로세스 강제 종료를 피하세요

Process.terminate 메서드를 사용해서 프로세스를 정지시키는 것은, 그 프로세스가 현재 사용하고 있는 공유 자원(가령 록, 세마포어, 파이프, 큐)을 손상하거나 다른 프로세스에서 사용할 수 없게 만들 수 있습니다.

따라서, 아마도 어떤 공유 자원도 사용하지 않는 프로세스에만 Process.terminate 사용을 고려하는 것이 최선일 겁니다.

큐를 사용하는 프로세스 조인하기

큐에 항목을 넣은 프로세스는 종료되기 전에 버퍼링 된 모든 항목이 “피더” 스레드에 의해 하부 파이프로 공급될 때까지 대기합니다. (자식 프로세스는 Queue.cancel_join_thread 메서드를 호출해서 이 동작을 회피할 수 있습니다.)

이것은, 큐를 사용할 때마다 큐에 넣은 모든 항목이 결국 프로세스가 조인되기 전에 제거되도록 해야 함을 의미합니다. 그렇지 않으면 큐에 항목을 넣은 프로세스가 종료되리라고 보장할 수 없습니다. 데몬이 아닌 프로세스가 자동으로 조인된다는 것도 기억하세요.

교착 상태에 빠지는 예는 다음과 같습니다:

from multiprocessing import Process, Queue

def f(q):
    q.put('X' * 1000000)

if __name__ == '__main__':
    queue = Queue()
    p = Process(target=f, args=(queue,))
    p.start()
    p.join()                    # this deadlocks
    obj = queue.get()

이 문제를 고치는 방법은 마지막 두 줄의 순서를 바꾸는 것입니다 (또는 간단히 p.join() 줄을 지우는 것입니다).

자식 프로세스에 자원을 명시적으로 전달하세요.

fork 시작 방법을 사용하는 유닉스에서, 자식 프로세스는 전역 자원을 사용하여 부모 프로세스에서 생성된 공유 자원을 사용할 수 있습니다. 그러나 자식 프로세스의 생성자에 객체를 인자로 전달하는 것이 더 좋습니다.

윈도우 및 다른 시작 방법과 (잠재적으로) 호환될 수 있는 코드를 만드는 것 외에도, 이것은 자식 프로세스가 아직 살아있는 동안 객체가 부모 프로세스에서 가비지 수집되지 않음을 보장합니다. 부모 프로세스에서 그 객체가 가비지 수집될 때 일부 자원이 해제되면 이것이 중요 할 수 있습니다.

그래서 예를 들면

from multiprocessing import Process, Lock

def f():
    ... do something using "lock" ...

if __name__ == '__main__':
    lock = Lock()
    for i in range(10):
        Process(target=f).start()

는 다음과 같이 다시 써야 합니다

from multiprocessing import Process, Lock

def f(l):
    ... do something using "l" ...

if __name__ == '__main__':
    lock = Lock()
    for i in range(10):
        Process(target=f, args=(lock,)).start()

sys.stdin 을 “파일류 객체”로 교체할 때 조심하세요

multiprocessing은 원래 무조건 다음과 같이 호출했습니다

os.close(sys.stdin.fileno())

multiprocessing.Process._bootstrap() 메서드에서 하는 작업입니다 — 이것은 손자 프로세스와 관련된 문제로 이어졌습니다. 이것은 다음과 같이 변경되었습니다:

sys.stdin.close()
sys.stdin = open(os.open(os.devnull, os.O_RDONLY), closefd=False)

이것은 프로세스가 서로 충돌해서 파일 기술자 에러를 일으키는 근본적인 문제를 해결하지만, sys.stdin() 을 출력 버퍼링을 사용하는 “파일과 유사한 객체”로 교체하는 응용 프로그램에 잠재적 위험을 만듭니다. 이 위험은, 다중 프로세스가 이 파일류 객체에 close()를 호출하면, 같은 데이터가 객체에 여러 번 플러시 되도록 만들어 손상을 일으킬 수 있다는 것입니다.

파일류 객체를 작성하고 여러분 자신의 캐싱을 구현하면, 캐시에 추가할 때마다 pid를 저장하고, pid가 변경되면 캐시를 버려서 포크에 안전하게 만들 수 있습니다. 예를 들면:

@property
def cache(self):
    pid = os.getpid()
    if pid != self._pid:
        self._pid = pid
        self._cache = []
    return self._cache

자세한 내용은 bpo-5155 [https://bugs.python.org/issue?@action=redirect&bpo=5155], bpo-5313 [https://bugs.python.org/issue?@action=redirect&bpo=5313] 및 bpo-5331 [https://bugs.python.org/issue?@action=redirect&bpo=5331]을 참조하십시오.

spawn 과 forkserver 시작 방법

fork 시작 방법에는 적용되지 않는 몇 가지 추가 제한 사항이 있습니다.

더 높은 피클 가능성

Process.__init__() 에 대한 모든 인자가 피클 가능한지 확인하십시오. 또한, Process 의 서브 클래스를 만들면, Process.start 메서드가 호출될 때 그 인스턴스가 피클 가능하도록 해야 합니다.

전역 변수

자식 프로세스에서 실행되는 코드가 전역 변수에 접근하려고 시도하면, 그 값은 (있는 경우) Process.start 가 호출되는 시점의 부모 프로세스의 값과 같지 않을 수 있습니다.

하지만, 모듈 수준의 상수인 전역 변수는 문제가 되지 않습니다.

메인 모듈의 안전한 임포트

메인 모듈이 의도하지 않은 부작용(가령 새 프로세스 시작)을 일으키지 않고 새 파이썬 인터프리터가 안전하게 임포트 할 수 있는지 확인하십시오.

예를 들어, spawn 또는 forkserver 시작 방법을 사용해서 다음 모듈을 실행하면 RuntimeError 로 실패합니다:

from multiprocessing import Process

def foo():
    print('hello')

p = Process(target=foo)
p.start()

대신 다음과 같이 if __name__ == '__main__': 을 사용하여 프로그램의 “진입 지점”을 보호해야 합니다:

from multiprocessing import Process, freeze_support, set_start_method

def foo():
    print('hello')

if __name__ == '__main__':
    freeze_support()
    set_start_method('spawn')
    p = Process(target=foo)
    p.start()

(freeze_support() 줄은 프로그램이 프로즌 되지 않고 정상적으로 실행될 경우 생략될 수 있습니다.)

이것은 새로 스폰 된 파이썬 인터프리터가 모듈을 안전하게 임포트 한 다음 모듈의 foo() 함수를 실행할 수 있게 해줍니다.

메인 모듈에서 풀이나 관리자를 만들면 비슷한 제한이 적용됩니다.

예제

사용자 정의된 관리자와 프락시를 만들고 사용하는 방법에 대한 시연:

from multiprocessing import freeze_support
from multiprocessing.managers import BaseManager, BaseProxy
import operator

##

class Foo:
    def f(self):
        print('you called Foo.f()')
    def g(self):
        print('you called Foo.g()')
    def _h(self):
        print('you called Foo._h()')

# A simple generator function
def baz():
    for i in range(10):
        yield i*i

# Proxy type for generator objects
class GeneratorProxy(BaseProxy):
    _exposed_ = ['__next__']
    def __iter__(self):
        return self
    def __next__(self):
        return self._callmethod('__next__')

# Function to return the operator module
def get_operator_module():
    return operator

##

class MyManager(BaseManager):
    pass

# register the Foo class; make `f()` and `g()` accessible via proxy
MyManager.register('Foo1', Foo)

# register the Foo class; make `g()` and `_h()` accessible via proxy
MyManager.register('Foo2', Foo, exposed=('g', '_h'))

# register the generator function baz; use `GeneratorProxy` to make proxies
MyManager.register('baz', baz, proxytype=GeneratorProxy)

# register get_operator_module(); make public functions accessible via proxy
MyManager.register('operator', get_operator_module)

##

def test():
    manager = MyManager()
    manager.start()

    print('-' * 20)

    f1 = manager.Foo1()
    f1.f()
    f1.g()
    assert not hasattr(f1, '_h')
    assert sorted(f1._exposed_) == sorted(['f', 'g'])

    print('-' * 20)

    f2 = manager.Foo2()
    f2.g()
    f2._h()
    assert not hasattr(f2, 'f')
    assert sorted(f2._exposed_) == sorted(['g', '_h'])

    print('-' * 20)

    it = manager.baz()
    for i in it:
        print('<%d>' % i, end=' ')
    print()

    print('-' * 20)

    op = manager.operator()
    print('op.add(23, 45) =', op.add(23, 45))
    print('op.pow(2, 94) =', op.pow(2, 94))
    print('op._exposed_ =', op._exposed_)

##

if __name__ == '__main__':
    freeze_support()
    test()

Pool 사용하기:

import multiprocessing
import time
import random
import sys

#
# Functions used by test code
#

def calculate(func, args):
    result = func(*args)
    return '%s says that %s%s = %s' % (
        multiprocessing.current_process().name,
        func.__name__, args, result
        )

def calculatestar(args):
    return calculate(*args)

def mul(a, b):
    time.sleep(0.5 * random.random())
    return a * b

def plus(a, b):
    time.sleep(0.5 * random.random())
    return a + b

def f(x):
    return 1.0 / (x - 5.0)

def pow3(x):
    return x ** 3

def noop(x):
    pass

#
# Test code
#

def test():
    PROCESSES = 4
    print('Creating pool with %d processes\n' % PROCESSES)

    with multiprocessing.Pool(PROCESSES) as pool:
        #
        # Tests
        #

        TASKS = [(mul, (i, 7)) for i in range(10)] + \
                [(plus, (i, 8)) for i in range(10)]

        results = [pool.apply_async(calculate, t) for t in TASKS]
        imap_it = pool.imap(calculatestar, TASKS)
        imap_unordered_it = pool.imap_unordered(calculatestar, TASKS)

        print('Ordered results using pool.apply_async():')
        for r in results:
            print('\t', r.get())
        print()

        print('Ordered results using pool.imap():')
        for x in imap_it:
            print('\t', x)
        print()

        print('Unordered results using pool.imap_unordered():')
        for x in imap_unordered_it:
            print('\t', x)
        print()

        print('Ordered results using pool.map() --- will block till complete:')
        for x in pool.map(calculatestar, TASKS):
            print('\t', x)
        print()

        #
        # Test error handling
        #

        print('Testing error handling:')

        try:
            print(pool.apply(f, (5,)))
        except ZeroDivisionError:
            print('\tGot ZeroDivisionError as expected from pool.apply()')
        else:
            raise AssertionError('expected ZeroDivisionError')

        try:
            print(pool.map(f, list(range(10))))
        except ZeroDivisionError:
            print('\tGot ZeroDivisionError as expected from pool.map()')
        else:
            raise AssertionError('expected ZeroDivisionError')

        try:
            print(list(pool.imap(f, list(range(10)))))
        except ZeroDivisionError:
            print('\tGot ZeroDivisionError as expected from list(pool.imap())')
        else:
            raise AssertionError('expected ZeroDivisionError')

        it = pool.imap(f, list(range(10)))
        for i in range(10):
            try:
                x = next(it)
            except ZeroDivisionError:
                if i == 5:
                    pass
            except StopIteration:
                break
            else:
                if i == 5:
                    raise AssertionError('expected ZeroDivisionError')

        assert i == 9
        print('\tGot ZeroDivisionError as expected from IMapIterator.next()')
        print()

        #
        # Testing timeouts
        #

        print('Testing ApplyResult.get() with timeout:', end=' ')
        res = pool.apply_async(calculate, TASKS[0])
        while 1:
            sys.stdout.flush()
            try:
                sys.stdout.write('\n\t%s' % res.get(0.02))
                break
            except multiprocessing.TimeoutError:
                sys.stdout.write('.')
        print()
        print()

        print('Testing IMapIterator.next() with timeout:', end=' ')
        it = pool.imap(calculatestar, TASKS)
        while 1:
            sys.stdout.flush()
            try:
                sys.stdout.write('\n\t%s' % it.next(0.02))
            except StopIteration:
                break
            except multiprocessing.TimeoutError:
                sys.stdout.write('.')
        print()
        print()

if __name__ == '__main__':
    multiprocessing.freeze_support()
    test()

큐를 사용하여 작업을 작업자 프로세스 집단에 제공하고 결과를 수집하는 방법을 보여주는 예:

import time
import random

from multiprocessing import Process, Queue, current_process, freeze_support

#
# Function run by worker processes
#

def worker(input, output):
    for func, args in iter(input.get, 'STOP'):
        result = calculate(func, args)
        output.put(result)

#
# Function used to calculate result
#

def calculate(func, args):
    result = func(*args)
    return '%s says that %s%s = %s' % \
        (current_process().name, func.__name__, args, result)

#
# Functions referenced by tasks
#

def mul(a, b):
    time.sleep(0.5*random.random())
    return a * b

def plus(a, b):
    time.sleep(0.5*random.random())
    return a + b

#
#
#

def test():
    NUMBER_OF_PROCESSES = 4
    TASKS1 = [(mul, (i, 7)) for i in range(20)]
    TASKS2 = [(plus, (i, 8)) for i in range(10)]

    # Create queues
    task_queue = Queue()
    done_queue = Queue()

    # Submit tasks
    for task in TASKS1:
        task_queue.put(task)

    # Start worker processes
    for i in range(NUMBER_OF_PROCESSES):
        Process(target=worker, args=(task_queue, done_queue)).start()

    # Get and print results
    print('Unordered results:')
    for i in range(len(TASKS1)):
        print('\t', done_queue.get())

    # Add more tasks using `put()`
    for task in TASKS2:
        task_queue.put(task)

    # Get and print some more results
    for i in range(len(TASKS2)):
        print('\t', done_queue.get())

    # Tell child processes to stop
    for i in range(NUMBER_OF_PROCESSES):
        task_queue.put('STOP')

if __name__ == '__main__':
    freeze_support()
    test()

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

동시 실행 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

동시 실행 »

|

concurrent 패키지

현재, 이 패키지에는 하나의 모듈만 있습니다.:

concurrent.futures – 병렬 작업 시작하기

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

동시 실행 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

동시 실행 »

|

concurrent.futures — 병렬 작업 실행하기

버전 3.2에 추가.

소스 코드: Lib/concurrent/futures/thread.py [https://github.com/python/cpython/tree/3.7/Lib/concurrent/futures/thread.py]와 Lib/concurrent/futures/process.py [https://github.com/python/cpython/tree/3.7/Lib/concurrent/futures/process.py]

concurrent.futures 모듈은 비동기적으로 콜러블을 실행하는 고수준 인터페이스를 제공합니다.

비동기 실행은 (ThreadPoolExecutor를 사용해서) 스레드나 (ProcessPoolExecutor를 사용해서) 별도의 프로세스로 수행 할 수 있습니다. 둘 다 추상 Executor 클래스로 정의된 것과 같은 인터페이스를 구현합니다.

Executor 객체

class concurrent.futures.Executor

비동기적으로 호출을 실행하는 메서드를 제공하는 추상 클래스입니다. 직접 사용해서는 안 되며, 구체적인 하위 클래스를 통해 사용해야 합니다.

submit(fn, *args, **kwargs)

콜러블 fn 이 fn(*args **kwargs) 처럼 실행되도록 예약하고, 콜러블 객체의 실행을 나타내는 Future 객체를 반환합니다.

with ThreadPoolExecutor(max_workers=1) as executor:
    future = executor.submit(pow, 323, 1235)
    print(future.result())

map(func, *iterables, timeout=None, chunksize=1)

map(func, *iterables) 과 비슷하지만, 다음과 같은 차이가 있습니다:

iterables 는 느긋하게 처리되는 것이 아니라 즉시 수집됩니다.

func 는 비동기적으로 실행되며 func 에 대한 여러 호출이 동시에 이루어질 수 있습니다.

반환된 이터레이터는 __next__() 가 호출되었을 때, Executor.map() 에 대한 최초 호출에서 timeout 초 후에도 결과를 사용할 수 없는 경우 concurrent.futures.TimeoutError 를 발생시킵니다. timeout 은 int 또는 float가 될 수 있습니다. timeout 이 지정되지 않았거나 None 인 경우, 대기 시간에는 제한이 없습니다.

func 호출이 예외를 일으키면, 값을 이터레이터에서 꺼낼 때 해당 예외가 발생합니다.

ProcessPoolExecutor를 사용할 때, 이 메서드는 iterables 를 다수의 덩어리로 잘라서 별도의 작업으로 풀에 제출합니다. 이러한 덩어리의 (대략적인) 크기는 chunksize 를 양의 정수로 설정하여 지정할 수 있습니다. 매우 긴 이터러블의 경우 chunksize 에 큰 값을 사용하면 기본 크기인 1에 비해 성능이 크게 향상될 수 있습니다. ThreadPoolExecutor 의 경우, chunksize 는 아무런 효과가 없습니다.

버전 3.5에서 변경: chunksize 인자가 추가되었습니다.

shutdown(wait=True)

현재 계류 중인 퓨처가 실행 완료될 때, 사용 중인 모든 자원을 해제해야 한다는 것을 실행기에 알립니다. 종료(shutdown) 후에 이루어지는 Executor.submit() 과 Executor.map() 호출은 RuntimeError 를 발생시킵니다.

wait 가 True 면, 계류 중인 모든 퓨처가 실행을 마치고 실행기와 관련된 자원이 해제될 때까지 이 메서드는 돌아오지 않습니다. wait 가 False 면, 이 메서드는 즉시 돌아오고 실행기와 연관된 자원은 계류 중인 모든 퓨처가 실행을 마칠 때 해제됩니다. wait 의 값과 관계없이, 모든 계류 중인 퓨처가 실행을 마칠 때까지 전체 파이썬 프로그램이 종료되지 않습니다.

with 문을 사용하여 Executor를 종료시키면 (Executor.shutdown() 를 wait 값 True 로 호출한 것처럼 대기합니다), 이 메서드를 명시적으로 호출할 필요가 없어집니다.:

import shutil
with ThreadPoolExecutor(max_workers=4) as e:
    e.submit(shutil.copy, 'src1.txt', 'dest1.txt')
    e.submit(shutil.copy, 'src2.txt', 'dest2.txt')
    e.submit(shutil.copy, 'src3.txt', 'dest3.txt')
    e.submit(shutil.copy, 'src4.txt', 'dest4.txt')

ThreadPoolExecutor

ThreadPoolExecutor 는 스레드 풀을 사용하여 호출을 비동기적으로 실행하는 Executor 서브 클래스입니다.

Future와 관련된 콜러블 객체가 다른 Future 의 결과를 기다릴 때 교착 상태가 발생할 수 있습니다. 예를 들면:

import time
def wait_on_b():
    time.sleep(5)
    print(b.result())  # b will never complete because it is waiting on a.
    return 5

def wait_on_a():
    time.sleep(5)
    print(a.result())  # a will never complete because it is waiting on b.
    return 6

executor = ThreadPoolExecutor(max_workers=2)
a = executor.submit(wait_on_b)
b = executor.submit(wait_on_a)

그리고:

def wait_on_future():
    f = executor.submit(pow, 5, 2)
    # This will never complete because there is only one worker thread and
    # it is executing this function.
    print(f.result())

executor = ThreadPoolExecutor(max_workers=1)
executor.submit(wait_on_future)

class concurrent.futures.ThreadPoolExecutor(max_workers=None, thread_name_prefix='', initializer=None, initargs=())

최대 max_workers 스레드의 풀을 사용하여 호출을 비동기적으로 실행하는 Executor 서브 클래스.

initializer 는 각 작업자 스레드의 시작 부분에서 호출되는 선택적 콜러블입니다; initargs 는 initializer에 전달되는 인자들의 튜플입니다. initializer 가 예외를 발생시키는 경우, 현재 계류 중인 모든 작업과 풀에 추가로 작업을 제출하려는 시도는 BrokenThreadPool 을 발생시킵니다.

버전 3.5에서 변경: max_workers 가 None 이거나 주어지지 않았다면, 기본값으로 기계의 프로세서 수에 5 를 곱한 값을 사용합니다. ThreadPoolExecutor 가 CPU 작업보다는 I/O를 동시에 진행하는데 자주 쓰이고, 작업자의 수가 ProcessPoolExecutor 보다 많아야 한다고 가정하고 있습니다.

버전 3.6에 추가: thread_name_prefix 인자가 추가되어, 디버깅 편의를 위해 사용자가 풀이 만드는 작업자 스레드의 threading.Thread 이름을 제어 할 수 있습니다.

버전 3.7에서 변경: initializer 및 initargs 인자가 추가되었습니다.

ThreadPoolExecutor 예제

import concurrent.futures
import urllib.request

URLS = ['http://www.foxnews.com/',
        'http://www.cnn.com/',
        'http://europe.wsj.com/',
        'http://www.bbc.co.uk/',
        'http://nonexistant-subdomain.python.org/']

# Retrieve a single page and report the URL and contents
def load_url(url, timeout):
    with urllib.request.urlopen(url, timeout=timeout) as conn:
        return conn.read()

# We can use a with statement to ensure threads are cleaned up promptly
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
    # Start the load operations and mark each future with its URL
    future_to_url = {executor.submit(load_url, url, 60): url for url in URLS}
    for future in concurrent.futures.as_completed(future_to_url):
        url = future_to_url[future]
        try:
            data = future.result()
        except Exception as exc:
            print('%r generated an exception: %s' % (url, exc))
        else:
            print('%r page is %d bytes' % (url, len(data)))

ProcessPoolExecutor

ProcessPoolExecutor 클래스는 프로세스 풀을 사용하여 호출을 비동기적으로 실행하는 Executor 서브 클래스입니다. ProcessPoolExecutor 는 multiprocessing 모듈을 사용합니다. 전역 인터프리터 록 을 피할 수 있도록 하지만, 오직 피클 가능한 객체만 실행되고 반환될 수 있음을 의미합니다.

__main__ 모듈은 작업자 서브 프로세스가 임포트 할 수 있어야 합니다. 즉, ProcessPoolExecutor 는 대화형 인터프리터에서 작동하지 않습니다.

ProcessPoolExecutor 에 제출된 콜러블에서 Executor 나 Future 메서드를 호출하면 교착 상태가 발생합니다.

class concurrent.futures.ProcessPoolExecutor(max_workers=None, mp_context=None, initializer=None, initargs=())

최대 max_workers 프로세스의 풀을 사용하여 호출을 비동기적으로 실행하는 Executor 서브 클래스. max_workers 가 None 이거나 주어지지 않았다면, 기계의 프로세서 수를 기본값으로 사용합니다. max_workers 가 0 보다 작거나 같으면 ValueError 가 발생합니다. 윈도우에서, max_workers는 61보다 작거나 같아야 합니다. 그렇지 않으면 ValueError가 발생합니다. max_workers가 None 이면, 더 많은 프로세서를 사용할 수 있다 할지라도 선택된 기본값은 최대 61이 될 것입니다. mp_context 는 multiprocessing 컨텍스트이거나 None일 수 있습니다. 작업자들을 만드는데 사용될 것입니다. mp_context 가 None 이거나 주어지지 않으면 기본 multiprocessing 컨텍스트가 사용됩니다.

initializer 는 각 작업자 프로세스의 시작 부분에서 호출되는 선택적 콜러블입니다; initargs 는 initializer에 전달되는 인자들의 튜플입니다. initializer 가 예외를 발생시키는 경우, 현재 계류 중인 모든 작업과 풀에 추가로 작업을 제출하려는 시도는 BrokenProcessPool 을 발생시킵니다.

버전 3.3에서 변경: 작업자 프로세스 중 하나가 갑자기 종료되면, BrokenProcessPool 오류가 발생합니다. 이전에는, 동작이 정의되지 않았지만, 실행기나 그 퓨처에 대한 연산이 종종 멈추거나 교착 상태에 빠졌습니다.

버전 3.7에서 변경: mp_context 인자가 추가되어 사용자가 풀에서 만드는 작업자 프로세스의 시작 방법을 제어 할 수 있습니다.

initializer 및 initargs 인자가 추가되었습니다.

ProcessPoolExecutor 예제

import concurrent.futures
import math

PRIMES = [
    112272535095293,
    112582705942171,
    112272535095293,
    115280095190773,
    115797848077099,
    1099726899285419]

def is_prime(n):
    if n % 2 == 0:
        return False

    sqrt_n = int(math.floor(math.sqrt(n)))
    for i in range(3, sqrt_n + 1, 2):
        if n % i == 0:
            return False
    return True

def main():
    with concurrent.futures.ProcessPoolExecutor() as executor:
        for number, prime in zip(PRIMES, executor.map(is_prime, PRIMES)):
            print('%d is prime: %s' % (number, prime))

if __name__ == '__main__':
    main()

Future 객체

Future 클래스는 콜러블 객체의 비동기 실행을 캡슐화합니다. Future 인스턴스는 Executor.submit() 에 의해 생성됩니다.

class concurrent.futures.Future

콜러블 객체의 비동기 실행을 캡슐화합니다. Future 인스턴스는 Executor.submit() 에 의해 생성되며 테스트를 제외하고는 직접 생성되어서는 안 됩니다.

cancel()

호출을 취소하려고 시도합니다. 호출이 현재 실행 중이거나 실행 종료했고 취소할 수 없는 경우 메서드는 False 를 반환하고, 그렇지 않으면 호출이 취소되고 메서드는 True 를 반환합니다.

cancelled()

호출이 성공적으로 취소되었으면 True 를 반환합니다.

running()

호출이 현재 실행 중이고 취소할 수 없는 경우 True 를 반환합니다.

done()

호출이 성공적으로 취소되었거나 실행이 완료되었으면 True 를 반환합니다.

result(timeout=None)

호출이 반환한 값을 돌려줍니다. 호출이 아직 완료되지 않는 경우, 이 메서드는 timeout 초까지 대기합니다. timeout 초 내에 호출이 완료되지 않으면 concurrent.futures.TimeoutError 가 발생합니다. timeout 은 int 또는 float가 될 수 있습니다. timeout 이 지정되지 않았거나 None 인 경우, 대기 시간에는 제한이 없습니다.

완료하기 전에 퓨처가 취소되면 CancelledError 가 발생합니다.

호출이 예외를 일으키는 경우, 이 메서드는 같은 예외를 발생시킵니다.

exception(timeout=None)

호출이 일으킨 예외를 돌려줍니다. 호출이 아직 완료되지 않는 경우, 이 메서드는 timeout 초까지 대기합니다. timeout 초 내에 호출이 완료되지 않으면 concurrent.futures.TimeoutError 가 발생합니다. timeout 은 int 또는 float가 될 수 있습니다. timeout 이 지정되지 않았거나 None 인 경우, 대기 시간에는 제한이 없습니다.

완료하기 전에 퓨처가 취소되면 CancelledError 가 발생합니다.

호출이 예외 없이 완료되면, None 이 반환됩니다.

add_done_callback(fn)

콜러블 fn 을 퓨처에 연결합니다. fn 은 퓨처가 취소되거나 실행이 종료될 때 퓨처를 유일한 인자로 호출됩니다.

추가된 콜러블은 추가된 순서대로 호출되며, 항상 콜러블을 추가한 프로세스에 속하는 스레드에서 호출됩니다. 콜러블이 Exception 서브 클래스를 발생시키면, 로그 되고 무시됩니다. 콜러블이 BaseException 서브 클래스를 발생시키면, 동작은 정의되지 않습니다.

퓨처가 이미 완료되었거나 취소된 경우 fn 이 즉시 호출됩니다.

다음 Future 메서드는 단위 테스트와 Executor 의 구현을 위한 것입니다.

set_running_or_notify_cancel()

이 메서드는 Future와 관련된 작업을 실행하기 전에 Executor 구현에 의해서만 호출되거나 단위 테스트에서만 호출되어야 합니다.

메서드가 False 를 반환하면, Future 가 취소된 것입니다. 즉 Future.cancel() 이 호출되었고 True를 반환했습니다. Future 완료를 기다리는 (즉, as_completed() 또는 wait()를 통해) 모든 스레드는 깨어납니다.

메서드가 True 를 반환하면, Future 가 취소되지 않았고 실행 상태로 진입했습니다. 즉 Future.running() 을 호출하면 True 가 반환됩니다.

이 메서드는 한 번만 호출 할 수 있으며, Future.set_result() 또는 Future.set_exception() 이 호출 된 후에는 호출할 수 없습니다.

set_result(result)

Future와 관련된 작업 결과를 result 로 설정합니다.

이 메서드는 Executor 구현과 단위 테스트에서만 사용해야 합니다.

set_exception(exception)

Future와 관련된 작업 결과를 Exception exception 으로 설정합니다.

이 메서드는 Executor 구현과 단위 테스트에서만 사용해야 합니다.

모듈 함수

concurrent.futures.wait(fs, timeout=None, return_when=ALL_COMPLETED)

fs 로 주어진 여러 (서로 다른 Executor 인스턴스가 만든 것들도 가능합니다) Future 인스턴스들이 완료할 때까지 기다립니다. 집합들의 이름있는 2-튜플을 돌려줍니다. done 이라는 이름의 첫 번째 집합은 대기가 끝나기 전에 완료된 (끝났거나 취소된) 퓨처를 담고 있습니다. not_done 이라는 이름의 두 번째 집합은 완료되지 않은 (계류 중이거나 실행 중인) 퓨처를 담고 있습니다.

timeout 은 반환하기 전에 대기 할 최대 시간(초)을 제어하는 데 사용할 수 있습니다. timeout 은 int 또는 float가 될 수 있습니다. timeout 이 지정되지 않았거나 None 인 경우, 대기 시간에는 제한이 없습니다.

return_when 은, 이 함수가 언제 반환되어야 하는지를 나타냅니다. 다음 상수 중 하나여야 합니다:

상수

설명

FIRST_COMPLETED

퓨처가 어느 하나라도 끝나거나 취소될 때 함수가 반환됩니다.

FIRST_EXCEPTION

어느 한 퓨처가 예외를 일으켜 완료하면 함수가 반환됩니다. 어떤 퓨처도 예외를 발생시키지 않으면 ALL_COMPLETED와 같습니다.

ALL_COMPLETED

모든 퓨처가 끝나거나 취소되면 함수가 반환됩니다.

concurrent.futures.as_completed(fs, timeout=None)

fs 로 주어진 여러 (서로 다른 Executor 인스턴스가 만든 것들도 가능합니다) 퓨처들이 완료되는 대로 (끝났거나 취소된 퓨처) 일드 하는 Future 인스턴스의 이터레이터를 반환합니다. fs 에 중복된 퓨처가 들어있으면 한 번만 반환됩니다. as_completed() 가 호출되기 전에 완료한 모든 퓨처들이 먼저 일드 됩니다. 반환된 이터레이터는, __next__() 가 호출되고, as_completed() 호출 시점으로부터 timeout 초 후에 결과를 얻을 수 없는 경우 concurrent.futures.TimeoutError 를 발생시킵니다. timeout 은 int 또는 float가 될 수 있습니다. timeout 이 지정되지 않았거나 None 인 경우, 대기 시간에는 제한이 없습니다.

더 보기

PEP 3148 [https://www.python.org/dev/peps/pep-3148] – 퓨처 - 계산을 비동기적으로 실행

파이썬 표준 라이브러리에 포함하기 위해, 이 기능을 설명한 제안.

예외 클래스

exception concurrent.futures.CancelledError

퓨처가 취소될 때 발생합니다.

exception concurrent.futures.TimeoutError

퓨처 연산이 지정된 제한시간을 초과할 때 발생합니다.

exception concurrent.futures.BrokenExecutor

RuntimeError 에서 파생됩니다, 이 예외 클래스는 어떤 이유로 실행기가 망가져서 새 작업을 제출하거나 실행할 수 없을 때 발생합니다.

버전 3.7에 추가.

exception concurrent.futures.thread.BrokenThreadPool

BrokenExecutor 에서 파생됩니다, 이 예외 클래스는 ThreadPoolExecutor 의 작업자 중 하나가 초기화에 실패했을 때 발생합니다.

버전 3.7에 추가.

exception concurrent.futures.process.BrokenProcessPool

BrokenExecutor 에서 파생됩니다 (예전에는 RuntimeError), 이 예외 클래스는 ProcessPoolExecutor 의 작업자 중 하나가 깨끗하지 못한 방식으로 (예를 들어, 외부에서 강제 종료된 경우) 종료되었을 때 발생합니다.

버전 3.3에 추가.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

동시 실행 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

동시 실행 »

|

subprocess — Subprocess management

Source code: Lib/subprocess.py [https://github.com/python/cpython/tree/3.7/Lib/subprocess.py]

The subprocess module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes. This module intends to replace several older modules and functions:

os.system
os.spawn*

Information about how the subprocess module can be used to replace these modules and functions can be found in the following sections.

더 보기

PEP 324 [https://www.python.org/dev/peps/pep-0324] – PEP proposing the subprocess module

Using the subprocess Module

The recommended approach to invoking subprocesses is to use the run() function for all use cases it can handle. For more advanced use cases, the underlying Popen interface can be used directly.

The run() function was added in Python 3.5; if you need to retain compatibility with older versions, see the Older high-level API section.

subprocess.run(args, *, stdin=None, input=None, stdout=None, stderr=None, capture_output=False, shell=False, cwd=None, timeout=None, check=False, encoding=None, errors=None, text=None, env=None, universal_newlines=None, **other_popen_kwargs)

Run the command described by args. Wait for command to complete, then return a CompletedProcess instance.

The arguments shown above are merely the most common ones, described below in Frequently Used Arguments (hence the use of keyword-only notation in the abbreviated signature). The full function signature is largely the same as that of the Popen constructor - most of the arguments to this function are passed through to that interface. (timeout, input, check, and capture_output are not.)

If capture_output is true, stdout and stderr will be captured. When used, the internal Popen object is automatically created with stdout=PIPE and stderr=PIPE. The stdout and stderr arguments may not be supplied at the same time as capture_output. If you wish to capture and combine both streams into one, use stdout=PIPE and stderr=STDOUT instead of capture_output.

The timeout argument is passed to Popen.communicate(). If the timeout expires, the child process will be killed and waited for. The TimeoutExpired exception will be re-raised after the child process has terminated.

The input argument is passed to Popen.communicate() and thus to the subprocess’s stdin. If used it must be a byte sequence, or a string if encoding or errors is specified or text is true. When used, the internal Popen object is automatically created with stdin=PIPE, and the stdin argument may not be used as well.

If check is true, and the process exits with a non-zero exit code, a CalledProcessError exception will be raised. Attributes of that exception hold the arguments, the exit code, and stdout and stderr if they were captured.

If encoding or errors are specified, or text is true, file objects for stdin, stdout and stderr are opened in text mode using the specified encoding and errors or the io.TextIOWrapper default. The universal_newlines argument is equivalent to text and is provided for backwards compatibility. By default, file objects are opened in binary mode.

If env is not None, it must be a mapping that defines the environment variables for the new process; these are used instead of the default behavior of inheriting the current process’ environment. It is passed directly to Popen.

Examples:

>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')

버전 3.5에 추가.

버전 3.6에서 변경: Added encoding and errors parameters

버전 3.7에서 변경: Added the text parameter, as a more understandable alias of universal_newlines. Added the capture_output parameter.

버전 3.7.17에서 변경: Changed Windows shell search order for shell=True. The current directory and %PATH% are replaced with %COMSPEC% and %SystemRoot%\System32\cmd.exe. As a result, dropping a malicious program named cmd.exe into a current directory no longer works.

class subprocess.CompletedProcess

The return value from run(), representing a process that has finished.

args

The arguments used to launch the process. This may be a list or a string.

returncode

Exit status of the child process. Typically, an exit status of 0 indicates that it ran successfully.

A negative value -N indicates that the child was terminated by signal N (POSIX only).

stdout

Captured stdout from the child process. A bytes sequence, or a string if run() was called with an encoding, errors, or text=True. None if stdout was not captured.

If you ran the process with stderr=subprocess.STDOUT, stdout and stderr will be combined in this attribute, and stderr will be None.

stderr

Captured stderr from the child process. A bytes sequence, or a string if run() was called with an encoding, errors, or text=True. None if stderr was not captured.

check_returncode()

If returncode is non-zero, raise a CalledProcessError.

버전 3.5에 추가.

subprocess.DEVNULL

Special value that can be used as the stdin, stdout or stderr argument to Popen and indicates that the special file os.devnull will be used.

버전 3.3에 추가.

subprocess.PIPE

Special value that can be used as the stdin, stdout or stderr argument to Popen and indicates that a pipe to the standard stream should be opened. Most useful with Popen.communicate().

subprocess.STDOUT

Special value that can be used as the stderr argument to Popen and indicates that standard error should go into the same handle as standard output.

exception subprocess.SubprocessError

Base class for all other exceptions from this module.

버전 3.3에 추가.

exception subprocess.TimeoutExpired

Subclass of SubprocessError, raised when a timeout expires while waiting for a child process.

cmd

Command that was used to spawn the child process.

timeout

Timeout in seconds.

output

Output of the child process if it was captured by run() or check_output(). Otherwise, None.

stdout

Alias for output, for symmetry with stderr.

stderr

Stderr output of the child process if it was captured by run(). Otherwise, None.

버전 3.3에 추가.

버전 3.5에서 변경: stdout and stderr attributes added

exception subprocess.CalledProcessError

Subclass of SubprocessError, raised when a process run by check_call() or check_output() returns a non-zero exit status.

returncode

Exit status of the child process. If the process exited due to a signal, this will be the negative signal number.

cmd

Command that was used to spawn the child process.

output

Output of the child process if it was captured by run() or check_output(). Otherwise, None.

stdout

Alias for output, for symmetry with stderr.

stderr

Stderr output of the child process if it was captured by run(). Otherwise, None.

버전 3.5에서 변경: stdout and stderr attributes added

Frequently Used Arguments

To support a wide variety of use cases, the Popen constructor (and the convenience functions) accept a large number of optional arguments. For most typical use cases, many of these arguments can be safely left at their default values. The arguments that are most commonly needed are:

args is required for all calls and should be a string, or a sequence of program arguments. Providing a sequence of arguments is generally preferred, as it allows the module to take care of any required escaping and quoting of arguments (e.g. to permit spaces in file names). If passing a single string, either shell must be True (see below) or else the string must simply name the program to be executed without specifying any arguments.

stdin, stdout and stderr specify the executed program’s standard input, standard output and standard error file handles, respectively. Valid values are PIPE, DEVNULL, an existing file descriptor (a positive integer), an existing file object, and None. PIPE indicates that a new pipe to the child should be created. DEVNULL indicates that the special file os.devnull will be used. With the default settings of None, no redirection will occur; the child’s file handles will be inherited from the parent. Additionally, stderr can be STDOUT, which indicates that the stderr data from the child process should be captured into the same file handle as for stdout.

If encoding or errors are specified, or text (also known as universal_newlines) is true, the file objects stdin, stdout and stderr will be opened in text mode using the encoding and errors specified in the call or the defaults for io.TextIOWrapper.

For stdin, line ending characters '\n' in the input will be converted to the default line separator os.linesep. For stdout and stderr, all line endings in the output will be converted to '\n'. For more information see the documentation of the io.TextIOWrapper class when the newline argument to its constructor is None.

If text mode is not used, stdin, stdout and stderr will be opened as binary streams. No encoding or line ending conversion is performed.

버전 3.6에 추가: Added encoding and errors parameters.

버전 3.7에 추가: Added the text parameter as an alias for universal_newlines.

참고

The newlines attribute of the file objects Popen.stdin, Popen.stdout and Popen.stderr are not updated by the Popen.communicate() method.

If shell is True, the specified command will be executed through the shell. This can be useful if you are using Python primarily for the enhanced control flow it offers over most system shells and still want convenient access to other shell features such as shell pipes, filename wildcards, environment variable expansion, and expansion of ~ to a user’s home directory. However, note that Python itself offers implementations of many shell-like features (in particular, glob, fnmatch, os.walk(), os.path.expandvars(), os.path.expanduser(), and shutil).

버전 3.3에서 변경: When universal_newlines is True, the class uses the encoding locale.getpreferredencoding(False) instead of locale.getpreferredencoding(). See the io.TextIOWrapper class for more information on this change.

참고

Read the Security Considerations section before using shell=True.

These options, along with all of the other options, are described in more detail in the Popen constructor documentation.

Popen Constructor

The underlying process creation and management in this module is handled by the Popen class. It offers a lot of flexibility so that developers are able to handle the less common cases not covered by the convenience functions.

class subprocess.Popen(args, bufsize=-1, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=True, shell=False, cwd=None, env=None, universal_newlines=None, startupinfo=None, creationflags=0, restore_signals=True, start_new_session=False, pass_fds=(), *, encoding=None, errors=None, text=None)

Execute a child program in a new process. On POSIX, the class uses os.execvp()-like behavior to execute the child program. On Windows, the class uses the Windows CreateProcess() function. The arguments to Popen are as follows.

args should be a sequence of program arguments or else a single string. By default, the program to execute is the first item in args if args is a sequence. If args is a string, the interpretation is platform-dependent and described below. See the shell and executable arguments for additional differences from the default behavior. Unless otherwise stated, it is recommended to pass args as a sequence.

An example of passing some arguments to an external program as a sequence is:

Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."])

On POSIX, if args is a string, the string is interpreted as the name or path of the program to execute. However, this can only be done if not passing arguments to the program.

참고

It may not be obvious how to break a shell command into a sequence of arguments, especially in complex cases. shlex.split() can illustrate how to determine the correct tokenization for args:

>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!

Note in particular that options (such as -input) and arguments (such as eggs.txt) that are separated by whitespace in the shell go in separate list elements, while arguments that need quoting or backslash escaping when used in the shell (such as filenames containing spaces or the echo command shown above) are single list elements.

On Windows, if args is a sequence, it will be converted to a string in a manner described in Converting an argument sequence to a string on Windows. This is because the underlying CreateProcess() operates on strings.

The shell argument (which defaults to False) specifies whether to use the shell as the program to execute. If shell is True, it is recommended to pass args as a string rather than as a sequence.

On POSIX with shell=True, the shell defaults to /bin/sh. If args is a string, the string specifies the command to execute through the shell. This means that the string must be formatted exactly as it would be when typed at the shell prompt. This includes, for example, quoting or backslash escaping filenames with spaces in them. If args is a sequence, the first item specifies the command string, and any additional items will be treated as additional arguments to the shell itself. That is to say, Popen does the equivalent of:

Popen(['/bin/sh', '-c', args[0], args[1], ...])

On Windows with shell=True, the COMSPEC environment variable specifies the default shell. The only time you need to specify shell=True on Windows is when the command you wish to execute is built into the shell (e.g. dir or copy). You do not need shell=True to run a batch file or console-based executable.

참고

Read the Security Considerations section before using shell=True.

bufsize will be supplied as the corresponding argument to the open() function when creating the stdin/stdout/stderr pipe file objects:

0 means unbuffered (read and write are one system call and can return short)

1 means line buffered (only usable if universal_newlines=True i.e., in a text mode)

any other positive value means use a buffer of approximately that size

negative bufsize (the default) means the system default of io.DEFAULT_BUFFER_SIZE will be used.

버전 3.3.1에서 변경: bufsize now defaults to -1 to enable buffering by default to match the behavior that most code expects. In versions prior to Python 3.2.4 and 3.3.1 it incorrectly defaulted to 0 which was unbuffered and allowed short reads. This was unintentional and did not match the behavior of Python 2 as most code expected.

The executable argument specifies a replacement program to execute. It is very seldom needed. When shell=False, executable replaces the program to execute specified by args. However, the original args is still passed to the program. Most programs treat the program specified by args as the command name, which can then be different from the program actually executed. On POSIX, the args name becomes the display name for the executable in utilities such as ps. If shell=True, on POSIX the executable argument specifies a replacement shell for the default /bin/sh.

버전 3.6에서 변경: executable parameter accepts a path-like object on POSIX.

버전 3.7.17에서 변경: Changed Windows shell search order for shell=True. The current directory and %PATH% are replaced with %COMSPEC% and %SystemRoot%\System32\cmd.exe. As a result, dropping a malicious program named cmd.exe into a current directory no longer works.

stdin, stdout and stderr specify the executed program’s standard input, standard output and standard error file handles, respectively. Valid values are PIPE, DEVNULL, an existing file descriptor (a positive integer), an existing file object, and None. PIPE indicates that a new pipe to the child should be created. DEVNULL indicates that the special file os.devnull will be used. With the default settings of None, no redirection will occur; the child’s file handles will be inherited from the parent. Additionally, stderr can be STDOUT, which indicates that the stderr data from the applications should be captured into the same file handle as for stdout.

If preexec_fn is set to a callable object, this object will be called in the child process just before the child is executed. (POSIX only)

경고

The preexec_fn parameter is not safe to use in the presence of threads in your application. The child process could deadlock before exec is called. If you must use it, keep it trivial! Minimize the number of libraries you call into.

참고

If you need to modify the environment for the child use the env parameter rather than doing it in a preexec_fn. The start_new_session parameter can take the place of a previously common use of preexec_fn to call os.setsid() in the child.

If close_fds is true, all file descriptors except 0, 1 and 2 will be closed before the child process is executed. Otherwise when close_fds is false, file descriptors obey their inheritable flag as described in 파일 기술자의 상속.

On Windows, if close_fds is true then no handles will be inherited by the child process unless explicitly passed in the handle_list element of STARTUPINFO.lpAttributeList, or by standard handle redirection.

버전 3.2에서 변경: The default for close_fds was changed from False to what is described above.

버전 3.7에서 변경: On Windows the default for close_fds was changed from False to True when redirecting the standard handles. It’s now possible to set close_fds to True when redirecting the standard handles.

pass_fds is an optional sequence of file descriptors to keep open between the parent and child. Providing any pass_fds forces close_fds to be True. (POSIX only)

버전 3.2에 추가: The pass_fds parameter was added.

If cwd is not None, the function changes the working directory to cwd before executing the child. cwd can be a str and path-like object. In particular, the function looks for executable (or for the first item in args) relative to cwd if the executable path is a relative path.

버전 3.6에서 변경: cwd parameter accepts a path-like object.

If restore_signals is true (the default) all signals that Python has set to SIG_IGN are restored to SIG_DFL in the child process before the exec. Currently this includes the SIGPIPE, SIGXFZ and SIGXFSZ signals. (POSIX only)

버전 3.2에서 변경: restore_signals was added.

If start_new_session is true the setsid() system call will be made in the child process prior to the execution of the subprocess. (POSIX only)

버전 3.2에서 변경: start_new_session was added.

If env is not None, it must be a mapping that defines the environment variables for the new process; these are used instead of the default behavior of inheriting the current process’ environment.

참고

If specified, env must provide any variables required for the program to execute. On Windows, in order to run a side-by-side assembly [https://en.wikipedia.org/wiki/Side-by-Side_Assembly] the specified env must include a valid SystemRoot.

If encoding or errors are specified, or text is true, the file objects stdin, stdout and stderr are opened in text mode with the specified encoding and errors, as described above in Frequently Used Arguments. The universal_newlines argument is equivalent to text and is provided for backwards compatibility. By default, file objects are opened in binary mode.

버전 3.6에 추가: encoding and errors were added.

버전 3.7에 추가: text was added as a more readable alias for universal_newlines.

If given, startupinfo will be a STARTUPINFO object, which is passed to the underlying CreateProcess function. creationflags, if given, can be one or more of the following flags:

CREATE_NEW_CONSOLE

CREATE_NEW_PROCESS_GROUP

ABOVE_NORMAL_PRIORITY_CLASS

BELOW_NORMAL_PRIORITY_CLASS

HIGH_PRIORITY_CLASS

IDLE_PRIORITY_CLASS

NORMAL_PRIORITY_CLASS

REALTIME_PRIORITY_CLASS

CREATE_NO_WINDOW

DETACHED_PROCESS

CREATE_DEFAULT_ERROR_MODE

CREATE_BREAKAWAY_FROM_JOB

Popen objects are supported as context managers via the with statement: on exit, standard file descriptors are closed, and the process is waited for.

with Popen(["ifconfig"], stdout=PIPE) as proc:
    log.write(proc.stdout.read())

버전 3.2에서 변경: Added context manager support.

버전 3.6에서 변경: Popen destructor now emits a ResourceWarning warning if the child process is still running.

Exceptions

Exceptions raised in the child process, before the new program has started to execute, will be re-raised in the parent.

The most common exception raised is OSError. This occurs, for example, when trying to execute a non-existent file. Applications should prepare for OSError exceptions.

A ValueError will be raised if Popen is called with invalid arguments.

check_call() and check_output() will raise CalledProcessError if the called process returns a non-zero return code.

All of the functions and methods that accept a timeout parameter, such as call() and Popen.communicate() will raise TimeoutExpired if the timeout expires before the process exits.

Exceptions defined in this module all inherit from SubprocessError.

버전 3.3에 추가: The SubprocessError base class was added.

Security Considerations

Unlike some other popen functions, this implementation will never implicitly call a system shell. This means that all characters, including shell metacharacters, can safely be passed to child processes. If the shell is invoked explicitly, via shell=True, it is the application’s responsibility to ensure that all whitespace and metacharacters are quoted appropriately to avoid shell injection [https://en.wikipedia.org/wiki/Shell_injection#Shell_injection] vulnerabilities.

When using shell=True, the shlex.quote() function can be used to properly escape whitespace and shell metacharacters in strings that are going to be used to construct shell commands.

Popen Objects

Instances of the Popen class have the following methods:

Popen.poll()

Check if child process has terminated. Set and return returncode attribute. Otherwise, returns None.

Popen.wait(timeout=None)

Wait for child process to terminate. Set and return returncode attribute.

If the process does not terminate after timeout seconds, raise a TimeoutExpired exception. It is safe to catch this exception and retry the wait.

참고

This will deadlock when using stdout=PIPE or stderr=PIPE and the child process generates enough output to a pipe such that it blocks waiting for the OS pipe buffer to accept more data. Use Popen.communicate() when using pipes to avoid that.

참고

The function is implemented using a busy loop (non-blocking call and short sleeps). Use the asyncio module for an asynchronous wait: see asyncio.create_subprocess_exec.

버전 3.3에서 변경: timeout was added.

Popen.communicate(input=None, timeout=None)

Interact with process: Send data to stdin. Read data from stdout and stderr, until end-of-file is reached. Wait for process to terminate. The optional input argument should be data to be sent to the child process, or None, if no data should be sent to the child. If streams were opened in text mode, input must be a string. Otherwise, it must be bytes.

communicate() returns a tuple (stdout_data, stderr_data). The data will be strings if streams were opened in text mode; otherwise, bytes.

Note that if you want to send data to the process’s stdin, you need to create the Popen object with stdin=PIPE. Similarly, to get anything other than None in the result tuple, you need to give stdout=PIPE and/or stderr=PIPE too.

If the process does not terminate after timeout seconds, a TimeoutExpired exception will be raised. Catching this exception and retrying communication will not lose any output.

The child process is not killed if the timeout expires, so in order to cleanup properly a well-behaved application should kill the child process and finish communication:

proc = subprocess.Popen(...)
try:
    outs, errs = proc.communicate(timeout=15)
except TimeoutExpired:
    proc.kill()
    outs, errs = proc.communicate()

참고

The data read is buffered in memory, so do not use this method if the data size is large or unlimited.

버전 3.3에서 변경: timeout was added.

Popen.send_signal(signal)

Sends the signal signal to the child.

참고

On Windows, SIGTERM is an alias for terminate(). CTRL_C_EVENT and CTRL_BREAK_EVENT can be sent to processes started with a creationflags parameter which includes CREATE_NEW_PROCESS_GROUP.

Popen.terminate()

Stop the child. On POSIX OSs the method sends SIGTERM to the child. On Windows the Win32 API function TerminateProcess() is called to stop the child.

Popen.kill()

Kills the child. On POSIX OSs the function sends SIGKILL to the child. On Windows kill() is an alias for terminate().

The following attributes are also available:

Popen.args

The args argument as it was passed to Popen – a sequence of program arguments or else a single string.

버전 3.3에 추가.

Popen.stdin

If the stdin argument was PIPE, this attribute is a writeable stream object as returned by open(). If the encoding or errors arguments were specified or the universal_newlines argument was True, the stream is a text stream, otherwise it is a byte stream. If the stdin argument was not PIPE, this attribute is None.

Popen.stdout

If the stdout argument was PIPE, this attribute is a readable stream object as returned by open(). Reading from the stream provides output from the child process. If the encoding or errors arguments were specified or the universal_newlines argument was True, the stream is a text stream, otherwise it is a byte stream. If the stdout argument was not PIPE, this attribute is None.

Popen.stderr

If the stderr argument was PIPE, this attribute is a readable stream object as returned by open(). Reading from the stream provides error output from the child process. If the encoding or errors arguments were specified or the universal_newlines argument was True, the stream is a text stream, otherwise it is a byte stream. If the stderr argument was not PIPE, this attribute is None.

경고

Use communicate() rather than .stdin.write, .stdout.read or .stderr.read to avoid deadlocks due to any of the other OS pipe buffers filling up and blocking the child process.

Popen.pid

The process ID of the child process.

Note that if you set the shell argument to True, this is the process ID of the spawned shell.

Popen.returncode

The child return code, set by poll() and wait() (and indirectly by communicate()). A None value indicates that the process hasn’t terminated yet.

A negative value -N indicates that the child was terminated by signal N (POSIX only).

Windows Popen Helpers

The STARTUPINFO class and following constants are only available on Windows.

class subprocess.STARTUPINFO(*, dwFlags=0, hStdInput=None, hStdOutput=None, hStdError=None, wShowWindow=0, lpAttributeList=None)

Partial support of the Windows STARTUPINFO [https://msdn.microsoft.com/en-us/library/ms686331(v=vs.85).aspx] structure is used for Popen creation. The following attributes can be set by passing them as keyword-only arguments.

버전 3.7에서 변경: Keyword-only argument support was added.

dwFlags

A bit field that determines whether certain STARTUPINFO attributes are used when the process creates a window.

si = subprocess.STARTUPINFO()
si.dwFlags = subprocess.STARTF_USESTDHANDLES | subprocess.STARTF_USESHOWWINDOW

hStdInput

If dwFlags specifies STARTF_USESTDHANDLES, this attribute is the standard input handle for the process. If STARTF_USESTDHANDLES is not specified, the default for standard input is the keyboard buffer.

hStdOutput

If dwFlags specifies STARTF_USESTDHANDLES, this attribute is the standard output handle for the process. Otherwise, this attribute is ignored and the default for standard output is the console window’s buffer.

hStdError

If dwFlags specifies STARTF_USESTDHANDLES, this attribute is the standard error handle for the process. Otherwise, this attribute is ignored and the default for standard error is the console window’s buffer.

wShowWindow

If dwFlags specifies STARTF_USESHOWWINDOW, this attribute can be any of the values that can be specified in the nCmdShow parameter for the ShowWindow [https://msdn.microsoft.com/en-us/library/ms633548(v=vs.85).aspx] function, except for SW_SHOWDEFAULT. Otherwise, this attribute is ignored.

SW_HIDE is provided for this attribute. It is used when Popen is called with shell=True.

lpAttributeList

A dictionary of additional attributes for process creation as given in STARTUPINFOEX, see UpdateProcThreadAttribute [https://msdn.microsoft.com/en-us/library/windows/desktop/ms686880(v=vs.85).aspx].

Supported attributes:

handle_list

Sequence of handles that will be inherited. close_fds must be true if non-empty.

The handles must be temporarily made inheritable by os.set_handle_inheritable() when passed to the Popen constructor, else OSError will be raised with Windows error ERROR_INVALID_PARAMETER (87).

경고

In a multithreaded process, use caution to avoid leaking handles that are marked inheritable when combining this feature with concurrent calls to other process creation functions that inherit all handles such as os.system(). This also applies to standard handle redirection, which temporarily creates inheritable handles.

버전 3.7에 추가.

Windows Constants

The subprocess module exposes the following constants.

subprocess.STD_INPUT_HANDLE

The standard input device. Initially, this is the console input buffer, CONIN$.

subprocess.STD_OUTPUT_HANDLE

The standard output device. Initially, this is the active console screen buffer, CONOUT$.

subprocess.STD_ERROR_HANDLE

The standard error device. Initially, this is the active console screen buffer, CONOUT$.

subprocess.SW_HIDE

Hides the window. Another window will be activated.

subprocess.STARTF_USESTDHANDLES

Specifies that the STARTUPINFO.hStdInput, STARTUPINFO.hStdOutput, and STARTUPINFO.hStdError attributes contain additional information.

subprocess.STARTF_USESHOWWINDOW

Specifies that the STARTUPINFO.wShowWindow attribute contains additional information.

subprocess.CREATE_NEW_CONSOLE

The new process has a new console, instead of inheriting its parent’s console (the default).

subprocess.CREATE_NEW_PROCESS_GROUP

A Popen creationflags parameter to specify that a new process group will be created. This flag is necessary for using os.kill() on the subprocess.

This flag is ignored if CREATE_NEW_CONSOLE is specified.

subprocess.ABOVE_NORMAL_PRIORITY_CLASS

A Popen creationflags parameter to specify that a new process will have an above average priority.

버전 3.7에 추가.

subprocess.BELOW_NORMAL_PRIORITY_CLASS

A Popen creationflags parameter to specify that a new process will have a below average priority.

버전 3.7에 추가.

subprocess.HIGH_PRIORITY_CLASS

A Popen creationflags parameter to specify that a new process will have a high priority.

버전 3.7에 추가.

subprocess.IDLE_PRIORITY_CLASS

A Popen creationflags parameter to specify that a new process will have an idle (lowest) priority.

버전 3.7에 추가.

subprocess.NORMAL_PRIORITY_CLASS

A Popen creationflags parameter to specify that a new process will have an normal priority. (default)

버전 3.7에 추가.

subprocess.REALTIME_PRIORITY_CLASS

A Popen creationflags parameter to specify that a new process will have realtime priority. You should almost never use REALTIME_PRIORITY_CLASS, because this interrupts system threads that manage mouse input, keyboard input, and background disk flushing. This class can be appropriate for applications that “talk” directly to hardware or that perform brief tasks that should have limited interruptions.

버전 3.7에 추가.

subprocess.CREATE_NO_WINDOW

A Popen creationflags parameter to specify that a new process will not create a window.

버전 3.7에 추가.

subprocess.DETACHED_PROCESS

A Popen creationflags parameter to specify that a new process will not inherit its parent’s console. This value cannot be used with CREATE_NEW_CONSOLE.

버전 3.7에 추가.

subprocess.CREATE_DEFAULT_ERROR_MODE

A Popen creationflags parameter to specify that a new process does not inherit the error mode of the calling process. Instead, the new process gets the default error mode. This feature is particularly useful for multithreaded shell applications that run with hard errors disabled.

버전 3.7에 추가.

subprocess.CREATE_BREAKAWAY_FROM_JOB

A Popen creationflags parameter to specify that a new process is not associated with the job.

버전 3.7에 추가.

Older high-level API

Prior to Python 3.5, these three functions comprised the high level API to subprocess. You can now use run() in many cases, but lots of existing code calls these functions.

subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False, cwd=None, timeout=None, **other_popen_kwargs)

Run the command described by args. Wait for command to complete, then return the returncode attribute.

Code needing to capture stdout or stderr should use run() instead:

run(…).returncode

To suppress stdout or stderr, supply a value of DEVNULL.

The arguments shown above are merely some common ones. The full function signature is the same as that of the Popen constructor - this function passes all supplied arguments other than timeout directly through to that interface.

참고

Do not use stdout=PIPE or stderr=PIPE with this function. The child process will block if it generates enough output to a pipe to fill up the OS pipe buffer as the pipes are not being read from.

버전 3.3에서 변경: timeout was added.

버전 3.7.17에서 변경: Changed Windows shell search order for shell=True. The current directory and %PATH% are replaced with %COMSPEC% and %SystemRoot%\System32\cmd.exe. As a result, dropping a malicious program named cmd.exe into a current directory no longer works.

subprocess.check_call(args, *, stdin=None, stdout=None, stderr=None, shell=False, cwd=None, timeout=None, **other_popen_kwargs)

Run command with arguments. Wait for command to complete. If the return code was zero then return, otherwise raise CalledProcessError. The CalledProcessError object will have the return code in the returncode attribute.

Code needing to capture stdout or stderr should use run() instead:

run(…, check=True)

To suppress stdout or stderr, supply a value of DEVNULL.

The arguments shown above are merely some common ones. The full function signature is the same as that of the Popen constructor - this function passes all supplied arguments other than timeout directly through to that interface.

참고

Do not use stdout=PIPE or stderr=PIPE with this function. The child process will block if it generates enough output to a pipe to fill up the OS pipe buffer as the pipes are not being read from.

버전 3.3에서 변경: timeout was added.

버전 3.7.17에서 변경: Changed Windows shell search order for shell=True. The current directory and %PATH% are replaced with %COMSPEC% and %SystemRoot%\System32\cmd.exe. As a result, dropping a malicious program named cmd.exe into a current directory no longer works.

subprocess.check_output(args, *, stdin=None, stderr=None, shell=False, cwd=None, encoding=None, errors=None, universal_newlines=None, timeout=None, text=None, **other_popen_kwargs)

Run command with arguments and return its output.

If the return code was non-zero it raises a CalledProcessError. The CalledProcessError object will have the return code in the returncode attribute and any output in the output attribute.

This is equivalent to:

run(..., check=True, stdout=PIPE).stdout

The arguments shown above are merely some common ones. The full function signature is largely the same as that of run() - most arguments are passed directly through to that interface. However, explicitly passing input=None to inherit the parent’s standard input file handle is not supported.

By default, this function will return the data as encoded bytes. The actual encoding of the output data may depend on the command being invoked, so the decoding to text will often need to be handled at the application level.

This behaviour may be overridden by setting text, encoding, errors, or universal_newlines to True as described in Frequently Used Arguments and run().

To also capture standard error in the result, use stderr=subprocess.STDOUT:

>>> subprocess.check_output(
...     "ls non_existent_file; exit 0",
...     stderr=subprocess.STDOUT,
...     shell=True)
'ls: non_existent_file: No such file or directory\n'

버전 3.1에 추가.

버전 3.3에서 변경: timeout was added.

버전 3.4에서 변경: Support for the input keyword argument was added.

버전 3.6에서 변경: encoding and errors were added. See run() for details.

버전 3.7에 추가: text was added as a more readable alias for universal_newlines.

버전 3.7.17에서 변경: Changed Windows shell search order for shell=True. The current directory and %PATH% are replaced with %COMSPEC% and %SystemRoot%\System32\cmd.exe. As a result, dropping a malicious program named cmd.exe into a current directory no longer works.

Replacing Older Functions with the subprocess Module

In this section, “a becomes b” means that b can be used as a replacement for a.

참고

All “a” functions in this section fail (more or less) silently if the executed program cannot be found; the “b” replacements raise OSError instead.

In addition, the replacements using check_output() will fail with a CalledProcessError if the requested operation produces a non-zero return code. The output is still available as the output attribute of the raised exception.

In the following examples, we assume that the relevant functions have already been imported from the subprocess module.

Replacing /bin/sh shell backquote

output=`mycmd myarg`

becomes:

output = check_output(["mycmd", "myarg"])

Replacing shell pipeline

output=`dmesg | grep hda`

becomes:

p1 = Popen(["dmesg"], stdout=PIPE)
p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
p1.stdout.close()  # Allow p1 to receive a SIGPIPE if p2 exits.
output = p2.communicate()[0]

The p1.stdout.close() call after starting the p2 is important in order for p1 to receive a SIGPIPE if p2 exits before p1.

Alternatively, for trusted input, the shell’s own pipeline support may still be used directly:

output=`dmesg | grep hda`

becomes:

output=check_output("dmesg | grep hda", shell=True)

Replacing os.system()

sts = os.system("mycmd" + " myarg")
# becomes
sts = call("mycmd" + " myarg", shell=True)

Notes:

Calling the program through the shell is usually not required.

A more realistic example would look like this:

try:
    retcode = call("mycmd" + " myarg", shell=True)
    if retcode < 0:
        print("Child was terminated by signal", -retcode, file=sys.stderr)
    else:
        print("Child returned", retcode, file=sys.stderr)
except OSError as e:
    print("Execution failed:", e, file=sys.stderr)

Replacing the os.spawn family

P_NOWAIT example:

pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg")
==>
pid = Popen(["/bin/mycmd", "myarg"]).pid

P_WAIT example:

retcode = os.spawnlp(os.P_WAIT, "/bin/mycmd", "mycmd", "myarg")
==>
retcode = call(["/bin/mycmd", "myarg"])

Vector example:

os.spawnvp(os.P_NOWAIT, path, args)
==>
Popen([path] + args[1:])

Environment example:

os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env)
==>
Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"})

Replacing os.popen(), os.popen2(), os.popen3()

(child_stdin, child_stdout) = os.popen2(cmd, mode, bufsize)
==>
p = Popen(cmd, shell=True, bufsize=bufsize,
          stdin=PIPE, stdout=PIPE, close_fds=True)
(child_stdin, child_stdout) = (p.stdin, p.stdout)

(child_stdin,
 child_stdout,
 child_stderr) = os.popen3(cmd, mode, bufsize)
==>
p = Popen(cmd, shell=True, bufsize=bufsize,
          stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)
(child_stdin,
 child_stdout,
 child_stderr) = (p.stdin, p.stdout, p.stderr)

(child_stdin, child_stdout_and_stderr) = os.popen4(cmd, mode, bufsize)
==>
p = Popen(cmd, shell=True, bufsize=bufsize,
          stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
(child_stdin, child_stdout_and_stderr) = (p.stdin, p.stdout)

Return code handling translates as follows:

pipe = os.popen(cmd, 'w')
...
rc = pipe.close()
if rc is not None and rc >> 8:
    print("There were some errors")
==>
process = Popen(cmd, stdin=PIPE)
...
process.stdin.close()
if process.wait() != 0:
    print("There were some errors")

Replacing functions from the popen2 module

참고

If the cmd argument to popen2 functions is a string, the command is executed through /bin/sh. If it is a list, the command is directly executed.

(child_stdout, child_stdin) = popen2.popen2("somestring", bufsize, mode)
==>
p = Popen("somestring", shell=True, bufsize=bufsize,
          stdin=PIPE, stdout=PIPE, close_fds=True)
(child_stdout, child_stdin) = (p.stdout, p.stdin)

(child_stdout, child_stdin) = popen2.popen2(["mycmd", "myarg"], bufsize, mode)
==>
p = Popen(["mycmd", "myarg"], bufsize=bufsize,
          stdin=PIPE, stdout=PIPE, close_fds=True)
(child_stdout, child_stdin) = (p.stdout, p.stdin)

popen2.Popen3 and popen2.Popen4 basically work as subprocess.Popen, except that:

Popen raises an exception if the execution fails.

The capturestderr argument is replaced with the stderr argument.

stdin=PIPE and stdout=PIPE must be specified.

popen2 closes all file descriptors by default, but you have to specify close_fds=True with Popen to guarantee this behavior on all platforms or past Python versions.

Legacy Shell Invocation Functions

This module also provides the following legacy functions from the 2.x commands module. These operations implicitly invoke the system shell and none of the guarantees described above regarding security and exception handling consistency are valid for these functions.

subprocess.getstatusoutput(cmd)

Return (exitcode, output) of executing cmd in a shell.

Execute the string cmd in a shell with Popen.check_output() and return a 2-tuple (exitcode, output). The locale encoding is used; see the notes on Frequently Used Arguments for more details.

A trailing newline is stripped from the output. The exit code for the command can be interpreted as the return code of subprocess. Example:

>>> subprocess.getstatusoutput('ls /bin/ls')
(0, '/bin/ls')
>>> subprocess.getstatusoutput('cat /bin/junk')
(1, 'cat: /bin/junk: No such file or directory')
>>> subprocess.getstatusoutput('/bin/junk')
(127, 'sh: /bin/junk: not found')
>>> subprocess.getstatusoutput('/bin/kill $$')
(-15, '')

Availability: POSIX & Windows.

버전 3.3.4에서 변경: Windows support was added.

The function now returns (exitcode, output) instead of (status, output) as it did in Python 3.3.3 and earlier. exitcode has the same value as returncode.

subprocess.getoutput(cmd)

Return output (stdout and stderr) of executing cmd in a shell.

Like getstatusoutput(), except the exit code is ignored and the return value is a string containing the command’s output. Example:

>>> subprocess.getoutput('ls /bin/ls')
'/bin/ls'

Availability: POSIX & Windows.

버전 3.3.4에서 변경: Windows support added

Notes

Converting an argument sequence to a string on Windows

On Windows, an args sequence is converted to a string that can be parsed using the following rules (which correspond to the rules used by the MS C runtime):

Arguments are delimited by white space, which is either a space or a tab.

A string surrounded by double quotation marks is interpreted as a single argument, regardless of white space contained within. A quoted string can be embedded in an argument.

A double quotation mark preceded by a backslash is interpreted as a literal double quotation mark.

Backslashes are interpreted literally, unless they immediately precede a double quotation mark.

If backslashes immediately precede a double quotation mark, every pair of backslashes is interpreted as a literal backslash. If the number of backslashes is odd, the last backslash escapes the next double quotation mark as described in rule 3.

더 보기

shlex

Module which provides function to parse and escape command lines.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

동시 실행 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

동시 실행 »

|

sched — 이벤트 스케줄러

소스 코드: Lib/sched.py [https://github.com/python/cpython/tree/3.7/Lib/sched.py]

sched 모듈은 범용 이벤트 스케줄러를 구현하는 클래스를 정의합니다:

class sched.scheduler(timefunc=time.monotonic, delayfunc=time.sleep)

scheduler 클래스는 이벤트 스케줄링을 위한 일반적인 인터페이스를 정의합니다. “외부 세계”를 실제로 다루기 위해 두 개의 함수를 요구합니다 — timefunc는 인자 없이 호출할 수 있어야 하고, 숫자(단위가 무엇이든, “시간”)를 반환합니다. delayfunc 함수는 하나의 인자로 호출 가능해야 하며, timefunc의 출력과 호환되어야 하고, 그 시간 동안 지연시켜야 합니다. delayfunc는 다중 스레드 응용 프로그램에서 다른 스레드가 실행할 기회를 주기 위해 각 이벤트가 실행된 후 0 인자로 호출되기도 합니다.

버전 3.3에서 변경: timefunc 와 delayfunc 매개 변수는 선택적입니다.

버전 3.3에서 변경: scheduler 클래스는 다중 스레드 환경에서 안전하게 사용할 수 있습니다.

예제:

>>> import sched, time
>>> s = sched.scheduler(time.time, time.sleep)
>>> def print_time(a='default'):
...     print("From print_time", time.time(), a)
...
>>> def print_some_times():
...     print(time.time())
...     s.enter(10, 1, print_time)
...     s.enter(5, 2, print_time, argument=('positional',))
...     s.enter(5, 1, print_time, kwargs={'a': 'keyword'})
...     s.run()
...     print(time.time())
...
>>> print_some_times()
930343690.257
From print_time 930343695.274 positional
From print_time 930343695.275 keyword
From print_time 930343700.273 default
930343700.276

스케줄러 객체

scheduler 인스턴스에는 다음과 같은 메서드와 어트리뷰트가 있습니다:

scheduler.enterabs(time, priority, action, argument=(), kwargs={})

새 이벤트를 예약합니다. time 인자는 생성자에 전달된 timefunc 함수의 반환 값과 호환되는 숫자 형이어야 합니다. 같은 time으로 예약된 이벤트는 priority 순으로 실행됩니다. 낮은 숫자는 높은 우선순위를 나타냅니다.

이벤트를 실행하는 것은 action(*argument, **kwargs)를 실행하는 것을 의미합니다. argument는 action에 대한 위치 인자가 들어있는 시퀀스입니다. kwargs는 action에 대한 키워드 인자가 들어있는 딕셔너리입니다.

반환 값은 나중에 이벤트를 취소하는 데 사용할 수 있는 이벤트입니다 (cancel() 참조).

버전 3.3에서 변경: argument 매개 변수는 선택적입니다.

버전 3.3에 추가: kwargs 매개 변수가 추가되었습니다.

scheduler.enter(delay, priority, action, argument=(), kwargs={})

delay 시간 단위 후로 이벤트를 예약합니다. 상대 시간 이외의 다른 인자, 효과 및 반환 값은 enterabs()와 같습니다.

버전 3.3에서 변경: argument 매개 변수는 선택적입니다.

버전 3.3에 추가: kwargs 매개 변수가 추가되었습니다.

scheduler.cancel(event)

큐에서 이벤트를 제거합니다. event가 현재 큐에 없으면, 이 메서드는 ValueError를 발생시킵니다.

scheduler.empty()

Return True if the event queue is empty.

scheduler.run(blocking=True)

모든 예약된 이벤트를 실행합니다. 이 메서드는 다음 이벤트를 (생성자에 전달된 delayfunc() 함수를 사용하여) 기다린 다음 예약된 이벤트가 소진될 때까지 계속 실행합니다.

blocking이 거짓이면 시간이 도래한 (있다면) 예약된 이벤트를 모두 실행한 다음, 스케줄러에서 다음 예약된 호출까지의 (있다면) 대기시간을 반환합니다 .

action 이나 delayfunc는 예외를 발생시킬 수 있습니다. 두 경우 모두, 스케줄러는 일관된 상태를 유지하고 예외를 전파합니다. action에 의해 예외가 발생하면, 이후에 run()을 호출할 때 이벤트를 실행하려고 하지 않습니다.

일련의 이벤트가 다음 이벤트 이전에 사용 가능한 시간보다 실행하는 데 더 오래 걸리면, 스케줄러는 단순히 지연됩니다. 어떤 이벤트도 삭제되지 않습니다; 더는 적절하지 않은 이벤트를 취소할 책임은 호출 코드에 있습니다.

버전 3.3에 추가: blocking 매개 변수가 추가되었습니다.

scheduler.queue

남은 이벤트의 리스트를 실행될 순서대로 반환하는 읽기 전용 어트리뷰트입니다. 각 이벤트는 다음과 같은 필드를 갖는 네임드 튜플로 표시됩니다: time, priority, action, argument, kwargs.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

동시 실행 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

동시 실행 »

|

queue — 동기화된 큐 클래스

소스 코드: Lib/queue.py [https://github.com/python/cpython/tree/3.7/Lib/queue.py]

The queue module implements multi-producer, multi-consumer queues. It is especially useful in threaded programming when information must be exchanged safely between multiple threads. The Queue class in this module implements all the required locking semantics. It depends on the availability of thread support in Python; see the threading module.

모듈은 항목을 꺼내는 순서 만 다른 3가지 유형의 큐를 구현합니다. FIFO 큐에서는, 추가된 첫 번째 작업이 처음으로 꺼내지는 작업입니다. LIFO 큐에서는, 가장 최근에 추가된 항목이 처음으로 꺼내지는 항목입니다 (스택처럼 작동합니다). 우선순위(priority) 큐에서는, 항목이 정렬된 상태로 유지되고 (heapq 모듈을 사용합니다) 가장 낮은 값을 갖는 항목이 먼저 꺼내집니다.

내부적으로, 이러한 3가지 유형의 큐는 록을 사용하여 경쟁 스레드를 일시적으로 블록합니다; 그러나, 스레드 내에서의 재진입을 처리하도록 설계되지는 않았습니다.

또한, 이 모듈은 “간단한” FIFO 큐 유형인 SimpleQueue를 구현합니다. 이 특정 구현은 작은 기능을 포기하는 대신 추가 보장을 제공합니다.

queue 모듈은 다음 클래스와 예외를 정의합니다:

class queue.Queue(maxsize=0)

FIFO 큐의 생성자. maxsize는 큐에 배치할 수 있는 항목 수에 대한 상한을 설정하는 정수입니다. 일단, 이 크기에 도달하면, 큐 항목이 소비될 때까지 삽입이 블록 됩니다. maxsize가 0보다 작거나 같으면, 큐 크기는 무한합니다.

class queue.LifoQueue(maxsize=0)

LIFO 큐의 생성자. maxsize는 큐에 배치할 수 있는 항목 수에 대한 상한을 설정하는 정수입니다. 일단, 이 크기에 도달하면, 큐 항목이 소비될 때까지 삽입이 블록 됩니다. maxsize가 0보다 작거나 같으면, 큐 크기는 무한합니다.

class queue.PriorityQueue(maxsize=0)

우선순위 큐의 생성자. maxsize는 큐에 배치할 수 있는 항목 수에 대한 상한을 설정하는 정수입니다. 일단, 이 크기에 도달하면, 큐 항목이 소비될 때까지 삽입이 블록 됩니다. maxsize가 0보다 작거나 같으면, 큐 크기는 무한합니다.

가장 낮은 값을 갖는 항목이 먼저 꺼내집니다 (가장 낮은 값을 갖는 항목은 sorted(list(entries))[0] 에 의해 반환되는 항목입니다). 항목의 전형적인 패턴은 (priority_number, data) 형식의 튜플입니다.

data 요소를 비교할 수 없으면, 데이터는 데이터 항목을 무시하고 우선순위 숫자만 비교하는 클래스로 감쌀 수 있습니다:

from dataclasses import dataclass, field
from typing import Any

@dataclass(order=True)
class PrioritizedItem:
    priority: int
    item: Any=field(compare=False)

class queue.SimpleQueue

상한 없는 FIFO 큐의 생성자. 단순 큐에는 작업 추적과 같은 고급 기능이 없습니다.

버전 3.7에 추가.

exception queue.Empty

비 블로킹 get()(또는 get_nowait())이 비어있는 Queue 객체에 호출될 때 발생하는 예외.

exception queue.Full

비 블로킹 put()(또는 put_nowait())이 가득 찬 Queue 객체에 호출될 때 발생하는 예외.

큐 객체

큐 객체(Queue, LifoQueue 또는 PriorityQueue)는 아래에 설명된 공용 메서드를 제공합니다.

Queue.qsize()

큐의 대략의 크기를 돌려줍니다. 주의하십시오, qsize() > 0 은 후속 get()이 블록 되지 않는다는 것을 보장하지 않으며, qsize() < maxsize 도 put()이 블록 되지 않는다고 보장하지 않습니다.

Queue.empty()

큐가 비어 있으면 True를, 그렇지 않으면 False를 반환합니다. empty()가 True를 반환하면, put()에 대한 후속 호출이 블록 되지 않는다고 보장하는 것은 아닙니다. 마찬가지로 empty()가 False를 반환하면, get()에 대한 후속 호출이 블록 되지 않는다고 보장하는 것은 아닙니다.

Queue.full()

큐가 가득 차면 True를, 그렇지 않으면 False를 반환합니다. full()이 True를 반환하면, get()에 대한 후속 호출이 블록 되지 않는다고 보장하는 것은 아닙니다. 마찬가지로 full()이 False를 반환하면, put()에 대한 후속 호출이 블록 되지 않는다고 보장하는 것은 아닙니다.

Queue.put(item, block=True, timeout=None)

큐에 item을 넣습니다. 선택적 인자 block이 참이고 timeout이 None(기본값)이면, 사용 가능한 슬롯이 확보될 때까지 필요하면 블록합니다. timeout이 양수면, 최대 timeout 초 동안 블록하고 그 시간 내에 사용 가능한 슬롯이 없으면 Full 예외가 발생합니다. 그렇지 않으면 (block이 거짓), 빈 슬롯이 즉시 사용할 수 있으면 큐에 항목을 넣고, 그렇지 않으면 Full 예외를 발생시킵니다 (이때 timeout은 무시됩니다).

Queue.put_nowait(item)

put(item, False)와 동등합니다.

Queue.get(block=True, timeout=None)

큐에서 항목을 제거하고 반환합니다. 선택적 인자 block이 참이고 timeout이 None(기본값)이면, 항목이 사용 가능할 때까지 필요하면 블록합니다. timeout이 양수면, 최대 timeout 초 동안 블록하고 그 시간 내에 사용 가능한 항목이 없으면 Empty 예외가 발생합니다. 그렇지 않으면 (block이 거짓), 즉시 사용할 수 있는 항목이 있으면 반환하고, 그렇지 않으면 Empty 예외를 발생시킵니다 (이때 timeout은 무시됩니다).

POSIX 시스템에서 3.0 이전에서, 윈도우의 모든 버전에서, block이 참이고 timeout이 None이면, 이 연산은 하부 록에 대한 중단되지 않는(uninterruptible) 대기로 들어갑니다. 이는 어떤 예외도 발생할 수 없음을 뜻하고, 특히 SIGINT가 KeyboardInterrupt를 일으키지 않습니다.

Queue.get_nowait()

get(False)와 동등합니다.

큐에 넣은 작업이 데몬 소비자 스레드에 의해 완전히 처리되었는지를 추적하는 것을 지원하는 두 가지 메서드가 제공됩니다.

Queue.task_done()

앞서 큐에 넣은 작업이 완료되었음을 나타냅니다. 큐 소비자 스레드에서 사용됩니다. 작업을 꺼내는 데 사용되는 get()마다, 후속 task_done() 호출은 작업에 대한 처리가 완료되었음을 큐에 알려줍니다.

join()이 현재 블로킹 중이면, 모든 항목이 처리되면 (큐로 put() 된 모든 항목에 대해 task_done() 호출이 수신되었음을 뜻합니다) 재개됩니다.

큐에 있는 항목보다 더 많이 호출되면 ValueError를 발생시킵니다.

Queue.join()

큐의 모든 항목을 꺼내서 처리할 때까지 블록합니다.

완료되지 않은 작업 카운트는 항목이 큐에 추가될 때마다 올라갑니다. 소비자 스레드가 task_done()을 호출해서 항목을 꺼내고 작업이 모두 완료되었음을 나타낼 때마다 카운트가 내려갑니다. 완료되지 않은 작업 카운트가 0으로 떨어지면, join()이 블록 해제됩니다.

큐에 포함된 작업이 완료될 때까지 대기하는 방법의 예:

def worker():
    while True:
        item = q.get()
        if item is None:
            break
        do_work(item)
        q.task_done()

q = queue.Queue()
threads = []
for i in range(num_worker_threads):
    t = threading.Thread(target=worker)
    t.start()
    threads.append(t)

for item in source():
    q.put(item)

# block until all tasks are done
q.join()

# stop workers
for i in range(num_worker_threads):
    q.put(None)
for t in threads:
    t.join()

SimpleQueue 객체

SimpleQueue 객체는 아래에서 설명하는 공용 메서드를 제공합니다.

SimpleQueue.qsize()

큐의 대략의 크기를 돌려줍니다. 주의하십시오, qsize() > 0 은 후속 get()이 블록 되지 않는다는 것을 보장하지 않습니다.

SimpleQueue.empty()

큐가 비어 있으면 True를, 그렇지 않으면 False를 반환합니다. empty()가 False를 반환하면, get()에 대한 후속 호출이 블록 되지 않는다는 것을 보장하지는 않습니다.

SimpleQueue.put(item, block=True, timeout=None)

item을 큐에 넣습니다. 이 메서드는 결코 블록하지 않고 항상 성공합니다 (메모리 할당 실패와 같은 잠재적 저수준 에러 제외). 선택적 인자 block과 timeout은 무시되고 Queue.put()과의 호환성을 위해서만 제공됩니다.

CPython implementation detail: This method has a C implementation which is reentrant. That is, a put() or get() call can be interrupted by another put() call in the same thread without deadlocking or corrupting internal state inside the queue. This makes it appropriate for use in destructors such as __del__ methods or weakref callbacks.

SimpleQueue.put_nowait(item)

put(item)과 동등합니다, Queue.put_nowait()와의 호환성을 위해 제공됩니다.

SimpleQueue.get(block=True, timeout=None)

큐에서 항목을 제거하고 반환합니다. 선택적 인자 block이 참이고 timeout이 None(기본값)이면, 항목이 사용 가능할 때까지 필요하면 블록합니다. timeout이 양수면, 최대 timeout 초 동안 블록하고 그 시간 내에 사용 가능한 항목이 없으면 Empty 예외가 발생합니다. 그렇지 않으면 (block이 거짓), 즉시 사용할 수 있는 항목이 있으면 반환하고, 그렇지 않으면 Empty 예외를 발생시킵니다 (이때 timeout은 무시됩니다).

SimpleQueue.get_nowait()

get(False)와 동등합니다.

더 보기

multiprocessing.Queue 클래스

(다중 스레드 대신) 다중 프로세스 문맥에서 사용하기 위한 큐 클래스.

collections.deque is an alternative implementation of unbounded queues with fast atomic append() and popleft() operations that do not require locking.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

동시 실행 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

동시 실행 »

|

_thread — 저수준 스레드 API

이 모듈은 다중 스레드(경량 프로세스 (light-weight processes) 나 태스크 (tasks)라고도 합니다)로 작업하는데 필요한 저수준 기본 요소를 제공합니다 — 전역 데이터 공간을 공유하는 여러 개의 제어 스레드를 뜻합니다. 동기화를 위해서, 간단한 록(뮤텍스 (mutexes)나 이진 세마포어 (binary semaphores)라고도 합니다)이 제공됩니다. threading 모듈은 이 모듈 위에 구축되어 사용하기 쉬운 고수준의 스레딩 API를 제공합니다.

버전 3.7에서 변경: 이 모듈은 선택 사항이었지만, 이제는 항상 사용할 수 있습니다.

이 모듈은 다음 상수와 함수를 정의합니다:

exception _thread.error

스레드 특정 에러에서 발생합니다.

버전 3.3에서 변경: 이것은 이제 내장 RuntimeError의 동의어입니다.

_thread.LockType

이것은 록 객체의 형입니다.

_thread.start_new_thread(function, args[, kwargs])

새 스레드를 시작하고 식별자를 반환합니다. 스레드는 인자 목록 args(튜플이어야 합니다)로 함수 function을 실행합니다. 선택적 kwargs 인자는 키워드 인자 딕셔너리를 지정합니다. 함수가 반환되면, 스레드는 조용히 종료합니다. 함수가 처리되지 않은 예외로 종료되면, 스택 트레이스가 인쇄된 다음 스레드가 종료합니다 (하지만 다른 스레드는 계속 실행됩니다).

_thread.interrupt_main()

메인 스레드에 도달한 signal.SIGINT 시그널의 효과를 시뮬레이트합니다. 스레드는 이 함수를 사용하여 메인 스레드를 인터럽트 할 수 있습니다.

signal.SIGINT가 파이썬에 의해 처리되지 않으면 (signal.SIG_DFL이나 signal.SIG_IGN으로 설정됩니다), 이 함수는 아무것도 하지 않습니다.

_thread.exit()

SystemExit 예외를 발생시킵니다. 잡히지 않으면, 스레드가 조용히 종료되도록 합니다.

_thread.allocate_lock()

새로운 록 객체를 반환합니다. 록의 메서드는 아래에 설명되어 있습니다. 록은 초기에 잠금 해제되어 있습니다.

_thread.get_ident()

현재 스레드의 ‘스레드 식별자(thread identifier)’를 반환합니다. 이것은 0이 아닌 정수입니다. 그 값은 직접적인 의미가 없습니다; 이것은 예를 들어 스레드 특정 데이터의 딕셔너리를 인덱싱하는 데 사용되는 매직 쿠키로 사용하려는 의도입니다. 스레드 식별자는 스레드가 종료되고 다른 스레드가 만들어질 때 재활용될 수 있습니다.

_thread.stack_size([size])

새로운 스레드를 만들 때 사용된 스레드의 스택 크기를 반환합니다. 선택적 size 인자는 이후에 만들어지는 스레드에 사용할 스택 크기를 지정하며, 0(플랫폼 또는 구성된 기본값을 사용합니다)이나 최소 32,768(32 KiB)의 양의 정숫값이어야 합니다. size를 지정하지 않으면 0이 사용됩니다. 스레드 스택 크기 변경이 지원되지 않으면, RuntimeError가 발생합니다. 지정된 스택 크기가 유효하지 않으면, ValueError가 발생하고, 스택 크기는 변경되지 않습니다. 32 KiB는 현재 인터프리터 자체에 충분한 스택 공간을 보장하기 위해 지원되는 최소 스택 크기 값입니다. 일부 플랫폼에서는 스택 크기 값에 특별한 제한이 있을 수 있습니다, 가령 최소 스택 크기 > 32KB를 요구하거나 시스템 메모리 페이지 크기의 배수로 할당하는 것을 요구할 수 있습니다 - 자세한 내용은 플랫폼 설명서를 참조하십시오 (4 KiB 페이지가 일반적입니다; 더 구체적인 정보가 없으면 스택 크기로 4096의 배수를 사용하는 것이 제안된 방법입니다).

가용성: 윈도우, POSIX 스레드가 있는 시스템.

_thread.TIMEOUT_MAX

Lock.acquire()의 timeout 매개 변수에 허용되는 최댓값. 이 값보다 큰 timeout을 지정하면 OverflowError가 발생합니다.

버전 3.2에 추가.

록 객체에는 다음과 같은 메서드가 있습니다:

lock.acquire(waitflag=1, timeout=-1)

선택적 인자가 아무것도 없으면, 이 메서드는 조건 없이 록을 획득합니다, 필요하면 다른 스레드가 록을 해제할 때까지 대기합니다 (한 번에 하나의 스레드만 록을 획득할 수 있습니다 — 이것이 록의 존재 이유입니다).

정수 waitflag 인자가 있으면, 행동은 그 값에 따라 다릅니다: 0이면 대기하지 않고 즉시 획득할 수 있을 때만 록이 획득되고, 0이 아니면 위와 같이 록이 조건 없이 획득됩니다.

부동 소수점 timeout 인자가 있고 양수이면, 반환하기 전에 대기할 최대 시간을 초로 지정합니다. 음의 timeout 인자는 제한 없는 대기를 지정합니다. waitflag이 0이면 timeout을 지정할 수 없습니다.

록이 성공적으로 획득되면 반환 값은 True이고, 그렇지 않으면 False입니다.

버전 3.2에서 변경: timeout 매개 변수가 추가되었습니다.

버전 3.2에서 변경: 록 획득은 이제 POSIX의 시그널에 의해 중단될 수 있습니다.

lock.release()

록을 해제합니다. 록은 반드시 이전에 획득된 것이어야 하지만, 반드시 같은 스레드에 의해 획득된 것일 필요는 없습니다.

lock.locked()

록의 상태를 반환합니다: 어떤 스레드에 의해 획득되었으면 True, 그렇지 않으면 False를 반환합니다.

이러한 메서드 외에도, with 문을 통해 록 객체를 사용할 수도 있습니다, 예를 들어:

import _thread

a_lock = _thread.allocate_lock()

with a_lock:
    print("a_lock is locked while this executes")

주의 사항:

스레드는 이상한 방식으로 인터럽트와 상호 작용합니다: KeyboardInterrupt 예외는 임의의 스레드가 수신합니다. (signal 모듈을 사용할 수 있으면, 인터럽트는 항상 메인 스레드로 갑니다.)

sys.exit()를 호출하거나 SystemExit 예외를 발생시키는 것은 _thread.exit()를 호출하는 것과 동등합니다.

록에 대한 acquire() 메서드를 인터럽트 할 수 없습니다 — 록이 획득된 후에 KeyboardInterrupt 예외가 발생합니다.

메인 스레드가 종료할 때, 다른 스레드가 살아남는지는 시스템이 정의합니다. 대부분 시스템에서, try … finally 절을 실행하거나 객체 파괴자(destructor)를 실행하지 않고 강제 종료됩니다.

메인 스레드가 종료할 때, (try … finally 절이 적용되는 것을 제외하고는) 일반적인 정리 작업을 수행하지 않으며, 표준 I/O 파일은 플러시 되지 않습니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

동시 실행 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

동시 실행 »

|

_dummy_thread — Drop-in replacement for the _thread module

Source code: Lib/_dummy_thread.py [https://github.com/python/cpython/tree/3.7/Lib/_dummy_thread.py]

버전 3.7부터 폐지: Python now always has threading enabled. Please use _thread (or, better, threading) instead.

This module provides a duplicate interface to the _thread module. It was meant to be imported when the _thread module was not provided on a platform.

Be careful to not use this module where deadlock might occur from a thread being created that blocks waiting for another thread to be created. This often occurs with blocking I/O.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

동시 실행 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

동시 실행 »

|

dummy_threading — Drop-in replacement for the threading module

Source code: Lib/dummy_threading.py [https://github.com/python/cpython/tree/3.7/Lib/dummy_threading.py]

버전 3.7부터 폐지: Python now always has threading enabled. Please use threading instead.

This module provides a duplicate interface to the threading module. It was meant to be imported when the _thread module was not provided on a platform.

Be careful to not use this module where deadlock might occur from a thread being created that blocks waiting for another thread to be created. This often occurs with blocking I/O.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

동시 실행 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

|

contextvars — 컨텍스트 변수

이 모듈은 컨텍스트-로컬 상태를 관리, 저장, 액세스하기 위한 API를 제공합니다. ContextVar 클래스는 컨텍스트 변수 를 선언하고 사용하는 데 쓰입니다. copy_context() 함수와 Context 클래스는 비동기 프레임워크에서 현재 컨텍스트를 관리하는 데 사용해야 합니다.

상태가 있는 컨텍스트 관리자는 동시성 코드에서 상태가 예기치 않게 다른 코드로 유출되는 것을 방지하기 위해 threading.local() 대신 컨텍스트 변수를 사용해야 합니다.

자세한 내용은 PEP 567 [https://www.python.org/dev/peps/pep-0567]을 참조하십시오.

버전 3.7에 추가.

컨텍스트 변수

class contextvars.ContextVar(name[, *, default])

이 클래스는 새로운 컨텍스트 변수를 선언하는 데 사용됩니다. 예:

var: ContextVar[int] = ContextVar('var', default=42)

필수 name 매개 변수는 인트로스팩션 및 디버그 목적으로 사용됩니다.

선택적 키워드 전용 default 매개 변수는 변수에 대한 값이 현재 컨텍스트에서 발견되지 않으면 ContextVar.get() 에 의해 반환됩니다.

중요: 컨텍스트 변수는 최상위 모듈 수준에서 만들어져야 하고 클로저에서 만들어져서는 안 됩니다. Context 객체는 컨텍스트 변수에 대해 강한 참조를 유지해서 컨텍스트 변수가 제대로 가비지 수집되지 못하게 합니다.

name

변수의 이름. 읽기 전용 프로퍼티입니다.

버전 3.7.1에 추가.

get([default])

현재 컨텍스트의 컨텍스트 변수에 대한 값을 반환합니다.

현재 컨텍스트에서 변수에 대한 값이 없는 경우 메서드는:

제공된 경우 메서드의 default 인자 값을 반환합니다; 또는

생성 시에 제공된 경우, 컨텍스트 변수의 기본값을 반환합니다; 또는

LookupError 를 발생시킵니다.

set(value)

현재 컨텍스트에서 컨텍스트 변수의 새 값을 설정하려면 호출합니다.

필수 value 인자는 컨텍스트 변수의 새 값입니다.

ContextVar.reset() 메서드를 통해 변수를 이전 값으로 복원하는 데 사용할 수 있는 Token 객체를 반환합니다.

reset(token)

token 을 생성 한 ContextVar.set() 이 사용되기 전의 값으로 컨텍스트 변수를 재설정합니다.

예를 들면:

var = ContextVar('var')

token = var.set('new value')
# code that uses 'var'; var.get() returns 'new value'.
var.reset(token)

# After the reset call the var has no value again, so
# var.get() would raise a LookupError.

class contextvars.Token

Token 객체는 ContextVar.set() 메서드에 의해 반환됩니다. ContextVar.reset() 메서드에 전달해서 변수의 값을 해당 set 이전의 값으로 되돌릴 수 있습니다.

Token.var

읽기 전용 프로퍼티. 토큰을 생성 한 ContextVar 객체를 가리 킵니다.

Token.old_value

읽기 전용 프로퍼티. 토큰을 생성 한 ContextVar.set() 메서드 호출 전 변수의 값으로 설정됩니다. Token.MISSING 은 호출 전에 변수가 설정되지 않았음을 나타냅니다.

Token.MISSING

Token.old_value 에 의해 사용되는 표지 객체.

수동 컨텍스트 관리

contextvars.copy_context()

현재 Context 객체의 복사본을 반환합니다.

다음 코드 조각은 현재 컨텍스트의 복사본을 가져와서 모든 변수와 그 변수에 설정된 값을 출력합니다:

ctx: Context = copy_context()
print(list(ctx.items()))

이 함수는 O(1) 복잡도를 갖고 있습니다. 즉, 몇 가지 컨텍스트 변수가 있는 컨텍스트와 컨텍스트 변수가 잔뜩 있는 컨텍스트에 대해 똑같이 빠르게 작동합니다.

class contextvars.Context

ContextVars 에서 그 값으로의 매핑.

Context() 는 값이 없는 빈 컨텍스트를 만듭니다. 현재 컨텍스트의 복사본을 얻으려면 copy_context() 함수를 사용하십시오.

Context는 collections.abc.Mapping 인터페이스를 구현합니다.

run(callable, *args, **kwargs)

run 메서드가 호출된 컨텍스트 객체에서 callable(*args, **kwargs) 코드를 실행합니다. 실행 결과를 반환하거나 예외가 발생하면 예외를 전파합니다.

callable 이 만드는 모든 컨텍스트 변수에 대한 변경 사항은 컨텍스트 개체에 포함됩니다:

var = ContextVar('var')
var.set('spam')

def main():
    # 'var' was set to 'spam' before
    # calling 'copy_context()' and 'ctx.run(main)', so:
    # var.get() == ctx[var] == 'spam'

    var.set('ham')

    # Now, after setting 'var' to 'ham':
    # var.get() == ctx[var] == 'ham'

ctx = copy_context()

# Any changes that the 'main' function makes to 'var'
# will be contained in 'ctx'.
ctx.run(main)

# The 'main()' function was run in the 'ctx' context,
# so changes to 'var' are contained in it:
# ctx[var] == 'ham'

# However, outside of 'ctx', 'var' is still set to 'spam':
# var.get() == 'spam'

이 메서드는 둘 이상의 OS 스레드에서 같은 컨텍스트 객체에 대해 호출될 때나 재귀적으로 호출될 때 RuntimeError 를 발생시킵니다.

copy()

컨텍스트 객체의 얕은 복사본을 반환합니다.

var in context

context 에 var 의 값이 설정되었으면 True 를, 그렇지 않으면 False를 반환합니다.

context[var]

var ContextVar 변수의 값을 돌려줍니다. 컨텍스트 객체에 변수가 설정되어 있지 않으면 KeyError 가 발생합니다.

get(var[, default])

컨텍스트 객체에 var 의 값이 있으면, var 의 값을 돌려줍니다. 그렇지 않으면 default 를 반환합니다. default 가 주어지지 않으면 None 을 반환합니다.

iter(context)

컨텍스트 객체에 저장된 변수에 대한 이터레이터를 반환합니다.

len(proxy)

컨텍스트 객체에 설정된 변수의 개수를 반환합니다.

keys()

컨텍스트 객체의 모든 변수 목록을 반환합니다.

values()

컨텍스트 객체의 모든 변수의 값 목록을 반환합니다.

items()

컨텍스트 객체에서 모든 변수와 해당 값을 포함하는 2-튜플의 목록을 반환합니다.

asyncio 지원

컨텍스트 변수는 asyncio 에서 기본적으로 지원되며 추가 구성없이 사용할 수 있습니다. 예를 들어, 이것은 컨텍스트 변수를 사용하여, 원격 클라이언트의 주소를 해당 클라이언트를 처리하는 Task에서 사용할 수 있도록 하는 간단한 메아리 서버입니다:

import asyncio
import contextvars

client_addr_var = contextvars.ContextVar('client_addr')

def render_goodbye():
    # The address of the currently handled client can be accessed
    # without passing it explicitly to this function.

    client_addr = client_addr_var.get()
    return f'Good bye, client @ {client_addr}\n'.encode()

async def handle_request(reader, writer):
    addr = writer.transport.get_extra_info('socket').getpeername()
    client_addr_var.set(addr)

    # In any code that we call is now possible to get
    # client's address by calling 'client_addr_var.get()'.

    while True:
        line = await reader.readline()
        print(line)
        if not line.strip():
            break
        writer.write(line)

    writer.write(render_goodbye())
    writer.close()

async def main():
    srv = await asyncio.start_server(
        handle_request, '127.0.0.1', 8081)

    async with srv:
        await srv.serve_forever()

asyncio.run(main())

# To test it you can use telnet:
#     telnet 127.0.0.1 8081

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

|

네트워킹과 프로세스 간 통신

이 장에서 설명하는 모듈은 네트워킹과 프로세스 간 통신을 위한 메커니즘을 제공합니다.

어떤 모듈은 같은 기계에 있는 두 개의 프로세스에서만 작동합니다 (예를 들어, signal과 mmap). 다른 모듈은 두 개 이상의 프로세스가 여러 기계에서 통신하는 데 사용할 수 있는 네트워킹 프로토콜을 지원합니다.

이 장에서 설명하는 모듈 목록은 다음과 같습니다:

asyncio — 비동기 I/O

socket — 저수준 네트워킹 인터페이스

ssl — 소켓 객체용 TLS/SSL 래퍼

select — Waiting for I/O completion

selectors — 고수준 I/O 다중화

asyncore — Asynchronous socket handler

asynchat — Asynchronous socket command/response handler

signal — Set handlers for asynchronous events

mmap — 메모리 맵 파일 지원

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

네트워킹과 프로세스 간 통신 »

|

asyncio — 비동기 I/O

Hello World!

import asyncio

async def main():
    print('Hello ...')
    await asyncio.sleep(1)
    print('... World!')

# Python 3.7+
asyncio.run(main())

asyncio는 async/await 구문을 사용하여 동시성 코드를 작성하는 라이브러리입니다.

asyncio는 고성능 네트워크 및 웹 서버, 데이터베이스 연결 라이브러리, 분산 작업 큐 등을 제공하는 여러 파이썬 비동기 프레임워크의 기반으로 사용됩니다.

asyncio는 종종 IO 병목이면서 고수준의 구조화된 네트워크 코드에 가장 적합합니다.

asyncio는 다음과 같은 작업을 위한 고수준 API 집합을 제공합니다:

파이썬 코루틴들을 동시에 실행하고 실행을 완전히 제어할 수 있습니다.

네트워크 IO와 IPC를 수행합니다;

자식 프로세스를 제어합니다;

큐를 통해 작업을 분산합니다;

동시성 코드를 동기화합니다;

또한, 라이브러리와 프레임워크 개발자가 다음과 같은 작업을 할 수 있도록 하는 저수준 API가 있습니다:

네트워킹, 자식 프로세스 실행, OS 시그널 처리 등의 비동기 API를 제공하는 이벤트 루프를 만들고 관리합니다.

트랜스포트를 사용하여 효율적인 프로토콜을 구현합니다.

콜백 기반 라이브러리와 async/await 구문을 사용한 코드 간에 다리를 놓습니다.

레퍼런스

고수준 API

코루틴과 태스크

스트림

동기화 프리미티브

서브 프로세스

큐

예외

저수준 API

이벤트 루프

퓨처

트랜스포트와 프로토콜

정책

플랫폼 지원

가이드 및 자습서

고수준 API 색인

저수준 API 색인

asyncio로 개발하기

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

네트워킹과 프로세스 간 통신 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

네트워킹과 프로세스 간 통신 »

asyncio — 비동기 I/O »

|

코루틴과 태스크

이 절에서는 코루틴과 태스크로 작업하기 위한 고급 asyncio API에 관해 설명합니다.

코루틴

어웨이터블

asyncio 프로그램 실행하기

태스크 만들기

잠자기

동시에 태스크 실행하기

취소로부터 보호하기

시간제한

대기 프리미티브

다른 스레드에서 예약하기

인트로스팩션

Task 객체

제너레이터 기반 코루틴

코루틴

async/await 문법으로 선언된 코루틴은 asyncio 응용 프로그램을 작성하는 기본 방법입니다. 예를 들어, 다음 코드 조각(파이썬 3.7 이상 필요)은 “hello”를 인쇄하고, 1초 동안 기다린 다음, “world”를 인쇄합니다:

>>> import asyncio

>>> async def main():
...     print('hello')
...     await asyncio.sleep(1)
...     print('world')

>>> asyncio.run(main())
hello
world

단지 코루틴을 호출하는 것으로 실행되도록 예약하는 것은 아닙니다:

>>> main()
<coroutine object main at 0x1053bb7c8>

코루틴을 실제로 실행하기 위해, asyncio가 세 가지 주요 메커니즘을 제공합니다:

최상위 진입점 “main()” 함수를 실행하는 asyncio.run() 함수 (위의 예를 보세요.)

코루틴을 기다리기. 다음 코드 조각은 1초를 기다린 후 “hello”를 인쇄한 다음 또 2초를 기다린 후 “world”를 인쇄합니다:

import asyncio
import time

async def say_after(delay, what):
    await asyncio.sleep(delay)
    print(what)

async def main():
    print(f"started at {time.strftime('%X')}")

    await say_after(1, 'hello')
    await say_after(2, 'world')

    print(f"finished at {time.strftime('%X')}")

asyncio.run(main())

예상 출력:

started at 17:13:52
hello
world
finished at 17:13:55

코루틴을 asyncio 태스크로 동시에 실행하는 asyncio.create_task() 함수.

위의 예를 수정해서 두 개의 say_after 코루틴을 동시에 실행해 봅시다:

async def main():
    task1 = asyncio.create_task(
        say_after(1, 'hello'))

    task2 = asyncio.create_task(
        say_after(2, 'world'))

    print(f"started at {time.strftime('%X')}")

    # Wait until both tasks are completed (should take
    # around 2 seconds.)
    await task1
    await task2

    print(f"finished at {time.strftime('%X')}")

예상 출력은 이제 코드 조각이 이전보다 1초 빠르게 실행되었음을 보여줍니다:

started at 17:14:32
hello
world
finished at 17:14:34

어웨이터블

우리는 객체가 await 표현식에서 사용될 수 있을 때 어웨이터블 객체라고 말합니다. 많은 asyncio API는 어웨이터블을 받아들이도록 설계되었습니다.

어웨이터블 객체에는 세 가지 주요 유형이 있습니다: 코루틴, 태스크 및 퓨처.

코루틴

파이썬 코루틴은 어웨이터블이므로 다른 코루틴에서 기다릴 수 있습니다:

import asyncio

async def nested():
    return 42

async def main():
    # Nothing happens if we just call "nested()".
    # A coroutine object is created but not awaited,
    # so it *won't run at all*.
    nested()

    # Let's do it differently now and await it:
    print(await nested())  # will print "42".

asyncio.run(main())

중요

이 설명서에서 “코루틴” 이라는 용어는 두 가지 밀접한 관련 개념에 사용될 수 있습니다:

코루틴 함수: async def 함수;

코루틴 객체: 코루틴 함수를 호출하여 반환된 객체.

asyncio는 기존 제너레이터 기반 코루틴도 지원합니다.

태스크

태스크는 코루틴을 동시에 예약하는 데 사용됩니다.

코루틴이 asyncio.create_task()와 같은 함수를 사용하여 태스크로 싸일 때 코루틴은 곧 실행되도록 자동으로 예약됩니다:

import asyncio

async def nested():
    return 42

async def main():
    # Schedule nested() to run soon concurrently
    # with "main()".
    task = asyncio.create_task(nested())

    # "task" can now be used to cancel "nested()", or
    # can simply be awaited to wait until it is complete:
    await task

asyncio.run(main())

퓨처

Future는 비동기 연산의 최종 결과를 나타내는 특별한 저수준 어웨이터블 객체입니다.

Future 객체를 기다릴 때, 그것은 코루틴이 Future가 다른 곳에서 해결될 때까지 기다릴 것을 뜻합니다.

콜백 기반 코드를 async/await와 함께 사용하려면 asyncio의 Future 객체가 필요합니다.

일반적으로 응용 프로그램 수준 코드에서 Future 객체를 만들 필요는 없습니다.

때때로 라이브러리와 일부 asyncio API에 의해 노출되는 Future 객체를 기다릴 수 있습니다:

async def main():
    await function_that_returns_a_future_object()

    # this is also valid:
    await asyncio.gather(
        function_that_returns_a_future_object(),
        some_python_coroutine()
    )

Future 객체를 반환하는 저수준 함수의 좋은 예는 loop.run_in_executor()입니다.

asyncio 프로그램 실행하기

asyncio.run(coro, *, debug=False)

Execute the coroutine coro and return the result.

이 함수는 전달된 코루틴을 실행하고, asyncio 이벤트 루프와 비동기 제너레이터의 파이널리제이션을 관리합니다.

다른 asyncio 이벤트 루프가 같은 스레드에서 실행 중일 때, 이 함수를 호출할 수 없습니다.

debug이 True면, 이벤트 루프가 디버그 모드로 실행됩니다.

이 함수는 항상 새 이벤트 루프를 만들고 끝에 이벤트 루프를 닫습니다. asyncio 프로그램의 메인 진입 지점으로 사용해야 하고, 이상적으로는 한 번만 호출해야 합니다.

예:

async def main():
    await asyncio.sleep(1)
    print('hello')

asyncio.run(main())

버전 3.7에 추가: 중요: 이 함수는 파이썬 3.7에서 잠정적으로 asyncio에 추가되었습니다.

태스크 만들기

asyncio.create_task(coro)

coro 코루틴을 Task로 감싸고 실행을 예약합니다. Task 객체를 반환합니다.

get_running_loop()에 의해 반환된 루프에서 태스크가 실행되고, 현재 스레드에 실행 중인 루프가 없으면 RuntimeError가 발생합니다.

이 함수는 파이썬 3.7에서 추가되었습니다. 파이썬 3.7 이전 버전에서는, 대신 저수준 asyncio.ensure_future() 함수를 사용할 수 있습니다:

async def coro():
    ...

# In Python 3.7+
task = asyncio.create_task(coro())
...

# This works in all Python versions but is less readable
task = asyncio.ensure_future(coro())
...

버전 3.7에 추가.

잠자기

coroutine asyncio.sleep(delay, result=None, *, loop=None)

delay 초 동안 블록합니다.

result가 제공되면, 코루틴이 완료될 때 호출자에게 반환됩니다.

sleep()은 항상 현재 태스크를 일시 중단해서 다른 태스크를 실행할 수 있도록 합니다.

loop 인자는 폐지되었고 파이썬 3.10에서 삭제 예정입니다.

5초 동안 현재 날짜를 매초 표시하는 코루틴의 예:

import asyncio
import datetime

async def display_date():
    loop = asyncio.get_running_loop()
    end_time = loop.time() + 5.0
    while True:
        print(datetime.datetime.now())
        if (loop.time() + 1.0) >= end_time:
            break
        await asyncio.sleep(1)

asyncio.run(display_date())

동시에 태스크 실행하기

awaitable asyncio.gather(*aws, loop=None, return_exceptions=False)

aws 시퀀스에 있는 어웨이터블 객체를 동시에 실행합니다.

aws에 있는 어웨이터블이 코루틴이면 자동으로 태스크로 예약됩니다.

모든 어웨이터블이 성공적으로 완료되면, 결과는 반환된 값들이 합쳐진 리스트입니다. 결괏값의 순서는 aws에 있는 어웨이터블의 순서와 일치합니다.

return_exceptions가 False(기본값)면, 첫 번째 발생한 예외가 gather()를 기다리는 태스크로 즉시 전파됩니다. aws 시퀀스의 다른 어웨이터블은 취소되지 않고 계속 실행됩니다.

return_exceptions가 True면, 예외는 성공적인 결과처럼 처리되고, 결과 리스트에 집계됩니다.

gather()가 취소되면, 모든 제출된 (아직 완료되지 않은) 어웨이터블도 취소됩니다.

aws 시퀀스의 Task나 Future가 취소되면, 그것이 CancelledError를 일으킨 것처럼 처리됩니다 – 이때 gather() 호출은 취소되지 않습니다. 이것은 제출된 태스크/퓨처 하나를 취소하는 것이 다른 태스크/퓨처를 취소하게 되는 것을 막기 위한 것입니다.

예:

import asyncio

async def factorial(name, number):
    f = 1
    for i in range(2, number + 1):
        print(f"Task {name}: Compute factorial({i})...")
        await asyncio.sleep(1)
        f *= i
    print(f"Task {name}: factorial({number}) = {f}")

async def main():
    # Schedule three calls *concurrently*:
    await asyncio.gather(
        factorial("A", 2),
        factorial("B", 3),
        factorial("C", 4),
    )

asyncio.run(main())

# Expected output:
#
#     Task A: Compute factorial(2)...
#     Task B: Compute factorial(2)...
#     Task C: Compute factorial(2)...
#     Task A: factorial(2) = 2
#     Task B: Compute factorial(3)...
#     Task C: Compute factorial(3)...
#     Task B: factorial(3) = 6
#     Task C: Compute factorial(4)...
#     Task C: factorial(4) = 24

버전 3.7에서 변경: gather 자체가 취소되면, return_exceptions와 관계없이 취소가 전파됩니다.

취소로부터 보호하기

awaitable asyncio.shield(aw, *, loop=None)

어웨이터블 객체를 취소로부터 보호합니다.

aw가 코루틴이면 자동으로 태스크로 예약됩니다.

다음 문장:

res = await shield(something())

은 다음과 동등합니다:

res = await something()

단, 그것을 포함하는 코루틴이 취소되면, something()에서 실행 중인 태스크는 취소되지 않는다는 것만 예외입니다. something()의 관점에서는, 취소가 일어나지 않았습니다. 호출자는 여전히 취소되었고, “await” 표현식은 여전히 CancelledError를 발생시킵니다.

something()가 다른 수단(즉, 그 안에서 스스로)에 의해 취소되면, shield()도 취소됩니다.

취소를 완전히 무시하려면(권장되지 않습니다), 다음과 같이 shield() 함수를 try/except 절과 결합해야 합니다:

try:
    res = await shield(something())
except CancelledError:
    res = None

시간제한

coroutine asyncio.wait_for(aw, timeout, *, loop=None)

aw 어웨이터블이 제한된 시간 내에 완료될 때까지 기다립니다.

aw가 코루틴이면 자동으로 태스크로 예약됩니다.

timeout은 None 또는 대기할 float 나 int 초 수입니다. timeout이 None이면 퓨처가 완료될 때까지 블록합니다.

시간 초과가 발생하면, 태스크를 취소하고 asyncio.TimeoutError를 발생시킵니다.

태스크 취소를 피하려면, shield()로 감싸십시오.

이 함수는 퓨처가 실제로 취소될 때까지 대기하므로, 총 대기 시간이 timeout을 초과할 수 있습니다.

대기가 취소되면, 퓨처 aw도 취소됩니다.

loop 인자는 폐지되었고 파이썬 3.10에서 삭제 예정입니다.

예:

async def eternity():
    # Sleep for one hour
    await asyncio.sleep(3600)
    print('yay!')

async def main():
    # Wait for at most 1 second
    try:
        await asyncio.wait_for(eternity(), timeout=1.0)
    except asyncio.TimeoutError:
        print('timeout!')

asyncio.run(main())

# Expected output:
#
#     timeout!

버전 3.7에서 변경: 시간 초과로 인해 aw가 취소되면, wait_for는 aw가 취소될 때까지 대기합니다. 이전에는 asyncio.TimeoutError가 즉시 발생했습니다.

대기 프리미티브

coroutine asyncio.wait(aws, *, loop=None, timeout=None, return_when=ALL_COMPLETED)

aws 집합에 있는 어웨이터블 객체를 동시에 실행하고, return_when에 의해 지정된 조건을 만족할 때까지 블록합니다.

aws에 있는 어웨이터블이 코루틴이면, 자동으로 태스크로 예약됩니다. 코루틴 객체를 wait()로 직접 전달하는 것은 혼란스러운 동작으로 연결되므로 폐지되었습니다.

두 집합의 태스크/퓨처를 반환합니다: (done, pending).

사용법:

done, pending = await asyncio.wait(aws)

loop 인자는 폐지되었고 파이썬 3.10에서 삭제 예정입니다.

timeout(float나 int)을 지정하면, 반환하기 전에 대기할 최대 시간(초)을 제어할 수 있습니다.

이 함수는 asyncio.TimeoutError를 발생시키지 않음에 유의하십시오. 시간 초과가 발생할 때 완료되지 않은 퓨처나 태스크는 단순히 두 번째 집합으로 반환됩니다.

return_when는 이 함수가 언제 반환해야 하는지 나타냅니다. 다음 상수 중 하나여야 합니다:

상수

설명

FIRST_COMPLETED

퓨처가 하나라도 끝나거나 취소될 때 함수가 반환됩니다.

FIRST_EXCEPTION

퓨처가 하나라도 예외를 일으켜 끝나면 함수가 반환됩니다. 어떤 퓨처도 예외를 일으키지 않으면 ALL_COMPLETED와 같습니다.

ALL_COMPLETED

모든 퓨처가 끝나거나 취소되면 함수가 반환됩니다.

wait_for()와 달리, wait()는 시간 초과가 발생할 때 퓨처를 취소하지 않습니다.

참고

wait()는 코루틴을 태스크로 자동 예약하고, 나중에 묵시적으로 생성된 Task 객체를 (done, pending) 집합으로 반환합니다. 따라서 다음 코드는 기대한 대로 작동하지 않습니다:

async def foo():
    return 42

coro = foo()
done, pending = await asyncio.wait({coro})

if coro in done:
    # This branch will never be run!

위의 조각을 고치는 방법은 다음과 같습니다:

async def foo():
    return 42

task = asyncio.create_task(foo())
done, pending = await asyncio.wait({task})

if task in done:
    # Everything will work as expected now.

코루틴 객체를 wait()로 직접 전달하는 것은 폐지되었습니다.

asyncio.as_completed(aws, *, loop=None, timeout=None)

aws 집합에 있는 어웨이터블 객체를 동시에 실행합니다. Future 객체의 이터레이터를 반환합니다. 반환된 각 Future 객체는 남아있는 어웨이터블 집합의 가장 빠른 결과를 나타냅니다.

모든 퓨처가 완료되기 전에 시간 초과가 발생하면 asyncio.TimeoutError를 발생시킵니다.

예:

for f in as_completed(aws):
    earliest_result = await f
    # ...

다른 스레드에서 예약하기

asyncio.run_coroutine_threadsafe(coro, loop)

주어진 이벤트 루프에 코루틴을 제출합니다. 스레드 안전합니다.

다른 OS 스레드에서 결과를 기다리는 concurrent.futures.Future를 반환합니다.

이 함수는 이벤트 루프가 실행 중인 스레드가 아닌, 다른 OS 스레드에서 호출하기 위한 것입니다. 예:

# Create a coroutine
coro = asyncio.sleep(1, result=3)

# Submit the coroutine to a given loop
future = asyncio.run_coroutine_threadsafe(coro, loop)

# Wait for the result with an optional timeout argument
assert future.result(timeout) == 3

코루틴에서 예외가 발생하면, 반환된 Future에 통지됩니다. 또한, 이벤트 루프에서 태스크를 취소하는 데 사용할 수 있습니다:

try:
    result = future.result(timeout)
except asyncio.TimeoutError:
    print('The coroutine took too long, cancelling the task...')
    future.cancel()
except Exception as exc:
    print(f'The coroutine raised an exception: {exc!r}')
else:
    print(f'The coroutine returned: {result!r}')

설명서의 동시성과 다중 스레드 절을 참조하십시오.

다른 asyncio 함수와 달리, 이 함수는 loop 인자가 명시적으로 전달되어야 합니다.

버전 3.5.1에 추가.

인트로스팩션

asyncio.current_task(loop=None)

현재 실행 중인 Task 인스턴스를 반환하거나 태스크가 실행되고 있지 않으면 None을 반환합니다.

loop가 None이면, 현재 루프를 가져오는 데 get_running_loop()가 사용됩니다.

버전 3.7에 추가.

asyncio.all_tasks(loop=None)

루프에 의해 실행되는 아직 완료되지 않은 Task 객체 집합을 반환합니다.

loop가 None이면, 현재 루프를 가져오는 데 get_running_loop()가 사용됩니다.

버전 3.7에 추가.

Task 객체

class asyncio.Task(coro, *, loop=None)

파이썬 코루틴을 실행하는 퓨처류 객체입니다. 스레드 안전하지 않습니다.

태스크는 이벤트 루프에서 코루틴을 실행하는 데 사용됩니다. 만약 코루틴이 Future를 기다리고 있다면, 태스크는 코루틴의 실행을 일시 중지하고 Future의 완료를 기다립니다. 퓨처가 완료되면, 감싸진 코루틴의 실행이 다시 시작됩니다.

이벤트 루프는 협업 스케줄링을 사용합니다: 이벤트 루프는 한 번에 하나의 Task를 실행합니다. Task가 Future의 완료를 기다리는 동안, 이벤트 루프는 다른 태스크, 콜백을 실행하거나 IO 연산을 수행합니다.

테스트를 만들려면 고수준 asyncio.create_task() 함수를 사용하거나, 저수준 loop.create_task() 나 ensure_future() 함수를 사용하십시오. 태스크의 인스턴스를 직접 만드는 것은 권장되지 않습니다.

실행 중인 Task를 취소하려면 cancel() 메서드를 사용하십시오. 이를 호출하면 태스크가 감싼 코루틴으로 CancelledError 예외를 던집니다. 코루틴이 취소 중에 Future 객체를 기다리고 있으면, Future 객체가 취소됩니다.

cancelled()는 태스크가 취소되었는지 확인하는 데 사용할 수 있습니다. 이 메서드는 감싼 코루틴이 CancelledError 예외를 억제하지 않고 실제로 취소되었으면 True를 반환합니다.

asyncio.Task는 Future.set_result()와 Future.set_exception()을 제외한 모든 API를 Future에서 상속받습니다.

태스크는 contextvars 모듈을 지원합니다. 태스크가 만들어질 때 현재 컨텍스트를 복사하고 나중에 복사된 컨텍스트에서 코루틴을 실행합니다.

버전 3.7에서 변경: contextvars 모듈에 대한 지원이 추가되었습니다.

cancel()

Task 취소를 요청합니다.

이벤트 루프의 다음 사이클에서 감싼 코루틴으로 CancelledError 예외를 던져넣도록 합니다.

그러면 코루틴은 try … … except CancelledError … finally 블록으로 정리하거나 예외를 억제하여 요청을 거부할 수 있습니다. 따라서, Future.cancel()와 달리 Task.cancel()은 Task가 취소됨을 보장하지는 않습니다. 하지만 취소를 완전히 억제하는 것은 일반적이지 않고, 그렇게 하지 말도록 적극적으로 권합니다.

다음 예는 코루틴이 취소 요청을 가로채는 방법을 보여줍니다:

async def cancel_me():
    print('cancel_me(): before sleep')

    try:
        # Wait for 1 hour
        await asyncio.sleep(3600)
    except asyncio.CancelledError:
        print('cancel_me(): cancel sleep')
        raise
    finally:
        print('cancel_me(): after sleep')

async def main():
    # Create a "cancel_me" Task
    task = asyncio.create_task(cancel_me())

    # Wait for 1 second
    await asyncio.sleep(1)

    task.cancel()
    try:
        await task
    except asyncio.CancelledError:
        print("main(): cancel_me is cancelled now")

asyncio.run(main())

# Expected output:
#
#     cancel_me(): before sleep
#     cancel_me(): cancel sleep
#     cancel_me(): after sleep
#     main(): cancel_me is cancelled now

cancelled()

Task가 취소(cancelled)되었으면 True를 반환합니다.

Task는 cancel()로 취소가 요청되고 감싼 코루틴이 자신에게 전달된 CancelledError 예외를 확산할 때 최소(cancelled)됩니다.

done()

Task가 완료(done)되었으면 True를 반환합니다.

감싼 코루틴이 값을 반환하거나 예외를 일으키거나, Task가 취소되면 Task는 완료(done)됩니다.

result()

Task의 결과를 반환합니다.

Task가 완료(done)되었으면 감싼 코루틴의 결과가 반환됩니다 (또는 코루틴이 예외를 발생시켰으면 해당 예외가 다시 발생합니다).

태스크가 취소(cancelled)되었으면, 이 메서드는 CancelledError 예외를 발생시킵니다.

태스크 결과를 아직 사용할 수 없으면, 이 메서드는 InvalidStateError 예외를 발생시킵니다.

exception()

Task의 예외를 반환합니다.

감싼 코루틴이 예외를 발생시키면, 그 예외가 반환됩니다. 감싼 코루틴이 정상적으로 반환되면, 이 메서드는 None을 반환합니다.

태스크가 취소(cancelled)되었으면, 이 메서드는 CancelledError 예외를 발생시킵니다.

태스크가 아직 완료(done)되지 않았으면, 이 메서드는 InvalidStateError 예외를 발생시킵니다.

add_done_callback(callback, *, context=None)

태스크가 완료(done)될 때 실행할 콜백을 추가합니다.

이 메서드는 저수준 콜백 기반 코드에서만 사용해야 합니다.

자세한 내용은 Future.add_done_callback() 설명서를 참조하십시오.

remove_done_callback(callback)

콜백 목록에서 callback을 제거합니다.

이 메서드는 저수준 콜백 기반 코드에서만 사용해야 합니다.

자세한 내용은 Future.remove_done_callback() 설명서를 참조하십시오.

get_stack(*, limit=None)

이 Task의 스택 프레임 리스트를 돌려줍니다.

감싼 코루틴이 완료되지 않았으면, 일시 정지된 곳의 스택을 반환합니다. 코루틴이 성공적으로 완료되었거나 취소되었으면 빈 리스트가 반환됩니다. 코루틴이 예외로 종료되었으면, 이것은 트레이스백 프레임의 리스트를 반환합니다.

프레임은 항상 가장 오래된 것부터 순서대로 정렬됩니다.

일시 정지된 코루틴에서는 하나의 스택 프레임만 반환됩니다.

선택적 limit 인자는 반환할 최대 프레임 수를 설정합니다; 기본적으로 사용 가능한 모든 프레임이 반환됩니다. 반환되는 리스트의 순서는 스택과 트레이스백 중 어느 것이 반환되는지에 따라 다릅니다: 스택은 최신 프레임이 반환되지만, 트레이스백은 가장 오래된 프레임이 반환됩니다. (이는 traceback 모듈의 동작과 일치합니다.)

print_stack(*, limit=None, file=None)

이 Task의 스택이나 트레이스백을 인쇄합니다.

이것은 get_stack()으로 얻은 프레임에 대해 traceback 모듈과 유사한 출력을 생성합니다.

limit 인자는 get_stack()에 직접 전달됩니다.

file 인자는 출력이 기록되는 I/O 스트림입니다; 기본적으로 출력은 sys.stderr에 기록됩니다.

classmethod all_tasks(loop=None)

이벤트 루프의 모든 태스크 집합을 돌려줍니다.

기본적으로 현재 이벤트 루프에 대한 모든 태스크가 반환됩니다. loop가 None이면, 현재 루프를 가져오는 데 get_event_loop() 함수가 사용됩니다.

이 메서드는 폐지되었고 파이썬 3.9에서 제거됩니다. asyncio.all_tasks() 함수를 대신 사용하십시오.

classmethod current_task(loop=None)

현재 실행 중인 태스크나 None을 반환합니다.

loop가 None이면, 현재 루프를 가져오는 데 get_event_loop() 함수가 사용됩니다.

이 메서드는 폐지되었고 파이썬 3.9에서 제거됩니다. asyncio.current_task() 함수를 대신 사용하십시오.

제너레이터 기반 코루틴

참고

제너레이터 기반 코루틴에 대한 지원은 폐지되었고 파이썬 3.10에서 삭제될 예정입니다.

제너레이터 기반 코루틴은 async/await 문법 전에 나왔습니다. 퓨처와 다른 코루틴을 기다리기 위해 yield from 표현식을 사용하는 파이썬 제너레이터입니다.

제너레이터 기반 코루틴은 @asyncio.coroutine으로 데코레이트 되어야 하지만 강제되지는 않습니다.

@asyncio.coroutine

제너레이터 기반 코루틴을 표시하는 데코레이터.

이 데코레이터는 기존 제너레이터 기반 코루틴이 async/await 코드와 호환되도록 합니다:

@asyncio.coroutine
def old_style_coroutine():
    yield from asyncio.sleep(1)

async def main():
    await old_style_coroutine()

이 데코레이터는 폐지되었고 파이썬 3.10에서 삭제 예정입니다.

async def 코루틴에는 이 데코레이터를 사용하면 안 됩니다.

asyncio.iscoroutine(obj)

obj가 코루틴 객체면 True를 반환합니다.

이 메서드는 제너레이터 기반 코루틴에 대해 True를 반환하기 때문에, inspect.iscoroutine()과 다릅니다.

asyncio.iscoroutinefunction(func)

func가 코루틴 함수면 True를 반환합니다.

이 메서드는 @coroutine으로 데코레이트 된 제너레이터 기반 코루틴 함수에 대해 True를 반환하기 때문에, inspect.iscoroutinefunction()과 다릅니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

네트워킹과 프로세스 간 통신 »

asyncio — 비동기 I/O »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

네트워킹과 프로세스 간 통신 »

asyncio — 비동기 I/O »

|

스트림

스트림은 네트워크 연결로 작업하기 위해, async/await에서 사용할 수 있는 고수준 프리미티브입니다. 스트림은 콜백이나 저수준 프로토콜과 트랜스포트를 사용하지 않고 데이터를 송수신할 수 있게 합니다.

다음은 asyncio 스트림을 사용하여 작성된 TCP 메아리 클라이언트의 예입니다:

import asyncio

async def tcp_echo_client(message):
    reader, writer = await asyncio.open_connection(
        '127.0.0.1', 8888)

    print(f'Send: {message!r}')
    writer.write(message.encode())

    data = await reader.read(100)
    print(f'Received: {data.decode()!r}')

    print('Close the connection')
    writer.close()
    await writer.wait_closed()

asyncio.run(tcp_echo_client('Hello World!'))

아래의 예제 절도 참조하십시오.

스트림 함수

다음 최상위 asyncio 함수를 사용하여 스트림을 만들고 작업할 수 있습니다.:

coroutine asyncio.open_connection(host=None, port=None, *, loop=None, limit=None, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None)

네트워크 연결을 만들고 (reader, writer) 객체 쌍을 반환합니다.

반환된 reader 와 writer 객체는 StreamReader 와 StreamWriter 클래스의 인스턴스입니다.

loop 인자는 선택적이며 이 함수를 코루틴에서 기다릴 때 언제나 자동으로 결정될 수 있습니다.

limit는 반환된 StreamReader 인스턴스가 사용하는 버퍼 크기 한계를 결정합니다. 기본적으로 limit는 64KB로 설정됩니다.

나머지 인자는 loop.create_connection()로 직접 전달됩니다.

버전 3.7에 추가: ssl_handshake_timeout 매개 변수.

coroutine asyncio.start_server(client_connected_cb, host=None, port=None, *, loop=None, limit=None, family=socket.AF_UNSPEC, flags=socket.AI_PASSIVE, sock=None, backlog=100, ssl=None, reuse_address=None, reuse_port=None, ssl_handshake_timeout=None, start_serving=True)

소켓 서버를 시작합니다.

새 클라이언트 연결이 만들어질 때마다 client_connected_cb 콜백이 호출됩니다. 이 콜백은 두 개의 인자로 (reader, writer) 쌍을 받는데, StreamReader 와 StreamWriter 클래스의 인스턴스입니다.

client_connected_cb는 일반 콜러블이나 코루틴 함수 일 수 있습니다; 코루틴 함수면, 자동으로 Task로 예약됩니다.

loop 인자는 선택적이며, 이 메서드를 코루틴이 기다릴 때 항상 자동으로 결정될 수 있습니다.

limit는 반환된 StreamReader 인스턴스가 사용하는 버퍼 크기 한계를 결정합니다. 기본적으로 limit는 64KB로 설정됩니다.

나머지 인자는 loop.create_server()로 직접 전달됩니다.

버전 3.7에 추가: ssl_handshake_timeout 와 start_serving 매개 변수.

유닉스 소켓

coroutine asyncio.open_unix_connection(path=None, *, loop=None, limit=None, ssl=None, sock=None, server_hostname=None, ssl_handshake_timeout=None)

유닉스 소켓 연결을 만들고 (reader, writer) 쌍을 반환합니다.

open_connection()과 비슷하지만, 유닉스 소켓에서 작동합니다.

loop.create_unix_connection()의 설명서도 참조하십시오.

가용성: 유닉스.

버전 3.7에 추가: ssl_handshake_timeout 매개 변수.

버전 3.7에서 변경: path 매개 변수는 이제 경로류 객체가 될 수 있습니다.

coroutine asyncio.start_unix_server(client_connected_cb, path=None, *, loop=None, limit=None, sock=None, backlog=100, ssl=None, ssl_handshake_timeout=None, start_serving=True)

유닉스 소켓 서버를 시작합니다.

start_server()와 비슷하지만, 유닉스 소켓에서 작동합니다.

loop.create_unix_server()의 설명서도 참조하십시오.

가용성: 유닉스.

버전 3.7에 추가: ssl_handshake_timeout 와 start_serving 매개 변수.

버전 3.7에서 변경: path 매개 변수는 이제 경로류 객체가 될 수 있습니다.

StreamReader

class asyncio.StreamReader

IO 스트림에서 데이터를 읽는 API를 제공하는 판독기(reader) 객체를 나타냅니다.

StreamReader 객체를 직접 인스턴스로 만드는 것은 권장되지 않습니다. 대신 open_connection()과 start_server()를 사용하십시오.

coroutine read(n=-1)

최대 n 바이트를 읽습니다. n이 제공되지 않거나 -1로 설정되면, EOF까지 읽은 후 모든 읽은 바이트를 반환합니다.

EOF를 수신했고 내부 버퍼가 비어 있으면, 빈 bytes 객체를 반환합니다.

coroutine readline()

한 줄을 읽습니다. 여기서 “줄”은 \n로 끝나는 바이트의 시퀀스입니다.

EOF를 수신했고, \n를 찾을 수 없으면, 이 메서드는 부분적으로 읽은 데이터를 반환합니다.

EOF를 수신했고, 내부 버퍼가 비어 있으면 빈 bytes 객체를 반환합니다.

coroutine readexactly(n)

정확히 n 바이트를 읽습니다.

n 바이트를 읽기 전에 EOF에 도달하면, IncompleteReadError를 일으킵니다. 부분적으로 읽은 데이터를 가져오려면 IncompleteReadError.partial 어트리뷰트를 사용하십시오.

coroutine readuntil(separator=b'\n')

separator가 발견될 때까지 스트림에서 데이터를 읽습니다.

성공하면, 데이터와 separator가 내부 버퍼에서 제거됩니다 (소비됩니다). 반환된 데이터에는 끝에 separator가 포함됩니다.

읽은 데이터의 양이 구성된 스트림 제한을 초과하면 LimitOverrunError 예외가 발생하고, 데이터는 내부 버퍼에 그대로 남아 있으며 다시 읽을 수 있습니다.

완전한 separator가 발견되기 전에 EOF에 도달하면 IncompleteReadError 예외가 발생하고, 내부 버퍼가 재설정됩니다. IncompleteReadError.partial 어트리뷰트에는 separator 일부가 포함될 수 있습니다.

버전 3.5.2에 추가.

at_eof()

버퍼가 비어 있고 feed_eof()가 호출되었으면 True를 반환합니다.

StreamWriter

class asyncio.StreamWriter

IO 스트림에 데이터를 쓰는 API를 제공하는 기록기(writer) 객체를 나타냅니다.

StreamWriter 객체를 직접 인스턴스로 만드는 것은 권장되지 않습니다. 대신 open_connection()과 start_server()를 사용하십시오.

can_write_eof()

Return True if the underlying transport supports the write_eof() method, False otherwise.

write_eof()

버퍼링 된 쓰기 데이터가 플러시 된 후에 스트림의 쓰기 끝을 닫습니다.

transport

하부 asyncio 트랜스포트를 돌려줍니다.

get_extra_info(name, default=None)

선택적 트랜스포트 정보에 액세스합니다; 자세한 내용은 BaseTransport.get_extra_info()를 참조하십시오.

write(data)

스트림에 data를 기록합니다.

이 메서드는 흐름 제어의 대상이 아닙니다. write() 호출 뒤에는 drain()이 와야 합니다.

writelines(data)

스트림에 바이트열의 리스트(또는 임의의 이터러블)를 기록합니다.

이 메서드는 흐름 제어의 대상이 아닙니다. writelines() 호출 뒤에는 drain()이 와야 합니다.

coroutine drain()

스트림에 기록을 다시 시작하는 것이 적절할 때까지 기다립니다. 예:

writer.write(data)
await writer.drain()

이것은 하부 IO 쓰기 버퍼와 상호 작용하는 흐름 제어 메서드입니다. 버퍼의 크기가 높은 수위에 도달하면, 버퍼 크기가 낮은 수위까지 내려가서 쓰기가 다시 시작될 수 있을 때까지 drain()은 블록합니다. 기다릴 것이 없으면, drain()은 즉시 반환합니다.

close()

스트림을 닫습니다.

is_closing()

스트림이 닫혔거나 닫히고 있으면 True를 반환합니다.

버전 3.7에 추가.

coroutine wait_closed()

스트림이 닫힐 때까지 기다립니다.

하부 연결이 닫힐 때까지 기다리려면 close() 뒤에 호출해야 합니다.

버전 3.7에 추가.

예제

스트림을 사용하는 TCP 메아리 클라이언트

asyncio.open_connection() 함수를 사용하는 TCP 메아리 클라이언트:

import asyncio

async def tcp_echo_client(message):
    reader, writer = await asyncio.open_connection(
        '127.0.0.1', 8888)

    print(f'Send: {message!r}')
    writer.write(message.encode())

    data = await reader.read(100)
    print(f'Received: {data.decode()!r}')

    print('Close the connection')
    writer.close()

asyncio.run(tcp_echo_client('Hello World!'))

더 보기

TCP 메아리 클라이언트 프로토콜 예제는 저수준 loop.create_connection() 메서드를 사용합니다.

스트림을 사용하는 TCP 메아리 서버

asyncio.start_server() 함수를 사용하는 TCP 메아리 서버:

import asyncio

async def handle_echo(reader, writer):
    data = await reader.read(100)
    message = data.decode()
    addr = writer.get_extra_info('peername')

    print(f"Received {message!r} from {addr!r}")

    print(f"Send: {message!r}")
    writer.write(data)
    await writer.drain()

    print("Close the connection")
    writer.close()

async def main():
    server = await asyncio.start_server(
        handle_echo, '127.0.0.1', 8888)

    addr = server.sockets[0].getsockname()
    print(f'Serving on {addr}')

    async with server:
        await server.serve_forever()

asyncio.run(main())

더 보기

TCP 메아리 서버 프로토콜 예제는 loop.create_server() 메서드를 사용합니다.

HTTP 헤더 가져오기

명령 줄로 전달된 URL의 HTTP 헤더를 조회하는 간단한 예제:

import asyncio
import urllib.parse
import sys

async def print_http_headers(url):
    url = urllib.parse.urlsplit(url)
    if url.scheme == 'https':
        reader, writer = await asyncio.open_connection(
            url.hostname, 443, ssl=True)
    else:
        reader, writer = await asyncio.open_connection(
            url.hostname, 80)

    query = (
        f"HEAD {url.path or '/'} HTTP/1.0\r\n"
        f"Host: {url.hostname}\r\n"
        f"\r\n"
    )

    writer.write(query.encode('latin-1'))
    while True:
        line = await reader.readline()
        if not line:
            break

        line = line.decode('latin1').rstrip()
        if line:
            print(f'HTTP header> {line}')

    # Ignore the body, close the socket
    writer.close()

url = sys.argv[1]
asyncio.run(print_http_headers(url))

사용법:

python example.py http://example.com/path/page.html

또는 HTTPS를 사용하면:

python example.py https://example.com/path/page.html

스트림을 사용하여 데이터를 기다리는 열린 소켓 등록

소켓이 open_connection() 함수를 사용하여 데이터를 수신할 때까지 기다리는 코루틴:

import asyncio
import socket

async def wait_for_data():
    # Get a reference to the current event loop because
    # we want to access low-level APIs.
    loop = asyncio.get_running_loop()

    # Create a pair of connected sockets.
    rsock, wsock = socket.socketpair()

    # Register the open socket to wait for data.
    reader, writer = await asyncio.open_connection(sock=rsock)

    # Simulate the reception of data from the network
    loop.call_soon(wsock.send, 'abc'.encode())

    # Wait for data
    data = await reader.read(100)

    # Got data, we are done: close the socket
    print("Received:", data.decode())
    writer.close()

    # Close the second socket
    wsock.close()

asyncio.run(wait_for_data())

더 보기

프로토콜을 사용하여 데이터를 기다리는 열린 소켓 등록 예제는 저수준 프로토콜과 loop.create_connection() 메서드를 사용합니다.

파일 기술자에서 읽기 이벤트를 관찰하기 예제는 저수준 loop.add_reader() 메서드를 사용하여 파일 기술자를 관찰합니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

네트워킹과 프로세스 간 통신 »

asyncio — 비동기 I/O »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

네트워킹과 프로세스 간 통신 »

asyncio — 비동기 I/O »

|

동기화 프리미티브

asyncio 동기화 프리미티브는 threading 모듈의 것과 유사하도록 설계되었습니다만 두 가지 중요한 주의 사항이 있습니다:

asyncio 프리미티브는 스레드 안전하지 않으므로, OS 스레드 동기화(이를 위해서는 threading을 사용하십시오)에 사용하면 안 됩니다.

이러한 동기화 프리미티브의 메서드는 timeout 인자를 받아들이지 않습니다; asyncio.wait_for() 함수를 사용하여 시간제한이 있는 연산을 수행하십시오.

asyncio에는 다음과 같은 기본 동기화 프리미티브가 있습니다:

Lock

Event

Condition

Semaphore

BoundedSemaphore

Lock

class asyncio.Lock(*, loop=None)

asyncio 태스크를 위한 뮤텍스 록을 구현합니다. 스레드 안전하지 않습니다.

asyncio 록은 공유 자원에 대한 독점 액세스를 보장하는 데 사용될 수 있습니다.

Lock을 사용하는 가장 좋은 방법은 async with 문입니다:

lock = asyncio.Lock()

# ... later
async with lock:
    # access shared state

이는 다음과 동등합니다:

lock = asyncio.Lock()

# ... later
await lock.acquire()
try:
    # access shared state
finally:
    lock.release()

coroutine acquire()

록을 얻습니다.

이 메서드는 록이 풀림(unlocked)이 될 때까지 기다리고, 잠김(locked)으로 설정한 다음 True를 반환합니다.

잠금이 해제되기를 기다리는 acquire()에서 둘 이상의 코루틴 블록 될 때, 결국 한 개의 코루틴만 진행됩니다.

록을 얻는 것은 공평(fair)합니다: 진행할 코루틴은 록을 기다리기 시작한 첫 번째 코루틴이 됩니다.

release()

록을 반납합니다.

록이 잠김(locked)이면 풀림(unlocked)으로 재설정하고 돌아옵니다.

록이 풀림(unlocked)이면 RuntimeError가 발생합니다.

locked()

록이 잠김(locked)이면 True를 반환합니다.

Event

class asyncio.Event(*, loop=None)

이벤트 객체. 스레드 안전하지 않습니다.

asyncio 이벤트는 어떤 이벤트가 발생했음을 여러 asyncio 태스크에 알리는 데 사용할 수 있습니다.

Event 객체는 set() 메서드로 참으로 설정하고 clear() 메서드로 거짓으로 재설정할 수 있는 내부 플래그를 관리합니다. wait() 메서드는 플래그가 참으로 설정될 때까지 블록합니다. 플래그는 초기에 거짓으로 설정됩니다.

예:

async def waiter(event):
    print('waiting for it ...')
    await event.wait()
    print('... got it!')

async def main():
    # Create an Event object.
    event = asyncio.Event()

    # Spawn a Task to wait until 'event' is set.
    waiter_task = asyncio.create_task(waiter(event))

    # Sleep for 1 second and set the event.
    await asyncio.sleep(1)
    event.set()

    # Wait until the waiter task is finished.
    await waiter_task

asyncio.run(main())

coroutine wait()

이벤트가 설정될 때까지 기다립니다.

이벤트가 설정되었으면 True를 즉시 반환합니다. 그렇지 않으면 다른 태스크가 set()을 호출할 때까지 블록합니다.

set()

이벤트를 설정합니다.

이벤트가 설정되기를 기다리는 모든 태스크는 즉시 깨어납니다.

clear()

이벤트를 지웁니다 (재설정).

이제 wait()를 기다리는 태스크는 set() 메서드가 다시 호출될 때까지 블록 됩니다.

is_set()

이벤트가 설정되면 True를 반환합니다.

Condition

class asyncio.Condition(lock=None, *, loop=None)

Condition 객체. 스레드 안전하지 않습니다.

asyncio 조건 프리미티브는 태스크가 어떤 이벤트가 발생하기를 기다린 다음 공유 자원에 독점적으로 액세스하는데 사용할 수 있습니다.

본질에서, Condition 객체는 Event와 Lock의 기능을 결합합니다. 여러 개의 Condition 객체가 하나의 Lock을 공유할 수 있으므로, 공유 자원의 특정 상태에 관심이 있는 다른 태스크 간에 공유 자원에 대한 독점적 액세스를 조정할 수 있습니다.

선택적 lock 인자는 Lock 객체나 None 이어야 합니다. 후자의 경우 새로운 Lock 객체가 자동으로 만들어집니다.

Condition을 사용하는 가장 좋은 방법은 async with 문입니다:

cond = asyncio.Condition()

# ... later
async with cond:
    await cond.wait()

이는 다음과 동등합니다:

cond = asyncio.Condition()

# ... later
await cond.acquire()
try:
    await cond.wait()
finally:
    cond.release()

coroutine acquire()

하부 록을 얻습니다.

이 메서드는 하부 록이 풀림(unlocked)이 될 때까지 대기하고, 잠김(locked)으로 설정한 다음 True를 반환합니다.

notify(n=1)

이 조건을 기다리는 최대 n 태스크(기본적으로 1개)를 깨웁니다. 대기 중인 태스크가 없으면 이 메서드는 no-op입니다.

이 메서드를 호출하기 전에 록을 얻어야 하고, 호출 직후에 반납해야 합니다. 풀린(unlocked) 록으로 호출하면 RuntimeError 에러가 발생합니다.

locked()

하부 록을 얻었으면 True를 돌려줍니다.

notify_all()

이 조건에 대기 중인 모든 태스크를 깨웁니다.

이 메서드는 notify()처럼 작동하지만, 대기 중인 모든 태스크를 깨웁니다.

이 메서드를 호출하기 전에 록을 얻어야 하고, 호출 직후에 반납해야 합니다. 풀린(unlocked) 록으로 호출하면 RuntimeError 에러가 발생합니다.

release()

하부 록을 반납합니다.

풀린 록으로 호출하면, RuntimeError가 발생합니다.

coroutine wait()

알릴 때까지 기다립니다.

이 메서드가 호출될 때 호출하는 태스크가 록을 얻지 않았으면 RuntimeError가 발생합니다.

이 메서드는 하부 잠금을 반납한 다음, notify() 나 notify_all() 호출 때문에 깨어날 때까지 블록합니다. 일단 깨어나면, Condition은 록을 다시 얻고, 이 메서드는 True를 돌려줍니다.

coroutine wait_for(predicate)

predicate가 참이 될 때까지 기다립니다.

predicate는 논릿값으로 해석될 결과를 돌려주는 콜러블이어야 합니다. 최종값이 반환 값입니다.

Semaphore

class asyncio.Semaphore(value=1, *, loop=None)

Semaphore 객체. 스레드 안전하지 않습니다.

세마포어는 각 acquire() 호출로 감소하고, 각 release() 호출로 증가하는 내부 카운터를 관리합니다. 카운터는 절대로 0 밑으로 내려갈 수 없습니다; acquire()가 0을 만나면, release()를 호출할 때까지 기다리면서 블록합니다.

선택적 value 인자는 내부 카운터의 초깃값을 제공합니다 (기본적으로 1). 지정된 값이 0보다 작으면 ValueError가 발생합니다.

Semaphore를 사용하는 가장 좋은 방법은 async with 문입니다:

sem = asyncio.Semaphore(10)

# ... later
async with sem:
    # work with shared resource

이는 다음과 동등합니다:

sem = asyncio.Semaphore(10)

# ... later
await sem.acquire()
try:
    # work with shared resource
finally:
    sem.release()

coroutine acquire()

세마포어를 얻습니다.

내부 카운터가 0보다 크면, 1 감소시키고 True를 즉시 반환합니다. 0이면, release()가 호출될 때까지 기다린 다음 True를 반환합니다.

locked()

세마포어를 즉시 얻을 수 없으면 True를 반환합니다.

release()

세마포어를 반납하고 내부 카운터를 1 증가시킵니다. 세마포어를 얻기 위해 대기하는 태스크를 깨울 수 있습니다.

BoundedSemaphore와 달리, Semaphore는 acquire() 호출보다 더 많은 release() 호출을 허용합니다.

BoundedSemaphore

class asyncio.BoundedSemaphore(value=1, *, loop=None)

제한된 세마포어 객체. 스레드 안전하지 않습니다.

제한된 세마포어는 초기 value 위로 내부 카운터를 증가시키면 release()에서 ValueError를 발생시키는 Semaphore 버전입니다.

버전 3.7부터 폐지: await lock 이나 yield from lock 및/또는 with 문(with await lock, with (yield from lock))을 사용하여 록을 얻는 것은 폐지되었습니다. 대신 async with lock을 사용하십시오.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

네트워킹과 프로세스 간 통신 »

asyncio — 비동기 I/O »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

네트워킹과 프로세스 간 통신 »

asyncio — 비동기 I/O »

|

서브 프로세스

이 절에서는 서브 프로세스를 만들고 관리하기 위한 고수준 async/await asyncio API에 관해 설명합니다.

다음은 asyncio가 셸 명령을 실행하고 결과를 얻는 방법의 예입니다:

import asyncio

async def run(cmd):
    proc = await asyncio.create_subprocess_shell(
        cmd,
        stdout=asyncio.subprocess.PIPE,
        stderr=asyncio.subprocess.PIPE)

    stdout, stderr = await proc.communicate()

    print(f'[{cmd!r} exited with {proc.returncode}]')
    if stdout:
        print(f'[stdout]\n{stdout.decode()}')
    if stderr:
        print(f'[stderr]\n{stderr.decode()}')

asyncio.run(run('ls /zzz'))

는 다음과 같이 인쇄할 것입니다:

['ls /zzz' exited with 1]
[stderr]
ls: /zzz: No such file or directory

모든 asyncio 서브 프로세스 함수는 비동기이고, asyncio가 이러한 함수로 작업 할 수 있는 많은 도구를 제공하기 때문에, 여러 서브 프로세스를 병렬로 실행하고 감시하기가 쉽습니다. 여러 명령을 동시에 실행하도록 위 예제를 수정하는 것은 아주 간단합니다:

async def main():
    await asyncio.gather(
        run('ls /zzz'),
        run('sleep 1; echo "hello"'))

asyncio.run(main())

예제 하위 절도 참조하십시오.

서브 프로세스 만들기

coroutine asyncio.create_subprocess_exec(program, *args, stdin=None, stdout=None, stderr=None, loop=None, limit=None, **kwds)

서브 프로세스를 만듭니다.

limit 인자는 Process.stdout 과 Process.stderr에 대한 StreamReader 래퍼의 버퍼 한계를 설정합니다 (subprocess.PIPE가 stdout 및 stderr 인자에 전달되었을 때).

Process 인스턴스를 반환합니다.

다른 매개 변수에 관해서는 loop.subprocess_exec()의 설명서를 참조하십시오.

coroutine asyncio.create_subprocess_shell(cmd, stdin=None, stdout=None, stderr=None, loop=None, limit=None, **kwds)

cmd 셸 명령을 실행합니다.

limit 인자는 Process.stdout 과 Process.stderr에 대한 StreamReader 래퍼의 버퍼 한계를 설정합니다 (subprocess.PIPE가 stdout 및 stderr 인자에 전달되었을 때).

Process 인스턴스를 반환합니다.

다른 매개 변수에 관해서는 loop.subprocess_shell()의 설명서를 참조하십시오.

중요

셸 주입 [https://en.wikipedia.org/wiki/Shell_injection#Shell_injection] 취약점을 피하고자 모든 공백과 특수 문자를 적절하게 따옴표로 감싸는 것은 응용 프로그램의 책임입니다. shlex.quote() 함수는 셸 명령을 구성하는 데 사용될 문자열의 공백 문자와 특수 셸 문자를 올바르게 이스케이프 하는 데 사용할 수 있습니다.

참고

윈도우 에서 기본 asyncio 이벤트 루프 구현은 서브 프로세스를 지원하지 않습니다. ProactorEventLoop를 쓰면 윈도우에서 서브 프로세스를 사용할 수 있습니다. 자세한 내용은 윈도우에서의 서브 프로세스 지원을 참조하십시오.

더 보기

또한, asyncio에는 서브 프로세스와 함께 작동하는 다음과 같은 저수준 API가 있습니다: 서브 프로세스 트랜스포트 와 서브 프로세스 프로토콜 뿐만 아니라 loop.subprocess_exec(), loop.subprocess_shell(), loop.connect_read_pipe(), loop.connect_write_pipe().

상수

asyncio.subprocess.PIPE

stdin, stdout 또는 stderr 매개 변수로 전달될 수 있습니다.

PIPE가 stdin 인자로 전달되면, Process.stdin 어트리뷰트는 StreamWriter 인스턴스를 가리킵니다.

PIPE가 stdout 이나 stderr 인자로 전달되면, Process.stdout 과 Process.stderr 어트리뷰트는 StreamReader 인스턴스를 가리 킵니다.

asyncio.subprocess.STDOUT

stderr 인자로 사용할 수 있는 특수 값이며, 표준 에러를 표준 출력으로 리디렉션해야 함을 나타냅니다.

asyncio.subprocess.DEVNULL

프로세스 생성 함수의 stdin, stdout 또는 stderr 인자로 사용할 수 있는 특수 값입니다. 특수 파일 os.devnull이 해당 서브 프로세스 스트림에 사용됨을 나타냅니다.

서브 프로세스와 상호 작용하기

create_subprocess_exec() 와 create_subprocess_shell() 함수는 모두 Process 클래스의 인스턴스를 반환합니다. Process는 서브 프로세스와 통신하고 완료를 관찰할 수 있는 고수준 래퍼입니다.

class asyncio.subprocess.Process

create_subprocess_exec() 와 create_subprocess_shell() 함수로 만들어진 OS 프로세스를 감싸는 객체.

이 클래스는 subprocess.Popen 클래스와 비슷한 API를 갖도록 설계되었지만, 주목할만한 차이점이 있습니다:

Popen과 달리, Process 인스턴스에는 poll() 메서드와 동등한 것이 없습니다;

communicate() 와 wait() 메서드에는 timeout 매개 변수가 없습니다: wait_for() 함수를 사용하십시오;

Process.wait() 메서드는 비동기이지만, subprocess.Popen.wait() 메서드는 블로킹 비지 루프(blocking busy loop)로 구현됩니다;

universal_newlines 매개 변수는 지원되지 않습니다.

이 클래스는 스레드 안전하지 않습니다.

서브 프로세스와 스레드 절도 참조하십시오.

coroutine wait()

자식 프로세스가 종료할 때까지 기다립니다.

returncode 어트리뷰트를 설정하고 반환합니다.

참고

이 메서드는 stdout=PIPE 나 stderr=PIPE를 사용하고 자식 프로세스가 너무 많은 출력을 만들면 교착 상태가 될 수 있습니다. 자식 프로세스는 OS 파이프 버퍼가 더 많은 데이터를 받아들이도록 기다리면서 블록 됩니다. 이 조건을 피하고자, 파이프를 사용할 때는 communicate() 메서드를 사용하십시오.

coroutine communicate(input=None)

프로세스와 상호 작용합니다:

데이터를 stdin으로 보냅니다 (input이 None이 아니면);

EOF에 도달할 때까지 stdout 과 stderr에서 데이터를 읽습니다;

프로세스가 종료할 때까지 기다립니다.

선택적 input 인자는 자식 프로세스로 전송될 데이터(bytes 객체)입니다.

튜플 (stdout_data, stderr_data)를 반환합니다.

input을 stdin에 쓸 때 BrokenPipeError 나 ConnectionResetError 예외가 발생하면, 예외를 무시합니다. 이 조건은 모든 데이터가 stdin에 기록되기 전에 프로세스가 종료할 때 발생합니다.

프로세스의 ‘stdin으로 데이터를 보내려면, 프로세스를 stdin=PIPE로 만들어야 합니다. 마찬가지로, 결과 튜플에서 None 이외의 것을 얻으려면, stdout=PIPE 와/나 stderr=PIPE 인자를 사용하여 프로세스를 만들어야 합니다.

데이터가 메모리에 버퍼링 되므로, 데이터 크기가 크거나 무제한이면 이 메서드를 사용하지 마십시오.

send_signal(signal)

시그널 signal를 자식 프로세스로 보냅니다.

참고

윈도우에서, SIGTERM은 terminate()의 별칭입니다. CTRL_C_EVENT 와 CTRL_BREAK_EVENT는 CREATE_NEW_PROCESS_GROUP을 포함하는 creationflags 매개 변수로 시작된 프로세스로 전송될 수 있습니다.

terminate()

자식 프로세스를 중지합니다.

POSIX 시스템에서 이 메서드는 signal.SIGTERM를 자식 프로세스로 보냅니다.

윈도우에서는 Win32 API 함수 TerminateProcess()가 호출되어 자식 프로세스를 중지합니다.

kill()

자식을 죽입니다.

POSIX 시스템에서 이 메서드는 SIGKILL를 자식 프로세스로 보냅니다.

윈도우에서 이 메서드는 terminate()의 별칭입니다.

stdin

표준 입력 스트림(StreamWriter) 또는 프로세스가 stdin=None으로 만들어졌으면 None.

stdout

표준 출력 스트림(StreamReader) 또는 프로세스가 stdout=None으로 만들어졌으면 None.

stderr

표준 에러 스트림(StreamReader) 또는 프로세스가 stderr=None으로 만들어졌으면 None.

경고

process.stdin.write(), await process.stdout.read() 또는 await process.stderr.read 대신 communicate() 메서드를 사용하십시오. 이렇게 하면 스트림이 읽기나 쓰기를 일시 중지하고 자식 프로세스를 블록하는 것으로 인한 교착 상태가 발생하지 않습니다.

pid

프로세스 식별 번호 (PID).

create_subprocess_shell() 함수로 만들어진 프로세스의 경우, 이 어트리뷰트는 생성된 셸의 PID입니다.

returncode

프로세스가 종료할 때의 반환 코드.

None 값은 프로세스가 아직 종료하지 않았음을 나타냅니다.

음수 값 -N은 자식이 시그널 N으로 종료되었음을 나타냅니다 (POSIX만 해당).

서브 프로세스와 스레드

표준 asyncio 이벤트 루프는 다른 스레드에서 서브 프로세스를 실행하는 것을 지원하지만, 다음과 같은 제약이 있습니다:

이벤트 루프는 메인 스레드에서 실행되어야 합니다.

다른 스레드에서 서브 프로세스를 실행하기 전에 메인 스레드에서 자식 관찰자의 인스턴스를 만들어야 합니다. 메인 스레드에서 get_child_watcher() 함수를 호출하여 자식 감시자의 인스턴스를 만듭니다.

대체 이벤트 루프 구현은 위의 제한 사항을 공유하지 않을 수도 있습니다; 해당 설명서를 참조하십시오.

더 보기

asyncio의 동시성과 다중 스레드 절.

예제

Process 클래스를 사용하여 서브 프로세스를 제어하고 StreamReader 클래스를 사용하여 표준 출력을 읽는 예제.

서브 프로세스는 create_subprocess_exec() 함수로 만듭니다:

import asyncio
import sys

async def get_date():
    code = 'import datetime; print(datetime.datetime.now())'

    # Create the subprocess; redirect the standard output
    # into a pipe.
    proc = await asyncio.create_subprocess_exec(
        sys.executable, '-c', code,
        stdout=asyncio.subprocess.PIPE)

    # Read one line of output.
    data = await proc.stdout.readline()
    line = data.decode('ascii').rstrip()

    # Wait for the subprocess exit.
    await proc.wait()
    return line

if sys.platform == "win32":
    asyncio.set_event_loop_policy(
        asyncio.WindowsProactorEventLoopPolicy())

date = asyncio.run(get_date())
print(f"Current date: {date}")

저수준 API를 사용하여 작성된 같은 예제도 참조하십시오.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

네트워킹과 프로세스 간 통신 »

asyncio — 비동기 I/O »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

네트워킹과 프로세스 간 통신 »

asyncio — 비동기 I/O »

|

큐

asyncio 큐는 queue 모듈의 클래스와 유사하도록 설계되었습니다. asyncio 큐는 스레드 안전하지 않지만, async/await 코드에서 사용되도록 설계되었습니다.

asyncio 큐의 메서드에는 timeout 매개 변수가 없습니다; 시간제한이 있는 큐 연산을 하려면 asyncio.wait_for() 함수를 사용하십시오.

아래의 예제 절도 참조하십시오.

Queue

class asyncio.Queue(maxsize=0, *, loop=None)

선입 선출 (FIFO) 큐.

maxsize가 0보다 작거나 같으면 큐 크기는 무한합니다. 0보다 큰 정수면, 큐가 maxsize에 도달했을 때 get()이 항목을 제거할 때까지 await put()이 블록합니다.

표준 라이브러리의 스레드를 쓰는 queue와는 달리, 큐의 크기는 항상 알려져 있으며 qsize() 메서드를 호출하여 얻을 수 있습니다.

이 클래스는 스레드 안전하지 않습니다.

maxsize

큐에 허용되는 항목 수.

empty()

큐가 비어 있으면 True를 반환하고, 그렇지 않으면 False를 반환합니다.

full()

큐에 maxsize 항목이 있으면 True를 반환합니다.

큐가 maxsize=0 (기본값)으로 초기화되었으면, full()은 절대 True를 반환하지 않습니다.

coroutine get()

큐에서 항목을 제거하고 반환합니다. 큐가 비어 있으면, 항목이 들어올 때까지 기다립니다.

get_nowait()

항목을 즉시 사용할 수 있으면 항목을 반환하고, 그렇지 않으면 QueueEmpty를 발생시킵니다.

coroutine join()

큐의 모든 항목을 수신하여 처리할 때까지 블록합니다.

완료되지 않은 작업 수는 항목이 큐에 추가될 때마다 증가합니다. 이 수는 소비자 코루틴이 항목을 수신했고 그 항목에 관한 작업이 모두 완료되었음을 나타내는 task_done()를 호출할 때마다 감소합니다. 완료되지 않은 작업 수가 0으로 떨어지면 join()가 블록 해제됩니다.

coroutine put(item)

큐에 항목을 넣습니다. 큐가 가득 차면, 항목을 추가할 빈자리가 생길 때까지 기다립니다.

put_nowait(item)

블록하지 않고 항목을 큐에 넣습니다.

자리가 즉시 나지 않으면, QueueFull를 일으킵니다.

qsize()

큐에 있는 항목 수를 돌려줍니다.

task_done()

이전에 큐에 넣은 작업이 완료되었음을 나타냅니다.

큐 소비자가 사용합니다. 작업을 꺼내는 데 사용된 get() 마다, 뒤따르는 task_done() 호출은 작업에 관한 처리가 완료되었음을 큐에 알려줍니다.

join()이 현재 블록 중이면, 모든 항목이 처리될 때 다시 시작됩니다 (큐에 put()한 모든 항목에 대해 task_done() 호출이 수신되었음을 뜻합니다).

큐에 넣은 항목보다 더 많이 호출되면 ValueError를 발생시킵니다.

우선순위 큐

class asyncio.PriorityQueue

Queue의 변형; 우선순위 순서로 항목을 꺼냅니다 (가장 낮은 우선순위가 처음입니다).

엔트리는 일반적으로 (priority_number, data) 형식의 튜플입니다.

LIFO 큐

class asyncio.LifoQueue

가장 최근에 추가된 항목을 먼저 꺼내는 Queue의 변형 (후입 선출).

예외

exception asyncio.QueueEmpty

이 예외는 get_nowait() 메서드가 빈 큐에 호출될 때 발생합니다.

exception asyncio.QueueFull

put_nowait() 메서드가 maxsize에 도달한 큐에 호출될 때 발생하는 예외입니다.

예제

큐를 사용하여 여러 동시 태스크로 작업 부하를 분산시킬 수 있습니다:

import asyncio
import random
import time

async def worker(name, queue):
    while True:
        # Get a "work item" out of the queue.
        sleep_for = await queue.get()

        # Sleep for the "sleep_for" seconds.
        await asyncio.sleep(sleep_for)

        # Notify the queue that the "work item" has been processed.
        queue.task_done()

        print(f'{name} has slept for {sleep_for:.2f} seconds')

async def main():
    # Create a queue that we will use to store our "workload".
    queue = asyncio.Queue()

    # Generate random timings and put them into the queue.
    total_sleep_time = 0
    for _ in range(20):
        sleep_for = random.uniform(0.05, 1.0)
        total_sleep_time += sleep_for
        queue.put_nowait(sleep_for)

    # Create three worker tasks to process the queue concurrently.
    tasks = []
    for i in range(3):
        task = asyncio.create_task(worker(f'worker-{i}', queue))
        tasks.append(task)

    # Wait until the queue is fully processed.
    started_at = time.monotonic()
    await queue.join()
    total_slept_for = time.monotonic() - started_at

    # Cancel our worker tasks.
    for task in tasks:
        task.cancel()
    # Wait until all worker tasks are cancelled.
    await asyncio.gather(*tasks, return_exceptions=True)

    print('====')
    print(f'3 workers slept in parallel for {total_slept_for:.2f} seconds')
    print(f'total expected sleep time: {total_sleep_time:.2f} seconds')

asyncio.run(main())

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

네트워킹과 프로세스 간 통신 »

asyncio — 비동기 I/O »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

네트워킹과 프로세스 간 통신 »

asyncio — 비동기 I/O »

|

예외

exception asyncio.TimeoutError

작업이 주어진 마감 시간을 초과했습니다.

중요

이 예외는 내장 TimeoutError 예외와 다릅니다.

exception asyncio.CancelledError

작업이 취소되었습니다.

이 예외는 asyncio 태스크가 취소될 때 사용자 정의 작업을 수행하기 위해 잡을 수 있습니다. 거의 모든 상황에서 예외를 다시 일으켜야 합니다.

중요

이 예외는 Exception의 서브 클래스이므로, 지나치게 광범위한 try..except 블록에 의해 의도하지 않게 억제될 수 있습니다:

try:
    await operation
except Exception:
    # The cancellation is broken because the *except* block
    # suppresses the CancelledError exception.
    log.log('an error has occurred')

대신, 다음 패턴을 사용해야 합니다:

try:
    await operation
except asyncio.CancelledError:
    raise
except Exception:
    log.log('an error has occurred')

exception asyncio.InvalidStateError

Task 나 Future의 내부 상태가 잘못되었습니다.

이미 결괏값이 설정된 Future 객체에 대해 결괏값을 설정하는 것과 같은 상황에서 발생할 수 있습니다.

exception asyncio.SendfileNotAvailableError

주어진 소켓이나 파일 유형에서는 “sendfile” 시스템 호출을 사용할 수 없습니다.

RuntimeError의 서브 클래스입니다.

exception asyncio.IncompleteReadError

요청한 읽기 작업이 완전히 완료되지 않았습니다.

asyncio 스트림 API가 일으킵니다.

이 예외는 EOFError의 서브 클래스입니다.

expected

기대하는 바이트의 총수 (int).

partial

스트림이 끝나기 전에 읽은 bytes 문자열.

exception asyncio.LimitOverrunError

구분 기호를 찾는 동안 버퍼 크기 제한에 도달했습니다.

asyncio 스트림 API가 일으킵니다.

consumed

소비된 바이트의 총수.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

네트워킹과 프로세스 간 통신 »

asyncio — 비동기 I/O »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

네트워킹과 프로세스 간 통신 »

asyncio — 비동기 I/O »

|

이벤트 루프

머리말

이벤트 루프는 모든 asyncio 응용 프로그램의 핵심입니다. 이벤트 루프는 비동기 태스크 및 콜백을 실행하고 네트워크 IO 연산을 수행하며 자식 프로세스를 실행합니다.

응용 프로그램 개발자는 일반적으로 asyncio.run()과 같은 고수준의 asyncio 함수를 사용해야 하며, 루프 객체를 참조하거나 메서드를 호출할 필요가 거의 없습니다. 이 절은 주로 이벤트 루프 동작을 세부적으로 제어해야 하는 저수준 코드, 라이브러리 및 프레임워크의 작성자를 대상으로 합니다.

이벤트 루프 얻기

다음 저수준 함수를 사용하여 이벤트 루프를 가져오거나 설정하거나 만들 수 있습니다.:

asyncio.get_running_loop()

현재 OS 스레드에서 실행 중인 이벤트 루프를 반환합니다.

실행 중인 이벤트 루프가 없으면 RuntimeError가 발생합니다. 이 함수는 코루틴이나 콜백에서만 호출할 수 있습니다.

버전 3.7에 추가.

asyncio.get_event_loop()

Get the current event loop.

If there is no current event loop set in the current OS thread, the OS thread is main, and set_event_loop() has not yet been called, asyncio will create a new event loop and set it as the current one.

이 함수는 (특히 사용자 정의 이벤트 루프 정책을 사용할 때) 다소 복잡한 동작을 하므로, 코루틴과 콜백에서 get_event_loop()보다 get_running_loop() 함수를 사용하는 것이 좋습니다.

저수준 함수를 사용하여 수동으로 이벤트 루프를 만들고 닫는 대신 asyncio.run() 함수를 사용하는 것도 고려하십시오.

asyncio.set_event_loop(loop)

loop를 현재 OS 스레드의 현재 이벤트 루프로 설정합니다.

asyncio.new_event_loop()

새 이벤트 루프 객체를 만듭니다.

get_event_loop(), set_event_loop() 및 new_event_loop() 함수의 동작은 사용자 정의 이벤트 루프 정책 설정에 의해 변경될 수 있음에 유의하십시오.

목차

이 설명서 페이지는 다음과 같은 절로 구성됩니다:

이벤트 루프 메서드 절은 이벤트 루프 API의 레퍼런스 설명서입니다.

콜백 핸들 절은 loop.call_soon() 및 loop.call_later()와 같은 예약 메서드에서 반환된 Handle 및 TimerHandle 인스턴스를 설명합니다.

서버 객체 절은 loop.create_server()와 같은 이벤트 루프 메서드에서 반환되는 형을 설명합니다.

이벤트 루프 구현 절은 SelectorEventLoop 및 ProactorEventLoop 클래스를 설명합니다.

예제 절에서는 일부 이벤트 루프 API로 작업하는 방법을 보여줍니다.

이벤트 루프 메서드

이벤트 루프에는 다음과 같은 저수준 API가 있습니다:

루프 실행 및 중지

콜백 예약하기

지연된 콜백 예약

퓨처와 태스크 만들기

네트워크 연결 열기

네트워크 서버 만들기

파일 전송

TLS 업그레이드

파일 기술자 관찰하기

소켓 객체로 직접 작업하기

DNS

파이프로 작업하기

유닉스 시그널

스레드 또는 프로세스 풀에서 코드를 실행하기

에러 처리 API

디버그 모드 활성화

자식 프로세스 실행하기

루프 실행 및 중지

loop.run_until_complete(future)

future(Future의 인스턴스)가 완료할 때까지 실행합니다.

인자가 코루틴 객체 면, asyncio.Task로 실행되도록 묵시적으로 예약 됩니다.

퓨처의 결과를 반환하거나 퓨처의 예외를 일으킵니다.

loop.run_forever()

stop()가 호출될 때까지 이벤트 루프를 실행합니다.

run_forever() 가 호출되기 전에 stop() 이 호출되었으면, 루프는 시간제한 0으로 I/O 셀렉터를 한 번 폴링하고, I/O 이벤트에 따라 예약된 모든 콜백(과 이미 예약된 것들)을 실행한 다음 종료합니다.

만약 stop() 이 run_forever() 가 실행 중일 때 호출되면, 루프는 현재 걸려있는 콜백들을 실행한 다음 종료합니다. 콜백에 의해 예약되는 새 콜백은 이 경우 실행되지 않습니다; 대신 그것들은 다음에 run_forever()나 run_until_complete()가 호출될 때 실행됩니다.

loop.stop()

이벤트 루프를 중지합니다.

loop.is_running()

이벤트 루프가 현재 실행 중이면 True 를 반환합니다.

loop.is_closed()

이벤트 루프가 닫혔으면 True 를 반환합니다.

loop.close()

이벤트 루프를 닫습니다.

이 함수를 호출할 때 루프는 반드시 실행 중이지 않아야 합니다. 계류 중인 모든 콜백을 버립니다.

이 메서드는 모든 큐를 비우고 실행기를 종료하지만, 실행기가 완료할 때까지 기다리지 않습니다.

이 메서드는 멱등적(itempotent)이고 되돌릴 수 없습니다. 이벤트 루프가 닫힌 후에 다른 메서드를 호출해서는 안 됩니다.

coroutine loop.shutdown_asyncgens()

현재 열려있는 비동기 제너레이터 객체를 모두 aclose() 호출로 닫도록 예약 합니다. 이 메서드를 호출한 후에는, 새 비동기 생성기가 이터레이트 되면 이벤트 루프에서 경고를 보냅니다. 예약된 모든 비동기 제너레이터를 신뢰성 있게 종료하는 데 사용해야 합니다.

asyncio.run()가 사용될 때 이 함수를 호출할 필요는 없다는 점에 유의하세요.

예:

try:
    loop.run_forever()
finally:
    loop.run_until_complete(loop.shutdown_asyncgens())
    loop.close()

버전 3.6에 추가.

콜백 예약하기

loop.call_soon(callback, *args, context=None)

이벤트 루프의 다음 이터레이션 때 args 인자로 호출할 callback을 예약합니다.

콜백은 등록된 순서대로 호출됩니다. 각 콜백은 정확히 한 번 호출됩니다.

선택적인 키워드 전용 context 인자는 callback 을 실행할 사용자 정의 contextvars.Context 를 지정할 수 있게 합니다. context 가 제공되지 않을 때는 현재 컨텍스트가 사용됩니다.

asyncio.Handle 인스턴스가 반환되는데, 나중에 콜백을 취소하는 데 사용할 수 있습니다.

이 메서드는 스레드 안전하지 않습니다.

loop.call_soon_threadsafe(callback, *args, context=None)

스레드 안전한 call_soon() 변형입니다. 다른 스레드에서 콜백을 예약하는 데 사용해야 합니다.

설명서의 동시성과 다중 스레딩 절을 참고하십시오.

버전 3.7에서 변경: context 키워드 전용 매개 변수가 추가되었습니다. 자세한 정보는 PEP 567 [https://www.python.org/dev/peps/pep-0567]을 보십시오.

참고

대부분 asyncio 예약 함수는 키워드 인자 전달을 허용하지 않습니다. 그렇게 하려면 functools.partial()을 사용하십시오:

# will schedule "print("Hello", flush=True)"
loop.call_soon(
    functools.partial(print, "Hello", flush=True))

asyncio는 디버그 및 오류 메시지에서 partial 객체를 더욱 잘 표시할 수 있으므로, partial 객체를 사용하는 것이 람다를 사용하는 것보다 편리합니다.

지연된 콜백 예약

이벤트 루프는 콜백 함수가 미래의 어떤 시점에서 호출되도록 예약하는 메커니즘을 제공합니다. 이벤트 루프는 단조 시계를 사용하여 시간을 추적합니다.

loop.call_later(delay, callback, *args, context=None)

지정된 delay 초 (int 또는 float) 뒤에 callback 이 호출되도록 예약합니다.

asyncio.TimerHandle 의 인스턴스가 반환되는데, 콜백을 취소하는 데 사용할 수 있습니다.

callback 은 정확히 한번 호출됩니다. 두 콜백이 정확히 같은 시간에 예약되면, 어떤 것이 먼저 호출되는지는 정의되지 않습니다.

선택적 위치 args 는 호출 될 때 콜백에 전달됩니다. 콜백을 키워드 인자로 호출하고 싶으면 functools.partial() 를 사용하십시오.

선택적인 키워드 전용 context 인자는 callback 을 실행할 사용자 정의 contextvars.Context 를 지정할 수 있게 합니다. context 가 제공되지 않을 때는 현재 컨텍스트가 사용됩니다.

버전 3.7에서 변경: context 키워드 전용 매개 변수가 추가되었습니다. 자세한 정보는 PEP 567 [https://www.python.org/dev/peps/pep-0567]을 보십시오.

버전 3.7.1에서 변경: 파이썬 3.7.0 및 이전 버전에서 기본 이벤트 루프 구현을 사용할 때, delay는 하루를 초과할 수 없었습니다. 이 문제는 파이썬 3.7.1에서 수정되었습니다.

loop.call_at(when, callback, *args, context=None)

지정된 절대 타임스탬프 when(int 또는 float)에 callback 이 호출되도록 예약합니다. loop.time() 과 같은 시간 참조를 사용하십시오.

이 메서드의 동작은 call_later()와 같습니다.

asyncio.TimerHandle 의 인스턴스가 반환되는데, 콜백을 취소하는 데 사용할 수 있습니다.

버전 3.7에서 변경: context 키워드 전용 매개 변수가 추가되었습니다. 자세한 정보는 PEP 567 [https://www.python.org/dev/peps/pep-0567]을 보십시오.

버전 3.7.1에서 변경: 파이썬 3.7.0 및 이전 버전에서 기본 이벤트 루프 구현을 사용할 때, when와 현재 시각의 차이는 하루를 초과할 수 없었습니다. 이 문제는 파이썬 3.7.1에서 수정되었습니다.

loop.time()

이벤트 루프의 내부 단조 시계에 따라, float 값으로 현재 시각을 반환합니다.

참고

버전 3.8에서 변경: 파이썬 3.7 및 이전 버전에서 제한 시간(상대적인 delay 나 절대적인 when)은 1일을 초과하지 않아야 했습니다. 이 문제는 파이썬 3.8에서 수정되었습니다.

더 보기

asyncio.sleep() 함수.

퓨처와 태스크 만들기

loop.create_future()

이벤트 루프에 연결된 asyncio.Future 객체를 만듭니다.

이것이 asyncio에서 퓨처를 만드는 데 선호되는 방법입니다. 이렇게 하면 제삼자 이벤트 루프가 Future 객체의 다른 구현(더 나은 성능이나 계측(instrumentation))을 제공할 수 있습니다

버전 3.5.2에 추가.

loop.create_task(coro)

코루틴 의 실행을 예약합니다. Task 객체를 반환합니다.

제삼자 이벤트 루프는 상호 운용성을 위해 자신만의 Task 의 서브 클래스를 사용할 수 있습니다. 이 경우, 결과 형은 Task 의 서브 클래스입니다.

loop.set_task_factory(factory)

loop.create_task() 에 의해 사용되는 태스크 팩토리를 설정합니다.

factory 가 None 이면 기본 태스크 팩토리가 설정됩니다. 그렇지 않으면, factory 는 반드시 콜러블 이어야 하고, (loop, coro) 과 일치하는 서명을 가져야 합니다. 여기서 loop 는 활성 이벤트 루프에 대한 참조가 되고, coro 는 코루틴 객체가 됩니다. 콜러블은 asyncio.Future 호환 객체를 반환해야 합니다.

loop.get_task_factory()

태스크 팩토리를 반환하거나, 기본값이 사용 중이면 None 을 반환합니다.

네트워크 연결 열기

coroutine loop.create_connection(protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None)

주어진 host 와 port로 지정된 주소로의 스트리밍 트랜스포트 연결을 엽니다.

소켓 패밀리는 host(또는 지정된 경우 family)에 따라 AF_INET 또는 AF_INET6일 수 있습니다.

소켓 유형은 SOCK_STREAM이 됩니다.

protocol_factory 는 반드시 asyncio 프로토콜 구현을 반환하는 콜러블이어야 합니다.

이 메서드는 백그라운드에서 연결을 맺으려고 시도합니다. 성공하면, (transport, protocol) 쌍을 반환합니다.

하부 연산의 시간순 개요는 다음과 같습니다:

연결이 맺어지고, 이를 위한 트랜스포트(transport) 가 만들어집니다.

protocol_factory 가 인자 없이 호출되고, 프로토콜(protocol) 인스턴스를 반환할 것으로 기대됩니다.

프로토콜 인스턴스는 connection_made() 메서드를 호출함으로써 트랜스포트와 연결됩니다.

성공하면 (transport, protocol) 튜플이 반환됩니다.

만들어진 트랜스포트는 구현 의존적인 양방향 스트림입니다.

다른 인자들:

ssl: 주어지고 거짓이 아니면, SSL/TLS 트랜스포트가 만들어집니다 (기본적으로는 평범한 TCP 트랜스포트가 만들어집니다). ssl 이 ssl.SSLContext 객체면, 트랜스포트를 만들 때 이 컨텍스트가 사용됩니다; ssl 이 True 면, ssl.create_default_context() 가 반환하는 기본 컨텍스트가 사용됩니다.

더 보기

SSL/TLS 보안 고려 사항

server_hostname는 대상 서버의 인증서가 일치될 호스트 이름을 설정하거나 대체합니다. ssl이 None이 아닐 때만 전달되어야 합니다. 기본적으로 host 인자의 값이 사용됩니다. host 가 비어 있으면, 기본값이 없고 server_hostname 값을 전달해야 합니다. server_hostname 이 빈 문자열이면, 호스트 이름 일치가 비활성화됩니다 (이것은 심각한 보안 위험으로, 잠재적인 중간자 공격을 허용하게 됩니다).

family, proto, flags 는 host 결정을 위해 getaddrinfo() 에 전달할 선택적 주소 패밀리, 프로토콜, 플래그입니다. 주어지면, 이것들은 모두 해당하는 socket 모듈 상수에 대응하는 정수여야 합니다.

sock 이 주어지면, 트랜스포트가 사용할, 기존의 이미 연결된 socket.socket 객체여야 합니다. sock 이 주어지면, host, port, family, proto, flags, local_addr 를 지정해서는 안 됩니다.

local_addr 이 주어지면, 소켓을 로컬에 바인드 하는데 사용되는 (local_host, local_port) 튜플이어야 합니다. local_host 와 local_port 는 host 및 port 와 유사하게 getaddrinfo() 를 사용하여 조회됩니다.

ssl_handshake_timeout 은 (TLS 연결의 경우) 연결을 중단하기 전에 TLS 핸드 셰이크가 완료될 때까지 대기하는 시간(초)입니다. None (기본값) 이면 60.0 초가 사용됩니다.

버전 3.7에 추가: ssl_handshake_timeout 매개 변수.

버전 3.6에서 변경: 소켓 옵션 TCP_NODELAY는 기본적으로 모든 TCP 연결에 대해 설정됩니다.

버전 3.5에서 변경: ProactorEventLoop에 SSL/TLS에 대한 지원이 추가되었습니다.

더 보기

open_connection() 함수는 고수준 대안 API입니다. async/await 코드에서 직접 사용할 수 있는 (StreamReader, StreamWriter) 쌍을 반환합니다.

coroutine loop.create_datagram_endpoint(protocol_factory, local_addr=None, remote_addr=None, *, family=0, proto=0, flags=0, reuse_address=None, reuse_port=None, allow_broadcast=None, sock=None)

참고

The parameter reuse_address is no longer supported, as using SO_REUSEADDR poses a significant security concern for UDP. Explicitly passing reuse_address=True will raise an exception.

When multiple processes with differing UIDs assign sockets to an indentical UDP socket address with SO_REUSEADDR, incoming packets can become randomly distributed among the sockets.

For supported platforms, reuse_port can be used as a replacement for similar functionality. With reuse_port, SO_REUSEPORT is used instead, which specifically prevents processes with differing UIDs from assigning sockets to the same socket address.

데이터 그램 연결을 만듭니다.

소켓 패밀리는 host(또는 주어지면 family)에 따라 AF_INET, AF_INET6 또는 AF_UNIX일 수 있습니다.

소켓 유형은 SOCK_DGRAM이 됩니다.

protocol_factory 는 반드시 프로토콜 구현을 반환하는 콜러블이어야 합니다.

성공하면 (transport, protocol) 튜플이 반환됩니다.

다른 인자들:

local_addr 이 주어지면, 소켓을 로컬에 바인드 하는 데 사용되는 (local_host, local_port) 튜플입니다. local_host 와 local_port 는 getaddrinfo()를 사용하여 조회됩니다.

remote_addr 이 주어지면, 소켓을 원격 주소에 연결하는 데 사용되는 (remote_host, remote_port) 튜플입니다. remote_host 와 remote_port 는 getaddrinfo()를 사용하여 조회됩니다.

family, proto, flags 는 host 결정을 위해 getaddrinfo() 에 전달할 선택적 주소 패밀리, 프로토콜, 플래그입니다. 주어지면, 이것들은 모두 해당하는 socket 모듈 상수에 대응하는 정수여야 합니다.

reuse_port 는 모두 만들 때 이 플래그를 설정하는 한, 이 말단이 다른 기존 말단이 바인드 된 것과 같은 포트에 바인드 되도록 허용하도록 커널에 알려줍니다. 이 옵션은 윈도우나 일부 유닉스에서는 지원되지 않습니다. SO_REUSEPORT 상수가 정의되어 있지 않으면, 이 기능은 지원되지 않는 것입니다.

allow_broadcast 는 이 말단이 브로드캐스트 주소로 메시지를 보낼 수 있도록 커널에 알립니다.

sock 은 트랜스포트가 사용할 소켓 객체로, 기존의 이미 연결된 socket.socket 객체를 사용하기 위해 선택적으로 지정할 수 있습니다. 지정되면 local_addr 과 remote_addr 를 생략해야 합니다 (반드시 None 이어야 합니다).

윈도우에서, ProactorEventLoop를 사용할 때, 이 메서드는 지원되지 않습니다.

UDP 메아리 클라이언트 프로토콜 과 UDP 메아리 서버 프로토콜 예제를 참고하세요.

버전 3.4.4에서 변경: family, proto, flags, reuse_address, reuse_port, allow_broadcast, sock 매개 변수가 추가되었습니다.

버전 3.7.6에서 변경: The reuse_address parameter is no longer supported due to security concerns.

coroutine loop.create_unix_connection(protocol_factory, path=None, *, ssl=None, sock=None, server_hostname=None, ssl_handshake_timeout=None)

유닉스 연결을 만듭니다.

소켓 패밀리는 AF_UNIX가 됩니다; 소켓 유형은 SOCK_STREAM이 됩니다.

성공하면 (transport, protocol) 튜플이 반환됩니다.

path 는 유닉스 도메인 소켓의 이름이며, sock 매개 변수가 지정되지 않으면 필수입니다. 추상 유닉스 소켓, str, bytes, Path 경로가 지원됩니다.

이 메서드의 인자에 관한 정보는 loop.create_connection() 메서드의 설명서를 참조하십시오.

가용성: 유닉스.

버전 3.7에 추가: ssl_handshake_timeout 매개 변수.

버전 3.7에서 변경: path 매개 변수는 이제 경로류 객체 가 될 수 있습니다.

네트워크 서버 만들기

coroutine loop.create_server(protocol_factory, host=None, port=None, *, family=socket.AF_UNSPEC, flags=socket.AI_PASSIVE, sock=None, backlog=100, ssl=None, reuse_address=None, reuse_port=None, ssl_handshake_timeout=None, start_serving=True)

host 주소의 port 에서 리스닝하는 TCP 서버(소켓 유형 SOCK_STREAM)를 만듭니다.

Server 객체를 반환합니다.

인자:

protocol_factory 는 반드시 프로토콜 구현을 반환하는 콜러블이어야 합니다.

host 매개 변수는 서버가 리스닝할 위치를 결정하는 여러 형으로 설정할 수 있습니다.:

host가 문자열이면, TCP 서버는 host로 지정된 단일 네트워크 인터페이스에 바인딩 됩니다.

host가 문자열의 시퀀스면, TCP 서버는 시퀀스로 지정된 모든 네트워크 인터페이스에 바인딩 됩니다.

host가 빈 문자열이거나 None이면, 모든 인터페이스가 사용되는 것으로 가정하고, 여러 소켓의 리스트가 반환됩니다 (대체로 IPv4 하나와 IPv6 하나).

family 는 socket.AF_INET 또는 AF_INET6 중 하나로 설정되어, 소켓이 IPv4 또는 IPv6을 사용하게 할 수 있습니다. 설정되지 않으면, family 는 호스트 이름에 의해 결정됩니다(기본값 socket.AF_UNSPEC).

flags 은 getaddrinfo()를 위한 비트 마스크입니다.

sock 은 기존 소켓 객체를 사용하기 위해 선택적으로 지정할 수 있습니다. 지정되면, host 및 port 는 지정할 수 없습니다.

backlog 는 listen() 으로 전달되는 최대 대기 연결 수 입니다 (기본값은 100).

ssl 을 SSLContext 인스턴스로 설정하면, 들어오는 연결에 TLS를 사용합니다.

reuse_address 는, 일반적인 시간제한이 만료될 때까지 기다리지 않고, TIME_WAIT 상태의 로컬 소켓을 재사용하도록 커널에 알려줍니다. 지정하지 않으면 유닉스에서 자동으로 True 로 설정됩니다.

reuse_port 는 모두 만들 때 이 플래그를 설정하는 한, 이 말단이 다른 기존 말단이 바인드 된 것과 같은 포트에 바인드 되도록 허용하도록 커널에 알려줍니다. 이 옵션은 윈도우에서 지원되지 않습니다.

ssl_handshake_timeout 은 (TLS 서버의 경우) 연결을 중단하기 전에 TLS 핸드 셰이크가 완료될 때까지 대기하는 시간(초)입니다. None (기본값) 이면 60.0 초가 사용됩니다.

start_serving 을 True (기본값) 로 설정하면, 생성된 서버가 즉시 연결을 받아들입니다. False 로 설정되면, 사용자는 서버가 연결을 받기 시작하도록 Server.start_serving() 이나 Server.serve_forever()를 await 해야 합니다.

버전 3.7에 추가: ssl_handshake_timeout 과 start_serving 매개 변수 추가.

버전 3.6에서 변경: 소켓 옵션 TCP_NODELAY는 기본적으로 모든 TCP 연결에 대해 설정됩니다.

버전 3.5에서 변경: ProactorEventLoop에 SSL/TLS에 대한 지원이 추가되었습니다.

버전 3.5.1에서 변경: host 매개 변수는 문자열의 시퀀스가 될 수 있습니다.

더 보기

start_server() 함수는 async/await 코드에서 사용할 수 있는 StreamReader 및 StreamWriter 쌍을 반환하는 고수준의 대체 API입니다.

coroutine loop.create_unix_server(protocol_factory, path=None, *, sock=None, backlog=100, ssl=None, ssl_handshake_timeout=None, start_serving=True)

loop.create_server()와 유사하지만, 소켓 패밀리 AF_UNIX 용입니다.

path 는 유닉스 도메인 소켓의 이름이며, sock 매개 변수가 제공되지 않으면 필수입니다. 추상 유닉스 소켓, str, bytes, Path 경로가 지원됩니다.

이 메서드의 인자에 대한 정보는 loop.create_server() 메서드의 설명서를 참조하십시오.

가용성: 유닉스.

버전 3.7에 추가: ssl_handshake_timeout 과 start_serving 매개 변수.

버전 3.7에서 변경: path 매개 변수는 이제 Path 객체일 수 있습니다.

coroutine loop.connect_accepted_socket(protocol_factory, sock, *, ssl=None, ssl_handshake_timeout=None)

이미 받아들인 연결을 트랜스포트/프로토콜 쌍으로 래핑합니다.

이 메서드는 asyncio 밖에서 연결을 받아들이지만, 그 연결을 처리하는데 asyncio 를 사용하는 서버에서 사용됩니다.

매개 변수:

protocol_factory 는 반드시 프로토콜 구현을 반환하는 콜러블이어야 합니다.

sock 은 socket.accept 가 반환한 기존 소켓 객체입니다.

ssl 을 SSLContext 로 설정하면, 들어오는 연결에 SSL을 사용합니다.

ssl_handshake_timeout 은 (SSL 연결의 경우) 연결을 중단하기 전에 SSL 핸드 셰이크가 완료될 때까지 대기하는 시간(초)입니다. None (기본값) 이면 60.0 초가 사용됩니다.

(transport, protocol) 쌍을 반환합니다.

버전 3.7에 추가: ssl_handshake_timeout 매개 변수.

버전 3.5.3에 추가.

파일 전송

coroutine loop.sendfile(transport, file, offset=0, count=None, *, fallback=True)

file 을 transport 로 보냅니다. 전송된 총 바이트 수를 반환합니다.

이 메서드는 가능한 경우 고성능 os.sendfile() 을 사용합니다.

file 는 바이너리 모드로 열린 일반 파일 객체여야 합니다.

offset 은 파일 읽기 시작할 위치를 알려줍니다. count 를 제공하면, EOF에 도달할 때까지 파일을 보내는 대신, 전송할 총 바이트 수를 지정합니다. 파일의 위치가 갱신됩니다, 이 메서드가 에러를 일으킬 때조차. 그리고, file.tell() 는 실제 전송된 바이트 수를 얻는 데 사용될 수 있습니다.

fallback 을 True 로 설정하면, 플랫폼이 sendfile 시스템 호출을 지원하지 않을 때 (가령 유닉스에서 SSL 소켓을 사용하거나 윈도우인 경우), asyncio 가 파일을 수동으로 읽고 보내도록 합니다.

시스템이 sendfile 시스템 호출을 지원하지 않고 fallback 이 False 면 SendfileNotAvailableError 를 발생시킵니다.

버전 3.7에 추가.

TLS 업그레이드

coroutine loop.start_tls(transport, protocol, sslcontext, *, server_side=False, server_hostname=None, ssl_handshake_timeout=None)

기존 트랜스포트 기반 연결을 TLS로 업그레이드합니다.

protocol 이 await 의 직후에 사용해야 하는 새로운 트랜스포트 인스턴스를 반환합니다. start_tls 메서드에 전달된 transport 인스턴스는 절대로 다시 사용해서는 안 됩니다.

매개 변수:

create_server()와 create_connection() 같은 메서드가 반환하는 transport 와 protocol 인스턴스.

sslcontext: 구성된 SSLContext 의 인스턴스.

(create_server() 에 의해 생성된 것과 같은) 서버 측 연결이 업그레이드될 때 server_side 에 True 를 전달합니다.

server_hostname: 대상 서버의 인증서가 일치될 호스트 이름을 설정하거나 대체합니다.

ssl_handshake_timeout 은 (TLS 연결의 경우) 연결을 중단하기 전에 TLS 핸드 셰이크가 완료될 때까지 대기하는 시간(초)입니다. None (기본값) 이면 60.0 초가 사용됩니다.

버전 3.7에 추가.

파일 기술자 관찰하기

loop.add_reader(fd, callback, *args)

fd 파일 기술자가 읽기 가능한지 관찰하기 시작하고, 일단 fd가 읽기 가능해지면 지정한 인자로 callback 을 호출합니다.

loop.remove_reader(fd)

fd 파일 기술자가 읽기 가능한지 관찰하는 것을 중단합니다.

loop.add_writer(fd, callback, *args)

fd 파일 기술자가 쓰기 가능한지 관찰하기 시작하고, 일단 fd가 쓰기 가능해지면 지정한 인자로 callback 을 호출합니다.

callback 에 키워드 인자를 전달하려면 functools.partial()를 사용하십시오.

loop.remove_writer(fd)

fd 파일 기술자가 쓰기 가능한지 관찰하는 것을 중단합니다.

이 메서드의 일부 제한 사항은 플랫폼 지원 절을 참조하십시오.

소켓 객체로 직접 작업하기

일반적으로 loop.create_connection() 및 loop.create_server()와 같은 트랜스포트 기반 API를 사용하는 프로토콜 구현은 소켓을 직접 사용하는 구현보다 빠릅니다. 그러나, 성능이 결정적이지 않고 socket 객체로 직접 작업하는 것이 더 편리한 사용 사례가 있습니다.

coroutine loop.sock_recv(sock, nbytes)

sock 에서 최대 nbytes 를 수신합니다. socket.recv() 의 비동기 버전.

수신한 데이터를 바이트열 객체로 반환합니다.

sock 은 반드시 비 블로킹 소켓이어야 합니다.

버전 3.7에서 변경: 이 메서드가 항상 코루틴 메서드라고 설명되어왔지만, 파이썬 3.7 이전에는 Future를 반환했습니다. 파이썬 3.7부터, 이것은 async def 메서드입니다.

coroutine loop.sock_recv_into(sock, buf)

sock 에서 buf 버퍼로 데이터를 수신합니다. 블로킹 socket.recv_into() 메서드를 따라 만들어졌습니다.

버퍼에 기록된 바이트 수를 돌려줍니다.

sock 은 반드시 비 블로킹 소켓이어야 합니다.

버전 3.7에 추가.

coroutine loop.sock_sendall(sock, data)

data 를 sock 소켓으로 보냅니다. socket.sendall() 의 비동기 버전.

이 메서드는 data 의 모든 데이터가 송신되거나 에러가 발생할 때까지 소켓으로 계속 송신합니다. 성공하면 None 이 반환됩니다. 에러가 발생하면 예외가 발생합니다. 또한, 연결의 수신 단에서 성공적으로 처리한 (있기는 하다면) 데이터의 크기를 확인하는 방법은 없습니다.

sock 은 반드시 비 블로킹 소켓이어야 합니다.

버전 3.7에서 변경: 이 메서드가 항상 코루틴 메서드라고 설명되어왔지만, 파이썬 3.7 이전에는 Future를 반환했습니다. 파이썬 3.7부터, 이것은 async def 메서드입니다.

coroutine loop.sock_connect(sock, address)

sock을 address에 있는 원격 소켓에 연결합니다.

socket.connect() 의 비동기 버전.

sock 은 반드시 비 블로킹 소켓이어야 합니다.

버전 3.5.2에서 변경: address 는 더는 결정될 필요가 없습니다. sock_connect 는 socket.inet_pton()을 호출하여 address 가 이미 결정되었는지를 검사합니다. 그렇지 않으면, loop.getaddrinfo() 가 address 를 결정하는 데 사용됩니다.

더 보기

loop.create_connection()과 asyncio.open_connection().

coroutine loop.sock_accept(sock)

연결을 받아들입니다. 블로킹 socket.accept() 메서드를 따라 만들어졌습니다.

소켓은 주소에 바인드 되어 연결을 리스닝해야 합니다. 반환 값은 (conn, address) 쌍인데, conn 은 연결로 데이터를 주고받을 수 있는 새 소켓 객체이고, address 는 연결의 반대편 끝의 소켓에 바인드 된 주소입니다.

sock 은 반드시 비 블로킹 소켓이어야 합니다.

버전 3.7에서 변경: 이 메서드가 항상 코루틴 메서드라고 설명되어왔지만, 파이썬 3.7 이전에는 Future를 반환했습니다. 파이썬 3.7부터, 이것은 async def 메서드입니다.

더 보기

loop.create_server()와 start_server().

coroutine loop.sock_sendfile(sock, file, offset=0, count=None, *, fallback=True)

가능하면 고성능 os.sendfile 을 사용하여 파일을 보냅니다. 전송된 총 바이트 수를 반환합니다.

socket.sendfile()의 비동기 버전.

sock 은 반드시 비 블로킹 socket.SOCK_STREAM socket 이어야 합니다.

file 는 바이너리 모드로 열린 일반 파일 객체여야 합니다.

offset 은 파일 읽기 시작할 위치를 알려줍니다. count 를 제공하면, EOF에 도달할 때까지 파일을 보내는 대신, 전송할 총 바이트 수를 지정합니다. 파일의 위치가 갱신됩니다, 이 메서드가 에러를 일으킬 때조차. 그리고, file.tell() 는 실제 전송된 바이트 수를 얻는 데 사용될 수 있습니다.

fallback 을 True 로 설정하면, 플랫폼이 sendfile 시스템 호출을 지원하지 않을 때 (가령 유닉스에서 SSL 소켓을 사용하거나 윈도우인 경우), asyncio 가 파일을 수동으로 읽고 보내도록 합니다.

시스템이 sendfile 시스템 호출을 지원하지 않고 fallback 이 False 면 SendfileNotAvailableError 를 발생시킵니다.

sock 은 반드시 비 블로킹 소켓이어야 합니다.

버전 3.7에 추가.

DNS

coroutine loop.getaddrinfo(host, port, *, family=0, type=0, proto=0, flags=0)

socket.getaddrinfo() 의 비동기 버전.

coroutine loop.getnameinfo(sockaddr, flags=0)

socket.getnameinfo() 의 비동기 버전.

버전 3.7에서 변경: getaddrinfo 와 getnameinfo 메서드는 모두 코루틴 메서드라고 설명되어왔지만, 파이썬 3.7 이전에 실제로는 asyncio.Future 객체를 반환했습니다. 파이썬 3.7부터 두 가지 메서드 모두 코루틴입니다.

파이프로 작업하기

coroutine loop.connect_read_pipe(protocol_factory, pipe)

이벤트 루프에 pipe의 읽기용 끝을 등록합니다.

protocol_factory 는 반드시 asyncio 프로토콜 구현을 반환하는 콜러블이어야 합니다.

pipe는 파일류 객체입니다.

쌍 (transport, protocol)를 반환합니다. 여기서 transport는 ReadTransport 인터페이스를 지원하고, protocol은 protocol_factory에 의해 인스턴스로 만들어진 객체입니다.

SelectorEventLoop 이벤트 루프를 사용하면, pipe 는 비 블로킹 모드로 설정됩니다.

coroutine loop.connect_write_pipe(protocol_factory, pipe)

이벤트 루프에 pipe의 쓰기용 끝을 등록합니다.

protocol_factory 는 반드시 asyncio 프로토콜 구현을 반환하는 콜러블이어야 합니다.

pipe는 파일류 객체입니다.

쌍 (transport, protocol)를 반환합니다. 여기서 transport는 WriteTransport 인터페이스를 지원하고, protocol은 protocol_factory에 의해 인스턴스로 만들어진 객체입니다.

SelectorEventLoop 이벤트 루프를 사용하면, pipe 는 비 블로킹 모드로 설정됩니다.

참고

윈도우에서 SelectorEventLoop는 위의 메서드들을 지원하지 않습니다. 윈도우에서는 대신 ProactorEventLoop를 사용하십시오.

더 보기

loop.subprocess_exec() 와 loop.subprocess_shell() 메서드.

유닉스 시그널

loop.add_signal_handler(signum, callback, *args)

callback을 signum 시그널의 처리기로 설정합니다.

콜백은 다른 대기 중인 콜백과 해당 이벤트 루프의 실행 가능한 코루틴과 함께 loop에 의해 호출됩니다. signal.signal()을 사용하여 등록된 시그널 처리기와 달리, 이 함수로 등록된 콜백은 이벤트 루프와 상호 작용할 수 있습니다.

시그널 번호가 유효하지 않거나 잡을 수 없으면 ValueError 를 발생시킵니다. 처리기를 설정하는 데 문제가 있는 경우 RuntimeError 를 발생시킵니다.

callback 에 키워드 인자를 전달하려면 functools.partial()를 사용하십시오.

signal.signal()와 마찬가지로, 이 함수는 메인 스레드에서 호출되어야 합니다.

loop.remove_signal_handler(sig)

sig 시그널의 처리기를 제거합니다.

시그널 처리기가 제거되면 True 를, 주어진 시그널에 처리기가 설정되지 않았으면 False 를 반환합니다.

가용성: 유닉스.

더 보기

signal 모듈.

스레드 또는 프로세스 풀에서 코드를 실행하기

awaitable loop.run_in_executor(executor, func, *args)

지정된 실행기에서 func 가 호출되도록 배치합니다.

executor 인자는 Executor 인스턴스여야 합니다. executor 가 None 이면 기본 실행기가 사용됩니다.

예:

import asyncio
import concurrent.futures

def blocking_io():
    # File operations (such as logging) can block the
    # event loop: run them in a thread pool.
    with open('/dev/urandom', 'rb') as f:
        return f.read(100)

def cpu_bound():
    # CPU-bound operations will block the event loop:
    # in general it is preferable to run them in a
    # process pool.
    return sum(i * i for i in range(10 ** 7))

async def main():
    loop = asyncio.get_running_loop()

    ## Options:

    # 1. Run in the default loop's executor:
    result = await loop.run_in_executor(
        None, blocking_io)
    print('default thread pool', result)

    # 2. Run in a custom thread pool:
    with concurrent.futures.ThreadPoolExecutor() as pool:
        result = await loop.run_in_executor(
            pool, blocking_io)
        print('custom thread pool', result)

    # 3. Run in a custom process pool:
    with concurrent.futures.ProcessPoolExecutor() as pool:
        result = await loop.run_in_executor(
            pool, cpu_bound)
        print('custom process pool', result)

asyncio.run(main())

이 메서드는 asyncio.Future 객체를 반환합니다.

func 에 키워드 인자를 전달하려면 functools.partial()를 사용하십시오.

버전 3.5.3에서 변경: loop.run_in_executor() 는 더는 자신이 만드는 스레드 풀 실행기의 max_workers 를 설정하지 않습니다. 대신 스레드 풀 실행기(ThreadPoolExecutor)가 스스로 기본값을 설정하도록 합니다.

loop.set_default_executor(executor)

executor를 run_in_executor()에서 사용하는 기본 실행기로 설정합니다. executor는 ThreadPoolExecutor의 인스턴스여야 합니다.

버전 3.7부터 폐지: ThreadPoolExecutor 인스턴스가 아닌 실행기의 사용은 폐지되었고, 파이썬 3.9에서는 에러를 일으키게 됩니다.

executor는 반드시 concurrent.futures.ThreadPoolExecutor의 인스턴스여야 합니다.

에러 처리 API

이벤트 루프에서 예외를 처리하는 방법을 사용자 정의 할 수 있습니다.

loop.set_exception_handler(handler)

handler 를 새 이벤트 루프 예외 처리기로 설정합니다.

handler가 None 이면, 기본 예외 처리기가 설정됩니다. 그렇지 않으면, handler는 반드시 (loop, context) 와 일치하는 서명을 가진 콜러블이어야 합니다. 여기서 loop는 활성 이벤트 루프에 대한 참조가 될 것이고, context 는 예외에 관한 세부 정보를 담고 있는 dict 객체가 됩니다 (context에 대한 자세한 내용은 call_exception_handler() 문서를 참조하십시오).

loop.get_exception_handler()

현재 예외 처리기를 반환하거나, 사용자 정의 예외 처리기가 설정되지 않았으면 None 을 반환합니다.

버전 3.5.2에 추가.

loop.default_exception_handler(context)

기본 예외 처리기.

예외가 발생하고 예외 처리기가 설정되지 않았을 때 호출됩니다. 기본 동작으로 위임하려는 사용자 정의 예외 처리기가 호출할 수 있습니다.

context 매개 변수는 call_exception_handler() 에서와 같은 의미입니다.

loop.call_exception_handler(context)

현재 이벤트 루프 예외 처리기를 호출합니다.

context 는 다음 키를 포함하는 dict 객체입니다 (새 키가 미래의 파이썬 버전에서 추가될 수 있습니다):

‘message’: 에러 메시지;

‘exception’ (선택적): 예외 객체;

‘future’ (선택적): asyncio.Future 인스턴스;

‘handle’ (선택적): asyncio.Handle 인스턴스;

‘protocol’ (선택적): 프로토콜 인스턴스;

‘transport’ (선택적): 트랜스포트 인스턴스;

‘socket’ (선택적): socket.socket 인스턴스.

참고

이 메서드는 서브 클래스 된 이벤트 루프에서 재정의되지 않아야 합니다. 사용자 정의 예외 처리를 위해서는 set_exception_handler() 메서드를 사용하십시오.

디버그 모드 활성화

loop.get_debug()

이벤트 루프의 디버그 모드(bool)를 가져옵니다.

기본값은 환경 변수 PYTHONASYNCIODEBUG 가 비어 있지 않은 문자열로 설정되면 True 이고, 그렇지 않으면 False 입니다.

loop.set_debug(enabled: bool)

이벤트 루프의 디버그 모드를 설정합니다.

버전 3.7에서 변경: 이제 새로운 -X dev 명령 줄 옵션을 사용하여 디버그 모드를 활성화할 수 있습니다.

더 보기

asyncio의 디버그 모드.

자식 프로세스 실행하기

이 하위 절에서 설명하는 메서드는 저수준입니다. 일반적인 async/await 코드에서는 대신 고수준의 asyncio.create_subprocess_shell() 및 asyncio.create_subprocess_exec() 편리 함수를 사용하는 것을 고려하십시오.

참고

Windows 의 기본 asyncio 이벤트 루프는 자식 프로세스를 지원하지 않습니다. 자세한 내용은 윈도우에서의 자식 프로세스 지원을 참조하십시오.

coroutine loop.subprocess_exec(protocol_factory, *args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, **kwargs)

args로 지정된 하나 이상의 문자열 인자로 서브 프로세스를 만듭니다.

args는 반드시 다음과 같은 것으로 표현되는 문자열의 목록이어야 합니다:

str;

또는 파일 시스템 인코딩으로로 인코딩된 bytes.

첫 번째 문자열은 프로그램 실행 파일을 지정하고, 나머지 문자열은 인자를 지정합니다. 함께, 문자열 인자들은 프로그램의 argv를 구성합니다.

이것은 shell=False와 문자열의 목록을 첫 번째 인자로 호출된 표준 라이브러리 subprocess.Popen 클래스와 유사합니다. 그러나 Popen이 문자열 목록인 단일 인자를 받아들이지만, subprocess_exec는 여러 문자열 인자를 받아들입니다.

protocol_factory는 반드시 asyncio.SubprocessProtocol 클래스의 서브 클래스를 반환하는 콜러블이어야 합니다.

다른 매개 변수:

stdin: connect_write_pipe()를 사용하여 자식 프로세스의 표준 입력 스트림에 연결될 파이프를 나타내는 파일류 객체 또는 subprocess.PIPE 상수 (기본값). 기본적으로 새 파이프가 만들어지고 연결됩니다.

stdout: connect_read_pipe()를 사용하여 자식 프로세스의 표준 출력 스트림에 연결될 파이프를 나타내는 파일류 객체 또는 subprocess.PIPE 상수 (기본값). 기본적으로 새 파이프가 만들어지고 연결됩니다.

stderr: connect_read_pipe()를 사용하여 자식 프로세스의 표준 에러 스트림에 연결될 파이프를 나타내는 파일류 객체 또는 subprocess.PIPE (기본값) 또는 subprocess.STDOUT 상수 중 하나.

기본적으로 새 파이프가 만들어지고 연결됩니다. subprocess.STDOUT가 지정되면, 자식 프로세스의 표준 에러 스트림은 표준 출력 스트림과 같은 파이프에 연결됩니다.

다른 모든 키워드 인자는 해석 없이 subprocess.Popen로 전달됩니다. 다만, bufsize, universal_newlines 및 shell은 예외인데, 이것들은 지정되지 않아야 합니다.

다른 인자에 관한 설명은 subprocess.Popen 클래스의 생성자를 참조하십시오.

(transport, protocol) 쌍을 반환합니다. 여기에서 transport는 asyncio.SubprocessTransport 베이스 클래스를 따르고, protocol은 protocol_factory에 의해 인스턴스로 만들어진 객체입니다.

coroutine loop.subprocess_shell(protocol_factory, cmd, *, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, **kwargs)

플랫폼의 “셸” 구문을 사용하는 cmd로 자식 프로세스를 만듭니다. cmd는 str이나 파일 시스템 인코딩으로 인코딩된 bytes 일 수 있습니다.

이것은 shell=True로 호출된 표준 라이브러리 subprocess.Popen 클래스와 유사합니다.

protocol_factory는 반드시 SubprocessProtocol 클래스의 서브 클래스를 반환하는 콜러블이어야 합니다.

나머지 인자에 관한 자세한 내용은 subprocess_exec()를 참조하십시오.

(transport, protocol) 쌍을 반환합니다. 여기서 transport는 SubprocessTransport 베이스 클래스를 따르고, protocol은 protocol_factory에 의해 인스턴스로 만들어진 객체입니다.

참고

셸 주입 [https://en.wikipedia.org/wiki/Shell_injection#Shell_injection] 취약점을 피하고자 모든 공백과 특수 문자를 적절하게 따옴표 처리하는 것은 응용 프로그램의 책임입니다. shlex.quote() 함수를 사용하여 셸 명령을 구성하는 데 사용될 문자열에 있는 공백 및 특수 문자를 올바르게 이스케이프 할 수 있습니다.

콜백 핸들

class asyncio.Handle

loop.call_soon(), loop.call_soon_threadsafe() 에 의해 반환되는 콜백 래퍼 객체.

cancel()

콜백을 취소합니다. 콜백이 이미 취소되었거나 실행되었다면 이 메서드는 아무 효과가 없습니다.

cancelled()

콜백이 취소되었으면 True 을 반환합니다.

버전 3.7에 추가.

class asyncio.TimerHandle

loop.call_later() 및 loop.call_at() 에 의해 반환되는 콜백 래퍼 객체.

이 클래스는 Handle의 서브 클래스입니다.

when()

예약된 콜백 시간을 float 초로 반환합니다.

시간은 절대 타임스탬프입니다. loop.time() 과 같은 시간 참조를 사용합니다.

버전 3.7에 추가.

서버 객체

Server 객체는 loop.create_server(), loop.create_unix_server(), start_server(), start_unix_server()로 만듭니다.

클래스의 인스턴스를 직접 만들지 마십시오.

class asyncio.Server

Server 객체는 비동기 컨텍스트 관리자입니다. async with 문에서 사용될 때, async with 문이 완료되면 서버 객체가 닫혀 있고 새 연결을 받아들이지 않는다는 것이 보장됩니다:

srv = await loop.create_server(...)

async with srv:
    # some code

# At this point, srv is closed and no longer accepts new connections.

버전 3.7에서 변경: Server 객체는 파이썬 3.7부터 비동기 컨텍스트 관리자입니다.

close()

서버를 중지합니다: 리스닝 소켓을 닫고 sockets 어트리뷰트를 None 으로 설정합니다.

이미 받아들여진 클라이언트 연결을 나타내는 소켓은 열린 채로 있습니다.

서버는 비동기적으로 닫힙니다. 서버가 닫힐 때까지 대기하려면 wait_closed() 코루틴을 사용하십시오.

get_loop()

서버 객체와 연관된 이벤트 루프를 반환합니다.

버전 3.7에 추가.

coroutine start_serving()

연결을 받아들이기 시작합니다.

이 메서드는 멱등적이라서, 서버가 이미 시작되었을 때도 호출 할 수 있습니다.

loop.create_server()와 asyncio.start_server() 의 start_serving 키워드 전용 매개 변수는 즉시 연결을 받아들이지 않는 서버 객체를 만들 수 있도록 합니다. 이 경우 Server.start_serving(), 또는 Server.serve_forever()를 사용하여 Server가 연결을 받아들이기 시작하도록 할 수 있습니다.

버전 3.7에 추가.

coroutine serve_forever()

코루틴이 취소될 때까지 연결을 받아들이기 시작합니다. serve_forever 태스크를 취소하면 서버가 닫힙니다.

이 메서드는 서버가 이미 연결을 받아들이고 있어도 호출 할 수 있습니다. 하나의 Server 객체 당 하나의 serve_forever 태스크만 존재할 수 있습니다.

예:

async def client_connected(reader, writer):
    # Communicate with the client with
    # reader/writer streams.  For example:
    await reader.readline()

async def main(host, port):
    srv = await asyncio.start_server(
        client_connected, host, port)
    await srv.serve_forever()

asyncio.run(main('127.0.0.1', 0))

버전 3.7에 추가.

is_serving()

서버가 새 연결을 받아들이고 있으면 True 를 반환합니다.

버전 3.7에 추가.

coroutine wait_closed()

close() 메서드가 완료될 때까지 기다립니다.

sockets

서버가 리스닝하고 있는 socket.socket 객체의 리스트, 또는 서버가 닫혀 있다면 None.

버전 3.7에서 변경: 파이썬 3.7 이전에는 Server.sockets 가 서버 소켓의 내부 리스트를 직접 반환했습니다. 3.7에서는 그 리스트의 복사본이 반환됩니다.

이벤트 루프 구현

asyncio에는 두 가지 이벤트 루프 구현이 함께 제공됩니다: SelectorEventLoop 및 ProactorEventLoop.

기본적으로 asyncio는 모든 플랫폼에서 SelectorEventLoop를 사용하도록 구성됩니다.

class asyncio.SelectorEventLoop

selectors 모듈을 기반으로 하는 이벤트 루프.

주어진 플랫폼에서 사용할 수 있는 가장 효율적인 selector를 사용합니다. 정확한 셀렉터 구현을 수동으로 구성하여 사용할 수도 있습니다.:

import asyncio
import selectors

selector = selectors.SelectSelector()
loop = asyncio.SelectorEventLoop(selector)
asyncio.set_event_loop(loop)

가용성: 유닉스, 윈도우.

class asyncio.ProactorEventLoop

“I/O 완료 포트”(IOCP)를 사용하는 윈도우용 이벤트 루프.

가용성: 윈도우.

윈도우에서 ProactorEventLoop를 사용하는 예:

import asyncio
import sys

if sys.platform == 'win32':
    loop = asyncio.ProactorEventLoop()
    asyncio.set_event_loop(loop)

더 보기

I/O 완료 포트에 관한 MSDN 설명서 [https://docs.microsoft.com/en-ca/windows/desktop/FileIO/i-o-completion-ports].

class asyncio.AbstractEventLoop

asyncio 호환 이벤트 루프의 추상 베이스 클래스.

이벤트 루프 메서드 절은 AbstractEventLoop의 다른 구현이 정의해야 하는 모든 메서드를 나열합니다.

예제

이 절의 모든 예는 의도적으로 loop.run_forever() 및 loop.call_soon()와 같은 저수준 이벤트 루프 API를 사용하는 방법을 보여줍니다. 현대 asyncio 응용 프로그램은 거의 이런 식으로 작성할 필요가 없습니다; asyncio.run()과 같은 고수준 함수를 사용하는 것을 고려하십시오.

call_soon()을 사용하는 Hello World

콜백을 예약하기 위해 loop.call_soon() 메서드를 사용하는 예제. 콜백은 "Hello World" 를 표시한 다음 이벤트 루프를 중지합니다:

import asyncio

def hello_world(loop):
    """A callback to print 'Hello World' and stop the event loop"""
    print('Hello World')
    loop.stop()

loop = asyncio.get_event_loop()

# Schedule a call to hello_world()
loop.call_soon(hello_world, loop)

# Blocking call interrupted by loop.stop()
try:
    loop.run_forever()
finally:
    loop.close()

더 보기

코루틴과 run() 함수로 작성된 유사한 Hello World 예제.

call_later()로 현재 날짜를 표시합니다.

초마다 현재 날짜를 표시하는 콜백의 예입니다. 콜백은 loop.call_later() 메서드를 사용하여 5초 동안 자신을 다시 예약한 다음 이벤트 루프를 중지합니다:

import asyncio
import datetime

def display_date(end_time, loop):
    print(datetime.datetime.now())
    if (loop.time() + 1.0) < end_time:
        loop.call_later(1, display_date, end_time, loop)
    else:
        loop.stop()

loop = asyncio.get_event_loop()

# Schedule the first call to display_date()
end_time = loop.time() + 5.0
loop.call_soon(display_date, end_time, loop)

# Blocking call interrupted by loop.stop()
try:
    loop.run_forever()
finally:
    loop.close()

더 보기

코루틴과 run() 함수로 작성된 유사한 현재 날짜 예제.

파일 기술자에서 읽기 이벤트를 관찰하기

loop.add_reader() 메서드를 사용하여 파일 기술자가 데이터를 수신할 때까지 기다렸다가 이벤트 루프를 닫습니다:

import asyncio
from socket import socketpair

# Create a pair of connected file descriptors
rsock, wsock = socketpair()

loop = asyncio.get_event_loop()

def reader():
    data = rsock.recv(100)
    print("Received:", data.decode())

    # We are done: unregister the file descriptor
    loop.remove_reader(rsock)

    # Stop the event loop
    loop.stop()

# Register the file descriptor for read event
loop.add_reader(rsock, reader)

# Simulate the reception of data from the network
loop.call_soon(wsock.send, 'abc'.encode())

try:
    # Run the event loop
    loop.run_forever()
finally:
    # We are done. Close sockets and the event loop.
    rsock.close()
    wsock.close()
    loop.close()

더 보기

트랜스포트, 프로토콜, loop.create_connection() 메서드를 사용한 유사한 예제.

고수준의 asyncio.open_connection() 함수와 스트림을 사용하는 또 다른 유사한 예제.

SIGINT 및 SIGTERM에 대한 시그널 처리기 설정

(이 signals 예제는 유닉스에서만 작동합니다.)

loop.add_signal_handler() 메서드를 사용하여 SIGINT와 SIGTERM 시그널을 위한 처리기를 등록합니다:

import asyncio
import functools
import os
import signal

def ask_exit(signame, loop):
    print("got signal %s: exit" % signame)
    loop.stop()

async def main():
    loop = asyncio.get_running_loop()

    for signame in {'SIGINT', 'SIGTERM'}:
        loop.add_signal_handler(
            getattr(signal, signame),
            functools.partial(ask_exit, signame, loop))

    await asyncio.sleep(3600)

print("Event loop running for 1 hour, press Ctrl+C to interrupt.")
print(f"pid {os.getpid()}: send SIGINT or SIGTERM to exit.")

asyncio.run(main())

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

네트워킹과 프로세스 간 통신 »

asyncio — 비동기 I/O »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

네트워킹과 프로세스 간 통신 »

asyncio — 비동기 I/O »

|

퓨처

Future 객체는 저수준 콜백 기반 코드와 고수준 async/await 코드 간에 다리를 놓는 데 사용됩니다.

퓨처 함수

asyncio.isfuture(obj)

obj가 다음 중 하나면 True를 반환합니다:

asyncio.Future의 인스턴스,

asyncio.Task의 인스턴스,

_asyncio_future_blocking 어트리뷰트를 가진 퓨처류 객체.

버전 3.5에 추가.

asyncio.ensure_future(obj, *, loop=None)

다음을 반환합니다:

obj가 Future, Task 또는 퓨처류 객체면, obj 인자를 있는 그대로 (isfuture()로 검사합니다.)

a Task object wrapping obj, if obj is a coroutine (iscoroutine() is used for the test); in this case the coroutine will be scheduled by ensure_future().

obj가 어웨이터블이면, obj를 기다릴 Task 객체 (inspect.isawaitable()로 검사합니다.)

obj가 이 중 어느 것도 아니면, TypeError가 발생합니다.

중요

새 태스크를 만드는 데 선호되는 create_task() 함수도 참조하십시오.

버전 3.5.1에서 변경: 함수는 모든 어웨이터블 객체를 받아들입니다.

asyncio.wrap_future(future, *, loop=None)

concurrent.futures.Future 객체를 asyncio.Future 객체로 감쌉니다.

Future 객체

class asyncio.Future(*, loop=None)

Future는 비동기 연산의 최종 결과를 나타냅니다. 스레드 안전하지 않습니다.

Future는 어웨이터블 객체입니다. 코루틴은 결과나 예외가 설정되거나 취소될 때까지 Future 객체를 기다릴 수 있습니다.

일반적으로 퓨처는 저수준 콜백 기반 코드(예를 들어, asyncio 트랜스포트를 사용하여 구현된 프로토콜에서)가 고수준 async/await 코드와 상호 운용되도록 하는 데 사용됩니다.

간단한 규칙은 사용자가 만나는 API에서 Future 객체를 절대 노출하지 않는 것이며, Future 객체를 만드는 권장 방법은 loop.create_future()를 호출하는 것입니다. 이런 식으로 대체 이벤트 루프 구현이 자신의 최적화된 Future 객체 구현을 주입할 수 있습니다.

버전 3.7에서 변경: contextvars 모듈에 대한 지원이 추가되었습니다.

result()

Future의 결과를 반환합니다.

Future가 완료(done)했고 set_result() 메서드로 결과가 설정되었으면, 결괏값이 반환됩니다.

Future가 완료(done)했고 set_exception() 메서드로 예외가 설정되었으면, 이 메서드는 예외를 발생시킵니다.

Future가 취소(cancelled)되었으면, 이 메서드는 CancelledError 예외를 발생시킵니다.

Future의 결과를 아직 사용할 수 없으면, 이 메서드는 InvalidStateError 예외를 발생시킵니다.

set_result(result)

Future를 완료(done)로 표시하고, 그 결과를 설정합니다.

Future가 이미 완료(done)했으면, InvalidStateError 에러를 발생시킵니다.

set_exception(exception)

Future를 완료(done)로 표시하고, 예외를 설정합니다.

Future가 이미 완료(done)했으면, InvalidStateError 에러를 발생시킵니다.

done()

Future가 완료(done)했으면 True를 반환합니다.

Future는 취소(cancelled)되었거나 set_result() 나 set_exception() 호출로 결과나 예외가 설정되면 완료(done)됩니다.

cancelled()

Future가 최소(cancelled)되었으면, True를 반환합니다.

이 메서드는 대개 결과나 예외를 설정하기 전에 Future가 취소(cancelled)되었는지 확인하는 데 사용됩니다:

if not fut.cancelled():
    fut.set_result(42)

add_done_callback(callback, *, context=None)

Future가 완료(done)될 때 실행할 콜백을 추가합니다.

callback는 유일한 인자인 Future 객체로 호출됩니다.

이 메서드가 호출될 때 Future가 이미 완료(done)되었으면, 콜백이 loop.call_soon()으로 예약됩니다.

선택적 키워드 전용 context 인자는 callback이 실행될 사용자 정의 contextvars.Context를 지정할 수 있도록 합니다. context가 제공되지 않으면 현재 컨텍스트가 사용됩니다.

functools.partial()을 사용하여 매개 변수를 callback에 전달할 수 있습니다, 예를 들어:

# Call 'print("Future:", fut)' when "fut" is done.
fut.add_done_callback(
    functools.partial(print, "Future:"))

버전 3.7에서 변경: context 키워드 전용 매개 변수가 추가되었습니다. 자세한 내용은 PEP 567 [https://www.python.org/dev/peps/pep-0567]을 참조하십시오.

remove_done_callback(callback)

콜백 목록에서 callback을 제거합니다.

제거된 콜백 수를 반환합니다. 콜백이 두 번 이상 추가되지 않는 한 일반적으로 1입니다.

cancel()

Future를 취소하고 콜백을 예약합니다.

Future가 이미 완료(done)했거나 취소(cancelled)되었으면, False를 반환합니다. 그렇지 않으면 Future의 상태를 취소(cancelled)로 변경하고, 콜백을 예약한 다음 True를 반환합니다.

exception()

이 Future에 설정된 예외를 반환합니다.

Future가 완료(done)했을 때만 예외(또는 예외가 설정되지 않았으면 None)가 반환됩니다.

Future가 취소(cancelled)되었으면, 이 메서드는 CancelledError 예외를 발생시킵니다.

Future가 아직 완료(done)하지 않았으면, 이 메서드는 InvalidStateError 예외를 발생시킵니다.

get_loop()

Future 객체가 연결된 이벤트 루프를 반환합니다.

버전 3.7에 추가.

이 예제는 Future 객체를 만들고, Future에 결과를 설정하는 비동기 Task를 만들고 예약하며, Future가 결과를 얻을 때까지 기다립니다:

async def set_after(fut, delay, value):
    # Sleep for *delay* seconds.
    await asyncio.sleep(delay)

    # Set *value* as a result of *fut* Future.
    fut.set_result(value)

async def main():
    # Get the current event loop.
    loop = asyncio.get_running_loop()

    # Create a new Future object.
    fut = loop.create_future()

    # Run "set_after()" coroutine in a parallel Task.
    # We are using the low-level "loop.create_task()" API here because
    # we already have a reference to the event loop at hand.
    # Otherwise we could have just used "asyncio.create_task()".
    loop.create_task(
        set_after(fut, 1, '... world'))

    print('hello ...')

    # Wait until *fut* has a result (1 second) and print it.
    print(await fut)

asyncio.run(main())

중요

Future 객체는 concurrent.futures.Future를 흉내 내도록 설계되었습니다. 주요 차이점은 다음과 같습니다:

asyncio 퓨처와는 달리, concurrent.futures.Future 인스턴스는 await 할 수 없습니다.

asyncio.Future.result() 와 asyncio.Future.exception()은 timeout 인자를 받아들이지 않습니다.

asyncio.Future.result() 와 asyncio.Future.exception()는 Future가 완료(done)하지 않았을 때 InvalidStateError 예외를 발생시킵니다.

asyncio.Future.add_done_callback()으로 등록된 콜백은 즉시 호출되지 않습니다. 대신 loop.call_soon()로 예약됩니다.

asyncio Future는 concurrent.futures.wait() 와 concurrent.futures.as_completed() 함수와 호환되지 않습니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

네트워킹과 프로세스 간 통신 »

asyncio — 비동기 I/O »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

네트워킹과 프로세스 간 통신 »

asyncio — 비동기 I/O »

|

트랜스포트와 프로토콜

머리말

트랜스포트와 프로토콜은 loop.create_connection()와 같은 저수준 이벤트 루프 API에서 사용됩니다. 그들은 콜백 기반 프로그래밍 스타일을 사용하고 네트워크 나 IPC 프로토콜(예를 들어 HTTP)의 고성능 구현을 가능하게 합니다.

본질에서 트랜스포트와 프로토콜은 라이브러리와 프레임워크에서만 사용되어야 하며 고수준 asyncio 응용 프로그램에서는 사용되지 않아야 합니다.

이 문서 페이지는 트랜스포트와 프로토콜을 모두 다룹니다.

소개

최상위 수준에서, 트랜스포트는 어떻게(how) 바이트를 전송할지를 다루지만, 프로토콜은 어떤(which) 바이트를 전송할지를 결정합니다 (그리고 어느 정도는 언제(when)도).

같은 것을 다른 식으로 말하면: 트랜스포트는 소켓(또는 유사한 I/O 엔드포인트)의 추상화지만, 프로토콜은 트랜스포트의 관점에서 응용 프로그램의 추상화입니다.

또 다른 시각은 트랜스포트와 프로토콜 인터페이스가 함께 네트워크 I/O와 프로세스 간 I/O를 사용하기 위한 추상 인터페이스를 정의한다는 것입니다.

트랜스포트 객체와 프로토콜 객체 간에는 항상 1:1 관계가 있습니다: 프로토콜은 트랜스포트 메서드를 호출하여 데이터를 보내지만, 트랜스포트는 프로토콜 메서드를 호출하여 받은 데이터를 전달합니다.

대부분의 연결 지향 이벤트 루프 메서드(가령 loop.create_connection())는 Transport 객체로 표현되는 받아들인 연결을 위한 Protocol 객체를 만드는 데 사용되는 protocol_factory 인자를 받아들입니다. 이러한 메서드는 대개 (transport, protocol)의 튜플을 반환합니다.

목차

이 설명서 페이지는 다음 절로 구성됩니다:

트랜스포트 절은 asyncio BaseTransport, ReadTransport, WriteTransport, Transport, DatagramTransport 및 SubprocessTransport 클래스를 설명합니다.

프로토콜 절은 asyncio BaseProtocol, Protocol, BufferedProtocol, DatagramProtocol 및 SubprocessProtocol 클래스를 설명합니다.

예제 절은 트랜스포트, 프로토콜 및 저수준 이벤트 루프 API를 사용하는 방법을 보여줍니다.

트랜스포트

트랜스포트는 다양한 종류의 통신 채널을 추상화하기 위해 asyncio에서 제공하는 클래스입니다.

트랜스포트 객체는 항상 asyncio 이벤트 루프에 의해 인스턴스로 만들어집니다.

asyncio는 TCP, UDP, SSL 및 서브 프로세스 파이프를 위한 트랜스포트를 구현합니다. 트랜스포트에서 사용할 수 있는 메서드는 트랜스포트의 종류에 따라 다릅니다.

트랜스포트 클래스는 스레드 안전하지 않습니다.

트랜스포트 계층 구조

class asyncio.BaseTransport

모든 트랜스포트의 베이스 클래스. 모든 asyncio 트랜스포트가 공유하는 메서드를 포함합니다.

class asyncio.WriteTransport(BaseTransport)

쓰기 전용 연결을 위한 베이스 트랜스포트

WriteTransport 클래스의 인스턴스는 loop.connect_write_pipe() 이벤트 루프 메서드에서 반환되며 loop.subprocess_exec()와 같은 서브 프로세스 관련 메서드에서도 사용됩니다.

class asyncio.ReadTransport(BaseTransport)

읽기 전용 연결을 위한 베이스 트랜스포트

ReadTransport 클래스의 인스턴스는 loop.connect_read_pipe() 이벤트 루프 메서드에서 반환되며 loop.subprocess_exec()와 같은 서브 프로세스 관련 메서드에서도 사용됩니다.

class asyncio.Transport(WriteTransport, ReadTransport)

TCP 연결과 같은 양방향 트랜스포트를 나타내는 인터페이스.

사용자는 트랜스포트를 직접 인스턴스로 만들지 않습니다; 유틸리티 함수를 호출하고, 프로토콜 팩토리와 트랜스포트와 프로토콜을 만드는 데 필요한 기타 정보를 전달합니다.

Transport 클래스의 인스턴스는 loop.create_connection(), loop.create_unix_connection(), loop.create_server(), loop.sendfile() 등과 같은 이벤트 루프 메서드에서 반환되거나 사용됩니다.

class asyncio.DatagramTransport(BaseTransport)

데이터 그램 (UDP) 연결을 위한 트랜스포트.

DatagramTransport 클래스의 인스턴스는 loop.create_datagram_endpoint() 이벤트 루프 메서드에서 반환됩니다.

class asyncio.SubprocessTransport(BaseTransport)

부모와 그 자식 OS 프로세스 간의 연결을 나타내는 추상화.

SubprocessTransport 클래스의 인스턴스는 이벤트 루프 메서드 loop.subprocess_shell()과 loop.subprocess_exec()에서 반환됩니다.

베이스 트랜스포트

BaseTransport.close()

트랜스포트를 닫습니다.

트랜스포트에 송신 데이터용 버퍼가 있으면, 버퍼 된 데이터는 비동기적으로 플러시 됩니다. 더는 데이터가 수신되지 않습니다. 버퍼 된 모든 데이터가 플러시 된 후, 프로토콜의 protocol.connection_lost() 메서드가 None을 인자로 사용하여 호출됩니다.

BaseTransport.is_closing()

트랜스포트가 닫히는 중이거나 닫혔으면 True를 반환합니다.

BaseTransport.get_extra_info(name, default=None)

트랜스포트나 그것이 사용하는 하부 자원에 대한 정보를 반환합니다.

name은 얻고자 하는 트랜스포트 특정 정보의 조각을 나타내는 문자열입니다.

default는 정보가 없거나 트랜스포트가 제삼자 이벤트 루프 구현이나 현재 플랫폼에서 조회를 지원하지 않을 때 반환 할 값입니다.

예를 들어, 다음 코드는 트랜스포트의 하부 소켓 객체를 가져오려고 시도합니다:

sock = transport.get_extra_info('socket')
if sock is not None:
    print(sock.getsockopt(...))

일부 트랜스포트에서 조회할 수 있는 정보의 범주:

소켓:

'peername': 소켓이 연결된 원격 주소, socket.socket.getpeername()의 결과 (에러 시 None)

'socket': socket.socket 인스턴스

'sockname': 소켓 자체 주소, socket.socket.getsockname()의 결과

SSL 소켓:

'compression': 문자열로 표현된 사용된 압축 알고리즘, 또는 연결이 압축되지 않았으면 None; ssl.SSLSocket.compression()의 결과

'cipher': 사용되는 암호 체계의 이름, 이의 사용을 정의하는 SSL 프로토콜의 버전 및 사용되는 비밀 비트의 수를 포함하는 3-튜플; ssl.SSLSocket.cipher()의 결과

'peercert': 피어 인증서; ssl.SSLSocket.getpeercert()의 결과

'sslcontext': ssl.SSLContext 인스턴스

'ssl_object': ssl.SSLObject 나 ssl.SSLSocket 인스턴스

파이프:

'pipe': 파이프 객체

서브 프로세스:

'subprocess': subprocess.Popen 인스턴스

BaseTransport.set_protocol(protocol)

새 프로토콜을 설정합니다.

프로토콜의 교환은 두 프로토콜이 교환을 지원한다고 문서화 되었을 때만 수행되어야 합니다.

BaseTransport.get_protocol()

현재 프로토콜을 반환합니다.

읽기 전용 트랜스포트

ReadTransport.is_reading()

트랜스 포트가 새로운 데이터를 받고 있으면 True를 반환합니다.

버전 3.7에 추가.

ReadTransport.pause_reading()

트랜스포트의 수신 끝을 일시 중지합니다. resume_reading()이 호출 될 때까지 프로토콜의 protocol.data_received() 메서드에 데이터가 전달되지 않습니다.

버전 3.7에서 변경: 이 메서드는 멱등적(idempotent)입니다. 즉, 트랜스포트가 이미 일시 중지되거나 닫혔을 때도 호출할 수 있습니다.

ReadTransport.resume_reading()

수신 끝을 재개합니다. 읽을 수 있는 데이터가 있다면 프로토콜의 protocol.data_received() 메서드가 다시 한번 호출됩니다.

버전 3.7에서 변경: 이 메서드는 멱등적(idempotent)입니다. 즉, 트랜스포트가 이미 읽고 있을 때도 호출할 수 있습니다.

쓰기 전용 트랜스포트

WriteTransport.abort()

계류 중인 작업이 완료될 때까지 기다리지 않고, 즉시 트랜스포트를 닫습니다. 버퍼 된 데이터는 손실됩니다. 더는 데이터가 수신되지 않습니다. 프로토콜의 protocol.connection_lost() 메서드는 결국 None을 인자로 사용하여 호출됩니다.

WriteTransport.can_write_eof()

트랜스포트가 write_eof()를 지원하면 True를 반환하고, 그렇지 않으면 False를 반환합니다.

WriteTransport.get_write_buffer_size()

트랜스포트가 사용하는 출력 버퍼의 현재 크기를 반환합니다.

WriteTransport.get_write_buffer_limits()

쓰기 흐름 제어를 위한 high 와 low 수위(watermark)를 가져옵니다. 튜플 (low, high)를 반환합니다. 여기서 low 와 high는 양의 바이트 수입니다.

제한을 설정하려면 set_write_buffer_limits()를 사용하십시오.

버전 3.4.2에 추가.

WriteTransport.set_write_buffer_limits(high=None, low=None)

쓰기 흐름 제어를 위한 high 와 low 수위(watermark)를 설정합니다.

이 두 값(바이트 수로 측정)은 프로토콜의 protocol.pause_writing() 과 protocol.resume_writing() 메서드가 언제 호출될지를 제어합니다. 지정하면, low 수위는 high 수위보다 작거나 같아야 합니다. high 와 low는 음수가 될 수 없습니다.

버퍼 크기가 high 값보다 크거나 같아질 때 pause_writing()가 호출됩니다. 쓰기가 일시 중지되면, 버퍼 크기가 low 값보다 작거나 같아질 때 resume_writing()이 호출됩니다.

기본값은 구현에 따라 다릅니다. high 수위만 주어지면, low 수위는 high 수위보다 작거나 같은 구현 특정 기본값이 사용됩니다. high를 0으로 설정하면, low도 0으로 설정되고, 버퍼가 비어있지 않게 될 때마다 pause_writing()가 호출되도록 합니다. low를 0으로 설정하면 버퍼가 빌 때만 resume_writing()이 호출됩니다. 두 제한 중 하나에 0을 사용하는 것은 I/O와 계산을 동시에 수행할 기회를 줄이기 때문에 일반적으로 최선이 아닙니다.

제한을 가져오려면 get_write_buffer_limits()를 사용하십시오.

WriteTransport.write(data)

어떤 data 바이트열을 트랜스포트에 기록합니다.

이 메서드는 블록하지 않습니다; 데이터를 버퍼하고 비동기적으로 전송되도록 배치합니다.

WriteTransport.writelines(list_of_data)

트랜스포트에 데이터 바이트열 리스트(또는 임의의 이터러블)를 기록합니다. 이것은 이터러블이 산출하는 각 요소에 대해 write()를 호출하는 것과 기능 면에서 동등하지만, 더 효율적으로 구현될 수 있습니다.

WriteTransport.write_eof()

버퍼 된 모든 데이터를 플러시 한 후 트랜스포트의 쓰기 끝을 닫습니다. 데이터가 여전히 수신될 수 있습니다.

이 메서드는 트랜스포트(예를 들어 SSL)가 반만 닫힌 연결을 지원하지 않으면 NotImplementedError를 발생시킬 수 있습니다.

데이터 그램 트랜스포트

DatagramTransport.sendto(data, addr=None)

addr(트랜스포트 종속적인 대상 주소)에 의해 주어진 원격 피어로 data 바이트열을 보냅니다. addr가 None이면, 트랜스포트를 만들 때 지정된 대상 주소로 data가 전송됩니다.

이 메서드는 블록하지 않습니다; 데이터를 버퍼하고 비동기적으로 전송되도록 배치합니다.

DatagramTransport.abort()

계류 중인 작업이 완료될 때까지 기다리지 않고, 즉시 트랜스포트를 닫습니다. 버퍼 된 데이터는 손실됩니다. 더는 데이터가 수신되지 않습니다. 프로토콜의 protocol.connection_lost() 메서드는 결국 None을 인자로 사용하여 호출됩니다.

서브 프로세스 트랜스포트

SubprocessTransport.get_pid()

서브 프로세스 ID를 정수로 반환합니다.

SubprocessTransport.get_pipe_transport(fd)

정수 파일 기술자 fd에 대응하는 통신 파이프의 트랜스포트를 돌려줍니다:

0: 표준 입력(stdin)의 읽을 수 있는 스트리밍 트랜스포트, 또는 서브 프로세스가 stdin=PIPE로 만들어지지 않았으면 None

1: 표준 출력(stdout)의 쓸 수 있는 스트리밍 트랜스포트, 또는 서브 프로세스가 stdout=PIPE로 만들어지지 않았으면 None

2: 표준 오류(stderr)의 쓸 수 있는 스트리밍 트랜스포트, 또는 서브 프로세스가 stderr=PIPE로 만들어지지 않았으면 None

다른 fd: None

SubprocessTransport.get_returncode()

서브 프로세스 반환 값을 정수로, 혹은 반환되지 않았으면 None을 반환합니다. subprocess.Popen.returncode 어트리뷰트와 유사합니다.

SubprocessTransport.kill()

서브 프로세스를 죽입니다.

POSIX 시스템에서, 이 함수는 SIGKILL을 서브 프로세스로 보냅니다. 윈도우에서, 이 메서드는 terminate()의 별칭입니다.

subprocess.Popen.kill()도 참조하십시오.

SubprocessTransport.send_signal(signal)

subprocess.Popen.send_signal()와 마찬가지로 signal 번호를 서브 프로세스로 보냅니다.

SubprocessTransport.terminate()

서브 프로세스를 중지합니다.

POSIX 시스템에서, 이 메서드는 SIGTERM을 서브 프로세스로 보냅니다. 윈도에서, 서브 프로세스를 중지하기 위해 윈도우 API 함수 TerminateProcess() 가 호출됩니다.

subprocess.Popen.terminate()도 참조하십시오.

SubprocessTransport.close()

kill() 메서드를 호출하여 서브 프로세스를 죽입니다.

서브 프로세스가 아직 반환하지 않았으면, stdin, stdout 및 stderr 파이프의 트랜스포트를 닫습니다.

프로토콜

asyncio는 네트워크 프로토콜을 구현하는 데 사용해야 하는 추상 베이스 클래스 집합을 제공합니다. 이러한 클래스는 트랜스포트와 함께 사용해야 합니다.

추상 베이스 프로토콜 클래스의 서브 클래스는 일부 또는 모든 메서드를 구현할 수 있습니다. 이 모든 메서드는 콜백입니다: 이것들은 특정 이벤트에서 트랜스포트에 의해 호출됩니다, 예를 들어 어떤 데이터가 수신될 때. 베이스 프로토콜 메서드는 해당 트랜스포트에 의해 호출되어야 합니다.

베이스 프로토콜

class asyncio.BaseProtocol

모든 프로토콜이 공유하는 메서드를 가진 베이스 프로토콜.

class asyncio.Protocol(BaseProtocol)

스트리밍 프로토콜(TCP, 유닉스 소켓 등)을 구현하기 위한 베이스 클래스.

class asyncio.BufferedProtocol(BaseProtocol)

수신 버퍼의 수동 제어로 스트리밍 프로토콜을 구현하기 위한 베이스 클래스.

class asyncio.DatagramProtocol(BaseProtocol)

데이터 그램 (UDP) 프로토콜을 구현하기 위한 베이스 클래스.

class asyncio.SubprocessProtocol(BaseProtocol)

자식 프로세스와 통신하는 (단방향 파이프) 프로토콜을 구현하기 위한 베이스 클래스.

베이스 프로토콜

모든 asyncio 프로토콜은 베이스 프로토콜 콜백을 구현할 수 있습니다.

연결 콜백

연결 콜백은 모든 프로토콜에서 성공적으로 연결될 때마다 정확히 한 번 호출됩니다. 다른 모든 프로토콜 콜백은 이 두 메서드 사이에서만 호출될 수 있습니다.

BaseProtocol.connection_made(transport)

연결이 이루어질 때 호출됩니다.

transport 인자는 연결을 나타내는 트랜스포트입니다. 트랜스포트에 대한 참조를 저장하는 것은 프로토콜의 책임입니다.

BaseProtocol.connection_lost(exc)

연결이 끊어지거나 닫힐 때 호출됩니다.

인자는 예외 객체나 None입니다. 후자는 정상적인 EOF가 수신되었거나, 연결의 이쪽에서 연결이 중단(abort)되거나 닫혔다는 것을 의미합니다.

흐름 제어 콜백

흐름 제어 콜백은 프로토콜에 의해 수행되는 쓰기를 일시 중지하거나 다시 시작하도록 트랜스포트에 의해 호출될 수 있습니다.

자세한 내용은 set_write_buffer_limits() 메서드 설명서를 참조하십시오.

BaseProtocol.pause_writing()

트랜스포트 버퍼가 높은 수위를 넘을 때 호출됩니다.

BaseProtocol.resume_writing()

트랜스포트 버퍼가 낮은 수위 아래로 내려갈 때 호출됩니다.

버퍼 크기가 높은 수위와 같으면, pause_writing()이 호출되지 않습니다: 버퍼 크기는 엄격하게 초과해야 합니다.

반대로, resume_writing()은 버퍼 크기가 낮은 수위와 같거나 낮을 때 호출됩니다. 이러한 종료 조건은 수위가 0일 때 예상대로 진행되게 하려면 중요합니다.

스트리밍 프로토콜

loop.create_server(), loop.create_unix_server(), loop.create_connection(), loop.create_unix_connection(), loop.connect_accepted_socket(), loop.connect_read_pipe() 및 loop.connect_write_pipe()와 같은 이벤트 메서드는 스트리밍 프로토콜을 반환하는 팩토리를 받아들입니다.

Protocol.data_received(data)

어떤 데이터가 수신될 때 호출됩니다. data는 수신 데이터가 들어있는 비어 있지 않은 바이트열 객체입니다.

데이터가 버퍼 되고, 조각으로 나뉘고, 재조립되는지는 트랜스포트에 달려있습니다. 일반적으로, 특정 의미에 의존해서는 안 되며, 구문 분석을 일반적이고 유연하게 만들어야 합니다. 그러나, 데이터는 항상 올바른 순서로 수신됩니다.

이 메서드는 연결이 열려있는 동안 임의의 횟수만큼 호출될 수 있습니다.

그러나, protocol.eof_received()는 최대한 한 번만 호출됩니다. 일단 eof_received()가 호출되면, data_received()는 더는 호출되지 않습니다.

Protocol.eof_received()

다른 쪽 끝이 더는 데이터를 보내지 않을 것이라는 신호를 보낼 때 호출됩니다 (예를 들어, 다른 쪽 끝도 asyncio를 사용하면, transport.write_eof()를 호출하여).

이 메서드는 거짓 값(None 포함)을 반환할 수 있으며, 이때 트랜스포트는 스스로 닫힙니다. 반대로, 이 메서드가 참값을 반환하면, 사용된 프로토콜이 트랜스포트를 닫을지를 결정합니다. 기본 구현이 None을 반환하기 때문에, 묵시적으로 연결을 닫습니다.

SSL을 포함한 일부 트랜스포트는, 반만 닫힌 연결을 지원하지 않습니다. 이때, 이 메서드에서 참을 반환하면 연결이 닫힙니다.

상태 기계:

start -> connection_made
    [-> data_received]*
    [-> eof_received]?
-> connection_lost -> end

버퍼 된 스트리밍 프로토콜

버전 3.7에 추가: 중요: 이것은 파이썬 3.7에서 잠정적으로 asyncio에 추가되었습니다! 이것은 실험용 API로서, 파이썬 3.8에서 변경되거나 완전히 제거될 수 있습니다.

버퍼 된 프로토콜은 스트리밍 프로토콜을 지원하는 모든 이벤트 루프 메서드와 함께 사용할 수 있습니다.

BufferedProtocol 구현은 수신 버퍼의 명시적 수동 할당과 제어를 허용합니다. 이벤트 루프는 프로토콜에서 제공하는 버퍼를 사용하여 불필요한 데이터 복사를 피할 수 있습니다. 이로 인해 대량의 데이터를 수신하는 프로토콜의 성능이 크게 향상될 수 있습니다. 정교한 프로토콜 구현은 버퍼 할당 수를 크게 줄일 수 있습니다.

다음 콜백은 BufferedProtocol 인스턴스에 호출됩니다.:

BufferedProtocol.get_buffer(sizehint)

새로운 수신 버퍼를 할당하기 위해서 호출됩니다.

sizehint는 반환되는 버퍼에 대해 권장되는 최소 크기입니다. sizehint가 제안하는 것보다 더 작거나 큰 버퍼를 반환하는 것이 허용됩니다. -1로 설정하면 버퍼 크기는 임의적일 수 있습니다. 크기가 0인 버퍼를 반환하는 것은 에러입니다.

get_buffer()는 버퍼 프로토콜을 구현하는 객체를 반환해야 합니다.

BufferedProtocol.buffer_updated(nbytes)

수신된 데이터로 버퍼가 갱신될 때 호출됩니다.

nbytes는 버퍼에 기록된 총 바이트 수입니다.

BufferedProtocol.eof_received()

protocol.eof_received() 메서드의 설명서를 참조하십시오.

get_buffer()는 연결 중에 임의의 횟수만큼 호출될 수 있습니다. 그러나, protocol.eof_received()는 최대한 한 번만 호출되며, 호출되면 get_buffer()와 buffer_updated()는 그 이후로 호출되지 않습니다.

상태 기계:

start -> connection_made
    [-> get_buffer
        [-> buffer_updated]?
    ]*
    [-> eof_received]?
-> connection_lost -> end

데이터 그램 프로토콜

데이터 그램 프로토콜 인스턴스는 loop.create_datagram_endpoint() 메서드에 전달된 프로토콜 팩토리에 의해 만들어져야 합니다.

DatagramProtocol.datagram_received(data, addr)

데이터 그램이 수신될 때 호출됩니다. data는 수신 데이터를 포함하는 바이트열 객체입니다. addr는 데이터를 보내는 피어의 주소입니다; 정확한 형식은 트랜스포트에 따라 다릅니다.

DatagramProtocol.error_received(exc)

이전의 송신이나 수신 연산이 OSError를 일으킬 때 호출됩니다. exc는 OSError 인스턴스입니다.

이 메서드는 드문 조건에서 호출됩니다, 트랜스포트(예를 들어 UDP)가 데이터 그램을 수신자에게 전달할 수 없음을 감지했을 때입니다. 하지만 대부분 전달할 수 없는 데이터 그램은 조용히 삭제됩니다.

참고

BSD 시스템(macOS, FreeBSD 등)에서는, 너무 많은 패킷을 쓰는 것으로 인한 전송 실패를 감지하는 신뢰성 있는 방법이 없으므로 데이터 그램 프로토콜에 대한 흐름 제어가 지원되지 않습니다.

소켓은 항상 ‘ready’로 나타나고 여분의 패킷은 삭제됩니다. errno가 errno.ENOBUFS로 설정된 OSError가 발생할 수도 그렇지 않을 수도 있습니다; 발생하면, DatagramProtocol.error_received()에게 보고되지만 그렇지 않으면 무시됩니다.

서브 프로세스 프로토콜

서브 프로세스 프로토콜 인스턴스는 loop.subprocess_exec() 와 loop.subprocess_shell() 메서드에 전달된 프로토콜 팩토리에 의해 만들어져야 합니다.

SubprocessProtocol.pipe_data_received(fd, data)

자식 프로세스가 stdout 이나 stderr 파이프에 데이터를 쓸 때 호출됩니다.

fd는 파이프의 정수 파일 기술자입니다.

data는 수신 된 데이터를 포함하는 비어 있지 않은 바이트열 객체입니다.

SubprocessProtocol.pipe_connection_lost(fd, exc)

자식 프로세스와 통신하는 파이프 중 하나가 닫히면 호출됩니다.

fd는 닫힌 정수 파일 기술자입니다.

SubprocessProtocol.process_exited()

자식 프로세스가 종료할 때 호출됩니다.

예제

TCP 메아리 서버

loop.create_server() 메서드를 사용하여 TCP 메아리 서버를 만들고, 받은 데이터를 다시 보내고, 연결을 닫습니다:

import asyncio

class EchoServerProtocol(asyncio.Protocol):
    def connection_made(self, transport):
        peername = transport.get_extra_info('peername')
        print('Connection from {}'.format(peername))
        self.transport = transport

    def data_received(self, data):
        message = data.decode()
        print('Data received: {!r}'.format(message))

        print('Send: {!r}'.format(message))
        self.transport.write(data)

        print('Close the client socket')
        self.transport.close()

async def main():
    # Get a reference to the event loop as we plan to use
    # low-level APIs.
    loop = asyncio.get_running_loop()

    server = await loop.create_server(
        lambda: EchoServerProtocol(),
        '127.0.0.1', 8888)

    async with server:
        await server.serve_forever()

asyncio.run(main())

더 보기

스트림을 사용하는 TCP 메아리 서버 예제는 고수준 asyncio.start_server() 함수를 사용합니다.

TCP 메아리 클라이언트

loop.create_connection() 메서드를 사용하는 TCP 메아리 클라이언트, 데이터를 보내고 연결이 닫힐 때까지 기다립니다:

import asyncio

class EchoClientProtocol(asyncio.Protocol):
    def __init__(self, message, on_con_lost):
        self.message = message
        self.on_con_lost = on_con_lost

    def connection_made(self, transport):
        transport.write(self.message.encode())
        print('Data sent: {!r}'.format(self.message))

    def data_received(self, data):
        print('Data received: {!r}'.format(data.decode()))

    def connection_lost(self, exc):
        print('The server closed the connection')
        self.on_con_lost.set_result(True)

async def main():
    # Get a reference to the event loop as we plan to use
    # low-level APIs.
    loop = asyncio.get_running_loop()

    on_con_lost = loop.create_future()
    message = 'Hello World!'

    transport, protocol = await loop.create_connection(
        lambda: EchoClientProtocol(message, on_con_lost),
        '127.0.0.1', 8888)

    # Wait until the protocol signals that the connection
    # is lost and close the transport.
    try:
        await on_con_lost
    finally:
        transport.close()

asyncio.run(main())

더 보기

스트림을 사용하는 TCP 메아리 클라이언트 예제는 고수준 asyncio.open_connection() 함수를 사용합니다.

UDP 메아리 서버

loop.create_datagram_endpoint() 메서드를 사용하는 UDP 메아리 서버, 수신된 데이터를 다시 보냅니다:

import asyncio

class EchoServerProtocol:
    def connection_made(self, transport):
        self.transport = transport

    def datagram_received(self, data, addr):
        message = data.decode()
        print('Received %r from %s' % (message, addr))
        print('Send %r to %s' % (message, addr))
        self.transport.sendto(data, addr)

async def main():
    print("Starting UDP server")

    # Get a reference to the event loop as we plan to use
    # low-level APIs.
    loop = asyncio.get_running_loop()

    # One protocol instance will be created to serve all
    # client requests.
    transport, protocol = await loop.create_datagram_endpoint(
        lambda: EchoServerProtocol(),
        local_addr=('127.0.0.1', 9999))

    try:
        await asyncio.sleep(3600)  # Serve for 1 hour.
    finally:
        transport.close()

asyncio.run(main())

UDP 메아리 클라이언트

loop.create_datagram_endpoint() 메서드를 사용하는 UDP 메아리 클라이언트, 데이터를 보내고 응답을 받으면 트랜스포트를 닫습니다:

import asyncio

class EchoClientProtocol:
    def __init__(self, message, on_con_lost):
        self.message = message
        self.on_con_lost = on_con_lost
        self.transport = None

    def connection_made(self, transport):
        self.transport = transport
        print('Send:', self.message)
        self.transport.sendto(self.message.encode())

    def datagram_received(self, data, addr):
        print("Received:", data.decode())

        print("Close the socket")
        self.transport.close()

    def error_received(self, exc):
        print('Error received:', exc)

    def connection_lost(self, exc):
        print("Connection closed")
        self.on_con_lost.set_result(True)

async def main():
    # Get a reference to the event loop as we plan to use
    # low-level APIs.
    loop = asyncio.get_running_loop()

    on_con_lost = loop.create_future()
    message = "Hello World!"

    transport, protocol = await loop.create_datagram_endpoint(
        lambda: EchoClientProtocol(message, on_con_lost),
        remote_addr=('127.0.0.1', 9999))

    try:
        await on_con_lost
    finally:
        transport.close()

asyncio.run(main())

기존 소켓 연결하기

프로토콜과 함께 loop.create_connection() 메서드를 사용하여 소켓이 데이터를 수신할 때까지 기다립니다:

import asyncio
import socket

class MyProtocol(asyncio.Protocol):

    def __init__(self, on_con_lost):
        self.transport = None
        self.on_con_lost = on_con_lost

    def connection_made(self, transport):
        self.transport = transport

    def data_received(self, data):
        print("Received:", data.decode())

        # We are done: close the transport;
        # connection_lost() will be called automatically.
        self.transport.close()

    def connection_lost(self, exc):
        # The socket has been closed
        self.on_con_lost.set_result(True)

async def main():
    # Get a reference to the event loop as we plan to use
    # low-level APIs.
    loop = asyncio.get_running_loop()
    on_con_lost = loop.create_future()

    # Create a pair of connected sockets
    rsock, wsock = socket.socketpair()

    # Register the socket to wait for data.
    transport, protocol = await loop.create_connection(
        lambda: MyProtocol(on_con_lost), sock=rsock)

    # Simulate the reception of data from the network.
    loop.call_soon(wsock.send, 'abc'.encode())

    try:
        await protocol.on_con_lost
    finally:
        transport.close()
        wsock.close()

asyncio.run(main())

더 보기

파일 기술자에서 읽기 이벤트를 관찰하기 예제는 저수준의 loop.add_reader() 메서드를 사용하여 FD를 등록합니다.

스트림을 사용하여 데이터를 기다리는 열린 소켓 등록 예제는 코루틴에서 open_connection() 함수에 의해 생성된 고수준 스트림을 사용합니다.

loop.subprocess_exec() 와 SubprocessProtocol

서브 프로세스의 출력을 가져오고 서브 프로세스가 끝날 때까지 대기하는 데 사용되는 서브 프로세스 프로토콜의 예.

서브 프로세스는 loop.subprocess_exec() 메서드에 의해 만들어집니다:

import asyncio
import sys

class DateProtocol(asyncio.SubprocessProtocol):
    def __init__(self, exit_future):
        self.exit_future = exit_future
        self.output = bytearray()

    def pipe_data_received(self, fd, data):
        self.output.extend(data)

    def process_exited(self):
        self.exit_future.set_result(True)

async def get_date():
    # Get a reference to the event loop as we plan to use
    # low-level APIs.
    loop = asyncio.get_running_loop()

    code = 'import datetime; print(datetime.datetime.now())'
    exit_future = asyncio.Future(loop=loop)

    # Create the subprocess controlled by DateProtocol;
    # redirect the standard output into a pipe.
    transport, protocol = await loop.subprocess_exec(
        lambda: DateProtocol(exit_future),
        sys.executable, '-c', code,
        stdin=None, stderr=None)

    # Wait for the subprocess exit using the process_exited()
    # method of the protocol.
    await exit_future

    # Close the stdout pipe.
    transport.close()

    # Read the output which was collected by the
    # pipe_data_received() method of the protocol.
    data = bytes(protocol.output)
    return data.decode('ascii').rstrip()

if sys.platform == "win32":
    asyncio.set_event_loop_policy(
        asyncio.WindowsProactorEventLoopPolicy())

date = asyncio.run(get_date())
print(f"Current date: {date}")

고수준 API를 사용하여 작성된 같은 예제도 참조하십시오.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

네트워킹과 프로세스 간 통신 »

asyncio — 비동기 I/O »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

네트워킹과 프로세스 간 통신 »

asyncio — 비동기 I/O »

|

정책

이벤트 루프 정책은 이벤트 루프의 관리를 제어하는 프로세스별 전역 객체입니다. 각 이벤트 루프는 기본 정책이 있는데, 정책 API를 사용하여 변경하고 사용자 정의할 수 있습니다.

정책은 컨텍스트의 개념을 정의하고 컨텍스트마다 별도의 이벤트 루프를 관리합니다. 기본 정책은 컨텍스트를 현재 스레드로 정의합니다.

사용자 정의 이벤트 루프 정책을 사용하여, get_event_loop(), set_event_loop() 및 new_event_loop() 함수의 동작을 사용자 정의할 수 있습니다.

정책 객체는 AbstractEventLoopPolicy 추상 베이스 클래스에 정의된 API를 구현해야 합니다.

정책을 얻고 설정하기

다음 함수는 현재 프로세스의 정책을 가져오고 설정하는 데 사용할 수 있습니다:

asyncio.get_event_loop_policy()

현재의 프로세스 전반의 정책을 돌려줍니다.

asyncio.set_event_loop_policy(policy)

현재 프로세스 전반의 정책을 policy로 설정합니다.

policy를 None으로 설정하면, 기본 정책이 복원됩니다.

정책 객체

추상 이벤트 루프 정책 베이스 클래스는 다음과 같이 정의됩니다:

class asyncio.AbstractEventLoopPolicy

asyncio 정책의 추상 베이스 클래스.

get_event_loop()

현재 컨텍스트의 이벤트 루프를 가져옵니다.

AbstractEventLoop 인터페이스를 구현하는 이벤트 루프 객체를 반환합니다.

이 메서드는 절대 None을 반환해서는 안 됩니다.

버전 3.6에서 변경.

set_event_loop(loop)

현재 컨텍스트에 대한 이벤트 루프를 loop로 설정합니다.

new_event_loop()

새 이벤트 루프 객체를 만들고 반환합니다.

이 메서드는 절대 None을 반환해서는 안 됩니다.

get_child_watcher()

자식 프로세스 감시자 객체를 얻습니다.

AbstractChildWatcher 인터페이스를 구현하고 있는 감시자 객체를 돌려줍니다.

이 함수는 유닉스 전용입니다.

set_child_watcher(watcher)

현재의 자식 프로세스 감시자를 watcher로 설정합니다.

이 함수는 유닉스 전용입니다.

asyncio에는 다음과 같은 내장 정책이 제공됩니다:

class asyncio.DefaultEventLoopPolicy

기본 asyncio 정책. 유닉스와 윈도우 플랫폼 모두에서 SelectorEventLoop를 사용합니다.

수동으로 기본 정책을 설치할 필요는 없습니다. asyncio는 기본 정책을 자동으로 사용하도록 구성됩니다.

class asyncio.WindowsProactorEventLoopPolicy

ProactorEventLoop 이벤트 루프 구현을 사용하는 대안 이벤트 루프 정책.

가용성: 윈도우.

프로세스 감시자

프로세스 감시자는 이벤트 루프가 유닉스에서 자식 프로세스를 관찰하는 방법을 사용자 정의할 수 있도록 합니다. 특히, 이벤트 루프는 자식 프로세스가 언제 종료했는지 알 필요가 있습니다.

asyncio에서, 자식 프로세스는 create_subprocess_exec() 와 loop.subprocess_exec() 함수로 만들어집니다.

asyncio는 자식 관찰자가 구현해야 하는 AbstractChildWatcher 추상 베이스 클래스를 정의하며, SafeChildWatcher(기본적으로 사용하도록 구성됩니다)와 FastChildWatcher의 두 가지 구현이 있습니다.

서브 프로세스와 스레드 절도 참조하십시오.

다음 두 함수를 사용하여 asyncio 이벤트 루프에서 사용되는 자식 프로세스 감시자 구현을 사용자 정의할 수 있습니다:

asyncio.get_child_watcher()

현재 정책에 대한 현재 자식 감시자를 반환합니다.

asyncio.set_child_watcher(watcher)

현재 정책에 대한 현재 자식 관찰자를 watcher로 설정합니다. watcher는 AbstractChildWatcher 베이스 클래스에 정의된 메서드를 구현해야 합니다.

참고

제삼자 이벤트 루프 구현은 사용자 정의 자식 관찰자를 지원하지 않을 수 있습니다. 이러한 이벤트 루프에서는, set_child_watcher() 사용은 금지되거나 효과가 없습니다.

class asyncio.AbstractChildWatcher

add_child_handler(pid, callback, *args)

새로운 자식 처리기를 등록합니다.

PID가 pid 인 프로세스가 종료할 때 callback(pid, returncode, *args)가 호출되도록 배치합니다. 같은 프로세스에 대해 다른 콜백을 지정하면 이전 처리기가 교체됩니다.

callback 콜러블은 스레드 안전해야 합니다.

remove_child_handler(pid)

PID가 pid 인 프로세스의 처리기를 제거합니다.

이 함수는 처리기가 성공적으로 제거되면 True를, 제거할 것이 없으면 False를 반환합니다.

attach_loop(loop)

감시자를 이벤트 루프에 연결합니다.

감시자가 이전에 이벤트 루프에 연결되었으면, 새 루프에 연결하기 전에 먼저 제거됩니다.

참고: loop는 None 일 수 있습니다.

close()

감시자를 닫습니다.

이 메서드는 하부 자원을 정리하기 위해 호출해야 합니다.

class asyncio.SafeChildWatcher

이 구현은 SIGCHLD 시그널에 대해 명시적으로 모든 프로세스를 폴링하여 프로세스를 스포닝하는 다른 코드를 방해하지 않습니다.

이것은 안전한 해법이지만 많은 수의 프로세스를 처리할 때 상당한 오버헤드가 있습니다 (SIGCHLD가 수신될 때마다 O(n)).

asyncio는 기본적으로 이 안전한 구현을 사용합니다.

class asyncio.FastChildWatcher

이 구현은 os.waitpid(-1)를 직접 호출하여 종료된 모든 프로세스를 거둡니다. 프로세스를 스포닝하는 다른 코드를 망가뜨리고 그들의 종료를 기다릴 수 있습니다.

많은 수의 자식을 처리할 때 눈에 띄는 오버헤드가 없습니다 (자식이 종료될 때마다 O(1)).

사용자 정의 정책

새로운 이벤트 루프 정책을 구현하려면, DefaultEventLoopPolicy의 서브 클래스를 만들고 사용자 정의 동작이 필요한 메서드를 재정의하는 것이 좋습니다, 예를 들어:

class MyEventLoopPolicy(asyncio.DefaultEventLoopPolicy):

    def get_event_loop(self):
        """Get the event loop.

        This may be None or an instance of EventLoop.
        """
        loop = super().get_event_loop()
        # Do something with loop ...
        return loop

asyncio.set_event_loop_policy(MyEventLoopPolicy())

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

네트워킹과 프로세스 간 통신 »

asyncio — 비동기 I/O »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

네트워킹과 프로세스 간 통신 »

asyncio — 비동기 I/O »

|

플랫폼 지원

asyncio 모듈은 이식성이 있도록 설계되었지만, 플랫폼의 하부 아키텍처와 기능으로 인해 일부 플랫폼에는 미묘한 차이점과 제약이 있습니다.

모든 플랫폼

loop.add_reader()와 loop.add_writer()는 파일 I/O를 감시하는데 사용할 수 없습니다.

윈도우

윈도우의 모든 이벤트 루프는 다음 메서드를 지원하지 않습니다:

loop.create_unix_connection() 와 loop.create_unix_server()는 지원되지 않습니다. socket.AF_UNIX 소켓 패밀리는 유닉스에만 적용됩니다.

loop.add_signal_handler()와 loop.remove_signal_handler()는 지원되지 않습니다.

SelectorEventLoop에는 다음과 같은 제약이 있습니다:

SelectSelector는 소켓 이벤트를 기다리는 데 사용됩니다: 소켓을 지원하며 512개의 소켓으로 제한됩니다.

loop.add_reader()와 loop.add_writer()는 소켓 핸들만 받아들입니다 (예를 들어, 파이프 파일 기술자는 지원되지 않습니다).

파이프는 지원되지 않으므로, loop.connect_read_pipe()와 loop.connect_write_pipe() 메서드는 구현되지 않습니다.

서브 프로세스는 지원되지 않습니다, 즉, loop.subprocess_exec() 와 loop.subprocess_shell() 메서드가 구현되지 않습니다.

ProactorEventLoop에는 다음과 같은 제약이 있습니다:

loop.create_datagram_endpoint() 메서드는 지원되지 않습니다.

loop.add_reader()와 loop.add_writer() 메서드는 지원되지 않습니다.

윈도우에서 단조 시계의 해상도는 대개 15.6 msec 근처입니다. 최상의 해상도는 0.5 msec입니다. 해상도는 하드웨어(HPET [https://en.wikipedia.org/wiki/High_Precision_Event_Timer]이 사용 가능한지)와 윈도우 구성에 따라 다릅니다.

윈도우에서의 서브 프로세스 지원

윈도우의 SelectorEventLoop는 서브 프로세스를 지원하지 않습니다. 윈도우에서는, 대신 ProactorEventLoop를 사용해야 합니다:

import asyncio

asyncio.set_event_loop_policy(
    asyncio.WindowsProactorEventLoopPolicy())

asyncio.run(your_code())

ProactorEventLoop가 자식 프로세스를 관찰하는 다른 메커니즘을 가지고 있으므로, policy.set_child_watcher() 함수도 지원되지 않습니다.

macOS

최신 macOS 버전은 완전하게 지원됩니다.

macOS <= 10.8

macOS 10.6, 10.7 및 10.8에서, 기본 이벤트 루프는 selectors.KqueueSelector를 사용하는데, 이 버전에서는 문자 장치를 지원하지 않습니다. 이러한 이전 버전의 macOS에서 문자 장치를 지원하려면, SelectorEventLoop가 SelectSelector 나 PollSelector를 사용하도록 수동으로 구성할 수 있습니다. 예:

import asyncio
import selectors

selector = selectors.SelectSelector()
loop = asyncio.SelectorEventLoop(selector)
asyncio.set_event_loop(loop)

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

네트워킹과 프로세스 간 통신 »

asyncio — 비동기 I/O »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

네트워킹과 프로세스 간 통신 »

asyncio — 비동기 I/O »

|

고수준 API 색인

이 페이지에는 모든 고수준의 async/await 활성화된 asyncio API가 나열됩니다.

태스크

asyncio 프로그램을 실행하고, 태스크를 만들고, 시간제한 있게 여러 가지를 기다리는 유틸리티.

run()

이벤트 루프를 만들고, 코루틴을 실행하고, 루프를 닫습니다.

create_task()

asyncio Task를 시작합니다.

await sleep()

몇 초 동안 잠잡니다.

await gather()

여러 가지를 동시에 예약하고 기다립니다.

await wait_for()

시간제한 있게 실행합니다.

await shield()

취소로부터 보호합니다.

await wait()

완료를 감시합니다.

current_task()

현재 Task를 돌려줍니다.

all_tasks()

이벤트 루프의 모든 태스크를 반환합니다.

Task

Task 객체.

run_coroutine_threadsafe()

다른 OS 스레드에서 코루틴을 예약합니다.

for in as_completed()

for 루프로 완료를 감시합니다.

예제

여러 가지를 병렬로 실행하기 위해 asyncio.gather() 사용하기.

시간제한을 주기 위해 asyncio.wait_for() 사용하기.

취소.

asyncio.sleep() 사용하기.

주 태스크 설명서 페이지를 참조하십시오.

큐

큐는 여러 asyncio 태스크 간에 작업을 분산하고, 연결 풀과 pub/sub 패턴을 구현하는 데 사용해야 합니다.

Queue

FIFO 큐.

PriorityQueue

우선순위 큐.

LifoQueue

LIFO 큐.

예제

여러 태스크로 작업부하를 분산하는데 asyncio.Queue 사용하기.

큐 설명서 페이지도 참조하십시오.

서브 프로세스

서브 프로세스를 생성하고 셸 명령을 실행하는 유틸리티.

await create_subprocess_exec()

서브 프로세스를 만듭니다.

await create_subprocess_shell()

셸 명령을 실행합니다.

예제

셸 명령 실행하기.

서브 프로세스 API 설명서도 참조하십시오.

스트림

네트워크 IO로 작업하는 고수준 API

await open_connection()

TCP 연결을 만듭니다.

await open_unix_connection()

유닉스 소켓 연결을 만듭니다.

await start_server()

TCP 서버를 시작합니다.

await start_unix_server()

유닉스 소켓 서버를 시작합니다.

StreamReader

네트워크 데이터를 수신하는 고수준 async/await 객체.

StreamWriter

네트워크 데이터를 보내는 고수준 async/await 객체.

예제

예제 TCP 클라이언트.

스트림 API 설명서도 참조하십시오.

동기화

태스크에 쓸 수 있는 threading과 유사한 동기화 프리미티브.

Lock

뮤텍스 록.

Event

이벤트 객체.

Condition

조건 객체.

Semaphore

세마포어.

BoundedSemaphore

제한된 세마포어.

예제

asyncio.Event 사용하기.

asyncio 동기화 프리미티브의 설명서도 참조하십시오.

예외

asyncio.TimeoutError

wait_for()와 같은 함수에서 시간 초과 시 발생합니다. asyncio.TimeoutError는 내장 TimeoutError 예외와 관련이 없음에 유의하세요.

asyncio.CancelledError

Task가 취소될 때 발생합니다. Task.cancel()도 참조하십시오.

예제

취소 요청 시에 코드를 실행하기 위해 CancelledError 처리하기.

asyncio 전용 예외의 전체 목록도 참조하십시오.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

네트워킹과 프로세스 간 통신 »

asyncio — 비동기 I/O »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

네트워킹과 프로세스 간 통신 »

asyncio — 비동기 I/O »

|

저수준 API 색인

이 페이지는 모든 저수준 asyncio API를 나열합니다.

이벤트 루프 얻기

asyncio.get_running_loop()

실행 중인 이벤트 루프를 가져오는 데 선호되는 함수.

asyncio.get_event_loop()

이벤트 루프 인스턴스를 가져옵니다 (현재 또는 정책을 통해).

asyncio.set_event_loop()

현재 정책을 통해 현재 이벤트 루프를 설정합니다.

asyncio.new_event_loop()

새 이벤트 루프를 만듭니다.

예제

asyncio.get_running_loop() 사용하기.

이벤트 루프 메서드

이벤트 루프 메서드에 관한 주 설명서 절도 참조하십시오.

수명주기

loop.run_until_complete()

완료할 때까지 퓨처/태스크/어웨이터블을 실행합니다.

loop.run_forever()

이벤트 루프를 영원히 실행합니다.

loop.stop()

이벤트 루프를 중지합니다.

loop.close()

이벤트 루프를 닫습니다.

loop.is_running()

이벤트 루프가 실행 중이면 True를 반환합니다.

loop.is_closed()

이벤트 루프가 닫혔으면 True를 반환합니다.

await loop.shutdown_asyncgens()

비동기 제너레이터를 닫습니다.

디버깅

loop.set_debug()

디버그 모드를 활성화 또는 비활성화합니다.

loop.get_debug()

현재의 디버그 모드를 얻습니다.

콜백 예약하기

loop.call_soon()

콜백을 곧 호출합니다.

loop.call_soon_threadsafe()

스레드 안전한 loop.call_soon()의 변형입니다.

loop.call_later()

주어진 시간 후에 콜백을 호출합니다.

loop.call_at()

주어진 시간 에 콜백을 호출합니다.

스레드/프로세스 풀

await loop.run_in_executor()

concurrent.futures 실행기에서 CPU-병목이나 다른 블로킹 함수를 실행합니다.

loop.set_default_executor()

loop.run_in_executor()의 기본 실행기를 설정합니다.

태스크와 퓨처

loop.create_future()

Future 객체를 만듭니다.

loop.create_task()

코루틴을 Task로 예약합니다.

loop.set_task_factory()

loop.create_task()가 태스크를 만드는데 사용하는 팩토리를 설정합니다.

loop.get_task_factory()

loop.create_task()가 태스크를 만드는데 사용하는 팩토리를 얻습니다.

DNS

await loop.getaddrinfo()

socket.getaddrinfo()의 비동기 버전.

await loop.getnameinfo()

socket.getnameinfo()의 비동기 버전.

네트워킹과 IPC

await loop.create_connection()

TCP 연결을 엽니다.

await loop.create_server()

TCP 서버를 만듭니다.

await loop.create_unix_connection()

유닉스 소켓 연결을 엽니다.

await loop.create_unix_server()

Unix 소켓 서버를 만듭니다.

await loop.connect_accepted_socket()

socket을 (transport, protocol) 쌍으로 감쌉니다.

await loop.create_datagram_endpoint()

데이터 그램 (UDP) 연결을 엽니다.

await loop.sendfile()

트랜스포트를 통해 파일을 보냅니다.

await loop.start_tls()

기존 연결을 TLS로 업그레이드합니다.

await loop.connect_read_pipe()

파이프의 읽기 끝을 (transport, protocol) 쌍으로 감쌉니다.

await loop.connect_write_pipe()

파이프의 쓰기 끝을 (transport, protocol) 쌍으로 감쌉니다.

소켓

await loop.sock_recv()

socket에서 데이터를 수신합니다.

await loop.sock_recv_into()

socket에서 데이터를 버퍼로 수신합니다.

await loop.sock_sendall()

데이터를 socket으로 보냅니다.

await loop.sock_connect()

socket을 연결합니다.

await loop.sock_accept()

socket 연결을 수락합니다.

await loop.sock_sendfile()

socket를 통해 파일을 보냅니다.

loop.add_reader()

파일 기술자가 읽기 가능한지 관찰하기 시작합니다.

loop.remove_reader()

파일 기술자가 읽기 가능한지 관찰하는 것을 중단합니다.

loop.add_writer()

파일 기술자가 쓰기 가능한지 관찰하기 시작합니다.

loop.remove_writer()

파일 기술자가 쓰기 가능한지 관찰하는 것을 중단합니다.

유닉스 시그널

loop.add_signal_handler()

signal에 대한 처리기를 추가합니다.

loop.remove_signal_handler()

signal에 대한 처리기를 제거합니다.

서브 프로세스

loop.subprocess_exec()

서브 프로세스를 스폰합니다.

loop.subprocess_shell()

셸 명령으로 서브 프로세스를 스폰합니다.

에러 처리

loop.call_exception_handler()

예외 처리기를 호출합니다.

loop.set_exception_handler()

새로운 예외 처리기를 설정합니다.

loop.get_exception_handler()

현재 예외 처리기를 가져옵니다.

loop.default_exception_handler()

기본 예외 처리기 구현.

예제

asyncio.get_event_loop() 와 loop.run_forever() 사용하기.

loop.call_later() 사용하기.

loop.create_connection()을 사용하여 메아리 클라이언트 구현하기.

loop.create_connection()을 사용하여 소켓 연결하기.

add_reader()를 사용하여 FD에서 읽기 이벤트 관찰하기.

loop.add_signal_handler() 사용하기.

loop.subprocess_exec() 사용하기.

트랜스포트

모든 트랜스포트는 다음과 같은 메서드를 구현합니다:

transport.close()

트랜스포트를 닫습니다.

transport.is_closing()

트랜스포트가 닫히고 있거나 닫혔으면 True를 반환합니다.

transport.get_extra_info()

트랜스포트에 대한 정보를 요청합니다.

transport.set_protocol()

새 프로토콜을 설정합니다.

transport.get_protocol()

현재 프로토콜을 돌려줍니다.

데이터를 받을 수 있는 트랜스포트 (TCP 및 유닉스 연결, 파이프 등). loop.create_connection(), loop.create_unix_connection(), loop.connect_read_pipe() 등의 메서드에서 반환됩니다:

트랜스포트 읽기

transport.is_reading()

트랜스포트가 수신 중이면 True를 반환합니다.

transport.pause_reading()

수신을 일시 정지합니다.

transport.resume_reading()

수신을 재개합니다.

데이터를 전송할 수 있는 트랜스포트 (TCP와 유닉스 연결, 파이프 등). loop.create_connection(), loop.create_unix_connection(), loop.connect_write_pipe() 등의 메서드에서 반환됩니다:

트랜스포트 쓰기

transport.write()

데이터를 트랜스포트에 씁니다.

transport.writelines()

버퍼들을 트랜스포트에 씁니다.

transport.can_write_eof()

트랜스포트가 EOF 전송을 지원하면 True를 반환합니다.

transport.write_eof()

버퍼 된 데이터를 플러시 한 후 닫고 EOF를 보냅니다.

transport.abort()

즉시 트랜스포트를 닫습니다.

transport.get_write_buffer_size()

쓰기 흐름 제어를 위한 높은 수위와 낮은 수위를 반환합니다.

transport.set_write_buffer_limits()

쓰기 흐름 제어를 위한 새로운 높은 수위와 낮은 수위를 설정합니다.

loop.create_datagram_endpoint()에서 반환된 트랜스포트:

데이터 그램 트랜스포트

transport.sendto()

데이터를 원격 피어로 보냅니다.

transport.abort()

즉시 트랜스포트를 닫습니다.

서브 프로세스에 대한 저수준 트랜스포트 추상화. loop.subprocess_exec() 와 loop.subprocess_shell()가 반환합니다:

서브 프로세스 트랜스포트

transport.get_pid()

서브 프로세스의 프로세스 ID를 돌려줍니다.

transport.get_pipe_transport()

요청한 통신 파이프 (stdin, stdout 또는 stderr)에 대한 트랜스포트를 반환합니다.

transport.get_returncode()

서브 프로세스 반환 코드를 돌려줍니다.

transport.kill()

서브 프로세스를 죽입니다.

transport.send_signal()

서브 프로세스에 시그널을 보냅니다.

transport.terminate()

서브 프로세스를 중지합니다.

transport.close()

서브 프로세스를 죽이고 모든 파이프를 닫습니다.

프로토콜

프로토콜 클래스는 다음 콜백 메서드를 구현할 수 있습니다:

callback connection_made()

연결이 이루어질 때 호출됩니다.

callback connection_lost()

연결이 끊어지거나 닫힐 때 호출됩니다.

callback pause_writing()

트랜스포트 버퍼가 높은 수위를 초과할 때 호출됩니다.

callback resume_writing()

트랜스포트 버퍼가 낮은 수위 아래로 내려갈 때 호출됩니다.

스트리밍 프로토콜 (TCP, 유닉스 소켓, 파이프)

callback data_received()

어떤 데이터가 수신될 때 호출됩니다.

callback eof_received()

EOF가 수신될 때 호출됩니다.

버퍼 된 스트리밍 프로토콜

callback get_buffer()

새로운 수신 버퍼를 할당하기 위해서 호출됩니다.

callback buffer_updated()

수신된 데이터로 버퍼가 갱신될 때 호출됩니다.

callback eof_received()

EOF가 수신될 때 호출됩니다.

데이터 그램 프로토콜

callback datagram_received()

데이터 그램이 수신될 때 호출됩니다.

callback error_received()

이전의 송신이나 수신 연산이 OSError를 일으킬 때 호출됩니다.

서브 프로세스 프로토콜

callback pipe_data_received()

자식 프로세스가 stdout 이나 stderr 파이프에 데이터를 쓸 때 호출됩니다.

callback pipe_connection_lost()

자식 프로세스와 통신하는 파이프 중 하나가 닫힐 때 호출됩니다.

callback process_exited()

자식 프로세스가 종료할 때 호출됩니다.

이벤트 루프 정책

정책은 asyncio.get_event_loop()와 같은 함수의 동작을 변경하는 저수준 메커니즘입니다. 자세한 내용은 주 정책 절을 참조하십시오.

정책 액세스하기

asyncio.get_event_loop_policy()

현재 프로세스 전반의 정책을 돌려줍니다.

asyncio.set_event_loop_policy()

새로운 프로세스 전반의 정책을 설정합니다.

AbstractEventLoopPolicy

정책 객체의 베이스 클래스.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

네트워킹과 프로세스 간 통신 »

asyncio — 비동기 I/O »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

네트워킹과 프로세스 간 통신 »

asyncio — 비동기 I/O »

|

asyncio로 개발하기

비동기 프로그래밍은 고전적인 “순차적” 프로그래밍과 다릅니다.

이 페이지는 흔한 실수와 함정을 나열하고, 이를 피하는 방법을 설명합니다.

디버그 모드

기본적으로 asyncio는 프로덕션 모드로 실행됩니다. 개발을 쉽게 하려고 asyncio에는 디버그 모드를 제공합니다.

여러 가지 방법으로 asyncio 디버그 모드를 활성화할 수 있습니다:

PYTHONASYNCIODEBUG 환경 변수를 1로 설정.

-X dev 파이썬 명령 줄 옵션 사용.

debug=True를 asyncio.run()로 전달.

loop.set_debug()를 호출.

디버그 모드를 활성화하는 것 외에도, 다음을 고려하십시오:

asyncio 로거의 로그 수준을 logging.DEBUG로 설정, 예를 들어 응용 프로그램 시작 시 다음 코드 조각을 실행할 수 있습니다:

logging.basicConfig(level=logging.DEBUG)

ResourceWarning 경고를 표시하도록 warnings 모듈을 구성. 이렇게 하는 한 가지 방법은 -W default 명령 줄 옵션을 사용하는 것입니다.

디버그 모드가 활성화되면:

asyncio는 기다리지 않은 코루틴을 검사하고 로그 합니다; 이것은 “잊힌 await” 함정을 완화합니다.

많은 스레드 안전하지 않은 asyncio API(loop.call_soon()과 loop.call_at() 메서드와 같은)가 잘못된 스레드에서 호출될 때 예외를 발생시킵니다.

I/O 선택기의 실행 시간은 I/O 연산 수행에 너무 오래 걸리면 로그 됩니다.

100ms보다 오래 걸리는 콜백이 로그 됩니다. loop.slow_callback_duration 어트리뷰트는 “느린” 것으로 간주할 최소 실행 시간(초)을 설정하는 데 사용될 수 있습니다.

동시성과 다중 스레드

이벤트 루프는 스레드(일반적으로 주 스레드)에서 실행되며 그 스레드에서 모든 콜백과 태스크를 실행합니다. 태스크가 이벤트 루프에서 실행되는 동안, 다른 태스크는 같은 스레드에서 실행될 수 없습니다. 태스크가 await 표현식을 실행하면, 실행 중인 태스크가 일시 중지되고 이벤트 루프는 다음 태스크를 실행합니다.

다른 OS 스레드에서 콜백을 예약하려면, loop.call_soon_threadsafe() 메서드를 사용해야 합니다. 예:

loop.call_soon_threadsafe(callback, *args)

거의 모든 asyncio 객체는 스레드 안전하지 않습니다. 태스크나 콜백 외부에서 작동하는 코드가 없으면 일반적으로 문제가 되지 않습니다. 그러한 코드가 저수준 asyncio API를 호출해야 하면, loop.call_soon_threadsafe() 메서드를 사용해야 합니다, 예를 들어:

loop.call_soon_threadsafe(fut.cancel)

다른 OS 스레드에서 코루틴 객체를 예약하려면, run_coroutine_threadsafe() 함수를 사용해야 합니다. 결과에 액세스할 수 있도록 concurrent.futures.Future를 반환합니다:

async def coro_func():
     return await asyncio.sleep(1, 42)

# Later in another OS thread:

future = asyncio.run_coroutine_threadsafe(coro_func(), loop)
# Wait for the result:
result = future.result()

시그널을 처리하고 자식 프로세스를 실행하려면, 이벤트 루프를 메인 스레드에서 실행해야 합니다.

loop.run_in_executor() 메서드는 concurrent.futures.ThreadPoolExecutor와 함께 사용되어, 이벤트 루프가 실행되는 OS 스레드를 블록하지 않고 다른 OS 스레드에서 블로킹 코드를 실행할 수 있습니다.

블로킹 코드 실행하기

블로킹 (CPU 병목) 코드는 직접 호출하면 안 됩니다. 예를 들어, 함수가 CPU 집약적인 계산을 1초 동안 수행하면, 모든 동시 asyncio 태스크와 IO 연산이 1초 지연됩니다.

An executor can be used to run a task in a different thread or even in a different process to avoid blocking the OS thread with the event loop. See the loop.run_in_executor() method for more details.

로깅

asyncio는 logging 모듈을 사용하고, 모든 로깅은 "asyncio" 로거를 통해 수행됩니다.

기본 로그 수준은 logging.INFO며, 쉽게 조정할 수 있습니다:

logging.getLogger("asyncio").setLevel(logging.WARNING)

await 하지 않은 코루틴 감지

코루틴 함수가 호출되었지만 기다리지 않을 때(예를 들어, await coro() 대신 coro())나 코루틴이 asyncio.create_task()로 예약되지 않으면 asyncio가 RuntimeWarning을 방출합니다:

import asyncio

async def test():
    print("never scheduled")

async def main():
    test()

asyncio.run(main())

출력:

test.py:7: RuntimeWarning: coroutine 'test' was never awaited
  test()

디버그 모드에서의 출력:

test.py:7: RuntimeWarning: coroutine 'test' was never awaited
Coroutine created at (most recent call last)
  File "../t.py", line 9, in <module>
    asyncio.run(main(), debug=True)

  < .. >

  File "../t.py", line 7, in main
    test()
  test()

일반적인 수정법은 코루틴을 await 하거나 asyncio.create_task() 함수를 호출하는 것입니다:

async def main():
    await test()

전달되지 않은 예외 감지

Future.set_exception()가 호출되었지만, Future 객체가 await 되지 않으면, 예외는 절대로 사용자 코드로 전파되지 않습니다. 이럴 때, Future 객체가 가비지 수집될 때 asyncio가 로그 메시지를 출력합니다.

처리되지 않은 예외의 예:

import asyncio

async def bug():
    raise Exception("not consumed")

async def main():
    asyncio.create_task(bug())

asyncio.run(main())

출력:

Task exception was never retrieved
future: <Task finished coro=<bug() done, defined at test.py:3>
  exception=Exception('not consumed')>

Traceback (most recent call last):
  File "test.py", line 4, in bug
    raise Exception("not consumed")
Exception: not consumed

태스크가 만들어진 곳의 트레이스백을 얻으려면 디버그 모드를 활성화하세요:

asyncio.run(main(), debug=True)

디버그 모드에서의 출력:

Task exception was never retrieved
future: <Task finished coro=<bug() done, defined at test.py:3>
    exception=Exception('not consumed') created at asyncio/tasks.py:321>

source_traceback: Object created at (most recent call last):
  File "../t.py", line 9, in <module>
    asyncio.run(main(), debug=True)

< .. >

Traceback (most recent call last):
  File "../t.py", line 4, in bug
    raise Exception("not consumed")
Exception: not consumed

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

네트워킹과 프로세스 간 통신 »

asyncio — 비동기 I/O »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

네트워킹과 프로세스 간 통신 »

|

socket — 저수준 네트워킹 인터페이스

소스 코드: Lib/socket.py [https://github.com/python/cpython/tree/3.7/Lib/socket.py]

이 모듈은 BSD socket 인터페이스에 대한 액세스를 제공합니다. 모든 현대 유닉스 시스템, 윈도우, MacOS, 그리고 아마 추가 플랫폼에서 사용할 수 있습니다.

참고

호출이 운영 체제 소켓 API로 이루어지기 때문에, 일부 동작은 플랫폼에 따라 다를 수 있습니다.

파이썬 인터페이스는 유닉스 시스템 호출과 소켓을 위한 라이브러리 인터페이스를 파이썬의 객체 지향 스타일로 직역한 것입니다: socket() 함수는 소켓 객체 (socket object)를 반환하고, 이것의 메서드는 다양한 소켓 시스템 호출을 구현합니다. 매개 변수 형은 C 인터페이스보다 다소 고수준입니다: 파이썬 파일에 대한 read() 와 write() 연산처럼, 수신 연산의 버퍼 할당은 자동이고 전송 연산에서 버퍼 길이는 묵시적입니다.

더 보기

모듈 socketserver

네트워크 서버 작성을 단순화하는 클래스.

모듈 ssl

소켓 객체용 TLS/SSL 래퍼.

소켓 패밀리

시스템과 빌드 옵션에 따라, 다양한 소켓 패밀리가 이 모듈에서 지원됩니다.

특정 소켓 객체가 요구하는 주소 형식은 소켓 객체를 만들 때 지정된 주소 패밀리에 따라 자동으로 선택됩니다. 소켓 주소는 다음과 같이 표현됩니다:

파일 시스템 노드에 바인드 된 AF_UNIX 소켓의 주소는 파일 시스템 인코딩과 'surrogateescape' 에러 처리기(PEP 383 [https://www.python.org/dev/peps/pep-0383]을 참조하세요)를 사용하는 문자열로 표현됩니다. 리눅스의 추상 이름 공간(abstract namespace)에 있는 주소는 처음에 널 바이트가 있는 바이트열류 객체로 반환됩니다; 이 이름 공간의 소켓은 일반 파일 시스템 소켓과 통신 할 수 있으므로, 리눅스에서 실행하려는 프로그램은 두 가지 유형의 주소를 모두 다뤄야 할 수도 있습니다. 문자열이나 바이트열류 객체는 인자로 전달할 때 두 가지 유형의 주소에 모두 사용할 수 있습니다.

버전 3.3에서 변경: 이전에는, AF_UNIX 소켓 경로가 UTF-8 인코딩을 사용한다고 가정했습니다.

버전 3.5에서 변경: 이제 쓰기 가능한 바이트열류 객체를 받아들입니다.

쌍 (host, port)가 AF_INET 주소 패밀리에 사용됩니다. 여기서 host는 'daring.cwi.nl'과 같은 인터넷 도메인 표기법의 호스트 명이나 '100.50.200.5'와 같은 IPv4 주소를 나타내는 문자열이고, port는 정수입니다.

IPv4 주소의 경우, 호스트 주소 대신 두 개의 특수 형식이 허용됩니다: ''는 모든 인터페이스에 바인딩하는 데 사용되는 INADDR_ANY를 나타내며 '<broadcast>' 문자열은 INADDR_BROADCAST를 나타냅니다. 이 동작은 IPv6와 호환되지 않으므로, 여러분의 파이썬 프로그램에서 IPv6를 지원하려는 경우에는 이것들을 사용하지 않을 수 있습니다.

AF_INET6 주소 패밀리의 경우, 4-튜플 (host, port, flowinfo, scopeid)가 사용됩니다. 여기서 flowinfo 와 scopeid는 C에서 struct sockaddr_in6의 sin6_flowinfo 와 sin6_scope_id 멤버를 나타냅니다. socket 모듈 메서드의 경우, flowinfo 와 scopeid는 이전 버전과의 호환성을 위해 생략할 수 있습니다. 그러나, scopeid를 생략하면 스코프가 지정된(scoped) IPv6 주소를 조작하는 데 문제가 발생할 수 있습니다.

버전 3.7에서 변경: 멀티캐스트 주소(의미 있는 scopeid를 가진)의 경우, address에는 %scope (또는 zone id) 부분이 포함될 수 없습니다. 이 정보는 불필요하므로 안전하게 생략할 수 있습니다 (권장 사항).

AF_NETLINK 소켓은 (pid, groups) 쌍으로 표현됩니다.

TIPC에 대한 리눅스 전용 지원은 AF_TIPC 주소 패밀리를 사용하여 사용할 수 있습니다. TIPC는 클러스터 된 컴퓨터 환경에서 사용하도록 설계된 개방형 비 IP 기반 네트워크 프로토콜입니다. 주소는 튜플로 표현되며 필드는 주소 유형에 따라 다릅니다. 일반적인 튜플 형식은 (addr_type, v1, v2, v3 [, scope])입니다. 이때:

addr_type은 TIPC_ADDR_NAMESEQ, TIPC_ADDR_NAME 또는 TIPC_ADDR_ID 중 하나입니다.

scope는 TIPC_ZONE_SCOPE, TIPC_CLUSTER_SCOPE 또는 TIPC_NODE_SCOPE 중 하나입니다.

addr_type이 TIPC_ADDR_NAME이면, v1은 서버 유형이고, v2는 포트 식별자이며, v3은 0이어야 합니다.

addr_type이 TIPC_ADDR_NAMESEQ면, v1은 서버 유형이고, v2는 하위 포트 번호이며, v3는 상위 포트 번호입니다.

addr_type이 TIPC_ADDR_ID면, v1은 노드이고, v2는 참조이며, v3는 0으로 설정되어야 합니다.

튜플 (interface, )가 AF_CAN 주소 패밀리에 사용됩니다. 여기서 interface는 'can0'과 같은 네트워크 인터페이스 이름을 나타내는 문자열입니다. 네트워크 인터페이스 이름 ''는 이 패밀리의 모든 네트워크 인터페이스에서 패킷을 수신하는 데 사용할 수 있습니다.

CAN_ISOTP 프로토콜은 튜플 (interface, rx_addr, tx_addr)를 요구하는데, 두 개의 추가 매개 변수는 모두 CAN 식별자(표준 또는 확장)를 나타내는 부호 없는 long 정수입니다.

문자열이나 튜플 (id, unit)는 PF_SYSTEM 패밀리의 SYSPROTO_CONTROL 프로토콜에 사용됩니다. 문자열은 동적으로 할당된 ID를 사용하는 커널 컨트롤의 이름입니다. 튜플은 커널 컨트롤의 ID와 유닛 번호가 알려져 있거나 등록된 ID가 사용될 때 사용할 수 있습니다.

버전 3.3에 추가.

AF_BLUETOOTH는 다음 프로토콜 및 주소 형식을 지원합니다:

BTPROTO_L2CAP는 (bdaddr, psm)를 받아들입니다. 여기서 bdaddr은 문자열 블루투스 주소이고 psm은 정수입니다.

BTPROTO_RFCOMM은 (bdaddr, channel)를 받아들입니다. 여기서 bdaddr은 문자열 블루투스 주소이고 channel은 정수입니다.

BTPROTO_HCI는 (device_id,)를 받아들입니다. 여기서 device_id는 정수나 인터페이스의 블루투스 주소인 문자열입니다. (이것은 여러분의 OS에 따라 다릅니다; NetBSD와 FreeBSD는 블루투스 주소를 기대하지만 다른 모든 것은 정수를 기대합니다.)

버전 3.2에서 변경: NetBSD 및 DragonFlyBSD 지원이 추가되었습니다.

BTPROTO_SCO는 bdaddr를 받아들입니다. 여기서 bdaddr는 블루투스 주소의 문자열 형식이 포함된 bytes 객체입니다. (예, b'12:23:34:45:56:67') 이 프로토콜은 FreeBSD에서 지원되지 않습니다.

AF_ALG는 커널 암호 인터페이스에 기반한 리눅스 전용 소켓입니다. 알고리즘 소켓은 2~4개의 요소를 갖는 (type, name [, feat [, mask]]) 튜플로 구성됩니다. 여기서:

type은 문자열의 알고리즘 유형입니다, 예를 들어, aead, hash, skcipher 또는 rng.

name은 알고리즘 이름과 연산 모드 문자열입니다, 예를 들어, sha256, hmac(sha256), cbc(aes) 또는 drbg_nopr_ctr_aes256.

feat 과 mask는 부호 없는 32비트 정수입니다.

Availability: Linux 2.6.38, some algorithm types require more recent Kernels.

버전 3.6에 추가.

AF_VSOCK은 가상 기계와 호스트가 통신할 수 있게 합니다. 소켓은 (CID, port) 튜플로 표현되는데, 컨텍스트 ID 또는 CID와 port는 정수입니다.

Availability: Linux >= 4.8 QEMU >= 2.8 ESX >= 4.0 ESX Workstation >= 6.5.

버전 3.7에 추가.

AF_PACKET은 네트워크 장치에 직접 연결된 저수준 인터페이스입니다. 패킷은 튜플 (ifname, proto[, pkttype[, hatype[, addr]]])로 표현됩니다. 여기서:

ifname - 장치 이름을 지정하는 문자열

proto - 이더넷 프로토콜 번호를 지정하는 네트워크 바이트 순서 정수.

pkttype - 패킷 유형을 지정하는 선택적 정수.:

PACKET_HOST (기본값) - 로컬 호스트로 향하는 패킷.

PACKET_BROADCAST - 물리 계층 브로드캐스트 패킷.

PACKET_MULTIHOST - 물리 계층 멀티캐스트 주소로 전송된 패킷.

PACKET_OTHERHOST - 무차별 모드의 장치 관리자에 의해 포착된 다른 호스트로 향하는 패킷.

PACKET_OUTGOING - 패킷 소켓으로 루프 백 된 로컬 호스트에서 시작된 패킷.

hatype - ARP 하드웨어 주소 유형을 지정하는 선택적 정수.

addr - 하드웨어 물리 주소를 지정하는 선택적 바이트열류 객체, 해석은 장치에 따라 다릅니다.

IPv4/v6 소켓 주소의 host 부분에 호스트 명을 사용하면, 파이썬이 DNS 결정에서 반환된 첫 번째 주소를 사용하기 때문에, 프로그램은 비결정적인 동작을 보일 수 있습니다. 소켓 주소는 DNS 결정 결과 및/또는 호스트 구성에 따라 실제 IPv4/v6 주소로 다르게 결정됩니다. 결정론적 동작을 위해서는 host 부분에 숫자 주소를 사용하십시오.

모든 에러는 예외를 발생시킵니다. 잘못된 인자 형과 메모리 부족 조건에 대한 일반적인 예외가 발생할 수 있습니다. 파이썬 3.3부터, 소켓이나 주소 의미와 관련된 에러는 OSError 나 그 서브 클래스 중 하나를 발생시킵니다 (예전에는 socket.error를 발생시켰습니다).

비 블로킹 모드는 setblocking()을 통해 지원됩니다. 시간제한을 기반으로 하는 일반화는 settimeout()을 통해 지원됩니다.

모듈 내용

모듈 socket은 다음 요소를 노출합니다.

예외

exception socket.error

OSError의 폐지된 별칭.

버전 3.3에서 변경: PEP 3151 [https://www.python.org/dev/peps/pep-3151]을 따라, 이 클래스는 OSError의 별칭이 되었습니다.

exception socket.herror

OSError의 서브 클래스, 이 예외는 주소 관련 에러에서 발생합니다. 즉 gethostbyname_ex()와 gethostbyaddr()를 포함하는 POSIX C API의 h_errno를 사용하는 함수들. 수반되는 값은 라이브러리 호출이 반환한 에러를 나타내는 (h_errno, string) 쌍입니다. h_errno는 숫자 값이고, string은 hstrerror() C 함수에 의해 반환된 h_errno의 설명을 나타냅니다.

버전 3.3에서 변경: 이 클래스는 OSError의 서브 클래스가 되었습니다.

exception socket.gaierror

OSError의 서브 클래스, 이 예외는 getaddrinfo() 와 getnameinfo()에 의한 주소 관련 에러에서 발생합니다. 수반되는 값은 라이브러리 호출이 반환한 에러를 나타내는 (error, string) 쌍입니다. string은 gai_strerror() C 함수가 반환한 error의 설명을 나타냅니다. 숫자 error 값은 이 모듈에 정의된 EAI_* 상수 중 하나와 일치합니다.

버전 3.3에서 변경: 이 클래스는 OSError의 서브 클래스가 되었습니다.

exception socket.timeout

OSError의 서브 클래스, 이 예외는 앞서 settimeout() 호출을 통해 (또는 묵시적으로 setdefaulttimeout()를 통해) 시간제한이 활성화된 소켓에서 시간 초과가 일어날 때 발생합니다. 수반되는 값은 현재는 항상 “timed out” 값을 갖는 문자열입니다.

버전 3.3에서 변경: 이 클래스는 OSError의 서브 클래스가 되었습니다.

상수

AF_* 와 SOCK_* 상수는 이제 AddressFamily 와 SocketKind IntEnum 컬렉션입니다.

버전 3.4에 추가.

socket.AF_UNIX

socket.AF_INET

socket.AF_INET6

이 상수는 socket()의 첫 번째 인자에 사용되는 주소 (및 프로토콜) 패밀리를 나타냅니다. AF_UNIX 상수가 정의되지 않으면 이 프로토콜은 지원되지 않습니다. 시스템에 따라 더 많은 상수를 사용할 수 있습니다.

socket.SOCK_STREAM

socket.SOCK_DGRAM

socket.SOCK_RAW

socket.SOCK_RDM

socket.SOCK_SEQPACKET

이 상수는 socket()의 두 번째 인자에 사용되는 소켓 유형을 나타냅니다. 시스템에 따라 더 많은 상수를 사용할 수 있습니다. (SOCK_STREAM과 SOCK_DGRAM 만 일반적으로 유용합니다.)

socket.SOCK_CLOEXEC

socket.SOCK_NONBLOCK

이 두 상수는, 정의되었다면, 소켓 유형과 결합하여 일부 플래그를 원자 적으로 설정할 수 있도록 합니다 (따라서 경쟁 조건의 가능성과 별도 호출의 필요성을 피할 수 있습니다).

더 보기

좀 더 철저한 설명은 Secure File Descriptor Handling [http://udrepper.livejournal.com/20407.html].

가용성: 리눅스 >= 2.6.27.

버전 3.2에 추가.

SO_*

socket.SOMAXCONN

MSG_*

SOL_*

SCM_*

IPPROTO_*

IPPORT_*

INADDR_*

IP_*

IPV6_*

EAI_*

AI_*

NI_*

TCP_*

소켓 및/또는 IP 프로토콜에 대한 유닉스 설명서에서 설명된 이 형식의 많은 상수는 소켓 모듈에도 정의되어 있습니다. 일반적으로 소켓 객체의 setsockopt() 와 getsockopt() 메서드 인자에 사용됩니다. 대부분 유닉스 헤더 파일에 정의된 기호만 정의됩니다; 몇 가지 기호는 기본값이 제공됩니다.

버전 3.6에서 변경: SO_DOMAIN, SO_PROTOCOL, SO_PEERSEC, SO_PASSSEC, TCP_USER_TIMEOUT, TCP_CONGESTION가 추가되었습니다.

버전 3.6.5에서 변경: 윈도우에서, 런타임 윈도우가 지원하면 TCP_FASTOPEN, TCP_KEEPCNT가 나타납니다.

버전 3.7에서 변경: TCP_NOTSENT_LOWAT가 추가되었습니다.

윈도우에서, 런타임 윈도우가 지원하면 TCP_KEEPIDLE, TCP_KEEPINTVL가 나타납니다.

socket.AF_CAN

socket.PF_CAN

SOL_CAN_*

CAN_*

리눅스 설명서에 설명되어있는 이 형식의 많은 상수는 소켓 모듈에도 정의되어 있습니다.

가용성 : 리눅스 >= 2.6.25.

버전 3.3에 추가.

socket.CAN_BCM

CAN_BCM_*

CAN 프로토콜 패밀리에서 CAN_BCM은 브로드캐스트 관리자 (Broadcast Manager, BCM) 프로토콜입니다. 리눅스 설명서에서 설명된 브로드캐스트 관리자 상수도 소켓 모듈에 정의되어 있습니다.

가용성 : 리눅스 >= 2.6.25.

버전 3.4에 추가.

socket.CAN_RAW_FD_FRAMES

CAN_RAW 소켓에서 CAN FD 지원을 활성화합니다. 기본적으로 비활성화되어 있습니다. 여러분의 응용 프로그램이 CAN과 CAN FD 프레임을 모두 보낼 수 있도록 합니다; 그러나 소켓에서 읽을 때 CAN과 CAN FD 프레임을 모두 받아들여야 합니다.

이 상수는 리눅스 설명서에 설명되어 있습니다.

가용성 : 리눅스 >= 3.6.

버전 3.5에 추가.

socket.CAN_ISOTP

CAN 프로토콜 패밀리의 CAN_ISOTP는 ISO-TP (ISO 15765-2) 프로토콜입니다. ISO-TP 상수는 리눅스 설명서에 설명되어 있습니다.

가용성 : 리눅스 >= 2.6.25.

버전 3.7에 추가.

socket.AF_PACKET

socket.PF_PACKET

PACKET_*

리눅스 설명서에 설명되어있는 이 형식의 많은 상수는 소켓 모듈에도 정의되어 있습니다.

가용성 : 리눅스 >= 2.2.

socket.AF_RDS

socket.PF_RDS

socket.SOL_RDS

RDS_*

리눅스 설명서에 설명되어있는 이 형식의 많은 상수는 소켓 모듈에도 정의되어 있습니다.

가용성 : 리눅스 >= 2.6.30.

버전 3.3에 추가.

socket.SIO_RCVALL

socket.SIO_KEEPALIVE_VALS

socket.SIO_LOOPBACK_FAST_PATH

RCVALL_*

윈도우 WSAIoctl()용 상수. 이 상수는 소켓 객체의 ioctl() 메서드에 대한 인자로 사용됩니다.

버전 3.6에서 변경: SIO_LOOPBACK_FAST_PATH가 추가되었습니다.

TIPC_*

TIPC 관련 상수. C 소켓 API에서 내보낸 것과 일치합니다. 자세한 정보는 TIPC 설명서를 참조하십시오.

socket.AF_ALG

socket.SOL_ALG

ALG_*

리눅스 커널 암호화용 상수.

가용성 : 리눅스 >= 2.6.38.

버전 3.6에 추가.

socket.AF_VSOCK

socket.IOCTL_VM_SOCKETS_GET_LOCAL_CID

VMADDR*

SO_VM*

리눅스 호스트/게스트 통신용 상수.

가용성 : 리눅스 >= 4.8.

버전 3.7에 추가.

socket.AF_LINK

가용성 : BSD, OSX.

버전 3.4에 추가.

socket.has_ipv6

이 상수는 이 플랫폼에서 IPv6가 지원되는지를 나타내는 논릿값을 포함합니다.

socket.BDADDR_ANY

socket.BDADDR_LOCAL

이들은 특수한 의미를 지닌 블루투스 주소를 포함하는 문자열 상수입니다. 예를 들어, BDADDR_ANY는 바인딩 소켓을 BTPROTO_RFCOMM로 지정할 때 임의의(any) 주소를 나타내는 데 사용할 수 있습니다.

socket.HCI_FILTER

socket.HCI_TIME_STAMP

socket.HCI_DATA_DIR

BTPROTO_HCI와 함께 사용하십시오. NetBSD 나 DragonFlyBSD에서는 HCI_FILTER를 사용할 수 없습니다. HCI_TIME_STAMP와 HCI_DATA_DIR는 FreeBSD, NetBSD 또는 DragonFlyBSD에서 사용할 수 없습니다.

함수

소켓 만들기

다음 함수는 모두 소켓 객체를 만듭니다.

socket.socket(family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None)

지정된 주소 패밀리, 소켓 유형, 및 프로토콜 번호를 사용하여 새로운 소켓을 만듭니다. 주소 패밀리는 AF_INET (기본값), AF_INET6, AF_UNIX, AF_CAN, AF_PACKET 또는 AF_RDS 여야 합니다. 소켓 유형은 SOCK_STREAM (기본값), SOCK_DGRAM, SOCK_RAW 또는 기타 SOCK_ 상수 중 하나여야 합니다. 프로토콜 번호는 일반적으로 0이며 생략될 수도 있고, 주소 패밀리가 AF_CAN 일 때 프로토콜은 CAN_RAW, CAN_BCM 또는 CAN_ISOTP 중 하나여야 합니다.

fileno를 지정하면, family, type 및 proto 값이 지정된 파일 기술자에서 자동 감지됩니다. 명시적 family, type 또는 proto 인자를 사용하여 함수를 호출하면 자동 감지가 무효화 될 수 있습니다. 이는 파이썬이 socket.getpeername()의 반환 값을 나타내는 방식에 영향을 미치지만, 실제 OS 자원에는 영향을 주지 않습니다. socket.fromfd()와는 달리, fileno는 복제본이 아니라 같은 소켓을 반환합니다. 이렇게 하면 socket.close()를 사용하여 분리된 소켓을 닫을 수 있습니다.

새로 만들어진 소켓은 상속 불가능합니다.

버전 3.3에서 변경: AF_CAN 패밀리가 추가되었습니다. AF_RDS 패밀리가 추가되었습니다.

버전 3.4에서 변경: CAN_BCM 프로토콜이 추가되었습니다.

버전 3.4에서 변경: 반환된 소켓은 이제 상속 불가능합니다.

버전 3.7에서 변경: CAN_ISOTP 프로토콜이 추가되었습니다.

버전 3.7에서 변경: When SOCK_NONBLOCK or SOCK_CLOEXEC bit flags are applied to type they are cleared, and socket.type will not reflect them. They are still passed to the underlying system socket() call. Therefore,

sock = socket.socket(
    socket.AF_INET,
    socket.SOCK_STREAM | socket.SOCK_NONBLOCK)

는 여전히 SOCK_NONBLOCK를 지원하는 OS에서 비 블로킹 소켓을 만들지만, sock.type은 socket.SOCK_STREAM로 설정됩니다.

socket.socketpair([family[, type[, proto]]])

제공된 주소 패밀리, 소켓 유형 및 프로토콜 번호를 사용하여 연결된 소켓 객체 쌍을 만듭니다. 주소 패밀리, 소켓 유형 및 프로토콜 번호는 위의 socket() 함수와 같습니다. 플랫폼에서 정의되어 있으면 기본 패밀리는 AF_UNIX입니다; 그렇지 않으면 기본값은 AF_INET입니다.

새로 만들어진 소켓은 상속 불가능합니다.

버전 3.2에서 변경: 반환된 소켓 객체는 이제 부분 집합이 아닌 전체 소켓 API를 지원합니다.

버전 3.4에서 변경: 반환된 소켓은 이제 상속 불가능합니다.

버전 3.5에서 변경: 윈도우 지원이 추가되었습니다.

socket.create_connection(address[, timeout[, source_address]])

인터넷 address(2-튜플 (host, port))에서 리스닝하는 TCP 서비스에 연결하고 소켓 객체를 반환합니다. 이것은 socket.connect() 보다 고수준 함수입니다: host가 숫자가 아닌 호스트 명이면, AF_INET과 AF_INET6 모두로 결정하려고 시도한 다음, 연결이 성공할 때까지 차례대로 모든 가능한 주소로 연결을 시도합니다. 이것은 IPv4 및 IPv6 모두에 호환되는 클라이언트를 쉽게 작성할 수 있도록 합니다.

선택적 timeout 매개 변수를 전달하면 연결을 시도하기 전에 소켓 인스턴스의 시간제한을 설정합니다. timeout이 제공되지 않으면, getdefaulttimeout()에 의해 반환된 전역 기본 시간제한 설정이 사용됩니다.

제공되면, source_address는 연결하기 전에 소켓이 소스 주소로 바인드 할 2-튜플 (host, port) 여야 합니다. 호스트나 포트가 각각 ‘’ 나 0이면 OS 기본 동작이 사용됩니다.

버전 3.2에서 변경: source_address가 추가되었습니다.

socket.fromfd(fd, family, type, proto=0)

파일 기술자 fd(파일 객체의 fileno() 메서드에서 반환된 정수)를 복제하고 결과로 소켓 객체를 만듭니다. 주소 패밀리, 소켓 유형 및 프로토콜 번호는 위의 socket() 함수와 같습니다. 파일 기술자는 소켓을 참조해야 하지만, 검사하지는 않습니다 — 파일 기술자가 유효하지 않으면 객체에 대한 후속 연산이 실패할 수 있습니다. 이 함수는 거의 필요하지 않지만, 프로그램에 표준 입력이나 출력으로 프로그램에 전달된 (가령 유닉스 inet 데몬으로 시작한 서버) 소켓의 소켓 옵션을 가져오거나 설정하는 데 사용할 수 있습니다. 소켓은 블로킹 모드로 간주합니다.

새로 만들어진 소켓은 상속 불가능합니다.

버전 3.4에서 변경: 반환된 소켓은 이제 상속 불가능합니다.

socket.fromshare(data)

socket.share() 메서드에서 얻은 데이터로 소켓의 인스턴스를 만듭니다. 소켓은 블로킹 모드로 간주합니다.

가용성: 윈도우.

버전 3.3에 추가.

socket.SocketType

이것은 소켓 객체 형을 나타내는 파이썬 형 객체입니다. type(socket(...))과 같습니다.

기타 함수

socket 모듈은 또한 다양한 네트워크 관련 서비스를 제공합니다:

socket.close(fd)

소켓 파일 기술자를 닫습니다. 이것은 os.close()와 비슷하지만, 소켓 용입니다. 일부 플랫폼(가장 눈에 띄는 것은 윈도우)에서는 os.close()가 소켓 파일 기술자에 대해 작동하지 않습니다.

버전 3.7에 추가.

socket.getaddrinfo(host, port, family=0, type=0, proto=0, flags=0)

host/port 인자를 해당 서비스에 연결된 소켓을 만드는 데 필요한 모든 인자가 들어있는 5-튜플의 시퀀스로 변환합니다. host는 도메인 이름, IPv4/v6 주소의 문자열 표현 또는 None``입니다. *port*\는 ``'http'와 같은 문자열 서비스 이름, 숫자 포트 번호 또는 None``입니다. ``None을 host 와 port의 값으로 전달해서, NULL을 하부 C API에 전달할 수 있습니다.

family, type 및 proto 인자는 선택적으로 지정되어 반환된 주소 목록을 축소합니다. 이 인자 각각에 대한 값으로 0을 전달하면 전체 결과 범위가 선택됩니다. flags 인자는 AI_* 상수 중 하나 또는 여러 개일 수 있으며, 결과가 계산되고 반환되는 방식에 영향을 줍니다. 예를 들어, AI_NUMERICHOST는 도메인 이름 결정을 비활성화하고, host가 도메인 이름이면 에러를 발생시킵니다.

이 함수는 다음과 같은 구조의 5-튜플의 리스트를 반환합니다:

(family, type, proto, canonname, sockaddr)

이 튜플에서, family, type, proto는 모두 정수이며 socket() 함수로 전달됩니다. canonname은 AI_CANONNAME가 flags 인자의 일부일 때 host의 규범적(canonical) 이름을 나타내는 문자열입니다; 그렇지 않으면 canonname가 비어 있습니다. sockaddr은 반환된 family에 따라 형식이 달라지는, 소켓 주소를 설명하는 튜플이며 (AF_INET이면 (address, port) 2-튜플, AF_INET6이면 (address, port, flow info, scope id) 4-튜플), socket.connect() 메서드로 전달됩니다.

다음 예제는 example.org의 포트 80으로 가는 가상의 TCP 연결에 대한 주소 정보를 가져옵니다 (IPv6가 활성화되지 않았으면 여러분의 시스템에서는 결과가 다를 수 있습니다):

>>> socket.getaddrinfo("example.org", 80, proto=socket.IPPROTO_TCP)
[(<AddressFamily.AF_INET6: 10>, <SocketType.SOCK_STREAM: 1>,
 6, '', ('2606:2800:220:1:248:1893:25c8:1946', 80, 0, 0)),
 (<AddressFamily.AF_INET: 2>, <SocketType.SOCK_STREAM: 1>,
 6, '', ('93.184.216.34', 80))]

버전 3.2에서 변경: 매개 변수는 이제 키워드 인자를 사용하여 전달할 수 있습니다.

버전 3.7에서 변경: IPv6 멀티캐스트 주소의 경우, 주소를 나타내는 문자열에는 %scope 부분이 포함되지 않습니다.

socket.getfqdn([name])

name의 완전히 정규화된 도메인 이름을 반환합니다. name이 생략되거나 비어 있으면, 지역 호스트로 해석됩니다. 완전히 정규화된 이름을 찾기 위해, gethostbyaddr()에 의해 반환된 호스트 이름이 검사되고, 있다면 그 호스트의 별칭이 뒤따릅니다. 마침표가 포함된 첫 번째 이름이 선택됩니다. 완전히 정규화된 도메인 이름이 없으면, gethostname()에서 반환된 호스트 이름이 반환됩니다.

socket.gethostbyname(hostname)

호스트 이름을 IPv4 주소 형식으로 변환합니다. IPv4 주소는 '100.50.200.5'와 같은 문자열로 반환됩니다. 호스트 이름이 IPv4 주소면 변경되지 않고 반환됩니다. 더욱 완전한 인터페이스는 gethostbyname_ex()를 참조하십시오. gethostbyname()는 IPv6 이름 결정을 지원하지 않으며, IPv4/v6 이중 스택 지원을 위해서는 대신 getaddrinfo()를 사용해야 합니다.

socket.gethostbyname_ex(hostname)

호스트 이름을 IPv4 주소 형식으로 변환합니다, 확장 인터페이스. 트리플 (hostname, aliaslist, ipaddrlist)를 반환합니다. 여기서 hostname은 지정된 ip_address에 응답하는 기본 호스트 이름이고, aliaslist는 같은 주소에 대한 대안 호스트 이름의 리스트(비어있을 수 있습니다)이며, ipaddrlist는 같은 호스트의 같은 인터페이스에 대한 IPv4 주소 리스트입니다 (항상 그렇지는 않지만, 종종 단일 주소). gethostbyname_ex()는 IPv6 이름 결정을 지원하지 않으며, IPv4/v6 이중 스택 지원을 위해서는 대신 getaddrinfo()를 사용해야 합니다.

socket.gethostname()

파이썬 인터프리터가 현재 실행 중인 기계의 호스트 명을 포함한 문자열을 반환합니다.

참고: gethostname()은 항상 완전히 정규화된 도메인 이름을 반환하지는 않습니다; 원한다면 getfqdn()을 사용하십시오.

socket.gethostbyaddr(ip_address)

트리플 (hostname, aliaslist, ipaddrlist)를 반환합니다. 여기서 hostname는 지정된 ip_address에 응답하는 기본 호스트 이름이고, aliaslist는 같은 주소에 대한 대체 호스트 이름의 (비어있을 수 있는) 리스트이며, ipaddrlist는 같은 호스트의 같은 인터페이스에 대한 IPv4/v6 주소 리스트입니다 (대개 단일 주소만 포함합니다). 완전히 정규화된 도메인 이름을 찾으려면, getfqdn() 함수를 사용하십시오. gethostbyaddr()는 IPv4와 IPv6를 모두 지원합니다.

socket.getnameinfo(sockaddr, flags)

소켓 주소 sockaddr를 2-튜플 (host, port)로 변환합니다. flags의 설정에 따라, 결과의 host에 완전히 정규화된 도메인 이름이나 숫자 주소 표현이 포함될 수 있습니다. 마찬가지로, port에는 문자열 포트 이름이나 숫자 포트 번호가 포함될 수 있습니다.

IPv6 주소의 경우, sockaddr에 의미 있는 scopeid가 있으면 %scope를 host 부분에 덧붙입니다. 보통 이것은 멀티캐스트 주소에서 일어납니다.

socket.getprotobyname(protocolname)

인터넷 프로토콜 이름(예를 들어, 'icmp')을 socket() 함수의 (선택적인) 세 번째 인자로 전달하기에 적합한 상수로 변환합니다. 이것은 일반적으로 “원시” 모드(SOCK_RAW)로 열린 소켓에만 필요합니다; 일반 소켓 모드에서는, 프로토콜이 생략되거나 0이면 올바른 프로토콜이 자동으로 선택됩니다.

socket.getservbyname(servicename[, protocolname])

인터넷 서비스 이름과 프로토콜 이름을 해당 서비스의 포트 번호로 변환합니다. 선택적 프로토콜 이름은, 주어진다면, 'tcp' 나 'udp' 여야 합니다, 그렇지 않으면 모든 프로토콜과 일치합니다.

socket.getservbyport(port[, protocolname])

인터넷 포트 번호와 프로토콜 이름을 해당 서비스의 서비스 이름으로 변환합니다. 선택적 프로토콜 이름은, 주어진다면, 'tcp' 나 'udp' 여야 합니다, 그렇지 않으면 모든 프로토콜과 일치합니다.

socket.ntohl(x)

32비트 양의 정수를 네트워크 바이트 순서에서 호스트 바이트 순서로 변환합니다. 호스트 바이트 순서가 네트워크 바이트 순서와 같은 시스템에서, 이것은 아무 일도 하지 않습니다; 그렇지 않으면, 4바이트 스와프 연산을 수행합니다.

socket.ntohs(x)

16비트 양의 정수를 네트워크 바이트 순서에서 호스트 바이트 순서로 변환합니다. 호스트 바이트 순서가 네트워크 바이트 순서와 같은 시스템에서, 이것은 아무 일도 하지 않습니다; 그렇지 않으면, 2바이트 스와프 연산을 수행합니다.

버전 3.7부터 폐지: x가 16비트 부호 없는 정수에 맞지 않지만, 양의 C int에 맞으면, 16비트 부호 없는 정수로 자동 절단됩니다. 이 자동 절단 기능은 폐지되었으며, 미래 버전의 파이썬에서는 예외가 발생할 것입니다.

socket.htonl(x)

32비트 양의 정수를 호스트 바이트 순서에서 네트워크 바이트 순서로 변환합니다. 호스트 바이트 순서가 네트워크 바이트 순서와 같은 시스템에서, 이것은 아무 일도 하지 않습니다; 그렇지 않으면, 4바이트 스와프 연산을 수행합니다.

socket.htons(x)

16비트 양의 정수를 호스트 바이트 순서에서 네트워크 바이트 순서로 변환합니다. 호스트 바이트 순서가 네트워크 바이트 순서와 같은 시스템에서, 이것은 아무 일도 하지 않습니다; 그렇지 않으면, 2바이트 스와프 연산을 수행합니다.

버전 3.7부터 폐지: x가 16비트 부호 없는 정수에 맞지 않지만, 양의 C int에 맞으면, 16비트 부호 없는 정수로 자동 절단됩니다. 이 자동 절단 기능은 폐지되었으며, 미래 버전의 파이썬에서는 예외가 발생할 것입니다.

socket.inet_aton(ip_string)

IPv4 주소를 점 분리 쿼드 문자열 형식(예를 들어, ‘123.45.67.89’)에서 길이가 4자인 바이트열 객체로 32비트 압축 바이너리 형식으로 변환합니다. 이 함수는 표준 C 라이브러리를 사용하고 struct in_addr 형(이 함수가 반환하는 32비트 압축 바이너리의 C형입니다)의 객체를 요구하는 프로그램과 대화할 때 유용합니다.

inet_aton()는 3점 미만의 문자열도 허용합니다; 자세한 내용은 유닉스 매뉴얼 페이지 inet(3)을 참조하십시오.

이 함수에 전달된 IPv4 주소 문자열이 유효하지 않으면, OSError가 발생합니다. 정확히 무엇이 유효한지는 inet_aton()의 하부 C 구현에 따라 달라짐에 유의하십시오.

inet_aton()은 IPv6를 지원하지 않으며, IPv4/v6 이중 스택 지원을 위해서는 대신 inet_pton()를 사용해야 합니다.

socket.inet_ntoa(packed_ip)

32비트 압축 IPv4 주소(길이가 4바이트인 바이트열 객체)를 표준 점선 분리 쿼드 문자열 표현(예를 들어, ‘123.45.67.89’)으로 변환합니다. 이 함수는 표준 C 라이브러리를 사용하고 struct in_addr 형(이 함수가 인자로 받아들이는 32비트 압축 바이너리 데이터의 C형입니다)의 객체를 요구하는 프로그램과 대화할 때 유용합니다.

이 함수에 전달된 바이트 시퀀스가 정확히 4바이트 길이가 아니면, OSError가 발생합니다. inet_ntoa()는 IPv6를 지원하지 않으며, IPv4/v6 이중 스택 지원을 위해서는 대신 inet_ntop()를 사용해야 합니다.

버전 3.5에서 변경: 이제 쓰기 가능한 바이트열류 객체를 받아들입니다.

socket.inet_pton(address_family, ip_string)

패밀리 특정 문자열 형식의 IP 주소를 압축 바이너리 형식으로 변환합니다. inet_pton()는 라이브러리나 네트워크 프로토콜이 struct in_addr 형(inet_aton()과 유사)이나 struct in6_addr 형의 객체로 호출할 때 유용합니다.

address_family에 대해 지원되는 값은 현재 AF_INET과 AF_INET6입니다. IP 주소 문자열 ip_string가 유효하지 않으면, OSError가 발생합니다. 정확히 무엇이 유효한지는 address_family의 값과 inet_pton()의 하부 구현에 따라 달라집니다.

가용성: 유닉스(모든 플랫폼이 아닐 수도 있음), 윈도우.

버전 3.4에서 변경: 윈도우 지원이 추가되었습니다

socket.inet_ntop(address_family, packed_ip)

압축 IP 주소(일정 길이의 바이트열 객체)를 그것의 표준 패밀리 특정 문자열 표현(예를 들어, '7.10.0.5' 나 '5aef:2b::8')으로 변환합니다. inet_ntop()는 라이브러리나 네트워크 프로토콜이 struct in_addr 형(inet_ntoa()와 유사)이나 struct in6_addr 형의 객체를 반환할 때 유용합니다.

address_family에 대해 지원되는 값은 현재 AF_INET과 AF_INET6입니다. 바이트열 객체 packed_ip가 지정된 주소 패밀리의 올바른 길이가 아니면, ValueError가 발생합니다. inet_ntop() 호출로 인한 에러에는 OSError가 발생합니다.

가용성: 유닉스(모든 플랫폼이 아닐 수도 있음), 윈도우.

버전 3.4에서 변경: 윈도우 지원이 추가되었습니다

버전 3.5에서 변경: 이제 쓰기 가능한 바이트열류 객체를 받아들입니다.

socket.CMSG_LEN(length)

주어진 length의 연관된 데이터가 있는 보조(ancillary) 데이터 항목의 (후행 패딩을 제외한) 총 길이를 반환합니다. 이 값은 recvmsg()가 보조 데이터의 단일 항목을 수신하기 위한 버퍼 크기로 종종 사용될 수 있지만, RFC 3542 [https://tools.ietf.org/html/rfc3542.html]는 이식성 있는 응용 프로그램에서 CMSG_SPACE()를 사용하도록 요구하는데, 항목이 버퍼의 마지막 부분일 때도 패딩을 위한 공간을 포함합니다. length가 허용되는 값 범위를 벗어나면 OverflowError를 발생시킵니다.

가용성: 대부분 유닉스 플랫폼, 다른 것들도 가능합니다.

버전 3.3에 추가.

socket.CMSG_SPACE(length)

주어진 length의 연관된 데이터가 있는 보조(ancillary) 데이터 항목을 수신하기 위해 recvmsg()에 필요한 버퍼 크기를 반환하는데, 후행 패딩을 포함합니다. 여러 항목을 수신하는 데 필요한 버퍼 공간은 연관된 데이터 길이에 대한 CMSG_SPACE() 값의 합입니다. length가 허용되는 값 범위를 벗어나면 OverflowError를 발생시킵니다.

일부 시스템에서는 이 함수를 제공하지 않으면서 보조(ancillary) 데이터를 지원할 수 있음에 유의하십시오. 또한, 이 함수의 결과를 사용하여 버퍼 크기를 설정하면 수신할 수 있는 보조 데이터의 양이 정확하게 제한되지 않을 수 있음에도 유의하십시오. 추가 데이터가 패딩 영역에 들어갈 수 있기 때문입니다.

가용성: 대부분 유닉스 플랫폼, 다른 것들도 가능합니다.

버전 3.3에 추가.

socket.getdefaulttimeout()

새로운 소켓 객체의 기본 시간제한을 초 단위로 (float) 반환합니다. None 값은 새 소켓 객체가 시간제한이 없음을 나타냅니다. 소켓 모듈을 처음 임포트 할 때 기본값은 None입니다.

socket.setdefaulttimeout(timeout)

새 소켓 객체의 기본 시간제한을 초 단위로 (float) 설정합니다. 소켓 모듈을 처음 임포트 할 때 기본값은 None입니다. 가능한 값과 해당 의미는 settimeout()을 참조하십시오.

socket.sethostname(name)

기계의 호스트 명을 name으로 설정합니다. 충분한 권한이 없으면 OSError가 발생합니다.

가용성: 유닉스.

버전 3.3에 추가.

socket.if_nameindex()

네트워크 인터페이스 정보 (인덱스 정수, 이름 문자열) 튜플의 리스트를 반환합니다. 시스템 호출이 실패하면 OSError.

가용성: 유닉스.

버전 3.3에 추가.

socket.if_nametoindex(if_name)

인터페이스 이름에 대응하는 네트워크 인터페이스 인덱스 번호를 반환합니다. 주어진 이름을 가진 인터페이스가 없으면 OSError.

가용성: 유닉스.

버전 3.3에 추가.

socket.if_indextoname(if_index)

인터페이스 인덱스 번호에 해당하는 네트워크 인터페이스 이름을 반환합니다. 지정된 인덱스의 인터페이스가 없으면 OSError.

가용성: 유닉스.

버전 3.3에 추가.

소켓 객체

소켓 객체에는 다음과 같은 메서드가 있습니다. makefile()를 제외하고, 이것들은 소켓에 적용할 수 있는 유닉스 시스템 호출에 해당합니다.

버전 3.2에서 변경: 컨텍스트 관리자 프로토콜 지원이 추가되었습니다. 컨텍스트 관리자를 빠져나가는 것은 close()를 호출하는 것과 동등합니다.

socket.accept()

연결을 받아들입니다. 소켓은 주소에 바인드되어 연결을 리스닝하고 있어야 합니다. 반환 값은 (conn, address) 쌍입니다. 여기서 conn는 연결에서 데이터를 보내고 받을 수 있는 새로운 소켓 객체이고, address는 연결의 다른 끝에 있는 소켓에 바인드 된 주소입니다.

새로 만들어진 소켓은 상속 불가능합니다.

버전 3.4에서 변경: 소켓은 이제 상속 불가능합니다.

버전 3.5에서 변경: 시스템 호출이 인터럽트 되고 시그널 처리기가 예외를 발생시키지 않으면, 메서드는 이제 InterruptedError 예외를 발생시키는 대신 시스템 호출을 재시도합니다 (이유는 PEP 475 [https://www.python.org/dev/peps/pep-0475]를 참조하십시오).

socket.bind(address)

소켓을 address에 바인드 합니다. 소켓은 이미 바인드 되어 있으면 안 됩니다. (address의 형식은 주소 패밀리에 따라 다릅니다 — 위를 보십시오.)

socket.close()

소켓을 닫힌 상태로 표시합니다. 하부 시스템 자원(예를 들어, 파일 기술자)도 makefile()로 만든 모든 파일 객체가 닫힐 때 닫힙니다. 일단 닫히면, 소켓 객체에 대한 이후의 모든 연산이 실패합니다. 원격 끝은 더는 데이터를 수신하지 않게 됩니다 (계류 중인 데이터가 플러시 된 후에).

소켓은 가비지 수집될 때 자동으로 닫히지만, 명시적으로 close()하거나 with 문을 사용하는 것이 좋습니다.

버전 3.6에서 변경: 하부 close() 호출이 수행될 때 에러가 발생하면 이제 OSError가 발생합니다.

참고

close()는 연결과 관련된 자원을 해제하지만, 반드시 연결을 즉시 닫을 필요는 없습니다. 적시에 연결을 닫으려면, close() 전에 shutdown()을 호출하십시오.

socket.connect(address)

address에 있는 원격 소켓에 연결합니다. (address의 형식은 주소 패밀리에 따라 다릅니다 — 위를 보십시오.)

시그널로 연결이 인터럽트 되면, 메서드는 연결이 완료될 때까지 대기하거나, 시그널 처리기가 예외를 발생시키지 않고 소켓이 블로킹하거나 시간제한이 있으면 socket.timeout을 발생시킵니다. 비 블로킹 소켓의 경우, 이 메서드는 시그널로 연결이 인터럽트 되면 InterruptedError 예외(또는 시그널 처리기에서 발생한 예외)를 발생시킵니다.

버전 3.5에서 변경: 연결이 시그널에 의해 인터럽트 되고, 시그널 처리기가 예외를 발생시키지 않고, 소켓이 블로킹하거나 시간제한을 가지면, 이 메서드는 이제 InterruptedError 예외를 발생시키는 대신 연결이 완료될 때까지 대기합니다 (이유는 PEP 475 [https://www.python.org/dev/peps/pep-0475]를 참조하십시오).

socket.connect_ex(address)

connect(address)와 비슷하지만, C 수준의 connect() 호출로 반환된 에러에 대한 예외를 발생시키는 대신 에러 표시기를 반환합니다 (“호스트를 찾을 수 없음”과 같은 다른 문제는 여전히 예외를 발생시킬 수 있습니다). 연산이 성공하면 에러 표시기는 0이고, 그렇지 않으면 errno 변수의 값입니다. 예를 들어 비동기 연결을 지원하는 데 유용합니다.

socket.detach()

하부 파일 기술자를 실제로 닫지 않으면서 소켓 객체를 닫힌 상태로 만듭니다. 파일 기술자가 반환되고, 다른 용도로 재사용 될 수 있습니다.

버전 3.2에 추가.

socket.dup()

소켓을 복제합니다.

새로 만들어진 소켓은 상속 불가능합니다.

버전 3.4에서 변경: 소켓은 이제 상속 불가능합니다.

socket.fileno()

소켓의 파일 기술자(작은 정수)를 반환하거나, 실패하면 -1을 반환합니다. 이것은 select.select()에서 유용합니다.

윈도우에서, 이 메서드가 돌려주는 작은 정수는 파일 기술자를 사용할 수 있는 곳(가령 os.fdopen())에 사용할 수 없습니다. 유닉스에는 이러한 제한이 없습니다.

socket.get_inheritable()

소켓의 파일 기술자나 소켓 핸들의 상속 가능 플래그를 가져옵니다: 소켓이 자식 프로세스에서 상속될 수 있으면 True, 그렇지 않으면 False.

버전 3.4에 추가.

socket.getpeername()

소켓이 연결된 원격 주소를 반환합니다. 이것은 예를 들어, 원격 IPv4/v6 소켓의 포트 번호를 찾는 데 유용합니다. (반환되는 주소의 형식은 주소 패밀리에 따라 다릅니다 — 위를 보십시오.) 일부 시스템에서는 이 함수가 지원되지 않습니다.

socket.getsockname()

소켓 자신의 주소를 반환합니다. 이것은 예를 들어 IPv4/v6 소켓의 포트 번호를 찾는 데 유용합니다. (반환되는 주소의 형식은 주소 패밀리에 따라 다릅니다 — 위를 보십시오.)

socket.getsockopt(level, optname[, buflen])

주어진 소켓 옵션의 값을 반환합니다 (유닉스 매뉴얼 페이지 getsockopt(2)를 보십시오). 필요한 기호 상수(SO_* 등)는 이 모듈에서 정의됩니다. buflen이 없으면, 정수 옵션을 가정하고 해당 정숫값이 함수에서 반환됩니다. buflen이 있으면, 옵션을 수신하는 데 사용되는 버퍼의 최대 길이를 지정하고, 이 버퍼가 바이트열 객체로 반환됩니다. 버퍼의 내용을 디코딩하는 것은 호출자의 책임입니다 (바이트열로 인코딩된 C 구조체를 디코딩하는 방법은 선택적 내장 모듈 struct를 참조하십시오).

socket.getblocking()

소켓이 블로킹 모드면 True를 반환하고, 비 블로킹이면 False를 반환합니다.

이것은 socket.gettimeout() == 0를 검사하는 것과 동등합니다.

버전 3.7에 추가.

socket.gettimeout()

소켓 연산에 관련한 시간제한을 초(float)로 돌려줍니다. 시간제한이 설정되어 있지 않으면 None를 돌려줍니다. 이것은 setblocking() 이나 settimeout()에 대한 마지막 호출을 반영합니다.

socket.ioctl(control, option)

플랫폼

윈도우

ioctl() 메서드는 WSAIoctl 시스템 인터페이스에 대한 제한된 인터페이스입니다. 자세한 내용은 Win32 설명서 [https://msdn.microsoft.com/en-us/library/ms741621%28VS.85%29.aspx]를 참조하십시오.

다른 플랫폼에서는, 범용 fcntl.fcntl() 과 fcntl.ioctl() 함수를 사용할 수 있습니다; 첫 번째 인자로 소켓 객체를 받아들입니다.

현재 다음 제어 코드만 지원됩니다: SIO_RCVALL, SIO_KEEPALIVE_VALS 및 SIO_LOOPBACK_FAST_PATH.

버전 3.6에서 변경: SIO_LOOPBACK_FAST_PATH가 추가되었습니다.

socket.listen([backlog])

서버가 연결을 수락하도록 합니다. backlog가 지정되면, 0 이상이어야 합니다 (더 낮으면 0으로 설정됩니다); 새로운 연결을 거부하기 전에 시스템이 허락할 수락되지 않은 연결 수를 지정합니다. 지정하지 않으면, 기본값으로 적당한 값이 선택됩니다.

버전 3.5에서 변경: 이제 backlog 매개 변수가 선택적입니다.

socket.makefile(mode='r', buffering=None, *, encoding=None, errors=None, newline=None)

소켓과 결합한 파일 객체를 돌려줍니다. 정확한 반환형은 makefile()에 주어진 인자에 따라 다릅니다. 이 인자는 내장 open() 함수와 같은 방식으로 해석됩니다. 단, 지원되는 mode 값은 'r' (기본값), 'w' 및 'b' 뿐입니다.

소켓은 블로킹 모드 여야 합니다; 시간제한을 가질 수 있지만, 시간 초과가 발생하면 파일 객체의 내부 버퍼가 일관성없는 상태로 끝날 수 있습니다.

makefile()에 의해 반환된 파일 객체를 닫는 것은, 다른 모든 파일 객체가 닫혔고 소켓 객체에서 socket.close()가 호출되었지 않은 한 원래 소켓을 닫지는 않습니다.

참고

윈도우에서, makefile()로 만든 파일류 객체는 파일 기술자가 있는 파일 객체가 필요한 곳에서는 사용할 수 없습니다, 가령 subprocess.Popen()의 stream 인자.

socket.recv(bufsize[, flags])

소켓에서 데이터를 수신합니다. 반환 값은 수신된 데이터를 나타내는 바이트열 객체입니다. 한 번에 수신할 수 있는 최대 데이터양은 bufsize에 의해 지정됩니다. 선택적 인자 flags의 의미는 유닉스 매뉴얼 페이지 recv(2)를 보십시오; 기본값은 0입니다.

참고

하드웨어와 네트워크 현실과 가장 잘 일치하려면, bufsize의 값은 2의 비교적 작은 거듭제곱이어야 합니다, 예를 들어 4096.

버전 3.5에서 변경: 시스템 호출이 인터럽트 되고 시그널 처리기가 예외를 발생시키지 않으면, 메서드는 이제 InterruptedError 예외를 발생시키는 대신 시스템 호출을 재시도합니다 (이유는 PEP 475 [https://www.python.org/dev/peps/pep-0475]를 참조하십시오).

socket.recvfrom(bufsize[, flags])

소켓에서 데이터를 수신합니다. 반환 값은 (bytes, address) 쌍입니다. 여기서 bytes는 수신한 데이터를 나타내는 바이트열 객체이고, address는 데이터를 보내는 소켓의 주소입니다. 선택적 인자 flags의 의미는 유닉스 매뉴얼 페이지 recv(2)를 보십시오; 기본값은 0입니다. (address의 형식은 주소 패밀리에 따라 다릅니다 — 위를 보십시오.)

버전 3.5에서 변경: 시스템 호출이 인터럽트 되고 시그널 처리기가 예외를 발생시키지 않으면, 메서드는 이제 InterruptedError 예외를 발생시키는 대신 시스템 호출을 재시도합니다 (이유는 PEP 475 [https://www.python.org/dev/peps/pep-0475]를 참조하십시오).

버전 3.7에서 변경: 멀티캐스트 IPv6 주소의 경우, address의 첫 번째 항목에는 %scope 부분이 더는 포함되지 않습니다. 전체 IPv6 주소를 얻으려면 getnameinfo()를 사용하십시오.

socket.recvmsg(bufsize[, ancbufsize[, flags]])

일반 데이터(최대 bufsize 바이트)와 보조(ancillary) 데이터를 소켓에서 수신합니다. ancbufsize 인자는 보조 데이터 수신에 사용되는 내부 버퍼의 크기를 바이트 단위로 설정합니다; 기본값은 0이며 보조 데이터가 수신되지 않는다는 뜻입니다. 보조 데이터를 위한 적절한 버퍼 크기는 CMSG_SPACE() 나 CMSG_LEN()를 사용하여 계산할 수 있으며, 버퍼에 들어가지 않는 항목은 잘리거나 삭제될 수 있습니다. flags 인자의 기본값은 0이고 recv()와 같은 의미입니다.

반환 값은 4-튜플입니다: (data, ancdata, msg_flags, address). data 항목은 일반 데이터를 담은 bytes 객체입니다. ancdata 항목은 수신된 보조 데이터(제어 메시지)를 나타내는 0개 이상의 튜플 (cmsg_level, cmsg_type, cmsg_data)의 리스트입니다: cmsg_level 와 cmsg_type는 각각 프로토콜 수준과 프로토콜 특정 형을 지정하는 정수이고, cmsg_data는 연결된 데이터를 담은 bytes 객체입니다. msg_flags 항목은 수신된 메시지의 조건을 나타내는 다양한 플래그의 비트별 OR입니다; 자세한 내용은 시스템 설명서를 참조하십시오. 수신 소켓이 연결되어있지 않으면, address는 송신 소켓의 주소입니다, (사용 가능하다면); 그렇지 않으면 값은 지정되지 않습니다.

일부 시스템에서는, sendmsg()와 recvmsg()를 사용하여 AF_UNIX 소켓을 통해 프로세스 간에 파일 기술자를 전달할 수 있습니다. 이 기능을 사용하면 (SOCK_STREAM 소켓으로 제한되는 경우가 많습니다), recvmsg()는 보조 데이터에서 (socket.SOL_SOCKET, socket.SCM_RIGHTS, fds) 형식의 항목을 반환합니다. 여기서 fds는 새 파일 기술자를 네이티브 C int 형의 바이너리 배열로 나타내는 bytes 객체입니다. recvmsg()가 시스템 호출이 반환된 후에 예외를 발생시키면, 먼저 이 메커니즘을 통해 수신된 모든 파일 기술자를 닫으려고 시도합니다.

일부 시스템은 부분적으로만 수신된 보조 데이터 항목의 절단 길이를 나타내지 않습니다. 항목이 버퍼의 끝을 넘어 확장된 것처럼 보이면, recvmsg()는 RuntimeWarning를 발생시키고, 관련 데이터의 시작 전에 절단되지 않은 버퍼 내에 있는 부분을 반환합니다.

SCM_RIGHTS 메커니즘을 지원하는 시스템에서, 다음 함수는 최대 maxfds 파일 기술자를 수신하여, 메시지 데이터와 기술자를 담은 리스트를 반환합니다 (관련 없는 수신되는 제어 메시지와 같은 예기치 않은 조건은 무시하면서). sendmsg()를 참조하십시오.

import socket, array

def recv_fds(sock, msglen, maxfds):
    fds = array.array("i")   # Array of ints
    msg, ancdata, flags, addr = sock.recvmsg(msglen, socket.CMSG_LEN(maxfds * fds.itemsize))
    for cmsg_level, cmsg_type, cmsg_data in ancdata:
        if cmsg_level == socket.SOL_SOCKET and cmsg_type == socket.SCM_RIGHTS:
            # Append data, ignoring any truncated integers at the end.
            fds.frombytes(cmsg_data[:len(cmsg_data) - (len(cmsg_data) % fds.itemsize)])
    return msg, list(fds)

가용성: 대부분 유닉스 플랫폼, 다른 것들도 가능합니다.

버전 3.3에 추가.

버전 3.5에서 변경: 시스템 호출이 인터럽트 되고 시그널 처리기가 예외를 발생시키지 않으면, 메서드는 이제 InterruptedError 예외를 발생시키는 대신 시스템 호출을 재시도합니다 (이유는 PEP 475 [https://www.python.org/dev/peps/pep-0475]를 참조하십시오).

socket.recvmsg_into(buffers[, ancbufsize[, flags]])

recvmsg()처럼 동작해서, 일반 데이터와 보조 데이터를 소켓에서 수신하지만, 새로운 바이트열 객체를 반환하는 대신 일반 데이터를 일련의 버퍼로 분산시킵니다. buffers 인자는 쓰기 가능한 버퍼(예를 들어, bytearray 객체)를 내보내는 객체의 이터러블이어야 합니다; 이것들은 모두 기록되었거나 버퍼가 더는 없을 때까지 일반 데이터의 연속적인 덩어리로 채워질 것입니다. 운영 체제는 사용할 수 있는 버퍼 수에 제한(sysconf() 값 SC_IOV_MAX)을 설정할 수 있습니다. ancbufsize 와 flags 인자는 recvmsg()와 같은 의미가 있습니다.

반환 값은 4-튜플입니다: (nbytes, ancdata, msg_flags, address). 여기서 nbytes는 버퍼에 기록된 일반 데이터의 총 바이트 수이며, ancdata, msg_flags 및 address는 recvmsg()와 같습니다.

예제:

>>> import socket
>>> s1, s2 = socket.socketpair()
>>> b1 = bytearray(b'----')
>>> b2 = bytearray(b'0123456789')
>>> b3 = bytearray(b'--------------')
>>> s1.send(b'Mary had a little lamb')
22
>>> s2.recvmsg_into([b1, memoryview(b2)[2:9], b3])
(22, [], 0, None)
>>> [b1, b2, b3]
[bytearray(b'Mary'), bytearray(b'01 had a 9'), bytearray(b'little lamb---')]

가용성: 대부분 유닉스 플랫폼, 다른 것들도 가능합니다.

버전 3.3에 추가.

socket.recvfrom_into(buffer[, nbytes[, flags]])

소켓에서 데이터를 수신하는데, 새로운 바이트열을 만드는 대신 buffer에 씁니다. 반환 값은 쌍 (nbytes, address)입니다. 여기서 nbytes는 수신 된 바이트 수이고, address는 데이터를 보내는 소켓의 주소입니다. 선택적 인자 flags의 의미에 대해서는 유닉스 매뉴얼 페이지 recv(2)를 보십시오; 기본값은 0입니다. (address의 형식은 주소 패밀리에 따라 다릅니다 — 위를 보십시오.)

socket.recv_into(buffer[, nbytes[, flags]])

소켓에서 최대 nbytes 바이트까지 수신하는데, 새 바이트열을 만드는 대신 데이터를 버퍼에 저장합니다. nbytes가 지정되지 않으면 (또는 0), 지정된 버퍼에서 사용 가능한 크기까지 수신합니다. 수신 한 바이트 수를 반환합니다. 선택적 인자 flags의 의미에 대해서는 유닉스 매뉴얼 페이지 recv(2)를 보십시오; 기본값은 0입니다.

socket.send(bytes[, flags])

소켓에 데이터를 보냅니다. 소켓은 원격 소켓에 연결되어야 합니다. 선택적 flags 인자는 위의 recv()와 같은 의미입니다. 전송된 바이트 수를 반환합니다. 응용 프로그램은 모든 데이터가 전송되었는지 확인해야 합니다; 일부 데이터만 전송되었으면, 응용 프로그램은 나머지 데이터의 전달을 시도해야 합니다. 이 주제에 대한 자세한 정보는, 소켓 프로그래밍 HOWTO를 참조하십시오.

버전 3.5에서 변경: 시스템 호출이 인터럽트 되고 시그널 처리기가 예외를 발생시키지 않으면, 메서드는 이제 InterruptedError 예외를 발생시키는 대신 시스템 호출을 재시도합니다 (이유는 PEP 475 [https://www.python.org/dev/peps/pep-0475]를 참조하십시오).

socket.sendall(bytes[, flags])

소켓에 데이터를 보냅니다. 소켓은 원격 소켓에 연결되어야 합니다. 선택적 flags 인자는 위의 recv()와 같은 의미입니다. send()와 달리, 이 메서드는 모든 데이터가 전송되거나 에러가 발생할 때까지 bytes의 데이터를 계속 전송합니다. 성공하면 None이 반환됩니다. 에러가 발생하면, 예외가 발생하는데, 성공적으로 전송된 데이터양을 (있기는 하다면) 확인하는 방법은 없습니다.

버전 3.5에서 변경: 소켓 시간제한은 데이터가 성공적으로 전송될 때마다 더는 재설정되지 않습니다. 소켓 시간제한은 이제 모든 데이터를 전송할 수 있는 최대 총 지속 시간입니다.

버전 3.5에서 변경: 시스템 호출이 인터럽트 되고 시그널 처리기가 예외를 발생시키지 않으면, 메서드는 이제 InterruptedError 예외를 발생시키는 대신 시스템 호출을 재시도합니다 (이유는 PEP 475 [https://www.python.org/dev/peps/pep-0475]를 참조하십시오).

socket.sendto(bytes, address)

socket.sendto(bytes, flags, address)

소켓에 데이터를 보냅니다. 대상 소켓이 address로 지정되므로, 소켓은 원격 소켓에 연결되지 않아야 합니다. 선택적 flags 인자는 위의 recv()와 같은 의미가 있습니다. 전송된 바이트 수를 반환합니다. (address의 형식은 주소 패밀리에 따라 다릅니다 — 위를 보십시오.)

버전 3.5에서 변경: 시스템 호출이 인터럽트 되고 시그널 처리기가 예외를 발생시키지 않으면, 메서드는 이제 InterruptedError 예외를 발생시키는 대신 시스템 호출을 재시도합니다 (이유는 PEP 475 [https://www.python.org/dev/peps/pep-0475]를 참조하십시오).

socket.sendmsg(buffers[, ancdata[, flags[, address]]])

소켓에 일반과 보조 데이터를 보는데, 일련의 버퍼에서 일반 데이터를 모아서 단일 메시지로 연결합니다. buffers 인자는 일반 데이터를 바이트열류 객체의 이터러블로 지정합니다 (예를 들어, bytes 객체); 운영 체제는 사용할 수 있는 버퍼 수에 제한(sysconf() 값 SC_IOV_MAX)을 설정할 수 있습니다. ancdata 인자는 보조 데이터 (제어 메시지)를 0개 이상의 튜플 (cmsg_level, cmsg_type, cmsg_data)의 이터러블로 지정합니다. 여기서 cmsg_level 와 cmsg_type는 각각 프로토콜 수준과 프로토콜 특정 형을 지정하는 정수이고, cmsg_data는 연결된 데이터를 담은 바이트열류 객체입니다. 일부 시스템(특히, CMSG_SPACE()가 없는 시스템)은 호출 당 하나의 제어 메시지를 송신하는 것만 지원할 수 있습니다. flags 인자의 기본값은 0이고 send()와 같은 의미입니다. address가 제공되고 None이 아니면, 메시지의 대상 주소를 설정합니다. 반환 값은 전송된 일반 데이터의 바이트 수입니다.

다음 함수는 SCM_RIGHTS 메커니즘을 지원하는 시스템에서, AF_UNIX 소켓을 통해 파일 기술자 리스트 fds를 보냅니다. recvmsg()도 참조하세요.

import socket, array

def send_fds(sock, msg, fds):
    return sock.sendmsg([msg], [(socket.SOL_SOCKET, socket.SCM_RIGHTS, array.array("i", fds))])

가용성: 대부분 유닉스 플랫폼, 다른 것들도 가능합니다.

버전 3.3에 추가.

버전 3.5에서 변경: 시스템 호출이 인터럽트 되고 시그널 처리기가 예외를 발생시키지 않으면, 메서드는 이제 InterruptedError 예외를 발생시키는 대신 시스템 호출을 재시도합니다 (이유는 PEP 475 [https://www.python.org/dev/peps/pep-0475]를 참조하십시오).

socket.sendmsg_afalg([msg, ]*, op[, iv[, assoclen[, flags]]])

AF_ALG 소켓용, sendmsg()의 특수한 버전. AF_ALG 소켓에 대한 모드, IV, AEAD 관련 데이터 길이 및 플래그를 설정합니다.

가용성 : 리눅스 >= 2.6.38.

버전 3.6에 추가.

socket.sendfile(file, offset=0, count=None)

고성능 os.sendfile을 사용하여 EOF에 도달할 때까지 파일을 보내고, 보낸 총 바이트 수를 반환합니다. file은 바이너리 모드로 열린 일반 파일 객체여야 합니다. os.sendfile을 사용할 수 없거나 (예를 들어, 윈도우) file가 일반 파일이 아니면, send()가 대신 사용됩니다. offset은 파일 읽기 시작할 위치를 알려줍니다. 지정되면, count는 EOF에 도달할 때까지 파일을 전송하는 대신 전송할 총 바이트 수입니다. 파일 위치는 반환하거나 에러가 발생했을 때 갱신됩니다. 이때 file.tell()을 사용하여 전송된 바이트 수를 계산할 수 있습니다. 소켓은 SOCK_STREAM 유형이어야 합니다. 비 블로킹 소켓은 지원되지 않습니다.

버전 3.5에 추가.

socket.set_inheritable(inheritable)

소켓의 파일 기술자나 소켓 핸들의 상속 가능 플래그를 설정합니다.

버전 3.4에 추가.

socket.setblocking(flag)

소켓의 블로킹이나 비 블로킹 모드를 설정합니다. flag가 거짓이면, 소켓은 비 블로킹으로 설정되고, 그렇지 않으면 블로킹 모드로 설정됩니다.

이 메서드는 특정 settimeout() 호출의 줄인 표현입니다:

sock.setblocking(True)는 sock.settimeout(None)와 동등합니다

sock.setblocking(False)는 sock.settimeout(0.0)와 동등합니다

버전 3.7에서 변경: 이 메서드는 더는 socket.type에 SOCK_NONBLOCK 플래그를 적용하지 않습니다.

socket.settimeout(value)

블로킹 소켓 연산에 시간제한을 설정합니다. value 인자는 초로 표현된 음수가 아닌 부동 소수점 수나 None 일 수 있습니다. 0이 아닌 값을 주면, 후속 소켓 연산에서, 연산이 완료되기 전에 시간제한 기간 value가 지나면 timeout 예외를 발생시킵니다. 0을 지정하면, 소켓은 비 블로킹 모드가 됩니다. None이 주어지면, 소켓은 블로킹 모드가 됩니다.

자세한 내용은, 소켓 시간제한에 대한 참고 사항을 보십시오.

버전 3.7에서 변경: 이 메서드는 더는 socket.type의 SOCK_NONBLOCK 플래그를 토글하지 않습니다.

socket.setsockopt(level, optname, value: int)

socket.setsockopt(level, optname, value: buffer)

socket.setsockopt(level, optname, None, optlen: int)

Set the value of the given socket option (see the Unix manual page setsockopt(2)). The needed symbolic constants are defined in the socket module (SO_* etc.). The value can be an integer, None or a bytes-like object representing a buffer. In the later case it is up to the caller to ensure that the bytestring contains the proper bits (see the optional built-in module struct for a way to encode C structures as bytestrings). When value is set to None, optlen argument is required. It’s equivalent to call setsockopt() C function with optval=NULL and optlen=optlen.

버전 3.5에서 변경: 이제 쓰기 가능한 바이트열류 객체를 받아들입니다.

버전 3.6에서 변경: setsockopt(level, optname, None, optlen: int) 형식이 추가되었습니다.

socket.shutdown(how)

연결의 한쪽 또는 양쪽 절반을 닫습니다. how가 SHUT_RD면, 추가 수신이 허용되지 않습니다. how가 SHUT_WR이면, 추가 전송이 허용되지 않습니다. how가 SHUT_RDWR이면, 추가 송수신이 허용되지 않습니다.

socket.share(process_id)

소켓을 복제하고 대상 프로세스와 공유할 수 있도록 준비합니다. 대상 프로세스는 process_id로 제공되어야 합니다. 결과 바이트열 객체는 어떤 프로세스 간 통신의 형태를 사용하여 대상 프로세스로 전달될 수 있으며 그곳에서 fromshare()를 사용하여 소켓을 다시 만들 수 있습니다. 일단, 이 메서드가 호출되면, 운영 체제가 이미 대상 프로세스를 위해 이를 복제 했으므로 소켓을 닫아도 안전합니다.

가용성: 윈도우.

버전 3.3에 추가.

메서드 read() 나 write()가 없다는 점에 유의하십시오; 대신 recv() 와 send()를 flags 인자 없이 사용하십시오.

소켓 객체는 또한 socket 생성자에 지정된 값에 대응하는 다음과 같은 (읽기 전용) 어트리뷰트를 가집니다.

socket.family

소켓 패밀리.

socket.type

소켓 유형.

socket.proto

소켓 프로토콜.

소켓 시간제한에 대한 참고 사항

소켓 객체는 세 가지 모드 중 하나일 수 있습니다: 블로킹, 비 블로킹, 또는 시간제한. 소켓은 기본적으로 항상 블로킹 모드로 생성되지만, 이는 setdefaulttimeout()를 호출하여 변경할 수 있습니다.

블로킹 모드에서, 연산은 완료되거나 시스템에서 에러(가령 연결 시간 초과)를 반환할 때까지 블록합니다.

비 블로킹 모드에서, 연산은 즉시 완료할 수 없으면 실패합니다 (불행히도 시스템 종속적인 에러로): select의 함수를 사용하여 소켓이 읽기나 쓰기가 가능한 시기를 알 수 있습니다.

시간제한 모드에서, 연산은 소켓에 대해 지정된 제한 시간 내에 완료할 수 없거나 (timeout 예외 발생), 시스템이 에러를 반환하면 실패합니다.

참고

운영 체제 수준에서, 시간제한 모드의 소켓은 내부적으로 비 블로킹 모드로 설정됩니다. 또한, 블로킹과 시간제한 모드는 같은 네트워크 끝점을 가리키는 파일 기술자와 소켓 객체 간에 공유됩니다. 이 구현 세부 사항은 가시적인 결과를 가져올 수 있습니다, 예를 들어, 소켓의 fileno()를 사용하기로 한 경우가 그렇습니다.

시간제한과 connect 메서드

connect() 연산도 시간제한 설정의 영향을 받으며, 일반적으로 connect()를 호출하기 전에 settimeout()를 호출하거나 create_connection()에 timeout 매개 변수를 전달하는 것이 좋습니다. 그러나, 시스템 네트워크 스택은 파이썬 소켓 시간제한 설정과 관계없이 자체의 연결 시간제한 에러를 반환할 수 있습니다.

시간제한과 accept 메서드

getdefaulttimeout()가 None이 아니면, accept() 메서드에서 반환된 소켓은 그 시간제한을 상속합니다. 그렇지 않으면, 동작은 리스닝 소켓의 설정에 따라 다릅니다:

리스닝 소켓이 블로킹 모드 나 시간제한 모드에 있으면, accept()에 의해 반환된 소켓은 블로킹 모드에 있습니다.

리스닝 소켓이 비 블로킹 모드에 있으면, accept()에 의해 반환된 소켓이 블로킹 모드인지 비 블로킹 모드인지는 운영 체제에 따라 다릅니다. 플랫폼 간 동작을 보장하려면, 이 설정을 직접 재정의하는 것이 좋습니다.

예제

다음은 TCP/IP 프로토콜을 사용하는 4가지 최소 예제 프로그램입니다: (하나의 클라이언트만 서비스하는) 수신한 모든 데이터를 반향하는 서버와, 이를 사용하는 클라이언트. 서버는 socket(), bind(), listen(), accept() (두 개 이상의 클라이언트에 서비스를 제공하기 위해 accept()를 반복할 수 있습니다) 절차를 수행해야 하지만, 클라이언트는 socket(), connect() 절차만 요구함에 유의하십시오. 또한, 서버는 수신 대기 중인 소켓이 아니라 accept()가 반환한 새 소켓에 대해서 sendall()/recv()를 한다는 것에도 유의하십시오.

처음 두 예제는 IPv4만 지원합니다.

# Echo server program
import socket

HOST = ''                 # Symbolic name meaning all available interfaces
PORT = 50007              # Arbitrary non-privileged port
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.bind((HOST, PORT))
    s.listen(1)
    conn, addr = s.accept()
    with conn:
        print('Connected by', addr)
        while True:
            data = conn.recv(1024)
            if not data: break
            conn.sendall(data)

# Echo client program
import socket

HOST = 'daring.cwi.nl'    # The remote host
PORT = 50007              # The same port as used by the server
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.connect((HOST, PORT))
    s.sendall(b'Hello, world')
    data = s.recv(1024)
print('Received', repr(data))

다음 두 예제는 위의 두 예제와 같지만, IPv4와 IPv6를 모두 지원합니다. 서버 측은 사용 가능한 첫 번째 주소 패밀리를 리슨합니다 (대신 두 주소를 모두 리슨 해야 합니다). 대부분 IPv6 지원 시스템에서, IPv6가 우선하며 서버가 IPv4 트래픽을 허용하지 않을 수 있습니다. 클라이언트 측은 이름 결정의 결과로 반환된 모든 주소에 연결을 시도하고 성공적으로 연결된 첫 번째 주소로 트래픽을 보냅니다.

# Echo server program
import socket
import sys

HOST = None               # Symbolic name meaning all available interfaces
PORT = 50007              # Arbitrary non-privileged port
s = None
for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC,
                              socket.SOCK_STREAM, 0, socket.AI_PASSIVE):
    af, socktype, proto, canonname, sa = res
    try:
        s = socket.socket(af, socktype, proto)
    except OSError as msg:
        s = None
        continue
    try:
        s.bind(sa)
        s.listen(1)
    except OSError as msg:
        s.close()
        s = None
        continue
    break
if s is None:
    print('could not open socket')
    sys.exit(1)
conn, addr = s.accept()
with conn:
    print('Connected by', addr)
    while True:
        data = conn.recv(1024)
        if not data: break
        conn.send(data)

# Echo client program
import socket
import sys

HOST = 'daring.cwi.nl'    # The remote host
PORT = 50007              # The same port as used by the server
s = None
for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, socket.SOCK_STREAM):
    af, socktype, proto, canonname, sa = res
    try:
        s = socket.socket(af, socktype, proto)
    except OSError as msg:
        s = None
        continue
    try:
        s.connect(sa)
    except OSError as msg:
        s.close()
        s = None
        continue
    break
if s is None:
    print('could not open socket')
    sys.exit(1)
with s:
    s.sendall(b'Hello, world')
    data = s.recv(1024)
print('Received', repr(data))

다음 예제는 윈도우에서 원시(raw) 소켓으로 매우 간단한 네트워크 스니퍼를 작성하는 방법을 보여줍니다. 이 예제는 인터페이스를 수정하기 위해 관리자 권한이 필요합니다:

import socket

# the public network interface
HOST = socket.gethostbyname(socket.gethostname())

# create a raw socket and bind it to the public interface
s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP)
s.bind((HOST, 0))

# Include IP headers
s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)

# receive all packages
s.ioctl(socket.SIO_RCVALL, socket.RCVALL_ON)

# receive a package
print(s.recvfrom(65565))

# disabled promiscuous mode
s.ioctl(socket.SIO_RCVALL, socket.RCVALL_OFF)

다음 예제는 원시(raw) 소켓 프로토콜을 사용하여, 소켓 인터페이스를 사용하여 CAN 네트워크와 통신하는 방법을 보여줍니다. 대신 브로드캐스트 관리자 프로토콜로 CAN을 사용하려면, 소켓을 이렇게 여십시오:

socket.socket(socket.AF_CAN, socket.SOCK_DGRAM, socket.CAN_BCM)

소켓을 바인드(CAN_RAW)하거나 연결(CAN_BCM)한 후, socket.send() 와 socket.recv() 연산(과 대응 연산)을 소켓 객체에 평소와 같이 사용할 수 있습니다.

이 마지막 예제는 특별한 권한이 필요할 수 있습니다:

import socket
import struct

# CAN frame packing/unpacking (see 'struct can_frame' in <linux/can.h>)

can_frame_fmt = "=IB3x8s"
can_frame_size = struct.calcsize(can_frame_fmt)

def build_can_frame(can_id, data):
    can_dlc = len(data)
    data = data.ljust(8, b'\x00')
    return struct.pack(can_frame_fmt, can_id, can_dlc, data)

def dissect_can_frame(frame):
    can_id, can_dlc, data = struct.unpack(can_frame_fmt, frame)
    return (can_id, can_dlc, data[:can_dlc])

# create a raw socket and bind it to the 'vcan0' interface
s = socket.socket(socket.AF_CAN, socket.SOCK_RAW, socket.CAN_RAW)
s.bind(('vcan0',))

while True:
    cf, addr = s.recvfrom(can_frame_size)

    print('Received: can_id=%x, can_dlc=%x, data=%s' % dissect_can_frame(cf))

    try:
        s.send(cf)
    except OSError:
        print('Error sending CAN frame')

    try:
        s.send(build_can_frame(0x01, b'\x01\x02\x03'))
    except OSError:
        print('Error sending CAN frame')

실행 간격이 너무 짧게 여러 번 예제를 실행하면 이 에러가 발생할 수 있습니다:

OSError: [Errno 98] Address already in use

이것은 이전 실행이 소켓을 TIME_WAIT 상태로 남겨 두었고, 즉시 재사용할 수 없기 때문입니다.

이것을 방지하기 위해서 설정할 수 있는 socket 플래그 socket.SO_REUSEADDR가 있습니다:

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((HOST, PORT))

SO_REUSEADDR 플래그는 자연스러운 시간제한이 만료되기를 기다리지 않고 TIME_WAIT 상태의 지역 소켓을 재사용하도록 커널에 알립니다.

더 보기

(C로 하는) 소켓 프로그래밍에 대한 소개는 다음 논문을 참조하십시오:

An Introductory 4.3BSD Interprocess Communication Tutorial, Stuart Sechrest 저

An Advanced 4.3BSD Interprocess Communication Tutorial, Samuel J. Leffler 외 저,

둘 다 유닉스 프로그래머 매뉴얼, 보충 문서 1 (섹션 PS1:7과 PS1:8)에 있습니다. 다양한 소켓 관련 시스템 호출에 대한 플랫폼별 레퍼런스 자료는 소켓 의미의 세부 정보에 대한 중요한 소스입니다. 유닉스에서는 매뉴얼 페이지를 참조하십시오; 윈도우에서는, WinSock (또는 Winsock 2) 명세를 참조하십시오. IPv6 지원 API의 경우, 독자는 Basic Socket Interface Extensions for IPv6라는 제목의 RFC 3493 [https://tools.ietf.org/html/rfc3493.html]를 참조하고 싶을 겁니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

네트워킹과 프로세스 간 통신 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

네트워킹과 프로세스 간 통신 »

|

ssl — 소켓 객체용 TLS/SSL 래퍼

소스 코드: Lib/ssl.py [https://github.com/python/cpython/tree/3.7/Lib/ssl.py]

이 모듈은 클라이언트 쪽과 서버 쪽 네트워크 소켓에 대한 전송 계층 보안(Transport Layer Security) (“보안 소켓 계층(Secure Sockets Layer)” 이라고도 함) 암호화와 피어 인증 기능에 대한 액세스를 제공합니다. 이 모듈은 OpenSSL 라이브러리를 사용합니다. OpenSSL이 해당 플랫폼에 설치되어있는 한, 모든 최신 유닉스 시스템, 윈도우, 맥 OS X 및 추가 플랫폼에서 사용할 수 있습니다.

참고

운영 체제 소켓 API를 호출하기 때문에, 일부 동작은 플랫폼에 따라 다를 수 있습니다. 설치된 OpenSSL 버전도 동작을 바꿀 수 있습니다. 예를 들어, TLSv1.1과 TLSv1.2는 openssl 버전 1.0.1과 함께 제공됩니다.

경고

보안 고려 사항을 읽지 않고 이 모듈을 사용하지 마십시오. 그렇게 하면 ssl 모듈의 기본 설정이 반드시 여러분의 응용 프로그램에 적합하지는 않으므로 잘못된 보안 인식으로 이어질 수 있습니다.

이 절에서는 ssl 모듈의 객체와 함수를 설명합니다; TLS, SSL 및 인증서에 대한보다 일반적인 정보는, 하단의 “더 보기” 절에 있는 문서를 참조하십시오.

This module provides a class, ssl.SSLSocket, which is derived from the socket.socket type, and provides a socket-like wrapper that also encrypts and decrypts the data going over the socket with SSL. It supports additional methods such as getpeercert(), which retrieves the certificate of the other side of the connection, and cipher(), which retrieves the cipher being used for the secure connection.

더욱 정교한 응용 프로그램의 경우, ssl.SSLContext 클래스는 설정과 인증서를 관리하는 데 도움이 되며, SSLContext.wrap_socket() 메서드를 통해 만들어진 SSL 소켓이 상속할 수 있습니다.

버전 3.5.3에서 변경: OpenSSL 1.1.0과의 링크를 지원하도록 갱신되었습니다

버전 3.6에서 변경: OpenSSL 0.9.8, 1.0.0 및 1.0.1은 폐지되었으며 더는 지원되지 않습니다. 미래에는 ssl 모듈이 최소한 OpenSSL 1.0.2 나 1.1.0을 요구할 것입니다.

함수, 상수 및 예외

소켓 생성

파이썬 3.2와 2.7.9 이후로, SSLSocket 객체로 소켓을 포장하기 위해 SSLContext 인스턴스의 SSLContext.wrap_socket()을 사용하는 것이 좋습니다. 도우미 함수 create_default_context()는 보안 기본 설정의 새 컨텍스트를 반환합니다. 오래된 wrap_socket() 함수는 비효율적이고 서버 이름 표시(SNI)와 호스트 이름 일치를 지원하지 않기 때문에 폐지되었습니다.

기본 컨텍스트와 IPv4/IPv6 이중 스택을 사용하는 클라이언트 소켓 예제:

import socket
import ssl

hostname = 'www.python.org'
context = ssl.create_default_context()

with socket.create_connection((hostname, 443)) as sock:
    with context.wrap_socket(sock, server_hostname=hostname) as ssock:
        print(ssock.version())

사용자 정의 컨텍스트와 IPv4를 사용하는 클라이언트 소켓 예제:

hostname = 'www.python.org'
# PROTOCOL_TLS_CLIENT requires valid cert chain and hostname
context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
context.load_verify_locations('path/to/cabundle.pem')

with socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) as sock:
    with context.wrap_socket(sock, server_hostname=hostname) as ssock:
        print(ssock.version())

localhost IPv4에서 리스닝하는 서버 소켓 예제:

context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
context.load_cert_chain('/path/to/certchain.pem', '/path/to/private.key')

with socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) as sock:
    sock.bind(('127.0.0.1', 8443))
    sock.listen(5)
    with context.wrap_socket(sock, server_side=True) as ssock:
        conn, addr = ssock.accept()
        ...

컨텍스트 생성

편리 함수는 공통 목적을 위한 SSLContext 객체를 만드는 데 도움이 됩니다.

ssl.create_default_context(purpose=Purpose.SERVER_AUTH, cafile=None, capath=None, cadata=None)

지정된 purpose를 위한 기본 설정으로 새 SSLContext 객체를 반환합니다. 설정은 ssl 모듈에 의해 선택되며, 일반적으로 SSLContext 생성자를 직접 호출할 때 보다 높은 보안 수준을 나타냅니다.

cafile, capath, cadata는, SSLContext.load_verify_locations()에서와 같이, 인증서 확인을 위해 신뢰할 수 있는 선택적 CA 인증서를 나타냅니다. 세 개 모두가 None이면, 이 함수는 대신 시스템의 기본 CA 인증서를 신뢰하도록 선택할 수 있습니다.

설정은: PROTOCOL_TLS, OP_NO_SSLv2 및 OP_NO_SSLv3이며, RC4가 없는 높은 암호화 사이퍼 스위트가 포함되고, 인증되지 않은 사이퍼 스위트는 포함되지 않습니다. SERVER_AUTH를 purpose로 전달하면 verify_mode가 CERT_REQUIRED로 설정되고 CA 인증서가 로드되거나 (cafile, capath 또는 cadata 중 하나 이상이 제공될 때), SSLContext.load_default_certs()를 사용하여 기본 CA 인증서를 로드합니다.

참고

프로토콜, 옵션, 사이퍼 및 기타 설정은 사전 폐지 없이 언제든지 더욱 제한적인 값으로 변경될 수 있습니다. 이 값은 호환성과 보안 간의 적절한 균형을 나타냅니다.

응용 프로그램에 특정 설정이 필요하면, SSLContext를 만들어 설정을 직접 적용해야 합니다.

참고

특정 이전 클라이언트나 서버가 이 함수로 만든 SSLContext로 연결을 시도할 때 “Protocol or cipher suite mismatch”라는 에러가 발생하면, 이 함수가 OP_NO_SSLv3를 사용해서 제외하는 SSL3.0만 지원하는 것일 수 있습니다. SSL3.0은 완전히 망가진 [https://en.wikipedia.org/wiki/POODLE]것으로 널리 인식되고 있습니다. 이 함수를 계속 사용하면서 SSL 3.0 연결을 계속 허용하려면 다음과 같이 다시 활성화할 수 있습니다:

ctx = ssl.create_default_context(Purpose.CLIENT_AUTH)
ctx.options &= ~ssl.OP_NO_SSLv3

버전 3.4에 추가.

버전 3.4.4에서 변경: RC4는 기본 사이퍼 문자열에서 삭제되었습니다.

버전 3.6에서 변경: ChaCha20/Poly1305가 기본 사이퍼 문자열에 추가되었습니다.

3DES가 기본 사이퍼 문자열에서 삭제되었습니다.

예외

exception ssl.SSLError

하부 SSL 구현(현재 OpenSSL 라이브러리에서 제공)으로부터의 에러를 알리기 위해 발생합니다. 이는 하부 네트워크 연결에 겹쳐진 상위 수준의 암호화와 인증 계층에서 문제가 있음을 나타냅니다. 이 에러는 OSError의 서브 형입니다. SSLError 인스턴스의 에러 코드와 메시지는 OpenSSL 라이브러리에 의해 제공됩니다.

버전 3.3에서 변경: SSLError는 socket.error의 서브 형이었습니다.

library

SSL, PEM 또는 X509와 같이, 에러가 발생한 OpenSSL 하위 모듈을 지정하는 문자열 기호입니다. 가능한 값의 범위는 OpenSSL 버전에 따라 다릅니다.

버전 3.3에 추가.

reason

이 에러가 발생한 이유를 나타내는 문자열 기호, 예를 들어, CERTIFICATE_VERIFY_FAILED. 가능한 값의 범위는 OpenSSL 버전에 따라 다릅니다.

버전 3.3에 추가.

exception ssl.SSLZeroReturnError

읽기나 쓰기를 시도하고 SSL 연결이 정상적으로 닫혔을 때 발생하는 SSLError의 서브 클래스. 이것이 하부 트랜스포트(TCP 읽기)가 닫혔음을 뜻하지는 않습니다.

버전 3.3에 추가.

exception ssl.SSLWantReadError

데이터를 읽거나 쓰려고 하지만, 요청을 만족하려면 하부 TCP 트랜스포트에서 데이터를 더 수신해야 할 때, 비 블로킹 SSL 소켓에 의해 발생하는 SSLError의 서브 클래스.

버전 3.3에 추가.

exception ssl.SSLWantWriteError

데이터를 읽거나 쓰려고 하지만, 요청을 만족하려면 하부 TCP 트랜스포트로 데이터를 더 보내야 할 때, 비 블로킹 SSL 소켓에 의해 발생하는 SSLError의 서브 클래스.

버전 3.3에 추가.

exception ssl.SSLSyscallError

SSL 소켓에서 작업을 수행하는 동안 시스템 에러를 만났을 때 발생하는 SSLError의 서브 클래스. 불행히도 원래의 errno 번호를 검사하는 쉬운 방법은 없습니다.

버전 3.3에 추가.

exception ssl.SSLEOFError

SSL 연결이 갑자기 종료되었을 때 발생하는 SSLError의 서브 클래스. 일반적으로, 이 에러가 발생하면 하부 트랜스포트를 다시 사용하지 않아야 합니다.

버전 3.3에 추가.

exception ssl.SSLCertVerificationError

인증서 유효성 검사가 실패했을 때 발생하는 SSLError의 서브 클래스.

버전 3.7에 추가.

verify_code

유효성 검사 에러를 나타내는 숫자 에러 번호.

verify_message

사람이 읽을 수 있는 유효성 검사 에러 문자열.

exception ssl.CertificateError

SSLCertVerificationError의 별칭.

버전 3.7에서 변경: 예외는 이제 SSLCertVerificationError의 별칭입니다.

난수 생성

ssl.RAND_bytes(num)

길이 num의 암호학적으로 강한 의사 난수 바이트열을 반환합니다. PRNG에 충분한 데이터가 시드(seed) 되지 않았거나 현재 RAND 메서드에서 지원되지 않는 연산이면 SSLError를 발생시킵니다. RAND_status()를 PRNG의 상태를 확인하는 데 사용할 수 있으며 RAND_add()는 PRNG를 시드 하는 데 사용할 수 있습니다.

거의 모든 응용 프로그램에서 os.urandom()을 선호합니다.

암호학적 생성기의 요구 사항을 얻으려면 위키피디아 기사 Cryptographically secure pseudorandom number generator (CSPRNG) [https://en.wikipedia.org/wiki/Cryptographically_secure_pseudorandom_number_generator]를 읽으십시오.

버전 3.3에 추가.

ssl.RAND_pseudo_bytes(num)

(bytes, is_cryptographic) 을 반환합니다: bytes는 num 길이의 의사 난수 바이트열이며, 생성된 bytes가 암호학적으로 강하면 is_cryptographic은 True입니다. 현재 RAND 메서드에서 지원되지 않는 연산이면 SSLError를 발생시킵니다.

생성된 의사 난수 바이트 시퀀스는 충분한 길이일 때 고유하지만, 예측할 수 없는 것은 아닙니다. 이것들은 비암호화 목적이나 암호화 프로토콜에서의 특정 목적을 위해 사용될 수 있지만, 보통 키 생성 등을 위해 사용되지는 않습니다.

거의 모든 응용 프로그램에서 os.urandom()을 선호합니다.

버전 3.3에 추가.

버전 3.6부터 폐지: OpenSSL은 ssl.RAND_pseudo_bytes()를 폐지했습니다. 대신 ssl.RAND_bytes()를 사용하십시오.

ssl.RAND_status()

SSL 의사 난수 생성기에 ‘충분한’ 임의성이 시드 되었으면 True를 반환하고, 그렇지 않으면 False를 반환합니다. ssl.RAND_egd()와 ssl.RAND_add()를 사용하여 의사 난수 생성기의 임의성을 높일 수 있습니다.

ssl.RAND_egd(path)

어딘가에 엔트로피 수집 데몬(EGD - entropy-gathering daemon)을 실행 중이고, path가 그곳으로 열려있는 소켓 연결의 경로명이면, 그 소켓에서 256바이트의 임의성을 읽고, 생성된 비밀 키의 보안을 강화하기 위해 이를 SSL 의사 난수 생성기에 추가합니다. 이것은 일반적으로 더 나은 임의성 소스가 없는 시스템에서만 필요합니다.

엔트로피 수집 데몬의 소스에 대해서는 http://egd.sourceforge.net/ 나 http://prngd.sourceforge.net/ 을 참조하십시오.

가용성: LibreSSL 과 OpenSSL > 1.1.0에서는 사용할 수 없습니다.

ssl.RAND_add(bytes, entropy)

주어진 bytes를 SSL 의사 난수 생성기에 섞습니다. 매개 변수 entropy(float)는 문자열에 포함된 엔트로피의 하한값이므로 항상 0.0을 사용할 수 있습니다. 엔트로피 소스에 대한 추가 정보는 RFC 1750 [https://tools.ietf.org/html/rfc1750.html]을 참조하십시오.

버전 3.5에서 변경: 이제 쓰기 가능한 바이트열류 객체를 받아들입니다.

인증서 처리

ssl.match_hostname(cert, hostname)

cert(SSLSocket.getpeercert()에서 반환된 디코딩된 형식)가 지정된 hostname과 일치하는지 확인합니다. 적용되는 규칙은 RFC 2818 [https://tools.ietf.org/html/rfc2818.html], RFC 5280 [https://tools.ietf.org/html/rfc5280.html] 및 RFC 6125 [https://tools.ietf.org/html/rfc6125.html]에 설명된 대로 HTTPS 서버의 신원(identity)을 확인하기 위한 것입니다. HTTPS 외에도, 이 함수는 FTPS, IMAPS, POPS 및 그 밖의 다양한 SSL 기반 프로토콜에서 서버의 신원을 확인하는 데 적합합니다.

실패하면 CertificateError가 발생합니다. 성공하면, 함수는 아무것도 반환하지 않습니다:

>>> cert = {'subject': ((('commonName', 'example.com'),),)}
>>> ssl.match_hostname(cert, "example.com")
>>> ssl.match_hostname(cert, "example.org")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/py3k/Lib/ssl.py", line 130, in match_hostname
ssl.CertificateError: hostname 'example.org' doesn't match 'example.com'

버전 3.2에 추가.

버전 3.3.3에서 변경: 이 함수는 이제 RFC 6125 [https://tools.ietf.org/html/rfc6125.html], 6.4.3절을 따르며 다중 와일드카드(예를 들어, *.*.com 나 *a*.example.org)나 국제화된 도메인 이름(IDN) 내부의 와일드카드와 일치하지 않습니다. www*.xn--pthon-kva.org와 같은 IDN A-레이블은 계속 지원되지만, x*.python.org는 더는 xn--tda.python.org와 일치하지 않습니다.

버전 3.5에서 변경: 인증서의 subjectAltName 필드에 있을 때, IP 주소의 일치는 이제 지원됩니다.

버전 3.7에서 변경: 이 함수는 더는 TLS 연결에 사용되지 않습니다. 이제 호스트 이름 일치는 OpenSSL에 의해 수행됩니다.

와일드카드가 가장 왼쪽에 있고 그 세그먼트의 유일한 문자일 때 와일드카드를 허용합니다. www*.example.com와 같은 부분적인 와일드카드는 더는 지원되지 않습니다.

버전 3.7부터 폐지.

ssl.cert_time_to_seconds(cert_time)

인증서의 “notBefore” 나 “notAfter” 날짜를 나타내는 "%b %d %H:%M:%S %Y %Z" strptime 형식(C 로케일)의 cert_time 문자열이 지정하는 시간을 Epoch 이후 초 단위로 반환합니다.

여기 예제가 있습니다:

>>> import ssl
>>> timestamp = ssl.cert_time_to_seconds("Jan  5 09:34:43 2018 GMT")
>>> timestamp
1515144883
>>> from datetime import datetime
>>> print(datetime.utcfromtimestamp(timestamp))
2018-01-05 09:34:43

“notBefore” 나 “notAfter” 날짜는 GMT(RFC 5280 [https://tools.ietf.org/html/rfc5280.html])를 사용해야 합니다.

버전 3.5에서 변경: 입력된 시간을 입력 문자열의 ‘GMT’ 시간대로 지정된 UTC 시간으로 해석합니다. 이전에는 지역 시간대가 사용되었습니다. 정수를 반환합니다 (입력 형식에는 부분 초가 없습니다).

ssl.get_server_certificate(addr, ssl_version=PROTOCOL_TLS, ca_certs=None)

주어진 SSL로 보호된 서버의 주소 addr((hostname, port-number) 쌍)에 대해, 서버 인증서를 가져와서 PEM-인코딩된 문자열로 반환합니다. ssl_version이 지정되면, 해당 버전의 SSL 프로토콜을 사용하여 서버에 연결을 시도합니다. ca_certs가 지정되면, 루트 인증서 목록을 포함하는 파일이어야 하는데, SSLContext.wrap_socket()에서 같은 매개 변수에 사용된 것과 같은 형식입니다. 호출은 해당 루트 인증서 집합에 대해 서버 인증서의 유효성을 검사하려고 시도하며, 유효성 검사 시도가 실패하면 실패합니다.

버전 3.3에서 변경: 이 함수는 이제 IPv6와 호환됩니다.

버전 3.5에서 변경: 최신 서버와의 호환성을 최대화하기 위해 기본 ssl_version이 PROTOCOL_SSLv3에서 PROTOCOL_TLS로 변경되었습니다.

ssl.DER_cert_to_PEM_cert(DER_cert_bytes)

인증서가 DER-인코딩된 바이트열로 주어지면, 같은 인증서의 PEM-인코딩된 문자열 버전을 반환합니다.

ssl.PEM_cert_to_DER_cert(PEM_cert_string)

인증서가 ASCII PEM 문자열로 주어지면, 같은 인증서의 DER-인코딩된 바이트열 시퀀스를 반환합니다.

ssl.get_default_verify_paths()

OpenSSL의 기본 cafile 및 capath에 대한 경로가 있는 네임드 튜플을 반환합니다. 경로는 SSLContext.set_default_verify_paths()에서 사용하는 경로와 같습니다. 반환 값은 네임드 튜플 DefaultVerifyPaths입니다.:

cafile - cafile에 대한 확인된 경로나 파일이 존재하지 않으면 None,

capath - capath에 대한 확인된 경로나 디렉터리가 존재하지 않으면 None,

openssl_cafile_env - cafile을 가리키는 OpenSSL의 환경 키,

openssl_cafile - cafile에 대한 하드 코딩된 경로,

openssl_capath_env - capath를 가리키는 OpenSSL의 환경 키,

openssl_capath - capath 디렉터리에 대한 하드 코딩된 경로

가용성: LibreSSL은 환경 변수 openssl_cafile_env와 openssl_capath_env를 무시합니다.

버전 3.4에 추가.

ssl.enum_certificates(store_name)

윈도우의 시스템 인증서 저장소에서 인증서를 꺼냅니다. store_name은 CA, ROOT 또는 MY 중 하나일 수 있습니다. 윈도우가 추가 인증서 저장소를 제공 할 수도 있습니다.

이 함수는 (cert_bytes, encoding_type, trust) 튜플의 리스트를 반환합니다. encoding_type은 cert_bytes의 인코딩을 지정합니다. X.509 ASN.1 데이터를 위한 x509_asn이거나 PKCS#7 ASN.1 데이터를 위한 pkcs_7_asn입니다. Trust는 인증서의 목적을 OIDS 집합으로 지정하거나, 인증서가 모든 목적에 대해 신뢰할 수 있으면 정확히 True입니다.

예제:

>>> ssl.enum_certificates("CA")
[(b'data...', 'x509_asn', {'1.3.6.1.5.5.7.3.1', '1.3.6.1.5.5.7.3.2'}),
 (b'data...', 'x509_asn', True)]

가용성: 윈도우.

버전 3.4에 추가.

ssl.enum_crls(store_name)

윈도우의 시스템 인증서 저장소에서 CRL을 꺼냅니다. store_name는 CA, ROOT 또는 MY 중 하나일 수 있습니다. 윈도우가 추가 인증서 저장소를 제공 할 수도 있습니다.

이 함수는 (cert_bytes, encoding_type, trust) 튜플의 리스트를 반환합니다. encoding_type은 cert_bytes의 인코딩을 지정합니다. X.509 ASN.1 데이터를 위한 x509_asn이거나 PKCS#7 ASN.1 데이터를 위한 pkcs_7_asn입니다.

가용성: 윈도우.

버전 3.4에 추가.

ssl.wrap_socket(sock, keyfile=None, certfile=None, server_side=False, cert_reqs=CERT_NONE, ssl_version=PROTOCOL_TLS, ca_certs=None, do_handshake_on_connect=True, suppress_ragged_eofs=True, ciphers=None)

socket.socket의 인스턴스 sock을 취해서, SSL 컨텍스트에 하부 소켓을 감싸는 socket.socket의 서브 형인 ssl.SSLSocket 인스턴스를 반환합니다. sock은 SOCK_STREAM 소켓이어야합니다; 다른 소켓 유형은 지원되지 않습니다.

내부적으로, 함수는 프로토콜이 ssl_version 이고 SSLContext.options이 cert_reqs로 설정된 SSLContext를 만듭니다. 매개 변수 keyfile, certfile, ca_certs 또는 ciphers가 설정되면, 값은 SSLContext.load_cert_chain(), SSLContext.load_verify_locations() 및 SSLContext.set_ciphers()로 전달됩니다.

인자 server_side, do_handshake_on_connect 및 suppress_ragged_eofs는 SSLContext.wrap_socket()과 같은 의미입니다.

버전 3.7부터 폐지: 파이썬 3.2와 2.7.9부터, wrap_socket() 대신 SSLContext.wrap_socket()을 사용하는 것이 좋습니다. 최상위 함수는 제한적이고 서버 이름 표시나 호스트 이름 일치가 없는 안전하지 않은 클라이언트 소켓을 만듭니다.

상수

모든 상수는 이제 enum.IntEnum 이나 enum.IntFlag 컬렉션입니다.

버전 3.6에 추가.

ssl.CERT_NONE

SSLContext.verify_mode나 wrap_socket()의 cert_reqs 매개 변수의 가능한 값. PROTOCOL_TLS_CLIENT를 제외하고는, 기본 모드입니다. 클라이언트 측 소켓에서는, 모든 인증서가 허용됩니다. 신뢰할 수 없거나 만료된 인증서와 같은 유효성 검사 에러는 무시되며 TLS/SSL 핸드 셰이크를 중단하지 않습니다.

서버 모드에서는, 클라이언트에서 인증서를 요청하지 않으므로 클라이언트는 클라이언트 인증서 인증을 위해 인증서를 보내지 않습니다.

아래의 보안 고려 사항의 논의를 참조하십시오.

ssl.CERT_OPTIONAL

SSLContext.verify_mode나 wrap_socket()의 cert_reqs 매개 변수의 가능한 값. 클라이언트 모드에서, CERT_OPTIONAL는 CERT_REQUIRED와 같은 의미입니다. 클라이언트 측 소켓에서는 대신 CERT_REQUIRED를 사용하는 것이 좋습니다.

서버 모드에서는, 클라이언트 인증서 요청이 클라이언트로 전송됩니다. 클라이언트는 요청을 무시하거나 TLS 클라이언트 인증서 인증을 수행하기 위해 인증서를 보낼 수 있습니다. 클라이언트가 인증서를 보내기로 선택하면, 인증서가 유효성 검사됩니다. 모든 유효성 검사 에러는, TLS 핸드 셰이크를 즉시 중단합니다.

이 설정을 사용하려면 유효한 CA 인증서 집합을 SSLContext.load_verify_locations() 나 wrap_socket()의 ca_certs 매개 변숫값으로 전달해야 합니다.

ssl.CERT_REQUIRED

SSLContext.verify_mode나 wrap_socket()의 cert_reqs 매개 변수의 가능한 값. 이 모드에서는, 소켓 연결의 다른 쪽에서 인증서를 요구합니다; 인증서가 제공되지 않거나 유효성 검사에 실패하면 SSLError가 발생합니다. 이 모드는 호스트 이름 일치를 수행하지 않기 때문에 클라이언트 모드에서 인증서를 유효성 검사하기에 충분하지 않습니다. 인증서의 진위를 검사하기 위해 check_hostname도 활성화해야 합니다. PROTOCOL_TLS_CLIENT는 기본적으로 CERT_REQUIRED를 사용하고 check_hostname을 활성화합니다.

서버 소켓에서, 이 모드는 필수 TLS 클라이언트 인증서 인증을 제공합니다. 클라이언트 인증서 요청이 클라이언트에 보내지고 클라이언트는 유효하고 신뢰할 수 있는 인증서를 제공해야 합니다.

이 설정을 사용하려면 유효한 CA 인증서 집합을 SSLContext.load_verify_locations() 나 wrap_socket()의 ca_certs 매개 변숫값으로 전달해야 합니다.

class ssl.VerifyMode

CERT_* 상수의 enum.IntEnum 컬렉션.

버전 3.6에 추가.

ssl.VERIFY_DEFAULT

SSLContext.verify_flags의 가능한 값. 이 모드에서는 인증서 해지 목록(CRL)을 검사하지 않습니다. 기본적으로 OpenSSL은 CRL을 요구하지도 검사하지도 않습니다.

버전 3.4에 추가.

ssl.VERIFY_CRL_CHECK_LEAF

Possible value for SSLContext.verify_flags. In this mode, only the peer cert is checked but none of the intermediate CA certificates. The mode requires a valid CRL that is signed by the peer cert’s issuer (its direct ancestor CA). If no proper CRL has has been loaded with SSLContext.load_verify_locations, validation will fail.

버전 3.4에 추가.

ssl.VERIFY_CRL_CHECK_CHAIN

SSLContext.verify_flags의 가능한 값. 이 모드에서는, 피어 인증서 체인의 모든 인증서에 대한 CRL이 확인됩니다.

버전 3.4에 추가.

ssl.VERIFY_X509_STRICT

망가진 X.509 인증서에 대한 우회를 사용하지 못하도록 하는 SSLContext.verify_flags의 가능한 값.

버전 3.4에 추가.

ssl.VERIFY_X509_TRUSTED_FIRST

SSLContext.verify_flags의 가능한 값. OpenSSL이 인증서의 유효성을 검사하기 위해 트러스트 체인을 구축할 때 신뢰할 수 있는 인증서를 선호하도록 지시합니다. 이 플래그는 기본적으로 활성화됩니다.

버전 3.4.4에 추가.

class ssl.VerifyFlags

VERIFY_* 상수의 enum.IntFlag 컬렉션.

버전 3.6에 추가.

ssl.PROTOCOL_TLS

클라이언트와 서버가 모두 지원하는 가장 높은 프로토콜 버전을 선택합니다. 이름에도 불구하고, 이 옵션은 “SSL” 과 “TLS” 프로토콜을 모두 선택할 수 있습니다.

버전 3.6에 추가.

ssl.PROTOCOL_TLS_CLIENT

PROTOCOL_TLS처럼 가장 높은 프로토콜 버전을 자동 협상하지만, 클라이언트 측 SSLSocket 연결만 지원합니다. 이 프로토콜은 기본적으로 CERT_REQUIRED와 check_hostname을 활성화합니다.

버전 3.6에 추가.

ssl.PROTOCOL_TLS_SERVER

PROTOCOL_TLS처럼 가장 높은 프로토콜 버전을 자동 협상하지만, 서버 측 SSLSocket 연결만 지원합니다.

버전 3.6에 추가.

ssl.PROTOCOL_SSLv23

Alias for PROTOCOL_TLS.

버전 3.6부터 폐지: 대신 PROTOCOL_TLS를 사용하십시오.

ssl.PROTOCOL_SSLv2

채널 암호화 프로토콜로 SSL 버전 2를 선택합니다.

OpenSSL이 OPENSSL_NO_SSL2 플래그로 컴파일되었으면 이 프로토콜을 사용할 수 없습니다.

경고

SSL 버전 2는 안전하지 않습니다. 사용하지 말도록 강력히 권고합니다.

버전 3.6부터 폐지: OpenSSL은 SSLv2에 대한 지원을 제거했습니다.

ssl.PROTOCOL_SSLv3

채널 암호화 프로토콜로 SSL 버전 3을 선택합니다.

OpenSSL이 OPENSSL_NO_SSLv3 플래그로 컴파일되었으면 이 프로토콜을 사용할 수 없습니다.

경고

SSL 버전 3은 안전하지 않습니다. 사용하지 말도록 강력히 권고합니다.

버전 3.6부터 폐지: OpenSSL은 모든 버전 특정 프로토콜을 폐지했습니다. 대신 OP_NO_SSLv3와 같은 플래그와 함께 기본 프로토콜 PROTOCOL_TLS를 사용하십시오.

ssl.PROTOCOL_TLSv1

채널 암호화 프로토콜로 TLS 버전 1.0을 선택합니다.

버전 3.6부터 폐지: OpenSSL은 모든 버전 특정 프로토콜을 폐지했습니다. 대신 OP_NO_SSLv3와 같은 플래그와 함께 기본 프로토콜 PROTOCOL_TLS를 사용하십시오.

ssl.PROTOCOL_TLSv1_1

채널 암호화 프로토콜로 TLS 버전 1.1을 선택합니다. openssl 버전 1.0.1+ 에서만 사용할 수 있습니다.

버전 3.4에 추가.

버전 3.6부터 폐지: OpenSSL은 모든 버전 특정 프로토콜을 폐지했습니다. 대신 OP_NO_SSLv3와 같은 플래그와 함께 기본 프로토콜 PROTOCOL_TLS를 사용하십시오.

ssl.PROTOCOL_TLSv1_2

채널 암호화 프로토콜로 TLS 버전 1.2를 선택합니다. 이것은 가장 현대적인 버전이며, 양측이 모두 가능하다면 최대한의 보호를 위해 아마도 제일 나은 선택입니다. openssl 버전 1.0.1+ 에서만 사용할 수 있습니다.

버전 3.4에 추가.

버전 3.6부터 폐지: OpenSSL은 모든 버전 특정 프로토콜을 폐지했습니다. 대신 OP_NO_SSLv3와 같은 플래그와 함께 기본 프로토콜 PROTOCOL_TLS를 사용하십시오.

ssl.OP_ALL

다른 SSL 구현에 있는 다양한 버그에 대한 해결 방법을 활성화합니다. 이 옵션은 기본적으로 설정됩니다. 반드시 OpenSSL의 SSL_OP_ALL 상수와 같은 플래그를 설정할 필요는 없습니다.

버전 3.2에 추가.

ssl.OP_NO_SSLv2

SSLv2 연결을 방지합니다. 이 옵션은 PROTOCOL_TLS와 결합해서만 적용할 수 있습니다. 피어가 SSLv2를 프로토콜 버전으로 선택하지 못하도록 합니다.

버전 3.2에 추가.

버전 3.6부터 폐지: SSLv2는 폐지되었습니다.

ssl.OP_NO_SSLv3

SSLv3 연결을 방지합니다. 이 옵션은 PROTOCOL_TLS와 결합해서만 적용할 수 있습니다. 피어가 프로토콜 버전으로 SSLv3을 선택하지 못하게 합니다.

버전 3.2에 추가.

버전 3.6부터 폐지: SSLv3은 폐지되었습니다.

ssl.OP_NO_TLSv1

TLSv1 연결을 금지합니다. 이 옵션은 PROTOCOL_TLS와 결합해서만 적용할 수 있습니다. 피어가 TLSv1을 프로토콜 버전으로 선택하지 못하게 합니다.

버전 3.2에 추가.

버전 3.7부터 폐지: 이 옵션은 OpenSSL 1.1.0부터 폐지되었습니다, 새로운 SSLContext.minimum_version과 SSLContext.maximum_version을 대신 사용하십시오.

ssl.OP_NO_TLSv1_1

TLSv1.1 연결을 금지합니다. 이 옵션은 PROTOCOL_TLS와 결합해서만 적용할 수 있습니다. 피어가 TLSv1.1을 프로토콜 버전으로 선택하지 못하게 합니다. openssl 버전 1.0.1+ 에서만 사용할 수 있습니다.

버전 3.4에 추가.

버전 3.7부터 폐지: 이 옵션은 OpenSSL 1.1.0부터 폐지되었습니다.

ssl.OP_NO_TLSv1_2

TLSv1.2 연결을 방지합니다. 이 옵션은 PROTOCOL_TLS와 결합해서만 적용할 수 있습니다. 피어가 프로토콜 버전으로 TLSv1.2를 선택하지 못하게 합니다. openssl 버전 1.0.1+ 에서만 사용할 수 있습니다.

버전 3.4에 추가.

버전 3.7부터 폐지: 이 옵션은 OpenSSL 1.1.0부터 폐지되었습니다.

ssl.OP_NO_TLSv1_3

TLSv1.3 연결을 방지합니다. 이 옵션은 PROTOCOL_TLS와 결합해서만 적용할 수 있습니다. 피어가 프로토콜 버전으로 TLSv1.3을 선택하지 못하게 합니다. TLS 1.3은 OpenSSL 1.1.1 이상에서 사용할 수 있습니다. 파이썬이 OpenSSL의 이전 버전에 대해 컴파일되면, 플래그의 기본값은 0입니다.

버전 3.7에 추가.

버전 3.7부터 폐지: 이 옵션은 OpenSSL 1.1.0부터 폐지되었습니다. OpenSSL 1.0.2와의 하위 호환성을 위해 2.7.15, 3.6.3 및 3.7.0에 추가되었습니다.

ssl.OP_NO_RENEGOTIATION

TLSv1.2와 그 이전 버전에서 모든 재협상을 비활성화합니다. HelloRequest 메시지를 보내지 않고, ClientHello를 통한 재협상 요청을 무시합니다.

이 옵션은 OpenSSL 1.1.0h 이상에서만 사용할 수 있습니다.

버전 3.7에 추가.

ssl.OP_CIPHER_SERVER_PREFERENCE

클라이언트보다는 서버의 사이퍼 순서 선호를 사용합니다. 이 옵션은 클라이언트 소켓과 SSLv2 서버 소켓에는 영향을 미치지 않습니다.

버전 3.3에 추가.

ssl.OP_SINGLE_DH_USE

서로 다른 SSL 세션에 대해 같은 DH 키 재사용을 방지합니다. 이렇게 하면 FS(forward secrecy)는 향상되지만, 더 많은 계산 자원을 요구합니다. 이 옵션은 서버 소켓에만 적용됩니다.

버전 3.3에 추가.

ssl.OP_SINGLE_ECDH_USE

서로 다른 SSL 세션에 대해 같은 ECDH 키 재사용을 방지합니다. 이렇게 하면 FS(forward secrecy)는 향상되지만, 더 많은 계산 자원을 요구합니다. 이 옵션은 서버 소켓에만 적용됩니다.

버전 3.3에 추가.

ssl.OP_ENABLE_MIDDLEBOX_COMPAT

TLS 1.3 연결을 더 TLS 1.2 연결처럼 보이게 하려고 TLS 1.3 핸드 셰이크에서 더미 암호 변경 사양(CCS - Change Cipher Spec) 메시지를 보냅니다.

이 옵션은 OpenSSL 1.1.1 이상에서만 사용할 수 있습니다.

버전 3.8에 추가.

ssl.OP_NO_COMPRESSION

SSL 채널에서 압축을 사용하지 않습니다. 응용 프로그램 프로토콜이 자체 압축 방법을 지원할 때 유용합니다.

이 옵션은 OpenSSL 1.0.0 이상에서만 사용할 수 있습니다.

버전 3.3에 추가.

class ssl.Options

OP_* 상수의 enum.IntFlag 컬렉션.

ssl.OP_NO_TICKET

클라이언트 측에서 세션 티켓을 요청하지 못하게 합니다.

버전 3.6에 추가.

ssl.HAS_ALPN

OpenSSL 라이브러리가 RFC 7301 [https://tools.ietf.org/html/rfc7301.html]에서 설명한 대로 응용 계층 프로토콜 협상(Application-Layer Protocol Negotiation) TLS 확장에 대한 지원을 기본 제공하는지 여부

버전 3.5에 추가.

ssl.HAS_NEVER_CHECK_COMMON_NAME

OpenSSL 라이브러리가 SCN(subject common name)을 검사하지 않는 지원을 기본 제공하고 SSLContext.hostname_checks_common_name가 쓰기 가능한지 아닌지.

버전 3.7에 추가.

ssl.HAS_ECDH

OpenSSL 라이브러리가 타원 곡선(Elliptic Curve) 기반 Diffie-Hellman 키 교환 지원을 기본 제공하는지 여부. 기능이 배포자에 의해 명시적으로 비활성화되어 있지 않은 한, 참이어야 합니다.

버전 3.3에 추가.

ssl.HAS_SNI

OpenSSL 라이브러리가 서버 이름 표시(Server Name Indication) 확장(RFC 6066 [https://tools.ietf.org/html/rfc6066.html]에 정의된 대로)에 대한 지원을 기본 제공하는지 여부.

버전 3.2에 추가.

ssl.HAS_NPN

OpenSSL 라이브러리가 Application Layer Protocol Negotiation [https://en.wikipedia.org/wiki/Application-Layer_Protocol_Negotiation]에 설명된 대로 NPN(Next Protocol Negotiation)에 대한 지원을 기본 제공하는지 여부. 참이면 SSLContext.set_npn_protocols() 메서드를 사용하여 지원할 프로토콜을 알릴 수 있습니다.

버전 3.3에 추가.

ssl.HAS_SSLv2

OpenSSL 라이브러리가 SSL 2.0 프로토콜 지원을 기본 제공하는지 여부

버전 3.7에 추가.

ssl.HAS_SSLv3

OpenSSL 라이브러리가 SSL 3.0 프로토콜 지원을 기본 제공하는지 여부

버전 3.7에 추가.

ssl.HAS_TLSv1

OpenSSL 라이브러리가 TLS 1.0 프로토콜 지원을 기본 제공하는지 여부

버전 3.7에 추가.

ssl.HAS_TLSv1_1

OpenSSL 라이브러리가 TLS 1.1 프로토콜 지원을 기본 제공하는지 여부

버전 3.7에 추가.

ssl.HAS_TLSv1_2

OpenSSL 라이브러리가 TLS 1.2 프로토콜 지원을 기본 제공하는지 여부

버전 3.7에 추가.

ssl.HAS_TLSv1_3

OpenSSL 라이브러리가 TLS 1.3 프로토콜 지원을 기본 제공하는지 여부

버전 3.7에 추가.

ssl.CHANNEL_BINDING_TYPES

지원되는 TLS 채널 바인딩 유형의 리스트. 이 리스트의 문자열은 SSLSocket.get_channel_binding()에 대한 인자로 사용될 수 있습니다.

버전 3.3에 추가.

ssl.OPENSSL_VERSION

인터프리터에 의해 로드된 OpenSSL 라이브러리의 버전 문자열:

>>> ssl.OPENSSL_VERSION
'OpenSSL 1.0.2k  26 Jan 2017'

버전 3.2에 추가.

ssl.OPENSSL_VERSION_INFO

OpenSSL 라이브러리에 대한 버전 정보를 나타내는 5개의 정수 튜플:

>>> ssl.OPENSSL_VERSION_INFO
(1, 0, 2, 11, 15)

버전 3.2에 추가.

ssl.OPENSSL_VERSION_NUMBER

단일 정수로 표현되는, OpenSSL 라이브러리의 원시 버전 번호:

>>> ssl.OPENSSL_VERSION_NUMBER
268443839
>>> hex(ssl.OPENSSL_VERSION_NUMBER)
'0x100020bf'

버전 3.2에 추가.

ssl.ALERT_DESCRIPTION_HANDSHAKE_FAILURE

ssl.ALERT_DESCRIPTION_INTERNAL_ERROR

ALERT_DESCRIPTION_*

RFC 5246 [https://tools.ietf.org/html/rfc5246.html] 및 기타의 경고 설명. IANA TLS Alert Registry [https://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6]에는 이 목록과 그 의미가 정의된 RFC에 대한 참조가 들어 있습니다.

SSLContext.set_servername_callback()에서 콜백 함수의 반환 값으로 사용됩니다.

버전 3.4에 추가.

class ssl.AlertDescription

ALERT_DESCRIPTION_* 상수의 enum.IntEnum 컬렉션.

버전 3.6에 추가.

Purpose.SERVER_AUTH

create_default_context()와 SSLContext.load_default_certs() 옵션. 이 값은 컨텍스트가 웹 서버를 인증하는 데 사용될 수 있음을 나타냅니다 (따라서 클라이언트 측 소켓을 만드는 데 사용됩니다).

버전 3.4에 추가.

Purpose.CLIENT_AUTH

create_default_context() 와 SSLContext.load_default_certs() 옵션. 이 값은 컨텍스트가 웹 클라이언트를 인증하는 데 사용될 수 있음을 나타냅니다 (따라서 서버 측 소켓을 만드는 데 사용됩니다).

버전 3.4에 추가.

class ssl.SSLErrorNumber

SSL_ERROR_* 상수의 enum.IntEnum 컬렉션.

버전 3.6에 추가.

class ssl.TLSVersion

SSLContext.maximum_version과 SSLContext.minimum_version 용 SSL과 TLS 버전의 enum.IntEnum 컬렉션.

버전 3.7에 추가.

TLSVersion.MINIMUM_SUPPORTED

TLSVersion.MAXIMUM_SUPPORTED

지원되는 SSL 또는 TLS 버전의 최소 또는 최대. 이것들은 마법 상수(magic constant)입니다. 이들의 값은 사용 가능한 가장 낮거나 높은 TLS/SSL 버전을 반영하지 않습니다.

TLSVersion.SSLv3

TLSVersion.TLSv1

TLSVersion.TLSv1_1

TLSVersion.TLSv1_2

TLSVersion.TLSv1_3

SSL 3.0 에서 TLS 1.3.

SSL 소켓

class ssl.SSLSocket(socket.socket)

SSL 소켓은 다음과 같은 소켓 객체 메서드를 제공합니다:

accept()

bind()

close()

connect()

detach()

fileno()

getpeername(), getsockname()

getsockopt(), setsockopt()

gettimeout(), settimeout(), setblocking()

listen()

makefile()

recv(), recv_into() (그러나 0이 아닌 flags 인자를 전달하는 것은 허용되지 않습니다)

send(), sendall() (같은 제한 있음)

sendfile() (그러나 os.sendfile는 평문 소켓에만 사용되며, 그렇지 않으면 send()가 사용됩니다)

shutdown()

그러나 SSL (및 TLS) 프로토콜은 TCP 위에 자체 프레임을 가지고 있으므로, SSL 소켓 추상화는 특정 측면에서 정상적인 OS 수준 소켓의 사양에서 벗어날 수 있습니다. 특히 비 블로킹 소켓에 대한 참고 사항을 보십시오.

SSLSocket의 인스턴스는 SSLContext.wrap_socket() 메서드를 사용하여 민들어야 합니다.

버전 3.5에서 변경: sendfile() 메서드가 추가되었습니다.

버전 3.5에서 변경: shutdown()은 바이트가 수신되거나 전송될 때마다 소켓 시간제한을 재설정하지 않습니다. 소켓 시간제한은 이제 shutdown의 최대 총 지속 시간입니다.

버전 3.6부터 폐지: SSLSocket 인스턴스를 직접 만드는 것은 폐지되었습니다, SSLContext.wrap_socket()를 사용하여 소켓을 감싸십시오.

버전 3.7에서 변경: SSLSocket 인스턴스는 wrap_socket()로 만들어야 합니다. 이전 버전에서는 직접 인스턴스를 만들 수 있었습니다. 이것은 문서로 만들어지거나 공식적으로 지원된 적이 없습니다.

SSL 소켓에는 다음과 같은 추가 메서드와 어트리뷰트도 있습니다:

SSLSocket.read(len=1024, buffer=None)

SSL 소켓에서 최대 len 바이트의 데이터를 읽고 그 결과를 bytes 인스턴스로 반환합니다. buffer가 지정되면, 대신 버퍼로 읽어 들이고, 읽은 바이트 수를 반환합니다.

소켓이 비 블로킹이고 읽기가 블록 되려고 하면 SSLWantReadError 나 SSLWantWriteError를 발생시킵니다.

언제나 재협상이 가능하므로, read()를 호출해도 쓰기 연산이 발생할 수 있습니다.

버전 3.5에서 변경: 소켓 시간제한은 바이트가 수신되거나 전송될 때마다 재설정되지 않습니다. 소켓 시간제한은 이제 최대 len 바이트까지 읽을 때까지의 최대 총 지속 시간입니다.

버전 3.6부터 폐지: read() 대신 recv()를 사용하십시오.

SSLSocket.write(buf)

SSL 소켓에 buf를 기록하고, 기록한 바이트 수를 돌려줍니다. buf 인자는 버퍼 인터페이스를 지원하는 객체여야 합니다.

소켓이 비 블로킹이고, 쓰기가 블록 하려고 하면 SSLWantReadError 나 SSLWantWriteError를 발생시킵니다.

언제나 재협상이 가능하므로, write()를 호출해도 읽기 연산이 발생할 수 있습니다.

버전 3.5에서 변경: 소켓 시간제한은 바이트가 수신되거나 전송될 때마다 재설정되지 않습니다. 소켓 시간제한은 이제 buf를 쓰는 최대 총 지속 시간입니다.

버전 3.6부터 폐지: write() 대신 send()를 사용하십시오.

참고

read() 과 write() 메서드는 암호화되지 않은 응용 프로그램 수준 데이터를 읽고 쓰고 그것을 암호화되고 와이어 수준(wire-level) 데이터로 복호화/암호화하는 저수준 메서드입니다. 이 메서드는 활성화된 SSL 연결, 즉, 핸드 셰이크가 완료되고, SSLSocket.unwrap()가 호출되지 않은 것이 필요합니다.

일반적으로 이러한 메서드 대신 recv() 와 send()와 같은 소켓 API 메서드를 사용해야합니다.

SSLSocket.do_handshake()

SSL 설정 핸드 셰이크를 수행합니다.

버전 3.4에서 변경: 핸드 셰이크 메서드는 소켓의 context의 check_hostname 어트리뷰트가 참일 때 match_hostname()도 수행합니다.

버전 3.5에서 변경: 소켓 시간제한은 바이트가 수신되거나 전송될 때마다 재설정되지 않습니다. 소켓 시간제한은 이제 핸드 셰이크의 최대 지속 시간입니다.

버전 3.7에서 변경: 호스트 이름이나 IP 주소는 핸드 셰이크 중 OpenSSL에서 일치합니다. 함수 match_hostname()는 더는 사용되지 않습니다. OpenSSL이 호스트 이름이나 IP 주소를 거절할 경우, 핸드 셰이크가 일찍 중단되고 TLS 경고 메시지가 상대방에게 전송됩니다.

SSLSocket.getpeercert(binary_form=False)

연결의 다른 끝의 피어에 대한 인증서가 없으면 None을 반환합니다. SSL 핸드 셰이크가 아직 수행되지 않았으면, ValueError를 발생시킵니다.

binary_form 매개 변수가 False이고, 피어에서 인증서를 받았으면, 이 메서드는 dict 인스턴스를 반환합니다. 인증서의 유효성을 검사하지 않았으면, 딕셔너리는 비어 있습니다. 인증서의 유효성을 검사했으면 subject(인증서가 발행된 주체)와 issuer(인증서를 발급한 주체)와 같은 몇 가지 키가 있는 dict를 반환합니다. 인증서가 SAN(Subject Alternative Name) 확장(RFC 3280 [https://tools.ietf.org/html/rfc3280.html] 참조)의 인스턴스를 포함하면 딕셔너리에 subjectAltName 키도 있습니다.

subject 와 issuer 필드는 각 필드에 대한 인증서의 데이터 구조에 제공된 RDN(relative distinguished name)의 시퀀스를 포함하는 튜플이며, 각 RDN은 이름-값 쌍의 시퀀스입니다. 실제 예를 들어 보겠습니다:

{'issuer': ((('countryName', 'IL'),),
            (('organizationName', 'StartCom Ltd.'),),
            (('organizationalUnitName',
              'Secure Digital Certificate Signing'),),
            (('commonName',
              'StartCom Class 2 Primary Intermediate Server CA'),)),
 'notAfter': 'Nov 22 08:15:19 2013 GMT',
 'notBefore': 'Nov 21 03:09:52 2011 GMT',
 'serialNumber': '95F0',
 'subject': ((('description', '571208-SLe257oHY9fVQ07Z'),),
             (('countryName', 'US'),),
             (('stateOrProvinceName', 'California'),),
             (('localityName', 'San Francisco'),),
             (('organizationName', 'Electronic Frontier Foundation, Inc.'),),
             (('commonName', '*.eff.org'),),
             (('emailAddress', 'hostmaster@eff.org'),)),
 'subjectAltName': (('DNS', '*.eff.org'), ('DNS', 'eff.org')),
 'version': 3}

참고

특정 서비스를 위해 인증서를 유효성 검사하려면, match_hostname() 함수를 사용할 수 있습니다.

binary_form 매개 변수가 True이고, 인증서가 제공되었으면, 이 메서드는 전체 인증서의 DER-인코딩 형식을 바이트 시퀀스로 반환하고, 피어가 인증서를 제공하지 않았으면 None을 반환합니다. 피어가 인증서를 제공하는지는 SSL 소켓의 역할에 따라 다릅니다:

클라이언트 SSL 소켓의 경우, 서버는 유효성 검사가 필요한지에 관계없이 항상 인증서를 제공합니다.

서버 SSL 소켓의 경우, 클라이언트는 서버가 요청할 때만 인증서를 제공합니다; 따라서 CERT_NONE(CERT_OPTIONAL 나 CERT_REQUIRED 대신)을 사용하면 getpeercert()는 None을 반환합니다.

버전 3.2에서 변경: 반환된 딕셔너리에는 issuer 와 notBefore와 같은 추가 항목이 포함됩니다.

버전 3.4에서 변경: 핸드 셰이크가 완료되지 않았으면 ValueError가 발생합니다. 반환된 딕셔너리에는 crlDistributionPoints, caIssuers 및 OCSP URI와 같은 추가 X509v3 확장 항목이 포함됩니다.

버전 3.7.6에서 변경: IPv6 address strings no longer have a trailing new line.

SSLSocket.cipher()

사용되는 사이퍼의 이름, 그것의 사용을 정의하는 SSL 프로토콜의 버전 및 사용되는 비밀 비트의 수를 포함하는 3-튜플을 반환합니다. 연결이 이루어지지 않았으면 None을 반환합니다.

SSLSocket.shared_ciphers()

핸드 셰이크 중에 클라이언트에 의해 공유되는 사이퍼의 리스트를 돌려줍니다. 반환된 리스트의 각 항목은 사이퍼의 이름, 그것의 사용을 정의하는 SSL 프로토콜의 버전 및 사이퍼가 사용하는 비밀 비트의 수를 포함하는 3-튜플입니다. 연결이 이루어지지 않았거나 소켓이 클라이언트 소켓이면 shared_ciphers()는 None을 반환합니다.

버전 3.5에 추가.

SSLSocket.compression()

사용되는 압축 알고리즘을 문자열로 반환하거나, 연결이 압축되지 않으면 None을 반환합니다.

상위-수준 프로토콜이 자체 압축 메커니즘을 지원하면, OP_NO_COMPRESSION을 사용하여 SSL-수준 압축을 비활성화할 수 있습니다.

버전 3.3에 추가.

SSLSocket.get_channel_binding(cb_type="tls-unique")

현재 연결에 대한 채널 바인딩 데이터를 바이트열 객체로 가져옵니다. 연결되어 있지 않거나 핸드 셰이크가 완료되지 않았으면 None을 반환합니다.

cb_type 매개 변수를 사용하여 원하는 채널 바인딩 유형을 선택할 수 있습니다. 유효한 채널 바인딩 유형은 CHANNEL_BINDING_TYPES 리스트에 나열됩니다. 현재는 RFC 5929 [https://tools.ietf.org/html/rfc5929.html]가 정의한 ‘tls-unique’ 채널 바인딩만 지원됩니다. 지원되지 않는 채널 바인딩 유형이 요청되면 ValueError가 발생합니다.

버전 3.3에 추가.

SSLSocket.selected_alpn_protocol()

TLS 핸드 셰이크 중에 선택된 프로토콜을 반환합니다. SSLContext.set_alpn_protocols()가 호출되지 않았거나, 상대방이 ALPN을 지원하지 않거나, 이 소켓이 클라이언트가 제안한 프로토콜 중 어떤 것도 지원하지 않거나, 핸드 셰이크가 아직 발생하지 않았으면 None이 반환됩니다.

버전 3.5에 추가.

SSLSocket.selected_npn_protocol()

TLS/SSL 핸드 셰이크 중에 선택된 상위-수준의 프로토콜을 반환합니다. SSLContext.set_npn_protocols()가 호출되지 않았거나, 상대방이 NPN을 지원하지 않거나, 핸드 셰이크가 아직 발생하지 않았으면 None을 반환합니다.

버전 3.3에 추가.

SSLSocket.unwrap()

SSL 종료 핸드 셰이크를 수행해서 하부 소켓에서 TLS 계층을 제거하고, 하부 소켓 객체를 반환합니다. 이것은 연결을 통한 암호화된 연산에서 암호화되지 않은 것으로 이동하는 데 사용할 수 있습니다. 원래 소켓이 아닌 반환된 소켓을 연결의 다른 쪽과 계속 통신하기 위해 항상 사용해야 합니다.

SSLSocket.verify_client_post_handshake()

TLS 1.3 클라이언트로부터 PHA(post-handshake authentication)를 요청합니다. PHA는 양쪽에서 PHA가 활성화된 초기 TLS 핸드 셰이크 후에 서버 측 소켓에서 TLS 1.3 연결에 대해서만 시작할 수 있습니다, SSLContext.post_handshake_auth를 참조하세요.

이 메서드는 즉시 인증서 교환을 수행하지 않습니다. 서버 측은 다음 쓰기 이벤트 중에 CertificateRequest를 보내고 클라이언트가 다음 읽기 이벤트에서 인증서로 응답할 것으로 기대합니다.

사전 조건이 모두 충족되지 않으면 (예를 들어, TLS 1.3이 아니거나 PHA가 활성화되지 않았을 때), SSLError가 발생합니다.

참고

OpenSSL 1.1.1과 TLS 1.3이 활성화된 경우에만 사용할 수 있습니다. TLS 1.3 지원이 없으면, 이 메서드는 NotImplementedError를 발생시킵니다.

버전 3.7.1에 추가.

SSLSocket.version()

연결에서 협상한 실제 SSL 프로토콜 버전을 문자열로 반환하거나, 보안 연결이 이루어지지 않았으면 None을 반환합니다. 이 글을 쓰는 시점에서, 가능한 반환 값은 "SSLv2", "SSLv3", "TLSv1", "TLSv1.1" 및 "TLSv1.2"입니다. 최근의 OpenSSL 버전은 더욱더 많은 반환 값을 정의할 수 있습니다.

버전 3.5에 추가.

SSLSocket.pending()

접속에 계류 중인, 읽기용으로 이미 복호화된 바이트의 수를 돌려줍니다.

SSLSocket.context

이 SSL 소켓이 연결된 SSLContext 객체. SSL 소켓이 폐지된 wrap_socket() 함수(SSLContext.wrap_socket()이 아니라)를 사용하여 만들어졌으면, 이것은 이 SSL 소켓에 대해 만든 사용자 정의 컨텍스트 객체입니다.

버전 3.2에 추가.

SSLSocket.server_side

서버 측 소켓에서는 True이고 클라이언트 측 소켓에서는 False 인 논릿값.

버전 3.2에 추가.

SSLSocket.server_hostname

서버의 호스트 이름: str 형, 또는 서버 측 소켓이거나 호스트 이름이 생성자에 지정되지 않았으면 None.

버전 3.2에 추가.

버전 3.7에서 변경: 어트리뷰트는 이제 항상 ASCII 텍스트입니다. server_hostname이 국제화 된 도메인 이름(IDN)일 때, 이 어트리뷰트는 이제 U-레이블 형식("pythön.org") 대신 A-레이블 형식("xn--pythn-mua.org")을 저장합니다.

SSLSocket.session

이 SSL 연결을 위한 SSLSession. 이 세션은 TLS 핸드 셰이크가 수행된 후 클라이언트와 서버 측 소켓에서 사용할 수 있습니다. 클라이언트 소켓의 경우 세션을 다시 사용하기 위해 do_handshake()가 호출되기 전에 세션을 설정할 수 있습니다.

버전 3.6에 추가.

SSLSocket.session_reused

버전 3.6에 추가.

SSL 컨텍스트

버전 3.2에 추가.

SSL 컨텍스트는 SSL 구성 옵션, 인증서 및 개인 키와 같이 단일 SSL 연결보다 수명이 긴 다양한 데이터를 보관합니다. 또한, 같은 클라이언트의 반복된 연결 속도를 높이기 위해 서버 측 소켓에 대한 SSL 세션 캐시를 관리합니다.

class ssl.SSLContext(protocol=PROTOCOL_TLS)

새 SSL 컨텍스트를 만듭니다. protocol를 전달할 수 있는데, 이 모듈에 정의된 PROTOCOL_* 상수 중 하나여야 합니다. 매개 변수는 사용할 SSL 프로토콜의 버전을 지정합니다. 일반적으로 서버는 특정 프로토콜 버전을 선택하고, 클라이언트는 서버의 선택에 적응해야 합니다. 대부분의 버전은 다른 버전과 상호 운용할 수 없습니다. 지정하지 않으면, 기본값은 PROTOCOL_TLS입니다; 다른 버전과의 호환성이 가장 뛰어납니다.

다음은 클라이언트의 어느 버전(행)이 서버의 어떤 버전(열)에 연결할 수 있는지 보여주는 표입니다:

클라이언트 / 서버

SSLv2

SSLv3

TLS 3

TLSv1

TLSv1.1

TLSv1.2

SSLv2

yes

no

no 1

no

no

no

SSLv3

no

yes

no 2

no

no

no

TLS (SSLv23) 3

no 1

no 2

yes

yes

yes

yes

TLSv1

no

no

yes

yes

no

no

TLSv1.1

no

no

yes

no

yes

no

TLSv1.2

no

no

yes

no

no

yes

각주

1(1,2)

SSLContext는 기본적으로 OP_NO_SSLv2로 SSLv2를 비활성화합니다.

2(1,2)

SSLContext는 기본적으로 OP_NO_SSLv3으로 SSLv3을 비활성화합니다.

3(1,2)

TLS 1.3 프로토콜은 OpenSSL >= 1.1.1에서 PROTOCOL_TLS로 사용할 수 있습니다. TLS 1.3만을 위한 전용 PROTOCOL 상수는 없습니다.

더 보기

create_default_context()는 ssl 모듈이 주어진 목적을 위한 보안 설정을 선택할 수 있게 합니다.

버전 3.6에서 변경: 컨텍스트는 안전한 기본값으로 생성됩니다. OP_NO_COMPRESSION, OP_CIPHER_SERVER_PREFERENCE, OP_SINGLE_DH_USE, OP_SINGLE_ECDH_USE, OP_NO_SSLv2 (PROTOCOL_SSLv2 제외) 및 OP_NO_SSLv3 (PROTOCOL_SSLv3 제외) 옵션은 기본적으로 설정됩니다. 초기 사이퍼 스위트 리스트에는 HIGH 사이퍼만 포함되고 NULL 사이퍼나 MD5 사이퍼는 포함되지 않습니다 (PROTOCOL_SSLv2 제외).

SSLContext 객체에는 다음과 같은 메서드와 어트리뷰트가 있습니다:

SSLContext.cert_store_stats()

로드된 X.509 인증서 수량, CA 인증서로 표시된 X.509 인증서 및 인증서 취소 목록(CRL)의 수에 대한 통계를 딕셔너리로 가져옵니다.

하나의 CA 인증서와 다른 인증서 하나를 가진 컨텍스트 예:

>>> context.cert_store_stats()
{'crl': 0, 'x509_ca': 1, 'x509': 2}

버전 3.4에 추가.

SSLContext.load_cert_chain(certfile, keyfile=None, password=None)

개인 키와 해당 인증서를 로드합니다. certfile 문자열은 인증서뿐만 아니라 인증서의 신뢰성을 확보하는 데 필요한 여러 CA 인증서가 포함된 PEM 형식의 단일 파일 경로여야 합니다. keyfile 문자열이 있으면 개인 키가 들어있는 파일을 가리켜야 합니다. 그렇지 않으면 개인 키도 certfile에서 가져옵니다. 인증서가 certfile에 저장되는 방법에 대한 자세한 내용은 인증서의 논의를 참조하십시오.

password 인자는 개인 키의 복호화를 위한 암호를 얻기 위해 호출하는 함수가 될 수 있습니다. 개인 키가 암호화되어있고 암호가 필요한 경우에만 호출됩니다. 인자 없이 호출되며, 문자열, 바이트열 또는 bytearray를 반환해야 합니다. 반환 값이 문자열이면 키를 해독하기 전에 UTF-8로 인코딩됩니다. 또는 문자열, 바이트열 또는 bytearray 값을 password 인자로 직접 제공할 수 있습니다. 개인 키가 암호화되지 않고 암호가 필요 없으면 무시됩니다.

password 인자가 지정되지 않고 암호가 필요하면, OpenSSL의 기본 암호 프롬프트 메커니즘을 사용하여 대화식으로 사용자에게 암호를 묻습니다.

개인 키가 인증서와 일치하지 않으면 SSLError가 발생합니다.

버전 3.3에서 변경: 새로운 선택적 인자 password.

SSLContext.load_default_certs(purpose=Purpose.SERVER_AUTH)

기본 위치에서 기본 “인증 기관”(CA) 인증서 집합을 로드합니다. 윈도우에서는 CA 와 ROOT 시스템 저장소에서 CA 인증서를 로드합니다. 다른 시스템에서는 SSLContext.set_default_verify_paths()를 호출합니다. 장래에 이 메서드는 다른 위치에서도 CA 인증서를 로드할 수 있습니다.

purpose 플래그는 로드되는 CA 인증서의 종류를 지정합니다. 기본 설정인 Purpose.SERVER_AUTH는 TLS 웹 서버 인증 (클라이언트 측 소켓)용으로 표시되고 신뢰 되는 인증서를 로드합니다. Purpose.CLIENT_AUTH는 서버 측에서 클라이언트 인증서 확인을 위한 CA 인증서를 로드합니다.

버전 3.4에 추가.

SSLContext.load_verify_locations(cafile=None, capath=None, cadata=None)

verify_mode가 CERT_NONE가 아닐 때, 다른 피어의 인증서를 확인하는 데 사용되는 “인증 기관” (CA) 인증서 집합을 로드합니다. cafile 나 capath 중 적어도 하나는 지정해야 합니다.

이 메서드는 PEM 이나 DER 형식으로 인증서 해지 목록(CRL)을 로드할 수도 있습니다. CRL을 사용하려면 SSLContext.verify_flags를 올바르게 구성해야 합니다.

cafile 문자열이 있으면 이어붙인 PEM 형식의 CA 인증서 파일 경로입니다. 이 파일에 인증서를 정렬하는 방법에 대한 자세한 내용은 인증서의 논의를 참조하십시오.

capath 문자열이 있으면, OpenSSL 특정 배치 [https://www.openssl.org/docs/manmaster/man3/SSL_CTX_load_verify_locations.html]를 따르는 PEM 형식의 여러 CA 인증서를 포함하는 디렉터리에 대한 경로입니다.

cadata 객체가 있으면, 하나 이상의 PEM-인코딩된 인증서의 ASCII 문자열이거나 DER-인코딩된 인증서의 바이트열류 객체입니다. capath와 마찬가지로 PEM-인코딩된 인증서 주위에 추가한 줄은 무시되지만 적어도 하나의 인증서가 있어야 합니다.

버전 3.4에서 변경: 새로운 선택적 인자 cadata

SSLContext.get_ca_certs(binary_form=False)

로드된 “인증 기관” (CA) 인증서 목록을 가져옵니다. binary_form 매개 변수가 False면 각 리스트 항목은 SSLSocket.getpeercert()의 출력과 같은 딕셔너리입니다. 그렇지 않으면, 이 메서드는 DER-인코딩된 인증서의 리스트를 반환합니다. 반환된 리스트에는 인증서가 SSL 연결이 요청하고 로드되지 않는 한 capath의 인증서가 포함되어 있지 않습니다.

참고

capath 디렉터리의 인증서는 적어도 한 번 이상 사용하지 않으면 로드되지 않습니다.

버전 3.4에 추가.

SSLContext.get_ciphers()

활성화된 사이퍼의 리스트를 가져옵니다. 리스트는 사이퍼 우선순위 순입니다. SSLContext.set_ciphers()를 참조하십시오.

예제:

>>> ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
>>> ctx.set_ciphers('ECDHE+AESGCM:!ECDSA')
>>> ctx.get_ciphers()  # OpenSSL 1.0.x
[{'alg_bits': 256,
  'description': 'ECDHE-RSA-AES256-GCM-SHA384 TLSv1.2 Kx=ECDH     Au=RSA  '
                 'Enc=AESGCM(256) Mac=AEAD',
  'id': 50380848,
  'name': 'ECDHE-RSA-AES256-GCM-SHA384',
  'protocol': 'TLSv1/SSLv3',
  'strength_bits': 256},
 {'alg_bits': 128,
  'description': 'ECDHE-RSA-AES128-GCM-SHA256 TLSv1.2 Kx=ECDH     Au=RSA  '
                 'Enc=AESGCM(128) Mac=AEAD',
  'id': 50380847,
  'name': 'ECDHE-RSA-AES128-GCM-SHA256',
  'protocol': 'TLSv1/SSLv3',
  'strength_bits': 128}]

OpenSSL 1.1 이상에서 사이퍼 딕셔너리에는 다음과 같은 추가 필드가 포함됩니다:

>>> ctx.get_ciphers()  # OpenSSL 1.1+
[{'aead': True,
  'alg_bits': 256,
  'auth': 'auth-rsa',
  'description': 'ECDHE-RSA-AES256-GCM-SHA384 TLSv1.2 Kx=ECDH     Au=RSA  '
                 'Enc=AESGCM(256) Mac=AEAD',
  'digest': None,
  'id': 50380848,
  'kea': 'kx-ecdhe',
  'name': 'ECDHE-RSA-AES256-GCM-SHA384',
  'protocol': 'TLSv1.2',
  'strength_bits': 256,
  'symmetric': 'aes-256-gcm'},
 {'aead': True,
  'alg_bits': 128,
  'auth': 'auth-rsa',
  'description': 'ECDHE-RSA-AES128-GCM-SHA256 TLSv1.2 Kx=ECDH     Au=RSA  '
                 'Enc=AESGCM(128) Mac=AEAD',
  'digest': None,
  'id': 50380847,
  'kea': 'kx-ecdhe',
  'name': 'ECDHE-RSA-AES128-GCM-SHA256',
  'protocol': 'TLSv1.2',
  'strength_bits': 128,
  'symmetric': 'aes-128-gcm'}]

가용성: OpenSSL 1.0.2+.

버전 3.6에 추가.

SSLContext.set_default_verify_paths()

OpenSSL 라이브러리를 빌드할 때 정의된 파일 시스템 경로에서 기본 “인증 기관” (CA) 인증서 집합을 로드합니다. 불행히도, 이 메서드가 성공하는지를 쉽게 알 방법이 없습니다: 인증서를 찾을 수 없어도 에러가 반환되지 않습니다. 하지만 OpenSSL 라이브러리가 운영 체제 일부로 제공되면 올바르게 구성되었을 가능성이 큽니다.

SSLContext.set_ciphers(ciphers)

이 컨텍스트로 만들어진 소켓에 사용할 수 있는 사이퍼를 설정합니다. OpenSSL 사이퍼 리스트 형식 [https://www.openssl.org/docs/manmaster/man1/ciphers.html]의 문자열이어야 합니다. 사이퍼를 아무것도 선택할 수 없으면 (컴파일 시간 옵션이나 다른 구성이 지정된 모든 사이퍼의 사용을 금지하기 때문에), SSLError가 발생합니다.

참고

연결될 때, SSL 소켓의 SSLSocket.cipher() 메서드가 현재 선택된 사이퍼를 제공합니다.

OpenSSL 1.1.1에는 기본적으로 활성화된 TLS 1.3 사이퍼 스위트가 있습니다. 이 스위트는 set_ciphers()로 비활성화할 수 없습니다.

SSLContext.set_alpn_protocols(protocols)

SSL/TLS 핸드 셰이크 중에 소켓이 알려야 하는 프로토콜을 지정합니다. 우선순위에 따라 정렬된 ['http/1.1', 'spdy/2']와 같은 ASCII 문자열 리스트여야 합니다. 프로토콜 선택은 핸드 셰이크 중에 발생하며, RFC 7301 [https://tools.ietf.org/html/rfc7301.html]에 따라 처리됩니다. 성공적인 핸드 셰이크가 끝나면, SSLSocket.selected_alpn_protocol() 메서드는 합의된 프로토콜을 반환합니다.

This method will raise NotImplementedError if HAS_ALPN is False.

OpenSSL 1.1.0에서 1.1.0e는 양측이 ALPN을 지원하지만, 프로토콜에 합의할 수 없으면 핸드 셰이크를 중지하고 SSLError를 발생시킵니다. 1.1.0f+는 1.0.2처럼 동작합니다, SSLSocket.selected_alpn_protocol()는 None을 반환합니다.

버전 3.5에 추가.

SSLContext.set_npn_protocols(protocols)

SSL/TLS 핸드 셰이크 중에 소켓이 알려야 하는 프로토콜을 지정합니다. 우선순위에 따라 정렬된 ['http/1.1', 'spdy/2']와 같은 문자열 리스트여야 합니다. 프로토콜 선택은 핸드 셰이크 중에 발생하며, Application Layer Protocol Negotiation [https://en.wikipedia.org/wiki/Application-Layer_Protocol_Negotiation]에 따라 처리됩니다. 성공적인 핸드 셰이크가 끝나면, SSLSocket.selected_npn_protocol() 메서드는 합의된 프로토콜을 반환합니다.

This method will raise NotImplementedError if HAS_NPN is False.

버전 3.3에 추가.

SSLContext.sni_callback

TLS 클라이언트가 서버 이름 표시를 지정할 때 SSL/TLS 서버에서 TLS 클라이언트 Hello 핸드 셰이크 메시지를 받은 후 호출될 콜백 함수를 등록합니다. 서버 이름 표시 메커니즘은 RFC 6066 [https://tools.ietf.org/html/rfc6066.html] section 3 - Server Name Indication에서 지정됩니다.

SSLContext 당 하나의 콜백 만 설정할 수 있습니다. sni_callback이 None으로 설정되면 콜백이 비활성화됩니다. 이 함수를 호출하면 이전에 등록된 콜백이 비활성화됩니다.

콜백 함수는 세 개의 인자로 호출됩니다. 첫 번째는 ssl.SSLSocket이고, 두 번째는 클라이언트가 통신하려는 서버 이름을 나타내는 문자열(또는 TLS 클라이언트 Hello에 서버 이름이 없으면 None)이며, 세 번째 인자는 원래 SSLContext입니다. 서버 이름 인자는 텍스트입니다. 국제화된 도메인 이름의 경우, 서버 이름은 IDN A-레이블("xn--pythn-mua.org")입니다.

이 콜백은 일반적으로 ssl.SSLSocket의 SSLSocket.context 어트리뷰트를 서버 이름과 일치하는 인증서 체인을 나타내는 SSLContext 형의 새 객체로 변경하는 데 사용됩니다.

TLS 연결의 초기 협상 단계로 인해, SSLSocket.selected_alpn_protocol()과 SSLSocket.context와 같은 제한된 메서드와 어트리뷰트만 사용할 수 있습니다. SSLSocket.getpeercert(), SSLSocket.getpeercert(), SSLSocket.cipher() 및 SSLSocket.compress() 메서드는 TLS 연결이 TLS 클라이언트 Hello 이상으로 진행되었을 것을 요구하므로, 의미 있는 값을 반환하거나 안전하게 호출할 수 없습니다.

TLS 협상을 계속하려면 sni_callback 함수가 None을 반환해야 합니다. TLS 실패가 필요하면, 상수 ALERT_DESCRIPTION_*를 반환할 수 있습니다. 다른 반환 값은 ALERT_DESCRIPTION_INTERNAL_ERROR로 TLS 치명적인 에러를 발생시킵니다.

sni_callback 함수에서 예외가 발생하면, TLS 연결이 치명적인 TLS 경고 메시지 ALERT_DESCRIPTION_HANDSHAKE_FAILURE로 종료됩니다.

이 메서드는 OpenSSL 라이브러리가 빌드될 때 OPENSSL_NO_TLSEXT가 정의되었으면 NotImplementedError를 발생시킵니다.

버전 3.7에 추가.

SSLContext.set_servername_callback(server_name_callback)

이전 버전과의 호환성을 위해 유지되는 기존 API입니다. 가능하면, 대신 sni_callback을 사용해야 합니다. 주어진 server_name_callback은 sni_callback과 비슷하지만, 서버 호스트 이름이 IDN-인코딩된 국제화된 도메인 이름일 때 server_name_callback은 디코딩된 U-레이블("pythön.org")을 받습니다.

서버 이름에 디코딩 에러가 있으면, TLS 연결이 클라이언트로 ALERT_DESCRIPTION_INTERNAL_ERROR 치명적인 TLS 경고 메시지를 주면서 종료됩니다.

버전 3.4에 추가.

SSLContext.load_dh_params(dhfile)

Diffie-Hellman (DH) 키 교환을 위한 키 생성 매개 변수를 로드합니다. DH 키 교환을 사용하면 계산 자원(서버와 클라이언트 모두)을 희생하여 FS(forward secrecy)를 향상합니다. dhfile 매개 변수는 PEM 형식의 DH 매개 변수를 포함하는 파일의 경로여야 합니다.

이 설정은 클라이언트 소켓에는 적용되지 않습니다. OP_SINGLE_DH_USE 옵션을 사용하여 보안을 더 향상할 수도 있습니다.

버전 3.3에 추가.

SSLContext.set_ecdh_curve(curve_name)

타원 곡선(Elliptic Curve) 기반 Diffie-Hellman (ECDH) 키 교환을 위한 곡선 이름을 설정합니다. 보안성에 대한 논란의 여지는 있지만 ECDH는 일반 DH보다 상당히 빠릅니다. curve_name 매개 변수는 잘 알려진 타원 곡선을 설명하는 문자열이어야 합니다, 예를 들어, 널리 지원되는 곡선인 prime256v1.

이 설정은 클라이언트 소켓에는 적용되지 않습니다. OP_SINGLE_ECDH_USE 옵션을 사용하여 보안을 더 향상할 수도 있습니다.

HAS_ECDH가 False면 이 메서드를 사용할 수 없습니다.

버전 3.3에 추가.

더 보기

SSL/TLS & Perfect Forward Secrecy [https://vincent.bernat.im/en/blog/2011-ssl-perfect-forward-secrecy]

Vincent Bernat.

SSLContext.wrap_socket(sock, server_side=False, do_handshake_on_connect=True, suppress_ragged_eofs=True, server_hostname=None, session=None)

기존 파이썬 소켓 sock을 감싸고 SSLContext.sslsocket_class(기본값 SSLSocket)의 인스턴스를 반환합니다. 반환 된 SSL 소켓은 컨텍스트, 설정 및 인증서에 연결됩니다. sock은 SOCK_STREAM 소켓이어야합니다; 다른 소켓 유형은 지원되지 않습니다.

매개 변수 server_side는 서버 측과 클라이언트 측 동작 중 어느 것이 소켓에서 필요한지를 식별하는 논릿값입니다.

클라이언트 측 소켓의 경우, 컨텍스트 구성이 지연됩니다; 하부 소켓이 아직 연결되어 있지 않으면, connect()가 소켓에서 호출된 후 컨텍스트 생성이 수행됩니다. 서버 측 소켓의 경우, 소켓에 원격 피어가 없으면, 리스닝 소켓이라고 가정하고, 서버 측 SSL 감싸기는 accept() 메서드를 통해 받아들인 클라이언트 연결에 대해 자동으로 수행됩니다. 메서드는 SSLError를 발생시킬 수 있습니다.

클라이언트 연결에서, 선택적 매개 변수 server_hostname는 연결하려는 서비스의 호스트 이름을 지정합니다. 이를 통해 단일 서버는 HTTP 가상 호스트와 매우 흡사하게 서로 다른 인증서로 여러 SSL 기반 서비스를 호스팅 할 수 있습니다. server_side가 참일 때 server_hostname를 지정하면 ValueError가 발생합니다.

매개 변수 do_handshake_on_connect는 socket.connect()를 수행한 후 SSL 핸드 셰이크를 자동으로 수행할지, 또는 응용 프로그램이 SSLSocket.do_handshake() 메서드를 호출하여 명시적으로 호출할지를 지정합니다. SSLSocket.do_handshake()를 명시적으로 호출하면, 핸드 셰이크에 수반되는 소켓 I/O의 블로킹 동작을 프로그램에서 제어할 수 있습니다.

매개 변수 suppress_ragged_eofs는 SSLSocket.recv() 메서드가 연결의 다른 끝으로부터의 예기치 않은 EOF를 알리는 방법을 지정합니다. True(기본값)로 지정되면, 하부 소켓에서 발생한 예기치 않은 EOF 에러에 대한 응답으로 정상 EOF(빈 바이트열 객체)를 반환합니다. False면 예외를 호출자에게 다시 발생시킵니다.

session, session을 참조하십시오.

버전 3.5에서 변경: OpenSSL에 SNI가 없더라도 항상 server_hostname을 전달할 수 있습니다.

버전 3.6에서 변경: session 인자가 추가되었습니다.

버전 3.7에서 변경: 이 메서드는 하드 코드 된 SSLSocket 대신 SSLContext.sslsocket_class 인스턴스를 반환합니다.

SSLContext.sslsocket_class

The return type of SSLContext.wrap_socket(), defaults to SSLSocket. The attribute can be overridden on instance of class in order to return a custom subclass of SSLSocket.

버전 3.7에 추가.

SSLContext.wrap_bio(incoming, outgoing, server_side=False, server_hostname=None, session=None)

Wrap the BIO objects incoming and outgoing and return an instance of SSLContext.sslobject_class (default SSLObject). The SSL routines will read input data from the incoming BIO and write data to the outgoing BIO.

server_side, server_hostname 및 session 매개 변수는 SSLContext.wrap_socket()에서와 같은 의미입니다.

버전 3.6에서 변경: session 인자가 추가되었습니다.

버전 3.7에서 변경: 이 메서드는 하드 코드 된 SSLObject 대신 SSLContext.sslobject_class 인스턴스를 반환합니다.

SSLContext.sslobject_class

SSLContext.wrap_bio()의 반환형, 기본값은 SSLObject입니다. 이 어트리뷰트는 SSLObject의 사용자 정의 서브 클래스를 반환하기 위해 클래스의 인스턴스에서 재정의될 수 있습니다.

버전 3.7에 추가.

SSLContext.session_stats()

이 컨텍스트에 의해 생성되거나 관리된 SSL 세션에 대한 통계를 가져옵니다. 각 정보 조각 [https://www.openssl.org/docs/man1.1.0/ssl/SSL_CTX_sess_number.html]의 이름을 숫자 값에 매핑하는 딕셔너리가 반환됩니다. 예를 들어, 다음은 컨텍스트가 생성된 이후 세션 캐시의 총 적중 횟수 및 누락 횟수입니다:

>>> stats = context.session_stats()
>>> stats['hits'], stats['misses']
(0, 0)

SSLContext.check_hostname

Whether to match the peer cert’s hostname with match_hostname() in SSLSocket.do_handshake(). The context’s verify_mode must be set to CERT_OPTIONAL or CERT_REQUIRED, and you must pass server_hostname to wrap_socket() in order to match the hostname. Enabling hostname checking automatically sets verify_mode from CERT_NONE to CERT_REQUIRED. It cannot be set back to CERT_NONE as long as hostname checking is enabled. The PROTOCOL_TLS_CLIENT protocol enables hostname checking by default. With other protocols, hostname checking must be enabled explicitly.

예제:

import socket, ssl

context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
context.verify_mode = ssl.CERT_REQUIRED
context.check_hostname = True
context.load_default_certs()

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ssl_sock = context.wrap_socket(s, server_hostname='www.verisign.com')
ssl_sock.connect(('www.verisign.com', 443))

버전 3.4에 추가.

버전 3.7에서 변경: 호스트 이름 검사가 활성화되고 verify_mode가 CERT_NONE이면 이제 verify_mode가 CERT_REQUIRED로 자동 변경됩니다. 이전에는 같은 작업이 ValueError로 실패했을 것입니다.

참고

이 기능을 사용하려면 OpenSSL 0.9.8f 이상이 필요합니다.

SSLContext.maximum_version

지원되는 가장 높은 TLS 버전을 나타내는 TLSVersion 열거형 멤버. 기본값은 TLSVersion.MAXIMUM_SUPPORTED입니다. 어트리뷰트는 PROTOCOL_TLS, PROTOCOL_TLS_CLIENT 및 PROTOCOL_TLS_SERVER 이외의 프로토콜에 대해 읽기 전용입니다.

어트리뷰트 maximum_version, minimum_version 및 SSLContext.options는 모두 컨텍스트의 지원되는 SSL과 TLS 버전에 영향을 줍니다. 구현은 부적합한 조합을 방지하지 못합니다. 예를 들어, options에 OP_NO_TLSv1_2가 있고 maximum_version이 TLSVersion.TLSv1_2로 설정된 컨텍스트는 TLS 1.2 연결을 이룰 수 없습니다.

참고

ssl 모듈을 OpenSSL 1.1.0g 이상으로 컴파일하지 않으면 이 어트리뷰트를 사용할 수 없습니다.

버전 3.7에 추가.

SSLContext.minimum_version

가장 낮은 지원 버전 또는 TLSVersion.MINIMUM_SUPPORTED이라는 것만 제외하면 SSLContext.maximum_version과 같습니다.

참고

ssl 모듈을 OpenSSL 1.1.0g 이상으로 컴파일하지 않으면 이 어트리뷰트를 사용할 수 없습니다.

버전 3.7에 추가.

SSLContext.options

이 컨텍스트에서 활성화된 SSL 옵션 집합을 나타내는 정수. 기본값은 OP_ALL이지만, OP_NO_SSLv2와 같은 다른 옵션을 함께 OR로 연결하여 지정할 수 있습니다.

참고

0.9.8m보다 오래된 OpenSSL 버전에서는, 옵션을 지우지는 못하고 설정만 할 수 있습니다. (해당 비트를 재설정하여) 옵션을 지우려고 하면 ValueError가 발생합니다.

버전 3.6에서 변경: SSLContext.options는 Options 플래그를 반환합니다.:

>>> ssl.create_default_context().options
<Options.OP_ALL|OP_NO_SSLv3|OP_NO_SSLv2|OP_NO_COMPRESSION: 2197947391>

SSLContext.post_handshake_auth

TLS 1.3 포스트 핸드 셰이크 클라이언트 인증을 사용합니다. 포스트 핸드 셰이크 인증은 기본적으로 사용되지 않으며 서버는 초기 핸드 셰이크 중에 TLS 클라이언트 인증서만 요청할 수 있습니다. 활성화되면, 서버는 핸드 셰이크 후에 언제든지 TLS 클라이언트 인증서를 요청할 수 있습니다.

클라이언트 측 소켓에서 활성화될 때, 클라이언트는 포스트 핸드 셰이크 인증을 지원하는 서버에 신호를 보냅니다.

서버 측 소켓에서 활성화될 때, SSLContext.verify_mode도 CERT_OPTIONAL이나 CERT_REQUIRED로 설정해야 합니다. 실제 클라이언트 인증서 교환은 SSLSocket.verify_client_post_handshake()가 호출되고 일부 I/O가 수행될 때까지 지연됩니다.

참고

OpenSSL 1.1.1과 TLS 1.3이 활성화될 때만 사용할 수 있습니다. TLS 1.3을 지원 없이는, 프로퍼티 값이 None이며 수정할 수 없습니다.

버전 3.7.1에 추가.

SSLContext.protocol

컨텍스트를 구성할 때 선택한 프로토콜 버전. 이 어트리뷰트는 읽기 전용입니다.

SSLContext.hostname_checks_common_name

check_hostname가 SAN(subject alternative name) 확장이 없을 때 인증서의 SCN(subject common name)을 유효성 검사하는 것으로 폴백 할지 아닐지 (기본값: 참)

참고

OpenSSL 1.1.0 이상에서만 쓰기 가능합니다.

버전 3.7에 추가.

SSLContext.verify_flags

인증서 유효성 검사 연산을 위한 플래그. VERIFY_CRL_CHECK_LEAF와 같은 플래그를 함께 OR로 연결하여 설정할 수 있습니다. 기본적으로 OpenSSL은 인증서 해지 목록(CRL)을 요구하지도 확인하지도 않습니다. openssl 버전 0.9.8+ 에서만 사용할 수 있습니다.

버전 3.4에 추가.

버전 3.6에서 변경: SSLContext.verify_flags는 VerifyFlags 플래그를 반환합니다.:

>>> ssl.create_default_context().verify_flags
<VerifyFlags.VERIFY_X509_TRUSTED_FIRST: 32768>

SSLContext.verify_mode

다른 피어의 인증서를 확인할지와 확인이 실패할 때 어떻게 해야 하는지를 나타냅니다. 이 어트리뷰트는 CERT_NONE, CERT_OPTIONAL 또는 CERT_REQUIRED 중 하나여야 합니다.

버전 3.6에서 변경: SSLContext.verify_mode는 VerifyMode 열거형을 반환합니다.:

>>> ssl.create_default_context().verify_mode
<VerifyMode.CERT_REQUIRED: 2>

인증서

인증서는 일반적으로 공개키/개인키 시스템 일부입니다. 이 시스템에서, 각 주체(principal)(시스템, 사람 또는 조직일 수 있습니다)에게는 고유한 두 부분으로 된 암호화 키가 지정됩니다. 열쇠의 한 부분은 공개(public)며, 공개키(public key)라고 불립니다; 다른 부분은 비밀로 유지되며, 개인키(private key)라고 합니다. 두 부분은 관련이 있습니다. 두 부분 중 하나를 사용하여 메시지를 암호화하면, 다른 부분으로 해독할 수 있고, 오직 다른 부분으로만 해독할 수 있습니다.

인증서에는 두 주체에 대한 정보가 들어 있습니다. 주체(subject)의 이름과 주체의 공개키가 들어 있습니다. 또한 발행자(issuer)라는 두 번째 주체의 진술을 포함하는데, 해당 주체(subject)는 자신이 주장하는 존재며, 실제로 공개키 또한 주체(subject)의 것이 맞는다는 내용입니다. 발행자의 진술은 발행자만이 알고 있는 발행자의 개인키로 서명됩니다. 그러나 누구든지 발행자의 공개키를 찾고 이를 사용하여 진술을 해독하고 인증서의 다른 정보와 비교함으로써 발행자의 진술을 확인할 수 있습니다. 또한, 인증서에는 유효 기간에 대한 정보가 들어 있습니다. 이것은 “notBefore”와 “notAfter”라고 하는 두 개의 필드로 표현됩니다.

파이썬에서 인증서를 사용할 때, 클라이언트나 서버는 인증서를 사용하여 자신이 누구인지 증명할 수 있습니다. 네트워크 연결의 다른 쪽은 인증서 생성을 요구받을 수도 있으며, 해당 인증서는 이러한 유효성 검사가 필요한 클라이언트나 서버를 만족하도록 유효성을 검사할 수 있습니다. 유효성 검증이 실패하면 연결 시도가 예외를 발생시키도록 설정할 수 있습니다. 유효성 검사는 하부 OpenSSL 프레임워크에 의해 자동으로 수행됩니다; 응용 프로그램은 그 메커니즘에 관심을 두지 않아도 됩니다. 그러나 응용 프로그램은 일반적으로 이 절차를 수행할 수 있도록 인증서 집합을 제공해야 합니다.

파이썬은 인증서를 포함하기 위해 파일을 사용합니다. 그들은 “PEM”(RFC 1422 [https://tools.ietf.org/html/rfc1422.html]를 참조하세요)으로 포맷해야 합니다. 머릿줄과 꼬리 줄로 감싼 base-64 로 인코딩된 형식입니다:

-----BEGIN CERTIFICATE-----
... (certificate in base64 PEM encoding) ...
-----END CERTIFICATE-----

인증서 체인

인증서를 포함하는 파이썬 파일에는 인증서 시퀀스가 포함될 수 있는데, 때로 인증서 체인(*certificate chain)이라고 부릅니다. 이 체인은 클라이언트 또는 서버 “당사자” 주체에 대한 특정 인증서로 시작해야 하며, 그다음에 그 인증서의 발행자에 대한 인증서가 오고, 그다음에 직전 인증서 발행자에 대한 인증서가 오는 식으로 이어지다가, 결국에는 자체 서명(self-signed) 인증서를 얻게 되는데, 주체와 발행자가 같은 인증서로 때로 루트 인증서라고도 부릅니다. 인증서는 인증서 파일에 함께 이어붙여야 합니다. 예를 들어, 서버 인증서에서 서버 인증서에 서명한 인증 기관의 인증서를 거쳐 인증 기관의 인증서를 발행한 기관의 루트 인증서에 이르는 세 개의 인증서 체인이 있다고 가정합시다:

-----BEGIN CERTIFICATE-----
... (certificate for your server)...
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
... (the certificate for the CA)...
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
... (the root certificate for the CA's issuer)...
-----END CERTIFICATE-----

CA 인증서

연결의 반대편의 인증서의 유효성 검사가 필요하면, 신뢰할 수 있는 각 발행자의 인증서 체인으로 채워진 “CA 인증서” 파일을 제공해야 합니다. 다시 말하지만, 이 파일은 단지 이러한 체인들을 함께 이어붙인 것입니다. 유효성 검사를 위해, 파이썬은 일치하는 파일에서 찾은 첫 번째 체인을 사용합니다. 플랫폼의 인증서 파일은 SSLContext.load_default_certs()를 호출하여 사용할 수 있습니다, 이는 create_default_context()로 자동으로 수행됩니다.

결합한 키와 인증서

종종 개인 키는 인증서와 같은 파일에 저장됩니다; 이럴 때, SSLContext.load_cert_chain()과 wrap_socket()에 대한 certfile 매개 변수만 전달하면 됩니다. 개인 키가 인증서와 함께 저장되면, 인증서 체인의 첫 번째 인증서보다 먼저 와야 합니다.:

-----BEGIN RSA PRIVATE KEY-----
... (private key in base64 encoding) ...
-----END RSA PRIVATE KEY-----
-----BEGIN CERTIFICATE-----
... (certificate in base64 PEM encoding) ...
-----END CERTIFICATE-----

자체 서명 인증서

SSL-암호화된 연결 서비스를 제공하는 서버를 만들려면, 해당 서비스에 대한 인증서를 얻어야 합니다. 인증 기관에서 사는 등 다양한 방법으로 적절한 인증서를 얻을 수 있습니다. 또 다른 일반적인 관행은 자체 서명 인증서를 생성하는 것입니다. 이렇게 하는 가장 간단한 방법은 OpenSSL 패키지에서 다음과 같은 방법을 사용하는 것입니다:

% openssl req -new -x509 -days 365 -nodes -out cert.pem -keyout cert.pem
Generating a 1024 bit RSA private key
.......++++++
.............................++++++
writing new private key to 'cert.pem'
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [AU]:US
State or Province Name (full name) [Some-State]:MyState
Locality Name (eg, city) []:Some City
Organization Name (eg, company) [Internet Widgits Pty Ltd]:My Organization, Inc.
Organizational Unit Name (eg, section) []:My Group
Common Name (eg, YOUR name) []:myserver.mygroup.myorganization.com
Email Address []:ops@myserver.mygroup.myorganization.com
%

자체 서명 인증서의 단점은 그 자신이 루트 인증서이고, 아무도 그들의 알려진(그리고 신뢰할 수 있는) 루트 인증서의 캐시에 이 인증서를 갖고 있지 않다는 것입니다.

예제

SSL 지원 검사하기

파이썬 설치에 SSL 지원이 있는지를 검사하려면, 사용자 코드는 다음과 같은 관용구를 사용해야 합니다:

try:
    import ssl
except ImportError:
    pass
else:
    ...  # do something that requires SSL support

클라이언트 측 연산

이 예제는 자동 인증서 확인을 포함하여 클라이언트 소켓에 대해 권장되는 보안 설정을 사용하여 SSL 컨텍스트를 만듭니다:

>>> context = ssl.create_default_context()

보안 설정을 직접 조정하려면, 처음부터 컨텍스트를 만들 수 있습니다 (그러나 올바른 설정을 얻지 못할 수도 있습니다):

>>> context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
>>> context.load_verify_locations("/etc/ssl/certs/ca-bundle.crt")

(이 코드 조각은 운영 체제가 모든 CA 인증서 번들을 /etc/ssl/certs/ca-bundle.crt에 배치한다고 가정합니다; 그렇지 않으면, 에러가 발생하고 위치를 조정해야 합니다)

The PROTOCOL_TLS_CLIENT protocol configures the context for cert validation and hostname verification. verify_mode is set to CERT_REQUIRED and check_hostname is set to True. All other protocols create SSL contexts with insecure defaults.

When you use the context to connect to a server, CERT_REQUIRED and check_hostname validate the server certificate: it ensures that the server certificate was signed with one of the CA certificates, checks the signature for correctness, and verifies other properties like validity and identity of the hostname:

>>> conn = context.wrap_socket(socket.socket(socket.AF_INET),
...                            server_hostname="www.python.org")
>>> conn.connect(("www.python.org", 443))

그런 다음 인증서를 가져올 수 있습니다:

>>> cert = conn.getpeercert()

시각적인 검사는 인증서가 원하는 서비스(즉, HTTPS 호스트 www.python.org)를 식별함을 보여줍니다:

>>> pprint.pprint(cert)
{'OCSP': ('http://ocsp.digicert.com',),
 'caIssuers': ('http://cacerts.digicert.com/DigiCertSHA2ExtendedValidationServerCA.crt',),
 'crlDistributionPoints': ('http://crl3.digicert.com/sha2-ev-server-g1.crl',
                           'http://crl4.digicert.com/sha2-ev-server-g1.crl'),
 'issuer': ((('countryName', 'US'),),
            (('organizationName', 'DigiCert Inc'),),
            (('organizationalUnitName', 'www.digicert.com'),),
            (('commonName', 'DigiCert SHA2 Extended Validation Server CA'),)),
 'notAfter': 'Sep  9 12:00:00 2016 GMT',
 'notBefore': 'Sep  5 00:00:00 2014 GMT',
 'serialNumber': '01BB6F00122B177F36CAB49CEA8B6B26',
 'subject': ((('businessCategory', 'Private Organization'),),
             (('1.3.6.1.4.1.311.60.2.1.3', 'US'),),
             (('1.3.6.1.4.1.311.60.2.1.2', 'Delaware'),),
             (('serialNumber', '3359300'),),
             (('streetAddress', '16 Allen Rd'),),
             (('postalCode', '03894-4801'),),
             (('countryName', 'US'),),
             (('stateOrProvinceName', 'NH'),),
             (('localityName', 'Wolfeboro'),),
             (('organizationName', 'Python Software Foundation'),),
             (('commonName', 'www.python.org'),)),
 'subjectAltName': (('DNS', 'www.python.org'),
                    ('DNS', 'python.org'),
                    ('DNS', 'pypi.org'),
                    ('DNS', 'docs.python.org'),
                    ('DNS', 'testpypi.org'),
                    ('DNS', 'bugs.python.org'),
                    ('DNS', 'wiki.python.org'),
                    ('DNS', 'hg.python.org'),
                    ('DNS', 'mail.python.org'),
                    ('DNS', 'packaging.python.org'),
                    ('DNS', 'pythonhosted.org'),
                    ('DNS', 'www.pythonhosted.org'),
                    ('DNS', 'test.pythonhosted.org'),
                    ('DNS', 'us.pycon.org'),
                    ('DNS', 'id.python.org')),
 'version': 3}

이제 SSL 채널이 설정되고 인증서가 확인되었습니다, 서버와 대화할 수 있습니다:

>>> conn.sendall(b"HEAD / HTTP/1.0\r\nHost: linuxfr.org\r\n\r\n")
>>> pprint.pprint(conn.recv(1024).split(b"\r\n"))
[b'HTTP/1.1 200 OK',
 b'Date: Sat, 18 Oct 2014 18:27:20 GMT',
 b'Server: nginx',
 b'Content-Type: text/html; charset=utf-8',
 b'X-Frame-Options: SAMEORIGIN',
 b'Content-Length: 45679',
 b'Accept-Ranges: bytes',
 b'Via: 1.1 varnish',
 b'Age: 2188',
 b'X-Served-By: cache-lcy1134-LCY',
 b'X-Cache: HIT',
 b'X-Cache-Hits: 11',
 b'Vary: Cookie',
 b'Strict-Transport-Security: max-age=63072000; includeSubDomains',
 b'Connection: close',
 b'',
 b'']

아래의 보안 고려 사항의 논의를 참조하십시오.

서버 측 연산

서버 연산의 경우, 일반적으로 서버 인증서와 개인 키가 각각 파일에 있어야 합니다. 먼저 클라이언트가 여러분의 신원을 확인할 수 있도록 키와 인증서가 있는 컨텍스트를 만듭니다. 그런 다음 소켓을 열고, 포트에 바인드 하고, listen()을 호출한 다음 클라이언트가 연결하기를 기다립니다:

import socket, ssl

context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
context.load_cert_chain(certfile="mycertfile", keyfile="mykeyfile")

bindsocket = socket.socket()
bindsocket.bind(('myaddr.mydomain.com', 10023))
bindsocket.listen(5)

클라이언트가 연결하면, 소켓에서 accept()를 호출하여 다른 쪽 끝과 연결된 새 소켓을 얻고, 컨텍스트의 SSLContext.wrap_socket() 메서드를 사용하여 연결을 위한 서버 측 SSL 소켓을 만듭니다.:

while True:
    newsocket, fromaddr = bindsocket.accept()
    connstream = context.wrap_socket(newsocket, server_side=True)
    try:
        deal_with_client(connstream)
    finally:
        connstream.shutdown(socket.SHUT_RDWR)
        connstream.close()

그런 다음 connstream에서 데이터를 읽고 클라이언트와 작업을 마칠 때까지 (또는 클라이언트가 마칠 때까지) 뭔가 합니다:

def deal_with_client(connstream):
    data = connstream.recv(1024)
    # empty data means the client is finished with us
    while data:
        if not do_something(connstream, data):
            # we'll assume do_something returns False
            # when we're finished with client
            break
        data = connstream.recv(1024)
    # finished with client

그리고는 새로운 클라이언트 연결을 리스닝하는 것으로 돌아갑니다 (물론, 실제 서버는 별도의 스레드에서 각 클라이언트 연결을 처리하거나 소켓을 비 블로킹 모드로 만들고 이벤트 루프를 사용합니다).

비 블로킹 소켓에 대한 참고 사항

SSL 소켓은 비 블로킹 모드에서 일반 소켓과 약간 다르게 작동합니다. 비 블로킹 소켓으로 작업할 때 주의해야 할 몇 가지 사항이 있습니다:

대부분 SSLSocket 메서드는 I/O 연산이 블록하려고 할 때 BlockingIOError 대신 SSLWantWriteError 나 SSLWantReadError를 발생시킵니다. 하부 소켓에서의 읽기 연산이 필요하면 SSLWantReadError가 발생하고, 하부 소켓에서의 쓰기 연산이 필요하면 SSLWantWriteError가 발생합니다. SSL 소켓에 대한 쓰기 시도는 우선 하부 소켓에서 읽기가 필요할 수 있으며, SSL 소켓에서 읽기를 시도하면 하부 소켓에서 선행 쓰기가 필요할 수 있습니다.

버전 3.5에서 변경: 이전 파이썬 버전에서는, SSLSocket.send() 메서드가 SSLWantWriteError 나 SSLWantReadError를 발생시키는 대신 0을 반환했습니다.

select()를 호출하면 OS-수준 소켓을 읽을 수 있음을 (또는 쓸 수 있음을) 알려줄 수 있습니다만, 이것이 상위 SSL 계층에 충분한 데이터가 있음을 의미하지는 않습니다. 예를 들어, SSL 프레임의 일부만 도착했을 수 있습니다. 따라서, SSLSocket.recv() 와 SSLSocket.send() 실패를 처리할 준비가 되어 있어야 하며, select()를 다시 호출한 후 재시도해야 합니다.

반대로, SSL 계층에는 자체 프레임이 있으므로, SSL 소켓에는 select()가 인식하지 못하더라도 읽을 수 있는 데이터가 있을 수 있습니다. 따라서, 먼저 SSLSocket.recv()를 호출하여 잠재적으로 사용 가능한 모든 데이터를 꺼낸 다음, 여전히 필요할 때만 select() 호출에 블록해야 합니다.

(물론, poll() 이나 selectors 모듈에 있는 것과 같은 다른 프리미티브를 사용할 때도 비슷한 조항이 적용됩니다)

SSL 핸드 셰이크 자체는 비 블로킹입니다: SSLSocket.do_handshake() 메서드는 성공적으로 반환될 때까지 재시도해야 합니다. 다음은 select()를 사용하여 소켓의 준비 상태를 기다리는 개요입니다:

while True:
    try:
        sock.do_handshake()
        break
    except ssl.SSLWantReadError:
        select.select([sock], [], [])
    except ssl.SSLWantWriteError:
        select.select([], [sock], [])

더 보기

asyncio 모듈은 비 블로킹 SSL 소켓을 지원하며 더 고수준의 API를 제공합니다. selectors 모듈을 사용하여 이벤트를 폴링 하고 SSLWantWriteError, SSLWantReadError 및 BlockingIOError 예외를 처리합니다. SSL 핸드 셰이크도 비동기적으로 실행됩니다.

메모리 BIO 지원

버전 3.5에 추가.

SSL 모듈이 파이썬 2.6에서 소개된 이래로, SSLSocket 클래스는 관련성이 있지만, 별개의 두 기능 영역을 제공했습니다:

SSL 프로토콜 처리

네트워크 IO

네트워크 IO API는 socket.socket가 제공하는 것과 같으며, SSLSocket는 그 것을 상속합니다. 이렇게해서 SSL 소켓을 일반 소켓의 드롭 인 대체품으로 사용할 수 있으므로, 기존 응용 프로그램에 SSL 지원을 쉽게 추가 할 수 있습니다.

SSL 프로토콜 처리와 네트워크 IO의 결합은 일반적으로 잘 작동하지만, 그렇지 않은 경우도 있습니다. socket.socket 과 내부 OpenSSL 소켓 IO 루틴이 가정하는 “파일 기술자에 대한 select/poll” (준비 상태 기반) 모델과 다른 IO 멀티플렉싱 모델을 사용하려는 비동기 IO 프레임워크가 그 예입니다. 이것은 주로 이 모델이 효율적이지 않은 윈도우와 같은 플랫폼과 관련이 있습니다. 이를 위해, SSLObject라는 SSLSocket의 축소된 범위 변형이 제공됩니다.

class ssl.SSLObject

네트워크 IO 메서드를 포함하지 않는 SSL 프로토콜 인스턴스를 나타내는 SSLSocket의 축소 범위 변형입니다. 이 클래스는 일반적으로 메모리 버퍼를 통해 SSL 용 비동기 IO를 구현하려는 프레임워크 작성자가 사용합니다.

이 클래스는 OpenSSL에 의해 구현된 저수준 SSL 객체 위에 인터페이스를 구현합니다. 이 객체는 SSL 연결의 상태를 캡처하지만, 네트워크 IO 자체를 제공하지는 않습니다. IO는 OpenSSL의 IO 추상화 계층인 별도의 “BIO” 객체를 통해 수행되어야 합니다.

이 클래스에는 공개된 생성자가 없습니다. SSLObject 인스턴스는 wrap_bio() 메서드를 사용해서 만들어야 합니다. 이 메서드는 SSLObject 인스턴스를 생성하고 BIO 쌍에 연결합니다. incoming BIO는 파이썬에서 SSL 프로토콜 인스턴스로 데이터를 전달하는 데 사용되는 반면, outgoing BIO는 반대 방향으로 데이터를 전달하는 데 사용됩니다.

다음 메서드를 사용할 수 있습니다:

context

server_side

server_hostname

session

session_reused

read()

write()

getpeercert()

selected_npn_protocol()

cipher()

shared_ciphers()

compression()

pending()

do_handshake()

unwrap()

get_channel_binding()

SSLSocket와 비교할 때, 이 객체에는 다음과 같은 기능이 없습니다:

모든 형태의 네트워크 IO; recv() 와 send()는 하부 MemoryBIO 버퍼만 읽고 씁니다.

do_handshake_on_connect 기작이 없습니다. 핸드 셰이크를 시작하려면 항상 do_handshake()를 수동으로 호출해야 합니다.

suppress_ragged_eofs는 처리되지 않습니다. 프로토콜을 위반하는 모든 파일 끝(end-of-file) 조건은 SSLEOFError 예외를 통해 보고됩니다.

메서드 unwrap() 호출은 하부 소켓을 반환하는 SSL 소켓과 달리 아무것도 반환하지 않습니다.

SSLContext.set_servername_callback()에 전달된 server_name_callback 콜백은 첫 번째 매개 변수로 SSLSocket 인스턴스 대신 SSLObject 인스턴스를 받습니다.

SSLObject 사용과 관련된 몇 가지 참고 사항:

SSLObject의 모든 IO는 비 블로킹입니다. 이것은 예를 들어 read()는 incoming BIO에 있는 것보다 많은 데이터가 필요하면 SSLWantReadError를 발생시킨다는 것을 의미합니다.

wrap_socket() 에 있는 것과 같은 모듈 수준의 wrap_bio() 호출이 없습니다. SSLObject는 항상 SSLContext를 통해 만들어집니다.

버전 3.7에서 변경: SSLObject 인스턴스는 wrap_bio()로 만들어야 합니다. 이전 버전에서는, 직접 인스턴스를 만들 수 있었습니다. 이것은 문서로 만들어지거나 공식적으로 지원된 적이 없습니다.

SSLObject는 메모리 버퍼를 사용하여 바깥세상과 통신합니다. MemoryBIO 클래스는 이 목적으로 사용할 수 있는 메모리 버퍼를 제공합니다. OpenSSL 메모리 BIO (Basic IO) 객체를 감쌉니다:

class ssl.MemoryBIO

파이썬과 SSL 프로토콜 인스턴스 간에 데이터를 전달하는 데 사용할 수 있는 메모리 버퍼.

pending

현재 메모리 버퍼에 있는 바이트의 수를 반환합니다.

eof

메모리 BIO가 현재 EOF(end-of-file) 위치에 있는지를 나타내는 논릿값입니다.

read(n=-1)

메모리 버퍼에서 최대 n 바이트를 읽습니다. n이 지정되지 않았거나 음수면, 모든 바이트가 반환됩니다.

write(buf)

buf의 바이트를 메모리 BIO에 씁니다. buf 인자는 버퍼 프로토콜을 지원하는 객체여야 합니다.

반환 값은 기록된 바이트 수인데, 항상 buf의 길이와 같습니다.

write_eof()

EOF 마커를 메모리 BIO에 씁니다. 이 메서드가 호출된 후, write()를 호출하는 것은 불법입니다. eof 어트리뷰트는 현재 버퍼에 있는 모든 데이터를 읽은 후에 참이 됩니다.

SSL 세션

버전 3.6에 추가.

class ssl.SSLSession

session에서 사용되는 세션 객체.

id

time

timeout

ticket_lifetime_hint

has_ticket

보안 고려 사항

가장 좋은 기본값

클라이언트의 경우, 보안 정책에 대한 특별한 요구 사항이 없으면, create_default_context() 함수를 사용하여 SSL 컨텍스트를 만드는 것이 좋습니다. 시스템의 신뢰할 수 있는 CA 인증서를 로드하고, 인증서 유효성 검사와 호스트 이름 검사를 활성화하고, 합리적으로 안전한 프로토콜과 사이퍼 설정을 선택합니다.

예를 들어, 다음은 smtplib.SMTP 클래스를 사용하여 SMTP 서버에 대한 신뢰할 수 있고 안전한 연결을 만드는 방법입니다:

>>> import ssl, smtplib
>>> smtp = smtplib.SMTP("mail.python.org", port=587)
>>> context = ssl.create_default_context()
>>> smtp.starttls(context=context)
(220, b'2.0.0 Ready to start TLS')

연결에 클라이언트 인증서가 필요하면, SSLContext.load_cert_chain()으로 추가할 수 있습니다.

대조적으로, SSLContext 생성자를 직접 호출하여 SSL 컨텍스트를 만들면, 기본적으로 인증서 유효성 검사나 호스트 이름 확인이 활성화되지 않습니다. 그렇게 하면, 아래 단락을 읽고 적절한 보안 수준을 달성하십시오.

수동 설정

인증서 확인

SSLContext 생성자를 직접 호출할 때, CERT_NONE이 기본값입니다. 이것은 다른 피어를 인증하지 않기 때문에, 특히 대부분 대화를 나누려는 서버의 신뢰성을 보장하고 싶어 하는 클라이언트 모드에서는 안전하지 않을 수 있습니다. 따라서 클라이언트 모드에서는, CERT_REQUIRED를 사용하는 것이 좋습니다. 그러나 그 자체로는 충분하지 않습니다; SSLSocket.getpeercert()를 호출하여 얻을 수 있는 서버 인증서가 원하는 서비스와 일치하는지 확인해야 합니다. 많은 프로토콜과 응용 프로그램에서 서비스는 호스트 이름으로 식별할 수 있습니다; 이럴 때, match_hostname() 함수를 사용할 수 있습니다. 이 공통 검사는 SSLContext.check_hostname이 활성화되면 자동으로 수행됩니다.

버전 3.7에서 변경: 이제 호스트 이름 일치가 OpenSSL에 의해 수행됩니다. 파이썬은 더는 match_hostname()을 사용하지 않습니다.

서버 모드에서, (고수준 인증 메커니즘을 사용하는 대신) SSL 계층을 사용하여 클라이언트를 인증하려면, CERT_REQUIRED를 지정하고 클라이언트 인증서도 비슷하게 확인해야 합니다.

프로토콜 버전

SSL 버전 2와 3은 안전하지 않은 것으로 간주하므로 사용하기에 위험합니다. 클라이언트와 서버 간에 최대한의 호환성을 원하면 프로토콜 버전으로 PROTOCOL_TLS_CLIENT 나 PROTOCOL_TLS_SERVER를 사용하는 것이 좋습니다. SSLv2 및 SSLv3은 기본적으로 비활성화되어 있습니다.

>>> client_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
>>> client_context.options |= ssl.OP_NO_TLSv1
>>> client_context.options |= ssl.OP_NO_TLSv1_1

위에 만들어진 SSL 컨텍스트는 서버로 TLSv1.2 이상(시스템이 지원한다면)의 연결만 허용합니다. PROTOCOL_TLS_CLIENT는 기본적으로 인증서 유효성 검사와 호스트 이름 검사를 의미합니다. 인증서를 컨텍스트에 로드 해야 합니다.

사이퍼 선택

고급 보안 요구 사항이 있으면, SSLContext.set_ciphers() 메서드를 통해 SSL 세션을 협상할 때 활성화되는 사이퍼의 미세 조정이 가능합니다. 파이썬 3.2.3부터, ssl 모듈은 기본적으로 특정 약한 사이퍼를 비활성화하지만, 사이퍼 선택을 추가로 제한하려고 할 수 있습니다. 사이퍼 목록 형식 [https://www.openssl.org/docs/manmaster/man1/ciphers.html#CIPHER-LIST-FORMAT]에 대한 OpenSSL의 설명서를 읽으십시오. 주어진 사이퍼 목록에 의해 활성화된 사이퍼를 확인하려면, SSLContext.get_ciphers() 나 시스템에서 openssl ciphers 명령을 사용하십시오.

다중 프로세싱

다중 프로세스 응용 프로그램(예를 들어, : multiprocessing 이나 concurrent.futures 모듈을 사용하는)의 일부로 이 모듈을 사용하면, OpenSSL의 내부 난수 생성기가 포크 된 프로세스를 제대로 처리하지 못합니다. 응용 프로그램이 os.fork()와 함께 SSL 기능을 사용하면, 부모 프로세스의 PRNG 상태를 변경해야 합니다. RAND_add(), RAND_bytes() 또는 RAND_pseudo_bytes()의 성공적인 호출이면 충분합니다.

TLS 1.3

버전 3.7에 추가.

파이썬은 OpenSSL 1.1.1을 사용해서 TLS 1.3에 대한 잠정적이고 실험적인 지원을 제공합니다. 새 프로토콜은 이전 버전의 TLS/SSL과 약간 다르게 동작합니다. 몇몇 새로운 TLS 1.3 기능은 아직 제공되지 않습니다.

TLS 1.3은 분리된 사이퍼 스위트 집합을 사용합니다. 모든 AES-GCM과 ChaCha20 사이퍼 스위트는 기본적으로 활성화되어 있습니다. SSLContext.set_ciphers() 메서드는 아직 TLS 1.3 사이퍼를 활성화하거나 비활성화할 수 없지만, SSLContext.get_ciphers()는 이들을 반환합니다.

세션 티켓은 더는 초기 핸드 셰이크의 일부로 전송되지 않고 다르게 처리됩니다. SSLSocket.session 과 SSLSession은 TLS 1.3과 호환되지 않습니다.

클라이언트 측 인증서도 더는 초기 핸드 셰이크 중에 검증되지 않습니다. 서버는 언제든지 인증서를 요청할 수 있습니다. 클라이언트는 서버와 응용 프로그램 데이터를 주고받는 동안 인증서 요청을 처리합니다.

초기 데이터(early data), 지연된 TLS 클라이언트 인증서 요청, 서명 알고리즘 구성 및 rekeying과 같은 TLS 1.3 기능은 아직 지원되지 않습니다.

LibreSSL 지원

LibreSSL은 OpenSSL 1.0.1 포크입니다. ssl 모듈은 LibreSSL을 제한적으로 지원합니다. ssl 모듈이 LibreSSL로 컴파일될 때 일부 기능을 사용할 수 없습니다.

LibreSSL >= 2.6.1은 더는 NPN을 지원하지 않습니다. SSLContext.set_npn_protocols()와 SSLSocket.selected_npn_protocol() 메서드는 사용할 수 없습니다.

SSLContext.set_default_verify_paths()는 비록 get_default_verify_paths()가 여전히 보고하지만, 환경 변수 SSL_CERT_FILE와 SSL_CERT_PATH를 무시합니다.

더 보기

socket.socket 클래스

하부 socket 클래스의 설명서

SSL/TLS Strong Encryption: An Introduction [https://httpd.apache.org/docs/trunk/en/ssl/ssl_intro.html]

Apache HTTP 서버 설명서의 개요

RFC 1422: Privacy Enhancement for Internet Electronic Mail: Part II: Certificate-Based Key Management [https://tools.ietf.org/html/rfc1422.html]

Steve Kent

RFC 4086: Randomness Requirements for Security [https://tools.ietf.org/html/rfc4086.html]

Donald E., Jeffrey I. Schiller

RFC 5280: Internet X.509 Public Key Infrastructure Certificate and Certificate Revocation List (CRL) Profile [https://tools.ietf.org/html/rfc5280.html]

D. Cooper

RFC 5246: The Transport Layer Security (TLS) Protocol Version 1.2 [https://tools.ietf.org/html/rfc5246.html]

T. Dierks et. al.

RFC 6066: Transport Layer Security (TLS) Extensions [https://tools.ietf.org/html/rfc6066.html]

D. Eastlake

IANA TLS: Transport Layer Security (TLS) Parameters [https://www.iana.org/assignments/tls-parameters/tls-parameters.xml]

IANA

RFC 7525: Recommendations for Secure Use of Transport Layer Security (TLS) and Datagram Transport Layer Security (DTLS) [https://tools.ietf.org/html/rfc7525.html]

IETF

모질라의 서버 측 TLS 추천 [https://wiki.mozilla.org/Security/Server_Side_TLS]

Mozilla

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

네트워킹과 프로세스 간 통신 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

네트워킹과 프로세스 간 통신 »

|

select — Waiting for I/O completion

This module provides access to the select() and poll() functions available in most operating systems, devpoll() available on Solaris and derivatives, epoll() available on Linux 2.5+ and kqueue() available on most BSD. Note that on Windows, it only works for sockets; on other operating systems, it also works for other file types (in particular, on Unix, it works on pipes). It cannot be used on regular files to determine whether a file has grown since it was last read.

참고

The selectors module allows high-level and efficient I/O multiplexing, built upon the select module primitives. Users are encouraged to use the selectors module instead, unless they want precise control over the OS-level primitives used.

The module defines the following:

exception select.error

A deprecated alias of OSError.

버전 3.3에서 변경: Following PEP 3151 [https://www.python.org/dev/peps/pep-3151], this class was made an alias of OSError.

select.devpoll()

(Only supported on Solaris and derivatives.) Returns a /dev/poll polling object; see section /dev/poll Polling Objects below for the methods supported by devpoll objects.

devpoll() objects are linked to the number of file descriptors allowed at the time of instantiation. If your program reduces this value, devpoll() will fail. If your program increases this value, devpoll() may return an incomplete list of active file descriptors.

The new file descriptor is non-inheritable.

버전 3.3에 추가.

버전 3.4에서 변경: The new file descriptor is now non-inheritable.

select.epoll(sizehint=-1, flags=0)

(Only supported on Linux 2.5.44 and newer.) Return an edge polling object, which can be used as Edge or Level Triggered interface for I/O events.

sizehint informs epoll about the expected number of events to be registered. It must be positive, or -1 to use the default. It is only used on older systems where epoll_create1() is not available; otherwise it has no effect (though its value is still checked).

flags is deprecated and completely ignored. However, when supplied, its value must be 0 or select.EPOLL_CLOEXEC, otherwise OSError is raised.

See the Edge and Level Trigger Polling (epoll) Objects section below for the methods supported by epolling objects.

epoll objects support the context management protocol: when used in a with statement, the new file descriptor is automatically closed at the end of the block.

The new file descriptor is non-inheritable.

버전 3.3에서 변경: Added the flags parameter.

버전 3.4에서 변경: Support for the with statement was added. The new file descriptor is now non-inheritable.

버전 3.4부터 폐지: The flags parameter. select.EPOLL_CLOEXEC is used by default now. Use os.set_inheritable() to make the file descriptor inheritable.

select.poll()

(Not supported by all operating systems.) Returns a polling object, which supports registering and unregistering file descriptors, and then polling them for I/O events; see section Polling Objects below for the methods supported by polling objects.

select.kqueue()

(Only supported on BSD.) Returns a kernel queue object; see section Kqueue Objects below for the methods supported by kqueue objects.

The new file descriptor is non-inheritable.

버전 3.4에서 변경: The new file descriptor is now non-inheritable.

select.kevent(ident, filter=KQ_FILTER_READ, flags=KQ_EV_ADD, fflags=0, data=0, udata=0)

(Only supported on BSD.) Returns a kernel event object; see section Kevent Objects below for the methods supported by kevent objects.

select.select(rlist, wlist, xlist[, timeout])

This is a straightforward interface to the Unix select() system call. The first three arguments are iterables of ‘waitable objects’: either integers representing file descriptors or objects with a parameterless method named fileno() returning such an integer:

rlist: wait until ready for reading

wlist: wait until ready for writing

xlist: wait for an “exceptional condition” (see the manual page for what your system considers such a condition)

Empty iterables are allowed, but acceptance of three empty iterables is platform-dependent. (It is known to work on Unix but not on Windows.) The optional timeout argument specifies a time-out as a floating point number in seconds. When the timeout argument is omitted the function blocks until at least one file descriptor is ready. A time-out value of zero specifies a poll and never blocks.

The return value is a triple of lists of objects that are ready: subsets of the first three arguments. When the time-out is reached without a file descriptor becoming ready, three empty lists are returned.

Among the acceptable object types in the iterables are Python file objects (e.g. sys.stdin, or objects returned by open() or os.popen()), socket objects returned by socket.socket(). You may also define a wrapper class yourself, as long as it has an appropriate fileno() method (that really returns a file descriptor, not just a random integer).

참고

File objects on Windows are not acceptable, but sockets are. On Windows, the underlying select() function is provided by the WinSock library, and does not handle file descriptors that don’t originate from WinSock.

버전 3.5에서 변경: The function is now retried with a recomputed timeout when interrupted by a signal, except if the signal handler raises an exception (see PEP 475 [https://www.python.org/dev/peps/pep-0475] for the rationale), instead of raising InterruptedError.

select.PIPE_BUF

The minimum number of bytes which can be written without blocking to a pipe when the pipe has been reported as ready for writing by select(), poll() or another interface in this module. This doesn’t apply to other kind of file-like objects such as sockets.

This value is guaranteed by POSIX to be at least 512.

Availability: Unix

버전 3.2에 추가.

/dev/poll Polling Objects

Solaris and derivatives have /dev/poll. While select() is O(highest file descriptor) and poll() is O(number of file descriptors), /dev/poll is O(active file descriptors).

/dev/poll behaviour is very close to the standard poll() object.

devpoll.close()

Close the file descriptor of the polling object.

버전 3.4에 추가.

devpoll.closed

True if the polling object is closed.

버전 3.4에 추가.

devpoll.fileno()

Return the file descriptor number of the polling object.

버전 3.4에 추가.

devpoll.register(fd[, eventmask])

Register a file descriptor with the polling object. Future calls to the poll() method will then check whether the file descriptor has any pending I/O events. fd can be either an integer, or an object with a fileno() method that returns an integer. File objects implement fileno(), so they can also be used as the argument.

eventmask is an optional bitmask describing the type of events you want to check for. The constants are the same that with poll() object. The default value is a combination of the constants POLLIN, POLLPRI, and POLLOUT.

경고

Registering a file descriptor that’s already registered is not an error, but the result is undefined. The appropriate action is to unregister or modify it first. This is an important difference compared with poll().

devpoll.modify(fd[, eventmask])

This method does an unregister() followed by a register(). It is (a bit) more efficient that doing the same explicitly.

devpoll.unregister(fd)

Remove a file descriptor being tracked by a polling object. Just like the register() method, fd can be an integer or an object with a fileno() method that returns an integer.

Attempting to remove a file descriptor that was never registered is safely ignored.

devpoll.poll([timeout])

Polls the set of registered file descriptors, and returns a possibly-empty list containing (fd, event) 2-tuples for the descriptors that have events or errors to report. fd is the file descriptor, and event is a bitmask with bits set for the reported events for that descriptor — POLLIN for waiting input, POLLOUT to indicate that the descriptor can be written to, and so forth. An empty list indicates that the call timed out and no file descriptors had any events to report. If timeout is given, it specifies the length of time in milliseconds which the system will wait for events before returning. If timeout is omitted, -1, or None, the call will block until there is an event for this poll object.

버전 3.5에서 변경: The function is now retried with a recomputed timeout when interrupted by a signal, except if the signal handler raises an exception (see PEP 475 [https://www.python.org/dev/peps/pep-0475] for the rationale), instead of raising InterruptedError.

Edge and Level Trigger Polling (epoll) Objects

https://linux.die.net/man/4/epoll

eventmask

Constant

Meaning

EPOLLIN

Available for read

EPOLLOUT

Available for write

EPOLLPRI

Urgent data for read

EPOLLERR

Error condition happened on the assoc. fd

EPOLLHUP

Hang up happened on the assoc. fd

EPOLLET

Set Edge Trigger behavior, the default is Level Trigger behavior

EPOLLONESHOT

Set one-shot behavior. After one event is pulled out, the fd is internally disabled

EPOLLEXCLUSIVE

Wake only one epoll object when the associated fd has an event. The default (if this flag is not set) is to wake all epoll objects polling on a fd.

EPOLLRDHUP

Stream socket peer closed connection or shut down writing half of connection.

EPOLLRDNORM

Equivalent to EPOLLIN

EPOLLRDBAND

Priority data band can be read.

EPOLLWRNORM

Equivalent to EPOLLOUT

EPOLLWRBAND

Priority data may be written.

EPOLLMSG

Ignored.

버전 3.6에 추가: EPOLLEXCLUSIVE was added. It’s only supported by Linux Kernel 4.5 or later.

epoll.close()

Close the control file descriptor of the epoll object.

epoll.closed

True if the epoll object is closed.

epoll.fileno()

Return the file descriptor number of the control fd.

epoll.fromfd(fd)

Create an epoll object from a given file descriptor.

epoll.register(fd[, eventmask])

Register a fd descriptor with the epoll object.

epoll.modify(fd, eventmask)

Modify a registered file descriptor.

epoll.unregister(fd)

Remove a registered file descriptor from the epoll object.

epoll.poll(timeout=-1, maxevents=-1)

Wait for events. timeout in seconds (float)

버전 3.5에서 변경: The function is now retried with a recomputed timeout when interrupted by a signal, except if the signal handler raises an exception (see PEP 475 [https://www.python.org/dev/peps/pep-0475] for the rationale), instead of raising InterruptedError.

Polling Objects

The poll() system call, supported on most Unix systems, provides better scalability for network servers that service many, many clients at the same time. poll() scales better because the system call only requires listing the file descriptors of interest, while select() builds a bitmap, turns on bits for the fds of interest, and then afterward the whole bitmap has to be linearly scanned again. select() is O(highest file descriptor), while poll() is O(number of file descriptors).

poll.register(fd[, eventmask])

Register a file descriptor with the polling object. Future calls to the poll() method will then check whether the file descriptor has any pending I/O events. fd can be either an integer, or an object with a fileno() method that returns an integer. File objects implement fileno(), so they can also be used as the argument.

eventmask is an optional bitmask describing the type of events you want to check for, and can be a combination of the constants POLLIN, POLLPRI, and POLLOUT, described in the table below. If not specified, the default value used will check for all 3 types of events.

Constant

Meaning

POLLIN

There is data to read

POLLPRI

There is urgent data to read

POLLOUT

Ready for output: writing will not block

POLLERR

Error condition of some sort

POLLHUP

Hung up

POLLRDHUP

Stream socket peer closed connection, or shut down writing half of connection

POLLNVAL

Invalid request: descriptor not open

Registering a file descriptor that’s already registered is not an error, and has the same effect as registering the descriptor exactly once.

poll.modify(fd, eventmask)

Modifies an already registered fd. This has the same effect as register(fd, eventmask). Attempting to modify a file descriptor that was never registered causes an OSError exception with errno ENOENT to be raised.

poll.unregister(fd)

Remove a file descriptor being tracked by a polling object. Just like the register() method, fd can be an integer or an object with a fileno() method that returns an integer.

Attempting to remove a file descriptor that was never registered causes a KeyError exception to be raised.

poll.poll([timeout])

Polls the set of registered file descriptors, and returns a possibly-empty list containing (fd, event) 2-tuples for the descriptors that have events or errors to report. fd is the file descriptor, and event is a bitmask with bits set for the reported events for that descriptor — POLLIN for waiting input, POLLOUT to indicate that the descriptor can be written to, and so forth. An empty list indicates that the call timed out and no file descriptors had any events to report. If timeout is given, it specifies the length of time in milliseconds which the system will wait for events before returning. If timeout is omitted, negative, or None, the call will block until there is an event for this poll object.

버전 3.5에서 변경: The function is now retried with a recomputed timeout when interrupted by a signal, except if the signal handler raises an exception (see PEP 475 [https://www.python.org/dev/peps/pep-0475] for the rationale), instead of raising InterruptedError.

Kqueue Objects

kqueue.close()

Close the control file descriptor of the kqueue object.

kqueue.closed

True if the kqueue object is closed.

kqueue.fileno()

Return the file descriptor number of the control fd.

kqueue.fromfd(fd)

Create a kqueue object from a given file descriptor.

kqueue.control(changelist, max_events[, timeout]) → eventlist

Low level interface to kevent

changelist must be an iterable of kevent objects or None

max_events must be 0 or a positive integer

timeout in seconds (floats possible); the default is None, to wait forever

버전 3.5에서 변경: The function is now retried with a recomputed timeout when interrupted by a signal, except if the signal handler raises an exception (see PEP 475 [https://www.python.org/dev/peps/pep-0475] for the rationale), instead of raising InterruptedError.

Kevent Objects

https://www.freebsd.org/cgi/man.cgi?query=kqueue&sektion=2

kevent.ident

Value used to identify the event. The interpretation depends on the filter but it’s usually the file descriptor. In the constructor ident can either be an int or an object with a fileno() method. kevent stores the integer internally.

kevent.filter

Name of the kernel filter.

Constant

Meaning

KQ_FILTER_READ

Takes a descriptor and returns whenever there is data available to read

KQ_FILTER_WRITE

Takes a descriptor and returns whenever there is data available to write

KQ_FILTER_AIO

AIO requests

KQ_FILTER_VNODE

Returns when one or more of the requested events watched in fflag occurs

KQ_FILTER_PROC

Watch for events on a process id

KQ_FILTER_NETDEV

Watch for events on a network device [not available on Mac OS X]

KQ_FILTER_SIGNAL

Returns whenever the watched signal is delivered to the process

KQ_FILTER_TIMER

Establishes an arbitrary timer

kevent.flags

Filter action.

Constant

Meaning

KQ_EV_ADD

Adds or modifies an event

KQ_EV_DELETE

Removes an event from the queue

KQ_EV_ENABLE

Permitscontrol() to returns the event

KQ_EV_DISABLE

Disablesevent

KQ_EV_ONESHOT

Removes event after first occurrence

KQ_EV_CLEAR

Reset the state after an event is retrieved

KQ_EV_SYSFLAGS

internal event

KQ_EV_FLAG1

internal event

KQ_EV_EOF

Filter specific EOF condition

KQ_EV_ERROR

See return values

kevent.fflags

Filter specific flags.

KQ_FILTER_READ and KQ_FILTER_WRITE filter flags:

Constant

Meaning

KQ_NOTE_LOWAT

low water mark of a socket buffer

KQ_FILTER_VNODE filter flags:

Constant

Meaning

KQ_NOTE_DELETE

unlink() was called

KQ_NOTE_WRITE

a write occurred

KQ_NOTE_EXTEND

the file was extended

KQ_NOTE_ATTRIB

an attribute was changed

KQ_NOTE_LINK

the link count has changed

KQ_NOTE_RENAME

the file was renamed

KQ_NOTE_REVOKE

access to the file was revoked

KQ_FILTER_PROC filter flags:

Constant

Meaning

KQ_NOTE_EXIT

the process has exited

KQ_NOTE_FORK

the process has called fork()

KQ_NOTE_EXEC

the process has executed a new process

KQ_NOTE_PCTRLMASK

internal filter flag

KQ_NOTE_PDATAMASK

internal filter flag

KQ_NOTE_TRACK

follow a process across fork()

KQ_NOTE_CHILD

returned on the child process for NOTE_TRACK

KQ_NOTE_TRACKERR

unable to attach to a child

KQ_FILTER_NETDEV filter flags (not available on Mac OS X):

Constant

Meaning

KQ_NOTE_LINKUP

link is up

KQ_NOTE_LINKDOWN

link is down

KQ_NOTE_LINKINV

link state is invalid

kevent.data

Filter specific data.

kevent.udata

User defined value.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

네트워킹과 프로세스 간 통신 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

네트워킹과 프로세스 간 통신 »

|

selectors — 고수준 I/O 다중화

버전 3.4에 추가.

소스 코드: Lib/selectors.py [https://github.com/python/cpython/tree/3.7/Lib/selectors.py]

소개

이 모듈은 select 모듈 프리미티브에 기반하여 고수준의 효율적인 I/O 다중화를 가능하게 합니다. 사용되는 OS 수준 프리미티브를 정확하게 제어하고 싶지 않으면, 사용자는 이 모듈을 대신 사용하는 것이 좋습니다.

여러 파일 객체에 대한 I/O 준비 알림을 기다리는 데 사용할 수 있는 몇 가지 구체적인 구현 (KqueueSelector, EpollSelector…)과 함께 BaseSelector 추상 베이스 클래스를 정의합니다. 다음에서 “파일 객체”는 fileno() 메서드가 있는 모든 객체나 날 파일 기술자를 가리킵니다. 파일 객체를 참조하십시오.

DefaultSelector는 현재 플랫폼에서 사용할 수 있는 가장 효율적인 구현의 별칭입니다: 대부분 사용자는 기본적으로 이것을 선택해야 합니다.

참고

지원되는 파일 객체의 유형은 플랫폼에 따라 다릅니다: 윈도우에서는 소켓은 지원되지만, 파이프는 지원되지 않습니다. 반면에, 유닉스에서는 둘 다 지원됩니다 (fifo나 특수 파일 장치와 같은 다른 유형도 지원될 수 있습니다).

더 보기

select

저수준 I/O 다중화 모듈.

클래스

클래스 계층 구조:

BaseSelector
+-- SelectSelector
+-- PollSelector
+-- EpollSelector
+-- DevpollSelector
+-- KqueueSelector

다음에서, events는 주어진 파일 객체에서 어떤 I/O 이벤트를 기다려야 하는지를 나타내는 비트 마스크입니다. 다음 모듈 상수의 조합일 수 있습니다:

상수

의미

EVENT_READ

읽기 가능

EVENT_WRITE

쓰기 가능

class selectors.SelectorKey

SelectorKey는 파일 객체에 그것의 하부 파일 기술자, 선택한 이벤트 마스크 및 첨부된 데이터를 연결하는 데 사용되는 namedtuple입니다. 여러 BaseSelector 메서드에 의해 반환됩니다.

fileobj

등록된 파일 객체.

fd

하부 파일 기술자.

events

이 파일 객체에서 기다려야 하는 이벤트.

data

이 파일 객체에 연결된 선택적인 불투명한 데이터: 예를 들어, 이것은 클라이언트별 세션 ID를 저장하는 데 사용될 수 있습니다.

class selectors.BaseSelector

BaseSelector는 여러 파일 객체에 대한 I/O 이벤트 준비를 기다리는 데 사용됩니다. 파일 스트림 등록, 등록 취소 및 선택적 제한 시간과 함께 해당 스트림에서 I/O 이벤트를 기다리는 메서드를 지원합니다. 추상 베이스 클래스이므로, 인스턴스를 만들 수 없습니다. DefaultSelector를 대신 사용하거나, 특정 구현을 사용하고 싶고, 플랫폼에서 지원한다면 SelectSelector, KqueueSelector 등을 사용하십시오. BaseSelector와 그것의 구상 구현은 컨텍스트 관리자 프로토콜을 지원합니다.

abstractmethod register(fileobj, events, data=None)

I/O 이벤트를 셀렉트하고 감시하기 위한 파일 객체를 등록합니다.

fileobj는 감시할 파일 객체입니다. 정수 파일 기술자이거나 fileno() 메서드를 가진 객체일 수 있습니다. events는 감시할 이벤트의 비트 마스크입니다. data는 불투명한 객체입니다.

새로운 SelectorKey 인스턴스를 반환하거나, 유효하지 않은 이벤트 마스크나 파일 기술자의 경우 ValueError를, 파일 객체가 이미 등록된 경우 KeyError를 발생시킵니다.

abstractmethod unregister(fileobj)

셀렉트로부터 파일 객체를 등록 해지하고, 감시에서 삭제합니다. 파일 객체는 닫히기 전에 등록 해지되어야 합니다.

fileobj는 이전에 등록된 파일 객체여야 합니다.

연결된 SelectorKey 인스턴스를 반환하거나, fileobj가 등록되어 있지 않으면 KeyError를 발생시킵니다. fileobj가 유효하지 않으면 (예를 들어, fileno() 메서드가 없거나 fileno() 메서드가 유효하지 않은 반환 값을 가지면) ValueError가 발생합니다.

modify(fileobj, events, data=None)

등록된 파일 객체의 감시되는 이벤트나 첨부된 데이터를 변경합니다.

이것은 더 효율적으로 구현될 수 있다는 점을 제외하면, BaseSelector.unregister(fileobj)() 다음에 BaseSelector.register(fileobj, events, data)()하는 것과 동등합니다.

새로운 SelectorKey 인스턴스를 반환하거나, 유효하지 않은 이벤트 마스크나 파일 기술자의 경우 ValueError를, 파일 객체가 등록되지 않았으면 KeyError를 발생시킵니다.

abstractmethod select(timeout=None)

등록된 파일 객체의 일부가 준비될 때까지 기다리거나, 제한 시간이 만료됩니다.

timeout > 0 이면, 최대 대기 시간을 초로 지정합니다. timeout <= 0이면, 호출은 블록하지 않고, 현재 준비된 파일 객체를 보고합니다. timeout이 None이면, 감시되는 파일 객체가 준비될 때까지 호출이 블록 됩니다.

각 준비된 파일 객체마다 하나씩, (key, events) 튜플의 리스트를 반환합니다.

key는 준비된 파일 객체에 해당하는 SelectorKey 인스턴스입니다. events는 이 파일 객체에서 준비된 이벤트의 비트 마스크입니다.

참고

현재 프로세스가 시그널을 받으면, 이 메서드는 파일 객체가 준비되거나 제한 시간이 지나기 전에 반환할 수 있습니다: 이때는 빈 리스트가 반환됩니다.

버전 3.5에서 변경: 시그널에 의해 인터럽트 되었을 때, 셀렉터는 이제 시그널 처리기가 예외를 발생시키지 않으면, 제한 시간 이전에 빈 이벤트 리스트를 반환하는 대신, 재계산 된 제한 시간으로 재 시도됩니다 (근거는 PEP 475 [https://www.python.org/dev/peps/pep-0475]를 참조하세요).

close()

셀렉터를 닫습니다.

모든 하부 자원을 해제하기 위해 이 메서드를 호출해야 합니다. 일단 닫은 후에는 셀렉터를 더는 사용하지 않아야 합니다.

get_key(fileobj)

등록된 파일 객체에 연결된 키를 반환합니다.

이 파일 객체에 연결된 SelectorKey 인스턴스를 반환하거나, 파일 객체가 등록되지 않았으면 KeyError를 발생시킵니다.

abstractmethod get_map()

파일 객체에서 셀렉터로의 매핑을 반환합니다.

등록된 파일 객체를 연결된 SelectorKey 인스턴스로 매핑하는 Mapping 인스턴스를 반환합니다.

class selectors.DefaultSelector

현재의 플랫폼에서 사용할 수 있는 가장 효율적인 구현을 사용하는 기본 셀렉터 클래스입니다. 대부분 사용자는 기본적으로 이것을 선택해야 합니다.

class selectors.SelectSelector

select.select() 기반 셀렉터.

class selectors.PollSelector

select.poll() 기반 셀렉터.

class selectors.EpollSelector

select.epoll() 기반 셀렉터.

fileno()

하부 select.epoll() 객체에서 사용하는 파일 기술자를 반환합니다.

class selectors.DevpollSelector

select.devpoll() 기반 셀렉터.

fileno()

하부 select.devpoll() 객체에서 사용하는 파일 기술자를 반환합니다.

버전 3.5에 추가.

class selectors.KqueueSelector

select.kqueue() 기반 셀렉터.

fileno()

하부 select.kqueue() 객체에서 사용하는 파일 기술자를 반환합니다.

예제

다음은 간단한 메아리 서버 구현입니다:

import selectors
import socket

sel = selectors.DefaultSelector()

def accept(sock, mask):
    conn, addr = sock.accept()  # Should be ready
    print('accepted', conn, 'from', addr)
    conn.setblocking(False)
    sel.register(conn, selectors.EVENT_READ, read)

def read(conn, mask):
    data = conn.recv(1000)  # Should be ready
    if data:
        print('echoing', repr(data), 'to', conn)
        conn.send(data)  # Hope it won't block
    else:
        print('closing', conn)
        sel.unregister(conn)
        conn.close()

sock = socket.socket()
sock.bind(('localhost', 1234))
sock.listen(100)
sock.setblocking(False)
sel.register(sock, selectors.EVENT_READ, accept)

while True:
    events = sel.select()
    for key, mask in events:
        callback = key.data
        callback(key.fileobj, mask)

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

네트워킹과 프로세스 간 통신 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

네트워킹과 프로세스 간 통신 »

|

asyncore — Asynchronous socket handler

Source code: Lib/asyncore.py [https://github.com/python/cpython/tree/3.7/Lib/asyncore.py]

버전 3.6부터 폐지: Please use asyncio instead.

참고

This module exists for backwards compatibility only. For new code we recommend using asyncio.

This module provides the basic infrastructure for writing asynchronous socket service clients and servers.

There are only two ways to have a program on a single processor do “more than one thing at a time.” Multi-threaded programming is the simplest and most popular way to do it, but there is another very different technique, that lets you have nearly all the advantages of multi-threading, without actually using multiple threads. It’s really only practical if your program is largely I/O bound. If your program is processor bound, then pre-emptive scheduled threads are probably what you really need. Network servers are rarely processor bound, however.

If your operating system supports the select() system call in its I/O library (and nearly all do), then you can use it to juggle multiple communication channels at once; doing other work while your I/O is taking place in the “background.” Although this strategy can seem strange and complex, especially at first, it is in many ways easier to understand and control than multi-threaded programming. The asyncore module solves many of the difficult problems for you, making the task of building sophisticated high-performance network servers and clients a snap. For “conversational” applications and protocols the companion asynchat module is invaluable.

The basic idea behind both modules is to create one or more network channels, instances of class asyncore.dispatcher and asynchat.async_chat. Creating the channels adds them to a global map, used by the loop() function if you do not provide it with your own map.

Once the initial channel(s) is(are) created, calling the loop() function activates channel service, which continues until the last channel (including any that have been added to the map during asynchronous service) is closed.

asyncore.loop([timeout[, use_poll[, map[, count]]]])

Enter a polling loop that terminates after count passes or all open channels have been closed. All arguments are optional. The count parameter defaults to None, resulting in the loop terminating only when all channels have been closed. The timeout argument sets the timeout parameter for the appropriate select() or poll() call, measured in seconds; the default is 30 seconds. The use_poll parameter, if true, indicates that poll() should be used in preference to select() (the default is False).

The map parameter is a dictionary whose items are the channels to watch. As channels are closed they are deleted from their map. If map is omitted, a global map is used. Channels (instances of asyncore.dispatcher, asynchat.async_chat and subclasses thereof) can freely be mixed in the map.

class asyncore.dispatcher

The dispatcher class is a thin wrapper around a low-level socket object. To make it more useful, it has a few methods for event-handling which are called from the asynchronous loop. Otherwise, it can be treated as a normal non-blocking socket object.

The firing of low-level events at certain times or in certain connection states tells the asynchronous loop that certain higher-level events have taken place. For example, if we have asked for a socket to connect to another host, we know that the connection has been made when the socket becomes writable for the first time (at this point you know that you may write to it with the expectation of success). The implied higher-level events are:

Event

Description

handle_connect()

Implied by the first read or write event

handle_close()

Implied by a read event with no data available

handle_accepted()

Implied by a read event on a listening socket

During asynchronous processing, each mapped channel’s readable() and writable() methods are used to determine whether the channel’s socket should be added to the list of channels select()ed or poll()ed for read and write events.

Thus, the set of channel events is larger than the basic socket events. The full set of methods that can be overridden in your subclass follows:

handle_read()

Called when the asynchronous loop detects that a read() call on the channel’s socket will succeed.

handle_write()

Called when the asynchronous loop detects that a writable socket can be written. Often this method will implement the necessary buffering for performance. For example:

def handle_write(self):
    sent = self.send(self.buffer)
    self.buffer = self.buffer[sent:]

handle_expt()

Called when there is out of band (OOB) data for a socket connection. This will almost never happen, as OOB is tenuously supported and rarely used.

handle_connect()

Called when the active opener’s socket actually makes a connection. Might send a “welcome” banner, or initiate a protocol negotiation with the remote endpoint, for example.

handle_close()

Called when the socket is closed.

handle_error()

Called when an exception is raised and not otherwise handled. The default version prints a condensed traceback.

handle_accept()

Called on listening channels (passive openers) when a connection can be established with a new remote endpoint that has issued a connect() call for the local endpoint. Deprecated in version 3.2; use handle_accepted() instead.

버전 3.2부터 폐지.

handle_accepted(sock, addr)

Called on listening channels (passive openers) when a connection has been established with a new remote endpoint that has issued a connect() call for the local endpoint. sock is a new socket object usable to send and receive data on the connection, and addr is the address bound to the socket on the other end of the connection.

버전 3.2에 추가.

readable()

Called each time around the asynchronous loop to determine whether a channel’s socket should be added to the list on which read events can occur. The default method simply returns True, indicating that by default, all channels will be interested in read events.

writable()

Called each time around the asynchronous loop to determine whether a channel’s socket should be added to the list on which write events can occur. The default method simply returns True, indicating that by default, all channels will be interested in write events.

In addition, each channel delegates or extends many of the socket methods. Most of these are nearly identical to their socket partners.

create_socket(family=socket.AF_INET, type=socket.SOCK_STREAM)

This is identical to the creation of a normal socket, and will use the same options for creation. Refer to the socket documentation for information on creating sockets.

버전 3.3에서 변경: family and type arguments can be omitted.

connect(address)

As with the normal socket object, address is a tuple with the first element the host to connect to, and the second the port number.

send(data)

Send data to the remote end-point of the socket.

recv(buffer_size)

Read at most buffer_size bytes from the socket’s remote end-point. An empty bytes object implies that the channel has been closed from the other end.

Note that recv() may raise BlockingIOError , even though select.select() or select.poll() has reported the socket ready for reading.

listen(backlog)

Listen for connections made to the socket. The backlog argument specifies the maximum number of queued connections and should be at least 1; the maximum value is system-dependent (usually 5).

bind(address)

Bind the socket to address. The socket must not already be bound. (The format of address depends on the address family — refer to the socket documentation for more information.) To mark the socket as re-usable (setting the SO_REUSEADDR option), call the dispatcher object’s set_reuse_addr() method.

accept()

Accept a connection. The socket must be bound to an address and listening for connections. The return value can be either None or a pair (conn, address) where conn is a new socket object usable to send and receive data on the connection, and address is the address bound to the socket on the other end of the connection. When None is returned it means the connection didn’t take place, in which case the server should just ignore this event and keep listening for further incoming connections.

close()

Close the socket. All future operations on the socket object will fail. The remote end-point will receive no more data (after queued data is flushed). Sockets are automatically closed when they are garbage-collected.

class asyncore.dispatcher_with_send

A dispatcher subclass which adds simple buffered output capability, useful for simple clients. For more sophisticated usage use asynchat.async_chat.

class asyncore.file_dispatcher

A file_dispatcher takes a file descriptor or file object along with an optional map argument and wraps it for use with the poll() or loop() functions. If provided a file object or anything with a fileno() method, that method will be called and passed to the file_wrapper constructor.

Availability: Unix.

class asyncore.file_wrapper

A file_wrapper takes an integer file descriptor and calls os.dup() to duplicate the handle so that the original handle may be closed independently of the file_wrapper. This class implements sufficient methods to emulate a socket for use by the file_dispatcher class.

Availability: Unix.

asyncore Example basic HTTP client

Here is a very basic HTTP client that uses the dispatcher class to implement its socket handling:

import asyncore

class HTTPClient(asyncore.dispatcher):

    def __init__(self, host, path):
        asyncore.dispatcher.__init__(self)
        self.create_socket()
        self.connect( (host, 80) )
        self.buffer = bytes('GET %s HTTP/1.0\r\nHost: %s\r\n\r\n' %
                            (path, host), 'ascii')

    def handle_connect(self):
        pass

    def handle_close(self):
        self.close()

    def handle_read(self):
        print(self.recv(8192))

    def writable(self):
        return (len(self.buffer) > 0)

    def handle_write(self):
        sent = self.send(self.buffer)
        self.buffer = self.buffer[sent:]

client = HTTPClient('www.python.org', '/')
asyncore.loop()

asyncore Example basic echo server

Here is a basic echo server that uses the dispatcher class to accept connections and dispatches the incoming connections to a handler:

import asyncore

class EchoHandler(asyncore.dispatcher_with_send):

    def handle_read(self):
        data = self.recv(8192)
        if data:
            self.send(data)

class EchoServer(asyncore.dispatcher):

    def __init__(self, host, port):
        asyncore.dispatcher.__init__(self)
        self.create_socket()
        self.set_reuse_addr()
        self.bind((host, port))
        self.listen(5)

    def handle_accepted(self, sock, addr):
        print('Incoming connection from %s' % repr(addr))
        handler = EchoHandler(sock)

server = EchoServer('localhost', 8080)
asyncore.loop()

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

네트워킹과 프로세스 간 통신 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

네트워킹과 프로세스 간 통신 »

|

asynchat — Asynchronous socket command/response handler

Source code: Lib/asynchat.py [https://github.com/python/cpython/tree/3.7/Lib/asynchat.py]

버전 3.6부터 폐지: Please use asyncio instead.

참고

This module exists for backwards compatibility only. For new code we recommend using asyncio.

This module builds on the asyncore infrastructure, simplifying asynchronous clients and servers and making it easier to handle protocols whose elements are terminated by arbitrary strings, or are of variable length. asynchat defines the abstract class async_chat that you subclass, providing implementations of the collect_incoming_data() and found_terminator() methods. It uses the same asynchronous loop as asyncore, and the two types of channel, asyncore.dispatcher and asynchat.async_chat, can freely be mixed in the channel map. Typically an asyncore.dispatcher server channel generates new asynchat.async_chat channel objects as it receives incoming connection requests.

class asynchat.async_chat

This class is an abstract subclass of asyncore.dispatcher. To make practical use of the code you must subclass async_chat, providing meaningful collect_incoming_data() and found_terminator() methods. The asyncore.dispatcher methods can be used, although not all make sense in a message/response context.

Like asyncore.dispatcher, async_chat defines a set of events that are generated by an analysis of socket conditions after a select() call. Once the polling loop has been started the async_chat object’s methods are called by the event-processing framework with no action on the part of the programmer.

Two class attributes can be modified, to improve performance, or possibly even to conserve memory.

ac_in_buffer_size

The asynchronous input buffer size (default 4096).

ac_out_buffer_size

The asynchronous output buffer size (default 4096).

Unlike asyncore.dispatcher, async_chat allows you to define a FIFO queue of producers. A producer need have only one method, more(), which should return data to be transmitted on the channel. The producer indicates exhaustion (i.e. that it contains no more data) by having its more() method return the empty bytes object. At this point the async_chat object removes the producer from the queue and starts using the next producer, if any. When the producer queue is empty the handle_write() method does nothing. You use the channel object’s set_terminator() method to describe how to recognize the end of, or an important breakpoint in, an incoming transmission from the remote endpoint.

To build a functioning async_chat subclass your input methods collect_incoming_data() and found_terminator() must handle the data that the channel receives asynchronously. The methods are described below.

async_chat.close_when_done()

Pushes a None on to the producer queue. When this producer is popped off the queue it causes the channel to be closed.

async_chat.collect_incoming_data(data)

Called with data holding an arbitrary amount of received data. The default method, which must be overridden, raises a NotImplementedError exception.

async_chat.discard_buffers()

In emergencies this method will discard any data held in the input and/or output buffers and the producer queue.

async_chat.found_terminator()

Called when the incoming data stream matches the termination condition set by set_terminator(). The default method, which must be overridden, raises a NotImplementedError exception. The buffered input data should be available via an instance attribute.

async_chat.get_terminator()

Returns the current terminator for the channel.

async_chat.push(data)

Pushes data on to the channel’s queue to ensure its transmission. This is all you need to do to have the channel write the data out to the network, although it is possible to use your own producers in more complex schemes to implement encryption and chunking, for example.

async_chat.push_with_producer(producer)

Takes a producer object and adds it to the producer queue associated with the channel. When all currently-pushed producers have been exhausted the channel will consume this producer’s data by calling its more() method and send the data to the remote endpoint.

async_chat.set_terminator(term)

Sets the terminating condition to be recognized on the channel. term may be any of three types of value, corresponding to three different ways to handle incoming protocol data.

term

Description

string

Will call found_terminator() when the string is found in the input stream

integer

Will call found_terminator() when the indicated number of characters have been received

None

The channel continues to collect data forever

Note that any data following the terminator will be available for reading by the channel after found_terminator() is called.

asynchat Example

The following partial example shows how HTTP requests can be read with async_chat. A web server might create an http_request_handler object for each incoming client connection. Notice that initially the channel terminator is set to match the blank line at the end of the HTTP headers, and a flag indicates that the headers are being read.

Once the headers have been read, if the request is of type POST (indicating that further data are present in the input stream) then the Content-Length: header is used to set a numeric terminator to read the right amount of data from the channel.

The handle_request() method is called once all relevant input has been marshalled, after setting the channel terminator to None to ensure that any extraneous data sent by the web client are ignored.

import asynchat

class http_request_handler(asynchat.async_chat):

    def __init__(self, sock, addr, sessions, log):
        asynchat.async_chat.__init__(self, sock=sock)
        self.addr = addr
        self.sessions = sessions
        self.ibuffer = []
        self.obuffer = b""
        self.set_terminator(b"\r\n\r\n")
        self.reading_headers = True
        self.handling = False
        self.cgi_data = None
        self.log = log

    def collect_incoming_data(self, data):
        """Buffer the data"""
        self.ibuffer.append(data)

    def found_terminator(self):
        if self.reading_headers:
            self.reading_headers = False
            self.parse_headers(b"".join(self.ibuffer))
            self.ibuffer = []
            if self.op.upper() == b"POST":
                clen = self.headers.getheader("content-length")
                self.set_terminator(int(clen))
            else:
                self.handling = True
                self.set_terminator(None)
                self.handle_request()
        elif not self.handling:
            self.set_terminator(None)  # browsers sometimes over-send
            self.cgi_data = parse(self.headers, b"".join(self.ibuffer))
            self.handling = True
            self.ibuffer = []
            self.handle_request()

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

네트워킹과 프로세스 간 통신 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

네트워킹과 프로세스 간 통신 »

|

signal — Set handlers for asynchronous events

This module provides mechanisms to use signal handlers in Python.

General rules

The signal.signal() function allows defining custom handlers to be executed when a signal is received. A small number of default handlers are installed: SIGPIPE is ignored (so write errors on pipes and sockets can be reported as ordinary Python exceptions) and SIGINT is translated into a KeyboardInterrupt exception if the parent process has not changed it.

A handler for a particular signal, once set, remains installed until it is explicitly reset (Python emulates the BSD style interface regardless of the underlying implementation), with the exception of the handler for SIGCHLD, which follows the underlying implementation.

Execution of Python signal handlers

A Python signal handler does not get executed inside the low-level (C) signal handler. Instead, the low-level signal handler sets a flag which tells the virtual machine to execute the corresponding Python signal handler at a later point(for example at the next bytecode instruction). This has consequences:

It makes little sense to catch synchronous errors like SIGFPE or SIGSEGV that are caused by an invalid operation in C code. Python will return from the signal handler to the C code, which is likely to raise the same signal again, causing Python to apparently hang. From Python 3.3 onwards, you can use the faulthandler module to report on synchronous errors.

A long-running calculation implemented purely in C (such as regular expression matching on a large body of text) may run uninterrupted for an arbitrary amount of time, regardless of any signals received. The Python signal handlers will be called when the calculation finishes.

Signals and threads

Python signal handlers are always executed in the main Python thread, even if the signal was received in another thread. This means that signals can’t be used as a means of inter-thread communication. You can use the synchronization primitives from the threading module instead.

Besides, only the main thread is allowed to set a new signal handler.

Module contents

버전 3.5에서 변경: signal (SIG*), handler (SIG_DFL, SIG_IGN) and sigmask (SIG_BLOCK, SIG_UNBLOCK, SIG_SETMASK) related constants listed below were turned into enums. getsignal(), pthread_sigmask(), sigpending() and sigwait() functions return human-readable enums.

The variables defined in the signal module are:

signal.SIG_DFL

This is one of two standard signal handling options; it will simply perform the default function for the signal. For example, on most systems the default action for SIGQUIT is to dump core and exit, while the default action for SIGCHLD is to simply ignore it.

signal.SIG_IGN

This is another standard signal handler, which will simply ignore the given signal.

signal.SIGABRT

Abort signal from abort(3).

signal.SIGALRM

Timer signal from alarm(2).

Availability: Unix.

signal.SIGBREAK

Interrupt from keyboard (CTRL + BREAK).

Availability: Windows.

signal.SIGBUS

Bus error (bad memory access).

Availability: Unix.

signal.SIGCHLD

Child process stopped or terminated.

Availability: Windows.

signal.SIGCLD

Alias to SIGCHLD.

signal.SIGCONT

Continue the process if it is currently stopped

Availability: Unix.

signal.SIGFPE

Floating-point exception. For example, division by zero.

더 보기

ZeroDivisionError is raised when the second argument of a division or modulo operation is zero.

signal.SIGHUP

Hangup detected on controlling terminal or death of controlling process.

Availability: Unix.

signal.SIGILL

Illegal instruction.

signal.SIGINT

Interrupt from keyboard (CTRL + C).

Default action is to raise KeyboardInterrupt.

signal.SIGKILL

Kill signal.

It cannot be caught, blocked, or ignored.

Availability: Unix.

signal.SIGPIPE

Broken pipe: write to pipe with no readers.

Default action is to ignore the signal.

Availability: Unix.

signal.SIGSEGV

Segmentation fault: invalid memory reference.

signal.SIGTERM

Termination signal.

signal.SIGUSR1

User-defined signal 1.

Availability: Unix.

signal.SIGUSR2

User-defined signal 2.

Availability: Unix.

signal.SIGWINCH

Window resize signal.

Availability: Unix.

SIG*

All the signal numbers are defined symbolically. For example, the hangup signal is defined as signal.SIGHUP; the variable names are identical to the names used in C programs, as found in <signal.h>. The Unix man page for ‘signal()’ lists the existing signals (on some systems this is signal(2), on others the list is in signal(7)). Note that not all systems define the same set of signal names; only those names defined by the system are defined by this module.

signal.CTRL_C_EVENT

The signal corresponding to the Ctrl+C keystroke event. This signal can only be used with os.kill().

Availability: Windows.

버전 3.2에 추가.

signal.CTRL_BREAK_EVENT

The signal corresponding to the Ctrl+Break keystroke event. This signal can only be used with os.kill().

Availability: Windows.

버전 3.2에 추가.

signal.NSIG

One more than the number of the highest signal number.

signal.ITIMER_REAL

Decrements interval timer in real time, and delivers SIGALRM upon expiration.

signal.ITIMER_VIRTUAL

Decrements interval timer only when the process is executing, and delivers SIGVTALRM upon expiration.

signal.ITIMER_PROF

Decrements interval timer both when the process executes and when the system is executing on behalf of the process. Coupled with ITIMER_VIRTUAL, this timer is usually used to profile the time spent by the application in user and kernel space. SIGPROF is delivered upon expiration.

signal.SIG_BLOCK

A possible value for the how parameter to pthread_sigmask() indicating that signals are to be blocked.

버전 3.3에 추가.

signal.SIG_UNBLOCK

A possible value for the how parameter to pthread_sigmask() indicating that signals are to be unblocked.

버전 3.3에 추가.

signal.SIG_SETMASK

A possible value for the how parameter to pthread_sigmask() indicating that the signal mask is to be replaced.

버전 3.3에 추가.

The signal module defines one exception:

exception signal.ItimerError

Raised to signal an error from the underlying setitimer() or getitimer() implementation. Expect this error if an invalid interval timer or a negative time is passed to setitimer(). This error is a subtype of OSError.

버전 3.3에 추가: This error used to be a subtype of IOError, which is now an alias of OSError.

The signal module defines the following functions:

signal.alarm(time)

If time is non-zero, this function requests that a SIGALRM signal be sent to the process in time seconds. Any previously scheduled alarm is canceled (only one alarm can be scheduled at any time). The returned value is then the number of seconds before any previously set alarm was to have been delivered. If time is zero, no alarm is scheduled, and any scheduled alarm is canceled. If the return value is zero, no alarm is currently scheduled.

Availability: Unix. See the man page alarm(2) for further information.

signal.getsignal(signalnum)

Return the current signal handler for the signal signalnum. The returned value may be a callable Python object, or one of the special values signal.SIG_IGN, signal.SIG_DFL or None. Here, signal.SIG_IGN means that the signal was previously ignored, signal.SIG_DFL means that the default way of handling the signal was previously in use, and None means that the previous signal handler was not installed from Python.

signal.pause()

Cause the process to sleep until a signal is received; the appropriate handler will then be called. Returns nothing.

Availability: Unix. See the man page signal(2) for further information.

See also sigwait(), sigwaitinfo(), sigtimedwait() and sigpending().

signal.pthread_kill(thread_id, signalnum)

Send the signal signalnum to the thread thread_id, another thread in the same process as the caller. The target thread can be executing any code (Python or not). However, if the target thread is executing the Python interpreter, the Python signal handlers will be executed by the main thread. Therefore, the only point of sending a signal to a particular Python thread would be to force a running system call to fail with InterruptedError.

Use threading.get_ident() or the ident attribute of threading.Thread objects to get a suitable value for thread_id.

If signalnum is 0, then no signal is sent, but error checking is still performed; this can be used to check if the target thread is still running.

Availability: Unix. See the man page pthread_kill(3) for further information.

See also os.kill().

버전 3.3에 추가.

signal.pthread_sigmask(how, mask)

Fetch and/or change the signal mask of the calling thread. The signal mask is the set of signals whose delivery is currently blocked for the caller. Return the old signal mask as a set of signals.

The behavior of the call is dependent on the value of how, as follows.

SIG_BLOCK: The set of blocked signals is the union of the current set and the mask argument.

SIG_UNBLOCK: The signals in mask are removed from the current set of blocked signals. It is permissible to attempt to unblock a signal which is not blocked.

SIG_SETMASK: The set of blocked signals is set to the mask argument.

mask is a set of signal numbers (e.g. {signal.SIGINT, signal.SIGTERM}). Use range(1, signal.NSIG) for a full mask including all signals.

For example, signal.pthread_sigmask(signal.SIG_BLOCK, []) reads the signal mask of the calling thread.

SIGKILL and SIGSTOP cannot be blocked.

Availability: Unix. See the man page sigprocmask(3) and pthread_sigmask(3) for further information.

See also pause(), sigpending() and sigwait().

버전 3.3에 추가.

signal.setitimer(which, seconds, interval=0.0)

Sets given interval timer (one of signal.ITIMER_REAL, signal.ITIMER_VIRTUAL or signal.ITIMER_PROF) specified by which to fire after seconds (float is accepted, different from alarm()) and after that every interval seconds (if interval is non-zero). The interval timer specified by which can be cleared by setting seconds to zero.

When an interval timer fires, a signal is sent to the process. The signal sent is dependent on the timer being used; signal.ITIMER_REAL will deliver SIGALRM, signal.ITIMER_VIRTUAL sends SIGVTALRM, and signal.ITIMER_PROF will deliver SIGPROF.

The old values are returned as a tuple: (delay, interval).

Attempting to pass an invalid interval timer will cause an ItimerError.

Availability: Unix.

signal.getitimer(which)

Returns current value of a given interval timer specified by which.

Availability: Unix.

signal.set_wakeup_fd(fd, *, warn_on_full_buffer=True)

Set the wakeup file descriptor to fd. When a signal is received, the signal number is written as a single byte into the fd. This can be used by a library to wakeup a poll or select call, allowing the signal to be fully processed.

The old wakeup fd is returned (or -1 if file descriptor wakeup was not enabled). If fd is -1, file descriptor wakeup is disabled. If not -1, fd must be non-blocking. It is up to the library to remove any bytes from fd before calling poll or select again.

When threads are enabled, this function can only be called from the main thread; attempting to call it from other threads will cause a ValueError exception to be raised.

There are two common ways to use this function. In both approaches, you use the fd to wake up when a signal arrives, but then they differ in how they determine which signal or signals have arrived.

In the first approach, we read the data out of the fd’s buffer, and the byte values give you the signal numbers. This is simple, but in rare cases it can run into a problem: generally the fd will have a limited amount of buffer space, and if too many signals arrive too quickly, then the buffer may become full, and some signals may be lost. If you use this approach, then you should set warn_on_full_buffer=True, which will at least cause a warning to be printed to stderr when signals are lost.

In the second approach, we use the wakeup fd only for wakeups, and ignore the actual byte values. In this case, all we care about is whether the fd’s buffer is empty or non-empty; a full buffer doesn’t indicate a problem at all. If you use this approach, then you should set warn_on_full_buffer=False, so that your users are not confused by spurious warning messages.

버전 3.5에서 변경: On Windows, the function now also supports socket handles.

버전 3.7에서 변경: Added warn_on_full_buffer parameter.

signal.siginterrupt(signalnum, flag)

Change system call restart behaviour: if flag is False, system calls will be restarted when interrupted by signal signalnum, otherwise system calls will be interrupted. Returns nothing.

Availability: Unix. See the man page siginterrupt(3) for further information.

Note that installing a signal handler with signal() will reset the restart behaviour to interruptible by implicitly calling siginterrupt() with a true flag value for the given signal.

signal.signal(signalnum, handler)

Set the handler for signal signalnum to the function handler. handler can be a callable Python object taking two arguments (see below), or one of the special values signal.SIG_IGN or signal.SIG_DFL. The previous signal handler will be returned (see the description of getsignal() above). (See the Unix man page signal(2) for further information.)

When threads are enabled, this function can only be called from the main thread; attempting to call it from other threads will cause a ValueError exception to be raised.

The handler is called with two arguments: the signal number and the current stack frame (None or a frame object; for a description of frame objects, see the description in the type hierarchy or see the attribute descriptions in the inspect module).

On Windows, signal() can only be called with SIGABRT, SIGFPE, SIGILL, SIGINT, SIGSEGV, SIGTERM, or SIGBREAK. A ValueError will be raised in any other case. Note that not all systems define the same set of signal names; an AttributeError will be raised if a signal name is not defined as SIG* module level constant.

signal.sigpending()

Examine the set of signals that are pending for delivery to the calling thread (i.e., the signals which have been raised while blocked). Return the set of the pending signals.

Availability: Unix. See the man page sigpending(2) for further information.

See also pause(), pthread_sigmask() and sigwait().

버전 3.3에 추가.

signal.sigwait(sigset)

Suspend execution of the calling thread until the delivery of one of the signals specified in the signal set sigset. The function accepts the signal (removes it from the pending list of signals), and returns the signal number.

Availability: Unix. See the man page sigwait(3) for further information.

See also pause(), pthread_sigmask(), sigpending(), sigwaitinfo() and sigtimedwait().

버전 3.3에 추가.

signal.sigwaitinfo(sigset)

Suspend execution of the calling thread until the delivery of one of the signals specified in the signal set sigset. The function accepts the signal and removes it from the pending list of signals. If one of the signals in sigset is already pending for the calling thread, the function will return immediately with information about that signal. The signal handler is not called for the delivered signal. The function raises an InterruptedError if it is interrupted by a signal that is not in sigset.

The return value is an object representing the data contained in the siginfo_t structure, namely: si_signo, si_code, si_errno, si_pid, si_uid, si_status, si_band.

Availability: Unix. See the man page sigwaitinfo(2) for further information.

See also pause(), sigwait() and sigtimedwait().

버전 3.3에 추가.

버전 3.5에서 변경: The function is now retried if interrupted by a signal not in sigset and the signal handler does not raise an exception (see PEP 475 [https://www.python.org/dev/peps/pep-0475] for the rationale).

signal.sigtimedwait(sigset, timeout)

Like sigwaitinfo(), but takes an additional timeout argument specifying a timeout. If timeout is specified as 0, a poll is performed. Returns None if a timeout occurs.

Availability: Unix. See the man page sigtimedwait(2) for further information.

See also pause(), sigwait() and sigwaitinfo().

버전 3.3에 추가.

버전 3.5에서 변경: The function is now retried with the recomputed timeout if interrupted by a signal not in sigset and the signal handler does not raise an exception (see PEP 475 [https://www.python.org/dev/peps/pep-0475] for the rationale).

Example

Here is a minimal example program. It uses the alarm() function to limit the time spent waiting to open a file; this is useful if the file is for a serial device that may not be turned on, which would normally cause the os.open() to hang indefinitely. The solution is to set a 5-second alarm before opening the file; if the operation takes too long, the alarm signal will be sent, and the handler raises an exception.

import signal, os

def handler(signum, frame):
    print('Signal handler called with signal', signum)
    raise OSError("Couldn't open device!")

# Set the signal handler and a 5-second alarm
signal.signal(signal.SIGALRM, handler)
signal.alarm(5)

# This open() may hang indefinitely
fd = os.open('/dev/ttyS0', os.O_RDWR)

signal.alarm(0)          # Disable the alarm

Note on SIGPIPE

Piping output of your program to tools like head(1) will cause a SIGPIPE signal to be sent to your process when the receiver of its standard output closes early. This results in an exception like BrokenPipeError: [Errno 32] Broken pipe. To handle this case, wrap your entry point to catch this exception as follows:

import os
import sys

def main():
    try:
        # simulate large output (your code replaces this loop)
        for x in range(10000):
            print("y")
        # flush output here to force SIGPIPE to be triggered
        # while inside this try block.
        sys.stdout.flush()
    except BrokenPipeError:
        # Python flushes standard streams on exit; redirect remaining output
        # to devnull to avoid another BrokenPipeError at shutdown
        devnull = os.open(os.devnull, os.O_WRONLY)
        os.dup2(devnull, sys.stdout.fileno())
        sys.exit(1)  # Python exits with error code 1 on EPIPE

if __name__ == '__main__':
    main()

Do not set SIGPIPE’s disposition to SIG_DFL in order to avoid BrokenPipeError. Doing that would cause your program to exit unexpectedly also whenever any socket connection is interrupted while your program is still writing to it.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

네트워킹과 프로세스 간 통신 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

네트워킹과 프로세스 간 통신 »

|

mmap — 메모리 맵 파일 지원

메모리 맵 파일 객체는 동시에 bytearray 와 파일 객체처럼 작동합니다. bytearray를 기대하는 대부분 장소에서 mmap 객체를 사용할 수 있습니다. 예를 들어, re 모듈을 사용하여 메모리 맵 파일을 검색할 수 있습니다. obj[index] = 97를 사용해서 한 바이트를 변경하거나, 슬라이스에 대입하여 서브 시퀀스를 변경할 수도 있습니다: obj[i1:i2] = b'...'. 또한 현재 파일 위치에서 시작하여 데이터를 읽고 쓸 수 있고, 다른 위치로 파일을 seek() 할 수 있습니다.

메모리 맵 파일은 mmap 생성자로 만드는데, 유닉스와 윈도우에서 다릅니다. 두 경우 모두 갱신을 위해 열린 파일에 대한 파일 기술자를 제공해야 합니다. 기존 파이썬 파일 객체를 매핑하려면, fileno() 메서드를 사용하여 fileno 매개 변수에 대한 올바른 값을 가져오십시오. 그렇지 않으면, 파일 기술자를 직접 반환하는 os.open() 함수를 사용하여 파일을 열 수 있습니다 (완료되면 파일을 닫아야 합니다).

참고

쓰기 가능하고 버퍼링 되는 파일에 대한 메모리 맵을 만들려면, 먼저 파일을 flush()해야 합니다. 버퍼에 대한 지역 변경 사항이 실제로 매핑에 반영되게 하는 데 필요합니다.

유닉스와 윈도우 버전의 생성자 모두에서, access는 선택적 키워드 매개 변수로 지정될 수 있습니다. access는 ACCESS_READ, ACCESS_WRITE 또는 ACCESS_COPY 중 하나의 값을 받아, 읽기 전용, 동시 기록(write-through) 또는 쓸 때 복사(copy-on-write) 메모리를 각각 지정하거나, ACCESS_DEFAULT를 사용하여 prot로 위임합니다. access는 유닉스와 윈도우에서 모두 사용할 수 있습니다. access를 지정하지 않으면, 윈도우 mmap은 동시 기록(write-through) 매핑을 반환합니다. 세 가지 액세스 유형 모두에서 초기 메모리값은 지정된 파일에서 가져옵니다. ACCESS_READ 메모리 맵에 대입하면 TypeError 예외가 발생합니다. ACCESS_WRITE 메모리 맵에 대입하면 메모리와 하부 파일에 모두 영향을 줍니다. ACCESS_COPY 메모리 맵에 대입하면 메모리에는 영향을 미치지만, 하부 파일은 변경되지 않습니다.

버전 3.7에서 변경: ACCESS_DEFAULT 상수가 추가되었습니다.

익명 메모리를 매핑하려면, length와 함께 -1을 fileno로 전달해야 합니다.

class mmap.mmap(fileno, length, tagname=None, access=ACCESS_DEFAULT[, offset])

(윈도우 버전) 파일 핸들 fileno로 지정된 파일의 length 바이트를 매핑하고, mmap 객체를 만듭니다. length가 파일의 현재 크기보다 크면, 파일은 length 바이트를 포함하도록 확장됩니다. length가 0 이면, 맵의 최대 길이는 파일의 현재 길이입니다. 단, 파일이 비어 있으면 윈도우에서 예외가 발생합니다 (윈도우에는 빈 매핑을 만들 수 없습니다).

tagname가 지정되고 None이 아니면, 매핑의 태그 이름을 제공하는 문자열입니다. 윈도우에서는 같은 파일에 대해 여러 가지 다른 매핑을 사용할 수 있게 합니다. 기존 태그의 이름을 지정하면, 해당 태그가 열리고, 그렇지 않으면 이 이름의 새 태그가 만들어집니다. 이 매개 변수가 생략되거나 None 이면, 매핑은 이름 없이 만들어집니다. 태그 매개 변수의 사용을 피하면 코드를 유닉스와 윈도우 사이에서 이식성 있게 유지할 수 있습니다.

offset은 음이 아닌 정수 오프셋으로 지정할 수 있습니다. mmap 참조는 파일 시작 부분으로부터의 오프셋에 상대적입니다. offset의 기본값은 0입니다. offset은 ALLOCATIONGRANULARITY의 배수여야 합니다.

class mmap.mmap(fileno, length, flags=MAP_SHARED, prot=PROT_WRITE|PROT_READ, access=ACCESS_DEFAULT[, offset])

(유닉스 버전) 파일 기술자 fileno로 지정된 파일의 length 바이트를 매핑하고, mmap 객체를 반환합니다. length가 0 이면, 맵의 최대 길이는 mmap가 호출될 때 파일의 현재 길이입니다.

flags는 매핑의 특성을 지정합니다. MAP_PRIVATE는 비공개 쓸 때 복사 (copy-on-write) 매핑을 생성하므로, mmap 객체의 내용에 대한 변경 사항은 이 프로세스에만 적용되고, MAP_SHARED는 파일의 같은 영역을 매핑하는 다른 모든 프로세스와 공유되는 매핑을 만듭니다. 기본값은 MAP_SHARED입니다.

prot가 지정되면 원하는 메모리 보호를 제공합니다; 가장 유용한 두 값은 페이지를 읽거나 쓰도록 지정할 수 있는 PROT_READ와 PROT_WRITE입니다. prot의 기본값은 PROT_READ | PROT_WRITE입니다.

access는 선택적 키워드 매개 변수로 flags 와 prot 대신 지정 될 수 있습니다. flags, prot 와 access를 모두 지정하는 것은 에러입니다. 이 매개 변수를 사용하는 방법에 대한 정보는 위의 access 설명을 참조하십시오.

offset은 음이 아닌 정수 오프셋으로 지정할 수 있습니다. mmap 참조는 파일 시작 부분으로부터의 오프셋에 상대적입니다. offset의 기본값은 0입니다. offset은 유닉스 시스템에서 PAGESIZE와 같은 ALLOCATIONGRANULARITY의 배수여야 합니다.

생성된 메모리 매핑의 유효성을 보장하기 위해, 기술자 fileno로 지정된 파일은 맥 OS X 및 OpenVMS의 물리적 저장 장치와 내부적으로 자동 동기화됩니다.

이 예제는 mmap을 사용하는 간단한 방법을 보여줍니다:

import mmap

# write a simple example file
with open("hello.txt", "wb") as f:
    f.write(b"Hello Python!\n")

with open("hello.txt", "r+b") as f:
    # memory-map the file, size 0 means whole file
    mm = mmap.mmap(f.fileno(), 0)
    # read content via standard file methods
    print(mm.readline())  # prints b"Hello Python!\n"
    # read content via slice notation
    print(mm[:5])  # prints b"Hello"
    # update content using slice notation;
    # note that new content must have same size
    mm[6:] = b" world!\n"
    # ... and read again using standard file methods
    mm.seek(0)
    print(mm.readline())  # prints b"Hello  world!\n"
    # close the map
    mm.close()

mmap은 with 문에서 컨텍스트 관리자로 사용할 수도 있습니다:

import mmap

with mmap.mmap(-1, 13) as mm:
    mm.write(b"Hello world!")

버전 3.2에 추가: 컨텍스트 관리자 지원.

다음 예제는 익명 맵을 만들고 부모와 자식 프로세스 간에 데이터를 교환하는 방법을 보여줍니다:

import mmap
import os

mm = mmap.mmap(-1, 13)
mm.write(b"Hello world!")

pid = os.fork()

if pid == 0:  # In a child process
    mm.seek(0)
    print(mm.readline())

    mm.close()

메모리 맵 파일 객체는 다음 메서드를 지원합니다:

close()

mmap를 닫습니다. 이후에 객체의 다른 메서드를 호출하면 ValueError 예외가 발생합니다. 열려있는 파일을 닫지 않습니다.

closed

파일이 닫혔으면 True입니다.

버전 3.2에 추가.

find(sub[, start[, end]])

서브 시퀀스 sub가 발견되는 객체에서 가장 낮은 인덱스를 반환합니다. sub는 [start, end] 범위에 포함되어야 합니다. 선택적 인자 start 와 end는 슬라이스 표기법처럼 해석됩니다. 실패하면 -1를 반환합니다.

버전 3.5에서 변경: 이제 쓰기 가능한 바이트열류 객체를 받아들입니다.

flush([offset[, size]])

파일의 메모리 내 복사본에 대한 변경 사항을 디스크로 플러시 합니다. 이 호출을 사용하지 않으면, 객체가 파괴되기 전에 변경 내용이 기록된다고 보장할 수 없습니다. offset과 size가 지정되면, 지정된 바이트 범위의 변경 사항만 디스크로 플러시 됩니다; 그렇지 않으면, 매핑의 전체 범위가 플러시 됩니다. offset은 PAGESIZE 나 ALLOCATIONGRANULARITY의 배수여야 합니다.

(윈도우 버전) 반환된 0이 아닌 값은 성공을 나타냅니다; 0은 실패를 나타냅니다.

(유닉스 버전) 성공을 나타내기 위해 0 값이 반환됩니다. 호출이 실패하면 예외가 발생합니다.

move(dest, src, count)

오프셋 src에서 시작하는 count 바이트를 대상 인덱스 dest로 복사합니다. mmap이 ACCESS_READ로 만들어졌으면, move를 호출하면 TypeError 예외가 발생합니다.

read([n])

현재의 파일 위치로부터 최대 n 바이트를 포함하는 bytes를 반환합니다. 인자가 생략되거나 None 이거나 음수면, 현재 파일 위치에서 매핑의 끝까지 모든 바이트를 반환합니다. 파일 위치는 반환된 바이트의 뒤를 가리키도록 갱신됩니다.

버전 3.3에서 변경: 인자는 생략되거나 None 일 수 있습니다.

read_byte()

현재 파일 위치의 한 바이트를 정수로 반환하고, 파일 위치를 1 증가시킵니다.

readline()

현재 파일 위치에서 시작하여 다음 줄 바꿈까지 한 줄을 반환합니다.

resize(newsize)

맵과 하부 파일(있다면)의 크기를 조정합니다. mmap이 ACCESS_READ 나 ACCESS_COPY로 만들어졌을 때, 맵의 크기를 조정하면 TypeError 예외가 발생합니다.

rfind(sub[, start[, end]])

서브 시퀀스 sub가 발견되는 객체에서 가장 높은 인덱스를 반환합니다. sub는 [start, end] 범위에 포함되어야 합니다. 선택적 인자 start 와 end는 슬라이스 표기법처럼 해석됩니다. 실패하면 -1를 반환합니다.

버전 3.5에서 변경: 이제 쓰기 가능한 바이트열류 객체를 받아들입니다.

seek(pos[, whence])

파일의 현재 위치를 설정합니다. whence 인자는 선택적이며 기본값은 os.SEEK_SET 또는 0 (절대 파일 위치)입니다; 다른 값은 os.SEEK_CUR 또는 1 (현재 위치를 기준으로 seek)과 os.SEEK_END 또는 2 (파일의 끝을 기준으로 seek)입니다.

size()

파일의 길이를 반환합니다. 메모리 매핑된 영역의 크기보다 클 수 있습니다.

tell()

파일 포인터의 현재 위치를 반환합니다.

write(bytes)

bytes의 바이트를 파일 포인터의 현재 위치에 있는 메모리에 기록하고 기록된 바이트 수를 반환합니다 (쓰기가 실패하면 ValueError가 발생하기 때문에 결코 len(bytes)보다 작지 않습니다). 파일 위치는 기록된 바이트 뒤를 가리 키도록 갱신됩니다. mmap이 ACCESS_READ로 만들어졌으면, 기록할 때 TypeError 예외가 발생합니다.

버전 3.5에서 변경: 이제 쓰기 가능한 바이트열류 객체를 받아들입니다.

버전 3.6에서 변경: 이제 기록한 바이트 수가 반환됩니다.

write_byte(byte)

정수 byte를 파일 포인터의 현재 위치에 있는 메모리에 기록합니다; 파일 위치가 1 증가합니다. mmap이 ACCESS_READ로 만들어졌으면, 기록할 때 TypeError 예외가 발생합니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

네트워킹과 프로세스 간 통신 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

|

인터넷 데이터 처리

이 장에서는 인터넷에서 일반적으로 사용되는 데이터 형식 처리를 지원하는 모듈에 관해 설명합니다.

email — 전자 메일과 MIME 처리 패키지

email.message: Representing an email message

email.parser: Parsing email messages

FeedParser API

Parser API

Additional notes

email.generator: Generating MIME documents

email.policy: Policy Objects

email.errors: 예외와 결함 클래스

email.headerregistry: Custom Header Objects

email.contentmanager: MIME 콘텐츠 관리

콘텐츠 관리자 인스턴스

email: 예제

email.message.Message: Representing an email message using the compat32 API

email.mime: Creating email and MIME objects from scratch

email.header: Internationalized headers

email.charset: Representing character sets

email.encoders: Encoders

email.utils: 기타 유틸리티

email.iterators: 이터레이터

json — JSON 인코더와 디코더

기본 사용법

인코더와 디코더

예외

표준 준수와 상호 운용성

문자 인코딩

무한대와 NaN 숫자 값

오브젝트 내에서 반복된 이름

오브젝트나 배열이 아닌 최상윗값

구현 제약 사항

명령 줄 인터페이스

명령 줄 옵션

mailcap — Mailcap 파일 처리

mailbox — Manipulate mailboxes in various formats

Mailbox objects

Maildir

mbox

MH

Babyl

MMDF

Message objects

MaildirMessage

mboxMessage

MHMessage

BabylMessage

MMDFMessage

Exceptions

Examples

mimetypes — 파일명을 MIME 유형에 매핑

MimeTypes 객체

base64 — Base16, Base32, Base64, Base85 데이터 인코딩

binhex — binhex4 파일 인코딩과 디코딩

노트

binascii — 바이너리와 ASCII 간의 변환

quopri — MIME quoted-printable 데이터 인코딩과 디코딩

uu — uuencode 파일 인코딩과 디코딩

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 데이터 처리 »

|

email — 전자 메일과 MIME 처리 패키지

소스 코드: Lib/email/__init__.py [https://github.com/python/cpython/tree/3.7/Lib/email/__init__.py]

email 패키지는 전자 메일 메시지를 관리하기 위한 라이브러리입니다. 특히 SMTP (RFC 2821 [https://tools.ietf.org/html/rfc2821.html]), NNTP 또는 다른 서버로 전자 메일 메시지를 보내도록 설계되지 않았습니다; 그런 것들은 smtplib와 nntplib 같은 모듈의 기능입니다. email 패키지는 RFC 5233 [https://tools.ietf.org/html/rfc5233.html]와 RFC 6532 [https://tools.ietf.org/html/rfc6532.html]뿐만 아니라, RFC 2045 [https://tools.ietf.org/html/rfc2045.html], RFC 2046 [https://tools.ietf.org/html/rfc2046.html], RFC 2047 [https://tools.ietf.org/html/rfc2047.html], RFC 2183 [https://tools.ietf.org/html/rfc2183.html] 및 RFC 2231 [https://tools.ietf.org/html/rfc2231.html]와 같은 MIME 관련 RFC를 지원하여 가능한 최대로 RFC를 준수하려고 시도합니다.

email 패키지의 전체 구조는 세 가지 주요 구성 요소와 다른 구성 요소의 동작을 제어하는 네 번째 구성 요소로 나눌 수 있습니다.

패키지의 중심 구성 요소는 전자 메일 메시지를 나타내는 “객체 모델”입니다. 응용 프로그램은 주로 message 서브 모듈에 정의된 객체 모델 인터페이스를 통해 패키지와 상호 작용합니다. 응용 프로그램은 이 API를 사용하여 기존 전자 메일에 대해 질문을 하거나, 새 전자 메일을 작성하거나, 같은 객체 모델 인터페이스를 사용하는 전자 메일 하위 구성 요소를 추가하거나 제거할 수 있습니다. 즉, 전자 메일 메시지와 MIME 하위 구성 요소의 특성에 따라, 전자 메일 객체 모델은 모두 EmailMessage API를 제공하는 객체의 트리 구조입니다.

패키지의 다른 두 가지 주요 구성 요소는 parser와 generator입니다. 구문 분석기(parser)는 직렬화된 전자 메일 메시지(바이트 스트림)를 가져와 EmailMessage 객체의 트리로 변환합니다. 생성기(generator)는 EmailMessage를 받아서 직렬화된 바이트 스트림으로 다시 변환합니다. (구문 분석기와 생성기는 텍스트 문자의 스트림도 처리하지만, 이 사용법은 유효하지 않은 메시지로 끝나기 쉬우므로 사용하지 않는 것이 좋습니다.)

제어 구성 요소는 policy 모듈입니다. 모든 EmailMessage, 모든 generator 및 모든 parser에는 그것의 동작을 제어하는 연관된 policy 객체가 있습니다. 일반적으로 응용 프로그램은 EmailMessage가 만들어질 때 정책을 지정하기만 하면 되는데, EmailMessage를 직접 인스턴스로 만들어서 새 전자 메일을 만들거나, parser를 사용하여 입력 스트림을 구문 분석할 때입니다. 그러나 메시지가 generator를 사용하여 직렬화될 때 정책을 변경할 수 있습니다. 이것은, 예를 들어, 범용 전자 메일 메시지를 디스크에서 구분 분석하지만, 전자 메일 서버로 보낼 때 표준 SMTP 설정을 사용하여 직렬화할 수 있도록 합니다.

email 패키지는 응용 프로그램으로부터 각종 관리적인 RFC의 세부 사항을 숨기기 위해 최선을 다합니다. 개념적으로 응용 프로그램은 전자 메일 메시지를 유니코드 텍스트와 바이너리 첨부 파일의 구조화 된 트리로 처리할 수 있어야 하며, 직렬화될 때 이것들이 어떻게 표시되는지 걱정할 필요가 없어야 합니다. 하지만, 실제로는, MIME 메시지와 그 구조, 특히 MIME “콘텐츠 형식(content type)”의 이름과 특성, 그리고 다중 부분 문서를 식별하는 방법을 관리하는 규칙 중 적어도 일부를 신경 쓸 필요가 종종 있습니다. 대부분, 이 지식은 더욱 복잡한 응용 프로그램에만 필요하며, 그럴 때도 그 구조가 어떻게 표현되는지에 대한 세부 사항이 아닌, 문제가 되는 고수준 구조에 관한 것이어야 합니다. MIME 콘텐츠 유형은 최신 인터넷 소프트웨어(전자 메일뿐만 아니라)에서 널리 사용되므로, 많은 프로그래머에게 익숙한 개념입니다.

다음 절에서는 email 패키지의 기능에 관해 설명합니다. 응용 프로그램에서 사용할 기본 인터페이스인 message 객체 모델부터 시작하여, parser와 generator 구성 요소를 다룹니다. 그런 다음 policy 제어를 다뤄서, 라이브러리의 주요 구성 요소를 마무리합니다.

다음 세 절에서는 패키지에서 발생할 수 있는 예외와 parser가 감지할 수 있는 결함(RFC를 준수하지 않는)에 관해 설명합니다. 그런 다음 headerregistry와 contentmanager 하위 구성 요소를 다룹니다. 이것들은 각각 헤더와 페이로드를 보다 자세하게 조작할 수 있는 도구를 제공합니다. 이 두 구성 요소는 모두 단순하지 않은 메시지를 소비하고 생성하는 것과 관련된 기능을 포함하지만, 고급 응용 프로그램이 관심을 가질 확장 API를 설명하기도 합니다.

그다음은 이전 절에서 다룬 API의 기본 부분들을 사용하는 일련의 예제입니다.

앞의 내용은 email 패키지의 최신(유니코드 친화적인) API를 나타냅니다. Message 클래스로 시작하는 나머지 절에서는 전자 메일 메시지가 표현되는 방법에 대한 세부 사항을 훨씬 직접 다루는 레거시 compat32 API를 다룹니다. compat32 API는 응용 프로그램으로부터 RFC 세부 사항을 숨기지 않습니다만, 그 수준에서 작동해야 하는 응용 프로그램에는 유용한 도구가 될 수 있습니다. 이 설명서는 과거 호환성을 위해 여전히 compat32 API를 사용하는 응용 프로그램과도 관련이 있습니다.

버전 3.6에서 변경: 새로운 EmailMessage/EmailPolicy API를 홍보하기 위해 설명서가 재구성되고 다시 작성되었습니다.

email 패키지 설명서의 목차:

email.message: Representing an email message

email.parser: Parsing email messages

FeedParser API

Parser API

Additional notes

email.generator: Generating MIME documents

email.policy: Policy Objects

email.errors: 예외와 결함 클래스

email.headerregistry: Custom Header Objects

email.contentmanager: MIME 콘텐츠 관리

콘텐츠 관리자 인스턴스

email: 예제

레거시 API:

email.message.Message: Representing an email message using the compat32 API

email.mime: Creating email and MIME objects from scratch

email.header: Internationalized headers

email.charset: Representing character sets

email.encoders: Encoders

email.utils: 기타 유틸리티

email.iterators: 이터레이터

더 보기

모듈 smtplib

SMTP (Simple Mail Transport Protocol) 클라이언트

모듈 poplib

POP (Post Office Protocol) 클라이언트

모듈 imaplib

IMAP (Internet Message Access Protocol) 클라이언트

모듈 nntplib

NNTP (Net News Transport Protocol) 클라이언트

모듈 mailbox

다양한 표준 형식을 사용하여 디스크에 메시지 모음을 만들고, 읽고, 관리하는 도구.

모듈 smtpd

SMTP 서버 프레임워크 (주로 테스트에 유용합니다)

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 데이터 처리 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 데이터 처리 »

email — 전자 메일과 MIME 처리 패키지 »

|

email.message: Representing an email message

Source code: Lib/email/message.py [https://github.com/python/cpython/tree/3.7/Lib/email/message.py]

버전 3.6에 추가: 1

The central class in the email package is the EmailMessage class, imported from the email.message module. It is the base class for the email object model. EmailMessage provides the core functionality for setting and querying header fields, for accessing message bodies, and for creating or modifying structured messages.

An email message consists of headers and a payload (which is also referred to as the content). Headers are RFC 5322 [https://tools.ietf.org/html/rfc5322.html] or RFC 6532 [https://tools.ietf.org/html/rfc6532.html] style field names and values, where the field name and value are separated by a colon. The colon is not part of either the field name or the field value. The payload may be a simple text message, or a binary object, or a structured sequence of sub-messages each with their own set of headers and their own payload. The latter type of payload is indicated by the message having a MIME type such as multipart/* or message/rfc822.

The conceptual model provided by an EmailMessage object is that of an ordered dictionary of headers coupled with a payload that represents the RFC 5322 [https://tools.ietf.org/html/rfc5322.html] body of the message, which might be a list of sub-EmailMessage objects. In addition to the normal dictionary methods for accessing the header names and values, there are methods for accessing specialized information from the headers (for example the MIME content type), for operating on the payload, for generating a serialized version of the message, and for recursively walking over the object tree.

The EmailMessage dictionary-like interface is indexed by the header names, which must be ASCII values. The values of the dictionary are strings with some extra methods. Headers are stored and returned in case-preserving form, but field names are matched case-insensitively. Unlike a real dict, there is an ordering to the keys, and there can be duplicate keys. Additional methods are provided for working with headers that have duplicate keys.

The payload is either a string or bytes object, in the case of simple message objects, or a list of EmailMessage objects, for MIME container documents such as multipart/* and message/rfc822 message objects.

class email.message.EmailMessage(policy=default)

If policy is specified use the rules it specifies to update and serialize the representation of the message. If policy is not set, use the default policy, which follows the rules of the email RFCs except for line endings (instead of the RFC mandated \r\n, it uses the Python standard \n line endings). For more information see the policy documentation.

as_string(unixfrom=False, maxheaderlen=None, policy=None)

Return the entire message flattened as a string. When optional unixfrom is true, the envelope header is included in the returned string. unixfrom defaults to False. For backward compatibility with the base Message class maxheaderlen is accepted, but defaults to None, which means that by default the line length is controlled by the max_line_length of the policy. The policy argument may be used to override the default policy obtained from the message instance. This can be used to control some of the formatting produced by the method, since the specified policy will be passed to the Generator.

Flattening the message may trigger changes to the EmailMessage if defaults need to be filled in to complete the transformation to a string (for example, MIME boundaries may be generated or modified).

Note that this method is provided as a convenience and may not be the most useful way to serialize messages in your application, especially if you are dealing with multiple messages. See email.generator.Generator for a more flexible API for serializing messages. Note also that this method is restricted to producing messages serialized as “7 bit clean” when utf8 is False, which is the default.

버전 3.6에서 변경: the default behavior when maxheaderlen is not specified was changed from defaulting to 0 to defaulting to the value of max_line_length from the policy.

__str__()

Equivalent to as_string(policy=self.policy.clone(utf8=True)). Allows str(msg) to produce a string containing the serialized message in a readable format.

버전 3.4에서 변경: the method was changed to use utf8=True, thus producing an RFC 6531 [https://tools.ietf.org/html/rfc6531.html]-like message representation, instead of being a direct alias for as_string().

as_bytes(unixfrom=False, policy=None)

Return the entire message flattened as a bytes object. When optional unixfrom is true, the envelope header is included in the returned string. unixfrom defaults to False. The policy argument may be used to override the default policy obtained from the message instance. This can be used to control some of the formatting produced by the method, since the specified policy will be passed to the BytesGenerator.

Flattening the message may trigger changes to the EmailMessage if defaults need to be filled in to complete the transformation to a string (for example, MIME boundaries may be generated or modified).

Note that this method is provided as a convenience and may not be the most useful way to serialize messages in your application, especially if you are dealing with multiple messages. See email.generator.BytesGenerator for a more flexible API for serializing messages.

__bytes__()

Equivalent to as_bytes(). Allows bytes(msg) to produce a bytes object containing the serialized message.

is_multipart()

Return True if the message’s payload is a list of sub-EmailMessage objects, otherwise return False. When is_multipart() returns False, the payload should be a string object (which might be a CTE encoded binary payload). Note that is_multipart() returning True does not necessarily mean that “msg.get_content_maintype() == ‘multipart’” will return the True. For example, is_multipart will return True when the EmailMessage is of type message/rfc822.

set_unixfrom(unixfrom)

Set the message’s envelope header to unixfrom, which should be a string. (See mboxMessage for a brief description of this header.)

get_unixfrom()

Return the message’s envelope header. Defaults to None if the envelope header was never set.

The following methods implement the mapping-like interface for accessing the message’s headers. Note that there are some semantic differences between these methods and a normal mapping (i.e. dictionary) interface. For example, in a dictionary there are no duplicate keys, but here there may be duplicate message headers. Also, in dictionaries there is no guaranteed order to the keys returned by keys(), but in an EmailMessage object, headers are always returned in the order they appeared in the original message, or in which they were added to the message later. Any header deleted and then re-added is always appended to the end of the header list.

These semantic differences are intentional and are biased toward convenience in the most common use cases.

Note that in all cases, any envelope header present in the message is not included in the mapping interface.

__len__()

Return the total number of headers, including duplicates.

__contains__(name)

Return True if the message object has a field named name. Matching is done without regard to case and name does not include the trailing colon. Used for the in operator. For example:

if 'message-id' in myMessage:
   print('Message-ID:', myMessage['message-id'])

__getitem__(name)

Return the value of the named header field. name does not include the colon field separator. If the header is missing, None is returned; a KeyError is never raised.

Note that if the named field appears more than once in the message’s headers, exactly which of those field values will be returned is undefined. Use the get_all() method to get the values of all the extant headers named name.

Using the standard (non-compat32) policies, the returned value is an instance of a subclass of email.headerregistry.BaseHeader.

__setitem__(name, val)

Add a header to the message with field name name and value val. The field is appended to the end of the message’s existing headers.

Note that this does not overwrite or delete any existing header with the same name. If you want to ensure that the new header is the only one present in the message with field name name, delete the field first, e.g.:

del msg['subject']
msg['subject'] = 'Python roolz!'

If the policy defines certain headers to be unique (as the standard policies do), this method may raise a ValueError when an attempt is made to assign a value to such a header when one already exists. This behavior is intentional for consistency’s sake, but do not depend on it as we may choose to make such assignments do an automatic deletion of the existing header in the future.

__delitem__(name)

Delete all occurrences of the field with name name from the message’s headers. No exception is raised if the named field isn’t present in the headers.

keys()

Return a list of all the message’s header field names.

values()

Return a list of all the message’s field values.

items()

Return a list of 2-tuples containing all the message’s field headers and values.

get(name, failobj=None)

Return the value of the named header field. This is identical to __getitem__() except that optional failobj is returned if the named header is missing (failobj defaults to None).

Here are some additional useful header related methods:

get_all(name, failobj=None)

Return a list of all the values for the field named name. If there are no such named headers in the message, failobj is returned (defaults to None).

add_header(_name, _value, **_params)

Extended header setting. This method is similar to __setitem__() except that additional header parameters can be provided as keyword arguments. _name is the header field to add and _value is the primary value for the header.

For each item in the keyword argument dictionary _params, the key is taken as the parameter name, with underscores converted to dashes (since dashes are illegal in Python identifiers). Normally, the parameter will be added as key="value" unless the value is None, in which case only the key will be added.

If the value contains non-ASCII characters, the charset and language may be explicitly controlled by specifying the value as a three tuple in the format (CHARSET, LANGUAGE, VALUE), where CHARSET is a string naming the charset to be used to encode the value, LANGUAGE can usually be set to None or the empty string (see RFC 2231 [https://tools.ietf.org/html/rfc2231.html] for other possibilities), and VALUE is the string value containing non-ASCII code points. If a three tuple is not passed and the value contains non-ASCII characters, it is automatically encoded in RFC 2231 [https://tools.ietf.org/html/rfc2231.html] format using a CHARSET of utf-8 and a LANGUAGE of None.

Here is an example:

msg.add_header('Content-Disposition', 'attachment', filename='bud.gif')

This will add a header that looks like

Content-Disposition: attachment; filename="bud.gif"

An example of the extended interface with non-ASCII characters:

msg.add_header('Content-Disposition', 'attachment',
               filename=('iso-8859-1', '', 'Fußballer.ppt'))

replace_header(_name, _value)

Replace a header. Replace the first header found in the message that matches _name, retaining header order and field name case of the original header. If no matching header is found, raise a KeyError.

get_content_type()

Return the message’s content type, coerced to lower case of the form maintype/subtype. If there is no Content-Type header in the message return the value returned by get_default_type(). If the Content-Type header is invalid, return text/plain.

(According to RFC 2045 [https://tools.ietf.org/html/rfc2045.html], messages always have a default type, get_content_type() will always return a value. RFC 2045 [https://tools.ietf.org/html/rfc2045.html] defines a message’s default type to be text/plain unless it appears inside a multipart/digest container, in which case it would be message/rfc822. If the Content-Type header has an invalid type specification, RFC 2045 [https://tools.ietf.org/html/rfc2045.html] mandates that the default type be text/plain.)

get_content_maintype()

Return the message’s main content type. This is the maintype part of the string returned by get_content_type().

get_content_subtype()

Return the message’s sub-content type. This is the subtype part of the string returned by get_content_type().

get_default_type()

Return the default content type. Most messages have a default content type of text/plain, except for messages that are subparts of multipart/digest containers. Such subparts have a default content type of message/rfc822.

set_default_type(ctype)

Set the default content type. ctype should either be text/plain or message/rfc822, although this is not enforced. The default content type is not stored in the Content-Type header, so it only affects the return value of the get_content_type methods when no Content-Type header is present in the message.

set_param(param, value, header='Content-Type', requote=True, charset=None, language='', replace=False)

Set a parameter in the Content-Type header. If the parameter already exists in the header, replace its value with value. When header is Content-Type (the default) and the header does not yet exist in the message, add it, set its value to text/plain, and append the new parameter value. Optional header specifies an alternative header to Content-Type.

If the value contains non-ASCII characters, the charset and language may be explicitly specified using the optional charset and language parameters. Optional language specifies the RFC 2231 [https://tools.ietf.org/html/rfc2231.html] language, defaulting to the empty string. Both charset and language should be strings. The default is to use the utf8 charset and None for the language.

If replace is False (the default) the header is moved to the end of the list of headers. If replace is True, the header will be updated in place.

Use of the requote parameter with EmailMessage objects is deprecated.

Note that existing parameter values of headers may be accessed through the params attribute of the header value (for example, msg['Content-Type'].params['charset']).

버전 3.4에서 변경: replace keyword was added.

del_param(param, header='content-type', requote=True)

Remove the given parameter completely from the Content-Type header. The header will be re-written in place without the parameter or its value. Optional header specifies an alternative to Content-Type.

Use of the requote parameter with EmailMessage objects is deprecated.

get_filename(failobj=None)

Return the value of the filename parameter of the Content-Disposition header of the message. If the header does not have a filename parameter, this method falls back to looking for the name parameter on the Content-Type header. If neither is found, or the header is missing, then failobj is returned. The returned string will always be unquoted as per email.utils.unquote().

get_boundary(failobj=None)

Return the value of the boundary parameter of the Content-Type header of the message, or failobj if either the header is missing, or has no boundary parameter. The returned string will always be unquoted as per email.utils.unquote().

set_boundary(boundary)

Set the boundary parameter of the Content-Type header to boundary. set_boundary() will always quote boundary if necessary. A HeaderParseError is raised if the message object has no Content-Type header.

Note that using this method is subtly different from deleting the old Content-Type header and adding a new one with the new boundary via add_header(), because set_boundary() preserves the order of the Content-Type header in the list of headers.

get_content_charset(failobj=None)

Return the charset parameter of the Content-Type header, coerced to lower case. If there is no Content-Type header, or if that header has no charset parameter, failobj is returned.

get_charsets(failobj=None)

Return a list containing the character set names in the message. If the message is a multipart, then the list will contain one element for each subpart in the payload, otherwise, it will be a list of length 1.

Each item in the list will be a string which is the value of the charset parameter in the Content-Type header for the represented subpart. If the subpart has no Content-Type header, no charset parameter, or is not of the text main MIME type, then that item in the returned list will be failobj.

is_attachment()

Return True if there is a Content-Disposition header and its (case insensitive) value is attachment, False otherwise.

버전 3.4.2에서 변경: is_attachment is now a method instead of a property, for consistency with is_multipart().

get_content_disposition()

Return the lowercased value (without parameters) of the message’s Content-Disposition header if it has one, or None. The possible values for this method are inline, attachment or None if the message follows RFC 2183 [https://tools.ietf.org/html/rfc2183.html].

버전 3.5에 추가.

The following methods relate to interrogating and manipulating the content (payload) of the message.

walk()

The walk() method is an all-purpose generator which can be used to iterate over all the parts and subparts of a message object tree, in depth-first traversal order. You will typically use walk() as the iterator in a for loop; each iteration returns the next subpart.

Here’s an example that prints the MIME type of every part of a multipart message structure:

>>> for part in msg.walk():
...     print(part.get_content_type())
multipart/report
text/plain
message/delivery-status
text/plain
text/plain
message/rfc822
text/plain

walk iterates over the subparts of any part where is_multipart() returns True, even though msg.get_content_maintype() == 'multipart' may return False. We can see this in our example by making use of the _structure debug helper function:

>>> for part in msg.walk():
...     print(part.get_content_maintype() == 'multipart',
...           part.is_multipart())
True True
False False
False True
False False
False False
False True
False False
>>> _structure(msg)
multipart/report
    text/plain
    message/delivery-status
        text/plain
        text/plain
    message/rfc822
        text/plain

Here the message parts are not multiparts, but they do contain subparts. is_multipart() returns True and walk descends into the subparts.

get_body(preferencelist=('related', 'html', 'plain'))

Return the MIME part that is the best candidate to be the “body” of the message.

preferencelist must be a sequence of strings from the set related, html, and plain, and indicates the order of preference for the content type of the part returned.

Start looking for candidate matches with the object on which the get_body method is called.

If related is not included in preferencelist, consider the root part (or subpart of the root part) of any related encountered as a candidate if the (sub-)part matches a preference.

When encountering a multipart/related, check the start parameter and if a part with a matching Content-ID is found, consider only it when looking for candidate matches. Otherwise consider only the first (default root) part of the multipart/related.

If a part has a Content-Disposition header, only consider the part a candidate match if the value of the header is inline.

If none of the candidates matches any of the preferences in preferencelist, return None.

Notes: (1) For most applications the only preferencelist combinations that really make sense are ('plain',), ('html', 'plain'), and the default ('related', 'html', 'plain'). (2) Because matching starts with the object on which get_body is called, calling get_body on a multipart/related will return the object itself unless preferencelist has a non-default value. (3) Messages (or message parts) that do not specify a Content-Type or whose Content-Type header is invalid will be treated as if they are of type text/plain, which may occasionally cause get_body to return unexpected results.

iter_attachments()

Return an iterator over all of the immediate sub-parts of the message that are not candidate “body” parts. That is, skip the first occurrence of each of text/plain, text/html, multipart/related, or multipart/alternative (unless they are explicitly marked as attachments via Content-Disposition: attachment), and return all remaining parts. When applied directly to a multipart/related, return an iterator over the all the related parts except the root part (ie: the part pointed to by the start parameter, or the first part if there is no start parameter or the start parameter doesn’t match the Content-ID of any of the parts). When applied directly to a multipart/alternative or a non-multipart, return an empty iterator.

iter_parts()

Return an iterator over all of the immediate sub-parts of the message, which will be empty for a non-multipart. (See also walk().)

get_content(*args, content_manager=None, **kw)

Call the get_content() method of the content_manager, passing self as the message object, and passing along any other arguments or keywords as additional arguments. If content_manager is not specified, use the content_manager specified by the current policy.

set_content(*args, content_manager=None, **kw)

Call the set_content() method of the content_manager, passing self as the message object, and passing along any other arguments or keywords as additional arguments. If content_manager is not specified, use the content_manager specified by the current policy.

make_related(boundary=None)

Convert a non-multipart message into a multipart/related message, moving any existing Content- headers and payload into a (new) first part of the multipart. If boundary is specified, use it as the boundary string in the multipart, otherwise leave the boundary to be automatically created when it is needed (for example, when the message is serialized).

make_alternative(boundary=None)

Convert a non-multipart or a multipart/related into a multipart/alternative, moving any existing Content- headers and payload into a (new) first part of the multipart. If boundary is specified, use it as the boundary string in the multipart, otherwise leave the boundary to be automatically created when it is needed (for example, when the message is serialized).

make_mixed(boundary=None)

Convert a non-multipart, a multipart/related, or a multipart-alternative into a multipart/mixed, moving any existing Content- headers and payload into a (new) first part of the multipart. If boundary is specified, use it as the boundary string in the multipart, otherwise leave the boundary to be automatically created when it is needed (for example, when the message is serialized).

add_related(*args, content_manager=None, **kw)

If the message is a multipart/related, create a new message object, pass all of the arguments to its set_content() method, and attach() it to the multipart. If the message is a non-multipart, call make_related() and then proceed as above. If the message is any other type of multipart, raise a TypeError. If content_manager is not specified, use the content_manager specified by the current policy. If the added part has no Content-Disposition header, add one with the value inline.

add_alternative(*args, content_manager=None, **kw)

If the message is a multipart/alternative, create a new message object, pass all of the arguments to its set_content() method, and attach() it to the multipart. If the message is a non-multipart or multipart/related, call make_alternative() and then proceed as above. If the message is any other type of multipart, raise a TypeError. If content_manager is not specified, use the content_manager specified by the current policy.

add_attachment(*args, content_manager=None, **kw)

If the message is a multipart/mixed, create a new message object, pass all of the arguments to its set_content() method, and attach() it to the multipart. If the message is a non-multipart, multipart/related, or multipart/alternative, call make_mixed() and then proceed as above. If content_manager is not specified, use the content_manager specified by the current policy. If the added part has no Content-Disposition header, add one with the value attachment. This method can be used both for explicit attachments (Content-Disposition: attachment) and inline attachments (Content-Disposition: inline), by passing appropriate options to the content_manager.

clear()

Remove the payload and all of the headers.

clear_content()

Remove the payload and all of the Content- headers, leaving all other headers intact and in their original order.

EmailMessage objects have the following instance attributes:

preamble

The format of a MIME document allows for some text between the blank line following the headers, and the first multipart boundary string. Normally, this text is never visible in a MIME-aware mail reader because it falls outside the standard MIME armor. However, when viewing the raw text of the message, or when viewing the message in a non-MIME aware reader, this text can become visible.

The preamble attribute contains this leading extra-armor text for MIME documents. When the Parser discovers some text after the headers but before the first boundary string, it assigns this text to the message’s preamble attribute. When the Generator is writing out the plain text representation of a MIME message, and it finds the message has a preamble attribute, it will write this text in the area between the headers and the first boundary. See email.parser and email.generator for details.

Note that if the message object has no preamble, the preamble attribute will be None.

epilogue

The epilogue attribute acts the same way as the preamble attribute, except that it contains text that appears between the last boundary and the end of the message. As with the preamble, if there is no epilog text this attribute will be None.

defects

The defects attribute contains a list of all the problems found when parsing this message. See email.errors for a detailed description of the possible parsing defects.

class email.message.MIMEPart(policy=default)

This class represents a subpart of a MIME message. It is identical to EmailMessage, except that no MIME-Version headers are added when set_content() is called, since sub-parts do not need their own MIME-Version headers.

Footnotes

1

Originally added in 3.4 as a provisional module. Docs for legacy message class moved to email.message.Message: Representing an email message using the compat32 API.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 데이터 처리 »

email — 전자 메일과 MIME 처리 패키지 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 데이터 처리 »

email — 전자 메일과 MIME 처리 패키지 »

|

email.parser: Parsing email messages

Source code: Lib/email/parser.py [https://github.com/python/cpython/tree/3.7/Lib/email/parser.py]

Message object structures can be created in one of two ways: they can be created from whole cloth by creating an EmailMessage object, adding headers using the dictionary interface, and adding payload(s) using set_content() and related methods, or they can be created by parsing a serialized representation of the email message.

The email package provides a standard parser that understands most email document structures, including MIME documents. You can pass the parser a bytes, string or file object, and the parser will return to you the root EmailMessage instance of the object structure. For simple, non-MIME messages the payload of this root object will likely be a string containing the text of the message. For MIME messages, the root object will return True from its is_multipart() method, and the subparts can be accessed via the payload manipulation methods, such as get_body(), iter_parts(), and walk().

There are actually two parser interfaces available for use, the Parser API and the incremental FeedParser API. The Parser API is most useful if you have the entire text of the message in memory, or if the entire message lives in a file on the file system. FeedParser is more appropriate when you are reading the message from a stream which might block waiting for more input (such as reading an email message from a socket). The FeedParser can consume and parse the message incrementally, and only returns the root object when you close the parser.

Note that the parser can be extended in limited ways, and of course you can implement your own parser completely from scratch. All of the logic that connects the email package’s bundled parser and the EmailMessage class is embodied in the policy class, so a custom parser can create message object trees any way it finds necessary by implementing custom versions of the appropriate policy methods.

FeedParser API

The BytesFeedParser, imported from the email.feedparser module, provides an API that is conducive to incremental parsing of email messages, such as would be necessary when reading the text of an email message from a source that can block (such as a socket). The BytesFeedParser can of course be used to parse an email message fully contained in a bytes-like object, string, or file, but the BytesParser API may be more convenient for such use cases. The semantics and results of the two parser APIs are identical.

The BytesFeedParser’s API is simple; you create an instance, feed it a bunch of bytes until there’s no more to feed it, then close the parser to retrieve the root message object. The BytesFeedParser is extremely accurate when parsing standards-compliant messages, and it does a very good job of parsing non-compliant messages, providing information about how a message was deemed broken. It will populate a message object’s defects attribute with a list of any problems it found in a message. See the email.errors module for the list of defects that it can find.

Here is the API for the BytesFeedParser:

class email.parser.BytesFeedParser(_factory=None, *, policy=policy.compat32)

Create a BytesFeedParser instance. Optional _factory is a no-argument callable; if not specified use the message_factory from the policy. Call _factory whenever a new message object is needed.

If policy is specified use the rules it specifies to update the representation of the message. If policy is not set, use the compat32 policy, which maintains backward compatibility with the Python 3.2 version of the email package and provides Message as the default factory. All other policies provide EmailMessage as the default _factory. For more information on what else policy controls, see the policy documentation.

Note: The policy keyword should always be specified; The default will change to email.policy.default in a future version of Python.

버전 3.2에 추가.

버전 3.3에서 변경: Added the policy keyword.

버전 3.6에서 변경: _factory defaults to the policy message_factory.

feed(data)

Feed the parser some more data. data should be a bytes-like object containing one or more lines. The lines can be partial and the parser will stitch such partial lines together properly. The lines can have any of the three common line endings: carriage return, newline, or carriage return and newline (they can even be mixed).

close()

Complete the parsing of all previously fed data and return the root message object. It is undefined what happens if feed() is called after this method has been called.

class email.parser.FeedParser(_factory=None, *, policy=policy.compat32)

Works like BytesFeedParser except that the input to the feed() method must be a string. This is of limited utility, since the only way for such a message to be valid is for it to contain only ASCII text or, if utf8 is True, no binary attachments.

버전 3.3에서 변경: Added the policy keyword.

Parser API

The BytesParser class, imported from the email.parser module, provides an API that can be used to parse a message when the complete contents of the message are available in a bytes-like object or file. The email.parser module also provides Parser for parsing strings, and header-only parsers, BytesHeaderParser and HeaderParser, which can be used if you’re only interested in the headers of the message. BytesHeaderParser and HeaderParser can be much faster in these situations, since they do not attempt to parse the message body, instead setting the payload to the raw body.

class email.parser.BytesParser(_class=None, *, policy=policy.compat32)

Create a BytesParser instance. The _class and policy arguments have the same meaning and semantics as the _factory and policy arguments of BytesFeedParser.

Note: The policy keyword should always be specified; The default will change to email.policy.default in a future version of Python.

버전 3.3에서 변경: Removed the strict argument that was deprecated in 2.4. Added the policy keyword.

버전 3.6에서 변경: _class defaults to the policy message_factory.

parse(fp, headersonly=False)

Read all the data from the binary file-like object fp, parse the resulting bytes, and return the message object. fp must support both the readline() and the read() methods.

The bytes contained in fp must be formatted as a block of RFC 5322 [https://tools.ietf.org/html/rfc5322.html] (or, if utf8 is True, RFC 6532 [https://tools.ietf.org/html/rfc6532.html]) style headers and header continuation lines, optionally preceded by an envelope header. The header block is terminated either by the end of the data or by a blank line. Following the header block is the body of the message (which may contain MIME-encoded subparts, including subparts with a Content-Transfer-Encoding of 8bit).

Optional headersonly is a flag specifying whether to stop parsing after reading the headers or not. The default is False, meaning it parses the entire contents of the file.

parsebytes(bytes, headersonly=False)

Similar to the parse() method, except it takes a bytes-like object instead of a file-like object. Calling this method on a bytes-like object is equivalent to wrapping bytes in a BytesIO instance first and calling parse().

Optional headersonly is as with the parse() method.

버전 3.2에 추가.

class email.parser.BytesHeaderParser(_class=None, *, policy=policy.compat32)

Exactly like BytesParser, except that headersonly defaults to True.

버전 3.3에 추가.

class email.parser.Parser(_class=None, *, policy=policy.compat32)

This class is parallel to BytesParser, but handles string input.

버전 3.3에서 변경: Removed the strict argument. Added the policy keyword.

버전 3.6에서 변경: _class defaults to the policy message_factory.

parse(fp, headersonly=False)

Read all the data from the text-mode file-like object fp, parse the resulting text, and return the root message object. fp must support both the readline() and the read() methods on file-like objects.

Other than the text mode requirement, this method operates like BytesParser.parse().

parsestr(text, headersonly=False)

Similar to the parse() method, except it takes a string object instead of a file-like object. Calling this method on a string is equivalent to wrapping text in a StringIO instance first and calling parse().

Optional headersonly is as with the parse() method.

class email.parser.HeaderParser(_class=None, *, policy=policy.compat32)

Exactly like Parser, except that headersonly defaults to True.

Since creating a message object structure from a string or a file object is such a common task, four functions are provided as a convenience. They are available in the top-level email package namespace.

email.message_from_bytes(s, _class=None, *, policy=policy.compat32)

Return a message object structure from a bytes-like object. This is equivalent to BytesParser().parsebytes(s). Optional _class and policy are interpreted as with the BytesParser class constructor.

버전 3.2에 추가.

버전 3.3에서 변경: Removed the strict argument. Added the policy keyword.

email.message_from_binary_file(fp, _class=None, *, policy=policy.compat32)

Return a message object structure tree from an open binary file object. This is equivalent to BytesParser().parse(fp). _class and policy are interpreted as with the BytesParser class constructor.

버전 3.2에 추가.

버전 3.3에서 변경: Removed the strict argument. Added the policy keyword.

email.message_from_string(s, _class=None, *, policy=policy.compat32)

Return a message object structure from a string. This is equivalent to Parser().parsestr(s). _class and policy are interpreted as with the Parser class constructor.

버전 3.3에서 변경: Removed the strict argument. Added the policy keyword.

email.message_from_file(fp, _class=None, *, policy=policy.compat32)

Return a message object structure tree from an open file object. This is equivalent to Parser().parse(fp). _class and policy are interpreted as with the Parser class constructor.

버전 3.3에서 변경: Removed the strict argument. Added the policy keyword.

버전 3.6에서 변경: _class defaults to the policy message_factory.

Here’s an example of how you might use message_from_bytes() at an interactive Python prompt:

>>> import email
>>> msg = email.message_from_bytes(myBytes)

Additional notes

Here are some notes on the parsing semantics:

Most non-multipart type messages are parsed as a single message object with a string payload. These objects will return False for is_multipart(), and iter_parts() will yield an empty list.

All multipart type messages will be parsed as a container message object with a list of sub-message objects for their payload. The outer container message will return True for is_multipart(), and iter_parts() will yield a list of subparts.

Most messages with a content type of message/* (such as message/delivery-status and message/rfc822) will also be parsed as container object containing a list payload of length 1. Their is_multipart() method will return True. The single element yielded by iter_parts() will be a sub-message object.

Some non-standards-compliant messages may not be internally consistent about their multipart-edness. Such messages may have a Content-Type header of type multipart, but their is_multipart() method may return False. If such messages were parsed with the FeedParser, they will have an instance of the MultipartInvariantViolationDefect class in their defects attribute list. See email.errors for details.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 데이터 처리 »

email — 전자 메일과 MIME 처리 패키지 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 데이터 처리 »

email — 전자 메일과 MIME 처리 패키지 »

|

email.generator: Generating MIME documents

Source code: Lib/email/generator.py [https://github.com/python/cpython/tree/3.7/Lib/email/generator.py]

One of the most common tasks is to generate the flat (serialized) version of the email message represented by a message object structure. You will need to do this if you want to send your message via smtplib.SMTP.sendmail() or the nntplib module, or print the message on the console. Taking a message object structure and producing a serialized representation is the job of the generator classes.

As with the email.parser module, you aren’t limited to the functionality of the bundled generator; you could write one from scratch yourself. However the bundled generator knows how to generate most email in a standards-compliant way, should handle MIME and non-MIME email messages just fine, and is designed so that the bytes-oriented parsing and generation operations are inverses, assuming the same non-transforming policy is used for both. That is, parsing the serialized byte stream via the BytesParser class and then regenerating the serialized byte stream using BytesGenerator should produce output identical to the input 1. (On the other hand, using the generator on an EmailMessage constructed by program may result in changes to the EmailMessage object as defaults are filled in.)

The Generator class can be used to flatten a message into a text (as opposed to binary) serialized representation, but since Unicode cannot represent binary data directly, the message is of necessity transformed into something that contains only ASCII characters, using the standard email RFC Content Transfer Encoding techniques for encoding email messages for transport over channels that are not “8 bit clean”.

class email.generator.BytesGenerator(outfp, mangle_from_=None, maxheaderlen=None, *, policy=None)

Return a BytesGenerator object that will write any message provided to the flatten() method, or any surrogateescape encoded text provided to the write() method, to the file-like object outfp. outfp must support a write method that accepts binary data.

If optional mangle_from_ is True, put a > character in front of any line in the body that starts with the exact string "From ", that is From followed by a space at the beginning of a line. mangle_from_ defaults to the value of the mangle_from_ setting of the policy (which is True for the compat32 policy and False for all others). mangle_from_ is intended for use when messages are stored in unix mbox format (see mailbox and WHY THE CONTENT-LENGTH FORMAT IS BAD [https://www.jwz.org/doc/content-length.html]).

If maxheaderlen is not None, refold any header lines that are longer than maxheaderlen, or if 0, do not rewrap any headers. If manheaderlen is None (the default), wrap headers and other message lines according to the policy settings.

If policy is specified, use that policy to control message generation. If policy is None (the default), use the policy associated with the Message or EmailMessage object passed to flatten to control the message generation. See email.policy for details on what policy controls.

버전 3.2에 추가.

버전 3.3에서 변경: Added the policy keyword.

버전 3.6에서 변경: The default behavior of the mangle_from_ and maxheaderlen parameters is to follow the policy.

flatten(msg, unixfrom=False, linesep=None)

Print the textual representation of the message object structure rooted at msg to the output file specified when the BytesGenerator instance was created.

If the policy option cte_type is 8bit (the default), copy any headers in the original parsed message that have not been modified to the output with any bytes with the high bit set reproduced as in the original, and preserve the non-ASCII Content-Transfer-Encoding of any body parts that have them. If cte_type is 7bit, convert the bytes with the high bit set as needed using an ASCII-compatible Content-Transfer-Encoding. That is, transform parts with non-ASCII Content-Transfer-Encoding (Content-Transfer-Encoding: 8bit) to an ASCII compatible Content-Transfer-Encoding, and encode RFC-invalid non-ASCII bytes in headers using the MIME unknown-8bit character set, thus rendering them RFC-compliant.

If unixfrom is True, print the envelope header delimiter used by the Unix mailbox format (see mailbox) before the first of the RFC 5322 [https://tools.ietf.org/html/rfc5322.html] headers of the root message object. If the root object has no envelope header, craft a standard one. The default is False. Note that for subparts, no envelope header is ever printed.

If linesep is not None, use it as the separator character between all the lines of the flattened message. If linesep is None (the default), use the value specified in the policy.

clone(fp)

Return an independent clone of this BytesGenerator instance with the exact same option settings, and fp as the new outfp.

write(s)

Encode s using the ASCII codec and the surrogateescape error handler, and pass it to the write method of the outfp passed to the BytesGenerator’s constructor.

As a convenience, EmailMessage provides the methods as_bytes() and bytes(aMessage) (a.k.a. __bytes__()), which simplify the generation of a serialized binary representation of a message object. For more detail, see email.message.

Because strings cannot represent binary data, the Generator class must convert any binary data in any message it flattens to an ASCII compatible format, by converting them to an ASCII compatible Content-Transfer_Encoding. Using the terminology of the email RFCs, you can think of this as Generator serializing to an I/O stream that is not “8 bit clean”. In other words, most applications will want to be using BytesGenerator, and not Generator.

class email.generator.Generator(outfp, mangle_from_=None, maxheaderlen=None, *, policy=None)

Return a Generator object that will write any message provided to the flatten() method, or any text provided to the write() method, to the file-like object outfp. outfp must support a write method that accepts string data.

If optional mangle_from_ is True, put a > character in front of any line in the body that starts with the exact string "From ", that is From followed by a space at the beginning of a line. mangle_from_ defaults to the value of the mangle_from_ setting of the policy (which is True for the compat32 policy and False for all others). mangle_from_ is intended for use when messages are stored in unix mbox format (see mailbox and WHY THE CONTENT-LENGTH FORMAT IS BAD [https://www.jwz.org/doc/content-length.html]).

If maxheaderlen is not None, refold any header lines that are longer than maxheaderlen, or if 0, do not rewrap any headers. If manheaderlen is None (the default), wrap headers and other message lines according to the policy settings.

If policy is specified, use that policy to control message generation. If policy is None (the default), use the policy associated with the Message or EmailMessage object passed to flatten to control the message generation. See email.policy for details on what policy controls.

버전 3.3에서 변경: Added the policy keyword.

버전 3.6에서 변경: The default behavior of the mangle_from_ and maxheaderlen parameters is to follow the policy.

flatten(msg, unixfrom=False, linesep=None)

Print the textual representation of the message object structure rooted at msg to the output file specified when the Generator instance was created.

If the policy option cte_type is 8bit, generate the message as if the option were set to 7bit. (This is required because strings cannot represent non-ASCII bytes.) Convert any bytes with the high bit set as needed using an ASCII-compatible Content-Transfer-Encoding. That is, transform parts with non-ASCII Content-Transfer-Encoding (Content-Transfer-Encoding: 8bit) to an ASCII compatible Content-Transfer-Encoding, and encode RFC-invalid non-ASCII bytes in headers using the MIME unknown-8bit character set, thus rendering them RFC-compliant.

If unixfrom is True, print the envelope header delimiter used by the Unix mailbox format (see mailbox) before the first of the RFC 5322 [https://tools.ietf.org/html/rfc5322.html] headers of the root message object. If the root object has no envelope header, craft a standard one. The default is False. Note that for subparts, no envelope header is ever printed.

If linesep is not None, use it as the separator character between all the lines of the flattened message. If linesep is None (the default), use the value specified in the policy.

버전 3.2에서 변경: Added support for re-encoding 8bit message bodies, and the linesep argument.

clone(fp)

Return an independent clone of this Generator instance with the exact same options, and fp as the new outfp.

write(s)

Write s to the write method of the outfp passed to the Generator’s constructor. This provides just enough file-like API for Generator instances to be used in the print() function.

As a convenience, EmailMessage provides the methods as_string() and str(aMessage) (a.k.a. __str__()), which simplify the generation of a formatted string representation of a message object. For more detail, see email.message.

The email.generator module also provides a derived class, DecodedGenerator, which is like the Generator base class, except that non-text parts are not serialized, but are instead represented in the output stream by a string derived from a template filled in with information about the part.

class email.generator.DecodedGenerator(outfp, mangle_from_=None, maxheaderlen=None, fmt=None, *, policy=None)

Act like Generator, except that for any subpart of the message passed to Generator.flatten(), if the subpart is of main type text, print the decoded payload of the subpart, and if the main type is not text, instead of printing it fill in the string fmt using information from the part and print the resulting filled-in string.

To fill in fmt, execute fmt % part_info, where part_info is a dictionary composed of the following keys and values:

type – Full MIME type of the non-text part

maintype – Main MIME type of the non-text part

subtype – Sub-MIME type of the non-text part

filename – Filename of the non-text part

description – Description associated with the non-text part

encoding – Content transfer encoding of the non-text part

If fmt is None, use the following default fmt:

“[Non-text (%(type)s) part of message omitted, filename %(filename)s]”

Optional _mangle_from_ and maxheaderlen are as with the Generator base class.

Footnotes

1

This statement assumes that you use the appropriate setting for unixfrom, and that there are no policy settings calling for automatic adjustments (for example, refold_source must be none, which is not the default). It is also not 100% true, since if the message does not conform to the RFC standards occasionally information about the exact original text is lost during parsing error recovery. It is a goal to fix these latter edge cases when possible.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 데이터 처리 »

email — 전자 메일과 MIME 처리 패키지 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 데이터 처리 »

email — 전자 메일과 MIME 처리 패키지 »

|

email.policy: Policy Objects

버전 3.3에 추가.

Source code: Lib/email/policy.py [https://github.com/python/cpython/tree/3.7/Lib/email/policy.py]

The email package’s prime focus is the handling of email messages as described by the various email and MIME RFCs. However, the general format of email messages (a block of header fields each consisting of a name followed by a colon followed by a value, the whole block followed by a blank line and an arbitrary ‘body’), is a format that has found utility outside of the realm of email. Some of these uses conform fairly closely to the main email RFCs, some do not. Even when working with email, there are times when it is desirable to break strict compliance with the RFCs, such as generating emails that interoperate with email servers that do not themselves follow the standards, or that implement extensions you want to use in ways that violate the standards.

Policy objects give the email package the flexibility to handle all these disparate use cases.

A Policy object encapsulates a set of attributes and methods that control the behavior of various components of the email package during use. Policy instances can be passed to various classes and methods in the email package to alter the default behavior. The settable values and their defaults are described below.

There is a default policy used by all classes in the email package. For all of the parser classes and the related convenience functions, and for the Message class, this is the Compat32 policy, via its corresponding pre-defined instance compat32. This policy provides for complete backward compatibility (in some cases, including bug compatibility) with the pre-Python3.3 version of the email package.

This default value for the policy keyword to EmailMessage is the EmailPolicy policy, via its pre-defined instance default.

When a Message or EmailMessage object is created, it acquires a policy. If the message is created by a parser, a policy passed to the parser will be the policy used by the message it creates. If the message is created by the program, then the policy can be specified when it is created. When a message is passed to a generator, the generator uses the policy from the message by default, but you can also pass a specific policy to the generator that will override the one stored on the message object.

The default value for the policy keyword for the email.parser classes and the parser convenience functions will be changing in a future version of Python. Therefore you should always specify explicitly which policy you want to use when calling any of the classes and functions described in the parser module.

The first part of this documentation covers the features of Policy, an abstract base class that defines the features that are common to all policy objects, including compat32. This includes certain hook methods that are called internally by the email package, which a custom policy could override to obtain different behavior. The second part describes the concrete classes EmailPolicy and Compat32, which implement the hooks that provide the standard behavior and the backward compatible behavior and features, respectively.

Policy instances are immutable, but they can be cloned, accepting the same keyword arguments as the class constructor and returning a new Policy instance that is a copy of the original but with the specified attributes values changed.

As an example, the following code could be used to read an email message from a file on disk and pass it to the system sendmail program on a Unix system:

>>> from email import message_from_binary_file
>>> from email.generator import BytesGenerator
>>> from email import policy
>>> from subprocess import Popen, PIPE
>>> with open('mymsg.txt', 'rb') as f:
...     msg = message_from_binary_file(f, policy=policy.default)
>>> p = Popen(['sendmail', msg['To'].addresses[0]], stdin=PIPE)
>>> g = BytesGenerator(p.stdin, policy=msg.policy.clone(linesep='\r\n'))
>>> g.flatten(msg)
>>> p.stdin.close()
>>> rc = p.wait()

Here we are telling BytesGenerator to use the RFC correct line separator characters when creating the binary string to feed into sendmail's stdin, where the default policy would use \n line separators.

Some email package methods accept a policy keyword argument, allowing the policy to be overridden for that method. For example, the following code uses the as_bytes() method of the msg object from the previous example and writes the message to a file using the native line separators for the platform on which it is running:

>>> import os
>>> with open('converted.txt', 'wb') as f:
...     f.write(msg.as_bytes(policy=msg.policy.clone(linesep=os.linesep)))
17

Policy objects can also be combined using the addition operator, producing a policy object whose settings are a combination of the non-default values of the summed objects:

>>> compat_SMTP = policy.compat32.clone(linesep='\r\n')
>>> compat_strict = policy.compat32.clone(raise_on_defect=True)
>>> compat_strict_SMTP = compat_SMTP + compat_strict

This operation is not commutative; that is, the order in which the objects are added matters. To illustrate:

>>> policy100 = policy.compat32.clone(max_line_length=100)
>>> policy80 = policy.compat32.clone(max_line_length=80)
>>> apolicy = policy100 + policy80
>>> apolicy.max_line_length
80
>>> apolicy = policy80 + policy100
>>> apolicy.max_line_length
100

class email.policy.Policy(**kw)

This is the abstract base class for all policy classes. It provides default implementations for a couple of trivial methods, as well as the implementation of the immutability property, the clone() method, and the constructor semantics.

The constructor of a policy class can be passed various keyword arguments. The arguments that may be specified are any non-method properties on this class, plus any additional non-method properties on the concrete class. A value specified in the constructor will override the default value for the corresponding attribute.

This class defines the following properties, and thus values for the following may be passed in the constructor of any policy class:

max_line_length

The maximum length of any line in the serialized output, not counting the end of line character(s). Default is 78, per RFC 5322 [https://tools.ietf.org/html/rfc5322.html]. A value of 0 or None indicates that no line wrapping should be done at all.

linesep

The string to be used to terminate lines in serialized output. The default is \n because that’s the internal end-of-line discipline used by Python, though \r\n is required by the RFCs.

cte_type

Controls the type of Content Transfer Encodings that may be or are required to be used. The possible values are:

7bit

all data must be “7 bit clean” (ASCII-only). This means that where necessary data will be encoded using either quoted-printable or base64 encoding.

8bit

data is not constrained to be 7 bit clean. Data in headers is still required to be ASCII-only and so will be encoded (see fold_binary() and utf8 below for exceptions), but body parts may use the 8bit CTE.

A cte_type value of 8bit only works with BytesGenerator, not Generator, because strings cannot contain binary data. If a Generator is operating under a policy that specifies cte_type=8bit, it will act as if cte_type is 7bit.

raise_on_defect

If True, any defects encountered will be raised as errors. If False (the default), defects will be passed to the register_defect() method.

mangle_from_

If True, lines starting with “From “ in the body are escaped by putting a > in front of them. This parameter is used when the message is being serialized by a generator. Default: False.

버전 3.5에 추가: The mangle_from_ parameter.

message_factory

A factory function for constructing a new empty message object. Used by the parser when building messages. Defaults to None, in which case Message is used.

버전 3.6에 추가.

The following Policy method is intended to be called by code using the email library to create policy instances with custom settings:

clone(**kw)

Return a new Policy instance whose attributes have the same values as the current instance, except where those attributes are given new values by the keyword arguments.

The remaining Policy methods are called by the email package code, and are not intended to be called by an application using the email package. A custom policy must implement all of these methods.

handle_defect(obj, defect)

Handle a defect found on obj. When the email package calls this method, defect will always be a subclass of Defect.

The default implementation checks the raise_on_defect flag. If it is True, defect is raised as an exception. If it is False (the default), obj and defect are passed to register_defect().

register_defect(obj, defect)

Register a defect on obj. In the email package, defect will always be a subclass of Defect.

The default implementation calls the append method of the defects attribute of obj. When the email package calls handle_defect, obj will normally have a defects attribute that has an append method. Custom object types used with the email package (for example, custom Message objects) should also provide such an attribute, otherwise defects in parsed messages will raise unexpected errors.

header_max_count(name)

Return the maximum allowed number of headers named name.

Called when a header is added to an EmailMessage or Message object. If the returned value is not 0 or None, and there are already a number of headers with the name name greater than or equal to the value returned, a ValueError is raised.

Because the default behavior of Message.__setitem__ is to append the value to the list of headers, it is easy to create duplicate headers without realizing it. This method allows certain headers to be limited in the number of instances of that header that may be added to a Message programmatically. (The limit is not observed by the parser, which will faithfully produce as many headers as exist in the message being parsed.)

The default implementation returns None for all header names.

header_source_parse(sourcelines)

The email package calls this method with a list of strings, each string ending with the line separation characters found in the source being parsed. The first line includes the field header name and separator. All whitespace in the source is preserved. The method should return the (name, value) tuple that is to be stored in the Message to represent the parsed header.

If an implementation wishes to retain compatibility with the existing email package policies, name should be the case preserved name (all characters up to the ‘:’ separator), while value should be the unfolded value (all line separator characters removed, but whitespace kept intact), stripped of leading whitespace.

sourcelines may contain surrogateescaped binary data.

There is no default implementation

header_store_parse(name, value)

The email package calls this method with the name and value provided by the application program when the application program is modifying a Message programmatically (as opposed to a Message created by a parser). The method should return the (name, value) tuple that is to be stored in the Message to represent the header.

If an implementation wishes to retain compatibility with the existing email package policies, the name and value should be strings or string subclasses that do not change the content of the passed in arguments.

There is no default implementation

header_fetch_parse(name, value)

The email package calls this method with the name and value currently stored in the Message when that header is requested by the application program, and whatever the method returns is what is passed back to the application as the value of the header being retrieved. Note that there may be more than one header with the same name stored in the Message; the method is passed the specific name and value of the header destined to be returned to the application.

value may contain surrogateescaped binary data. There should be no surrogateescaped binary data in the value returned by the method.

There is no default implementation

fold(name, value)

The email package calls this method with the name and value currently stored in the Message for a given header. The method should return a string that represents that header “folded” correctly (according to the policy settings) by composing the name with the value and inserting linesep characters at the appropriate places. See RFC 5322 [https://tools.ietf.org/html/rfc5322.html] for a discussion of the rules for folding email headers.

value may contain surrogateescaped binary data. There should be no surrogateescaped binary data in the string returned by the method.

fold_binary(name, value)

The same as fold(), except that the returned value should be a bytes object rather than a string.

value may contain surrogateescaped binary data. These could be converted back into binary data in the returned bytes object.

class email.policy.EmailPolicy(**kw)

This concrete Policy provides behavior that is intended to be fully compliant with the current email RFCs. These include (but are not limited to) RFC 5322 [https://tools.ietf.org/html/rfc5322.html], RFC 2047 [https://tools.ietf.org/html/rfc2047.html], and the current MIME RFCs.

This policy adds new header parsing and folding algorithms. Instead of simple strings, headers are str subclasses with attributes that depend on the type of the field. The parsing and folding algorithm fully implement RFC 2047 [https://tools.ietf.org/html/rfc2047.html] and RFC 5322 [https://tools.ietf.org/html/rfc5322.html].

The default value for the message_factory attribute is EmailMessage.

In addition to the settable attributes listed above that apply to all policies, this policy adds the following additional attributes:

버전 3.6에 추가: 1

utf8

If False, follow RFC 5322 [https://tools.ietf.org/html/rfc5322.html], supporting non-ASCII characters in headers by encoding them as “encoded words”. If True, follow RFC 6532 [https://tools.ietf.org/html/rfc6532.html] and use utf-8 encoding for headers. Messages formatted in this way may be passed to SMTP servers that support the SMTPUTF8 extension (RFC 6531 [https://tools.ietf.org/html/rfc6531.html]).

refold_source

If the value for a header in the Message object originated from a parser (as opposed to being set by a program), this attribute indicates whether or not a generator should refold that value when transforming the message back into serialized form. The possible values are:

none

all source values use original folding

long

source values that have any line that is longer than max_line_length will be refolded

all

all values are refolded.

The default is long.

header_factory

A callable that takes two arguments, name and value, where name is a header field name and value is an unfolded header field value, and returns a string subclass that represents that header. A default header_factory (see headerregistry) is provided that supports custom parsing for the various address and date RFC 5322 [https://tools.ietf.org/html/rfc5322.html] header field types, and the major MIME header field stypes. Support for additional custom parsing will be added in the future.

content_manager

An object with at least two methods: get_content and set_content. When the get_content() or set_content() method of an EmailMessage object is called, it calls the corresponding method of this object, passing it the message object as its first argument, and any arguments or keywords that were passed to it as additional arguments. By default content_manager is set to raw_data_manager.

버전 3.4에 추가.

The class provides the following concrete implementations of the abstract methods of Policy:

header_max_count(name)

Returns the value of the max_count attribute of the specialized class used to represent the header with the given name.

header_source_parse(sourcelines)

The name is parsed as everything up to the ‘:’ and returned unmodified. The value is determined by stripping leading whitespace off the remainder of the first line, joining all subsequent lines together, and stripping any trailing carriage return or linefeed characters.

header_store_parse(name, value)

The name is returned unchanged. If the input value has a name attribute and it matches name ignoring case, the value is returned unchanged. Otherwise the name and value are passed to header_factory, and the resulting header object is returned as the value. In this case a ValueError is raised if the input value contains CR or LF characters.

header_fetch_parse(name, value)

If the value has a name attribute, it is returned to unmodified. Otherwise the name, and the value with any CR or LF characters removed, are passed to the header_factory, and the resulting header object is returned. Any surrogateescaped bytes get turned into the unicode unknown-character glyph.

fold(name, value)

Header folding is controlled by the refold_source policy setting. A value is considered to be a ‘source value’ if and only if it does not have a name attribute (having a name attribute means it is a header object of some sort). If a source value needs to be refolded according to the policy, it is converted into a header object by passing the name and the value with any CR and LF characters removed to the header_factory. Folding of a header object is done by calling its fold method with the current policy.

Source values are split into lines using splitlines(). If the value is not to be refolded, the lines are rejoined using the linesep from the policy and returned. The exception is lines containing non-ascii binary data. In that case the value is refolded regardless of the refold_source setting, which causes the binary data to be CTE encoded using the unknown-8bit charset.

fold_binary(name, value)

The same as fold() if cte_type is 7bit, except that the returned value is bytes.

If cte_type is 8bit, non-ASCII binary data is converted back into bytes. Headers with binary data are not refolded, regardless of the refold_header setting, since there is no way to know whether the binary data consists of single byte characters or multibyte characters.

The following instances of EmailPolicy provide defaults suitable for specific application domains. Note that in the future the behavior of these instances (in particular the HTTP instance) may be adjusted to conform even more closely to the RFCs relevant to their domains.

email.policy.default

An instance of EmailPolicy with all defaults unchanged. This policy uses the standard Python \n line endings rather than the RFC-correct \r\n.

email.policy.SMTP

Suitable for serializing messages in conformance with the email RFCs. Like default, but with linesep set to \r\n, which is RFC compliant.

email.policy.SMTPUTF8

The same as SMTP except that utf8 is True. Useful for serializing messages to a message store without using encoded words in the headers. Should only be used for SMTP transmission if the sender or recipient addresses have non-ASCII characters (the smtplib.SMTP.send_message() method handles this automatically).

email.policy.HTTP

Suitable for serializing headers with for use in HTTP traffic. Like SMTP except that max_line_length is set to None (unlimited).

email.policy.strict

Convenience instance. The same as default except that raise_on_defect is set to True. This allows any policy to be made strict by writing:

somepolicy + policy.strict

With all of these EmailPolicies, the effective API of the email package is changed from the Python 3.2 API in the following ways:

Setting a header on a Message results in that header being parsed and a header object created.

Fetching a header value from a Message results in that header being parsed and a header object created and returned.

Any header object, or any header that is refolded due to the policy settings, is folded using an algorithm that fully implements the RFC folding algorithms, including knowing where encoded words are required and allowed.

From the application view, this means that any header obtained through the EmailMessage is a header object with extra attributes, whose string value is the fully decoded unicode value of the header. Likewise, a header may be assigned a new value, or a new header created, using a unicode string, and the policy will take care of converting the unicode string into the correct RFC encoded form.

The header objects and their attributes are described in headerregistry.

class email.policy.Compat32(**kw)

This concrete Policy is the backward compatibility policy. It replicates the behavior of the email package in Python 3.2. The policy module also defines an instance of this class, compat32, that is used as the default policy. Thus the default behavior of the email package is to maintain compatibility with Python 3.2.

The following attributes have values that are different from the Policy default:

mangle_from_

The default is True.

The class provides the following concrete implementations of the abstract methods of Policy:

header_source_parse(sourcelines)

The name is parsed as everything up to the ‘:’ and returned unmodified. The value is determined by stripping leading whitespace off the remainder of the first line, joining all subsequent lines together, and stripping any trailing carriage return or linefeed characters.

header_store_parse(name, value)

The name and value are returned unmodified.

header_fetch_parse(name, value)

If the value contains binary data, it is converted into a Header object using the unknown-8bit charset. Otherwise it is returned unmodified.

fold(name, value)

Headers are folded using the Header folding algorithm, which preserves existing line breaks in the value, and wraps each resulting line to the max_line_length. Non-ASCII binary data are CTE encoded using the unknown-8bit charset.

fold_binary(name, value)

Headers are folded using the Header folding algorithm, which preserves existing line breaks in the value, and wraps each resulting line to the max_line_length. If cte_type is 7bit, non-ascii binary data is CTE encoded using the unknown-8bit charset. Otherwise the original source header is used, with its existing line breaks and any (RFC invalid) binary data it may contain.

email.policy.compat32

An instance of Compat32, providing backward compatibility with the behavior of the email package in Python 3.2.

Footnotes

1

Originally added in 3.3 as a provisional feature.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 데이터 처리 »

email — 전자 메일과 MIME 처리 패키지 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 데이터 처리 »

email — 전자 메일과 MIME 처리 패키지 »

|

email.errors: 예외와 결함 클래스

소스 코드: Lib/email/errors.py [https://github.com/python/cpython/tree/3.7/Lib/email/errors.py]

email.errors 모듈에는 다음과 같은 예외 클래스가 정의되어 있습니다:

exception email.errors.MessageError

이것은 email 패키지가 발생시킬 수 있는 모든 예외의 베이스 클래스입니다. 표준 Exception 클래스에서 파생되며 추가 메서드를 정의하지 않습니다.

exception email.errors.MessageParseError

이것은 Parser 클래스에서 발생하는 예외의 베이스 클래스입니다. MessageError에서 파생됩니다. 이 클래스는 headerregistry에서 사용하는 구문 분석기에서도 내부적으로 사용됩니다.

exception email.errors.HeaderParseError

메시지의 RFC 5322 [https://tools.ietf.org/html/rfc5322.html] 헤더를 구문 분석할 때 일부 에러 조건에서 발생합니다. 이 클래스는 MessageParseError에서 파생됩니다. 메서드가 호출될 때 콘텐츠 유형을 알 수 없으면, set_boundary() 메서드는 이 에러를 발생시킵니다. Header는 특정 base64 디코딩 에러와 내장된 헤더를 포함하는 것으로 보이는 헤더를 만들려고 할 때 (즉, 연장 줄(continuation line)이어야 할 곳에 선행 공백이 없고 헤더처럼 보이는 것이 있을 때) 이 에러를 발생시킬 수 있습니다.

exception email.errors.BoundaryError

폐지되었고 더는 사용되지 않습니다.

exception email.errors.MultipartConversionError

add_payload()를 사용하여 페이 로드가 Message 객체에 추가되었지만, 페이 로드가 이미 스칼라(scalar)이고 메시지의 Content-Type 메인 유형이 multipart도 아니고 누락되지도 않았으면 발생합니다. MultipartConversionError는 MessageError와 내장 TypeError에서 다중 상속됩니다.

Message.add_payload()는 폐지되었으므로, 실제로 이 예외는 거의 발생하지 않습니다. 그러나 MIMENonMultipart에서 파생된 클래스(예를 들어 MIMEImage)의 인스턴스에서 attach() 메서드를 호출하면 예외가 발생할 수도 있습니다.

다음은 메시지를 구문 분석하는 동안 FeedParser가 찾을 수 있는 결함 목록입니다. 문제가 발견된 메시지에 결함이 추가됨에 유의하십시오. 그래서, 예를 들어, multipart/alternative 내에 중첩된 메시지에 잘못된 헤더가 있으면, 해당 중첩 메시지 객체가 결함을 갖게 되지만 포함하는 메시지는 그렇지 않습니다.

모든 결함 클래스는 email.errors.MessageDefect의 서브 클래스입니다.

NoBoundaryInMultipartDefect – 메시지가 멀티 파트라고 주장했지만, boundary 파라미터가 없습니다.

StartBoundaryNotFoundDefect – Content-Type 헤더에서 주장하는 시작 경계를 찾지 못했습니다.

CloseBoundaryNotFoundDefect – 시작 경계가 발견되었지만, 해당하는 종료 경계가 발견되지 않았습니다.

버전 3.3에 추가.

FirstHeaderLineIsContinuationDefect – 메시지의 첫 번째 헤더 줄에 연장 줄(continuation line)이 있습니다.

MisplacedEnvelopeHeaderDefect - 헤더 블록 중간에 “Unix From” 헤더가 있습니다.

MissingHeaderBodySeparatorDefect - 헤더를 구문 분석하는 중에 선행 공백이 없지만 ‘:’ 가 포함되지 않은 줄이 발견되었습니다. 그 줄이 본문의 첫 번째 줄을 나타내는 것으로 가정하여 구문 분석이 계속됩니다.

버전 3.3에 추가.

MalformedHeaderDefect – 콜론이 없거나 다른 식으로 잘못된 헤더가 발견되었습니다.

버전 3.3부터 폐지: 이 결함은 여러 파이썬 버전에서 사용되지 않았습니다.

MultipartInvariantViolationDefect – A message claimed to be a multipart, but no subparts were found. Note that when a message has this defect, its is_multipart() method may return False even though its content type claims to be multipart.

InvalidBase64PaddingDefect – base64로 인코딩된 바이트열 블록을 디코딩할 때, 패딩이 올바르지 않습니다. 디코딩을 수행하기 위해 충분한 패딩이 추가되지만, 바이트열을 디코딩한 결과는 유효하지 않을 수 있습니다.

InvalidBase64CharactersDefect – base64로 인코딩된 바이트열 블록을 디코딩할 때, base64 알파벳 이외의 문자가 발견되었습니다. 문자는 무시되지만, 바이트열을 디코딩한 결과는 유효하지 않을 수 있습니다.

InvalidBase64LengthDefect – base64로 인코딩된 바이트열 블록을 디코딩할 때, 비 패딩 base64 문자 수가 유효하지 않습니다 (4의 배수보다 1이 큽니다). 인코딩된 블록은 그대로 유지됩니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 데이터 처리 »

email — 전자 메일과 MIME 처리 패키지 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 데이터 처리 »

email — 전자 메일과 MIME 처리 패키지 »

|

email.headerregistry: Custom Header Objects

Source code: Lib/email/headerregistry.py [https://github.com/python/cpython/tree/3.7/Lib/email/headerregistry.py]

버전 3.6에 추가: 1

Headers are represented by customized subclasses of str. The particular class used to represent a given header is determined by the header_factory of the policy in effect when the headers are created. This section documents the particular header_factory implemented by the email package for handling RFC 5322 [https://tools.ietf.org/html/rfc5322.html] compliant email messages, which not only provides customized header objects for various header types, but also provides an extension mechanism for applications to add their own custom header types.

When using any of the policy objects derived from EmailPolicy, all headers are produced by HeaderRegistry and have BaseHeader as their last base class. Each header class has an additional base class that is determined by the type of the header. For example, many headers have the class UnstructuredHeader as their other base class. The specialized second class for a header is determined by the name of the header, using a lookup table stored in the HeaderRegistry. All of this is managed transparently for the typical application program, but interfaces are provided for modifying the default behavior for use by more complex applications.

The sections below first document the header base classes and their attributes, followed by the API for modifying the behavior of HeaderRegistry, and finally the support classes used to represent the data parsed from structured headers.

class email.headerregistry.BaseHeader(name, value)

name and value are passed to BaseHeader from the header_factory call. The string value of any header object is the value fully decoded to unicode.

This base class defines the following read-only properties:

name

The name of the header (the portion of the field before the ‘:’). This is exactly the value passed in the header_factory call for name; that is, case is preserved.

defects

A tuple of HeaderDefect instances reporting any RFC compliance problems found during parsing. The email package tries to be complete about detecting compliance issues. See the errors module for a discussion of the types of defects that may be reported.

max_count

The maximum number of headers of this type that can have the same name. A value of None means unlimited. The BaseHeader value for this attribute is None; it is expected that specialized header classes will override this value as needed.

BaseHeader also provides the following method, which is called by the email library code and should not in general be called by application programs:

fold(*, policy)

Return a string containing linesep characters as required to correctly fold the header according to policy. A cte_type of 8bit will be treated as if it were 7bit, since headers may not contain arbitrary binary data. If utf8 is False, non-ASCII data will be RFC 2047 [https://tools.ietf.org/html/rfc2047.html] encoded.

BaseHeader by itself cannot be used to create a header object. It defines a protocol that each specialized header cooperates with in order to produce the header object. Specifically, BaseHeader requires that the specialized class provide a classmethod() named parse. This method is called as follows:

parse(string, kwds)

kwds is a dictionary containing one pre-initialized key, defects. defects is an empty list. The parse method should append any detected defects to this list. On return, the kwds dictionary must contain values for at least the keys decoded and defects. decoded should be the string value for the header (that is, the header value fully decoded to unicode). The parse method should assume that string may contain content-transfer-encoded parts, but should correctly handle all valid unicode characters as well so that it can parse un-encoded header values.

BaseHeader’s __new__ then creates the header instance, and calls its init method. The specialized class only needs to provide an init method if it wishes to set additional attributes beyond those provided by BaseHeader itself. Such an init method should look like this:

def init(self, *args, **kw):
    self._myattr = kw.pop('myattr')
    super().init(*args, **kw)

That is, anything extra that the specialized class puts in to the kwds dictionary should be removed and handled, and the remaining contents of kw (and args) passed to the BaseHeader init method.

class email.headerregistry.UnstructuredHeader

An “unstructured” header is the default type of header in RFC 5322 [https://tools.ietf.org/html/rfc5322.html]. Any header that does not have a specified syntax is treated as unstructured. The classic example of an unstructured header is the Subject header.

In RFC 5322 [https://tools.ietf.org/html/rfc5322.html], an unstructured header is a run of arbitrary text in the ASCII character set. RFC 2047 [https://tools.ietf.org/html/rfc2047.html], however, has an RFC 5322 [https://tools.ietf.org/html/rfc5322.html] compatible mechanism for encoding non-ASCII text as ASCII characters within a header value. When a value containing encoded words is passed to the constructor, the UnstructuredHeader parser converts such encoded words into unicode, following the RFC 2047 [https://tools.ietf.org/html/rfc2047.html] rules for unstructured text. The parser uses heuristics to attempt to decode certain non-compliant encoded words. Defects are registered in such cases, as well as defects for issues such as invalid characters within the encoded words or the non-encoded text.

This header type provides no additional attributes.

class email.headerregistry.DateHeader

RFC 5322 [https://tools.ietf.org/html/rfc5322.html] specifies a very specific format for dates within email headers. The DateHeader parser recognizes that date format, as well as recognizing a number of variant forms that are sometimes found “in the wild”.

This header type provides the following additional attributes:

datetime

If the header value can be recognized as a valid date of one form or another, this attribute will contain a datetime instance representing that date. If the timezone of the input date is specified as -0000 (indicating it is in UTC but contains no information about the source timezone), then datetime will be a naive datetime. If a specific timezone offset is found (including +0000), then datetime will contain an aware datetime that uses datetime.timezone to record the timezone offset.

The decoded value of the header is determined by formatting the datetime according to the RFC 5322 [https://tools.ietf.org/html/rfc5322.html] rules; that is, it is set to:

email.utils.format_datetime(self.datetime)

When creating a DateHeader, value may be datetime instance. This means, for example, that the following code is valid and does what one would expect:

msg['Date'] = datetime(2011, 7, 15, 21)

Because this is a naive datetime it will be interpreted as a UTC timestamp, and the resulting value will have a timezone of -0000. Much more useful is to use the localtime() function from the utils module:

msg['Date'] = utils.localtime()

This example sets the date header to the current time and date using the current timezone offset.

class email.headerregistry.AddressHeader

Address headers are one of the most complex structured header types. The AddressHeader class provides a generic interface to any address header.

This header type provides the following additional attributes:

groups

A tuple of Group objects encoding the addresses and groups found in the header value. Addresses that are not part of a group are represented in this list as single-address Groups whose display_name is None.

addresses

A tuple of Address objects encoding all of the individual addresses from the header value. If the header value contains any groups, the individual addresses from the group are included in the list at the point where the group occurs in the value (that is, the list of addresses is “flattened” into a one dimensional list).

The decoded value of the header will have all encoded words decoded to unicode. idna encoded domain names are also decoded to unicode. The decoded value is set by joining the str value of the elements of the groups attribute with ', '.

A list of Address and Group objects in any combination may be used to set the value of an address header. Group objects whose display_name is None will be interpreted as single addresses, which allows an address list to be copied with groups intact by using the list obtained from the groups attribute of the source header.

class email.headerregistry.SingleAddressHeader

A subclass of AddressHeader that adds one additional attribute:

address

The single address encoded by the header value. If the header value actually contains more than one address (which would be a violation of the RFC under the default policy), accessing this attribute will result in a ValueError.

Many of the above classes also have a Unique variant (for example, UniqueUnstructuredHeader). The only difference is that in the Unique variant, max_count is set to 1.

class email.headerregistry.MIMEVersionHeader

There is really only one valid value for the MIME-Version header, and that is 1.0. For future proofing, this header class supports other valid version numbers. If a version number has a valid value per RFC 2045 [https://tools.ietf.org/html/rfc2045.html], then the header object will have non-None values for the following attributes:

version

The version number as a string, with any whitespace and/or comments removed.

major

The major version number as an integer

minor

The minor version number as an integer

class email.headerregistry.ParameterizedMIMEHeader

MIME headers all start with the prefix ‘Content-’. Each specific header has a certain value, described under the class for that header. Some can also take a list of supplemental parameters, which have a common format. This class serves as a base for all the MIME headers that take parameters.

params

A dictionary mapping parameter names to parameter values.

class email.headerregistry.ContentTypeHeader

A ParameterizedMIMEHeader class that handles the Content-Type header.

content_type

The content type string, in the form maintype/subtype.

maintype

subtype

class email.headerregistry.ContentDispositionHeader

A ParameterizedMIMEHeader class that handles the Content-Disposition header.

content-disposition

inline and attachment are the only valid values in common use.

class email.headerregistry.ContentTransferEncoding

Handles the Content-Transfer-Encoding header.

cte

Valid values are 7bit, 8bit, base64, and quoted-printable. See RFC 2045 [https://tools.ietf.org/html/rfc2045.html] for more information.

class email.headerregistry.HeaderRegistry(base_class=BaseHeader, default_class=UnstructuredHeader, use_default_map=True)

This is the factory used by EmailPolicy by default. HeaderRegistry builds the class used to create a header instance dynamically, using base_class and a specialized class retrieved from a registry that it holds. When a given header name does not appear in the registry, the class specified by default_class is used as the specialized class. When use_default_map is True (the default), the standard mapping of header names to classes is copied in to the registry during initialization. base_class is always the last class in the generated class’s __bases__ list.

The default mappings are:

subject

UniqueUnstructuredHeader

date

UniqueDateHeader

resent-date

DateHeader

orig-date

UniqueDateHeader

sender

UniqueSingleAddressHeader

resent-sender

SingleAddressHeader

to

UniqueAddressHeader

resent-to

AddressHeader

cc

UniqueAddressHeader

resent-cc

AddressHeader

from

UniqueAddressHeader

resent-from

AddressHeader

reply-to

UniqueAddressHeader

HeaderRegistry has the following methods:

map_to_type(self, name, cls)

name is the name of the header to be mapped. It will be converted to lower case in the registry. cls is the specialized class to be used, along with base_class, to create the class used to instantiate headers that match name.

__getitem__(name)

Construct and return a class to handle creating a name header.

__call__(name, value)

Retrieves the specialized header associated with name from the registry (using default_class if name does not appear in the registry) and composes it with base_class to produce a class, calls the constructed class’s constructor, passing it the same argument list, and finally returns the class instance created thereby.

The following classes are the classes used to represent data parsed from structured headers and can, in general, be used by an application program to construct structured values to assign to specific headers.

class email.headerregistry.Address(display_name='', username='', domain='', addr_spec=None)

The class used to represent an email address. The general form of an address is:

[display_name] <username@domain>

or:

username@domain

where each part must conform to specific syntax rules spelled out in RFC 5322 [https://tools.ietf.org/html/rfc5322.html].

As a convenience addr_spec can be specified instead of username and domain, in which case username and domain will be parsed from the addr_spec. An addr_spec must be a properly RFC quoted string; if it is not Address will raise an error. Unicode characters are allowed and will be property encoded when serialized. However, per the RFCs, unicode is not allowed in the username portion of the address.

display_name

The display name portion of the address, if any, with all quoting removed. If the address does not have a display name, this attribute will be an empty string.

username

The username portion of the address, with all quoting removed.

domain

The domain portion of the address.

addr_spec

The username@domain portion of the address, correctly quoted for use as a bare address (the second form shown above). This attribute is not mutable.

__str__()

The str value of the object is the address quoted according to RFC 5322 [https://tools.ietf.org/html/rfc5322.html] rules, but with no Content Transfer Encoding of any non-ASCII characters.

To support SMTP (RFC 5321 [https://tools.ietf.org/html/rfc5321.html]), Address handles one special case: if username and domain are both the empty string (or None), then the string value of the Address is <>.

class email.headerregistry.Group(display_name=None, addresses=None)

The class used to represent an address group. The general form of an address group is:

display_name: [address-list];

As a convenience for processing lists of addresses that consist of a mixture of groups and single addresses, a Group may also be used to represent single addresses that are not part of a group by setting display_name to None and providing a list of the single address as addresses.

display_name

The display_name of the group. If it is None and there is exactly one Address in addresses, then the Group represents a single address that is not in a group.

addresses

A possibly empty tuple of Address objects representing the addresses in the group.

__str__()

The str value of a Group is formatted according to RFC 5322 [https://tools.ietf.org/html/rfc5322.html], but with no Content Transfer Encoding of any non-ASCII characters. If display_name is none and there is a single Address in the addresses list, the str value will be the same as the str of that single Address.

Footnotes

1

Originally added in 3.3 as a provisional module

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 데이터 처리 »

email — 전자 메일과 MIME 처리 패키지 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 데이터 처리 »

email — 전자 메일과 MIME 처리 패키지 »

|

email.contentmanager: MIME 콘텐츠 관리

소스 코드: Lib/email/contentmanager.py [https://github.com/python/cpython/tree/3.7/Lib/email/contentmanager.py]

버전 3.6에 추가: 1

class email.contentmanager.ContentManager

콘텐츠 관리자를 위한 베이스 클래스. get_content와 set_content 디스패치 메서드뿐만 아니라 MIME 콘텐츠와 다른 표현 간의 변환기를 등록하는 표준 등록소 메커니즘을 제공합니다.

get_content(msg, *args, **kw)

msg의 mimetype을 기반으로 처리기 함수를 찾고 (다음 단락을 참조하십시오), 모든 인자를 전달하여 그것을 호출하고, 이 호출의 결과를 반환합니다. 처리기가 msg에서 페이 로드를 추출하고 추출된 데이터에 대한 정보를 인코딩하는 객체를 반환할 것으로 기대합니다.

처리기를 찾으려면, 등록소에서 다음 키를 찾는데, 처음 발견되는 것에서 멈춥니다:

전체 MIME 유형을 나타내는 문자열 (maintype/subtype)

maintype을 나타내는 문자열

빈 문자열

이러한 키 중 아무것도 이러한 처리기를 생성하지 않으면, 전체 MIME 유형에 대해 KeyError를 발생시킵니다.

set_content(msg, obj, *args, **kw)

maintype이 multipart이면, TypeError를 발생시킵니다; 그렇지 않으면 obj의 형을 기반으로 처리기 함수를 찾고 (다음 단락을 참조하십시오), msg에서 clear_content()를 호출한 다음, 모든 인자를 전달해서 처리기 함수를 호출합니다. 처리기가 obj를 msg로 변환하고 저장할 것으로 기대하는데, 저장된 데이터를 해석하는 데 필요한 정보를 인코딩하기 위해 다양한 MIME 헤더를 추가하는 등 msg에 다른 변경을 가할 수 있습니다.

처리기를 찾으려면, obj의 형을 얻고 (typ = type(obj)), 등록소에서 다음 키를 찾는데 처음 발견되는 것에서 멈춥니다:

형 자체 (typ)

형의 완전히 정규화된 이름 (typ.__module__ + '.' + typ.__qualname__).

형의 qualname (typ.__qualname__)

형의 이름 (typ.__name__).

이 중 아무것도 일치하지 않으면, MRO(typ.__mro__)의 각 형에 대해 위의 모든 검사를 반복합니다. 마지막으로, 다른 키가 처리기를 생성하지 않으면, None 키의 처리기를 확인합니다. None에 대한 처리기가 없으면, 형의 완전히 정규화된 이름으로 KeyError를 발생시킵니다.

MIME-Version 헤더가 없으면 추가합니다 (MIMEPart를 참조하십시오).

add_get_handler(key, handler)

함수 handler를 key의 처리기로 기록합니다. 가능한 key 값은 get_content()를 참조하십시오.

add_set_handler(typekey, handler)

typekey와 일치하는 형의 객체가 set_content()에 전달될 때 호출할 함수로 handler를 기록합니다. 가능한 typekey 값은 set_content()를 참조하십시오.

콘텐츠 관리자 인스턴스

현재 email 패키지는 하나의 구상 콘텐츠 관리자 raw_data_manager만 제공하지만, 향후에는 더 추가될 수 있습니다. raw_data_manager는 EmailPolicy와 그 파생물에 의해 제공되는 content_manager입니다.

email.contentmanager.raw_data_manager

이 콘텐츠 관리자는 Message 자체에서 제공하는 것 외에는 최소 인터페이스 만 제공합니다: 텍스트, 날 바이트열 및 Message 객체만 다룹니다. 그런데도 기본 API와 비교할 때 상당한 이점을 제공합니다: 텍스트 파트에 대한 get_content는 응용 프로그램이 수동으로 디코딩할 필요 없이 유니코드 문자열을 반환하고, set_content는 파트에 추가된 헤더를 제어하고 콘텐츠 전송 인코딩을 제어하기 위한 다양한 옵션을 제공하고, 다양한 add_ 메서드를 사용할 수 있도록 해서, 멀티 파트 메시지 작성을 단순화합니다.

email.contentmanager.get_content(msg, errors='replace')

파트의 페이 로드를 문자열(text 파트의 경우), EmailMessage 객체 (message/rfc822 파트의 경우) 또는 bytes 객체 (다른 모든 비 멀티 파트 유형의 경우)로 반환합니다. multipart에서 호출되면 KeyError를 발생시킵니다. 파트가 text 파트이고 errors가 지정되면, 페이 로드를 유니코드로 디코딩할 때 에러 처리기로 사용합니다. 기본 에러 처리기는 replace입니다.

email.contentmanager.set_content(msg, <'str'>, subtype="plain", charset='utf-8' cte=None, disposition=None, filename=None, cid=None, params=None, headers=None)

email.contentmanager.set_content(msg, <'bytes'>, maintype, subtype, cte="base64", disposition=None, filename=None, cid=None, params=None, headers=None)

email.contentmanager.set_content(msg, <'EmailMessage'>, cte=None, disposition=None, filename=None, cid=None, params=None, headers=None)

msg에 헤더와 페이 로드를 추가합니다:

maintype/subtype 값으로 Content-Type 헤더를 추가합니다.

str의 경우, MIME maintype을 text로 설정하고, 서브 유형은 지정되었으면 subtype으로 설정하고, 지정되지 않았으면 plain으로 설정합니다.

bytes의 경우, 지정된 maintype과 subtype을 사용하거나, 지정되지 않았으면 TypeError를 발생시킵니다.

EmailMessage 객체의 경우, 메인 유형을 message로 설정하고, 서브 유형은 지정되었으면 subtype으로 설정하고, 지정되지 않았으면 rfc822로 설정합니다. subtype이 partial이면 에러를 발생시킵니다 (bytes 객체를 사용하여 message/partial 파트를 구성해야 합니다).

charset이 제공되면 (str에만 유효합니다), 지정된 문자 집합을 사용하여 문자열을 바이트열로 인코딩합니다. 기본값은 utf-8입니다. 지정된 charset이 표준 MIME 문자 집합 이름의 알려진 별칭이면, 표준 문자 집합을 대신 사용합니다.

cte가 설정되면, 지정된 콘텐츠 전송 인코딩을 사용하여 페이 로드를 인코딩하고, Content-Transfer-Encoding 헤더를 해당 값으로 설정합니다. cte의 가능한 값은 quoted-printable, base64, 7bit, 8bit 및 binary입니다. 지정된 인코딩으로 입력을 인코딩할 수 없으면 (예를 들어, 비 ASCII 값을 포함하는 입력에 대해 cte를 7bit로 지정합니다), ValueError를 발생시킵니다.

str 객체의 경우, cte가 설정되지 않으면 휴리스틱을 사용하여 가장 간결한 인코딩을 결정합니다.

EmailMessage의 경우, RFC 2046 [https://tools.ietf.org/html/rfc2046.html]에 따라, subtype rfc822에 대해 quoted-printable이나 base64의 cte가 요청되거나, subtype external-body에 대해 7bit 이외의 cte에 대해 에러를 발생시킵니다. message/rfc822의 경우, cte가 지정되지 않으면 8bit를 사용합니다. subtype의 다른 모든 값에는 7bit를 사용합니다.

참고

binary의 cte는 실제로 아직 제대로 작동하지 않습니다. set_content에 의해 수정된 EmailMessage 객체는 올바르지만, BytesGenerator는 이것을 올바르게 직렬화하지 않습니다.

disposition이 설정되면, 이를 Content-Disposition 헤더의 값으로 사용합니다. 지정되지 않고 filename이 지정되면, 값이 attachment인 헤더를 추가합니다. disposition이 지정되지 않고 filename도 지정되지 않으면, 헤더를 추가하지 않습니다. disposition에 유효한 값은 attachment와 inline뿐 입니다.

filename이 지정되면, 이를 Content-Disposition 헤더의 filename 파라미터의 값으로 사용합니다.

cid가 지정되면, cid를 값으로 사용하여 Content-ID 헤더를 추가합니다.

params가 지정되면, 그것의 items 메서드를 이터레이트하고 결과 (key, value) 쌍을 사용하여 Content-Type 헤더에 추가 파라미터를 설정합니다.

headers가 지정되고 headername: headervalue 형식의 문자열 리스트나 header 객체 (name 어트리뷰트를 가진 것으로 문자열과 구별됩니다) 리스트면, 헤더를 msg에 추가합니다.

각주

1

원래 3.4에서 잠정적 모듈로 추가되었습니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 데이터 처리 »

email — 전자 메일과 MIME 처리 패키지 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 데이터 처리 »

email — 전자 메일과 MIME 처리 패키지 »

|

email: 예제

다음은 email 패키지를 사용하여 간단한 전자 우편 메시지뿐만 아니라 더 복잡한 MIME 메시지를 읽고 쓰고 보내는 방법에 대한 몇 가지 예입니다.

먼저 간단한 텍스트 메시지를 만들고 보내는 방법을 살펴보겠습니다 (텍스트 내용과 주소에 유니코드 문자가 포함될 수 있습니다):

# Import smtplib for the actual sending function
import smtplib

# Import the email modules we'll need
from email.message import EmailMessage

# Open the plain text file whose name is in textfile for reading.
with open(textfile) as fp:
    # Create a text/plain message
    msg = EmailMessage()
    msg.set_content(fp.read())

# me == the sender's email address
# you == the recipient's email address
msg['Subject'] = f'The contents of {textfile}'
msg['From'] = me
msg['To'] = you

# Send the message via our own SMTP server.
s = smtplib.SMTP('localhost')
s.send_message(msg)
s.quit()

parser 모듈의 클래스를 사용하여 RFC 822 [https://tools.ietf.org/html/rfc822.html] 헤더를 쉽게 구문 분석할 수 있습니다:

# Import the email modules we'll need
from email.parser import BytesParser, Parser
from email.policy import default

# If the e-mail headers are in a file, uncomment these two lines:
# with open(messagefile, 'rb') as fp:
#     headers = BytesParser(policy=default).parse(fp)

#  Or for parsing headers in a string (this is an uncommon operation), use:
headers = Parser(policy=default).parsestr(
        'From: Foo Bar <user@example.com>\n'
        'To: <someone_else@example.com>\n'
        'Subject: Test message\n'
        '\n'
        'Body would go here\n')

#  Now the header items can be accessed as a dictionary:
print('To: {}'.format(headers['to']))
print('From: {}'.format(headers['from']))
print('Subject: {}'.format(headers['subject']))

# You can also access the parts of the addresses:
print('Recipient username: {}'.format(headers['to'].addresses[0].username))
print('Sender name: {}'.format(headers['from'].addresses[0].display_name))

다음은 디렉터리에 있을 수 있는 가족사진을 포함하는 MIME 메시지를 보내는 방법의 예입니다:

# Import smtplib for the actual sending function
import smtplib

# And imghdr to find the types of our images
import imghdr

# Here are the email package modules we'll need
from email.message import EmailMessage

# Create the container email message.
msg = EmailMessage()
msg['Subject'] = 'Our family reunion'
# me == the sender's email address
# family = the list of all recipients' email addresses
msg['From'] = me
msg['To'] = ', '.join(family)
msg.preamble = 'You will not see this in a MIME-aware mail reader.\n'

# Open the files in binary mode.  Use imghdr to figure out the
# MIME subtype for each specific image.
for file in pngfiles:
    with open(file, 'rb') as fp:
        img_data = fp.read()
    msg.add_attachment(img_data, maintype='image',
                                 subtype=imghdr.what(None, img_data))

# Send the email via our own SMTP server.
with smtplib.SMTP('localhost') as s:
    s.send_message(msg)

다음은 디렉터리의 전체 내용을 전자 우편 메시지로 보내는 방법의 예입니다: 1

#!/usr/bin/env python3

"""Send the contents of a directory as a MIME message."""

import os
import smtplib
# For guessing MIME type based on file name extension
import mimetypes

from argparse import ArgumentParser

from email.message import EmailMessage
from email.policy import SMTP

def main():
    parser = ArgumentParser(description="""\
Send the contents of a directory as a MIME message.
Unless the -o option is given, the email is sent by forwarding to your local
SMTP server, which then does the normal delivery process.  Your local machine
must be running an SMTP server.
""")
    parser.add_argument('-d', '--directory',
                        help="""Mail the contents of the specified directory,
                        otherwise use the current directory.  Only the regular
                        files in the directory are sent, and we don't recurse to
                        subdirectories.""")
    parser.add_argument('-o', '--output',
                        metavar='FILE',
                        help="""Print the composed message to FILE instead of
                        sending the message to the SMTP server.""")
    parser.add_argument('-s', '--sender', required=True,
                        help='The value of the From: header (required)')
    parser.add_argument('-r', '--recipient', required=True,
                        action='append', metavar='RECIPIENT',
                        default=[], dest='recipients',
                        help='A To: header value (at least one required)')
    args = parser.parse_args()
    directory = args.directory
    if not directory:
        directory = '.'
    # Create the message
    msg = EmailMessage()
    msg['Subject'] = f'Contents of directory {os.path.abspath(directory)}'
    msg['To'] = ', '.join(args.recipients)
    msg['From'] = args.sender
    msg.preamble = 'You will not see this in a MIME-aware mail reader.\n'

    for filename in os.listdir(directory):
        path = os.path.join(directory, filename)
        if not os.path.isfile(path):
            continue
        # Guess the content type based on the file's extension.  Encoding
        # will be ignored, although we should check for simple things like
        # gzip'd or compressed files.
        ctype, encoding = mimetypes.guess_type(path)
        if ctype is None or encoding is not None:
            # No guess could be made, or the file is encoded (compressed), so
            # use a generic bag-of-bits type.
            ctype = 'application/octet-stream'
        maintype, subtype = ctype.split('/', 1)
        with open(path, 'rb') as fp:
            msg.add_attachment(fp.read(),
                               maintype=maintype,
                               subtype=subtype,
                               filename=filename)
    # Now send or store the message
    if args.output:
        with open(args.output, 'wb') as fp:
            fp.write(msg.as_bytes(policy=SMTP))
    else:
        with smtplib.SMTP('localhost') as s:
            s.send_message(msg)

if __name__ == '__main__':
    main()

다음은 위와 같은 MIME 메시지를 디렉터리로 푸는 방법의 예입니다:

#!/usr/bin/env python3

"""Unpack a MIME message into a directory of files."""

import os
import email
import mimetypes

from email.policy import default

from argparse import ArgumentParser

def main():
    parser = ArgumentParser(description="""\
Unpack a MIME message into a directory of files.
""")
    parser.add_argument('-d', '--directory', required=True,
                        help="""Unpack the MIME message into the named
                        directory, which will be created if it doesn't already
                        exist.""")
    parser.add_argument('msgfile')
    args = parser.parse_args()

    with open(args.msgfile, 'rb') as fp:
        msg = email.message_from_binary_file(fp, policy=default)

    try:
        os.mkdir(args.directory)
    except FileExistsError:
        pass

    counter = 1
    for part in msg.walk():
        # multipart/* are just containers
        if part.get_content_maintype() == 'multipart':
            continue
        # Applications should really sanitize the given filename so that an
        # email message can't be used to overwrite important files
        filename = part.get_filename()
        if not filename:
            ext = mimetypes.guess_extension(part.get_content_type())
            if not ext:
                # Use a generic bag-of-bits extension
                ext = '.bin'
            filename = f'part-{counter:03d}{ext}'
        counter += 1
        with open(os.path.join(args.directory, filename), 'wb') as fp:
            fp.write(part.get_payload(decode=True))

if __name__ == '__main__':
    main()

다음은 대체 일반 텍스트 버전으로 HTML 메시지를 만드는 방법의 예입니다. 좀 더 흥미롭게 하기 위해, html 부분에 관련 이미지를 포함하고, 보낼 뿐만 아니라, 보낼 것의 사본을 디스크에 저장합니다.

#!/usr/bin/env python3

import smtplib

from email.message import EmailMessage
from email.headerregistry import Address
from email.utils import make_msgid

# Create the base text message.
msg = EmailMessage()
msg['Subject'] = "Ayons asperges pour le déjeuner"
msg['From'] = Address("Pepé Le Pew", "pepe", "example.com")
msg['To'] = (Address("Penelope Pussycat", "penelope", "example.com"),
             Address("Fabrette Pussycat", "fabrette", "example.com"))
msg.set_content("""\
Salut!

Cela ressemble à un excellent recipie[1] déjeuner.

[1] http://www.yummly.com/recipe/Roasted-Asparagus-Epicurious-203718

--Pepé
""")

# Add the html version.  This converts the message into a multipart/alternative
# container, with the original text message as the first part and the new html
# message as the second part.
asparagus_cid = make_msgid()
msg.add_alternative("""\
<html>
  <head></head>
  <body>
    <p>Salut!</p>
    <p>Cela ressemble à un excellent
        <a href="http://www.yummly.com/recipe/Roasted-Asparagus-Epicurious-203718">
            recipie
        </a> déjeuner.
    </p>
    <img src="cid:{asparagus_cid}" />
  </body>
</html>
""".format(asparagus_cid=asparagus_cid[1:-1]), subtype='html')
# note that we needed to peel the <> off the msgid for use in the html.

# Now add the related image to the html part.
with open("roasted-asparagus.jpg", 'rb') as img:
    msg.get_payload()[1].add_related(img.read(), 'image', 'jpeg',
                                     cid=asparagus_cid)

# Make a local copy of what we are going to send.
with open('outgoing.msg', 'wb') as f:
    f.write(bytes(msg))

# Send the message via local SMTP server.
with smtplib.SMTP('localhost') as s:
    s.send_message(msg)

마지막 예에서 메시지를 보냈다면, 다음은 그것을 처리하는 한 가지 방법입니다:

import os
import sys
import tempfile
import mimetypes
import webbrowser

# Import the email modules we'll need
from email import policy
from email.parser import BytesParser

# An imaginary module that would make this work and be safe.
from imaginary import magic_html_parser

# In a real program you'd get the filename from the arguments.
with open('outgoing.msg', 'rb') as fp:
    msg = BytesParser(policy=policy.default).parse(fp)

# Now the header items can be accessed as a dictionary, and any non-ASCII will
# be converted to unicode:
print('To:', msg['to'])
print('From:', msg['from'])
print('Subject:', msg['subject'])

# If we want to print a preview of the message content, we can extract whatever
# the least formatted payload is and print the first three lines.  Of course,
# if the message has no plain text part printing the first three lines of html
# is probably useless, but this is just a conceptual example.
simplest = msg.get_body(preferencelist=('plain', 'html'))
print()
print(''.join(simplest.get_content().splitlines(keepends=True)[:3]))

ans = input("View full message?")
if ans.lower()[0] == 'n':
    sys.exit()

# We can extract the richest alternative in order to display it:
richest = msg.get_body()
partfiles = {}
if richest['content-type'].maintype == 'text':
    if richest['content-type'].subtype == 'plain':
        for line in richest.get_content().splitlines():
            print(line)
        sys.exit()
    elif richest['content-type'].subtype == 'html':
        body = richest
    else:
        print("Don't know how to display {}".format(richest.get_content_type()))
        sys.exit()
elif richest['content-type'].content_type == 'multipart/related':
    body = richest.get_body(preferencelist=('html'))
    for part in richest.iter_attachments():
        fn = part.get_filename()
        if fn:
            extension = os.path.splitext(part.get_filename())[1]
        else:
            extension = mimetypes.guess_extension(part.get_content_type())
        with tempfile.NamedTemporaryFile(suffix=extension, delete=False) as f:
            f.write(part.get_content())
            # again strip the <> to go from email form of cid to html form.
            partfiles[part['content-id'][1:-1]] = f.name
else:
    print("Don't know how to display {}".format(richest.get_content_type()))
    sys.exit()
with tempfile.NamedTemporaryFile(mode='w', delete=False) as f:
    # The magic_html_parser has to rewrite the href="cid:...." attributes to
    # point to the filenames in partfiles.  It also has to do a safety-sanitize
    # of the html.  It could be written using html.parser.
    f.write(magic_html_parser(body.get_content(), partfiles))
webbrowser.open(f.name)
os.remove(f.name)
for fn in partfiles.values():
    os.remove(fn)

# Of course, there are lots of email messages that could break this simple
# minded program, but it will handle the most common ones.

프롬프트까지, 위의 출력은 다음과 같습니다:

To: Penelope Pussycat <penelope@example.com>, Fabrette Pussycat <fabrette@example.com>
From: Pepé Le Pew <pepe@example.com>
Subject: Ayons asperges pour le déjeuner

Salut!

Cela ressemble à un excellent recipie[1] déjeuner.

각주

1

영감과 예를 주신 Matthew Dixon Cowles에게 감사드립니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 데이터 처리 »

email — 전자 메일과 MIME 처리 패키지 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 데이터 처리 »

email — 전자 메일과 MIME 처리 패키지 »

|

email.message.Message: Representing an email message using the compat32 API

The Message class is very similar to the EmailMessage class, without the methods added by that class, and with the default behavior of certain other methods being slightly different. We also document here some methods that, while supported by the EmailMessage class, are not recommended unless you are dealing with legacy code.

The philosophy and structure of the two classes is otherwise the same.

This document describes the behavior under the default (for Message) policy Compat32. If you are going to use another policy, you should be using the EmailMessage class instead.

An email message consists of headers and a payload. Headers must be RFC 5233 [https://tools.ietf.org/html/rfc5233.html] style names and values, where the field name and value are separated by a colon. The colon is not part of either the field name or the field value. The payload may be a simple text message, or a binary object, or a structured sequence of sub-messages each with their own set of headers and their own payload. The latter type of payload is indicated by the message having a MIME type such as multipart/* or message/rfc822.

The conceptual model provided by a Message object is that of an ordered dictionary of headers with additional methods for accessing both specialized information from the headers, for accessing the payload, for generating a serialized version of the message, and for recursively walking over the object tree. Note that duplicate headers are supported but special methods must be used to access them.

The Message pseudo-dictionary is indexed by the header names, which must be ASCII values. The values of the dictionary are strings that are supposed to contain only ASCII characters; there is some special handling for non-ASCII input, but it doesn’t always produce the correct results. Headers are stored and returned in case-preserving form, but field names are matched case-insensitively. There may also be a single envelope header, also known as the Unix-From header or the From_ header. The payload is either a string or bytes, in the case of simple message objects, or a list of Message objects, for MIME container documents (e.g. multipart/* and message/rfc822).

Here are the methods of the Message class:

class email.message.Message(policy=compat32)

If policy is specified (it must be an instance of a policy class) use the rules it specifies to update and serialize the representation of the message. If policy is not set, use the compat32 policy, which maintains backward compatibility with the Python 3.2 version of the email package. For more information see the policy documentation.

버전 3.3에서 변경: The policy keyword argument was added.

as_string(unixfrom=False, maxheaderlen=0, policy=None)

Return the entire message flattened as a string. When optional unixfrom is true, the envelope header is included in the returned string. unixfrom defaults to False. For backward compatibility reasons, maxheaderlen defaults to 0, so if you want a different value you must override it explicitly (the value specified for max_line_length in the policy will be ignored by this method). The policy argument may be used to override the default policy obtained from the message instance. This can be used to control some of the formatting produced by the method, since the specified policy will be passed to the Generator.

Flattening the message may trigger changes to the Message if defaults need to be filled in to complete the transformation to a string (for example, MIME boundaries may be generated or modified).

Note that this method is provided as a convenience and may not always format the message the way you want. For example, by default it does not do the mangling of lines that begin with From that is required by the unix mbox format. For more flexibility, instantiate a Generator instance and use its flatten() method directly. For example:

from io import StringIO
from email.generator import Generator
fp = StringIO()
g = Generator(fp, mangle_from_=True, maxheaderlen=60)
g.flatten(msg)
text = fp.getvalue()

If the message object contains binary data that is not encoded according to RFC standards, the non-compliant data will be replaced by unicode “unknown character” code points. (See also as_bytes() and BytesGenerator.)

버전 3.4에서 변경: the policy keyword argument was added.

__str__()

Equivalent to as_string(). Allows str(msg) to produce a string containing the formatted message.

as_bytes(unixfrom=False, policy=None)

Return the entire message flattened as a bytes object. When optional unixfrom is true, the envelope header is included in the returned string. unixfrom defaults to False. The policy argument may be used to override the default policy obtained from the message instance. This can be used to control some of the formatting produced by the method, since the specified policy will be passed to the BytesGenerator.

Flattening the message may trigger changes to the Message if defaults need to be filled in to complete the transformation to a string (for example, MIME boundaries may be generated or modified).

Note that this method is provided as a convenience and may not always format the message the way you want. For example, by default it does not do the mangling of lines that begin with From that is required by the unix mbox format. For more flexibility, instantiate a BytesGenerator instance and use its flatten() method directly. For example:

from io import BytesIO
from email.generator import BytesGenerator
fp = BytesIO()
g = BytesGenerator(fp, mangle_from_=True, maxheaderlen=60)
g.flatten(msg)
text = fp.getvalue()

버전 3.4에 추가.

__bytes__()

Equivalent to as_bytes(). Allows bytes(msg) to produce a bytes object containing the formatted message.

버전 3.4에 추가.

is_multipart()

Return True if the message’s payload is a list of sub-Message objects, otherwise return False. When is_multipart() returns False, the payload should be a string object (which might be a CTE encoded binary payload). (Note that is_multipart() returning True does not necessarily mean that “msg.get_content_maintype() == ‘multipart’” will return the True. For example, is_multipart will return True when the Message is of type message/rfc822.)

set_unixfrom(unixfrom)

Set the message’s envelope header to unixfrom, which should be a string.

get_unixfrom()

Return the message’s envelope header. Defaults to None if the envelope header was never set.

attach(payload)

Add the given payload to the current payload, which must be None or a list of Message objects before the call. After the call, the payload will always be a list of Message objects. If you want to set the payload to a scalar object (e.g. a string), use set_payload() instead.

This is a legacy method. On the EmailMessage class its functionality is replaced by set_content() and the related make and add methods.

get_payload(i=None, decode=False)

Return the current payload, which will be a list of Message objects when is_multipart() is True, or a string when is_multipart() is False. If the payload is a list and you mutate the list object, you modify the message’s payload in place.

With optional argument i, get_payload() will return the i-th element of the payload, counting from zero, if is_multipart() is True. An IndexError will be raised if i is less than 0 or greater than or equal to the number of items in the payload. If the payload is a string (i.e. is_multipart() is False) and i is given, a TypeError is raised.

Optional decode is a flag indicating whether the payload should be decoded or not, according to the Content-Transfer-Encoding header. When True and the message is not a multipart, the payload will be decoded if this header’s value is quoted-printable or base64. If some other encoding is used, or Content-Transfer-Encoding header is missing, the payload is returned as-is (undecoded). In all cases the returned value is binary data. If the message is a multipart and the decode flag is True, then None is returned. If the payload is base64 and it was not perfectly formed (missing padding, characters outside the base64 alphabet), then an appropriate defect will be added to the message’s defect property (InvalidBase64PaddingDefect or InvalidBase64CharactersDefect, respectively).

When decode is False (the default) the body is returned as a string without decoding the Content-Transfer-Encoding. However, for a Content-Transfer-Encoding of 8bit, an attempt is made to decode the original bytes using the charset specified by the Content-Type header, using the replace error handler. If no charset is specified, or if the charset given is not recognized by the email package, the body is decoded using the default ASCII charset.

This is a legacy method. On the EmailMessage class its functionality is replaced by get_content() and iter_parts().

set_payload(payload, charset=None)

Set the entire message object’s payload to payload. It is the client’s responsibility to ensure the payload invariants. Optional charset sets the message’s default character set; see set_charset() for details.

This is a legacy method. On the EmailMessage class its functionality is replaced by set_content().

set_charset(charset)

Set the character set of the payload to charset, which can either be a Charset instance (see email.charset), a string naming a character set, or None. If it is a string, it will be converted to a Charset instance. If charset is None, the charset parameter will be removed from the Content-Type header (the message will not be otherwise modified). Anything else will generate a TypeError.

If there is no existing MIME-Version header one will be added. If there is no existing Content-Type header, one will be added with a value of text/plain. Whether the Content-Type header already exists or not, its charset parameter will be set to charset.output_charset. If charset.input_charset and charset.output_charset differ, the payload will be re-encoded to the output_charset. If there is no existing Content-Transfer-Encoding header, then the payload will be transfer-encoded, if needed, using the specified Charset, and a header with the appropriate value will be added. If a Content-Transfer-Encoding header already exists, the payload is assumed to already be correctly encoded using that Content-Transfer-Encoding and is not modified.

This is a legacy method. On the EmailMessage class its functionality is replaced by the charset parameter of the email.emailmessage.EmailMessage.set_content() method.

get_charset()

Return the Charset instance associated with the message’s payload.

This is a legacy method. On the EmailMessage class it always returns None.

The following methods implement a mapping-like interface for accessing the message’s RFC 2822 [https://tools.ietf.org/html/rfc2822.html] headers. Note that there are some semantic differences between these methods and a normal mapping (i.e. dictionary) interface. For example, in a dictionary there are no duplicate keys, but here there may be duplicate message headers. Also, in dictionaries there is no guaranteed order to the keys returned by keys(), but in a Message object, headers are always returned in the order they appeared in the original message, or were added to the message later. Any header deleted and then re-added are always appended to the end of the header list.

These semantic differences are intentional and are biased toward maximal convenience.

Note that in all cases, any envelope header present in the message is not included in the mapping interface.

In a model generated from bytes, any header values that (in contravention of the RFCs) contain non-ASCII bytes will, when retrieved through this interface, be represented as Header objects with a charset of unknown-8bit.

__len__()

Return the total number of headers, including duplicates.

__contains__(name)

Return True if the message object has a field named name. Matching is done case-insensitively and name should not include the trailing colon. Used for the in operator, e.g.:

if 'message-id' in myMessage:
   print('Message-ID:', myMessage['message-id'])

__getitem__(name)

Return the value of the named header field. name should not include the colon field separator. If the header is missing, None is returned; a KeyError is never raised.

Note that if the named field appears more than once in the message’s headers, exactly which of those field values will be returned is undefined. Use the get_all() method to get the values of all the extant named headers.

__setitem__(name, val)

Add a header to the message with field name name and value val. The field is appended to the end of the message’s existing fields.

Note that this does not overwrite or delete any existing header with the same name. If you want to ensure that the new header is the only one present in the message with field name name, delete the field first, e.g.:

del msg['subject']
msg['subject'] = 'Python roolz!'

__delitem__(name)

Delete all occurrences of the field with name name from the message’s headers. No exception is raised if the named field isn’t present in the headers.

keys()

Return a list of all the message’s header field names.

values()

Return a list of all the message’s field values.

items()

Return a list of 2-tuples containing all the message’s field headers and values.

get(name, failobj=None)

Return the value of the named header field. This is identical to __getitem__() except that optional failobj is returned if the named header is missing (defaults to None).

Here are some additional useful methods:

get_all(name, failobj=None)

Return a list of all the values for the field named name. If there are no such named headers in the message, failobj is returned (defaults to None).

add_header(_name, _value, **_params)

Extended header setting. This method is similar to __setitem__() except that additional header parameters can be provided as keyword arguments. _name is the header field to add and _value is the primary value for the header.

For each item in the keyword argument dictionary _params, the key is taken as the parameter name, with underscores converted to dashes (since dashes are illegal in Python identifiers). Normally, the parameter will be added as key="value" unless the value is None, in which case only the key will be added. If the value contains non-ASCII characters, it can be specified as a three tuple in the format (CHARSET, LANGUAGE, VALUE), where CHARSET is a string naming the charset to be used to encode the value, LANGUAGE can usually be set to None or the empty string (see RFC 2231 [https://tools.ietf.org/html/rfc2231.html] for other possibilities), and VALUE is the string value containing non-ASCII code points. If a three tuple is not passed and the value contains non-ASCII characters, it is automatically encoded in RFC 2231 [https://tools.ietf.org/html/rfc2231.html] format using a CHARSET of utf-8 and a LANGUAGE of None.

Here’s an example:

msg.add_header('Content-Disposition', 'attachment', filename='bud.gif')

This will add a header that looks like

Content-Disposition: attachment; filename="bud.gif"

An example with non-ASCII characters:

msg.add_header('Content-Disposition', 'attachment',
               filename=('iso-8859-1', '', 'Fußballer.ppt'))

Which produces

Content-Disposition: attachment; filename*="iso-8859-1''Fu%DFballer.ppt"

replace_header(_name, _value)

Replace a header. Replace the first header found in the message that matches _name, retaining header order and field name case. If no matching header was found, a KeyError is raised.

get_content_type()

Return the message’s content type. The returned string is coerced to lower case of the form maintype/subtype. If there was no Content-Type header in the message the default type as given by get_default_type() will be returned. Since according to RFC 2045 [https://tools.ietf.org/html/rfc2045.html], messages always have a default type, get_content_type() will always return a value.

RFC 2045 [https://tools.ietf.org/html/rfc2045.html] defines a message’s default type to be text/plain unless it appears inside a multipart/digest container, in which case it would be message/rfc822. If the Content-Type header has an invalid type specification, RFC 2045 [https://tools.ietf.org/html/rfc2045.html] mandates that the default type be text/plain.

get_content_maintype()

Return the message’s main content type. This is the maintype part of the string returned by get_content_type().

get_content_subtype()

Return the message’s sub-content type. This is the subtype part of the string returned by get_content_type().

get_default_type()

Return the default content type. Most messages have a default content type of text/plain, except for messages that are subparts of multipart/digest containers. Such subparts have a default content type of message/rfc822.

set_default_type(ctype)

Set the default content type. ctype should either be text/plain or message/rfc822, although this is not enforced. The default content type is not stored in the Content-Type header.

get_params(failobj=None, header='content-type', unquote=True)

Return the message’s Content-Type parameters, as a list. The elements of the returned list are 2-tuples of key/value pairs, as split on the '=' sign. The left hand side of the '=' is the key, while the right hand side is the value. If there is no '=' sign in the parameter the value is the empty string, otherwise the value is as described in get_param() and is unquoted if optional unquote is True (the default).

Optional failobj is the object to return if there is no Content-Type header. Optional header is the header to search instead of Content-Type.

This is a legacy method. On the EmailMessage class its functionality is replaced by the params property of the individual header objects returned by the header access methods.

get_param(param, failobj=None, header='content-type', unquote=True)

Return the value of the Content-Type header’s parameter param as a string. If the message has no Content-Type header or if there is no such parameter, then failobj is returned (defaults to None).

Optional header if given, specifies the message header to use instead of Content-Type.

Parameter keys are always compared case insensitively. The return value can either be a string, or a 3-tuple if the parameter was RFC 2231 [https://tools.ietf.org/html/rfc2231.html] encoded. When it’s a 3-tuple, the elements of the value are of the form (CHARSET, LANGUAGE, VALUE). Note that both CHARSET and LANGUAGE can be None, in which case you should consider VALUE to be encoded in the us-ascii charset. You can usually ignore LANGUAGE.

If your application doesn’t care whether the parameter was encoded as in RFC 2231 [https://tools.ietf.org/html/rfc2231.html], you can collapse the parameter value by calling email.utils.collapse_rfc2231_value(), passing in the return value from get_param(). This will return a suitably decoded Unicode string when the value is a tuple, or the original string unquoted if it isn’t. For example:

rawparam = msg.get_param('foo')
param = email.utils.collapse_rfc2231_value(rawparam)

In any case, the parameter value (either the returned string, or the VALUE item in the 3-tuple) is always unquoted, unless unquote is set to False.

This is a legacy method. On the EmailMessage class its functionality is replaced by the params property of the individual header objects returned by the header access methods.

set_param(param, value, header='Content-Type', requote=True, charset=None, language='', replace=False)

Set a parameter in the Content-Type header. If the parameter already exists in the header, its value will be replaced with value. If the Content-Type header as not yet been defined for this message, it will be set to text/plain and the new parameter value will be appended as per RFC 2045 [https://tools.ietf.org/html/rfc2045.html].

Optional header specifies an alternative header to Content-Type, and all parameters will be quoted as necessary unless optional requote is False (the default is True).

If optional charset is specified, the parameter will be encoded according to RFC 2231 [https://tools.ietf.org/html/rfc2231.html]. Optional language specifies the RFC 2231 language, defaulting to the empty string. Both charset and language should be strings.

If replace is False (the default) the header is moved to the end of the list of headers. If replace is True, the header will be updated in place.

버전 3.4에서 변경: replace keyword was added.

del_param(param, header='content-type', requote=True)

Remove the given parameter completely from the Content-Type header. The header will be re-written in place without the parameter or its value. All values will be quoted as necessary unless requote is False (the default is True). Optional header specifies an alternative to Content-Type.

set_type(type, header='Content-Type', requote=True)

Set the main type and subtype for the Content-Type header. type must be a string in the form maintype/subtype, otherwise a ValueError is raised.

This method replaces the Content-Type header, keeping all the parameters in place. If requote is False, this leaves the existing header’s quoting as is, otherwise the parameters will be quoted (the default).

An alternative header can be specified in the header argument. When the Content-Type header is set a MIME-Version header is also added.

This is a legacy method. On the EmailMessage class its functionality is replaced by the make_ and add_ methods.

get_filename(failobj=None)

Return the value of the filename parameter of the Content-Disposition header of the message. If the header does not have a filename parameter, this method falls back to looking for the name parameter on the Content-Type header. If neither is found, or the header is missing, then failobj is returned. The returned string will always be unquoted as per email.utils.unquote().

get_boundary(failobj=None)

Return the value of the boundary parameter of the Content-Type header of the message, or failobj if either the header is missing, or has no boundary parameter. The returned string will always be unquoted as per email.utils.unquote().

set_boundary(boundary)

Set the boundary parameter of the Content-Type header to boundary. set_boundary() will always quote boundary if necessary. A HeaderParseError is raised if the message object has no Content-Type header.

Note that using this method is subtly different than deleting the old Content-Type header and adding a new one with the new boundary via add_header(), because set_boundary() preserves the order of the Content-Type header in the list of headers. However, it does not preserve any continuation lines which may have been present in the original Content-Type header.

get_content_charset(failobj=None)

Return the charset parameter of the Content-Type header, coerced to lower case. If there is no Content-Type header, or if that header has no charset parameter, failobj is returned.

Note that this method differs from get_charset() which returns the Charset instance for the default encoding of the message body.

get_charsets(failobj=None)

Return a list containing the character set names in the message. If the message is a multipart, then the list will contain one element for each subpart in the payload, otherwise, it will be a list of length 1.

Each item in the list will be a string which is the value of the charset parameter in the Content-Type header for the represented subpart. However, if the subpart has no Content-Type header, no charset parameter, or is not of the text main MIME type, then that item in the returned list will be failobj.

get_content_disposition()

Return the lowercased value (without parameters) of the message’s Content-Disposition header if it has one, or None. The possible values for this method are inline, attachment or None if the message follows RFC 2183 [https://tools.ietf.org/html/rfc2183.html].

버전 3.5에 추가.

walk()

The walk() method is an all-purpose generator which can be used to iterate over all the parts and subparts of a message object tree, in depth-first traversal order. You will typically use walk() as the iterator in a for loop; each iteration returns the next subpart.

Here’s an example that prints the MIME type of every part of a multipart message structure:

>>> for part in msg.walk():
...     print(part.get_content_type())
multipart/report
text/plain
message/delivery-status
text/plain
text/plain
message/rfc822
text/plain

walk iterates over the subparts of any part where is_multipart() returns True, even though msg.get_content_maintype() == 'multipart' may return False. We can see this in our example by making use of the _structure debug helper function:

>>> for part in msg.walk():
...     print(part.get_content_maintype() == 'multipart',
...           part.is_multipart())
True True
False False
False True
False False
False False
False True
False False
>>> _structure(msg)
multipart/report
    text/plain
    message/delivery-status
        text/plain
        text/plain
    message/rfc822
        text/plain

Here the message parts are not multiparts, but they do contain subparts. is_multipart() returns True and walk descends into the subparts.

Message objects can also optionally contain two instance attributes, which can be used when generating the plain text of a MIME message.

preamble

The format of a MIME document allows for some text between the blank line following the headers, and the first multipart boundary string. Normally, this text is never visible in a MIME-aware mail reader because it falls outside the standard MIME armor. However, when viewing the raw text of the message, or when viewing the message in a non-MIME aware reader, this text can become visible.

The preamble attribute contains this leading extra-armor text for MIME documents. When the Parser discovers some text after the headers but before the first boundary string, it assigns this text to the message’s preamble attribute. When the Generator is writing out the plain text representation of a MIME message, and it finds the message has a preamble attribute, it will write this text in the area between the headers and the first boundary. See email.parser and email.generator for details.

Note that if the message object has no preamble, the preamble attribute will be None.

epilogue

The epilogue attribute acts the same way as the preamble attribute, except that it contains text that appears between the last boundary and the end of the message.

You do not need to set the epilogue to the empty string in order for the Generator to print a newline at the end of the file.

defects

The defects attribute contains a list of all the problems found when parsing this message. See email.errors for a detailed description of the possible parsing defects.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 데이터 처리 »

email — 전자 메일과 MIME 처리 패키지 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 데이터 처리 »

email — 전자 메일과 MIME 처리 패키지 »

|

email.mime: Creating email and MIME objects from scratch

Source code: Lib/email/mime/ [https://github.com/python/cpython/tree/3.7/Lib/email/mime/]

This module is part of the legacy (Compat32) email API. Its functionality is partially replaced by the contentmanager in the new API, but in certain applications these classes may still be useful, even in non-legacy code.

Ordinarily, you get a message object structure by passing a file or some text to a parser, which parses the text and returns the root message object. However you can also build a complete message structure from scratch, or even individual Message objects by hand. In fact, you can also take an existing structure and add new Message objects, move them around, etc. This makes a very convenient interface for slicing-and-dicing MIME messages.

You can create a new object structure by creating Message instances, adding attachments and all the appropriate headers manually. For MIME messages though, the email package provides some convenient subclasses to make things easier.

Here are the classes:

class email.mime.base.MIMEBase(_maintype, _subtype, *, policy=compat32, **_params)

Module: email.mime.base

This is the base class for all the MIME-specific subclasses of Message. Ordinarily you won’t create instances specifically of MIMEBase, although you could. MIMEBase is provided primarily as a convenient base class for more specific MIME-aware subclasses.

_maintype is the Content-Type major type (e.g. text or image), and _subtype is the Content-Type minor type (e.g. plain or gif). _params is a parameter key/value dictionary and is passed directly to Message.add_header.

If policy is specified, (defaults to the compat32 policy) it will be passed to Message.

The MIMEBase class always adds a Content-Type header (based on _maintype, _subtype, and _params), and a MIME-Version header (always set to 1.0).

버전 3.6에서 변경: Added policy keyword-only parameter.

class email.mime.nonmultipart.MIMENonMultipart

Module: email.mime.nonmultipart

A subclass of MIMEBase, this is an intermediate base class for MIME messages that are not multipart. The primary purpose of this class is to prevent the use of the attach() method, which only makes sense for multipart messages. If attach() is called, a MultipartConversionError exception is raised.

class email.mime.multipart.MIMEMultipart(_subtype='mixed', boundary=None, _subparts=None, *, policy=compat32, **_params)

Module: email.mime.multipart

A subclass of MIMEBase, this is an intermediate base class for MIME messages that are multipart. Optional _subtype defaults to mixed, but can be used to specify the subtype of the message. A Content-Type header of multipart/_subtype will be added to the message object. A MIME-Version header will also be added.

Optional boundary is the multipart boundary string. When None (the default), the boundary is calculated when needed (for example, when the message is serialized).

_subparts is a sequence of initial subparts for the payload. It must be possible to convert this sequence to a list. You can always attach new subparts to the message by using the Message.attach method.

Optional policy argument defaults to compat32.

Additional parameters for the Content-Type header are taken from the keyword arguments, or passed into the _params argument, which is a keyword dictionary.

버전 3.6에서 변경: Added policy keyword-only parameter.

class email.mime.application.MIMEApplication(_data, _subtype='octet-stream', _encoder=email.encoders.encode_base64, *, policy=compat32, **_params)

Module: email.mime.application

A subclass of MIMENonMultipart, the MIMEApplication class is used to represent MIME message objects of major type application. _data is a string containing the raw byte data. Optional _subtype specifies the MIME subtype and defaults to octet-stream.

Optional _encoder is a callable (i.e. function) which will perform the actual encoding of the data for transport. This callable takes one argument, which is the MIMEApplication instance. It should use get_payload() and set_payload() to change the payload to encoded form. It should also add any Content-Transfer-Encoding or other headers to the message object as necessary. The default encoding is base64. See the email.encoders module for a list of the built-in encoders.

Optional policy argument defaults to compat32.

_params are passed straight through to the base class constructor.

버전 3.6에서 변경: Added policy keyword-only parameter.

class email.mime.audio.MIMEAudio(_audiodata, _subtype=None, _encoder=email.encoders.encode_base64, *, policy=compat32, **_params)

Module: email.mime.audio

A subclass of MIMENonMultipart, the MIMEAudio class is used to create MIME message objects of major type audio. _audiodata is a string containing the raw audio data. If this data can be decoded by the standard Python module sndhdr, then the subtype will be automatically included in the Content-Type header. Otherwise you can explicitly specify the audio subtype via the _subtype argument. If the minor type could not be guessed and _subtype was not given, then TypeError is raised.

Optional _encoder is a callable (i.e. function) which will perform the actual encoding of the audio data for transport. This callable takes one argument, which is the MIMEAudio instance. It should use get_payload() and set_payload() to change the payload to encoded form. It should also add any Content-Transfer-Encoding or other headers to the message object as necessary. The default encoding is base64. See the email.encoders module for a list of the built-in encoders.

Optional policy argument defaults to compat32.

_params are passed straight through to the base class constructor.

버전 3.6에서 변경: Added policy keyword-only parameter.

class email.mime.image.MIMEImage(_imagedata, _subtype=None, _encoder=email.encoders.encode_base64, *, policy=compat32, **_params)

Module: email.mime.image

A subclass of MIMENonMultipart, the MIMEImage class is used to create MIME message objects of major type image. _imagedata is a string containing the raw image data. If this data can be decoded by the standard Python module imghdr, then the subtype will be automatically included in the Content-Type header. Otherwise you can explicitly specify the image subtype via the _subtype argument. If the minor type could not be guessed and _subtype was not given, then TypeError is raised.

Optional _encoder is a callable (i.e. function) which will perform the actual encoding of the image data for transport. This callable takes one argument, which is the MIMEImage instance. It should use get_payload() and set_payload() to change the payload to encoded form. It should also add any Content-Transfer-Encoding or other headers to the message object as necessary. The default encoding is base64. See the email.encoders module for a list of the built-in encoders.

Optional policy argument defaults to compat32.

_params are passed straight through to the MIMEBase constructor.

버전 3.6에서 변경: Added policy keyword-only parameter.

class email.mime.message.MIMEMessage(_msg, _subtype='rfc822', *, policy=compat32)

Module: email.mime.message

A subclass of MIMENonMultipart, the MIMEMessage class is used to create MIME objects of main type message. _msg is used as the payload, and must be an instance of class Message (or a subclass thereof), otherwise a TypeError is raised.

Optional _subtype sets the subtype of the message; it defaults to rfc822.

Optional policy argument defaults to compat32.

버전 3.6에서 변경: Added policy keyword-only parameter.

class email.mime.text.MIMEText(_text, _subtype='plain', _charset=None, *, policy=compat32)

Module: email.mime.text

A subclass of MIMENonMultipart, the MIMEText class is used to create MIME objects of major type text. _text is the string for the payload. _subtype is the minor type and defaults to plain. _charset is the character set of the text and is passed as an argument to the MIMENonMultipart constructor; it defaults to us-ascii if the string contains only ascii code points, and utf-8 otherwise. The _charset parameter accepts either a string or a Charset instance.

Unless the _charset argument is explicitly set to None, the MIMEText object created will have both a Content-Type header with a charset parameter, and a Content-Transfer-Encoding header. This means that a subsequent set_payload call will not result in an encoded payload, even if a charset is passed in the set_payload command. You can “reset” this behavior by deleting the Content-Transfer-Encoding header, after which a set_payload call will automatically encode the new payload (and add a new Content-Transfer-Encoding header).

Optional policy argument defaults to compat32.

버전 3.5에서 변경: _charset also accepts Charset instances.

버전 3.6에서 변경: Added policy keyword-only parameter.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 데이터 처리 »

email — 전자 메일과 MIME 처리 패키지 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 데이터 처리 »

email — 전자 메일과 MIME 처리 패키지 »

|

email.header: Internationalized headers

Source code: Lib/email/header.py [https://github.com/python/cpython/tree/3.7/Lib/email/header.py]

This module is part of the legacy (Compat32) email API. In the current API encoding and decoding of headers is handled transparently by the dictionary-like API of the EmailMessage class. In addition to uses in legacy code, this module can be useful in applications that need to completely control the character sets used when encoding headers.

The remaining text in this section is the original documentation of the module.

RFC 2822 [https://tools.ietf.org/html/rfc2822.html] is the base standard that describes the format of email messages. It derives from the older RFC 822 [https://tools.ietf.org/html/rfc822.html] standard which came into widespread use at a time when most email was composed of ASCII characters only. RFC 2822 [https://tools.ietf.org/html/rfc2822.html] is a specification written assuming email contains only 7-bit ASCII characters.

Of course, as email has been deployed worldwide, it has become internationalized, such that language specific character sets can now be used in email messages. The base standard still requires email messages to be transferred using only 7-bit ASCII characters, so a slew of RFCs have been written describing how to encode email containing non-ASCII characters into RFC 2822 [https://tools.ietf.org/html/rfc2822.html]-compliant format. These RFCs include RFC 2045 [https://tools.ietf.org/html/rfc2045.html], RFC 2046 [https://tools.ietf.org/html/rfc2046.html], RFC 2047 [https://tools.ietf.org/html/rfc2047.html], and RFC 2231 [https://tools.ietf.org/html/rfc2231.html]. The email package supports these standards in its email.header and email.charset modules.

If you want to include non-ASCII characters in your email headers, say in the Subject or To fields, you should use the Header class and assign the field in the Message object to an instance of Header instead of using a string for the header value. Import the Header class from the email.header module. For example:

>>> from email.message import Message
>>> from email.header import Header
>>> msg = Message()
>>> h = Header('p\xf6stal', 'iso-8859-1')
>>> msg['Subject'] = h
>>> msg.as_string()
'Subject: =?iso-8859-1?q?p=F6stal?=\n\n'

Notice here how we wanted the Subject field to contain a non-ASCII character? We did this by creating a Header instance and passing in the character set that the byte string was encoded in. When the subsequent Message instance was flattened, the Subject field was properly RFC 2047 [https://tools.ietf.org/html/rfc2047.html] encoded. MIME-aware mail readers would show this header using the embedded ISO-8859-1 character.

Here is the Header class description:

class email.header.Header(s=None, charset=None, maxlinelen=None, header_name=None, continuation_ws=' ', errors='strict')

Create a MIME-compliant header that can contain strings in different character sets.

Optional s is the initial header value. If None (the default), the initial header value is not set. You can later append to the header with append() method calls. s may be an instance of bytes or str, but see the append() documentation for semantics.

Optional charset serves two purposes: it has the same meaning as the charset argument to the append() method. It also sets the default character set for all subsequent append() calls that omit the charset argument. If charset is not provided in the constructor (the default), the us-ascii character set is used both as s’s initial charset and as the default for subsequent append() calls.

The maximum line length can be specified explicitly via maxlinelen. For splitting the first line to a shorter value (to account for the field header which isn’t included in s, e.g. Subject) pass in the name of the field in header_name. The default maxlinelen is 76, and the default value for header_name is None, meaning it is not taken into account for the first line of a long, split header.

Optional continuation_ws must be RFC 2822 [https://tools.ietf.org/html/rfc2822.html]-compliant folding whitespace, and is usually either a space or a hard tab character. This character will be prepended to continuation lines. continuation_ws defaults to a single space character.

Optional errors is passed straight through to the append() method.

append(s, charset=None, errors='strict')

Append the string s to the MIME header.

Optional charset, if given, should be a Charset instance (see email.charset) or the name of a character set, which will be converted to a Charset instance. A value of None (the default) means that the charset given in the constructor is used.

s may be an instance of bytes or str. If it is an instance of bytes, then charset is the encoding of that byte string, and a UnicodeError will be raised if the string cannot be decoded with that character set.

If s is an instance of str, then charset is a hint specifying the character set of the characters in the string.

In either case, when producing an RFC 2822 [https://tools.ietf.org/html/rfc2822.html]-compliant header using RFC 2047 [https://tools.ietf.org/html/rfc2047.html] rules, the string will be encoded using the output codec of the charset. If the string cannot be encoded using the output codec, a UnicodeError will be raised.

Optional errors is passed as the errors argument to the decode call if s is a byte string.

encode(splitchars=';, \t', maxlinelen=None, linesep='\n')

Encode a message header into an RFC-compliant format, possibly wrapping long lines and encapsulating non-ASCII parts in base64 or quoted-printable encodings.

Optional splitchars is a string containing characters which should be given extra weight by the splitting algorithm during normal header wrapping. This is in very rough support of RFC 2822 [https://tools.ietf.org/html/rfc2822.html]’s ‘higher level syntactic breaks’: split points preceded by a splitchar are preferred during line splitting, with the characters preferred in the order in which they appear in the string. Space and tab may be included in the string to indicate whether preference should be given to one over the other as a split point when other split chars do not appear in the line being split. Splitchars does not affect RFC 2047 [https://tools.ietf.org/html/rfc2047.html] encoded lines.

maxlinelen, if given, overrides the instance’s value for the maximum line length.

linesep specifies the characters used to separate the lines of the folded header. It defaults to the most useful value for Python application code (\n), but \r\n can be specified in order to produce headers with RFC-compliant line separators.

버전 3.2에서 변경: Added the linesep argument.

The Header class also provides a number of methods to support standard operators and built-in functions.

__str__()

Returns an approximation of the Header as a string, using an unlimited line length. All pieces are converted to unicode using the specified encoding and joined together appropriately. Any pieces with a charset of 'unknown-8bit' are decoded as ASCII using the 'replace' error handler.

버전 3.2에서 변경: Added handling for the 'unknown-8bit' charset.

__eq__(other)

This method allows you to compare two Header instances for equality.

__ne__(other)

This method allows you to compare two Header instances for inequality.

The email.header module also provides the following convenient functions.

email.header.decode_header(header)

Decode a message header value without converting the character set. The header value is in header.

This function returns a list of (decoded_string, charset) pairs containing each of the decoded parts of the header. charset is None for non-encoded parts of the header, otherwise a lower case string containing the name of the character set specified in the encoded string.

Here’s an example:

>>> from email.header import decode_header
>>> decode_header('=?iso-8859-1?q?p=F6stal?=')
[(b'p\xf6stal', 'iso-8859-1')]

email.header.make_header(decoded_seq, maxlinelen=None, header_name=None, continuation_ws=' ')

Create a Header instance from a sequence of pairs as returned by decode_header().

decode_header() takes a header value string and returns a sequence of pairs of the format (decoded_string, charset) where charset is the name of the character set.

This function takes one of those sequence of pairs and returns a Header instance. Optional maxlinelen, header_name, and continuation_ws are as in the Header constructor.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 데이터 처리 »

email — 전자 메일과 MIME 처리 패키지 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 데이터 처리 »

email — 전자 메일과 MIME 처리 패키지 »

|

email.charset: Representing character sets

Source code: Lib/email/charset.py [https://github.com/python/cpython/tree/3.7/Lib/email/charset.py]

This module is part of the legacy (Compat32) email API. In the new API only the aliases table is used.

The remaining text in this section is the original documentation of the module.

This module provides a class Charset for representing character sets and character set conversions in email messages, as well as a character set registry and several convenience methods for manipulating this registry. Instances of Charset are used in several other modules within the email package.

Import this class from the email.charset module.

class email.charset.Charset(input_charset=DEFAULT_CHARSET)

Map character sets to their email properties.

This class provides information about the requirements imposed on email for a specific character set. It also provides convenience routines for converting between character sets, given the availability of the applicable codecs. Given a character set, it will do its best to provide information on how to use that character set in an email message in an RFC-compliant way.

Certain character sets must be encoded with quoted-printable or base64 when used in email headers or bodies. Certain character sets must be converted outright, and are not allowed in email.

Optional input_charset is as described below; it is always coerced to lower case. After being alias normalized it is also used as a lookup into the registry of character sets to find out the header encoding, body encoding, and output conversion codec to be used for the character set. For example, if input_charset is iso-8859-1, then headers and bodies will be encoded using quoted-printable and no output conversion codec is necessary. If input_charset is euc-jp, then headers will be encoded with base64, bodies will not be encoded, but output text will be converted from the euc-jp character set to the iso-2022-jp character set.

Charset instances have the following data attributes:

input_charset

The initial character set specified. Common aliases are converted to their official email names (e.g. latin_1 is converted to iso-8859-1). Defaults to 7-bit us-ascii.

header_encoding

If the character set must be encoded before it can be used in an email header, this attribute will be set to Charset.QP (for quoted-printable), Charset.BASE64 (for base64 encoding), or Charset.SHORTEST for the shortest of QP or BASE64 encoding. Otherwise, it will be None.

body_encoding

Same as header_encoding, but describes the encoding for the mail message’s body, which indeed may be different than the header encoding. Charset.SHORTEST is not allowed for body_encoding.

output_charset

Some character sets must be converted before they can be used in email headers or bodies. If the input_charset is one of them, this attribute will contain the name of the character set output will be converted to. Otherwise, it will be None.

input_codec

The name of the Python codec used to convert the input_charset to Unicode. If no conversion codec is necessary, this attribute will be None.

output_codec

The name of the Python codec used to convert Unicode to the output_charset. If no conversion codec is necessary, this attribute will have the same value as the input_codec.

Charset instances also have the following methods:

get_body_encoding()

Return the content transfer encoding used for body encoding.

This is either the string quoted-printable or base64 depending on the encoding used, or it is a function, in which case you should call the function with a single argument, the Message object being encoded. The function should then set the Content-Transfer-Encoding header itself to whatever is appropriate.

Returns the string quoted-printable if body_encoding is QP, returns the string base64 if body_encoding is BASE64, and returns the string 7bit otherwise.

get_output_charset()

Return the output character set.

This is the output_charset attribute if that is not None, otherwise it is input_charset.

header_encode(string)

Header-encode the string string.

The type of encoding (base64 or quoted-printable) will be based on the header_encoding attribute.

header_encode_lines(string, maxlengths)

Header-encode a string by converting it first to bytes.

This is similar to header_encode() except that the string is fit into maximum line lengths as given by the argument maxlengths, which must be an iterator: each element returned from this iterator will provide the next maximum line length.

body_encode(string)

Body-encode the string string.

The type of encoding (base64 or quoted-printable) will be based on the body_encoding attribute.

The Charset class also provides a number of methods to support standard operations and built-in functions.

__str__()

Returns input_charset as a string coerced to lower case. __repr__() is an alias for __str__().

__eq__(other)

This method allows you to compare two Charset instances for equality.

__ne__(other)

This method allows you to compare two Charset instances for inequality.

The email.charset module also provides the following functions for adding new entries to the global character set, alias, and codec registries:

email.charset.add_charset(charset, header_enc=None, body_enc=None, output_charset=None)

Add character properties to the global registry.

charset is the input character set, and must be the canonical name of a character set.

Optional header_enc and body_enc is either Charset.QP for quoted-printable, Charset.BASE64 for base64 encoding, Charset.SHORTEST for the shortest of quoted-printable or base64 encoding, or None for no encoding. SHORTEST is only valid for header_enc. The default is None for no encoding.

Optional output_charset is the character set that the output should be in. Conversions will proceed from input charset, to Unicode, to the output charset when the method Charset.convert() is called. The default is to output in the same character set as the input.

Both input_charset and output_charset must have Unicode codec entries in the module’s character set-to-codec mapping; use add_codec() to add codecs the module does not know about. See the codecs module’s documentation for more information.

The global character set registry is kept in the module global dictionary CHARSETS.

email.charset.add_alias(alias, canonical)

Add a character set alias. alias is the alias name, e.g. latin-1. canonical is the character set’s canonical name, e.g. iso-8859-1.

The global charset alias registry is kept in the module global dictionary ALIASES.

email.charset.add_codec(charset, codecname)

Add a codec that map characters in the given character set to and from Unicode.

charset is the canonical name of a character set. codecname is the name of a Python codec, as appropriate for the second argument to the str’s encode() method.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 데이터 처리 »

email — 전자 메일과 MIME 처리 패키지 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 데이터 처리 »

email — 전자 메일과 MIME 처리 패키지 »

|

email.encoders: Encoders

Source code: Lib/email/encoders.py [https://github.com/python/cpython/tree/3.7/Lib/email/encoders.py]

This module is part of the legacy (Compat32) email API. In the new API the functionality is provided by the cte parameter of the set_content() method.

This module is deprecated in Python 3. The functions provided here should not be called explicitly since the MIMEText class sets the content type and CTE header using the _subtype and _charset values passed during the instaniation of that class.

The remaining text in this section is the original documentation of the module.

When creating Message objects from scratch, you often need to encode the payloads for transport through compliant mail servers. This is especially true for image/* and text/* type messages containing binary data.

The email package provides some convenient encodings in its encoders module. These encoders are actually used by the MIMEAudio and MIMEImage class constructors to provide default encodings. All encoder functions take exactly one argument, the message object to encode. They usually extract the payload, encode it, and reset the payload to this newly encoded value. They should also set the Content-Transfer-Encoding header as appropriate.

Note that these functions are not meaningful for a multipart message. They must be applied to individual subparts instead, and will raise a TypeError if passed a message whose type is multipart.

Here are the encoding functions provided:

email.encoders.encode_quopri(msg)

Encodes the payload into quoted-printable form and sets the Content-Transfer-Encoding header to quoted-printable 1. This is a good encoding to use when most of your payload is normal printable data, but contains a few unprintable characters.

email.encoders.encode_base64(msg)

Encodes the payload into base64 form and sets the Content-Transfer-Encoding header to base64. This is a good encoding to use when most of your payload is unprintable data since it is a more compact form than quoted-printable. The drawback of base64 encoding is that it renders the text non-human readable.

email.encoders.encode_7or8bit(msg)

This doesn’t actually modify the message’s payload, but it does set the Content-Transfer-Encoding header to either 7bit or 8bit as appropriate, based on the payload data.

email.encoders.encode_noop(msg)

This does nothing; it doesn’t even set the Content-Transfer-Encoding header.

Footnotes

1

Note that encoding with encode_quopri() also encodes all tabs and space characters in the data.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 데이터 처리 »

email — 전자 메일과 MIME 처리 패키지 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 데이터 처리 »

email — 전자 메일과 MIME 처리 패키지 »

|

email.utils: 기타 유틸리티

소스 코드: Lib/email/utils.py [https://github.com/python/cpython/tree/3.7/Lib/email/utils.py]

email.utils 모듈에서 제공되는 몇 가지 유용한 유틸리티가 있습니다:

email.utils.localtime(dt=None)

지역 시간을 어웨어 datetime 객체로 반환합니다. 인자 없이 호출되면, 현재 시각을 반환합니다. 그렇지 않으면 dt 인자가 datetime 인스턴스여야 하며, 시스템 시간대 데이터베이스에 따라 지역 시간대로 변환됩니다. dt가 나이브하면 (즉, dt.tzinfo가 None이면), 지역 시간으로 간주합니다. 이 경우, isdst에 대한 양수나 0 값은 localtime 이 지정된 시간에 서머 타임(예를 들어, 일광 절약 시간)이 유효한지 그렇지 않은지를 처음에 가정하게 합니다. isdst에 대한 음수 값은 localtime 이 서머 타임이 지정된 시간에 유효한지를 결정하게 합니다.

버전 3.3에 추가.

email.utils.make_msgid(idstring=None, domain=None)

RFC 2822 [https://tools.ietf.org/html/rfc2822.html]-준수 Message-ID 헤더에 적합한 문자열을 반환합니다. 선택적인 idstring이 주어지면, 메시지 id의 고유성을 강화하는 데 사용되는 문자열입니다. 선택적인 domain이 주어지면, msgid의 ‘@’ 다음 부분을 제공합니다. 기본값은 로컬 호스트 명입니다. 일반적으로 이 기본값을 재정의할 필요는 없지만, 여러 호스트에 걸쳐 일관된 도메인 이름을 사용하는 분산 시스템을 구성하는 경우와 같이 특정 경우에 유용할 수 있습니다.

버전 3.2에서 변경: domain 키워드가 추가되었습니다.

나머지 함수는 레거시 (Compat32) email API의 일부입니다. 이것들이 제공하는 구문 분석과 포매팅은 새 API의 헤더 구문 분석 장치가 자동으로 수행하므로, 새 API에서 이것들을 직접 사용할 필요는 없습니다.

email.utils.quote(str)

str에 있는 역 슬래시를 두 개의 역 슬래시로 대체하고, 큰따옴표는 역 슬래시-큰따옴표로 대체한 새 문자열을 반환합니다.

email.utils.unquote(str)

str의 unquote 된 버전인 새 문자열을 반환합니다. str가 큰따옴표로 끝나고 시작하면, 큰따옴표가 제거됩니다. 마찬가지로 str이 화살괄호(angle brackets)로 끝나고 시작하면, 제거됩니다.

email.utils.parseaddr(address)

address(To나 Cc와 같은 주소를 포함하는 필드의 값이어야 합니다)를 realname과 email 주소 구성 요소로 구문 분석합니다. 구문 분석에 실패하지 않는 한 해당 정보의 튜플을 반환합니다. 실패하면 ('', '')의 2-튜플이 반환됩니다.

email.utils.formataddr(pair, charset='utf-8')

parseaddr()의 역, (realname, email_address) 형식의 2-튜플을 취해 To나 Cc 헤더에 적합한 문자열 값을 반환합니다. pair의 첫 번째 요소가 거짓이면, 두 번째 요소는 수정되지 않은 채 반환됩니다.

선택적 charset은 realname에 비 ASCII 문자가 포함되어있을 때 realname의 RFC 2047 [https://tools.ietf.org/html/rfc2047.html] 인코딩에 사용될 문자 집합입니다. str이나 Charset의 인스턴스가 될 수 있습니다. 기본값은 utf-8입니다.

버전 3.3에서 변경: charset 옵션이 추가되었습니다.

email.utils.getaddresses(fieldvalues)

이 메서드는 parseaddr()에 의해 반환된 형식의 2-튜플 리스트를 반환합니다. fieldvalues는 Message.get_all에 의해 반환될 수 있는 헤더 필드 값의 시퀀스입니다. 다음은 메시지의 모든 수신자를 얻는 간단한 예입니다:

from email.utils import getaddresses

tos = msg.get_all('to', [])
ccs = msg.get_all('cc', [])
resent_tos = msg.get_all('resent-to', [])
resent_ccs = msg.get_all('resent-cc', [])
all_recipients = getaddresses(tos + ccs + resent_tos + resent_ccs)

email.utils.parsedate(date)

RFC 2822 [https://tools.ietf.org/html/rfc2822.html]의 규칙에 따라 날짜를 구문 분석하려고 시도합니다. 그러나, 일부 메일러는 지정된 대로 이 형식을 따르지 않으므로 parsedate()는 이러한 경우에 올바르게 추측하려고 합니다. date는 RFC 2822 [https://tools.ietf.org/html/rfc2822.html] 날짜를 포함하는 문자열입니다 (가령 "Mon, 20 Nov 1995 19:12:08 -0500"). 날짜 구문 분석에 성공하면, parsedate()는 time.mktime()에 직접 전달할 수 있는 9-튜플을 반환합니다; 그렇지 않으면, None을 반환합니다. 결과 튜플의 인덱스 6, 7 및 8은 사용할 수 없음에 유의하십시오.

email.utils.parsedate_tz(date)

Performs the same function as parsedate(), but returns either None or a 10-tuple; the first 9 elements make up a tuple that can be passed directly to time.mktime(), and the tenth is the offset of the date’s timezone from UTC (which is the official term for Greenwich Mean Time) 1. If the input string has no timezone, the last element of the tuple returned is 0, which represents UTC. Note that indexes 6, 7, and 8 of the result tuple are not usable.

email.utils.parsedate_to_datetime(date)

format_datetime()의 역. parsedate()와 같은 기능을 수행하지만, 성공 시에 datetime을 반환합니다. 입력 date의 시간대가 -0000이면, datetime은 나이브 datetime이 되고, date가 RFC를 준수하면 UTC로 시간이 표시되지만, date가 온 메시지의 실제 소스 시간대는 표시되지 않습니다. 입력 date에 다른 유효한 시간대 오프셋이 있으면, datetime은 해당 timezone tzinfo가 있는 어웨어 datetime이 됩니다.

버전 3.3에 추가.

email.utils.mktime_tz(tuple)

parsedate_tz()에 의해 반환된 10-튜플을 UTC 타임스탬프(Epoch 이후 초)로 바꿉니다. 튜플의 시간대 항목이 None이면, 지역 시간으로 간주합니다.

email.utils.formatdate(timeval=None, localtime=False, usegmt=False)

RFC 2822 [https://tools.ietf.org/html/rfc2822.html]에 따르는 날짜 문자열을 반환합니다, 예를 들어:

Fri, 09 Nov 2001 01:08:47 -0000

선택적 timeval이 주어지면 time.gmtime()과 time.localtime()이 받아들이는 부동 소수점 시간 값입니다, 그렇지 않으면 현재 시각이 사용됩니다.

선택적 localtime 은, True일 때, timeval을 해석하고, UTC 대신 일광 절약 시간을 적절히 고려하는 지역 시간대에 상대적인 날짜를 반환토록 하는 플래그입니다. 기본값은 UTC가 사용된다는 뜻인 False입니다.

선택적 usegmt는, True일 때, 날짜 문자열의 시간대를 숫자 -0000 대신 ASCII 문자열 GMT로 출력하도록 하는 플래그입니다. 일부 프로토콜(가령 HTTP)에 필요합니다. 이것은 localtime 이 False일 때만 적용됩니다. 기본값은 False입니다.

email.utils.format_datetime(dt, usegmt=False)

formatdate와 같지만, 입력이 datetime 인스턴스입니다. 나이브 datetime이면, “소스 시간대에 대한 정보가 없는 UTC”로 간주하며, 관습적으로 -0000이 시간대로 사용됩니다. 어웨어 datetime이면, 숫자 시간대 오프셋이 사용됩니다. 오프셋이 0인 어웨어 시간대면, usegmt를 True로 설정해서 GMT 문자열을 숫자 시간대 오프셋 대신 사용할 수 있습니다. 이것은 표준을 준수하는 HTTP date 헤더를 생성하는 방법을 제공합니다.

버전 3.3에 추가.

email.utils.decode_rfc2231(s)

RFC 2231 [https://tools.ietf.org/html/rfc2231.html]에 따라 s 문자열을 디코드합니다.

email.utils.encode_rfc2231(s, charset=None, language=None)

RFC 2231 [https://tools.ietf.org/html/rfc2231.html]에 따라 s 문자열을 인코드합니다. 선택적인 charset과 language가 주어지면, 사용할 문자 집합 이름과 언어 이름입니다. 둘 다 지정되지 않으면, s가 그대로 반환됩니다. charset이 주어졌지만, language가 지정되지 않으면, 문자열은 language에 대해 빈 문자열을 사용하여 인코딩됩니다.

email.utils.collapse_rfc2231_value(value, errors='replace', fallback_charset='us-ascii')

header 매개 변수가 RFC 2231 [https://tools.ietf.org/html/rfc2231.html]로 인코딩되었을 때, Message.get_param은 문자 집합, 언어 및 값이 포함된 3-튜플을 반환할 수 있습니다. collapse_rfc2231_value()는 이것을 유니코드 문자열로 변환합니다. 선택적 errors는 str의 encode() 메서드의 errors 인자로 전달됩니다; 기본값은 'replace'입니다. 선택적 fallback_charset은 RFC 2231 [https://tools.ietf.org/html/rfc2231.html] 헤더에 있는 것이 파이썬에 알려지지 않았을 때 사용할 문자 집합을 지정합니다; 기본값은 'us-ascii'입니다.

편의상, collapse_rfc2231_value()에 전달된 value가 튜플이 아니면, 문자열이어야 하고 unquote 되어 반환됩니다.

email.utils.decode_params(params)

RFC 2231 [https://tools.ietf.org/html/rfc2231.html]에 따라 매개 변수 리스트를 디코드합니다. params는 (content-type, string-value) 형식의 요소를 포함하는 2-튜플의 시퀀스입니다.

각주

1

시간대 오프셋의 부호는 같은 시간대에 대한 time.timezone 변수의 부호와 반대임에 유의하십시오; 이 모듈이 RFC 2822 [https://tools.ietf.org/html/rfc2822.html]를 따르지만, 후자의 변수는 POSIX 표준을 따릅니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 데이터 처리 »

email — 전자 메일과 MIME 처리 패키지 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 데이터 처리 »

email — 전자 메일과 MIME 처리 패키지 »

|

email.iterators: 이터레이터

소스 코드: Lib/email/iterators.py [https://github.com/python/cpython/tree/3.7/Lib/email/iterators.py]

메시지 객체 트리를 이터레이트 하는 것은 Message.walk 메서드를 사용하면 매우 쉽습니다. email.iterators 모듈은 메시지 객체 트리에 대한 유용한 고수준 이터레이션을 제공합니다.

email.iterators.body_line_iterator(msg, decode=False)

msg의 모든 서브 파트에 있는 모든 페이 로드를 이터레이트 하여, 문자열 페이 로드를 한 줄씩 반환합니다. 모든 서브 파트 헤더를 건너뛰고, 파이썬 문자열이 아닌 페이 로드가 있는 서브 파트를 건너뜁니다. 이는 readline()을 사용하여 파일에서 메시지의 평평한(flat) 텍스트 표현을 읽는 것과 다소 유사하며, 모든 중간 헤더를 건너뜁니다.

선택적 decode는 Message.get_payload로 전달됩니다.

email.iterators.typed_subpart_iterator(msg, maintype='text', subtype=None)

msg의 모든 서브 파트를 이터레이트 하여, maintype과 subtype으로 지정된 MIME 유형과 일치하는 서브 파트만 반환합니다.

subtype은 선택적임에 유의하십시오; 생략하면, 서브 파트 MIME 형식 일치는 메인 형식으로만 수행됩니다. maintype도 선택적입니다; 기본값은 text입니다.

따라서, 기본적으로 typed_subpart_iterator()는 MIME 유형이 text/* 인 각 서브 파트를 반환합니다.

유용한 디버깅 도구로 다음 함수가 추가되었습니다. 이것은 패키지에서 지원되는 공용 인터페이스의 일부로 간주하지 않아야 합니다.

email.iterators._structure(msg, fp=None, level=0, include_default=False)

메시지 객체 구조의 콘텐츠 유형을 들여쓰기하여 인쇄합니다. 예를 들면:

>>> msg = email.message_from_file(somefile)
>>> _structure(msg)
multipart/mixed
    text/plain
    text/plain
    multipart/digest
        message/rfc822
            text/plain
        message/rfc822
            text/plain
        message/rfc822
            text/plain
        message/rfc822
            text/plain
        message/rfc822
            text/plain
    text/plain

선택적 fp는 출력을 인쇄할 파일류 객체입니다. 파이썬의 print() 함수에 적합해야 합니다. level은 내부적으로 사용됩니다. include_default가 참이면, 기본 유형도 인쇄합니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 데이터 처리 »

email — 전자 메일과 MIME 처리 패키지 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 데이터 처리 »

|

json — JSON 인코더와 디코더

소스 코드: Lib/json/__init__.py [https://github.com/python/cpython/tree/3.7/Lib/json/__init__.py]

RFC 7159 [https://tools.ietf.org/html/rfc7159.html](RFC 4627 [https://tools.ietf.org/html/rfc4627.html]을 대체합니다)와 ECMA-404 [http://www.ecma-international.org/publications/standards/Ecma-404.htm]로 규정되는 JSON (JavaScript Object Notation) [http://json.org]은 JavaScript [https://en.wikipedia.org/wiki/JavaScript] 객체 리터럴 문법에서 영감을 얻은 경량 데이터 교환 형식입니다 (JavaScript 1의 엄격한 부분집합은 아닙니다).

경고

Be cautious when parsing JSON data from untrusted sources. A malicious JSON string may cause the decoder to consume considerable CPU and memory resources. Limiting the size of data to be parsed is recommended.

json은 표준 라이브러리 marshal과 pickle 모듈 사용자에게 익숙한 API를 제공합니다.

기본 파이썬 객체 계층 구조 인코딩:

>>> import json
>>> json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])
'["foo", {"bar": ["baz", null, 1.0, 2]}]'
>>> print(json.dumps("\"foo\bar"))
"\"foo\bar"
>>> print(json.dumps('\u1234'))
"\u1234"
>>> print(json.dumps('\\'))
"\\"
>>> print(json.dumps({"c": 0, "b": 0, "a": 0}, sort_keys=True))
{"a": 0, "b": 0, "c": 0}
>>> from io import StringIO
>>> io = StringIO()
>>> json.dump(['streaming API'], io)
>>> io.getvalue()
'["streaming API"]'

간결한 인코딩:

>>> import json
>>> json.dumps([1, 2, 3, {'4': 5, '6': 7}], separators=(',', ':'))
'[1,2,3,{"4":5,"6":7}]'

예쁜 인쇄:

>>> import json
>>> print(json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4))
{
    "4": 5,
    "6": 7
}

JSON 디코딩:

>>> import json
>>> json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]')
['foo', {'bar': ['baz', None, 1.0, 2]}]
>>> json.loads('"\\"foo\\bar"')
'"foo\x08ar'
>>> from io import StringIO
>>> io = StringIO('["streaming API"]')
>>> json.load(io)
['streaming API']

JSON 객체 디코딩 특수화:

>>> import json
>>> def as_complex(dct):
...     if '__complex__' in dct:
...         return complex(dct['real'], dct['imag'])
...     return dct
...
>>> json.loads('{"__complex__": true, "real": 1, "imag": 2}',
...     object_hook=as_complex)
(1+2j)
>>> import decimal
>>> json.loads('1.1', parse_float=decimal.Decimal)
Decimal('1.1')

JSONEncoder 확장하기:

>>> import json
>>> class ComplexEncoder(json.JSONEncoder):
...     def default(self, obj):
...         if isinstance(obj, complex):
...             return [obj.real, obj.imag]
...         # Let the base class default method raise the TypeError
...         return json.JSONEncoder.default(self, obj)
...
>>> json.dumps(2 + 1j, cls=ComplexEncoder)
'[2.0, 1.0]'
>>> ComplexEncoder().encode(2 + 1j)
'[2.0, 1.0]'
>>> list(ComplexEncoder().iterencode(2 + 1j))
['[2.0', ', 1.0', ']']

셸에서 json.tool을 사용하여 유효성을 검사하고 예쁘게 인쇄합니다:

$ echo '{"json":"obj"}' | python -m json.tool
{
    "json": "obj"
}
$ echo '{1.2:3.4}' | python -m json.tool
Expecting property name enclosed in double quotes: line 1 column 2 (char 1)

자세한 설명은 명령 줄 인터페이스를 참조하십시오.

참고

JSON은 YAML [http://yaml.org/] 1.2의 부분 집합입니다. 이 모듈의 기본 설정(특히 기본 separators 값)으로 생성된 JSON은 YAML 1.0과 1.1의 부분 집합이기도 합니다. 따라서 이 모듈을 YAML 직렬화기로 사용할 수도 있습니다.

기본 사용법

json.dump(obj, fp, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)

이 변환표를 사용하여 obj를 JSON 형식 스트림으로 fp(.write()를 지원하는 파일류 객체)로 직렬화합니다.

skipkeys가 참이면 (기본값: False), 기본형(str, int, float, bool, None)이 아닌 딕셔너리 키는 TypeError를 발생시키는 대신 건너뜁니다.

json 모듈은 항상 bytes 객체가 아니라 str 객체를 생성합니다. 따라서, fp.write()는 str 입력을 지원해야 합니다.

ensure_ascii가 참(기본값)이면, 출력에서 모든 비 ASCII 문자가 이스케이프 되도록 보장됩니다. ensure_ascii가 거짓이면, 그 문자들은 있는 그대로 출력됩니다.

check_circular가 거짓이면 (기본값: True), 컨테이너형에 대한 순환 참조 검사를 건너뛰고 순환 참조는 OverflowError를 일으킵니다 (또는 더 나빠질 수 있습니다).

allow_nan이 거짓이면 (기본값: True), JSON 사양을 엄격히 준수하여 범위를 벗어난 float 값(nan, inf, -inf)을 직렬화하면 ValueError를 일으킵니다. allow_nan이 참이면, JavaScript의 대응 물(NaN, Infinity, -Infinity)이 사용됩니다.

indent가 음이 아닌 정수나 문자열이면, JSON 배열 요소와 오브젝트 멤버가 해당 들여쓰기 수준으로 예쁘게 인쇄됩니다. 0, 음수 또는 ""의 들여쓰기 수준은 줄 넘김만 삽입합니다. None(기본값)은 가장 간결한(compact) 표현을 선택합니다. 양의 정수 indent를 사용하면, 수준 당 그만큼의 스페이스로 들여쓰기합니다. indent가 문자열이면 (가령 "\t"), 각 수준을 들려 쓰는 데 그 문자열을 사용합니다.

버전 3.2에서 변경: indent에 정수뿐만 아니라 문자열을 허용합니다.

지정되면, separators는 (item_separator, key_separator) 튜플이어야 합니다. 기본값은 indent가 None이면 (', ', ': ')이고, 그렇지 않으면 (',', ': ')입니다. 가장 간결한 JSON 표현을 얻으려면, (',', ':')를 지정하여 공백을 제거해야 합니다.

버전 3.4에서 변경: indent가 None이 아니면, (',', ': ')를 기본값으로 사용합니다.

지정되면, default는 달리 직렬화할 수 없는 객체에 대해 호출되는 함수여야 합니다. 객체의 JSON 인코딩 가능한 버전을 반환하거나 TypeError를 발생시켜야 합니다. 지정하지 않으면, TypeError가 발생합니다.

sort_keys가 참이면 (기본값: False), 딕셔너리의 출력이 키로 정렬됩니다.

사용자 정의 JSONEncoder 서브 클래스(예를 들어, default() 메서드를 재정의하여 추가 형을 직렬화하는 것)를 사용하려면, cls 키워드 인자로 지정하십시오; 그렇지 않으면 JSONEncoder가 사용됩니다.

버전 3.6에서 변경: 모든 선택적 매개 변수는 이제 키워드-전용입니다.

참고

pickle과 marshal과 달리, JSON은 프레임 프로토콜이 아니므로 같은 fp를 사용하여 dump()를 반복 호출하여 여러 객체를 직렬화하려고 하면 잘못된 JSON 파일이 생성됩니다.

json.dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)

이 변환표를 사용하여 obj를 JSON 형식의 str로 직렬화합니다. 인자는 dump()에서와 같은 의미입니다.

참고

JSON의 키/값 쌍에 있는 키는 항상 str 형입니다. 딕셔너리를 JSON으로 변환하면, 딕셔너리의 모든 키가 문자열로 강제 변환됩니다. 이것의 결과로, 딕셔너리를 JSON으로 변환한 다음 다시 딕셔너리로 변환하면, 딕셔너리가 원래의 것과 같지 않을 수 있습니다. 즉, x에 비 문자열 키가 있으면 loads(dumps(x)) != x입니다.

json.load(fp, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)

이 변환표를 사용하여 fp(JSON 문서를 포함하는 .read()를 지원하는 텍스트 파일이나 바이너리 파일)를 파이썬 객체로 역 직렬화합니다.

object_hook은 모든 오브젝트 리터럴의 디코딩된 결과(dict)로 호출되는 선택적 함수입니다. object_hook의 반환 값이 dict 대신에 사용됩니다. 이 기능은 사용자 정의 디코더를 구현하는 데 사용할 수 있습니다 (예를 들어, JSON-RPC [http://www.jsonrpc.org] 클래스 힌팅(class hinting)).

object_pairs_hook은 모든 오브젝트 리터럴의 쌍의 순서 있는 목록으로 디코딩된 결과로 호출되는 선택적 함수입니다. dict 대신 object_pairs_hook의 반환 값이 사용됩니다. 이 기능은 사용자 정의 디코더를 구현하는 데 사용할 수 있습니다. object_hook도 정의되어 있으면, object_pairs_hook이 우선순위를 갖습니다.

버전 3.1에서 변경: object_pairs_hook에 대한 지원이 추가되었습니다.

parse_float가 지정되면, 디코딩될 모든 JSON float의 문자열로 호출됩니다. 기본적으로, 이것은 float(num_str)와 동등합니다. JSON float에 대해 다른 데이터형이나 구문 분석기를 사용하고자 할 때 사용될 수 있습니다 (예를 들어, decimal.Decimal).

parse_int가 지정되면, 디코딩될 모든 JSON int의 문자열로 호출됩니다. 기본적으로 이것은 int(num_str)와 동등합니다. JSON 정수에 대해 다른 데이터형이나 구문 분석기를 사용하고자 할 때 사용될 수 있습니다 (예를 들어 float).

버전 3.7.14에서 변경: The default parse_int of int() now limits the maximum length of the integer string via the interpreter’s integer string conversion length limitation to help avoid denial of service attacks.

parse_constant가 지정되면, 다음과 같은 문자열 중 하나로 호출됩니다: '-Infinity', 'Infinity', 'NaN'. 잘못된 JSON 숫자를 만날 때 예외를 발생시키는 데 사용할 수 있습니다.

버전 3.1에서 변경: parse_constant는 더는 ‘null’, ‘true’, ‘false’에 대해 호출되지 않습니다.

사용자 정의 JSONDecoder 서브 클래스를 사용하려면, cls 키워드 인자로 지정하십시오; 그렇지 않으면 JSONDecoder가 사용됩니다. 추가 키워드 인자는 클래스 생성자에 전달됩니다.

역 직렬화되는 데이터가 유효한 JSON 문서가 아니면, JSONDecodeError가 발생합니다.

버전 3.6에서 변경: 모든 선택적 매개 변수는 이제 키워드-전용입니다.

버전 3.6에서 변경: fp는 이제 바이너리 파일이 될 수 있습니다. 입력 인코딩은 UTF-8, UTF-16 또는 UTF-32 여야 합니다.

json.loads(s, *, encoding=None, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)

이 변환표를 사용하여 s(JSON 문서를 포함하는 str, bytes 또는 bytearray 인스턴스)를 파이썬 객체로 역 직렬화합니다.

무시되고 폐지된 encoding을 제외하고는, 다른 인자는 load()와 같은 의미를 가집니다.

역 직렬화되는 데이터가 유효한 JSON 문서가 아니면, JSONDecodeError가 발생합니다.

버전 3.6에서 변경: s는 이제 bytes나 bytearray 형일 수 있습니다. 입력 인코딩은 UTF-8, UTF-16 또는 UTF-32 여야 합니다.

인코더와 디코더

class json.JSONDecoder(*, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, strict=True, object_pairs_hook=None)

간단한 JSON 디코더.

기본적으로 디코딩할 때 다음과 같은 변환을 수행합니다:

JSON

파이썬

오브젝트(object)

dict

배열(array)

list

문자열(string)

str

숫자 (정수)

int

숫자 (실수)

float

true

True

false

False

null

None

또한, NaN, Infinity 및 -Infinity를 해당 float 값으로 이해합니다. 이 값은 JSON 명세에 속하지 않습니다.

object_hook이 지정되면, 모든 JSON 오브젝트의 디코딩된 결과로 호출되며, 반환 값을 주어진 dict 대신 사용합니다. 사용자 정의 역 직렬화를 제공하는 데 사용할 수 있습니다 (예를 들어, JSON-RPC 클래스 힌팅을 지원하기 위해).

object_pairs_hook이 지정되면 모든 오브젝트 리터럴의 쌍의 순서 있는 목록으로 디코딩된 결과로 호출됩니다. dict 대신 object_pairs_hook의 반환 값이 사용됩니다. 이 기능은 사용자 정의 디코더를 구현하는 데 사용할 수 있습니다. object_hook도 정의되어 있으면, object_pairs_hook이 우선순위를 갖습니다.

버전 3.1에서 변경: object_pairs_hook에 대한 지원이 추가되었습니다.

parse_float가 지정되면, 디코딩될 모든 JSON float의 문자열로 호출됩니다. 기본적으로, 이것은 float(num_str)와 동등합니다. JSON float에 대해 다른 데이터형이나 구문 분석기를 사용하고자 할 때 사용될 수 있습니다 (예를 들어, decimal.Decimal).

parse_int가 지정되면, 디코딩될 모든 JSON int의 문자열로 호출됩니다. 기본적으로 이것은 int(num_str)와 동등합니다. JSON 정수에 대해 다른 데이터형이나 구문 분석기를 사용하고자 할 때 사용될 수 있습니다 (예를 들어 float).

parse_constant가 지정되면, 다음과 같은 문자열 중 하나로 호출됩니다: '-Infinity', 'Infinity', 'NaN'. 잘못된 JSON 숫자를 만날 때 예외를 발생시키는 데 사용할 수 있습니다.

strict가 거짓이면 (True가 기본값입니다), 문자열 안에 제어 문자가 허용됩니다. 이 문맥에서 제어 문자는 0–31 범위의 문자 코드를 가진 것들인데, '\t' (탭), '\n', '\r' 및 '\0'을 포함합니다.

역 직렬화되는 데이터가 유효한 JSON 문서가 아니면, JSONDecodeError가 발생합니다.

버전 3.6에서 변경: 모든 매개 변수가 이제 키워드-전용입니다.

decode(s)

s(JSON 문서가 포함된 str 인스턴스)의 파이썬 표현을 반환합니다.

주어진 JSON 문서가 유효하지 않으면 JSONDecodeError가 발생합니다.

raw_decode(s)

s(JSON 문서로 시작하는 str)에서 JSON 문서를 디코딩하고, 파이썬 표현과 문서가 끝난 s에서의 인덱스로 구성된 2-튜플을 반환합니다.

끝에 여분의 데이터가 있을 수 있는 문자열에서 JSON 문서를 디코딩하는 데 사용할 수 있습니다.

class json.JSONEncoder(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)

파이썬 데이터 구조를 위한 확장 가능한 JSON 인코더

기본적으로 다음 객체와 형을 지원합니다.:

파이썬

JSON

dict

오브젝트(object)

list, tuple

배열(array)

str

문자열(string)

int, float, int와 float에서 파생된 열거형

숫자(number)

True

true

False

false

None

null

버전 3.4에서 변경: int와 float 파생 Enum 클래스에 대한 지원이 추가되었습니다.

다른 객체를 인식하도록 확장하려면, 서브 클래스를 만들고, 가능하면 o에 대한 직렬화 가능 객체를 반환하고, 그렇지 않으면 (TypeError를 발생시키기 위해) 슈퍼 클래스 구현을 호출하는 다른 메서드로 default() 메서드를 구현합니다.

skipkeys가 거짓(기본값)이면, str, int, float 또는 None이 아닌 키의 인코딩을 시도하는 것은 TypeError입니다. skipkeys가 참이면 이러한 항목은 단순히 건너뜁니다.

ensure_ascii가 참(기본값)이면, 출력에서 모든 비 ASCII 문자가 이스케이프 되도록 보장됩니다. ensure_ascii가 거짓이면, 그 문자들은 있는 그대로 출력됩니다.

check_circular가 참(기본값)이면, 리스트, 딕셔너리 및 사용자 정의 객체는 무한 재귀 (OverflowError를 유발할 수 있습니다)를 방지하기 위해 인코딩 중에 순환 참조를 검사합니다. 그렇지 않으면, 그러한 검사가 수행되지 않습니다.

allow_nan이 참(기본값)이면, NaN, Infinity 및 -Infinity는 그 자체로 인코딩됩니다. 이 동작은 JSON 사양을 따르지 않지만, 대부분의 JavaScript 기반 인코더 및 디코더와 일치합니다. 그렇지 않으면, 그러한 float를 인코딩하는 것은 ValueError가 됩니다.

sort_keys가 참(기본값: False)이면, 딕셔너리의 출력이 키로 정렬됩니다; JSON 직렬화를 이전과 비교할 수 있도록 해서 회귀 테스트에 유용합니다.

indent가 음이 아닌 정수나 문자열이면, JSON 배열 요소와 오브젝트 멤버가 해당 들여쓰기 수준으로 예쁘게 인쇄됩니다. 0, 음수 또는 ""의 들여쓰기 수준은 줄 넘김만 삽입합니다. None(기본값)은 가장 간결한(compact) 표현을 선택합니다. 양의 정수 indent를 사용하면, 수준 당 그만큼의 스페이스로 들여쓰기합니다. indent가 문자열이면 (가령 "\t"), 각 수준을 들려 쓰는 데 그 문자열을 사용합니다.

버전 3.2에서 변경: indent에 정수뿐만 아니라 문자열을 허용합니다.

지정되면, separators는 (item_separator, key_separator) 튜플이어야 합니다. 기본값은 indent가 None이면 (', ', ': ')이고, 그렇지 않으면 (',', ': ')입니다. 가장 간결한 JSON 표현을 얻으려면, (',', ':')를 지정하여 공백을 제거해야 합니다.

버전 3.4에서 변경: indent가 None이 아니면, (',', ': ')를 기본값으로 사용합니다.

지정되면, default는 달리 직렬화할 수 없는 객체에 대해 호출되는 함수여야 합니다. 객체의 JSON 인코딩 가능한 버전을 반환하거나 TypeError를 발생시켜야 합니다. 지정하지 않으면, TypeError가 발생합니다.

버전 3.6에서 변경: 모든 매개 변수가 이제 키워드-전용입니다.

default(o)

o의 직렬화 가능 객체를 반환하거나 (TypeError를 발생시키기 위해서) 베이스 구현을 호출하도록 세비 클래스에 이 메서드를 구현하십시오.

예를 들어, 임의의 이터레이터를 지원하려면, 다음과 같이 default를 구현할 수 있습니다:

def default(self, o):
   try:
       iterable = iter(o)
   except TypeError:
       pass
   else:
       return list(iterable)
   # Let the base class default method raise the TypeError
   return json.JSONEncoder.default(self, o)

encode(o)

파이썬 데이터 구조 o의 JSON 문자열 표현을 반환합니다. 예를 들면:

>>> json.JSONEncoder().encode({"foo": ["bar", "baz"]})
'{"foo": ["bar", "baz"]}'

iterencode(o)

주어진 객체 o를 인코딩하고, 준비될 때마다 각 문자열 표현을 산출(yield)합니다. 예를 들면:

for chunk in json.JSONEncoder().iterencode(bigobject):
    mysocket.write(chunk)

예외

exception json.JSONDecodeError(msg, doc, pos)

다음 추가 어트리뷰트가 있는 ValueError의 서브 클래스:

msg

형식 없는 에러 메시지.

doc

구문 분석 중인 JSON 문서.

pos

구문 분석에 실패한 위치의 시작 부분을 나타내는 doc의 인덱스.

lineno

pos에 해당하는 줄.

colno

pos에 해당하는 열.

버전 3.5에 추가.

표준 준수와 상호 운용성

JSON 형식은 RFC 7159 [https://tools.ietf.org/html/rfc7159.html]와 ECMA-404 [http://www.ecma-international.org/publications/standards/Ecma-404.htm]에 의해 지정됩니다. 이 절에서는 이 모듈의 RFC 준수 수준에 대해 자세히 설명합니다. 단순화를 위해, JSONEncoder 및 JSONDecoder 서브 클래스와 명시적으로 언급되지 않은 매개 변수는 고려되지 않습니다.

유효한 JavaScript이지만 유효한 JSON이 아닌 확장을 구현함으로써, 이 모듈은 엄격한 방식으로 RFC를 준수하지는 않습니다. 특히:

무한대와 NaN 숫자 값이 받아들여지고 출력됩니다;

오브젝트 내에서 반복되는 이름이 허용되고, 마지막 이름-값 쌍의 값만 사용됩니다.

RFC가 RFC를 준수하는 구문 분석기가 RFC를 준수하지 않는 입력 텍스트를 받아들이도록 허용하기 때문에, 이 모듈의 역 직렬화기는 기본 설정에서 기술적으로 RFC를 준수합니다.

문자 인코딩

RFC는 UTF-8, UTF-16 또는 UTF-32를 사용하여 JSON을 표현할 것을 요구하고, 최대 상호 운용성을 위해 권장되는 기본값은 UTF-8입니다.

RFC에 의해 요구되는 것은 아니지만 허용되기 때문에, 이 모듈의 직렬화기는 기본적으로 ensure_ascii=True를 설정하므로, 결과 문자열에 ASCII 문자만 포함되도록 출력을 이스케이핑 합니다.

ensure_ascii 매개 변수 외에도, 이 모듈은 파이썬 객체와 유니코드 문자열 사이의 변환으로 엄격하게 정의되어 있으므로, 문자 인코딩 문제를 직접 다루지 않습니다.

RFC는 JSON 텍스트의 시작 부분에 바이트 순서 표시(BOM)를 추가하는 것을 금지하고 있으며, 이 모듈의 직렬화기는 BOM을 출력에 추가하지 않습니다. RFC는 JSON 역 직렬화기가 입력에서 초기 BOM을 무시하는 것을 허용하지만 요구하지는 않습니다. 이 모듈의 역 직렬화기는 초기 BOM이 있을 때 ValueError를 발생시킵니다.

RFC는 유효한 유니코드 문자에 해당하지 않는 바이트 시퀀스(예를 들어, 쌍을 이루지 않은 UTF-16 대리 코드(unpaired UTF-16 surrogates))가 포함된 JSON 문자열을 명시적으로 금지하지 않지만, 상호 운용성 문제를 일으킬 수 있다고 지적하고 있습니다. 기본적으로, 이 모듈은 이러한 시퀀스의 코드 포인트를 받아들이고 (원래 str에 있을 때) 출력합니다.

무한대와 NaN 숫자 값

RFC는 무한대나 NaN 숫자 값의 표현을 허용하지 않습니다. 그런데도, 기본적으로, 이 모듈은 유효한 JSON 숫자 리터럴 값인 것처럼 Infinity, -Infinity 및 NaN을 받아들이고 출력합니다:

>>> # Neither of these calls raises an exception, but the results are not valid JSON
>>> json.dumps(float('-inf'))
'-Infinity'
>>> json.dumps(float('nan'))
'NaN'
>>> # Same when deserializing
>>> json.loads('-Infinity')
-inf
>>> json.loads('NaN')
nan

직렬화기에서, allow_nan 매개 변수를 사용하여 이 동작을 변경할 수 있습니다. 역 직렬화기에서, parse_constant 매개 변수를 사용하여 이 동작을 변경할 수 있습니다.

오브젝트 내에서 반복된 이름

RFC는 JSON 오브젝트 내에서 이름이 고유해야 한다고 지정하지만, JSON 오브젝트 내에서 반복되는 이름을 처리하는 방법을 지정하지는 않습니다. 기본적으로, 이 모듈은 예외를 발생시키지 않습니다; 대신, 주어진 이름에 대한 마지막 이름-값 쌍을 제외한 모든 것을 무시합니다:

>>> weird_json = '{"x": 1, "x": 2, "x": 3}'
>>> json.loads(weird_json)
{'x': 3}

object_pairs_hook 매개 변수는 이 동작을 변경하는 데 사용할 수 있습니다.

오브젝트나 배열이 아닌 최상윗값

폐지된 RFC 4627 [https://tools.ietf.org/html/rfc4627.html]에 의해 지정된 이전 버전의 JSON은 JSON 텍스트의 최상윗값이 JSON 오브젝트나 배열(파이썬 dict나 list)이어야 하고, JSON null, 불리언, 숫자 또는 문자열 값이 될 수 없다고 요구합니다. RFC 7159 [https://tools.ietf.org/html/rfc7159.html]는 그 제한을 제거했으며, 이 모듈은 직렬화기와 역 직렬화기에서 이러한 제한을 구현하지 않으며, 그런 적도 없습니다.

이와 관계없이, 최대한의 상호 운용성을 위해, 여러분은 자발적으로 제한을 준수하기를 원할 수 있습니다.

구현 제약 사항

일부 JSON 역 직렬화기 구현은 다음과 같은 것들에 대한 제한을 설정할 수 있습니다:

받아들인 JSON 텍스트의 크기

JSON 오브젝트와 배열의 최대 중첩 수준

JSON 숫자의 범위와 정밀도

JSON 문자열의 내용과 최대 길이

이 모듈은 관련 파이썬 데이터형 자체나 파이썬 인터프리터 자체의 한계 외에는 어떤 제한도 가하지 않습니다.

JSON으로 직렬화할 때, 여러분의 JSON을 사용할 응용 프로그램에 있는 이러한 제한 사항에 주의하십시오. 특히, JSON 숫자가 IEEE 754 배정도 숫자로 역 직렬화되는 것이 일반적이고, 그래서 그 표현의 범위와 정밀도 제한이 적용됩니다. 이것은 매우 큰 규모의 파이썬 int 값을 직렬화하거나, decimal.Decimal과 같은 “색다른” 숫자 형의 인스턴스를 직렬화할 때 특히 중요합니다.

명령 줄 인터페이스

소스 코드: Lib/json/tool.py [https://github.com/python/cpython/tree/3.7/Lib/json/tool.py]

json.tool 모듈은 JSON 객체의 유효성을 검사하고 예쁘게 인쇄하는 간단한 명령 줄 인터페이스를 제공합니다.

선택적 infile과 outfile 인자가 지정되지 않으면, 각각 sys.stdin과 sys.stdout이 사용됩니다:

$ echo '{"json": "obj"}' | python -m json.tool
{
    "json": "obj"
}
$ echo '{1.2:3.4}' | python -m json.tool
Expecting property name enclosed in double quotes: line 1 column 2 (char 1)

버전 3.5에서 변경: 출력은 이제 입력과 같은 순서입니다. 딕셔너리의 출력을 키에 대해 알파벳 순으로 정렬하려면 --sort-keys 옵션을 사용하십시오.

명령 줄 옵션

infile

유효성을 검사하거나 예쁘게 인쇄할 JSON 파일:

$ python -m json.tool mp_films.json
[
    {
        "title": "And Now for Something Completely Different",
        "year": 1971
    },
    {
        "title": "Monty Python and the Holy Grail",
        "year": 1975
    }
]

infile이 지정되지 않으면, sys.stdin에서 읽습니다.

outfile

infile의 출력을 지정된 outfile에 씁니다. 그렇지 않으면, sys.stdout에 씁니다.

--sort-keys

딕셔너리의 출력을 키에 대해 알파벳 순으로 정렬합니다.

버전 3.5에 추가.

-h, --help

도움말 메시지를 표시합니다.

각주

1

the errata for RFC 7159 [https://www.rfc-editor.org/errata_search.php?rfc=7159]에서 언급했듯이, JSON은 문자열에 U+2028(LINE SEPARATOR)과 U+2029(PARAGRAPH SEPARATOR) 문자를 허용하지만, JavaScript(ECMAScript Edition 5.1 기준)는 허용하지 않습니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 데이터 처리 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 데이터 처리 »

|

mailcap — Mailcap 파일 처리

소스 코드: Lib/mailcap.py [https://github.com/python/cpython/tree/3.7/Lib/mailcap.py]

Mailcap 파일은 메일 리더와 웹 브라우저와 같은 MIME 인식 응용 프로그램이 MIME 형식의 파일에 따라 반응하는 방식을 구성하는 데 사용됩니다. (“mailcap” 이라는 이름은 “mail capability” 라는 구문에서 왔습니다.) 예를 들어, mailcap 파일에는 video/mpeg; xmpeg %s와 같은 줄이 있을 수 있습니다. 그러면, 사용자가 MIME 유형이 video/mpeg 인 전자 메일 메시지 또는 웹 문서를 만나면, %s가 파일명(대개 임시 파일에 속한 파일)으로 치환되고 xmpeg 프로그램을 자동으로 시작하여 파일을 볼 수 있습니다.

The mailcap format is documented in RFC 1524 [https://tools.ietf.org/html/rfc1524.html], “A User Agent Configuration Mechanism For Multimedia Mail Format Information”, but is not an Internet standard. However, mailcap files are supported on most Unix systems.

mailcap.findmatch(caps, MIMEtype, key='view', filename='/dev/null', plist=[])

2-튜플을 반환합니다; 첫 번째 요소는 실행될 명령 줄(os.system()에 전달될 수 있음)을 포함하는 문자열이고, 두 번째 요소는 지정된 MIME 유형에 대한 mailcap 항목입니다. 일치하는 MIME 유형을 찾을 수 없으면 (None, None)이 반환됩니다.

key는 원하는 이름인데, 수행할 활동의 유형을 나타냅니다; 가장 흔히 MIME 형식의 데이터 본문을 보고만 싶으므로 기본값은 ‘view’ 입니다. 주어진 MIME 유형의 새 본문을 만들거나 기존 본문 데이터를 변경하려고 할 때, 다른 가능한 값으로 ‘compose’ 이나 ‘edit’ 가 있습니다. 이 필드의 전체 목록은 RFC 1524 [https://tools.ietf.org/html/rfc1524.html]를 참조하십시오.

filename은 명령 줄에서 %s에 치환될 파일명입니다. 기본값은 '/dev/null' 이지만, 거의 확실하게 원하는 것이 아닐 것이기 때문에, 보통 파일명을 지정하여 이를 대체합니다.

plist는 이름있는 매개 변수를 포함하는 리스트일 수 있습니다; 기본값은 단순히 빈 리스트입니다. 리스트의 각 항목은 매개 변수 이름, 등호('=') 및 매개 변수의 값이 포함된 문자열이어야 합니다. Mailcap 항목은 %{foo}와 같은 이름있는 매개 변수를 포함할 수 있는데, ‘foo’ 라는 이름의 매개 변수의 값으로 치환됩니다. 예를 들어, 명령 줄 showpartial %{id} %{number} %{total}이 mailcap 파일에 있고, plist가 ['id=1', 'number=2', 'total=3']로 설정되었으면, 결과 명령 줄은 'showpartial 1 2 3'가 됩니다.

mailcap 파일에서, “test” 필드를 선택적으로 지정하여 mailcap 줄이 적용되는지를 판단하기 위해 일부 외부 조건(가령 기계 아키텍처나 사용 중인 윈도우 시스템)을 검사할 수 있습니다. findmatch()는 자동으로 그러한 조건을 검사하고 검사가 실패하면 항목을 건너뜁니다.

버전 3.7.16에서 변경: To prevent security issues with shell metacharacters (symbols that have special effects in a shell command line), findmatch will refuse to inject ASCII characters other than alphanumerics and @+=:,./-_ into the returned command line.

If a disallowed character appears in filename, findmatch will always return (None, None) as if no entry was found. If such a character appears elsewhere (a value in plist or in MIMEtype), findmatch will ignore all mailcap entries which use that value. A warning will be raised in either case.

mailcap.getcaps()

MIME 유형을 mailcap 파일 항목 리스트에 매핑하는 딕셔너리를 반환합니다. 이 딕셔너리는 findmatch() 함수에 전달되어야 합니다. 항목은 딕셔너리의 리스트로 저장되지만, 이 표현의 세부 사항을 알 필요는 없습니다.

이 정보는 시스템에서 발견된 모든 mailcap 파일에서 파생됩니다. 사용자의 mailcap 파일 $HOME/.mailcap의 설정은 시스템 mailcap 파일 /etc/mailcap, /usr/etc/mailcap 및 /usr/local/etc/mailcap의 설정보다 우선합니다.

사용 예:

>>> import mailcap
>>> d = mailcap.getcaps()
>>> mailcap.findmatch(d, 'video/mpeg', filename='tmp1223')
('xmpeg tmp1223', {'view': 'xmpeg %s'})

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 데이터 처리 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 데이터 처리 »

|

mailbox — Manipulate mailboxes in various formats

Source code: Lib/mailbox.py [https://github.com/python/cpython/tree/3.7/Lib/mailbox.py]

This module defines two classes, Mailbox and Message, for accessing and manipulating on-disk mailboxes and the messages they contain. Mailbox offers a dictionary-like mapping from keys to messages. Message extends the email.message module’s Message class with format-specific state and behavior. Supported mailbox formats are Maildir, mbox, MH, Babyl, and MMDF.

더 보기

Module email

Represent and manipulate messages.

Mailbox objects

class mailbox.Mailbox

A mailbox, which may be inspected and modified.

The Mailbox class defines an interface and is not intended to be instantiated. Instead, format-specific subclasses should inherit from Mailbox and your code should instantiate a particular subclass.

The Mailbox interface is dictionary-like, with small keys corresponding to messages. Keys are issued by the Mailbox instance with which they will be used and are only meaningful to that Mailbox instance. A key continues to identify a message even if the corresponding message is modified, such as by replacing it with another message.

Messages may be added to a Mailbox instance using the set-like method add() and removed using a del statement or the set-like methods remove() and discard().

Mailbox interface semantics differ from dictionary semantics in some noteworthy ways. Each time a message is requested, a new representation (typically a Message instance) is generated based upon the current state of the mailbox. Similarly, when a message is added to a Mailbox instance, the provided message representation’s contents are copied. In neither case is a reference to the message representation kept by the Mailbox instance.

The default Mailbox iterator iterates over message representations, not keys as the default dictionary iterator does. Moreover, modification of a mailbox during iteration is safe and well-defined. Messages added to the mailbox after an iterator is created will not be seen by the iterator. Messages removed from the mailbox before the iterator yields them will be silently skipped, though using a key from an iterator may result in a KeyError exception if the corresponding message is subsequently removed.

경고

Be very cautious when modifying mailboxes that might be simultaneously changed by some other process. The safest mailbox format to use for such tasks is Maildir; try to avoid using single-file formats such as mbox for concurrent writing. If you’re modifying a mailbox, you must lock it by calling the lock() and unlock() methods before reading any messages in the file or making any changes by adding or deleting a message. Failing to lock the mailbox runs the risk of losing messages or corrupting the entire mailbox.

Mailbox instances have the following methods:

add(message)

Add message to the mailbox and return the key that has been assigned to it.

Parameter message may be a Message instance, an email.message.Message instance, a string, a byte string, or a file-like object (which should be open in binary mode). If message is an instance of the appropriate format-specific Message subclass (e.g., if it’s an mboxMessage instance and this is an mbox instance), its format-specific information is used. Otherwise, reasonable defaults for format-specific information are used.

버전 3.2에서 변경: Support for binary input was added.

remove(key)

__delitem__(key)

discard(key)

Delete the message corresponding to key from the mailbox.

If no such message exists, a KeyError exception is raised if the method was called as remove() or __delitem__() but no exception is raised if the method was called as discard(). The behavior of discard() may be preferred if the underlying mailbox format supports concurrent modification by other processes.

__setitem__(key, message)

Replace the message corresponding to key with message. Raise a KeyError exception if no message already corresponds to key.

As with add(), parameter message may be a Message instance, an email.message.Message instance, a string, a byte string, or a file-like object (which should be open in binary mode). If message is an instance of the appropriate format-specific Message subclass (e.g., if it’s an mboxMessage instance and this is an mbox instance), its format-specific information is used. Otherwise, the format-specific information of the message that currently corresponds to key is left unchanged.

iterkeys()

keys()

Return an iterator over all keys if called as iterkeys() or return a list of keys if called as keys().

itervalues()

__iter__()

values()

Return an iterator over representations of all messages if called as itervalues() or __iter__() or return a list of such representations if called as values(). The messages are represented as instances of the appropriate format-specific Message subclass unless a custom message factory was specified when the Mailbox instance was initialized.

참고

The behavior of __iter__() is unlike that of dictionaries, which iterate over keys.

iteritems()

items()

Return an iterator over (key, message) pairs, where key is a key and message is a message representation, if called as iteritems() or return a list of such pairs if called as items(). The messages are represented as instances of the appropriate format-specific Message subclass unless a custom message factory was specified when the Mailbox instance was initialized.

get(key, default=None)

__getitem__(key)

Return a representation of the message corresponding to key. If no such message exists, default is returned if the method was called as get() and a KeyError exception is raised if the method was called as __getitem__(). The message is represented as an instance of the appropriate format-specific Message subclass unless a custom message factory was specified when the Mailbox instance was initialized.

get_message(key)

Return a representation of the message corresponding to key as an instance of the appropriate format-specific Message subclass, or raise a KeyError exception if no such message exists.

get_bytes(key)

Return a byte representation of the message corresponding to key, or raise a KeyError exception if no such message exists.

버전 3.2에 추가.

get_string(key)

Return a string representation of the message corresponding to key, or raise a KeyError exception if no such message exists. The message is processed through email.message.Message to convert it to a 7bit clean representation.

get_file(key)

Return a file-like representation of the message corresponding to key, or raise a KeyError exception if no such message exists. The file-like object behaves as if open in binary mode. This file should be closed once it is no longer needed.

버전 3.2에서 변경: The file object really is a binary file; previously it was incorrectly returned in text mode. Also, the file-like object now supports the context management protocol: you can use a with statement to automatically close it.

참고

Unlike other representations of messages, file-like representations are not necessarily independent of the Mailbox instance that created them or of the underlying mailbox. More specific documentation is provided by each subclass.

__contains__(key)

Return True if key corresponds to a message, False otherwise.

__len__()

Return a count of messages in the mailbox.

clear()

Delete all messages from the mailbox.

pop(key, default=None)

Return a representation of the message corresponding to key and delete the message. If no such message exists, return default. The message is represented as an instance of the appropriate format-specific Message subclass unless a custom message factory was specified when the Mailbox instance was initialized.

popitem()

Return an arbitrary (key, message) pair, where key is a key and message is a message representation, and delete the corresponding message. If the mailbox is empty, raise a KeyError exception. The message is represented as an instance of the appropriate format-specific Message subclass unless a custom message factory was specified when the Mailbox instance was initialized.

update(arg)

Parameter arg should be a key-to-message mapping or an iterable of (key, message) pairs. Updates the mailbox so that, for each given key and message, the message corresponding to key is set to message as if by using __setitem__(). As with __setitem__(), each key must already correspond to a message in the mailbox or else a KeyError exception will be raised, so in general it is incorrect for arg to be a Mailbox instance.

참고

Unlike with dictionaries, keyword arguments are not supported.

flush()

Write any pending changes to the filesystem. For some Mailbox subclasses, changes are always written immediately and flush() does nothing, but you should still make a habit of calling this method.

lock()

Acquire an exclusive advisory lock on the mailbox so that other processes know not to modify it. An ExternalClashError is raised if the lock is not available. The particular locking mechanisms used depend upon the mailbox format. You should always lock the mailbox before making any modifications to its contents.

unlock()

Release the lock on the mailbox, if any.

close()

Flush the mailbox, unlock it if necessary, and close any open files. For some Mailbox subclasses, this method does nothing.

Maildir

class mailbox.Maildir(dirname, factory=None, create=True)

A subclass of Mailbox for mailboxes in Maildir format. Parameter factory is a callable object that accepts a file-like message representation (which behaves as if opened in binary mode) and returns a custom representation. If factory is None, MaildirMessage is used as the default message representation. If create is True, the mailbox is created if it does not exist.

If create is True and the dirname path exists, it will be treated as an existing maildir without attempting to verify its directory layout.

It is for historical reasons that dirname is named as such rather than path.

Maildir is a directory-based mailbox format invented for the qmail mail transfer agent and now widely supported by other programs. Messages in a Maildir mailbox are stored in separate files within a common directory structure. This design allows Maildir mailboxes to be accessed and modified by multiple unrelated programs without data corruption, so file locking is unnecessary.

Maildir mailboxes contain three subdirectories, namely: tmp, new, and cur. Messages are created momentarily in the tmp subdirectory and then moved to the new subdirectory to finalize delivery. A mail user agent may subsequently move the message to the cur subdirectory and store information about the state of the message in a special “info” section appended to its file name.

Folders of the style introduced by the Courier mail transfer agent are also supported. Any subdirectory of the main mailbox is considered a folder if '.' is the first character in its name. Folder names are represented by Maildir without the leading '.'. Each folder is itself a Maildir mailbox but should not contain other folders. Instead, a logical nesting is indicated using '.' to delimit levels, e.g., “Archived.2005.07”.

참고

The Maildir specification requires the use of a colon (':') in certain message file names. However, some operating systems do not permit this character in file names, If you wish to use a Maildir-like format on such an operating system, you should specify another character to use instead. The exclamation point ('!') is a popular choice. For example:

import mailbox
mailbox.Maildir.colon = '!'

The colon attribute may also be set on a per-instance basis.

Maildir instances have all of the methods of Mailbox in addition to the following:

list_folders()

Return a list of the names of all folders.

get_folder(folder)

Return a Maildir instance representing the folder whose name is folder. A NoSuchMailboxError exception is raised if the folder does not exist.

add_folder(folder)

Create a folder whose name is folder and return a Maildir instance representing it.

remove_folder(folder)

Delete the folder whose name is folder. If the folder contains any messages, a NotEmptyError exception will be raised and the folder will not be deleted.

clean()

Delete temporary files from the mailbox that have not been accessed in the last 36 hours. The Maildir specification says that mail-reading programs should do this occasionally.

Some Mailbox methods implemented by Maildir deserve special remarks:

add(message)

__setitem__(key, message)

update(arg)

경고

These methods generate unique file names based upon the current process ID. When using multiple threads, undetected name clashes may occur and cause corruption of the mailbox unless threads are coordinated to avoid using these methods to manipulate the same mailbox simultaneously.

flush()

All changes to Maildir mailboxes are immediately applied, so this method does nothing.

lock()

unlock()

Maildir mailboxes do not support (or require) locking, so these methods do nothing.

close()

Maildir instances do not keep any open files and the underlying mailboxes do not support locking, so this method does nothing.

get_file(key)

Depending upon the host platform, it may not be possible to modify or remove the underlying message while the returned file remains open.

더 보기

maildir man page from qmail [http://www.qmail.org/man/man5/maildir.html]

The original specification of the format.

Using maildir format [https://cr.yp.to/proto/maildir.html]

Notes on Maildir by its inventor. Includes an updated name-creation scheme and details on “info” semantics.

maildir man page from Courier [http://www.courier-mta.org/maildir.html]

Another specification of the format. Describes a common extension for supporting folders.

mbox

class mailbox.mbox(path, factory=None, create=True)

A subclass of Mailbox for mailboxes in mbox format. Parameter factory is a callable object that accepts a file-like message representation (which behaves as if opened in binary mode) and returns a custom representation. If factory is None, mboxMessage is used as the default message representation. If create is True, the mailbox is created if it does not exist.

The mbox format is the classic format for storing mail on Unix systems. All messages in an mbox mailbox are stored in a single file with the beginning of each message indicated by a line whose first five characters are “From “.

Several variations of the mbox format exist to address perceived shortcomings in the original. In the interest of compatibility, mbox implements the original format, which is sometimes referred to as mboxo. This means that the Content-Length header, if present, is ignored and that any occurrences of “From ” at the beginning of a line in a message body are transformed to “>From ” when storing the message, although occurrences of “>From ” are not transformed to “From ” when reading the message.

Some Mailbox methods implemented by mbox deserve special remarks:

get_file(key)

Using the file after calling flush() or close() on the mbox instance may yield unpredictable results or raise an exception.

lock()

unlock()

Three locking mechanisms are used—dot locking and, if available, the flock() and lockf() system calls.

더 보기

mbox man page from qmail [http://www.qmail.org/man/man5/mbox.html]

A specification of the format and its variations.

mbox man page from tin [http://www.tin.org/bin/man.cgi?section=5&topic=mbox]

Another specification of the format, with details on locking.

Configuring Netscape Mail on Unix: Why The Content-Length Format is Bad [https://www.jwz.org/doc/content-length.html]

An argument for using the original mbox format rather than a variation.

“mbox” is a family of several mutually incompatible mailbox formats [https://www.loc.gov/preservation/digital/formats/fdd/fdd000383.shtml]

A history of mbox variations.

MH

class mailbox.MH(path, factory=None, create=True)

A subclass of Mailbox for mailboxes in MH format. Parameter factory is a callable object that accepts a file-like message representation (which behaves as if opened in binary mode) and returns a custom representation. If factory is None, MHMessage is used as the default message representation. If create is True, the mailbox is created if it does not exist.

MH is a directory-based mailbox format invented for the MH Message Handling System, a mail user agent. Each message in an MH mailbox resides in its own file. An MH mailbox may contain other MH mailboxes (called folders) in addition to messages. Folders may be nested indefinitely. MH mailboxes also support sequences, which are named lists used to logically group messages without moving them to sub-folders. Sequences are defined in a file called .mh_sequences in each folder.

The MH class manipulates MH mailboxes, but it does not attempt to emulate all of mh’s behaviors. In particular, it does not modify and is not affected by the context or .mh_profile files that are used by mh to store its state and configuration.

MH instances have all of the methods of Mailbox in addition to the following:

list_folders()

Return a list of the names of all folders.

get_folder(folder)

Return an MH instance representing the folder whose name is folder. A NoSuchMailboxError exception is raised if the folder does not exist.

add_folder(folder)

Create a folder whose name is folder and return an MH instance representing it.

remove_folder(folder)

Delete the folder whose name is folder. If the folder contains any messages, a NotEmptyError exception will be raised and the folder will not be deleted.

get_sequences()

Return a dictionary of sequence names mapped to key lists. If there are no sequences, the empty dictionary is returned.

set_sequences(sequences)

Re-define the sequences that exist in the mailbox based upon sequences, a dictionary of names mapped to key lists, like returned by get_sequences().

pack()

Rename messages in the mailbox as necessary to eliminate gaps in numbering. Entries in the sequences list are updated correspondingly.

참고

Already-issued keys are invalidated by this operation and should not be subsequently used.

Some Mailbox methods implemented by MH deserve special remarks:

remove(key)

__delitem__(key)

discard(key)

These methods immediately delete the message. The MH convention of marking a message for deletion by prepending a comma to its name is not used.

lock()

unlock()

Three locking mechanisms are used—dot locking and, if available, the flock() and lockf() system calls. For MH mailboxes, locking the mailbox means locking the .mh_sequences file and, only for the duration of any operations that affect them, locking individual message files.

get_file(key)

Depending upon the host platform, it may not be possible to remove the underlying message while the returned file remains open.

flush()

All changes to MH mailboxes are immediately applied, so this method does nothing.

close()

MH instances do not keep any open files, so this method is equivalent to unlock().

더 보기

nmh - Message Handling System [http://www.nongnu.org/nmh/]

Home page of nmh, an updated version of the original mh.

MH & nmh: Email for Users & Programmers [https://rand-mh.sourceforge.io/book/]

A GPL-licensed book on mh and nmh, with some information on the mailbox format.

Babyl

class mailbox.Babyl(path, factory=None, create=True)

A subclass of Mailbox for mailboxes in Babyl format. Parameter factory is a callable object that accepts a file-like message representation (which behaves as if opened in binary mode) and returns a custom representation. If factory is None, BabylMessage is used as the default message representation. If create is True, the mailbox is created if it does not exist.

Babyl is a single-file mailbox format used by the Rmail mail user agent included with Emacs. The beginning of a message is indicated by a line containing the two characters Control-Underscore ('\037') and Control-L ('\014'). The end of a message is indicated by the start of the next message or, in the case of the last message, a line containing a Control-Underscore ('\037') character.

Messages in a Babyl mailbox have two sets of headers, original headers and so-called visible headers. Visible headers are typically a subset of the original headers that have been reformatted or abridged to be more attractive. Each message in a Babyl mailbox also has an accompanying list of labels, or short strings that record extra information about the message, and a list of all user-defined labels found in the mailbox is kept in the Babyl options section.

Babyl instances have all of the methods of Mailbox in addition to the following:

get_labels()

Return a list of the names of all user-defined labels used in the mailbox.

참고

The actual messages are inspected to determine which labels exist in the mailbox rather than consulting the list of labels in the Babyl options section, but the Babyl section is updated whenever the mailbox is modified.

Some Mailbox methods implemented by Babyl deserve special remarks:

get_file(key)

In Babyl mailboxes, the headers of a message are not stored contiguously with the body of the message. To generate a file-like representation, the headers and body are copied together into an io.BytesIO instance, which has an API identical to that of a file. As a result, the file-like object is truly independent of the underlying mailbox but does not save memory compared to a string representation.

lock()

unlock()

Three locking mechanisms are used—dot locking and, if available, the flock() and lockf() system calls.

더 보기

Format of Version 5 Babyl Files [https://quimby.gnus.org/notes/BABYL]

A specification of the Babyl format.

Reading Mail with Rmail [https://www.gnu.org/software/emacs/manual/html_node/emacs/Rmail.html]

The Rmail manual, with some information on Babyl semantics.

MMDF

class mailbox.MMDF(path, factory=None, create=True)

A subclass of Mailbox for mailboxes in MMDF format. Parameter factory is a callable object that accepts a file-like message representation (which behaves as if opened in binary mode) and returns a custom representation. If factory is None, MMDFMessage is used as the default message representation. If create is True, the mailbox is created if it does not exist.

MMDF is a single-file mailbox format invented for the Multichannel Memorandum Distribution Facility, a mail transfer agent. Each message is in the same form as an mbox message but is bracketed before and after by lines containing four Control-A ('\001') characters. As with the mbox format, the beginning of each message is indicated by a line whose first five characters are “From “, but additional occurrences of “From ” are not transformed to “>From ” when storing messages because the extra message separator lines prevent mistaking such occurrences for the starts of subsequent messages.

Some Mailbox methods implemented by MMDF deserve special remarks:

get_file(key)

Using the file after calling flush() or close() on the MMDF instance may yield unpredictable results or raise an exception.

lock()

unlock()

Three locking mechanisms are used—dot locking and, if available, the flock() and lockf() system calls.

더 보기

mmdf man page from tin [http://www.tin.org/bin/man.cgi?section=5&topic=mmdf]

A specification of MMDF format from the documentation of tin, a newsreader.

MMDF [https://en.wikipedia.org/wiki/MMDF]

A Wikipedia article describing the Multichannel Memorandum Distribution Facility.

Message objects

class mailbox.Message(message=None)

A subclass of the email.message module’s Message. Subclasses of mailbox.Message add mailbox-format-specific state and behavior.

If message is omitted, the new instance is created in a default, empty state. If message is an email.message.Message instance, its contents are copied; furthermore, any format-specific information is converted insofar as possible if message is a Message instance. If message is a string, a byte string, or a file, it should contain an RFC 2822 [https://tools.ietf.org/html/rfc2822.html]-compliant message, which is read and parsed. Files should be open in binary mode, but text mode files are accepted for backward compatibility.

The format-specific state and behaviors offered by subclasses vary, but in general it is only the properties that are not specific to a particular mailbox that are supported (although presumably the properties are specific to a particular mailbox format). For example, file offsets for single-file mailbox formats and file names for directory-based mailbox formats are not retained, because they are only applicable to the original mailbox. But state such as whether a message has been read by the user or marked as important is retained, because it applies to the message itself.

There is no requirement that Message instances be used to represent messages retrieved using Mailbox instances. In some situations, the time and memory required to generate Message representations might not be acceptable. For such situations, Mailbox instances also offer string and file-like representations, and a custom message factory may be specified when a Mailbox instance is initialized.

MaildirMessage

class mailbox.MaildirMessage(message=None)

A message with Maildir-specific behaviors. Parameter message has the same meaning as with the Message constructor.

Typically, a mail user agent application moves all of the messages in the new subdirectory to the cur subdirectory after the first time the user opens and closes the mailbox, recording that the messages are old whether or not they’ve actually been read. Each message in cur has an “info” section added to its file name to store information about its state. (Some mail readers may also add an “info” section to messages in new.) The “info” section may take one of two forms: it may contain “2,” followed by a list of standardized flags (e.g., “2,FR”) or it may contain “1,” followed by so-called experimental information. Standard flags for Maildir messages are as follows:

Flag

Meaning

Explanation

D

Draft

Under composition

F

Flagged

Marked as important

P

Passed

Forwarded, resent, or bounced

R

Replied

Replied to

S

Seen

Read

T

Trashed

Marked for subsequent deletion

MaildirMessage instances offer the following methods:

get_subdir()

Return either “new” (if the message should be stored in the new subdirectory) or “cur” (if the message should be stored in the cur subdirectory).

참고

A message is typically moved from new to cur after its mailbox has been accessed, whether or not the message is has been read. A message msg has been read if "S" in msg.get_flags() is True.

set_subdir(subdir)

Set the subdirectory the message should be stored in. Parameter subdir must be either “new” or “cur”.

get_flags()

Return a string specifying the flags that are currently set. If the message complies with the standard Maildir format, the result is the concatenation in alphabetical order of zero or one occurrence of each of 'D', 'F', 'P', 'R', 'S', and 'T'. The empty string is returned if no flags are set or if “info” contains experimental semantics.

set_flags(flags)

Set the flags specified by flags and unset all others.

add_flag(flag)

Set the flag(s) specified by flag without changing other flags. To add more than one flag at a time, flag may be a string of more than one character. The current “info” is overwritten whether or not it contains experimental information rather than flags.

remove_flag(flag)

Unset the flag(s) specified by flag without changing other flags. To remove more than one flag at a time, flag maybe a string of more than one character. If “info” contains experimental information rather than flags, the current “info” is not modified.

get_date()

Return the delivery date of the message as a floating-point number representing seconds since the epoch.

set_date(date)

Set the delivery date of the message to date, a floating-point number representing seconds since the epoch.

get_info()

Return a string containing the “info” for a message. This is useful for accessing and modifying “info” that is experimental (i.e., not a list of flags).

set_info(info)

Set “info” to info, which should be a string.

When a MaildirMessage instance is created based upon an mboxMessage or MMDFMessage instance, the Status and X-Status headers are omitted and the following conversions take place:

Resulting state

mboxMessage or MMDFMessage state

“cur” subdirectory

O flag

F flag

F flag

R flag

A flag

S flag

R flag

T flag

D flag

When a MaildirMessage instance is created based upon an MHMessage instance, the following conversions take place:

Resulting state

MHMessage state

“cur” subdirectory

“unseen” sequence

“cur” subdirectory and S flag

no “unseen” sequence

F flag

“flagged” sequence

R flag

“replied” sequence

When a MaildirMessage instance is created based upon a BabylMessage instance, the following conversions take place:

Resulting state

BabylMessage state

“cur” subdirectory

“unseen” label

“cur” subdirectory and S flag

no “unseen” label

P flag

“forwarded” or “resent” label

R flag

“answered” label

T flag

“deleted” label

mboxMessage

class mailbox.mboxMessage(message=None)

A message with mbox-specific behaviors. Parameter message has the same meaning as with the Message constructor.

Messages in an mbox mailbox are stored together in a single file. The sender’s envelope address and the time of delivery are typically stored in a line beginning with “From ” that is used to indicate the start of a message, though there is considerable variation in the exact format of this data among mbox implementations. Flags that indicate the state of the message, such as whether it has been read or marked as important, are typically stored in Status and X-Status headers.

Conventional flags for mbox messages are as follows:

Flag

Meaning

Explanation

R

Read

Read

O

Old

Previously detected by MUA

D

Deleted

Marked for subsequent deletion

F

Flagged

Marked as important

A

Answered

Replied to

The “R” and “O” flags are stored in the Status header, and the “D”, “F”, and “A” flags are stored in the X-Status header. The flags and headers typically appear in the order mentioned.

mboxMessage instances offer the following methods:

get_from()

Return a string representing the “From ” line that marks the start of the message in an mbox mailbox. The leading “From ” and the trailing newline are excluded.

set_from(from_, time_=None)

Set the “From ” line to from_, which should be specified without a leading “From ” or trailing newline. For convenience, time_ may be specified and will be formatted appropriately and appended to from_. If time_ is specified, it should be a time.struct_time instance, a tuple suitable for passing to time.strftime(), or True (to use time.gmtime()).

get_flags()

Return a string specifying the flags that are currently set. If the message complies with the conventional format, the result is the concatenation in the following order of zero or one occurrence of each of 'R', 'O', 'D', 'F', and 'A'.

set_flags(flags)

Set the flags specified by flags and unset all others. Parameter flags should be the concatenation in any order of zero or more occurrences of each of 'R', 'O', 'D', 'F', and 'A'.

add_flag(flag)

Set the flag(s) specified by flag without changing other flags. To add more than one flag at a time, flag may be a string of more than one character.

remove_flag(flag)

Unset the flag(s) specified by flag without changing other flags. To remove more than one flag at a time, flag maybe a string of more than one character.

When an mboxMessage instance is created based upon a MaildirMessage instance, a “From ” line is generated based upon the MaildirMessage instance’s delivery date, and the following conversions take place:

Resulting state

MaildirMessage state

R flag

S flag

O flag

“cur” subdirectory

D flag

T flag

F flag

F flag

A flag

R flag

When an mboxMessage instance is created based upon an MHMessage instance, the following conversions take place:

Resulting state

MHMessage state

R flag and O flag

no “unseen” sequence

O flag

“unseen” sequence

F flag

“flagged” sequence

A flag

“replied” sequence

When an mboxMessage instance is created based upon a BabylMessage instance, the following conversions take place:

Resulting state

BabylMessage state

R flag and O flag

no “unseen” label

O flag

“unseen” label

D flag

“deleted” label

A flag

“answered” label

When a Message instance is created based upon an MMDFMessage instance, the “From ” line is copied and all flags directly correspond:

Resulting state

MMDFMessage state

R flag

R flag

O flag

O flag

D flag

D flag

F flag

F flag

A flag

A flag

MHMessage

class mailbox.MHMessage(message=None)

A message with MH-specific behaviors. Parameter message has the same meaning as with the Message constructor.

MH messages do not support marks or flags in the traditional sense, but they do support sequences, which are logical groupings of arbitrary messages. Some mail reading programs (although not the standard mh and nmh) use sequences in much the same way flags are used with other formats, as follows:

Sequence

Explanation

unseen

Not read, but previously detected by MUA

replied

Replied to

flagged

Marked as important

MHMessage instances offer the following methods:

get_sequences()

Return a list of the names of sequences that include this message.

set_sequences(sequences)

Set the list of sequences that include this message.

add_sequence(sequence)

Add sequence to the list of sequences that include this message.

remove_sequence(sequence)

Remove sequence from the list of sequences that include this message.

When an MHMessage instance is created based upon a MaildirMessage instance, the following conversions take place:

Resulting state

MaildirMessage state

“unseen” sequence

no S flag

“replied” sequence

R flag

“flagged” sequence

F flag

When an MHMessage instance is created based upon an mboxMessage or MMDFMessage instance, the Status and X-Status headers are omitted and the following conversions take place:

Resulting state

mboxMessage or MMDFMessage state

“unseen” sequence

no R flag

“replied” sequence

A flag

“flagged” sequence

F flag

When an MHMessage instance is created based upon a BabylMessage instance, the following conversions take place:

Resulting state

BabylMessage state

“unseen” sequence

“unseen” label

“replied” sequence

“answered” label

BabylMessage

class mailbox.BabylMessage(message=None)

A message with Babyl-specific behaviors. Parameter message has the same meaning as with the Message constructor.

Certain message labels, called attributes, are defined by convention to have special meanings. The attributes are as follows:

Label

Explanation

unseen

Not read, but previously detected by MUA

deleted

Marked for subsequent deletion

filed

Copied to another file or mailbox

answered

Replied to

forwarded

Forwarded

edited

Modified by the user

resent

Resent

By default, Rmail displays only visible headers. The BabylMessage class, though, uses the original headers because they are more complete. Visible headers may be accessed explicitly if desired.

BabylMessage instances offer the following methods:

get_labels()

Return a list of labels on the message.

set_labels(labels)

Set the list of labels on the message to labels.

add_label(label)

Add label to the list of labels on the message.

remove_label(label)

Remove label from the list of labels on the message.

get_visible()

Return an Message instance whose headers are the message’s visible headers and whose body is empty.

set_visible(visible)

Set the message’s visible headers to be the same as the headers in message. Parameter visible should be a Message instance, an email.message.Message instance, a string, or a file-like object (which should be open in text mode).

update_visible()

When a BabylMessage instance’s original headers are modified, the visible headers are not automatically modified to correspond. This method updates the visible headers as follows: each visible header with a corresponding original header is set to the value of the original header, each visible header without a corresponding original header is removed, and any of Date, From, Reply-To, To, CC, and Subject that are present in the original headers but not the visible headers are added to the visible headers.

When a BabylMessage instance is created based upon a MaildirMessage instance, the following conversions take place:

Resulting state

MaildirMessage state

“unseen” label

no S flag

“deleted” label

T flag

“answered” label

R flag

“forwarded” label

P flag

When a BabylMessage instance is created based upon an mboxMessage or MMDFMessage instance, the Status and X-Status headers are omitted and the following conversions take place:

Resulting state

mboxMessage or MMDFMessage state

“unseen” label

no R flag

“deleted” label

D flag

“answered” label

A flag

When a BabylMessage instance is created based upon an MHMessage instance, the following conversions take place:

Resulting state

MHMessage state

“unseen” label

“unseen” sequence

“answered” label

“replied” sequence

MMDFMessage

class mailbox.MMDFMessage(message=None)

A message with MMDF-specific behaviors. Parameter message has the same meaning as with the Message constructor.

As with message in an mbox mailbox, MMDF messages are stored with the sender’s address and the delivery date in an initial line beginning with “From “. Likewise, flags that indicate the state of the message are typically stored in Status and X-Status headers.

Conventional flags for MMDF messages are identical to those of mbox message and are as follows:

Flag

Meaning

Explanation

R

Read

Read

O

Old

Previously detected by MUA

D

Deleted

Marked for subsequent deletion

F

Flagged

Marked as important

A

Answered

Replied to

The “R” and “O” flags are stored in the Status header, and the “D”, “F”, and “A” flags are stored in the X-Status header. The flags and headers typically appear in the order mentioned.

MMDFMessage instances offer the following methods, which are identical to those offered by mboxMessage:

get_from()

Return a string representing the “From ” line that marks the start of the message in an mbox mailbox. The leading “From ” and the trailing newline are excluded.

set_from(from_, time_=None)

Set the “From ” line to from_, which should be specified without a leading “From ” or trailing newline. For convenience, time_ may be specified and will be formatted appropriately and appended to from_. If time_ is specified, it should be a time.struct_time instance, a tuple suitable for passing to time.strftime(), or True (to use time.gmtime()).

get_flags()

Return a string specifying the flags that are currently set. If the message complies with the conventional format, the result is the concatenation in the following order of zero or one occurrence of each of 'R', 'O', 'D', 'F', and 'A'.

set_flags(flags)

Set the flags specified by flags and unset all others. Parameter flags should be the concatenation in any order of zero or more occurrences of each of 'R', 'O', 'D', 'F', and 'A'.

add_flag(flag)

Set the flag(s) specified by flag without changing other flags. To add more than one flag at a time, flag may be a string of more than one character.

remove_flag(flag)

Unset the flag(s) specified by flag without changing other flags. To remove more than one flag at a time, flag maybe a string of more than one character.

When an MMDFMessage instance is created based upon a MaildirMessage instance, a “From ” line is generated based upon the MaildirMessage instance’s delivery date, and the following conversions take place:

Resulting state

MaildirMessage state

R flag

S flag

O flag

“cur” subdirectory

D flag

T flag

F flag

F flag

A flag

R flag

When an MMDFMessage instance is created based upon an MHMessage instance, the following conversions take place:

Resulting state

MHMessage state

R flag and O flag

no “unseen” sequence

O flag

“unseen” sequence

F flag

“flagged” sequence

A flag

“replied” sequence

When an MMDFMessage instance is created based upon a BabylMessage instance, the following conversions take place:

Resulting state

BabylMessage state

R flag and O flag

no “unseen” label

O flag

“unseen” label

D flag

“deleted” label

A flag

“answered” label

When an MMDFMessage instance is created based upon an mboxMessage instance, the “From ” line is copied and all flags directly correspond:

Resulting state

mboxMessage state

R flag

R flag

O flag

O flag

D flag

D flag

F flag

F flag

A flag

A flag

Exceptions

The following exception classes are defined in the mailbox module:

exception mailbox.Error

The based class for all other module-specific exceptions.

exception mailbox.NoSuchMailboxError

Raised when a mailbox is expected but is not found, such as when instantiating a Mailbox subclass with a path that does not exist (and with the create parameter set to False), or when opening a folder that does not exist.

exception mailbox.NotEmptyError

Raised when a mailbox is not empty but is expected to be, such as when deleting a folder that contains messages.

exception mailbox.ExternalClashError

Raised when some mailbox-related condition beyond the control of the program causes it to be unable to proceed, such as when failing to acquire a lock that another program already holds a lock, or when a uniquely-generated file name already exists.

exception mailbox.FormatError

Raised when the data in a file cannot be parsed, such as when an MH instance attempts to read a corrupted .mh_sequences file.

Examples

A simple example of printing the subjects of all messages in a mailbox that seem interesting:

import mailbox
for message in mailbox.mbox('~/mbox'):
    subject = message['subject']       # Could possibly be None.
    if subject and 'python' in subject.lower():
        print(subject)

To copy all mail from a Babyl mailbox to an MH mailbox, converting all of the format-specific information that can be converted:

import mailbox
destination = mailbox.MH('~/Mail')
destination.lock()
for message in mailbox.Babyl('~/RMAIL'):
    destination.add(mailbox.MHMessage(message))
destination.flush()
destination.unlock()

This example sorts mail from several mailing lists into different mailboxes, being careful to avoid mail corruption due to concurrent modification by other programs, mail loss due to interruption of the program, or premature termination due to malformed messages in the mailbox:

import mailbox
import email.errors

list_names = ('python-list', 'python-dev', 'python-bugs')

boxes = {name: mailbox.mbox('~/email/%s' % name) for name in list_names}
inbox = mailbox.Maildir('~/Maildir', factory=None)

for key in inbox.iterkeys():
    try:
        message = inbox[key]
    except email.errors.MessageParseError:
        continue                # The message is malformed. Just leave it.

    for name in list_names:
        list_id = message['list-id']
        if list_id and name in list_id:
            # Get mailbox to use
            box = boxes[name]

            # Write copy to disk before removing original.
            # If there's a crash, you might duplicate a message, but
            # that's better than losing a message completely.
            box.lock()
            box.add(message)
            box.flush()
            box.unlock()

            # Remove original message
            inbox.lock()
            inbox.discard(key)
            inbox.flush()
            inbox.unlock()
            break               # Found destination, so stop looking.

for box in boxes.itervalues():
    box.close()

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 데이터 처리 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 데이터 처리 »

|

mimetypes — 파일명을 MIME 유형에 매핑

소스 코드: Lib/mimetypes.py [https://github.com/python/cpython/tree/3.7/Lib/mimetypes.py]

mimetypes 모듈은 파일명이나 URL과 파일명 확장자와 연관된 MIME 유형 간의 변환을 제공합니다. 변환은 파일명에서 MIME 유형으로, MIME 유형에서 파일 이름 확장자로 제공됩니다; 후자의 변환에서는 인코딩이 지원되지 않습니다.

이 모듈은 하나의 클래스와 여러 편리 함수를 제공합니다. 함수가 이 모듈에 대한 일반 인터페이스이지만, 일부 응용 프로그램은 클래스에도 관심이 있을 수 있습니다.

아래에 설명된 함수는 이 모듈의 기본 인터페이스를 제공합니다. 모듈이 초기화되지 않았으면, 함수가 init()가 설정하는 정보에 의존하면 init()를 호출합니다.

mimetypes.guess_type(url, strict=True)

Guess the type of a file based on its filename or URL, given by url. The return value is a tuple (type, encoding) where type is None if the type can’t be guessed (missing or unknown suffix) or a string of the form 'type/subtype', usable for a MIME content-type header.

encoding은 인코딩에 사용된 프로그램의 이름(예를 들어, compress나 gzip)이거나, 인코딩이 없으면 None입니다. 인코딩은 Content-Encoding 헤더로 사용하기에 적합합니다, Content-Transfer-Encoding 헤더가 아닙니다. 매핑은 테이블 기반입니다. 인코딩 접미사는 대소 문자를 구분합니다; 유형 접미사는 먼저 대소 문자를 구분해서 시도한 후에, 대소 문자를 구분하지 않고 시도합니다.

선택적 strict 인자는 알려진 MIME 유형 목록을 IANA에 등록된 [https://www.iana.org/assignments/media-types/media-types.xhtml] 공식 유형으로만 제한할지를 지정하는 플래그입니다. strict가 True(기본값)이면 IANA 유형만 지원됩니다; strict가 False일 때, 추가로 표준이 아니지만, 일반적으로 사용되는 MIME 유형도 인식됩니다.

mimetypes.guess_all_extensions(type, strict=True)

type으로 주어진 MIME 유형을 기반으로 파일의 확장자를 추측합니다. 반환 값은 가능한 모든 파일명 확장자를 제공하는 문자열 리스트인데, 선행 점('.')을 포함합니다. 확장자는 특정 데이터 스트림과 연관되었음이 보장되지는 않지만, guess_type()에 의해 MIME 유형 type으로 매핑됩니다.

선택적 strict 인자는 guess_type() 함수에서와 같은 의미를 가집니다.

mimetypes.guess_extension(type, strict=True)

type으로 주어진 MIME 유형을 기반으로 파일의 확장자를 추측합니다. 반환 값은 파일명 확장자를 제공하는 문자열인데, 선행 점('.')을 포함합니다. 확장자는 특정 데이터 스트림과 연관되었음이 보장되지는 않지만, guess_type()에 의해 MIME 유형 type으로 매핑됩니다. type에 대해 추측할 수 있는 확장이 없으면, None이 반환됩니다.

선택적 strict 인자는 guess_type() 함수에서와 같은 의미를 가집니다.

일부 추가 함수와 데이터 항목은 모듈의 동작을 제어하는 데 사용할 수 있습니다.

mimetypes.init(files=None)

내부 데이터 구조를 초기화합니다. 주어지면, files는 기본 유형 맵을 보강하는 데 사용해야 하는 파일 이름의 시퀀스여야 합니다. 생략하면, 사용할 파일 이름은 knownfiles에서 가져옵니다; 윈도우에서는, 현재 레지스트리 설정이 로드됩니다. files나 knownfiles에서 명명된 각 파일은 그 앞에서 명명된 파일보다 우선합니다. 반복적으로 init()를 호출할 수 있습니다.

files에 빈 리스트를 지정하면 시스템 기본값이 적용되지 않습니다: 내장 리스트로부터 온 잘 알려진 값만 나타납니다.

If files is None the internal data structure is completely rebuilt to its initial default value. This is a stable operation and will produce the same results when called multiple times.

버전 3.2에서 변경: 이전에는, 윈도우 레지스트리 설정이 무시되었습니다.

mimetypes.read_mime_types(filename)

filename 파일이 있으면, 그 파일에 주어진 유형 맵을 로드합니다. 유형 맵은 선행 점('.')을 포함하는 파일명 확장자를 'type/subtype' 형식의 문자열로 매핑하는 딕셔너리로 반환됩니다. filename 파일이 없거나 읽을 수 없으면 None이 반환됩니다.

mimetypes.add_type(type, ext, strict=True)

MIME 유형 type에서 확장자 ext로의 매핑을 추가합니다. 확장자가 이미 알려져 있으면, 새 유형이 이전 유형을 대체합니다. 유형이 이미 알려져 있으면, 확장이 알려진 확장 리스트에 추가됩니다.

strict가 True(기본값)이면, 매핑이 공식 MIME 유형에 추가되고, 그렇지 않으면 비표준 MIME 유형에 추가됩니다.

mimetypes.inited

전역 데이터 구조가 초기화되었는지를 나타내는 플래그. 이것은 init()에 의해 True로 설정됩니다.

mimetypes.knownfiles

일반적으로 설치된 유형 맵 파일 이름의 리스트입니다. 이 파일들은 일반적으로 mime.types로 명명되며 패키지별로 다른 위치에 설치됩니다.

mimetypes.suffix_map

접미사를 접미사에 매핑하는 딕셔너리. 인코딩과 유형이 같은 확장자로 표시되는 인코딩된 파일을 인식하도록 하는 데 사용됩니다. 예를 들어, .tgz 확장자는 인코딩과 유형을 별도로 인식 할 수 있도록, .tar.gz에 매핑됩니다.

mimetypes.encodings_map

파일명 확장자를 인코딩 유형에 매핑하는 딕셔너리.

mimetypes.types_map

파일명 확장자를 MIME 유형에 매핑하는 딕셔너리.

mimetypes.common_types

파일명 확장자를 비표준이지만 일반적으로 발견되는 MIME 유형에 매핑하는 딕셔너리.

모듈의 사용 예:

>>> import mimetypes
>>> mimetypes.init()
>>> mimetypes.knownfiles
['/etc/mime.types', '/etc/httpd/mime.types', ... ]
>>> mimetypes.suffix_map['.tgz']
'.tar.gz'
>>> mimetypes.encodings_map['.gz']
'gzip'
>>> mimetypes.types_map['.tgz']
'application/x-tar-gz'

MimeTypes 객체

MimeTypes 클래스는 하나 이상의 MIME 유형 데이터베이스가 필요한 응용 프로그램에 유용 할 수 있습니다. mimetypes 모듈과 유사한 인터페이스를 제공합니다.

class mimetypes.MimeTypes(filenames=(), strict=True)

이 클래스는 MIME 유형 데이터베이스를 나타냅니다. 기본적으로, 이 모듈의 나머지 부분과 같은 데이터베이스에 대한 액세스를 제공합니다. 초기 데이터베이스는 모듈이 제공하는 것의 사본이며, read()나 readfp() 메서드를 사용하여 추가 mime.types-스타일 파일을 데이터베이스에 로드하여 확장할 수 있습니다. 기본 데이터가 필요하지 않으면, 추가 데이터를 로드하기 전에 매핑 딕셔너리를 지울 수도 있습니다.

선택적 filenames 매개 변수는 기본 데이터베이스의 “위”에 추가 파일을 로드하게 하는 데 사용할 수 있습니다.

suffix_map

접미사를 접미사에 매핑하는 딕셔너리. 인코딩과 유형이 같은 확장자로 표시되는 인코딩된 파일을 인식하도록 하는 데 사용됩니다. 예를 들어, .tgz 확장자는 인코딩과 유형을 별도로 인식 할 수 있도록, .tar.gz에 매핑됩니다. 이것은 초기에는 모듈에 정의된 전역 suffix_map의 사본입니다.

encodings_map

파일명 확장자를 인코딩 유형에 매핑하는 딕셔너리. 이것은 초기에는 모듈에 정의된 전역 encodings_map의 사본입니다.

types_map

파일명 확장자를 MIME 유형으로 매핑하는 두 개의 딕셔너리를 포함하는 튜플: 첫 번째 딕셔너리는 비표준 유형 용이고 두 번째는 표준 유형 용입니다. common_types와 types_map으로 초기화됩니다.

types_map_inv

MIME 타입을 파일명 확장자 리스트로 매핑하는 두 개의 딕셔너리를 포함하는 튜플: 첫 번째 딕셔너리는 비표준 유형 용이고 두 번째는 표준 유형 용입니다. common_types와 types_map으로 초기화됩니다.

guess_extension(type, strict=True)

guess_extension() 함수와 유사하고, 객체의 일부로 저장된 테이블을 사용합니다.

guess_type(url, strict=True)

guess_type() 함수와 유사하고, 객체의 일부로 저장된 테이블을 사용합니다.

guess_all_extensions(type, strict=True)

guess_all_extensions() 함수와 유사하고, 객체의 일부로 저장된 테이블을 사용합니다.

read(filename, strict=True)

filename이라는 이름의 파일에서 MIME 정보를 로드합니다. readfp()를 사용하여 파일을 구문 분석합니다.

strict가 True이면, 정보는 표준 유형 리스트에 추가되고, 그렇지 않으면 비표준 유형 리스트에 추가됩니다.

readfp(fp, strict=True)

열린 파일 fp에서 MIME 유형 정보를 로드합니다. 파일은 표준 mime.types 파일의 형식이어야 합니다.

strict가 True이면, 정보는 표준 유형 리스트에 추가되고, 그렇지 않으면 비표준 유형 리스트에 추가됩니다.

read_windows_registry(strict=True)

윈도우 레지스트리에서 MIME 유형 정보를 로드합니다.

가용성: 윈도우.

strict가 True이면, 정보는 표준 유형 리스트에 추가되고, 그렇지 않으면 비표준 유형 리스트에 추가됩니다.

버전 3.2에 추가.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 데이터 처리 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 데이터 처리 »

|

base64 — Base16, Base32, Base64, Base85 데이터 인코딩

소스 코드: Lib/base64.py [https://github.com/python/cpython/tree/3.7/Lib/base64.py]

이 모듈은 바이너리 데이터를 인쇄 가능한 ASCII 문자로 인코딩하고 이러한 인코딩을 다시 바이너리 데이터로 디코딩하는 함수를 제공합니다. Base16, Base32 및 Base64 알고리즘을 정의하는 RFC 3548 [https://tools.ietf.org/html/rfc3548.html]에 지정된 인코딩과 사실상의 표준인 Ascii85와 Base85 인코딩에 대한 인코딩과 디코딩 함수를 제공합니다.

RFC 3548 [https://tools.ietf.org/html/rfc3548.html] 인코딩은 전자 우편으로 안전하게 보내거나, URL의 일부로 사용하거나, HTTP POST 요청의 일부로 포함 할 수 있도록 바이너리 데이터를 인코딩하는 데 적합합니다. 인코딩 알고리즘은 uuencode 프로그램과 다릅니다.

이 모듈은 두 개의 인터페이스를 제공합니다. 최신 인터페이스는 바이트열류 객체를 ASCII bytes로 인코딩하고, 바이트열류 객체나 ASCII를 포함하는 문자열을 bytes로 디코딩하는 것을 지원합니다. RFC 3548 [https://tools.ietf.org/html/rfc3548.html]에 정의된 두 가지(일반, 그리고 URL과 파일 시스템에서 안전한) base-64 알파벳이 모두 지원됩니다.

레거시 인터페이스는 문자열로부터의 디코딩을 지원하지 않지만, 파일 객체에서 인코딩과 디코딩하는 함수를 제공합니다. Base64 표준 알파벳만 지원하며, RFC 2045 [https://tools.ietf.org/html/rfc2045.html]에 따라 76자마다 개행 문자를 추가합니다. RFC 2045 [https://tools.ietf.org/html/rfc2045.html] 지원을 원한다면 아마도 대신 email 패키지를 보고 싶을 것입니다.

버전 3.3에서 변경: ASCII 전용 유니코드 문자열은 이제 최신 인터페이스의 디코딩 함수가 받아들입니다.

버전 3.4에서 변경: 모든 바이트열류 객체는 이제 이 모듈의 모든 인코딩과 디코딩 함수가 받아들입니다. Ascii85/Base85 지원이 추가되었습니다.

최신 인터페이스는 다음과 같은 것들을 제공합니다:

base64.b64encode(s, altchars=None)

Base64를 사용하여 바이트열류 객체 s를 인코딩하고 인코딩된 bytes를 반환합니다.

선택적 altchars는 +와 / 문자의 대체 알파벳을 지정하는 최소 길이 2(추가 문자는 무시됩니다)의 바이트열류 객체여야 합니다. 이를 통해 응용 프로그램은 URL이나 파일 시스템에서 안전한 Base64 문자열을 생성할 수 있습니다. 기본값은 None이며, 표준 Base64 알파벳이 사용됩니다.

base64.b64decode(s, altchars=None, validate=False)

Base64로 인코딩된 바이트열류 객체나 ASCII 문자열 s를 디코딩하고 디코딩된 bytes를 반환합니다.

선택적 altchars는 +와 / 문자 대신에 사용되는 대체 알파벳을 지정하는 최소 길이 2(추가 문자는 무시됩니다)의 바이트열류 객체나 ASCII 문자열이어야 합니다.

s가 잘못 채워지면(padded) binascii.Error 예외가 발생합니다.

validate가 False(기본값)면, 일반 base-64 알파벳도 대체 알파벳도 아닌 문자는 채우기(padding) 검사 전에 버려집니다. validate가 True면, 입력에 이 알파벳이 아닌 문자가 있으면 binascii.Error가 발생합니다.

base64.standard_b64encode(s)

표준 Base64 알파벳을 사용하여 바이트열류 객체 s를 인코딩하고 인코딩된 bytes를 반환합니다.

base64.standard_b64decode(s)

표준 Base64 알파벳을 사용하여 바이트열류 객체나 ASCII 문자열 s를 디코딩하고 디코딩된 bytes를 반환합니다.

base64.urlsafe_b64encode(s)

표준 Base64 알파벳에서 + 대신 -를, / 대신 _를 사용하도록 대체한 URL과 파일 시스템에서 안전한 알파벳을 사용하여 바이트열류 객체 s를 인코딩하고, 인코딩된 bytes를 반환합니다. 결과에는 여전히 =가 포함될 수 있습니다.

base64.urlsafe_b64decode(s)

표준 Base64 알파벳에서 + 대신 -를, / 대신 _를 사용하도록 대체한 URL과 파일 시스템에서 안전한 알파벳을 사용하여 바이트열류 객체나 ASCII 문자열 s를 디코딩하고, 디코딩된 bytes를 반환합니다.

base64.b32encode(s)

Base32를 사용하여 바이트열류 객체 s를 인코딩하고 인코딩된 bytes를 반환합니다.

base64.b32decode(s, casefold=False, map01=None)

Base32로 인코딩된 바이트열류 객체나 ASCII 문자열 s를 디코딩하고 디코딩된 bytes를 반환합니다.

선택적 casefold는 소문자 알파벳을 입력으로 사용할 수 있는지를 지정하는 플래그입니다. 보안을 위해, 기본값은 False입니다.

RFC 3548 [https://tools.ietf.org/html/rfc3548.html]은 숫자 0(영)을 글자 O(오)로 선택적으로 매핑하고, 숫자 1(일)을 글자 I(아이)나 글자 L(엘)로 선택적으로 매핑할 수 있게 합니다. 선택적 인자 map01이 None이 아니면, 숫자 1이 매핑되어야 하는 글자를 지정합니다 (map01이 None이 아닐 때, 숫자 0은 항상 글자 O로 매핑됩니다). 보안상의 이유로 기본값은 None이고, 0과 1은 입력에 허용되지 않습니다.

s가 잘못 채워졌거나(padded) 입력에 알파벳이 아닌 문자가 있으면 binascii.Error가 발생합니다.

base64.b16encode(s)

Base16을 사용하여 바이트열류 객체 s를 인코딩하고 인코딩된 bytes를 반환합니다.

base64.b16decode(s, casefold=False)

Base16으로 인코딩된 바이트열류 객체나 ASCII 문자열 s를 디코딩하고 디코딩된 bytes를 반환합니다.

선택적 casefold는 소문자 알파벳을 입력으로 사용할 수 있는지를 지정하는 플래그입니다. 보안을 위해, 기본값은 False입니다.

s가 잘못 채워졌거나(padded) 입력에 알파벳이 아닌 문자가 있으면 binascii.Error가 발생합니다.

base64.a85encode(b, *, foldspaces=False, wrapcol=0, pad=False, adobe=False)

Ascii85를 사용하여 바이트열류 객체 b를 인코딩하고 인코딩된 bytes를 반환합니다.

foldspaces는 ‘btoa’ 가 지원하듯이 4개의 연속된 스페이스 (ASCII 0x20) 대신 특수한 짧은 시퀀스 ‘y’ 를 사용하는 선택적 플래그입니다. 이 기능은 “표준” Ascii85 인코딩에서 지원되지 않습니다.

wrapcol은 출력에 줄 바꿈 (b'\n') 문자가 추가되어야 하는지를 제어합니다. 이것이 0이 아니면, 각 출력 줄의 길이는 이 문자 수를 넘지 않습니다.

pad는 인코딩하기 전에 입력이 4의 배수로 채워졌는지를 제어합니다. btoa 구현은 항상 채운다는 것에 유의하십시오.

adobe는 인코딩된 바이트 시퀀스가 Adobe 구현에서 사용되는 <~와 ~>로 프레임화되는지를 제어합니다.

버전 3.4에 추가.

base64.a85decode(b, *, foldspaces=False, adobe=False, ignorechars=b' \t\n\r\v')

Ascii85로 인코딩된 바이트열류 객체나 ASCII 문자열 b를 디코딩하고 디코딩된 bytes를 반환합니다.

foldspaces는 짧은 시퀀스 ‘y’ 를 4개의 연속 된 스페이스(ASCII 0x20)에 대한 축약으로 받아들여야 하는지를 지정하는 플래그입니다. 이 기능은 “표준” Ascii85 인코딩에서 지원되지 않습니다.

adobe는 입력 시퀀스가 Adobe Ascii85 형식인지(즉 <~ 와 ~> 로 프레임화되었는지)를 제어합니다.

ignorechars는 입력에서 무시할 문자가 포함된 바이트열류 객체나 ASCII 문자열이어야 합니다. 여기에는 공백 문자만 포함되어야 하며, 기본적으로 ASCII의 모든 공백 문자가 포함됩니다.

버전 3.4에 추가.

base64.b85encode(b, pad=False)

base85를 사용하여 바이트열류 객체 b를 인코딩하고 (예를 들어 git 스타일 바이너리 diff에서 사용되는 것처럼), 인코딩된 bytes를 반환합니다.

pad가 참이면, 입력은 b'\0'으로 채워져서 길이는 인코딩 전에 4바이트의 배수가 됩니다.

버전 3.4에 추가.

base64.b85decode(b)

base85로 인코딩된 바이트열류 객체나 ASCII 문자열 b를 디코딩하고 디코딩된 bytes를 반환합니다. 필요하면, 채우기는 묵시적으로 제거됩니다.

버전 3.4에 추가.

레거시 인터페이스:

base64.decode(input, output)

바이너리 input 파일의 내용을 디코딩하고 결과 바이너리 데이터를 output 파일에 씁니다. input과 output은 파일 객체여야 합니다. input은 input.readline()이 빈 바이트열 객체를 반환할 때까지 읽힙니다.

base64.decodebytes(s)

하나 이상의 base64 인코딩된 데이터 줄을 포함해야 하는 바이트열류 객체 s를 디코딩하고 디코딩된 bytes를 반환합니다.

버전 3.1에 추가.

base64.decodestring(s)

decodebytes()의 폐지된 별칭.

버전 3.1부터 폐지.

base64.encode(input, output)

바이너리 input 파일의 내용을 인코딩하고 base64로 인코딩된 결과 데이터를 output 파일에 씁니다. input과 output은 파일 객체여야 합니다. input은 input.read()이 빈 바이트열 객체를 반환할 때까지 읽힙니다. encode()는 RFC 2045 [https://tools.ietf.org/html/rfc2045.html](MIME)에 따라 출력의 76바이트마다 개행 문자(b'\n')를 삽입할 뿐만 아니라, 항상 출력이 개행 문자로 끝나도록 합니다.

base64.encodebytes(s)

임의의 바이너리 데이터를 포함할 수 있는 바이트열류 객체 s를 인코딩하고, RFC 2045 [https://tools.ietf.org/html/rfc2045.html] (MIME)에 따라 76바이트의 출력마다 개행(b'\n')이 삽입되고, 후행 개행이 붙은 base64 인코딩된 데이터를 포함하는 bytes를 반환합니다.

버전 3.1에 추가.

base64.encodestring(s)

encodebytes()의 폐지된 별칭.

버전 3.1부터 폐지.

모듈 사용 예:

>>> import base64
>>> encoded = base64.b64encode(b'data to be encoded')
>>> encoded
b'ZGF0YSB0byBiZSBlbmNvZGVk'
>>> data = base64.b64decode(encoded)
>>> data
b'data to be encoded'

더 보기

모듈 binascii

ASCII에서 바이너리로, 바이너리에서 ASCII로의 변환이 포함된 지원 모듈.

RFC 1521 [https://tools.ietf.org/html/rfc1521.html] - MIME (Multipurpose Internet Mail Extensions) Part One: Mechanisms for Specifying and Describing the Format of Internet Message Bodies

5.2 절, “Base64 Content-Transfer-Encoding” 은 base64 인코딩의 정의를 제공합니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 데이터 처리 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 데이터 처리 »

|

binhex — binhex4 파일 인코딩과 디코딩

소스 코드: Lib/binhex.py [https://github.com/python/cpython/tree/3.7/Lib/binhex.py]

이 모듈은 binhex4 형식의 파일을 인코드하고 디코드합니다. ASCII 형식의 매킨토시 파일 표현을 허용하는 형식입니다. 데이터 포크만 처리됩니다.

binhex 모듈은 다음 함수를 정의합니다:

binhex.binhex(input, output)

파일명 input을 가진 바이너리 파일을 binhex 파일 output으로 변환합니다. output 매개 변수는 파일명이나 파일류 객체(write()와 close() 메서드를 지원하는 임의의 객체)일 수 있습니다.

binhex.hexbin(input, output)

binhex 파일 input을 디코드합니다. input은 파일명이나 read() 와 close() 메서드를 지원하는 파일류 객체일 수 있습니다. output 인자가 None이 아니면 결과 파일은 그 이름의 파일에 기록됩니다. output이 None이면 출력 파일명은 binhex 파일에서 읽습니다.

다음 예외도 정의됩니다:

exception binhex.Error

binhex 형식을 사용하여 무언가를 인코드할 수 없거나 (예를 들어, 파일명이 파일명 필드에 들어가기에는 너무 길어서), 입력이 제대로 인코드 된 binhex 데이터가 아닐 때 발생하는 예외.

더 보기

모듈 binascii

ASCII에서 바이너리로, 바이너리에서 ASCII로의 변환이 포함된 지원 모듈.

노트

코더 및 디코더에 대한 대안적인 더 강력한 인터페이스가 있습니다, 자세한 내용은 소스를 참조하세요.

매킨토시 이외의 플랫폼에서 텍스트 파일을 코딩하거나 디코딩하면, 오래된 매킨토시 개행 규칙(줄의 끝으로 캐리지 리턴사용)을 계속 사용하게 됩니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 데이터 처리 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 데이터 처리 »

|

binascii — 바이너리와 ASCII 간의 변환

binascii 모듈에는 바이너리와 다양한 ASCII 인코딩 바이너리 표현 사이를 변환하는 여러 가지 방법이 포함되어 있습니다. 일반적으로 이러한 함수는 직접 사용하지 않고, 대신 uu, base64 또는 binhex와 같은 래퍼 모듈을 사용합니다. binascii 모듈에는 고수준 모듈에서 사용하는 보다 빠른 속도를 위해 C로 작성된 저수준 함수가 들어 있습니다.

참고

a2b_* 함수는 ASCII 문자만 포함하는 유니코드 문자열을 받아들입니다. 다른 함수는 바이트열류 객체(가령 bytes, bytearray 및 버퍼 프로토콜을 지원하는 다른 객체)만 받아들입니다.

버전 3.3에서 변경: ASCII로만 이루어진 유니코드 문자열은 이제 a2b_* 함수에서 허용됩니다.

binascii 모듈은 다음 함수를 정의합니다:

binascii.a2b_uu(string)

한 줄의 UU 인코딩된 데이터 string을 바이너리로 역변환하고 바이너리 데이터를 반환합니다. 마지막 줄을 제외하고는, 줄은 보통 45 (바이너리) 바이트를 포함합니다. 줄 데이터 뒤에는 공백 문자가 올 수 있습니다.

binascii.b2a_uu(data, *, backtick=False)

바이너리 data를 ASCII 문자의 줄로 변환합니다, 반환 값은 개행 문자를 포함하는 변환 된 줄입니다. data의 길이는 최대 45이어야 합니다. backtick가 참이면, 0은 스페이스 대신 '`'으로 표현됩니다.

버전 3.7에서 변경: backtick 매개 변수가 추가되었습니다.

binascii.a2b_base64(string)

base64 데이터 블록을 바이너리로 역변환하고 바이너리 데이터를 반환합니다. 한 번에 한 줄 이상을 전달할 수 있습니다.

binascii.b2a_base64(data, *, newline=True)

바이너리 data를 base64 코딩으로 ASCII 문자의 줄로 변환합니다. 반환 값은 변환된 줄인데, newline이 참이면, 개행 문자를 포함합니다. 이 함수의 출력은 RFC 3548 [https://tools.ietf.org/html/rfc3548.html]을 따릅니다.

버전 3.6에서 변경: newline 매개 변수가 추가되었습니다.

binascii.a2b_qp(data, header=False)

quoted-printable data 블록을 바이너리로 역변환하고 바이너리 데이터를 반환합니다. 한 번에 한 줄 이상을 전달할 수 있습니다. 선택적 인자 header가 있고 참이면, 밑줄(underscore)은 스페이스로 디코딩됩니다.

binascii.b2a_qp(data, quotetabs=False, istext=True, header=False)

바이너리 data를 quoted-printable 인코딩으로 ASCII 문자의 줄로 변환합니다. 반환 값은 변환된 줄입니다. 선택적 인자 quotetabs가 있고 참이면, 모든 탭과 스페이스가 인코딩됩니다. 선택적 인자 istext가 있고 참이면, 개행 문자는 인코딩되지 않지만, 후행 공백은 인코딩됩니다. 선택적 인자 header가 있고 참이면, 스페이스는 RFC 1522 [https://tools.ietf.org/html/rfc1522.html]에 따라 밑줄로 인코딩됩니다. 선택적 인자 header가 있고 거짓이면, 개행 문자도 함께 인코딩됩니다; 그렇지 않으면 라인 피드(linefeed) 변환이 바이너리 데이터 스트림을 손상할 수 있습니다.

binascii.a2b_hqx(string)

RLE 압축 해제 없이 binhex4 형식의 ASCII data를 바이너리로 변환합니다. 이 문자열에는 완전한 바이너리 바이트가 포함되거나, (binhex4 데이터의 마지막 부분에서) 나머지 비트가 0이어야 합니다.

binascii.rledecode_hqx(data)

binhex4 표준에 따라, data에 대해 RLE 압축 해제를 수행합니다. 이 알고리즘은 바이트 다음에 오는 0x90을 반복 표시기로 사용하고, 그 뒤에 카운트가 옵니다. 카운트 0은 바이트 값 0x90을 지정합니다. 이 루틴은 data 입력 데이터가 불완전한 반복 표시기로 끝나지 않는 한(이때는 Incomplete 예외가 발생합니다) 압축 해제된 데이터를 반환합니다.

버전 3.2에서 변경: 바이트열이나 bytearray 객체만 입력으로 허용합니다.

binascii.rlecode_hqx(data)

binhex4 스타일의 RLE 압축을 data에 대해 수행하고 결과를 반환합니다.

binascii.b2a_hqx(data)

hexbin4 바이너리에서 ASCII로의 변환을 수행하고 결과 문자열을 반환합니다. 인자는 이미 RLE로 코드화되어 있어야 하며, (마지막 조각을 제외하고) 길이가 3의 배수여야 합니다.

binascii.crc_hqx(data, value)

초기 CRC value로 시작하는, data의 16비트 CRC 값을 계산하고 결과를 반환합니다. 종종 0x1021로 표시되는, CRC-CCITT 다항식 x¹⁶ + x¹² + x⁵ + 1을 사용합니다. 이 CRC는 binhex4 형식에서 사용됩니다.

binascii.crc32(data[, value])

초기 CRC value로 시작하는, data의 32비트 체크섬인 CRC-32를 계산합니다. 기본 초기 CRC는 0입니다. 이 알고리즘은 ZIP 파일 체크섬과 일치합니다. 이 알고리즘은 체크섬 알고리즘으로 사용하도록 설계되었으므로, 일반 해시 알고리즘으로 사용하기에 적합하지 않습니다. 다음과 같이 사용하십시오:

print(binascii.crc32(b"hello world"))
# Or, in two pieces:
crc = binascii.crc32(b"hello")
crc = binascii.crc32(b" world", crc)
print('crc32 = {:#010x}'.format(crc))

버전 3.0에서 변경: 결과는 항상 부호 없는 정수입니다. 모든 파이썬 버전과 플랫폼에서 같은 숫자 값을 생성하려면, crc32(data) & 0xffffffff를 사용하십시오.

binascii.b2a_hex(data)

binascii.hexlify(data)

바이너리 data의 16진수 표현을 반환합니다. data의 모든 바이트는 해당 2자리 16진수 표현으로 변환됩니다. 따라서 반환된 바이트열 객체의 길이는 data 의 두 배입니다.

비슷한 기능(하지만 텍스트 문자열을 반환하는)을 bytes.hex() 메서드를 사용하여 편리하게 액세스할 수도 있습니다.

binascii.a2b_hex(hexstr)

binascii.unhexlify(hexstr)

16진수 문자열 hexstr로 표현된 바이너리 데이터를 반환합니다. 이 함수는 b2a_hex()의 역함수입니다. hexstr는 짝수개의 16진수(대소문자 모두 가능합니다)를 포함해야 하며, 그렇지 않으면 Error 예외가 발생합니다.

비슷한 기능(텍스트 문자열 인자만 받아들이지만, 공백에 대해 더 느슨한)을 bytes.fromhex() 클래스 메서드를 사용하여 액세스할 수도 있습니다.

exception binascii.Error

에러 시 발생하는 예외. 이들은 대개 프로그래밍 에러입니다.

exception binascii.Incomplete

불완전한 데이터에서 발생하는 예외. 이들은 일반적으로 프로그래밍 에러가 아니지만, 조금 더 많은 데이터를 읽고 다시 시도하면 처리될 수 있습니다.

더 보기

모듈 base64

RFC 호환 base64 스타일 인코딩으로, 베이스 16, 32, 64 및 85를 지원합니다.

모듈 binhex

매킨토시에서 사용되는 binhex 형식 지원.

모듈 uu

유닉스에서 사용되는 UU 인코딩 지원.

모듈 quopri

MIME 이메일 메시지에 사용되는 quoted-printable 인코딩 지원.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 데이터 처리 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 데이터 처리 »

|

quopri — MIME quoted-printable 데이터 인코딩과 디코딩

소스 코드: Lib/quopri.py [https://github.com/python/cpython/tree/3.7/Lib/quopri.py]

이 모듈은 RFC 1521 [https://tools.ietf.org/html/rfc1521.html]: “MIME (Multipurpose Internet Mail Extensions) 1부: 인터넷 메시지 본문의 형식을 지정하고 설명하기 위한 메커니즘”에 정의된 대로, quoted-printable 전송 인코딩과 디코딩을 수행합니다. quoted-printable 인코딩은 인쇄할 수 없는 문자가 비교적 적은 데이터를 위해 설계되었습니다; base64 모듈을 통해 사용할 수 있는 base64 인코딩 체계는 그래픽 파일을 보낼 때와 같이 그런 문자가 많은 경우 더 압축적입니다.

quopri.decode(input, output, header=False)

input 파일의 내용을 디코딩하고 결과로 디코딩된 바이너리 데이터를 output 파일에 씁니다. input 과 output는 바이너리 파일 객체 여야 합니다. 선택적 인자 header가 있고 참이면, 밑줄은 스페이스로 디코딩됩니다. 이것은 RFC 1522 [https://tools.ietf.org/html/rfc1522.html]: “MIME (Multipurpose Internet Mail Extensions) 2부: 비 ASCII 텍스트를 위한 메시지 헤더 확장”에서 설명한 대로 “Q”-인코딩된 헤더를 디코딩하는 데 사용됩니다.

quopri.encode(input, output, quotetabs, header=False)

input 파일의 내용을 인코딩하고 결과 quoted-printable 데이터를 output 파일에 씁니다. input 과 output은 바이너리 파일 객체 여야 합니다. quotetabs는 포함 된 스페이스와 탭을 인코딩할지를 제어하는 비 선택적 플래그입니다; 참이면 그러한 공백 문자를 인코드하고, 거짓이면 인코드하지 않고 남겨둡니다. 줄 끝에 나타나는 공백과 탭은 RFC 1521 [https://tools.ietf.org/html/rfc1521.html]에 따라 항상 인코딩됨에 유의하십시오. header는 스페이스를 RFC 1522 [https://tools.ietf.org/html/rfc1522.html]에 따라 밑줄로 인코딩할지를 제어하는 플래그입니다.

quopri.decodestring(s, header=False)

decode()와 비슷하지만, 소스 bytes를 받아들이고 해독된 해당 bytes를 반환합니다.

quopri.encodestring(s, quotetabs=False, header=False)

encode()와 비슷하지만, 소스 bytes를 받아들이고 인코딩된 해당 bytes를 반환합니다. 기본적으로 encode() 함수의 quotetabs 매개 변수에 False 값을 보냅니다.

더 보기

모듈 base64

MIME base64 데이터 인코딩과 디코딩

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 데이터 처리 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 데이터 처리 »

|

uu — uuencode 파일 인코딩과 디코딩

소스 코드: Lib/uu.py [https://github.com/python/cpython/tree/3.7/Lib/uu.py]

이 모듈은 uuencode 형식으로 파일을 인코딩과 디코딩해서, 임의의 바이너리 데이터를 ASCII 전용 연결을 통해 전송할 수 있도록 합니다. 파일 인자를 기대하는 모든 위치에서 파일류 객체를 사용할 수 있습니다. 이전 버전과의 호환성을 위해, 경로명을 포함하는 문자열도 허용되며 해당 파일은 읽기와 쓰기 용으로 열립니다; 경로명 '-'는 표준 입력이나 출력을 의미하는 것으로 이해됩니다. 그러나, 이 인터페이스는 폐지되었습니다; 호출자가 파일을 스스로 여는 것이 더 좋으며, 필요한 경우 윈도우에서 모드가 'rb' 나 'wb'인지 확인하십시오.

이 코드는 Lance Ellinghouse가 작성했으며, Jack Jansen이 수정했습니다.

uu 모듈은 다음 함수를 정의합니다:

uu.encode(in_file, out_file, name=None, mode=None, *, backtick=False)

in_file 파일을 out_file 파일로 uuencode합니다. uuencode 된 파일은 파일을 디코딩한 결과의 기본값으로 name 과 mode를 지정하는 헤더를 갖습니다. 기본 기본값은 in_file 에서 얻거나, 각각 '-' 과 0o666입니다. backtick이 참이면, 0은 스페이스 대신에 '`'로 표현됩니다.

버전 3.7에서 변경: backtick 매개 변수가 추가되었습니다.

uu.decode(in_file, out_file=None, mode=None, quiet=False)

이 호출은 uuencode 된 파일 in_file를 디코딩하여, 파일 out_file에 결과를 저장합니다. out_file이 경로명이면, 파일을 만들어야 할 때 mode를 사용하여 사용 권한 비트를 설정합니다. out_file 과 mode의 기본값은 uuencode 헤더에서 가져옵니다. 그러나, 헤더에 지정된 파일이 이미 존재하면, uu.Error가 발생합니다.

입력이 잘못된 uuencoder에 의해 만들어졌고, 파이썬이 그 에러로부터 복구할 수 있다면, decode()는 표준 에러에 경고를 인쇄할 수 있습니다. quiet를 참으로 설정하면, 이 경고가 사라집니다.

exception uu.Error

Exception의 서브 클래스인데, 다양한 상황(가령 위에 언급한 것과 같은, 하지만 형식이 잘못된 헤더나, 잘린 입력 파일도 포함됩니다)에서 uu.decode()가 발생시킬 수 있습니다.

더 보기

모듈 binascii

ASCII와 바이너리 간의 변환을 포함하는 지원 모듈.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 데이터 처리 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

|

구조화된 마크업 처리 도구

파이썬은 다양한 형태의 구조화된 데이터 마크업을 다루는 다양한 모듈을 지원합니다. 여기에는 SGML (Standard Generalized Markup Language) 및 HTML (Hypertext Markup Language) 을 다루는 모듈과 XML (Extensible Markup Language) 작업을 위한 여러 인터페이스가 포함됩니다.

html — 하이퍼텍스트 마크업 언어 지원

html.parser — 간단한 HTML과 XHTML 구문 분석기

HTML 구문 분석기 응용 프로그램 예제

HTMLParser 메서드

예제

html.entities — HTML 일반 엔티티의 정의

XML 처리 모듈

XML 취약점

defusedxml와 defusedexpat 패키지

xml.etree.ElementTree — The ElementTree XML API

Tutorial

XML tree and elements

Parsing XML

Pull API for non-blocking parsing

Finding interesting elements

Modifying an XML File

Building XML documents

Parsing XML with Namespaces

Additional resources

XPath support

Example

Supported XPath syntax

Reference

Functions

XInclude support

Example

Reference

Functions

Element Objects

ElementTree Objects

QName Objects

TreeBuilder Objects

XMLParser Objects

XMLPullParser Objects

Exceptions

xml.dom — 문서 객체 모델 API

모듈 내용

DOM의 객체

DOMImplementation 객체

Node 객체

NodeList 객체

DocumentType 객체

Document 객체

Element 객체

Attr 객체

NamedNodeMap 객체

Comment 객체

Text와 CDATASection 객체

ProcessingInstruction 객체

예외

규격 준수

형 매핑

접근자 메서드

xml.dom.minidom — 최소 DOM 구현

DOM 객체

DOM 예제

minidom과 DOM 표준

xml.dom.pulldom — 부분 DOM 트리 구축 지원

DOMEventStream 객체

xml.sax — SAX2 구문 분석기 지원

SAXException 객체

xml.sax.handler — Base classes for SAX handlers

ContentHandler Objects

DTDHandler Objects

EntityResolver Objects

ErrorHandler Objects

xml.sax.saxutils — SAX 유틸리티

xml.sax.xmlreader — XML 구문 분석기 인터페이스

XMLReader 객체

IncrementalParser 객체

Locator 객체

InputSource 객체

Attributes 인터페이스

AttributesNS 인터페이스

xml.parsers.expat — Fast XML parsing using Expat

XMLParser Objects

ExpatError Exceptions

Example

Content Model Descriptions

Expat error constants

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

구조화된 마크업 처리 도구 »

|

html — 하이퍼텍스트 마크업 언어 지원

소스 코드: Lib/html/__init__.py [https://github.com/python/cpython/tree/3.7/Lib/html/__init__.py]

이 모듈은 HTML을 조작하는 유틸리티를 정의합니다.

html.escape(s, quote=True)

문자열 s의 문자 &, < 및 >를 HTML-안전 시퀀스로 변환합니다. HTML에 이러한 문자가 포함될 수 있는 텍스트를 표시해야 할 때 사용하십시오. 선택적 플래그 quote가 참이면, 문자 (") 와 (') 도 변환됩니다; <a href="..."> 에서처럼 따옴표로 구분된 HTML 어트리뷰트에 포함하는 데 도움이 됩니다.

버전 3.2에 추가.

html.unescape(s)

문자열 s의 모든 이름과 숫자 문자 참조(예를 들어, &gt;, &#62;, &#x3e;)를 해당 유니코드 문자로 변환합니다. 이 함수는 유효하거나 유효하지 않은 문자 참조 모두에 대해 HTML 5 표준에 정의된 규칙과 HTML 5 이름 문자 참조 목록을 사용합니다.

버전 3.4에 추가.

html 패키지의 서브 모듈은 다음과 같습니다:

html.parser – 관대한 구문 분석 모드가 있는 HTML/XHTML 구문 분석기

html.entities – HTML 엔티티 정의

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

구조화된 마크업 처리 도구 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

구조화된 마크업 처리 도구 »

|

html.parser — 간단한 HTML과 XHTML 구문 분석기

소스 코드: Lib/html/parser.py [https://github.com/python/cpython/tree/3.7/Lib/html/parser.py]

이 모듈은 HTML(HyperText Mark-up Language)와 XHTML 형식의 텍스트 파일을 구문 분석하기 위한 기초로 사용되는 클래스 HTMLParser를 정의합니다.

class html.parser.HTMLParser(*, convert_charrefs=True)

잘못된 마크업을 구문 분석할 수 있는 구문 분석기 인스턴스를 만듭니다.

convert_charrefs가 True(기본값)이면, (script/style 요소에 있는 것을 제외한) 모든 문자 참조(character references)가 자동으로 해당 유니코드 문자로 변환됩니다.

HTMLParser 인스턴스는 HTML 데이터를 받아서 시작 태그, 종료 태그, 텍스트, 주석 및 기타 마크업 요소를 만날 때마다 처리기 메서드를 호출합니다. 사용자는 원하는 동작을 구현하기 위해 HTMLParser의 서브 클래스를 만들고 해당 메서드를 재정의해야 합니다.

이 구문 분석기는 종료 태그가 시작 태그와 일치하는지 검사하거나, 바깥(outer) 요소를 닫음으로써 묵시적으로 닫힌 요소에 대해 종료 태그 처리기를 호출하지 않습니다.

버전 3.4에서 변경: convert_charrefs 키워드 인자가 추가되었습니다.

버전 3.5에서 변경: 인자 convert_charrefs의 기본값은 이제 True입니다.

HTML 구문 분석기 응용 프로그램 예제

기본 예제로, 다음은 HTMLParser 클래스를 사용하여 시작 태그, 종료 태그 및 데이터를 만날 때마다 인쇄하는 간단한 HTML 구문 분석기입니다:

from html.parser import HTMLParser

class MyHTMLParser(HTMLParser):
    def handle_starttag(self, tag, attrs):
        print("Encountered a start tag:", tag)

    def handle_endtag(self, tag):
        print("Encountered an end tag :", tag)

    def handle_data(self, data):
        print("Encountered some data  :", data)

parser = MyHTMLParser()
parser.feed('<html><head><title>Test</title></head>'
            '<body><h1>Parse me!</h1></body></html>')

출력은 다음과 같습니다:

Encountered a start tag: html
Encountered a start tag: head
Encountered a start tag: title
Encountered some data  : Test
Encountered an end tag : title
Encountered an end tag : head
Encountered a start tag: body
Encountered a start tag: h1
Encountered some data  : Parse me!
Encountered an end tag : h1
Encountered an end tag : body
Encountered an end tag : html

HTMLParser 메서드

HTMLParser 인스턴스에는 다음과 같은 메서드가 있습니다:

HTMLParser.feed(data)

구문 분석기에 텍스트를 입력합니다. 완전한 요소로 구성되어있는 부분까지 처리됩니다; 불완전한 데이터는 더 많은 데이터가 공급되거나 close()가 호출될 때까지 버퍼링 됩니다. data는 str이어야 합니다.

HTMLParser.close()

버퍼링 된 모든 데이터를 마치 파일 끝(end-of-file) 표시가 붙은 것처럼 처리합니다. 이 메서드는 파생 클래스에 의해 입력 끝에서의 추가 처리를 정의하기 위해 재정의될 수 있지만, 재정의된 버전에서는 항상 HTMLParser 베이스 클래스 메서드인 close()를 호출해야 합니다.

HTMLParser.reset()

인스턴스를 재설정합니다. 처리되지 않은 모든 데이터를 잃습니다. 이것은 인스턴스 생성 시에 묵시적으로 호출됩니다.

HTMLParser.getpos()

현재의 줄 번호와 오프셋(offset)을 반환합니다.

HTMLParser.get_starttag_text()

가장 최근에 열렸던 시작 태그의 텍스트를 반환합니다. 이것은 일반적으로 구조화된 처리에 필요하지 않지만, “배치된 대로(as deployed)” HTML을 다루거나 최소한의 변경(어트리뷰트 사이의 공백을 보존할 수 있음, 등등)으로 입력을 다시 생성하는 데 유용할 수 있습니다.

다음 메서드는 데이터나 마크업 요소를 만날 때 호출되며 서브 클래스에서 재정의하려는 용도입니다. 베이스 클래스 구현은 아무 일도 하지 않습니다 (handle_startendtag()는 예외입니다).:

HTMLParser.handle_starttag(tag, attrs)

이 메서드는 태그의 시작(예를 들어, <div id="main">)을 처리하기 위해 호출됩니다.

tag 인자는 소문자로 변환된 태그의 이름입니다. attrs 인자는 태그의 <> 화살괄호 안에 있는 어트리뷰트를 포함하는 (name, value) 쌍의 리스트입니다. name은 소문자로 변환되고, value의 따옴표는 제거되고, 문자와 엔티티 참조는 치환됩니다.

예를 들어, 태그 <A HREF="https://www.cwi.nl/">의 경우, 이 메서드는 handle_starttag('a', [('href', 'https://www.cwi.nl/')])로 호출됩니다.

html.entities의 모든 엔티티 참조가 어트리뷰트 값에서 치환됩니다.

HTMLParser.handle_endtag(tag)

이 메서드는 요소의 종료 태그(예를 들어, </div>)를 처리하기 위해 호출됩니다.

tag 인자는 소문자로 변환된 태그의 이름입니다.

HTMLParser.handle_startendtag(tag, attrs)

handle_starttag()와 비슷하지만, 구문 분석기가 XHTML 스타일의 빈 태그(<img ... />)를 만날 때 호출됩니다. 이 메서드는 이 특정의 어휘 정보(lexical information)가 필요한 서브 클래스에 의해 재정의될 수 있습니다; 기본 구현은 단순히 handle_starttag()와 handle_endtag()를 호출합니다.

HTMLParser.handle_data(data)

이 메서드는 임의의 데이터(예를 들어, 텍스트 노드와 <script>...</script> 및 <style>...</style>의 내용)를 처리하기 위해 호출됩니다.

HTMLParser.handle_entityref(name)

이 메서드는 &name; 형식(예를 들어, &gt;)의 이름있는 문자 참조를 처리하기 위해 호출됩니다. 여기서 name은 일반 엔티티 참조(예를 들어, 'gt')입니다. convert_charrefs가 True이면, 이 메서드는 호출되지 않습니다.

HTMLParser.handle_charref(name)

이 메서드는 &#NNN;과 &#xNNN; 형식의 10진수 및 16진수 문자 참조를 처리하기 위해 호출됩니다. 예를 들어, &gt;에 해당하는 10진수는 &#62;이고, 반면에 16진수는 &#x3E;입니다; 이때 메서드는 '62'나 'x3E'를 받습니다. 이 메서드는 convert_charrefs가 True이면 호출되지 않습니다.

HTMLParser.handle_comment(data)

이 메서드는 주석을 만날 때 호출됩니다 (예를 들어, <!--comment-->).

예를 들어, 주석 <!-- comment -->는 이 메서드가 인자 ' comment '로 호출되도록 합니다.

Internet Explorer 조건부 주석(condcoms)의 내용도 이 메서드로 보내지므로, <!--[if IE 9]>IE9-specific content<![endif]-->의 경우, 이 메서드는 '[if IE 9]>IE9-specific content<![endif]'를 받습니다.

HTMLParser.handle_decl(decl)

이 메서드는 HTML doctype 선언(예를 들어, <!DOCTYPE html>)을 처리하기 위해 호출됩니다.

decl 매개 변수는 <!...> 마크업 내의 선언 전체 내용입니다 (예를 들어, 'DOCTYPE html').

HTMLParser.handle_pi(data)

처리 명령(processing instruction)을 만날 때 호출되는 메서드. data 매개 변수에는 전체 처리 명령이 포함됩니다. 예를 들어, 처리 명령 <?proc color='red'>의 경우, 이 메서드는 handle_pi("proc color='red'")로 호출됩니다. 파생 클래스에 의해 재정의되려는 목적입니다; 베이스 클래스 구현은 아무것도 수행하지 않습니다.

참고

HTMLParser 클래스는 처리 명령에 대해 SGML 구문 규칙을 사용합니다. 후행 '?'를 사용하는 XHTML 처리 명령은 '?'가 data에 포함되도록 합니다.

HTMLParser.unknown_decl(data)

이 메서드는 구문 분석기가 인식할 수 없는 선언을 읽었을 때 호출됩니다.

data 매개 변수는 <![...]> 마크업 안에 있는 선언의 전체 내용입니다. 파생 클래스가 재정의하는 것이 때때로 유용합니다. 베이스 클래스 구현은 아무것도 수행하지 않습니다.

예제

다음 클래스는 더 많은 예를 설명하는 데 사용할 구문 분석기를 구현합니다:

from html.parser import HTMLParser
from html.entities import name2codepoint

class MyHTMLParser(HTMLParser):
    def handle_starttag(self, tag, attrs):
        print("Start tag:", tag)
        for attr in attrs:
            print("     attr:", attr)

    def handle_endtag(self, tag):
        print("End tag  :", tag)

    def handle_data(self, data):
        print("Data     :", data)

    def handle_comment(self, data):
        print("Comment  :", data)

    def handle_entityref(self, name):
        c = chr(name2codepoint[name])
        print("Named ent:", c)

    def handle_charref(self, name):
        if name.startswith('x'):
            c = chr(int(name[1:], 16))
        else:
            c = chr(int(name))
        print("Num ent  :", c)

    def handle_decl(self, data):
        print("Decl     :", data)

parser = MyHTMLParser()

doctype 구문 분석하기:

>>> parser.feed('<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" '
...             '"http://www.w3.org/TR/html4/strict.dtd">')
Decl     : DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"

몇 가지 어트리뷰트를 가진 요소와 제목을 구문 분석하기:

>>> parser.feed('<img src="python-logo.png" alt="The Python logo">')
Start tag: img
     attr: ('src', 'python-logo.png')
     attr: ('alt', 'The Python logo')
>>>
>>> parser.feed('<h1>Python</h1>')
Start tag: h1
Data     : Python
End tag  : h1

script와 style 요소의 내용은 더 구문 분석하지 않고 있는 그대로 반환됩니다:

>>> parser.feed('<style type="text/css">#python { color: green }</style>')
Start tag: style
     attr: ('type', 'text/css')
Data     : #python { color: green }
End tag  : style

>>> parser.feed('<script type="text/javascript">'
...             'alert("<strong>hello!</strong>");</script>')
Start tag: script
     attr: ('type', 'text/javascript')
Data     : alert("<strong>hello!</strong>");
End tag  : script

주석 구문 분석하기:

>>> parser.feed('<!-- a comment -->'
...             '<!--[if IE 9]>IE-specific content<![endif]-->')
Comment  :  a comment
Comment  : [if IE 9]>IE-specific content<![endif]

이름있는 문자 참조와 숫자 문자 참조를 구문 분석하고 올바른 문자로 변환합니다 (참고: 이 3개의 참조는 모두 '>'와 동등합니다):

>>> parser.feed('&gt;&#62;&#x3E;')
Named ent: >
Num ent  : >
Num ent  : >

불완전한 청크를 feed()로 보내는 것이 작동합니다만, handle_data()가 두 번 이상 호출될 수 있습니다 (convert_charrefs가 True로 설정되지 않은 한):

>>> for chunk in ['<sp', 'an>buff', 'ered ', 'text</s', 'pan>']:
...     parser.feed(chunk)
...
Start tag: span
Data     : buff
Data     : ered
Data     : text
End tag  : span

잘못된 HTML(예를 들어, 따옴표 처리되지 않은 어트리뷰트)을 구문 분석하는 것도 동작합니다:

>>> parser.feed('<p><a class=link href=#main>tag soup</p ></a>')
Start tag: p
Start tag: a
     attr: ('class', 'link')
     attr: ('href', '#main')
Data     : tag soup
End tag  : p
End tag  : a

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

구조화된 마크업 처리 도구 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

구조화된 마크업 처리 도구 »

|

html.entities — HTML 일반 엔티티의 정의

소스 코드: Lib/html/entities.py [https://github.com/python/cpython/tree/3.7/Lib/html/entities.py]

이 모듈은 네 가지 딕셔너리 html5, name2codepoint, codepoint2name 와 entitydefs를 정의합니다.

html.entities.html5

HTML5 이름 문자 참조 1 를 해당 유니코드 문자에 매핑하는 딕셔너리, 예를 들어 html5['gt;'] == '>'. 후미 세미콜론이 이름에 포함됨에 유의하십시오 (예를 들어 'gt;'). 하지만 일부 이름은 세미콜론 없이도 표준에서 허용됩니다: 이럴 때 이름은 ';'가 있거나 없는 형태가 모두 포함됩니다. html.unescape()도 참조하십시오.

버전 3.3에 추가.

html.entities.entitydefs

XHTML 1.0 엔티티 정의를 ISO Latin-1의 치환 텍스트에 매핑하는 딕셔너리.

html.entities.name2codepoint

HTML 엔티티 이름을 유니코드 코드 포인트에 매핑하는 딕셔너리.

html.entities.codepoint2name

유니코드 코드 포인트를 HTML 엔티티 이름에 매핑하는 딕셔너리.

각주

1

https://www.w3.org/TR/html5/syntax.html#named-character-references 를 참조하십시오.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

구조화된 마크업 처리 도구 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

구조화된 마크업 처리 도구 »

|

XML 처리 모듈

소스 코드: Lib/xml/ [https://github.com/python/cpython/tree/3.7/Lib/xml/]

XML 처리를 위한 파이썬의 인터페이스는 xml 패키지로 묶여있습니다.

경고

XML 모듈은 잘못되었거나 악의적으로 구성된 데이터로부터 안전하지 않습니다. 신뢰할 수 없거나 인증되지 않은 데이터를 구문 분석해야 하면 XML 취약점과 defusedxml와 defusedexpat 패키지 절을 참조하십시오.

xml 패키지의 모듈들은 최소한 하나의 SAX 호환 XML 구문 분석기가 있도록 요구함에 유의해야 합니다. Expat 구문 분석기가 파이썬에 포함되어 있으므로, xml.parsers.expat 모듈을 항상 사용할 수 있습니다.

xml.dom 과 xml.sax 패키지에 대한 설명서는 DOM과 SAX 인터페이스에 대한 파이썬 바인딩의 정의입니다.

XML 처리 서브 모듈은 다음과 같습니다:

xml.etree.ElementTree: ElementTree API, 간단하고 가벼운 XML 프로세서

xml.dom: DOM API 정의

xml.dom.minidom: 최소 DOM 구현

xml.dom.pulldom: 부분 DOM 트리 구축 지원

xml.sax: SAX2 베이스 클래스와 편리 함수

xml.parsers.expat: Expat 구문 분석기 바인딩

XML 취약점

XML 처리 모듈은 악의적으로 구성된 데이터로부터 안전하지 않습니다. 공격자는 XML 기능을 악용하여 서비스 거부 공격을 수행하거나, 로컬 파일에 액세스하거나, 다른 기계로 네트워크 연결을 만들거나, 방화벽을 우회할 수 있습니다.

다음 표는 알려진 공격의 개요와 다양한 모듈이 취약한지를 보여줍니다.

종류

sax

etree

minidom

pulldom

xmlrpc

billion laughs(억만 웃음)

Vulnerable (1)

Vulnerable (1)

Vulnerable (1)

Vulnerable (1)

Vulnerable (1)

quadratic blowup(이차 폭발)

Vulnerable (1)

Vulnerable (1)

Vulnerable (1)

Vulnerable (1)

Vulnerable (1)

external entity expansion(외부 엔티티 확장)

Safe (5)

Safe (2)

Safe (3)

Safe (5)

안전 (4)

DTD [https://en.wikipedia.org/wiki/Document_type_definition] retrieval(DTD 조회)

Safe (5)

안전

안전

Safe (5)

안전

decompression bomb(압축해제 폭탄)

안전

안전

안전

안전

취약

Expat 2.4.1 and newer is not vulnerable to the “billion laughs” and “quadratic blowup” vulnerabilities. Items still listed as vulnerable due to potential reliance on system-provided libraries. Check pyexpat.EXPAT_VERSION.

xml.etree.ElementTree는 외부 엔티티를 확장하지 않고 엔티티가 있으면 ParserError를 발생시킵니다.

xml.dom.minidom은 외부 엔티티를 확장하지 않고 확장되지 않은 엔티티를 그대로 반환합니다.

xmlrpclib는 외부 엔티티를 확장하지 않고 생략합니다.

파이썬 3.7.1부터, 외부 일반 엔티티는 더는 기본적으로 처리되지 않습니다.

billion laughs(억만 웃음) / exponential entity expansion(지수적 엔티티 확장)

지수적 엔티티 확장으로도 알려진, Billion Laughs [https://en.wikipedia.org/wiki/Billion_laughs] 공격은 여러 수준의 중첩된 엔티티를 사용합니다. 각 엔티티는 다른 엔티티를 여러 번 참조하며, 최종 엔티티 정의에는 작은 문자열이 포함됩니다. 지수적인 확장으로 수 기가바이트의 텍스트가 생성되고 많은 메모리와 CPU 시간이 소모됩니다.

quadratic blowup entity expansion(이차 폭발 엔티티 확장)

이차 폭발 공격은 Billion Laughs [https://en.wikipedia.org/wiki/Billion_laughs] 공격과 유사합니다; 이 역시 엔티티 확장을 남용합니다. 중첩된 엔티티 대신 2천 개 이상의 문자를 갖는 커다란 엔티티 하나를 계속 반복합니다. 공격은 지수적인 경우만큼 효율적이지 않지만 깊이 중첩된 엔티티를 금지하는 구문 분석기 대응책을 우회합니다.

external entity expansion(외부 엔티티 확장)

엔티티 선언은 대체 텍스트 이상의 것을 포함할 수 있습니다. 외부 자원이나 지역 파일을 가리킬 수도 있습니다. XML 구문 분석기는 자원에 액세스하고 그 내용을 XML 문서에 포함합니다.

DTD [https://en.wikipedia.org/wiki/Document_type_definition] retrieval(DTD 조회)

파이썬의 xml.dom.pulldom 같은 일부 XML 라이브러리는 원격이나 지역 위치에서 문서 유형 정의(DTD)를 조회합니다. 이 기능은 외부 엔티티 확장 문제와 비슷한 결과를 줍니다.

decompression bomb(압축해제 폭탄)

압축 해제 폭탄(일명 ZIP bomb [https://en.wikipedia.org/wiki/Zip_bomb])은 gzip 압축된 HTTP 스트림이나 LZMA 압축 파일과 같은, 압축된 XML 스트림을 구문 분석할 수 있는 모든 XML 라이브러리에 적용됩니다. 공격자는 전송된 데이터의 양을 3배 이상 줄일 수 있습니다.

PyPI의 defusedxml [https://pypi.org/project/defusedxml/] 설명서에는 모든 알려진 공격 벡터에 대한 추가 정보가 예제와 레퍼런스와 함께 제공됩니다.

defusedxml와 defusedexpat 패키지

defusedxml [https://pypi.org/project/defusedxml/]은 순수한 파이썬 패키지인데, 모든 악의적인 조작을 방지하도록 수정된, 모든 표준 라이브러리 XML 구문 분석기의 서브 클래스를 제공합니다. 신뢰할 수 없는 XML 데이터를 구문 분석하는 서버 코드에는 이 패키지를 사용하는 것이 좋습니다. 이 패키지에는 XPath 주입과 같은 XML 공격(exploit)에 대한 예제 공격과 확장된 설명서가 함께 제공됩니다.

defusedexpat [https://pypi.org/project/defusedexpat/]은 엔티티 확장 DoS 공격에 대한 대책이 있는 수정된 libexpat 와 패치된 pyexpat 모듈을 제공합니다. defusedexpat 모듈은 여전히 합리적이고 구성 가능한 양의 엔티티 확장을 허용합니다. 이 수정이 향후의 파이썬 배포에 포함될 수 있지만, 이전 버전과의 호환성을 없애기 때문에 파이썬의 버그 수정 배포에는 포함되지 않을 것입니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

구조화된 마크업 처리 도구 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

구조화된 마크업 처리 도구 »

|

xml.etree.ElementTree — The ElementTree XML API

Source code: Lib/xml/etree/ElementTree.py [https://github.com/python/cpython/tree/3.7/Lib/xml/etree/ElementTree.py]

The xml.etree.ElementTree module implements a simple and efficient API for parsing and creating XML data.

버전 3.3에서 변경: This module will use a fast implementation whenever available. The xml.etree.cElementTree module is deprecated.

경고

The xml.etree.ElementTree module is not secure against maliciously constructed data. If you need to parse untrusted or unauthenticated data see XML 취약점.

Tutorial

This is a short tutorial for using xml.etree.ElementTree (ET in short). The goal is to demonstrate some of the building blocks and basic concepts of the module.

XML tree and elements

XML is an inherently hierarchical data format, and the most natural way to represent it is with a tree. ET has two classes for this purpose - ElementTree represents the whole XML document as a tree, and Element represents a single node in this tree. Interactions with the whole document (reading and writing to/from files) are usually done on the ElementTree level. Interactions with a single XML element and its sub-elements are done on the Element level.

Parsing XML

We’ll be using the following XML document as the sample data for this section:

<?xml version="1.0"?>
<data>
    <country name="Liechtenstein">
        <rank>1</rank>
        <year>2008</year>
        <gdppc>141100</gdppc>
        <neighbor name="Austria" direction="E"/>
        <neighbor name="Switzerland" direction="W"/>
    </country>
    <country name="Singapore">
        <rank>4</rank>
        <year>2011</year>
        <gdppc>59900</gdppc>
        <neighbor name="Malaysia" direction="N"/>
    </country>
    <country name="Panama">
        <rank>68</rank>
        <year>2011</year>
        <gdppc>13600</gdppc>
        <neighbor name="Costa Rica" direction="W"/>
        <neighbor name="Colombia" direction="E"/>
    </country>
</data>

We can import this data by reading from a file:

import xml.etree.ElementTree as ET
tree = ET.parse('country_data.xml')
root = tree.getroot()

Or directly from a string:

root = ET.fromstring(country_data_as_string)

fromstring() parses XML from a string directly into an Element, which is the root element of the parsed tree. Other parsing functions may create an ElementTree. Check the documentation to be sure.

As an Element, root has a tag and a dictionary of attributes:

>>> root.tag
'data'
>>> root.attrib
{}

It also has children nodes over which we can iterate:

>>> for child in root:
...     print(child.tag, child.attrib)
...
country {'name': 'Liechtenstein'}
country {'name': 'Singapore'}
country {'name': 'Panama'}

Children are nested, and we can access specific child nodes by index:

>>> root[0][1].text
'2008'

참고

Not all elements of the XML input will end up as elements of the parsed tree. Currently, this module skips over any XML comments, processing instructions, and document type declarations in the input. Nevertheless, trees built using this module’s API rather than parsing from XML text can have comments and processing instructions in them; they will be included when generating XML output. A document type declaration may be accessed by passing a custom TreeBuilder instance to the XMLParser constructor.

Pull API for non-blocking parsing

Most parsing functions provided by this module require the whole document to be read at once before returning any result. It is possible to use an XMLParser and feed data into it incrementally, but it is a push API that calls methods on a callback target, which is too low-level and inconvenient for most needs. Sometimes what the user really wants is to be able to parse XML incrementally, without blocking operations, while enjoying the convenience of fully constructed Element objects.

The most powerful tool for doing this is XMLPullParser. It does not require a blocking read to obtain the XML data, and is instead fed with data incrementally with XMLPullParser.feed() calls. To get the parsed XML elements, call XMLPullParser.read_events(). Here is an example:

>>> parser = ET.XMLPullParser(['start', 'end'])
>>> parser.feed('<mytag>sometext')
>>> list(parser.read_events())
[('start', <Element 'mytag' at 0x7fa66db2be58>)]
>>> parser.feed(' more text</mytag>')
>>> for event, elem in parser.read_events():
...     print(event)
...     print(elem.tag, 'text=', elem.text)
...
end

The obvious use case is applications that operate in a non-blocking fashion where the XML data is being received from a socket or read incrementally from some storage device. In such cases, blocking reads are unacceptable.

Because it’s so flexible, XMLPullParser can be inconvenient to use for simpler use-cases. If you don’t mind your application blocking on reading XML data but would still like to have incremental parsing capabilities, take a look at iterparse(). It can be useful when you’re reading a large XML document and don’t want to hold it wholly in memory.

Finding interesting elements

Element has some useful methods that help iterate recursively over all the sub-tree below it (its children, their children, and so on). For example, Element.iter():

>>> for neighbor in root.iter('neighbor'):
...     print(neighbor.attrib)
...
{'name': 'Austria', 'direction': 'E'}
{'name': 'Switzerland', 'direction': 'W'}
{'name': 'Malaysia', 'direction': 'N'}
{'name': 'Costa Rica', 'direction': 'W'}
{'name': 'Colombia', 'direction': 'E'}

Element.findall() finds only elements with a tag which are direct children of the current element. Element.find() finds the first child with a particular tag, and Element.text accesses the element’s text content. Element.get() accesses the element’s attributes:

>>> for country in root.findall('country'):
...     rank = country.find('rank').text
...     name = country.get('name')
...     print(name, rank)
...
Liechtenstein 1
Singapore 4
Panama 68

More sophisticated specification of which elements to look for is possible by using XPath.

Modifying an XML File

ElementTree provides a simple way to build XML documents and write them to files. The ElementTree.write() method serves this purpose.

Once created, an Element object may be manipulated by directly changing its fields (such as Element.text), adding and modifying attributes (Element.set() method), as well as adding new children (for example with Element.append()).

Let’s say we want to add one to each country’s rank, and add an updated attribute to the rank element:

>>> for rank in root.iter('rank'):
...     new_rank = int(rank.text) + 1
...     rank.text = str(new_rank)
...     rank.set('updated', 'yes')
...
>>> tree.write('output.xml')

Our XML now looks like this:

<?xml version="1.0"?>
<data>
    <country name="Liechtenstein">
        <rank updated="yes">2</rank>
        <year>2008</year>
        <gdppc>141100</gdppc>
        <neighbor name="Austria" direction="E"/>
        <neighbor name="Switzerland" direction="W"/>
    </country>
    <country name="Singapore">
        <rank updated="yes">5</rank>
        <year>2011</year>
        <gdppc>59900</gdppc>
        <neighbor name="Malaysia" direction="N"/>
    </country>
    <country name="Panama">
        <rank updated="yes">69</rank>
        <year>2011</year>
        <gdppc>13600</gdppc>
        <neighbor name="Costa Rica" direction="W"/>
        <neighbor name="Colombia" direction="E"/>
    </country>
</data>

We can remove elements using Element.remove(). Let’s say we want to remove all countries with a rank higher than 50:

>>> for country in root.findall('country'):
...     rank = int(country.find('rank').text)
...     if rank > 50:
...         root.remove(country)
...
>>> tree.write('output.xml')

Our XML now looks like this:

<?xml version="1.0"?>
<data>
    <country name="Liechtenstein">
        <rank updated="yes">2</rank>
        <year>2008</year>
        <gdppc>141100</gdppc>
        <neighbor name="Austria" direction="E"/>
        <neighbor name="Switzerland" direction="W"/>
    </country>
    <country name="Singapore">
        <rank updated="yes">5</rank>
        <year>2011</year>
        <gdppc>59900</gdppc>
        <neighbor name="Malaysia" direction="N"/>
    </country>
</data>

Building XML documents

The SubElement() function also provides a convenient way to create new sub-elements for a given element:

>>> a = ET.Element('a')
>>> b = ET.SubElement(a, 'b')
>>> c = ET.SubElement(a, 'c')
>>> d = ET.SubElement(c, 'd')
>>> ET.dump(a)
<a><b /><c><d /></c></a>

Parsing XML with Namespaces

If the XML input has namespaces [https://en.wikipedia.org/wiki/XML_namespace], tags and attributes with prefixes in the form prefix:sometag get expanded to {uri}sometag where the prefix is replaced by the full URI. Also, if there is a default namespace [https://www.w3.org/TR/xml-names/#defaulting], that full URI gets prepended to all of the non-prefixed tags.

Here is an XML example that incorporates two namespaces, one with the prefix “fictional” and the other serving as the default namespace:

<?xml version="1.0"?>
<actors xmlns:fictional="http://characters.example.com"
        xmlns="http://people.example.com">
    <actor>
        <name>John Cleese</name>
        <fictional:character>Lancelot</fictional:character>
        <fictional:character>Archie Leach</fictional:character>
    </actor>
    <actor>
        <name>Eric Idle</name>
        <fictional:character>Sir Robin</fictional:character>
        <fictional:character>Gunther</fictional:character>
        <fictional:character>Commander Clement</fictional:character>
    </actor>
</actors>

One way to search and explore this XML example is to manually add the URI to every tag or attribute in the xpath of a find() or findall():

root = fromstring(xml_text)
for actor in root.findall('{http://people.example.com}actor'):
    name = actor.find('{http://people.example.com}name')
    print(name.text)
    for char in actor.findall('{http://characters.example.com}character'):
        print(' |-->', char.text)

A better way to search the namespaced XML example is to create a dictionary with your own prefixes and use those in the search functions:

ns = {'real_person': 'http://people.example.com',
      'role': 'http://characters.example.com'}

for actor in root.findall('real_person:actor', ns):
    name = actor.find('real_person:name', ns)
    print(name.text)
    for char in actor.findall('role:character', ns):
        print(' |-->', char.text)

These two approaches both output:

John Cleese
 |--> Lancelot
 |--> Archie Leach
Eric Idle
 |--> Sir Robin
 |--> Gunther
 |--> Commander Clement

Additional resources

See http://effbot.org/zone/element-index.htm for tutorials and links to other docs.

XPath support

This module provides limited support for XPath expressions [https://www.w3.org/TR/xpath] for locating elements in a tree. The goal is to support a small subset of the abbreviated syntax; a full XPath engine is outside the scope of the module.

Example

Here’s an example that demonstrates some of the XPath capabilities of the module. We’ll be using the countrydata XML document from the Parsing XML section:

import xml.etree.ElementTree as ET

root = ET.fromstring(countrydata)

# Top-level elements
root.findall(".")

# All 'neighbor' grand-children of 'country' children of the top-level
# elements
root.findall("./country/neighbor")

# Nodes with name='Singapore' that have a 'year' child
root.findall(".//year/..[@name='Singapore']")

# 'year' nodes that are children of nodes with name='Singapore'
root.findall(".//*[@name='Singapore']/year")

# All 'neighbor' nodes that are the second child of their parent
root.findall(".//neighbor[2]")

Supported XPath syntax

Syntax

Meaning

tag

Selects all child elements with the given tag. For example, spam selects all child elements named spam, and spam/egg selects all grandchildren named egg in all children named spam.

*

Selects all child elements. For example, */egg selects all grandchildren named egg.

.

Selects the current node. This is mostly useful at the beginning of the path, to indicate that it’s a relative path.

//

Selects all subelements, on all levels beneath the current element. For example, .//egg selects all egg elements in the entire tree.

..

Selects the parent element. Returns None if the path attempts to reach the ancestors of the start element (the element find was called on).

[@attrib]

Selects all elements that have the given attribute.

[@attrib='value']

Selects all elements for which the given attribute has the given value. The value cannot contain quotes.

[tag]

Selects all elements that have a child named tag. Only immediate children are supported.

[.='text']

Selects all elements whose complete text content, including descendants, equals the given text.

버전 3.7에 추가.

[tag='text']

Selects all elements that have a child named tag whose complete text content, including descendants, equals the given text.

[position]

Selects all elements that are located at the given position. The position can be either an integer (1 is the first position), the expression last() (for the last position), or a position relative to the last position (e.g. last()-1).

Predicates (expressions within square brackets) must be preceded by a tag name, an asterisk, or another predicate. position predicates must be preceded by a tag name.

Reference

Functions

xml.etree.ElementTree.Comment(text=None)

Comment element factory. This factory function creates a special element that will be serialized as an XML comment by the standard serializer. The comment string can be either a bytestring or a Unicode string. text is a string containing the comment string. Returns an element instance representing a comment.

Note that XMLParser skips over comments in the input instead of creating comment objects for them. An ElementTree will only contain comment nodes if they have been inserted into to the tree using one of the Element methods.

xml.etree.ElementTree.dump(elem)

Writes an element tree or element structure to sys.stdout. This function should be used for debugging only.

The exact output format is implementation dependent. In this version, it’s written as an ordinary XML file.

elem is an element tree or an individual element.

xml.etree.ElementTree.fromstring(text, parser=None)

Parses an XML section from a string constant. Same as XML(). text is a string containing XML data. parser is an optional parser instance. If not given, the standard XMLParser parser is used. Returns an Element instance.

xml.etree.ElementTree.fromstringlist(sequence, parser=None)

Parses an XML document from a sequence of string fragments. sequence is a list or other sequence containing XML data fragments. parser is an optional parser instance. If not given, the standard XMLParser parser is used. Returns an Element instance.

버전 3.2에 추가.

xml.etree.ElementTree.iselement(element)

Check if an object appears to be a valid element object. element is an element instance. Return True if this is an element object.

xml.etree.ElementTree.iterparse(source, events=None, parser=None)

Parses an XML section into an element tree incrementally, and reports what’s going on to the user. source is a filename or file object containing XML data. events is a sequence of events to report back. The supported events are the strings "start", "end", "start-ns" and "end-ns" (the “ns” events are used to get detailed namespace information). If events is omitted, only "end" events are reported. parser is an optional parser instance. If not given, the standard XMLParser parser is used. parser must be a subclass of XMLParser and can only use the default TreeBuilder as a target. Returns an iterator providing (event, elem) pairs.

Note that while iterparse() builds the tree incrementally, it issues blocking reads on source (or the file it names). As such, it’s unsuitable for applications where blocking reads can’t be made. For fully non-blocking parsing, see XMLPullParser.

참고

iterparse() only guarantees that it has seen the “>” character of a starting tag when it emits a “start” event, so the attributes are defined, but the contents of the text and tail attributes are undefined at that point. The same applies to the element children; they may or may not be present.

If you need a fully populated element, look for “end” events instead.

버전 3.4부터 폐지: The parser argument.

xml.etree.ElementTree.parse(source, parser=None)

Parses an XML section into an element tree. source is a filename or file object containing XML data. parser is an optional parser instance. If not given, the standard XMLParser parser is used. Returns an ElementTree instance.

xml.etree.ElementTree.ProcessingInstruction(target, text=None)

PI element factory. This factory function creates a special element that will be serialized as an XML processing instruction. target is a string containing the PI target. text is a string containing the PI contents, if given. Returns an element instance, representing a processing instruction.

Note that XMLParser skips over processing instructions in the input instead of creating comment objects for them. An ElementTree will only contain processing instruction nodes if they have been inserted into to the tree using one of the Element methods.

xml.etree.ElementTree.register_namespace(prefix, uri)

Registers a namespace prefix. The registry is global, and any existing mapping for either the given prefix or the namespace URI will be removed. prefix is a namespace prefix. uri is a namespace uri. Tags and attributes in this namespace will be serialized with the given prefix, if at all possible.

버전 3.2에 추가.

xml.etree.ElementTree.SubElement(parent, tag, attrib={}, **extra)

Subelement factory. This function creates an element instance, and appends it to an existing element.

The element name, attribute names, and attribute values can be either bytestrings or Unicode strings. parent is the parent element. tag is the subelement name. attrib is an optional dictionary, containing element attributes. extra contains additional attributes, given as keyword arguments. Returns an element instance.

xml.etree.ElementTree.tostring(element, encoding="us-ascii", method="xml", *, short_empty_elements=True)

Generates a string representation of an XML element, including all subelements. element is an Element instance. encoding 1 is the output encoding (default is US-ASCII). Use encoding="unicode" to generate a Unicode string (otherwise, a bytestring is generated). method is either "xml", "html" or "text" (default is "xml"). short_empty_elements has the same meaning as in ElementTree.write(). Returns an (optionally) encoded string containing the XML data.

버전 3.4에 추가: The short_empty_elements parameter.

xml.etree.ElementTree.tostringlist(element, encoding="us-ascii", method="xml", *, short_empty_elements=True)

Generates a string representation of an XML element, including all subelements. element is an Element instance. encoding 1 is the output encoding (default is US-ASCII). Use encoding="unicode" to generate a Unicode string (otherwise, a bytestring is generated). method is either "xml", "html" or "text" (default is "xml"). short_empty_elements has the same meaning as in ElementTree.write(). Returns a list of (optionally) encoded strings containing the XML data. It does not guarantee any specific sequence, except that b"".join(tostringlist(element)) == tostring(element).

버전 3.2에 추가.

버전 3.4에 추가: The short_empty_elements parameter.

xml.etree.ElementTree.XML(text, parser=None)

Parses an XML section from a string constant. This function can be used to embed “XML literals” in Python code. text is a string containing XML data. parser is an optional parser instance. If not given, the standard XMLParser parser is used. Returns an Element instance.

xml.etree.ElementTree.XMLID(text, parser=None)

Parses an XML section from a string constant, and also returns a dictionary which maps from element id:s to elements. text is a string containing XML data. parser is an optional parser instance. If not given, the standard XMLParser parser is used. Returns a tuple containing an Element instance and a dictionary.

XInclude support

This module provides limited support for XInclude directives [https://www.w3.org/TR/xinclude/], via the xml.etree.ElementInclude helper module. This module can be used to insert subtrees and text strings into element trees, based on information in the tree.

Example

Here’s an example that demonstrates use of the XInclude module. To include an XML document in the current document, use the {http://www.w3.org/2001/XInclude}include element and set the parse attribute to "xml", and use the href attribute to specify the document to include.

<?xml version="1.0"?>
<document xmlns:xi="http://www.w3.org/2001/XInclude">
  <xi:include href="source.xml" parse="xml" />
</document>

By default, the href attribute is treated as a file name. You can use custom loaders to override this behaviour. Also note that the standard helper does not support XPointer syntax.

To process this file, load it as usual, and pass the root element to the xml.etree.ElementTree module:

from xml.etree import ElementTree, ElementInclude

tree = ElementTree.parse("document.xml")
root = tree.getroot()

ElementInclude.include(root)

The ElementInclude module replaces the {http://www.w3.org/2001/XInclude}include element with the root element from the source.xml document. The result might look something like this:

<document xmlns:xi="http://www.w3.org/2001/XInclude">
  <para>This is a paragraph.</para>
</document>

If the parse attribute is omitted, it defaults to “xml”. The href attribute is required.

To include a text document, use the {http://www.w3.org/2001/XInclude}include element, and set the parse attribute to “text”:

<?xml version="1.0"?>
<document xmlns:xi="http://www.w3.org/2001/XInclude">
  Copyright (c) <xi:include href="year.txt" parse="text" />.
</document>

The result might look something like:

<document xmlns:xi="http://www.w3.org/2001/XInclude">
  Copyright (c) 2003.
</document>

Reference

Functions

xml.etree.ElementInclude.default_loader(href, parse, encoding=None)

Default loader. This default loader reads an included resource from disk. href is a URL. parse is for parse mode either “xml” or “text”. encoding is an optional text encoding. If not given, encoding is utf-8. Returns the expanded resource. If the parse mode is "xml", this is an ElementTree instance. If the parse mode is “text”, this is a Unicode string. If the loader fails, it can return None or raise an exception.

xml.etree.ElementInclude.include(elem, loader=None)

This function expands XInclude directives. elem is the root element. loader is an optional resource loader. If omitted, it defaults to default_loader(). If given, it should be a callable that implements the same interface as default_loader(). Returns the expanded resource. If the parse mode is "xml", this is an ElementTree instance. If the parse mode is “text”, this is a Unicode string. If the loader fails, it can return None or raise an exception.

Element Objects

class xml.etree.ElementTree.Element(tag, attrib={}, **extra)

Element class. This class defines the Element interface, and provides a reference implementation of this interface.

The element name, attribute names, and attribute values can be either bytestrings or Unicode strings. tag is the element name. attrib is an optional dictionary, containing element attributes. extra contains additional attributes, given as keyword arguments.

tag

A string identifying what kind of data this element represents (the element type, in other words).

text

tail

These attributes can be used to hold additional data associated with the element. Their values are usually strings but may be any application-specific object. If the element is created from an XML file, the text attribute holds either the text between the element’s start tag and its first child or end tag, or None, and the tail attribute holds either the text between the element’s end tag and the next tag, or None. For the XML data

<a><b>1<c>2<d/>3</c></b>4</a>

the a element has None for both text and tail attributes, the b element has text "1" and tail "4", the c element has text "2" and tail None, and the d element has text None and tail "3".

To collect the inner text of an element, see itertext(), for example "".join(element.itertext()).

Applications may store arbitrary objects in these attributes.

attrib

A dictionary containing the element’s attributes. Note that while the attrib value is always a real mutable Python dictionary, an ElementTree implementation may choose to use another internal representation, and create the dictionary only if someone asks for it. To take advantage of such implementations, use the dictionary methods below whenever possible.

The following dictionary-like methods work on the element attributes.

clear()

Resets an element. This function removes all subelements, clears all attributes, and sets the text and tail attributes to None.

get(key, default=None)

Gets the element attribute named key.

Returns the attribute value, or default if the attribute was not found.

items()

Returns the element attributes as a sequence of (name, value) pairs. The attributes are returned in an arbitrary order.

keys()

Returns the elements attribute names as a list. The names are returned in an arbitrary order.

set(key, value)

Set the attribute key on the element to value.

The following methods work on the element’s children (subelements).

append(subelement)

Adds the element subelement to the end of this element’s internal list of subelements. Raises TypeError if subelement is not an Element.

extend(subelements)

Appends subelements from a sequence object with zero or more elements. Raises TypeError if a subelement is not an Element.

버전 3.2에 추가.

find(match, namespaces=None)

Finds the first subelement matching match. match may be a tag name or a path. Returns an element instance or None. namespaces is an optional mapping from namespace prefix to full name.

findall(match, namespaces=None)

Finds all matching subelements, by tag name or path. Returns a list containing all matching elements in document order. namespaces is an optional mapping from namespace prefix to full name.

findtext(match, default=None, namespaces=None)

Finds text for the first subelement matching match. match may be a tag name or a path. Returns the text content of the first matching element, or default if no element was found. Note that if the matching element has no text content an empty string is returned. namespaces is an optional mapping from namespace prefix to full name.

getchildren()

버전 3.2부터 폐지: Use list(elem) or iteration.

getiterator(tag=None)

버전 3.2부터 폐지: Use method Element.iter() instead.

insert(index, subelement)

Inserts subelement at the given position in this element. Raises TypeError if subelement is not an Element.

iter(tag=None)

Creates a tree iterator with the current element as the root. The iterator iterates over this element and all elements below it, in document (depth first) order. If tag is not None or '*', only elements whose tag equals tag are returned from the iterator. If the tree structure is modified during iteration, the result is undefined.

버전 3.2에 추가.

iterfind(match, namespaces=None)

Finds all matching subelements, by tag name or path. Returns an iterable yielding all matching elements in document order. namespaces is an optional mapping from namespace prefix to full name.

버전 3.2에 추가.

itertext()

Creates a text iterator. The iterator loops over this element and all subelements, in document order, and returns all inner text.

버전 3.2에 추가.

makeelement(tag, attrib)

Creates a new element object of the same type as this element. Do not call this method, use the SubElement() factory function instead.

remove(subelement)

Removes subelement from the element. Unlike the find* methods this method compares elements based on the instance identity, not on tag value or contents.

Element objects also support the following sequence type methods for working with subelements: __delitem__(), __getitem__(), __setitem__(), __len__().

Caution: Elements with no subelements will test as False. This behavior will change in future versions. Use specific len(elem) or elem is None test instead.

element = root.find('foo')

if not element:  # careful!
    print("element not found, or element has no subelements")

if element is None:
    print("element not found")

ElementTree Objects

class xml.etree.ElementTree.ElementTree(element=None, file=None)

ElementTree wrapper class. This class represents an entire element hierarchy, and adds some extra support for serialization to and from standard XML.

element is the root element. The tree is initialized with the contents of the XML file if given.

_setroot(element)

Replaces the root element for this tree. This discards the current contents of the tree, and replaces it with the given element. Use with care. element is an element instance.

find(match, namespaces=None)

Same as Element.find(), starting at the root of the tree.

findall(match, namespaces=None)

Same as Element.findall(), starting at the root of the tree.

findtext(match, default=None, namespaces=None)

Same as Element.findtext(), starting at the root of the tree.

getiterator(tag=None)

버전 3.2부터 폐지: Use method ElementTree.iter() instead.

getroot()

Returns the root element for this tree.

iter(tag=None)

Creates and returns a tree iterator for the root element. The iterator loops over all elements in this tree, in section order. tag is the tag to look for (default is to return all elements).

iterfind(match, namespaces=None)

Same as Element.iterfind(), starting at the root of the tree.

버전 3.2에 추가.

parse(source, parser=None)

Loads an external XML section into this element tree. source is a file name or file object. parser is an optional parser instance. If not given, the standard XMLParser parser is used. Returns the section root element.

write(file, encoding="us-ascii", xml_declaration=None, default_namespace=None, method="xml", *, short_empty_elements=True)

Writes the element tree to a file, as XML. file is a file name, or a file object opened for writing. encoding 1 is the output encoding (default is US-ASCII). xml_declaration controls if an XML declaration should be added to the file. Use False for never, True for always, None for only if not US-ASCII or UTF-8 or Unicode (default is None). default_namespace sets the default XML namespace (for “xmlns”). method is either "xml", "html" or "text" (default is "xml"). The keyword-only short_empty_elements parameter controls the formatting of elements that contain no content. If True (the default), they are emitted as a single self-closed tag, otherwise they are emitted as a pair of start/end tags.

The output is either a string (str) or binary (bytes). This is controlled by the encoding argument. If encoding is "unicode", the output is a string; otherwise, it’s binary. Note that this may conflict with the type of file if it’s an open file object; make sure you do not try to write a string to a binary stream and vice versa.

버전 3.4에 추가: The short_empty_elements parameter.

This is the XML file that is going to be manipulated:

<html>
    <head>
        <title>Example page</title>
    </head>
    <body>
        <p>Moved to <a href="http://example.org/">example.org</a>
        or <a href="http://example.com/">example.com</a>.</p>
    </body>
</html>

Example of changing the attribute “target” of every link in first paragraph:

>>> from xml.etree.ElementTree import ElementTree
>>> tree = ElementTree()
>>> tree.parse("index.xhtml")
<Element 'html' at 0xb77e6fac>
>>> p = tree.find("body/p")     # Finds first occurrence of tag p in body
>>> p
<Element 'p' at 0xb77ec26c>
>>> links = list(p.iter("a"))   # Returns list of all links
>>> links
[<Element 'a' at 0xb77ec2ac>, <Element 'a' at 0xb77ec1cc>]
>>> for i in links:             # Iterates through all found links
...     i.attrib["target"] = "blank"
>>> tree.write("output.xhtml")

QName Objects

class xml.etree.ElementTree.QName(text_or_uri, tag=None)

QName wrapper. This can be used to wrap a QName attribute value, in order to get proper namespace handling on output. text_or_uri is a string containing the QName value, in the form {uri}local, or, if the tag argument is given, the URI part of a QName. If tag is given, the first argument is interpreted as a URI, and this argument is interpreted as a local name. QName instances are opaque.

TreeBuilder Objects

class xml.etree.ElementTree.TreeBuilder(element_factory=None)

Generic element structure builder. This builder converts a sequence of start, data, and end method calls to a well-formed element structure. You can use this class to build an element structure using a custom XML parser, or a parser for some other XML-like format. element_factory, when given, must be a callable accepting two positional arguments: a tag and a dict of attributes. It is expected to return a new element instance.

close()

Flushes the builder buffers, and returns the toplevel document element. Returns an Element instance.

data(data)

Adds text to the current element. data is a string. This should be either a bytestring, or a Unicode string.

end(tag)

Closes the current element. tag is the element name. Returns the closed element.

start(tag, attrs)

Opens a new element. tag is the element name. attrs is a dictionary containing element attributes. Returns the opened element.

In addition, a custom TreeBuilder object can provide the following method:

doctype(name, pubid, system)

Handles a doctype declaration. name is the doctype name. pubid is the public identifier. system is the system identifier. This method does not exist on the default TreeBuilder class.

버전 3.2에 추가.

XMLParser Objects

class xml.etree.ElementTree.XMLParser(html=0, target=None, encoding=None)

This class is the low-level building block of the module. It uses xml.parsers.expat for efficient, event-based parsing of XML. It can be fed XML data incrementally with the feed() method, and parsing events are translated to a push API - by invoking callbacks on the target object. If target is omitted, the standard TreeBuilder is used. The html argument was historically used for backwards compatibility and is now deprecated. If encoding 1 is given, the value overrides the encoding specified in the XML file.

버전 3.4부터 폐지: The html argument. The remaining arguments should be passed via keyword to prepare for the removal of the html argument.

close()

Finishes feeding data to the parser. Returns the result of calling the close() method of the target passed during construction; by default, this is the toplevel document element.

doctype(name, pubid, system)

버전 3.2부터 폐지: Define the TreeBuilder.doctype() method on a custom TreeBuilder target.

feed(data)

Feeds data to the parser. data is encoded data.

XMLParser.feed() calls target’s start(tag, attrs_dict) method for each opening tag, its end(tag) method for each closing tag, and data is processed by method data(data). XMLParser.close() calls target’s method close(). XMLParser can be used not only for building a tree structure. This is an example of counting the maximum depth of an XML file:

>>> from xml.etree.ElementTree import XMLParser
>>> class MaxDepth:                     # The target object of the parser
...     maxDepth = 0
...     depth = 0
...     def start(self, tag, attrib):   # Called for each opening tag.
...         self.depth += 1
...         if self.depth > self.maxDepth:
...             self.maxDepth = self.depth
...     def end(self, tag):             # Called for each closing tag.
...         self.depth -= 1
...     def data(self, data):
...         pass            # We do not need to do anything with data.
...     def close(self):    # Called when all data has been parsed.
...         return self.maxDepth
...
>>> target = MaxDepth()
>>> parser = XMLParser(target=target)
>>> exampleXml = """
... <a>
...   <b>
...   </b>
...   <b>
...     <c>
...       <d>
...       </d>
...     </c>
...   </b>
... </a>"""
>>> parser.feed(exampleXml)
>>> parser.close()
4

XMLPullParser Objects

class xml.etree.ElementTree.XMLPullParser(events=None)

A pull parser suitable for non-blocking applications. Its input-side API is similar to that of XMLParser, but instead of pushing calls to a callback target, XMLPullParser collects an internal list of parsing events and lets the user read from it. events is a sequence of events to report back. The supported events are the strings "start", "end", "start-ns" and "end-ns" (the “ns” events are used to get detailed namespace information). If events is omitted, only "end" events are reported.

feed(data)

Feed the given bytes data to the parser.

close()

Signal the parser that the data stream is terminated. Unlike XMLParser.close(), this method always returns None. Any events not yet retrieved when the parser is closed can still be read with read_events().

read_events()

Return an iterator over the events which have been encountered in the data fed to the parser. The iterator yields (event, elem) pairs, where event is a string representing the type of event (e.g. "end") and elem is the encountered Element object.

Events provided in a previous call to read_events() will not be yielded again. Events are consumed from the internal queue only when they are retrieved from the iterator, so multiple readers iterating in parallel over iterators obtained from read_events() will have unpredictable results.

참고

XMLPullParser only guarantees that it has seen the “>” character of a starting tag when it emits a “start” event, so the attributes are defined, but the contents of the text and tail attributes are undefined at that point. The same applies to the element children; they may or may not be present.

If you need a fully populated element, look for “end” events instead.

버전 3.4에 추가.

Exceptions

class xml.etree.ElementTree.ParseError

XML parse error, raised by the various parsing methods in this module when parsing fails. The string representation of an instance of this exception will contain a user-friendly error message. In addition, it will have the following attributes available:

code

A numeric error code from the expat parser. See the documentation of xml.parsers.expat for the list of error codes and their meanings.

position

A tuple of line, column numbers, specifying where the error occurred.

Footnotes

1(1,2,3,4)

The encoding string included in XML output should conform to the appropriate standards. For example, “UTF-8” is valid, but “UTF8” is not. See https://www.w3.org/TR/2006/REC-xml11-20060816/#NT-EncodingDecl and https://www.iana.org/assignments/character-sets/character-sets.xhtml.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

구조화된 마크업 처리 도구 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

구조화된 마크업 처리 도구 »

|

xml.dom — 문서 객체 모델 API

소스 코드: Lib/xml/dom/__init__.py [https://github.com/python/cpython/tree/3.7/Lib/xml/dom/__init__.py]

문서 객체 모델(Document Object Model), 또는 “DOM”은 XML 문서를 액세스하고 수정하기 위한 W3C(World Wide Web Consortium)의 교차 언어 API입니다. DOM 구현은 XML 문서를 트리 구조로 나타내거나, 클라이언트 코드가 이러한 구조를 처음부터 구축 할 수 있도록 합니다. 그런 다음 잘 알려진 인터페이스를 제공하는 객체 집합을 통해 구조에 액세스 할 수 있습니다.

DOM은 무작위 액세스 응용 프로그램에 매우 유용합니다. SAX에서는 한 번에 한 조각의 문서만 볼 수 있습니다. 하나의 SAX 요소를 보고 있는 동안, 다른 SAX 요소에 액세스할 수 없습니다. 텍스트 노드를 보고 있으면, 이것을 포함하는 요소에 액세스할 수 없습니다. SAX 응용 프로그램을 작성할 때는, 문서에서의 프로그램의 위치를 자신의 코드 어딘가에서 추적해야 합니다. SAX는 여러분을 위해 대신해주지 않습니다. 또한, XML 문서를 미리 보아야 한다면, 운이 다했다고 보아야 합니다.

트리에 액세스할 수 없는 이벤트 중심 모델에서는 일부 응용 프로그램이 불가능합니다. 물론 SAX 이벤트에서 트리를 직접 만들 수는 있지만, DOM을 사용하면 그런 코드를 작성하지 않아도 됩니다. DOM은 XML 데이터의 표준 트리 표현입니다.

문서 객체 모델은 W3C에 의해 단계적으로 또는 그들의 용어로는 “수준”으로 정의됩니다. API의 파이썬 매핑은 실질적으로 DOM 수준 2 권장 사항을 기반으로 합니다.

DOM 응용 프로그램은 일반적으로 일부 XML을 DOM으로 구문 분석하는 것으로 시작합니다. 이것을 달성하는 방법은 DOM 수준 1은 전혀 다루지 않으며, 수준 2는 제한된 개선만을 제공합니다: Document 생성 메서드에 대한 액세스를 제공하는 DOMImplementation 객체 클래스가 있습니다만, 구현에 독립적인 방법으로 XML 판독기(reader)/기록기(writer)/Document 구축기(builder)를 액세스하는 방법이 없습니다. 기존 Document 객체 없이 이러한 메서드에 액세스할 수 있는 잘 정의된 방법도 없습니다. 파이썬에서, 각 DOM 구현은 getDOMImplementation() 함수를 제공합니다. DOM 수준 3은 판독기(reader)에 대한 인터페이스를 정의하는 로드/저장 명세를 추가하지만, 아직 파이썬 표준 라이브러리에서는 사용할 수 없습니다.

일단 DOM 문서 객체가 있으면, 프로퍼티와 메서드를 통해 XML 문서의 일부에 액세스 할 수 있습니다. 이러한 프로퍼티는 DOM 명세에 정의되어 있습니다; 레퍼런스 설명서의 이 부분은 파이썬이 명세를 해석하는 방법을 설명합니다.

W3C에서 제공하는 명세는 Java, ECMAScript 및 OMG IDL 용 DOM API를 정의합니다. 여기에 정의된 파이썬 매핑은 대부분 명세의 IDL 버전을 기반으로 하지만, 엄격한 준수는 필요하지 않습니다 (구현은 IDL의 엄격한 매핑을 자유롭게 지원할 수 있습니다). 매핑 요구 사항에 대한 자세한 내용은 규격 준수 절을 참조하십시오.

더 보기

Document Object Model (DOM) Level 2 Specification [https://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/]

파이썬 DOM API의 기반이 되는 W3C 권장 사항.

Document Object Model (DOM) Level 1 Specification [https://www.w3.org/TR/REC-DOM-Level-1/]

xml.dom.minidom이 지원하는 DOM에 대한 W3C 권장 사항.

Python Language Mapping Specification [http://www.omg.org/cgi-bin/doc?formal/02-11-05.pdf]

OMG IDL에서 파이썬으로의 매핑을 지정합니다.

모듈 내용

xml.dom에는 다음 함수가 포함되어 있습니다:

xml.dom.registerDOMImplementation(name, factory)

factory 함수를 name이라는 이름으로 등록합니다. 팩토리(factory) 함수는 DOMImplementation 인터페이스를 구현하는 객체를 반환해야 합니다. 팩토리 함수는 호출 때마다 같은 객체를 반환하거나 특정 구현에 적합하다면 새 객체를 반환할 수 있습니다 (예를 들어, 해당 구현이 일부 사용자 정의를 지원하는 경우).

xml.dom.getDOMImplementation(name=None, features=())

적절한 DOM 구현을 반환합니다. name은 잘 알려진 DOM 구현의 모듈 이름이거나, None입니다. None이 아니면, 해당 모듈을 임포트하고 성공하면 DOMImplementation 객체를 반환합니다. 이름이 지정되지 않고, 환경 변수 PYTHON_DOM이 설정되면, 이 변수를 구현을 찾는 데 사용합니다.

이름을 지정하지 않으면, 사용 가능한 구현을 검사하여 필요한 기능 집합이 있는 구현을 찾습니다. 구현을 찾을 수 없으면, ImportError를 발생시킵니다. 기능 목록은 사용 가능한 DOMImplementation 객체의 hasFeature() 메서드로 전달되는 (feature, version) 쌍의 시퀀스여야 합니다.

몇 가지 편의 상수도 제공됩니다:

xml.dom.EMPTY_NAMESPACE

이름 공간이 DOM의 노드와 연결되어 있지 않음을 나타내는 데 사용되는 값. 이것은 일반적으로 노드의 namespaceURI에서 발견되거나, 이름 공간별 메서드에 대한 namespaceURI 매개 변수로 사용됩니다.

xml.dom.XML_NAMESPACE

예약된 접두어 xml과 연관된 이름 공간 URI, Namespaces in XML <https://www.w3.org/TR/REC-xml-names/>에서 정의됩니다 (4절).

xml.dom.XMLNS_NAMESPACE

이름 공간 선언의 이름 공간 URI, Document Object Model (DOM) Level 2 Core Specification [https://www.w3.org/TR/DOM-Level-2-Core/core.html]에서 정의됩니다 (1.1.8 절).

xml.dom.XHTML_NAMESPACE

XHTML 이름 공간의 URI, XHTML 1.0: The Extensible HyperText Markup Language [https://www.w3.org/TR/xhtml1/]에서 정의됩니다 (3.1.1 절).

또한, xml.dom에는 베이스 Node 클래스와 DOM 예외 클래스가 포함됩니다. 이 모듈에서 제공하는 Node 클래스는 DOM 명세에 정의된 메서드나 어트리뷰트를 구현하지 않습니다; 구상(concrete) DOM 구현이 이를 제공해야 합니다. 이 모듈의 일부로 제공되는 Node 클래스는 구상 Node 객체의 nodeType 어트리뷰트에 사용되는 상수를 제공합니다; 그것들은 DOM 명세를 준수하기 위해 모듈 수준이 아니라 클래스 내에 위치합니다.

DOM의 객체

DOM에 대한 결정적인 문서는 W3C의 DOM 명세입니다.

DOM 어트리뷰트는 간단한 문자열 대신 노드로 조작될 수도 있음에 유의하십시오. 하지만 그렇게 해야만 하는 경우는 매우 드물어서, 이 사용법은 아직 문서화되지 않았습니다.

인터페이스

절

목적

DOMImplementation

DOMImplementation 객체

하부 구현에 대한 인터페이스.

Node

Node 객체

문서에 있는 대부분 객체에 대한 베이스 인터페이스.

NodeList

NodeList 객체

노드의 시퀀스를 위한 인터페이스.

DocumentType

DocumentType 객체

문서를 처리하는 데 필요한 선언에 대한 정보.

Document

Document 객체

전체 문서를 나타내는 객체.

Element

Element 객체

문서 계층의 엘리먼트 노드.

Attr

Attr 객체

엘리먼트 노드의 어트리뷰트 값 노드

Comment

Comment 객체

소스 문서에 있는 주석의 표현.

Text

Text와 CDATASection 객체

문서의 텍스트 내용을 포함하는 노드.

ProcessingInstruction

ProcessingInstruction 객체

처리 명령어 표현.

추가 절에서 파이썬에서 DOM 작업을 위해 정의된 예외에 관해 설명합니다.

DOMImplementation 객체

DOMImplementation 인터페이스는 응용 프로그램이 사용 중인 DOM에서 특정 기능의 가용성을 판별할 방법을 제공합니다. DOM 수준 2는 DOMImplementation을 사용하여 새로운 Document와 DocumentType 객체를 만드는 기능을 추가했습니다.

DOMImplementation.hasFeature(feature, version)

Return True if the feature identified by the pair of strings feature and version is implemented.

DOMImplementation.createDocument(namespaceUri, qualifiedName, doctype)

지정된 namespaceUri와 qualifiedName을 가진 자식 Element 객체를 포함하는 새 Document 객체(DOM의 루트)를 반환합니다. doctype은 createDocumentType()으로 만든 DocumentType 객체거나 None이어야 합니다. 파이썬 DOM API에서, Element 자식이 만들어지지 않음을 표시하기 위해 처음 두 인자는 None일 수 있습니다.

DOMImplementation.createDocumentType(qualifiedName, publicId, systemId)

XML 문서 형 선언에 포함된 정보를 나타내는, 지정된 qualifiedName, publicId 및 systemId 문자열을 캡슐화하는 새 DocumentType 객체를 반환합니다.

Node 객체

XML 문서의 모든 구성 요소는 Node의 서브 클래스입니다.

Node.nodeType

노드 형을 나타내는 정수. 형의 기호 상수는 Node 객체에 있습니다: ELEMENT_NODE, ATTRIBUTE_NODE, TEXT_NODE, CDATA_SECTION_NODE, ENTITY_NODE, PROCESSING_INSTRUCTION_NODE, COMMENT_NODE, DOCUMENT_NODE, DOCUMENT_TYPE_NODE, NOTATION_NODE. 이것은 읽기 전용 어트리뷰트입니다.

Node.parentNode

현재 노드의 부모, 또는 문서 노드의 경우 None. 값은 항상 Node 객체나 None입니다. Element 노드의 경우, 이것은 부모 엘리먼트가 되는데, 루트 엘리먼트는 예외로, 이때는 Document 객체가 됩니다. Attr 노드의 경우, 항상 None입니다. 이것은 읽기 전용 어트리뷰트입니다.

Node.attributes

어트리뷰트 객체의 NamedNodeMap. 엘리먼트에만 실제 값이 있습니다; 다른 것은 이 어트리뷰트에서 None을 제공합니다. 이것은 읽기 전용 어트리뷰트입니다.

Node.previousSibling

같은 부모를 갖고 이 노드 바로 앞에 있는 노드. 예를 들어 self 엘리먼트의 시작 태그 바로 앞에 오는 종료 태그의 엘리먼트. 물론, XML 문서는 단순히 엘리먼트만으로 구성되지 않기 때문에, 이전 형제(previous sibling)는 텍스트, 주석 또는 뭔가 다른 것이 될 수 있습니다. 이 노드가 부모의 첫 번째 자식이면, 이 어트리뷰트는 None입니다. 이것은 읽기 전용 어트리뷰트입니다.

Node.nextSibling

같은 부모를 갖고 이 노드 바로 뒤에 나오는 노드. previousSibling도 참조하십시오. 이것이 부모의 마지막 자식이면, 이 어트리뷰트는 None입니다. 이것은 읽기 전용 어트리뷰트입니다.

Node.childNodes

이 노드에 포함된 노드의 리스트. 이것은 읽기 전용 어트리뷰트입니다.

Node.firstChild

노드의 첫 번째 자식 (있다면), 또는 None. 이것은 읽기 전용 어트리뷰트입니다.

Node.lastChild

노드의 마지막 자식 (있다면), 또는 None. 이것은 읽기 전용 어트리뷰트입니다.

Node.localName

콜론이 있으면 그 뒤에 오는 tagName의 부분, 그렇지 않으면 전체 tagName. 값은 문자열입니다.

Node.prefix

콜론이 있으면 그 앞에 오는 tagName의 부분, 그렇지 않으면 빈 문자열. 값은 문자열이나 None입니다.

Node.namespaceURI

엘리먼트 이름과 연관된 이름 공간. 이것은 문자열이나 None입니다. 이것은 읽기 전용 어트리뷰트입니다.

Node.nodeName

이는 각 노드 형마다 다른 의미입니다; 자세한 내용은 DOM 명세를 참조하십시오. 여기서 얻는 정보를 항상 다른 프로퍼티에서 얻을 수 있습니다, 가령 엘리먼트의 tagName 프로퍼티나 어트리뷰트의 name 프로퍼티. 모든 노드 형에서, 이 어트리뷰트의 값은 문자열이나 None입니다. 이것은 읽기 전용 어트리뷰트입니다.

Node.nodeValue

이는 각 노드 형마다 다른 의미입니다; 자세한 내용은 DOM 명세를 참조하십시오. 상황은 nodeName과 유사합니다. 값은 문자열이나 None입니다.

Node.hasAttributes()

Return True if the node has any attributes.

Node.hasChildNodes()

Return True if the node has any child nodes.

Node.isSameNode(other)

Return True if other refers to the same node as this node. This is especially useful for DOM implementations which use any sort of proxy architecture (because more than one object can refer to the same node).

참고

이것은 여전히 “작업 초안” 단계에 있는 제안된 DOM 수준 3 API를 기반으로 하지만, 이 특정 인터페이스는 논란의 여지가 없는 것으로 보입니다. W3C의 변경 사항이 파이썬 DOM 인터페이스에서 이 메서드에 반드시 영향을 미치는 것은 아닙니다 (이를 위한 새 W3C API도 지원되기는 하겠지만).

Node.appendChild(newChild)

자식 리스트의 끝에 이 노드의 새 자식 노드를 추가하고, newChild를 반환합니다. 노드가 이미 트리에 있으면, 먼저 제거됩니다.

Node.insertBefore(newChild, refChild)

기존 자식 앞에 새 자식 노드를 삽입합니다. refChild가 이 노드의 자식이어야 합니다; 그렇지 않으면 ValueError가 발생합니다. newChild가 반환됩니다. refChild가 None이면, 자식 리스트의 끝에 newChild를 삽입합니다.

Node.removeChild(oldChild)

자식 노드를 제거합니다. oldChild는 이 노드의 자식이어야 합니다; 그렇지 않으면, ValueError가 발생합니다. 성공하면 oldChild가 반환됩니다. oldChild가 더는 사용되지 않으면, 그것의 unlink() 메서드를 호출해야 합니다.

Node.replaceChild(newChild, oldChild)

기존 노드를 새 노드로 교체합니다. oldChild는 이 노드의 자식이어야 합니다. 그렇지 않으면, ValueError가 발생합니다.

Node.normalize()

모든 텍스트 스트레치(stretch)가 단일 Text 인스턴스로 저장되도록, 인접한 텍스트 노드를 결합합니다. 이는 많은 응용 프로그램에서 DOM 트리의 텍스트 처리를 단순화합니다.

Node.cloneNode(deep)

이 노드를 복제합니다. deep을 설정하면 모든 자식 노드도 복제됩니다. 복제를 반환합니다.

NodeList 객체

NodeList는 노드의 시퀀스를 나타냅니다. 이러한 객체는 DOM Core 권장 사항에서 두 가지 방식으로 사용됩니다: Element 객체는 자식 노드의 리스트를 제공하고, Node의 getElementsByTagName()과 getElementsByTagNameNS() 메서드는 이 인터페이스를 사용하여 조회 결과를 나타냅니다.

DOM 수준 2 권장 사항은 이러한 객체에 대해 하나의 메서드와 하나의 어트리뷰트를 정의합니다:

NodeList.item(i)

시퀀스의 i 번째 항목(있다면)이나 None을 반환합니다. 인덱스 i는 0보다 작거나 시퀀스의 길이보다 크거나 같을 수 없습니다.

NodeList.length

시퀀스의 노드 수.

또한, 파이썬 DOM 인터페이스는 NodeList 객체를 파이썬 시퀀스로 사용할 수 있도록 몇 가지 추가 지원을 요구합니다. 모든 NodeList 구현에는 __len__()과 __getitem__()에 대한 지원이 포함되어야 합니다; 이를 통해 for 문에서 NodeList를 이터레이트할 수 있고, len() 내장 함수를 적절히 지원할 수 있습니다.

DOM 구현이 문서 수정을 지원하면, NodeList 구현은 __setitem__()과 __delitem__() 메서드도 지원해야 합니다.

DocumentType 객체

문서에 의해 선언된 표기법과 엔티티에 대한 정보(구문 분석기가 사용하고 정보를 제공할 수 있으면 외부 부분 집합(external subset)을 포함하는)는 DocumentType 객체에서 사용 가능합니다. 문서의 DocumentType은 Document 객체의 doctype 어트리뷰트에서 사용 가능합니다; 문서에 DOCTYPE 선언이 없으면, 문서의 doctype 어트리뷰트는 이 인터페이스의 인스턴스 대신 None으로 설정됩니다.

DocumentType은 Node의 특수화(specialization)이고 다음 어트리뷰트를 추가합니다:

DocumentType.publicId

문서 형 정의의 외부 부분 집합(external subset)에 대한 공용 식별자. 문자열이나 None입니다.

DocumentType.systemId

문서 형 정의의 외부 부분 집합(external subset)에 대한 시스템 식별자. 문자열로 표현된 URI이거나 None입니다.

DocumentType.internalSubset

문서에서 완전한 내부 부분 집합(internal subset)을 제공하는 문자열. 부분 집합을 묶는 대괄호는 포함되지 않습니다. 문서에 내부 부분 집합이 없으면 None이어야 합니다.

DocumentType.name

DOCTYPE 선언에 제공된 루트 엘리먼트의 이름 (있다면).

DocumentType.entities

외부 엔터티의 정의를 제공하는 NamedNodeMap입니다. 엔티티 이름이 두 번 이상 정의되면, 첫 번째 정의 만 제공됩니다 (XML 권장 사항에 따라 다른 정의는 무시됩니다). 구문 분석기가 정보를 제공하지 않거나 정의된 엔터티가 없으면 None일 수 있습니다.

DocumentType.notations

표기법의 정의를 제공하는 NamedNodeMap입니다. 표기법 이름이 두 번 이상 정의되면, 첫 번째 정의 만 제공됩니다 (XML 권장 사항에 따라 다른 정의는 무시됩니다). 구문 분석기가 정보를 제공하지 않거나 정의된 표기법이 없으면 None일 수 있습니다.

Document 객체

Document는 구성 엘리먼트, 어트리뷰트, 처리 명령어, 주석 등을 포함한 전체 XML 문서를 나타냅니다. Node의 프로퍼티를 상속한다는 점을 기억하십시오.

Document.documentElement

문서의 유일한 루트 엘리먼트.

Document.createElement(tagName)

새 엘리먼트 노드를 만들고 반환합니다. 엘리먼트는 만들어질 때 문서에 삽입되지 않습니다. insertBefore()나 appendChild()와 같은 다른 메서드 중 하나를 사용하여 명시적으로 삽입해야 합니다.

Document.createElementNS(namespaceURI, tagName)

이름 공간을 사용하여 새 엘리먼트를 만들고 반환합니다. tagName은 접두사를 가질 수 있습니다. 엘리먼트는 만들어질 때 문서에 삽입되지 않습니다. insertBefore()나 appendChild()와 같은 다른 메서드 중 하나를 사용하여 명시적으로 삽입해야 합니다.

Document.createTextNode(data)

매개 변수로 전달된 data를 포함하는 텍스트 노드를 만들고 반환합니다. 다른 생성 메서드와 마찬가지로 이 메서드는 노드를 트리에 삽입하지 않습니다.

Document.createComment(data)

매개 변수로 전달된 data를 포함하는 주석 노드를 만들고 반환합니다. 다른 생성 메서드와 마찬가지로 이 메서드는 노드를 트리에 삽입하지 않습니다.

Document.createProcessingInstruction(target, data)

매개 변수로 전달된 target과 data를 포함하는 처리 명령어 노드를 만들고 반환합니다. 다른 생성 메서드와 마찬가지로 이 메서드는 노드를 트리에 삽입하지 않습니다.

Document.createAttribute(name)

어트리뷰트 노드를 만들고 반환합니다. 이 메서드는 어트리뷰틀 노드를 특정 엘리먼트와 연관시키지 않습니다. 새로 만들어진 어트리뷰트 인스턴스를 사용하려면 적절한 Element 객체에서 setAttributeNode()를 사용해야 합니다.

Document.createAttributeNS(namespaceURI, qualifiedName)

이름 공간을 사용하여 어트리뷰트 노드를 만들고 반환합니다. tagName은 접두사를 가질 수 있습니다. 이 메서드는 어트리뷰트 노드를 특정 엘리먼트와 연관시키지 않습니다. 새로 만들어진 어트리뷰트 인스턴스를 사용하려면 적절한 Element 객체에서 setAttributeNode()를 사용해야합니다.

Document.getElementsByTagName(tagName)

특정 엘리먼트 형 이름을 가진 모든 자손(직계 자식, 자식의 자식 등)을 검색합니다.

Document.getElementsByTagNameNS(namespaceURI, localName)

특정 이름 공간 URI와 지역 이름(localname)을 사용하여 모든 자손(직계 자식, 자식의 자식 등)을 검색합니다. 지역 이름은 접두사 다음에 나오는 이름 공간의 일부입니다.

Element 객체

Element는 Node의 서브 클래스이므로, 모든 어트리뷰트를 상속합니다.

Element.tagName

엘리먼트 형 이름. 이름 공간을 사용하는 문서에서는 콜론을 포함할 수 있습니다. 값은 문자열입니다.

Element.getElementsByTagName(tagName)

Document 클래스의 동등한 메서드와 같습니다.

Element.getElementsByTagNameNS(namespaceURI, localName)

Document 클래스의 동등한 메서드와 같습니다.

Element.hasAttribute(name)

Return True if the element has an attribute named by name.

Element.hasAttributeNS(namespaceURI, localName)

Return True if the element has an attribute named by namespaceURI and localName.

Element.getAttribute(name)

name이라는 이름의 어트리뷰트의 값을 문자열로 반환합니다. 그러한 어트리뷰트가 없으면, 어트리뷰트에 값이 없는 것처럼 빈 문자열이 반환됩니다.

Element.getAttributeNode(attrname)

attrname이라는 이름의 어트리뷰트에 대한 Attr 노드를 반환합니다.

Element.getAttributeNS(namespaceURI, localName)

namespaceURI와 localName으로 이름이 지정된 어트리뷰트의 값을 문자열로 반환합니다. 그러한 어트리뷰트가 없으면, 어트리뷰트에 값이 없는 것처럼 빈 문자열이 반환됩니다.

Element.getAttributeNodeNS(namespaceURI, localName)

namespaceURI와 localName으로 주어진 어트리뷰트의 값을 노드로 반환합니다.

Element.removeAttribute(name)

이름(name)으로 어트리뷰트를 제거합니다. 일치하는 어트리뷰트가 없으면 NotFoundErr가 발생합니다.

Element.removeAttributeNode(oldAttr)

존재하면, 어트리뷰트 목록에서 oldAttr를 제거하고 반환합니다. oldAttr가 없으면 NotFoundErr가 발생합니다.

Element.removeAttributeNS(namespaceURI, localName)

이름으로 어트리뷰트를 제거합니다. qname이 아닌 localName을 사용함에 유의하십시오. 일치하는 어트리뷰트가 없어도 예외가 발생하지 않습니다.

Element.setAttribute(name, value)

문자열로 어트리뷰트 값을 설정합니다.

Element.setAttributeNode(newAttr)

엘리먼트에 새 어트리뷰트 노드를 추가합니다. name 어트리뷰트가 일치할 때 필요하면 기존 어트리뷰트를 대체합니다. 대체가 발생하면, 이전 어트리뷰트 노드가 반환됩니다. newAttr가 이미 사용 중이면 InuseAttributeErr가 발생합니다.

Element.setAttributeNodeNS(newAttr)

엘리먼트에 새 어트리뷰트 노드를 추가합니다. namespaceURI와 localName 어트리뷰트가 일치할 때 필요하면 기존 어트리뷰트를 대체합니다. 대체가 발생하면 이전 어트리뷰트 노드가 반환됩니다. newAttr가 이미 사용 중이면 InuseAttributeErr가 발생합니다.

Element.setAttributeNS(namespaceURI, qname, value)

문자열로 namespaceURI와 qname으로 지정된 어트리뷰트 값을 설정합니다. qname은 전체 어트리뷰트 이름임에 유의하십시오. 이것은 위와 다릅니다.

Attr 객체

Attr은 Node를 상속하므로, 모든 어트리뷰트를 상속합니다.

Attr.name

어트리뷰트 이름. 이름 공간을 사용하는 문서에서는 콜론을 포함할 수 있습니다.

Attr.localName

콜론이 있으면 그 뒤에 오는 이름의 일부, 그렇지 않으면 전체 이름. 이것은 읽기 전용 어트리뷰트입니다.

Attr.prefix

콜론이 있으면 그 앞에 오는 이름의 일부, 그렇지 않으면 빈 문자열.

Attr.value

어트리뷰트의 텍스트 값. 이것은 nodeValue 어트리뷰트의 동의어입니다.

NamedNodeMap 객체

NamedNodeMap은 Node를 상속하지 않습니다.

NamedNodeMap.length

어트리뷰트 목록의 길이입니다.

NamedNodeMap.item(index)

특정 인덱스에 있는 어트리뷰트를 반환합니다. 어트리뷰트를 얻는 순서는 임의적이지만 DOM 수명 동안 일관적입니다. 각 항목은 어트리뷰트 노드입니다. value 어트리뷰트로 값을 얻으십시오.

이 클래스에 더 많은 매핑 동작을 제공하는 실험적인 메서드도 있습니다. 이를 사용하거나 Element 객체에서 표준화된 getAttribute*() 메서드 집합을 사용할 수 있습니다.

Comment 객체

Comment는 XML 문서의 주석을 나타냅니다. Node의 서브 클래스이지만, 자식 노드를 가질 수 없습니다.

Comment.data

주석의 내용을 제공하는 문자열. 이 어트리뷰트는 선행 <!--와 후행 --> 사이의 모든 문자를 포함하지만, 이들을 포함하지는 않습니다.

Text와 CDATASection 객체

Text 인터페이스는 XML 문서의 텍스트를 나타냅니다. 구문 분석기와 DOM 구현이 DOM의 XML 확장을 지원하면, CDATA로 표시된 섹션으로 묶인 텍스트 부분은 CDATASection 객체에 저장됩니다. 이 두 인터페이스는 같지만, nodeType 어트리뷰트에서 다른 값을 제공합니다.

이 인터페이스는 Node 인터페이스를 확장합니다. 자식 노드를 가질 수 없습니다.

Text.data

문자열로 표현된 텍스트 노드의 내용.

참고

CDATASection 노드의 사용이 그 노드가 완전한 CDATA 표시 섹션을 표현한다고 나타내는 것은 아닙니다, 단지 노드의 내용이 CDATA 섹션의 일부임을 나타낼 뿐입니다. 단일 CDATA 섹션은 문서 트리에서 둘 이상의 노드로 표현될 수 있습니다. 인접한 두 개의 CDATASection 노드가 다른 CDATA 표시 섹션을 나타내는지를 확인할 방법은 없습니다.

ProcessingInstruction 객체

XML 문서의 처리 명령어를 나타냅니다; 이것은 Node 인터페이스를 상속하며 자식 노드를 가질 수 없습니다.

ProcessingInstruction.target

첫 번째 공백 문자까지의 처리 명령어의 내용. 이것은 읽기 전용 어트리뷰트입니다.

ProcessingInstruction.data

첫 번째 공백 문자 다음에 오는 처리 명령어의 내용.

예외

DOM 수준 2 권장 사항은 단일 예외 DOMException과 응용 프로그램이 어떤 종류의 에러가 발생했는지 판별하도록 하는 여러 상수를 정의합니다. DOMException 인스턴스에는 구체적인 예외에 적절한 값을 제공하는 code 어트리뷰트가 있습니다.

파이썬 DOM 인터페이스는 상수를 제공하지만, 동시에 예외 집합을 확장하여 DOM에 의해 정의된 각 예외 코드마다 구체적인 예외가 존재하도록 합니다. 구현 시 적절한 구체적인 예외를 발생시켜야 하며, 각 예외는 code 속성으로 적절한 값을 제공합니다.

exception xml.dom.DOMException

모든 구체적인 DOM 예외에 사용되는 베이스 예외 클래스. 이 예외 클래스는 직접 인스턴스 화할 수 없습니다.

exception xml.dom.DomstringSizeErr

지정된 텍스트 범위가 문자열에 맞지 않을 때 발생합니다. 이것은 파이썬 DOM 구현에서 사용되는 것으로 알려지지 않았지만, 파이썬으로 작성되지 않은 DOM 구현에서 수신될 수 있습니다.

exception xml.dom.HierarchyRequestErr

노드 형이 허용하지 않는 곳에 노드를 삽입하려고 할 때 발생합니다.

exception xml.dom.IndexSizeErr

메서드의 인덱스(index)나 크기(size) 매개 변수가 음수이거나 허용된 값을 초과할 때 발생합니다.

exception xml.dom.InuseAttributeErr

문서의 다른 곳에 이미 존재하는 Attr 노드를 삽입하려고 할 때 발생합니다.

exception xml.dom.InvalidAccessErr

하부 객체에서 매개 변수나 연산이 지원되지 않으면 발생합니다.

exception xml.dom.InvalidCharacterErr

이 예외는 문자열 매개 변수에 XML 1.0 권장 사항에서 사용 중인 컨텍스트에서 허용되지 않는 문자가 포함될 때 발생합니다. 예를 들어, 엘리먼트 형 이름에 스페이스가 있는 Element 노드를 만들려고 하면 이 에러가 발생합니다.

exception xml.dom.InvalidModificationErr

노드 형을 수정하려고 할 때 발생합니다.

exception xml.dom.InvalidStateErr

정의되지 않았거나 더는 사용할 수 없는 객체를 사용하려고 할 때 발생합니다.

exception xml.dom.NamespaceErr

Namespaces in XML [https://www.w3.org/TR/REC-xml-names/] 권장 사항에서 허용되지 않는 방식으로 객체를 변경하려고 시도하면 이 예외가 발생합니다.

exception xml.dom.NotFoundErr

참조된 컨텍스트에 노드가 존재하지 않을 때 발생하는 예외. 예를 들어, NamedNodeMap.removeNamedItem()은 전달된 노드가 맵에 존재하지 않으면 이것을 발생시킵니다.

exception xml.dom.NotSupportedErr

구현이 요청된 형의 객체나 연산을 지원하지 않을 때 발생합니다.

exception xml.dom.NoDataAllowedErr

데이터를 지원하지 않는 노드에 데이터가 지정되면 발생합니다.

exception xml.dom.NoModificationAllowedErr

수정이 허용되지 않는 객체(가령 읽기 전용 노드)를 수정하려고 하면 발생합니다.

exception xml.dom.SyntaxErr

유효하지 않거나 잘못된 문자열이 지정될 때 발생합니다.

exception xml.dom.WrongDocumentErr

노드가 현재 속한 것과 다른 문서에 삽입되고 구현이 한 문서에서 다른 문서로 노드 이전을 지원하지 않을 때 발생합니다.

DOM 권장 사항에 정의된 예외 코드는 이 테이블에 따라 위에서 설명한 예외에 매핑됩니다:

상수

예외

DOMSTRING_SIZE_ERR

DomstringSizeErr

HIERARCHY_REQUEST_ERR

HierarchyRequestErr

INDEX_SIZE_ERR

IndexSizeErr

INUSE_ATTRIBUTE_ERR

InuseAttributeErr

INVALID_ACCESS_ERR

InvalidAccessErr

INVALID_CHARACTER_ERR

InvalidCharacterErr

INVALID_MODIFICATION_ERR

InvalidModificationErr

INVALID_STATE_ERR

InvalidStateErr

NAMESPACE_ERR

NamespaceErr

NOT_FOUND_ERR

NotFoundErr

NOT_SUPPORTED_ERR

NotSupportedErr

NO_DATA_ALLOWED_ERR

NoDataAllowedErr

NO_MODIFICATION_ALLOWED_ERR

NoModificationAllowedErr

SYNTAX_ERR

SyntaxErr

WRONG_DOCUMENT_ERR

WrongDocumentErr

규격 준수

이 섹션에서는 규격 준수 요구 사항과 파이썬 DOM API, W3C DOM 권장 사항 및 파이썬의 OMG IDL 매핑 간의 관계에 관해 설명합니다.

형 매핑

DOM 명세에 사용된 IDL 형은 다음 표에 따라 파이썬 형에 매핑됩니다.

IDL 형

파이썬 형

boolean

bool 또는 int

int

int

long int

int

unsigned int

int

DOMString

str 또는 bytes

null

None

접근자 메서드

OMG IDL에서 파이썬으로의 매핑은 Java 매핑과 거의 같은 방식으로 IDL attribute 선언에 대한 접근자 함수를 정의합니다. 다음과 같은 IDL 선언 매핑은:

readonly attribute string someValue;
         attribute string anotherValue;

세 개의 접근자 함수를 산출합니다: someValue를 위한 “get” 메서드(_get_someValue())와 anotherValue를 위한 “get”과 “set” 메서드(_get_anotherValue()와 _set_anotherValue()). 특히, 매핑은 IDL 어트리뷰트가 일반 파이썬 어트리뷰트로 액세스할 수 있도록 요구하지 않습니다: object.someValue는 작동할 필요 없으며, AttributeError를 발생시킬 수 있습니다.

그러나, 파이썬 DOM API는 일반 어트리뷰트 액세스가 동작하도록 요구합니다. 이것은 파이썬 IDL 컴파일러에 의해 생성된 일반적인 서로게이트가 작동하지 않을 수 있으며, DOM 객체가 CORBA를 통해 액세스되는 경우 래퍼 객체가 클라이언트에 필요할 수 있음을 의미합니다. CORBA DOM 클라이언트에 대해 추가적인 고려가 필요하지만, 파이썬에서 CORBA를 통해 DOM을 사용한 경험이 있는 구현자들은 이것을 문제라고 보지 않습니다. readonly로 선언된 어트리뷰트는 모든 DOM 구현에서 쓰기 액세스를 제한하지 않을 수 있습니다.

파이썬 DOM API에서는, 접근자 함수가 필요하지 않습니다. 제공되면, 파이썬 IDL 매핑으로 정의된 형식을 취해야 하지만, 어트리뷰트를 파이썬에서 직접 액세스할 수 있어서 이러한 메서드들은 불필요한 것으로 간주합니다. readonly 어트리뷰트에 “set” 접근자를 제공해서는 안 됩니다.

IDL 정의는 W3C DOM API의 요구 사항을 완전히 담지 않습니다. 가령 getElementsByTagName()의 반환 값과 같은 특정 객체가 “살아있다(live)”는 개념과 같은 것을 표현하지 못합니다. 파이썬 DOM API는 구현이 이러한 요구 사항을 강제하도록 요구하지 않습니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

구조화된 마크업 처리 도구 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

구조화된 마크업 처리 도구 »

|

xml.dom.minidom — 최소 DOM 구현

소스 코드: Lib/xml/dom/minidom.py [https://github.com/python/cpython/tree/3.7/Lib/xml/dom/minidom.py]

xml.dom.minidom은 다른 언어와 유사한 API를 갖는 문서 객체 모델 인터페이스의 최소 구현입니다. 전체(full) DOM보다 단순하고 훨씬 작고자 합니다. DOM에 아직 능숙하지 않은 사용자는 XML 처리에 대신 xml.etree.ElementTree 모듈을 사용하는 것을 고려해야 합니다.

경고

xml.dom.minidom 모듈은 악의적으로 구성된 데이터로부터 안전하지 않습니다. 신뢰할 수 없거나 인증되지 않은 데이터를 구문 분석해야 하면 XML 취약점를 참조하십시오.

DOM 응용 프로그램은 일반적으로 일부 XML을 DOM으로 구문 분석하는 것으로 시작합니다. xml.dom.minidom에서는, 구문 분석 함수를 통해 수행됩니다:

from xml.dom.minidom import parse, parseString

dom1 = parse('c:\\temp\\mydata.xml')  # parse an XML file by name

datasource = open('c:\\temp\\mydata.xml')
dom2 = parse(datasource)  # parse an open file

dom3 = parseString('<myxml>Some data<empty/> some more data</myxml>')

parse() 함수는 파일명이나 열린 파일 객체를 취할 수 있습니다.

xml.dom.minidom.parse(filename_or_file, parser=None, bufsize=None)

주어진 입력에서 Document를 반환합니다. filename_or_file은 파일명이나 파일류 객체일 수 있습니다. 제공되면, parser는 SAX2 구문 분석기 객체여야 합니다. 이 함수는 구문 분석기의 문서 처리기를 변경하고 이름 공간 지원을 활성화합니다; 다른 구문 분석기 구성(엔티티 해석기 설정과 같은)은 미리 수행되어 있어야 합니다.

문자열로 XML을 갖고 있다면, parseString() 함수를 대신 사용할 수 있습니다:

xml.dom.minidom.parseString(string, parser=None)

string을 표현하는 Document를 반환합니다. 이 메서드는 문자열에 대한 io.StringIO 객체를 만들고 이를 parse()에 전달합니다.

두 함수 모두 문서의 내용을 표현하는 Document 객체를 반환합니다.

parse()와 parseString() 함수가 하는 일은 임의의 SAX 구문 분석기에서 구문 분석 이벤트를 받아들일 수 있고 이를 DOM 트리로 변환하는 “DOM 구축기(builder)”를 XML 구문 분석기와 연결하는 것입니다. 함수의 이름은 오해의 소지가 있지만, 인터페이스를 배울 때 이해하기 쉽습니다. 이 함수가 반환되기 전에 문서 구문 분석이 완료됩니다; 단지 이 함수들이 구문 분석기 구현 자체를 제공하지는 않을 뿐입니다.

“DOM 구현” 객체의 메서드를 호출하여 Document를 만들 수도 있습니다. xml.dom 패키지나 xml.dom.minidom 모듈에 있는 getDOMImplementation() 함수를 호출하여 이 객체를 얻을 수 있습니다. 일단 Document를 얻으면, 자식 노드를 추가하여 DOM을 채울 수 있습니다:

from xml.dom.minidom import getDOMImplementation

impl = getDOMImplementation()

newdoc = impl.createDocument(None, "some_tag", None)
top_element = newdoc.documentElement
text = newdoc.createTextNode('Some textual content.')
top_element.appendChild(text)

일단 DOM 문서 객체를 얻으면, 프로퍼티와 메서드를 통해 XML 문서의 일부에 액세스 할 수 있습니다. 이러한 프로퍼티들은 DOM 명세에 정의되어 있습니다. 문서 객체의 주 프로퍼티는 documentElement 프로퍼티입니다. XML 문서의 메인 엘리먼트를 제공합니다: 모든 다른 것들을 담는 것. 예제 프로그램은 다음과 같습니다:

dom3 = parseString("<myxml>Some data</myxml>")
assert dom3.documentElement.tagName == "myxml"

DOM 트리로의 작업이 끝나면, unlink() 메서드를 선택적으로 호출하여 필요 없는 객체를 조기에 정리할 수 있습니다. unlink()는 DOM API에 대한 xml.dom.minidom만의 확장이며 그 노드와 자손들을 실질적으로 쓸모없게 만듭니다. 그렇지 않으면, 파이썬의 가비지 수집기가 결국 트리의 객체를 처리하게 될 것입니다.

더 보기

Document Object Model (DOM) Level 1 Specification [https://www.w3.org/TR/REC-DOM-Level-1/]

xml.dom.minidom이 지원하는 DOM에 대한 W3C 권장 사항.

DOM 객체

파이썬 용 DOM API의 정의는 xml.dom 모듈 설명서의 일부로 제공됩니다. 이 절은 그 API와 xml.dom.minidom의 차이점을 나열합니다.

Node.unlink()

순환 GC가 없는 파이썬 버전에서 가비지 수집되도록 DOM 내의 내부 참조를 끊습니다. 순환 GC를 사용할 수 있더라도, 이를 사용하면 대량의 메모리를 더 빨리 사용할 수 있도록 하므로, 더 필요 없게 되는 즉시 DOM 객체에 대해 이를 호출하는 것이 좋습니다. Document 객체에서만 호출하면 되지만, 해당 노드의 자식을 삭제하기 위해 자식 노드에서 호출할 수 있습니다.

with 문을 사용하면 이 메서드를 명시적으로 호출하지 않아도 됩니다. 다음 코드는 with 블록이 종료될 때 dom을 자동으로 unlink 합니다:

with xml.dom.minidom.parse(datasource) as dom:
    ... # Work with dom.

Node.writexml(writer, indent="", addindent="", newl="")

기록기(writer) 객체에 XML을 씁니다. 기록기는 입력으로 텍스트를 받지만 바이트열은 받지 않습니다, 파일 객체 인터페이스와 일치하는 write() 메서드를 가져야 합니다. indent 매개 변수는 현재 노드의 들여쓰기입니다. addindent 매개 변수는 현재 노드의 서브 노드에 사용할 증분(incremental) 들여쓰기입니다. newl 매개 변수는 개행을 끝내는 데 사용할 문자열을 지정합니다.

Document 노드의 경우, 추가 키워드 인자 encoding을 사용하여 XML 헤더의 인코딩 필드를 지정할 수 있습니다.

Node.toxml(encoding=None)

DOM 노드가 나타내는 XML이 포함된 문자열이나 바이트열을 반환합니다.

명시적인 encoding 1 인자를 사용하면, 결과는 지정된 인코딩의 바이트열 입니다. encoding 인자가 없으면, 결과는 유니코드 문자열이며, 결과 문자열의 XML 선언은 인코딩을 지정하지 않습니다. UTF-8이 XML의 기본 인코딩이기 때문에, UTF-8 이외의 인코딩으로 이 문자열을 인코딩하는 것은 올바르지 않습니다.

Node.toprettyxml(indent="\t", newl="\n", encoding=None)

문서의 예쁘게 인쇄된 버전을 반환합니다. indent는 들여쓰기 문자열을 지정하고 기본값은 탭입니다; newl은 각 줄의 끝에서 방출되는 문자열을 지정하고 기본값은 \n입니다.

encoding 인자는 toxml()의 해당 인자처럼 동작합니다.

DOM 예제

이 예제 프로그램은 간단한 프로그램의 상당히 현실적인 예입니다. 이 특별한 경우에, 우리는 DOM의 유연성을 크게 활용하지 않습니다.

import xml.dom.minidom

document = """\
<slideshow>
<title>Demo slideshow</title>
<slide><title>Slide title</title>
<point>This is a demo</point>
<point>Of a program for processing slides</point>
</slide>

<slide><title>Another demo slide</title>
<point>It is important</point>
<point>To have more than</point>
<point>one slide</point>
</slide>
</slideshow>
"""

dom = xml.dom.minidom.parseString(document)

def getText(nodelist):
    rc = []
    for node in nodelist:
        if node.nodeType == node.TEXT_NODE:
            rc.append(node.data)
    return ''.join(rc)

def handleSlideshow(slideshow):
    print("<html>")
    handleSlideshowTitle(slideshow.getElementsByTagName("title")[0])
    slides = slideshow.getElementsByTagName("slide")
    handleToc(slides)
    handleSlides(slides)
    print("</html>")

def handleSlides(slides):
    for slide in slides:
        handleSlide(slide)

def handleSlide(slide):
    handleSlideTitle(slide.getElementsByTagName("title")[0])
    handlePoints(slide.getElementsByTagName("point"))

def handleSlideshowTitle(title):
    print("<title>%s</title>" % getText(title.childNodes))

def handleSlideTitle(title):
    print("<h2>%s</h2>" % getText(title.childNodes))

def handlePoints(points):
    print("<ul>")
    for point in points:
        handlePoint(point)
    print("</ul>")

def handlePoint(point):
    print("<li>%s</li>" % getText(point.childNodes))

def handleToc(slides):
    for slide in slides:
        title = slide.getElementsByTagName("title")[0]
        print("<p>%s</p>" % getText(title.childNodes))

handleSlideshow(dom)

minidom과 DOM 표준

xml.dom.minidom 모듈은 본질적으로 일부 DOM 2 기능(주로 이름 공간 기능)이 있는 DOM 1.0 호환 DOM입니다.

파이썬에서 DOM 인터페이스의 사용법은 간단합니다. 다음과 같은 매핑 규칙이 적용됩니다:

인터페이스는 인스턴스 객체를 통해 액세스 됩니다. 응용 프로그램은 클래스를 직접 인스턴스로 만들어서는 안 됩니다; Document 객체에서 제공되는 생성자 함수를 사용해야 합니다. 파생 인터페이스는 베이스 인터페이스의 모든 연산(및 어트리뷰트)과 새로운 연산을 지원합니다.

연산은 메서드로 사용됩니다. DOM은 in 매개 변수만 사용하므로, 인자는 정상적인 순서(왼쪽에서 오른쪽으로)로 전달됩니다. 선택적 인자가 없습니다. void 연산은 None을 반환합니다.

IDL 어트리뷰트는 인스턴스 어트리뷰트에 매핑됩니다. 파이썬 용 OMG IDL 언어 매핑과의 호환성을 위해, 접근자 메서드 _get_foo()와 _set_foo()를 통해 어트리뷰트 foo에 액세스할 수도 있습니다. readonly 어트리뷰트는 변경하지 않아야 합니다; 실행 시간에 강제되지는 않습니다.

short int, unsigned int, unsigned long long 및 boolean 형은 모두 파이썬 정수 객체에 매핑됩니다.

DOMString 형은 파이썬 문자열에 매핑됩니다. xml.dom.minidom은 바이트열이나 문자열을 지원하지만, 일반적으로 문자열을 생성합니다. DOMString 형의 값은 W3C의 DOM 명세에 의해 IDL null 값을 가질 수 있을 때 None일 수도 있습니다.

const 선언은 해당 스코프에 있는 변수에 매핑됩니다 (예를 들어 xml.dom.minidom.Node.PROCESSING_INSTRUCTION_NODE); 변경되지 않아야 합니다.

DOMException은 현재 xml.dom.minidom에서 지원되지 않습니다. 대신, xml.dom.minidom은 TypeError와 AttributeError와 같은 표준 파이썬 예외를 사용합니다.

NodeList 객체는 파이썬의 내장 리스트 형을 사용하여 구현됩니다. 이러한 객체는 DOM 명세에 정의된 인터페이스를 제공하지만, 이전 버전의 파이썬에서는 공식 API를 지원하지 않습니다. 그러나 W3C 권장 사항에 정의된 인터페이스보다 훨씬 “파이썬답습니다”.

다음 인터페이스는 xml.dom.minidom에서 구현되지 않습니다:

DOMTimeStamp

EntityReference

이들 대부분은 대부분의 DOM 사용자에게 일반적인 쓸모를 제공하지 않는 XML 문서의 정보를 반영합니다.

각주

1

XML 출력에 포함된 인코딩 이름은 적절한 표준을 준수해야 합니다. 예를 들어, XML 문서의 선언에서 “UTF-8”은 유효하지만, “UTF8”은 파이썬이 이를 인코딩 이름으로 받아들이더라도 유효하지 않습니다. https://www.w3.org/TR/2006/REC-xml11-20060816/#NT-EncodingDecl 과 https://www.iana.org/assignments/character-sets/character-sets.xhtml 을 참조하십시오.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

구조화된 마크업 처리 도구 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

구조화된 마크업 처리 도구 »

|

xml.dom.pulldom — 부분 DOM 트리 구축 지원

소스 코드: Lib/xml/dom/pulldom.py [https://github.com/python/cpython/tree/3.7/Lib/xml/dom/pulldom.py]

xml.dom.pulldom 모듈은 필요할 때 문서의 DOM 액세스 가능한 조각을 생성하도록 요청할 수 있는 “풀 구문 분석기 (pull parser)”를 제공합니다. 기본 개념은 들어오는 XML 스트림에서 “이벤트”를 끌어당겨서(pull) 처리하는 것입니다. 콜백을 통한 이벤트 구동 처리 모델(event-driven processing model)을 사용하는 SAX와 달리 풀 구문 분석기 사용자는 스트림에서 이벤트를 명시적으로 가져와서 처리가 완료되거나 에러 조건이 발생할 때까지 그 이벤트들을 루핑해야 합니다.

경고

xml.dom.pulldom 모듈은 악의적으로 구성된 데이터로부터 안전하지 않습니다. 신뢰할 수 없거나 인증되지 않은 데이터를 구문 분석해야 하면 XML 취약점를 참조하십시오.

버전 3.7.1에서 변경: SAX 구문 분석기는 보안을 강화하기 위해 더는 일반 외부 엔티티를 처리하지 않습니다. 외부 엔티티를 처리를 활성화하려면, 사용자 정의 구문 분석기 인스턴스를 전달하십시오:

from xml.dom.pulldom import parse
from xml.sax import make_parser
from xml.sax.handler import feature_external_ges

parser = make_parser()
parser.setFeature(feature_external_ges, True)
parse(filename, parser=parser)

예:

from xml.dom import pulldom

doc = pulldom.parse('sales_items.xml')
for event, node in doc:
    if event == pulldom.START_ELEMENT and node.tagName == 'item':
        if int(node.getAttribute('price')) > 50:
            doc.expandNode(node)
            print(node.toxml())

event는 상수이며 다음 중 하나일 수 있습니다:

START_ELEMENT

END_ELEMENT

COMMENT

START_DOCUMENT

END_DOCUMENT

CHARACTERS

PROCESSING_INSTRUCTION

IGNORABLE_WHITESPACE

node는 xml.dom.minidom.Document, xml.dom.minidom.Element 또는 xml.dom.minidom.Text 형의 객체입니다.

문서는 “평평한(flat)” 이벤트 스트림으로 취급되므로, 문서 “트리”는 묵시적으로 탐색 되며 트리에서의 깊이와 관계없이 원하는 요소를 찾습니다. 다시 말해, 문서 노드의 재귀적 검색과 같은 계층적 문제를 고려할 필요는 없습니다. 하지만, 엘리먼트의 문맥이 중요하다면, 문맥과 관련된 상태를 유지하거나 (즉, 주어진 지점에서 문서의 어느 위치에 있는지 기억함으로써), DOMEventStream.expandNode() 메서드를 사용하고 DOM 관련 처리로 전환해야 합니다.

class xml.dom.pulldom.PullDom(documentFactory=None)

xml.sax.handler.ContentHandler의 서브 클래스.

class xml.dom.pulldom.SAX2DOM(documentFactory=None)

xml.sax.handler.ContentHandler의 서브 클래스.

xml.dom.pulldom.parse(stream_or_string, parser=None, bufsize=None)

주어진 입력으로부터 DOMEventStream을 반환합니다. stream_or_string은 파일 이름이거나 파일류 객체일 수 있습니다. 주어질 때, parser는 XMLReader 객체여야 합니다. 이 함수는 구문 분석기의 문서 처리기를 변경하고 이름 공간 지원을 활성화합니다; 다른 구문 분석기 구성(엔티티 해석기 설정과 같은)은 미리 수행되어 있어야 합니다.

문자열로 XML을 갖고 있다면, parseString() 함수를 대신 사용할 수 있습니다:

xml.dom.pulldom.parseString(string, parser=None)

(유니코드) string을 표현하는 DOMEventStream을 반환합니다.

xml.dom.pulldom.default_bufsize

parse()의 bufsize 매개 변수의 기본값.

이 변수의 값은 parse()를 호출하기 전에 변경될 수 있으며 새 값이 적용됩니다.

DOMEventStream 객체

class xml.dom.pulldom.DOMEventStream(stream, parser, bufsize)

getEvent()

event와 현재 node를 포함하는 튜플을 반환합니다. 노드는 이벤트가 START_DOCUMENT와 같으면 xml.dom.minidom.Document, 이벤트가 START_ELEMENT나 END_ELEMENT와 같으면 xml.dom.minidom.Element, 이벤트가 CHARACTERS와 같으면 xml.dom.minidom.Text 입니다. expandNode()가 호출되지 않는 한 현재 노드에는 자식에 대한 정보가 없습니다.

expandNode(node)

node의 모든 자식을 node로 확장합니다. 예:

from xml.dom import pulldom

xml = '<html><title>Foo</title> <p>Some text <div>and more</div></p> </html>'
doc = pulldom.parseString(xml)
for event, node in doc:
    if event == pulldom.START_ELEMENT and node.tagName == 'p':
        # Following statement only prints '<p/>'
        print(node.toxml())
        doc.expandNode(node)
        # Following statement prints node with all its children '<p>Some text <div>and more</div></p>'
        print(node.toxml())

reset()

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

구조화된 마크업 처리 도구 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

구조화된 마크업 처리 도구 »

|

xml.sax — SAX2 구문 분석기 지원

소스 코드: Lib/xml/sax/__init__.py [https://github.com/python/cpython/tree/3.7/Lib/xml/sax/__init__.py]

xml.sax 패키지는 파이썬용 SAX(Simple API for XML) 인터페이스를 구현하는 여러 모듈을 제공합니다. 패키지 자체는 대부분 SAX API의 사용자가 사용하게 될 SAX 예외와 편리 함수를 제공합니다.

경고

xml.sax 모듈은 악의적으로 구성된 데이터로부터 안전하지 않습니다. 신뢰할 수 없거나 인증되지 않은 데이터를 구문 분석해야 하면 XML 취약점을 참조하십시오.

버전 3.7.1에서 변경: SAX 구문 분석기는 보안을 강화하기 위해 더는 일반 외부 엔티티를 처리하지 않습니다. 이전에는, 구문 분석기가 DTD와 엔티티에 대해 네트워크 연결을 만들어 원격 파일을 가져오거나 파일 시스템에서 로컬 파일을 로드했습니다. 이 기능은 구문 분석기 객체에 대해 인자 feature_external_ges로 메서드 setFeature()를 사용하여 다시 활성화할 수 있습니다.

편리 함수는 다음과 같습니다:

xml.sax.make_parser(parser_list=[])

SAX XMLReader 객체를 만들고 반환합니다. 발견된 첫 번째 구문 분석기가 사용됩니다. parser_list가 제공되면, create_parser()라는 함수가 있는 모듈의 이름을 나타내는 문자열 리스트여야 합니다. parser_list에 나열된 모듈은 기본 구문 분석기 목록에 있는 모듈보다 먼저 사용됩니다.

xml.sax.parse(filename_or_stream, handler, error_handler=handler.ErrorHandler())

SAX 구문 분석기를 만들어 문서 구문 분석에 사용합니다. filename_or_stream으로 전달된 문서는 파일명이나 파일 객체일 수 있습니다. handler 매개 변수는 SAX ContentHandler 인스턴스여야 합니다. error_handler가 주어지면, SAX ErrorHandler 인스턴스여야 합니다; 생략하면, 모든 에러에서 SAXParseException이 발생합니다. 반환 값은 없습니다; 모든 작업은 전달된 handler가 처리해야 합니다.

xml.sax.parseString(string, handler, error_handler=handler.ErrorHandler())

parse()와 비슷하지만, 매개 변수로 받은 버퍼 string에서 구문 분석합니다. string은 str 인스턴스나 바이트열류 객체여야 합니다.

버전 3.5에서 변경: str 인스턴스에 대한 지원이 추가되었습니다.

전형적인 SAX 응용 프로그램은 입력기(reader), 처리기(handler) 및 입력 소스(input source)의 세 가지 종류의 객체를 사용합니다: 이 문맥에서 “입력기(Reader)”는 구문 분석기에 대한 또 다른 용어입니다, 즉, 입력 소스에서 바이트나 문자를 읽고, 이벤트 시퀀스를 생성하는 코드 조각입니다. 그런 다음 이벤트는 처리기 객체로 배포됩니다, 즉 입력기가 처리기의 메서드를 호출합니다. 따라서 SAX 응용 프로그램은 입력기 객체를 얻고, 입력 소스를 만들거나 열고, 처리기를 만들고, 이 객체들을 모두 연결해야 합니다. 준비의 마지막 단계로, 입력기가 입력을 구문 분석하도록 호출됩니다. 구문 분석하는 동안, 처리기 객체의 메서드는 입력 데이터로부터 온 구조적 및 구문적 이벤트를 기반으로 호출됩니다.

이러한 객체들은, 인터페이스만 중요합니다; 그들은 일반적으로 응용 프로그램 자체에 의해 인스턴스로 만들어지지 않습니다. 파이썬에는 인터페이스에 대한 명시적인 개념이 없으므로, 이것들이 형식적으로는 클래스로 소개되지만, 응용 프로그램은 제공된 클래스를 상속하지 않는 구현을 사용할 수 있습니다. InputSource, Locator, Attributes, AttributesNS 및 XMLReader 인터페이스는 모듈 xml.sax.xmlreader에 정의되어 있습니다. 처리기 인터페이스는 xml.sax.handler에 정의되어 있습니다. 편의상, InputSource(종종 직접 인스턴스를 만듭니다)와 처리기 클래스들은 xml.sax에서도 사용할 수 있습니다. 이러한 인터페이스는 아래에 설명되어 있습니다.

이러한 클래스 외에도, xml.sax는 다음과 같은 예외 클래스를 제공합니다.

exception xml.sax.SAXException(msg, exception=None)

XML 에러나 경고를 캡슐화합니다. 이 클래스에는 XML 구문 분석기나 응용 프로그램의 기본 에러나 경고 정보가 포함될 수 있습니다: 추가 기능을 제공하거나 지역화를 추가하기 위해 서브 클래싱 될 수 있습니다. ErrorHandler 인터페이스에 정의된 처리기가 이 예외의 인스턴스를 수신하지만, 예외를 실제로 발생시킬 필요는 없음에 유의하십시오 — 정보를 담는 컨테이너로도 유용합니다.

인스턴스로 만들어질 때, msg는 사람이 읽을 수 있는 에러에 관한 설명이어야 합니다. 선택적 exception 매개 변수를 주면, None이거나 구문 분석 코드에 의해 잡힌 예외여야 하고, 정보로 함께 전달됩니다.

이것은 다른 SAX 예외 클래스의 베이스 클래스입니다.

exception xml.sax.SAXParseException(msg, exception, locator)

구문 분석 에러 시 발생하는 SAXException의 서브 클래스. 이 클래스의 인스턴스는 SAX ErrorHandler 인터페이스의 메서드에 전달되어 구문 분석 에러에 대한 정보를 제공합니다. 이 클래스는 SAXException 인터페이스뿐만 아니라 SAX Locator 인터페이스를 지원합니다.

exception xml.sax.SAXNotRecognizedException(msg, exception=None)

SAX XMLReader가 인식할 수 없는 기능이나 속성을 만날 때 발생하는 SAXException의 서브 클래스. SAX 응용 프로그램과 확장은 유사한 목적으로 이 클래스를 사용할 수 있습니다.

exception xml.sax.SAXNotSupportedException(msg, exception=None)

SAX XMLReader가 지원되지 않는 기능을 활성화하거나 구현에서 지원하지 않는 값으로 속성을 설정하도록 요청될 때 발생하는 SAXException의 서브 클래스. SAX 응용 프로그램과 확장은 유사한 목적으로 이 클래스를 사용할 수 있습니다.

더 보기

SAX: The Simple API for XML [http://www.saxproject.org/]

이 사이트는 SAX API의 정의가 집중되는 곳입니다. Java 구현과 온라인 설명서를 제공합니다. 구현과 역사적 정보에 대한 링크도 있습니다.

모듈 xml.sax.handler

응용 프로그램이 제공하는 객체에 대한 인터페이스의 정의.

모듈 xml.sax.saxutils

SAX 응용 프로그램에서 사용하기 위한 편리 함수.

모듈 xml.sax.xmlreader

구문 분석기가 제공하는 객체에 대한 인터페이스의 정의.

SAXException 객체

SAXException 예외 클래스는 다음 메서드를 지원합니다:

SAXException.getMessage()

에러 상태를 설명하는 사람이 읽을 수 있는 메시지를 반환합니다.

SAXException.getException()

캡슐화된 예외 객체나 None을 반환합니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

구조화된 마크업 처리 도구 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

구조화된 마크업 처리 도구 »

|

xml.sax.handler — Base classes for SAX handlers

Source code: Lib/xml/sax/handler.py [https://github.com/python/cpython/tree/3.7/Lib/xml/sax/handler.py]

The SAX API defines four kinds of handlers: content handlers, DTD handlers, error handlers, and entity resolvers. Applications normally only need to implement those interfaces whose events they are interested in; they can implement the interfaces in a single object or in multiple objects. Handler implementations should inherit from the base classes provided in the module xml.sax.handler, so that all methods get default implementations.

class xml.sax.handler.ContentHandler

This is the main callback interface in SAX, and the one most important to applications. The order of events in this interface mirrors the order of the information in the document.

class xml.sax.handler.DTDHandler

Handle DTD events.

This interface specifies only those DTD events required for basic parsing (unparsed entities and attributes).

class xml.sax.handler.EntityResolver

Basic interface for resolving entities. If you create an object implementing this interface, then register the object with your Parser, the parser will call the method in your object to resolve all external entities.

class xml.sax.handler.ErrorHandler

Interface used by the parser to present error and warning messages to the application. The methods of this object control whether errors are immediately converted to exceptions or are handled in some other way.

In addition to these classes, xml.sax.handler provides symbolic constants for the feature and property names.

xml.sax.handler.feature_namespaces

value: "http://xml.org/sax/features/namespaces"

true: Perform Namespace processing.

false: Optionally do not perform Namespace processing (implies namespace-prefixes; default).

access: (parsing) read-only; (not parsing) read/write

xml.sax.handler.feature_namespace_prefixes

value: "http://xml.org/sax/features/namespace-prefixes"

true: Report the original prefixed names and attributes used for Namespace declarations.

false: Do not report attributes used for Namespace declarations, and optionally do not report original prefixed names (default).

access: (parsing) read-only; (not parsing) read/write

xml.sax.handler.feature_string_interning

value: "http://xml.org/sax/features/string-interning"

true: All element names, prefixes, attribute names, Namespace URIs, and local names are interned using the built-in intern function.

false: Names are not necessarily interned, although they may be (default).

access: (parsing) read-only; (not parsing) read/write

xml.sax.handler.feature_validation

value: "http://xml.org/sax/features/validation"

true: Report all validation errors (implies external-general-entities and external-parameter-entities).

false: Do not report validation errors.

access: (parsing) read-only; (not parsing) read/write

xml.sax.handler.feature_external_ges

value: "http://xml.org/sax/features/external-general-entities"

true: Include all external general (text) entities.

false: Do not include external general entities.

access: (parsing) read-only; (not parsing) read/write

xml.sax.handler.feature_external_pes

value: "http://xml.org/sax/features/external-parameter-entities"

true: Include all external parameter entities, including the external DTD subset.

false: Do not include any external parameter entities, even the external DTD subset.

access: (parsing) read-only; (not parsing) read/write

xml.sax.handler.all_features

List of all features.

xml.sax.handler.property_lexical_handler

value: "http://xml.org/sax/properties/lexical-handler"

data type: xml.sax.sax2lib.LexicalHandler (not supported in Python 2)

description: An optional extension handler for lexical events like comments.

access: read/write

xml.sax.handler.property_declaration_handler

value: "http://xml.org/sax/properties/declaration-handler"

data type: xml.sax.sax2lib.DeclHandler (not supported in Python 2)

description: An optional extension handler for DTD-related events other than notations and unparsed entities.

access: read/write

xml.sax.handler.property_dom_node

value: "http://xml.org/sax/properties/dom-node"

data type: org.w3c.dom.Node (not supported in Python 2)

description: When parsing, the current DOM node being visited if this is a DOM iterator; when not parsing, the root DOM node for iteration.

access: (parsing) read-only; (not parsing) read/write

xml.sax.handler.property_xml_string

value: "http://xml.org/sax/properties/xml-string"

data type: String

description: The literal string of characters that was the source for the current event.

access: read-only

xml.sax.handler.all_properties

List of all known property names.

ContentHandler Objects

Users are expected to subclass ContentHandler to support their application. The following methods are called by the parser on the appropriate events in the input document:

ContentHandler.setDocumentLocator(locator)

Called by the parser to give the application a locator for locating the origin of document events.

SAX parsers are strongly encouraged (though not absolutely required) to supply a locator: if it does so, it must supply the locator to the application by invoking this method before invoking any of the other methods in the DocumentHandler interface.

The locator allows the application to determine the end position of any document-related event, even if the parser is not reporting an error. Typically, the application will use this information for reporting its own errors (such as character content that does not match an application’s business rules). The information returned by the locator is probably not sufficient for use with a search engine.

Note that the locator will return correct information only during the invocation of the events in this interface. The application should not attempt to use it at any other time.

ContentHandler.startDocument()

Receive notification of the beginning of a document.

The SAX parser will invoke this method only once, before any other methods in this interface or in DTDHandler (except for setDocumentLocator()).

ContentHandler.endDocument()

Receive notification of the end of a document.

The SAX parser will invoke this method only once, and it will be the last method invoked during the parse. The parser shall not invoke this method until it has either abandoned parsing (because of an unrecoverable error) or reached the end of input.

ContentHandler.startPrefixMapping(prefix, uri)

Begin the scope of a prefix-URI Namespace mapping.

The information from this event is not necessary for normal Namespace processing: the SAX XML reader will automatically replace prefixes for element and attribute names when the feature_namespaces feature is enabled (the default).

There are cases, however, when applications need to use prefixes in character data or in attribute values, where they cannot safely be expanded automatically; the startPrefixMapping() and endPrefixMapping() events supply the information to the application to expand prefixes in those contexts itself, if necessary.

Note that startPrefixMapping() and endPrefixMapping() events are not guaranteed to be properly nested relative to each-other: all startPrefixMapping() events will occur before the corresponding startElement() event, and all endPrefixMapping() events will occur after the corresponding endElement() event, but their order is not guaranteed.

ContentHandler.endPrefixMapping(prefix)

End the scope of a prefix-URI mapping.

See startPrefixMapping() for details. This event will always occur after the corresponding endElement() event, but the order of endPrefixMapping() events is not otherwise guaranteed.

ContentHandler.startElement(name, attrs)

Signals the start of an element in non-namespace mode.

The name parameter contains the raw XML 1.0 name of the element type as a string and the attrs parameter holds an object of the Attributes interface (see Attributes 인터페이스) containing the attributes of the element. The object passed as attrs may be re-used by the parser; holding on to a reference to it is not a reliable way to keep a copy of the attributes. To keep a copy of the attributes, use the copy() method of the attrs object.

ContentHandler.endElement(name)

Signals the end of an element in non-namespace mode.

The name parameter contains the name of the element type, just as with the startElement() event.

ContentHandler.startElementNS(name, qname, attrs)

Signals the start of an element in namespace mode.

The name parameter contains the name of the element type as a (uri, localname) tuple, the qname parameter contains the raw XML 1.0 name used in the source document, and the attrs parameter holds an instance of the AttributesNS interface (see AttributesNS 인터페이스) containing the attributes of the element. If no namespace is associated with the element, the uri component of name will be None. The object passed as attrs may be re-used by the parser; holding on to a reference to it is not a reliable way to keep a copy of the attributes. To keep a copy of the attributes, use the copy() method of the attrs object.

Parsers may set the qname parameter to None, unless the feature_namespace_prefixes feature is activated.

ContentHandler.endElementNS(name, qname)

Signals the end of an element in namespace mode.

The name parameter contains the name of the element type, just as with the startElementNS() method, likewise the qname parameter.

ContentHandler.characters(content)

Receive notification of character data.

The Parser will call this method to report each chunk of character data. SAX parsers may return all contiguous character data in a single chunk, or they may split it into several chunks; however, all of the characters in any single event must come from the same external entity so that the Locator provides useful information.

content may be a string or bytes instance; the expat reader module always produces strings.

참고

The earlier SAX 1 interface provided by the Python XML Special Interest Group used a more Java-like interface for this method. Since most parsers used from Python did not take advantage of the older interface, the simpler signature was chosen to replace it. To convert old code to the new interface, use content instead of slicing content with the old offset and length parameters.

ContentHandler.ignorableWhitespace(whitespace)

Receive notification of ignorable whitespace in element content.

Validating Parsers must use this method to report each chunk of ignorable whitespace (see the W3C XML 1.0 recommendation, section 2.10): non-validating parsers may also use this method if they are capable of parsing and using content models.

SAX parsers may return all contiguous whitespace in a single chunk, or they may split it into several chunks; however, all of the characters in any single event must come from the same external entity, so that the Locator provides useful information.

ContentHandler.processingInstruction(target, data)

Receive notification of a processing instruction.

The Parser will invoke this method once for each processing instruction found: note that processing instructions may occur before or after the main document element.

A SAX parser should never report an XML declaration (XML 1.0, section 2.8) or a text declaration (XML 1.0, section 4.3.1) using this method.

ContentHandler.skippedEntity(name)

Receive notification of a skipped entity.

The Parser will invoke this method once for each entity skipped. Non-validating processors may skip entities if they have not seen the declarations (because, for example, the entity was declared in an external DTD subset). All processors may skip external entities, depending on the values of the feature_external_ges and the feature_external_pes properties.

DTDHandler Objects

DTDHandler instances provide the following methods:

DTDHandler.notationDecl(name, publicId, systemId)

Handle a notation declaration event.

DTDHandler.unparsedEntityDecl(name, publicId, systemId, ndata)

Handle an unparsed entity declaration event.

EntityResolver Objects

EntityResolver.resolveEntity(publicId, systemId)

Resolve the system identifier of an entity and return either the system identifier to read from as a string, or an InputSource to read from. The default implementation returns systemId.

ErrorHandler Objects

Objects with this interface are used to receive error and warning information from the XMLReader. If you create an object that implements this interface, then register the object with your XMLReader, the parser will call the methods in your object to report all warnings and errors. There are three levels of errors available: warnings, (possibly) recoverable errors, and unrecoverable errors. All methods take a SAXParseException as the only parameter. Errors and warnings may be converted to an exception by raising the passed-in exception object.

ErrorHandler.error(exception)

Called when the parser encounters a recoverable error. If this method does not raise an exception, parsing may continue, but further document information should not be expected by the application. Allowing the parser to continue may allow additional errors to be discovered in the input document.

ErrorHandler.fatalError(exception)

Called when the parser encounters an error it cannot recover from; parsing is expected to terminate when this method returns.

ErrorHandler.warning(exception)

Called when the parser presents minor warning information to the application. Parsing is expected to continue when this method returns, and document information will continue to be passed to the application. Raising an exception in this method will cause parsing to end.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

구조화된 마크업 처리 도구 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

구조화된 마크업 처리 도구 »

|

xml.sax.saxutils — SAX 유틸리티

소스 코드: Lib/xml/sax/saxutils.py [https://github.com/python/cpython/tree/3.7/Lib/xml/sax/saxutils.py]

xml.sax.saxutils 모듈은 SAX 응용 프로그램을 만들 때 직접 사용하거나 베이스 클래스로 사용하는 데 모두 유용한 많은 클래스와 함수를 포함합니다.

xml.sax.saxutils.escape(data, entities={})

data 문자열에 있는 '&', '<' 및 '>'를 이스케이프 합니다.

딕셔너리를 선택적 entities 매개 변수로 전달하여 data의 다른 문자열을 이스케이프 할 수 있습니다. 키와 값은 모두 문자열이어야 합니다; 각 키는 해당 값으로 치환되게 됩니다. 문자 '&', '<' 및 '>'는 entities가 제공되더라도 항상 이스케이프 됩니다.

xml.sax.saxutils.unescape(data, entities={})

data 문자열에 있는 '&amp;', '&lt;' 및 '&gt;'를 역 이스케이프 합니다.

딕셔너리를 선택적 entities 매개 변수로 전달하여 data의 다른 문자열을 역 이스케이프 할 수 있습니다. 키와 값은 모두 문자열이어야 합니다; 각 키는 해당 값으로 치환되게 됩니다. '&amp', '&lt;' 및 '&gt;'는 entities가 제공되더라도 항상 역 이스케이프 됩니다.

xml.sax.saxutils.quoteattr(data, entities={})

escape()와 비슷하지만, data가 어트리뷰트 값으로 사용되도록 준비합니다. 반환 값은 추가로 필요한 치환이 적용된 data의 따옴표 붙은 버전입니다. quoteattr()는 data의 내용에 따라 인용 부호 문자를 선택하여 가능하면 문자열의 인용 부호 문자를 인코딩하지 않습니다. 작은따옴표와 큰따옴표가 모두 data에 이미 있으면, 큰따옴표 문자가 인코딩되고, data는 큰따옴표로 묶입니다. 결과 문자열은 어트리뷰트 값으로 직접 사용할 수 있습니다:

>>> print("<element attr=%s>" % quoteattr("ab ' cd \" ef"))
<element attr="ab ' cd &quot; ef">

이 함수는 참조 구상 문법(reference concrete syntax)을 사용하여 HTML이나 모든 SGML을 위한 어트리뷰트 값을 생성할 때 유용합니다.

class xml.sax.saxutils.XMLGenerator(out=None, encoding='iso-8859-1', short_empty_elements=False)

이 클래스는 SAX 이벤트를 다시 XML 문서에 쓰는 방식으로 ContentHandler 인터페이스를 구현합니다. 다시 말해, XMLGenerator를 내용 처리기로 사용하면 구문 분석 중인 원본 문서를 재생산합니다. out은 파일류 객체 여야하고, 기본값은 sys.stdout입니다. encoding은 출력 스트림의 인코딩이고, 기본값은 'iso-8859-1'입니다. short_empty_elements는 내용이 없는 엘리먼트의 형식을 제어합니다: False(기본값)는 시작/끝 태그 쌍으로 출력하고, True로 설정하면 하나의 스스로 닫힌 태그를 출력합니다.

버전 3.2에 추가: short_empty_elements 매개 변수.

class xml.sax.saxutils.XMLFilterBase(base)

이 클래스는 XMLReader와 클라이언트 응용 프로그램의 이벤트 처리기 사이에 위치하도록 설계되었습니다. 기본적으로, 이것은 요청을 입력기에 전달하고 이벤트를 변경 없이 처리기에 전달할 뿐 아무것도 하지 않지만, 서브 클래스는 특정 메서드를 재정의하여 이벤트 스트림이나 구성 요청이 지나갈 때 수정할 수 있습니다.

xml.sax.saxutils.prepare_input_source(source, base='')

이 함수는 입력 소스와 선택적인 베이스 URL을 받아들이고 완전히 결정되고 읽을 준비가 된 InputSource 객체를 반환합니다. 입력 소스는 문자열, 파일류 객체 또는 InputSource 객체로 지정할 수 있습니다; 구문 분석기는 parse() 메서드에 대한 다형적인 source 인자를 구현하는 데 이 함수를 사용할 수 있습니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

구조화된 마크업 처리 도구 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

구조화된 마크업 처리 도구 »

|

xml.sax.xmlreader — XML 구문 분석기 인터페이스

소스 코드: Lib/xml/sax/xmlreader.py [https://github.com/python/cpython/tree/3.7/Lib/xml/sax/xmlreader.py]

SAX 구문 분석기는 XMLReader 인터페이스를 구현합니다. 이들은 함수 create_parser()를 제공해야 하는 파이썬 모듈로 구현됩니다. 이 함수는 새로운 구문 분석기 객체를 만들기 위해 인자 없이 xml.sax.make_parser()에 의해 호출됩니다.

class xml.sax.xmlreader.XMLReader

SAX 구문 분석기가 상속할 수 있는 베이스 클래스.

class xml.sax.xmlreader.IncrementalParser

때에 따라 입력 소스를 한 번에 구문 분석하지 않고 문서를 사용 가능할 때마다 청크로 공급하는 것이 바람직합니다. 입력기(reader)는 일반적으로 전체 파일을 읽지 않고 덩어리로 읽습니다; 여전히 전체 문서가 처리될 때까지 parse()는 반환하지 않습니다. 따라서 parse()의 블로킹 동작이 바람직하지 않을 때 이 인터페이스를 사용해야 합니다.

구문 분석기가 인스턴스화 되면 즉시 feed 메서드에서 데이터를 받아들일 수 있습니다. 구문 분석이 close 호출로 완료된 후, 구문 분석기가 feed나 parse 메서드를 사용하여 새 데이터를 받아들일 준비가 되도록 하려면 reset 메서드를 호출해야 합니다.

이러한 메서드들은 구문 분석 중, 즉 parse가 호출된 후 반환하기 전에 호출하지 않아야 합니다.

기본적으로, 이 클래스는 SAX 2.0 드라이버 작성자의 편의를 위해 IncrementalParser 인터페이스의 feed, close 및 reset 메서드를 사용하여 XMLReader 인터페이스의 parse 메서드를 구현합니다.

class xml.sax.xmlreader.Locator

SAX 이벤트를 문서 위치에 관련시키기 위한 인터페이스. 로케이터 객체는 DocumentHandler 메서드들을 호출하는 동안에만 유효한 결과를 반환합니다; 다른 때에는 결과를 예측할 수 없습니다. 정보가 없으면, 메서드는 None을 반환할 수 있습니다.

class xml.sax.xmlreader.InputSource(system_id=None)

엔티티를 읽기 위해 XMLReader에 필요한 정보의 캡슐화.

이 클래스는 공개 식별자, 시스템 식별자, 바이트 스트림 (문자 인코딩 정보도 포함할 수 있습니다) 및/또는 엔티티의 문자 스트림에 대한 정보를 포함할 수 있습니다.

응용 프로그램은 XMLReader.parse() 메서드에서 사용하고 EntityResolver.resolveEntity에서 반환하기 위해 이 클래스의 객체를 만듭니다.

InputSource는 응용 프로그램에 속하며, XMLReader는 응용 프로그램에서 전달된 InputSource 객체를 수정할 수는 없지만, 복사하여 수정할 수는 있습니다.

class xml.sax.xmlreader.AttributesImpl(attrs)

이것은 Attributes 인터페이스의 구현입니다 (Attributes 인터페이스 절을 참조하십시오). 이것은 startElement() 호출에서 요소 어트리뷰트를 나타내는 딕셔너리류 객체입니다. 가장 유용한 딕셔너리 연산 외에도, 인터페이스에서 설명하는 여러 가지 메서드를 지원합니다. 이 클래스의 객체는 입력기(reader)가 인스턴스화 해야 합니다; attrs는 어트리뷰트 이름에서 어트리뷰트 값으로의 매핑을 포함하는 딕셔너리류 객체여야 합니다.

class xml.sax.xmlreader.AttributesNSImpl(attrs, qnames)

startElementNS()에 전달될 AttributesImpl의 이름 공간(namespace) 인식 변형입니다. AttributesImpl에서 파생되었지만, namespaceURI와 localname의 2-튜플로 구성된 어트리뷰트 이름을 이해합니다. 또한, 원본 문서에 나타나는 정규화 된 이름을 기대하는 여러 가지 메서드를 제공합니다. 이 클래스는 AttributesNS 인터페이스를 구현합니다 (AttributesNS 인터페이스 절을 참조하십시오).

XMLReader 객체

XMLReader 인터페이스는 다음과 같은 메서드를 지원합니다:

XMLReader.parse(source)

Process an input source, producing SAX events. The source object can be a system identifier (a string identifying the input source – typically a file name or a URL), a file-like object, or an InputSource object. When parse() returns, the input is completely processed, and the parser object can be discarded or reset.

버전 3.5에서 변경: 문자 스트림 지원이 추가되었습니다.

XMLReader.getContentHandler()

현재 ContentHandler를 반환합니다.

XMLReader.setContentHandler(handler)

현재 ContentHandler를 설정합니다. ContentHandler가 설정되지 않으면, 내용 이벤트가 버려집니다.

XMLReader.getDTDHandler()

현재 DTDHandler를 반환합니다.

XMLReader.setDTDHandler(handler)

현재 DTDHandler를 설정합니다. DTDHandler가 설정되지 않으면, DTD 이벤트가 버려집니다.

XMLReader.getEntityResolver()

현재 EntityResolver를 반환합니다.

XMLReader.setEntityResolver(handler)

현재 EntityResolver를 설정합니다. EntityResolver가 설정되지 않으면, 외부 엔티티를 결정하려고 할 때 엔티티에 대한 시스템 식별자가 열리게 되고, 사용할 수 없으면 실패합니다.

XMLReader.getErrorHandler()

현재 ErrorHandler를 반환합니다.

XMLReader.setErrorHandler(handler)

현재 에러 처리기를 설정합니다. ErrorHandler가 설정되지 않으면, 에러는 예외를 발생시키고, 경고는 인쇄됩니다.

XMLReader.setLocale(locale)

응용 프로그램이 에러와 경고에 대한 로케일을 설정하도록 합니다.

SAX 구문 분석기는 에러와 경고에 대한 지역화를 제공하지 않아도 됩니다; 그러나, 요청된 로케일을 지원할 수 없으면 SAX 예외를 발생시켜야 합니다. 응용 프로그램은 구문 분석 중에 로케일 변경을 요청할 수 있습니다.

XMLReader.getFeature(featurename)

기능 featurename의 현재 설정을 반환합니다. 기능이 인식되지 않으면, SAXNotRecognizedException이 발생합니다. 잘 알려진 기능 이름(featurename)은 모듈 xml.sax.handler에 나열되어 있습니다.

XMLReader.setFeature(featurename, value)

featurename을 value로 설정합니다. 기능이 인식되지 않으면, SAXNotRecognizedException가 발생합니다. 구문 분석기가 기능이나 해당 설정을 지원하지 않으면 SAXNotSupportedException이 발생합니다.

XMLReader.getProperty(propertyname)

속성 propertyname의 현재 설정을 반환합니다. 속성이 인식되지 않으면 SAXNotRecognizedException이 발생합니다. 잘 알려진 속성 이름은 모듈 xml.sax.handler에 나열되어 있습니다.

XMLReader.setProperty(propertyname, value)

propertyname을 value로 설정합니다. 속성이 인식되지 않으면 SAXNotRecognizedException이 발생합니다. 구문 분석기가 속성이나 해당 설정을 지원하지 않으면 SAXNotSupportedException이 발생합니다.

IncrementalParser 객체

IncrementalParser 인스턴스는 다음과 같은 추가 메서드를 제공합니다:

IncrementalParser.feed(data)

data 청크를 처리합니다.

IncrementalParser.close()

문서의 끝을 가정합니다. 끝에서만 확인할 수 있는 올바른 구성(well-formedness) 조건을 확인하고, 처리기를 호출하며 구문 분석 중에 할당된 자원을 정리할 수 있습니다.

IncrementalParser.reset()

이 메서드는 close가 호출된 후에 호출되어 새 문서를 구문 분석할 수 있도록 구문 분석기를 재설정합니다. reset을 호출하지 않고, close 후에 parse나 feed를 호출한 결과는 정의되지 않습니다.

Locator 객체

Locator 인스턴스는 다음 메서드를 제공합니다:

Locator.getColumnNumber()

현재 이벤트가 시작되는 열 번호를 반환합니다.

Locator.getLineNumber()

현재 이벤트가 시작되는 줄 번호를 반환합니다.

Locator.getPublicId()

현재 이벤트의 공개 식별자를 반환합니다.

Locator.getSystemId()

현재 이벤트의 시스템 식별자를 반환합니다.

InputSource 객체

InputSource.setPublicId(id)

이 InputSource의 공개 식별자를 설정합니다.

InputSource.getPublicId()

이 InputSource의 공개 식별자를 반환합니다.

InputSource.setSystemId(id)

이 InputSource의 시스템 식별자를 설정합니다.

InputSource.getSystemId()

이 InputSource의 시스템 식별자를 반환합니다.

InputSource.setEncoding(encoding)

이 InputSource의 문자 인코딩을 설정합니다.

인코딩은 XML 인코딩 선언에 허용되는 문자열이어야 합니다 (XML 권장 사항의 4.3.3 절을 참조하십시오).

InputSource에 문자 스트림도 포함되어 있으면 InputSource의 인코딩 어트리뷰트는 무시됩니다.

InputSource.getEncoding()

이 InputSource의 문자 인코딩을 가져옵니다.

InputSource.setByteStream(bytefile)

이 입력 소스의 바이트 스트림(바이너리 파일)을 설정합니다.

문자 스트림도 지정되어 있으면 SAX 구문 분석기는 이것을 무시하지만, URI 연결 자체를 여는 것보다 바이트 스트림을 먼저 사용합니다.

응용 프로그램이 바이트 스트림의 문자 인코딩을 알고 있으면, setEncoding 메서드로 설정해야 합니다.

InputSource.getByteStream()

이 입력 소스의 바이트 스트림을 가져옵니다.

getEncoding 메서드는 이 바이트 스트림의 문자 인코딩을 반환하거나, 알 수 없으면 None을 반환합니다.

InputSource.setCharacterStream(charfile)

이 입력 소스에 대한 문자 스트림(텍스트 파일)을 설정합니다.

문자 스트림이 지정되면 SAX 구문 분석기는 모든 바이트 스트림을 무시하고 시스템 식별자에 대한 URI 연결을 열려고 시도하지 않습니다.

InputSource.getCharacterStream()

이 입력 소스의 문자 스트림을 가져옵니다.

Attributes 인터페이스

Attributes 객체는 메서드 copy(), get(), __contains__(), items(), keys() 및 values()를 포함하는 매핑 프로토콜의 일부를 구현합니다. 다음과 같은 메서드도 제공됩니다:

Attributes.getLength()

어트리뷰트 수를 반환합니다.

Attributes.getNames()

어트리뷰트의 이름을 반환합니다.

Attributes.getType(name)

어트리뷰트 name의 유형을 반환합니다. 일반적으로 'CDATA'입니다.

Attributes.getValue(name)

어트리뷰트 name의 값을 반환합니다.

AttributesNS 인터페이스

이 인터페이스는 Attributes 인터페이스의 서브 형입니다 (Attributes 인터페이스 절을 참조하십시오). 그 인터페이스에서 지원하는 모든 메서드는 AttributesNS 객체에서도 사용 가능합니다.

다음과 같은 메서드도 제공됩니다:

AttributesNS.getValueByQName(name)

정규화된 이름(qualified name)의 값을 반환합니다.

AttributesNS.getNameByQName(name)

정규화된 name에 대한 (namespace, localname) 쌍을 반환합니다.

AttributesNS.getQNameByName(name)

(namespace, localname) 쌍에 대한 정규화된 이름을 반환합니다.

AttributesNS.getQNames()

모든 어트리뷰트의 정규화된 이름을 반환합니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

구조화된 마크업 처리 도구 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

구조화된 마크업 처리 도구 »

|

xml.parsers.expat — Fast XML parsing using Expat

경고

The pyexpat module is not secure against maliciously constructed data. If you need to parse untrusted or unauthenticated data see XML 취약점.

The xml.parsers.expat module is a Python interface to the Expat non-validating XML parser. The module provides a single extension type, xmlparser, that represents the current state of an XML parser. After an xmlparser object has been created, various attributes of the object can be set to handler functions. When an XML document is then fed to the parser, the handler functions are called for the character data and markup in the XML document.

This module uses the pyexpat module to provide access to the Expat parser. Direct use of the pyexpat module is deprecated.

This module provides one exception and one type object:

exception xml.parsers.expat.ExpatError

The exception raised when Expat reports an error. See section ExpatError Exceptions for more information on interpreting Expat errors.

exception xml.parsers.expat.error

Alias for ExpatError.

xml.parsers.expat.XMLParserType

The type of the return values from the ParserCreate() function.

The xml.parsers.expat module contains two functions:

xml.parsers.expat.ErrorString(errno)

Returns an explanatory string for a given error number errno.

xml.parsers.expat.ParserCreate(encoding=None, namespace_separator=None)

Creates and returns a new xmlparser object. encoding, if specified, must be a string naming the encoding used by the XML data. Expat doesn’t support as many encodings as Python does, and its repertoire of encodings can’t be extended; it supports UTF-8, UTF-16, ISO-8859-1 (Latin1), and ASCII. If encoding 1 is given it will override the implicit or explicit encoding of the document.

Expat can optionally do XML namespace processing for you, enabled by providing a value for namespace_separator. The value must be a one-character string; a ValueError will be raised if the string has an illegal length (None is considered the same as omission). When namespace processing is enabled, element type names and attribute names that belong to a namespace will be expanded. The element name passed to the element handlers StartElementHandler and EndElementHandler will be the concatenation of the namespace URI, the namespace separator character, and the local part of the name. If the namespace separator is a zero byte (chr(0)) then the namespace URI and the local part will be concatenated without any separator.

For example, if namespace_separator is set to a space character (' ') and the following document is parsed:

<?xml version="1.0"?>
<root xmlns    = "http://default-namespace.org/"
      xmlns:py = "http://www.python.org/ns/">
  <py:elem1 />
  <elem2 xmlns="" />
</root>

StartElementHandler will receive the following strings for each element:

http://default-namespace.org/ root
http://www.python.org/ns/ elem1
elem2

Due to limitations in the Expat library used by pyexpat, the xmlparser instance returned can only be used to parse a single XML document. Call ParserCreate for each document to provide unique parser instances.

더 보기

The Expat XML Parser [http://www.libexpat.org/]

Home page of the Expat project.

XMLParser Objects

xmlparser objects have the following methods:

xmlparser.Parse(data[, isfinal])

Parses the contents of the string data, calling the appropriate handler functions to process the parsed data. isfinal must be true on the final call to this method; it allows the parsing of a single file in fragments, not the submission of multiple files. data can be the empty string at any time.

xmlparser.ParseFile(file)

Parse XML data reading from the object file. file only needs to provide the read(nbytes) method, returning the empty string when there’s no more data.

xmlparser.SetBase(base)

Sets the base to be used for resolving relative URIs in system identifiers in declarations. Resolving relative identifiers is left to the application: this value will be passed through as the base argument to the ExternalEntityRefHandler(), NotationDeclHandler(), and UnparsedEntityDeclHandler() functions.

xmlparser.GetBase()

Returns a string containing the base set by a previous call to SetBase(), or None if SetBase() hasn’t been called.

xmlparser.GetInputContext()

Returns the input data that generated the current event as a string. The data is in the encoding of the entity which contains the text. When called while an event handler is not active, the return value is None.

xmlparser.ExternalEntityParserCreate(context[, encoding])

Create a “child” parser which can be used to parse an external parsed entity referred to by content parsed by the parent parser. The context parameter should be the string passed to the ExternalEntityRefHandler() handler function, described below. The child parser is created with the ordered_attributes and specified_attributes set to the values of this parser.

xmlparser.SetParamEntityParsing(flag)

Control parsing of parameter entities (including the external DTD subset). Possible flag values are XML_PARAM_ENTITY_PARSING_NEVER, XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE and XML_PARAM_ENTITY_PARSING_ALWAYS. Return true if setting the flag was successful.

xmlparser.UseForeignDTD([flag])

Calling this with a true value for flag (the default) will cause Expat to call the ExternalEntityRefHandler with None for all arguments to allow an alternate DTD to be loaded. If the document does not contain a document type declaration, the ExternalEntityRefHandler will still be called, but the StartDoctypeDeclHandler and EndDoctypeDeclHandler will not be called.

Passing a false value for flag will cancel a previous call that passed a true value, but otherwise has no effect.

This method can only be called before the Parse() or ParseFile() methods are called; calling it after either of those have been called causes ExpatError to be raised with the code attribute set to errors.codes[errors.XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING].

xmlparser objects have the following attributes:

xmlparser.buffer_size

The size of the buffer used when buffer_text is true. A new buffer size can be set by assigning a new integer value to this attribute. When the size is changed, the buffer will be flushed.

xmlparser.buffer_text

Setting this to true causes the xmlparser object to buffer textual content returned by Expat to avoid multiple calls to the CharacterDataHandler() callback whenever possible. This can improve performance substantially since Expat normally breaks character data into chunks at every line ending. This attribute is false by default, and may be changed at any time.

xmlparser.buffer_used

If buffer_text is enabled, the number of bytes stored in the buffer. These bytes represent UTF-8 encoded text. This attribute has no meaningful interpretation when buffer_text is false.

xmlparser.ordered_attributes

Setting this attribute to a non-zero integer causes the attributes to be reported as a list rather than a dictionary. The attributes are presented in the order found in the document text. For each attribute, two list entries are presented: the attribute name and the attribute value. (Older versions of this module also used this format.) By default, this attribute is false; it may be changed at any time.

xmlparser.specified_attributes

If set to a non-zero integer, the parser will report only those attributes which were specified in the document instance and not those which were derived from attribute declarations. Applications which set this need to be especially careful to use what additional information is available from the declarations as needed to comply with the standards for the behavior of XML processors. By default, this attribute is false; it may be changed at any time.

The following attributes contain values relating to the most recent error encountered by an xmlparser object, and will only have correct values once a call to Parse() or ParseFile() has raised an xml.parsers.expat.ExpatError exception.

xmlparser.ErrorByteIndex

Byte index at which an error occurred.

xmlparser.ErrorCode

Numeric code specifying the problem. This value can be passed to the ErrorString() function, or compared to one of the constants defined in the errors object.

xmlparser.ErrorColumnNumber

Column number at which an error occurred.

xmlparser.ErrorLineNumber

Line number at which an error occurred.

The following attributes contain values relating to the current parse location in an xmlparser object. During a callback reporting a parse event they indicate the location of the first of the sequence of characters that generated the event. When called outside of a callback, the position indicated will be just past the last parse event (regardless of whether there was an associated callback).

xmlparser.CurrentByteIndex

Current byte index in the parser input.

xmlparser.CurrentColumnNumber

Current column number in the parser input.

xmlparser.CurrentLineNumber

Current line number in the parser input.

Here is the list of handlers that can be set. To set a handler on an xmlparser object o, use o.handlername = func. handlername must be taken from the following list, and func must be a callable object accepting the correct number of arguments. The arguments are all strings, unless otherwise stated.

xmlparser.XmlDeclHandler(version, encoding, standalone)

Called when the XML declaration is parsed. The XML declaration is the (optional) declaration of the applicable version of the XML recommendation, the encoding of the document text, and an optional “standalone” declaration. version and encoding will be strings, and standalone will be 1 if the document is declared standalone, 0 if it is declared not to be standalone, or -1 if the standalone clause was omitted. This is only available with Expat version 1.95.0 or newer.

xmlparser.StartDoctypeDeclHandler(doctypeName, systemId, publicId, has_internal_subset)

Called when Expat begins parsing the document type declaration (<!DOCTYPE ...). The doctypeName is provided exactly as presented. The systemId and publicId parameters give the system and public identifiers if specified, or None if omitted. has_internal_subset will be true if the document contains and internal document declaration subset. This requires Expat version 1.2 or newer.

xmlparser.EndDoctypeDeclHandler()

Called when Expat is done parsing the document type declaration. This requires Expat version 1.2 or newer.

xmlparser.ElementDeclHandler(name, model)

Called once for each element type declaration. name is the name of the element type, and model is a representation of the content model.

xmlparser.AttlistDeclHandler(elname, attname, type, default, required)

Called for each declared attribute for an element type. If an attribute list declaration declares three attributes, this handler is called three times, once for each attribute. elname is the name of the element to which the declaration applies and attname is the name of the attribute declared. The attribute type is a string passed as type; the possible values are 'CDATA', 'ID', 'IDREF', … default gives the default value for the attribute used when the attribute is not specified by the document instance, or None if there is no default value (#IMPLIED values). If the attribute is required to be given in the document instance, required will be true. This requires Expat version 1.95.0 or newer.

xmlparser.StartElementHandler(name, attributes)

Called for the start of every element. name is a string containing the element name, and attributes is the element attributes. If ordered_attributes is true, this is a list (see ordered_attributes for a full description). Otherwise it’s a dictionary mapping names to values.

xmlparser.EndElementHandler(name)

Called for the end of every element.

xmlparser.ProcessingInstructionHandler(target, data)

Called for every processing instruction.

xmlparser.CharacterDataHandler(data)

Called for character data. This will be called for normal character data, CDATA marked content, and ignorable whitespace. Applications which must distinguish these cases can use the StartCdataSectionHandler, EndCdataSectionHandler, and ElementDeclHandler callbacks to collect the required information.

xmlparser.UnparsedEntityDeclHandler(entityName, base, systemId, publicId, notationName)

Called for unparsed (NDATA) entity declarations. This is only present for version 1.2 of the Expat library; for more recent versions, use EntityDeclHandler instead. (The underlying function in the Expat library has been declared obsolete.)

xmlparser.EntityDeclHandler(entityName, is_parameter_entity, value, base, systemId, publicId, notationName)

Called for all entity declarations. For parameter and internal entities, value will be a string giving the declared contents of the entity; this will be None for external entities. The notationName parameter will be None for parsed entities, and the name of the notation for unparsed entities. is_parameter_entity will be true if the entity is a parameter entity or false for general entities (most applications only need to be concerned with general entities). This is only available starting with version 1.95.0 of the Expat library.

xmlparser.NotationDeclHandler(notationName, base, systemId, publicId)

Called for notation declarations. notationName, base, and systemId, and publicId are strings if given. If the public identifier is omitted, publicId will be None.

xmlparser.StartNamespaceDeclHandler(prefix, uri)

Called when an element contains a namespace declaration. Namespace declarations are processed before the StartElementHandler is called for the element on which declarations are placed.

xmlparser.EndNamespaceDeclHandler(prefix)

Called when the closing tag is reached for an element that contained a namespace declaration. This is called once for each namespace declaration on the element in the reverse of the order for which the StartNamespaceDeclHandler was called to indicate the start of each namespace declaration’s scope. Calls to this handler are made after the corresponding EndElementHandler for the end of the element.

xmlparser.CommentHandler(data)

Called for comments. data is the text of the comment, excluding the leading '<!--' and trailing '-->'.

xmlparser.StartCdataSectionHandler()

Called at the start of a CDATA section. This and EndCdataSectionHandler are needed to be able to identify the syntactical start and end for CDATA sections.

xmlparser.EndCdataSectionHandler()

Called at the end of a CDATA section.

xmlparser.DefaultHandler(data)

Called for any characters in the XML document for which no applicable handler has been specified. This means characters that are part of a construct which could be reported, but for which no handler has been supplied.

xmlparser.DefaultHandlerExpand(data)

This is the same as the DefaultHandler(), but doesn’t inhibit expansion of internal entities. The entity reference will not be passed to the default handler.

xmlparser.NotStandaloneHandler()

Called if the XML document hasn’t been declared as being a standalone document. This happens when there is an external subset or a reference to a parameter entity, but the XML declaration does not set standalone to yes in an XML declaration. If this handler returns 0, then the parser will raise an XML_ERROR_NOT_STANDALONE error. If this handler is not set, no exception is raised by the parser for this condition.

xmlparser.ExternalEntityRefHandler(context, base, systemId, publicId)

Called for references to external entities. base is the current base, as set by a previous call to SetBase(). The public and system identifiers, systemId and publicId, are strings if given; if the public identifier is not given, publicId will be None. The context value is opaque and should only be used as described below.

For external entities to be parsed, this handler must be implemented. It is responsible for creating the sub-parser using ExternalEntityParserCreate(context), initializing it with the appropriate callbacks, and parsing the entity. This handler should return an integer; if it returns 0, the parser will raise an XML_ERROR_EXTERNAL_ENTITY_HANDLING error, otherwise parsing will continue.

If this handler is not provided, external entities are reported by the DefaultHandler callback, if provided.

ExpatError Exceptions

ExpatError exceptions have a number of interesting attributes:

ExpatError.code

Expat’s internal error number for the specific error. The errors.messages dictionary maps these error numbers to Expat’s error messages. For example:

from xml.parsers.expat import ParserCreate, ExpatError, errors

p = ParserCreate()
try:
    p.Parse(some_xml_document)
except ExpatError as err:
    print("Error:", errors.messages[err.code])

The errors module also provides error message constants and a dictionary codes mapping these messages back to the error codes, see below.

ExpatError.lineno

Line number on which the error was detected. The first line is numbered 1.

ExpatError.offset

Character offset into the line where the error occurred. The first column is numbered 0.

Example

The following program defines three handlers that just print out their arguments.

import xml.parsers.expat

# 3 handler functions
def start_element(name, attrs):
    print('Start element:', name, attrs)
def end_element(name):
    print('End element:', name)
def char_data(data):
    print('Character data:', repr(data))

p = xml.parsers.expat.ParserCreate()

p.StartElementHandler = start_element
p.EndElementHandler = end_element
p.CharacterDataHandler = char_data

p.Parse("""<?xml version="1.0"?>
<parent id="top"><child1 name="paul">Text goes here</child1>
<child2 name="fred">More text</child2>
</parent>""", 1)

The output from this program is:

Start element: parent {'id': 'top'}
Start element: child1 {'name': 'paul'}
Character data: 'Text goes here'
End element: child1
Character data: '\n'
Start element: child2 {'name': 'fred'}
Character data: 'More text'
End element: child2
Character data: '\n'
End element: parent

Content Model Descriptions

Content models are described using nested tuples. Each tuple contains four values: the type, the quantifier, the name, and a tuple of children. Children are simply additional content model descriptions.

The values of the first two fields are constants defined in the xml.parsers.expat.model module. These constants can be collected in two groups: the model type group and the quantifier group.

The constants in the model type group are:

xml.parsers.expat.model.XML_CTYPE_ANY

The element named by the model name was declared to have a content model of ANY.

xml.parsers.expat.model.XML_CTYPE_CHOICE

The named element allows a choice from a number of options; this is used for content models such as (A | B | C).

xml.parsers.expat.model.XML_CTYPE_EMPTY

Elements which are declared to be EMPTY have this model type.

xml.parsers.expat.model.XML_CTYPE_MIXED

xml.parsers.expat.model.XML_CTYPE_NAME

xml.parsers.expat.model.XML_CTYPE_SEQ

Models which represent a series of models which follow one after the other are indicated with this model type. This is used for models such as (A, B, C).

The constants in the quantifier group are:

xml.parsers.expat.model.XML_CQUANT_NONE

No modifier is given, so it can appear exactly once, as for A.

xml.parsers.expat.model.XML_CQUANT_OPT

The model is optional: it can appear once or not at all, as for A?.

xml.parsers.expat.model.XML_CQUANT_PLUS

The model must occur one or more times (like A+).

xml.parsers.expat.model.XML_CQUANT_REP

The model must occur zero or more times, as for A*.

Expat error constants

The following constants are provided in the xml.parsers.expat.errors module. These constants are useful in interpreting some of the attributes of the ExpatError exception objects raised when an error has occurred. Since for backwards compatibility reasons, the constants’ value is the error message and not the numeric error code, you do this by comparing its code attribute with errors.codes[errors.XML_ERROR_CONSTANT_NAME].

The errors module has the following attributes:

xml.parsers.expat.errors.codes

A dictionary mapping numeric error codes to their string descriptions.

버전 3.2에 추가.

xml.parsers.expat.errors.messages

A dictionary mapping string descriptions to their error codes.

버전 3.2에 추가.

xml.parsers.expat.errors.XML_ERROR_ASYNC_ENTITY

xml.parsers.expat.errors.XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF

An entity reference in an attribute value referred to an external entity instead of an internal entity.

xml.parsers.expat.errors.XML_ERROR_BAD_CHAR_REF

A character reference referred to a character which is illegal in XML (for example, character 0, or ‘&#0;’).

xml.parsers.expat.errors.XML_ERROR_BINARY_ENTITY_REF

An entity reference referred to an entity which was declared with a notation, so cannot be parsed.

xml.parsers.expat.errors.XML_ERROR_DUPLICATE_ATTRIBUTE

An attribute was used more than once in a start tag.

xml.parsers.expat.errors.XML_ERROR_INCORRECT_ENCODING

xml.parsers.expat.errors.XML_ERROR_INVALID_TOKEN

Raised when an input byte could not properly be assigned to a character; for example, a NUL byte (value 0) in a UTF-8 input stream.

xml.parsers.expat.errors.XML_ERROR_JUNK_AFTER_DOC_ELEMENT

Something other than whitespace occurred after the document element.

xml.parsers.expat.errors.XML_ERROR_MISPLACED_XML_PI

An XML declaration was found somewhere other than the start of the input data.

xml.parsers.expat.errors.XML_ERROR_NO_ELEMENTS

The document contains no elements (XML requires all documents to contain exactly one top-level element)..

xml.parsers.expat.errors.XML_ERROR_NO_MEMORY

Expat was not able to allocate memory internally.

xml.parsers.expat.errors.XML_ERROR_PARAM_ENTITY_REF

A parameter entity reference was found where it was not allowed.

xml.parsers.expat.errors.XML_ERROR_PARTIAL_CHAR

An incomplete character was found in the input.

xml.parsers.expat.errors.XML_ERROR_RECURSIVE_ENTITY_REF

An entity reference contained another reference to the same entity; possibly via a different name, and possibly indirectly.

xml.parsers.expat.errors.XML_ERROR_SYNTAX

Some unspecified syntax error was encountered.

xml.parsers.expat.errors.XML_ERROR_TAG_MISMATCH

An end tag did not match the innermost open start tag.

xml.parsers.expat.errors.XML_ERROR_UNCLOSED_TOKEN

Some token (such as a start tag) was not closed before the end of the stream or the next token was encountered.

xml.parsers.expat.errors.XML_ERROR_UNDEFINED_ENTITY

A reference was made to an entity which was not defined.

xml.parsers.expat.errors.XML_ERROR_UNKNOWN_ENCODING

The document encoding is not supported by Expat.

xml.parsers.expat.errors.XML_ERROR_UNCLOSED_CDATA_SECTION

A CDATA marked section was not closed.

xml.parsers.expat.errors.XML_ERROR_EXTERNAL_ENTITY_HANDLING

xml.parsers.expat.errors.XML_ERROR_NOT_STANDALONE

The parser determined that the document was not “standalone” though it declared itself to be in the XML declaration, and the NotStandaloneHandler was set and returned 0.

xml.parsers.expat.errors.XML_ERROR_UNEXPECTED_STATE

xml.parsers.expat.errors.XML_ERROR_ENTITY_DECLARED_IN_PE

xml.parsers.expat.errors.XML_ERROR_FEATURE_REQUIRES_XML_DTD

An operation was requested that requires DTD support to be compiled in, but Expat was configured without DTD support. This should never be reported by a standard build of the xml.parsers.expat module.

xml.parsers.expat.errors.XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING

A behavioral change was requested after parsing started that can only be changed before parsing has started. This is (currently) only raised by UseForeignDTD().

xml.parsers.expat.errors.XML_ERROR_UNBOUND_PREFIX

An undeclared prefix was found when namespace processing was enabled.

xml.parsers.expat.errors.XML_ERROR_UNDECLARING_PREFIX

The document attempted to remove the namespace declaration associated with a prefix.

xml.parsers.expat.errors.XML_ERROR_INCOMPLETE_PE

A parameter entity contained incomplete markup.

xml.parsers.expat.errors.XML_ERROR_XML_DECL

The document contained no document element at all.

xml.parsers.expat.errors.XML_ERROR_TEXT_DECL

There was an error parsing a text declaration in an external entity.

xml.parsers.expat.errors.XML_ERROR_PUBLICID

Characters were found in the public id that are not allowed.

xml.parsers.expat.errors.XML_ERROR_SUSPENDED

The requested operation was made on a suspended parser, but isn’t allowed. This includes attempts to provide additional input or to stop the parser.

xml.parsers.expat.errors.XML_ERROR_NOT_SUSPENDED

An attempt to resume the parser was made when the parser had not been suspended.

xml.parsers.expat.errors.XML_ERROR_ABORTED

This should not be reported to Python applications.

xml.parsers.expat.errors.XML_ERROR_FINISHED

The requested operation was made on a parser which was finished parsing input, but isn’t allowed. This includes attempts to provide additional input or to stop the parser.

xml.parsers.expat.errors.XML_ERROR_SUSPEND_PE

Footnotes

1

The encoding string included in XML output should conform to the appropriate standards. For example, “UTF-8” is valid, but “UTF8” is not. See https://www.w3.org/TR/2006/REC-xml11-20060816/#NT-EncodingDecl and https://www.iana.org/assignments/character-sets/character-sets.xhtml.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

구조화된 마크업 처리 도구 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

|

인터넷 프로토콜과 지원

이 장에서 설명하는 모듈은 인터넷 프로토콜을 구현하고 관련 기술을 지원합니다. 모두 파이썬으로 구현됩니다. 대부분 모듈은 시스템 의존적인 모듈 socket을 요구하는데, 현재 대부분의 대중적인 플랫폼에서 지원됩니다. 다음은 개요입니다:

webbrowser — 편리한 웹 브라우저 제어기

브라우저 제어기 객체

cgi — Common Gateway Interface support

Introduction

Using the cgi module

Higher Level Interface

Functions

Caring about security

Installing your CGI script on a Unix system

Testing your CGI script

Debugging CGI scripts

Common problems and solutions

cgitb — CGI 스크립트를 위한 트레이스백 관리자

wsgiref — WSGI 유틸리티와 참조 구현

wsgiref.util – WSGI 환경 유틸리티

wsgiref.headers – WSGI 응답 헤더 도구

wsgiref.simple_server – 간단한 WSGI HTTP 서버

wsgiref.validate — WSGI 적합성 검사기

wsgiref.handlers – 서버/게이트웨이 베이스 클래스

예제

urllib — URL 처리 모듈

urllib.request — Extensible library for opening URLs

Request Objects

OpenerDirector Objects

BaseHandler Objects

HTTPRedirectHandler Objects

HTTPCookieProcessor Objects

ProxyHandler Objects

HTTPPasswordMgr Objects

HTTPPasswordMgrWithPriorAuth Objects

AbstractBasicAuthHandler Objects

HTTPBasicAuthHandler Objects

ProxyBasicAuthHandler Objects

AbstractDigestAuthHandler Objects

HTTPDigestAuthHandler Objects

ProxyDigestAuthHandler Objects

HTTPHandler Objects

HTTPSHandler Objects

FileHandler Objects

DataHandler Objects

FTPHandler Objects

CacheFTPHandler Objects

UnknownHandler Objects

HTTPErrorProcessor Objects

Examples

Legacy interface

urllib.request Restrictions

urllib.response — Response classes used by urllib

urllib.parse — Parse URLs into components

URL Parsing

URL parsing security

Parsing ASCII Encoded Bytes

Structured Parse Results

URL Quoting

urllib.error — urllib.request에 의해 발생하는 예외 클래스

urllib.robotparser — robots.txt 구문 분석기

http — HTTP 모듈

HTTP 상태 코드

http.client — HTTP protocol client

HTTPConnection Objects

HTTPResponse Objects

Examples

HTTPMessage Objects

ftplib — FTP protocol client

FTP Objects

FTP_TLS Objects

poplib — POP3 프로토콜 클라이언트

POP3 객체

POP3 예제

imaplib — IMAP4 protocol client

IMAP4 Objects

IMAP4 Example

nntplib — NNTP protocol client

NNTP Objects

Attributes

Methods

Utility functions

smtplib — SMTP protocol client

SMTP Objects

SMTP Example

smtpd — SMTP Server

SMTPServer Objects

DebuggingServer Objects

PureProxy Objects

MailmanProxy Objects

SMTPChannel Objects

telnetlib — 텔넷 클라이언트

텔넷 객체

텔넷 예제

uuid — RFC 4122 에 따른 UUID 객체

예제

socketserver — A framework for network servers

Server Creation Notes

Server Objects

Request Handler Objects

Examples

socketserver.TCPServer Example

socketserver.UDPServer Example

Asynchronous Mixins

http.server — HTTP servers

Security Considerations

http.cookies — HTTP 상태 관리

쿠키 객체

Morsel 객체

예제

http.cookiejar — Cookie handling for HTTP clients

CookieJar and FileCookieJar Objects

FileCookieJar subclasses and co-operation with web browsers

CookiePolicy Objects

DefaultCookiePolicy Objects

Cookie Objects

Examples

xmlrpc — XMLRPC 서버와 클라이언트 모듈

xmlrpc.client — XML-RPC client access

ServerProxy Objects

DateTime Objects

Binary Objects

Fault Objects

ProtocolError Objects

MultiCall Objects

Convenience Functions

Example of Client Usage

Example of Client and Server Usage

xmlrpc.server — 기본 XML-RPC 서버

SimpleXMLRPCServer 객체

SimpleXMLRPCServer 예제

CGIXMLRPCRequestHandler

XMLRPC 서버 문서화

DocXMLRPCServer 객체

DocCGIXMLRPCRequestHandler

ipaddress — IPv4/IPv6 manipulation library

Convenience factory functions

IP Addresses

Address objects

Conversion to Strings and Integers

Operators

Comparison operators

Arithmetic operators

IP Network definitions

Prefix, net mask and host mask

Network objects

Operators

Logical operators

Iteration

Networks as containers of addresses

Interface objects

Operators

Logical operators

Other Module Level Functions

Custom Exceptions

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 프로토콜과 지원 »

|

webbrowser — 편리한 웹 브라우저 제어기

소스 코드: Lib/webbrowser.py [https://github.com/python/cpython/tree/3.7/Lib/webbrowser.py]

webbrowser 모듈은 웹 기반 문서를 사용자에게 표시할 수 있는 고수준 인터페이스를 제공합니다. 대부분은, 이 모듈의 open() 함수를 호출하면 올바른 작업이 수행됩니다.

유닉스에서, X11에서는 그래픽 브라우저가 선호되지만, 그래픽 브라우저를 사용할 수 없거나 X11 디스플레이를 사용할 수 없으면 텍스트 모드 브라우저가 사용됩니다. 텍스트 모드 브라우저가 사용되면, 사용자가 브라우저를 종료할 때까지 호출하는 프로세스가 블록 됩니다.

환경 변수 BROWSER가 있으면, 플랫폼 기본값보다 먼저 시도하기 위해 os.pathsep으로 구분된 브라우저 목록으로 해석됩니다. 목록 부분의 값에 문자열 %s가 포함되어 있으면, %s를 인자 URL로 치환해서 만들어지는 리터럴 브라우저 명령 줄로 해석됩니다; 부분이 %s를 포함하지 않으면, 단순히 시작할 브라우저의 이름으로 해석됩니다. 1

유닉스가 아닌 플랫폼에서, 또는 유닉스에서 원격 브라우저를 사용할 수 있을 때, 제어하는 프로세스는 사용자가 브라우저를 완료할 때까지 기다리지 않고, 원격 브라우저가 디스플레이에 자체 창을 유지하도록 허용합니다. 유닉스에서 원격 브라우저를 사용할 수 없으면, 제어하는 프로세스가 새 브라우저를 시작하고 기다랍니다.

스크립트 webbrowser는 모듈의 명령 줄 인터페이스로 사용될 수 있습니다. 인자로 URL을 받아들입니다. 다음과 같은 선택적 매개 변수를 받아들입니다: -n은 가능하다면 새 브라우저 창에서 URL을 엽니다; -t는 새 브라우저 페이지(“탭”)에서 URL을 엽니다. 당연히, 이 옵션들은 상호 배타적입니다. 사용 예:

python -m webbrowser -t "http://www.python.org"

다음 예외가 정의됩니다:

exception webbrowser.Error

브라우저 제어 에러가 일어날 때 발생하는 예외.

다음 함수가 정의됩니다:

webbrowser.open(url, new=0, autoraise=True)

기본 브라우저를 사용하여 url을 표시합니다. new가 0이면, 가능하다면 같은 브라우저 창에서 url이 열립니다. new가 1이면, 가능하다면 새 브라우저 창이 열립니다. new가 2이면, 가능하다면 새 브라우저 페이지(“탭”)가 열립니다. autoraise가 True이면, 가능하다면 창을 올립니다(raise) (이것은 많은 창 관리자에서 이 변수의 설정과 관계없이 일어납니다).

일부 플랫폼에서, 이 함수를 사용하여 파일명을 여는 것은 동작하고 운영 체제의 연결된 프로그램이 시작될 수 있습니다. 하지만, 이것은 지원되지도 이식성 있지도 않습니다.

webbrowser.open_new(url)

가능하다면, 기본 브라우저의 새 창에서 url을 엽니다, 그렇지 않으면, 유일한 브라우저 창에서 url을 엽니다.

webbrowser.open_new_tab(url)

가능하다면, 기본 브라우저의 새 페이지(“탭”)에서 url을 엽니다, 그렇지 않으면 open_new()와 동등합니다.

webbrowser.get(using=None)

브라우저 유형 using에 대한 제어기 객체를 반환합니다. using이 None이면, 호출자의 환경에 적합한 기본 브라우저을 위한 제어기 객체를 반환합니다.

webbrowser.register(name, constructor, instance=None, *, preferred=False)

브라우저 유형 name을 등록합니다. 일단 브라우저 유형이 등록되면, get() 함수는 해당 브라우저 유형에 대한 제어기를 반환할 수 있습니다. instance가 제공되지 않거나, None이면, 필요할 때 constructor가 매개 변수 없이 호출되어 인스턴스를 만듭니다. instance가 제공되면, constructor는 절대로 호출되지 않으며, None일 수 있습니다.

preferred를 True로 설정하면 이 브라우저를 인자 없이 get()을 호출할 때 선호되는 결과가 되도록 합니다. 그렇지 않으면, 이 엔트리 포인트는 BROWSER 변수를 설정하거나 선언한 처리기의 이름과 일치하는 비어 있지 않은 인자로 get()을 호출하려는 경우에만 유용합니다.

버전 3.7에서 변경: preferred 키워드 전용 매개 변수가 추가되었습니다.

여러 가지 브라우저 유형이 미리 정의되어 있습니다. 이 표는 get() 함수로 전달될 수 있는 유형 이름과 제어기 클래스의 해당 인스턴스 화를 제공합니다, 모두 이 모듈에서 정의됩니다.

유형 이름

클래스 이름

노트

'mozilla'

Mozilla('mozilla')

'firefox'

Mozilla('mozilla')

'netscape'

Mozilla('netscape')

'galeon'

Galeon('galeon')

'epiphany'

Galeon('epiphany')

'skipstone'

BackgroundBrowser('skipstone')

'kfmclient'

Konqueror()

(1)

'konqueror'

Konqueror()

(1)

'kfm'

Konqueror()

(1)

'mosaic'

BackgroundBrowser('mosaic')

'opera'

Opera()

'grail'

Grail()

'links'

GenericBrowser('links')

'elinks'

Elinks('elinks')

'lynx'

GenericBrowser('lynx')

'w3m'

GenericBrowser('w3m')

'windows-default'

WindowsDefault

(2)

'macosx'

MacOSX('default')

(3)

'safari'

MacOSX('safari')

(3)

'google-chrome'

Chrome('google-chrome')

'chrome'

Chrome('chrome')

'chromium'

Chromium('chromium')

'chromium-browser'

Chromium('chromium-browser')

노트:

“Konqueror”는 유닉스용 KDE 데스크톱 환경의 파일 관리자이며, KDE가 실행 중일 때만 의미가 있습니다. 신뢰성 있게 KDE를 탐지하는 방법이 있다면 좋을 것입니다; KDEDIR 변수로는 충분하지 않습니다. KDE 2에서 konqueror 명령을 사용할 때조차도 “kfm”이라는 이름이 사용됨에 유의하십시오 — 구현이 Konqueror를 실행하기 위한 최상의 전략을 선택합니다.

윈도우 플랫폼에서만.

맥 OS X 플랫폼에서만.

버전 3.3에 추가: Chrome/Chromium에 대한 지원이 추가되었습니다.

여기 몇 가지 간단한 예제가 있습니다:

url = 'http://docs.python.org/'

# Open URL in a new tab, if a browser window is already open.
webbrowser.open_new_tab(url)

# Open URL in new window, raising the window if possible.
webbrowser.open_new(url)

브라우저 제어기 객체

브라우저 제어기는 세 가지 모듈 수준의 편리 함수와 평행하게 다음과 같은 메서드를 제공합니다:

controller.open(url, new=0, autoraise=True)

이 제어기가 처리하는 브라우저를 사용하여 url을 표시합니다. new가 1이면, 가능하다면 새 브라우저 창이 열립니다. new가 2이면, 가능하다면 새 브라우저 페이지(“탭”)가 열립니다.

controller.open_new(url)

가능하다면, 이 제어기가 처리하는 브라우저의 새 창에 url을 엽니다, 그렇지 않으면, 유일한 브라우저 창에 url을 엽니다. 별칭 open_new().

controller.open_new_tab(url)

가능하다면, 이 제어기가 처리하는 브라우저의 새 페이지(“탭”)에 url을 엽니다, 그렇지 않으면 open_new()와 동등합니다.

각주

1

전체 경로 없이 여기에서 명명된 실행 파일은 PATH 환경 변수에 지정된 디렉터리에서 검색됩니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 프로토콜과 지원 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 프로토콜과 지원 »

|

cgi — Common Gateway Interface support

Source code: Lib/cgi.py [https://github.com/python/cpython/tree/3.7/Lib/cgi.py]

Support module for Common Gateway Interface (CGI) scripts.

This module defines a number of utilities for use by CGI scripts written in Python.

Introduction

A CGI script is invoked by an HTTP server, usually to process user input submitted through an HTML <FORM> or <ISINDEX> element.

Most often, CGI scripts live in the server’s special cgi-bin directory. The HTTP server places all sorts of information about the request (such as the client’s hostname, the requested URL, the query string, and lots of other goodies) in the script’s shell environment, executes the script, and sends the script’s output back to the client.

The script’s input is connected to the client too, and sometimes the form data is read this way; at other times the form data is passed via the “query string” part of the URL. This module is intended to take care of the different cases and provide a simpler interface to the Python script. It also provides a number of utilities that help in debugging scripts, and the latest addition is support for file uploads from a form (if your browser supports it).

The output of a CGI script should consist of two sections, separated by a blank line. The first section contains a number of headers, telling the client what kind of data is following. Python code to generate a minimal header section looks like this:

print("Content-Type: text/html")    # HTML is following
print()                             # blank line, end of headers

The second section is usually HTML, which allows the client software to display nicely formatted text with header, in-line images, etc. Here’s Python code that prints a simple piece of HTML:

print("<TITLE>CGI script output</TITLE>")
print("<H1>This is my first CGI script</H1>")
print("Hello, world!")

Using the cgi module

Begin by writing import cgi.

When you write a new script, consider adding these lines:

import cgitb
cgitb.enable()

This activates a special exception handler that will display detailed reports in the Web browser if any errors occur. If you’d rather not show the guts of your program to users of your script, you can have the reports saved to files instead, with code like this:

import cgitb
cgitb.enable(display=0, logdir="/path/to/logdir")

It’s very helpful to use this feature during script development. The reports produced by cgitb provide information that can save you a lot of time in tracking down bugs. You can always remove the cgitb line later when you have tested your script and are confident that it works correctly.

To get at submitted form data, use the FieldStorage class. If the form contains non-ASCII characters, use the encoding keyword parameter set to the value of the encoding defined for the document. It is usually contained in the META tag in the HEAD section of the HTML document or by the Content-Type header). This reads the form contents from the standard input or the environment (depending on the value of various environment variables set according to the CGI standard). Since it may consume standard input, it should be instantiated only once.

The FieldStorage instance can be indexed like a Python dictionary. It allows membership testing with the in operator, and also supports the standard dictionary method keys() and the built-in function len(). Form fields containing empty strings are ignored and do not appear in the dictionary; to keep such values, provide a true value for the optional keep_blank_values keyword parameter when creating the FieldStorage instance.

For instance, the following code (which assumes that the Content-Type header and blank line have already been printed) checks that the fields name and addr are both set to a non-empty string:

form = cgi.FieldStorage()
if "name" not in form or "addr" not in form:
    print("<H1>Error</H1>")
    print("Please fill in the name and addr fields.")
    return
print("<p>name:", form["name"].value)
print("<p>addr:", form["addr"].value)
...further form processing here...

Here the fields, accessed through form[key], are themselves instances of FieldStorage (or MiniFieldStorage, depending on the form encoding). The value attribute of the instance yields the string value of the field. The getvalue() method returns this string value directly; it also accepts an optional second argument as a default to return if the requested key is not present.

If the submitted form data contains more than one field with the same name, the object retrieved by form[key] is not a FieldStorage or MiniFieldStorage instance but a list of such instances. Similarly, in this situation, form.getvalue(key) would return a list of strings. If you expect this possibility (when your HTML form contains multiple fields with the same name), use the getlist() method, which always returns a list of values (so that you do not need to special-case the single item case). For example, this code concatenates any number of username fields, separated by commas:

value = form.getlist("username")
usernames = ",".join(value)

If a field represents an uploaded file, accessing the value via the value attribute or the getvalue() method reads the entire file in memory as bytes. This may not be what you want. You can test for an uploaded file by testing either the filename attribute or the file attribute. You can then read the data from the file attribute before it is automatically closed as part of the garbage collection of the FieldStorage instance (the read() and readline() methods will return bytes):

fileitem = form["userfile"]
if fileitem.file:
    # It's an uploaded file; count lines
    linecount = 0
    while True:
        line = fileitem.file.readline()
        if not line: break
        linecount = linecount + 1

FieldStorage objects also support being used in a with statement, which will automatically close them when done.

If an error is encountered when obtaining the contents of an uploaded file (for example, when the user interrupts the form submission by clicking on a Back or Cancel button) the done attribute of the object for the field will be set to the value -1.

The file upload draft standard entertains the possibility of uploading multiple files from one field (using a recursive multipart/* encoding). When this occurs, the item will be a dictionary-like FieldStorage item. This can be determined by testing its type attribute, which should be multipart/form-data (or perhaps another MIME type matching multipart/*). In this case, it can be iterated over recursively just like the top-level form object.

When a form is submitted in the “old” format (as the query string or as a single data part of type application/x-www-form-urlencoded), the items will actually be instances of the class MiniFieldStorage. In this case, the list, file, and filename attributes are always None.

A form submitted via POST that also has a query string will contain both FieldStorage and MiniFieldStorage items.

버전 3.4에서 변경: The file attribute is automatically closed upon the garbage collection of the creating FieldStorage instance.

버전 3.5에서 변경: Added support for the context management protocol to the FieldStorage class.

Higher Level Interface

The previous section explains how to read CGI form data using the FieldStorage class. This section describes a higher level interface which was added to this class to allow one to do it in a more readable and intuitive way. The interface doesn’t make the techniques described in previous sections obsolete — they are still useful to process file uploads efficiently, for example.

The interface consists of two simple methods. Using the methods you can process form data in a generic way, without the need to worry whether only one or more values were posted under one name.

In the previous section, you learned to write following code anytime you expected a user to post more than one value under one name:

item = form.getvalue("item")
if isinstance(item, list):
    # The user is requesting more than one item.
else:
    # The user is requesting only one item.

This situation is common for example when a form contains a group of multiple checkboxes with the same name:

<input type="checkbox" name="item" value="1" />
<input type="checkbox" name="item" value="2" />

In most situations, however, there’s only one form control with a particular name in a form and then you expect and need only one value associated with this name. So you write a script containing for example this code:

user = form.getvalue("user").upper()

The problem with the code is that you should never expect that a client will provide valid input to your scripts. For example, if a curious user appends another user=foo pair to the query string, then the script would crash, because in this situation the getvalue("user") method call returns a list instead of a string. Calling the upper() method on a list is not valid (since lists do not have a method of this name) and results in an AttributeError exception.

Therefore, the appropriate way to read form data values was to always use the code which checks whether the obtained value is a single value or a list of values. That’s annoying and leads to less readable scripts.

A more convenient approach is to use the methods getfirst() and getlist() provided by this higher level interface.

FieldStorage.getfirst(name, default=None)

This method always returns only one value associated with form field name. The method returns only the first value in case that more values were posted under such name. Please note that the order in which the values are received may vary from browser to browser and should not be counted on. 1 If no such form field or value exists then the method returns the value specified by the optional parameter default. This parameter defaults to None if not specified.

FieldStorage.getlist(name)

This method always returns a list of values associated with form field name. The method returns an empty list if no such form field or value exists for name. It returns a list consisting of one item if only one such value exists.

Using these methods you can write nice compact code:

import cgi
form = cgi.FieldStorage()
user = form.getfirst("user", "").upper()    # This way it's safe.
for item in form.getlist("item"):
    do_something(item)

Functions

These are useful if you want more control, or if you want to employ some of the algorithms implemented in this module in other circumstances.

cgi.parse(fp=None, environ=os.environ, keep_blank_values=False, strict_parsing=False, separator="&")

Parse a query in the environment or from a file (the file defaults to sys.stdin). The keep_blank_values, strict_parsing and separator parameters are passed to urllib.parse.parse_qs() unchanged.

cgi.parse_qs(qs, keep_blank_values=False, strict_parsing=False)

This function is deprecated in this module. Use urllib.parse.parse_qs() instead. It is maintained here only for backward compatibility.

cgi.parse_qsl(qs, keep_blank_values=False, strict_parsing=False)

This function is deprecated in this module. Use urllib.parse.parse_qsl() instead. It is maintained here only for backward compatibility.

cgi.parse_multipart(fp, pdict, encoding="utf-8", errors="replace", separator="&")

Parse input of type multipart/form-data (for file uploads). Arguments are fp for the input file, pdict for a dictionary containing other parameters in the Content-Type header, and encoding, the request encoding.

Returns a dictionary just like urllib.parse.parse_qs(): keys are the field names, each value is a list of values for that field. For non-file fields, the value is a list of strings.

This is easy to use but not much good if you are expecting megabytes to be uploaded — in that case, use the FieldStorage class instead which is much more flexible.

버전 3.7에서 변경: Added the encoding and errors parameters. For non-file fields, the value is now a list of strings, not bytes.

버전 3.7.10에서 변경: Added the separator parameter.

cgi.parse_header(string)

Parse a MIME header (such as Content-Type) into a main value and a dictionary of parameters.

cgi.test()

Robust test CGI script, usable as main program. Writes minimal HTTP headers and formats all information provided to the script in HTML form.

cgi.print_environ()

Format the shell environment in HTML.

cgi.print_form(form)

Format a form in HTML.

cgi.print_directory()

Format the current directory in HTML.

cgi.print_environ_usage()

Print a list of useful (used by CGI) environment variables in HTML.

cgi.escape(s, quote=False)

Convert the characters '&', '<' and '>' in string s to HTML-safe sequences. Use this if you need to display text that might contain such characters in HTML. If the optional flag quote is true, the quotation mark character (") is also translated; this helps for inclusion in an HTML attribute value delimited by double quotes, as in <a href="...">. Note that single quotes are never translated.

버전 3.2부터 폐지: This function is unsafe because quote is false by default, and therefore deprecated. Use html.escape() instead.

Caring about security

There’s one important rule: if you invoke an external program (via the os.system() or os.popen() functions. or others with similar functionality), make very sure you don’t pass arbitrary strings received from the client to the shell. This is a well-known security hole whereby clever hackers anywhere on the Web can exploit a gullible CGI script to invoke arbitrary shell commands. Even parts of the URL or field names cannot be trusted, since the request doesn’t have to come from your form!

To be on the safe side, if you must pass a string gotten from a form to a shell command, you should make sure the string contains only alphanumeric characters, dashes, underscores, and periods.

Installing your CGI script on a Unix system

Read the documentation for your HTTP server and check with your local system administrator to find the directory where CGI scripts should be installed; usually this is in a directory cgi-bin in the server tree.

Make sure that your script is readable and executable by “others”; the Unix file mode should be 0o755 octal (use chmod 0755 filename). Make sure that the first line of the script contains #! starting in column 1 followed by the pathname of the Python interpreter, for instance:

#!/usr/local/bin/python

Make sure the Python interpreter exists and is executable by “others”.

Make sure that any files your script needs to read or write are readable or writable, respectively, by “others” — their mode should be 0o644 for readable and 0o666 for writable. This is because, for security reasons, the HTTP server executes your script as user “nobody”, without any special privileges. It can only read (write, execute) files that everybody can read (write, execute). The current directory at execution time is also different (it is usually the server’s cgi-bin directory) and the set of environment variables is also different from what you get when you log in. In particular, don’t count on the shell’s search path for executables (PATH) or the Python module search path (PYTHONPATH) to be set to anything interesting.

If you need to load modules from a directory which is not on Python’s default module search path, you can change the path in your script, before importing other modules. For example:

import sys
sys.path.insert(0, "/usr/home/joe/lib/python")
sys.path.insert(0, "/usr/local/lib/python")

(This way, the directory inserted last will be searched first!)

Instructions for non-Unix systems will vary; check your HTTP server’s documentation (it will usually have a section on CGI scripts).

Testing your CGI script

Unfortunately, a CGI script will generally not run when you try it from the command line, and a script that works perfectly from the command line may fail mysteriously when run from the server. There’s one reason why you should still test your script from the command line: if it contains a syntax error, the Python interpreter won’t execute it at all, and the HTTP server will most likely send a cryptic error to the client.

Assuming your script has no syntax errors, yet it does not work, you have no choice but to read the next section.

Debugging CGI scripts

First of all, check for trivial installation errors — reading the section above on installing your CGI script carefully can save you a lot of time. If you wonder whether you have understood the installation procedure correctly, try installing a copy of this module file (cgi.py) as a CGI script. When invoked as a script, the file will dump its environment and the contents of the form in HTML form. Give it the right mode etc, and send it a request. If it’s installed in the standard cgi-bin directory, it should be possible to send it a request by entering a URL into your browser of the form:

http://yourhostname/cgi-bin/cgi.py?name=Joe+Blow&addr=At+Home

If this gives an error of type 404, the server cannot find the script – perhaps you need to install it in a different directory. If it gives another error, there’s an installation problem that you should fix before trying to go any further. If you get a nicely formatted listing of the environment and form content (in this example, the fields should be listed as “addr” with value “At Home” and “name” with value “Joe Blow”), the cgi.py script has been installed correctly. If you follow the same procedure for your own script, you should now be able to debug it.

The next step could be to call the cgi module’s test() function from your script: replace its main code with the single statement

cgi.test()

This should produce the same results as those gotten from installing the cgi.py file itself.

When an ordinary Python script raises an unhandled exception (for whatever reason: of a typo in a module name, a file that can’t be opened, etc.), the Python interpreter prints a nice traceback and exits. While the Python interpreter will still do this when your CGI script raises an exception, most likely the traceback will end up in one of the HTTP server’s log files, or be discarded altogether.

Fortunately, once you have managed to get your script to execute some code, you can easily send tracebacks to the Web browser using the cgitb module. If you haven’t done so already, just add the lines:

import cgitb
cgitb.enable()

to the top of your script. Then try running it again; when a problem occurs, you should see a detailed report that will likely make apparent the cause of the crash.

If you suspect that there may be a problem in importing the cgitb module, you can use an even more robust approach (which only uses built-in modules):

import sys
sys.stderr = sys.stdout
print("Content-Type: text/plain")
print()
...your code here...

This relies on the Python interpreter to print the traceback. The content type of the output is set to plain text, which disables all HTML processing. If your script works, the raw HTML will be displayed by your client. If it raises an exception, most likely after the first two lines have been printed, a traceback will be displayed. Because no HTML interpretation is going on, the traceback will be readable.

Common problems and solutions

Most HTTP servers buffer the output from CGI scripts until the script is completed. This means that it is not possible to display a progress report on the client’s display while the script is running.

Check the installation instructions above.

Check the HTTP server’s log files. (tail -f logfile in a separate window may be useful!)

Always check a script for syntax errors first, by doing something like python script.py.

If your script does not have any syntax errors, try adding import cgitb; cgitb.enable() to the top of the script.

When invoking external programs, make sure they can be found. Usually, this means using absolute path names — PATH is usually not set to a very useful value in a CGI script.

When reading or writing external files, make sure they can be read or written by the userid under which your CGI script will be running: this is typically the userid under which the web server is running, or some explicitly specified userid for a web server’s suexec feature.

Don’t try to give a CGI script a set-uid mode. This doesn’t work on most systems, and is a security liability as well.

Footnotes

1

Note that some recent versions of the HTML specification do state what order the field values should be supplied in, but knowing whether a request was received from a conforming browser, or even from a browser at all, is tedious and error-prone.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 프로토콜과 지원 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 프로토콜과 지원 »

|

cgitb — CGI 스크립트를 위한 트레이스백 관리자

소스 코드: Lib/cgitb.py [https://github.com/python/cpython/tree/3.7/Lib/cgitb.py]

cgitb 모듈은 파이썬 스크립트를 위한 특별한 예외 처리기를 제공합니다. (이 이름은 약간 오해의 소지가 있습니다. 원래는 CGI 스크립트를 위해 HTML로 광범위한 트레이스백 정보를 표시하기 위해 고안됐습니다. 나중에 이 정보를 일반 텍스트로도 표시하도록 일반화됐습니다.) 이 모듈이 활성화된 후, 잡히지 않는 예외가 발생하면, 자세한 형식의 보고서가 표시됩니다. 보고서에는 문제를 디버그하는 데 도움이 되도록, 현재 실행 중인 함수의 인자와 지역 변수의 값뿐만 아니라 각 수준의 소스 코드 발췌를 보여주는 트레이스백이 포함되어 있습니다. 선택적으로, 이 정보를 브라우저로 보내지 않고 파일에 저장할 수 있습니다.

이 기능을 활성화하려면, 단순히 CGI 스크립트 상단에 이것을 추가하면 됩니다:

import cgitb
cgitb.enable()

enable() 함수에 제공되는 옵션은 브라우저에 보고서를 표시할지와 나중에 분석 할 수 있도록 보고서를 파일에 기록할지를 제어합니다.

cgitb.enable(display=1, logdir=None, context=5, format="html")

이 함수는 cgitb 모듈이 sys.excepthook 의 값을 설정하여 인터프리터의 기본 예외 처리를 인수하도록 합니다.

선택적 인자 display 는 기본적으로 1 로 설정되어 있으며 브라우저에 트레이스백을 보내지 않도록 0 으로 설정할 수 있습니다. logdir 인자가 있으면 트레이스백 보고서가 파일에 기록됩니다. logdir 값은 이 파일들이 위치 할 디렉터리여야 합니다. 선택적 인자 context 는 트레이스백에서 현재 소스 코드 행 주위에 표시할 문맥 행 수입니다. 기본값은 5 입니다. 선택적 인자 format 이 "html" 이면 출력은 HTML로 포맷됩니다. 그 외의 다른 값은 일반 텍스트 출력을 강제합니다. 기본값은 "html" 입니다.

cgitb.text(info, context=5)

이 함수는 info (sys.exc_info() 의 결과를 담은 3-튜플) 가 기술하는 예외를 처리하는데, 그 트레이스백을 텍스트로 포맷한 다음 결과를 문자열로 반환합니다. 선택적 인자 context 는 트레이스백에서 현재 소스 코드 행 주위에 표시할 문맥 행 수입니다. 기본값은 5 입니다.

cgitb.html(info, context=5)

이 함수는 info (sys.exc_info() 의 결과를 담은 3-튜플) 가 기술하는 예외를 처리하는데, 그 트레이스백을 HTML로 포맷한 다음 결과를 문자열로 반환합니다. 선택적 인자 context 는 트레이스백에서 현재 소스 코드 행 주위에 표시할 문맥 행 수입니다. 기본값은 5 입니다.

cgitb.handler(info=None)

이 함수는 기본 설정을 사용하여 예외를 처리합니다 (즉, 브라우저에 보고서를 표시하지만, 파일에 기록하지는 않습니다). 이것은 여러분이 예외를 잡았지만 cgitb를 사용해서 보고하고 싶을 때 사용할 수 있습니다. 선택적인 info 인자는 sys.exc_info() 에 의해 반환된 튜플과 똑같이, 예외 형, 예외 값, 트레이스백 객체를 포함하는 3-튜플이어야 합니다. info 인자가 제공되지 않으면, 현재 예외를 sys.exc_info()에서 얻습니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 프로토콜과 지원 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 프로토콜과 지원 »

|

wsgiref — WSGI 유틸리티와 참조 구현

WSGI(Web Server Gateway Interface)는 웹 서버 소프트웨어와 파이썬으로 작성된 웹 응용 프로그램 간의 표준 인터페이스입니다. 표준 인터페이스는 여러 웹 서버에서 WSGI를 지원하는 응용 프로그램을 쉽게 사용할 수 있도록 합니다.

웹 서버와 프로그래밍 프레임워크의 작성자만 WSGI 설계의 모든 세부 사항과 코너 케이스를 알 필요가 있습니다. 단지 WSGI 응용 프로그램을 설치하거나 기존 프레임워크를 사용하여 웹 응용 프로그램을 작성하기 위해, WSGI의 모든 세부 사항을 이해할 필요는 없습니다.

wsgiref는 웹 서버나 프레임워크에 WSGI 지원을 추가하는 데 사용할 수 있는, WSGI 명세의 참조 구현입니다. WSGI 환경 변수와 응답 헤더를 조작하는 유틸리티, WSGI 서버 구현을 위한 베이스 클래스, WSGI 응용 프로그램을 서비스하는 데모 HTTP 서버 및 WSGI 서버와 응용 프로그램이 WSGI 명세(PEP 3333 [https://www.python.org/dev/peps/pep-3333])에 부합하는지 확인하는 유효성 검사 도구를 제공합니다.

WSGI에 대한 더 자세한 정보 및 자습서와 기타 자원에 대한 링크는 wsgi.readthedocs.io [https://wsgi.readthedocs.io/]를 참조하십시오.

wsgiref.util – WSGI 환경 유틸리티

이 모듈은 WSGI 환경으로 작업하기 위한 다양한 유틸리티 함수를 제공합니다. WSGI 환경은 PEP 3333 [https://www.python.org/dev/peps/pep-3333]에서 설명한 대로 HTTP 요청 변수를 포함하는 딕셔너리입니다. environ 매개 변수를 취하는 모든 함수는 WSGI 호환 딕셔너리가 제공될 것으로 기대합니다; 자세한 명세는 PEP 3333 [https://www.python.org/dev/peps/pep-3333]를 참조하십시오.

wsgiref.util.guess_scheme(environ)

environ 딕셔너리에서 HTTPS 환경 변수를 검사하여 wsgi.url_scheme이 “http”와 “https” 중 어느 것인지 추측합니다. 반환 값은 문자열입니다.

이 함수는 CGI 나 FastCGI와 같은 CGI와 유사한 프로토콜을 감싸는 게이트웨이를 만들 때 유용합니다. 일반적으로, 이러한 프로토콜을 제공하는 서버는 SSL을 통해 요청이 수신될 때 “1”, “yes” 또는 “on” 값을 갖는 HTTPS 변수를 포함합니다. 따라서, 이 함수는 그런 값을 발견하면 “https”를 반환하고, 그렇지 않으면 “http”를 반환합니다.

wsgiref.util.request_uri(environ, include_query=True)

PEP 3333 [https://www.python.org/dev/peps/pep-3333]의 “URL 재구성” 절에 있는 알고리즘을 사용하여 전체 요청 URI를 반환합니다. 선택적으로 질의 문자열(query string)을 포함합니다. include_query가 거짓이면 질의 문자열은 결과 URI에 포함되지 않습니다.

wsgiref.util.application_uri(environ)

PATH_INFO 와 QUERY_STRING 변수가 무시된다는 점을 제외하면 request_uri()와 유사합니다. 결과는 요청이 가리키는 응용 프로그램 객체의 기본 URI입니다.

wsgiref.util.shift_path_info(environ)

단일 이름을 PATH_INFO에서 SCRIPT_NAME로 이동하고 이름을 반환합니다. environ 딕셔너리는 그 자리에서 수정됩니다; 원본 PATH_INFO 나 SCRIPT_NAME를 그대로 유지해야 하면 사본을 사용하십시오.

PATH_INFO에 남아있는 경로 세그먼트가 없으면, None이 반환됩니다.

일반적으로, 이 루틴은 요청 URI 경로의 각 부분을 처리하는 데 사용됩니다, 예를 들어 경로를 일련의 딕셔너리 키로 취급합니다. 이 루틴은 전달된 환경을 수정하여 대상 URI에 있는 다른 WSGI 응용 프로그램을 호출하는 데 적합하게 만듭니다. 예를 들어, /foo에 WSGI 응용 프로그램이 있고, 요청 URI 경로가 /foo/bar/baz이고, /foo의 WSGI 응용 프로그램이 shift_path_info()를 호출하면 “bar” 문자열을 수신하고 전달할 환경이 /foo/bar에 있는 WSGI 응용 프로그램에 전달하기 적합하도록 갱신됩니다. 즉, SCRIPT_NAME는 /foo에서 /foo/bar로 변경되고, PATH_INFO는 /bar/baz에서 /baz로 변경됩니다.

PATH_INFO가 단지 “/”일 때, 이 루틴은 빈 문자열을 반환하고 SCRIPT_NAME에 후행 슬래시를 추가합니다; 빈 경로 세그먼트는 일반적으로 무시되고, SCRIPT_NAME는 일반적으로 슬래시로 끝나지 않음에도 그렇게 합니다. 의도적인 동작입니다. 이 루틴을 사용하여 객체를 탐색할 때, 응용 프로그램이 /x로 끝나는 URI와 /x/로 끝나는 URI의 차이를 구별할 수 있도록 하기 위함입니다.

wsgiref.util.setup_testing_defaults(environ)

테스트 목적으로 environ를 뻔한 기본값으로 갱신합니다.

이 루틴은 HTTP_HOST, SERVER_NAME, SERVER_PORT, REQUEST_METHOD, SCRIPT_NAME, PATH_INFO 및 모든 PEP 3333 [https://www.python.org/dev/peps/pep-3333]에서 정의된 wsgi.* 변수를 포함하여 WSGI에 필요한 다양한 매개 변수를 추가합니다. 기본값만 제공하며, 이 변수들에 대한 기존 설정을 대체하지 않습니다.

이 루틴은 WSGI 서버와 응용 프로그램의 단위 테스트가 더미 환경을 쉽게 설정하도록 하기 위한 것입니다. 데이터가 가짜이므로, 실제 WSGI 서버나 응용 프로그램에서 사용해서는 안 됩니다!

사용 예:

from wsgiref.util import setup_testing_defaults
from wsgiref.simple_server import make_server

# A relatively simple WSGI application. It's going to print out the
# environment dictionary after being updated by setup_testing_defaults
def simple_app(environ, start_response):
    setup_testing_defaults(environ)

    status = '200 OK'
    headers = [('Content-type', 'text/plain; charset=utf-8')]

    start_response(status, headers)

    ret = [("%s: %s\n" % (key, value)).encode("utf-8")
           for key, value in environ.items()]
    return ret

with make_server('', 8000, simple_app) as httpd:
    print("Serving on port 8000...")
    httpd.serve_forever()

위의 환경 함수 외에도, wsgiref.util 모듈은 다음과 같은 기타 유틸리티를 제공합니다:

wsgiref.util.is_hop_by_hop(header_name)

Return True if ‘header_name’ is an HTTP/1.1 “Hop-by-Hop” header, as defined by RFC 2616 [https://tools.ietf.org/html/rfc2616.html].

class wsgiref.util.FileWrapper(filelike, blksize=8192)

파일류 객체를 이터레이터로 변환하는 래퍼. 결과 객체는 파이썬 2.1과 Jython과의 호환성을 위해, __getitem__() 과 __iter__() 이터레이션 스타일을 모두 지원합니다. 객체가 이터레이트될 때, 선택적인 blksize 매개 변수는 산출할 바이트열을 얻기 위해 filelike 객체의 read() 메서드에 반복적으로 전달됩니다. read()가 빈 바이트열을 반환하면 이터레이션이 종료되고 다시 시작할 수 없습니다.

filelike에 close() 메서드가 있으면, 반환된 객체에도 close() 메서드가 있고, 호출될 때 filelike 객체의 close() 메서드를 호출합니다.

사용 예:

from io import StringIO
from wsgiref.util import FileWrapper

# We're using a StringIO-buffer for as the file-like object
filelike = StringIO("This is an example file-like object"*10)
wrapper = FileWrapper(filelike, blksize=5)

for chunk in wrapper:
    print(chunk)

wsgiref.headers – WSGI 응답 헤더 도구

이 모듈은 매핑류 인터페이스를 사용하여 WSGI 응답 헤더를 편리하게 조작할 수 있는 클래스 Headers 하나를 제공합니다.

class wsgiref.headers.Headers([headers])

PEP 3333 [https://www.python.org/dev/peps/pep-3333]에 설명된 것처럼 헤더 이름/값 튜플의 리스트이어야 하는 headers를 감싸는 매핑류 객체를 만듭니다. headers의 기본값은 빈 리스트입니다.

Headers 객체는 __getitem__(), get(), __setitem__(), setdefault(), __delitem__() 및 __contains__()를 포함한 일반적인 매핑 연산을 지원합니다. 이러한 각 메서드에 대해, 키는 헤더 이름(대소 문자를 구분하지 않습니다)이며, 값은 해당 헤더 이름과 연관된 첫 번째 값입니다. 헤더를 설정하면 해당 헤더의 기존 값이 삭제된 다음, 감싸진 헤러 리스트의 끝에 새 값이 추가됩니다. 헤더의 기존 순서는 일반적으로 유지되며, 감싸진 리스트의 끝에 새 헤더가 추가됩니다.

딕셔너리와 달리, Headers 객체는 감싸진 헤더 리스트에 없는 키를 가져오거나 삭제하려고 하면 에러를 발생시키지 않습니다. 존재하지 않는 헤더를 가져오려고 하면 None을 반환하고, 존재하지 않는 헤더를 삭제하면 아무것도 하지 않습니다.

Headers 객체는 keys(), values() 및 items() 메서드도 지원합니다. keys() 와 items()에 의해 반환된 리스트에는 다중-값 헤더가 있으면 같은 키가 두 번 이상 포함될 수 있습니다. Headers 객체의 len()는 items()의 길이와 같고, 이는 감싸진 헤더 리스트의 길이와 같습니다. 실제로, items() 메서드는 단지 감싸진 헤더 리스트의 복사본을 반환합니다.

Headers 객체에서 bytes()를 호출하면 HTTP 응답 헤더로 전송하기에 적합한 포맷된 바이트열이 반환됩니다. 각 헤더는 콜론과 공백으로 구분된 값과 함께 줄에 들어갑니다. 각 줄은 캐리지 리턴과 줄넘김으로 끝나며, 바이트열은 빈 줄로 끝납니다.

Headers 객체는 매핑 인터페이스와 포매팅 기능 외에도, 다중-값 헤더를 조회하거나 추가하고, MIME 파라미터가 있는 헤더를 추가하기 위해 다음과 같은 메서드를 제공합니다:

get_all(name)

주어진 이름의 헤더에 대한 모든 값의 리스트를 반환합니다.

반환된 리스트는 원래 헤더 리스트에 나타나거나 이 인스턴스에 추가된 순서대로 정렬되고, 중복을 포함할 수 있습니다. 삭제되고 다시 삽입된 필드는 항상 헤더 리스트의 끝에 추가됩니다. 주어진 이름의 필드가 존재하지 않으면, 빈 리스트를 반환합니다.

add_header(name, value, **_params)

키워드 인자로 지정되는 선택적 MIME 파라미터와 함께 헤더를 추가합니다 (다중-값 가능).

name은 추가할 헤더 필드입니다. 키워드 인자는 헤더 필드에 대한 MIME 파라미터를 설정하는 데 사용될 수 있습니다. 각 파라미터는 문자열이나 None 이어야 합니다. 파라미터 이름의 밑줄은 대시로 변환됩니다; 파이썬 식별자에서는 대시가 유효하지 않지만 많은 MIME 파라미터 이름에는 대시가 포함되기 때문입니다. 파라미터값이 문자열이면 name="value" 형식으로 헤더 값 파라미터에 추가됩니다. None이면 파라미터 이름 만 추가됩니다. (이것은 값이 없는 MIME 파라미터에 사용됩니다.) 사용 예:

h.add_header('content-disposition', 'attachment', filename='bud.gif')

위의 코드는 다음과 같은 헤더를 추가합니다:

Content-Disposition: attachment; filename="bud.gif"

버전 3.5에서 변경: headers 매개 변수는 선택적입니다.

wsgiref.simple_server – 간단한 WSGI HTTP 서버

이 모듈은 WSGI 응용 프로그램을 서빙하는 간단한 HTTP 서버(http.server 기반)를 구현합니다. 각 서버 인스턴스는 주어진 호스트와 포트에서 단일 WSGI 응용 프로그램을 서빙합니다. 단일 호스트와 포트에서 여러 응용 프로그램을 서빙하려면, PATH_INFO를 구문 분석하여 각 요청에 대해 호출할 응용 프로그램을 선택하는 WSGI 응용 프로그램을 만들어야 합니다. (예를 들어, wsgiref.util의 shift_path_info() 함수를 사용해서.)

wsgiref.simple_server.make_server(host, port, app, server_class=WSGIServer, handler_class=WSGIRequestHandler)

host 와 port에서 수신을 기다리고, app에 대한 연결을 수락하는 새 WSGI 서버를 만듭니다. 반환 값은 제공된 server_class의 인스턴스이며, 지정된 handler_class를 사용하여 요청을 처리합니다. app는 PEP 3333 [https://www.python.org/dev/peps/pep-3333]에 정의된 WSGI 응용 프로그램 객체여야 합니다.

사용 예:

from wsgiref.simple_server import make_server, demo_app

with make_server('', 8000, demo_app) as httpd:
    print("Serving HTTP on port 8000...")

    # Respond to requests until process is killed
    httpd.serve_forever()

    # Alternative: serve one request, then exit
    httpd.handle_request()

wsgiref.simple_server.demo_app(environ, start_response)

이 함수는 작지만 완벽한 WSGI 응용 프로그램인데, “Hello world!” 메시지와 environ 매개 변수에 제공된 키/값 쌍 목록이 포함된 텍스트 페이지를 반환합니다. WSGI 서버(가령 wsgiref.simple_server)가 간단한 WSGI 응용 프로그램을 올바르게 실행할 수 있는지 확인하는 데 유용합니다.

class wsgiref.simple_server.WSGIServer(server_address, RequestHandlerClass)

WSGIServer 인스턴스를 만듭니다. server_address는 (host,port) 튜플이어야 하며, RequestHandlerClass는 http.server.BaseHTTPRequestHandler의 서브 클래스여야 하는데, 요청을 처리하는 데 사용됩니다.

make_server() 함수가 모든 세부 사항을 처리할 수 있으므로, 일반적으로 이 생성자를 호출할 필요가 없습니다.

WSGIServer는 http.server.HTTPServer의 서브 클래스이므로, 모든 메서드(가령 serve_forever()와 handle_request())를 사용할 수 있습니다. WSGIServer는 또한 다음과 같은 WSGI 전용 메서드를 제공합니다:

set_app(application)

콜러블 application을 요청을 수신하는 WSGI 응용 프로그램으로 설정합니다.

get_app()

현재 설정되어있는 응용 프로그램 콜러블을 반환합니다.

그러나 일반적으로, 이러한 추가 메서드를 사용할 필요가 없는데, set_app()는 일반적으로 make_server()에서 호출되고, get_app()은 주로 요청 처리기 인스턴스의 필요를 위해 존재하기 때문입니다

class wsgiref.simple_server.WSGIRequestHandler(request, client_address, server)

지정된 request (즉, 소켓), client_address ((host,port) 튜플) 및 server (WSGIServer 인스턴스)를 위한 HTTP 처리기를 만듭니다.

이 클래스의 인스턴스를 직접 만들 필요는 없습니다; WSGIServer 객체가 필요에 따라 자동으로 만듭니다. 그러나, 이 클래스를 서브 클래싱하여 handler_class로 make_server() 함수에 제공할 수 있습니다. 서브 클래스에서 재정의하는데 적합한 메서드들은 다음과 같습니다:

get_environ()

요청에 대한 WSGI 환경을 포함하는 딕셔너리를 반환합니다. 기본 구현은 WSGIServer 객체의 base_environ 딕셔너리 어트리뷰트의 내용을 복사한 다음, HTTP 요청으로부터 온 다양한 헤더를 추가합니다. 이 메서드를 호출할 때마다 PEP 3333 [https://www.python.org/dev/peps/pep-3333]에 지정된 CGI 환경 변수를 모두 포함하는 새 딕셔너리를 반환해야 합니다.

get_stderr()

wsgi.errors 스트림으로 사용해야 하는 객체를 반환합니다. 기본 구현은 단지 sys.stderr를 반환합니다.

handle()

HTTP 요청을 처리합니다. 기본 구현은 wsgiref.handlers 클래스를 사용하여 실제 WSGI 응용 프로그램 인터페이스를 구현하는 처리기 인스턴스를 만듭니다.

wsgiref.validate — WSGI 적합성 검사기

새로운 WSGI 응용 프로그램 객체, 프레임워크, 서버 또는 미들웨어를 만들 때, wsgiref.validate를 사용하여 새 코드의 적합성을 확인하는 것이 유용할 수 있습니다. 이 모듈은 WSGI 서버나 게이트웨이와 WSGI 응용 프로그램 객체 사이의 통신을 검증하는 WSGI 응용 프로그램 객체를 만드는 함수를 제공하여, 양측의 프로토콜 준수 여부를 검사할 수 있도록 합니다.

이 유틸리티는 완전한 PEP 3333 [https://www.python.org/dev/peps/pep-3333] 적합성을 보장하지는 않습니다; 이 모듈에서 에러가 없다고 해서 에러가 존재하지 않는다는 것을 의미하지는 않습니다. 그러나, 이 모듈에서 오류가 발생하면, 서버나 응용 프로그램이 100% 적합하지 않다는 것은 사실상 확실합니다.

이 모듈은 Ian Bicking의 “Python Paste” 라이브러리의 paste.lint 모듈을 기반으로 합니다.

wsgiref.validate.validator(application)

application 감싸고 새 WSGI 응용 프로그램 객체를 반환합니다. 반환된 응용 프로그램은 모든 요청을 원래 application으로 전달하고, application과 이를 호출하는 서버가 모두 WSGI 명세와 RFC 2616 [https://tools.ietf.org/html/rfc2616.html]를 준수하는지 확인합니다.

탐지된 모든 부적합 결과는 AssertionError를 일으킵니다; 그러나 이러한 에러를 처리하는 방법은 서버에 따라 다릅니다. 예를 들어, wsgiref.simple_server와 wsgiref.handlers를 기반으로 하는 다른 (에러 처리 메서드를 재정의해서 다른 작업을 수행하지 않는) 서버는 단순히 에러가 발생했다는 메시지를 출력하고 sys.stderr 나 기타 에러 스트림으로 트레이스백을 덤프합니다.

이 래퍼는 의심스럽기는 하지만 PEP 3333 [https://www.python.org/dev/peps/pep-3333]에서 실제로 금지되지 않을 수도 있는 동작을 나타내도록 warnings 모듈을 사용하여 출력을 생성할 수도 있습니다. 파이썬 명령 줄 옵션이나 warnings API를 사용해서 억제되지 않는 한, 그러한 경고는 sys.stderr(같은 객체가 아니라면 wsgi.errors가 아닙니다)에 기록됩니다.

사용 예:

from wsgiref.validate import validator
from wsgiref.simple_server import make_server

# Our callable object which is intentionally not compliant to the
# standard, so the validator is going to break
def simple_app(environ, start_response):
    status = '200 OK'  # HTTP Status
    headers = [('Content-type', 'text/plain')]  # HTTP Headers
    start_response(status, headers)

    # This is going to break because we need to return a list, and
    # the validator is going to inform us
    return b"Hello World"

# This is the application wrapped in a validator
validator_app = validator(simple_app)

with make_server('', 8000, validator_app) as httpd:
    print("Listening on port 8000....")
    httpd.serve_forever()

wsgiref.handlers – 서버/게이트웨이 베이스 클래스

이 모듈은 WSGI 서버와 게이트웨이를 구현하기 위한 베이스 처리기 클래스를 제공합니다. 이러한 베이스 클래스는 입력, 출력 및 에러 스트림과 함께 CGI와 유사한 환경이 제공되는 한, WSGI 응용 프로그램과 통신하는 대부분 작업을 처리합니다.

class wsgiref.handlers.CGIHandler

sys.stdin, sys.stdout, sys.stderr 및 os.environ를 통한 CGI 기반 호출. 이것은 WSGI 응용 프로그램이 있고 CGI 스크립트로 실행하려고 할 때 유용합니다. CGIHandler().run(app)을 호출하기만 하면 됩니다. 여기서 app은 호출할 WSGI 응용 프로그램 객체입니다.

이 클래스는 wsgi.run_once를 참으로, wsgi.multithread를 거짓으로, wsgi.multiprocess를 참으로 설정하고, 필요한 CGI 스트림과 환경을 얻기 위해 항상 sys와 os를 사용하는 BaseCGIHandler의 서브 클래스입니다.

class wsgiref.handlers.IISCGIHandler

config allowPathInfo 옵션 (IIS>=7) 나 metabase allowPathInfoForScriptMappings (IIS<7)를 설정하지 않고도, Microsoft IIS 웹 서버에 배포할 때 사용할 수 있는 CGIHandler의 특수한 대안.

기본적으로, IIS는 앞에 SCRIPT_NAME이 중복된 PATH_INFO를 제공하므로, 라우팅을 구현하려는 WSGI 응용 프로그램에 문제가 발생합니다. 이 처리기는 중복된 경로를 제거합니다.

IIS가 올바른 PATH_INFO를 전달하도록 구성할 수 있지만, PATH_TRANSLATED가 잘못되는 다른 버그가 발생합니다. 다행히도 이 변수는 거의 사용되지 않으며 WSGI에서 보장하지 않습니다. 그러나 IIS<7에서는 설정이 가상 호스트 수준에서만 이루어지므로, 다른 모든 스크립트 매핑에 영향을 미치며, 그중 많은 것들이 PATH_TRANSLATED 버그에 노출되면 망가집니다. 이러한 이유로 IIS<7은 거의 수정해서 배포되지 않습니다. (아직도 UI가 없어서 IIS7 조차도 거의 사용하지 않습니다.)

CGI 코드가 옵션이 설정되었는지를 알 수 있는 방법이 없으므로, 별도의 처리기 클래스가 제공됩니다. CGIHandler와 같은 방식으로 사용됩니다. 즉, IISCGIHandler().run(app)을 호출합니다. 여기서 app은 호출할 WSGI 응용 프로그램 객체입니다.

버전 3.2에 추가.

class wsgiref.handlers.BaseCGIHandler(stdin, stdout, stderr, environ, multithread=True, multiprocess=False)

CGIHandler와 유사하지만, sys 와 os 모듈을 사용하는 대신, CGI 환경과 I/O 스트림이 명시적으로 지정됩니다. multithread 와 multiprocess 값은 처리기 인스턴스가 실행하는 모든 응용 프로그램에 대한 wsgi.multithread 와 wsgi.multiprocess 플래그를 설정하는 데 사용됩니다.

이 클래스는 HTTP “오리진 서버” 이외의 소프트웨어에서 사용하기 위한 SimpleHandler의 서브 클래스입니다. HTTP 상태를 보내기 위해 Status: 헤더를 사용하는 게이트웨이 프로토콜 구현(가령 CGI, FastCGI, SCGI 등)을 작성하는 경우 SimpleHandler 대신 이것을 서브클래싱하고 싶을 겁니다.

class wsgiref.handlers.SimpleHandler(stdin, stdout, stderr, environ, multithread=True, multiprocess=False)

BaseCGIHandler와 유사하지만, HTTP 오리진 서버에 사용하도록 설계되었습니다. HTTP 서버 구현을 작성하는 경우 BaseCGIHandler 대신 이것을 서브 클래싱하고 싶을 겁니다.

이 클래스는 BaseHandler의 서브 클래스입니다. __init__(), get_stdin(), get_stderr(), add_cgi_vars(), _write() 및 _flush() 메서드를 재정의하여 명시적으로 환경과 스트림을 생성자를 통해 설정하는 것을 지원합니다. 제공된 환경과 스트림은 stdin, stdout, stderr 및 environ 어트리뷰트에 저장됩니다.

stdout의 write() 메서드는 io.BufferedIOBase처럼 각 덩어리 전체를 기록해야 합니다.

class wsgiref.handlers.BaseHandler

이것은 WSGI 응용 프로그램을 실행하기 위한 추상 베이스 클래스입니다. 원칙적으로 여러 요청에 대해 재사용할 수 있는 서브 클래스를 만들 수 있지만, 각 인스턴스는 단일 HTTP 요청을 처리합니다.

BaseHandler 인스턴스에는 외부 사용을 위한 하나의 메서드 만 있습니다:

run(app)

지정된 WSGI 응용 프로그램인 app을 실행합니다.

다른 모든 BaseHandler 메서드는 응용 프로그램을 실행하는 과정에서 이 메서드에 의해 호출되므로, 주로 과정을 사용자 정의하기 위해 존재합니다.

다음 메서드는 서브 클래스에서 반드시 재정의되어야 합니다:

_write(data)

클라이언트로의 전송을 위해 바이트열 data를 버퍼링합니다. 이 메서드가 실제로 데이터를 전송해도 상관없습니다; BaseHandler는 쓰기와 플러시 연산을 분리하여 하부 시스템에 실제로 이러한 구분이 있을 때 효율성을 높입니다.

_flush()

버퍼링 된 데이터를 클라이언트로 전송하도록 강제합니다. 이 메서드가 아무 일도 하지 않아도 상관없습니다 (즉, _write()가 실제로 데이터를 보낸다면).

get_stdin()

현재 처리 중인 요청의 wsgi.input으로 사용하기에 적합한 입력 스트림 객체를 반환합니다.

get_stderr()

현재 처리 중인 요청의 wsgi.errors로 사용하기에 적합한 출력 스트림 객체를 반환합니다.

add_cgi_vars()

현재 요청에 대한 CGI 변수를 environ 어트리뷰트에 삽입합니다.

재정의하고 싶을 수 있는 다른 메서드와 어트리뷰트는 다음과 같습니다. 그러나, 이 목록은 요약에 지나지 않고, 재정의할 수 있는 모든 메서드가 포함되어 있지 않습니다. 사용자 정의된 BaseHandler 서브 클래스를 작성하기 전에 독스트링과 소스 코드를 참조하여 추가 정보를 얻어야 합니다.

WSGI 환경을 사용자 정의하기 위한 어트리뷰트와 메서드:

wsgi_multithread

wsgi.multithread 환경 변수에 사용될 값. BaseHandler에서는 기본값이 참이지만, 다른 서브 클래스는 다른 기본값을 가질 수 있습니다 (또는 생성자에 의해 설정될 수 있습니다).

wsgi_multiprocess

wsgi.multiprocess 환경 변수에 사용될 값. BaseHandler에서는 기본값이 참이지만, 다른 서브 클래스는 다른 기본값을 가질 수 있습니다 (또는 생성자에 의해 설정될 수 있습니다).

wsgi_run_once

wsgi.run_once 환경 변수에 사용될 값. BaseHandler에서는 기본값이 거짓이지만, CGIHandler는 기본적으로 참으로 설정합니다.

os_environ

모든 요청의 WSGI 환경에 포함될 기본 환경 변수. 기본적으로, wsgiref.handlers를 임포트 한 시점의 os.environ 사본이지만, 서브 클래스는 클래스나 인스턴스 수준에서 자체적으로 만들 수 있습니다. 기본값이 여러 클래스와 인스턴스 간에 공유되므로, 딕셔너리는 읽기 전용으로 간주해야 합니다.

server_software

origin_server 어트리뷰트가 설정된 경우, 이 어트리뷰트의 값은 기본 SERVER_SOFTWARE WSGI 환경 변수를 설정하는 데 사용되고, HTTP 응답의 기본 Server: 헤더를 설정하는 데도 사용됩니다. HTTP 오리진 서버가 아닌 처리기(가령 BaseCGIHandler 와 CGIHandler)에서는 무시됩니다.

버전 3.3에서 변경: “Python”이라는 용어는 “CPython”, “Jython” 등과 같은 구현 특정 용어로 대체됩니다.

get_scheme()

현재의 요청에 사용되고 있는 URL 스킴을 반환합니다. 기본 구현은 wsgiref.util의 guess_scheme() 함수를 사용하여, 현재 요청의 environ 변수를 기반으로, 스킴이 “http”와 “https” 중 어느 것인지 추측합니다.

setup_environ()

environ 어트리뷰트를 완전히 채워진 WSGI 환경으로 설정합니다. 기본 구현에서는 위의 모든 메서드와 어트리뷰트에 더해 get_stdin(), get_stderr() 및 add_cgi_vars() 메서드와 wsgi_file_wrapper 어트리뷰트를 모두 사용합니다. origin_server 어트리뷰트가 참이고 server_software 어트리뷰트가 설정된 경우 SERVER_SOFTWARE 키가 없으면 삽입합니다.

예외 처리를 사용자 정의하기 위한 메서드와 어트리뷰트:

log_exception(exc_info)

exc_info 튜플을 서버 로그에 기록합니다. exc_info는 (type, value, traceback) 튜플입니다. 기본 구현은 요청의 wsgi.errors 스트림에 트레이스백을 쓰고 플러시 합니다. 서브 클래스는 이 메서드를 재정의해서, 형식을 변경하거나 출력의 대상을 바꾸거나, 관리자에게 트레이스백을 메일로 보내거나, 적절한 것으로 생각되는 다른 액션을 수행할 수 있습니다.

traceback_limit

기본 log_exception() 메서드에 의해 출력되는 트레이스백에 포함하는 프레임의 최대 수. None이면, 모든 프레임이 포함됩니다.

error_output(environ, start_response)

이 메서드는 사용자를 위한 에러 페이지를 생성하는 WSGI 응용 프로그램입니다. 헤더가 클라이언트에 전송되기 전에 오류가 발생할 때만 호출됩니다.

이 메서드는 sys.exc_info()를 사용하여 현재 에러 정보에 액세스할 수 있으며, 호출할 때 해당 정보를 start_response로 전달해야 합니다 (PEP 3333 [https://www.python.org/dev/peps/pep-3333]의 “에러 처리” 절에서 설명하듯이).

기본 구현은 error_status, error_headers 및 error_body 어트리뷰트를 사용하여 출력 페이지를 생성합니다. 서브 클래스는 이것을 재정의하여, 더욱 동적인 에러 출력을 생성할 수 있습니다.

그러나, 보안 관점에서 오래된 사용자에게는 진단을 내보내지 않는 것이 좋습니다; 이상적으로, 진단 출력을 활성화하기 위해서는 특별한 것을 해야 합니다. 이것이 기본 구현이 아무것도 포함하지 않는 이유입니다.

error_status

에러 응답에 사용되는 HTTP 상태. PEP 3333 [https://www.python.org/dev/peps/pep-3333]에 정의된 상태 문자열이어야 합니다; 기본값은 500 코드와 메시지입니다.

error_headers

에러 응답에 사용되는 HTTP 헤더. 이것은 PEP 3333 [https://www.python.org/dev/peps/pep-3333]에서 설명하는 WSGI 응답 헤더 ((name, value) 튜플)의 리스트여야 합니다. 기본 리스트는 단지 콘텐츠 형식을 text/plain으로 설정합니다.

error_body

에러 응답 바디. 이것은 HTTP 응답 바디 바이트열이어야 합니다. 기본적으로 “A server error occurred. Please contact the administrator.” 라는 단순 텍스트입니다.

PEP 3333 [https://www.python.org/dev/peps/pep-3333]의 “선택적 플랫폼 특정 파일 처리” 기능을 위한 메서드와 어트리뷰트:

wsgi_file_wrapper

wsgi.file_wrapper 팩토리나 None. 이 어트리뷰트의 기본값은 wsgiref.util.FileWrapper 클래스입니다.

sendfile()

플랫폼 특정 파일 전송을 구현하기 위해 재정의합니다. 이 메서드는 응용 프로그램의 반환 값이 wsgi_file_wrapper 어트리뷰트로 지정된 클래스의 인스턴스일 때만 호출됩니다. 파일을 성공적으로 전송할 수 있었으면 참값을 반환해야 합니다. 그러면 기본 전송 코드가 실행되지 않습니다. 이 메서드의 기본 구현은 단지 거짓 값을 반환합니다.

기타 메서드와 어트리뷰트:

origin_server

특별한 Status: 헤더를 통해 HTTP 상태를 원하는 CGI와 같은 게이트웨이 프로토콜을 통하는 것이 아니라, 처리기의 _write()와 _flush()가 클라이언트와 직접 통신하는 데 사용되는 경우 이 어트리뷰트를 참으로 설정해야 합니다.

BaseHandler에서는 이 어트리뷰트의 기본값이 참이지만, BaseCGIHandler와 CGIHandler에서는 거짓입니다.

http_version

origin_server가 참이면, 이 문자열 어트리뷰트를 사용하여 클라이언트로 보내는 응답 집합의 HTTP 버전을 설정합니다. 기본값은 "1.0"입니다.

wsgiref.handlers.read_environ()

CGI 변수를 os.environ에서 PEP 3333 “유니코드에 들어있는 바이트열” 문자열로 변환하여, 새 딕셔너리를 반환합니다. 이 함수는 os.environ을 직접 사용하는 대신 CGIHandler와 IISCGIHandler에서 사용됩니다. os.environ은 파이썬 3을 사용하는 모든 플랫폼과 웹 서버에서 WSGI를 준수한다는 보장이 없습니다 – 구체적으로, OS의 실제 환경이 유니코드인 곳(가령 윈도우)이나 환경은 바이트열이지만 파이썬이 디코딩하기 위해 사용하는 시스템 인코딩이 ISO-8859-1 이외의 것인 곳(예를 들어 UTF-8을 사용하는 유닉스 시스템).

여러분 자신의 CGI 기반 처리기를 구현한다면, os.environ에서 직접 값을 복사하는 대신 이 루틴을 사용하는 것이 좋습니다.

버전 3.2에 추가.

예제

이것은 “Hello World” WSGI 응용 프로그램입니다:

from wsgiref.simple_server import make_server

# Every WSGI application must have an application object - a callable
# object that accepts two arguments. For that purpose, we're going to
# use a function (note that you're not limited to a function, you can
# use a class for example). The first argument passed to the function
# is a dictionary containing CGI-style environment variables and the
# second variable is the callable object (see PEP 333).
def hello_world_app(environ, start_response):
    status = '200 OK'  # HTTP Status
    headers = [('Content-type', 'text/plain; charset=utf-8')]  # HTTP Headers
    start_response(status, headers)

    # The returned object is going to be printed
    return [b"Hello World"]

with make_server('', 8000, hello_world_app) as httpd:
    print("Serving on port 8000...")

    # Serve until process is killed
    httpd.serve_forever()

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 프로토콜과 지원 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 프로토콜과 지원 »

|

urllib — URL 처리 모듈

소스 코드: Lib/urllib/ [https://github.com/python/cpython/tree/3.7/Lib/urllib/]

urllib는 URL 작업을 위한 여러 모듈을 모은 패키지입니다.:

URL을 열고 읽기 위한 urllib.request

urllib.request에 의해 발생하는 예외를 포함하는 urllib.error

URL 구문 분석을 위한 urllib.parse

robots.txt 파일을 구문 분석하기 위한 urllib.robotparser

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 프로토콜과 지원 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 프로토콜과 지원 »

|

urllib.request — Extensible library for opening URLs

Source code: Lib/urllib/request.py [https://github.com/python/cpython/tree/3.7/Lib/urllib/request.py]

The urllib.request module defines functions and classes which help in opening URLs (mostly HTTP) in a complex world — basic and digest authentication, redirections, cookies and more.

더 보기

The Requests package [https://requests.readthedocs.io/en/master/] is recommended for a higher-level HTTP client interface.

The urllib.request module defines the following functions:

urllib.request.urlopen(url, data=None, [timeout, ]*, cafile=None, capath=None, cadefault=False, context=None)

Open the URL url, which can be either a string or a Request object.

data must be an object specifying additional data to be sent to the server, or None if no such data is needed. See Request for details.

urllib.request module uses HTTP/1.1 and includes Connection:close header in its HTTP requests.

The optional timeout parameter specifies a timeout in seconds for blocking operations like the connection attempt (if not specified, the global default timeout setting will be used). This actually only works for HTTP, HTTPS and FTP connections.

If context is specified, it must be a ssl.SSLContext instance describing the various SSL options. See HTTPSConnection for more details.

The optional cafile and capath parameters specify a set of trusted CA certificates for HTTPS requests. cafile should point to a single file containing a bundle of CA certificates, whereas capath should point to a directory of hashed certificate files. More information can be found in ssl.SSLContext.load_verify_locations().

The cadefault parameter is ignored.

This function always returns an object which can work as a context manager and has methods such as

geturl() — return the URL of the resource retrieved, commonly used to determine if a redirect was followed

info() — return the meta-information of the page, such as headers, in the form of an email.message_from_string() instance (see Quick Reference to HTTP Headers [http://jkorpela.fi/http.html])

getcode() – return the HTTP status code of the response.

For HTTP and HTTPS URLs, this function returns a http.client.HTTPResponse object slightly modified. In addition to the three new methods above, the msg attribute contains the same information as the reason attribute — the reason phrase returned by server — instead of the response headers as it is specified in the documentation for HTTPResponse.

For FTP, file, and data URLs and requests explicitly handled by legacy URLopener and FancyURLopener classes, this function returns a urllib.response.addinfourl object.

Raises URLError on protocol errors.

Note that None may be returned if no handler handles the request (though the default installed global OpenerDirector uses UnknownHandler to ensure this never happens).

In addition, if proxy settings are detected (for example, when a *_proxy environment variable like http_proxy is set), ProxyHandler is default installed and makes sure the requests are handled through the proxy.

The legacy urllib.urlopen function from Python 2.6 and earlier has been discontinued; urllib.request.urlopen() corresponds to the old urllib2.urlopen. Proxy handling, which was done by passing a dictionary parameter to urllib.urlopen, can be obtained by using ProxyHandler objects.

버전 3.2에서 변경: cafile and capath were added.

버전 3.2에서 변경: HTTPS virtual hosts are now supported if possible (that is, if ssl.HAS_SNI is true).

버전 3.2에 추가: data can be an iterable object.

버전 3.3에서 변경: cadefault was added.

버전 3.4.3에서 변경: context was added.

버전 3.6부터 폐지: cafile, capath and cadefault are deprecated in favor of context. Please use ssl.SSLContext.load_cert_chain() instead, or let ssl.create_default_context() select the system’s trusted CA certificates for you.

urllib.request.install_opener(opener)

Install an OpenerDirector instance as the default global opener. Installing an opener is only necessary if you want urlopen to use that opener; otherwise, simply call OpenerDirector.open() instead of urlopen(). The code does not check for a real OpenerDirector, and any class with the appropriate interface will work.

urllib.request.build_opener([handler, ...])

Return an OpenerDirector instance, which chains the handlers in the order given. handlers can be either instances of BaseHandler, or subclasses of BaseHandler (in which case it must be possible to call the constructor without any parameters). Instances of the following classes will be in front of the handlers, unless the handlers contain them, instances of them or subclasses of them: ProxyHandler (if proxy settings are detected), UnknownHandler, HTTPHandler, HTTPDefaultErrorHandler, HTTPRedirectHandler, FTPHandler, FileHandler, HTTPErrorProcessor.

If the Python installation has SSL support (i.e., if the ssl module can be imported), HTTPSHandler will also be added.

A BaseHandler subclass may also change its handler_order attribute to modify its position in the handlers list.

urllib.request.pathname2url(path)

Convert the pathname path from the local syntax for a path to the form used in the path component of a URL. This does not produce a complete URL. The return value will already be quoted using the quote() function.

urllib.request.url2pathname(path)

Convert the path component path from a percent-encoded URL to the local syntax for a path. This does not accept a complete URL. This function uses unquote() to decode path.

urllib.request.getproxies()

This helper function returns a dictionary of scheme to proxy server URL mappings. It scans the environment for variables named <scheme>_proxy, in a case insensitive approach, for all operating systems first, and when it cannot find it, looks for proxy information from Mac OSX System Configuration for Mac OS X and Windows Systems Registry for Windows. If both lowercase and uppercase environment variables exist (and disagree), lowercase is preferred.

참고

If the environment variable REQUEST_METHOD is set, which usually indicates your script is running in a CGI environment, the environment variable HTTP_PROXY (uppercase _PROXY) will be ignored. This is because that variable can be injected by a client using the “Proxy:” HTTP header. If you need to use an HTTP proxy in a CGI environment, either use ProxyHandler explicitly, or make sure the variable name is in lowercase (or at least the _proxy suffix).

The following classes are provided:

class urllib.request.Request(url, data=None, headers={}, origin_req_host=None, unverifiable=False, method=None)

This class is an abstraction of a URL request.

url should be a string containing a valid URL.

data must be an object specifying additional data to send to the server, or None if no such data is needed. Currently HTTP requests are the only ones that use data. The supported object types include bytes, file-like objects, and iterables. If no Content-Length nor Transfer-Encoding header field has been provided, HTTPHandler will set these headers according to the type of data. Content-Length will be used to send bytes objects, while Transfer-Encoding: chunked as specified in RFC 7230 [https://tools.ietf.org/html/rfc7230.html], Section 3.3.1 will be used to send files and other iterables.

For an HTTP POST request method, data should be a buffer in the standard application/x-www-form-urlencoded format. The urllib.parse.urlencode() function takes a mapping or sequence of 2-tuples and returns an ASCII string in this format. It should be encoded to bytes before being used as the data parameter.

headers should be a dictionary, and will be treated as if add_header() was called with each key and value as arguments. This is often used to “spoof” the User-Agent header value, which is used by a browser to identify itself – some HTTP servers only allow requests coming from common browsers as opposed to scripts. For example, Mozilla Firefox may identify itself as "Mozilla/5.0 (X11; U; Linux i686) Gecko/20071127 Firefox/2.0.0.11", while urllib’s default user agent string is "Python-urllib/2.6" (on Python 2.6).

An appropriate Content-Type header should be included if the data argument is present. If this header has not been provided and data is not None, Content-Type: application/x-www-form-urlencoded will be added as a default.

The next two arguments are only of interest for correct handling of third-party HTTP cookies:

origin_req_host should be the request-host of the origin transaction, as defined by RFC 2965 [https://tools.ietf.org/html/rfc2965.html]. It defaults to http.cookiejar.request_host(self). This is the host name or IP address of the original request that was initiated by the user. For example, if the request is for an image in an HTML document, this should be the request-host of the request for the page containing the image.

unverifiable should indicate whether the request is unverifiable, as defined by RFC 2965 [https://tools.ietf.org/html/rfc2965.html]. It defaults to False. An unverifiable request is one whose URL the user did not have the option to approve. For example, if the request is for an image in an HTML document, and the user had no option to approve the automatic fetching of the image, this should be true.

method should be a string that indicates the HTTP request method that will be used (e.g. 'HEAD'). If provided, its value is stored in the method attribute and is used by get_method(). The default is 'GET' if data is None or 'POST' otherwise. Subclasses may indicate a different default method by setting the method attribute in the class itself.

참고

The request will not work as expected if the data object is unable to deliver its content more than once (e.g. a file or an iterable that can produce the content only once) and the request is retried for HTTP redirects or authentication. The data is sent to the HTTP server right away after the headers. There is no support for a 100-continue expectation in the library.

버전 3.3에서 변경: Request.method argument is added to the Request class.

버전 3.4에서 변경: Default Request.method may be indicated at the class level.

버전 3.6에서 변경: Do not raise an error if the Content-Length has not been provided and data is neither None nor a bytes object. Fall back to use chunked transfer encoding instead.

class urllib.request.OpenerDirector

The OpenerDirector class opens URLs via BaseHandlers chained together. It manages the chaining of handlers, and recovery from errors.

class urllib.request.BaseHandler

This is the base class for all registered handlers — and handles only the simple mechanics of registration.

class urllib.request.HTTPDefaultErrorHandler

A class which defines a default handler for HTTP error responses; all responses are turned into HTTPError exceptions.

class urllib.request.HTTPRedirectHandler

A class to handle redirections.

class urllib.request.HTTPCookieProcessor(cookiejar=None)

A class to handle HTTP Cookies.

class urllib.request.ProxyHandler(proxies=None)

Cause requests to go through a proxy. If proxies is given, it must be a dictionary mapping protocol names to URLs of proxies. The default is to read the list of proxies from the environment variables <protocol>_proxy. If no proxy environment variables are set, then in a Windows environment proxy settings are obtained from the registry’s Internet Settings section, and in a Mac OS X environment proxy information is retrieved from the OS X System Configuration Framework.

To disable autodetected proxy pass an empty dictionary.

The no_proxy environment variable can be used to specify hosts which shouldn’t be reached via proxy; if set, it should be a comma-separated list of hostname suffixes, optionally with :port appended, for example cern.ch,ncsa.uiuc.edu,some.host:8080.

참고

HTTP_PROXY will be ignored if a variable REQUEST_METHOD is set; see the documentation on getproxies().

class urllib.request.HTTPPasswordMgr

Keep a database of (realm, uri) -> (user, password) mappings.

class urllib.request.HTTPPasswordMgrWithDefaultRealm

Keep a database of (realm, uri) -> (user, password) mappings. A realm of None is considered a catch-all realm, which is searched if no other realm fits.

class urllib.request.HTTPPasswordMgrWithPriorAuth

A variant of HTTPPasswordMgrWithDefaultRealm that also has a database of uri -> is_authenticated mappings. Can be used by a BasicAuth handler to determine when to send authentication credentials immediately instead of waiting for a 401 response first.

버전 3.5에 추가.

class urllib.request.AbstractBasicAuthHandler(password_mgr=None)

This is a mixin class that helps with HTTP authentication, both to the remote host and to a proxy. password_mgr, if given, should be something that is compatible with HTTPPasswordMgr; refer to section HTTPPasswordMgr Objects for information on the interface that must be supported. If passwd_mgr also provides is_authenticated and update_authenticated methods (see HTTPPasswordMgrWithPriorAuth Objects), then the handler will use the is_authenticated result for a given URI to determine whether or not to send authentication credentials with the request. If is_authenticated returns True for the URI, credentials are sent. If is_authenticated is False, credentials are not sent, and then if a 401 response is received the request is re-sent with the authentication credentials. If authentication succeeds, update_authenticated is called to set is_authenticated True for the URI, so that subsequent requests to the URI or any of its super-URIs will automatically include the authentication credentials.

버전 3.5에 추가: Added is_authenticated support.

class urllib.request.HTTPBasicAuthHandler(password_mgr=None)

Handle authentication with the remote host. password_mgr, if given, should be something that is compatible with HTTPPasswordMgr; refer to section HTTPPasswordMgr Objects for information on the interface that must be supported. HTTPBasicAuthHandler will raise a ValueError when presented with a wrong Authentication scheme.

class urllib.request.ProxyBasicAuthHandler(password_mgr=None)

Handle authentication with the proxy. password_mgr, if given, should be something that is compatible with HTTPPasswordMgr; refer to section HTTPPasswordMgr Objects for information on the interface that must be supported.

class urllib.request.AbstractDigestAuthHandler(password_mgr=None)

This is a mixin class that helps with HTTP authentication, both to the remote host and to a proxy. password_mgr, if given, should be something that is compatible with HTTPPasswordMgr; refer to section HTTPPasswordMgr Objects for information on the interface that must be supported.

class urllib.request.HTTPDigestAuthHandler(password_mgr=None)

Handle authentication with the remote host. password_mgr, if given, should be something that is compatible with HTTPPasswordMgr; refer to section HTTPPasswordMgr Objects for information on the interface that must be supported. When both Digest Authentication Handler and Basic Authentication Handler are both added, Digest Authentication is always tried first. If the Digest Authentication returns a 40x response again, it is sent to Basic Authentication handler to Handle. This Handler method will raise a ValueError when presented with an authentication scheme other than Digest or Basic.

버전 3.3에서 변경: Raise ValueError on unsupported Authentication Scheme.

class urllib.request.ProxyDigestAuthHandler(password_mgr=None)

Handle authentication with the proxy. password_mgr, if given, should be something that is compatible with HTTPPasswordMgr; refer to section HTTPPasswordMgr Objects for information on the interface that must be supported.

class urllib.request.HTTPHandler

A class to handle opening of HTTP URLs.

class urllib.request.HTTPSHandler(debuglevel=0, context=None, check_hostname=None)

A class to handle opening of HTTPS URLs. context and check_hostname have the same meaning as in http.client.HTTPSConnection.

버전 3.2에서 변경: context and check_hostname were added.

class urllib.request.FileHandler

Open local files.

class urllib.request.DataHandler

Open data URLs.

버전 3.4에 추가.

class urllib.request.FTPHandler

Open FTP URLs.

class urllib.request.CacheFTPHandler

Open FTP URLs, keeping a cache of open FTP connections to minimize delays.

class urllib.request.UnknownHandler

A catch-all class to handle unknown URLs.

class urllib.request.HTTPErrorProcessor

Process HTTP error responses.

Request Objects

The following methods describe Request’s public interface, and so all may be overridden in subclasses. It also defines several public attributes that can be used by clients to inspect the parsed request.

Request.full_url

The original URL passed to the constructor.

버전 3.4에서 변경.

Request.full_url is a property with setter, getter and a deleter. Getting full_url returns the original request URL with the fragment, if it was present.

Request.type

The URI scheme.

Request.host

The URI authority, typically a host, but may also contain a port separated by a colon.

Request.origin_req_host

The original host for the request, without port.

Request.selector

The URI path. If the Request uses a proxy, then selector will be the full URL that is passed to the proxy.

Request.data

The entity body for the request, or None if not specified.

버전 3.4에서 변경: Changing value of Request.data now deletes “Content-Length” header if it was previously set or calculated.

Request.unverifiable

boolean, indicates whether the request is unverifiable as defined by RFC 2965 [https://tools.ietf.org/html/rfc2965.html].

Request.method

The HTTP request method to use. By default its value is None, which means that get_method() will do its normal computation of the method to be used. Its value can be set (thus overriding the default computation in get_method()) either by providing a default value by setting it at the class level in a Request subclass, or by passing a value in to the Request constructor via the method argument.

버전 3.3에 추가.

버전 3.4에서 변경: A default value can now be set in subclasses; previously it could only be set via the constructor argument.

Request.get_method()

Return a string indicating the HTTP request method. If Request.method is not None, return its value, otherwise return 'GET' if Request.data is None, or 'POST' if it’s not. This is only meaningful for HTTP requests.

버전 3.3에서 변경: get_method now looks at the value of Request.method.

Request.add_header(key, val)

Add another header to the request. Headers are currently ignored by all handlers except HTTP handlers, where they are added to the list of headers sent to the server. Note that there cannot be more than one header with the same name, and later calls will overwrite previous calls in case the key collides. Currently, this is no loss of HTTP functionality, since all headers which have meaning when used more than once have a (header-specific) way of gaining the same functionality using only one header.

Request.add_unredirected_header(key, header)

Add a header that will not be added to a redirected request.

Request.has_header(header)

Return whether the instance has the named header (checks both regular and unredirected).

Request.remove_header(header)

Remove named header from the request instance (both from regular and unredirected headers).

버전 3.4에 추가.

Request.get_full_url()

Return the URL given in the constructor.

버전 3.4에서 변경.

Returns Request.full_url

Request.set_proxy(host, type)

Prepare the request by connecting to a proxy server. The host and type will replace those of the instance, and the instance’s selector will be the original URL given in the constructor.

Request.get_header(header_name, default=None)

Return the value of the given header. If the header is not present, return the default value.

Request.header_items()

Return a list of tuples (header_name, header_value) of the Request headers.

버전 3.4에서 변경: The request methods add_data, has_data, get_data, get_type, get_host, get_selector, get_origin_req_host and is_unverifiable that were deprecated since 3.3 have been removed.

OpenerDirector Objects

OpenerDirector instances have the following methods:

OpenerDirector.add_handler(handler)

handler should be an instance of BaseHandler. The following methods are searched, and added to the possible chains (note that HTTP errors are a special case). Note that, in the following, protocol should be replaced with the actual protocol to handle, for example http_response() would be the HTTP protocol response handler. Also type should be replaced with the actual HTTP code, for example http_error_404() would handle HTTP 404 errors.

<protocol>_open() — signal that the handler knows how to open protocol URLs.

See BaseHandler.<protocol>_open() for more information.

http_error_<type>() — signal that the handler knows how to handle HTTP errors with HTTP error code type.

See BaseHandler.http_error_<nnn>() for more information.

<protocol>_error() — signal that the handler knows how to handle errors from (non-http) protocol.

<protocol>_request() — signal that the handler knows how to pre-process protocol requests.

See BaseHandler.<protocol>_request() for more information.

<protocol>_response() — signal that the handler knows how to post-process protocol responses.

See BaseHandler.<protocol>_response() for more information.

OpenerDirector.open(url, data=None[, timeout])

Open the given url (which can be a request object or a string), optionally passing the given data. Arguments, return values and exceptions raised are the same as those of urlopen() (which simply calls the open() method on the currently installed global OpenerDirector). The optional timeout parameter specifies a timeout in seconds for blocking operations like the connection attempt (if not specified, the global default timeout setting will be used). The timeout feature actually works only for HTTP, HTTPS and FTP connections).

OpenerDirector.error(proto, *args)

Handle an error of the given protocol. This will call the registered error handlers for the given protocol with the given arguments (which are protocol specific). The HTTP protocol is a special case which uses the HTTP response code to determine the specific error handler; refer to the http_error_<type>() methods of the handler classes.

Return values and exceptions raised are the same as those of urlopen().

OpenerDirector objects open URLs in three stages:

The order in which these methods are called within each stage is determined by sorting the handler instances.

Every handler with a method named like <protocol>_request() has that method called to pre-process the request.

Handlers with a method named like <protocol>_open() are called to handle the request. This stage ends when a handler either returns a non-None value (ie. a response), or raises an exception (usually URLError). Exceptions are allowed to propagate.

In fact, the above algorithm is first tried for methods named default_open(). If all such methods return None, the algorithm is repeated for methods named like <protocol>_open(). If all such methods return None, the algorithm is repeated for methods named unknown_open().

Note that the implementation of these methods may involve calls of the parent OpenerDirector instance’s open() and error() methods.

Every handler with a method named like <protocol>_response() has that method called to post-process the response.

BaseHandler Objects

BaseHandler objects provide a couple of methods that are directly useful, and others that are meant to be used by derived classes. These are intended for direct use:

BaseHandler.add_parent(director)

Add a director as parent.

BaseHandler.close()

Remove any parents.

The following attribute and methods should only be used by classes derived from BaseHandler.

참고

The convention has been adopted that subclasses defining <protocol>_request() or <protocol>_response() methods are named *Processor; all others are named *Handler.

BaseHandler.parent

A valid OpenerDirector, which can be used to open using a different protocol, or handle errors.

BaseHandler.default_open(req)

This method is not defined in BaseHandler, but subclasses should define it if they want to catch all URLs.

This method, if implemented, will be called by the parent OpenerDirector. It should return a file-like object as described in the return value of the open() of OpenerDirector, or None. It should raise URLError, unless a truly exceptional thing happens (for example, MemoryError should not be mapped to URLError).

This method will be called before any protocol-specific open method.

BaseHandler.<protocol>_open(req)

This method is not defined in BaseHandler, but subclasses should define it if they want to handle URLs with the given protocol.

This method, if defined, will be called by the parent OpenerDirector. Return values should be the same as for default_open().

BaseHandler.unknown_open(req)

This method is not defined in BaseHandler, but subclasses should define it if they want to catch all URLs with no specific registered handler to open it.

This method, if implemented, will be called by the parent OpenerDirector. Return values should be the same as for default_open().

BaseHandler.http_error_default(req, fp, code, msg, hdrs)

This method is not defined in BaseHandler, but subclasses should override it if they intend to provide a catch-all for otherwise unhandled HTTP errors. It will be called automatically by the OpenerDirector getting the error, and should not normally be called in other circumstances.

req will be a Request object, fp will be a file-like object with the HTTP error body, code will be the three-digit code of the error, msg will be the user-visible explanation of the code and hdrs will be a mapping object with the headers of the error.

Return values and exceptions raised should be the same as those of urlopen().

BaseHandler.http_error_<nnn>(req, fp, code, msg, hdrs)

nnn should be a three-digit HTTP error code. This method is also not defined in BaseHandler, but will be called, if it exists, on an instance of a subclass, when an HTTP error with code nnn occurs.

Subclasses should override this method to handle specific HTTP errors.

Arguments, return values and exceptions raised should be the same as for http_error_default().

BaseHandler.<protocol>_request(req)

This method is not defined in BaseHandler, but subclasses should define it if they want to pre-process requests of the given protocol.

This method, if defined, will be called by the parent OpenerDirector. req will be a Request object. The return value should be a Request object.

BaseHandler.<protocol>_response(req, response)

This method is not defined in BaseHandler, but subclasses should define it if they want to post-process responses of the given protocol.

This method, if defined, will be called by the parent OpenerDirector. req will be a Request object. response will be an object implementing the same interface as the return value of urlopen(). The return value should implement the same interface as the return value of urlopen().

HTTPRedirectHandler Objects

참고

Some HTTP redirections require action from this module’s client code. If this is the case, HTTPError is raised. See RFC 2616 [https://tools.ietf.org/html/rfc2616.html] for details of the precise meanings of the various redirection codes.

An HTTPError exception raised as a security consideration if the HTTPRedirectHandler is presented with a redirected URL which is not an HTTP, HTTPS or FTP URL.

HTTPRedirectHandler.redirect_request(req, fp, code, msg, hdrs, newurl)

Return a Request or None in response to a redirect. This is called by the default implementations of the http_error_30*() methods when a redirection is received from the server. If a redirection should take place, return a new Request to allow http_error_30*() to perform the redirect to newurl. Otherwise, raise HTTPError if no other handler should try to handle this URL, or return None if you can’t but another handler might.

참고

The default implementation of this method does not strictly follow RFC 2616 [https://tools.ietf.org/html/rfc2616.html], which says that 301 and 302 responses to POST requests must not be automatically redirected without confirmation by the user. In reality, browsers do allow automatic redirection of these responses, changing the POST to a GET, and the default implementation reproduces this behavior.

HTTPRedirectHandler.http_error_301(req, fp, code, msg, hdrs)

Redirect to the Location: or URI: URL. This method is called by the parent OpenerDirector when getting an HTTP ‘moved permanently’ response.

HTTPRedirectHandler.http_error_302(req, fp, code, msg, hdrs)

The same as http_error_301(), but called for the ‘found’ response.

HTTPRedirectHandler.http_error_303(req, fp, code, msg, hdrs)

The same as http_error_301(), but called for the ‘see other’ response.

HTTPRedirectHandler.http_error_307(req, fp, code, msg, hdrs)

The same as http_error_301(), but called for the ‘temporary redirect’ response.

HTTPCookieProcessor Objects

HTTPCookieProcessor instances have one attribute:

HTTPCookieProcessor.cookiejar

The http.cookiejar.CookieJar in which cookies are stored.

ProxyHandler Objects

ProxyHandler.<protocol>_open(request)

The ProxyHandler will have a method <protocol>_open() for every protocol which has a proxy in the proxies dictionary given in the constructor. The method will modify requests to go through the proxy, by calling request.set_proxy(), and call the next handler in the chain to actually execute the protocol.

HTTPPasswordMgr Objects

These methods are available on HTTPPasswordMgr and HTTPPasswordMgrWithDefaultRealm objects.

HTTPPasswordMgr.add_password(realm, uri, user, passwd)

uri can be either a single URI, or a sequence of URIs. realm, user and passwd must be strings. This causes (user, passwd) to be used as authentication tokens when authentication for realm and a super-URI of any of the given URIs is given.

HTTPPasswordMgr.find_user_password(realm, authuri)

Get user/password for given realm and URI, if any. This method will return (None, None) if there is no matching user/password.

For HTTPPasswordMgrWithDefaultRealm objects, the realm None will be searched if the given realm has no matching user/password.

HTTPPasswordMgrWithPriorAuth Objects

This password manager extends HTTPPasswordMgrWithDefaultRealm to support tracking URIs for which authentication credentials should always be sent.

HTTPPasswordMgrWithPriorAuth.add_password(realm, uri, user, passwd, is_authenticated=False)

realm, uri, user, passwd are as for HTTPPasswordMgr.add_password(). is_authenticated sets the initial value of the is_authenticated flag for the given URI or list of URIs. If is_authenticated is specified as True, realm is ignored.

HTTPPasswordMgr.find_user_password(realm, authuri)

Same as for HTTPPasswordMgrWithDefaultRealm objects

HTTPPasswordMgrWithPriorAuth.update_authenticated(self, uri, is_authenticated=False)

Update the is_authenticated flag for the given uri or list of URIs.

HTTPPasswordMgrWithPriorAuth.is_authenticated(self, authuri)

Returns the current state of the is_authenticated flag for the given URI.

AbstractBasicAuthHandler Objects

AbstractBasicAuthHandler.http_error_auth_reqed(authreq, host, req, headers)

Handle an authentication request by getting a user/password pair, and re-trying the request. authreq should be the name of the header where the information about the realm is included in the request, host specifies the URL and path to authenticate for, req should be the (failed) Request object, and headers should be the error headers.

host is either an authority (e.g. "python.org") or a URL containing an authority component (e.g. "http://python.org/"). In either case, the authority must not contain a userinfo component (so, "python.org" and "python.org:80" are fine, "joe:password@python.org" is not).

HTTPBasicAuthHandler Objects

HTTPBasicAuthHandler.http_error_401(req, fp, code, msg, hdrs)

Retry the request with authentication information, if available.

ProxyBasicAuthHandler Objects

ProxyBasicAuthHandler.http_error_407(req, fp, code, msg, hdrs)

Retry the request with authentication information, if available.

AbstractDigestAuthHandler Objects

AbstractDigestAuthHandler.http_error_auth_reqed(authreq, host, req, headers)

authreq should be the name of the header where the information about the realm is included in the request, host should be the host to authenticate to, req should be the (failed) Request object, and headers should be the error headers.

HTTPDigestAuthHandler Objects

HTTPDigestAuthHandler.http_error_401(req, fp, code, msg, hdrs)

Retry the request with authentication information, if available.

ProxyDigestAuthHandler Objects

ProxyDigestAuthHandler.http_error_407(req, fp, code, msg, hdrs)

Retry the request with authentication information, if available.

HTTPHandler Objects

HTTPHandler.http_open(req)

Send an HTTP request, which can be either GET or POST, depending on req.has_data().

HTTPSHandler Objects

HTTPSHandler.https_open(req)

Send an HTTPS request, which can be either GET or POST, depending on req.has_data().

FileHandler Objects

FileHandler.file_open(req)

Open the file locally, if there is no host name, or the host name is 'localhost'.

버전 3.2에서 변경: This method is applicable only for local hostnames. When a remote hostname is given, an URLError is raised.

DataHandler Objects

DataHandler.data_open(req)

Read a data URL. This kind of URL contains the content encoded in the URL itself. The data URL syntax is specified in RFC 2397 [https://tools.ietf.org/html/rfc2397.html]. This implementation ignores white spaces in base64 encoded data URLs so the URL may be wrapped in whatever source file it comes from. But even though some browsers don’t mind about a missing padding at the end of a base64 encoded data URL, this implementation will raise an ValueError in that case.

FTPHandler Objects

FTPHandler.ftp_open(req)

Open the FTP file indicated by req. The login is always done with empty username and password.

CacheFTPHandler Objects

CacheFTPHandler objects are FTPHandler objects with the following additional methods:

CacheFTPHandler.setTimeout(t)

Set timeout of connections to t seconds.

CacheFTPHandler.setMaxConns(m)

Set maximum number of cached connections to m.

UnknownHandler Objects

UnknownHandler.unknown_open()

Raise a URLError exception.

HTTPErrorProcessor Objects

HTTPErrorProcessor.http_response(request, response)

Process HTTP error responses.

For 200 error codes, the response object is returned immediately.

For non-200 error codes, this simply passes the job on to the http_error_<type>() handler methods, via OpenerDirector.error(). Eventually, HTTPDefaultErrorHandler will raise an HTTPError if no other handler handles the error.

HTTPErrorProcessor.https_response(request, response)

Process HTTPS error responses.

The behavior is same as http_response().

Examples

In addition to the examples below, more examples are given in HOWTO Fetch Internet Resources Using The urllib Package.

This example gets the python.org main page and displays the first 300 bytes of it.

>>> import urllib.request
>>> with urllib.request.urlopen('http://www.python.org/') as f:
...     print(f.read(300))
...
b'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\n\n\n<html
xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">\n\n<head>\n
<meta http-equiv="content-type" content="text/html; charset=utf-8" />\n
<title>Python Programming '

Note that urlopen returns a bytes object. This is because there is no way for urlopen to automatically determine the encoding of the byte stream it receives from the HTTP server. In general, a program will decode the returned bytes object to string once it determines or guesses the appropriate encoding.

The following W3C document, https://www.w3.org/International/O-charset, lists the various ways in which an (X)HTML or an XML document could have specified its encoding information.

As the python.org website uses utf-8 encoding as specified in its meta tag, we will use the same for decoding the bytes object.

>>> with urllib.request.urlopen('http://www.python.org/') as f:
...     print(f.read(100).decode('utf-8'))
...
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtm

It is also possible to achieve the same result without using the context manager approach.

>>> import urllib.request
>>> f = urllib.request.urlopen('http://www.python.org/')
>>> print(f.read(100).decode('utf-8'))
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtm

In the following example, we are sending a data-stream to the stdin of a CGI and reading the data it returns to us. Note that this example will only work when the Python installation supports SSL.

>>> import urllib.request
>>> req = urllib.request.Request(url='https://localhost/cgi-bin/test.cgi',
...                       data=b'This data is passed to stdin of the CGI')
>>> with urllib.request.urlopen(req) as f:
...     print(f.read().decode('utf-8'))
...
Got Data: "This data is passed to stdin of the CGI"

The code for the sample CGI used in the above example is:

#!/usr/bin/env python
import sys
data = sys.stdin.read()
print('Content-type: text/plain\n\nGot Data: "%s"' % data)

Here is an example of doing a PUT request using Request:

import urllib.request
DATA = b'some data'
req = urllib.request.Request(url='http://localhost:8080', data=DATA,method='PUT')
with urllib.request.urlopen(req) as f:
    pass
print(f.status)
print(f.reason)

Use of Basic HTTP Authentication:

import urllib.request
# Create an OpenerDirector with support for Basic HTTP Authentication...
auth_handler = urllib.request.HTTPBasicAuthHandler()
auth_handler.add_password(realm='PDQ Application',
                          uri='https://mahler:8092/site-updates.py',
                          user='klem',
                          passwd='kadidd!ehopper')
opener = urllib.request.build_opener(auth_handler)
# ...and install it globally so it can be used with urlopen.
urllib.request.install_opener(opener)
urllib.request.urlopen('http://www.example.com/login.html')

build_opener() provides many handlers by default, including a ProxyHandler. By default, ProxyHandler uses the environment variables named <scheme>_proxy, where <scheme> is the URL scheme involved. For example, the http_proxy environment variable is read to obtain the HTTP proxy’s URL.

This example replaces the default ProxyHandler with one that uses programmatically-supplied proxy URLs, and adds proxy authorization support with ProxyBasicAuthHandler.

proxy_handler = urllib.request.ProxyHandler({'http': 'http://www.example.com:3128/'})
proxy_auth_handler = urllib.request.ProxyBasicAuthHandler()
proxy_auth_handler.add_password('realm', 'host', 'username', 'password')

opener = urllib.request.build_opener(proxy_handler, proxy_auth_handler)
# This time, rather than install the OpenerDirector, we use it directly:
opener.open('http://www.example.com/login.html')

Adding HTTP headers:

Use the headers argument to the Request constructor, or:

import urllib.request
req = urllib.request.Request('http://www.example.com/')
req.add_header('Referer', 'http://www.python.org/')
# Customize the default User-Agent header value:
req.add_header('User-Agent', 'urllib-example/0.1 (Contact: . . .)')
r = urllib.request.urlopen(req)

OpenerDirector automatically adds a User-Agent header to every Request. To change this:

import urllib.request
opener = urllib.request.build_opener()
opener.addheaders = [('User-agent', 'Mozilla/5.0')]
opener.open('http://www.example.com/')

Also, remember that a few standard headers (Content-Length, Content-Type and Host) are added when the Request is passed to urlopen() (or OpenerDirector.open()).

Here is an example session that uses the GET method to retrieve a URL containing parameters:

>>> import urllib.request
>>> import urllib.parse
>>> params = urllib.parse.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
>>> url = "http://www.musi-cal.com/cgi-bin/query?%s" % params
>>> with urllib.request.urlopen(url) as f:
...     print(f.read().decode('utf-8'))
...

The following example uses the POST method instead. Note that params output from urlencode is encoded to bytes before it is sent to urlopen as data:

>>> import urllib.request
>>> import urllib.parse
>>> data = urllib.parse.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
>>> data = data.encode('ascii')
>>> with urllib.request.urlopen("http://requestb.in/xrbl82xr", data) as f:
...     print(f.read().decode('utf-8'))
...

The following example uses an explicitly specified HTTP proxy, overriding environment settings:

>>> import urllib.request
>>> proxies = {'http': 'http://proxy.example.com:8080/'}
>>> opener = urllib.request.FancyURLopener(proxies)
>>> with opener.open("http://www.python.org") as f:
...     f.read().decode('utf-8')
...

The following example uses no proxies at all, overriding environment settings:

>>> import urllib.request
>>> opener = urllib.request.FancyURLopener({})
>>> with opener.open("http://www.python.org/") as f:
...     f.read().decode('utf-8')
...

Legacy interface

The following functions and classes are ported from the Python 2 module urllib (as opposed to urllib2). They might become deprecated at some point in the future.

urllib.request.urlretrieve(url, filename=None, reporthook=None, data=None)

Copy a network object denoted by a URL to a local file. If the URL points to a local file, the object will not be copied unless filename is supplied. Return a tuple (filename, headers) where filename is the local file name under which the object can be found, and headers is whatever the info() method of the object returned by urlopen() returned (for a remote object). Exceptions are the same as for urlopen().

The second argument, if present, specifies the file location to copy to (if absent, the location will be a tempfile with a generated name). The third argument, if present, is a callable that will be called once on establishment of the network connection and once after each block read thereafter. The callable will be passed three arguments; a count of blocks transferred so far, a block size in bytes, and the total size of the file. The third argument may be -1 on older FTP servers which do not return a file size in response to a retrieval request.

The following example illustrates the most common usage scenario:

>>> import urllib.request
>>> local_filename, headers = urllib.request.urlretrieve('http://python.org/')
>>> html = open(local_filename)
>>> html.close()

If the url uses the http: scheme identifier, the optional data argument may be given to specify a POST request (normally the request type is GET). The data argument must be a bytes object in standard application/x-www-form-urlencoded format; see the urllib.parse.urlencode() function.

urlretrieve() will raise ContentTooShortError when it detects that the amount of data available was less than the expected amount (which is the size reported by a Content-Length header). This can occur, for example, when the download is interrupted.

The Content-Length is treated as a lower bound: if there’s more data to read, urlretrieve reads more data, but if less data is available, it raises the exception.

You can still retrieve the downloaded data in this case, it is stored in the content attribute of the exception instance.

If no Content-Length header was supplied, urlretrieve can not check the size of the data it has downloaded, and just returns it. In this case you just have to assume that the download was successful.

urllib.request.urlcleanup()

Cleans up temporary files that may have been left behind by previous calls to urlretrieve().

class urllib.request.URLopener(proxies=None, **x509)

버전 3.3부터 폐지.

Base class for opening and reading URLs. Unless you need to support opening objects using schemes other than http:, ftp:, or file:, you probably want to use FancyURLopener.

By default, the URLopener class sends a User-Agent header of urllib/VVV, where VVV is the urllib version number. Applications can define their own User-Agent header by subclassing URLopener or FancyURLopener and setting the class attribute version to an appropriate string value in the subclass definition.

The optional proxies parameter should be a dictionary mapping scheme names to proxy URLs, where an empty dictionary turns proxies off completely. Its default value is None, in which case environmental proxy settings will be used if present, as discussed in the definition of urlopen(), above.

Additional keyword parameters, collected in x509, may be used for authentication of the client when using the https: scheme. The keywords key_file and cert_file are supported to provide an SSL key and certificate; both are needed to support client authentication.

URLopener objects will raise an OSError exception if the server returns an error code.

open(fullurl, data=None)

Open fullurl using the appropriate protocol. This method sets up cache and proxy information, then calls the appropriate open method with its input arguments. If the scheme is not recognized, open_unknown() is called. The data argument has the same meaning as the data argument of urlopen().

This method always quotes fullurl using quote().

open_unknown(fullurl, data=None)

Overridable interface to open unknown URL types.

retrieve(url, filename=None, reporthook=None, data=None)

Retrieves the contents of url and places it in filename. The return value is a tuple consisting of a local filename and either an email.message.Message object containing the response headers (for remote URLs) or None (for local URLs). The caller must then open and read the contents of filename. If filename is not given and the URL refers to a local file, the input filename is returned. If the URL is non-local and filename is not given, the filename is the output of tempfile.mktemp() with a suffix that matches the suffix of the last path component of the input URL. If reporthook is given, it must be a function accepting three numeric parameters: A chunk number, the maximum size chunks are read in and the total size of the download (-1 if unknown). It will be called once at the start and after each chunk of data is read from the network. reporthook is ignored for local URLs.

If the url uses the http: scheme identifier, the optional data argument may be given to specify a POST request (normally the request type is GET). The data argument must in standard application/x-www-form-urlencoded format; see the urllib.parse.urlencode() function.

version

Variable that specifies the user agent of the opener object. To get urllib to tell servers that it is a particular user agent, set this in a subclass as a class variable or in the constructor before calling the base constructor.

class urllib.request.FancyURLopener(...)

버전 3.3부터 폐지.

FancyURLopener subclasses URLopener providing default handling for the following HTTP response codes: 301, 302, 303, 307 and 401. For the 30x response codes listed above, the Location header is used to fetch the actual URL. For 401 response codes (authentication required), basic HTTP authentication is performed. For the 30x response codes, recursion is bounded by the value of the maxtries attribute, which defaults to 10.

For all other response codes, the method http_error_default() is called which you can override in subclasses to handle the error appropriately.

참고

According to the letter of RFC 2616 [https://tools.ietf.org/html/rfc2616.html], 301 and 302 responses to POST requests must not be automatically redirected without confirmation by the user. In reality, browsers do allow automatic redirection of these responses, changing the POST to a GET, and urllib reproduces this behaviour.

The parameters to the constructor are the same as those for URLopener.

참고

When performing basic authentication, a FancyURLopener instance calls its prompt_user_passwd() method. The default implementation asks the users for the required information on the controlling terminal. A subclass may override this method to support more appropriate behavior if needed.

The FancyURLopener class offers one additional method that should be overloaded to provide the appropriate behavior:

prompt_user_passwd(host, realm)

Return information needed to authenticate the user at the given host in the specified security realm. The return value should be a tuple, (user, password), which can be used for basic authentication.

The implementation prompts for this information on the terminal; an application should override this method to use an appropriate interaction model in the local environment.

urllib.request Restrictions

Currently, only the following protocols are supported: HTTP (versions 0.9 and 1.0), FTP, local files, and data URLs.

버전 3.4에서 변경: Added support for data URLs.

The caching feature of urlretrieve() has been disabled until someone finds the time to hack proper processing of Expiration time headers.

There should be a function to query whether a particular URL is in the cache.

For backward compatibility, if a URL appears to point to a local file but the file can’t be opened, the URL is re-interpreted using the FTP protocol. This can sometimes cause confusing error messages.

The urlopen() and urlretrieve() functions can cause arbitrarily long delays while waiting for a network connection to be set up. This means that it is difficult to build an interactive Web client using these functions without using threads.

The data returned by urlopen() or urlretrieve() is the raw data returned by the server. This may be binary data (such as an image), plain text or (for example) HTML. The HTTP protocol provides type information in the reply header, which can be inspected by looking at the Content-Type header. If the returned data is HTML, you can use the module html.parser to parse it.

The code handling the FTP protocol cannot differentiate between a file and a directory. This can lead to unexpected behavior when attempting to read a URL that points to a file that is not accessible. If the URL ends in a /, it is assumed to refer to a directory and will be handled accordingly. But if an attempt to read a file leads to a 550 error (meaning the URL cannot be found or is not accessible, often for permission reasons), then the path is treated as a directory in order to handle the case when a directory is specified by a URL but the trailing / has been left off. This can cause misleading results when you try to fetch a file whose read permissions make it inaccessible; the FTP code will try to read it, fail with a 550 error, and then perform a directory listing for the unreadable file. If fine-grained control is needed, consider using the ftplib module, subclassing FancyURLopener, or changing _urlopener to meet your needs.

urllib.response — Response classes used by urllib

The urllib.response module defines functions and classes which define a minimal file like interface, including read() and readline(). The typical response object is an addinfourl instance, which defines an info() method and that returns headers and a geturl() method that returns the url. Functions defined by this module are used internally by the urllib.request module.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 프로토콜과 지원 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 프로토콜과 지원 »

|

urllib.parse — Parse URLs into components

Source code: Lib/urllib/parse.py [https://github.com/python/cpython/tree/3.7/Lib/urllib/parse.py]

This module defines a standard interface to break Uniform Resource Locator (URL) strings up in components (addressing scheme, network location, path etc.), to combine the components back into a URL string, and to convert a “relative URL” to an absolute URL given a “base URL.”

The module has been designed to match the Internet RFC on Relative Uniform Resource Locators. It supports the following URL schemes: file, ftp, gopher, hdl, http, https, imap, mailto, mms, news, nntp, prospero, rsync, rtsp, rtspu, sftp, shttp, sip, sips, snews, svn, svn+ssh, telnet, wais, ws, wss.

The urllib.parse module defines functions that fall into two broad categories: URL parsing and URL quoting. These are covered in detail in the following sections.

URL Parsing

The URL parsing functions focus on splitting a URL string into its components, or on combining URL components into a URL string.

urllib.parse.urlparse(urlstring, scheme='', allow_fragments=True)

Parse a URL into six components, returning a 6-item named tuple. This corresponds to the general structure of a URL: scheme://netloc/path;parameters?query#fragment. Each tuple item is a string, possibly empty. The components are not broken up in smaller parts (for example, the network location is a single string), and % escapes are not expanded. The delimiters as shown above are not part of the result, except for a leading slash in the path component, which is retained if present. For example:

>>> from urllib.parse import urlparse
>>> o = urlparse('http://www.cwi.nl:80/%7Eguido/Python.html')
>>> o
ParseResult(scheme='http', netloc='www.cwi.nl:80', path='/%7Eguido/Python.html',
            params='', query='', fragment='')
>>> o.scheme
'http'
>>> o.port
80
>>> o.geturl()
'http://www.cwi.nl:80/%7Eguido/Python.html'

Following the syntax specifications in RFC 1808 [https://tools.ietf.org/html/rfc1808.html], urlparse recognizes a netloc only if it is properly introduced by ‘//’. Otherwise the input is presumed to be a relative URL and thus to start with a path component.

 >>> from urllib.parse import urlparse
 >>> urlparse('//www.cwi.nl:80/%7Eguido/Python.html')
 ParseResult(scheme='', netloc='www.cwi.nl:80', path='/%7Eguido/Python.html',
            params='', query='', fragment='')
 >>> urlparse('www.cwi.nl/%7Eguido/Python.html')
 ParseResult(scheme='', netloc='', path='www.cwi.nl/%7Eguido/Python.html',
            params='', query='', fragment='')
 >>> urlparse('help/Python.html')
 ParseResult(scheme='', netloc='', path='help/Python.html', params='',
            query='', fragment='')

The scheme argument gives the default addressing scheme, to be used only if the URL does not specify one. It should be the same type (text or bytes) as urlstring, except that the default value '' is always allowed, and is automatically converted to b'' if appropriate.

If the allow_fragments argument is false, fragment identifiers are not recognized. Instead, they are parsed as part of the path, parameters or query component, and fragment is set to the empty string in the return value.

The return value is a named tuple, which means that its items can be accessed by index or as named attributes, which are:

Attribute

Index

Value

Value if not present

scheme

0

URL scheme specifier

scheme parameter

netloc

1

Network location part

empty string

path

2

Hierarchical path

empty string

params

3

Parameters for last path element

empty string

query

4

Query component

empty string

fragment

5

Fragment identifier

empty string

username

User name

None

password

Password

None

hostname

Host name (lower case)

None

port

Port number as integer, if present

None

Reading the port attribute will raise a ValueError if an invalid port is specified in the URL. See section Structured Parse Results for more information on the result object.

Unmatched square brackets in the netloc attribute will raise a ValueError.

Characters in the netloc attribute that decompose under NFKC normalization (as used by the IDNA encoding) into any of /, ?, #, @, or : will raise a ValueError. If the URL is decomposed before parsing, no error will be raised.

As is the case with all named tuples, the subclass has a few additional methods and attributes that are particularly useful. One such method is _replace(). The _replace() method will return a new ParseResult object replacing specified fields with new values.

 >>> from urllib.parse import urlparse
 >>> u = urlparse('//www.cwi.nl:80/%7Eguido/Python.html')
 >>> u
 ParseResult(scheme='', netloc='www.cwi.nl:80', path='/%7Eguido/Python.html',
             params='', query='', fragment='')
 >>> u._replace(scheme='http')
 ParseResult(scheme='http', netloc='www.cwi.nl:80', path='/%7Eguido/Python.html',
             params='', query='', fragment='')

경고

urlparse() does not perform validation. See URL parsing security for details.

버전 3.2에서 변경: Added IPv6 URL parsing capabilities.

버전 3.3에서 변경: The fragment is now parsed for all URL schemes (unless allow_fragment is false), in accordance with RFC 3986 [https://tools.ietf.org/html/rfc3986.html]. Previously, a whitelist of schemes that support fragments existed.

버전 3.6에서 변경: Out-of-range port numbers now raise ValueError, instead of returning None.

버전 3.7.3에서 변경: Characters that affect netloc parsing under NFKC normalization will now raise ValueError.

urllib.parse.parse_qs(qs, keep_blank_values=False, strict_parsing=False, encoding='utf-8', errors='replace', max_num_fields=None, separator='&')

Parse a query string given as a string argument (data of type application/x-www-form-urlencoded). Data are returned as a dictionary. The dictionary keys are the unique query variable names and the values are lists of values for each name.

The optional argument keep_blank_values is a flag indicating whether blank values in percent-encoded queries should be treated as blank strings. A true value indicates that blanks should be retained as blank strings. The default false value indicates that blank values are to be ignored and treated as if they were not included.

The optional argument strict_parsing is a flag indicating what to do with parsing errors. If false (the default), errors are silently ignored. If true, errors raise a ValueError exception.

The optional encoding and errors parameters specify how to decode percent-encoded sequences into Unicode characters, as accepted by the bytes.decode() method.

The optional argument max_num_fields is the maximum number of fields to read. If set, then throws a ValueError if there are more than max_num_fields fields read.

The optional argument separator is the symbol to use for separating the query arguments. It defaults to &.

Use the urllib.parse.urlencode() function (with the doseq parameter set to True) to convert such dictionaries into query strings.

버전 3.2에서 변경: Add encoding and errors parameters.

버전 3.7.2에서 변경: Added max_num_fields parameter.

버전 3.7.10에서 변경: Added separator parameter with the default value of &. Python versions earlier than Python 3.7.10 allowed using both ; and & as query parameter separator. This has been changed to allow only a single separator key, with & as the default separator.

urllib.parse.parse_qsl(qs, keep_blank_values=False, strict_parsing=False, encoding='utf-8', errors='replace', max_num_fields=None, separator='&')

Parse a query string given as a string argument (data of type application/x-www-form-urlencoded). Data are returned as a list of name, value pairs.

The optional argument keep_blank_values is a flag indicating whether blank values in percent-encoded queries should be treated as blank strings. A true value indicates that blanks should be retained as blank strings. The default false value indicates that blank values are to be ignored and treated as if they were not included.

The optional argument strict_parsing is a flag indicating what to do with parsing errors. If false (the default), errors are silently ignored. If true, errors raise a ValueError exception.

The optional encoding and errors parameters specify how to decode percent-encoded sequences into Unicode characters, as accepted by the bytes.decode() method.

The optional argument max_num_fields is the maximum number of fields to read. If set, then throws a ValueError if there are more than max_num_fields fields read.

The optional argument separator is the symbol to use for separating the query arguments. It defaults to &.

Use the urllib.parse.urlencode() function to convert such lists of pairs into query strings.

버전 3.2에서 변경: Add encoding and errors parameters.

버전 3.7.2에서 변경: Added max_num_fields parameter.

버전 3.7.10에서 변경: Added separator parameter with the default value of &. Python versions earlier than Python 3.7.10 allowed using both ; and & as query parameter separator. This has been changed to allow only a single separator key, with & as the default separator.

urllib.parse.urlunparse(parts)

Construct a URL from a tuple as returned by urlparse(). The parts argument can be any six-item iterable. This may result in a slightly different, but equivalent URL, if the URL that was parsed originally had unnecessary delimiters (for example, a ? with an empty query; the RFC states that these are equivalent).

urllib.parse.urlsplit(urlstring, scheme='', allow_fragments=True)

This is similar to urlparse(), but does not split the params from the URL. This should generally be used instead of urlparse() if the more recent URL syntax allowing parameters to be applied to each segment of the path portion of the URL (see RFC 2396 [https://tools.ietf.org/html/rfc2396.html]) is wanted. A separate function is needed to separate the path segments and parameters. This function returns a 5-item named tuple:

(addressing scheme, network location, path, query, fragment identifier).

The return value is a named tuple, its items can be accessed by index or as named attributes:

Attribute

Index

Value

Value if not present

scheme

0

URL scheme specifier

scheme parameter

netloc

1

Network location part

empty string

path

2

Hierarchical path

empty string

query

3

Query component

empty string

fragment

4

Fragment identifier

empty string

username

User name

None

password

Password

None

hostname

Host name (lower case)

None

port

Port number as integer, if present

None

Reading the port attribute will raise a ValueError if an invalid port is specified in the URL. See section Structured Parse Results for more information on the result object.

Unmatched square brackets in the netloc attribute will raise a ValueError.

Characters in the netloc attribute that decompose under NFKC normalization (as used by the IDNA encoding) into any of /, ?, #, @, or : will raise a ValueError. If the URL is decomposed before parsing, no error will be raised.

Following some of the WHATWG spec [https://url.spec.whatwg.org/#concept-basic-url-parser] that updates RFC 3986, leading C0 control and space characters are stripped from the URL. \n, \r and tab \t characters are removed from the URL at any position.

경고

urlsplit() does not perform validation. See URL parsing security for details.

버전 3.6에서 변경: Out-of-range port numbers now raise ValueError, instead of returning None.

버전 3.7.3에서 변경: Characters that affect netloc parsing under NFKC normalization will now raise ValueError.

버전 3.7.11에서 변경: ASCII newline and tab characters are stripped from the URL.

버전 3.7.17에서 변경: Leading WHATWG C0 control and space characters are stripped from the URL.

urllib.parse.urlunsplit(parts)

Combine the elements of a tuple as returned by urlsplit() into a complete URL as a string. The parts argument can be any five-item iterable. This may result in a slightly different, but equivalent URL, if the URL that was parsed originally had unnecessary delimiters (for example, a ? with an empty query; the RFC states that these are equivalent).

urllib.parse.urljoin(base, url, allow_fragments=True)

Construct a full (“absolute”) URL by combining a “base URL” (base) with another URL (url). Informally, this uses components of the base URL, in particular the addressing scheme, the network location and (part of) the path, to provide missing components in the relative URL. For example:

>>> from urllib.parse import urljoin
>>> urljoin('http://www.cwi.nl/%7Eguido/Python.html', 'FAQ.html')
'http://www.cwi.nl/%7Eguido/FAQ.html'

The allow_fragments argument has the same meaning and default as for urlparse().

참고

If url is an absolute URL (that is, starting with // or scheme://), the url’s host name and/or scheme will be present in the result. For example:

>>> urljoin('http://www.cwi.nl/%7Eguido/Python.html',
...         '//www.python.org/%7Eguido')
'http://www.python.org/%7Eguido'

If you do not want that behavior, preprocess the url with urlsplit() and urlunsplit(), removing possible scheme and netloc parts.

버전 3.5에서 변경: Behaviour updated to match the semantics defined in RFC 3986 [https://tools.ietf.org/html/rfc3986.html].

urllib.parse.urldefrag(url)

If url contains a fragment identifier, return a modified version of url with no fragment identifier, and the fragment identifier as a separate string. If there is no fragment identifier in url, return url unmodified and an empty string.

The return value is a named tuple, its items can be accessed by index or as named attributes:

Attribute

Index

Value

Value if not present

url

0

URL with no fragment

empty string

fragment

1

Fragment identifier

empty string

See section Structured Parse Results for more information on the result object.

버전 3.2에서 변경: Result is a structured object rather than a simple 2-tuple.

URL parsing security

The urlsplit() and urlparse() APIs do not perform validation of inputs. They may not raise errors on inputs that other applications consider invalid. They may also succeed on some inputs that might not be considered URLs elsewhere. Their purpose is for practical functionality rather than purity.

Instead of raising an exception on unusual input, they may instead return some component parts as empty strings. Or components may contain more than perhaps they should.

We recommend that users of these APIs where the values may be used anywhere with security implications code defensively. Do some verification within your code before trusting a returned component part. Does that scheme make sense? Is that a sensible path? Is there anything strange about that hostname? etc.

Parsing ASCII Encoded Bytes

The URL parsing functions were originally designed to operate on character strings only. In practice, it is useful to be able to manipulate properly quoted and encoded URLs as sequences of ASCII bytes. Accordingly, the URL parsing functions in this module all operate on bytes and bytearray objects in addition to str objects.

If str data is passed in, the result will also contain only str data. If bytes or bytearray data is passed in, the result will contain only bytes data.

Attempting to mix str data with bytes or bytearray in a single function call will result in a TypeError being raised, while attempting to pass in non-ASCII byte values will trigger UnicodeDecodeError.

To support easier conversion of result objects between str and bytes, all return values from URL parsing functions provide either an encode() method (when the result contains str data) or a decode() method (when the result contains bytes data). The signatures of these methods match those of the corresponding str and bytes methods (except that the default encoding is 'ascii' rather than 'utf-8'). Each produces a value of a corresponding type that contains either bytes data (for encode() methods) or str data (for decode() methods).

Applications that need to operate on potentially improperly quoted URLs that may contain non-ASCII data will need to do their own decoding from bytes to characters before invoking the URL parsing methods.

The behaviour described in this section applies only to the URL parsing functions. The URL quoting functions use their own rules when producing or consuming byte sequences as detailed in the documentation of the individual URL quoting functions.

버전 3.2에서 변경: URL parsing functions now accept ASCII encoded byte sequences

Structured Parse Results

The result objects from the urlparse(), urlsplit() and urldefrag() functions are subclasses of the tuple type. These subclasses add the attributes listed in the documentation for those functions, the encoding and decoding support described in the previous section, as well as an additional method:

urllib.parse.SplitResult.geturl()

Return the re-combined version of the original URL as a string. This may differ from the original URL in that the scheme may be normalized to lower case and empty components may be dropped. Specifically, empty parameters, queries, and fragment identifiers will be removed.

For urldefrag() results, only empty fragment identifiers will be removed. For urlsplit() and urlparse() results, all noted changes will be made to the URL returned by this method.

The result of this method remains unchanged if passed back through the original parsing function:

>>> from urllib.parse import urlsplit
>>> url = 'HTTP://www.Python.org/doc/#'
>>> r1 = urlsplit(url)
>>> r1.geturl()
'http://www.Python.org/doc/'
>>> r2 = urlsplit(r1.geturl())
>>> r2.geturl()
'http://www.Python.org/doc/'

The following classes provide the implementations of the structured parse results when operating on str objects:

class urllib.parse.DefragResult(url, fragment)

Concrete class for urldefrag() results containing str data. The encode() method returns a DefragResultBytes instance.

버전 3.2에 추가.

class urllib.parse.ParseResult(scheme, netloc, path, params, query, fragment)

Concrete class for urlparse() results containing str data. The encode() method returns a ParseResultBytes instance.

class urllib.parse.SplitResult(scheme, netloc, path, query, fragment)

Concrete class for urlsplit() results containing str data. The encode() method returns a SplitResultBytes instance.

The following classes provide the implementations of the parse results when operating on bytes or bytearray objects:

class urllib.parse.DefragResultBytes(url, fragment)

Concrete class for urldefrag() results containing bytes data. The decode() method returns a DefragResult instance.

버전 3.2에 추가.

class urllib.parse.ParseResultBytes(scheme, netloc, path, params, query, fragment)

Concrete class for urlparse() results containing bytes data. The decode() method returns a ParseResult instance.

버전 3.2에 추가.

class urllib.parse.SplitResultBytes(scheme, netloc, path, query, fragment)

Concrete class for urlsplit() results containing bytes data. The decode() method returns a SplitResult instance.

버전 3.2에 추가.

URL Quoting

The URL quoting functions focus on taking program data and making it safe for use as URL components by quoting special characters and appropriately encoding non-ASCII text. They also support reversing these operations to recreate the original data from the contents of a URL component if that task isn’t already covered by the URL parsing functions above.

urllib.parse.quote(string, safe='/', encoding=None, errors=None)

Replace special characters in string using the %xx escape. Letters, digits, and the characters '_.-~' are never quoted. By default, this function is intended for quoting the path section of URL. The optional safe parameter specifies additional ASCII characters that should not be quoted — its default value is '/'.

string may be either a str or a bytes.

버전 3.7에서 변경: Moved from RFC 2396 [https://tools.ietf.org/html/rfc2396.html] to RFC 3986 [https://tools.ietf.org/html/rfc3986.html] for quoting URL strings. “~” is now included in the set of unreserved characters.

The optional encoding and errors parameters specify how to deal with non-ASCII characters, as accepted by the str.encode() method. encoding defaults to 'utf-8'. errors defaults to 'strict', meaning unsupported characters raise a UnicodeEncodeError. encoding and errors must not be supplied if string is a bytes, or a TypeError is raised.

Note that quote(string, safe, encoding, errors) is equivalent to quote_from_bytes(string.encode(encoding, errors), safe).

Example: quote('/El Niño/') yields '/El%20Ni%C3%B1o/'.

urllib.parse.quote_plus(string, safe='', encoding=None, errors=None)

Like quote(), but also replace spaces by plus signs, as required for quoting HTML form values when building up a query string to go into a URL. Plus signs in the original string are escaped unless they are included in safe. It also does not have safe default to '/'.

Example: quote_plus('/El Niño/') yields '%2FEl+Ni%C3%B1o%2F'.

urllib.parse.quote_from_bytes(bytes, safe='/')

Like quote(), but accepts a bytes object rather than a str, and does not perform string-to-bytes encoding.

Example: quote_from_bytes(b'a&\xef') yields 'a%26%EF'.

urllib.parse.unquote(string, encoding='utf-8', errors='replace')

Replace %xx escapes by their single-character equivalent. The optional encoding and errors parameters specify how to decode percent-encoded sequences into Unicode characters, as accepted by the bytes.decode() method.

string must be a str.

encoding defaults to 'utf-8'. errors defaults to 'replace', meaning invalid sequences are replaced by a placeholder character.

Example: unquote('/El%20Ni%C3%B1o/') yields '/El Niño/'.

urllib.parse.unquote_plus(string, encoding='utf-8', errors='replace')

Like unquote(), but also replace plus signs by spaces, as required for unquoting HTML form values.

string must be a str.

Example: unquote_plus('/El+Ni%C3%B1o/') yields '/El Niño/'.

urllib.parse.unquote_to_bytes(string)

Replace %xx escapes by their single-octet equivalent, and return a bytes object.

string may be either a str or a bytes.

If it is a str, unescaped non-ASCII characters in string are encoded into UTF-8 bytes.

Example: unquote_to_bytes('a%26%EF') yields b'a&\xef'.

urllib.parse.urlencode(query, doseq=False, safe='', encoding=None, errors=None, quote_via=quote_plus)

Convert a mapping object or a sequence of two-element tuples, which may contain str or bytes objects, to a percent-encoded ASCII text string. If the resultant string is to be used as a data for POST operation with the urlopen() function, then it should be encoded to bytes, otherwise it would result in a TypeError.

The resulting string is a series of key=value pairs separated by '&' characters, where both key and value are quoted using the quote_via function. By default, quote_plus() is used to quote the values, which means spaces are quoted as a '+' character and ‘/’ characters are encoded as %2F, which follows the standard for GET requests (application/x-www-form-urlencoded). An alternate function that can be passed as quote_via is quote(), which will encode spaces as %20 and not encode ‘/’ characters. For maximum control of what is quoted, use quote and specify a value for safe.

When a sequence of two-element tuples is used as the query argument, the first element of each tuple is a key and the second is a value. The value element in itself can be a sequence and in that case, if the optional parameter doseq is evaluates to True, individual key=value pairs separated by '&' are generated for each element of the value sequence for the key. The order of parameters in the encoded string will match the order of parameter tuples in the sequence.

The safe, encoding, and errors parameters are passed down to quote_via (the encoding and errors parameters are only passed when a query element is a str).

To reverse this encoding process, parse_qs() and parse_qsl() are provided in this module to parse query strings into Python data structures.

Refer to urllib examples to find out how urlencode method can be used for generating query string for a URL or data for POST.

버전 3.2에서 변경: Query parameter supports bytes and string objects.

버전 3.5에 추가: quote_via parameter.

더 보기

WHATWG [https://url.spec.whatwg.org/] - URL Living standard

Working Group for the URL Standard that defines URLs, domains, IP addresses, the application/x-www-form-urlencoded format, and their API.

RFC 3986 [https://tools.ietf.org/html/rfc3986.html] - Uniform Resource Identifiers

This is the current standard (STD66). Any changes to urllib.parse module should conform to this. Certain deviations could be observed, which are mostly for backward compatibility purposes and for certain de-facto parsing requirements as commonly observed in major browsers.

RFC 2732 [https://tools.ietf.org/html/rfc2732.html] - Format for Literal IPv6 Addresses in URL’s.

This specifies the parsing requirements of IPv6 URLs.

RFC 2396 [https://tools.ietf.org/html/rfc2396.html] - Uniform Resource Identifiers (URI): Generic Syntax

Document describing the generic syntactic requirements for both Uniform Resource Names (URNs) and Uniform Resource Locators (URLs).

RFC 2368 [https://tools.ietf.org/html/rfc2368.html] - The mailto URL scheme.

Parsing requirements for mailto URL schemes.

RFC 1808 [https://tools.ietf.org/html/rfc1808.html] - Relative Uniform Resource Locators

This Request For Comments includes the rules for joining an absolute and a relative URL, including a fair number of “Abnormal Examples” which govern the treatment of border cases.

RFC 1738 [https://tools.ietf.org/html/rfc1738.html] - Uniform Resource Locators (URL)

This specifies the formal syntax and semantics of absolute URLs.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 프로토콜과 지원 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 프로토콜과 지원 »

|

urllib.error — urllib.request에 의해 발생하는 예외 클래스

소스 코드: Lib/urllib/error.py [https://github.com/python/cpython/tree/3.7/Lib/urllib/error.py]

urllib.error모듈은 urllib.request에 의해 발생하는 예외에 대한 예외 클래스를 정의합니다. 베이스 예외 클래스는 URLError입니다.

urllib.error에 의해 다음과 같은 예외가 적절하게 발생합니다.

exception urllib.error.URLError

처리기가 문제에 봉착하는 경우, 처리기는 해당 예외(또는 파생된 예외)를 발생시킵니다. 이 예외는 OSError의 서브 클래스입니다.

reason

이 에러가 발생한 원인입니다. 메시지 문자열이거나 다른 예외 인스턴스가 될 수 있습니다.

버전 3.3에서 변경: URLError는 IOError가 아닌, OSError의 서브 클래스가 되었습니다.

exception urllib.error.HTTPError

HTTPError는 URLError의 서브 클래스로 예외 클래스이긴 하지만, 예외가 아닌 파일류 반환 값(urlopen()의 반환 값과 동일한 값)으로도 작동할 수 있습니다. 이 방법은 인증 요청 같은 독특한(exotic) HTTP 에러를 처리할 때 유용합니다.

code

RFC 2616 [https://tools.ietf.org/html/rfc2616.html]에 정의된 HTTP 상태 코드입니다. 이 숫자 값은 http.server.BaseHTTPRequestHandler.responses에서 찾을 수 있는 상태 코드 딕셔너리에 있는 값에 해당합니다.

reason

일반적으로 이 에러의 원인을 설명하는 문자열입니다.

headers

HTTPError를 발생시킨 HTTP 요청의 응답 헤더입니다.

버전 3.4에 추가.

exception urllib.error.ContentTooShortError(msg, content)

이 예외는 다운로드받은 데이터양이 Content-Length 헤더 값을 통해 예상한 양보다 적은 것을 urlretrieve()함수가 감지했을 때 발생합니다. content어트리뷰트는 다운로드받은 (그리고 아마도 잘린) 데이터를 저장합니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 프로토콜과 지원 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 프로토콜과 지원 »

|

urllib.robotparser — robots.txt 구문 분석기

소스 코드: Lib/urllib/robotparser.py [https://github.com/python/cpython/tree/3.7/Lib/urllib/robotparser.py]

이 모듈은 클래스 하나 RobotFileParser를 제공하는데, 특정 사용자 에이전트가 robots.txt 파일을 게시한 웹 사이트에서 URL을 가져올 수 있는지에 대한 질문에 대답합니다. robots.txt 파일의 구조에 대한 자세한 내용은 http://www.robotstxt.org/orig.html 을 참조하십시오.

class urllib.robotparser.RobotFileParser(url='')

이 클래스는 url에 있는 robots.txt 파일을 읽고, 구문 분석하고, 그에 대한 질문에 대답하는 메서드를 제공합니다.

set_url(url)

robots.txt 파일을 가리키는 URL을 설정합니다.

read()

robots.txt URL을 읽어서 구문 분석기에 넘깁니다.

parse(lines)

lines 인자를 구문 분석합니다.

can_fetch(useragent, url)

구문 분석된 robots.txt 파일에 포함된 규칙에 따라, useragent가 url를 가져올 수 있으면 True를 반환합니다.

mtime()

robots.txt 파일을 마지막으로 가져온 시간을 반환합니다. 이것은 새 robots.txt 파일을 주기적으로 확인해야 하는 장기 실행 웹 스파이더에 유용합니다.

modified()

robots.txt 파일을 마지막으로 가져온 시간을 현재 시각으로 설정합니다.

crawl_delay(useragent)

robots.txt에서 해당 useragent에 대한 Crawl-delay 파라미터의 값을 반환합니다. 해당 파라미터가 없거나, 지정된 useragent에 적용되지 않거나, 이 파라미터에 대한 robots.txt 항목이 잘못된 구문이면 None을 반환합니다.

버전 3.6에 추가.

request_rate(useragent)

robots.txt에서 Request-rate 파라미터의 내용을 네임드 튜플 RequestRate(requests, seconds)로 반환합니다. 해당 파라미터가 없거나, 지정된 useragent에 적용되지 않거나, 이 파라미터에 대한 robots.txt 항목이 잘못된 구문이면 None을 반환합니다.

버전 3.6에 추가.

다음 예제는 RobotFileParser 클래스의 기본 사용을 보여줍니다:

>>> import urllib.robotparser
>>> rp = urllib.robotparser.RobotFileParser()
>>> rp.set_url("http://www.musi-cal.com/robots.txt")
>>> rp.read()
>>> rrate = rp.request_rate("*")
>>> rrate.requests
3
>>> rrate.seconds
20
>>> rp.crawl_delay("*")
6
>>> rp.can_fetch("*", "http://www.musi-cal.com/cgi-bin/search?city=San+Francisco")
False
>>> rp.can_fetch("*", "http://www.musi-cal.com/")
True

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 프로토콜과 지원 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 프로토콜과 지원 »

|

http — HTTP 모듈

소스 코드: Lib/http/__init__.py [https://github.com/python/cpython/tree/3.7/Lib/http/__init__.py]

http는 하이퍼텍스트 전송 프로토콜로 작업 하기 위한 여러 모듈을 수집하는 패키지입니다:

http.client는 저수준 HTTP 프로토콜 클라이언트입니다. 고수준의 URL 열기는 urllib.request를 사용합니다

http.server는 socketserver에 기반을 둔 기본적인 HTTP 서버 클래스를 포함합니다

http.cookies는 쿠키를 사용하여 상태 관리를 구현하는 유틸리티가 있습니다

http.cookiejar는 쿠키의 지속성을 제공합니다

http는 여러 HTTP 상태 코드와 관련 메시지를 http.HTTPStatus 열거형을 통해 정의하는 모듈이기도 합니다:

class http.HTTPStatus

버전 3.5에 추가.

HTTP 상태 코드, 이유 구문 그리고 긴 영문 설명의 집합을 정의하는 enum.IntEnum의 서브 클래스입니다.

사용법:

>>> from http import HTTPStatus
>>> HTTPStatus.OK
<HTTPStatus.OK: 200>
>>> HTTPStatus.OK == 200
True
>>> HTTPStatus.OK.value
200
>>> HTTPStatus.OK.phrase
'OK'
>>> HTTPStatus.OK.description
'Request fulfilled, document follows'
>>> list(HTTPStatus)
[<HTTPStatus.CONTINUE: 100>, <HTTPStatus.SWITCHING_PROTOCOLS: 101>, ...]

HTTP 상태 코드

http.HTTPStatus에서 지원하는 IANA 등록 [https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml] 상태 코드는 다음과 같습니다:

코드

열거 이름

세부 사항

100

CONTINUE

HTTP/1.1 RFC 7231 [https://tools.ietf.org/html/rfc7231.html], 섹션 6.2.1

101

SWITCHING_PROTOCOLS

HTTP/1.1 RFC 7231 [https://tools.ietf.org/html/rfc7231.html], 섹션 6.2.2

102

PROCESSING

WebDAV RFC 2518 [https://tools.ietf.org/html/rfc2518.html], 섹션 10.1

200

OK

HTTP/1.1 RFC 7231 [https://tools.ietf.org/html/rfc7231.html], 섹션 6.3.1

201

CREATED

HTTP/1.1 RFC 7231 [https://tools.ietf.org/html/rfc7231.html], 섹션 6.3.2

202

ACCEPTED

HTTP/1.1 RFC 7231 [https://tools.ietf.org/html/rfc7231.html], 섹션 6.3.3

203

NON_AUTHORITATIVE_INFORMATION

HTTP/1.1 RFC 7231 [https://tools.ietf.org/html/rfc7231.html], 섹션 6.3.4

204

NO_CONTENT

HTTP/1.1 RFC 7231 [https://tools.ietf.org/html/rfc7231.html], 섹션 6.3.5

205

RESET_CONTENT

HTTP/1.1 RFC 7231 [https://tools.ietf.org/html/rfc7231.html], 섹션 6.3.6

206

PARTIAL_CONTENT

HTTP/1.1 RFC 7233 [https://tools.ietf.org/html/rfc7233.html], 섹션 4.1

207

MULTI_STATUS

WebDAV RFC 4918 [https://tools.ietf.org/html/rfc4918.html], 섹션 11.1

208

ALREADY_REPORTED

WebDAV 바인딩 확장 RFC 5842 [https://tools.ietf.org/html/rfc5842.html], 섹션 7.1 (실험적)

226

IM_USED

HTTP의 델타 인코딩 RFC 3229 [https://tools.ietf.org/html/rfc3229.html], 섹션 10.4.1

300

MULTIPLE_CHOICES

HTTP/1.1 RFC 7231 [https://tools.ietf.org/html/rfc7231.html], 섹션 6.4.1

301

MOVED_PERMANENTLY

HTTP/1.1 RFC 7231 [https://tools.ietf.org/html/rfc7231.html], 섹션 6.4.2

302

FOUND

HTTP/1.1 RFC 7231 [https://tools.ietf.org/html/rfc7231.html], 섹션 6.4.3

303

SEE_OTHER

HTTP/1.1 RFC 7231 [https://tools.ietf.org/html/rfc7231.html], 섹션 6.4.4

304

NOT_MODIFIED

HTTP/1.1 RFC 7232 [https://tools.ietf.org/html/rfc7232.html], 섹션 4.1

305

USE_PROXY

HTTP/1.1 RFC 7231 [https://tools.ietf.org/html/rfc7231.html], 섹션 6.4.5

307

TEMPORARY_REDIRECT

HTTP/1.1 RFC 7231 [https://tools.ietf.org/html/rfc7231.html], 섹션 6.4.7

308

PERMANENT_REDIRECT

영구 리디렉션 RFC 7238 [https://tools.ietf.org/html/rfc7238.html], 섹션 3 (실험적)

400

BAD_REQUEST

HTTP/1.1 RFC 7231 [https://tools.ietf.org/html/rfc7231.html], 섹션 6.5.1

401

UNAUTHORIZED

HTTP/1.1 인증 RFC 7235 [https://tools.ietf.org/html/rfc7235.html], 섹션 3.1

402

PAYMENT_REQUIRED

HTTP/1.1 RFC 7231 [https://tools.ietf.org/html/rfc7231.html], 섹션 6.5.2

403

FORBIDDEN

HTTP/1.1 RFC 7231 [https://tools.ietf.org/html/rfc7231.html], 섹션 6.5.3

404

NOT_FOUND

HTTP/1.1 RFC 7231 [https://tools.ietf.org/html/rfc7231.html], 섹션 6.5.4

405

METHOD_NOT_ALLOWED

HTTP/1.1 RFC 7231 [https://tools.ietf.org/html/rfc7231.html], 섹션 6.5.5

406

NOT_ACCEPTABLE

HTTP/1.1 RFC 7231 [https://tools.ietf.org/html/rfc7231.html], 섹션 6.5.6

407

PROXY_AUTHENTICATION_REQUIRED

HTTP/1.1 인증 RFC 7235 [https://tools.ietf.org/html/rfc7235.html], 섹션 3.2

408

REQUEST_TIMEOUT

HTTP/1.1 RFC 7231 [https://tools.ietf.org/html/rfc7231.html], 섹션 6.5.7

409

CONFLICT

HTTP/1.1 RFC 7231 [https://tools.ietf.org/html/rfc7231.html], 섹션 6.5.8

410

GONE

HTTP/1.1 RFC 7231 [https://tools.ietf.org/html/rfc7231.html], 섹션 6.5.9

411

LENGTH_REQUIRED

HTTP/1.1 RFC 7231 [https://tools.ietf.org/html/rfc7231.html], 섹션 6.5.10

412

PRECONDITION_FAILED

HTTP/1.1 RFC 7232 [https://tools.ietf.org/html/rfc7232.html], 섹션 4.2

413

REQUEST_ENTITY_TOO_LARGE

HTTP/1.1 RFC 7231 [https://tools.ietf.org/html/rfc7231.html], 섹션 6.5.11

414

REQUEST_URI_TOO_LONG

HTTP/1.1 RFC 7231 [https://tools.ietf.org/html/rfc7231.html], 섹션 6.5.12

415

UNSUPPORTED_MEDIA_TYPE

HTTP/1.1 RFC 7231 [https://tools.ietf.org/html/rfc7231.html], 섹션 6.5.13

416

REQUESTED_RANGE_NOT_SATISFIABLE

HTTP/1.1 범위 요청 RFC 7233 [https://tools.ietf.org/html/rfc7233.html], 섹션 4.4

417

EXPECTATION_FAILED

HTTP/1.1 RFC 7231 [https://tools.ietf.org/html/rfc7231.html], 섹션 6.5.14

421

MISDIRECTED_REQUEST

HTTP/2 RFC 7540 [https://tools.ietf.org/html/rfc7540.html], 섹션 9.1.2

422

UNPROCESSABLE_ENTITY

WebDAV RFC 4918 [https://tools.ietf.org/html/rfc4918.html], 섹션 11.2

423

LOCKED

WebDAV RFC 4918 [https://tools.ietf.org/html/rfc4918.html], 섹션 11.3

424

FAILED_DEPENDENCY

WebDAV RFC 4918 [https://tools.ietf.org/html/rfc4918.html], 섹션 11.4

426

UPGRADE_REQUIRED

HTTP/1.1 RFC 7231 [https://tools.ietf.org/html/rfc7231.html], 섹션 6.5.15

428

PRECONDITION_REQUIRED

추가 HTTP 상태 코드 RFC 6585 [https://tools.ietf.org/html/rfc6585.html]

429

TOO_MANY_REQUESTS

추가 HTTP 상태 코드 RFC 6585 [https://tools.ietf.org/html/rfc6585.html]

431

REQUEST_HEADER_FIELDS_TOO_LARGE

추가 HTTP 상태 코드 RFC 6585 [https://tools.ietf.org/html/rfc6585.html]

500

INTERNAL_SERVER_ERROR

HTTP/1.1 RFC 7231 [https://tools.ietf.org/html/rfc7231.html], 섹션 6.6.1

501

NOT_IMPLEMENTED

HTTP/1.1 RFC 7231 [https://tools.ietf.org/html/rfc7231.html], 섹션 6.6.2

502

BAD_GATEWAY

HTTP/1.1 RFC 7231 [https://tools.ietf.org/html/rfc7231.html], 섹션 6.6.3

503

SERVICE_UNAVAILABLE

HTTP/1.1 RFC 7231 [https://tools.ietf.org/html/rfc7231.html], 섹션 6.6.4

504

GATEWAY_TIMEOUT

HTTP/1.1 RFC 7231 [https://tools.ietf.org/html/rfc7231.html], 섹션 6.6.5

505

HTTP_VERSION_NOT_SUPPORTED

HTTP/1.1 RFC 7231 [https://tools.ietf.org/html/rfc7231.html], 섹션 6.6.6

506

VARIANT_ALSO_NEGOTIATES

HTTP의 투명한 콘텐츠 협상 RFC 2295 [https://tools.ietf.org/html/rfc2295.html], 섹션 8.1 (실험적)

507

INSUFFICIENT_STORAGE

WebDAV RFC 4918 [https://tools.ietf.org/html/rfc4918.html], 섹션 11.5

508

LOOP_DETECTED

WebDAV 바인딩 확장 RFC 5842 [https://tools.ietf.org/html/rfc5842.html], 섹션 7.2 (실험적)

510

NOT_EXTENDED

HTTP 확장 프레임워크 RFC 2774 [https://tools.ietf.org/html/rfc2774.html], 섹션 7 (실험적)

511

NETWORK_AUTHENTICATION_REQUIRED

추가 HTTP 상태 코드 RFC 6585 [https://tools.ietf.org/html/rfc6585.html], 섹션 6

이전 버전과의 호환성을 유지하기 위해 열거값은 http.client 모듈에 상수 형태로도 있습니다. 열거명과 상수명은 동일합니다 (즉, http.HTTPStatus.OK는 http.client.OK로도 사용 가능합니다).

버전 3.7에서 변경: 421 MISDIRECTED_REQUEST 상태 코드 추가.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 프로토콜과 지원 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 프로토콜과 지원 »

|

http.client — HTTP protocol client

Source code: Lib/http/client.py [https://github.com/python/cpython/tree/3.7/Lib/http/client.py]

This module defines classes which implement the client side of the HTTP and HTTPS protocols. It is normally not used directly — the module urllib.request uses it to handle URLs that use HTTP and HTTPS.

더 보기

The Requests package [https://requests.readthedocs.io/en/master/] is recommended for a higher-level HTTP client interface.

참고

HTTPS support is only available if Python was compiled with SSL support (through the ssl module).

The module provides the following classes:

class http.client.HTTPConnection(host, port=None, [timeout, ]source_address=None, blocksize=8192)

An HTTPConnection instance represents one transaction with an HTTP server. It should be instantiated passing it a host and optional port number. If no port number is passed, the port is extracted from the host string if it has the form host:port, else the default HTTP port (80) is used. If the optional timeout parameter is given, blocking operations (like connection attempts) will timeout after that many seconds (if it is not given, the global default timeout setting is used). The optional source_address parameter may be a tuple of a (host, port) to use as the source address the HTTP connection is made from. The optional blocksize parameter sets the buffer size in bytes for sending a file-like message body.

For example, the following calls all create instances that connect to the server at the same host and port:

>>> h1 = http.client.HTTPConnection('www.python.org')
>>> h2 = http.client.HTTPConnection('www.python.org:80')
>>> h3 = http.client.HTTPConnection('www.python.org', 80)
>>> h4 = http.client.HTTPConnection('www.python.org', 80, timeout=10)

버전 3.2에서 변경: source_address was added.

버전 3.4에서 변경: The strict parameter was removed. HTTP 0.9-style “Simple Responses” are not longer supported.

버전 3.7에서 변경: blocksize parameter was added.

class http.client.HTTPSConnection(host, port=None, key_file=None, cert_file=None, [timeout, ]source_address=None, *, context=None, check_hostname=None, blocksize=8192)

A subclass of HTTPConnection that uses SSL for communication with secure servers. Default port is 443. If context is specified, it must be a ssl.SSLContext instance describing the various SSL options.

Please read 보안 고려 사항 for more information on best practices.

버전 3.2에서 변경: source_address, context and check_hostname were added.

버전 3.2에서 변경: This class now supports HTTPS virtual hosts if possible (that is, if ssl.HAS_SNI is true).

버전 3.4에서 변경: The strict parameter was removed. HTTP 0.9-style “Simple Responses” are no longer supported.

버전 3.4.3에서 변경: This class now performs all the necessary certificate and hostname checks by default. To revert to the previous, unverified, behavior ssl._create_unverified_context() can be passed to the context parameter.

버전 3.7.4에서 변경: This class now enables TLS 1.3 ssl.SSLContext.post_handshake_auth for the default context or when cert_file is passed with a custom context.

버전 3.6부터 폐지: key_file and cert_file are deprecated in favor of context. Please use ssl.SSLContext.load_cert_chain() instead, or let ssl.create_default_context() select the system’s trusted CA certificates for you.

The check_hostname parameter is also deprecated; the ssl.SSLContext.check_hostname attribute of context should be used instead.

class http.client.HTTPResponse(sock, debuglevel=0, method=None, url=None)

Class whose instances are returned upon successful connection. Not instantiated directly by user.

버전 3.4에서 변경: The strict parameter was removed. HTTP 0.9 style “Simple Responses” are no longer supported.

The following exceptions are raised as appropriate:

exception http.client.HTTPException

The base class of the other exceptions in this module. It is a subclass of Exception.

exception http.client.NotConnected

A subclass of HTTPException.

exception http.client.InvalidURL

A subclass of HTTPException, raised if a port is given and is either non-numeric or empty.

exception http.client.UnknownProtocol

A subclass of HTTPException.

exception http.client.UnknownTransferEncoding

A subclass of HTTPException.

exception http.client.UnimplementedFileMode

A subclass of HTTPException.

exception http.client.IncompleteRead

A subclass of HTTPException.

exception http.client.ImproperConnectionState

A subclass of HTTPException.

exception http.client.CannotSendRequest

A subclass of ImproperConnectionState.

exception http.client.CannotSendHeader

A subclass of ImproperConnectionState.

exception http.client.ResponseNotReady

A subclass of ImproperConnectionState.

exception http.client.BadStatusLine

A subclass of HTTPException. Raised if a server responds with a HTTP status code that we don’t understand.

exception http.client.LineTooLong

A subclass of HTTPException. Raised if an excessively long line is received in the HTTP protocol from the server.

exception http.client.RemoteDisconnected

A subclass of ConnectionResetError and BadStatusLine. Raised by HTTPConnection.getresponse() when the attempt to read the response results in no data read from the connection, indicating that the remote end has closed the connection.

버전 3.5에 추가: Previously, BadStatusLine('') was raised.

The constants defined in this module are:

http.client.HTTP_PORT

The default port for the HTTP protocol (always 80).

http.client.HTTPS_PORT

The default port for the HTTPS protocol (always 443).

http.client.responses

This dictionary maps the HTTP 1.1 status codes to the W3C names.

Example: http.client.responses[http.client.NOT_FOUND] is 'Not Found'.

See HTTP 상태 코드 for a list of HTTP status codes that are available in this module as constants.

HTTPConnection Objects

HTTPConnection instances have the following methods:

HTTPConnection.request(method, url, body=None, headers={}, *, encode_chunked=False)

This will send a request to the server using the HTTP request method method and the selector url.

If body is specified, the specified data is sent after the headers are finished. It may be a str, a bytes-like object, an open file object, or an iterable of bytes. If body is a string, it is encoded as ISO-8859-1, the default for HTTP. If it is a bytes-like object, the bytes are sent as is. If it is a file object, the contents of the file is sent; this file object should support at least the read() method. If the file object is an instance of io.TextIOBase, the data returned by the read() method will be encoded as ISO-8859-1, otherwise the data returned by read() is sent as is. If body is an iterable, the elements of the iterable are sent as is until the iterable is exhausted.

The headers argument should be a mapping of extra HTTP headers to send with the request.

If headers contains neither Content-Length nor Transfer-Encoding, but there is a request body, one of those header fields will be added automatically. If body is None, the Content-Length header is set to 0 for methods that expect a body (PUT, POST, and PATCH). If body is a string or a bytes-like object that is not also a file, the Content-Length header is set to its length. Any other type of body (files and iterables in general) will be chunk-encoded, and the Transfer-Encoding header will automatically be set instead of Content-Length.

The encode_chunked argument is only relevant if Transfer-Encoding is specified in headers. If encode_chunked is False, the HTTPConnection object assumes that all encoding is handled by the calling code. If it is True, the body will be chunk-encoded.

참고

Chunked transfer encoding has been added to the HTTP protocol version 1.1. Unless the HTTP server is known to handle HTTP 1.1, the caller must either specify the Content-Length, or must pass a str or bytes-like object that is not also a file as the body representation.

버전 3.2에 추가: body can now be an iterable.

버전 3.6에서 변경: If neither Content-Length nor Transfer-Encoding are set in headers, file and iterable body objects are now chunk-encoded. The encode_chunked argument was added. No attempt is made to determine the Content-Length for file objects.

HTTPConnection.getresponse()

Should be called after a request is sent to get the response from the server. Returns an HTTPResponse instance.

참고

Note that you must have read the whole response before you can send a new request to the server.

버전 3.5에서 변경: If a ConnectionError or subclass is raised, the HTTPConnection object will be ready to reconnect when a new request is sent.

HTTPConnection.set_debuglevel(level)

Set the debugging level. The default debug level is 0, meaning no debugging output is printed. Any value greater than 0 will cause all currently defined debug output to be printed to stdout. The debuglevel is passed to any new HTTPResponse objects that are created.

버전 3.1에 추가.

HTTPConnection.set_tunnel(host, port=None, headers=None)

Set the host and the port for HTTP Connect Tunnelling. This allows running the connection through a proxy server.

The host and port arguments specify the endpoint of the tunneled connection (i.e. the address included in the CONNECT request, not the address of the proxy server).

The headers argument should be a mapping of extra HTTP headers to send with the CONNECT request.

For example, to tunnel through a HTTPS proxy server running locally on port 8080, we would pass the address of the proxy to the HTTPSConnection constructor, and the address of the host that we eventually want to reach to the set_tunnel() method:

>>> import http.client
>>> conn = http.client.HTTPSConnection("localhost", 8080)
>>> conn.set_tunnel("www.python.org")
>>> conn.request("HEAD","/index.html")

버전 3.2에 추가.

HTTPConnection.connect()

Connect to the server specified when the object was created. By default, this is called automatically when making a request if the client does not already have a connection.

HTTPConnection.close()

Close the connection to the server.

HTTPConnection.blocksize

Buffer size in bytes for sending a file-like message body.

버전 3.7에 추가.

As an alternative to using the request() method described above, you can also send your request step by step, by using the four functions below.

HTTPConnection.putrequest(method, url, skip_host=False, skip_accept_encoding=False)

This should be the first call after the connection to the server has been made. It sends a line to the server consisting of the method string, the url string, and the HTTP version (HTTP/1.1). To disable automatic sending of Host: or Accept-Encoding: headers (for example to accept additional content encodings), specify skip_host or skip_accept_encoding with non-False values.

HTTPConnection.putheader(header, argument[, ...])

Send an RFC 822 [https://tools.ietf.org/html/rfc822.html]-style header to the server. It sends a line to the server consisting of the header, a colon and a space, and the first argument. If more arguments are given, continuation lines are sent, each consisting of a tab and an argument.

HTTPConnection.endheaders(message_body=None, *, encode_chunked=False)

Send a blank line to the server, signalling the end of the headers. The optional message_body argument can be used to pass a message body associated with the request.

If encode_chunked is True, the result of each iteration of message_body will be chunk-encoded as specified in RFC 7230 [https://tools.ietf.org/html/rfc7230.html], Section 3.3.1. How the data is encoded is dependent on the type of message_body. If message_body implements the buffer interface the encoding will result in a single chunk. If message_body is a collections.abc.Iterable, each iteration of message_body will result in a chunk. If message_body is a file object, each call to .read() will result in a chunk. The method automatically signals the end of the chunk-encoded data immediately after message_body.

참고

Due to the chunked encoding specification, empty chunks yielded by an iterator body will be ignored by the chunk-encoder. This is to avoid premature termination of the read of the request by the target server due to malformed encoding.

버전 3.6에 추가: Chunked encoding support. The encode_chunked parameter was added.

HTTPConnection.send(data)

Send data to the server. This should be used directly only after the endheaders() method has been called and before getresponse() is called.

HTTPResponse Objects

An HTTPResponse instance wraps the HTTP response from the server. It provides access to the request headers and the entity body. The response is an iterable object and can be used in a with statement.

버전 3.5에서 변경: The io.BufferedIOBase interface is now implemented and all of its reader operations are supported.

HTTPResponse.read([amt])

Reads and returns the response body, or up to the next amt bytes.

HTTPResponse.readinto(b)

Reads up to the next len(b) bytes of the response body into the buffer b. Returns the number of bytes read.

버전 3.3에 추가.

HTTPResponse.getheader(name, default=None)

Return the value of the header name, or default if there is no header matching name. If there is more than one header with the name name, return all of the values joined by ‘, ‘. If ‘default’ is any iterable other than a single string, its elements are similarly returned joined by commas.

HTTPResponse.getheaders()

Return a list of (header, value) tuples.

HTTPResponse.fileno()

Return the fileno of the underlying socket.

HTTPResponse.msg

A http.client.HTTPMessage instance containing the response headers. http.client.HTTPMessage is a subclass of email.message.Message.

HTTPResponse.version

HTTP protocol version used by server. 10 for HTTP/1.0, 11 for HTTP/1.1.

HTTPResponse.status

Status code returned by server.

HTTPResponse.reason

Reason phrase returned by server.

HTTPResponse.debuglevel

A debugging hook. If debuglevel is greater than zero, messages will be printed to stdout as the response is read and parsed.

HTTPResponse.closed

Is True if the stream is closed.

Examples

Here is an example session that uses the GET method:

>>> import http.client
>>> conn = http.client.HTTPSConnection("www.python.org")
>>> conn.request("GET", "/")
>>> r1 = conn.getresponse()
>>> print(r1.status, r1.reason)
200 OK
>>> data1 = r1.read()  # This will return entire content.
>>> # The following example demonstrates reading data in chunks.
>>> conn.request("GET", "/")
>>> r1 = conn.getresponse()
>>> while True:
...     chunk = r1.read(200)  # 200 bytes
...     if not chunk:
...          break
...     print(repr(chunk))
b'<!doctype html>\n<!--[if"...
...
>>> # Example of an invalid request
>>> conn = http.client.HTTPSConnection("docs.python.org")
>>> conn.request("GET", "/parrot.spam")
>>> r2 = conn.getresponse()
>>> print(r2.status, r2.reason)
404 Not Found
>>> data2 = r2.read()
>>> conn.close()

Here is an example session that uses the HEAD method. Note that the HEAD method never returns any data.

>>> import http.client
>>> conn = http.client.HTTPSConnection("www.python.org")
>>> conn.request("HEAD", "/")
>>> res = conn.getresponse()
>>> print(res.status, res.reason)
200 OK
>>> data = res.read()
>>> print(len(data))
0
>>> data == b''
True

Here is an example session that shows how to POST requests:

>>> import http.client, urllib.parse
>>> params = urllib.parse.urlencode({'@number': 12524, '@type': 'issue', '@action': 'show'})
>>> headers = {"Content-type": "application/x-www-form-urlencoded",
...            "Accept": "text/plain"}
>>> conn = http.client.HTTPConnection("bugs.python.org")
>>> conn.request("POST", "", params, headers)
>>> response = conn.getresponse()
>>> print(response.status, response.reason)
302 Found
>>> data = response.read()
>>> data
b'Redirecting to <a href="http://bugs.python.org/issue12524">http://bugs.python.org/issue12524</a>'
>>> conn.close()

Client side HTTP PUT requests are very similar to POST requests. The difference lies only the server side where HTTP server will allow resources to be created via PUT request. It should be noted that custom HTTP methods are also handled in urllib.request.Request by setting the appropriate method attribute. Here is an example session that shows how to send a PUT request using http.client:

>>> # This creates an HTTP message
>>> # with the content of BODY as the enclosed representation
>>> # for the resource http://localhost:8080/file
...
>>> import http.client
>>> BODY = "***filecontents***"
>>> conn = http.client.HTTPConnection("localhost", 8080)
>>> conn.request("PUT", "/file", BODY)
>>> response = conn.getresponse()
>>> print(response.status, response.reason)
200, OK

HTTPMessage Objects

An http.client.HTTPMessage instance holds the headers from an HTTP response. It is implemented using the email.message.Message class.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 프로토콜과 지원 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 프로토콜과 지원 »

|

ftplib — FTP protocol client

Source code: Lib/ftplib.py [https://github.com/python/cpython/tree/3.7/Lib/ftplib.py]

This module defines the class FTP and a few related items. The FTP class implements the client side of the FTP protocol. You can use this to write Python programs that perform a variety of automated FTP jobs, such as mirroring other FTP servers. It is also used by the module urllib.request to handle URLs that use FTP. For more information on FTP (File Transfer Protocol), see Internet RFC 959 [https://tools.ietf.org/html/rfc959.html].

Here’s a sample session using the ftplib module:

>>> from ftplib import FTP
>>> ftp = FTP('ftp.debian.org')     # connect to host, default port
>>> ftp.login()                     # user anonymous, passwd anonymous@
'230 Login successful.'
>>> ftp.cwd('debian')               # change into "debian" directory
>>> ftp.retrlines('LIST')           # list directory contents
-rw-rw-r--    1 1176     1176         1063 Jun 15 10:18 README
...
drwxr-sr-x    5 1176     1176         4096 Dec 19  2000 pool
drwxr-sr-x    4 1176     1176         4096 Nov 17  2008 project
drwxr-xr-x    3 1176     1176         4096 Oct 10  2012 tools
'226 Directory send OK.'
>>> with open('README', 'wb') as fp:
>>>     ftp.retrbinary('RETR README', fp.write)
'226 Transfer complete.'
>>> ftp.quit()

The module defines the following items:

class ftplib.FTP(host='', user='', passwd='', acct='', timeout=None, source_address=None)

Return a new instance of the FTP class. When host is given, the method call connect(host) is made. When user is given, additionally the method call login(user, passwd, acct) is made (where passwd and acct default to the empty string when not given). The optional timeout parameter specifies a timeout in seconds for blocking operations like the connection attempt (if is not specified, the global default timeout setting will be used). source_address is a 2-tuple (host, port) for the socket to bind to as its source address before connecting.

The FTP class supports the with statement, e.g.:

>>> from ftplib import FTP
>>> with FTP("ftp1.at.proftpd.org") as ftp:
...     ftp.login()
...     ftp.dir()
...
'230 Anonymous login ok, restrictions apply.'
dr-xr-xr-x   9 ftp      ftp           154 May  6 10:43 .
dr-xr-xr-x   9 ftp      ftp           154 May  6 10:43 ..
dr-xr-xr-x   5 ftp      ftp          4096 May  6 10:43 CentOS
dr-xr-xr-x   3 ftp      ftp            18 Jul 10  2008 Fedora
>>>

버전 3.2에서 변경: Support for the with statement was added.

버전 3.3에서 변경: source_address parameter was added.

class ftplib.FTP_TLS(host='', user='', passwd='', acct='', keyfile=None, certfile=None, context=None, timeout=None, source_address=None)

A FTP subclass which adds TLS support to FTP as described in RFC 4217 [https://tools.ietf.org/html/rfc4217.html]. Connect as usual to port 21 implicitly securing the FTP control connection before authenticating. Securing the data connection requires the user to explicitly ask for it by calling the prot_p() method. context is a ssl.SSLContext object which allows bundling SSL configuration options, certificates and private keys into a single (potentially long-lived) structure. Please read 보안 고려 사항 for best practices.

keyfile and certfile are a legacy alternative to context – they can point to PEM-formatted private key and certificate chain files (respectively) for the SSL connection.

버전 3.2에 추가.

버전 3.3에서 변경: source_address parameter was added.

버전 3.4에서 변경: The class now supports hostname check with ssl.SSLContext.check_hostname and Server Name Indication (see ssl.HAS_SNI).

버전 3.6부터 폐지: keyfile and certfile are deprecated in favor of context. Please use ssl.SSLContext.load_cert_chain() instead, or let ssl.create_default_context() select the system’s trusted CA certificates for you.

Here’s a sample session using the FTP_TLS class:

>>> ftps = FTP_TLS('ftp.pureftpd.org')
>>> ftps.login()
'230 Anonymous user logged in'
>>> ftps.prot_p()
'200 Data protection level set to "private"'
>>> ftps.nlst()
['6jack', 'OpenBSD', 'antilink', 'blogbench', 'bsdcam', 'clockspeed', 'djbdns-jedi', 'docs', 'eaccelerator-jedi', 'favicon.ico', 'francotone', 'fugu', 'ignore', 'libpuzzle', 'metalog', 'minidentd', 'misc', 'mysql-udf-global-user-variables', 'php-jenkins-hash', 'php-skein-hash', 'php-webdav', 'phpaudit', 'phpbench', 'pincaster', 'ping', 'posto', 'pub', 'public', 'public_keys', 'pure-ftpd', 'qscan', 'qtc', 'sharedance', 'skycache', 'sound', 'tmp', 'ucarp']

exception ftplib.error_reply

Exception raised when an unexpected reply is received from the server.

exception ftplib.error_temp

Exception raised when an error code signifying a temporary error (response codes in the range 400–499) is received.

exception ftplib.error_perm

Exception raised when an error code signifying a permanent error (response codes in the range 500–599) is received.

exception ftplib.error_proto

Exception raised when a reply is received from the server that does not fit the response specifications of the File Transfer Protocol, i.e. begin with a digit in the range 1–5.

ftplib.all_errors

The set of all exceptions (as a tuple) that methods of FTP instances may raise as a result of problems with the FTP connection (as opposed to programming errors made by the caller). This set includes the four exceptions listed above as well as OSError.

더 보기

Module netrc

Parser for the .netrc file format. The file .netrc is typically used by FTP clients to load user authentication information before prompting the user.

FTP Objects

Several methods are available in two flavors: one for handling text files and another for binary files. These are named for the command which is used followed by lines for the text version or binary for the binary version.

FTP instances have the following methods:

FTP.set_debuglevel(level)

Set the instance’s debugging level. This controls the amount of debugging output printed. The default, 0, produces no debugging output. A value of 1 produces a moderate amount of debugging output, generally a single line per request. A value of 2 or higher produces the maximum amount of debugging output, logging each line sent and received on the control connection.

FTP.connect(host='', port=0, timeout=None, source_address=None)

Connect to the given host and port. The default port number is 21, as specified by the FTP protocol specification. It is rarely needed to specify a different port number. This function should be called only once for each instance; it should not be called at all if a host was given when the instance was created. All other methods can only be used after a connection has been made. The optional timeout parameter specifies a timeout in seconds for the connection attempt. If no timeout is passed, the global default timeout setting will be used. source_address is a 2-tuple (host, port) for the socket to bind to as its source address before connecting.

버전 3.3에서 변경: source_address parameter was added.

FTP.getwelcome()

Return the welcome message sent by the server in reply to the initial connection. (This message sometimes contains disclaimers or help information that may be relevant to the user.)

FTP.login(user='anonymous', passwd='', acct='')

Log in as the given user. The passwd and acct parameters are optional and default to the empty string. If no user is specified, it defaults to 'anonymous'. If user is 'anonymous', the default passwd is 'anonymous@'. This function should be called only once for each instance, after a connection has been established; it should not be called at all if a host and user were given when the instance was created. Most FTP commands are only allowed after the client has logged in. The acct parameter supplies “accounting information”; few systems implement this.

FTP.abort()

Abort a file transfer that is in progress. Using this does not always work, but it’s worth a try.

FTP.sendcmd(cmd)

Send a simple command string to the server and return the response string.

FTP.voidcmd(cmd)

Send a simple command string to the server and handle the response. Return nothing if a response code corresponding to success (codes in the range 200–299) is received. Raise error_reply otherwise.

FTP.retrbinary(cmd, callback, blocksize=8192, rest=None)

Retrieve a file in binary transfer mode. cmd should be an appropriate RETR command: 'RETR filename'. The callback function is called for each block of data received, with a single bytes argument giving the data block. The optional blocksize argument specifies the maximum chunk size to read on the low-level socket object created to do the actual transfer (which will also be the largest size of the data blocks passed to callback). A reasonable default is chosen. rest means the same thing as in the transfercmd() method.

FTP.retrlines(cmd, callback=None)

Retrieve a file or directory listing in ASCII transfer mode. cmd should be an appropriate RETR command (see retrbinary()) or a command such as LIST or NLST (usually just the string 'LIST'). LIST retrieves a list of files and information about those files. NLST retrieves a list of file names. The callback function is called for each line with a string argument containing the line with the trailing CRLF stripped. The default callback prints the line to sys.stdout.

FTP.set_pasv(val)

Enable “passive” mode if val is true, otherwise disable passive mode. Passive mode is on by default.

FTP.storbinary(cmd, fp, blocksize=8192, callback=None, rest=None)

Store a file in binary transfer mode. cmd should be an appropriate STOR command: "STOR filename". fp is a file object (opened in binary mode) which is read until EOF using its read() method in blocks of size blocksize to provide the data to be stored. The blocksize argument defaults to 8192. callback is an optional single parameter callable that is called on each block of data after it is sent. rest means the same thing as in the transfercmd() method.

버전 3.2에서 변경: rest parameter added.

FTP.storlines(cmd, fp, callback=None)

Store a file in ASCII transfer mode. cmd should be an appropriate STOR command (see storbinary()). Lines are read until EOF from the file object fp (opened in binary mode) using its readline() method to provide the data to be stored. callback is an optional single parameter callable that is called on each line after it is sent.

FTP.transfercmd(cmd, rest=None)

Initiate a transfer over the data connection. If the transfer is active, send an EPRT or PORT command and the transfer command specified by cmd, and accept the connection. If the server is passive, send an EPSV or PASV command, connect to it, and start the transfer command. Either way, return the socket for the connection.

If optional rest is given, a REST command is sent to the server, passing rest as an argument. rest is usually a byte offset into the requested file, telling the server to restart sending the file’s bytes at the requested offset, skipping over the initial bytes. Note however that RFC 959 [https://tools.ietf.org/html/rfc959.html] requires only that rest be a string containing characters in the printable range from ASCII code 33 to ASCII code 126. The transfercmd() method, therefore, converts rest to a string, but no check is performed on the string’s contents. If the server does not recognize the REST command, an error_reply exception will be raised. If this happens, simply call transfercmd() without a rest argument.

FTP.ntransfercmd(cmd, rest=None)

Like transfercmd(), but returns a tuple of the data connection and the expected size of the data. If the expected size could not be computed, None will be returned as the expected size. cmd and rest means the same thing as in transfercmd().

FTP.mlsd(path="", facts=[])

List a directory in a standardized format by using MLSD command (RFC 3659 [https://tools.ietf.org/html/rfc3659.html]). If path is omitted the current directory is assumed. facts is a list of strings representing the type of information desired (e.g. ["type", "size", "perm"]). Return a generator object yielding a tuple of two elements for every file found in path. First element is the file name, the second one is a dictionary containing facts about the file name. Content of this dictionary might be limited by the facts argument but server is not guaranteed to return all requested facts.

버전 3.3에 추가.

FTP.nlst(argument[, ...])

Return a list of file names as returned by the NLST command. The optional argument is a directory to list (default is the current server directory). Multiple arguments can be used to pass non-standard options to the NLST command.

참고

If your server supports the command, mlsd() offers a better API.

FTP.dir(argument[, ...])

Produce a directory listing as returned by the LIST command, printing it to standard output. The optional argument is a directory to list (default is the current server directory). Multiple arguments can be used to pass non-standard options to the LIST command. If the last argument is a function, it is used as a callback function as for retrlines(); the default prints to sys.stdout. This method returns None.

참고

If your server supports the command, mlsd() offers a better API.

FTP.rename(fromname, toname)

Rename file fromname on the server to toname.

FTP.delete(filename)

Remove the file named filename from the server. If successful, returns the text of the response, otherwise raises error_perm on permission errors or error_reply on other errors.

FTP.cwd(pathname)

Set the current directory on the server.

FTP.mkd(pathname)

Create a new directory on the server.

FTP.pwd()

Return the pathname of the current directory on the server.

FTP.rmd(dirname)

Remove the directory named dirname on the server.

FTP.size(filename)

Request the size of the file named filename on the server. On success, the size of the file is returned as an integer, otherwise None is returned. Note that the SIZE command is not standardized, but is supported by many common server implementations.

FTP.quit()

Send a QUIT command to the server and close the connection. This is the “polite” way to close a connection, but it may raise an exception if the server responds with an error to the QUIT command. This implies a call to the close() method which renders the FTP instance useless for subsequent calls (see below).

FTP.close()

Close the connection unilaterally. This should not be applied to an already closed connection such as after a successful call to quit(). After this call the FTP instance should not be used any more (after a call to close() or quit() you cannot reopen the connection by issuing another login() method).

FTP_TLS Objects

FTP_TLS class inherits from FTP, defining these additional objects:

FTP_TLS.ssl_version

The SSL version to use (defaults to ssl.PROTOCOL_SSLv23).

FTP_TLS.auth()

Set up a secure control connection by using TLS or SSL, depending on what is specified in the ssl_version attribute.

버전 3.4에서 변경: The method now supports hostname check with ssl.SSLContext.check_hostname and Server Name Indication (see ssl.HAS_SNI).

FTP_TLS.ccc()

Revert control channel back to plaintext. This can be useful to take advantage of firewalls that know how to handle NAT with non-secure FTP without opening fixed ports.

버전 3.3에 추가.

FTP_TLS.prot_p()

Set up secure data connection.

FTP_TLS.prot_c()

Set up clear text data connection.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 프로토콜과 지원 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 프로토콜과 지원 »

|

poplib — POP3 프로토콜 클라이언트

소스 코드: Lib/poplib.py [https://github.com/python/cpython/tree/3.7/Lib/poplib.py]

이 모듈은 POP3 서버에 대한 연결을 캡슐화하고 RFC 1939 [https://tools.ietf.org/html/rfc1939.html]에 정의된 대로 프로토콜을 구현하는 클래스 POP3를 정의합니다. POP3 클래스는 RFC 1939 [https://tools.ietf.org/html/rfc1939.html]의 최소(minimal)와 선택적인(optional) 명령 집합을 모두 지원합니다. POP3 클래스는 이미 맺어진 연결에서 암호화된 통신을 활성화하기 위해 RFC 2595 [https://tools.ietf.org/html/rfc2595.html]에서 도입된 STLS 명령도 지원합니다.

또한, 이 모듈은 SSL을 하부 프로토콜 계층으로 사용하는 POP3 서버에 연결하기 위한 지원을 제공하는 클래스 POP3_SSL을 제공합니다.

POP3는 광범위하게 지원되지만 노후화되었음에 유의하십시오. POP3 서버의 구현 품질은 매우 다양하며, 그중 너무 많은 것들이 형편없습니다. 여러분의 메일 서버가 IMAP을 지원한다면, IMAP 서버가 더 잘 구현되는 경향이 있으므로 imaplib.IMAP4 클래스를 사용하는 것이 좋습니다.

poplib 모듈은 두 가지 클래스를 제공합니다:

class poplib.POP3(host, port=POP3_PORT[, timeout])

이 클래스는 실제 POP3 프로토콜을 구현합니다. 인스턴스가 초기화될 때 연결이 만들어집니다. port를 생략하면, 표준 POP3 포트(110)가 사용됩니다. 선택적 timeout 매개 변수는 연결 시도의 제한 시간을 초로 지정합니다 (지정하지 않으면, 전역 기본 제한 시간 설정이 사용됩니다).

class poplib.POP3_SSL(host, port=POP3_SSL_PORT, keyfile=None, certfile=None, timeout=None, context=None)

SSL 암호화된 소켓을 통해 서버에 연결하는 POP3의 서브 클래스입니다. port가 지정되지 않으면, 표준 POP3-over-SSL 포트(995)가 사용됩니다. timeout은 POP3 생성자에서처럼 동작합니다. context는 선택적인 ssl.SSLContext 객체인데, SSL 구성 옵션, 인증서 및 개인 키를 단일 (잠재적으로 수명이 긴) 구조로 묶을 수 있도록 합니다. 모범 사례는 보안 고려 사항을 읽으십시오.

keyfile과 certfile은 context의 레거시 대안입니다 - SSL 연결을 위해 각각 PEM 형식의 개인 키와 인증서 체인 파일을 가리킬 수 있습니다.

버전 3.2에서 변경: context 매개 변수가 추가되었습니다.

버전 3.4에서 변경: 클래스는 이제 ssl.SSLContext.check_hostname을 통한 호스트 이름 검사와 서버 이름 표시(Server Name Indication)를 지원합니다 (ssl.HAS_SNI를 참조하십시오).

버전 3.6부터 폐지: keyfile과 certfile은 폐지되었고, context로 대체합니다. 대신 ssl.SSLContext.load_cert_chain()을 사용하거나, ssl.create_default_context()가 시스템의 신뢰할 수 있는 CA 인증서를 선택하도록 하십시오.

한가지 예외가 poplib 모듈의 어트리뷰트로 정의됩니다:

exception poplib.error_proto

이 모듈로부터 비롯된 모든 에러에서 발생하는 예외 (socket 모듈에서 비롯된 에러는 잡지 않습니다). 예외의 이유는 문자열로 생성자에 전달됩니다.

더 보기

모듈 imaplib

표준 파이썬 IMAP 모듈.

Frequently Asked Questions About Fetchmail [http://www.catb.org/~esr/fetchmail/fetchmail-FAQ.html]

fetchmail POP/IMAP 클라이언트에 대한 FAQ는 POP 프로토콜에 기반하는 응용 프로그램을 작성해야 할 때 유용할 수 있는 POP3 서버 다양성과 RFC 위반에 대한 정보를 수집합니다.

POP3 객체

모든 POP3 명령은 소문자로 바뀐 같은 이름의 메서드로 표현됩니다; 대부분 서버에서 보낸 응답 텍스트를 반환합니다.

POP3 인스턴스에는 다음과 같은 메서드가 있습니다:

POP3.set_debuglevel(level)

인스턴스의 디버깅 수준을 설정합니다. 이것은 인쇄되는 디버깅 출력의 양을 제어합니다. 기본값인 0은 디버깅 출력을 생성하지 않습니다. 1 값은 적절한 양의 디버깅 출력을 생성하는데, 일반적으로 요청당 한 줄입니다. 2 이상의 값은 제어 연결에서 보내고 받은 각 줄을 로깅 하여 최대량의 디버깅 출력을 생성합니다.

POP3.getwelcome()

POP3 서버가 보낸 인사말 문자열을 반환합니다.

POP3.capa()

RFC 2449 [https://tools.ietf.org/html/rfc2449.html]에 지정된 대로 서버의 기능을 조회합니다. {'name': ['param'...]} 형식의 딕셔너리를 반환합니다.

버전 3.4에 추가.

POP3.user(username)

user 명령을 보냅니다, 응답은 암호가 필요함을 가리켜야 합니다.

POP3.pass_(password)

암호를 보냅니다, 응답에는 메시지 수와 우편함 크기가 포함됩니다. 참고: quit()가 호출될 때까지 서버의 우편함은 잠깁니다.

POP3.apop(user, secret)

POP3 서버에 로그인하기 위해 더 안전한 APOP 인증을 사용합니다.

POP3.rpop(user)

POP3 서버에 로그인하기 위해 RPOP 인증(유닉스 r-명령과 유사합니다)을 사용합니다.

POP3.stat()

우편함 상태를 가져옵니다. 결과는 2개의 정수의 튜플입니다: (message count, mailbox size).

POP3.list([which])

메시지 목록을 요청합니다, 결과는 (response, ['mesg_num octets', ...], octets) 형식입니다. which가 설정되면, 목록에 표시할 메시지입니다.

POP3.retr(which)

전체 메시지 번호 which를 가져오고 읽었음을 알리는 플래그를 설정합니다. 결과는 (response, ['line', ...], octets) 형식입니다.

POP3.dele(which)

메시지 번호 which를 삭제로 표시합니다. 대부분 서버에서 삭제는 실제로 QUIT 때까지 수행되지 않습니다 (주된 예외는 Eudora QPOP인데, 모든 연결 단절 시 계류 중인 삭제를 수행하여 의도적으로 RFC를 위반합니다).

POP3.rset()

우편함에 대한 모든 삭제 표시를 제거합니다.

POP3.noop()

아무것도 하지 않습니다. 연결 유지로 사용될 수 있습니다.

POP3.quit()

로그아웃: 변경 내용 커밋, 우편함 잠금 해제, 연결 끊기.

POP3.top(which, howmuch)

메시지 번호 which의 메시지 헤더와 메시지의 howmuch 개 줄을 가져옵니다. 결과는 (response, ['line', ...], octets) 형식입니다.

이 메서드가 사용하는 POP3 TOP 명령은, RETR 명령과 달리, 메시지의 읽었음을 알리는 플래그를 설정하지 않습니다; 불행히도, TOP은 RFC에서 부실하게 기술되어 있고 종종 유명하지 않은 서버에서 망가져 있습니다. 사용할 POP3 서버를 신뢰하기 전에 이 메서드를 수동으로 테스트하십시오.

POP3.uidl(which=None)

메시지 다이제스트 (고유 ID) 목록을 반환합니다. which가 지정되면, 결과에는 해당 메시지의 고유 ID가 'response mesgnum uid 형식으로 포함됩니다. 그렇지 않으면, 결과는 목록 (response, ['mesgnum uid', ...], octets)입니다.

POP3.utf8()

UTF-8 모드로의 전환을 시도합니다. 성공하면 서버 응답을 반환하고, 그렇지 않으면 error_proto를 발생시킵니다. RFC 6856 [https://tools.ietf.org/html/rfc6856.html]에서 정의되었습니다.

버전 3.5에 추가.

POP3.stls(context=None)

RFC 2595 [https://tools.ietf.org/html/rfc2595.html]에 지정된 대로 활성 연결에서 TLS 세션을 시작합니다. 사용자 인증 전에만 허용됩니다.

context 매개 변수는 ssl.SSLContext 객체인데, SSL 구성 옵션, 인증서 및 개인 키를 단일 (잠재적으로 수명이 긴) 구조로 묶을 수 있도록 합니다. 모범 사례는 보안 고려 사항을 읽으십시오.

이 메서드는 ssl.SSLContext.check_hostname을 통한 호스트 이름 검사와 서버 이름 표시(Server Name Indication)를 지원합니다 (ssl.HAS_SNI를 참조하십시오)

버전 3.4에 추가.

POP3_SSL의 인스턴스에는 추가 메서드가 없습니다. 이 서브 클래스의 인터페이스는 그 부모와 같습니다.

POP3 예제

다음은 우편함을 열고 모든 메시지를 가져와서 인쇄하는 (에러 검사 없는) 최소한의 예입니다:

import getpass, poplib

M = poplib.POP3('localhost')
M.user(getpass.getuser())
M.pass_(getpass.getpass())
numMessages = len(M.list()[1])
for i in range(numMessages):
    for j in M.retr(i+1)[1]:
        print(j)

모듈의 끝에는, 더욱 광범위한 사용 예제가 포함된 테스트 섹션이 있습니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 프로토콜과 지원 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 프로토콜과 지원 »

|

imaplib — IMAP4 protocol client

Source code: Lib/imaplib.py [https://github.com/python/cpython/tree/3.7/Lib/imaplib.py]

This module defines three classes, IMAP4, IMAP4_SSL and IMAP4_stream, which encapsulate a connection to an IMAP4 server and implement a large subset of the IMAP4rev1 client protocol as defined in RFC 2060 [https://tools.ietf.org/html/rfc2060.html]. It is backward compatible with IMAP4 (RFC 1730 [https://tools.ietf.org/html/rfc1730.html]) servers, but note that the STATUS command is not supported in IMAP4.

Three classes are provided by the imaplib module, IMAP4 is the base class:

class imaplib.IMAP4(host='', port=IMAP4_PORT)

This class implements the actual IMAP4 protocol. The connection is created and protocol version (IMAP4 or IMAP4rev1) is determined when the instance is initialized. If host is not specified, '' (the local host) is used. If port is omitted, the standard IMAP4 port (143) is used.

The IMAP4 class supports the with statement. When used like this, the IMAP4 LOGOUT command is issued automatically when the with statement exits. E.g.:

>>> from imaplib import IMAP4
>>> with IMAP4("domain.org") as M:
...     M.noop()
...
('OK', [b'Nothing Accomplished. d25if65hy903weo.87'])

버전 3.5에서 변경: Support for the with statement was added.

Three exceptions are defined as attributes of the IMAP4 class:

exception IMAP4.error

Exception raised on any errors. The reason for the exception is passed to the constructor as a string.

exception IMAP4.abort

IMAP4 server errors cause this exception to be raised. This is a sub-class of IMAP4.error. Note that closing the instance and instantiating a new one will usually allow recovery from this exception.

exception IMAP4.readonly

This exception is raised when a writable mailbox has its status changed by the server. This is a sub-class of IMAP4.error. Some other client now has write permission, and the mailbox will need to be re-opened to re-obtain write permission.

There’s also a subclass for secure connections:

class imaplib.IMAP4_SSL(host='', port=IMAP4_SSL_PORT, keyfile=None, certfile=None, ssl_context=None)

This is a subclass derived from IMAP4 that connects over an SSL encrypted socket (to use this class you need a socket module that was compiled with SSL support). If host is not specified, '' (the local host) is used. If port is omitted, the standard IMAP4-over-SSL port (993) is used. ssl_context is a ssl.SSLContext object which allows bundling SSL configuration options, certificates and private keys into a single (potentially long-lived) structure. Please read 보안 고려 사항 for best practices.

keyfile and certfile are a legacy alternative to ssl_context - they can point to PEM-formatted private key and certificate chain files for the SSL connection. Note that the keyfile/certfile parameters are mutually exclusive with ssl_context, a ValueError is raised if keyfile/certfile is provided along with ssl_context.

버전 3.3에서 변경: ssl_context parameter added.

버전 3.4에서 변경: The class now supports hostname check with ssl.SSLContext.check_hostname and Server Name Indication (see ssl.HAS_SNI).

버전 3.6부터 폐지: keyfile and certfile are deprecated in favor of ssl_context. Please use ssl.SSLContext.load_cert_chain() instead, or let ssl.create_default_context() select the system’s trusted CA certificates for you.

The second subclass allows for connections created by a child process:

class imaplib.IMAP4_stream(command)

This is a subclass derived from IMAP4 that connects to the stdin/stdout file descriptors created by passing command to subprocess.Popen().

The following utility functions are defined:

imaplib.Internaldate2tuple(datestr)

Parse an IMAP4 INTERNALDATE string and return corresponding local time. The return value is a time.struct_time tuple or None if the string has wrong format.

imaplib.Int2AP(num)

Converts an integer into a string representation using characters from the set [A .. P].

imaplib.ParseFlags(flagstr)

Converts an IMAP4 FLAGS response to a tuple of individual flags.

imaplib.Time2Internaldate(date_time)

Convert date_time to an IMAP4 INTERNALDATE representation. The return value is a string in the form: "DD-Mmm-YYYY HH:MM:SS +HHMM" (including double-quotes). The date_time argument can be a number (int or float) representing seconds since epoch (as returned by time.time()), a 9-tuple representing local time an instance of time.struct_time (as returned by time.localtime()), an aware instance of datetime.datetime, or a double-quoted string. In the last case, it is assumed to already be in the correct format.

Note that IMAP4 message numbers change as the mailbox changes; in particular, after an EXPUNGE command performs deletions the remaining messages are renumbered. So it is highly advisable to use UIDs instead, with the UID command.

At the end of the module, there is a test section that contains a more extensive example of usage.

더 보기

Documents describing the protocol, and sources and binaries for servers implementing it, can all be found at the University of Washington’s IMAP Information Center (https://www.washington.edu/imap/).

IMAP4 Objects

All IMAP4rev1 commands are represented by methods of the same name, either upper-case or lower-case.

All arguments to commands are converted to strings, except for AUTHENTICATE, and the last argument to APPEND which is passed as an IMAP4 literal. If necessary (the string contains IMAP4 protocol-sensitive characters and isn’t enclosed with either parentheses or double quotes) each string is quoted. However, the password argument to the LOGIN command is always quoted. If you want to avoid having an argument string quoted (eg: the flags argument to STORE) then enclose the string in parentheses (eg: r'(\Deleted)').

Each command returns a tuple: (type, [data, ...]) where type is usually 'OK' or 'NO', and data is either the text from the command response, or mandated results from the command. Each data is either a string, or a tuple. If a tuple, then the first part is the header of the response, and the second part contains the data (ie: ‘literal’ value).

The message_set options to commands below is a string specifying one or more messages to be acted upon. It may be a simple message number ('1'), a range of message numbers ('2:4'), or a group of non-contiguous ranges separated by commas ('1:3,6:9'). A range can contain an asterisk to indicate an infinite upper bound ('3:*').

An IMAP4 instance has the following methods:

IMAP4.append(mailbox, flags, date_time, message)

Append message to named mailbox.

IMAP4.authenticate(mechanism, authobject)

Authenticate command — requires response processing.

mechanism specifies which authentication mechanism is to be used - it should appear in the instance variable capabilities in the form AUTH=mechanism.

authobject must be a callable object:

data = authobject(response)

It will be called to process server continuation responses; the response argument it is passed will be bytes. It should return bytes data that will be base64 encoded and sent to the server. It should return None if the client abort response * should be sent instead.

버전 3.5에서 변경: string usernames and passwords are now encoded to utf-8 instead of being limited to ASCII.

IMAP4.check()

Checkpoint mailbox on server.

IMAP4.close()

Close currently selected mailbox. Deleted messages are removed from writable mailbox. This is the recommended command before LOGOUT.

IMAP4.copy(message_set, new_mailbox)

Copy message_set messages onto end of new_mailbox.

IMAP4.create(mailbox)

Create new mailbox named mailbox.

IMAP4.delete(mailbox)

Delete old mailbox named mailbox.

IMAP4.deleteacl(mailbox, who)

Delete the ACLs (remove any rights) set for who on mailbox.

IMAP4.enable(capability)

Enable capability (see RFC 5161 [https://tools.ietf.org/html/rfc5161.html]). Most capabilities do not need to be enabled. Currently only the UTF8=ACCEPT capability is supported (see RFC 6855 [https://tools.ietf.org/html/rfc6855.html]).

버전 3.5에 추가: The enable() method itself, and RFC 6855 [https://tools.ietf.org/html/rfc6855.html] support.

IMAP4.expunge()

Permanently remove deleted items from selected mailbox. Generates an EXPUNGE response for each deleted message. Returned data contains a list of EXPUNGE message numbers in order received.

IMAP4.fetch(message_set, message_parts)

Fetch (parts of) messages. message_parts should be a string of message part names enclosed within parentheses, eg: "(UID BODY[TEXT])". Returned data are tuples of message part envelope and data.

IMAP4.getacl(mailbox)

Get the ACLs for mailbox. The method is non-standard, but is supported by the Cyrus server.

IMAP4.getannotation(mailbox, entry, attribute)

Retrieve the specified ANNOTATIONs for mailbox. The method is non-standard, but is supported by the Cyrus server.

IMAP4.getquota(root)

Get the quota root’s resource usage and limits. This method is part of the IMAP4 QUOTA extension defined in rfc2087.

IMAP4.getquotaroot(mailbox)

Get the list of quota roots for the named mailbox. This method is part of the IMAP4 QUOTA extension defined in rfc2087.

IMAP4.list([directory[, pattern]])

List mailbox names in directory matching pattern. directory defaults to the top-level mail folder, and pattern defaults to match anything. Returned data contains a list of LIST responses.

IMAP4.login(user, password)

Identify the client using a plaintext password. The password will be quoted.

IMAP4.login_cram_md5(user, password)

Force use of CRAM-MD5 authentication when identifying the client to protect the password. Will only work if the server CAPABILITY response includes the phrase AUTH=CRAM-MD5.

IMAP4.logout()

Shutdown connection to server. Returns server BYE response.

IMAP4.lsub(directory='""', pattern='*')

List subscribed mailbox names in directory matching pattern. directory defaults to the top level directory and pattern defaults to match any mailbox. Returned data are tuples of message part envelope and data.

IMAP4.myrights(mailbox)

Show my ACLs for a mailbox (i.e. the rights that I have on mailbox).

IMAP4.namespace()

Returns IMAP namespaces as defined in RFC 2342 [https://tools.ietf.org/html/rfc2342.html].

IMAP4.noop()

Send NOOP to server.

IMAP4.open(host, port)

Opens socket to port at host. This method is implicitly called by the IMAP4 constructor. The connection objects established by this method will be used in the IMAP4.read(), IMAP4.readline(), IMAP4.send(), and IMAP4.shutdown() methods. You may override this method.

IMAP4.partial(message_num, message_part, start, length)

Fetch truncated part of a message. Returned data is a tuple of message part envelope and data.

IMAP4.proxyauth(user)

Assume authentication as user. Allows an authorised administrator to proxy into any user’s mailbox.

IMAP4.read(size)

Reads size bytes from the remote server. You may override this method.

IMAP4.readline()

Reads one line from the remote server. You may override this method.

IMAP4.recent()

Prompt server for an update. Returned data is None if no new messages, else value of RECENT response.

IMAP4.rename(oldmailbox, newmailbox)

Rename mailbox named oldmailbox to newmailbox.

IMAP4.response(code)

Return data for response code if received, or None. Returns the given code, instead of the usual type.

IMAP4.search(charset, criterion[, ...])

Search mailbox for matching messages. charset may be None, in which case no CHARSET will be specified in the request to the server. The IMAP protocol requires that at least one criterion be specified; an exception will be raised when the server returns an error. charset must be None if the UTF8=ACCEPT capability was enabled using the enable() command.

Example:

# M is a connected IMAP4 instance...
typ, msgnums = M.search(None, 'FROM', '"LDJ"')

# or:
typ, msgnums = M.search(None, '(FROM "LDJ")')

IMAP4.select(mailbox='INBOX', readonly=False)

Select a mailbox. Returned data is the count of messages in mailbox (EXISTS response). The default mailbox is 'INBOX'. If the readonly flag is set, modifications to the mailbox are not allowed.

IMAP4.send(data)

Sends data to the remote server. You may override this method.

IMAP4.setacl(mailbox, who, what)

Set an ACL for mailbox. The method is non-standard, but is supported by the Cyrus server.

IMAP4.setannotation(mailbox, entry, attribute[, ...])

Set ANNOTATIONs for mailbox. The method is non-standard, but is supported by the Cyrus server.

IMAP4.setquota(root, limits)

Set the quota root’s resource limits. This method is part of the IMAP4 QUOTA extension defined in rfc2087.

IMAP4.shutdown()

Close connection established in open. This method is implicitly called by IMAP4.logout(). You may override this method.

IMAP4.socket()

Returns socket instance used to connect to server.

IMAP4.sort(sort_criteria, charset, search_criterion[, ...])

The sort command is a variant of search with sorting semantics for the results. Returned data contains a space separated list of matching message numbers.

Sort has two arguments before the search_criterion argument(s); a parenthesized list of sort_criteria, and the searching charset. Note that unlike search, the searching charset argument is mandatory. There is also a uid sort command which corresponds to sort the way that uid search corresponds to search. The sort command first searches the mailbox for messages that match the given searching criteria using the charset argument for the interpretation of strings in the searching criteria. It then returns the numbers of matching messages.

This is an IMAP4rev1 extension command.

IMAP4.starttls(ssl_context=None)

Send a STARTTLS command. The ssl_context argument is optional and should be a ssl.SSLContext object. This will enable encryption on the IMAP connection. Please read 보안 고려 사항 for best practices.

버전 3.2에 추가.

버전 3.4에서 변경: The method now supports hostname check with ssl.SSLContext.check_hostname and Server Name Indication (see ssl.HAS_SNI).

IMAP4.status(mailbox, names)

Request named status conditions for mailbox.

IMAP4.store(message_set, command, flag_list)

Alters flag dispositions for messages in mailbox. command is specified by section 6.4.6 of RFC 2060 [https://tools.ietf.org/html/rfc2060.html] as being one of “FLAGS”, “+FLAGS”, or “-FLAGS”, optionally with a suffix of “.SILENT”.

For example, to set the delete flag on all messages:

typ, data = M.search(None, 'ALL')
for num in data[0].split():
   M.store(num, '+FLAGS', '\\Deleted')
M.expunge()

참고

Creating flags containing ‘]’ (for example: “[test]”) violates RFC 3501 [https://tools.ietf.org/html/rfc3501.html] (the IMAP protocol). However, imaplib has historically allowed creation of such tags, and popular IMAP servers, such as Gmail, accept and produce such flags. There are non-Python programs which also create such tags. Although it is an RFC violation and IMAP clients and servers are supposed to be strict, imaplib nonetheless continues to allow such tags to be created for backward compatibility reasons, and as of Python 3.6, handles them if they are sent from the server, since this improves real-world compatibility.

IMAP4.subscribe(mailbox)

Subscribe to new mailbox.

IMAP4.thread(threading_algorithm, charset, search_criterion[, ...])

The thread command is a variant of search with threading semantics for the results. Returned data contains a space separated list of thread members.

Thread members consist of zero or more messages numbers, delimited by spaces, indicating successive parent and child.

Thread has two arguments before the search_criterion argument(s); a threading_algorithm, and the searching charset. Note that unlike search, the searching charset argument is mandatory. There is also a uid thread command which corresponds to thread the way that uid search corresponds to search. The thread command first searches the mailbox for messages that match the given searching criteria using the charset argument for the interpretation of strings in the searching criteria. It then returns the matching messages threaded according to the specified threading algorithm.

This is an IMAP4rev1 extension command.

IMAP4.uid(command, arg[, ...])

Execute command args with messages identified by UID, rather than message number. Returns response appropriate to command. At least one argument must be supplied; if none are provided, the server will return an error and an exception will be raised.

IMAP4.unsubscribe(mailbox)

Unsubscribe from old mailbox.

IMAP4.xatom(name[, ...])

Allow simple extension commands notified by server in CAPABILITY response.

The following attributes are defined on instances of IMAP4:

IMAP4.PROTOCOL_VERSION

The most recent supported protocol in the CAPABILITY response from the server.

IMAP4.debug

Integer value to control debugging output. The initialize value is taken from the module variable Debug. Values greater than three trace each command.

IMAP4.utf8_enabled

Boolean value that is normally False, but is set to True if an enable() command is successfully issued for the UTF8=ACCEPT capability.

버전 3.5에 추가.

IMAP4 Example

Here is a minimal example (without error checking) that opens a mailbox and retrieves and prints all messages:

import getpass, imaplib

M = imaplib.IMAP4()
M.login(getpass.getuser(), getpass.getpass())
M.select()
typ, data = M.search(None, 'ALL')
for num in data[0].split():
    typ, data = M.fetch(num, '(RFC822)')
    print('Message %s\n%s\n' % (num, data[0][1]))
M.close()
M.logout()

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 프로토콜과 지원 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 프로토콜과 지원 »

|

nntplib — NNTP protocol client

Source code: Lib/nntplib.py [https://github.com/python/cpython/tree/3.7/Lib/nntplib.py]

This module defines the class NNTP which implements the client side of the Network News Transfer Protocol. It can be used to implement a news reader or poster, or automated news processors. It is compatible with RFC 3977 [https://tools.ietf.org/html/rfc3977.html] as well as the older RFC 977 [https://tools.ietf.org/html/rfc977.html] and RFC 2980 [https://tools.ietf.org/html/rfc2980.html].

Here are two small examples of how it can be used. To list some statistics about a newsgroup and print the subjects of the last 10 articles:

>>> s = nntplib.NNTP('news.gmane.io')
>>> resp, count, first, last, name = s.group('gmane.comp.python.committers')
>>> print('Group', name, 'has', count, 'articles, range', first, 'to', last)
Group gmane.comp.python.committers has 1096 articles, range 1 to 1096
>>> resp, overviews = s.over((last - 9, last))
>>> for id, over in overviews:
...     print(id, nntplib.decode_header(over['subject']))
...
1087 Re: Commit privileges for Łukasz Langa
1088 Re: 3.2 alpha 2 freeze
1089 Re: 3.2 alpha 2 freeze
1090 Re: Commit privileges for Łukasz Langa
1091 Re: Commit privileges for Łukasz Langa
1092 Updated ssh key
1093 Re: Updated ssh key
1094 Re: Updated ssh key
1095 Hello fellow committers!
1096 Re: Hello fellow committers!
>>> s.quit()
'205 Bye!'

To post an article from a binary file (this assumes that the article has valid headers, and that you have right to post on the particular newsgroup):

>>> s = nntplib.NNTP('news.gmane.io')
>>> f = open('article.txt', 'rb')
>>> s.post(f)
'240 Article posted successfully.'
>>> s.quit()
'205 Bye!'

The module itself defines the following classes:

class nntplib.NNTP(host, port=119, user=None, password=None, readermode=None, usenetrc=False[, timeout])

Return a new NNTP object, representing a connection to the NNTP server running on host host, listening at port port. An optional timeout can be specified for the socket connection. If the optional user and password are provided, or if suitable credentials are present in /.netrc and the optional flag usenetrc is true, the AUTHINFO USER and AUTHINFO PASS commands are used to identify and authenticate the user to the server. If the optional flag readermode is true, then a mode reader command is sent before authentication is performed. Reader mode is sometimes necessary if you are connecting to an NNTP server on the local machine and intend to call reader-specific commands, such as group. If you get unexpected NNTPPermanentErrors, you might need to set readermode. The NNTP class supports the with statement to unconditionally consume OSError exceptions and to close the NNTP connection when done, e.g.:

>>> from nntplib import NNTP
>>> with NNTP('news.gmane.io') as n:
...     n.group('gmane.comp.python.committers')
...
('211 1755 1 1755 gmane.comp.python.committers', 1755, 1, 1755, 'gmane.comp.python.committers')
>>>

버전 3.2에서 변경: usenetrc is now False by default.

버전 3.3에서 변경: Support for the with statement was added.

class nntplib.NNTP_SSL(host, port=563, user=None, password=None, ssl_context=None, readermode=None, usenetrc=False[, timeout])

Return a new NNTP_SSL object, representing an encrypted connection to the NNTP server running on host host, listening at port port. NNTP_SSL objects have the same methods as NNTP objects. If port is omitted, port 563 (NNTPS) is used. ssl_context is also optional, and is a SSLContext object. Please read 보안 고려 사항 for best practices. All other parameters behave the same as for NNTP.

Note that SSL-on-563 is discouraged per RFC 4642 [https://tools.ietf.org/html/rfc4642.html], in favor of STARTTLS as described below. However, some servers only support the former.

버전 3.2에 추가.

버전 3.4에서 변경: The class now supports hostname check with ssl.SSLContext.check_hostname and Server Name Indication (see ssl.HAS_SNI).

exception nntplib.NNTPError

Derived from the standard exception Exception, this is the base class for all exceptions raised by the nntplib module. Instances of this class have the following attribute:

response

The response of the server if available, as a str object.

exception nntplib.NNTPReplyError

Exception raised when an unexpected reply is received from the server.

exception nntplib.NNTPTemporaryError

Exception raised when a response code in the range 400–499 is received.

exception nntplib.NNTPPermanentError

Exception raised when a response code in the range 500–599 is received.

exception nntplib.NNTPProtocolError

Exception raised when a reply is received from the server that does not begin with a digit in the range 1–5.

exception nntplib.NNTPDataError

Exception raised when there is some error in the response data.

NNTP Objects

When connected, NNTP and NNTP_SSL objects support the following methods and attributes.

Attributes

NNTP.nntp_version

An integer representing the version of the NNTP protocol supported by the server. In practice, this should be 2 for servers advertising RFC 3977 [https://tools.ietf.org/html/rfc3977.html] compliance and 1 for others.

버전 3.2에 추가.

NNTP.nntp_implementation

A string describing the software name and version of the NNTP server, or None if not advertised by the server.

버전 3.2에 추가.

Methods

The response that is returned as the first item in the return tuple of almost all methods is the server’s response: a string beginning with a three-digit code. If the server’s response indicates an error, the method raises one of the above exceptions.

Many of the following methods take an optional keyword-only argument file. When the file argument is supplied, it must be either a file object opened for binary writing, or the name of an on-disk file to be written to. The method will then write any data returned by the server (except for the response line and the terminating dot) to the file; any list of lines, tuples or objects that the method normally returns will be empty.

버전 3.2에서 변경: Many of the following methods have been reworked and fixed, which makes them incompatible with their 3.1 counterparts.

NNTP.quit()

Send a QUIT command and close the connection. Once this method has been called, no other methods of the NNTP object should be called.

NNTP.getwelcome()

Return the welcome message sent by the server in reply to the initial connection. (This message sometimes contains disclaimers or help information that may be relevant to the user.)

NNTP.getcapabilities()

Return the RFC 3977 [https://tools.ietf.org/html/rfc3977.html] capabilities advertised by the server, as a dict instance mapping capability names to (possibly empty) lists of values. On legacy servers which don’t understand the CAPABILITIES command, an empty dictionary is returned instead.

>>> s = NNTP('news.gmane.io')
>>> 'POST' in s.getcapabilities()
True

버전 3.2에 추가.

NNTP.login(user=None, password=None, usenetrc=True)

Send AUTHINFO commands with the user name and password. If user and password are None and usenetrc is true, credentials from ~/.netrc will be used if possible.

Unless intentionally delayed, login is normally performed during the NNTP object initialization and separately calling this function is unnecessary. To force authentication to be delayed, you must not set user or password when creating the object, and must set usenetrc to False.

버전 3.2에 추가.

NNTP.starttls(context=None)

Send a STARTTLS command. This will enable encryption on the NNTP connection. The context argument is optional and should be a ssl.SSLContext object. Please read 보안 고려 사항 for best practices.

Note that this may not be done after authentication information has been transmitted, and authentication occurs by default if possible during a NNTP object initialization. See NNTP.login() for information on suppressing this behavior.

버전 3.2에 추가.

버전 3.4에서 변경: The method now supports hostname check with ssl.SSLContext.check_hostname and Server Name Indication (see ssl.HAS_SNI).

NNTP.newgroups(date, *, file=None)

Send a NEWGROUPS command. The date argument should be a datetime.date or datetime.datetime object. Return a pair (response, groups) where groups is a list representing the groups that are new since the given date. If file is supplied, though, then groups will be empty.

>>> from datetime import date, timedelta
>>> resp, groups = s.newgroups(date.today() - timedelta(days=3))
>>> len(groups)
85
>>> groups[0]
GroupInfo(group='gmane.network.tor.devel', last='4', first='1', flag='m')

NNTP.newnews(group, date, *, file=None)

Send a NEWNEWS command. Here, group is a group name or '*', and date has the same meaning as for newgroups(). Return a pair (response, articles) where articles is a list of message ids.

This command is frequently disabled by NNTP server administrators.

NNTP.list(group_pattern=None, *, file=None)

Send a LIST or LIST ACTIVE command. Return a pair (response, list) where list is a list of tuples representing all the groups available from this NNTP server, optionally matching the pattern string group_pattern. Each tuple has the form (group, last, first, flag), where group is a group name, last and first are the last and first article numbers, and flag usually takes one of these values:

y: Local postings and articles from peers are allowed.

m: The group is moderated and all postings must be approved.

n: No local postings are allowed, only articles from peers.

j: Articles from peers are filed in the junk group instead.

x: No local postings, and articles from peers are ignored.

=foo.bar: Articles are filed in the foo.bar group instead.

If flag has another value, then the status of the newsgroup should be considered unknown.

This command can return very large results, especially if group_pattern is not specified. It is best to cache the results offline unless you really need to refresh them.

버전 3.2에서 변경: group_pattern was added.

NNTP.descriptions(grouppattern)

Send a LIST NEWSGROUPS command, where grouppattern is a wildmat string as specified in RFC 3977 [https://tools.ietf.org/html/rfc3977.html] (it’s essentially the same as DOS or UNIX shell wildcard strings). Return a pair (response, descriptions), where descriptions is a dictionary mapping group names to textual descriptions.

>>> resp, descs = s.descriptions('gmane.comp.python.*')
>>> len(descs)
295
>>> descs.popitem()
('gmane.comp.python.bio.general', 'BioPython discussion list (Moderated)')

NNTP.description(group)

Get a description for a single group group. If more than one group matches (if ‘group’ is a real wildmat string), return the first match. If no group matches, return an empty string.

This elides the response code from the server. If the response code is needed, use descriptions().

NNTP.group(name)

Send a GROUP command, where name is the group name. The group is selected as the current group, if it exists. Return a tuple (response, count, first, last, name) where count is the (estimated) number of articles in the group, first is the first article number in the group, last is the last article number in the group, and name is the group name.

NNTP.over(message_spec, *, file=None)

Send an OVER command, or an XOVER command on legacy servers. message_spec can be either a string representing a message id, or a (first, last) tuple of numbers indicating a range of articles in the current group, or a (first, None) tuple indicating a range of articles starting from first to the last article in the current group, or None to select the current article in the current group.

Return a pair (response, overviews). overviews is a list of (article_number, overview) tuples, one for each article selected by message_spec. Each overview is a dictionary with the same number of items, but this number depends on the server. These items are either message headers (the key is then the lower-cased header name) or metadata items (the key is then the metadata name prepended with ":"). The following items are guaranteed to be present by the NNTP specification:

the subject, from, date, message-id and references headers

the :bytes metadata: the number of bytes in the entire raw article (including headers and body)

the :lines metadata: the number of lines in the article body

The value of each item is either a string, or None if not present.

It is advisable to use the decode_header() function on header values when they may contain non-ASCII characters:

>>> _, _, first, last, _ = s.group('gmane.comp.python.devel')
>>> resp, overviews = s.over((last, last))
>>> art_num, over = overviews[0]
>>> art_num
117216
>>> list(over.keys())
['xref', 'from', ':lines', ':bytes', 'references', 'date', 'message-id', 'subject']
>>> over['from']
'=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?= <martin@v.loewis.de>'
>>> nntplib.decode_header(over['from'])
'"Martin v. Löwis" <martin@v.loewis.de>'

버전 3.2에 추가.

NNTP.help(*, file=None)

Send a HELP command. Return a pair (response, list) where list is a list of help strings.

NNTP.stat(message_spec=None)

Send a STAT command, where message_spec is either a message id (enclosed in '<' and '>') or an article number in the current group. If message_spec is omitted or None, the current article in the current group is considered. Return a triple (response, number, id) where number is the article number and id is the message id.

>>> _, _, first, last, _ = s.group('gmane.comp.python.devel')
>>> resp, number, message_id = s.stat(first)
>>> number, message_id
(9099, '<20030112190404.GE29873@epoch.metaslash.com>')

NNTP.next()

Send a NEXT command. Return as for stat().

NNTP.last()

Send a LAST command. Return as for stat().

NNTP.article(message_spec=None, *, file=None)

Send an ARTICLE command, where message_spec has the same meaning as for stat(). Return a tuple (response, info) where info is a namedtuple with three attributes number, message_id and lines (in that order). number is the article number in the group (or 0 if the information is not available), message_id the message id as a string, and lines a list of lines (without terminating newlines) comprising the raw message including headers and body.

>>> resp, info = s.article('<20030112190404.GE29873@epoch.metaslash.com>')
>>> info.number
0
>>> info.message_id
'<20030112190404.GE29873@epoch.metaslash.com>'
>>> len(info.lines)
65
>>> info.lines[0]
b'Path: main.gmane.org!not-for-mail'
>>> info.lines[1]
b'From: Neal Norwitz <neal@metaslash.com>'
>>> info.lines[-3:]
[b'There is a patch for 2.3 as well as 2.2.', b'', b'Neal']

NNTP.head(message_spec=None, *, file=None)

Same as article(), but sends a HEAD command. The lines returned (or written to file) will only contain the message headers, not the body.

NNTP.body(message_spec=None, *, file=None)

Same as article(), but sends a BODY command. The lines returned (or written to file) will only contain the message body, not the headers.

NNTP.post(data)

Post an article using the POST command. The data argument is either a file object opened for binary reading, or any iterable of bytes objects (representing raw lines of the article to be posted). It should represent a well-formed news article, including the required headers. The post() method automatically escapes lines beginning with . and appends the termination line.

If the method succeeds, the server’s response is returned. If the server refuses posting, a NNTPReplyError is raised.

NNTP.ihave(message_id, data)

Send an IHAVE command. message_id is the id of the message to send to the server (enclosed in '<' and '>'). The data parameter and the return value are the same as for post().

NNTP.date()

Return a pair (response, date). date is a datetime object containing the current date and time of the server.

NNTP.slave()

Send a SLAVE command. Return the server’s response.

NNTP.set_debuglevel(level)

Set the instance’s debugging level. This controls the amount of debugging output printed. The default, 0, produces no debugging output. A value of 1 produces a moderate amount of debugging output, generally a single line per request or response. A value of 2 or higher produces the maximum amount of debugging output, logging each line sent and received on the connection (including message text).

The following are optional NNTP extensions defined in RFC 2980 [https://tools.ietf.org/html/rfc2980.html]. Some of them have been superseded by newer commands in RFC 3977 [https://tools.ietf.org/html/rfc3977.html].

NNTP.xhdr(hdr, str, *, file=None)

Send an XHDR command. The hdr argument is a header keyword, e.g. 'subject'. The str argument should have the form 'first-last' where first and last are the first and last article numbers to search. Return a pair (response, list), where list is a list of pairs (id, text), where id is an article number (as a string) and text is the text of the requested header for that article. If the file parameter is supplied, then the output of the XHDR command is stored in a file. If file is a string, then the method will open a file with that name, write to it then close it. If file is a file object, then it will start calling write() on it to store the lines of the command output. If file is supplied, then the returned list is an empty list.

NNTP.xover(start, end, *, file=None)

Send an XOVER command. start and end are article numbers delimiting the range of articles to select. The return value is the same of for over(). It is recommended to use over() instead, since it will automatically use the newer OVER command if available.

NNTP.xpath(id)

Return a pair (resp, path), where path is the directory path to the article with message ID id. Most of the time, this extension is not enabled by NNTP server administrators.

버전 3.3부터 폐지: The XPATH extension is not actively used.

Utility functions

The module also defines the following utility function:

nntplib.decode_header(header_str)

Decode a header value, un-escaping any escaped non-ASCII characters. header_str must be a str object. The unescaped value is returned. Using this function is recommended to display some headers in a human readable form:

>>> decode_header("Some subject")
'Some subject'
>>> decode_header("=?ISO-8859-15?Q?D=E9buter_en_Python?=")
'Débuter en Python'
>>> decode_header("Re: =?UTF-8?B?cHJvYmzDqG1lIGRlIG1hdHJpY2U=?=")
'Re: problème de matrice'

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 프로토콜과 지원 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 프로토콜과 지원 »

|

smtplib — SMTP protocol client

Source code: Lib/smtplib.py [https://github.com/python/cpython/tree/3.7/Lib/smtplib.py]

The smtplib module defines an SMTP client session object that can be used to send mail to any Internet machine with an SMTP or ESMTP listener daemon. For details of SMTP and ESMTP operation, consult RFC 821 [https://tools.ietf.org/html/rfc821.html] (Simple Mail Transfer Protocol) and RFC 1869 [https://tools.ietf.org/html/rfc1869.html] (SMTP Service Extensions).

class smtplib.SMTP(host='', port=0, local_hostname=None, [timeout, ]source_address=None)

An SMTP instance encapsulates an SMTP connection. It has methods that support a full repertoire of SMTP and ESMTP operations. If the optional host and port parameters are given, the SMTP connect() method is called with those parameters during initialization. If specified, local_hostname is used as the FQDN of the local host in the HELO/EHLO command. Otherwise, the local hostname is found using socket.getfqdn(). If the connect() call returns anything other than a success code, an SMTPConnectError is raised. The optional timeout parameter specifies a timeout in seconds for blocking operations like the connection attempt (if not specified, the global default timeout setting will be used). If the timeout expires, socket.timeout is raised. The optional source_address parameter allows binding to some specific source address in a machine with multiple network interfaces, and/or to some specific source TCP port. It takes a 2-tuple (host, port), for the socket to bind to as its source address before connecting. If omitted (or if host or port are '' and/or 0 respectively) the OS default behavior will be used.

For normal use, you should only require the initialization/connect, sendmail(), and SMTP.quit() methods. An example is included below.

The SMTP class supports the with statement. When used like this, the SMTP QUIT command is issued automatically when the with statement exits. E.g.:

>>> from smtplib import SMTP
>>> with SMTP("domain.org") as smtp:
...     smtp.noop()
...
(250, b'Ok')
>>>

버전 3.3에서 변경: Support for the with statement was added.

버전 3.3에서 변경: source_address argument was added.

버전 3.5에 추가: The SMTPUTF8 extension (RFC 6531 [https://tools.ietf.org/html/rfc6531.html]) is now supported.

class smtplib.SMTP_SSL(host='', port=0, local_hostname=None, keyfile=None, certfile=None, [timeout, ]context=None, source_address=None)

An SMTP_SSL instance behaves exactly the same as instances of SMTP. SMTP_SSL should be used for situations where SSL is required from the beginning of the connection and using starttls() is not appropriate. If host is not specified, the local host is used. If port is zero, the standard SMTP-over-SSL port (465) is used. The optional arguments local_hostname, timeout and source_address have the same meaning as they do in the SMTP class. context, also optional, can contain a SSLContext and allows configuring various aspects of the secure connection. Please read 보안 고려 사항 for best practices.

keyfile and certfile are a legacy alternative to context, and can point to a PEM formatted private key and certificate chain file for the SSL connection.

버전 3.3에서 변경: context was added.

버전 3.3에서 변경: source_address argument was added.

버전 3.4에서 변경: The class now supports hostname check with ssl.SSLContext.check_hostname and Server Name Indication (see ssl.HAS_SNI).

버전 3.6부터 폐지: keyfile and certfile are deprecated in favor of context. Please use ssl.SSLContext.load_cert_chain() instead, or let ssl.create_default_context() select the system’s trusted CA certificates for you.

class smtplib.LMTP(host='', port=LMTP_PORT, local_hostname=None, source_address=None)

The LMTP protocol, which is very similar to ESMTP, is heavily based on the standard SMTP client. It’s common to use Unix sockets for LMTP, so our connect() method must support that as well as a regular host:port server. The optional arguments local_hostname and source_address have the same meaning as they do in the SMTP class. To specify a Unix socket, you must use an absolute path for host, starting with a ‘/’.

Authentication is supported, using the regular SMTP mechanism. When using a Unix socket, LMTP generally don’t support or require any authentication, but your mileage might vary.

A nice selection of exceptions is defined as well:

exception smtplib.SMTPException

Subclass of OSError that is the base exception class for all the other exceptions provided by this module.

버전 3.4에서 변경: SMTPException became subclass of OSError

exception smtplib.SMTPServerDisconnected

This exception is raised when the server unexpectedly disconnects, or when an attempt is made to use the SMTP instance before connecting it to a server.

exception smtplib.SMTPResponseException

Base class for all exceptions that include an SMTP error code. These exceptions are generated in some instances when the SMTP server returns an error code. The error code is stored in the smtp_code attribute of the error, and the smtp_error attribute is set to the error message.

exception smtplib.SMTPSenderRefused

Sender address refused. In addition to the attributes set by on all SMTPResponseException exceptions, this sets ‘sender’ to the string that the SMTP server refused.

exception smtplib.SMTPRecipientsRefused

All recipient addresses refused. The errors for each recipient are accessible through the attribute recipients, which is a dictionary of exactly the same sort as SMTP.sendmail() returns.

exception smtplib.SMTPDataError

The SMTP server refused to accept the message data.

exception smtplib.SMTPConnectError

Error occurred during establishment of a connection with the server.

exception smtplib.SMTPHeloError

The server refused our HELO message.

exception smtplib.SMTPNotSupportedError

The command or option attempted is not supported by the server.

버전 3.5에 추가.

exception smtplib.SMTPAuthenticationError

SMTP authentication went wrong. Most probably the server didn’t accept the username/password combination provided.

더 보기

RFC 821 [https://tools.ietf.org/html/rfc821.html] - Simple Mail Transfer Protocol

Protocol definition for SMTP. This document covers the model, operating procedure, and protocol details for SMTP.

RFC 1869 [https://tools.ietf.org/html/rfc1869.html] - SMTP Service Extensions

Definition of the ESMTP extensions for SMTP. This describes a framework for extending SMTP with new commands, supporting dynamic discovery of the commands provided by the server, and defines a few additional commands.

SMTP Objects

An SMTP instance has the following methods:

SMTP.set_debuglevel(level)

Set the debug output level. A value of 1 or True for level results in debug messages for connection and for all messages sent to and received from the server. A value of 2 for level results in these messages being timestamped.

버전 3.5에서 변경: Added debuglevel 2.

SMTP.docmd(cmd, args='')

Send a command cmd to the server. The optional argument args is simply concatenated to the command, separated by a space.

This returns a 2-tuple composed of a numeric response code and the actual response line (multiline responses are joined into one long line.)

In normal operation it should not be necessary to call this method explicitly. It is used to implement other methods and may be useful for testing private extensions.

If the connection to the server is lost while waiting for the reply, SMTPServerDisconnected will be raised.

SMTP.connect(host='localhost', port=0)

Connect to a host on a given port. The defaults are to connect to the local host at the standard SMTP port (25). If the hostname ends with a colon (':') followed by a number, that suffix will be stripped off and the number interpreted as the port number to use. This method is automatically invoked by the constructor if a host is specified during instantiation. Returns a 2-tuple of the response code and message sent by the server in its connection response.

SMTP.helo(name='')

Identify yourself to the SMTP server using HELO. The hostname argument defaults to the fully qualified domain name of the local host. The message returned by the server is stored as the helo_resp attribute of the object.

In normal operation it should not be necessary to call this method explicitly. It will be implicitly called by the sendmail() when necessary.

SMTP.ehlo(name='')

Identify yourself to an ESMTP server using EHLO. The hostname argument defaults to the fully qualified domain name of the local host. Examine the response for ESMTP option and store them for use by has_extn(). Also sets several informational attributes: the message returned by the server is stored as the ehlo_resp attribute, does_esmtp is set to true or false depending on whether the server supports ESMTP, and esmtp_features will be a dictionary containing the names of the SMTP service extensions this server supports, and their parameters (if any).

Unless you wish to use has_extn() before sending mail, it should not be necessary to call this method explicitly. It will be implicitly called by sendmail() when necessary.

SMTP.ehlo_or_helo_if_needed()

This method calls ehlo() and/or helo() if there has been no previous EHLO or HELO command this session. It tries ESMTP EHLO first.

SMTPHeloError

The server didn’t reply properly to the HELO greeting.

SMTP.has_extn(name)

Return True if name is in the set of SMTP service extensions returned by the server, False otherwise. Case is ignored.

SMTP.verify(address)

Check the validity of an address on this server using SMTP VRFY. Returns a tuple consisting of code 250 and a full RFC 822 [https://tools.ietf.org/html/rfc822.html] address (including human name) if the user address is valid. Otherwise returns an SMTP error code of 400 or greater and an error string.

참고

Many sites disable SMTP VRFY in order to foil spammers.

SMTP.login(user, password, *, initial_response_ok=True)

Log in on an SMTP server that requires authentication. The arguments are the username and the password to authenticate with. If there has been no previous EHLO or HELO command this session, this method tries ESMTP EHLO first. This method will return normally if the authentication was successful, or may raise the following exceptions:

SMTPHeloError

The server didn’t reply properly to the HELO greeting.

SMTPAuthenticationError

The server didn’t accept the username/password combination.

SMTPNotSupportedError

The AUTH command is not supported by the server.

SMTPException

No suitable authentication method was found.

Each of the authentication methods supported by smtplib are tried in turn if they are advertised as supported by the server. See auth() for a list of supported authentication methods. initial_response_ok is passed through to auth().

Optional keyword argument initial_response_ok specifies whether, for authentication methods that support it, an “initial response” as specified in RFC 4954 [https://tools.ietf.org/html/rfc4954.html] can be sent along with the AUTH command, rather than requiring a challenge/response.

버전 3.5에서 변경: SMTPNotSupportedError may be raised, and the initial_response_ok parameter was added.

SMTP.auth(mechanism, authobject, *, initial_response_ok=True)

Issue an SMTP AUTH command for the specified authentication mechanism, and handle the challenge response via authobject.

mechanism specifies which authentication mechanism is to be used as argument to the AUTH command; the valid values are those listed in the auth element of esmtp_features.

authobject must be a callable object taking an optional single argument:

data = authobject(challenge=None)

If optional keyword argument initial_response_ok is true, authobject() will be called first with no argument. It can return the RFC 4954 [https://tools.ietf.org/html/rfc4954.html] “initial response” ASCII str which will be encoded and sent with the AUTH command as below. If the authobject() does not support an initial response (e.g. because it requires a challenge), it should return None when called with challenge=None. If initial_response_ok is false, then authobject() will not be called first with None.

If the initial response check returns None, or if initial_response_ok is false, authobject() will be called to process the server’s challenge response; the challenge argument it is passed will be a bytes. It should return ASCII str data that will be base64 encoded and sent to the server.

The SMTP class provides authobjects for the CRAM-MD5, PLAIN, and LOGIN mechanisms; they are named SMTP.auth_cram_md5, SMTP.auth_plain, and SMTP.auth_login respectively. They all require that the user and password properties of the SMTP instance are set to appropriate values.

User code does not normally need to call auth directly, but can instead call the login() method, which will try each of the above mechanisms in turn, in the order listed. auth is exposed to facilitate the implementation of authentication methods not (or not yet) supported directly by smtplib.

버전 3.5에 추가.

SMTP.starttls(keyfile=None, certfile=None, context=None)

Put the SMTP connection in TLS (Transport Layer Security) mode. All SMTP commands that follow will be encrypted. You should then call ehlo() again.

If keyfile and certfile are provided, they are used to create an ssl.SSLContext.

Optional context parameter is an ssl.SSLContext object; This is an alternative to using a keyfile and a certfile and if specified both keyfile and certfile should be None.

If there has been no previous EHLO or HELO command this session, this method tries ESMTP EHLO first.

버전 3.6부터 폐지: keyfile and certfile are deprecated in favor of context. Please use ssl.SSLContext.load_cert_chain() instead, or let ssl.create_default_context() select the system’s trusted CA certificates for you.

SMTPHeloError

The server didn’t reply properly to the HELO greeting.

SMTPNotSupportedError

The server does not support the STARTTLS extension.

RuntimeError

SSL/TLS support is not available to your Python interpreter.

버전 3.3에서 변경: context was added.

버전 3.4에서 변경: The method now supports hostname check with SSLContext.check_hostname and Server Name Indicator (see HAS_SNI).

버전 3.5에서 변경: The error raised for lack of STARTTLS support is now the SMTPNotSupportedError subclass instead of the base SMTPException.

SMTP.sendmail(from_addr, to_addrs, msg, mail_options=(), rcpt_options=())

Send mail. The required arguments are an RFC 822 [https://tools.ietf.org/html/rfc822.html] from-address string, a list of RFC 822 [https://tools.ietf.org/html/rfc822.html] to-address strings (a bare string will be treated as a list with 1 address), and a message string. The caller may pass a list of ESMTP options (such as 8bitmime) to be used in MAIL FROM commands as mail_options. ESMTP options (such as DSN commands) that should be used with all RCPT commands can be passed as rcpt_options. (If you need to use different ESMTP options to different recipients you have to use the low-level methods such as mail(), rcpt() and data() to send the message.)

참고

The from_addr and to_addrs parameters are used to construct the message envelope used by the transport agents. sendmail does not modify the message headers in any way.

msg may be a string containing characters in the ASCII range, or a byte string. A string is encoded to bytes using the ascii codec, and lone \r and \n characters are converted to \r\n characters. A byte string is not modified.

If there has been no previous EHLO or HELO command this session, this method tries ESMTP EHLO first. If the server does ESMTP, message size and each of the specified options will be passed to it (if the option is in the feature set the server advertises). If EHLO fails, HELO will be tried and ESMTP options suppressed.

This method will return normally if the mail is accepted for at least one recipient. Otherwise it will raise an exception. That is, if this method does not raise an exception, then someone should get your mail. If this method does not raise an exception, it returns a dictionary, with one entry for each recipient that was refused. Each entry contains a tuple of the SMTP error code and the accompanying error message sent by the server.

If SMTPUTF8 is included in mail_options, and the server supports it, from_addr and to_addrs may contain non-ASCII characters.

This method may raise the following exceptions:

SMTPRecipientsRefused

All recipients were refused. Nobody got the mail. The recipients attribute of the exception object is a dictionary with information about the refused recipients (like the one returned when at least one recipient was accepted).

SMTPHeloError

The server didn’t reply properly to the HELO greeting.

SMTPSenderRefused

The server didn’t accept the from_addr.

SMTPDataError

The server replied with an unexpected error code (other than a refusal of a recipient).

SMTPNotSupportedError

SMTPUTF8 was given in the mail_options but is not supported by the server.

Unless otherwise noted, the connection will be open even after an exception is raised.

버전 3.2에서 변경: msg may be a byte string.

버전 3.5에서 변경: SMTPUTF8 support added, and SMTPNotSupportedError may be raised if SMTPUTF8 is specified but the server does not support it.

SMTP.send_message(msg, from_addr=None, to_addrs=None, mail_options=(), rcpt_options=())

This is a convenience method for calling sendmail() with the message represented by an email.message.Message object. The arguments have the same meaning as for sendmail(), except that msg is a Message object.

If from_addr is None or to_addrs is None, send_message fills those arguments with addresses extracted from the headers of msg as specified in RFC 5322 [https://tools.ietf.org/html/rfc5322.html]: from_addr is set to the Sender field if it is present, and otherwise to the From field. to_addrs combines the values (if any) of the To, Cc, and Bcc fields from msg. If exactly one set of Resent-* headers appear in the message, the regular headers are ignored and the Resent-* headers are used instead. If the message contains more than one set of Resent-* headers, a ValueError is raised, since there is no way to unambiguously detect the most recent set of Resent- headers.

send_message serializes msg using BytesGenerator with \r\n as the linesep, and calls sendmail() to transmit the resulting message. Regardless of the values of from_addr and to_addrs, send_message does not transmit any Bcc or Resent-Bcc headers that may appear in msg. If any of the addresses in from_addr and to_addrs contain non-ASCII characters and the server does not advertise SMTPUTF8 support, an SMTPNotSupported error is raised. Otherwise the Message is serialized with a clone of its policy with the utf8 attribute set to True, and SMTPUTF8 and BODY=8BITMIME are added to mail_options.

버전 3.2에 추가.

버전 3.5에 추가: Support for internationalized addresses (SMTPUTF8).

SMTP.quit()

Terminate the SMTP session and close the connection. Return the result of the SMTP QUIT command.

Low-level methods corresponding to the standard SMTP/ESMTP commands HELP, RSET, NOOP, MAIL, RCPT, and DATA are also supported. Normally these do not need to be called directly, so they are not documented here. For details, consult the module code.

SMTP Example

This example prompts the user for addresses needed in the message envelope (‘To’ and ‘From’ addresses), and the message to be delivered. Note that the headers to be included with the message must be included in the message as entered; this example doesn’t do any processing of the RFC 822 [https://tools.ietf.org/html/rfc822.html] headers. In particular, the ‘To’ and ‘From’ addresses must be included in the message headers explicitly.

import smtplib

def prompt(prompt):
    return input(prompt).strip()

fromaddr = prompt("From: ")
toaddrs  = prompt("To: ").split()
print("Enter message, end with ^D (Unix) or ^Z (Windows):")

# Add the From: and To: headers at the start!
msg = ("From: %s\r\nTo: %s\r\n\r\n"
       % (fromaddr, ", ".join(toaddrs)))
while True:
    try:
        line = input()
    except EOFError:
        break
    if not line:
        break
    msg = msg + line

print("Message length is", len(msg))

server = smtplib.SMTP('localhost')
server.set_debuglevel(1)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()

참고

In general, you will want to use the email package’s features to construct an email message, which you can then send via send_message(); see email: 예제.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 프로토콜과 지원 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 프로토콜과 지원 »

|

smtpd — SMTP Server

Source code: Lib/smtpd.py [https://github.com/python/cpython/tree/3.7/Lib/smtpd.py]

This module offers several classes to implement SMTP (email) servers.

더 보기

The aiosmtpd [http://aiosmtpd.readthedocs.io/] package is a recommended replacement for this module. It is based on asyncio and provides a more straightforward API. smtpd should be considered deprecated.

Several server implementations are present; one is a generic do-nothing implementation, which can be overridden, while the other two offer specific mail-sending strategies.

Additionally the SMTPChannel may be extended to implement very specific interaction behaviour with SMTP clients.

The code supports RFC 5321 [https://tools.ietf.org/html/rfc5321.html], plus the RFC 1870 [https://tools.ietf.org/html/rfc1870.html] SIZE and RFC 6531 [https://tools.ietf.org/html/rfc6531.html] SMTPUTF8 extensions.

SMTPServer Objects

class smtpd.SMTPServer(localaddr, remoteaddr, data_size_limit=33554432, map=None, enable_SMTPUTF8=False, decode_data=False)

Create a new SMTPServer object, which binds to local address localaddr. It will treat remoteaddr as an upstream SMTP relayer. Both localaddr and remoteaddr should be a (host, port) tuple. The object inherits from asyncore.dispatcher, and so will insert itself into asyncore’s event loop on instantiation.

data_size_limit specifies the maximum number of bytes that will be accepted in a DATA command. A value of None or 0 means no limit.

map is the socket map to use for connections (an initially empty dictionary is a suitable value). If not specified the asyncore global socket map is used.

enable_SMTPUTF8 determines whether the SMTPUTF8 extension (as defined in RFC 6531 [https://tools.ietf.org/html/rfc6531.html]) should be enabled. The default is False. When True, SMTPUTF8 is accepted as a parameter to the MAIL command and when present is passed to process_message() in the kwargs['mail_options'] list. decode_data and enable_SMTPUTF8 cannot be set to True at the same time.

decode_data specifies whether the data portion of the SMTP transaction should be decoded using UTF-8. When decode_data is False (the default), the server advertises the 8BITMIME extension (RFC 6152 [https://tools.ietf.org/html/rfc6152.html]), accepts the BODY=8BITMIME parameter to the MAIL command, and when present passes it to process_message() in the kwargs['mail_options'] list. decode_data and enable_SMTPUTF8 cannot be set to True at the same time.

process_message(peer, mailfrom, rcpttos, data, **kwargs)

Raise a NotImplementedError exception. Override this in subclasses to do something useful with this message. Whatever was passed in the constructor as remoteaddr will be available as the _remoteaddr attribute. peer is the remote host’s address, mailfrom is the envelope originator, rcpttos are the envelope recipients and data is a string containing the contents of the e-mail (which should be in RFC 5321 [https://tools.ietf.org/html/rfc5321.html] format).

If the decode_data constructor keyword is set to True, the data argument will be a unicode string. If it is set to False, it will be a bytes object.

kwargs is a dictionary containing additional information. It is empty if decode_data=True was given as an init argument, otherwise it contains the following keys:

mail_options:

a list of all received parameters to the MAIL command (the elements are uppercase strings; example: ['BODY=8BITMIME', 'SMTPUTF8']).

rcpt_options:

same as mail_options but for the RCPT command. Currently no RCPT TO options are supported, so for now this will always be an empty list.

Implementations of process_message should use the **kwargs signature to accept arbitrary keyword arguments, since future feature enhancements may add keys to the kwargs dictionary.

Return None to request a normal 250 Ok response; otherwise return the desired response string in RFC 5321 [https://tools.ietf.org/html/rfc5321.html] format.

channel_class

Override this in subclasses to use a custom SMTPChannel for managing SMTP clients.

버전 3.4에 추가: The map constructor argument.

버전 3.5에서 변경: localaddr and remoteaddr may now contain IPv6 addresses.

버전 3.5에 추가: The decode_data and enable_SMTPUTF8 constructor parameters, and the kwargs parameter to process_message() when decode_data is False.

버전 3.6에서 변경: decode_data is now False by default.

DebuggingServer Objects

class smtpd.DebuggingServer(localaddr, remoteaddr)

Create a new debugging server. Arguments are as per SMTPServer. Messages will be discarded, and printed on stdout.

PureProxy Objects

class smtpd.PureProxy(localaddr, remoteaddr)

Create a new pure proxy server. Arguments are as per SMTPServer. Everything will be relayed to remoteaddr. Note that running this has a good chance to make you into an open relay, so please be careful.

MailmanProxy Objects

class smtpd.MailmanProxy(localaddr, remoteaddr)

Create a new pure proxy server. Arguments are as per SMTPServer. Everything will be relayed to remoteaddr, unless local mailman configurations knows about an address, in which case it will be handled via mailman. Note that running this has a good chance to make you into an open relay, so please be careful.

SMTPChannel Objects

class smtpd.SMTPChannel(server, conn, addr, data_size_limit=33554432, map=None, enable_SMTPUTF8=False, decode_data=False)

Create a new SMTPChannel object which manages the communication between the server and a single SMTP client.

conn and addr are as per the instance variables described below.

data_size_limit specifies the maximum number of bytes that will be accepted in a DATA command. A value of None or 0 means no limit.

enable_SMTPUTF8 determines whether the SMTPUTF8 extension (as defined in RFC 6531 [https://tools.ietf.org/html/rfc6531.html]) should be enabled. The default is False. decode_data and enable_SMTPUTF8 cannot be set to True at the same time.

A dictionary can be specified in map to avoid using a global socket map.

decode_data specifies whether the data portion of the SMTP transaction should be decoded using UTF-8. The default is False. decode_data and enable_SMTPUTF8 cannot be set to True at the same time.

To use a custom SMTPChannel implementation you need to override the SMTPServer.channel_class of your SMTPServer.

버전 3.5에서 변경: The decode_data and enable_SMTPUTF8 parameters were added.

버전 3.6에서 변경: decode_data is now False by default.

The SMTPChannel has the following instance variables:

smtp_server

Holds the SMTPServer that spawned this channel.

conn

Holds the socket object connecting to the client.

addr

Holds the address of the client, the second value returned by socket.accept

received_lines

Holds a list of the line strings (decoded using UTF-8) received from the client. The lines have their "\r\n" line ending translated to "\n".

smtp_state

Holds the current state of the channel. This will be either COMMAND initially and then DATA after the client sends a “DATA” line.

seen_greeting

Holds a string containing the greeting sent by the client in its “HELO”.

mailfrom

Holds a string containing the address identified in the “MAIL FROM:” line from the client.

rcpttos

Holds a list of strings containing the addresses identified in the “RCPT TO:” lines from the client.

received_data

Holds a string containing all of the data sent by the client during the DATA state, up to but not including the terminating "\r\n.\r\n".

fqdn

Holds the fully-qualified domain name of the server as returned by socket.getfqdn().

peer

Holds the name of the client peer as returned by conn.getpeername() where conn is conn.

The SMTPChannel operates by invoking methods named smtp_<command> upon reception of a command line from the client. Built into the base SMTPChannel class are methods for handling the following commands (and responding to them appropriately):

Command

Action taken

HELO

Accepts the greeting from the client and stores it in seen_greeting. Sets server to base command mode.

EHLO

Accepts the greeting from the client and stores it in seen_greeting. Sets server to extended command mode.

NOOP

Takes no action.

QUIT

Closes the connection cleanly.

MAIL

Accepts the “MAIL FROM:” syntax and stores the supplied address as mailfrom. In extended command mode, accepts the RFC 1870 [https://tools.ietf.org/html/rfc1870.html] SIZE attribute and responds appropriately based on the value of data_size_limit.

RCPT

Accepts the “RCPT TO:” syntax and stores the supplied addresses in the rcpttos list.

RSET

Resets the mailfrom, rcpttos, and received_data, but not the greeting.

DATA

Sets the internal state to DATA and stores remaining lines from the client in received_data until the terminator "\r\n.\r\n" is received.

HELP

Returns minimal information on command syntax

VRFY

Returns code 252 (the server doesn’t know if the address is valid)

EXPN

Reports that the command is not implemented.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 프로토콜과 지원 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 프로토콜과 지원 »

|

telnetlib — 텔넷 클라이언트

소스 코드: Lib/telnetlib.py [https://github.com/python/cpython/tree/3.7/Lib/telnetlib.py]

telnetlib 모듈은 텔넷 프로토콜을 구현하는 Telnet 클래스를 제공합니다. 프로토콜에 대한 자세한 내용은 RFC 854 [https://tools.ietf.org/html/rfc854.html]를 참조하십시오. 또한, 프로토콜 문자(아래를 보십시오)와 텔넷 옵션을 위한 기호 상수를 제공합니다. 텔넷 옵션의 기호 이름은 arpa/telnet.h의 정의를 따르며, 선행 TELOPT_는 제거됩니다. 전통적으로 arpa/telnet.h에 포함되지 않는 옵션의 기호 이름에 대해서는 모듈 소스 자체를 참조하십시오.

텔넷 명령을 위한 기호 상수는 다음과 같습니다: IAC, DONT, DO, WONT, WILL, SE (Subnegotiation End), NOP (No Operation), DM (Data Mark), BRK (Break), IP (Interrupt process), AO (Abort output), AYT (Are You There), EC (Erase Character), EL (Erase Line), GA (Go Ahead), SB (Subnegotiation Begin).

class telnetlib.Telnet(host=None, port=0[, timeout])

Telnet represents a connection to a Telnet server. The instance is initially not connected by default; the open() method must be used to establish a connection. Alternatively, the host name and optional port number can be passed to the constructor too, in which case the connection to the server will be established before the constructor returns. The optional timeout parameter specifies a timeout in seconds for blocking operations like the connection attempt (if not specified, the global default timeout setting will be used).

이미 연결된 인스턴스를 다시 열지 마십시오.

이 클래스에는 많은 read_*() 메서드가 있습니다. 이들 중 일부는 연결의 끝을 읽을 때 EOFError를 발생시킴에 유의하십시오. 다른 이유로 빈 문자열을 반환할 수 있기 때문입니다. 아래의 개별 설명을 참조하십시오.

Telnet 객체는 컨텍스트 관리자이며 with 문에서 사용할 수 있습니다. with 블록이 끝날 때, close() 메서드가 호출됩니다:

>>> from telnetlib import Telnet
>>> with Telnet('localhost', 23) as tn:
...     tn.interact()
...

버전 3.6에서 변경: 컨텍스트 관리자 지원을 추가했습니다

더 보기

RFC 854 [https://tools.ietf.org/html/rfc854.html] - Telnet Protocol Specification

텔넷 프로토콜의 정의.

텔넷 객체

Telnet 인스턴스에는 다음과 같은 메서드가 있습니다.:

Telnet.read_until(expected, timeout=None)

주어진 바이트열 expected를 만나거나 timeout 초가 경과 할 때까지 읽습니다.

일치하는 것을 찾을 수 없으면, 사용 가능한 것을 대신 반환합니다. 빈 바이트열도 가능합니다. 연결이 닫혀 있고 사용할 수 있는 요리된 데이터가 없으면 EOFError를 발생시킵니다.

Telnet.read_all()

EOF까지 모든 데이터를 바이트열로 읽습니다; 연결이 닫힐 때까지 블록합니다.

Telnet.read_some()

EOF를 만나지 않으면 적어도 1바이트의 요리된 데이터를 읽습니다. EOF를 만나면 b''를 반환합니다. 즉시 사용할 수 있는 데이터가 없으면 블록합니다.

Telnet.read_very_eager()

I/O에서 블록하지 않고 읽을 수 있는 모든 것을 읽습니다 (eager).

연결이 닫혀 있고 사용할 수 있는 요리된 데이터가 없으면 EOFError를 발생시킵니다. 그렇지 않고 사용할 수 있는 요리된 데이터가 없으면 b''를 반환합니다. IAC 시퀀스의 중간에 있지 않으면 블록하지 않습니다.

Telnet.read_eager()

쉽게 사용할 수 있는 데이터를 읽습니다.

연결이 닫혀 있고 사용할 수 있는 요리된 데이터가 없으면 EOFError를 발생시킵니다. 그렇지 않고 사용할 수 있는 요리된 데이터가 없으면 b''를 반환합니다. IAC 시퀀스의 중간에 있지 않으면 블록하지 않습니다.

Telnet.read_lazy()

이미 큐에 있는 데이터를 처리하고 반환합니다 (lazy).

연결이 닫혀 있고 사용할 수 있는 데이터가 없으면 EOFError를 발생시킵니다. 그렇지 않고 사용할 수 있는 요리된 데이터가 없으면 b''를 반환합니다. IAC 시퀀스의 중간에 있지 않으면 블록하지 않습니다.

Telnet.read_very_lazy()

요리된 큐에 있는 모든 데이터를 반환합니다 (very lazy).

연결이 닫혀 있고 사용할 수 있는 데이터가 없으면 EOFError를 발생시킵니다. 그렇지 않고 사용할 수 있는 요리된 데이터가 없으면 b''를 반환합니다. 이 메서드는 절대 블록하지 않습니다.

Telnet.read_sb_data()

SB/SE 쌍(suboption begin/end)간에 수집된 데이터를 반환합니다. SE 명령으로 호출되었을 때 콜백은 이 데이터에 액세스해야 합니다. 이 방법은 절대 블록하지 않습니다.

Telnet.open(host, port=0[, timeout])

호스트에 연결합니다. 선택적 두 번째 인자는 포트 번호이며, 기본값은 표준 텔넷 포트(23)입니다. 선택적 timeout 매개 변수는 연결 시도와 같은 블로킹 연산에 대한 시간제한을 초로 지정합니다 (지정하지 않으면, 전역 기본 시간제한 설정이 사용됩니다).

이미 연결된 인스턴스를 다시 열려고 하지 마십시오.

Telnet.msg(msg, *args)

디버그 수준이 > 0 일 때 디버그 메시지를 인쇄합니다. 추가 인자가 있으면, 표준 문자열 포매팅 연산자를 사용하여 메시지에 치환됩니다.

Telnet.set_debuglevel(debuglevel)

디버그 수준을 설정합니다. debuglevel의 값이 클수록, 더 많은 디버그 출력을 얻을 수 있습니다 (sys.stdout으로).

Telnet.close()

연결을 닫습니다.

Telnet.get_socket()

내부적으로 사용되는 소켓 객체를 반환합니다.

Telnet.fileno()

내부적으로 사용되는 소켓 객체의 파일 기술자를 반환합니다.

Telnet.write(buffer)

IAC 문자를 중복(doubling)해서 소켓에 바이트열을 기록합니다. 연결이 블록 되면 블록 할 수 있습니다. 연결이 닫히면 OSError가 발생할 수 있습니다.

버전 3.3에서 변경: 이 메서드는 방법은 socket.error를 발생시켰습니다. 이제는 OSError의 별칭입니다.

Telnet.interact()

상호 작용 함수, 매우 단순한 텔넷 클라이언트를 에뮬레이션합니다.

Telnet.mt_interact()

interact()의 다중 스레드 버전.

Telnet.expect(list, timeout=None)

정규식 리스트 중 하나가 일치할 때까지 읽습니다.

첫 번째 인자는 컴파일되었거나 (정규식 객체) 컴파일되지 않은 (바이트열) 정규식의 리스트입니다. 선택적 두 번째 인자는 초 단위의 시간제한입니다; 기본값은 무기한 블록 하는 것입니다.

세 항목의 튜플을 반환합니다: 일치하는 첫 번째 정규식의 리스트 인덱스; 반환된 일치 객체; 그리고 일치를 포함해서 그때까지 읽은 바이트열.

파일의 끝이 발견되고 아무런 바이트도 읽히지 않았으면, EOFError를 발생시킵니다. 그렇지 않으면, 아무것도 일치하지 않을 때, (-1, None, data)를 반환합니다. 여기서 data는 지금까지 받은 바이트열입니다 (시간 초과가 발생하면 빈 바이트열일 수 있습니다).

정규식이 탐욕적인 일치(가령 .*)로 끝나거나 둘 이상의 정규식이 같은 입력과 일치 할 수 있으면, 결과는 비결정적이며, I/O 타이밍에 따라 달라질 수 있습니다.

Telnet.set_option_negotiation_callback(callback)

입력 흐름에서 텔넷 옵션을 읽을 때마다, 이 callback(설정되었다면)은 다음과 같은 매개 변수로 호출됩니다: callback(telnet socket, command (DO/DONT/WILL/WONT), option). telnetlib은 나중에 다른 작업을 수행하지 않습니다.

텔넷 예제

일반적인 사용을 보여주는 간단한 예제:

import getpass
import telnetlib

HOST = "localhost"
user = input("Enter your remote account: ")
password = getpass.getpass()

tn = telnetlib.Telnet(HOST)

tn.read_until(b"login: ")
tn.write(user.encode('ascii') + b"\n")
if password:
    tn.read_until(b"Password: ")
    tn.write(password.encode('ascii') + b"\n")

tn.write(b"ls\n")
tn.write(b"exit\n")

print(tn.read_all().decode('ascii'))

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 프로토콜과 지원 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 프로토콜과 지원 »

|

uuid — RFC 4122 [https://tools.ietf.org/html/rfc4122.html] 에 따른 UUID 객체

소스 코드: Lib/uuid.py [https://github.com/python/cpython/tree/3.7/Lib/uuid.py]

이 모듈은 RFC 4122 [https://tools.ietf.org/html/rfc4122.html]에서 명시한 버전 1, 3, 4 및 5의 UUID를 생성하기 위해 불변 UUID 객체(UUID 클래스)와 uuid1(), uuid3(), uuid4(), uuid5()를 제공합니다.

고유 ID만을 얻고자 한다면 uuid1() 또는 uuid4()를 호출하는 것이 좋습니다. uuid1() 함수는 컴퓨터의 네트워크 주소를 포함하여 UUID를 생성하므로 개인정보가 노출될 수 있음을 명심해야 합니다. uuid4()는 무작위 UUID를 생성합니다.

기본 플랫폼의 지원 여부에 따라, uuid1()은 “안전한” UUID를 반환하거나 그렇지 않을 수도 있습니다. 안전한 UUID는 두 프로세스가 같은 UUID를 얻지 못하게 하는 동기화 메서드에 의해 생성됩니다. UUID의 모든 인스턴스는 UUID의 안정성에 대한 정보를 중계하는 is_safe 어트리뷰트가 있고, 다음의 열거체를 사용합니다.

class uuid.SafeUUID

버전 3.7에 추가.

safe

플랫폼이 다중 프로세스에 안전한 방식으로 UUID를 생성합니다.

unsafe

다중 프로세스에 안전한 방식으로 생성되지 않습니다.

unknown

플랫폼이 UUID를 안전하게 생성하였는지에 대한 정보를 제공하지 않습니다.

class uuid.UUID(hex=None, bytes=None, bytes_le=None, fields=None, int=None, version=None, *, is_safe=SafeUUID.unknown)

32자리 16진수 문자열, bytes 인자에 빅 엔디안 순서 16바이트열, bytes_le 인자에 리틀 엔디안 순서 16바이트열, fields 인자에 여섯 개의 정수로 이루어진 튜플(32-bit time_low, 16-bit time_mid, 16-bit time_hi_version, 8-bit clock_seq_hi_variant, 8-bit clock_seq_low, 48-bit node), int 인자에 단일 128bit 정수 중 하나를 이용하여 UUID를 만듭니다. 16진수 문자열로 주어졌을 경우 중괄호, 붙임표(hyphen), URN 접두어는 모두 선택사항입니다. 예를 들어, 아래 표현들은 모두 같은 UUID를 산출합니다:

UUID('{12345678-1234-5678-1234-567812345678}')
UUID('12345678123456781234567812345678')
UUID('urn:uuid:12345678-1234-5678-1234-567812345678')
UUID(bytes=b'\x12\x34\x56\x78'*4)
UUID(bytes_le=b'\x78\x56\x34\x12\x34\x12\x78\x56' +
              b'\x12\x34\x56\x78\x12\x34\x56\x78')
UUID(fields=(0x12345678, 0x1234, 0x5678, 0x12, 0x34, 0x567812345678))
UUID(int=0x12345678123456781234567812345678)

hex, bytes, bytes_le, fields, int 중 하나는 반드시 주어져야 합니다. version 인자는 선택사항입니다; 인자로 주어질 경우, 결과로 생성된 UUID는 RFC 4122 [https://tools.ietf.org/html/rfc4122.html]에 따라 변종 및 버전 번호를 설정하고 주어진 hex, bytes, bytes_le, fields, int 비트를 오버라이딩 합니다.

UUID 객체끼리 비교할 때 UUID.int 어트리뷰트를 비교하여 수행합니다. UUID가 아닌 객체와 비교하면 TypeError가 발생합니다.

str(uuid)는 12345678-1234-5678-1234-567812345678과같이 32자리 16진수 UUID로 표현합니다.

UUID 객체는 다음과 같은 읽기 전용 어트리뷰트를 갖습니다.

UUID.bytes

16바이트 문자열(여섯 개의 빅 엔디안 순서 정수 필드 포함)인 UUID

UUID.bytes_le

16바이트 문자열(리틀 엔디안 순서 time_low, time_mid, time_hi_version)인 UUID

UUID.fields

UUID의 여섯 개의 정수 필드로 이루어진 튜플. 여섯 개의 개별 어트리뷰트와 두 개의 파생된 어트리뷰트도 사용 가능:

필드

의미

time_low

UUID의 처음 32bit

time_mid

UUID의 다음 16bit

time_hi_version

UUID의 다음 16bit

clock_seq_hi_variant

UUID의 다음 8bit

clock_seq_low

UUID의 다음 8bit

node

UUID의 마지막 48bit

time

60bit 타임스탬프

clock_seq

14bit 시퀀스 번호

UUID.hex

16진수 32자리 문자열 UUID

UUID.int

128bit 정수 UUID

UUID.urn

RFC 4122 [https://tools.ietf.org/html/rfc4122.html]에서 명시한 URN의 UUID

UUID.variant

UUID 변종은 UUID의 내부 레이아웃을 결정합니다. 이는 상수 RESERVED_NCS, RFC_4122, RESERVED_MICROSOFT, 및 RESERVED_FUTURE 중 하나입니다.

UUID.version

UUID 버전 번호 (1부터 5까지이며, 변종이 RFC_4122일 때만 유효)

UUID.is_safe

플랫폼이 UUID를 다중 프로세스에 안전한 방식으로 생성했는지를 나타내는 SafeUUID의 열거체입니다.

버전 3.7에 추가.

uuid 모듈은 다음의 함수들을 정의합니다.

uuid.getnode()

하드웨어 주소를 48bit 양의 정수로 가져옵니다. 최초 실행 시 별도의 프로그램으로 실행될 수 있고, 매우 느려질 수 있습니다. 하드웨어 주소를 얻기 위한 시도가 모두 실패하면, RFC 4122 [https://tools.ietf.org/html/rfc4122.html]가 권장하는 대로 멀티캐스트 비트(첫 옥텟의 최하위 비트)가 1로 설정된 무작위 48bit 숫자를 선택합니다. “하드웨어 주소”는 네트워크 인터페이스의 MAC 주소를 뜻합니다. 여러 네트워크 인터페이스를 가진 머신에서 보편적으로 관리하는 MAC 주소(즉, 첫 번째 옥텟의 두 번째 최하위 비트가 unset인 경우)는 로컬에서 관리하는 MAC 주소보다 우선하지만, 순서를 보장하지는 않습니다.

버전 3.7에서 변경: 보편적으로 관리하는 MAC 주소는 로컬로 관리하는 MAC 주소보다 우선합니다. 전자는 주소가 전 세계적으로 고유함을 보장하지만, 후자는 그렇지 않기 때문입니다.

uuid.uuid1(node=None, clock_seq=None)

호스트 ID, 시퀀스 번호 및 현재 시각으로 UUID 생성. node가 주어지지 않으면, getnode()를 사용하여 하드웨어 주소를 얻습니다. clock_seq가 주어지면 시퀀스 번호로 사용합니다. 그렇지 않을 경우, 무작위 14bit 시퀀스 번호를 사용합니다.

uuid.uuid3(namespace, name)

이름 공간 식별자(UUID) 및 이름(문자열)의 MD5 해시를 기반으로 UUID 생성.

uuid.uuid4()

무작위 UUID 생성.

uuid.uuid5(namespace, name)

이름 공간 식별자(UUID) 및 이름(문자열)의 SHA-1 해시를 기반으로 UUID 생성.

uuid 모듈은 uuid3()과 uuid5()를 위한 아래의 이름 공간 식별자를 정의합니다.

uuid.NAMESPACE_DNS

이 이름 공간이 지정되면 name 문자열은 전체 도메인 이름(FQDN)입니다.

uuid.NAMESPACE_URL

이 이름 공간이 지정되면 name 문자열은 URL입니다.

uuid.NAMESPACE_OID

이 이름 공간이 지정되면 name 문자열은 ISO OID입니다.

uuid.NAMESPACE_X500

이 이름 공간이 지정되면 name 문자열은 DER이나 텍스트 출력 형식의 X.500 DN입니다.

uuid 모듈은 variant 어트리뷰트로 사용할 수 있는 값으로 다음의 상수를 정의합니다:

uuid.RESERVED_NCS

NCS 호환성을 위해 예약됨.

uuid.RFC_4122

RFC 4122 [https://tools.ietf.org/html/rfc4122.html] 의 UUID 레이아웃 명시.

uuid.RESERVED_MICROSOFT

마이크로소프트 호환성을 위해 예약됨.

uuid.RESERVED_FUTURE

추후 정의를 위해 예약됨.

더 보기

RFC 4122 [https://tools.ietf.org/html/rfc4122.html] - 범용 고유 식별자(UUID) URN 이름 공간

이 명세는 UUID를 위한 통합 자원 식별자 이름 공간, UUID의 내부 형식 및 UUID 생성 방법을 정의합니다.

예제

uuid 모듈을 사용하는 전형적인 몇 가지 예제입니다:

>>> import uuid

>>> # make a UUID based on the host ID and current time
>>> uuid.uuid1()
UUID('a8098c1a-f86e-11da-bd1a-00112444be1e')

>>> # make a UUID using an MD5 hash of a namespace UUID and a name
>>> uuid.uuid3(uuid.NAMESPACE_DNS, 'python.org')
UUID('6fa459ea-ee8a-3ca4-894e-db77e160355e')

>>> # make a random UUID
>>> uuid.uuid4()
UUID('16fd2706-8baf-433b-82eb-8c7fada847da')

>>> # make a UUID using a SHA-1 hash of a namespace UUID and a name
>>> uuid.uuid5(uuid.NAMESPACE_DNS, 'python.org')
UUID('886313e1-3b8a-5372-9b90-0c9aee199e5d')

>>> # make a UUID from a string of hex digits (braces and hyphens ignored)
>>> x = uuid.UUID('{00010203-0405-0607-0809-0a0b0c0d0e0f}')

>>> # convert a UUID to a string of hex digits in standard form
>>> str(x)
'00010203-0405-0607-0809-0a0b0c0d0e0f'

>>> # get the raw 16 bytes of the UUID
>>> x.bytes
b'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f'

>>> # make a UUID from a 16-byte string
>>> uuid.UUID(bytes=x.bytes)
UUID('00010203-0405-0607-0809-0a0b0c0d0e0f')

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 프로토콜과 지원 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 프로토콜과 지원 »

|

socketserver — A framework for network servers

Source code: Lib/socketserver.py [https://github.com/python/cpython/tree/3.7/Lib/socketserver.py]

The socketserver module simplifies the task of writing network servers.

There are four basic concrete server classes:

class socketserver.TCPServer(server_address, RequestHandlerClass, bind_and_activate=True)

This uses the Internet TCP protocol, which provides for continuous streams of data between the client and server. If bind_and_activate is true, the constructor automatically attempts to invoke server_bind() and server_activate(). The other parameters are passed to the BaseServer base class.

class socketserver.UDPServer(server_address, RequestHandlerClass, bind_and_activate=True)

This uses datagrams, which are discrete packets of information that may arrive out of order or be lost while in transit. The parameters are the same as for TCPServer.

class socketserver.UnixStreamServer(server_address, RequestHandlerClass, bind_and_activate=True)

class socketserver.UnixDatagramServer(server_address, RequestHandlerClass, bind_and_activate=True)

These more infrequently used classes are similar to the TCP and UDP classes, but use Unix domain sockets; they’re not available on non-Unix platforms. The parameters are the same as for TCPServer.

These four classes process requests synchronously; each request must be completed before the next request can be started. This isn’t suitable if each request takes a long time to complete, because it requires a lot of computation, or because it returns a lot of data which the client is slow to process. The solution is to create a separate process or thread to handle each request; the ForkingMixIn and ThreadingMixIn mix-in classes can be used to support asynchronous behaviour.

Creating a server requires several steps. First, you must create a request handler class by subclassing the BaseRequestHandler class and overriding its handle() method; this method will process incoming requests. Second, you must instantiate one of the server classes, passing it the server’s address and the request handler class. It is recommended to use the server in a with statement. Then call the handle_request() or serve_forever() method of the server object to process one or many requests. Finally, call server_close() to close the socket (unless you used a with statement).

When inheriting from ThreadingMixIn for threaded connection behavior, you should explicitly declare how you want your threads to behave on an abrupt shutdown. The ThreadingMixIn class defines an attribute daemon_threads, which indicates whether or not the server should wait for thread termination. You should set the flag explicitly if you would like threads to behave autonomously; the default is False, meaning that Python will not exit until all threads created by ThreadingMixIn have exited.

Server classes have the same external methods and attributes, no matter what network protocol they use.

Server Creation Notes

There are five classes in an inheritance diagram, four of which represent synchronous servers of four types:

+------------+
| BaseServer |
+------------+
      |
      v
+-----------+        +------------------+
| TCPServer |------->| UnixStreamServer |
+-----------+        +------------------+
      |
      v
+-----------+        +--------------------+
| UDPServer |------->| UnixDatagramServer |
+-----------+        +--------------------+

Note that UnixDatagramServer derives from UDPServer, not from UnixStreamServer — the only difference between an IP and a Unix stream server is the address family, which is simply repeated in both Unix server classes.

class socketserver.ForkingMixIn

class socketserver.ThreadingMixIn

Forking and threading versions of each type of server can be created using these mix-in classes. For instance, ThreadingUDPServer is created as follows:

class ThreadingUDPServer(ThreadingMixIn, UDPServer):
    pass

The mix-in class comes first, since it overrides a method defined in UDPServer. Setting the various attributes also changes the behavior of the underlying server mechanism.

ForkingMixIn and the Forking classes mentioned below are only available on POSIX platforms that support fork().

socketserver.ForkingMixIn.server_close() waits until all child processes complete, except if socketserver.ForkingMixIn.block_on_close attribute is false.

socketserver.ThreadingMixIn.server_close() waits until all non-daemon threads complete, except if socketserver.ThreadingMixIn.block_on_close attribute is false. Use daemonic threads by setting ThreadingMixIn.daemon_threads to True to not wait until threads complete.

버전 3.7에서 변경: socketserver.ForkingMixIn.server_close() and socketserver.ThreadingMixIn.server_close() now waits until all child processes and non-daemonic threads complete. Add a new socketserver.ForkingMixIn.block_on_close class attribute to opt-in for the pre-3.7 behaviour.

class socketserver.ForkingTCPServer

class socketserver.ForkingUDPServer

class socketserver.ThreadingTCPServer

class socketserver.ThreadingUDPServer

These classes are pre-defined using the mix-in classes.

To implement a service, you must derive a class from BaseRequestHandler and redefine its handle() method. You can then run various versions of the service by combining one of the server classes with your request handler class. The request handler class must be different for datagram or stream services. This can be hidden by using the handler subclasses StreamRequestHandler or DatagramRequestHandler.

Of course, you still have to use your head! For instance, it makes no sense to use a forking server if the service contains state in memory that can be modified by different requests, since the modifications in the child process would never reach the initial state kept in the parent process and passed to each child. In this case, you can use a threading server, but you will probably have to use locks to protect the integrity of the shared data.

On the other hand, if you are building an HTTP server where all data is stored externally (for instance, in the file system), a synchronous class will essentially render the service “deaf” while one request is being handled – which may be for a very long time if a client is slow to receive all the data it has requested. Here a threading or forking server is appropriate.

In some cases, it may be appropriate to process part of a request synchronously, but to finish processing in a forked child depending on the request data. This can be implemented by using a synchronous server and doing an explicit fork in the request handler class handle() method.

Another approach to handling multiple simultaneous requests in an environment that supports neither threads nor fork() (or where these are too expensive or inappropriate for the service) is to maintain an explicit table of partially finished requests and to use selectors to decide which request to work on next (or whether to handle a new incoming request). This is particularly important for stream services where each client can potentially be connected for a long time (if threads or subprocesses cannot be used). See asyncore for another way to manage this.

Server Objects

class socketserver.BaseServer(server_address, RequestHandlerClass)

This is the superclass of all Server objects in the module. It defines the interface, given below, but does not implement most of the methods, which is done in subclasses. The two parameters are stored in the respective server_address and RequestHandlerClass attributes.

fileno()

Return an integer file descriptor for the socket on which the server is listening. This function is most commonly passed to selectors, to allow monitoring multiple servers in the same process.

handle_request()

Process a single request. This function calls the following methods in order: get_request(), verify_request(), and process_request(). If the user-provided handle() method of the handler class raises an exception, the server’s handle_error() method will be called. If no request is received within timeout seconds, handle_timeout() will be called and handle_request() will return.

serve_forever(poll_interval=0.5)

Handle requests until an explicit shutdown() request. Poll for shutdown every poll_interval seconds. Ignores the timeout attribute. It also calls service_actions(), which may be used by a subclass or mixin to provide actions specific to a given service. For example, the ForkingMixIn class uses service_actions() to clean up zombie child processes.

버전 3.3에서 변경: Added service_actions call to the serve_forever method.

service_actions()

This is called in the serve_forever() loop. This method can be overridden by subclasses or mixin classes to perform actions specific to a given service, such as cleanup actions.

버전 3.3에 추가.

shutdown()

Tell the serve_forever() loop to stop and wait until it does. shutdown() must be called while serve_forever() is running in a different thread otherwise it will deadlock.

server_close()

Clean up the server. May be overridden.

address_family

The family of protocols to which the server’s socket belongs. Common examples are socket.AF_INET and socket.AF_UNIX.

RequestHandlerClass

The user-provided request handler class; an instance of this class is created for each request.

server_address

The address on which the server is listening. The format of addresses varies depending on the protocol family; see the documentation for the socket module for details. For Internet protocols, this is a tuple containing a string giving the address, and an integer port number: ('127.0.0.1', 80), for example.

socket

The socket object on which the server will listen for incoming requests.

The server classes support the following class variables:

allow_reuse_address

Whether the server will allow the reuse of an address. This defaults to False, and can be set in subclasses to change the policy.

request_queue_size

The size of the request queue. If it takes a long time to process a single request, any requests that arrive while the server is busy are placed into a queue, up to request_queue_size requests. Once the queue is full, further requests from clients will get a “Connection denied” error. The default value is usually 5, but this can be overridden by subclasses.

socket_type

The type of socket used by the server; socket.SOCK_STREAM and socket.SOCK_DGRAM are two common values.

timeout

Timeout duration, measured in seconds, or None if no timeout is desired. If handle_request() receives no incoming requests within the timeout period, the handle_timeout() method is called.

There are various server methods that can be overridden by subclasses of base server classes like TCPServer; these methods aren’t useful to external users of the server object.

finish_request(request, client_address)

Actually processes the request by instantiating RequestHandlerClass and calling its handle() method.

get_request()

Must accept a request from the socket, and return a 2-tuple containing the new socket object to be used to communicate with the client, and the client’s address.

handle_error(request, client_address)

This function is called if the handle() method of a RequestHandlerClass instance raises an exception. The default action is to print the traceback to standard error and continue handling further requests.

버전 3.6에서 변경: Now only called for exceptions derived from the Exception class.

handle_timeout()

This function is called when the timeout attribute has been set to a value other than None and the timeout period has passed with no requests being received. The default action for forking servers is to collect the status of any child processes that have exited, while in threading servers this method does nothing.

process_request(request, client_address)

Calls finish_request() to create an instance of the RequestHandlerClass. If desired, this function can create a new process or thread to handle the request; the ForkingMixIn and ThreadingMixIn classes do this.

server_activate()

Called by the server’s constructor to activate the server. The default behavior for a TCP server just invokes listen() on the server’s socket. May be overridden.

server_bind()

Called by the server’s constructor to bind the socket to the desired address. May be overridden.

verify_request(request, client_address)

Must return a Boolean value; if the value is True, the request will be processed, and if it’s False, the request will be denied. This function can be overridden to implement access controls for a server. The default implementation always returns True.

버전 3.6에서 변경: Support for the context manager protocol was added. Exiting the context manager is equivalent to calling server_close().

Request Handler Objects

class socketserver.BaseRequestHandler

This is the superclass of all request handler objects. It defines the interface, given below. A concrete request handler subclass must define a new handle() method, and can override any of the other methods. A new instance of the subclass is created for each request.

setup()

Called before the handle() method to perform any initialization actions required. The default implementation does nothing.

handle()

This function must do all the work required to service a request. The default implementation does nothing. Several instance attributes are available to it; the request is available as self.request; the client address as self.client_address; and the server instance as self.server, in case it needs access to per-server information.

The type of self.request is different for datagram or stream services. For stream services, self.request is a socket object; for datagram services, self.request is a pair of string and socket.

finish()

Called after the handle() method to perform any clean-up actions required. The default implementation does nothing. If setup() raises an exception, this function will not be called.

class socketserver.StreamRequestHandler

class socketserver.DatagramRequestHandler

These BaseRequestHandler subclasses override the setup() and finish() methods, and provide self.rfile and self.wfile attributes. The self.rfile and self.wfile attributes can be read or written, respectively, to get the request data or return data to the client.

The rfile attributes of both classes support the io.BufferedIOBase readable interface, and DatagramRequestHandler.wfile supports the io.BufferedIOBase writable interface.

버전 3.6에서 변경: StreamRequestHandler.wfile also supports the io.BufferedIOBase writable interface.

Examples

socketserver.TCPServer Example

This is the server side:

import socketserver

class MyTCPHandler(socketserver.BaseRequestHandler):
    """
    The request handler class for our server.

    It is instantiated once per connection to the server, and must
    override the handle() method to implement communication to the
    client.
    """

    def handle(self):
        # self.request is the TCP socket connected to the client
        self.data = self.request.recv(1024).strip()
        print("{} wrote:".format(self.client_address[0]))
        print(self.data)
        # just send back the same data, but upper-cased
        self.request.sendall(self.data.upper())

if __name__ == "__main__":
    HOST, PORT = "localhost", 9999

    # Create the server, binding to localhost on port 9999
    with socketserver.TCPServer((HOST, PORT), MyTCPHandler) as server:
        # Activate the server; this will keep running until you
        # interrupt the program with Ctrl-C
        server.serve_forever()

An alternative request handler class that makes use of streams (file-like objects that simplify communication by providing the standard file interface):

class MyTCPHandler(socketserver.StreamRequestHandler):

    def handle(self):
        # self.rfile is a file-like object created by the handler;
        # we can now use e.g. readline() instead of raw recv() calls
        self.data = self.rfile.readline().strip()
        print("{} wrote:".format(self.client_address[0]))
        print(self.data)
        # Likewise, self.wfile is a file-like object used to write back
        # to the client
        self.wfile.write(self.data.upper())

The difference is that the readline() call in the second handler will call recv() multiple times until it encounters a newline character, while the single recv() call in the first handler will just return what has been sent from the client in one sendall() call.

This is the client side:

import socket
import sys

HOST, PORT = "localhost", 9999
data = " ".join(sys.argv[1:])

# Create a socket (SOCK_STREAM means a TCP socket)
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
    # Connect to server and send data
    sock.connect((HOST, PORT))
    sock.sendall(bytes(data + "\n", "utf-8"))

    # Receive data from the server and shut down
    received = str(sock.recv(1024), "utf-8")

print("Sent:     {}".format(data))
print("Received: {}".format(received))

The output of the example should look something like this:

Server:

$ python TCPServer.py
127.0.0.1 wrote:
b'hello world with TCP'
127.0.0.1 wrote:
b'python is nice'

Client:

$ python TCPClient.py hello world with TCP
Sent:     hello world with TCP
Received: HELLO WORLD WITH TCP
$ python TCPClient.py python is nice
Sent:     python is nice
Received: PYTHON IS NICE

socketserver.UDPServer Example

This is the server side:

import socketserver

class MyUDPHandler(socketserver.BaseRequestHandler):
    """
    This class works similar to the TCP handler class, except that
    self.request consists of a pair of data and client socket, and since
    there is no connection the client address must be given explicitly
    when sending data back via sendto().
    """

    def handle(self):
        data = self.request[0].strip()
        socket = self.request[1]
        print("{} wrote:".format(self.client_address[0]))
        print(data)
        socket.sendto(data.upper(), self.client_address)

if __name__ == "__main__":
    HOST, PORT = "localhost", 9999
    with socketserver.UDPServer((HOST, PORT), MyUDPHandler) as server:
        server.serve_forever()

This is the client side:

import socket
import sys

HOST, PORT = "localhost", 9999
data = " ".join(sys.argv[1:])

# SOCK_DGRAM is the socket type to use for UDP sockets
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

# As you can see, there is no connect() call; UDP has no connections.
# Instead, data is directly sent to the recipient via sendto().
sock.sendto(bytes(data + "\n", "utf-8"), (HOST, PORT))
received = str(sock.recv(1024), "utf-8")

print("Sent:     {}".format(data))
print("Received: {}".format(received))

The output of the example should look exactly like for the TCP server example.

Asynchronous Mixins

To build asynchronous handlers, use the ThreadingMixIn and ForkingMixIn classes.

An example for the ThreadingMixIn class:

import socket
import threading
import socketserver

class ThreadedTCPRequestHandler(socketserver.BaseRequestHandler):

    def handle(self):
        data = str(self.request.recv(1024), 'ascii')
        cur_thread = threading.current_thread()
        response = bytes("{}: {}".format(cur_thread.name, data), 'ascii')
        self.request.sendall(response)

class ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
    pass

def client(ip, port, message):
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
        sock.connect((ip, port))
        sock.sendall(bytes(message, 'ascii'))
        response = str(sock.recv(1024), 'ascii')
        print("Received: {}".format(response))

if __name__ == "__main__":
    # Port 0 means to select an arbitrary unused port
    HOST, PORT = "localhost", 0

    server = ThreadedTCPServer((HOST, PORT), ThreadedTCPRequestHandler)
    with server:
        ip, port = server.server_address

        # Start a thread with the server -- that thread will then start one
        # more thread for each request
        server_thread = threading.Thread(target=server.serve_forever)
        # Exit the server thread when the main thread terminates
        server_thread.daemon = True
        server_thread.start()
        print("Server loop running in thread:", server_thread.name)

        client(ip, port, "Hello World 1")
        client(ip, port, "Hello World 2")
        client(ip, port, "Hello World 3")

        server.shutdown()

The output of the example should look something like this:

$ python ThreadedTCPServer.py
Server loop running in thread: Thread-1
Received: Thread-2: Hello World 1
Received: Thread-3: Hello World 2
Received: Thread-4: Hello World 3

The ForkingMixIn class is used in the same way, except that the server will spawn a new process for each request. Available only on POSIX platforms that support fork().

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 프로토콜과 지원 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 프로토콜과 지원 »

|

http.server — HTTP servers

Source code: Lib/http/server.py [https://github.com/python/cpython/tree/3.7/Lib/http/server.py]

This module defines classes for implementing HTTP servers (Web servers).

경고

http.server is not recommended for production. It only implements basic security checks.

One class, HTTPServer, is a socketserver.TCPServer subclass. It creates and listens at the HTTP socket, dispatching the requests to a handler. Code to create and run the server looks like this:

def run(server_class=HTTPServer, handler_class=BaseHTTPRequestHandler):
    server_address = ('', 8000)
    httpd = server_class(server_address, handler_class)
    httpd.serve_forever()

class http.server.HTTPServer(server_address, RequestHandlerClass)

This class builds on the TCPServer class by storing the server address as instance variables named server_name and server_port. The server is accessible by the handler, typically through the handler’s server instance variable.

class http.server.ThreadingHTTPServer(server_address, RequestHandlerClass)

This class is identical to HTTPServer but uses threads to handle requests by using the ThreadingMixIn. This is useful to handle web browsers pre-opening sockets, on which HTTPServer would wait indefinitely.

버전 3.7에 추가.

The HTTPServer and ThreadingHTTPServer must be given a RequestHandlerClass on instantiation, of which this module provides three different variants:

class http.server.BaseHTTPRequestHandler(request, client_address, server)

This class is used to handle the HTTP requests that arrive at the server. By itself, it cannot respond to any actual HTTP requests; it must be subclassed to handle each request method (e.g. GET or POST). BaseHTTPRequestHandler provides a number of class and instance variables, and methods for use by subclasses.

The handler will parse the request and the headers, then call a method specific to the request type. The method name is constructed from the request. For example, for the request method SPAM, the do_SPAM() method will be called with no arguments. All of the relevant information is stored in instance variables of the handler. Subclasses should not need to override or extend the __init__() method.

BaseHTTPRequestHandler has the following instance variables:

client_address

Contains a tuple of the form (host, port) referring to the client’s address.

server

Contains the server instance.

close_connection

Boolean that should be set before handle_one_request() returns, indicating if another request may be expected, or if the connection should be shut down.

requestline

Contains the string representation of the HTTP request line. The terminating CRLF is stripped. This attribute should be set by handle_one_request(). If no valid request line was processed, it should be set to the empty string.

command

Contains the command (request type). For example, 'GET'.

path

Contains the request path.

request_version

Contains the version string from the request. For example, 'HTTP/1.0'.

headers

Holds an instance of the class specified by the MessageClass class variable. This instance parses and manages the headers in the HTTP request. The parse_headers() function from http.client is used to parse the headers and it requires that the HTTP request provide a valid RFC 2822 [https://tools.ietf.org/html/rfc2822.html] style header.

rfile

An io.BufferedIOBase input stream, ready to read from the start of the optional input data.

wfile

Contains the output stream for writing a response back to the client. Proper adherence to the HTTP protocol must be used when writing to this stream in order to achieve successful interoperation with HTTP clients.

버전 3.6에서 변경: This is an io.BufferedIOBase stream.

BaseHTTPRequestHandler has the following attributes:

server_version

Specifies the server software version. You may want to override this. The format is multiple whitespace-separated strings, where each string is of the form name[/version]. For example, 'BaseHTTP/0.2'.

sys_version

Contains the Python system version, in a form usable by the version_string method and the server_version class variable. For example, 'Python/1.4'.

error_message_format

Specifies a format string that should be used by send_error() method for building an error response to the client. The string is filled by default with variables from responses based on the status code that passed to send_error().

error_content_type

Specifies the Content-Type HTTP header of error responses sent to the client. The default value is 'text/html'.

protocol_version

This specifies the HTTP protocol version used in responses. If set to 'HTTP/1.1', the server will permit HTTP persistent connections; however, your server must then include an accurate Content-Length header (using send_header()) in all of its responses to clients. For backwards compatibility, the setting defaults to 'HTTP/1.0'.

MessageClass

Specifies an email.message.Message-like class to parse HTTP headers. Typically, this is not overridden, and it defaults to http.client.HTTPMessage.

responses

This attribute contains a mapping of error code integers to two-element tuples containing a short and long message. For example, {code: (shortmessage, longmessage)}. The shortmessage is usually used as the message key in an error response, and longmessage as the explain key. It is used by send_response_only() and send_error() methods.

A BaseHTTPRequestHandler instance has the following methods:

handle()

Calls handle_one_request() once (or, if persistent connections are enabled, multiple times) to handle incoming HTTP requests. You should never need to override it; instead, implement appropriate do_*() methods.

handle_one_request()

This method will parse and dispatch the request to the appropriate do_*() method. You should never need to override it.

handle_expect_100()

When a HTTP/1.1 compliant server receives an Expect: 100-continue request header it responds back with a 100 Continue followed by 200 OK headers. This method can be overridden to raise an error if the server does not want the client to continue. For e.g. server can chose to send 417 Expectation Failed as a response header and return False.

버전 3.2에 추가.

send_error(code, message=None, explain=None)

Sends and logs a complete error reply to the client. The numeric code specifies the HTTP error code, with message as an optional, short, human readable description of the error. The explain argument can be used to provide more detailed information about the error; it will be formatted using the error_message_format attribute and emitted, after a complete set of headers, as the response body. The responses attribute holds the default values for message and explain that will be used if no value is provided; for unknown codes the default value for both is the string ???. The body will be empty if the method is HEAD or the response code is one of the following: 1xx, 204 No Content, 205 Reset Content, 304 Not Modified.

버전 3.4에서 변경: The error response includes a Content-Length header. Added the explain argument.

send_response(code, message=None)

Adds a response header to the headers buffer and logs the accepted request. The HTTP response line is written to the internal buffer, followed by Server and Date headers. The values for these two headers are picked up from the version_string() and date_time_string() methods, respectively. If the server does not intend to send any other headers using the send_header() method, then send_response() should be followed by an end_headers() call.

버전 3.3에서 변경: Headers are stored to an internal buffer and end_headers() needs to be called explicitly.

send_header(keyword, value)

Adds the HTTP header to an internal buffer which will be written to the output stream when either end_headers() or flush_headers() is invoked. keyword should specify the header keyword, with value specifying its value. Note that, after the send_header calls are done, end_headers() MUST BE called in order to complete the operation.

버전 3.2에서 변경: Headers are stored in an internal buffer.

send_response_only(code, message=None)

Sends the response header only, used for the purposes when 100 Continue response is sent by the server to the client. The headers not buffered and sent directly the output stream.If the message is not specified, the HTTP message corresponding the response code is sent.

버전 3.2에 추가.

end_headers()

Adds a blank line (indicating the end of the HTTP headers in the response) to the headers buffer and calls flush_headers().

버전 3.2에서 변경: The buffered headers are written to the output stream.

flush_headers()

Finally send the headers to the output stream and flush the internal headers buffer.

버전 3.3에 추가.

log_request(code='-', size='-')

Logs an accepted (successful) request. code should specify the numeric HTTP code associated with the response. If a size of the response is available, then it should be passed as the size parameter.

log_error(...)

Logs an error when a request cannot be fulfilled. By default, it passes the message to log_message(), so it takes the same arguments (format and additional values).

log_message(format, ...)

Logs an arbitrary message to sys.stderr. This is typically overridden to create custom error logging mechanisms. The format argument is a standard printf-style format string, where the additional arguments to log_message() are applied as inputs to the formatting. The client ip address and current date and time are prefixed to every message logged.

version_string()

Returns the server software’s version string. This is a combination of the server_version and sys_version attributes.

date_time_string(timestamp=None)

Returns the date and time given by timestamp (which must be None or in the format returned by time.time()), formatted for a message header. If timestamp is omitted, it uses the current date and time.

The result looks like 'Sun, 06 Nov 1994 08:49:37 GMT'.

log_date_time_string()

Returns the current date and time, formatted for logging.

address_string()

Returns the client address.

버전 3.3에서 변경: Previously, a name lookup was performed. To avoid name resolution delays, it now always returns the IP address.

class http.server.SimpleHTTPRequestHandler(request, client_address, server, directory=None)

This class serves files from the current directory and below, directly mapping the directory structure to HTTP requests.

A lot of the work, such as parsing the request, is done by the base class BaseHTTPRequestHandler. This class implements the do_GET() and do_HEAD() functions.

The following are defined as class-level attributes of SimpleHTTPRequestHandler:

server_version

This will be "SimpleHTTP/" + __version__, where __version__ is defined at the module level.

extensions_map

A dictionary mapping suffixes into MIME types. The default is signified by an empty string, and is considered to be application/octet-stream. The mapping is used case-insensitively, and so should contain only lower-cased keys.

directory

If not specified, the directory to serve is the current working directory.

The SimpleHTTPRequestHandler class defines the following methods:

do_HEAD()

This method serves the 'HEAD' request type: it sends the headers it would send for the equivalent GET request. See the do_GET() method for a more complete explanation of the possible headers.

do_GET()

The request is mapped to a local file by interpreting the request as a path relative to the current working directory.

If the request was mapped to a directory, the directory is checked for a file named index.html or index.htm (in that order). If found, the file’s contents are returned; otherwise a directory listing is generated by calling the list_directory() method. This method uses os.listdir() to scan the directory, and returns a 404 error response if the listdir() fails.

If the request was mapped to a file, it is opened. Any OSError exception in opening the requested file is mapped to a 404, 'File not found' error. If there was a 'If-Modified-Since' header in the request, and the file was not modified after this time, a 304, 'Not Modified' response is sent. Otherwise, the content type is guessed by calling the guess_type() method, which in turn uses the extensions_map variable, and the file contents are returned.

A 'Content-type:' header with the guessed content type is output, followed by a 'Content-Length:' header with the file’s size and a 'Last-Modified:' header with the file’s modification time.

Then follows a blank line signifying the end of the headers, and then the contents of the file are output. If the file’s MIME type starts with text/ the file is opened in text mode; otherwise binary mode is used.

For example usage, see the implementation of the test() function invocation in the http.server module.

버전 3.7에서 변경: Support of the 'If-Modified-Since' header.

The SimpleHTTPRequestHandler class can be used in the following manner in order to create a very basic webserver serving files relative to the current directory:

import http.server
import socketserver

PORT = 8000

Handler = http.server.SimpleHTTPRequestHandler

with socketserver.TCPServer(("", PORT), Handler) as httpd:
    print("serving at port", PORT)
    httpd.serve_forever()

http.server can also be invoked directly using the -m switch of the interpreter with a port number argument. Similar to the previous example, this serves files relative to the current directory:

python -m http.server 8000

By default, server binds itself to all interfaces. The option -b/--bind specifies a specific address to which it should bind. For example, the following command causes the server to bind to localhost only:

python -m http.server 8000 --bind 127.0.0.1

버전 3.4에 추가: --bind argument was introduced.

By default, server uses the current directory. The option -d/--directory specifies a directory to which it should serve the files. For example, the following command uses a specific directory:

python -m http.server --directory /tmp/

버전 3.7에 추가: --directory specify alternate directory

class http.server.CGIHTTPRequestHandler(request, client_address, server)

This class is used to serve either files or output of CGI scripts from the current directory and below. Note that mapping HTTP hierarchic structure to local directory structure is exactly as in SimpleHTTPRequestHandler.

참고

CGI scripts run by the CGIHTTPRequestHandler class cannot execute redirects (HTTP code 302), because code 200 (script output follows) is sent prior to execution of the CGI script. This pre-empts the status code.

The class will however, run the CGI script, instead of serving it as a file, if it guesses it to be a CGI script. Only directory-based CGI are used — the other common server configuration is to treat special extensions as denoting CGI scripts.

The do_GET() and do_HEAD() functions are modified to run CGI scripts and serve the output, instead of serving files, if the request leads to somewhere below the cgi_directories path.

The CGIHTTPRequestHandler defines the following data member:

cgi_directories

This defaults to ['/cgi-bin', '/htbin'] and describes directories to treat as containing CGI scripts.

The CGIHTTPRequestHandler defines the following method:

do_POST()

This method serves the 'POST' request type, only allowed for CGI scripts. Error 501, “Can only POST to CGI scripts”, is output when trying to POST to a non-CGI url.

Note that CGI scripts will be run with UID of user nobody, for security reasons. Problems with the CGI script will be translated to error 403.

CGIHTTPRequestHandler can be enabled in the command line by passing the --cgi option:

python -m http.server --cgi 8000

Security Considerations

SimpleHTTPRequestHandler will follow symbolic links when handling requests, this makes it possible for files outside of the specified directory to be served.

Earlier versions of Python did not scrub control characters from the log messages emitted to stderr from python -m http.server or the default BaseHTTPRequestHandler .log_message implementation. This could allow remote clients connecting to your server to send nefarious control codes to your terminal.

버전 3.7.16에 추가: scrubbing control characters from log messages

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 프로토콜과 지원 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 프로토콜과 지원 »

|

http.cookies — HTTP 상태 관리

소스 코드: Lib/http/cookies.py [https://github.com/python/cpython/tree/3.7/Lib/http/cookies.py]

http.cookies 모듈은 HTTP 상태 관리 메커니즘인 쿠키의 개념을 추상화하는 클래스를 정의합니다. 그것은 단순한 문자열 전용 쿠키를 지원하고, 동시에 직렬화 가능한 데이터형을 쿠키값으로 갖는 데 필요한 추상화를 제공합니다.

이 모듈은 예전에는 RFC 2109 [https://tools.ietf.org/html/rfc2109.html]와 RFC 2068 [https://tools.ietf.org/html/rfc2068.html] 명세에서 설명된 구문 분석 규칙을 엄격하게 적용했습니다. 그 이후로 MSIE 3.0x가 이 명세에 명시된 문자 규칙을 따르지 않으며 쿠키 처리와 관련하여 오늘날의 많은 브라우저와 서버가 구문 분석 규칙을 완화했다는 사실이 발견되었습니다. 결과적으로, 사용되는 구문 분석 규칙은 약간 덜 엄격합니다.

문자 집합, string.ascii_letters, string.digits 및 !#$%&'*+-.^_`|~:는 이 모듈이 쿠키 이름(key)에 허용한 유효한 문자 집합을 나타냅니다.

버전 3.3에서 변경: ‘:’를 유효한 쿠키 이름 문자로 허용합니다.

참고

잘못된 쿠키가 발견되면, CookieError가 발생하므로, 쿠키 데이터가 브라우저에서 제공되면 항상 잘못된 데이터일 가능성에 대비하고 구문 분석할 때 CookieError를 잡아야 합니다.

exception http.cookies.CookieError

RFC 2109 [https://tools.ietf.org/html/rfc2109.html] 위반으로 인해 실패하는 예외: 잘못된 어트리뷰트, 잘못된 Set-Cookie 헤더 등

class http.cookies.BaseCookie([input])

이 클래스는 키가 문자열이고 값이 Morsel 인스턴스인 딕셔너리 형 객체입니다. 키에 값을 설정하면, 값이 먼저 키와 값이 포함된 Morsel로 변환됩니다.

input이 주어지면, load() 메서드로 전달됩니다.

class http.cookies.SimpleCookie([input])

이 클래스는 BaseCookie에서 파생되며 value_decode()와 value_encode()를 재정의합니다. SimpleCookie는 문자열 쿠키값을 지원합니다. 값을 설정할 때, SimpleCookie는 내장 str()을 호출하여 값을 문자열로 변환합니다. HTTP에서 수신된 값은 문자열로 유지됩니다.

더 보기

모듈 http.cookiejar

웹 클라이언트용 HTTP 쿠키 처리. http.cookiejar와 http.cookies 모듈 간의 의존성은 없습니다.

RFC 2109 [https://tools.ietf.org/html/rfc2109.html] - HTTP State Management Mechanism (HTTP 상태 관리 메커니즘)

이것은 이 모듈이 구현한 상태 관리 명세입니다.

쿠키 객체

BaseCookie.value_decode(val)

문자열 표현으로부터 튜플 (real_value, coded_value)를 반환합니다. real_value는 모든 형이 될 수 있습니다. 이 메서드는 BaseCookie에서는 아무런 디코딩을 하지 않습니다 — 재정의할 수 있도록 존재합니다.

BaseCookie.value_encode(val)

튜플 (real_value, coded_value)를 반환합니다. val은 모든 형이 될 수 있지만, coded_value는 항상 문자열로 변환됩니다. 이 메서드는 BaseCookie에서는 아무런 인코딩을 하지 않습니다 — 재정의할 수 있도록 존재합니다.

일반적으로, value_encode()와 value_decode()는 value_decode 범위에서 역연산입니다.

BaseCookie.output(attrs=None, header='Set-Cookie:', sep='\r\n')

HTTP 헤더로서 송신하기 적절한 문자열 표현을 반환합니다. attrs와 header는 각 Morsel의 output() 메서드로 전송됩니다. sep는 헤더를 함께 결합하는 데 사용되며, 기본적으로 '\r\n' (CRLF) 조합입니다.

BaseCookie.js_output(attrs=None)

자바스크립트를 지원하는 브라우저에서 실행될 때 HTTP 헤더가 전송된 것처럼 작동하는, 삽입 가능한 자바스크립트 코드 조각을 반환합니다.

attrs의 의미는 output()과 같습니다.

BaseCookie.load(rawdata)

rawdata가 문자열이면, HTTP_COOKIE로 구문 분석하고 거기에 있는 값을 Morsel로 추가합니다. 딕셔너리면, 다음과 동등합니다:

for k, v in rawdata.items():
    cookie[k] = v

Morsel 객체

class http.cookies.Morsel

RFC 2109 [https://tools.ietf.org/html/rfc2109.html] 어트리뷰트를 포함하는 키/값 쌍을 추상화합니다.

Morsel은 딕셔너리류 객체이며, 키의 집합은 상수입니다 — 다음과 같은 유효한 RFC 2109 [https://tools.ietf.org/html/rfc2109.html] 어트리뷰트입니다

expires

path

comment

domain

max-age

secure

version

httponly

httponly 어트리뷰트는 쿠키가 HTTP 요청으로만 전송되고 자바스크립트를 통해 액세스할 수 없도록 지정합니다. 이것은 교차 사이트 스크립팅의 일부 형식을 방지하기 위한 것입니다.

키는 대소 문자를 구분하지 않으며 기본값은 ''입니다.

버전 3.5에서 변경: __eq__()는 이제 key와 value를 고려합니다.

버전 3.7에서 변경: 어트리뷰트 key, value 및 coded_value는 읽기 전용입니다. 설정하려면 set()을 사용하십시오.

Morsel.value

쿠키의 값.

Morsel.coded_value

쿠키의 인코딩된 값 — 이것을 전송해야 합니다.

Morsel.key

쿠키의 이름.

Morsel.set(key, value, coded_value)

key, value 및 coded_value 어트리뷰트를 설정합니다.

Morsel.isReservedKey(K)

K가 Morsel의 키 집합의 구성원인지를 판단합니다.

Morsel.output(attrs=None, header='Set-Cookie:')

HTTP 헤더로 보내기에 적합한, Morsel의 문자열 표현을 반환합니다. 기본적으로, attrs가 주어지지 않는 한, 모든 어트리뷰트가 포함됩니다. 주어지면 사용할 어트리뷰트 리스트여야 합니다. header는 기본적으로 "Set-Cookie:"입니다.

Morsel.js_output(attrs=None)

자바스크립트를 지원하는 브라우저에서 실행될 때, HTTP 헤더가 전송된 것처럼 작동하는, 삽입 가능한 자바스크립트 코드 조각을 반환합니다.

attrs의 의미는 output()과 같습니다.

Morsel.OutputString(attrs=None)

둘러싸는 HTTP나 자바스크립트 없이 Morsel을 표현하는 문자열을 반환합니다.

attrs의 의미는 output()과 같습니다.

Morsel.update(values)

Morsel 딕셔너리의 값을 닥셔너리 values의 값으로 갱신합니다. values 딕셔너리의 키 중 하나라도 유효한 RFC 2109 [https://tools.ietf.org/html/rfc2109.html] 어트리뷰트가 아니면 에러를 발생시킵니다.

버전 3.5에서 변경: 유효하지 않은 키에 대해서 에러가 발생합니다.

Morsel.copy(value)

Morsel 객체의 얕은 복사본을 반환합니다.

버전 3.5에서 변경: 딕셔너리 대신 Morsel 객체를 반환합니다.

Morsel.setdefault(key, value=None)

key가 유효한 RFC 2109 [https://tools.ietf.org/html/rfc2109.html] 어트리뷰트가 아니면 에러를 발생시킵니다. 그렇지 않으면, dict.setdefault()와 같이 동작합니다.

예제

다음 예제는 http.cookies 모듈을 사용하는 방법을 보여줍니다.

>>> from http import cookies
>>> C = cookies.SimpleCookie()
>>> C["fig"] = "newton"
>>> C["sugar"] = "wafer"
>>> print(C) # generate HTTP headers
Set-Cookie: fig=newton
Set-Cookie: sugar=wafer
>>> print(C.output()) # same thing
Set-Cookie: fig=newton
Set-Cookie: sugar=wafer
>>> C = cookies.SimpleCookie()
>>> C["rocky"] = "road"
>>> C["rocky"]["path"] = "/cookie"
>>> print(C.output(header="Cookie:"))
Cookie: rocky=road; Path=/cookie
>>> print(C.output(attrs=[], header="Cookie:"))
Cookie: rocky=road
>>> C = cookies.SimpleCookie()
>>> C.load("chips=ahoy; vienna=finger") # load from a string (HTTP header)
>>> print(C)
Set-Cookie: chips=ahoy
Set-Cookie: vienna=finger
>>> C = cookies.SimpleCookie()
>>> C.load('keebler="E=everybody; L=\\"Loves\\"; fudge=\\012;";')
>>> print(C)
Set-Cookie: keebler="E=everybody; L=\"Loves\"; fudge=\012;"
>>> C = cookies.SimpleCookie()
>>> C["oreo"] = "doublestuff"
>>> C["oreo"]["path"] = "/"
>>> print(C)
Set-Cookie: oreo=doublestuff; Path=/
>>> C = cookies.SimpleCookie()
>>> C["twix"] = "none for you"
>>> C["twix"].value
'none for you'
>>> C = cookies.SimpleCookie()
>>> C["number"] = 7 # equivalent to C["number"] = str(7)
>>> C["string"] = "seven"
>>> C["number"].value
'7'
>>> C["string"].value
'seven'
>>> print(C)
Set-Cookie: number=7
Set-Cookie: string=seven

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 프로토콜과 지원 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 프로토콜과 지원 »

|

http.cookiejar — Cookie handling for HTTP clients

Source code: Lib/http/cookiejar.py [https://github.com/python/cpython/tree/3.7/Lib/http/cookiejar.py]

The http.cookiejar module defines classes for automatic handling of HTTP cookies. It is useful for accessing web sites that require small pieces of data – cookies – to be set on the client machine by an HTTP response from a web server, and then returned to the server in later HTTP requests.

Both the regular Netscape cookie protocol and the protocol defined by RFC 2965 [https://tools.ietf.org/html/rfc2965.html] are handled. RFC 2965 handling is switched off by default. RFC 2109 [https://tools.ietf.org/html/rfc2109.html] cookies are parsed as Netscape cookies and subsequently treated either as Netscape or RFC 2965 cookies according to the ‘policy’ in effect. Note that the great majority of cookies on the Internet are Netscape cookies. http.cookiejar attempts to follow the de-facto Netscape cookie protocol (which differs substantially from that set out in the original Netscape specification), including taking note of the max-age and port cookie-attributes introduced with RFC 2965.

참고

The various named parameters found in Set-Cookie and Set-Cookie2 headers (eg. domain and expires) are conventionally referred to as attributes. To distinguish them from Python attributes, the documentation for this module uses the term cookie-attribute instead.

The module defines the following exception:

exception http.cookiejar.LoadError

Instances of FileCookieJar raise this exception on failure to load cookies from a file. LoadError is a subclass of OSError.

버전 3.3에서 변경: LoadError was made a subclass of OSError instead of IOError.

The following classes are provided:

class http.cookiejar.CookieJar(policy=None)

policy is an object implementing the CookiePolicy interface.

The CookieJar class stores HTTP cookies. It extracts cookies from HTTP requests, and returns them in HTTP responses. CookieJar instances automatically expire contained cookies when necessary. Subclasses are also responsible for storing and retrieving cookies from a file or database.

class http.cookiejar.FileCookieJar(filename, delayload=None, policy=None)

policy is an object implementing the CookiePolicy interface. For the other arguments, see the documentation for the corresponding attributes.

A CookieJar which can load cookies from, and perhaps save cookies to, a file on disk. Cookies are NOT loaded from the named file until either the load() or revert() method is called. Subclasses of this class are documented in section FileCookieJar subclasses and co-operation with web browsers.

class http.cookiejar.CookiePolicy

This class is responsible for deciding whether each cookie should be accepted from / returned to the server.

class http.cookiejar.DefaultCookiePolicy(blocked_domains=None, allowed_domains=None, netscape=True, rfc2965=False, rfc2109_as_netscape=None, hide_cookie2=False, strict_domain=False, strict_rfc2965_unverifiable=True, strict_ns_unverifiable=False, strict_ns_domain=DefaultCookiePolicy.DomainLiberal, strict_ns_set_initial_dollar=False, strict_ns_set_path=False)

Constructor arguments should be passed as keyword arguments only. blocked_domains is a sequence of domain names that we never accept cookies from, nor return cookies to. allowed_domains if not None, this is a sequence of the only domains for which we accept and return cookies. For all other arguments, see the documentation for CookiePolicy and DefaultCookiePolicy objects.

DefaultCookiePolicy implements the standard accept / reject rules for Netscape and RFC 2965 [https://tools.ietf.org/html/rfc2965.html] cookies. By default, RFC 2109 [https://tools.ietf.org/html/rfc2109.html] cookies (ie. cookies received in a Set-Cookie header with a version cookie-attribute of 1) are treated according to the RFC 2965 rules. However, if RFC 2965 handling is turned off or rfc2109_as_netscape is True, RFC 2109 cookies are ‘downgraded’ by the CookieJar instance to Netscape cookies, by setting the version attribute of the Cookie instance to 0. DefaultCookiePolicy also provides some parameters to allow some fine-tuning of policy.

class http.cookiejar.Cookie

This class represents Netscape, RFC 2109 [https://tools.ietf.org/html/rfc2109.html] and RFC 2965 [https://tools.ietf.org/html/rfc2965.html] cookies. It is not expected that users of http.cookiejar construct their own Cookie instances. Instead, if necessary, call make_cookies() on a CookieJar instance.

더 보기

Module urllib.request

URL opening with automatic cookie handling.

Module http.cookies

HTTP cookie classes, principally useful for server-side code. The http.cookiejar and http.cookies modules do not depend on each other.

https://curl.haxx.se/rfc/cookie_spec.html

The specification of the original Netscape cookie protocol. Though this is still the dominant protocol, the ‘Netscape cookie protocol’ implemented by all the major browsers (and http.cookiejar) only bears a passing resemblance to the one sketched out in cookie_spec.html.

RFC 2109 [https://tools.ietf.org/html/rfc2109.html] - HTTP State Management Mechanism

Obsoleted by RFC 2965 [https://tools.ietf.org/html/rfc2965.html]. Uses Set-Cookie with version=1.

RFC 2965 [https://tools.ietf.org/html/rfc2965.html] - HTTP State Management Mechanism

The Netscape protocol with the bugs fixed. Uses Set-Cookie2 in place of Set-Cookie. Not widely used.

http://kristol.org/cookie/errata.html

Unfinished errata to RFC 2965 [https://tools.ietf.org/html/rfc2965.html].

RFC 2964 [https://tools.ietf.org/html/rfc2964.html] - Use of HTTP State Management

CookieJar and FileCookieJar Objects

CookieJar objects support the iterator protocol for iterating over contained Cookie objects.

CookieJar has the following methods:

CookieJar.add_cookie_header(request)

Add correct Cookie header to request.

If policy allows (ie. the rfc2965 and hide_cookie2 attributes of the CookieJar’s CookiePolicy instance are true and false respectively), the Cookie2 header is also added when appropriate.

The request object (usually a urllib.request.Request instance) must support the methods get_full_url(), get_host(), get_type(), unverifiable(), has_header(), get_header(), header_items(), add_unredirected_header() and origin_req_host attribute as documented by urllib.request.

버전 3.3에서 변경: request object needs origin_req_host attribute. Dependency on a deprecated method get_origin_req_host() has been removed.

CookieJar.extract_cookies(response, request)

Extract cookies from HTTP response and store them in the CookieJar, where allowed by policy.

The CookieJar will look for allowable Set-Cookie and Set-Cookie2 headers in the response argument, and store cookies as appropriate (subject to the CookiePolicy.set_ok() method’s approval).

The response object (usually the result of a call to urllib.request.urlopen(), or similar) should support an info() method, which returns an email.message.Message instance.

The request object (usually a urllib.request.Request instance) must support the methods get_full_url(), get_host(), unverifiable(), and origin_req_host attribute, as documented by urllib.request. The request is used to set default values for cookie-attributes as well as for checking that the cookie is allowed to be set.

버전 3.3에서 변경: request object needs origin_req_host attribute. Dependency on a deprecated method get_origin_req_host() has been removed.

CookieJar.set_policy(policy)

Set the CookiePolicy instance to be used.

CookieJar.make_cookies(response, request)

Return sequence of Cookie objects extracted from response object.

See the documentation for extract_cookies() for the interfaces required of the response and request arguments.

CookieJar.set_cookie_if_ok(cookie, request)

Set a Cookie if policy says it’s OK to do so.

CookieJar.set_cookie(cookie)

Set a Cookie, without checking with policy to see whether or not it should be set.

CookieJar.clear([domain[, path[, name]]])

Clear some cookies.

If invoked without arguments, clear all cookies. If given a single argument, only cookies belonging to that domain will be removed. If given two arguments, cookies belonging to the specified domain and URL path are removed. If given three arguments, then the cookie with the specified domain, path and name is removed.

Raises KeyError if no matching cookie exists.

CookieJar.clear_session_cookies()

Discard all session cookies.

Discards all contained cookies that have a true discard attribute (usually because they had either no max-age or expires cookie-attribute, or an explicit discard cookie-attribute). For interactive browsers, the end of a session usually corresponds to closing the browser window.

Note that the save() method won’t save session cookies anyway, unless you ask otherwise by passing a true ignore_discard argument.

FileCookieJar implements the following additional methods:

FileCookieJar.save(filename=None, ignore_discard=False, ignore_expires=False)

Save cookies to a file.

This base class raises NotImplementedError. Subclasses may leave this method unimplemented.

filename is the name of file in which to save cookies. If filename is not specified, self.filename is used (whose default is the value passed to the constructor, if any); if self.filename is None, ValueError is raised.

ignore_discard: save even cookies set to be discarded. ignore_expires: save even cookies that have expired

The file is overwritten if it already exists, thus wiping all the cookies it contains. Saved cookies can be restored later using the load() or revert() methods.

FileCookieJar.load(filename=None, ignore_discard=False, ignore_expires=False)

Load cookies from a file.

Old cookies are kept unless overwritten by newly loaded ones.

Arguments are as for save().

The named file must be in the format understood by the class, or LoadError will be raised. Also, OSError may be raised, for example if the file does not exist.

버전 3.3에서 변경: IOError used to be raised, it is now an alias of OSError.

FileCookieJar.revert(filename=None, ignore_discard=False, ignore_expires=False)

Clear all cookies and reload cookies from a saved file.

revert() can raise the same exceptions as load(). If there is a failure, the object’s state will not be altered.

FileCookieJar instances have the following public attributes:

FileCookieJar.filename

Filename of default file in which to keep cookies. This attribute may be assigned to.

FileCookieJar.delayload

If true, load cookies lazily from disk. This attribute should not be assigned to. This is only a hint, since this only affects performance, not behaviour (unless the cookies on disk are changing). A CookieJar object may ignore it. None of the FileCookieJar classes included in the standard library lazily loads cookies.

FileCookieJar subclasses and co-operation with web browsers

The following CookieJar subclasses are provided for reading and writing.

class http.cookiejar.MozillaCookieJar(filename, delayload=None, policy=None)

A FileCookieJar that can load from and save cookies to disk in the Mozilla cookies.txt file format (which is also used by the Lynx and Netscape browsers).

참고

This loses information about RFC 2965 [https://tools.ietf.org/html/rfc2965.html] cookies, and also about newer or non-standard cookie-attributes such as port.

경고

Back up your cookies before saving if you have cookies whose loss / corruption would be inconvenient (there are some subtleties which may lead to slight changes in the file over a load / save round-trip).

Also note that cookies saved while Mozilla is running will get clobbered by Mozilla.

class http.cookiejar.LWPCookieJar(filename, delayload=None, policy=None)

A FileCookieJar that can load from and save cookies to disk in format compatible with the libwww-perl library’s Set-Cookie3 file format. This is convenient if you want to store cookies in a human-readable file.

CookiePolicy Objects

Objects implementing the CookiePolicy interface have the following methods:

CookiePolicy.set_ok(cookie, request)

Return boolean value indicating whether cookie should be accepted from server.

cookie is a Cookie instance. request is an object implementing the interface defined by the documentation for CookieJar.extract_cookies().

CookiePolicy.return_ok(cookie, request)

Return boolean value indicating whether cookie should be returned to server.

cookie is a Cookie instance. request is an object implementing the interface defined by the documentation for CookieJar.add_cookie_header().

CookiePolicy.domain_return_ok(domain, request)

Return False if cookies should not be returned, given cookie domain.

This method is an optimization. It removes the need for checking every cookie with a particular domain (which might involve reading many files). Returning true from domain_return_ok() and path_return_ok() leaves all the work to return_ok().

If domain_return_ok() returns true for the cookie domain, path_return_ok() is called for the cookie path. Otherwise, path_return_ok() and return_ok() are never called for that cookie domain. If path_return_ok() returns true, return_ok() is called with the Cookie object itself for a full check. Otherwise, return_ok() is never called for that cookie path.

Note that domain_return_ok() is called for every cookie domain, not just for the request domain. For example, the function might be called with both ".example.com" and "www.example.com" if the request domain is "www.example.com". The same goes for path_return_ok().

The request argument is as documented for return_ok().

CookiePolicy.path_return_ok(path, request)

Return False if cookies should not be returned, given cookie path.

See the documentation for domain_return_ok().

In addition to implementing the methods above, implementations of the CookiePolicy interface must also supply the following attributes, indicating which protocols should be used, and how. All of these attributes may be assigned to.

CookiePolicy.netscape

Implement Netscape protocol.

CookiePolicy.rfc2965

Implement RFC 2965 [https://tools.ietf.org/html/rfc2965.html] protocol.

CookiePolicy.hide_cookie2

Don’t add Cookie2 header to requests (the presence of this header indicates to the server that we understand RFC 2965 [https://tools.ietf.org/html/rfc2965.html] cookies).

The most useful way to define a CookiePolicy class is by subclassing from DefaultCookiePolicy and overriding some or all of the methods above. CookiePolicy itself may be used as a ‘null policy’ to allow setting and receiving any and all cookies (this is unlikely to be useful).

DefaultCookiePolicy Objects

Implements the standard rules for accepting and returning cookies.

Both RFC 2965 [https://tools.ietf.org/html/rfc2965.html] and Netscape cookies are covered. RFC 2965 handling is switched off by default.

The easiest way to provide your own policy is to override this class and call its methods in your overridden implementations before adding your own additional checks:

import http.cookiejar
class MyCookiePolicy(http.cookiejar.DefaultCookiePolicy):
    def set_ok(self, cookie, request):
        if not http.cookiejar.DefaultCookiePolicy.set_ok(self, cookie, request):
            return False
        if i_dont_want_to_store_this_cookie(cookie):
            return False
        return True

In addition to the features required to implement the CookiePolicy interface, this class allows you to block and allow domains from setting and receiving cookies. There are also some strictness switches that allow you to tighten up the rather loose Netscape protocol rules a little bit (at the cost of blocking some benign cookies).

A domain blacklist and whitelist is provided (both off by default). Only domains not in the blacklist and present in the whitelist (if the whitelist is active) participate in cookie setting and returning. Use the blocked_domains constructor argument, and blocked_domains() and set_blocked_domains() methods (and the corresponding argument and methods for allowed_domains). If you set a whitelist, you can turn it off again by setting it to None.

Domains in block or allow lists that do not start with a dot must equal the cookie domain to be matched. For example, "example.com" matches a blacklist entry of "example.com", but "www.example.com" does not. Domains that do start with a dot are matched by more specific domains too. For example, both "www.example.com" and "www.coyote.example.com" match ".example.com" (but "example.com" itself does not). IP addresses are an exception, and must match exactly. For example, if blocked_domains contains "192.168.1.2" and ".168.1.2", 192.168.1.2 is blocked, but 193.168.1.2 is not.

DefaultCookiePolicy implements the following additional methods:

DefaultCookiePolicy.blocked_domains()

Return the sequence of blocked domains (as a tuple).

DefaultCookiePolicy.set_blocked_domains(blocked_domains)

Set the sequence of blocked domains.

DefaultCookiePolicy.is_blocked(domain)

Return whether domain is on the blacklist for setting or receiving cookies.

DefaultCookiePolicy.allowed_domains()

Return None, or the sequence of allowed domains (as a tuple).

DefaultCookiePolicy.set_allowed_domains(allowed_domains)

Set the sequence of allowed domains, or None.

DefaultCookiePolicy.is_not_allowed(domain)

Return whether domain is not on the whitelist for setting or receiving cookies.

DefaultCookiePolicy instances have the following attributes, which are all initialised from the constructor arguments of the same name, and which may all be assigned to.

DefaultCookiePolicy.rfc2109_as_netscape

If true, request that the CookieJar instance downgrade RFC 2109 [https://tools.ietf.org/html/rfc2109.html] cookies (ie. cookies received in a Set-Cookie header with a version cookie-attribute of 1) to Netscape cookies by setting the version attribute of the Cookie instance to 0. The default value is None, in which case RFC 2109 cookies are downgraded if and only if RFC 2965 [https://tools.ietf.org/html/rfc2965.html] handling is turned off. Therefore, RFC 2109 cookies are downgraded by default.

General strictness switches:

DefaultCookiePolicy.strict_domain

Don’t allow sites to set two-component domains with country-code top-level domains like .co.uk, .gov.uk, .co.nz.etc. This is far from perfect and isn’t guaranteed to work!

RFC 2965 [https://tools.ietf.org/html/rfc2965.html] protocol strictness switches:

DefaultCookiePolicy.strict_rfc2965_unverifiable

Follow RFC 2965 [https://tools.ietf.org/html/rfc2965.html] rules on unverifiable transactions (usually, an unverifiable transaction is one resulting from a redirect or a request for an image hosted on another site). If this is false, cookies are never blocked on the basis of verifiability

Netscape protocol strictness switches:

DefaultCookiePolicy.strict_ns_unverifiable

Apply RFC 2965 [https://tools.ietf.org/html/rfc2965.html] rules on unverifiable transactions even to Netscape cookies.

DefaultCookiePolicy.strict_ns_domain

Flags indicating how strict to be with domain-matching rules for Netscape cookies. See below for acceptable values.

DefaultCookiePolicy.strict_ns_set_initial_dollar

Ignore cookies in Set-Cookie: headers that have names starting with '$'.

DefaultCookiePolicy.strict_ns_set_path

Don’t allow setting cookies whose path doesn’t path-match request URI.

strict_ns_domain is a collection of flags. Its value is constructed by or-ing together (for example, DomainStrictNoDots|DomainStrictNonDomain means both flags are set).

DefaultCookiePolicy.DomainStrictNoDots

When setting cookies, the ‘host prefix’ must not contain a dot (eg. www.foo.bar.com can’t set a cookie for .bar.com, because www.foo contains a dot).

DefaultCookiePolicy.DomainStrictNonDomain

Cookies that did not explicitly specify a domain cookie-attribute can only be returned to a domain equal to the domain that set the cookie (eg. spam.example.com won’t be returned cookies from example.com that had no domain cookie-attribute).

DefaultCookiePolicy.DomainRFC2965Match

When setting cookies, require a full RFC 2965 [https://tools.ietf.org/html/rfc2965.html] domain-match.

The following attributes are provided for convenience, and are the most useful combinations of the above flags:

DefaultCookiePolicy.DomainLiberal

Equivalent to 0 (ie. all of the above Netscape domain strictness flags switched off).

DefaultCookiePolicy.DomainStrict

Equivalent to DomainStrictNoDots|DomainStrictNonDomain.

Cookie Objects

Cookie instances have Python attributes roughly corresponding to the standard cookie-attributes specified in the various cookie standards. The correspondence is not one-to-one, because there are complicated rules for assigning default values, because the max-age and expires cookie-attributes contain equivalent information, and because RFC 2109 [https://tools.ietf.org/html/rfc2109.html] cookies may be ‘downgraded’ by http.cookiejar from version 1 to version 0 (Netscape) cookies.

Assignment to these attributes should not be necessary other than in rare circumstances in a CookiePolicy method. The class does not enforce internal consistency, so you should know what you’re doing if you do that.

Cookie.version

Integer or None. Netscape cookies have version 0. RFC 2965 [https://tools.ietf.org/html/rfc2965.html] and RFC 2109 [https://tools.ietf.org/html/rfc2109.html] cookies have a version cookie-attribute of 1. However, note that http.cookiejar may ‘downgrade’ RFC 2109 cookies to Netscape cookies, in which case version is 0.

Cookie.name

Cookie name (a string).

Cookie.value

Cookie value (a string), or None.

Cookie.port

String representing a port or a set of ports (eg. ‘80’, or ‘80,8080’), or None.

Cookie.path

Cookie path (a string, eg. '/acme/rocket_launchers').

Cookie.secure

True if cookie should only be returned over a secure connection.

Cookie.expires

Integer expiry date in seconds since epoch, or None. See also the is_expired() method.

Cookie.discard

True if this is a session cookie.

Cookie.comment

String comment from the server explaining the function of this cookie, or None.

Cookie.comment_url

URL linking to a comment from the server explaining the function of this cookie, or None.

Cookie.rfc2109

True if this cookie was received as an RFC 2109 [https://tools.ietf.org/html/rfc2109.html] cookie (ie. the cookie arrived in a Set-Cookie header, and the value of the Version cookie-attribute in that header was 1). This attribute is provided because http.cookiejar may ‘downgrade’ RFC 2109 cookies to Netscape cookies, in which case version is 0.

Cookie.port_specified

True if a port or set of ports was explicitly specified by the server (in the Set-Cookie / Set-Cookie2 header).

Cookie.domain_specified

True if a domain was explicitly specified by the server.

Cookie.domain_initial_dot

True if the domain explicitly specified by the server began with a dot ('.').

Cookies may have additional non-standard cookie-attributes. These may be accessed using the following methods:

Cookie.has_nonstandard_attr(name)

Return True if cookie has the named cookie-attribute.

Cookie.get_nonstandard_attr(name, default=None)

If cookie has the named cookie-attribute, return its value. Otherwise, return default.

Cookie.set_nonstandard_attr(name, value)

Set the value of the named cookie-attribute.

The Cookie class also defines the following method:

Cookie.is_expired(now=None)

True if cookie has passed the time at which the server requested it should expire. If now is given (in seconds since the epoch), return whether the cookie has expired at the specified time.

Examples

The first example shows the most common usage of http.cookiejar:

import http.cookiejar, urllib.request
cj = http.cookiejar.CookieJar()
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
r = opener.open("http://example.com/")

This example illustrates how to open a URL using your Netscape, Mozilla, or Lynx cookies (assumes Unix/Netscape convention for location of the cookies file):

import os, http.cookiejar, urllib.request
cj = http.cookiejar.MozillaCookieJar()
cj.load(os.path.join(os.path.expanduser("~"), ".netscape", "cookies.txt"))
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
r = opener.open("http://example.com/")

The next example illustrates the use of DefaultCookiePolicy. Turn on RFC 2965 [https://tools.ietf.org/html/rfc2965.html] cookies, be more strict about domains when setting and returning Netscape cookies, and block some domains from setting cookies or having them returned:

import urllib.request
from http.cookiejar import CookieJar, DefaultCookiePolicy
policy = DefaultCookiePolicy(
    rfc2965=True, strict_ns_domain=Policy.DomainStrict,
    blocked_domains=["ads.net", ".ads.net"])
cj = CookieJar(policy)
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
r = opener.open("http://example.com/")

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 프로토콜과 지원 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 프로토콜과 지원 »

|

xmlrpc — XMLRPC 서버와 클라이언트 모듈

XML-RPC는 HTTP를 트랜스포트로 사용해서 전달되는 XML을 사용하는 원격 프로시저 호출 방법입니다. 이를 통해, 클라이언트는 원격 서버(서버는 URI로 지정됩니다)의 매개 변수가 있는 메서드를 호출하고 구조화된 데이터를 받을 수 있습니다.

xmlrpc는 XML-RPC를 구현하는 서버와 클라이언트 모듈을 모아둔 패키지입니다. 모듈은 다음과 같습니다:

xmlrpc.client

xmlrpc.server

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 프로토콜과 지원 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 프로토콜과 지원 »

|

xmlrpc.client — XML-RPC client access

Source code: Lib/xmlrpc/client.py [https://github.com/python/cpython/tree/3.7/Lib/xmlrpc/client.py]

XML-RPC is a Remote Procedure Call method that uses XML passed via HTTP(S) as a transport. With it, a client can call methods with parameters on a remote server (the server is named by a URI) and get back structured data. This module supports writing XML-RPC client code; it handles all the details of translating between conformable Python objects and XML on the wire.

경고

The xmlrpc.client module is not secure against maliciously constructed data. If you need to parse untrusted or unauthenticated data see XML 취약점.

버전 3.5에서 변경: For HTTPS URIs, xmlrpc.client now performs all the necessary certificate and hostname checks by default.

class xmlrpc.client.ServerProxy(uri, transport=None, encoding=None, verbose=False, allow_none=False, use_datetime=False, use_builtin_types=False, *, context=None)

버전 3.3에서 변경: The use_builtin_types flag was added.

A ServerProxy instance is an object that manages communication with a remote XML-RPC server. The required first argument is a URI (Uniform Resource Indicator), and will normally be the URL of the server. The optional second argument is a transport factory instance; by default it is an internal SafeTransport instance for https: URLs and an internal HTTP Transport instance otherwise. The optional third argument is an encoding, by default UTF-8. The optional fourth argument is a debugging flag.

The following parameters govern the use of the returned proxy instance. If allow_none is true, the Python constant None will be translated into XML; the default behaviour is for None to raise a TypeError. This is a commonly-used extension to the XML-RPC specification, but isn’t supported by all clients and servers; see http://ontosys.com/xml-rpc/extensions.php [https://web.archive.org/web/20130120074804/http://ontosys.com/xml-rpc/extensions.php] for a description. The use_builtin_types flag can be used to cause date/time values to be presented as datetime.datetime objects and binary data to be presented as bytes objects; this flag is false by default. datetime.datetime, bytes and bytearray objects may be passed to calls. The obsolete use_datetime flag is similar to use_builtin_types but it applies only to date/time values.

Both the HTTP and HTTPS transports support the URL syntax extension for HTTP Basic Authentication: http://user:pass@host:port/path. The user:pass portion will be base64-encoded as an HTTP ‘Authorization’ header, and sent to the remote server as part of the connection process when invoking an XML-RPC method. You only need to use this if the remote server requires a Basic Authentication user and password. If an HTTPS URL is provided, context may be ssl.SSLContext and configures the SSL settings of the underlying HTTPS connection.

The returned instance is a proxy object with methods that can be used to invoke corresponding RPC calls on the remote server. If the remote server supports the introspection API, the proxy can also be used to query the remote server for the methods it supports (service discovery) and fetch other server-associated metadata.

Types that are conformable (e.g. that can be marshalled through XML), include the following (and except where noted, they are unmarshalled as the same Python type):

XML-RPC type

Python type

boolean

bool

int, i1, i2, i4, i8 or biginteger

int in range from -2147483648 to 2147483647. Values get the <int> tag.

double or float

float. Values get the <double> tag.

string

str

array

list or tuple containing conformable elements. Arrays are returned as lists.

struct

dict. Keys must be strings, values may be any conformable type. Objects of user-defined classes can be passed in; only their __dict__ attribute is transmitted.

dateTime.iso8601

DateTime or datetime.datetime. Returned type depends on values of use_builtin_types and use_datetime flags.

base64

Binary, bytes or bytearray. Returned type depends on the value of the use_builtin_types flag.

nil

The None constant. Passing is allowed only if allow_none is true.

bigdecimal

decimal.Decimal. Returned type only.

This is the full set of data types supported by XML-RPC. Method calls may also raise a special Fault instance, used to signal XML-RPC server errors, or ProtocolError used to signal an error in the HTTP/HTTPS transport layer. Both Fault and ProtocolError derive from a base class called Error. Note that the xmlrpc client module currently does not marshal instances of subclasses of built-in types.

When passing strings, characters special to XML such as <, >, and & will be automatically escaped. However, it’s the caller’s responsibility to ensure that the string is free of characters that aren’t allowed in XML, such as the control characters with ASCII values between 0 and 31 (except, of course, tab, newline and carriage return); failing to do this will result in an XML-RPC request that isn’t well-formed XML. If you have to pass arbitrary bytes via XML-RPC, use bytes or bytearray classes or the Binary wrapper class described below.

Server is retained as an alias for ServerProxy for backwards compatibility. New code should use ServerProxy.

버전 3.5에서 변경: Added the context argument.

버전 3.6에서 변경: Added support of type tags with prefixes (e.g. ex:nil). Added support of unmarshalling additional types used by Apache XML-RPC implementation for numerics: i1, i2, i8, biginteger, float and bigdecimal. See http://ws.apache.org/xmlrpc/types.html for a description.

더 보기

XML-RPC HOWTO [http://www.tldp.org/HOWTO/XML-RPC-HOWTO/index.html]

A good description of XML-RPC operation and client software in several languages. Contains pretty much everything an XML-RPC client developer needs to know.

XML-RPC Introspection [http://xmlrpc-c.sourceforge.net/introspection.html]

Describes the XML-RPC protocol extension for introspection.

XML-RPC Specification [http://xmlrpc.scripting.com/spec.html]

The official specification.

Unofficial XML-RPC Errata [http://effbot.org/zone/xmlrpc-errata.htm]

Fredrik Lundh’s “unofficial errata, intended to clarify certain details in the XML-RPC specification, as well as hint at ‘best practices’ to use when designing your own XML-RPC implementations.”

ServerProxy Objects

A ServerProxy instance has a method corresponding to each remote procedure call accepted by the XML-RPC server. Calling the method performs an RPC, dispatched by both name and argument signature (e.g. the same method name can be overloaded with multiple argument signatures). The RPC finishes by returning a value, which may be either returned data in a conformant type or a Fault or ProtocolError object indicating an error.

Servers that support the XML introspection API support some common methods grouped under the reserved system attribute:

ServerProxy.system.listMethods()

This method returns a list of strings, one for each (non-system) method supported by the XML-RPC server.

ServerProxy.system.methodSignature(name)

This method takes one parameter, the name of a method implemented by the XML-RPC server. It returns an array of possible signatures for this method. A signature is an array of types. The first of these types is the return type of the method, the rest are parameters.

Because multiple signatures (ie. overloading) is permitted, this method returns a list of signatures rather than a singleton.

Signatures themselves are restricted to the top level parameters expected by a method. For instance if a method expects one array of structs as a parameter, and it returns a string, its signature is simply “string, array”. If it expects three integers and returns a string, its signature is “string, int, int, int”.

If no signature is defined for the method, a non-array value is returned. In Python this means that the type of the returned value will be something other than list.

ServerProxy.system.methodHelp(name)

This method takes one parameter, the name of a method implemented by the XML-RPC server. It returns a documentation string describing the use of that method. If no such string is available, an empty string is returned. The documentation string may contain HTML markup.

버전 3.5에서 변경: Instances of ServerProxy support the context manager protocol for closing the underlying transport.

A working example follows. The server code:

from xmlrpc.server import SimpleXMLRPCServer

def is_even(n):
    return n % 2 == 0

server = SimpleXMLRPCServer(("localhost", 8000))
print("Listening on port 8000...")
server.register_function(is_even, "is_even")
server.serve_forever()

The client code for the preceding server:

import xmlrpc.client

with xmlrpc.client.ServerProxy("http://localhost:8000/") as proxy:
    print("3 is even: %s" % str(proxy.is_even(3)))
    print("100 is even: %s" % str(proxy.is_even(100)))

DateTime Objects

class xmlrpc.client.DateTime

This class may be initialized with seconds since the epoch, a time tuple, an ISO 8601 time/date string, or a datetime.datetime instance. It has the following methods, supported mainly for internal use by the marshalling/unmarshalling code:

decode(string)

Accept a string as the instance’s new time value.

encode(out)

Write the XML-RPC encoding of this DateTime item to the out stream object.

It also supports certain of Python’s built-in operators through rich comparison and __repr__() methods.

A working example follows. The server code:

import datetime
from xmlrpc.server import SimpleXMLRPCServer
import xmlrpc.client

def today():
    today = datetime.datetime.today()
    return xmlrpc.client.DateTime(today)

server = SimpleXMLRPCServer(("localhost", 8000))
print("Listening on port 8000...")
server.register_function(today, "today")
server.serve_forever()

The client code for the preceding server:

import xmlrpc.client
import datetime

proxy = xmlrpc.client.ServerProxy("http://localhost:8000/")

today = proxy.today()
# convert the ISO8601 string to a datetime object
converted = datetime.datetime.strptime(today.value, "%Y%m%dT%H:%M:%S")
print("Today: %s" % converted.strftime("%d.%m.%Y, %H:%M"))

Binary Objects

class xmlrpc.client.Binary

This class may be initialized from bytes data (which may include NULs). The primary access to the content of a Binary object is provided by an attribute:

data

The binary data encapsulated by the Binary instance. The data is provided as a bytes object.

Binary objects have the following methods, supported mainly for internal use by the marshalling/unmarshalling code:

decode(bytes)

Accept a base64 bytes object and decode it as the instance’s new data.

encode(out)

Write the XML-RPC base 64 encoding of this binary item to the out stream object.

The encoded data will have newlines every 76 characters as per RFC 2045 section 6.8 [https://tools.ietf.org/html/rfc2045.html#section-6.8], which was the de facto standard base64 specification when the XML-RPC spec was written.

It also supports certain of Python’s built-in operators through __eq__() and __ne__() methods.

Example usage of the binary objects. We’re going to transfer an image over XMLRPC:

from xmlrpc.server import SimpleXMLRPCServer
import xmlrpc.client

def python_logo():
    with open("python_logo.jpg", "rb") as handle:
        return xmlrpc.client.Binary(handle.read())

server = SimpleXMLRPCServer(("localhost", 8000))
print("Listening on port 8000...")
server.register_function(python_logo, 'python_logo')

server.serve_forever()

The client gets the image and saves it to a file:

import xmlrpc.client

proxy = xmlrpc.client.ServerProxy("http://localhost:8000/")
with open("fetched_python_logo.jpg", "wb") as handle:
    handle.write(proxy.python_logo().data)

Fault Objects

class xmlrpc.client.Fault

A Fault object encapsulates the content of an XML-RPC fault tag. Fault objects have the following attributes:

faultCode

A string indicating the fault type.

faultString

A string containing a diagnostic message associated with the fault.

In the following example we’re going to intentionally cause a Fault by returning a complex type object. The server code:

from xmlrpc.server import SimpleXMLRPCServer

# A marshalling error is going to occur because we're returning a
# complex number
def add(x, y):
    return x+y+0j

server = SimpleXMLRPCServer(("localhost", 8000))
print("Listening on port 8000...")
server.register_function(add, 'add')

server.serve_forever()

The client code for the preceding server:

import xmlrpc.client

proxy = xmlrpc.client.ServerProxy("http://localhost:8000/")
try:
    proxy.add(2, 5)
except xmlrpc.client.Fault as err:
    print("A fault occurred")
    print("Fault code: %d" % err.faultCode)
    print("Fault string: %s" % err.faultString)

ProtocolError Objects

class xmlrpc.client.ProtocolError

A ProtocolError object describes a protocol error in the underlying transport layer (such as a 404 ‘not found’ error if the server named by the URI does not exist). It has the following attributes:

url

The URI or URL that triggered the error.

errcode

The error code.

errmsg

The error message or diagnostic string.

headers

A dict containing the headers of the HTTP/HTTPS request that triggered the error.

In the following example we’re going to intentionally cause a ProtocolError by providing an invalid URI:

import xmlrpc.client

# create a ServerProxy with a URI that doesn't respond to XMLRPC requests
proxy = xmlrpc.client.ServerProxy("http://google.com/")

try:
    proxy.some_method()
except xmlrpc.client.ProtocolError as err:
    print("A protocol error occurred")
    print("URL: %s" % err.url)
    print("HTTP/HTTPS headers: %s" % err.headers)
    print("Error code: %d" % err.errcode)
    print("Error message: %s" % err.errmsg)

MultiCall Objects

The MultiCall object provides a way to encapsulate multiple calls to a remote server into a single request 1.

class xmlrpc.client.MultiCall(server)

Create an object used to boxcar method calls. server is the eventual target of the call. Calls can be made to the result object, but they will immediately return None, and only store the call name and parameters in the MultiCall object. Calling the object itself causes all stored calls to be transmitted as a single system.multicall request. The result of this call is a generator; iterating over this generator yields the individual results.

A usage example of this class follows. The server code:

from xmlrpc.server import SimpleXMLRPCServer

def add(x, y):
    return x + y

def subtract(x, y):
    return x - y

def multiply(x, y):
    return x * y

def divide(x, y):
    return x // y

# A simple server with simple arithmetic functions
server = SimpleXMLRPCServer(("localhost", 8000))
print("Listening on port 8000...")
server.register_multicall_functions()
server.register_function(add, 'add')
server.register_function(subtract, 'subtract')
server.register_function(multiply, 'multiply')
server.register_function(divide, 'divide')
server.serve_forever()

The client code for the preceding server:

import xmlrpc.client

proxy = xmlrpc.client.ServerProxy("http://localhost:8000/")
multicall = xmlrpc.client.MultiCall(proxy)
multicall.add(7, 3)
multicall.subtract(7, 3)
multicall.multiply(7, 3)
multicall.divide(7, 3)
result = multicall()

print("7+3=%d, 7-3=%d, 7*3=%d, 7//3=%d" % tuple(result))

Convenience Functions

xmlrpc.client.dumps(params, methodname=None, methodresponse=None, encoding=None, allow_none=False)

Convert params into an XML-RPC request. or into a response if methodresponse is true. params can be either a tuple of arguments or an instance of the Fault exception class. If methodresponse is true, only a single value can be returned, meaning that params must be of length 1. encoding, if supplied, is the encoding to use in the generated XML; the default is UTF-8. Python’s None value cannot be used in standard XML-RPC; to allow using it via an extension, provide a true value for allow_none.

xmlrpc.client.loads(data, use_datetime=False, use_builtin_types=False)

Convert an XML-RPC request or response into Python objects, a (params, methodname). params is a tuple of argument; methodname is a string, or None if no method name is present in the packet. If the XML-RPC packet represents a fault condition, this function will raise a Fault exception. The use_builtin_types flag can be used to cause date/time values to be presented as datetime.datetime objects and binary data to be presented as bytes objects; this flag is false by default.

The obsolete use_datetime flag is similar to use_builtin_types but it applies only to date/time values.

버전 3.3에서 변경: The use_builtin_types flag was added.

Example of Client Usage

# simple test program (from the XML-RPC specification)
from xmlrpc.client import ServerProxy, Error

# server = ServerProxy("http://localhost:8000") # local server
with ServerProxy("http://betty.userland.com") as proxy:

    print(proxy)

    try:
        print(proxy.examples.getStateName(41))
    except Error as v:
        print("ERROR", v)

To access an XML-RPC server through a HTTP proxy, you need to define a custom transport. The following example shows how:

import http.client
import xmlrpc.client

class ProxiedTransport(xmlrpc.client.Transport):

    def set_proxy(self, host, port=None, headers=None):
        self.proxy = host, port
        self.proxy_headers = headers

    def make_connection(self, host):
        connection = http.client.HTTPConnection(*self.proxy)
        connection.set_tunnel(host, headers=self.proxy_headers)
        self._connection = host, connection
        return connection

transport = ProxiedTransport()
transport.set_proxy('proxy-server', 8080)
server = xmlrpc.client.ServerProxy('http://betty.userland.com', transport=transport)
print(server.examples.getStateName(41))

Example of Client and Server Usage

See SimpleXMLRPCServer 예제.

Footnotes

1

This approach has been first presented in a discussion on xmlrpc.com [https://web.archive.org/web/20060624230303/http://www.xmlrpc.com/discuss/msgReader$1208?mode=topic].

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 프로토콜과 지원 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 프로토콜과 지원 »

|

xmlrpc.server — 기본 XML-RPC 서버

소스 코드: Lib/xmlrpc/server.py [https://github.com/python/cpython/tree/3.7/Lib/xmlrpc/server.py]

xmlrpc.server 모듈은 파이썬으로 작성된 XML-RPC 서버를 위한 기본 서버 프레임워크를 제공합니다. 서버는 SimpleXMLRPCServer를 사용하여 독립적이거나, CGIXMLRPCRequestHandler를 사용하여 CGI 환경에 내장될 수 있습니다.

경고

xmlrpc.server 모듈은 악의적으로 구성된 데이터로부터 안전하지 않습니다. 신뢰할 수 없거나 인증되지 않은 데이터를 구문 분석해야 한다면 XML 취약점를 참조하십시오.

class xmlrpc.server.SimpleXMLRPCServer(addr, requestHandler=SimpleXMLRPCRequestHandler, logRequests=True, allow_none=False, encoding=None, bind_and_activate=True, use_builtin_types=False)

새 서버 인스턴스를 만듭니다. 이 클래스는 XML-RPC 프로토콜에 의해 호출될 수 있는 함수를 등록하는 메서드를 제공합니다. requestHandler 매개 변수는 요청 처리기 인스턴스의 팩토리여야 합니다; 기본값은 SimpleXMLRPCRequestHandler 입니다. addr과 requestHandler 매개 변수는 socketserver.TCPServer 생성자에 전달됩니다. logRequests가 참(기본값)이면, 요청이 로그 됩니다; 이 매개 변수를 거짓으로 설정하면 로깅이 해제됩니다. allow_none과 encoding 매개 변수는 xmlrpc.client로 전달되고 서버에서 반환될 XML-RPC 응답을 제어합니다. bind_and_activate 매개 변수는 생성자가 server_bind()와 server_activate()를 즉시 호출하는지를 제어합니다; 기본값은 참입니다. 이를 거짓으로 설정하면 코드가 주소가 바인드되기 전에 allow_reuse_address 클래스 변수를 조작할 수 있습니다. use_builtin_types 매개 변수는 loads() 함수로 전달되며 날짜/시간 값이나 바이너리 데이터가 수신될 때 처리되는 형을 제어합니다; 기본값은 거짓입니다.

버전 3.3에서 변경: use_builtin_types 플래그가 추가되었습니다.

class xmlrpc.server.CGIXMLRPCRequestHandler(allow_none=False, encoding=None, use_builtin_types=False)

CGI 환경에서 XML-RPC 요청을 처리할 새 인스턴스를 만듭니다. allow_none과 encoding 매개 변수는 xmlrpc.client로 전달되고 서버에서 반환될 XML-RPC 응답을 제어합니다. use_builtin_types 매개 변수는 loads() 함수로 전달되며 날짜/시간 값이나 바이너리 데이터가 수신될 때 처리되는 형을 제어합니다; 기본값은 거짓입니다.

버전 3.3에서 변경: use_builtin_types 플래그가 추가되었습니다.

class xmlrpc.server.SimpleXMLRPCRequestHandler

새 요청 처리기 인스턴스를 만듭니다. 이 요청 처리기는 POST 요청을 지원하고 SimpleXMLRPCServer 생성자 매개 변수에 대한 logRequests 매개 변수가 적용되도록 로깅을 수정합니다.

SimpleXMLRPCServer 객체

SimpleXMLRPCServer 클래스는 socketserver.TCPServer를 기반으로 하며 간단한 독립형 XML-RPC 서버를 작성하는 수단을 제공합니다.

SimpleXMLRPCServer.register_function(function=None, name=None)

XML-RPC 요청에 응답할 수 있는 함수를 등록합니다. name이 제공되면, function과 연결되는 메서드 이름이 되고, 그렇지 않으면 function.__name__이 사용됩니다. name은 문자열이며 마침표 문자를 포함하여 파이썬 식별자에서 유효하지 않은 문자를 포함할 수 있습니다.

이 메서드는 데코레이터로도 사용할 수 있습니다. 데코레이터로 사용될 때, name은 function을 name으로 등록하기 위해 키워드 인자로만 제공될 수 있습니다. name을 제공하지 않으면, function.__name__이 사용됩니다.

버전 3.7에서 변경: register_function()은 데코레이터로 사용할 수 있습니다.

SimpleXMLRPCServer.register_instance(instance, allow_dotted_names=False)

register_function()을 사용하여 등록되지 않은 메서드 이름을 노출하는데 사용되는 객체를 등록합니다. instance가 _dispatch() 메서드를 포함하면, 요청된 메서드 이름과 요청의 매개 변수로 호출됩니다. API는 def _dispatch(self, method, params)입니다 (params가 가변 인자 목록을 나타내지 않음에 유의하십시오). 이것이 작업을 수행하기 위해 하부 함수를 호출하면, 해당 함수를 매개 변수 리스트를 확장하여 func(*params)로 호출합니다. _dispatch()의 반환 값이 클라이언트에 결과로 반환됩니다. instance에 _dispatch() 메서드가 없으면, 요청된 메서드의 이름과 일치하는 어트리뷰트를 검색합니다.

선택적 allow_dotted_names 인자가 참이고 인스턴스에 _dispatch() 메서드가 없으면, 요청된 메서드 이름에 마침표가 포함될 때, 메서드 이름의 각 구성 요소가 개별적으로 검색되어, 간단한 계층 구조 검색이 수행되는 효과를 줍니다. 이 검색에서 찾은 값은 요청의 매개 변수로 호출되며 반환 값은 클라이언트로 다시 전달됩니다.

경고

allow_dotted_names 옵션을 활성화하면 침입자가 모듈의 전역 변수에 액세스할 수 있으며 침입자가 여러분의 기계에서 임의의 코드를 실행할 수 있습니다. 안전한 폐쇄 네트워크에서만 이 옵션을 사용하십시오.

SimpleXMLRPCServer.register_introspection_functions()

XML-RPC 내부 검사 함수 system.listMethods, system.methodHelp 및 system.methodSignature를 등록합니다.

SimpleXMLRPCServer.register_multicall_functions()

XML-RPC 다중 호출(multicall) 함수 system.multicall을 등록합니다.

SimpleXMLRPCRequestHandler.rpc_paths

XML-RPC 요청을 수신하기 위한 URL의 유효한 경로 부분을 나열하는 튜플이어야 하는 어트리뷰트 값. 다른 경로로 들어오는 요청은 404 “no such page” HTTP 에러를 발생시킵니다. 이 튜플이 비어 있으면, 모든 경로를 유효한 것으로 간주합니다. 기본값은 ('/', '/RPC2')입니다.

SimpleXMLRPCServer 예제

서버 코드:

from xmlrpc.server import SimpleXMLRPCServer
from xmlrpc.server import SimpleXMLRPCRequestHandler

# Restrict to a particular path.
class RequestHandler(SimpleXMLRPCRequestHandler):
    rpc_paths = ('/RPC2',)

# Create server
with SimpleXMLRPCServer(('localhost', 8000),
                        requestHandler=RequestHandler) as server:
    server.register_introspection_functions()

    # Register pow() function; this will use the value of
    # pow.__name__ as the name, which is just 'pow'.
    server.register_function(pow)

    # Register a function under a different name
    def adder_function(x, y):
        return x + y
    server.register_function(adder_function, 'add')

    # Register an instance; all the methods of the instance are
    # published as XML-RPC methods (in this case, just 'mul').
    class MyFuncs:
        def mul(self, x, y):
            return x * y

    server.register_instance(MyFuncs())

    # Run the server's main loop
    server.serve_forever()

다음 클라이언트 코드는 앞의 서버가 제공하는 메서드를 호출합니다:

import xmlrpc.client

s = xmlrpc.client.ServerProxy('http://localhost:8000')
print(s.pow(2,3))  # Returns 2**3 = 8
print(s.add(2,3))  # Returns 5
print(s.mul(5,2))  # Returns 5*2 = 10

# Print list of available methods
print(s.system.listMethods())

register_function()은 데코레이터로도 사용할 수 있습니다. 앞의 서버 예제에서 데코레이터 방식으로 함수를 등록할 수 있습니다:

from xmlrpc.server import SimpleXMLRPCServer
from xmlrpc.server import SimpleXMLRPCRequestHandler

class RequestHandler(SimpleXMLRPCRequestHandler):
    rpc_paths = ('/RPC2',)

with SimpleXMLRPCServer(('localhost', 8000),
                        requestHandler=RequestHandler) as server:
    server.register_introspection_functions()

    # Register pow() function; this will use the value of
    # pow.__name__ as the name, which is just 'pow'.
    server.register_function(pow)

    # Register a function under a different name, using
    # register_function as a decorator. *name* can only be given
    # as a keyword argument.
    @server.register_function(name='add')
    def adder_function(x, y):
        return x + y

    # Register a function under function.__name__.
    @server.register_function
    def mul(x, y):
        return x * y

    server.serve_forever()

Lib/xmlrpc/server.py 모듈에 포함된 다음 예는 점으로 구분된 이름을 허용하고 다중 호출 함수를 등록하는 서버를 보여줍니다.

경고

allow_dotted_names 옵션을 활성화하면 침입자가 모듈의 전역 변수에 액세스할 수 있으며 침입자가 여러분의 기계에서 임의의 코드를 실행할 수 있습니다. 이 예제는 안전한 폐쇄 네트워크 내에서만 사용하십시오.

import datetime

class ExampleService:
    def getData(self):
        return '42'

    class currentTime:
        @staticmethod
        def getCurrentTime():
            return datetime.datetime.now()

with SimpleXMLRPCServer(("localhost", 8000)) as server:
    server.register_function(pow)
    server.register_function(lambda x,y: x+y, 'add')
    server.register_instance(ExampleService(), allow_dotted_names=True)
    server.register_multicall_functions()
    print('Serving XML-RPC on localhost port 8000')
    try:
        server.serve_forever()
    except KeyboardInterrupt:
        print("\nKeyboard interrupt received, exiting.")
        sys.exit(0)

이 ExampleService 데모는 명령 줄에서 호출할 수 있습니다:

python -m xmlrpc.server

위 서버와 상호 작용하는 클라이언트는 Lib/xmlrpc/client.py에 포함되어 있습니다:

server = ServerProxy("http://localhost:8000")

try:
    print(server.currentTime.getCurrentTime())
except Error as v:
    print("ERROR", v)

multi = MultiCall(server)
multi.getData()
multi.pow(2,9)
multi.add(1,2)
try:
    for response in multi():
        print(response)
except Error as v:
    print("ERROR", v)

데모 XMLRPC 서버와 상호 작용하는 이 클라이언트는 다음과 같이 호출할 수 있습니다:

python -m xmlrpc.client

CGIXMLRPCRequestHandler

CGIXMLRPCRequestHandler 클래스는 파이썬 CGI 스크립트로 전송된 XML-RPC 요청을 처리하는 데 사용할 수 있습니다.

CGIXMLRPCRequestHandler.register_function(function=None, name=None)

XML-RPC 요청에 응답할 수 있는 함수를 등록합니다. name이 제공되면, function과 연결되는 메서드 이름이 되고, 그렇지 않으면 function.__name__이 사용됩니다. name은 문자열이며 마침표 문자를 포함하여 파이썬 식별자에서 유효하지 않은 문자를 포함할 수 있습니다.

이 메서드는 데코레이터로도 사용할 수 있습니다. 데코레이터로 사용될 때, name은 function을 name으로 등록하기 위해 키워드 인자로만 제공될 수 있습니다. name을 제공하지 않으면, function.__name__이 사용됩니다.

버전 3.7에서 변경: register_function()은 데코레이터로 사용할 수 있습니다.

CGIXMLRPCRequestHandler.register_instance(instance)

register_function()을 사용하여 등록되지 않은 메서드 이름을 노출하는데 사용되는 객체를 등록합니다. instance가 _dispatch() 메서드를 포함하면, 요청된 메서드 이름과 요청의 매개 변수로 호출됩니다; 반환 값이 클라이언트에 결과로 반환됩니다. instance에 _dispatch() 메서드가 없으면, 요청된 메서드의 이름과 일치하는 어트리뷰트를 검색합니다; 요청된 메서드 이름에 마침표가 포함될 때, 메서드 이름의 각 구성 요소가 개별적으로 검색되어, 간단한 계층 구조 검색이 수행되는 효과를 줍니다. 이 검색에서 찾은 값은 요청의 매개 변수로 호출되며 반환 값은 클라이언트로 다시 전달됩니다.

CGIXMLRPCRequestHandler.register_introspection_functions()

XML-RPC 내부 검사 함수 system.listMethods, system.methodHelp 및 system.methodSignature를 등록합니다.

CGIXMLRPCRequestHandler.register_multicall_functions()

XML-RPC 다중 호출(multicall) 함수 system.multicall을 등록합니다.

CGIXMLRPCRequestHandler.handle_request(request_text=None)

XML-RPC 요청을 처리합니다. request_text가 제공되면, HTTP 서버가 제공한 POST 데이터여야 합니다, 그렇지 않으면 stdin의 내용이 사용됩니다.

예:

class MyFuncs:
    def mul(self, x, y):
        return x * y

handler = CGIXMLRPCRequestHandler()
handler.register_function(pow)
handler.register_function(lambda x,y: x+y, 'add')
handler.register_introspection_functions()
handler.register_instance(MyFuncs())
handler.handle_request()

XMLRPC 서버 문서화

이 클래스들은 HTTP GET 요청에 대한 응답으로 HTML 설명서를 제공하기 위해 위의 클래스를 확장합니다. 서버는 DocXMLRPCServer를 사용하여 독립적이거나, DocCGIXMLRPCRequestHandler를 사용하여 CGI 환경에 내장될 수 있습니다.

class xmlrpc.server.DocXMLRPCServer(addr, requestHandler=DocXMLRPCRequestHandler, logRequests=True, allow_none=False, encoding=None, bind_and_activate=True, use_builtin_types=True)

새 서버 인스턴스를 만듭니다. 모든 매개 변수는 SimpleXMLRPCServer와 같은 의미입니다; requestHandler의 기본값은 DocXMLRPCRequestHandler 입니다.

버전 3.3에서 변경: use_builtin_types 플래그가 추가되었습니다.

class xmlrpc.server.DocCGIXMLRPCRequestHandler

CGI 환경에서 XML-RPC 요청을 처리할 새 인스턴스를 만듭니다.

class xmlrpc.server.DocXMLRPCRequestHandler

새 요청 처리기 인스턴스를 만듭니다. 이 요청 처리기는 XML-RPC POST 요청과 설명서 GET 요청을 지원하고, DocXMLRPCServer 생성자 매개 변수에 대한 logRequests 매개 변수가 적용되도록 로깅을 수정합니다.

DocXMLRPCServer 객체

DocXMLRPCServer 클래스는 SimpleXMLRPCServer 에서 파생되며 스스로 설명하는 독립형 XML-RPC 서버를 만드는 수단을 제공합니다. HTTP POST 요청은 XML-RPC 메서드 호출로 처리됩니다. HTTP GET 요청은 pydoc 스타일 HTML 문서를 생성하는 것으로 처리합니다. 이를 통해 서버는 자체 웹 기반 설명서를 제공할 수 있습니다.

DocXMLRPCServer.set_server_title(server_title)

생성된 HTML 설명서에 사용되는 제목을 설정합니다. 이 제목은 HTML “title” 요소 안에서 사용됩니다.

DocXMLRPCServer.set_server_name(server_name)

생성된 HTML 설명서에 사용되는 이름을 설정합니다. 이 이름은 설명서의 최상단의 “h1” 요소 안에 나타납니다.

DocXMLRPCServer.set_server_documentation(server_documentation)

생성된 HTML 설명서에 사용되는 설명을 설정합니다. 이 설명은 설명서에서 서버 이름 아래 단락으로 나타납니다.

DocCGIXMLRPCRequestHandler

DocCGIXMLRPCRequestHandler 클래스는 CGIXMLRPCRequestHandler 에서 파생되며 스스로 설명하는 XML-RPC CGI 스크립트를 만드는 수단을 제공합니다. HTTP POST 요청은 XML-RPC 메서드 호출로 처리됩니다. HTTP GET 요청은 pydoc 스타일 HTML 문서를 생성하는 것으로 처리합니다. 이를 통해 서버는 자체 웹 기반 설명서를 제공할 수 있습니다.

DocCGIXMLRPCRequestHandler.set_server_title(server_title)

생성된 HTML 설명서에 사용되는 제목을 설정합니다. 이 제목은 HTML “title” 요소 안에서 사용됩니다.

DocCGIXMLRPCRequestHandler.set_server_name(server_name)

생성된 HTML 설명서에 사용되는 이름을 설정합니다. 이 이름은 설명서의 최상단의 “h1” 요소 안에 나타납니다.

DocCGIXMLRPCRequestHandler.set_server_documentation(server_documentation)

생성된 HTML 설명서에 사용되는 설명을 설정합니다. 이 설명은 설명서에서 서버 이름 아래 단락으로 나타납니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 프로토콜과 지원 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 프로토콜과 지원 »

|

ipaddress — IPv4/IPv6 manipulation library

Source code: Lib/ipaddress.py [https://github.com/python/cpython/tree/3.7/Lib/ipaddress.py]

ipaddress provides the capabilities to create, manipulate and operate on IPv4 and IPv6 addresses and networks.

The functions and classes in this module make it straightforward to handle various tasks related to IP addresses, including checking whether or not two hosts are on the same subnet, iterating over all hosts in a particular subnet, checking whether or not a string represents a valid IP address or network definition, and so on.

This is the full module API reference—for an overview and introduction, see ipaddress 모듈에 대한 소개.

버전 3.3에 추가.

Convenience factory functions

The ipaddress module provides factory functions to conveniently create IP addresses, networks and interfaces:

ipaddress.ip_address(address)

Return an IPv4Address or IPv6Address object depending on the IP address passed as argument. Either IPv4 or IPv6 addresses may be supplied; integers less than 2**32 will be considered to be IPv4 by default. A ValueError is raised if address does not represent a valid IPv4 or IPv6 address.

>>> ipaddress.ip_address('192.168.0.1')
IPv4Address('192.168.0.1')
>>> ipaddress.ip_address('2001:db8::')
IPv6Address('2001:db8::')

ipaddress.ip_network(address, strict=True)

Return an IPv4Network or IPv6Network object depending on the IP address passed as argument. address is a string or integer representing the IP network. Either IPv4 or IPv6 networks may be supplied; integers less than 2**32 will be considered to be IPv4 by default. strict is passed to IPv4Network or IPv6Network constructor. A ValueError is raised if address does not represent a valid IPv4 or IPv6 address, or if the network has host bits set.

>>> ipaddress.ip_network('192.168.0.0/28')
IPv4Network('192.168.0.0/28')

ipaddress.ip_interface(address)

Return an IPv4Interface or IPv6Interface object depending on the IP address passed as argument. address is a string or integer representing the IP address. Either IPv4 or IPv6 addresses may be supplied; integers less than 2**32 will be considered to be IPv4 by default. A ValueError is raised if address does not represent a valid IPv4 or IPv6 address.

One downside of these convenience functions is that the need to handle both IPv4 and IPv6 formats means that error messages provide minimal information on the precise error, as the functions don’t know whether the IPv4 or IPv6 format was intended. More detailed error reporting can be obtained by calling the appropriate version specific class constructors directly.

IP Addresses

Address objects

The IPv4Address and IPv6Address objects share a lot of common attributes. Some attributes that are only meaningful for IPv6 addresses are also implemented by IPv4Address objects, in order to make it easier to write code that handles both IP versions correctly. Address objects are hashable, so they can be used as keys in dictionaries.

class ipaddress.IPv4Address(address)

Construct an IPv4 address. An AddressValueError is raised if address is not a valid IPv4 address.

The following constitutes a valid IPv4 address:

A string in decimal-dot notation, consisting of four decimal integers in the inclusive range 0–255, separated by dots (e.g. 192.168.0.1). Each integer represents an octet (byte) in the address. Leading zeroes are tolerated only for values less than 8 (as there is no ambiguity between the decimal and octal interpretations of such strings).

An integer that fits into 32 bits.

An integer packed into a bytes object of length 4 (most significant octet first).

>>> ipaddress.IPv4Address('192.168.0.1')
IPv4Address('192.168.0.1')
>>> ipaddress.IPv4Address(3232235521)
IPv4Address('192.168.0.1')
>>> ipaddress.IPv4Address(b'\xC0\xA8\x00\x01')
IPv4Address('192.168.0.1')

version

The appropriate version number: 4 for IPv4, 6 for IPv6.

max_prefixlen

The total number of bits in the address representation for this version: 32 for IPv4, 128 for IPv6.

The prefix defines the number of leading bits in an address that are compared to determine whether or not an address is part of a network.

compressed

exploded

The string representation in dotted decimal notation. Leading zeroes are never included in the representation.

As IPv4 does not define a shorthand notation for addresses with octets set to zero, these two attributes are always the same as str(addr) for IPv4 addresses. Exposing these attributes makes it easier to write display code that can handle both IPv4 and IPv6 addresses.

packed

The binary representation of this address - a bytes object of the appropriate length (most significant octet first). This is 4 bytes for IPv4 and 16 bytes for IPv6.

reverse_pointer

The name of the reverse DNS PTR record for the IP address, e.g.:

>>> ipaddress.ip_address("127.0.0.1").reverse_pointer
'1.0.0.127.in-addr.arpa'
>>> ipaddress.ip_address("2001:db8::1").reverse_pointer
'1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.8.b.d.0.1.0.0.2.ip6.arpa'

This is the name that could be used for performing a PTR lookup, not the resolved hostname itself.

버전 3.5에 추가.

is_multicast

True if the address is reserved for multicast use. See RFC 3171 [https://tools.ietf.org/html/rfc3171.html] (for IPv4) or RFC 2373 [https://tools.ietf.org/html/rfc2373.html] (for IPv6).

is_private

True if the address is allocated for private networks. See iana-ipv4-special-registry [https://www.iana.org/assignments/iana-ipv4-special-registry/iana-ipv4-special-registry.xhtml] (for IPv4) or iana-ipv6-special-registry [https://www.iana.org/assignments/iana-ipv6-special-registry/iana-ipv6-special-registry.xhtml] (for IPv6).

is_global

True if the address is allocated for public networks. See iana-ipv4-special-registry [https://www.iana.org/assignments/iana-ipv4-special-registry/iana-ipv4-special-registry.xhtml] (for IPv4) or iana-ipv6-special-registry [https://www.iana.org/assignments/iana-ipv6-special-registry/iana-ipv6-special-registry.xhtml] (for IPv6).

버전 3.4에 추가.

is_unspecified

True if the address is unspecified. See RFC 5735 [https://tools.ietf.org/html/rfc5735.html] (for IPv4) or RFC 2373 [https://tools.ietf.org/html/rfc2373.html] (for IPv6).

is_reserved

True if the address is otherwise IETF reserved.

is_loopback

True if this is a loopback address. See RFC 3330 [https://tools.ietf.org/html/rfc3330.html] (for IPv4) or RFC 2373 [https://tools.ietf.org/html/rfc2373.html] (for IPv6).

is_link_local

True if the address is reserved for link-local usage. See RFC 3927 [https://tools.ietf.org/html/rfc3927.html].

class ipaddress.IPv6Address(address)

Construct an IPv6 address. An AddressValueError is raised if address is not a valid IPv6 address.

The following constitutes a valid IPv6 address:

A string consisting of eight groups of four hexadecimal digits, each group representing 16 bits. The groups are separated by colons. This describes an exploded (longhand) notation. The string can also be compressed (shorthand notation) by various means. See RFC 4291 [https://tools.ietf.org/html/rfc4291.html] for details. For example, "0000:0000:0000:0000:0000:0abc:0007:0def" can be compressed to "::abc:7:def".

An integer that fits into 128 bits.

An integer packed into a bytes object of length 16, big-endian.

>>> ipaddress.IPv6Address('2001:db8::1000')
IPv6Address('2001:db8::1000')

compressed

The short form of the address representation, with leading zeroes in groups omitted and the longest sequence of groups consisting entirely of zeroes collapsed to a single empty group.

This is also the value returned by str(addr) for IPv6 addresses.

exploded

The long form of the address representation, with all leading zeroes and groups consisting entirely of zeroes included.

For the following attributes, see the corresponding documentation of the IPv4Address class:

packed

reverse_pointer

version

max_prefixlen

is_multicast

is_private

is_global

is_unspecified

is_reserved

is_loopback

is_link_local

버전 3.4에 추가: is_global

is_site_local

True if the address is reserved for site-local usage. Note that the site-local address space has been deprecated by RFC 3879 [https://tools.ietf.org/html/rfc3879.html]. Use is_private to test if this address is in the space of unique local addresses as defined by RFC 4193 [https://tools.ietf.org/html/rfc4193.html].

ipv4_mapped

For addresses that appear to be IPv4 mapped addresses (starting with ::FFFF/96), this property will report the embedded IPv4 address. For any other address, this property will be None.

sixtofour

For addresses that appear to be 6to4 addresses (starting with 2002::/16) as defined by RFC 3056 [https://tools.ietf.org/html/rfc3056.html], this property will report the embedded IPv4 address. For any other address, this property will be None.

teredo

For addresses that appear to be Teredo addresses (starting with 2001::/32) as defined by RFC 4380 [https://tools.ietf.org/html/rfc4380.html], this property will report the embedded (server, client) IP address pair. For any other address, this property will be None.

Conversion to Strings and Integers

To interoperate with networking interfaces such as the socket module, addresses must be converted to strings or integers. This is handled using the str() and int() builtin functions:

>>> str(ipaddress.IPv4Address('192.168.0.1'))
'192.168.0.1'
>>> int(ipaddress.IPv4Address('192.168.0.1'))
3232235521
>>> str(ipaddress.IPv6Address('::1'))
'::1'
>>> int(ipaddress.IPv6Address('::1'))
1

Operators

Address objects support some operators. Unless stated otherwise, operators can only be applied between compatible objects (i.e. IPv4 with IPv4, IPv6 with IPv6).

Comparison operators

Address objects can be compared with the usual set of comparison operators. Some examples:

>>> IPv4Address('127.0.0.2') > IPv4Address('127.0.0.1')
True
>>> IPv4Address('127.0.0.2') == IPv4Address('127.0.0.1')
False
>>> IPv4Address('127.0.0.2') != IPv4Address('127.0.0.1')
True

Arithmetic operators

Integers can be added to or subtracted from address objects. Some examples:

>>> IPv4Address('127.0.0.2') + 3
IPv4Address('127.0.0.5')
>>> IPv4Address('127.0.0.2') - 3
IPv4Address('126.255.255.255')
>>> IPv4Address('255.255.255.255') + 1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ipaddress.AddressValueError: 4294967296 (>= 2**32) is not permitted as an IPv4 address

IP Network definitions

The IPv4Network and IPv6Network objects provide a mechanism for defining and inspecting IP network definitions. A network definition consists of a mask and a network address, and as such defines a range of IP addresses that equal the network address when masked (binary AND) with the mask. For example, a network definition with the mask 255.255.255.0 and the network address 192.168.1.0 consists of IP addresses in the inclusive range 192.168.1.0 to 192.168.1.255.

Prefix, net mask and host mask

There are several equivalent ways to specify IP network masks. A prefix /<nbits> is a notation that denotes how many high-order bits are set in the network mask. A net mask is an IP address with some number of high-order bits set. Thus the prefix /24 is equivalent to the net mask 255.255.255.0 in IPv4, or ffff:ff00:: in IPv6. In addition, a host mask is the logical inverse of a net mask, and is sometimes used (for example in Cisco access control lists) to denote a network mask. The host mask equivalent to /24 in IPv4 is 0.0.0.255.

Network objects

All attributes implemented by address objects are implemented by network objects as well. In addition, network objects implement additional attributes. All of these are common between IPv4Network and IPv6Network, so to avoid duplication they are only documented for IPv4Network. Network objects are hashable, so they can be used as keys in dictionaries.

class ipaddress.IPv4Network(address, strict=True)

Construct an IPv4 network definition. address can be one of the following:

A string consisting of an IP address and an optional mask, separated by a slash (/). The IP address is the network address, and the mask can be either a single number, which means it’s a prefix, or a string representation of an IPv4 address. If it’s the latter, the mask is interpreted as a net mask if it starts with a non-zero field, or as a host mask if it starts with a zero field, with the single exception of an all-zero mask which is treated as a net mask. If no mask is provided, it’s considered to be /32.

For example, the following address specifications are equivalent: 192.168.1.0/24, 192.168.1.0/255.255.255.0 and 192.168.1.0/0.0.0.255.

An integer that fits into 32 bits. This is equivalent to a single-address network, with the network address being address and the mask being /32.

An integer packed into a bytes object of length 4, big-endian. The interpretation is similar to an integer address.

A two-tuple of an address description and a netmask, where the address description is either a string, a 32-bits integer, a 4-bytes packed integer, or an existing IPv4Address object; and the netmask is either an integer representing the prefix length (e.g. 24) or a string representing the prefix mask (e.g. 255.255.255.0).

An AddressValueError is raised if address is not a valid IPv4 address. A NetmaskValueError is raised if the mask is not valid for an IPv4 address.

If strict is True and host bits are set in the supplied address, then ValueError is raised. Otherwise, the host bits are masked out to determine the appropriate network address.

Unless stated otherwise, all network methods accepting other network/address objects will raise TypeError if the argument’s IP version is incompatible to self.

버전 3.5에서 변경: Added the two-tuple form for the address constructor parameter.

version

max_prefixlen

Refer to the corresponding attribute documentation in IPv4Address.

is_multicast

is_private

is_unspecified

is_reserved

is_loopback

is_link_local

These attributes are true for the network as a whole if they are true for both the network address and the broadcast address.

network_address

The network address for the network. The network address and the prefix length together uniquely define a network.

broadcast_address

The broadcast address for the network. Packets sent to the broadcast address should be received by every host on the network.

hostmask

The host mask, as an IPv4Address object.

netmask

The net mask, as an IPv4Address object.

with_prefixlen

compressed

exploded

A string representation of the network, with the mask in prefix notation.

with_prefixlen and compressed are always the same as str(network). exploded uses the exploded form the network address.

with_netmask

A string representation of the network, with the mask in net mask notation.

with_hostmask

A string representation of the network, with the mask in host mask notation.

num_addresses

The total number of addresses in the network.

prefixlen

Length of the network prefix, in bits.

hosts()

Returns an iterator over the usable hosts in the network. The usable hosts are all the IP addresses that belong to the network, except the network address itself and the network broadcast address. For networks with a mask length of 31, the network address and network broadcast address are also included in the result.

>>> list(ip_network('192.0.2.0/29').hosts())
[IPv4Address('192.0.2.1'), IPv4Address('192.0.2.2'),
 IPv4Address('192.0.2.3'), IPv4Address('192.0.2.4'),
 IPv4Address('192.0.2.5'), IPv4Address('192.0.2.6')]
>>> list(ip_network('192.0.2.0/31').hosts())
[IPv4Address('192.0.2.0'), IPv4Address('192.0.2.1')]

overlaps(other)

True if this network is partly or wholly contained in other or other is wholly contained in this network.

address_exclude(network)

Computes the network definitions resulting from removing the given network from this one. Returns an iterator of network objects. Raises ValueError if network is not completely contained in this network.

>>> n1 = ip_network('192.0.2.0/28')
>>> n2 = ip_network('192.0.2.1/32')
>>> list(n1.address_exclude(n2))
[IPv4Network('192.0.2.8/29'), IPv4Network('192.0.2.4/30'),
 IPv4Network('192.0.2.2/31'), IPv4Network('192.0.2.0/32')]

subnets(prefixlen_diff=1, new_prefix=None)

The subnets that join to make the current network definition, depending on the argument values. prefixlen_diff is the amount our prefix length should be increased by. new_prefix is the desired new prefix of the subnets; it must be larger than our prefix. One and only one of prefixlen_diff and new_prefix must be set. Returns an iterator of network objects.

>>> list(ip_network('192.0.2.0/24').subnets())
[IPv4Network('192.0.2.0/25'), IPv4Network('192.0.2.128/25')]
>>> list(ip_network('192.0.2.0/24').subnets(prefixlen_diff=2))
[IPv4Network('192.0.2.0/26'), IPv4Network('192.0.2.64/26'),
 IPv4Network('192.0.2.128/26'), IPv4Network('192.0.2.192/26')]
>>> list(ip_network('192.0.2.0/24').subnets(new_prefix=26))
[IPv4Network('192.0.2.0/26'), IPv4Network('192.0.2.64/26'),
 IPv4Network('192.0.2.128/26'), IPv4Network('192.0.2.192/26')]
>>> list(ip_network('192.0.2.0/24').subnets(new_prefix=23))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
    raise ValueError('new prefix must be longer')
ValueError: new prefix must be longer
>>> list(ip_network('192.0.2.0/24').subnets(new_prefix=25))
[IPv4Network('192.0.2.0/25'), IPv4Network('192.0.2.128/25')]

supernet(prefixlen_diff=1, new_prefix=None)

The supernet containing this network definition, depending on the argument values. prefixlen_diff is the amount our prefix length should be decreased by. new_prefix is the desired new prefix of the supernet; it must be smaller than our prefix. One and only one of prefixlen_diff and new_prefix must be set. Returns a single network object.

>>> ip_network('192.0.2.0/24').supernet()
IPv4Network('192.0.2.0/23')
>>> ip_network('192.0.2.0/24').supernet(prefixlen_diff=2)
IPv4Network('192.0.0.0/22')
>>> ip_network('192.0.2.0/24').supernet(new_prefix=20)
IPv4Network('192.0.0.0/20')

subnet_of(other)

Return True if this network is a subnet of other.

>>> a = ip_network('192.168.1.0/24')
>>> b = ip_network('192.168.1.128/30')
>>> b.subnet_of(a)
True

버전 3.7에 추가.

supernet_of(other)

Return True if this network is a supernet of other.

>>> a = ip_network('192.168.1.0/24')
>>> b = ip_network('192.168.1.128/30')
>>> a.supernet_of(b)
True

버전 3.7에 추가.

compare_networks(other)

Compare this network to other. In this comparison only the network addresses are considered; host bits aren’t. Returns either -1, 0 or 1.

>>> ip_network('192.0.2.1/32').compare_networks(ip_network('192.0.2.2/32'))
-1
>>> ip_network('192.0.2.1/32').compare_networks(ip_network('192.0.2.0/32'))
1
>>> ip_network('192.0.2.1/32').compare_networks(ip_network('192.0.2.1/32'))
0

버전 3.7부터 폐지: It uses the same ordering and comparison algorithm as “<”, “==”, and “>”

class ipaddress.IPv6Network(address, strict=True)

Construct an IPv6 network definition. address can be one of the following:

A string consisting of an IP address and an optional prefix length, separated by a slash (/). The IP address is the network address, and the prefix length must be a single number, the prefix. If no prefix length is provided, it’s considered to be /128.

Note that currently expanded netmasks are not supported. That means 2001:db00::0/24 is a valid argument while 2001:db00::0/ffff:ff00:: not.

An integer that fits into 128 bits. This is equivalent to a single-address network, with the network address being address and the mask being /128.

An integer packed into a bytes object of length 16, big-endian. The interpretation is similar to an integer address.

A two-tuple of an address description and a netmask, where the address description is either a string, a 128-bits integer, a 16-bytes packed integer, or an existing IPv6Address object; and the netmask is an integer representing the prefix length.

An AddressValueError is raised if address is not a valid IPv6 address. A NetmaskValueError is raised if the mask is not valid for an IPv6 address.

If strict is True and host bits are set in the supplied address, then ValueError is raised. Otherwise, the host bits are masked out to determine the appropriate network address.

버전 3.5에서 변경: Added the two-tuple form for the address constructor parameter.

version

max_prefixlen

is_multicast

is_private

is_unspecified

is_reserved

is_loopback

is_link_local

network_address

broadcast_address

hostmask

netmask

with_prefixlen

compressed

exploded

with_netmask

with_hostmask

num_addresses

prefixlen

hosts()

Returns an iterator over the usable hosts in the network. The usable hosts are all the IP addresses that belong to the network, except the Subnet-Router anycast address. For networks with a mask length of 127, the Subnet-Router anycast address is also included in the result.

overlaps(other)

address_exclude(network)

subnets(prefixlen_diff=1, new_prefix=None)

supernet(prefixlen_diff=1, new_prefix=None)

subnet_of(other)

supernet_of(other)

compare_networks(other)

Refer to the corresponding attribute documentation in IPv4Network.

is_site_local

These attribute is true for the network as a whole if it is true for both the network address and the broadcast address.

Operators

Network objects support some operators. Unless stated otherwise, operators can only be applied between compatible objects (i.e. IPv4 with IPv4, IPv6 with IPv6).

Logical operators

Network objects can be compared with the usual set of logical operators. Network objects are ordered first by network address, then by net mask.

Iteration

Network objects can be iterated to list all the addresses belonging to the network. For iteration, all hosts are returned, including unusable hosts (for usable hosts, use the hosts() method). An example:

>>> for addr in IPv4Network('192.0.2.0/28'):
...     addr
...
IPv4Address('192.0.2.0')
IPv4Address('192.0.2.1')
IPv4Address('192.0.2.2')
IPv4Address('192.0.2.3')
IPv4Address('192.0.2.4')
IPv4Address('192.0.2.5')
IPv4Address('192.0.2.6')
IPv4Address('192.0.2.7')
IPv4Address('192.0.2.8')
IPv4Address('192.0.2.9')
IPv4Address('192.0.2.10')
IPv4Address('192.0.2.11')
IPv4Address('192.0.2.12')
IPv4Address('192.0.2.13')
IPv4Address('192.0.2.14')
IPv4Address('192.0.2.15')

Networks as containers of addresses

Network objects can act as containers of addresses. Some examples:

>>> IPv4Network('192.0.2.0/28')[0]
IPv4Address('192.0.2.0')
>>> IPv4Network('192.0.2.0/28')[15]
IPv4Address('192.0.2.15')
>>> IPv4Address('192.0.2.6') in IPv4Network('192.0.2.0/28')
True
>>> IPv4Address('192.0.3.6') in IPv4Network('192.0.2.0/28')
False

Interface objects

Interface objects are hashable, so they can be used as keys in dictionaries.

class ipaddress.IPv4Interface(address)

Construct an IPv4 interface. The meaning of address is as in the constructor of IPv4Network, except that arbitrary host addresses are always accepted.

IPv4Interface is a subclass of IPv4Address, so it inherits all the attributes from that class. In addition, the following attributes are available:

ip

The address (IPv4Address) without network information.

>>> interface = IPv4Interface('192.0.2.5/24')
>>> interface.ip
IPv4Address('192.0.2.5')

network

The network (IPv4Network) this interface belongs to.

>>> interface = IPv4Interface('192.0.2.5/24')
>>> interface.network
IPv4Network('192.0.2.0/24')

with_prefixlen

A string representation of the interface with the mask in prefix notation.

>>> interface = IPv4Interface('192.0.2.5/24')
>>> interface.with_prefixlen
'192.0.2.5/24'

with_netmask

A string representation of the interface with the network as a net mask.

>>> interface = IPv4Interface('192.0.2.5/24')
>>> interface.with_netmask
'192.0.2.5/255.255.255.0'

with_hostmask

A string representation of the interface with the network as a host mask.

>>> interface = IPv4Interface('192.0.2.5/24')
>>> interface.with_hostmask
'192.0.2.5/0.0.0.255'

class ipaddress.IPv6Interface(address)

Construct an IPv6 interface. The meaning of address is as in the constructor of IPv6Network, except that arbitrary host addresses are always accepted.

IPv6Interface is a subclass of IPv6Address, so it inherits all the attributes from that class. In addition, the following attributes are available:

ip

network

with_prefixlen

with_netmask

with_hostmask

Refer to the corresponding attribute documentation in IPv4Interface.

Operators

Interface objects support some operators. Unless stated otherwise, operators can only be applied between compatible objects (i.e. IPv4 with IPv4, IPv6 with IPv6).

Logical operators

Interface objects can be compared with the usual set of logical operators.

For equality comparison (== and !=), both the IP address and network must be the same for the objects to be equal. An interface will not compare equal to any address or network object.

For ordering (<, >, etc) the rules are different. Interface and address objects with the same IP version can be compared, and the address objects will always sort before the interface objects. Two interface objects are first compared by their networks and, if those are the same, then by their IP addresses.

Other Module Level Functions

The module also provides the following module level functions:

ipaddress.v4_int_to_packed(address)

Represent an address as 4 packed bytes in network (big-endian) order. address is an integer representation of an IPv4 IP address. A ValueError is raised if the integer is negative or too large to be an IPv4 IP address.

>>> ipaddress.ip_address(3221225985)
IPv4Address('192.0.2.1')
>>> ipaddress.v4_int_to_packed(3221225985)
b'\xc0\x00\x02\x01'

ipaddress.v6_int_to_packed(address)

Represent an address as 16 packed bytes in network (big-endian) order. address is an integer representation of an IPv6 IP address. A ValueError is raised if the integer is negative or too large to be an IPv6 IP address.

ipaddress.summarize_address_range(first, last)

Return an iterator of the summarized network range given the first and last IP addresses. first is the first IPv4Address or IPv6Address in the range and last is the last IPv4Address or IPv6Address in the range. A TypeError is raised if first or last are not IP addresses or are not of the same version. A ValueError is raised if last is not greater than first or if first address version is not 4 or 6.

>>> [ipaddr for ipaddr in ipaddress.summarize_address_range(
...    ipaddress.IPv4Address('192.0.2.0'),
...    ipaddress.IPv4Address('192.0.2.130'))]
[IPv4Network('192.0.2.0/25'), IPv4Network('192.0.2.128/31'), IPv4Network('192.0.2.130/32')]

ipaddress.collapse_addresses(addresses)

Return an iterator of the collapsed IPv4Network or IPv6Network objects. addresses is an iterator of IPv4Network or IPv6Network objects. A TypeError is raised if addresses contains mixed version objects.

>>> [ipaddr for ipaddr in
... ipaddress.collapse_addresses([ipaddress.IPv4Network('192.0.2.0/25'),
... ipaddress.IPv4Network('192.0.2.128/25')])]
[IPv4Network('192.0.2.0/24')]

ipaddress.get_mixed_type_key(obj)

Return a key suitable for sorting between networks and addresses. Address and Network objects are not sortable by default; they’re fundamentally different, so the expression:

IPv4Address('192.0.2.0') <= IPv4Network('192.0.2.0/24')

doesn’t make sense. There are some times however, where you may wish to have ipaddress sort these anyway. If you need to do this, you can use this function as the key argument to sorted().

obj is either a network or address object.

Custom Exceptions

To support more specific error reporting from class constructors, the module defines the following exceptions:

exception ipaddress.AddressValueError(ValueError)

Any value error related to the address.

exception ipaddress.NetmaskValueError(ValueError)

Any value error related to the net mask.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

인터넷 프로토콜과 지원 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

|

멀티미디어 서비스

이 장에서 설명하는 모듈은 주로 멀티미디어 응용 프로그램에 유용한 다양한 알고리즘 또는 인터페이스를 구현합니다. 가용성은 설치에 달려있습니다. 다음은 개요입니다:

audioop — Manipulate raw audio data

aifc — AIFF와 AIFC 파일 읽고 쓰기

sunau — Sun AU 파일 읽고 쓰기

AU_read 객체

AU_write 객체

wave — WAV 파일 읽고 쓰기

Wave_read 객체

Wave_write 객체

chunk — IFF 청크된 데이터 읽기

colorsys — 색 체계 간의 변환

imghdr — 이미지 유형 판단

sndhdr — 음향 파일 유형 판단

ossaudiodev — Access to OSS-compatible audio devices

Audio Device Objects

Mixer Device Objects

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

멀티미디어 서비스 »

|

audioop — Manipulate raw audio data

The audioop module contains some useful operations on sound fragments. It operates on sound fragments consisting of signed integer samples 8, 16, 24 or 32 bits wide, stored in bytes-like objects. All scalar items are integers, unless specified otherwise.

버전 3.4에서 변경: Support for 24-bit samples was added. All functions now accept any bytes-like object. String input now results in an immediate error.

This module provides support for a-LAW, u-LAW and Intel/DVI ADPCM encodings.

A few of the more complicated operations only take 16-bit samples, otherwise the sample size (in bytes) is always a parameter of the operation.

The module defines the following variables and functions:

exception audioop.error

This exception is raised on all errors, such as unknown number of bytes per sample, etc.

audioop.add(fragment1, fragment2, width)

Return a fragment which is the addition of the two samples passed as parameters. width is the sample width in bytes, either 1, 2, 3 or 4. Both fragments should have the same length. Samples are truncated in case of overflow.

audioop.adpcm2lin(adpcmfragment, width, state)

Decode an Intel/DVI ADPCM coded fragment to a linear fragment. See the description of lin2adpcm() for details on ADPCM coding. Return a tuple (sample, newstate) where the sample has the width specified in width.

audioop.alaw2lin(fragment, width)

Convert sound fragments in a-LAW encoding to linearly encoded sound fragments. a-LAW encoding always uses 8 bits samples, so width refers only to the sample width of the output fragment here.

audioop.avg(fragment, width)

Return the average over all samples in the fragment.

audioop.avgpp(fragment, width)

Return the average peak-peak value over all samples in the fragment. No filtering is done, so the usefulness of this routine is questionable.

audioop.bias(fragment, width, bias)

Return a fragment that is the original fragment with a bias added to each sample. Samples wrap around in case of overflow.

audioop.byteswap(fragment, width)

“Byteswap” all samples in a fragment and returns the modified fragment. Converts big-endian samples to little-endian and vice versa.

버전 3.4에 추가.

audioop.cross(fragment, width)

Return the number of zero crossings in the fragment passed as an argument.

audioop.findfactor(fragment, reference)

Return a factor F such that rms(add(fragment, mul(reference, -F))) is minimal, i.e., return the factor with which you should multiply reference to make it match as well as possible to fragment. The fragments should both contain 2-byte samples.

The time taken by this routine is proportional to len(fragment).

audioop.findfit(fragment, reference)

Try to match reference as well as possible to a portion of fragment (which should be the longer fragment). This is (conceptually) done by taking slices out of fragment, using findfactor() to compute the best match, and minimizing the result. The fragments should both contain 2-byte samples. Return a tuple (offset, factor) where offset is the (integer) offset into fragment where the optimal match started and factor is the (floating-point) factor as per findfactor().

audioop.findmax(fragment, length)

Search fragment for a slice of length length samples (not bytes!) with maximum energy, i.e., return i for which rms(fragment[i*2:(i+length)*2]) is maximal. The fragments should both contain 2-byte samples.

The routine takes time proportional to len(fragment).

audioop.getsample(fragment, width, index)

Return the value of sample index from the fragment.

audioop.lin2adpcm(fragment, width, state)

Convert samples to 4 bit Intel/DVI ADPCM encoding. ADPCM coding is an adaptive coding scheme, whereby each 4 bit number is the difference between one sample and the next, divided by a (varying) step. The Intel/DVI ADPCM algorithm has been selected for use by the IMA, so it may well become a standard.

state is a tuple containing the state of the coder. The coder returns a tuple (adpcmfrag, newstate), and the newstate should be passed to the next call of lin2adpcm(). In the initial call, None can be passed as the state. adpcmfrag is the ADPCM coded fragment packed 2 4-bit values per byte.

audioop.lin2alaw(fragment, width)

Convert samples in the audio fragment to a-LAW encoding and return this as a bytes object. a-LAW is an audio encoding format whereby you get a dynamic range of about 13 bits using only 8 bit samples. It is used by the Sun audio hardware, among others.

audioop.lin2lin(fragment, width, newwidth)

Convert samples between 1-, 2-, 3- and 4-byte formats.

참고

In some audio formats, such as .WAV files, 16, 24 and 32 bit samples are signed, but 8 bit samples are unsigned. So when converting to 8 bit wide samples for these formats, you need to also add 128 to the result:

new_frames = audioop.lin2lin(frames, old_width, 1)
new_frames = audioop.bias(new_frames, 1, 128)

The same, in reverse, has to be applied when converting from 8 to 16, 24 or 32 bit width samples.

audioop.lin2ulaw(fragment, width)

Convert samples in the audio fragment to u-LAW encoding and return this as a bytes object. u-LAW is an audio encoding format whereby you get a dynamic range of about 14 bits using only 8 bit samples. It is used by the Sun audio hardware, among others.

audioop.max(fragment, width)

Return the maximum of the absolute value of all samples in a fragment.

audioop.maxpp(fragment, width)

Return the maximum peak-peak value in the sound fragment.

audioop.minmax(fragment, width)

Return a tuple consisting of the minimum and maximum values of all samples in the sound fragment.

audioop.mul(fragment, width, factor)

Return a fragment that has all samples in the original fragment multiplied by the floating-point value factor. Samples are truncated in case of overflow.

audioop.ratecv(fragment, width, nchannels, inrate, outrate, state[, weightA[, weightB]])

Convert the frame rate of the input fragment.

state is a tuple containing the state of the converter. The converter returns a tuple (newfragment, newstate), and newstate should be passed to the next call of ratecv(). The initial call should pass None as the state.

The weightA and weightB arguments are parameters for a simple digital filter and default to 1 and 0 respectively.

audioop.reverse(fragment, width)

Reverse the samples in a fragment and returns the modified fragment.

audioop.rms(fragment, width)

Return the root-mean-square of the fragment, i.e. sqrt(sum(S_i^2)/n).

This is a measure of the power in an audio signal.

audioop.tomono(fragment, width, lfactor, rfactor)

Convert a stereo fragment to a mono fragment. The left channel is multiplied by lfactor and the right channel by rfactor before adding the two channels to give a mono signal.

audioop.tostereo(fragment, width, lfactor, rfactor)

Generate a stereo fragment from a mono fragment. Each pair of samples in the stereo fragment are computed from the mono sample, whereby left channel samples are multiplied by lfactor and right channel samples by rfactor.

audioop.ulaw2lin(fragment, width)

Convert sound fragments in u-LAW encoding to linearly encoded sound fragments. u-LAW encoding always uses 8 bits samples, so width refers only to the sample width of the output fragment here.

Note that operations such as mul() or max() make no distinction between mono and stereo fragments, i.e. all samples are treated equal. If this is a problem the stereo fragment should be split into two mono fragments first and recombined later. Here is an example of how to do that:

def mul_stereo(sample, width, lfactor, rfactor):
    lsample = audioop.tomono(sample, width, 1, 0)
    rsample = audioop.tomono(sample, width, 0, 1)
    lsample = audioop.mul(lsample, width, lfactor)
    rsample = audioop.mul(rsample, width, rfactor)
    lsample = audioop.tostereo(lsample, width, 1, 0)
    rsample = audioop.tostereo(rsample, width, 0, 1)
    return audioop.add(lsample, rsample, width)

If you use the ADPCM coder to build network packets and you want your protocol to be stateless (i.e. to be able to tolerate packet loss) you should not only transmit the data but also the state. Note that you should send the initial state (the one you passed to lin2adpcm()) along to the decoder, not the final state (as returned by the coder). If you want to use struct.Struct to store the state in binary you can code the first element (the predicted value) in 16 bits and the second (the delta index) in 8.

The ADPCM coders have never been tried against other ADPCM coders, only against themselves. It could well be that I misinterpreted the standards in which case they will not be interoperable with the respective standards.

The find*() routines might look a bit funny at first sight. They are primarily meant to do echo cancellation. A reasonably fast way to do this is to pick the most energetic piece of the output sample, locate that in the input sample and subtract the whole output sample from the input sample:

def echocancel(outputdata, inputdata):
    pos = audioop.findmax(outputdata, 800)    # one tenth second
    out_test = outputdata[pos*2:]
    in_test = inputdata[pos*2:]
    ipos, factor = audioop.findfit(in_test, out_test)
    # Optional (for better cancellation):
    # factor = audioop.findfactor(in_test[ipos*2:ipos*2+len(out_test)],
    #              out_test)
    prefill = '\0'*(pos+ipos)*2
    postfill = '\0'*(len(inputdata)-len(prefill)-len(outputdata))
    outputdata = prefill + audioop.mul(outputdata, 2, -factor) + postfill
    return audioop.add(inputdata, outputdata, 2)

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

멀티미디어 서비스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

멀티미디어 서비스 »

|

aifc — AIFF와 AIFC 파일 읽고 쓰기

소스 코드: Lib/aifc.py [https://github.com/python/cpython/tree/3.7/Lib/aifc.py]

이 모듈은 AIFF와 AIFF-C 파일을 읽고 쓸 수 있도록 지원합니다. AIFF는 디지털 오디오 샘플을 파일에 저장하는 형식인 Audio Interchange File Format입니다. AIFF-C는 오디오 데이터를 압축하는 기능을 포함하는 이 형식의 새 버전입니다.

오디오 파일에는 오디오 데이터를 설명하는 많은 파라미터가 있습니다. 샘플링 속도나 프레임 속도는 음향을 샘플링하는 초당 횟수입니다. 채널 수는 오디오가 모노(mono), 스테레오(stereo) 또는 쿼드로(quadro)인지를 나타냅니다. 각 프레임은 채널 당 하나의 샘플로 구성됩니다. 샘플 크기는 각 샘플의 크기를 바이트로 표현한 것입니다. 따라서 프레임은 nchannels * samplesize 바이트로 구성되고, 1초 분량의 오디오는 nchannels * samplesize * framerate 바이트로 구성됩니다.

예를 들어, CD 품질 오디오는 샘플 크기가 2바이트 (16비트)이고, 2채널(스테레오)을 사용하며 프레임 속도가 44,100프레임/초입니다. 이는 4바이트(2*2)의 프레임 크기를 제공하고, 1초 분량의 오디오는 2*2*44100바이트(176,400바이트)를 차지합니다.

모듈 aifc는 다음 함수를 정의합니다:

aifc.open(file, mode=None)

AIFF나 AIFF-C 파일을 열고 아래에 설명된 메서드를 갖는 객체 인스턴스를 반환합니다. 인자 file는 파일을 명명하는 문자열이거나 파일 객체입니다. mode는 파일을 읽기 위해 열어야 할 때 'r'이나 'rb' 여야 하며, 파일을 쓰기 위해 열어야 하는 경우 'w'나 'wb' 여야 합니다. 생략하면, file.mode가 있으면 그것을 쓰고, 그렇지 않으면 'rb'가 사용됩니다. 쓰기 위해 열 때는, 앞으로 기록할 샘플의 총수를 미리 알고 writeframesraw() 및 setnframes()를 사용하지 않는 한 파일 객체는 위치 변경할 수 있어야(seekable) 합니다. open() 함수는 with 문에서 사용될 수 있습니다. with 블록이 완료될 때 close() 메서드가 호출됩니다.

버전 3.4에서 변경: with 문에 대한 지원이 추가되었습니다.

파일을 읽기 위해 열 때 open()가 반환하는 객체는 다음과 같은 메서드를 가집니다:

aifc.getnchannels()

오디오 채널 수를 반환합니다 (모노는 1, 스테레오는 2).

aifc.getsampwidth()

개별 샘플의 크기를 바이트 단위로 반환합니다.

aifc.getframerate()

샘플링 속도(초당 오디오 프레임의 수)를 반환합니다.

aifc.getnframes()

파일 내의 오디오 프레임의 수를 반환합니다.

aifc.getcomptype()

오디오 파일에서 사용된 압축 유형을 설명하는 길이 4의 바이트열을 반환합니다. AIFF 파일의 경우, 반환 값은 b'NONE'입니다.

aifc.getcompname()

오디오 파일에서 사용된 압축 유형을 사람이 읽을 수 있는 형식으로 변환할 수 있는 바이트열을 반환합니다. AIFF 파일의 경우, 반환 값은 b'not compressed'입니다.

aifc.getparams()

get*() 메서드의 결과와 동등한, namedtuple() (nchannels, sampwidth, framerate, nframes, comptype, compname)을 반환합니다.

aifc.getmarkers()

오디오 파일의 마커(marker) 리스트를 반환합니다. 마커는 세 요소의 튜플로 구성됩니다. 첫 번째는 마크 ID(정수)이고, 두 번째는 데이터 시작부터 따진 프레임에서의 마크 위치이며 (정수), 세 번째는 마크의 이름입니다 (문자열).

aifc.getmark(id)

지정된 id를 가진 마크에 대해 getmarkers()에 설명된 튜플을 반환합니다.

aifc.readframes(nframes)

오디오 파일에서 다음 nframes 프레임을 읽고 반환합니다. 반환된 데이터는 각 프레임의 모든 채널의 압축되지 않은 샘플을 포함하는 문자열입니다.

aifc.rewind()

읽기 포인터를 되감습니다. 다음 readframes()는 처음부터 시작됩니다.

aifc.setpos(pos)

지정된 프레임 번호로 위치 변경합니다.

aifc.tell()

현재의 프레임 번호를 반환합니다.

aifc.close()

AIFF 파일을 닫습니다. 이 메서드를 호출한 후에는 객체를 더는 사용할 수 없습니다.

파일을 쓰기 위해 열 때, open()이 반환하는 객체는 readframes()와 setpos()를 제외하고 위의 모든 메서드를 가집니다. 이에 더해 다음과 같은 메서드가 있습니다. get*() 메서드는 해당 set*() 메서드가 호출된 후에만 호출할 수 있습니다. 첫 번째 writeframes()나 writeframesraw() 이전에, 프레임 수를 제외한 모든 파라미터를 채워야 합니다.

aifc.aiff()

AIFF 파일을 만듭니다. 기본값은 AIFF-C 파일을 만드는 것입니다. 파일 이름이 '.aiff'로 끝날 때는 예외인데, 이때 기본값은 AIFF 파일입니다.

aifc.aifc()

AIFF-C 파일을 만듭니다. 기본값은 AIFF-C 파일을 만드는 것입니다. 파일 이름이 '.aiff'로 끝날 때는 예외인데, 이때 기본값은 AIFF 파일입니다.

aifc.setnchannels(nchannels)

오디오 파일의 채널 수를 지정합니다.

aifc.setsampwidth(width)

오디오 샘플의 크기를 바이트 단위로 지정합니다.

aifc.setframerate(rate)

샘플링 빈도를 초당 프레임 수로 지정합니다.

aifc.setnframes(nframes)

오디오 파일에 기록할 프레임 수를 지정합니다. 이 파라미터가 설정되지 않거나, 올바르게 설정되지 않으면, 파일은 위치 변경을 지원해야 합니다.

aifc.setcomptype(type, name)

압축 유형을 지정합니다. 지정하지 않으면, 오디오 데이터는 압축되지 않습니다. AIFF 파일에서, 압축은 불가능합니다. name 매개 변수는 사람이 읽을 수 있는 압축 유형 설명을 바이트열로 제공해야 하며, type 매개 변수는 길이가 4인 바이트열이어야 합니다. 현재 다음 압축 유형이 지원됩니다: b'NONE', b'ULAW', b'ALAW', b'G722'.

aifc.setparams(nchannels, sampwidth, framerate, comptype, compname)

위의 모든 파라미터를 한 번에 설정합니다. 인자는 여러 파라미터로 구성된 튜플입니다. 이것은 getparams() 호출의 결과를 setparams()의 인자로 사용할 수 있음을 뜻합니다.

aifc.setmark(id, pos, name)

지정된 id(0보다 큰 값)의 마크를 주어진 name으로 주어진 위치에 추가합니다. 이 메서드는 close() 이전에 언제든지 호출할 수 있습니다.

aifc.tell()

출력 파일의 현재 쓰기 위치를 반환합니다. setmark()와 함께 사용하면 유용합니다.

aifc.writeframes(data)

데이터를 출력 파일에 씁니다. 이 메서드는 오디오 파일 파라미터가 설정된 후에만 호출할 수 있습니다.

버전 3.4에서 변경: 이제 모든 바이트열류 객체가 허용됩니다.

aifc.writeframesraw(data)

오디오 파일의 헤더가 갱신되지 않는다는 점을 제외하고는, writeframes()와 같습니다.

버전 3.4에서 변경: 이제 모든 바이트열류 객체가 허용됩니다.

aifc.close()

AIFF 파일을 닫습니다. 파일의 헤더는 오디오 데이터의 실제 크기를 반영하도록 갱신됩니다. 이 메서드를 호출한 후에는, 객체를 더는 사용할 수 없습니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

멀티미디어 서비스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

멀티미디어 서비스 »

|

sunau — Sun AU 파일 읽고 쓰기

소스 코드: Lib/sunau.py [https://github.com/python/cpython/tree/3.7/Lib/sunau.py]

sunau 모듈은 Sun AU 음향 형식에 편리한 인터페이스를 제공합니다. 이 모듈은 모듈 aifc와 wave 모듈과 인터페이스 호환됩니다.

오디오 파일은 헤더와 뒤따르는 데이터로 구성됩니다. 헤더의 필드는 다음과 같습니다:

필드

내용

매직 워드

4바이트 .snd.

헤더 크기

info를 포함한 헤더의 크기 (바이트).

데이터 크기

데이터의 물리적 크기 (바이트).

인코딩(encoding)

오디오 샘플이 인코딩되는 방법을 나타냅니다.

샘플 속도(sample rate)

샘플링 속도.

채널 수

샘플의 채널 수.

info(정보)

오디오 파일에 대한 설명을 제공하는 ASCII 문자열 (널 바이트로 채워집니다).

info 필드는 제외하고, 모든 헤더 필드의 크기는 4바이트입니다. 이것들은 모두 빅 엔디안 바이트 순서로 인코딩된 32비트 부호 없는 정수입니다.

sunau 모듈은 다음 함수를 정의합니다:

sunau.open(file, mode)

file이 문자열이면, 그 이름으로 파일을 열고, 그렇지 않으면 위치 변경할 수 있는 파일류 객체로 처리합니다. mode는 다음 중 하나일 수 있습니다.

'r'

읽기 전용 모드.

'w'

쓰기 전용 모드.

읽기와 쓰기를 동시에 지원하지 않음에 유의하십시오.

'r'의 mode는 AU_read 객체를 반환하고, 'w' 나 'wb'의 mode는 AU_write 객체를 반환합니다.

sunau.openfp(file, mode)

이전 버전과의 호환성을 위해 유지되는, open()의 동의어입니다.

Deprecated since version 3.7, will be removed in version 3.9.

sunau 모듈은 다음 예외를 정의합니다:

exception sunau.Error

Sun AU 명세나 구현 결함으로 인해 무언가가 불가능할 때 발생하는 에러.

sunau 모듈은 다음 데이터 항목을 정의합니다:

sunau.AUDIO_FILE_MAGIC

유효한 모든 Sun AU 파일이 시작하는 빅 엔디안 형식으로 저장된 정수. 이것은 정수로 해석되는 문자열 .snd입니다.

sunau.AUDIO_FILE_ENCODING_MULAW_8

sunau.AUDIO_FILE_ENCODING_LINEAR_8

sunau.AUDIO_FILE_ENCODING_LINEAR_16

sunau.AUDIO_FILE_ENCODING_LINEAR_24

sunau.AUDIO_FILE_ENCODING_LINEAR_32

sunau.AUDIO_FILE_ENCODING_ALAW_8

이 모듈이 지원하는, AU 헤더의 인코딩 필드 값.

sunau.AUDIO_FILE_ENCODING_FLOAT

sunau.AUDIO_FILE_ENCODING_DOUBLE

sunau.AUDIO_FILE_ENCODING_ADPCM_G721

sunau.AUDIO_FILE_ENCODING_ADPCM_G722

sunau.AUDIO_FILE_ENCODING_ADPCM_G723_3

sunau.AUDIO_FILE_ENCODING_ADPCM_G723_5

추가로 알려진 AU 헤더의 인코딩 필드 값이지만, 이 모듈에서 지원하지 않는 값.

AU_read 객체

위의 open()에 의해 반환된 AU_read 객체는 다음과 같은 메서드를 가지고 있습니다:

AU_read.close()

스트림을 닫고, 인스턴스를 사용할 수 없게 합니다. (삭제 시 자동으로 호출됩니다.)

AU_read.getnchannels()

오디오 채널 수를 반환합니다 (모노는 1, 스테레오는 2).

AU_read.getsampwidth()

샘플 폭을 바이트 단위로 반환합니다.

AU_read.getframerate()

샘플링 빈도를 반환합니다.

AU_read.getnframes()

오디오 프레임의 수를 반환합니다.

AU_read.getcomptype()

압축 유형을 반환합니다. 지원되는 압축 유형은 'ULAW', 'ALAW' 및 'NONE'입니다.

AU_read.getcompname()

getcomptype()의 사람이 읽을 수 있는 버전. 지원되는 유형은 각각 'CCITT G.711 u-law', 'CCITT G.711 A-law' 및 'not compressed' 이름입니다.

AU_read.getparams()

get*() 메서드의 결과와 동등한, namedtuple() (nchannels, sampwidth, framerate, nframes, comptype, compname)를 반환합니다.

AU_read.readframes(n)

최대 n 프레임의 오디오를 bytes 객체로 읽고 반환합니다. 데이터는 선형 형식(linear format)으로 반환됩니다. 원본 데이터가 u-LAW 형식이면, 변환됩니다.

AU_read.rewind()

파일 포인터를 오디오 스트림의 시작 부분으로 되감습니다.

다음의 두 메서드는 이들 사이에서 호환 가능한 용어 “위치(position)”를 정의하며, 그 외에는 구현에 따라 다릅니다.

AU_read.setpos(pos)

파일 포인터를 지정된 위치로 설정합니다. tell()에서 반환된 값만 pos에 사용해야 합니다.

AU_read.tell()

현재 파일 포인터 위치를 반환합니다. 반환된 값은 파일에서의 실제 위치와 아무런 관련이 없음에 유의하십시오.

다음 두 함수는 aifc와의 호환성을 위해 정의되었으며, 흥미로운 작업을 수행하지 않습니다.

AU_read.getmarkers()

None을 반환합니다.

AU_read.getmark(id)

에러를 발생시킵니다.

AU_write 객체

위의 open()에서 반환된 AU_write 객체에는 다음과 같은 메서드가 있습니다:

AU_write.setnchannels(n)

채널 수를 설정합니다.

AU_write.setsampwidth(n)

샘플 폭을 설정합니다 (바이트 단위).

버전 3.4에서 변경: 24비트 샘플에 대한 지원이 추가되었습니다.

AU_write.setframerate(n)

프레임 속도를 설정합니다.

AU_write.setnframes(n)

프레임 수를 설정합니다. 더 많은 프레임이 기록되면 나중에 변경될 수 있습니다.

AU_write.setcomptype(type, name)

압축 유형과 설명을 설정합니다. 출력에는 'NONE' 과 'ULAW' 만 지원됩니다.

AU_write.setparams(tuple)

tuple은 (nchannels, sampwidth, framerate, nframes, comptype, compname)이어야 하며, set*() 메서드에 유효한 값이어야 합니다. 모든 파라미터를 설정합니다.

AU_write.tell()

파일의 현재 위치를 반환하는데, AU_read.tell() 과 AU_read.setpos() 메서드와 같은 면책 조항이 적용됩니다.

AU_write.writeframesraw(data)

nframes를 수정하지 않고 오디오 프레임을 씁니다.

버전 3.4에서 변경: 이제 모든 바이트열류 객체가 허락됩니다.

AU_write.writeframes(data)

오디오 프레임을 쓰고 nframes를 올바르게 만듭니다.

버전 3.4에서 변경: 이제 모든 바이트열류 객체가 허락됩니다.

AU_write.close()

nframes를 올바르게 만들고 파일을 닫습니다.

이 메서드는 삭제 시에 호출됩니다.

writeframes() 나 writeframesraw()를 호출한 후 파라미터를 설정하는 것은 유효하지 않습니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

멀티미디어 서비스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

멀티미디어 서비스 »

|

wave — WAV 파일 읽고 쓰기

소스 코드: Lib/wave.py [https://github.com/python/cpython/tree/3.7/Lib/wave.py]

wave 모듈은 WAV 음향 형식에 편리한 인터페이스를 제공합니다. 압축/압축 해제는 지원하지 않지만, 모노/스테레오를 지원합니다.

wave 모듈은 다음 함수와 예외를 정의합니다:

wave.open(file, mode=None)

file이 문자열이면, 그 이름의 파일을 엽니다, 그렇지 않으면 파일류 객체로 처리합니다. mode는 다음 중 하나일 수 있습니다:

'rb'

읽기 전용 모드.

'wb'

쓰기 전용 모드.

WAV 파일의 읽기와 쓰기를 동시에 허락하지 않음에 유의하십시오.

'rb' mode는 Wave_read 객체를 반환하고, 'wb' mode는 Wave_write 객체를 반환합니다. mode가 생략되고, 파일류 객체가 file로 전달되면, file.mode가 mode의 기본값으로 사용됩니다.

파일류 객체를 전달하면, close() 메서드가 호출될 때 wave 객체는 그 파일을 닫지 않습니다. 파일 객체를 닫는 것은 호출자의 책임입니다.

open() 함수는 with 문과 함께 사용할 수 있습니다. with 블록이 완료될 때, Wave_read.close()나 Wave_write.close() 메서드가 호출됩니다.

버전 3.4에서 변경: 위치 변경할 수 없는(unseekable) 파일에 대한 지원이 추가되었습니다.

wave.openfp(file, mode)

open()의 동의어입니다. 이전 버전과의 호환성을 위해 유지됩니다.

Deprecated since version 3.7, will be removed in version 3.9.

exception wave.Error

WAV 명세를 위반하거나 구현 결함으로 인해 무언가가 불가능할 때 발생하는 에러.

Wave_read 객체

open()이 반환하는, Wave_read 객체는 다음과 같은 메서드를 가지고 있습니다:

Wave_read.close()

스트림이 wave에 의해 열렸다면 스트림을 닫고, 인스턴스를 사용할 수 없게 만듭니다. 이것은 객체가 가비지 수집될 때 자동으로 호출됩니다.

Wave_read.getnchannels()

오디오 채널 수를 반환합니다 (모노는 1, 스테레오는 2).

Wave_read.getsampwidth()

샘플 폭을 바이트 단위로 반환합니다.

Wave_read.getframerate()

샘플링 빈도를 반환합니다.

Wave_read.getnframes()

오디오 프레임의 수를 반환합니다.

Wave_read.getcomptype()

압축 유형을 반환합니다 (지원되는 유형은 'NONE' 뿐입니다).

Wave_read.getcompname()

getcomptype()의 사람이 읽을 수 있는 버전. 보통 'not compressed'이 'NONE'에 해당합니다.

Wave_read.getparams()

get*() 메서드의 결과와 동등한, namedtuple() (nchannels, sampwidth, framerate, nframes, comptype, compname)를 반환합니다.

Wave_read.readframes(n)

최대 n 프레임의 오디오를 bytes 객체로 읽고 반환합니다.

Wave_read.rewind()

파일 포인터를 오디오 스트림의 시작 부분으로 되감습니다.

다음의 두 메서드는 aifc 모듈과의 호환성을 위해 정의되었으며, 흥미로운 작업을 수행하지 않습니다.

Wave_read.getmarkers()

None을 반환합니다.

Wave_read.getmark(id)

에러를 발생시킵니다.

다음의 두 메서드는 이들 사이에서 호환 가능한 용어 “위치(position)”를 정의하며, 그 외에는 구현에 따라 다릅니다.

Wave_read.setpos(pos)

파일 포인터를 지정된 위치로 설정합니다.

Wave_read.tell()

현재 파일 포인터 위치를 반환합니다.

Wave_write 객체

위치 변경할 수 있는(seekable) 출력 스트림의 경우, 실제로 기록된 프레임 수를 반영하도록 wave 헤더가 자동으로 갱신됩니다. 위치 변경할 수 없는(unseekable) 스트림의 경우, 첫 번째 프레임 데이터를 쓸 때, nframes 값이 정확해야 합니다. 정확한 nframes 값을 실현하려면 close()가 호출되기 전에 기록될 프레임 수로 setnframes()나 setparams()를 호출한 다음, writeframesraw()를 사용하여 프레임 데이터를 쓰거나, 기록할 모든 프레임 데이터로 writeframes()를 호출할 수 있습니다. 후자의 경우 writeframes()는 데이터의 프레임 수를 계산하고 프레임 데이터를 기록하기 전에 적절한 nframes를 설정합니다.

open()에 의해 반환된, Wave_write 객체에는 다음과 같은 메서드가 있습니다:

버전 3.4에서 변경: 위치 변경할 수 없는(unseekable) 파일에 대한 지원이 추가되었습니다.

Wave_write.close()

nframes를 올바르게 만들고, 파일이 wave로 열렸으면 파일을 닫습니다. 이 메서드는 객체가 가비지 수집될 때 호출됩니다. 출력 스트림이 위치 변경할 수 없고 nframes가 실제로 기록된 프레임 수와 일치하지 않으면 예외를 일으킵니다.

Wave_write.setnchannels(n)

채널 수를 설정합니다.

Wave_write.setsampwidth(n)

샘플 폭을 n 바이트로 설정합니다.

Wave_write.setframerate(n)

프레임 속도를 n으로 설정합니다.

버전 3.2에서 변경: 이 메서드에 대한 비 정수 입력은 가장 가까운 정수로 자리 올림 됩니다.

Wave_write.setnframes(n)

프레임 수를 n으로 설정합니다. 실제로 쓴 프레임 수가 다르면 나중에 변경됩니다 (이 변경 시도는 출력 스트림이 위치 변경할 수 없으면 에러를 발생시킵니다).

Wave_write.setcomptype(type, name)

압축 유형과 설명을 설정합니다. 현재, 압축 유형 NONE 만 지원됩니다. 즉, 압축하지 않습니다.

Wave_write.setparams(tuple)

tuple은 (nchannels, sampwidth, framerate, nframes, comptype, compname)이어야 하며, set*() 메서드에 유효한 값이어야 합니다. 모든 파라미터를 설정합니다.

Wave_write.tell()

파일의 현재 위치를 반환하는데, Wave_read.tell() 과 Wave_read.setpos() 메서드와 같은 면책 조항이 적용됩니다.

Wave_write.writeframesraw(data)

nframes를 수정하지 않고 오디오 프레임을 씁니다.

버전 3.4에서 변경: 이제 모든 바이트열류 객체가 허락됩니다.

Wave_write.writeframes(data)

오디오 프레임을 기록하고 nframes를 올바르게 만듭니다. 출력 스트림이 위치 변경할 수 없고 data를 기록한 후에 기록된 총 프레임 수가 nframes에 대해 이전에 설정된 값과 일치하지 않으면 에러가 발생시킵니다.

버전 3.4에서 변경: 이제 모든 바이트열류 객체가 허락됩니다.

writeframes()나 writeframesraw()를 호출한 후 파라미터를 설정하는 것이 유효하지 않고, 이를 시도하면 wave.Error가 발생함에 유의하십시오.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

멀티미디어 서비스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

멀티미디어 서비스 »

|

chunk — IFF 청크된 데이터 읽기

소스 코드: Lib/chunk.py [https://github.com/python/cpython/tree/3.7/Lib/chunk.py]

이 모듈은 EA IFF 85 청크를 사용하는 파일을 읽기 위한 인터페이스를 제공합니다. 1 이 형식은 적어도 AIFF/AIFF-C (Audio Interchange File Format) 와 RMFF (Real Media File Format)에서 사용됩니다. WAVE 오디오 파일 형식은 밀접하게 관련되어 있으며 이 모듈을 사용하여 읽을 수도 있습니다.

청크의 구조는 다음과 같습니다:

오프셋

길이

내용

0

4

청크 ID

4

4

빅 엔디안 바이트 순서로 청크의 크기. 헤더는 포함하지 않습니다.

8

n

데이터 바이트. 여기서 n은 앞 필드에서 주어진 크기입니다.

8 + n

0 또는 1

n가 홀수이고 청크 정렬이 사용된 경우 필요한 패드 바이트

ID는 청크의 유형을 식별하는 4바이트 문자열입니다.

크기 필드(빅 엔디안 바이트 순서를 사용하여 인코딩된 32비트 값)는 청크 데이터의 크기를 제공하며, 8바이트 헤더는 포함하지 않습니다.

일반적으로 IFF 형식의 파일은 하나 이상의 청크로 구성됩니다. 여기에 정의된 Chunk 클래스의 제안 된 사용법은 각 청크의 시작 부분에서 인스턴스를 만들고 끝까지 도달할 때까지 인스턴스에서 읽는 것입니다. 그다음에 새 인스턴스를 만들 수 있습니다. 파일의 끝에서, 새 인스턴스를 만드는 것은 EOFError 예외로 실패합니다.

class chunk.Chunk(file, align=True, bigendian=True, inclheader=False)

청크를 나타내는 클래스. file 인자는 파일류 객체를 기대합니다. 이 클래스의 인스턴스가 특별히 허용됩니다. 필요한 유일한 메서드는 read()입니다. seek() 와 tell() 메서드가 있고 예외를 발생시키지 않으면 이것들도 사용됩니다. 이러한 메서드가 존재하고, 예외가 발생하면, 객체가 변경되지 않았을 것으로 기대합니다. 선택적 인자 align이 참이면, 청크는 2바이트 경계에서 정렬되는 것으로 가정합니다. align이 거짓이면 정렬을 가정하지 않습니다. 기본값은 참입니다. 선택적 인자 bigendian이 거짓이면 청크 크기는 리틀 엔디안 순서로 간주합니다. 이것은 WAVE 오디오 파일에 필요합니다. 기본값은 참입니다. 선택적 인자 inclheader가 참이면, 청크 헤더에 주어진 크기는 헤더의 크기를 포함합니다. 기본값은 거짓입니다.

Chunk 객체는 다음 메서드를 지원합니다:

getname()

청크의 이름(ID)을 돌려줍니다. 이것은 청크의 처음 4바이트입니다.

getsize()

청크의 크기를 돌려줍니다.

close()

닫고 청크의 끝으로 건너뜁니다. 하부 파일을 닫지 않습니다.

나머지 메서드는 close() 메서드가 호출된 후에 호출되면 OSError를 발생시킵니다. 파이썬 3.3 이전에는 IOError를 발생시켰습니다. 이제는 OSError의 별칭입니다.

isatty()

False를 반환합니다.

seek(pos, whence=0)

청크의 현재 위치를 설정합니다. whence 인자는 선택 사항이며 기본값은 0(절대 파일 위치 지정)입니다; 다른 값은 1(현재 위치에 상대적인 탐색)과 2(파일의 끝에 상대적인 탐색)입니다. 반환 값이 없습니다. 하부 파일이 탐색을 허용하지 않으면, 정방향 탐색만 허용됩니다.

tell()

청크의 현재 위치를 반환합니다.

read(size=-1)

청크에서 최대 size 바이트를 읽습니다 (size 바이트를 얻기 전에 read가 청크 끝에 도달하면 덜 읽을 수 있습니다). size 인자가 음수이거나 생략되면, 청크의 끝까지 모든 데이터를 읽습니다. 청크의 끝이 즉시 발견되면 빈 바이트열 객체가 반환됩니다.

skip()

청크의 끝으로 건너뜁니다. 청크에 대한 모든 추가 read() 호출은 b''를 반환합니다. 청크의 내용에 관심이 없으면, 파일이 다음 청크의 시작을 가리키도록 이 메서드를 호출해야 합니다.

각주

1

“EA IFF 85” Standard for Interchange Format Files, Jerry Morrison, Electronic Arts, 1985년 1월.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

멀티미디어 서비스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

멀티미디어 서비스 »

|

colorsys — 색 체계 간의 변환

소스 코드: Lib/colorsys.py [https://github.com/python/cpython/tree/3.7/Lib/colorsys.py]

colorsys 모듈은 컴퓨터 모니터에서 사용되는 RGB (Red Green Blue, 적 녹 청) 색 공간과 세 가지 다른 좌표계 YIQ, HLS (Hue Lightness Saturation, 색상 명도 채도), HSV(Hue Saturation Value, 색상 채도 명도)로 표현된 색 간 양방향 색 변환을 정의합니다. 이러한 모든 색 공간의 좌표는 부동 소수점 값입니다. YIQ 공간에서, Y 좌표는 0과 1사이지만, I 와 Q 좌표는 양수나 음수가 될 수 있습니다. 다른 모든 공간에서, 좌표는 모두 0과 1 사이입니다.

더 보기

색 공간에 대한 자세한 내용은 http://poynton.ca/ColorFAQ.html 와 https://www.cambridgeincolour.com/tutorials/color-spaces.htm 에서 확인할 수 있습니다.

colorsys 모듈은 다음 함수를 정의합니다:

colorsys.rgb_to_yiq(r, g, b)

RGB 좌표에서 YIQ 좌표로 색을 변환합니다.

colorsys.yiq_to_rgb(y, i, q)

YIQ 좌표에서 RGB 좌표로 색을 변환합니다.

colorsys.rgb_to_hls(r, g, b)

RGB 좌표에서 HLS 좌표로 색을 변환합니다.

colorsys.hls_to_rgb(h, l, s)

HLS 좌표에서 RGB 좌표로 색을 변환합니다.

colorsys.rgb_to_hsv(r, g, b)

RGB 좌표에서 HSV 좌표로 색을 변환합니다.

colorsys.hsv_to_rgb(h, s, v)

HSV 좌표에서 RGB 좌표로 색을 변환합니다.

예:

>>> import colorsys
>>> colorsys.rgb_to_hsv(0.2, 0.4, 0.4)
(0.5, 0.5, 0.4)
>>> colorsys.hsv_to_rgb(0.5, 0.5, 0.4)
(0.2, 0.4, 0.4)

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

멀티미디어 서비스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

멀티미디어 서비스 »

|

imghdr — 이미지 유형 판단

소스 코드: Lib/imghdr.py [https://github.com/python/cpython/tree/3.7/Lib/imghdr.py]

imghdr 모듈은 파일이나 바이트 스트림에 포함된 이미지의 유형을 판단합니다.

imghdr 모듈은 다음 함수를 정의합니다:

imghdr.what(filename, h=None)

filename으로 이름이 지정된 파일에 포함된 이미지 데이터를 검사하고, 이미지 유형을 설명하는 문자열을 반환합니다. 선택적 h가 제공되면, filename는 무시되고 h가 검사할 바이트 스트림을 포함한다고 가정합니다.

버전 3.6에서 변경: 경로류 객체를 받아들입니다.

아래에 what()의 반환 값과 함께 나열된 것처럼, 다음과 같은 이미지 유형을 인식합니다:

값

이미지 형식

'rgb'

SGI ImgLib 파일

'gif'

GIF 87a 과 89a 파일

'pbm'

Portable Bitmap 파일

'pgm'

Portable Graymap 파일

'ppm'

Portable Pixmap 파일

'tiff'

TIFF 파일

'rast'

Sun Raster 파일

'xbm'

X Bitmap 파일

'jpeg'

JFIF 나 Exif 형식의 JPEG 데이터

'bmp'

BMP 파일

'png'

Portable Network Graphics

'webp'

WebP 파일

'exr'

OpenEXR 파일

버전 3.5에 추가: exr 과 webp 형식이 추가되었습니다.

이 변수에 추가해서 imghdr가 인식할 수 있는 파일 유형 목록을 확장할 수 있습니다:

imghdr.tests

개별검사를 수행하는 함수 리스트. 각 함수는 두 개의 인자를 받아들입니다: 바이트 스트림과 열린 파일류 객체. what()이 바이트 스트림으로 호출되면, 파일류 객체는 None이 됩니다.

검사 함수는 검사가 성공하면 이미지 유형을 설명하는 문자열을 반환하고, 실패하면 None을 반환해야 합니다.

예제:

>>> import imghdr
>>> imghdr.what('bass.gif')
'gif'

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

멀티미디어 서비스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

멀티미디어 서비스 »

|

sndhdr — 음향 파일 유형 판단

소스 코드: Lib/sndhdr.py [https://github.com/python/cpython/tree/3.7/Lib/sndhdr.py]

sndhdr은 파일에 있는 음향 데이터 유형을 판별하려고 하는 유틸리티 함수를 제공합니다. 이 함수는 파일에 저장된 음향 데이터의 형식을 결정할 수 있을 때 5가지 어트리뷰트를 포함하는 namedtuple()을 반환합니다: (filetype, framerate, nchannels, nframes, sampwidth). type의 값은 데이터 유형을 나타내며 'aifc', 'aiff', 'au', 'hcom', 'sndr', 'sndt', 'voc', 'wav', '8svx', 'sb', 'ub' 또는 'ul' 문자열 중 하나가 됩니다. sampling_rate는 실제 값이거나 알 수 없거나 디코드하기 어려우면 0입니다. 마찬가지로, channels는 채널 수거나 결정할 수 없거나 값을 디코드하기 어려우면 0이 됩니다. frames 의 값은 프레임 수 또는 -1이 됩니다. 튜플의 마지막 항목인 bits_per_sample는 비트 단위의 샘플 크기이거나 A-LAW의 경우 'A' 또는 u-LAW의 경우 'U' 입니다.

sndhdr.what(filename)

whathdr()를 사용하여 filename 파일에 저장된 음향 데이터 유형을 판단합니다. 성공하면 위의 설명과 같이 네임드 튜플을 반환합니다. 그렇지 않으면 None을 반환합니다.

버전 3.5에서 변경: 결과가 튜플에서 네임드 튜플로 변경되었습니다.

sndhdr.whathdr(filename)

파일 헤더에 따라 파일에 저장된 음향 데이터의 유형을 판단합니다. 파일의 이름은 filename으로 주어집니다. 이 함수는 성공 시에 위에서 설명한 네임드 튜플을 반환하고, 그렇지 않으면 None을 반환합니다.

버전 3.5에서 변경: 결과가 튜플에서 네임드 튜플로 변경되었습니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

멀티미디어 서비스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

멀티미디어 서비스 »

|

ossaudiodev — Access to OSS-compatible audio devices

This module allows you to access the OSS (Open Sound System) audio interface. OSS is available for a wide range of open-source and commercial Unices, and is the standard audio interface for Linux and recent versions of FreeBSD.

버전 3.3에서 변경: Operations in this module now raise OSError where IOError was raised.

더 보기

Open Sound System Programmer’s Guide [http://www.opensound.com/pguide/oss.pdf]

the official documentation for the OSS C API

The module defines a large number of constants supplied by the OSS device driver; see <sys/soundcard.h> on either Linux or FreeBSD for a listing.

ossaudiodev defines the following variables and functions:

exception ossaudiodev.OSSAudioError

This exception is raised on certain errors. The argument is a string describing what went wrong.

(If ossaudiodev receives an error from a system call such as open(), write(), or ioctl(), it raises OSError. Errors detected directly by ossaudiodev result in OSSAudioError.)

(For backwards compatibility, the exception class is also available as ossaudiodev.error.)

ossaudiodev.open(mode)

ossaudiodev.open(device, mode)

Open an audio device and return an OSS audio device object. This object supports many file-like methods, such as read(), write(), and fileno() (although there are subtle differences between conventional Unix read/write semantics and those of OSS audio devices). It also supports a number of audio-specific methods; see below for the complete list of methods.

device is the audio device filename to use. If it is not specified, this module first looks in the environment variable AUDIODEV for a device to use. If not found, it falls back to /dev/dsp.

mode is one of 'r' for read-only (record) access, 'w' for write-only (playback) access and 'rw' for both. Since many sound cards only allow one process to have the recorder or player open at a time, it is a good idea to open the device only for the activity needed. Further, some sound cards are half-duplex: they can be opened for reading or writing, but not both at once.

Note the unusual calling syntax: the first argument is optional, and the second is required. This is a historical artifact for compatibility with the older linuxaudiodev module which ossaudiodev supersedes.

ossaudiodev.openmixer([device])

Open a mixer device and return an OSS mixer device object. device is the mixer device filename to use. If it is not specified, this module first looks in the environment variable MIXERDEV for a device to use. If not found, it falls back to /dev/mixer.

Audio Device Objects

Before you can write to or read from an audio device, you must call three methods in the correct order:

setfmt() to set the output format

channels() to set the number of channels

speed() to set the sample rate

Alternately, you can use the setparameters() method to set all three audio parameters at once. This is more convenient, but may not be as flexible in all cases.

The audio device objects returned by open() define the following methods and (read-only) attributes:

oss_audio_device.close()

Explicitly close the audio device. When you are done writing to or reading from an audio device, you should explicitly close it. A closed device cannot be used again.

oss_audio_device.fileno()

Return the file descriptor associated with the device.

oss_audio_device.read(size)

Read size bytes from the audio input and return them as a Python string. Unlike most Unix device drivers, OSS audio devices in blocking mode (the default) will block read() until the entire requested amount of data is available.

oss_audio_device.write(data)

Write a bytes-like object data to the audio device and return the number of bytes written. If the audio device is in blocking mode (the default), the entire data is always written (again, this is different from usual Unix device semantics). If the device is in non-blocking mode, some data may not be written—see writeall().

버전 3.5에서 변경: Writable bytes-like object is now accepted.

oss_audio_device.writeall(data)

Write a bytes-like object data to the audio device: waits until the audio device is able to accept data, writes as much data as it will accept, and repeats until data has been completely written. If the device is in blocking mode (the default), this has the same effect as write(); writeall() is only useful in non-blocking mode. Has no return value, since the amount of data written is always equal to the amount of data supplied.

버전 3.5에서 변경: Writable bytes-like object is now accepted.

버전 3.2에서 변경: Audio device objects also support the context management protocol, i.e. they can be used in a with statement.

The following methods each map to exactly one ioctl() system call. The correspondence is obvious: for example, setfmt() corresponds to the SNDCTL_DSP_SETFMT ioctl, and sync() to SNDCTL_DSP_SYNC (this can be useful when consulting the OSS documentation). If the underlying ioctl() fails, they all raise OSError.

oss_audio_device.nonblock()

Put the device into non-blocking mode. Once in non-blocking mode, there is no way to return it to blocking mode.

oss_audio_device.getfmts()

Return a bitmask of the audio output formats supported by the soundcard. Some of the formats supported by OSS are:

Format

Description

AFMT_MU_LAW

a logarithmic encoding (used by Sun .au files and /dev/audio)

AFMT_A_LAW

a logarithmic encoding

AFMT_IMA_ADPCM

a 4:1 compressed format defined by the Interactive Multimedia Association

AFMT_U8

Unsigned, 8-bit audio

AFMT_S16_LE

Signed, 16-bit audio, little-endian byte order (as used by Intel processors)

AFMT_S16_BE

Signed, 16-bit audio, big-endian byte order (as used by 68k, PowerPC, Sparc)

AFMT_S8

Signed, 8 bit audio

AFMT_U16_LE

Unsigned, 16-bit little-endian audio

AFMT_U16_BE

Unsigned, 16-bit big-endian audio

Consult the OSS documentation for a full list of audio formats, and note that most devices support only a subset of these formats. Some older devices only support AFMT_U8; the most common format used today is AFMT_S16_LE.

oss_audio_device.setfmt(format)

Try to set the current audio format to format—see getfmts() for a list. Returns the audio format that the device was set to, which may not be the requested format. May also be used to return the current audio format—do this by passing an “audio format” of AFMT_QUERY.

oss_audio_device.channels(nchannels)

Set the number of output channels to nchannels. A value of 1 indicates monophonic sound, 2 stereophonic. Some devices may have more than 2 channels, and some high-end devices may not support mono. Returns the number of channels the device was set to.

oss_audio_device.speed(samplerate)

Try to set the audio sampling rate to samplerate samples per second. Returns the rate actually set. Most sound devices don’t support arbitrary sampling rates. Common rates are:

Rate

Description

8000

default rate for /dev/audio

11025

speech recording

22050

44100

CD quality audio (at 16 bits/sample and 2 channels)

96000

DVD quality audio (at 24 bits/sample)

oss_audio_device.sync()

Wait until the sound device has played every byte in its buffer. (This happens implicitly when the device is closed.) The OSS documentation recommends closing and re-opening the device rather than using sync().

oss_audio_device.reset()

Immediately stop playing or recording and return the device to a state where it can accept commands. The OSS documentation recommends closing and re-opening the device after calling reset().

oss_audio_device.post()

Tell the driver that there is likely to be a pause in the output, making it possible for the device to handle the pause more intelligently. You might use this after playing a spot sound effect, before waiting for user input, or before doing disk I/O.

The following convenience methods combine several ioctls, or one ioctl and some simple calculations.

oss_audio_device.setparameters(format, nchannels, samplerate[, strict=False])

Set the key audio sampling parameters—sample format, number of channels, and sampling rate—in one method call. format, nchannels, and samplerate should be as specified in the setfmt(), channels(), and speed() methods. If strict is true, setparameters() checks to see if each parameter was actually set to the requested value, and raises OSSAudioError if not. Returns a tuple (format, nchannels, samplerate) indicating the parameter values that were actually set by the device driver (i.e., the same as the return values of setfmt(), channels(), and speed()).

For example,

(fmt, channels, rate) = dsp.setparameters(fmt, channels, rate)

is equivalent to

fmt = dsp.setfmt(fmt)
channels = dsp.channels(channels)
rate = dsp.rate(rate)

oss_audio_device.bufsize()

Returns the size of the hardware buffer, in samples.

oss_audio_device.obufcount()

Returns the number of samples that are in the hardware buffer yet to be played.

oss_audio_device.obuffree()

Returns the number of samples that could be queued into the hardware buffer to be played without blocking.

Audio device objects also support several read-only attributes:

oss_audio_device.closed

Boolean indicating whether the device has been closed.

oss_audio_device.name

String containing the name of the device file.

oss_audio_device.mode

The I/O mode for the file, either "r", "rw", or "w".

Mixer Device Objects

The mixer object provides two file-like methods:

oss_mixer_device.close()

This method closes the open mixer device file. Any further attempts to use the mixer after this file is closed will raise an OSError.

oss_mixer_device.fileno()

Returns the file handle number of the open mixer device file.

버전 3.2에서 변경: Mixer objects also support the context management protocol.

The remaining methods are specific to audio mixing:

oss_mixer_device.controls()

This method returns a bitmask specifying the available mixer controls (“Control” being a specific mixable “channel”, such as SOUND_MIXER_PCM or SOUND_MIXER_SYNTH). This bitmask indicates a subset of all available mixer controls—the SOUND_MIXER_* constants defined at module level. To determine if, for example, the current mixer object supports a PCM mixer, use the following Python code:

mixer=ossaudiodev.openmixer()
if mixer.controls() & (1 << ossaudiodev.SOUND_MIXER_PCM):
    # PCM is supported
    ... code ...

For most purposes, the SOUND_MIXER_VOLUME (master volume) and SOUND_MIXER_PCM controls should suffice—but code that uses the mixer should be flexible when it comes to choosing mixer controls. On the Gravis Ultrasound, for example, SOUND_MIXER_VOLUME does not exist.

oss_mixer_device.stereocontrols()

Returns a bitmask indicating stereo mixer controls. If a bit is set, the corresponding control is stereo; if it is unset, the control is either monophonic or not supported by the mixer (use in combination with controls() to determine which).

See the code example for the controls() function for an example of getting data from a bitmask.

oss_mixer_device.reccontrols()

Returns a bitmask specifying the mixer controls that may be used to record. See the code example for controls() for an example of reading from a bitmask.

oss_mixer_device.get(control)

Returns the volume of a given mixer control. The returned volume is a 2-tuple (left_volume,right_volume). Volumes are specified as numbers from 0 (silent) to 100 (full volume). If the control is monophonic, a 2-tuple is still returned, but both volumes are the same.

Raises OSSAudioError if an invalid control is specified, or OSError if an unsupported control is specified.

oss_mixer_device.set(control, (left, right))

Sets the volume for a given mixer control to (left,right). left and right must be ints and between 0 (silent) and 100 (full volume). On success, the new volume is returned as a 2-tuple. Note that this may not be exactly the same as the volume specified, because of the limited resolution of some soundcard’s mixers.

Raises OSSAudioError if an invalid mixer control was specified, or if the specified volumes were out-of-range.

oss_mixer_device.get_recsrc()

This method returns a bitmask indicating which control(s) are currently being used as a recording source.

oss_mixer_device.set_recsrc(bitmask)

Call this function to specify a recording source. Returns a bitmask indicating the new recording source (or sources) if successful; raises OSError if an invalid source was specified. To set the current recording source to the microphone input:

mixer.setrecsrc (1 << ossaudiodev.SOUND_MIXER_MIC)

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

멀티미디어 서비스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

|

국제화

이 장에서 설명하는 모듈은 프로그램 메시지에 사용할 언어를 선택하거나 현지 규칙에 맞게 출력을 조정할 수 있는 메커니즘을 제공하여 언어 및 로케일에 종속되지 않는 소프트웨어를 작성하는 데 도움이 됩니다.

이 장에서 설명하는 모듈 목록은 다음과 같습니다:

gettext — Multilingual internationalization services

GNU gettext API

Class-based API

The NullTranslations class

The GNUTranslations class

Solaris message catalog support

The Catalog constructor

Internationalizing your programs and modules

Localizing your module

Localizing your application

Changing languages on the fly

Deferred translations

Acknowledgements

locale — Internationalization services

Background, details, hints, tips and caveats

For extension writers and programs that embed Python

Access to message catalogs

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

국제화 »

|

gettext — Multilingual internationalization services

Source code: Lib/gettext.py [https://github.com/python/cpython/tree/3.7/Lib/gettext.py]

The gettext module provides internationalization (I18N) and localization (L10N) services for your Python modules and applications. It supports both the GNU gettext message catalog API and a higher level, class-based API that may be more appropriate for Python files. The interface described below allows you to write your module and application messages in one natural language, and provide a catalog of translated messages for running under different natural languages.

Some hints on localizing your Python modules and applications are also given.

GNU gettext API

The gettext module defines the following API, which is very similar to the GNU gettext API. If you use this API you will affect the translation of your entire application globally. Often this is what you want if your application is monolingual, with the choice of language dependent on the locale of your user. If you are localizing a Python module, or if your application needs to switch languages on the fly, you probably want to use the class-based API instead.

gettext.bindtextdomain(domain, localedir=None)

Bind the domain to the locale directory localedir. More concretely, gettext will look for binary .mo files for the given domain using the path (on Unix): localedir/language/LC_MESSAGES/domain.mo, where languages is searched for in the environment variables LANGUAGE, LC_ALL, LC_MESSAGES, and LANG respectively.

If localedir is omitted or None, then the current binding for domain is returned. 1

gettext.bind_textdomain_codeset(domain, codeset=None)

Bind the domain to codeset, changing the encoding of byte strings returned by the lgettext(), ldgettext(), lngettext() and ldngettext() functions. If codeset is omitted, then the current binding is returned.

gettext.textdomain(domain=None)

Change or query the current global domain. If domain is None, then the current global domain is returned, otherwise the global domain is set to domain, which is returned.

gettext.gettext(message)

Return the localized translation of message, based on the current global domain, language, and locale directory. This function is usually aliased as _() in the local namespace (see examples below).

gettext.dgettext(domain, message)

Like gettext(), but look the message up in the specified domain.

gettext.ngettext(singular, plural, n)

Like gettext(), but consider plural forms. If a translation is found, apply the plural formula to n, and return the resulting message (some languages have more than two plural forms). If no translation is found, return singular if n is 1; return plural otherwise.

The Plural formula is taken from the catalog header. It is a C or Python expression that has a free variable n; the expression evaluates to the index of the plural in the catalog. See the GNU gettext documentation [https://www.gnu.org/software/gettext/manual/gettext.html] for the precise syntax to be used in .po files and the formulas for a variety of languages.

gettext.dngettext(domain, singular, plural, n)

Like ngettext(), but look the message up in the specified domain.

gettext.lgettext(message)

gettext.ldgettext(domain, message)

gettext.lngettext(singular, plural, n)

gettext.ldngettext(domain, singular, plural, n)

Equivalent to the corresponding functions without the l prefix (gettext(), dgettext(), ngettext() and dngettext()), but the translation is returned as a byte string encoded in the preferred system encoding if no other encoding was explicitly set with bind_textdomain_codeset().

경고

These functions should be avoided in Python 3, because they return encoded bytes. It’s much better to use alternatives which return Unicode strings instead, since most Python applications will want to manipulate human readable text as strings instead of bytes. Further, it’s possible that you may get unexpected Unicode-related exceptions if there are encoding problems with the translated strings. It is possible that the l*() functions will be deprecated in future Python versions due to their inherent problems and limitations.

Note that GNU gettext also defines a dcgettext() method, but this was deemed not useful and so it is currently unimplemented.

Here’s an example of typical usage for this API:

import gettext
gettext.bindtextdomain('myapplication', '/path/to/my/language/directory')
gettext.textdomain('myapplication')
_ = gettext.gettext
# ...
print(_('This is a translatable string.'))

Class-based API

The class-based API of the gettext module gives you more flexibility and greater convenience than the GNU gettext API. It is the recommended way of localizing your Python applications and modules. gettext defines a GNUTranslations class which implements the parsing of GNU .mo format files, and has methods for returning strings. Instances of this class can also install themselves in the built-in namespace as the function _().

gettext.find(domain, localedir=None, languages=None, all=False)

This function implements the standard .mo file search algorithm. It takes a domain, identical to what textdomain() takes. Optional localedir is as in bindtextdomain(). Optional languages is a list of strings, where each string is a language code.

If localedir is not given, then the default system locale directory is used. 2 If languages is not given, then the following environment variables are searched: LANGUAGE, LC_ALL, LC_MESSAGES, and LANG. The first one returning a non-empty value is used for the languages variable. The environment variables should contain a colon separated list of languages, which will be split on the colon to produce the expected list of language code strings.

find() then expands and normalizes the languages, and then iterates through them, searching for an existing file built of these components:

localedir/language/LC_MESSAGES/domain.mo

The first such file name that exists is returned by find(). If no such file is found, then None is returned. If all is given, it returns a list of all file names, in the order in which they appear in the languages list or the environment variables.

gettext.translation(domain, localedir=None, languages=None, class_=None, fallback=False, codeset=None)

Return a *Translations instance based on the domain, localedir, and languages, which are first passed to find() to get a list of the associated .mo file paths. Instances with identical .mo file names are cached. The actual class instantiated is class_ if provided, otherwise GNUTranslations. The class’s constructor must take a single file object argument. If provided, codeset will change the charset used to encode translated strings in the lgettext() and lngettext() methods.

If multiple files are found, later files are used as fallbacks for earlier ones. To allow setting the fallback, copy.copy() is used to clone each translation object from the cache; the actual instance data is still shared with the cache.

If no .mo file is found, this function raises OSError if fallback is false (which is the default), and returns a NullTranslations instance if fallback is true.

버전 3.3에서 변경: IOError used to be raised instead of OSError.

gettext.install(domain, localedir=None, codeset=None, names=None)

This installs the function _() in Python’s builtins namespace, based on domain, localedir, and codeset which are passed to the function translation().

For the names parameter, please see the description of the translation object’s install() method.

As seen below, you usually mark the strings in your application that are candidates for translation, by wrapping them in a call to the _() function, like this:

print(_('This string will be translated.'))

For convenience, you want the _() function to be installed in Python’s builtins namespace, so it is easily accessible in all modules of your application.

The NullTranslations class

Translation classes are what actually implement the translation of original source file message strings to translated message strings. The base class used by all translation classes is NullTranslations; this provides the basic interface you can use to write your own specialized translation classes. Here are the methods of NullTranslations:

class gettext.NullTranslations(fp=None)

Takes an optional file object fp, which is ignored by the base class. Initializes “protected” instance variables _info and _charset which are set by derived classes, as well as _fallback, which is set through add_fallback(). It then calls self._parse(fp) if fp is not None.

_parse(fp)

No-op in the base class, this method takes file object fp, and reads the data from the file, initializing its message catalog. If you have an unsupported message catalog file format, you should override this method to parse your format.

add_fallback(fallback)

Add fallback as the fallback object for the current translation object. A translation object should consult the fallback if it cannot provide a translation for a given message.

gettext(message)

If a fallback has been set, forward gettext() to the fallback. Otherwise, return message. Overridden in derived classes.

ngettext(singular, plural, n)

If a fallback has been set, forward ngettext() to the fallback. Otherwise, return singular if n is 1; return plural otherwise. Overridden in derived classes.

lgettext(message)

lngettext(singular, plural, n)

Equivalent to gettext() and ngettext(), but the translation is returned as a byte string encoded in the preferred system encoding if no encoding was explicitly set with set_output_charset(). Overridden in derived classes.

경고

These methods should be avoided in Python 3. See the warning for the lgettext() function.

info()

Return the “protected” _info variable, a dictionary containing the metadata found in the message catalog file.

charset()

Return the encoding of the message catalog file.

output_charset()

Return the encoding used to return translated messages in lgettext() and lngettext().

set_output_charset(charset)

Change the encoding used to return translated messages.

install(names=None)

This method installs gettext() into the built-in namespace, binding it to _.

If the names parameter is given, it must be a sequence containing the names of functions you want to install in the builtins namespace in addition to _(). Supported names are 'gettext', 'ngettext', 'lgettext' and 'lngettext'.

Note that this is only one way, albeit the most convenient way, to make the _() function available to your application. Because it affects the entire application globally, and specifically the built-in namespace, localized modules should never install _(). Instead, they should use this code to make _() available to their module:

import gettext
t = gettext.translation('mymodule', ...)
_ = t.gettext

This puts _() only in the module’s global namespace and so only affects calls within this module.

The GNUTranslations class

The gettext module provides one additional class derived from NullTranslations: GNUTranslations. This class overrides _parse() to enable reading GNU gettext format .mo files in both big-endian and little-endian format.

GNUTranslations parses optional metadata out of the translation catalog. It is convention with GNU gettext to include metadata as the translation for the empty string. This metadata is in RFC 822 [https://tools.ietf.org/html/rfc822.html]-style key: value pairs, and should contain the Project-Id-Version key. If the key Content-Type is found, then the charset property is used to initialize the “protected” _charset instance variable, defaulting to None if not found. If the charset encoding is specified, then all message ids and message strings read from the catalog are converted to Unicode using this encoding, else ASCII is assumed.

Since message ids are read as Unicode strings too, all *gettext() methods will assume message ids as Unicode strings, not byte strings.

The entire set of key/value pairs are placed into a dictionary and set as the “protected” _info instance variable.

If the .mo file’s magic number is invalid, the major version number is unexpected, or if other problems occur while reading the file, instantiating a GNUTranslations class can raise OSError.

class gettext.GNUTranslations

The following methods are overridden from the base class implementation:

gettext(message)

Look up the message id in the catalog and return the corresponding message string, as a Unicode string. If there is no entry in the catalog for the message id, and a fallback has been set, the look up is forwarded to the fallback’s gettext() method. Otherwise, the message id is returned.

ngettext(singular, plural, n)

Do a plural-forms lookup of a message id. singular is used as the message id for purposes of lookup in the catalog, while n is used to determine which plural form to use. The returned message string is a Unicode string.

If the message id is not found in the catalog, and a fallback is specified, the request is forwarded to the fallback’s ngettext() method. Otherwise, when n is 1 singular is returned, and plural is returned in all other cases.

Here is an example:

n = len(os.listdir('.'))
cat = GNUTranslations(somefile)
message = cat.ngettext(
    'There is %(num)d file in this directory',
    'There are %(num)d files in this directory',
    n) % {'num': n}

lgettext(message)

lngettext(singular, plural, n)

Equivalent to gettext() and ngettext(), but the translation is returned as a byte string encoded in the preferred system encoding if no encoding was explicitly set with set_output_charset().

경고

These methods should be avoided in Python 3. See the warning for the lgettext() function.

Solaris message catalog support

The Solaris operating system defines its own binary .mo file format, but since no documentation can be found on this format, it is not supported at this time.

The Catalog constructor

GNOME uses a version of the gettext module by James Henstridge, but this version has a slightly different API. Its documented usage was:

import gettext
cat = gettext.Catalog(domain, localedir)
_ = cat.gettext
print(_('hello world'))

For compatibility with this older module, the function Catalog() is an alias for the translation() function described above.

One difference between this module and Henstridge’s: his catalog objects supported access through a mapping API, but this appears to be unused and so is not currently supported.

Internationalizing your programs and modules

Internationalization (I18N) refers to the operation by which a program is made aware of multiple languages. Localization (L10N) refers to the adaptation of your program, once internationalized, to the local language and cultural habits. In order to provide multilingual messages for your Python programs, you need to take the following steps:

prepare your program or module by specially marking translatable strings

run a suite of tools over your marked files to generate raw messages catalogs

create language-specific translations of the message catalogs

use the gettext module so that message strings are properly translated

In order to prepare your code for I18N, you need to look at all the strings in your files. Any string that needs to be translated should be marked by wrapping it in _('...') — that is, a call to the function _(). For example:

filename = 'mylog.txt'
message = _('writing a log message')
with open(filename, 'w') as fp:
    fp.write(message)

In this example, the string 'writing a log message' is marked as a candidate for translation, while the strings 'mylog.txt' and 'w' are not.

There are a few tools to extract the strings meant for translation. The original GNU gettext only supported C or C++ source code but its extended version xgettext scans code written in a number of languages, including Python, to find strings marked as translatable. Babel [http://babel.pocoo.org/] is a Python internationalization library that includes a pybabel script to extract and compile message catalogs. François Pinard’s program called xpot does a similar job and is available as part of his po-utils package [https://github.com/pinard/po-utils].

(Python also includes pure-Python versions of these programs, called pygettext.py and msgfmt.py; some Python distributions will install them for you. pygettext.py is similar to xgettext, but only understands Python source code and cannot handle other programming languages such as C or C++. pygettext.py supports a command-line interface similar to xgettext; for details on its use, run pygettext.py --help. msgfmt.py is binary compatible with GNU msgfmt. With these two programs, you may not need the GNU gettext package to internationalize your Python applications.)

xgettext, pygettext, and similar tools generate .po files that are message catalogs. They are structured human-readable files that contain every marked string in the source code, along with a placeholder for the translated versions of these strings.

Copies of these .po files are then handed over to the individual human translators who write translations for every supported natural language. They send back the completed language-specific versions as a <language-name>.po file that’s compiled into a machine-readable .mo binary catalog file using the msgfmt program. The .mo files are used by the gettext module for the actual translation processing at run-time.

How you use the gettext module in your code depends on whether you are internationalizing a single module or your entire application. The next two sections will discuss each case.

Localizing your module

If you are localizing your module, you must take care not to make global changes, e.g. to the built-in namespace. You should not use the GNU gettext API but instead the class-based API.

Let’s say your module is called “spam” and the module’s various natural language translation .mo files reside in /usr/share/locale in GNU gettext format. Here’s what you would put at the top of your module:

import gettext
t = gettext.translation('spam', '/usr/share/locale')
_ = t.gettext

Localizing your application

If you are localizing your application, you can install the _() function globally into the built-in namespace, usually in the main driver file of your application. This will let all your application-specific files just use _('...') without having to explicitly install it in each file.

In the simple case then, you need only add the following bit of code to the main driver file of your application:

import gettext
gettext.install('myapplication')

If you need to set the locale directory, you can pass it into the install() function:

import gettext
gettext.install('myapplication', '/usr/share/locale')

Changing languages on the fly

If your program needs to support many languages at the same time, you may want to create multiple translation instances and then switch between them explicitly, like so:

import gettext

lang1 = gettext.translation('myapplication', languages=['en'])
lang2 = gettext.translation('myapplication', languages=['fr'])
lang3 = gettext.translation('myapplication', languages=['de'])

# start by using language1
lang1.install()

# ... time goes by, user selects language 2
lang2.install()

# ... more time goes by, user selects language 3
lang3.install()

Deferred translations

In most coding situations, strings are translated where they are coded. Occasionally however, you need to mark strings for translation, but defer actual translation until later. A classic example is:

animals = ['mollusk',
           'albatross',
           'rat',
           'penguin',
           'python', ]
# ...
for a in animals:
    print(a)

Here, you want to mark the strings in the animals list as being translatable, but you don’t actually want to translate them until they are printed.

Here is one way you can handle this situation:

def _(message): return message

animals = [_('mollusk'),
           _('albatross'),
           _('rat'),
           _('penguin'),
           _('python'), ]

del _

# ...
for a in animals:
    print(_(a))

This works because the dummy definition of _() simply returns the string unchanged. And this dummy definition will temporarily override any definition of _() in the built-in namespace (until the del command). Take care, though if you have a previous definition of _() in the local namespace.

Note that the second use of _() will not identify “a” as being translatable to the gettext program, because the parameter is not a string literal.

Another way to handle this is with the following example:

def N_(message): return message

animals = [N_('mollusk'),
           N_('albatross'),
           N_('rat'),
           N_('penguin'),
           N_('python'), ]

# ...
for a in animals:
    print(_(a))

In this case, you are marking translatable strings with the function N_(), which won’t conflict with any definition of _(). However, you will need to teach your message extraction program to look for translatable strings marked with N_(). xgettext, pygettext, pybabel extract, and xpot all support this through the use of the -k command-line switch. The choice of N_() here is totally arbitrary; it could have just as easily been MarkThisStringForTranslation().

Acknowledgements

The following people contributed code, feedback, design suggestions, previous implementations, and valuable experience to the creation of this module:

Peter Funk

James Henstridge

Juan David Ibáñez Palomar

Marc-André Lemburg

Martin von Löwis

François Pinard

Barry Warsaw

Gustavo Niemeyer

Footnotes

1

The default locale directory is system dependent; for example, on RedHat Linux it is /usr/share/locale, but on Solaris it is /usr/lib/locale. The gettext module does not try to support these system dependent defaults; instead its default is sys.base_prefix/share/locale (see sys.base_prefix). For this reason, it is always best to call bindtextdomain() with an explicit absolute path at the start of your application.

2

See the footnote for bindtextdomain() above.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

국제화 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

국제화 »

|

locale — Internationalization services

Source code: Lib/locale.py [https://github.com/python/cpython/tree/3.7/Lib/locale.py]

The locale module opens access to the POSIX locale database and functionality. The POSIX locale mechanism allows programmers to deal with certain cultural issues in an application, without requiring the programmer to know all the specifics of each country where the software is executed.

The locale module is implemented on top of the _locale module, which in turn uses an ANSI C locale implementation if available.

The locale module defines the following exception and functions:

exception locale.Error

Exception raised when the locale passed to setlocale() is not recognized.

locale.setlocale(category, locale=None)

If locale is given and not None, setlocale() modifies the locale setting for the category. The available categories are listed in the data description below. locale may be a string, or an iterable of two strings (language code and encoding). If it’s an iterable, it’s converted to a locale name using the locale aliasing engine. An empty string specifies the user’s default settings. If the modification of the locale fails, the exception Error is raised. If successful, the new locale setting is returned.

If locale is omitted or None, the current setting for category is returned.

setlocale() is not thread-safe on most systems. Applications typically start with a call of

import locale
locale.setlocale(locale.LC_ALL, '')

This sets the locale for all categories to the user’s default setting (typically specified in the LANG environment variable). If the locale is not changed thereafter, using multithreading should not cause problems.

locale.localeconv()

Returns the database of the local conventions as a dictionary. This dictionary has the following strings as keys:

Category

Key

Meaning

LC_NUMERIC

'decimal_point'

Decimal point character.

'grouping'

Sequence of numbers specifying which relative positions the 'thousands_sep' is expected. If the sequence is terminated with CHAR_MAX, no further grouping is performed. If the sequence terminates with a 0, the last group size is repeatedly used.

'thousands_sep'

Character used between groups.

LC_MONETARY

'int_curr_symbol'

International currency symbol.

'currency_symbol'

Local currency symbol.

'p_cs_precedes/n_cs_precedes'

Whether the currency symbol precedes the value (for positive resp. negative values).

'p_sep_by_space/n_sep_by_space'

Whether the currency symbol is separated from the value by a space (for positive resp. negative values).

'mon_decimal_point'

Decimal point used for monetary values.

'frac_digits'

Number of fractional digits used in local formatting of monetary values.

'int_frac_digits'

Number of fractional digits used in international formatting of monetary values.

'mon_thousands_sep'

Group separator used for monetary values.

'mon_grouping'

Equivalent to 'grouping', used for monetary values.

'positive_sign'

Symbol used to annotate a positive monetary value.

'negative_sign'

Symbol used to annotate a negative monetary value.

'p_sign_posn/n_sign_posn'

The position of the sign (for positive resp. negative values), see below.

All numeric values can be set to CHAR_MAX to indicate that there is no value specified in this locale.

The possible values for 'p_sign_posn' and 'n_sign_posn' are given below.

Value

Explanation

0

Currency and value are surrounded by parentheses.

1

The sign should precede the value and currency symbol.

2

The sign should follow the value and currency symbol.

3

The sign should immediately precede the value.

4

The sign should immediately follow the value.

CHAR_MAX

Nothing is specified in this locale.

The function sets temporarily the LC_CTYPE locale to the LC_NUMERIC locale or the LC_MONETARY locale if locales are different and numeric or monetary strings are non-ASCII. This temporary change affects other threads.

버전 3.7에서 변경: The function now sets temporarily the LC_CTYPE locale to the LC_NUMERIC locale in some cases.

locale.nl_langinfo(option)

Return some locale-specific information as a string. This function is not available on all systems, and the set of possible options might also vary across platforms. The possible argument values are numbers, for which symbolic constants are available in the locale module.

The nl_langinfo() function accepts one of the following keys. Most descriptions are taken from the corresponding description in the GNU C library.

locale.CODESET

Get a string with the name of the character encoding used in the selected locale.

locale.D_T_FMT

Get a string that can be used as a format string for time.strftime() to represent date and time in a locale-specific way.

locale.D_FMT

Get a string that can be used as a format string for time.strftime() to represent a date in a locale-specific way.

locale.T_FMT

Get a string that can be used as a format string for time.strftime() to represent a time in a locale-specific way.

locale.T_FMT_AMPM

Get a format string for time.strftime() to represent time in the am/pm format.

DAY_1 ... DAY_7

Get the name of the n-th day of the week.

참고

This follows the US convention of DAY_1 being Sunday, not the international convention (ISO 8601) that Monday is the first day of the week.

ABDAY_1 ... ABDAY_7

Get the abbreviated name of the n-th day of the week.

MON_1 ... MON_12

Get the name of the n-th month.

ABMON_1 ... ABMON_12

Get the abbreviated name of the n-th month.

locale.RADIXCHAR

Get the radix character (decimal dot, decimal comma, etc.).

locale.THOUSEP

Get the separator character for thousands (groups of three digits).

locale.YESEXPR

Get a regular expression that can be used with the regex function to recognize a positive response to a yes/no question.

참고

The expression is in the syntax suitable for the regex() function from the C library, which might differ from the syntax used in re.

locale.NOEXPR

Get a regular expression that can be used with the regex(3) function to recognize a negative response to a yes/no question.

locale.CRNCYSTR

Get the currency symbol, preceded by “-” if the symbol should appear before the value, “+” if the symbol should appear after the value, or “.” if the symbol should replace the radix character.

locale.ERA

Get a string that represents the era used in the current locale.

Most locales do not define this value. An example of a locale which does define this value is the Japanese one. In Japan, the traditional representation of dates includes the name of the era corresponding to the then-emperor’s reign.

Normally it should not be necessary to use this value directly. Specifying the E modifier in their format strings causes the time.strftime() function to use this information. The format of the returned string is not specified, and therefore you should not assume knowledge of it on different systems.

locale.ERA_D_T_FMT

Get a format string for time.strftime() to represent date and time in a locale-specific era-based way.

locale.ERA_D_FMT

Get a format string for time.strftime() to represent a date in a locale-specific era-based way.

locale.ERA_T_FMT

Get a format string for time.strftime() to represent a time in a locale-specific era-based way.

locale.ALT_DIGITS

Get a representation of up to 100 values used to represent the values 0 to 99.

locale.getdefaultlocale([envvars])

Tries to determine the default locale settings and returns them as a tuple of the form (language code, encoding).

According to POSIX, a program which has not called setlocale(LC_ALL, '') runs using the portable 'C' locale. Calling setlocale(LC_ALL, '') lets it use the default locale as defined by the LANG variable. Since we do not want to interfere with the current locale setting we thus emulate the behavior in the way described above.

To maintain compatibility with other platforms, not only the LANG variable is tested, but a list of variables given as envvars parameter. The first found to be defined will be used. envvars defaults to the search path used in GNU gettext; it must always contain the variable name 'LANG'. The GNU gettext search path contains 'LC_ALL', 'LC_CTYPE', 'LANG' and 'LANGUAGE', in that order.

Except for the code 'C', the language code corresponds to RFC 1766 [https://tools.ietf.org/html/rfc1766.html]. language code and encoding may be None if their values cannot be determined.

locale.getlocale(category=LC_CTYPE)

Returns the current setting for the given locale category as sequence containing language code, encoding. category may be one of the LC_* values except LC_ALL. It defaults to LC_CTYPE.

Except for the code 'C', the language code corresponds to RFC 1766 [https://tools.ietf.org/html/rfc1766.html]. language code and encoding may be None if their values cannot be determined.

locale.getpreferredencoding(do_setlocale=True)

Return the encoding used for text data, according to user preferences. User preferences are expressed differently on different systems, and might not be available programmatically on some systems, so this function only returns a guess.

On some systems, it is necessary to invoke setlocale() to obtain the user preferences, so this function is not thread-safe. If invoking setlocale is not necessary or desired, do_setlocale should be set to False.

On Android or in the UTF-8 mode (-X utf8 option), always return 'UTF-8', the locale and the do_setlocale argument are ignored.

버전 3.7에서 변경: The function now always returns UTF-8 on Android or if the UTF-8 mode is enabled.

locale.normalize(localename)

Returns a normalized locale code for the given locale name. The returned locale code is formatted for use with setlocale(). If normalization fails, the original name is returned unchanged.

If the given encoding is not known, the function defaults to the default encoding for the locale code just like setlocale().

locale.resetlocale(category=LC_ALL)

Sets the locale for category to the default setting.

The default setting is determined by calling getdefaultlocale(). category defaults to LC_ALL.

locale.strcoll(string1, string2)

Compares two strings according to the current LC_COLLATE setting. As any other compare function, returns a negative, or a positive value, or 0, depending on whether string1 collates before or after string2 or is equal to it.

locale.strxfrm(string)

Transforms a string to one that can be used in locale-aware comparisons. For example, strxfrm(s1) < strxfrm(s2) is equivalent to strcoll(s1, s2) < 0. This function can be used when the same string is compared repeatedly, e.g. when collating a sequence of strings.

locale.format_string(format, val, grouping=False, monetary=False)

Formats a number val according to the current LC_NUMERIC setting. The format follows the conventions of the % operator. For floating point values, the decimal point is modified if appropriate. If grouping is true, also takes the grouping into account.

If monetary is true, the conversion uses monetary thousands separator and grouping strings.

Processes formatting specifiers as in format % val, but takes the current locale settings into account.

버전 3.7에서 변경: The monetary keyword parameter was added.

locale.format(format, val, grouping=False, monetary=False)

Please note that this function works like format_string() but will only work for exactly one %char specifier. For example, '%f' and '%.0f' are both valid specifiers, but '%f KiB' is not.

For whole format strings, use format_string().

버전 3.7부터 폐지: Use format_string() instead.

locale.currency(val, symbol=True, grouping=False, international=False)

Formats a number val according to the current LC_MONETARY settings.

The returned string includes the currency symbol if symbol is true, which is the default. If grouping is true (which is not the default), grouping is done with the value. If international is true (which is not the default), the international currency symbol is used.

Note that this function will not work with the ‘C’ locale, so you have to set a locale via setlocale() first.

locale.str(float)

Formats a floating point number using the same format as the built-in function str(float), but takes the decimal point into account.

locale.delocalize(string)

Converts a string into a normalized number string, following the LC_NUMERIC settings.

버전 3.5에 추가.

locale.atof(string)

Converts a string to a floating point number, following the LC_NUMERIC settings.

locale.atoi(string)

Converts a string to an integer, following the LC_NUMERIC conventions.

locale.LC_CTYPE

Locale category for the character type functions. Depending on the settings of this category, the functions of module string dealing with case change their behaviour.

locale.LC_COLLATE

Locale category for sorting strings. The functions strcoll() and strxfrm() of the locale module are affected.

locale.LC_TIME

Locale category for the formatting of time. The function time.strftime() follows these conventions.

locale.LC_MONETARY

Locale category for formatting of monetary values. The available options are available from the localeconv() function.

locale.LC_MESSAGES

Locale category for message display. Python currently does not support application specific locale-aware messages. Messages displayed by the operating system, like those returned by os.strerror() might be affected by this category.

locale.LC_NUMERIC

Locale category for formatting numbers. The functions format(), atoi(), atof() and str() of the locale module are affected by that category. All other numeric formatting operations are not affected.

locale.LC_ALL

Combination of all locale settings. If this flag is used when the locale is changed, setting the locale for all categories is attempted. If that fails for any category, no category is changed at all. When the locale is retrieved using this flag, a string indicating the setting for all categories is returned. This string can be later used to restore the settings.

locale.CHAR_MAX

This is a symbolic constant used for different values returned by localeconv().

Example:

>>> import locale
>>> loc = locale.getlocale()  # get current locale
# use German locale; name might vary with platform
>>> locale.setlocale(locale.LC_ALL, 'de_DE')
>>> locale.strcoll('f\xe4n', 'foo')  # compare a string containing an umlaut
>>> locale.setlocale(locale.LC_ALL, '')   # use user's preferred locale
>>> locale.setlocale(locale.LC_ALL, 'C')  # use default (C) locale
>>> locale.setlocale(locale.LC_ALL, loc)  # restore saved locale

Background, details, hints, tips and caveats

The C standard defines the locale as a program-wide property that may be relatively expensive to change. On top of that, some implementation are broken in such a way that frequent locale changes may cause core dumps. This makes the locale somewhat painful to use correctly.

Initially, when a program is started, the locale is the C locale, no matter what the user’s preferred locale is. There is one exception: the LC_CTYPE category is changed at startup to set the current locale encoding to the user’s preferred locale encoding. The program must explicitly say that it wants the user’s preferred locale settings for other categories by calling setlocale(LC_ALL, '').

It is generally a bad idea to call setlocale() in some library routine, since as a side effect it affects the entire program. Saving and restoring it is almost as bad: it is expensive and affects other threads that happen to run before the settings have been restored.

If, when coding a module for general use, you need a locale independent version of an operation that is affected by the locale (such as certain formats used with time.strftime()), you will have to find a way to do it without using the standard library routine. Even better is convincing yourself that using locale settings is okay. Only as a last resort should you document that your module is not compatible with non-C locale settings.

The only way to perform numeric operations according to the locale is to use the special functions defined by this module: atof(), atoi(), format(), str().

There is no way to perform case conversions and character classifications according to the locale. For (Unicode) text strings these are done according to the character value only, while for byte strings, the conversions and classifications are done according to the ASCII value of the byte, and bytes whose high bit is set (i.e., non-ASCII bytes) are never converted or considered part of a character class such as letter or whitespace.

For extension writers and programs that embed Python

Extension modules should never call setlocale(), except to find out what the current locale is. But since the return value can only be used portably to restore it, that is not very useful (except perhaps to find out whether or not the locale is C).

When Python code uses the locale module to change the locale, this also affects the embedding application. If the embedding application doesn’t want this to happen, it should remove the _locale extension module (which does all the work) from the table of built-in modules in the config.c file, and make sure that the _locale module is not accessible as a shared library.

Access to message catalogs

locale.gettext(msg)

locale.dgettext(domain, msg)

locale.dcgettext(domain, msg, category)

locale.textdomain(domain)

locale.bindtextdomain(domain, dir)

The locale module exposes the C library’s gettext interface on systems that provide this interface. It consists of the functions gettext(), dgettext(), dcgettext(), textdomain(), bindtextdomain(), and bind_textdomain_codeset(). These are similar to the same functions in the gettext module, but use the C library’s binary format for message catalogs, and the C library’s search algorithms for locating message catalogs.

Python applications should normally find no need to invoke these functions, and should use gettext instead. A known exception to this rule are applications that link with additional C libraries which internally invoke gettext() or dcgettext(). For these applications, it may be necessary to bind the text domain, so that the libraries can properly locate their message catalogs.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

국제화 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

|

프로그램 프레임워크

이 장에서 설명하는 모듈은 주로 프로그램의 구조를 결정하는 프레임워크입니다. 현재 여기에 설명된 모듈은 모두 명령 줄 인터페이스 작성을 지향합니다.

이 장에서 설명하는 모듈의 전체 목록은 다음과 같습니다:

turtle — Turtle graphics

Introduction

Overview of available Turtle and Screen methods

Turtle methods

Methods of TurtleScreen/Screen

Methods of RawTurtle/Turtle and corresponding functions

Turtle motion

Tell Turtle’s state

Settings for measurement

Pen control

Drawing state

Color control

Filling

More drawing control

Turtle state

Visibility

Appearance

Using events

Special Turtle methods

Compound shapes

Methods of TurtleScreen/Screen and corresponding functions

Window control

Animation control

Using screen events

Input methods

Settings and special methods

Methods specific to Screen, not inherited from TurtleScreen

Public classes

Help and configuration

How to use help

Translation of docstrings into different languages

How to configure Screen and Turtles

turtledemo — Demo scripts

Changes since Python 2.6

Changes since Python 3.0

cmd — 줄 지향 명령 인터프리터 지원

Cmd 객체

Cmd 예

shlex — Simple lexical analysis

shlex Objects

Parsing Rules

Improved Compatibility with Shells

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

프로그램 프레임워크 »

|

turtle — Turtle graphics

Source code: Lib/turtle.py [https://github.com/python/cpython/tree/3.7/Lib/turtle.py]

Introduction

Turtle graphics is a popular way for introducing programming to kids. It was part of the original Logo programming language developed by Wally Feurzeig, Seymour Papert and Cynthia Solomon in 1967.

Imagine a robotic turtle starting at (0, 0) in the x-y plane. After an import turtle, give it the command turtle.forward(15), and it moves (on-screen!) 15 pixels in the direction it is facing, drawing a line as it moves. Give it the command turtle.right(25), and it rotates in-place 25 degrees clockwise.

Turtle star

Turtle can draw intricate shapes using programs that repeat simple moves.

from turtle import *
color('red', 'yellow')
begin_fill()
while True:
    forward(200)
    left(170)
    if abs(pos()) < 1:
        break
end_fill()
done()

By combining together these and similar commands, intricate shapes and pictures can easily be drawn.

The turtle module is an extended reimplementation of the same-named module from the Python standard distribution up to version Python 2.5.

It tries to keep the merits of the old turtle module and to be (nearly) 100% compatible with it. This means in the first place to enable the learning programmer to use all the commands, classes and methods interactively when using the module from within IDLE run with the -n switch.

The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses tkinter for the underlying graphics, it needs a version of Python installed with Tk support.

The object-oriented interface uses essentially two+two classes:

The TurtleScreen class defines graphics windows as a playground for the drawing turtles. Its constructor needs a tkinter.Canvas or a ScrolledCanvas as argument. It should be used when turtle is used as part of some application.

The function Screen() returns a singleton object of a TurtleScreen subclass. This function should be used when turtle is used as a standalone tool for doing graphics. As a singleton object, inheriting from its class is not possible.

All methods of TurtleScreen/Screen also exist as functions, i.e. as part of the procedure-oriented interface.

RawTurtle (alias: RawPen) defines Turtle objects which draw on a TurtleScreen. Its constructor needs a Canvas, ScrolledCanvas or TurtleScreen as argument, so the RawTurtle objects know where to draw.

Derived from RawTurtle is the subclass Turtle (alias: Pen), which draws on “the” Screen instance which is automatically created, if not already present.

All methods of RawTurtle/Turtle also exist as functions, i.e. part of the procedure-oriented interface.

The procedural interface provides functions which are derived from the methods of the classes Screen and Turtle. They have the same names as the corresponding methods. A screen object is automatically created whenever a function derived from a Screen method is called. An (unnamed) turtle object is automatically created whenever any of the functions derived from a Turtle method is called.

To use multiple turtles on a screen one has to use the object-oriented interface.

참고

In the following documentation the argument list for functions is given. Methods, of course, have the additional first argument self which is omitted here.

Overview of available Turtle and Screen methods

Turtle methods

Turtle motion

Move and draw

forward() | fd()

backward() | bk() | back()

right() | rt()

left() | lt()

goto() | setpos() | setposition()

setx()

sety()

setheading() | seth()

home()

circle()

dot()

stamp()

clearstamp()

clearstamps()

undo()

speed()

Tell Turtle’s state

position() | pos()

towards()

xcor()

ycor()

heading()

distance()

Setting and measurement

degrees()

radians()

Pen control

Drawing state

pendown() | pd() | down()

penup() | pu() | up()

pensize() | width()

pen()

isdown()

Color control

color()

pencolor()

fillcolor()

Filling

filling()

begin_fill()

end_fill()

More drawing control

reset()

clear()

write()

Turtle state

Visibility

showturtle() | st()

hideturtle() | ht()

isvisible()

Appearance

shape()

resizemode()

shapesize() | turtlesize()

shearfactor()

settiltangle()

tiltangle()

tilt()

shapetransform()

get_shapepoly()

Using events

onclick()

onrelease()

ondrag()

Special Turtle methods

begin_poly()

end_poly()

get_poly()

clone()

getturtle() | getpen()

getscreen()

setundobuffer()

undobufferentries()

Methods of TurtleScreen/Screen

Window control

bgcolor()

bgpic()

clear() | clearscreen()

reset() | resetscreen()

screensize()

setworldcoordinates()

Animation control

delay()

tracer()

update()

Using screen events

listen()

onkey() | onkeyrelease()

onkeypress()

onclick() | onscreenclick()

ontimer()

mainloop() | done()

Settings and special methods

mode()

colormode()

getcanvas()

getshapes()

register_shape() | addshape()

turtles()

window_height()

window_width()

Input methods

textinput()

numinput()

Methods specific to Screen

bye()

exitonclick()

setup()

title()

Methods of RawTurtle/Turtle and corresponding functions

Most of the examples in this section refer to a Turtle instance called turtle.

Turtle motion

turtle.forward(distance)

turtle.fd(distance)

매개변수

distance – a number (integer or float)

Move the turtle forward by the specified distance, in the direction the turtle is headed.

>>> turtle.position()
(0.00,0.00)
>>> turtle.forward(25)
>>> turtle.position()
(25.00,0.00)
>>> turtle.forward(-75)
>>> turtle.position()
(-50.00,0.00)

turtle.back(distance)

turtle.bk(distance)

turtle.backward(distance)

매개변수

distance – a number

Move the turtle backward by distance, opposite to the direction the turtle is headed. Do not change the turtle’s heading.

>>> turtle.position()
(0.00,0.00)
>>> turtle.backward(30)
>>> turtle.position()
(-30.00,0.00)

turtle.right(angle)

turtle.rt(angle)

매개변수

angle – a number (integer or float)

Turn turtle right by angle units. (Units are by default degrees, but can be set via the degrees() and radians() functions.) Angle orientation depends on the turtle mode, see mode().

>>> turtle.heading()
22.0
>>> turtle.right(45)
>>> turtle.heading()
337.0

turtle.left(angle)

turtle.lt(angle)

매개변수

angle – a number (integer or float)

Turn turtle left by angle units. (Units are by default degrees, but can be set via the degrees() and radians() functions.) Angle orientation depends on the turtle mode, see mode().

>>> turtle.heading()
22.0
>>> turtle.left(45)
>>> turtle.heading()
67.0

turtle.goto(x, y=None)

turtle.setpos(x, y=None)

turtle.setposition(x, y=None)

매개변수

x – a number or a pair/vector of numbers

y – a number or None

If y is None, x must be a pair of coordinates or a Vec2D (e.g. as returned by pos()).

Move turtle to an absolute position. If the pen is down, draw line. Do not change the turtle’s orientation.

>>> tp = turtle.pos()
>>> tp
(0.00,0.00)
>>> turtle.setpos(60,30)
>>> turtle.pos()
(60.00,30.00)
>>> turtle.setpos((20,80))
>>> turtle.pos()
(20.00,80.00)
>>> turtle.setpos(tp)
>>> turtle.pos()
(0.00,0.00)

turtle.setx(x)

매개변수

x – a number (integer or float)

Set the turtle’s first coordinate to x, leave second coordinate unchanged.

>>> turtle.position()
(0.00,240.00)
>>> turtle.setx(10)
>>> turtle.position()
(10.00,240.00)

turtle.sety(y)

매개변수

y – a number (integer or float)

Set the turtle’s second coordinate to y, leave first coordinate unchanged.

>>> turtle.position()
(0.00,40.00)
>>> turtle.sety(-10)
>>> turtle.position()
(0.00,-10.00)

turtle.setheading(to_angle)

turtle.seth(to_angle)

매개변수

to_angle – a number (integer or float)

Set the orientation of the turtle to to_angle. Here are some common directions in degrees:

standard mode

logo mode

0 - east

0 - north

90 - north

90 - east

180 - west

180 - south

270 - south

270 - west

>>> turtle.setheading(90)
>>> turtle.heading()
90.0

turtle.home()

Move turtle to the origin – coordinates (0,0) – and set its heading to its start-orientation (which depends on the mode, see mode()).

>>> turtle.heading()
90.0
>>> turtle.position()
(0.00,-10.00)
>>> turtle.home()
>>> turtle.position()
(0.00,0.00)
>>> turtle.heading()
0.0

turtle.circle(radius, extent=None, steps=None)

매개변수

radius – a number

extent – a number (or None)

steps – an integer (or None)

Draw a circle with given radius. The center is radius units left of the turtle; extent – an angle – determines which part of the circle is drawn. If extent is not given, draw the entire circle. If extent is not a full circle, one endpoint of the arc is the current pen position. Draw the arc in counterclockwise direction if radius is positive, otherwise in clockwise direction. Finally the direction of the turtle is changed by the amount of extent.

As the circle is approximated by an inscribed regular polygon, steps determines the number of steps to use. If not given, it will be calculated automatically. May be used to draw regular polygons.

>>> turtle.home()
>>> turtle.position()
(0.00,0.00)
>>> turtle.heading()
0.0
>>> turtle.circle(50)
>>> turtle.position()
(-0.00,0.00)
>>> turtle.heading()
0.0
>>> turtle.circle(120, 180)  # draw a semicircle
>>> turtle.position()
(0.00,240.00)
>>> turtle.heading()
180.0

turtle.dot(size=None, *color)

매개변수

size – an integer >= 1 (if given)

color – a colorstring or a numeric color tuple

Draw a circular dot with diameter size, using color. If size is not given, the maximum of pensize+4 and 2*pensize is used.

>>> turtle.home()
>>> turtle.dot()
>>> turtle.fd(50); turtle.dot(20, "blue"); turtle.fd(50)
>>> turtle.position()
(100.00,-0.00)
>>> turtle.heading()
0.0

turtle.stamp()

Stamp a copy of the turtle shape onto the canvas at the current turtle position. Return a stamp_id for that stamp, which can be used to delete it by calling clearstamp(stamp_id).

>>> turtle.color("blue")
>>> turtle.stamp()
11
>>> turtle.fd(50)

turtle.clearstamp(stampid)

매개변수

stampid – an integer, must be return value of previous stamp() call

Delete stamp with given stampid.

>>> turtle.position()
(150.00,-0.00)
>>> turtle.color("blue")
>>> astamp = turtle.stamp()
>>> turtle.fd(50)
>>> turtle.position()
(200.00,-0.00)
>>> turtle.clearstamp(astamp)
>>> turtle.position()
(200.00,-0.00)

turtle.clearstamps(n=None)

매개변수

n – an integer (or None)

Delete all or first/last n of turtle’s stamps. If n is None, delete all stamps, if n > 0 delete first n stamps, else if n < 0 delete last n stamps.

>>> for i in range(8):
...     turtle.stamp(); turtle.fd(30)
13
14
15
16
17
18
19
20
>>> turtle.clearstamps(2)
>>> turtle.clearstamps(-2)
>>> turtle.clearstamps()

turtle.undo()

Undo (repeatedly) the last turtle action(s). Number of available undo actions is determined by the size of the undobuffer.

>>> for i in range(4):
...     turtle.fd(50); turtle.lt(80)
...
>>> for i in range(8):
...     turtle.undo()

turtle.speed(speed=None)

매개변수

speed – an integer in the range 0..10 or a speedstring (see below)

Set the turtle’s speed to an integer value in the range 0..10. If no argument is given, return current speed.

If input is a number greater than 10 or smaller than 0.5, speed is set to 0. Speedstrings are mapped to speedvalues as follows:

“fastest”: 0

“fast”: 10

“normal”: 6

“slow”: 3

“slowest”: 1

Speeds from 1 to 10 enforce increasingly faster animation of line drawing and turtle turning.

Attention: speed = 0 means that no animation takes place. forward/back makes turtle jump and likewise left/right make the turtle turn instantly.

>>> turtle.speed()
3
>>> turtle.speed('normal')
>>> turtle.speed()
6
>>> turtle.speed(9)
>>> turtle.speed()
9

Tell Turtle’s state

turtle.position()

turtle.pos()

Return the turtle’s current location (x,y) (as a Vec2D vector).

>>> turtle.pos()
(440.00,-0.00)

turtle.towards(x, y=None)

매개변수

x – a number or a pair/vector of numbers or a turtle instance

y – a number if x is a number, else None

Return the angle between the line from turtle position to position specified by (x,y), the vector or the other turtle. This depends on the turtle’s start orientation which depends on the mode - “standard”/”world” or “logo”).

>>> turtle.goto(10, 10)
>>> turtle.towards(0,0)
225.0

turtle.xcor()

Return the turtle’s x coordinate.

>>> turtle.home()
>>> turtle.left(50)
>>> turtle.forward(100)
>>> turtle.pos()
(64.28,76.60)
>>> print(round(turtle.xcor(), 5))
64.27876

turtle.ycor()

Return the turtle’s y coordinate.

>>> turtle.home()
>>> turtle.left(60)
>>> turtle.forward(100)
>>> print(turtle.pos())
(50.00,86.60)
>>> print(round(turtle.ycor(), 5))
86.60254

turtle.heading()

Return the turtle’s current heading (value depends on the turtle mode, see mode()).

>>> turtle.home()
>>> turtle.left(67)
>>> turtle.heading()
67.0

turtle.distance(x, y=None)

매개변수

x – a number or a pair/vector of numbers or a turtle instance

y – a number if x is a number, else None

Return the distance from the turtle to (x,y), the given vector, or the given other turtle, in turtle step units.

>>> turtle.home()
>>> turtle.distance(30,40)
50.0
>>> turtle.distance((30,40))
50.0
>>> joe = Turtle()
>>> joe.forward(77)
>>> turtle.distance(joe)
77.0

Settings for measurement

turtle.degrees(fullcircle=360.0)

매개변수

fullcircle – a number

Set angle measurement units, i.e. set number of “degrees” for a full circle. Default value is 360 degrees.

>>> turtle.home()
>>> turtle.left(90)
>>> turtle.heading()
90.0

Change angle measurement unit to grad (also known as gon,
grade, or gradian and equals 1/100-th of the right angle.)
>>> turtle.degrees(400.0)
>>> turtle.heading()
100.0
>>> turtle.degrees(360)
>>> turtle.heading()
90.0

turtle.radians()

Set the angle measurement units to radians. Equivalent to degrees(2*math.pi).

>>> turtle.home()
>>> turtle.left(90)
>>> turtle.heading()
90.0
>>> turtle.radians()
>>> turtle.heading()
1.5707963267948966

Pen control

Drawing state

turtle.pendown()

turtle.pd()

turtle.down()

Pull the pen down – drawing when moving.

turtle.penup()

turtle.pu()

turtle.up()

Pull the pen up – no drawing when moving.

turtle.pensize(width=None)

turtle.width(width=None)

매개변수

width – a positive number

Set the line thickness to width or return it. If resizemode is set to “auto” and turtleshape is a polygon, that polygon is drawn with the same line thickness. If no argument is given, the current pensize is returned.

>>> turtle.pensize()
1
>>> turtle.pensize(10)   # from here on lines of width 10 are drawn

turtle.pen(pen=None, **pendict)

매개변수

pen – a dictionary with some or all of the below listed keys

pendict – one or more keyword-arguments with the below listed keys as keywords

Return or set the pen’s attributes in a “pen-dictionary” with the following key/value pairs:

“shown”: True/False

“pendown”: True/False

“pencolor”: color-string or color-tuple

“fillcolor”: color-string or color-tuple

“pensize”: positive number

“speed”: number in range 0..10

“resizemode”: “auto” or “user” or “noresize”

“stretchfactor”: (positive number, positive number)

“outline”: positive number

“tilt”: number

This dictionary can be used as argument for a subsequent call to pen() to restore the former pen-state. Moreover one or more of these attributes can be provided as keyword-arguments. This can be used to set several pen attributes in one statement.

>>> turtle.pen(fillcolor="black", pencolor="red", pensize=10)
>>> sorted(turtle.pen().items())
[('fillcolor', 'black'), ('outline', 1), ('pencolor', 'red'),
 ('pendown', True), ('pensize', 10), ('resizemode', 'noresize'),
 ('shearfactor', 0.0), ('shown', True), ('speed', 9),
 ('stretchfactor', (1.0, 1.0)), ('tilt', 0.0)]
>>> penstate=turtle.pen()
>>> turtle.color("yellow", "")
>>> turtle.penup()
>>> sorted(turtle.pen().items())[:3]
[('fillcolor', ''), ('outline', 1), ('pencolor', 'yellow')]
>>> turtle.pen(penstate, fillcolor="green")
>>> sorted(turtle.pen().items())[:3]
[('fillcolor', 'green'), ('outline', 1), ('pencolor', 'red')]

turtle.isdown()

Return True if pen is down, False if it’s up.

>>> turtle.penup()
>>> turtle.isdown()
False
>>> turtle.pendown()
>>> turtle.isdown()
True

Color control

turtle.pencolor(*args)

Return or set the pencolor.

Four input formats are allowed:

pencolor()

Return the current pencolor as color specification string or as a tuple (see example). May be used as input to another color/pencolor/fillcolor call.

pencolor(colorstring)

Set pencolor to colorstring, which is a Tk color specification string, such as "red", "yellow", or "#33cc8c".

pencolor((r, g, b))

Set pencolor to the RGB color represented by the tuple of r, g, and b. Each of r, g, and b must be in the range 0..colormode, where colormode is either 1.0 or 255 (see colormode()).

pencolor(r, g, b)

Set pencolor to the RGB color represented by r, g, and b. Each of r, g, and b must be in the range 0..colormode.

If turtleshape is a polygon, the outline of that polygon is drawn with the newly set pencolor.

>>> colormode()
1.0
>>> turtle.pencolor()
'red'
>>> turtle.pencolor("brown")
>>> turtle.pencolor()
'brown'
>>> tup = (0.2, 0.8, 0.55)
>>> turtle.pencolor(tup)
>>> turtle.pencolor()
(0.2, 0.8, 0.5490196078431373)
>>> colormode(255)
>>> turtle.pencolor()
(51.0, 204.0, 140.0)
>>> turtle.pencolor('#32c18f')
>>> turtle.pencolor()
(50.0, 193.0, 143.0)

turtle.fillcolor(*args)

Return or set the fillcolor.

Four input formats are allowed:

fillcolor()

Return the current fillcolor as color specification string, possibly in tuple format (see example). May be used as input to another color/pencolor/fillcolor call.

fillcolor(colorstring)

Set fillcolor to colorstring, which is a Tk color specification string, such as "red", "yellow", or "#33cc8c".

fillcolor((r, g, b))

Set fillcolor to the RGB color represented by the tuple of r, g, and b. Each of r, g, and b must be in the range 0..colormode, where colormode is either 1.0 or 255 (see colormode()).

fillcolor(r, g, b)

Set fillcolor to the RGB color represented by r, g, and b. Each of r, g, and b must be in the range 0..colormode.

If turtleshape is a polygon, the interior of that polygon is drawn with the newly set fillcolor.

>>> turtle.fillcolor("violet")
>>> turtle.fillcolor()
'violet'
>>> turtle.pencolor()
(50.0, 193.0, 143.0)
>>> turtle.fillcolor((50, 193, 143))  # Integers, not floats
>>> turtle.fillcolor()
(50.0, 193.0, 143.0)
>>> turtle.fillcolor('#ffffff')
>>> turtle.fillcolor()
(255.0, 255.0, 255.0)

turtle.color(*args)

Return or set pencolor and fillcolor.

Several input formats are allowed. They use 0 to 3 arguments as follows:

color()

Return the current pencolor and the current fillcolor as a pair of color specification strings or tuples as returned by pencolor() and fillcolor().

color(colorstring), color((r,g,b)), color(r,g,b)

Inputs as in pencolor(), set both, fillcolor and pencolor, to the given value.

color(colorstring1, colorstring2), color((r1,g1,b1), (r2,g2,b2))

Equivalent to pencolor(colorstring1) and fillcolor(colorstring2) and analogously if the other input format is used.

If turtleshape is a polygon, outline and interior of that polygon is drawn with the newly set colors.

>>> turtle.color("red", "green")
>>> turtle.color()
('red', 'green')
>>> color("#285078", "#a0c8f0")
>>> color()
((40.0, 80.0, 120.0), (160.0, 200.0, 240.0))

See also: Screen method colormode().

Filling

turtle.filling()

Return fillstate (True if filling, False else).

>>> turtle.begin_fill()
>>> if turtle.filling():
...    turtle.pensize(5)
... else:
...    turtle.pensize(3)

turtle.begin_fill()

To be called just before drawing a shape to be filled.

turtle.end_fill()

Fill the shape drawn after the last call to begin_fill().

Whether or not overlap regions for self-intersecting polygons or multiple shapes are filled depends on the operating system graphics, type of overlap, and number of overlaps. For example, the Turtle star above may be either all yellow or have some white regions.

>>> turtle.color("black", "red")
>>> turtle.begin_fill()
>>> turtle.circle(80)
>>> turtle.end_fill()

More drawing control

turtle.reset()

Delete the turtle’s drawings from the screen, re-center the turtle and set variables to the default values.

>>> turtle.goto(0,-22)
>>> turtle.left(100)
>>> turtle.position()
(0.00,-22.00)
>>> turtle.heading()
100.0
>>> turtle.reset()
>>> turtle.position()
(0.00,0.00)
>>> turtle.heading()
0.0

turtle.clear()

Delete the turtle’s drawings from the screen. Do not move turtle. State and position of the turtle as well as drawings of other turtles are not affected.

turtle.write(arg, move=False, align="left", font=("Arial", 8, "normal"))

매개변수

arg – object to be written to the TurtleScreen

move – True/False

align – one of the strings “left”, “center” or right”

font – a triple (fontname, fontsize, fonttype)

Write text - the string representation of arg - at the current turtle position according to align (“left”, “center” or right”) and with the given font. If move is true, the pen is moved to the bottom-right corner of the text. By default, move is False.

>>> turtle.write("Home = ", True, align="center")
>>> turtle.write((0,0), True)

Turtle state

Visibility

turtle.hideturtle()

turtle.ht()

Make the turtle invisible. It’s a good idea to do this while you’re in the middle of doing some complex drawing, because hiding the turtle speeds up the drawing observably.

>>> turtle.hideturtle()

turtle.showturtle()

turtle.st()

Make the turtle visible.

>>> turtle.showturtle()

turtle.isvisible()

Return True if the Turtle is shown, False if it’s hidden.

>>> turtle.hideturtle()
>>> turtle.isvisible()
False
>>> turtle.showturtle()
>>> turtle.isvisible()
True

Appearance

turtle.shape(name=None)

매개변수

name – a string which is a valid shapename

Set turtle shape to shape with given name or, if name is not given, return name of current shape. Shape with name must exist in the TurtleScreen’s shape dictionary. Initially there are the following polygon shapes: “arrow”, “turtle”, “circle”, “square”, “triangle”, “classic”. To learn about how to deal with shapes see Screen method register_shape().

>>> turtle.shape()
'classic'
>>> turtle.shape("turtle")
>>> turtle.shape()
'turtle'

turtle.resizemode(rmode=None)

매개변수

rmode – one of the strings “auto”, “user”, “noresize”

Set resizemode to one of the values: “auto”, “user”, “noresize”. If rmode is not given, return current resizemode. Different resizemodes have the following effects:

“auto”: adapts the appearance of the turtle corresponding to the value of pensize.

“user”: adapts the appearance of the turtle according to the values of stretchfactor and outlinewidth (outline), which are set by shapesize().

“noresize”: no adaption of the turtle’s appearance takes place.

resizemode(“user”) is called by shapesize() when used with arguments.

>>> turtle.resizemode()
'noresize'
>>> turtle.resizemode("auto")
>>> turtle.resizemode()
'auto'

turtle.shapesize(stretch_wid=None, stretch_len=None, outline=None)

turtle.turtlesize(stretch_wid=None, stretch_len=None, outline=None)

매개변수

stretch_wid – positive number

stretch_len – positive number

outline – positive number

Return or set the pen’s attributes x/y-stretchfactors and/or outline. Set resizemode to “user”. If and only if resizemode is set to “user”, the turtle will be displayed stretched according to its stretchfactors: stretch_wid is stretchfactor perpendicular to its orientation, stretch_len is stretchfactor in direction of its orientation, outline determines the width of the shapes’s outline.

>>> turtle.shapesize()
(1.0, 1.0, 1)
>>> turtle.resizemode("user")
>>> turtle.shapesize(5, 5, 12)
>>> turtle.shapesize()
(5, 5, 12)
>>> turtle.shapesize(outline=8)
>>> turtle.shapesize()
(5, 5, 8)

turtle.shearfactor(shear=None)

매개변수

shear – number (optional)

Set or return the current shearfactor. Shear the turtleshape according to the given shearfactor shear, which is the tangent of the shear angle. Do not change the turtle’s heading (direction of movement). If shear is not given: return the current shearfactor, i. e. the tangent of the shear angle, by which lines parallel to the heading of the turtle are sheared.

>>> turtle.shape("circle")
>>> turtle.shapesize(5,2)
>>> turtle.shearfactor(0.5)
>>> turtle.shearfactor()
0.5

turtle.tilt(angle)

매개변수

angle – a number

Rotate the turtleshape by angle from its current tilt-angle, but do not change the turtle’s heading (direction of movement).

>>> turtle.reset()
>>> turtle.shape("circle")
>>> turtle.shapesize(5,2)
>>> turtle.tilt(30)
>>> turtle.fd(50)
>>> turtle.tilt(30)
>>> turtle.fd(50)

turtle.settiltangle(angle)

매개변수

angle – a number

Rotate the turtleshape to point in the direction specified by angle, regardless of its current tilt-angle. Do not change the turtle’s heading (direction of movement).

>>> turtle.reset()
>>> turtle.shape("circle")
>>> turtle.shapesize(5,2)
>>> turtle.settiltangle(45)
>>> turtle.fd(50)
>>> turtle.settiltangle(-45)
>>> turtle.fd(50)

버전 3.1부터 폐지.

turtle.tiltangle(angle=None)

매개변수

angle – a number (optional)

Set or return the current tilt-angle. If angle is given, rotate the turtleshape to point in the direction specified by angle, regardless of its current tilt-angle. Do not change the turtle’s heading (direction of movement). If angle is not given: return the current tilt-angle, i. e. the angle between the orientation of the turtleshape and the heading of the turtle (its direction of movement).

>>> turtle.reset()
>>> turtle.shape("circle")
>>> turtle.shapesize(5,2)
>>> turtle.tilt(45)
>>> turtle.tiltangle()
45.0

turtle.shapetransform(t11=None, t12=None, t21=None, t22=None)

매개변수

t11 – a number (optional)

t12 – a number (optional)

t21 – a number (optional)

t12 – a number (optional)

Set or return the current transformation matrix of the turtle shape.

If none of the matrix elements are given, return the transformation matrix as a tuple of 4 elements. Otherwise set the given elements and transform the turtleshape according to the matrix consisting of first row t11, t12 and second row t21, 22. The determinant t11 * t22 - t12 * t21 must not be zero, otherwise an error is raised. Modify stretchfactor, shearfactor and tiltangle according to the given matrix.

>>> turtle = Turtle()
>>> turtle.shape("square")
>>> turtle.shapesize(4,2)
>>> turtle.shearfactor(-0.5)
>>> turtle.shapetransform()
(4.0, -1.0, -0.0, 2.0)

turtle.get_shapepoly()

Return the current shape polygon as tuple of coordinate pairs. This can be used to define a new shape or components of a compound shape.

>>> turtle.shape("square")
>>> turtle.shapetransform(4, -1, 0, 2)
>>> turtle.get_shapepoly()
((50, -20), (30, 20), (-50, 20), (-30, -20))

Using events

turtle.onclick(fun, btn=1, add=None)

매개변수

fun – a function with two arguments which will be called with the coordinates of the clicked point on the canvas

btn – number of the mouse-button, defaults to 1 (left mouse button)

add – True or False – if True, a new binding will be added, otherwise it will replace a former binding

Bind fun to mouse-click events on this turtle. If fun is None, existing bindings are removed. Example for the anonymous turtle, i.e. the procedural way:

>>> def turn(x, y):
...     left(180)
...
>>> onclick(turn)  # Now clicking into the turtle will turn it.
>>> onclick(None)  # event-binding will be removed

turtle.onrelease(fun, btn=1, add=None)

매개변수

fun – a function with two arguments which will be called with the coordinates of the clicked point on the canvas

btn – number of the mouse-button, defaults to 1 (left mouse button)

add – True or False – if True, a new binding will be added, otherwise it will replace a former binding

Bind fun to mouse-button-release events on this turtle. If fun is None, existing bindings are removed.

>>> class MyTurtle(Turtle):
...     def glow(self,x,y):
...         self.fillcolor("red")
...     def unglow(self,x,y):
...         self.fillcolor("")
...
>>> turtle = MyTurtle()
>>> turtle.onclick(turtle.glow)     # clicking on turtle turns fillcolor red,
>>> turtle.onrelease(turtle.unglow) # releasing turns it to transparent.

turtle.ondrag(fun, btn=1, add=None)

매개변수

fun – a function with two arguments which will be called with the coordinates of the clicked point on the canvas

btn – number of the mouse-button, defaults to 1 (left mouse button)

add – True or False – if True, a new binding will be added, otherwise it will replace a former binding

Bind fun to mouse-move events on this turtle. If fun is None, existing bindings are removed.

Remark: Every sequence of mouse-move-events on a turtle is preceded by a mouse-click event on that turtle.

>>> turtle.ondrag(turtle.goto)

Subsequently, clicking and dragging the Turtle will move it across the screen thereby producing handdrawings (if pen is down).

Special Turtle methods

turtle.begin_poly()

Start recording the vertices of a polygon. Current turtle position is first vertex of polygon.

turtle.end_poly()

Stop recording the vertices of a polygon. Current turtle position is last vertex of polygon. This will be connected with the first vertex.

turtle.get_poly()

Return the last recorded polygon.

>>> turtle.home()
>>> turtle.begin_poly()
>>> turtle.fd(100)
>>> turtle.left(20)
>>> turtle.fd(30)
>>> turtle.left(60)
>>> turtle.fd(50)
>>> turtle.end_poly()
>>> p = turtle.get_poly()
>>> register_shape("myFavouriteShape", p)

turtle.clone()

Create and return a clone of the turtle with same position, heading and turtle properties.

>>> mick = Turtle()
>>> joe = mick.clone()

turtle.getturtle()

turtle.getpen()

Return the Turtle object itself. Only reasonable use: as a function to return the “anonymous turtle”:

>>> pet = getturtle()
>>> pet.fd(50)
>>> pet
<turtle.Turtle object at 0x...>

turtle.getscreen()

Return the TurtleScreen object the turtle is drawing on. TurtleScreen methods can then be called for that object.

>>> ts = turtle.getscreen()
>>> ts
<turtle._Screen object at 0x...>
>>> ts.bgcolor("pink")

turtle.setundobuffer(size)

매개변수

size – an integer or None

Set or disable undobuffer. If size is an integer an empty undobuffer of given size is installed. size gives the maximum number of turtle actions that can be undone by the undo() method/function. If size is None, the undobuffer is disabled.

>>> turtle.setundobuffer(42)

turtle.undobufferentries()

Return number of entries in the undobuffer.

>>> while undobufferentries():
...     undo()

Compound shapes

To use compound turtle shapes, which consist of several polygons of different color, you must use the helper class Shape explicitly as described below:

Create an empty Shape object of type “compound”.

Add as many components to this object as desired, using the addcomponent() method.

For example:

>>> s = Shape("compound")
>>> poly1 = ((0,0),(10,-5),(0,10),(-10,-5))
>>> s.addcomponent(poly1, "red", "blue")
>>> poly2 = ((0,0),(10,-5),(-10,-5))
>>> s.addcomponent(poly2, "blue", "red")

Now add the Shape to the Screen’s shapelist and use it:

>>> register_shape("myshape", s)
>>> shape("myshape")

참고

The Shape class is used internally by the register_shape() method in different ways. The application programmer has to deal with the Shape class only when using compound shapes like shown above!

Methods of TurtleScreen/Screen and corresponding functions

Most of the examples in this section refer to a TurtleScreen instance called screen.

Window control

turtle.bgcolor(*args)

매개변수

args – a color string or three numbers in the range 0..colormode or a 3-tuple of such numbers

Set or return background color of the TurtleScreen.

>>> screen.bgcolor("orange")
>>> screen.bgcolor()
'orange'
>>> screen.bgcolor("#800080")
>>> screen.bgcolor()
(128.0, 0.0, 128.0)

turtle.bgpic(picname=None)

매개변수

picname – a string, name of a gif-file or "nopic", or None

Set background image or return name of current backgroundimage. If picname is a filename, set the corresponding image as background. If picname is "nopic", delete background image, if present. If picname is None, return the filename of the current backgroundimage.

>>> screen.bgpic()
'nopic'
>>> screen.bgpic("landscape.gif")
>>> screen.bgpic()
"landscape.gif"

turtle.clear()

turtle.clearscreen()

Delete all drawings and all turtles from the TurtleScreen. Reset the now empty TurtleScreen to its initial state: white background, no background image, no event bindings and tracing on.

참고

This TurtleScreen method is available as a global function only under the name clearscreen. The global function clear is a different one derived from the Turtle method clear.

turtle.reset()

turtle.resetscreen()

Reset all Turtles on the Screen to their initial state.

참고

This TurtleScreen method is available as a global function only under the name resetscreen. The global function reset is another one derived from the Turtle method reset.

turtle.screensize(canvwidth=None, canvheight=None, bg=None)

매개변수

canvwidth – positive integer, new width of canvas in pixels

canvheight – positive integer, new height of canvas in pixels

bg – colorstring or color-tuple, new background color

If no arguments are given, return current (canvaswidth, canvasheight). Else resize the canvas the turtles are drawing on. Do not alter the drawing window. To observe hidden parts of the canvas, use the scrollbars. With this method, one can make visible those parts of a drawing which were outside the canvas before.

>>> screen.screensize()
(400, 300)
>>> screen.screensize(2000,1500)
>>> screen.screensize()
(2000, 1500)

e.g. to search for an erroneously escaped turtle ;-)

turtle.setworldcoordinates(llx, lly, urx, ury)

매개변수

llx – a number, x-coordinate of lower left corner of canvas

lly – a number, y-coordinate of lower left corner of canvas

urx – a number, x-coordinate of upper right corner of canvas

ury – a number, y-coordinate of upper right corner of canvas

Set up user-defined coordinate system and switch to mode “world” if necessary. This performs a screen.reset(). If mode “world” is already active, all drawings are redrawn according to the new coordinates.

ATTENTION: in user-defined coordinate systems angles may appear distorted.

>>> screen.reset()
>>> screen.setworldcoordinates(-50,-7.5,50,7.5)
>>> for _ in range(72):
...     left(10)
...
>>> for _ in range(8):
...     left(45); fd(2)   # a regular octagon

Animation control

turtle.delay(delay=None)

매개변수

delay – positive integer

Set or return the drawing delay in milliseconds. (This is approximately the time interval between two consecutive canvas updates.) The longer the drawing delay, the slower the animation.

Optional argument:

>>> screen.delay()
10
>>> screen.delay(5)
>>> screen.delay()
5

turtle.tracer(n=None, delay=None)

매개변수

n – nonnegative integer

delay – nonnegative integer

Turn turtle animation on/off and set delay for update drawings. If n is given, only each n-th regular screen update is really performed. (Can be used to accelerate the drawing of complex graphics.) When called without arguments, returns the currently stored value of n. Second argument sets delay value (see delay()).

>>> screen.tracer(8, 25)
>>> dist = 2
>>> for i in range(200):
...     fd(dist)
...     rt(90)
...     dist += 2

turtle.update()

Perform a TurtleScreen update. To be used when tracer is turned off.

See also the RawTurtle/Turtle method speed().

Using screen events

turtle.listen(xdummy=None, ydummy=None)

Set focus on TurtleScreen (in order to collect key-events). Dummy arguments are provided in order to be able to pass listen() to the onclick method.

turtle.onkey(fun, key)

turtle.onkeyrelease(fun, key)

매개변수

fun – a function with no arguments or None

key – a string: key (e.g. “a”) or key-symbol (e.g. “space”)

Bind fun to key-release event of key. If fun is None, event bindings are removed. Remark: in order to be able to register key-events, TurtleScreen must have the focus. (See method listen().)

>>> def f():
...     fd(50)
...     lt(60)
...
>>> screen.onkey(f, "Up")
>>> screen.listen()

turtle.onkeypress(fun, key=None)

매개변수

fun – a function with no arguments or None

key – a string: key (e.g. “a”) or key-symbol (e.g. “space”)

Bind fun to key-press event of key if key is given, or to any key-press-event if no key is given. Remark: in order to be able to register key-events, TurtleScreen must have focus. (See method listen().)

>>> def f():
...     fd(50)
...
>>> screen.onkey(f, "Up")
>>> screen.listen()

turtle.onclick(fun, btn=1, add=None)

turtle.onscreenclick(fun, btn=1, add=None)

매개변수

fun – a function with two arguments which will be called with the coordinates of the clicked point on the canvas

btn – number of the mouse-button, defaults to 1 (left mouse button)

add – True or False – if True, a new binding will be added, otherwise it will replace a former binding

Bind fun to mouse-click events on this screen. If fun is None, existing bindings are removed.

Example for a TurtleScreen instance named screen and a Turtle instance named turtle:

>>> screen.onclick(turtle.goto) # Subsequently clicking into the TurtleScreen will
>>>                             # make the turtle move to the clicked point.
>>> screen.onclick(None)        # remove event binding again

참고

This TurtleScreen method is available as a global function only under the name onscreenclick. The global function onclick is another one derived from the Turtle method onclick.

turtle.ontimer(fun, t=0)

매개변수

fun – a function with no arguments

t – a number >= 0

Install a timer that calls fun after t milliseconds.

>>> running = True
>>> def f():
...     if running:
...         fd(50)
...         lt(60)
...         screen.ontimer(f, 250)
>>> f()   ### makes the turtle march around
>>> running = False

turtle.mainloop()

turtle.done()

Starts event loop - calling Tkinter’s mainloop function. Must be the last statement in a turtle graphics program. Must not be used if a script is run from within IDLE in -n mode (No subprocess) - for interactive use of turtle graphics.

>>> screen.mainloop()

Input methods

turtle.textinput(title, prompt)

매개변수

title – string

prompt – string

Pop up a dialog window for input of a string. Parameter title is the title of the dialog window, prompt is a text mostly describing what information to input. Return the string input. If the dialog is canceled, return None.

>>> screen.textinput("NIM", "Name of first player:")

turtle.numinput(title, prompt, default=None, minval=None, maxval=None)

매개변수

title – string

prompt – string

default – number (optional)

minval – number (optional)

maxval – number (optional)

Pop up a dialog window for input of a number. title is the title of the dialog window, prompt is a text mostly describing what numerical information to input. default: default value, minval: minimum value for input, maxval: maximum value for input The number input must be in the range minval .. maxval if these are given. If not, a hint is issued and the dialog remains open for correction. Return the number input. If the dialog is canceled, return None.

>>> screen.numinput("Poker", "Your stakes:", 1000, minval=10, maxval=10000)

Settings and special methods

turtle.mode(mode=None)

매개변수

mode – one of the strings “standard”, “logo” or “world”

Set turtle mode (“standard”, “logo” or “world”) and perform reset. If mode is not given, current mode is returned.

Mode “standard” is compatible with old turtle. Mode “logo” is compatible with most Logo turtle graphics. Mode “world” uses user-defined “world coordinates”. Attention: in this mode angles appear distorted if x/y unit-ratio doesn’t equal 1.

Mode

Initial turtle heading

positive angles

“standard”

to the right (east)

counterclockwise

“logo”

upward (north)

clockwise

>>> mode("logo")   # resets turtle heading to north
>>> mode()
'logo'

turtle.colormode(cmode=None)

매개변수

cmode – one of the values 1.0 or 255

Return the colormode or set it to 1.0 or 255. Subsequently r, g, b values of color triples have to be in the range 0..cmode.

>>> screen.colormode(1)
>>> turtle.pencolor(240, 160, 80)
Traceback (most recent call last):
     ...
TurtleGraphicsError: bad color sequence: (240, 160, 80)
>>> screen.colormode()
1.0
>>> screen.colormode(255)
>>> screen.colormode()
255
>>> turtle.pencolor(240,160,80)

turtle.getcanvas()

Return the Canvas of this TurtleScreen. Useful for insiders who know what to do with a Tkinter Canvas.

>>> cv = screen.getcanvas()
>>> cv
<turtle.ScrolledCanvas object ...>

turtle.getshapes()

Return a list of names of all currently available turtle shapes.

>>> screen.getshapes()
['arrow', 'blank', 'circle', ..., 'turtle']

turtle.register_shape(name, shape=None)

turtle.addshape(name, shape=None)

There are three different ways to call this function:

name is the name of a gif-file and shape is None: Install the corresponding image shape.

>>> screen.register_shape("turtle.gif")

참고

Image shapes do not rotate when turning the turtle, so they do not display the heading of the turtle!

name is an arbitrary string and shape is a tuple of pairs of coordinates: Install the corresponding polygon shape.

>>> screen.register_shape("triangle", ((5,-3), (0,5), (-5,-3)))

name is an arbitrary string and shape is a (compound) Shape object: Install the corresponding compound shape.

Add a turtle shape to TurtleScreen’s shapelist. Only thusly registered shapes can be used by issuing the command shape(shapename).

turtle.turtles()

Return the list of turtles on the screen.

>>> for turtle in screen.turtles():
...     turtle.color("red")

turtle.window_height()

Return the height of the turtle window.

>>> screen.window_height()
480

turtle.window_width()

Return the width of the turtle window.

>>> screen.window_width()
640

Methods specific to Screen, not inherited from TurtleScreen

turtle.bye()

Shut the turtlegraphics window.

turtle.exitonclick()

Bind bye() method to mouse clicks on the Screen.

If the value “using_IDLE” in the configuration dictionary is False (default value), also enter mainloop. Remark: If IDLE with the -n switch (no subprocess) is used, this value should be set to True in turtle.cfg. In this case IDLE’s own mainloop is active also for the client script.

turtle.setup(width=_CFG["width"], height=_CFG["height"], startx=_CFG["leftright"], starty=_CFG["topbottom"])

Set the size and position of the main window. Default values of arguments are stored in the configuration dictionary and can be changed via a turtle.cfg file.

매개변수

width – if an integer, a size in pixels, if a float, a fraction of the screen; default is 50% of screen

height – if an integer, the height in pixels, if a float, a fraction of the screen; default is 75% of screen

startx – if positive, starting position in pixels from the left edge of the screen, if negative from the right edge, if None, center window horizontally

starty – if positive, starting position in pixels from the top edge of the screen, if negative from the bottom edge, if None, center window vertically

>>> screen.setup (width=200, height=200, startx=0, starty=0)
>>>              # sets window to 200x200 pixels, in upper left of screen
>>> screen.setup(width=.75, height=0.5, startx=None, starty=None)
>>>              # sets window to 75% of screen by 50% of screen and centers

turtle.title(titlestring)

매개변수

titlestring – a string that is shown in the titlebar of the turtle graphics window

Set title of turtle window to titlestring.

>>> screen.title("Welcome to the turtle zoo!")

Public classes

class turtle.RawTurtle(canvas)

class turtle.RawPen(canvas)

매개변수

canvas – a tkinter.Canvas, a ScrolledCanvas or a TurtleScreen

Create a turtle. The turtle has all methods described above as “methods of Turtle/RawTurtle”.

class turtle.Turtle

Subclass of RawTurtle, has the same interface but draws on a default Screen object created automatically when needed for the first time.

class turtle.TurtleScreen(cv)

매개변수

cv – a tkinter.Canvas

Provides screen oriented methods like setbg() etc. that are described above.

class turtle.Screen

Subclass of TurtleScreen, with four methods added.

class turtle.ScrolledCanvas(master)

매개변수

master – some Tkinter widget to contain the ScrolledCanvas, i.e. a Tkinter-canvas with scrollbars added

Used by class Screen, which thus automatically provides a ScrolledCanvas as playground for the turtles.

class turtle.Shape(type_, data)

매개변수

type_ – one of the strings “polygon”, “image”, “compound”

Data structure modeling shapes. The pair (type_, data) must follow this specification:

type_

data

“polygon”

a polygon-tuple, i.e. a tuple of pairs of coordinates

“image”

an image (in this form only used internally!)

“compound”

None (a compound shape has to be constructed using the addcomponent() method)

addcomponent(poly, fill, outline=None)

매개변수

poly – a polygon, i.e. a tuple of pairs of numbers

fill – a color the poly will be filled with

outline – a color for the poly’s outline (if given)

Example:

>>> poly = ((0,0),(10,-5),(0,10),(-10,-5))
>>> s = Shape("compound")
>>> s.addcomponent(poly, "red", "blue")
>>> # ... add more components and then use register_shape()

See Compound shapes.

class turtle.Vec2D(x, y)

A two-dimensional vector class, used as a helper class for implementing turtle graphics. May be useful for turtle graphics programs too. Derived from tuple, so a vector is a tuple!

Provides (for a, b vectors, k number):

a + b vector addition

a - b vector subtraction

a * b inner product

k * a and a * k multiplication with scalar

abs(a) absolute value of a

a.rotate(angle) rotation

Help and configuration

How to use help

The public methods of the Screen and Turtle classes are documented extensively via docstrings. So these can be used as online-help via the Python help facilities:

When using IDLE, tooltips show the signatures and first lines of the docstrings of typed in function-/method calls.

Calling help() on methods or functions displays the docstrings:

>>> help(Screen.bgcolor)
Help on method bgcolor in module turtle:

bgcolor(self, *args) unbound turtle.Screen method
    Set or return backgroundcolor of the TurtleScreen.

    Arguments (if given): a color string or three numbers
    in the range 0..colormode or a 3-tuple of such numbers.

      >>> screen.bgcolor("orange")
      >>> screen.bgcolor()
      "orange"
      >>> screen.bgcolor(0.5,0,0.5)
      >>> screen.bgcolor()
      "#800080"

>>> help(Turtle.penup)
Help on method penup in module turtle:

penup(self) unbound turtle.Turtle method
    Pull the pen up -- no drawing when moving.

    Aliases: penup | pu | up

    No argument

    >>> turtle.penup()

The docstrings of the functions which are derived from methods have a modified form:

>>> help(bgcolor)
Help on function bgcolor in module turtle:

bgcolor(*args)
    Set or return backgroundcolor of the TurtleScreen.

    Arguments (if given): a color string or three numbers
    in the range 0..colormode or a 3-tuple of such numbers.

    Example::

      >>> bgcolor("orange")
      >>> bgcolor()
      "orange"
      >>> bgcolor(0.5,0,0.5)
      >>> bgcolor()
      "#800080"

>>> help(penup)
Help on function penup in module turtle:

penup()
    Pull the pen up -- no drawing when moving.

    Aliases: penup | pu | up

    No argument

    Example:
    >>> penup()

These modified docstrings are created automatically together with the function definitions that are derived from the methods at import time.

Translation of docstrings into different languages

There is a utility to create a dictionary the keys of which are the method names and the values of which are the docstrings of the public methods of the classes Screen and Turtle.

turtle.write_docstringdict(filename="turtle_docstringdict")

매개변수

filename – a string, used as filename

Create and write docstring-dictionary to a Python script with the given filename. This function has to be called explicitly (it is not used by the turtle graphics classes). The docstring dictionary will be written to the Python script filename.py. It is intended to serve as a template for translation of the docstrings into different languages.

If you (or your students) want to use turtle with online help in your native language, you have to translate the docstrings and save the resulting file as e.g. turtle_docstringdict_german.py.

If you have an appropriate entry in your turtle.cfg file this dictionary will be read in at import time and will replace the original English docstrings.

At the time of this writing there are docstring dictionaries in German and in Italian. (Requests please to glingl@aon.at.)

How to configure Screen and Turtles

The built-in default configuration mimics the appearance and behaviour of the old turtle module in order to retain best possible compatibility with it.

If you want to use a different configuration which better reflects the features of this module or which better fits to your needs, e.g. for use in a classroom, you can prepare a configuration file turtle.cfg which will be read at import time and modify the configuration according to its settings.

The built in configuration would correspond to the following turtle.cfg:

width = 0.5
height = 0.75
leftright = None
topbottom = None
canvwidth = 400
canvheight = 300
mode = standard
colormode = 1.0
delay = 10
undobuffersize = 1000
shape = classic
pencolor = black
fillcolor = black
resizemode = noresize
visible = True
language = english
exampleturtle = turtle
examplescreen = screen
title = Python Turtle Graphics
using_IDLE = False

Short explanation of selected entries:

The first four lines correspond to the arguments of the Screen.setup() method.

Line 5 and 6 correspond to the arguments of the method Screen.screensize().

shape can be any of the built-in shapes, e.g: arrow, turtle, etc. For more info try help(shape).

If you want to use no fillcolor (i.e. make the turtle transparent), you have to write fillcolor = "" (but all nonempty strings must not have quotes in the cfg-file).

If you want to reflect the turtle its state, you have to use resizemode = auto.

If you set e.g. language = italian the docstringdict turtle_docstringdict_italian.py will be loaded at import time (if present on the import path, e.g. in the same directory as turtle.

The entries exampleturtle and examplescreen define the names of these objects as they occur in the docstrings. The transformation of method-docstrings to function-docstrings will delete these names from the docstrings.

using_IDLE: Set this to True if you regularly work with IDLE and its -n switch (“no subprocess”). This will prevent exitonclick() to enter the mainloop.

There can be a turtle.cfg file in the directory where turtle is stored and an additional one in the current working directory. The latter will override the settings of the first one.

The Lib/turtledemo directory contains a turtle.cfg file. You can study it as an example and see its effects when running the demos (preferably not from within the demo-viewer).

turtledemo — Demo scripts

The turtledemo package includes a set of demo scripts. These scripts can be run and viewed using the supplied demo viewer as follows:

python -m turtledemo

Alternatively, you can run the demo scripts individually. For example,

python -m turtledemo.bytedesign

The turtledemo package directory contains:

A demo viewer __main__.py which can be used to view the sourcecode of the scripts and run them at the same time.

Multiple scripts demonstrating different features of the turtle module. Examples can be accessed via the Examples menu. They can also be run standalone.

A turtle.cfg file which serves as an example of how to write and use such files.

The demo scripts are:

Name

Description

Features

bytedesign

complex classical turtle graphics pattern

tracer(), delay, update()

chaos

graphs Verhulst dynamics, shows that computer’s computations can generate results sometimes against the common sense expectations

world coordinates

clock

analog clock showing time of your computer

turtles as clock’s hands, ontimer

colormixer

experiment with r, g, b

ondrag()

forest

3 breadth-first trees

randomization

fractalcurves

Hilbert & Koch curves

recursion

lindenmayer

ethnomathematics (indian kolams)

L-System

minimal_hanoi

Towers of Hanoi

Rectangular Turtles as Hanoi discs (shape, shapesize)

nim

play the classical nim game with three heaps of sticks against the computer.

turtles as nimsticks, event driven (mouse, keyboard)

paint

super minimalistic drawing program

onclick()

peace

elementary

turtle: appearance and animation

penrose

aperiodic tiling with kites and darts

stamp()

planet_and_moon

simulation of gravitational system

compound shapes, Vec2D

round_dance

dancing turtles rotating pairwise in opposite direction

compound shapes, clone shapesize, tilt, get_shapepoly, update

sorting_animate

visual demonstration of different sorting methods

simple alignment, randomization

tree

a (graphical) breadth first tree (using generators)

clone()

two_canvases

simple design

turtles on two canvases

wikipedia

a pattern from the wikipedia article on turtle graphics

clone(), undo()

yinyang

another elementary example

circle()

Have fun!

Changes since Python 2.6

The methods Turtle.tracer(), Turtle.window_width() and Turtle.window_height() have been eliminated. Methods with these names and functionality are now available only as methods of Screen. The functions derived from these remain available. (In fact already in Python 2.6 these methods were merely duplications of the corresponding TurtleScreen/Screen-methods.)

The method Turtle.fill() has been eliminated. The behaviour of begin_fill() and end_fill() have changed slightly: now every filling-process must be completed with an end_fill() call.

A method Turtle.filling() has been added. It returns a boolean value: True if a filling process is under way, False otherwise. This behaviour corresponds to a fill() call without arguments in Python 2.6.

Changes since Python 3.0

The methods Turtle.shearfactor(), Turtle.shapetransform() and Turtle.get_shapepoly() have been added. Thus the full range of regular linear transforms is now available for transforming turtle shapes. Turtle.tiltangle() has been enhanced in functionality: it now can be used to get or set the tiltangle. Turtle.settiltangle() has been deprecated.

The method Screen.onkeypress() has been added as a complement to Screen.onkey() which in fact binds actions to the keyrelease event. Accordingly the latter has got an alias: Screen.onkeyrelease().

The method Screen.mainloop() has been added. So when working only with Screen and Turtle objects one must not additionally import mainloop() anymore.

Two input methods has been added Screen.textinput() and Screen.numinput(). These popup input dialogs and return strings and numbers respectively.

Two example scripts tdemo_nim.py and tdemo_round_dance.py have been added to the Lib/turtledemo directory.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

프로그램 프레임워크 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

프로그램 프레임워크 »

|

cmd — 줄 지향 명령 인터프리터 지원

소스 코드: Lib/cmd.py [https://github.com/python/cpython/tree/3.7/Lib/cmd.py]

Cmd 클래스는 줄 지향 명령 인터프리터를 작성하기 위한 간단한 프레임워크를 제공합니다. 이것들은 종종 테스트 하네스(test harnesses), 관리 도구 및 나중에 더 복잡한 인터페이스로 포장될 프로토타입에 유용합니다.

class cmd.Cmd(completekey='tab', stdin=None, stdout=None)

Cmd 인스턴스나 서브 클래스 인스턴스는 줄 지향 인터프리터 프레임워크입니다. Cmd 자체를 인스턴스로 만들 이유는 없습니다; 그보다는, Cmd의 메서드를 상속하고 액션 메서드를 캡슐화하기 위해 여러분 스스로 정의한 인터프리터 클래스의 슈퍼 클래스로 유용합니다.

선택적 인자 completekey는 완성 키(completion key)의 readline 이름입니다; 기본값은 Tab입니다. completekey가 None이 아니고 readline을 사용할 수 있으면, 명령 완성이 자동으로 수행됩니다.

선택적 인자 stdin과 stdout은 Cmd 인스턴스나 서브 클래스 인스턴스가 입출력에 사용할 입력과 출력 파일 객체를 지정합니다. 지정하지 않으면, 기본적으로 sys.stdin과 sys.stdout이 됩니다.

지정된 stdin을 사용하려면, 인스턴스의 use_rawinput 어트리뷰트를 False로 설정해야 합니다, 그렇지 않으면 stdin이 무시됩니다.

Cmd 객체

Cmd 인스턴스에는 다음과 같은 메서드가 있습니다:

Cmd.cmdloop(intro=None)

반복해서 프롬프트를 제시하고, 입력을 받아들이고, 수신된 입력에서 초기 접두사를 구문 분석하고, 줄의 나머지 부분을 인자로 전달해서 액션 메서드를 호출합니다.

선택적 인자는 첫 번째 프롬프트 전에 제시할 배너나 소개 문자열입니다 (이것은 intro 클래스 어트리뷰트를 재정의합니다).

readline 모듈이 로드되면, 입력은 자동으로 bash와 유사한 히스토리 목록 편집을 상속합니다 (예를 들어, Control-P는 직전 명령으로 돌아가고(scroll back), Control-N은 다음 명령으로 이동하고(forward), Control-F는 커서를 비파괴적으로 오른쪽으로 이동하고, Control-B는 커서를 비파괴적으로 왼쪽으로 이동하고, 등등).

입력의 파일 끝(end-of-file)은 문자열 'EOF'로 전달됩니다.

인터프리터 인스턴스는 메서드 do_foo()가 있을 때만 명령 이름 foo를 인식합니다. 특수한 경우로, 문자 '?'로 시작하는 줄은 메서드 do_help()를 호출합니다. 또 다른 특수한 경우로, 문자 '!'로 시작하는 줄은 메서드 do_shell()을 (해당 메서드가 정의되었다면) 호출합니다.

이 메서드는 postcmd() 메서드가 참값을 반환할 때 반환합니다. postcmd()에 대한 stop 인자는 명령의 해당 do_*() 메서드에서 반환되는 값입니다.

완성(completion)이 활성화되면, 명령 완성이 자동으로 수행되고, 명령 인자의 완성은 인자 text, line, begidx 및 endidx로 complete_foo()를 호출하여 수행됩니다. text는 일치시키려는 문자열 접두사입니다: 반환된 모든 일치는 이 문자열로 시작해야 합니다. line은 선행 공백이 제거된 현재 입력 줄이며, begidx와 endidx는 접두사 텍스트의 시작과 끝 인덱스로, 인자의 위치에 따라 다른 완성을 제공하는 데 사용될 수 있습니다.

Cmd의 모든 서브 클래스는 미리 정의된 do_help()를 상속합니다. 인자 'bar'로 호출되면, 이 메서드는 해당 메서드 help_bar()를 호출하고, 존재하지 않으면 do_bar()의 독스트링이 있다면 인쇄합니다. 인자가 없으면, do_help()는 사용 가능한 모든 도움말 주제(즉, 해당 help_*() 메서드가 있거나 독스트링이 있는 모든 명령)을 나열하고, 설명이 없는 명령도 나열합니다.

Cmd.onecmd(str)

프롬프트에 대한 응답으로 입력된 것처럼 인자를 해석합니다. 재정의될 수도 있지만, 일반적으로 그럴 필요가 없어야 합니다; 유용한 실행 훅에 대해서는 precmd()와 postcmd() 메서드를 참조하십시오. 반환 값은 인터프리터의 명령 해석이 중지되어야 하는지를 나타내는 플래그입니다. 명령 str을 위한 do_*() 메서드가 있으면, 해당 메서드의 반환 값이 반환되고, 그렇지 않으면 default() 메서드의 반환 값이 반환됩니다.

Cmd.emptyline()

프롬프트에 응답하여 빈 줄을 입력할 때 호출되는 메서드. 이 메서드를 재정의하지 않으면, 입력된 마지막 비어 있지 않은 명령을 반복합니다.

Cmd.default(line)

명령 접두사가 인식되지 않을 때 입력 줄로 호출되는 메서드. 이 메서드를 재정의하지 않으면, 에러 메시지를 인쇄하고 반환합니다.

Cmd.completedefault(text, line, begidx, endidx)

명령 별 complete_*() 메서드가 없을 때 입력 줄을 완성하기 위해 호출되는 메서드. 기본적으로, 빈 리스트를 반환합니다.

Cmd.precmd(line)

명령 줄 line을 해석하기 직전에, 하지만 입력 프롬프트가 생성되고 제시된 후에 실행되는 훅 메서드. 이 메서드는 Cmd에서는 스텁(stub)입니다; 서브 클래스에 의해 재정의되기 위해 존재합니다. 반환 값은 onecmd() 메서드에 의해 실행될 명령으로 사용됩니다; precmd() 구현은 명령을 다시 쓰거나 단순히 line을 변경하지 않고 반환 할 수 있습니다.

Cmd.postcmd(stop, line)

명령 호출이 완료된 직후에 실행되는 훅 메서드. 이 메서는 Cmd에서는 스텁(stub)입니다; 서브 클래스에 의해 재정의되기 위해 존재합니다. line은 실행된 명령 줄이고, stop은 postcmd()를 호출한 후 실행이 종료될지를 나타내는 플래그입니다; 이것은 onecmd() 메서드의 반환 값입니다. 이 메서드의 반환 값은 stop에 해당하는 내부 플래그의 새 값으로 사용됩니다; 거짓을 반환하면 해석이 계속됩니다.

Cmd.preloop()

cmdloop()가 호출될 때 한 번 실행되는 훅 메서드. 이 메서드는 Cmd에서는 스텁(stub)입니다; 서브 클래스에 의해 재정의되기 위해 존재합니다.

Cmd.postloop()

cmdloop()가 반환하려고 할 때 한 번 실행되는 훅 메서드. 이 메서드는 Cmd에서는 스텁(stub)입니다; 서브 클래스에 의해 재정의되기 위해 존재합니다.

Cmd 서브 클래스의 인스턴스에는 몇 가지 공용 인스턴스 변수가 있습니다:

Cmd.prompt

입력을 요청하는 프롬프트.

Cmd.identchars

명령 접두사에 허용되는 문자들의 문자열.

Cmd.lastcmd

비어 있지 않은 마지막 명령 접두사.

Cmd.cmdqueue

계류 중인 입력 줄의 리스트. cmdqueue 리스트는 새로운 입력이 필요할 때 cmdloop()에서 점검됩니다; 비어 있지 않으면, 프롬프트에서 입력한 것처럼 해당 요소가 순서대로 처리됩니다.

Cmd.intro

소개나 배너로 제시할 문자열. cmdloop() 메서드에 인자를 제공하여 재정의할 수 있습니다.

Cmd.doc_header

도움말 출력에 설명된 명령 섹션이 있을 때 제시할 헤더입니다.

Cmd.misc_header

도움말 출력에 기타 도움말 주제에 대한 섹션이 있을 때 제시할 헤더 (즉, 해당 do_*() 메서드가 없는 help_*() 메서드가 있을 때).

Cmd.undoc_header

도움말 출력에 설명되지 않은 명령에 대한 섹션이 있을 때 제시할 헤더 (즉, 해당 help_*() 메서드가 없는 do_*() 메서드가 있을 때).

Cmd.ruler

도움말 메시지 헤더 아래에 구분선을 그리는 데 사용되는 문자입니다. 비어 있으면, 눈금자 선이 그려지지 않습니다. 기본값은 '='입니다.

Cmd.use_rawinput

기본값이 참인 플래그. 참이면, cmdloop()는 input()을 사용하여 프롬프트를 표시하고 다음 명령을 읽습니다; 거짓이면, sys.stdout.write()와 sys.stdin.readline()이 사용됩니다. (이는 지원하는 시스템에서 readline를 임포트 함으로써, 인터프리터가 Emacs와 유사한 줄 편집과 명령 히스토리 키 입력을 자동으로 지원한다는 의미입니다.)

Cmd 예

cmd 모듈은 주로 사용자가 대화식으로 프로그램을 사용할 수 있도록 하는 사용자 정의 셸을 만드는 데 유용합니다.

이 섹션에서는 turtle 모듈의 몇 가지 명령을 중심으로 셸을 작성하는 방법에 대한 간단한 예를 제공합니다.

forward()와 같은 기본 turtle 명령은 do_forward()라는 메서드로 Cmd 서브 클래스에 추가됩니다. 인자는 숫자로 변환되어 turtle 모듈로 전달됩니다. 독스트링은 셸에서 제공하는 도움말 유틸리티에서 사용됩니다.

이 예제에는 precmd() 메서드로 구현된 기초적인 녹화와 재생 기능도 포함되는데, 이 메서드는 입력을 소문자로 변환하고 명령을 파일에 쓰는 역할을 합니다. do_playback() 메서드는 파일을 읽고 즉시 재생하기 위해 녹화된 명령을 cmdqueue에 추가합니다:

import cmd, sys
from turtle import *

class TurtleShell(cmd.Cmd):
    intro = 'Welcome to the turtle shell.   Type help or ? to list commands.\n'
    prompt = '(turtle) '
    file = None

    # ----- basic turtle commands -----
    def do_forward(self, arg):
        'Move the turtle forward by the specified distance:  FORWARD 10'
        forward(*parse(arg))
    def do_right(self, arg):
        'Turn turtle right by given number of degrees:  RIGHT 20'
        right(*parse(arg))
    def do_left(self, arg):
        'Turn turtle left by given number of degrees:  LEFT 90'
        left(*parse(arg))
    def do_goto(self, arg):
        'Move turtle to an absolute position with changing orientation.  GOTO 100 200'
        goto(*parse(arg))
    def do_home(self, arg):
        'Return turtle to the home position:  HOME'
        home()
    def do_circle(self, arg):
        'Draw circle with given radius an options extent and steps:  CIRCLE 50'
        circle(*parse(arg))
    def do_position(self, arg):
        'Print the current turtle position:  POSITION'
        print('Current position is %d %d\n' % position())
    def do_heading(self, arg):
        'Print the current turtle heading in degrees:  HEADING'
        print('Current heading is %d\n' % (heading(),))
    def do_color(self, arg):
        'Set the color:  COLOR BLUE'
        color(arg.lower())
    def do_undo(self, arg):
        'Undo (repeatedly) the last turtle action(s):  UNDO'
    def do_reset(self, arg):
        'Clear the screen and return turtle to center:  RESET'
        reset()
    def do_bye(self, arg):
        'Stop recording, close the turtle window, and exit:  BYE'
        print('Thank you for using Turtle')
        self.close()
        bye()
        return True

    # ----- record and playback -----
    def do_record(self, arg):
        'Save future commands to filename:  RECORD rose.cmd'
        self.file = open(arg, 'w')
    def do_playback(self, arg):
        'Playback commands from a file:  PLAYBACK rose.cmd'
        self.close()
        with open(arg) as f:
            self.cmdqueue.extend(f.read().splitlines())
    def precmd(self, line):
        line = line.lower()
        if self.file and 'playback' not in line:
            print(line, file=self.file)
        return line
    def close(self):
        if self.file:
            self.file.close()
            self.file = None

def parse(arg):
    'Convert a series of zero or more numbers to an argument tuple'
    return tuple(map(int, arg.split()))

if __name__ == '__main__':
    TurtleShell().cmdloop()

다음은 도움말 기능과, 명령을 반복하기 위해 빈 줄을 사용하는 방법과, 간단한 녹화와 재생기능을 보여주기 위해 turtle 셀을 사용한 예제 세션입니다:

Welcome to the turtle shell.   Type help or ? to list commands.

(turtle) ?

Documented commands (type help <topic>):
========================================
bye     color    goto     home  playback  record  right
circle  forward  heading  left  position  reset   undo

(turtle) help forward
Move the turtle forward by the specified distance:  FORWARD 10
(turtle) record spiral.cmd
(turtle) position
Current position is 0 0

(turtle) heading
Current heading is 0

(turtle) reset
(turtle) circle 20
(turtle) right 30
(turtle) circle 40
(turtle) right 30
(turtle) circle 60
(turtle) right 30
(turtle) circle 80
(turtle) right 30
(turtle) circle 100
(turtle) right 30
(turtle) circle 120
(turtle) right 30
(turtle) circle 120
(turtle) heading
Current heading is 180

(turtle) forward 100
(turtle)
(turtle) right 90
(turtle) forward 100
(turtle)
(turtle) right 90
(turtle) forward 400
(turtle) right 90
(turtle) forward 500
(turtle) right 90
(turtle) forward 400
(turtle) right 90
(turtle) forward 300
(turtle) playback spiral.cmd
Current position is 0 0

Current heading is 0

Current heading is 180

(turtle) bye
Thank you for using Turtle

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

프로그램 프레임워크 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

프로그램 프레임워크 »

|

shlex — Simple lexical analysis

Source code: Lib/shlex.py [https://github.com/python/cpython/tree/3.7/Lib/shlex.py]

The shlex class makes it easy to write lexical analyzers for simple syntaxes resembling that of the Unix shell. This will often be useful for writing minilanguages, (for example, in run control files for Python applications) or for parsing quoted strings.

The shlex module defines the following functions:

shlex.split(s, comments=False, posix=True)

Split the string s using shell-like syntax. If comments is False (the default), the parsing of comments in the given string will be disabled (setting the commenters attribute of the shlex instance to the empty string). This function operates in POSIX mode by default, but uses non-POSIX mode if the posix argument is false.

참고

Since the split() function instantiates a shlex instance, passing None for s will read the string to split from standard input.

shlex.quote(s)

Return a shell-escaped version of the string s. The returned value is a string that can safely be used as one token in a shell command line, for cases where you cannot use a list.

This idiom would be unsafe:

>>> filename = 'somefile; rm -rf ~'
>>> command = 'ls -l {}'.format(filename)
>>> print(command)  # executed by a shell: boom!
ls -l somefile; rm -rf ~

quote() lets you plug the security hole:

>>> from shlex import quote
>>> command = 'ls -l {}'.format(quote(filename))
>>> print(command)
ls -l 'somefile; rm -rf ~'
>>> remote_command = 'ssh home {}'.format(quote(command))
>>> print(remote_command)
ssh home 'ls -l '"'"'somefile; rm -rf ~'"'"''

The quoting is compatible with UNIX shells and with split():

>>> from shlex import split
>>> remote_command = split(remote_command)
>>> remote_command
['ssh', 'home', "ls -l 'somefile; rm -rf ~'"]
>>> command = split(remote_command[-1])
>>> command
['ls', '-l', 'somefile; rm -rf ~']

버전 3.3에 추가.

The shlex module defines the following class:

class shlex.shlex(instream=None, infile=None, posix=False, punctuation_chars=False)

A shlex instance or subclass instance is a lexical analyzer object. The initialization argument, if present, specifies where to read characters from. It must be a file-/stream-like object with read() and readline() methods, or a string. If no argument is given, input will be taken from sys.stdin. The second optional argument is a filename string, which sets the initial value of the infile attribute. If the instream argument is omitted or equal to sys.stdin, this second argument defaults to “stdin”. The posix argument defines the operational mode: when posix is not true (default), the shlex instance will operate in compatibility mode. When operating in POSIX mode, shlex will try to be as close as possible to the POSIX shell parsing rules. The punctuation_chars argument provides a way to make the behaviour even closer to how real shells parse. This can take a number of values: the default value, False, preserves the behaviour seen under Python 3.5 and earlier. If set to True, then parsing of the characters ();<>|& is changed: any run of these characters (considered punctuation characters) is returned as a single token. If set to a non-empty string of characters, those characters will be used as the punctuation characters. Any characters in the wordchars attribute that appear in punctuation_chars will be removed from wordchars. See Improved Compatibility with Shells for more information. punctuation_chars can be set only upon shlex instance creation and can’t be modified later.

버전 3.6에서 변경: The punctuation_chars parameter was added.

더 보기

Module configparser

Parser for configuration files similar to the Windows .ini files.

shlex Objects

A shlex instance has the following methods:

shlex.get_token()

Return a token. If tokens have been stacked using push_token(), pop a token off the stack. Otherwise, read one from the input stream. If reading encounters an immediate end-of-file, eof is returned (the empty string ('') in non-POSIX mode, and None in POSIX mode).

shlex.push_token(str)

Push the argument onto the token stack.

shlex.read_token()

Read a raw token. Ignore the pushback stack, and do not interpret source requests. (This is not ordinarily a useful entry point, and is documented here only for the sake of completeness.)

shlex.sourcehook(filename)

When shlex detects a source request (see source below) this method is given the following token as argument, and expected to return a tuple consisting of a filename and an open file-like object.

Normally, this method first strips any quotes off the argument. If the result is an absolute pathname, or there was no previous source request in effect, or the previous source was a stream (such as sys.stdin), the result is left alone. Otherwise, if the result is a relative pathname, the directory part of the name of the file immediately before it on the source inclusion stack is prepended (this behavior is like the way the C preprocessor handles #include "file.h").

The result of the manipulations is treated as a filename, and returned as the first component of the tuple, with open() called on it to yield the second component. (Note: this is the reverse of the order of arguments in instance initialization!)

This hook is exposed so that you can use it to implement directory search paths, addition of file extensions, and other namespace hacks. There is no corresponding ‘close’ hook, but a shlex instance will call the close() method of the sourced input stream when it returns EOF.

For more explicit control of source stacking, use the push_source() and pop_source() methods.

shlex.push_source(newstream, newfile=None)

Push an input source stream onto the input stack. If the filename argument is specified it will later be available for use in error messages. This is the same method used internally by the sourcehook() method.

shlex.pop_source()

Pop the last-pushed input source from the input stack. This is the same method used internally when the lexer reaches EOF on a stacked input stream.

shlex.error_leader(infile=None, lineno=None)

This method generates an error message leader in the format of a Unix C compiler error label; the format is '"%s", line %d: ', where the %s is replaced with the name of the current source file and the %d with the current input line number (the optional arguments can be used to override these).

This convenience is provided to encourage shlex users to generate error messages in the standard, parseable format understood by Emacs and other Unix tools.

Instances of shlex subclasses have some public instance variables which either control lexical analysis or can be used for debugging:

shlex.commenters

The string of characters that are recognized as comment beginners. All characters from the comment beginner to end of line are ignored. Includes just '#' by default.

shlex.wordchars

The string of characters that will accumulate into multi-character tokens. By default, includes all ASCII alphanumerics and underscore. In POSIX mode, the accented characters in the Latin-1 set are also included. If punctuation_chars is not empty, the characters ~-./*?=, which can appear in filename specifications and command line parameters, will also be included in this attribute, and any characters which appear in punctuation_chars will be removed from wordchars if they are present there.

shlex.whitespace

Characters that will be considered whitespace and skipped. Whitespace bounds tokens. By default, includes space, tab, linefeed and carriage-return.

shlex.escape

Characters that will be considered as escape. This will be only used in POSIX mode, and includes just '\' by default.

shlex.quotes

Characters that will be considered string quotes. The token accumulates until the same quote is encountered again (thus, different quote types protect each other as in the shell.) By default, includes ASCII single and double quotes.

shlex.escapedquotes

Characters in quotes that will interpret escape characters defined in escape. This is only used in POSIX mode, and includes just '"' by default.

shlex.whitespace_split

If True, tokens will only be split in whitespaces. This is useful, for example, for parsing command lines with shlex, getting tokens in a similar way to shell arguments. If this attribute is True, punctuation_chars will have no effect, and splitting will happen only on whitespaces. When using punctuation_chars, which is intended to provide parsing closer to that implemented by shells, it is advisable to leave whitespace_split as False (the default value).

shlex.infile

The name of the current input file, as initially set at class instantiation time or stacked by later source requests. It may be useful to examine this when constructing error messages.

shlex.instream

The input stream from which this shlex instance is reading characters.

shlex.source

This attribute is None by default. If you assign a string to it, that string will be recognized as a lexical-level inclusion request similar to the source keyword in various shells. That is, the immediately following token will be opened as a filename and input will be taken from that stream until EOF, at which point the close() method of that stream will be called and the input source will again become the original input stream. Source requests may be stacked any number of levels deep.

shlex.debug

If this attribute is numeric and 1 or more, a shlex instance will print verbose progress output on its behavior. If you need to use this, you can read the module source code to learn the details.

shlex.lineno

Source line number (count of newlines seen so far plus one).

shlex.token

The token buffer. It may be useful to examine this when catching exceptions.

shlex.eof

Token used to determine end of file. This will be set to the empty string (''), in non-POSIX mode, and to None in POSIX mode.

shlex.punctuation_chars

A read-only property. Characters that will be considered punctuation. Runs of punctuation characters will be returned as a single token. However, note that no semantic validity checking will be performed: for example, ‘>>>’ could be returned as a token, even though it may not be recognised as such by shells.

버전 3.6에 추가.

Parsing Rules

When operating in non-POSIX mode, shlex will try to obey to the following rules.

Quote characters are not recognized within words (Do"Not"Separate is parsed as the single word Do"Not"Separate);

Escape characters are not recognized;

Enclosing characters in quotes preserve the literal value of all characters within the quotes;

Closing quotes separate words ("Do"Separate is parsed as "Do" and Separate);

If whitespace_split is False, any character not declared to be a word character, whitespace, or a quote will be returned as a single-character token. If it is True, shlex will only split words in whitespaces;

EOF is signaled with an empty string ('');

It’s not possible to parse empty strings, even if quoted.

When operating in POSIX mode, shlex will try to obey to the following parsing rules.

Quotes are stripped out, and do not separate words ("Do"Not"Separate" is parsed as the single word DoNotSeparate);

Non-quoted escape characters (e.g. '\') preserve the literal value of the next character that follows;

Enclosing characters in quotes which are not part of escapedquotes (e.g. "'") preserve the literal value of all characters within the quotes;

Enclosing characters in quotes which are part of escapedquotes (e.g. '"') preserves the literal value of all characters within the quotes, with the exception of the characters mentioned in escape. The escape characters retain its special meaning only when followed by the quote in use, or the escape character itself. Otherwise the escape character will be considered a normal character.

EOF is signaled with a None value;

Quoted empty strings ('') are allowed.

Improved Compatibility with Shells

버전 3.6에 추가.

The shlex class provides compatibility with the parsing performed by common Unix shells like bash, dash, and sh. To take advantage of this compatibility, specify the punctuation_chars argument in the constructor. This defaults to False, which preserves pre-3.6 behaviour. However, if it is set to True, then parsing of the characters ();<>|& is changed: any run of these characters is returned as a single token. While this is short of a full parser for shells (which would be out of scope for the standard library, given the multiplicity of shells out there), it does allow you to perform processing of command lines more easily than you could otherwise. To illustrate, you can see the difference in the following snippet:

 >>> import shlex
 >>> text = "a && b; c && d || e; f >'abc'; (def \"ghi\")"
 >>> list(shlex.shlex(text))
 ['a', '&', '&', 'b', ';', 'c', '&', '&', 'd', '|', '|', 'e', ';', 'f', '>',
 "'abc'", ';', '(', 'def', '"ghi"', ')']
 >>> list(shlex.shlex(text, punctuation_chars=True))
 ['a', '&&', 'b', ';', 'c', '&&', 'd', '||', 'e', ';', 'f', '>', "'abc'",
 ';', '(', 'def', '"ghi"', ')']

Of course, tokens will be returned which are not valid for shells, and you’ll need to implement your own error checks on the returned tokens.

Instead of passing True as the value for the punctuation_chars parameter, you can pass a string with specific characters, which will be used to determine which characters constitute punctuation. For example:

>>> import shlex
>>> s = shlex.shlex("a && b || c", punctuation_chars="|")
>>> list(s)
['a', '&', '&', 'b', '||', 'c']

참고

When punctuation_chars is specified, the wordchars attribute is augmented with the characters ~-./*?=. That is because these characters can appear in file names (including wildcards) and command-line arguments (e.g. --color=auto). Hence:

>>> import shlex
>>> s = shlex.shlex('~/a && b-c --color=auto || d *.py?',
...                 punctuation_chars=True)
>>> list(s)
['~/a', '&&', 'b-c', '--color=auto', '||', 'd', '*.py?']

For best effect, punctuation_chars should be set in conjunction with posix=True. (Note that posix=False is the default for shlex.)

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

프로그램 프레임워크 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

|

Tk를 사용한 그래픽 사용자 인터페이스

Tk/Tcl은 오랫동안 파이썬의 중요한 부분이었습니다. 견고하고 플랫폼 독립적인 윈도우 도구상자(파이썬 프로그래머는 tkinter 패키지를 통해 사용할 수 있습니다)와 그 확장(tkinter.tix와 tkinter.ttk 모듈)을 제공합니다.

tkinter 패키지는 Tcl/Tk 위에 올라가는 얇은 객체 지향 계층입니다. tkinter를 사용하기 위해 Tcl 코드를 작성할 필요는 없지만, Tk 문서와 때때로 Tcl 문서를 참고해야 합니다. tkinter는 Tk 위젯을 파이썬 클래스로 구현하는 래퍼 집합입니다. 또한, 내부 모듈 _tkinter는 파이썬과 Tcl이 상호 작용할 수 있게 해주는 스레드 안전한 메커니즘을 제공합니다.

tkinter의 가장 큰 장점은 빠르고, 일반적으로 파이썬과 함께 제공된다는 것입니다. 표준 설명서가 약하긴 하지만 레퍼런스, 자습서, 서적 및 기타 자료와 같은 훌륭한 자료를 구할 수 있습니다. tkinter는 낡은 모양과 느낌으로도 유명합니다만, Tk 8.5에서 크게 개선되었습니다. 그렇지만, 여러분이 관심을 기울일 만한 다른 GUI 라이브러리가 많이 있습니다. 대안에 관한 자세한 내용은 기타 그래픽 사용자 인터페이스 패키지 섹션을 참조하십시오.

tkinter — Tcl/Tk 파이썬 인터페이스

Tkinter 모듈

Tkinter 구명조끼

이 절을 사용하는 방법

간단한 Hello World 프로그램

Tcl/Tk (아주 빨리) 훑어보기

기본 Tk를 Tkinter로 매핑하기

Tk와 Tkinter의 관계

간편한 레퍼런스

옵션 설정

패커

패커 옵션

위젯 변수 결합하기

창 관리자

Tk 옵션 데이터형

바인딩과 이벤트

index 매개 변수

이미지

파일 처리기

tkinter.ttk — Tk themed widgets

Using Ttk

Ttk Widgets

Widget

Standard Options

Scrollable Widget Options

Label Options

Compatibility Options

Widget States

ttk.Widget

Combobox

Options

Virtual events

ttk.Combobox

Spinbox

Options

Virtual events

ttk.Spinbox

Notebook

Options

Tab Options

Tab Identifiers

Virtual Events

ttk.Notebook

Progressbar

Options

ttk.Progressbar

Separator

Options

Sizegrip

Platform-specific notes

Bugs

Treeview

Options

Item Options

Tag Options

Column Identifiers

Virtual Events

ttk.Treeview

Ttk Styling

Layouts

tkinter.tix — Extension widgets for Tk

Using Tix

Tix Widgets

Basic Widgets

File Selectors

Hierarchical ListBox

Tabular ListBox

Manager Widgets

Image Types

Miscellaneous Widgets

Form Geometry Manager

Tix Commands

tkinter.scrolledtext — 스크롤 되는 Text 위젯

IDLE

Menus

File menu (Shell and Editor)

Edit menu (Shell and Editor)

Format menu (Editor window only)

Run menu (Editor window only)

Shell menu (Shell window only)

Debug menu (Shell window only)

Options menu (Shell and Editor)

Window menu (Shell and Editor)

Help menu (Shell and Editor)

Context Menus

Editing and navigation

Editor windows

Key bindings

Automatic indentation

Completions

Calltips

Code Context

Python Shell window

Text colors

Startup and code execution

Command line usage

Startup failure

Running user code

User output in Shell

Developing tkinter applications

Running without a subprocess

Help and preferences

Help sources

Setting preferences

IDLE on macOS

Extensions

기타 그래픽 사용자 인터페이스 패키지

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

Tk를 사용한 그래픽 사용자 인터페이스 »

|

tkinter — Tcl/Tk 파이썬 인터페이스

소스 코드: Lib/tkinter/__init__.py [https://github.com/python/cpython/tree/3.7/Lib/tkinter/__init__.py]

tkinter 패키지(“Tk 인터페이스”)는 Tk GUI 툴킷에 대한 표준 파이썬 인터페이스입니다. Tk와 tkinter는 대부분의 유닉스 플랫폼과 윈도우 시스템에서 사용할 수 있습니다. (Tk 자체는 파이썬 일부가 아닙니다; ActiveState에서 유지 보수됩니다.)

명령 줄에서 python -m tkinter를 실행하면 간단한 Tk 인터페이스를 보여주는 창을 열어, tkinter가 시스템에 제대로 설치되었는지 알 수 있도록 하고, 설치된 Tcl/Tk 버전을 보여주기 때문에, 그 버전에 해당하는 Tcl/Tk 설명서를 읽을 수 있습니다.

더 보기

Tkinter 설명서:

파이썬 Tkinter 자원 [https://wiki.python.org/moin/TkInter]

파이썬 Tkinter 주제 지침서는 파이썬에서 Tk를 사용하는 것에 관한 많은 정보와 Tk에 관한 다른 정보 소스에 대한 링크를 제공합니다.

TKDocs [http://www.tkdocs.com/]

폭넓은 자습서와 일부 위젯(widget)에 대한 더 친절한 위젯 페이지.

Tkinter 8.5 reference: a GUI for Python [https://web.archive.org/web/20190524140835/https://infohost.nmt.edu/tcc/help/pubs/tkinter/web/index.html]

온라인 레퍼런스 자료.

effbot의 Tkinter 설명서 [http://effbot.org/tkinterbook/]

effbot.org에서 지원하는 tkinter의 온라인 레퍼런스.

Programming Python [http://learning-python.com/about-pp4e.html]

Mark Lutz의 책, 탁월하게 Tkinter를 다루고 있습니다.

Modern Tkinter for Busy Python Developers [https://www.amazon.com/Modern-Tkinter-Python-Developers-ebook/dp/B0071QDNLO/]

Book by Mark Roseman about building attractive and modern graphical user interfaces with Python and Tkinter.

Python and Tkinter Programming [https://www.manning.com/books/python-and-tkinter-programming]

John Grayson의 책(ISBN 1-884777-81-3).

Tcl/Tk 설명서:

Tk commands [https://www.tcl.tk/man/tcl8.6/TkCmd/contents.htm]

대부분의 명령은 tkinter나 tkinter.ttk 클래스로 사용할 수 있습니다. ‘8.6’을 여러분의 Tcl/Tk 설치 버전으로 바꾸십시오.

Tcl/Tk 최근 매뉴얼 페이지 [https://www.tcl.tk/doc/]

www.tcl.tk에 있는 최근 Tcl/Tk 매뉴얼.

ActiveState Tcl 홈페이지 [https://tcl.tk]

Tk/Tcl 개발은 주로 ActiveState에서 진행됩니다.

Tcl and the Tk Toolkit [https://www.amazon.com/exec/obidos/ASIN/020163337X]

Tcl의 발명가인 John Ousterhout의 책.

Practical Programming in Tcl and Tk [http://www.beedub.com/book/]

Brent Welch의 백과사전식 책.

Tkinter 모듈

대부분은, tkinter 만 있으면 충분하지만, 많은 추가 모듈도 사용할 수 있습니다. Tk 인터페이스는 _tkinter라는 바이너리 모듈에 있습니다. 이 모듈은 Tk에 대한 저수준 인터페이스를 포함하고 있고, 응용 프로그램 프로그래머가 직접 사용해서는 안 됩니다. 일반적으로 공유 라이브러리(또는 DLL)이지만, 때에 따라 파이썬 인터프리터에 정적으로 링크될 수도 있습니다.

Tk 인터페이스 모듈 외에도, tkinter에는 파이썬 모듈이 많이 포함되어 있습니다. tkinter.constants는 가장 중요한 모듈 중 하나입니다. tkinter를 임포트 하면 tkinter.constants를 자동으로 임포트 하므로, 일반적으로 Tkinter를 사용하려면 간단한 import 문만 필요합니다:

import tkinter

또는, 더 자주:

from tkinter import *

class tkinter.Tk(screenName=None, baseName=None, className='Tk', useTk=1)

Tk 클래스는 인자 없이 인스턴스화됩니다. 이것은 Tk의 최상위 위젯을 만드는데, 일반적으로 응용 프로그램의 메인 창입니다. 인스턴스마다 고유한 Tcl 인터프리터가 연결됩니다.

tkinter.Tcl(screenName=None, baseName=None, className='Tk', useTk=0)

Tcl() 함수는 Tk 서브 시스템을 초기화하지 않는다는 것을 제외하고는, Tk 클래스에 의해 만들어지는 것과 비슷한 객체를 만드는 팩토리 함수입니다. 불필요한 최상위 창을 만들고 싶지 않거나 만들 수 없는 (가령 X 서버가 없는 유닉스/리눅스 시스템) 환경에서 Tcl 인터프리터를 구동할 때 가장 유용합니다. Tcl() 객체에 의해 만들어진 객체는 loadtk() 메서드를 호출하여 만들어지는 최상위 창(과 초기화된 Tk 서브 시스템)을 가질 수 있습니다.

Tk 지원을 제공하는 다른 모듈은 다음과 같습니다:

tkinter.scrolledtext

세로 스크롤 막대가 내장된 Text 위젯.

tkinter.colorchooser

사용자가 색상을 선택할 수 있게 하는 대화 상자.

tkinter.commondialog

여기에 나열된 다른 모듈에 정의된 대화 상자의 베이스 기본 클래스.

tkinter.filedialog

사용자가 열거나 저장할 파일을 지정할 수 있도록 하는 일반 대화 상자입니다.

tkinter.font

글꼴과 관련된 작업에 도움이 되는 유틸리티.

tkinter.messagebox

표준 Tk 대화 상자에 액세스합니다.

tkinter.simpledialog

기본 대화 상자와 편리 함수.

tkinter.dnd

tkinter를 위한 드래그 앤드 드롭 지원. 이것은 실험적이며 Tk DND로 대체 될 때 폐지됩니다.

turtle

Tk 창에서의 터틀(turtle) 그래픽.

Tkinter 구명조끼

이 절은 Tk나 Tkinter에 대한 철저한 자습서가 되고자 하는 것은 아닙니다. 오히려, 시스템에 관한 몇 가지 입문 오리엔테이션을 제공하는 임시방편입니다.

크레딧:

Tk는 John Ousterhout이 버클리에 있을 때 쓴 것입니다.

Tkinter는 Steen Lumholt와 Guido van Rossum이 썼습니다.

이 구명조끼는 University of Virginia의 Matt Conway가 썼습니다.

HTML 렌더링은, 그리고 일부 자유로운 편집과 함께, Ken Manheimer가 FrameMaker 버전으로 제작했습니다.

Fredrik Lundh는 클래스 인터페이스 설명을 다듬고 수정하여 Tk 4.2에서 최신 버전으로 만들었습니다.

Mike Clarkson은 설명서를 LaTeX로 변환하고, 레퍼런스 설명서의 사용자 인터페이스 장을 엮었습니다.

이 절을 사용하는 방법

이 절은 두 부분으로 구성되어 있습니다: 첫 번째 (대략) 절반은 배경 자료를 다루고, 두 번째 절반은 따다 쓰기에 간편한 레퍼런스입니다.

“어쩌고를 어떻게 해야 합니까?”와 같은 형식의 질문에 대답하려 할 때, Tk에서 직접 “어쩌고” 하는 법을 알아내고, 이것을 다시 해당 tkinter 호출로 변환하는 것이 종종 최선입니다. 파이썬 프로그래머는 Tk 설명서를 보고 종종 올바른 파이썬 명령을 추측할 수 있습니다. 이것은 Tkinter를 사용하려면 Tk에 대해 조금은 알고 있어야 한다는 뜻입니다. 이 문서가 그 소임을 수행하기는 부족하므로, 우리가 할 수 있는 최선은 존재하는 최고의 설명서를 소개하는 것입니다. 여기 몇 가지 힌트가 있습니다:

저자는 Tk 매뉴얼 페이지의 복사본을 얻을 것을 강력히 제안합니다. 특히, manN 디렉터리의 매뉴얼 페이지가 가장 유용합니다. man3 매뉴얼 페이지는 Tk 라이브러리에 대한 C 인터페이스를 설명하므로 스크립트 작성자에게 특별히 도움이 되지는 않습니다.

Addison-Wesley는 초보자를 위한 Tcl과 Tk에 대한 훌륭한 소개인 John Ousterhout의 Tcl and the Tk Toolkit (ISBN 0-201-63337-X)이라는 책을 출간합니다. 이 책은 모든 것을 다루지는 않으며, 많은 세부 사항은 매뉴얼 페이지에 위임합니다.

tkinter/__init__.py는 대부분에게 최후의 수단이지만, 다른 모든 것에서 답을 찾을 수 없을 때 가야 할 좋은 곳일 수 있습니다.

간단한 Hello World 프로그램

import tkinter as tk

class Application(tk.Frame):
    def __init__(self, master=None):
        super().__init__(master)
        self.master = master
        self.pack()
        self.create_widgets()

    def create_widgets(self):
        self.hi_there = tk.Button(self)
        self.hi_there["text"] = "Hello World\n(click me)"
        self.hi_there["command"] = self.say_hi
        self.hi_there.pack(side="top")

        self.quit = tk.Button(self, text="QUIT", fg="red",
                              command=self.master.destroy)
        self.quit.pack(side="bottom")

    def say_hi(self):
        print("hi there, everyone!")

root = tk.Tk()
app = Application(master=root)
app.mainloop()

Tcl/Tk (아주 빨리) 훑어보기

클래스 계층 구조가 복잡해 보입니다만, 실제로는 응용 프로그램 프로그래머는 거의 항상 계층 구조의 바닥에 있는 클래스를 참조합니다.

노트:

이 클래스들은 하나의 이름 공간에서 특정 기능을 구성하기 위해 제공됩니다. 이들은 독립적으로 인스턴스화하려는 것이 아닙니다.

Tk 클래스는 응용 프로그램에서 한 번만 인스턴스화됩니다. 응용 프로그램 프로그래머는 명시적으로 인스턴스화 할 필요가 없으며, 다른 클래스 중 하나가 인스턴스화 될 때 시스템이 만듭니다.

Widget 클래스는 인스턴스화하는 용도가 아니며, “실제” 위젯을 만들기 위해 서브 클래싱하려는 것입니다 (C++에서, 이것은 ‘추상 클래스(abstract class)’라고 합니다).

이 레퍼런스 자료를 사용하기 위해, Tk의 짧은 구문을 읽는 방법과 Tk 명령의 여러 부분을 식별하는 방법을 알아야 할 때가 있을 것입니다. (아래에 나오는 것의 tkinter 등가물에 대해서는 기본 Tk를 Tkinter로 매핑하기 절을 참조하십시오.)

Tk 스크립트는 Tcl 프로그램입니다. 모든 Tcl 프로그램과 마찬가지로, Tk 스크립트는 스페이스로 구분된 토큰 목록일 뿐입니다. Tk 위젯은 단지 그것의 클래스(class), 그것을 구성하는 데 도움이 되는 옵션(options) 및 그것이 유용한 일을 하도록 하는 액션(actions)일 뿐입니다.

Tk에서 위젯을 만들려면, 명령은 항상 다음과 같은 형식입니다:

classCommand newPathname options

classCommand

어떤 종류의 위젯(버튼, 레이블, 메뉴…)을 만들지를 나타냅니다

newPathname

이 위젯의 새 이름입니다. Tk의 모든 이름은 고유해야 합니다. 이 기능을 강제하기 위해, Tk의 위젯은 파일 시스템의 파일과 마찬가지로, 경로명(pathnames)으로 이름이 지정됩니다. 최상위 수준 위젯, 루트(root), 는 .(마침표)로 표현하고, 자식들은 더 많은 마침표로 구분합니다. 예를 들어, .myApp.controlPanel.okButton은 위젯의 이름일 수 있습니다.

options

위젯의 모양과 때에 따라 그 동작을 구성합니다. 옵션은 플래그와 값의 목록 형태로 제공됩니다. 플래그는 유닉스 셸 명령 플래그처럼 ‘-‘가 앞에 오고, 값이 두 단어 이상이면 값을 따옴표로 묶습니다.

예를 들면:

button   .fred   -fg red -text "hi there"
   ^       ^     \______________________/
   |       |                |
 class    new            options
command  widget  (-opt val -opt val ...)

일단 만들어지면, 위젯에 대한 경로명이 새로운 명령이 됩니다. 이 새로운 위젯 명령(widget command)은 액션(action)을 수행할 새 위젯을 얻는 데 필요한 프로그래머의 손잡이입니다. C에서, 이것을 someAction(fred, someOptions)로 표현하고, C++에서는, fred.someAction(someOptions)으로 표현하며, Tk에서는, 다음과 같이 표현합니다:

.fred someAction someOptions

객체 이름 .fred가 점으로 시작함에 유의하십시오.

예상대로, someAction의 유효한 값은 위젯의 클래스에 따라 다릅니다: .fred disable은 fred가 버튼이면 작동하지만, fred가 레이블이면 작동하지 않습니다 (레이블의 비활성화는 Tk에서 지원되지 않습니다).

someOptions의 합법적인 값은 액션에 따라 다릅니다. disable과 같은 일부 액션에는 인자가 필요하지 않으며, 텍스트 입력 상자의 delete 명령과 같은 다른 액션에는 삭제할 텍스트 범위를 지정하는 인자가 필요합니다.

기본 Tk를 Tkinter로 매핑하기

Tk의 클래스 명령은 Tkinter의 클래스 생성자에 대응합니다.

button .fred                =====>  fred = Button()

객체의 마스터(master)는 생성 시 부여된 새로운 이름에 함축되어 있습니다. Tkinter에서, 마스터는 명시적으로 지정됩니다.

button .panel.fred          =====>  fred = Button(panel)

Tk의 구성 옵션은 뒤에 값이 오는 하이픈이 붙은 태그의 목록입니다. Tkinter에서 옵션은 인스턴스 생성자에서 키워드 인자로, 구성(configure) 호출에서는 키워드 인자로, 설정된 인스턴스에서는 딕셔너리 스타일의 인스턴스 인덱스로 지정됩니다. 옵션 설정에 대해서는 옵션 설정 절을 참조하십시오.

button .fred -fg red        =====>  fred = Button(panel, fg="red")
.fred configure -fg red     =====>  fred["fg"] = red
                            OR ==>  fred.config(fg="red")

Tk에서, 위젯에 대한 작업을 수행하려면, 위젯 이름을 명령으로 사용하고, 그 뒤에 액션 이름이 옵니다, 인자(옵션)가 붙는 것도 가능합니다. Tkinter에서는, 위젯의 액션을 호출하기 위해 클래스 인스턴스의 메서드를 호출합니다. 주어진 위젯이 수행할 수 있는 액션(메서드)은 tkinter/__init__.py에 나열됩니다.

.fred invoke                =====>  fred.invoke()

패커(packer)(지오메트리 관리자, geometry manager)에게 위젯을 전달하려면, pack을 선택적 인자로 호출합니다. Tkinter에서, Pack 클래스는 이 모든 기능을 담고 있으며, 다양한 형태의 pack 명령이 메서드로 구현됩니다. tkinter의 모든 위젯은 Pack의 서브 클래스이므로, 모든 패킹 메서드를 상속받습니다. Form 지오메트리 관리자에 대한 추가 정보는 tkinter.tix 모듈 설명서를 참조하십시오.

pack .fred -side left       =====>  fred.pack(side="left")

Tk와 Tkinter의 관계

위에서 아래로:

여러분의 응용 프로그램이 여기에 있습니다 (파이썬)

파이썬 응용 프로그램이 tkinter 호출을 합니다.

tkinter (파이썬 패키지)

이 호출(예를 들어, 버튼 위젯을 만든다고 합시다)은 파이썬으로 작성된 tkinter 패키지에 구현되어 있습니다. 이 파이썬 함수는 명령과 인자를 구문 분석하여, 파이썬 스크립트 대신 Tk 스크립트에서 나온 것처럼 보이는 형식으로 변환합니다.

_tkinter (C)

이 명령과 인자는 _tkinter - 밑줄에 주목하세요 - 확장 모듈의 C 함수에 전달됩니다.

Tk 위젯 (C와 Tcl)

이 C 함수는 Tk 라이브러리를 구성하는 C 함수를 포함하는 다른 C 모듈을 호출할 수 있습니다. Tk는 C와 약간의 Tcl로 구현됩니다. Tk 위젯의 Tcl 부분은 어떤 기본 동작을 위젯에 연결하는 데 사용되며, 파이썬 tkinter 패키지가 임포트 되는 시점에 한 번 실행됩니다. (사용자는 이 단계를 결코 보지 못합니다).

Tk (C)

Tk 위젯의 Tk 부분은 최종 … 로의 매핑을 구현합니다

Xlib (C)

화면에 그래픽을 그리기 위한 Xlib 라이브러리.

간편한 레퍼런스

옵션 설정

옵션은 위젯의 색상과 테두리 너비와 같은 것을 제어합니다. 옵션은 세 가지 방법으로 설정할 수 있습니다:

객체 생성 시, 키워드 인자 사용하기

fred = Button(self, fg="red", bg="blue")

객체 생성 후, 딕셔너리 인덱스처럼 옵션 이름을 다루기

fred["fg"] = "red"
fred["bg"] = "blue"

config() 메서드를 사용하여 객체 생성 이후 여러 어트리뷰트를 갱신하기.

fred.config(fg="red", bg="blue")

주어진 옵션과 그 동작에 대한 완전한 설명은, 해당 위젯의 Tk 매뉴얼 페이지를 참조하십시오.

매뉴얼 페이지는 각 위젯에 대해 “표준 옵션(STANDARD OPTIONS)”과 “위젯 특정 옵션(WIDGET SPECIFIC OPTIONS)”을 나열합니다. 전자는 많은 위젯에 공통적인 옵션 목록이며, 후자는 그 위젯에만 적용되는 옵션입니다. 표준 옵션은 options(3) 매뉴얼 페이지에 설명되어 있습니다.

이 문서에서는 표준과 위젯 특정 옵션을 구분하지 않습니다. 일부 옵션은 일부 위젯에 적용되지 않습니다. 특정 위젯이 특정 옵션에 응답하는지는 위젯의 클래스에 따라 다릅니다; 버튼에는 command 옵션이 있는데, 레이블은 그렇지 않습니다.

주어진 위젯이 지원하는 옵션은 위젯의 매뉴얼 페이지에 나열되거나, 실행 시간에 인자 없이 config() 메서드를 호출하거나 해당 위젯에서 keys() 메서드를 호출하여 조회할 수 있습니다. 이러한 호출의 반환 값은 키가 옵션의 이름인 문자열(예를 들어, 'relief')이고 값이 5-튜플인 딕셔너리입니다.

bg와 같은 일부 옵션은 긴 이름을 가진 공통 옵션의 동의어입니다 (bg는 “background”의 줄임말입니다). config() 메서드에 줄인 옵션을 전달하면 5-튜플이 아닌 2-튜플을 반환합니다. 전달된 2-튜플에는 동의어의 이름과 “실제” 옵션이 담겨있습니다 (가령 ('bg', 'background')).

인덱스

의미

예

0

옵션 이름

'relief'

1

데이터베이스 조회를 위한 옵션 이름

'relief'

2

데이터베이스 조회를 위한 옵션 클래스

'Relief'

3

기본값

'raised'

4

현재 값

'groove'

예:

>>> print(fred.config())
{'relief': ('relief', 'relief', 'Relief', 'raised', 'groove')}

물론, 인쇄된 딕셔너리에는 사용 가능한 모든 옵션과 해당 값이 포함됩니다. 이것은 예시일뿐입니다.

패커

패커(packer)는 Tk의 지오메트리 관리 메커니즘 중 하나입니다. 지오메트리 관리자는 컨테이너(위젯들의 공동 master) 내에서의 위젯 위치의 상대 위치를 지정하는 데 사용됩니다. 더 성가신 placer(잘 사용되지 않고, 여기서는 다루지 않습니다) 와는 달리, 패커는 위에, 왼쪽에, 채우기 등의 정성적(qualitative) 관계 규정을 취하고, 여러분을 위해 정확한 배치 좌표를 결정하기 위한 모든 작업을 수행합니다.

모든 master 위젯의 크기는 안에 있는 “슬레이브(slave) 위젯”의 크기에 의해 결정됩니다. 패커는 슬레이브 위젯이 패킹 되는 마스터 내부에 나타나는 위치를 제어하는 데 사용됩니다. 원하는 배치를 얻기 위해 프레임에 위젯을 팩하고, 프레임을 다른 프레임에 팩할 수 있습니다. 또한, 일단 팩 되면, 점진적인 구성의 변경을 수용하기 위해 배치가 동적으로 조정됩니다.

위젯은 지오메트리 관리자로 지오메트리를 지정할 때까지 표시되지 않습니다. 지오메트리 명세를 빠뜨리는 것은 초기에 흔한 실수이고, 위젯을 만들었지만, 아무것도 나타나지 않을 때 놀라게 됩니다. 위젯은 예를 들어 패커의 pack() 메서드가 적용된 후에만 나타납니다.

pack() 메서드는 컨테이너 내에서 위젯이 표시되는 위치와 메인 응용 프로그램 윈도우의 크기가 조정될 때 어떻게 동작할지를 제어하는 키워드 옵션/값 쌍으로 호출할 수 있습니다. 여기 몇 가지 예가 있습니다:

fred.pack()                     # defaults to side = "top"
fred.pack(side="left")
fred.pack(expand=1)

패커 옵션

패커와 그것이 받을 수 있는 옵션에 대한 더 자세한 정보는 매뉴얼 페이지와 John Ousterhout의 책의 183쪽을 참조하십시오.

anchor

앵커(anchor)형. 패커가 각 슬레이브를 컨테이너에 넣을 위치를 나타냅니다.

expand

불리언(boolean), 0 또는 1.

fill

유효한 값: 'x', 'y', 'both', 'none'.

ipadx와 ipady

거리(distance) - 슬레이브 위젯의 각 변의 내부 패딩을 지정합니다.

padx와 pady

거리(distance) - 슬레이브 위젯의 각 변의 외부 패딩을 지정합니다.

side

유효한 값: 'left', 'right', 'top', 'bottom'.

위젯 변수 결합하기

(텍스트 입력 위젯과 같은) 일부 위젯의 현재 값 설정은 특수 옵션을 사용하여 응용 프로그램 변수에 직접 연결할 수 있습니다. 이 옵션은 variable, textvariable, onvalue, offvalue 및 value입니다. 이 연결은 양방향으로 작동합니다: 어떤 이유로 든 변수가 변경되면, 연결된 위젯은 새 값을 반영하도록 갱신됩니다.

불행히도, tkinter의 현재 구현에서는 variable 또는 textvariable 옵션을 통해 임의의 파이썬 변수를 위젯으로 넘길 수 없습니다. 작동하는 유일한 종류의 변수는 tkinter에 정의된 Variable이라는 클래스에서 서브 클래싱되는 변수입니다.

이미 정의된 Variable의 유용한 서브 클래스가 많이 있습니다: StringVar, IntVar, DoubleVar 및 BooleanVar. 이러한 변수의 현재 값을 읽으려면 get() 메서드를 호출하고, 값을 바꾸려면 set() 메서드를 호출합니다. 이 프로토콜을 따르면, 여러분이 더는 개입하지 않더라도 위젯은 변수의 값을 항상 추적합니다.

예를 들면:

class App(Frame):
    def __init__(self, master=None):
        super().__init__(master)
        self.pack()

        self.entrythingy = Entry()
        self.entrythingy.pack()

        # here is the application variable
        self.contents = StringVar()
        # set it to some value
        self.contents.set("this is a variable")
        # tell the entry widget to watch this variable
        self.entrythingy["textvariable"] = self.contents

        # and here we get a callback when the user hits return.
        # we will have the program print out the value of the
        # application variable when the user hits return
        self.entrythingy.bind('<Key-Return>',
                              self.print_contents)

    def print_contents(self, event):
        print("hi. contents of entry is now ---->",
              self.contents.get())

창 관리자

Tk에는, 창 관리자와 상호 작용하기 위한 유틸리티 명령인 wm이 있습니다. wm 명령 옵션을 사용하여 제목, 배치, 아이콘 비트맵 등과 같은 항목을 제어할 수 있습니다. tkinter에서, 이러한 명령은 Wm 클래스의 메서드로 구현되었습니다. 최상위 위젯은 Wm 클래스의 서브 클래스이므로, Wm 메서드를 직접 호출할 수 있습니다.

주어진 위젯을 포함하는 최상위 창을 가져오려면, 종종 위젯의 마스터를 참조하는 것만으로도 됩니다. 물론 위젯이 프레임 안에 팩 되어 있다면, 마스터는 최상위 창을 나타내지 않을 것입니다. 임의의 위젯이 포함된 최상위 창을 가져오려면, _root() 메서드를 호출하면 됩니다. 이 메서드는 이 함수가 구현 일부이며, Tk 기능에 대한 인터페이스가 아니라는 사실을 나타내기 위해 밑줄로 시작합니다.

다음은 일반적인 사용 예입니다:

import tkinter as tk

class App(tk.Frame):
    def __init__(self, master=None):
        super().__init__(master)
        self.pack()

# create the application
myapp = App()

#
# here are method calls to the window manager class
#
myapp.master.title("My Do-Nothing Application")
myapp.master.maxsize(1000, 400)

# start the program
myapp.mainloop()

Tk 옵션 데이터형

anchor

유효한 값은 나침반의 눈금입니다: "n", "ne", "e", "se", "s", "sw", "w", "nw", 그리고 "center".

bitmap

8개의 내장된, 이름있는 비트맵이 있습니다: 'error', 'gray25', 'gray50', 'hourglass', 'info', 'questhead', 'question', 'warning'. X 비트맵 파일명을 지정하려면 "@/usr/contrib/bitmap/gumby.bit"처럼 @를 앞에 붙인 파일의 전체 경로를 지정하십시오.

boolean

정수 0이나 1 또는 문자열 "yes"나 "no"를 전달할 수 있습니다.

callback

인자를 취하지 않는 파이썬 함수입니다. 예를 들면:

def print_it():
    print("hi there")
fred["command"] = print_it

color

색상은 rgb.txt 파일에 있는 X 색상의 이름이나, RGB 값을 4비트: "#RGB", 8비트: "#RRGGBB", 12비트” "#RRRGGGBBB", 또는 16비트 "#RRRRGGGGBBBB" 범위로 표현하는 문자열로 제공됩니다. 여기서 R, G, B는 유효한 임의의 16진수를 나타냅니다. 자세한 내용은 Ousterhout의 책 160쪽을 참조하십시오.

cursor

XC_ 접두사 없이 cursorfont.h의 표준 X 커서 이름을 사용할 수 있습니다. 예를 들어, 손 모양 커서(XC_hand2)를 얻으려면, "hand2" 문자열을 사용하십시오. 여러분 자신의 비트맵과 마스크 파일을 지정할 수도 있습니다. Ousterhout의 책 179쪽을 보십시오.

distance

화면 거리는 픽셀이나 절대 거리로 지정할 수 있습니다. 픽셀은 숫자로 절대 거리는 문자열로 지정되며, 끝에 붙는 문자는 단위를 나타냅니다: c는 센티미터, i는 인치, m은 밀리미터, p는 프린터의 포인트입니다. 예를 들어, 3.5 인치는 "3.5i"로 표현됩니다.

font

Tk는 {courier 10 bold}와 같은, 목록 글꼴 이름 형식을 사용합니다. 양수로 표현된 글꼴 크기는 포인트로 측정됩니다; 음수로 표현된 크기는 픽셀 단위로 측정됩니다.

geometry

이것은 너비x높이 형식의 문자열로, 대부분의 위젯에서 너비와 높이는 픽셀 단위로 측정됩니다 (텍스트를 표시하는 위젯에서는 문자 단위). 예를 들어: fred["geometry"] = "200x100".

justify

유효한 값은 문자열입니다: "left", "center", "right" 및 "fill".

region

이것은 스페이스로 구분된 네 개의 요소가 있는 문자열이며, 각 요소는 유효한 거리(위를 참조하세요)입니다. 예를 들어: "2 3 4 5"와 "3i 2i 4.5i 2i"와 "3c 2c 4c 10.43c"는 모두 유효한 영역(region)입니다.

relief

위젯의 테두리 스타일을 결정합니다. 유효한 값은 다음과 같습니다: "raised", "sunken", "flat", "groove" 및 "ridge".

scrollcommand

이것은 거의 항상 어떤 스크롤 막대 위젯의 set() 메서드이지만, 단일 인자를 취하는 어떤 위젯 메서드도 가능합니다.

wrap:

"none", "char" 또는 "word" 중 하나여야 합니다.

바인딩과 이벤트

위젯 명령의 bind 메서드를 사용하면 특정 이벤트를 감시하고 해당 이벤트 유형이 발생할 때 콜백 함수가 트리거 되도록 할 수 있습니다. bind 메서드의 형식은 다음과 같습니다:

def bind(self, sequence, func, add=''):

여기에서:

sequence

는 대상 이벤트의 종류를 나타내는 문자열입니다. (자세한 내용은 bind 매뉴얼 페이지와 John Ousterhout의 책의 201쪽을 참조하십시오).

func

는 하나의 인자를 취하는 파이썬 함수로, 이벤트가 발생할 때 호출됩니다. 이벤트 인스턴스가 인자로 전달됩니다. (이런 식으로 설치되는 함수를 흔히 콜백(callbacks)이라고 합니다.)

add

는 선택적이고, ''나 '+'입니다. 빈 문자열을 전달하면 이 바인딩이 이 이벤트와 연관된 다른 바인딩을 대체 함을 나타냅니다. '+'를 전달하면 이 함수가 이 이벤트 유형에 바인딩 된 함수 목록에 추가됩니다.

예를 들면:

def turn_red(self, event):
    event.widget["activeforeground"] = "red"

self.button.bind("<Enter>", self.turn_red)

이벤트의 widget 필드가 turn_red() 콜백에서 어떻게 액세스 되는지 주목하십시오. 이 필드는 X 이벤트를 포착한 위젯을 포함합니다. 다음 표에는 사용자가 액세스할 수 있는 다른 이벤트 필드와 Tk에서 이들을 표시하는 방법이 나열되어 있습니다. Tk 매뉴얼 페이지를 참조할 때 유용할 수 있습니다.

Tk

Tkinter 이벤트 필드

Tk

Tkinter 이벤트 필드

%f

focus

%A

char

%h

height

%E

send_event

%k

keycode

%K

keysym

%s

state

%N

keysym_num

%t

time

%T

type

%w

width

%W

widget

%x

x

%X

x_root

%y

y

%Y

y_root

index 매개 변수

많은 위젯에는 “index” 매개 변수가 전달되어야 합니다. 이들은 Text 위젯의 특정 위치, Entry 위젯의 특정 문자 또는 Menu 위젯의 특정 메뉴 항목을 가리키는 데 사용됩니다.

Entry 위젯 인덱스 (인덱스, 뷰 인덱스 등)

Entry 위젯에는 표시되는 텍스트의 문자 위치를 참조하는 옵션이 있습니다. 다음 tkinter 함수를 사용하여 텍스트 위젯에서 이러한 특수 지점에 액세스할 수 있습니다:

Text 위젯 인덱스

Text 위젯의 인덱스 표기법은 매우 풍부하며 Tk 매뉴얼 페이지에 자세히 설명되어 있습니다.

메뉴 인덱스 (menu.invoke(), menu.entryconfig() 등)

메뉴에 대한 일부 옵션 및 메서드는 특정 메뉴 항목을 조작합니다. 옵션이나 매개 변수에 메뉴 인덱스가 필요한 때는 언제든지 다음과 같이 전달할 수 있습니다:

위에서부터 세고, 0에서 시작하는, 위젯에서 항목의 숫자 위치를 나타내는 정수.

현재 커서 아래에 있는 메뉴 위치를 나타내는, 문자열 "active".

마지막 메뉴 항목을 나타내는, 문자열 "last".

@6과 같이, @이 앞에 오는 정수로, 정수는 메뉴의 좌표계에서 y 픽셀 좌표로 해석됩니다.

아무런 메뉴 항목을 가리키지 않는, 문자열 "none"은 menu.activate()와 함께 사용되어 모든 항목을 비활성화합니다, 마지막으로,

메뉴 맨 위에서 아래로 스캔할 때, 메뉴 항목의 레이블과 패턴 일치하는 텍스트 문자열. 이 인덱스 유형은 다른 모든 항목 다음에 고려되므로, last, active 또는 none 레이블이 붙은 메뉴 항목과의 일치가 대신 위의 리터럴로 해석될 수 있음을 의미합니다.

이미지

서로 다른 형식의 이미지를 tkinter.Image의 해당 서브 클래스를 통해 만들 수 있습니다:

XBM 형식의 이미지를 위한 BitmapImage.

PGM, PPM, GIF 및 PNG 형식의 이미지를 위한 PhotoImage. 후자는 Tk 8.6부터 지원됩니다.

두 가지 유형의 이미지는 file 또는 data 옵션을 통해 만들어집니다 (다른 옵션도 사용할 수 있습니다).

그런 다음 image 옵션이 일부 위젯(예를 들어, 레이블, 버튼, 메뉴)에서 지원되는 곳이면 어디든 이미지 객체를 사용할 수 있습니다. 이 경우, Tk는 이미지에 대한 참조를 유지하지 않습니다. 이미지 객체에 대한 마지막 파이썬 참조가 삭제되면 이미지 데이터도 삭제되고, Tk는 이미지가 사용된 곳마다 빈 상자를 표시합니다.

더 보기

Pillow [http://python-pillow.org/] 패키지는 BMP, JPEG, TIFF 및 WebP와 같은 형식을 위한 지원을 추가합니다.

파일 처리기

Tk는 파일 기술자에서 I/O가 가능할 때 Tk 메인 루프에서 호출할 콜백 함수를 등록하고 등록 취소할 수 있도록 합니다. 파일 기술자당 하나의 처리기 만 등록 될 수 있습니다. 예제 코드:

import tkinter
widget = tkinter.Tk()
mask = tkinter.READABLE | tkinter.WRITABLE
widget.tk.createfilehandler(file, mask, callback)
...
widget.tk.deletefilehandler(file)

윈도우에서는 이 기능을 사용할 수 없습니다.

얼마나 많은 바이트를 읽을 수 있는지 모르므로, BufferedIOBase나 TextIOBase read()나 readline() 메서드를 사용하고 싶지 않을것입니다, 이것들은 미리 정의 된 바이트 수를 읽으려고하기 때문입니다. 소켓의 경우, recv() 또는 recvfrom() 메서드가 제대로 작동합니다; 다른 파일의 경우, 날(raw) 읽기나 os.read(file.fileno(), maxbytecount)를 사용하십시오.

Widget.tk.createfilehandler(file, mask, func)

파일 처리기 콜백 함수 func를 등록합니다. file 인자는 fileno() 메서드가 있는 객체이거나(가령 파일이나 소켓 객체), 정수 파일 기술자일 수 있습니다. mask 인자는 아래의 세 가지 상수들을 OR로 조합한 것입니다. 콜백은 다음과 같이 호출됩니다:

callback(file, mask)

Widget.tk.deletefilehandler(file)

파일 처리기를 등록 취소합니다.

tkinter.READABLE

tkinter.WRITABLE

tkinter.EXCEPTION

mask 인자에 사용되는 상수입니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

Tk를 사용한 그래픽 사용자 인터페이스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

Tk를 사용한 그래픽 사용자 인터페이스 »

|

tkinter.ttk — Tk themed widgets

Source code: Lib/tkinter/ttk.py [https://github.com/python/cpython/tree/3.7/Lib/tkinter/ttk.py]

The tkinter.ttk module provides access to the Tk themed widget set, introduced in Tk 8.5. If Python has not been compiled against Tk 8.5, this module can still be accessed if Tile has been installed. The former method using Tk 8.5 provides additional benefits including anti-aliased font rendering under X11 and window transparency (requiring a composition window manager on X11).

The basic idea for tkinter.ttk is to separate, to the extent possible, the code implementing a widget’s behavior from the code implementing its appearance.

더 보기

Tk Widget Styling Support [https://core.tcl.tk/tips/doc/trunk/tip/48.md]

A document introducing theming support for Tk

Using Ttk

To start using Ttk, import its module:

from tkinter import ttk

To override the basic Tk widgets, the import should follow the Tk import:

from tkinter import *
from tkinter.ttk import *

That code causes several tkinter.ttk widgets (Button, Checkbutton, Entry, Frame, Label, LabelFrame, Menubutton, PanedWindow, Radiobutton, Scale and Scrollbar) to automatically replace the Tk widgets.

This has the direct benefit of using the new widgets which gives a better look and feel across platforms; however, the replacement widgets are not completely compatible. The main difference is that widget options such as “fg”, “bg” and others related to widget styling are no longer present in Ttk widgets. Instead, use the ttk.Style class for improved styling effects.

더 보기

Converting existing applications to use Tile widgets [http://tktable.sourceforge.net/tile/doc/converting.txt]

A monograph (using Tcl terminology) about differences typically encountered when moving applications to use the new widgets.

Ttk Widgets

Ttk comes with 18 widgets, twelve of which already existed in tkinter: Button, Checkbutton, Entry, Frame, Label, LabelFrame, Menubutton, PanedWindow, Radiobutton, Scale, Scrollbar, and Spinbox. The other six are new: Combobox, Notebook, Progressbar, Separator, Sizegrip and Treeview. And all them are subclasses of Widget.

Using the Ttk widgets gives the application an improved look and feel. As discussed above, there are differences in how the styling is coded.

Tk code:

l1 = tkinter.Label(text="Test", fg="black", bg="white")
l2 = tkinter.Label(text="Test", fg="black", bg="white")

Ttk code:

style = ttk.Style()
style.configure("BW.TLabel", foreground="black", background="white")

l1 = ttk.Label(text="Test", style="BW.TLabel")
l2 = ttk.Label(text="Test", style="BW.TLabel")

For more information about TtkStyling, see the Style class documentation.

Widget

ttk.Widget defines standard options and methods supported by Tk themed widgets and is not supposed to be directly instantiated.

Standard Options

All the ttk Widgets accepts the following options:

Option

Description

class

Specifies the window class. The class is used when querying the option database for the window’s other options, to determine the default bindtags for the window, and to select the widget’s default layout and style. This option is read-only, and may only be specified when the window is created.

cursor

Specifies the mouse cursor to be used for the widget. If set to the empty string (the default), the cursor is inherited for the parent widget.

takefocus

Determines whether the window accepts the focus during keyboard traversal. 0, 1 or an empty string is returned. If 0 is returned, it means that the window should be skipped entirely during keyboard traversal. If 1, it means that the window should receive the input focus as long as it is viewable. And an empty string means that the traversal scripts make the decision about whether or not to focus on the window.

style

May be used to specify a custom widget style.

Scrollable Widget Options

The following options are supported by widgets that are controlled by a scrollbar.

Option

Description

xscrollcommand

Used to communicate with horizontal scrollbars.

When the view in the widget’s window change, the widget will generate a Tcl command based on the scrollcommand.

Usually this option consists of the method Scrollbar.set() of some scrollbar. This will cause the scrollbar to be updated whenever the view in the window changes.

yscrollcommand

Used to communicate with vertical scrollbars. For some more information, see above.

Label Options

The following options are supported by labels, buttons and other button-like widgets.

Option

Description

text

Specifies a text string to be displayed inside the widget.

textvariable

Specifies a name whose value will be used in place of the text option resource.

underline

If set, specifies the index (0-based) of a character to underline in the text string. The underline character is used for mnemonic activation.

image

Specifies an image to display. This is a list of 1 or more elements. The first element is the default image name. The rest of the list if a sequence of statespec/value pairs as defined by Style.map(), specifying different images to use when the widget is in a particular state or a combination of states. All images in the list should have the same size.

compound

Specifies how to display the image relative to the text, in the case both text and images options are present. Valid values are:

text: display text only

image: display image only

top, bottom, left, right: display image above, below, left of, or right of the text, respectively.

none: the default. display the image if present, otherwise the text.

width

If greater than zero, specifies how much space, in character widths, to allocate for the text label, if less than zero, specifies a minimum width. If zero or unspecified, the natural width of the text label is used.

Compatibility Options

Option

Description

state

May be set to “normal” or “disabled” to control the “disabled” state bit. This is a write-only option: setting it changes the widget state, but the Widget.state() method does not affect this option.

Widget States

The widget state is a bitmap of independent state flags.

Flag

Description

active

The mouse cursor is over the widget and pressing a mouse button will cause some action to occur

disabled

Widget is disabled under program control

focus

Widget has keyboard focus

pressed

Widget is being pressed

selected

“On”, “true”, or “current” for things like Checkbuttons and radiobuttons

background

Windows and Mac have a notion of an “active” or foreground window. The background state is set for widgets in a background window, and cleared for those in the foreground window

readonly

Widget should not allow user modification

alternate

A widget-specific alternate display format

invalid

The widget’s value is invalid

A state specification is a sequence of state names, optionally prefixed with an exclamation point indicating that the bit is off.

ttk.Widget

Besides the methods described below, the ttk.Widget supports the methods tkinter.Widget.cget() and tkinter.Widget.configure().

class tkinter.ttk.Widget

identify(x, y)

Returns the name of the element at position x y, or the empty string if the point does not lie within any element.

x and y are pixel coordinates relative to the widget.

instate(statespec, callback=None, *args, **kw)

Test the widget’s state. If a callback is not specified, returns True if the widget state matches statespec and False otherwise. If callback is specified then it is called with args if widget state matches statespec.

state(statespec=None)

Modify or inquire widget state. If statespec is specified, sets the widget state according to it and return a new statespec indicating which flags were changed. If statespec is not specified, returns the currently-enabled state flags.

statespec will usually be a list or a tuple.

Combobox

The ttk.Combobox widget combines a text field with a pop-down list of values. This widget is a subclass of Entry.

Besides the methods inherited from Widget: Widget.cget(), Widget.configure(), Widget.identify(), Widget.instate() and Widget.state(), and the following inherited from Entry: Entry.bbox(), Entry.delete(), Entry.icursor(), Entry.index(), Entry.insert(), Entry.selection(), Entry.xview(), it has some other methods, described at ttk.Combobox.

Options

This widget accepts the following specific options:

Option

Description

exportselection

Boolean value. If set, the widget selection is linked to the Window Manager selection (which can be returned by invoking Misc.selection_get, for example).

justify

Specifies how the text is aligned within the widget. One of “left”, “center”, or “right”.

height

Specifies the height of the pop-down listbox, in rows.

postcommand

A script (possibly registered with Misc.register) that is called immediately before displaying the values. It may specify which values to display.

state

One of “normal”, “readonly”, or “disabled”. In the “readonly” state, the value may not be edited directly, and the user can only selection of the values from the dropdown list. In the “normal” state, the text field is directly editable. In the “disabled” state, no interaction is possible.

textvariable

Specifies a name whose value is linked to the widget value. Whenever the value associated with that name changes, the widget value is updated, and vice versa. See tkinter.StringVar.

values

Specifies the list of values to display in the drop-down listbox.

width

Specifies an integer value indicating the desired width of the entry window, in average-size characters of the widget’s font.

Virtual events

The combobox widgets generates a <<ComboboxSelected>> virtual event when the user selects an element from the list of values.

ttk.Combobox

class tkinter.ttk.Combobox

current(newindex=None)

If newindex is specified, sets the combobox value to the element position newindex. Otherwise, returns the index of the current value or -1 if the current value is not in the values list.

get()

Returns the current value of the combobox.

set(value)

Sets the value of the combobox to value.

Spinbox

The ttk.Spinbox widget is a ttk.Entry enhanced with increment and decrement arrows. It can be used for numbers or lists of string values. This widget is a subclass of Entry.

Besides the methods inherited from Widget: Widget.cget(), Widget.configure(), Widget.identify(), Widget.instate() and Widget.state(), and the following inherited from Entry: Entry.bbox(), Entry.delete(), Entry.icursor(), Entry.index(), Entry.insert(), Entry.xview(), it has some other methods, described at ttk.Spinbox.

Options

This widget accepts the following specific options:

Option

Description

from

Float value. If set, this is the minimum value to which the decrement button will decrement. Must be spelled as from_ when used as an argument, since from is a Python keyword.

to

Float value. If set, this is the maximum value to which the increment button will increment.

increment

Float value. Specifies the amount which the increment/decrement buttons change the value. Defaults to 1.0.

values

Sequence of string or float values. If specified, the increment/decrement buttons will cycle through the items in this sequence rather than incrementing or decrementing numbers.

wrap

Boolean value. If True, increment and decrement buttons will cycle from the to value to the from value or the from value to the to value, respectively.

format

String value. This specifies the format of numbers set by the increment/decrement buttons. It must be in the form “%W.Pf”, where W is the padded width of the value, P is the precision, and ‘%’ and ‘f’ are literal.

command

Python callable. Will be called with no arguments whenever either of the increment or decrement buttons are pressed.

Virtual events

The spinbox widget generates an <<Increment>> virtual event when the user presses <Up>, and a <<Decrement>> virtual event when the user presses <Down>.

ttk.Spinbox

class tkinter.ttk.Spinbox

get()

Returns the current value of the spinbox.

set(value)

Sets the value of the spinbox to value.

Notebook

Ttk Notebook widget manages a collection of windows and displays a single one at a time. Each child window is associated with a tab, which the user may select to change the currently-displayed window.

Options

This widget accepts the following specific options:

Option

Description

height

If present and greater than zero, specifies the desired height of the pane area (not including internal padding or tabs). Otherwise, the maximum height of all panes is used.

padding

Specifies the amount of extra space to add around the outside of the notebook. The padding is a list up to four length specifications left top right bottom. If fewer than four elements are specified, bottom defaults to top, right defaults to left, and top defaults to left.

width

If present and greater than zero, specified the desired width of the pane area (not including internal padding). Otherwise, the maximum width of all panes is used.

Tab Options

There are also specific options for tabs:

Option

Description

state

Either “normal”, “disabled” or “hidden”. If “disabled”, then the tab is not selectable. If “hidden”, then the tab is not shown.

sticky

Specifies how the child window is positioned within the pane area. Value is a string containing zero or more of the characters “n”, “s”, “e” or “w”. Each letter refers to a side (north, south, east or west) that the child window will stick to, as per the grid() geometry manager.

padding

Specifies the amount of extra space to add between the notebook and this pane. Syntax is the same as for the option padding used by this widget.

text

Specifies a text to be displayed in the tab.

image

Specifies an image to display in the tab. See the option image described in Widget.

compound

Specifies how to display the image relative to the text, in the case both options text and image are present. See Label Options for legal values.

underline

Specifies the index (0-based) of a character to underline in the text string. The underlined character is used for mnemonic activation if Notebook.enable_traversal() is called.

Tab Identifiers

The tab_id present in several methods of ttk.Notebook may take any of the following forms:

An integer between zero and the number of tabs

The name of a child window

A positional specification of the form “@x,y”, which identifies the tab

The literal string “current”, which identifies the currently-selected tab

The literal string “end”, which returns the number of tabs (only valid for Notebook.index())

Virtual Events

This widget generates a <<NotebookTabChanged>> virtual event after a new tab is selected.

ttk.Notebook

class tkinter.ttk.Notebook

add(child, **kw)

Adds a new tab to the notebook.

If window is currently managed by the notebook but hidden, it is restored to its previous position.

See Tab Options for the list of available options.

forget(tab_id)

Removes the tab specified by tab_id, unmaps and unmanages the associated window.

hide(tab_id)

Hides the tab specified by tab_id.

The tab will not be displayed, but the associated window remains managed by the notebook and its configuration remembered. Hidden tabs may be restored with the add() command.

identify(x, y)

Returns the name of the tab element at position x, y, or the empty string if none.

index(tab_id)

Returns the numeric index of the tab specified by tab_id, or the total number of tabs if tab_id is the string “end”.

insert(pos, child, **kw)

Inserts a pane at the specified position.

pos is either the string “end”, an integer index, or the name of a managed child. If child is already managed by the notebook, moves it to the specified position.

See Tab Options for the list of available options.

select(tab_id=None)

Selects the specified tab_id.

The associated child window will be displayed, and the previously-selected window (if different) is unmapped. If tab_id is omitted, returns the widget name of the currently selected pane.

tab(tab_id, option=None, **kw)

Query or modify the options of the specific tab_id.

If kw is not given, returns a dictionary of the tab option values. If option is specified, returns the value of that option. Otherwise, sets the options to the corresponding values.

tabs()

Returns a list of windows managed by the notebook.

enable_traversal()

Enable keyboard traversal for a toplevel window containing this notebook.

This will extend the bindings for the toplevel window containing the notebook as follows:

Control-Tab: selects the tab following the currently selected one.

Shift-Control-Tab: selects the tab preceding the currently selected one.

Alt-K: where K is the mnemonic (underlined) character of any tab, will select that tab.

Multiple notebooks in a single toplevel may be enabled for traversal, including nested notebooks. However, notebook traversal only works properly if all panes have the notebook they are in as master.

Progressbar

The ttk.Progressbar widget shows the status of a long-running operation. It can operate in two modes: 1) the determinate mode which shows the amount completed relative to the total amount of work to be done and 2) the indeterminate mode which provides an animated display to let the user know that work is progressing.

Options

This widget accepts the following specific options:

Option

Description

orient

One of “horizontal” or “vertical”. Specifies the orientation of the progress bar.

length

Specifies the length of the long axis of the progress bar (width if horizontal, height if vertical).

mode

One of “determinate” or “indeterminate”.

maximum

A number specifying the maximum value. Defaults to 100.

value

The current value of the progress bar. In “determinate” mode, this represents the amount of work completed. In “indeterminate” mode, it is interpreted as modulo maximum; that is, the progress bar completes one “cycle” when its value increases by maximum.

variable

A name which is linked to the option value. If specified, the value of the progress bar is automatically set to the value of this name whenever the latter is modified.

phase

Read-only option. The widget periodically increments the value of this option whenever its value is greater than 0 and, in determinate mode, less than maximum. This option may be used by the current theme to provide additional animation effects.

ttk.Progressbar

class tkinter.ttk.Progressbar

start(interval=None)

Begin autoincrement mode: schedules a recurring timer event that calls Progressbar.step() every interval milliseconds. If omitted, interval defaults to 50 milliseconds.

step(amount=None)

Increments the progress bar’s value by amount.

amount defaults to 1.0 if omitted.

stop()

Stop autoincrement mode: cancels any recurring timer event initiated by Progressbar.start() for this progress bar.

Separator

The ttk.Separator widget displays a horizontal or vertical separator bar.

It has no other methods besides the ones inherited from ttk.Widget.

Options

This widget accepts the following specific option:

Option

Description

orient

One of “horizontal” or “vertical”. Specifies the orientation of the separator.

Sizegrip

The ttk.Sizegrip widget (also known as a grow box) allows the user to resize the containing toplevel window by pressing and dragging the grip.

This widget has neither specific options nor specific methods, besides the ones inherited from ttk.Widget.

Platform-specific notes

On MacOS X, toplevel windows automatically include a built-in size grip by default. Adding a Sizegrip is harmless, since the built-in grip will just mask the widget.

Bugs

If the containing toplevel’s position was specified relative to the right or bottom of the screen (e.g. ….), the Sizegrip widget will not resize the window.

This widget supports only “southeast” resizing.

Treeview

The ttk.Treeview widget displays a hierarchical collection of items. Each item has a textual label, an optional image, and an optional list of data values. The data values are displayed in successive columns after the tree label.

The order in which data values are displayed may be controlled by setting the widget option displaycolumns. The tree widget can also display column headings. Columns may be accessed by number or symbolic names listed in the widget option columns. See Column Identifiers.

Each item is identified by a unique name. The widget will generate item IDs if they are not supplied by the caller. There is a distinguished root item, named {}. The root item itself is not displayed; its children appear at the top level of the hierarchy.

Each item also has a list of tags, which can be used to associate event bindings with individual items and control the appearance of the item.

The Treeview widget supports horizontal and vertical scrolling, according to the options described in Scrollable Widget Options and the methods Treeview.xview() and Treeview.yview().

Options

This widget accepts the following specific options:

Option

Description

columns

A list of column identifiers, specifying the number of columns and their names.

displaycolumns

A list of column identifiers (either symbolic or integer indices) specifying which data columns are displayed and the order in which they appear, or the string “#all”.

height

Specifies the number of rows which should be visible. Note: the requested width is determined from the sum of the column widths.

padding

Specifies the internal padding for the widget. The padding is a list of up to four length specifications.

selectmode

Controls how the built-in class bindings manage the selection. One of “extended”, “browse” or “none”. If set to “extended” (the default), multiple items may be selected. If “browse”, only a single item will be selected at a time. If “none”, the selection will not be changed.

Note that the application code and tag bindings can set the selection however they wish, regardless of the value of this option.

show

A list containing zero or more of the following values, specifying which elements of the tree to display.

tree: display tree labels in column #0.

headings: display the heading row.

The default is “tree headings”, i.e., show all elements.

Note: Column #0 always refers to the tree column, even if show=”tree” is not specified.

Item Options

The following item options may be specified for items in the insert and item widget commands.

Option

Description

text

The textual label to display for the item.

image

A Tk Image, displayed to the left of the label.

values

The list of values associated with the item.

Each item should have the same number of values as the widget option columns. If there are fewer values than columns, the remaining values are assumed empty. If there are more values than columns, the extra values are ignored.

open

True/False value indicating whether the item’s children should be displayed or hidden.

tags

A list of tags associated with this item.

Tag Options

The following options may be specified on tags:

Option

Description

foreground

Specifies the text foreground color.

background

Specifies the cell or item background color.

font

Specifies the font to use when drawing text.

image

Specifies the item image, in case the item’s image option is empty.

Column Identifiers

Column identifiers take any of the following forms:

A symbolic name from the list of columns option.

An integer n, specifying the nth data column.

A string of the form #n, where n is an integer, specifying the nth display column.

Notes:

Item’s option values may be displayed in a different order than the order in which they are stored.

Column #0 always refers to the tree column, even if show=”tree” is not specified.

A data column number is an index into an item’s option values list; a display column number is the column number in the tree where the values are displayed. Tree labels are displayed in column #0. If option displaycolumns is not set, then data column n is displayed in column #n+1. Again, column #0 always refers to the tree column.

Virtual Events

The Treeview widget generates the following virtual events.

Event

Description

<<TreeviewSelect>>

Generated whenever the selection changes.

<<TreeviewOpen>>

Generated just before settings the focus item to open=True.

<<TreeviewClose>>

Generated just after setting the focus item to open=False.

The Treeview.focus() and Treeview.selection() methods can be used to determine the affected item or items.

ttk.Treeview

class tkinter.ttk.Treeview

bbox(item, column=None)

Returns the bounding box (relative to the treeview widget’s window) of the specified item in the form (x, y, width, height).

If column is specified, returns the bounding box of that cell. If the item is not visible (i.e., if it is a descendant of a closed item or is scrolled offscreen), returns an empty string.

get_children(item=None)

Returns the list of children belonging to item.

If item is not specified, returns root children.

set_children(item, *newchildren)

Replaces item’s child with newchildren.

Children present in item that are not present in newchildren are detached from the tree. No items in newchildren may be an ancestor of item. Note that not specifying newchildren results in detaching item’s children.

column(column, option=None, **kw)

Query or modify the options for the specified column.

If kw is not given, returns a dict of the column option values. If option is specified then the value for that option is returned. Otherwise, sets the options to the corresponding values.

The valid options/values are:

id

Returns the column name. This is a read-only option.

anchor: One of the standard Tk anchor values.

Specifies how the text in this column should be aligned with respect to the cell.

minwidth: width

The minimum width of the column in pixels. The treeview widget will not make the column any smaller than specified by this option when the widget is resized or the user drags a column.

stretch: True/False

Specifies whether the column’s width should be adjusted when the widget is resized.

width: width

The width of the column in pixels.

To configure the tree column, call this with column = “#0”

delete(*items)

Delete all specified items and all their descendants.

The root item may not be deleted.

detach(*items)

Unlinks all of the specified items from the tree.

The items and all of their descendants are still present, and may be reinserted at another point in the tree, but will not be displayed.

The root item may not be detached.

exists(item)

Returns True if the specified item is present in the tree.

focus(item=None)

If item is specified, sets the focus item to item. Otherwise, returns the current focus item, or ‘’ if there is none.

heading(column, option=None, **kw)

Query or modify the heading options for the specified column.

If kw is not given, returns a dict of the heading option values. If option is specified then the value for that option is returned. Otherwise, sets the options to the corresponding values.

The valid options/values are:

text: text

The text to display in the column heading.

image: imageName

Specifies an image to display to the right of the column heading.

anchor: anchor

Specifies how the heading text should be aligned. One of the standard Tk anchor values.

command: callback

A callback to be invoked when the heading label is pressed.

To configure the tree column heading, call this with column = “#0”.

identify(component, x, y)

Returns a description of the specified component under the point given by x and y, or the empty string if no such component is present at that position.

identify_row(y)

Returns the item ID of the item at position y.

identify_column(x)

Returns the data column identifier of the cell at position x.

The tree column has ID #0.

identify_region(x, y)

Returns one of:

region

meaning

heading

Tree heading area.

separator

Space between two columns headings.

tree

The tree area.

cell

A data cell.

Availability: Tk 8.6.

identify_element(x, y)

Returns the element at position x, y.

Availability: Tk 8.6.

index(item)

Returns the integer index of item within its parent’s list of children.

insert(parent, index, iid=None, **kw)

Creates a new item and returns the item identifier of the newly created item.

parent is the item ID of the parent item, or the empty string to create a new top-level item. index is an integer, or the value “end”, specifying where in the list of parent’s children to insert the new item. If index is less than or equal to zero, the new node is inserted at the beginning; if index is greater than or equal to the current number of children, it is inserted at the end. If iid is specified, it is used as the item identifier; iid must not already exist in the tree. Otherwise, a new unique identifier is generated.

See Item Options for the list of available points.

item(item, option=None, **kw)

Query or modify the options for the specified item.

If no options are given, a dict with options/values for the item is returned. If option is specified then the value for that option is returned. Otherwise, sets the options to the corresponding values as given by kw.

move(item, parent, index)

Moves item to position index in parent’s list of children.

It is illegal to move an item under one of its descendants. If index is less than or equal to zero, item is moved to the beginning; if greater than or equal to the number of children, it is moved to the end. If item was detached it is reattached.

next(item)

Returns the identifier of item’s next sibling, or ‘’ if item is the last child of its parent.

parent(item)

Returns the ID of the parent of item, or ‘’ if item is at the top level of the hierarchy.

prev(item)

Returns the identifier of item’s previous sibling, or ‘’ if item is the first child of its parent.

reattach(item, parent, index)

An alias for Treeview.move().

see(item)

Ensure that item is visible.

Sets all of item’s ancestors open option to True, and scrolls the widget if necessary so that item is within the visible portion of the tree.

selection(selop=None, items=None)

If selop is not specified, returns selected items. Otherwise, it will act according to the following selection methods.

Deprecated since version 3.6, will be removed in version 3.8: Using selection() for changing the selection state is deprecated. Use the following selection methods instead.

selection_set(*items)

items becomes the new selection.

버전 3.6에서 변경: items can be passed as separate arguments, not just as a single tuple.

selection_add(*items)

Add items to the selection.

버전 3.6에서 변경: items can be passed as separate arguments, not just as a single tuple.

selection_remove(*items)

Remove items from the selection.

버전 3.6에서 변경: items can be passed as separate arguments, not just as a single tuple.

selection_toggle(*items)

Toggle the selection state of each item in items.

버전 3.6에서 변경: items can be passed as separate arguments, not just as a single tuple.

set(item, column=None, value=None)

With one argument, returns a dictionary of column/value pairs for the specified item. With two arguments, returns the current value of the specified column. With three arguments, sets the value of given column in given item to the specified value.

tag_bind(tagname, sequence=None, callback=None)

Bind a callback for the given event sequence to the tag tagname. When an event is delivered to an item, the callbacks for each of the item’s tags option are called.

tag_configure(tagname, option=None, **kw)

Query or modify the options for the specified tagname.

If kw is not given, returns a dict of the option settings for tagname. If option is specified, returns the value for that option for the specified tagname. Otherwise, sets the options to the corresponding values for the given tagname.

tag_has(tagname, item=None)

If item is specified, returns 1 or 0 depending on whether the specified item has the given tagname. Otherwise, returns a list of all items that have the specified tag.

Availability: Tk 8.6

xview(*args)

Query or modify horizontal position of the treeview.

yview(*args)

Query or modify vertical position of the treeview.

Ttk Styling

Each widget in ttk is assigned a style, which specifies the set of elements making up the widget and how they are arranged, along with dynamic and default settings for element options. By default the style name is the same as the widget’s class name, but it may be overridden by the widget’s style option. If you don’t know the class name of a widget, use the method Misc.winfo_class() (somewidget.winfo_class()).

더 보기

Tcl’2004 conference presentation [http://tktable.sourceforge.net/tile/tile-tcl2004.pdf]

This document explains how the theme engine works

class tkinter.ttk.Style

This class is used to manipulate the style database.

configure(style, query_opt=None, **kw)

Query or set the default value of the specified option(s) in style.

Each key in kw is an option and each value is a string identifying the value for that option.

For example, to change every default button to be a flat button with some padding and a different background color:

from tkinter import ttk
import tkinter

root = tkinter.Tk()

ttk.Style().configure("TButton", padding=6, relief="flat",
   background="#ccc")

btn = ttk.Button(text="Sample")
btn.pack()

root.mainloop()

map(style, query_opt=None, **kw)

Query or sets dynamic values of the specified option(s) in style.

Each key in kw is an option and each value should be a list or a tuple (usually) containing statespecs grouped in tuples, lists, or some other preference. A statespec is a compound of one or more states and then a value.

An example may make it more understandable:

import tkinter
from tkinter import ttk

root = tkinter.Tk()

style = ttk.Style()
style.map("C.TButton",
    foreground=[('pressed', 'red'), ('active', 'blue')],
    background=[('pressed', '!disabled', 'black'), ('active', 'white')]
    )

colored_btn = ttk.Button(text="Test", style="C.TButton").pack()

root.mainloop()

Note that the order of the (states, value) sequences for an option does matter, if the order is changed to [('active', 'blue'), ('pressed', 'red')] in the foreground option, for example, the result would be a blue foreground when the widget were in active or pressed states.

lookup(style, option, state=None, default=None)

Returns the value specified for option in style.

If state is specified, it is expected to be a sequence of one or more states. If the default argument is set, it is used as a fallback value in case no specification for option is found.

To check what font a Button uses by default:

from tkinter import ttk

print(ttk.Style().lookup("TButton", "font"))

layout(style, layoutspec=None)

Define the widget layout for given style. If layoutspec is omitted, return the layout specification for given style.

layoutspec, if specified, is expected to be a list or some other sequence type (excluding strings), where each item should be a tuple and the first item is the layout name and the second item should have the format described in Layouts.

To understand the format, see the following example (it is not intended to do anything useful):

from tkinter import ttk
import tkinter

root = tkinter.Tk()

style = ttk.Style()
style.layout("TMenubutton", [
   ("Menubutton.background", None),
   ("Menubutton.button", {"children":
       [("Menubutton.focus", {"children":
           [("Menubutton.padding", {"children":
               [("Menubutton.label", {"side": "left", "expand": 1})]
           })]
       })]
   }),
])

mbtn = ttk.Menubutton(text='Text')
mbtn.pack()
root.mainloop()

element_create(elementname, etype, *args, **kw)

Create a new element in the current theme, of the given etype which is expected to be either “image”, “from” or “vsapi”. The latter is only available in Tk 8.6a for Windows XP and Vista and is not described here.

If “image” is used, args should contain the default image name followed by statespec/value pairs (this is the imagespec), and kw may have the following options:

border=padding

padding is a list of up to four integers, specifying the left, top, right, and bottom borders, respectively.

height=height

Specifies a minimum height for the element. If less than zero, the base image’s height is used as a default.

padding=padding

Specifies the element’s interior padding. Defaults to border’s value if not specified.

sticky=spec

Specifies how the image is placed within the final parcel. spec contains zero or more characters “n”, “s”, “w”, or “e”.

width=width

Specifies a minimum width for the element. If less than zero, the base image’s width is used as a default.

If “from” is used as the value of etype, element_create() will clone an existing element. args is expected to contain a themename, from which the element will be cloned, and optionally an element to clone from. If this element to clone from is not specified, an empty element will be used. kw is discarded.

element_names()

Returns the list of elements defined in the current theme.

element_options(elementname)

Returns the list of elementname’s options.

theme_create(themename, parent=None, settings=None)

Create a new theme.

It is an error if themename already exists. If parent is specified, the new theme will inherit styles, elements and layouts from the parent theme. If settings are present they are expected to have the same syntax used for theme_settings().

theme_settings(themename, settings)

Temporarily sets the current theme to themename, apply specified settings and then restore the previous theme.

Each key in settings is a style and each value may contain the keys ‘configure’, ‘map’, ‘layout’ and ‘element create’ and they are expected to have the same format as specified by the methods Style.configure(), Style.map(), Style.layout() and Style.element_create() respectively.

As an example, let’s change the Combobox for the default theme a bit:

from tkinter import ttk
import tkinter

root = tkinter.Tk()

style = ttk.Style()
style.theme_settings("default", {
   "TCombobox": {
       "configure": {"padding": 5},
       "map": {
           "background": [("active", "green2"),
                          ("!disabled", "green4")],
           "fieldbackground": [("!disabled", "green3")],
           "foreground": [("focus", "OliveDrab1"),
                          ("!disabled", "OliveDrab2")]
       }
   }
})

combo = ttk.Combobox().pack()

root.mainloop()

theme_names()

Returns a list of all known themes.

theme_use(themename=None)

If themename is not given, returns the theme in use. Otherwise, sets the current theme to themename, refreshes all widgets and emits a <<ThemeChanged>> event.

Layouts

A layout can be just None, if it takes no options, or a dict of options specifying how to arrange the element. The layout mechanism uses a simplified version of the pack geometry manager: given an initial cavity, each element is allocated a parcel. Valid options/values are:

side: whichside

Specifies which side of the cavity to place the element; one of top, right, bottom or left. If omitted, the element occupies the entire cavity.

sticky: nswe

Specifies where the element is placed inside its allocated parcel.

unit: 0 or 1

If set to 1, causes the element and all of its descendants to be treated as a single element for the purposes of Widget.identify() et al. It’s used for things like scrollbar thumbs with grips.

children: [sublayout… ]

Specifies a list of elements to place inside the element. Each element is a tuple (or other sequence type) where the first item is the layout name, and the other is a Layout.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

Tk를 사용한 그래픽 사용자 인터페이스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

Tk를 사용한 그래픽 사용자 인터페이스 »

|

tkinter.tix — Extension widgets for Tk

Source code: Lib/tkinter/tix.py [https://github.com/python/cpython/tree/3.7/Lib/tkinter/tix.py]

버전 3.6부터 폐지: This Tk extension is unmaintained and should not be used in new code. Use tkinter.ttk instead.

The tkinter.tix (Tk Interface Extension) module provides an additional rich set of widgets. Although the standard Tk library has many useful widgets, they are far from complete. The tkinter.tix library provides most of the commonly needed widgets that are missing from standard Tk: HList, ComboBox, Control (a.k.a. SpinBox) and an assortment of scrollable widgets. tkinter.tix also includes many more widgets that are generally useful in a wide range of applications: NoteBook, FileEntry, PanedWindow, etc; there are more than 40 of them.

With all these new widgets, you can introduce new interaction techniques into applications, creating more useful and more intuitive user interfaces. You can design your application by choosing the most appropriate widgets to match the special needs of your application and users.

더 보기

Tix Homepage [http://tix.sourceforge.net/]

The home page for Tix. This includes links to additional documentation and downloads.

Tix Man Pages [http://tix.sourceforge.net/dist/current/man/]

On-line version of the man pages and reference material.

Tix Programming Guide [http://tix.sourceforge.net/dist/current/docs/tix-book/tix.book.html]

On-line version of the programmer’s reference material.

Tix Development Applications [http://tix.sourceforge.net/Tixapps/src/Tide.html]

Tix applications for development of Tix and Tkinter programs. Tide applications work under Tk or Tkinter, and include TixInspect, an inspector to remotely modify and debug Tix/Tk/Tkinter applications.

Using Tix

class tkinter.tix.Tk(screenName=None, baseName=None, className='Tix')

Toplevel widget of Tix which represents mostly the main window of an application. It has an associated Tcl interpreter.

Classes in the tkinter.tix module subclasses the classes in the tkinter. The former imports the latter, so to use tkinter.tix with Tkinter, all you need to do is to import one module. In general, you can just import tkinter.tix, and replace the toplevel call to tkinter.Tk with tix.Tk:

from tkinter import tix
from tkinter.constants import *
root = tix.Tk()

To use tkinter.tix, you must have the Tix widgets installed, usually alongside your installation of the Tk widgets. To test your installation, try the following:

from tkinter import tix
root = tix.Tk()
root.tk.eval('package require Tix')

Tix Widgets

Tix [http://tix.sourceforge.net/dist/current/man/html/TixCmd/TixIntro.htm] introduces over 40 widget classes to the tkinter repertoire.

Basic Widgets

class tkinter.tix.Balloon

A Balloon [http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixBalloon.htm] that pops up over a widget to provide help. When the user moves the cursor inside a widget to which a Balloon widget has been bound, a small pop-up window with a descriptive message will be shown on the screen.

class tkinter.tix.ButtonBox

The ButtonBox [http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixButtonBox.htm] widget creates a box of buttons, such as is commonly used for Ok Cancel.

class tkinter.tix.ComboBox

The ComboBox [http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixComboBox.htm] widget is similar to the combo box control in MS Windows. The user can select a choice by either typing in the entry subwidget or selecting from the listbox subwidget.

class tkinter.tix.Control

The Control [http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixControl.htm] widget is also known as the SpinBox widget. The user can adjust the value by pressing the two arrow buttons or by entering the value directly into the entry. The new value will be checked against the user-defined upper and lower limits.

class tkinter.tix.LabelEntry

The LabelEntry [http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixLabelEntry.htm] widget packages an entry widget and a label into one mega widget. It can be used to simplify the creation of “entry-form” type of interface.

class tkinter.tix.LabelFrame

The LabelFrame [http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixLabelFrame.htm] widget packages a frame widget and a label into one mega widget. To create widgets inside a LabelFrame widget, one creates the new widgets relative to the frame subwidget and manage them inside the frame subwidget.

class tkinter.tix.Meter

The Meter [http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixMeter.htm] widget can be used to show the progress of a background job which may take a long time to execute.

class tkinter.tix.OptionMenu

The OptionMenu [http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixOptionMenu.htm] creates a menu button of options.

class tkinter.tix.PopupMenu

The PopupMenu [http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixPopupMenu.htm] widget can be used as a replacement of the tk_popup command. The advantage of the Tix PopupMenu widget is it requires less application code to manipulate.

class tkinter.tix.Select

The Select [http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixSelect.htm] widget is a container of button subwidgets. It can be used to provide radio-box or check-box style of selection options for the user.

class tkinter.tix.StdButtonBox

The StdButtonBox [http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixStdButtonBox.htm] widget is a group of standard buttons for Motif-like dialog boxes.

File Selectors

class tkinter.tix.DirList

The DirList [http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixDirList.htm] widget displays a list view of a directory, its previous directories and its sub-directories. The user can choose one of the directories displayed in the list or change to another directory.

class tkinter.tix.DirTree

The DirTree [http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixDirTree.htm] widget displays a tree view of a directory, its previous directories and its sub-directories. The user can choose one of the directories displayed in the list or change to another directory.

class tkinter.tix.DirSelectDialog

The DirSelectDialog [http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixDirSelectDialog.htm] widget presents the directories in the file system in a dialog window. The user can use this dialog window to navigate through the file system to select the desired directory.

class tkinter.tix.DirSelectBox

The DirSelectBox is similar to the standard Motif(TM) directory-selection box. It is generally used for the user to choose a directory. DirSelectBox stores the directories mostly recently selected into a ComboBox widget so that they can be quickly selected again.

class tkinter.tix.ExFileSelectBox

The ExFileSelectBox [http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixExFileSelectBox.htm] widget is usually embedded in a tixExFileSelectDialog widget. It provides a convenient method for the user to select files. The style of the ExFileSelectBox widget is very similar to the standard file dialog on MS Windows 3.1.

class tkinter.tix.FileSelectBox

The FileSelectBox [http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixFileSelectBox.htm] is similar to the standard Motif(TM) file-selection box. It is generally used for the user to choose a file. FileSelectBox stores the files mostly recently selected into a ComboBox widget so that they can be quickly selected again.

class tkinter.tix.FileEntry

The FileEntry [http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixFileEntry.htm] widget can be used to input a filename. The user can type in the filename manually. Alternatively, the user can press the button widget that sits next to the entry, which will bring up a file selection dialog.

Hierarchical ListBox

class tkinter.tix.HList

The HList [http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixHList.htm] widget can be used to display any data that have a hierarchical structure, for example, file system directory trees. The list entries are indented and connected by branch lines according to their places in the hierarchy.

class tkinter.tix.CheckList

The CheckList [http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixCheckList.htm] widget displays a list of items to be selected by the user. CheckList acts similarly to the Tk checkbutton or radiobutton widgets, except it is capable of handling many more items than checkbuttons or radiobuttons.

class tkinter.tix.Tree

The Tree [http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixTree.htm] widget can be used to display hierarchical data in a tree form. The user can adjust the view of the tree by opening or closing parts of the tree.

Tabular ListBox

class tkinter.tix.TList

The TList [http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixTList.htm] widget can be used to display data in a tabular format. The list entries of a TList widget are similar to the entries in the Tk listbox widget. The main differences are (1) the TList widget can display the list entries in a two dimensional format and (2) you can use graphical images as well as multiple colors and fonts for the list entries.

Manager Widgets

class tkinter.tix.PanedWindow

The PanedWindow [http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixPanedWindow.htm] widget allows the user to interactively manipulate the sizes of several panes. The panes can be arranged either vertically or horizontally. The user changes the sizes of the panes by dragging the resize handle between two panes.

class tkinter.tix.ListNoteBook

The ListNoteBook [http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixListNoteBook.htm] widget is very similar to the TixNoteBook widget: it can be used to display many windows in a limited space using a notebook metaphor. The notebook is divided into a stack of pages (windows). At one time only one of these pages can be shown. The user can navigate through these pages by choosing the name of the desired page in the hlist subwidget.

class tkinter.tix.NoteBook

The NoteBook [http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixNoteBook.htm] widget can be used to display many windows in a limited space using a notebook metaphor. The notebook is divided into a stack of pages. At one time only one of these pages can be shown. The user can navigate through these pages by choosing the visual “tabs” at the top of the NoteBook widget.

Image Types

The tkinter.tix module adds:

pixmap [http://tix.sourceforge.net/dist/current/man/html/TixCmd/pixmap.htm] capabilities to all tkinter.tix and tkinter widgets to create color images from XPM files.

Compound [http://tix.sourceforge.net/dist/current/man/html/TixCmd/compound.htm] image types can be used to create images that consists of multiple horizontal lines; each line is composed of a series of items (texts, bitmaps, images or spaces) arranged from left to right. For example, a compound image can be used to display a bitmap and a text string simultaneously in a Tk Button widget.

Miscellaneous Widgets

class tkinter.tix.InputOnly

The InputOnly [http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixInputOnly.htm] widgets are to accept inputs from the user, which can be done with the bind command (Unix only).

Form Geometry Manager

In addition, tkinter.tix augments tkinter by providing:

class tkinter.tix.Form

The Form [http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixForm.htm] geometry manager based on attachment rules for all Tk widgets.

Tix Commands

class tkinter.tix.tixCommand

The tix commands [http://tix.sourceforge.net/dist/current/man/html/TixCmd/tix.htm] provide access to miscellaneous elements of Tix’s internal state and the Tix application context. Most of the information manipulated by these methods pertains to the application as a whole, or to a screen or display, rather than to a particular window.

To view the current settings, the common usage is:

from tkinter import tix
root = tix.Tk()
print(root.tix_configure())

tixCommand.tix_configure(cnf=None, **kw)

Query or modify the configuration options of the Tix application context. If no option is specified, returns a dictionary all of the available options. If option is specified with no value, then the method returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). If one or more option-value pairs are specified, then the method modifies the given option(s) to have the given value(s); in this case the method returns an empty string. Option may be any of the configuration options.

tixCommand.tix_cget(option)

Returns the current value of the configuration option given by option. Option may be any of the configuration options.

tixCommand.tix_getbitmap(name)

Locates a bitmap file of the name name.xpm or name in one of the bitmap directories (see the tix_addbitmapdir() method). By using tix_getbitmap(), you can avoid hard coding the pathnames of the bitmap files in your application. When successful, it returns the complete pathname of the bitmap file, prefixed with the character @. The returned value can be used to configure the bitmap option of the Tk and Tix widgets.

tixCommand.tix_addbitmapdir(directory)

Tix maintains a list of directories under which the tix_getimage() and tix_getbitmap() methods will search for image files. The standard bitmap directory is $TIX_LIBRARY/bitmaps. The tix_addbitmapdir() method adds directory into this list. By using this method, the image files of an applications can also be located using the tix_getimage() or tix_getbitmap() method.

tixCommand.tix_filedialog([dlgclass])

Returns the file selection dialog that may be shared among different calls from this application. This method will create a file selection dialog widget when it is called the first time. This dialog will be returned by all subsequent calls to tix_filedialog(). An optional dlgclass parameter can be passed as a string to specified what type of file selection dialog widget is desired. Possible options are tix, FileSelectDialog or tixExFileSelectDialog.

tixCommand.tix_getimage(self, name)

Locates an image file of the name name.xpm, name.xbm or name.ppm in one of the bitmap directories (see the tix_addbitmapdir() method above). If more than one file with the same name (but different extensions) exist, then the image type is chosen according to the depth of the X display: xbm images are chosen on monochrome displays and color images are chosen on color displays. By using tix_getimage(), you can avoid hard coding the pathnames of the image files in your application. When successful, this method returns the name of the newly created image, which can be used to configure the image option of the Tk and Tix widgets.

tixCommand.tix_option_get(name)

Gets the options maintained by the Tix scheme mechanism.

tixCommand.tix_resetoptions(newScheme, newFontSet[, newScmPrio])

Resets the scheme and fontset of the Tix application to newScheme and newFontSet, respectively. This affects only those widgets created after this call. Therefore, it is best to call the resetoptions method before the creation of any widgets in a Tix application.

The optional parameter newScmPrio can be given to reset the priority level of the Tk options set by the Tix schemes.

Because of the way Tk handles the X option database, after Tix has been has imported and inited, it is not possible to reset the color schemes and font sets using the tix_config() method. Instead, the tix_resetoptions() method must be used.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

Tk를 사용한 그래픽 사용자 인터페이스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

Tk를 사용한 그래픽 사용자 인터페이스 »

|

tkinter.scrolledtext — 스크롤 되는 Text 위젯

소스 코드: Lib/tkinter/scrolledtext.py [https://github.com/python/cpython/tree/3.7/Lib/tkinter/scrolledtext.py]

tkinter.scrolledtext 모듈은 “올바로” 동작하도록 구성된 수직 스크롤 막대가 있는 기본 텍스트 위젯을 구현하는 같은 이름의 클래스를 제공합니다. ScrolledText 클래스를 사용하면 텍스트 위젯과 스크롤 막대를 직접 설정하기보다 훨씬 쉽습니다. 생성자는 tkinter.Text 클래스의 생성자와 같습니다.

텍스트 위젯과 스크롤 막대는 Frame에 함께 팩 되며, Grid와 Pack 지오메트리 관리자의 메서드를 Frame 객체에서 얻습니다. 이렇게 함으로써, 가장 일반적인 지오메트리 관리 동작을 달성하는데 ScrolledText 위젯을 직접 사용할 수 있습니다.

더욱 구체적인 제어가 필요하면, 다음 어트리뷰트를 사용할 수 있습니다:

ScrolledText.frame

텍스트 및 스크롤 막대 위젯을 둘러싼 프레임.

ScrolledText.vbar

스크롤 막대 위젯.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

Tk를 사용한 그래픽 사용자 인터페이스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

Tk를 사용한 그래픽 사용자 인터페이스 »

|

IDLE

Source code: Lib/idlelib/ [https://github.com/python/cpython/tree/3.7/Lib/idlelib/]

IDLE is Python’s Integrated Development and Learning Environment.

IDLE has the following features:

coded in 100% pure Python, using the tkinter GUI toolkit

cross-platform: works mostly the same on Windows, Unix, and macOS

Python shell window (interactive interpreter) with colorizing of code input, output, and error messages

multi-window text editor with multiple undo, Python colorizing, smart indent, call tips, auto completion, and other features

search within any window, replace within editor windows, and search through multiple files (grep)

debugger with persistent breakpoints, stepping, and viewing of global and local namespaces

configuration, browsers, and other dialogs

Menus

IDLE has two main window types, the Shell window and the Editor window. It is possible to have multiple editor windows simultaneously. On Windows and Linux, each has its own top menu. Each menu documented below indicates which window type it is associated with.

Output windows, such as used for Edit => Find in Files, are a subtype of editor window. They currently have the same top menu but a different default title and context menu.

On macOS, there is one application menu. It dynamically changes according to the window currently selected. It has an IDLE menu, and some entries described below are moved around to conform to Apple guidelines.

File menu (Shell and Editor)

New File

Create a new file editing window.

Open…

Open an existing file with an Open dialog.

Recent Files

Open a list of recent files. Click one to open it.

Open Module…

Open an existing module (searches sys.path).

Class Browser

Show functions, classes, and methods in the current Editor file in a tree structure. In the shell, open a module first.

Path Browser

Show sys.path directories, modules, functions, classes and methods in a tree structure.

Save

Save the current window to the associated file, if there is one. Windows that have been changed since being opened or last saved have a * before and after the window title. If there is no associated file, do Save As instead.

Save As…

Save the current window with a Save As dialog. The file saved becomes the new associated file for the window.

Save Copy As…

Save the current window to different file without changing the associated file.

Print Window

Print the current window to the default printer.

Close

Close the current window (ask to save if unsaved).

Exit

Close all windows and quit IDLE (ask to save unsaved windows).

Edit menu (Shell and Editor)

Undo

Undo the last change to the current window. A maximum of 1000 changes may be undone.

Redo

Redo the last undone change to the current window.

Cut

Copy selection into the system-wide clipboard; then delete the selection.

Copy

Copy selection into the system-wide clipboard.

Paste

Insert contents of the system-wide clipboard into the current window.

The clipboard functions are also available in context menus.

Select All

Select the entire contents of the current window.

Find…

Open a search dialog with many options

Find Again

Repeat the last search, if there is one.

Find Selection

Search for the currently selected string, if there is one.

Find in Files…

Open a file search dialog. Put results in a new output window.

Replace…

Open a search-and-replace dialog.

Go to Line

Move the cursor to the beginning of the line requested and make that line visible. A request past the end of the file goes to the end. Clear any selection and update the line and column status.

Show Completions

Open a scrollable list allowing selection of keywords and attributes. See Completions in the Editing and navigation section below.

Expand Word

Expand a prefix you have typed to match a full word in the same window; repeat to get a different expansion.

Show call tip

After an unclosed parenthesis for a function, open a small window with function parameter hints. See Calltips in the Editing and navigation section below.

Show surrounding parens

Highlight the surrounding parenthesis.

Format menu (Editor window only)

Indent Region

Shift selected lines right by the indent width (default 4 spaces).

Dedent Region

Shift selected lines left by the indent width (default 4 spaces).

Comment Out Region

Insert ## in front of selected lines.

Uncomment Region

Remove leading # or ## from selected lines.

Tabify Region

Turn leading stretches of spaces into tabs. (Note: We recommend using 4 space blocks to indent Python code.)

Untabify Region

Turn all tabs into the correct number of spaces.

Toggle Tabs

Open a dialog to switch between indenting with spaces and tabs.

New Indent Width

Open a dialog to change indent width. The accepted default by the Python community is 4 spaces.

Format Paragraph

Reformat the current blank-line-delimited paragraph in comment block or multiline string or selected line in a string. All lines in the paragraph will be formatted to less than N columns, where N defaults to 72.

Strip trailing whitespace

Remove trailing space and other whitespace characters after the last non-whitespace character of a line by applying str.rstrip to each line, including lines within multiline strings. Except for Shell windows, remove extra newlines at the end of the file.

Run menu (Editor window only)

Run Module

Do Check Module. If no error, restart the shell to clean the environment, then execute the module. Output is displayed in the Shell window. Note that output requires use of print or write. When execution is complete, the Shell retains focus and displays a prompt. At this point, one may interactively explore the result of execution. This is similar to executing a file with python -i file at a command line.

Run… Customized

Same as Run Module, but run the module with customized settings. Command Line Arguments extend sys.argv as if passed on a command line. The module can be run in the Shell without restarting.

Check Module

Check the syntax of the module currently open in the Editor window. If the module has not been saved IDLE will either prompt the user to save or autosave, as selected in the General tab of the Idle Settings dialog. If there is a syntax error, the approximate location is indicated in the Editor window.

Python Shell

Open or wake up the Python Shell window.

Shell menu (Shell window only)

View Last Restart

Scroll the shell window to the last Shell restart.

Restart Shell

Restart the shell to clean the environment.

Previous History

Cycle through earlier commands in history which match the current entry.

Next History

Cycle through later commands in history which match the current entry.

Interrupt Execution

Stop a running program.

Debug menu (Shell window only)

Go to File/Line

Look on the current line. with the cursor, and the line above for a filename and line number. If found, open the file if not already open, and show the line. Use this to view source lines referenced in an exception traceback and lines found by Find in Files. Also available in the context menu of the Shell window and Output windows.

Debugger (toggle)

When activated, code entered in the Shell or run from an Editor will run under the debugger. In the Editor, breakpoints can be set with the context menu. This feature is still incomplete and somewhat experimental.

Stack Viewer

Show the stack traceback of the last exception in a tree widget, with access to locals and globals.

Auto-open Stack Viewer

Toggle automatically opening the stack viewer on an unhandled exception.

Options menu (Shell and Editor)

Configure IDLE

Open a configuration dialog and change preferences for the following: fonts, indentation, keybindings, text color themes, startup windows and size, additional help sources, and extensions. On macOS, open the configuration dialog by selecting Preferences in the application menu. For more details, see Setting preferences under Help and preferences.

Most configuration options apply to all windows or all future windows. The option items below only apply to the active window.

Show/Hide Code Context (Editor Window only)

Open a pane at the top of the edit window which shows the block context of the code which has scrolled above the top of the window. See Code Context in the Editing and Navigation section below.

Show/Hide Line Numbers (Editor Window only)

Open a column to the left of the edit window which shows the number of each line of text. The default is off, which may be changed in the preferences (see Setting preferences).

Zoom/Restore Height

Toggles the window between normal size and maximum height. The initial size defaults to 40 lines by 80 chars unless changed on the General tab of the Configure IDLE dialog. The maximum height for a screen is determined by momentarily maximizing a window the first time one is zoomed on the screen. Changing screen settings may invalidate the saved height. This toggle has no effect when a window is maximized.

Window menu (Shell and Editor)

Lists the names of all open windows; select one to bring it to the foreground (deiconifying it if necessary).

Help menu (Shell and Editor)

About IDLE

Display version, copyright, license, credits, and more.

IDLE Help

Display this IDLE document, detailing the menu options, basic editing and navigation, and other tips.

Python Docs

Access local Python documentation, if installed, or start a web browser and open docs.python.org showing the latest Python documentation.

Turtle Demo

Run the turtledemo module with example Python code and turtle drawings.

Additional help sources may be added here with the Configure IDLE dialog under the General tab. See the Help sources subsection below for more on Help menu choices.

Context Menus

Open a context menu by right-clicking in a window (Control-click on macOS). Context menus have the standard clipboard functions also on the Edit menu.

Cut

Copy selection into the system-wide clipboard; then delete the selection.

Copy

Copy selection into the system-wide clipboard.

Paste

Insert contents of the system-wide clipboard into the current window.

Editor windows also have breakpoint functions. Lines with a breakpoint set are specially marked. Breakpoints only have an effect when running under the debugger. Breakpoints for a file are saved in the user’s .idlerc directory.

Set Breakpoint

Set a breakpoint on the current line.

Clear Breakpoint

Clear the breakpoint on that line.

Shell and Output windows also have the following.

Go to file/line

Same as in Debug menu.

The Shell window also has an output squeezing facility explained in the Python Shell window subsection below.

Squeeze

If the cursor is over an output line, squeeze all the output between the code above and the prompt below down to a ‘Squeezed text’ label.

Editing and navigation

Editor windows

IDLE may open editor windows when it starts, depending on settings and how you start IDLE. Thereafter, use the File menu. There can be only one open editor window for a given file.

The title bar contains the name of the file, the full path, and the version of Python and IDLE running the window. The status bar contains the line number (‘Ln’) and column number (‘Col’). Line numbers start with 1; column numbers with 0.

IDLE assumes that files with a known .py* extension contain Python code and that other files do not. Run Python code with the Run menu.

Key bindings

In this section, ‘C’ refers to the Control key on Windows and Unix and the Command key on macOS.

Backspace deletes to the left; Del deletes to the right

C-Backspace delete word left; C-Del delete word to the right

Arrow keys and Page Up/Page Down to move around

C-LeftArrow and C-RightArrow moves by words

Home/End go to begin/end of line

C-Home/C-End go to begin/end of file

Some useful Emacs bindings are inherited from Tcl/Tk:

C-a beginning of line

C-e end of line

C-k kill line (but doesn’t put it in clipboard)

C-l center window around the insertion point

C-b go backward one character without deleting (usually you can also use the cursor key for this)

C-f go forward one character without deleting (usually you can also use the cursor key for this)

C-p go up one line (usually you can also use the cursor key for this)

C-d delete next character

Standard keybindings (like C-c to copy and C-v to paste) may work. Keybindings are selected in the Configure IDLE dialog.

Automatic indentation

After a block-opening statement, the next line is indented by 4 spaces (in the Python Shell window by one tab). After certain keywords (break, return etc.) the next line is dedented. In leading indentation, Backspace deletes up to 4 spaces if they are there. Tab inserts spaces (in the Python Shell window one tab), number depends on Indent width. Currently, tabs are restricted to four spaces due to Tcl/Tk limitations.

See also the indent/dedent region commands on the Format menu.

Completions

Completions are supplied for functions, classes, and attributes of classes, both built-in and user-defined. Completions are also provided for filenames.

The AutoCompleteWindow (ACW) will open after a predefined delay (default is two seconds) after a ‘.’ or (in a string) an os.sep is typed. If after one of those characters (plus zero or more other characters) a tab is typed the ACW will open immediately if a possible continuation is found.

If there is only one possible completion for the characters entered, a Tab will supply that completion without opening the ACW.

‘Show Completions’ will force open a completions window, by default the C-space will open a completions window. In an empty string, this will contain the files in the current directory. On a blank line, it will contain the built-in and user-defined functions and classes in the current namespaces, plus any modules imported. If some characters have been entered, the ACW will attempt to be more specific.

If a string of characters is typed, the ACW selection will jump to the entry most closely matching those characters. Entering a tab will cause the longest non-ambiguous match to be entered in the Editor window or Shell. Two tab in a row will supply the current ACW selection, as will return or a double click. Cursor keys, Page Up/Down, mouse selection, and the scroll wheel all operate on the ACW.

“Hidden” attributes can be accessed by typing the beginning of hidden name after a ‘.’, e.g. ‘_’. This allows access to modules with __all__ set, or to class-private attributes.

Completions and the ‘Expand Word’ facility can save a lot of typing!

Completions are currently limited to those in the namespaces. Names in an Editor window which are not via __main__ and sys.modules will not be found. Run the module once with your imports to correct this situation. Note that IDLE itself places quite a few modules in sys.modules, so much can be found by default, e.g. the re module.

If you don’t like the ACW popping up unbidden, simply make the delay longer or disable the extension.

Calltips

A calltip is shown when one types ( after the name of an accessible function. A name expression may include dots and subscripts. A calltip remains until it is clicked, the cursor is moved out of the argument area, or ) is typed. When the cursor is in the argument part of a definition, the menu or shortcut display a calltip.

A calltip consists of the function signature and the first line of the docstring. For builtins without an accessible signature, the calltip consists of all lines up the fifth line or the first blank line. These details may change.

The set of accessible functions depends on what modules have been imported into the user process, including those imported by Idle itself, and what definitions have been run, all since the last restart.

For example, restart the Shell and enter itertools.count(. A calltip appears because Idle imports itertools into the user process for its own use. (This could change.) Enter turtle.write( and nothing appears. Idle does not import turtle. The menu or shortcut do nothing either. Enter import turtle and then turtle.write( will work.

In an editor, import statements have no effect until one runs the file. One might want to run a file after writing the import statements at the top, or immediately run an existing file before editing.

Code Context

Within an editor window containing Python code, code context can be toggled in order to show or hide a pane at the top of the window. When shown, this pane freezes the opening lines for block code, such as those beginning with class, def, or if keywords, that would have otherwise scrolled out of view. The size of the pane will be expanded and contracted as needed to show the all current levels of context, up to the maximum number of lines defined in the Configure IDLE dialog (which defaults to 15). If there are no current context lines and the feature is toggled on, a single blank line will display. Clicking on a line in the context pane will move that line to the top of the editor.

The text and background colors for the context pane can be configured under the Highlights tab in the Configure IDLE dialog.

Python Shell window

With IDLE’s Shell, one enters, edits, and recalls complete statements. Most consoles and terminals only work with a single physical line at a time.

When one pastes code into Shell, it is not compiled and possibly executed until one hits Return. One may edit pasted code first. If one pastes more that one statement into Shell, the result will be a SyntaxError when multiple statements are compiled as if they were one.

The editing features described in previous subsections work when entering code interactively. IDLE’s Shell window also responds to the following keys.

C-c interrupts executing command

C-d sends end-of-file; closes window if typed at a >>> prompt

Alt-/ (Expand word) is also useful to reduce typing

Command history

Alt-p retrieves previous command matching what you have typed. On macOS use C-p.

Alt-n retrieves next. On macOS use C-n.

Return while on any previous command retrieves that command

Text colors

Idle defaults to black on white text, but colors text with special meanings. For the shell, these are shell output, shell error, user output, and user error. For Python code, at the shell prompt or in an editor, these are keywords, builtin class and function names, names following class and def, strings, and comments. For any text window, these are the cursor (when present), found text (when possible), and selected text.

Text coloring is done in the background, so uncolorized text is occasionally visible. To change the color scheme, use the Configure IDLE dialog Highlighting tab. The marking of debugger breakpoint lines in the editor and text in popups and dialogs is not user-configurable.

Startup and code execution

Upon startup with the -s option, IDLE will execute the file referenced by the environment variables IDLESTARTUP or PYTHONSTARTUP. IDLE first checks for IDLESTARTUP; if IDLESTARTUP is present the file referenced is run. If IDLESTARTUP is not present, IDLE checks for PYTHONSTARTUP. Files referenced by these environment variables are convenient places to store functions that are used frequently from the IDLE shell, or for executing import statements to import common modules.

In addition, Tk also loads a startup file if it is present. Note that the Tk file is loaded unconditionally. This additional file is .Idle.py and is looked for in the user’s home directory. Statements in this file will be executed in the Tk namespace, so this file is not useful for importing functions to be used from IDLE’s Python shell.

Command line usage

idle.py [-c command] [-d] [-e] [-h] [-i] [-r file] [-s] [-t title] [-] [arg] ...

-c command  run command in the shell window
-d          enable debugger and open shell window
-e          open editor window
-h          print help message with legal combinations and exit
-i          open shell window
-r file     run file in shell window
-s          run $IDLESTARTUP or $PYTHONSTARTUP first, in shell window
-t title    set title of shell window
-           run stdin in shell (- must be last option before args)

If there are arguments:

If -, -c, or r is used, all arguments are placed in sys.argv[1:...] and sys.argv[0] is set to '', '-c', or '-r'. No editor window is opened, even if that is the default set in the Options dialog.

Otherwise, arguments are files opened for editing and sys.argv reflects the arguments passed to IDLE itself.

Startup failure

IDLE uses a socket to communicate between the IDLE GUI process and the user code execution process. A connection must be established whenever the Shell starts or restarts. (The latter is indicated by a divider line that says ‘RESTART’). If the user process fails to connect to the GUI process, it displays a Tk error box with a ‘cannot connect’ message that directs the user here. It then exits.

A common cause of failure is a user-written file with the same name as a standard library module, such as random.py and tkinter.py. When such a file is located in the same directory as a file that is about to be run, IDLE cannot import the stdlib file. The current fix is to rename the user file.

Though less common than in the past, an antivirus or firewall program may stop the connection. If the program cannot be taught to allow the connection, then it must be turned off for IDLE to work. It is safe to allow this internal connection because no data is visible on external ports. A similar problem is a network mis-configuration that blocks connections.

Python installation issues occasionally stop IDLE: multiple versions can clash, or a single installation might need admin access. If one undo the clash, or cannot or does not want to run as admin, it might be easiest to completely remove Python and start over.

A zombie pythonw.exe process could be a problem. On Windows, use Task Manager to check for one and stop it if there is. Sometimes a restart initiated by a program crash or Keyboard Interrupt (control-C) may fail to connect. Dismissing the error box or using Restart Shell on the Shell menu may fix a temporary problem.

When IDLE first starts, it attempts to read user configuration files in ~/.idlerc/ (~ is one’s home directory). If there is a problem, an error message should be displayed. Leaving aside random disk glitches, this can be prevented by never editing the files by hand. Instead, use the configuration dialog, under Options. Once there is an error in a user configuration file, the best solution may be to delete it and start over with the settings dialog.

If IDLE quits with no message, and it was not started from a console, try starting it from a console or terminal (python -m idlelib) and see if this results in an error message.

Running user code

With rare exceptions, the result of executing Python code with IDLE is intended to be the same as executing the same code by the default method, directly with Python in a text-mode system console or terminal window. However, the different interface and operation occasionally affect visible results. For instance, sys.modules starts with more entries, and threading.activeCount() returns 2 instead of 1.

By default, IDLE runs user code in a separate OS process rather than in the user interface process that runs the shell and editor. In the execution process, it replaces sys.stdin, sys.stdout, and sys.stderr with objects that get input from and send output to the Shell window. The original values stored in sys.__stdin__, sys.__stdout__, and sys.__stderr__ are not touched, but may be None.

When Shell has the focus, it controls the keyboard and screen. This is normally transparent, but functions that directly access the keyboard and screen will not work. These include system-specific functions that determine whether a key has been pressed and if so, which.

IDLE’s standard stream replacements are not inherited by subprocesses created in the execution process, whether directly by user code or by modules such as multiprocessing. If such subprocess use input from sys.stdin or print or write to sys.stdout or sys.stderr, IDLE should be started in a command line window. The secondary subprocess will then be attached to that window for input and output.

The IDLE code running in the execution process adds frames to the call stack that would not be there otherwise. IDLE wraps sys.getrecursionlimit and sys.setrecursionlimit to reduce the effect of the additional stack frames.

If sys is reset by user code, such as with importlib.reload(sys), IDLE’s changes are lost and input from the keyboard and output to the screen will not work correctly.

When user code raises SystemExit either directly or by calling sys.exit, IDLE returns to a Shell prompt instead of exiting.

User output in Shell

When a program outputs text, the result is determined by the corresponding output device. When IDLE executes user code, sys.stdout and sys.stderr are connected to the display area of IDLE’s Shell. Some of its features are inherited from the underlying Tk Text widget. Others are programmed additions. Where it matters, Shell is designed for development rather than production runs.

For instance, Shell never throws away output. A program that sends unlimited output to Shell will eventually fill memory, resulting in a memory error. In contrast, some system text windows only keep the last n lines of output. A Windows console, for instance, keeps a user-settable 1 to 9999 lines, with 300 the default.

A Tk Text widget, and hence IDLE’s Shell, displays characters (codepoints) in the BMP (Basic Multilingual Plane) subset of Unicode. Which characters are displayed with a proper glyph and which with a replacement box depends on the operating system and installed fonts. Tab characters cause the following text to begin after the next tab stop. (They occur every 8 ‘characters’). Newline characters cause following text to appear on a new line. Other control characters are ignored or displayed as a space, box, or something else, depending on the operating system and font. (Moving the text cursor through such output with arrow keys may exhibit some surprising spacing behavior.)

>>> s = 'a\tb\a<\x02><\r>\bc\nd'  # Enter 22 chars.
>>> len(s)
14
>>> s  # Display repr(s)
'a\tb\x07<\x02><\r>\x08c\nd'
>>> print(s, end='')  # Display s as is.
# Result varies by OS and font.  Try it.

The repr function is used for interactive echo of expression values. It returns an altered version of the input string in which control codes, some BMP codepoints, and all non-BMP codepoints are replaced with escape codes. As demonstrated above, it allows one to identify the characters in a string, regardless of how they are displayed.

Normal and error output are generally kept separate (on separate lines) from code input and each other. They each get different highlight colors.

For SyntaxError tracebacks, the normal ‘^’ marking where the error was detected is replaced by coloring the text with an error highlight. When code run from a file causes other exceptions, one may right click on a traceback line to jump to the corresponding line in an IDLE editor. The file will be opened if necessary.

Shell has a special facility for squeezing output lines down to a ‘Squeezed text’ label. This is done automatically for output over N lines (N = 50 by default). N can be changed in the PyShell section of the General page of the Settings dialog. Output with fewer lines can be squeezed by right clicking on the output. This can be useful lines long enough to slow down scrolling.

Squeezed output is expanded in place by double-clicking the label. It can also be sent to the clipboard or a separate view window by right-clicking the label.

Developing tkinter applications

IDLE is intentionally different from standard Python in order to facilitate development of tkinter programs. Enter import tkinter as tk; root = tk.Tk() in standard Python and nothing appears. Enter the same in IDLE and a tk window appears. In standard Python, one must also enter root.update() to see the window. IDLE does the equivalent in the background, about 20 times a second, which is about every 50 milliseconds. Next enter b = tk.Button(root, text='button'); b.pack(). Again, nothing visibly changes in standard Python until one enters root.update().

Most tkinter programs run root.mainloop(), which usually does not return until the tk app is destroyed. If the program is run with python -i or from an IDLE editor, a >>> shell prompt does not appear until mainloop() returns, at which time there is nothing left to interact with.

When running a tkinter program from an IDLE editor, one can comment out the mainloop call. One then gets a shell prompt immediately and can interact with the live application. One just has to remember to re-enable the mainloop call when running in standard Python.

Running without a subprocess

By default, IDLE executes user code in a separate subprocess via a socket, which uses the internal loopback interface. This connection is not externally visible and no data is sent to or received from the Internet. If firewall software complains anyway, you can ignore it.

If the attempt to make the socket connection fails, Idle will notify you. Such failures are sometimes transient, but if persistent, the problem may be either a firewall blocking the connection or misconfiguration of a particular system. Until the problem is fixed, one can run Idle with the -n command line switch.

If IDLE is started with the -n command line switch it will run in a single process and will not create the subprocess which runs the RPC Python execution server. This can be useful if Python cannot create the subprocess or the RPC socket interface on your platform. However, in this mode user code is not isolated from IDLE itself. Also, the environment is not restarted when Run/Run Module (F5) is selected. If your code has been modified, you must reload() the affected modules and re-import any specific items (e.g. from foo import baz) if the changes are to take effect. For these reasons, it is preferable to run IDLE with the default subprocess if at all possible.

버전 3.4부터 폐지.

Help and preferences

Help sources

Help menu entry “IDLE Help” displays a formatted html version of the IDLE chapter of the Library Reference. The result, in a read-only tkinter text window, is close to what one sees in a web browser. Navigate through the text with a mousewheel, the scrollbar, or up and down arrow keys held down. Or click the TOC (Table of Contents) button and select a section header in the opened box.

Help menu entry “Python Docs” opens the extensive sources of help, including tutorials, available at docs.python.org/x.y, where ‘x.y’ is the currently running Python version. If your system has an off-line copy of the docs (this may be an installation option), that will be opened instead.

Selected URLs can be added or removed from the help menu at any time using the General tab of the Configure IDLE dialog.

Setting preferences

The font preferences, highlighting, keys, and general preferences can be changed via Configure IDLE on the Option menu. Non-default user settings are saved in a .idlerc directory in the user’s home directory. Problems caused by bad user configuration files are solved by editing or deleting one or more of the files in .idlerc.

On the Font tab, see the text sample for the effect of font face and size on multiple characters in multiple languages. Edit the sample to add other characters of personal interest. Use the sample to select monospaced fonts. If particular characters have problems in Shell or an editor, add them to the top of the sample and try changing first size and then font.

On the Highlights and Keys tab, select a built-in or custom color theme and key set. To use a newer built-in color theme or key set with older IDLEs, save it as a new custom theme or key set and it well be accessible to older IDLEs.

IDLE on macOS

Under System Preferences: Dock, one can set “Prefer tabs when opening documents” to “Always”. This setting is not compatible with the tk/tkinter GUI framework used by IDLE, and it breaks a few IDLE features.

Extensions

IDLE contains an extension facility. Preferences for extensions can be changed with the Extensions tab of the preferences dialog. See the beginning of config-extensions.def in the idlelib directory for further information. The only current default extension is zzdummy, an example also used for testing.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

Tk를 사용한 그래픽 사용자 인터페이스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

Tk를 사용한 그래픽 사용자 인터페이스 »

|

기타 그래픽 사용자 인터페이스 패키지

주요 교차 플랫폼(윈도우, 맥 OS X, 유닉스 계열) GUI 도구상자를 파이썬에서 사용할 수 있습니다:

더 보기

PyGObject [https://wiki.gnome.org/Projects/PyGObject]

PyGObject는 GObject [https://developer.gnome.org/gobject/stable/]를 사용하여 C 라이브러리에 대한 인트로스펙션 바인딩을 제공합니다. 이 라이브러리 중 하나가 GTK+ 3 [https://www.gtk.org/] 위젯 집합입니다. GTK+에는 Tkinter가 제공하는 것보다 더 많은 위젯이 제공됩니다. 온라인 파이썬 GTK+ 3 자습서 [https://python-gtk-3-tutorial.readthedocs.io/]가 있습니다.

PyGTK [http://www.pygtk.org/]

PyGTK는 라이브러리의 이전 버전인 GTK+ 2에 대한 바인딩을 제공합니다. 이것은 C보다 약간 높은 수준의 객체 지향 인터페이스를 제공합니다. GNOME [https://www.gnome.org/] 바인딩도 있습니다. 온라인 자습서 [http://www.pygtk.org/pygtk2tutorial/index.html]가 있습니다.

PyQt [https://riverbankcomputing.com/software/pyqt/intro]

PyQt는 Qt 도구상자에 대한 sip-래핑 된 바인딩입니다. Qt는 유닉스, 윈도우 및 맥 OS X에서 사용할 수 있는 광범위한 C++ GUI 응용 프로그램 개발 프레임워크입니다. sip는 파이썬 클래스로 C++ 라이브러리에 대한 바인딩을 생성하는 도구이며, 파이썬 용으로 특별히 설계되었습니다.

PySide2 [https://doc.qt.io/qtforpython/]

Also known as the Qt for Python project, PySide2 is a newer binding to the Qt toolkit. It is provided by The Qt Company and aims to provide a complete port of PySide to Qt 5. Compared to PyQt, its licensing scheme is friendlier to non-open source applications.

wxPython [https://www.wxpython.org]

wxPython은 인기 있는 wxWidgets [https://www.wxwidgets.org/] (이전 wxWindows) C++ 도구상자를 기반으로 작성된 파이썬 용 교차 플랫폼 GUI 도구상자입니다. 윈도우, 맥 OS X 및 유닉스 시스템의 응용 프로그램에 대해 고유한 모양과 느낌을 제공하는데, 가능한 각 플랫폼 고유의 위젯 집합(유닉스 계열 시스템에서는 GTK+)을 사용합니다. 광범위한 위젯 외에도 wxPython은 온라인 설명서 및 문맥에 맞는 도움말, 인쇄, HTML 보기, 저수준 장치 컨텍스트 그리기, 끌어서 놓기, 시스템 클립보드 액세스, XML 기반 자원 형식 등과 이밖에도 많은 것들을 위한 클래스를 제공하는데, 사용자 기여 모듈의 라이브러리는 계속 늘어나고 있습니다.

PyGTK, PyQt, PySide2, and wxPython, all have a modern look and feel and more widgets than Tkinter. In addition, there are many other GUI toolkits for Python, both cross-platform, and platform-specific. See the GUI Programming [https://wiki.python.org/moin/GuiProgramming] page in the Python Wiki for a much more complete list, and also for links to documents where the different GUI toolkits are compared.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

Tk를 사용한 그래픽 사용자 인터페이스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

|

개발 도구

이 장에서 설명하는 모듈은 소프트웨어를 작성하는 것을 돕습니다. 예를 들어, pydoc 모듈은 모듈을 가져와서 모듈의 내용을 기반으로 설명서를 만듭니다. doctest 와 unittest 모듈에는 예상 출력이 만들어지는지 코드를 자동으로 실행하고 확인하는 단위 테스트를 작성하기 위한 프레임워크가 포함되어 있습니다. 2to3는 파이썬 2.x 소스 코드를 유효한 파이썬 3.x 코드로 변환할 수 있습니다.

이 장에서 설명하는 모듈 목록은 다음과 같습니다:

typing — Support for type hints

Type aliases

NewType

Callable

Generics

User-defined generic types

The Any type

Classes, functions, and decorators

pydoc — 설명서 생성과 온라인 도움말 시스템

doctest — 대화형 파이썬 예제 테스트

간단한 사용법: 독스트링에 있는 예제 확인하기

간단한 사용법: 텍스트 파일에 있는 예제 확인하기

작동 방법

어떤 독스트링을 검사합니까?

독스트링 예제는 어떻게 인식됩니까?

실행 컨텍스트란 무엇입니까?

예외는 어떻게 됩니까?

옵션 플래그

지시자

경고

기본 API

Unittest API

고급 API

DocTest 객체

Example 객체

DocTestFinder 객체

DocTestParser 객체

DocTestRunner 객체

OutputChecker 객체

디버깅

맺음말

unittest — 단위 테스트 프레임워크

기본 예시

명령행 인터페이스

명령행 옵션

테스트 탐색(Discovery)

테스트 코드 구조 잡기

이전의 테스트 코드를 다시 사용하기

테스트 건너뛰기와 예상된 실패

부분 테스트(subtest)를 사용하여 테스트 반복 구별 짖기

클래스와 함수

테스트 케이스

폐지된 에일리어스

테스트 분류

테스트를 로드하고 실행하기

load_tests 프로토콜

클래스와 모듈 픽스쳐

setUpClass 와 tearDownClass

setUpModule 과 tearDownModule

시그널 처리하기

unittest.mock — mock object library

Quick Guide

The Mock Class

Calling

Deleting Attributes

Mock names and the name attribute

Attaching Mocks as Attributes

The patchers

patch

patch.object

patch.dict

patch.multiple

patch methods: start and stop

patch builtins

TEST_PREFIX

Nesting Patch Decorators

Where to patch

Patching Descriptors and Proxy Objects

MagicMock and magic method support

Mocking Magic Methods

Magic Mock

Helpers

sentinel

DEFAULT

call

create_autospec

ANY

FILTER_DIR

mock_open

Autospeccing

Sealing mocks

unittest.mock — getting started

Using Mock

Mock Patching Methods

Mock for Method Calls on an Object

Mocking Classes

Naming your mocks

Tracking all Calls

Setting Return Values and Attributes

Raising exceptions with mocks

Side effect functions and iterables

Creating a Mock from an Existing Object

Patch Decorators

Further Examples

Mocking chained calls

Partial mocking

Mocking a Generator Method

Applying the same patch to every test method

Mocking Unbound Methods

Checking multiple calls with mock

Coping with mutable arguments

Nesting Patches

Mocking a dictionary with MagicMock

Mock subclasses and their attributes

Mocking imports with patch.dict

Tracking order of calls and less verbose call assertions

More complex argument matching

2to3 - 파이썬 2에서 파이썬 3으로 자동 코드 변환

2to3 사용법

변환자 목록

lib2to3 - 2to3 라이브러리

test — Regression tests package for Python

Writing Unit Tests for the test package

Running tests using the command-line interface

test.support — Utilities for the Python test suite

test.support.script_helper — Utilities for the Python execution tests

파이썬 개발 모드도 보십시오: -X dev 옵션과 PYTHONDEVMODE 환경 변수.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

개발 도구 »

|

typing — Support for type hints

버전 3.5에 추가.

Source code: Lib/typing.py [https://github.com/python/cpython/tree/3.7/Lib/typing.py]

참고

The Python runtime does not enforce function and variable type annotations. They can be used by third party tools such as type checkers, IDEs, linters, etc.

This module supports type hints as specified by PEP 484 [https://www.python.org/dev/peps/pep-0484] and PEP 526 [https://www.python.org/dev/peps/pep-0526]. The most fundamental support consists of the types Any, Union, Tuple, Callable, TypeVar, and Generic. For full specification please see PEP 484 [https://www.python.org/dev/peps/pep-0484]. For a simplified introduction to type hints see PEP 483 [https://www.python.org/dev/peps/pep-0483].

The function below takes and returns a string and is annotated as follows:

def greeting(name: str) -> str:
    return 'Hello ' + name

In the function greeting, the argument name is expected to be of type str and the return type str. Subtypes are accepted as arguments.

Type aliases

A type alias is defined by assigning the type to the alias. In this example, Vector and List[float] will be treated as interchangeable synonyms:

from typing import List
Vector = List[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])

Type aliases are useful for simplifying complex type signatures. For example:

from typing import Dict, Tuple, Sequence

ConnectionOptions = Dict[str, str]
Address = Tuple[str, int]
Server = Tuple[Address, ConnectionOptions]

def broadcast_message(message: str, servers: Sequence[Server]) -> None:
    ...

# The static type checker will treat the previous type signature as
# being exactly equivalent to this one.
def broadcast_message(
        message: str,
        servers: Sequence[Tuple[Tuple[str, int], Dict[str, str]]]) -> None:
    ...

Note that None as a type hint is a special case and is replaced by type(None).

NewType

Use the NewType() helper function to create distinct types:

from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)

The static type checker will treat the new type as if it were a subclass of the original type. This is useful in helping catch logical errors:

def get_user_name(user_id: UserId) -> str:
    ...

# typechecks
user_a = get_user_name(UserId(42351))

# does not typecheck; an int is not a UserId
user_b = get_user_name(-1)

You may still perform all int operations on a variable of type UserId, but the result will always be of type int. This lets you pass in a UserId wherever an int might be expected, but will prevent you from accidentally creating a UserId in an invalid way:

# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)

Note that these checks are enforced only by the static type checker. At runtime the statement Derived = NewType('Derived', Base) will make Derived a function that immediately returns whatever parameter you pass it. That means the expression Derived(some_value) does not create a new class or introduce any overhead beyond that of a regular function call.

More precisely, the expression some_value is Derived(some_value) is always true at runtime.

This also means that it is not possible to create a subtype of Derived since it is an identity function at runtime, not an actual type:

from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not typecheck
class AdminUserId(UserId): pass

However, it is possible to create a NewType() based on a ‘derived’ NewType:

from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)

and typechecking for ProUserId will work as expected.

See PEP 484 [https://www.python.org/dev/peps/pep-0484] for more details.

참고

Recall that the use of a type alias declares two types to be equivalent to one another. Doing Alias = Original will make the static type checker treat Alias as being exactly equivalent to Original in all cases. This is useful when you want to simplify complex type signatures.

In contrast, NewType declares one type to be a subtype of another. Doing Derived = NewType('Derived', Original) will make the static type checker treat Derived as a subclass of Original, which means a value of type Original cannot be used in places where a value of type Derived is expected. This is useful when you want to prevent logic errors with minimal runtime cost.

버전 3.5.2에 추가.

Callable

Frameworks expecting callback functions of specific signatures might be type hinted using Callable[[Arg1Type, Arg2Type], ReturnType].

For example:

from typing import Callable

def feeder(get_next_item: Callable[[], str]) -> None:
    # Body

def async_query(on_success: Callable[[int], None],
                on_error: Callable[[int, Exception], None]) -> None:
    # Body

It is possible to declare the return type of a callable without specifying the call signature by substituting a literal ellipsis for the list of arguments in the type hint: Callable[..., ReturnType].

Generics

Since type information about objects kept in containers cannot be statically inferred in a generic way, abstract base classes have been extended to support subscription to denote expected types for container elements.

from typing import Mapping, Sequence

def notify_by_email(employees: Sequence[Employee],
                    overrides: Mapping[str, str]) -> None: ...

Generics can be parameterized by using a new factory available in typing called TypeVar.

from typing import Sequence, TypeVar

T = TypeVar('T')      # Declare type variable

def first(l: Sequence[T]) -> T:   # Generic function
    return l[0]

User-defined generic types

A user-defined class can be defined as a generic class.

from typing import TypeVar, Generic
from logging import Logger

T = TypeVar('T')

class LoggedVar(Generic[T]):
    def __init__(self, value: T, name: str, logger: Logger) -> None:
        self.name = name
        self.logger = logger
        self.value = value

    def set(self, new: T) -> None:
        self.log('Set ' + repr(self.value))
        self.value = new

    def get(self) -> T:
        self.log('Get ' + repr(self.value))
        return self.value

    def log(self, message: str) -> None:
        self.logger.info('%s: %s', self.name, message)

Generic[T] as a base class defines that the class LoggedVar takes a single type parameter T . This also makes T valid as a type within the class body.

The Generic base class defines __class_getitem__() so that LoggedVar[t] is valid as a type:

from typing import Iterable

def zero_all_vars(vars: Iterable[LoggedVar[int]]) -> None:
    for var in vars:
        var.set(0)

A generic type can have any number of type variables, and type variables may be constrained:

from typing import TypeVar, Generic
...

T = TypeVar('T')
S = TypeVar('S', int, str)

class StrangePair(Generic[T, S]):
    ...

Each type variable argument to Generic must be distinct. This is thus invalid:

from typing import TypeVar, Generic
...

T = TypeVar('T')

class Pair(Generic[T, T]):   # INVALID
    ...

You can use multiple inheritance with Generic:

from typing import TypeVar, Generic, Sized

T = TypeVar('T')

class LinkedList(Sized, Generic[T]):
    ...

When inheriting from generic classes, some type variables could be fixed:

from typing import TypeVar, Mapping

T = TypeVar('T')

class MyDict(Mapping[str, T]):
    ...

In this case MyDict has a single parameter, T.

Using a generic class without specifying type parameters assumes Any for each position. In the following example, MyIterable is not generic but implicitly inherits from Iterable[Any]:

from typing import Iterable

class MyIterable(Iterable): # Same as Iterable[Any]

User defined generic type aliases are also supported. Examples:

from typing import TypeVar, Iterable, Tuple, Union
S = TypeVar('S')
Response = Union[Iterable[S], int]

# Return type here is same as Union[Iterable[str], int]
def response(query: str) -> Response[str]:
    ...

T = TypeVar('T', int, float, complex)
Vec = Iterable[Tuple[T, T]]

def inproduct(v: Vec[T]) -> T: # Same as Iterable[Tuple[T, T]]
    return sum(x*y for x, y in v)

버전 3.7에서 변경: Generic no longer has a custom metaclass.

A user-defined generic class can have ABCs as base classes without a metaclass conflict. Generic metaclasses are not supported. The outcome of parameterizing generics is cached, and most types in the typing module are hashable and comparable for equality.

The Any type

A special kind of type is Any. A static type checker will treat every type as being compatible with Any and Any as being compatible with every type.

This means that it is possible to perform any operation or method call on a value of type on Any and assign it to any variable:

from typing import Any

a = None    # type: Any
a = []      # OK
a = 2       # OK

s = ''      # type: str
s = a       # OK

def foo(item: Any) -> int:
    # Typechecks; 'item' could be any type,
    # and that type might have a 'bar' method
    item.bar()
    ...

Notice that no typechecking is performed when assigning a value of type Any to a more precise type. For example, the static type checker did not report an error when assigning a to s even though s was declared to be of type str and receives an int value at runtime!

Furthermore, all functions without a return type or parameter types will implicitly default to using Any:

def legacy_parser(text):
    ...
    return data

# A static type checker will treat the above
# as having the same signature as:
def legacy_parser(text: Any) -> Any:
    ...
    return data

This behavior allows Any to be used as an escape hatch when you need to mix dynamically and statically typed code.

Contrast the behavior of Any with the behavior of object. Similar to Any, every type is a subtype of object. However, unlike Any, the reverse is not true: object is not a subtype of every other type.

That means when the type of a value is object, a type checker will reject almost all operations on it, and assigning it to a variable (or using it as a return value) of a more specialized type is a type error. For example:

def hash_a(item: object) -> int:
    # Fails; an object does not have a 'magic' method.
    item.magic()
    ...

def hash_b(item: Any) -> int:
    # Typechecks
    item.magic()
    ...

# Typechecks, since ints and strs are subclasses of object
hash_a(42)
hash_a("foo")

# Typechecks, since Any is compatible with all types
hash_b(42)
hash_b("foo")

Use object to indicate that a value could be any type in a typesafe manner. Use Any to indicate that a value is dynamically typed.

Classes, functions, and decorators

The module defines the following classes, functions and decorators:

class typing.TypeVar

Type variable.

Usage:

T = TypeVar('T')  # Can be anything
A = TypeVar('A', str, bytes)  # Must be str or bytes

Type variables exist primarily for the benefit of static type checkers. They serve as the parameters for generic types as well as for generic function definitions. See class Generic for more information on generic types. Generic functions work as follows:

def repeat(x: T, n: int) -> Sequence[T]:
    """Return a list containing n references to x."""
    return [x]*n

def longest(x: A, y: A) -> A:
    """Return the longest of two strings."""
    return x if len(x) >= len(y) else y

The latter example’s signature is essentially the overloading of (str, str) -> str and (bytes, bytes) -> bytes. Also note that if the arguments are instances of some subclass of str, the return type is still plain str.

At runtime, isinstance(x, T) will raise TypeError. In general, isinstance() and issubclass() should not be used with types.

Type variables may be marked covariant or contravariant by passing covariant=True or contravariant=True. See PEP 484 [https://www.python.org/dev/peps/pep-0484] for more details. By default type variables are invariant. Alternatively, a type variable may specify an upper bound using bound=<type>. This means that an actual type substituted (explicitly or implicitly) for the type variable must be a subclass of the boundary type, see PEP 484 [https://www.python.org/dev/peps/pep-0484].

class typing.Generic

Abstract base class for generic types.

A generic type is typically declared by inheriting from an instantiation of this class with one or more type variables. For example, a generic mapping type might be defined as:

class Mapping(Generic[KT, VT]):
    def __getitem__(self, key: KT) -> VT:
        ...
        # Etc.

This class can then be used as follows:

X = TypeVar('X')
Y = TypeVar('Y')

def lookup_name(mapping: Mapping[X, Y], key: X, default: Y) -> Y:
    try:
        return mapping[key]
    except KeyError:
        return default

class typing.Type(Generic[CT_co])

A variable annotated with C may accept a value of type C. In contrast, a variable annotated with Type[C] may accept values that are classes themselves – specifically, it will accept the class object of C. For example:

a = 3         # Has type 'int'
b = int       # Has type 'Type[int]'
c = type(a)   # Also has type 'Type[int]'

Note that Type[C] is covariant:

class User: ...
class BasicUser(User): ...
class ProUser(User): ...
class TeamUser(User): ...

# Accepts User, BasicUser, ProUser, TeamUser, ...
def make_new_user(user_class: Type[User]) -> User:
    # ...
    return user_class()

The fact that Type[C] is covariant implies that all subclasses of C should implement the same constructor signature and class method signatures as C. The type checker should flag violations of this, but should also allow constructor calls in subclasses that match the constructor calls in the indicated base class. How the type checker is required to handle this particular case may change in future revisions of PEP 484 [https://www.python.org/dev/peps/pep-0484].

The only legal parameters for Type are classes, Any, type variables, and unions of any of these types. For example:

def new_non_team_user(user_class: Type[Union[BaseUser, ProUser]]): ...

Type[Any] is equivalent to Type which in turn is equivalent to type, which is the root of Python’s metaclass hierarchy.

버전 3.5.2에 추가.

class typing.Iterable(Generic[T_co])

A generic version of collections.abc.Iterable.

class typing.Iterator(Iterable[T_co])

A generic version of collections.abc.Iterator.

class typing.Reversible(Iterable[T_co])

A generic version of collections.abc.Reversible.

class typing.SupportsInt

An ABC with one abstract method __int__.

class typing.SupportsFloat

An ABC with one abstract method __float__.

class typing.SupportsComplex

An ABC with one abstract method __complex__.

class typing.SupportsBytes

An ABC with one abstract method __bytes__.

class typing.SupportsAbs

An ABC with one abstract method __abs__ that is covariant in its return type.

class typing.SupportsRound

An ABC with one abstract method __round__ that is covariant in its return type.

class typing.Container(Generic[T_co])

A generic version of collections.abc.Container.

class typing.Hashable

An alias to collections.abc.Hashable

class typing.Sized

An alias to collections.abc.Sized

class typing.Collection(Sized, Iterable[T_co], Container[T_co])

A generic version of collections.abc.Collection

버전 3.6.0에 추가.

class typing.AbstractSet(Sized, Collection[T_co])

A generic version of collections.abc.Set.

class typing.MutableSet(AbstractSet[T])

A generic version of collections.abc.MutableSet.

class typing.Mapping(Sized, Collection[KT], Generic[VT_co])

A generic version of collections.abc.Mapping. This type can be used as follows:

def get_position_in_index(word_list: Mapping[str, int], word: str) -> int:
    return word_list[word]

class typing.MutableMapping(Mapping[KT, VT])

A generic version of collections.abc.MutableMapping.

class typing.Sequence(Reversible[T_co], Collection[T_co])

A generic version of collections.abc.Sequence.

class typing.MutableSequence(Sequence[T])

A generic version of collections.abc.MutableSequence.

class typing.ByteString(Sequence[int])

A generic version of collections.abc.ByteString.

This type represents the types bytes, bytearray, and memoryview.

As a shorthand for this type, bytes can be used to annotate arguments of any of the types mentioned above.

class typing.Deque(deque, MutableSequence[T])

A generic version of collections.deque.

버전 3.5.4에 추가.

버전 3.6.1에 추가.

class typing.List(list, MutableSequence[T])

Generic version of list. Useful for annotating return types. To annotate arguments it is preferred to use an abstract collection type such as Sequence or Iterable.

This type may be used as follows:

T = TypeVar('T', int, float)

def vec2(x: T, y: T) -> List[T]:
    return [x, y]

def keep_positives(vector: Sequence[T]) -> List[T]:
    return [item for item in vector if item > 0]

class typing.Set(set, MutableSet[T])

A generic version of builtins.set. Useful for annotating return types. To annotate arguments it is preferred to use an abstract collection type such as AbstractSet.

class typing.FrozenSet(frozenset, AbstractSet[T_co])

A generic version of builtins.frozenset.

class typing.MappingView(Sized, Iterable[T_co])

A generic version of collections.abc.MappingView.

class typing.KeysView(MappingView[KT_co], AbstractSet[KT_co])

A generic version of collections.abc.KeysView.

class typing.ItemsView(MappingView, Generic[KT_co, VT_co])

A generic version of collections.abc.ItemsView.

class typing.ValuesView(MappingView[VT_co])

A generic version of collections.abc.ValuesView.

class typing.Awaitable(Generic[T_co])

A generic version of collections.abc.Awaitable.

버전 3.5.2에 추가.

class typing.Coroutine(Awaitable[V_co], Generic[T_co T_contra, V_co])

A generic version of collections.abc.Coroutine. The variance and order of type variables correspond to those of Generator, for example:

from typing import List, Coroutine
c = None # type: Coroutine[List[str], str, int]
...
x = c.send('hi') # type: List[str]
async def bar() -> None:
    x = await c # type: int

버전 3.5.3에 추가.

class typing.AsyncIterable(Generic[T_co])

A generic version of collections.abc.AsyncIterable.

버전 3.5.2에 추가.

class typing.AsyncIterator(AsyncIterable[T_co])

A generic version of collections.abc.AsyncIterator.

버전 3.5.2에 추가.

class typing.ContextManager(Generic[T_co])

A generic version of contextlib.AbstractContextManager.

버전 3.5.4에 추가.

버전 3.6.0에 추가.

class typing.AsyncContextManager(Generic[T_co])

A generic version of contextlib.AbstractAsyncContextManager.

버전 3.5.4에 추가.

버전 3.6.2에 추가.

class typing.Dict(dict, MutableMapping[KT, VT])

A generic version of dict. Useful for annotating return types. To annotate arguments it is preferred to use an abstract collection type such as Mapping.

This type can be used as follows:

def count_words(text: str) -> Dict[str, int]:
    ...

class typing.DefaultDict(collections.defaultdict, MutableMapping[KT, VT])

A generic version of collections.defaultdict.

버전 3.5.2에 추가.

class typing.OrderedDict(collections.OrderedDict, MutableMapping[KT, VT])

A generic version of collections.OrderedDict.

버전 3.7.2에 추가.

class typing.Counter(collections.Counter, Dict[T, int])

A generic version of collections.Counter.

버전 3.5.4에 추가.

버전 3.6.1에 추가.

class typing.ChainMap(collections.ChainMap, MutableMapping[KT, VT])

A generic version of collections.ChainMap.

버전 3.5.4에 추가.

버전 3.6.1에 추가.

class typing.Generator(Iterator[T_co], Generic[T_co, T_contra, V_co])

A generator can be annotated by the generic type Generator[YieldType, SendType, ReturnType]. For example:

def echo_round() -> Generator[int, float, str]:
    sent = yield 0
    while sent >= 0:
        sent = yield round(sent)
    return 'Done'

Note that unlike many other generics in the typing module, the SendType of Generator behaves contravariantly, not covariantly or invariantly.

If your generator will only yield values, set the SendType and ReturnType to None:

def infinite_stream(start: int) -> Generator[int, None, None]:
    while True:
        yield start
        start += 1

Alternatively, annotate your generator as having a return type of either Iterable[YieldType] or Iterator[YieldType]:

def infinite_stream(start: int) -> Iterator[int]:
    while True:
        yield start
        start += 1

class typing.AsyncGenerator(AsyncIterator[T_co], Generic[T_co, T_contra])

An async generator can be annotated by the generic type AsyncGenerator[YieldType, SendType]. For example:

async def echo_round() -> AsyncGenerator[int, float]:
    sent = yield 0
    while sent >= 0.0:
        rounded = await round(sent)
        sent = yield rounded

Unlike normal generators, async generators cannot return a value, so there is no ReturnType type parameter. As with Generator, the SendType behaves contravariantly.

If your generator will only yield values, set the SendType to None:

async def infinite_stream(start: int) -> AsyncGenerator[int, None]:
    while True:
        yield start
        start = await increment(start)

Alternatively, annotate your generator as having a return type of either AsyncIterable[YieldType] or AsyncIterator[YieldType]:

async def infinite_stream(start: int) -> AsyncIterator[int]:
    while True:
        yield start
        start = await increment(start)

버전 3.6.1에 추가.

class typing.Text

Text is an alias for str. It is provided to supply a forward compatible path for Python 2 code: in Python 2, Text is an alias for unicode.

Use Text to indicate that a value must contain a unicode string in a manner that is compatible with both Python 2 and Python 3:

def add_unicode_checkmark(text: Text) -> Text:
    return text + u' \u2713'

버전 3.5.2에 추가.

class typing.IO

class typing.TextIO

class typing.BinaryIO

Generic type IO[AnyStr] and its subclasses TextIO(IO[str]) and BinaryIO(IO[bytes]) represent the types of I/O streams such as returned by open().

class typing.Pattern

class typing.Match

These type aliases correspond to the return types from re.compile() and re.match(). These types (and the corresponding functions) are generic in AnyStr and can be made specific by writing Pattern[str], Pattern[bytes], Match[str], or Match[bytes].

class typing.NamedTuple

Typed version of collections.namedtuple().

Usage:

class Employee(NamedTuple):
    name: str
    id: int

This is equivalent to:

Employee = collections.namedtuple('Employee', ['name', 'id'])

To give a field a default value, you can assign to it in the class body:

class Employee(NamedTuple):
    name: str
    id: int = 3

employee = Employee('Guido')
assert employee.id == 3

Fields with a default value must come after any fields without a default.

The resulting class has two extra attributes: _field_types, giving a dict mapping field names to types, and _field_defaults, a dict mapping field names to default values. (The field names are in the _fields attribute, which is part of the namedtuple API.)

NamedTuple subclasses can also have docstrings and methods:

class Employee(NamedTuple):
    """Represents an employee."""
    name: str
    id: int = 3

    def __repr__(self) -> str:
        return f'<Employee {self.name}, id={self.id}>'

Backward-compatible usage:

Employee = NamedTuple('Employee', [('name', str), ('id', int)])

버전 3.6에서 변경: Added support for PEP 526 [https://www.python.org/dev/peps/pep-0526] variable annotation syntax.

버전 3.6.1에서 변경: Added support for default values, methods, and docstrings.

class typing.ForwardRef

A class used for internal typing representation of string forward references. For example, List["SomeClass"] is implicitly transformed into List[ForwardRef("SomeClass")]. This class should not be instantiated by a user, but may be used by introspection tools.

typing.NewType(typ)

A helper function to indicate a distinct types to a typechecker, see NewType. At runtime it returns a function that returns its argument. Usage:

UserId = NewType('UserId', int)
first_user = UserId(1)

버전 3.5.2에 추가.

typing.cast(typ, val)

Cast a value to a type.

This returns the value unchanged. To the type checker this signals that the return value has the designated type, but at runtime we intentionally don’t check anything (we want this to be as fast as possible).

typing.get_type_hints(obj[, globals[, locals]])

Return a dictionary containing type hints for a function, method, module or class object.

This is often the same as obj.__annotations__. In addition, forward references encoded as string literals are handled by evaluating them in globals and locals namespaces. If necessary, Optional[t] is added for function and method annotations if a default value equal to None is set. For a class C, return a dictionary constructed by merging all the __annotations__ along C.__mro__ in reverse order.

@typing.overload

The @overload decorator allows describing functions and methods that support multiple different combinations of argument types. A series of @overload-decorated definitions must be followed by exactly one non-@overload-decorated definition (for the same function/method). The @overload-decorated definitions are for the benefit of the type checker only, since they will be overwritten by the non-@overload-decorated definition, while the latter is used at runtime but should be ignored by a type checker. At runtime, calling a @overload-decorated function directly will raise NotImplementedError. An example of overload that gives a more precise type than can be expressed using a union or a type variable:

@overload
def process(response: None) -> None:
    ...
@overload
def process(response: int) -> Tuple[int, str]:
    ...
@overload
def process(response: bytes) -> str:
    ...
def process(response):
    <actual implementation>

See PEP 484 [https://www.python.org/dev/peps/pep-0484] for details and comparison with other typing semantics.

@typing.no_type_check

Decorator to indicate that annotations are not type hints.

This works as class or function decorator. With a class, it applies recursively to all methods defined in that class (but not to methods defined in its superclasses or subclasses).

This mutates the function(s) in place.

@typing.no_type_check_decorator

Decorator to give another decorator the no_type_check() effect.

This wraps the decorator with something that wraps the decorated function in no_type_check().

@typing.type_check_only

Decorator to mark a class or function to be unavailable at runtime.

This decorator is itself not available at runtime. It is mainly intended to mark classes that are defined in type stub files if an implementation returns an instance of a private class:

@type_check_only
class Response:  # private or not available at runtime
    code: int
    def get_header(self, name: str) -> str: ...

def fetch_response() -> Response: ...

Note that returning instances of private classes is not recommended. It is usually preferable to make such classes public.

typing.Any

Special type indicating an unconstrained type.

Every type is compatible with Any.

Any is compatible with every type.

typing.NoReturn

Special type indicating that a function never returns. For example:

from typing import NoReturn

def stop() -> NoReturn:
    raise RuntimeError('no way')

버전 3.5.4에 추가.

버전 3.6.2에 추가.

typing.Union

Union type; Union[X, Y] means either X or Y.

To define a union, use e.g. Union[int, str]. Details:

The arguments must be types and there must be at least one.

Unions of unions are flattened, e.g.:

Union[Union[int, str], float] == Union[int, str, float]

Unions of a single argument vanish, e.g.:

Union[int] == int  # The constructor actually returns int

Redundant arguments are skipped, e.g.:

Union[int, str, int] == Union[int, str]

When comparing unions, the argument order is ignored, e.g.:

Union[int, str] == Union[str, int]

You cannot subclass or instantiate a union.

You cannot write Union[X][Y].

You can use Optional[X] as a shorthand for Union[X, None].

버전 3.7에서 변경: Don’t remove explicit subclasses from unions at runtime.

typing.Optional

Optional type.

Optional[X] is equivalent to Union[X, None].

Note that this is not the same concept as an optional argument, which is one that has a default. An optional argument with a default does not require the Optional qualifier on its type annotation just because it is optional. For example:

def foo(arg: int = 0) -> None:
    ...

On the other hand, if an explicit value of None is allowed, the use of Optional is appropriate, whether the argument is optional or not. For example:

def foo(arg: Optional[int] = None) -> None:
    ...

typing.Tuple

Tuple type; Tuple[X, Y] is the type of a tuple of two items with the first item of type X and the second of type Y. The type of the empty tuple can be written as Tuple[()].

Example: Tuple[T1, T2] is a tuple of two elements corresponding to type variables T1 and T2. Tuple[int, float, str] is a tuple of an int, a float and a string.

To specify a variable-length tuple of homogeneous type, use literal ellipsis, e.g. Tuple[int, ...]. A plain Tuple is equivalent to Tuple[Any, ...], and in turn to tuple.

typing.Callable

Callable type; Callable[[int], str] is a function of (int) -> str.

The subscription syntax must always be used with exactly two values: the argument list and the return type. The argument list must be a list of types or an ellipsis; the return type must be a single type.

There is no syntax to indicate optional or keyword arguments; such function types are rarely used as callback types. Callable[..., ReturnType] (literal ellipsis) can be used to type hint a callable taking any number of arguments and returning ReturnType. A plain Callable is equivalent to Callable[..., Any], and in turn to collections.abc.Callable.

typing.ClassVar

Special type construct to mark class variables.

As introduced in PEP 526 [https://www.python.org/dev/peps/pep-0526], a variable annotation wrapped in ClassVar indicates that a given attribute is intended to be used as a class variable and should not be set on instances of that class. Usage:

class Starship:
    stats: ClassVar[Dict[str, int]] = {} # class variable
    damage: int = 10                     # instance variable

ClassVar accepts only types and cannot be further subscribed.

ClassVar is not a class itself, and should not be used with isinstance() or issubclass(). ClassVar does not change Python runtime behavior, but it can be used by third-party type checkers. For example, a type checker might flag the following code as an error:

enterprise_d = Starship(3000)
enterprise_d.stats = {} # Error, setting class variable on instance
Starship.stats = {}     # This is OK

버전 3.5.3에 추가.

typing.AnyStr

AnyStr is a type variable defined as AnyStr = TypeVar('AnyStr', str, bytes).

It is meant to be used for functions that may accept any kind of string without allowing different kinds of strings to mix. For example:

def concat(a: AnyStr, b: AnyStr) -> AnyStr:
    return a + b

concat(u"foo", u"bar")  # Ok, output has type 'unicode'
concat(b"foo", b"bar")  # Ok, output has type 'bytes'
concat(u"foo", b"bar")  # Error, cannot mix unicode and bytes

typing.TYPE_CHECKING

A special constant that is assumed to be True by 3rd party static type checkers. It is False at runtime. Usage:

if TYPE_CHECKING:
    import expensive_mod

def fun(arg: 'expensive_mod.SomeType') -> None:
    local_var: expensive_mod.AnotherType = other_fun()

Note that the first type annotation must be enclosed in quotes, making it a “forward reference”, to hide the expensive_mod reference from the interpreter runtime. Type annotations for local variables are not evaluated, so the second annotation does not need to be enclosed in quotes.

버전 3.5.2에 추가.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

개발 도구 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

개발 도구 »

|

pydoc — 설명서 생성과 온라인 도움말 시스템

소스 코드: Lib/pydoc.py [https://github.com/python/cpython/tree/3.7/Lib/pydoc.py]

pydoc 모듈은 파이썬 모듈로부터 자동으로 설명서를 생성합니다. 설명서는 콘솔에 텍스트 페이지로 표시하거나, 웹 브라우저로 제공하거나, HTML 파일에 저장할 수 있습니다.

모듈, 클래스, 함수 및 메서드의 경우, 표시된 설명서는 객체와 재귀적으로 그것의 설명 가능한 멤버들의 독스트링(즉, __doc__ 어트리뷰트)에서 파생됩니다. 독스트링이 없으면, pydoc은 소스 파일의 클래스, 함수 또는 메서드의 정의 바로 위나 모듈의 맨 위에 있는 주석 줄 블록에서 설명을 얻으려고 합니다 (inspect.getcomments()를 참조하십시오).

내장 함수 help()는 대화형 인터프리터에서 온라인 도움말 시스템을 호출합니다. 이 시스템은 pydoc을 사용하여 설명서를 콘솔에 텍스트로 생성합니다. 같은 텍스트 설명서는 운영 체제의 명령 프롬프트에서 pydoc을 스크립트로 실행하여 파이썬 인터프리터 외부에서도 볼 수 있습니다. 예를 들어,

pydoc sys

를 셸 프롬프트에서 실행하면, sys 모듈의 설명서를 유닉스 man 명령으로 표시되는 매뉴얼 페이지와 비슷한 스타일로 표시합니다. pydoc의 인자는 함수, 모듈 또는 패키지의 이름이거나 모듈이나 패키지의 모듈 내의 클래스, 메서드 또는 함수에 대한 점으로 구분된 참조일 수 있습니다. pydoc에 대한 인자가 경로처럼 보이고 (즉, 유닉스의 슬래시와 같이 운영 체제의 경로 구분 기호가 포함되어 있으면), 기존 파이썬 소스 파일을 가리키면, 해당 파일에 대한 설명서가 생성됩니다.

참고

객체와 그들의 설명을 찾기 위해, pydoc은 설명할 모듈을 임포트 합니다. 따라서, 모듈 수준의 모든 코드는 이때 실행됩니다. 파일이 임포트될 때가 아니라 스크립트로 호출할 때만 실행되도록 코드를 보호하려면 if __name__ == '__main__':를 사용하십시오.

출력을 콘솔에 인쇄할 때, pydoc은 읽기 쉽도록 출력을 페이지로 나누려고 합니다. PAGER 환경 변수가 설정되면, pydoc은 그 값을 페이지 매김 프로그램으로 사용합니다.

인자 앞에 -w 플래그를 지정하면 콘솔에 텍스트를 표시하는 대신, HTML 설명서가 현재 디렉터리에 파일로 기록됩니다.

인자 앞에 -k 플래그를 지정하면 인자로 주어진 키워드에 대해 사용 가능한 모든 모듈의 개요 행을 검색할 수 있습니다. 역시 유닉스 man 명령과 유사한 방식입니다. 모듈의 개요 행은 설명서 문자열의 첫 행입니다.

pydoc을 사용하여 방문하는 웹 브라우저에 설명서를 제공하는 HTTP 서버를 로컬 시스템에서 시작할 수도 있습니다. pydoc -p 1234는 포트 1234에서 HTTP 서버를 시작해서, 여러분이 선호하는 웹 브라우저에서 http://localhost:1234/의 설명서를 볼 수 있도록 합니다. 포트 번호로 0을 지정하면 사용되지 않는 임의의 포트가 선택됩니다.

pydoc -n <hostname>은 주어진 호스트 이름에서 리스닝하는 서버를 시작합니다. 기본적으로 호스트 이름은 ‘localhost’ 이지만 다른 컴퓨터에서 서버에 도달하도록 하고 싶으면 서버가 응답하는 호스트 이름을 변경해야 할 수 있습니다. 개발 중에 컨테이너 내에서 pydoc을 실행하려는 경우 특히 유용합니다.

pydoc -b는 서버를 시작하고 모듈 색인 페이지로 웹 브라우저를 추가로 엽니다. 제공되는 각 페이지에는 상단에 탐색 바가 있어, 개별 항목에 대한 도움말을 조회(Get)하고, 개요 행에 키워드가 있는 모든 모듈을 검색(Search)하고, 모듈 색인(Module index), 주제(Topics) 및 키워드(Keywords) 페이지로 이동할 수 있습니다.

pydoc이 설명서를 생성할 때, 현재 환경과 경로를 사용하여 모듈을 찾습니다. 따라서, pydoc spam을 호출하면 정확히 파이썬 인터프리터를 시작하고 import spam을 입력할 때 얻는 모듈의 버전을 설명합니다.

코어 모듈에 대한 모듈 설명은 https://docs.python.org/X.Y/library/에 있다고 가정합니다. 여기서 X와 Y는 파이썬 인터프리터의 주 버전 번호와 부 버전 번호입니다. 이는 PYTHONDOCS 환경 변수를 다른 URL로 설정하거나 라이브러리 레퍼런스 매뉴얼 페이지가 있는 로컬 디렉터리로 설정하여 재정의할 수 있습니다.

버전 3.2에서 변경: -b 옵션이 추가되었습니다.

버전 3.3에서 변경: -g 명령 줄 옵션이 제거되었습니다.

버전 3.4에서 변경: 이제 pydoc은 inspect.getfullargspec() 대신 inspect.signature()를 사용하여 콜러블에서 서명 정보를 추출합니다.

버전 3.7에서 변경: -n 옵션이 추가되었습니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

개발 도구 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

개발 도구 »

|

doctest — 대화형 파이썬 예제 테스트

소스 코드: Lib/doctest.py [https://github.com/python/cpython/tree/3.7/Lib/doctest.py]

doctest 모듈은 대화형 파이썬 세션처럼 보이는 텍스트를 검색한 다음, 해당 세션을 실행하여 표시된 대로 정확하게 작동하는지 검증합니다. doctest를 사용하는 몇 가지 일반적인 방법이 있습니다:

모든 대화식 예제가 설명된 대로 작동하는지 확인하여 모듈의 독스트링이 최신인지 확인합니다.

테스트 파일이나 테스트 객체의 대화형 예제가 예상대로 작동하는지 확인하여 회귀 테스트를 수행합니다.

입/출력 예제를 그대로 보여줌으로써 패키지에 대한 자습서를 작성합니다. 예제나 설명문 중 어느 것이 강조되는지에 따라, “문학적 테스트(literate testing)”나 “실행 가능한 설명서(executable documentation)”의 느낌을 줍니다.

여기에 완전하지만 작은 예제 모듈이 있습니다:

"""
This is the "example" module.

The example module supplies one function, factorial().  For example,

>>> factorial(5)
120
"""

def factorial(n):
    """Return the factorial of n, an exact integer >= 0.

    >>> [factorial(n) for n in range(6)]
    [1, 1, 2, 6, 24, 120]
    >>> factorial(30)
    265252859812191058636308480000000
    >>> factorial(-1)
    Traceback (most recent call last):
        ...
    ValueError: n must be >= 0

    Factorials of floats are OK, but the float must be an exact integer:
    >>> factorial(30.1)
    Traceback (most recent call last):
        ...
    ValueError: n must be exact integer
    >>> factorial(30.0)
    265252859812191058636308480000000

    It must also not be ridiculously large:
    >>> factorial(1e100)
    Traceback (most recent call last):
        ...
    OverflowError: n too large
    """

    import math
    if not n >= 0:
        raise ValueError("n must be >= 0")
    if math.floor(n) != n:
        raise ValueError("n must be exact integer")
    if n+1 == n:  # catch a value like 1e300
        raise OverflowError("n too large")
    result = 1
    factor = 2
    while factor <= n:
        result *= factor
        factor += 1
    return result

if __name__ == "__main__":
    import doctest
    doctest.testmod()

example.py를 명령 줄에서 직접 실행하면, doctest가 마술을 부리기 시작합니다:

$ python example.py
$

출력이 없습니다! 이것이 정상이며, 모든 예제가 작동했다는 것을 뜻합니다. -v를 스크립트에 전달하면, doctest는 시도하고 있는 내용에 대한 자세한 로그를 출력하고 끝에 요약을 인쇄합니다.:

$ python example.py -v
Trying:
    factorial(5)
Expecting:
    120
ok
Trying:
    [factorial(n) for n in range(6)]
Expecting:
    [1, 1, 2, 6, 24, 120]
ok

결국, 다음과 같이 끝납니다:

Trying:
    factorial(1e100)
Expecting:
    Traceback (most recent call last):
        ...
    OverflowError: n too large
ok
2 items passed all tests:
   1 tests in __main__
   8 tests in __main__.factorial
9 tests in 2 items.
9 passed and 0 failed.
Test passed.
$

이것이 doctest를 생산적으로 사용하기 위해서 알아야 할 모든 것입니다! 시도해 보세요. 다음 절에서는 자세한 내용을 제공합니다. 표준 파이썬 테스트 스위트와 라이브러리에는 doctest 예제가 많습니다. 특히 유용한 예제는 표준 테스트 파일 Lib/test/test_doctest.py에서 찾을 수 있습니다.

간단한 사용법: 독스트링에 있는 예제 확인하기

doctest를 사용하는 가장 간단한 방법은 (하지만 계속 이렇게 할 필요는 없습니다) 각 모듈 M을 다음과 같이 끝내는 것입니다:

if __name__ == "__main__":
    import doctest
    doctest.testmod()

그러면 doctest는 모듈 M의 독스트링을 검사합니다.

모듈을 스크립트로 실행하면 독스트링의 예제가 실행되고 검증됩니다:

python M.py

예제가 실패하지 않는 한 아무것도 표시되지 않습니다, 실패하면 실패한 예제와 실패 원인이 stdout으로 출력되고, 마지막 출력 줄은 ***Test Failed*** N failures.입니다. 여기서 N은 실패한 예제의 수입니다.

대신 -v 스위치로 실행해 보십시오:

python M.py -v

그러면 시도한 모든 예제에 대한 자세한 보고서가 표준 출력으로 출력되고, 끝에 정돈된 요약이 붙습니다.

verbose=True를 testmod()에 전달하여 상세 모드를 강제하거나, verbose=False를 전달하여 상세 모드를 금지할 수 있습니다. 두 경우 모두, sys.argv는 testmod()에 의해 검사되지 않습니다 (따라서 -v를 전달하거나 그렇지 않아도 효과가 없습니다).

또한 testmod()를 실행하는 명령 줄 단축법이 있습니다. 파이썬 인터프리터에게 표준 라이브러리에서 직접 doctest 모듈을 실행하도록 지시하고 명령 줄에 모듈 이름(들)을 전달할 수 있습니다:

python -m doctest -v example.py

이렇게 하면 example.py를 독립 실행형 모듈로 임포트하고, testmod()를 실행합니다. 파일이 패키지 일부이고 그 패키지에서 다른 서브 모듈을 임포트하면, 올바르게 작동하지 않을 수 있음에 유의하십시오.

testmod()에 대한 자세한 내용은, 기본 API 절을 참조하십시오.

간단한 사용법: 텍스트 파일에 있는 예제 확인하기

doctest의 또 다른 간단한 활용은 텍스트 파일에 있는 대화형 예제를 테스트하는 것입니다. 이것은 testfile() 함수로 수행할 수 있습니다:

import doctest
doctest.testfile("example.txt")

이 짧은 스크립트는 example.txt 파일에 들어있는 대화형 파이썬 예제를 실행하고 검증합니다. 파일 내용은 하나의 거대한 독스트링인 것처럼 취급됩니다; 파일이 파이썬 프로그램일 필요가 없습니다! 예를 들어, example.txt에 다음과 같은 것이 들어있습니다:

The ``example`` module
======================

Using ``factorial``
-------------------

This is an example text file in reStructuredText format.  First import
``factorial`` from the ``example`` module:

    >>> from example import factorial

Now use it:

    >>> factorial(6)
    120

doctest.testfile("example.txt")를 실행하면 이 문서에 있는 에러를 찾습니다:

File "./example.txt", line 14, in example.txt
Failed example:
    factorial(6)
Expected:
    120
Got:
    720

testmod()와 마찬가지로, testfile()은 예제가 실패하지 않는 한 아무것도 표시하지 않습니다. 예제가 실패하면, 실패한 예제와 실패 원인이 testmod()와 같은 형식을 사용하여 stdout에 인쇄됩니다.

기본적으로, testfile()은 호출하는 모듈의 디렉터리에서 파일을 찾습니다. 다른 위치에서 파일을 찾도록 지시하는 데 사용할 수 있는 선택적 인자에 대한 설명은 기본 API 절을 참조하십시오.

testmod()와 마찬가지로, testfile()의 상세도는 -v 명령 줄 스위치나 선택적 키워드 인자 verbose를 사용하여 설정할 수 있습니다.

또한 testfile()를 실행하는 명령 줄 단축법이 있습니다. 파이썬 인터프리터에게 표준 라이브러리에서 직접 doctest 모듈을 실행하도록 지시하고 명령 줄에 파일 이름(들)을 전달할 수 있습니다:

python -m doctest -v example.txt

파일 이름은 .py로 끝나지 않으므로, doctest는 testmod()가 아니라 testfile()로 실행되어야 한다고 추론합니다.

testfile()에 대한 자세한 내용은, 기본 API 절을 참조하십시오.

작동 방법

이 절에서는 doctest가 어떻게 작동하는지 자세히 설명합니다: 어떤 독스트링을 살피는지, 대화형 예제를 어떻게 찾는지, 사용하는 실행 컨텍스트는 무엇인지, 예외를 어떻게 처리하는지, 어떻게 옵션 플래그를 사용하여 동작을 제어하는지. 이것은 doctest 예제를 작성하기 위해 알아야 할 정보입니다; 이러한 예제에 대해 실제로 doctest를 실행하는 방법에 대한 자세한 내용은 다음 절을 참조하십시오.

어떤 독스트링을 검사합니까?

모듈 독스트링과 모든 함수, 클래스 및 메서드 독스트링이 검색됩니다. 모듈로 임포트 된 객체는 검색되지 않습니다.

또한, M.__test__가 존재하고 “참이면”, 딕셔너리이어야 하고 각 항목은 (문자열) 이름을 함수 객체, 클래스 객체 또는 문자열에 매핑합니다. M.__test__에서 발견된 함수와 클래스 객체 독스트링이 검색되고, 문자열은 독스트링인 것처럼 처리됩니다. 출력에서, M.__test__의 키 K가 이름으로 나타납니다

<name of M>.__test__.K

발견된 모든 클래스는 포함된 메서드와 중첩된 클래스의 독스트링을 테스트하기 위해 유사하게 재귀적으로 검색됩니다.

CPython implementation detail: Prior to version 3.4, extension modules written in C were not fully searched by doctest.

독스트링 예제는 어떻게 인식됩니까?

대부분 대화형 콘솔 세션의 복사하여 붙여넣기가 잘 작동하지만, doctest는 특정 파이썬 셸의 정확한 에뮬레이션을 시도하지 않습니다.

>>> # comments are ignored
>>> x = 12
>>> x
12
>>> if x == 13:
...     print("yes")
... else:
...     print("no")
...     print("NO")
...     print("NO!!!")
...
no
NO
NO!!!
>>>

모든 예상 출력은 코드가 포함된 마지막 '>>> ' 또는 '... ' 줄 바로 다음에 나와야 하며, (있다면) 예상 출력은 다음 '>>> ' 나 전체 공백 줄까지 확장됩니다.

세부 사항:

예상 출력은 전체 공백 줄을 포함할 수 없습니다. 그러한 줄은 예상 출력의 끝으로 인식되기 때문입니다. 예상 출력이 빈 줄을 포함하면, doctest 예제에서 빈 줄이 나타나는 곳에 <BLANKLINE>을 넣으십시오.

모든 하드 탭 문자는 8열 탭 정지를 사용하여 스페이스로 확장됩니다. 테스트 된 코드에 의해 생성된 출력의 탭은 수정되지 않습니다. 샘플 출력의 모든 하드 탭이 확장되므로, 이것은 코드 출력에 하드 탭이 포함될 때 doctest가 통과할 수 있는 유일한 방법은, NORMALIZE_WHITESPACE 옵션이나 지시자가 유효한 경우뿐임을 의미합니다. 또는, 출력을 캡처하여 테스트 일부로 예상값과 비교하도록 테스트를 다시 작성할 수 있습니다. 이러한 소스의 탭 처리는 시행착오를 거쳐 얻어진 것이며, 가장 에러가 발생하지 않는 방법으로 입증되었습니다. 사용자 정의 DocTestParser 클래스를 작성하여 탭 처리에 다른 알고리즘을 사용하는 것도 가능합니다.

stdout으로의 출력은 캡처되지만, stderr로의 출력은 그렇지 않습니다 (예외 트레이스백은 다른 수단을 통해 캡처됩니다).

대화식 세션에서 역 슬래시를 통해 줄을 계속하거나, 다른 이유로 백 슬래시를 사용하면, 날 독스트링(raw docstring)을 사용해서 역 슬래시를 입력한 그대로 유지해야 합니다:

>>> def f(x):
...     r'''Backslashes in a raw docstring: m\n'''
>>> print(f.__doc__)
Backslashes in a raw docstring: m\n

그렇지 않으면, 백 슬래시가 문자열 일부로 해석됩니다. 예를 들어, 위의 \n은 개행 문자로 해석됩니다. 또는, doctest 버전에서 각 백 슬래시를 중복시킬 수 있습니다 (그리고 날 문자열은 사용하지 않습니다):

>>> def f(x):
...     '''Backslashes in a raw docstring: m\\n'''
>>> print(f.__doc__)
Backslashes in a raw docstring: m\n

시작 열은 중요하지 않습니다:

>>> assert "Easy!"
      >>> import math
          >>> math.floor(1.9)
          1

그리고 예제를 시작한 초기 '>>> ' 줄에 나타나는 것만큼의 선행 공백을 예상 출력에서 제거합니다.

실행 컨텍스트란 무엇입니까?

기본적으로, doctest가 테스트할 독스트링을 찾을 때마다, M의 전역 이름 공간(globals)의 앝은 복사를 사용하므로, 실행 중인 테스트는 모듈의 실제 전역을 변경하지 않고, M의 한 테스트가 실수로 다른 테스트가 작동하도록 만드는 부스러기를 남기지 않습니다. 이는 예제가 M에서 최상위 수준에 정의된 이름과 실행 중인 독스트링에서 앞서 정의한 이름을 자유롭게 사용할 수 있음을 의미합니다. 예제는 다른 독스트링에 정의된 이름을 볼 수 없습니다.

대신 globs=your_dict를 testmod()나 testfile()로 전달하여 실행 컨텍스트로 여러분 자신의 딕셔너리를 사용하도록 할 수 있습니다.

예외는 어떻게 됩니까?

문제없습니다, 트레이스백이 예제에 의해 생성된 유일한 출력이기만 하면 됩니다: 그냥 트레이스백을 붙여넣으십시오. 1 트레이스백에는 빠르게 변할 가능성이 있는 세부 사항(예를 들어, 정확한 파일 경로와 줄 번호)이 포함되어 있으므로, 이것은 doctest가 수락할 내용에 유연하도록 신경 써야 하는 한 가지 사례입니다.

간단한 예:

>>> [1, 2, 3].remove(42)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: list.remove(x): x not in list

이 doctest는 list.remove(x): x not in list 세부 정보를 포함하는 ValueError가 발생하면 성공합니다.

예외의 예상 출력은 다음 두 줄 중 한 가지가 예제의 첫 번째 줄과 같게 들여쓰기 된 트레이스백 헤더로 시작해야 합니다:

Traceback (most recent call last):
Traceback (innermost last):

트레이스백 헤더 다음에는 선택적인 트레이스백 스택이 오며, 그 내용은 doctest가 무시합니다. 보통 트레이스백 스택은 생략되거나, 대화형 세션에서 그대로 복사됩니다.

트레이스백 스택 다음에는 가장 흥미로운 부분이 옵니다: 예외 형과 세부 사항이 있는 줄. 대개 이것은 트레이스백의 마지막 줄이지만, 예외에 여러 줄로 구성된 세부 사항이 있으면 여러 줄로 확장될 수 있습니다:

>>> raise ValueError('multi\n    line\ndetail')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: multi
    line
detail

(ValueError로 시작하는) 마지막 세 줄이 예외의 형 및 세부 사항과 비교되고, 나머지는 무시됩니다.

모범 사례는 예제에 중요한 설명으로서의 가치를 추가하지 않는 한 트레이스백 스택을 생략하는 것입니다. 따라서 마지막 예제는 이렇게 하는 것이 더 좋습니다:

>>> raise ValueError('multi\n    line\ndetail')
Traceback (most recent call last):
    ...
ValueError: multi
    line
detail

트레이스백이 매우 특별하게 취급된다는 점에 유의하십시오. 특히, 다시 작성된 예제에서, ...의 사용은 doctest의 ELLIPSIS 옵션과 무관합니다. 이 예제의 줄임표는 생략하거나, 3개(혹은 300개)의 쉼표나 숫자 또는 몬티 파이썬 쇼의 들여쓰기 된 대본이어도 똑같이 잘 동작합니다.

한 번쯤 읽어야 할 세부 정보이지만, 기억할 필요는 없습니다:

Doctest는 예상 출력이 예외 트레이스백에서 온 것인지 일반 인쇄에서 온 것인지 추측할 수 없습니다. 그래서, 예를 들어, ValueError: 42 is prime을 예상하는 예제는 ValueError가 실제로 발생해도 통과하지만, 예제가 단지 그 트레이스백 텍스트를 출력해도 통과합니다. 실제로는, 일반 출력은 거의 트레이스백 헤더 줄로 시작하지 않으므로, 실제 문제가 되지는 않습니다.

(있다면) 트레이스백 스택의 각 줄은 예제의 첫 번째 줄보다 더 들여쓰기 되거나, 또는 영숫자(alphanumeric)가 아닌 문자로 시작해야 합니다. 트레이스백 헤더 뒤에 같은 정도로 들여쓰기 되고, 영숫자로 시작하는 첫 번째 줄은 예외 세부 사항의 시작으로 간주합니다. 물론 이것은 진짜 트레이스백에 잘 들어맞습니다.

IGNORE_EXCEPTION_DETAIL doctest 옵션을 지정하면, 가장 왼쪽 콜론 다음에 오는 모든 것과 예외 이름의 모듈 정보가 무시됩니다.

대화형 셸은 일부 SyntaxError에서 트레이스백 헤더 줄을 생략합니다. 그러나 doctest는 트레이스백 헤더 줄을 사용하여 예외를 비 예외와 구별합니다. 따라서 트레이스백 헤더를 생략하는 SyntaxError를 테스트해야 하는 드문 경우에는, 트레이스백 헤더 줄을 수동으로 테스트 예제에 추가해야 합니다.

일부 SyntaxError의 경우, 파이썬은 ^ 마커를 사용하여 구문 에러의 문자 위치를 표시합니다:

>>> 1 1
  File "<stdin>", line 1
    1 1
      ^
SyntaxError: invalid syntax

에러의 위치를 나타내는 줄은 예외 형과 세부 사항 앞에 오므로, doctest가 점검하지 않습니다. 예를 들어, ^ 마커를 잘못된 위치에 넣어도, 다음 테스트가 통과합니다:

>>> 1 1
  File "<stdin>", line 1
    1 1
    ^
SyntaxError: invalid syntax

옵션 플래그

많은 옵션 플래그가 doctest의 다양한 동작을 제어합니다. 플래그의 기호 이름은 모듈 상수로 제공되며, 함께 비트별 OR되어 다양한 함수로 전달될 수 있습니다. 이 이름은 doctest 지시자에서도 사용될 수 있으며, -o 옵션을 통해 doctest 명령 줄 인터페이스로 전달될 수 있습니다.

버전 3.4에 추가: -o 명령 줄 옵션.

첫 번째 옵션 그룹은 테스트의 의미를 정의하는데, doctest가 실제 출력이 예제의 예상 출력과 일치하는지를 결정하는 측면을 제어합니다:

doctest.DONT_ACCEPT_TRUE_FOR_1

기본적으로, 예상 출력 블록에 1 만 있으면, 단지 1이나 True 만 포함된 실제 출력 블록을 일치하는 것으로 간주하며, 0과 False도 유사하게 다룹니다. DONT_ACCEPT_TRUE_FOR_1이 지정되면, 두 치환 모두 허용되지 않습니다. 기본 동작은 파이썬이 많은 함수의 반환형을 정수에서 논릿값으로 변경했다는 것을 반영합니다; “작은 정수” 출력을 예상하는 doctest가 이러한 경우에 여전히 작동합니다. 아마도 이 옵션은 사라지게 되겠지만, 몇 년 동안은 남아있을 겁니다.

doctest.DONT_ACCEPT_BLANKLINE

기본적으로, 예상 출력 블록에 <BLANKLINE> 문자열만 포함된 줄이 있으면, 해당하는 줄은 실제 출력의 빈 줄과 일치합니다. 진짜 빈 줄은 예상 출력을 끝내므로, 이것이 빈 줄을 예상하는 유일한 방법입니다. DONT_ACCEPT_BLANKLINE이 지정되면, 이 치환은 허용되지 않습니다.

doctest.NORMALIZE_WHITESPACE

지정되면, 모든 공백(빈칸과 개행) 시퀀스는 같게 취급됩니다. 예상 출력 내의 모든 공백 시퀀스는 실제 출력 내의 모든 공백 시퀀스와 일치합니다. 기본적으로, 공백은 정확히 일치해야 합니다. NORMALIZE_WHITESPACE는 예상 출력 줄이 매우 길고 소스의 여러 줄에 걸쳐 줄넘김하려는 경우에 특히 유용합니다.

doctest.ELLIPSIS

지정되면, 예상 출력의 줄임표(...)가 실제 출력의 모든 부분 문자열과 일치 할 수 있습니다. 여기에는 줄 경계를 넘는 부분 문자열과 빈 부분 문자열이 포함되므로, 사용을 간단하게 유지하는 것이 가장 좋습니다. 복잡한 사용은 정규식에서 .*를 쓸 때처럼 “이런, 너무 많이 일치하는군!” 과 같은 상황을 만들 수 있습니다.

doctest.IGNORE_EXCEPTION_DETAIL

지정하면, 예외를 예상하는 예제가, 예외 세부 사항이 일치하지 않아도 예상 형의 예외가 발생하면 통과합니다. 예를 들어, ValueError: 42를 예상하는 예제는 발생한 실제 예외가 ValueError: 3*14이면 통과하지만, 예를 들어 TypeError가 발생하면 실패합니다.

또한, 파이썬 3 doctest 보고서에 사용된 모듈 이름도 무시합니다. 따라서 이 두 변형은 이 플래그가 지정되면 테스트가 파이썬 2.7이나 파이썬 3.2(또는 이후 버전)에서 실행되는지와 관계없이 작동합니다:

>>> raise CustomError('message')
Traceback (most recent call last):
CustomError: message

>>> raise CustomError('message')
Traceback (most recent call last):
my_module.CustomError: message

ELLIPSIS를 사용하여 예외 메시지의 세부 사항을 무시할 수도 있지만, 그러한 테스트는 모듈 세부 사항이 예외 이름의 일부로 인쇄되는지에 따라 여전히 실패할 수 있음에 유의하십시오. IGNORE_EXCEPTION_DETAIL과 파이썬 2.3의 세부 사항을 사용하는 것은 또한 예외 세부 사항에 신경 쓰지 않고 여전히 파이썬 2.3이나 그 이전 버전(이 배포는 doctest 지시자를 지원하지 않고 무의미한 주석으로 무시합니다)에서 통과하는 doctest를 작성하는 유일하게 명확한 방법입니다. 예를 들면:

>>> (1, 2)[3] = 'moo'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: object doesn't support item assignment

는 플래그가 지정될 때 파이썬 2.3 이후 버전에서 통과합니다. 파이썬 2.4에서 세부 사항이 “doesn’t” 대신 “does not”으로 변경되었음에도 통과합니다.

버전 3.2에서 변경: IGNORE_EXCEPTION_DETAIL은 이제 테스트 중인 예외를 포함하는 모듈과 관련된 정보도 무시합니다.

doctest.SKIP

지정되면, 예제를 전혀 실행하지 않습니다. 이것은 doctest 예제가 설명서와 테스트 케이스의 두 가지 역할을 하는 문맥에서, 설명을 위해 예제를 포함해야 하지만 검사하지는 않아야 할 때 유용할 수 있습니다. 예를 들어, 예제의 출력이 임의적일 수 있습니다; 또는 예제가 테스트 구동기에서 사용할 수 없는 자원에 의존할 수 있습니다.

SKIP 플래그는 임시로 “주석 처리한” 예제를 위해 사용될 수도 있습니다.

doctest.COMPARISON_FLAGS

위의 모든 비교 플래그를 함께 OR 한 비트 마스크.

두 번째 옵션 그룹은 테스트 실패가 보고되는 방식을 제어합니다:

doctest.REPORT_UDIFF

지정되면, 여러 줄의 예상 및 실제 출력을 수반하는 실패가 통합(unified) diff를 사용하여 표시됩니다.

doctest.REPORT_CDIFF

지정되면, 여러 줄의 예상 및 실제 출력을 수반하는 실패가 문맥(context) diff를 사용하여 표시됩니다.

doctest.REPORT_NDIFF

지정되면, 차이점은 널리 사용되는 ndiff.py 유틸리티와 같은 알고리즘을 사용하여, difflib.Differ로 계산됩니다. 이 방법은 줄 간의 차이뿐만 아니라 줄 안에서의 차이점을 표시하는 유일한 방법입니다. 예를 들어, 예상 출력 줄에 숫자 1이 포함된 줄에 실제 출력이 문자 l을 포함하고 있으면, 일치하지 않는 열 위치를 나타내는 캐럿(caret)이 들어간 줄이 삽입됩니다.

doctest.REPORT_ONLY_FIRST_FAILURE

지정되면, 각 doctest에서 실패한 첫 번째 예제를 표시하지만, 나머지 모든 예제에 대해서는 출력을 억제합니다. 이렇게 하면 doctest가 이전의 실패로 인해 망가진 올바른 예제를 보고하지 않게 되지만, 첫 번째 실패와 무관하게 실패한 잘못된 예제를 숨길 수도 있습니다. REPORT_ONLY_FIRST_FAILURE가 지정될 때, 나머지 예제는 여전히 실행되며, 보고된 총실패 수에 포함됩니다; 출력만 억제됩니다.

doctest.FAIL_FAST

지정되면, 첫 번째 실패 예제 후에 종료하고, 나머지 예제를 실행하지 않습니다. 따라서, 보고되는 실패 횟수는 최대 1입니다. 이 플래그는 디버깅 중에 유용할 수 있습니다, 첫 번째 실패 이후의 예제는 디버깅 출력조차 생성하지 않기 때문입니다.

doctest 명령 줄은 옵션 -f를 -o FAIL_FAST의 축약으로 받아들입니다.

버전 3.4에 추가.

doctest.REPORTING_FLAGS

위의 모든 보고(reporting) 플래그를 함께 OR 한 비트 마스크.

새로운 옵션 플래그 이름을 등록하는 방법도 있습니다만, 서브 클래스를 통해 doctest 내부를 확장하려고 하지 않는 한 유용하지는 않습니다:

doctest.register_optionflag(name)

지정된 이름으로 새로운 옵션 플래그를 만들고, 새로운 플래그의 정숫값을 반환합니다. register_optionflag()은 OutputChecker나 DocTestRunner를 서브 클래싱할 때 서브 클래스가 지원하는 새 옵션을 만들 때 사용할 수 있습니다. register_optionflag()는 항상 다음의 관용구를 사용하여 호출해야 합니다:

MY_FLAG = register_optionflag('MY_FLAG')

지시자

Doctest 지시자를 사용하면 개별 예제의 옵션 플래그를 수정할 수 있습니다. Doctest 지시자는 예제의 소스 코드 뒤에 오는 특수한 파이썬 주석입니다:

directive             ::=  "#" "doctest:" directive_options
directive_options     ::=  directive_option ("," directive_option)\*
directive_option      ::=  on_or_off directive_option_name
on_or_off             ::=  "+" \| "-"
directive_option_name ::=  "DONT_ACCEPT_BLANKLINE" \| "NORMALIZE_WHITESPACE" \| ...

+나 -와 지시자 옵션 이름 사이의 공백은 허용되지 않습니다. 지시자 옵션 이름은 위에 설명된 옵션 플래그 이름 중 하나일 수 있습니다.

예제의 doctest 지시자는 그 단일 예제에 대한 doctest의 동작을 수정합니다. 이름 붙인 동작을 활성화하려면 +를 사용하고, 비활성화하려면 -를 사용하십시오.

예를 들어, 이 테스트는 통과합니다:

>>> print(list(range(20)))
[0,   1,  2,  3,  4,  5,  6,  7,  8,  9,
10,  11, 12, 13, 14, 15, 16, 17, 18, 19]

지시자가 없으면 실패하는데, 실제 출력에는 한 자리 숫자 리스트 요소 앞에 두 개의 공백이 없기도 하고, 실제 출력은 한 줄이기 때문입니다. 이 테스트도 통과하는데, 그러기 위해서 역시 지시자가 필요합니다:

>>> print(list(range(20)))
[0, 1, ..., 18, 19]

하나의 물리적 줄에 여러 개의 지시자를 쉼표로 구분하여 사용할 수 있습니다:

>>> print(list(range(20)))
[0,    1, ...,   18,    19]

하나의 예제에 여러 개의 지시자 주석이 사용되면, 모두 결합합니다:

>>> print(list(range(20)))
...
[0,    1, ...,   18,    19]

앞의 예가 보여주듯이, 여러분의 예제에 지시자만 포함된 ... 줄을 추가할 수 있습니다. 예가 너무 길어서 지시자가 같은 줄에 편안하게 들어갈 수 없을 때 유용할 수 있습니다:

>>> print(list(range(5)) + list(range(10, 20)) + list(range(30, 40)))
...
[0, ..., 4, 10, ..., 19, 30, ..., 39]

모든 옵션은 기본적으로 비활성화되고, 지시자가 표시된 예제에만 적용되므로, (지시자에 +를 통해) 옵션을 활성화하는 것이 일반적으로 유일한 의미 있는 선택입니다. 하지만, doctest를 실행하는 함수에 옵션 플래그를 전달하여 다른 기본값을 설정할 수도 있습니다. 이럴 때, 지시자에서 -를 통해 옵션을 비활성화하는 것이 유용할 수 있습니다.

경고

doctest는 예상 출력에서 정확한 일치를 요구하는 것에 심각합니다. 단일 문자가 일치하지 않아도 테스트가 실패합니다. 여러분이 출력에 있어서 파이썬이 정확히 무엇을 보장하고 무엇을 보장하지 않는지 배워감에 따라, 이것은 아마도 여러분을 몇 번 놀라게 할 것입니다. 예를 들어, 집합을 인쇄할 때, 파이썬은 원소가 특정 순서로 인쇄되는 것을 보장하지 않으므로, 다음과 같은 테스트는

>>> foo()
{"Hermione", "Harry"}

취약합니다! 한 가지 해결 방법은 다음과 같습니다

>>> foo() == {"Hermione", "Harry"}
True

대신에. 또 다른 방법은

>>> d = sorted(foo())
>>> d
['Harry', 'Hermione']

참고

파이썬 3.6 이전에는, 딕셔너리를 인쇄할 때, 파이썬은 키-값 쌍이 특정 순서로 인쇄되는 것을 보증하지 않았습니다.

다른 것들도 있지만, 아마 아이디어를 얻었을 겁니다.

또 다른 나쁜 생각은 객체 주소를 포함하는 것들을 출력하는 것입니다

>>> id(1.0) # certain to fail some of the time
7948648
>>> class C: pass
>>> C()   # the default repr() for instances embeds an address
<__main__.C instance at 0x00AC18F0>

ELLIPSIS 지시자는 마지막 예제를 다루는 좋은 접근법을 제공합니다

>>> C()
<__main__.C instance at 0x...>

부동 소수점 숫자도 플랫폼에 따라 약간의 출력 변동이 있습니다. 파이썬이 float 포매팅을 플랫폼 C 라이브러리에 위임하고 있고, 이때 C 라이브러리의 품질이 크게 다르기 때문입니다.

>>> 1./7  # risky
0.14285714285714285
>>> print(1./7) # safer
0.142857142857
>>> print(round(1./7, 6)) # much safer
0.142857

I/2.**J 형식의 숫자는 모든 플랫폼에서 안전하며, 저는 종종 이런 형식의 숫자를 만들도록 doctest 예제를 꾸밉니다:

>>> 3./4  # utterly safe
0.75

간단한 분수는 또한 사람들이 이해하기가 더 쉬우므로, 더 좋은 설명서가 되도록 합니다.

기본 API

testmod()와 testfile() 함수는 대부분 기본 사용에 충분한 doctest에 대한 간단한 인터페이스를 제공합니다. 이 두 함수에 대한 덜 형식적인 소개는 섹션 간단한 사용법: 독스트링에 있는 예제 확인하기와 간단한 사용법: 텍스트 파일에 있는 예제 확인하기를 참조하십시오.

doctest.testfile(filename, module_relative=True, name=None, package=None, globs=None, verbose=None, report=True, optionflags=0, extraglobs=None, raise_on_error=False, parser=DocTestParser(), encoding=None)

filename를 제외한 모든 인자는 선택적이며 키워드 형식으로 지정해야 합니다.

filename 파일에 있는 예제를 테스트합니다. (failure_count, test_count)를 반환합니다.

선택적 인자 module_relative는 filename을 해석하는 방법을 지정합니다:

module_relative가 True(기본값)이면, filename는 OS 독립적 모듈 상대 경로를 지정합니다. 기본적으로, 이 경로는 호출하는 모듈의 디렉터리에 상대적입니다; 그러나 package 인자가 지정되면, 해당 패키지에 상대적입니다. OS 독립성을 보장하기 위해, filename은 / 문자를 사용하여 경로 세그먼트를 분리해야 하며, 절대 경로일 수 없습니다 (즉, /로 시작할 수 없습니다).

module_relative가 False이면, filename은 OS 특정 경로를 지정합니다. 경로는 절대나 상대일 수 있습니다; 상대 경로는 현재 작업 디렉터리를 기준으로 해석됩니다.

선택적 인자 name은 테스트의 이름을 제공합니다; 기본적으로, 또는 None이면, os.path.basename(filename)이 사용됩니다.

선택적 인자 package는 디렉터리가 모듈 상대 filename의 기본 디렉터리로 사용될 파이썬 패키지나 파이썬 패키지의 이름입니다. 패키지를 지정하지 않으면, 호출하는 모듈의 디렉터리가 모듈 상대 filename의 기본 디렉터리로 사용됩니다. module_relative가 False일 때 package를 지정하는 것은 에러입니다.

선택적 인자 globs는 예제를 실행할 때 전역으로 사용될 딕셔너리를 제공합니다. doctest를 위해 이 딕셔너리의 새 얕은 사본이 만들어지므로, 예제는 깨끗한 서판으로 시작합니다. 기본적으로, 또는 None이면, 새 빈 딕셔너리가 사용됩니다.

선택적 인자 extraglobs는 예제를 실행하는 데 사용되는 전역에 병합될 딕셔너리를 제공합니다. 이것은 dict.update()처럼 작동합니다: globs와 extraglobs에 공통 키가 있으면, extraglobs의 연관된 값이 병합된 딕셔너리에 나타납니다. 기본적으로, 또는 None이면, 추가 전역은 사용되지 않습니다. doctest의 매개 변수화를 허용하는 고급 기능입니다. 예를 들어, doctest는 클래스의 일반 이름을 사용하여 베이스 클래스용으로 작성할 수 있습니다, 그런 다음 일반 이름을 테스트할 서브 클래스에 매핑하는 extraglobs 딕셔너리를 전달하여 임의의 수의 서브 클래스를 테스트하는데 재사용할 수 있습니다.

선택적 인자 verbose가 참이면 많은 것들을 인쇄하고, 거짓이면 실패만 인쇄합니다; 기본적으로, 또는 None이면, '-v'가 sys.argv에 있을 때만 참입니다.

선택적 인자 report가 참이면 끝에 요약을 인쇄하고, 그렇지 않으면 끝에 아무것도 인쇄하지 않습니다. verbose 모드에서는 요약 정보가 상세히 표시되며, 그렇지 않으면 요약 정보는 매우 간단합니다 (사실, 모든 테스트가 통과되면 비어 있습니다).

선택적 인자 optionflags(기본값은 0)는 옵션 플래그의 비트별 OR를 취합니다. 옵션 플래그 절을 참조하십시오.

선택적 인자 raise_on_error의 기본값은 거짓입니다. 참이면, 예제에서 첫 번째 실패나 예기치 않은 예외가 발생할 때 예외가 발생합니다. 이것은 실패를 사후(post-mortem) 디버깅할 수 있도록 합니다. 기본 동작은 예제를 계속 실행하는 것입니다.

선택적 인자 parser는 파일에서 테스트를 추출하는 데 사용할 DocTestParser(또는 서브 클래스)를 지정합니다. 기본값은 일반 파서(즉, DocTestParser())입니다.

선택적 인자 encoding은 파일을 유니코드로 변환하는 데 사용할 인코딩을 지정합니다.

doctest.testmod(m=None, name=None, globs=None, verbose=None, report=True, optionflags=0, extraglobs=None, raise_on_error=False, exclude_empty=False)

모든 인자는 선택적이며, m을 제외한 모든 인자는 키워드 형식으로 지정해야 합니다.

모듈 m(또는 m가 제공되지 않았거나 None이면 모듈 __main__)에서 도달할 수 있는 함수와 클래스의 독스트링에 있는 예제를 테스트합니다. m.__doc__으로 시작합니다.

딕셔너리 m.__test__이 존재하고 None이 아니면, 여기에서 도달할 수 있는 예제도 테스트합니다. m.__test__는 이름(문자열)을 함수, 클래스 및 문자열에 매핑합니다; 함수와 클래스 독스트링에서 예제를 검색합니다; 문자열은 그것이 독스트링인 것처럼 직접 검색합니다.

모듈 m에 속하는 객체에 연결된 독스트링 만 검색합니다.

(failure_count, test_count)를 반환합니다.

선택적 인자 name은 모듈의 이름을 제공합니다; 기본적으로, 또는 None이면, m.__name__이 사용됩니다.

선택적 인자 exclude_empty의 기본값은 거짓입니다. 참이면, doctest가 발견되지 않은 객체는 고려 대상에서 제외됩니다. 기본값은 이전 버전과의 호환성을 위한 해킹입니다, 여전히 testmod()와 함께 doctest.master.summarize()를 사용하는 코드는 테스트가 없는 객체에 대해 계속 출력합니다. 새로운 DocTestFinder 생성자에 대한 exclude_empty 인자의 기본값은 참입니다.

선택적 인자 extraglobs, verbose, report, optionflags, raise_on_error 및 globs는 위의 함수 testfile()와 같습니다만, globs의 기본값이 m.__dict__인 점이 다릅니다.

doctest.run_docstring_examples(f, globs, verbose=False, name="NoName", compileflags=None, optionflags=0)

객체 f와 관련된 예제를 테스트합니다. 여기서, f는 문자열, 모듈, 함수 또는 클래스 객체일 수 있습니다.

딕셔너리 인자 globs의 얕은 사본이 실행 컨텍스트에 사용됩니다.

선택적 인자 name은 실패 메시지에서 사용되며, 기본값은 "NoName"입니다.

선택적 인자 verbose가 참이면, 실패가 없어도 출력이 생성됩니다. 기본적으로, 출력은 예제가 실패할 때만 생성됩니다.

선택적 인자 compileflags는 예제를 실행할 때 파이썬 컴파일러에서 사용해야 하는 플래그 집합을 제공합니다. 기본적으로, 또는 None이면, globs에서 발견되는 퓨처 기능 집합에 해당하는 플래그가 추론됩니다.

선택적 인자 optionflags는 위의 함수 testfile()에서 처럼 작동합니다.

Unittest API

doctest된 모듈 모음이 늘어남에 따라, 모든 doctest를 체계적으로 실행하는 방법이 필요합니다. doctest는 doctest가 포함된 모듈과 텍스트 파일로부터 unittest 테스트 스위트를 만드는 데 사용할 수 있는 두 가지 함수를 제공합니다. unittest 테스트 탐색과 통합하려면, 테스트 모듈에 load_tests() 함수를 포함하십시오:

import unittest
import doctest
import my_module_with_doctests

def load_tests(loader, tests, ignore):
    tests.addTests(doctest.DocTestSuite(my_module_with_doctests))
    return tests

Doctest가 있는 텍스트 파일과 모듈로부터 unittest.TestSuite 인스턴스를 만드는 두 가지 주요 함수가 있습니다:

doctest.DocFileSuite(*paths, module_relative=True, package=None, setUp=None, tearDown=None, globs=None, optionflags=0, parser=DocTestParser(), encoding=None)

하나 이상의 텍스트 파일로부터 doctest 테스트를 unittest.TestSuite로 변환합니다.

반환된 unittest.TestSuite는 unittest 프레임워크에 의해 실행되고, 각 파일에 있는 대화식 예제를 실행합니다. 어떤 파일의 예제가 실패하면, 합성된 단위 테스트가 실패하고, 테스트를 포함하는 파일의 이름과 (때로는 근사치인) 줄 번호를 보여주는 failureException 예외가 발생합니다.

검사할 텍스트 파일을 하나 이상의 paths(문자열)로 전달합니다.

옵션은 키워드 인자로 제공될 수 있습니다:

선택적 인자 module_relative는 paths에 있는 파일명을 해석하는 방법을 지정합니다:

module_relative가 True(기본값)이면, paths의 각 파일명은 OS 독립적 모듈 상대 경로를 지정합니다. 기본적으로, 이 경로는 호출하는 모듈의 디렉터리에 상대적입니다; 그러나 package 인자가 지정되면, 해당 패키지에 상대적입니다. OS 독립성을 보장하기 위해, 각 파일명은 / 문자를 사용하여 경로 세그먼트를 분리해야 하며, 절대 경로일 수 없습니다 (즉, /로 시작할 수 없습니다).

module_relative가 False이면, paths의 각 파일명은 OS 특정 경로를 지정합니다. 경로는 절대나 상대일 수 있습니다; 상대 경로는 현재 작업 디렉터리를 기준으로 해석됩니다.

선택적 인자 package는 디렉터리가 paths의 모듈 상대 파일명의 기본 디렉터리로 사용될 파이썬 패키지나 파이썬 패키지의 이름입니다. 패키지를 지정하지 않으면, 호출하는 모듈의 디렉터리가 모듈 상대 파일명의 기본 디렉터리로 사용됩니다. module_relative가 False일 때 package를 지정하는 것은 에러입니다.

선택적 인자 setUp은 테스트 스위트에 대한 사전 설정(set-up) 함수를 지정합니다. 이것은 각 파일에서 테스트를 실행하기 전에 호출됩니다. setUp 함수로 DocTest 객체가 전달됩니다. setUp 함수는 전달된 테스트의 globs 어트리뷰트를 통해 테스트 전역에 액세스할 수 있습니다.

선택적 인자 tearDown은 테스트 스위트에 사후 정리(tear-down) 함수를 지정합니다. 이것은 각 파일에서 테스트를 실행한 후에 호출됩니다. tearDown 함수로 DocTest 객체가 전달됩니다. tearDown 함수는 전달된 테스트의 globs 어트리뷰트를 통해 테스트 전역에 액세스할 수 있습니다.

선택적 인자 globs는 테스트의 초기 전역 변수를 포함하는 딕셔너리입니다. 이 딕셔너리의 새 사본이 테스트마다 만들어집니다. 기본적으로, globs는 새로운 빈 딕셔너리입니다.

선택적 인자 optionflags는 테스트에 대한 기본 doctest 옵션을 지정하는데, 개별 옵션 플래그를 함께 OR 해서 만들어집니다. 옵션 플래그 절을 참조하십시오. 보고(reporting) 옵션을 설정하는 더 좋은 방법은 아래 함수 set_unittest_reportflags()를 참조하십시오.

선택적 인자 parser는 파일에서 테스트를 추출하는 데 사용할 DocTestParser(또는 서브 클래스)를 지정합니다. 기본값은 일반 파서(즉, DocTestParser())입니다.

선택적 인자 encoding은 파일을 유니코드로 변환하는 데 사용할 인코딩을 지정합니다.

전역 __file__이 DocFileSuite()를 사용하여 텍스트 파일에서 로드된 doctest에 제공된 전역에 추가됩니다.

doctest.DocTestSuite(module=None, globs=None, extraglobs=None, test_finder=None, setUp=None, tearDown=None, checker=None)

모듈에 대한 doctest 테스트를 unittest.TestSuite로 변환합니다.

반환된 unittest.TestSuite는 unittest 프레임워크에 의해 실행되고, 모듈에 있는 각 doctest를 실행합니다. 어떤 doctest가 실패하면, 합성된 단위 테스트가 실패하고, 테스트를 포함하는 파일의 이름과 (때로는 근사치인) 줄 번호를 보여주는 failureException 예외가 발생합니다.

선택적 인자 module은 테스트할 모듈을 제공합니다. 모듈 객체나 (점으로 구분될 수 있는) 모듈 이름일 수 있습니다. 지정하지 않으면, 이 함수를 호출하는 모듈이 사용됩니다.

선택적 인자 globs는 테스트의 초기 전역 변수를 포함하는 딕셔너리입니다. 이 딕셔너리의 새 사본이 테스트마다 만들어집니다. 기본적으로, globs는 새로운 빈 딕셔너리입니다.

선택적 인자 extraglobs는 globs에 병합되는 전역 변수의 추가 집합을 지정합니다. 기본적으로, 추가 전역 변수는 사용되지 않습니다.

선택적 인자 test_finder는 모듈에서 doctest를 추출하는 데 사용되는 DocTestFinder 객체(또는 드롭 인 대체)입니다.

선택적 인자 setUp, tearDown 및 optionflags는 위의 함수 DocFileSuite()와 같습니다.

이 함수는 testmod()와 같은 검색 기법을 사용합니다.

버전 3.5에서 변경: module에 독스트링이 없으면 DocTestSuite()는 ValueError를 발생시키는 대신 빈 unittest.TestSuite를 반환합니다.

수면 아래에서, DocTestSuite()는 doctest.DocTestCase 인스턴스에서 unittest.TestSuite를 만들고, DocTestCase는 unittest.TestCase의 서브 클래스입니다. DocTestCase는 여기에서 설명되지는 않지만 (내부 세부 사항입니다), 그것의 코드를 살펴보면 unittest 통합의 정확한 세부 사항에 대한 질문에 대한 답을 얻을 수 있습니다.

마찬가지로, DocFileSuite()는 doctest.DocFileCase 인스턴스에서 unittest.TestSuite를 만들고, DocFileCase는 DocTestCase의 서브 클래스입니다.

따라서 unittest.TestSuite를 만드는 두 가지 방법 모두 DocTestCase의 인스턴스를 실행합니다. 이것은 미묘한 이유로 중요합니다: 여러분이 doctest 함수를 직접 실행할 때, 옵션 플래그를 doctest 함수에 전달하여 사용 중인 doctest 옵션을 직접 제어할 수 있습니다. 그러나, unittest 프레임워크를 작성한다면, unittest가 테스트가 언제 어떻게 실행되는지 궁극적으로 제어합니다. 프레임워크 저자는 일반적으로 doctest (아마도, 예를 들어, 명령 줄 옵션으로 지정하는) 보고(reporting) 옵션을 제어하려고 하지만, unittest를 통해 doctest 테스트 실행기로 옵션을 전달할 방법이 없습니다.

이러한 이유로, doctest는 unittest 지원에 특화된 doctest 보고(reporting) 플래그 개념을 다음 함수를 통해 지원합니다:

doctest.set_unittest_reportflags(flags)

사용할 doctest 보고 플래그를 설정합니다.

인자 flags는 옵션 플래그의 비트별 OR를 취합니다. 옵션 플래그 절을 참조하십시오. “보고 플래그”만 사용할 수 있습니다.

이것은 모듈 전역 설정이며, 모듈 unittest에 의해 실행되는 모든 미래의 doctest에 영향을 줍니다. DocTestCase의 runTest() 메서드는 DocTestCase 인스턴스가 생성될 때 테스트 케이스에 대해 지정된 옵션 플래그를 봅니다. 보고 플래그가 지정되지 않았으면 (이것이 일반적이고 예상되는 경우입니다), doctest의 unittest보고 플래그는 옵션 플래그에 비트별 OR되고, 이렇게 손질된 옵션 플래그가 doctest를 실행하기 위해 만들어진 DocTestRunner 인스턴스로 전달됩니다. DocTestCase 인스턴스가 생성될 때 보고 플래그가 지정되었으면, doctest의 unittest 보고 플래그는 무시됩니다.

함수가 호출되기 전에 유효했던 unittest 보고 플래그의 값이 함수에 의해 반환됩니다.

고급 API

기본 API는 doctest를 사용하기 쉽게 하기 위한 간단한 래퍼입니다. 그것은 매우 유연하며, 대부분 사용자의 요구를 충족시켜야 합니다; 그러나, 테스팅에 대한 세밀한 제어가 필요하거나, doctest의 기능을 확장하려면, 고급 API를 사용해야 합니다.

고급 API는 doctest 케이스에서 추출한 대화식 예제를 저장하는 데 사용되는 두 개의 컨테이너 클래스를 중심으로 돌아갑니다:

Example: 예상 출력과 쌍을 이루는 단일 파이썬 문장.

DocTest: 일반적으로 단일 독스트링이나 텍스트 파일에서 추출된 Example의 모음.

doctest 예제를 찾고, 구문 분석하고, 실행하고, 검사하기 위해 추가 처리 클래스가 정의됩니다:

DocTestFinder: 주어진 모듈에서 모든 독스트링을 찾고, DocTestParser를 사용하여 대화식 예제가 들어있는 모든 독스트링에서 DocTest를 만듭니다.

DocTestParser: 문자열(가령 객체의 독스트링)에서 DocTest 객체를 만듭니다.

DocTestRunner: DocTest에 있는 예제를 실행하고, OutputChecker를 사용하여 출력을 확인합니다.

OutputChecker: doctest 예제의 실제 출력을 예상 출력과 비교하고, 그들이 일치하는지 결정합니다.

이러한 처리 클래스 간의 관계는 다음 도표에 요약되어 있습니다:

                            list of:
+------+                   +---------+
|module| --DocTestFinder-> | DocTest | --DocTestRunner-> results
+------+    |        ^     +---------+     |       ^    (printed)
            |        |     | Example |     |       |
            v        |     |   ...   |     v       |
           DocTestParser   | Example |   OutputChecker
                           +---------+

DocTest 객체

class doctest.DocTest(examples, globs, name, filename, lineno, docstring)

단일 이름 공간에서 실행되어야 하는 doctest 예제의 모음. 생성자 인자는 같은 이름의 어트리뷰트를 초기화하는 데 사용됩니다.

DocTest는 다음 어트리뷰트를 정의합니다. 이들은 생성자에 의해 초기화되며, 직접 수정하면 안 됩니다.

examples

이 테스트가 실행해야 하는 개별 대화형 파이썬 예제를 인코딩하는 Example 객체의 리스트.

globs

예제가 실행되어야 하는 이름 공간 (일명 전역). 이름을 값에 매핑하는 딕셔너리입니다. 예제가 만든 이름 공간의 모든 변경 사항(가령 새 변수 바인딩)은 테스트가 실행된 후 globs에 반영됩니다.

name

DocTest를 식별하는 문자열 이름. 일반적으로, 테스트가 추출된 객체나 파일의 이름입니다.

filename

이 DocTest가 추출된 파일의 이름; 또는 파일 이름을 알 수 없거나 파일에서 DocTest가 추출되지 않았으면 None.

lineno

이 DocTest가 시작되는 filename 내의 줄 번호, 또는 줄 번호가 없으면 None. 이 줄 번호는 파일의 시작 부분을 기준으로 0에서 시작합니다.

docstring

테스트가 추출된 문자열, 또는 문자열이 없거나 테스트가 문자열에서 추출되지 않았으면 None.

Example 객체

class doctest.Example(source, want, exc_msg=None, lineno=0, indent=0, options=None)

파이썬 문장과 예상 출력으로 구성된 단일 대화형 예제. 생성자 인자는 같은 이름의 어트리뷰트를 초기화하는 데 사용됩니다.

Example는 다음 어트리뷰트를 정의합니다. 이들은 생성자에 의해 초기화되며, 직접 수정하면 안 됩니다.

source

예제의 소스 코드가 포함된 문자열. 이 소스 코드는 단일 파이썬 문으로 구성되며 항상 개행으로 끝납니다; 생성자는 필요하면 개행 문자를 추가합니다.

want

예제의 소스 코드를 실행할 때 (stdout이나 예외 발생 시 트레이스백으로부터) 예상되는 출력. want는 출력이 예상되지 않으면 빈 문자열이고, 그렇지 않으면 개행으로 끝납니다. 생성자는 필요하면 개행을 추가합니다.

exc_msg

예제가 예외를 생성할 것으로 예상되면, 예제에서 생성된 예외 메시지; 또는 예외를 생성할 것으로 예상되지 않으면 None. 이 예외 메시지는 traceback.format_exception_only()의 반환 값과 비교됩니다. exc_msg는 None이 아니면 개행으로 끝납니다. 생성자는 필요하면 개행을 추가합니다.

lineno

이 예제가 시작하는 이 예제를 포함하는 문자열 내의 줄 번호. 이 줄 번호는 포함하는 문자열의 시작 부분을 기준으로 0에서 시작합니다.

indent

포함하는 문자열 내에서의 이 예제의 들여쓰기, 즉 예제의 첫 번째 프롬프트 앞에 오는 스페이스 문자의 수.

options

옵션 플래그에서 True나 False 로 매핑하는 딕셔너리, 이 예제의 기본 옵션을 재정의하는 데 사용됩니다. 이 딕셔너리에 포함되지 않은 옵션 플래그는 (DocTestRunner의 optionflags에 지정된 대로) 기본값으로 남습니다. 기본적으로, 아무런 옵션도 설정되지 않습니다.

DocTestFinder 객체

class doctest.DocTestFinder(verbose=False, parser=DocTestParser(), recurse=True, exclude_empty=True)

주어진 객체에 관련된 DocTest를 그것의 독스트링과 그것이 포함하는 객체의 독스트링으로부터 추출하기 위해서 사용되는 처리 클래스. DocTest는 모듈, 클래스, 함수, 메서드, 정적 메서드, 클래스 메서드 및 프로퍼티에서 추출할 수 있습니다.

선택적 인자 verbose는 파인더가 검색한 객체를 표시하는 데 사용될 수 있습니다. 기본값은 False (출력 없음)입니다.

선택적 인자 parser는 독스트링에서 doctest를 추출하는 데 사용되는 DocTestParser 객체 (또는 드롭 인 대체)를 지정합니다.

선택적 인자 recurse가 거짓이면, DocTestFinder.find()는 오직 주어진 객체만을 검사 할 뿐, 포함된 객체는 검사하지 않습니다.

선택적 인자 exclude_empty가 거짓이면, DocTestFinder.find()는 빈 독스트링을 가진 객체에 대한 테스트를 포함합니다.

DocTestFinder는 다음 메서드를 정의합니다:

find(obj[, name][, module][, globs][, extraglobs])

obj의 독스트링이나 포함된 객체의 독스트링으로 정의된 DocTest의 리스트를 반환합니다.

선택적 인자 name은 객체의 이름을 지정합니다. 이 이름은 반환된 DocTest의 이름을 구성하는 데 사용됩니다. name이 지정되지 않으면, obj.__name__이 사용됩니다.

선택적 매개 변수 module은 주어진 객체를 포함하는 모듈입니다. 모듈이 지정되지 않거나 None이면, 테스트 파인더는 자동으로 올바른 모듈을 판별하려고 시도합니다. 객체의 모듈은 다음과 같이 사용됩니다:

globs가 지정되지 않으면, 기본 이름 공간으로.

DocTestFinder가 다른 모듈에서 임포트 된 객체에서 DocTest를 추출하지 못하도록 하려고. (module이 아닌 다른 모듈을 가진 포함 된 객체는 무시됩니다.)

객체를 포함하는 파일의 이름을 찾으려고.

해당 파일 내에서 객체의 줄 번호를 찾는 데 도움이 됩니다.

module이 False면, 모듈을 찾으려고 시도하지 않습니다. 이것은 눈에 띄지 않는데, 대부분 doctest 자체를 테스트할 때 사용합니다: module이 False이거나, None이지만 자동으로 찾을 수 없으면, 모든 객체는 (존재하지 않는) 모듈에 속한 것으로 간주하므로, 포함된 모든 객체에서 (재귀적으로) doctest를 검색합니다.

각 DocTest에 대한 전역은 globs와 extraglobs(extraglobs의 바인딩이 globs의 바인딩에 우선합니다)를 결합하여 구성됩니다. 각 DocTest마다 전역 딕셔너리의 새 얕은 복사본이 만들어집니다. globs를 지정하지 않으면, 기본값은 모듈이 지정되었다면 모듈의 __dict__, 또는 그렇지 않으면 {}입니다. extraglobs가 지정되지 않으면, 기본값은 {}입니다.

DocTestParser 객체

class doctest.DocTestParser

문자열에서 대화형 예제를 추출하고, 이를 사용하여 DocTest 객체를 만드는 데 사용되는 처리 클래스.

DocTestParser는 다음 메서드를 정의합니다:

get_doctest(string, globs, name, filename, lineno)

주어진 문자열에서 모든 doctest 예제를 추출하고, 이를 DocTest 객체로 모읍니다.

globs, name, filename 및 lineno는 새 DocTest 객체의 어트리뷰트입니다. 자세한 내용은 DocTest 설명서를 참조하십시오.

get_examples(string, name='<string>')

주어진 문자열에서 모든 doctest 예제를 추출하고, 이를 Example 객체의 리스트로 반환합니다. 줄 번호는 0부터 시작합니다. 선택적 인자 name은, 이 문자열을 식별하는 이름이며, 에러 메시지에만 사용됩니다.

parse(string, name='<string>')

주어진 문자열을 예제와 중간에 있는 텍스트로 나누고, 이를 Example와 문자열이 번갈아 나오는 리스트로 반환합니다. Example의 줄 번호는 0부터 시작합니다. 선택적 인자 name은, 이 문자열을 식별하는 이름이며, 에러 메시지에만 사용됩니다.

DocTestRunner 객체

class doctest.DocTestRunner(checker=None, verbose=None, optionflags=0)

DocTest에 있는 대화형 예제를 실행하고 검증하는 데 사용되는 처리 클래스.

예상 출력과 실제 출력 간의 비교는 OutputChecker에 의해 수행됩니다. 이 비교는 여러 옵션 플래그로 사용자 정의할 수 있습니다; 자세한 내용은 옵션 플래그 절을 참조하십시오. 옵션 플래그로 충분하지 않으면, OutputChecker의 서브 클래스를 생성자에 전달하여 비교를 사용자 정의할 수도 있습니다.

테스트 실행기의 디스플레이 출력은 두 가지 방법으로 제어할 수 있습니다. 첫째, 출력 함수를 TestRunner.run()로 전달할 수 있습니다; 이 함수는 표시되어야 하는 문자열로 호출됩니다. 기본값은 sys.stdout.write입니다. 출력을 캡처하는 것으로 충분하지 않으면, DocTestRunner를 서브 클래싱하고 report_start(), report_success(), report_unexpected_exception() 및 report_failure() 메서드를 재정의하여 디스플레이 출력을 사용자 정의할 수 있습니다.

선택적 키워드 인자 checker는 예상 출력을 doctest 예제의 실제 출력과 비교하는 데 사용되는 OutputChecker 객체(또는 드롭 인 대체)를 지정합니다.

선택적 키워드 인자 verbose는 DocTestRunner의 상세도를 제어합니다. verbose가 True이면, 실행될 때 각 예제에 대한 정보가 인쇄됩니다. verbose가 False이면, 실패만 인쇄됩니다. verbose가 지정되지 않거나 None이면, 명령 줄 스위치 -v가 사용될 때만 상세 출력이 사용됩니다.

선택적 키워드 인자 optionflags는 테스트 실행기가 예상 출력을 실제 출력과 비교하는 방법과 실패를 표시하는 방법을 제어하는 데 사용할 수 있습니다. 자세한 내용은 옵션 플래그 절을 참조하십시오.

DocTestParser는 다음 메서드를 정의합니다:

report_start(out, test, example)

테스트 러너가 주어진 예제를 처리하려고 한다고 보고합니다. 이 메서드는 DocTestRunner의 서브 클래스가 출력을 사용자 정의할 수 있도록 제공됩니다; 직접 호출해서는 안 됩니다.

example은 처리될 예제입니다. test는 예제를 포함하는 테스트입니다. out은 DocTestRunner.run()에 전달된 출력 함수입니다.

report_success(out, test, example, got)

주어진 예제가 성공적으로 실행되었음을 보고합니다. 이 메서드는 DocTestRunner의 서브 클래스가 출력을 사용자 정의할 수 있도록 제공됩니다; 직접 호출해서는 안 됩니다.

example은 처리될 예제입니다. got은 예제의 실제 출력입니다. test는 example을 포함하는 테스트입니다. out은 DocTestRunner.run()에 전달된 출력 함수입니다.

report_failure(out, test, example, got)

주어진 예제가 실패했음을 보고합니다. 이 메서드는 DocTestRunner의 서브 클래스가 출력을 사용자 정의할 수 있도록 제공됩니다; 직접 호출해서는 안 됩니다.

example은 처리될 예제입니다. got은 예제의 실제 출력입니다. test는 example을 포함하는 테스트입니다. out은 DocTestRunner.run()에 전달된 출력 함수입니다.

report_unexpected_exception(out, test, example, exc_info)

주어진 예제가 예기치 않은 예외를 발생시켰다고 보고합니다. 이 메서드는 DocTestRunner의 서브 클래스가 출력을 사용자 정의할 수 있도록 제공됩니다; 직접 호출해서는 안 됩니다.

example은 처리될 예제입니다. exc_info는 예기치 않은 예외에 대한 정보를 포함하는 튜플입니다 (sys.exc_info()에 의해 반환되는 것). test는 example을 포함하는 테스트입니다. out은 DocTestRunner.run()에 전달된 출력 함수입니다.

run(test, compileflags=None, out=None, clear_globs=True)

test(DocTest 객체)에 있는 예제를 실행하고, 출력 함수 out을 사용하여 결과를 표시합니다.

예제는 이름 공간 test.globs에서 실행됩니다. clear_globs가 참(기본값)이면, 가비지 수집을 돕기 위해 테스트가 실행된 후 이 이름 공간이 지워집니다. 테스트가 완료된 후에 이름 공간을 검사하려면 clear_globs=False를 사용하십시오.

compileflags는 예제를 실행할 때 파이썬 컴파일러에서 사용해야 하는 플래그 집합을 제공합니다. 지정되지 않으면, globs에 적용되는 퓨처-임포트 플래그 집합이 기본값이 됩니다.

각 예제의 출력은 DocTestRunner의 출력 검사기를 사용하여 검사되며, 결과는 DocTestRunner.report_*() 메서드로 포맷됩니다.

summarize(verbose=None)

이 DocTestRunner가 실행 한 모든 테스트 케이스의 요약을 인쇄하고, 네임드 튜플 TestResults(failed, attempted)를 반환합니다.

선택적 verbose 인자는 요약이 얼마나 상세할지를 제어합니다. 상세도가 지정되지 않으면, DocTestRunner의 상세도가 사용됩니다.

OutputChecker 객체

class doctest.OutputChecker

A class used to check the whether the actual output from a doctest example matches the expected output. OutputChecker defines two methods: check_output(), which compares a given pair of outputs, and returns True if they match; and output_difference(), which returns a string describing the differences between two outputs.

OutputChecker는 다음 메서드를 정의합니다:

check_output(want, got, optionflags)

예제의 실제 출력(got)이 예상 출력(want)과 일치할 때만 True를 반환합니다. 이 문자열은 같으면 항상 일치하는 것으로 간주합니다; 그러나 테스트 실행기가 사용하는 옵션 플래그에 따라 몇 가지 정확하지 않은 일치 유형도 가능합니다. 옵션 플래그에 대한 자세한 정보는 옵션 플래그 절을 참조하십시오.

output_difference(example, got, optionflags)

주어진 예제(example)에 대한 예상 출력과 실제 출력(got)의 차이를 설명하는 문자열을 반환합니다. optionflags는 want와 got을 비교하는 데 사용되는 옵션 플래그 집합입니다.

디버깅

Doctest는 doctest 예제를 디버깅하기 위한 몇 가지 메커니즘을 제공합니다:

몇몇 함수는 doctest를 파이썬 디버거 pdb에서 실행할 수 있는 실행 가능한 파이썬 프로그램으로 변환합니다.

DebugRunner 클래스는 첫 번째 실패한 예제에 대한 예외를 발생시키는 DocTestRunner의 서브 클래스이며 해당 예제에 대한 정보가 들어 있습니다. 이 정보는 예제에서 사후 디버깅을 수행하는 데 사용될 수 있습니다.

DocTestSuite()에 의해 생성된 unittest 케이스는 unittest.TestCase에 의해 정의된 debug() 메서드를 지원합니다.

doctest 예제에 pdb.set_trace()에 대한 호출을 추가 할 수 있습니다. 그러면 해당하는 줄이 실행될 때 파이썬 디버거로 들어갑니다. 그런 다음 변수의 현재 값을 검사하는 등의 일을 할 수 있습니다. 예를 들어, a.py가 다음과 같은 모듈 독스트링을 포함한다고 가정합시다:

"""
>>> def f(x):
...     g(x*2)
>>> def g(x):
...     print(x+3)
...     import pdb; pdb.set_trace()
>>> f(3)
9
"""

그러면 대화형 파이썬 세션은 이런 식이 됩니다:

>>> import a, doctest
>>> doctest.testmod(a)
--Return--
> <doctest a[1]>(3)g()->None
-> import pdb; pdb.set_trace()
(Pdb) list
  1     def g(x):
  2         print(x+3)
  3  ->     import pdb; pdb.set_trace()
[EOF]
(Pdb) p x
6
(Pdb) step
--Return--
> <doctest a[0]>(2)f()->None
-> g(x*2)
(Pdb) list
  1     def f(x):
  2  ->     g(x*2)
[EOF]
(Pdb) p x
3
(Pdb) step
--Return--
> <doctest a[2]>(1)?()->None
-> f(3)
(Pdb) cont
(0, 3)
>>>

Doctest를 파이썬 코드로 변환하고, 디버거에서 합성 코드를 실행할 수 있는 함수들:

doctest.script_from_examples(s)

예제가 있는 텍스트를 스크립트로 변환합니다.

인자 s는 doctest 예제를 포함하는 문자열입니다. 문자열은 파이썬 스크립트로 변환됩니다. 여기서 s의 doctest 예제는 일반 코드로 변환되고, 나머지는 파이썬 주석으로 변환됩니다. 생성된 스크립트는 문자열로 반환됩니다. 예를 들어,

import doctest
print(doctest.script_from_examples(r"""
    Set x and y to 1 and 2.
    >>> x, y = 1, 2

    Print their sum:
    >>> print(x+y)
    3
"""))

는 다음과 같이 출력합니다:

# Set x and y to 1 and 2.
x, y = 1, 2
#
# Print their sum:
print(x+y)
# Expected:
## 3

이 함수는 다른 함수(아래 참조)에서 내부적으로 사용되지만, 대화형 파이썬 세션을 파이썬 스크립트로 변환하려고 할 때도 유용합니다.

doctest.testsource(module, name)

객체에 대한 doctest를 스크립트로 변환합니다.

인자 module은 doctest가 관심 대상인 객체를 포함하는 모듈 객체나 모듈의 점으로 구분된 이름입니다. 인자 name은 doctest가 관심 대상인 객체의 (모듈 내에서의) 이름입니다. 결과는 위의 script_from_examples()에서 설명한 대로 파이썬 스크립트로 변환된 객체의 독스트링을 포함하는 문자열입니다. 예를 들어, 모듈 a.py에 최상위 함수 f()가 포함되었다면,

import a, doctest
print(doctest.testsource(a, "a.f"))

는 doctest가 코드로 변환되고 나머지는 주석으로 배치된, 함수 f()의 독스트링의 스크립트 버전을 인쇄합니다.

doctest.debug(module, name, pm=False)

객체의 doctest를 디버그합니다.

module과 name 인자는 위의 함수 testsource()와 같습니다. 명명된 객체의 독스트링에 대한 합성된 파이썬 스크립트가 임시 파일에 기록되고, 그 파일을 파이썬 디버거 pdb의 제어하에 실행합니다.

module.__dict__의 얕은 사본이 지역과 전역 실행 컨텍스트 모두에 사용됩니다.

선택적 인자 pm은 사후 디버깅이 사용되는지를 제어합니다. pm이 참값이면, 스크립트 파일은 직접 실행되고, 처리되지 않은 예외를 발생시켜 스크립트가 종료될 때만 디버거가 개입합니다. 그럴 때, 사후 디버깅이 pdb.post_mortem()를 통해 호출되어, 처리되지 않은 예외로부터 온 트레이스백 객체를 전달합니다. pm이 지정되지 않았거나 거짓이면, 스크립트는 적절한 exec() 호출을 pdb.run()에 전달하여 시작부터 디버거에서 실행됩니다.

doctest.debug_src(src, pm=False, globs=None)

문자열에 있는 doctest를 디버그합니다.

doctest 예제를 포함하는 문자열이 src 인자를 통해 직접 지정된다는 점을 제외하면, 위의 함수 debug()과 같습니다.

선택적 인자 pm은 위의 함수 debug()에서와 같은 의미를 가집니다.

선택적 인자 globs는 지역과 전역 실행 컨텍스트 모두에 사용할 딕셔너리를 제공합니다. 지정되지 않거나 None이면, 빈 딕셔너리가 사용됩니다. 지정되면, 딕셔너리의 얕은 사본이 사용됩니다.

DebugRunner 클래스와 이 클래스가 발생시킬 수 있는 특별한 예외는 주로 테스트 프레임워크 작성자가 관심을 가지며, 여기에서는 대략적으로만 다룰 예정입니다. 자세한 내용은 소스 코드, 특히 DebugRunner의 독스트링(doctest입니다!)을 참조하십시오:

class doctest.DebugRunner(checker=None, verbose=None, optionflags=0)

실패를 만나자마자 예외를 발생시키는 DocTestRunner의 서브 클래스. 예기치 않은 예외가 발생하면, 테스트, 예제 및 원래 예외가 포함된 UnexpectedException 예외가 발생합니다. 출력이 일치하지 않으면, 테스트, 예제 및 실제 출력을 포함하는 DocTestFailure 예외가 발생합니다.

생성자 매개 변수와 메서드에 대한 자세한 내용은 고급 API 절의 DocTestRunner 설명서를 참조하십시오.

DebugRunner 인스턴스가 발생시킬 수 있는 두 가지 예외가 있습니다:

exception doctest.DocTestFailure(test, example, got)

doctest 예제의 실제 출력이 예상 출력과 일치하지 않는다는 것을 알리기 위해 DocTestRunner가 발생시키는 예외. 생성자 인자는 같은 이름의 어트리뷰트를 초기화하는 데 사용됩니다.

DocTestFailure는 다음 어트리뷰트를 정의합니다:

DocTestFailure.test

예제가 실패했을 때 실행 중이던 DocTest 객체.

DocTestFailure.example

실패한 Example.

DocTestFailure.got

예제의 실제 출력.

exception doctest.UnexpectedException(test, example, exc_info)

doctest 예제가 예기치 않은 예외를 발생시켰음을 알리기 위해 DocTestRunner가 발생시키는 예외. 생성자 인자는 같은 이름의 어트리뷰트를 초기화하는 데 사용됩니다.

UnexpectedException는 다음 어트리뷰트를 정의합니다:

UnexpectedException.test

예제가 실패했을 때 실행 중이던 DocTest 객체.

UnexpectedException.example

실패한 Example.

UnexpectedException.exc_info

sys.exc_info()에 의해 반환되는 것과 같은, 예기치 않은 예외에 대한 정보가 포함된 튜플.

맺음말

소개에서 언급했듯이, doctest는 다음 세 가지 주요 용도로 성장했습니다:

독스트링에 있는 예제 검사.

회귀 테스트.

실행 가능한 문서/문학적(literate) 테스트.

이러한 용도들은 다른 요구 사항을 가지며, 이를 구별하는 것이 중요합니다. 특히, 모호한 테스트 케이스로 독스트링을 채우는 것은 나쁜 설명서를 만듭니다.

독스트링을 작성할 때, 독스트링 예제를 주의해서 선택하십시오. 여기에는 배울 필요가 있는 기술이 있습니다—처음에는 자연스럽지 않을 수도 있습니다. 예제는 설명서에 진짜 가치를 부여해야 합니다. 좋은 예제는 종종 많은 단어의 가치가 있습니다. 주의 깊게 작업 된다면, 예제는 사용자에게 매우 가치 있을 것이며, 몇 년이 지나고 변함에 따라 여러 번 수집하는 데 드는 시간을 갚을 것입니다. 제 doctest 예제 중 하나가 “해가 없는” 변경 후에 얼마나 자주 작동을 멈추는지 지금도 놀라울 뿐입니다.

Doctest는 회귀 테스트를 위한 훌륭한 도구도 제공합니다. 특히 설명 텍스트를 생략하지 않는다면 더욱더 그렇습니다. 설명과 예제를 번갈아 보여줌으로써, 실제로 무엇이 왜 테스트 되는지를 추적하기가 훨씬 쉬워집니다. 테스트가 실패할 때, 좋은 설명은 문제가 무엇인지, 어떻게 고쳐야 하는지를 쉽게 파악할 수 있게 해줍니다. 코드 기반 테스트에 광범위한 주석을 쓸 수는 있는 것은 사실이지만, 그렇게 하는 프로그래머는 거의 없습니다. 많은 사람이 doctest 접근법을 사용하는 것이 훨씬 더 명확한 테스트를 유도한다는 것을 발견했습니다. 어쩌면 단순히 doctest가 설명을 작성하는 것을 코드를 작성하는 것보다 조금 더 쉽게 만들고, 코드에 주석을 쓰는 것이 조금 더 어렵기 때문일 것입니다. 저는 단지 그것보다는 더 깊이 들어간다고 생각합니다: doctest 기반 테스트를 작성할 때의 자연스러운 태도는 소프트웨어의 미세한 포인트를 설명하고 그것을 예제로 보여주는 것입니다. 이것은 자연스럽게 가장 간단한 기능으로 시작하고, 복잡하고 지엽적인 경우까지 논리적으로 진행되는 테스트 파일로 이어집니다. 무작위로 보이는 격리된 기능 조각을 테스트하는 격리된 함수들의 모음 대신에, 일관된 내러티브가 얻어집니다. 이것은 다른 태도이며, 테스트와 설명의 구별을 모호하게 하면서 다른 결과를 낳습니다.

회귀 테스트는 전용 객체나 파일로 제한하는 것이 가장 좋습니다. 테스트 구성을 위한 몇 가지 옵션이 있습니다.:

대화형 예제로 테스트 케이스가 들어있는 텍스트 파일을 작성하고, testfile()이나 DocFileSuite()를 사용하여 파일을 테스트하십시오. doctest를 처음부터 사용하도록 고안된 새로운 프로젝트에서 가장 쉬운 방법이지만, 이 방법을 권장합니다.

명명된 주제에 대한 테스트 케이스를 포함하는 단일 독스트링으로 구성된 _regrtest_topic이라는 함수를 정의하십시오. 이 함수들은 모듈과 같은 파일에 포함되거나 별도의 테스트 파일로 분리될 수 있습니다.

회귀 테스트 주제에서 테스트 케이스가 포함된 독스트링에 대한 __test__ 딕셔너리 매핑을 정의하십시오.

테스트를 모듈에 배치할 때, 모듈 자체가 테스트 실행기가 될 수 있습니다. 테스트가 실패할 때, 문제를 디버깅하는 동안 실패한 doctest 만 다시 실행하도록 테스트 실행기를 조정할 수 있습니다. 다음은 그러한 테스트 실행기의 최소 예입니다:

if __name__ == '__main__':
    import doctest
    flags = doctest.REPORT_NDIFF|doctest.FAIL_FAST
    if len(sys.argv) > 1:
        name = sys.argv[1]
        if name in globals():
            obj = globals()[name]
        else:
            obj = __test__[name]
        doctest.run_docstring_examples(obj, globals(), name=name,
                                       optionflags=flags)
    else:
        fail, total = doctest.testmod(optionflags=flags)
        print("{} failures out of {} tests".format(fail, total))

각주

1

예상 출력과 예외를 모두 포함하는 예제는 지원되지 않습니다. 어디에서 하나가 끝나고 다른 하나가 시작되는지 추측하는 것은 너무 에러가 발생하기 쉽고, 이것은 또한 혼란스러운 테스트를 만들게 됩니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

개발 도구 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

개발 도구 »

|

unittest — 단위 테스트 프레임워크

소스 코드: Lib/unittest/__init__.py [https://github.com/python/cpython/tree/3.7/Lib/unittest/__init__.py]

(당신이 이미 테스트 기본 개념에 친숙하다면, assert 메서드 목록으로 건너뛰어도 좋습니다.)

unittest 단위 테스트 프레임워크는 본래 JUnit으로부터 영감을 받고 다른 언어의 주요 단위 테스트 프레임워크와 비슷한 특징을 가지고 있습니다. 이것은 테스트 자동화, 테스트를 위한 사전 설정(setup)과 종료(shutdown) 코드 공유, 테스트를 컬렉션에 종합하기, 테스트와 리포트 프레임워크의 분리 등을 지원합니다.

이를 달성하기 위해 unittest는 객체 지향적인 방법으로 몇 가지 중요한 개념을 지원합니다.

테스트 픽스쳐

테스트 픽스쳐 (test fixture)는 1개 또는 그 이상의 테스트를 수행할 때 필요한 준비와 그와 관련된 정리 동작에 해당합니다. 예를 들어 이것은 임시 또는 프락시 데이터베이스, 디렉터리를 생성하거나 서버 프로세스를 시작하는 것 등을 포함합니다.

테스트 케이스

테스트 케이스(test case)는 테스트의 개별 단위입니다. 이것은 특정한 입력 모음에 대해서 특정한 결과를 확인합니다. unittest는 베이스 클래스인 TestCase를 지원합니다. 이 클래스는 새로운 테스트 케이스를 만드는 데 사용됩니다.

테스트 묶음

테스트 묶음(test suite)은 여러 테스트 케이스, 테스트 묶음, 또는 둘 다의 모임입니다. 이것은 서로 같이 실행되어야 할 테스트들을 종합하는 데 사용됩니다.

테스트 실행자

테스트 실행자(test runner)는 테스트 실행을 조율하고 테스트 결과를 사용자에게 제공하는 역할을 하는 컴포넌트입니다. 실행자는 테스트 실행 결과를 보여주기 위해 그래픽 인터페이스, 텍스트 인터페이스를 사용하거나 특별한 값을 반환할 수도 있습니다.

더 보기

doctest 모듈

매우 다른 특징을 가지고 있는 또 다른 테스트 지원 모듈

Simple Smalltalk Testing: With Patterns [https://web.archive.org/web/20150315073817/http://www.xprogramming.com/testfram.htm]

unittest에 영향을 준 Kent Beck의 패턴을 사용한 테스트 프레임워크 원본 논문

pytest [https://docs.pytest.org/]

Third-party unittest framework with a lighter-weight syntax for writing tests. For example, assert func(10) == 42.

파이썬 테스트 도구 분류 [https://wiki.python.org/moin/PythonTestingToolsTaxonomy]

함수형 테스트 프레임워크와 모의 객체 라이브러리를 포함한 광범위한 파이썬 테스트 도구 목록

Testing in Python 메일링 리스트 [http://lists.idyll.org/listinfo/testing-in-python]

파이썬에서 테스트하기와 테스트 도구에 대해 논의하는 특정-주제-그룹(special-interest-group)

파이썬 소스 배포판에 있는 Tools/unittestgui/unittestgui.py 스크립트는 테스트 탐색 및 실행을 위한 GUI 도구입니다. 이것은 단위 테스트가 처음인 사람들이 쉽게 사용할 수 있도록 만들어졌습니다. 라이브 환경에서는 Buildbot [https://buildbot.net/], Jenkins [https://jenkins.io/] 또는 Hudson [http://hudson-ci.org/]과 같은 지속적인 통합 시스템을 이용하여 테스트가 이루어지길 추천합니다.

기본 예시

unittest 모듈은 테스트를 구성하고 실행하는 데 풍부한 도구 모음을 제공하고 있습니다. 이 절에서는 대부분 사용자의 요구를 충족시키기 위해 일부 도구 모음만으로도 충분하다는 것을 보여줍니다.

문자열 관련된 3개의 메서드를 테스트하기 위한 짧은 스크립트가 여기에 있습니다:

import unittest

class TestStringMethods(unittest.TestCase):

    def test_upper(self):
        self.assertEqual('foo'.upper(), 'FOO')

    def test_isupper(self):
        self.assertTrue('FOO'.isupper())
        self.assertFalse('Foo'.isupper())

    def test_split(self):
        s = 'hello world'
        self.assertEqual(s.split(), ['hello', 'world'])
        # check that s.split fails when the separator is not a string
        with self.assertRaises(TypeError):
            s.split(2)

if __name__ == '__main__':
    unittest.main()

테스트 케이스는 unittest.TestCase를 서브 클래스 해서 생성하였습니다. 각각 3개의 테스트는 test 글자로 시작하는 이름을 가진 메서드로 정의했습니다. 이 명명 규칙은 테스트 실행자가 어떤 메서드가 테스트인지 알게 해줍니다.

각 테스트의 핵심은 기대되는 결과를 확인하기 위해 assertEqual()를 호출, 조건을 검증하기 위해 assertTrue() 또는 assertFalse()를 호출, 특정 예외가 발생했는지 검증하기 위해 assertRaises()를 호출하는 것입니다. assert 문장을 대신하여 이 메서드들을 사용하면 테스트 실행자가 모든 테스트 결과를 취합하여 리포트를 생성할 수 있습니다.

setUp()과 tearDown() 메서드로 각각의 테스트 메서드 전과 후에 실행될 명령어를 정의할 수 있습니다. 테스트 코드 구조 잡기에서 이것을 더 자세히 다루겠습니다.

마지막 블록은 테스트를 실행하는 간단한 방법을 보여줍니다. unittest.main()은 테스트 스크립트에 명령행 인터페이스를 제공합니다. 명령행에서 위 스크립트를 실행하면, 다음과 같은 출력이 나옵니다:

...
----------------------------------------------------------------------
Ran 3 tests in 0.000s

OK

-v 옵션을 테스트 스크립트에 넘겨주게 되면 unittest.main()은 높은 상세도(verbosity)를 설정하여 그에 따른 출력이 나옵니다:

test_isupper (__main__.TestStringMethods) ... ok
test_split (__main__.TestStringMethods) ... ok
test_upper (__main__.TestStringMethods) ... ok

----------------------------------------------------------------------
Ran 3 tests in 0.001s

OK

위의 예시는 unittest에서 가장 자주 사용되는 기능을 보여주며 이것은 많은 일상적인 테스트 요구 사항을 충족시키기에 충분합니다. 문서의 나머지 부분은 기초부터 시작해서 모든 기능을 살펴봅니다.

명령행 인터페이스

unittest 모듈은 명령행을 사용하여 모듈, 클래스, 심지어 각 테스트 메서드의 테스트들을 실행할 수 있습니다:

python -m unittest test_module1 test_module2
python -m unittest test_module.TestClass
python -m unittest test_module.TestClass.test_method

모듈 이름이나 완전히 정규화된 클래스나 메서드 이름이 포함된 목록을 전달할 수 있습니다.

테스트 모듈은 파일 경로로도 지정할 수 있습니다:

python -m unittest tests/test_something.py

이것으로 테스트 모듈을 지정할 때 셸(shell)의 파일 이름 완성 기능을 사용할 수 있습니다. 지정된 파일은 반드시 모듈로 임포트 가능해야 합니다. 파일 경로는 ‘.py’ 가 빠지면서 모듈 이름으로 변경되고 경로 구분자도 ‘.’로 변경됩니다. 만약 당신이 임포트 가능하지 않은 테스트 파일을 모듈로 사용하고 싶으시다면 이 방법 대신에 그 파일을 직접 실행해야 합니다.

-v 옵션을 사용하여 더 자세한 정보(높은 상세도)로 테스트를 실행할 수 있습니다:

python -m unittest -v test_module

아무 인자 없이 실행하면 테스트 탐색(Discovery)이 실행됩니다:

python -m unittest

모든 명령행 옵션 목록을 보기:

python -m unittest -h

버전 3.2에서 변경: 이전 버전에서는 개별 테스트 메서드만 실행이 가능했고, 모듈과 클래스는 불가능했습니다.

명령행 옵션

unittest는 다음과 같은 명령행 옵션을 제공합니다:

-b, --buffer

테스트가 실행될 동안 표준 출력과 표준 에러 스트림이 버퍼링 됩니다. 통과한 테스트 중에 나온 출력은 버려집니다. 보통 테스트 실패나 에러에서 나온 출력은 표시되고 실패 메시지에 추가됩니다.

-c, --catch

테스트 실행 중에 Control-C를 누르면 현재 테스트가 끝날 때까지 기다린 다음 지금까지의 모든 결과를 보고합니다. Control-C를 다시 누르면 일반적인 KeyboardInterrupt 예외를 발생합니다.

이 기능과 관련된 함수는 시그널 처리하기를 참고하십시오.

-f, --failfast

첫 번째 에러나 실패가 발생하면 테스트 실행을 중단합니다.

-k

패턴이나 부분 문자열과 일치하는 테스트 메서드나 클래스만 실행합니다. 이 옵션은 여러 번 사용될 수 있습니다. 이 경우 주어진 패턴과 일치하는 모든 테스트 케이스가 포함됩니다.

와일드카드 문자(*)를 포함한 패턴은 fnmatch.fnmatchcase()를 사용하여 그에 일치하는 테스트 이름을 찾고; 그렇지 않은 경우 단순히 대소문자를 구별하는 부분 문자열 일치가 사용됩니다.

패턴을 테스트 로더가 임포트한 완전히 정규화된 테스트 메서드 이름과 대조합니다.

예를 들어 -k foo는 foo_tests.SomeTest.test_something, bar_tests.SomeTest.test_foo에 일치하지만, bar_tests.FooTest.test_something에는 일치하지 않습니다.

--locals

트레이스백(traceback)에서 지역 변수를 표시합니다.

버전 3.2에 추가: 명령행 옵션인 -b, -c, -f가 추가되었습니다.

버전 3.5에 추가: 명령행 옵션 --locals.

버전 3.7에 추가: 명령행 옵션 -k.

명령행은 프로젝트의 모든 테스트 또는 일부분의 테스트 탐색을 위해서도 사용할 수 있습니다.

테스트 탐색(Discovery)

버전 3.2에 추가.

unittest는 간단한 테스트 탐색을 지원합니다. 테스트 탐색에 호환되기 위해서는 모든 테스트 파일은 반드시 프로젝트의 가장 상위 디렉터리로부터 모듈 또는 패키지(이름 공간 패키지 포함)로 임포트 가능해야 합니다(이 말은 파일 이름이 반드시 유효한 식별자이어야 한다는 뜻입니다).

테스트 탐색은 TestLoader.discover()로 구현되어 있습니다, 그러나 명령행으로 사용할 수도 있습니다. 기본적인 명령행 사용법은 다음과 같습니다:

cd project_directory
python -m unittest discover

참고

단축형인 python -m unittest는 python -m unittest discover와 같습니다. 테스트 탐색에 인자를 전달하고 싶을 때는 discover 부속 명령어(sub-command)를 명시적으로 사용해야 합니다.

discover 부-명령어는 다음과 같은 옵션을 가지고 있습니다:

-v, --verbose

상세한 출력

-s, --start-directory directory

탐색을 시작할 디렉터리(기본값 .)

-p, --pattern pattern

테스트 파일을 검색할 패턴(기본값 test*.py)

-t, --top-level-directory directory

프로젝트의 최상위 디렉터리(기본값 시작 디렉터리)

-s, -p, -t 옵션은 이 순서대로 위치 인자로서 사용할 수 있습니다. 다음 2개의 명령행은 같습니다:

python -m unittest discover -s project_directory -p "*_test.py"
python -m unittest discover project_directory "*_test.py"

경로가 사용되는 곳에 패키지 이름을 전달하는 것도 가능합니다, 예를 들어 myproject.subpackage.test를 시작 디렉터리로 사용할 수 있습니다. 주어진 패키지 이름은 임포트되어 그것의 파일 시스템상의 위치를 시작 디렉터리로 사용하게 됩니다.

조심

테스트 탐색은 테스트를 임포트하여 로드합니다. 테스트 탐색이 당신이 지정한 시작 디렉터리로부터 모든 테스트 파일을 찾았다면 임포트하기 위해 그 파일 경로를 패키지 이름으로 바꿉니다. 예를 들어 foo/bar/baz.py는 foo.bar.baz로 임포트될 것입니다.

만약 당신이 전역적으로 설치된 패키지가 있고 테스트 탐색을 다른 패키지 복사본에 하려고 시도한다면 임포트가 잘못된 위치에서 발생할 수도 있습니다. 만약 이런 일이 발생한다면 테스트 탐색은 경고하고 종료될 것입니다.

만약 당신이 시작 디렉터리로 경로가 아닌 패키지 이름을 전달했다면 테스트 탐색은 임포트가 어느 경로로부터 되었든 간에 당신이 의도한 경로라고 간주하여 경고를 발생하지 않을 것입니다.

테스트 모듈과 패키지는 load_tests 프로토콜을 통하여 테스트 로드와 탐색을 사용자 정의할 수 있습니다.

버전 3.4에서 변경: 테스트 탐색은 이름 공간 패키지를 지원합니다.

테스트 코드 구조 잡기

단위 테스트의 기본 구성 블록은 테스트 케이스(test cases) — 정확성을 위해 설정되고 확인될 하나의 시나리오입니다. unittest에서 테스트 케이스는 unittest.TestCase 인스턴스에 해당합니다. 당신만의 테스트 케이스를 만들기 위해서는 TestCase의 서브 클래스를 작성하거나 FunctionTestCase를 사용해야 합니다.

TestCase 인스턴스의 테스트 코드는 완전히 독립적으로 되어 있어야 합니다, 그래야지 이것을 각각 단독으로 실행하거나 다른 여러 테스트 케이스와 함께 임의의 조합으로 실행할 수 있습니다.

가장 간단한 TestCase의 서브 클래스는 특정 테스트 코드를 수행하도록 단순히 테스트 메서드(즉 test로 이름이 시작하는 함수)를 구현하는 것입니다:

import unittest

class DefaultWidgetSizeTestCase(unittest.TestCase):
    def test_default_widget_size(self):
        widget = Widget('The widget')
        self.assertEqual(widget.size(), (50, 50))

어떤 것을 테스트하기 위해서는 TestCase 베이스 클래스에서 제공하는 assert*() 메서드 중 한 개를 사용합니다. 테스트가 실패한다면 그 이유를 설명한 메시지가 포함된 예외가 발생합니다, 그리고 unittest는 해당 테스트 케이스를 실패(failure)로 취급합니다. 다른 모든 예외는 에러(errors)로 취급합니다.

테스트는 매우 많지만, 그것을 위한 사전 설정은 계속 반복될 수 있습니다. 다행히, setUp()이란 메서드를 작성하여 사전 설정 코드를 밖으로 분리해낼 수 있습니다. 테스트 프레임워크가 1개의 테스트마다 매번 자동으로 이것을 호출할 것입니다:

import unittest

class WidgetTestCase(unittest.TestCase):
    def setUp(self):
        self.widget = Widget('The widget')

    def test_default_widget_size(self):
        self.assertEqual(self.widget.size(), (50,50),
                         'incorrect default size')

    def test_widget_resize(self):
        self.widget.resize(100,150)
        self.assertEqual(self.widget.size(), (100,150),
                         'wrong size after resize')

참고

다양한 테스트가 실행될 순서는 테스트 메서드의 이름을 가지고 내장된 문자열 정렬 순서에 의하여 결정될 것입니다.

만약 setUp() 메서드가 테스트 실행 중에 예외를 발생시킨다면 프레임워크는 테스트에 오류가 있는 것으로 간주하여 테스트 메서드를 실행하지 않을 것입니다.

마찬가지로 테스트 메서드가 실행되고 나서 정리하기 위해 tearDown() 메서드를 제공합니다:

import unittest

class WidgetTestCase(unittest.TestCase):
    def setUp(self):
        self.widget = Widget('The widget')

    def tearDown(self):
        self.widget.dispose()

만약 setUp()이 성공했다면, 테스트가 성공했든 실패했든 상관없이 tearDown()이 실행될 것입니다.

이와 같은 테스트를 위한 실행 환경을 테스트 픽스쳐(test fixture)라고 부릅니다. 개별 테스트 메서드를 실행하기 위해 고유한 테스트 픽스쳐에 해당하는 새로운 테스트 케이스 인스턴스가 생성됩니다. 따라서 setUp(), tearDown(), __init__()는 테스트 당 1번씩 실행됩니다.

테스트하려는 기능에 따라 테스트들을 같이 모아서 테스트 케이스 구현을 사용하는 것을 추천합니다. 이것을 위해 unittest는 메커니즘을 제공합니다: 테스트 묶음(test suite), 이것은 unittest의 TestSuite 클래스에 해당합니다. 대부분의 경우 unittest.main()이 테스트를 실행하기 위해 모듈의 모든 테스트 케이스를 수집하여 적절한 행동을 취할 것입니다.

그러나 당신이 테스트 묶음을 사용자 정의하고 싶다면 그것을 직접 만들어야 합니다:

def suite():
    suite = unittest.TestSuite()
    suite.addTest(WidgetTestCase('test_default_widget_size'))
    suite.addTest(WidgetTestCase('test_widget_resize'))
    return suite

if __name__ == '__main__':
    runner = unittest.TextTestRunner()
    runner.run(suite())

당신은 테스트 케이스와 테스트 묶음의 정의를 테스트하려는 코드와 같은 모듈(예를 들어 file:widget.py)에 넣을 수 있습니다, 그러나 테스트 코드를 분리된 모듈(예를 들어 test_widget.py)에 넣으면 몇 가지 이점이 있습니다:

테스트 모듈이 명령행에서 독립적으로 작동할 수 있습니다.

테스트 코드가 배포될 코드와 쉽게 분리될 수 있습니다.

충분한 이유 없이 테스트하려는 코드에 맞춰서 테스트 코드를 바꾸려는 유혹이 덜 합니다.

테스트 코드가 테스트하려는 코드에 비해 훨씬 덜 빈번하게 수정되어야 합니다.

테스트하려는 코드는 더 쉽게 리팩토링할 수 있습니다.

C 언어로 작성된 모듈의 테스트 코드는 반드시 분리된 모듈에 위치해야 합니다, 따라서 일관성을 지키는 것이 어떨까요?

만약 테스트 전략이 바뀌더라도 소스 코드를 바꿀 필요가 없습니다.

이전의 테스트 코드를 다시 사용하기

어떤 사용자들은 이전의 모든 테스트 함수를 TestCase 서브 클래스로 변경하는 작업 없이 기존의 테스트 코드를 unittest로 실행하고 싶어 할 것입니다.

이러한 이유로 unittest는 FunctionTestCase 클래스를 제공합니다. 이 TestCase의 서브 클래스는 기존 테스트 함수를 감싸는데 사용할 수 있습니다. 사전 설정과 정리 함수 또한 같이 사용할 수 있습니다.

다음과 같은 테스트 함수가 있을 때:

def testSomething():
    something = makeSomething()
    assert something.name is not None
    # ...

다음과 같이 동등한 테스트 케이스 인스턴스를 생성할 수 있습니다, 추가로 사전 설정과 정리 메서드를 함께 설정합니다:

testcase = unittest.FunctionTestCase(testSomething,
                                     setUp=makeSomethingDB,
                                     tearDown=deleteSomethingDB)

참고

FunctionTestCase를 사용하여 기존 테스트를 unittest-기반 시스템으로 빠르게 변경할 수 있을지라도 이 방법을 추천하지는 않습니다. 시간을 들여서 적절한 TestCase 서브 클래스를 설정하는 것이 미래에 있을 테스트 리팩토링을 대단히 쉽게 만들어줄 것입니다.

어떤 경우에는 doctest 모듈을 사용하여 기존 테스트가 작성되었을 수도 있습니다. 만약 그렇다면 doctest가 제공하는 DocTestSuite 클래스를 사용하여 기존의 doctest-기반 테스트로부터 unittest.TestSuite 인스턴스를 자동으로 만들 수 있습니다.

테스트 건너뛰기와 예상된 실패

버전 3.1에 추가.

unittest는 테스트 중에서 개별 테스트 메서드나 심지어 전체 클래스를 건너뛸 수 있는 기능을 제공합니다. 게다가 테스트를 “예상된 실패”로 표시하는 기능도 지원합니다, 테스트가 망가져서 실패하더라도 그것을 TestResult에 실패라고 기록하지 않습니다.

테스트 건너뛰기는 단순히 skip() 데코레이터나 그것의 조건 변형 중 하나를 사용하거나, setUp()이나 테스트 메서드 안에서 TestCase.skipTest()를 호출하거나, SkipTest를 직접 발생시키면 됩니다.

기본적인 건너뛰기는 다음과 같습니다:

class MyTestCase(unittest.TestCase):

    @unittest.skip("demonstrating skipping")
    def test_nothing(self):
        self.fail("shouldn't happen")

    @unittest.skipIf(mylib.__version__ < (1, 3),
                     "not supported in this library version")
    def test_format(self):
        # Tests that work for only a certain version of the library.
        pass

    @unittest.skipUnless(sys.platform.startswith("win"), "requires Windows")
    def test_windows_support(self):
        # windows specific testing code
        pass

    def test_maybe_skipped(self):
        if not external_resource_available():
            self.skipTest("external resource not available")
        # test code that depends on the external resource
        pass

아래는 위의 예를 상세 모드로 실행했을 때의 출력입니다:

test_format (__main__.MyTestCase) ... skipped 'not supported in this library version'
test_nothing (__main__.MyTestCase) ... skipped 'demonstrating skipping'
test_maybe_skipped (__main__.MyTestCase) ... skipped 'external resource not available'
test_windows_support (__main__.MyTestCase) ... skipped 'requires Windows'

----------------------------------------------------------------------
Ran 4 tests in 0.005s

OK (skipped=4)

클래스도 메서드처럼 건너뛰기가 가능합니다:

@unittest.skip("showing class skipping")
class MySkippedTestCase(unittest.TestCase):
    def test_not_run(self):
        pass

TestCase.setUp() 또한 테스트를 건너뛸 수 있습니다. 이것은 사전 설정해야 할 자원을 사용할 수 없을 때 유용합니다.

예상된 실패는 expectedFailure() 데코레이터를 사용합니다.

class ExpectedFailureTestCase(unittest.TestCase):
    @unittest.expectedFailure
    def test_fail(self):
        self.assertEqual(1, 0, "broken")

자신만의 건너뛰기 데코레이터를 만들기는 쉽습니다. 테스트를 건너뛰고 싶을 때 skip()를 호출하도록 데코레이터를 만들면 됩니다. 다음의 데코레이터는 특정 어트리뷰트가 있는 객체가 전달되지 않으면 테스트를 건너뜁니다:

def skipUnlessHasattr(obj, attr):
    if hasattr(obj, attr):
        return lambda func: func
    return unittest.skip("{!r} doesn't have {!r}".format(obj, attr))

다음 데코레이터들과 예외는 테스트 건너뛰기와 예상된 실패를 구현합니다:

@unittest.skip(reason)

조건 없이 데코레이트된 테스트를 건너뜁니다. reason은 왜 이 테스트가 건너뛰어 졌는지를 설명해야 합니다.

@unittest.skipIf(condition, reason)

condition이 참이면 데코레이트된 테스트를 건너뜁니다.

@unittest.skipUnless(condition, reason)

condition이 참이 아니면 데코레이트된 테스트를 건너뜁니다.

@unittest.expectedFailure

테스트가 예상된 실패라는 표시를 합니다. 테스트가 실패하면 성공으로 간주합니다. 테스트에 통과하면 실패로 간주합니다.

exception unittest.SkipTest(reason)

이 예외는 테스트를 건너뛰기 위해서 발생합니다.

보통은 이 예외를 직접 발생시키기보다는 TestCase.skipTest()나 건너뛰기 데코레이터를 사용할 수 있습니다.

건너뛰는 테스트는 테스트 전후로 setUp()이나 tearDown()를 실행하지 않을 것입니다. 건너뛰는 클래스는 setUpClass()나 tearDownClass()를 실행하지 않을 것입니다. 건너뛰는 모듈은 setUpModule()이나 tearDownModule()을 실행하지 않을 것입니다.

부분 테스트(subtest)를 사용하여 테스트 반복 구별 짖기

버전 3.4에 추가.

여러분의 테스트들이 아주 작은 부분에서만 다를 때, 예를 들어 몇몇 매개변수, unittest는 subTest() 컨텍스트 관리자를 사용하여 테스트 메서드의 바디 안에서 그것들은 구별 짖게 해줍니다.

예를 들어, 다음 테스트는:

class NumbersTest(unittest.TestCase):

    def test_even(self):
        """
        Test that numbers between 0 and 5 are all even.
        """
        for i in range(0, 6):
            with self.subTest(i=i):
                self.assertEqual(i % 2, 0)

다음의 출력을 만듭니다:

======================================================================
FAIL: test_even (__main__.NumbersTest) (i=1)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "subtests.py", line 32, in test_even
    self.assertEqual(i % 2, 0)
AssertionError: 1 != 0

======================================================================
FAIL: test_even (__main__.NumbersTest) (i=3)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "subtests.py", line 32, in test_even
    self.assertEqual(i % 2, 0)
AssertionError: 1 != 0

======================================================================
FAIL: test_even (__main__.NumbersTest) (i=5)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "subtests.py", line 32, in test_even
    self.assertEqual(i % 2, 0)
AssertionError: 1 != 0

부분 테스트를 사용하지 않는다면 테스트 실행은 첫 번째 실패 후에 중단될 것이고 i 값이 표시되지 않기 때문에 에러를 진단하는 데 쉽지 않을 것입니다:

======================================================================
FAIL: test_even (__main__.NumbersTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "subtests.py", line 32, in test_even
    self.assertEqual(i % 2, 0)
AssertionError: 1 != 0

클래스와 함수

이 절은 unittest의 API를 심도 있게 설명합니다.

테스트 케이스

class unittest.TestCase(methodName='runTest')

TestCase 클래스의 인스턴스는 unittest 세계에서 논리적인 테스트 단위에 해당합니다. 이 클래스는 베이스 클래스로 사용되며, 특정 테스트는 구상 클래스로 구현됩니다. 이 클래스는 테스트 실행자가 테스트를 실행할 수 있는 인터페이스를 구현하고 테스트 코드가 검사하고 다양한 실패를 보고할 수 있는 메서드를 구현합니다.

TestCase의 각 인스턴스는 하나의 베이스 메서드: methodName이 지정하는 이름의 메서드를 실행할 것입니다. 대부분의 TestCase 사용에서, 당신은 methodName을 바꾸거나 기본 runTest() 메서드를 재구현하지 않을 것입니다.

버전 3.2에서 변경: methodName 제공 없이도 TestCase를 성공적으로 인스턴스화할 수 있습니다. 이것은 대화형 인터프리터에서 TestCase로 쉽게 실험을 할 수 있게 합니다.

TestCase 인스턴스는 3가지 메서드 그룹을 제공합니다: 한 그룹은 테스트를 실행하는 데 사용되고, 다른 한 그룹은 조건을 확인하고 실패를 보고하는 테스트 구현으로 사용되고, 몇몇 조회 메서드는 테스트 자체에 관한 정보를 수집할 수 있게 해줍니다.

첫 번째 그룹(테스트 실행) 안에 메서드는:

setUp()

테스트 픽스쳐를 준비하기 위해 호출되는 메서드입니다. 이 메서드는 테스트 메서드를 호출하기 바로 직전에 호출됩니다; AssertionError 또는 SkipTest이외의 이 메서드에서 발생한 모든 예외는 테스트 실패가 아닌 오류로 간주합니다. 기본 구현은 아무것도 하지 않습니다.

tearDown()

테스트 메서드가 불리고 결과가 기록되고 나서 바로 다음에 호출되는 메서드입니다. 테스트 메서드가 예외를 발생했더라도 이 메서드는 불립니다, 따라서 서브 클래스의 구현은 내부 상태를 확인하는 데 특별히 주의를 기울여야 합니다. AssertionError 또는 SkipTest이외의 이 메서드에서 발생하는 모든 예외는 테스트 실패가 아닌 오류로 간주합니다(따라서 보고된 오류의 총 숫자가 증가합니다). 이 메서드는 테스트 메서드의 결과물에 영향받지 않고 setUp()이 성공했을 때만 불립니다. 기본 구현은 아무것도 하지 않습니다.

setUpClass()

개별 클래스의 테스트들이 실행되기 전에 불리는 클래스 메서드입니다. setUpClass는 클래스만 인자로 받아 호출되고 classmethod()로 데코레이트해야 합니다:

@classmethod
def setUpClass(cls):
    ...

더 자세한 것은 클래스와 모듈 픽스쳐를 보십시오.

버전 3.2에 추가.

tearDownClass()

개별 클래스의 테스트들이 실행되고 난 뒤에 불리는 클래스 메서드입니다. tearDownClass는 클래스만 인자로 받아 호출되고 classmethod()로 데코레이트해야 합니다:

@classmethod
def tearDownClass(cls):
    ...

더 자세한 것은 클래스와 모듈 픽스쳐를 보십시오.

버전 3.2에 추가.

run(result=None)

테스트를 실행하고, result 인자로 전달된 TestResult에 결과를 수집합니다. 만약 result 인자가 전달 안 되거나 None이라면 임시 결과 객체를 (defaultTestResult() 메서드를 불러서) 생성하여 사용합니다. run() 호출자에게 결과 객체를 반환합니다.

단순히 TestCase 인스턴스를 호출하는 것으로 같은 효과를 볼 수 있습니다.

버전 3.3에서 변경: 기존 버전의 run은 결과를 반환하지 않았습니다. 인스턴스 호출 또한 그렇지 않았습니다.

skipTest(reason)

테스트 메서드나 setUp()에서 이것을 호출하면 현재 테스트를 건너뜁니다. 자세한 정보는 테스트 건너뛰기와 예상된 실패를 보십시오.

버전 3.1에 추가.

subTest(msg=None, **params)

둘러싼 코드 블록을 부분 테스트로서 실행하는 컨텍스트 관리자를 반환합니다. msg 및 params는 선택 사항이며 부분 테스트가 실패 할 때마다 표시되는 임의의 값으로 당신이 명확하게 알아보게 해줍니다.

테스트 케이스는 여러 개의 부분 테스트 선언을 포함할 수 있고, 그것들은 자유롭게 중첩될 수 있습니다.

자세한 정보는 부분 테스트(subtest)를 사용하여 테스트 반복 구별 짖기를 보십시오.

버전 3.4에 추가.

debug()

결과를 수집하지 않고 테스트를 실행합니다. 이것은 테스트에서 발생한 예외가 호출자로 전파될 수 있게 해서, 디버거 환경에서 테스트를 실행할 때 사용될 수 있습니다.

TestCase 클래스는 값을 검사하고 실패를 보고하기 위해 몇 개의 assert 메서드를 제공합니다. 다음 표는 보통 많이 사용되는 메서드들입니다(더 많은 assert 메서드는 표 아래를 보십시오):

메서드

검사하는 내용

추가된 버전

assertEqual(a, b)

a == b

assertNotEqual(a, b)

a != b

assertTrue(x)

bool(x) is True

assertFalse(x)

bool(x) is False

assertIs(a, b)

a is b

3.1

assertIsNot(a, b)

a is not b

3.1

assertIsNone(x)

x is None

3.1

assertIsNotNone(x)

x is not None

3.1

assertIn(a, b)

a in b

3.1

assertNotIn(a, b)

a not in b

3.1

assertIsInstance(a, b)

isinstance(a, b)

3.2

assertNotIsInstance(a, b)

not isinstance(a, b)

3.2

모든 assert 메서드는 msg 인자를 받을 수 있습니다, 만약 그것이 전달된다면 실패 시 에러 메시지로 사용됩니다(longMessage 도 참고하십시오). assertRaises(), assertRaisesRegex(), assertWarns(), assertWarnsRegex()는 컨텍스트 관리자로서 사용될 때만 그들에게 msg 키워드 인자를 전달할 수 있다는 점을 주의하십시오.

assertEqual(first, second, msg=None)

first와 second가 같은지 테스트합니다. 비교한 값이 같지 않으면 테스트는 실패할 것입니다.

추가로, 만약 first와 second가 정확히 같은 형(type)이고 list, tuple, dict, set, frozenset, str 이거나 addTypeEqualityFunc()에 등록된 서브 클래스 형 중 하나일 경우 더 유용한 기본 에러 메시지를 생성하기 위해 형-특화(type-specific) 동등성 함수가 불릴 것입니다(형-특화 메서드 목록을 참고하십시오).

버전 3.1에서 변경: 형-특화 동등성 함수가 자동으로 불리도록 추가

버전 3.2에서 변경: 문자열 비교를 위해서 assertMultiLineEqual()를 기본 형-특화 동등성 함수에 추가

assertNotEqual(first, second, msg=None)

first와 second가 같지 않은지 테스트합니다, 비교한 값이 같으면 테스트는 실패할 것입니다.

assertTrue(expr, msg=None)

assertFalse(expr, msg=None)

expr이 참(또는 거짓)인지 테스트합니다.

이것은 bool(expr) is True와 동등하고 expr is True와 동등하지 않다는 것에 주의하십시오(후자를 위해선 assertIs(expr, True)를 사용하십시오). 더 구체적인 메서드를 사용할 수 있을 때는 이 메서드를 지양해야 합니다(예, assertTrue(a == b) 대신에 assertEqual(a, b)), 왜냐하면 실패의 경우에 구체적인 메서드가 더 나은 에러 메시지를 제공하기 때문입니다.

assertIs(first, second, msg=None)

assertIsNot(first, second, msg=None)

first와 second가 같은 객체로 평가되는지(아닌지) 테스트합니다.

버전 3.1에 추가.

assertIsNone(expr, msg=None)

assertIsNotNone(expr, msg=None)

expr이 None 인지(아닌지) 테스트합니다.

버전 3.1에 추가.

assertIn(member, container, msg=None)

assertNotIn(member, container, msg=None)

Test that member is (or is not) in container.

버전 3.1에 추가.

assertIsInstance(obj, cls, msg=None)

assertNotIsInstance(obj, cls, msg=None)

obj가 cls(isinstance()가 지원하는 것처럼 클래스 또는 클래스의 튜플)의 인스턴스인지(아닌지) 테스트합니다. 정확한 형 검사를 위해서는 assertIs(type(obj), cls)를 사용하십시오.

버전 3.2에 추가.

다음의 메서드를 사용하여 예외, 경고, 로그 메시지의 발생을 검사할 수 있습니다:

메서드

검사하는 내용

추가된 버전

assertRaises(exc, fun, *args, **kwds)

fun(*args, **kwds)가 exc를 발생

assertRaisesRegex(exc, r, fun, *args, **kwds)

fun(*args, **kwds)가 exc를 발생하고 메시지가 정규식 r에 일치

3.1

assertWarns(warn, fun, *args, **kwds)

fun(*args, **kwds)가 warn을 발생

3.2

assertWarnsRegex(warn, r, fun, *args, **kwds)

fun(*args, **kwds)가 warn을 발생하고 메시지가 정규식 r에 일치

3.2

assertLogs(logger, level)

with 블록이 최소 level로 logger에 로그를 남김

3.4

assertRaises(exception, callable, *args, **kwds)

assertRaises(exception, *, msg=None)

assertRaises()에 전달된 어떤 위치 또는 키워드 인자와 함께 callable이 호출되었을 때 예외가 발생하는지 테스트합니다. exception이 발생하면 테스트를 통과하고, 다른 예외가 발생하면 에러이고, 아무 예외도 발생하지 않으면 실패입니다. 여러 예외 모음을 잡기 위해서 예외 클래스를 포함한 튜플을 exception으로 전달해도 좋습니다.

만약 선택적인 msg와 함께 오직 exception 인자만 전달된다면, 테스트할 코드를 함수가 아닌 인라인으로 작성할 수 있도록 컨텍스트 관리자를 반환합니다:

with self.assertRaises(SomeException):
    do_something()

컨텍스트 관리자로 사용되면, assertRaises()는 추가적인 키워드 인자인 msg를 받을 수 있습니다.

컨텍스트 관리자는 잡은 예외 객체를 exception 어트리뷰트에 저장할 것입니다. 이것은 발생한 예외에 대해서 추가적인 검사를 수행하려는 경우에 유용할 수 있습니다:

with self.assertRaises(SomeException) as cm:
    do_something()

the_exception = cm.exception
self.assertEqual(the_exception.error_code, 3)

버전 3.1에서 변경: assertRaises()를 컨텍스트 관리자로 사용할 수 있도록 기능 추가.

버전 3.2에서 변경: exception 어트리뷰트 추가.

버전 3.3에서 변경: 컨텍스트 관리자로 사용될 때 msg 키워드 인자 추가.

assertRaisesRegex(exception, regex, callable, *args, **kwds)

assertRaisesRegex(exception, regex, *, msg=None)

assertRaises()와 비슷하지만 발생한 예외의 문자열 표현이 regex에 일치하는지 테스트합니다. regex는 정규식 객체나 re.search()에 사용되기 적합한 정규식 문자열이 될 수 있습니다. 예:

self.assertRaisesRegex(ValueError, "invalid literal for.*XYZ'$",
                       int, 'XYZ')

또는:

with self.assertRaisesRegex(ValueError, 'literal'):
   int('XYZ')

버전 3.1에 추가: assertRaisesRegexp 라는 이름으로 추가되었습니다.

버전 3.2에서 변경: assertRaisesRegex()으로 이름 변경.

버전 3.3에서 변경: 컨텍스트 관리자로 사용될 때 msg 키워드 인자 추가.

assertWarns(warning, callable, *args, **kwds)

assertWarns(warning, *, msg=None)

assertWarns()에 전달된 어떤 위치 또는 키워드 인자와 함께 callable이 호출되었을 때 경고(warning)가 발생하는지 테스트합니다. warning이 발생하면 테스트를 통과하고, 그렇지 않으면 실패입니다. 예외가 발생하면 에러입니다. 여러 경고 모음을 잡기 위해서 경고 클래스를 포함한 튜플을 warnings로 전달해도 좋습니다.

만약 선택적인 msg와 함께 오직 warning 인자만 전달된다면, 테스트할 코드를 함수가 아닌 인라인으로 작성할 수 있도록 컨텍스트 관리자를 반환합니다:

with self.assertWarns(SomeWarning):
    do_something()

컨텍스트 관리자로 사용되면, assertWarns()는 추가적인 키워드 인자인 msg를 받을 수 있습니다.

컨텍스트 관리자는 잡은 경고 객체를 warning 어트리뷰트에 저장하고, 경고를 발생한 소스코드 줄을 filename과 lineno에 저장할 것입니다. 이것은 발생한 경고에 대해서 추가적인 검사를 수행하려는 경우에 유용할 수 있습니다:

with self.assertWarns(SomeWarning) as cm:
    do_something()

self.assertIn('myfile.py', cm.filename)
self.assertEqual(320, cm.lineno)

이 메서드는 호출될 때 적용될 경고 필터와 관계없이 작동합니다.

버전 3.2에 추가.

버전 3.3에서 변경: 컨텍스트 관리자로 사용될 때 msg 키워드 인자 추가.

assertWarnsRegex(warning, regex, callable, *args, **kwds)

assertWarnsRegex(warning, regex, *, msg=None)

assertWarns()와 비슷하지만 발생한 경고의 메시지가 regex에 일치하는지 테스트합니다. regex는 정규식 객체나 re.search()에 사용되기 적합한 정규식 문자열이 될 수 있습니다. 예:

self.assertWarnsRegex(DeprecationWarning,
                      r'legacy_function\(\) is deprecated',
                      legacy_function, 'XYZ')

또는:

with self.assertWarnsRegex(RuntimeWarning, 'unsafe frobnicating'):
    frobnicate('/etc/passwd')

버전 3.2에 추가.

버전 3.3에서 변경: 컨텍스트 관리자로 사용될 때 msg 키워드 인자 추가.

assertLogs(logger=None, level=None)

최소한 level로 logger나 그 자식들에 최소한 1개의 메시지가 기록되는지 테스트하는 컨텍스트 관리자입니다.

logger가 주어졌다면, logging.Logger 객체이거나 로거의 이름인 str이어야 합니다. 기본값은 모든 메시지를 잡을 루트 로거입니다.

level이 주어졌다면, 로그 수준의 숫자 값이거나 그에 대응하는 문자열이어야 합니다(예를 들어 "ERROR"이거나 logging.ERROR). 기본값은 logging.INFO입니다.

만약 with 블록 안에서 logger와 level 조건을 만족하는 최소한 1개의 메시지가 나왔다면 테스트는 성공하고, 그렇지 않으면 실패합니다.

컨텍스트 관리자에 의해 반환되는 객체는 조건에 일치하는 로그 메시지를 추적하기 위한 기록 도우미입니다. 이것은 2개의 어트리뷰트를 가지고 있습니다:

records

조건에 일치하는 메시지의 logging.LogRecord 객체 목록.

output

조건에 일치하는 메시지의 포맷 출력인 str 객체 목록.

예:

with self.assertLogs('foo', level='INFO') as cm:
   logging.getLogger('foo').info('first message')
   logging.getLogger('foo.bar').error('second message')
self.assertEqual(cm.output, ['INFO:foo:first message',
                             'ERROR:foo.bar:second message'])

버전 3.4에 추가.

더 구체적인 검사를 수행하기 위한 또 다른 메서드가 있습니다, 아래와 같이:

메서드

검사하는 내용

추가된 버전

assertAlmostEqual(a, b)

round(a-b, 7) == 0

assertNotAlmostEqual(a, b)

round(a-b, 7) != 0

assertGreater(a, b)

a > b

3.1

assertGreaterEqual(a, b)

a >= b

3.1

assertLess(a, b)

a < b

3.1

assertLessEqual(a, b)

a <= b

3.1

assertRegex(s, r)

r.search(s)

3.1

assertNotRegex(s, r)

not r.search(s)

3.2

assertCountEqual(a, b)

순서와 상관없이 a와 b가 같은 개수의 같은 요소를 가졌는지.

3.2

assertAlmostEqual(first, second, places=7, msg=None, delta=None)

assertNotAlmostEqual(first, second, places=7, msg=None, delta=None)

first와 second가 근사하게 같은지(또는 근사하게 같지 않은지) 테스트합니다. 이는 값 차이를 계산하고, 주어진 소수 자릿(places)수(기본값 7)로 반올림한 뒤, 0과 비교하는 것으로 이루어집니다. 이 메서드는 값을 유효 숫자 자릿수(significant digits)가 아닌 주어진 소수 자릿수(decimal places)(즉, round() 함수와 같이)로 반올림합니다.

만약 places 대신에 delta가 주어진다면 first와 second의 값 차이는 반드시 delta보다 작거나 같아야(또는 커야) 합니다.

delta와 places가 동시에 주어지면 TypeError가 발생합니다.

버전 3.2에서 변경: assertAlmostEqual()은 같다고 비교되는 거의 동등한 객체를 자동으로 고려합니다. assertNotAlmostEqual()은 객체가 같다고 비교되면 자동으로 실패합니다. delta 키워드 인자를 추가.

assertGreater(first, second, msg=None)

assertGreaterEqual(first, second, msg=None)

assertLess(first, second, msg=None)

assertLessEqual(first, second, msg=None)

first를 second와 비교해서 각각 메서드 이름에 해당하는 >, >=, <, <= 인지 테스트합니다. 그렇지 않으면 테스트는 실패합니다:

>>> self.assertGreaterEqual(3, 4)
AssertionError: "3" unexpectedly not greater than or equal to "4"

버전 3.1에 추가.

assertRegex(text, regex, msg=None)

assertNotRegex(text, regex, msg=None)

regex 검색이 text에 일치하는지(아닌지) 테스트합니다. 실패의 경우, 에러 메시지는 패턴과 text(또는 패턴과 예상과 달리 일치한 text의 부분)를 포함할 것입니다. regex는 정규식 객체나 re.search()에 사용되기 적합한 정규식 문자열이 될 수 있습니다.

버전 3.1에 추가: assertRegexpMatches 라는 이름으로 추가되었습니다.

버전 3.2에서 변경: assertRegexpMatches() 메서드가 assertRegex()로 이름 변경되었습니다.

버전 3.2에 추가: assertNotRegex().

버전 3.5에 추가: assertNotRegexpMatches이름은 assertNotRegex()의 폐지된 에일리어스입니다.

assertCountEqual(first, second, msg=None)

first 시퀀스가 순서에 상관없이 second와 같은 요소를 포함하는지 테스트합니다. 그렇지 않은 경우, 시퀀스들의 차이를 나열한 에러 메시지가 생성됩니다.

first와 second를 비교할 때 중복된 요소는 무시하지 않습니다. 두 개의 시퀀스에 각 요소가 같은 수 만큼 있는 것을 확인합니다. assertEqual(Counter(list(first)), Counter(list(second)))와 같지만 해시 불가능한(unhashable) 시퀀스에도 작동합니다.

버전 3.2에 추가.

assertEqual() 메서드는 같은 형의 객체의 동등성 검사를 다른 형-특화 메서드에게로 보냅니다. 이러한 메서드들은 대부분의 내장 형에 대해서 이미 구현되어 있지만, addTypeEqualityFunc()을 사용하여 새로운 메서드를 등록하는 것도 가능합니다:

addTypeEqualityFunc(typeobj, function)

정확히 같은 (서브 클래스가 아닌) typeobj 형의 두 객체가 같은지 비교 검사하기 위해 assertEqual()한테 불리는 형-특화 메서드를 등록합니다. function은 반드시 2개의 위치 인자를 받아야 하고 assertEqual()이 그러한 것처럼 msg=None 키워드 인자를 세 번째로 받아야 합니다. 이것은 처음 2개의 매개변수가 같지 않은 것이 확인될 경우 self.failureException(msg)을 반드시 발생시켜야 합니다 – 에러 메시지에 유용한 정보를 제공하고 비동등성을 자세히 설명할 수 있을 것입니다.

버전 3.1에 추가.

assertEqual()에서 자동으로 사용하는 형-특화 메서드 목록은 다음 표에 정리되어 있습니다. 보통은 이 메서드를 직접 부를 필요가 없다는 것을 기억하십시오.

메서드

을 비교하기 위해

추가된 버전

assertMultiLineEqual(a, b)

문자열

3.1

assertSequenceEqual(a, b)

시퀀스

3.1

assertListEqual(a, b)

리스트

3.1

assertTupleEqual(a, b)

튜플

3.1

assertSetEqual(a, b)

집합 또는 불변 집합

3.1

assertDictEqual(a, b)

딕셔너리

3.1

assertMultiLineEqual(first, second, msg=None)

여러 줄 문자열인 first와 second가 같은지 테스트합니다. 같지 않을 경우 에러 메시지에 다른 부분이 강조된 두 문자열의 차이가 포함됩니다. 이 메서드는 assertEqual()에서 문자열을 비교할 때 기본적으로 사용됩니다.

버전 3.1에 추가.

assertSequenceEqual(first, second, msg=None, seq_type=None)

2개의 시퀀스가 같은지 테스트합니다. seq_type이 전달된 경우, first와 second 둘 다 seq_type의 인스턴스이어야 하고 그렇지 않은 경우 실패가 발생합니다. 시퀀스가 다른 경우, 에러 메시지는 2개 사이의 차이점을 보여주게 됩니다.

이 메서드는 assertEqual()에서 직접 호출되진 않지만, assertListEqual()와 assertTupleEqual()을 구현할 때 사용됩니다.

버전 3.1에 추가.

assertListEqual(first, second, msg=None)

assertTupleEqual(first, second, msg=None)

2개의 리스트나 튜플이 같은지 테스트합니다. 만약 같지 않다면 에러 메시지는 2개 사이의 차이점만 보여주게 됩니다. 매개변수 중 하나가 잘못된 형인 경우 에러가 발생합니다. 이 메서드는 assertEqual()에서 리스트와 튜플을 비교할 때 기본적으로 사용됩니다.

버전 3.1에 추가.

assertSetEqual(first, second, msg=None)

2개의 집합이 같은지 테스트합니다. 같지 않은 경우 에러 메시지는 집합 사이의 차이를 나열하게 됩니다. 이 메서드는 assertEqual()에서 집합이나 불변 집합을 비교할 때 기본적으로 사용됩니다.

first와 second 중 하나가 set.difference() 메서드를 가지고 있지 않으면 실패합니다.

버전 3.1에 추가.

assertDictEqual(first, second, msg=None)

2개의 딕셔너리가 같은지 테스트합니다. 같지 않은 경우 에러 메시지는 딕셔너리 사이의 차이를 보여주게 됩니다. 이 메서드는 assertEqual()에서 딕셔너리를 비교할 때 기본적으로 사용될 것입니다.

버전 3.1에 추가.

마지막으로 TestCase가 다음의 메서드와 어트리뷰트를 제공합니다:

fail(msg=None)

무조건 테스트 실패 신호를 보냅니다, 에러 메시지를 위해 msg나 None을 전달합니다.

failureException

이 클래스 어트리뷰트는 테스트 메서드에서 발생한 예외를 줍니다. 만약 테스트 프레임워크가 추가 정보를 전달하기 위해 특수한 예외를 사용할 필요가 있다면, 프레임워크와 “공정하게 행동하기” 위해서 이 예외를 서브 클래스해야 합니다. 이 어트리뷰트의 초깃값은 AssertionError 입니다.

longMessage

이 클래스 어트리뷰트는 실패한 assertXYY 호출에 msg 인자로 전달된 사용자 정의 실패 메시지가 어떻게 동작하는지를 결정합니다. True가 기본값입니다. 이 경우, 사용자 정의 메시지가 표준 실패 메시지 끝에 추가됩니다. False로 설정할 경우 사용자 정의 메시지가 표준 메시지를 대체합니다.

이 클래스 설정은 인스턴스 어트리뷰트를 설정하여 개별 테스트 메서드에 의해 재정의될 수 있습니다, assert 메서드를 호출하기 전에 self.longMessage를 True 또는 False로 설정하는 것입니다.

이 클래스 설정은 각 테스트 호출 전에 재설정됩니다.

버전 3.1에 추가.

maxDiff

이 어트리뷰트는 실패 시 diff를 보고하는 assert 메서드의 최대 diff 출력 길이를 설정합니다. 기본값은 80*8 문자입니다. 이 어트리뷰트에 영향을 받는 assert 메서드는 assertSequenceEqual()(이것에 위임하는 모든 시퀀스 비교 메서드를 포함), assertDictEqual(), assertMultiLineEqual() 입니다.

maxDiff를 None으로 설정하면 diff의 최대 길이 제한이 없어지는 것을 뜻합니다.

버전 3.2에 추가.

테스트 프레임워크는 테스트에 관한 정보를 수집하기 위해 다음의 메서드를 사용할 수 있습니다:

countTestCases()

이 테스트 객체에 해당하는 테스트 개수를 반환합니다. TestCase 인스턴스에 대해서는 이것은 항상 1입니다.

defaultTestResult()

이 테스트 케이스 클래스를 위해서 사용되는 테스트 결과 클래스의 인스턴스를 반환합니다(run() 메서드에 다른 결과 인스턴스가 전달되지 않은 경우에).

TestCase 인스턴스에 대해서는 이것은 항상 TestResult의 인스턴스입니다; TestCase의 서브 클래스는 이것을 필요에 따라 재정의해야 합니다.

id()

특정 테스트 케이스를 식별하는 문자열을 반환합니다. 이것은 보통 모듈과 클래스 이름을 포함한 테스트 메서드의 완전한 이름(full name)입니다.

shortDescription()

테스트의 설명을 반환하거나 설명이 제공되지 않았으면 None을 반환합니다. 이 메서드의 기본 구현은 가능하다면 테스트 메서드의 독스트링의 첫 번째 줄을 반환하고 그렇지 않으면 None을 반환합니다.

버전 3.1에서 변경: 3.1 버전에서 docstring이 있는 경우에도 짧은 설명에 테스트 이름을 추가하도록 변경되었습니다. 이것은 unittest 확장과 호환성 문제를 일으켰고 테스트 이름 추가는 파이썬 3.2에서 TextTestResult로 옮겨졌습니다.

addCleanup(function, *args, **kwargs)

테스트 중에 사용된 자원을 정리하기 위해 tearDown() 이후에 불리는 함수를 추가합니다. 함수들은 추가된 순서의 반대 순서대로 불리게 됩니다(LIFO). 함수가 추가될 때 addCleanup()에 같이 전달된 위치 인자나 키워드 인자와 함께 호출됩니다.

만약 setUp()이 실패한다면, 즉 tearDown()이 불리지 않더라도, 정리 함수들은 여전히 불리게 될 것입니다.

버전 3.1에 추가.

doCleanups()

이 메서드는 tearDown() 이후나, setUp()이 예외를 발생시키면 setUp()이후에 조건 없이 호출됩니다.

addCleanup()에서 추가된 모든 정리 함수들을 호출하는 책임이 있습니다. 만약 정리 함수를 tearDown() 이전에 불러야 할 필요가 있다면 doCleanups()를 직접 부를 수 있습니다.

doCleanups()는 한 번에 하나씩 정리 함수 스택에서 메서드를 꺼내기 때문에 언제든지 호출될 수 있습니다.

버전 3.1에 추가.

class unittest.FunctionTestCase(testFunc, setUp=None, tearDown=None, description=None)

이 클래스는 테스트 실행자가 테스트를 수행할 수 있게 TestCase 인터페이스 일부를 구현합니다, 하지만 테스트 코드가 검사하거나 에러를 보고하는 데 사용하는 메서드를 제공하지는 않습니다. 이것은 레거시 테스트 코드를 사용하여 테스트 케이스를 생성할 때 사용할 수 있습니다, 이것은 레거시 테스트 코드가 unittest-기반 테스트 프레임워크에 통합될 수 있게 해줍니다.

폐지된 에일리어스

역사적인 이유로 인해 TestCase 메서드의 일부는 지금은 폐지된 에일리어스를 1개 또는 그 이상 가졌습니다. 다음 표는 폐지된 에일리어스과 그에 맞는 올바른 이름을 나열합니다:

메서드 이름

폐지된 에일리어스

폐지된 에일리어스

assertEqual()

failUnlessEqual

assertEquals

assertNotEqual()

failIfEqual

assertNotEquals

assertTrue()

failUnless

assert_

assertFalse()

failIf

assertRaises()

failUnlessRaises

assertAlmostEqual()

failUnlessAlmostEqual

assertAlmostEquals

assertNotAlmostEqual()

failIfAlmostEqual

assertNotAlmostEquals

assertRegex()

assertRegexpMatches

assertNotRegex()

assertNotRegexpMatches

assertRaisesRegex()

assertRaisesRegexp

버전 3.1부터 폐지: 두 번째 열에 나열된 fail* 에일리어스는 폐지되었습니다.

버전 3.2부터 폐지: 세 번째 열에 나열된 assert* 에일리어스는 폐지되었습니다.

버전 3.2부터 폐지: assertRegexpMatches와 assertRaisesRegexp는 assertRegex()와 assertRaisesRegex()로 이름이 변경되었습니다.

버전 3.5부터 폐지: assertNotRegexpMatches 이름은 폐지되고 assertNotRegex()으로 대체합니다.

테스트 분류

class unittest.TestSuite(tests=())

이 클래스는 개별 테스트 케이스와 테스트 묶음의 집합체를 나타냅니다. 이 클래스는 테스트 실행자가 이것을 다른 테스트 케이스처럼 실행할 수 있기 위해 필요한 인터페이스를 제공합니다. TestSuite 인스턴스를 실행하는 것은 테스트 묶음을 이터레이션하면서 각 테스트를 개별적으로 실행하는 것과 같습니다.

tests가 주어졌다면, 그것은 초기에 이 테스트 묶음을 만들 때 사용될 개별 테스트 케이스이거나 다른 테스트 묶음의 이터러블이어야 합니다. 나중에 컬렉션에 테스트 케이스나 테스트 묶음을 추가할 수 있는 추가 메서드가 제공됩니다.

TestSuite 객체는 TestCase 객체와 흡사하게 행동합니다만, 테스트를 실제로 구현하지 않는 것이 다릅니다. 대신에, 이것은 다 같이 실행되어야 하는 테스트 그룹에 테스트들을 모으는 데 사용됩니다. TestSuite 인스턴스에 테스트를 추가하기 위해 몇몇 추가적인 메서드를 사용할 수 있습니다.

addTest(test)

테스트 묶음에 TestCase나 TestSuite 추가하기.

addTests(tests)

이 테스트 묶음에 TestCase와 TestSuite 인스턴스의 이터러블에서 나온 모든 테스트를 추가하기.

이것은 tests를 이터레이션하면서 각 요소에 대해 addTest()를 호출하는 것과 같습니다.

TestSuite는 다음 메서드를 TestCase와 공유합니다:

run(result)

이 테스트 묶음과 연관된 테스트를 실행하고, result로 전달된 테스트 결과 객체에 결과를 수집합니다. TestCase.run()과 달리 TestSuite.run()은 결과 객체가 반드시 전달되어야 합니다.

debug()

결과를 수집하지 않고 이 테스트 묶음과 연관된 테스트를 실행합니다. 이것은 테스트에서 발생한 예외가 호출자로 전파될 수 있게 해서 디버거 환경에서 테스트를 실행할 때 사용될 수 있습니다.

countTestCases()

이 테스트 객체에 해당하는 테스트 개수를 반환합니다, 모든 개별 테스트와 서브-테스트 묶음을 포함합니다.

__iter__()

TestSuite로 묶인 테스트들은 항상 이터레이션으로 접근합니다. 서브 클래스는 __iter__()를 재정의하여 테스트를 지연해서 제공할 수 있습니다. 이 메서드는 한 개의 테스트 묶음에서 여러 번 불릴 수 있다는 것을 기억하십시오(예를 들어 테스트 개수를 세거나 동등성을 위해 비교할 때), 그러므로 TestSuite.run() 전에 수 번의 이터레이션이 반환한 테스트들은 매 이터레이션 호출마다 반드시 같아야 합니다. TestSuite.run() 후에는 호출자가 테스트 참조를 보존하기 위해 TestSuite._removeTestAtIndex()를 재정의한 서브 클래스를 사용하는 경우가 아니라면 이 메서드에 의해 반환된 테스트에 의존하면 안 됩니다.

버전 3.2에서 변경: 이전 버전에서는 TestSuite가 이터레이션을 사용하기보다는 직접 테스트에 접근했습니다, 따라서 __iter__()를 재정의하는 것은 테스트를 제공하기에 충분하지 않았습니다.

버전 3.4에서 변경: 이전 버전에서는 TestSuite가 TestSuite.run() 후에 각 TestCase 의 참조를 유지했습니다. 서브 클래스는 TestSuite._removeTestAtIndex()를 재정의해서 이 동작을 복구할 수 있습니다.

TestSuite 객체의 전형적인 사용법은 최종 사용자 테스트 장치(harness)보다는 TestRunner에 의해 run() 메서드가 호출되는 것입니다.

테스트를 로드하고 실행하기

class unittest.TestLoader

TestLoader 클래스는 클래스와 모듈로부터 테스트 묶음을 생성하는 데 사용됩니다. 보통, 이 클래스의 인스턴스를 생성할 필요는 없습니다; unittest 모듈은 공유 가능한 unittest.defaultTestLoader 인스턴스를 제공합니다. 그러나 서브 클래스나 인스턴스를 사용함으로 몇몇 변경 가능한 속성을 사용자 정의할 수 있습니다.

TestLoader 객체는 다음 어트리뷰트를 가집니다:

errors

테스트를 로드하는 동안 발생한 치명적이지 않은(non-fatal) 에러 목록입니다. 어떤 시점에도 로더에 의해 재설정되지 않습니다. 치명적인 에러는 예외를 발생시키는 관련 메서드에 의해 신호가 발생하여 호출자에게 전달됩니다. 치명적이지 않은 에러는 실행 시에 원래 에러를 발생시킬 합성(synthetic) 테스트가 표시하기도 합니다.

버전 3.5에 추가.

TestLoader 객체는 다음 메서드를 가집니다:

loadTestsFromTestCase(testCaseClass)

TestCase에서 파생된 testCaseClass에 포함된 모든 테스트 케이스의 묶음을 반환합니다.

테스트 케이스 인스턴스는 getTestCaseNames()에 의해 이름 지어진 각 메서드를 위해 생성됩니다. 기본값은 test로 시작되는 메서드 이름입니다. 만약 getTestCaseNames()가 아무 메서드도 반환하지 않지만, runTest() 메서드가 구현되었다면 이 메서드를 위해서 1개의 테스트 케이스가 대신 생성됩니다.

loadTestsFromModule(module, pattern=None)

주어진 모듈에 포함된 모든 테스트 케이스 묶음을 반환합니다. 이 메서드는 TestCase에서 파생된 클래스를 찾기 위해 module을 검색하고 클래스에 정의된 각 테스트 메서드를 위해 클래스의 인스턴스를 생성합니다.

참고

TestCase에서 파생된 클래스의 계층 사용이 픽스쳐와 도우미 함수를 공유하는 데 편리할 수 있지만 직접 인스턴스화를 하도록 의도되지 않은 베이스 클래스에 테스트 메서드를 정의하는 것은 이 메서드와 잘 작동하지 않습니다. 그러나 그렇게 하는 것이 픽스처들이 다르고 서브 클래스에서 정의될 경우에는 유용할 수 있습니다.

만약 모듈이 load_tests 함수를 제공한다면 테스트 로드를 위해 이것을 호출할 것입니다. 이것은 모듈이 테스트 로드를 사용자 정의할 수 있도록 해줍니다. 이것은 load_tests 프로토콜입니다. pattern 인자는 load_tests에 세 번째 인자로 전달됩니다.

버전 3.2에서 변경: load_tests 지원이 추가됨.

버전 3.5에서 변경: 문서로 만들어 져 있지 않고 공식적이지 않은 use_load_tests 기본 인자를 폐지하고 무시합니다, 하지만 하위 호환성을 위해 여전히 그것을 수용합니다. 이 메서드는 이제 load_tests에 세 번째 인자로 전달되는 pattern을 오직 키워드 인자로써 수용합니다.

loadTestsFromName(name, module=None)

문자열 지정자에 맞는 모든 테스트 케이스 묶음을 반환합니다.

지정자 name은 모듈, 테스트 케이스 클래스, 테스트 케이스 클래스에 있는 테스트 메서드, TestSuite 인스턴스, TestCase나 TestSuite 인스턴스를 반환하는 콜러블 객체로 해석될 수 있는 “점으로 구분된 이름(dotted name)”입니다. 이 검사는 여기에 나열된 순서대로 적용됩니다; 즉, 테스트 케이스 클래스에 있는 메서드는 “콜러블 객체”보다는 “테스트 케이스 클래스에 있는 테스트 메서드”로 선택될 것입니다.

예를 들어, 만약 당신이 TestCase에서 파생된 클래스인 SampleTestCase를 포함한 SampleTests 모듈을 가지고 있고 그 클래스는 3개의 테스트 메서드(test_one(), test_two(), test_three())를 가지고 있다면, 지정자 'SampleTests.SampleTestCase' 에 대해서 이 메서드는 모든 3개의 테스트 메서드를 실행할 테스트 묶음으로 반환할 것입니다. 지정자가 'SampleTests.SampleTestCase.test_two' 라면 이 메서드는 오직 test_two() 테스트 메서드를 실행할 테스트 묶음을 반환할 것입니다. 지정자는 아직 임포트되지 않은 모듈이나 패키지를 가리킬 수 있습니다; 부작용(side-effect)으로써 그것들이 임포트될 것입니다.

이 메서드는 주어진 module에 상대적인 name을 선택적으로 해석할 수 있습니다.

버전 3.5에서 변경: 만약 name 순회 중에 ImportError나 AttributeError가 발생한다면 실행할 때 그 에러를 일으키는 합성 테스트가 반환될 것입니다. 이 에러는 self.errors 에러 모임에 포함될 것입니다.

loadTestsFromNames(names, module=None)

loadTestsFromName()와 비슷하지만, 1개의 이름이 아닌 이름의 시퀀스를 받습니다. 반환 값은 각 이름에 정의된 모든 테스트를 지원하는 테스트 묶음입니다.

getTestCaseNames(testCaseClass)

testCaseClass 안에서 찾은 메서드 이름을 정렬된 시퀀스로 반환합니다; 이 클래스는 TestCase의 서브 클래스이어야 합니다.

discover(start_dir, pattern='test*.py', top_level_dir=None)

지정된 시작 디렉터리부터 하위 디렉터리를 재귀적으로 순회하여 모든 테스트 모듈을 찾아, 이를 포함하는 TestSuite 객체를 반환합니다. pattern에 일치하는 테스트 파일만 로드될 것입니다. (셸 방식의 패턴 일치를 사용합니다.) 임포트 가능한(즉, 유효한 파이썬 식별자인) 모듈 이름만 로드될 것입니다.

모든 테스트 모듈은 반드시 프로젝트의 최상위 수준에서 임포트 가능해야 합니다. 만약 시작 디렉터리가 최상위 디렉터리가 아니라면 최상위 디렉터리를 따로 지정해야 합니다.

만약 모듈 임포트가 실패한다면, 예를 들어 문법 에러로 인해, 이것은 1개의 에러로 기록되고 탐색이 계속 진행될 것입니다. 만약 SkipTest가 발생해서 임포트가 실패했다면, 이것은 에러가 아닌 건너뛰기로 기록될 것입니다.

만약 패키지(__init__.py 라는 이름의 파일을 포함한 디렉터리)를 찾으면, load_tests 함수가 있는지 패키지를 검사할 것입니다. 만약 존재한다면 그 패키지에 대해서 package.load_tests(loader, tests, pattern)가 불릴 것입니다. 만약 load_tests 함수 자체가 loader.discover를 호출할지라도, 테스트 탐색은 실행 중에 패키지에 대한 테스트 검사를 한 번만 실행하도록 보장합니다.

만약 load_tests가 존재한다면 탐색은 패키지 안을 재귀 탐색하지 않습니다. load_tests가 패키지 안의 모든 테스트를 로드할 책임이 있습니다.

패턴은 의도적으로 로더 어트리뷰트로 저장되지 않아 패키지가 자신에 대한 탐색을 계속할 수 있습니다. top_level_dir는 저장되어 load_tests가 loader.discover()에게 이 인자를 건네줄 필요가 없습니다.

start_dir는 디렉터리뿐만 아니라 점으로 구분된 모듈 이름이 될 수 있습니다.

버전 3.2에 추가.

버전 3.4에서 변경: 임포트 시에 SkipTest가 발생한 모듈은 에러가 아닌, 건너뛰기로 기록됩니다. 탐색은 이름 공간 패키지를 지원합니다. 임포트되기 전에 경로들이 정렬되어 파일 시스템의 정렬 순서가 파일 이름에 의존하지 않더라도 실행 순서가 같아지도록 합니다.

버전 3.5에서 변경: 이제 발견된 패키지는 그것의 경로가 pattern과 일치하는지 여부와 상관없이 load_tests를 검사합니다, 왜냐하면 패키지 이름이 기본 패턴과 일치하는 것이 불가능하기 때문입니다.

TestLoader의 다음 어트리뷰트들은 서브 클래스나 인스턴스에 대입을 통해 구성할 수 있습니다.

testMethodPrefix

테스트 메서드로 해석할 메서드 이름의 접두사에 해당하는 문자열입니다. 기본값은 'test' 입니다.

이것은 getTestCaseNames() 과 모든 loadTestsFrom*() 메서드에 영향을 미칩니다.

sortTestMethodsUsing

getTestCaseNames()와 모든 loadTestsFrom*() 메서드에서 메서드 이름 정렬 시에 이름 비교하는 데 사용될 함수입니다.

suiteClass

테스트 목록에서 테스트 묶음을 생성하는 콜러블 객체입니다. 결과 객체에 어떤 메서드도 필요하지 않습니다. 기본값은 TestSuite 클래스입니다.

이것은 모든 loadTestsFrom*() 메서드에 영향을 미칩니다.

testNamePatterns

테스트 묶음에 포함되기 위해서 테스트 메서드가 일치해야 할 유닉스 셸-방식의 와일드카드 테스트 이름 패턴 목록입니다(-v 옵션을 보십시오).

만약 이 어트리뷰트가 None(기본값)이 아니라면, 테스트 묶음에 포함될 모든 테스트 메서드는 이 목록의 패턴 중 1개와 반드시 일치해야 합니다. 이 패턴 일치는 항상 fnmatch.fnmatchcase()를 사용하여 수행된다는 것을 기억하십시오, 그래서 -v 옵션에 패턴을 건네주는 것과 달리, 간단한 부분 문자열 패턴은 * 와일드카드를 사용하도록 변경되어야 할 것입니다.

이것은 모든 loadTestsFrom*() 메서드에 영향을 미칩니다.

버전 3.7에 추가.

class unittest.TestResult

어떤 테스트가 성공했고 어떤 테스트가 실패했는지에 관한 정보를 엮는데 사용되는 클래스입니다.

TestResult 객체는 여러 테스트의 결과들을 저장합니다. TestCase와 TestSuite 클래스는 결과가 올바르게 기록되는 것을 보장합니다; 테스트 작성자가 테스트 결과를 기록하는 것에 대해서 걱정할 필요가 없습니다.

unittest 위에 만들어진 테스트 프레임워크는 보고 목적으로 여러 테스트가 실행하면서 만들어낸 TestResult 객체에 접근하고 싶을 수도 있습니다; TestRunner.run() 메서드는 이 목적을 위해 TestResult 인스턴스를 반환합니다.

TestResult 인스턴스는 테스트 실행 결과를 조사할 때 관심이 생길만한 다음과 같은 어트리뷰트를 가지고 있습니다.

errors

TestCase 인스턴스와 포맷된(formatted) 트레이스백 문자열로 구성된 2-튜플을 포함하는 목록입니다. 각 튜플은 예기치 못한 예외가 발생한 테스트에 해당합니다.

failures

TestCase 인스턴스와 포맷된(formatted) 트레이스백 문자열로 구성된 2-튜플을 포함하는 목록입니다. 각 튜플은 TestCase.assert*() 메서드를 사용하여 명시적으로 실패가 발생한 테스트에 해당합니다.

skipped

TestCase 인스턴스와 테스트 건너뛰기한 이유 문자열로 구성된 2-튜플을 포함하는 목록입니다.

버전 3.1에 추가.

expectedFailures

TestCase 인스턴스와 포맷된(formatted) 트레이스백 문자열로 구성된 2-튜플을 포함하는 목록입니다. 각 튜플은 테스트 케이스의 예상된 실패에 해당합니다.

unexpectedSuccesses

예상된 실패로 표시되었지만 성공한 TestCase 인스턴스를 포함하는 목록입니다.

shouldStop

테스트 실행이 stop()에 의해 정지되어야 할 때 True로 설정합니다.

testsRun

이제까지 실행된 테스트 총 개수입니다.

buffer

참으로 설정하면 sys.stdout와 sys.stderr가 startTest()와 stopTest() 호출 사이에서 버퍼링될 것입니다. 수집된 출력은 테스트가 실패하거나 에러가 발생한 경우에만 실제 sys.stdout와 sys.stderr에 출력될 것입니다. 모든 출력은 실패 / 에러 메시지에도 첨부됩니다.

버전 3.2에 추가.

failfast

참으로 설정하면 첫 번째 실패 또는 에러에서 stop()이 호출될 것입니다.

버전 3.2에 추가.

tb_locals

참으로 설정하면 지역 변수가 트레이스백에 보일 것입니다.

버전 3.5에 추가.

wasSuccessful()

이제까지 실행한 모든 테스트가 성공했다면 True를 반환하고, 그렇지 않으면 False를 반환합니다.

버전 3.4에서 변경: expectedFailure() 데코레이터로 표시된 테스트에서 unexpectedSuccesses가 있다면 False를 반환합니다.

stop()

shouldStop 어트리뷰트를 True로 설정하여 현재 실행 중인 테스트 모음을 중단해야 함을 알리기 위한 용도로 이 메서드를 부를 수 있습니다. TestRunner 객체는 이 신호를 존중하여 어떠한 추가 테스트 없이 반환해야 합니다.

예를 들어, 사용자가 키보드로 중단 신호를 보낼 때 테스트 프레임워크를 중단하기 위해 TextTestRunner가 이 기능을 사용합니다. TestRunner 구현을 제공하는 대화형 도구는 비슷한 방법으로 이것을 사용할 수 있습니다.

TestResult 클래스의 다음 메서드는 내부 자료 구조를 관리하려고 사용되고, 추가적인 보고 요구사항을 지원하기 위해 서브 클래스에서 확장할 수도 있습니다. 이것은 테스트가 실행 중에 대화형 보고를 지원하는 도구를 만들 때 특별히 유용합니다.

startTest(test)

테스트 케이스 test가 막 실행되려 할 때 호출됩니다.

stopTest(test)

결과에 상관없이 테스트 케이스 test가 실행되고 나서 호출됩니다.

startTestRun()

모든 테스트가 실행되기 전에 1번 호출됩니다.

버전 3.1에 추가.

stopTestRun()

모든 테스트가 실행되고 나서 1번 호출됩니다.

버전 3.1에 추가.

addError(test, err)

테스트 케이스 test가 예기치 못한 예외를 발생한 경우 호출됩니다. err는 sys.exc_info()가 반환한 형식의 튜플입니다: (type, value, traceback).

기본 구현은 (test, formatted_err) 튜플을 인스턴스의 errors 어트리뷰트에 추가합니다, 여기서 formatted_err는 err에서 파생된 포맷한 트레이스백입니다.

addFailure(test, err)

테스트 케이스 test가 실패 신호를 보낸 경우 호출됩니다. err는 sys.exc_info()가 반환한 형식의 튜플입니다: (type, value, traceback).

기본 구현은 (test, formatted_err) 튜플을 인스턴스의 failures 어트리뷰트에 추가합니다, 여기서 formatted_err는 err에서 파생된 포맷한 트레이스백입니다.

addSuccess(test)

테스트 케이스 test가 성공하면 호출됩니다.

기본 구현은 아무것도 하지 않습니다.

addSkip(test, reason)

테스트 케이스 test가 건너뛰어지면 호출됩니다. reason은 테스트가 준 건너뛰는 이유입니다.

기본 구현은 (test, reason) 튜플을 인스턴스의 skipped 어트리뷰트에 추가합니다.

addExpectedFailure(test, err)

테스트 케이스 test가 실패했지만 expectedFailure() 데코레이터로 표시된 경우 호출됩니다

기본 구현은 (test, formatted_err) 튜플을 인스턴스의 expectedFailures 어트리뷰트에 추가합니다, 여기서 formatted_err는 err에서 파생된 포맷한 트레이스백입니다.

addUnexpectedSuccess(test)

테스트 케이스 test가 expectedFailure() 데코레이터로 표시되었지만, 성공한 경우 호출됩니다.

기본 구현은 테스트를 인스턴스의 unexpectedSuccesses 어트리뷰트에 추가합니다.

addSubTest(test, subtest, outcome)

부분 테스트가 완료되었을 때 호출됩니다. test는 테스트 메서드에 대응하는 테스트 케이스입니다. subtest는 부분 테스트를 설명하는 사용자 지정 TestCase 인스턴스입니다.

outcome이 None이면, 부분 테스트가 성공한 것입니다. 그렇지 않으면 예외와 함께 실패한 것인데 outcome은 sys.exc_info()가 반환한 형식의 튜플입니다: (type, value, traceback).

기본 구현은 결과가 성공인 경우 아무것도 하지 않고 부분 테스트의 실패를 일반적인 실패로 기록합니다.

버전 3.4에 추가.

class unittest.TextTestResult(stream, descriptions, verbosity)

TextTestRunner에서 사용하는 TestResult의 구체적인 구현입니다.

버전 3.2에 추가: 이 클래스는 이전에 _TextTestResult 이름이었습니다. 이 이름은 여전히 에일리어스로 존재하지만 폐지된 상태입니다.

unittest.defaultTestLoader

공유 목적의 TestLoader 클래스의 인스턴스입니다. 만약 TestLoader를 사용자 정의할 필요가 없다면, 계속 새로운 인스턴스를 생성하는 것 대신 이 인스턴스를 사용할 수 있습니다.

class unittest.TextTestRunner(stream=None, descriptions=True, verbosity=1, failfast=False, buffer=False, resultclass=None, warnings=None, *, tb_locals=False)

결과를 스트림으로 출력하는 기본 테스트 실행자 구현입니다. 만약 stream이 기본값인 None이라면, sys.stderr가 출력 스트림으로 사용됩니다. 이 클래스는 몇 가지 설정 가능한 매개변수를 가지고 있지만, 본질적으로 매우 간단합니다. 테스트 묶음을 실행하는 그래픽 애플리케이션은 대안 구현을 제공해야 합니다. 이러한 구현은 unittest에 기능이 추가될 때 실행자를 만드는 인터페이스가 변하기 때문에 **kwargs를 받아들여야 합니다.

기본적으로 이 실행자는 DeprecationWarning, PendingDeprecationWarning, ResourceWarning, ImportWarning이 기본적으로 무시 설정이 되어 있더라도 이것들을 보여줍니다. 폐지된 unittest 메서드 에 의해 발생한 폐지 경고도 특수한 경우이고, 경고 필터가 'default' 또는 'always' 일 때, 너무 많은 경고 메시지를 피하고자 그것들이 모듈당 1번만 보일 것입니다. 파이썬의 -Wd이나 -Wa 옵션(경고 제어를 보십시오)을 사용하고 warnings를 None으로 설정하여 이 동작을 오버라이드 할 수 있습니다.

버전 3.2에서 변경: warnings 인자 추가.

버전 3.2에서 변경: 임포트 시간이 아닌 인스턴스화 시간에 기본 스트림이 sys.stderr으로 설정됩니다.

버전 3.5에서 변경: tb_locals 매개변수 추가.

_makeResult()

이 메서드는 run()가 사용하는 TestResult 인스턴스를 반환합니다. 직접 호출하게 의도되지 않았지만, 사용자 정의 TestResult를 제공하기 위해 서브 클래스에서 오버라이드할 수 있습니다.

_makeResult()는 TextTestRunner 생성자에 resultclass 인자로 전달된 클래스나 콜러블을 인스턴스화합니다. 만약 resultclass가 제공되지 않았다면 기본값은 TextTestResult 입니다. 결과 클래스는 다음 인자와 함께 인스턴스화됩니다:

stream, descriptions, verbosity

run(test)

이 메서드는 TextTestRunner의 주된 공개 인터페이스입니다. 이 메서드는 TestSuite나 TestCase 인스턴스를 받습니다. TestResult는 _makeResult()를 호출하여 생성하고 테스트가 실행되며 결과가 stdout에 출력됩니다.

unittest.main(module='__main__', defaultTest=None, argv=None, testRunner=None, testLoader=unittest.defaultTestLoader, exit=True, verbosity=1, failfast=None, catchbreak=None, buffer=None, warnings=None)

module에서 테스트 모음을 로드하고 실행하는 명령행 프로그램입니다; 이것은 주로 편리하게 실행 가능한 테스트 모듈을 만들기 위한 것입니다. 이 함수의 가장 간단한 사용은 테스트 스크립트 마지막에 다음과 같은 줄을 포함하는 것입니다:

if __name__ == '__main__':
    unittest.main()

당신은 상세도 인자를 전달하여 좀 더 자세한 정보와 함께 테스트를 실행할 수 있습니다:

if __name__ == '__main__':
    unittest.main(verbosity=2)

defaultTest 인자는 argv로 테스트 이름이 지정되지 않은 경우 실행될 1개의 테스트 이름이거나 테스트 이름의 이터러블입니다. 만약 이 인자가 지정되지 않거나 None이면서 argv로 테스트 이름이 지정되지 않으면 module 안에서 찾은 모든 테스트가 실행됩니다.

argv 인자는 프로그램에 전달된 옵션 목록이 될 수 있습니다, 첫 번째 요소는 프로그램 이름입니다. 만약 이 인자가 지정되지 않거나 None이면, sys.argv 값이 사용됩니다.

testRunner 인자는 테스트 실행자 클래스나 이미 생성된 테스트 실행자 인스턴스일 수 있습니다. 기본적으로 main은 실행한 테스트가 성공인지 실패인지를 나타내는 종료 코드와 함께 sys.exit()을 호출합니다.

testLoader 인자는 TestLoader 인스턴스이어야 하고 기본값은 defaultTestLoader 입니다.

main은 exit=False 인자를 전달하여 대화형 인터프리터에서 사용하는 것을 지원합니다. 이것은 sys.exit() 호출 없이 결과가 표준 출력에 표시됩니다:

>>> from unittest import main
>>> main(module='test_module', exit=False)

failfast, catchbreak, buffer 매개변수는 명령행 옵션의 같은 이름과 같은 효과를 가지고 있습니다.

warnings 인자는 테스트 실행 중에 사용되어야 할 경고 필터를 지정합니다. 만약 아무 값도 지정되지 않았다면, -W 옵션이 python으로 전달된 경우(경고 제어를 보십시오)에는 None으로 남아 있고, 그렇지 않은 경우에는 'default'로 설정됩니다.

사실 main 호출은 TestProgram 클래스의 인스턴스를 반환합니다. 이것은 실행된 테스트의 결과를 result 어트리뷰트에 저장합니다.

버전 3.1에서 변경: exit 매개변수가 추가되었습니다.

버전 3.2에서 변경: verbosity, failfast, catchbreak, buffer, warnings 매개변수가 추가되었습니다.

버전 3.4에서 변경: defaultTest 매개변수가 테스트 이름의 이터러블도 받을 수 있게 바뀌었습니다.

load_tests 프로토콜

버전 3.2에 추가.

load_tests 라 불리는 함수를 구현함으로써 모듈이나 패키지는 일반 테스트 실행이나 테스트 탐색 중에 그것들로부터 테스트가 어떻게 로드될지를 사용자 정의할 수 있습니다.

만약 테스트 모듈이 load_tests를 정의했다면 그것은 다음 인자와 함께 TestLoader.loadTestsFromModule()의해 호출될 것입니다:

load_tests(loader, standard_tests, pattern)

여기서 pattern은 loadTestsFromModule에서 바로 전달된 것입니다. 기본값은 None입니다.

이것은 TestSuite를 반환해야 합니다.

loader는 로딩을 실행할 TestLoader 인스턴스입니다. standard_tests는 모듈에서 기본적으로 로드될 테스트입니다. 테스트 모듈이 테스트 기본 모음에서 오직 테스트를 추가하거나 빼기를 원하는 것은 흔한 일입니다. 세 번째 인자는 테스트 탐색의 일부로서 패키지를 로드할 때 사용됩니다.

특정 TestCase 클래스 모음에서 테스트를 로드하는 전형적인 load_tests 함수는 다음과 같습니다:

test_cases = (TestCase1, TestCase2, TestCase3)

def load_tests(loader, tests, pattern):
    suite = TestSuite()
    for test_class in test_cases:
        tests = loader.loadTestsFromTestCase(test_class)
        suite.addTests(tests)
    return suite

만약 탐색이 명령행 또는 TestLoader.discover()로부터, 패키지가 포함된 디렉터리에서 시작된다면, load_tests를 위해 패키지 __init__.py를 검사합니다. 만약 함수가 존재하지 않으면, 탐색은 그저 다른 디렉터리인 것처럼 패키지 안을 재귀 순회할 것입니다. 그렇지 않다면, 패키지의 테스트를 위한 탐색은 다음 인자와 함께 불리는 load_tests에게 맡겨질 것입니다:

load_tests(loader, standard_tests, pattern)

이것은 패키지의 모든 테스트에 해당하는 TestSuite를 반환해야 합니다. (standard_tests는 오직 __init__.py로부터 수집된 테스트만 포함할 것입니다.

패턴이 load_tests로 전달되기 때문에 패키지는 테스트 검색을 계속 진행(그리고 잠재적으로 수정)할 수 있습니다. 테스트 패키지를 위해서 ‘아무것도 하지 않는’ load_tests 함수는 다음과 같을 것입니다:

def load_tests(loader, standard_tests, pattern):
    # top level directory cached on loader instance
    this_dir = os.path.dirname(__file__)
    package_tests = loader.discover(start_dir=this_dir, pattern=pattern)
    standard_tests.addTests(package_tests)
    return standard_tests

버전 3.5에서 변경: 패키지 이름이 기본 패턴과 일치하는 것이 불가능하기 때문에 탐색이 더는 pattern 일치를 위해서 패키지 이름을 검사하지 않습니다.

클래스와 모듈 픽스쳐

클래스와 모듈 단계의 픽스쳐는 TestSuite에 구현되어 있습니다. 테스트 묶음이 새로운 클래스의 테스트를 만나면(만약 존재한다면) 이전 클래스의 tearDownClass() 가 호출되고, 이어 새로운 클래스의 setUpClass()가 호출됩니다.

마찬가지로 만약 테스트가 이전 테스트와 다른 모듈의 것이라면 이전 모듈의 tearDownModule이 실행되고, 이어 새로운 모듈의 setUpModule이 호출됩니다.

모든 테스트가 실행된 뒤에 마지막으로 tearDownClass와 tearDownModule이 실행됩니다.

공유하는 픽스쳐의 경우 테스트 병렬화와 같은 [잠재적인] 기능과 잘 동작하지 않고 이것은 테스트 분리를 망가트립니다. 이것을 주의 깊게 사용해야 합니다.

unittest의 테스트 로더에 의해 생성된 테스트들의 기본 정렬 순서는 같은 모듈과 클래스의 모든 테스트를 그룹화하는 것입니다. 이것은 setUpClass / setUpModule(등) 이 클래스와 모듈별로 정확하게 1번씩 호출되게 할 것입니다. 만약 당신이 무작위로 순서를 정하여, 그래서 다른 모듈과 클래스의 테스트가 서로 인접한다면, 이 공유 픽스처 함수는 1번의 테스트 실행에서 여러 번 호출될 수 있습니다.

공유 픽스처는 비표준 정렬 순서를 사용하는 테스트 묶음과 같이 작동하는 것을 의도하지 않습니다. 공유 픽스처를 지원하길 원치 않는 프레임워크를 위해서 BaseTestSuite가 여전히 존재합니다.

공유 픽스처 함수 중 1개에서 발생한 예외가 있다면, 테스트를 에러로 보고합니다. 해당 테스트 인스턴스가 없기 때문에 에러를 나타내기 위해 _ErrorHolder 객체(TestCase와 같은 인터페이스를 가진)가 생성됩니다. 당신이 그저 표준 unittest의 테스트 실행자를 사용한다면 이 세부 항목은 중요하지 않습니다, 그러나 당신이 프레임워크의 저자라면 이것은 관련이 있을 수 있습니다.

setUpClass 와 tearDownClass

이것들은 반드시 클래스 메서드로 구현되어야 합니다:

import unittest

class Test(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cls._connection = createExpensiveConnectionObject()

    @classmethod
    def tearDownClass(cls):
        cls._connection.destroy()

만약 당신이 베이스 클래스의 setUpClass와 tearDownClass를 호출하고 싶다면 당신이 그것을 직접 호출해야만 합니다. TestCase의 구현은 비어있습니다.

만약 setUpClass 중에 예외가 발생한다면 클래스의 테스트는 실행되지 않고 tearDownClass 는 실행되지 않습니다. 건너뛴 클래스는 setUpClass 또는 tearDownClass가 실행되지 않을 것입니다. 만약 예외가 SkipTest 예외라면 클래스는 에러 대신 건너뛰어졌다고 보고될 것입니다.

setUpModule 과 tearDownModule

이것들은 함수로 구현되어야 합니다:

def setUpModule():
    createConnection()

def tearDownModule():
    closeConnection()

만약 setUpModule 중에 예외가 발생한다면 모듈의 테스트는 실행되지 않고 tearDownModule 는 실행되지 않습니다. 만약 예외가 SkipTest 예외라면 모듈은 에러 대신 건너뛰어졌다고 보고될 것입니다.

시그널 처리하기

버전 3.2에 추가.

unittest의 -c/--catch 명령행 옵션은, unittest.main()의 catchbreak 매개 변수와 함께, 테스트 실행 중에 control-C를 사용하기 편하게 처리하도록 합니다. 중단 시그널 잡기를 활성화 하면 control-C는 현재 실행 중인 테스트를 완료하고, 그러면 테스트 실행이 끝나고 이제까지의 모든 결과를 보고할 것입니다. 두 번째 control-c는 평소와 같이 KeyboardInterrupt를 발생할 것입니다.

control-c 시그널 처리기는 자체 signal.SIGINT 처리기를 설치하는 코드 또는 테스트와의 호환성을 유지하려고 노력합니다. 만약 unittest 처리기가 불리지만 그것이 설치된 signal.SIGINT 처리기가 아니면, 즉 그것이 테스트 중에 시스템에 의해 대체되고 위임된다면, 그것은 기본 처리기를 호출합니다. 이것은 설치된 처리기를 대체하고 위임하는 코드에 의해 일반적으로 기대되는 동작입니다. unittest control-c 처리를 개별 테스트 별로 비활성화하고 싶을 때는 removeHandler() 데코레이터를 사용할 수 있습니다.

프레임워크 작성자가 테스트 프레임워크에서 control-c 처리 기능을 활성화하기 위해 몇 가지 유틸리티 함수가 있습니다.

unittest.installHandler()

control-c 처리기를 설치합니다. signal.SIGINT를 받았을 때(보통 사용자가 control-c를 눌렀을 때의 응답으로써) 모든 등록된 결과에 stop()이 호출됩니다.

unittest.registerResult(result)

control-c 처리를 위해서 TestResult 객체를 등록합니다. 결과 등록은 그것의 약한 참조를 저장합니다, 그래서 결과가 가비지 수거되는 것을 막지 않습니다.

만약 control-c 처리가 활성화되지 않았다면 TestResult 객체 등록은 부작용이 없습니다, 그래서 테스트 프레임워크는 처리가 가능한지 여부와 관계없이 자신이 만든 모든 결과를 무조건 등록할 수 있습니다.

unittest.removeResult(result)

등록한 결과를 제거합니다. 결과가 제거되고 나면 control-c에 대한 응답으로 결과 객체의 stop()을 더는 호출하지 않게 됩니다.

unittest.removeHandler(function=None)

인자 없이 호출된 경우 이 함수는 만약 control-c 처리기가 설치되었다면 그것을 제거합니다. 또한 이 함수는 테스트 실행 중에 임시로 처리기를 제거하기 위해 테스트 데코레이터로써 사용될 수도 있습니다:

@unittest.removeHandler
def test_signal_handling(self):
    ...

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

개발 도구 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

개발 도구 »

|

unittest.mock — mock object library

버전 3.3에 추가.

Source code: Lib/unittest/mock.py [https://github.com/python/cpython/tree/3.7/Lib/unittest/mock.py]

unittest.mock is a library for testing in Python. It allows you to replace parts of your system under test with mock objects and make assertions about how they have been used.

unittest.mock provides a core Mock class removing the need to create a host of stubs throughout your test suite. After performing an action, you can make assertions about which methods / attributes were used and arguments they were called with. You can also specify return values and set needed attributes in the normal way.

Additionally, mock provides a patch() decorator that handles patching module and class level attributes within the scope of a test, along with sentinel for creating unique objects. See the quick guide for some examples of how to use Mock, MagicMock and patch().

Mock is very easy to use and is designed for use with unittest. Mock is based on the ‘action -> assertion’ pattern instead of ‘record -> replay’ used by many mocking frameworks.

There is a backport of unittest.mock for earlier versions of Python, available as mock on PyPI [https://pypi.org/project/mock].

Quick Guide

Mock and MagicMock objects create all attributes and methods as you access them and store details of how they have been used. You can configure them, to specify return values or limit what attributes are available, and then make assertions about how they have been used:

>>> from unittest.mock import MagicMock
>>> thing = ProductionClass()
>>> thing.method = MagicMock(return_value=3)
>>> thing.method(3, 4, 5, key='value')
3
>>> thing.method.assert_called_with(3, 4, 5, key='value')

side_effect allows you to perform side effects, including raising an exception when a mock is called:

>>> mock = Mock(side_effect=KeyError('foo'))
>>> mock()
Traceback (most recent call last):
 ...
KeyError: 'foo'

>>> values = {'a': 1, 'b': 2, 'c': 3}
>>> def side_effect(arg):
...     return values[arg]
...
>>> mock.side_effect = side_effect
>>> mock('a'), mock('b'), mock('c')
(1, 2, 3)
>>> mock.side_effect = [5, 4, 3, 2, 1]
>>> mock(), mock(), mock()
(5, 4, 3)

Mock has many other ways you can configure it and control its behaviour. For example the spec argument configures the mock to take its specification from another object. Attempting to access attributes or methods on the mock that don’t exist on the spec will fail with an AttributeError.

The patch() decorator / context manager makes it easy to mock classes or objects in a module under test. The object you specify will be replaced with a mock (or other object) during the test and restored when the test ends:

>>> from unittest.mock import patch
>>> @patch('module.ClassName2')
... @patch('module.ClassName1')
... def test(MockClass1, MockClass2):
...     module.ClassName1()
...     module.ClassName2()
...     assert MockClass1 is module.ClassName1
...     assert MockClass2 is module.ClassName2
...     assert MockClass1.called
...     assert MockClass2.called
...
>>> test()

참고

When you nest patch decorators the mocks are passed in to the decorated function in the same order they applied (the normal Python order that decorators are applied). This means from the bottom up, so in the example above the mock for module.ClassName1 is passed in first.

With patch() it matters that you patch objects in the namespace where they are looked up. This is normally straightforward, but for a quick guide read where to patch.

As well as a decorator patch() can be used as a context manager in a with statement:

>>> with patch.object(ProductionClass, 'method', return_value=None) as mock_method:
...     thing = ProductionClass()
...     thing.method(1, 2, 3)
...
>>> mock_method.assert_called_once_with(1, 2, 3)

There is also patch.dict() for setting values in a dictionary just during a scope and restoring the dictionary to its original state when the test ends:

>>> foo = {'key': 'value'}
>>> original = foo.copy()
>>> with patch.dict(foo, {'newkey': 'newvalue'}, clear=True):
...     assert foo == {'newkey': 'newvalue'}
...
>>> assert foo == original

Mock supports the mocking of Python magic methods. The easiest way of using magic methods is with the MagicMock class. It allows you to do things like:

>>> mock = MagicMock()
>>> mock.__str__.return_value = 'foobarbaz'
>>> str(mock)
'foobarbaz'
>>> mock.__str__.assert_called_with()

Mock allows you to assign functions (or other Mock instances) to magic methods and they will be called appropriately. The MagicMock class is just a Mock variant that has all of the magic methods pre-created for you (well, all the useful ones anyway).

The following is an example of using magic methods with the ordinary Mock class:

>>> mock = Mock()
>>> mock.__str__ = Mock(return_value='wheeeeee')
>>> str(mock)
'wheeeeee'

For ensuring that the mock objects in your tests have the same api as the objects they are replacing, you can use auto-speccing. Auto-speccing can be done through the autospec argument to patch, or the create_autospec() function. Auto-speccing creates mock objects that have the same attributes and methods as the objects they are replacing, and any functions and methods (including constructors) have the same call signature as the real object.

This ensures that your mocks will fail in the same way as your production code if they are used incorrectly:

>>> from unittest.mock import create_autospec
>>> def function(a, b, c):
...     pass
...
>>> mock_function = create_autospec(function, return_value='fishy')
>>> mock_function(1, 2, 3)
'fishy'
>>> mock_function.assert_called_once_with(1, 2, 3)
>>> mock_function('wrong arguments')
Traceback (most recent call last):
 ...
TypeError: <lambda>() takes exactly 3 arguments (1 given)

create_autospec() can also be used on classes, where it copies the signature of the __init__ method, and on callable objects where it copies the signature of the __call__ method.

The Mock Class

Mock is a flexible mock object intended to replace the use of stubs and test doubles throughout your code. Mocks are callable and create attributes as new mocks when you access them 1. Accessing the same attribute will always return the same mock. Mocks record how you use them, allowing you to make assertions about what your code has done to them.

MagicMock is a subclass of Mock with all the magic methods pre-created and ready to use. There are also non-callable variants, useful when you are mocking out objects that aren’t callable: NonCallableMock and NonCallableMagicMock

The patch() decorators makes it easy to temporarily replace classes in a particular module with a Mock object. By default patch() will create a MagicMock for you. You can specify an alternative class of Mock using the new_callable argument to patch().

class unittest.mock.Mock(spec=None, side_effect=None, return_value=DEFAULT, wraps=None, name=None, spec_set=None, unsafe=False, **kwargs)

Create a new Mock object. Mock takes several optional arguments that specify the behaviour of the Mock object:

spec: This can be either a list of strings or an existing object (a class or instance) that acts as the specification for the mock object. If you pass in an object then a list of strings is formed by calling dir on the object (excluding unsupported magic attributes and methods). Accessing any attribute not in this list will raise an AttributeError.

If spec is an object (rather than a list of strings) then __class__ returns the class of the spec object. This allows mocks to pass isinstance() tests.

spec_set: A stricter variant of spec. If used, attempting to set or get an attribute on the mock that isn’t on the object passed as spec_set will raise an AttributeError.

side_effect: A function to be called whenever the Mock is called. See the side_effect attribute. Useful for raising exceptions or dynamically changing return values. The function is called with the same arguments as the mock, and unless it returns DEFAULT, the return value of this function is used as the return value.

Alternatively side_effect can be an exception class or instance. In this case the exception will be raised when the mock is called.

If side_effect is an iterable then each call to the mock will return the next value from the iterable.

A side_effect can be cleared by setting it to None.

return_value: The value returned when the mock is called. By default this is a new Mock (created on first access). See the return_value attribute.

unsafe: By default if any attribute starts with assert or assret will raise an AttributeError. Passing unsafe=True will allow access to these attributes.

버전 3.5에 추가.

wraps: Item for the mock object to wrap. If wraps is not None then calling the Mock will pass the call through to the wrapped object (returning the real result). Attribute access on the mock will return a Mock object that wraps the corresponding attribute of the wrapped object (so attempting to access an attribute that doesn’t exist will raise an AttributeError).

If the mock has an explicit return_value set then calls are not passed to the wrapped object and the return_value is returned instead.

name: If the mock has a name then it will be used in the repr of the mock. This can be useful for debugging. The name is propagated to child mocks.

Mocks can also be called with arbitrary keyword arguments. These will be used to set attributes on the mock after it is created. See the configure_mock() method for details.

assert_called()

Assert that the mock was called at least once.

>>> mock = Mock()
>>> mock.method()
<Mock name='mock.method()' id='...'>
>>> mock.method.assert_called()

버전 3.6에 추가.

assert_called_once()

Assert that the mock was called exactly once.

>>> mock = Mock()
>>> mock.method()
<Mock name='mock.method()' id='...'>
>>> mock.method.assert_called_once()
>>> mock.method()
<Mock name='mock.method()' id='...'>
>>> mock.method.assert_called_once()
Traceback (most recent call last):
...
AssertionError: Expected 'method' to have been called once. Called 2 times.

버전 3.6에 추가.

assert_called_with(*args, **kwargs)

This method is a convenient way of asserting that calls are made in a particular way:

>>> mock = Mock()
>>> mock.method(1, 2, 3, test='wow')
<Mock name='mock.method()' id='...'>
>>> mock.method.assert_called_with(1, 2, 3, test='wow')

assert_called_once_with(*args, **kwargs)

Assert that the mock was called exactly once and that that call was with the specified arguments.

>>> mock = Mock(return_value=None)
>>> mock('foo', bar='baz')
>>> mock.assert_called_once_with('foo', bar='baz')
>>> mock('other', bar='values')
>>> mock.assert_called_once_with('other', bar='values')
Traceback (most recent call last):
  ...
AssertionError: Expected 'mock' to be called once. Called 2 times.

assert_any_call(*args, **kwargs)

assert the mock has been called with the specified arguments.

The assert passes if the mock has ever been called, unlike assert_called_with() and assert_called_once_with() that only pass if the call is the most recent one, and in the case of assert_called_once_with() it must also be the only call.

>>> mock = Mock(return_value=None)
>>> mock(1, 2, arg='thing')
>>> mock('some', 'thing', 'else')
>>> mock.assert_any_call(1, 2, arg='thing')

assert_has_calls(calls, any_order=False)

assert the mock has been called with the specified calls. The mock_calls list is checked for the calls.

If any_order is false then the calls must be sequential. There can be extra calls before or after the specified calls.

If any_order is true then the calls can be in any order, but they must all appear in mock_calls.

>>> mock = Mock(return_value=None)
>>> mock(1)
>>> mock(2)
>>> mock(3)
>>> mock(4)
>>> calls = [call(2), call(3)]
>>> mock.assert_has_calls(calls)
>>> calls = [call(4), call(2), call(3)]
>>> mock.assert_has_calls(calls, any_order=True)

assert_not_called()

Assert the mock was never called.

>>> m = Mock()
>>> m.hello.assert_not_called()
>>> obj = m.hello()
>>> m.hello.assert_not_called()
Traceback (most recent call last):
  ...
AssertionError: Expected 'hello' to not have been called. Called 1 times.

버전 3.5에 추가.

reset_mock(*, return_value=False, side_effect=False)

The reset_mock method resets all the call attributes on a mock object:

>>> mock = Mock(return_value=None)
>>> mock('hello')
>>> mock.called
True
>>> mock.reset_mock()
>>> mock.called
False

버전 3.6에서 변경: Added two keyword only argument to the reset_mock function.

This can be useful where you want to make a series of assertions that reuse the same object. Note that reset_mock() doesn’t clear the return value, side_effect or any child attributes you have set using normal assignment by default. In case you want to reset return_value or side_effect, then pass the corresponding parameter as True. Child mocks and the return value mock (if any) are reset as well.

참고

return_value, and side_effect are keyword only argument.

mock_add_spec(spec, spec_set=False)

Add a spec to a mock. spec can either be an object or a list of strings. Only attributes on the spec can be fetched as attributes from the mock.

If spec_set is true then only attributes on the spec can be set.

attach_mock(mock, attribute)

Attach a mock as an attribute of this one, replacing its name and parent. Calls to the attached mock will be recorded in the method_calls and mock_calls attributes of this one.

configure_mock(**kwargs)

Set attributes on the mock through keyword arguments.

Attributes plus return values and side effects can be set on child mocks using standard dot notation and unpacking a dictionary in the method call:

>>> mock = Mock()
>>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
>>> mock.configure_mock(**attrs)
>>> mock.method()
3
>>> mock.other()
Traceback (most recent call last):
  ...
KeyError

The same thing can be achieved in the constructor call to mocks:

>>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
>>> mock = Mock(some_attribute='eggs', **attrs)
>>> mock.some_attribute
'eggs'
>>> mock.method()
3
>>> mock.other()
Traceback (most recent call last):
  ...
KeyError

configure_mock() exists to make it easier to do configuration after the mock has been created.

__dir__()

Mock objects limit the results of dir(some_mock) to useful results. For mocks with a spec this includes all the permitted attributes for the mock.

See FILTER_DIR for what this filtering does, and how to switch it off.

_get_child_mock(**kw)

Create the child mocks for attributes and return value. By default child mocks will be the same type as the parent. Subclasses of Mock may want to override this to customize the way child mocks are made.

For non-callable mocks the callable variant will be used (rather than any custom subclass).

called

A boolean representing whether or not the mock object has been called:

>>> mock = Mock(return_value=None)
>>> mock.called
False
>>> mock()
>>> mock.called
True

call_count

An integer telling you how many times the mock object has been called:

>>> mock = Mock(return_value=None)
>>> mock.call_count
0
>>> mock()
>>> mock()
>>> mock.call_count
2

return_value

Set this to configure the value returned by calling the mock:

>>> mock = Mock()
>>> mock.return_value = 'fish'
>>> mock()
'fish'

The default return value is a mock object and you can configure it in the normal way:

>>> mock = Mock()
>>> mock.return_value.attribute = sentinel.Attribute
>>> mock.return_value()
<Mock name='mock()()' id='...'>
>>> mock.return_value.assert_called_with()

return_value can also be set in the constructor:

>>> mock = Mock(return_value=3)
>>> mock.return_value
3
>>> mock()
3

side_effect

This can either be a function to be called when the mock is called, an iterable or an exception (class or instance) to be raised.

If you pass in a function it will be called with same arguments as the mock and unless the function returns the DEFAULT singleton the call to the mock will then return whatever the function returns. If the function returns DEFAULT then the mock will return its normal value (from the return_value).

If you pass in an iterable, it is used to retrieve an iterator which must yield a value on every call. This value can either be an exception instance to be raised, or a value to be returned from the call to the mock (DEFAULT handling is identical to the function case).

An example of a mock that raises an exception (to test exception handling of an API):

>>> mock = Mock()
>>> mock.side_effect = Exception('Boom!')
>>> mock()
Traceback (most recent call last):
  ...
Exception: Boom!

Using side_effect to return a sequence of values:

>>> mock = Mock()
>>> mock.side_effect = [3, 2, 1]
>>> mock(), mock(), mock()
(3, 2, 1)

Using a callable:

>>> mock = Mock(return_value=3)
>>> def side_effect(*args, **kwargs):
...     return DEFAULT
...
>>> mock.side_effect = side_effect
>>> mock()
3

side_effect can be set in the constructor. Here’s an example that adds one to the value the mock is called with and returns it:

>>> side_effect = lambda value: value + 1
>>> mock = Mock(side_effect=side_effect)
>>> mock(3)
4
>>> mock(-8)
-7

Setting side_effect to None clears it:

>>> m = Mock(side_effect=KeyError, return_value=3)
>>> m()
Traceback (most recent call last):
 ...
KeyError
>>> m.side_effect = None
>>> m()
3

call_args

This is either None (if the mock hasn’t been called), or the arguments that the mock was last called with. This will be in the form of a tuple: the first member is any ordered arguments the mock was called with (or an empty tuple) and the second member is any keyword arguments (or an empty dictionary).

>>> mock = Mock(return_value=None)
>>> print(mock.call_args)
None
>>> mock()
>>> mock.call_args
call()
>>> mock.call_args == ()
True
>>> mock(3, 4)
>>> mock.call_args
call(3, 4)
>>> mock.call_args == ((3, 4),)
True
>>> mock(3, 4, 5, key='fish', next='w00t!')
>>> mock.call_args
call(3, 4, 5, key='fish', next='w00t!')

call_args, along with members of the lists call_args_list, method_calls and mock_calls are call objects. These are tuples, so they can be unpacked to get at the individual arguments and make more complex assertions. See calls as tuples.

call_args_list

This is a list of all the calls made to the mock object in sequence (so the length of the list is the number of times it has been called). Before any calls have been made it is an empty list. The call object can be used for conveniently constructing lists of calls to compare with call_args_list.

>>> mock = Mock(return_value=None)
>>> mock()
>>> mock(3, 4)
>>> mock(key='fish', next='w00t!')
>>> mock.call_args_list
[call(), call(3, 4), call(key='fish', next='w00t!')]
>>> expected = [(), ((3, 4),), ({'key': 'fish', 'next': 'w00t!'},)]
>>> mock.call_args_list == expected
True

Members of call_args_list are call objects. These can be unpacked as tuples to get at the individual arguments. See calls as tuples.

method_calls

As well as tracking calls to themselves, mocks also track calls to methods and attributes, and their methods and attributes:

>>> mock = Mock()
>>> mock.method()
<Mock name='mock.method()' id='...'>
>>> mock.property.method.attribute()
<Mock name='mock.property.method.attribute()' id='...'>
>>> mock.method_calls
[call.method(), call.property.method.attribute()]

Members of method_calls are call objects. These can be unpacked as tuples to get at the individual arguments. See calls as tuples.

mock_calls

mock_calls records all calls to the mock object, its methods, magic methods and return value mocks.

>>> mock = MagicMock()
>>> result = mock(1, 2, 3)
>>> mock.first(a=3)
<MagicMock name='mock.first()' id='...'>
>>> mock.second()
<MagicMock name='mock.second()' id='...'>
>>> int(mock)
1
>>> result(1)
<MagicMock name='mock()()' id='...'>
>>> expected = [call(1, 2, 3), call.first(a=3), call.second(),
... call.__int__(), call()(1)]
>>> mock.mock_calls == expected
True

Members of mock_calls are call objects. These can be unpacked as tuples to get at the individual arguments. See calls as tuples.

참고

The way mock_calls are recorded means that where nested calls are made, the parameters of ancestor calls are not recorded and so will always compare equal:

>>> mock = MagicMock()
>>> mock.top(a=3).bottom()
<MagicMock name='mock.top().bottom()' id='...'>
>>> mock.mock_calls
[call.top(a=3), call.top().bottom()]
>>> mock.mock_calls[-1] == call.top(a=-1).bottom()
True

__class__

Normally the __class__ attribute of an object will return its type. For a mock object with a spec, __class__ returns the spec class instead. This allows mock objects to pass isinstance() tests for the object they are replacing / masquerading as:

>>> mock = Mock(spec=3)
>>> isinstance(mock, int)
True

__class__ is assignable to, this allows a mock to pass an isinstance() check without forcing you to use a spec:

>>> mock = Mock()
>>> mock.__class__ = dict
>>> isinstance(mock, dict)
True

class unittest.mock.NonCallableMock(spec=None, wraps=None, name=None, spec_set=None, **kwargs)

A non-callable version of Mock. The constructor parameters have the same meaning of Mock, with the exception of return_value and side_effect which have no meaning on a non-callable mock.

Mock objects that use a class or an instance as a spec or spec_set are able to pass isinstance() tests:

>>> mock = Mock(spec=SomeClass)
>>> isinstance(mock, SomeClass)
True
>>> mock = Mock(spec_set=SomeClass())
>>> isinstance(mock, SomeClass)
True

The Mock classes have support for mocking magic methods. See magic methods for the full details.

The mock classes and the patch() decorators all take arbitrary keyword arguments for configuration. For the patch() decorators the keywords are passed to the constructor of the mock being created. The keyword arguments are for configuring attributes of the mock:

>>> m = MagicMock(attribute=3, other='fish')
>>> m.attribute
3
>>> m.other
'fish'

The return value and side effect of child mocks can be set in the same way, using dotted notation. As you can’t use dotted names directly in a call you have to create a dictionary and unpack it using **:

>>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
>>> mock = Mock(some_attribute='eggs', **attrs)
>>> mock.some_attribute
'eggs'
>>> mock.method()
3
>>> mock.other()
Traceback (most recent call last):
  ...
KeyError

A callable mock which was created with a spec (or a spec_set) will introspect the specification object’s signature when matching calls to the mock. Therefore, it can match the actual call’s arguments regardless of whether they were passed positionally or by name:

>>> def f(a, b, c): pass
...
>>> mock = Mock(spec=f)
>>> mock(1, 2, c=3)
<Mock name='mock()' id='140161580456576'>
>>> mock.assert_called_with(1, 2, 3)
>>> mock.assert_called_with(a=1, b=2, c=3)

This applies to assert_called_with(), assert_called_once_with(), assert_has_calls() and assert_any_call(). When Autospeccing, it will also apply to method calls on the mock object.

버전 3.4에서 변경: Added signature introspection on specced and autospecced mock objects.

class unittest.mock.PropertyMock(*args, **kwargs)

A mock intended to be used as a property, or other descriptor, on a class. PropertyMock provides __get__() and __set__() methods so you can specify a return value when it is fetched.

Fetching a PropertyMock instance from an object calls the mock, with no args. Setting it calls the mock with the value being set.

>>> class Foo:
...     @property
...     def foo(self):
...         return 'something'
...     @foo.setter
...     def foo(self, value):
...         pass
...
>>> with patch('__main__.Foo.foo', new_callable=PropertyMock) as mock_foo:
...     mock_foo.return_value = 'mockity-mock'
...     this_foo = Foo()
...     print(this_foo.foo)
...     this_foo.foo = 6
...
mockity-mock
>>> mock_foo.mock_calls
[call(), call(6)]

Because of the way mock attributes are stored you can’t directly attach a PropertyMock to a mock object. Instead you can attach it to the mock type object:

>>> m = MagicMock()
>>> p = PropertyMock(return_value=3)
>>> type(m).foo = p
>>> m.foo
3
>>> p.assert_called_once_with()

Calling

Mock objects are callable. The call will return the value set as the return_value attribute. The default return value is a new Mock object; it is created the first time the return value is accessed (either explicitly or by calling the Mock) - but it is stored and the same one returned each time.

Calls made to the object will be recorded in the attributes like call_args and call_args_list.

If side_effect is set then it will be called after the call has been recorded, so if side_effect raises an exception the call is still recorded.

The simplest way to make a mock raise an exception when called is to make side_effect an exception class or instance:

>>> m = MagicMock(side_effect=IndexError)
>>> m(1, 2, 3)
Traceback (most recent call last):
  ...
IndexError
>>> m.mock_calls
[call(1, 2, 3)]
>>> m.side_effect = KeyError('Bang!')
>>> m('two', 'three', 'four')
Traceback (most recent call last):
  ...
KeyError: 'Bang!'
>>> m.mock_calls
[call(1, 2, 3), call('two', 'three', 'four')]

If side_effect is a function then whatever that function returns is what calls to the mock return. The side_effect function is called with the same arguments as the mock. This allows you to vary the return value of the call dynamically, based on the input:

>>> def side_effect(value):
...     return value + 1
...
>>> m = MagicMock(side_effect=side_effect)
>>> m(1)
2
>>> m(2)
3
>>> m.mock_calls
[call(1), call(2)]

If you want the mock to still return the default return value (a new mock), or any set return value, then there are two ways of doing this. Either return mock.return_value from inside side_effect, or return DEFAULT:

>>> m = MagicMock()
>>> def side_effect(*args, **kwargs):
...     return m.return_value
...
>>> m.side_effect = side_effect
>>> m.return_value = 3
>>> m()
3
>>> def side_effect(*args, **kwargs):
...     return DEFAULT
...
>>> m.side_effect = side_effect
>>> m()
3

To remove a side_effect, and return to the default behaviour, set the side_effect to None:

>>> m = MagicMock(return_value=6)
>>> def side_effect(*args, **kwargs):
...     return 3
...
>>> m.side_effect = side_effect
>>> m()
3
>>> m.side_effect = None
>>> m()
6

The side_effect can also be any iterable object. Repeated calls to the mock will return values from the iterable (until the iterable is exhausted and a StopIteration is raised):

>>> m = MagicMock(side_effect=[1, 2, 3])
>>> m()
1
>>> m()
2
>>> m()
3
>>> m()
Traceback (most recent call last):
  ...
StopIteration

If any members of the iterable are exceptions they will be raised instead of returned:

>>> iterable = (33, ValueError, 66)
>>> m = MagicMock(side_effect=iterable)
>>> m()
33
>>> m()
Traceback (most recent call last):
 ...
ValueError
>>> m()
66

Deleting Attributes

Mock objects create attributes on demand. This allows them to pretend to be objects of any type.

You may want a mock object to return False to a hasattr() call, or raise an AttributeError when an attribute is fetched. You can do this by providing an object as a spec for a mock, but that isn’t always convenient.

You “block” attributes by deleting them. Once deleted, accessing an attribute will raise an AttributeError.

>>> mock = MagicMock()
>>> hasattr(mock, 'm')
True
>>> del mock.m
>>> hasattr(mock, 'm')
False
>>> del mock.f
>>> mock.f
Traceback (most recent call last):
    ...
AttributeError: f

Mock names and the name attribute

Since “name” is an argument to the Mock constructor, if you want your mock object to have a “name” attribute you can’t just pass it in at creation time. There are two alternatives. One option is to use configure_mock():

>>> mock = MagicMock()
>>> mock.configure_mock(name='my_name')
>>> mock.name
'my_name'

A simpler option is to simply set the “name” attribute after mock creation:

>>> mock = MagicMock()
>>> mock.name = "foo"

Attaching Mocks as Attributes

When you attach a mock as an attribute of another mock (or as the return value) it becomes a “child” of that mock. Calls to the child are recorded in the method_calls and mock_calls attributes of the parent. This is useful for configuring child mocks and then attaching them to the parent, or for attaching mocks to a parent that records all calls to the children and allows you to make assertions about the order of calls between mocks:

>>> parent = MagicMock()
>>> child1 = MagicMock(return_value=None)
>>> child2 = MagicMock(return_value=None)
>>> parent.child1 = child1
>>> parent.child2 = child2
>>> child1(1)
>>> child2(2)
>>> parent.mock_calls
[call.child1(1), call.child2(2)]

The exception to this is if the mock has a name. This allows you to prevent the “parenting” if for some reason you don’t want it to happen.

>>> mock = MagicMock()
>>> not_a_child = MagicMock(name='not-a-child')
>>> mock.attribute = not_a_child
>>> mock.attribute()
<MagicMock name='not-a-child()' id='...'>
>>> mock.mock_calls
[]

Mocks created for you by patch() are automatically given names. To attach mocks that have names to a parent you use the attach_mock() method:

>>> thing1 = object()
>>> thing2 = object()
>>> parent = MagicMock()
>>> with patch('__main__.thing1', return_value=None) as child1:
...     with patch('__main__.thing2', return_value=None) as child2:
...         parent.attach_mock(child1, 'child1')
...         parent.attach_mock(child2, 'child2')
...         child1('one')
...         child2('two')
...
>>> parent.mock_calls
[call.child1('one'), call.child2('two')]

1

The only exceptions are magic methods and attributes (those that have leading and trailing double underscores). Mock doesn’t create these but instead raises an AttributeError. This is because the interpreter will often implicitly request these methods, and gets very confused to get a new Mock object when it expects a magic method. If you need magic method support see magic methods.

The patchers

The patch decorators are used for patching objects only within the scope of the function they decorate. They automatically handle the unpatching for you, even if exceptions are raised. All of these functions can also be used in with statements or as class decorators.

patch

참고

patch() is straightforward to use. The key is to do the patching in the right namespace. See the section where to patch.

unittest.mock.patch(target, new=DEFAULT, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs)

patch() acts as a function decorator, class decorator or a context manager. Inside the body of the function or with statement, the target is patched with a new object. When the function/with statement exits the patch is undone.

If new is omitted, then the target is replaced with a MagicMock. If patch() is used as a decorator and new is omitted, the created mock is passed in as an extra argument to the decorated function. If patch() is used as a context manager the created mock is returned by the context manager.

target should be a string in the form 'package.module.ClassName'. The target is imported and the specified object replaced with the new object, so the target must be importable from the environment you are calling patch() from. The target is imported when the decorated function is executed, not at decoration time.

The spec and spec_set keyword arguments are passed to the MagicMock if patch is creating one for you.

In addition you can pass spec=True or spec_set=True, which causes patch to pass in the object being mocked as the spec/spec_set object.

new_callable allows you to specify a different class, or callable object, that will be called to create the new object. By default MagicMock is used.

A more powerful form of spec is autospec. If you set autospec=True then the mock will be created with a spec from the object being replaced. All attributes of the mock will also have the spec of the corresponding attribute of the object being replaced. Methods and functions being mocked will have their arguments checked and will raise a TypeError if they are called with the wrong signature. For mocks replacing a class, their return value (the ‘instance’) will have the same spec as the class. See the create_autospec() function and Autospeccing.

Instead of autospec=True you can pass autospec=some_object to use an arbitrary object as the spec instead of the one being replaced.

By default patch() will fail to replace attributes that don’t exist. If you pass in create=True, and the attribute doesn’t exist, patch will create the attribute for you when the patched function is called, and delete it again after the patched function has exited. This is useful for writing tests against attributes that your production code creates at runtime. It is off by default because it can be dangerous. With it switched on you can write passing tests against APIs that don’t actually exist!

참고

버전 3.5에서 변경: If you are patching builtins in a module then you don’t need to pass create=True, it will be added by default.

Patch can be used as a TestCase class decorator. It works by decorating each test method in the class. This reduces the boilerplate code when your test methods share a common patchings set. patch() finds tests by looking for method names that start with patch.TEST_PREFIX. By default this is 'test', which matches the way unittest finds tests. You can specify an alternative prefix by setting patch.TEST_PREFIX.

Patch can be used as a context manager, with the with statement. Here the patching applies to the indented block after the with statement. If you use “as” then the patched object will be bound to the name after the “as”; very useful if patch() is creating a mock object for you.

patch() takes arbitrary keyword arguments. These will be passed to the Mock (or new_callable) on construction.

patch.dict(...), patch.multiple(...) and patch.object(...) are available for alternate use-cases.

patch() as function decorator, creating the mock for you and passing it into the decorated function:

>>> @patch('__main__.SomeClass')
... def function(normal_argument, mock_class):
...     print(mock_class is SomeClass)
...
>>> function(None)
True

Patching a class replaces the class with a MagicMock instance. If the class is instantiated in the code under test then it will be the return_value of the mock that will be used.

If the class is instantiated multiple times you could use side_effect to return a new mock each time. Alternatively you can set the return_value to be anything you want.

To configure return values on methods of instances on the patched class you must do this on the return_value. For example:

>>> class Class:
...     def method(self):
...         pass
...
>>> with patch('__main__.Class') as MockClass:
...     instance = MockClass.return_value
...     instance.method.return_value = 'foo'
...     assert Class() is instance
...     assert Class().method() == 'foo'
...

If you use spec or spec_set and patch() is replacing a class, then the return value of the created mock will have the same spec.

>>> Original = Class
>>> patcher = patch('__main__.Class', spec=True)
>>> MockClass = patcher.start()
>>> instance = MockClass()
>>> assert isinstance(instance, Original)
>>> patcher.stop()

The new_callable argument is useful where you want to use an alternative class to the default MagicMock for the created mock. For example, if you wanted a NonCallableMock to be used:

>>> thing = object()
>>> with patch('__main__.thing', new_callable=NonCallableMock) as mock_thing:
...     assert thing is mock_thing
...     thing()
...
Traceback (most recent call last):
  ...
TypeError: 'NonCallableMock' object is not callable

Another use case might be to replace an object with an io.StringIO instance:

>>> from io import StringIO
>>> def foo():
...     print('Something')
...
>>> @patch('sys.stdout', new_callable=StringIO)
... def test(mock_stdout):
...     foo()
...     assert mock_stdout.getvalue() == 'Something\n'
...
>>> test()

When patch() is creating a mock for you, it is common that the first thing you need to do is to configure the mock. Some of that configuration can be done in the call to patch. Any arbitrary keywords you pass into the call will be used to set attributes on the created mock:

>>> patcher = patch('__main__.thing', first='one', second='two')
>>> mock_thing = patcher.start()
>>> mock_thing.first
'one'
>>> mock_thing.second
'two'

As well as attributes on the created mock attributes, like the return_value and side_effect, of child mocks can also be configured. These aren’t syntactically valid to pass in directly as keyword arguments, but a dictionary with these as keys can still be expanded into a patch() call using **:

>>> config = {'method.return_value': 3, 'other.side_effect': KeyError}
>>> patcher = patch('__main__.thing', **config)
>>> mock_thing = patcher.start()
>>> mock_thing.method()
3
>>> mock_thing.other()
Traceback (most recent call last):
  ...
KeyError

By default, attempting to patch a function in a module (or a method or an attribute in a class) that does not exist will fail with AttributeError:

>>> @patch('sys.non_existing_attribute', 42)
... def test():
...     assert sys.non_existing_attribute == 42
...
>>> test()
Traceback (most recent call last):
  ...
AttributeError: <module 'sys' (built-in)> does not have the attribute 'non_existing'

but adding create=True in the call to patch() will make the previous example work as expected:

>>> @patch('sys.non_existing_attribute', 42, create=True)
... def test(mock_stdout):
...     assert sys.non_existing_attribute == 42
...
>>> test()

patch.object

patch.object(target, attribute, new=DEFAULT, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs)

patch the named member (attribute) on an object (target) with a mock object.

patch.object() can be used as a decorator, class decorator or a context manager. Arguments new, spec, create, spec_set, autospec and new_callable have the same meaning as for patch(). Like patch(), patch.object() takes arbitrary keyword arguments for configuring the mock object it creates.

When used as a class decorator patch.object() honours patch.TEST_PREFIX for choosing which methods to wrap.

You can either call patch.object() with three arguments or two arguments. The three argument form takes the object to be patched, the attribute name and the object to replace the attribute with.

When calling with the two argument form you omit the replacement object, and a mock is created for you and passed in as an extra argument to the decorated function:

>>> @patch.object(SomeClass, 'class_method')
... def test(mock_method):
...     SomeClass.class_method(3)
...     mock_method.assert_called_with(3)
...
>>> test()

spec, create and the other arguments to patch.object() have the same meaning as they do for patch().

patch.dict

patch.dict(in_dict, values=(), clear=False, **kwargs)

Patch a dictionary, or dictionary like object, and restore the dictionary to its original state after the test.

in_dict can be a dictionary or a mapping like container. If it is a mapping then it must at least support getting, setting and deleting items plus iterating over keys.

in_dict can also be a string specifying the name of the dictionary, which will then be fetched by importing it.

values can be a dictionary of values to set in the dictionary. values can also be an iterable of (key, value) pairs.

If clear is true then the dictionary will be cleared before the new values are set.

patch.dict() can also be called with arbitrary keyword arguments to set values in the dictionary.

patch.dict() can be used as a context manager, decorator or class decorator. When used as a class decorator patch.dict() honours patch.TEST_PREFIX for choosing which methods to wrap.

patch.dict() can be used to add members to a dictionary, or simply let a test change a dictionary, and ensure the dictionary is restored when the test ends.

>>> foo = {}
>>> with patch.dict(foo, {'newkey': 'newvalue'}):
...     assert foo == {'newkey': 'newvalue'}
...
>>> assert foo == {}

>>> import os
>>> with patch.dict('os.environ', {'newkey': 'newvalue'}):
...     print(os.environ['newkey'])
...
newvalue
>>> assert 'newkey' not in os.environ

Keywords can be used in the patch.dict() call to set values in the dictionary:

>>> mymodule = MagicMock()
>>> mymodule.function.return_value = 'fish'
>>> with patch.dict('sys.modules', mymodule=mymodule):
...     import mymodule
...     mymodule.function('some', 'args')
...
'fish'

patch.dict() can be used with dictionary like objects that aren’t actually dictionaries. At the very minimum they must support item getting, setting, deleting and either iteration or membership test. This corresponds to the magic methods __getitem__(), __setitem__(), __delitem__() and either __iter__() or __contains__().

>>> class Container:
...     def __init__(self):
...         self.values = {}
...     def __getitem__(self, name):
...         return self.values[name]
...     def __setitem__(self, name, value):
...         self.values[name] = value
...     def __delitem__(self, name):
...         del self.values[name]
...     def __iter__(self):
...         return iter(self.values)
...
>>> thing = Container()
>>> thing['one'] = 1
>>> with patch.dict(thing, one=2, two=3):
...     assert thing['one'] == 2
...     assert thing['two'] == 3
...
>>> assert thing['one'] == 1
>>> assert list(thing) == ['one']

patch.multiple

patch.multiple(target, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs)

Perform multiple patches in a single call. It takes the object to be patched (either as an object or a string to fetch the object by importing) and keyword arguments for the patches:

with patch.multiple(settings, FIRST_PATCH='one', SECOND_PATCH='two'):
    ...

Use DEFAULT as the value if you want patch.multiple() to create mocks for you. In this case the created mocks are passed into a decorated function by keyword, and a dictionary is returned when patch.multiple() is used as a context manager.

patch.multiple() can be used as a decorator, class decorator or a context manager. The arguments spec, spec_set, create, autospec and new_callable have the same meaning as for patch(). These arguments will be applied to all patches done by patch.multiple().

When used as a class decorator patch.multiple() honours patch.TEST_PREFIX for choosing which methods to wrap.

If you want patch.multiple() to create mocks for you, then you can use DEFAULT as the value. If you use patch.multiple() as a decorator then the created mocks are passed into the decorated function by keyword.

>>> thing = object()
>>> other = object()

>>> @patch.multiple('__main__', thing=DEFAULT, other=DEFAULT)
... def test_function(thing, other):
...     assert isinstance(thing, MagicMock)
...     assert isinstance(other, MagicMock)
...
>>> test_function()

patch.multiple() can be nested with other patch decorators, but put arguments passed by keyword after any of the standard arguments created by patch():

>>> @patch('sys.exit')
... @patch.multiple('__main__', thing=DEFAULT, other=DEFAULT)
... def test_function(mock_exit, other, thing):
...     assert 'other' in repr(other)
...     assert 'thing' in repr(thing)
...     assert 'exit' in repr(mock_exit)
...
>>> test_function()

If patch.multiple() is used as a context manager, the value returned by the context manager is a dictionary where created mocks are keyed by name:

>>> with patch.multiple('__main__', thing=DEFAULT, other=DEFAULT) as values:
...     assert 'other' in repr(values['other'])
...     assert 'thing' in repr(values['thing'])
...     assert values['thing'] is thing
...     assert values['other'] is other
...

patch methods: start and stop

All the patchers have start() and stop() methods. These make it simpler to do patching in setUp methods or where you want to do multiple patches without nesting decorators or with statements.

To use them call patch(), patch.object() or patch.dict() as normal and keep a reference to the returned patcher object. You can then call start() to put the patch in place and stop() to undo it.

If you are using patch() to create a mock for you then it will be returned by the call to patcher.start.

>>> patcher = patch('package.module.ClassName')
>>> from package import module
>>> original = module.ClassName
>>> new_mock = patcher.start()
>>> assert module.ClassName is not original
>>> assert module.ClassName is new_mock
>>> patcher.stop()
>>> assert module.ClassName is original
>>> assert module.ClassName is not new_mock

A typical use case for this might be for doing multiple patches in the setUp method of a TestCase:

>>> class MyTest(TestCase):
...     def setUp(self):
...         self.patcher1 = patch('package.module.Class1')
...         self.patcher2 = patch('package.module.Class2')
...         self.MockClass1 = self.patcher1.start()
...         self.MockClass2 = self.patcher2.start()
...
...     def tearDown(self):
...         self.patcher1.stop()
...         self.patcher2.stop()
...
...     def test_something(self):
...         assert package.module.Class1 is self.MockClass1
...         assert package.module.Class2 is self.MockClass2
...
>>> MyTest('test_something').run()

조심

If you use this technique you must ensure that the patching is “undone” by calling stop. This can be fiddlier than you might think, because if an exception is raised in the setUp then tearDown is not called. unittest.TestCase.addCleanup() makes this easier:

>>> class MyTest(TestCase):
...     def setUp(self):
...         patcher = patch('package.module.Class')
...         self.MockClass = patcher.start()
...         self.addCleanup(patcher.stop)
...
...     def test_something(self):
...         assert package.module.Class is self.MockClass
...

As an added bonus you no longer need to keep a reference to the patcher object.

It is also possible to stop all patches which have been started by using patch.stopall().

patch.stopall()

Stop all active patches. Only stops patches started with start.

patch builtins

You can patch any builtins within a module. The following example patches builtin ord():

>>> @patch('__main__.ord')
... def test(mock_ord):
...     mock_ord.return_value = 101
...     print(ord('c'))
...
>>> test()
101

TEST_PREFIX

All of the patchers can be used as class decorators. When used in this way they wrap every test method on the class. The patchers recognise methods that start with 'test' as being test methods. This is the same way that the unittest.TestLoader finds test methods by default.

It is possible that you want to use a different prefix for your tests. You can inform the patchers of the different prefix by setting patch.TEST_PREFIX:

>>> patch.TEST_PREFIX = 'foo'
>>> value = 3
>>>
>>> @patch('__main__.value', 'not three')
... class Thing:
...     def foo_one(self):
...         print(value)
...     def foo_two(self):
...         print(value)
...
>>>
>>> Thing().foo_one()
not three
>>> Thing().foo_two()
not three
>>> value
3

Nesting Patch Decorators

If you want to perform multiple patches then you can simply stack up the decorators.

You can stack up multiple patch decorators using this pattern:

>>> @patch.object(SomeClass, 'class_method')
... @patch.object(SomeClass, 'static_method')
... def test(mock1, mock2):
...     assert SomeClass.static_method is mock1
...     assert SomeClass.class_method is mock2
...     SomeClass.static_method('foo')
...     SomeClass.class_method('bar')
...     return mock1, mock2
...
>>> mock1, mock2 = test()
>>> mock1.assert_called_once_with('foo')
>>> mock2.assert_called_once_with('bar')

Note that the decorators are applied from the bottom upwards. This is the standard way that Python applies decorators. The order of the created mocks passed into your test function matches this order.

Where to patch

patch() works by (temporarily) changing the object that a name points to with another one. There can be many names pointing to any individual object, so for patching to work you must ensure that you patch the name used by the system under test.

The basic principle is that you patch where an object is looked up, which is not necessarily the same place as where it is defined. A couple of examples will help to clarify this.

Imagine we have a project that we want to test with the following structure:

a.py
    -> Defines SomeClass

b.py
    -> from a import SomeClass
    -> some_function instantiates SomeClass

Now we want to test some_function but we want to mock out SomeClass using patch(). The problem is that when we import module b, which we will have to do then it imports SomeClass from module a. If we use patch() to mock out a.SomeClass then it will have no effect on our test; module b already has a reference to the real SomeClass and it looks like our patching had no effect.

The key is to patch out SomeClass where it is used (or where it is looked up). In this case some_function will actually look up SomeClass in module b, where we have imported it. The patching should look like:

@patch('b.SomeClass')

However, consider the alternative scenario where instead of from a import SomeClass module b does import a and some_function uses a.SomeClass. Both of these import forms are common. In this case the class we want to patch is being looked up in the module and so we have to patch a.SomeClass instead:

@patch('a.SomeClass')

Patching Descriptors and Proxy Objects

Both patch and patch.object correctly patch and restore descriptors: class methods, static methods and properties. You should patch these on the class rather than an instance. They also work with some objects that proxy attribute access, like the django settings object [http://www.voidspace.org.uk/python/weblog/arch_d7_2010_12_04.shtml#e1198].

MagicMock and magic method support

Mocking Magic Methods

Mock supports mocking the Python protocol methods, also known as “magic methods”. This allows mock objects to replace containers or other objects that implement Python protocols.

Because magic methods are looked up differently from normal methods 2, this support has been specially implemented. This means that only specific magic methods are supported. The supported list includes almost all of them. If there are any missing that you need please let us know.

You mock magic methods by setting the method you are interested in to a function or a mock instance. If you are using a function then it must take self as the first argument 3.

>>> def __str__(self):
...     return 'fooble'
...
>>> mock = Mock()
>>> mock.__str__ = __str__
>>> str(mock)
'fooble'

>>> mock = Mock()
>>> mock.__str__ = Mock()
>>> mock.__str__.return_value = 'fooble'
>>> str(mock)
'fooble'

>>> mock = Mock()
>>> mock.__iter__ = Mock(return_value=iter([]))
>>> list(mock)
[]

One use case for this is for mocking objects used as context managers in a with statement:

>>> mock = Mock()
>>> mock.__enter__ = Mock(return_value='foo')
>>> mock.__exit__ = Mock(return_value=False)
>>> with mock as m:
...     assert m == 'foo'
...
>>> mock.__enter__.assert_called_with()
>>> mock.__exit__.assert_called_with(None, None, None)

Calls to magic methods do not appear in method_calls, but they are recorded in mock_calls.

참고

If you use the spec keyword argument to create a mock then attempting to set a magic method that isn’t in the spec will raise an AttributeError.

The full list of supported magic methods is:

__hash__, __sizeof__, __repr__ and __str__

__dir__, __format__ and __subclasses__

__floor__, __trunc__ and __ceil__

Comparisons: __lt__, __gt__, __le__, __ge__, __eq__ and __ne__

Container methods: __getitem__, __setitem__, __delitem__, __contains__, __len__, __iter__, __reversed__ and __missing__

Context manager: __enter__ and __exit__

Unary numeric methods: __neg__, __pos__ and __invert__

The numeric methods (including right hand and in-place variants): __add__, __sub__, __mul__, __matmul__, __div__, __truediv__, __floordiv__, __mod__, __divmod__, __lshift__, __rshift__, __and__, __xor__, __or__, and __pow__

Numeric conversion methods: __complex__, __int__, __float__ and __index__

Descriptor methods: __get__, __set__ and __delete__

Pickling: __reduce__, __reduce_ex__, __getinitargs__, __getnewargs__, __getstate__ and __setstate__

The following methods exist but are not supported as they are either in use by mock, can’t be set dynamically, or can cause problems:

__getattr__, __setattr__, __init__ and __new__

__prepare__, __instancecheck__, __subclasscheck__, __del__

Magic Mock

There are two MagicMock variants: MagicMock and NonCallableMagicMock.

class unittest.mock.MagicMock(*args, **kw)

MagicMock is a subclass of Mock with default implementations of most of the magic methods. You can use MagicMock without having to configure the magic methods yourself.

The constructor parameters have the same meaning as for Mock.

If you use the spec or spec_set arguments then only magic methods that exist in the spec will be created.

class unittest.mock.NonCallableMagicMock(*args, **kw)

A non-callable version of MagicMock.

The constructor parameters have the same meaning as for MagicMock, with the exception of return_value and side_effect which have no meaning on a non-callable mock.

The magic methods are setup with MagicMock objects, so you can configure them and use them in the usual way:

>>> mock = MagicMock()
>>> mock[3] = 'fish'
>>> mock.__setitem__.assert_called_with(3, 'fish')
>>> mock.__getitem__.return_value = 'result'
>>> mock[2]
'result'

By default many of the protocol methods are required to return objects of a specific type. These methods are preconfigured with a default return value, so that they can be used without you having to do anything if you aren’t interested in the return value. You can still set the return value manually if you want to change the default.

Methods and their defaults:

__lt__: NotImplemented

__gt__: NotImplemented

__le__: NotImplemented

__ge__: NotImplemented

__int__: 1

__contains__: False

__len__: 0

__iter__: iter([])

__exit__: False

__complex__: 1j

__float__: 1.0

__bool__: True

__index__: 1

__hash__: default hash for the mock

__str__: default str for the mock

__sizeof__: default sizeof for the mock

For example:

>>> mock = MagicMock()
>>> int(mock)
1
>>> len(mock)
0
>>> list(mock)
[]
>>> object() in mock
False

The two equality methods, __eq__() and __ne__(), are special. They do the default equality comparison on identity, using the side_effect attribute, unless you change their return value to return something else:

>>> MagicMock() == 3
False
>>> MagicMock() != 3
True
>>> mock = MagicMock()
>>> mock.__eq__.return_value = True
>>> mock == 3
True

The return value of MagicMock.__iter__() can be any iterable object and isn’t required to be an iterator:

>>> mock = MagicMock()
>>> mock.__iter__.return_value = ['a', 'b', 'c']
>>> list(mock)
['a', 'b', 'c']
>>> list(mock)
['a', 'b', 'c']

If the return value is an iterator, then iterating over it once will consume it and subsequent iterations will result in an empty list:

>>> mock.__iter__.return_value = iter(['a', 'b', 'c'])
>>> list(mock)
['a', 'b', 'c']
>>> list(mock)
[]

MagicMock has all of the supported magic methods configured except for some of the obscure and obsolete ones. You can still set these up if you want.

Magic methods that are supported but not setup by default in MagicMock are:

__subclasses__

__dir__

__format__

__get__, __set__ and __delete__

__reversed__ and __missing__

__reduce__, __reduce_ex__, __getinitargs__, __getnewargs__, __getstate__ and __setstate__

__getformat__ and __setformat__

2

Magic methods should be looked up on the class rather than the instance. Different versions of Python are inconsistent about applying this rule. The supported protocol methods should work with all supported versions of Python.

3

The function is basically hooked up to the class, but each Mock instance is kept isolated from the others.

Helpers

sentinel

unittest.mock.sentinel

The sentinel object provides a convenient way of providing unique objects for your tests.

Attributes are created on demand when you access them by name. Accessing the same attribute will always return the same object. The objects returned have a sensible repr so that test failure messages are readable.

버전 3.7에서 변경: The sentinel attributes now preserve their identity when they are copied or pickled.

Sometimes when testing you need to test that a specific object is passed as an argument to another method, or returned. It can be common to create named sentinel objects to test this. sentinel provides a convenient way of creating and testing the identity of objects like this.

In this example we monkey patch method to return sentinel.some_object:

>>> real = ProductionClass()
>>> real.method = Mock(name="method")
>>> real.method.return_value = sentinel.some_object
>>> result = real.method()
>>> assert result is sentinel.some_object
>>> sentinel.some_object
sentinel.some_object

DEFAULT

unittest.mock.DEFAULT

The DEFAULT object is a pre-created sentinel (actually sentinel.DEFAULT). It can be used by side_effect functions to indicate that the normal return value should be used.

call

unittest.mock.call(*args, **kwargs)

call() is a helper object for making simpler assertions, for comparing with call_args, call_args_list, mock_calls and method_calls. call() can also be used with assert_has_calls().

>>> m = MagicMock(return_value=None)
>>> m(1, 2, a='foo', b='bar')
>>> m()
>>> m.call_args_list == [call(1, 2, a='foo', b='bar'), call()]
True

call.call_list()

For a call object that represents multiple calls, call_list() returns a list of all the intermediate calls as well as the final call.

call_list is particularly useful for making assertions on “chained calls”. A chained call is multiple calls on a single line of code. This results in multiple entries in mock_calls on a mock. Manually constructing the sequence of calls can be tedious.

call_list() can construct the sequence of calls from the same chained call:

>>> m = MagicMock()
>>> m(1).method(arg='foo').other('bar')(2.0)
<MagicMock name='mock().method().other()()' id='...'>
>>> kall = call(1).method(arg='foo').other('bar')(2.0)
>>> kall.call_list()
[call(1),
 call().method(arg='foo'),
 call().method().other('bar'),
 call().method().other()(2.0)]
>>> m.mock_calls == kall.call_list()
True

A call object is either a tuple of (positional args, keyword args) or (name, positional args, keyword args) depending on how it was constructed. When you construct them yourself this isn’t particularly interesting, but the call objects that are in the Mock.call_args, Mock.call_args_list and Mock.mock_calls attributes can be introspected to get at the individual arguments they contain.

The call objects in Mock.call_args and Mock.call_args_list are two-tuples of (positional args, keyword args) whereas the call objects in Mock.mock_calls, along with ones you construct yourself, are three-tuples of (name, positional args, keyword args).

You can use their “tupleness” to pull out the individual arguments for more complex introspection and assertions. The positional arguments are a tuple (an empty tuple if there are no positional arguments) and the keyword arguments are a dictionary:

>>> m = MagicMock(return_value=None)
>>> m(1, 2, 3, arg='one', arg2='two')
>>> kall = m.call_args
>>> args, kwargs = kall
>>> args
(1, 2, 3)
>>> kwargs
{'arg2': 'two', 'arg': 'one'}
>>> args is kall[0]
True
>>> kwargs is kall[1]
True

>>> m = MagicMock()
>>> m.foo(4, 5, 6, arg='two', arg2='three')
<MagicMock name='mock.foo()' id='...'>
>>> kall = m.mock_calls[0]
>>> name, args, kwargs = kall
>>> name
'foo'
>>> args
(4, 5, 6)
>>> kwargs
{'arg2': 'three', 'arg': 'two'}
>>> name is m.mock_calls[0][0]
True

create_autospec

unittest.mock.create_autospec(spec, spec_set=False, instance=False, **kwargs)

Create a mock object using another object as a spec. Attributes on the mock will use the corresponding attribute on the spec object as their spec.

Functions or methods being mocked will have their arguments checked to ensure that they are called with the correct signature.

If spec_set is True then attempting to set attributes that don’t exist on the spec object will raise an AttributeError.

If a class is used as a spec then the return value of the mock (the instance of the class) will have the same spec. You can use a class as the spec for an instance object by passing instance=True. The returned mock will only be callable if instances of the mock are callable.

create_autospec() also takes arbitrary keyword arguments that are passed to the constructor of the created mock.

See Autospeccing for examples of how to use auto-speccing with create_autospec() and the autospec argument to patch().

ANY

unittest.mock.ANY

Sometimes you may need to make assertions about some of the arguments in a call to mock, but either not care about some of the arguments or want to pull them individually out of call_args and make more complex assertions on them.

To ignore certain arguments you can pass in objects that compare equal to everything. Calls to assert_called_with() and assert_called_once_with() will then succeed no matter what was passed in.

>>> mock = Mock(return_value=None)
>>> mock('foo', bar=object())
>>> mock.assert_called_once_with('foo', bar=ANY)

ANY can also be used in comparisons with call lists like mock_calls:

>>> m = MagicMock(return_value=None)
>>> m(1)
>>> m(1, 2)
>>> m(object())
>>> m.mock_calls == [call(1), call(1, 2), ANY]
True

FILTER_DIR

unittest.mock.FILTER_DIR

FILTER_DIR is a module level variable that controls the way mock objects respond to dir() (only for Python 2.6 or more recent). The default is True, which uses the filtering described below, to only show useful members. If you dislike this filtering, or need to switch it off for diagnostic purposes, then set mock.FILTER_DIR = False.

With filtering on, dir(some_mock) shows only useful attributes and will include any dynamically created attributes that wouldn’t normally be shown. If the mock was created with a spec (or autospec of course) then all the attributes from the original are shown, even if they haven’t been accessed yet:

>>> dir(Mock())
['assert_any_call',
 'assert_called_once_with',
 'assert_called_with',
 'assert_has_calls',
 'attach_mock',
 ...
>>> from urllib import request
>>> dir(Mock(spec=request))
['AbstractBasicAuthHandler',
 'AbstractDigestAuthHandler',
 'AbstractHTTPHandler',
 'BaseHandler',
 ...

Many of the not-very-useful (private to Mock rather than the thing being mocked) underscore and double underscore prefixed attributes have been filtered from the result of calling dir() on a Mock. If you dislike this behaviour you can switch it off by setting the module level switch FILTER_DIR:

>>> from unittest import mock
>>> mock.FILTER_DIR = False
>>> dir(mock.Mock())
['_NonCallableMock__get_return_value',
 '_NonCallableMock__get_side_effect',
 '_NonCallableMock__return_value_doc',
 '_NonCallableMock__set_return_value',
 '_NonCallableMock__set_side_effect',
 '__call__',
 '__class__',
 ...

Alternatively you can just use vars(my_mock) (instance members) and dir(type(my_mock)) (type members) to bypass the filtering irrespective of mock.FILTER_DIR.

mock_open

unittest.mock.mock_open(mock=None, read_data=None)

A helper function to create a mock to replace the use of open(). It works for open() called directly or used as a context manager.

The mock argument is the mock object to configure. If None (the default) then a MagicMock will be created for you, with the API limited to methods or attributes available on standard file handles.

read_data is a string for the read(), readline(), and readlines() methods of the file handle to return. Calls to those methods will take data from read_data until it is depleted. The mock of these methods is pretty simplistic: every time the mock is called, the read_data is rewound to the start. If you need more control over the data that you are feeding to the tested code you will need to customize this mock for yourself. When that is insufficient, one of the in-memory filesystem packages on PyPI [https://pypi.org] can offer a realistic filesystem for testing.

버전 3.4에서 변경: Added readline() and readlines() support. The mock of read() changed to consume read_data rather than returning it on each call.

버전 3.5에서 변경: read_data is now reset on each call to the mock.

버전 3.7.1에서 변경: Added __iter__() to implementation so that iteration (such as in for loops) correctly consumes read_data.

Using open() as a context manager is a great way to ensure your file handles are closed properly and is becoming common:

with open('/some/path', 'w') as f:
    f.write('something')

The issue is that even if you mock out the call to open() it is the returned object that is used as a context manager (and has __enter__() and __exit__() called).

Mocking context managers with a MagicMock is common enough and fiddly enough that a helper function is useful.

>>> m = mock_open()
>>> with patch('__main__.open', m):
...     with open('foo', 'w') as h:
...         h.write('some stuff')
...
>>> m.mock_calls
[call('foo', 'w'),
 call().__enter__(),
 call().write('some stuff'),
 call().__exit__(None, None, None)]
>>> m.assert_called_once_with('foo', 'w')
>>> handle = m()
>>> handle.write.assert_called_once_with('some stuff')

And for reading files:

>>> with patch('__main__.open', mock_open(read_data='bibble')) as m:
...     with open('foo') as h:
...         result = h.read()
...
>>> m.assert_called_once_with('foo')
>>> assert result == 'bibble'

Autospeccing

Autospeccing is based on the existing spec feature of mock. It limits the api of mocks to the api of an original object (the spec), but it is recursive (implemented lazily) so that attributes of mocks only have the same api as the attributes of the spec. In addition mocked functions / methods have the same call signature as the original so they raise a TypeError if they are called incorrectly.

Before I explain how auto-speccing works, here’s why it is needed.

Mock is a very powerful and flexible object, but it suffers from two flaws when used to mock out objects from a system under test. One of these flaws is specific to the Mock api and the other is a more general problem with using mock objects.

First the problem specific to Mock. Mock has two assert methods that are extremely handy: assert_called_with() and assert_called_once_with().

>>> mock = Mock(name='Thing', return_value=None)
>>> mock(1, 2, 3)
>>> mock.assert_called_once_with(1, 2, 3)
>>> mock(1, 2, 3)
>>> mock.assert_called_once_with(1, 2, 3)
Traceback (most recent call last):
 ...
AssertionError: Expected 'mock' to be called once. Called 2 times.

Because mocks auto-create attributes on demand, and allow you to call them with arbitrary arguments, if you misspell one of these assert methods then your assertion is gone:

>>> mock = Mock(name='Thing', return_value=None)
>>> mock(1, 2, 3)
>>> mock.assret_called_once_with(4, 5, 6)

Your tests can pass silently and incorrectly because of the typo.

The second issue is more general to mocking. If you refactor some of your code, rename members and so on, any tests for code that is still using the old api but uses mocks instead of the real objects will still pass. This means your tests can all pass even though your code is broken.

Note that this is another reason why you need integration tests as well as unit tests. Testing everything in isolation is all fine and dandy, but if you don’t test how your units are “wired together” there is still lots of room for bugs that tests might have caught.

mock already provides a feature to help with this, called speccing. If you use a class or instance as the spec for a mock then you can only access attributes on the mock that exist on the real class:

>>> from urllib import request
>>> mock = Mock(spec=request.Request)
>>> mock.assret_called_with
Traceback (most recent call last):
 ...
AttributeError: Mock object has no attribute 'assret_called_with'

The spec only applies to the mock itself, so we still have the same issue with any methods on the mock:

>>> mock.has_data()
<mock.Mock object at 0x...>
>>> mock.has_data.assret_called_with()

Auto-speccing solves this problem. You can either pass autospec=True to patch() / patch.object() or use the create_autospec() function to create a mock with a spec. If you use the autospec=True argument to patch() then the object that is being replaced will be used as the spec object. Because the speccing is done “lazily” (the spec is created as attributes on the mock are accessed) you can use it with very complex or deeply nested objects (like modules that import modules that import modules) without a big performance hit.

Here’s an example of it in use:

>>> from urllib import request
>>> patcher = patch('__main__.request', autospec=True)
>>> mock_request = patcher.start()
>>> request is mock_request
True
>>> mock_request.Request
<MagicMock name='request.Request' spec='Request' id='...'>

You can see that request.Request has a spec. request.Request takes two arguments in the constructor (one of which is self). Here’s what happens if we try to call it incorrectly:

>>> req = request.Request()
Traceback (most recent call last):
 ...
TypeError: <lambda>() takes at least 2 arguments (1 given)

The spec also applies to instantiated classes (i.e. the return value of specced mocks):

>>> req = request.Request('foo')
>>> req
<NonCallableMagicMock name='request.Request()' spec='Request' id='...'>

Request objects are not callable, so the return value of instantiating our mocked out request.Request is a non-callable mock. With the spec in place any typos in our asserts will raise the correct error:

>>> req.add_header('spam', 'eggs')
<MagicMock name='request.Request().add_header()' id='...'>
>>> req.add_header.assret_called_with
Traceback (most recent call last):
 ...
AttributeError: Mock object has no attribute 'assret_called_with'
>>> req.add_header.assert_called_with('spam', 'eggs')

In many cases you will just be able to add autospec=True to your existing patch() calls and then be protected against bugs due to typos and api changes.

As well as using autospec through patch() there is a create_autospec() for creating autospecced mocks directly:

>>> from urllib import request
>>> mock_request = create_autospec(request)
>>> mock_request.Request('foo', 'bar')
<NonCallableMagicMock name='mock.Request()' spec='Request' id='...'>

This isn’t without caveats and limitations however, which is why it is not the default behaviour. In order to know what attributes are available on the spec object, autospec has to introspect (access attributes) the spec. As you traverse attributes on the mock a corresponding traversal of the original object is happening under the hood. If any of your specced objects have properties or descriptors that can trigger code execution then you may not be able to use autospec. On the other hand it is much better to design your objects so that introspection is safe 4.

A more serious problem is that it is common for instance attributes to be created in the __init__() method and not to exist on the class at all. autospec can’t know about any dynamically created attributes and restricts the api to visible attributes.

>>> class Something:
...   def __init__(self):
...     self.a = 33
...
>>> with patch('__main__.Something', autospec=True):
...   thing = Something()
...   thing.a
...
Traceback (most recent call last):
  ...
AttributeError: Mock object has no attribute 'a'

There are a few different ways of resolving this problem. The easiest, but not necessarily the least annoying, way is to simply set the required attributes on the mock after creation. Just because autospec doesn’t allow you to fetch attributes that don’t exist on the spec it doesn’t prevent you setting them:

>>> with patch('__main__.Something', autospec=True):
...   thing = Something()
...   thing.a = 33
...

There is a more aggressive version of both spec and autospec that does prevent you setting non-existent attributes. This is useful if you want to ensure your code only sets valid attributes too, but obviously it prevents this particular scenario:

>>> with patch('__main__.Something', autospec=True, spec_set=True):
...   thing = Something()
...   thing.a = 33
...
Traceback (most recent call last):
 ...
AttributeError: Mock object has no attribute 'a'

Probably the best way of solving the problem is to add class attributes as default values for instance members initialised in __init__(). Note that if you are only setting default attributes in __init__() then providing them via class attributes (shared between instances of course) is faster too. e.g.

class Something:
    a = 33

This brings up another issue. It is relatively common to provide a default value of None for members that will later be an object of a different type. None would be useless as a spec because it wouldn’t let you access any attributes or methods on it. As None is never going to be useful as a spec, and probably indicates a member that will normally of some other type, autospec doesn’t use a spec for members that are set to None. These will just be ordinary mocks (well - MagicMocks):

>>> class Something:
...     member = None
...
>>> mock = create_autospec(Something)
>>> mock.member.foo.bar.baz()
<MagicMock name='mock.member.foo.bar.baz()' id='...'>

If modifying your production classes to add defaults isn’t to your liking then there are more options. One of these is simply to use an instance as the spec rather than the class. The other is to create a subclass of the production class and add the defaults to the subclass without affecting the production class. Both of these require you to use an alternative object as the spec. Thankfully patch() supports this - you can simply pass the alternative object as the autospec argument:

>>> class Something:
...   def __init__(self):
...     self.a = 33
...
>>> class SomethingForTest(Something):
...   a = 33
...
>>> p = patch('__main__.Something', autospec=SomethingForTest)
>>> mock = p.start()
>>> mock.a
<NonCallableMagicMock name='Something.a' spec='int' id='...'>

4

This only applies to classes or already instantiated objects. Calling a mocked class to create a mock instance does not create a real instance. It is only attribute lookups - along with calls to dir() - that are done.

Sealing mocks

unittest.mock.seal(mock)

Seal will disable the automatic creation of mocks when accessing an attribute of the mock being sealed or any of its attributes that are already mocks recursively.

If a mock instance with a name or a spec is assigned to an attribute it won’t be considered in the sealing chain. This allows one to prevent seal from fixing part of the mock object.

>>> mock = Mock()
>>> mock.submock.attribute1 = 2
>>> mock.not_submock = mock.Mock(name="sample_name")
>>> seal(mock)
>>> mock.new_attribute  # This will raise AttributeError.
>>> mock.submock.attribute2  # This will raise AttributeError.
>>> mock.not_submock.attribute2  # This won't raise.

버전 3.7에 추가.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

개발 도구 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

개발 도구 »

|

unittest.mock — getting started

버전 3.3에 추가.

Using Mock

Mock Patching Methods

Common uses for Mock objects include:

Patching methods

Recording method calls on objects

You might want to replace a method on an object to check that it is called with the correct arguments by another part of the system:

>>> real = SomeClass()
>>> real.method = MagicMock(name='method')
>>> real.method(3, 4, 5, key='value')
<MagicMock name='method()' id='...'>

Once our mock has been used (real.method in this example) it has methods and attributes that allow you to make assertions about how it has been used.

참고

In most of these examples the Mock and MagicMock classes are interchangeable. As the MagicMock is the more capable class it makes a sensible one to use by default.

Once the mock has been called its called attribute is set to True. More importantly we can use the assert_called_with() or assert_called_once_with() method to check that it was called with the correct arguments.

This example tests that calling ProductionClass().method results in a call to the something method:

>>> class ProductionClass:
...     def method(self):
...         self.something(1, 2, 3)
...     def something(self, a, b, c):
...         pass
...
>>> real = ProductionClass()
>>> real.something = MagicMock()
>>> real.method()
>>> real.something.assert_called_once_with(1, 2, 3)

Mock for Method Calls on an Object

In the last example we patched a method directly on an object to check that it was called correctly. Another common use case is to pass an object into a method (or some part of the system under test) and then check that it is used in the correct way.

The simple ProductionClass below has a closer method. If it is called with an object then it calls close on it.

>>> class ProductionClass:
...     def closer(self, something):
...         something.close()
...

So to test it we need to pass in an object with a close method and check that it was called correctly.

>>> real = ProductionClass()
>>> mock = Mock()
>>> real.closer(mock)
>>> mock.close.assert_called_with()

We don’t have to do any work to provide the ‘close’ method on our mock. Accessing close creates it. So, if ‘close’ hasn’t already been called then accessing it in the test will create it, but assert_called_with() will raise a failure exception.

Mocking Classes

A common use case is to mock out classes instantiated by your code under test. When you patch a class, then that class is replaced with a mock. Instances are created by calling the class. This means you access the “mock instance” by looking at the return value of the mocked class.

In the example below we have a function some_function that instantiates Foo and calls a method on it. The call to patch() replaces the class Foo with a mock. The Foo instance is the result of calling the mock, so it is configured by modifying the mock return_value.

>>> def some_function():
...     instance = module.Foo()
...     return instance.method()
...
>>> with patch('module.Foo') as mock:
...     instance = mock.return_value
...     instance.method.return_value = 'the result'
...     result = some_function()
...     assert result == 'the result'

Naming your mocks

It can be useful to give your mocks a name. The name is shown in the repr of the mock and can be helpful when the mock appears in test failure messages. The name is also propagated to attributes or methods of the mock:

>>> mock = MagicMock(name='foo')
>>> mock
<MagicMock name='foo' id='...'>
>>> mock.method
<MagicMock name='foo.method' id='...'>

Tracking all Calls

Often you want to track more than a single call to a method. The mock_calls attribute records all calls to child attributes of the mock - and also to their children.

>>> mock = MagicMock()
>>> mock.method()
<MagicMock name='mock.method()' id='...'>
>>> mock.attribute.method(10, x=53)
<MagicMock name='mock.attribute.method()' id='...'>
>>> mock.mock_calls
[call.method(), call.attribute.method(10, x=53)]

If you make an assertion about mock_calls and any unexpected methods have been called, then the assertion will fail. This is useful because as well as asserting that the calls you expected have been made, you are also checking that they were made in the right order and with no additional calls:

You use the call object to construct lists for comparing with mock_calls:

>>> expected = [call.method(), call.attribute.method(10, x=53)]
>>> mock.mock_calls == expected
True

However, parameters to calls that return mocks are not recorded, which means it is not possible to track nested calls where the parameters used to create ancestors are important:

>>> m = Mock()
>>> m.factory(important=True).deliver()
<Mock name='mock.factory().deliver()' id='...'>
>>> m.mock_calls[-1] == call.factory(important=False).deliver()
True

Setting Return Values and Attributes

Setting the return values on a mock object is trivially easy:

>>> mock = Mock()
>>> mock.return_value = 3
>>> mock()
3

Of course you can do the same for methods on the mock:

>>> mock = Mock()
>>> mock.method.return_value = 3
>>> mock.method()
3

The return value can also be set in the constructor:

>>> mock = Mock(return_value=3)
>>> mock()
3

If you need an attribute setting on your mock, just do it:

>>> mock = Mock()
>>> mock.x = 3
>>> mock.x
3

Sometimes you want to mock up a more complex situation, like for example mock.connection.cursor().execute("SELECT 1"). If we wanted this call to return a list, then we have to configure the result of the nested call.

We can use call to construct the set of calls in a “chained call” like this for easy assertion afterwards:

>>> mock = Mock()
>>> cursor = mock.connection.cursor.return_value
>>> cursor.execute.return_value = ['foo']
>>> mock.connection.cursor().execute("SELECT 1")
['foo']
>>> expected = call.connection.cursor().execute("SELECT 1").call_list()
>>> mock.mock_calls
[call.connection.cursor(), call.connection.cursor().execute('SELECT 1')]
>>> mock.mock_calls == expected
True

It is the call to .call_list() that turns our call object into a list of calls representing the chained calls.

Raising exceptions with mocks

A useful attribute is side_effect. If you set this to an exception class or instance then the exception will be raised when the mock is called.

>>> mock = Mock(side_effect=Exception('Boom!'))
>>> mock()
Traceback (most recent call last):
  ...
Exception: Boom!

Side effect functions and iterables

side_effect can also be set to a function or an iterable. The use case for side_effect as an iterable is where your mock is going to be called several times, and you want each call to return a different value. When you set side_effect to an iterable every call to the mock returns the next value from the iterable:

>>> mock = MagicMock(side_effect=[4, 5, 6])
>>> mock()
4
>>> mock()
5
>>> mock()
6

For more advanced use cases, like dynamically varying the return values depending on what the mock is called with, side_effect can be a function. The function will be called with the same arguments as the mock. Whatever the function returns is what the call returns:

>>> vals = {(1, 2): 1, (2, 3): 2}
>>> def side_effect(*args):
...     return vals[args]
...
>>> mock = MagicMock(side_effect=side_effect)
>>> mock(1, 2)
1
>>> mock(2, 3)
2

Creating a Mock from an Existing Object

One problem with over use of mocking is that it couples your tests to the implementation of your mocks rather than your real code. Suppose you have a class that implements some_method. In a test for another class, you provide a mock of this object that also provides some_method. If later you refactor the first class, so that it no longer has some_method - then your tests will continue to pass even though your code is now broken!

Mock allows you to provide an object as a specification for the mock, using the spec keyword argument. Accessing methods / attributes on the mock that don’t exist on your specification object will immediately raise an attribute error. If you change the implementation of your specification, then tests that use that class will start failing immediately without you having to instantiate the class in those tests.

>>> mock = Mock(spec=SomeClass)
>>> mock.old_method()
Traceback (most recent call last):
   ...
AttributeError: object has no attribute 'old_method'

Using a specification also enables a smarter matching of calls made to the mock, regardless of whether some parameters were passed as positional or named arguments:

>>> def f(a, b, c): pass
...
>>> mock = Mock(spec=f)
>>> mock(1, 2, 3)
<Mock name='mock()' id='140161580456576'>
>>> mock.assert_called_with(a=1, b=2, c=3)

If you want this smarter matching to also work with method calls on the mock, you can use auto-speccing.

If you want a stronger form of specification that prevents the setting of arbitrary attributes as well as the getting of them then you can use spec_set instead of spec.

Patch Decorators

참고

With patch() it matters that you patch objects in the namespace where they are looked up. This is normally straightforward, but for a quick guide read where to patch.

A common need in tests is to patch a class attribute or a module attribute, for example patching a builtin or patching a class in a module to test that it is instantiated. Modules and classes are effectively global, so patching on them has to be undone after the test or the patch will persist into other tests and cause hard to diagnose problems.

mock provides three convenient decorators for this: patch(), patch.object() and patch.dict(). patch takes a single string, of the form package.module.Class.attribute to specify the attribute you are patching. It also optionally takes a value that you want the attribute (or class or whatever) to be replaced with. ‘patch.object’ takes an object and the name of the attribute you would like patched, plus optionally the value to patch it with.

patch.object:

>>> original = SomeClass.attribute
>>> @patch.object(SomeClass, 'attribute', sentinel.attribute)
... def test():
...     assert SomeClass.attribute == sentinel.attribute
...
>>> test()
>>> assert SomeClass.attribute == original

>>> @patch('package.module.attribute', sentinel.attribute)
... def test():
...     from package.module import attribute
...     assert attribute is sentinel.attribute
...
>>> test()

If you are patching a module (including builtins) then use patch() instead of patch.object():

>>> mock = MagicMock(return_value=sentinel.file_handle)
>>> with patch('builtins.open', mock):
...     handle = open('filename', 'r')
...
>>> mock.assert_called_with('filename', 'r')
>>> assert handle == sentinel.file_handle, "incorrect file handle returned"

The module name can be ‘dotted’, in the form package.module if needed:

>>> @patch('package.module.ClassName.attribute', sentinel.attribute)
... def test():
...     from package.module import ClassName
...     assert ClassName.attribute == sentinel.attribute
...
>>> test()

A nice pattern is to actually decorate test methods themselves:

>>> class MyTest(unittest.TestCase):
...     @patch.object(SomeClass, 'attribute', sentinel.attribute)
...     def test_something(self):
...         self.assertEqual(SomeClass.attribute, sentinel.attribute)
...
>>> original = SomeClass.attribute
>>> MyTest('test_something').test_something()
>>> assert SomeClass.attribute == original

If you want to patch with a Mock, you can use patch() with only one argument (or patch.object() with two arguments). The mock will be created for you and passed into the test function / method:

>>> class MyTest(unittest.TestCase):
...     @patch.object(SomeClass, 'static_method')
...     def test_something(self, mock_method):
...         SomeClass.static_method()
...         mock_method.assert_called_with()
...
>>> MyTest('test_something').test_something()

You can stack up multiple patch decorators using this pattern:

>>> class MyTest(unittest.TestCase):
...     @patch('package.module.ClassName1')
...     @patch('package.module.ClassName2')
...     def test_something(self, MockClass2, MockClass1):
...         self.assertIs(package.module.ClassName1, MockClass1)
...         self.assertIs(package.module.ClassName2, MockClass2)
...
>>> MyTest('test_something').test_something()

When you nest patch decorators the mocks are passed in to the decorated function in the same order they applied (the normal Python order that decorators are applied). This means from the bottom up, so in the example above the mock for test_module.ClassName2 is passed in first.

There is also patch.dict() for setting values in a dictionary just during a scope and restoring the dictionary to its original state when the test ends:

>>> foo = {'key': 'value'}
>>> original = foo.copy()
>>> with patch.dict(foo, {'newkey': 'newvalue'}, clear=True):
...     assert foo == {'newkey': 'newvalue'}
...
>>> assert foo == original

patch, patch.object and patch.dict can all be used as context managers.

Where you use patch() to create a mock for you, you can get a reference to the mock using the “as” form of the with statement:

>>> class ProductionClass:
...     def method(self):
...         pass
...
>>> with patch.object(ProductionClass, 'method') as mock_method:
...     mock_method.return_value = None
...     real = ProductionClass()
...     real.method(1, 2, 3)
...
>>> mock_method.assert_called_with(1, 2, 3)

As an alternative patch, patch.object and patch.dict can be used as class decorators. When used in this way it is the same as applying the decorator individually to every method whose name starts with “test”.

Further Examples

Here are some more examples for some slightly more advanced scenarios.

Mocking chained calls

Mocking chained calls is actually straightforward with mock once you understand the return_value attribute. When a mock is called for the first time, or you fetch its return_value before it has been called, a new Mock is created.

This means that you can see how the object returned from a call to a mocked object has been used by interrogating the return_value mock:

>>> mock = Mock()
>>> mock().foo(a=2, b=3)
<Mock name='mock().foo()' id='...'>
>>> mock.return_value.foo.assert_called_with(a=2, b=3)

From here it is a simple step to configure and then make assertions about chained calls. Of course another alternative is writing your code in a more testable way in the first place…

So, suppose we have some code that looks a little bit like this:

>>> class Something:
...     def __init__(self):
...         self.backend = BackendProvider()
...     def method(self):
...         response = self.backend.get_endpoint('foobar').create_call('spam', 'eggs').start_call()
...         # more code

Assuming that BackendProvider is already well tested, how do we test method()? Specifically, we want to test that the code section # more code uses the response object in the correct way.

As this chain of calls is made from an instance attribute we can monkey patch the backend attribute on a Something instance. In this particular case we are only interested in the return value from the final call to start_call so we don’t have much configuration to do. Let’s assume the object it returns is ‘file-like’, so we’ll ensure that our response object uses the builtin open() as its spec.

To do this we create a mock instance as our mock backend and create a mock response object for it. To set the response as the return value for that final start_call we could do this:

mock_backend.get_endpoint.return_value.create_call.return_value.start_call.return_value = mock_response

We can do that in a slightly nicer way using the configure_mock() method to directly set the return value for us:

>>> something = Something()
>>> mock_response = Mock(spec=open)
>>> mock_backend = Mock()
>>> config = {'get_endpoint.return_value.create_call.return_value.start_call.return_value': mock_response}
>>> mock_backend.configure_mock(**config)

With these we monkey patch the “mock backend” in place and can make the real call:

>>> something.backend = mock_backend
>>> something.method()

Using mock_calls we can check the chained call with a single assert. A chained call is several calls in one line of code, so there will be several entries in mock_calls. We can use call.call_list() to create this list of calls for us:

>>> chained = call.get_endpoint('foobar').create_call('spam', 'eggs').start_call()
>>> call_list = chained.call_list()
>>> assert mock_backend.mock_calls == call_list

Partial mocking

In some tests I wanted to mock out a call to datetime.date.today() to return a known date, but I didn’t want to prevent the code under test from creating new date objects. Unfortunately datetime.date is written in C, and so I couldn’t just monkey-patch out the static date.today() method.

I found a simple way of doing this that involved effectively wrapping the date class with a mock, but passing through calls to the constructor to the real class (and returning real instances).

The patch decorator is used here to mock out the date class in the module under test. The side_effect attribute on the mock date class is then set to a lambda function that returns a real date. When the mock date class is called a real date will be constructed and returned by side_effect.

>>> from datetime import date
>>> with patch('mymodule.date') as mock_date:
...     mock_date.today.return_value = date(2010, 10, 8)
...     mock_date.side_effect = lambda *args, **kw: date(*args, **kw)
...
...     assert mymodule.date.today() == date(2010, 10, 8)
...     assert mymodule.date(2009, 6, 8) == date(2009, 6, 8)
...

Note that we don’t patch datetime.date globally, we patch date in the module that uses it. See where to patch.

When date.today() is called a known date is returned, but calls to the date(...) constructor still return normal dates. Without this you can find yourself having to calculate an expected result using exactly the same algorithm as the code under test, which is a classic testing anti-pattern.

Calls to the date constructor are recorded in the mock_date attributes (call_count and friends) which may also be useful for your tests.

An alternative way of dealing with mocking dates, or other builtin classes, is discussed in this blog entry [https://williambert.online/2011/07/how-to-unit-testing-in-django-with-mocking-and-patching/].

Mocking a Generator Method

A Python generator is a function or method that uses the yield statement to return a series of values when iterated over 1.

A generator method / function is called to return the generator object. It is the generator object that is then iterated over. The protocol method for iteration is __iter__(), so we can mock this using a MagicMock.

Here’s an example class with an “iter” method implemented as a generator:

>>> class Foo:
...     def iter(self):
...         for i in [1, 2, 3]:
...             yield i
...
>>> foo = Foo()
>>> list(foo.iter())
[1, 2, 3]

How would we mock this class, and in particular its “iter” method?

To configure the values returned from the iteration (implicit in the call to list), we need to configure the object returned by the call to foo.iter().

>>> mock_foo = MagicMock()
>>> mock_foo.iter.return_value = iter([1, 2, 3])
>>> list(mock_foo.iter())
[1, 2, 3]

1

There are also generator expressions and more advanced uses [http://www.dabeaz.com/coroutines/index.html] of generators, but we aren’t concerned about them here. A very good introduction to generators and how powerful they are is: Generator Tricks for Systems Programmers [http://www.dabeaz.com/generators/].

Applying the same patch to every test method

If you want several patches in place for multiple test methods the obvious way is to apply the patch decorators to every method. This can feel like unnecessary repetition. For Python 2.6 or more recent you can use patch() (in all its various forms) as a class decorator. This applies the patches to all test methods on the class. A test method is identified by methods whose names start with test:

>>> @patch('mymodule.SomeClass')
... class MyTest(TestCase):
...
...     def test_one(self, MockSomeClass):
...         self.assertIs(mymodule.SomeClass, MockSomeClass)
...
...     def test_two(self, MockSomeClass):
...         self.assertIs(mymodule.SomeClass, MockSomeClass)
...
...     def not_a_test(self):
...         return 'something'
...
>>> MyTest('test_one').test_one()
>>> MyTest('test_two').test_two()
>>> MyTest('test_two').not_a_test()
'something'

An alternative way of managing patches is to use the patch methods: start and stop. These allow you to move the patching into your setUp and tearDown methods.

>>> class MyTest(TestCase):
...     def setUp(self):
...         self.patcher = patch('mymodule.foo')
...         self.mock_foo = self.patcher.start()
...
...     def test_foo(self):
...         self.assertIs(mymodule.foo, self.mock_foo)
...
...     def tearDown(self):
...         self.patcher.stop()
...
>>> MyTest('test_foo').run()

If you use this technique you must ensure that the patching is “undone” by calling stop. This can be fiddlier than you might think, because if an exception is raised in the setUp then tearDown is not called. unittest.TestCase.addCleanup() makes this easier:

>>> class MyTest(TestCase):
...     def setUp(self):
...         patcher = patch('mymodule.foo')
...         self.addCleanup(patcher.stop)
...         self.mock_foo = patcher.start()
...
...     def test_foo(self):
...         self.assertIs(mymodule.foo, self.mock_foo)
...
>>> MyTest('test_foo').run()

Mocking Unbound Methods

Whilst writing tests today I needed to patch an unbound method (patching the method on the class rather than on the instance). I needed self to be passed in as the first argument because I want to make asserts about which objects were calling this particular method. The issue is that you can’t patch with a mock for this, because if you replace an unbound method with a mock it doesn’t become a bound method when fetched from the instance, and so it doesn’t get self passed in. The workaround is to patch the unbound method with a real function instead. The patch() decorator makes it so simple to patch out methods with a mock that having to create a real function becomes a nuisance.

If you pass autospec=True to patch then it does the patching with a real function object. This function object has the same signature as the one it is replacing, but delegates to a mock under the hood. You still get your mock auto-created in exactly the same way as before. What it means though, is that if you use it to patch out an unbound method on a class the mocked function will be turned into a bound method if it is fetched from an instance. It will have self passed in as the first argument, which is exactly what I wanted:

>>> class Foo:
...   def foo(self):
...     pass
...
>>> with patch.object(Foo, 'foo', autospec=True) as mock_foo:
...   mock_foo.return_value = 'foo'
...   foo = Foo()
...   foo.foo()
...
'foo'
>>> mock_foo.assert_called_once_with(foo)

If we don’t use autospec=True then the unbound method is patched out with a Mock instance instead, and isn’t called with self.

Checking multiple calls with mock

mock has a nice API for making assertions about how your mock objects are used.

>>> mock = Mock()
>>> mock.foo_bar.return_value = None
>>> mock.foo_bar('baz', spam='eggs')
>>> mock.foo_bar.assert_called_with('baz', spam='eggs')

If your mock is only being called once you can use the assert_called_once_with() method that also asserts that the call_count is one.

>>> mock.foo_bar.assert_called_once_with('baz', spam='eggs')
>>> mock.foo_bar()
>>> mock.foo_bar.assert_called_once_with('baz', spam='eggs')
Traceback (most recent call last):
    ...
AssertionError: Expected to be called once. Called 2 times.

Both assert_called_with and assert_called_once_with make assertions about the most recent call. If your mock is going to be called several times, and you want to make assertions about all those calls you can use call_args_list:

>>> mock = Mock(return_value=None)
>>> mock(1, 2, 3)
>>> mock(4, 5, 6)
>>> mock()
>>> mock.call_args_list
[call(1, 2, 3), call(4, 5, 6), call()]

The call helper makes it easy to make assertions about these calls. You can build up a list of expected calls and compare it to call_args_list. This looks remarkably similar to the repr of the call_args_list:

>>> expected = [call(1, 2, 3), call(4, 5, 6), call()]
>>> mock.call_args_list == expected
True

Coping with mutable arguments

Another situation is rare, but can bite you, is when your mock is called with mutable arguments. call_args and call_args_list store references to the arguments. If the arguments are mutated by the code under test then you can no longer make assertions about what the values were when the mock was called.

Here’s some example code that shows the problem. Imagine the following functions defined in ‘mymodule’:

def frob(val):
    pass

def grob(val):
    "First frob and then clear val"
    frob(val)
    val.clear()

When we try to test that grob calls frob with the correct argument look what happens:

>>> with patch('mymodule.frob') as mock_frob:
...     val = {6}
...     mymodule.grob(val)
...
>>> val
set()
>>> mock_frob.assert_called_with({6})
Traceback (most recent call last):
    ...
AssertionError: Expected: (({6},), {})
Called with: ((set(),), {})

One possibility would be for mock to copy the arguments you pass in. This could then cause problems if you do assertions that rely on object identity for equality.

Here’s one solution that uses the side_effect functionality. If you provide a side_effect function for a mock then side_effect will be called with the same args as the mock. This gives us an opportunity to copy the arguments and store them for later assertions. In this example I’m using another mock to store the arguments so that I can use the mock methods for doing the assertion. Again a helper function sets this up for me.

>>> from copy import deepcopy
>>> from unittest.mock import Mock, patch, DEFAULT
>>> def copy_call_args(mock):
...     new_mock = Mock()
...     def side_effect(*args, **kwargs):
...         args = deepcopy(args)
...         kwargs = deepcopy(kwargs)
...         new_mock(*args, **kwargs)
...         return DEFAULT
...     mock.side_effect = side_effect
...     return new_mock
...
>>> with patch('mymodule.frob') as mock_frob:
...     new_mock = copy_call_args(mock_frob)
...     val = {6}
...     mymodule.grob(val)
...
>>> new_mock.assert_called_with({6})
>>> new_mock.call_args
call({6})

copy_call_args is called with the mock that will be called. It returns a new mock that we do the assertion on. The side_effect function makes a copy of the args and calls our new_mock with the copy.

참고

If your mock is only going to be used once there is an easier way of checking arguments at the point they are called. You can simply do the checking inside a side_effect function.

>>> def side_effect(arg):
...     assert arg == {6}
...
>>> mock = Mock(side_effect=side_effect)
>>> mock({6})
>>> mock(set())
Traceback (most recent call last):
    ...
AssertionError

An alternative approach is to create a subclass of Mock or MagicMock that copies (using copy.deepcopy()) the arguments. Here’s an example implementation:

>>> from copy import deepcopy
>>> class CopyingMock(MagicMock):
...     def __call__(self, *args, **kwargs):
...         args = deepcopy(args)
...         kwargs = deepcopy(kwargs)
...         return super(CopyingMock, self).__call__(*args, **kwargs)
...
>>> c = CopyingMock(return_value=None)
>>> arg = set()
>>> c(arg)
>>> arg.add(1)
>>> c.assert_called_with(set())
>>> c.assert_called_with(arg)
Traceback (most recent call last):
    ...
AssertionError: Expected call: mock({1})
Actual call: mock(set())
>>> c.foo
<CopyingMock name='mock.foo' id='...'>

When you subclass Mock or MagicMock all dynamically created attributes, and the return_value will use your subclass automatically. That means all children of a CopyingMock will also have the type CopyingMock.

Nesting Patches

Using patch as a context manager is nice, but if you do multiple patches you can end up with nested with statements indenting further and further to the right:

>>> class MyTest(TestCase):
...
...     def test_foo(self):
...         with patch('mymodule.Foo') as mock_foo:
...             with patch('mymodule.Bar') as mock_bar:
...                 with patch('mymodule.Spam') as mock_spam:
...                     assert mymodule.Foo is mock_foo
...                     assert mymodule.Bar is mock_bar
...                     assert mymodule.Spam is mock_spam
...
>>> original = mymodule.Foo
>>> MyTest('test_foo').test_foo()
>>> assert mymodule.Foo is original

With unittest cleanup functions and the patch methods: start and stop we can achieve the same effect without the nested indentation. A simple helper method, create_patch, puts the patch in place and returns the created mock for us:

>>> class MyTest(TestCase):
...
...     def create_patch(self, name):
...         patcher = patch(name)
...         thing = patcher.start()
...         self.addCleanup(patcher.stop)
...         return thing
...
...     def test_foo(self):
...         mock_foo = self.create_patch('mymodule.Foo')
...         mock_bar = self.create_patch('mymodule.Bar')
...         mock_spam = self.create_patch('mymodule.Spam')
...
...         assert mymodule.Foo is mock_foo
...         assert mymodule.Bar is mock_bar
...         assert mymodule.Spam is mock_spam
...
>>> original = mymodule.Foo
>>> MyTest('test_foo').run()
>>> assert mymodule.Foo is original

Mocking a dictionary with MagicMock

You may want to mock a dictionary, or other container object, recording all access to it whilst having it still behave like a dictionary.

We can do this with MagicMock, which will behave like a dictionary, and using side_effect to delegate dictionary access to a real underlying dictionary that is under our control.

When the __getitem__() and __setitem__() methods of our MagicMock are called (normal dictionary access) then side_effect is called with the key (and in the case of __setitem__ the value too). We can also control what is returned.

After the MagicMock has been used we can use attributes like call_args_list to assert about how the dictionary was used:

>>> my_dict = {'a': 1, 'b': 2, 'c': 3}
>>> def getitem(name):
...      return my_dict[name]
...
>>> def setitem(name, val):
...     my_dict[name] = val
...
>>> mock = MagicMock()
>>> mock.__getitem__.side_effect = getitem
>>> mock.__setitem__.side_effect = setitem

참고

An alternative to using MagicMock is to use Mock and only provide the magic methods you specifically want:

>>> mock = Mock()
>>> mock.__getitem__ = Mock(side_effect=getitem)
>>> mock.__setitem__ = Mock(side_effect=setitem)

A third option is to use MagicMock but passing in dict as the spec (or spec_set) argument so that the MagicMock created only has dictionary magic methods available:

>>> mock = MagicMock(spec_set=dict)
>>> mock.__getitem__.side_effect = getitem
>>> mock.__setitem__.side_effect = setitem

With these side effect functions in place, the mock will behave like a normal dictionary but recording the access. It even raises a KeyError if you try to access a key that doesn’t exist.

>>> mock['a']
1
>>> mock['c']
3
>>> mock['d']
Traceback (most recent call last):
    ...
KeyError: 'd'
>>> mock['b'] = 'fish'
>>> mock['d'] = 'eggs'
>>> mock['b']
'fish'
>>> mock['d']
'eggs'

After it has been used you can make assertions about the access using the normal mock methods and attributes:

>>> mock.__getitem__.call_args_list
[call('a'), call('c'), call('d'), call('b'), call('d')]
>>> mock.__setitem__.call_args_list
[call('b', 'fish'), call('d', 'eggs')]
>>> my_dict
{'a': 1, 'c': 3, 'b': 'fish', 'd': 'eggs'}

Mock subclasses and their attributes

There are various reasons why you might want to subclass Mock. One reason might be to add helper methods. Here’s a silly example:

>>> class MyMock(MagicMock):
...     def has_been_called(self):
...         return self.called
...
>>> mymock = MyMock(return_value=None)
>>> mymock
<MyMock id='...'>
>>> mymock.has_been_called()
False
>>> mymock()
>>> mymock.has_been_called()
True

The standard behaviour for Mock instances is that attributes and the return value mocks are of the same type as the mock they are accessed on. This ensures that Mock attributes are Mocks and MagicMock attributes are MagicMocks 2. So if you’re subclassing to add helper methods then they’ll also be available on the attributes and return value mock of instances of your subclass.

>>> mymock.foo
<MyMock name='mock.foo' id='...'>
>>> mymock.foo.has_been_called()
False
>>> mymock.foo()
<MyMock name='mock.foo()' id='...'>
>>> mymock.foo.has_been_called()
True

Sometimes this is inconvenient. For example, one user [https://code.google.com/archive/p/mock/issues/105] is subclassing mock to created a Twisted adaptor [https://twistedmatrix.com/documents/11.0.0/api/twisted.python.components.html]. Having this applied to attributes too actually causes errors.

Mock (in all its flavours) uses a method called _get_child_mock to create these “sub-mocks” for attributes and return values. You can prevent your subclass being used for attributes by overriding this method. The signature is that it takes arbitrary keyword arguments (**kwargs) which are then passed onto the mock constructor:

>>> class Subclass(MagicMock):
...     def _get_child_mock(self, **kwargs):
...         return MagicMock(**kwargs)
...
>>> mymock = Subclass()
>>> mymock.foo
<MagicMock name='mock.foo' id='...'>
>>> assert isinstance(mymock, Subclass)
>>> assert not isinstance(mymock.foo, Subclass)
>>> assert not isinstance(mymock(), Subclass)

2

An exception to this rule are the non-callable mocks. Attributes use the callable variant because otherwise non-callable mocks couldn’t have callable methods.

Mocking imports with patch.dict

One situation where mocking can be hard is where you have a local import inside a function. These are harder to mock because they aren’t using an object from the module namespace that we can patch out.

Generally local imports are to be avoided. They are sometimes done to prevent circular dependencies, for which there is usually a much better way to solve the problem (refactor the code) or to prevent “up front costs” by delaying the import. This can also be solved in better ways than an unconditional local import (store the module as a class or module attribute and only do the import on first use).

That aside there is a way to use mock to affect the results of an import. Importing fetches an object from the sys.modules dictionary. Note that it fetches an object, which need not be a module. Importing a module for the first time results in a module object being put in sys.modules, so usually when you import something you get a module back. This need not be the case however.

This means you can use patch.dict() to temporarily put a mock in place in sys.modules. Any imports whilst this patch is active will fetch the mock. When the patch is complete (the decorated function exits, the with statement body is complete or patcher.stop() is called) then whatever was there previously will be restored safely.

Here’s an example that mocks out the ‘fooble’ module.

>>> mock = Mock()
>>> with patch.dict('sys.modules', {'fooble': mock}):
...    import fooble
...    fooble.blob()
...
<Mock name='mock.blob()' id='...'>
>>> assert 'fooble' not in sys.modules
>>> mock.blob.assert_called_once_with()

As you can see the import fooble succeeds, but on exit there is no ‘fooble’ left in sys.modules.

This also works for the from module import name form:

>>> mock = Mock()
>>> with patch.dict('sys.modules', {'fooble': mock}):
...    from fooble import blob
...    blob.blip()
...
<Mock name='mock.blob.blip()' id='...'>
>>> mock.blob.blip.assert_called_once_with()

With slightly more work you can also mock package imports:

>>> mock = Mock()
>>> modules = {'package': mock, 'package.module': mock.module}
>>> with patch.dict('sys.modules', modules):
...    from package.module import fooble
...    fooble()
...
<Mock name='mock.module.fooble()' id='...'>
>>> mock.module.fooble.assert_called_once_with()

Tracking order of calls and less verbose call assertions

The Mock class allows you to track the order of method calls on your mock objects through the method_calls attribute. This doesn’t allow you to track the order of calls between separate mock objects, however we can use mock_calls to achieve the same effect.

Because mocks track calls to child mocks in mock_calls, and accessing an arbitrary attribute of a mock creates a child mock, we can create our separate mocks from a parent one. Calls to those child mock will then all be recorded, in order, in the mock_calls of the parent:

>>> manager = Mock()
>>> mock_foo = manager.foo
>>> mock_bar = manager.bar

>>> mock_foo.something()
<Mock name='mock.foo.something()' id='...'>
>>> mock_bar.other.thing()
<Mock name='mock.bar.other.thing()' id='...'>

>>> manager.mock_calls
[call.foo.something(), call.bar.other.thing()]

We can then assert about the calls, including the order, by comparing with the mock_calls attribute on the manager mock:

>>> expected_calls = [call.foo.something(), call.bar.other.thing()]
>>> manager.mock_calls == expected_calls
True

If patch is creating, and putting in place, your mocks then you can attach them to a manager mock using the attach_mock() method. After attaching calls will be recorded in mock_calls of the manager.

>>> manager = MagicMock()
>>> with patch('mymodule.Class1') as MockClass1:
...     with patch('mymodule.Class2') as MockClass2:
...         manager.attach_mock(MockClass1, 'MockClass1')
...         manager.attach_mock(MockClass2, 'MockClass2')
...         MockClass1().foo()
...         MockClass2().bar()
...
<MagicMock name='mock.MockClass1().foo()' id='...'>
<MagicMock name='mock.MockClass2().bar()' id='...'>
>>> manager.mock_calls
[call.MockClass1(),
 call.MockClass1().foo(),
 call.MockClass2(),
 call.MockClass2().bar()]

If many calls have been made, but you’re only interested in a particular sequence of them then an alternative is to use the assert_has_calls() method. This takes a list of calls (constructed with the call object). If that sequence of calls are in mock_calls then the assert succeeds.

>>> m = MagicMock()
>>> m().foo().bar().baz()
<MagicMock name='mock().foo().bar().baz()' id='...'>
>>> m.one().two().three()
<MagicMock name='mock.one().two().three()' id='...'>
>>> calls = call.one().two().three().call_list()
>>> m.assert_has_calls(calls)

Even though the chained call m.one().two().three() aren’t the only calls that have been made to the mock, the assert still succeeds.

Sometimes a mock may have several calls made to it, and you are only interested in asserting about some of those calls. You may not even care about the order. In this case you can pass any_order=True to assert_has_calls:

>>> m = MagicMock()
>>> m(1), m.two(2, 3), m.seven(7), m.fifty('50')
(...)
>>> calls = [call.fifty('50'), call(1), call.seven(7)]
>>> m.assert_has_calls(calls, any_order=True)

More complex argument matching

Using the same basic concept as ANY we can implement matchers to do more complex assertions on objects used as arguments to mocks.

Suppose we expect some object to be passed to a mock that by default compares equal based on object identity (which is the Python default for user defined classes). To use assert_called_with() we would need to pass in the exact same object. If we are only interested in some of the attributes of this object then we can create a matcher that will check these attributes for us.

You can see in this example how a ‘standard’ call to assert_called_with isn’t sufficient:

>>> class Foo:
...     def __init__(self, a, b):
...         self.a, self.b = a, b
...
>>> mock = Mock(return_value=None)
>>> mock(Foo(1, 2))
>>> mock.assert_called_with(Foo(1, 2))
Traceback (most recent call last):
    ...
AssertionError: Expected: call(<__main__.Foo object at 0x...>)
Actual call: call(<__main__.Foo object at 0x...>)

A comparison function for our Foo class might look something like this:

>>> def compare(self, other):
...     if not type(self) == type(other):
...         return False
...     if self.a != other.a:
...         return False
...     if self.b != other.b:
...         return False
...     return True
...

And a matcher object that can use comparison functions like this for its equality operation would look something like this:

>>> class Matcher:
...     def __init__(self, compare, some_obj):
...         self.compare = compare
...         self.some_obj = some_obj
...     def __eq__(self, other):
...         return self.compare(self.some_obj, other)
...

Putting all this together:

>>> match_foo = Matcher(compare, Foo(1, 2))
>>> mock.assert_called_with(match_foo)

The Matcher is instantiated with our compare function and the Foo object we want to compare against. In assert_called_with the Matcher equality method will be called, which compares the object the mock was called with against the one we created our matcher with. If they match then assert_called_with passes, and if they don’t an AssertionError is raised:

>>> match_wrong = Matcher(compare, Foo(3, 4))
>>> mock.assert_called_with(match_wrong)
Traceback (most recent call last):
    ...
AssertionError: Expected: ((<Matcher object at 0x...>,), {})
Called with: ((<Foo object at 0x...>,), {})

With a bit of tweaking you could have the comparison function raise the AssertionError directly and provide a more useful failure message.

As of version 1.5, the Python testing library PyHamcrest [https://pyhamcrest.readthedocs.io/] provides similar functionality, that may be useful here, in the form of its equality matcher (hamcrest.library.integration.match_equality [https://pyhamcrest.readthedocs.io/en/release-1.8/integration/#module-hamcrest.library.integration.match_equality]).

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

개발 도구 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

개발 도구 »

|

2to3 - 파이썬 2에서 파이썬 3으로 자동 코드 변환

2to3는 파이썬 2.x 소스 코드를 유효한 파이썬 3.x 코드로 변환하기 위해 일련의 변환자(fixers)를 적용하는 프로그램입니다. 표준 라이브러리는 많은 양의 변환자를 제공하고 있어 코드 대부분을 처리할 수 있을 것입니다. 2to3에서 사용하는 모듈인 lib2to3 는 유연하고 제네릭합니다. 따라서 2to3 프로그램을 위해 당신만의 변환자를 작성할 수 있습니다. 또한 lib2to3 는 파이썬 코드를 자동으로 수정해주는 커스텀 응용 프로그램에서도 사용할 수 있습니다.

2to3 사용법

파이썬 인터프리터가 설치될 때, 보통 2to3 스크립트도 같이 설치됩니다. 2to3 스크립트 파일은 파이썬 루트 디렉터리의 하위 디렉터리인 Tools/scripts 에서 찾을 수 있습니다.

2to3의 기본 인자는 변환하고자 하는 파일이나 디렉터리 리스트입니다. 디렉터리의 경우 하위 폴더의 파이썬 소스까지 적용됩니다.

샘플 파이썬 2.x 코드가 여기 있습니다. example.py:

def greet(name):
    print "Hello, {0}!".format(name)
print "What's your name?"
name = raw_input()
greet(name)

명령줄에서 2to3를 실행하면 이 코드를 파이썬 3.x 코드로 바꿀 수 있습니다:

$ 2to3 example.py

원본 파일과 변환 결과를 비교한 차이점(diff)이 출력됩니다. 2to3은 원본 소스 파일에 필요한 수정사항을 바로 적용할 수도 있습니다. (-n 옵션이 적용되지 않았다면 원본 파일에 대한 백업이 생성될 것입니다.) -w 옵션을 사용하면 바로 원본 파일이 수정됩니다.

$ 2to3 -w example.py

example.py 를 변환한 결과는 다음과 같습니다.

def greet(name):
    print("Hello, {0}!".format(name))
print("What's your name?")
name = input()
greet(name)

변환 과정에서 들여쓰기와 주석은 그대로 보존됩니다.

기본적으로 2to3는 미리 정의된 변환자 를 사용하여 실행됩니다. -l 옵션을 사용하면 사용 가능한 모든 변환자를 볼 수 있습니다. 특정 변환자만 명시적으로 설정하고 싶으시면 -f 를 사용하시면 됩니다. 마찬가지로 -x 옵션으로 특정 변환자를 비활성화할 수도 있습니다. 다음 예는 imports 와 has_key 변환자만 사용한 것입니다.

$ 2to3 -f imports -f has_key example.py

다음은 apply 변환자만 빼고 모든 변환자를 실행하는 명령어입니다.

$ 2to3 -x apply example.py

몇몇 변환자는 기본적으로 실행되지 않기 때문에 명시적으로 명령줄에서 설정해야 합니다. 기본 변환자에 idioms 변환자를 추가한 예시가 여기 있습니다.

$ 2to3 -f all -f idioms example.py

모든 기본 변환자를 활성화하기 위해 all 값을 사용한 것을 주목해주세요.

때때로 2to3는 자동 변환을 하지 못하고 당신의 코드에서 수정이 필요한 부분을 찾을 수도 있습니다. 이러면 파일의 비교 결과 아래에 경고 문구를 출력할 것입니다. 당신은 이 소스코드를 3.x 버전에 맞도록 경고 사항을 수정해야 합니다.

2to3는 doctest도 수정할 수 있습니다. 이것을 활성화하기 위해서는 -d 옵션을 사용하세요. 이것은 오직 doctest만 수정한다는 것을 명심하세요. 이것을 사용하기 위해서 꼭 적합한 파이썬 모듈이 필요한 것은 아닙니다. 예를 들어 reST 문서에 있는 예와 같은 doctest도 이 옵션과 함께 수정할 수 있습니다.

-v 옵션은 변환 과정 동안 더 자세한 정보를 출력하게 해줍니다.

어떤 print 문장의 경우는 문장 또는 함수 호출로 파싱될 수 있기 때문에 2to3이 print 함수를 포함한 파일을 항상 처리할 수 있는 것은 아닙니다. 2to3이 from __future__ import print_function 이란 컴파일러 지시어를 찾았다면 2to3는 print() 를 함수로 처리하도록 내부 처리 문법을 변경할 것입니다. 이러한 변경은 -p 옵션을 가지고 직접 활성화할 수도 있습니다. 출력 문장이 이미 변경된 코드에 변환자를 실행하기 위해 -p 옵션을 사용하세요.

-o 또는 --output-dir 옵션을 사용하면 출력 파일이 쓰일 디렉터리를 설정할 수 있습니다.:option:!-n 옵션은 입력 파일을 덮어쓰지 않아 백업 파일이 필요 없을 때 사용할 수 있습니다.

버전 3.2.3에 추가: -o 옵션이 추가되었습니다.

-W 또는 --write-unchanged-files 옵션은 변경 사항이 없더라도 항상 출력 파일을 쓰도록 합니다. 이것을 -o 옵션과 함께 쓰면 한 디렉터리에 있는 전체 파이썬 소스 트리를 파이썬 3.x로 변환해서 다른 디렉터리로 복사할 때 유용하게 사용할 수 있습니다. 이치에 맞게 하기 위해 이 옵션은 -w 옵션을 포함하고 있습니다.

버전 3.2.3에 추가: -W 옵션이 추가되었습니다.

--add-suffix 옵션은 모든 출력 파일 이름 뒤에 추가할 문자열을 지정합니다. 다른 파일 이름으로 저장할 때 백업 파일이 필요하지 않다면 -n 옵션을 같이 사용해야 합니다. 예시:

$ 2to3 -n -W --add-suffix=3 example.py

이 명령어는 출력 파일의 이름을 example.py3 로 만들어 줍니다.

버전 3.2.3에 추가: --add-suffix 옵션이 추가되었습니다.

한 디렉터리에서 다른 디렉터리로 전체 프로젝트를 변환하고 싶을 때는 다음과 같이 하면 됩니다.

$ 2to3 --output-dir=python3-version/mycode -W -n python2-version/mycode

변환자 목록

변환되는 코드의 각각 단계는 변환자 안에 캡슐화되어 있습니다. 2to3 -l 명령어를 실행하면 변환자 목록을 보실 수 있습니다. 위에 적어놓은 것 과 같이, 각 변환자는 개별적으로 활성화/비활성화를 할 수 있습니다. 변환자들에 대한 자세한 설명이 아래에 있습니다.

apply

apply() 사용을 제거합니다. 예를 들어 apply(function, *args, **kwargs) 를 function(*args, **kwargs) 로 변경합니다.

asserts

폐지된 unittest 메서드 이름을 올바른 것으로 변경합니다.

변경 전

변경 후

failUnlessEqual(a, b)

assertEqual(a, b)

assertEquals(a, b)

assertEqual(a, b)

failIfEqual(a, b)

assertNotEqual(a, b)

assertNotEquals(a, b)

assertNotEqual(a, b)

failUnless(a)

assertTrue(a)

assert_(a)

assertTrue(a)

failIf(a)

assertFalse(a)

failUnlessRaises(exc, cal)

assertRaises(exc, cal)

failUnlessAlmostEqual(a, b)

assertAlmostEqual(a, b)

assertAlmostEquals(a, b)

assertAlmostEqual(a, b)

failIfAlmostEqual(a, b)

assertNotAlmostEqual(a, b)

assertNotAlmostEquals(a, b)

assertNotAlmostEqual(a, b)

basestring

basestring 을 str 로 변환합니다.

buffer

buffer 를 memoryview 로 변환합니다. memoryview API가 buffer API와 비슷하긴 하지만 완전히 같진 않아서 이 변환자는 선택적으로 실행됩니다.

dict

딕셔너리 이터레이션 메서드를 변환합니다. dict.iteritems() 를 dict.items() 로, dict.iterkeys() 를 dict.keys() 로, dict.itervalues() 를 dict.values() 로 변경합니다. 마찬가지로 dict.viewitems(), dict.viewkeys(), dict.viewvalues() 를 각각 dict.items(), dict.keys(), dict.values() 로 변경합니다. 기존의 dict.items(), dict.keys(), dict.values() 의 사용을 list 로 감싸도록 바꿉니다.

except

except X, T 를 except X as T 로 변환합니다.

exec

exec 문장을 exec() 함수로 변환합니다.

execfile

execfile() 사용을 제거합니다. execfile() 에 사용되는 인자는 open(), compile(), exec() 을 사용하도록 바뀝니다.

exitfunc

sys.exitfunc 대입이 atexit 모듈을 사용하도록 바뀝니다.

filter

filter() 함수 사용을 list 로 감싸도록 바꿉니다.

funcattrs

이름이 변경된 함수 어트리뷰트를 변환합니다. 예를 들어 my_function.func_closure 를 my_function.__closure__ 로 변경합니다.

future

from __future__ import new_feature 구문을 제거합니다.

getcwdu

os.getcwdu() 를 os.getcwd() 로 변경합니다.

has_key

dict.has_key(key) 를 key in dict 로 바꿉니다.

idioms

이 선택적인 변환자는 이디엄을 더 사용하도록 파이썬 코드를 변환해줍니다. type(x) is SomeClass 나 type(x) == SomeClass 같은 형 비교는 isinstance(x, SomeClass) 로 변환합니다. while 1 는 while True 로 변환합니다. 또한 이 변환자는 sorted() 가 올바른 위치에 사용될 수 있도록 수정합니다. 예를 들어 다음 코드는

L = list(some_iterable)
L.sort()

아래와 같이 변경됩니다.

L = sorted(some_iterable)

import

같은 단계 경로의 임포트를 찾아 상대 경로 임포트로 변경합니다.

imports

표준 라이브러리에 있는 모듈의 이름 변경 사항을 처리합니다.

imports2

표준 라이브러리에 있는 또 다른 모듈의 이름 변경 사항을 처리합니다. 기술적인 제한 사항 때문에 imports 변환자와 분리했습니다.

input

input(prompt) 를 eval(input(prompt)) 로 변경합니다.

intern

intern() 를 sys.intern() 로 변경합니다.

isinstance

isinstance() 의 두 번째 인자에서 중복된 형을 수정합니다. 예를 들어 isinstance(x, (int, int)) 를 isinstance(x, int) 로, isinstance(x, (int, float, int)) 를 isinstance(x, (int, float)) 로 변경합니다.

itertools_imports

itertools.ifilter(), itertools.izip(), itertools.imap() 임포트를 제거합니다. itertools.ifilterfalse() 임포트를 itertools.filterfalse() 로 바꿉니다.

itertools

itertools.ifilter(), itertools.izip(), itertools.imap() 를 각각 그것에 맞는 내장 함수로 변경합니다. itertools.ifilterfalse() 를 itertools.filterfalse() 로 변경합니다.

long

long 을 int 로 바꿉니다.

map

map() 을 list 로 감싸도록 바꿉니다. map(None, x) 를 list(x) 로 바꿉니다. from future_builtins import map 를 사용하면 이 변환자가 비활성화됩니다.

metaclass

구식의 메타 클래스 문법(클래스 바디에 __metaclass__ = Meta 를 사용)을 새로운 문법(class X(metaclass=Meta))으로 변경합니다.

methodattrs

구식의 메서드 어트리뷰트 이름을 수정합니다. 예를 들어 meth.im_func 를 meth.__func__ 로 변경합니다.

ne

구식의 부등호 문법인 <> 을 != 로 변경합니다.

next

이터레이터의 next() 메서드 사용을 next() 함수로 변경합니다. 또한 next() 메서드를 __next__() 로 바꿉니다.

nonzero

__nonzero__() 를 __bool__() 로 변경합니다.

numliterals

8진수 리터럴을 새 문법으로 변경합니다.

operator

operator 모듈에 있는 다양한 함수 호출을 그것에 대응하는 다른 함수 호출로 변경합니다. import collections.abc 와 같이 필요하다면 import 구문도 추가됩니다. 다음과 같이 변경합니다.

변경 전

변경 후

operator.isCallable(obj)

callable(obj)

operator.sequenceIncludes(obj)

operator.contains(obj)

operator.isSequenceType(obj)

isinstance(obj, collections.abc.Sequence)

operator.isMappingType(obj)

isinstance(obj, collections.abc.Mapping)

operator.isNumberType(obj)

isinstance(obj, numbers.Number)

operator.repeat(obj, n)

operator.mul(obj, n)

operator.irepeat(obj, n)

operator.imul(obj, n)

paren

리스트 컴프리헨션 안에 괄호가 필요한 경우 추가합니다. 예를 들어 [x for x in 1, 2] 를 [x for x in (1, 2)] 로 변경합니다.

print

print 구문을 print() 함수로 변경합니다.

raise

raise E, V 를 raise E(V) 로, raise E, V, T 를 raise E(V).with_traceback(T) 로 변경합니다. 만약 E 가 튜플인 경우, 변환된 결과물은 동작하지 않을 것입니다. 왜냐하면 튜플이 예외를 대체하는 것은 3.0부터 사라졌기 때문입니다.

raw_input

raw_input() 를 input() 로 변경합니다.

reduce

reduce() 를 functools.reduce() 로 변경합니다.

reload

reload() 를 importlib.reload() 로 변경합니다.

renames

sys.maxint 를 sys.maxsize 로 변경합니다.

repr

백틱 repr을 repr() 함수로 바꿉니다.

set_literal

set 생성자를 집합 리터럴로 바꿉니다. 이 변환자는 선택적입니다.

standarderror

StandardError 를 Exception 로 바꿉니다.

sys_exc

더 사용되지 않을 sys.exc_value, sys.exc_type, sys.exc_traceback 를 sys.exc_info() 로 변경합니다.

throw

제너레이터 throw() 메서드의 API 변경 사항을 반영합니다.

tuple_params

묵시적으로 튜플 매개 변수를 언패킹하는 것을 제거합니다. 이로 인해 이 변환자는 임시 변수를 추가합니다.

types

types 모듈에서 몇몇 멤버가 삭제되어 코드가 동작하지 않던 것을 수정합니다.

unicode

unicode 를 str 로 변경합니다.

urllib

urllib 와 urllib2 를 urllib 패키지로 변경합니다.

ws_comma

쉼표로 구분뒨 아이템 목록에서 필요 이상의 공백을 제거합니다. 이 변경자는 선택적입니다.

xrange

xrange() 를 range() 로 바꿉니다. 기존 range() 를 list 로 감쌉니다.

xreadlines

for x in file.xreadlines() 를 for x in file 로 변경합니다.

zip

zip() 를 list 로 감쌉니다. 이 변환자는 from future_builtins import zip 가 있을 때는 비활성화됩니다.

lib2to3 - 2to3 라이브러리

소스 코드: Lib/lib2to3/ [https://github.com/python/cpython/tree/3.7/Lib/lib2to3/]

참고

lib2to3 API는 미래에 크게 바뀔 수 있기 때문에 안정적이지 않다고 생각해야 합니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

개발 도구 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

개발 도구 »

|

test — Regression tests package for Python

참고

The test package is meant for internal use by Python only. It is documented for the benefit of the core developers of Python. Any use of this package outside of Python’s standard library is discouraged as code mentioned here can change or be removed without notice between releases of Python.

The test package contains all regression tests for Python as well as the modules test.support and test.regrtest. test.support is used to enhance your tests while test.regrtest drives the testing suite.

Each module in the test package whose name starts with test_ is a testing suite for a specific module or feature. All new tests should be written using the unittest or doctest module. Some older tests are written using a “traditional” testing style that compares output printed to sys.stdout; this style of test is considered deprecated.

더 보기

Module unittest

Writing PyUnit regression tests.

Module doctest

Tests embedded in documentation strings.

Writing Unit Tests for the test package

It is preferred that tests that use the unittest module follow a few guidelines. One is to name the test module by starting it with test_ and end it with the name of the module being tested. The test methods in the test module should start with test_ and end with a description of what the method is testing. This is needed so that the methods are recognized by the test driver as test methods. Also, no documentation string for the method should be included. A comment (such as # Tests function returns only True or False) should be used to provide documentation for test methods. This is done because documentation strings get printed out if they exist and thus what test is being run is not stated.

A basic boilerplate is often used:

import unittest
from test import support

class MyTestCase1(unittest.TestCase):

    # Only use setUp() and tearDown() if necessary

    def setUp(self):
        ... code to execute in preparation for tests ...

    def tearDown(self):
        ... code to execute to clean up after tests ...

    def test_feature_one(self):
        # Test feature one.
        ... testing code ...

    def test_feature_two(self):
        # Test feature two.
        ... testing code ...

    ... more test methods ...

class MyTestCase2(unittest.TestCase):
    ... same structure as MyTestCase1 ...

... more test classes ...

if __name__ == '__main__':
    unittest.main()

This code pattern allows the testing suite to be run by test.regrtest, on its own as a script that supports the unittest CLI, or via the python -m unittest CLI.

The goal for regression testing is to try to break code. This leads to a few guidelines to be followed:

The testing suite should exercise all classes, functions, and constants. This includes not just the external API that is to be presented to the outside world but also “private” code.

Whitebox testing (examining the code being tested when the tests are being written) is preferred. Blackbox testing (testing only the published user interface) is not complete enough to make sure all boundary and edge cases are tested.

Make sure all possible values are tested including invalid ones. This makes sure that not only all valid values are acceptable but also that improper values are handled correctly.

Exhaust as many code paths as possible. Test where branching occurs and thus tailor input to make sure as many different paths through the code are taken.

Add an explicit test for any bugs discovered for the tested code. This will make sure that the error does not crop up again if the code is changed in the future.

Make sure to clean up after your tests (such as close and remove all temporary files).

If a test is dependent on a specific condition of the operating system then verify the condition already exists before attempting the test.

Import as few modules as possible and do it as soon as possible. This minimizes external dependencies of tests and also minimizes possible anomalous behavior from side-effects of importing a module.

Try to maximize code reuse. On occasion, tests will vary by something as small as what type of input is used. Minimize code duplication by subclassing a basic test class with a class that specifies the input:

class TestFuncAcceptsSequencesMixin:

    func = mySuperWhammyFunction

    def test_func(self):
        self.func(self.arg)

class AcceptLists(TestFuncAcceptsSequencesMixin, unittest.TestCase):
    arg = [1, 2, 3]

class AcceptStrings(TestFuncAcceptsSequencesMixin, unittest.TestCase):
    arg = 'abc'

class AcceptTuples(TestFuncAcceptsSequencesMixin, unittest.TestCase):
    arg = (1, 2, 3)

When using this pattern, remember that all classes that inherit from unittest.TestCase are run as tests. The Mixin class in the example above does not have any data and so can’t be run by itself, thus it does not inherit from unittest.TestCase.

더 보기

Test Driven Development

A book by Kent Beck on writing tests before code.

Running tests using the command-line interface

The test package can be run as a script to drive Python’s regression test suite, thanks to the -m option: python -m test. Under the hood, it uses test.regrtest; the call python -m test.regrtest used in previous Python versions still works. Running the script by itself automatically starts running all regression tests in the test package. It does this by finding all modules in the package whose name starts with test_, importing them, and executing the function test_main() if present or loading the tests via unittest.TestLoader.loadTestsFromModule if test_main does not exist. The names of tests to execute may also be passed to the script. Specifying a single regression test (python -m test test_spam) will minimize output and only print whether the test passed or failed.

Running test directly allows what resources are available for tests to use to be set. You do this by using the -u command-line option. Specifying all as the value for the -u option enables all possible resources: python -m test -uall. If all but one resource is desired (a more common case), a comma-separated list of resources that are not desired may be listed after all. The command python -m test -uall,-audio,-largefile will run test with all resources except the audio and largefile resources. For a list of all resources and more command-line options, run python -m test -h.

Some other ways to execute the regression tests depend on what platform the tests are being executed on. On Unix, you can run make test at the top-level directory where Python was built. On Windows, executing rt.bat from your PCbuild directory will run all regression tests.

test.support — Utilities for the Python test suite

The test.support module provides support for Python’s regression test suite.

참고

test.support is not a public module. It is documented here to help Python developers write tests. The API of this module is subject to change without backwards compatibility concerns between releases.

This module defines the following exceptions:

exception test.support.TestFailed

Exception to be raised when a test fails. This is deprecated in favor of unittest-based tests and unittest.TestCase’s assertion methods.

exception test.support.ResourceDenied

Subclass of unittest.SkipTest. Raised when a resource (such as a network connection) is not available. Raised by the requires() function.

The test.support module defines the following constants:

test.support.verbose

True when verbose output is enabled. Should be checked when more detailed information is desired about a running test. verbose is set by test.regrtest.

test.support.is_jython

True if the running interpreter is Jython.

test.support.is_android

True if the system is Android.

test.support.unix_shell

Path for shell if not on Windows; otherwise None.

test.support.FS_NONASCII

A non-ASCII character encodable by os.fsencode().

test.support.TESTFN

Set to a name that is safe to use as the name of a temporary file. Any temporary file that is created should be closed and unlinked (removed).

test.support.TESTFN_UNICODE

Set to a non-ASCII name for a temporary file.

test.support.TESTFN_ENCODING

Set to sys.getfilesystemencoding().

test.support.TESTFN_UNENCODABLE

Set to a filename (str type) that should not be able to be encoded by file system encoding in strict mode. It may be None if it’s not possible to generate such a filename.

test.support.TESTFN_UNDECODABLE

Set to a filename (bytes type) that should not be able to be decoded by file system encoding in strict mode. It may be None if it’s not possible to generate such a filename.

test.support.TESTFN_NONASCII

Set to a filename containing the FS_NONASCII character.

test.support.IPV6_ENABLED

Set to True if IPV6 is enabled on this host, False otherwise.

test.support.SAVEDCWD

Set to os.getcwd().

test.support.PGO

Set when tests can be skipped when they are not useful for PGO.

test.support.PIPE_MAX_SIZE

A constant that is likely larger than the underlying OS pipe buffer size, to make writes blocking.

test.support.SOCK_MAX_SIZE

A constant that is likely larger than the underlying OS socket buffer size, to make writes blocking.

test.support.TEST_SUPPORT_DIR

Set to the top level directory that contains test.support.

test.support.TEST_HOME_DIR

Set to the top level directory for the test package.

test.support.TEST_DATA_DIR

Set to the data directory within the test package.

test.support.MAX_Py_ssize_t

Set to sys.maxsize for big memory tests.

test.support.max_memuse

Set by set_memlimit() as the memory limit for big memory tests. Limited by MAX_Py_ssize_t.

test.support.real_max_memuse

Set by set_memlimit() as the memory limit for big memory tests. Not limited by MAX_Py_ssize_t.

test.support.MISSING_C_DOCSTRINGS

Return True if running on CPython, not on Windows, and configuration not set with WITH_DOC_STRINGS.

test.support.HAVE_DOCSTRINGS

Check for presence of docstrings.

test.support.TEST_HTTP_URL

Define the URL of a dedicated HTTP server for the network tests.

test.support.ALWAYS_EQ

Object that is equal to anything. Used to test mixed type comparison.

test.support.LARGEST

Object that is greater than anything (except itself). Used to test mixed type comparison.

test.support.SMALLEST

Object that is less than anything (except itself). Used to test mixed type comparison.

The test.support module defines the following functions:

test.support.forget(module_name)

Remove the module named module_name from sys.modules and delete any byte-compiled files of the module.

test.support.unload(name)

Delete name from sys.modules.

test.support.unlink(filename)

Call os.unlink() on filename. On Windows platforms, this is wrapped with a wait loop that checks for the existence fo the file.

test.support.rmdir(filename)

Call os.rmdir() on filename. On Windows platforms, this is wrapped with a wait loop that checks for the existence of the file.

test.support.rmtree(path)

Call shutil.rmtree() on path or call os.lstat() and os.rmdir() to remove a path and its contents. On Windows platforms, this is wrapped with a wait loop that checks for the existence of the files.

test.support.make_legacy_pyc(source)

Move a PEP 3147/488 pyc file to its legacy pyc location and return the file system path to the legacy pyc file. The source value is the file system path to the source file. It does not need to exist, however the PEP 3147/488 pyc file must exist.

test.support.is_resource_enabled(resource)

Return True if resource is enabled and available. The list of available resources is only set when test.regrtest is executing the tests.

test.support.python_is_optimized()

Return True if Python was not built with -O0 or -Og.

test.support.with_pymalloc()

Return _testcapi.WITH_PYMALLOC.

test.support.requires(resource, msg=None)

Raise ResourceDenied if resource is not available. msg is the argument to ResourceDenied if it is raised. Always returns True if called by a function whose __name__ is '__main__'. Used when tests are executed by test.regrtest.

test.support.system_must_validate_cert(f)

Raise unittest.SkipTest on TLS certification validation failures.

test.support.sortdict(dict)

Return a repr of dict with keys sorted.

test.support.findfile(filename, subdir=None)

Return the path to the file named filename. If no match is found filename is returned. This does not equal a failure since it could be the path to the file.

Setting subdir indicates a relative path to use to find the file rather than looking directly in the path directories.

test.support.create_empty_file(filename)

Create an empty file with filename. If it already exists, truncate it.

test.support.fd_count()

Count the number of open file descriptors.

test.support.match_test(test)

Match test to patterns set in set_match_tests().

test.support.set_match_tests(patterns)

Define match test with regular expression patterns.

test.support.run_unittest(*classes)

Execute unittest.TestCase subclasses passed to the function. The function scans the classes for methods starting with the prefix test_ and executes the tests individually.

It is also legal to pass strings as parameters; these should be keys in sys.modules. Each associated module will be scanned by unittest.TestLoader.loadTestsFromModule(). This is usually seen in the following test_main() function:

def test_main():
    support.run_unittest(__name__)

This will run all tests defined in the named module.

test.support.run_doctest(module, verbosity=None, optionflags=0)

Run doctest.testmod() on the given module. Return (failure_count, test_count).

If verbosity is None, doctest.testmod() is run with verbosity set to verbose. Otherwise, it is run with verbosity set to None. optionflags is passed as optionflags to doctest.testmod().

test.support.setswitchinterval(interval)

Set the sys.setswitchinterval() to the given interval. Defines a minimum interval for Android systems to prevent the system from hanging.

test.support.check_impl_detail(**guards)

Use this check to guard CPython’s implementation-specific tests or to run them only on the implementations guarded by the arguments:

check_impl_detail()               # Only on CPython (default).
check_impl_detail(jython=True)    # Only on Jython.
check_impl_detail(cpython=False)  # Everywhere except CPython.

test.support.check_warnings(*filters, quiet=True)

A convenience wrapper for warnings.catch_warnings() that makes it easier to test that a warning was correctly raised. It is approximately equivalent to calling warnings.catch_warnings(record=True) with warnings.simplefilter() set to always and with the option to automatically validate the results that are recorded.

check_warnings accepts 2-tuples of the form ("message regexp", WarningCategory) as positional arguments. If one or more filters are provided, or if the optional keyword argument quiet is False, it checks to make sure the warnings are as expected: each specified filter must match at least one of the warnings raised by the enclosed code or the test fails, and if any warnings are raised that do not match any of the specified filters the test fails. To disable the first of these checks, set quiet to True.

If no arguments are specified, it defaults to:

check_warnings(("", Warning), quiet=True)

In this case all warnings are caught and no errors are raised.

On entry to the context manager, a WarningRecorder instance is returned. The underlying warnings list from catch_warnings() is available via the recorder object’s warnings attribute. As a convenience, the attributes of the object representing the most recent warning can also be accessed directly through the recorder object (see example below). If no warning has been raised, then any of the attributes that would otherwise be expected on an object representing a warning will return None.

The recorder object also has a reset() method, which clears the warnings list.

The context manager is designed to be used like this:

with check_warnings(("assertion is always true", SyntaxWarning),
                    ("", UserWarning)):
    exec('assert(False, "Hey!")')
    warnings.warn(UserWarning("Hide me!"))

In this case if either warning was not raised, or some other warning was raised, check_warnings() would raise an error.

When a test needs to look more deeply into the warnings, rather than just checking whether or not they occurred, code like this can be used:

with check_warnings(quiet=True) as w:
    warnings.warn("foo")
    assert str(w.args[0]) == "foo"
    warnings.warn("bar")
    assert str(w.args[0]) == "bar"
    assert str(w.warnings[0].args[0]) == "foo"
    assert str(w.warnings[1].args[0]) == "bar"
    w.reset()
    assert len(w.warnings) == 0

Here all warnings will be caught, and the test code tests the captured warnings directly.

버전 3.2에서 변경: New optional arguments filters and quiet.

test.support.check_no_resource_warning(testcase)

Context manager to check that no ResourceWarning was raised. You must remove the object which may emit ResourceWarning before the end of the context manager.

test.support.set_memlimit(limit)

Set the values for max_memuse and real_max_memuse for big memory tests.

test.support.record_original_stdout(stdout)

Store the value from stdout. It is meant to hold the stdout at the time the regrtest began.

test.support.get_original_stdout()

Return the original stdout set by record_original_stdout() or sys.stdout if it’s not set.

test.support.strip_python_strerr(stderr)

Strip the stderr of a Python process from potential debug output emitted by the interpreter. This will typically be run on the result of subprocess.Popen.communicate().

test.support.args_from_interpreter_flags()

Return a list of command line arguments reproducing the current settings in sys.flags and sys.warnoptions.

test.support.optim_args_from_interpreter_flags()

Return a list of command line arguments reproducing the current optimization settings in sys.flags.

test.support.captured_stdin()

test.support.captured_stdout()

test.support.captured_stderr()

A context managers that temporarily replaces the named stream with io.StringIO object.

Example use with output streams:

with captured_stdout() as stdout, captured_stderr() as stderr:
    print("hello")
    print("error", file=sys.stderr)
assert stdout.getvalue() == "hello\n"
assert stderr.getvalue() == "error\n"

Example use with input stream:

with captured_stdin() as stdin:
    stdin.write('hello\n')
    stdin.seek(0)
    # call test code that consumes from sys.stdin
    captured = input()
self.assertEqual(captured, "hello")

test.support.temp_dir(path=None, quiet=False)

A context manager that creates a temporary directory at path and yields the directory.

If path is None, the temporary directory is created using tempfile.mkdtemp(). If quiet is False, the context manager raises an exception on error. Otherwise, if path is specified and cannot be created, only a warning is issued.

test.support.change_cwd(path, quiet=False)

A context manager that temporarily changes the current working directory to path and yields the directory.

If quiet is False, the context manager raises an exception on error. Otherwise, it issues only a warning and keeps the current working directory the same.

test.support.temp_cwd(name='tempcwd', quiet=False)

A context manager that temporarily creates a new directory and changes the current working directory (CWD).

The context manager creates a temporary directory in the current directory with name name before temporarily changing the current working directory. If name is None, the temporary directory is created using tempfile.mkdtemp().

If quiet is False and it is not possible to create or change the CWD, an error is raised. Otherwise, only a warning is raised and the original CWD is used.

test.support.temp_umask(umask)

A context manager that temporarily sets the process umask.

test.support.transient_internet(resource_name, *, timeout=30.0, errnos=())

A context manager that raises ResourceDenied when various issues with the internet connection manifest themselves as exceptions.

test.support.disable_faulthandler()

A context manager that replaces sys.stderr with sys.__stderr__.

test.support.gc_collect()

Force as many objects as possible to be collected. This is needed because timely deallocation is not guaranteed by the garbage collector. This means that __del__ methods may be called later than expected and weakrefs may remain alive for longer than expected.

test.support.disable_gc()

A context manager that disables the garbage collector upon entry and reenables it upon exit.

test.support.swap_attr(obj, attr, new_val)

Context manager to swap out an attribute with a new object.

Usage:

with swap_attr(obj, "attr", 5):
    ...

This will set obj.attr to 5 for the duration of the with block, restoring the old value at the end of the block. If attr doesn’t exist on obj, it will be created and then deleted at the end of the block.

The old value (or None if it doesn’t exist) will be assigned to the target of the “as” clause, if there is one.

test.support.swap_item(obj, attr, new_val)

Context manager to swap out an item with a new object.

Usage:

with swap_item(obj, "item", 5):
    ...

This will set obj["item"] to 5 for the duration of the with block, restoring the old value at the end of the block. If item doesn’t exist on obj, it will be created and then deleted at the end of the block.

The old value (or None if it doesn’t exist) will be assigned to the target of the “as” clause, if there is one.

test.support.wait_threads_exit(timeout=60.0)

Context manager to wait until all threads created in the with statement exit.

test.support.start_threads(threads, unlock=None)

Context manager to start threads. It attempts to join the threads upon exit.

test.support.calcobjsize(fmt)

Return struct.calcsize() for nP{fmt}0n or, if gettotalrefcount exists, 2PnP{fmt}0P.

test.support.calcvobjsize(fmt)

Return struct.calcsize() for nPn{fmt}0n or, if gettotalrefcount exists, 2PnPn{fmt}0P.

test.support.checksizeof(test, o, size)

For testcase test, assert that the sys.getsizeof for o plus the GC header size equals size.

test.support.can_symlink()

Return True if the OS supports symbolic links, False otherwise.

test.support.can_xattr()

Return True if the OS supports xattr, False otherwise.

@test.support.skip_unless_symlink

A decorator for running tests that require support for symbolic links.

@test.support.skip_unless_xattr

A decorator for running tests that require support for xattr.

@test.support.skip_unless_bind_unix_socket

A decorator for running tests that require a functional bind() for Unix sockets.

@test.support.anticipate_failure(condition)

A decorator to conditionally mark tests with unittest.expectedFailure(). Any use of this decorator should have an associated comment identifying the relevant tracker issue.

@test.support.run_with_locale(catstr, *locales)

A decorator for running a function in a different locale, correctly resetting it after it has finished. catstr is the locale category as a string (for example "LC_ALL"). The locales passed will be tried sequentially, and the first valid locale will be used.

@test.support.run_with_tz(tz)

A decorator for running a function in a specific timezone, correctly resetting it after it has finished.

@test.support.requires_freebsd_version(*min_version)

Decorator for the minimum version when running test on FreeBSD. If the FreeBSD version is less than the minimum, raise unittest.SkipTest.

@test.support.requires_linux_version(*min_version)

Decorator for the minimum version when running test on Linux. If the Linux version is less than the minimum, raise unittest.SkipTest.

@test.support.requires_mac_version(*min_version)

Decorator for the minimum version when running test on Mac OS X. If the MAC OS X version is less than the minimum, raise unittest.SkipTest.

@test.support.requires_IEEE_754

Decorator for skipping tests on non-IEEE 754 platforms.

@test.support.requires_zlib

Decorator for skipping tests if zlib doesn’t exist.

@test.support.requires_gzip

Decorator for skipping tests if gzip doesn’t exist.

@test.support.requires_bz2

Decorator for skipping tests if bz2 doesn’t exist.

@test.support.requires_lzma

Decorator for skipping tests if lzma doesn’t exist.

@test.support.requires_resource(resource)

Decorator for skipping tests if resource is not available.

@test.support.requires_docstrings

Decorator for only running the test if HAVE_DOCSTRINGS.

@test.support.cpython_only(test)

Decorator for tests only applicable to CPython.

@test.support.impl_detail(msg=None, **guards)

Decorator for invoking check_impl_detail() on guards. If that returns False, then uses msg as the reason for skipping the test.

@test.support.no_tracing(func)

Decorator to temporarily turn off tracing for the duration of the test.

@test.support.refcount_test(test)

Decorator for tests which involve reference counting. The decorator does not run the test if it is not run by CPython. Any trace function is unset for the duration of the test to prevent unexpected refcounts caused by the trace function.

@test.support.reap_threads(func)

Decorator to ensure the threads are cleaned up even if the test fails.

@test.support.bigmemtest(size, memuse, dry_run=True)

Decorator for bigmem tests.

size is a requested size for the test (in arbitrary, test-interpreted units.) memuse is the number of bytes per unit for the test, or a good estimate of it. For example, a test that needs two byte buffers, of 4 GiB each, could be decorated with @bigmemtest(size=_4G, memuse=2).

The size argument is normally passed to the decorated test method as an extra argument. If dry_run is True, the value passed to the test method may be less than the requested value. If dry_run is False, it means the test doesn’t support dummy runs when -M is not specified.

@test.support.bigaddrspacetest(f)

Decorator for tests that fill the address space. f is the function to wrap.

test.support.make_bad_fd()

Create an invalid file descriptor by opening and closing a temporary file, and returning its descriptor.

test.support.check_syntax_error(testcase, statement, errtext='', *, lineno=None, offset=None)

Test for syntax errors in statement by attempting to compile statement. testcase is the unittest instance for the test. errtext is the text of the error raised by SyntaxError. If lineno is not None, compares to the line of the SyntaxError. If offset is not None, compares to the offset of the SyntaxError.

test.support.open_urlresource(url, *args, **kw)

Open url. If open fails, raises TestFailed.

test.support.import_module(name, deprecated=False, *, required_on())

This function imports and returns the named module. Unlike a normal import, this function raises unittest.SkipTest if the module cannot be imported.

Module and package deprecation messages are suppressed during this import if deprecated is True. If a module is required on a platform but optional for others, set required_on to an iterable of platform prefixes which will be compared against sys.platform.

버전 3.1에 추가.

test.support.import_fresh_module(name, fresh=(), blocked=(), deprecated=False)

This function imports and returns a fresh copy of the named Python module by removing the named module from sys.modules before doing the import. Note that unlike reload(), the original module is not affected by this operation.

fresh is an iterable of additional module names that are also removed from the sys.modules cache before doing the import.

blocked is an iterable of module names that are replaced with None in the module cache during the import to ensure that attempts to import them raise ImportError.

The named module and any modules named in the fresh and blocked parameters are saved before starting the import and then reinserted into sys.modules when the fresh import is complete.

Module and package deprecation messages are suppressed during this import if deprecated is True.

This function will raise ImportError if the named module cannot be imported.

Example use:

# Get copies of the warnings module for testing without affecting the
# version being used by the rest of the test suite. One copy uses the
# C implementation, the other is forced to use the pure Python fallback
# implementation
py_warnings = import_fresh_module('warnings', blocked=['_warnings'])
c_warnings = import_fresh_module('warnings', fresh=['_warnings'])

버전 3.1에 추가.

test.support.modules_setup()

Return a copy of sys.modules.

test.support.modules_cleanup(oldmodules)

Remove modules except for oldmodules and encodings in order to preserve internal cache.

test.support.threading_setup()

Return current thread count and copy of dangling threads.

test.support.threading_cleanup(*original_values)

Cleanup up threads not specified in original_values. Designed to emit a warning if a test leaves running threads in the background.

test.support.join_thread(thread, timeout=30.0)

Join a thread within timeout. Raise an AssertionError if thread is still alive after timeout seconds.

test.support.reap_children()

Use this at the end of test_main whenever sub-processes are started. This will help ensure that no extra children (zombies) stick around to hog resources and create problems when looking for refleaks.

test.support.get_attribute(obj, name)

Get an attribute, raising unittest.SkipTest if AttributeError is raised.

test.support.bind_port(sock, host=HOST)

Bind the socket to a free port and return the port number. Relies on ephemeral ports in order to ensure we are using an unbound port. This is important as many tests may be running simultaneously, especially in a buildbot environment. This method raises an exception if the sock.family is AF_INET and sock.type is SOCK_STREAM, and the socket has SO_REUSEADDR or SO_REUSEPORT set on it. Tests should never set these socket options for TCP/IP sockets. The only case for setting these options is testing multicasting via multiple UDP sockets.

Additionally, if the SO_EXCLUSIVEADDRUSE socket option is available (i.e. on Windows), it will be set on the socket. This will prevent anyone else from binding to our host/port for the duration of the test.

test.support.bind_unix_socket(sock, addr)

Bind a unix socket, raising unittest.SkipTest if PermissionError is raised.

test.support.find_unused_port(family=socket.AF_INET, socktype=socket.SOCK_STREAM)

Returns an unused port that should be suitable for binding. This is achieved by creating a temporary socket with the same family and type as the sock parameter (default is AF_INET, SOCK_STREAM), and binding it to the specified host address (defaults to 0.0.0.0) with the port set to 0, eliciting an unused ephemeral port from the OS. The temporary socket is then closed and deleted, and the ephemeral port is returned.

Either this method or bind_port() should be used for any tests where a server socket needs to be bound to a particular port for the duration of the test. Which one to use depends on whether the calling code is creating a Python socket, or if an unused port needs to be provided in a constructor or passed to an external program (i.e. the -accept argument to openssl’s s_server mode). Always prefer bind_port() over find_unused_port() where possible. Using a hard coded port is discouraged since it can make multiple instances of the test impossible to run simultaneously, which is a problem for buildbots.

test.support.load_package_tests(pkg_dir, loader, standard_tests, pattern)

Generic implementation of the unittest load_tests protocol for use in test packages. pkg_dir is the root directory of the package; loader, standard_tests, and pattern are the arguments expected by load_tests. In simple cases, the test package’s __init__.py can be the following:

import os
from test.support import load_package_tests

def load_tests(*args):
    return load_package_tests(os.path.dirname(__file__), *args)

test.support.fs_is_case_insensitive(directory)

Return True if the file system for directory is case-insensitive.

test.support.detect_api_mismatch(ref_api, other_api, *, ignore=())

Returns the set of attributes, functions or methods of ref_api not found on other_api, except for a defined list of items to be ignored in this check specified in ignore.

By default this skips private attributes beginning with ‘_’ but includes all magic methods, i.e. those starting and ending in ‘__’.

버전 3.5에 추가.

test.support.patch(test_instance, object_to_patch, attr_name, new_value)

Override object_to_patch.attr_name with new_value. Also add cleanup procedure to test_instance to restore object_to_patch for attr_name. The attr_name should be a valid attribute for object_to_patch.

test.support.run_in_subinterp(code)

Run code in subinterpreter. Raise unittest.SkipTest if tracemalloc is enabled.

test.support.check_free_after_iterating(test, iter, cls, args=())

Assert that iter is deallocated after iterating.

test.support.missing_compiler_executable(cmd_names=[])

Check for the existence of the compiler executables whose names are listed in cmd_names or all the compiler executables when cmd_names is empty and return the first missing executable or None when none is found missing.

test.support.check__all__(test_case, module, name_of_module=None, extra=(), blacklist=())

Assert that the __all__ variable of module contains all public names.

The module’s public names (its API) are detected automatically based on whether they match the public name convention and were defined in module.

The name_of_module argument can specify (as a string or tuple thereof) what module(s) an API could be defined in order to be detected as a public API. One case for this is when module imports part of its public API from other modules, possibly a C backend (like csv and its _csv).

The extra argument can be a set of names that wouldn’t otherwise be automatically detected as “public”, like objects without a proper __module__ attribute. If provided, it will be added to the automatically detected ones.

The blacklist argument can be a set of names that must not be treated as part of the public API even though their names indicate otherwise.

Example use:

import bar
import foo
import unittest
from test import support

class MiscTestCase(unittest.TestCase):
    def test__all__(self):
        support.check__all__(self, foo)

class OtherTestCase(unittest.TestCase):
    def test__all__(self):
        extra = {'BAR_CONST', 'FOO_CONST'}
        blacklist = {'baz'}  # Undocumented name.
        # bar imports part of its API from _bar.
        support.check__all__(self, bar, ('bar', '_bar'),
                             extra=extra, blacklist=blacklist)

버전 3.6에 추가.

test.support.adjust_int_max_str_digits(max_digits)

This function returns a context manager that will change the global sys.set_int_max_str_digits() setting for the duration of the context to allow execution of test code that needs a different limit on the number of digits when converting between an integer and string.

버전 3.7.14에 추가.

The test.support module defines the following classes:

class test.support.TransientResource(exc, **kwargs)

Instances are a context manager that raises ResourceDenied if the specified exception type is raised. Any keyword arguments are treated as attribute/value pairs to be compared against any exception raised within the with statement. Only if all pairs match properly against attributes on the exception is ResourceDenied raised.

class test.support.EnvironmentVarGuard

Class used to temporarily set or unset environment variables. Instances can be used as a context manager and have a complete dictionary interface for querying/modifying the underlying os.environ. After exit from the context manager all changes to environment variables done through this instance will be rolled back.

버전 3.1에서 변경: Added dictionary interface.

EnvironmentVarGuard.set(envvar, value)

Temporarily set the environment variable envvar to the value of value.

EnvironmentVarGuard.unset(envvar)

Temporarily unset the environment variable envvar.

class test.support.SuppressCrashReport

A context manager used to try to prevent crash dialog popups on tests that are expected to crash a subprocess.

On Windows, it disables Windows Error Reporting dialogs using SetErrorMode [https://msdn.microsoft.com/en-us/library/windows/desktop/ms680621.aspx].

On UNIX, resource.setrlimit() is used to set resource.RLIMIT_CORE’s soft limit to 0 to prevent coredump file creation.

On both platforms, the old value is restored by __exit__().

class test.support.CleanImport(*module_names)

A context manager to force import to return a new module reference. This is useful for testing module-level behaviors, such as the emission of a DeprecationWarning on import. Example usage:

with CleanImport('foo'):
    importlib.import_module('foo')  # New reference.

class test.support.DirsOnSysPath(*paths)

A context manager to temporarily add directories to sys.path.

This makes a copy of sys.path, appends any directories given as positional arguments, then reverts sys.path to the copied settings when the context ends.

Note that all sys.path modifications in the body of the context manager, including replacement of the object, will be reverted at the end of the block.

class test.support.SaveSignals

Class to save and restore signal handlers registered by the Python signal handler.

class test.support.Matcher

matches(self, d, **kwargs)

Try to match a single dict with the supplied arguments.

match_value(self, k, dv, v)

Try to match a single stored value (dv) with a supplied value (v).

class test.support.WarningsRecorder

Class used to record warnings for unit tests. See documentation of check_warnings() above for more details.

class test.support.BasicTestRunner

run(test)

Run test and return the result.

class test.support.TestHandler(logging.handlers.BufferingHandler)

Class for logging support.

class test.support.FakePath(path)

Simple path-like object. It implements the __fspath__() method which just returns the path argument. If path is an exception, it will be raised in __fspath__().

test.support.script_helper — Utilities for the Python execution tests

The test.support.script_helper module provides support for Python’s script execution tests.

test.support.script_helper.interpreter_requires_environment()

Return True if sys.executable interpreter requires environment variables in order to be able to run at all.

This is designed to be used with @unittest.skipIf() to annotate tests that need to use an assert_python*() function to launch an isolated mode (-I) or no environment mode (-E) sub-interpreter process.

A normal build & test does not run into this situation but it can happen when trying to run the standard library test suite from an interpreter that doesn’t have an obvious home with Python’s current home finding logic.

Setting PYTHONHOME is one way to get most of the testsuite to run in that situation. PYTHONPATH or PYTHONUSERSITE are other common environment variables that might impact whether or not the interpreter can start.

test.support.script_helper.run_python_until_end(*args, **env_vars)

Set up the environment based on env_vars for running the interpreter in a subprocess. The values can include __isolated, __cleanenv, __cwd, and TERM.

test.support.script_helper.assert_python_ok(*args, **env_vars)

Assert that running the interpreter with args and optional environment variables env_vars succeeds (rc == 0) and return a (return code, stdout, stderr) tuple.

If the __cleanenv keyword is set, env_vars is used as a fresh environment.

Python is started in isolated mode (command line option -I), except if the __isolated keyword is set to False.

test.support.script_helper.assert_python_failure(*args, **env_vars)

Assert that running the interpreter with args and optional environment variables env_vars fails (rc != 0) and return a (return code, stdout, stderr) tuple.

See assert_python_ok() for more options.

test.support.script_helper.spawn_python(*args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, **kw)

Run a Python subprocess with the given arguments.

kw is extra keyword args to pass to subprocess.Popen(). Returns a subprocess.Popen object.

test.support.script_helper.kill_python(p)

Run the given subprocess.Popen process until completion and return stdout.

test.support.script_helper.make_script(script_dir, script_basename, source, omit_suffix=False)

Create script containing source in path script_dir and script_basename. If omit_suffix is False, append .py to the name. Return the full script path.

test.support.script_helper.make_zip_script(zip_dir, zip_basename, script_name, name_in_zip=None)

Create zip file at zip_dir and zip_basename with extension zip which contains the files in script_name. name_in_zip is the archive name. Return a tuple containing (full path, full path of archive name).

test.support.script_helper.make_pkg(pkg_dir, init_source='')

Create a directory named pkg_dir containing an __init__ file with init_source as its contents.

test.support.script_helper.make_zip_pkg(zip_dir, zip_basename, pkg_name, script_basename, source, depth=1, compiled=False)

Create a zip package directory with a path of zip_dir and zip_basename containing an empty __init__ file and a file script_basename containing the source. If compiled is True, both source files will be compiled and added to the zip package. Return a tuple of the full zip path and the archive name for the zip file.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

개발 도구 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

|

디버깅과 프로파일링

이 라이브러리들은 파이썬 개발을 돕습니다: 디버거를 사용하면 코드를 단계별로 실행하고, 스택 프레임을 분석하고, 중단 점을 설정할 수 있으며, 프로파일러는 코드를 실행하고, 프로그램의 병목 지점을 식별할 수 있도록 실행 시간을 자세하게 분석합니다.

bdb — Debugger framework

faulthandler — 파이썬 트레이스백 덤프

트레이스백 덤프하기

결함 처리기 상태

시간 초과 후에 트레이스백 덤프하기

사용자 시그널에 트레이스백 덤프하기

파일 기술자 관련 문제

예제

pdb — 파이썬 디버거

디버거 명령들

The Python Profilers

Introduction to the profilers

Instant User’s Manual

profile and cProfile Module Reference

The Stats Class

What Is Deterministic Profiling?

Limitations

Calibration

Using a custom timer

timeit — 작은 코드 조각의 실행 시간 측정

기본 예제

파이썬 인터페이스

명령 줄 인터페이스

예제

trace — 파이썬 문장 실행 추적

명령 줄 사용법

주요 옵션

수정자

필터

프로그래밍 인터페이스

tracemalloc — Trace memory allocations

Examples

Display the top 10

Compute differences

Get the traceback of a memory block

Pretty top

API

Functions

DomainFilter

Filter

Frame

Snapshot

Statistic

StatisticDiff

Trace

Traceback

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

디버깅과 프로파일링 »

|

bdb — Debugger framework

Source code: Lib/bdb.py [https://github.com/python/cpython/tree/3.7/Lib/bdb.py]

The bdb module handles basic debugger functions, like setting breakpoints or managing execution via the debugger.

The following exception is defined:

exception bdb.BdbQuit

Exception raised by the Bdb class for quitting the debugger.

The bdb module also defines two classes:

class bdb.Breakpoint(self, file, line, temporary=0, cond=None, funcname=None)

This class implements temporary breakpoints, ignore counts, disabling and (re-)enabling, and conditionals.

Breakpoints are indexed by number through a list called bpbynumber and by (file, line) pairs through bplist. The former points to a single instance of class Breakpoint. The latter points to a list of such instances since there may be more than one breakpoint per line.

When creating a breakpoint, its associated filename should be in canonical form. If a funcname is defined, a breakpoint hit will be counted when the first line of that function is executed. A conditional breakpoint always counts a hit.

Breakpoint instances have the following methods:

deleteMe()

Delete the breakpoint from the list associated to a file/line. If it is the last breakpoint in that position, it also deletes the entry for the file/line.

enable()

Mark the breakpoint as enabled.

disable()

Mark the breakpoint as disabled.

bpformat()

Return a string with all the information about the breakpoint, nicely formatted:

The breakpoint number.

If it is temporary or not.

Its file,line position.

The condition that causes a break.

If it must be ignored the next N times.

The breakpoint hit count.

버전 3.2에 추가.

bpprint(out=None)

Print the output of bpformat() to the file out, or if it is None, to standard output.

class bdb.Bdb(skip=None)

The Bdb class acts as a generic Python debugger base class.

This class takes care of the details of the trace facility; a derived class should implement user interaction. The standard debugger class (pdb.Pdb) is an example.

The skip argument, if given, must be an iterable of glob-style module name patterns. The debugger will not step into frames that originate in a module that matches one of these patterns. Whether a frame is considered to originate in a certain module is determined by the __name__ in the frame globals.

버전 3.1에 추가: The skip argument.

The following methods of Bdb normally don’t need to be overridden.

canonic(filename)

Auxiliary method for getting a filename in a canonical form, that is, as a case-normalized (on case-insensitive filesystems) absolute path, stripped of surrounding angle brackets.

reset()

Set the botframe, stopframe, returnframe and quitting attributes with values ready to start debugging.

trace_dispatch(frame, event, arg)

This function is installed as the trace function of debugged frames. Its return value is the new trace function (in most cases, that is, itself).

The default implementation decides how to dispatch a frame, depending on the type of event (passed as a string) that is about to be executed. event can be one of the following:

"line": A new line of code is going to be executed.

"call": A function is about to be called, or another code block entered.

"return": A function or other code block is about to return.

"exception": An exception has occurred.

"c_call": A C function is about to be called.

"c_return": A C function has returned.

"c_exception": A C function has raised an exception.

For the Python events, specialized functions (see below) are called. For the C events, no action is taken.

The arg parameter depends on the previous event.

See the documentation for sys.settrace() for more information on the trace function. For more information on code and frame objects, refer to 표준형 계층.

dispatch_line(frame)

If the debugger should stop on the current line, invoke the user_line() method (which should be overridden in subclasses). Raise a BdbQuit exception if the Bdb.quitting flag is set (which can be set from user_line()). Return a reference to the trace_dispatch() method for further tracing in that scope.

dispatch_call(frame, arg)

If the debugger should stop on this function call, invoke the user_call() method (which should be overridden in subclasses). Raise a BdbQuit exception if the Bdb.quitting flag is set (which can be set from user_call()). Return a reference to the trace_dispatch() method for further tracing in that scope.

dispatch_return(frame, arg)

If the debugger should stop on this function return, invoke the user_return() method (which should be overridden in subclasses). Raise a BdbQuit exception if the Bdb.quitting flag is set (which can be set from user_return()). Return a reference to the trace_dispatch() method for further tracing in that scope.

dispatch_exception(frame, arg)

If the debugger should stop at this exception, invokes the user_exception() method (which should be overridden in subclasses). Raise a BdbQuit exception if the Bdb.quitting flag is set (which can be set from user_exception()). Return a reference to the trace_dispatch() method for further tracing in that scope.

Normally derived classes don’t override the following methods, but they may if they want to redefine the definition of stopping and breakpoints.

stop_here(frame)

This method checks if the frame is somewhere below botframe in the call stack. botframe is the frame in which debugging started.

break_here(frame)

This method checks if there is a breakpoint in the filename and line belonging to frame or, at least, in the current function. If the breakpoint is a temporary one, this method deletes it.

break_anywhere(frame)

This method checks if there is a breakpoint in the filename of the current frame.

Derived classes should override these methods to gain control over debugger operation.

user_call(frame, argument_list)

This method is called from dispatch_call() when there is the possibility that a break might be necessary anywhere inside the called function.

user_line(frame)

This method is called from dispatch_line() when either stop_here() or break_here() yields True.

user_return(frame, return_value)

This method is called from dispatch_return() when stop_here() yields True.

user_exception(frame, exc_info)

This method is called from dispatch_exception() when stop_here() yields True.

do_clear(arg)

Handle how a breakpoint must be removed when it is a temporary one.

This method must be implemented by derived classes.

Derived classes and clients can call the following methods to affect the stepping state.

set_step()

Stop after one line of code.

set_next(frame)

Stop on the next line in or below the given frame.

set_return(frame)

Stop when returning from the given frame.

set_until(frame)

Stop when the line with the line no greater than the current one is reached or when returning from current frame.

set_trace([frame])

Start debugging from frame. If frame is not specified, debugging starts from caller’s frame.

set_continue()

Stop only at breakpoints or when finished. If there are no breakpoints, set the system trace function to None.

set_quit()

Set the quitting attribute to True. This raises BdbQuit in the next call to one of the dispatch_*() methods.

Derived classes and clients can call the following methods to manipulate breakpoints. These methods return a string containing an error message if something went wrong, or None if all is well.

set_break(filename, lineno, temporary=0, cond, funcname)

Set a new breakpoint. If the lineno line doesn’t exist for the filename passed as argument, return an error message. The filename should be in canonical form, as described in the canonic() method.

clear_break(filename, lineno)

Delete the breakpoints in filename and lineno. If none were set, an error message is returned.

clear_bpbynumber(arg)

Delete the breakpoint which has the index arg in the Breakpoint.bpbynumber. If arg is not numeric or out of range, return an error message.

clear_all_file_breaks(filename)

Delete all breakpoints in filename. If none were set, an error message is returned.

clear_all_breaks()

Delete all existing breakpoints.

get_bpbynumber(arg)

Return a breakpoint specified by the given number. If arg is a string, it will be converted to a number. If arg is a non-numeric string, if the given breakpoint never existed or has been deleted, a ValueError is raised.

버전 3.2에 추가.

get_break(filename, lineno)

Check if there is a breakpoint for lineno of filename.

get_breaks(filename, lineno)

Return all breakpoints for lineno in filename, or an empty list if none are set.

get_file_breaks(filename)

Return all breakpoints in filename, or an empty list if none are set.

get_all_breaks()

Return all breakpoints that are set.

Derived classes and clients can call the following methods to get a data structure representing a stack trace.

get_stack(f, t)

Get a list of records for a frame and all higher (calling) and lower frames, and the size of the higher part.

format_stack_entry(frame_lineno, lprefix=': ')

Return a string with information about a stack entry, identified by a (frame, lineno) tuple:

The canonical form of the filename which contains the frame.

The function name, or "<lambda>".

The input arguments.

The return value.

The line of code (if it exists).

The following two methods can be called by clients to use a debugger to debug a statement, given as a string.

run(cmd, globals=None, locals=None)

Debug a statement executed via the exec() function. globals defaults to __main__.__dict__, locals defaults to globals.

runeval(expr, globals=None, locals=None)

Debug an expression executed via the eval() function. globals and locals have the same meaning as in run().

runctx(cmd, globals, locals)

For backwards compatibility. Calls the run() method.

runcall(func, *args, **kwds)

Debug a single function call, and return its result.

Finally, the module defines the following functions:

bdb.checkfuncname(b, frame)

Check whether we should break here, depending on the way the breakpoint b was set.

If it was set via line number, it checks if b.line is the same as the one in the frame also passed as argument. If the breakpoint was set via function name, we have to check we are in the right frame (the right function) and if we are in its first executable line.

bdb.effective(file, line, frame)

Determine if there is an effective (active) breakpoint at this line of code. Return a tuple of the breakpoint and a boolean that indicates if it is ok to delete a temporary breakpoint. Return (None, None) if there is no matching breakpoint.

bdb.set_trace()

Start debugging with a Bdb instance from caller’s frame.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

디버깅과 프로파일링 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

디버깅과 프로파일링 »

|

faulthandler — 파이썬 트레이스백 덤프

버전 3.3에 추가.

이 모듈은 결함(fault) 시, 시간 초과 후 또는 사용자 시그널에 파이썬 트레이스백을 명시적으로 덤프하는 함수를 포함합니다. SIGSEGV, SIGFPE, SIGABRT, SIGBUS 및 SIGILL 시그널에 대한 결함 처리기를 설치하려면 faulthandler.enable()를 호출하십시오. PYTHONFAULTHANDLER 환경 변수를 설정하거나 -X faulthandler 명령 줄 옵션을 사용하여 시작할 때 활성화할 수도 있습니다.

결함 처리기는 Apport나 윈도우 결함 처리기(Windows fault handler)와 같은 시스템 결함 처리기와 호환됩니다. 이 모듈은 sigaltstack() 함수를 사용할 수 있으면 시그널 처리기에 대체 스택을 사용합니다. 이것은 스택 오버플로에서조차 트레이스백을 덤프할 수 있도록 합니다.

결함 처리기는 치명적일 때 호출되므로 시그널 안전한 함수만 사용할 수 있습니다 (예를 들어, 힙에 메모리를 할당할 수 없습니다). 이 제한 때문에 일반적인 파이썬 트레이스백에 비해 트레이스백 덤프는 최소화됩니다:

ASCII만 지원됩니다. 인코딩 시 backslashreplace 에러 처리기가 사용됩니다.

각 문자열은 500자로 제한됩니다.

파일명, 함수 이름 및 줄 번호만 표시됩니다. (소스 코드 없음)

100프레임과 100스레드로 제한됩니다.

순서가 뒤집힙니다: 가장 최근의 호출이 먼저 표시됩니다.

기본적으로, 파이썬 트레이스백은 sys.stderr에 기록됩니다. 트레이스백을 보려면, 응용 프로그램이 터미널에서 실행되어야 합니다. 로그 파일을 faulthandler.enable()로 전달할 수도 있습니다.

모듈은 C로 구현되어 있으므로, 충돌 시나 파이썬이 교착 상태에 빠질 때 트레이스백을 덤프할 수 있습니다.

트레이스백 덤프하기

faulthandler.dump_traceback(file=sys.stderr, all_threads=True)

모든 스레드의 트레이스백을 file로 덤프합니다. all_threads가 False면, 현재 스레드만 덤프합니다.

버전 3.5에서 변경: 이 함수에 파일 기술자를 전달하는 지원이 추가되었습니다.

결함 처리기 상태

faulthandler.enable(file=sys.stderr, all_threads=True)

결함 처리기를 활성화합니다: SIGSEGV, SIGFPE, SIGABRT, SIGBUS 및 SIGILL 시그널에 대한 처리기를 설치하여 파이썬 트레이스백을 덤프합니다. all_threads가 True면 실행 중인 모든 스레드에 대한 트레이스백을 생성합니다. 그렇지 않으면, 현재 스레드만 덤프합니다.

file은 결함 처리기가 비활성화될 때까지 열려 있어야 합니다: 파일 기술자 관련 문제를 참조하십시오.

버전 3.5에서 변경: 이 함수에 파일 기술자를 전달하는 지원이 추가되었습니다.

버전 3.6에서 변경: 윈도우에서는, 윈도우 예외(Windows exception) 처리기도 설치됩니다.

faulthandler.disable()

결함 처리기를 비활성화합니다: enable()로 설치된 시그널 처리기를 제거합니다.

faulthandler.is_enabled()

결함 처리기가 활성화되었는지 검사합니다.

시간 초과 후에 트레이스백 덤프하기

faulthandler.dump_traceback_later(timeout, repeat=False, file=sys.stderr, exit=False)

timeout 초의 시간제한 후, 또는 repeat가 True면 매 timeout 초마다, 모든 스레드의 트레이스백을 덤프합니다. exit가 True면, 트레이스백을 덤프한 후 status=1 로 _exit()를 호출합니다. (_exit()가 프로세스를 즉시 종료함에 유의하십시오. 파일 버퍼를 플러시 하는 것과 같은 정리 작업을 수행하지 않습니다.) 함수가 두 번 호출되면, 새 호출은 이전 매개 변수를 대체하고 시간제한을 다시 설정합니다. 타이머는 1초 미만의 해상도를 갖습니다.

file은 트레이스백이 덤프 되거나 cancel_dump_traceback_later()가 호출될 때까지 열려 있어야 합니다: 파일 기술자 관련 문제를 참조하십시오.

This function is implemented using a watchdog thread.

버전 3.7에서 변경: This function is now always available.

버전 3.5에서 변경: 이 함수에 파일 기술자를 전달하는 지원이 추가되었습니다.

faulthandler.cancel_dump_traceback_later()

마지막 dump_traceback_later() 호출을 취소합니다.

사용자 시그널에 트레이스백 덤프하기

faulthandler.register(signum, file=sys.stderr, all_threads=True, chain=False)

사용자 시그널을 등록합니다: signum 시그널에 대한 처리기를 설치해서, 모든 스레드, 또는 all_threads가 False면 현재 스레드의, 트레이스백을 file로 덤프합니다. chain이 True면 이전 처리기를 호출합니다.

file은 시그널이 unregister()로 등록 해지 될 때까지 열려 있어야 합니다: 파일 기술자 관련 문제를 참조하십시오.

윈도우에서는 사용할 수 없습니다.

버전 3.5에서 변경: 이 함수에 파일 기술자를 전달하는 지원이 추가되었습니다.

faulthandler.unregister(signum)

사용자 시그널을 등록 해지합니다: register()로 설치된 signum 시그널 처리기를 제거합니다. 시그널이 등록되었으면 True를 반환하고, 그렇지 않으면 False를 반환합니다.

윈도우에서는 사용할 수 없습니다.

파일 기술자 관련 문제

enable(), dump_traceback_later() 및 register()는 file 인자의 파일 기술자를 유지합니다. 파일이 닫히고 파일 기술자가 새 파일에 의해 다시 사용되거나, os.dup2()가 파일 기술자를 바꾸는 데 사용되면, 트레이스백이 다른 파일에 기록됩니다. 파일을 바꿀 때마다 이 함수들을 다시 호출하십시오.

예제

리눅스에서 결함 처리기를 활성화하거나 그렇지 않았을 때의 세그멘테이션 결함 예제:

$ python3 -c "import ctypes; ctypes.string_at(0)"
Segmentation fault

$ python3 -q -X faulthandler
>>> import ctypes
>>> ctypes.string_at(0)
Fatal Python error: Segmentation fault

Current thread 0x00007fb899f39700 (most recent call first):
  File "/home/python/cpython/Lib/ctypes/__init__.py", line 486 in string_at
  File "<stdin>", line 1 in <module>
Segmentation fault

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

디버깅과 프로파일링 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

디버깅과 프로파일링 »

|

pdb — 파이썬 디버거

소스 코드: Lib/pdb.py [https://github.com/python/cpython/tree/3.7/Lib/pdb.py]

pdb 모듈은 파이썬 프로그램을 위한 대화형 소스 코드 디버거를 정의합니다. 소스 라인 단계의 중단점(breakpoint) 및 단계 실행(single stepping) 설정, 스택 프레임 검사, 소스 코드 목록, 그리고 모든 스택 프레임의 컨텍스트에서 임의의 파이썬 코드 평가를 지원합니다. 또한 포스트-모템(post-mortem) 디버깅을 지원하며, 프로그램 제어 하에서도 호출될 수 있습니다.

이 디버거는 확장이 가능합니다 – 디버거는 실제로 Pdb 클래스로 정의됩니다. 현재 문서화되어 있진 않지만, 소스를 읽어보시면 쉽게 이해하실 수 있습니다. 확장 인터페이스는 bdb 와 cmd 모듈을 활용합니다.

디버거의 프롬프트는 (Pdb) 입니다. 디버거 제어하에 프로그램을 실행하는 일반적인 사용법은 다음과 같습니다:

>>> import pdb
>>> import mymodule
>>> pdb.run('mymodule.test()')
> <string>(0)?()
(Pdb) continue
> <string>(1)?()
(Pdb) continue
NameError: 'spam'
> <string>(1)?()
(Pdb)

버전 3.3에서 변경: readline 모듈을 통한 탭-완성은 명령과 명령 인자에 사용할 수 있습니다, 예를 들면, 현재 전역 및 지역 이름들은 p 명령의 인자로 제공됩니다.

pdb.py 는 다른 스크립트를 디버그하기 위한 스크립트로 호출될 수 있습니다. 예를 들면:

python3 -m pdb myscript.py

스크립트로 호출하는 경우, 디버깅 중인 프로그램이 비정상적으로 종료되면 pdb는 자동으로 포스트-모템(post-mortem) 디버깅을 시작합니다. 포스트-모템 디버깅이 끝나면 (또는 프로그램이 정상적으로 종료되면), pdb는 프로그램을 재시작합니다. 자동 재시작은 중단점과 같은 pdb의 상태를 유지하고 대부분의 경우 프로그램 종료 시 디버거를 종료하는 것보다 유용합니다.

버전 3.2에 추가: pdb.py 는 이제 .pdbrc 파일에 주어진 것처럼 명령을 실행하는 -c 옵션을 받을 수 있습니다, 디버거 명령들 을 확인해보세요.

버전 3.7에 추가: pdb.py 는 이제 python3 -m과 비슷한 모듈을 실행하는 -m 옵션을 받을 수 있습니다. 스크립트와 마찬가지로, 디버거는 모듈의 첫 번째 줄 바로 전에 실행을 일시정지합니다.

실행 중인 프로그램에서 디버거로 진입하는 일반적인 사용법은:

import pdb; pdb.set_trace()

위 코드를 디버거로 진입하고 싶은 구간에 추가하면 됩니다. 그런 다음 이 문장 뒤에 오는 코드를 단계별로 실행하고, continue 명령을 사용하여 디버거 없이 프로그램을 계속 실행할 수 있습니다.

버전 3.7에 추가: 내장 breakpoint()가, 기본값으로 호출될 때는, import pdb; pdb.set_trace()를 대신해서 사용할 수 있습니다.

에러가 발생하는 프로그램을 검사하는 일반적인 사용법은 다음과 같습니다:

>>> import pdb
>>> import mymodule
>>> mymodule.test()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "./mymodule.py", line 4, in test
    test2()
  File "./mymodule.py", line 3, in test2
    print(spam)
NameError: spam
>>> pdb.pm()
> ./mymodule.py(3)test2()
-> print(spam)
(Pdb)

이 모듈은 다음과 같은 함수를 정의합니다; 각 함수는 조금 다른 방식으로 디버거로 진입합니다:

pdb.run(statement, globals=None, locals=None)

디버거 제어하에 statement (주어진 문자열 또는 코드 객체)를 실행합니다. 코드가 실행하기 전에 디버거 프롬프트가 나타납니다; 중단점을 지정하고 continue를 입력하거나, step 또는 next를 통해 문장을 단계별로 살펴볼 수 있습니다. (이 모든 명령은 아래에 설명되어 있습니다.) 선택적 인자 globals 와 locals는 코드가 실행되는 환경을 구체적으로 명시합니다; 기본적으로는 이 모듈의 딕셔너리 __main__ 이 사용됩니다. (내장 함수 exec() 또는 eval() 에 대한 설명 참조.)

pdb.runeval(expression, globals=None, locals=None)

디버거 제어하에 문자열 또는 코드 객체로 주어진 expression을 평가합니다. runeval() 이 반환될 때, 표현식의 값을 반환합니다. 그렇지 않으면 이 함수는 run()과 유사한 함수입니다.

pdb.runcall(function, *args, **kwds)

주어진 인자와 함께 function (문자열이 아닌, 함수 또는 메서드 객체)를 호출합니다. runcall() 이 반환될 때, 함수 호출로 반환된 값을 반환합니다. 디버거 프롬프트는 함수에 진입하자마자 나타납니다.

pdb.set_trace(*, header=None)

호출하는 스택 프레임에서 디버거에 진입합니다. 코드가 디버그 되지 않는 경우 일지라도 (예를 들면, assertion이 실패하는 경우), 프로그램의 특정 지점에 중단점을 하드 코딩할 때 유용하게 사용됩니다. header 값을 주면, 디버깅이 시작되기 바로 전에 그 값이 콘솔에 출력됩니다.

버전 3.7에서 변경: 키워드 전용 인자 header.

pdb.post_mortem(traceback=None)

주어진 traceback 객체의 포스트-모템(post-mortem) 디버깅으로 진입합니다. 만약 traceback이 주어지지 않았다면, 현재 처리되고 있는 하나의 예외를 사용합니다. (기본값을 사용하는 경우 예외는 반드시 처리되고 있어야 합니다.)

pdb.pm()

sys.last_traceback 에서 찾은 traceback 의 포스트-모템(post-mortem) 디버깅으로 진입합니다.

run* 함수와 set_trace()는 Pdb 클래스를 인스턴스 화하고 같은 이름의 메서드를 호출하는 에일리어스(alias) 입니다. 더 많은 기능에 액세스하려면, 아래를 참고하여 직접 하셔야 합니다:

class pdb.Pdb(completekey='tab', stdin=None, stdout=None, skip=None, nosigint=False, readrc=True)

Pdb 는 디버거 클래스입니다.

completekey, stdin 그리고 stdout 인자는 내부 cmd.Cmd 클래스로 전달됩니다; 자세한 설명은 해당 클래스에서 확인할 수 있습니다.

skip 인자가 주어진다면, 반드시 글로브-스타일(glob-style) 모듈 이름 패턴의 이터러블(iterable) 이어야 합니다. 디버거는 이 패턴 중 하나와 일치하는 모듈에서 시작되는 프레임 단계로 들어가지 않습니다. 1

기본적으로, Pdb는 사용자가 continue 명령을 내릴 때, SIGINT 신호(사용자가 콘솔에서 Ctrl-C를 누를 때 전송되는 신호) 에 대한 핸들러를 설정합니다. 사용자는 Ctrl-C를 눌러서 디버거를 벗어날 수 있습니다. 만약 Pdb가 SIGINT 핸들러를 건드리지 않길 원한다면 nosigint 설정을 참으로 변경하면 됩니다.

readrc 인자는 기본적으로 참이고 Pdb가 파일 시스템으로부터 .pdbrc를 불러올지 여부를 제어합니다.

skip으로 추적하기 위한 호출 예시:

import pdb; pdb.Pdb(skip=['django.*']).set_trace()

버전 3.1에 추가: skip 인자.

버전 3.2에 추가: nosigint 인자. 이전에는, Pdb가 SIGINT 핸들러를 설정하지 않았습니다.

버전 3.6에서 변경: readrc 인자.

run(statement, globals=None, locals=None)

runeval(expression, globals=None, locals=None)

runcall(function, *args, **kwds)

set_trace()

위에 설명된 함수에 대한 설명서를 참조하시면 됩니다.

디버거 명령들

디버거가 인식할 수 있는 명령이 아래 나열되어 있습니다. 대부분의 명령은 한두 문자로 단축될 수 있습니다; 예를 들면, h(elp) 는 h 또는 help로 help 명령을 입력할 때 사용할 수 있습니다. (하지만 he, hel, H, Help 또는 HELP는 사용할 수 없습니다.) 인자는 반드시 명령과 공백(스페이스나 탭)으로 분리되어야 합니다. 선택적 인자는 명령 문법에서 대괄호([])로 묶여있습니다; 대괄호는 입력하지 않습니다. 명령 문법에서 대체 가능한 인자는 세로 바(|)로 분리되어 있습니다.

빈 줄을 입력하면 마지막으로 입력된 명령이 반복됩니다. 예외: 만약 마지막 명령이 list 명령이면, 다음 11줄이 나열됩니다.

디버거가 인식하지 못하는 명령은 파이썬 문장으로 가정하고 디버깅 중인 프로그램의 컨텍스트에서 실행됩니다. 파이썬 문장 앞에 느낌표(!)를 붙여 사용할 수도 있습니다. 이 방법은 디버깅 중인 프로그램을 검사하는 강력한 방법입니다. 변수를 변경하거나 함수를 호출하는 것도 가능합니다. 이 문장에서 예외가 발생하면, 예외 명은 출력되지만 디버거의 상태는 변경되지 않습니다.

디버거는 에일리어스을 지원합니다. 에일리어스는 검사 중인 컨텍스트에서 특정 수준의 적응성을 허용하는 매개변수를 가질 수 있습니다.

한 줄에 여러 명령은 ;; 로 구분하여 입력할 수 있습니다. (단일 ; 는 파이썬 파서로 전달되는 한 줄에서, 여러 명령을 구분하기 위한 분리 기호이므로 사용되지 않습니다.) 명령을 똑똑하게 분리하진 못합니다; 입력의 맨 처음 ;; 에서 나뉘며, 따옴표로 묶인 문자열 중간에 있더라도 나눠집니다.

만약 파일 .pdbrc 가 사용자의 홈 디렉터리 또는 현재 디렉터리에 있으면, 디버거 프롬프트에서 입력된 것처럼 읽히고 실행됩니다. 이것은 특히 에일리어스에 유용합니다. 만약 두 파일이 모두 존재하면, 홈 디렉터리에 있는 파일이 먼저 읽히고 거기에 정의된 에일리어스는 로컬 파일에 의해 무시될 수 있습니다.

버전 3.2에서 변경: .pdbrc 는 continue와 next같이 디버깅을 계속하는 명령을 포함할 수 있습니다. 이전에는, 이런 명령이 효과가 없었습니다.

h(elp) [command]

인자가 없는 경우에는, 사용 가능한 명령 리스트를 출력합니다. command 인자가 주어진 경우에는, 해당 명령의 도움말을 출력합니다. help pdb 는 전체 문서(pdb 모듈의 독스트링)를 표시합니다. command 인자는 반드시 식별자이어야 하므로, ! 명령의 도움말을 얻기 위해서 help exec 가 꼭 입력되어야 합니다.

w(here)

가장 최근 프레임을 맨 아래로 하는 스택 트레이스를 출력합니다. 화살표는 현재 프레임을 나타내며, 대부분의 명령의 컨텍스트를 명확히 합니다.

d(own) [count]

스택 트레이스에서 현재 프레임을 count (기본 1) 단계 아래로 (새로운 프레임으로) 이동합니다.

u(p) [count]

스택 트레이스에서 현재 프레임을 count (기본 1) 단계 위로 (이전 프레임으로) 이동합니다.

b(reak) [([filename:]lineno | function) [, condition]]

lineno 인자가 주어진 경우, 현재 파일의 해당 줄 번호에 브레이크를 설정합니다. function 인자가 주어진 경우, 함수 내에서 첫 번째 실행 가능한 문장에서 브레이크를 설정합니다. 줄 번호는 다른 파일 (아마도 아직 로드되지 않은 파일)에 중단점을 지정하기 위해, 파일명과 콜론을 접두사로 사용할 수 있습니다. 파일은 sys.path 에서 검색합니다. 주의할 점은 각 중단점에 번호가 지정되며, 다른 모든 중단점 명령이 그 번호를 참조하게 됩니다.

두 번째 인자가 있는 경우, 중단점을 적용하기 전에 표현식이 반드시 참이어야 합니다.

인자가 없다면, 각 중단점, 중단점에 도달한 횟수, 현재까지 무시 횟수, 그리고 관련 조건(있는 경우)을 포함한 모든 중단지점을 나열합니다.

tbreak [([filename:]lineno | function) [, condition]]

한번 도달하면 제거되는 임시중단점입니다. 인자는 break과 동일합니다.

cl(ear) [filename:lineno | bpnumber [bpnumber ...]]

filename:lineno 인자가 주어진 경우, 해당 줄에 있는 모든 중단점을 제거합니다. 공백으로 구분된 중단점 번호 배열이 주어진 경우, 해당 중단점을 제거합니다. 인자가 없는 경우, 모든 중단지점을 재차 확인 후 제거합니다.

disable [bpnumber [bpnumber ...]]

공백으로 구분된 중단점 번호로 해당 중단점을 비활성화합니다. 중단점을 비활성화하는 것은 프로그램이 실행을 중단할 수 없다는 것입니다, 하지만 중단점을 제거하는 것과는 달리, 중단점 목록에 남아있으며 (재-)활성화할 수 있습니다.

enable [bpnumber [bpnumber ...]]

지정된 중단점을 활성화합니다.

ignore bpnumber [count]

해당 중단점 번호를 무시할 횟수를 설정합니다. 만약 횟수가 생략된 경우, 무시 횟수는 0으로 설정됩니다. 무시 횟수가 0일 때 중단점이 활성화됩니다. 0이 아닐 때는, 중단점에 도달하고 중단점이 비활성화되지 않고 연관 조건이 참일 때마다 그 횟수가 차감됩니다.

condition bpnumber [condition]

중단점에 새로운 condition을 설정합니다, 표현식이 참일 때만 중단점이 적용됩니다. 만약 condition이 없다면, 설정되어있던 모든 조건이 제거됩니다; 즉, 중단점에 적용되어있던 조건이 없어집니다.

commands [bpnumber]

중단점 번호 bpnumber 에 대한 명령을 지정합니다. 명령 목록은 다음 줄에 나타나게 됩니다. 명령을 종료하려면 end만 입력하면 됩니다. 예를 들면:

(Pdb) commands 1
(com) p some_variable
(com) end
(Pdb)

중단점에 지정된 모든 명령을 제거하려면, commands 입력 후에 바로 end를 입력하면 됩니다; 즉, 아무 명령을 설정하지 않는 것입니다.

bpnumber 인자가 주어지지 않으면, commands는 마지막 중단점 묶음을 참조하게 됩니다.

중단점 명령을 활용해서 프로그램을 다시 시작할 수도 있습니다. continue 명령이나, step 또는 실행을 재개하는 다른 명령을 사용하기만 하면 됩니다.

실행을 재개하는 아무 명령 (continue, step, next, return, jump, quit 및 해당 명령의 약어들)을 지정하는 것은 (end 명령을 붙인 것처럼) 해당 명령 목록을 끝내는 것입니다. 왜냐하면 실행을 재개할 때마다, 명령 목록을 가진 다른 중단점을 맞이할 수 있고, 어떤 목록을 실행해야 할지 모르는 상황이 생기기 때문입니다.

만약 ‘slient’ 명령을 사용하면, 중단점에서 멈출 때 나오는 메시지는 출력되지 않습니다. 특정 메시지를 출력하고 진행되는 중단점에 바람직할 수 있습니다. 다만 그 어떤 명령도 출력하지 않는다면, 그 중단점에 도달했다는 것은 알 수 없습니다.

s(tep)

현재 줄을 실행하고, 멈출 수 있는 가장 첫 번째 줄(호출되는 함수 또는 현재 함수의 다음 줄) 에서 멈춥니다.

n(ext)

현재 함수의 다음 줄에 도달하거나, 반환할 때까지 계속 실행합니다. next와 step의 차이점은 step은 호출된 함수 안에서 멈추고, next는 호출된 함수를 재빠르게 실행하고 현재 함수의 바로 다음 줄에서만 멈춥니다.

unt(il) [lineno]

인자가 없는 경우에는, 현재 줄 번호보다 높은 줄 번호에 도달할 때까지 계속 실행합니다.

줄 번호가 주어진 경우에는, 해당 번호보다 크거나 같은 줄에 도달할 때까지 계속 실행합니다. 두 경우 모두 현재 프레임이 반환될 때 멈춥니다.

버전 3.2에서 변경: 줄 번호를 명시적으로 줄 수 있도록 허용합니다.

r(eturn)

현재 함수가 반환될 때까지 계속 실행합니다.

c(ont(inue))

중단점을 마주칠 때까지 계속 실행합니다.

j(ump) lineno

다음으로 실행될 줄을 설정할 수 있습니다. 프레임의 맨 마지막에서만 실행이 가능합니다. 이전 줄로 돌아가 코드를 재실행하거나, 실행을 원치 않는 코드를 건너뛸 수 있습니다.

중요한 점은 이 명령은 언제나 실행할 수 있진 않습니다 – for 루프 내부로 들어가거나 finally 절을 건너뛰는 것은 불가능합니다.

l(ist) [first[, last]]

현재 파일의 소스 코드를 나열합니다. 인자가 없는 경우, 현재 줄 주위로 11줄을 나열하거나 이전 줄을 이어서 나열합니다. 인자로 .을 입력한 경우, 현재 줄 주위로 11줄을 나열합니다. 한 인자만 주어진 경우, 해당 줄 주위로 11줄을 나열합니다. 두 인자가 주어진 경우, 두 인자 사이의 모든 줄을 나열합니다; 만약 두 번째 인자가 첫 번째 인자보다 작은 경우, 첫 번째 인자로부터 나열하는 줄 수로 인식합니다.

현재 프레임에서 현재 위치는 ->로 표시됩니다. 예외를 디버깅할 때, 예외가 최초로 발생하거나 전파된 줄이 현재 줄과 다른 경우에는 >>로 표시됩니다.

버전 3.2에 추가: >>표시

ll | longlist

현재 함수나 프레임의 소스 코드 전체를 나열합니다. 참고할만한 줄은 list처럼 표시됩니다.

버전 3.2에 추가.

a(rgs)

현재 함수의 인자 목록을 출력합니다.

p expression

현재 컨텍스트에서 expression을 실행하고 값을 출력합니다.

참고

디버거 명령은 아니지만, print()도 사용될 수 있습니다 — 이때는 파이썬의 print() 함수를 실행하게 됩니다.

pp expression

p 명령과 비슷하지만, 표현식의 값을 pprint 모듈을 활용하여 보기 좋은 형태로 출력합니다.

whatis expression

expression의 형(type)을 출력합니다.

source expression

주어진 객체의 소스 코드를 가져와서 보여줍니다.

버전 3.2에 추가.

display [expression]

현재 프레임에서 실행이 중지될 때마다, 표현식의 값이 변경된 경우 표시합니다.

표현식이 주어지지 않은 경우, 현재 프레임에서 표시되는 모든 표현식을 나열합니다.

버전 3.2에 추가.

undisplay [expression]

현재 프레임에서 표현식을 더는 표시하지 않습니다. 표현식이 주어지지 않은 경우, 현재 프레임에서 표시되는 모든 표현식을 제거합니다.

버전 3.2에 추가.

interact

현재 스코프에서 찾을 수 있는 모든 지역 또는 전역 이름을 담고 있는 전역 이름 공간을 가진 (code 모듈을 활용하는) 대화형 인터프리터를 시작합니다.

버전 3.2에 추가.

alias [name [command]]

command를 실행하는 name이라 불리는 에일리어스를 생성합니다. 명령은 따옴표로 감싸지 않아도 됩니다. 대체할 수 있는 파라미터는 %1, %2 등으로 표시되지만, %* 는 모든 파라미터로 대체됩니다. 만약 명령이 주어지지 않으면, 현재 name의 에일리어스가 표시됩니다. 만약 아무 인자가 주어지지 않으면, 모든 에일리어스가 나열됩니다.

에일리어스는 중첩될 수 있고 pdb 프롬프트 내에서 정당하게 입력할 수 있는 모든 것을 담을 수 있습니다. 주의할 점은 pdb 내부 명령들이 에일리어스에 의해 오버라이드 될 수 있습니다. 그 명령은 에일리어스가 없어질 때까지 사용할 수 없게 됩니다. 에일리어싱은 명령 줄의 첫 번째 단어에 회귀적으로 적용됩니다; 나머지 단어들은 적용되지 않습니다.

.pdbrc파일에 추가되면 특히 유용한 두 에일리어스 예시:

# Print instance variables (usage "pi classInst")
alias pi for k in %1.__dict__.keys(): print("%1.",k,"=",%1.__dict__[k])
# Print instance variables in self
alias ps pi self

unalias name

지정된 에일리어스를 제거합니다.

! statement

현재 스택 프레임의 컨텍스트에서 단일 statement를 실행합니다. 문장의 첫 단어가 디버거 명령이 아닌 경우, 느낌표는 제외해도 됩니다. 전역 변수를 설정하려면 실행하려는 명령과 동일한 줄 맨 앞에 global문장을 붙이면 됩니다, 예를 들면:

(Pdb) global list_options; list_options = ['-l']
(Pdb)

run [args ...]

restart [args ...]

디버그 된 파이썬 프로그램을 재시작합니다. 만약 인자가 주어진 경우, shlex으로 나뉘게 되고 결과는 새 sys.argv로 사용됩니다. 이전 기록, 중단점, 행동 그리고 디버거 옵션은 유지됩니다. restart는 run의 에일리어스입니다.

q(uit)

디버거를 종료합니다. 실행되고 있는 프로그램이 종료됩니다.

debug code

Enter a recursive debugger that steps through the code argument (which is an arbitrary expression or statement to be executed in the current environment).

retval

Print the return value for the last return of a function.

각주

1

프레임이 특정 모듈에서 시작되는 것으로 간주하는지 여부는 프레임 전역에 있는 __name__에 의해 결정됩니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

디버깅과 프로파일링 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

디버깅과 프로파일링 »

|

The Python Profilers

Source code: Lib/profile.py [https://github.com/python/cpython/tree/3.7/Lib/profile.py] and Lib/pstats.py [https://github.com/python/cpython/tree/3.7/Lib/pstats.py]

Introduction to the profilers

cProfile and profile provide deterministic profiling of Python programs. A profile is a set of statistics that describes how often and for how long various parts of the program executed. These statistics can be formatted into reports via the pstats module.

The Python standard library provides two different implementations of the same profiling interface:

cProfile is recommended for most users; it’s a C extension with reasonable overhead that makes it suitable for profiling long-running programs. Based on lsprof, contributed by Brett Rosen and Ted Czotter.

profile, a pure Python module whose interface is imitated by cProfile, but which adds significant overhead to profiled programs. If you’re trying to extend the profiler in some way, the task might be easier with this module. Originally designed and written by Jim Roskind.

참고

The profiler modules are designed to provide an execution profile for a given program, not for benchmarking purposes (for that, there is timeit for reasonably accurate results). This particularly applies to benchmarking Python code against C code: the profilers introduce overhead for Python code, but not for C-level functions, and so the C code would seem faster than any Python one.

Instant User’s Manual

This section is provided for users that “don’t want to read the manual.” It provides a very brief overview, and allows a user to rapidly perform profiling on an existing application.

To profile a function that takes a single argument, you can do:

import cProfile
import re
cProfile.run('re.compile("foo|bar")')

(Use profile instead of cProfile if the latter is not available on your system.)

The above action would run re.compile() and print profile results like the following:

      197 function calls (192 primitive calls) in 0.002 seconds

Ordered by: standard name

ncalls  tottime  percall  cumtime  percall filename:lineno(function)
     1    0.000    0.000    0.001    0.001 <string>:1(<module>)
     1    0.000    0.000    0.001    0.001 re.py:212(compile)
     1    0.000    0.000    0.001    0.001 re.py:268(_compile)
     1    0.000    0.000    0.000    0.000 sre_compile.py:172(_compile_charset)
     1    0.000    0.000    0.000    0.000 sre_compile.py:201(_optimize_charset)
     4    0.000    0.000    0.000    0.000 sre_compile.py:25(_identityfunction)
   3/1    0.000    0.000    0.000    0.000 sre_compile.py:33(_compile)

The first line indicates that 197 calls were monitored. Of those calls, 192 were primitive, meaning that the call was not induced via recursion. The next line: Ordered by: standard name, indicates that the text string in the far right column was used to sort the output. The column headings include:

ncalls

for the number of calls.

tottime

for the total time spent in the given function (and excluding time made in calls to sub-functions)

percall

is the quotient of tottime divided by ncalls

cumtime

is the cumulative time spent in this and all subfunctions (from invocation till exit). This figure is accurate even for recursive functions.

percall

is the quotient of cumtime divided by primitive calls

filename:lineno(function)

provides the respective data of each function

When there are two numbers in the first column (for example 3/1), it means that the function recursed. The second value is the number of primitive calls and the former is the total number of calls. Note that when the function does not recurse, these two values are the same, and only the single figure is printed.

Instead of printing the output at the end of the profile run, you can save the results to a file by specifying a filename to the run() function:

import cProfile
import re
cProfile.run('re.compile("foo|bar")', 'restats')

The pstats.Stats class reads profile results from a file and formats them in various ways.

The file cProfile can also be invoked as a script to profile another script. For example:

python -m cProfile [-o output_file] [-s sort_order] (-m module | myscript.py)

-o writes the profile results to a file instead of to stdout

-s specifies one of the sort_stats() sort values to sort the output by. This only applies when -o is not supplied.

-m specifies that a module is being profiled instead of a script.

버전 3.7에 추가: Added the -m option.

The pstats module’s Stats class has a variety of methods for manipulating and printing the data saved into a profile results file:

import pstats
from pstats import SortKey
p = pstats.Stats('restats')
p.strip_dirs().sort_stats(-1).print_stats()

The strip_dirs() method removed the extraneous path from all the module names. The sort_stats() method sorted all the entries according to the standard module/line/name string that is printed. The print_stats() method printed out all the statistics. You might try the following sort calls:

p.sort_stats(SortKey.NAME)
p.print_stats()

The first call will actually sort the list by function name, and the second call will print out the statistics. The following are some interesting calls to experiment with:

p.sort_stats(SortKey.CUMULATIVE).print_stats(10)

This sorts the profile by cumulative time in a function, and then only prints the ten most significant lines. If you want to understand what algorithms are taking time, the above line is what you would use.

If you were looking to see what functions were looping a lot, and taking a lot of time, you would do:

p.sort_stats(SortKey.TIME).print_stats(10)

to sort according to time spent within each function, and then print the statistics for the top ten functions.

You might also try:

p.sort_stats(SortKey.FILENAME).print_stats('__init__')

This will sort all the statistics by file name, and then print out statistics for only the class init methods (since they are spelled with __init__ in them). As one final example, you could try:

p.sort_stats(SortKey.TIME, SortKey.CUMULATIVE).print_stats(.5, 'init')

This line sorts statistics with a primary key of time, and a secondary key of cumulative time, and then prints out some of the statistics. To be specific, the list is first culled down to 50% (re: .5) of its original size, then only lines containing init are maintained, and that sub-sub-list is printed.

If you wondered what functions called the above functions, you could now (p is still sorted according to the last criteria) do:

p.print_callers(.5, 'init')

and you would get a list of callers for each of the listed functions.

If you want more functionality, you’re going to have to read the manual, or guess what the following functions do:

p.print_callees()
p.add('restats')

Invoked as a script, the pstats module is a statistics browser for reading and examining profile dumps. It has a simple line-oriented interface (implemented using cmd) and interactive help.

profile and cProfile Module Reference

Both the profile and cProfile modules provide the following functions:

profile.run(command, filename=None, sort=-1)

This function takes a single argument that can be passed to the exec() function, and an optional file name. In all cases this routine executes:

exec(command, __main__.__dict__, __main__.__dict__)

and gathers profiling statistics from the execution. If no file name is present, then this function automatically creates a Stats instance and prints a simple profiling report. If the sort value is specified, it is passed to this Stats instance to control how the results are sorted.

profile.runctx(command, globals, locals, filename=None, sort=-1)

This function is similar to run(), with added arguments to supply the globals and locals dictionaries for the command string. This routine executes:

exec(command, globals, locals)

and gathers profiling statistics as in the run() function above.

class profile.Profile(timer=None, timeunit=0.0, subcalls=True, builtins=True)

This class is normally only used if more precise control over profiling is needed than what the cProfile.run() function provides.

A custom timer can be supplied for measuring how long code takes to run via the timer argument. This must be a function that returns a single number representing the current time. If the number is an integer, the timeunit specifies a multiplier that specifies the duration of each unit of time. For example, if the timer returns times measured in thousands of seconds, the time unit would be .001.

Directly using the Profile class allows formatting profile results without writing the profile data to a file:

import cProfile, pstats, io
from pstats import SortKey
pr = cProfile.Profile()
pr.enable()
# ... do something ...
pr.disable()
s = io.StringIO()
sortby = SortKey.CUMULATIVE
ps = pstats.Stats(pr, stream=s).sort_stats(sortby)
ps.print_stats()
print(s.getvalue())

enable()

Start collecting profiling data.

disable()

Stop collecting profiling data.

create_stats()

Stop collecting profiling data and record the results internally as the current profile.

print_stats(sort=-1)

Create a Stats object based on the current profile and print the results to stdout.

dump_stats(filename)

Write the results of the current profile to filename.

run(cmd)

Profile the cmd via exec().

runctx(cmd, globals, locals)

Profile the cmd via exec() with the specified global and local environment.

runcall(func, *args, **kwargs)

Profile func(*args, **kwargs)

Note that profiling will only work if the called command/function actually returns. If the interpreter is terminated (e.g. via a sys.exit() call during the called command/function execution) no profiling results will be printed.

The Stats Class

Analysis of the profiler data is done using the Stats class.

class pstats.Stats(*filenames or profile, stream=sys.stdout)

This class constructor creates an instance of a “statistics object” from a filename (or list of filenames) or from a Profile instance. Output will be printed to the stream specified by stream.

The file selected by the above constructor must have been created by the corresponding version of profile or cProfile. To be specific, there is no file compatibility guaranteed with future versions of this profiler, and there is no compatibility with files produced by other profilers, or the same profiler run on a different operating system. If several files are provided, all the statistics for identical functions will be coalesced, so that an overall view of several processes can be considered in a single report. If additional files need to be combined with data in an existing Stats object, the add() method can be used.

Instead of reading the profile data from a file, a cProfile.Profile or profile.Profile object can be used as the profile data source.

Stats objects have the following methods:

strip_dirs()

This method for the Stats class removes all leading path information from file names. It is very useful in reducing the size of the printout to fit within (close to) 80 columns. This method modifies the object, and the stripped information is lost. After performing a strip operation, the object is considered to have its entries in a “random” order, as it was just after object initialization and loading. If strip_dirs() causes two function names to be indistinguishable (they are on the same line of the same filename, and have the same function name), then the statistics for these two entries are accumulated into a single entry.

add(*filenames)

This method of the Stats class accumulates additional profiling information into the current profiling object. Its arguments should refer to filenames created by the corresponding version of profile.run() or cProfile.run(). Statistics for identically named (re: file, line, name) functions are automatically accumulated into single function statistics.

dump_stats(filename)

Save the data loaded into the Stats object to a file named filename. The file is created if it does not exist, and is overwritten if it already exists. This is equivalent to the method of the same name on the profile.Profile and cProfile.Profile classes.

sort_stats(*keys)

This method modifies the Stats object by sorting it according to the supplied criteria. The argument can be either a string or a SortKey enum identifying the basis of a sort (example: 'time', 'name', SortKey.TIME or SortKey.NAME). The SortKey enums argument have advantage over the string argument in that it is more robust and less error prone.

When more than one key is provided, then additional keys are used as secondary criteria when there is equality in all keys selected before them. For example, sort_stats(SortKey.NAME, SortKey.FILE) will sort all the entries according to their function name, and resolve all ties (identical function names) by sorting by file name.

For the string argument, abbreviations can be used for any key names, as long as the abbreviation is unambiguous.

The following are the valid string and SortKey:

Valid String Arg

Valid enum Arg

Meaning

'calls'

SortKey.CALLS

call count

'cumulative'

SortKey.CUMULATIVE

cumulative time

'cumtime'

N/A

cumulative time

'file'

N/A

file name

'filename'

SortKey.FILENAME

file name

'module'

N/A

file name

'ncalls'

N/A

call count

'pcalls'

SortKey.PCALLS

primitive call count

'line'

SortKey.LINE

line number

'name'

SortKey.NAME

function name

'nfl'

SortKey.NFL

name/file/line

'stdname'

SortKey.STDNAME

standard name

'time'

SortKey.TIME

internal time

'tottime'

N/A

internal time

Note that all sorts on statistics are in descending order (placing most time consuming items first), where as name, file, and line number searches are in ascending order (alphabetical). The subtle distinction between SortKey.NFL and SortKey.STDNAME is that the standard name is a sort of the name as printed, which means that the embedded line numbers get compared in an odd way. For example, lines 3, 20, and 40 would (if the file names were the same) appear in the string order 20, 3 and 40. In contrast, SortKey.NFL does a numeric compare of the line numbers. In fact, sort_stats(SortKey.NFL) is the same as sort_stats(SortKey.NAME, SortKey.FILENAME, SortKey.LINE).

For backward-compatibility reasons, the numeric arguments -1, 0, 1, and 2 are permitted. They are interpreted as 'stdname', 'calls', 'time', and 'cumulative' respectively. If this old style format (numeric) is used, only one sort key (the numeric key) will be used, and additional arguments will be silently ignored.

버전 3.7에 추가: Added the SortKey enum.

reverse_order()

This method for the Stats class reverses the ordering of the basic list within the object. Note that by default ascending vs descending order is properly selected based on the sort key of choice.

print_stats(*restrictions)

This method for the Stats class prints out a report as described in the profile.run() definition.

The order of the printing is based on the last sort_stats() operation done on the object (subject to caveats in add() and strip_dirs()).

The arguments provided (if any) can be used to limit the list down to the significant entries. Initially, the list is taken to be the complete set of profiled functions. Each restriction is either an integer (to select a count of lines), or a decimal fraction between 0.0 and 1.0 inclusive (to select a percentage of lines), or a string that will interpreted as a regular expression (to pattern match the standard name that is printed). If several restrictions are provided, then they are applied sequentially. For example:

print_stats(.1, 'foo:')

would first limit the printing to first 10% of list, and then only print functions that were part of filename .*foo:. In contrast, the command:

print_stats('foo:', .1)

would limit the list to all functions having file names .*foo:, and then proceed to only print the first 10% of them.

print_callers(*restrictions)

This method for the Stats class prints a list of all functions that called each function in the profiled database. The ordering is identical to that provided by print_stats(), and the definition of the restricting argument is also identical. Each caller is reported on its own line. The format differs slightly depending on the profiler that produced the stats:

With profile, a number is shown in parentheses after each caller to show how many times this specific call was made. For convenience, a second non-parenthesized number repeats the cumulative time spent in the function at the right.

With cProfile, each caller is preceded by three numbers: the number of times this specific call was made, and the total and cumulative times spent in the current function while it was invoked by this specific caller.

print_callees(*restrictions)

This method for the Stats class prints a list of all function that were called by the indicated function. Aside from this reversal of direction of calls (re: called vs was called by), the arguments and ordering are identical to the print_callers() method.

What Is Deterministic Profiling?

Deterministic profiling is meant to reflect the fact that all function call, function return, and exception events are monitored, and precise timings are made for the intervals between these events (during which time the user’s code is executing). In contrast, statistical profiling (which is not done by this module) randomly samples the effective instruction pointer, and deduces where time is being spent. The latter technique traditionally involves less overhead (as the code does not need to be instrumented), but provides only relative indications of where time is being spent.

In Python, since there is an interpreter active during execution, the presence of instrumented code is not required to do deterministic profiling. Python automatically provides a hook (optional callback) for each event. In addition, the interpreted nature of Python tends to add so much overhead to execution, that deterministic profiling tends to only add small processing overhead in typical applications. The result is that deterministic profiling is not that expensive, yet provides extensive run time statistics about the execution of a Python program.

Call count statistics can be used to identify bugs in code (surprising counts), and to identify possible inline-expansion points (high call counts). Internal time statistics can be used to identify “hot loops” that should be carefully optimized. Cumulative time statistics should be used to identify high level errors in the selection of algorithms. Note that the unusual handling of cumulative times in this profiler allows statistics for recursive implementations of algorithms to be directly compared to iterative implementations.

Limitations

One limitation has to do with accuracy of timing information. There is a fundamental problem with deterministic profilers involving accuracy. The most obvious restriction is that the underlying “clock” is only ticking at a rate (typically) of about .001 seconds. Hence no measurements will be more accurate than the underlying clock. If enough measurements are taken, then the “error” will tend to average out. Unfortunately, removing this first error induces a second source of error.

The second problem is that it “takes a while” from when an event is dispatched until the profiler’s call to get the time actually gets the state of the clock. Similarly, there is a certain lag when exiting the profiler event handler from the time that the clock’s value was obtained (and then squirreled away), until the user’s code is once again executing. As a result, functions that are called many times, or call many functions, will typically accumulate this error. The error that accumulates in this fashion is typically less than the accuracy of the clock (less than one clock tick), but it can accumulate and become very significant.

The problem is more important with profile than with the lower-overhead cProfile. For this reason, profile provides a means of calibrating itself for a given platform so that this error can be probabilistically (on the average) removed. After the profiler is calibrated, it will be more accurate (in a least square sense), but it will sometimes produce negative numbers (when call counts are exceptionally low, and the gods of probability work against you :-). ) Do not be alarmed by negative numbers in the profile. They should only appear if you have calibrated your profiler, and the results are actually better than without calibration.

Calibration

The profiler of the profile module subtracts a constant from each event handling time to compensate for the overhead of calling the time function, and socking away the results. By default, the constant is 0. The following procedure can be used to obtain a better constant for a given platform (see Limitations).

import profile
pr = profile.Profile()
for i in range(5):
    print(pr.calibrate(10000))

The method executes the number of Python calls given by the argument, directly and again under the profiler, measuring the time for both. It then computes the hidden overhead per profiler event, and returns that as a float. For example, on a 1.8Ghz Intel Core i5 running Mac OS X, and using Python’s time.process_time() as the timer, the magical number is about 4.04e-6.

The object of this exercise is to get a fairly consistent result. If your computer is very fast, or your timer function has poor resolution, you might have to pass 100000, or even 1000000, to get consistent results.

When you have a consistent answer, there are three ways you can use it:

import profile

# 1. Apply computed bias to all Profile instances created hereafter.
profile.Profile.bias = your_computed_bias

# 2. Apply computed bias to a specific Profile instance.
pr = profile.Profile()
pr.bias = your_computed_bias

# 3. Specify computed bias in instance constructor.
pr = profile.Profile(bias=your_computed_bias)

If you have a choice, you are better off choosing a smaller constant, and then your results will “less often” show up as negative in profile statistics.

Using a custom timer

If you want to change how current time is determined (for example, to force use of wall-clock time or elapsed process time), pass the timing function you want to the Profile class constructor:

pr = profile.Profile(your_time_func)

The resulting profiler will then call your_time_func. Depending on whether you are using profile.Profile or cProfile.Profile, your_time_func’s return value will be interpreted differently:

profile.Profile

your_time_func should return a single number, or a list of numbers whose sum is the current time (like what os.times() returns). If the function returns a single time number, or the list of returned numbers has length 2, then you will get an especially fast version of the dispatch routine.

Be warned that you should calibrate the profiler class for the timer function that you choose (see Calibration). For most machines, a timer that returns a lone integer value will provide the best results in terms of low overhead during profiling. (os.times() is pretty bad, as it returns a tuple of floating point values). If you want to substitute a better timer in the cleanest fashion, derive a class and hardwire a replacement dispatch method that best handles your timer call, along with the appropriate calibration constant.

cProfile.Profile

your_time_func should return a single number. If it returns integers, you can also invoke the class constructor with a second argument specifying the real duration of one unit of time. For example, if your_integer_time_func returns times measured in thousands of seconds, you would construct the Profile instance as follows:

pr = cProfile.Profile(your_integer_time_func, 0.001)

As the cProfile.Profile class cannot be calibrated, custom timer functions should be used with care and should be as fast as possible. For the best results with a custom timer, it might be necessary to hard-code it in the C source of the internal _lsprof module.

Python 3.3 adds several new functions in time that can be used to make precise measurements of process or wall-clock time. For example, see time.perf_counter().

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

디버깅과 프로파일링 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

디버깅과 프로파일링 »

|

timeit — 작은 코드 조각의 실행 시간 측정

소스 코드: Lib/timeit.py [https://github.com/python/cpython/tree/3.7/Lib/timeit.py]

이 모듈은 파이썬 코드의 작은 조각의 시간을 측정하는 간단한 방법을 제공합니다. 명령 줄 인터페이스뿐만 아니라 콜러블도 있습니다. 실행 시간을 측정에 따르는 흔한 함정들을 피할 수 있습니다. O’Reilly가 출판한 Python Cookbook에 있는 Tim Peters의 “Algorithms” 장의 개요도 참조하십시오.

기본 예제

다음 예제에서는 명령 줄 인터페이스를 사용하여 세 가지 다른 표현식을 비교하는 방법을 보여줍니다:

$ python3 -m timeit '"-".join(str(n) for n in range(100))'
10000 loops, best of 5: 30.2 usec per loop
$ python3 -m timeit '"-".join([str(n) for n in range(100)])'
10000 loops, best of 5: 27.5 usec per loop
$ python3 -m timeit '"-".join(map(str, range(100)))'
10000 loops, best of 5: 23.2 usec per loop

이것은 파이썬 인터페이스로는 다음과 같이 할 수 있습니다:

>>> import timeit
>>> timeit.timeit('"-".join(str(n) for n in range(100))', number=10000)
0.3018611848820001
>>> timeit.timeit('"-".join([str(n) for n in range(100)])', number=10000)
0.2727368790656328
>>> timeit.timeit('"-".join(map(str, range(100)))', number=10000)
0.23702679807320237

콜러블을 파이썬 인터페이스로 전달할 수도 있습니다:

>>> timeit.timeit(lambda: "-".join(map(str, range(100))), number=10000)
0.19665591977536678

그러나 timeit()은 명령 줄 인터페이스가 사용될 때만 반복 횟수를 자동으로 결정합니다. 예제 절에서 고급 예제를 찾을 수 있습니다.

파이썬 인터페이스

이 모듈은 세 개의 편리 함수와 하나의 공용 클래스를 정의합니다:

timeit.timeit(stmt='pass', setup='pass', timer=<default timer>, number=1000000, globals=None)

지정된 문장, setup 코드 및 timer 함수로 Timer 인스턴스를 만들고, number 실행으로 timeit() 메서드를 실행합니다. 선택적 globals 인자는 코드를 실행할 이름 공간을 지정합니다.

버전 3.5에서 변경: 선택적 globals 매개 변수가 추가되었습니다.

timeit.repeat(stmt='pass', setup='pass', timer=<default timer>, repeat=5, number=1000000, globals=None)

주어진 문장, setup 코드 및 timer 함수로 Timer 인스턴스를 생성하고, 주어진 repeat 카운트와 number 실행으로 repeat() 메서드를 실행합니다. 선택적 globals 인자는 코드를 실행할 이름 공간을 지정합니다.

버전 3.5에서 변경: 선택적 globals 매개 변수가 추가되었습니다.

버전 3.7에서 변경: repeat의 기본값이 3에서 5로 변경되었습니다.

timeit.default_timer()

기본 타이머, 항상 time.perf_counter()입니다.

버전 3.3에서 변경: 이제 time.perf_counter()가 기본 타이머입니다.

class timeit.Timer(stmt='pass', setup='pass', timer=<timer function>, globals=None)

작은 코드 조각의 실행 속도를 측정하기 위한 클래스.

생성자는 시간 측정될 문장, 설정에 사용되는 추가 문장 및 타이머 함수를 받아들입니다. 두 문장의 기본값은 'pass'입니다; 타이머 함수는 플랫폼에 따라 다릅니다 (모듈 독스트링을 참조하십시오). stmt와 setup은 여러 줄에 걸친 문자열 리터럴을 포함하지 않는 한 ;나 줄 바꿈으로 구분된 여러 개의 문장을 포함 할 수도 있습니다. 문장은 기본적으로 timeit의 이름 공간 내에서 실행됩니다; 이 동작은 globals에 이름 공간을 전달하여 제어 할 수 있습니다.

첫 번째 문장의 실행 시간을 측정하려면, timeit() 메서드를 사용하십시오. repeat()와 autorange() 메서드는 timeit()을 여러 번 호출하는 편리 메서드입니다.

setup의 실행 시간은 전체 측정 실행 시간에서 제외됩니다.

stmt와 setup 매개 변수는 인자 없이 호출 할 수 있는 객체를 받아들일 수도 있습니다. 이렇게 하면 timeit()에 의해 실행될 타이머 함수에 그들에 대한 호출을 포함시킵니다. 이때는 여분의 함수 호출로 인해 타이밍 오버헤드가 약간 더 커집니다.

버전 3.5에서 변경: 선택적 globals 매개 변수가 추가되었습니다.

timeit(number=1000000)

주 문장의 number 실행의 시간을 측정합니다. setup 문장을 한 번 실행한 다음, 주 문장을 여러 번 실행하는 데 걸리는 시간을 초 단위로 float로 반환합니다. 인자는 루프를 통과하는 횟수이며, 기본값은 백만입니다. 주 문장, setup 문장 및 사용할 타이머 함수는 생성자에 전달됩니다.

참고

기본적으로, timeit()은 시간 측정 중에 가비지 수거를 일시적으로 끕니다. 이 방법의 장점은 독립적인 시간 측정이 더 잘 비교될 수 있다는 것입니다. 단점은 GC가 측정되는 함수의 성능에서 중요한 요소가 될 수 있다는 것입니다. 그렇다면, GC를 setup 문자열의 첫 번째 문장에서 다시 활성화할 수 있습니다. 예를 들면:

timeit.Timer('for i in range(10): oct(i)', 'gc.enable()').timeit()

autorange(callback=None)

timeit()를 호출하는 횟수를 자동으로 결정합니다.

이 함수는 총 시간이 0.2초 이상이 될 때까지 timeit()을 반복적으로 호출하고, 최종 (루프 수, 해당 루프 수에 소요된 시간)을 반환하는 편리 함수입니다. 실행 시간이 적어도 0.2초가 될 때까지 1, 2, 5, 10, 20, 50 … 로 루프 수를 증가시키면서 timeit()을 호출합니다.

callback이 주어지고 None이 아니면, 각 시도 다음에 두 개의 인자로 호출합니다: callback(number, time_taken).

버전 3.6에 추가.

repeat(repeat=5, number=1000000)

timeit()을 몇 번 호출합니다.

이것은 반복적으로 timeit()을 호출하여 결과 리스트를 반환하는 편리 함수입니다. 첫 번째 인자는 timeit()을 호출할 횟수를 지정합니다. 두 번째 인자는 timeit()에 대한 number 인자를 지정합니다.

참고

결과 벡터로부터 평균과 표준 편차를 계산하고 이를 보고하고 싶을 수 있습니다. 하지만, 이것은 별로 유용하지 않습니다. 일반적으로, 가장 낮은 값이 여러분의 기계가 주어진 코드 조각을 얼마나 빨리 실행할 수 있는지에 대한 하한값을 제공합니다; 결과 벡터의 더 높은 값은 일반적으로 파이썬의 속도 변동성 때문이 아니라, 시간 측정의 정확성을 방해하는 다른 프로세스에 의해 발생합니다. 따라서 결과의 min()이 여러분이 관심을 기울여야 할 유일한 숫자일 것입니다. 그 후에, 전체 벡터를 살펴보고 통계보다는 상식을 적용해야 합니다.

버전 3.7에서 변경: repeat의 기본값이 3에서 5로 변경되었습니다.

print_exc(file=None)

측정되는 코드로부터의 트레이스백을 인쇄하는 도우미.

일반적인 사용:

t = Timer(...)       # outside the try/except
try:
    t.timeit(...)    # or t.repeat(...)
except Exception:
    t.print_exc()

표준 트레이스백에 비해 장점은 컴파일된 템플릿의 소스 행이 표시된다는 것입니다. 선택적 file 인자는 트레이스백을 보내야 할 곳을 지시합니다; 기본값은 sys.stderr입니다.

명령 줄 인터페이스

명령 줄에서 프로그램으로 호출할 때, 다음 형식이 사용됩니다:

python -m timeit [-n N] [-r N] [-u U] [-s S] [-h] [statement ...]

이때 다음 옵션을 지원합니다:

-n N, --number=N

‘statement’를 실행하는 횟수

-r N, --repeat=N

타이머 반복 횟수 (기본값 5)

-s S, --setup=S

초기에 한 번 실행될 문장 (기본값 pass)

-p, --process

벽시계 시간이 아니라 프로세스 시간을 측정합니다, 기본값인 time.perf_counter() 대신 time.process_time()을 사용합니다

버전 3.3에 추가.

-u, --unit=U

타이머 출력의 시간 단위를 지정합니다; nsec, usec, msec 또는 sec 중에서 선택할 수 있습니다.

버전 3.5에 추가.

-v, --verbose

날 시간 측정 결과를 인쇄합니다; 더 많은 자릿수 정밀도를 위해서는 반복하십시오

-h, --help

짧은 사용법 메시지를 출력하고 종료합니다

여러 줄의 문장은 각 줄을 별도의 statement 인자로 지정하여 제공할 수 있습니다; 들여쓰기 된 줄은 인자를 따옴표로 묶고 선행 공백을 사용하면 됩니다. 여러 개의 -s 옵션도 비슷하게 취급됩니다.

If -n is not given, a suitable number of loops is calculated by trying increasing numbers from the sequence 1, 2, 5, 10, 20, 50, … until the total time is at least 0.2 seconds.

default_timer() 측정은 같은 기계에서 실행되는 다른 프로그램의 영향을 받을 수 있으므로, 정확한 시간 측정이 필요할 때 가장 좋은 방법은 시간 측정을 몇 번 반복하고 가장 좋은 시간을 사용하는 것입니다. 이 작업에는 -r 옵션이 좋습니다; 대부분의 경우 기본값인 5번 반복으로 충분할 것입니다. time.process_time()을 사용하여 CPU 시간을 측정 할 수 있습니다.

참고

pass 문을 실행하는 것과 관련된 어떤 기준 오버헤드가 있습니다. 여기에 있는 코드는 그것을 숨기려고 시도하지는 않지만, 여러분은 신경 써야 합니다. 기준 오버헤드는 인자 없이 프로그램을 호출하여 측정 할 수 있으며, 파이썬 버전마다 다를 수 있습니다.

예제

처음에 한 번만 실행되는 setup 문을 제공 할 수 있습니다:

$ python -m timeit -s 'text = "sample string"; char = "g"'  'char in text'
5000000 loops, best of 5: 0.0877 usec per loop
$ python -m timeit -s 'text = "sample string"; char = "g"'  'text.find(char)'
1000000 loops, best of 5: 0.342 usec per loop

>>> import timeit
>>> timeit.timeit('char in text', setup='text = "sample string"; char = "g"')
0.41440500499993504
>>> timeit.timeit('text.find(char)', setup='text = "sample string"; char = "g"')
1.7246671520006203

Timer 클래스와 그 메서드를 사용하여 같은 작업을 수행 할 수 있습니다:

>>> import timeit
>>> t = timeit.Timer('char in text', setup='text = "sample string"; char = "g"')
>>> t.timeit()
0.3955516149999312
>>> t.repeat()
[0.40183617287970225, 0.37027556854118704, 0.38344867356679524, 0.3712595970846668, 0.37866875250654886]

다음 예제는 여러 줄을 포함하는 표현식의 시간을 측정하는 방법을 보여줍니다. 여기서 우리는 누락되었거나 존재하는 객체 어트리뷰트를 검사하는데 hasattr()과 try/except를 사용하는 비용을 비교합니다:

$ python -m timeit 'try:' '  str.__bool__' 'except AttributeError:' '  pass'
20000 loops, best of 5: 15.7 usec per loop
$ python -m timeit 'if hasattr(str, "__bool__"): pass'
50000 loops, best of 5: 4.26 usec per loop

$ python -m timeit 'try:' '  int.__bool__' 'except AttributeError:' '  pass'
200000 loops, best of 5: 1.43 usec per loop
$ python -m timeit 'if hasattr(int, "__bool__"): pass'
100000 loops, best of 5: 2.23 usec per loop

>>> import timeit
>>> # attribute is missing
>>> s = """\
... try:
...     str.__bool__
... except AttributeError:
...     pass
... """
>>> timeit.timeit(stmt=s, number=100000)
0.9138244460009446
>>> s = "if hasattr(str, '__bool__'): pass"
>>> timeit.timeit(stmt=s, number=100000)
0.5829014980008651
>>>
>>> # attribute is present
>>> s = """\
... try:
...     int.__bool__
... except AttributeError:
...     pass
... """
>>> timeit.timeit(stmt=s, number=100000)
0.04215312199994514
>>> s = "if hasattr(int, '__bool__'): pass"
>>> timeit.timeit(stmt=s, number=100000)
0.08588060699912603

timeit 모듈이 여러분이 정의한 함수에 액세스하도록 하려면, import 문이 포함된 setup 매개 변수를 전달하면 됩니다:

def test():
    """Stupid test function"""
    L = [i for i in range(100)]

if __name__ == '__main__':
    import timeit
    print(timeit.timeit("test()", setup="from __main__ import test"))

또 다른 옵션은 globals()를 globals 매개 변수로 전달해서, 여러분의 현재 전역 이름 공간에서 코드가 실행되도록 하는 것입니다. 임포트를 개별적으로 지정하는 것보다 편리 할 수 있습니다:

def f(x):
    return x**2
def g(x):
    return x**4
def h(x):
    return x**8

import timeit
print(timeit.timeit('[func(42) for func in (f,g,h)]', globals=globals()))

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

디버깅과 프로파일링 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

디버깅과 프로파일링 »

|

trace — 파이썬 문장 실행 추적

소스 코드: Lib/trace.py [https://github.com/python/cpython/tree/3.7/Lib/trace.py]

trace 모듈을 사용하면 프로그램 실행을 추적하고, 주석 처리된 문장 커버리지 리스트를 생성하고, 호출자/피호출자 관계를 인쇄하고, 프로그램 실행 중 호출되는 함수를 나열할 수 있습니다. 다른 프로그램이나 명령 줄에서 사용할 수 있습니다.

더 보기

Coverage.py [https://coverage.readthedocs.io/]

브랜치 커버리지와 같은 고급 기능과 함께 HTML 출력을 제공하는 널리 사용되는 제삼자 커버리지 도구.

명령 줄 사용법

trace 모듈은 명령 줄에서 호출할 수 있습니다. 다음과 같이 간단할 수도 있습니다

python -m trace --count -C . somefile.py ...

이것은 somefile.py를 실행하고 실행 중에 임포트 한 모든 파이썬 모듈들의 주석이 달린 리스트를 현재 디렉터리에 생성합니다.

--help

사용법을 표시하고 종료합니다.

--version

모듈의 버전을 표시하고 종료합니다.

주요 옵션

trace를 호출할 때 다음 옵션 중 적어도 하나를 지정해야 합니다. --listfuncs 옵션은 --trace 나 --count 옵션과 함께 사용할 수 없습니다. --listfuncs이 제공되면, --count 나 --trace는 허용되지 않으며, 반대의 경우도 마찬가지입니다.

-c, --count

프로그램 완료 시 각 문장이 실행된 횟수를 보여주는 주석이 달린 리스팅 파일 집합을 생성합니다. 아래의 --coverdir, --file 및 --no-report도 참조하십시오.

-t, --trace

줄이 실행될 때마다 표시합니다.

-l, --listfuncs

프로그램을 실행하여 실행되는 함수들을 표시합니다.

-r, --report

--count 와 --file 옵션을 사용한 이전 프로그램 실행에서 주석이 달린 목록을 생성합니다. 이것은 어떤 코드도 실행하지 않습니다.

-T, --trackcalls

프로그램을 실행하여 노출된 호출 관계를 표시합니다.

수정자

-f, --file=<file>

여러 추적 실행에서 실행 횟수를 누적할 파일의 이름. --count 옵션과 함께 사용해야 합니다.

-C, --coverdir=<dir>

보고서 파일이 저장되는 디렉터리. package.module에 대한 커버리지 보고서는 dir/package/module.cover 파일에 기록됩니다.

-m, --missing

주석이 달린 리스팅을 작성할 때, >>>>>>로 실행되지 않은 줄을 표시합니다.

-s, --summary

--count 나 --report를 사용할 때, 처리된 각 파일에 대한 요약을 표준출력으로 기록합니다.

-R, --no-report

주석이 달린 리스팅을 생성하지 않습니다. 이것은 --count를 사용하여 여러 번 실행한 다음, 마지막에 주석이 달린 리스팅의 단일 집합을 생성하려고 할 때 유용합니다.

-g, --timing

프로그램이 시작된 이후의 시간을 각 줄 앞에 붙입니다. 추적하는 동안에만 사용됩니다.

필터

이 옵션들은 여러 번 반복 될 수 있습니다.

--ignore-module=<mod>

주어진 각 모듈 이름과 (패키지라면) 그 서브 모듈을 무시합니다. 인자는 쉼표로 구분된 이름 목록일 수 있습니다.

--ignore-dir=<dir>

명명된 디렉터리와 하위 디렉터리의 모든 모듈과 패키지를 무시합니다. 인자는 os.pathsep으로 구분된 디렉터리 목록일 수 있습니다.

프로그래밍 인터페이스

class trace.Trace(count=1, trace=1, countfuncs=0, countcallers=0, ignoremods=(), ignoredirs=(), infile=None, outfile=None, timing=False)

단일 문장이나 표현식의 실행을 추적할 객체를 만듭니다. 모든 매개 변수는 선택 사항입니다. count는 줄 번호의 카운팅을 활성화합니다. trace는 줄 실행 추적을 활성화합니다. countfuncs는 실행 중에 호출된 함수들의 리스팅을 활성화합니다. countcallers는 호출 관계 추적을 활성화합니다. ignoremods는 무시할 모듈이나 패키지의 리스트입니다. ignoredirs는 들어있는 모듈이나 패키지를 무시해야 하는 디렉터리의 리스트입니다. infile은 저장된 카운트 정보를 읽을 파일 이름입니다. outfile는 갱신된 카운트 정보를 쓰는 파일의 이름입니다. timing는 추적이 시작될 때에 상대적인 타임스탬프 표시를 활성화합니다.

run(cmd)

명령을 실행하고 현재 추적 매개 변수를 사용하여 실행에서 통계를 수집합니다. cmd는 exec()로 전달하는데 적합한 문자열이나 코드 객체여야 합니다.

runctx(cmd, globals=None, locals=None)

정의된 전역과 지역 환경에서, 명령을 실행하고 현재 추적 매개 변수를 사용하여 실행에서 통계를 수집합니다. 정의되지 않으면, globals 와 locals의 기본값은 빈 딕셔너리입니다.

runfunc(func, *args, **kwds)

현재 추적 매개 변수를 갖는 Trace 객체의 제어하에 주어진 인자로 func를 호출합니다.

results()

주어진 Trace 인스턴스에 대한 모든 이전 run, runctx 및 runfunc 호출의 누적 결과를 포함하는 CoverageResults 객체를 반환합니다. 누적된 추적 결과를 재설정하지 않습니다.

class trace.CoverageResults

Trace.results()에 의해 만들어진 커버리지 결과를 위한 컨테이너. 사용자가 직접 만들어서는 안 됩니다.

update(other)

다른 CoverageResults 객체의 데이터를 병합합니다.

write_results(show_missing=True, summary=False, coverdir=None)

커버리지 결과를 기록합니다. 실행 카운트가 없는 줄을 표시하려면 show_missing을 설정하십시오. 모듈당 커버리지 요약을 출력에 포함 시키려면 summary를 설정하십시오. coverdir은 커버리지 결과 파일이 출력될 디렉터리를 지정합니다. None이면, 각 소스 파일의 결과가 해당 디렉터리에 위치합니다.

프로그래밍 인터페이스의 사용을 보여주는 간단한 예제:

import sys
import trace

# create a Trace object, telling it what to ignore, and whether to
# do tracing or line-counting or both.
tracer = trace.Trace(
    ignoredirs=[sys.prefix, sys.exec_prefix],
    trace=0,
    count=1)

# run the new command using the given tracer
tracer.run('main()')

# make a report, placing output in the current directory
r = tracer.results()
r.write_results(show_missing=True, coverdir=".")

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

디버깅과 프로파일링 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

디버깅과 프로파일링 »

|

tracemalloc — Trace memory allocations

버전 3.4에 추가.

Source code: Lib/tracemalloc.py [https://github.com/python/cpython/tree/3.7/Lib/tracemalloc.py]

The tracemalloc module is a debug tool to trace memory blocks allocated by Python. It provides the following information:

Traceback where an object was allocated

Statistics on allocated memory blocks per filename and per line number: total size, number and average size of allocated memory blocks

Compute the differences between two snapshots to detect memory leaks

To trace most memory blocks allocated by Python, the module should be started as early as possible by setting the PYTHONTRACEMALLOC environment variable to 1, or by using -X tracemalloc command line option. The tracemalloc.start() function can be called at runtime to start tracing Python memory allocations.

By default, a trace of an allocated memory block only stores the most recent frame (1 frame). To store 25 frames at startup: set the PYTHONTRACEMALLOC environment variable to 25, or use the -X tracemalloc=25 command line option.

Examples

Display the top 10

Display the 10 files allocating the most memory:

import tracemalloc

tracemalloc.start()

# ... run your application ...

snapshot = tracemalloc.take_snapshot()
top_stats = snapshot.statistics('lineno')

print("[ Top 10 ]")
for stat in top_stats[:10]:
    print(stat)

Example of output of the Python test suite:

[ Top 10 ]
<frozen importlib._bootstrap>:716: size=4855 KiB, count=39328, average=126 B
<frozen importlib._bootstrap>:284: size=521 KiB, count=3199, average=167 B
/usr/lib/python3.4/collections/__init__.py:368: size=244 KiB, count=2315, average=108 B
/usr/lib/python3.4/unittest/case.py:381: size=185 KiB, count=779, average=243 B
/usr/lib/python3.4/unittest/case.py:402: size=154 KiB, count=378, average=416 B
/usr/lib/python3.4/abc.py:133: size=88.7 KiB, count=347, average=262 B
<frozen importlib._bootstrap>:1446: size=70.4 KiB, count=911, average=79 B
<frozen importlib._bootstrap>:1454: size=52.0 KiB, count=25, average=2131 B
<string>:5: size=49.7 KiB, count=148, average=344 B
/usr/lib/python3.4/sysconfig.py:411: size=48.0 KiB, count=1, average=48.0 KiB

We can see that Python loaded 4855 KiB data (bytecode and constants) from modules and that the collections module allocated 244 KiB to build namedtuple types.

See Snapshot.statistics() for more options.

Compute differences

Take two snapshots and display the differences:

import tracemalloc
tracemalloc.start()
# ... start your application ...

snapshot1 = tracemalloc.take_snapshot()
# ... call the function leaking memory ...
snapshot2 = tracemalloc.take_snapshot()

top_stats = snapshot2.compare_to(snapshot1, 'lineno')

print("[ Top 10 differences ]")
for stat in top_stats[:10]:
    print(stat)

Example of output before/after running some tests of the Python test suite:

[ Top 10 differences ]
<frozen importlib._bootstrap>:716: size=8173 KiB (+4428 KiB), count=71332 (+39369), average=117 B
/usr/lib/python3.4/linecache.py:127: size=940 KiB (+940 KiB), count=8106 (+8106), average=119 B
/usr/lib/python3.4/unittest/case.py:571: size=298 KiB (+298 KiB), count=589 (+589), average=519 B
<frozen importlib._bootstrap>:284: size=1005 KiB (+166 KiB), count=7423 (+1526), average=139 B
/usr/lib/python3.4/mimetypes.py:217: size=112 KiB (+112 KiB), count=1334 (+1334), average=86 B
/usr/lib/python3.4/http/server.py:848: size=96.0 KiB (+96.0 KiB), count=1 (+1), average=96.0 KiB
/usr/lib/python3.4/inspect.py:1465: size=83.5 KiB (+83.5 KiB), count=109 (+109), average=784 B
/usr/lib/python3.4/unittest/mock.py:491: size=77.7 KiB (+77.7 KiB), count=143 (+143), average=557 B
/usr/lib/python3.4/urllib/parse.py:476: size=71.8 KiB (+71.8 KiB), count=969 (+969), average=76 B
/usr/lib/python3.4/contextlib.py:38: size=67.2 KiB (+67.2 KiB), count=126 (+126), average=546 B

We can see that Python has loaded 8173 KiB of module data (bytecode and constants), and that this is 4428 KiB more than had been loaded before the tests, when the previous snapshot was taken. Similarly, the linecache module has cached 940 KiB of Python source code to format tracebacks, all of it since the previous snapshot.

If the system has little free memory, snapshots can be written on disk using the Snapshot.dump() method to analyze the snapshot offline. Then use the Snapshot.load() method reload the snapshot.

Get the traceback of a memory block

Code to display the traceback of the biggest memory block:

import tracemalloc

# Store 25 frames
tracemalloc.start(25)

# ... run your application ...

snapshot = tracemalloc.take_snapshot()
top_stats = snapshot.statistics('traceback')

# pick the biggest memory block
stat = top_stats[0]
print("%s memory blocks: %.1f KiB" % (stat.count, stat.size / 1024))
for line in stat.traceback.format():
    print(line)

Example of output of the Python test suite (traceback limited to 25 frames):

903 memory blocks: 870.1 KiB
  File "<frozen importlib._bootstrap>", line 716
  File "<frozen importlib._bootstrap>", line 1036
  File "<frozen importlib._bootstrap>", line 934
  File "<frozen importlib._bootstrap>", line 1068
  File "<frozen importlib._bootstrap>", line 619
  File "<frozen importlib._bootstrap>", line 1581
  File "<frozen importlib._bootstrap>", line 1614
  File "/usr/lib/python3.4/doctest.py", line 101
    import pdb
  File "<frozen importlib._bootstrap>", line 284
  File "<frozen importlib._bootstrap>", line 938
  File "<frozen importlib._bootstrap>", line 1068
  File "<frozen importlib._bootstrap>", line 619
  File "<frozen importlib._bootstrap>", line 1581
  File "<frozen importlib._bootstrap>", line 1614
  File "/usr/lib/python3.4/test/support/__init__.py", line 1728
    import doctest
  File "/usr/lib/python3.4/test/test_pickletools.py", line 21
    support.run_doctest(pickletools)
  File "/usr/lib/python3.4/test/regrtest.py", line 1276
    test_runner()
  File "/usr/lib/python3.4/test/regrtest.py", line 976
    display_failure=not verbose)
  File "/usr/lib/python3.4/test/regrtest.py", line 761
    match_tests=ns.match_tests)
  File "/usr/lib/python3.4/test/regrtest.py", line 1563
    main()
  File "/usr/lib/python3.4/test/__main__.py", line 3
    regrtest.main_in_temp_cwd()
  File "/usr/lib/python3.4/runpy.py", line 73
    exec(code, run_globals)
  File "/usr/lib/python3.4/runpy.py", line 160
    "__main__", fname, loader, pkg_name)

We can see that the most memory was allocated in the importlib module to load data (bytecode and constants) from modules: 870.1 KiB. The traceback is where the importlib loaded data most recently: on the import pdb line of the doctest module. The traceback may change if a new module is loaded.

Pretty top

Code to display the 10 lines allocating the most memory with a pretty output, ignoring <frozen importlib._bootstrap> and <unknown> files:

import linecache
import os
import tracemalloc

def display_top(snapshot, key_type='lineno', limit=10):
    snapshot = snapshot.filter_traces((
        tracemalloc.Filter(False, "<frozen importlib._bootstrap>"),
        tracemalloc.Filter(False, "<unknown>"),
    ))
    top_stats = snapshot.statistics(key_type)

    print("Top %s lines" % limit)
    for index, stat in enumerate(top_stats[:limit], 1):
        frame = stat.traceback[0]
        print("#%s: %s:%s: %.1f KiB"
              % (index, frame.filename, frame.lineno, stat.size / 1024))
        line = linecache.getline(frame.filename, frame.lineno).strip()
        if line:
            print('    %s' % line)

    other = top_stats[limit:]
    if other:
        size = sum(stat.size for stat in other)
        print("%s other: %.1f KiB" % (len(other), size / 1024))
    total = sum(stat.size for stat in top_stats)
    print("Total allocated size: %.1f KiB" % (total / 1024))

tracemalloc.start()

# ... run your application ...

snapshot = tracemalloc.take_snapshot()
display_top(snapshot)

Example of output of the Python test suite:

Top 10 lines
#1: Lib/base64.py:414: 419.8 KiB
    _b85chars2 = [(a + b) for a in _b85chars for b in _b85chars]
#2: Lib/base64.py:306: 419.8 KiB
    _a85chars2 = [(a + b) for a in _a85chars for b in _a85chars]
#3: collections/__init__.py:368: 293.6 KiB
    exec(class_definition, namespace)
#4: Lib/abc.py:133: 115.2 KiB
    cls = super().__new__(mcls, name, bases, namespace)
#5: unittest/case.py:574: 103.1 KiB
    testMethod()
#6: Lib/linecache.py:127: 95.4 KiB
    lines = fp.readlines()
#7: urllib/parse.py:476: 71.8 KiB
    for a in _hexdig for b in _hexdig}
#8: <string>:5: 62.0 KiB
#9: Lib/_weakrefset.py:37: 60.0 KiB
    self.data = set()
#10: Lib/base64.py:142: 59.8 KiB
    _b32tab2 = [a + b for a in _b32tab for b in _b32tab]
6220 other: 3602.8 KiB
Total allocated size: 5303.1 KiB

See Snapshot.statistics() for more options.

API

Functions

tracemalloc.clear_traces()

Clear traces of memory blocks allocated by Python.

See also stop().

tracemalloc.get_object_traceback(obj)

Get the traceback where the Python object obj was allocated. Return a Traceback instance, or None if the tracemalloc module is not tracing memory allocations or did not trace the allocation of the object.

See also gc.get_referrers() and sys.getsizeof() functions.

tracemalloc.get_traceback_limit()

Get the maximum number of frames stored in the traceback of a trace.

The tracemalloc module must be tracing memory allocations to get the limit, otherwise an exception is raised.

The limit is set by the start() function.

tracemalloc.get_traced_memory()

Get the current size and peak size of memory blocks traced by the tracemalloc module as a tuple: (current: int, peak: int).

tracemalloc.get_tracemalloc_memory()

Get the memory usage in bytes of the tracemalloc module used to store traces of memory blocks. Return an int.

tracemalloc.is_tracing()

True if the tracemalloc module is tracing Python memory allocations, False otherwise.

See also start() and stop() functions.

tracemalloc.start(nframe: int=1)

Start tracing Python memory allocations: install hooks on Python memory allocators. Collected tracebacks of traces will be limited to nframe frames. By default, a trace of a memory block only stores the most recent frame: the limit is 1. nframe must be greater or equal to 1.

Storing more than 1 frame is only useful to compute statistics grouped by 'traceback' or to compute cumulative statistics: see the Snapshot.compare_to() and Snapshot.statistics() methods.

Storing more frames increases the memory and CPU overhead of the tracemalloc module. Use the get_tracemalloc_memory() function to measure how much memory is used by the tracemalloc module.

The PYTHONTRACEMALLOC environment variable (PYTHONTRACEMALLOC=NFRAME) and the -X tracemalloc=NFRAME command line option can be used to start tracing at startup.

See also stop(), is_tracing() and get_traceback_limit() functions.

tracemalloc.stop()

Stop tracing Python memory allocations: uninstall hooks on Python memory allocators. Also clears all previously collected traces of memory blocks allocated by Python.

Call take_snapshot() function to take a snapshot of traces before clearing them.

See also start(), is_tracing() and clear_traces() functions.

tracemalloc.take_snapshot()

Take a snapshot of traces of memory blocks allocated by Python. Return a new Snapshot instance.

The snapshot does not include memory blocks allocated before the tracemalloc module started to trace memory allocations.

Tracebacks of traces are limited to get_traceback_limit() frames. Use the nframe parameter of the start() function to store more frames.

The tracemalloc module must be tracing memory allocations to take a snapshot, see the start() function.

See also the get_object_traceback() function.

DomainFilter

class tracemalloc.DomainFilter(inclusive: bool, domain: int)

Filter traces of memory blocks by their address space (domain).

버전 3.6에 추가.

inclusive

If inclusive is True (include), match memory blocks allocated in the address space domain.

If inclusive is False (exclude), match memory blocks not allocated in the address space domain.

domain

Address space of a memory block (int). Read-only property.

Filter

class tracemalloc.Filter(inclusive: bool, filename_pattern: str, lineno: int=None, all_frames: bool=False, domain: int=None)

Filter on traces of memory blocks.

See the fnmatch.fnmatch() function for the syntax of filename_pattern. The '.pyc' file extension is replaced with '.py'.

Examples:

Filter(True, subprocess.__file__) only includes traces of the subprocess module

Filter(False, tracemalloc.__file__) excludes traces of the tracemalloc module

Filter(False, "<unknown>") excludes empty tracebacks

버전 3.5에서 변경: The '.pyo' file extension is no longer replaced with '.py'.

버전 3.6에서 변경: Added the domain attribute.

domain

Address space of a memory block (int or None).

tracemalloc uses the domain 0 to trace memory allocations made by Python. C extensions can use other domains to trace other resources.

inclusive

If inclusive is True (include), only match memory blocks allocated in a file with a name matching filename_pattern at line number lineno.

If inclusive is False (exclude), ignore memory blocks allocated in a file with a name matching filename_pattern at line number lineno.

lineno

Line number (int) of the filter. If lineno is None, the filter matches any line number.

filename_pattern

Filename pattern of the filter (str). Read-only property.

all_frames

If all_frames is True, all frames of the traceback are checked. If all_frames is False, only the most recent frame is checked.

This attribute has no effect if the traceback limit is 1. See the get_traceback_limit() function and Snapshot.traceback_limit attribute.

Frame

class tracemalloc.Frame

Frame of a traceback.

The Traceback class is a sequence of Frame instances.

filename

Filename (str).

lineno

Line number (int).

Snapshot

class tracemalloc.Snapshot

Snapshot of traces of memory blocks allocated by Python.

The take_snapshot() function creates a snapshot instance.

compare_to(old_snapshot: Snapshot, key_type: str, cumulative: bool=False)

Compute the differences with an old snapshot. Get statistics as a sorted list of StatisticDiff instances grouped by key_type.

See the Snapshot.statistics() method for key_type and cumulative parameters.

The result is sorted from the biggest to the smallest by: absolute value of StatisticDiff.size_diff, StatisticDiff.size, absolute value of StatisticDiff.count_diff, Statistic.count and then by StatisticDiff.traceback.

dump(filename)

Write the snapshot into a file.

Use load() to reload the snapshot.

filter_traces(filters)

Create a new Snapshot instance with a filtered traces sequence, filters is a list of DomainFilter and Filter instances. If filters is an empty list, return a new Snapshot instance with a copy of the traces.

All inclusive filters are applied at once, a trace is ignored if no inclusive filters match it. A trace is ignored if at least one exclusive filter matches it.

버전 3.6에서 변경: DomainFilter instances are now also accepted in filters.

classmethod load(filename)

Load a snapshot from a file.

See also dump().

statistics(key_type: str, cumulative: bool=False)

Get statistics as a sorted list of Statistic instances grouped by key_type:

key_type

description

'filename'

filename

'lineno'

filename and line number

'traceback'

traceback

If cumulative is True, cumulate size and count of memory blocks of all frames of the traceback of a trace, not only the most recent frame. The cumulative mode can only be used with key_type equals to 'filename' and 'lineno'.

The result is sorted from the biggest to the smallest by: Statistic.size, Statistic.count and then by Statistic.traceback.

traceback_limit

Maximum number of frames stored in the traceback of traces: result of the get_traceback_limit() when the snapshot was taken.

traces

Traces of all memory blocks allocated by Python: sequence of Trace instances.

The sequence has an undefined order. Use the Snapshot.statistics() method to get a sorted list of statistics.

Statistic

class tracemalloc.Statistic

Statistic on memory allocations.

Snapshot.statistics() returns a list of Statistic instances.

See also the StatisticDiff class.

count

Number of memory blocks (int).

size

Total size of memory blocks in bytes (int).

traceback

Traceback where the memory block was allocated, Traceback instance.

StatisticDiff

class tracemalloc.StatisticDiff

Statistic difference on memory allocations between an old and a new Snapshot instance.

Snapshot.compare_to() returns a list of StatisticDiff instances. See also the Statistic class.

count

Number of memory blocks in the new snapshot (int): 0 if the memory blocks have been released in the new snapshot.

count_diff

Difference of number of memory blocks between the old and the new snapshots (int): 0 if the memory blocks have been allocated in the new snapshot.

size

Total size of memory blocks in bytes in the new snapshot (int): 0 if the memory blocks have been released in the new snapshot.

size_diff

Difference of total size of memory blocks in bytes between the old and the new snapshots (int): 0 if the memory blocks have been allocated in the new snapshot.

traceback

Traceback where the memory blocks were allocated, Traceback instance.

Trace

class tracemalloc.Trace

Trace of a memory block.

The Snapshot.traces attribute is a sequence of Trace instances.

버전 3.6에서 변경: Added the domain attribute.

domain

Address space of a memory block (int). Read-only property.

tracemalloc uses the domain 0 to trace memory allocations made by Python. C extensions can use other domains to trace other resources.

size

Size of the memory block in bytes (int).

traceback

Traceback where the memory block was allocated, Traceback instance.

Traceback

class tracemalloc.Traceback

Sequence of Frame instances sorted from the oldest frame to the most recent frame.

A traceback contains at least 1 frame. If the tracemalloc module failed to get a frame, the filename "<unknown>" at line number 0 is used.

When a snapshot is taken, tracebacks of traces are limited to get_traceback_limit() frames. See the take_snapshot() function.

The Trace.traceback attribute is an instance of Traceback instance.

버전 3.7에서 변경: Frames are now sorted from the oldest to the most recent, instead of most recent to oldest.

format(limit=None, most_recent_first=False)

Format the traceback as a list of lines with newlines. Use the linecache module to retrieve lines from the source code. If limit is set, format the limit most recent frames if limit is positive. Otherwise, format the abs(limit) oldest frames. If most_recent_first is True, the order of the formatted frames is reversed, returning the most recent frame first instead of last.

Similar to the traceback.format_tb() function, except that format() does not include newlines.

Example:

print("Traceback (most recent call first):")
for line in traceback:
    print(line)

Output:

Traceback (most recent call first):
  File "test.py", line 9
    obj = Object()
  File "test.py", line 12
    tb = tracemalloc.get_object_traceback(f())

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

디버깅과 프로파일링 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

|

소프트웨어 패키징 및 배포

이 라이브러리는 파이썬 소프트웨어를 게시하고 설치하는 데 도움을 줍니다. 이 모듈은 파이썬 패키지 색인 [https://pypi.org]과 함께 작동하도록 설계되었지만, 로컬 색인 서버와 함께 사용할 수도, 색인 서버 없이 사용할 수도 있습니다.

distutils — 파이썬 모듈 빌드와 설치

ensurepip — pip 설치 프로그램 부트스트랩

명령 줄 인터페이스

모듈 API

venv — 가상 환경 생성

가상 환경 만들기

API

EnvBuilder 확장 예제

zipapp — Manage executable Python zip archives

Basic Example

Command-Line Interface

Python API

Examples

Specifying the Interpreter

Creating Standalone Applications with zipapp

Making a Windows executable

Caveats

The Python Zip Application Archive Format

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

소프트웨어 패키징 및 배포 »

|

distutils — 파이썬 모듈 빌드와 설치

distutils 패키지는 파이썬 설치에 추가 모듈을 빌드하고 설치하는 것을 지원합니다. 새 모듈은 100% 순수 파이썬이거나 C로 작성된 확장 모듈일 수도 있고, 파이썬과 C로 코딩된 모듈을 포함하는 파이썬 패키지 모음일 수도 있습니다.

대부분 파이썬 사용자는 직접 이 모듈을 사용하려고 하지 않을겁니다, 대신 파이썬 패키징 위원회가 유지하는 교차 버전 도구를 사용합니다. 특히, setuptools [https://setuptools.readthedocs.io/en/latest/]는 다음을 제공하는 distutils의 향상된 대안입니다:

프로젝트 의존성 선언 지원

소스 배포에 포함할 파일을 구성하기 위한 추가 메커니즘 (버전 제어 시스템과의 통합을 위한 플러그인 포함)

응용 프로그램 플러그인 시스템의 기초로 사용할 수 있는 프로젝트 “진입점”을 선언할 수 있는 능력

미리 빌드 할 필요 없이, 설치 시 윈도우 명령 줄 실행 파일을 자동으로 생성하는 능력

지원되는 모든 파이썬 버전에서 일관된 동작

권장되는 pip [https://pip.pypa.io/] 설치 관리자는 setuptools로 모든 setup.py 스크립트를 실행합니다. 스크립트 자체가 distutils 만 임포트 할 때조차 그렇습니다. 자세한 내용은 파이썬 패키징 사용자 지침서 [https://packaging.python.org]를 참조하십시오.

패키징 도구 작성자와 현재 패키징과 배포 시스템의 세부 사항을 더 깊이 이해하고자 하는 사용자를 위해, 기존의 distutils 기반 사용자 설명서와 API 레퍼런스를 계속 제공합니다:

파이썬 모듈 설치 (레거시 버전)

파이썬 모듈 배포 (레거시 버전)

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

소프트웨어 패키징 및 배포 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

소프트웨어 패키징 및 배포 »

|

ensurepip — pip 설치 프로그램 부트스트랩

버전 3.4에 추가.

ensurepip 패키지는 pip 설치 프로그램을 기존의 파이썬 설치나 가상 환경으로 부트스트랩 하는데 필요한 지원을 제공합니다. 이 부트스트랩 접근 방식은 pip가 자체 배포 주기가 있는 독립적인 프로젝트이며, 최신 사용 가능한 안정 버전이 CPython 참조 인터프리터의 유지 보수와 기능 배포에 번들로 제공된다는 사실을 반영합니다.

대부분, 파이썬의 최종 사용자는 이 모듈을 직접 호출할 필요가 없습니다 (pip는 기본적으로 부트스트랩 되어있어야 하기 때문입니다). 하지만, 파이썬을 설치할 때 (또는 가상 환경을 만들 때) pip를 건너뛰었거나 그 후에 명시적으로 pip를 제거했다면 필요할 수 있습니다.

참고

이 모듈은 인터넷에 접속하지 않습니다. pip를 부트스트랩 하는 데 필요한 모든 구성 요소는 패키지의 내부 부품으로 포함됩니다.

더 보기

파이썬 모듈 설치하기

파이썬 패키지를 설치하기 위한 최종 사용자 지침서

PEP 453 [https://www.python.org/dev/peps/pep-0453]: 파이썬 설치에서 pip의 명시적 부트스트랩

이 모듈의 원래 근거와 사양.

명령 줄 인터페이스

명령 줄 인터페이스는 인터프리터의 -m 스위치를 사용하여 호출됩니다.

가장 간단한 호출은 이렇습니다:

python -m ensurepip

이 호출은 아직 설치되지 않았으면 pip를 설치하지만, 그렇지 않으면 아무것도 하지 않습니다. pip의 설치 버전이 적어도 ensurepip에 번들 된 최신 버전이 되도록 하려면, --upgrade 옵션을 전달하십시오:

python -m ensurepip --upgrade

기본적으로, pip는 현재 가상 환경(활성화되었다면)이나 시스템 사이트 패키지(활성 가상 환경이 없으면)에 설치됩니다. 설치 위치는 두 개의 추가 명령 줄 옵션을 통해 제어할 수 있습니다:

--root <dir>: 현재 활성화된 가상 환경의 루트(있다면)나 현재 파이썬 설치의 기본 루트 대신, 지정된 루트 디렉터리에 상대적으로 pip를 설치합니다.

--user: pip를 현재 파이썬 설치에 전역적으로 설치하지 않고 사용자 사이트 패키지 디렉터리에 설치합니다 (이 옵션은 활성 가상 환경에서는 허용되지 않습니다).

기본적으로, pipX 와 pipX.Y 스크립트가 설치됩니다 (여기서 X.Y는 ensurepip를 호출하는 데 사용된 파이썬 버전을 나타냅니다). 설치된 스크립트는 두 개의 추가 명령 줄 옵션을 통해 제어할 수 있습니다:

--altinstall: 대안 설치가 요청되면, pipX 스크립트가 설치되지 않습니다.

--default-pip: if a “default pip” installation is requested, the pip script will be installed in addition to the two regular scripts.

두 스크립트 선택 옵션을 모두 제공하면 예외가 발생합니다.

모듈 API

ensurepip는 프로그래밍 방식으로 사용하기 위해 두 가지 함수를 제공합니다:

ensurepip.version()

환경을 부트스트랩 할 때 설치될 pip의 번들 버전을 지정하는 문자열을 반환합니다.

ensurepip.bootstrap(root=None, upgrade=False, user=False, altinstall=False, default_pip=False, verbosity=0)

pip를 현재나 지정된 환경으로 부트스트랩 합니다.

root는 상대 경로로 설치할 대안 루트 디렉터리를 지정합니다. root가 None이면, 설치는 현재 환경의 기본 설치 위치를 사용합니다.

upgrade는 이미 설치된 이전 버전의 pip를 번들 된 버전으로 업그레이드할지를 나타냅니다.

user는 전역으로 설치하는 대신 사용자 구성을 사용할지를 나타냅니다.

기본적으로, pipX 및 pipX.Y 스크립트가 설치됩니다 (여기서 X.Y는 현재 버전의 파이썬을 나타냅니다).

altinstall가 설정되면, pipX가 설치되지 않습니다.

default_pip가 설정되면, 두 개의 일반 스크립트에 더해 pip가 설치됩니다.

altinstall 과 default_pip를 모두 설정하면 ValueError가 발생합니다.

verbosity는 부트스트랩 연산에서 sys.stdout로 출력하는 수준을 제어합니다.

참고

부트스트랩 프로세스에는 sys.path 와 os.environ 모두에 부작용이 있습니다. 대신 자식 프로세스에서 명령 줄 인터페이스를 호출하면 이러한 부작용을 피할 수 있습니다.

참고

부트스트랩 프로세스는 pip에 필요한 추가 모듈을 설치할 수 있지만, 다른 소프트웨어는 이러한 종속성이 기본적으로 항상 존재한다고 가정해서는 안 됩니다 (pip의 차후 버전에서 제거될 수 있기 때문입니다).

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

소프트웨어 패키징 및 배포 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

소프트웨어 패키징 및 배포 »

|

venv — 가상 환경 생성

버전 3.3에 추가.

소스 코드: Lib/venv/ [https://github.com/python/cpython/tree/3.7/Lib/venv/]

venv 모듈은 자체 사이트 디렉터리를 갖는 경량 “가상 환경”을 만들고, 선택적으로 시스템 사이트 디렉터리에서 격리할 수 있도록 지원합니다. 각 가상 환경은 고유한 파이썬 바이너리(이 환경을 만드는 데 사용된 바이너리 버전과 일치함)를 가지며 자신의 사이트 디렉터리에 독립적으로 설치된 파이썬 패키지 집합을 가질 수 있습니다.

파이썬 가상 환경에 대한 자세한 내용은 PEP 405 [https://www.python.org/dev/peps/pep-0405]를 참조하십시오.

더 보기

Python Packaging User Guide: Creating and using virtual environments [https://packaging.python.org/installing/#creating-virtual-environments]

참고

pyvenv 스크립트는 파이썬 3.6 에서 폐지되었고, 가상 환경이 어떤 파이썬 인터프리터를 기반으로 하는지에 대한 잠재적인 혼동을 방지하기 위해 python3 -m venv를 사용합니다.

가상 환경 만들기

가상 환경은 venv 명령을 실행해서 만들어집니다:

python3 -m venv /path/to/new/virtual/environment

이 명령을 실행하면 대상 디렉터리가 만들어지고 (이미 존재하지 않는 부모 디렉터리도 만듭니다) 명령이 실행된 파이썬 설치를 가리키는 home 키가 있는 pyvenv.cfg 파일이 배치됩니다. 또한 파이썬 바이너리/바이너리들의 사본/심볼릭 링크를 포함하는 bin (또는 윈도우의 경우 Scripts) 서브 디렉터리를 만듭니다 (플랫폼이나 환경 생성 시에 사용된 인자에 적절하게). 또한 (처음에는 비어있는) lib/pythonX.Y/site-packages (윈도우에서는, Lib\site-packages) 서브 디렉터리를 만듭니다. 기존 디렉터리가 지정되면 재사용됩니다.

버전 3.6부터 폐지: pyvenv는 파이썬 3.3 및 3.4 용 가상 환경을 만드는 데 권장되는 도구였으며, 파이썬 3.6 에서 폐지되었습니다 [https://docs.python.org/dev/whatsnew/3.6.html#deprecated-features].

버전 3.5에서 변경: 이제 가상 환경을 만들 때 venv를 사용하는 것이 좋습니다.

윈도우에서는, 다음과 같이 venv 명령을 호출하십시오:

c:\>c:\Python35\python -m venv c:\path\to\myenv

또는, 여러분의 파이썬 설치에 PATH 와 PATHEXT 변수를 구성했으면:

c:\>python -m venv c:\path\to\myenv

명령에 -h를 사용하면 사용 가능한 옵션이 표시됩니다:

usage: venv [-h] [--system-site-packages] [--symlinks | --copies] [--clear]
            [--upgrade] [--without-pip] [--prompt PROMPT]
            ENV_DIR [ENV_DIR ...]

Creates virtual Python environments in one or more target directories.

positional arguments:
  ENV_DIR               A directory to create the environment in.

optional arguments:
  -h, --help            show this help message and exit
  --system-site-packages
                        Give the virtual environment access to the system
                        site-packages dir.
  --symlinks            Try to use symlinks rather than copies, when symlinks
                        are not the default for the platform.
  --copies              Try to use copies rather than symlinks, even when
                        symlinks are the default for the platform.
  --clear               Delete the contents of the environment directory if it
                        already exists, before environment creation.
  --upgrade             Upgrade the environment directory to use this version
                        of Python, assuming Python has been upgraded in-place.
  --without-pip         Skips installing or upgrading pip in the virtual
                        environment (pip is bootstrapped by default)
  --prompt PROMPT       Provides an alternative prompt prefix for this
                        environment.

Once an environment has been created, you may wish to activate it, e.g. by
sourcing an activate script in its bin directory.

버전 3.4에서 변경: 기본적으로 pip을 설치합니다. --without-pip 와 --copies 옵션을 추가했습니다.

버전 3.4에서 변경: 이전 버전에서는, --clear 나 --upgrade 옵션이 제공되지 않았을 때, 대상 디렉터리가 이미 존재하면 에러가 발생했습니다.

참고

심볼릭 링크가 윈도우에서 지원되지만, 추천하지는 않습니다. 특히 파일 탐색기에서 python.exe를 더블 클릭하면 심볼릭 링크를 열심히 따라가고(resolve) 가상 환경은 무시됩니다.

만들어진 pyvenv.cfg 파일에는 include-system-site-packages 키도 포함되어 있으며, venv가 --system-site-packages 옵션으로 실행되면 true로 설정되고, 그렇지 않으면 false로 설정됩니다.

--without-pip 옵션을 주지 않는 한, 가상 환경으로 pip을 부트스트랩 하기 위해 ensurepip가 호출됩니다.

venv에 여러 경로를 지정할 수 있습니다. 이때 지정된 옵션에 따라 제공된 각 경로에서 같은 가상 환경이 만들어집니다.

일단 가상 환경이 만들어지면, 가상 환경의 바이너리 디렉터리에 있는 스크립트를 사용하여 “활성화”할 수 있습니다. 스크립트의 호출은 플랫폼에 따라 다릅니다 (<venv>는 가상 환경을 포함하는 디렉터리의 경로로 대체되어야 합니다):

플랫폼

셸

가상 환경을 활성화하는 명령

Posix

bash/zsh

$ source <venv>/bin/activate

fish

$ . <venv>/bin/activate.fish

csh/tcsh

$ source <venv>/bin/activate.csh

윈도우

cmd.exe

C:\> <venv>\Scripts\activate.bat

PowerShell

PS C:\> <venv>\Scripts\Activate.ps1

환경을 구체적으로 활성화할 필요는 없습니다; 활성화는 단지 PATH의 처음에 가상 환경의 바이너리 디렉터리를 추가해서, “python”이 가상 환경의 파이썬 인터프리터를 호출하고 전체 경로를 사용하지 않고도 설치된 스크립트를 실행할 수 있도록 할 뿐입니다. 그러나, 가상 환경에 설치된 모든 스크립트는 활성화하지 않고도 실행 가능해야 하며, 자동으로 가상 환경의 파이썬을 사용하여 실행해야 합니다.

You can deactivate a virtual environment by typing “deactivate” in your shell. The exact mechanism is platform-specific and is an internal implementation detail (typically a script or shell function will be used).

버전 3.4에 추가: fish 와 csh 활성화 스크립트.

참고

가상 환경은 파이썬 인터프리터, 라이브러리 및 스크립트가 다른 가상 환경에 설치된 것과 (기본적으로) “시스템” 파이썬(즉, 여러분의 운영 체제 일부로 설치되어있는 것)에 설치된 모든 라이브러리와 격리되어있는 파이썬 환경입니다.

가상 환경은 파이썬 실행 파일과 가상 환경임을 나타내는 다른 파일을 포함하는 디렉터리 트리입니다.

Common installation tools such as setuptools [https://pypi.org/project/setuptools/] and pip [https://pypi.org/project/pip/] work as expected with virtual environments. In other words, when a virtual environment is active, they install Python packages into the virtual environment without needing to be told to do so explicitly.

가상 환경이 활성일 때 (즉, 가상 환경의 파이썬 인터프리터가 실행 중일 때), 어트리뷰트 sys.prefix 와 sys.exec_prefix는 가상 환경의 베이스 디렉터리를 가리키지만, sys.base_prefix와 sys.base_exec_prefix는 가상 환경을 만들 때 사용한 가상이 아닌 환경의 파이썬을 가리킵니다. 가상 환경이 활성화되어 있지 않으면, sys.prefix는 sys.base_prefix와 같고, sys.exec_prefix는 sys.base_exec_prefix와 같습니다 (모두 가상 환경이 아닌 파이썬 설치를 가리킵니다).

When a virtual environment is active, any options that change the installation path will be ignored from all distutils configuration files to prevent projects being inadvertently installed outside of the virtual environment.

When working in a command shell, users can make a virtual environment active by running an activate script in the virtual environment’s executables directory (the precise filename and command to use the file is shell-dependent), which prepends the virtual environment’s directory for executables to the PATH environment variable for the running shell. There should be no need in other circumstances to activate a virtual environment; scripts installed into virtual environments have a “shebang” line which points to the virtual environment’s Python interpreter. This means that the script will run with that interpreter regardless of the value of PATH. On Windows, “shebang” line processing is supported if you have the Python Launcher for Windows installed (this was added to Python in 3.3 - see PEP 397 [https://www.python.org/dev/peps/pep-0397] for more details). Thus, double-clicking an installed script in a Windows Explorer window should run the script with the correct interpreter without there needing to be any reference to its virtual environment in PATH.

API

위에서 설명한 고수준 메서드는 제삼자 가상 환경 작성자가 필요에 따라 환경을 사용자 정의할 수 있는 메커니즘을 제공하는 간단한 API를 사용합니다: EnvBuilder 클래스.

class venv.EnvBuilder(system_site_packages=False, clear=False, symlinks=False, upgrade=False, with_pip=False, prompt=None)

EnvBuilder 클래스는 인스턴스를 만들 때 다음 키워드 인자를 받아들입니다:

system_site_packages – 시스템 파이썬 site-packages가 환경에서 사용 가능해야 함을 나타내는 논릿값입니다 (기본값은 False).

clear – 참이면, 환경을 만들기 전에, 대상 디렉터리에 존재하는 내용을 지우도록 하는 논릿값.

symlinks – 파이썬 바이너리를 복사하는 대신 심볼릭 링크하려고 시도할지를 나타내는 논릿값입니다.

upgrade – 참이면 실행 중인 파이썬으로 기존 환경을 업그레이드하도록 하는 논릿값 - 파이썬이 그 자리에서 업그레이드되었을 때 사용됩니다 (기본값은 False).

with_pip – 참이면 가상 환경에 pip이 설치되도록 하는 논릿값입니다. --default-pip 옵션과 함께 ensurepip를 사용합니다.

prompt – 가상 환경이 활성화된 후 사용할 문자열입니다 (기본값은 환경의 디렉터리 이름이 사용됨을 뜻하는 None입니다).

버전 3.4에서 변경: with_pip 매개 변수 추가

버전 3.6에 추가: prompt 매개 변수 추가

Creators of third-party virtual environment tools will be free to use the provided EnvBuilder class as a base class.

반환된 객체에는 메서드 create가 있습니다:

create(env_dir)

Create a virtual environment by specifying the target directory (absolute or relative to the current directory) which is to contain the virtual environment. The create method will either create the environment in the specified directory, or raise an appropriate exception.

The create method of the EnvBuilder class illustrates the hooks available for subclass customization:

def create(self, env_dir):
    """
    Create a virtualized Python environment in a directory.
    env_dir is the target directory to create an environment in.
    """
    env_dir = os.path.abspath(env_dir)
    context = self.ensure_directories(env_dir)
    self.create_configuration(context)
    self.setup_python(context)
    self.setup_scripts(context)
    self.post_setup(context)

메서드 ensure_directories(), create_configuration(), setup_python(), setup_scripts() 및 post_setup() 각각을 재정의할 수 있습니다.

ensure_directories(env_dir)

환경 디렉터리와 필요한 모든 디렉터리를 만들고 문맥 객체를 돌려줍니다. 이것은 다른 메서드에서 사용하기 위한 어트리뷰트(가령 경로)를 담고 있을 뿐입니다. 기존 환경 디렉터리에 작동하도록 clear 나 upgrade가 지정되어있는 한, 디렉터리는 이미 존재할 수 있습니다.

create_configuration(context)

환경에 pyvenv.cfg 구성 파일을 만듭니다.

setup_python(context)

환경에 파이썬 실행 파일의 복사본이나 심볼릭 링크를 만듭니다. POSIX 시스템에서, 특정 실행 파일 python3.x가 사용되면, 해당 이름의 파일이 이미 존재하지 않는 한 python 과 python3 심볼릭 링크가 해당 실행 파일을 가리키도록 만들어집니다.

setup_scripts(context)

플랫폼에 적합한 활성화 스크립트를 가상 환경에 설치합니다.

post_setup(context)

제삼자 구현에서 재정의하여 가상 환경에 패키지를 사전 설치하거나 다른 생성 후 단계를 수행할 수 있는 메서드입니다.

버전 3.7.2에서 변경: 윈도우는 이제 실제 바이너리를 복사하는 대신 python[w].exe를 위한 리디렉터 스크립트를 사용합니다. 3.7.2 에서만, 소스 트리의 빌드에서 실행하지 않는 한 setup_python()아무 작업도 수행하지 않습니다.

버전 3.7.3에서 변경: 윈도우는 setup_scripts() 대신 setup_python()의 일부로 리디렉터 스크립트를 복사합니다. 이것은 3.7.2는 해당하지 않습니다. 심볼릭 링크를 사용하면, 원래 실행 파일이 링크됩니다.

또한, EnvBuilder는 가상 환경에 사용자 정의 스크립트를 설치하는 데 도움이 되는 유틸리티 메서드를 제공하는데, 서브 클래스의 setup_scripts() 나 post_setup()에서 호출할 수 있습니다.

install_scripts(context, path)

path는 “common”, “posix”, “nt” 서브 디렉터리를 포함해야 하는 디렉터리 경로입니다. 각 디렉터리에는 환경의 bin 디렉터리로 들어갈 스크립트가 들어 있습니다. “common”과 os.name에 해당하는 디렉터리의 내용은 자리 표시자의 일부 텍스트 치환 후 복사됩니다:

__VENV_DIR__은 환경 디렉터리의 절대 경로로 치환됩니다.

__VENV_NAME__은 환경 이름(환경 디렉터리의 최종 경로 세그먼트)으로 치환됩니다.

__VENV_PROMPT__는 프롬프트(괄호로 묶인 환경 이름과 그 뒤의 스페이스)로 치환됩니다

__VENV_BIN_NAME__은 bin 디렉터리의 이름(bin 이나 Scripts)으로 치환됩니다.

__VENV_PYTHON__은 환경의 실행 파일의 절대 경로로 치환됩니다.

디렉터리는 존재하는 것이 허용됩니다 (기존 환경이 업그레이드될 때).

모듈 수준의 편리 함수도 있습니다:

venv.create(env_dir, system_site_packages=False, clear=False, symlinks=False, with_pip=False, prompt=None)

주어진 키워드 인자로 EnvBuilder를 만들고, env_dir 인자로 create() 메서드를 호출합니다.

버전 3.3에 추가.

버전 3.4에서 변경: with_pip 매개 변수 추가

버전 3.6에서 변경: prompt 매개 변수 추가

EnvBuilder 확장 예제

다음 스크립트는 생성된 가상 환경에 setuptools 와 pip을 설치하는 서브 클래스를 구현하여 EnvBuilder를 확장하는 방법을 보여줍니다:

import os
import os.path
from subprocess import Popen, PIPE
import sys
from threading import Thread
from urllib.parse import urlparse
from urllib.request import urlretrieve
import venv

class ExtendedEnvBuilder(venv.EnvBuilder):
    """
    This builder installs setuptools and pip so that you can pip or
    easy_install other packages into the created virtual environment.

    :param nodist: If true, setuptools and pip are not installed into the
                   created virtual environment.
    :param nopip: If true, pip is not installed into the created
                  virtual environment.
    :param progress: If setuptools or pip are installed, the progress of the
                     installation can be monitored by passing a progress
                     callable. If specified, it is called with two
                     arguments: a string indicating some progress, and a
                     context indicating where the string is coming from.
                     The context argument can have one of three values:
                     'main', indicating that it is called from virtualize()
                     itself, and 'stdout' and 'stderr', which are obtained
                     by reading lines from the output streams of a subprocess
                     which is used to install the app.

                     If a callable is not specified, default progress
                     information is output to sys.stderr.
    """

    def __init__(self, *args, **kwargs):
        self.nodist = kwargs.pop('nodist', False)
        self.nopip = kwargs.pop('nopip', False)
        self.progress = kwargs.pop('progress', None)
        self.verbose = kwargs.pop('verbose', False)
        super().__init__(*args, **kwargs)

    def post_setup(self, context):
        """
        Set up any packages which need to be pre-installed into the
        virtual environment being created.

        :param context: The information for the virtual environment
                        creation request being processed.
        """
        os.environ['VIRTUAL_ENV'] = context.env_dir
        if not self.nodist:
            self.install_setuptools(context)
        # Can't install pip without setuptools
        if not self.nopip and not self.nodist:
            self.install_pip(context)

    def reader(self, stream, context):
        """
        Read lines from a subprocess' output stream and either pass to a progress
        callable (if specified) or write progress information to sys.stderr.
        """
        progress = self.progress
        while True:
            s = stream.readline()
            if not s:
                break
            if progress is not None:
                progress(s, context)
            else:
                if not self.verbose:
                    sys.stderr.write('.')
                else:
                    sys.stderr.write(s.decode('utf-8'))
                sys.stderr.flush()
        stream.close()

    def install_script(self, context, name, url):
        _, _, path, _, _, _ = urlparse(url)
        fn = os.path.split(path)[-1]
        binpath = context.bin_path
        distpath = os.path.join(binpath, fn)
        # Download script into the virtual environment's binaries folder
        urlretrieve(url, distpath)
        progress = self.progress
        if self.verbose:
            term = '\n'
        else:
            term = ''
        if progress is not None:
            progress('Installing %s ...%s' % (name, term), 'main')
        else:
            sys.stderr.write('Installing %s ...%s' % (name, term))
            sys.stderr.flush()
        # Install in the virtual environment
        args = [context.env_exe, fn]
        p = Popen(args, stdout=PIPE, stderr=PIPE, cwd=binpath)
        t1 = Thread(target=self.reader, args=(p.stdout, 'stdout'))
        t1.start()
        t2 = Thread(target=self.reader, args=(p.stderr, 'stderr'))
        t2.start()
        p.wait()
        t1.join()
        t2.join()
        if progress is not None:
            progress('done.', 'main')
        else:
            sys.stderr.write('done.\n')
        # Clean up - no longer needed
        os.unlink(distpath)

    def install_setuptools(self, context):
        """
        Install setuptools in the virtual environment.

        :param context: The information for the virtual environment
                        creation request being processed.
        """
        url = 'https://bitbucket.org/pypa/setuptools/downloads/ez_setup.py'
        self.install_script(context, 'setuptools', url)
        # clear up the setuptools archive which gets downloaded
        pred = lambda o: o.startswith('setuptools-') and o.endswith('.tar.gz')
        files = filter(pred, os.listdir(context.bin_path))
        for f in files:
            f = os.path.join(context.bin_path, f)
            os.unlink(f)

    def install_pip(self, context):
        """
        Install pip in the virtual environment.

        :param context: The information for the virtual environment
                        creation request being processed.
        """
        url = 'https://raw.github.com/pypa/pip/master/contrib/get-pip.py'
        self.install_script(context, 'pip', url)

def main(args=None):
    compatible = True
    if sys.version_info < (3, 3):
        compatible = False
    elif not hasattr(sys, 'base_prefix'):
        compatible = False
    if not compatible:
        raise ValueError('This script is only for use with '
                         'Python 3.3 or later')
    else:
        import argparse

        parser = argparse.ArgumentParser(prog=__name__,
                                         description='Creates virtual Python '
                                                     'environments in one or '
                                                     'more target '
                                                     'directories.')
        parser.add_argument('dirs', metavar='ENV_DIR', nargs='+',
                            help='A directory in which to create the
                                 'virtual environment.')
        parser.add_argument('--no-setuptools', default=False,
                            action='store_true', dest='nodist',
                            help="Don't install setuptools or pip in the "
                                 "virtual environment.")
        parser.add_argument('--no-pip', default=False,
                            action='store_true', dest='nopip',
                            help="Don't install pip in the virtual "
                                 "environment.")
        parser.add_argument('--system-site-packages', default=False,
                            action='store_true', dest='system_site',
                            help='Give the virtual environment access to the '
                                 'system site-packages dir.')
        if os.name == 'nt':
            use_symlinks = False
        else:
            use_symlinks = True
        parser.add_argument('--symlinks', default=use_symlinks,
                            action='store_true', dest='symlinks',
                            help='Try to use symlinks rather than copies, '
                                 'when symlinks are not the default for '
                                 'the platform.')
        parser.add_argument('--clear', default=False, action='store_true',
                            dest='clear', help='Delete the contents of the '
                                               'virtual environment '
                                               'directory if it already '
                                               'exists, before virtual '
                                               'environment creation.')
        parser.add_argument('--upgrade', default=False, action='store_true',
                            dest='upgrade', help='Upgrade the virtual '
                                                 'environment directory to '
                                                 'use this version of '
                                                 'Python, assuming Python '
                                                 'has been upgraded '
                                                 'in-place.')
        parser.add_argument('--verbose', default=False, action='store_true',
                            dest='verbose', help='Display the output '
                                               'from the scripts which '
                                               'install setuptools and pip.')
        options = parser.parse_args(args)
        if options.upgrade and options.clear:
            raise ValueError('you cannot supply --upgrade and --clear together.')
        builder = ExtendedEnvBuilder(system_site_packages=options.system_site,
                                       clear=options.clear,
                                       symlinks=options.symlinks,
                                       upgrade=options.upgrade,
                                       nodist=options.nodist,
                                       nopip=options.nopip,
                                       verbose=options.verbose)
        for d in options.dirs:
            builder.create(d)

if __name__ == '__main__':
    rc = 1
    try:
        main()
        rc = 0
    except Exception as e:
        print('Error: %s' % e, file=sys.stderr)
    sys.exit(rc)

이 스크립트는 온라인 [https://gist.github.com/vsajip/4673395]에서 내려받을 수도 있습니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

소프트웨어 패키징 및 배포 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

소프트웨어 패키징 및 배포 »

|

zipapp — Manage executable Python zip archives

버전 3.5에 추가.

Source code: Lib/zipapp.py [https://github.com/python/cpython/tree/3.7/Lib/zipapp.py]

This module provides tools to manage the creation of zip files containing Python code, which can be executed directly by the Python interpreter. The module provides both a Command-Line Interface and a Python API.

Basic Example

The following example shows how the Command-Line Interface can be used to create an executable archive from a directory containing Python code. When run, the archive will execute the main function from the module myapp in the archive.

$ python -m zipapp myapp -m "myapp:main"
$ python myapp.pyz
<output from myapp>

Command-Line Interface

When called as a program from the command line, the following form is used:

$ python -m zipapp source [options]

If source is a directory, this will create an archive from the contents of source. If source is a file, it should be an archive, and it will be copied to the target archive (or the contents of its shebang line will be displayed if the –info option is specified).

The following options are understood:

-o <output>, --output=<output>

Write the output to a file named output. If this option is not specified, the output filename will be the same as the input source, with the extension .pyz added. If an explicit filename is given, it is used as is (so a .pyz extension should be included if required).

An output filename must be specified if the source is an archive (and in that case, output must not be the same as source).

-p <interpreter>, --python=<interpreter>

Add a #! line to the archive specifying interpreter as the command to run. Also, on POSIX, make the archive executable. The default is to write no #! line, and not make the file executable.

-m <mainfn>, --main=<mainfn>

Write a __main__.py file to the archive that executes mainfn. The mainfn argument should have the form “pkg.mod:fn”, where “pkg.mod” is a package/module in the archive, and “fn” is a callable in the given module. The __main__.py file will execute that callable.

--main cannot be specified when copying an archive.

-c, --compress

Compress files with the deflate method, reducing the size of the output file. By default, files are stored uncompressed in the archive.

--compress has no effect when copying an archive.

버전 3.7에 추가.

--info

Display the interpreter embedded in the archive, for diagnostic purposes. In this case, any other options are ignored and SOURCE must be an archive, not a directory.

-h, --help

Print a short usage message and exit.

Python API

The module defines two convenience functions:

zipapp.create_archive(source, target=None, interpreter=None, main=None, filter=None, compressed=False)

Create an application archive from source. The source can be any of the following:

The name of a directory, or a path-like object referring to a directory, in which case a new application archive will be created from the content of that directory.

The name of an existing application archive file, or a path-like object referring to such a file, in which case the file is copied to the target (modifying it to reflect the value given for the interpreter argument). The file name should include the .pyz extension, if required.

A file object open for reading in bytes mode. The content of the file should be an application archive, and the file object is assumed to be positioned at the start of the archive.

The target argument determines where the resulting archive will be written:

If it is the name of a file, or a path-like object, the archive will be written to that file.

If it is an open file object, the archive will be written to that file object, which must be open for writing in bytes mode.

If the target is omitted (or None), the source must be a directory and the target will be a file with the same name as the source, with a .pyz extension added.

The interpreter argument specifies the name of the Python interpreter with which the archive will be executed. It is written as a “shebang” line at the start of the archive. On POSIX, this will be interpreted by the OS, and on Windows it will be handled by the Python launcher. Omitting the interpreter results in no shebang line being written. If an interpreter is specified, and the target is a filename, the executable bit of the target file will be set.

The main argument specifies the name of a callable which will be used as the main program for the archive. It can only be specified if the source is a directory, and the source does not already contain a __main__.py file. The main argument should take the form “pkg.module:callable” and the archive will be run by importing “pkg.module” and executing the given callable with no arguments. It is an error to omit main if the source is a directory and does not contain a __main__.py file, as otherwise the resulting archive would not be executable.

The optional filter argument specifies a callback function that is passed a Path object representing the path to the file being added (relative to the source directory). It should return True if the file is to be added.

The optional compressed argument determines whether files are compressed. If set to True, files in the archive are compressed with the deflate method; otherwise, files are stored uncompressed. This argument has no effect when copying an existing archive.

If a file object is specified for source or target, it is the caller’s responsibility to close it after calling create_archive.

When copying an existing archive, file objects supplied only need read and readline, or write methods. When creating an archive from a directory, if the target is a file object it will be passed to the zipfile.ZipFile class, and must supply the methods needed by that class.

버전 3.7에 추가: Added the filter and compressed arguments.

zipapp.get_interpreter(archive)

Return the interpreter specified in the #! line at the start of the archive. If there is no #! line, return None. The archive argument can be a filename or a file-like object open for reading in bytes mode. It is assumed to be at the start of the archive.

Examples

Pack up a directory into an archive, and run it.

$ python -m zipapp myapp
$ python myapp.pyz
<output from myapp>

The same can be done using the create_archive() function:

>>> import zipapp
>>> zipapp.create_archive('myapp', 'myapp.pyz')

To make the application directly executable on POSIX, specify an interpreter to use.

$ python -m zipapp myapp -p "/usr/bin/env python"
$ ./myapp.pyz
<output from myapp>

To replace the shebang line on an existing archive, create a modified archive using the create_archive() function:

>>> import zipapp
>>> zipapp.create_archive('old_archive.pyz', 'new_archive.pyz', '/usr/bin/python3')

To update the file in place, do the replacement in memory using a BytesIO object, and then overwrite the source afterwards. Note that there is a risk when overwriting a file in place that an error will result in the loss of the original file. This code does not protect against such errors, but production code should do so. Also, this method will only work if the archive fits in memory:

>>> import zipapp
>>> import io
>>> temp = io.BytesIO()
>>> zipapp.create_archive('myapp.pyz', temp, '/usr/bin/python2')
>>> with open('myapp.pyz', 'wb') as f:
>>>     f.write(temp.getvalue())

Specifying the Interpreter

Note that if you specify an interpreter and then distribute your application archive, you need to ensure that the interpreter used is portable. The Python launcher for Windows supports most common forms of POSIX #! line, but there are other issues to consider:

If you use “/usr/bin/env python” (or other forms of the “python” command, such as “/usr/bin/python”), you need to consider that your users may have either Python 2 or Python 3 as their default, and write your code to work under both versions.

If you use an explicit version, for example “/usr/bin/env python3” your application will not work for users who do not have that version. (This may be what you want if you have not made your code Python 2 compatible).

There is no way to say “python X.Y or later”, so be careful of using an exact version like “/usr/bin/env python3.4” as you will need to change your shebang line for users of Python 3.5, for example.

Typically, you should use an “/usr/bin/env python2” or “/usr/bin/env python3”, depending on whether your code is written for Python 2 or 3.

Creating Standalone Applications with zipapp

Using the zipapp module, it is possible to create self-contained Python programs, which can be distributed to end users who only need to have a suitable version of Python installed on their system. The key to doing this is to bundle all of the application’s dependencies into the archive, along with the application code.

The steps to create a standalone archive are as follows:

Create your application in a directory as normal, so you have a myapp directory containing a __main__.py file, and any supporting application code.

Install all of your application’s dependencies into the myapp directory, using pip:

$ python -m pip install -r requirements.txt --target myapp

(this assumes you have your project requirements in a requirements.txt file - if not, you can just list the dependencies manually on the pip command line).

Optionally, delete the .dist-info directories created by pip in the myapp directory. These hold metadata for pip to manage the packages, and as you won’t be making any further use of pip they aren’t required - although it won’t do any harm if you leave them.

Package the application using:

$ python -m zipapp -p "interpreter" myapp

This will produce a standalone executable, which can be run on any machine with the appropriate interpreter available. See Specifying the Interpreter for details. It can be shipped to users as a single file.

On Unix, the myapp.pyz file is executable as it stands. You can rename the file to remove the .pyz extension if you prefer a “plain” command name. On Windows, the myapp.pyz[w] file is executable by virtue of the fact that the Python interpreter registers the .pyz and .pyzw file extensions when installed.

Making a Windows executable

On Windows, registration of the .pyz extension is optional, and furthermore, there are certain places that don’t recognise registered extensions “transparently” (the simplest example is that subprocess.run(['myapp']) won’t find your application - you need to explicitly specify the extension).

On Windows, therefore, it is often preferable to create an executable from the zipapp. This is relatively easy, although it does require a C compiler. The basic approach relies on the fact that zipfiles can have arbitrary data prepended, and Windows exe files can have arbitrary data appended. So by creating a suitable launcher and tacking the .pyz file onto the end of it, you end up with a single-file executable that runs your application.

A suitable launcher can be as simple as the following:

#define Py_LIMITED_API 1
#include "Python.h"

#define WIN32_LEAN_AND_MEAN
#include <windows.h>

#ifdef WINDOWS
int WINAPI wWinMain(
    HINSTANCE hInstance,      /* handle to current instance */
    HINSTANCE hPrevInstance,  /* handle to previous instance */
    LPWSTR lpCmdLine,         /* pointer to command line */
    int nCmdShow              /* show state of window */
)
#else
int wmain()
#endif
{
    wchar_t **myargv = _alloca((__argc + 1) * sizeof(wchar_t*));
    myargv[0] = __wargv[0];
    memcpy(myargv + 1, __wargv, __argc * sizeof(wchar_t *));
    return Py_Main(__argc+1, myargv);
}

If you define the WINDOWS preprocessor symbol, this will generate a GUI executable, and without it, a console executable.

To compile the executable, you can either just use the standard MSVC command line tools, or you can take advantage of the fact that distutils knows how to compile Python source:

>>> from distutils.ccompiler import new_compiler
>>> import distutils.sysconfig
>>> import sys
>>> import os
>>> from pathlib import Path

>>> def compile(src):
>>>     src = Path(src)
>>>     cc = new_compiler()
>>>     exe = src.stem
>>>     cc.add_include_dir(distutils.sysconfig.get_python_inc())
>>>     cc.add_library_dir(os.path.join(sys.base_exec_prefix, 'libs'))
>>>     # First the CLI executable
>>>     objs = cc.compile([str(src)])
>>>     cc.link_executable(objs, exe)
>>>     # Now the GUI executable
>>>     cc.define_macro('WINDOWS')
>>>     objs = cc.compile([str(src)])
>>>     cc.link_executable(objs, exe + 'w')

>>> if __name__ == "__main__":
>>>     compile("zastub.c")

The resulting launcher uses the “Limited ABI”, so it will run unchanged with any version of Python 3.x. All it needs is for Python (python3.dll) to be on the user’s PATH.

For a fully standalone distribution, you can distribute the launcher with your application appended, bundled with the Python “embedded” distribution. This will run on any PC with the appropriate architecture (32 bit or 64 bit).

Caveats

There are some limitations to the process of bundling your application into a single file. In most, if not all, cases they can be addressed without needing major changes to your application.

If your application depends on a package that includes a C extension, that package cannot be run from a zip file (this is an OS limitation, as executable code must be present in the filesystem for the OS loader to load it). In this case, you can exclude that dependency from the zipfile, and either require your users to have it installed, or ship it alongside your zipfile and add code to your __main__.py to include the directory containing the unzipped module in sys.path. In this case, you will need to make sure to ship appropriate binaries for your target architecture(s) (and potentially pick the correct version to add to sys.path at runtime, based on the user’s machine).

If you are shipping a Windows executable as described above, you either need to ensure that your users have python3.dll on their PATH (which is not the default behaviour of the installer) or you should bundle your application with the embedded distribution.

The suggested launcher above uses the Python embedding API. This means that in your application, sys.executable will be your application, and not a conventional Python interpreter. Your code and its dependencies need to be prepared for this possibility. For example, if your application uses the multiprocessing module, it will need to call multiprocessing.set_executable() to let the module know where to find the standard Python interpreter.

The Python Zip Application Archive Format

Python has been able to execute zip files which contain a __main__.py file since version 2.6. In order to be executed by Python, an application archive simply has to be a standard zip file containing a __main__.py file which will be run as the entry point for the application. As usual for any Python script, the parent of the script (in this case the zip file) will be placed on sys.path and thus further modules can be imported from the zip file.

The zip file format allows arbitrary data to be prepended to a zip file. The zip application format uses this ability to prepend a standard POSIX “shebang” line to the file (#!/path/to/interpreter).

Formally, the Python zip application format is therefore:

An optional shebang line, containing the characters b'#!' followed by an interpreter name, and then a newline (b'\n') character. The interpreter name can be anything acceptable to the OS “shebang” processing, or the Python launcher on Windows. The interpreter should be encoded in UTF-8 on Windows, and in sys.getfilesystemencoding() on POSIX.

Standard zipfile data, as generated by the zipfile module. The zipfile content must include a file called __main__.py (which must be in the “root” of the zipfile - i.e., it cannot be in a subdirectory). The zipfile data can be compressed or uncompressed.

If an application archive has a shebang line, it may have the executable bit set on POSIX systems, to allow it to be executed directly.

There is no requirement that the tools in this module are used to create application archives - the module is a convenience, but archives in the above format created by any means are acceptable to Python.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

소프트웨어 패키징 및 배포 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

|

파이썬 실행시간 서비스

이 장에서 설명하는 모듈들은 파이썬 인터프리터와 그 환경과의 상호 작용과 관련된 다양한 서비스를 제공합니다. 다음은 개요입니다:

sys — System-specific parameters and functions

sysconfig — 파이썬의 구성 정보에 접근하기

구성 변수

설치 경로

기타 함수

sysconfig 를 스크립트로 사용하기

builtins — 내장 객체

__main__ — 최상위 스크립트 환경

warnings — Warning control

Warning Categories

The Warnings Filter

Describing Warning Filters

Default Warning Filter

Overriding the default filter

Temporarily Suppressing Warnings

Testing Warnings

Updating Code For New Versions of Dependencies

Available Functions

Available Context Managers

dataclasses — 데이터 클래스

모듈 수준의 데코레이터, 클래스 및 함수

초기화 후처리

클래스 변수

초기화 전용 변수

고정 인스턴스

계승

기본 팩토리 함수

가변 기본값

예외

contextlib — Utilities for with-statement contexts

Utilities

Examples and Recipes

Supporting a variable number of context managers

Catching exceptions from __enter__ methods

Cleaning up in an __enter__ implementation

Replacing any use of try-finally and flag variables

Using a context manager as a function decorator

Single use, reusable and reentrant context managers

Reentrant context managers

Reusable context managers

abc — 추상 베이스 클래스

atexit — 종료 처리기

atexit 예제

traceback — 스택 트레이스백 인쇄와 조회

TracebackException 객체

StackSummary 객체

FrameSummary 객체

트레이스백 예제

__future__ — 퓨처 문 정의

gc — 가비지 수거기 인터페이스

inspect — Inspect live objects

Types and members

Retrieving source code

Introspecting callables with the Signature object

Classes and functions

The interpreter stack

Fetching attributes statically

Current State of Generators and Coroutines

Code Objects Bit Flags

Command Line Interface

site — 사이트별 구성 훅

Readline 구성

모듈 내용

Command Line Interface

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

파이썬 실행시간 서비스 »

|

sys — System-specific parameters and functions

This module provides access to some variables used or maintained by the interpreter and to functions that interact strongly with the interpreter. It is always available.

sys.abiflags

On POSIX systems where Python was built with the standard configure script, this contains the ABI flags as specified by PEP 3149 [https://www.python.org/dev/peps/pep-3149].

버전 3.2에 추가.

sys.argv

The list of command line arguments passed to a Python script. argv[0] is the script name (it is operating system dependent whether this is a full pathname or not). If the command was executed using the -c command line option to the interpreter, argv[0] is set to the string '-c'. If no script name was passed to the Python interpreter, argv[0] is the empty string.

To loop over the standard input, or the list of files given on the command line, see the fileinput module.

참고

On Unix, command line arguments are passed by bytes from OS. Python decodes them with filesystem encoding and “surrogateescape” error handler. When you need original bytes, you can get it by [os.fsencode(arg) for arg in sys.argv].

sys.base_exec_prefix

Set during Python startup, before site.py is run, to the same value as exec_prefix. If not running in a virtual environment, the values will stay the same; if site.py finds that a virtual environment is in use, the values of prefix and exec_prefix will be changed to point to the virtual environment, whereas base_prefix and base_exec_prefix will remain pointing to the base Python installation (the one which the virtual environment was created from).

버전 3.3에 추가.

sys.base_prefix

Set during Python startup, before site.py is run, to the same value as prefix. If not running in a virtual environment, the values will stay the same; if site.py finds that a virtual environment is in use, the values of prefix and exec_prefix will be changed to point to the virtual environment, whereas base_prefix and base_exec_prefix will remain pointing to the base Python installation (the one which the virtual environment was created from).

버전 3.3에 추가.

sys.byteorder

An indicator of the native byte order. This will have the value 'big' on big-endian (most-significant byte first) platforms, and 'little' on little-endian (least-significant byte first) platforms.

sys.builtin_module_names

A tuple of strings giving the names of all modules that are compiled into this Python interpreter. (This information is not available in any other way — modules.keys() only lists the imported modules.)

sys.call_tracing(func, args)

Call func(*args), while tracing is enabled. The tracing state is saved, and restored afterwards. This is intended to be called from a debugger from a checkpoint, to recursively debug some other code.

sys.copyright

A string containing the copyright pertaining to the Python interpreter.

sys._clear_type_cache()

Clear the internal type cache. The type cache is used to speed up attribute and method lookups. Use the function only to drop unnecessary references during reference leak debugging.

This function should be used for internal and specialized purposes only.

sys._current_frames()

Return a dictionary mapping each thread’s identifier to the topmost stack frame currently active in that thread at the time the function is called. Note that functions in the traceback module can build the call stack given such a frame.

This is most useful for debugging deadlock: this function does not require the deadlocked threads’ cooperation, and such threads’ call stacks are frozen for as long as they remain deadlocked. The frame returned for a non-deadlocked thread may bear no relationship to that thread’s current activity by the time calling code examines the frame.

This function should be used for internal and specialized purposes only.

sys.breakpointhook()

This hook function is called by built-in breakpoint(). By default, it drops you into the pdb debugger, but it can be set to any other function so that you can choose which debugger gets used.

The signature of this function is dependent on what it calls. For example, the default binding (e.g. pdb.set_trace()) expects no arguments, but you might bind it to a function that expects additional arguments (positional and/or keyword). The built-in breakpoint() function passes its *args and **kws straight through. Whatever breakpointhooks() returns is returned from breakpoint().

The default implementation first consults the environment variable PYTHONBREAKPOINT. If that is set to "0" then this function returns immediately; i.e. it is a no-op. If the environment variable is not set, or is set to the empty string, pdb.set_trace() is called. Otherwise this variable should name a function to run, using Python’s dotted-import nomenclature, e.g. package.subpackage.module.function. In this case, package.subpackage.module would be imported and the resulting module must have a callable named function(). This is run, passing in *args and **kws, and whatever function() returns, sys.breakpointhook() returns to the built-in breakpoint() function.

Note that if anything goes wrong while importing the callable named by PYTHONBREAKPOINT, a RuntimeWarning is reported and the breakpoint is ignored.

Also note that if sys.breakpointhook() is overridden programmatically, PYTHONBREAKPOINT is not consulted.

버전 3.7에 추가.

sys._debugmallocstats()

Print low-level information to stderr about the state of CPython’s memory allocator.

If Python is configured –with-pydebug, it also performs some expensive internal consistency checks.

버전 3.3에 추가.

CPython implementation detail: This function is specific to CPython. The exact output format is not defined here, and may change.

sys.dllhandle

Integer specifying the handle of the Python DLL.

Availability: Windows.

sys.displayhook(value)

If value is not None, this function prints repr(value) to sys.stdout, and saves value in builtins._. If repr(value) is not encodable to sys.stdout.encoding with sys.stdout.errors error handler (which is probably 'strict'), encode it to sys.stdout.encoding with 'backslashreplace' error handler.

sys.displayhook is called on the result of evaluating an expression entered in an interactive Python session. The display of these values can be customized by assigning another one-argument function to sys.displayhook.

Pseudo-code:

def displayhook(value):
    if value is None:
        return
    # Set '_' to None to avoid recursion
    builtins._ = None
    text = repr(value)
    try:
        sys.stdout.write(text)
    except UnicodeEncodeError:
        bytes = text.encode(sys.stdout.encoding, 'backslashreplace')
        if hasattr(sys.stdout, 'buffer'):
            sys.stdout.buffer.write(bytes)
        else:
            text = bytes.decode(sys.stdout.encoding, 'strict')
            sys.stdout.write(text)
    sys.stdout.write("\n")
    builtins._ = value

버전 3.2에서 변경: Use 'backslashreplace' error handler on UnicodeEncodeError.

sys.dont_write_bytecode

If this is true, Python won’t try to write .pyc files on the import of source modules. This value is initially set to True or False depending on the -B command line option and the PYTHONDONTWRITEBYTECODE environment variable, but you can set it yourself to control bytecode file generation.

sys.excepthook(type, value, traceback)

This function prints out a given traceback and exception to sys.stderr.

When an exception is raised and uncaught, the interpreter calls sys.excepthook with three arguments, the exception class, exception instance, and a traceback object. In an interactive session this happens just before control is returned to the prompt; in a Python program this happens just before the program exits. The handling of such top-level exceptions can be customized by assigning another three-argument function to sys.excepthook.

sys.__breakpointhook__

sys.__displayhook__

sys.__excepthook__

These objects contain the original values of breakpointhook, displayhook, and excepthook at the start of the program. They are saved so that breakpointhook, displayhook and excepthook can be restored in case they happen to get replaced with broken or alternative objects.

버전 3.7에 추가: __breakpointhook__

sys.exc_info()

This function returns a tuple of three values that give information about the exception that is currently being handled. The information returned is specific both to the current thread and to the current stack frame. If the current stack frame is not handling an exception, the information is taken from the calling stack frame, or its caller, and so on until a stack frame is found that is handling an exception. Here, “handling an exception” is defined as “executing an except clause.” For any stack frame, only information about the exception being currently handled is accessible.

If no exception is being handled anywhere on the stack, a tuple containing three None values is returned. Otherwise, the values returned are (type, value, traceback). Their meaning is: type gets the type of the exception being handled (a subclass of BaseException); value gets the exception instance (an instance of the exception type); traceback gets a traceback object (see the Reference Manual) which encapsulates the call stack at the point where the exception originally occurred.

sys.exec_prefix

A string giving the site-specific directory prefix where the platform-dependent Python files are installed; by default, this is also '/usr/local'. This can be set at build time with the --exec-prefix argument to the configure script. Specifically, all configuration files (e.g. the pyconfig.h header file) are installed in the directory exec_prefix/lib/pythonX.Y/config, and shared library modules are installed in exec_prefix/lib/pythonX.Y/lib-dynload, where X.Y is the version number of Python, for example 3.2.

참고

If a virtual environment is in effect, this value will be changed in site.py to point to the virtual environment. The value for the Python installation will still be available, via base_exec_prefix.

sys.executable

A string giving the absolute path of the executable binary for the Python interpreter, on systems where this makes sense. If Python is unable to retrieve the real path to its executable, sys.executable will be an empty string or None.

sys.exit([arg])

Exit from Python. This is implemented by raising the SystemExit exception, so cleanup actions specified by finally clauses of try statements are honored, and it is possible to intercept the exit attempt at an outer level.

The optional argument arg can be an integer giving the exit status (defaulting to zero), or another type of object. If it is an integer, zero is considered “successful termination” and any nonzero value is considered “abnormal termination” by shells and the like. Most systems require it to be in the range 0–127, and produce undefined results otherwise. Some systems have a convention for assigning specific meanings to specific exit codes, but these are generally underdeveloped; Unix programs generally use 2 for command line syntax errors and 1 for all other kind of errors. If another type of object is passed, None is equivalent to passing zero, and any other object is printed to stderr and results in an exit code of 1. In particular, sys.exit("some error message") is a quick way to exit a program when an error occurs.

Since exit() ultimately “only” raises an exception, it will only exit the process when called from the main thread, and the exception is not intercepted.

버전 3.6에서 변경: If an error occurs in the cleanup after the Python interpreter has caught SystemExit (such as an error flushing buffered data in the standard streams), the exit status is changed to 120.

sys.flags

The named tuple flags exposes the status of command line flags. The attributes are read only.

attribute

flag

debug

-d

inspect

-i

interactive

-i

isolated

-I

optimize

-O or -OO

dont_write_bytecode

-B

no_user_site

-s

no_site

-S

ignore_environment

-E

verbose

-v

bytes_warning

-b

quiet

-q

hash_randomization

-R

dev_mode

-X dev

utf8_mode

-X utf8

int_max_str_digits

-X int_max_str_digits (integer string conversion length limitation)

버전 3.2에서 변경: Added quiet attribute for the new -q flag.

버전 3.2.3에 추가: The hash_randomization attribute.

버전 3.3에서 변경: Removed obsolete division_warning attribute.

버전 3.4에서 변경: Added isolated attribute for -I isolated flag.

버전 3.7에서 변경: Added dev_mode attribute for the new -X dev flag and utf8_mode attribute for the new -X utf8 flag.

버전 3.7.14에서 변경: Added the int_max_str_digits attribute.

sys.float_info

A named tuple holding information about the float type. It contains low level information about the precision and internal representation. The values correspond to the various floating-point constants defined in the standard header file float.h for the ‘C’ programming language; see section 5.2.4.2.2 of the 1999 ISO/IEC C standard [C99], ‘Characteristics of floating types’, for details.

attribute

float.h macro

explanation

epsilon

DBL_EPSILON

difference between 1.0 and the least value greater than 1.0 that is representable as a float

dig

DBL_DIG

maximum number of decimal digits that can be faithfully represented in a float; see below

mant_dig

DBL_MANT_DIG

float precision: the number of base-radix digits in the significand of a float

max

DBL_MAX

maximum representable positive finite float

max_exp

DBL_MAX_EXP

maximum integer e such that radix**(e-1) is a representable finite float

max_10_exp

DBL_MAX_10_EXP

maximum integer e such that 10**e is in the range of representable finite floats

min

DBL_MIN

minimum representable positive normalized float

min_exp

DBL_MIN_EXP

minimum integer e such that radix**(e-1) is a normalized float

min_10_exp

DBL_MIN_10_EXP

minimum integer e such that 10**e is a normalized float

radix

FLT_RADIX

radix of exponent representation

rounds

FLT_ROUNDS

integer constant representing the rounding mode used for arithmetic operations. This reflects the value of the system FLT_ROUNDS macro at interpreter startup time. See section 5.2.4.2.2 of the C99 standard for an explanation of the possible values and their meanings.

The attribute sys.float_info.dig needs further explanation. If s is any string representing a decimal number with at most sys.float_info.dig significant digits, then converting s to a float and back again will recover a string representing the same decimal value:

>>> import sys
>>> sys.float_info.dig
15
>>> s = '3.14159265358979'    # decimal string with 15 significant digits
>>> format(float(s), '.15g')  # convert to float and back -> same value
'3.14159265358979'

But for strings with more than sys.float_info.dig significant digits, this isn’t always true:

>>> s = '9876543211234567'    # 16 significant digits is too many!
>>> format(float(s), '.16g')  # conversion changes value
'9876543211234568'

sys.float_repr_style

A string indicating how the repr() function behaves for floats. If the string has value 'short' then for a finite float x, repr(x) aims to produce a short string with the property that float(repr(x)) == x. This is the usual behaviour in Python 3.1 and later. Otherwise, float_repr_style has value 'legacy' and repr(x) behaves in the same way as it did in versions of Python prior to 3.1.

버전 3.1에 추가.

sys.getallocatedblocks()

Return the number of memory blocks currently allocated by the interpreter, regardless of their size. This function is mainly useful for tracking and debugging memory leaks. Because of the interpreter’s internal caches, the result can vary from call to call; you may have to call _clear_type_cache() and gc.collect() to get more predictable results.

If a Python build or implementation cannot reasonably compute this information, getallocatedblocks() is allowed to return 0 instead.

버전 3.4에 추가.

sys.getandroidapilevel()

Return the build time API version of Android as an integer.

Availability: Android.

버전 3.7에 추가.

sys.getcheckinterval()

Return the interpreter’s “check interval”; see setcheckinterval().

버전 3.2부터 폐지: Use getswitchinterval() instead.

sys.getdefaultencoding()

Return the name of the current default string encoding used by the Unicode implementation.

sys.getdlopenflags()

Return the current value of the flags that are used for dlopen() calls. Symbolic names for the flag values can be found in the os module (RTLD_xxx constants, e.g. os.RTLD_LAZY).

Availability: Unix.

sys.getfilesystemencoding()

Return the name of the encoding used to convert between Unicode filenames and bytes filenames. For best compatibility, str should be used for filenames in all cases, although representing filenames as bytes is also supported. Functions accepting or returning filenames should support either str or bytes and internally convert to the system’s preferred representation.

This encoding is always ASCII-compatible.

os.fsencode() and os.fsdecode() should be used to ensure that the correct encoding and errors mode are used.

In the UTF-8 mode, the encoding is utf-8 on any platform.

On Mac OS X, the encoding is 'utf-8'.

On Unix, the encoding is the locale encoding.

On Windows, the encoding may be 'utf-8' or 'mbcs', depending on user configuration.

버전 3.2에서 변경: getfilesystemencoding() result cannot be None anymore.

버전 3.6에서 변경: Windows is no longer guaranteed to return 'mbcs'. See PEP 529 [https://www.python.org/dev/peps/pep-0529] and _enablelegacywindowsfsencoding() for more information.

버전 3.7에서 변경: Return ‘utf-8’ in the UTF-8 mode.

sys.getfilesystemencodeerrors()

Return the name of the error mode used to convert between Unicode filenames and bytes filenames. The encoding name is returned from getfilesystemencoding().

os.fsencode() and os.fsdecode() should be used to ensure that the correct encoding and errors mode are used.

버전 3.6에 추가.

sys.get_int_max_str_digits()

Returns the current value for the integer string conversion length limitation. See also set_int_max_str_digits().

버전 3.7.14에 추가.

sys.getrefcount(object)

Return the reference count of the object. The count returned is generally one higher than you might expect, because it includes the (temporary) reference as an argument to getrefcount().

sys.getrecursionlimit()

Return the current value of the recursion limit, the maximum depth of the Python interpreter stack. This limit prevents infinite recursion from causing an overflow of the C stack and crashing Python. It can be set by setrecursionlimit().

sys.getsizeof(object[, default])

Return the size of an object in bytes. The object can be any type of object. All built-in objects will return correct results, but this does not have to hold true for third-party extensions as it is implementation specific.

Only the memory consumption directly attributed to the object is accounted for, not the memory consumption of objects it refers to.

If given, default will be returned if the object does not provide means to retrieve the size. Otherwise a TypeError will be raised.

getsizeof() calls the object’s __sizeof__ method and adds an additional garbage collector overhead if the object is managed by the garbage collector.

See recursive sizeof recipe [https://code.activestate.com/recipes/577504] for an example of using getsizeof() recursively to find the size of containers and all their contents.

sys.getswitchinterval()

Return the interpreter’s “thread switch interval”; see setswitchinterval().

버전 3.2에 추가.

sys._getframe([depth])

Return a frame object from the call stack. If optional integer depth is given, return the frame object that many calls below the top of the stack. If that is deeper than the call stack, ValueError is raised. The default for depth is zero, returning the frame at the top of the call stack.

CPython implementation detail: This function should be used for internal and specialized purposes only. It is not guaranteed to exist in all implementations of Python.

sys.getprofile()

Get the profiler function as set by setprofile().

sys.gettrace()

Get the trace function as set by settrace().

CPython implementation detail: The gettrace() function is intended only for implementing debuggers, profilers, coverage tools and the like. Its behavior is part of the implementation platform, rather than part of the language definition, and thus may not be available in all Python implementations.

sys.getwindowsversion()

Return a named tuple describing the Windows version currently running. The named elements are major, minor, build, platform, service_pack, service_pack_minor, service_pack_major, suite_mask, product_type and platform_version. service_pack contains a string, platform_version a 3-tuple and all other values are integers. The components can also be accessed by name, so sys.getwindowsversion()[0] is equivalent to sys.getwindowsversion().major. For compatibility with prior versions, only the first 5 elements are retrievable by indexing.

platform will be 2 (VER_PLATFORM_WIN32_NT).

product_type may be one of the following values:

Constant

Meaning

1 (VER_NT_WORKSTATION)

The system is a workstation.

2 (VER_NT_DOMAIN_CONTROLLER)

The system is a domain controller.

3 (VER_NT_SERVER)

The system is a server, but not a domain controller.

This function wraps the Win32 GetVersionEx() function; see the Microsoft documentation on OSVERSIONINFOEX() for more information about these fields.

platform_version returns the accurate major version, minor version and build number of the current operating system, rather than the version that is being emulated for the process. It is intended for use in logging rather than for feature detection.

Availability: Windows.

버전 3.2에서 변경: Changed to a named tuple and added service_pack_minor, service_pack_major, suite_mask, and product_type.

버전 3.6에서 변경: Added platform_version

sys.get_asyncgen_hooks()

Returns an asyncgen_hooks object, which is similar to a namedtuple of the form (firstiter, finalizer), where firstiter and finalizer are expected to be either None or functions which take an asynchronous generator iterator as an argument, and are used to schedule finalization of an asynchronous generator by an event loop.

버전 3.6에 추가: See PEP 525 [https://www.python.org/dev/peps/pep-0525] for more details.

참고

This function has been added on a provisional basis (see PEP 411 [https://www.python.org/dev/peps/pep-0411] for details.)

sys.get_coroutine_origin_tracking_depth()

Get the current coroutine origin tracking depth, as set by set_coroutine_origin_tracking_depth().

버전 3.7에 추가.

참고

This function has been added on a provisional basis (see PEP 411 [https://www.python.org/dev/peps/pep-0411] for details.) Use it only for debugging purposes.

sys.get_coroutine_wrapper()

Returns None, or a wrapper set by set_coroutine_wrapper().

버전 3.5에 추가: See PEP 492 [https://www.python.org/dev/peps/pep-0492] for more details.

참고

This function has been added on a provisional basis (see PEP 411 [https://www.python.org/dev/peps/pep-0411] for details.) Use it only for debugging purposes.

버전 3.7부터 폐지: The coroutine wrapper functionality has been deprecated, and will be removed in 3.8. See bpo-32591 [https://bugs.python.org/issue?@action=redirect&bpo=32591] for details.

sys.hash_info

A named tuple giving parameters of the numeric hash implementation. For more details about hashing of numeric types, see 숫자 형의 해싱.

attribute

explanation

width

width in bits used for hash values

modulus

prime modulus P used for numeric hash scheme

inf

hash value returned for a positive infinity

nan

hash value returned for a nan

imag

multiplier used for the imaginary part of a complex number

algorithm

name of the algorithm for hashing of str, bytes, and memoryview

hash_bits

internal output size of the hash algorithm

seed_bits

size of the seed key of the hash algorithm

버전 3.2에 추가.

버전 3.4에서 변경: Added algorithm, hash_bits and seed_bits

sys.hexversion

The version number encoded as a single integer. This is guaranteed to increase with each version, including proper support for non-production releases. For example, to test that the Python interpreter is at least version 1.5.2, use:

if sys.hexversion >= 0x010502F0:
    # use some advanced feature
    ...
else:
    # use an alternative implementation or warn the user
    ...

This is called hexversion since it only really looks meaningful when viewed as the result of passing it to the built-in hex() function. The named tuple sys.version_info may be used for a more human-friendly encoding of the same information.

More details of hexversion can be found at API와 ABI 버전 붙이기.

sys.implementation

An object containing information about the implementation of the currently running Python interpreter. The following attributes are required to exist in all Python implementations.

name is the implementation’s identifier, e.g. 'cpython'. The actual string is defined by the Python implementation, but it is guaranteed to be lower case.

version is a named tuple, in the same format as sys.version_info. It represents the version of the Python implementation. This has a distinct meaning from the specific version of the Python language to which the currently running interpreter conforms, which sys.version_info represents. For example, for PyPy 1.8 sys.implementation.version might be sys.version_info(1, 8, 0, 'final', 0), whereas sys.version_info would be sys.version_info(2, 7, 2, 'final', 0). For CPython they are the same value, since it is the reference implementation.

hexversion is the implementation version in hexadecimal format, like sys.hexversion.

cache_tag is the tag used by the import machinery in the filenames of cached modules. By convention, it would be a composite of the implementation’s name and version, like 'cpython-33'. However, a Python implementation may use some other value if appropriate. If cache_tag is set to None, it indicates that module caching should be disabled.

sys.implementation may contain additional attributes specific to the Python implementation. These non-standard attributes must start with an underscore, and are not described here. Regardless of its contents, sys.implementation will not change during a run of the interpreter, nor between implementation versions. (It may change between Python language versions, however.) See PEP 421 [https://www.python.org/dev/peps/pep-0421] for more information.

버전 3.3에 추가.

참고

The addition of new required attributes must go through the normal PEP process. See PEP 421 [https://www.python.org/dev/peps/pep-0421] for more information.

sys.int_info

A named tuple that holds information about Python’s internal representation of integers. The attributes are read only.

Attribute

Explanation

bits_per_digit

number of bits held in each digit. Python integers are stored internally in base 2**int_info.bits_per_digit

sizeof_digit

size in bytes of the C type used to represent a digit

default_max_str_digits

default value for sys.get_int_max_str_digits() when it is not otherwise explicitly configured.

str_digits_check_threshold

minimum non-zero value for sys.set_int_max_str_digits(), PYTHONINTMAXSTRDIGITS, or -X int_max_str_digits.

버전 3.1에 추가.

버전 3.7.14에서 변경: Added default_max_str_digits and str_digits_check_threshold.

sys.__interactivehook__

When this attribute exists, its value is automatically called (with no arguments) when the interpreter is launched in interactive mode. This is done after the PYTHONSTARTUP file is read, so that you can set this hook there. The site module sets this.

버전 3.4에 추가.

sys.intern(string)

Enter string in the table of “interned” strings and return the interned string – which is string itself or a copy. Interning strings is useful to gain a little performance on dictionary lookup – if the keys in a dictionary are interned, and the lookup key is interned, the key comparisons (after hashing) can be done by a pointer compare instead of a string compare. Normally, the names used in Python programs are automatically interned, and the dictionaries used to hold module, class or instance attributes have interned keys.

Interned strings are not immortal; you must keep a reference to the return value of intern() around to benefit from it.

sys.is_finalizing()

Return True if the Python interpreter is shutting down, False otherwise.

버전 3.5에 추가.

sys.last_type

sys.last_value

sys.last_traceback

These three variables are not always defined; they are set when an exception is not handled and the interpreter prints an error message and a stack traceback. Their intended use is to allow an interactive user to import a debugger module and engage in post-mortem debugging without having to re-execute the command that caused the error. (Typical use is import pdb; pdb.pm() to enter the post-mortem debugger; see pdb module for more information.)

The meaning of the variables is the same as that of the return values from exc_info() above.

sys.maxsize

An integer giving the maximum value a variable of type Py_ssize_t can take. It’s usually 2**31 - 1 on a 32-bit platform and 2**63 - 1 on a 64-bit platform.

sys.maxunicode

An integer giving the value of the largest Unicode code point, i.e. 1114111 (0x10FFFF in hexadecimal).

버전 3.3에서 변경: Before PEP 393 [https://www.python.org/dev/peps/pep-0393], sys.maxunicode used to be either 0xFFFF or 0x10FFFF, depending on the configuration option that specified whether Unicode characters were stored as UCS-2 or UCS-4.

sys.meta_path

A list of meta path finder objects that have their find_spec() methods called to see if one of the objects can find the module to be imported. The find_spec() method is called with at least the absolute name of the module being imported. If the module to be imported is contained in a package, then the parent package’s __path__ attribute is passed in as a second argument. The method returns a module spec, or None if the module cannot be found.

더 보기

importlib.abc.MetaPathFinder

The abstract base class defining the interface of finder objects on meta_path.

importlib.machinery.ModuleSpec

The concrete class which find_spec() should return instances of.

버전 3.4에서 변경: Module specs were introduced in Python 3.4, by PEP 451 [https://www.python.org/dev/peps/pep-0451]. Earlier versions of Python looked for a method called find_module(). This is still called as a fallback if a meta_path entry doesn’t have a find_spec() method.

sys.modules

This is a dictionary that maps module names to modules which have already been loaded. This can be manipulated to force reloading of modules and other tricks. However, replacing the dictionary will not necessarily work as expected and deleting essential items from the dictionary may cause Python to fail.

sys.path

A list of strings that specifies the search path for modules. Initialized from the environment variable PYTHONPATH, plus an installation-dependent default.

As initialized upon program startup, the first item of this list, path[0], is the directory containing the script that was used to invoke the Python interpreter. If the script directory is not available (e.g. if the interpreter is invoked interactively or if the script is read from standard input), path[0] is the empty string, which directs Python to search modules in the current directory first. Notice that the script directory is inserted before the entries inserted as a result of PYTHONPATH.

A program is free to modify this list for its own purposes. Only strings and bytes should be added to sys.path; all other data types are ignored during import.

더 보기

Module site This describes how to use .pth files to extend sys.path.

sys.path_hooks

A list of callables that take a path argument to try to create a finder for the path. If a finder can be created, it is to be returned by the callable, else raise ImportError.

Originally specified in PEP 302 [https://www.python.org/dev/peps/pep-0302].

sys.path_importer_cache

A dictionary acting as a cache for finder objects. The keys are paths that have been passed to sys.path_hooks and the values are the finders that are found. If a path is a valid file system path but no finder is found on sys.path_hooks then None is stored.

Originally specified in PEP 302 [https://www.python.org/dev/peps/pep-0302].

버전 3.3에서 변경: None is stored instead of imp.NullImporter when no finder is found.

sys.platform

This string contains a platform identifier that can be used to append platform-specific components to sys.path, for instance.

For Unix systems, except on Linux, this is the lowercased OS name as returned by uname -s with the first part of the version as returned by uname -r appended, e.g. 'sunos5' or 'freebsd8', at the time when Python was built. Unless you want to test for a specific system version, it is therefore recommended to use the following idiom:

if sys.platform.startswith('freebsd'):
    # FreeBSD-specific code here...
elif sys.platform.startswith('linux'):
    # Linux-specific code here...

For other systems, the values are:

System

platform value

Linux

'linux'

Windows

'win32'

Windows/Cygwin

'cygwin'

Mac OS X

'darwin'

버전 3.3에서 변경: On Linux, sys.platform doesn’t contain the major version anymore. It is always 'linux', instead of 'linux2' or 'linux3'. Since older Python versions include the version number, it is recommended to always use the startswith idiom presented above.

더 보기

os.name has a coarser granularity. os.uname() gives system-dependent version information.

The platform module provides detailed checks for the system’s identity.

sys.prefix

A string giving the site-specific directory prefix where the platform independent Python files are installed; by default, this is the string '/usr/local'. This can be set at build time with the --prefix argument to the configure script. The main collection of Python library modules is installed in the directory prefix/lib/pythonX.Y while the platform independent header files (all except pyconfig.h) are stored in prefix/include/pythonX.Y, where X.Y is the version number of Python, for example 3.2.

참고

If a virtual environment is in effect, this value will be changed in site.py to point to the virtual environment. The value for the Python installation will still be available, via base_prefix.

sys.ps1

sys.ps2

Strings specifying the primary and secondary prompt of the interpreter. These are only defined if the interpreter is in interactive mode. Their initial values in this case are '>>> ' and '... '. If a non-string object is assigned to either variable, its str() is re-evaluated each time the interpreter prepares to read a new interactive command; this can be used to implement a dynamic prompt.

sys.setcheckinterval(interval)

Set the interpreter’s “check interval”. This integer value determines how often the interpreter checks for periodic things such as thread switches and signal handlers. The default is 100, meaning the check is performed every 100 Python virtual instructions. Setting it to a larger value may increase performance for programs using threads. Setting it to a value <= 0 checks every virtual instruction, maximizing responsiveness as well as overhead.

버전 3.2부터 폐지: This function doesn’t have an effect anymore, as the internal logic for thread switching and asynchronous tasks has been rewritten. Use setswitchinterval() instead.

sys.setdlopenflags(n)

Set the flags used by the interpreter for dlopen() calls, such as when the interpreter loads extension modules. Among other things, this will enable a lazy resolving of symbols when importing a module, if called as sys.setdlopenflags(0). To share symbols across extension modules, call as sys.setdlopenflags(os.RTLD_GLOBAL). Symbolic names for the flag values can be found in the os module (RTLD_xxx constants, e.g. os.RTLD_LAZY).

Availability: Unix.

sys.set_int_max_str_digits(n)

Set the integer string conversion length limitation used by this interpreter. See also get_int_max_str_digits().

버전 3.7.14에 추가.

sys.setprofile(profilefunc)

Set the system’s profile function, which allows you to implement a Python source code profiler in Python. See chapter The Python Profilers for more information on the Python profiler. The system’s profile function is called similarly to the system’s trace function (see settrace()), but it is called with different events, for example it isn’t called for each executed line of code (only on call and return, but the return event is reported even when an exception has been set). The function is thread-specific, but there is no way for the profiler to know about context switches between threads, so it does not make sense to use this in the presence of multiple threads. Also, its return value is not used, so it can simply return None. Error in the profile function will cause itself unset.

Profile functions should have three arguments: frame, event, and arg. frame is the current stack frame. event is a string: 'call', 'return', 'c_call', 'c_return', or 'c_exception'. arg depends on the event type.

The events have the following meaning:

'call'

A function is called (or some other code block entered). The profile function is called; arg is None.

'return'

A function (or other code block) is about to return. The profile function is called; arg is the value that will be returned, or None if the event is caused by an exception being raised.

'c_call'

A C function is about to be called. This may be an extension function or a built-in. arg is the C function object.

'c_return'

A C function has returned. arg is the C function object.

'c_exception'

A C function has raised an exception. arg is the C function object.

sys.setrecursionlimit(limit)

Set the maximum depth of the Python interpreter stack to limit. This limit prevents infinite recursion from causing an overflow of the C stack and crashing Python.

The highest possible limit is platform-dependent. A user may need to set the limit higher when they have a program that requires deep recursion and a platform that supports a higher limit. This should be done with care, because a too-high limit can lead to a crash.

If the new limit is too low at the current recursion depth, a RecursionError exception is raised.

버전 3.5.1에서 변경: A RecursionError exception is now raised if the new limit is too low at the current recursion depth.

sys.setswitchinterval(interval)

Set the interpreter’s thread switch interval (in seconds). This floating-point value determines the ideal duration of the “timeslices” allocated to concurrently running Python threads. Please note that the actual value can be higher, especially if long-running internal functions or methods are used. Also, which thread becomes scheduled at the end of the interval is the operating system’s decision. The interpreter doesn’t have its own scheduler.

버전 3.2에 추가.

sys.settrace(tracefunc)

Set the system’s trace function, which allows you to implement a Python source code debugger in Python. The function is thread-specific; for a debugger to support multiple threads, it must register a trace function using settrace() for each thread being debugged or use threading.settrace().

Trace functions should have three arguments: frame, event, and arg. frame is the current stack frame. event is a string: 'call', 'line', 'return', 'exception' or 'opcode'. arg depends on the event type.

The trace function is invoked (with event set to 'call') whenever a new local scope is entered; it should return a reference to a local trace function to be used for the new scope, or None if the scope shouldn’t be traced.

The local trace function should return a reference to itself (or to another function for further tracing in that scope), or None to turn off tracing in that scope.

If there is any error occurred in the trace function, it will be unset, just like settrace(None) is called.

The events have the following meaning:

'call'

A function is called (or some other code block entered). The global trace function is called; arg is None; the return value specifies the local trace function.

'line'

The interpreter is about to execute a new line of code or re-execute the condition of a loop. The local trace function is called; arg is None; the return value specifies the new local trace function. See Objects/lnotab_notes.txt for a detailed explanation of how this works. Per-line events may be disabled for a frame by setting f_trace_lines to False on that frame.

'return'

A function (or other code block) is about to return. The local trace function is called; arg is the value that will be returned, or None if the event is caused by an exception being raised. The trace function’s return value is ignored.

'exception'

An exception has occurred. The local trace function is called; arg is a tuple (exception, value, traceback); the return value specifies the new local trace function.

'opcode'

The interpreter is about to execute a new opcode (see dis for opcode details). The local trace function is called; arg is None; the return value specifies the new local trace function. Per-opcode events are not emitted by default: they must be explicitly requested by setting f_trace_opcodes to True on the frame.

Note that as an exception is propagated down the chain of callers, an 'exception' event is generated at each level.

For more fine-grained usage, it’s possible to set a trace function by assigning frame.f_trace = tracefunc explicitly, rather than relying on it being set indirectly via the return value from an already installed trace function. This is also required for activating the trace function on the current frame, which settrace() doesn’t do. Note that in order for this to work, a global tracing function must have been installed with settrace() in order to enable the runtime tracing machinery, but it doesn’t need to be the same tracing function (e.g. it could be a low overhead tracing function that simply returns None to disable itself immediately on each frame).

For more information on code and frame objects, refer to 표준형 계층.

CPython implementation detail: The settrace() function is intended only for implementing debuggers, profilers, coverage tools and the like. Its behavior is part of the implementation platform, rather than part of the language definition, and thus may not be available in all Python implementations.

버전 3.7에서 변경: 'opcode' event type added; f_trace_lines and f_trace_opcodes attributes added to frames

sys.set_asyncgen_hooks(firstiter, finalizer)

Accepts two optional keyword arguments which are callables that accept an asynchronous generator iterator as an argument. The firstiter callable will be called when an asynchronous generator is iterated for the first time. The finalizer will be called when an asynchronous generator is about to be garbage collected.

버전 3.6에 추가: See PEP 525 [https://www.python.org/dev/peps/pep-0525] for more details, and for a reference example of a finalizer method see the implementation of asyncio.Loop.shutdown_asyncgens in Lib/asyncio/base_events.py [https://github.com/python/cpython/tree/3.7/Lib/asyncio/base_events.py]

참고

This function has been added on a provisional basis (see PEP 411 [https://www.python.org/dev/peps/pep-0411] for details.)

sys.set_coroutine_origin_tracking_depth(depth)

Allows enabling or disabling coroutine origin tracking. When enabled, the cr_origin attribute on coroutine objects will contain a tuple of (filename, line number, function name) tuples describing the traceback where the coroutine object was created, with the most recent call first. When disabled, cr_origin will be None.

To enable, pass a depth value greater than zero; this sets the number of frames whose information will be captured. To disable, pass set depth to zero.

This setting is thread-specific.

버전 3.7에 추가.

참고

This function has been added on a provisional basis (see PEP 411 [https://www.python.org/dev/peps/pep-0411] for details.) Use it only for debugging purposes.

sys.set_coroutine_wrapper(wrapper)

Allows intercepting creation of coroutine objects (only ones that are created by an async def function; generators decorated with types.coroutine() or asyncio.coroutine() will not be intercepted).

The wrapper argument must be either:

a callable that accepts one argument (a coroutine object);

None, to reset the wrapper.

If called twice, the new wrapper replaces the previous one. The function is thread-specific.

The wrapper callable cannot define new coroutines directly or indirectly:

def wrapper(coro):
    async def wrap(coro):
        return await coro
    return wrap(coro)
sys.set_coroutine_wrapper(wrapper)

async def foo():
    pass

# The following line will fail with a RuntimeError, because
# ``wrapper`` creates a ``wrap(coro)`` coroutine:
foo()

See also get_coroutine_wrapper().

버전 3.5에 추가: See PEP 492 [https://www.python.org/dev/peps/pep-0492] for more details.

참고

This function has been added on a provisional basis (see PEP 411 [https://www.python.org/dev/peps/pep-0411] for details.) Use it only for debugging purposes.

버전 3.7부터 폐지: The coroutine wrapper functionality has been deprecated, and will be removed in 3.8. See bpo-32591 [https://bugs.python.org/issue?@action=redirect&bpo=32591] for details.

sys._enablelegacywindowsfsencoding()

Changes the default filesystem encoding and errors mode to ‘mbcs’ and ‘replace’ respectively, for consistency with versions of Python prior to 3.6.

This is equivalent to defining the PYTHONLEGACYWINDOWSFSENCODING environment variable before launching Python.

Availability: Windows.

버전 3.6에 추가: See PEP 529 [https://www.python.org/dev/peps/pep-0529] for more details.

sys.stdin

sys.stdout

sys.stderr

File objects used by the interpreter for standard input, output and errors:

stdin is used for all interactive input (including calls to input());

stdout is used for the output of print() and expression statements and for the prompts of input();

The interpreter’s own prompts and its error messages go to stderr.

These streams are regular text files like those returned by the open() function. Their parameters are chosen as follows:

The character encoding is platform-dependent. Non-Windows platforms use the locale encoding (see locale.getpreferredencoding()).

On Windows, UTF-8 is used for the console device. Non-character devices such as disk files and pipes use the system locale encoding (i.e. the ANSI codepage). Non-console character devices such as NUL (i.e. where isatty() returns True) use the value of the console input and output codepages at startup, respectively for stdin and stdout/stderr. This defaults to the system locale encoding if the process is not initially attached to a console.

The special behaviour of the console can be overridden by setting the environment variable PYTHONLEGACYWINDOWSSTDIO before starting Python. In that case, the console codepages are used as for any other character device.

Under all platforms, you can override the character encoding by setting the PYTHONIOENCODING environment variable before starting Python or by using the new -X utf8 command line option and PYTHONUTF8 environment variable. However, for the Windows console, this only applies when PYTHONLEGACYWINDOWSSTDIO is also set.

When interactive, stdout and stderr streams are line-buffered. Otherwise, they are block-buffered like regular text files. You can override this value with the -u command-line option.

참고

To write or read binary data from/to the standard streams, use the underlying binary buffer object. For example, to write bytes to stdout, use sys.stdout.buffer.write(b'abc').

However, if you are writing a library (and do not control in which context its code will be executed), be aware that the standard streams may be replaced with file-like objects like io.StringIO which do not support the buffer attribute.

sys.__stdin__

sys.__stdout__

sys.__stderr__

These objects contain the original values of stdin, stderr and stdout at the start of the program. They are used during finalization, and could be useful to print to the actual standard stream no matter if the sys.std* object has been redirected.

It can also be used to restore the actual files to known working file objects in case they have been overwritten with a broken object. However, the preferred way to do this is to explicitly save the previous stream before replacing it, and restore the saved object.

참고

Under some conditions stdin, stdout and stderr as well as the original values __stdin__, __stdout__ and __stderr__ can be None. It is usually the case for Windows GUI apps that aren’t connected to a console and Python apps started with pythonw.

sys.thread_info

A named tuple holding information about the thread implementation.

Attribute

Explanation

name

Name of the thread implementation:

'nt': Windows threads

'pthread': POSIX threads

'solaris': Solaris threads

lock

Name of the lock implementation:

'semaphore': a lock uses a semaphore

'mutex+cond': a lock uses a mutex and a condition variable

None if this information is unknown

version

Name and version of the thread library. It is a string, or None if this information is unknown.

버전 3.3에 추가.

sys.tracebacklimit

When this variable is set to an integer value, it determines the maximum number of levels of traceback information printed when an unhandled exception occurs. The default is 1000. When set to 0 or less, all traceback information is suppressed and only the exception type and value are printed.

sys.version

A string containing the version number of the Python interpreter plus additional information on the build number and compiler used. This string is displayed when the interactive interpreter is started. Do not extract version information out of it, rather, use version_info and the functions provided by the platform module.

sys.api_version

The C API version for this interpreter. Programmers may find this useful when debugging version conflicts between Python and extension modules.

sys.version_info

A tuple containing the five components of the version number: major, minor, micro, releaselevel, and serial. All values except releaselevel are integers; the release level is 'alpha', 'beta', 'candidate', or 'final'. The version_info value corresponding to the Python version 2.0 is (2, 0, 0, 'final', 0). The components can also be accessed by name, so sys.version_info[0] is equivalent to sys.version_info.major and so on.

버전 3.1에서 변경: Added named component attributes.

sys.warnoptions

This is an implementation detail of the warnings framework; do not modify this value. Refer to the warnings module for more information on the warnings framework.

sys.winver

The version number used to form registry keys on Windows platforms. This is stored as string resource 1000 in the Python DLL. The value is normally the first three characters of version. It is provided in the sys module for informational purposes; modifying this value has no effect on the registry keys used by Python.

Availability: Windows.

sys._xoptions

A dictionary of the various implementation-specific flags passed through the -X command-line option. Option names are either mapped to their values, if given explicitly, or to True. Example:

$ ./python -Xa=b -Xc
Python 3.2a3+ (py3k, Oct 16 2010, 20:14:50)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys._xoptions
{'a': 'b', 'c': True}

CPython implementation detail: This is a CPython-specific way of accessing options passed through -X. Other implementations may export them through other means, or not at all.

버전 3.2에 추가.

Citations

C99

ISO/IEC 9899:1999. “Programming languages – C.” A public draft of this standard is available at http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

파이썬 실행시간 서비스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

파이썬 실행시간 서비스 »

|

sysconfig — 파이썬의 구성 정보에 접근하기

버전 3.2에 추가.

소스 코드: Lib/sysconfig.py [https://github.com/python/cpython/tree/3.7/Lib/sysconfig.py]

sysconfig 모듈은 설치 경로 목록과 현재 플랫폼과 관련된 구성 변수와 같은 파이썬 구성 정보에 대한 액세스를 제공합니다.

구성 변수

Python 배포판에는 Makefile 과 pyconfig.h 헤더 파일이 들어 있습니다. 이 파일은 파이썬 바이너리 자체와 distutils 를 사용하여 컴파일된 타사 C 확장을 빌드하는 데 필요합니다.

sysconfig 는 get_config_vars() 또는 get_config_var()를 사용하여 액세스 할 수 있는 딕셔너리에 이들 파일에 있는 모든 변수를 넣습니다.

윈도우에서는 훨씬 작은 세트입니다.

sysconfig.get_config_vars(*args)

인자가 없으면, 현재 플랫폼과 관련된 모든 구성 변수의 딕셔너리를 반환합니다.

인자가 있으면, 인자를 사용하여 구성 변수 딕셔너리에서 각 인자를 조회한 결괏값 리스트를 돌려줍니다.

인자별로, 값이 없으면 None 을 반환합니다.

sysconfig.get_config_var(name)

하나의 변수 name 의 값을 반환합니다. get_config_vars().get(name) 과 같습니다.

name 을 찾지 못하면 None 을 반환합니다.

사용 예:

>>> import sysconfig
>>> sysconfig.get_config_var('Py_ENABLE_SHARED')
0
>>> sysconfig.get_config_var('LIBDIR')
'/usr/local/lib'
>>> sysconfig.get_config_vars('AR', 'CXX')
['ar', 'g++']

설치 경로

파이썬은 플랫폼과 설치 옵션에 따라 다른 설치 스킴을 사용합니다. 이 스킴은 os.name 에 의해 반환된 값을 기반으로 하는 고유한 식별자로 sysconfig 에 저장됩니다.

distutils 또는 Distutils 기반 시스템을 사용하여 설치되는 모든 새로운 구성 요소는 파일을 올바른 장소에 복사하기 위해 같은 스킴을 따릅니다.

파이썬은 현재 7가지 스킴을 지원합니다:

posix_prefix: scheme for POSIX platforms like Linux or Mac OS X. This is the default scheme used when Python or a component is installed.

posix_home: scheme for POSIX platforms used when a home option is used upon installation. This scheme is used when a component is installed through Distutils with a specific home prefix.

posix_user: scheme for POSIX platforms used when a component is installed through Distutils and the user option is used. This scheme defines paths located under the user home directory.

nt: 윈도우와 같은 NT 플랫폼을 위한 스킴.

nt_user: user 옵션이 사용될 때 NT 플랫폼용 스킴.

각 스킴은 일련의 경로로 구성되며 각 경로는 고유한 식별자를 가집니다. 파이썬은 현재 8개의 경로를 사용합니다:

stdlib: 플랫폼마다 다르지 않은 표준 파이썬 라이브러리 파일이 들어있는 디렉터리.

platstdlib: 플랫폼마다 다른 표준 파이썬 라이브러리 파일이 들어있는 디렉터리.

platlib: 사이트마다, 플랫폼마다 다른 파일용 디렉터리.

purelib: 사이트마다 다르지만, 플랫폼마다 다르지 않은 파일이 들어있는 디렉터리.

include: 플랫폼마다 다르지 않은 헤더 파일용 디렉터리.

platinclude: 플랫폼마다 다른 헤더 파일용 디렉터리.

scripts: 스크립트 파일용 디렉터리.

data: 데이터 파일용 디렉터리.

sysconfig 는 이러한 경로를 결정하는 몇 가지 함수를 제공합니다.

sysconfig.get_scheme_names()

현재 sysconfig 에서 지원되는 모든 스킴을 포함하는 튜플을 돌려줍니다.

sysconfig.get_path_names()

현재 sysconfig 에서 지원되는 모든 경로명을 포함하는 튜플을 돌려줍니다.

sysconfig.get_path(name[, scheme[, vars[, expand]]])

scheme 이라는 설치 스킴에서, 경로 name 에 해당하는 설치 경로를 돌려줍니다.

name 은 get_path_names() 가 돌려주는 리스트에 있는 값이어야 합니다.

sysconfig 는 각 경로명에 해당하는 설치 경로를 플랫폼별로 확장할 변수와 함께 저장합니다. 예를 들어, nt 스킴의 stdlib 경로는 {base}/Lib 입니다.

get_path() 는 get_config_vars() 에 의해 반환된 변수를 사용하여 경로를 확장합니다. 모든 변수는 각 플랫폼에 대한 기본값을 가지므로 이 함수를 호출하고 기본값을 가져올 수 있습니다.

scheme 이 제공되면, 그것은 get_scheme_names() 에 의해 반환된 리스트에 있는 값이어야 합니다. 그렇지 않으면, 현재 플랫폼의 기본 스킴이 사용됩니다.

vars 가 제공되면, get_config_vars() 에 의해 반환된 딕셔너리를 갱신할 변수의 딕셔너리여야 합니다.

expand 가 False 로 설정되면, 경로는 변수를 사용하여 확장되지 않습니다.

name 을 찾지 못하면 None 을 반환합니다.

sysconfig.get_paths([scheme[, vars[, expand]]])

설치 스킴에 해당하는 모든 설치 경로를 포함하는 딕셔너리를 돌려줍니다. 자세한 정보는 get_path() 를 보십시오.

scheme 을 제공하지 않으면, 현재 플랫폼에 대한 기본 스킴을 사용합니다.

vars 가 제공되면, 경로를 확장하는 데 사용되는 딕셔너리를 갱신하는 변수의 딕셔너리여야 합니다.

expand 를 거짓으로 설정하면 경로가 확장되지 않습니다.

scheme 이 존재하는 스킴이 아니면, get_paths() 는 KeyError 를 발생시킵니다.

기타 함수

sysconfig.get_python_version()

MAJOR.MINOR 파이썬 버전 번호를 문자열로 반환합니다. '%d.%d' % sys.version_info[:2] 와 유사합니다.

sysconfig.get_platform()

현재의 플랫폼을 식별하는 문자열을 돌려줍니다.

이는 주로 플랫폼별 빌드 디렉터리와 플랫폼별로 빌드 된 배포판을 구별하기 위해 사용됩니다. 포함된 정확한 정보는 OS에 따라 다르지만, 일반적으로 OS 이름과 버전 및 아키텍처를 포함합니다 (‘os.uname()’ 에서 제공됩니다); 예를 들어, 리눅스에서 커널 버전은 특별히 중요하지 않습니다.

반환 값의 예:

linux-i586

linux-alpha (?)

solaris-2.6-sun4u

윈도우는 다음 중 하나를 반환합니다:

win-amd64 (AMD64의 64비트 윈도우, 일명 x86_64, Intel64, EM64T 등)

win32 (기타 모든 것 - 구체적으로, sys.platform이 반환됩니다)

맥 OS X 는 다음을 반환 할 수 있습니다:

macosx-10.6-ppc

macosx-10.4-ppc64

macosx-10.3-i386

macosx-10.4-fat

다른 포직스 이외의 플랫폼의 경우, 현재는 sys.platform 만 반환합니다.

sysconfig.is_python_build()

실행 중인 파이썬 인터프리터가 소스에서 빌드되어 빌드 된 위치에서 실행되고, make install 을 실행하거나 바이너리 설치 프로그램을 통해 설치 한 결과가 아닌 위치에서 실행되는 것이 아니라면 True 를 반환합니다.

sysconfig.parse_config_h(fp[, vars])

config.h-스타일 파일을 해석합니다.

fp 는 config.h-류 파일을 가리키는 파일류 객체입니다.

이름/값 쌍을 포함하는 딕셔너리가 반환됩니다. 선택적 딕셔너리가 두 번째 인자로 전달되면, 새 사전 대신 사용되며 파일에서 읽은 값으로 갱신됩니다.

sysconfig.get_config_h_filename()

pyconfig.h 의 경로를 반환합니다.

sysconfig.get_makefile_filename()

Makefile 의 경로를 반환합니다.

sysconfig 를 스크립트로 사용하기

sysconfig 를 파이썬의 -m 옵션으로 스크립트로 사용할 수 있습니다:

$ python -m sysconfig
Platform: "macosx-10.4-i386"
Python version: "3.2"
Current installation scheme: "posix_prefix"

Paths:
        data = "/usr/local"
        include = "/Users/tarek/Dev/svn.python.org/py3k/Include"
        platinclude = "."
        platlib = "/usr/local/lib/python3.2/site-packages"
        platstdlib = "/usr/local/lib/python3.2"
        purelib = "/usr/local/lib/python3.2/site-packages"
        scripts = "/usr/local/bin"
        stdlib = "/usr/local/lib/python3.2"

Variables:
        AC_APPLE_UNIVERSAL_BUILD = "0"
        AIX_GENUINE_CPLUSPLUS = "0"
        AR = "ar"
        ARFLAGS = "rc"
        ...

이 호출은 get_platform(), get_python_version(), get_path() 및 get_config_vars() 에 의해 반환된 정보를 표준 출력에 인쇄합니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

파이썬 실행시간 서비스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

파이썬 실행시간 서비스 »

|

builtins — 내장 객체

이 모듈은 파이썬의 모든 ‘내장’ 식별자에 대한 직접 액세스를 제공합니다. 예를 들어, builtins.open 은 내장 함수 open() 의 완전한 이름입니다. 설명서는 내장 함수 와 내장 상수를 참조하세요.

이 모듈은 일반적으로 대부분의 응용 프로그램에서 명시적으로 액세스하지 않지만, 내장된 값과 이름이 같은 객체를 제공하면서도 그 이름의 내장 객체가 필요한 모듈에서 유용 할 수 있습니다. 예를 들어, 내장 open() 을 감싸는 open() 함수를 구현하고자 하는 모듈에서 이 모듈을 직접 사용할 수 있습니다:

import builtins

def open(path):
    f = builtins.open(path, 'r')
    return UpperCaser(f)

class UpperCaser:
    '''Wrapper around a file that converts output to upper-case.'''

    def __init__(self, f):
        self._f = f

    def read(self, count=-1):
        return self._f.read(count).upper()

    # ...

구현 세부 사항으로, 대부분 모듈은 전역 변수로 __builtins__ 라는 이름을 가지고 있습니다. __builtins__ 의 값은, 보통 이 모듈이거나 모듈의 __dict__ 어트리뷰트의 값입니다. 이것은 구현 세부 사항이므로, 파이썬의 대안 구현에서는 사용되지 않을 수 있습니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

파이썬 실행시간 서비스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

파이썬 실행시간 서비스 »

|

__main__ — 최상위 스크립트 환경

'__main__' 은 최상위 코드가 실행되는 스코프의 이름입니다. 모듈의 __name__ 은 표준 입력, 스크립트 또는 대화식 프롬프트에서 읽힐 때 '__main__' 으로 설정됩니다.

모듈은 자신의 __name__ 을 검사하여 메인 스코프에서 실행 중인지를 확인할 수 있습니다. 이 때문에 임포트될 때는 실행되지 않지만, 스크립트로 실행되거나 python -m 으로 실행될 때 조건부로 동작하는 공통 관용구를 사용할 수 있습니다:

if __name__ == "__main__":
    # execute only if run as a script
    main()

패키지의 경우, __main__.py 모듈을 포함 시키면 같은 효과를 얻을 수 있습니다. 모듈의 내용은 모듈이 -m 으로 실행될 때 실행됩니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

파이썬 실행시간 서비스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

파이썬 실행시간 서비스 »

|

warnings — Warning control

Source code: Lib/warnings.py [https://github.com/python/cpython/tree/3.7/Lib/warnings.py]

Warning messages are typically issued in situations where it is useful to alert the user of some condition in a program, where that condition (normally) doesn’t warrant raising an exception and terminating the program. For example, one might want to issue a warning when a program uses an obsolete module.

Python programmers issue warnings by calling the warn() function defined in this module. (C programmers use PyErr_WarnEx(); see Exception Handling for details).

Warning messages are normally written to sys.stderr, but their disposition can be changed flexibly, from ignoring all warnings to turning them into exceptions. The disposition of warnings can vary based on the warning category (see below), the text of the warning message, and the source location where it is issued. Repetitions of a particular warning for the same source location are typically suppressed.

There are two stages in warning control: first, each time a warning is issued, a determination is made whether a message should be issued or not; next, if a message is to be issued, it is formatted and printed using a user-settable hook.

The determination whether to issue a warning message is controlled by the warning filter, which is a sequence of matching rules and actions. Rules can be added to the filter by calling filterwarnings() and reset to its default state by calling resetwarnings().

The printing of warning messages is done by calling showwarning(), which may be overridden; the default implementation of this function formats the message by calling formatwarning(), which is also available for use by custom implementations.

더 보기

logging.captureWarnings() allows you to handle all warnings with the standard logging infrastructure.

Warning Categories

There are a number of built-in exceptions that represent warning categories. This categorization is useful to be able to filter out groups of warnings.

While these are technically built-in exceptions, they are documented here, because conceptually they belong to the warnings mechanism.

User code can define additional warning categories by subclassing one of the standard warning categories. A warning category must always be a subclass of the Warning class.

The following warnings category classes are currently defined:

Class

Description

Warning

This is the base class of all warning category classes. It is a subclass of Exception.

UserWarning

The default category for warn().

DeprecationWarning

Base category for warnings about deprecated features when those warnings are intended for other Python developers (ignored by default, unless triggered by code in __main__).

SyntaxWarning

Base category for warnings about dubious syntactic features.

RuntimeWarning

Base category for warnings about dubious runtime features.

FutureWarning

Base category for warnings about deprecated features when those warnings are intended for end users of applications that are written in Python.

PendingDeprecationWarning

Base category for warnings about features that will be deprecated in the future (ignored by default).

ImportWarning

Base category for warnings triggered during the process of importing a module (ignored by default).

UnicodeWarning

Base category for warnings related to Unicode.

BytesWarning

Base category for warnings related to bytes and bytearray.

ResourceWarning

Base category for warnings related to resource usage.

버전 3.7에서 변경: Previously DeprecationWarning and FutureWarning were distinguished based on whether a feature was being removed entirely or changing its behaviour. They are now distinguished based on their intended audience and the way they’re handled by the default warnings filters.

The Warnings Filter

The warnings filter controls whether warnings are ignored, displayed, or turned into errors (raising an exception).

Conceptually, the warnings filter maintains an ordered list of filter specifications; any specific warning is matched against each filter specification in the list in turn until a match is found; the filter determines the disposition of the match. Each entry is a tuple of the form (action, message, category, module, lineno), where:

action is one of the following strings:

Value

Disposition

"default"

print the first occurrence of matching warnings for each location (module + line number) where the warning is issued

"error"

turn matching warnings into exceptions

"ignore"

never print matching warnings

"always"

always print matching warnings

"module"

print the first occurrence of matching warnings for each module where the warning is issued (regardless of line number)

"once"

print only the first occurrence of matching warnings, regardless of location

message is a string containing a regular expression that the start of the warning message must match. The expression is compiled to always be case-insensitive.

category is a class (a subclass of Warning) of which the warning category must be a subclass in order to match.

module is a string containing a regular expression that the module name must match. The expression is compiled to be case-sensitive.

lineno is an integer that the line number where the warning occurred must match, or 0 to match all line numbers.

Since the Warning class is derived from the built-in Exception class, to turn a warning into an error we simply raise category(message).

If a warning is reported and doesn’t match any registered filter then the “default” action is applied (hence its name).

Describing Warning Filters

The warnings filter is initialized by -W options passed to the Python interpreter command line and the PYTHONWARNINGS environment variable. The interpreter saves the arguments for all supplied entries without interpretation in sys.warnoptions; the warnings module parses these when it is first imported (invalid options are ignored, after printing a message to sys.stderr).

Individual warnings filters are specified as a sequence of fields separated by colons:

action:message:category:module:line

The meaning of each of these fields is as described in The Warnings Filter. When listing multiple filters on a single line (as for PYTHONWARNINGS), the individual filters are separated by commas,and the filters listed later take precedence over those listed before them (as they’re applied left-to-right, and the most recently applied filters take precedence over earlier ones).

Commonly used warning filters apply to either all warnings, warnings in a particular category, or warnings raised by particular modules or packages. Some examples:

default                      # Show all warnings (even those ignored by default)
ignore                       # Ignore all warnings
error                        # Convert all warnings to errors
error::ResourceWarning       # Treat ResourceWarning messages as errors
default::DeprecationWarning  # Show DeprecationWarning messages
ignore,default:::mymodule    # Only report warnings triggered by "mymodule"
error:::mymodule[.*]         # Convert warnings to errors in "mymodule"
                             # and any subpackages of "mymodule"

Default Warning Filter

By default, Python installs several warning filters, which can be overridden by the -W command-line option, the PYTHONWARNINGS environment variable and calls to filterwarnings().

In regular release builds, the default warning filter has the following entries (in order of precedence):

default::DeprecationWarning:__main__
ignore::DeprecationWarning
ignore::PendingDeprecationWarning
ignore::ImportWarning
ignore::ResourceWarning

In debug builds, the list of default warning filters is empty.

버전 3.2에서 변경: DeprecationWarning is now ignored by default in addition to PendingDeprecationWarning.

버전 3.7에서 변경: DeprecationWarning is once again shown by default when triggered directly by code in __main__.

버전 3.7에서 변경: BytesWarning no longer appears in the default filter list and is instead configured via sys.warnoptions when -b is specified twice.

Overriding the default filter

Developers of applications written in Python may wish to hide all Python level warnings from their users by default, and only display them when running tests or otherwise working on the application. The sys.warnoptions attribute used to pass filter configurations to the interpreter can be used as a marker to indicate whether or not warnings should be disabled:

import sys

if not sys.warnoptions:
    import warnings
    warnings.simplefilter("ignore")

Developers of test runners for Python code are advised to instead ensure that all warnings are displayed by default for the code under test, using code like:

import sys

if not sys.warnoptions:
    import os, warnings
    warnings.simplefilter("default") # Change the filter in this process
    os.environ["PYTHONWARNINGS"] = "default" # Also affect subprocesses

Finally, developers of interactive shells that run user code in a namespace other than __main__ are advised to ensure that DeprecationWarning messages are made visible by default, using code like the following (where user_ns is the module used to execute code entered interactively):

import warnings
warnings.filterwarnings("default", category=DeprecationWarning,
                                   module=user_ns.get("__name__"))

Temporarily Suppressing Warnings

If you are using code that you know will raise a warning, such as a deprecated function, but do not want to see the warning (even when warnings have been explicitly configured via the command line), then it is possible to suppress the warning using the catch_warnings context manager:

import warnings

def fxn():
    warnings.warn("deprecated", DeprecationWarning)

with warnings.catch_warnings():
    warnings.simplefilter("ignore")
    fxn()

While within the context manager all warnings will simply be ignored. This allows you to use known-deprecated code without having to see the warning while not suppressing the warning for other code that might not be aware of its use of deprecated code. Note: this can only be guaranteed in a single-threaded application. If two or more threads use the catch_warnings context manager at the same time, the behavior is undefined.

Testing Warnings

To test warnings raised by code, use the catch_warnings context manager. With it you can temporarily mutate the warnings filter to facilitate your testing. For instance, do the following to capture all raised warnings to check:

import warnings

def fxn():
    warnings.warn("deprecated", DeprecationWarning)

with warnings.catch_warnings(record=True) as w:
    # Cause all warnings to always be triggered.
    warnings.simplefilter("always")
    # Trigger a warning.
    fxn()
    # Verify some things
    assert len(w) == 1
    assert issubclass(w[-1].category, DeprecationWarning)
    assert "deprecated" in str(w[-1].message)

One can also cause all warnings to be exceptions by using error instead of always. One thing to be aware of is that if a warning has already been raised because of a once/default rule, then no matter what filters are set the warning will not be seen again unless the warnings registry related to the warning has been cleared.

Once the context manager exits, the warnings filter is restored to its state when the context was entered. This prevents tests from changing the warnings filter in unexpected ways between tests and leading to indeterminate test results. The showwarning() function in the module is also restored to its original value. Note: this can only be guaranteed in a single-threaded application. If two or more threads use the catch_warnings context manager at the same time, the behavior is undefined.

When testing multiple operations that raise the same kind of warning, it is important to test them in a manner that confirms each operation is raising a new warning (e.g. set warnings to be raised as exceptions and check the operations raise exceptions, check that the length of the warning list continues to increase after each operation, or else delete the previous entries from the warnings list before each new operation).

Updating Code For New Versions of Dependencies

Warning categories that are primarily of interest to Python developers (rather than end users of applications written in Python) are ignored by default.

Notably, this “ignored by default” list includes DeprecationWarning (for every module except __main__), which means developers should make sure to test their code with typically ignored warnings made visible in order to receive timely notifications of future breaking API changes (whether in the standard library or third party packages).

In the ideal case, the code will have a suitable test suite, and the test runner will take care of implicitly enabling all warnings when running tests (the test runner provided by the unittest module does this).

In less ideal cases, applications can be checked for use of deprecated interfaces by passing -Wd to the Python interpreter (this is shorthand for -W default) or setting PYTHONWARNINGS=default in the environment. This enables default handling for all warnings, including those that are ignored by default. To change what action is taken for encountered warnings you can change what argument is passed to -W (e.g. -W error). See the -W flag for more details on what is possible.

Available Functions

warnings.warn(message, category=None, stacklevel=1, source=None)

Issue a warning, or maybe ignore it or raise an exception. The category argument, if given, must be a warning category class (see above); it defaults to UserWarning. Alternatively message can be a Warning instance, in which case category will be ignored and message.__class__ will be used. In this case the message text will be str(message). This function raises an exception if the particular warning issued is changed into an error by the warnings filter see above. The stacklevel argument can be used by wrapper functions written in Python, like this:

def deprecation(message):
    warnings.warn(message, DeprecationWarning, stacklevel=2)

This makes the warning refer to deprecation()’s caller, rather than to the source of deprecation() itself (since the latter would defeat the purpose of the warning message).

source, if supplied, is the destroyed object which emitted a ResourceWarning.

버전 3.6에서 변경: Added source parameter.

warnings.warn_explicit(message, category, filename, lineno, module=None, registry=None, module_globals=None, source=None)

This is a low-level interface to the functionality of warn(), passing in explicitly the message, category, filename and line number, and optionally the module name and the registry (which should be the __warningregistry__ dictionary of the module). The module name defaults to the filename with .py stripped; if no registry is passed, the warning is never suppressed. message must be a string and category a subclass of Warning or message may be a Warning instance, in which case category will be ignored.

module_globals, if supplied, should be the global namespace in use by the code for which the warning is issued. (This argument is used to support displaying source for modules found in zipfiles or other non-filesystem import sources).

source, if supplied, is the destroyed object which emitted a ResourceWarning.

버전 3.6에서 변경: Add the source parameter.

warnings.showwarning(message, category, filename, lineno, file=None, line=None)

Write a warning to a file. The default implementation calls formatwarning(message, category, filename, lineno, line) and writes the resulting string to file, which defaults to sys.stderr. You may replace this function with any callable by assigning to warnings.showwarning. line is a line of source code to be included in the warning message; if line is not supplied, showwarning() will try to read the line specified by filename and lineno.

warnings.formatwarning(message, category, filename, lineno, line=None)

Format a warning the standard way. This returns a string which may contain embedded newlines and ends in a newline. line is a line of source code to be included in the warning message; if line is not supplied, formatwarning() will try to read the line specified by filename and lineno.

warnings.filterwarnings(action, message='', category=Warning, module='', lineno=0, append=False)

Insert an entry into the list of warnings filter specifications. The entry is inserted at the front by default; if append is true, it is inserted at the end. This checks the types of the arguments, compiles the message and module regular expressions, and inserts them as a tuple in the list of warnings filters. Entries closer to the front of the list override entries later in the list, if both match a particular warning. Omitted arguments default to a value that matches everything.

warnings.simplefilter(action, category=Warning, lineno=0, append=False)

Insert a simple entry into the list of warnings filter specifications. The meaning of the function parameters is as for filterwarnings(), but regular expressions are not needed as the filter inserted always matches any message in any module as long as the category and line number match.

warnings.resetwarnings()

Reset the warnings filter. This discards the effect of all previous calls to filterwarnings(), including that of the -W command line options and calls to simplefilter().

Available Context Managers

class warnings.catch_warnings(*, record=False, module=None)

A context manager that copies and, upon exit, restores the warnings filter and the showwarning() function. If the record argument is False (the default) the context manager returns None on entry. If record is True, a list is returned that is progressively populated with objects as seen by a custom showwarning() function (which also suppresses output to sys.stdout). Each object in the list has attributes with the same names as the arguments to showwarning().

The module argument takes a module that will be used instead of the module returned when you import warnings whose filter will be protected. This argument exists primarily for testing the warnings module itself.

참고

The catch_warnings manager works by replacing and then later restoring the module’s showwarning() function and internal list of filter specifications. This means the context manager is modifying global state and therefore is not thread-safe.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

파이썬 실행시간 서비스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

파이썬 실행시간 서비스 »

|

dataclasses — 데이터 클래스

소스 코드: Lib/dataclasses.py [https://github.com/python/cpython/tree/3.7/Lib/dataclasses.py]

이 모듈은 __init__() 나 __repr__() 과 같은 생성된 특수 메서드 를 사용자 정의 클래스에 자동으로 추가하는 데코레이터와 함수를 제공합니다. 원래 PEP 557 [https://www.python.org/dev/peps/pep-0557] 에 설명되어 있습니다.

생성된 메서드에서 사용할 멤버 변수는 PEP 526 [https://www.python.org/dev/peps/pep-0526] 형 어노테이션을 사용하여 정의됩니다. 예를 들어, 이 코드는:

from dataclasses import dataclass

@dataclass
class InventoryItem:
    '''Class for keeping track of an item in inventory.'''
    name: str
    unit_price: float
    quantity_on_hand: int = 0

    def total_cost(self) -> float:
        return self.unit_price * self.quantity_on_hand

다른 것 중에서도, 다음과 같은 __init__() 를 추가합니다:

def __init__(self, name: str, unit_price: float, quantity_on_hand: int=0):
    self.name = name
    self.unit_price = unit_price
    self.quantity_on_hand = quantity_on_hand

이 메서드는 클래스에 자동으로 추가됩니다: 위의 InventoryItem 정의에서 직접 지정되지는 않았습니다.

버전 3.7에 추가.

모듈 수준의 데코레이터, 클래스 및 함수

@dataclasses.dataclass(*, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False)

이 함수는 (아래에서 설명하는) 생성된 특수 메서드를 클래스에 추가하는데 사용되는 데코레이터 입니다.

dataclass() 데코레이터는 클래스를 검사하여 필드를 찾습니다. 필드는 형 어노테이션을 가진 클래스 변수로 정의됩니다. 아래에 설명된 두 가지 예외를 제외하고는, dataclass() 는 변수 어노테이션에 지정된 형을 검사하지 않습니다.

생성된 모든 메서드의 필드 순서는 클래스 정의에 나타나는 순서입니다.

dataclass() 데코레이터는 여러 “따분한” 메서드들을 클래스에 추가하는데, 아래에서 설명합니다. 추가할 메서드가 클래스에 이미 존재하면, 동작은 매개 변수에 따라 다른데, 아래에 문서화됩니다. 데코레이터는 호출된 클래스와 같은 클래스를 반환합니다: 새 클래스가 만들어지지 않습니다.

dataclass() 가 매개변수 없는 단순한 데코레이터로 사용되면, 이 서명에 문서화 된 기본값들이 제공된 것처럼 행동합니다. 즉, 다음 dataclass() 의 세 가지 용법은 동등합니다:

@dataclass
class C:
    ...

@dataclass()
class C:
    ...

@dataclass(init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False)
class C:
   ...

dataclass() 의 매개변수는 다음과 같습니다:

init: 참(기본값)이면, __init__() 메서드가 생성됩니다.

클래스가 이미 __init__() 를 정의했으면, 이 매개변수는 무시됩니다.

repr: 참(기본값)이면, __repr__() 메서드가 생성됩니다. 생성된 repr 문자열은 클래스 이름과 각 필드의 이름과 repr 을 갖습니다. 각 필드는 클래스에 정의된 순서대로 표시됩니다. repr에서 제외하도록 표시된 필드는 포함되지 않습니다. 예를 들어: 예 :InventoryItem(name='widget', unit_price=3.0, quantity_on_hand=10).

클래스가 이미 __repr__() 을 정의했으면, 이 매개변수는 무시됩니다.

eq: 참(기본값)이면, __eq__() 메서드가 생성됩니다. 이 메서드는 클래스를 필드의 튜플인 것처럼 순서대로 비교합니다. 비교되는 두 인스턴스는 같은 형이어야 합니다.

클래스가 이미 __eq__() 를 정의했으면, 이 매개변수는 무시됩니다.

order: 참이면 (기본값은 False), __lt__(), __le__(), __gt__(), __ge__() 메서드가 생성됩니다. 이것들은 클래스를 필드의 튜플인 것처럼 순서대로 비교합니다. 비교되는 두 인스턴스는 같은 형이어야 합니다. order 가 참이고 eq 가 거짓이면 ValueError 가 발생합니다.

클래스가 이미 __lt__(), __le__(), __gt__(), __ge__() 중 하나를 정의하고 있다면 TypeError 가 발생합니다.

unsafe_hash: False (기본값) 면 : eq 와 frozen 의 설정에 따라 __hash__() 메서드가 생성됩니다.

__hash__() 는 내장 hash() 에 의해 사용되며, 딕셔너리와 집합 같은 해시 컬렉션에 객체가 추가될 때 사용됩니다. __hash__() 를 갖는다는 것은 클래스의 인스턴스가 불변이라는 것을 의미합니다. 가변성은 프로그래머의 의도, __eq__() 의 존재와 행동, dataclass() 데코레이터의 eq 와 frozen 플래그의 값에 의존하는 복잡한 성질입니다.

기본적으로, dataclass() 는 안전하지 않다면 __hash__() 메서드를 묵시적으로 추가하지 않습니다. 기존에 명시적으로 정의된 __hash__() 메서드를 추가하거나 변경하지도 않습니다. __hash__() 문서에서 설명된 대로, 클래스 어트리뷰트를 __hash__ = None 로 설정하는 것은 파이썬에 특별한 의미가 있습니다.

__hash__() 가 명시적으로 정의되어 있지 않거나 None 으로 설정된 경우, dataclass() 는 묵시적 __hash__() 메서드를 추가할 수 있습니다. 권장하지는 않지만, unsafe_hash=True 로 dataclass() 가 __hash__() 메서드를 만들도록 강제할 수 있습니다. 이것은 당신의 클래스가 논리적으로 불변이지만, 그런데도 변경될 수 있는 경우 일 수 있습니다. 이는 특수한 사용 사례이므로 신중하게 고려해야 합니다.

다음은 __hash__() 메서드의 묵시적 생성을 관장하는 규칙입니다. 데이터 클래스에 명시적 __hash__() 메서드를 가지면서 unsafe_hash=True 를 설정할 수는 없습니다; 그러면 TypeError 가 발생합니다.

eq 와 frozen 이 모두 참이면, 기본적으로 dataclass() 는 __hash__() 메서드를 만듭니다. eq 가 참이고 frozen 이 거짓이면, __hash__() 가 None 으로 설정되어 해시 불가능하다고 표시됩니다(가변이기 때문입니다). 만약 eq 가 거짓이면, __hash__() 를 건드리지 않는데, 슈퍼 클래스의 __hash__() 가 사용된다는 뜻이 됩니다 (슈퍼 클래스가 object 라면, id 기반 해싱으로 돌아간다는 뜻입니다).

frozen: If true (the default is False), assigning to fields will generate an exception. This emulates read-only frozen instances. If __setattr__() or __delattr__() is defined in the class, then TypeError is raised. See the discussion below.

필드는 선택적으로 일반적인 파이썬 문법을 사용하여 기본값을 지정할 수 있습니다:

@dataclass
class C:
    a: int       # 'a' has no default value
    b: int = 0   # assign a default value for 'b'

이 예제에서, a 와 b 모두 추가된 __init__() 메서드에 포함되는데, 이런 식으로 정의됩니다:

def __init__(self, a: int, b: int = 0):

기본값이 없는 필드가 기본값이 있는 필드 뒤에 오는 경우 TypeError 가 발생합니다. 이것은 단일 클래스에서 일어날 수도 있고, 클래스 상속의 결과일 때도 마찬가지입니다.

dataclasses.field(*, default=MISSING, default_factory=MISSING, repr=True, hash=None, init=True, compare=True, metadata=None)

일반적이고 간단한 사용 사례의 경우 다른 기능은 필요하지 않습니다. 그러나 필드별로 추가 정보가 필요한 일부 데이터 클래스 기능이 있습니다. 추가 정보에 대한 필요성을 충족시키기 위해, 기본 필드 값을 제공된 field() 함수 호출로 바꿀 수 있습니다. 예를 들면:

@dataclass
class C:
    mylist: List[int] = field(default_factory=list)

c = C()
c.mylist += [1, 2, 3]

위에서 보인 것처럼, MISSING 값은 default 와 default_factory 매개변수가 제공되는지를 탐지하는데 사용되는 표지 객체입니다. None 이 default 에 유효한 값이기 때문에 이 표지가 사용됩니다. 어떤 코드도 MISSING 값을 직접 사용해서는 안 됩니다.

field() 의 매개변수는 다음과 같습니다:

default: 제공되면, 이 필드의 기본값이 됩니다. 이것은 field() 호출 자체가 기본값의 정상 위치를 대체하기 때문에 필요합니다.

default_factory: 제공되면, 이 필드의 기본값이 필요할 때 호출되는 인자가 없는 콜러블이어야 합니다. 여러 용도 중에서도, 이것은 아래에서 논의되는 것처럼 가변 기본값을 가진 필드를 지정하는 데 사용될 수 있습니다. default 와 default_factory 를 모두 지정하는 것은 에러입니다.

init: 참(기본값)이면, 이 필드는 생성된 __init__() 메서드의 매개변수로 포함됩니다.

repr: 참(기본값)이면, 이 필드는 생성된 __repr__() 메서드가 돌려주는 문자열에 포함됩니다.

compare: 참(기본값)이면, 이 필드는 생성된 같음 및 비교 메서드(__eq__(), __gt__() 등)에 포함됩니다.

hash: 이것은 bool 또는 None 일 수 있습니다. 참이면, 이 필드는 생성된 __hash__() 메서드에 포함됩니다. None (기본값) 이면, compare 의 값을 사용합니다. 이것은 일반적으로 기대되는 행동입니다. 필드가 비교에 사용되면 해시에서 고려해야 합니다. 이 값을 None 이외의 값으로 설정하는 것은 권장하지 않습니다.

hash=False 이지만 compare=True 로 설정하는 한 가지 가능한 이유는, 동등 비교에 포함되는 필드가 해시값을 계산하는 데 비용이 많이 들고, 형의 해시값에 이바지하는 다른 필드가 있는 경우입니다. 필드가 해시에서 제외된 경우에도 비교에는 계속 사용됩니다.

metadata: 매핑이나 None이 될 수 있습니다. None은 빈 딕셔너리로 취급됩니다. 이 값은 MappingProxyType() 로 감싸져서 읽기 전용으로 만들어지고, Field 객체에 노출됩니다. 데이터 클래스에서는 전혀 사용되지 않으며, 제삼자 확장 메커니즘으로 제공됩니다. 여러 제삼자는 이름 공간으로 사용할 자신만의 키를 가질 수 있습니다.

필드의 기본값이 field() 호출로 지정되면, 이 필드의 클래스 어트리뷰트는 지정한 default 값으로 대체됩니다. default 가 제공되지 않으면 클래스 어트리뷰트는 삭제됩니다. 그 의도는, dataclass() 데코레이터 실행 후에, 기본값 자체가 지정된 것처럼 클래스 어트리뷰트가 모드 필드의 기본값을 갖도록 만드는 것입니다. 예를 들어, 이렇게 한 후에는:

@dataclass
class C:
    x: int
    y: int = field(repr=False)
    z: int = field(repr=False, default=10)
    t: int = 20

클래스 어트리뷰트 C.z 는 10 이 되고, 클래스 어트리뷰트 C.t 는 20 이 되고, 클래스 어트리뷰트 C.x 와 C.y 는 설정되지 않게 됩니다.

class dataclasses.Field

Field 객체는 정의된 각 필드를 설명합니다. 이 객체는 내부적으로 생성되며 fields() 모듈 수준 메서드(아래 참조)가 돌려줍니다. 사용자는 직접 Field 인스턴스 객체를 만들어서는 안 됩니다. 문서화 된 어트리뷰트는 다음과 같습니다:

name: 필드의 이름.

type: 필드의 형.

default, default_factory, init, repr, hash, compare, metadata 는 field() 선언에서와 같은 의미와 값을 가지고 있습니다.

다른 어트리뷰트도 있을 수 있지만, 내부적인 것이므로 검사하거나 의존해서는 안 됩니다.

dataclasses.fields(class_or_instance)

데이터 클래스의 필드들을 정의하는 Field 객체들의 튜플을 돌려줍니다. 데이터 클래스나 데이터 클래스의 인스턴스를 받아들입니다. 데이터 클래스 나 데이터 클래스의 인스턴스를 전달하지 않으면 TypeError 를 돌려줍니다. ClassVar 또는 InitVar 인 의사 필드는 반환하지 않습니다.

dataclasses.asdict(instance, *, dict_factory=dict)

데이터 클래스 instance 를 딕셔너리로 변환합니다 (팩토리 함수 dict_factory 를 사용합니다). 각 데이터 클래스는 각 필드를 name: value 쌍으로 갖는 딕셔너리로 변환됩니다. 데이터 클래스, 딕셔너리, 리스트 및 튜플은 재귀적으로 변환됩니다. 예를 들면:

@dataclass
class Point:
     x: int
     y: int

@dataclass
class C:
     mylist: List[Point]

p = Point(10, 20)
assert asdict(p) == {'x': 10, 'y': 20}

c = C([Point(0, 0), Point(10, 4)])
assert asdict(c) == {'mylist': [{'x': 0, 'y': 0}, {'x': 10, 'y': 4}]}

instance 가 데이터 클래스 인스턴스가 아닌 경우 TypeError 를 일으킵니다.

dataclasses.astuple(instance, *, tuple_factory=tuple)

데이터 클래스 instance 를 튜플로 변환합니다 (팩토리 함수 tuple_factory 를 사용합니다). 각 데이터 클래스는 각 필드 값들의 튜플로 변환됩니다. 데이터 클래스, 딕셔너리, 리스트 및 튜플은 재귀적으로 변환됩니다.

이전 예에서 계속하면:

assert astuple(p) == (10, 20)
assert astuple(c) == ([(0, 0), (10, 4)],)

instance 가 데이터 클래스 인스턴스가 아닌 경우 TypeError 를 일으킵니다.

dataclasses.make_dataclass(cls_name, fields, *, bases=(), namespace=None, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False)

새로운 데이터 클래스를 만드는데, 이름은 cls_name 이고, fields 에 정의된 필드들을 갖고, bases 에 주어진 베이스 클래스들을 갖고, namespace 로 주어진 이름 공간으로 초기화됩니다. fields 는 요소가 name, (name, type) 또는 (name, type, Field) 인 이터러블입니다. name 만 제공되면 typing.Any 가 type 으로 사용됩니다. init, repr, eq, order, unsafe_hash, frozen 의 값은 dataclass() 에서와 같은 의미가 있습니다.

이 함수가 꼭 필요하지는 않습니다. 임의의 파이썬 메커니즘으로 __annotations__ 을 갖는 새 클래스를 만든 후에 dataclass() 함수를 적용하면 데이터 클래스로 변환되기 때문입니다. 이 함수는 편의상 제공됩니다. 예를 들어:

C = make_dataclass('C',
                   [('x', int),
                     'y',
                    ('z', int, field(default=5))],
                   namespace={'add_one': lambda self: self.x + 1})

는 다음과 동등합니다:

@dataclass
class C:
    x: int
    y: 'typing.Any'
    z: int = 5

    def add_one(self):
        return self.x + 1

dataclasses.replace(instance, **changes)

instance 와 같은 형의 새 객체를 만드는데, 필드를 changes 의 값들로 대체합니다. instance 가 데이터 클래스가 아니라면 TypeError 를 발생시킵니다. changes 의 값이 필드를 지정하지 않으면 TypeError 를 발생시킵니다.

새로 반환된 객체는 데이터 클래스의 __init__() 메서드를 호출하여 생성됩니다. 이렇게 함으로써 (있는 경우) __post_init__() 의 호출을 보장합니다.

기본값을 가지지 않는 초기화 전용 변수가 존재한다면, replace() 호출에 반드시 지정해서 __init__() 와 __post_init__() 에 전달 될 수 있도록 해야 합니다.

changes 가 init=False 를 갖는 것으로 정의된 필드를 포함하는 것은 에러입니다. 이 경우 ValueError 가 발생합니다.

replace()를 호출하는 동안 init=False 필드가 어떻게 작동하는지 미리 경고합니다. 그것들은 소스 객체로부터 복사되는 것이 아니라, (초기화되기는 한다면) __post_init__() 에서 초기화됩니다. init=False 필드는 거의 사용되지 않으리라고 예상합니다. 사용된다면, 대체 클래스 생성자를 사용하거나, 인스턴스 복사를 처리하는 사용자 정의 replace() (또는 비슷하게 이름 지어진) 메서드를 사용하는 것이 좋을 것입니다.

dataclasses.is_dataclass(class_or_instance)

Return True if its parameter is a dataclass or an instance of one, otherwise return False.

(데이터 클래스 자체가 아니라) 데이터 클래스의 인스턴스인지 알아야 한다면 not isinstance(obj, type) 검사를 추가하십시오:

def is_dataclass_instance(obj):
    return is_dataclass(obj) and not isinstance(obj, type)

초기화 후처리

클래스에 __post_init__() 가 정의된 경우, 생성된 __init__() 코드는 __post_init__() 메서드를 호출합니다. 일반적으로 self.__post_init__() 로 호출됩니다. 그러나, InitVar 필드가 정의되어 있으면, 클래스에 정의된 순서대로 __post_init__() 로 전달됩니다. __init__() 메서드가 생성되지 않으면, __post_init__() 가 자동으로 호출되지 않습니다.

다른 용도 중에서도, 하나나 그 이상의 다른 필드에 의존하는 필드 값을 초기화하는데 사용할 수 있습니다. 예를 들면:

@dataclass
class C:
    a: float
    b: float
    c: float = field(init=False)

    def __post_init__(self):
        self.c = self.a + self.b

매개변수를 __post_init__() 에 전달하는 방법은 초기화 전용 변수에 대한 아래 섹션을 참조하십시오. 또한 replace() 가 init=False 필드를 처리하는 방식에 관한 경고를 보십시오.

클래스 변수

dataclass() 가 실제로 필드의 형을 검사하는 두 곳 중 하나는 필드가 PEP 526 [https://www.python.org/dev/peps/pep-0526] 에 정의된 클래스 변수인지를 확인하는 것입니다. 필드의 형이 typing.ClassVar 인지 검사합니다. 필드가 ClassVar 인 경우, 필드로 취급되지 않고 데이터 클래스 메커니즘에서 무시됩니다. 이런 ClassVar 의사 필드는 모듈 수준 fields() 함수에 의해 반환되지 않습니다.

초기화 전용 변수

dataclass() 가 형 어노테이션을 검사하는 다른 한 곳은 필드가 초기화 전용 변수인지 확인하는 것입니다. 필드의 형이 dataclasses.InitVar 인지 검사합니다. 필드가 InitVar 인 경우, 초기화 전용 변수라고 불리는 의사 필드로 간주합니다. 실제 필드가 아니므로, 모듈 수준 fields() 함수에 의해 반환되지 않습니다. 초기화 전용 필드는 생성된 __init__() 메서드의 매개변수로 추가되며, 선택적인 __post_init__() 메서드로 전달됩니다. 이 외에 데이터 클래스에서 사용되는 곳은 없습니다.

예를 들어, 클래스를 만들 때 값이 제공되지 않으면, 필드가 데이터베이스로부터 초기화된다고 가정합시다:

@dataclass
class C:
    i: int
    j: int = None
    database: InitVar[DatabaseType] = None

    def __post_init__(self, database):
        if self.j is None and database is not None:
            self.j = database.lookup('j')

c = C(10, database=my_database)

이 경우, fields() 는 i 와 j 를 위한 Field 객체를 반환하지만, database 는 반환하지 않습니다.

고정 인스턴스

정말로 불변인 파이썬 객체를 만드는 것은 불가능합니다. 그러나, frozen=True 를 dataclass() 데코레이터에 전달함으로써 불변성을 흉내 낼 수 있습니다. 이 경우, 데이터 클래스는 __setattr__() 과 __delattr__() 메서드를 클래스에 추가합니다. 이 메서드는 호출될 때 FrozenInstanceError 를 발생시킵니다.

frozen=True 를 사용할 때 약간의 성능 저하가 있습니다: __init__() 는 필드를 초기화하는데 간단한 대입을 사용할 수 없고, object.__setattr__() 을 사용해야 합니다.

계승

데이터 클래스가 dataclass() 데코레이터에 의해 생성될 때, 클래스의 모든 베이스 클래스들을 MRO 역순(즉, object 에서 시작해서)으로 조사하고, 발견되는 데이터 클래스마다 그 베이스 클래스의 필드들을 순서 있는 필드 매핑에 추가합니다. 모든 생성된 메서드들은 이 합쳐지고 계산된 순서 있는 필드 매핑을 사용합니다. 필드들이 삽입 순서이기 때문에, 파생 클래스는 베이스 클래스를 재정의합니다. 예:

@dataclass
class Base:
    x: Any = 15.0
    y: int = 0

@dataclass
class C(Base):
    z: int = 10
    x: int = 15

필드의 최종 목록은 순서대로 x, y, z 입니다. x 의 최종 형은 클래스 C 에서 지정된 int 입니다.

생성된 C 의 __init__() 메서드는 이렇게 됩니다:

def __init__(self, x: int = 15, y: int = 0, z: int = 10):

기본 팩토리 함수

field() 가 default_factory 를 지정하면, 필드의 기본값이 필요할 때 인자 없이 호출됩니다. 예를 들어, 리스트의 새 인스턴스를 만들려면, 이렇게 하세요:

mylist: list = field(default_factory=list)

필드가 (init=False 를 사용해서) __init__() 에서 제외되고, 그 필드가 default_factory 를 지정하면, 생성된 __init__() 함수는 항상 기본 팩토리 함수를 호출합니다. 이는 필드에 초기화 값을 제공할 수 있는 다른 방법이 없기 때문입니다.

가변 기본값

파이썬은 기본 멤버 변숫값을 클래스 어트리뷰트에 저장합니다. 데이터 클래스를 사용하지 않는 이 예제를 생각해보세요:

class C:
    x = []
    def add(self, element):
        self.x.append(element)

o1 = C()
o2 = C()
o1.add(1)
o2.add(2)
assert o1.x == [1, 2]
assert o1.x is o2.x

클래스 C 의 두 인스턴스는 예상대로 같은 클래스 변수 x 를 공유합니다.

데이터 클래스를 사용해서, 만약 이 코드가 올바르다면:

@dataclass
class D:
    x: List = []
    def add(self, element):
        self.x += element

비슷한 코드를 생성합니다:

class D:
    x = []
    def __init__(self, x=x):
        self.x = x
    def add(self, element):
        self.x += element

assert D().x is D().x

이것은 클래스 C 를 사용한 원래 예제와 같은 문제를 가지고 있습니다. 즉, 클래스 인스턴스를 만들 때 x 에 대한 값을 지정하지 않는 클래스 D 의 두 인스턴스는 같은 x 를 공유합니다. 데이터 클래스는 일반적인 파이썬 클래스 생성을 사용하기 때문에, 이 동작 역시 공유합니다. 데이터 클래스가 이 조건을 감지하는 일반적인 방법은 없습니다. 대신, 데이터 클래스는 list, dict, set 형의 기본 매개변수를 탐지하면 TypeError 를 발생시킵니다. 이것은 부분적인 해결책이지만, 흔한 오류로부터 보호합니다.

기본 팩토리 함수를 사용하면 필드의 기본값으로 가변형의 새 인스턴스를 만들 수 있습니다:

@dataclass
class D:
    x: list = field(default_factory=list)

assert D().x is not D().x

예외

exception dataclasses.FrozenInstanceError

frozen=True 로 정의된 데이터 클래스에서 묵시적으로 정의된 __setattr__() 또는 __delattr__() 이 호출 될 때 발생합니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

파이썬 실행시간 서비스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

파이썬 실행시간 서비스 »

|

contextlib — Utilities for with-statement contexts

Source code: Lib/contextlib.py [https://github.com/python/cpython/tree/3.7/Lib/contextlib.py]

This module provides utilities for common tasks involving the with statement. For more information see also 컨텍스트 관리자 형 and with 문 컨텍스트 관리자.

Utilities

Functions and classes provided:

class contextlib.AbstractContextManager

An abstract base class for classes that implement object.__enter__() and object.__exit__(). A default implementation for object.__enter__() is provided which returns self while object.__exit__() is an abstract method which by default returns None. See also the definition of 컨텍스트 관리자 형.

버전 3.6에 추가.

class contextlib.AbstractAsyncContextManager

An abstract base class for classes that implement object.__aenter__() and object.__aexit__(). A default implementation for object.__aenter__() is provided which returns self while object.__aexit__() is an abstract method which by default returns None. See also the definition of 비동기 컨텍스트 관리자.

버전 3.7에 추가.

@contextlib.contextmanager

This function is a decorator that can be used to define a factory function for with statement context managers, without needing to create a class or separate __enter__() and __exit__() methods.

While many objects natively support use in with statements, sometimes a resource needs to be managed that isn’t a context manager in its own right, and doesn’t implement a close() method for use with contextlib.closing

An abstract example would be the following to ensure correct resource management:

from contextlib import contextmanager

@contextmanager
def managed_resource(*args, **kwds):
    # Code to acquire resource, e.g.:
    resource = acquire_resource(*args, **kwds)
    try:
        yield resource
    finally:
        # Code to release resource, e.g.:
        release_resource(resource)

>>> with managed_resource(timeout=3600) as resource:
...     # Resource is released at the end of this block,
...     # even if code in the block raises an exception

The function being decorated must return a generator-iterator when called. This iterator must yield exactly one value, which will be bound to the targets in the with statement’s as clause, if any.

At the point where the generator yields, the block nested in the with statement is executed. The generator is then resumed after the block is exited. If an unhandled exception occurs in the block, it is reraised inside the generator at the point where the yield occurred. Thus, you can use a try…except…finally statement to trap the error (if any), or ensure that some cleanup takes place. If an exception is trapped merely in order to log it or to perform some action (rather than to suppress it entirely), the generator must reraise that exception. Otherwise the generator context manager will indicate to the with statement that the exception has been handled, and execution will resume with the statement immediately following the with statement.

contextmanager() uses ContextDecorator so the context managers it creates can be used as decorators as well as in with statements. When used as a decorator, a new generator instance is implicitly created on each function call (this allows the otherwise “one-shot” context managers created by contextmanager() to meet the requirement that context managers support multiple invocations in order to be used as decorators).

버전 3.2에서 변경: Use of ContextDecorator.

@contextlib.asynccontextmanager

Similar to contextmanager(), but creates an asynchronous context manager.

This function is a decorator that can be used to define a factory function for async with statement asynchronous context managers, without needing to create a class or separate __aenter__() and __aexit__() methods. It must be applied to an asynchronous generator function.

A simple example:

from contextlib import asynccontextmanager

@asynccontextmanager
async def get_connection():
    conn = await acquire_db_connection()
    try:
        yield conn
    finally:
        await release_db_connection(conn)

async def get_all_users():
    async with get_connection() as conn:
        return conn.query('SELECT ...')

버전 3.7에 추가.

contextlib.closing(thing)

Return a context manager that closes thing upon completion of the block. This is basically equivalent to:

from contextlib import contextmanager

@contextmanager
def closing(thing):
    try:
        yield thing
    finally:
        thing.close()

And lets you write code like this:

from contextlib import closing
from urllib.request import urlopen

with closing(urlopen('http://www.python.org')) as page:
    for line in page:
        print(line)

without needing to explicitly close page. Even if an error occurs, page.close() will be called when the with block is exited.

contextlib.nullcontext(enter_result=None)

Return a context manager that returns enter_result from __enter__, but otherwise does nothing. It is intended to be used as a stand-in for an optional context manager, for example:

def myfunction(arg, ignore_exceptions=False):
    if ignore_exceptions:
        # Use suppress to ignore all exceptions.
        cm = contextlib.suppress(Exception)
    else:
        # Do not ignore any exceptions, cm has no effect.
        cm = contextlib.nullcontext()
    with cm:
        # Do something

An example using enter_result:

def process_file(file_or_path):
    if isinstance(file_or_path, str):
        # If string, open file
        cm = open(file_or_path)
    else:
        # Caller is responsible for closing file
        cm = nullcontext(file_or_path)

    with cm as file:
        # Perform processing on the file

버전 3.7에 추가.

contextlib.suppress(*exceptions)

Return a context manager that suppresses any of the specified exceptions if they occur in the body of a with statement and then resumes execution with the first statement following the end of the with statement.

As with any other mechanism that completely suppresses exceptions, this context manager should be used only to cover very specific errors where silently continuing with program execution is known to be the right thing to do.

For example:

from contextlib import suppress

with suppress(FileNotFoundError):
    os.remove('somefile.tmp')

with suppress(FileNotFoundError):
    os.remove('someotherfile.tmp')

This code is equivalent to:

try:
    os.remove('somefile.tmp')
except FileNotFoundError:
    pass

try:
    os.remove('someotherfile.tmp')
except FileNotFoundError:
    pass

This context manager is reentrant.

버전 3.4에 추가.

contextlib.redirect_stdout(new_target)

Context manager for temporarily redirecting sys.stdout to another file or file-like object.

This tool adds flexibility to existing functions or classes whose output is hardwired to stdout.

For example, the output of help() normally is sent to sys.stdout. You can capture that output in a string by redirecting the output to an io.StringIO object:

f = io.StringIO()
with redirect_stdout(f):
    help(pow)
s = f.getvalue()

To send the output of help() to a file on disk, redirect the output to a regular file:

with open('help.txt', 'w') as f:
    with redirect_stdout(f):
        help(pow)

To send the output of help() to sys.stderr:

with redirect_stdout(sys.stderr):
    help(pow)

Note that the global side effect on sys.stdout means that this context manager is not suitable for use in library code and most threaded applications. It also has no effect on the output of subprocesses. However, it is still a useful approach for many utility scripts.

This context manager is reentrant.

버전 3.4에 추가.

contextlib.redirect_stderr(new_target)

Similar to redirect_stdout() but redirecting sys.stderr to another file or file-like object.

This context manager is reentrant.

버전 3.5에 추가.

class contextlib.ContextDecorator

A base class that enables a context manager to also be used as a decorator.

Context managers inheriting from ContextDecorator have to implement __enter__ and __exit__ as normal. __exit__ retains its optional exception handling even when used as a decorator.

ContextDecorator is used by contextmanager(), so you get this functionality automatically.

Example of ContextDecorator:

from contextlib import ContextDecorator

class mycontext(ContextDecorator):
    def __enter__(self):
        print('Starting')
        return self

    def __exit__(self, *exc):
        print('Finishing')
        return False

>>> @mycontext()
... def function():
...     print('The bit in the middle')
...
>>> function()
Starting
The bit in the middle
Finishing

>>> with mycontext():
...     print('The bit in the middle')
...
Starting
The bit in the middle
Finishing

This change is just syntactic sugar for any construct of the following form:

def f():
    with cm():
        # Do stuff

ContextDecorator lets you instead write:

@cm()
def f():
    # Do stuff

It makes it clear that the cm applies to the whole function, rather than just a piece of it (and saving an indentation level is nice, too).

Existing context managers that already have a base class can be extended by using ContextDecorator as a mixin class:

from contextlib import ContextDecorator

class mycontext(ContextBaseClass, ContextDecorator):
    def __enter__(self):
        return self

    def __exit__(self, *exc):
        return False

참고

As the decorated function must be able to be called multiple times, the underlying context manager must support use in multiple with statements. If this is not the case, then the original construct with the explicit with statement inside the function should be used.

버전 3.2에 추가.

class contextlib.ExitStack

A context manager that is designed to make it easy to programmatically combine other context managers and cleanup functions, especially those that are optional or otherwise driven by input data.

For example, a set of files may easily be handled in a single with statement as follows:

with ExitStack() as stack:
    files = [stack.enter_context(open(fname)) for fname in filenames]
    # All opened files will automatically be closed at the end of
    # the with statement, even if attempts to open files later
    # in the list raise an exception

Each instance maintains a stack of registered callbacks that are called in reverse order when the instance is closed (either explicitly or implicitly at the end of a with statement). Note that callbacks are not invoked implicitly when the context stack instance is garbage collected.

This stack model is used so that context managers that acquire their resources in their __init__ method (such as file objects) can be handled correctly.

Since registered callbacks are invoked in the reverse order of registration, this ends up behaving as if multiple nested with statements had been used with the registered set of callbacks. This even extends to exception handling - if an inner callback suppresses or replaces an exception, then outer callbacks will be passed arguments based on that updated state.

This is a relatively low level API that takes care of the details of correctly unwinding the stack of exit callbacks. It provides a suitable foundation for higher level context managers that manipulate the exit stack in application specific ways.

버전 3.3에 추가.

enter_context(cm)

Enters a new context manager and adds its __exit__() method to the callback stack. The return value is the result of the context manager’s own __enter__() method.

These context managers may suppress exceptions just as they normally would if used directly as part of a with statement.

push(exit)

Adds a context manager’s __exit__() method to the callback stack.

As __enter__ is not invoked, this method can be used to cover part of an __enter__() implementation with a context manager’s own __exit__() method.

If passed an object that is not a context manager, this method assumes it is a callback with the same signature as a context manager’s __exit__() method and adds it directly to the callback stack.

By returning true values, these callbacks can suppress exceptions the same way context manager __exit__() methods can.

The passed in object is returned from the function, allowing this method to be used as a function decorator.

callback(callback, *args, **kwds)

Accepts an arbitrary callback function and arguments and adds it to the callback stack.

Unlike the other methods, callbacks added this way cannot suppress exceptions (as they are never passed the exception details).

The passed in callback is returned from the function, allowing this method to be used as a function decorator.

pop_all()

Transfers the callback stack to a fresh ExitStack instance and returns it. No callbacks are invoked by this operation - instead, they will now be invoked when the new stack is closed (either explicitly or implicitly at the end of a with statement).

For example, a group of files can be opened as an “all or nothing” operation as follows:

with ExitStack() as stack:
    files = [stack.enter_context(open(fname)) for fname in filenames]
    # Hold onto the close method, but don't call it yet.
    close_files = stack.pop_all().close
    # If opening any file fails, all previously opened files will be
    # closed automatically. If all files are opened successfully,
    # they will remain open even after the with statement ends.
    # close_files() can then be invoked explicitly to close them all.

close()

Immediately unwinds the callback stack, invoking callbacks in the reverse order of registration. For any context managers and exit callbacks registered, the arguments passed in will indicate that no exception occurred.

class contextlib.AsyncExitStack

An asynchronous context manager, similar to ExitStack, that supports combining both synchronous and asynchronous context managers, as well as having coroutines for cleanup logic.

The close() method is not implemented, aclose() must be used instead.

enter_async_context(cm)

Similar to enter_context() but expects an asynchronous context manager.

push_async_exit(exit)

Similar to push() but expects either an asynchronous context manager or a coroutine function.

push_async_callback(callback, *args, **kwds)

Similar to callback() but expects a coroutine function.

aclose()

Similar to close() but properly handles awaitables.

Continuing the example for asynccontextmanager():

async with AsyncExitStack() as stack:
    connections = [await stack.enter_async_context(get_connection())
        for i in range(5)]
    # All opened connections will automatically be released at the end of
    # the async with statement, even if attempts to open a connection
    # later in the list raise an exception.

버전 3.7에 추가.

Examples and Recipes

This section describes some examples and recipes for making effective use of the tools provided by contextlib.

Supporting a variable number of context managers

The primary use case for ExitStack is the one given in the class documentation: supporting a variable number of context managers and other cleanup operations in a single with statement. The variability may come from the number of context managers needed being driven by user input (such as opening a user specified collection of files), or from some of the context managers being optional:

with ExitStack() as stack:
    for resource in resources:
        stack.enter_context(resource)
    if need_special_resource():
        special = acquire_special_resource()
        stack.callback(release_special_resource, special)
    # Perform operations that use the acquired resources

As shown, ExitStack also makes it quite easy to use with statements to manage arbitrary resources that don’t natively support the context management protocol.

Catching exceptions from __enter__ methods

It is occasionally desirable to catch exceptions from an __enter__ method implementation, without inadvertently catching exceptions from the with statement body or the context manager’s __exit__ method. By using ExitStack the steps in the context management protocol can be separated slightly in order to allow this:

stack = ExitStack()
try:
    x = stack.enter_context(cm)
except Exception:
    # handle __enter__ exception
else:
    with stack:
        # Handle normal case

Actually needing to do this is likely to indicate that the underlying API should be providing a direct resource management interface for use with try/except/finally statements, but not all APIs are well designed in that regard. When a context manager is the only resource management API provided, then ExitStack can make it easier to handle various situations that can’t be handled directly in a with statement.

Cleaning up in an __enter__ implementation

As noted in the documentation of ExitStack.push(), this method can be useful in cleaning up an already allocated resource if later steps in the __enter__() implementation fail.

Here’s an example of doing this for a context manager that accepts resource acquisition and release functions, along with an optional validation function, and maps them to the context management protocol:

from contextlib import contextmanager, AbstractContextManager, ExitStack

class ResourceManager(AbstractContextManager):

    def __init__(self, acquire_resource, release_resource, check_resource_ok=None):
        self.acquire_resource = acquire_resource
        self.release_resource = release_resource
        if check_resource_ok is None:
            def check_resource_ok(resource):
                return True
        self.check_resource_ok = check_resource_ok

    @contextmanager
    def _cleanup_on_error(self):
        with ExitStack() as stack:
            stack.push(self)
            yield
            # The validation check passed and didn't raise an exception
            # Accordingly, we want to keep the resource, and pass it
            # back to our caller
            stack.pop_all()

    def __enter__(self):
        resource = self.acquire_resource()
        with self._cleanup_on_error():
            if not self.check_resource_ok(resource):
                msg = "Failed validation for {!r}"
                raise RuntimeError(msg.format(resource))
        return resource

    def __exit__(self, *exc_details):
        # We don't need to duplicate any of our resource release logic
        self.release_resource()

Replacing any use of try-finally and flag variables

A pattern you will sometimes see is a try-finally statement with a flag variable to indicate whether or not the body of the finally clause should be executed. In its simplest form (that can’t already be handled just by using an except clause instead), it looks something like this:

cleanup_needed = True
try:
    result = perform_operation()
    if result:
        cleanup_needed = False
finally:
    if cleanup_needed:
        cleanup_resources()

As with any try statement based code, this can cause problems for development and review, because the setup code and the cleanup code can end up being separated by arbitrarily long sections of code.

ExitStack makes it possible to instead register a callback for execution at the end of a with statement, and then later decide to skip executing that callback:

from contextlib import ExitStack

with ExitStack() as stack:
    stack.callback(cleanup_resources)
    result = perform_operation()
    if result:
        stack.pop_all()

This allows the intended cleanup up behaviour to be made explicit up front, rather than requiring a separate flag variable.

If a particular application uses this pattern a lot, it can be simplified even further by means of a small helper class:

from contextlib import ExitStack

class Callback(ExitStack):
    def __init__(self, callback, *args, **kwds):
        super(Callback, self).__init__()
        self.callback(callback, *args, **kwds)

    def cancel(self):
        self.pop_all()

with Callback(cleanup_resources) as cb:
    result = perform_operation()
    if result:
        cb.cancel()

If the resource cleanup isn’t already neatly bundled into a standalone function, then it is still possible to use the decorator form of ExitStack.callback() to declare the resource cleanup in advance:

from contextlib import ExitStack

with ExitStack() as stack:
    @stack.callback
    def cleanup_resources():
        ...
    result = perform_operation()
    if result:
        stack.pop_all()

Due to the way the decorator protocol works, a callback function declared this way cannot take any parameters. Instead, any resources to be released must be accessed as closure variables.

Using a context manager as a function decorator

ContextDecorator makes it possible to use a context manager in both an ordinary with statement and also as a function decorator.

For example, it is sometimes useful to wrap functions or groups of statements with a logger that can track the time of entry and time of exit. Rather than writing both a function decorator and a context manager for the task, inheriting from ContextDecorator provides both capabilities in a single definition:

from contextlib import ContextDecorator
import logging

logging.basicConfig(level=logging.INFO)

class track_entry_and_exit(ContextDecorator):
    def __init__(self, name):
        self.name = name

    def __enter__(self):
        logging.info('Entering: %s', self.name)

    def __exit__(self, exc_type, exc, exc_tb):
        logging.info('Exiting: %s', self.name)

Instances of this class can be used as both a context manager:

with track_entry_and_exit('widget loader'):
    print('Some time consuming activity goes here')
    load_widget()

And also as a function decorator:

@track_entry_and_exit('widget loader')
def activity():
    print('Some time consuming activity goes here')
    load_widget()

Note that there is one additional limitation when using context managers as function decorators: there’s no way to access the return value of __enter__(). If that value is needed, then it is still necessary to use an explicit with statement.

더 보기

PEP 343 [https://www.python.org/dev/peps/pep-0343] - The “with” statement

The specification, background, and examples for the Python with statement.

Single use, reusable and reentrant context managers

Most context managers are written in a way that means they can only be used effectively in a with statement once. These single use context managers must be created afresh each time they’re used - attempting to use them a second time will trigger an exception or otherwise not work correctly.

This common limitation means that it is generally advisable to create context managers directly in the header of the with statement where they are used (as shown in all of the usage examples above).

Files are an example of effectively single use context managers, since the first with statement will close the file, preventing any further IO operations using that file object.

Context managers created using contextmanager() are also single use context managers, and will complain about the underlying generator failing to yield if an attempt is made to use them a second time:

>>> from contextlib import contextmanager
>>> @contextmanager
... def singleuse():
...     print("Before")
...     yield
...     print("After")
...
>>> cm = singleuse()
>>> with cm:
...     pass
...
Before
After
>>> with cm:
...     pass
...
Traceback (most recent call last):
    ...
RuntimeError: generator didn't yield

Reentrant context managers

More sophisticated context managers may be “reentrant”. These context managers can not only be used in multiple with statements, but may also be used inside a with statement that is already using the same context manager.

threading.RLock is an example of a reentrant context manager, as are suppress() and redirect_stdout(). Here’s a very simple example of reentrant use:

>>> from contextlib import redirect_stdout
>>> from io import StringIO
>>> stream = StringIO()
>>> write_to_stream = redirect_stdout(stream)
>>> with write_to_stream:
...     print("This is written to the stream rather than stdout")
...     with write_to_stream:
...         print("This is also written to the stream")
...
>>> print("This is written directly to stdout")
This is written directly to stdout
>>> print(stream.getvalue())
This is written to the stream rather than stdout
This is also written to the stream

Real world examples of reentrancy are more likely to involve multiple functions calling each other and hence be far more complicated than this example.

Note also that being reentrant is not the same thing as being thread safe. redirect_stdout(), for example, is definitely not thread safe, as it makes a global modification to the system state by binding sys.stdout to a different stream.

Reusable context managers

Distinct from both single use and reentrant context managers are “reusable” context managers (or, to be completely explicit, “reusable, but not reentrant” context managers, since reentrant context managers are also reusable). These context managers support being used multiple times, but will fail (or otherwise not work correctly) if the specific context manager instance has already been used in a containing with statement.

threading.Lock is an example of a reusable, but not reentrant, context manager (for a reentrant lock, it is necessary to use threading.RLock instead).

Another example of a reusable, but not reentrant, context manager is ExitStack, as it invokes all currently registered callbacks when leaving any with statement, regardless of where those callbacks were added:

>>> from contextlib import ExitStack
>>> stack = ExitStack()
>>> with stack:
...     stack.callback(print, "Callback: from first context")
...     print("Leaving first context")
...
Leaving first context
Callback: from first context
>>> with stack:
...     stack.callback(print, "Callback: from second context")
...     print("Leaving second context")
...
Leaving second context
Callback: from second context
>>> with stack:
...     stack.callback(print, "Callback: from outer context")
...     with stack:
...         stack.callback(print, "Callback: from inner context")
...         print("Leaving inner context")
...     print("Leaving outer context")
...
Leaving inner context
Callback: from inner context
Callback: from outer context
Leaving outer context

As the output from the example shows, reusing a single stack object across multiple with statements works correctly, but attempting to nest them will cause the stack to be cleared at the end of the innermost with statement, which is unlikely to be desirable behaviour.

Using separate ExitStack instances instead of reusing a single instance avoids that problem:

>>> from contextlib import ExitStack
>>> with ExitStack() as outer_stack:
...     outer_stack.callback(print, "Callback: from outer context")
...     with ExitStack() as inner_stack:
...         inner_stack.callback(print, "Callback: from inner context")
...         print("Leaving inner context")
...     print("Leaving outer context")
...
Leaving inner context
Callback: from inner context
Leaving outer context
Callback: from outer context

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

파이썬 실행시간 서비스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

파이썬 실행시간 서비스 »

|

abc — 추상 베이스 클래스

소스 코드: Lib/abc.py [https://github.com/python/cpython/tree/3.7/Lib/abc.py]

이 모듈은, PEP 3119 [https://www.python.org/dev/peps/pep-3119]에서 설명된 대로, 파이썬에서 추상 베이스 클래스 (ABC) 를 정의하기 위한 기반 구조를 제공합니다; 이것이 왜 파이썬에 추가되었는지는 PEP를 참조하십시오. (ABC를 기반으로 하는 숫자의 형 계층 구조에 관해서는 PEP 3141 [https://www.python.org/dev/peps/pep-3141]과 numbers 모듈을 참고하십시오.)

collections 모듈은 ABC로부터 파생된 몇 가지 구상(concrete) 클래스를 가지고 있습니다; 이것은 물론 더 파생될 수 있습니다. 또한, collections.abc 서브 모듈에는 클래스나 인스턴스가 특정 인터페이스를 (예를 들어, 해시 가능이거나 매핑이면) 제공하는지 검사하는 데 사용할 수 있는 ABC가 있습니다.

이 모듈은 ABC를 정의하기 위한 메타 클래스 ABCMeta와 상속을 통해 ABC를 정의하는 대안적 방법을 제공하는 도우미 클래스 ABC를 제공합니다:

class abc.ABC

ABCMeta를 메타 클래스로 가지는 도우미 클래스. 이 클래스를 사용하면, 때로 혼란스러운 메타 클래스를 사용하지 않고, 추상 베이스 클래스를 간단히 ABC에서 파생시켜서 만들 수 있습니다. 예를 들어:

from abc import ABC

class MyABC(ABC):
    pass

ABC 의 형은 여전히 ABCMeta 이므로, ABC를 상속할 때는 메타 클래스 사용에 관한 일반적인 주의가 필요한데, 다중 상속이 메타 클래스 충돌을 일으킬 수 있기 때문입니다. metaclass 키워드를 전달하고 ABCMeta를 직접 사용해서 추상 베이스 클래스를 정의할 수도 있습니다, 예를 들어:

from abc import ABCMeta

class MyABC(metaclass=ABCMeta):
    pass

버전 3.4에 추가.

class abc.ABCMeta

추상 베이스 클래스 (ABC)를 정의하기 위한 메타 클래스.

이 메타 클래스를 사용하여 ABC를 만듭니다. ABC는 직접 서브 클래싱 될 수 있으며 믹스 인 클래스의 역할을 합니다. 관련 없는 구상 클래스(심지어 내장 클래스도)와 관련 없는 ABC를 “가상 서브 클래스”로 등록 할 수 있습니다 – 이들과 이들의 서브 클래스는 내장 issubclass() 함수에 의해 등록하는 ABC의 서브 클래스로 간주합니다. 하지만 등록하는 ABC는 그들의 MRO (메서드 결정 순서)에 나타나지 않을 것이고, 등록하는 ABC가 정의한 메서드 구현도 호출할 수 없을 것입니다 (super()를 통해서도 가능하지 않습니다). 1

ABCMeta를 메타 클래스로 생성된 클래스는 다음과 같은 메서드를 가집니다:

register(subclass)

이 ABC의 “가상 서브 클래스”로 subclass 를 등록합니다. 예를 들면:

from abc import ABC

class MyABC(ABC):
    pass

MyABC.register(tuple)

assert issubclass(tuple, MyABC)
assert isinstance((), MyABC)

버전 3.3에서 변경: 클래스 데코레이터로 사용할 수 있도록, 등록된 subclass 돌려줍니다.

버전 3.4에서 변경: register() 호출을 감지하려면, get_cache_token() 함수를 사용할 수 있습니다.

추상 베이스 클래스에서 다음 메서드를 재정의할 수도 있습니다:

__subclasshook__(subclass)

(반드시 클래스 메서드로 정의되어야 합니다.)

subclass 를 이 ABC의 서브 클래스로 간주할지를 검사합니다. 이것은, ABC의 서브 클래스로 취급하고 싶은 클래스마다 register()를 호출할 필요 없이, issubclass 의 행동을 더 사용자 정의할 수 있음을 의미합니다. (이 클래스 메서드는 ABC의 __subclasscheck__() 메서드에서 호출됩니다.)

이 메서드는 True, False 또는 NotImplemented 를 반환해야 합니다. True 를 반환하면, subclass 를 이 ABC의 서브 클래스로 간주합니다. False 를 반환하면, subclass 를 ABC의 서브 클래스로 간주하지 않습니다. NotImplemented 를 반환하면, 서브 클래스 검사가 일반적인 메커니즘으로 계속됩니다.

이러한 개념들의 시연으로, 이 예제 ABC 정의를 보십시오:

class Foo:
    def __getitem__(self, index):
        ...
    def __len__(self):
        ...
    def get_iterator(self):
        return iter(self)

class MyIterable(ABC):

    @abstractmethod
    def __iter__(self):
        while False:
            yield None

    def get_iterator(self):
        return self.__iter__()

    @classmethod
    def __subclasshook__(cls, C):
        if cls is MyIterable:
            if any("__iter__" in B.__dict__ for B in C.__mro__):
                return True
        return NotImplemented

MyIterable.register(Foo)

ABC MyIterable 은 추상 메서드로 __iter__() 라는 표준 이터러블 메서드를 정의합니다. 여기에 제공된 구현은 여전히 서브 클래스에서 호출 할 수 있습니다. get_iterator() 메서드 또한 MyIterable 추상 베이스 클래스의 일부이지만, 추상이 아닌 파생 클래스에서 재정의될 필요는 없습니다.

여기에 정의된 __subclasshook__() 클래스 메서드는 자신의 (또는 그것의 __mro__ 리스트를 통해 액세스 되는 베이스 클래스 중 하나의) __dict__ 에 __iter__() 메서드를 가진 모든 클래스도 MyIterable 로 간주한다고 말합니다.

마지막으로, 마지막 줄은, Foo 가 __iter__() 메서드를 정의하지는 않았음에도 불구하고 (이것은 __len__() 과 __getitem__() 로 정의되는 이전 스타일의 이터러블 프로토콜을 사용합니다), MyIterable 의 가상 서브 클래스로 만듭니다. 이렇게 하면 get_iterator 가 Foo 의 메서드로 사용할 수 있지 않으므로, 별도로 제공됩니다.

abc 모듈은 다음 데코레이터도 제공합니다:

@abc.abstractmethod

추상 메서드를 나타내는 데코레이터.

이 데코레이터를 사용하려면 클래스의 메타 클래스가 ABCMeta 이거나 여기에서 파생된 것이어야 합니다. ABCMeta 에서 파생된 메타 클래스를 가진 클래스는 모든 추상 메서드와 프로퍼티가 재정의되지 않는 한 인스턴스로 만들 수 없습니다. 추상 메서드는 일반적인 ‘super’ 호출 메커니즘을 사용하여 호출 할 수 있습니다. abstractmethod() 는 프로퍼티와 디스크립터에 대한 추상 메서드를 선언하는 데 사용될 수 있습니다.

클래스에 추상 메서드를 동적으로 추가하거나, 메서드나 클래스가 작성된 후에 추상화 상태를 수정하려고 시도하는 것은 지원되지 않습니다. abstractmethod() 는 정규 상속을 사용하여 파생된 서브 클래스에만 영향을 줍니다; ABC의 register() 메서드로 등록된 “가상 서브 클래스” 는 영향을 받지 않습니다.

abstractmethod() 가 다른 메서드 디스크립터와 함께 적용될 때, 다음 사용 예제와 같이 가장 안쪽의 데코레이터로 적용되어야 합니다:

class C(ABC):
    @abstractmethod
    def my_abstract_method(self, ...):
        ...
    @classmethod
    @abstractmethod
    def my_abstract_classmethod(cls, ...):
        ...
    @staticmethod
    @abstractmethod
    def my_abstract_staticmethod(...):
        ...

    @property
    @abstractmethod
    def my_abstract_property(self):
        ...
    @my_abstract_property.setter
    @abstractmethod
    def my_abstract_property(self, val):
        ...

    @abstractmethod
    def _get_x(self):
        ...
    @abstractmethod
    def _set_x(self, val):
        ...
    x = property(_get_x, _set_x)

추상 베이스 클래스 장치와 정확하게 상호 작용하기 위해서, 디스크립터는 __isabstractmethod__ 를 사용하여 자신을 추상으로 식별해야 합니다. 일반적으로 이 어트리뷰트는 디스크립터를 구성하는 데 사용된 메서드 중 어느 하나라도 추상이면 True 여야 합니다. 예를 들어, 파이썬의 내장 property는 다음과 동등한 일을 합니다:

class Descriptor:
    ...
    @property
    def __isabstractmethod__(self):
        return any(getattr(f, '__isabstractmethod__', False) for
                   f in (self._fget, self._fset, self._fdel))

참고

자바 추상 메서드와 달리, 이 추상 메서드는 구현을 가질 수 있습니다. 이 구현은 그것을 재정의하는 클래스에서 super() 메커니즘을 통해 호출 할 수 있습니다. 이는 협업적 다중 상속을 사용하는 프레임워크에서 super-호출의 종점으로 유용 할 수 있습니다.

abc 모듈은 다음 레거시 데코레이터도 지원합니다:

@abc.abstractclassmethod

버전 3.2에 추가.

버전 3.3부터 폐지: 이제 classmethod 와 abstractmethod() 를 함께 사용할 수 있어서, 이 데코레이터는 필요 없습니다.

내장 classmethod() 의 서브 클래스로, 추상 classmethod를 나타냅니다. 그 외에는 abstractmethod() 와 유사합니다.

classmethod() 데코레이터가 이제 추상 메서드에 적용될 때 추상으로 정확하게 식별되기 때문에, 이 특별한 경우는 폐지되었습니다.:

class C(ABC):
    @classmethod
    @abstractmethod
    def my_abstract_classmethod(cls, ...):
        ...

@abc.abstractstaticmethod

버전 3.2에 추가.

버전 3.3부터 폐지: 이제 staticmethod 와 abstractmethod() 를 함께 사용할 수 있어서, 이 데코레이터는 필요 없습니다.

내장 staticmethod() 의 서브 클래스로, 추상 staticmethod를 나타냅니다. 그 외에는 abstractmethod() 와 유사합니다.

staticmethod() 데코레이터가 이제 추상 메서드에 적용될 때 추상으로 정확하게 식별되기 때문에, 이 특별한 경우는 폐지되었습니다.:

class C(ABC):
    @staticmethod
    @abstractmethod
    def my_abstract_staticmethod(...):
        ...

@abc.abstractproperty

버전 3.3부터 폐지: 이제 property, property.getter(), property.setter(), property.deleter() 와 abstractmethod() 를 함께 사용할 수 있어서, 이 데코레이터는 필요 없습니다.

내장 property() 의 서브 클래스로, 추상 property를 나타냅니다.

property() 데코레이터가 이제 추상 메서드에 적용될 때 추상으로 정확하게 식별되기 때문에, 이 특별한 경우는 폐지되었습니다.:

class C(ABC):
    @property
    @abstractmethod
    def my_abstract_property(self):
        ...

위의 예제는 읽기 전용 프로퍼티를 정의합니다; 하나나 그 이상의 하부 메서드를 추상으로 적절하게 표시하여 읽기-쓰기 추상 프로퍼티를 정의할 수도 있습니다:

class C(ABC):
    @property
    def x(self):
        ...

    @x.setter
    @abstractmethod
    def x(self, val):
        ...

일부 구성 요소만 추상인 경우, 서브 클래스에서 구상 프로퍼티를 만들기 위해서는 해당 구성 요소만 갱신하면 됩니다:

class D(C):
    @C.x.setter
    def x(self, val):
        ...

abc 모듈은 또한 다음과 같은 기능을 제공합니다 :

abc.get_cache_token()

현재의 추상 베이스 클래스 캐시 토큰을 반환합니다.

토큰은 가상 서브 클래스를 위한 추상 베이스 클래스 캐시의 현재 버전을 식별하는 (동등성 검사를 지원하는) 불투명 객체입니다. 임의의 ABC에서 ABCMeta.register() 가 호출될 때마다 토큰이 변경됩니다.

버전 3.4에 추가.

각주

1

C++ 프로그래머는 파이썬의 가상 베이스 클래스 개념이 C++과 다르다는 것을 알아야 합니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

파이썬 실행시간 서비스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

파이썬 실행시간 서비스 »

|

atexit — 종료 처리기

atexit 모듈은 정리 함수를 등록하고 해제하는 함수를 정의합니다. 이렇게 등록된 함수는 정상적인 인터프리터 종료 시 자동으로 실행됩니다. atexit는 이 함수들을 등록된 역순 으로 실행합니다; A, B, C 를 등록하면, 인터프리터 종료 시각에 C, B, A 순서로 실행됩니다.

참고: 이 모듈을 통해 등록된 함수는 다음과 같은 경우 호출되지 않습니다. 프로그램이 파이썬이 처리하지 않는 시그널에 의해 종료될 때. 파이썬의 치명적인 내부 에러가 감지되었을 때. os._exit() 가 호출될 때.

버전 3.7에서 변경: C-API 서브 인터프리터와 함께 사용될 때, 등록된 함수는 등록된 인터프리터에 국지적입니다.

atexit.register(func, *args, **kwargs)

func 를 종료 시에 실행할 함수로 등록합니다. func 에 전달되어야 하는 선택적 인자는 register() 에 인자로 전달되어야 합니다. 같은 함수와 인자를 두 번 이상 등록 할 수 있습니다.

정상적인 프로그램 종료 시에 (예를 들어, sys.exit() 가 호출되거나 주 모듈의 실행이 완료된 경우에), 등록된 모든 함수는 후입선출 순서로 호출됩니다. 낮은 수준의 모듈은 일반적으로 상위 수준 모듈보다 먼저 임포트 되기 때문에 나중에 정리해야 한다는 가정입니다.

종료 처리기의 실행 중에 예외가 발생하면 (SystemExit가 발생하지 않는다면) 트레이스백이 인쇄되고 예외 정보가 저장됩니다. 모든 종료 처리기가 실행될 기회를 얻은 후에 발생한 마지막 예외를 다시 일으킵니다.

이 함수는 func 을 반환하므로 데코레이터로 사용할 수 있습니다.

atexit.unregister(func)

인터프리터 종료 시 실행할 함수 목록에서 func 를 제거합니다. unregister()를 호출한 후에는, 인터프리터가 종료할 때 func 이 호출되지 않음이 보장됩니다. 두 번 이상 등록했더라도 그렇습니다. unregister() 는 func 가 이전에 등록되지 않았다면 아무것도 하지 않습니다.

더 보기

모듈 readline

readline 히스토리 파일을 읽고 쓰는 atexit 의 유용한 예.

atexit 예제

다음의 간단한 예제는, 모듈이 임포트 될 때 파일에서 카운터를 읽고 프로그램이 종료할 때 프로그램의 명시적인 호출에 의존하지 않고 카운터의 변경된 값을 자동으로 저장하는 방법을 보여줍니다.:

try:
    with open("counterfile") as infile:
        _count = int(infile.read())
except FileNotFoundError:
    _count = 0

def incrcounter(n):
    global _count
    _count = _count + n

def savecounter():
    with open("counterfile", "w") as outfile:
        outfile.write("%d" % _count)

import atexit
atexit.register(savecounter)

위치 및 키워드 인자가 등록된 함수가 호출될 때 전달되도록 register() 에 전달할 수 있습니다:

def goodbye(name, adjective):
    print('Goodbye, %s, it was %s to meet you.' % (name, adjective))

import atexit
atexit.register(goodbye, 'Donny', 'nice')

# or:
atexit.register(goodbye, adjective='nice', name='Donny')

데코레이터 로 사용하기:

import atexit

@atexit.register
def goodbye():
    print("You are now leaving the Python sector.")

이 방법은 인자 없이 호출할 수 있는 함수에서만 작동합니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

파이썬 실행시간 서비스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

파이썬 실행시간 서비스 »

|

traceback — 스택 트레이스백 인쇄와 조회

소스 코드: Lib/traceback.py [https://github.com/python/cpython/tree/3.7/Lib/traceback.py]

이 모듈은 파이썬 프로그램의 스택 트레이스를 추출, 포맷 및 인쇄하는 표준 인터페이스를 제공합니다. 스택 트레이스를 인쇄할 때 파이썬 인터프리터의 동작을 정확하게 모방합니다. 이것은 가령 인터프리터를 둘러싸는 “래퍼”처럼 프로그램 제어 하에서 스택 트레이스를 인쇄하려고 할 때 유용합니다.

이 모듈은 트레이스백 객체를 사용합니다 — 이는 sys.last_traceback 변수에 저장되고 sys.exc_info()의 세 번째 항목으로 반환되는 객체 형입니다.

이 모듈은 다음 함수를 정의합니다:

traceback.print_tb(tb, limit=None, file=None)

limit가 양수면 (호출자 프레임에서 시작하여) 트레이스백 객체 tb의 최대 limit 개의 스택 트레이스 항목을 인쇄합니다. 그렇지 않으면, 마지막 abs(limit) 항목을 인쇄합니다. limit가 생략되거나 None이면, 모든 항목이 인쇄됩니다. file이 생략되거나 None이면, 출력은 sys.stderr로 갑니다; 그렇지 않으면 출력을 받을 열린 파일이나 파일류 객체여야 합니다.

버전 3.5에서 변경: 음수 limit 지원을 추가했습니다.

traceback.print_exception(etype, value, tb, limit=None, file=None, chain=True)

예외 정보와 트레이스백 객체 tb의 스택 트레이스 항목을 file로 인쇄합니다. 이것은 다음과 같은 점에서 print_tb()와 다릅니다:

tb가 None이 아니면, 헤더 Traceback (most recent call last):를 인쇄합니다.

스택 트레이스 다음에 예외 etype과 value를 인쇄합니다.

type(value)가 SyntaxError고 value가 적절한 형식을 가지면, 에러의 대략적인 위치를 나타내는 캐럿(caret)과 함께 문법 에러가 발생한 줄을 인쇄합니다.

선택적 limit 인자는 print_tb()와 같은 의미입니다. chain이 참(기본값)이면, 처리되지 않은 예외를 인쇄할 때 인터프리터 자체가 하는 것과 마찬가지로, 연결된 예외(예외의 __cause__나 __context__ 어트리뷰트)도 인쇄됩니다.

버전 3.5에서 변경: etype 인자는 무시되고 value 형에서 유추됩니다.

traceback.print_exc(limit=None, file=None, chain=True)

이것은 print_exception(*sys.exc_info(), limit, file, chain)의 줄임 표현입니다.

traceback.print_last(limit=None, file=None, chain=True)

이것은 print_exception(sys.last_type, sys.last_value, sys.last_traceback, limit, file, chain)의 줄임 표현입니다. 일반적으로 예외가 대화식 프롬프트에 도달한 후에만 작동합니다 (sys.last_type을 참조하십시오).

traceback.print_stack(f=None, limit=None, file=None)

limit가 양수면 (호출 지점에서 시작하여) 최대 limit 개의 스택 트레이스 항목을 인쇄합니다. 그렇지 않으면, 마지막 abs(limit) 항목을 인쇄합니다. limit가 생략되거나 None이면, 모든 항목이 인쇄됩니다. 선택적 f 인자를 사용하여 시작할 대체 스택 프레임을 지정할 수 있습니다. 선택적 file 인자는 print_tb()와 같은 의미입니다.

버전 3.5에서 변경: 음수 limit 지원을 추가했습니다.

traceback.extract_tb(tb, limit=None)

트레이스백 객체 tb에서 추출된 “전 처리된” 스택 트레이스 항목의 리스트를 나타내는 StackSummary 객체를 반환합니다. 스택 트레이스의 대체 포매팅으로 유용합니다. 선택적 limit 인자는 print_tb()와 같은 의미입니다. “전 처리된” 스택 트레이스 항목은 일반적으로 스택 트레이스를 위해 인쇄되는 정보를 나타내는 어트리뷰트 filename, lineno, name 및 line을 포함하는 FrameSummary 객체입니다. line은 선행과 후행 공백이 제거된 문자열입니다; 소스를 사용할 수 없으면 None입니다.

traceback.extract_stack(f=None, limit=None)

현재 스택 프레임에서 날 트레이스백을 추출합니다. 반환 값은 extract_tb()와 같은 형식입니다. 선택적 f와 limit 인자는 print_stack()과 같은 의미입니다.

traceback.format_list(extracted_list)

extract_tb()나 extract_stack()이 반환한 튜플이나 FrameSummary 객체의 리스트가 제공되면, 인쇄할 준비가 된 문자열의 리스트를 반환합니다. 결과 리스트의 각 문자열은 인자 리스트에서 같은 인덱스를 가진 항목에 해당합니다. 각 문자열은 줄 바꿈으로 끝납니다; 소스 텍스트 줄이 None이 아닌 항목의 경우, 문자열에 내부 줄 바꿈도 포함될 수 있습니다.

traceback.format_exception_only(etype, value)

트레이스백의 예외 부분을 포맷합니다. 인자는 sys.last_type과 sys.last_value에서 제공하는 것과 같은 예외 형과 값입니다. 반환 값은 각각 줄 바꿈으로 끝나는 문자열의 리스트입니다. 일반적으로, 리스트는 단일 문자열을 포함합니다; 그러나, SyntaxError 예외의 경우, 문법 에러가 발생한 위치에 대한 자세한 정보를 (인쇄될 때) 표시하는 여러 줄을 포함합니다. 어떤 예외가 발생했는지를 나타내는 메시지는 리스트에서 항상 마지막 문자열입니다.

traceback.format_exception(etype, value, tb, limit=None, chain=True)

스택 트레이스와 예외 정보를 포맷합니다. 인자는 print_exception()의 해당하는 인자와 같은 의미입니다. 반환 값은 각각 줄 바꿈으로 끝나고 일부는 내부 줄 바꿈을 포함하는 문자열의 리스트입니다. 이 줄들을 이어붙여서 인쇄하면, print_exception()과 정확히 같은 텍스트가 인쇄됩니다.

버전 3.5에서 변경: etype 인자는 무시되고 value 형에서 유추됩니다.

traceback.format_exc(limit=None, chain=True)

이것은 print_exc(limit)와 비슷하지만, 파일로 인쇄하는 대신 문자열을 반환합니다.

traceback.format_tb(tb, limit=None)

format_list(extract_tb(tb, limit))의 줄임 표현입니다.

traceback.format_stack(f=None, limit=None)

format_list(extract_stack(f, limit))의 줄임 표현입니다.

traceback.clear_frames(tb)

각 프레임 객체의 clear() 메서드를 호출하여 트레이스백 tb에 있는 모든 스택 프레임의 지역 변수를 지웁니다.

버전 3.4에 추가.

traceback.walk_stack(f)

주어진 프레임에서 f.f_back을 따라 스택을 걸어가며 각 프레임의 프레임과 줄 번호를 산출(yield)합니다. f가 None이면, 현재 스택이 사용됩니다. 이 도우미는 StackSummary.extract()와 함께 사용됩니다.

버전 3.5에 추가.

traceback.walk_tb(tb)

tb_next를 따라 트레이스백을 걸으면서 각 프레임의 프레임과 줄 번호를 산출(yield)합니다. 이 도우미는 StackSummary.extract()와 함께 사용됩니다.

버전 3.5에 추가.

이 모듈은 또한 다음과 같은 클래스를 정의합니다:

TracebackException 객체

버전 3.5에 추가.

TracebackException 객체는 실제 예외에서 만들어져 나중에 인쇄하기 위한 데이터를 경량 방식으로 포착합니다.

class traceback.TracebackException(exc_type, exc_value, exc_traceback, *, limit=None, lookup_lines=True, capture_locals=False)

나중에 렌더링하기 위해 예외를 포착합니다. limit, lookup_lines 및 capture_locals는 StackSummary 클래스와 같습니다.

locals가 포착되면, 트레이스백에도 표시됨에 유의하십시오.

__cause__

원래 __cause__의 TracebackException.

__context__

원래 __context__의 TracebackException.

__suppress_context__

원래 예외의 __suppress_context__ 값.

stack

트레이스백을 나타내는 StackSummary.

exc_type

원래 트레이스백의 클래스.

filename

문법 에러일 때 - 에러가 발생한 파일 이름.

lineno

문법 에러일 때 - 에러가 발생한 줄 번호.

text

문법 에러일 때 - 에러가 발생한 텍스트.

offset

문법 에러일 때 - 에러가 발생한 텍스트에서의 오프셋.

msg

문법 에러일 때 - 컴파일러 에러 메시지.

classmethod from_exception(exc, *, limit=None, lookup_lines=True, capture_locals=False)

나중에 렌더링하기 위해 예외를 포착합니다. limit, lookup_lines 및 capture_locals는 StackSummary 클래스와 같습니다.

locals가 포착되면, 트레이스백에도 표시됨에 유의하십시오.

format(*, chain=True)

예외를 포맷합니다.

chain이 True가 아니면, __cause__와 __context__는 포맷되지 않습니다.

반환 값은 각각 줄 바꿈으로 끝나고 일부는 내부 줄 바꿈을 포함하는 문자열의 제너레이터입니다. print_exception()은 단지 파일에 줄을 인쇄하는 이 메서드를 둘러싸는 래퍼입니다.

어떤 예외가 발생했는지를 나타내는 메시지는 항상 출력의 마지막 문자열입니다.

format_exception_only()

트레이스백의 예외 부분을 포맷합니다.

반환 값은 각각 줄 바꿈으로 끝나는 문자열의 제너레이터입니다.

일반적으로, 제너레이터는 단일 문자열을 방출합니다; 그러나 SyntaxError 예외의 경우, 문법 에러가 발생한 위치에 대한 자세한 정보를 (인쇄할 때) 표시하는 여러 줄을 방출합니다.

어떤 예외가 발생했는지를 나타내는 메시지는 항상 출력의 마지막 문자열입니다.

StackSummary 객체

버전 3.5에 추가.

StackSummary 객체는 포맷 준비가 된 호출 스택을 나타냅니다.

class traceback.StackSummary

classmethod extract(frame_gen, *, limit=None, lookup_lines=True, capture_locals=False)

(walk_stack()이나 walk_tb()에서 반환된 것과 같은) 프레임 제너레이터로 StackSummary 객체를 생성합니다.

limit가 제공되면, frame_gen에서 이 수 만큼의 프레임만 취합니다. lookup_lines가 False이면, 반환된 FrameSummary 객체는 아직 해당 줄을 읽지 않아서 StackSummary를 만드는 비용을 줄입니다 (실제로 포맷되지 않을 수 있다면 유용 할 수 있습니다). capture_locals가 True이면, 각 FrameSummary의 지역 변수는 객체 표현(representation)으로 포착됩니다.

classmethod from_list(a_list)

제공된 FrameSummary 객체의 리스트나 이전 스타일의 튜플 리스트로 StackSummary 객체를 생성합니다. 각 튜플은 파일명(filename), 줄 번호(lineno), 이름(name), 줄(line)을 요소로 하는 4-튜플이어야 합니다.

format()

인쇄 준비가 된 문자열의 리스트를 반환합니다. 결과 리스트의 각 문자열은 스택의 단일 프레임에 해당합니다. 각 문자열은 줄 바꿈으로 끝납니다; 소스 텍스트 줄이 있는 항목의 경우, 문자열에 내부 줄 바꿈도 포함될 수 있습니다.

같은 프레임과 줄의 긴 시퀀스의 경우, 처음 몇 번의 반복이 표시된 다음, 정확한 추가의 반복 횟수를 나타내는 요약 줄이 표시됩니다.

버전 3.6에서 변경: 반복되는 프레임의 긴 시퀀스가 이제 축약됩니다.

FrameSummary 객체

버전 3.5에 추가.

FrameSummary 객체는 트레이스백에서 단일 프레임을 나타냅니다.

class traceback.FrameSummary(filename, lineno, name, lookup_line=True, locals=None, line=None)

포맷되거나 인쇄 중인 트레이스백이나 스택의 단일 프레임을 나타냅니다. 선택적으로 문자열로 변환된 버전의 프레임 지역 변수를 포함할 수 있습니다. lookup_line이 False이면, FrameSummary의 line 어트리뷰트에 액세스할 때까지 (튜플로 캐스트 할 때도 발생합니다) 소스 코드를 찾지 않습니다. line은 직접 제공될 수 있으며, 줄 조회가 전혀 발생하지 않도록 합니다. locals는 선택적 지역 변수 딕셔너리이며, 제공되면 변수 표현(representation)은 나중에 표시할 수 있도록 요약에 저장됩니다.

트레이스백 예제

이 간단한 예제는 표준 파이썬 대화식 인터프리터 루프와 비슷하지만 (하지만 덜 유용한) 기본적인 읽기-평가-인쇄 루프를 구현합니다. 인터프리터 루프의 더욱 완전한 구현은 code 모듈을 참조하십시오.

import sys, traceback

def run_user_code(envdir):
    source = input(">>> ")
    try:
        exec(source, envdir)
    except Exception:
        print("Exception in user code:")
        print("-"*60)
        traceback.print_exc(file=sys.stdout)
        print("-"*60)

envdir = {}
while True:
    run_user_code(envdir)

다음 예제는 예외와 추적을 인쇄하고 포맷하는 다양한 방법을 보여줍니다:

import sys, traceback

def lumberjack():
    bright_side_of_death()

def bright_side_of_death():
    return tuple()[0]

try:
    lumberjack()
except IndexError:
    exc_type, exc_value, exc_traceback = sys.exc_info()
    print("*** print_tb:")
    traceback.print_tb(exc_traceback, limit=1, file=sys.stdout)
    print("*** print_exception:")
    # exc_type below is ignored on 3.5 and later
    traceback.print_exception(exc_type, exc_value, exc_traceback,
                              limit=2, file=sys.stdout)
    print("*** print_exc:")
    traceback.print_exc(limit=2, file=sys.stdout)
    print("*** format_exc, first and last line:")
    formatted_lines = traceback.format_exc().splitlines()
    print(formatted_lines[0])
    print(formatted_lines[-1])
    print("*** format_exception:")
    # exc_type below is ignored on 3.5 and later
    print(repr(traceback.format_exception(exc_type, exc_value,
                                          exc_traceback)))
    print("*** extract_tb:")
    print(repr(traceback.extract_tb(exc_traceback)))
    print("*** format_tb:")
    print(repr(traceback.format_tb(exc_traceback)))
    print("*** tb_lineno:", exc_traceback.tb_lineno)

예제의 출력은 다음과 유사합니다:

*** print_tb:
  File "<doctest...>", line 10, in <module>
    lumberjack()
*** print_exception:
Traceback (most recent call last):
  File "<doctest...>", line 10, in <module>
    lumberjack()
  File "<doctest...>", line 4, in lumberjack
    bright_side_of_death()
IndexError: tuple index out of range
*** print_exc:
Traceback (most recent call last):
  File "<doctest...>", line 10, in <module>
    lumberjack()
  File "<doctest...>", line 4, in lumberjack
    bright_side_of_death()
IndexError: tuple index out of range
*** format_exc, first and last line:
Traceback (most recent call last):
IndexError: tuple index out of range
*** format_exception:
['Traceback (most recent call last):\n',
 '  File "<doctest...>", line 10, in <module>\n    lumberjack()\n',
 '  File "<doctest...>", line 4, in lumberjack\n    bright_side_of_death()\n',
 '  File "<doctest...>", line 7, in bright_side_of_death\n    return tuple()[0]\n',
 'IndexError: tuple index out of range\n']
*** extract_tb:
[<FrameSummary file <doctest...>, line 10 in <module>>,
 <FrameSummary file <doctest...>, line 4 in lumberjack>,
 <FrameSummary file <doctest...>, line 7 in bright_side_of_death>]
*** format_tb:
['  File "<doctest...>", line 10, in <module>\n    lumberjack()\n',
 '  File "<doctest...>", line 4, in lumberjack\n    bright_side_of_death()\n',
 '  File "<doctest...>", line 7, in bright_side_of_death\n    return tuple()[0]\n']
*** tb_lineno: 10

다음 예제는 스택을 인쇄하고 포맷하는 다양한 방법을 보여줍니다:

>>> import traceback
>>> def another_function():
...     lumberstack()
...
>>> def lumberstack():
...     traceback.print_stack()
...     print(repr(traceback.extract_stack()))
...     print(repr(traceback.format_stack()))
...
>>> another_function()
  File "<doctest>", line 10, in <module>
    another_function()
  File "<doctest>", line 3, in another_function
    lumberstack()
  File "<doctest>", line 6, in lumberstack
    traceback.print_stack()
[('<doctest>', 10, '<module>', 'another_function()'),
 ('<doctest>', 3, 'another_function', 'lumberstack()'),
 ('<doctest>', 7, 'lumberstack', 'print(repr(traceback.extract_stack()))')]
['  File "<doctest>", line 10, in <module>\n    another_function()\n',
 '  File "<doctest>", line 3, in another_function\n    lumberstack()\n',
 '  File "<doctest>", line 8, in lumberstack\n    print(repr(traceback.format_stack()))\n']

이 마지막 예제는 마지막 몇 가지 포매팅 함수를 예시합니다:

>>> import traceback
>>> traceback.format_list([('spam.py', 3, '<module>', 'spam.eggs()'),
...                        ('eggs.py', 42, 'eggs', 'return "bacon"')])
['  File "spam.py", line 3, in <module>\n    spam.eggs()\n',
 '  File "eggs.py", line 42, in eggs\n    return "bacon"\n']
>>> an_error = IndexError('tuple index out of range')
>>> traceback.format_exception_only(type(an_error), an_error)
['IndexError: tuple index out of range\n']

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

파이썬 실행시간 서비스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

파이썬 실행시간 서비스 »

|

__future__ — 퓨처 문 정의

소스 코드: Lib/__future__.py [https://github.com/python/cpython/tree/3.7/Lib/__future__.py]

__future__ 는 실제 모듈이며 세 가지 용도로 사용됩니다:

임포트 문을 분석하고 임포트하는 모듈을 발견하리라고 기대하는 기존 도구가 혼동하지 않게 하려고.

2.1 이전의 배포에서 퓨처 문 을 실행하면 최소한 실행시간 예외를 일으키도록 보장하기 위해 (2.1 이전에는 그런 이름의 모듈이 없으므로 __future__ 임포트는 실패합니다).

호환되지 않는 변경 사항이 도입된 시점과 그것이 필수적일 때를 — 또는 이미 필수적으로 된 때를 — 문서로 만들기 위해. 이것은 실행 가능한 문서 형식이며, __future__ 를 임포트 해서 내용을 들여다봄으로써 프로그래밍 방식으로 검사 할 수 있습니다.

__future__.py 의 각 문장은 다음과 같은 형식입니다:

FeatureName = _Feature(OptionalRelease, MandatoryRelease,
                       CompilerFlag)

보통, OptionalRelease 는 MandatoryRelease 보다 작으며, 둘 다 sys.version_info와 같은 형태의 5-튜플입니다:

(PY_MAJOR_VERSION, # the 2 in 2.1.0a3; an int
 PY_MINOR_VERSION, # the 1; an int
 PY_MICRO_VERSION, # the 0; an int
 PY_RELEASE_LEVEL, # "alpha", "beta", "candidate" or "final"; string
 PY_RELEASE_SERIAL # the 3; an int
)

OptionalRelease 는 해당 기능이 승인된 첫 번째 배포를 기록합니다.

MandatoryRelease 가 아직 배포되지 않은 경우, MandatoryRelease 는 해당 기능이 언어 일부가 될 배포를 예측합니다.

그렇지 않으면 MandatoryRelease 는 기능이 언어 일부가 된 때를 기록합니다; 그 배포와 그 이후의 배포에서, 모듈이 해당 기능을 사용하기 위해 더 퓨처 문을 요구하지 않지만, 그러한 임포트는 계속 사용할 수 있습니다.

MandatoryRelease 는 None 일 수도 있습니다. 이는 계획된 기능이 삭제되었음을 의미합니다.

클래스 _Feature 의 인스턴스는 두 개의 상응하는 메서드인 getOptionalRelease() 와 getMandatoryRelease() 를 가지고 있습니다.

CompilerFlag 은 동적으로 컴파일되는 코드에서 해당 기능을 활성화하기 위해, 내장 함수 compile() 의 네 번째 인자로 전달되어야 하는 (비트 필드) 플래그입니다. 이 플래그는 _Feature 인스턴스의 compiler_flag 어트리뷰트에 저장됩니다.

어떤 기능 설명도 __future__ 에서 삭제되지 않습니다. 파이썬 2.1에서 소개된 이후로 이 메커니즘을 사용하여 다음과 같은 기능이 언어에 도입되었습니다:

기능

선택적 버전

필수적 버전

효과

nested_scopes

2.1.0b1

2.2

PEP 227 [https://www.python.org/dev/peps/pep-0227]: 정적으로 중첩된 스코프

generators

2.2.0a1

2.3

PEP 255 [https://www.python.org/dev/peps/pep-0255]: 단순 제너레이터

division

2.2.0a2

3.0

PEP 238 [https://www.python.org/dev/peps/pep-0238]: 나누기 연산자 변경

absolute_import

2.5.0a1

3.0

PEP 328 [https://www.python.org/dev/peps/pep-0328]: 임포트: 복수 줄 및 절대/상대

with_statement

2.5.0a1

2.6

PEP 343 [https://www.python.org/dev/peps/pep-0343]: “with” 문

print_function

2.6.0a2

3.0

PEP 3105 [https://www.python.org/dev/peps/pep-3105]: print를 함수로 만들기

unicode_literals

2.6.0a2

3.0

PEP 3112 [https://www.python.org/dev/peps/pep-3112]: 파이썬 3000의 바이트열 리터럴

generator_stop

3.5.0b1

3.7

PEP 479 [https://www.python.org/dev/peps/pep-0479]: 제너레이터 내부의 StopIteration 처리

annotations

3.7.0b1

4.0

PEP 563 [https://www.python.org/dev/peps/pep-0563]: 어노테이션의 지연된 평가

더 보기

퓨처 문

컴파일러가 퓨처 임포트를 처리하는 방법.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

파이썬 실행시간 서비스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

파이썬 실행시간 서비스 »

|

gc — 가비지 수거기 인터페이스

이 모듈은 선택적인 가비지 수거기에 대한 인터페이스를 제공합니다. 수거기를 비활성화하고, 수거 빈도를 조정하며, 디버깅 옵션을 설정하는 기능을 제공합니다. 또한 수거기가 발견했지만 해제할 수 없는 도달 불가능한 객체에 대한 액세스를 제공합니다. 수거기는 파이썬에서 이미 사용된 참조 횟수 추적을 보충하므로, 프로그램이 참조 순환을 만들지 않는다고 확신한다면 수거기를 비활성화 할 수 있습니다. gc.disable()을 호출하여 자동 수거를 비활성화 할 수 있습니다. 누수가 발생하는 프로그램을 디버그하려면, gc.set_debug(gc.DEBUG_LEAK)을 호출하십시오. 이것은 gc.DEBUG_SAVEALL을 포함하므로, 가비지 수거된 객체가 검사를 위해 gc.garbage에 저장되도록 함에 유의하십시오.

gc 모듈은 다음 함수를 제공합니다:

gc.enable()

자동 가비지 수거를 활성화합니다.

gc.disable()

자동 가비지 수거를 비활성화합니다.

gc.isenabled()

Return True if automatic collection is enabled.

gc.collect(generation=2)

인자가 없으면, 전체 수거를 실행합니다. 선택적 인자 generation은 어떤 세대를 수거할지 지정하는 정수(0에서 2)일 수 있습니다. 세대 번호가 유효하지 않으면 ValueError가 발생합니다. 발견된 도달할 수 없는(unreachable) 객체의 수가 반환됩니다.

여러 내장형을 위해 유지되는 자유 목록(free list)은 전체 수거나 최고 세대(2)의 수거가 실행될 때마다 지워집니다. 특정 구현(특히 float)으로 인해, 일부 자유 목록에서 모든 항목이 해제되지는 않을 수 있습니다.

gc.set_debug(flags)

가비지 수거 디버깅 플래그를 설정합니다. 디버깅 정보가 sys.stderr에 기록됩니다. 디버깅을 제어하기 위해 비트 연산을 사용하여 결합할 수 있는 디버깅 플래그 목록은 아래를 참조하십시오.

gc.get_debug()

현재 설정된 디버깅 플래그를 반환합니다.

gc.get_objects()

Returns a list of all objects tracked by the collector, excluding the list returned.

gc.get_stats()

인터프리터가 시작된 이후의 수거 통계를 포함하는 세 개의 세대별 딕셔너리의 리스트를 반환합니다. 향후 키 수는 변경될 수 있지만, 현재 각 딕셔너리에는 다음과 같은 항목이 포함됩니다:

collections는 이 세대가 수거된 횟수입니다.

collected는 이 세대 내에서 수거된 총 객체 수입니다.

uncollectable은 이 세대 내에서 수거할 수 없는 (따라서 garbage 리스트로 이동된) 것으로 확인된 총 객체 수입니다.

버전 3.4에 추가.

gc.set_threshold(threshold0[, threshold1[, threshold2]])

가비지 수거 임곗값(수거 빈도)을 설정합니다. threshold0을 0으로 설정하면 수거가 비활성화됩니다.

The GC classifies objects into three generations depending on how many collection sweeps they have survived. New objects are placed in the youngest generation (generation 0). If an object survives a collection it is moved into the next older generation. Since generation 2 is the oldest generation, objects in that generation remain there after a collection. In order to decide when to run, the collector keeps track of the number object allocations and deallocations since the last collection. When the number of allocations minus the number of deallocations exceeds threshold0, collection starts. Initially only generation 0 is examined. If generation 0 has been examined more than threshold1 times since generation 1 has been examined, then generation 1 is examined as well. With the third generation, things are a bit more complicated, see Collecting the oldest generation [https://devguide.python.org/garbage_collector/#collecting-the-oldest-generation] for more information.

gc.get_count()

현재 수거 횟수를 (count0, count1, count2)의 튜플로 반환합니다.

gc.get_threshold()

현재 수거 임곗값을 (threshold0, threshold1, threshold2)의 튜플로 반환합니다.

gc.get_referrers(*objs)

objs에 있는 것을 직접 참조하는 객체의 리스트를 반환합니다. 이 함수는 가비지 수거를 지원하는 컨테이너만 찾습니다; 다른 객체를 참조하지만, 가비지 수거를 지원하지 않는 확장형은 찾을 수 없습니다.

이미 참조 해제되었지만, 순환에 참여해서 가비지 수거기에 의해 아직 수거되지 않은 객체는 결과 참조자(referrer)에 나열될 수 있음에 유의하십시오. 현재 살아있는 객체만 가져오려면, get_referrers()를 호출하기 전에 collect()를 호출하십시오.

경고

get_referrers()에서 반환된 객체를 사용할 때는, 그중 일부는 아직 생성 중이라서 일시적으로 유효하지 않은 상태일 수 있기 때문에 주의해야 합니다. 디버깅 이외의 목적으로 get_referrers()를 사용하지 마십시오.

gc.get_referents(*objs)

인자로 제공된 객체가 직접 참조하는 객체의 리스트를 반환합니다. 반환된 피 참조자(referent)는 인자의 C 수준 tp_traverse 메서드(있다면)가 방문한 객체이며, 실제로 직접 도달할 수 있는 모든 객체는 아닐 수 있습니다. tp_traverse 메서드는 가비지 수거를 지원하는 객체에서만 지원되며, 순환에 참여하는 객체만 방문하면 됩니다. 그래서, 예를 들어, 인자에서 정수에 직접 도달 할 수 있으면, 해당 정수 객체가 결과 목록에 나타날 수도 그렇지 않을 수도 있습니다.

gc.is_tracked(obj)

가비지 수거기가 객체를 현재 추적하고 있으면 True를, 그렇지 않으면 False를 반환합니다. 일반적인 규칙으로, 원자 형(atomic type)의 인스턴스는 추적하지 않고, 원자 형이 아닌 인스턴스(컨테이너, 사용자 정의 객체…)는 추적합니다. 그러나 간단한 인스턴스의 가비지 수거기 크기를 줄이기 위해 일부 형별 최적화가 존재할 수 있습니다 (예를 들어, 원자적 키와 값만 포함하는 딕셔너리):

>>> gc.is_tracked(0)
False
>>> gc.is_tracked("a")
False
>>> gc.is_tracked([])
True
>>> gc.is_tracked({})
False
>>> gc.is_tracked({"a": 1})
False
>>> gc.is_tracked({"a": []})
True

버전 3.1에 추가.

gc.freeze()

Freeze all the objects tracked by gc - move them to a permanent generation and ignore all the future collections. This can be used before a POSIX fork() call to make the gc copy-on-write friendly or to speed up collection. Also collection before a POSIX fork() call may free pages for future allocation which can cause copy-on-write too so it’s advised to disable gc in master process and freeze before fork and enable gc in child process.

버전 3.7에 추가.

gc.unfreeze()

영구 세대(permanent generation)의 객체를 고정 해제하고, 가장 나이 든 세대로 되돌립니다.

버전 3.7에 추가.

gc.get_freeze_count()

영구 세대(permanent generation)에 있는 객체 수를 반환합니다.

버전 3.7에 추가.

다음 변수가 전용 액세스로 제공됩니다 (값을 변경할 수는 있지만, 다시 연결해서는 안 됩니다):

gc.garbage

A list of objects which the collector found to be unreachable but could not be freed (uncollectable objects). Starting with Python 3.4, this list should be empty most of the time, except when using instances of C extension types with a non-NULL tp_del slot.

DEBUG_SAVEALL이 설정되면, 도달할 수 없는 모든 객체가 해제되지 않고 이 목록에 추가됩니다.

버전 3.2에서 변경: 인터프리터 종료 시 이 목록이 비어 있지 않으면, ResourceWarning이 발생하는데, 기본적으로 조용(silent)합니다. DEBUG_UNCOLLECTABLE이 설정되면, 추가로 모든 수거 할 수 없는 객체가 인쇄됩니다.

버전 3.4에서 변경: PEP 442 [https://www.python.org/dev/peps/pep-0442]에 따라, __del__() 메서드를 가진 객체는 더는 gc.garbage에 들어가지 않습니다.

gc.callbacks

수거 전후에 가비지 수거기가 호출할 콜백의 리스트입니다. 콜백은 두 인자로 호출됩니다, phase와 info.

phase는 다음 두 값 중 하나일 수 있습니다:

“start”: 가비지 수거를 시작하려고 합니다.

“stop”: 가비지 수거가 완료되었습니다.

info는 콜백에 추가 정보를 제공하는 딕셔너리입니다. 현재 다음 키가 정의되어 있습니다:

“generation”: 수거되는 가장 나이 든 세대.

“collected”: phase가 “stop”일 때, 성공적으로 수거된 객체 수.

“uncollectable”: phase가 “stop”일 때, 수거할 수 없어서 garbage에 들어간 객체 수.

응용 프로그램은 이 리스트에 자체 콜백을 추가 할 수 있습니다. 주요 사용 사례는 다음과 같습니다:

다양한 세대가 수거되는 빈도와 수거에 걸린 시간과 같은 가비지 수거에 대한 통계 수집.

응용 프로그램이 자신의 수거할 수 없는 형이 garbage에 나타날 때 식별하고 지울 수 있도록 합니다.

버전 3.3에 추가.

set_debug()와 함께 사용하기 위해 다음 상수가 제공됩니다:

gc.DEBUG_STATS

수거 중 통계를 인쇄합니다. 이 정보는 수거 빈도를 조정할 때 유용 할 수 있습니다.

gc.DEBUG_COLLECTABLE

발견된 수거 가능한 객체에 대한 정보를 인쇄합니다.

gc.DEBUG_UNCOLLECTABLE

발견된 수거 할 수 없는 객체에 대한 정보를 인쇄합니다 (도달 할 수 있지만, 수거기가 해제할 수 없는 객체). 이 객체는 garbage 리스트에 추가됩니다.

버전 3.2에서 변경: 인터프리터 종료 시에 garbage 리스트가 비어있지 않으면 내용을 인쇄하기도 합니다.

gc.DEBUG_SAVEALL

설정하면, 발견된 모든 도달할 수 없는 객체를 해제하는 대신 garbage에 추가합니다. 누수가 있는 프로그램을 디버깅하는 데 유용 할 수 있습니다.

gc.DEBUG_LEAK

수거기가 누수가 있는 프로그램에 대한 정보를 인쇄하도록 하는 데 필요한 디버깅 플래그 (DEBUG_COLLECTABLE | DEBUG_UNCOLLECTABLE | DEBUG_SAVEALL과 같습니다).

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

파이썬 실행시간 서비스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

파이썬 실행시간 서비스 »

|

inspect — Inspect live objects

Source code: Lib/inspect.py [https://github.com/python/cpython/tree/3.7/Lib/inspect.py]

The inspect module provides several useful functions to help get information about live objects such as modules, classes, methods, functions, tracebacks, frame objects, and code objects. For example, it can help you examine the contents of a class, retrieve the source code of a method, extract and format the argument list for a function, or get all the information you need to display a detailed traceback.

There are four main kinds of services provided by this module: type checking, getting source code, inspecting classes and functions, and examining the interpreter stack.

Types and members

The getmembers() function retrieves the members of an object such as a class or module. The functions whose names begin with “is” are mainly provided as convenient choices for the second argument to getmembers(). They also help you determine when you can expect to find the following special attributes:

Type

Attribute

Description

module

__doc__

documentation string

__file__

filename (missing for built-in modules)

class

__doc__

documentation string

__name__

name with which this class was defined

__qualname__

qualified name

__module__

name of module in which this class was defined

method

__doc__

documentation string

__name__

name with which this method was defined

__qualname__

qualified name

__func__

function object containing implementation of method

__self__

instance to which this method is bound, or None

__module__

name of module in which this method was defined

function

__doc__

documentation string

__name__

name with which this function was defined

__qualname__

qualified name

__code__

code object containing compiled function bytecode

__defaults__

tuple of any default values for positional or keyword parameters

__kwdefaults__

mapping of any default values for keyword-only parameters

__globals__

global namespace in which this function was defined

__annotations__

mapping of parameters names to annotations; "return" key is reserved for return annotations.

__module__

name of module in which this function was defined

traceback

tb_frame

frame object at this level

tb_lasti

index of last attempted instruction in bytecode

tb_lineno

current line number in Python source code

tb_next

next inner traceback object (called by this level)

frame

f_back

next outer frame object (this frame’s caller)

f_builtins

builtins namespace seen by this frame

f_code

code object being executed in this frame

f_globals

global namespace seen by this frame

f_lasti

index of last attempted instruction in bytecode

f_lineno

current line number in Python source code

f_locals

local namespace seen by this frame

f_trace

tracing function for this frame, or None

code

co_argcount

number of arguments (not including keyword only arguments, * or ** args)

co_code

string of raw compiled bytecode

co_cellvars

tuple of names of cell variables (referenced by containing scopes)

co_consts

tuple of constants used in the bytecode

co_filename

name of file in which this code object was created

co_firstlineno

number of first line in Python source code

co_flags

bitmap of CO_* flags, read more here

co_lnotab

encoded mapping of line numbers to bytecode indices

co_freevars

tuple of names of free variables (referenced via a function’s closure)

co_kwonlyargcount

number of keyword only arguments (not including ** arg)

co_name

name with which this code object was defined

co_names

tuple of names of local variables

co_nlocals

number of local variables

co_stacksize

virtual machine stack space required

co_varnames

tuple of names of arguments and local variables

generator

__name__

name

__qualname__

qualified name

gi_frame

frame

gi_running

is the generator running?

gi_code

code

gi_yieldfrom

object being iterated by yield from, or None

coroutine

__name__

name

__qualname__

qualified name

cr_await

object being awaited on, or None

cr_frame

frame

cr_running

is the coroutine running?

cr_code

code

cr_origin

where coroutine was created, or None. See sys.set_coroutine_origin_tracking_depth()

builtin

__doc__

documentation string

__name__

original name of this function or method

__qualname__

qualified name

__self__

instance to which a method is bound, or None

버전 3.5에서 변경: Add __qualname__ and gi_yieldfrom attributes to generators.

The __name__ attribute of generators is now set from the function name, instead of the code name, and it can now be modified.

버전 3.7에서 변경: Add cr_origin attribute to coroutines.

inspect.getmembers(object[, predicate])

Return all the members of an object in a list of (name, value) pairs sorted by name. If the optional predicate argument is supplied, only members for which the predicate returns a true value are included.

참고

getmembers() will only return class attributes defined in the metaclass when the argument is a class and those attributes have been listed in the metaclass’ custom __dir__().

inspect.getmodulename(path)

Return the name of the module named by the file path, without including the names of enclosing packages. The file extension is checked against all of the entries in importlib.machinery.all_suffixes(). If it matches, the final path component is returned with the extension removed. Otherwise, None is returned.

Note that this function only returns a meaningful name for actual Python modules - paths that potentially refer to Python packages will still return None.

버전 3.3에서 변경: The function is based directly on importlib.

inspect.ismodule(object)

Return True if the object is a module.

inspect.isclass(object)

Return True if the object is a class, whether built-in or created in Python code.

inspect.ismethod(object)

Return True if the object is a bound method written in Python.

inspect.isfunction(object)

Return True if the object is a Python function, which includes functions created by a lambda expression.

inspect.isgeneratorfunction(object)

Return True if the object is a Python generator function.

inspect.isgenerator(object)

Return True if the object is a generator.

inspect.iscoroutinefunction(object)

Return True if the object is a coroutine function (a function defined with an async def syntax).

버전 3.5에 추가.

inspect.iscoroutine(object)

Return True if the object is a coroutine created by an async def function.

버전 3.5에 추가.

inspect.isawaitable(object)

Return True if the object can be used in await expression.

Can also be used to distinguish generator-based coroutines from regular generators:

def gen():
    yield
@types.coroutine
def gen_coro():
    yield

assert not isawaitable(gen())
assert isawaitable(gen_coro())

버전 3.5에 추가.

inspect.isasyncgenfunction(object)

Return True if the object is an asynchronous generator function, for example:

>>> async def agen():
...     yield 1
...
>>> inspect.isasyncgenfunction(agen)
True

버전 3.6에 추가.

inspect.isasyncgen(object)

Return True if the object is an asynchronous generator iterator created by an asynchronous generator function.

버전 3.6에 추가.

inspect.istraceback(object)

Return True if the object is a traceback.

inspect.isframe(object)

Return True if the object is a frame.

inspect.iscode(object)

Return True if the object is a code.

inspect.isbuiltin(object)

Return True if the object is a built-in function or a bound built-in method.

inspect.isroutine(object)

Return True if the object is a user-defined or built-in function or method.

inspect.isabstract(object)

Return True if the object is an abstract base class.

inspect.ismethoddescriptor(object)

Return True if the object is a method descriptor, but not if ismethod(), isclass(), isfunction() or isbuiltin() are true.

This, for example, is true of int.__add__. An object passing this test has a __get__() method but not a __set__() method, but beyond that the set of attributes varies. A __name__ attribute is usually sensible, and __doc__ often is.

Methods implemented via descriptors that also pass one of the other tests return False from the ismethoddescriptor() test, simply because the other tests promise more – you can, e.g., count on having the __func__ attribute (etc) when an object passes ismethod().

inspect.isdatadescriptor(object)

Return True if the object is a data descriptor.

Data descriptors have both a __get__ and a __set__ method. Examples are properties (defined in Python), getsets, and members. The latter two are defined in C and there are more specific tests available for those types, which is robust across Python implementations. Typically, data descriptors will also have __name__ and __doc__ attributes (properties, getsets, and members have both of these attributes), but this is not guaranteed.

inspect.isgetsetdescriptor(object)

Return True if the object is a getset descriptor.

CPython implementation detail: getsets are attributes defined in extension modules via PyGetSetDef structures. For Python implementations without such types, this method will always return False.

inspect.ismemberdescriptor(object)

Return True if the object is a member descriptor.

CPython implementation detail: Member descriptors are attributes defined in extension modules via PyMemberDef structures. For Python implementations without such types, this method will always return False.

Retrieving source code

inspect.getdoc(object)

Get the documentation string for an object, cleaned up with cleandoc(). If the documentation string for an object is not provided and the object is a class, a method, a property or a descriptor, retrieve the documentation string from the inheritance hierarchy.

버전 3.5에서 변경: Documentation strings are now inherited if not overridden.

inspect.getcomments(object)

Return in a single string any lines of comments immediately preceding the object’s source code (for a class, function, or method), or at the top of the Python source file (if the object is a module). If the object’s source code is unavailable, return None. This could happen if the object has been defined in C or the interactive shell.

inspect.getfile(object)

Return the name of the (text or binary) file in which an object was defined. This will fail with a TypeError if the object is a built-in module, class, or function.

inspect.getmodule(object)

Try to guess which module an object was defined in.

inspect.getsourcefile(object)

Return the name of the Python source file in which an object was defined. This will fail with a TypeError if the object is a built-in module, class, or function.

inspect.getsourcelines(object)

Return a list of source lines and starting line number for an object. The argument may be a module, class, method, function, traceback, frame, or code object. The source code is returned as a list of the lines corresponding to the object and the line number indicates where in the original source file the first line of code was found. An OSError is raised if the source code cannot be retrieved.

버전 3.3에서 변경: OSError is raised instead of IOError, now an alias of the former.

inspect.getsource(object)

Return the text of the source code for an object. The argument may be a module, class, method, function, traceback, frame, or code object. The source code is returned as a single string. An OSError is raised if the source code cannot be retrieved.

버전 3.3에서 변경: OSError is raised instead of IOError, now an alias of the former.

inspect.cleandoc(doc)

Clean up indentation from docstrings that are indented to line up with blocks of code.

All leading whitespace is removed from the first line. Any leading whitespace that can be uniformly removed from the second line onwards is removed. Empty lines at the beginning and end are subsequently removed. Also, all tabs are expanded to spaces.

Introspecting callables with the Signature object

버전 3.3에 추가.

The Signature object represents the call signature of a callable object and its return annotation. To retrieve a Signature object, use the signature() function.

inspect.signature(callable, *, follow_wrapped=True)

Return a Signature object for the given callable:

>>> from inspect import signature
>>> def foo(a, *, b:int, **kwargs):
...     pass

>>> sig = signature(foo)

>>> str(sig)
'(a, *, b:int, **kwargs)'

>>> str(sig.parameters['b'])
'b:int'

>>> sig.parameters['b'].annotation
<class 'int'>

Accepts a wide range of Python callables, from plain functions and classes to functools.partial() objects.

Raises ValueError if no signature can be provided, and TypeError if that type of object is not supported.

A slash(/) in the signature of a function denotes that the parameters prior to it are positional-only. For more info, see the FAQ entry on positional-only parameters.

버전 3.5에 추가: follow_wrapped parameter. Pass False to get a signature of callable specifically (callable.__wrapped__ will not be used to unwrap decorated callables.)

참고

Some callables may not be introspectable in certain implementations of Python. For example, in CPython, some built-in functions defined in C provide no metadata about their arguments.

class inspect.Signature(parameters=None, *, return_annotation=Signature.empty)

A Signature object represents the call signature of a function and its return annotation. For each parameter accepted by the function it stores a Parameter object in its parameters collection.

The optional parameters argument is a sequence of Parameter objects, which is validated to check that there are no parameters with duplicate names, and that the parameters are in the right order, i.e. positional-only first, then positional-or-keyword, and that parameters with defaults follow parameters without defaults.

The optional return_annotation argument, can be an arbitrary Python object, is the “return” annotation of the callable.

Signature objects are immutable. Use Signature.replace() to make a modified copy.

버전 3.5에서 변경: Signature objects are picklable and hashable.

empty

A special class-level marker to specify absence of a return annotation.

parameters

An ordered mapping of parameters’ names to the corresponding Parameter objects. Parameters appear in strict definition order, including keyword-only parameters.

버전 3.7에서 변경: Python only explicitly guaranteed that it preserved the declaration order of keyword-only parameters as of version 3.7, although in practice this order had always been preserved in Python 3.

return_annotation

The “return” annotation for the callable. If the callable has no “return” annotation, this attribute is set to Signature.empty.

bind(*args, **kwargs)

Create a mapping from positional and keyword arguments to parameters. Returns BoundArguments if *args and **kwargs match the signature, or raises a TypeError.

bind_partial(*args, **kwargs)

Works the same way as Signature.bind(), but allows the omission of some required arguments (mimics functools.partial() behavior.) Returns BoundArguments, or raises a TypeError if the passed arguments do not match the signature.

replace(*[, parameters][, return_annotation])

Create a new Signature instance based on the instance replace was invoked on. It is possible to pass different parameters and/or return_annotation to override the corresponding properties of the base signature. To remove return_annotation from the copied Signature, pass in Signature.empty.

>>> def test(a, b):
...     pass
>>> sig = signature(test)
>>> new_sig = sig.replace(return_annotation="new return anno")
>>> str(new_sig)
"(a, b) -> 'new return anno'"

classmethod from_callable(obj, *, follow_wrapped=True)

Return a Signature (or its subclass) object for a given callable obj. Pass follow_wrapped=False to get a signature of obj without unwrapping its __wrapped__ chain.

This method simplifies subclassing of Signature:

class MySignature(Signature):
    pass
sig = MySignature.from_callable(min)
assert isinstance(sig, MySignature)

버전 3.5에 추가.

class inspect.Parameter(name, kind, *, default=Parameter.empty, annotation=Parameter.empty)

Parameter objects are immutable. Instead of modifying a Parameter object, you can use Parameter.replace() to create a modified copy.

버전 3.5에서 변경: Parameter objects are picklable and hashable.

empty

A special class-level marker to specify absence of default values and annotations.

name

The name of the parameter as a string. The name must be a valid Python identifier.

CPython implementation detail: CPython generates implicit parameter names of the form .0 on the code objects used to implement comprehensions and generator expressions.

버전 3.6에서 변경: These parameter names are exposed by this module as names like implicit0.

default

The default value for the parameter. If the parameter has no default value, this attribute is set to Parameter.empty.

annotation

The annotation for the parameter. If the parameter has no annotation, this attribute is set to Parameter.empty.

kind

Describes how argument values are bound to the parameter. Possible values (accessible via Parameter, like Parameter.KEYWORD_ONLY):

Name

Meaning

POSITIONAL_ONLY

Value must be supplied as a positional argument.

Python has no explicit syntax for defining positional-only parameters, but many built-in and extension module functions (especially those that accept only one or two parameters) accept them.

POSITIONAL_OR_KEYWORD

Value may be supplied as either a keyword or positional argument (this is the standard binding behaviour for functions implemented in Python.)

VAR_POSITIONAL

A tuple of positional arguments that aren’t bound to any other parameter. This corresponds to a *args parameter in a Python function definition.

KEYWORD_ONLY

Value must be supplied as a keyword argument. Keyword only parameters are those which appear after a * or *args entry in a Python function definition.

VAR_KEYWORD

A dict of keyword arguments that aren’t bound to any other parameter. This corresponds to a **kwargs parameter in a Python function definition.

Example: print all keyword-only arguments without default values:

>>> def foo(a, b, *, c, d=10):
...     pass

>>> sig = signature(foo)
>>> for param in sig.parameters.values():
...     if (param.kind == param.KEYWORD_ONLY and
...                        param.default is param.empty):
...         print('Parameter:', param)
Parameter: c

replace(*[, name][, kind][, default][, annotation])

Create a new Parameter instance based on the instance replaced was invoked on. To override a Parameter attribute, pass the corresponding argument. To remove a default value or/and an annotation from a Parameter, pass Parameter.empty.

>>> from inspect import Parameter
>>> param = Parameter('foo', Parameter.KEYWORD_ONLY, default=42)
>>> str(param)
'foo=42'

>>> str(param.replace()) # Will create a shallow copy of 'param'
'foo=42'

>>> str(param.replace(default=Parameter.empty, annotation='spam'))
"foo:'spam'"

버전 3.4에서 변경: In Python 3.3 Parameter objects were allowed to have name set to None if their kind was set to POSITIONAL_ONLY. This is no longer permitted.

class inspect.BoundArguments

Result of a Signature.bind() or Signature.bind_partial() call. Holds the mapping of arguments to the function’s parameters.

arguments

An ordered, mutable mapping (collections.OrderedDict) of parameters’ names to arguments’ values. Contains only explicitly bound arguments. Changes in arguments will reflect in args and kwargs.

Should be used in conjunction with Signature.parameters for any argument processing purposes.

참고

Arguments for which Signature.bind() or Signature.bind_partial() relied on a default value are skipped. However, if needed, use BoundArguments.apply_defaults() to add them.

args

A tuple of positional arguments values. Dynamically computed from the arguments attribute.

kwargs

A dict of keyword arguments values. Dynamically computed from the arguments attribute.

signature

A reference to the parent Signature object.

apply_defaults()

Set default values for missing arguments.

For variable-positional arguments (*args) the default is an empty tuple.

For variable-keyword arguments (**kwargs) the default is an empty dict.

>>> def foo(a, b='ham', *args): pass
>>> ba = inspect.signature(foo).bind('spam')
>>> ba.apply_defaults()
>>> ba.arguments
OrderedDict([('a', 'spam'), ('b', 'ham'), ('args', ())])

버전 3.5에 추가.

The args and kwargs properties can be used to invoke functions:

def test(a, *, b):
    ...

sig = signature(test)
ba = sig.bind(10, b=20)
test(*ba.args, **ba.kwargs)

더 보기

PEP 362 [https://www.python.org/dev/peps/pep-0362] - Function Signature Object.

The detailed specification, implementation details and examples.

Classes and functions

inspect.getclasstree(classes, unique=False)

Arrange the given list of classes into a hierarchy of nested lists. Where a nested list appears, it contains classes derived from the class whose entry immediately precedes the list. Each entry is a 2-tuple containing a class and a tuple of its base classes. If the unique argument is true, exactly one entry appears in the returned structure for each class in the given list. Otherwise, classes using multiple inheritance and their descendants will appear multiple times.

inspect.getargspec(func)

Get the names and default values of a Python function’s parameters. A named tuple ArgSpec(args, varargs, keywords, defaults) is returned. args is a list of the parameter names. varargs and keywords are the names of the * and ** parameters or None. defaults is a tuple of default argument values or None if there are no default arguments; if this tuple has n elements, they correspond to the last n elements listed in args.

버전 3.0부터 폐지: Use getfullargspec() for an updated API that is usually a drop-in replacement, but also correctly handles function annotations and keyword-only parameters.

Alternatively, use signature() and Signature Object, which provide a more structured introspection API for callables.

inspect.getfullargspec(func)

Get the names and default values of a Python function’s parameters. A named tuple is returned:

FullArgSpec(args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations)

args is a list of the positional parameter names. varargs is the name of the * parameter or None if arbitrary positional arguments are not accepted. varkw is the name of the ** parameter or None if arbitrary keyword arguments are not accepted. defaults is an n-tuple of default argument values corresponding to the last n positional parameters, or None if there are no such defaults defined. kwonlyargs is a list of keyword-only parameter names in declaration order. kwonlydefaults is a dictionary mapping parameter names from kwonlyargs to the default values used if no argument is supplied. annotations is a dictionary mapping parameter names to annotations. The special key "return" is used to report the function return value annotation (if any).

Note that signature() and Signature Object provide the recommended API for callable introspection, and support additional behaviours (like positional-only arguments) that are sometimes encountered in extension module APIs. This function is retained primarily for use in code that needs to maintain compatibility with the Python 2 inspect module API.

버전 3.4에서 변경: This function is now based on signature(), but still ignores __wrapped__ attributes and includes the already bound first parameter in the signature output for bound methods.

버전 3.6에서 변경: This method was previously documented as deprecated in favour of signature() in Python 3.5, but that decision has been reversed in order to restore a clearly supported standard interface for single-source Python 2/3 code migrating away from the legacy getargspec() API.

버전 3.7에서 변경: Python only explicitly guaranteed that it preserved the declaration order of keyword-only parameters as of version 3.7, although in practice this order had always been preserved in Python 3.

inspect.getargvalues(frame)

Get information about arguments passed into a particular frame. A named tuple ArgInfo(args, varargs, keywords, locals) is returned. args is a list of the argument names. varargs and keywords are the names of the * and ** arguments or None. locals is the locals dictionary of the given frame.

참고

This function was inadvertently marked as deprecated in Python 3.5.

inspect.formatargspec(args[, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations[, formatarg, formatvarargs, formatvarkw, formatvalue, formatreturns, formatannotations]])

Format a pretty argument spec from the values returned by getfullargspec().

The first seven arguments are (args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations).

The other six arguments are functions that are called to turn argument names, * argument name, ** argument name, default values, return annotation and individual annotations into strings, respectively.

For example:

>>> from inspect import formatargspec, getfullargspec
>>> def f(a: int, b: float):
...     pass
...
>>> formatargspec(*getfullargspec(f))
'(a: int, b: float)'

버전 3.5부터 폐지: Use signature() and Signature Object, which provide a better introspecting API for callables.

inspect.formatargvalues(args[, varargs, varkw, locals, formatarg, formatvarargs, formatvarkw, formatvalue])

Format a pretty argument spec from the four values returned by getargvalues(). The format* arguments are the corresponding optional formatting functions that are called to turn names and values into strings.

참고

This function was inadvertently marked as deprecated in Python 3.5.

inspect.getmro(cls)

Return a tuple of class cls’s base classes, including cls, in method resolution order. No class appears more than once in this tuple. Note that the method resolution order depends on cls’s type. Unless a very peculiar user-defined metatype is in use, cls will be the first element of the tuple.

inspect.getcallargs(func, *args, **kwds)

Bind the args and kwds to the argument names of the Python function or method func, as if it was called with them. For bound methods, bind also the first argument (typically named self) to the associated instance. A dict is returned, mapping the argument names (including the names of the * and ** arguments, if any) to their values from args and kwds. In case of invoking func incorrectly, i.e. whenever func(*args, **kwds) would raise an exception because of incompatible signature, an exception of the same type and the same or similar message is raised. For example:

>>> from inspect import getcallargs
>>> def f(a, b=1, *pos, **named):
...     pass
>>> getcallargs(f, 1, 2, 3) == {'a': 1, 'named': {}, 'b': 2, 'pos': (3,)}
True
>>> getcallargs(f, a=2, x=4) == {'a': 2, 'named': {'x': 4}, 'b': 1, 'pos': ()}
True
>>> getcallargs(f)
Traceback (most recent call last):
...
TypeError: f() missing 1 required positional argument: 'a'

버전 3.2에 추가.

버전 3.5부터 폐지: Use Signature.bind() and Signature.bind_partial() instead.

inspect.getclosurevars(func)

Get the mapping of external name references in a Python function or method func to their current values. A named tuple ClosureVars(nonlocals, globals, builtins, unbound) is returned. nonlocals maps referenced names to lexical closure variables, globals to the function’s module globals and builtins to the builtins visible from the function body. unbound is the set of names referenced in the function that could not be resolved at all given the current module globals and builtins.

TypeError is raised if func is not a Python function or method.

버전 3.3에 추가.

inspect.unwrap(func, *, stop=None)

Get the object wrapped by func. It follows the chain of __wrapped__ attributes returning the last object in the chain.

stop is an optional callback accepting an object in the wrapper chain as its sole argument that allows the unwrapping to be terminated early if the callback returns a true value. If the callback never returns a true value, the last object in the chain is returned as usual. For example, signature() uses this to stop unwrapping if any object in the chain has a __signature__ attribute defined.

ValueError is raised if a cycle is encountered.

버전 3.4에 추가.

The interpreter stack

When the following functions return “frame records,” each record is a named tuple FrameInfo(frame, filename, lineno, function, code_context, index). The tuple contains the frame object, the filename, the line number of the current line, the function name, a list of lines of context from the source code, and the index of the current line within that list.

버전 3.5에서 변경: Return a named tuple instead of a tuple.

참고

Keeping references to frame objects, as found in the first element of the frame records these functions return, can cause your program to create reference cycles. Once a reference cycle has been created, the lifespan of all objects which can be accessed from the objects which form the cycle can become much longer even if Python’s optional cycle detector is enabled. If such cycles must be created, it is important to ensure they are explicitly broken to avoid the delayed destruction of objects and increased memory consumption which occurs.

Though the cycle detector will catch these, destruction of the frames (and local variables) can be made deterministic by removing the cycle in a finally clause. This is also important if the cycle detector was disabled when Python was compiled or using gc.disable(). For example:

def handle_stackframe_without_leak():
    frame = inspect.currentframe()
    try:
        # do something with the frame
    finally:
        del frame

If you want to keep the frame around (for example to print a traceback later), you can also break reference cycles by using the frame.clear() method.

The optional context argument supported by most of these functions specifies the number of lines of context to return, which are centered around the current line.

inspect.getframeinfo(frame, context=1)

Get information about a frame or traceback object. A named tuple Traceback(filename, lineno, function, code_context, index) is returned.

inspect.getouterframes(frame, context=1)

Get a list of frame records for a frame and all outer frames. These frames represent the calls that lead to the creation of frame. The first entry in the returned list represents frame; the last entry represents the outermost call on frame’s stack.

버전 3.5에서 변경: A list of named tuples FrameInfo(frame, filename, lineno, function, code_context, index) is returned.

inspect.getinnerframes(traceback, context=1)

Get a list of frame records for a traceback’s frame and all inner frames. These frames represent calls made as a consequence of frame. The first entry in the list represents traceback; the last entry represents where the exception was raised.

버전 3.5에서 변경: A list of named tuples FrameInfo(frame, filename, lineno, function, code_context, index) is returned.

inspect.currentframe()

Return the frame object for the caller’s stack frame.

CPython implementation detail: This function relies on Python stack frame support in the interpreter, which isn’t guaranteed to exist in all implementations of Python. If running in an implementation without Python stack frame support this function returns None.

inspect.stack(context=1)

Return a list of frame records for the caller’s stack. The first entry in the returned list represents the caller; the last entry represents the outermost call on the stack.

버전 3.5에서 변경: A list of named tuples FrameInfo(frame, filename, lineno, function, code_context, index) is returned.

inspect.trace(context=1)

Return a list of frame records for the stack between the current frame and the frame in which an exception currently being handled was raised in. The first entry in the list represents the caller; the last entry represents where the exception was raised.

버전 3.5에서 변경: A list of named tuples FrameInfo(frame, filename, lineno, function, code_context, index) is returned.

Fetching attributes statically

Both getattr() and hasattr() can trigger code execution when fetching or checking for the existence of attributes. Descriptors, like properties, will be invoked and __getattr__() and __getattribute__() may be called.

For cases where you want passive introspection, like documentation tools, this can be inconvenient. getattr_static() has the same signature as getattr() but avoids executing code when it fetches attributes.

inspect.getattr_static(obj, attr, default=None)

Retrieve attributes without triggering dynamic lookup via the descriptor protocol, __getattr__() or __getattribute__().

Note: this function may not be able to retrieve all attributes that getattr can fetch (like dynamically created attributes) and may find attributes that getattr can’t (like descriptors that raise AttributeError). It can also return descriptors objects instead of instance members.

If the instance __dict__ is shadowed by another member (for example a property) then this function will be unable to find instance members.

버전 3.2에 추가.

getattr_static() does not resolve descriptors, for example slot descriptors or getset descriptors on objects implemented in C. The descriptor object is returned instead of the underlying attribute.

You can handle these with code like the following. Note that for arbitrary getset descriptors invoking these may trigger code execution:

# example code for resolving the builtin descriptor types
class _foo:
    __slots__ = ['foo']

slot_descriptor = type(_foo.foo)
getset_descriptor = type(type(open(__file__)).name)
wrapper_descriptor = type(str.__dict__['__add__'])
descriptor_types = (slot_descriptor, getset_descriptor, wrapper_descriptor)

result = getattr_static(some_object, 'foo')
if type(result) in descriptor_types:
    try:
        result = result.__get__()
    except AttributeError:
        # descriptors can raise AttributeError to
        # indicate there is no underlying value
        # in which case the descriptor itself will
        # have to do
        pass

Current State of Generators and Coroutines

When implementing coroutine schedulers and for other advanced uses of generators, it is useful to determine whether a generator is currently executing, is waiting to start or resume or execution, or has already terminated. getgeneratorstate() allows the current state of a generator to be determined easily.

inspect.getgeneratorstate(generator)

Get current state of a generator-iterator.

Possible states are:

GEN_CREATED: Waiting to start execution.

GEN_RUNNING: Currently being executed by the interpreter.

GEN_SUSPENDED: Currently suspended at a yield expression.

GEN_CLOSED: Execution has completed.

버전 3.2에 추가.

inspect.getcoroutinestate(coroutine)

Get current state of a coroutine object. The function is intended to be used with coroutine objects created by async def functions, but will accept any coroutine-like object that has cr_running and cr_frame attributes.

Possible states are:

CORO_CREATED: Waiting to start execution.

CORO_RUNNING: Currently being executed by the interpreter.

CORO_SUSPENDED: Currently suspended at an await expression.

CORO_CLOSED: Execution has completed.

버전 3.5에 추가.

The current internal state of the generator can also be queried. This is mostly useful for testing purposes, to ensure that internal state is being updated as expected:

inspect.getgeneratorlocals(generator)

Get the mapping of live local variables in generator to their current values. A dictionary is returned that maps from variable names to values. This is the equivalent of calling locals() in the body of the generator, and all the same caveats apply.

If generator is a generator with no currently associated frame, then an empty dictionary is returned. TypeError is raised if generator is not a Python generator object.

CPython implementation detail: This function relies on the generator exposing a Python stack frame for introspection, which isn’t guaranteed to be the case in all implementations of Python. In such cases, this function will always return an empty dictionary.

버전 3.3에 추가.

inspect.getcoroutinelocals(coroutine)

This function is analogous to getgeneratorlocals(), but works for coroutine objects created by async def functions.

버전 3.5에 추가.

Code Objects Bit Flags

Python code objects have a co_flags attribute, which is a bitmap of the following flags:

inspect.CO_OPTIMIZED

The code object is optimized, using fast locals.

inspect.CO_NEWLOCALS

If set, a new dict will be created for the frame’s f_locals when the code object is executed.

inspect.CO_VARARGS

The code object has a variable positional parameter (*args-like).

inspect.CO_VARKEYWORDS

The code object has a variable keyword parameter (**kwargs-like).

inspect.CO_NESTED

The flag is set when the code object is a nested function.

inspect.CO_GENERATOR

The flag is set when the code object is a generator function, i.e. a generator object is returned when the code object is executed.

inspect.CO_NOFREE

The flag is set if there are no free or cell variables.

inspect.CO_COROUTINE

The flag is set when the code object is a coroutine function. When the code object is executed it returns a coroutine object. See PEP 492 [https://www.python.org/dev/peps/pep-0492] for more details.

버전 3.5에 추가.

inspect.CO_ITERABLE_COROUTINE

The flag is used to transform generators into generator-based coroutines. Generator objects with this flag can be used in await expression, and can yield from coroutine objects. See PEP 492 [https://www.python.org/dev/peps/pep-0492] for more details.

버전 3.5에 추가.

inspect.CO_ASYNC_GENERATOR

The flag is set when the code object is an asynchronous generator function. When the code object is executed it returns an asynchronous generator object. See PEP 525 [https://www.python.org/dev/peps/pep-0525] for more details.

버전 3.6에 추가.

참고

The flags are specific to CPython, and may not be defined in other Python implementations. Furthermore, the flags are an implementation detail, and can be removed or deprecated in future Python releases. It’s recommended to use public APIs from the inspect module for any introspection needs.

Command Line Interface

The inspect module also provides a basic introspection capability from the command line.

By default, accepts the name of a module and prints the source of that module. A class or function within the module can be printed instead by appended a colon and the qualified name of the target object.

--details

Print information about the specified object rather than the source code

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

파이썬 실행시간 서비스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

파이썬 실행시간 서비스 »

|

site — 사이트별 구성 훅

소스 코드: Lib/site.py [https://github.com/python/cpython/tree/3.7/Lib/site.py]

이 모듈은 초기화 중에 자동으로 임포트 됩니다. 인터프리터의 -S 옵션을 사용하여 자동 임포트를 억제할 수 있습니다.

-S를 사용하지 않는 한, 이 모듈의 임포트는 사이트별 경로를 모듈 검색 경로에 추가하고 몇 가지 내장(builtins)을 추가합니다. 사용되었다면, 이 모듈은 모듈 검색 경로를 자동으로 수정하거나 내장을 추가하지 않고도 안전하게 임포트 할 수 있습니다. 일반적인 사이트별 추가를 명시적으로 트리거 하려면, site.main() 함수를 호출하십시오.

버전 3.3에서 변경: -S를 사용하는 경우에도 모듈을 임포트 하면 경로 조작을 트리거 했습니다.

머리와 꼬리 부분에서 최대 4개의 디렉터리를 구성하는 것으로 시작합니다. 머리 부분에는, sys.prefix와 sys.exec_prefix를 사용합니다; 빈 머리는 건너뜁니다. 꼬리 부분에는, 빈 문자열을 사용하고 lib/site-packages(윈도우에서)나 lib/pythonX.Y/site-packages(유닉스와 맥에서)를 사용합니다. 각 머리-꼬리 조합마다, 존재하는 디렉터리를 참조하는지 확인하고, 그렇다면 디렉터리를 sys.path에 추가하고 새로 추가된 경로에서 구성 파일을 검사합니다.

버전 3.5에서 변경: “site-python” 디렉터리에 대한 지원이 제거되었습니다.

If a file named “pyvenv.cfg” exists one directory above sys.executable, sys.prefix and sys.exec_prefix are set to that directory and it is also checked for site-packages (sys.base_prefix and sys.base_exec_prefix will always be the “real” prefixes of the Python installation). If “pyvenv.cfg” (a bootstrap configuration file) contains the key “include-system-site-packages” set to anything other than “false” (case-insensitive), the system-level prefixes will still also be searched for site-packages; otherwise they won’t.

경로 구성 파일은 이름이 name.pth 인 파일이며, 위에서 언급한 4개의 디렉터리 중 하나에 존재합니다; 내용은 sys.path에 추가될 추가 항목(한 줄에 하나씩)입니다. 존재하지 않는 항목은 sys.path에 추가되지 않으며, 항목이 파일이 아닌 디렉터리를 참조하는지 확인하지 않습니다. 어떤 항목도 sys.path에 두 번 추가되지 않습니다. 빈 줄과 #으로 시작하는 줄은 건너뜁니다. import로 시작하는 (공백이나 탭이 뒤따르는) 줄은 실행됩니다.

예를 들어, sys.prefix와 sys.exec_prefix가 /usr/local로 설정되었다고 가정하십시오. 그러면 파이썬 X.Y 라이브러리는 /usr/local/lib/pythonX.Y에 설치되어 있습니다. 여기에 foo, bar 및 spam이라는 세 개의 서브 디렉터리와, foo.pth와 bar.pth라는 두 개의 경로 구성 파일이 있는 서브 디렉터리 /usr/local/lib/pythonX.Y/site-packages가 있다고 가정하십시오. foo.pth에 다음이 포함되어 있고:

# foo package configuration

foo
bar
bletch

bar.pth는 다음을 포함한다고 가정하십시오:

# bar package configuration

bar

그러면 다음과 같은 버전 별 디렉터리가 이 순서대로 sys.path에 추가됩니다:

/usr/local/lib/pythonX.Y/site-packages/bar
/usr/local/lib/pythonX.Y/site-packages/foo

bletch가 존재하지 않기 때문에 생략되었음에 유의하십시오; bar.pth가 알파벳순으로 foo.pth 앞에 오기 때문에 bar 디렉터리가 foo 디렉터리보다 앞에 옵니다; spam은 경로 구성 파일에 언급되어 있지 않기 때문에 생략되었습니다.

이러한 경로 조작 후, 임의의 사이트별 사용자 정의를 수행할 수 있는 sitecustomize라는 모듈을 임포트 하려고 시도합니다. 일반적으로 시스템 관리자가 site-packages 디렉터리에 만듭니다. 이 임포트가 ImportError나 이것의 서브 클래스 예외로 실패하고, 예외의 name 어트리뷰트가 'sitecustomize'와 같으면, 조용히 무시됩니다. 윈도우에서 pythonw.exe(IDLE을 시작하는 데 기본적으로 사용됩니다)처럼, 사용 가능한 출력 스트림 없이 파이썬을 시작하면, sitecustomize의 출력 시도는 무시됩니다. 다른 예외는 절차의 조용한 그리고 아마도 정체불명의 실패로 이어집니다.

그런 다음, ENABLE_USER_SITE가 참이면, 임의의 사용자별 사용자 정의를 수행할 수 있는 usercustomize라는 모듈을 임포트 하려고 시도합니다. 이 파일은 사용자 site-packages 디렉터리(아래를 보십시오)에 만들어지는 것이 관례입니다, -s에 의해 비활성화되지 않는 한 sys.path의 일부입니다. 이 임포트가 ImportError나 이것의 서브 클래스 예외로 실패하고, 예외의 name 어트리뷰트가 'usercustomize'와 같으면, 조용히 무시됩니다.

유닉스가 아닌 일부 시스템에서는, sys.prefix와 sys.exec_prefix가 비어 있고, 경로 조작을 건너뜀에 유의하십시오; 하지만 sitecustomize와 usercustomize 임포트는 여전히 시도됩니다.

Readline 구성

readline을 지원하는 시스템에서, 파이썬이 대화형 모드로 -S 옵션 없이 시작되면, 이 모듈은 rlcompleter 모듈을 임포트하고 구성합니다. 기본 동작은 탭 완성을 활성화하고 ~/.python_history를 히스토리 저장 파일로 사용하는 것입니다. 이를 비활성화하려면, sitecustomize나 usercustomize 모듈 또는 PYTHONSTARTUP 파일에서 sys.__interactivehook__ 어트리뷰트를 삭제(또는 재정의)하십시오.

버전 3.4에서 변경: rlcompleter와 히스토리 활성화가 자동으로 이루어졌습니다.

모듈 내용

site.PREFIXES

site-packages 디렉터리의 접두사 리스트.

site.ENABLE_USER_SITE

사용자 site-packages 디렉터리의 상태를 나타내는 플래그. True는 활성화되어 sys.path에 추가되었음을 의미합니다. False는 사용자 요청(-s나 PYTHONNOUSERSITE로)에 의해 비활성화되었음을 의미합니다. None은 보안상의 이유(사용자나 그룹 id와 유효(effective) id가 일치하지 않음)로 또는 관리자에 의해 비활성화되었음을 의미합니다.

site.USER_SITE

실행 중인 파이썬의 사용자 site-packages 경로. getusersitepackages()가 아직 호출되지 않았으면 None일 수 있습니다. 기본값은 유닉스와 비 프레임워크 맥 OS X 빌드의 경우 ~/.local/lib/pythonX.Y/site-packages, 맥 프레임워크 빌드의 경우 ~/Library/Python/X.Y/lib/python/site-packages, 윈도우의 경우 %APPDATA%\Python\PythonXY\site-packages입니다. 이 디렉터리는 사이트 디렉터리이며, 이는 그 안에 있는 .pth 파일이 처리됨을 의미합니다.

site.USER_BASE

사용자 site-packages의 베이스 디렉터리에 대한 경로. getuserbase()가 아직 호출되지 않았으면 None일 수 있습니다. 기본값은 유닉스와 맥 OS X 비 프레임워크 빌드의 경우 ~/.local, 맥 프레임워크 빌드의 경우 ~/Library/Python/X.Y, 윈도우의 경우 %APPDATA%\Python입니다. 이 값은 Distutils에서 사용자 설치 스킴의 스크립트, 데이터 파일, 파이썬 모듈 등의 설치 디렉터리를 계산하는 데 사용됩니다. PYTHONUSERBASE 도 참조하십시오.

site.main()

모든 표준 사이트별 디렉터리를 모듈 검색 경로에 추가합니다. 파이썬 인터프리터가 -S 플래그로 시작되지 않았으면, 이 모듈이 임포트 될 때 이 함수가 자동으로 호출됩니다.

버전 3.3에서 변경: 이 함수는 무조건 호출되었습니다.

site.addsitedir(sitedir, known_paths=None)

sys.path에 디렉터리를 추가하고 .pth 파일을 처리합니다. 일반적으로 sitecustomize나 usercustomize에서 사용됩니다 (위를 참조하십시오).

site.getsitepackages()

모든 전역 site-packages 디렉터리를 포함하는 리스트를 반환합니다.

버전 3.2에 추가.

site.getuserbase()

사용자 베이스 디렉터리 USER_BASE의 경로를 반환합니다. 아직 초기화되지 않았으면, 이 함수는 PYTHONUSERBASE를 따라 설정합니다.

버전 3.2에 추가.

site.getusersitepackages()

사용자별 site-packages 디렉터리 USER_SITE의 경로를 반환합니다. 아직 초기화되지 않았으면, 이 함수는 PYTHONNOUSERSITE와 USER_BASE를 따라 설정합니다.

버전 3.2에 추가.

Command Line Interface

site 모듈은 명령 줄에서 사용자 디렉터리를 얻는 방법도 제공합니다:

$ python3 -m site --user-site
/home/user/.local/lib/python3.3/site-packages

인자 없이 호출되면, 표준 출력에 sys.path의 내용을 인쇄한 다음, USER_BASE의 값과 디렉터리가 존재하는지를 인쇄하고, USER_SITE에 대해 같은 것을 인쇄하고, 마지막으로 ENABLE_USER_SITE의 값을 인쇄합니다.

--user-base

사용자 베이스 디렉터리의 경로를 인쇄합니다.

--user-site

사용자 site-packages 디렉터리의 경로를 인쇄합니다.

두 옵션이 모두 제공되면, os.pathsep으로 구분하여, 사용자 베이스와 사용자 사이트를 (항상 이 순서대로) 인쇄합니다.

어떤 옵션이건 제공되면, 스크립트는 다음 값 중 하나로 종료됩니다: 사용자 site-packages 디렉터리가 활성화되었으면 0, 사용자에 의해 비활성화되었으면 1, 보안상의 이유나 관리자에 의해 비활성화되었으면 2, 그리고 에러가 있으면 2보다 큰 값.

더 보기

PEP 370 [https://www.python.org/dev/peps/pep-0370] – 사용자별 site-packages 디렉터리

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

파이썬 실행시간 서비스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

|

사용자 정의 파이썬 인터프리터

이 장에서 설명하는 모듈은 파이썬의 대화형 인터프리터와 비슷한 인터페이스를 작성할 수 있도록 합니다. 파이썬 언어 외에도 몇 가지 특별한 기능을 지원하는 파이썬 인터프리터를 원한다면, code 모듈을 살펴보아야 합니다. (codeop 모듈은 더 저수준이며, 불완전할 수도 있는 파이썬 코드 조각의 컴파일을 지원하는 데 사용됩니다.)

이 장에서 설명하는 모듈의 전체 목록은 다음과 같습니다:

code — 인터프리터 베이스 클래스

대화형 인터프리터 객체

대화형 콘솔 객체

codeop — 파이썬 코드 컴파일

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

사용자 정의 파이썬 인터프리터 »

|

code — 인터프리터 베이스 클래스

소스 코드: Lib/code.py [https://github.com/python/cpython/tree/3.7/Lib/code.py]

code 모듈은 파이썬에서 REPL(read-eval-print loop)을 구현하는 기능을 제공합니다. 대화형 인터프리터 프롬프트를 제공하는 응용 프로그램을 만드는 데 사용할 수 있는 두 개의 클래스와 편리 함수들이 포함되어 있습니다.

class code.InteractiveInterpreter(locals=None)

이 클래스는 구문 분석과 인터프리터 상태(사용자의 이름 공간)를 처리합니다; 입력 버퍼링이나 프롬프트 또는 입력 파일 이름 지정을 처리하지 않습니다 (파일명은 항상 명시적으로 전달됩니다). 선택적 locals 인자는 코드가 실행될 딕셔너리를 지정합니다; 기본값은 키 '__name__'이 '__console__'로 설정되고 키 '__doc__'이 None으로 설정된 새로 만들어진 딕셔너리입니다.

class code.InteractiveConsole(locals=None, filename="<console>")

대화형 파이썬 인터프리터의 동작을 가깝게 흉내 냅니다. 이 클래스는 InteractiveInterpreter를 기반으로 하며 친숙한 sys.ps1과 sys.ps2를 사용하는 프롬프트와 입력 버퍼링을 추가합니다.

code.interact(banner=None, readfunc=None, local=None, exitmsg=None)

REPL(read-eval-print loop)를 실행하는 편리 함수. 이것은 InteractiveConsole의 새 인스턴스를 만들고, 제공된다면 readfunc가 InteractiveConsole.raw_input() 메서드로 사용되도록 설정합니다. local이 제공되면 인터프리터 루프의 기본 이름 공간으로 사용하기 위해 InteractiveConsole 생성자로 전달됩니다. 그런 다음 인스턴스의 interact() 메서드를 실행하는데, 제공된다면 banner와 exitmsg를 각각 배너와 종료 메시지로 사용하도록 전달합니다. 콘솔 객체는 사용 후에 폐기됩니다.

버전 3.6에서 변경: exitmsg 매개 변수가 추가되었습니다.

code.compile_command(source, filename="<input>", symbol="single")

이 함수는 파이썬의 인터프리터 메인 루프(소위 REPL)를 흉내 내고 싶은 프로그램에 유용합니다. 까다로운 부분은 사용자가 후에 추가의 텍스트를 입력해서 완성할 수 있는 불완전한 명령을 입력했는지를 결정하는 것입니다 (완전한 명령이나 문법 에러가 아니라). 이 함수는 거의 항상 실제 인터프리터 메인 루프와 같은 결정을 내립니다.

source is the source string; filename is the optional filename from which source was read, defaulting to '<input>'; and symbol is the optional grammar start symbol, which should be 'single' (the default), 'eval' or 'exec'.

명령이 완전하고 유효하면 코드 객체(compile(source, filename, symbol)와 같습니다)를 반환합니다; 명령이 불완전하면 None을 반환합니다; 명령이 완전하고 문법 에러가 있으면 SyntaxError를 발생시키고, 명령에 유효하지 않은 리터럴이 포함되었으면 OverflowError나 ValueError를 발생시킵니다.

대화형 인터프리터 객체

InteractiveInterpreter.runsource(source, filename="<input>", symbol="single")

Compile and run some source in the interpreter. Arguments are the same as for compile_command(); the default for filename is '<input>', and for symbol is 'single'. One of several things can happen:

입력이 잘못되었습니다; compile_command()가 예외(SyntaxError나 OverflowError)를 발생시켰습니다. 문법 트레이스백이 showsyntaxerror() 메서드를 호출하여 인쇄됩니다. runsource()는 False를 반환합니다.

입력이 불완전하고, 더 많은 입력이 필요합니다; compile_command()가 None을 반환했습니다. runsource()는 True를 반환합니다.

입력이 완전합니다; compile_command()가 코드 객체를 반환했습니다. 코드는 runcode()(SystemExit를 제외한 실행 시간 예외도 처리합니다)를 호출하여 실행됩니다. runsource()는 False를 반환합니다.

반환 값은 다음 줄의 프롬프트에 sys.ps1과 sys.ps2 중 어느 것을 사용할지 결정하는 데 사용될 수 있습니다.

InteractiveInterpreter.runcode(code)

코드 객체를 실행합니다. 예외가 발생하면, showtraceback()가 호출되어 트레이스백을 표시합니다. 전파가 허락된 SystemExit를 제외한 모든 예외를 잡습니다.

KeyboardInterrupt에 대한 노트: 이 예외는 이 코드의 어딘가에서 발생할 수 있으며, 항상 잡히지는 않습니다. 호출자는 이것을 처리할 준비가 되어 있어야 합니다.

InteractiveInterpreter.showsyntaxerror(filename=None)

방금 발생한 문법 에러를 표시합니다. 스택 트레이스는 표시하지 않습니다, 문법 에러에는 그런 것이 없기 때문입니다. filename이 주어지면, 파이썬 구문 분석기가 제공하는 기본 파일명 대신에 예외에 채워집니다, 문자열에서 읽을 때는 항상 '<string>'을 사용하기 때문입니다. 출력은 write() 메서드로 기록됩니다.

InteractiveInterpreter.showtraceback()

방금 발생한 예외를 표시합니다. 첫 번째 스택 항목을 제거합니다, 그것은 인터프리터 객체 구현에 속하기 때문입니다. 출력은 write() 메서드로 기록됩니다.

버전 3.5에서 변경: 단지 기본(primary) 트레이스백이 아니라 전체 연결된(chained) 트레이스백이 표시됩니다.

InteractiveInterpreter.write(data)

문자열을 표준 에러 스트림(sys.stderr)에 기록합니다. 파생 클래스는 필요에 따라 적절한 출력 처리를 제공하기 위해 이것을 재정의해야 합니다.

대화형 콘솔 객체

InteractiveConsole 클래스는 InteractiveInterpreter의 서브 클래스이므로, 인터프리터 객체의 모든 메서드와 다음과 같은 추가 메서드를 제공합니다.

InteractiveConsole.interact(banner=None, exitmsg=None)

대화형 파이썬 콘솔을 가깝게 흉내 냅니다. 선택적 banner 인자는 첫 번째 상호 작용 전에 인쇄할 배너를 지정합니다; 기본적으로 표준 파이썬 인터프리터가 출력하는 것과 비슷한 배너를 출력한 다음 괄호 안에 콘솔 객체의 클래스 이름을 출력합니다 (실제 인터프리터와 혼동하지 않도록 하기 위함입니다 – 너무 비슷합니다!).

선택적 exitmsg 인자는 종료할 때 인쇄되는 종료 메시지를 지정합니다. 종료 메시지를 표시하지 않으려면 빈 문자열을 전달하십시오. exitmsg가 주어지지 않았거나 None이면, 기본 메시지가 인쇄됩니다.

버전 3.4에서 변경: 배너 인쇄를 억제하려면, 빈 문자열을 전달하십시오.

버전 3.6에서 변경: 종료할 때 종료 메시지를 인쇄합니다.

InteractiveConsole.push(line)

소스 텍스트 줄을 인터프리터로 밀어 넣습니다. line에는 후행 줄 바꿈이 없어야 합니다; 내부 줄 바꿈은 있을 수 있습니다. 줄은 버퍼에 추가되고 인터프리터의 runsource() 메서드가 이어붙인 버퍼의 내용을 소스로 하여 호출됩니다. 이것이 명령이 실행되었거나 유효하지 않았다고 알리면 버퍼는 재설정됩니다; 그렇지 않고 명령이 불완전하다면, 버퍼는 줄을 추가한 상태로 유지됩니다. 반환 값은 추가 입력이 필요하면 True이고, 어떤 식으로든 줄이 처리되었으면 False입니다 (runsource()와 같습니다).

InteractiveConsole.resetbuffer()

처리되지 않은 소스 텍스트를 입력 버퍼에서 제거합니다.

InteractiveConsole.raw_input(prompt="")

프롬프트를 기록하고 줄을 읽습니다. 반환된 줄에는 후행 줄 바꿈이 포함되지 않습니다. 사용자가 EOF 키 시퀀스를 입력하면, EOFError가 발생합니다. 기본 구현은 sys.stdin에서 읽습니다; 서브 클래스는 이것을 다른 구현으로 바꿀 수 있습니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

사용자 정의 파이썬 인터프리터 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

사용자 정의 파이썬 인터프리터 »

|

codeop — 파이썬 코드 컴파일

소스 코드: Lib/codeop.py [https://github.com/python/cpython/tree/3.7/Lib/codeop.py]

codeop 모듈은 code 모듈에서와같이 파이썬 읽기-평가-인쇄 루프를 에뮬레이트 할 수 있는 유틸리티를 제공합니다. 결과적으로, 모듈을 직접 사용하고 싶지 않을 것입니다; 여러분의 프로그램에 이러한 루프를 포함 시키려면 대신 code 모듈을 사용하는 것이 좋습니다.

이 작업에는 두 가지 부분이 있습니다:

입력 줄이 파이썬 문장을 완성하는지 알려주는 것: 간단히 말해서, ‘>>>’ 나 ‘...’ 를 다음에 인쇄할지 알려주기.

사용자가 입력한 퓨처 문을 기억해서, 후속 입력을 컴파일할 때 이것들이 효과가 있도록 하기.

codeop 모듈은 이들을 각각 수행하는 방법과 이들을 모두 수행하는 방법을 제공합니다.

단지 전자를 수행하려면:

codeop.compile_command(source, filename="<input>", symbol="single")

source를 컴파일하려고 시도합니다. source는 파이썬 코드의 문자열이어야 하며, source가 유효한 파이썬 코드면 코드 객체를 반환합니다. 이 경우, 코드 객체의 filename 어트리뷰트는 filename가 되는데, 기본값은 '<input>'입니다. source가 유효한 파이썬 코드가 *아니지만 유효한 파이썬 코드의 앞부분이면 None을 반환합니다.

source에 문제가 있으면, 예외가 발생합니다. 유효하지 않은 파이썬 구문이 있으면 SyntaxError가 발생하고, 유효하지 않은 리터럴이 있으면 OverflowError 나 ValueError가 발생합니다.

The symbol argument determines whether source is compiled as a statement ('single', the default), as a sequence of statements ('exec') or as an expression ('eval'). Any other value will cause ValueError to be raised.

참고

구문 분석기가 source의 끝에 도달하기 전에 성공적인 결과로 구문 분석을 중지하는 것이 가능합니다 (하지만 대체로 그렇지 않습니다); 이 경우, 뒤따르는 기호는 에러를 유발하는 대신 무시 될 수 있습니다. 예를 들어, 백 슬래시 뒤에 두 개의 개행이 오면 그 뒤에 임의의 가비지가 올 수 있습니다. 구문 분석기를 위한 API가 개선되면 이 문제가 해결될 것입니다.

class codeop.Compile

이 클래스의 인스턴스는 내장 함수 compile()와 같은 서명의 __call__() 메서드를 갖지만, 인스턴스가 __future__ 문을 포함하는 프로그램 텍스트를 컴파일하면 인스턴스가 이를 ‘기억’하고 모든 후속 프로그램 텍스트를 이 문장의 효과 아래에서 컴파일한다는 차이점이 있습니다.

class codeop.CommandCompiler

이 클래스의 인스턴스는 compile_command()와 같은 서명의 __call__() 메서드를 갖습니다; 차이점은, 인스턴스가 __future__ 문을 포함하는 프로그램 텍스트를 컴파일하면 인스턴스가 이를 ‘기억’하고 모든 후속 프로그램 텍스트를 이 문장의 효과 아래에서 컴파일한다는 것입니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

사용자 정의 파이썬 인터프리터 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

|

모듈 임포트 하기

이 장에서 설명하는 모듈은 다른 파이썬 모듈을 임포트하는 새로운 방법과 임포트 절차를 사용자 정의하기 위한 훅을 제공합니다.

이 장에서 설명하는 모듈의 전체 목록은 다음과 같습니다:

zipimport — Zip 저장소에서 모듈 임포트

zipimporter 객체

예제

pkgutil — 패키지 확장 유틸리티

modulefinder — 스크립트에서 사용되는 모듈 찾기

ModuleFinder의 사용 예

runpy — 파이썬 모듈 찾기와 실행

importlib — The implementation of import

Introduction

Functions

importlib.abc – Abstract base classes related to import

importlib.resources – Resources

importlib.machinery – Importers and path hooks

importlib.util – Utility code for importers

Examples

Importing programmatically

Checking if a module can be imported

Importing a source file directly

Setting up an importer

Approximating importlib.import_module()

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

모듈 임포트 하기 »

|

zipimport — Zip 저장소에서 모듈 임포트

이 모듈은 파이썬 모듈(*.py, *.pyc)과 패키지를 ZIP-형식 저장소에서 임포트하는 기능을 추가합니다. 일반적으로 zipimport 모듈을 명시적으로 사용할 필요는 없습니다; ZIP 저장소 경로가 sys.path 항목에 있으면 내장 import 메커니즘에 의해 자동으로 사용됩니다.

일반적으로, sys.path는 문자열 디렉터리 이름의 리스트입니다. 이 모듈은 또한 sys.path 항목이 ZIP 파일 저장소를 명명하는 문자열이 될 수 있도록 합니다. ZIP 저장소에는 패키지 임포트를 지원하는 하위 디렉터리 구조가 포함될 수 있으며, 저장소 내의 경로를 지정하여 하위 디렉터리에서만 임포트 되도록 할 수 있습니다. 예를 들어, 경로 example.zip/lib/는 저장소 내의 lib/ 서브 디렉터리에서만 임포트하도록 합니다.

모든 파일이 ZIP 저장소에 있을 수 있지만, .py 와 .pyc 파일만 임포트 할 수 있습니다. 동적 모듈(.pyd, .so)의 ZIP 임포트는 허용되지 않습니다. 저장소에 .py 파일만 포함되어있으면, 파이썬은 해당 .pyc 파일을 추가하여 저장소를 수정하지 않습니다. 즉, ZIP 저장소에 .pyc 파일이 포함되어 있지 않으면, 임포트가 다소 느릴 수 있습니다.

저장소 주석이 포함된 ZIP 저장소는 현재 지원되지 않습니다.

더 보기

PKZIP Application Note [https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT]

사용된 형식과 알고리즘 저자인 Phil Katz의 ZIP 파일 형식에 관한 설명서.

PEP 273 [https://www.python.org/dev/peps/pep-0273] - Zip 저장소에서 모듈 임포트

구현도 제공한 James C. Ahlstrom이 작성했습니다. 파이썬 2.3은 PEP 273의 명세를 따르지만, Just van Rossum이 작성한 구현을 사용하는데 PEP 302에 설명된 임포트 훅을 사용합니다.

PEP 302 [https://www.python.org/dev/peps/pep-0302] - 새 임포트 훅

이 모듈이 작동하는 데 도움이 되는 임포트 훅을 추가하는 PEP.

이 모듈은 예외를 정의합니다:

exception zipimport.ZipImportError

zipimporter 객체가 발생시키는 예외. ImportError의 서브 클래스이므로, ImportError로도 잡힐 수 있습니다.

zipimporter 객체

zipimporter는 ZIP 파일을 임포트하는 클래스입니다.

class zipimport.zipimporter(archivepath)

새로운 zipimporter 인스턴스를 만듭니다. archivepath는 ZIP 파일의 경로이거나, ZIP 파일 내의 특정 경로여야 합니다. 예를 들어, archivepath foo/bar.zip/lib는 ZIP 파일 foo/bar.zip 내의 lib 디렉터리에 있는 모듈을 찾습니다 (존재한다면).

archivepath가 유효한 ZIP 저장소를 가리키지 않으면 ZipImportError가 발생합니다.

find_module(fullname[, path])

fullname로 지정된 모듈을 검색합니다. fullname은 완전히 정규화된 (점으로 구분된) 모듈 이름이어야 합니다. 모듈이 발견되면 zipimporter 인스턴스 자체를 반환하고, 그렇지 않으면 None을 반환합니다. 선택적 path 인자는 무시됩니다—임포터 프로토콜과의 호환성을 위해 있습니다.

get_code(fullname)

지정된 모듈의 코드 객체를 반환합니다. 모듈을 찾을 수 없으면 ZipImportError를 발생시킵니다.

get_data(pathname)

pathname와 관련된 데이터를 반환합니다. 파일을 찾을 수 없으면 OSError를 발생시킵니다.

버전 3.3에서 변경: OSError 대신 IOError 를 발생시켜왔습니다.

get_filename(fullname)

지정한 모듈이 임포트될 때 설정될 __file__의 값을 반환합니다. 모듈을 찾을 수 없으면 ZipImportError를 발생시킵니다.

버전 3.1에 추가.

get_source(fullname)

지정된 모듈의 소스 코드를 반환합니다. 모듈을 찾을 수 없으면 ZipImportError를 발생시키고, 저장소에 모듈이 있지만, 소스가 없으면 None을 반환합니다.

is_package(fullname)

fullname으로 지정된 모듈이 패키지면 True를 반환합니다. 모듈을 찾을 수 없으면 ZipImportError를 발생시킵니다.

load_module(fullname)

fullname으로 지정된 모듈을 로드 합니다. fullname은 완전히 정규화된 (점으로 구분된) 모듈 이름이어야 합니다. 임포트 된 모듈을 반환하거나, 찾지 못하면 ZipImportError를 발생시킵니다.

archive

있을 수도 있는 하위 경로를 제외한, 임포터와 연결된 ZIP 파일의 파일 이름.

prefix

모듈이 검색되는 ZIP 파일 내의 하위 경로. ZIP 파일의 루트를 가리키는 zipimporter 객체에서는 빈 문자열입니다.

archive와 prefix 어트리뷰트는, 슬래시로 결합 될 때, zipimporter 생성자에 지정된 원래 archivepath 인자와 같습니다.

예제

다음은 ZIP 저장소에서 모듈을 임포트하는 예제입니다 - zipimport 모듈이 명시적으로 사용되지 않음에 유의하십시오.

$ unzip -l example.zip
Archive:  example.zip
  Length     Date   Time    Name
 --------    ----   ----    ----
     8467  11-26-02 22:30   jwzthreading.py
 --------                   -------
     8467                   1 file
$ ./python
Python 2.3 (#1, Aug 1 2003, 19:54:32)
>>> import sys
>>> sys.path.insert(0, 'example.zip')  # Add .zip file to front of path
>>> import jwzthreading
>>> jwzthreading.__file__
'example.zip/jwzthreading.py'

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

모듈 임포트 하기 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

모듈 임포트 하기 »

|

pkgutil — 패키지 확장 유틸리티

소스 코드: Lib/pkgutil.py [https://github.com/python/cpython/tree/3.7/Lib/pkgutil.py]

이 모듈은 임포트 시스템, 특히 패키지 지원을 위한 유틸리티를 제공합니다.

class pkgutil.ModuleInfo(module_finder, name, ispkg)

모듈 정보에 대한 간략한 요약을 담고 있는 네임드 튜플.

버전 3.6에 추가.

pkgutil.extend_path(path, name)

패키지를 구성하는 모듈의 검색 경로를 확장합니다. 의도된 사용법은 패키지의 __init__.py에 다음 코드를 삽입하는 것입니다:

from pkgutil import extend_path
__path__ = extend_path(__path__, __name__)

그러면 sys.path에 있는 디렉터리들의 모든 서브 디렉터리 중 패키지의 이름과 일치하는 것들을 패키지의 __path__에 추가합니다. 이것은 하나의 논리적 패키지의 부분들을 여러 디렉터리로 분배하려고 할 때 유용합니다.

*가 name 인자와 일치하는 *.pkg 파일도 찾습니다. 이 기능은 import로 시작하는 줄을 특수하게 다루지 않는다는 점을 제외하면, *.pth 파일과 유사합니다 (자세한 내용은 site 모듈을 참조하십시오). *.pkg 파일을 액면 그대로 신뢰합니다: 중복은 확인하지만, *.pkg 파일에 있는 모든 항목은 파일 시스템에 있는지에 관계없이 경로에 추가됩니다. (이것은 기능입니다.)

입력 경로가 리스트가 아니면 (프로즌 패키지의 경우처럼) 변경되지 않은 상태로 반환됩니다. 입력 경로는 수정되지 않습니다; 확장한 사본이 반환됩니다. 항목은 사본의 끝에 추가되기만 합니다.

sys.path기 시퀀스라고 가정합니다. 존재하는 디렉터리를 참조하는 문자열이 아닌 sys.path 항목은 무시됩니다. 파일명으로 사용될 때 에러를 일으키는 sys.path의 유니코드 항목은 이 함수가 예외를 발생시키도록 할 수 있습니다 (os.path.isdir() 동작과 일치합니다).

class pkgutil.ImpImporter(dirname=None)

파이썬의 “고전적인” 임포트 알고리즘을 감싸는 PEP 302 [https://www.python.org/dev/peps/pep-0302] 파인더.

dirname이 문자열이면, 해당 디렉터리를 검색하는 PEP 302 [https://www.python.org/dev/peps/pep-0302] 파인더가 만들어집니다. dirname이 None이면, 현재 sys.path와 프로즌 또는 내장 모듈을 검색하는 PEP 302 [https://www.python.org/dev/peps/pep-0302] 파인더가 만들어집니다.

ImpImporter는 현재 sys.meta_path에 넣어서 사용하는 것을 지원하지 않음에 유의하십시오.

버전 3.3부터 폐지: 표준 임포트 메커니즘이 이제 완전히 PEP 302를 준수하고 importlib에서 사용할 수 있으므로, 이 에뮬레이션은 더는 필요하지 않습니다.

class pkgutil.ImpLoader(fullname, file, filename, etc)

파이썬의 “고전적인” 임포트 알고리즘을 감싸는 로더.

버전 3.3부터 폐지: 표준 임포트 메커니즘이 이제 완전히 PEP 302를 준수하고 importlib에서 사용할 수 있으므로, 이 에뮬레이션은 더는 필요하지 않습니다.

pkgutil.find_loader(fullname)

주어진 fullname에 대한 모듈 로더를 가져옵니다.

이것은 importlib.util.find_spec()을 감싸는 하위 호환성 래퍼인데, 대부분의 실패를 ImportError로 변환하고 전체 ModuleSpec이 아닌 로더만 반환합니다.

버전 3.3에서 변경: 패키지 내부 PEP 302 임포트 에뮬레이션에 의존하는 대신, importlib에 직접 기반하도록 갱신되었습니다.

버전 3.4에서 변경: PEP 451 [https://www.python.org/dev/peps/pep-0451]에 기반하도록 갱신되었습니다

pkgutil.get_importer(path_item)

주어진 path_item에 대한 파인더를 가져옵니다.

반환된 파인더는 경로 훅 때문에 새로 만들어지면 sys.path_importer_cache에 캐시 됩니다.

sys.path_hooks의 재검색이 필요하면, 캐시(또는 그 일부)를 수동으로 지울 수 있습니다.

버전 3.3에서 변경: 패키지 내부 PEP 302 임포트 에뮬레이션에 의존하는 대신, importlib에 직접 기반하도록 갱신되었습니다.

pkgutil.get_loader(module_or_name)

module_or_name에 대한 로더 객체를 가져옵니다.

모듈이나 패키지가 일반 임포트 메커니즘을 통해 액세스할 수 있으면, 그 장치의 관련 부분을 감싸는 래퍼가 반환됩니다. 모듈을 찾거나 임포트 할 수 없으면 None을 반환합니다. 명명된 모듈이 아직 임포트 되지 않았다면, 패키지 __path__를 구성하기 위해 포함하는 패키지(있다면))를 임포트 합니다.

버전 3.3에서 변경: 패키지 내부 PEP 302 임포트 에뮬레이션에 의존하는 대신, importlib에 직접 기반하도록 갱신되었습니다.

버전 3.4에서 변경: PEP 451 [https://www.python.org/dev/peps/pep-0451]에 기반하도록 갱신되었습니다

pkgutil.iter_importers(fullname='')

주어진 모듈 이름에 대해 파인더 객체를 산출(yield)합니다.

fullname에 ‘.’이 포함되어 있으면, 파인더는 fullname을 포함하는 패키지를 위한 것입니다, 그렇지 않으면, 등록된 모든 최상위 수준 파인더입니다 (즉, sys.meta_path 와 sys.path_hooks에 있는 것들).

명명된 모듈이 패키지에 있으면, 이 함수를 호출하는 부작용으로 그 패키지를 임포트 합니다.

모듈 이름을 지정하지 않으면, 모든 최상위 수준 파인더가 생성됩니다.

버전 3.3에서 변경: 패키지 내부 PEP 302 임포트 에뮬레이션에 의존하는 대신, importlib에 직접 기반하도록 갱신되었습니다.

pkgutil.iter_modules(path=None, prefix='')

path의 모든 서브 모듈에 대한 ModuleInfo를, 또는 path가 None이면, sys.path에 있는 모든 최상위 모듈을 산출(yield)합니다.

path는 None이거나 모듈을 찾을 경로의 리스트이어야 합니다.

prefix는 출력 시 모든 모듈 이름 앞에 출력할 문자열입니다.

참고

iter_modules() 메서드를 정의하는 파인더에서만 작동합니다. 이 인터페이스는 비표준이므로, 모듈은 importlib.machinery.FileFinder와 zipimport.zipimporter에 대한 구현도 제공합니다.

버전 3.3에서 변경: 패키지 내부 PEP 302 임포트 에뮬레이션에 의존하는 대신, importlib에 직접 기반하도록 갱신되었습니다.

pkgutil.walk_packages(path=None, prefix='', onerror=None)

path에 재귀적으로 포함된 모든 모듈이나, path가 None이면 모든 액세스할 수 있는 모듈에 대한 ModuleInfo를 산출(yield)합니다.

path는 None이거나 모듈을 찾을 경로의 리스트이어야 합니다.

prefix는 출력 시 모든 모듈 이름 앞에 출력할 문자열입니다.

서브 모듈 검색을 위한 __path__ 어트리뷰트에 액세스하기 위해, 이 함수는 주어진 path에 있는 모든 패키지(모든 모듈이 아닙니다!)를 임포트 해야 함에 유의하십시오.

onerror는 패키지 임포트를 시도하는 동안 예외가 발생하면 하나의 인자(임포트 하려는 패키지의 이름)로 호출되는 함수입니다. onerror 함수가 제공되지 않으면, ImportError는 잡아서 무시하고, 다른 모든 예외는 전파되어 검색이 종료됩니다.

예제:

# list all modules python can access
walk_packages()

# list all submodules of ctypes
walk_packages(ctypes.__path__, ctypes.__name__ + '.')

참고

iter_modules() 메서드를 정의하는 파인더에서만 작동합니다. 이 인터페이스는 비표준이므로, 모듈은 importlib.machinery.FileFinder와 zipimport.zipimporter에 대한 구현도 제공합니다.

버전 3.3에서 변경: 패키지 내부 PEP 302 임포트 에뮬레이션에 의존하는 대신, importlib에 직접 기반하도록 갱신되었습니다.

pkgutil.get_data(package, resource)

패키지에서 리소스를 가져옵니다.

이것은 로더 get_data API에 대한 래퍼입니다. package 인자는 표준 모듈 형식(foo.bar)의 패키지 이름이어야 합니다. resource 인자는 /를 경로 분리자로 사용하는 상대 파일명의 형식이어야 합니다. 상위 디렉터리 이름 ..는 허용되지 않으며, 루트에서 시작하는(/로 시작하는) 이름도 허용되지 않습니다.

이 함수는 지정된 리소스의 내용인 바이트열을 반환합니다.

파일시스템에 있는 패키지(이미 임포트 되었습니다)의 경우, 이것은 대략 다음과 동등합니다:

d = os.path.dirname(sys.modules[package].__file__)
data = open(os.path.join(d, resource), 'rb').read()

패키지를 찾거나 로드 할 수 없거나, 패키지가 get_data를 지원하지 않는 로더를 사용하면, None이 반환됩니다. 특히, 이름 공간 패키지를 위한 로더는 get_data를 지원하지 않습니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

모듈 임포트 하기 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

모듈 임포트 하기 »

|

modulefinder — 스크립트에서 사용되는 모듈 찾기

소스 코드: Lib/modulefinder.py [https://github.com/python/cpython/tree/3.7/Lib/modulefinder.py]

이 모듈은 스크립트가 임포트 한 모듈 집합을 판단하는 데 사용할 수 있는 ModuleFinder 클래스를 제공합니다. modulefinder.py는 스크립트로 실행될 수도 있습니다, 인자로 파이썬 스크립트의 파일 이름을 지정하면, 임포트 된 모듈의 보고서가 인쇄됩니다.

modulefinder.AddPackagePath(pkg_name, path)

지정된 path에서 pkg_name 패키지를 찾을 수 있음을 기록합니다.

modulefinder.ReplacePackage(oldname, newname)

oldname 라는 이름의 모듈이 실제로는 newname라는 이름의 패키지라는 것을 지정할 수 있도록 합니다.

class modulefinder.ModuleFinder(path=None, debug=0, excludes=[], replace_paths=[])

이 클래스는 스크립트가 임포트하는 모듈 집합을 판단하는 run_script() 와 report() 메서드를 제공합니다. path는 모듈을 검색할 디렉터리 리스트일 수 있습니다; 지정되지 않으면, sys.path가 사용됩니다. debug는 디버깅 수준을 설정합니다; 값이 크면 클래스가 수행 중인 작업에 대한 디버깅 메시지를 인쇄합니다. excludes는 분석에서 제외할 모듈 이름 리스트입니다. replace_paths는 모듈 경로에서 교체될 (oldpath, newpath) 튜플의 리스트입니다.

report()

빠지거나 빠진 것으로 보이는 모듈뿐 아니라, 스크립트가 임포트하는 모듈과 그들의 경로의 목록에 관한 보고서를 표준 출력으로 인쇄합니다.

run_script(pathname)

파이썬 코드를 포함하는, pathname 파일의 내용을 분석합니다.

modules

모듈 이름을 모듈에 매핑하는 딕셔너리. ModuleFinder의 사용 예를 참조하십시오.

ModuleFinder의 사용 예

나중에 분석할 스크립트 (bacon.py):

import re, itertools

try:
    import baconhameggs
except ImportError:
    pass

try:
    import guido.python.ham
except ImportError:
    pass

bacon.py의 보고서를 출력하는 스크립트:

from modulefinder import ModuleFinder

finder = ModuleFinder()
finder.run_script('bacon.py')

print('Loaded modules:')
for name, mod in finder.modules.items():
    print('%s: ' % name, end='')
    print(','.join(list(mod.globalnames.keys())[:3]))

print('-'*50)
print('Modules not imported:')
print('\n'.join(finder.badmodules.keys()))

표본 출력(아키텍처에 따라 다를 수 있습니다):

Loaded modules:
_types:
copyreg:  _inverted_registry,_slotnames,__all__
sre_compile:  isstring,_sre,_optimize_unicode
_sre:
sre_constants:  REPEAT_ONE,makedict,AT_END_LINE
sys:
re:  __module__,finditer,_expand
itertools:
__main__:  re,itertools,baconhameggs
sre_parse:  _PATTERNENDERS,SRE_FLAG_UNICODE
array:
types:  __module__,IntType,TypeType
---------------------------------------------------
Modules not imported:
guido.python.ham
baconhameggs

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

모듈 임포트 하기 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

모듈 임포트 하기 »

|

runpy — 파이썬 모듈 찾기와 실행

소스 코드: Lib/runpy.py [https://github.com/python/cpython/tree/3.7/Lib/runpy.py]

runpy 모듈은 파이썬 모듈을 먼저 임포트 하지 않고 찾아서 실행하는 데 사용합니다. 주요 용도는 파일 시스템이 아닌 파이썬 모듈 이름 공간을 사용하여 스크립트를 찾을 수 있는 -m 명령 줄 스위치를 구현하는 것입니다.

이것은 샌드박스 모듈이 아닙니다 - 모든 코드가 현재 프로세스에서 실행되고, 모든 부작용(가령 다른 모듈의 캐시된 임포트)은 함수가 반환된 후에도 그대로 유지됩니다.

또한, 실행된 코드에서 정의된 모든 함수와 클래스는 runpy 함수가 반환된 후 올바르게 작동하지 않을 수 있습니다. 이러한 제한이 주어진 사용 사례에 적합하지 않으면, 이 모듈보다 importlib가 더 적합한 선택일 수 있습니다.

runpy 모듈은 두 가지 함수를 제공합니다:

runpy.run_module(mod_name, init_globals=None, run_name=None, alter_sys=False)

지정된 모듈의 코드를 실행하고 결과 모듈 전역 딕셔너리를 반환합니다. 모듈의 코드는 먼저 표준 임포트 메커니즘(자세한 내용은 PEP 302 [https://www.python.org/dev/peps/pep-0302]를 참조하십시오)을 사용하여 찾은 다음 새로운 모듈 이름 공간에서 실행됩니다.

mod_name 인자는 절대 모듈 이름이어야 합니다. 모듈 이름이 일반 모듈이 아닌 패키지를 참조하면, 해당 패키지를 임포트하고 그 패키지 내의 __main__ 서브 모듈을 실행하고 결과 모듈 전역 딕셔너리를 반환합니다.

선택적 딕셔너리 인자 init_globals는 코드가 실행되기 전에 모듈의 전역 딕셔너리를 미리 채우기 위해 사용될 수 있습니다. 제공된 딕셔너리는 수정되지 않습니다. 아래의 특수 전역 변수가 제공된 딕셔너리에 정의되어 있으면, 해당 정의가 run_module()에 의해 대체됩니다.

특수 전역 변수 __name__, __spec__, __file__, __cached__, __loader__ 및 __package__는 모듈 코드가 실행되기 전에 전역 딕셔너리에 설정됩니다 (이 변수는 최소한의 변수 집합임에 유의하십시오 - 인터프리터 구현 세부 사항에 따라 다른 변수가 묵시적으로 설정될 수 있습니다).

__name__은 (이 선택적 인자가 None이 아니면) run_name으로, 명명된 모듈이 패키지면 mod_name + '.__main__'으로, 그렇지 않으면 mod_name 인자로 설정됩니다.

__spec__은 실제로 임포트 된 모듈에 맞게 설정됩니다 (즉, __spec__.name은 항상 mod_name이나 mod_name + '.__main__이 됩니다, 절대 run_name은 아닙니다).

__file__, __cached__, __loader__ 및 __package__는 모듈 스펙에 따라 표준적으로 설정됩니다.

인자 alter_sys가 제공되고 True로 평가되면, sys.argv[0]은 __file__ 값으로 갱신되고 sys.modules[__name__]은 실행 중인 모듈에 대한 임시 모듈 객체로 갱신됩니다. sys.argv[0]과 sys.modules[__name__]은 함수가 반환되기 전에 원래 값으로 복원됩니다.

이 sys 조작은 스레드-안전하지 않습니다. 다른 스레드가 부분적으로 초기화된 모듈과 변경된 인자 목록을 볼 수 있습니다. 스레드를 사용하는 코드에서 이 함수를 호출할 때 sys 모듈을 단독으로 두는 것이 좋습니다.

더 보기

명령 줄에서 동등한 기능을 제공하는 -m 옵션.

버전 3.1에서 변경: __main__ 서브 모듈을 찾아 패키지를 실행할 수 있는 기능 추가.

버전 3.2에서 변경: __cached__ 전역 변수 추가 (PEP 3147 [https://www.python.org/dev/peps/pep-3147]을 참조하십시오).

버전 3.4에서 변경: PEP 451 [https://www.python.org/dev/peps/pep-0451]이 추가한 모듈 스펙 기능을 활용하도록 갱신되었습니다. 이것은 실제 모듈 이름을 항상 __spec__.name으로 액세스할 수 있으면서, __cached__가 이 방법으로 실행되는 모듈에 대해 올바르게 설정되도록 합니다.

runpy.run_path(file_path, init_globals=None, run_name=None)

명명된 파일 시스템 위치에 있는 코드를 실행하고 결과 모듈 전역 딕셔너리를 반환합니다. CPython 명령 줄에 제공된 스크립트 이름과 마찬가지로, 제공된 경로는 파이썬 소스 파일, 컴파일된 바이트 코드 파일 또는 __main__ 모듈이 포함된 유효한 sys.path 항목(예를 들어, 최상위 수준 __main__.py 파일을 포함하는 zip 파일)을 가리킬 수 있습니다.

간단한 스크립트의 경우, 지정된 코드는 단순히 새로운 모듈 이름 공간에서 실행됩니다. 유효한 sys.path 항목(보통 zip 파일이나 디렉터리)의 경우, 항목이 먼저 sys.path의 시작 부분에 추가됩니다. 그런 다음 함수는 갱신된 경로를 사용하여 __main__ 모듈을 찾아 실행합니다. 지정된 위치에 해당 모듈이 없을 때 sys.path의 다른 위치에 있는 기존 __main__ 항목을 호출하는 것을 막는 특별한 보호 장치가 없다는 점에 유의하십시오.

선택적 딕셔너리 인자 init_globals는 코드가 실행되기 전에 모듈의 전역 딕셔너리를 미리 채우기 위해 사용될 수 있습니다. 제공된 딕셔너리는 수정되지 않습니다. 아래의 특수 전역 변수가 제공된 딕셔너리에 정의되어 있으면, 해당 정의가 run_path()에 의해 대체됩니다.

특수 전역 변수 __name__, __spec__, __file__, __cached__, __loader__ 및 __package__는 모듈 코드가 실행되기 전에 전역 딕셔너리에 설정됩니다 (이 변수는 최소한의 변수 집합임에 유의하십시오 - 인터프리터 구현 세부 사항에 따라 다른 변수가 묵시적으로 설정될 수 있습니다).

__name__은 (이 선택적 인자가 None이 아니면) run_name으로, 그렇지 않으면 '<run_path>'로 설정됩니다.

제공된 경로가 스크립트 파일(소스나 사전 컴파일된 바이트 코드)을 직접 참조하면, __file__은 제공된 경로로 설정되고 __spec__, __cached__, __loader__ 및 __package__는 모두 None으로 설정됩니다.

제공된 경로가 유효한 sys.path 항목에 대한 참조면, __spec__은 임포트 된 __main__ 모듈에 대해 적절하게 설정됩니다 (즉, __spec__.name은 항상 __main__이 됩니다). __file__, __cached__, __loader__ 및 __package__는 모듈 스펙에 따라 표준적으로 설정됩니다.

sys 모듈에도 여러 가지 변경이 적용됩니다. 첫째, sys.path는 위에서 설명한 것처럼 변경될 수 있습니다. sys.argv[0]은 file_path 값으로 갱신되고 sys.modules[__name__]은 실행 중인 모듈에 대한 임시 모듈 객체로 갱신됩니다. 함수가 반환되기 전에 sys의 항목에 대한 모든 수정 내용이 되돌려집니다.

run_module()과 달리, sys에 대한 변경은 이 함수에서는 선택 사항이 아닌데, 이 조정이 sys.path 항목의 실행을 허용하는 데 필수적이기 때문입니다. 스레드-안전 제약 사항이 계속 적용되므로, 스레드를 사용하는 코드에서 이 함수를 사용하려면 임포트 잠금을 사용하여 직렬화하거나 별도의 프로세스에 위임해야 합니다.

더 보기

명령 줄에서의 동등한 기능에 대한 인터페이스 옵션 (python path/to/script).

버전 3.2에 추가.

버전 3.4에서 변경: PEP 451 [https://www.python.org/dev/peps/pep-0451]이 추가한 모듈 스펙 기능을 활용하도록 갱신되었습니다. 이것은 __main__이 직접 실행되는 대신 유효한 sys.path 항목에서 임포트 될 때 __cached__가 올바르게 설정되도록 합니다.

더 보기

PEP 338 [https://www.python.org/dev/peps/pep-0338] – 모듈을 스크립트로 실행하기

Nick Coghlan이 작성하고 구현한 PEP.

PEP 366 [https://www.python.org/dev/peps/pep-0366] – 메인 모듈 명시적 상대 임포트

Nick Coghlan이 작성하고 구현한 PEP.

PEP 451 [https://www.python.org/dev/peps/pep-0451] – 임포트 시스템의 ModuleSpec 형

Eric Snow가 작성하고 구현한 PEP

명령 줄과 환경 - CPython 명령 줄 세부 사항

importlib.import_module() 함수

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

모듈 임포트 하기 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

모듈 임포트 하기 »

|

importlib — The implementation of import

버전 3.1에 추가.

Source code: Lib/importlib/__init__.py [https://github.com/python/cpython/tree/3.7/Lib/importlib/__init__.py]

Introduction

The purpose of the importlib package is two-fold. One is to provide the implementation of the import statement (and thus, by extension, the __import__() function) in Python source code. This provides an implementation of import which is portable to any Python interpreter. This also provides an implementation which is easier to comprehend than one implemented in a programming language other than Python.

Two, the components to implement import are exposed in this package, making it easier for users to create their own custom objects (known generically as an importer) to participate in the import process.

더 보기

임포트(import) 문

The language reference for the import statement.

Packages specification [https://www.python.org/doc/essays/packages/]

Original specification of packages. Some semantics have changed since the writing of this document (e.g. redirecting based on None in sys.modules).

The __import__() function

The import statement is syntactic sugar for this function.

PEP 235 [https://www.python.org/dev/peps/pep-0235]

Import on Case-Insensitive Platforms

PEP 263 [https://www.python.org/dev/peps/pep-0263]

Defining Python Source Code Encodings

PEP 302 [https://www.python.org/dev/peps/pep-0302]

New Import Hooks

PEP 328 [https://www.python.org/dev/peps/pep-0328]

Imports: Multi-Line and Absolute/Relative

PEP 366 [https://www.python.org/dev/peps/pep-0366]

Main module explicit relative imports

PEP 420 [https://www.python.org/dev/peps/pep-0420]

Implicit namespace packages

PEP 451 [https://www.python.org/dev/peps/pep-0451]

A ModuleSpec Type for the Import System

PEP 488 [https://www.python.org/dev/peps/pep-0488]

Elimination of PYO files

PEP 489 [https://www.python.org/dev/peps/pep-0489]

Multi-phase extension module initialization

PEP 552 [https://www.python.org/dev/peps/pep-0552]

Deterministic pycs

PEP 3120 [https://www.python.org/dev/peps/pep-3120]

Using UTF-8 as the Default Source Encoding

PEP 3147 [https://www.python.org/dev/peps/pep-3147]

PYC Repository Directories

Functions

importlib.__import__(name, globals=None, locals=None, fromlist=(), level=0)

An implementation of the built-in __import__() function.

참고

Programmatic importing of modules should use import_module() instead of this function.

importlib.import_module(name, package=None)

Import a module. The name argument specifies what module to import in absolute or relative terms (e.g. either pkg.mod or ..mod). If the name is specified in relative terms, then the package argument must be set to the name of the package which is to act as the anchor for resolving the package name (e.g. import_module('..mod', 'pkg.subpkg') will import pkg.mod).

The import_module() function acts as a simplifying wrapper around importlib.__import__(). This means all semantics of the function are derived from importlib.__import__(). The most important difference between these two functions is that import_module() returns the specified package or module (e.g. pkg.mod), while __import__() returns the top-level package or module (e.g. pkg).

If you are dynamically importing a module that was created since the interpreter began execution (e.g., created a Python source file), you may need to call invalidate_caches() in order for the new module to be noticed by the import system.

버전 3.3에서 변경: Parent packages are automatically imported.

importlib.find_loader(name, path=None)

Find the loader for a module, optionally within the specified path. If the module is in sys.modules, then sys.modules[name].__loader__ is returned (unless the loader would be None or is not set, in which case ValueError is raised). Otherwise a search using sys.meta_path is done. None is returned if no loader is found.

A dotted name does not have its parents implicitly imported as that requires loading them and that may not be desired. To properly import a submodule you will need to import all parent packages of the submodule and use the correct argument to path.

버전 3.3에 추가.

버전 3.4에서 변경: If __loader__ is not set, raise ValueError, just like when the attribute is set to None.

버전 3.4부터 폐지: Use importlib.util.find_spec() instead.

importlib.invalidate_caches()

Invalidate the internal caches of finders stored at sys.meta_path. If a finder implements invalidate_caches() then it will be called to perform the invalidation. This function should be called if any modules are created/installed while your program is running to guarantee all finders will notice the new module’s existence.

버전 3.3에 추가.

importlib.reload(module)

Reload a previously imported module. The argument must be a module object, so it must have been successfully imported before. This is useful if you have edited the module source file using an external editor and want to try out the new version without leaving the Python interpreter. The return value is the module object (which can be different if re-importing causes a different object to be placed in sys.modules).

When reload() is executed:

Python module’s code is recompiled and the module-level code re-executed, defining a new set of objects which are bound to names in the module’s dictionary by reusing the loader which originally loaded the module. The init function of extension modules is not called a second time.

As with all other objects in Python the old objects are only reclaimed after their reference counts drop to zero.

The names in the module namespace are updated to point to any new or changed objects.

Other references to the old objects (such as names external to the module) are not rebound to refer to the new objects and must be updated in each namespace where they occur if that is desired.

There are a number of other caveats:

When a module is reloaded, its dictionary (containing the module’s global variables) is retained. Redefinitions of names will override the old definitions, so this is generally not a problem. If the new version of a module does not define a name that was defined by the old version, the old definition remains. This feature can be used to the module’s advantage if it maintains a global table or cache of objects — with a try statement it can test for the table’s presence and skip its initialization if desired:

try:
    cache
except NameError:
    cache = {}

It is generally not very useful to reload built-in or dynamically loaded modules. Reloading sys, __main__, builtins and other key modules is not recommended. In many cases extension modules are not designed to be initialized more than once, and may fail in arbitrary ways when reloaded.

If a module imports objects from another module using from … import …, calling reload() for the other module does not redefine the objects imported from it — one way around this is to re-execute the from statement, another is to use import and qualified names (module.name) instead.

If a module instantiates instances of a class, reloading the module that defines the class does not affect the method definitions of the instances — they continue to use the old class definition. The same is true for derived classes.

버전 3.4에 추가.

버전 3.7에서 변경: ModuleNotFoundError is raised when the module being reloaded lacks a ModuleSpec.

importlib.abc – Abstract base classes related to import

Source code: Lib/importlib/abc.py [https://github.com/python/cpython/tree/3.7/Lib/importlib/abc.py]

The importlib.abc module contains all of the core abstract base classes used by import. Some subclasses of the core abstract base classes are also provided to help in implementing the core ABCs.

ABC hierarchy:

object
 +-- Finder (deprecated)
 |    +-- MetaPathFinder
 |    +-- PathEntryFinder
 +-- Loader
      +-- ResourceLoader --------+
      +-- InspectLoader          |
           +-- ExecutionLoader --+
                                 +-- FileLoader
                                 +-- SourceLoader

class importlib.abc.Finder

An abstract base class representing a finder.

버전 3.3부터 폐지: Use MetaPathFinder or PathEntryFinder instead.

abstractmethod find_module(fullname, path=None)

An abstract method for finding a loader for the specified module. Originally specified in PEP 302 [https://www.python.org/dev/peps/pep-0302], this method was meant for use in sys.meta_path and in the path-based import subsystem.

버전 3.4에서 변경: Returns None when called instead of raising NotImplementedError.

class importlib.abc.MetaPathFinder

An abstract base class representing a meta path finder. For compatibility, this is a subclass of Finder.

버전 3.3에 추가.

find_spec(fullname, path, target=None)

An abstract method for finding a spec for the specified module. If this is a top-level import, path will be None. Otherwise, this is a search for a subpackage or module and path will be the value of __path__ from the parent package. If a spec cannot be found, None is returned. When passed in, target is a module object that the finder may use to make a more educated guess about what spec to return. importlib.util.spec_from_loader() may be useful for implementing concrete MetaPathFinders.

버전 3.4에 추가.

find_module(fullname, path)

A legacy method for finding a loader for the specified module. If this is a top-level import, path will be None. Otherwise, this is a search for a subpackage or module and path will be the value of __path__ from the parent package. If a loader cannot be found, None is returned.

If find_spec() is defined, backwards-compatible functionality is provided.

버전 3.4에서 변경: Returns None when called instead of raising NotImplementedError. Can use find_spec() to provide functionality.

버전 3.4부터 폐지: Use find_spec() instead.

invalidate_caches()

An optional method which, when called, should invalidate any internal cache used by the finder. Used by importlib.invalidate_caches() when invalidating the caches of all finders on sys.meta_path.

버전 3.4에서 변경: Returns None when called instead of NotImplemented.

class importlib.abc.PathEntryFinder

An abstract base class representing a path entry finder. Though it bears some similarities to MetaPathFinder, PathEntryFinder is meant for use only within the path-based import subsystem provided by PathFinder. This ABC is a subclass of Finder for compatibility reasons only.

버전 3.3에 추가.

find_spec(fullname, target=None)

An abstract method for finding a spec for the specified module. The finder will search for the module only within the path entry to which it is assigned. If a spec cannot be found, None is returned. When passed in, target is a module object that the finder may use to make a more educated guess about what spec to return. importlib.util.spec_from_loader() may be useful for implementing concrete PathEntryFinders.

버전 3.4에 추가.

find_loader(fullname)

A legacy method for finding a loader for the specified module. Returns a 2-tuple of (loader, portion) where portion is a sequence of file system locations contributing to part of a namespace package. The loader may be None while specifying portion to signify the contribution of the file system locations to a namespace package. An empty list can be used for portion to signify the loader is not part of a namespace package. If loader is None and portion is the empty list then no loader or location for a namespace package were found (i.e. failure to find anything for the module).

If find_spec() is defined then backwards-compatible functionality is provided.

버전 3.4에서 변경: Returns (None, []) instead of raising NotImplementedError. Uses find_spec() when available to provide functionality.

버전 3.4부터 폐지: Use find_spec() instead.

find_module(fullname)

A concrete implementation of Finder.find_module() which is equivalent to self.find_loader(fullname)[0].

버전 3.4부터 폐지: Use find_spec() instead.

invalidate_caches()

An optional method which, when called, should invalidate any internal cache used by the finder. Used by PathFinder.invalidate_caches() when invalidating the caches of all cached finders.

class importlib.abc.Loader

An abstract base class for a loader. See PEP 302 [https://www.python.org/dev/peps/pep-0302] for the exact definition for a loader.

Loaders that wish to support resource reading should implement a get_resource_reader(fullname) method as specified by importlib.abc.ResourceReader.

버전 3.7에서 변경: Introduced the optional get_resource_reader() method.

create_module(spec)

A method that returns the module object to use when importing a module. This method may return None, indicating that default module creation semantics should take place.

버전 3.4에 추가.

버전 3.5에서 변경: Starting in Python 3.6, this method will not be optional when exec_module() is defined.

exec_module(module)

An abstract method that executes the module in its own namespace when a module is imported or reloaded. The module should already be initialized when exec_module() is called. When this method exists, create_module() must be defined.

버전 3.4에 추가.

버전 3.6에서 변경: create_module() must also be defined.

load_module(fullname)

A legacy method for loading a module. If the module cannot be loaded, ImportError is raised, otherwise the loaded module is returned.

If the requested module already exists in sys.modules, that module should be used and reloaded. Otherwise the loader should create a new module and insert it into sys.modules before any loading begins, to prevent recursion from the import. If the loader inserted a module and the load fails, it must be removed by the loader from sys.modules; modules already in sys.modules before the loader began execution should be left alone (see importlib.util.module_for_loader()).

The loader should set several attributes on the module. (Note that some of these attributes can change when a module is reloaded):

__name__

The name of the module.

__file__

The path to where the module data is stored (not set for built-in modules).

__cached__

The path to where a compiled version of the module is/should be stored (not set when the attribute would be inappropriate).

__path__

A list of strings specifying the search path within a package. This attribute is not set on modules.

__package__

The parent package for the module/package. If the module is top-level then it has a value of the empty string. The importlib.util.module_for_loader() decorator can handle the details for __package__.

__loader__

The loader used to load the module. The importlib.util.module_for_loader() decorator can handle the details for __package__.

When exec_module() is available then backwards-compatible functionality is provided.

버전 3.4에서 변경: Raise ImportError when called instead of NotImplementedError. Functionality provided when exec_module() is available.

버전 3.4부터 폐지: The recommended API for loading a module is exec_module() (and create_module()). Loaders should implement it instead of load_module(). The import machinery takes care of all the other responsibilities of load_module() when exec_module() is implemented.

module_repr(module)

A legacy method which when implemented calculates and returns the given module’s repr, as a string. The module type’s default repr() will use the result of this method as appropriate.

버전 3.3에 추가.

버전 3.4에서 변경: Made optional instead of an abstractmethod.

버전 3.4부터 폐지: The import machinery now takes care of this automatically.

class importlib.abc.ResourceReader

An abstract base class to provide the ability to read resources.

From the perspective of this ABC, a resource is a binary artifact that is shipped within a package. Typically this is something like a data file that lives next to the __init__.py file of the package. The purpose of this class is to help abstract out the accessing of such data files so that it does not matter if the package and its data file(s) are stored in a e.g. zip file versus on the file system.

For any of methods of this class, a resource argument is expected to be a path-like object which represents conceptually just a file name. This means that no subdirectory paths should be included in the resource argument. This is because the location of the package the reader is for, acts as the “directory”. Hence the metaphor for directories and file names is packages and resources, respectively. This is also why instances of this class are expected to directly correlate to a specific package (instead of potentially representing multiple packages or a module).

Loaders that wish to support resource reading are expected to provide a method called get_resource_reader(fullname) which returns an object implementing this ABC’s interface. If the module specified by fullname is not a package, this method should return None. An object compatible with this ABC should only be returned when the specified module is a package.

버전 3.7에 추가.

abstractmethod open_resource(resource)

Returns an opened, file-like object for binary reading of the resource.

If the resource cannot be found, FileNotFoundError is raised.

abstractmethod resource_path(resource)

Returns the file system path to the resource.

If the resource does not concretely exist on the file system, raise FileNotFoundError.

abstractmethod is_resource(name)

Returns True if the named name is considered a resource. FileNotFoundError is raised if name does not exist.

abstractmethod contents()

Returns an iterable of strings over the contents of the package. Do note that it is not required that all names returned by the iterator be actual resources, e.g. it is acceptable to return names for which is_resource() would be false.

Allowing non-resource names to be returned is to allow for situations where how a package and its resources are stored are known a priori and the non-resource names would be useful. For instance, returning subdirectory names is allowed so that when it is known that the package and resources are stored on the file system then those subdirectory names can be used directly.

The abstract method returns an iterable of no items.

class importlib.abc.ResourceLoader

An abstract base class for a loader which implements the optional PEP 302 [https://www.python.org/dev/peps/pep-0302] protocol for loading arbitrary resources from the storage back-end.

버전 3.7부터 폐지: This ABC is deprecated in favour of supporting resource loading through importlib.abc.ResourceReader.

abstractmethod get_data(path)

An abstract method to return the bytes for the data located at path. Loaders that have a file-like storage back-end that allows storing arbitrary data can implement this abstract method to give direct access to the data stored. OSError is to be raised if the path cannot be found. The path is expected to be constructed using a module’s __file__ attribute or an item from a package’s __path__.

버전 3.4에서 변경: Raises OSError instead of NotImplementedError.

class importlib.abc.InspectLoader

An abstract base class for a loader which implements the optional PEP 302 [https://www.python.org/dev/peps/pep-0302] protocol for loaders that inspect modules.

get_code(fullname)

Return the code object for a module, or None if the module does not have a code object (as would be the case, for example, for a built-in module). Raise an ImportError if loader cannot find the requested module.

참고

While the method has a default implementation, it is suggested that it be overridden if possible for performance.

버전 3.4에서 변경: No longer abstract and a concrete implementation is provided.

abstractmethod get_source(fullname)

An abstract method to return the source of a module. It is returned as a text string using universal newlines, translating all recognized line separators into '\n' characters. Returns None if no source is available (e.g. a built-in module). Raises ImportError if the loader cannot find the module specified.

버전 3.4에서 변경: Raises ImportError instead of NotImplementedError.

is_package(fullname)

An abstract method to return a true value if the module is a package, a false value otherwise. ImportError is raised if the loader cannot find the module.

버전 3.4에서 변경: Raises ImportError instead of NotImplementedError.

static source_to_code(data, path='<string>')

Create a code object from Python source.

The data argument can be whatever the compile() function supports (i.e. string or bytes). The path argument should be the “path” to where the source code originated from, which can be an abstract concept (e.g. location in a zip file).

With the subsequent code object one can execute it in a module by running exec(code, module.__dict__).

버전 3.4에 추가.

버전 3.5에서 변경: Made the method static.

exec_module(module)

Implementation of Loader.exec_module().

버전 3.4에 추가.

load_module(fullname)

Implementation of Loader.load_module().

버전 3.4부터 폐지: use exec_module() instead.

class importlib.abc.ExecutionLoader

An abstract base class which inherits from InspectLoader that, when implemented, helps a module to be executed as a script. The ABC represents an optional PEP 302 [https://www.python.org/dev/peps/pep-0302] protocol.

abstractmethod get_filename(fullname)

An abstract method that is to return the value of __file__ for the specified module. If no path is available, ImportError is raised.

If source code is available, then the method should return the path to the source file, regardless of whether a bytecode was used to load the module.

버전 3.4에서 변경: Raises ImportError instead of NotImplementedError.

class importlib.abc.FileLoader(fullname, path)

An abstract base class which inherits from ResourceLoader and ExecutionLoader, providing concrete implementations of ResourceLoader.get_data() and ExecutionLoader.get_filename().

The fullname argument is a fully resolved name of the module the loader is to handle. The path argument is the path to the file for the module.

버전 3.3에 추가.

name

The name of the module the loader can handle.

path

Path to the file of the module.

load_module(fullname)

Calls super’s load_module().

버전 3.4부터 폐지: Use Loader.exec_module() instead.

abstractmethod get_filename(fullname)

Returns path.

abstractmethod get_data(path)

Reads path as a binary file and returns the bytes from it.

class importlib.abc.SourceLoader

An abstract base class for implementing source (and optionally bytecode) file loading. The class inherits from both ResourceLoader and ExecutionLoader, requiring the implementation of:

ResourceLoader.get_data()

ExecutionLoader.get_filename()

Should only return the path to the source file; sourceless loading is not supported.

The abstract methods defined by this class are to add optional bytecode file support. Not implementing these optional methods (or causing them to raise NotImplementedError) causes the loader to only work with source code. Implementing the methods allows the loader to work with source and bytecode files; it does not allow for sourceless loading where only bytecode is provided. Bytecode files are an optimization to speed up loading by removing the parsing step of Python’s compiler, and so no bytecode-specific API is exposed.

path_stats(path)

Optional abstract method which returns a dict containing metadata about the specified path. Supported dictionary keys are:

'mtime' (mandatory): an integer or floating-point number representing the modification time of the source code;

'size' (optional): the size in bytes of the source code.

Any other keys in the dictionary are ignored, to allow for future extensions. If the path cannot be handled, OSError is raised.

버전 3.3에 추가.

버전 3.4에서 변경: Raise OSError instead of NotImplementedError.

path_mtime(path)

Optional abstract method which returns the modification time for the specified path.

버전 3.3부터 폐지: This method is deprecated in favour of path_stats(). You don’t have to implement it, but it is still available for compatibility purposes. Raise OSError if the path cannot be handled.

버전 3.4에서 변경: Raise OSError instead of NotImplementedError.

set_data(path, data)

Optional abstract method which writes the specified bytes to a file path. Any intermediate directories which do not exist are to be created automatically.

When writing to the path fails because the path is read-only (errno.EACCES/PermissionError), do not propagate the exception.

버전 3.4에서 변경: No longer raises NotImplementedError when called.

get_code(fullname)

Concrete implementation of InspectLoader.get_code().

exec_module(module)

Concrete implementation of Loader.exec_module().

버전 3.4에 추가.

load_module(fullname)

Concrete implementation of Loader.load_module().

버전 3.4부터 폐지: Use exec_module() instead.

get_source(fullname)

Concrete implementation of InspectLoader.get_source().

is_package(fullname)

Concrete implementation of InspectLoader.is_package(). A module is determined to be a package if its file path (as provided by ExecutionLoader.get_filename()) is a file named __init__ when the file extension is removed and the module name itself does not end in __init__.

importlib.resources – Resources

Source code: Lib/importlib/resources.py [https://github.com/python/cpython/tree/3.7/Lib/importlib/resources.py]

버전 3.7에 추가.

This module leverages Python’s import system to provide access to resources within packages. If you can import a package, you can access resources within that package. Resources can be opened or read, in either binary or text mode.

Resources are roughly akin to files inside directories, though it’s important to keep in mind that this is just a metaphor. Resources and packages do not have to exist as physical files and directories on the file system.

참고

This module provides functionality similar to pkg_resources [https://setuptools.readthedocs.io/en/latest/pkg_resources.html] Basic Resource Access [http://setuptools.readthedocs.io/en/latest/pkg_resources.html#basic-resource-access] without the performance overhead of that package. This makes reading resources included in packages easier, with more stable and consistent semantics.

The standalone backport of this module provides more information on using importlib.resources [http://importlib-resources.readthedocs.io/en/latest/using.html] and migrating from pkg_resources to importlib.resources [http://importlib-resources.readthedocs.io/en/latest/migration.html].

Loaders that wish to support resource reading should implement a get_resource_reader(fullname) method as specified by importlib.abc.ResourceReader.

The following types are defined.

importlib.resources.Package

The Package type is defined as Union[str, ModuleType]. This means that where the function describes accepting a Package, you can pass in either a string or a module. Module objects must have a resolvable __spec__.submodule_search_locations that is not None.

importlib.resources.Resource

This type describes the resource names passed into the various functions in this package. This is defined as Union[str, os.PathLike].

The following functions are available.

importlib.resources.open_binary(package, resource)

Open for binary reading the resource within package.

package is either a name or a module object which conforms to the Package requirements. resource is the name of the resource to open within package; it may not contain path separators and it may not have sub-resources (i.e. it cannot be a directory). This function returns a typing.BinaryIO instance, a binary I/O stream open for reading.

importlib.resources.open_text(package, resource, encoding='utf-8', errors='strict')

Open for text reading the resource within package. By default, the resource is opened for reading as UTF-8.

package is either a name or a module object which conforms to the Package requirements. resource is the name of the resource to open within package; it may not contain path separators and it may not have sub-resources (i.e. it cannot be a directory). encoding and errors have the same meaning as with built-in open().

This function returns a typing.TextIO instance, a text I/O stream open for reading.

importlib.resources.read_binary(package, resource)

Read and return the contents of the resource within package as bytes.

package is either a name or a module object which conforms to the Package requirements. resource is the name of the resource to open within package; it may not contain path separators and it may not have sub-resources (i.e. it cannot be a directory). This function returns the contents of the resource as bytes.

importlib.resources.read_text(package, resource, encoding='utf-8', errors='strict')

Read and return the contents of resource within package as a str. By default, the contents are read as strict UTF-8.

package is either a name or a module object which conforms to the Package requirements. resource is the name of the resource to open within package; it may not contain path separators and it may not have sub-resources (i.e. it cannot be a directory). encoding and errors have the same meaning as with built-in open(). This function returns the contents of the resource as str.

importlib.resources.path(package, resource)

Return the path to the resource as an actual file system path. This function returns a context manager for use in a with statement. The context manager provides a pathlib.Path object.

Exiting the context manager cleans up any temporary file created when the resource needs to be extracted from e.g. a zip file.

package is either a name or a module object which conforms to the Package requirements. resource is the name of the resource to open within package; it may not contain path separators and it may not have sub-resources (i.e. it cannot be a directory).

importlib.resources.is_resource(package, name)

Return True if there is a resource named name in the package, otherwise False. Remember that directories are not resources! package is either a name or a module object which conforms to the Package requirements.

importlib.resources.contents(package)

Return an iterable over the named items within the package. The iterable returns str resources (e.g. files) and non-resources (e.g. directories). The iterable does not recurse into subdirectories.

package is either a name or a module object which conforms to the Package requirements.

importlib.machinery – Importers and path hooks

Source code: Lib/importlib/machinery.py [https://github.com/python/cpython/tree/3.7/Lib/importlib/machinery.py]

This module contains the various objects that help import find and load modules.

importlib.machinery.SOURCE_SUFFIXES

A list of strings representing the recognized file suffixes for source modules.

버전 3.3에 추가.

importlib.machinery.DEBUG_BYTECODE_SUFFIXES

A list of strings representing the file suffixes for non-optimized bytecode modules.

버전 3.3에 추가.

버전 3.5부터 폐지: Use BYTECODE_SUFFIXES instead.

importlib.machinery.OPTIMIZED_BYTECODE_SUFFIXES

A list of strings representing the file suffixes for optimized bytecode modules.

버전 3.3에 추가.

버전 3.5부터 폐지: Use BYTECODE_SUFFIXES instead.

importlib.machinery.BYTECODE_SUFFIXES

A list of strings representing the recognized file suffixes for bytecode modules (including the leading dot).

버전 3.3에 추가.

버전 3.5에서 변경: The value is no longer dependent on __debug__.

importlib.machinery.EXTENSION_SUFFIXES

A list of strings representing the recognized file suffixes for extension modules.

버전 3.3에 추가.

importlib.machinery.all_suffixes()

Returns a combined list of strings representing all file suffixes for modules recognized by the standard import machinery. This is a helper for code which simply needs to know if a filesystem path potentially refers to a module without needing any details on the kind of module (for example, inspect.getmodulename()).

버전 3.3에 추가.

class importlib.machinery.BuiltinImporter

An importer for built-in modules. All known built-in modules are listed in sys.builtin_module_names. This class implements the importlib.abc.MetaPathFinder and importlib.abc.InspectLoader ABCs.

Only class methods are defined by this class to alleviate the need for instantiation.

버전 3.5에서 변경: As part of PEP 489 [https://www.python.org/dev/peps/pep-0489], the builtin importer now implements Loader.create_module() and Loader.exec_module()

class importlib.machinery.FrozenImporter

An importer for frozen modules. This class implements the importlib.abc.MetaPathFinder and importlib.abc.InspectLoader ABCs.

Only class methods are defined by this class to alleviate the need for instantiation.

버전 3.4에서 변경: Gained create_module() and exec_module() methods.

class importlib.machinery.WindowsRegistryFinder

Finder for modules declared in the Windows registry. This class implements the importlib.abc.MetaPathFinder ABC.

Only class methods are defined by this class to alleviate the need for instantiation.

버전 3.3에 추가.

버전 3.6부터 폐지: Use site configuration instead. Future versions of Python may not enable this finder by default.

class importlib.machinery.PathFinder

A Finder for sys.path and package __path__ attributes. This class implements the importlib.abc.MetaPathFinder ABC.

Only class methods are defined by this class to alleviate the need for instantiation.

classmethod find_spec(fullname, path=None, target=None)

Class method that attempts to find a spec for the module specified by fullname on sys.path or, if defined, on path. For each path entry that is searched, sys.path_importer_cache is checked. If a non-false object is found then it is used as the path entry finder to look for the module being searched for. If no entry is found in sys.path_importer_cache, then sys.path_hooks is searched for a finder for the path entry and, if found, is stored in sys.path_importer_cache along with being queried about the module. If no finder is ever found then None is both stored in the cache and returned.

버전 3.4에 추가.

버전 3.5에서 변경: If the current working directory – represented by an empty string – is no longer valid then None is returned but no value is cached in sys.path_importer_cache.

classmethod find_module(fullname, path=None)

A legacy wrapper around find_spec().

버전 3.4부터 폐지: Use find_spec() instead.

classmethod invalidate_caches()

Calls importlib.abc.PathEntryFinder.invalidate_caches() on all finders stored in sys.path_importer_cache that define the method. Otherwise entries in sys.path_importer_cache set to None are deleted.

버전 3.7에서 변경: Entries of None in sys.path_importer_cache are deleted.

버전 3.4에서 변경: Calls objects in sys.path_hooks with the current working directory for '' (i.e. the empty string).

class importlib.machinery.FileFinder(path, *loader_details)

A concrete implementation of importlib.abc.PathEntryFinder which caches results from the file system.

The path argument is the directory for which the finder is in charge of searching.

The loader_details argument is a variable number of 2-item tuples each containing a loader and a sequence of file suffixes the loader recognizes. The loaders are expected to be callables which accept two arguments of the module’s name and the path to the file found.

The finder will cache the directory contents as necessary, making stat calls for each module search to verify the cache is not outdated. Because cache staleness relies upon the granularity of the operating system’s state information of the file system, there is a potential race condition of searching for a module, creating a new file, and then searching for the module the new file represents. If the operations happen fast enough to fit within the granularity of stat calls, then the module search will fail. To prevent this from happening, when you create a module dynamically, make sure to call importlib.invalidate_caches().

버전 3.3에 추가.

path

The path the finder will search in.

find_spec(fullname, target=None)

Attempt to find the spec to handle fullname within path.

버전 3.4에 추가.

find_loader(fullname)

Attempt to find the loader to handle fullname within path.

invalidate_caches()

Clear out the internal cache.

classmethod path_hook(*loader_details)

A class method which returns a closure for use on sys.path_hooks. An instance of FileFinder is returned by the closure using the path argument given to the closure directly and loader_details indirectly.

If the argument to the closure is not an existing directory, ImportError is raised.

class importlib.machinery.SourceFileLoader(fullname, path)

A concrete implementation of importlib.abc.SourceLoader by subclassing importlib.abc.FileLoader and providing some concrete implementations of other methods.

버전 3.3에 추가.

name

The name of the module that this loader will handle.

path

The path to the source file.

is_package(fullname)

Return True if path appears to be for a package.

path_stats(path)

Concrete implementation of importlib.abc.SourceLoader.path_stats().

set_data(path, data)

Concrete implementation of importlib.abc.SourceLoader.set_data().

load_module(name=None)

Concrete implementation of importlib.abc.Loader.load_module() where specifying the name of the module to load is optional.

버전 3.6부터 폐지: Use importlib.abc.Loader.exec_module() instead.

class importlib.machinery.SourcelessFileLoader(fullname, path)

A concrete implementation of importlib.abc.FileLoader which can import bytecode files (i.e. no source code files exist).

Please note that direct use of bytecode files (and thus not source code files) inhibits your modules from being usable by all Python implementations or new versions of Python which change the bytecode format.

버전 3.3에 추가.

name

The name of the module the loader will handle.

path

The path to the bytecode file.

is_package(fullname)

Determines if the module is a package based on path.

get_code(fullname)

Returns the code object for name created from path.

get_source(fullname)

Returns None as bytecode files have no source when this loader is used.

load_module(name=None)

Concrete implementation of importlib.abc.Loader.load_module() where specifying the name of the module to load is optional.

버전 3.6부터 폐지: Use importlib.abc.Loader.exec_module() instead.

class importlib.machinery.ExtensionFileLoader(fullname, path)

A concrete implementation of importlib.abc.ExecutionLoader for extension modules.

The fullname argument specifies the name of the module the loader is to support. The path argument is the path to the extension module’s file.

버전 3.3에 추가.

name

Name of the module the loader supports.

path

Path to the extension module.

create_module(spec)

Creates the module object from the given specification in accordance with PEP 489 [https://www.python.org/dev/peps/pep-0489].

버전 3.5에 추가.

exec_module(module)

Initializes the given module object in accordance with PEP 489 [https://www.python.org/dev/peps/pep-0489].

버전 3.5에 추가.

is_package(fullname)

Returns True if the file path points to a package’s __init__ module based on EXTENSION_SUFFIXES.

get_code(fullname)

Returns None as extension modules lack a code object.

get_source(fullname)

Returns None as extension modules do not have source code.

get_filename(fullname)

Returns path.

버전 3.4에 추가.

class importlib.machinery.ModuleSpec(name, loader, *, origin=None, loader_state=None, is_package=None)

A specification for a module’s import-system-related state. This is typically exposed as the module’s __spec__ attribute. In the descriptions below, the names in parentheses give the corresponding attribute available directly on the module object. E.g. module.__spec__.origin == module.__file__. Note however that while the values are usually equivalent, they can differ since there is no synchronization between the two objects. Thus it is possible to update the module’s __path__ at runtime, and this will not be automatically reflected in __spec__.submodule_search_locations.

버전 3.4에 추가.

name

(__name__)

A string for the fully-qualified name of the module.

loader

(__loader__)

The loader to use for loading. For namespace packages this should be set to None.

origin

(__file__)

Name of the place from which the module is loaded, e.g. “builtin” for built-in modules and the filename for modules loaded from source. Normally “origin” should be set, but it may be None (the default) which indicates it is unspecified (e.g. for namespace packages).

submodule_search_locations

(__path__)

List of strings for where to find submodules, if a package (None otherwise).

loader_state

Container of extra module-specific data for use during loading (or None).

cached

(__cached__)

String for where the compiled module should be stored (or None).

parent

(__package__)

(Read-only) Fully-qualified name of the package to which the module belongs as a submodule (or None).

has_location

Boolean indicating whether or not the module’s “origin” attribute refers to a loadable location.

importlib.util – Utility code for importers

Source code: Lib/importlib/util.py [https://github.com/python/cpython/tree/3.7/Lib/importlib/util.py]

This module contains the various objects that help in the construction of an importer.

importlib.util.MAGIC_NUMBER

The bytes which represent the bytecode version number. If you need help with loading/writing bytecode then consider importlib.abc.SourceLoader.

버전 3.4에 추가.

importlib.util.cache_from_source(path, debug_override=None, *, optimization=None)

Return the PEP 3147 [https://www.python.org/dev/peps/pep-3147]/PEP 488 [https://www.python.org/dev/peps/pep-0488] path to the byte-compiled file associated with the source path. For example, if path is /foo/bar/baz.py the return value would be /foo/bar/__pycache__/baz.cpython-32.pyc for Python 3.2. The cpython-32 string comes from the current magic tag (see get_tag(); if sys.implementation.cache_tag is not defined then NotImplementedError will be raised).

The optimization parameter is used to specify the optimization level of the bytecode file. An empty string represents no optimization, so /foo/bar/baz.py with an optimization of '' will result in a bytecode path of /foo/bar/__pycache__/baz.cpython-32.pyc. None causes the interpter’s optimization level to be used. Any other value’s string representation being used, so /foo/bar/baz.py with an optimization of 2 will lead to the bytecode path of /foo/bar/__pycache__/baz.cpython-32.opt-2.pyc. The string representation of optimization can only be alphanumeric, else ValueError is raised.

The debug_override parameter is deprecated and can be used to override the system’s value for __debug__. A True value is the equivalent of setting optimization to the empty string. A False value is the same as setting optimization to 1. If both debug_override an optimization are not None then TypeError is raised.

버전 3.4에 추가.

버전 3.5에서 변경: The optimization parameter was added and the debug_override parameter was deprecated.

버전 3.6에서 변경: Accepts a path-like object.

importlib.util.source_from_cache(path)

Given the path to a PEP 3147 [https://www.python.org/dev/peps/pep-3147] file name, return the associated source code file path. For example, if path is /foo/bar/__pycache__/baz.cpython-32.pyc the returned path would be /foo/bar/baz.py. path need not exist, however if it does not conform to PEP 3147 [https://www.python.org/dev/peps/pep-3147] or PEP 488 [https://www.python.org/dev/peps/pep-0488] format, a ValueError is raised. If sys.implementation.cache_tag is not defined, NotImplementedError is raised.

버전 3.4에 추가.

버전 3.6에서 변경: Accepts a path-like object.

importlib.util.decode_source(source_bytes)

Decode the given bytes representing source code and return it as a string with universal newlines (as required by importlib.abc.InspectLoader.get_source()).

버전 3.4에 추가.

importlib.util.resolve_name(name, package)

Resolve a relative module name to an absolute one.

If name has no leading dots, then name is simply returned. This allows for usage such as importlib.util.resolve_name('sys', __package__) without doing a check to see if the package argument is needed.

ValueError is raised if name is a relative module name but package is a false value (e.g. None or the empty string). ValueError is also raised a relative name would escape its containing package (e.g. requesting ..bacon from within the spam package).

버전 3.3에 추가.

importlib.util.find_spec(name, package=None)

Find the spec for a module, optionally relative to the specified package name. If the module is in sys.modules, then sys.modules[name].__spec__ is returned (unless the spec would be None or is not set, in which case ValueError is raised). Otherwise a search using sys.meta_path is done. None is returned if no spec is found.

If name is for a submodule (contains a dot), the parent module is automatically imported.

name and package work the same as for import_module().

버전 3.4에 추가.

버전 3.7에서 변경: Raises ModuleNotFoundError instead of AttributeError if package is in fact not a package (i.e. lacks a __path__ attribute).

importlib.util.module_from_spec(spec)

Create a new module based on spec and spec.loader.create_module.

If spec.loader.create_module does not return None, then any pre-existing attributes will not be reset. Also, no AttributeError will be raised if triggered while accessing spec or setting an attribute on the module.

This function is preferred over using types.ModuleType to create a new module as spec is used to set as many import-controlled attributes on the module as possible.

버전 3.5에 추가.

@importlib.util.module_for_loader

A decorator for importlib.abc.Loader.load_module() to handle selecting the proper module object to load with. The decorated method is expected to have a call signature taking two positional arguments (e.g. load_module(self, module)) for which the second argument will be the module object to be used by the loader. Note that the decorator will not work on static methods because of the assumption of two arguments.

The decorated method will take in the name of the module to be loaded as expected for a loader. If the module is not found in sys.modules then a new one is constructed. Regardless of where the module came from, __loader__ set to self and __package__ is set based on what importlib.abc.InspectLoader.is_package() returns (if available). These attributes are set unconditionally to support reloading.

If an exception is raised by the decorated method and a module was added to sys.modules, then the module will be removed to prevent a partially initialized module from being in left in sys.modules. If the module was already in sys.modules then it is left alone.

버전 3.3에서 변경: __loader__ and __package__ are automatically set (when possible).

버전 3.4에서 변경: Set __name__, __loader__ __package__ unconditionally to support reloading.

버전 3.4부터 폐지: The import machinery now directly performs all the functionality provided by this function.

@importlib.util.set_loader

A decorator for importlib.abc.Loader.load_module() to set the __loader__ attribute on the returned module. If the attribute is already set the decorator does nothing. It is assumed that the first positional argument to the wrapped method (i.e. self) is what __loader__ should be set to.

버전 3.4에서 변경: Set __loader__ if set to None, as if the attribute does not exist.

버전 3.4부터 폐지: The import machinery takes care of this automatically.

@importlib.util.set_package

A decorator for importlib.abc.Loader.load_module() to set the __package__ attribute on the returned module. If __package__ is set and has a value other than None it will not be changed.

버전 3.4부터 폐지: The import machinery takes care of this automatically.

importlib.util.spec_from_loader(name, loader, *, origin=None, is_package=None)

A factory function for creating a ModuleSpec instance based on a loader. The parameters have the same meaning as they do for ModuleSpec. The function uses available loader APIs, such as InspectLoader.is_package(), to fill in any missing information on the spec.

버전 3.4에 추가.

importlib.util.spec_from_file_location(name, location, *, loader=None, submodule_search_locations=None)

A factory function for creating a ModuleSpec instance based on the path to a file. Missing information will be filled in on the spec by making use of loader APIs and by the implication that the module will be file-based.

버전 3.4에 추가.

버전 3.6에서 변경: Accepts a path-like object.

importlib.util.source_hash(source_bytes)

Return the hash of source_bytes as bytes. A hash-based .pyc file embeds the source_hash() of the corresponding source file’s contents in its header.

버전 3.7에 추가.

class importlib.util.LazyLoader(loader)

A class which postpones the execution of the loader of a module until the module has an attribute accessed.

This class only works with loaders that define exec_module() as control over what module type is used for the module is required. For those same reasons, the loader’s create_module() method must return None or a type for which its __class__ attribute can be mutated along with not using slots. Finally, modules which substitute the object placed into sys.modules will not work as there is no way to properly replace the module references throughout the interpreter safely; ValueError is raised if such a substitution is detected.

참고

For projects where startup time is critical, this class allows for potentially minimizing the cost of loading a module if it is never used. For projects where startup time is not essential then use of this class is heavily discouraged due to error messages created during loading being postponed and thus occurring out of context.

버전 3.5에 추가.

버전 3.6에서 변경: Began calling create_module(), removing the compatibility warning for importlib.machinery.BuiltinImporter and importlib.machinery.ExtensionFileLoader.

classmethod factory(loader)

A static method which returns a callable that creates a lazy loader. This is meant to be used in situations where the loader is passed by class instead of by instance.

suffixes = importlib.machinery.SOURCE_SUFFIXES
loader = importlib.machinery.SourceFileLoader
lazy_loader = importlib.util.LazyLoader.factory(loader)
finder = importlib.machinery.FileFinder(path, (lazy_loader, suffixes))

Examples

Importing programmatically

To programmatically import a module, use importlib.import_module().

import importlib

itertools = importlib.import_module('itertools')

Checking if a module can be imported

If you need to find out if a module can be imported without actually doing the import, then you should use importlib.util.find_spec().

import importlib.util
import sys

# For illustrative purposes.
name = 'itertools'

spec = importlib.util.find_spec(name)
if spec is None:
    print("can't find the itertools module")
else:
    # If you chose to perform the actual import ...
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    # Adding the module to sys.modules is optional.
    sys.modules[name] = module

Importing a source file directly

To import a Python source file directly, use the following recipe (Python 3.5 and newer only):

import importlib.util
import sys

# For illustrative purposes.
import tokenize
file_path = tokenize.__file__
module_name = tokenize.__name__

spec = importlib.util.spec_from_file_location(module_name, file_path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
# Optional; only necessary if you want to be able to import the module
# by name later.
sys.modules[module_name] = module

Setting up an importer

For deep customizations of import, you typically want to implement an importer. This means managing both the finder and loader side of things. For finders there are two flavours to choose from depending on your needs: a meta path finder or a path entry finder. The former is what you would put on sys.meta_path while the latter is what you create using a path entry hook on sys.path_hooks which works with sys.path entries to potentially create a finder. This example will show you how to register your own importers so that import will use them (for creating an importer for yourself, read the documentation for the appropriate classes defined within this package):

import importlib.machinery
import sys

# For illustrative purposes only.
SpamMetaPathFinder = importlib.machinery.PathFinder
SpamPathEntryFinder = importlib.machinery.FileFinder
loader_details = (importlib.machinery.SourceFileLoader,
                  importlib.machinery.SOURCE_SUFFIXES)

# Setting up a meta path finder.
# Make sure to put the finder in the proper location in the list in terms of
# priority.
sys.meta_path.append(SpamMetaPathFinder)

# Setting up a path entry finder.
# Make sure to put the path hook in the proper location in the list in terms
# of priority.
sys.path_hooks.append(SpamPathEntryFinder.path_hook(loader_details))

Approximating importlib.import_module()

Import itself is implemented in Python code, making it possible to expose most of the import machinery through importlib. The following helps illustrate the various APIs that importlib exposes by providing an approximate implementation of importlib.import_module() (Python 3.4 and newer for the importlib usage, Python 3.6 and newer for other parts of the code).

import importlib.util
import sys

def import_module(name, package=None):
    """An approximate implementation of import."""
    absolute_name = importlib.util.resolve_name(name, package)
    try:
        return sys.modules[absolute_name]
    except KeyError:
        pass

    path = None
    if '.' in absolute_name:
        parent_name, _, child_name = absolute_name.rpartition('.')
        parent_module = import_module(parent_name)
        path = parent_module.__spec__.submodule_search_locations
    for finder in sys.meta_path:
        spec = finder.find_spec(absolute_name, path)
        if spec is not None:
            break
    else:
        msg = f'No module named {absolute_name!r}'
        raise ModuleNotFoundError(msg, name=absolute_name)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    sys.modules[absolute_name] = module
    if path is not None:
        setattr(parent_module, child_name, module)
    return module

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

모듈 임포트 하기 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

|

파이썬 언어 서비스

파이썬은 파이썬 언어로 작업하는 데 도움이 되는 여러 모듈을 제공합니다. 이 모듈들은 토큰화, 구문 분석, 문법 분석, 바이트 코드 역 어셈블리 및 기타 다양한 기능을 지원합니다.

이 모듈들은 다음과 같습니다:

parser — Access Python parse trees

Creating ST Objects

Converting ST Objects

Queries on ST Objects

Exceptions and Error Handling

ST Objects

Example: Emulation of compile()

ast — Abstract Syntax Trees

Node classes

Abstract Grammar

ast Helpers

symtable — 컴파일러 심볼 테이블 액세스

심볼 테이블 생성하기

심볼 테이블 검사하기

symbol — 파이썬 구문 분석 트리에 사용되는 상수

token — 파이썬 구문 분석 트리에 사용되는 상수

keyword — 파이썬 키워드 검사

tokenize — 파이썬 소스를 위한 토크나이저

입력 토큰화하기

명령 줄 사용법

예제

tabnanny — 모호한 들여쓰기 감지

pyclbr — Python module browser support

Function 객체

Class 객체

py_compile — 파이썬 소스 파일 컴파일

compileall — 파이썬 라이브러리 바이트 컴파일하기

명령 줄 사용

공용 함수

dis — Disassembler for Python bytecode

Bytecode analysis

Analysis functions

Python Bytecode Instructions

Opcode collections

pickletools — 피클 개발자를 위한 도구

명령 줄 사용법

명령 줄 옵션

프로그래밍 인터페이스

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

파이썬 언어 서비스 »

|

parser — Access Python parse trees

The parser module provides an interface to Python’s internal parser and byte-code compiler. The primary purpose for this interface is to allow Python code to edit the parse tree of a Python expression and create executable code from this. This is better than trying to parse and modify an arbitrary Python code fragment as a string because parsing is performed in a manner identical to the code forming the application. It is also faster.

참고

From Python 2.5 onward, it’s much more convenient to cut in at the Abstract Syntax Tree (AST) generation and compilation stage, using the ast module.

There are a few things to note about this module which are important to making use of the data structures created. This is not a tutorial on editing the parse trees for Python code, but some examples of using the parser module are presented.

Most importantly, a good understanding of the Python grammar processed by the internal parser is required. For full information on the language syntax, refer to 파이썬 언어 레퍼런스. The parser itself is created from a grammar specification defined in the file Grammar/Grammar in the standard Python distribution. The parse trees stored in the ST objects created by this module are the actual output from the internal parser when created by the expr() or suite() functions, described below. The ST objects created by sequence2st() faithfully simulate those structures. Be aware that the values of the sequences which are considered “correct” will vary from one version of Python to another as the formal grammar for the language is revised. However, transporting code from one Python version to another as source text will always allow correct parse trees to be created in the target version, with the only restriction being that migrating to an older version of the interpreter will not support more recent language constructs. The parse trees are not typically compatible from one version to another, though source code has usually been forward-compatible within a major release series.

Each element of the sequences returned by st2list() or st2tuple() has a simple form. Sequences representing non-terminal elements in the grammar always have a length greater than one. The first element is an integer which identifies a production in the grammar. These integers are given symbolic names in the C header file Include/graminit.h and the Python module symbol. Each additional element of the sequence represents a component of the production as recognized in the input string: these are always sequences which have the same form as the parent. An important aspect of this structure which should be noted is that keywords used to identify the parent node type, such as the keyword if in an if_stmt, are included in the node tree without any special treatment. For example, the if keyword is represented by the tuple (1, 'if'), where 1 is the numeric value associated with all NAME tokens, including variable and function names defined by the user. In an alternate form returned when line number information is requested, the same token might be represented as (1, 'if', 12), where the 12 represents the line number at which the terminal symbol was found.

Terminal elements are represented in much the same way, but without any child elements and the addition of the source text which was identified. The example of the if keyword above is representative. The various types of terminal symbols are defined in the C header file Include/token.h and the Python module token.

The ST objects are not required to support the functionality of this module, but are provided for three purposes: to allow an application to amortize the cost of processing complex parse trees, to provide a parse tree representation which conserves memory space when compared to the Python list or tuple representation, and to ease the creation of additional modules in C which manipulate parse trees. A simple “wrapper” class may be created in Python to hide the use of ST objects.

The parser module defines functions for a few distinct purposes. The most important purposes are to create ST objects and to convert ST objects to other representations such as parse trees and compiled code objects, but there are also functions which serve to query the type of parse tree represented by an ST object.

더 보기

Module symbol

Useful constants representing internal nodes of the parse tree.

Module token

Useful constants representing leaf nodes of the parse tree and functions for testing node values.

Creating ST Objects

ST objects may be created from source code or from a parse tree. When creating an ST object from source, different functions are used to create the 'eval' and 'exec' forms.

parser.expr(source)

The expr() function parses the parameter source as if it were an input to compile(source, 'file.py', 'eval'). If the parse succeeds, an ST object is created to hold the internal parse tree representation, otherwise an appropriate exception is raised.

parser.suite(source)

The suite() function parses the parameter source as if it were an input to compile(source, 'file.py', 'exec'). If the parse succeeds, an ST object is created to hold the internal parse tree representation, otherwise an appropriate exception is raised.

parser.sequence2st(sequence)

This function accepts a parse tree represented as a sequence and builds an internal representation if possible. If it can validate that the tree conforms to the Python grammar and all nodes are valid node types in the host version of Python, an ST object is created from the internal representation and returned to the called. If there is a problem creating the internal representation, or if the tree cannot be validated, a ParserError exception is raised. An ST object created this way should not be assumed to compile correctly; normal exceptions raised by compilation may still be initiated when the ST object is passed to compilest(). This may indicate problems not related to syntax (such as a MemoryError exception), but may also be due to constructs such as the result of parsing del f(0), which escapes the Python parser but is checked by the bytecode compiler.

Sequences representing terminal tokens may be represented as either two-element lists of the form (1, 'name') or as three-element lists of the form (1, 'name', 56). If the third element is present, it is assumed to be a valid line number. The line number may be specified for any subset of the terminal symbols in the input tree.

parser.tuple2st(sequence)

This is the same function as sequence2st(). This entry point is maintained for backward compatibility.

Converting ST Objects

ST objects, regardless of the input used to create them, may be converted to parse trees represented as list- or tuple- trees, or may be compiled into executable code objects. Parse trees may be extracted with or without line numbering information.

parser.st2list(st, line_info=False, col_info=False)

This function accepts an ST object from the caller in st and returns a Python list representing the equivalent parse tree. The resulting list representation can be used for inspection or the creation of a new parse tree in list form. This function does not fail so long as memory is available to build the list representation. If the parse tree will only be used for inspection, st2tuple() should be used instead to reduce memory consumption and fragmentation. When the list representation is required, this function is significantly faster than retrieving a tuple representation and converting that to nested lists.

If line_info is true, line number information will be included for all terminal tokens as a third element of the list representing the token. Note that the line number provided specifies the line on which the token ends. This information is omitted if the flag is false or omitted.

parser.st2tuple(st, line_info=False, col_info=False)

This function accepts an ST object from the caller in st and returns a Python tuple representing the equivalent parse tree. Other than returning a tuple instead of a list, this function is identical to st2list().

If line_info is true, line number information will be included for all terminal tokens as a third element of the list representing the token. This information is omitted if the flag is false or omitted.

parser.compilest(st, filename='<syntax-tree>')

The Python byte compiler can be invoked on an ST object to produce code objects which can be used as part of a call to the built-in exec() or eval() functions. This function provides the interface to the compiler, passing the internal parse tree from st to the parser, using the source file name specified by the filename parameter. The default value supplied for filename indicates that the source was an ST object.

Compiling an ST object may result in exceptions related to compilation; an example would be a SyntaxError caused by the parse tree for del f(0): this statement is considered legal within the formal grammar for Python but is not a legal language construct. The SyntaxError raised for this condition is actually generated by the Python byte-compiler normally, which is why it can be raised at this point by the parser module. Most causes of compilation failure can be diagnosed programmatically by inspection of the parse tree.

Queries on ST Objects

Two functions are provided which allow an application to determine if an ST was created as an expression or a suite. Neither of these functions can be used to determine if an ST was created from source code via expr() or suite() or from a parse tree via sequence2st().

parser.isexpr(st)

When st represents an 'eval' form, this function returns True, otherwise it returns False. This is useful, since code objects normally cannot be queried for this information using existing built-in functions. Note that the code objects created by compilest() cannot be queried like this either, and are identical to those created by the built-in compile() function.

parser.issuite(st)

This function mirrors isexpr() in that it reports whether an ST object represents an 'exec' form, commonly known as a “suite.” It is not safe to assume that this function is equivalent to not isexpr(st), as additional syntactic fragments may be supported in the future.

Exceptions and Error Handling

The parser module defines a single exception, but may also pass other built-in exceptions from other portions of the Python runtime environment. See each function for information about the exceptions it can raise.

exception parser.ParserError

Exception raised when a failure occurs within the parser module. This is generally produced for validation failures rather than the built-in SyntaxError raised during normal parsing. The exception argument is either a string describing the reason of the failure or a tuple containing a sequence causing the failure from a parse tree passed to sequence2st() and an explanatory string. Calls to sequence2st() need to be able to handle either type of exception, while calls to other functions in the module will only need to be aware of the simple string values.

Note that the functions compilest(), expr(), and suite() may raise exceptions which are normally raised by the parsing and compilation process. These include the built in exceptions MemoryError, OverflowError, SyntaxError, and SystemError. In these cases, these exceptions carry all the meaning normally associated with them. Refer to the descriptions of each function for detailed information.

ST Objects

Ordered and equality comparisons are supported between ST objects. Pickling of ST objects (using the pickle module) is also supported.

parser.STType

The type of the objects returned by expr(), suite() and sequence2st().

ST objects have the following methods:

ST.compile(filename='<syntax-tree>')

Same as compilest(st, filename).

ST.isexpr()

Same as isexpr(st).

ST.issuite()

Same as issuite(st).

ST.tolist(line_info=False, col_info=False)

Same as st2list(st, line_info, col_info).

ST.totuple(line_info=False, col_info=False)

Same as st2tuple(st, line_info, col_info).

Example: Emulation of compile()

While many useful operations may take place between parsing and bytecode generation, the simplest operation is to do nothing. For this purpose, using the parser module to produce an intermediate data structure is equivalent to the code

>>> code = compile('a + 5', 'file.py', 'eval')
>>> a = 5
>>> eval(code)
10

The equivalent operation using the parser module is somewhat longer, and allows the intermediate internal parse tree to be retained as an ST object:

>>> import parser
>>> st = parser.expr('a + 5')
>>> code = st.compile('file.py')
>>> a = 5
>>> eval(code)
10

An application which needs both ST and code objects can package this code into readily available functions:

import parser

def load_suite(source_string):
    st = parser.suite(source_string)
    return st, st.compile()

def load_expression(source_string):
    st = parser.expr(source_string)
    return st, st.compile()

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

파이썬 언어 서비스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

파이썬 언어 서비스 »

|

ast — Abstract Syntax Trees

Source code: Lib/ast.py [https://github.com/python/cpython/tree/3.7/Lib/ast.py]

The ast module helps Python applications to process trees of the Python abstract syntax grammar. The abstract syntax itself might change with each Python release; this module helps to find out programmatically what the current grammar looks like.

An abstract syntax tree can be generated by passing ast.PyCF_ONLY_AST as a flag to the compile() built-in function, or using the parse() helper provided in this module. The result will be a tree of objects whose classes all inherit from ast.AST. An abstract syntax tree can be compiled into a Python code object using the built-in compile() function.

Node classes

class ast.AST

This is the base of all AST node classes. The actual node classes are derived from the Parser/Python.asdl file, which is reproduced below. They are defined in the _ast C module and re-exported in ast.

There is one class defined for each left-hand side symbol in the abstract grammar (for example, ast.stmt or ast.expr). In addition, there is one class defined for each constructor on the right-hand side; these classes inherit from the classes for the left-hand side trees. For example, ast.BinOp inherits from ast.expr. For production rules with alternatives (aka “sums”), the left-hand side class is abstract: only instances of specific constructor nodes are ever created.

_fields

Each concrete class has an attribute _fields which gives the names of all child nodes.

Each instance of a concrete class has one attribute for each child node, of the type as defined in the grammar. For example, ast.BinOp instances have an attribute left of type ast.expr.

If these attributes are marked as optional in the grammar (using a question mark), the value might be None. If the attributes can have zero-or-more values (marked with an asterisk), the values are represented as Python lists. All possible attributes must be present and have valid values when compiling an AST with compile().

lineno

col_offset

Instances of ast.expr and ast.stmt subclasses have lineno and col_offset attributes. The lineno is the line number of source text (1-indexed so the first line is line 1) and the col_offset is the UTF-8 byte offset of the first token that generated the node. The UTF-8 offset is recorded because the parser uses UTF-8 internally.

The constructor of a class ast.T parses its arguments as follows:

If there are positional arguments, there must be as many as there are items in T._fields; they will be assigned as attributes of these names.

If there are keyword arguments, they will set the attributes of the same names to the given values.

For example, to create and populate an ast.UnaryOp node, you could use

node = ast.UnaryOp()
node.op = ast.USub()
node.operand = ast.Num()
node.operand.n = 5
node.operand.lineno = 0
node.operand.col_offset = 0
node.lineno = 0
node.col_offset = 0

or the more compact

node = ast.UnaryOp(ast.USub(), ast.Num(5, lineno=0, col_offset=0),
                   lineno=0, col_offset=0)

Abstract Grammar

The abstract grammar is currently defined as follows:

-- ASDL's 7 builtin types are:
-- identifier, int, string, bytes, object, singleton, constant
--
-- singleton: None, True or False
-- constant can be None, whereas None means "no value" for object.

module Python
{
    mod = Module(stmt* body)
        | Interactive(stmt* body)
        | Expression(expr body)

        -- not really an actual node but useful in Jython's typesystem.
        | Suite(stmt* body)

    stmt = FunctionDef(identifier name, arguments args,
                       stmt* body, expr* decorator_list, expr? returns)
          | AsyncFunctionDef(identifier name, arguments args,
                             stmt* body, expr* decorator_list, expr? returns)

          | ClassDef(identifier name,
             expr* bases,
             keyword* keywords,
             stmt* body,
             expr* decorator_list)
          | Return(expr? value)

          | Delete(expr* targets)
          | Assign(expr* targets, expr value)
          | AugAssign(expr target, operator op, expr value)
          -- 'simple' indicates that we annotate simple name without parens
          | AnnAssign(expr target, expr annotation, expr? value, int simple)

          -- use 'orelse' because else is a keyword in target languages
          | For(expr target, expr iter, stmt* body, stmt* orelse)
          | AsyncFor(expr target, expr iter, stmt* body, stmt* orelse)
          | While(expr test, stmt* body, stmt* orelse)
          | If(expr test, stmt* body, stmt* orelse)
          | With(withitem* items, stmt* body)
          | AsyncWith(withitem* items, stmt* body)

          | Raise(expr? exc, expr? cause)
          | Try(stmt* body, excepthandler* handlers, stmt* orelse, stmt* finalbody)
          | Assert(expr test, expr? msg)

          | Import(alias* names)
          | ImportFrom(identifier? module, alias* names, int? level)

          | Global(identifier* names)
          | Nonlocal(identifier* names)
          | Expr(expr value)
          | Pass | Break | Continue

          -- XXX Jython will be different
          -- col_offset is the byte offset in the utf8 string the parser uses
          attributes (int lineno, int col_offset)

          -- BoolOp() can use left & right?
    expr = BoolOp(boolop op, expr* values)
         | BinOp(expr left, operator op, expr right)
         | UnaryOp(unaryop op, expr operand)
         | Lambda(arguments args, expr body)
         | IfExp(expr test, expr body, expr orelse)
         | Dict(expr* keys, expr* values)
         | Set(expr* elts)
         | ListComp(expr elt, comprehension* generators)
         | SetComp(expr elt, comprehension* generators)
         | DictComp(expr key, expr value, comprehension* generators)
         | GeneratorExp(expr elt, comprehension* generators)
         -- the grammar constrains where yield expressions can occur
         | Await(expr value)
         | Yield(expr? value)
         | YieldFrom(expr value)
         -- need sequences for compare to distinguish between
         -- x < 4 < 3 and (x < 4) < 3
         | Compare(expr left, cmpop* ops, expr* comparators)
         | Call(expr func, expr* args, keyword* keywords)
         | Num(object n) -- a number as a PyObject.
         | Str(string s) -- need to specify raw, unicode, etc?
         | FormattedValue(expr value, int? conversion, expr? format_spec)
         | JoinedStr(expr* values)
         | Bytes(bytes s)
         | NameConstant(singleton value)
         | Ellipsis
         | Constant(constant value)

         -- the following expression can appear in assignment context
         | Attribute(expr value, identifier attr, expr_context ctx)
         | Subscript(expr value, slice slice, expr_context ctx)
         | Starred(expr value, expr_context ctx)
         | Name(identifier id, expr_context ctx)
         | List(expr* elts, expr_context ctx)
         | Tuple(expr* elts, expr_context ctx)

          -- col_offset is the byte offset in the utf8 string the parser uses
          attributes (int lineno, int col_offset)

    expr_context = Load | Store | Del | AugLoad | AugStore | Param

    slice = Slice(expr? lower, expr? upper, expr? step)
          | ExtSlice(slice* dims)
          | Index(expr value)

    boolop = And | Or

    operator = Add | Sub | Mult | MatMult | Div | Mod | Pow | LShift
                 | RShift | BitOr | BitXor | BitAnd | FloorDiv

    unaryop = Invert | Not | UAdd | USub

    cmpop = Eq | NotEq | Lt | LtE | Gt | GtE | Is | IsNot | In | NotIn

    comprehension = (expr target, expr iter, expr* ifs, int is_async)

    excepthandler = ExceptHandler(expr? type, identifier? name, stmt* body)
                    attributes (int lineno, int col_offset)

    arguments = (arg* args, arg? vararg, arg* kwonlyargs, expr* kw_defaults,
                 arg? kwarg, expr* defaults)

    arg = (identifier arg, expr? annotation)
           attributes (int lineno, int col_offset)

    -- keyword arguments supplied to call (NULL identifier for **kwargs)
    keyword = (identifier? arg, expr value)

    -- import name with optional 'as' alias.
    alias = (identifier name, identifier? asname)

    withitem = (expr context_expr, expr? optional_vars)
}

ast Helpers

Apart from the node classes, the ast module defines these utility functions and classes for traversing abstract syntax trees:

ast.parse(source, filename='<unknown>', mode='exec')

Parse the source into an AST node. Equivalent to compile(source, filename, mode, ast.PyCF_ONLY_AST).

경고

It is possible to crash the Python interpreter with a sufficiently large/complex string due to stack depth limitations in Python’s AST compiler.

ast.literal_eval(node_or_string)

Safely evaluate an expression node or a string containing a Python literal or container display. The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, and None.

This can be used for safely evaluating strings containing Python values from untrusted sources without the need to parse the values oneself. It is not capable of evaluating arbitrarily complex expressions, for example involving operators or indexing.

경고

It is possible to crash the Python interpreter with a sufficiently large/complex string due to stack depth limitations in Python’s AST compiler.

버전 3.2에서 변경: Now allows bytes and set literals.

ast.get_docstring(node, clean=True)

Return the docstring of the given node (which must be a FunctionDef, AsyncFunctionDef, ClassDef, or Module node), or None if it has no docstring. If clean is true, clean up the docstring’s indentation with inspect.cleandoc().

버전 3.5에서 변경: AsyncFunctionDef is now supported.

ast.fix_missing_locations(node)

When you compile a node tree with compile(), the compiler expects lineno and col_offset attributes for every node that supports them. This is rather tedious to fill in for generated nodes, so this helper adds these attributes recursively where not already set, by setting them to the values of the parent node. It works recursively starting at node.

ast.increment_lineno(node, n=1)

Increment the line number of each node in the tree starting at node by n. This is useful to “move code” to a different location in a file.

ast.copy_location(new_node, old_node)

Copy source location (lineno and col_offset) from old_node to new_node if possible, and return new_node.

ast.iter_fields(node)

Yield a tuple of (fieldname, value) for each field in node._fields that is present on node.

ast.iter_child_nodes(node)

Yield all direct child nodes of node, that is, all fields that are nodes and all items of fields that are lists of nodes.

ast.walk(node)

Recursively yield all descendant nodes in the tree starting at node (including node itself), in no specified order. This is useful if you only want to modify nodes in place and don’t care about the context.

class ast.NodeVisitor

A node visitor base class that walks the abstract syntax tree and calls a visitor function for every node found. This function may return a value which is forwarded by the visit() method.

This class is meant to be subclassed, with the subclass adding visitor methods.

visit(node)

Visit a node. The default implementation calls the method called self.visit_classname where classname is the name of the node class, or generic_visit() if that method doesn’t exist.

generic_visit(node)

This visitor calls visit() on all children of the node.

Note that child nodes of nodes that have a custom visitor method won’t be visited unless the visitor calls generic_visit() or visits them itself.

Don’t use the NodeVisitor if you want to apply changes to nodes during traversal. For this a special visitor exists (NodeTransformer) that allows modifications.

class ast.NodeTransformer

A NodeVisitor subclass that walks the abstract syntax tree and allows modification of nodes.

The NodeTransformer will walk the AST and use the return value of the visitor methods to replace or remove the old node. If the return value of the visitor method is None, the node will be removed from its location, otherwise it is replaced with the return value. The return value may be the original node in which case no replacement takes place.

Here is an example transformer that rewrites all occurrences of name lookups (foo) to data['foo']:

class RewriteName(NodeTransformer):

    def visit_Name(self, node):
        return Subscript(
            value=Name(id='data', ctx=Load()),
            slice=Index(value=Str(s=node.id)),
            ctx=node.ctx
        )

Keep in mind that if the node you’re operating on has child nodes you must either transform the child nodes yourself or call the generic_visit() method for the node first.

For nodes that were part of a collection of statements (that applies to all statement nodes), the visitor may also return a list of nodes rather than just a single node.

If NodeTransformer introduces new nodes (that weren’t part of original tree) without giving them location information (such as lineno), fix_missing_locations() should be called with the new sub-tree to recalculate the location information:

tree = ast.parse('foo', mode='eval')
new_tree = fix_missing_locations(RewriteName().visit(tree))

Usually you use the transformer like this:

node = YourTransformer().visit(node)

ast.dump(node, annotate_fields=True, include_attributes=False)

Return a formatted dump of the tree in node. This is mainly useful for debugging purposes. If annotate_fields is true (by default), the returned string will show the names and the values for fields. If annotate_fields is false, the result string will be more compact by omitting unambiguous field names. Attributes such as line numbers and column offsets are not dumped by default. If this is wanted, include_attributes can be set to true.

더 보기

Green Tree Snakes [https://greentreesnakes.readthedocs.io/], an external documentation resource, has good details on working with Python ASTs.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

파이썬 언어 서비스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

파이썬 언어 서비스 »

|

symtable — 컴파일러 심볼 테이블 액세스

소스 코드: Lib/symtable.py [https://github.com/python/cpython/tree/3.7/Lib/symtable.py]

심볼 테이블은 바이트 코드가 생성되기 바로 전에 AST에서 컴파일러에 의해 생성됩니다. 심볼 테이블은 코드에서 모든 식별자의 스코프를 계산합니다. symtable은 이러한 테이블을 검사하는 인터페이스를 제공합니다.

심볼 테이블 생성하기

symtable.symtable(code, filename, compile_type)

파이썬 소스 code에 대한 최상위 SymbolTable을 반환합니다. filename은 코드가 들어있는 파일의 이름입니다. compile_type은 compile()에 대한 mode 인자와 같습니다.

심볼 테이블 검사하기

class symtable.SymbolTable

블록에 대한 이름 공간 테이블. 생성자는 공개되지 않습니다.

get_type()

심볼 테이블의 형을 돌려줍니다. 가능한 값은 'class', 'module' 및 'function'입니다.

get_id()

테이블의 식별자를 돌려줍니다.

get_name()

테이블의 이름을 돌려줍니다. 테이블이 클래스를 위한 것이면 클래스의 이름이고, 테이블이 함수를 위한 것이면 함수의 이름이고, 테이블이 전역이면 'top'입니다 (get_type()은 'module'을 반환합니다).

get_lineno()

이 테이블이 나타내는 블록의 첫 번째 줄 번호를 반환합니다.

is_optimized()

이 테이블의 지역(locals)을 최적화할 수 있으면 True를 반환합니다.

is_nested()

블록이 중첩된 클래스나 함수면 True를 반환합니다.

has_children()

블록에 중첩된 이름 공간이 있으면 True를 반환합니다. 이것들은 get_children()으로 얻을 수 있습니다.

has_exec()

블록이 exec를 사용하면 True를 반환합니다.

get_identifiers()

이 테이블의 심볼 이름들의 리스트를 돌려줍니다.

lookup(name)

테이블에서 name을 찾아서 Symbol 인스턴스를 반환합니다.

get_symbols()

테이블에 있는 이름에 대한 Symbol 인스턴스 리스트를 반환합니다.

get_children()

중첩된 심볼 테이블의 리스트를 반환합니다.

class symtable.Function

함수나 메서드의 이름 공간. 이 클래스는 SymbolTable을 상속합니다.

get_parameters()

이 함수의 매개 변수 이름을 포함하는 튜플을 반환합니다.

get_locals()

이 함수의 지역 이름을 포함하는 튜플을 반환합니다.

get_globals()

이 함수의 전역 이름을 포함하는 튜플을 반환합니다.

get_frees()

이 함수의 자유 변수 이름을 포함하는 튜플을 반환합니다.

class symtable.Class

클래스의 이름 공간. 이 클래스는 SymbolTable을 상속합니다.

get_methods()

클래스에서 선언된 메서드 이름을 포함하는 튜플을 반환합니다.

class symtable.Symbol

소스의 식별자에 해당하는 SymbolTable의 항목. 생성자는 공개되지 않습니다.

get_name()

심볼의 이름을 돌려줍니다.

is_referenced()

심볼이 블록에서 사용되면 True를 반환합니다.

is_imported()

심볼이 import 문에서 만들어지면 True를 반환합니다.

is_parameter()

심볼이 매개 변수면 True를 반환합니다.

is_global()

심볼이 전역이면 True를 반환합니다.

is_declared_global()

심볼이 global 문으로 전역으로 선언되면 True를 반환합니다.

is_local()

심볼이 블록의 지역이면 True를 반환합니다.

is_free()

심볼이 블록에서 참조되지만 대입되지 않으면 True를 반환합니다.

is_assigned()

심볼이 블록에 대입되면 True를 반환합니다.

is_namespace()

이름 연결(name binding)이 새로운 이름 공간을 도입하면 True를 반환합니다.

이름이 함수나 클래스 문의 대상으로 사용되면 참입니다.

예를 들면:

>>> table = symtable.symtable("def some_func(): pass", "string", "exec")
>>> table.lookup("some_func").is_namespace()
True

하나의 이름을 여러 객체에 연결할 수 있음에 유의하십시오. 결과가 True 이면, 이름은 새 이름 공간을 도입하지 않는 int 나 list와 같은 다른 객체에도 연결되어있을 수 있습니다.

get_namespaces()

이 이름에 연결된 이름 공간의 리스트를 돌려줍니다.

get_namespace()

이 이름에 연결된 이름 공간을 돌려줍니다. 둘 이상의 이름 공간이 연결되면, ValueError가 발생합니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

파이썬 언어 서비스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

파이썬 언어 서비스 »

|

symbol — 파이썬 구문 분석 트리에 사용되는 상수

소스 코드: Lib/symbol.py [https://github.com/python/cpython/tree/3.7/Lib/symbol.py]

이 모듈은 구문 분석 트리의 내부 노드의 숫자 값을 나타내는 상수를 제공합니다. 대부분 파이썬 상수와 달리, 소문자 이름을 사용합니다. 언어 문법의 문맥에서 이름의 정의는 파이썬 배포판의 Grammar/Grammar 파일을 참조하십시오. 이름이 매핑되는 특정 숫자 값은 파이썬 버전 간에 변경될 수 있습니다.

이 모듈은 또한 하나의 추가 데이터 객체를 제공합니다:

symbol.sym_name

이 모듈에 정의된 상수의 숫자 값을 다시 이름 문자열로 매핑하여, 사람이 읽을 수 있는 구문 분석 트리 표현을 생성할 수 있도록 합니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

파이썬 언어 서비스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

파이썬 언어 서비스 »

|

token — 파이썬 구문 분석 트리에 사용되는 상수

소스 코드: Lib/token.py [https://github.com/python/cpython/tree/3.7/Lib/token.py]

이 모듈은 구문 분석 트리의 말단 노드의 숫자 값을 나타내는 상수를 제공합니다 (터미널 토큰). 언어 문법의 문맥에서 이름의 정의는 파이썬 배포판의 Grammar/Grammar 파일을 참조하십시오. 이름이 매핑되는 특정 숫자 값은 파이썬 버전 간에 변경될 수 있습니다.

이 모듈은 숫자 코드에서 이름으로의 매핑과 몇몇 함수도 제공합니다. 이 함수는 파이썬 C 헤더 파일의 정의를 반영합니다.

token.tok_name

이 모듈에 정의된 상수의 숫자 값을 다시 이름 문자열로 매핑하여 사람이 읽을 수 있는 구문 분석 트리 표현을 생성할 수 있도록 하는 딕셔너리.

token.ISTERMINAL(x)

Return True for terminal token values.

token.ISNONTERMINAL(x)

Return True for non-terminal token values.

token.ISEOF(x)

Return True if x is the marker indicating the end of input.

토큰 상수는 다음과 같습니다:

token.ENDMARKER

token.NAME

token.NUMBER

token.STRING

token.NEWLINE

token.INDENT

token.DEDENT

token.LPAR

token.RPAR

token.LSQB

token.RSQB

token.COLON

token.COMMA

token.SEMI

token.PLUS

token.MINUS

token.STAR

token.SLASH

token.VBAR

token.AMPER

token.LESS

token.GREATER

token.EQUAL

token.DOT

token.PERCENT

token.LBRACE

token.RBRACE

token.EQEQUAL

token.NOTEQUAL

token.LESSEQUAL

token.GREATEREQUAL

token.TILDE

token.CIRCUMFLEX

token.LEFTSHIFT

token.RIGHTSHIFT

token.DOUBLESTAR

token.PLUSEQUAL

token.MINEQUAL

token.STAREQUAL

token.SLASHEQUAL

token.PERCENTEQUAL

token.AMPEREQUAL

token.VBAREQUAL

token.CIRCUMFLEXEQUAL

token.LEFTSHIFTEQUAL

token.RIGHTSHIFTEQUAL

token.DOUBLESTAREQUAL

token.DOUBLESLASH

token.DOUBLESLASHEQUAL

token.AT

token.ATEQUAL

token.RARROW

token.ELLIPSIS

token.OP

token.ERRORTOKEN

token.N_TOKENS

token.NT_OFFSET

다음 토큰 유형 값은 C 토크나이저가 사용하지 않지만 tokenize 모듈에 필요합니다.

token.COMMENT

주석을 나타내는 데 사용되는 토큰 값.

token.NL

비종결 줄넘김을 나타내는데 사용되는 토큰 값. NEWLINE 토큰은 파이썬 코드의 논리적 줄의 끝을 나타냅니다; NL 토큰은 코드의 논리적 줄이 여러 물리적 줄로 이어질 때 생성됩니다.

token.ENCODING

소스 바이트열을 텍스트로 디코딩하는 데 사용되는 인코딩을 나타내는 토큰 값. tokenize.tokenize()에 의해 반환되는 첫 번째 토큰은 항상 ENCODING 토큰입니다.

버전 3.5에서 변경: AWAIT 와 ASYNC 토큰이 추가되었습니다.

버전 3.7에서 변경: COMMENT, NL 및 ENCODING 토큰이 추가되었습니다.

버전 3.7에서 변경: AWAIT 와 ASYNC 토큰이 제거되었습니다. “async”와 “await”는 이제 NAME 토큰으로 토큰화됩니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

파이썬 언어 서비스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

파이썬 언어 서비스 »

|

keyword — 파이썬 키워드 검사

소스 코드: Lib/keyword.py [https://github.com/python/cpython/tree/3.7/Lib/keyword.py]

This module allows a Python program to determine if a string is a keyword.

keyword.iskeyword(s)

Return True if s is a Python keyword.

keyword.kwlist

Sequence containing all the keywords defined for the interpreter. If any keywords are defined to only be active when particular __future__ statements are in effect, these will be included as well.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

파이썬 언어 서비스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

파이썬 언어 서비스 »

|

tokenize — 파이썬 소스를 위한 토크나이저

소스 코드: Lib/tokenize.py [https://github.com/python/cpython/tree/3.7/Lib/tokenize.py]

The tokenize module provides a lexical scanner for Python source code, implemented in Python. The scanner in this module returns comments as tokens as well, making it useful for implementing “pretty-printers”, including colorizers for on-screen displays.

토큰 스트림 처리를 단순화하기 위해, 모든 연산자와 구분자 토큰과 Ellipsis는 범용 OP 토큰 유형을 사용하여 반환됩니다. 정확한 유형은 tokenize.tokenize()에서 반환된 네임드 튜플의 exact_type 프로퍼티를 확인하여 파악할 수 있습니다.

입력 토큰화하기

기본 진입점은 제너레이터입니다:

tokenize.tokenize(readline)

tokenize() 제너레이터는 하나의 인자 readline을 요구합니다. 이 인자는 파일 객체의 io.IOBase.readline() 메서드와 같은 인터페이스를 제공하는 콜러블 객체여야 합니다. 함수를 호출할 때마다 한 줄의 입력을 바이트열로 반환해야 합니다.

제너레이터는 다음 멤버를 갖는 5-튜플을 생성합니다: 토큰 유형; 토큰 문자열; 토큰이 소스에서 시작하는 줄과 열을 지정하는 정수의 2-튜플 (srow, scol); 토큰이 소스에서 끝나는 줄과 열을 지정하는 정수의 2-튜플 (erow, ecol)과 토큰이 발견된 줄. 전달된 줄(마지막 튜플 항목)은 논리적 줄입니다; 이어지는 줄들이 포함됩니다. 5-튜플은 필드 이름이 type string start end line 인 네임드 튜플로 반환됩니다.

반환된 네임드 튜플에는 OP 토큰에 대한 정확한 연산자 유형이 포함된 exact_type이라는 추가 프로퍼티가 있습니다. 다른 모든 토큰 유형에서 exact_type은 네임드 튜플 type 필드와 같습니다.

버전 3.1에서 변경: 네임드 튜플에 대한 지원이 추가되었습니다.

버전 3.3에서 변경: exact_type에 대한 지원이 추가되었습니다.

tokenize()는 PEP 263 [https://www.python.org/dev/peps/pep-0263]에 따라 UTF-8 BOM이나 인코딩 쿠키를 찾아 파일의 소스 인코딩을 결정합니다.

token 모듈의 모든 상수도 tokenize에서 내보냅니다.

토큰화 프로세스를 역전시키는 또 다른 함수가 제공됩니다. 이것은 스크립트를 토큰화하고, 토큰 스트림을 수정한 후, 수정된 스크립트를 다시 쓰는 도구를 만드는 데 유용합니다.

tokenize.untokenize(iterable)

토큰을 파이썬 소스 코드로 역 변환합니다. iterable은 최소한 토큰 유형과 토큰 문자열의 두 요소가 있는 시퀀스를 반환해야 합니다. 추가 시퀀스 요소는 무시됩니다.

재구성된 스크립트는 단일 문자열로 반환됩니다. 결과는 다시 토큰화하면 입력과 일치함이 보장되어, 변환은 무손실이고 왕복이 보장됩니다. 보증은 토큰 유형과 토큰 문자열에만 적용되어, 토큰 간의 간격(열 위치)은 변경될 수 있습니다.

tokenize() 에 의해 출력되는 첫 번째 토큰 시퀀스인 ENCODING 토큰을 사용하여 인코딩된 바이트열을 반환합니다.

tokenize()는 토큰화하는 소스 파일의 인코딩을 감지해야 합니다. 이 작업을 수행하는 데 사용되는 함수를 사용할 수 있습니다:

tokenize.detect_encoding(readline)

detect_encoding() 함수는 파이썬 소스 파일을 디코딩할 때 사용해야 하는 인코딩을 감지하는 데 사용됩니다. tokenize() 제너레이터와 같은 방식으로, 하나의 인자 readline을 요구합니다.

readline을 최대 두 번 호출하고, 사용된 인코딩(문자열로)과 읽은 줄들(바이트열에서 디코드 되지 않습니다)의 리스트를 반환합니다.

PEP 263 [https://www.python.org/dev/peps/pep-0263]에 지정된 대로 UTF-8 BOM이나 인코딩 쿠키의 존재로부터 인코딩을 검색합니다. BOM과 쿠키가 모두 있지만 서로 일치하지 않으면 SyntaxError가 발생합니다. BOM이 발견되면, 'utf-8-sig'가 인코딩으로 반환됩니다.

인코딩이 지정되지 않으면, 기본값인 'utf-8'이 반환됩니다.

open()을 사용하여 파이썬 소스 파일을 여십시오: detect_encoding()을 사용하여 파일 인코딩을 감지합니다.

tokenize.open(filename)

detect_encoding()에 의해 감지된 인코딩을 사용하여 읽기 전용 모드로 파일을 엽니다.

버전 3.2에 추가.

exception tokenize.TokenError

여러 줄로 나눌 수 있는 독스트링이나 표현식이 파일의 어디에서도 완료되지 않을 때 발생합니다, 예를 들어:

"""Beginning of
docstring

또는:

[1,
 2,
 3

닫히지 않은 작은따옴표로 묶인 문자열은 에러를 발생시키지 않음에 유의하십시오. 그것들은 ERRORTOKEN로 토큰화되고, 그 뒤에 내용이 토큰화됩니다.

명령 줄 사용법

버전 3.3에 추가.

tokenize 모듈은 명령 줄에서 스크립트로 실행될 수 있습니다. 이렇게 간단합니다:

python -m tokenize [-e] [filename.py]

허용되는 옵션은 다음과 같습니다:

-h, --help

이 도움말 메시지를 표시하고 종료합니다

-e, --exact

정확한 유형(exact_type)을 사용하여 토큰 이름을 표시합니다

filename.py가 지정되면 그 내용은 표준출력(stdout)으로 토큰화됩니다. 그렇지 않으면, 표준입력(stdin)에 대해 토큰화가 수행됩니다.

예제

float 리터럴을 Decimal 객체로 변환하는 스크립트 재 작성기의 예제:

from tokenize import tokenize, untokenize, NUMBER, STRING, NAME, OP
from io import BytesIO

def decistmt(s):
    """Substitute Decimals for floats in a string of statements.

    >>> from decimal import Decimal
    >>> s = 'print(+21.3e-5*-.1234/81.7)'
    >>> decistmt(s)
    "print (+Decimal ('21.3e-5')*-Decimal ('.1234')/Decimal ('81.7'))"

    The format of the exponent is inherited from the platform C library.
    Known cases are "e-007" (Windows) and "e-07" (not Windows).  Since
    we're only showing 12 digits, and the 13th isn't close to 5, the
    rest of the output should be platform-independent.

    >>> exec(s)  #doctest: +ELLIPSIS
    -3.21716034272e-0...7

    Output from calculations with Decimal should be identical across all
    platforms.

    >>> exec(decistmt(s))
    -3.217160342717258261933904529E-7
    """
    result = []
    g = tokenize(BytesIO(s.encode('utf-8')).readline)  # tokenize the string
    for toknum, tokval, _, _, _ in g:
        if toknum == NUMBER and '.' in tokval:  # replace NUMBER tokens
            result.extend([
                (NAME, 'Decimal'),
                (OP, '('),
                (STRING, repr(tokval)),
                (OP, ')')
            ])
        else:
            result.append((toknum, tokval))
    return untokenize(result).decode('utf-8')

명령 줄에서 토큰화하는 예제. 스크립트:

def say_hello():
    print("Hello, World!")

say_hello()

는 다음 출력으로 토큰화됩니다. 여기서 첫 번째 열은 토큰이 발견된 줄/열 좌표의 범위이고, 두 번째 열은 토큰의 이름이며, 마지막 열은 토큰의 값입니다 (있다면)

$ python -m tokenize hello.py
0,0-0,0:            ENCODING       'utf-8'
1,0-1,3:            NAME           'def'
1,4-1,13:           NAME           'say_hello'
1,13-1,14:          OP             '('
1,14-1,15:          OP             ')'
1,15-1,16:          OP             ':'
1,16-1,17:          NEWLINE        '\n'
2,0-2,4:            INDENT         '    '
2,4-2,9:            NAME           'print'
2,9-2,10:           OP             '('
2,10-2,25:          STRING         '"Hello, World!"'
2,25-2,26:          OP             ')'
2,26-2,27:          NEWLINE        '\n'
3,0-3,1:            NL             '\n'
4,0-4,0:            DEDENT         ''
4,0-4,9:            NAME           'say_hello'
4,9-4,10:           OP             '('
4,10-4,11:          OP             ')'
4,11-4,12:          NEWLINE        '\n'
5,0-5,0:            ENDMARKER      ''

정확한 토큰 유형 이름은 -e 옵션을 사용하여 표시할 수 있습니다:

$ python -m tokenize -e hello.py
0,0-0,0:            ENCODING       'utf-8'
1,0-1,3:            NAME           'def'
1,4-1,13:           NAME           'say_hello'
1,13-1,14:          LPAR           '('
1,14-1,15:          RPAR           ')'
1,15-1,16:          COLON          ':'
1,16-1,17:          NEWLINE        '\n'
2,0-2,4:            INDENT         '    '
2,4-2,9:            NAME           'print'
2,9-2,10:           LPAR           '('
2,10-2,25:          STRING         '"Hello, World!"'
2,25-2,26:          RPAR           ')'
2,26-2,27:          NEWLINE        '\n'
3,0-3,1:            NL             '\n'
4,0-4,0:            DEDENT         ''
4,0-4,9:            NAME           'say_hello'
4,9-4,10:           LPAR           '('
4,10-4,11:          RPAR           ')'
4,11-4,12:          NEWLINE        '\n'
5,0-5,0:            ENDMARKER      ''

Example of tokenizing a file programmatically, reading unicode strings instead of bytes with generate_tokens():

import tokenize

with tokenize.open('hello.py') as f:
    tokens = tokenize.generate_tokens(f.readline)
    for token in tokens:
        print(token)

Or reading bytes directly with tokenize():

import tokenize

with open('hello.py', 'rb') as f:
    tokens = tokenize.tokenize(f.readline)
    for token in tokens:
        print(token)

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

파이썬 언어 서비스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

파이썬 언어 서비스 »

|

tabnanny — 모호한 들여쓰기 감지

소스 코드: Lib/tabnanny.py [https://github.com/python/cpython/tree/3.7/Lib/tabnanny.py]

이 모듈은 당장은 스크립트로 호출하기 위한 것입니다. 하지만 IDE로 임포트 해서 아래에 설명된 check() 함수를 사용할 수 있습니다.

참고

이 모듈에서 제공하는 API는 향후 배포에서 변경될 수 있습니다; 그러한 변경은 이전 버전과 호환되지 않을 수 있습니다.

tabnanny.check(file_or_dir)

file_or_dir가 디렉터리이고 심볼릭 링크가 아니면, file_or_dir라는 이름의 디렉터리 트리를 재귀적으로 내려가면서, 모든 .py 파일을 검사합니다. file_or_dir가 일반 파이썬 소스 파일이면, 공백과 관련된 문제가 있는지 확인합니다. 진단 메시지는 print() 함수를 사용하여 표준 출력에 기록됩니다.

tabnanny.verbose

상세 메시지를 인쇄할지를 나타내는 플래그. 이것은 스크립트로 호출되면 -v 옵션에 의해 증가합니다.

tabnanny.filename_only

공백 관련 문제가 있는 파일의 파일명만 인쇄할지를 나타내는 플래그. 이것은 스크립트로 호출되면 -q 옵션에 의해 참으로 설정됩니다.

exception tabnanny.NannyNag

모호한 들여쓰기를 감지하면 process_tokens()에 의해 발생합니다. check()에서 잡아서 처리됩니다.

tabnanny.process_tokens(tokens)

이 함수는 tokenize 모듈에서 생성된 토큰을 처리하기 위해 check()에서 사용됩니다.

더 보기

모듈 tokenize

파이썬 소스 코드를 위한 어휘 스캐너.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

파이썬 언어 서비스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

파이썬 언어 서비스 »

|

pyclbr — Python module browser support

소스 코드: Lib/pyclbr.py [https://github.com/python/cpython/tree/3.7/Lib/pyclbr.py]

pyclbr 모듈은 파이썬 코드 모듈에 정의된 함수, 클래스 및 메서드에 대한 제한된 정보를 제공합니다. 이 정보는 모듈 브라우저를 구현하기에 충분합니다. 정보는 모듈을 임포트 하기보다는 파이썬 소스 코드에서 추출되므로 이 모듈은 신뢰할 수 없는 코드와 함께 사용하는 것이 안전합니다. 이 제한으로 인해 이 모듈을 모든 표준 및 선택 확장 모듈을 포함하여 파이썬으로 구현되지 않은 모듈에 사용할 수 없습니다.

pyclbr.readmodule(module, path=None)

모듈 수준의 클래스 이름을 클래스 설명자에 매핑하는 딕셔너리를 돌려줍니다. 가능하면, 임포트 된 베이스 클래스에 관한 설명자가 포함됩니다. 매개 변수 module은 읽을 모듈 이름이 들어있는 문자열입니다; 패키지 내의 모듈 이름일 수 있습니다. 주어지면, path는 sys.path 앞에 추가된 디렉터리 경로 시퀀스인데, 모듈 소스 코드의 위치를 찾는 데 사용됩니다.

This function is the original interface and is only kept for back compatibility. It returns a filtered version of the following.

pyclbr.readmodule_ex(module, path=None)

def 나 class 문을 사용하여 모듈에 정의된 각 함수 및 클래스에 대한 함수나 클래스 설명자를 포함하는 딕셔너리 기반 트리를 반환합니다. 반환된 딕셔너리는 모듈 수준의 함수와 클래스 이름을 해당 설명자에 대응합니다. 중첩된 객체는 그들의 parent의 children 딕셔너리에 들어갑니다. readmodule과 마찬가지로, module은 읽을 모듈의 이름을 지정하고 path는 sys.path의 앞에 추가됩니다. 읽히는 모듈이 패키지면, 반환된 딕셔너리는 키 '__path__'를 가지는데, 값은 패키지 검색 경로를 포함하는 리스트입니다.

버전 3.7에 추가: 중첩된 정의에 대한 설명자. 새로운 children 어트리뷰트를 통해 액세스할 수 있습니다. 각에는 새로운 parent 어트리뷰트가 있습니다.

이러한 함수에 의해 반환되는 설명자는 Function과 Class 클래스의 인스턴스입니다. 사용자가 이러한 클래스의 인스턴스를 만들 것으로 기대하지 않습니다.

Function 객체

클래스 Function 인스턴스는 def 문으로 정의된 함수를 설명합니다. 다음과 같은 어트리뷰트를 가지고 있습니다 :

Function.file

함수가 정의된 파일의 이름.

Function.module

설명된 함수를 정의하는 모듈의 이름.

Function.name

함수의 이름.

Function.lineno

정의가 시작되는 파일의 줄 번호.

Function.parent

최상위 함수면, None. 중첩된 함수면, 부모.

버전 3.7에 추가.

Function.children

이름을 중첩된 함수와 클래스에 관한 설명자로 매핑하는 딕셔너리.

버전 3.7에 추가.

Class 객체

클래스 Class 인스턴스는 class 문으로 정의된 클래스를 설명합니다. Function과 같은 어트리뷰트에 더해 두 개의 어트리뷰트가 더 있습니다.

Class.file

클래스가 정의된 파일의 이름.

Class.module

설명된 클래스를 정의하는 모듈의 이름.

Class.name

클래스의 이름.

Class.lineno

정의가 시작되는 파일의 줄 번호.

Class.parent

최상위 클래스면, None. 중첩된 클래스면, 부모.

버전 3.7에 추가.

Class.children

이름을 중첩된 함수와 클래스에 관한 설명자로 매핑하는 딕셔너리.

버전 3.7에 추가.

Class.super

설명되는 클래스의 직접적인 베이스 클래스를 설명하는 Class 객체의 리스트. 슈퍼 클래스로 명명되었지만 readmodule_ex()가 찾을 수 없는 클래스는 Class 객체가 아니라 클래스 이름을 담은 문자열로 나열됩니다.

Class.methods

메서드 이름을 줄 번호에 매핑하는 딕셔너리. 최신 children 딕셔너리에서 파생될 수 있지만, 이전 버전과의 호환성을 위해 남아있습니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

파이썬 언어 서비스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

파이썬 언어 서비스 »

|

py_compile — 파이썬 소스 파일 컴파일

소스 코드: Lib/py_compile.py [https://github.com/python/cpython/tree/3.7/Lib/py_compile.py]

py_compile 모듈은 소스 파일에서 바이트 코드 파일을 생성하는 함수와 모듈 소스 파일이 스크립트로 호출될 때 사용되는 또 다른 함수를 제공합니다.

자주 사용되지는 않지만, 특히 일부 사용자가 소스 코드가 들어있는 디렉터리에 바이트 코드 캐시 파일을 쓸 수 있는 권한이 없을 때, 이 함수는 공유 사용을 위해 모듈을 설치할 때 유용할 수 있습니다.

exception py_compile.PyCompileError

파일을 컴파일하는 도중 에러가 일어날 때 발생하는 예외.

py_compile.compile(file, cfile=None, dfile=None, doraise=False, optimize=-1, invalidation_mode=PycInvalidationMode.TIMESTAMP)

바이트 코드로 소스 파일을 컴파일하고 바이트 코드 캐시 파일을 기록합니다. 소스 코드는 file이 지정하는 이름의 파일에서 로드됩니다. 바이트 코드는 cfile에 기록되며, 기본값은 .pyc로 끝나는 PEP 3147 [https://www.python.org/dev/peps/pep-3147]/PEP 488 [https://www.python.org/dev/peps/pep-0488] 경로입니다. 예를 들어, file이 /foo/bar/baz.py이면 cfile은 파이썬 3.2의 경우 /foo/bar/__pycache__/baz.cpython-32.pyc로 기본 설정됩니다. dfile이 지정되면, file 대신 에러 메시지에서 소스 파일 이름으로 사용됩니다. doraise가 참이면, file을 컴파일하는 동안 에러를 만나면 PyCompileError가 발생합니다. doraise가 거짓(기본값)이면, sys.stderr에 에러 문자열이 기록되지만, 예외는 발생하지 않습니다. 이 함수는 바이트 컴파일된 파일의 경로, 즉 사용된 cfile 값을 반환합니다.

cfile이 되는 경로(명시적으로 지정되거나 계산된 경로)가 심볼릭 링크나 비정규 파일이면, FileExistsError가 발생합니다. 이것은 바이트 컴파일된 파일을 해당 경로에 쓸 수 있을 때 임포트가 해당 경로를 일반 파일로 바꾼다는 경고로 작용합니다. 이는 동시 파일 기록 문제를 방지하기 위해 최종 바이트 컴파일된 파일을 위치시키는데 파일 이름 바꾸기를 사용하는 임포트의 부작용입니다.

optimize는 최적화 수준을 제어하고 내장 compile() 함수로 전달됩니다. 기본값 -1은 현재 인터프리터의 최적화 수준을 선택합니다.

invalidation_mode는 PycInvalidationMode enum의 멤버여야 하며 실행 시간에 생성된 바이트 코드 캐시를 무효로 하는 방법을 제어합니다. SOURCE_DATE_EPOCH 환경 변수가 설정되면 기본값은 PycInvalidationMode.CHECKED_HASH이고, 그렇지 않으면 기본값은 PycInvalidationMode.TIMESTAMP입니다.

버전 3.2에서 변경: cfile의 기본값을 PEP 3147 [https://www.python.org/dev/peps/pep-3147]과 호환되도록 변경했습니다. 이전 기본값은 file + 'c'(최적화가 활성화되었으면 'o')입니다. 또한 optimize 매개 변수가 추가되었습니다.

버전 3.4에서 변경: 바이트 코드 캐시 파일 쓰기에 importlib를 사용하도록 코드를 변경했습니다. 이것은 파일 생성/기록 의미가 이제 importlib가 하는 것과 일치한다는 것을 의미합니다, 예를 들어 권한, 쓰기-와-이동 의미 등. 또한, cfile이 심볼릭 링크나 비정규 파일이면 FileExistsError가 발생시키는 경고를 추가했습니다.

버전 3.7에서 변경: invalidation_mode 매개 변수가 PEP 552 [https://www.python.org/dev/peps/pep-0552]에 지정된 대로 추가되었습니다. SOURCE_DATE_EPOCH 환경 변수가 설정되면, invalidation_mode는 PycInvalidationMode.CHECKED_HASH로 강제 설정됩니다.

버전 3.7.2에서 변경: SOURCE_DATE_EPOCH 환경 변수는 더는 invalidation_mode 인자의 값을 재정의하지 않으며, 대신 기본값을 결정합니다.

class py_compile.PycInvalidationMode

인터프리터가 바이트 코드 파일이 소스 파일에 대해 최신 버전인지를 결정하는 데 사용할 수 있는 가능한 방법의 열거형입니다. .pyc 파일은 헤더에서 원하는 무효화 모드를 가리킵니다. 파이썬이 실행 시간에 .pyc 파일을 무효로 하는 방법에 대한 자세한 내용은 캐시된 바이트 코드 무효화를 참조하십시오.

버전 3.7에 추가.

TIMESTAMP

.pyc 파일은 파이썬이 실행 시간에 소스 파일의 메타 데이터와 비교하여 .pyc 파일을 재생성해야 하는지를 결정할 소스 파일의 타임스탬프와 크기를 포함합니다.

CHECKED_HASH

.pyc 파일은 파이썬이 실행 시간에 소스와 비교하여 .pyc 파일을 다시 생성해야 하는지를 결정할 소스 파일 내용의 해시를 포함합니다.

UNCHECKED_HASH

CHECKED_HASH와 마찬가지로, .pyc 파일에는 소스 파일 내용의 해시가 포함됩니다. 하지만, 파이썬은 실행 시간에 .pyc 파일이 최신 버전이라고 가정하고, 소스 파일에 대해 .pyc를 전혀 검증하지 않습니다.

이 옵션은 .pycs가 빌드 시스템처럼 파이썬 외부 시스템에 의해 최신 상태로 유지될 때 유용합니다.

py_compile.main(args=None)

여러 소스 파일을 컴파일합니다. args(또는 args가 None이면 명령 줄)로 이름 붙여진 파일이 컴파일되고 결과 바이트 코드가 일반적인 방식으로 캐시 됩니다. 이 함수는 소스 파일을 찾기 위해 디렉터리 구조를 검색하지 않습니다; 명시적으로 이름이 지정된 파일 만 컴파일합니다. '-'가 args의 유일한 매개 변수면, 파일 목록을 표준 입력에서 가져옵니다.

버전 3.2에서 변경: '-'에 대한 지원이 추가되었습니다.

이 모듈을 스크립트로 실행하면, main()이 명령 줄로 이름이 지정된 모든 파일을 컴파일하는 데 사용됩니다. 파일 중 하나를 컴파일할 수 없으면 종료 상태는 0이 아닙니다.

더 보기

모듈 compileall

디렉터리 트리에 있는 모든 파이썬 소스 파일을 컴파일하는 유틸리티.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

파이썬 언어 서비스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

파이썬 언어 서비스 »

|

compileall — 파이썬 라이브러리 바이트 컴파일하기

소스 코드: Lib/compileall.py [https://github.com/python/cpython/tree/3.7/Lib/compileall.py]

이 모듈은 파이썬 라이브러리 설치를 지원하는 몇 가지 유틸리티 함수를 제공합니다. 이 함수는 디렉터리 트리에서 파이썬 소스 파일을 컴파일합니다. 이 모듈을 사용하면 라이브러리 설치 시 캐시 된 바이트 코드 파일을 만들 수 있으므로, 라이브러리 디렉터리에 쓰기 권한이 없는 사용자도 사용할 수 있도록 합니다.

명령 줄 사용

이 모듈은 파이썬 소스를 컴파일하는 스크립트로 작동할 수 있습니다 (python -m compileall을 사용합니다).

directory ...

file ...

위치 인자는 컴파일할 파일이나 소스 파일을 포함하는 디렉터리이며 재귀적으로 탐색 됩니다. 인자가 주어지지 않으면, 명령 줄이 -l <directories from sys.path> 인 것처럼 행동합니다.

-l

서브 디렉터리를 재귀적으로 탐색하지 않고, 이름이 지정되었거나 암시된 디렉터리에 직접 포함된 소스 코드 파일 만 컴파일합니다.

-f

타임스탬프가 최신일 때도 강제로 다시 빌드합니다.

-q

컴파일된 파일 목록을 인쇄하지 않습니다. 한 번 전달하면, 에러 메시지는 여전히 인쇄됩니다. 두 번 전달하면 (-qq), 모든 출력이 억제됩니다.

-d destdir

디렉터리가 컴파일되는 각 파일의 경로 앞에 추가됩니다. 이것은 컴파일 시간 트레이스백에 나타나며, 바이트 코드 파일에 컴파일되어 들어가서, 바이트 코드 파일이 실행되는 시점에 소스 파일이 존재하지 않으면 트레이스백과 기타 메시지에 사용됩니다.

-x regex

regex는 컴파일 대상으로 고려되는 각 파일의 전체 경로를 검색(search)하는 데 사용되며, 정규식이 일치를 생성하면 그 파일을 건너뜁니다.

-i list

파일 list를 읽고 포함된 각 줄을 컴파일할 파일과 디렉터리 목록에 추가합니다. list가 -이면, stdin에서 줄을 읽습니다.

-b

바이트 코드 파일을 레거시 위치 및 이름에 써서, 다른 버전의 파이썬이 만든 바이트 코드 파일을 덮어쓸 수 있습니다. 기본값은 여러 버전의 파이썬의 바이트 코드 파일이 공존할 수 있는 PEP 3147 [https://www.python.org/dev/peps/pep-3147] 위치와 이름에 파일을 쓰는 것입니다.

-r

서브 디렉터리의 최대 재귀 수준을 제어합니다. 이것이 주어지면, -l 옵션은 고려되지 않습니다. python -m compileall <directory> -r 0은 python -m compileall <directory> -l과 동등합니다.

-j N

주어진 디렉터리 내의 파일을 컴파일하는 데 N 작업자를 사용합니다. 0이 사용되면, os.cpu_count()의 결과가 사용됩니다.

--invalidation-mode [timestamp|checked-hash|unchecked-hash]

생성된 바이트 코드 파일이 실행 시간에 무효가 되는 방식을 제어합니다. timestamp 값은 소스 타임스탬프와 크기가 포함된 .pyc 파일이 생성됨을 의미합니다. checked-hash와 unchecked-hash 값은 해시 기반 pyc를 생성합니다. 해시 기반 pyc는 타임스탬프 대신 소스 파일 내용의 해시를 포함합니다. 파이썬이 실행 시간에 바이트 코드 캐시 파일의 유효성을 검사하는 방법에 대한 자세한 내용은 캐시된 바이트 코드 무효화를 참조하십시오. 기본값은 SOURCE_DATE_EPOCH 환경 변수가 설정되지 않으면 timestamp이고, SOURCE_DATE_EPOCH 환경 변수가 설정되면 checked-hash입니다.

버전 3.2에서 변경: -i, -b 및 -h 옵션이 추가되었습니다.

버전 3.5에서 변경: -j, -r 및 -qq 옵션이 추가되었습니다. -q 옵션이 다중 수준 값으로 변경되었습니다. -b는 항상 .pyc로 끝나는 바이트 코드 파일을 생성하며, 결코 .pyo를 생성하지 않습니다.

버전 3.7에서 변경: --invalidation-mode 옵션이 추가되었습니다.

compile() 함수가 사용하는 최적화 수준을 제어하는 명령 줄 옵션은 없습니다. 파이썬 인터프리터 자신이 그 옵션을 제공하고 있기 때문입니다: python -O -m compileall.

공용 함수

compileall.compile_dir(dir, maxlevels=10, ddir=None, force=False, rx=None, quiet=0, legacy=False, optimize=-1, workers=1, invalidation_mode=py_compile.PycInvalidationMode.TIMESTAMP)

dir로 명명된 디렉터리 트리를 재귀적으로 탐색해 내려가면서, 발견되는 모든 .py 파일을 컴파일합니다. 모든 파일이 성공적으로 컴파일되면 참값을 반환하고, 그렇지 않으면 거짓값을 반환합니다.

maxlevels 매개 변수는 재귀의 깊이를 제한하는 데 사용됩니다; 기본값은 10입니다.

ddir이 주어지면, 컴파일 시간 트레이스백에서 사용하기 위해 컴파일되는 각 파일의 경로 앞에 추가되며, 바이트 코드 파일에 컴파일되어 들어가서, 바이트 코드 파일이 실행되는 시점에 소스 파일이 존재하지 않으면 트레이스백과 기타 메시지에 사용됩니다.

force가 참이면, 타임스탬프가 최신일 때도 모듈이 다시 컴파일됩니다.

rx가 주어지면, 컴파일 대상으로 고려되는 각 파일의 전체 경로로 그것의 search 메서드를 호출하고, 참값을 반환하면 그 파일을 건너뜁니다.

quiet가 False나 0(기본값)이면, 파일명과 기타 정보가 표준 출력에 인쇄됩니다. 1로 설정하면, 에러만 인쇄됩니다. 2로 설정하면, 모든 출력이 억제됩니다.

legacy가 참이면, 바이트 코드 파일을 레거시 위치 및 이름에 써서, 다른 버전의 파이썬이 만든 바이트 코드 파일을 덮어쓸 수 있습니다. 기본값은 여러 버전의 파이썬의 바이트 코드 파일이 공존할 수 있는 PEP 3147 [https://www.python.org/dev/peps/pep-3147] 위치와 이름에 파일을 쓰는 것입니다.

optimize는 컴파일러의 최적화 수준을 지정합니다. 내장 compile() 함수로 전달됩니다.

The argument workers specifies how many workers are used to compile files in parallel. The default is to not use multiple workers. If the platform can’t use multiple workers and workers argument is given, then sequential compilation will be used as a fallback. If workers is lower than 0, a ValueError will be raised.

invalidation_mode는 py_compile.PycInvalidationMode 열거형의 멤버여야 하며 실행 시간에 생성된 pyc가 무효가 되는 방식을 제어합니다.

버전 3.2에서 변경: legacy와 optimize 매개 변수가 추가되었습니다.

버전 3.5에서 변경: workers 매개 변수가 추가되었습니다.

버전 3.5에서 변경: quiet 매개 변수가 다중 수준 값으로 변경되었습니다.

버전 3.5에서 변경: legacy 매개 변수는 optimize 값과 상관없이 .pyo 파일이 아니라 .pyc 파일 만 기록합니다.

버전 3.6에서 변경: 경로류 객체를 받아들입니다.

버전 3.7에서 변경: invalidation_mode 매개 변수가 추가되었습니다.

compileall.compile_file(fullname, ddir=None, force=False, rx=None, quiet=0, legacy=False, optimize=-1, invalidation_mode=py_compile.PycInvalidationMode.TIMESTAMP)

경로 fullname의 파일을 컴파일합니다. 파일이 성공적으로 컴파일되면 참값을 반환하고, 그렇지 않으면 거짓값을 반환합니다.

ddir이 주어지면, 컴파일 시간 트레이스백에서 사용하기 위해 컴파일되는 파일의 경로 앞에 추가되며, 바이트 코드 파일에 컴파일되어 들어가서, 바이트 코드 파일이 실행되는 시점에 소스 파일이 존재하지 않으면 트레이스백과 기타 메시지에 사용됩니다.

rx가 주어지면, 컴파일 중인 파일의 전체 경로가 그것의 search 메서드로 전달되고, 참값을 반환하면, 파일이 컴파일되지 않고 True가 반환됩니다.

quiet가 False나 0(기본값)이면, 파일명과 기타 정보가 표준 출력에 인쇄됩니다. 1로 설정하면, 에러만 인쇄됩니다. 2로 설정하면, 모든 출력이 억제됩니다.

legacy가 참이면, 바이트 코드 파일을 레거시 위치 및 이름에 써서, 다른 버전의 파이썬이 만든 바이트 코드 파일을 덮어쓸 수 있습니다. 기본값은 여러 버전의 파이썬의 바이트 코드 파일이 공존할 수 있는 PEP 3147 [https://www.python.org/dev/peps/pep-3147] 위치와 이름에 파일을 쓰는 것입니다.

optimize는 컴파일러의 최적화 수준을 지정합니다. 내장 compile() 함수로 전달됩니다.

invalidation_mode는 py_compile.PycInvalidationMode 열거형의 멤버여야 하며 실행 시간에 생성된 pyc가 무효가 되는 방식을 제어합니다.

버전 3.2에 추가.

버전 3.5에서 변경: quiet 매개 변수가 다중 수준 값으로 변경되었습니다.

버전 3.5에서 변경: legacy 매개 변수는 optimize 값과 상관없이 .pyo 파일이 아니라 .pyc 파일 만 기록합니다.

버전 3.7에서 변경: invalidation_mode 매개 변수가 추가되었습니다.

compileall.compile_path(skip_curdir=True, maxlevels=0, force=False, quiet=0, legacy=False, optimize=-1, invalidation_mode=py_compile.PycInvalidationMode.TIMESTAMP)

sys.path에서 발견된 모든 .py 파일을 바이트 컴파일합니다. 모든 파일이 성공적으로 컴파일되면 참값을 반환하고, 그렇지 않으면 거짓값을 반환합니다.

skip_curdir가 참(기본값)이면, 현재 디렉터리가 검색에 포함되지 않습니다. 다른 모든 매개 변수는 compile_dir() 함수에 전달됩니다. 다른 컴파일 함수와 달리, maxlevels의 기본값은 0임에 유의하십시오.

버전 3.2에서 변경: legacy와 optimize 매개 변수가 추가되었습니다.

버전 3.5에서 변경: quiet 매개 변수가 다중 수준 값으로 변경되었습니다.

버전 3.5에서 변경: legacy 매개 변수는 optimize 값과 상관없이 .pyo 파일이 아니라 .pyc 파일 만 기록합니다.

버전 3.7에서 변경: invalidation_mode 매개 변수가 추가되었습니다.

Lib/ 서브 디렉터리와 그것의 모든 서브 디렉터리에 있는 모든 .py 파일을 강제로 다시 컴파일하려면 다음과 같이 합니다:

import compileall

compileall.compile_dir('Lib/', force=True)

# Perform same compilation, excluding files in .svn directories.
import re
compileall.compile_dir('Lib/', rx=re.compile(r'[/\\][.]svn'), force=True)

# pathlib.Path objects can also be used.
import pathlib
compileall.compile_dir(pathlib.Path('Lib/'), force=True)

더 보기

모듈 py_compile

단일 소스 파일을 바이트 컴파일합니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

파이썬 언어 서비스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

파이썬 언어 서비스 »

|

dis — Disassembler for Python bytecode

Source code: Lib/dis.py [https://github.com/python/cpython/tree/3.7/Lib/dis.py]

The dis module supports the analysis of CPython bytecode by disassembling it. The CPython bytecode which this module takes as an input is defined in the file Include/opcode.h and used by the compiler and the interpreter.

CPython implementation detail: Bytecode is an implementation detail of the CPython interpreter. No guarantees are made that bytecode will not be added, removed, or changed between versions of Python. Use of this module should not be considered to work across Python VMs or Python releases.

버전 3.6에서 변경: Use 2 bytes for each instruction. Previously the number of bytes varied by instruction.

Example: Given the function myfunc():

def myfunc(alist):
    return len(alist)

the following command can be used to display the disassembly of myfunc():

>>> dis.dis(myfunc)
  2           0 LOAD_GLOBAL              0 (len)
              2 LOAD_FAST                0 (alist)
              4 CALL_FUNCTION            1
              6 RETURN_VALUE

(The “2” is a line number).

Bytecode analysis

버전 3.4에 추가.

The bytecode analysis API allows pieces of Python code to be wrapped in a Bytecode object that provides easy access to details of the compiled code.

class dis.Bytecode(x, *, first_line=None, current_offset=None)

Analyse the bytecode corresponding to a function, generator, asynchronous generator, coroutine, method, string of source code, or a code object (as returned by compile()).

This is a convenience wrapper around many of the functions listed below, most notably get_instructions(), as iterating over a Bytecode instance yields the bytecode operations as Instruction instances.

If first_line is not None, it indicates the line number that should be reported for the first source line in the disassembled code. Otherwise, the source line information (if any) is taken directly from the disassembled code object.

If current_offset is not None, it refers to an instruction offset in the disassembled code. Setting this means dis() will display a “current instruction” marker against the specified opcode.

classmethod from_traceback(tb)

Construct a Bytecode instance from the given traceback, setting current_offset to the instruction responsible for the exception.

codeobj

The compiled code object.

first_line

The first source line of the code object (if available)

dis()

Return a formatted view of the bytecode operations (the same as printed by dis.dis(), but returned as a multi-line string).

info()

Return a formatted multi-line string with detailed information about the code object, like code_info().

버전 3.7에서 변경: This can now handle coroutine and asynchronous generator objects.

Example:

>>> bytecode = dis.Bytecode(myfunc)
>>> for instr in bytecode:
...     print(instr.opname)
...
LOAD_GLOBAL
LOAD_FAST
CALL_FUNCTION
RETURN_VALUE

Analysis functions

The dis module also defines the following analysis functions that convert the input directly to the desired output. They can be useful if only a single operation is being performed, so the intermediate analysis object isn’t useful:

dis.code_info(x)

Return a formatted multi-line string with detailed code object information for the supplied function, generator, asynchronous generator, coroutine, method, source code string or code object.

Note that the exact contents of code info strings are highly implementation dependent and they may change arbitrarily across Python VMs or Python releases.

버전 3.2에 추가.

버전 3.7에서 변경: This can now handle coroutine and asynchronous generator objects.

dis.show_code(x, *, file=None)

Print detailed code object information for the supplied function, method, source code string or code object to file (or sys.stdout if file is not specified).

This is a convenient shorthand for print(code_info(x), file=file), intended for interactive exploration at the interpreter prompt.

버전 3.2에 추가.

버전 3.4에서 변경: Added file parameter.

dis.dis(x=None, *, file=None, depth=None)

Disassemble the x object. x can denote either a module, a class, a method, a function, a generator, an asynchronous generator, a coroutine, a code object, a string of source code or a byte sequence of raw bytecode. For a module, it disassembles all functions. For a class, it disassembles all methods (including class and static methods). For a code object or sequence of raw bytecode, it prints one line per bytecode instruction. It also recursively disassembles nested code objects (the code of comprehensions, generator expressions and nested functions, and the code used for building nested classes). Strings are first compiled to code objects with the compile() built-in function before being disassembled. If no object is provided, this function disassembles the last traceback.

The disassembly is written as text to the supplied file argument if provided and to sys.stdout otherwise.

The maximal depth of recursion is limited by depth unless it is None. depth=0 means no recursion.

버전 3.4에서 변경: Added file parameter.

버전 3.7에서 변경: Implemented recursive disassembling and added depth parameter.

버전 3.7에서 변경: This can now handle coroutine and asynchronous generator objects.

dis.distb(tb=None, *, file=None)

Disassemble the top-of-stack function of a traceback, using the last traceback if none was passed. The instruction causing the exception is indicated.

The disassembly is written as text to the supplied file argument if provided and to sys.stdout otherwise.

버전 3.4에서 변경: Added file parameter.

dis.disassemble(code, lasti=-1, *, file=None)

dis.disco(code, lasti=-1, *, file=None)

Disassemble a code object, indicating the last instruction if lasti was provided. The output is divided in the following columns:

the line number, for the first instruction of each line

the current instruction, indicated as -->,

a labelled instruction, indicated with >>,

the address of the instruction,

the operation code name,

operation parameters, and

interpretation of the parameters in parentheses.

The parameter interpretation recognizes local and global variable names, constant values, branch targets, and compare operators.

The disassembly is written as text to the supplied file argument if provided and to sys.stdout otherwise.

버전 3.4에서 변경: Added file parameter.

dis.get_instructions(x, *, first_line=None)

Return an iterator over the instructions in the supplied function, method, source code string or code object.

The iterator generates a series of Instruction named tuples giving the details of each operation in the supplied code.

If first_line is not None, it indicates the line number that should be reported for the first source line in the disassembled code. Otherwise, the source line information (if any) is taken directly from the disassembled code object.

버전 3.4에 추가.

dis.findlinestarts(code)

This generator function uses the co_firstlineno and co_lnotab attributes of the code object code to find the offsets which are starts of lines in the source code. They are generated as (offset, lineno) pairs. See Objects/lnotab_notes.txt [https://github.com/python/cpython/tree/3.7/Objects/lnotab_notes.txt] for the co_lnotab format and how to decode it.

버전 3.6에서 변경: Line numbers can be decreasing. Before, they were always increasing.

dis.findlabels(code)

Detect all offsets in the raw compiled bytecode string code which are jump targets, and return a list of these offsets.

dis.stack_effect(opcode[, oparg])

Compute the stack effect of opcode with argument oparg.

버전 3.4에 추가.

Python Bytecode Instructions

The get_instructions() function and Bytecode class provide details of bytecode instructions as Instruction instances:

class dis.Instruction

Details for a bytecode operation

opcode

numeric code for operation, corresponding to the opcode values listed below and the bytecode values in the Opcode collections.

opname

human readable name for operation

arg

numeric argument to operation (if any), otherwise None

argval

resolved arg value (if known), otherwise same as arg

argrepr

human readable description of operation argument

offset

start index of operation within bytecode sequence

starts_line

line started by this opcode (if any), otherwise None

is_jump_target

True if other code jumps to here, otherwise False

버전 3.4에 추가.

The Python compiler currently generates the following bytecode instructions.

General instructions

NOP

Do nothing code. Used as a placeholder by the bytecode optimizer.

POP_TOP

Removes the top-of-stack (TOS) item.

ROT_TWO

Swaps the two top-most stack items.

ROT_THREE

Lifts second and third stack item one position up, moves top down to position three.

DUP_TOP

Duplicates the reference on top of the stack.

버전 3.2에 추가.

DUP_TOP_TWO

Duplicates the two references on top of the stack, leaving them in the same order.

버전 3.2에 추가.

Unary operations

Unary operations take the top of the stack, apply the operation, and push the result back on the stack.

UNARY_POSITIVE

Implements TOS = +TOS.

UNARY_NEGATIVE

Implements TOS = -TOS.

UNARY_NOT

Implements TOS = not TOS.

UNARY_INVERT

Implements TOS = ~TOS.

GET_ITER

Implements TOS = iter(TOS).

GET_YIELD_FROM_ITER

If TOS is a generator iterator or coroutine object it is left as is. Otherwise, implements TOS = iter(TOS).

버전 3.5에 추가.

Binary operations

Binary operations remove the top of the stack (TOS) and the second top-most stack item (TOS1) from the stack. They perform the operation, and put the result back on the stack.

BINARY_POWER

Implements TOS = TOS1 ** TOS.

BINARY_MULTIPLY

Implements TOS = TOS1 * TOS.

BINARY_MATRIX_MULTIPLY

Implements TOS = TOS1 @ TOS.

버전 3.5에 추가.

BINARY_FLOOR_DIVIDE

Implements TOS = TOS1 // TOS.

BINARY_TRUE_DIVIDE

Implements TOS = TOS1 / TOS.

BINARY_MODULO

Implements TOS = TOS1 % TOS.

BINARY_ADD

Implements TOS = TOS1 + TOS.

BINARY_SUBTRACT

Implements TOS = TOS1 - TOS.

BINARY_SUBSCR

Implements TOS = TOS1[TOS].

BINARY_LSHIFT

Implements TOS = TOS1 << TOS.

BINARY_RSHIFT

Implements TOS = TOS1 >> TOS.

BINARY_AND

Implements TOS = TOS1 & TOS.

BINARY_XOR

Implements TOS = TOS1 ^ TOS.

BINARY_OR

Implements TOS = TOS1 | TOS.

In-place operations

In-place operations are like binary operations, in that they remove TOS and TOS1, and push the result back on the stack, but the operation is done in-place when TOS1 supports it, and the resulting TOS may be (but does not have to be) the original TOS1.

INPLACE_POWER

Implements in-place TOS = TOS1 ** TOS.

INPLACE_MULTIPLY

Implements in-place TOS = TOS1 * TOS.

INPLACE_MATRIX_MULTIPLY

Implements in-place TOS = TOS1 @ TOS.

버전 3.5에 추가.

INPLACE_FLOOR_DIVIDE

Implements in-place TOS = TOS1 // TOS.

INPLACE_TRUE_DIVIDE

Implements in-place TOS = TOS1 / TOS.

INPLACE_MODULO

Implements in-place TOS = TOS1 % TOS.

INPLACE_ADD

Implements in-place TOS = TOS1 + TOS.

INPLACE_SUBTRACT

Implements in-place TOS = TOS1 - TOS.

INPLACE_LSHIFT

Implements in-place TOS = TOS1 << TOS.

INPLACE_RSHIFT

Implements in-place TOS = TOS1 >> TOS.

INPLACE_AND

Implements in-place TOS = TOS1 & TOS.

INPLACE_XOR

Implements in-place TOS = TOS1 ^ TOS.

INPLACE_OR

Implements in-place TOS = TOS1 | TOS.

STORE_SUBSCR

Implements TOS1[TOS] = TOS2.

DELETE_SUBSCR

Implements del TOS1[TOS].

Coroutine opcodes

GET_AWAITABLE

Implements TOS = get_awaitable(TOS), where get_awaitable(o) returns o if o is a coroutine object or a generator object with the CO_ITERABLE_COROUTINE flag, or resolves o.__await__.

버전 3.5에 추가.

GET_AITER

Implements TOS = TOS.__aiter__().

버전 3.5에 추가.

버전 3.7에서 변경: Returning awaitable objects from __aiter__ is no longer supported.

GET_ANEXT

Implements PUSH(get_awaitable(TOS.__anext__())). See GET_AWAITABLE for details about get_awaitable

버전 3.5에 추가.

BEFORE_ASYNC_WITH

Resolves __aenter__ and __aexit__ from the object on top of the stack. Pushes __aexit__ and result of __aenter__() to the stack.

버전 3.5에 추가.

SETUP_ASYNC_WITH

Creates a new frame object.

버전 3.5에 추가.

Miscellaneous opcodes

PRINT_EXPR

Implements the expression statement for the interactive mode. TOS is removed from the stack and printed. In non-interactive mode, an expression statement is terminated with POP_TOP.

BREAK_LOOP

Terminates a loop due to a break statement.

CONTINUE_LOOP(target)

Continues a loop due to a continue statement. target is the address to jump to (which should be a FOR_ITER instruction).

SET_ADD(i)

Calls set.add(TOS1[-i], TOS). Used to implement set comprehensions.

LIST_APPEND(i)

Calls list.append(TOS[-i], TOS). Used to implement list comprehensions.

MAP_ADD(i)

Calls dict.setitem(TOS1[-i], TOS, TOS1). Used to implement dict comprehensions.

버전 3.1에 추가.

For all of the SET_ADD, LIST_APPEND and MAP_ADD instructions, while the added value or key/value pair is popped off, the container object remains on the stack so that it is available for further iterations of the loop.

RETURN_VALUE

Returns with TOS to the caller of the function.

YIELD_VALUE

Pops TOS and yields it from a generator.

YIELD_FROM

Pops TOS and delegates to it as a subiterator from a generator.

버전 3.3에 추가.

SETUP_ANNOTATIONS

Checks whether __annotations__ is defined in locals(), if not it is set up to an empty dict. This opcode is only emitted if a class or module body contains variable annotations statically.

버전 3.6에 추가.

IMPORT_STAR

Loads all symbols not starting with '_' directly from the module TOS to the local namespace. The module is popped after loading all names. This opcode implements from module import *.

POP_BLOCK

Removes one block from the block stack. Per frame, there is a stack of blocks, denoting nested loops, try statements, and such.

POP_EXCEPT

Removes one block from the block stack. The popped block must be an exception handler block, as implicitly created when entering an except handler. In addition to popping extraneous values from the frame stack, the last three popped values are used to restore the exception state.

END_FINALLY

Terminates a finally clause. The interpreter recalls whether the exception has to be re-raised, or whether the function returns, and continues with the outer-next block.

LOAD_BUILD_CLASS

Pushes builtins.__build_class__() onto the stack. It is later called by CALL_FUNCTION to construct a class.

SETUP_WITH(delta)

This opcode performs several operations before a with block starts. First, it loads __exit__() from the context manager and pushes it onto the stack for later use by WITH_CLEANUP. Then, __enter__() is called, and a finally block pointing to delta is pushed. Finally, the result of calling the enter method is pushed onto the stack. The next opcode will either ignore it (POP_TOP), or store it in (a) variable(s) (STORE_FAST, STORE_NAME, or UNPACK_SEQUENCE).

버전 3.2에 추가.

WITH_CLEANUP_START

Cleans up the stack when a with statement block exits. TOS is the context manager’s __exit__() bound method. Below TOS are 1–3 values indicating how/why the finally clause was entered:

SECOND = None

(SECOND, THIRD) = (WHY_{RETURN,CONTINUE}), retval

SECOND = WHY_*; no retval below it

(SECOND, THIRD, FOURTH) = exc_info()

In the last case, TOS(SECOND, THIRD, FOURTH) is called, otherwise TOS(None, None, None). Pushes SECOND and result of the call to the stack.

WITH_CLEANUP_FINISH

Pops exception type and result of ‘exit’ function call from the stack.

If the stack represents an exception, and the function call returns a ‘true’ value, this information is “zapped” and replaced with a single WHY_SILENCED to prevent END_FINALLY from re-raising the exception. (But non-local gotos will still be resumed.)

All of the following opcodes use their arguments.

STORE_NAME(namei)

Implements name = TOS. namei is the index of name in the attribute co_names of the code object. The compiler tries to use STORE_FAST or STORE_GLOBAL if possible.

DELETE_NAME(namei)

Implements del name, where namei is the index into co_names attribute of the code object.

UNPACK_SEQUENCE(count)

Unpacks TOS into count individual values, which are put onto the stack right-to-left.

UNPACK_EX(counts)

Implements assignment with a starred target: Unpacks an iterable in TOS into individual values, where the total number of values can be smaller than the number of items in the iterable: one of the new values will be a list of all leftover items.

The low byte of counts is the number of values before the list value, the high byte of counts the number of values after it. The resulting values are put onto the stack right-to-left.

STORE_ATTR(namei)

Implements TOS.name = TOS1, where namei is the index of name in co_names.

DELETE_ATTR(namei)

Implements del TOS.name, using namei as index into co_names.

STORE_GLOBAL(namei)

Works as STORE_NAME, but stores the name as a global.

DELETE_GLOBAL(namei)

Works as DELETE_NAME, but deletes a global name.

LOAD_CONST(consti)

Pushes co_consts[consti] onto the stack.

LOAD_NAME(namei)

Pushes the value associated with co_names[namei] onto the stack.

BUILD_TUPLE(count)

Creates a tuple consuming count items from the stack, and pushes the resulting tuple onto the stack.

BUILD_LIST(count)

Works as BUILD_TUPLE, but creates a list.

BUILD_SET(count)

Works as BUILD_TUPLE, but creates a set.

BUILD_MAP(count)

Pushes a new dictionary object onto the stack. Pops 2 * count items so that the dictionary holds count entries: {..., TOS3: TOS2, TOS1: TOS}.

버전 3.5에서 변경: The dictionary is created from stack items instead of creating an empty dictionary pre-sized to hold count items.

BUILD_CONST_KEY_MAP(count)

The version of BUILD_MAP specialized for constant keys. Pops the top element on the stack which contains a tuple of keys, then starting from TOS1, pops count values to form values in the built dictionary.

버전 3.6에 추가.

BUILD_STRING(count)

Concatenates count strings from the stack and pushes the resulting string onto the stack.

버전 3.6에 추가.

BUILD_TUPLE_UNPACK(count)

Pops count iterables from the stack, joins them in a single tuple, and pushes the result. Implements iterable unpacking in tuple displays (*x, *y, *z).

버전 3.5에 추가.

BUILD_TUPLE_UNPACK_WITH_CALL(count)

This is similar to BUILD_TUPLE_UNPACK, but is used for f(*x, *y, *z) call syntax. The stack item at position count + 1 should be the corresponding callable f.

버전 3.6에 추가.

BUILD_LIST_UNPACK(count)

This is similar to BUILD_TUPLE_UNPACK, but pushes a list instead of tuple. Implements iterable unpacking in list displays [*x, *y, *z].

버전 3.5에 추가.

BUILD_SET_UNPACK(count)

This is similar to BUILD_TUPLE_UNPACK, but pushes a set instead of tuple. Implements iterable unpacking in set displays {*x, *y, *z}.

버전 3.5에 추가.

BUILD_MAP_UNPACK(count)

Pops count mappings from the stack, merges them into a single dictionary, and pushes the result. Implements dictionary unpacking in dictionary displays {**x, **y, **z}.

버전 3.5에 추가.

BUILD_MAP_UNPACK_WITH_CALL(count)

This is similar to BUILD_MAP_UNPACK, but is used for f(**x, **y, **z) call syntax. The stack item at position count + 2 should be the corresponding callable f.

버전 3.5에 추가.

버전 3.6에서 변경: The position of the callable is determined by adding 2 to the opcode argument instead of encoding it in the second byte of the argument.

LOAD_ATTR(namei)

Replaces TOS with getattr(TOS, co_names[namei]).

COMPARE_OP(opname)

Performs a Boolean operation. The operation name can be found in cmp_op[opname].

IMPORT_NAME(namei)

Imports the module co_names[namei]. TOS and TOS1 are popped and provide the fromlist and level arguments of __import__(). The module object is pushed onto the stack. The current namespace is not affected: for a proper import statement, a subsequent STORE_FAST instruction modifies the namespace.

IMPORT_FROM(namei)

Loads the attribute co_names[namei] from the module found in TOS. The resulting object is pushed onto the stack, to be subsequently stored by a STORE_FAST instruction.

JUMP_FORWARD(delta)

Increments bytecode counter by delta.

POP_JUMP_IF_TRUE(target)

If TOS is true, sets the bytecode counter to target. TOS is popped.

버전 3.1에 추가.

POP_JUMP_IF_FALSE(target)

If TOS is false, sets the bytecode counter to target. TOS is popped.

버전 3.1에 추가.

JUMP_IF_TRUE_OR_POP(target)

If TOS is true, sets the bytecode counter to target and leaves TOS on the stack. Otherwise (TOS is false), TOS is popped.

버전 3.1에 추가.

JUMP_IF_FALSE_OR_POP(target)

If TOS is false, sets the bytecode counter to target and leaves TOS on the stack. Otherwise (TOS is true), TOS is popped.

버전 3.1에 추가.

JUMP_ABSOLUTE(target)

Set bytecode counter to target.

FOR_ITER(delta)

TOS is an iterator. Call its __next__() method. If this yields a new value, push it on the stack (leaving the iterator below it). If the iterator indicates it is exhausted TOS is popped, and the byte code counter is incremented by delta.

LOAD_GLOBAL(namei)

Loads the global named co_names[namei] onto the stack.

SETUP_LOOP(delta)

Pushes a block for a loop onto the block stack. The block spans from the current instruction with a size of delta bytes.

SETUP_EXCEPT(delta)

Pushes a try block from a try-except clause onto the block stack. delta points to the first except block.

SETUP_FINALLY(delta)

Pushes a try block from a try-except clause onto the block stack. delta points to the finally block.

LOAD_FAST(var_num)

Pushes a reference to the local co_varnames[var_num] onto the stack.

STORE_FAST(var_num)

Stores TOS into the local co_varnames[var_num].

DELETE_FAST(var_num)

Deletes local co_varnames[var_num].

LOAD_CLOSURE(i)

Pushes a reference to the cell contained in slot i of the cell and free variable storage. The name of the variable is co_cellvars[i] if i is less than the length of co_cellvars. Otherwise it is co_freevars[i - len(co_cellvars)].

LOAD_DEREF(i)

Loads the cell contained in slot i of the cell and free variable storage. Pushes a reference to the object the cell contains on the stack.

LOAD_CLASSDEREF(i)

Much like LOAD_DEREF but first checks the locals dictionary before consulting the cell. This is used for loading free variables in class bodies.

버전 3.4에 추가.

STORE_DEREF(i)

Stores TOS into the cell contained in slot i of the cell and free variable storage.

DELETE_DEREF(i)

Empties the cell contained in slot i of the cell and free variable storage. Used by the del statement.

버전 3.2에 추가.

RAISE_VARARGS(argc)

Raises an exception using one of the 3 forms of the raise statement, depending on the value of argc:

0: raise (re-raise previous exception)

1: raise TOS (raise exception instance or type at TOS)

2: raise TOS1 from TOS (raise exception instance or type at TOS1 with __cause__ set to TOS)

CALL_FUNCTION(argc)

Calls a callable object with positional arguments. argc indicates the number of positional arguments. The top of the stack contains positional arguments, with the right-most argument on top. Below the arguments is a callable object to call. CALL_FUNCTION pops all arguments and the callable object off the stack, calls the callable object with those arguments, and pushes the return value returned by the callable object.

버전 3.6에서 변경: This opcode is used only for calls with positional arguments.

CALL_FUNCTION_KW(argc)

Calls a callable object with positional (if any) and keyword arguments. argc indicates the total number of positional and keyword arguments. The top element on the stack contains a tuple of keyword argument names. Below that are keyword arguments in the order corresponding to the tuple. Below that are positional arguments, with the right-most parameter on top. Below the arguments is a callable object to call. CALL_FUNCTION_KW pops all arguments and the callable object off the stack, calls the callable object with those arguments, and pushes the return value returned by the callable object.

버전 3.6에서 변경: Keyword arguments are packed in a tuple instead of a dictionary, argc indicates the total number of arguments.

CALL_FUNCTION_EX(flags)

Calls a callable object with variable set of positional and keyword arguments. If the lowest bit of flags is set, the top of the stack contains a mapping object containing additional keyword arguments. Below that is an iterable object containing positional arguments and a callable object to call. BUILD_MAP_UNPACK_WITH_CALL and BUILD_TUPLE_UNPACK_WITH_CALL can be used for merging multiple mapping objects and iterables containing arguments. Before the callable is called, the mapping object and iterable object are each “unpacked” and their contents passed in as keyword and positional arguments respectively. CALL_FUNCTION_EX pops all arguments and the callable object off the stack, calls the callable object with those arguments, and pushes the return value returned by the callable object.

버전 3.6에 추가.

LOAD_METHOD(namei)

Loads a method named co_names[namei] from the TOS object. TOS is popped. This bytecode distinguishes two cases: if TOS has a method with the correct name, the bytecode pushes the unbound method and TOS. TOS will be used as the first argument (self) by CALL_METHOD when calling the unbound method. Otherwise, NULL and the object return by the attribute lookup are pushed.

버전 3.7에 추가.

CALL_METHOD(argc)

Calls a method. argc is the number of positional arguments. Keyword arguments are not supported. This opcode is designed to be used with LOAD_METHOD. Positional arguments are on top of the stack. Below them, the two items described in LOAD_METHOD are on the stack (either self and an unbound method object or NULL and an arbitrary callable). All of them are popped and the return value is pushed.

버전 3.7에 추가.

MAKE_FUNCTION(flags)

Pushes a new function object on the stack. From bottom to top, the consumed stack must consist of values if the argument carries a specified flag value

0x01 a tuple of default values for positional-only and positional-or-keyword parameters in positional order

0x02 a dictionary of keyword-only parameters’ default values

0x04 an annotation dictionary

0x08 a tuple containing cells for free variables, making a closure

the code associated with the function (at TOS1)

the qualified name of the function (at TOS)

BUILD_SLICE(argc)

Pushes a slice object on the stack. argc must be 2 or 3. If it is 2, slice(TOS1, TOS) is pushed; if it is 3, slice(TOS2, TOS1, TOS) is pushed. See the slice() built-in function for more information.

EXTENDED_ARG(ext)

Prefixes any opcode which has an argument too big to fit into the default one byte. ext holds an additional byte which act as higher bits in the argument. For each opcode, at most three prefixal EXTENDED_ARG are allowed, forming an argument from two-byte to four-byte.

FORMAT_VALUE(flags)

Used for implementing formatted literal strings (f-strings). Pops an optional fmt_spec from the stack, then a required value. flags is interpreted as follows:

(flags & 0x03) == 0x00: value is formatted as-is.

(flags & 0x03) == 0x01: call str() on value before formatting it.

(flags & 0x03) == 0x02: call repr() on value before formatting it.

(flags & 0x03) == 0x03: call ascii() on value before formatting it.

(flags & 0x04) == 0x04: pop fmt_spec from the stack and use it, else use an empty fmt_spec.

Formatting is performed using PyObject_Format(). The result is pushed on the stack.

버전 3.6에 추가.

HAVE_ARGUMENT

This is not really an opcode. It identifies the dividing line between opcodes which don’t use their argument and those that do (< HAVE_ARGUMENT and >= HAVE_ARGUMENT, respectively).

버전 3.6에서 변경: Now every instruction has an argument, but opcodes < HAVE_ARGUMENT ignore it. Before, only opcodes >= HAVE_ARGUMENT had an argument.

Opcode collections

These collections are provided for automatic introspection of bytecode instructions:

dis.opname

Sequence of operation names, indexable using the bytecode.

dis.opmap

Dictionary mapping operation names to bytecodes.

dis.cmp_op

Sequence of all compare operation names.

dis.hasconst

Sequence of bytecodes that access a constant.

dis.hasfree

Sequence of bytecodes that access a free variable (note that ‘free’ in this context refers to names in the current scope that are referenced by inner scopes or names in outer scopes that are referenced from this scope. It does not include references to global or builtin scopes).

dis.hasname

Sequence of bytecodes that access an attribute by name.

dis.hasjrel

Sequence of bytecodes that have a relative jump target.

dis.hasjabs

Sequence of bytecodes that have an absolute jump target.

dis.haslocal

Sequence of bytecodes that access a local variable.

dis.hascompare

Sequence of bytecodes of Boolean operations.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

파이썬 언어 서비스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

파이썬 언어 서비스 »

|

pickletools — 피클 개발자를 위한 도구

소스 코드: Lib/pickletools.py [https://github.com/python/cpython/tree/3.7/Lib/pickletools.py]

이 모듈은 pickle 모듈의 깊은 세부 사항과 관련된 다양한 상수, 구현에 대한 긴 주석, 그리고 피클 된 데이터를 분석하기 위한 몇 가지 유용한 함수를 포함합니다. 이 모듈의 내용은 pickle에서 작업하는 파이썬 코어 개발자에게 유용합니다; 아마도 pickle 모듈의 일반 사용자는 pickletools 모듈을 적절한 용도를 찾지 못할 것입니다.

명령 줄 사용법

버전 3.2에 추가.

명령 줄에서 호출될 때, python -m pickletools는 하나 이상의 피클 파일의 내용을 역 어셈블합니다. 피클 형식의 세부 사항이 아닌 피클에 저장된 파이썬 객체를 보려면, 대신 -m pickle을 사용하는 것이 좋습니다. 그러나, 검사하려는 피클 파일이 신뢰할 수 없는 소스에서 왔을 때, 피클 바이트 코드를 실행하지 않으므로 -m pickletools가 더 안전한 옵션입니다.

예를 들어, 튜플 (1, 2)가 파일 x.pickle에 피클 된 경우:

$ python -m pickle x.pickle
(1, 2)

$ python -m pickletools x.pickle
    0: \x80 PROTO      3
    2: K    BININT1    1
    4: K    BININT1    2
    6: \x86 TUPLE2
    7: q    BINPUT     0
    9: .    STOP
highest protocol among opcodes = 2

명령 줄 옵션

-a, --annotate

각 줄에 짧은 opcode 설명으로 주석을 답니다.

-o, --output=<file>

출력이 기록되어야 하는 파일의 이름.

-l, --indentlevel=<num>

새 MARK 수준을 들여쓰기하는 공백의 수.

-m, --memo

여러 객체가 역 어셈블될 때, 역 어셈블리 간에 메모를 보존합니다.

-p, --preamble=<preamble>

하나 이상의 피클 파일이 지정될 때, 각 역 어셈블리 전에 주어진 프리앰블을 인쇄합니다.

프로그래밍 인터페이스

pickletools.dis(pickle, out=None, memo=None, indentlevel=4, annotate=0)

피클의 기호적인 역 어셈블리를 기본값이 sys.stdout인 파일류 객체 out으로 출력합니다. pickle는 문자열이나 파일류 객체가 될 수 있습니다. memo는 피클의 메모로 사용될 파이썬 딕셔너리일 수 있습니다; 같은 피클러로 만들어진 여러 피클에 걸쳐 역 어셈블리를 수행하는 데 사용할 수 있습니다. 스트림의 MARK 옵코드로 표시된 연속 수준은 indentlevel개의 스페이스로 들여쓰기 됩니다. 0이 아닌 값이 annotate에 주어지면, 출력의 각 옵코드에 짧은 설명이 주석으로 표시됩니다. annotate 값은 주석을 시작해야 하는 열의 힌트로 사용됩니다.

버전 3.2에 추가: annotate 인자.

pickletools.genops(pickle)

피클의 모든 옵코드에 대해 (opcode, arg, pos) 트리플을 반환하는 이터레이터를 제공합니다. opcode는 OpcodeInfo 클래스의 인스턴스입니다; arg는 옵코드 인자의 파이썬 객체로 디코딩된 값입니다; pos는 이 옵코드의 위치입니다. pickle은 문자열이나 파일류 객체가 될 수 있습니다.

pickletools.optimize(picklestring)

사용되지 않는 PUT 옵코드를 제거한 후 새로운 동등한 피클 문자열을 반환합니다. 최적화된 피클은 더 짧고, 전송 시간이 덜 걸리며, 저장 공간이 덜 필요하고, 역 피클이 더 효율적입니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

파이썬 언어 서비스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

|

기타 서비스

이 장에서 설명하는 모듈은 모든 파이썬 버전에서 사용할 수 있는 기타 서비스를 제공합니다. 다음은 개요입니다:

formatter — Generic output formatting

The Formatter Interface

Formatter Implementations

The Writer Interface

Writer Implementations

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

기타 서비스 »

|

formatter — Generic output formatting

버전 3.4부터 폐지: Due to lack of usage, the formatter module has been deprecated.

This module supports two interface definitions, each with multiple implementations: The formatter interface, and the writer interface which is required by the formatter interface.

Formatter objects transform an abstract flow of formatting events into specific output events on writer objects. Formatters manage several stack structures to allow various properties of a writer object to be changed and restored; writers need not be able to handle relative changes nor any sort of “change back” operation. Specific writer properties which may be controlled via formatter objects are horizontal alignment, font, and left margin indentations. A mechanism is provided which supports providing arbitrary, non-exclusive style settings to a writer as well. Additional interfaces facilitate formatting events which are not reversible, such as paragraph separation.

Writer objects encapsulate device interfaces. Abstract devices, such as file formats, are supported as well as physical devices. The provided implementations all work with abstract devices. The interface makes available mechanisms for setting the properties which formatter objects manage and inserting data into the output.

The Formatter Interface

Interfaces to create formatters are dependent on the specific formatter class being instantiated. The interfaces described below are the required interfaces which all formatters must support once initialized.

One data element is defined at the module level:

formatter.AS_IS

Value which can be used in the font specification passed to the push_font() method described below, or as the new value to any other push_property() method. Pushing the AS_IS value allows the corresponding pop_property() method to be called without having to track whether the property was changed.

The following attributes are defined for formatter instance objects:

formatter.writer

The writer instance with which the formatter interacts.

formatter.end_paragraph(blanklines)

Close any open paragraphs and insert at least blanklines before the next paragraph.

formatter.add_line_break()

Add a hard line break if one does not already exist. This does not break the logical paragraph.

formatter.add_hor_rule(*args, **kw)

Insert a horizontal rule in the output. A hard break is inserted if there is data in the current paragraph, but the logical paragraph is not broken. The arguments and keywords are passed on to the writer’s send_line_break() method.

formatter.add_flowing_data(data)

Provide data which should be formatted with collapsed whitespace. Whitespace from preceding and successive calls to add_flowing_data() is considered as well when the whitespace collapse is performed. The data which is passed to this method is expected to be word-wrapped by the output device. Note that any word-wrapping still must be performed by the writer object due to the need to rely on device and font information.

formatter.add_literal_data(data)

Provide data which should be passed to the writer unchanged. Whitespace, including newline and tab characters, are considered legal in the value of data.

formatter.add_label_data(format, counter)

Insert a label which should be placed to the left of the current left margin. This should be used for constructing bulleted or numbered lists. If the format value is a string, it is interpreted as a format specification for counter, which should be an integer. The result of this formatting becomes the value of the label; if format is not a string it is used as the label value directly. The label value is passed as the only argument to the writer’s send_label_data() method. Interpretation of non-string label values is dependent on the associated writer.

Format specifications are strings which, in combination with a counter value, are used to compute label values. Each character in the format string is copied to the label value, with some characters recognized to indicate a transform on the counter value. Specifically, the character '1' represents the counter value formatter as an Arabic number, the characters 'A' and 'a' represent alphabetic representations of the counter value in upper and lower case, respectively, and 'I' and 'i' represent the counter value in Roman numerals, in upper and lower case. Note that the alphabetic and roman transforms require that the counter value be greater than zero.

formatter.flush_softspace()

Send any pending whitespace buffered from a previous call to add_flowing_data() to the associated writer object. This should be called before any direct manipulation of the writer object.

formatter.push_alignment(align)

Push a new alignment setting onto the alignment stack. This may be AS_IS if no change is desired. If the alignment value is changed from the previous setting, the writer’s new_alignment() method is called with the align value.

formatter.pop_alignment()

Restore the previous alignment.

formatter.push_font((size, italic, bold, teletype))

Change some or all font properties of the writer object. Properties which are not set to AS_IS are set to the values passed in while others are maintained at their current settings. The writer’s new_font() method is called with the fully resolved font specification.

formatter.pop_font()

Restore the previous font.

formatter.push_margin(margin)

Increase the number of left margin indentations by one, associating the logical tag margin with the new indentation. The initial margin level is 0. Changed values of the logical tag must be true values; false values other than AS_IS are not sufficient to change the margin.

formatter.pop_margin()

Restore the previous margin.

formatter.push_style(*styles)

Push any number of arbitrary style specifications. All styles are pushed onto the styles stack in order. A tuple representing the entire stack, including AS_IS values, is passed to the writer’s new_styles() method.

formatter.pop_style(n=1)

Pop the last n style specifications passed to push_style(). A tuple representing the revised stack, including AS_IS values, is passed to the writer’s new_styles() method.

formatter.set_spacing(spacing)

Set the spacing style for the writer.

formatter.assert_line_data(flag=1)

Inform the formatter that data has been added to the current paragraph out-of-band. This should be used when the writer has been manipulated directly. The optional flag argument can be set to false if the writer manipulations produced a hard line break at the end of the output.

Formatter Implementations

Two implementations of formatter objects are provided by this module. Most applications may use one of these classes without modification or subclassing.

class formatter.NullFormatter(writer=None)

A formatter which does nothing. If writer is omitted, a NullWriter instance is created. No methods of the writer are called by NullFormatter instances. Implementations should inherit from this class if implementing a writer interface but don’t need to inherit any implementation.

class formatter.AbstractFormatter(writer)

The standard formatter. This implementation has demonstrated wide applicability to many writers, and may be used directly in most circumstances. It has been used to implement a full-featured World Wide Web browser.

The Writer Interface

Interfaces to create writers are dependent on the specific writer class being instantiated. The interfaces described below are the required interfaces which all writers must support once initialized. Note that while most applications can use the AbstractFormatter class as a formatter, the writer must typically be provided by the application.

writer.flush()

Flush any buffered output or device control events.

writer.new_alignment(align)

Set the alignment style. The align value can be any object, but by convention is a string or None, where None indicates that the writer’s “preferred” alignment should be used. Conventional align values are 'left', 'center', 'right', and 'justify'.

writer.new_font(font)

Set the font style. The value of font will be None, indicating that the device’s default font should be used, or a tuple of the form (size, italic, bold, teletype). Size will be a string indicating the size of font that should be used; specific strings and their interpretation must be defined by the application. The italic, bold, and teletype values are Boolean values specifying which of those font attributes should be used.

writer.new_margin(margin, level)

Set the margin level to the integer level and the logical tag to margin. Interpretation of the logical tag is at the writer’s discretion; the only restriction on the value of the logical tag is that it not be a false value for non-zero values of level.

writer.new_spacing(spacing)

Set the spacing style to spacing.

writer.new_styles(styles)

Set additional styles. The styles value is a tuple of arbitrary values; the value AS_IS should be ignored. The styles tuple may be interpreted either as a set or as a stack depending on the requirements of the application and writer implementation.

writer.send_line_break()

Break the current line.

writer.send_paragraph(blankline)

Produce a paragraph separation of at least blankline blank lines, or the equivalent. The blankline value will be an integer. Note that the implementation will receive a call to send_line_break() before this call if a line break is needed; this method should not include ending the last line of the paragraph. It is only responsible for vertical spacing between paragraphs.

writer.send_hor_rule(*args, **kw)

Display a horizontal rule on the output device. The arguments to this method are entirely application- and writer-specific, and should be interpreted with care. The method implementation may assume that a line break has already been issued via send_line_break().

writer.send_flowing_data(data)

Output character data which may be word-wrapped and re-flowed as needed. Within any sequence of calls to this method, the writer may assume that spans of multiple whitespace characters have been collapsed to single space characters.

writer.send_literal_data(data)

Output character data which has already been formatted for display. Generally, this should be interpreted to mean that line breaks indicated by newline characters should be preserved and no new line breaks should be introduced. The data may contain embedded newline and tab characters, unlike data provided to the send_formatted_data() interface.

writer.send_label_data(data)

Set data to the left of the current left margin, if possible. The value of data is not restricted; treatment of non-string values is entirely application- and writer-dependent. This method will only be called at the beginning of a line.

Writer Implementations

Three implementations of the writer object interface are provided as examples by this module. Most applications will need to derive new writer classes from the NullWriter class.

class formatter.NullWriter

A writer which only provides the interface definition; no actions are taken on any methods. This should be the base class for all writers which do not need to inherit any implementation methods.

class formatter.AbstractWriter

A writer which can be used in debugging formatters, but not much else. Each method simply announces itself by printing its name and arguments on standard output.

class formatter.DumbWriter(file=None, maxcol=72)

Simple writer class which writes output on the file object passed in as file or, if file is omitted, on standard output. The output is simply word-wrapped to the number of columns specified by maxcol. This class is suitable for reflowing a sequence of paragraphs.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

기타 서비스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

|

MS 윈도우 특정 서비스

이 장에서는 MS 윈도우 플랫폼에서만 사용 가능한 모듈에 관해 설명합니다.

msilib — Read and write Microsoft Installer files

Database Objects

View Objects

Summary Information Objects

Record Objects

Errors

CAB Objects

Directory Objects

Features

GUI classes

Precomputed tables

msvcrt — MS VC++ 런타임의 유용한 루틴

파일 연산

콘솔 I/O

기타 함수

winreg — Windows registry access

Functions

Constants

HKEY_* Constants

Access Rights

64-bit Specific

Value Types

Registry Handle Objects

winsound — 윈도우용 소리 재생 인터페이스

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

MS 윈도우 특정 서비스 »

|

msilib — Read and write Microsoft Installer files

Source code: Lib/msilib/__init__.py [https://github.com/python/cpython/tree/3.7/Lib/msilib/__init__.py]

The msilib supports the creation of Microsoft Installer (.msi) files. Because these files often contain an embedded “cabinet” file (.cab), it also exposes an API to create CAB files. Support for reading .cab files is currently not implemented; read support for the .msi database is possible.

This package aims to provide complete access to all tables in an .msi file, therefore, it is a fairly low-level API. Two primary applications of this package are the distutils command bdist_msi, and the creation of Python installer package itself (although that currently uses a different version of msilib).

The package contents can be roughly split into four parts: low-level CAB routines, low-level MSI routines, higher-level MSI routines, and standard table structures.

msilib.FCICreate(cabname, files)

Create a new CAB file named cabname. files must be a list of tuples, each containing the name of the file on disk, and the name of the file inside the CAB file.

The files are added to the CAB file in the order they appear in the list. All files are added into a single CAB file, using the MSZIP compression algorithm.

Callbacks to Python for the various steps of MSI creation are currently not exposed.

msilib.UuidCreate()

Return the string representation of a new unique identifier. This wraps the Windows API functions UuidCreate() and UuidToString().

msilib.OpenDatabase(path, persist)

Return a new database object by calling MsiOpenDatabase. path is the file name of the MSI file; persist can be one of the constants MSIDBOPEN_CREATEDIRECT, MSIDBOPEN_CREATE, MSIDBOPEN_DIRECT, MSIDBOPEN_READONLY, or MSIDBOPEN_TRANSACT, and may include the flag MSIDBOPEN_PATCHFILE. See the Microsoft documentation for the meaning of these flags; depending on the flags, an existing database is opened, or a new one created.

msilib.CreateRecord(count)

Return a new record object by calling MSICreateRecord(). count is the number of fields of the record.

msilib.init_database(name, schema, ProductName, ProductCode, ProductVersion, Manufacturer)

Create and return a new database name, initialize it with schema, and set the properties ProductName, ProductCode, ProductVersion, and Manufacturer.

schema must be a module object containing tables and _Validation_records attributes; typically, msilib.schema should be used.

The database will contain just the schema and the validation records when this function returns.

msilib.add_data(database, table, records)

Add all records to the table named table in database.

The table argument must be one of the predefined tables in the MSI schema, e.g. 'Feature', 'File', 'Component', 'Dialog', 'Control', etc.

records should be a list of tuples, each one containing all fields of a record according to the schema of the table. For optional fields, None can be passed.

Field values can be ints, strings, or instances of the Binary class.

class msilib.Binary(filename)

Represents entries in the Binary table; inserting such an object using add_data() reads the file named filename into the table.

msilib.add_tables(database, module)

Add all table content from module to database. module must contain an attribute tables listing all tables for which content should be added, and one attribute per table that has the actual content.

This is typically used to install the sequence tables.

msilib.add_stream(database, name, path)

Add the file path into the _Stream table of database, with the stream name name.

msilib.gen_uuid()

Return a new UUID, in the format that MSI typically requires (i.e. in curly braces, and with all hexdigits in upper-case).

더 보기

FCICreate [https://msdn.microsoft.com/en-us/library/bb432265.aspx] UuidCreate [https://msdn.microsoft.com/en-us/library/windows/desktop/aa379205.aspx] UuidToString [https://msdn.microsoft.com/en-us/library/windows/desktop/aa379352.aspx]

Database Objects

Database.OpenView(sql)

Return a view object, by calling MSIDatabaseOpenView(). sql is the SQL statement to execute.

Database.Commit()

Commit the changes pending in the current transaction, by calling MSIDatabaseCommit().

Database.GetSummaryInformation(count)

Return a new summary information object, by calling MsiGetSummaryInformation(). count is the maximum number of updated values.

Database.Close()

Close the database object, through MsiCloseHandle().

버전 3.7에 추가.

더 보기

MSIDatabaseOpenView [https://msdn.microsoft.com/en-us/library/windows/desktop/aa370082.aspx] MSIDatabaseCommit [https://msdn.microsoft.com/en-us/library/windows/desktop/aa370075.aspx] MSIGetSummaryInformation [https://msdn.microsoft.com/en-us/library/windows/desktop/aa370301.aspx] MsiCloseHandle [https://msdn.microsoft.com/en-us/library/windows/desktop/aa370067.aspx]

View Objects

View.Execute(params)

Execute the SQL query of the view, through MSIViewExecute(). If params is not None, it is a record describing actual values of the parameter tokens in the query.

View.GetColumnInfo(kind)

Return a record describing the columns of the view, through calling MsiViewGetColumnInfo(). kind can be either MSICOLINFO_NAMES or MSICOLINFO_TYPES.

View.Fetch()

Return a result record of the query, through calling MsiViewFetch().

View.Modify(kind, data)

Modify the view, by calling MsiViewModify(). kind can be one of MSIMODIFY_SEEK, MSIMODIFY_REFRESH, MSIMODIFY_INSERT, MSIMODIFY_UPDATE, MSIMODIFY_ASSIGN, MSIMODIFY_REPLACE, MSIMODIFY_MERGE, MSIMODIFY_DELETE, MSIMODIFY_INSERT_TEMPORARY, MSIMODIFY_VALIDATE, MSIMODIFY_VALIDATE_NEW, MSIMODIFY_VALIDATE_FIELD, or MSIMODIFY_VALIDATE_DELETE.

data must be a record describing the new data.

View.Close()

Close the view, through MsiViewClose().

더 보기

MsiViewExecute [https://msdn.microsoft.com/en-us/library/windows/desktop/aa370513.aspx] MSIViewGetColumnInfo [https://msdn.microsoft.com/en-us/library/windows/desktop/aa370516.aspx] MsiViewFetch [https://msdn.microsoft.com/en-us/library/windows/desktop/aa370514.aspx] MsiViewModify [https://msdn.microsoft.com/en-us/library/windows/desktop/aa370519.aspx] MsiViewClose [https://msdn.microsoft.com/en-us/library/windows/desktop/aa370510.aspx]

Summary Information Objects

SummaryInformation.GetProperty(field)

Return a property of the summary, through MsiSummaryInfoGetProperty(). field is the name of the property, and can be one of the constants PID_CODEPAGE, PID_TITLE, PID_SUBJECT, PID_AUTHOR, PID_KEYWORDS, PID_COMMENTS, PID_TEMPLATE, PID_LASTAUTHOR, PID_REVNUMBER, PID_LASTPRINTED, PID_CREATE_DTM, PID_LASTSAVE_DTM, PID_PAGECOUNT, PID_WORDCOUNT, PID_CHARCOUNT, PID_APPNAME, or PID_SECURITY.

SummaryInformation.GetPropertyCount()

Return the number of summary properties, through MsiSummaryInfoGetPropertyCount().

SummaryInformation.SetProperty(field, value)

Set a property through MsiSummaryInfoSetProperty(). field can have the same values as in GetProperty(), value is the new value of the property. Possible value types are integer and string.

SummaryInformation.Persist()

Write the modified properties to the summary information stream, using MsiSummaryInfoPersist().

더 보기

MsiSummaryInfoGetProperty [https://msdn.microsoft.com/en-us/library/windows/desktop/aa370409.aspx] MsiSummaryInfoGetPropertyCount [https://msdn.microsoft.com/en-us/library/windows/desktop/aa370488.aspx] MsiSummaryInfoSetProperty [https://msdn.microsoft.com/en-us/library/windows/desktop/aa370491.aspx] MsiSummaryInfoPersist [https://msdn.microsoft.com/en-us/library/windows/desktop/aa370490.aspx]

Record Objects

Record.GetFieldCount()

Return the number of fields of the record, through MsiRecordGetFieldCount().

Record.GetInteger(field)

Return the value of field as an integer where possible. field must be an integer.

Record.GetString(field)

Return the value of field as a string where possible. field must be an integer.

Record.SetString(field, value)

Set field to value through MsiRecordSetString(). field must be an integer; value a string.

Record.SetStream(field, value)

Set field to the contents of the file named value, through MsiRecordSetStream(). field must be an integer; value a string.

Record.SetInteger(field, value)

Set field to value through MsiRecordSetInteger(). Both field and value must be an integer.

Record.ClearData()

Set all fields of the record to 0, through MsiRecordClearData().

더 보기

MsiRecordGetFieldCount [https://msdn.microsoft.com/en-us/library/windows/desktop/aa370366.aspx] MsiRecordSetString [https://msdn.microsoft.com/en-us/library/windows/desktop/aa370373.aspx] MsiRecordSetStream [https://msdn.microsoft.com/en-us/library/windows/desktop/aa370372.aspx] MsiRecordSetInteger [https://msdn.microsoft.com/en-us/library/windows/desktop/aa370371.aspx] MsiRecordClearData [https://msdn.microsoft.com/en-us/library/windows/desktop/aa370364.aspx]

Errors

All wrappers around MSI functions raise MSIError; the string inside the exception will contain more detail.

CAB Objects

class msilib.CAB(name)

The class CAB represents a CAB file. During MSI construction, files will be added simultaneously to the Files table, and to a CAB file. Then, when all files have been added, the CAB file can be written, then added to the MSI file.

name is the name of the CAB file in the MSI file.

append(full, file, logical)

Add the file with the pathname full to the CAB file, under the name logical. If there is already a file named logical, a new file name is created.

Return the index of the file in the CAB file, and the new name of the file inside the CAB file.

commit(database)

Generate a CAB file, add it as a stream to the MSI file, put it into the Media table, and remove the generated file from the disk.

Directory Objects

class msilib.Directory(database, cab, basedir, physical, logical, default[, componentflags])

Create a new directory in the Directory table. There is a current component at each point in time for the directory, which is either explicitly created through start_component(), or implicitly when files are added for the first time. Files are added into the current component, and into the cab file. To create a directory, a base directory object needs to be specified (can be None), the path to the physical directory, and a logical directory name. default specifies the DefaultDir slot in the directory table. componentflags specifies the default flags that new components get.

start_component(component=None, feature=None, flags=None, keyfile=None, uuid=None)

Add an entry to the Component table, and make this component the current component for this directory. If no component name is given, the directory name is used. If no feature is given, the current feature is used. If no flags are given, the directory’s default flags are used. If no keyfile is given, the KeyPath is left null in the Component table.

add_file(file, src=None, version=None, language=None)

Add a file to the current component of the directory, starting a new one if there is no current component. By default, the file name in the source and the file table will be identical. If the src file is specified, it is interpreted relative to the current directory. Optionally, a version and a language can be specified for the entry in the File table.

glob(pattern, exclude=None)

Add a list of files to the current component as specified in the glob pattern. Individual files can be excluded in the exclude list.

remove_pyc()

Remove .pyc files on uninstall.

더 보기

Directory Table [https://msdn.microsoft.com/en-us/library/windows/desktop/aa368295.aspx] File Table [https://msdn.microsoft.com/en-us/library/windows/desktop/aa368596.aspx] Component Table [https://msdn.microsoft.com/en-us/library/windows/desktop/aa368007.aspx] FeatureComponents Table [https://msdn.microsoft.com/en-us/library/windows/desktop/aa368579.aspx]

Features

class msilib.Feature(db, id, title, desc, display, level=1, parent=None, directory=None, attributes=0)

Add a new record to the Feature table, using the values id, parent.id, title, desc, display, level, directory, and attributes. The resulting feature object can be passed to the start_component() method of Directory.

set_current()

Make this feature the current feature of msilib. New components are automatically added to the default feature, unless a feature is explicitly specified.

더 보기

Feature Table [https://msdn.microsoft.com/en-us/library/windows/desktop/aa368585.aspx]

GUI classes

msilib provides several classes that wrap the GUI tables in an MSI database. However, no standard user interface is provided; use bdist_msi to create MSI files with a user-interface for installing Python packages.

class msilib.Control(dlg, name)

Base class of the dialog controls. dlg is the dialog object the control belongs to, and name is the control’s name.

event(event, argument, condition=1, ordering=None)

Make an entry into the ControlEvent table for this control.

mapping(event, attribute)

Make an entry into the EventMapping table for this control.

condition(action, condition)

Make an entry into the ControlCondition table for this control.

class msilib.RadioButtonGroup(dlg, name, property)

Create a radio button control named name. property is the installer property that gets set when a radio button is selected.

add(name, x, y, width, height, text, value=None)

Add a radio button named name to the group, at the coordinates x, y, width, height, and with the label text. If value is None, it defaults to name.

class msilib.Dialog(db, name, x, y, w, h, attr, title, first, default, cancel)

Return a new Dialog object. An entry in the Dialog table is made, with the specified coordinates, dialog attributes, title, name of the first, default, and cancel controls.

control(name, type, x, y, width, height, attributes, property, text, control_next, help)

Return a new Control object. An entry in the Control table is made with the specified parameters.

This is a generic method; for specific types, specialized methods are provided.

text(name, x, y, width, height, attributes, text)

Add and return a Text control.

bitmap(name, x, y, width, height, text)

Add and return a Bitmap control.

line(name, x, y, width, height)

Add and return a Line control.

pushbutton(name, x, y, width, height, attributes, text, next_control)

Add and return a PushButton control.

radiogroup(name, x, y, width, height, attributes, property, text, next_control)

Add and return a RadioButtonGroup control.

checkbox(name, x, y, width, height, attributes, property, text, next_control)

Add and return a CheckBox control.

더 보기

Dialog Table [https://msdn.microsoft.com/en-us/library/windows/desktop/aa368286.aspx] Control Table [https://msdn.microsoft.com/en-us/library/windows/desktop/aa368044.aspx] Control Types [https://msdn.microsoft.com/en-us/library/windows/desktop/aa368039.aspx] ControlCondition Table [https://msdn.microsoft.com/en-us/library/windows/desktop/aa368035.aspx] ControlEvent Table [https://msdn.microsoft.com/en-us/library/windows/desktop/aa368037.aspx] EventMapping Table [https://msdn.microsoft.com/en-us/library/windows/desktop/aa368559.aspx] RadioButton Table [https://msdn.microsoft.com/en-us/library/windows/desktop/aa370962.aspx]

Precomputed tables

msilib provides a few subpackages that contain only schema and table definitions. Currently, these definitions are based on MSI version 2.0.

msilib.schema

This is the standard MSI schema for MSI 2.0, with the tables variable providing a list of table definitions, and _Validation_records providing the data for MSI validation.

msilib.sequence

This module contains table contents for the standard sequence tables: AdminExecuteSequence, AdminUISequence, AdvtExecuteSequence, InstallExecuteSequence, and InstallUISequence.

msilib.text

This module contains definitions for the UIText and ActionText tables, for the standard installer actions.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

MS 윈도우 특정 서비스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

MS 윈도우 특정 서비스 »

|

msvcrt — MS VC++ 런타임의 유용한 루틴

이 함수들은 윈도우 플랫폼에서 유용한 기능에 대한 액세스를 제공합니다. 일부 고수준 모듈은 이러한 함수를 사용하여 해당 서비스의 윈도우 구현을 구축합니다. 예를 들어, getpass 모듈은 getpass() 함수를 구현할 때 이를 사용합니다.

이 함수에 대한 자세한 설명은 플랫폼 API 설명서에서 찾을 수 있습니다.

이 모듈은 콘솔 I/O api의 일반과 광폭(wide) 문자 변형을 모두 구현합니다. 일반 API는 ASCII 문자만 다루며 국제화된 응용 프로그램에서는 제한적으로 사용됩니다. 가능하면 광폭 문자 API를 사용해야 합니다.

버전 3.3에서 변경: 이 모듈의 연산은 이제 IOError를 발생시키던 곳에서 OSError를 발생시킵니다.

파일 연산

msvcrt.locking(fd, mode, nbytes)

C 런타임의 파일 기술자 fd를 기반으로 파일 일부를 잠급니다. 실패하면 OSError를 발생시킵니다. 파일의 잠긴 영역은 현재 파일 위치에서부터 nbytes 바이트까지며, 파일 끝을 넘어 계속될 수 있습니다. mode는 아래에 나열된 LK_* 상수 중 하나여야 합니다. 파일의 여러 영역이 동시에 잠길 수 있지만 겹칠 수는 없습니다. 인접한 영역은 병합되지 않습니다; 개별적으로 잠금을 해제해야 합니다.

msvcrt.LK_LOCK

msvcrt.LK_RLCK

지정된 바이트를 잠급니다. 바이트를 잠글 수 없으면, 프로그램은 1초 후에 즉시 다시 시도합니다. 10 번 시도한 후에도 바이트를 잠글 수 없으면, OSError가 발생합니다.

msvcrt.LK_NBLCK

msvcrt.LK_NBRLCK

지정된 바이트를 잠급니다. 바이트를 잠글 수 없으면, OSError가 발생합니다.

msvcrt.LK_UNLCK

이전에 잠겨 있어야 하는 지정된 바이트의 잠금을 해제합니다.

msvcrt.setmode(fd, flags)

파일 기술자 fd의 줄 종료 변환 모드를 설정합니다. 텍스트 모드로 설정하려면, flags가 os.O_TEXT 여야 합니다; 바이너리는, os.O_BINARY 여야 합니다.

msvcrt.open_osfhandle(handle, flags)

Create a C runtime file descriptor from the file handle handle. The flags parameter should be a bitwise OR of os.O_APPEND, os.O_RDONLY, and os.O_TEXT. The returned file descriptor may be used as a parameter to os.fdopen() to create a file object.

msvcrt.get_osfhandle(fd)

파일 기술자 fd의 파일 핸들을 돌려줍니다. fd가 인식되지 않으면 OSError를 발생시킵니다.

콘솔 I/O

msvcrt.kbhit()

Return True if a keypress is waiting to be read.

msvcrt.getch()

키 누르기를 읽고 결과 문자를 바이트열로 반환합니다. 콘솔에 아무것도 에코 되지 않습니다. 이 호출은 키 누르기를 아직 사용할 수 없으면 블록하지만, Enter가 눌러지기를 기다리지는 않습니다. 누른 키가 특수 기능 키면, '\000' 이나 '\xe0'를 반환합니다; 다음 호출은 키코드를 반환합니다. 이 함수로 Control-C 키 누르기를 읽을 수 없습니다.

msvcrt.getwch()

유니코드 값을 반환하는 getch()의 광폭 문자 변형.

msvcrt.getche()

getch()와 비슷하지만, 인쇄 가능한 문자를 나타내는 경우 키 누르기가 에코 됩니다.

msvcrt.getwche()

유니코드 값을 반환하는 getche()의 광폭 문자 변형.

msvcrt.putch(char)

버퍼링하지 않고 바이트열 char을 콘솔에 인쇄합니다.

msvcrt.putwch(unicode_char)

유니코드 값을 받아들이는 putch()의 광폭 문자 변형.

msvcrt.ungetch(char)

바이트열 char이 콘솔 버퍼로 “푸시백” 되도록 합니다; getch() 나 getche()가 읽는 다음 문자가 됩니다.

msvcrt.ungetwch(unicode_char)

유니코드 값을 받아들이는 ungetch()의 광폭 문자 변형.

기타 함수

msvcrt.heapmin()

강제로 malloc() 힙이 자신을 정리하고, 사용하지 않는 블록을 운영 체제로 반환하도록 합니다. 실패하면, OSError가 발생합니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

MS 윈도우 특정 서비스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

MS 윈도우 특정 서비스 »

|

winreg — Windows registry access

These functions expose the Windows registry API to Python. Instead of using an integer as the registry handle, a handle object is used to ensure that the handles are closed correctly, even if the programmer neglects to explicitly close them.

버전 3.3에서 변경: Several functions in this module used to raise a WindowsError, which is now an alias of OSError.

Functions

This module offers the following functions:

winreg.CloseKey(hkey)

Closes a previously opened registry key. The hkey argument specifies a previously opened key.

참고

If hkey is not closed using this method (or via hkey.Close()), it is closed when the hkey object is destroyed by Python.

winreg.ConnectRegistry(computer_name, key)

Establishes a connection to a predefined registry handle on another computer, and returns a handle object.

computer_name is the name of the remote computer, of the form r"\\computername". If None, the local computer is used.

key is the predefined handle to connect to.

The return value is the handle of the opened key. If the function fails, an OSError exception is raised.

버전 3.3에서 변경: See above.

winreg.CreateKey(key, sub_key)

Creates or opens the specified key, returning a handle object.

key is an already open key, or one of the predefined HKEY_* constants.

sub_key is a string that names the key this method opens or creates.

If key is one of the predefined keys, sub_key may be None. In that case, the handle returned is the same key handle passed in to the function.

If the key already exists, this function opens the existing key.

The return value is the handle of the opened key. If the function fails, an OSError exception is raised.

버전 3.3에서 변경: See above.

winreg.CreateKeyEx(key, sub_key, reserved=0, access=KEY_WRITE)

Creates or opens the specified key, returning a handle object.

key is an already open key, or one of the predefined HKEY_* constants.

sub_key is a string that names the key this method opens or creates.

reserved is a reserved integer, and must be zero. The default is zero.

access is an integer that specifies an access mask that describes the desired security access for the key. Default is KEY_WRITE. See Access Rights for other allowed values.

If key is one of the predefined keys, sub_key may be None. In that case, the handle returned is the same key handle passed in to the function.

If the key already exists, this function opens the existing key.

The return value is the handle of the opened key. If the function fails, an OSError exception is raised.

버전 3.2에 추가.

버전 3.3에서 변경: See above.

winreg.DeleteKey(key, sub_key)

Deletes the specified key.

key is an already open key, or one of the predefined HKEY_* constants.

sub_key is a string that must be a subkey of the key identified by the key parameter. This value must not be None, and the key may not have subkeys.

This method can not delete keys with subkeys.

If the method succeeds, the entire key, including all of its values, is removed. If the method fails, an OSError exception is raised.

버전 3.3에서 변경: See above.

winreg.DeleteKeyEx(key, sub_key, access=KEY_WOW64_64KEY, reserved=0)

Deletes the specified key.

참고

The DeleteKeyEx() function is implemented with the RegDeleteKeyEx Windows API function, which is specific to 64-bit versions of Windows. See the RegDeleteKeyEx documentation [https://msdn.microsoft.com/en-us/library/ms724847%28VS.85%29.aspx].

key is an already open key, or one of the predefined HKEY_* constants.

sub_key is a string that must be a subkey of the key identified by the key parameter. This value must not be None, and the key may not have subkeys.

reserved is a reserved integer, and must be zero. The default is zero.

access is an integer that specifies an access mask that describes the desired security access for the key. Default is KEY_WOW64_64KEY. See Access Rights for other allowed values.

This method can not delete keys with subkeys.

If the method succeeds, the entire key, including all of its values, is removed. If the method fails, an OSError exception is raised.

On unsupported Windows versions, NotImplementedError is raised.

버전 3.2에 추가.

버전 3.3에서 변경: See above.

winreg.DeleteValue(key, value)

Removes a named value from a registry key.

key is an already open key, or one of the predefined HKEY_* constants.

value is a string that identifies the value to remove.

winreg.EnumKey(key, index)

Enumerates subkeys of an open registry key, returning a string.

key is an already open key, or one of the predefined HKEY_* constants.

index is an integer that identifies the index of the key to retrieve.

The function retrieves the name of one subkey each time it is called. It is typically called repeatedly until an OSError exception is raised, indicating, no more values are available.

버전 3.3에서 변경: See above.

winreg.EnumValue(key, index)

Enumerates values of an open registry key, returning a tuple.

key is an already open key, or one of the predefined HKEY_* constants.

index is an integer that identifies the index of the value to retrieve.

The function retrieves the name of one subkey each time it is called. It is typically called repeatedly, until an OSError exception is raised, indicating no more values.

The result is a tuple of 3 items:

Index

Meaning

0

A string that identifies the value name

1

An object that holds the value data, and whose type depends on the underlying registry type

2

An integer that identifies the type of the value data (see table in docs for SetValueEx())

버전 3.3에서 변경: See above.

winreg.ExpandEnvironmentStrings(str)

Expands environment variable placeholders %NAME% in strings like REG_EXPAND_SZ:

>>> ExpandEnvironmentStrings('%windir%')
'C:\\Windows'

winreg.FlushKey(key)

Writes all the attributes of a key to the registry.

key is an already open key, or one of the predefined HKEY_* constants.

It is not necessary to call FlushKey() to change a key. Registry changes are flushed to disk by the registry using its lazy flusher. Registry changes are also flushed to disk at system shutdown. Unlike CloseKey(), the FlushKey() method returns only when all the data has been written to the registry. An application should only call FlushKey() if it requires absolute certainty that registry changes are on disk.

참고

If you don’t know whether a FlushKey() call is required, it probably isn’t.

winreg.LoadKey(key, sub_key, file_name)

Creates a subkey under the specified key and stores registration information from a specified file into that subkey.

key is a handle returned by ConnectRegistry() or one of the constants HKEY_USERS or HKEY_LOCAL_MACHINE.

sub_key is a string that identifies the subkey to load.

file_name is the name of the file to load registry data from. This file must have been created with the SaveKey() function. Under the file allocation table (FAT) file system, the filename may not have an extension.

A call to LoadKey() fails if the calling process does not have the SE_RESTORE_PRIVILEGE privilege. Note that privileges are different from permissions – see the RegLoadKey documentation [https://msdn.microsoft.com/en-us/library/ms724889%28v=VS.85%29.aspx] for more details.

If key is a handle returned by ConnectRegistry(), then the path specified in file_name is relative to the remote computer.

winreg.OpenKey(key, sub_key, reserved=0, access=KEY_READ)

winreg.OpenKeyEx(key, sub_key, reserved=0, access=KEY_READ)

Opens the specified key, returning a handle object.

key is an already open key, or one of the predefined HKEY_* constants.

sub_key is a string that identifies the sub_key to open.

reserved is a reserved integer, and must be zero. The default is zero.

access is an integer that specifies an access mask that describes the desired security access for the key. Default is KEY_READ. See Access Rights for other allowed values.

The result is a new handle to the specified key.

If the function fails, OSError is raised.

버전 3.2에서 변경: Allow the use of named arguments.

버전 3.3에서 변경: See above.

winreg.QueryInfoKey(key)

Returns information about a key, as a tuple.

key is an already open key, or one of the predefined HKEY_* constants.

The result is a tuple of 3 items:

Index

Meaning

0

An integer giving the number of sub keys this key has.

1

An integer giving the number of values this key has.

2

An integer giving when the key was last modified (if available) as 100’s of nanoseconds since Jan 1, 1601.

winreg.QueryValue(key, sub_key)

Retrieves the unnamed value for a key, as a string.

key is an already open key, or one of the predefined HKEY_* constants.

sub_key is a string that holds the name of the subkey with which the value is associated. If this parameter is None or empty, the function retrieves the value set by the SetValue() method for the key identified by key.

Values in the registry have name, type, and data components. This method retrieves the data for a key’s first value that has a NULL name. But the underlying API call doesn’t return the type, so always use QueryValueEx() if possible.

winreg.QueryValueEx(key, value_name)

Retrieves the type and data for a specified value name associated with an open registry key.

key is an already open key, or one of the predefined HKEY_* constants.

value_name is a string indicating the value to query.

The result is a tuple of 2 items:

Index

Meaning

0

The value of the registry item.

1

An integer giving the registry type for this value (see table in docs for SetValueEx())

winreg.SaveKey(key, file_name)

Saves the specified key, and all its subkeys to the specified file.

key is an already open key, or one of the predefined HKEY_* constants.

file_name is the name of the file to save registry data to. This file cannot already exist. If this filename includes an extension, it cannot be used on file allocation table (FAT) file systems by the LoadKey() method.

If key represents a key on a remote computer, the path described by file_name is relative to the remote computer. The caller of this method must possess the SeBackupPrivilege security privilege. Note that privileges are different than permissions – see the Conflicts Between User Rights and Permissions documentation [https://msdn.microsoft.com/en-us/library/ms724878%28v=VS.85%29.aspx] for more details.

This function passes NULL for security_attributes to the API.

winreg.SetValue(key, sub_key, type, value)

Associates a value with a specified key.

key is an already open key, or one of the predefined HKEY_* constants.

sub_key is a string that names the subkey with which the value is associated.

type is an integer that specifies the type of the data. Currently this must be REG_SZ, meaning only strings are supported. Use the SetValueEx() function for support for other data types.

value is a string that specifies the new value.

If the key specified by the sub_key parameter does not exist, the SetValue function creates it.

Value lengths are limited by available memory. Long values (more than 2048 bytes) should be stored as files with the filenames stored in the configuration registry. This helps the registry perform efficiently.

The key identified by the key parameter must have been opened with KEY_SET_VALUE access.

winreg.SetValueEx(key, value_name, reserved, type, value)

Stores data in the value field of an open registry key.

key is an already open key, or one of the predefined HKEY_* constants.

value_name is a string that names the subkey with which the value is associated.

reserved can be anything – zero is always passed to the API.

type is an integer that specifies the type of the data. See Value Types for the available types.

value is a string that specifies the new value.

This method can also set additional value and type information for the specified key. The key identified by the key parameter must have been opened with KEY_SET_VALUE access.

To open the key, use the CreateKey() or OpenKey() methods.

Value lengths are limited by available memory. Long values (more than 2048 bytes) should be stored as files with the filenames stored in the configuration registry. This helps the registry perform efficiently.

winreg.DisableReflectionKey(key)

Disables registry reflection for 32-bit processes running on a 64-bit operating system.

key is an already open key, or one of the predefined HKEY_* constants.

Will generally raise NotImplementedError if executed on a 32-bit operating system.

If the key is not on the reflection list, the function succeeds but has no effect. Disabling reflection for a key does not affect reflection of any subkeys.

winreg.EnableReflectionKey(key)

Restores registry reflection for the specified disabled key.

key is an already open key, or one of the predefined HKEY_* constants.

Will generally raise NotImplementedError if executed on a 32-bit operating system.

Restoring reflection for a key does not affect reflection of any subkeys.

winreg.QueryReflectionKey(key)

Determines the reflection state for the specified key.

key is an already open key, or one of the predefined HKEY_* constants.

Returns True if reflection is disabled.

Will generally raise NotImplementedError if executed on a 32-bit operating system.

Constants

The following constants are defined for use in many _winreg functions.

HKEY_* Constants

winreg.HKEY_CLASSES_ROOT

Registry entries subordinate to this key define types (or classes) of documents and the properties associated with those types. Shell and COM applications use the information stored under this key.

winreg.HKEY_CURRENT_USER

Registry entries subordinate to this key define the preferences of the current user. These preferences include the settings of environment variables, data about program groups, colors, printers, network connections, and application preferences.

winreg.HKEY_LOCAL_MACHINE

Registry entries subordinate to this key define the physical state of the computer, including data about the bus type, system memory, and installed hardware and software.

winreg.HKEY_USERS

Registry entries subordinate to this key define the default user configuration for new users on the local computer and the user configuration for the current user.

winreg.HKEY_PERFORMANCE_DATA

Registry entries subordinate to this key allow you to access performance data. The data is not actually stored in the registry; the registry functions cause the system to collect the data from its source.

winreg.HKEY_CURRENT_CONFIG

Contains information about the current hardware profile of the local computer system.

winreg.HKEY_DYN_DATA

This key is not used in versions of Windows after 98.

Access Rights

For more information, see Registry Key Security and Access [https://msdn.microsoft.com/en-us/library/ms724878%28v=VS.85%29.aspx].

winreg.KEY_ALL_ACCESS

Combines the STANDARD_RIGHTS_REQUIRED, KEY_QUERY_VALUE, KEY_SET_VALUE, KEY_CREATE_SUB_KEY, KEY_ENUMERATE_SUB_KEYS, KEY_NOTIFY, and KEY_CREATE_LINK access rights.

winreg.KEY_WRITE

Combines the STANDARD_RIGHTS_WRITE, KEY_SET_VALUE, and KEY_CREATE_SUB_KEY access rights.

winreg.KEY_READ

Combines the STANDARD_RIGHTS_READ, KEY_QUERY_VALUE, KEY_ENUMERATE_SUB_KEYS, and KEY_NOTIFY values.

winreg.KEY_EXECUTE

Equivalent to KEY_READ.

winreg.KEY_QUERY_VALUE

Required to query the values of a registry key.

winreg.KEY_SET_VALUE

Required to create, delete, or set a registry value.

winreg.KEY_CREATE_SUB_KEY

Required to create a subkey of a registry key.

winreg.KEY_ENUMERATE_SUB_KEYS

Required to enumerate the subkeys of a registry key.

winreg.KEY_NOTIFY

Required to request change notifications for a registry key or for subkeys of a registry key.

winreg.KEY_CREATE_LINK

Reserved for system use.

64-bit Specific

For more information, see Accessing an Alternate Registry View [https://msdn.microsoft.com/en-us/library/aa384129(v=VS.85).aspx].

winreg.KEY_WOW64_64KEY

Indicates that an application on 64-bit Windows should operate on the 64-bit registry view.

winreg.KEY_WOW64_32KEY

Indicates that an application on 64-bit Windows should operate on the 32-bit registry view.

Value Types

For more information, see Registry Value Types [https://msdn.microsoft.com/en-us/library/ms724884%28v=VS.85%29.aspx].

winreg.REG_BINARY

Binary data in any form.

winreg.REG_DWORD

32-bit number.

winreg.REG_DWORD_LITTLE_ENDIAN

A 32-bit number in little-endian format. Equivalent to REG_DWORD.

winreg.REG_DWORD_BIG_ENDIAN

A 32-bit number in big-endian format.

winreg.REG_EXPAND_SZ

Null-terminated string containing references to environment variables (%PATH%).

winreg.REG_LINK

A Unicode symbolic link.

winreg.REG_MULTI_SZ

A sequence of null-terminated strings, terminated by two null characters. (Python handles this termination automatically.)

winreg.REG_NONE

No defined value type.

winreg.REG_QWORD

A 64-bit number.

버전 3.6에 추가.

winreg.REG_QWORD_LITTLE_ENDIAN

A 64-bit number in little-endian format. Equivalent to REG_QWORD.

버전 3.6에 추가.

winreg.REG_RESOURCE_LIST

A device-driver resource list.

winreg.REG_FULL_RESOURCE_DESCRIPTOR

A hardware setting.

winreg.REG_RESOURCE_REQUIREMENTS_LIST

A hardware resource list.

winreg.REG_SZ

A null-terminated string.

Registry Handle Objects

This object wraps a Windows HKEY object, automatically closing it when the object is destroyed. To guarantee cleanup, you can call either the Close() method on the object, or the CloseKey() function.

All registry functions in this module return one of these objects.

All registry functions in this module which accept a handle object also accept an integer, however, use of the handle object is encouraged.

Handle objects provide semantics for __bool__() – thus

if handle:
    print("Yes")

will print Yes if the handle is currently valid (has not been closed or detached).

The object also support comparison semantics, so handle objects will compare true if they both reference the same underlying Windows handle value.

Handle objects can be converted to an integer (e.g., using the built-in int() function), in which case the underlying Windows handle value is returned. You can also use the Detach() method to return the integer handle, and also disconnect the Windows handle from the handle object.

PyHKEY.Close()

Closes the underlying Windows handle.

If the handle is already closed, no error is raised.

PyHKEY.Detach()

Detaches the Windows handle from the handle object.

The result is an integer that holds the value of the handle before it is detached. If the handle is already detached or closed, this will return zero.

After calling this function, the handle is effectively invalidated, but the handle is not closed. You would call this function when you need the underlying Win32 handle to exist beyond the lifetime of the handle object.

PyHKEY.__enter__()

PyHKEY.__exit__(*exc_info)

The HKEY object implements __enter__() and __exit__() and thus supports the context protocol for the with statement:

with OpenKey(HKEY_LOCAL_MACHINE, "foo") as key:
    ...  # work with key

will automatically close key when control leaves the with block.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

MS 윈도우 특정 서비스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

MS 윈도우 특정 서비스 »

|

winsound — 윈도우용 소리 재생 인터페이스

winsound 모듈은 윈도우 플랫폼에서 제공하는 기본 소리 재생 장치에 대한 액세스를 제공합니다. 함수와 여러 상수를 포함합니다.

winsound.Beep(frequency, duration)

PC 스피커로 신호음을 울립니다. frequency 매개 변수는 소리의 주파수를 헤르츠 단위로 지정하며 37에서 32,767 범위에 있어야 합니다. duration 매개 변수는 소리의 지속 시간을 밀리 초로 지정합니다. 시스템이 스피커에서 신호음을 울리지 못하면, RuntimeError가 발생합니다.

winsound.PlaySound(sound, flags)

플랫폼 API에서 하부 PlaySound() 함수를 호출합니다. sound 매개 변수는 파일명, 시스템 소리 별칭, 바이트열류 객체의 오디오 데이터 또는 None 일 수 있습니다. 해석은 flags의 값에 따라 달라지는데, 아래에 설명된 상수의 비트별 OR 결합이 될 수 있습니다. sound 매개 변수가 None이면, 현재 재생 중인 파형 소리가 중지됩니다. 시스템이 에러를 표시하면 RuntimeError가 발생합니다.

winsound.MessageBeep(type=MB_OK)

플랫폼 API에서 하부 MessageBeep() 함수를 호출합니다. 레지스트리에 지정된 소리를 재생합니다. type 인자는 재생할 소리를 지정합니다; 가능한 값은 아래에 설명된 -1, MB_ICONASTERISK, MB_ICONEXCLAMATION, MB_ICONHAND, MB_ICONQUESTION 및 MB_OK입니다. -1 값은 “간단한 신호음”을 생성합니다; 이것은 소리를 재생할 수 없을 때 최종 대체가 됩니다. 시스템이 에러를 표시하면 RuntimeError가 발생합니다.

winsound.SND_FILENAME

sound 매개 변수는 WAV 파일의 이름입니다. SND_ALIAS와 함께 사용하지 마십시오.

winsound.SND_ALIAS

sound 매개 변수는 레지스트리의 소리 연결 이름입니다. 레지스트리에 그러한 이름이 없으면, SND_NODEFAULT도 함께 지정하지 않는 한 시스템 기본 소리를 재생합니다. 기본 소리가 등록되어 있지 않으면, RuntimeError를 일으킵니다. SND_FILENAME과 함께 사용하지 마십시오.

모든 Win32 시스템은 적어도 다음을 지원합니다; 대부분 시스템은 더 많은 것을 지원합니다:

PlaySound() 이름

해당 제어판 소리 이름

'SystemAsterisk'

Asterisk

'SystemExclamation'

Exclamation

'SystemExit'

Exit Windows

'SystemHand'

Critical Stop

'SystemQuestion'

Question

예를 들면:

import winsound
# Play Windows exit sound.
winsound.PlaySound("SystemExit", winsound.SND_ALIAS)

# Probably play Windows default sound, if any is registered (because
# "*" probably isn't the registered name of any sound).
winsound.PlaySound("*", winsound.SND_ALIAS)

winsound.SND_LOOP

소리를 반복해서 재생합니다. 블로킹을 피하고자 SND_ASYNC 플래그도 사용해야 합니다. SND_MEMORY와 함께 사용할 수 없습니다.

winsound.SND_MEMORY

PlaySound()에 대한 sound 매개 변수는 바이트열류 객체의 WAV 파일의 메모리 이미지입니다.

참고

이 모듈은 메모리 이미지를 비동기적으로 재생하는 것을 지원하지 않으므로, 이 플래그와 SND_ASYNC의 조합은 RuntimeError를 발생시킵니다.

winsound.SND_PURGE

지정된 소리의 모든 인스턴스 재생을 중지합니다.

참고

이 플래그는 최신 윈도우 플랫폼에서 지원되지 않습니다.

winsound.SND_ASYNC

소리를 비동기적으로 재생할 수 있도록, 즉시 반환합니다.

winsound.SND_NODEFAULT

지정된 소리를 찾을 수 없을 때, 시스템 기본 소리를 재생하지 않습니다.

winsound.SND_NOSTOP

현재 재생 중인 소리를 중단하지 않습니다.

winsound.SND_NOWAIT

사운드 드라이버가 바쁘면 즉시 반환합니다.

참고

이 플래그는 최신 윈도우 플랫폼에서 지원되지 않습니다.

winsound.MB_ICONASTERISK

SystemDefault 소리를 재생합니다.

winsound.MB_ICONEXCLAMATION

SystemExclamation 소리를 재생합니다.

winsound.MB_ICONHAND

SystemHand 소리를 재생합니다.

winsound.MB_ICONQUESTION

SystemQuestion 소리를 재생합니다.

winsound.MB_OK

SystemDefault 소리를 재생합니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

MS 윈도우 특정 서비스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

|

유닉스 특정 서비스

이 장에서 설명하는 모듈은 유닉스 운영 체제(혹은 때에 따라 일부 혹은 많은 변종)에 고유한 기능에 대한 인터페이스를 제공합니다. 다음은 개요입니다:

posix — 가장 일반적인 POSIX 시스템 호출

대용량 파일 지원

주목할만한 모듈 내용

pwd — 암호 데이터베이스

spwd — 섀도 암호 데이터베이스

grp — 그룹 데이터베이스

crypt — 유닉스 비밀번호 확인 함수

해싱 방법

모듈 어트리뷰트

모듈 함수

예제

termios — POSIX 스타일 tty 제어

예제

tty — 터미널 제어 함수

pty — 의사 터미널 유틸리티

예제

fcntl — fcntl과 ioctl 시스템 호출

pipes — 셸 파이프라인에 대한 인터페이스

Template 객체

resource — 자원 사용 정보

자원 제한

자원 사용량

nis — Sun의 NIS(옐로 페이지)에 대한 인터페이스

syslog — 유닉스 syslog 라이브러리 루틴

예제

간단한 예제

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

유닉스 특정 서비스 »

|

posix — 가장 일반적인 POSIX 시스템 호출

이 모듈은 C 표준과 POSIX 표준(얇게 위장한 유닉스 인터페이스)에 의해 표준화된 운영 체제 기능에 대한 액세스를 제공합니다.

이 모듈을 직접 임포트 하지 마십시오. 대신, 이 인터페이스의 이식성 있는 버전을 제공하는 모듈 os를 임포트 하십시오. 유닉스에서, os 모듈은 posix 인터페이스의 상위집합을 제공합니다. 비 유닉스 운영 체제에서는 posix 모듈을 사용할 수 없지만, os 인터페이스를 통해 항상 부분집합을 사용할 수 있습니다. 일단 os를 임포트하면, posix 대신 사용해도 성능 저하가 없습니다. 또한, os는 os.environ의 항목이 변경될 때 자동으로 putenv()를 호출하는 등의 몇 가지 추가 기능을 제공합니다.

에러는 예외로 보고됩니다; 보통 예외는 형 에러로 인한 것입니다만, 시스템 호출 때문에 보고되는 에러는 OSError를 발생시킵니다.

대용량 파일 지원

여러 운영 체제(AIX, HP-UX, Irix 및 Solaris 포함)는 int와 long이 32비트 값인 C 프로그래밍 모델로 인한 2 GiB보다 큰 파일에 대한 지원을 제공합니다. 이것은 일반적으로 관련 크기 및 오프셋 형을 64비트 값으로 정의하여 수행됩니다. 이러한 파일을 때로 대용량 파일 (large files)이라고 합니다.

Large file support is enabled in Python when the size of an off_t is larger than a long and the long long is at least as large as an off_t. It may be necessary to configure and compile Python with certain compiler flags to enable this mode. For example, it is enabled by default with recent versions of Irix, but with Solaris 2.6 and 2.7 you need to do something like:

CFLAGS="`getconf LFS_CFLAGS`" OPT="-g -O2 $CFLAGS" \
        ./configure

대용량 파일을 사용할 수 있는 리눅스 시스템에서, 이렇게 할 수 있습니다:

CFLAGS='-D_LARGEFILE64_SOURCE -D_FILE_OFFSET_BITS=64' OPT="-g -O2 $CFLAGS" \
        ./configure

주목할만한 모듈 내용

os 모듈 설명서에서 설명된 많은 함수 외에도, posix는 다음 데이터 항목을 정의합니다:

posix.environ

인터프리터가 시작될 때 문자열 환경을 나타내는 딕셔너리. 키와 값은 유닉스에서는 바이트열이고 윈도우에서는 str입니다. 예를 들어, environ[b'HOME'](윈도우에서는 environ['HOME'])은 홈 디렉터리의 경로명이며, C의 getenv("HOME")와 동등합니다.

이 딕셔너리를 수정해도 execv(), popen() 또는 system()에 전달되는 문자열 환경에는 영향을 주지 않습니다; 환경을 변경해야 하는 경우 environ을 execve()로 전달하거나, system() 이나 popen()의 명령 문자열에 변수 대입과 export 문장을 추가하십시오.

버전 3.2에서 변경: 유닉스에서, 키와 값은 바이트열입니다.

참고

os 모듈은 수정 시 환경을 갱신하는 environ의 대체 구현을 제공합니다. os.environ를 갱신하면 이 딕셔너리를 쓸모없게 만드는 것에 유의하십시오. os 모듈 버전을 사용하는 것이 posix 모듈에 직접 액세스하는 것보다 권장됩니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

유닉스 특정 서비스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

유닉스 특정 서비스 »

|

pwd — 암호 데이터베이스

이 모듈은 유닉스 사용자 계정과 암호 데이터베이스에 대한 액세스를 제공합니다. 모든 유닉스 버전에서 사용할 수 있습니다.

암호 데이터베이스 항목은 passwd 구조체(아래의 어트리뷰트 필드, <pwd.h>를 보세요)의 멤버에 해당하는 어트리뷰트를 가진 튜플류 객체로 보고됩니다.:

인덱스

어트리뷰트

의미

0

pw_name

로그인 이름

1

pw_passwd

선택적 암호화된 암호

2

pw_uid

숫자 사용자 ID

3

pw_gid

숫자 그룹 ID

4

pw_gecos

사용자 이름이나 주석 필드

5

pw_dir

사용자 홈 디렉터리

6

pw_shell

사용자 명령 인터프리터

uid 및 gid 항목은 정수이고, 다른 모든 항목은 문자열입니다. 요청된 항목을 찾을 수 없으면 KeyError가 발생합니다.

참고

전통적인 유닉스에서 필드 pw_passwd는 대개 DES 파생 알고리즘으로 암호화된 암호를 포함합니다 (모듈 crypt를 보세요). 그러나 대부분의 현대 유닉스는 소위 섀도 암호 시스템을 사용합니다. 이러한 유닉스에서 pw_passwd 필드는 별표 ('*') 또는 문자 'x' 만 포함하고, 암호화된 암호는 세계(world)가 읽을 수 없는 파일 /etc/shadow에 저장됩니다. pw_passwd 필드에 유용한 것이 포함되어 있는지는 시스템에 따라 다릅니다. 사용할 수 있다면, spwd 모듈을 암호화된 암호에 대한 액세스가 필요한 곳에 사용해야 합니다.

다음 항목을 정의합니다:

pwd.getpwuid(uid)

주어진 숫자 사용자 ID에 대한 암호 데이터베이스 항목을 반환합니다.

pwd.getpwnam(name)

주어진 사용자 이름에 대한 암호 데이터베이스 항목을 반환합니다.

pwd.getpwall()

사용 가능한 모든 암호 데이터베이스 항목의 리스트를 임의의 순서로 반환합니다.

더 보기

모듈 grp

그룹 데이터베이스에 대한 인터페이스, 이것과 유사합니다.

모듈 spwd

섀도 암호 데이터베이스와의 인터페이스, 이것과 유사합니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

유닉스 특정 서비스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

유닉스 특정 서비스 »

|

spwd — 섀도 암호 데이터베이스

이 모듈은 유닉스 섀도 암호 데이터베이스에 대한 액세스를 제공합니다. 다양한 유닉스 버전에서 사용할 수 있습니다.

섀도 암호 데이터베이스에 액세스할 수 있는 충분한 권한이 있어야 합니다 (일반적으로 루트여야 함을 뜻합니다).

섀도 암호 데이터베이스 항목은 튜플류 객체로 보고됩니다. 어트리뷰트는 spwd 구조체의 멤버에 해당합니다 (아래의 어트리뷰트 필드, <shadow.h> 참조):

인덱스

어트리뷰트

의미

0

sp_namp

로그인 이름

1

sp_pwdp

암호화된 암호

2

sp_lstchg

최종 변경 날짜

3

sp_min

변경 간 최소 일수

4

sp_max

변경 간 최대 일수

5

sp_warn

암호 만료 며칠 전에 사용자에게 경고할지, 날짜 수로 표현

6

sp_inact

암호 만료 후 며칠 후에 계정이 비활성화될지, 날짜 수로 표현

7

sp_expire

계정 만료일, 1970-01-01 이후 일수로 표현

8

sp_flag

예약됨

sp_namp 및 sp_pwdp 항목은 문자열이며, 다른 모든 항목은 정수입니다. 요청된 항목을 찾을 수 없으면 KeyError가 발생합니다.

다음 함수가 정의됩니다:

spwd.getspnam(name)

지정된 사용자 이름에 대한 섀도 암호 데이터베이스 항목을 반환합니다.

버전 3.6에서 변경: 사용자에게 권한이 없으면 KeyError 대신 PermissionError를 발생시킵니다.

spwd.getspall()

사용 가능한 모든 섀도 암호 데이터베이스 항목의 리스트를 임의의 순서로 반환합니다.

더 보기

모듈 grp

그룹 데이터베이스에 대한 인터페이스, 이것과 유사합니다.

모듈 pwd

일반적인 암호 데이터베이스와의 인터페이스, 이것과 유사합니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

유닉스 특정 서비스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

유닉스 특정 서비스 »

|

grp — 그룹 데이터베이스

이 모듈은 유닉스 그룹 데이터베이스에 대한 액세스를 제공합니다. 모든 유닉스 버전에서 사용할 수 있습니다.

그룹 데이터베이스 항목은 group 구조체(아래의 어트리뷰트 필드, <pwd.h>를 보세요)의 멤버에 해당하는 어트리뷰트를 가진 튜플류 객체로 보고됩니다.:

인덱스

어트리뷰트

의미

0

gr_name

그룹의 이름

1

gr_passwd

(암호화된) 그룹 암호; 종종 비어있습니다

2

gr_gid

숫자 그룹 ID

3

gr_mem

모든 그룹 구성원의 사용자 이름

gid는 정수고, 이름과 암호는 문자열이며, 구성원 목록은 문자열 리스트입니다. (대부분 사용자는 암호 데이터베이스에 따라 속한 그룹의 구성원으로 명시적으로 나열되지 않습니다. 완전한 멤버십 정보를 얻으려면 두 데이터베이스를 모두 확인하십시오. + 나 -로 시작하는 gr_name은 YP/NIS 참조일 수 있고 getgrnam() 이나 getgrgid()로 액세스하지 못할 수 있습니다.)

다음 항목을 정의합니다:

grp.getgrgid(gid)

주어진 숫자 그룹 ID에 대한 그룹 데이터베이스 항목을 반환합니다. 요청된 항목을 찾을 수 없으면 KeyError가 발생합니다.

버전 3.6부터 폐지: 파이썬 3.6부터 getgrgid()에서 float나 문자열과 같은 정수가 아닌 인자의 지원은 폐지되었습니다.

grp.getgrnam(name)

지정된 그룹 이름에 대한 그룹 데이터베이스의 항목을 반환합니다. 요청된 항목을 찾을 수 없으면 KeyError가 발생합니다.

grp.getgrall()

사용 가능한 모든 그룹 항목의 리스트를 임의의 순서로 반환합니다.

더 보기

모듈 pwd

사용자 데이터베이스와의 인터페이스, 이것과 유사합니다.

모듈 spwd

섀도 암호 데이터베이스와의 인터페이스, 이것과 유사합니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

유닉스 특정 서비스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

유닉스 특정 서비스 »

|

crypt — 유닉스 비밀번호 확인 함수

소스 코드: Lib/crypt.py [https://github.com/python/cpython/tree/3.7/Lib/crypt.py]

이 모듈은 수정된 DES 알고리즘을 기반으로 하는 단방향 해시 함수인 crypt(3) 루틴에 대한 인터페이스를 구현합니다; 자세한 내용은 유닉스 매뉴얼 페이지를 참조하십시오. 가능한 용도는 실제 암호를 저장하지 않고 암호를 확인하기 위해 해시 된 암호를 저장하거나 사전으로 유닉스 암호를 해독하려고 시도하는 것을 포함합니다.

이 모듈의 동작은 실행 중인 시스템의 crypt(3) 루틴의 실제 구현에 따라 달라집니다. 따라서, 현재 구현에서 사용할 수 있는 모든 확장을 이 모듈에서도 사용할 수 있습니다.

해싱 방법

버전 3.3에 추가.

crypt 모듈은 해싱 방법 목록을 정의합니다 (모든 플랫폼에서 모든 방법을 사용할 수 있는 것은 아닙니다):

crypt.METHOD_SHA512

SHA-512 해시 함수를 기반으로 16문자의 솔트(salt)와 86문자의 해시를 사용하는 모듈형 암호 형식(Modular Crypt Format) 방법. 이것은 가장 강력한 방법입니다.

crypt.METHOD_SHA256

SHA-256 해시 함수를 기반으로 16자의 솔트와 43자의 해시를 사용하는 또 다른 모듈형 암호 형식 방법.

crypt.METHOD_BLOWFISH

Blowfish 암호를 기반으로 22문자의 솔트와 31문자의 해시를 사용하는 또 다른 모듈형 암호 형식 방법.

버전 3.7에 추가.

crypt.METHOD_MD5

MD5 해시 함수를 기반으로 8자의 솔트와 22자의 해시를 사용하는 또 다른 모듈형 암호 형식 방법.

crypt.METHOD_CRYPT

2문자의 솔트와 13문자의 해시를 사용하는 전통적인 방법. 이것은 가장 약한 방법입니다.

모듈 어트리뷰트

버전 3.3에 추가.

crypt.methods

사용 가능한 비밀번호 해싱 알고리즘 리스트, crypt.METHOD_* 객체들. 이 리스트는 가장 강한 것부터 가장 약한 것 순으로 정렬됩니다.

모듈 함수

crypt 모듈은 다음 함수를 정의합니다:

crypt.crypt(word, salt=None)

word는 대개 프롬프트나 그래픽 인터페이스에서 입력한 사용자의 비밀번호입니다. 선택적 salt는 mksalt()에서 반환된 문자열, crypt.METHOD_* 값 중 하나(모든 플랫폼에서 모든 것을 사용할 수 있는 것은 아니지만), 또는 이 함수가 반환하는 솔트를 포함한 전체 암호화된 비밀번호입니다. salt가 제공되지 않으면, (methods()에서 반환되는) 가장 강력한 방법이 사용됩니다.

비밀번호 확인은 일반적으로 word로 평문 비밀번호를 전달하는 것으로 수행됩니다. 이전 crypt() 호출의 전체 결과와 이 호출의 결과가 같아야 합니다.

salt(무작위의 2자나 16자 문자열, 방법을 가리키기 위해 앞에 $digit$가 붙을 수 있음)는 암호화 알고리즘을 교란하는 데 사용됩니다. salt의 문자는 $digit$를 앞에 붙이는 모듈형 암호 형식을 제외하고는 [./a-zA-Z0-9] 집합에 있어야 합니다.

해시 된 비밀번호를 문자열로 반환합니다. 이 문자열은 솔트와 같은 알파벳의 문자로 구성됩니다.

몇 가지 crypt(3) 확장이 salt에 다른 크기의 다른 값을 허용하기 때문에, 암호를 확인할 때 전체 암호화된 비밀번호를 솔트로 사용하는 것이 좋습니다.

버전 3.3에서 변경: salt에 대한 문자열 외에 crypt.METHOD_* 값을 받아들입니다.

crypt.mksalt(method=None, *, rounds=None)

지정된 방법의 무작위로 생성된 솔트를 반환합니다. method가 주어지지 않으면, methods()에 의해 반환된 가장 강력한 방법이 사용됩니다.

반환 값은 salt 인자로 crypt()에 전달하기에 적합한 문자열입니다.

rounds는 METHOD_SHA256, METHOD_SHA512 및 METHOD_BLOWFISH에 대한 라운드 수를 지정합니다. METHOD_SHA256 과 METHOD_SHA512의 경우 1000와 999_999_999 사이의 정수여야 하며, 기본값은 5000입니다. METHOD_BLOWFISH의 경우 16(2⁴)과 2_147_483_648(2³¹) 사이의 2의 거듭제곱이어야 하며, 기본값은 4096(2¹²)입니다.

버전 3.3에 추가.

버전 3.7에서 변경: rounds 매개 변수가 추가되었습니다.

예제

일반적인 사용법을 보여주는 간단한 예제 (타이밍 공격에 대한 노출을 제한하기 위해서는 상수 시간 비교 연산이 필요합니다. hmac.compare_digest()가 이 목적에 적합합니다):

import pwd
import crypt
import getpass
from hmac import compare_digest as compare_hash

def login():
    username = input('Python login: ')
    cryptedpasswd = pwd.getpwnam(username)[1]
    if cryptedpasswd:
        if cryptedpasswd == 'x' or cryptedpasswd == '*':
            raise ValueError('no support for shadow passwords')
        cleartext = getpass.getpass()
        return compare_hash(crypt.crypt(cleartext, cryptedpasswd), cryptedpasswd)
    else:
        return True

가장 강력한 방법을 사용하여 비밀번호의 해시를 생성하고, 원본과 비교하여 확인하려면 이렇게 합니다:

import crypt
from hmac import compare_digest as compare_hash

hashed = crypt.crypt(plaintext)
if not compare_hash(hashed, crypt.crypt(plaintext, hashed)):
    raise ValueError("hashed version doesn't validate against original")

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

유닉스 특정 서비스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

유닉스 특정 서비스 »

|

termios — POSIX 스타일 tty 제어

이 모듈은 tty I/O 제어를 위한 POSIX 호출에 대한 인터페이스를 제공합니다. 이 호출에 대한 자세한 설명은 termios(3) 유닉스 매뉴얼 페이지를 참조하십시오. 설치 중에 구성된 POSIX termios 스타일 tty I/O 제어를 지원하는 유닉스 버전에서만 사용할 수 있습니다.

이 모듈의 모든 함수는 첫 번째 인자로 파일 기술자 fd를 받아들입니다. sys.stdin.fileno()에 의해 반환된 것과 같은 정수 파일 기술자이거나, sys.stdin 자체와 같은 파일 객체 일 수 있습니다.

이 모듈은 여기에 제공된 함수로 작업하는 데 필요한 모든 상수도 정의합니다; 이것들은 C에 있는 것들과 같은 이름을 가집니다. 이 터미널 제어 인터페이스의 사용에 대한 자세한 내용은 시스템 설명서를 참조하십시오.

모듈은 다음 함수를 정의합니다:

termios.tcgetattr(fd)

다음과 같이 파일 기술자 fd에 대한 tty 어트리뷰트를 포함하는 리스트를 반환합니다: [iflag, oflag, cflag, lflag, ispeed, ospeed, cc]. 여기서 cc는 tty 특수 문자 리스트입니다 (각기 길이 1인 문자열인데, 인덱스가 VMIN 과 VTIME 인 항목은 예외인데, 이 필드가 정의될 때 정수입니다). cc 배열의 인덱싱뿐만 아니라 플래그와 속도의 해석은 termios 모듈에 정의된 기호 상수를 사용해서 이루어져야 합니다.

termios.tcsetattr(fd, when, attributes)

파일 기술자 fd에 대한 tty 어트리뷰트를 attributes로 설정합니다. attributes는 tcgetattr()에 의해 반환된 것과 같은 리스트입니다. when 인자는 언제 어트리뷰트가 변경되는지를 결정합니다: 즉시 변경하려면 TCSANOW, 계류 중인 모든 출력을 전송한 후에 변경하려면 TCSADRAIN, 계류 중인 모든 출력을 전송하고 계류 중인 모든 입력을 버린 후 변경하려면 TCSAFLUSH.

termios.tcsendbreak(fd, duration)

파일 기술자 fd에 브레이크(break)를 보냅니다. 0 duration은 0.25–0.5 초 동안 브레이크를 보냅니다; 0이 아닌 duration은 시스템 종속적인 의미가 있습니다.

termios.tcdrain(fd)

파일 기술자 fd에 기록된 모든 출력이 전송될 때까지 기다립니다.

termios.tcflush(fd, queue)

파일 기술자 fd에 계류 중인 데이터를 버립니다. queue 선택기는 어떤 큐인지를 지정합니다: 입력 큐는 TCIFLUSH, 출력 큐는 TCOFLUSH 또는 두 큐 모두는 TCIOFLUSH.

termios.tcflow(fd, action)

파일 기술자 fd에서 입력 또는 출력을 일시 중단하거나 다시 시작합니다. action 인자는 출력을 일시 중단하는 TCOOFF, 출력을 다시 시작하는 TCOON, 입력을 일시 중단하는 TCIOFF 또는 입력을 다시 시작하는 TCION가 될 수 있습니다.

더 보기

모듈 tty

공통 터미널 제어 연산을 위한 편리 함수.

예제

이것은 에코가 꺼진 상태에서 암호를 묻는 함수입니다. 별도의 tcgetattr() 호출과 try … finally 문을 사용하여 이전 tty 어트리뷰트가 어떤 일이 발생하든 정확하게 복원되도록 하는 것에 유의하십시오:

def getpass(prompt="Password: "):
    import termios, sys
    fd = sys.stdin.fileno()
    old = termios.tcgetattr(fd)
    new = termios.tcgetattr(fd)
    new[3] = new[3] & ~termios.ECHO          # lflags
    try:
        termios.tcsetattr(fd, termios.TCSADRAIN, new)
        passwd = input(prompt)
    finally:
        termios.tcsetattr(fd, termios.TCSADRAIN, old)
    return passwd

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

유닉스 특정 서비스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

유닉스 특정 서비스 »

|

tty — 터미널 제어 함수

소스 코드: Lib/tty.py [https://github.com/python/cpython/tree/3.7/Lib/tty.py]

tty 모듈은 tty를 cbreak 및 raw 모드로 설정하는 함수를 정의합니다.

termios 모듈이 필요하기 때문에 유닉스에서만 작동합니다.

tty 모듈은 다음 함수를 정의합니다.:

tty.setraw(fd, when=termios.TCSAFLUSH)

파일 기술자 fd의 모드를 raw로 변경합니다. when이 생략되면, 기본값은 termios.TCSAFLUSH이며 termios.tcsetattr()로 전달됩니다.

tty.setcbreak(fd, when=termios.TCSAFLUSH)

파일 기술자 fd의 모드를 cbreak로 변경합니다. when이 생략되면, 기본값은 termios.TCSAFLUSH이며 termios.tcsetattr()로 전달됩니다.

더 보기

모듈 termios

저수준 터미널 제어 인터페이스.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

유닉스 특정 서비스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

유닉스 특정 서비스 »

|

pty — 의사 터미널 유틸리티

소스 코드: Lib/pty.py [https://github.com/python/cpython/tree/3.7/Lib/pty.py]

pty 모듈은 의사 터미널 개념을 처리하기 위한 연산을 정의합니다: 다른 프로세스를 시작하고, 그것의 제어 터미널에 프로그래밍 방식으로 쓰고 읽습니다.

의사 터미널 처리는 플랫폼에 따라 매우 다르므로, 리눅스에서만 수행할 수 있는 코드가 있습니다. (리눅스 코드는 다른 플랫폼에서도 작동하리라고 기대되지만, 아직 테스트 되지는 않았습니다.)

pty 모듈은 다음 함수를 정의합니다:

pty.fork()

포크. 자식의 제어 터미널을 의사 터미널에 연결합니다. 반환 값은 (pid, fd)입니다. 자식은 pid 0을 받고, fd는 유효하지 않음에 유의하십시오. 부모의 반환 값은 자식의 pid이고, fd는 자식의 제어 터미널(또한, 자식의 표준 입력과 출력)에 연결된 파일 기술자입니다.

pty.openpty()

가능하면 os.openpty()를 사용하고, 그렇지 않으면 일반 유닉스 시스템을 위한 에뮬레이션 코드를 사용해서 새로운 의사 터미널 쌍을 엽니다. 각각 마스터와 슬레이브인 파일 기술자 쌍 (master, slave)를 반환합니다.

pty.spawn(argv[, master_read[, stdin_read]])

프로세스를 스폰하고, 그것의 제어 터미널을 현재 프로세스의 표준 입출력과 연결합니다. 이것은 종종 제어 터미널에서 읽으려고 하는 프로그램을 조절하는 데 사용됩니다. pty 뒤에 스폰된 프로세스가 결국 종료할 것으로 기대하고, 그 때 spawn이 반환됩니다.

함수 master_read와 stdin_read는 그들이 읽어야 할 파일 기술자를 전달받고, 항상 바이트열을 반환해야 합니다. 자식 프로세스가 종료하기 전에 spawn이 강제로 반환되게 하려면 OSError를 발생시켜야 합니다.

두 함수의 기본 구현은 함수가 호출될 때마다 최대 1024바이트를 읽고 반환합니다. master_read 콜백으로 의사 터미널의 마스터 파일 기술자가 전달되어 자식 프로세스의 출력을 읽으며, stdin_read는 파일 기술자 0을 전달받아, 부모 프로세스의 표준 입력을 읽습니다.

두 콜백 중 하나가 빈 바이트열을 반환하는 것은 파일 끝(EOF) 조건으로 해석되며, 그 이후로 해당 콜백은 호출되지 않습니다. stdin_read가 EOF 신호를 보내면 제어 터미널은 더는 부모 프로세스나 자식 프로세스와 통신할 수 없습니다. 자식 프로세스가 입력 없이 종료하지 않는 한, spawn은 영원히 반복됩니다. master_read가 EOF 신호를 보내면 같은 동작으로 이어집니다 (적어도 리눅스에서는).

두 콜백이 모두 EOF 신호를 보내면, select가 세 개의 빈 리스트를 전달할 때 플랫폼에서 에러를 일으키지 않는 한 spawn은 아마도 절대 반환하지 않습니다. 이것은 버그이고, issue 26228 [https://bugs.python.org/issue26228]에서 설명하고 있습니다.

버전 3.4에서 변경: 이제 spawn()은 자식 프로세스에 대한 os.waitpid()로부터 온 상태 값을 반환합니다.

예제

다음 프로그램은 유닉스 명령 script(1)과 유사하게 동작하며, 의사 터미널을 사용하여 터미널 세션의 모든 입력과 출력을 “typescript”에 기록합니다.

import argparse
import os
import pty
import sys
import time

parser = argparse.ArgumentParser()
parser.add_argument('-a', dest='append', action='store_true')
parser.add_argument('-p', dest='use_python', action='store_true')
parser.add_argument('filename', nargs='?', default='typescript')
options = parser.parse_args()

shell = sys.executable if options.use_python else os.environ.get('SHELL', 'sh')
filename = options.filename
mode = 'ab' if options.append else 'wb'

with open(filename, mode) as script:
    def read(fd):
        data = os.read(fd, 1024)
        script.write(data)
        return data

    print('Script started, file is', filename)
    script.write(('Script started on %s\n' % time.asctime()).encode())

    pty.spawn(shell, read)

    script.write(('Script done on %s\n' % time.asctime()).encode())
    print('Script done, file is', filename)

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

유닉스 특정 서비스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

유닉스 특정 서비스 »

|

fcntl — fcntl과 ioctl 시스템 호출

이 모듈은 파일 기술자에 대한 파일 제어와 I/O 제어를 수행합니다. fcntl()과 ioctl() 유닉스 루틴에 대한 인터페이스입니다. 이 호출에 대한 자세한 설명은 fcntl(2)과 ioctl(2) 유닉스 매뉴얼 페이지를 참조하십시오.

이 모듈의 모든 함수는 첫 번째 인자로 파일 기술자 fd를 받아들입니다. 이것은 sys.stdin.fileno()에 의해 반환된 것과 같은 정수 파일 기술자이거나 sys.stdin 자체와 같은 io.IOBase 객체일 수 있습니다. 이 객체는 실제 파일 기술자를 반환하는 fileno()를 제공합니다.

버전 3.3에서 변경: 이 모듈의 연산은 IOError를 발생시켰는데, 이제는 OSError를 발생시킵니다.

이 모듈은 다음 함수를 정의합니다:

fcntl.fcntl(fd, cmd, arg=0)

파일 기술자 fd(fileno() 메서드를 제공하는 파일 객체도 허용됩니다)에 대해 cmd 연산을 수행합니다. cmd에 사용되는 값은 운영 체제에 따라 다르며, 관련 C 헤더 파일에 사용된 것과 같은 이름을 사용하여 fcntl 모듈에서 상수로 제공됩니다. 인자 arg는 정숫값이나 bytes 객체가 될 수 있습니다. 정숫값일 때, 이 함수의 반환 값은 C fcntl() 호출의 정수 반환 값입니다. 인자가 바이트열일 때 바이너리 구조체를 나타냅니다, 예를 들어 struct.pack()으로 만든 것입니다. 바이너리 데이터는 주소가 C fcntl() 호출에 전달될 버퍼로 복사됩니다. 호출 성공 후 반환 값은 버퍼 내용이며, bytes 객체로 변환됩니다. 반환된 객체의 길이는 arg 인자의 길이와 같습니다. 이것은 1024바이트로 제한됩니다. 운영 체제에 의해 버퍼로 반환된 정보가 1024바이트보다 크면, 세그멘테이션 위반이나 더 미묘한 데이터 손상이 발생할 가능성이 큽니다.

fcntl()이 실패하면, OSError가 발생합니다.

fcntl.ioctl(fd, request, arg=0, mutate_flag=True)

이 함수는 인자 처리가 훨씬 더 복잡하다는 점을 제외하면, fcntl() 함수와 같습니다.

request 매개 변수는 32비트에 맞출 수 있는 값으로 제한됩니다. request 인자로 사용하기 위한 추가 상수는 관련 C 헤더 파일에서 사용된 것과 같은 이름으로 termios 모듈에서 제공됩니다.

매개 변수 arg는 정수, 읽기 전용 버퍼 인터페이스를 지원하는 (bytes 같은) 객체 또는 읽기-쓰기 버퍼 인터페이스를 지원하는 (bytearray 같은) 객체 중 하나일 수 있습니다.

마지막 경우를 제외하고는, 동작이 fcntl() 함수와 같습니다.

가변 버퍼가 전달되면, 동작은 mutate_flag 매개 변수의 값에 의해 결정됩니다.

거짓이면, 버퍼의 가변성은 무시되고 동작은 읽기 전용 버퍼일 때와 같습니다. 단, 위에서 언급한 1024바이트 제한은 피할 수 있습니다 – 최소한 전달한 버퍼가 운영 체제가 원하는 만큼 길면 작동해야 합니다.

mutate_flag가 참(기본값)이면, 버퍼가 (결과적으로) 하부 ioctl() 시스템 호출로 전달되고, 이 호출의 반환 코드는 호출하는 파이썬으로 다시 전달되고 버퍼의 새로운 내용은 ioctl()의 동작을 반영합니다. 이것은 약간 단순화한 설명인데, 제공된 버퍼가 1024바이트보다 작으면, 1024바이트 길이의 정적 버퍼에 먼저 복사된 다음, 이 정적 버퍼가 ioctl()로 전달되고, 정적 버퍼를 제공된 버퍼로 다시 복사하기 때문입니다.

ioctl()이 실패하면, OSError 예외가 발생합니다.

예제:

>>> import array, fcntl, struct, termios, os
>>> os.getpgrp()
13341
>>> struct.unpack('h', fcntl.ioctl(0, termios.TIOCGPGRP, "  "))[0]
13341
>>> buf = array.array('h', [0])
>>> fcntl.ioctl(0, termios.TIOCGPGRP, buf, 1)
0
>>> buf
array('h', [13341])

fcntl.flock(fd, operation)

파일 기술자 fd(fileno() 메서드를 제공하는 파일 객체도 허용됩니다)에 대한 잠금 연산 operation을 수행합니다. 자세한 내용은 유닉스 매뉴얼 flock(2)를 참조하십시오. (일부 시스템에서는, 이 함수가 fcntl()를 사용하여 에뮬레이트됩니다.)

flock()이 실패하면, OSError 예외가 발생합니다.

fcntl.lockf(fd, cmd, len=0, start=0, whence=0)

이것은 본질에서 fcntl() 잠금 호출에 대한 래퍼입니다. fd는 잠그거나 잠금 해제할 파일의 파일 기술자이고, cmd는 다음 값 중 하나입니다:

LOCK_UN – 잠금 해제

LOCK_SH – 공유 잠금 획득

LOCK_EX – 배타적 잠금 획득

cmd가 LOCK_SH나 LOCK_EX 일 때, 잠금 획득시 블로킹을 피하고자 LOCK_NB와 비트별 OR 될 수 있습니다. LOCK_NB가 사용되고 잠금을 얻을 수 없을 때, OSError가 발생하고 errno 어트리뷰트가 EACCES나 EAGAIN으로 설정됩니다 (운영 체제에 따라 다릅니다; 이식성을 위해서 두 값을 모두 확인하십시오). 적어도 일부 시스템에서, LOCK_EX는 파일 기술자가 쓰기 위해 열린 파일을 참조할 때만 사용할 수 있습니다.

len은 잠글 바이트 수, start는 whence가 정의하는 기준으로 잠금이 시작되는 바이트 오프셋이며 whence는 io.IOBase.seek()에서와 같은데, 구체적으로 다음과 같습니다:

0 – 파일의 시작에 상대적 (os.SEEK_SET)

1 – 현재 버퍼 위치에 상대적 (os.SEEK_CUR)

2 – 파일의 끝에 상대적 (os.SEEK_END)

start의 기본값은 파일 시작 부분에서 시작한다는 의미인 0입니다. len의 기본값은 파일 끝까지 잠그는 것을 의미하는 0입니다. whence의 기본값도 0입니다.

예제 (모두 SVR4 호환 시스템에서):

import struct, fcntl, os

f = open(...)
rv = fcntl.fcntl(f, fcntl.F_SETFL, os.O_NDELAY)

lockdata = struct.pack('hhllhh', fcntl.F_WRLCK, 0, 0, 0, 0, 0)
rv = fcntl.fcntl(f, fcntl.F_SETLKW, lockdata)

첫 번째 예제에서 반환 값 변수 rv는 정숫값을 저장합니다; 두 번째 예제에서는 bytes 객체를 저장합니다. lockdata 변수에 대한 구조체 배치는 시스템 종속적입니다 — 그래서 flock() 호출을 사용하는 것이 더 좋을 수 있습니다.

더 보기

모듈 os

잠금 플래그 O_SHLOCK과 O_EXLOCK이 os 모듈에 있으면 (BSD에만 해당합니다), os.open() 함수는 lockf()와 flock() 함수의 대안을 제공합니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

유닉스 특정 서비스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

유닉스 특정 서비스 »

|

pipes — 셸 파이프라인에 대한 인터페이스

소스 코드: Lib/pipes.py [https://github.com/python/cpython/tree/3.7/Lib/pipes.py]

pipes 모듈은 파이프라인 개념을 추상화하는 클래스를 정의합니다 — 하나의 파일을 다른 파일로 변환하는 일련의 변환기입니다.

모듈이 /bin/sh 명령 줄을 사용하므로, os.system() 와 os.popen()를 위한 POSIX 나 그와 호환되는 셸이 필요합니다.

pipes 모듈은 다음 클래스를 정의합니다:

class pipes.Template

파이프라인의 추상화.

예제:

>>> import pipes
>>> t = pipes.Template()
>>> t.append('tr a-z A-Z', '--')
>>> f = t.open('pipefile', 'w')
>>> f.write('hello world')
>>> f.close()
>>> open('pipefile').read()
'HELLO WORLD'

Template 객체

Template 객체는 다음 메서드를 갖습니다:

Template.reset()

파이프라인 템플릿을 초기 상태로 복원합니다.

Template.clone()

새로운 동등한 파이프라인 템플릿을 반환합니다.

Template.debug(flag)

flag가 참이면, 디버깅을 켭니다. 그렇지 않으면, 디버깅을 끕니다. 디버깅이 켜지면, 실행되는 명령이 인쇄되고, 셸에 set -x 명령이 주어져 더 자세한 정보가 표시됩니다.

Template.append(cmd, kind)

끝에 새로운 액션을 추가합니다. cmd 변수는 올바른 bourne 셸 명령이어야 합니다. kind 변수는 두 개의 문자로 구성됩니다.

첫 번째 문자는 '-' (명령이 표준 입력을 읽음을 의미), 'f' (명령이 명령 줄에서 주어진 파일을 읽음을 의미) 또는 '.' (명령이 입력을 읽지 않음을 의미하므로, 반드시 첫 번째여야 합니다) 일 수 있습니다.

마찬가지로, 두 번째 문자는 '-' (명령이 표준 출력에 쓰는 것을 의미), 'f' (명령이 명령 줄에서 주어진 파일에 쓰는 것을 의미) 또는 '.' (명령이 아무것도 쓰지 않음을 의미하므로, 반드시 마지막이어야 합니다) 일 수 있습니다.

Template.prepend(cmd, kind)

처음에 새로운 액션을 추가합니다. 인자에 대한 설명은 append()를 참조하십시오.

Template.open(file, mode)

file로 열려 있지만, 파이프라인에서 읽거나 파이프라인으로 쓰는 파일류 객체를 반환합니다. 'r', 'w' 중 하나만 주어질 수 있습니다.

Template.copy(infile, outfile)

파이프를 통해 infile를 outfile로 복사합니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

유닉스 특정 서비스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

유닉스 특정 서비스 »

|

resource — 자원 사용 정보

이 모듈은 프로그램에서 사용하는 시스템 자원을 측정하고 제어하기 위한 기본 메커니즘을 제공합니다.

기호 상수는 특정 시스템 자원을 지정하고 현재 프로세스나 그 자식들에 대한 사용 정보를 요청하는 데 사용됩니다.

시스템 호출(syscall) 실패 시 OSError가 발생합니다.

exception resource.error

폐지된 OSError의 별칭.

버전 3.3에서 변경: PEP 3151 [https://www.python.org/dev/peps/pep-3151]에 따라, 이 클래스는 OSError의 별칭이 되었습니다.

자원 제한

아래 설명된 setrlimit() 함수를 사용하여 자원 사용량을 제한 할 수 있습니다. 각 자원은 제한의 쌍으로 제어됩니다: 소프트 제한과 하드 제한. 소프트 제한은 현재 제한이며, 시간이 지남에 따라 프로세스에 의해 낮아지거나 높아질 수 있습니다. 소프트 제한은 하드 제한을 초과할 수 없습니다. 하드 제한은 소프트 제한보다 큰 값으로 낮출 수 있지만, 높일 수는 없습니다. (슈퍼 유저의 유효 UID를 갖는 프로세스만 하드 제한을 높일 수 있습니다.)

제한될 수 있는 구체적인 자원은 시스템에 따라 다릅니다. getrlimit(2) 매뉴얼 페이지에 설명되어 있습니다. 아래에 나열된 자원은 하부 운영 체제에서 지원할 때 지원됩니다; 운영 체제에서 검사하거나 제어할 수 없는 자원은 해당 플랫폼에서는 이 모듈에서 정의되지 않습니다.

resource.RLIM_INFINITY

무제한 자원의 제한을 나타내는 데 사용되는 상수.

resource.getrlimit(resource)

resource의 현재 소프트와 하드 제한인 튜플 (soft, hard)를 반환합니다. 유효하지 않은 resource가 지정되면 ValueError가 발생하고, 하부 시스템 호출이 예기치 않게 실패하면 error가 발생합니다.

resource.setrlimit(resource, limits)

resource의 새로운 소비 제한을 설정합니다. limits 인자는 새로운 제한을 설명하는 두 정수의 튜플 (soft, hard)이어야 합니다. RLIM_INFINITY 값을 사용하여 무제한 제한을 요청할 수 있습니다.

유효하지 않은 resource가 지정되거나, 새 소프트 제한이 하드 제한을 초과하거나, 프로세스가 하드 제한을 높이려고 시도하면 ValueError가 발생합니다. 해당 자원의 하드나 시스템 제한이 무제한이 아닐 때 RLIM_INFINITY 제한을 지정하면 ValueError가 발생합니다. 슈퍼 유저의 유효 UID를 갖는 프로세스는 무제한을 포함하여 임의의 유효한 제한 값을 요청할 수 있지만, 요청된 제한이 시스템이 부과한 제한을 초과하면 ValueError가 여전히 발생합니다.

하부 시스템 호출이 실패하면 setrlimit도 error를 발생시킬 수 있습니다.

resource.prlimit(pid, resource[, limits])

하나의 함수에서 setrlimit()와 getrlimit()를 결합하고 임의 프로세스의 자원 제한을 가져오고 설정하도록 지원합니다. pid가 0이면, 호출은 현재 프로세스에 적용됩니다. resource와 limits는 limits가 선택적이라는 점을 제외하고 setrlimit()와 같은 의미입니다.

limits가 제공되지 않으면 함수는 프로세스 pid의 resource 제한을 반환합니다. limits가 제공되면 프로세스의 resource 제한이 설정되고 이전 자원 제한이 반환됩니다.

pid를 찾을 수 없으면 ProcessLookupError가 발생하고 사용자가 프로세스에 대해 CAP_SYS_RESOURCE가 없으면 PermissionError가 발생합니다.

가용성: glibc 2.13 이상이 설치된 리눅스 2.6.36 이상.

버전 3.4에 추가.

이 기호들은 setrlimit()와 getrlimit() 함수를 사용하여 소비를 제어할 수 있는 아래 설명된 자원을 정의합니다. 이 기호의 값은 정확히 C 프로그램에서 사용하는 상수입니다.

getrlimit(2)에 관한 유닉스 매뉴얼 페이지는 사용 가능한 자원을 나열합니다. 모든 시스템이 같은 자원을 나타내는 데 같은 기호나 같은 값을 사용하는 것은 아닙니다. 이 모듈은 플랫폼 차이를 감추려고 시도하지 않습니다 — 플랫폼에서 정의되지 않은 기호는 해당 플랫폼에서 이 모듈에서 제공되지 않습니다.

resource.RLIMIT_CORE

현재 프로세스가 만들 수 있는 코어(core) 파일의 최대 크기 (바이트). 전체 프로세스 이미지를 담기 위해 더 큰 코어가 필요할 때 부분 코어 파일이 생성될 수 있습니다.

resource.RLIMIT_CPU

프로세스가 사용할 수 있는 최대 프로세서 시간 (초). 이 제한을 초과하면, SIGXCPU 시그널이 프로세스로 전송됩니다. (이 시그널을 포착하고, 열려있는 파일을 디스크로 플러시 하는 등 유용한 작업을 수행하는 방법에 대한 정보는 signal 모듈 설명서를 참조하십시오.)

resource.RLIMIT_FSIZE

프로세스가 만들 수 있는 파일의 최대 크기.

resource.RLIMIT_DATA

프로세스 힙(heap)의 최대 크기 (바이트).

resource.RLIMIT_STACK

현재 프로세스에 대한 호출 스택의 최대 크기 (바이트). 이것은 다중 스레드 프로세스에서 메인 스레드의 스택에만 영향을 줍니다.

resource.RLIMIT_RSS

프로세스에서 사용할 수 있는 최대 상주 집합(resident set) 크기.

resource.RLIMIT_NPROC

현재 프로세스가 만들 수 있는 최대 프로세스 수.

resource.RLIMIT_NOFILE

현재 프로세스에 대한 열린 파일 기술자의 최대 수.

resource.RLIMIT_OFILE

RLIMIT_NOFILE의 BSD 이름.

resource.RLIMIT_MEMLOCK

메모리에 잠겨 있을 수 있는 최대 주소 공간.

resource.RLIMIT_VMEM

프로세스가 차지할 수 있는 가장 큰 매핑된 메모리(mapped memory) 영역.

resource.RLIMIT_AS

프로세스에서 사용할 수 있는 주소 공간의 최대 영역 (바이트).

resource.RLIMIT_MSGQUEUE

POSIX 메시지 큐에 할당할 수 있는 바이트 수.

가용성: 리눅스 2.6.8 이상.

버전 3.4에 추가.

resource.RLIMIT_NICE

프로세스의 나이스(nice) 수준의 상한 (20 - rlim_cur로 계산됩니다).

가용성: 리눅스 2.6.12 이상.

버전 3.4에 추가.

resource.RLIMIT_RTPRIO

실시간 우선순위의 상한.

가용성: 리눅스 2.6.12 이상.

버전 3.4에 추가.

resource.RLIMIT_RTTIME

프로세스가 블로킹 시스템 호출 없이 실시간 스케줄링 하에서 소비할 수 있는 CPU 시간의 시간제한 (마이크로초).

가용성: 리눅스 2.6.25 이상.

버전 3.4에 추가.

resource.RLIMIT_SIGPENDING

프로세스가 큐에 넣을 수 있는 시그널 수입니다.

가용성: 리눅스 2.6.8 이상.

버전 3.4에 추가.

resource.RLIMIT_SBSIZE

이 사용자의 소켓 버퍼 사용량의 최대 크기 (바이트). 이것은 이 사용자가 모든 시점에 보유할 수 있는 네트워크 메모리양과 mbuf들의 양을 제한합니다.

가용성: FreeBSD 9 이상.

버전 3.4에 추가.

resource.RLIMIT_SWAP

이 사용자 ID의 모든 프로세스에서 예약하거나 사용할 수 있는 스와프 공간의 최대 크기 (바이트). 이 제한은 vm.overcommit sysctl의 비트 1이 설정되었을 때만 적용됩니다. 이 sysctl에 대한 자세한 설명은 tuning(7)를 참조하십시오.

가용성: FreeBSD 9 이상.

버전 3.4에 추가.

resource.RLIMIT_NPTS

이 사용자 ID로 만들어지는 최대 의사 터미널(pseudo-terminal) 수.

가용성: FreeBSD 9 이상.

버전 3.4에 추가.

자원 사용량

이 함수는 자원 사용량 정보를 조회하는 데 사용됩니다:

resource.getrusage(who)

이 함수는 who 매개 변수에 지정된 대로 현재 프로세스나 그 자식이 소비한 자원을 설명하는 객체를 반환합니다. who 매개 변수는 아래에 설명된 RUSAGE_* 상수 중 하나를 사용하여 지정해야 합니다.

반환 값의 필드는 각각 특정 시스템 자원이 어떻게 사용되었는지를 설명합니다. 예를 들어, 사용자 모드로 실행에 든 시간이나 프로세스가 주 메모리에서 스와프된 횟수. 일부 값은 클록 틱(clock tick) 내부에 의존합니다, 예를 들어, 프로세스에서 사용 중인 메모리양.

이전 버전과의 호환성을 위해, 반환 값은 16개 요소의 튜플로 액세스 할 수도 있습니다.

반환 값의 필드 ru_utime과 ru_stime은 각각 사용자 모드에서 실행된 시간과 시스템 모드에서 실행된 시간을 나타내는 부동 소수점 값입니다. 나머지 값은 정수입니다. 이러한 값에 대한 자세한 내용은 getrusage(2) 매뉴얼 페이지를 참조하십시오. 간략한 요약은 다음과 같습니다:

인덱스

필드

자원

0

ru_utime

time in user mode (float)

1

ru_stime

time in system mode (float)

2

ru_maxrss

최대 상주 집합(resident set) 크기

3

ru_ixrss

공유 메모리 크기

4

ru_idrss

비공유 메모리 크기

5

ru_isrss

비공유 스택 크기

6

ru_minflt

I/O가 필요 없는 페이지 폴트(page fault)

7

ru_majflt

I/O가 필요한 페이지 폴트(page fault)

8

ru_nswap

스와프(swap out) 수

9

ru_inblock

블록 입력 연산(block input operations)

10

ru_oublock

블록 출력 연산(block output operations)

11

ru_msgsnd

보낸 메시지

12

ru_msgrcv

받은 메시지

13

ru_nsignals

받은 시그널

14

ru_nvcsw

자발적 컨텍스트 전환(voluntary context switches)

15

ru_nivcsw

비자발적 컨텍스트 전환(involuntary context switches)

유효하지 않은 who 매개 변수가 지정되면 이 함수는 ValueError를 발생시킵니다. 비정상적인 상황에서 error 예외가 발생할 수도 있습니다.

resource.getpagesize()

시스템 페이지의 바이트 수를 반환합니다. (하드웨어 페이지 크기와 같을 필요는 없습니다.)

다음 RUSAGE_* 기호는 getrusage() 함수에 전달되어 제공할 프로세스 정보를 지정합니다.

resource.RUSAGE_SELF

호출하는 프로세스가 소비한 자원을 요청하기 위해 getrusage()로 전달합니다. 이는 프로세스의 모든 스레드가 사용하는 자원의 합계입니다.

resource.RUSAGE_CHILDREN

호출하는 프로세스의 종료되어 기다리고 있는 자식 프로세스에서 소비한 자원을 요청하기 위해 getrusage()로 전달합니다.

resource.RUSAGE_BOTH

현재 프로세스와 자식 프로세스 모두에서 소비한 자원을 요청하기 위해 getrusage()로 전달합니다. 모든 시스템에서 사용 가능한 것은 아닙니다.

resource.RUSAGE_THREAD

현재 스레드가 소비한 자원을 요청하기 위해 getrusage()에 전달합니다. 모든 시스템에서 사용 가능한 것은 아닙니다.

버전 3.2에 추가.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

유닉스 특정 서비스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

유닉스 특정 서비스 »

|

nis — Sun의 NIS(옐로 페이지)에 대한 인터페이스

nis 모듈은 여러 호스트의 중앙 관리에 유용한 NIS 라이브러리를 감싸는 얇은 래퍼를 제공합니다.

NIS가 유닉스 시스템에만 존재하므로, 이 모듈은 유닉스에서만 사용할 수 있습니다.

nis 모듈은 다음 함수를 정의합니다:

nis.match(key, mapname, domain=default_domain)

맵 mapname에서 key에 대한 일치를 반환하거나, 일치가 없으면 에러(nis.error)를 발생시킵니다. 둘 다 문자열이어야 하며, key는 8비트 클린해야 합니다. 반환 값은 임의의 바이트 배열입니다 (NULL 이나 다른 기쁨을 포함할 수 있습니다).

mapname이 다른 이름의 별칭인지 먼저 검사합니다.

domain 인자는 조회에 사용된 NIS 도메인을 오버라이드할 수 있게 합니다. 지정하지 않으면, 조회는 기본 NIS 도메인에서 이루어집니다.

nis.cat(mapname, domain=default_domain)

match(key, mapname)==value가 되도록 key를 value에 매핑하는 딕셔너리를 반환합니다. 딕셔너리의 키와 값은 모두 임의의 바이트 배열입니다.

mapname이 다른 이름의 별칭인지 먼저 검사합니다.

domain 인자는 조회에 사용된 NIS 도메인을 오버라이드할 수 있게 합니다. 지정하지 않으면, 조회는 기본 NIS 도메인에서 이루어집니다.

nis.maps(domain=default_domain)

유효한 모든 맵 리스트를 반환합니다.

domain 인자는 조회에 사용된 NIS 도메인을 오버라이드할 수 있게 합니다. 지정하지 않으면, 조회는 기본 NIS 도메인에서 이루어집니다.

nis.get_default_domain()

시스템 기본 NIS 도메인을 반환합니다.

nis 모듈은 다음 예외를 정의합니다:

exception nis.error

NIS 함수가 에러 코드를 반환할 때 발생하는 에러.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

유닉스 특정 서비스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

유닉스 특정 서비스 »

|

syslog — 유닉스 syslog 라이브러리 루틴

이 모듈은 유닉스 syslog 라이브러리 루틴에 대한 인터페이스를 제공합니다. syslog 기능에 대한 자세한 설명은 유닉스 매뉴얼 페이지를 참조하십시오.

이 모듈은 시스템 syslog 계열의 루틴을 감쌉니다. syslog 서버와 통신할 수 있는 순수한 파이썬 라이브러리는 logging.handlers 모듈에서 SysLogHandler로 제공됩니다.

모듈은 다음 함수를 정의합니다:

syslog.syslog(message)

syslog.syslog(priority, message)

message 문자열을 시스템 로거로 보냅니다. 필요하면 끝에 줄 넘김이 추가됩니다. 각 메시지에는 시설(facility) 과 수준(level)으로 구성된 우선순위(priority)로 꼬리표가 붙습니다. 선택적 priority 인자(기본값은 LOG_INFO)는 메시지 우선순위를 결정합니다. 시설이 논리합(LOG_INFO | LOG_USER)을 사용하여 priority로 인코딩되지 않으면, openlog() 호출에 지정된 값이 사용됩니다.

syslog() 호출 이전에 openlog()가 호출되지 않았으면, 인자 없이 openlog()가 호출됩니다.

syslog.openlog([ident[, logoption[, facility]]])

후속 syslog() 호출의 로깅 옵션은 openlog()를 호출하여 설정할 수 있습니다. 로그가 현재 열려 있지 않으면 syslog()는 인자 없이 openlog()를 호출합니다.

선택적 ident 키워드 인자는 모든 메시지 앞에 추가되는 문자열이며, 기본값은 선행 경로 구성 요소가 제거된 sys.argv[0]입니다. 선택적 logoption 키워드 인자(기본값은 0)는 비트 필드입니다 – 결합할 수 있는 가능한 값은 아래를 보십시오. 선택적 facility 키워드 인자(기본값은 LOG_USER)는 명시적으로 인코드 된 시설이 없는 메시지에 대한 기본 시설을 설정합니다.

버전 3.2에서 변경: 이전 버전에서는, 키워드 인자가 허용되지 않았고, ident가 필수였습니다. ident의 기본값은 시스템 라이브러리에 따라 달랐으며, 종종 파이썬 프로그램 파일 이름 대신 python이었습니다.

syslog.closelog()

syslog 모듈값을 재설정하고 시스템 라이브러리 closelog()를 호출합니다.

이것은 모듈이 처음 임포트될 때처럼 작동하도록 합니다. 예를 들어, openlog()는 첫 번째 syslog() 호출에서 호출되며(openlog()가 아직 호출되지 않았다면), ident 와 기타 openlog() 매개 변수가 기본값으로 재설정됩니다.

syslog.setlogmask(maskpri)

우선순위 마스크를 maskpri로 설정하고 이전 마스크값을 반환합니다. maskpri에 설정되지 않은 우선순위 수준으로 syslog()를 호출하면 무시됩니다. 기본값은 모든 우선순위를 로그 하는 것입니다. 함수 LOG_MASK(pri)는 개별 우선순위 pri에 대한 마스크를 계산합니다. 함수 LOG_UPTO(pri)는 pri까지의 모든 우선순위에 대한 마스크를 계산합니다.

모듈은 다음 상수를 정의합니다:

우선순위 수준 (높음에서 낮음 순서):

LOG_EMERG, LOG_ALERT, LOG_CRIT, LOG_ERR, LOG_WARNING, LOG_NOTICE, LOG_INFO, LOG_DEBUG.

시설:

LOG_KERN, LOG_USER, LOG_MAIL, LOG_DAEMON, LOG_AUTH, LOG_LPR, LOG_NEWS, LOG_UUCP, LOG_CRON, LOG_SYSLOG, LOG_LOCAL0 ~ LOG_LOCAL7 및 <syslog.h>에 정의되었으면, LOG_AUTHPRIV.

로그 옵션:

LOG_PID, LOG_CONS, LOG_NDELAY 및 <syslog.h>에 정의되었으면, LOG_ODELAY, LOG_NOWAIT 및 LOG_PERROR.

예제

간단한 예제

간단한 예제 집합:

import syslog

syslog.syslog('Processing started')
if error:
    syslog.syslog(syslog.LOG_ERR, 'Processing started')

일부 로그 옵션 설정의 예, 이것은 로그 메시지에 프로세스 ID를 포함하며, 메일 로깅에 사용되는 대상 시설로 메시지를 기록합니다:

syslog.openlog(logoption=syslog.LOG_PID, facility=syslog.LOG_MAIL)
syslog.syslog('E-mail processing initiated...')

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

유닉스 특정 서비스 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

|

대체된 모듈

이 장에서 설명하는 모듈은 폐지되었으며 하위 호환성을 위해서만 유지됩니다. 다른 모듈에 의해 대체되었습니다.

optparse — Parser for command line options

Background

Terminology

What are options for?

What are positional arguments for?

Tutorial

Understanding option actions

The store action

Handling boolean (flag) options

Other actions

Default values

Generating help

Grouping Options

Printing a version string

How optparse handles errors

Putting it all together

Reference Guide

Creating the parser

Populating the parser

Defining options

Option attributes

Standard option actions

Standard option types

Parsing arguments

Querying and manipulating your option parser

Conflicts between options

Cleanup

Other methods

Option Callbacks

Defining a callback option

How callbacks are called

Raising errors in a callback

Callback example 1: trivial callback

Callback example 2: check option order

Callback example 3: check option order (generalized)

Callback example 4: check arbitrary condition

Callback example 5: fixed arguments

Callback example 6: variable arguments

Extending optparse

Adding new types

Adding new actions

imp — Access the import internals

Examples

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

대체된 모듈 »

|

optparse — Parser for command line options

Source code: Lib/optparse.py [https://github.com/python/cpython/tree/3.7/Lib/optparse.py]

버전 3.2부터 폐지: The optparse module is deprecated and will not be developed further; development will continue with the argparse module.

optparse is a more convenient, flexible, and powerful library for parsing command-line options than the old getopt module. optparse uses a more declarative style of command-line parsing: you create an instance of OptionParser, populate it with options, and parse the command line. optparse allows users to specify options in the conventional GNU/POSIX syntax, and additionally generates usage and help messages for you.

Here’s an example of using optparse in a simple script:

from optparse import OptionParser
...
parser = OptionParser()
parser.add_option("-f", "--file", dest="filename",
                  help="write report to FILE", metavar="FILE")
parser.add_option("-q", "--quiet",
                  action="store_false", dest="verbose", default=True,
                  help="don't print status messages to stdout")

(options, args) = parser.parse_args()

With these few lines of code, users of your script can now do the “usual thing” on the command-line, for example:

<yourscript> --file=outfile -q

As it parses the command line, optparse sets attributes of the options object returned by parse_args() based on user-supplied command-line values. When parse_args() returns from parsing this command line, options.filename will be "outfile" and options.verbose will be False. optparse supports both long and short options, allows short options to be merged together, and allows options to be associated with their arguments in a variety of ways. Thus, the following command lines are all equivalent to the above example:

<yourscript> -f outfile --quiet
<yourscript> --quiet --file outfile
<yourscript> -q -foutfile
<yourscript> -qfoutfile

Additionally, users can run one of

<yourscript> -h
<yourscript> --help

and optparse will print out a brief summary of your script’s options:

Usage: <yourscript> [options]

Options:
  -h, --help            show this help message and exit
  -f FILE, --file=FILE  write report to FILE
  -q, --quiet           don't print status messages to stdout

where the value of yourscript is determined at runtime (normally from sys.argv[0]).

Background

optparse was explicitly designed to encourage the creation of programs with straightforward, conventional command-line interfaces. To that end, it supports only the most common command-line syntax and semantics conventionally used under Unix. If you are unfamiliar with these conventions, read this section to acquaint yourself with them.

Terminology

argument

a string entered on the command-line, and passed by the shell to execl() or execv(). In Python, arguments are elements of sys.argv[1:] (sys.argv[0] is the name of the program being executed). Unix shells also use the term “word”.

It is occasionally desirable to substitute an argument list other than sys.argv[1:], so you should read “argument” as “an element of sys.argv[1:], or of some other list provided as a substitute for sys.argv[1:]”.

option

an argument used to supply extra information to guide or customize the execution of a program. There are many different syntaxes for options; the traditional Unix syntax is a hyphen (“-”) followed by a single letter, e.g. -x or -F. Also, traditional Unix syntax allows multiple options to be merged into a single argument, e.g. -x -F is equivalent to -xF. The GNU project introduced -- followed by a series of hyphen-separated words, e.g. --file or --dry-run. These are the only two option syntaxes provided by optparse.

Some other option syntaxes that the world has seen include:

a hyphen followed by a few letters, e.g. -pf (this is not the same as multiple options merged into a single argument)

a hyphen followed by a whole word, e.g. -file (this is technically equivalent to the previous syntax, but they aren’t usually seen in the same program)

a plus sign followed by a single letter, or a few letters, or a word, e.g. +f, +rgb

a slash followed by a letter, or a few letters, or a word, e.g. /f, /file

These option syntaxes are not supported by optparse, and they never will be. This is deliberate: the first three are non-standard on any environment, and the last only makes sense if you’re exclusively targeting VMS, MS-DOS, and/or Windows.

option argument

an argument that follows an option, is closely associated with that option, and is consumed from the argument list when that option is. With optparse, option arguments may either be in a separate argument from their option:

-f foo
--file foo

or included in the same argument:

-ffoo
--file=foo

Typically, a given option either takes an argument or it doesn’t. Lots of people want an “optional option arguments” feature, meaning that some options will take an argument if they see it, and won’t if they don’t. This is somewhat controversial, because it makes parsing ambiguous: if -a takes an optional argument and -b is another option entirely, how do we interpret -ab? Because of this ambiguity, optparse does not support this feature.

positional argument

something leftover in the argument list after options have been parsed, i.e. after options and their arguments have been parsed and removed from the argument list.

required option

an option that must be supplied on the command-line; note that the phrase “required option” is self-contradictory in English. optparse doesn’t prevent you from implementing required options, but doesn’t give you much help at it either.

For example, consider this hypothetical command-line:

prog -v --report report.txt foo bar

-v and --report are both options. Assuming that --report takes one argument, report.txt is an option argument. foo and bar are positional arguments.

What are options for?

Options are used to provide extra information to tune or customize the execution of a program. In case it wasn’t clear, options are usually optional. A program should be able to run just fine with no options whatsoever. (Pick a random program from the Unix or GNU toolsets. Can it run without any options at all and still make sense? The main exceptions are find, tar, and dd—all of which are mutant oddballs that have been rightly criticized for their non-standard syntax and confusing interfaces.)

Lots of people want their programs to have “required options”. Think about it. If it’s required, then it’s not optional! If there is a piece of information that your program absolutely requires in order to run successfully, that’s what positional arguments are for.

As an example of good command-line interface design, consider the humble cp utility, for copying files. It doesn’t make much sense to try to copy files without supplying a destination and at least one source. Hence, cp fails if you run it with no arguments. However, it has a flexible, useful syntax that does not require any options at all:

cp SOURCE DEST
cp SOURCE ... DEST-DIR

You can get pretty far with just that. Most cp implementations provide a bunch of options to tweak exactly how the files are copied: you can preserve mode and modification time, avoid following symlinks, ask before clobbering existing files, etc. But none of this distracts from the core mission of cp, which is to copy either one file to another, or several files to another directory.

What are positional arguments for?

Positional arguments are for those pieces of information that your program absolutely, positively requires to run.

A good user interface should have as few absolute requirements as possible. If your program requires 17 distinct pieces of information in order to run successfully, it doesn’t much matter how you get that information from the user—most people will give up and walk away before they successfully run the program. This applies whether the user interface is a command-line, a configuration file, or a GUI: if you make that many demands on your users, most of them will simply give up.

In short, try to minimize the amount of information that users are absolutely required to supply—use sensible defaults whenever possible. Of course, you also want to make your programs reasonably flexible. That’s what options are for. Again, it doesn’t matter if they are entries in a config file, widgets in the “Preferences” dialog of a GUI, or command-line options—the more options you implement, the more flexible your program is, and the more complicated its implementation becomes. Too much flexibility has drawbacks as well, of course; too many options can overwhelm users and make your code much harder to maintain.

Tutorial

While optparse is quite flexible and powerful, it’s also straightforward to use in most cases. This section covers the code patterns that are common to any optparse-based program.

First, you need to import the OptionParser class; then, early in the main program, create an OptionParser instance:

from optparse import OptionParser
...
parser = OptionParser()

Then you can start defining options. The basic syntax is:

parser.add_option(opt_str, ...,
                  attr=value, ...)

Each option has one or more option strings, such as -f or --file, and several option attributes that tell optparse what to expect and what to do when it encounters that option on the command line.

Typically, each option will have one short option string and one long option string, e.g.:

parser.add_option("-f", "--file", ...)

You’re free to define as many short option strings and as many long option strings as you like (including zero), as long as there is at least one option string overall.

The option strings passed to OptionParser.add_option() are effectively labels for the option defined by that call. For brevity, we will frequently refer to encountering an option on the command line; in reality, optparse encounters option strings and looks up options from them.

Once all of your options are defined, instruct optparse to parse your program’s command line:

(options, args) = parser.parse_args()

(If you like, you can pass a custom argument list to parse_args(), but that’s rarely necessary: by default it uses sys.argv[1:].)

parse_args() returns two values:

options, an object containing values for all of your options—e.g. if --file takes a single string argument, then options.file will be the filename supplied by the user, or None if the user did not supply that option

args, the list of positional arguments leftover after parsing options

This tutorial section only covers the four most important option attributes: action, type, dest (destination), and help. Of these, action is the most fundamental.

Understanding option actions

Actions tell optparse what to do when it encounters an option on the command line. There is a fixed set of actions hard-coded into optparse; adding new actions is an advanced topic covered in section Extending optparse. Most actions tell optparse to store a value in some variable—for example, take a string from the command line and store it in an attribute of options.

If you don’t specify an option action, optparse defaults to store.

The store action

The most common option action is store, which tells optparse to take the next argument (or the remainder of the current argument), ensure that it is of the correct type, and store it to your chosen destination.

For example:

parser.add_option("-f", "--file",
                  action="store", type="string", dest="filename")

Now let’s make up a fake command line and ask optparse to parse it:

args = ["-f", "foo.txt"]
(options, args) = parser.parse_args(args)

When optparse sees the option string -f, it consumes the next argument, foo.txt, and stores it in options.filename. So, after this call to parse_args(), options.filename is "foo.txt".

Some other option types supported by optparse are int and float. Here’s an option that expects an integer argument:

parser.add_option("-n", type="int", dest="num")

Note that this option has no long option string, which is perfectly acceptable. Also, there’s no explicit action, since the default is store.

Let’s parse another fake command-line. This time, we’ll jam the option argument right up against the option: since -n42 (one argument) is equivalent to -n 42 (two arguments), the code

(options, args) = parser.parse_args(["-n42"])
print(options.num)

will print 42.

If you don’t specify a type, optparse assumes string. Combined with the fact that the default action is store, that means our first example can be a lot shorter:

parser.add_option("-f", "--file", dest="filename")

If you don’t supply a destination, optparse figures out a sensible default from the option strings: if the first long option string is --foo-bar, then the default destination is foo_bar. If there are no long option strings, optparse looks at the first short option string: the default destination for -f is f.

optparse also includes the built-in complex type. Adding types is covered in section Extending optparse.

Handling boolean (flag) options

Flag options—set a variable to true or false when a particular option is seen—are quite common. optparse supports them with two separate actions, store_true and store_false. For example, you might have a verbose flag that is turned on with -v and off with -q:

parser.add_option("-v", action="store_true", dest="verbose")
parser.add_option("-q", action="store_false", dest="verbose")

Here we have two different options with the same destination, which is perfectly OK. (It just means you have to be a bit careful when setting default values—see below.)

When optparse encounters -v on the command line, it sets options.verbose to True; when it encounters -q, options.verbose is set to False.

Other actions

Some other actions supported by optparse are:

"store_const"

store a constant value

"append"

append this option’s argument to a list

"count"

increment a counter by one

"callback"

call a specified function

These are covered in section Reference Guide, Reference Guide and section Option Callbacks.

Default values

All of the above examples involve setting some variable (the “destination”) when certain command-line options are seen. What happens if those options are never seen? Since we didn’t supply any defaults, they are all set to None. This is usually fine, but sometimes you want more control. optparse lets you supply a default value for each destination, which is assigned before the command line is parsed.

First, consider the verbose/quiet example. If we want optparse to set verbose to True unless -q is seen, then we can do this:

parser.add_option("-v", action="store_true", dest="verbose", default=True)
parser.add_option("-q", action="store_false", dest="verbose")

Since default values apply to the destination rather than to any particular option, and these two options happen to have the same destination, this is exactly equivalent:

parser.add_option("-v", action="store_true", dest="verbose")
parser.add_option("-q", action="store_false", dest="verbose", default=True)

Consider this:

parser.add_option("-v", action="store_true", dest="verbose", default=False)
parser.add_option("-q", action="store_false", dest="verbose", default=True)

Again, the default value for verbose will be True: the last default value supplied for any particular destination is the one that counts.

A clearer way to specify default values is the set_defaults() method of OptionParser, which you can call at any time before calling parse_args():

parser.set_defaults(verbose=True)
parser.add_option(...)
(options, args) = parser.parse_args()

As before, the last value specified for a given option destination is the one that counts. For clarity, try to use one method or the other of setting default values, not both.

Generating help

optparse’s ability to generate help and usage text automatically is useful for creating user-friendly command-line interfaces. All you have to do is supply a help value for each option, and optionally a short usage message for your whole program. Here’s an OptionParser populated with user-friendly (documented) options:

usage = "usage: %prog [options] arg1 arg2"
parser = OptionParser(usage=usage)
parser.add_option("-v", "--verbose",
                  action="store_true", dest="verbose", default=True,
                  help="make lots of noise [default]")
parser.add_option("-q", "--quiet",
                  action="store_false", dest="verbose",
                  help="be vewwy quiet (I'm hunting wabbits)")
parser.add_option("-f", "--filename",
                  metavar="FILE", help="write output to FILE")
parser.add_option("-m", "--mode",
                  default="intermediate",
                  help="interaction mode: novice, intermediate, "
                       "or expert [default: %default]")

If optparse encounters either -h or --help on the command-line, or if you just call parser.print_help(), it prints the following to standard output:

Usage: <yourscript> [options] arg1 arg2

Options:
  -h, --help            show this help message and exit
  -v, --verbose         make lots of noise [default]
  -q, --quiet           be vewwy quiet (I'm hunting wabbits)
  -f FILE, --filename=FILE
                        write output to FILE
  -m MODE, --mode=MODE  interaction mode: novice, intermediate, or
                        expert [default: intermediate]

(If the help output is triggered by a help option, optparse exits after printing the help text.)

There’s a lot going on here to help optparse generate the best possible help message:

the script defines its own usage message:

usage = "usage: %prog [options] arg1 arg2"

optparse expands %prog in the usage string to the name of the current program, i.e. os.path.basename(sys.argv[0]). The expanded string is then printed before the detailed option help.

If you don’t supply a usage string, optparse uses a bland but sensible default: "Usage: %prog [options]", which is fine if your script doesn’t take any positional arguments.

every option defines a help string, and doesn’t worry about line-wrapping—optparse takes care of wrapping lines and making the help output look good.

options that take a value indicate this fact in their automatically-generated help message, e.g. for the “mode” option:

-m MODE, --mode=MODE

Here, “MODE” is called the meta-variable: it stands for the argument that the user is expected to supply to -m/--mode. By default, optparse converts the destination variable name to uppercase and uses that for the meta-variable. Sometimes, that’s not what you want—for example, the --filename option explicitly sets metavar="FILE", resulting in this automatically-generated option description:

-f FILE, --filename=FILE

This is important for more than just saving space, though: the manually written help text uses the meta-variable FILE to clue the user in that there’s a connection between the semi-formal syntax -f FILE and the informal semantic description “write output to FILE”. This is a simple but effective way to make your help text a lot clearer and more useful for end users.

options that have a default value can include %default in the help string—optparse will replace it with str() of the option’s default value. If an option has no default value (or the default value is None), %default expands to none.

Grouping Options

When dealing with many options, it is convenient to group these options for better help output. An OptionParser can contain several option groups, each of which can contain several options.

An option group is obtained using the class OptionGroup:

class optparse.OptionGroup(parser, title, description=None)

where

parser is the OptionParser instance the group will be inserted in to

title is the group title

description, optional, is a long description of the group

OptionGroup inherits from OptionContainer (like OptionParser) and so the add_option() method can be used to add an option to the group.

Once all the options are declared, using the OptionParser method add_option_group() the group is added to the previously defined parser.

Continuing with the parser defined in the previous section, adding an OptionGroup to a parser is easy:

group = OptionGroup(parser, "Dangerous Options",
                    "Caution: use these options at your own risk.  "
                    "It is believed that some of them bite.")
group.add_option("-g", action="store_true", help="Group option.")
parser.add_option_group(group)

This would result in the following help output:

Usage: <yourscript> [options] arg1 arg2

Options:
  -h, --help            show this help message and exit
  -v, --verbose         make lots of noise [default]
  -q, --quiet           be vewwy quiet (I'm hunting wabbits)
  -f FILE, --filename=FILE
                        write output to FILE
  -m MODE, --mode=MODE  interaction mode: novice, intermediate, or
                        expert [default: intermediate]

  Dangerous Options:
    Caution: use these options at your own risk.  It is believed that some
    of them bite.

    -g                  Group option.

A bit more complete example might involve using more than one group: still extending the previous example:

group = OptionGroup(parser, "Dangerous Options",
                    "Caution: use these options at your own risk.  "
                    "It is believed that some of them bite.")
group.add_option("-g", action="store_true", help="Group option.")
parser.add_option_group(group)

group = OptionGroup(parser, "Debug Options")
group.add_option("-d", "--debug", action="store_true",
                 help="Print debug information")
group.add_option("-s", "--sql", action="store_true",
                 help="Print all SQL statements executed")
group.add_option("-e", action="store_true", help="Print every action done")
parser.add_option_group(group)

that results in the following output:

Usage: <yourscript> [options] arg1 arg2

Options:
  -h, --help            show this help message and exit
  -v, --verbose         make lots of noise [default]
  -q, --quiet           be vewwy quiet (I'm hunting wabbits)
  -f FILE, --filename=FILE
                        write output to FILE
  -m MODE, --mode=MODE  interaction mode: novice, intermediate, or expert
                        [default: intermediate]

  Dangerous Options:
    Caution: use these options at your own risk.  It is believed that some
    of them bite.

    -g                  Group option.

  Debug Options:
    -d, --debug         Print debug information
    -s, --sql           Print all SQL statements executed
    -e                  Print every action done

Another interesting method, in particular when working programmatically with option groups is:

OptionParser.get_option_group(opt_str)

Return the OptionGroup to which the short or long option string opt_str (e.g. '-o' or '--option') belongs. If there’s no such OptionGroup, return None.

Printing a version string

Similar to the brief usage string, optparse can also print a version string for your program. You have to supply the string as the version argument to OptionParser:

parser = OptionParser(usage="%prog [-f] [-q]", version="%prog 1.0")

%prog is expanded just like it is in usage. Apart from that, version can contain anything you like. When you supply it, optparse automatically adds a --version option to your parser. If it encounters this option on the command line, it expands your version string (by replacing %prog), prints it to stdout, and exits.

For example, if your script is called /usr/bin/foo:

$ /usr/bin/foo --version
foo 1.0

The following two methods can be used to print and get the version string:

OptionParser.print_version(file=None)

Print the version message for the current program (self.version) to file (default stdout). As with print_usage(), any occurrence of %prog in self.version is replaced with the name of the current program. Does nothing if self.version is empty or undefined.

OptionParser.get_version()

Same as print_version() but returns the version string instead of printing it.

How optparse handles errors

There are two broad classes of errors that optparse has to worry about: programmer errors and user errors. Programmer errors are usually erroneous calls to OptionParser.add_option(), e.g. invalid option strings, unknown option attributes, missing option attributes, etc. These are dealt with in the usual way: raise an exception (either optparse.OptionError or TypeError) and let the program crash.

Handling user errors is much more important, since they are guaranteed to happen no matter how stable your code is. optparse can automatically detect some user errors, such as bad option arguments (passing -n 4x where -n takes an integer argument), missing arguments (-n at the end of the command line, where -n takes an argument of any type). Also, you can call OptionParser.error() to signal an application-defined error condition:

(options, args) = parser.parse_args()
...
if options.a and options.b:
    parser.error("options -a and -b are mutually exclusive")

In either case, optparse handles the error the same way: it prints the program’s usage message and an error message to standard error and exits with error status 2.

Consider the first example above, where the user passes 4x to an option that takes an integer:

$ /usr/bin/foo -n 4x
Usage: foo [options]

foo: error: option -n: invalid integer value: '4x'

Or, where the user fails to pass a value at all:

$ /usr/bin/foo -n
Usage: foo [options]

foo: error: -n option requires an argument

optparse-generated error messages take care always to mention the option involved in the error; be sure to do the same when calling OptionParser.error() from your application code.

If optparse’s default error-handling behaviour does not suit your needs, you’ll need to subclass OptionParser and override its exit() and/or error() methods.

Putting it all together

Here’s what optparse-based scripts usually look like:

from optparse import OptionParser
...
def main():
    usage = "usage: %prog [options] arg"
    parser = OptionParser(usage)
    parser.add_option("-f", "--file", dest="filename",
                      help="read data from FILENAME")
    parser.add_option("-v", "--verbose",
                      action="store_true", dest="verbose")
    parser.add_option("-q", "--quiet",
                      action="store_false", dest="verbose")
    ...
    (options, args) = parser.parse_args()
    if len(args) != 1:
        parser.error("incorrect number of arguments")
    if options.verbose:
        print("reading %s..." % options.filename)
    ...

if __name__ == "__main__":
    main()

Reference Guide

Creating the parser

The first step in using optparse is to create an OptionParser instance.

class optparse.OptionParser(...)

The OptionParser constructor has no required arguments, but a number of optional keyword arguments. You should always pass them as keyword arguments, i.e. do not rely on the order in which the arguments are declared.

usage (default: "%prog [options]")

The usage summary to print when your program is run incorrectly or with a help option. When optparse prints the usage string, it expands %prog to os.path.basename(sys.argv[0]) (or to prog if you passed that keyword argument). To suppress a usage message, pass the special value optparse.SUPPRESS_USAGE.

option_list (default: [])

A list of Option objects to populate the parser with. The options in option_list are added after any options in standard_option_list (a class attribute that may be set by OptionParser subclasses), but before any version or help options. Deprecated; use add_option() after creating the parser instead.

option_class (default: optparse.Option)

Class to use when adding options to the parser in add_option().

version (default: None)

A version string to print when the user supplies a version option. If you supply a true value for version, optparse automatically adds a version option with the single option string --version. The substring %prog is expanded the same as for usage.

conflict_handler (default: "error")

Specifies what to do when options with conflicting option strings are added to the parser; see section Conflicts between options.

description (default: None)

A paragraph of text giving a brief overview of your program. optparse reformats this paragraph to fit the current terminal width and prints it when the user requests help (after usage, but before the list of options).

formatter (default: a new IndentedHelpFormatter)

An instance of optparse.HelpFormatter that will be used for printing help text. optparse provides two concrete classes for this purpose: IndentedHelpFormatter and TitledHelpFormatter.

add_help_option (default: True)

If true, optparse will add a help option (with option strings -h and --help) to the parser.

prog

The string to use when expanding %prog in usage and version instead of os.path.basename(sys.argv[0]).

epilog (default: None)

A paragraph of help text to print after the option help.

Populating the parser

There are several ways to populate the parser with options. The preferred way is by using OptionParser.add_option(), as shown in section Tutorial. add_option() can be called in one of two ways:

pass it an Option instance (as returned by make_option())

pass it any combination of positional and keyword arguments that are acceptable to make_option() (i.e., to the Option constructor), and it will create the Option instance for you

The other alternative is to pass a list of pre-constructed Option instances to the OptionParser constructor, as in:

option_list = [
    make_option("-f", "--filename",
                action="store", type="string", dest="filename"),
    make_option("-q", "--quiet",
                action="store_false", dest="verbose"),
    ]
parser = OptionParser(option_list=option_list)

(make_option() is a factory function for creating Option instances; currently it is an alias for the Option constructor. A future version of optparse may split Option into several classes, and make_option() will pick the right class to instantiate. Do not instantiate Option directly.)

Defining options

Each Option instance represents a set of synonymous command-line option strings, e.g. -f and --file. You can specify any number of short or long option strings, but you must specify at least one overall option string.

The canonical way to create an Option instance is with the add_option() method of OptionParser.

OptionParser.add_option(option)

OptionParser.add_option(*opt_str, attr=value, ...)

To define an option with only a short option string:

parser.add_option("-f", attr=value, ...)

And to define an option with only a long option string:

parser.add_option("--foo", attr=value, ...)

The keyword arguments define attributes of the new Option object. The most important option attribute is action, and it largely determines which other attributes are relevant or required. If you pass irrelevant option attributes, or fail to pass required ones, optparse raises an OptionError exception explaining your mistake.

An option’s action determines what optparse does when it encounters this option on the command-line. The standard option actions hard-coded into optparse are:

"store"

store this option’s argument (default)

"store_const"

store a constant value

"store_true"

store True

"store_false"

store False

"append"

append this option’s argument to a list

"append_const"

append a constant value to a list

"count"

increment a counter by one

"callback"

call a specified function

"help"

print a usage message including all options and the documentation for them

(If you don’t supply an action, the default is "store". For this action, you may also supply type and dest option attributes; see Standard option actions.)

As you can see, most actions involve storing or updating a value somewhere. optparse always creates a special object for this, conventionally called options (it happens to be an instance of optparse.Values). Option arguments (and various other values) are stored as attributes of this object, according to the dest (destination) option attribute.

For example, when you call

parser.parse_args()

one of the first things optparse does is create the options object:

options = Values()

If one of the options in this parser is defined with

parser.add_option("-f", "--file", action="store", type="string", dest="filename")

and the command-line being parsed includes any of the following:

-ffoo
-f foo
--file=foo
--file foo

then optparse, on seeing this option, will do the equivalent of

options.filename = "foo"

The type and dest option attributes are almost as important as action, but action is the only one that makes sense for all options.

Option attributes

The following option attributes may be passed as keyword arguments to OptionParser.add_option(). If you pass an option attribute that is not relevant to a particular option, or fail to pass a required option attribute, optparse raises OptionError.

Option.action

(default: "store")

Determines optparse’s behaviour when this option is seen on the command line; the available options are documented here.

Option.type

(default: "string")

The argument type expected by this option (e.g., "string" or "int"); the available option types are documented here.

Option.dest

(default: derived from option strings)

If the option’s action implies writing or modifying a value somewhere, this tells optparse where to write it: dest names an attribute of the options object that optparse builds as it parses the command line.

Option.default

The value to use for this option’s destination if the option is not seen on the command line. See also OptionParser.set_defaults().

Option.nargs

(default: 1)

How many arguments of type type should be consumed when this option is seen. If > 1, optparse will store a tuple of values to dest.

Option.const

For actions that store a constant value, the constant value to store.

Option.choices

For options of type "choice", the list of strings the user may choose from.

Option.callback

For options with action "callback", the callable to call when this option is seen. See section Option Callbacks for detail on the arguments passed to the callable.

Option.callback_args

Option.callback_kwargs

Additional positional and keyword arguments to pass to callback after the four standard callback arguments.

Option.help

Help text to print for this option when listing all available options after the user supplies a help option (such as --help). If no help text is supplied, the option will be listed without help text. To hide this option, use the special value optparse.SUPPRESS_HELP.

Option.metavar

(default: derived from option strings)

Stand-in for the option argument(s) to use when printing help text. See section Tutorial for an example.

Standard option actions

The various option actions all have slightly different requirements and effects. Most actions have several relevant option attributes which you may specify to guide optparse’s behaviour; a few have required attributes, which you must specify for any option using that action.

"store" [relevant: type, dest, nargs, choices]

The option must be followed by an argument, which is converted to a value according to type and stored in dest. If nargs > 1, multiple arguments will be consumed from the command line; all will be converted according to type and stored to dest as a tuple. See the Standard option types section.

If choices is supplied (a list or tuple of strings), the type defaults to "choice".

If type is not supplied, it defaults to "string".

If dest is not supplied, optparse derives a destination from the first long option string (e.g., --foo-bar implies foo_bar). If there are no long option strings, optparse derives a destination from the first short option string (e.g., -f implies f).

Example:

parser.add_option("-f")
parser.add_option("-p", type="float", nargs=3, dest="point")

As it parses the command line

-f foo.txt -p 1 -3.5 4 -fbar.txt

optparse will set

options.f = "foo.txt"
options.point = (1.0, -3.5, 4.0)
options.f = "bar.txt"

"store_const" [required: const; relevant: dest]

The value const is stored in dest.

Example:

parser.add_option("-q", "--quiet",
                  action="store_const", const=0, dest="verbose")
parser.add_option("-v", "--verbose",
                  action="store_const", const=1, dest="verbose")
parser.add_option("--noisy",
                  action="store_const", const=2, dest="verbose")

If --noisy is seen, optparse will set

options.verbose = 2

"store_true" [relevant: dest]

A special case of "store_const" that stores True to dest.

"store_false" [relevant: dest]

Like "store_true", but stores False.

Example:

parser.add_option("--clobber", action="store_true", dest="clobber")
parser.add_option("--no-clobber", action="store_false", dest="clobber")

"append" [relevant: type, dest, nargs, choices]

The option must be followed by an argument, which is appended to the list in dest. If no default value for dest is supplied, an empty list is automatically created when optparse first encounters this option on the command-line. If nargs > 1, multiple arguments are consumed, and a tuple of length nargs is appended to dest.

The defaults for type and dest are the same as for the "store" action.

Example:

parser.add_option("-t", "--tracks", action="append", type="int")

If -t3 is seen on the command-line, optparse does the equivalent of:

options.tracks = []
options.tracks.append(int("3"))

If, a little later on, --tracks=4 is seen, it does:

options.tracks.append(int("4"))

The append action calls the append method on the current value of the option. This means that any default value specified must have an append method. It also means that if the default value is non-empty, the default elements will be present in the parsed value for the option, with any values from the command line appended after those default values:

>>> parser.add_option("--files", action="append", default=['~/.mypkg/defaults'])
>>> opts, args = parser.parse_args(['--files', 'overrides.mypkg'])
>>> opts.files
['~/.mypkg/defaults', 'overrides.mypkg']

"append_const" [required: const; relevant: dest]

Like "store_const", but the value const is appended to dest; as with "append", dest defaults to None, and an empty list is automatically created the first time the option is encountered.

"count" [relevant: dest]

Increment the integer stored at dest. If no default value is supplied, dest is set to zero before being incremented the first time.

Example:

parser.add_option("-v", action="count", dest="verbosity")

The first time -v is seen on the command line, optparse does the equivalent of:

options.verbosity = 0
options.verbosity += 1

Every subsequent occurrence of -v results in

options.verbosity += 1

"callback" [required: callback; relevant: type, nargs, callback_args, callback_kwargs]

Call the function specified by callback, which is called as

func(option, opt_str, value, parser, *args, **kwargs)

See section Option Callbacks for more detail.

"help"

Prints a complete help message for all the options in the current option parser. The help message is constructed from the usage string passed to OptionParser’s constructor and the help string passed to every option.

If no help string is supplied for an option, it will still be listed in the help message. To omit an option entirely, use the special value optparse.SUPPRESS_HELP.

optparse automatically adds a help option to all OptionParsers, so you do not normally need to create one.

Example:

from optparse import OptionParser, SUPPRESS_HELP

# usually, a help option is added automatically, but that can
# be suppressed using the add_help_option argument
parser = OptionParser(add_help_option=False)

parser.add_option("-h", "--help", action="help")
parser.add_option("-v", action="store_true", dest="verbose",
                  help="Be moderately verbose")
parser.add_option("--file", dest="filename",
                  help="Input file to read data from")
parser.add_option("--secret", help=SUPPRESS_HELP)

If optparse sees either -h or --help on the command line, it will print something like the following help message to stdout (assuming sys.argv[0] is "foo.py"):

Usage: foo.py [options]

Options:
  -h, --help        Show this help message and exit
  -v                Be moderately verbose
  --file=FILENAME   Input file to read data from

After printing the help message, optparse terminates your process with sys.exit(0).

"version"

Prints the version number supplied to the OptionParser to stdout and exits. The version number is actually formatted and printed by the print_version() method of OptionParser. Generally only relevant if the version argument is supplied to the OptionParser constructor. As with help options, you will rarely create version options, since optparse automatically adds them when needed.

Standard option types

optparse has five built-in option types: "string", "int", "choice", "float" and "complex". If you need to add new option types, see section Extending optparse.

Arguments to string options are not checked or converted in any way: the text on the command line is stored in the destination (or passed to the callback) as-is.

Integer arguments (type "int") are parsed as follows:

if the number starts with 0x, it is parsed as a hexadecimal number

if the number starts with 0, it is parsed as an octal number

if the number starts with 0b, it is parsed as a binary number

otherwise, the number is parsed as a decimal number

The conversion is done by calling int() with the appropriate base (2, 8, 10, or 16). If this fails, so will optparse, although with a more useful error message.

"float" and "complex" option arguments are converted directly with float() and complex(), with similar error-handling.

"choice" options are a subtype of "string" options. The choices option attribute (a sequence of strings) defines the set of allowed option arguments. optparse.check_choice() compares user-supplied option arguments against this master list and raises OptionValueError if an invalid string is given.

Parsing arguments

The whole point of creating and populating an OptionParser is to call its parse_args() method:

(options, args) = parser.parse_args(args=None, values=None)

where the input parameters are

args

the list of arguments to process (default: sys.argv[1:])

values

an optparse.Values object to store option arguments in (default: a new instance of Values) – if you give an existing object, the option defaults will not be initialized on it

and the return values are

options

the same object that was passed in as values, or the optparse.Values instance created by optparse

args

the leftover positional arguments after all options have been processed

The most common usage is to supply neither keyword argument. If you supply values, it will be modified with repeated setattr() calls (roughly one for every option argument stored to an option destination) and returned by parse_args().

If parse_args() encounters any errors in the argument list, it calls the OptionParser’s error() method with an appropriate end-user error message. This ultimately terminates your process with an exit status of 2 (the traditional Unix exit status for command-line errors).

Querying and manipulating your option parser

The default behavior of the option parser can be customized slightly, and you can also poke around your option parser and see what’s there. OptionParser provides several methods to help you out:

OptionParser.disable_interspersed_args()

Set parsing to stop on the first non-option. For example, if -a and -b are both simple options that take no arguments, optparse normally accepts this syntax:

prog -a arg1 -b arg2

and treats it as equivalent to

prog -a -b arg1 arg2

To disable this feature, call disable_interspersed_args(). This restores traditional Unix syntax, where option parsing stops with the first non-option argument.

Use this if you have a command processor which runs another command which has options of its own and you want to make sure these options don’t get confused. For example, each command might have a different set of options.

OptionParser.enable_interspersed_args()

Set parsing to not stop on the first non-option, allowing interspersing switches with command arguments. This is the default behavior.

OptionParser.get_option(opt_str)

Returns the Option instance with the option string opt_str, or None if no options have that option string.

OptionParser.has_option(opt_str)

Return True if the OptionParser has an option with option string opt_str (e.g., -q or --verbose).

OptionParser.remove_option(opt_str)

If the OptionParser has an option corresponding to opt_str, that option is removed. If that option provided any other option strings, all of those option strings become invalid. If opt_str does not occur in any option belonging to this OptionParser, raises ValueError.

Conflicts between options

If you’re not careful, it’s easy to define options with conflicting option strings:

parser.add_option("-n", "--dry-run", ...)
...
parser.add_option("-n", "--noisy", ...)

(This is particularly true if you’ve defined your own OptionParser subclass with some standard options.)

Every time you add an option, optparse checks for conflicts with existing options. If it finds any, it invokes the current conflict-handling mechanism. You can set the conflict-handling mechanism either in the constructor:

parser = OptionParser(..., conflict_handler=handler)

or with a separate call:

parser.set_conflict_handler(handler)

The available conflict handlers are:

"error" (default)

assume option conflicts are a programming error and raise OptionConflictError

"resolve"

resolve option conflicts intelligently (see below)

As an example, let’s define an OptionParser that resolves conflicts intelligently and add conflicting options to it:

parser = OptionParser(conflict_handler="resolve")
parser.add_option("-n", "--dry-run", ..., help="do no harm")
parser.add_option("-n", "--noisy", ..., help="be noisy")

At this point, optparse detects that a previously-added option is already using the -n option string. Since conflict_handler is "resolve", it resolves the situation by removing -n from the earlier option’s list of option strings. Now --dry-run is the only way for the user to activate that option. If the user asks for help, the help message will reflect that:

Options:
  --dry-run     do no harm
  ...
  -n, --noisy   be noisy

It’s possible to whittle away the option strings for a previously-added option until there are none left, and the user has no way of invoking that option from the command-line. In that case, optparse removes that option completely, so it doesn’t show up in help text or anywhere else. Carrying on with our existing OptionParser:

parser.add_option("--dry-run", ..., help="new dry-run option")

At this point, the original -n/--dry-run option is no longer accessible, so optparse removes it, leaving this help text:

Options:
  ...
  -n, --noisy   be noisy
  --dry-run     new dry-run option

Cleanup

OptionParser instances have several cyclic references. This should not be a problem for Python’s garbage collector, but you may wish to break the cyclic references explicitly by calling destroy() on your OptionParser once you are done with it. This is particularly useful in long-running applications where large object graphs are reachable from your OptionParser.

Other methods

OptionParser supports several other public methods:

OptionParser.set_usage(usage)

Set the usage string according to the rules described above for the usage constructor keyword argument. Passing None sets the default usage string; use optparse.SUPPRESS_USAGE to suppress a usage message.

OptionParser.print_usage(file=None)

Print the usage message for the current program (self.usage) to file (default stdout). Any occurrence of the string %prog in self.usage is replaced with the name of the current program. Does nothing if self.usage is empty or not defined.

OptionParser.get_usage()

Same as print_usage() but returns the usage string instead of printing it.

OptionParser.set_defaults(dest=value, ...)

Set default values for several option destinations at once. Using set_defaults() is the preferred way to set default values for options, since multiple options can share the same destination. For example, if several “mode” options all set the same destination, any one of them can set the default, and the last one wins:

parser.add_option("--advanced", action="store_const",
                  dest="mode", const="advanced",
                  default="novice")    # overridden below
parser.add_option("--novice", action="store_const",
                  dest="mode", const="novice",
                  default="advanced")  # overrides above setting

To avoid this confusion, use set_defaults():

parser.set_defaults(mode="advanced")
parser.add_option("--advanced", action="store_const",
                  dest="mode", const="advanced")
parser.add_option("--novice", action="store_const",
                  dest="mode", const="novice")

Option Callbacks

When optparse’s built-in actions and types aren’t quite enough for your needs, you have two choices: extend optparse or define a callback option. Extending optparse is more general, but overkill for a lot of simple cases. Quite often a simple callback is all you need.

There are two steps to defining a callback option:

define the option itself using the "callback" action

write the callback; this is a function (or method) that takes at least four arguments, as described below

Defining a callback option

As always, the easiest way to define a callback option is by using the OptionParser.add_option() method. Apart from action, the only option attribute you must specify is callback, the function to call:

parser.add_option("-c", action="callback", callback=my_callback)

callback is a function (or other callable object), so you must have already defined my_callback() when you create this callback option. In this simple case, optparse doesn’t even know if -c takes any arguments, which usually means that the option takes no arguments—the mere presence of -c on the command-line is all it needs to know. In some circumstances, though, you might want your callback to consume an arbitrary number of command-line arguments. This is where writing callbacks gets tricky; it’s covered later in this section.

optparse always passes four particular arguments to your callback, and it will only pass additional arguments if you specify them via callback_args and callback_kwargs. Thus, the minimal callback function signature is:

def my_callback(option, opt, value, parser):

The four arguments to a callback are described below.

There are several other option attributes that you can supply when you define a callback option:

type

has its usual meaning: as with the "store" or "append" actions, it instructs optparse to consume one argument and convert it to type. Rather than storing the converted value(s) anywhere, though, optparse passes it to your callback function.

nargs

also has its usual meaning: if it is supplied and > 1, optparse will consume nargs arguments, each of which must be convertible to type. It then passes a tuple of converted values to your callback.

callback_args

a tuple of extra positional arguments to pass to the callback

callback_kwargs

a dictionary of extra keyword arguments to pass to the callback

How callbacks are called

All callbacks are called as follows:

func(option, opt_str, value, parser, *args, **kwargs)

where

option

is the Option instance that’s calling the callback

opt_str

is the option string seen on the command-line that’s triggering the callback. (If an abbreviated long option was used, opt_str will be the full, canonical option string—e.g. if the user puts --foo on the command-line as an abbreviation for --foobar, then opt_str will be "--foobar".)

value

is the argument to this option seen on the command-line. optparse will only expect an argument if type is set; the type of value will be the type implied by the option’s type. If type for this option is None (no argument expected), then value will be None. If nargs > 1, value will be a tuple of values of the appropriate type.

parser

is the OptionParser instance driving the whole thing, mainly useful because you can access some other interesting data through its instance attributes:

parser.largs

the current list of leftover arguments, ie. arguments that have been consumed but are neither options nor option arguments. Feel free to modify parser.largs, e.g. by adding more arguments to it. (This list will become args, the second return value of parse_args().)

parser.rargs

the current list of remaining arguments, ie. with opt_str and value (if applicable) removed, and only the arguments following them still there. Feel free to modify parser.rargs, e.g. by consuming more arguments.

parser.values

the object where option values are by default stored (an instance of optparse.OptionValues). This lets callbacks use the same mechanism as the rest of optparse for storing option values; you don’t need to mess around with globals or closures. You can also access or modify the value(s) of any options already encountered on the command-line.

args

is a tuple of arbitrary positional arguments supplied via the callback_args option attribute.

kwargs

is a dictionary of arbitrary keyword arguments supplied via callback_kwargs.

Raising errors in a callback

The callback function should raise OptionValueError if there are any problems with the option or its argument(s). optparse catches this and terminates the program, printing the error message you supply to stderr. Your message should be clear, concise, accurate, and mention the option at fault. Otherwise, the user will have a hard time figuring out what they did wrong.

Callback example 1: trivial callback

Here’s an example of a callback option that takes no arguments, and simply records that the option was seen:

def record_foo_seen(option, opt_str, value, parser):
    parser.values.saw_foo = True

parser.add_option("--foo", action="callback", callback=record_foo_seen)

Of course, you could do that with the "store_true" action.

Callback example 2: check option order

Here’s a slightly more interesting example: record the fact that -a is seen, but blow up if it comes after -b in the command-line.

def check_order(option, opt_str, value, parser):
    if parser.values.b:
        raise OptionValueError("can't use -a after -b")
    parser.values.a = 1
...
parser.add_option("-a", action="callback", callback=check_order)
parser.add_option("-b", action="store_true", dest="b")

Callback example 3: check option order (generalized)

If you want to re-use this callback for several similar options (set a flag, but blow up if -b has already been seen), it needs a bit of work: the error message and the flag that it sets must be generalized.

def check_order(option, opt_str, value, parser):
    if parser.values.b:
        raise OptionValueError("can't use %s after -b" % opt_str)
    setattr(parser.values, option.dest, 1)
...
parser.add_option("-a", action="callback", callback=check_order, dest='a')
parser.add_option("-b", action="store_true", dest="b")
parser.add_option("-c", action="callback", callback=check_order, dest='c')

Callback example 4: check arbitrary condition

Of course, you could put any condition in there—you’re not limited to checking the values of already-defined options. For example, if you have options that should not be called when the moon is full, all you have to do is this:

def check_moon(option, opt_str, value, parser):
    if is_moon_full():
        raise OptionValueError("%s option invalid when moon is full"
                               % opt_str)
    setattr(parser.values, option.dest, 1)
...
parser.add_option("--foo",
                  action="callback", callback=check_moon, dest="foo")

(The definition of is_moon_full() is left as an exercise for the reader.)

Callback example 5: fixed arguments

Things get slightly more interesting when you define callback options that take a fixed number of arguments. Specifying that a callback option takes arguments is similar to defining a "store" or "append" option: if you define type, then the option takes one argument that must be convertible to that type; if you further define nargs, then the option takes nargs arguments.

Here’s an example that just emulates the standard "store" action:

def store_value(option, opt_str, value, parser):
    setattr(parser.values, option.dest, value)
...
parser.add_option("--foo",
                  action="callback", callback=store_value,
                  type="int", nargs=3, dest="foo")

Note that optparse takes care of consuming 3 arguments and converting them to integers for you; all you have to do is store them. (Or whatever; obviously you don’t need a callback for this example.)

Callback example 6: variable arguments

Things get hairy when you want an option to take a variable number of arguments. For this case, you must write a callback, as optparse doesn’t provide any built-in capabilities for it. And you have to deal with certain intricacies of conventional Unix command-line parsing that optparse normally handles for you. In particular, callbacks should implement the conventional rules for bare -- and - arguments:

either -- or - can be option arguments

bare -- (if not the argument to some option): halt command-line processing and discard the --

bare - (if not the argument to some option): halt command-line processing but keep the - (append it to parser.largs)

If you want an option that takes a variable number of arguments, there are several subtle, tricky issues to worry about. The exact implementation you choose will be based on which trade-offs you’re willing to make for your application (which is why optparse doesn’t support this sort of thing directly).

Nevertheless, here’s a stab at a callback for an option with variable arguments:

def vararg_callback(option, opt_str, value, parser):
    assert value is None
    value = []

    def floatable(str):
        try:
            float(str)
            return True
        except ValueError:
            return False

    for arg in parser.rargs:
        # stop on --foo like options
        if arg[:2] == "--" and len(arg) > 2:
            break
        # stop on -a, but not on -3 or -3.0
        if arg[:1] == "-" and len(arg) > 1 and not floatable(arg):
            break
        value.append(arg)

    del parser.rargs[:len(value)]
    setattr(parser.values, option.dest, value)

...
parser.add_option("-c", "--callback", dest="vararg_attr",
                  action="callback", callback=vararg_callback)

Extending optparse

Since the two major controlling factors in how optparse interprets command-line options are the action and type of each option, the most likely direction of extension is to add new actions and new types.

Adding new types

To add new types, you need to define your own subclass of optparse’s Option class. This class has a couple of attributes that define optparse’s types: TYPES and TYPE_CHECKER.

Option.TYPES

A tuple of type names; in your subclass, simply define a new tuple TYPES that builds on the standard one.

Option.TYPE_CHECKER

A dictionary mapping type names to type-checking functions. A type-checking function has the following signature:

def check_mytype(option, opt, value)

where option is an Option instance, opt is an option string (e.g., -f), and value is the string from the command line that must be checked and converted to your desired type. check_mytype() should return an object of the hypothetical type mytype. The value returned by a type-checking function will wind up in the OptionValues instance returned by OptionParser.parse_args(), or be passed to a callback as the value parameter.

Your type-checking function should raise OptionValueError if it encounters any problems. OptionValueError takes a single string argument, which is passed as-is to OptionParser’s error() method, which in turn prepends the program name and the string "error:" and prints everything to stderr before terminating the process.

Here’s a silly example that demonstrates adding a "complex" option type to parse Python-style complex numbers on the command line. (This is even sillier than it used to be, because optparse 1.3 added built-in support for complex numbers, but never mind.)

First, the necessary imports:

from copy import copy
from optparse import Option, OptionValueError

You need to define your type-checker first, since it’s referred to later (in the TYPE_CHECKER class attribute of your Option subclass):

def check_complex(option, opt, value):
    try:
        return complex(value)
    except ValueError:
        raise OptionValueError(
            "option %s: invalid complex value: %r" % (opt, value))

Finally, the Option subclass:

class MyOption (Option):
    TYPES = Option.TYPES + ("complex",)
    TYPE_CHECKER = copy(Option.TYPE_CHECKER)
    TYPE_CHECKER["complex"] = check_complex

(If we didn’t make a copy() of Option.TYPE_CHECKER, we would end up modifying the TYPE_CHECKER attribute of optparse’s Option class. This being Python, nothing stops you from doing that except good manners and common sense.)

That’s it! Now you can write a script that uses the new option type just like any other optparse-based script, except you have to instruct your OptionParser to use MyOption instead of Option:

parser = OptionParser(option_class=MyOption)
parser.add_option("-c", type="complex")

Alternately, you can build your own option list and pass it to OptionParser; if you don’t use add_option() in the above way, you don’t need to tell OptionParser which option class to use:

option_list = [MyOption("-c", action="store", type="complex", dest="c")]
parser = OptionParser(option_list=option_list)

Adding new actions

Adding new actions is a bit trickier, because you have to understand that optparse has a couple of classifications for actions:

“store” actions

actions that result in optparse storing a value to an attribute of the current OptionValues instance; these options require a dest attribute to be supplied to the Option constructor.

“typed” actions

actions that take a value from the command line and expect it to be of a certain type; or rather, a string that can be converted to a certain type. These options require a type attribute to the Option constructor.

These are overlapping sets: some default “store” actions are "store", "store_const", "append", and "count", while the default “typed” actions are "store", "append", and "callback".

When you add an action, you need to categorize it by listing it in at least one of the following class attributes of Option (all are lists of strings):

Option.ACTIONS

All actions must be listed in ACTIONS.

Option.STORE_ACTIONS

“store” actions are additionally listed here.

Option.TYPED_ACTIONS

“typed” actions are additionally listed here.

Option.ALWAYS_TYPED_ACTIONS

Actions that always take a type (i.e. whose options always take a value) are additionally listed here. The only effect of this is that optparse assigns the default type, "string", to options with no explicit type whose action is listed in ALWAYS_TYPED_ACTIONS.

In order to actually implement your new action, you must override Option’s take_action() method and add a case that recognizes your action.

For example, let’s add an "extend" action. This is similar to the standard "append" action, but instead of taking a single value from the command-line and appending it to an existing list, "extend" will take multiple values in a single comma-delimited string, and extend an existing list with them. That is, if --names is an "extend" option of type "string", the command line

--names=foo,bar --names blah --names ding,dong

would result in a list

["foo", "bar", "blah", "ding", "dong"]

Again we define a subclass of Option:

class MyOption(Option):

    ACTIONS = Option.ACTIONS + ("extend",)
    STORE_ACTIONS = Option.STORE_ACTIONS + ("extend",)
    TYPED_ACTIONS = Option.TYPED_ACTIONS + ("extend",)
    ALWAYS_TYPED_ACTIONS = Option.ALWAYS_TYPED_ACTIONS + ("extend",)

    def take_action(self, action, dest, opt, value, values, parser):
        if action == "extend":
            lvalue = value.split(",")
            values.ensure_value(dest, []).extend(lvalue)
        else:
            Option.take_action(
                self, action, dest, opt, value, values, parser)

Features of note:

"extend" both expects a value on the command-line and stores that value somewhere, so it goes in both STORE_ACTIONS and TYPED_ACTIONS.

to ensure that optparse assigns the default type of "string" to "extend" actions, we put the "extend" action in ALWAYS_TYPED_ACTIONS as well.

MyOption.take_action() implements just this one new action, and passes control back to Option.take_action() for the standard optparse actions.

values is an instance of the optparse_parser.Values class, which provides the very useful ensure_value() method. ensure_value() is essentially getattr() with a safety valve; it is called as

values.ensure_value(attr, value)

If the attr attribute of values doesn’t exist or is None, then ensure_value() first sets it to value, and then returns ‘value. This is very handy for actions like "extend", "append", and "count", all of which accumulate data in a variable and expect that variable to be of a certain type (a list for the first two, an integer for the latter). Using ensure_value() means that scripts using your action don’t have to worry about setting a default value for the option destinations in question; they can just leave the default as None and ensure_value() will take care of getting it right when it’s needed.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

대체된 모듈 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

대체된 모듈 »

|

imp — Access the import internals

Source code: Lib/imp.py [https://github.com/python/cpython/tree/3.7/Lib/imp.py]

버전 3.4부터 폐지: The imp module is deprecated in favor of importlib.

This module provides an interface to the mechanisms used to implement the import statement. It defines the following constants and functions:

imp.get_magic()

Return the magic string value used to recognize byte-compiled code files (.pyc files). (This value may be different for each Python version.)

버전 3.4부터 폐지: Use importlib.util.MAGIC_NUMBER instead.

imp.get_suffixes()

Return a list of 3-element tuples, each describing a particular type of module. Each triple has the form (suffix, mode, type), where suffix is a string to be appended to the module name to form the filename to search for, mode is the mode string to pass to the built-in open() function to open the file (this can be 'r' for text files or 'rb' for binary files), and type is the file type, which has one of the values PY_SOURCE, PY_COMPILED, or C_EXTENSION, described below.

버전 3.3부터 폐지: Use the constants defined on importlib.machinery instead.

imp.find_module(name[, path])

Try to find the module name. If path is omitted or None, the list of directory names given by sys.path is searched, but first a few special places are searched: the function tries to find a built-in module with the given name (C_BUILTIN), then a frozen module (PY_FROZEN), and on some systems some other places are looked in as well (on Windows, it looks in the registry which may point to a specific file).

Otherwise, path must be a list of directory names; each directory is searched for files with any of the suffixes returned by get_suffixes() above. Invalid names in the list are silently ignored (but all list items must be strings).

If search is successful, the return value is a 3-element tuple (file, pathname, description):

file is an open file object positioned at the beginning, pathname is the pathname of the file found, and description is a 3-element tuple as contained in the list returned by get_suffixes() describing the kind of module found.

If the module is built-in or frozen then file and pathname are both None and the description tuple contains empty strings for its suffix and mode; the module type is indicated as given in parentheses above. If the search is unsuccessful, ImportError is raised. Other exceptions indicate problems with the arguments or environment.

If the module is a package, file is None, pathname is the package path and the last item in the description tuple is PKG_DIRECTORY.

This function does not handle hierarchical module names (names containing dots). In order to find P.M, that is, submodule M of package P, use find_module() and load_module() to find and load package P, and then use find_module() with the path argument set to P.__path__. When P itself has a dotted name, apply this recipe recursively.

버전 3.3부터 폐지: Use importlib.util.find_spec() instead unless Python 3.3 compatibility is required, in which case use importlib.find_loader(). For example usage of the former case, see the Examples section of the importlib documentation.

imp.load_module(name, file, pathname, description)

Load a module that was previously found by find_module() (or by an otherwise conducted search yielding compatible results). This function does more than importing the module: if the module was already imported, it will reload the module! The name argument indicates the full module name (including the package name, if this is a submodule of a package). The file argument is an open file, and pathname is the corresponding file name; these can be None and '', respectively, when the module is a package or not being loaded from a file. The description argument is a tuple, as would be returned by get_suffixes(), describing what kind of module must be loaded.

If the load is successful, the return value is the module object; otherwise, an exception (usually ImportError) is raised.

Important: the caller is responsible for closing the file argument, if it was not None, even when an exception is raised. This is best done using a try … finally statement.

버전 3.3부터 폐지: If previously used in conjunction with imp.find_module() then consider using importlib.import_module(), otherwise use the loader returned by the replacement you chose for imp.find_module(). If you called imp.load_module() and related functions directly with file path arguments then use a combination of importlib.util.spec_from_file_location() and importlib.util.module_from_spec(). See the Examples section of the importlib documentation for details of the various approaches.

imp.new_module(name)

Return a new empty module object called name. This object is not inserted in sys.modules.

버전 3.4부터 폐지: Use importlib.util.module_from_spec() instead.

imp.reload(module)

Reload a previously imported module. The argument must be a module object, so it must have been successfully imported before. This is useful if you have edited the module source file using an external editor and want to try out the new version without leaving the Python interpreter. The return value is the module object (the same as the module argument).

When reload(module) is executed:

Python modules’ code is recompiled and the module-level code reexecuted, defining a new set of objects which are bound to names in the module’s dictionary. The init function of extension modules is not called a second time.

As with all other objects in Python the old objects are only reclaimed after their reference counts drop to zero.

The names in the module namespace are updated to point to any new or changed objects.

Other references to the old objects (such as names external to the module) are not rebound to refer to the new objects and must be updated in each namespace where they occur if that is desired.

There are a number of other caveats:

When a module is reloaded, its dictionary (containing the module’s global variables) is retained. Redefinitions of names will override the old definitions, so this is generally not a problem. If the new version of a module does not define a name that was defined by the old version, the old definition remains. This feature can be used to the module’s advantage if it maintains a global table or cache of objects — with a try statement it can test for the table’s presence and skip its initialization if desired:

try:
    cache
except NameError:
    cache = {}

It is legal though generally not very useful to reload built-in or dynamically loaded modules, except for sys, __main__ and builtins. In many cases, however, extension modules are not designed to be initialized more than once, and may fail in arbitrary ways when reloaded.

If a module imports objects from another module using from … import …, calling reload() for the other module does not redefine the objects imported from it — one way around this is to re-execute the from statement, another is to use import and qualified names (module.*name*) instead.

If a module instantiates instances of a class, reloading the module that defines the class does not affect the method definitions of the instances — they continue to use the old class definition. The same is true for derived classes.

버전 3.3에서 변경: Relies on both __name__ and __loader__ being defined on the module being reloaded instead of just __name__.

버전 3.4부터 폐지: Use importlib.reload() instead.

The following functions are conveniences for handling PEP 3147 [https://www.python.org/dev/peps/pep-3147] byte-compiled file paths.

버전 3.2에 추가.

imp.cache_from_source(path, debug_override=None)

Return the PEP 3147 [https://www.python.org/dev/peps/pep-3147] path to the byte-compiled file associated with the source path. For example, if path is /foo/bar/baz.py the return value would be /foo/bar/__pycache__/baz.cpython-32.pyc for Python 3.2. The cpython-32 string comes from the current magic tag (see get_tag(); if sys.implementation.cache_tag is not defined then NotImplementedError will be raised). By passing in True or False for debug_override you can override the system’s value for __debug__, leading to optimized bytecode.

path need not exist.

버전 3.3에서 변경: If sys.implementation.cache_tag is None, then NotImplementedError is raised.

버전 3.4부터 폐지: Use importlib.util.cache_from_source() instead.

버전 3.5에서 변경: The debug_override parameter no longer creates a .pyo file.

imp.source_from_cache(path)

Given the path to a PEP 3147 [https://www.python.org/dev/peps/pep-3147] file name, return the associated source code file path. For example, if path is /foo/bar/__pycache__/baz.cpython-32.pyc the returned path would be /foo/bar/baz.py. path need not exist, however if it does not conform to PEP 3147 [https://www.python.org/dev/peps/pep-3147] format, a ValueError is raised. If sys.implementation.cache_tag is not defined, NotImplementedError is raised.

버전 3.3에서 변경: Raise NotImplementedError when sys.implementation.cache_tag is not defined.

버전 3.4부터 폐지: Use importlib.util.source_from_cache() instead.

imp.get_tag()

Return the PEP 3147 [https://www.python.org/dev/peps/pep-3147] magic tag string matching this version of Python’s magic number, as returned by get_magic().

버전 3.4부터 폐지: Use sys.implementation.cache_tag directly starting in Python 3.3.

The following functions help interact with the import system’s internal locking mechanism. Locking semantics of imports are an implementation detail which may vary from release to release. However, Python ensures that circular imports work without any deadlocks.

imp.lock_held()

Return True if the global import lock is currently held, else False. On platforms without threads, always return False.

On platforms with threads, a thread executing an import first holds a global import lock, then sets up a per-module lock for the rest of the import. This blocks other threads from importing the same module until the original import completes, preventing other threads from seeing incomplete module objects constructed by the original thread. An exception is made for circular imports, which by construction have to expose an incomplete module object at some point.

버전 3.3에서 변경: The locking scheme has changed to per-module locks for the most part. A global import lock is kept for some critical tasks, such as initializing the per-module locks.

버전 3.4부터 폐지.

imp.acquire_lock()

Acquire the interpreter’s global import lock for the current thread. This lock should be used by import hooks to ensure thread-safety when importing modules.

Once a thread has acquired the import lock, the same thread may acquire it again without blocking; the thread must release it once for each time it has acquired it.

On platforms without threads, this function does nothing.

버전 3.3에서 변경: The locking scheme has changed to per-module locks for the most part. A global import lock is kept for some critical tasks, such as initializing the per-module locks.

버전 3.4부터 폐지.

imp.release_lock()

Release the interpreter’s global import lock. On platforms without threads, this function does nothing.

버전 3.3에서 변경: The locking scheme has changed to per-module locks for the most part. A global import lock is kept for some critical tasks, such as initializing the per-module locks.

버전 3.4부터 폐지.

The following constants with integer values, defined in this module, are used to indicate the search result of find_module().

imp.PY_SOURCE

The module was found as a source file.

버전 3.3부터 폐지.

imp.PY_COMPILED

The module was found as a compiled code object file.

버전 3.3부터 폐지.

imp.C_EXTENSION

The module was found as dynamically loadable shared library.

버전 3.3부터 폐지.

imp.PKG_DIRECTORY

The module was found as a package directory.

버전 3.3부터 폐지.

imp.C_BUILTIN

The module was found as a built-in module.

버전 3.3부터 폐지.

imp.PY_FROZEN

The module was found as a frozen module.

버전 3.3부터 폐지.

class imp.NullImporter(path_string)

The NullImporter type is a PEP 302 [https://www.python.org/dev/peps/pep-0302] import hook that handles non-directory path strings by failing to find any modules. Calling this type with an existing directory or empty string raises ImportError. Otherwise, a NullImporter instance is returned.

Instances have only one method:

find_module(fullname[, path])

This method always returns None, indicating that the requested module could not be found.

버전 3.3에서 변경: None is inserted into sys.path_importer_cache instead of an instance of NullImporter.

버전 3.4부터 폐지: Insert None into sys.path_importer_cache instead.

Examples

The following function emulates what was the standard import statement up to Python 1.4 (no hierarchical module names). (This implementation wouldn’t work in that version, since find_module() has been extended and load_module() has been added in 1.4.)

import imp
import sys

def __import__(name, globals=None, locals=None, fromlist=None):
    # Fast path: see if the module has already been imported.
    try:
        return sys.modules[name]
    except KeyError:
        pass

    # If any of the following calls raises an exception,
    # there's a problem we can't handle -- let the caller handle it.

    fp, pathname, description = imp.find_module(name)

    try:
        return imp.load_module(name, fp, pathname, description)
    finally:
        # Since we may exit via an exception, close fp explicitly.
        if fp:
            fp.close()

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

대체된 모듈 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

|

문서로 만들어지지 않은 모듈

여기, 현재 문서로 만들어지지 않았지만, 문서로 만들어야 하는 모듈의 목록이 있습니다. 이것들의 문서를 기고해 주십시오! (이메일을 통해 docs@python.org 로 보내주십시오.)

이 장의 아이디어와 원래 내용은 Fredrik Lundh의 글에서 가져온 것입니다; 이 장의 구체적인 내용은 상당히 개정되었습니다.

플랫폼 특정 모듈

이 모듈은 os.path 모듈을 구현하는 데 사용되며, 이 언급 이상의 것들이 설명되지 않았습니다. 문서로 만들 필요가 거의 없습니다.

ntpath

— Win32 와 Win64 플랫폼에서 os.path를 구현합니다.

posixpath

— POSIX에서 os.path를 구현합니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 표준 라이브러리 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

|

파이썬 인터프리터 확장 및 내장

이 문서는 새로운 모듈로 파이썬 인터프리터를 확장하기 위해 C 나 C++로 모듈을 작성하는 방법을 설명합니다. 이러한 모듈은 새로운 함수뿐만 아니라 새로운 객체 형과 메서드를 정의할 수 있습니다. 또한, 확장 언어로 사용하기 위해, 파이썬 인터프리터를 다른 응용 프로그램에 내장시키는 방법에 관해서도 설명합니다. 마지막으로, 하부 운영 체제에서 이 기능을 지원하는 경우, 동적으로 (실행시간에) 인터프리터에 로드될 수 있도록 확장 모듈을 컴파일하고 링크하는 방법을 보여줍니다.

이 문서는 파이썬에 대한 기본 지식을 전제로 합니다. 언어에 대한 형식적이지 않은 소개는 파이썬 자습서 를 보십시오. 파이썬 언어 레퍼런스 는 보다 형식적인 언어 정의를 제공합니다. 파이썬 표준 라이브러리 는 존재하는 객체 형, 함수 및 모듈(내장된 것과 파이썬으로 작성된 것 모두)을 설명하는데, 이것들이 언어의 응용 범위를 넓힙니다.

전체 파이썬/C API에 대한 자세한 설명은 별도의 파이썬/C API 레퍼런스 설명서 를 참조하십시오.

권장 제삼자 도구

이 지침서는 이 버전의 CPython의 일부로 제공되는, 확장을 만들기 위한 기본 도구만을 다룹니다. Cython [http://cython.org/], cffi [https://cffi.readthedocs.io], SWIG [http://www.swig.org] 와 Numba [https://numba.pydata.org/] 와 같은 제삼자 도구는 파이썬을 위한 C와 C++ 확장을 만드는 더 간단하고 세련된 접근법을 제공합니다.

더 보기

파이썬 패키징 사용자 지침서: 바이너리 확장 [https://packaging.python.org/guides/packaging-binary-extensions/]

파이썬 패키징 사용자 지침서는 바이너리 확장의 생성을 단순화하는 몇 가지 사용 가능한 도구를 다루고 있을 뿐만 아니라, 확장 모듈을 만드는 것이 왜 바람직한지 여러 가지 이유에 대해서도 논의합니다.

제삼자 도구 없이 확장 만들기

지침서의 이 부문에서는 제삼자 도구의 도움 없이 C와 C++ 확장을 만드는 방법에 관해 설명합니다. 여러분 자신의 C 확장을 만드는 데 권장되는 방법이라기보다는, 주로 도구를 제작하는 사람들을 대상으로 합니다.

1. Extending Python with C or C++

1.1. A Simple Example

1.2. Intermezzo: Errors and Exceptions

1.3. Back to the Example

1.4. The Module’s Method Table and Initialization Function

1.5. Compilation and Linkage

1.6. Calling Python Functions from C

1.7. Extracting Parameters in Extension Functions

1.8. Keyword Parameters for Extension Functions

1.9. Building Arbitrary Values

1.10. Reference Counts

1.11. Writing Extensions in C++

1.12. Providing a C API for an Extension Module

2. Defining Extension Types: Tutorial

2.1. The Basics

2.2. Adding data and methods to the Basic example

2.3. Providing finer control over data attributes

2.4. Supporting cyclic garbage collection

2.5. Subclassing other types

3. Defining Extension Types: Assorted Topics

3.1. Finalization and De-allocation

3.2. Object Presentation

3.3. Attribute Management

3.4. Object Comparison

3.5. Abstract Protocol Support

3.6. Weak Reference Support

3.7. More Suggestions

4. C와 C++ 확장 빌드하기

4.1. distutils로 C와 C++ 확장 빌드하기

4.2. 확장 모듈 배포하기

5. 윈도우에서 C와 C++ 확장 빌드하기

5.1. 요리책 접근법

5.2. 유닉스와 윈도우의 차이점

5.3. DLL을 실제로 사용하기

더 큰 응용 프로그램에 CPython 런타임을 내장하기

때로는, 파이썬 인터프리터를 메인 응용 프로그램으로 사용하고 그 안에서 실행되는 확장을 만드는 대신, CPython 런타임을 더 큰 응용 프로그램에 내장하는 것이 바람직합니다. 이 절에서는 이를 성공적으로 수행하는 데 관련된 몇 가지 세부 사항에 관해 설명합니다.

1. 다른 응용 프로그램에 파이썬 내장하기

1.1. 매우 고수준의 내장

1.2. 매우 고수준 내장을 넘어서: 개요

1.3. 순수한 내장

1.4. 내장된 파이썬을 확장하기

1.5. C++로 파이썬 내장하기

1.6. 유닉스 계열 시스템에서 컴파일과 링크하기

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 인터프리터 확장 및 내장 »

|

1. Extending Python with C or C++

It is quite easy to add new built-in modules to Python, if you know how to program in C. Such extension modules can do two things that can’t be done directly in Python: they can implement new built-in object types, and they can call C library functions and system calls.

To support extensions, the Python API (Application Programmers Interface) defines a set of functions, macros and variables that provide access to most aspects of the Python run-time system. The Python API is incorporated in a C source file by including the header "Python.h".

The compilation of an extension module depends on its intended use as well as on your system setup; details are given in later chapters.

참고

The C extension interface is specific to CPython, and extension modules do not work on other Python implementations. In many cases, it is possible to avoid writing C extensions and preserve portability to other implementations. For example, if your use case is calling C library functions or system calls, you should consider using the ctypes module or the cffi [https://cffi.readthedocs.io/] library rather than writing custom C code. These modules let you write Python code to interface with C code and are more portable between implementations of Python than writing and compiling a C extension module.

1.1. A Simple Example

Let’s create an extension module called spam (the favorite food of Monty Python fans…) and let’s say we want to create a Python interface to the C library function system() 1. This function takes a null-terminated character string as argument and returns an integer. We want this function to be callable from Python as follows:

>>> import spam
>>> status = spam.system("ls -l")

Begin by creating a file spammodule.c. (Historically, if a module is called spam, the C file containing its implementation is called spammodule.c; if the module name is very long, like spammify, the module name can be just spammify.c.)

The first two lines of our file can be:

#define PY_SSIZE_T_CLEAN
#include <Python.h>

which pulls in the Python API (you can add a comment describing the purpose of the module and a copyright notice if you like).

참고

Since Python may define some pre-processor definitions which affect the standard headers on some systems, you must include Python.h before any standard headers are included.

It is recommended to always define PY_SSIZE_T_CLEAN before including Python.h. See Extracting Parameters in Extension Functions for a description of this macro.

All user-visible symbols defined by Python.h have a prefix of Py or PY, except those defined in standard header files. For convenience, and since they are used extensively by the Python interpreter, "Python.h" includes a few standard header files: <stdio.h>, <string.h>, <errno.h>, and <stdlib.h>. If the latter header file does not exist on your system, it declares the functions malloc(), free() and realloc() directly.

The next thing we add to our module file is the C function that will be called when the Python expression spam.system(string) is evaluated (we’ll see shortly how it ends up being called):

static PyObject *
spam_system(PyObject *self, PyObject *args)
{
    const char *command;
    int sts;

    if (!PyArg_ParseTuple(args, "s", &command))
        return NULL;
    sts = system(command);
    return PyLong_FromLong(sts);
}

There is a straightforward translation from the argument list in Python (for example, the single expression "ls -l") to the arguments passed to the C function. The C function always has two arguments, conventionally named self and args.

The self argument points to the module object for module-level functions; for a method it would point to the object instance.

The args argument will be a pointer to a Python tuple object containing the arguments. Each item of the tuple corresponds to an argument in the call’s argument list. The arguments are Python objects — in order to do anything with them in our C function we have to convert them to C values. The function PyArg_ParseTuple() in the Python API checks the argument types and converts them to C values. It uses a template string to determine the required types of the arguments as well as the types of the C variables into which to store the converted values. More about this later.

PyArg_ParseTuple() returns true (nonzero) if all arguments have the right type and its components have been stored in the variables whose addresses are passed. It returns false (zero) if an invalid argument list was passed. In the latter case it also raises an appropriate exception so the calling function can return NULL immediately (as we saw in the example).

1.2. Intermezzo: Errors and Exceptions

An important convention throughout the Python interpreter is the following: when a function fails, it should set an exception condition and return an error value (usually a NULL pointer). Exceptions are stored in a static global variable inside the interpreter; if this variable is NULL no exception has occurred. A second global variable stores the “associated value” of the exception (the second argument to raise). A third variable contains the stack traceback in case the error originated in Python code. These three variables are the C equivalents of the result in Python of sys.exc_info() (see the section on module sys in the Python Library Reference). It is important to know about them to understand how errors are passed around.

The Python API defines a number of functions to set various types of exceptions.

The most common one is PyErr_SetString(). Its arguments are an exception object and a C string. The exception object is usually a predefined object like PyExc_ZeroDivisionError. The C string indicates the cause of the error and is converted to a Python string object and stored as the “associated value” of the exception.

Another useful function is PyErr_SetFromErrno(), which only takes an exception argument and constructs the associated value by inspection of the global variable errno. The most general function is PyErr_SetObject(), which takes two object arguments, the exception and its associated value. You don’t need to Py_INCREF() the objects passed to any of these functions.

You can test non-destructively whether an exception has been set with PyErr_Occurred(). This returns the current exception object, or NULL if no exception has occurred. You normally don’t need to call PyErr_Occurred() to see whether an error occurred in a function call, since you should be able to tell from the return value.

When a function f that calls another function g detects that the latter fails, f should itself return an error value (usually NULL or -1). It should not call one of the PyErr_*() functions — one has already been called by g. f’s caller is then supposed to also return an error indication to its caller, again without calling PyErr_*(), and so on — the most detailed cause of the error was already reported by the function that first detected it. Once the error reaches the Python interpreter’s main loop, this aborts the currently executing Python code and tries to find an exception handler specified by the Python programmer.

(There are situations where a module can actually give a more detailed error message by calling another PyErr_*() function, and in such cases it is fine to do so. As a general rule, however, this is not necessary, and can cause information about the cause of the error to be lost: most operations can fail for a variety of reasons.)

To ignore an exception set by a function call that failed, the exception condition must be cleared explicitly by calling PyErr_Clear(). The only time C code should call PyErr_Clear() is if it doesn’t want to pass the error on to the interpreter but wants to handle it completely by itself (possibly by trying something else, or pretending nothing went wrong).

Every failing malloc() call must be turned into an exception — the direct caller of malloc() (or realloc()) must call PyErr_NoMemory() and return a failure indicator itself. All the object-creating functions (for example, PyLong_FromLong()) already do this, so this note is only relevant to those who call malloc() directly.

Also note that, with the important exception of PyArg_ParseTuple() and friends, functions that return an integer status usually return a positive value or zero for success and -1 for failure, like Unix system calls.

Finally, be careful to clean up garbage (by making Py_XDECREF() or Py_DECREF() calls for objects you have already created) when you return an error indicator!

The choice of which exception to raise is entirely yours. There are predeclared C objects corresponding to all built-in Python exceptions, such as PyExc_ZeroDivisionError, which you can use directly. Of course, you should choose exceptions wisely — don’t use PyExc_TypeError to mean that a file couldn’t be opened (that should probably be PyExc_IOError). If something’s wrong with the argument list, the PyArg_ParseTuple() function usually raises PyExc_TypeError. If you have an argument whose value must be in a particular range or must satisfy other conditions, PyExc_ValueError is appropriate.

You can also define a new exception that is unique to your module. For this, you usually declare a static object variable at the beginning of your file:

static PyObject *SpamError;

and initialize it in your module’s initialization function (PyInit_spam()) with an exception object:

PyMODINIT_FUNC
PyInit_spam(void)
{
    PyObject *m;

    m = PyModule_Create(&spammodule);
    if (m == NULL)
        return NULL;

    SpamError = PyErr_NewException("spam.error", NULL, NULL);
    Py_XINCREF(SpamError);
    if (PyModule_AddObject(m, "error", SpamError) < 0) {
        Py_XDECREF(SpamError);
        Py_CLEAR(SpamError);
        Py_DECREF(m);
        return NULL;
    }

    return m;
}

Note that the Python name for the exception object is spam.error. The PyErr_NewException() function may create a class with the base class being Exception (unless another class is passed in instead of NULL), described in 내장 예외.

Note also that the SpamError variable retains a reference to the newly created exception class; this is intentional! Since the exception could be removed from the module by external code, an owned reference to the class is needed to ensure that it will not be discarded, causing SpamError to become a dangling pointer. Should it become a dangling pointer, C code which raises the exception could cause a core dump or other unintended side effects.

We discuss the use of PyMODINIT_FUNC as a function return type later in this sample.

The spam.error exception can be raised in your extension module using a call to PyErr_SetString() as shown below:

static PyObject *
spam_system(PyObject *self, PyObject *args)
{
    const char *command;
    int sts;

    if (!PyArg_ParseTuple(args, "s", &command))
        return NULL;
    sts = system(command);
    if (sts < 0) {
        PyErr_SetString(SpamError, "System command failed");
        return NULL;
    }
    return PyLong_FromLong(sts);
}

1.3. Back to the Example

Going back to our example function, you should now be able to understand this statement:

if (!PyArg_ParseTuple(args, "s", &command))
    return NULL;

It returns NULL (the error indicator for functions returning object pointers) if an error is detected in the argument list, relying on the exception set by PyArg_ParseTuple(). Otherwise the string value of the argument has been copied to the local variable command. This is a pointer assignment and you are not supposed to modify the string to which it points (so in Standard C, the variable command should properly be declared as const char *command).

The next statement is a call to the Unix function system(), passing it the string we just got from PyArg_ParseTuple():

sts = system(command);

Our spam.system() function must return the value of sts as a Python object. This is done using the function PyLong_FromLong().

return PyLong_FromLong(sts);

In this case, it will return an integer object. (Yes, even integers are objects on the heap in Python!)

If you have a C function that returns no useful argument (a function returning void), the corresponding Python function must return None. You need this idiom to do so (which is implemented by the Py_RETURN_NONE macro):

Py_INCREF(Py_None);
return Py_None;

Py_None is the C name for the special Python object None. It is a genuine Python object rather than a NULL pointer, which means “error” in most contexts, as we have seen.

1.4. The Module’s Method Table and Initialization Function

I promised to show how spam_system() is called from Python programs. First, we need to list its name and address in a “method table”:

static PyMethodDef SpamMethods[] = {
    ...
    {"system",  spam_system, METH_VARARGS,
     "Execute a shell command."},
    ...
    {NULL, NULL, 0, NULL}        /* Sentinel */
};

Note the third entry (METH_VARARGS). This is a flag telling the interpreter the calling convention to be used for the C function. It should normally always be METH_VARARGS or METH_VARARGS | METH_KEYWORDS; a value of 0 means that an obsolete variant of PyArg_ParseTuple() is used.

When using only METH_VARARGS, the function should expect the Python-level parameters to be passed in as a tuple acceptable for parsing via PyArg_ParseTuple(); more information on this function is provided below.

The METH_KEYWORDS bit may be set in the third field if keyword arguments should be passed to the function. In this case, the C function should accept a third PyObject * parameter which will be a dictionary of keywords. Use PyArg_ParseTupleAndKeywords() to parse the arguments to such a function.

The method table must be referenced in the module definition structure:

static struct PyModuleDef spammodule = {
    PyModuleDef_HEAD_INIT,
    "spam",   /* name of module */
    spam_doc, /* module documentation, may be NULL */
    -1,       /* size of per-interpreter state of the module,
                 or -1 if the module keeps state in global variables. */
    SpamMethods
};

This structure, in turn, must be passed to the interpreter in the module’s initialization function. The initialization function must be named PyInit_name(), where name is the name of the module, and should be the only non-static item defined in the module file:

PyMODINIT_FUNC
PyInit_spam(void)
{
    return PyModule_Create(&spammodule);
}

Note that PyMODINIT_FUNC declares the function as PyObject * return type, declares any special linkage declarations required by the platform, and for C++ declares the function as extern "C".

When the Python program imports module spam for the first time, PyInit_spam() is called. (See below for comments about embedding Python.) It calls PyModule_Create(), which returns a module object, and inserts built-in function objects into the newly created module based upon the table (an array of PyMethodDef structures) found in the module definition. PyModule_Create() returns a pointer to the module object that it creates. It may abort with a fatal error for certain errors, or return NULL if the module could not be initialized satisfactorily. The init function must return the module object to its caller, so that it then gets inserted into sys.modules.

When embedding Python, the PyInit_spam() function is not called automatically unless there’s an entry in the PyImport_Inittab table. To add the module to the initialization table, use PyImport_AppendInittab(), optionally followed by an import of the module:

int
main(int argc, char *argv[])
{
    wchar_t *program = Py_DecodeLocale(argv[0], NULL);
    if (program == NULL) {
        fprintf(stderr, "Fatal error: cannot decode argv[0]\n");
        exit(1);
    }

    /* Add a built-in module, before Py_Initialize */
    PyImport_AppendInittab("spam", PyInit_spam);

    /* Pass argv[0] to the Python interpreter */
    Py_SetProgramName(program);

    /* Initialize the Python interpreter.  Required. */
    Py_Initialize();

    /* Optionally import the module; alternatively,
       import can be deferred until the embedded script
       imports it. */
    PyImport_ImportModule("spam");

    ...

    PyMem_RawFree(program);
    return 0;
}

참고

Removing entries from sys.modules or importing compiled modules into multiple interpreters within a process (or following a fork() without an intervening exec()) can create problems for some extension modules. Extension module authors should exercise caution when initializing internal data structures.

A more substantial example module is included in the Python source distribution as Modules/xxmodule.c. This file may be used as a template or simply read as an example.

참고

Unlike our spam example, xxmodule uses multi-phase initialization (new in Python 3.5), where a PyModuleDef structure is returned from PyInit_spam, and creation of the module is left to the import machinery. For details on multi-phase initialization, see PEP 489 [https://www.python.org/dev/peps/pep-0489].

1.5. Compilation and Linkage

There are two more things to do before you can use your new extension: compiling and linking it with the Python system. If you use dynamic loading, the details may depend on the style of dynamic loading your system uses; see the chapters about building extension modules (chapter C와 C++ 확장 빌드하기) and additional information that pertains only to building on Windows (chapter 윈도우에서 C와 C++ 확장 빌드하기) for more information about this.

If you can’t use dynamic loading, or if you want to make your module a permanent part of the Python interpreter, you will have to change the configuration setup and rebuild the interpreter. Luckily, this is very simple on Unix: just place your file (spammodule.c for example) in the Modules/ directory of an unpacked source distribution, add a line to the file Modules/Setup.local describing your file:

spam spammodule.o

and rebuild the interpreter by running make in the toplevel directory. You can also run make in the Modules/ subdirectory, but then you must first rebuild Makefile there by running ‘make Makefile’. (This is necessary each time you change the Setup file.)

If your module requires additional libraries to link with, these can be listed on the line in the configuration file as well, for instance:

spam spammodule.o -lX11

1.6. Calling Python Functions from C

So far we have concentrated on making C functions callable from Python. The reverse is also useful: calling Python functions from C. This is especially the case for libraries that support so-called “callback” functions. If a C interface makes use of callbacks, the equivalent Python often needs to provide a callback mechanism to the Python programmer; the implementation will require calling the Python callback functions from a C callback. Other uses are also imaginable.

Fortunately, the Python interpreter is easily called recursively, and there is a standard interface to call a Python function. (I won’t dwell on how to call the Python parser with a particular string as input — if you’re interested, have a look at the implementation of the -c command line option in Modules/main.c from the Python source code.)

Calling a Python function is easy. First, the Python program must somehow pass you the Python function object. You should provide a function (or some other interface) to do this. When this function is called, save a pointer to the Python function object (be careful to Py_INCREF() it!) in a global variable — or wherever you see fit. For example, the following function might be part of a module definition:

static PyObject *my_callback = NULL;

static PyObject *
my_set_callback(PyObject *dummy, PyObject *args)
{
    PyObject *result = NULL;
    PyObject *temp;

    if (PyArg_ParseTuple(args, "O:set_callback", &temp)) {
        if (!PyCallable_Check(temp)) {
            PyErr_SetString(PyExc_TypeError, "parameter must be callable");
            return NULL;
        }
        Py_XINCREF(temp);         /* Add a reference to new callback */
        Py_XDECREF(my_callback);  /* Dispose of previous callback */
        my_callback = temp;       /* Remember new callback */
        /* Boilerplate to return "None" */
        Py_INCREF(Py_None);
        result = Py_None;
    }
    return result;
}

This function must be registered with the interpreter using the METH_VARARGS flag; this is described in section The Module’s Method Table and Initialization Function. The PyArg_ParseTuple() function and its arguments are documented in section Extracting Parameters in Extension Functions.

The macros Py_XINCREF() and Py_XDECREF() increment/decrement the reference count of an object and are safe in the presence of NULL pointers (but note that temp will not be NULL in this context). More info on them in section Reference Counts.

Later, when it is time to call the function, you call the C function PyObject_CallObject(). This function has two arguments, both pointers to arbitrary Python objects: the Python function, and the argument list. The argument list must always be a tuple object, whose length is the number of arguments. To call the Python function with no arguments, pass in NULL, or an empty tuple; to call it with one argument, pass a singleton tuple. Py_BuildValue() returns a tuple when its format string consists of zero or more format codes between parentheses. For example:

int arg;
PyObject *arglist;
PyObject *result;
...
arg = 123;
...
/* Time to call the callback */
arglist = Py_BuildValue("(i)", arg);
result = PyObject_CallObject(my_callback, arglist);
Py_DECREF(arglist);

PyObject_CallObject() returns a Python object pointer: this is the return value of the Python function. PyObject_CallObject() is “reference-count-neutral” with respect to its arguments. In the example a new tuple was created to serve as the argument list, which is Py_DECREF()-ed immediately after the PyObject_CallObject() call.

The return value of PyObject_CallObject() is “new”: either it is a brand new object, or it is an existing object whose reference count has been incremented. So, unless you want to save it in a global variable, you should somehow Py_DECREF() the result, even (especially!) if you are not interested in its value.

Before you do this, however, it is important to check that the return value isn’t NULL. If it is, the Python function terminated by raising an exception. If the C code that called PyObject_CallObject() is called from Python, it should now return an error indication to its Python caller, so the interpreter can print a stack trace, or the calling Python code can handle the exception. If this is not possible or desirable, the exception should be cleared by calling PyErr_Clear(). For example:

if (result == NULL)
    return NULL; /* Pass error back */
...use result...
Py_DECREF(result);

Depending on the desired interface to the Python callback function, you may also have to provide an argument list to PyObject_CallObject(). In some cases the argument list is also provided by the Python program, through the same interface that specified the callback function. It can then be saved and used in the same manner as the function object. In other cases, you may have to construct a new tuple to pass as the argument list. The simplest way to do this is to call Py_BuildValue(). For example, if you want to pass an integral event code, you might use the following code:

PyObject *arglist;
...
arglist = Py_BuildValue("(l)", eventcode);
result = PyObject_CallObject(my_callback, arglist);
Py_DECREF(arglist);
if (result == NULL)
    return NULL; /* Pass error back */
/* Here maybe use the result */
Py_DECREF(result);

Note the placement of Py_DECREF(arglist) immediately after the call, before the error check! Also note that strictly speaking this code is not complete: Py_BuildValue() may run out of memory, and this should be checked.

You may also call a function with keyword arguments by using PyObject_Call(), which supports arguments and keyword arguments. As in the above example, we use Py_BuildValue() to construct the dictionary.

PyObject *dict;
...
dict = Py_BuildValue("{s:i}", "name", val);
result = PyObject_Call(my_callback, NULL, dict);
Py_DECREF(dict);
if (result == NULL)
    return NULL; /* Pass error back */
/* Here maybe use the result */
Py_DECREF(result);

1.7. Extracting Parameters in Extension Functions

The PyArg_ParseTuple() function is declared as follows:

int PyArg_ParseTuple(PyObject *arg, const char *format, ...);

The arg argument must be a tuple object containing an argument list passed from Python to a C function. The format argument must be a format string, whose syntax is explained in Parsing arguments and building values in the Python/C API Reference Manual. The remaining arguments must be addresses of variables whose type is determined by the format string.

Note that while PyArg_ParseTuple() checks that the Python arguments have the required types, it cannot check the validity of the addresses of C variables passed to the call: if you make mistakes there, your code will probably crash or at least overwrite random bits in memory. So be careful!

Note that any Python object references which are provided to the caller are borrowed references; do not decrement their reference count!

Some example calls:

#define PY_SSIZE_T_CLEAN  /* Make "s#" use Py_ssize_t rather than int. */
#include <Python.h>

int ok;
int i, j;
long k, l;
const char *s;
Py_ssize_t size;

ok = PyArg_ParseTuple(args, ""); /* No arguments */
    /* Python call: f() */

ok = PyArg_ParseTuple(args, "s", &s); /* A string */
    /* Possible Python call: f('whoops!') */

ok = PyArg_ParseTuple(args, "lls", &k, &l, &s); /* Two longs and a string */
    /* Possible Python call: f(1, 2, 'three') */

ok = PyArg_ParseTuple(args, "(ii)s#", &i, &j, &s, &size);
    /* A pair of ints and a string, whose size is also returned */
    /* Possible Python call: f((1, 2), 'three') */

{
    const char *file;
    const char *mode = "r";
    int bufsize = 0;
    ok = PyArg_ParseTuple(args, "s|si", &file, &mode, &bufsize);
    /* A string, and optionally another string and an integer */
    /* Possible Python calls:
       f('spam')
       f('spam', 'w')
       f('spam', 'wb', 100000) */
}

{
    int left, top, right, bottom, h, v;
    ok = PyArg_ParseTuple(args, "((ii)(ii))(ii)",
             &left, &top, &right, &bottom, &h, &v);
    /* A rectangle and a point */
    /* Possible Python call:
       f(((0, 0), (400, 300)), (10, 10)) */
}

{
    Py_complex c;
    ok = PyArg_ParseTuple(args, "D:myfunction", &c);
    /* a complex, also providing a function name for errors */
    /* Possible Python call: myfunction(1+2j) */
}

1.8. Keyword Parameters for Extension Functions

The PyArg_ParseTupleAndKeywords() function is declared as follows:

int PyArg_ParseTupleAndKeywords(PyObject *arg, PyObject *kwdict,
                                const char *format, char *kwlist[], ...);

The arg and format parameters are identical to those of the PyArg_ParseTuple() function. The kwdict parameter is the dictionary of keywords received as the third parameter from the Python runtime. The kwlist parameter is a NULL-terminated list of strings which identify the parameters; the names are matched with the type information from format from left to right. On success, PyArg_ParseTupleAndKeywords() returns true, otherwise it returns false and raises an appropriate exception.

참고

Nested tuples cannot be parsed when using keyword arguments! Keyword parameters passed in which are not present in the kwlist will cause TypeError to be raised.

Here is an example module which uses keywords, based on an example by Geoff Philbrick (philbrick@hks.com):

#define PY_SSIZE_T_CLEAN  /* Make "s#" use Py_ssize_t rather than int. */
#include <Python.h>

static PyObject *
keywdarg_parrot(PyObject *self, PyObject *args, PyObject *keywds)
{
    int voltage;
    const char *state = "a stiff";
    const char *action = "voom";
    const char *type = "Norwegian Blue";

    static char *kwlist[] = {"voltage", "state", "action", "type", NULL};

    if (!PyArg_ParseTupleAndKeywords(args, keywds, "i|sss", kwlist,
                                     &voltage, &state, &action, &type))
        return NULL;

    printf("-- This parrot wouldn't %s if you put %i Volts through it.\n",
           action, voltage);
    printf("-- Lovely plumage, the %s -- It's %s!\n", type, state);

    Py_RETURN_NONE;
}

static PyMethodDef keywdarg_methods[] = {
    /* The cast of the function is necessary since PyCFunction values
     * only take two PyObject* parameters, and keywdarg_parrot() takes
     * three.
     */
    {"parrot", (PyCFunction)keywdarg_parrot, METH_VARARGS | METH_KEYWORDS,
     "Print a lovely skit to standard output."},
    {NULL, NULL, 0, NULL}   /* sentinel */
};

static struct PyModuleDef keywdargmodule = {
    PyModuleDef_HEAD_INIT,
    "keywdarg",
    NULL,
    -1,
    keywdarg_methods
};

PyMODINIT_FUNC
PyInit_keywdarg(void)
{
    return PyModule_Create(&keywdargmodule);
}

1.9. Building Arbitrary Values

This function is the counterpart to PyArg_ParseTuple(). It is declared as follows:

PyObject *Py_BuildValue(const char *format, ...);

It recognizes a set of format units similar to the ones recognized by PyArg_ParseTuple(), but the arguments (which are input to the function, not output) must not be pointers, just values. It returns a new Python object, suitable for returning from a C function called from Python.

One difference with PyArg_ParseTuple(): while the latter requires its first argument to be a tuple (since Python argument lists are always represented as tuples internally), Py_BuildValue() does not always build a tuple. It builds a tuple only if its format string contains two or more format units. If the format string is empty, it returns None; if it contains exactly one format unit, it returns whatever object is described by that format unit. To force it to return a tuple of size 0 or one, parenthesize the format string.

Examples (to the left the call, to the right the resulting Python value):

Py_BuildValue("")                        None
Py_BuildValue("i", 123)                  123
Py_BuildValue("iii", 123, 456, 789)      (123, 456, 789)
Py_BuildValue("s", "hello")              'hello'
Py_BuildValue("y", "hello")              b'hello'
Py_BuildValue("ss", "hello", "world")    ('hello', 'world')
Py_BuildValue("s#", "hello", 4)          'hell'
Py_BuildValue("y#", "hello", 4)          b'hell'
Py_BuildValue("()")                      ()
Py_BuildValue("(i)", 123)                (123,)
Py_BuildValue("(ii)", 123, 456)          (123, 456)
Py_BuildValue("(i,i)", 123, 456)         (123, 456)
Py_BuildValue("[i,i]", 123, 456)         [123, 456]
Py_BuildValue("{s:i,s:i}",
              "abc", 123, "def", 456)    {'abc': 123, 'def': 456}
Py_BuildValue("((ii)(ii)) (ii)",
              1, 2, 3, 4, 5, 6)          (((1, 2), (3, 4)), (5, 6))

1.10. Reference Counts

In languages like C or C++, the programmer is responsible for dynamic allocation and deallocation of memory on the heap. In C, this is done using the functions malloc() and free(). In C++, the operators new and delete are used with essentially the same meaning and we’ll restrict the following discussion to the C case.

Every block of memory allocated with malloc() should eventually be returned to the pool of available memory by exactly one call to free(). It is important to call free() at the right time. If a block’s address is forgotten but free() is not called for it, the memory it occupies cannot be reused until the program terminates. This is called a memory leak. On the other hand, if a program calls free() for a block and then continues to use the block, it creates a conflict with re-use of the block through another malloc() call. This is called using freed memory. It has the same bad consequences as referencing uninitialized data — core dumps, wrong results, mysterious crashes.

Common causes of memory leaks are unusual paths through the code. For instance, a function may allocate a block of memory, do some calculation, and then free the block again. Now a change in the requirements for the function may add a test to the calculation that detects an error condition and can return prematurely from the function. It’s easy to forget to free the allocated memory block when taking this premature exit, especially when it is added later to the code. Such leaks, once introduced, often go undetected for a long time: the error exit is taken only in a small fraction of all calls, and most modern machines have plenty of virtual memory, so the leak only becomes apparent in a long-running process that uses the leaking function frequently. Therefore, it’s important to prevent leaks from happening by having a coding convention or strategy that minimizes this kind of errors.

Since Python makes heavy use of malloc() and free(), it needs a strategy to avoid memory leaks as well as the use of freed memory. The chosen method is called reference counting. The principle is simple: every object contains a counter, which is incremented when a reference to the object is stored somewhere, and which is decremented when a reference to it is deleted. When the counter reaches zero, the last reference to the object has been deleted and the object is freed.

An alternative strategy is called automatic garbage collection. (Sometimes, reference counting is also referred to as a garbage collection strategy, hence my use of “automatic” to distinguish the two.) The big advantage of automatic garbage collection is that the user doesn’t need to call free() explicitly. (Another claimed advantage is an improvement in speed or memory usage — this is no hard fact however.) The disadvantage is that for C, there is no truly portable automatic garbage collector, while reference counting can be implemented portably (as long as the functions malloc() and free() are available — which the C Standard guarantees). Maybe some day a sufficiently portable automatic garbage collector will be available for C. Until then, we’ll have to live with reference counts.

While Python uses the traditional reference counting implementation, it also offers a cycle detector that works to detect reference cycles. This allows applications to not worry about creating direct or indirect circular references; these are the weakness of garbage collection implemented using only reference counting. Reference cycles consist of objects which contain (possibly indirect) references to themselves, so that each object in the cycle has a reference count which is non-zero. Typical reference counting implementations are not able to reclaim the memory belonging to any objects in a reference cycle, or referenced from the objects in the cycle, even though there are no further references to the cycle itself.

The cycle detector is able to detect garbage cycles and can reclaim them. The gc module exposes a way to run the detector (the collect() function), as well as configuration interfaces and the ability to disable the detector at runtime. The cycle detector is considered an optional component; though it is included by default, it can be disabled at build time using the --without-cycle-gc option to the configure script on Unix platforms (including Mac OS X). If the cycle detector is disabled in this way, the gc module will not be available.

1.10.1. Reference Counting in Python

There are two macros, Py_INCREF(x) and Py_DECREF(x), which handle the incrementing and decrementing of the reference count. Py_DECREF() also frees the object when the count reaches zero. For flexibility, it doesn’t call free() directly — rather, it makes a call through a function pointer in the object’s type object. For this purpose (and others), every object also contains a pointer to its type object.

The big question now remains: when to use Py_INCREF(x) and Py_DECREF(x)? Let’s first introduce some terms. Nobody “owns” an object; however, you can own a reference to an object. An object’s reference count is now defined as the number of owned references to it. The owner of a reference is responsible for calling Py_DECREF() when the reference is no longer needed. Ownership of a reference can be transferred. There are three ways to dispose of an owned reference: pass it on, store it, or call Py_DECREF(). Forgetting to dispose of an owned reference creates a memory leak.

It is also possible to borrow 2 a reference to an object. The borrower of a reference should not call Py_DECREF(). The borrower must not hold on to the object longer than the owner from which it was borrowed. Using a borrowed reference after the owner has disposed of it risks using freed memory and should be avoided completely 3.

The advantage of borrowing over owning a reference is that you don’t need to take care of disposing of the reference on all possible paths through the code — in other words, with a borrowed reference you don’t run the risk of leaking when a premature exit is taken. The disadvantage of borrowing over owning is that there are some subtle situations where in seemingly correct code a borrowed reference can be used after the owner from which it was borrowed has in fact disposed of it.

A borrowed reference can be changed into an owned reference by calling Py_INCREF(). This does not affect the status of the owner from which the reference was borrowed — it creates a new owned reference, and gives full owner responsibilities (the new owner must dispose of the reference properly, as well as the previous owner).

1.10.2. Ownership Rules

Whenever an object reference is passed into or out of a function, it is part of the function’s interface specification whether ownership is transferred with the reference or not.

Most functions that return a reference to an object pass on ownership with the reference. In particular, all functions whose function it is to create a new object, such as PyLong_FromLong() and Py_BuildValue(), pass ownership to the receiver. Even if the object is not actually new, you still receive ownership of a new reference to that object. For instance, PyLong_FromLong() maintains a cache of popular values and can return a reference to a cached item.

Many functions that extract objects from other objects also transfer ownership with the reference, for instance PyObject_GetAttrString(). The picture is less clear, here, however, since a few common routines are exceptions: PyTuple_GetItem(), PyList_GetItem(), PyDict_GetItem(), and PyDict_GetItemString() all return references that you borrow from the tuple, list or dictionary.

The function PyImport_AddModule() also returns a borrowed reference, even though it may actually create the object it returns: this is possible because an owned reference to the object is stored in sys.modules.

When you pass an object reference into another function, in general, the function borrows the reference from you — if it needs to store it, it will use Py_INCREF() to become an independent owner. There are exactly two important exceptions to this rule: PyTuple_SetItem() and PyList_SetItem(). These functions take over ownership of the item passed to them — even if they fail! (Note that PyDict_SetItem() and friends don’t take over ownership — they are “normal.”)

When a C function is called from Python, it borrows references to its arguments from the caller. The caller owns a reference to the object, so the borrowed reference’s lifetime is guaranteed until the function returns. Only when such a borrowed reference must be stored or passed on, it must be turned into an owned reference by calling Py_INCREF().

The object reference returned from a C function that is called from Python must be an owned reference — ownership is transferred from the function to its caller.

1.10.3. Thin Ice

There are a few situations where seemingly harmless use of a borrowed reference can lead to problems. These all have to do with implicit invocations of the interpreter, which can cause the owner of a reference to dispose of it.

The first and most important case to know about is using Py_DECREF() on an unrelated object while borrowing a reference to a list item. For instance:

void
bug(PyObject *list)
{
    PyObject *item = PyList_GetItem(list, 0);

    PyList_SetItem(list, 1, PyLong_FromLong(0L));
    PyObject_Print(item, stdout, 0); /* BUG! */
}

This function first borrows a reference to list[0], then replaces list[1] with the value 0, and finally prints the borrowed reference. Looks harmless, right? But it’s not!

Let’s follow the control flow into PyList_SetItem(). The list owns references to all its items, so when item 1 is replaced, it has to dispose of the original item 1. Now let’s suppose the original item 1 was an instance of a user-defined class, and let’s further suppose that the class defined a __del__() method. If this class instance has a reference count of 1, disposing of it will call its __del__() method.

Since it is written in Python, the __del__() method can execute arbitrary Python code. Could it perhaps do something to invalidate the reference to item in bug()? You bet! Assuming that the list passed into bug() is accessible to the __del__() method, it could execute a statement to the effect of del list[0], and assuming this was the last reference to that object, it would free the memory associated with it, thereby invalidating item.

The solution, once you know the source of the problem, is easy: temporarily increment the reference count. The correct version of the function reads:

void
no_bug(PyObject *list)
{
    PyObject *item = PyList_GetItem(list, 0);

    Py_INCREF(item);
    PyList_SetItem(list, 1, PyLong_FromLong(0L));
    PyObject_Print(item, stdout, 0);
    Py_DECREF(item);
}

This is a true story. An older version of Python contained variants of this bug and someone spent a considerable amount of time in a C debugger to figure out why his __del__() methods would fail…

The second case of problems with a borrowed reference is a variant involving threads. Normally, multiple threads in the Python interpreter can’t get in each other’s way, because there is a global lock protecting Python’s entire object space. However, it is possible to temporarily release this lock using the macro Py_BEGIN_ALLOW_THREADS, and to re-acquire it using Py_END_ALLOW_THREADS. This is common around blocking I/O calls, to let other threads use the processor while waiting for the I/O to complete. Obviously, the following function has the same problem as the previous one:

void
bug(PyObject *list)
{
    PyObject *item = PyList_GetItem(list, 0);
    Py_BEGIN_ALLOW_THREADS
    ...some blocking I/O call...
    Py_END_ALLOW_THREADS
    PyObject_Print(item, stdout, 0); /* BUG! */
}

1.10.4. NULL Pointers

In general, functions that take object references as arguments do not expect you to pass them NULL pointers, and will dump core (or cause later core dumps) if you do so. Functions that return object references generally return NULL only to indicate that an exception occurred. The reason for not testing for NULL arguments is that functions often pass the objects they receive on to other function — if each function were to test for NULL, there would be a lot of redundant tests and the code would run more slowly.

It is better to test for NULL only at the “source:” when a pointer that may be NULL is received, for example, from malloc() or from a function that may raise an exception.

The macros Py_INCREF() and Py_DECREF() do not check for NULL pointers — however, their variants Py_XINCREF() and Py_XDECREF() do.

The macros for checking for a particular object type (Pytype_Check()) don’t check for NULL pointers — again, there is much code that calls several of these in a row to test an object against various different expected types, and this would generate redundant tests. There are no variants with NULL checking.

The C function calling mechanism guarantees that the argument list passed to C functions (args in the examples) is never NULL — in fact it guarantees that it is always a tuple 4.

It is a severe error to ever let a NULL pointer “escape” to the Python user.

1.11. Writing Extensions in C++

It is possible to write extension modules in C++. Some restrictions apply. If the main program (the Python interpreter) is compiled and linked by the C compiler, global or static objects with constructors cannot be used. This is not a problem if the main program is linked by the C++ compiler. Functions that will be called by the Python interpreter (in particular, module initialization functions) have to be declared using extern "C". It is unnecessary to enclose the Python header files in extern "C" {...} — they use this form already if the symbol __cplusplus is defined (all recent C++ compilers define this symbol).

1.12. Providing a C API for an Extension Module

Many extension modules just provide new functions and types to be used from Python, but sometimes the code in an extension module can be useful for other extension modules. For example, an extension module could implement a type “collection” which works like lists without order. Just like the standard Python list type has a C API which permits extension modules to create and manipulate lists, this new collection type should have a set of C functions for direct manipulation from other extension modules.

At first sight this seems easy: just write the functions (without declaring them static, of course), provide an appropriate header file, and document the C API. And in fact this would work if all extension modules were always linked statically with the Python interpreter. When modules are used as shared libraries, however, the symbols defined in one module may not be visible to another module. The details of visibility depend on the operating system; some systems use one global namespace for the Python interpreter and all extension modules (Windows, for example), whereas others require an explicit list of imported symbols at module link time (AIX is one example), or offer a choice of different strategies (most Unices). And even if symbols are globally visible, the module whose functions one wishes to call might not have been loaded yet!

Portability therefore requires not to make any assumptions about symbol visibility. This means that all symbols in extension modules should be declared static, except for the module’s initialization function, in order to avoid name clashes with other extension modules (as discussed in section The Module’s Method Table and Initialization Function). And it means that symbols that should be accessible from other extension modules must be exported in a different way.

Python provides a special mechanism to pass C-level information (pointers) from one extension module to another one: Capsules. A Capsule is a Python data type which stores a pointer (void *). Capsules can only be created and accessed via their C API, but they can be passed around like any other Python object. In particular, they can be assigned to a name in an extension module’s namespace. Other extension modules can then import this module, retrieve the value of this name, and then retrieve the pointer from the Capsule.

There are many ways in which Capsules can be used to export the C API of an extension module. Each function could get its own Capsule, or all C API pointers could be stored in an array whose address is published in a Capsule. And the various tasks of storing and retrieving the pointers can be distributed in different ways between the module providing the code and the client modules.

Whichever method you choose, it’s important to name your Capsules properly. The function PyCapsule_New() takes a name parameter (const char *); you’re permitted to pass in a NULL name, but we strongly encourage you to specify a name. Properly named Capsules provide a degree of runtime type-safety; there is no feasible way to tell one unnamed Capsule from another.

In particular, Capsules used to expose C APIs should be given a name following this convention:

modulename.attributename

The convenience function PyCapsule_Import() makes it easy to load a C API provided via a Capsule, but only if the Capsule’s name matches this convention. This behavior gives C API users a high degree of certainty that the Capsule they load contains the correct C API.

The following example demonstrates an approach that puts most of the burden on the writer of the exporting module, which is appropriate for commonly used library modules. It stores all C API pointers (just one in the example!) in an array of void pointers which becomes the value of a Capsule. The header file corresponding to the module provides a macro that takes care of importing the module and retrieving its C API pointers; client modules only have to call this macro before accessing the C API.

The exporting module is a modification of the spam module from section A Simple Example. The function spam.system() does not call the C library function system() directly, but a function PySpam_System(), which would of course do something more complicated in reality (such as adding “spam” to every command). This function PySpam_System() is also exported to other extension modules.

The function PySpam_System() is a plain C function, declared static like everything else:

static int
PySpam_System(const char *command)
{
    return system(command);
}

The function spam_system() is modified in a trivial way:

static PyObject *
spam_system(PyObject *self, PyObject *args)
{
    const char *command;
    int sts;

    if (!PyArg_ParseTuple(args, "s", &command))
        return NULL;
    sts = PySpam_System(command);
    return PyLong_FromLong(sts);
}

In the beginning of the module, right after the line

#include <Python.h>

two more lines must be added:

#define SPAM_MODULE
#include "spammodule.h"

The #define is used to tell the header file that it is being included in the exporting module, not a client module. Finally, the module’s initialization function must take care of initializing the C API pointer array:

PyMODINIT_FUNC
PyInit_spam(void)
{
    PyObject *m;
    static void *PySpam_API[PySpam_API_pointers];
    PyObject *c_api_object;

    m = PyModule_Create(&spammodule);
    if (m == NULL)
        return NULL;

    /* Initialize the C API pointer array */
    PySpam_API[PySpam_System_NUM] = (void *)PySpam_System;

    /* Create a Capsule containing the API pointer array's address */
    c_api_object = PyCapsule_New((void *)PySpam_API, "spam._C_API", NULL);

    if (PyModule_AddObject(m, "_C_API", c_api_object) < 0) {
        Py_XDECREF(c_api_object);
        Py_DECREF(m);
        return NULL;
    }

    return m;
}

Note that PySpam_API is declared static; otherwise the pointer array would disappear when PyInit_spam() terminates!

The bulk of the work is in the header file spammodule.h, which looks like this:

#ifndef Py_SPAMMODULE_H
#define Py_SPAMMODULE_H
#ifdef __cplusplus
extern "C" {
#endif

/* Header file for spammodule */

/* C API functions */
#define PySpam_System_NUM 0
#define PySpam_System_RETURN int
#define PySpam_System_PROTO (const char *command)

/* Total number of C API pointers */
#define PySpam_API_pointers 1

#ifdef SPAM_MODULE
/* This section is used when compiling spammodule.c */

static PySpam_System_RETURN PySpam_System PySpam_System_PROTO;

#else
/* This section is used in modules that use spammodule's API */

static void **PySpam_API;

#define PySpam_System \
 (*(PySpam_System_RETURN (*)PySpam_System_PROTO) PySpam_API[PySpam_System_NUM])

/* Return -1 on error, 0 on success.
 * PyCapsule_Import will set an exception if there's an error.
 */
static int
import_spam(void)
{
    PySpam_API = (void **)PyCapsule_Import("spam._C_API", 0);
    return (PySpam_API != NULL) ? 0 : -1;
}

#endif

#ifdef __cplusplus
}
#endif

#endif /* !defined(Py_SPAMMODULE_H) */

All that a client module must do in order to have access to the function PySpam_System() is to call the function (or rather macro) import_spam() in its initialization function:

PyMODINIT_FUNC
PyInit_client(void)
{
    PyObject *m;

    m = PyModule_Create(&clientmodule);
    if (m == NULL)
        return NULL;
    if (import_spam() < 0)
        return NULL;
    /* additional initialization can happen here */
    return m;
}

The main disadvantage of this approach is that the file spammodule.h is rather complicated. However, the basic structure is the same for each function that is exported, so it has to be learned only once.

Finally it should be mentioned that Capsules offer additional functionality, which is especially useful for memory allocation and deallocation of the pointer stored in a Capsule. The details are described in the Python/C API Reference Manual in the section 캡슐 and in the implementation of Capsules (files Include/pycapsule.h and Objects/pycapsule.c in the Python source code distribution).

Footnotes

1

An interface for this function already exists in the standard module os — it was chosen as a simple and straightforward example.

2

The metaphor of “borrowing” a reference is not completely correct: the owner still has a copy of the reference.

3

Checking that the reference count is at least 1 does not work — the reference count itself could be in freed memory and may thus be reused for another object!

4

These guarantees don’t hold when you use the “old” style calling convention — this is still found in much existing code.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 인터프리터 확장 및 내장 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 인터프리터 확장 및 내장 »

|

2. Defining Extension Types: Tutorial

Python allows the writer of a C extension module to define new types that can be manipulated from Python code, much like the built-in str and list types. The code for all extension types follows a pattern, but there are some details that you need to understand before you can get started. This document is a gentle introduction to the topic.

2.1. The Basics

The CPython runtime sees all Python objects as variables of type PyObject*, which serves as a “base type” for all Python objects. The PyObject structure itself only contains the object’s reference count and a pointer to the object’s “type object”. This is where the action is; the type object determines which (C) functions get called by the interpreter when, for instance, an attribute gets looked up on an object, a method called, or it is multiplied by another object. These C functions are called “type methods”.

So, if you want to define a new extension type, you need to create a new type object.

This sort of thing can only be explained by example, so here’s a minimal, but complete, module that defines a new type named Custom inside a C extension module custom:

참고

What we’re showing here is the traditional way of defining static extension types. It should be adequate for most uses. The C API also allows defining heap-allocated extension types using the PyType_FromSpec() function, which isn’t covered in this tutorial.

#define PY_SSIZE_T_CLEAN
#include <Python.h>

typedef struct {
    PyObject_HEAD
    /* Type-specific fields go here. */
} CustomObject;

static PyTypeObject CustomType = {
    PyVarObject_HEAD_INIT(NULL, 0)
    .tp_name = "custom.Custom",
    .tp_doc = "Custom objects",
    .tp_basicsize = sizeof(CustomObject),
    .tp_itemsize = 0,
    .tp_flags = Py_TPFLAGS_DEFAULT,
    .tp_new = PyType_GenericNew,
};

static PyModuleDef custommodule = {
    PyModuleDef_HEAD_INIT,
    .m_name = "custom",
    .m_doc = "Example module that creates an extension type.",
    .m_size = -1,
};

PyMODINIT_FUNC
PyInit_custom(void)
{
    PyObject *m;
    if (PyType_Ready(&CustomType) < 0)
        return NULL;

    m = PyModule_Create(&custommodule);
    if (m == NULL)
        return NULL;

    Py_INCREF(&CustomType);
    if (PyModule_AddObject(m, "Custom", (PyObject *) &CustomType) < 0) {
        Py_DECREF(&CustomType);
        Py_DECREF(m);
        return NULL;
    }

    return m;
}

Now that’s quite a bit to take in at once, but hopefully bits will seem familiar from the previous chapter. This file defines three things:

What a Custom object contains: this is the CustomObject struct, which is allocated once for each Custom instance.

How the Custom type behaves: this is the CustomType struct, which defines a set of flags and function pointers that the interpreter inspects when specific operations are requested.

How to initialize the custom module: this is the PyInit_custom function and the associated custommodule struct.

The first bit is:

typedef struct {
    PyObject_HEAD
} CustomObject;

This is what a Custom object will contain. PyObject_HEAD is mandatory at the start of each object struct and defines a field called ob_base of type PyObject, containing a pointer to a type object and a reference count (these can be accessed using the macros Py_REFCNT and Py_TYPE respectively). The reason for the macro is to abstract away the layout and to enable additional fields in debug builds.

참고

There is no semicolon above after the PyObject_HEAD macro. Be wary of adding one by accident: some compilers will complain.

Of course, objects generally store additional data besides the standard PyObject_HEAD boilerplate; for example, here is the definition for standard Python floats:

typedef struct {
    PyObject_HEAD
    double ob_fval;
} PyFloatObject;

The second bit is the definition of the type object.

static PyTypeObject CustomType = {
    PyVarObject_HEAD_INIT(NULL, 0)
    .tp_name = "custom.Custom",
    .tp_doc = "Custom objects",
    .tp_basicsize = sizeof(CustomObject),
    .tp_itemsize = 0,
    .tp_flags = Py_TPFLAGS_DEFAULT,
    .tp_new = PyType_GenericNew,
};

참고

We recommend using C99-style designated initializers as above, to avoid listing all the PyTypeObject fields that you don’t care about and also to avoid caring about the fields’ declaration order.

The actual definition of PyTypeObject in object.h has many more fields than the definition above. The remaining fields will be filled with zeros by the C compiler, and it’s common practice to not specify them explicitly unless you need them.

We’re going to pick it apart, one field at a time:

PyVarObject_HEAD_INIT(NULL, 0)

This line is mandatory boilerplate to initialize the ob_base field mentioned above.

.tp_name = "custom.Custom",

The name of our type. This will appear in the default textual representation of our objects and in some error messages, for example:

>>> "" + custom.Custom()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "custom.Custom") to str

Note that the name is a dotted name that includes both the module name and the name of the type within the module. The module in this case is custom and the type is Custom, so we set the type name to custom.Custom. Using the real dotted import path is important to make your type compatible with the pydoc and pickle modules.

.tp_basicsize = sizeof(CustomObject),
.tp_itemsize = 0,

This is so that Python knows how much memory to allocate when creating new Custom instances. tp_itemsize is only used for variable-sized objects and should otherwise be zero.

참고

If you want your type to be subclassable from Python, and your type has the same tp_basicsize as its base type, you may have problems with multiple inheritance. A Python subclass of your type will have to list your type first in its __bases__, or else it will not be able to call your type’s __new__() method without getting an error. You can avoid this problem by ensuring that your type has a larger value for tp_basicsize than its base type does. Most of the time, this will be true anyway, because either your base type will be object, or else you will be adding data members to your base type, and therefore increasing its size.

We set the class flags to Py_TPFLAGS_DEFAULT.

.tp_flags = Py_TPFLAGS_DEFAULT,

All types should include this constant in their flags. It enables all of the members defined until at least Python 3.3. If you need further members, you will need to OR the corresponding flags.

We provide a doc string for the type in tp_doc.

.tp_doc = "Custom objects",

To enable object creation, we have to provide a tp_new handler. This is the equivalent of the Python method __new__(), but has to be specified explicitly. In this case, we can just use the default implementation provided by the API function PyType_GenericNew().

.tp_new = PyType_GenericNew,

Everything else in the file should be familiar, except for some code in PyInit_custom():

if (PyType_Ready(&CustomType) < 0)
    return;

This initializes the Custom type, filling in a number of members to the appropriate default values, including ob_type that we initially set to NULL.

Py_INCREF(&CustomType);
if (PyModule_AddObject(m, "Custom", (PyObject *) &CustomType) < 0) {
    Py_DECREF(&CustomType);
    Py_DECREF(m);
    return NULL;
}

This adds the type to the module dictionary. This allows us to create Custom instances by calling the Custom class:

>>> import custom
>>> mycustom = custom.Custom()

That’s it! All that remains is to build it; put the above code in a file called custom.c and:

from distutils.core import setup, Extension
setup(name="custom", version="1.0",
      ext_modules=[Extension("custom", ["custom.c"])])

in a file called setup.py; then typing

$ python setup.py build

at a shell should produce a file custom.so in a subdirectory; move to that directory and fire up Python — you should be able to import custom and play around with Custom objects.

That wasn’t so hard, was it?

Of course, the current Custom type is pretty uninteresting. It has no data and doesn’t do anything. It can’t even be subclassed.

참고

While this documentation showcases the standard distutils module for building C extensions, it is recommended in real-world use cases to use the newer and better-maintained setuptools library. Documentation on how to do this is out of scope for this document and can be found in the Python Packaging User’s Guide [https://packaging.python.org/tutorials/distributing-packages/].

2.2. Adding data and methods to the Basic example

Let’s extend the basic example to add some data and methods. Let’s also make the type usable as a base class. We’ll create a new module, custom2 that adds these capabilities:

#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include "structmember.h"

typedef struct {
    PyObject_HEAD
    PyObject *first; /* first name */
    PyObject *last;  /* last name */
    int number;
} CustomObject;

static void
Custom_dealloc(CustomObject *self)
{
    Py_XDECREF(self->first);
    Py_XDECREF(self->last);
    Py_TYPE(self)->tp_free((PyObject *) self);
}

static PyObject *
Custom_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
    CustomObject *self;
    self = (CustomObject *) type->tp_alloc(type, 0);
    if (self != NULL) {
        self->first = PyUnicode_FromString("");
        if (self->first == NULL) {
            Py_DECREF(self);
            return NULL;
        }
        self->last = PyUnicode_FromString("");
        if (self->last == NULL) {
            Py_DECREF(self);
            return NULL;
        }
        self->number = 0;
    }
    return (PyObject *) self;
}

static int
Custom_init(CustomObject *self, PyObject *args, PyObject *kwds)
{
    static char *kwlist[] = {"first", "last", "number", NULL};
    PyObject *first = NULL, *last = NULL, *tmp;

    if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OOi", kwlist,
                                     &first, &last,
                                     &self->number))
        return -1;

    if (first) {
        tmp = self->first;
        Py_INCREF(first);
        self->first = first;
        Py_XDECREF(tmp);
    }
    if (last) {
        tmp = self->last;
        Py_INCREF(last);
        self->last = last;
        Py_XDECREF(tmp);
    }
    return 0;
}

static PyMemberDef Custom_members[] = {
    {"first", T_OBJECT_EX, offsetof(CustomObject, first), 0,
     "first name"},
    {"last", T_OBJECT_EX, offsetof(CustomObject, last), 0,
     "last name"},
    {"number", T_INT, offsetof(CustomObject, number), 0,
     "custom number"},
    {NULL}  /* Sentinel */
};

static PyObject *
Custom_name(CustomObject *self, PyObject *Py_UNUSED(ignored))
{
    if (self->first == NULL) {
        PyErr_SetString(PyExc_AttributeError, "first");
        return NULL;
    }
    if (self->last == NULL) {
        PyErr_SetString(PyExc_AttributeError, "last");
        return NULL;
    }
    return PyUnicode_FromFormat("%S %S", self->first, self->last);
}

static PyMethodDef Custom_methods[] = {
    {"name", (PyCFunction) Custom_name, METH_NOARGS,
     "Return the name, combining the first and last name"
    },
    {NULL}  /* Sentinel */
};

static PyTypeObject CustomType = {
    PyVarObject_HEAD_INIT(NULL, 0)
    .tp_name = "custom2.Custom",
    .tp_doc = "Custom objects",
    .tp_basicsize = sizeof(CustomObject),
    .tp_itemsize = 0,
    .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
    .tp_new = Custom_new,
    .tp_init = (initproc) Custom_init,
    .tp_dealloc = (destructor) Custom_dealloc,
    .tp_members = Custom_members,
    .tp_methods = Custom_methods,
};

static PyModuleDef custommodule = {
    PyModuleDef_HEAD_INIT,
    .m_name = "custom2",
    .m_doc = "Example module that creates an extension type.",
    .m_size = -1,
};

PyMODINIT_FUNC
PyInit_custom2(void)
{
    PyObject *m;
    if (PyType_Ready(&CustomType) < 0)
        return NULL;

    m = PyModule_Create(&custommodule);
    if (m == NULL)
        return NULL;

    Py_INCREF(&CustomType);
    if (PyModule_AddObject(m, "Custom", (PyObject *) &CustomType) < 0) {
        Py_DECREF(&CustomType);
        Py_DECREF(m);
        return NULL;
    }

    return m;
}

This version of the module has a number of changes.

We’ve added an extra include:

#include <structmember.h>

This include provides declarations that we use to handle attributes, as described a bit later.

The Custom type now has three data attributes in its C struct, first, last, and number. The first and last variables are Python strings containing first and last names. The number attribute is a C integer.

The object structure is updated accordingly:

typedef struct {
    PyObject_HEAD
    PyObject *first; /* first name */
    PyObject *last;  /* last name */
    int number;
} CustomObject;

Because we now have data to manage, we have to be more careful about object allocation and deallocation. At a minimum, we need a deallocation method:

static void
Custom_dealloc(CustomObject *self)
{
    Py_XDECREF(self->first);
    Py_XDECREF(self->last);
    Py_TYPE(self)->tp_free((PyObject *) self);
}

which is assigned to the tp_dealloc member:

.tp_dealloc = (destructor) Custom_dealloc,

This method first clears the reference counts of the two Python attributes. Py_XDECREF() correctly handles the case where its argument is NULL (which might happen here if tp_new failed midway). It then calls the tp_free member of the object’s type (computed by Py_TYPE(self)) to free the object’s memory. Note that the object’s type might not be CustomType, because the object may be an instance of a subclass.

참고

The explicit cast to destructor above is needed because we defined Custom_dealloc to take a CustomObject * argument, but the tp_dealloc function pointer expects to receive a PyObject * argument. Otherwise, the compiler will emit a warning. This is object-oriented polymorphism, in C!

We want to make sure that the first and last names are initialized to empty strings, so we provide a tp_new implementation:

static PyObject *
Custom_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
    CustomObject *self;
    self = (CustomObject *) type->tp_alloc(type, 0);
    if (self != NULL) {
        self->first = PyUnicode_FromString("");
        if (self->first == NULL) {
            Py_DECREF(self);
            return NULL;
        }
        self->last = PyUnicode_FromString("");
        if (self->last == NULL) {
            Py_DECREF(self);
            return NULL;
        }
        self->number = 0;
    }
    return (PyObject *) self;
}

and install it in the tp_new member:

.tp_new = Custom_new,

The tp_new handler is responsible for creating (as opposed to initializing) objects of the type. It is exposed in Python as the __new__() method. It is not required to define a tp_new member, and indeed many extension types will simply reuse PyType_GenericNew() as done in the first version of the Custom type above. In this case, we use the tp_new handler to initialize the first and last attributes to non-NULL default values.

tp_new is passed the type being instantiated (not necessarily CustomType, if a subclass is instantiated) and any arguments passed when the type was called, and is expected to return the instance created. tp_new handlers always accept positional and keyword arguments, but they often ignore the arguments, leaving the argument handling to initializer (a.k.a. tp_init in C or __init__ in Python) methods.

참고

tp_new shouldn’t call tp_init explicitly, as the interpreter will do it itself.

The tp_new implementation calls the tp_alloc slot to allocate memory:

self = (CustomObject *) type->tp_alloc(type, 0);

Since memory allocation may fail, we must check the tp_alloc result against NULL before proceeding.

참고

We didn’t fill the tp_alloc slot ourselves. Rather PyType_Ready() fills it for us by inheriting it from our base class, which is object by default. Most types use the default allocation strategy.

참고

If you are creating a co-operative tp_new (one that calls a base type’s tp_new or __new__()), you must not try to determine what method to call using method resolution order at runtime. Always statically determine what type you are going to call, and call its tp_new directly, or via type->tp_base->tp_new. If you do not do this, Python subclasses of your type that also inherit from other Python-defined classes may not work correctly. (Specifically, you may not be able to create instances of such subclasses without getting a TypeError.)

We also define an initialization function which accepts arguments to provide initial values for our instance:

static int
Custom_init(CustomObject *self, PyObject *args, PyObject *kwds)
{
    static char *kwlist[] = {"first", "last", "number", NULL};
    PyObject *first = NULL, *last = NULL, *tmp;

    if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OOi", kwlist,
                                     &first, &last,
                                     &self->number))
        return -1;

    if (first) {
        tmp = self->first;
        Py_INCREF(first);
        self->first = first;
        Py_XDECREF(tmp);
    }
    if (last) {
        tmp = self->last;
        Py_INCREF(last);
        self->last = last;
        Py_XDECREF(tmp);
    }
    return 0;
}

by filling the tp_init slot.

.tp_init = (initproc) Custom_init,

The tp_init slot is exposed in Python as the __init__() method. It is used to initialize an object after it’s created. Initializers always accept positional and keyword arguments, and they should return either 0 on success or -1 on error.

Unlike the tp_new handler, there is no guarantee that tp_init is called at all (for example, the pickle module by default doesn’t call __init__() on unpickled instances). It can also be called multiple times. Anyone can call the __init__() method on our objects. For this reason, we have to be extra careful when assigning the new attribute values. We might be tempted, for example to assign the first member like this:

if (first) {
    Py_XDECREF(self->first);
    Py_INCREF(first);
    self->first = first;
}

But this would be risky. Our type doesn’t restrict the type of the first member, so it could be any kind of object. It could have a destructor that causes code to be executed that tries to access the first member; or that destructor could release the Global interpreter Lock and let arbitrary code run in other threads that accesses and modifies our object.

To be paranoid and protect ourselves against this possibility, we almost always reassign members before decrementing their reference counts. When don’t we have to do this?

when we absolutely know that the reference count is greater than 1;

when we know that deallocation of the object 1 will neither release the GIL nor cause any calls back into our type’s code;

when decrementing a reference count in a tp_dealloc handler on a type which doesn’t support cyclic garbage collection 2.

We want to expose our instance variables as attributes. There are a number of ways to do that. The simplest way is to define member definitions:

static PyMemberDef Custom_members[] = {
    {"first", T_OBJECT_EX, offsetof(CustomObject, first), 0,
     "first name"},
    {"last", T_OBJECT_EX, offsetof(CustomObject, last), 0,
     "last name"},
    {"number", T_INT, offsetof(CustomObject, number), 0,
     "custom number"},
    {NULL}  /* Sentinel */
};

and put the definitions in the tp_members slot:

.tp_members = Custom_members,

Each member definition has a member name, type, offset, access flags and documentation string. See the Generic Attribute Management section below for details.

A disadvantage of this approach is that it doesn’t provide a way to restrict the types of objects that can be assigned to the Python attributes. We expect the first and last names to be strings, but any Python objects can be assigned. Further, the attributes can be deleted, setting the C pointers to NULL. Even though we can make sure the members are initialized to non-NULL values, the members can be set to NULL if the attributes are deleted.

We define a single method, Custom.name(), that outputs the objects name as the concatenation of the first and last names.

static PyObject *
Custom_name(CustomObject *self)
{
    if (self->first == NULL) {
        PyErr_SetString(PyExc_AttributeError, "first");
        return NULL;
    }
    if (self->last == NULL) {
        PyErr_SetString(PyExc_AttributeError, "last");
        return NULL;
    }
    return PyUnicode_FromFormat("%S %S", self->first, self->last);
}

The method is implemented as a C function that takes a Custom (or Custom subclass) instance as the first argument. Methods always take an instance as the first argument. Methods often take positional and keyword arguments as well, but in this case we don’t take any and don’t need to accept a positional argument tuple or keyword argument dictionary. This method is equivalent to the Python method:

def name(self):
    return "%s %s" % (self.first, self.last)

Note that we have to check for the possibility that our first and last members are NULL. This is because they can be deleted, in which case they are set to NULL. It would be better to prevent deletion of these attributes and to restrict the attribute values to be strings. We’ll see how to do that in the next section.

Now that we’ve defined the method, we need to create an array of method definitions:

static PyMethodDef Custom_methods[] = {
    {"name", (PyCFunction) Custom_name, METH_NOARGS,
     "Return the name, combining the first and last name"
    },
    {NULL}  /* Sentinel */
};

(note that we used the METH_NOARGS flag to indicate that the method is expecting no arguments other than self)

and assign it to the tp_methods slot:

.tp_methods = Custom_methods,

Finally, we’ll make our type usable as a base class for subclassing. We’ve written our methods carefully so far so that they don’t make any assumptions about the type of the object being created or used, so all we need to do is to add the Py_TPFLAGS_BASETYPE to our class flag definition:

.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,

We rename PyInit_custom() to PyInit_custom2(), update the module name in the PyModuleDef struct, and update the full class name in the PyTypeObject struct.

Finally, we update our setup.py file to build the new module:

from distutils.core import setup, Extension
setup(name="custom", version="1.0",
      ext_modules=[
         Extension("custom", ["custom.c"]),
         Extension("custom2", ["custom2.c"]),
         ])

2.3. Providing finer control over data attributes

In this section, we’ll provide finer control over how the first and last attributes are set in the Custom example. In the previous version of our module, the instance variables first and last could be set to non-string values or even deleted. We want to make sure that these attributes always contain strings.

#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include "structmember.h"

typedef struct {
    PyObject_HEAD
    PyObject *first; /* first name */
    PyObject *last;  /* last name */
    int number;
} CustomObject;

static void
Custom_dealloc(CustomObject *self)
{
    Py_XDECREF(self->first);
    Py_XDECREF(self->last);
    Py_TYPE(self)->tp_free((PyObject *) self);
}

static PyObject *
Custom_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
    CustomObject *self;
    self = (CustomObject *) type->tp_alloc(type, 0);
    if (self != NULL) {
        self->first = PyUnicode_FromString("");
        if (self->first == NULL) {
            Py_DECREF(self);
            return NULL;
        }
        self->last = PyUnicode_FromString("");
        if (self->last == NULL) {
            Py_DECREF(self);
            return NULL;
        }
        self->number = 0;
    }
    return (PyObject *) self;
}

static int
Custom_init(CustomObject *self, PyObject *args, PyObject *kwds)
{
    static char *kwlist[] = {"first", "last", "number", NULL};
    PyObject *first = NULL, *last = NULL, *tmp;

    if (!PyArg_ParseTupleAndKeywords(args, kwds, "|UUi", kwlist,
                                     &first, &last,
                                     &self->number))
        return -1;

    if (first) {
        tmp = self->first;
        Py_INCREF(first);
        self->first = first;
        Py_DECREF(tmp);
    }
    if (last) {
        tmp = self->last;
        Py_INCREF(last);
        self->last = last;
        Py_DECREF(tmp);
    }
    return 0;
}

static PyMemberDef Custom_members[] = {
    {"number", T_INT, offsetof(CustomObject, number), 0,
     "custom number"},
    {NULL}  /* Sentinel */
};

static PyObject *
Custom_getfirst(CustomObject *self, void *closure)
{
    Py_INCREF(self->first);
    return self->first;
}

static int
Custom_setfirst(CustomObject *self, PyObject *value, void *closure)
{
    PyObject *tmp;
    if (value == NULL) {
        PyErr_SetString(PyExc_TypeError, "Cannot delete the first attribute");
        return -1;
    }
    if (!PyUnicode_Check(value)) {
        PyErr_SetString(PyExc_TypeError,
                        "The first attribute value must be a string");
        return -1;
    }
    tmp = self->first;
    Py_INCREF(value);
    self->first = value;
    Py_DECREF(tmp);
    return 0;
}

static PyObject *
Custom_getlast(CustomObject *self, void *closure)
{
    Py_INCREF(self->last);
    return self->last;
}

static int
Custom_setlast(CustomObject *self, PyObject *value, void *closure)
{
    PyObject *tmp;
    if (value == NULL) {
        PyErr_SetString(PyExc_TypeError, "Cannot delete the last attribute");
        return -1;
    }
    if (!PyUnicode_Check(value)) {
        PyErr_SetString(PyExc_TypeError,
                        "The last attribute value must be a string");
        return -1;
    }
    tmp = self->last;
    Py_INCREF(value);
    self->last = value;
    Py_DECREF(tmp);
    return 0;
}

static PyGetSetDef Custom_getsetters[] = {
    {"first", (getter) Custom_getfirst, (setter) Custom_setfirst,
     "first name", NULL},
    {"last", (getter) Custom_getlast, (setter) Custom_setlast,
     "last name", NULL},
    {NULL}  /* Sentinel */
};

static PyObject *
Custom_name(CustomObject *self, PyObject *Py_UNUSED(ignored))
{
    return PyUnicode_FromFormat("%S %S", self->first, self->last);
}

static PyMethodDef Custom_methods[] = {
    {"name", (PyCFunction) Custom_name, METH_NOARGS,
     "Return the name, combining the first and last name"
    },
    {NULL}  /* Sentinel */
};

static PyTypeObject CustomType = {
    PyVarObject_HEAD_INIT(NULL, 0)
    .tp_name = "custom3.Custom",
    .tp_doc = "Custom objects",
    .tp_basicsize = sizeof(CustomObject),
    .tp_itemsize = 0,
    .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
    .tp_new = Custom_new,
    .tp_init = (initproc) Custom_init,
    .tp_dealloc = (destructor) Custom_dealloc,
    .tp_members = Custom_members,
    .tp_methods = Custom_methods,
    .tp_getset = Custom_getsetters,
};

static PyModuleDef custommodule = {
    PyModuleDef_HEAD_INIT,
    .m_name = "custom3",
    .m_doc = "Example module that creates an extension type.",
    .m_size = -1,
};

PyMODINIT_FUNC
PyInit_custom3(void)
{
    PyObject *m;
    if (PyType_Ready(&CustomType) < 0)
        return NULL;

    m = PyModule_Create(&custommodule);
    if (m == NULL)
        return NULL;

    Py_INCREF(&CustomType);
    if (PyModule_AddObject(m, "Custom", (PyObject *) &CustomType) < 0) {
        Py_DECREF(&CustomType);
        Py_DECREF(m);
        return NULL;
    }

    return m;
}

To provide greater control, over the first and last attributes, we’ll use custom getter and setter functions. Here are the functions for getting and setting the first attribute:

static PyObject *
Custom_getfirst(CustomObject *self, void *closure)
{
    Py_INCREF(self->first);
    return self->first;
}

static int
Custom_setfirst(CustomObject *self, PyObject *value, void *closure)
{
    PyObject *tmp;
    if (value == NULL) {
        PyErr_SetString(PyExc_TypeError, "Cannot delete the first attribute");
        return -1;
    }
    if (!PyUnicode_Check(value)) {
        PyErr_SetString(PyExc_TypeError,
                        "The first attribute value must be a string");
        return -1;
    }
    tmp = self->first;
    Py_INCREF(value);
    self->first = value;
    Py_DECREF(tmp);
    return 0;
}

The getter function is passed a Custom object and a “closure”, which is a void pointer. In this case, the closure is ignored. (The closure supports an advanced usage in which definition data is passed to the getter and setter. This could, for example, be used to allow a single set of getter and setter functions that decide the attribute to get or set based on data in the closure.)

The setter function is passed the Custom object, the new value, and the closure. The new value may be NULL, in which case the attribute is being deleted. In our setter, we raise an error if the attribute is deleted or if its new value is not a string.

We create an array of PyGetSetDef structures:

static PyGetSetDef Custom_getsetters[] = {
    {"first", (getter) Custom_getfirst, (setter) Custom_setfirst,
     "first name", NULL},
    {"last", (getter) Custom_getlast, (setter) Custom_setlast,
     "last name", NULL},
    {NULL}  /* Sentinel */
};

and register it in the tp_getset slot:

.tp_getset = Custom_getsetters,

The last item in a PyGetSetDef structure is the “closure” mentioned above. In this case, we aren’t using a closure, so we just pass NULL.

We also remove the member definitions for these attributes:

static PyMemberDef Custom_members[] = {
    {"number", T_INT, offsetof(CustomObject, number), 0,
     "custom number"},
    {NULL}  /* Sentinel */
};

We also need to update the tp_init handler to only allow strings 3 to be passed:

static int
Custom_init(CustomObject *self, PyObject *args, PyObject *kwds)
{
    static char *kwlist[] = {"first", "last", "number", NULL};
    PyObject *first = NULL, *last = NULL, *tmp;

    if (!PyArg_ParseTupleAndKeywords(args, kwds, "|UUi", kwlist,
                                     &first, &last,
                                     &self->number))
        return -1;

    if (first) {
        tmp = self->first;
        Py_INCREF(first);
        self->first = first;
        Py_DECREF(tmp);
    }
    if (last) {
        tmp = self->last;
        Py_INCREF(last);
        self->last = last;
        Py_DECREF(tmp);
    }
    return 0;
}

With these changes, we can assure that the first and last members are never NULL so we can remove checks for NULL values in almost all cases. This means that most of the Py_XDECREF() calls can be converted to Py_DECREF() calls. The only place we can’t change these calls is in the tp_dealloc implementation, where there is the possibility that the initialization of these members failed in tp_new.

We also rename the module initialization function and module name in the initialization function, as we did before, and we add an extra definition to the setup.py file.

2.4. Supporting cyclic garbage collection

Python has a cyclic garbage collector (GC) that can identify unneeded objects even when their reference counts are not zero. This can happen when objects are involved in cycles. For example, consider:

>>> l = []
>>> l.append(l)
>>> del l

In this example, we create a list that contains itself. When we delete it, it still has a reference from itself. Its reference count doesn’t drop to zero. Fortunately, Python’s cyclic garbage collector will eventually figure out that the list is garbage and free it.

In the second version of the Custom example, we allowed any kind of object to be stored in the first or last attributes 4. Besides, in the second and third versions, we allowed subclassing Custom, and subclasses may add arbitrary attributes. For any of those two reasons, Custom objects can participate in cycles:

>>> import custom3
>>> class Derived(custom3.Custom): pass
...
>>> n = Derived()
>>> n.some_attribute = n

To allow a Custom instance participating in a reference cycle to be properly detected and collected by the cyclic GC, our Custom type needs to fill two additional slots and to enable a flag that enables these slots:

#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include "structmember.h"

typedef struct {
    PyObject_HEAD
    PyObject *first; /* first name */
    PyObject *last;  /* last name */
    int number;
} CustomObject;

static int
Custom_traverse(CustomObject *self, visitproc visit, void *arg)
{
    Py_VISIT(self->first);
    Py_VISIT(self->last);
    return 0;
}

static int
Custom_clear(CustomObject *self)
{
    Py_CLEAR(self->first);
    Py_CLEAR(self->last);
    return 0;
}

static void
Custom_dealloc(CustomObject *self)
{
    PyObject_GC_UnTrack(self);
    Custom_clear(self);
    Py_TYPE(self)->tp_free((PyObject *) self);
}

static PyObject *
Custom_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
    CustomObject *self;
    self = (CustomObject *) type->tp_alloc(type, 0);
    if (self != NULL) {
        self->first = PyUnicode_FromString("");
        if (self->first == NULL) {
            Py_DECREF(self);
            return NULL;
        }
        self->last = PyUnicode_FromString("");
        if (self->last == NULL) {
            Py_DECREF(self);
            return NULL;
        }
        self->number = 0;
    }
    return (PyObject *) self;
}

static int
Custom_init(CustomObject *self, PyObject *args, PyObject *kwds)
{
    static char *kwlist[] = {"first", "last", "number", NULL};
    PyObject *first = NULL, *last = NULL, *tmp;

    if (!PyArg_ParseTupleAndKeywords(args, kwds, "|UUi", kwlist,
                                     &first, &last,
                                     &self->number))
        return -1;

    if (first) {
        tmp = self->first;
        Py_INCREF(first);
        self->first = first;
        Py_DECREF(tmp);
    }
    if (last) {
        tmp = self->last;
        Py_INCREF(last);
        self->last = last;
        Py_DECREF(tmp);
    }
    return 0;
}

static PyMemberDef Custom_members[] = {
    {"number", T_INT, offsetof(CustomObject, number), 0,
     "custom number"},
    {NULL}  /* Sentinel */
};

static PyObject *
Custom_getfirst(CustomObject *self, void *closure)
{
    Py_INCREF(self->first);
    return self->first;
}

static int
Custom_setfirst(CustomObject *self, PyObject *value, void *closure)
{
    if (value == NULL) {
        PyErr_SetString(PyExc_TypeError, "Cannot delete the first attribute");
        return -1;
    }
    if (!PyUnicode_Check(value)) {
        PyErr_SetString(PyExc_TypeError,
                        "The first attribute value must be a string");
        return -1;
    }
    Py_INCREF(value);
    Py_CLEAR(self->first);
    self->first = value;
    return 0;
}

static PyObject *
Custom_getlast(CustomObject *self, void *closure)
{
    Py_INCREF(self->last);
    return self->last;
}

static int
Custom_setlast(CustomObject *self, PyObject *value, void *closure)
{
    if (value == NULL) {
        PyErr_SetString(PyExc_TypeError, "Cannot delete the last attribute");
        return -1;
    }
    if (!PyUnicode_Check(value)) {
        PyErr_SetString(PyExc_TypeError,
                        "The last attribute value must be a string");
        return -1;
    }
    Py_INCREF(value);
    Py_CLEAR(self->last);
    self->last = value;
    return 0;
}

static PyGetSetDef Custom_getsetters[] = {
    {"first", (getter) Custom_getfirst, (setter) Custom_setfirst,
     "first name", NULL},
    {"last", (getter) Custom_getlast, (setter) Custom_setlast,
     "last name", NULL},
    {NULL}  /* Sentinel */
};

static PyObject *
Custom_name(CustomObject *self, PyObject *Py_UNUSED(ignored))
{
    return PyUnicode_FromFormat("%S %S", self->first, self->last);
}

static PyMethodDef Custom_methods[] = {
    {"name", (PyCFunction) Custom_name, METH_NOARGS,
     "Return the name, combining the first and last name"
    },
    {NULL}  /* Sentinel */
};

static PyTypeObject CustomType = {
    PyVarObject_HEAD_INIT(NULL, 0)
    .tp_name = "custom4.Custom",
    .tp_doc = "Custom objects",
    .tp_basicsize = sizeof(CustomObject),
    .tp_itemsize = 0,
    .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
    .tp_new = Custom_new,
    .tp_init = (initproc) Custom_init,
    .tp_dealloc = (destructor) Custom_dealloc,
    .tp_traverse = (traverseproc) Custom_traverse,
    .tp_clear = (inquiry) Custom_clear,
    .tp_members = Custom_members,
    .tp_methods = Custom_methods,
    .tp_getset = Custom_getsetters,
};

static PyModuleDef custommodule = {
    PyModuleDef_HEAD_INIT,
    .m_name = "custom4",
    .m_doc = "Example module that creates an extension type.",
    .m_size = -1,
};

PyMODINIT_FUNC
PyInit_custom4(void)
{
    PyObject *m;
    if (PyType_Ready(&CustomType) < 0)
        return NULL;

    m = PyModule_Create(&custommodule);
    if (m == NULL)
        return NULL;

    Py_INCREF(&CustomType);
    if (PyModule_AddObject(m, "Custom", (PyObject *) &CustomType) < 0) {
        Py_DECREF(&CustomType);
        Py_DECREF(m);
        return NULL;
    }

    return m;
}

First, the traversal method lets the cyclic GC know about subobjects that could participate in cycles:

static int
Custom_traverse(CustomObject *self, visitproc visit, void *arg)
{
    int vret;
    if (self->first) {
        vret = visit(self->first, arg);
        if (vret != 0)
            return vret;
    }
    if (self->last) {
        vret = visit(self->last, arg);
        if (vret != 0)
            return vret;
    }
    return 0;
}

For each subobject that can participate in cycles, we need to call the visit() function, which is passed to the traversal method. The visit() function takes as arguments the subobject and the extra argument arg passed to the traversal method. It returns an integer value that must be returned if it is non-zero.

Python provides a Py_VISIT() macro that automates calling visit functions. With Py_VISIT(), we can minimize the amount of boilerplate in Custom_traverse:

static int
Custom_traverse(CustomObject *self, visitproc visit, void *arg)
{
    Py_VISIT(self->first);
    Py_VISIT(self->last);
    return 0;
}

참고

The tp_traverse implementation must name its arguments exactly visit and arg in order to use Py_VISIT().

Second, we need to provide a method for clearing any subobjects that can participate in cycles:

static int
Custom_clear(CustomObject *self)
{
    Py_CLEAR(self->first);
    Py_CLEAR(self->last);
    return 0;
}

Notice the use of the Py_CLEAR() macro. It is the recommended and safe way to clear data attributes of arbitrary types while decrementing their reference counts. If you were to call Py_XDECREF() instead on the attribute before setting it to NULL, there is a possibility that the attribute’s destructor would call back into code that reads the attribute again (especially if there is a reference cycle).

참고

You could emulate Py_CLEAR() by writing:

PyObject *tmp;
tmp = self->first;
self->first = NULL;
Py_XDECREF(tmp);

Nevertheless, it is much easier and less error-prone to always use Py_CLEAR() when deleting an attribute. Don’t try to micro-optimize at the expense of robustness!

The deallocator Custom_dealloc may call arbitrary code when clearing attributes. It means the circular GC can be triggered inside the function. Since the GC assumes reference count is not zero, we need to untrack the object from the GC by calling PyObject_GC_UnTrack() before clearing members. Here is our reimplemented deallocator using PyObject_GC_UnTrack() and Custom_clear:

static void
Custom_dealloc(CustomObject *self)
{
    PyObject_GC_UnTrack(self);
    Custom_clear(self);
    Py_TYPE(self)->tp_free((PyObject *) self);
}

Finally, we add the Py_TPFLAGS_HAVE_GC flag to the class flags:

.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,

That’s pretty much it. If we had written custom tp_alloc or tp_free handlers, we’d need to modify them for cyclic garbage collection. Most extensions will use the versions automatically provided.

2.5. Subclassing other types

It is possible to create new extension types that are derived from existing types. It is easiest to inherit from the built in types, since an extension can easily use the PyTypeObject it needs. It can be difficult to share these PyTypeObject structures between extension modules.

In this example we will create a SubList type that inherits from the built-in list type. The new type will be completely compatible with regular lists, but will have an additional increment() method that increases an internal counter:

>>> import sublist
>>> s = sublist.SubList(range(3))
>>> s.extend(s)
>>> print(len(s))
6
>>> print(s.increment())
1
>>> print(s.increment())
2

#define PY_SSIZE_T_CLEAN
#include <Python.h>

typedef struct {
    PyListObject list;
    int state;
} SubListObject;

static PyObject *
SubList_increment(SubListObject *self, PyObject *unused)
{
    self->state++;
    return PyLong_FromLong(self->state);
}

static PyMethodDef SubList_methods[] = {
    {"increment", (PyCFunction) SubList_increment, METH_NOARGS,
     PyDoc_STR("increment state counter")},
    {NULL},
};

static int
SubList_init(SubListObject *self, PyObject *args, PyObject *kwds)
{
    if (PyList_Type.tp_init((PyObject *) self, args, kwds) < 0)
        return -1;
    self->state = 0;
    return 0;
}

static PyTypeObject SubListType = {
    PyVarObject_HEAD_INIT(NULL, 0)
    .tp_name = "sublist.SubList",
    .tp_doc = "SubList objects",
    .tp_basicsize = sizeof(SubListObject),
    .tp_itemsize = 0,
    .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
    .tp_init = (initproc) SubList_init,
    .tp_methods = SubList_methods,
};

static PyModuleDef sublistmodule = {
    PyModuleDef_HEAD_INIT,
    .m_name = "sublist",
    .m_doc = "Example module that creates an extension type.",
    .m_size = -1,
};

PyMODINIT_FUNC
PyInit_sublist(void)
{
    PyObject *m;
    SubListType.tp_base = &PyList_Type;
    if (PyType_Ready(&SubListType) < 0)
        return NULL;

    m = PyModule_Create(&sublistmodule);
    if (m == NULL)
        return NULL;

    Py_INCREF(&SubListType);
    if (PyModule_AddObject(m, "SubList", (PyObject *) &SubListType) < 0) {
        Py_DECREF(&SubListType);
        Py_DECREF(m);
        return NULL;
    }

    return m;
}

As you can see, the source code closely resembles the Custom examples in previous sections. We will break down the main differences between them.

typedef struct {
    PyListObject list;
    int state;
} SubListObject;

The primary difference for derived type objects is that the base type’s object structure must be the first value. The base type will already include the PyObject_HEAD() at the beginning of its structure.

When a Python object is a SubList instance, its PyObject * pointer can be safely cast to both PyListObject * and SubListObject *:

static int
SubList_init(SubListObject *self, PyObject *args, PyObject *kwds)
{
    if (PyList_Type.tp_init((PyObject *) self, args, kwds) < 0)
        return -1;
    self->state = 0;
    return 0;
}

We see above how to call through to the __init__ method of the base type.

This pattern is important when writing a type with custom tp_new and tp_dealloc members. The tp_new handler should not actually create the memory for the object with its tp_alloc, but let the base class handle it by calling its own tp_new.

The PyTypeObject struct supports a tp_base specifying the type’s concrete base class. Due to cross-platform compiler issues, you can’t fill that field directly with a reference to PyList_Type; it should be done later in the module initialization function:

PyMODINIT_FUNC
PyInit_sublist(void)
{
    PyObject* m;
    SubListType.tp_base = &PyList_Type;
    if (PyType_Ready(&SubListType) < 0)
        return NULL;

    m = PyModule_Create(&sublistmodule);
    if (m == NULL)
        return NULL;

    Py_INCREF(&SubListType);
    if (PyModule_AddObject(m, "SubList", (PyObject *) &SubListType) < 0) {
        Py_DECREF(&SubListType);
        Py_DECREF(m);
        return NULL;
    }

    return m;
}

Before calling PyType_Ready(), the type structure must have the tp_base slot filled in. When we are deriving an existing type, it is not necessary to fill out the tp_alloc slot with PyType_GenericNew() – the allocation function from the base type will be inherited.

After that, calling PyType_Ready() and adding the type object to the module is the same as with the basic Custom examples.

Footnotes

1

This is true when we know that the object is a basic type, like a string or a float.

2

We relied on this in the tp_dealloc handler in this example, because our type doesn’t support garbage collection.

3

We now know that the first and last members are strings, so perhaps we could be less careful about decrementing their reference counts, however, we accept instances of string subclasses. Even though deallocating normal strings won’t call back into our objects, we can’t guarantee that deallocating an instance of a string subclass won’t call back into our objects.

4

Also, even with our attributes restricted to strings instances, the user could pass arbitrary str subclasses and therefore still create reference cycles.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 인터프리터 확장 및 내장 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 인터프리터 확장 및 내장 »

|

3. Defining Extension Types: Assorted Topics

This section aims to give a quick fly-by on the various type methods you can implement and what they do.

Here is the definition of PyTypeObject, with some fields only used in debug builds omitted:

typedef struct _typeobject {
    PyObject_VAR_HEAD
    const char *tp_name; /* For printing, in format "<module>.<name>" */
    Py_ssize_t tp_basicsize, tp_itemsize; /* For allocation */

    /* Methods to implement standard operations */

    destructor tp_dealloc;
    printfunc tp_print;
    getattrfunc tp_getattr;
    setattrfunc tp_setattr;
    PyAsyncMethods *tp_as_async; /* formerly known as tp_compare (Python 2)
                                    or tp_reserved (Python 3) */
    reprfunc tp_repr;

    /* Method suites for standard classes */

    PyNumberMethods *tp_as_number;
    PySequenceMethods *tp_as_sequence;
    PyMappingMethods *tp_as_mapping;

    /* More standard operations (here for binary compatibility) */

    hashfunc tp_hash;
    ternaryfunc tp_call;
    reprfunc tp_str;
    getattrofunc tp_getattro;
    setattrofunc tp_setattro;

    /* Functions to access object as input/output buffer */
    PyBufferProcs *tp_as_buffer;

    /* Flags to define presence of optional/expanded features */
    unsigned long tp_flags;

    const char *tp_doc; /* Documentation string */

    /* call function for all accessible objects */
    traverseproc tp_traverse;

    /* delete references to contained objects */
    inquiry tp_clear;

    /* rich comparisons */
    richcmpfunc tp_richcompare;

    /* weak reference enabler */
    Py_ssize_t tp_weaklistoffset;

    /* Iterators */
    getiterfunc tp_iter;
    iternextfunc tp_iternext;

    /* Attribute descriptor and subclassing stuff */
    struct PyMethodDef *tp_methods;
    struct PyMemberDef *tp_members;
    struct PyGetSetDef *tp_getset;
    struct _typeobject *tp_base;
    PyObject *tp_dict;
    descrgetfunc tp_descr_get;
    descrsetfunc tp_descr_set;
    Py_ssize_t tp_dictoffset;
    initproc tp_init;
    allocfunc tp_alloc;
    newfunc tp_new;
    freefunc tp_free; /* Low-level free-memory routine */
    inquiry tp_is_gc; /* For PyObject_IS_GC */
    PyObject *tp_bases;
    PyObject *tp_mro; /* method resolution order */
    PyObject *tp_cache;
    PyObject *tp_subclasses;
    PyObject *tp_weaklist;
    destructor tp_del;

    /* Type attribute cache version tag. Added in version 2.6 */
    unsigned int tp_version_tag;

    destructor tp_finalize;

} PyTypeObject;

Now that’s a lot of methods. Don’t worry too much though – if you have a type you want to define, the chances are very good that you will only implement a handful of these.

As you probably expect by now, we’re going to go over this and give more information about the various handlers. We won’t go in the order they are defined in the structure, because there is a lot of historical baggage that impacts the ordering of the fields. It’s often easiest to find an example that includes the fields you need and then change the values to suit your new type.

const char *tp_name; /* For printing */

The name of the type – as mentioned in the previous chapter, this will appear in various places, almost entirely for diagnostic purposes. Try to choose something that will be helpful in such a situation!

Py_ssize_t tp_basicsize, tp_itemsize; /* For allocation */

These fields tell the runtime how much memory to allocate when new objects of this type are created. Python has some built-in support for variable length structures (think: strings, tuples) which is where the tp_itemsize field comes in. This will be dealt with later.

const char *tp_doc;

Here you can put a string (or its address) that you want returned when the Python script references obj.__doc__ to retrieve the doc string.

Now we come to the basic type methods – the ones most extension types will implement.

3.1. Finalization and De-allocation

destructor tp_dealloc;

This function is called when the reference count of the instance of your type is reduced to zero and the Python interpreter wants to reclaim it. If your type has memory to free or other clean-up to perform, you can put it here. The object itself needs to be freed here as well. Here is an example of this function:

static void
newdatatype_dealloc(newdatatypeobject *obj)
{
    free(obj->obj_UnderlyingDatatypePtr);
    Py_TYPE(obj)->tp_free(obj);
}

One important requirement of the deallocator function is that it leaves any pending exceptions alone. This is important since deallocators are frequently called as the interpreter unwinds the Python stack; when the stack is unwound due to an exception (rather than normal returns), nothing is done to protect the deallocators from seeing that an exception has already been set. Any actions which a deallocator performs which may cause additional Python code to be executed may detect that an exception has been set. This can lead to misleading errors from the interpreter. The proper way to protect against this is to save a pending exception before performing the unsafe action, and restoring it when done. This can be done using the PyErr_Fetch() and PyErr_Restore() functions:

static void
my_dealloc(PyObject *obj)
{
    MyObject *self = (MyObject *) obj;
    PyObject *cbresult;

    if (self->my_callback != NULL) {
        PyObject *err_type, *err_value, *err_traceback;

        /* This saves the current exception state */
        PyErr_Fetch(&err_type, &err_value, &err_traceback);

        cbresult = PyObject_CallObject(self->my_callback, NULL);
        if (cbresult == NULL)
            PyErr_WriteUnraisable(self->my_callback);
        else
            Py_DECREF(cbresult);

        /* This restores the saved exception state */
        PyErr_Restore(err_type, err_value, err_traceback);

        Py_DECREF(self->my_callback);
    }
    Py_TYPE(obj)->tp_free((PyObject*)self);
}

참고

There are limitations to what you can safely do in a deallocator function. First, if your type supports garbage collection (using tp_traverse and/or tp_clear), some of the object’s members can have been cleared or finalized by the time tp_dealloc is called. Second, in tp_dealloc, your object is in an unstable state: its reference count is equal to zero. Any call to a non-trivial object or API (as in the example above) might end up calling tp_dealloc again, causing a double free and a crash.

Starting with Python 3.4, it is recommended not to put any complex finalization code in tp_dealloc, and instead use the new tp_finalize type method.

더 보기

PEP 442 [https://www.python.org/dev/peps/pep-0442] explains the new finalization scheme.

3.2. Object Presentation

In Python, there are two ways to generate a textual representation of an object: the repr() function, and the str() function. (The print() function just calls str().) These handlers are both optional.

reprfunc tp_repr;
reprfunc tp_str;

The tp_repr handler should return a string object containing a representation of the instance for which it is called. Here is a simple example:

static PyObject *
newdatatype_repr(newdatatypeobject * obj)
{
    return PyUnicode_FromFormat("Repr-ified_newdatatype{{size:%d}}",
                                obj->obj_UnderlyingDatatypePtr->size);
}

If no tp_repr handler is specified, the interpreter will supply a representation that uses the type’s tp_name and a uniquely-identifying value for the object.

The tp_str handler is to str() what the tp_repr handler described above is to repr(); that is, it is called when Python code calls str() on an instance of your object. Its implementation is very similar to the tp_repr function, but the resulting string is intended for human consumption. If tp_str is not specified, the tp_repr handler is used instead.

Here is a simple example:

static PyObject *
newdatatype_str(newdatatypeobject * obj)
{
    return PyUnicode_FromFormat("Stringified_newdatatype{{size:%d}}",
                                obj->obj_UnderlyingDatatypePtr->size);
}

3.3. Attribute Management

For every object which can support attributes, the corresponding type must provide the functions that control how the attributes are resolved. There needs to be a function which can retrieve attributes (if any are defined), and another to set attributes (if setting attributes is allowed). Removing an attribute is a special case, for which the new value passed to the handler is NULL.

Python supports two pairs of attribute handlers; a type that supports attributes only needs to implement the functions for one pair. The difference is that one pair takes the name of the attribute as a char*, while the other accepts a PyObject*. Each type can use whichever pair makes more sense for the implementation’s convenience.

getattrfunc  tp_getattr;        /* char * version */
setattrfunc  tp_setattr;
/* ... */
getattrofunc tp_getattro;       /* PyObject * version */
setattrofunc tp_setattro;

If accessing attributes of an object is always a simple operation (this will be explained shortly), there are generic implementations which can be used to provide the PyObject* version of the attribute management functions. The actual need for type-specific attribute handlers almost completely disappeared starting with Python 2.2, though there are many examples which have not been updated to use some of the new generic mechanism that is available.

3.3.1. Generic Attribute Management

Most extension types only use simple attributes. So, what makes the attributes simple? There are only a couple of conditions that must be met:

The name of the attributes must be known when PyType_Ready() is called.

No special processing is needed to record that an attribute was looked up or set, nor do actions need to be taken based on the value.

Note that this list does not place any restrictions on the values of the attributes, when the values are computed, or how relevant data is stored.

When PyType_Ready() is called, it uses three tables referenced by the type object to create descriptors which are placed in the dictionary of the type object. Each descriptor controls access to one attribute of the instance object. Each of the tables is optional; if all three are NULL, instances of the type will only have attributes that are inherited from their base type, and should leave the tp_getattro and tp_setattro fields NULL as well, allowing the base type to handle attributes.

The tables are declared as three fields of the type object:

struct PyMethodDef *tp_methods;
struct PyMemberDef *tp_members;
struct PyGetSetDef *tp_getset;

If tp_methods is not NULL, it must refer to an array of PyMethodDef structures. Each entry in the table is an instance of this structure:

typedef struct PyMethodDef {
    const char  *ml_name;       /* method name */
    PyCFunction  ml_meth;       /* implementation function */
    int          ml_flags;      /* flags */
    const char  *ml_doc;        /* docstring */
} PyMethodDef;

One entry should be defined for each method provided by the type; no entries are needed for methods inherited from a base type. One additional entry is needed at the end; it is a sentinel that marks the end of the array. The ml_name field of the sentinel must be NULL.

The second table is used to define attributes which map directly to data stored in the instance. A variety of primitive C types are supported, and access may be read-only or read-write. The structures in the table are defined as:

typedef struct PyMemberDef {
    const char *name;
    int         type;
    int         offset;
    int         flags;
    const char *doc;
} PyMemberDef;

For each entry in the table, a descriptor will be constructed and added to the type which will be able to extract a value from the instance structure. The type field should contain one of the type codes defined in the structmember.h header; the value will be used to determine how to convert Python values to and from C values. The flags field is used to store flags which control how the attribute can be accessed.

The following flag constants are defined in structmember.h; they may be combined using bitwise-OR.

Constant

Meaning

READONLY

Never writable.

READ_RESTRICTED

Not readable in restricted mode.

WRITE_RESTRICTED

Not writable in restricted mode.

RESTRICTED

Not readable or writable in restricted mode.

An interesting advantage of using the tp_members table to build descriptors that are used at runtime is that any attribute defined this way can have an associated doc string simply by providing the text in the table. An application can use the introspection API to retrieve the descriptor from the class object, and get the doc string using its __doc__ attribute.

As with the tp_methods table, a sentinel entry with a name value of NULL is required.

3.3.2. Type-specific Attribute Management

For simplicity, only the char* version will be demonstrated here; the type of the name parameter is the only difference between the char* and PyObject* flavors of the interface. This example effectively does the same thing as the generic example above, but does not use the generic support added in Python 2.2. It explains how the handler functions are called, so that if you do need to extend their functionality, you’ll understand what needs to be done.

The tp_getattr handler is called when the object requires an attribute look-up. It is called in the same situations where the __getattr__() method of a class would be called.

Here is an example:

static PyObject *
newdatatype_getattr(newdatatypeobject *obj, char *name)
{
    if (strcmp(name, "data") == 0)
    {
        return PyLong_FromLong(obj->data);
    }

    PyErr_Format(PyExc_AttributeError,
                 "'%.50s' object has no attribute '%.400s'",
                 tp->tp_name, name);
    return NULL;
}

The tp_setattr handler is called when the __setattr__() or __delattr__() method of a class instance would be called. When an attribute should be deleted, the third parameter will be NULL. Here is an example that simply raises an exception; if this were really all you wanted, the tp_setattr handler should be set to NULL.

static int
newdatatype_setattr(newdatatypeobject *obj, char *name, PyObject *v)
{
    PyErr_Format(PyExc_RuntimeError, "Read-only attribute: %s", name);
    return -1;
}

3.4. Object Comparison

richcmpfunc tp_richcompare;

The tp_richcompare handler is called when comparisons are needed. It is analogous to the rich comparison methods, like __lt__(), and also called by PyObject_RichCompare() and PyObject_RichCompareBool().

This function is called with two Python objects and the operator as arguments, where the operator is one of Py_EQ, Py_NE, Py_LE, Py_GT, Py_LT or Py_GT. It should compare the two objects with respect to the specified operator and return Py_True or Py_False if the comparison is successful, Py_NotImplemented to indicate that comparison is not implemented and the other object’s comparison method should be tried, or NULL if an exception was set.

Here is a sample implementation, for a datatype that is considered equal if the size of an internal pointer is equal:

static PyObject *
newdatatype_richcmp(PyObject *obj1, PyObject *obj2, int op)
{
    PyObject *result;
    int c, size1, size2;

    /* code to make sure that both arguments are of type
       newdatatype omitted */

    size1 = obj1->obj_UnderlyingDatatypePtr->size;
    size2 = obj2->obj_UnderlyingDatatypePtr->size;

    switch (op) {
    case Py_LT: c = size1 <  size2; break;
    case Py_LE: c = size1 <= size2; break;
    case Py_EQ: c = size1 == size2; break;
    case Py_NE: c = size1 != size2; break;
    case Py_GT: c = size1 >  size2; break;
    case Py_GE: c = size1 >= size2; break;
    }
    result = c ? Py_True : Py_False;
    Py_INCREF(result);
    return result;
 }

3.5. Abstract Protocol Support

Python supports a variety of abstract ‘protocols;’ the specific interfaces provided to use these interfaces are documented in 추상 객체 계층.

A number of these abstract interfaces were defined early in the development of the Python implementation. In particular, the number, mapping, and sequence protocols have been part of Python since the beginning. Other protocols have been added over time. For protocols which depend on several handler routines from the type implementation, the older protocols have been defined as optional blocks of handlers referenced by the type object. For newer protocols there are additional slots in the main type object, with a flag bit being set to indicate that the slots are present and should be checked by the interpreter. (The flag bit does not indicate that the slot values are non-NULL. The flag may be set to indicate the presence of a slot, but a slot may still be unfilled.)

PyNumberMethods   *tp_as_number;
PySequenceMethods *tp_as_sequence;
PyMappingMethods  *tp_as_mapping;

If you wish your object to be able to act like a number, a sequence, or a mapping object, then you place the address of a structure that implements the C type PyNumberMethods, PySequenceMethods, or PyMappingMethods, respectively. It is up to you to fill in this structure with appropriate values. You can find examples of the use of each of these in the Objects directory of the Python source distribution.

hashfunc tp_hash;

This function, if you choose to provide it, should return a hash number for an instance of your data type. Here is a simple example:

static Py_hash_t
newdatatype_hash(newdatatypeobject *obj)
{
    Py_hash_t result;
    result = obj->some_size + 32767 * obj->some_number;
    if (result == -1)
       result = -2;
    return result;
}

Py_hash_t is a signed integer type with a platform-varying width. Returning -1 from tp_hash indicates an error, which is why you should be careful to avoid returning it when hash computation is successful, as seen above.

ternaryfunc tp_call;

This function is called when an instance of your data type is “called”, for example, if obj1 is an instance of your data type and the Python script contains obj1('hello'), the tp_call handler is invoked.

This function takes three arguments:

self is the instance of the data type which is the subject of the call. If the call is obj1('hello'), then self is obj1.

args is a tuple containing the arguments to the call. You can use PyArg_ParseTuple() to extract the arguments.

kwds is a dictionary of keyword arguments that were passed. If this is non-NULL and you support keyword arguments, use PyArg_ParseTupleAndKeywords() to extract the arguments. If you do not want to support keyword arguments and this is non-NULL, raise a TypeError with a message saying that keyword arguments are not supported.

Here is a toy tp_call implementation:

static PyObject *
newdatatype_call(newdatatypeobject *self, PyObject *args, PyObject *kwds)
{
    PyObject *result;
    const char *arg1;
    const char *arg2;
    const char *arg3;

    if (!PyArg_ParseTuple(args, "sss:call", &arg1, &arg2, &arg3)) {
        return NULL;
    }
    result = PyUnicode_FromFormat(
        "Returning -- value: [%d] arg1: [%s] arg2: [%s] arg3: [%s]\n",
        obj->obj_UnderlyingDatatypePtr->size,
        arg1, arg2, arg3);
    return result;
}

/* Iterators */
getiterfunc tp_iter;
iternextfunc tp_iternext;

These functions provide support for the iterator protocol. Both handlers take exactly one parameter, the instance for which they are being called, and return a new reference. In the case of an error, they should set an exception and return NULL. tp_iter corresponds to the Python __iter__() method, while tp_iternext corresponds to the Python __next__() method.

Any iterable object must implement the tp_iter handler, which must return an iterator object. Here the same guidelines apply as for Python classes:

For collections (such as lists and tuples) which can support multiple independent iterators, a new iterator should be created and returned by each call to tp_iter.

Objects which can only be iterated over once (usually due to side effects of iteration, such as file objects) can implement tp_iter by returning a new reference to themselves – and should also therefore implement the tp_iternext handler.

Any iterator object should implement both tp_iter and tp_iternext. An iterator’s tp_iter handler should return a new reference to the iterator. Its tp_iternext handler should return a new reference to the next object in the iteration, if there is one. If the iteration has reached the end, tp_iternext may return NULL without setting an exception, or it may set StopIteration in addition to returning NULL; avoiding the exception can yield slightly better performance. If an actual error occurs, tp_iternext should always set an exception and return NULL.

3.6. Weak Reference Support

One of the goals of Python’s weak reference implementation is to allow any type to participate in the weak reference mechanism without incurring the overhead on performance-critical objects (such as numbers).

더 보기

Documentation for the weakref module.

For an object to be weakly referencable, the extension type must do two things:

Include a PyObject* field in the C object structure dedicated to the weak reference mechanism. The object’s constructor should leave it NULL (which is automatic when using the default tp_alloc).

Set the tp_weaklistoffset type member to the offset of the aforementioned field in the C object structure, so that the interpreter knows how to access and modify that field.

Concretely, here is how a trivial object structure would be augmented with the required field:

typedef struct {
    PyObject_HEAD
    PyObject *weakreflist;  /* List of weak references */
} TrivialObject;

And the corresponding member in the statically-declared type object:

static PyTypeObject TrivialType = {
    PyVarObject_HEAD_INIT(NULL, 0)
    /* ... other members omitted for brevity ... */
    .tp_weaklistoffset = offsetof(TrivialObject, weakreflist),
};

The only further addition is that tp_dealloc needs to clear any weak references (by calling PyObject_ClearWeakRefs()) if the field is non-NULL:

static void
Trivial_dealloc(TrivialObject *self)
{
    /* Clear weakrefs first before calling any destructors */
    if (self->weakreflist != NULL)
        PyObject_ClearWeakRefs((PyObject *) self);
    /* ... remainder of destruction code omitted for brevity ... */
    Py_TYPE(self)->tp_free((PyObject *) self);
}

3.7. More Suggestions

In order to learn how to implement any specific method for your new data type, get the CPython source code. Go to the Objects directory, then search the C source files for tp_ plus the function you want (for example, tp_richcompare). You will find examples of the function you want to implement.

When you need to verify that an object is a concrete instance of the type you are implementing, use the PyObject_TypeCheck() function. A sample of its use might be something like the following:

if (!PyObject_TypeCheck(some_object, &MyType)) {
    PyErr_SetString(PyExc_TypeError, "arg #1 not a mything");
    return NULL;
}

더 보기

Download CPython source releases.

https://www.python.org/downloads/source/

The CPython project on GitHub, where the CPython source code is developed.

https://github.com/python/cpython

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 인터프리터 확장 및 내장 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 인터프리터 확장 및 내장 »

|

4. C와 C++ 확장 빌드하기

CPython의 C 확장은 초기화 함수를 내보내는 공유 라이브러리입니다 (예를 들어, 리눅스는 .so, 윈도우는 .pyd).

임포트 할 수 있으려면, 공유 라이브러리가 PYTHONPATH에 있어야 하며, 모듈 이름을 따라 적절한 확장자를 붙여서 이름 지어야 합니다. distutils를 사용하면, 올바른 파일 이름이 자동으로 생성됩니다.

초기화 함수는 다음과 같은 서명을 갖습니다:

PyObject* PyInit_modulename(void)

완전히 초기화된 모듈이나 PyModuleDef 인스턴스를 반환합니다. 자세한 내용은 Initializing C modules을 참조하십시오.

ASCII로만 이루어진 이름을 가진 모듈의 경우, 함수의 이름을 PyInit_<modulename>이어야 합니다. 여기서 <modulename>을 모듈의 이름으로 치환합니다. Multi-phase initialization를 사용할 때 ASCII가 아닌 모듈 이름이 허용됩니다. 이 경우, 초기화 함수 이름은 PyInitU_<modulename>이며 <modulename>은 파이썬의 punycode 인코딩으로 인코딩되고 하이픈을 밑줄로 대체합니다. 파이썬에서:

def initfunc_name(name):
    try:
        suffix = b'_' + name.encode('ascii')
    except UnicodeEncodeError:
        suffix = b'U_' + name.encode('punycode').replace(b'-', b'_')
    return b'PyInit' + suffix

여러 초기화 함수를 정의하여 단일 공유 라이브러리에서 여러 모듈을 내보낼 수 있습니다. 그러나, 이들을 임포트 하려면 심볼릭 링크나 사용자 정의 임포터를 사용해야 합니다. 기본적으로 파일 이름에 해당하는 함수만 발견되기 때문입니다. 자세한 내용은 PEP 489 [https://www.python.org/dev/peps/pep-0489]의 “한 라이브러리에 여러 모듈” 절을 참조하십시오.

4.1. distutils로 C와 C++ 확장 빌드하기

확장 모듈은 파이썬에 포함된 distutils를 사용하여 빌드할 수 있습니다. distutils가 바이너리 패키지의 생성을 지원하기 때문에, 사용자는 확장을 설치하기 위해 꼭 컴파일러와 distutils가 필요하지는 않습니다.

distutils 패키지에는 드라이버 스크립트인 setup.py가 들어 있습니다. 이것은 평범한 파이썬 파일인데, 대부분 간단한 경우에 이런 식입니다:

from distutils.core import setup, Extension

module1 = Extension('demo',
                    sources = ['demo.c'])

setup (name = 'PackageName',
       version = '1.0',
       description = 'This is a demo package',
       ext_modules = [module1])

이 setup.py와 파일 demo.c로 다음을 실행하면

python setup.py build

demo.c를 컴파일하고, build 디렉터리에 demo라는 확장 모듈을 생성합니다. 시스템에 따라, 모듈 파일은 build/lib.system 하위 디렉터리에 들어가고, demo.so나 demo.pyd와 같은 이름을 가질 수 있습니다.

setup.py에서, 모든 실행은 setup 함수를 호출하여 수행됩니다. 이것은 다양한 키워드 인자를 받아들입니다. 위의 예에서는 일부만 사용합니다. 구체적으로, 이 예는 패키지를 빌드하기 위한 메타 정보를 지정하고 패키지의 내용을 지정합니다. 일반적으로, 패키지는 파이썬 소스 모듈, 문서, 서브 패키지 등과 같은 추가 모듈이 포함됩니다. distutils의 기능에 대한 자세한 내용은 파이썬 모듈 배포 (레거시 버전)의 distutils 설명서를 참조하십시오; 이 절에서는 확장 모듈을 빌드하는 것만 설명합니다.

드라이버 스크립트를 더 잘 구조화하기 위해, setup()에 대한 인자를 미리 계산하는 것이 일반적입니다. 위의 예에서, setup()에 대한 ext_modules 인자는 확장 모듈의 리스트며, 각 모듈은 Extension의 인스턴스입니다. 이 예에서, 인스턴스는 단일 소스 파일 demo.c를 컴파일하여 빌드하는 demo라는 확장을 정의합니다.

많은 경우, 확장을 빌드하는 것은 더 복잡합니다. 왜냐하면, 추가적인 전처리기 정의와 라이브러리가 필요할 수 있기 때문입니다. 이는 아래에서 예시합니다.

from distutils.core import setup, Extension

module1 = Extension('demo',
                    define_macros = [('MAJOR_VERSION', '1'),
                                     ('MINOR_VERSION', '0')],
                    include_dirs = ['/usr/local/include'],
                    libraries = ['tcl83'],
                    library_dirs = ['/usr/local/lib'],
                    sources = ['demo.c'])

setup (name = 'PackageName',
       version = '1.0',
       description = 'This is a demo package',
       author = 'Martin v. Loewis',
       author_email = 'martin@v.loewis.de',
       url = 'https://docs.python.org/extending/building',
       long_description = '''
This is really just a demo package.
''',
       ext_modules = [module1])

이 예에서, setup()는 추가 메타 정보로 호출되며, 배포 패키지를 빌드해야 할 때 권장됩니다. 확장 자체에 대해서는, 전처리기 정의, 인클루드 디렉터리, 라이브러리 디렉터리 및 라이브러리를 지정합니다. 컴파일러에 따라, distutils는 이 정보를 다양한 방법으로 컴파일러에 전달합니다. 예를 들어, 유닉스에서는 다음과 같은 컴파일 명령으로 이어질 수 있습니다

gcc -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -fPIC -DMAJOR_VERSION=1 -DMINOR_VERSION=0 -I/usr/local/include -I/usr/local/include/python2.2 -c demo.c -o build/temp.linux-i686-2.2/demo.o

gcc -shared build/temp.linux-i686-2.2/demo.o -L/usr/local/lib -ltcl83 -o build/lib.linux-i686-2.2/demo.so

이 줄은 예시 목적일 뿐입니다; distutils 사용자는 distutils가 올바르게 호출한다고 믿어야 합니다.

4.2. 확장 모듈 배포하기

확장이 성공적으로 빌드되면, 이를 사용하는 세 가지 방법이 있습니다.

최종 사용자는 보통 모듈을 설치하고 싶을 것이고, 다음을 실행합니다

python setup.py install

모듈 관리자는 소스 패키지를 생성해야 합니다; 그러려면, 이렇게 실행합니다

python setup.py sdist

때에 따라, 추가 파일을 소스 배포에 포함해야 합니다; 이 작업은 MANIFEST.in 파일을 통해 수행됩니다; 자세한 내용은 Specifying the files to distribute를 참조하십시오.

소스 배포가 성공적으로 빌드되면, 관리자는 바이너리 배포도 만들 수 있습니다. 플랫폼에 따라, 이를 위해 다음 명령 중 하나를 사용할 수 있습니다.

python setup.py bdist_wininst
python setup.py bdist_rpm
python setup.py bdist_dumb

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 인터프리터 확장 및 내장 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 인터프리터 확장 및 내장 »

|

5. 윈도우에서 C와 C++ 확장 빌드하기

이 장에서는 Microsoft Visual C++를 사용하여 파이썬 용 윈도우 확장 모듈을 만드는 방법을 간략히 설명하고, 이 확장 모듈의 작동 방식에 대한 보다 자세한 배경 정보를 제공합니다. 설명 자료는 파이썬 확장을 빌드하는 법을 배우는 윈도우 프로그래머와 유닉스와 윈도우 모두에서 성공적으로 빌드 할 수 있는 소프트웨어 제작에 관심이 있는 유닉스 프로그래머 모두에게 유용합니다.

모듈 저자는 확장 모듈을 빌드하는데 이 섹션에서 설명하는 것 대신 distutils 접근 방식을 사용하는 것이 좋습니다. 파이썬을 빌드하는 데 사용된 C 컴파일러가 여전히 필요합니다; 보통 Microsoft Visual C++입니다.

참고

이 장에서는 인코딩된 파이썬 버전 번호를 포함하는 여러 파일 이름을 언급합니다. 이 파일 이름은 XY로 나타낸 버전 번호로 표시됩니다; 실제로, 'X'는 주(major) 버전 번호이고 'Y'는 여러분이 작업 중인 파이썬 배포의 부(minor) 버전 번호입니다. 예를 들어, 파이썬 2.2.1을 사용하면, XY는 실제로는 22가 됩니다.

5.1. 요리책 접근법

유닉스에서처럼, 윈도우에서 확장 모듈을 빌드하는 두 가지 접근법이 있습니다: distutils 패키지를 사용하여 빌드 프로세스를 제어하거나 수동으로 작업합니다. distutils 접근법은 대부분 확장에서 잘 작동합니다; distutils를 사용하여 확장 모듈을 빌드하고 패키징하는 방법에 대한 설명은 파이썬 모듈 배포 (레거시 버전)에 있습니다. 수동으로 작업할 수밖에 없다면, winsound [https://github.com/python/cpython/tree/3.7/PCbuild/winsound.vcxproj] 표준 라이브러리 모듈의 프로젝트 파일을 연구하는 것이 도움이 될 겁니다.

5.2. 유닉스와 윈도우의 차이점

유닉스와 윈도우는 코드의 실행시간 로딩에 완전히 다른 패러다임을 사용합니다. 동적으로 로드 할 수 있는 모듈을 빌드하려고 시도하기 전에, 시스템 작동 방식을 알고 있어야 합니다.

유닉스에서, 공유 오브젝트 (.so) 파일은 프로그램에서 사용할 코드와 프로그램에서 찾을 것으로 예상되는 함수와 데이터의 이름을 포함합니다. 파일이 프로그램에 결합할 때, 파일의 코드에 있는 함수와 데이터의 모든 참조가 함수와 데이터가 메모리에 놓이게 되는 프로그램에서의 실제 위치를 가리키도록 변경됩니다. 이것은 기본적으로 링크 작업입니다.

윈도우에서, 동적 연결 라이브러리 (.dll) 파일에는 매달린(dangling) 참조가 없습니다. 대신, 함수나 데이터에 대한 액세스는 참조 테이블(lookup table)을 통해 이루어집니다. 따라서 DLL 코드는 프로그램의 메모리를 참조하도록 실행 시간에 수정될 필요가 없습니다; 대신, 코드는 이미 DLL의 참조 테이블을 사용하고 있고, 실행 시간에 참조 테이블이 함수와 데이터를 가리 키도록 수정됩니다.

유닉스에는, 한가지 유형의 라이브러리 파일(.a) 만 있는데, 여러 오브젝트 파일(.o)의 코드가 포함됩니다. 공유 오브젝트 파일(.so)을 만들기 위한 링크 단계에서, 링커는 식별자가 정의된 위치를 알 수 없음을 발견할 수 있습니다. 링커는 라이브러리의 오브젝트 파일에서 그것들을 찾습니다. 발견하면, 그 오브젝트 파일의 모든 코드를 포함합니다.

윈도우에는, 두 가지 유형의 라이브러리, 정적 라이브러리와 임포트 라이브러리가 있습니다 (둘 다 .lib라고 합니다). 정적 라이브러리는 유닉스 .a 파일과 같습니다; 필요할 때 포함될 코드가 들어 있습니다. 임포트 라이브러리는 기본적으로 특정 식별자가 합법적이고 DLL이 로드될 때 프로그램에 존재하게 된다고 링커를 안심시키기 위해서만 사용됩니다. 따라서 링커는 임포트 라이브러리의 정보를 사용하여 DLL에 포함되지 않은 식별자를 사용하는 참조 테이블을 작성합니다. 응용 프로그램이나 DLL이 링크될 때, 임포트 라이브러리가 만들어질 수 있습니다. 이것은 응용 프로그램이나 DLL의 심볼을 사용하는, 이후의 모든 DLL에 사용해야 합니다.

다른 코드 블록 A를 공유해야 하는, 두 개의 동적 로드 모듈 B와 C를 빌드한다고 가정합니다. 유닉스에서는, B.so와 C.so에 대해 링커로 A.a를 전달하지 않습니다; 전달하면 B와 C가 각각 자신의 복사본을 갖게 되어 두 번 포함하게 됩니다. 윈도우에서는, A.dll를 빌드하면 A.lib도 빌드됩니다. 여러분은 B와 C에 대헤 링커로 A.lib를 전달 합니다. A.lib는 코드를 포함하지 않습니다; 실행 시간에 A의 코드에 액세스하는 데 사용될 정보만 포함합니다.

윈도우에서, 임포트 라이브러리를 사용하는 것은 import spam을 사용하는 것과 비슷합니다; 이것은 스팸의 이름에 액세스할 수 있도록 하지만, 별도의 복사본을 만들지는 않습니다. 유닉스에서, 라이브러리와 링크하는 것은 from spam import *와 더 비슷합니다; 별도의 복사본을 만듭니다.

5.3. DLL을 실제로 사용하기

윈도우 파이썬은 Microsoft Visual C++로 빌드되었습니다; 다른 컴파일러를 사용하는 것은 동작할 수도 있고 그렇지 않을 수도 있습니다 (볼랜드는 되는 것 같지만). 이 섹션의 나머지 부분은 MSVC++에만 해당합니다.

윈도우에서 DLL을 만들 때, pythonXY.lib를 링커에 전달해야 합니다. 두 개의 DLL, spam과 (spam에 있는 C 함수를 사용하는) ni를 빌드하려면, 다음 명령을 사용할 수 있습니다:

cl /LD /I/python/include spam.c ../libs/pythonXY.lib
cl /LD /I/python/include ni.c spam.lib ../libs/pythonXY.lib

첫 번째 명령은 세 개의 파일을 만들었습니다: spam.obj, spam.dll 및 spam.lib. Spam.dll은 파이썬 함수(가령 PyArg_ParseTuple())를 포함하지 않지만, pythonXY.lib 덕분에 파이썬 코드를 찾는 방법을 알고 있습니다.

두 번째 명령은 ni.dll(그리고 .obj와 .lib)을 만들었습니다. spam과 파이썬 실행 파일에서 필요한 함수를 찾는 방법을 알고 있습니다.

모든 식별자를 참조 테이블로 내보내지는 않습니다. 다른 모듈(파이썬 포함)이 식별자를 볼 수 있게 하려면, void _declspec(dllexport) initspam(void)나 PyObject _declspec(dllexport) *NiGetSpamData(void)처럼 _declspec(dllexport)라고 선언해야 합니다.

Developer Studio는 실제로 필요하지 않은 많은 임포트 라이브러리를 던져넣어서 실행 파일에 약 100K를 추가합니다. 이것들을 제거하려면, 프로젝트 설정 대화 상자를 통해 ignore default libraries를 지정하십시오. 올바른 msvcrtxx.lib를 라이브러리 목록에 추가하십시오.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 인터프리터 확장 및 내장 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 인터프리터 확장 및 내장 »

|

1. 다른 응용 프로그램에 파이썬 내장하기

이전 장에서는 파이썬을 확장하는 방법, 즉 C 함수의 라이브러리를 파이썬에 연결하여 파이썬의 기능을 확장하는 방법에 관해 설명했습니다. 다른 방법도 가능합니다: 파이썬을 내장시켜 C/C++ 응용 프로그램을 풍부하게 만들 수 있습니다. 내장은 C 나 C++가 아닌 파이썬으로 응용 프로그램의 일부 기능을 구현하는 능력을 응용 프로그램에 제공합니다. 이것은 여러 목적으로 사용될 수 있습니다; 한 가지 예는 사용자가 파이썬으로 스크립트를 작성하여 응용 프로그램을 필요에 맞게 조정할 수 있게 하는 것입니다. 일부 기능을 파이썬으로 작성하기가 더 쉽다면 직접 사용할 수도 있습니다.

파이썬을 내장하는 것은 파이썬을 확장하는 것과 유사합니다만, 아주 같지는 않습니다. 차이점은, 파이썬을 확장할 때 응용 프로그램의 주 프로그램은 여전히 파이썬 인터프리터입니다. 반면에 파이썬을 내장하면 주 프로그램은 파이썬과 아무 관련이 없습니다 — 대신 응용 프로그램 일부에서 간혹 파이썬 코드를 실행하기 위해 파이썬 인터프리터를 호출합니다.

그래서 파이썬을 내장한다면, 여러분은 자신의 메인 프로그램을 제공하게 됩니다. 이 메인 프로그램이해야 할 일 중 하나는 파이썬 인터프리터를 초기화하는 것입니다. 최소한, Py_Initialize() 함수를 호출해야 합니다. 파이썬에 명령 줄 인자를 전달하는 선택적 호출이 있습니다. 그런 다음 나중에 응용 프로그램의 어느 부분에서나 인터프리터를 호출할 수 있습니다.

인터프리터를 호출하는 방법에는 여러 가지가 있습니다: 파이썬 문장을 포함하는 문자열을 PyRun_SimpleString()에 전달하거나, stdio 파일 포인터와 파일명(에러 메시지에서의 식별만을 위해)을 PyRun_SimpleFile()에 전달할 수 있습니다. 또한, 이전 장에서 설명한 저수준의 연산을 호출하여 파이썬 객체를 만들고 사용할 수 있습니다.

더 보기

파이썬/C API 레퍼런스 설명서

파이썬의 C 인터페이스에 대한 자세한 내용은 이 매뉴얼에 있습니다. 필요한 정보가 많이 있습니다.

1.1. 매우 고수준의 내장

파이썬을 내장하는 가장 간단한 형태는 매우 고수준의 인터페이스를 사용하는 것입니다. 이 인터페이스는 응용 프로그램과 직접 상호 작용할 필요 없이 파이썬 스크립트를 실행하기 위한 것입니다. 이것은 예를 들어 파일에 대해 어떤 연산을 수행하는 데 사용될 수 있습니다.

#define PY_SSIZE_T_CLEAN
#include <Python.h>

int
main(int argc, char *argv[])
{
    wchar_t *program = Py_DecodeLocale(argv[0], NULL);
    if (program == NULL) {
        fprintf(stderr, "Fatal error: cannot decode argv[0]\n");
        exit(1);
    }
    Py_SetProgramName(program);  /* optional but recommended */
    Py_Initialize();
    PyRun_SimpleString("from time import time,ctime\n"
                       "print('Today is', ctime(time()))\n");
    if (Py_FinalizeEx() < 0) {
        exit(120);
    }
    PyMem_RawFree(program);
    return 0;
}

Py_SetProgramName() 함수는 파이썬 런타임 라이브러리에 대한 경로를 인터프리터에게 알리기 위해 Py_Initialize()보다 먼저 호출되어야 합니다. 다음으로, 파이썬 인터프리터는 Py_Initialize()로 초기화되고, 날짜와 시간을 인쇄하는 하드 코딩된 파이썬 스크립트가 실행됩니다. 그런 다음, Py_FinalizeEx() 호출이 인터프리터를 종료하고 프로그램이 끝납니다. 실제 프로그램에서는 파이썬 스크립트를 다른 소스(아마도 텍스트 편집기 루틴, 파일 또는 데이터베이스)에서 가져올 수 있습니다. 파일에서 파이썬 코드를 얻는 것은 PyRun_SimpleFile() 함수를 사용하면 더 잘할 수 있는데, 메모리 공간을 할당하고 파일 내용을 로드하는 번거로움을 덜어줍니다.

1.2. 매우 고수준 내장을 넘어서: 개요

고수준 인터페이스는 응용 프로그램에서 임의의 파이썬 코드를 실행할 수 있는 능력을 제공하지만, 최소한 데이터 값을 교환하는 것이 꽤 번거롭습니다. 그러길 원한다면 저수준의 호출을 사용해야 합니다. 더 많은 C 코드를 작성해야 하는 대신, 거의 모든 것을 달성할 수 있습니다.

파이썬을 확장하는 것과 파이썬을 내장하는 것은 다른 의도에도 불구하고 꽤 똑같은 활동이라는 점에 유의해야 합니다. 이전 장에서 논의된 대부분 주제는 여전히 유효합니다. 이것을 보시려면, 파이썬에서 C로의 확장 코드가 실제로 하는 일을 생각해보십시오:

데이터값을 파이썬에서 C로 변환하고,

변환된 값을 사용하여 C 루틴으로 함수 호출을 수행하고,

그 호출에서 얻은 데이터값을 C에서 파이썬으로 변환합니다.

파이썬을 내장할 때, 인터페이스 코드는 다음을 수행합니다:

데이터값을 C에서 파이썬으로 변환하고,

변환된 값을 사용하여 파이썬 인터페이스 루틴으로 함수 호출을 수행하고,

그 호출에서 얻은 데이터 값을 파이썬에서 C로 변환합니다.

보시다시피, 데이터 변환 단계가 언어 간 전송의 다른 방향을 수용하기 위해 단순히 교환됩니다. 유일한 차이점은 두 데이터 변환 간에 호출하는 루틴입니다. 확장할 때는 C 루틴을 호출하고, 내장할 때는 파이썬 루틴을 호출합니다.

이 장에서는 파이썬에서 C로 데이터를 변환하는 방법과 그 반대로 데이터를 변환하는 방법에 관해서는 설명하지 않습니다. 또한, 참조의 올바른 사용과 에러를 다루는 것을 이해하고 있다고 가정합니다. 이러한 측면은 인터프리터를 확장하는 것과 다르지 않으므로, 이전 장에서 필요한 정보를 참조할 수 있습니다.

1.3. 순수한 내장

첫 번째 프로그램은 파이썬 스크립트에 있는 함수를 실행하는 것을 목표로 합니다. 매우 고수준의 인터페이스에 관한 절에서와같이, 파이썬 인터프리터는 애플리케이션과 직접 상호 작용하지 않습니다 (하지만 다음 절에서 바뀔 것입니다).

파이썬 스크립트에서 정의된 함수를 실행하는 코드는 다음과 같습니다:

#define PY_SSIZE_T_CLEAN
#include <Python.h>

int
main(int argc, char *argv[])
{
    PyObject *pName, *pModule, *pFunc;
    PyObject *pArgs, *pValue;
    int i;

    if (argc < 3) {
        fprintf(stderr,"Usage: call pythonfile funcname [args]\n");
        return 1;
    }

    Py_Initialize();
    pName = PyUnicode_DecodeFSDefault(argv[1]);
    /* Error checking of pName left out */

    pModule = PyImport_Import(pName);
    Py_DECREF(pName);

    if (pModule != NULL) {
        pFunc = PyObject_GetAttrString(pModule, argv[2]);
        /* pFunc is a new reference */

        if (pFunc && PyCallable_Check(pFunc)) {
            pArgs = PyTuple_New(argc - 3);
            for (i = 0; i < argc - 3; ++i) {
                pValue = PyLong_FromLong(atoi(argv[i + 3]));
                if (!pValue) {
                    Py_DECREF(pArgs);
                    Py_DECREF(pModule);
                    fprintf(stderr, "Cannot convert argument\n");
                    return 1;
                }
                /* pValue reference stolen here: */
                PyTuple_SetItem(pArgs, i, pValue);
            }
            pValue = PyObject_CallObject(pFunc, pArgs);
            Py_DECREF(pArgs);
            if (pValue != NULL) {
                printf("Result of call: %ld\n", PyLong_AsLong(pValue));
                Py_DECREF(pValue);
            }
            else {
                Py_DECREF(pFunc);
                Py_DECREF(pModule);
                PyErr_Print();
                fprintf(stderr,"Call failed\n");
                return 1;
            }
        }
        else {
            if (PyErr_Occurred())
                PyErr_Print();
            fprintf(stderr, "Cannot find function \"%s\"\n", argv[2]);
        }
        Py_XDECREF(pFunc);
        Py_DECREF(pModule);
    }
    else {
        PyErr_Print();
        fprintf(stderr, "Failed to load \"%s\"\n", argv[1]);
        return 1;
    }
    if (Py_FinalizeEx() < 0) {
        return 120;
    }
    return 0;
}

이 코드는 argv[1]를 사용하여 파이썬 스크립트를 로드하고, argv[2]에서 명명된 함수를 호출합니다. 정수 인자는 argv 배열의 남은 값들입니다. 이 프로그램을 컴파일하고 링크하면 (완성된 실행 파일을 call이라고 부릅시다), 다음과 같은 파이썬 스크립트를 실행하는 데 사용합니다:

def multiply(a,b):
    print("Will compute", a, "times", b)
    c = 0
    for i in range(0, a):
        c = c + b
    return c

그러면 결과는 다음과 같아야 합니다:

$ call multiply multiply 3 2
Will compute 3 times 2
Result of call: 6

프로그램이 기능보다 상당히 큰 편이지만, 대부분 코드는 파이썬과 C 사이의 데이터 변환과 에러 보고를 위한 것입니다. 파이썬 내장과 관련된 흥미로운 부분은 다음처럼 시작합니다

Py_Initialize();
pName = PyUnicode_DecodeFSDefault(argv[1]);
/* Error checking of pName left out */
pModule = PyImport_Import(pName);

인터프리터를 초기화한 후, 스크립트는 PyImport_Import()를 사용하여 로드됩니다. 이 루틴은 인자로 파이썬 문자열을 요구하는데, PyUnicode_FromString() 데이터 변환 루틴을 사용하여 구성됩니다.

pFunc = PyObject_GetAttrString(pModule, argv[2]);
/* pFunc is a new reference */

if (pFunc && PyCallable_Check(pFunc)) {
    ...
}
Py_XDECREF(pFunc);

일단 스크립트가 로드되면, 우리가 찾고 있는 이름이 PyObject_GetAttrString()를 사용하여 검색됩니다. 이름이 존재하고, 반환된 객체가 콜러블이면, 그것이 함수라고 안전하게 가정할 수 있습니다. 그런 다음 프로그램은 인자의 튜플을 일반적인 방법으로 구성하여 진행합니다. 그런 다음 파이썬 함수 호출은 이렇게 이루어집니다:

pValue = PyObject_CallObject(pFunc, pArgs);

Upon return of the function, pValue is either NULL or it contains a reference to the return value of the function. Be sure to release the reference after examining the value.

1.4. 내장된 파이썬을 확장하기

지금까지 내장된 파이썬 인터프리터는 애플리케이션 자체의 기능에 액세스할 수 없었습니다. 파이썬 API는 내장된 인터프리터를 확장함으로써 이것을 허용합니다. 즉, 내장된 인터프리터는 응용 프로그램에서 제공하는 루틴으로 확장됩니다. 복잡하게 들리지만, 그렇게 나쁘지는 않습니다. 잠시 응용 프로그램이 파이썬 인터프리터를 시작한다는 것을 잊어버리십시오. 대신, 응용 프로그램을 서브 루틴의 집합으로 간주하고, 일반 파이썬 확장을 작성하는 것처럼 파이썬에서 해당 루틴에 액세스할 수 있도록 연결 코드를 작성하십시오. 예를 들면:

static int numargs=0;

/* Return the number of arguments of the application command line */
static PyObject*
emb_numargs(PyObject *self, PyObject *args)
{
    if(!PyArg_ParseTuple(args, ":numargs"))
        return NULL;
    return PyLong_FromLong(numargs);
}

static PyMethodDef EmbMethods[] = {
    {"numargs", emb_numargs, METH_VARARGS,
     "Return the number of arguments received by the process."},
    {NULL, NULL, 0, NULL}
};

static PyModuleDef EmbModule = {
    PyModuleDef_HEAD_INIT, "emb", NULL, -1, EmbMethods,
    NULL, NULL, NULL, NULL
};

static PyObject*
PyInit_emb(void)
{
    return PyModule_Create(&EmbModule);
}

위의 코드를 main() 함수 바로 위에 삽입하십시오. 또한, Py_Initialize()에 대한 호출 전에 다음 두 문장을 삽입하십시오:

numargs = argc;
PyImport_AppendInittab("emb", &PyInit_emb);

이 두 줄은 numargs 변수를 초기화하고, emb.numargs() 함수를 내장된 파이썬 인터프리터가 액세스할 수 있도록 만듭니다. 이러한 확장을 통해, 파이썬 스크립트는 다음과 같은 작업을 수행할 수 있습니다

import emb
print("Number of arguments", emb.numargs())

실제 응용 프로그램에서, 이 방법은 응용 프로그램의 API를 파이썬에 노출합니다.

1.5. C++로 파이썬 내장하기

파이썬을 C++ 프로그램에 내장하는 것도 가능합니다; 이것이 어떻게 수행되는지는 사용된 C++ 시스템의 세부 사항에 달려 있습니다; 일반적으로 C++로 메인 프로그램을 작성하고, C++ 컴파일러를 사용하여 프로그램을 컴파일하고 링크해야 합니다. C++을 사용하여 파이썬 자체를 다시 컴파일할 필요는 없습니다.

1.6. 유닉스 계열 시스템에서 컴파일과 링크하기

파이썬 인터프리터를 응용 프로그램에 내장하기 위해 컴파일러(와 링커)에 적절한 플래그를 찾는 것이 늘 간단하지는 않습니다. 특히, 특히 파이썬이 자신에게 링크된 C 동적 확장(.so 파일)으로 구현된 라이브러리 모듈을 로드해야 하기 때문입니다.

필요한 컴파일러와 링커 플래그를 찾으려면, 설치 절차의 일부로 생성된 pythonX.Y-config 스크립트를 실행할 수 있습니다 (python3-config 스크립트도 사용 가능할 수 있습니다). 이 스크립트에는 여러 옵션이 있으며, 다음과 같은 것들은 여러분에 직접 유용할 것입니다:

pythonX.Y-config --cflags는 컴파일 할 때의 권장 플래그를 제공합니다:

$ /opt/bin/python3.4-config --cflags
-I/opt/include/python3.4m -I/opt/include/python3.4m -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes

pythonX.Y-config --ldflags는 링크 할 때의 권장 플래그를 제공합니다:

$ /opt/bin/python3.4-config --ldflags
-L/opt/lib/python3.4/config-3.4m -lpthread -ldl -lutil -lm -lpython3.4m -Xlinker -export-dynamic

참고

여러 파이썬 설치 간의 (특히 시스템 파이썬과 여러분이 직접 컴파일한 파이썬 간의) 혼란을 피하려면, 위의 예와 같이 pythonX.Y-config의 절대 경로를 사용하는 것이 좋습니다.

이 절차가 여러분을 위해 작동하지 않는다면 (모든 유닉스 계열 플랫폼에서 작동하는 것은 보장되지 않습니다; 하지만, 버그 보고를 환영합니다), 동적 링크에 관한 시스템의 설명서를 읽는 것과/이나 파이썬의 Makefile과 (그 위치를 찾으려면 sysconfig.get_makefile_filename()를 사용하십시오) 컴파일 옵션을 검사해야 합니다. 이때, sysconfig 모듈은 여러분이 결합하려는 구성 값을 프로그래밍 방식으로 추출하는 데 유용한 도구입니다. 예를 들어:

>>> import sysconfig
>>> sysconfig.get_config_var('LIBS')
'-lpthread -ldl  -lutil'
>>> sysconfig.get_config_var('LINKFORSHARED')
'-Xlinker -export-dynamic'

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 인터프리터 확장 및 내장 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

|

파이썬/C API 레퍼런스 설명서

이 설명서는 확장 모듈을 작성하거나 파이썬을 내장하고자 하는 C와 C++ 프로그래머가 사용하는 API에 관해 설명합니다. 이 설명서와 쌍을 이루는 파이썬 인터프리터 확장 및 내장 는 확장 제작의 일반 원칙을 설명하지만, API 함수를 자세하게 설명하지는 않습니다.

Introduction

Coding standards

Include Files

Useful macros

Objects, Types and Reference Counts

Exceptions

Embedding Python

Debugging Builds

안정적인 응용 프로그램 바이너리 인터페이스

The Very High Level Layer

참조 횟수

Exception Handling

Printing and clearing

Raising exceptions

Issuing warnings

Querying the error indicator

Signal Handling

Exception Classes

Exception Objects

Unicode Exception Objects

Recursion Control

Standard Exceptions

Standard Warning Categories

유틸리티

Operating System Utilities

System Functions

Process Control

모듈 임포트 하기

데이터 마샬링 지원

Parsing arguments and building values

문자열 변환과 포매팅

리플렉션

코덱 등록소와 지원 함수

추상 객체 계층

Object Protocol

숫자 프로토콜

시퀀스 프로토콜

매핑 프로토콜

이터레이터 프로토콜

버퍼 프로토콜

낡은 버퍼 프로토콜

구상 객체 계층

기본 객체

숫자 객체

시퀀스 객체

컨테이너 객체

함수 객체

기타 객체

Initialization, Finalization, and Threads

Before Python Initialization

Global configuration variables

Initializing and finalizing the interpreter

Process-wide parameters

Thread State and the Global Interpreter Lock

Sub-interpreter support

Asynchronous Notifications

Profiling and Tracing

Advanced Debugger Support

Thread Local Storage Support

Memory Management

Overview

Raw Memory Interface

Memory Interface

Object allocators

Default Memory Allocators

Customize Memory Allocators

The pymalloc allocator

tracemalloc C API

Examples

객체 구현 지원

힙에 객체 할당하기

Common Object Structures

Type Objects

Number Object Structures

Mapping Object Structures

Sequence Object Structures

Buffer Object Structures

Async Object Structures

순환 가비지 수집 지원

API와 ABI 버전 붙이기

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

|

Introduction

The Application Programmer’s Interface to Python gives C and C++ programmers access to the Python interpreter at a variety of levels. The API is equally usable from C++, but for brevity it is generally referred to as the Python/C API. There are two fundamentally different reasons for using the Python/C API. The first reason is to write extension modules for specific purposes; these are C modules that extend the Python interpreter. This is probably the most common use. The second reason is to use Python as a component in a larger application; this technique is generally referred to as embedding Python in an application.

Writing an extension module is a relatively well-understood process, where a “cookbook” approach works well. There are several tools that automate the process to some extent. While people have embedded Python in other applications since its early existence, the process of embedding Python is less straightforward than writing an extension.

Many API functions are useful independent of whether you’re embedding or extending Python; moreover, most applications that embed Python will need to provide a custom extension as well, so it’s probably a good idea to become familiar with writing an extension before attempting to embed Python in a real application.

Coding standards

If you’re writing C code for inclusion in CPython, you must follow the guidelines and standards defined in PEP 7 [https://www.python.org/dev/peps/pep-0007]. These guidelines apply regardless of the version of Python you are contributing to. Following these conventions is not necessary for your own third party extension modules, unless you eventually expect to contribute them to Python.

Include Files

All function, type and macro definitions needed to use the Python/C API are included in your code by the following line:

#define PY_SSIZE_T_CLEAN
#include <Python.h>

This implies inclusion of the following standard headers: <stdio.h>, <string.h>, <errno.h>, <limits.h>, <assert.h> and <stdlib.h> (if available).

참고

Since Python may define some pre-processor definitions which affect the standard headers on some systems, you must include Python.h before any standard headers are included.

It is recommended to always define PY_SSIZE_T_CLEAN before including Python.h. See Parsing arguments and building values for a description of this macro.

All user visible names defined by Python.h (except those defined by the included standard headers) have one of the prefixes Py or _Py. Names beginning with _Py are for internal use by the Python implementation and should not be used by extension writers. Structure member names do not have a reserved prefix.

참고

User code should never define names that begin with Py or _Py. This confuses the reader, and jeopardizes the portability of the user code to future Python versions, which may define additional names beginning with one of these prefixes.

The header files are typically installed with Python. On Unix, these are located in the directories prefix/include/pythonversion/ and exec_prefix/include/pythonversion/, where prefix and exec_prefix are defined by the corresponding parameters to Python’s configure script and version is '%d.%d' % sys.version_info[:2]. On Windows, the headers are installed in prefix/include, where prefix is the installation directory specified to the installer.

To include the headers, place both directories (if different) on your compiler’s search path for includes. Do not place the parent directories on the search path and then use #include <pythonX.Y/Python.h>; this will break on multi-platform builds since the platform independent headers under prefix include the platform specific headers from exec_prefix.

C++ users should note that although the API is defined entirely using C, the header files properly declare the entry points to be extern "C". As a result, there is no need to do anything special to use the API from C++.

Useful macros

Several useful macros are defined in the Python header files. Many are defined closer to where they are useful (e.g. Py_RETURN_NONE). Others of a more general utility are defined here. This is not necessarily a complete listing.

Py_UNREACHABLE()

Use this when you have a code path that you do not expect to be reached. For example, in the default: clause in a switch statement for which all possible values are covered in case statements. Use this in places where you might be tempted to put an assert(0) or abort() call.

버전 3.7에 추가.

Py_ABS(x)

Return the absolute value of x.

버전 3.3에 추가.

Py_MIN(x, y)

Return the minimum value between x and y.

버전 3.3에 추가.

Py_MAX(x, y)

Return the maximum value between x and y.

버전 3.3에 추가.

Py_STRINGIFY(x)

Convert x to a C string. E.g. Py_STRINGIFY(123) returns "123".

버전 3.4에 추가.

Py_MEMBER_SIZE(type, member)

Return the size of a structure (type) member in bytes.

버전 3.6에 추가.

Py_CHARMASK(c)

Argument must be a character or an integer in the range [-128, 127] or [0, 255]. This macro returns c cast to an unsigned char.

Py_GETENV(s)

Like getenv(s), but returns NULL if -E was passed on the command line (i.e. if Py_IgnoreEnvironmentFlag is set).

Py_UNUSED(arg)

Use this for unused arguments in a function definition to silence compiler warnings, e.g. PyObject* func(PyObject *Py_UNUSED(ignored)).

버전 3.4에 추가.

PyDoc_STRVAR(name, str)

Creates a variable with name name that can be used in docstrings. If Python is built without docstrings, the value will be empty.

Use PyDoc_STRVAR for docstrings to support building Python without docstrings, as specified in PEP 7 [https://www.python.org/dev/peps/pep-0007].

Example:

PyDoc_STRVAR(pop_doc, "Remove and return the rightmost element.");

static PyMethodDef deque_methods[] = {
    // ...
    {"pop", (PyCFunction)deque_pop, METH_NOARGS, pop_doc},
    // ...
}

PyDoc_STR(str)

Creates a docstring for the given input string or an empty string if docstrings are disabled.

Use PyDoc_STR in specifying docstrings to support building Python without docstrings, as specified in PEP 7 [https://www.python.org/dev/peps/pep-0007].

Example:

static PyMethodDef pysqlite_row_methods[] = {
    {"keys", (PyCFunction)pysqlite_row_keys, METH_NOARGS,
        PyDoc_STR("Returns the keys of the row.")},
    {NULL, NULL}
};

Objects, Types and Reference Counts

Most Python/C API functions have one or more arguments as well as a return value of type PyObject*. This type is a pointer to an opaque data type representing an arbitrary Python object. Since all Python object types are treated the same way by the Python language in most situations (e.g., assignments, scope rules, and argument passing), it is only fitting that they should be represented by a single C type. Almost all Python objects live on the heap: you never declare an automatic or static variable of type PyObject, only pointer variables of type PyObject* can be declared. The sole exception are the type objects; since these must never be deallocated, they are typically static PyTypeObject objects.

All Python objects (even Python integers) have a type and a reference count. An object’s type determines what kind of object it is (e.g., an integer, a list, or a user-defined function; there are many more as explained in 표준형 계층). For each of the well-known types there is a macro to check whether an object is of that type; for instance, PyList_Check(a) is true if (and only if) the object pointed to by a is a Python list.

Reference Counts

The reference count is important because today’s computers have a finite (and often severely limited) memory size; it counts how many different places there are that have a reference to an object. Such a place could be another object, or a global (or static) C variable, or a local variable in some C function. When an object’s reference count becomes zero, the object is deallocated. If it contains references to other objects, their reference count is decremented. Those other objects may be deallocated in turn, if this decrement makes their reference count become zero, and so on. (There’s an obvious problem with objects that reference each other here; for now, the solution is “don’t do that.”)

Reference counts are always manipulated explicitly. The normal way is to use the macro Py_INCREF() to increment an object’s reference count by one, and Py_DECREF() to decrement it by one. The Py_DECREF() macro is considerably more complex than the incref one, since it must check whether the reference count becomes zero and then cause the object’s deallocator to be called. The deallocator is a function pointer contained in the object’s type structure. The type-specific deallocator takes care of decrementing the reference counts for other objects contained in the object if this is a compound object type, such as a list, as well as performing any additional finalization that’s needed. There’s no chance that the reference count can overflow; at least as many bits are used to hold the reference count as there are distinct memory locations in virtual memory (assuming sizeof(Py_ssize_t) >= sizeof(void*)). Thus, the reference count increment is a simple operation.

It is not necessary to increment an object’s reference count for every local variable that contains a pointer to an object. In theory, the object’s reference count goes up by one when the variable is made to point to it and it goes down by one when the variable goes out of scope. However, these two cancel each other out, so at the end the reference count hasn’t changed. The only real reason to use the reference count is to prevent the object from being deallocated as long as our variable is pointing to it. If we know that there is at least one other reference to the object that lives at least as long as our variable, there is no need to increment the reference count temporarily. An important situation where this arises is in objects that are passed as arguments to C functions in an extension module that are called from Python; the call mechanism guarantees to hold a reference to every argument for the duration of the call.

However, a common pitfall is to extract an object from a list and hold on to it for a while without incrementing its reference count. Some other operation might conceivably remove the object from the list, decrementing its reference count and possible deallocating it. The real danger is that innocent-looking operations may invoke arbitrary Python code which could do this; there is a code path which allows control to flow back to the user from a Py_DECREF(), so almost any operation is potentially dangerous.

A safe approach is to always use the generic operations (functions whose name begins with PyObject_, PyNumber_, PySequence_ or PyMapping_). These operations always increment the reference count of the object they return. This leaves the caller with the responsibility to call Py_DECREF() when they are done with the result; this soon becomes second nature.

Reference Count Details

The reference count behavior of functions in the Python/C API is best explained in terms of ownership of references. Ownership pertains to references, never to objects (objects are not owned: they are always shared). “Owning a reference” means being responsible for calling Py_DECREF on it when the reference is no longer needed. Ownership can also be transferred, meaning that the code that receives ownership of the reference then becomes responsible for eventually decref’ing it by calling Py_DECREF() or Py_XDECREF() when it’s no longer needed—or passing on this responsibility (usually to its caller). When a function passes ownership of a reference on to its caller, the caller is said to receive a new reference. When no ownership is transferred, the caller is said to borrow the reference. Nothing needs to be done for a borrowed reference.

Conversely, when a calling function passes in a reference to an object, there are two possibilities: the function steals a reference to the object, or it does not. Stealing a reference means that when you pass a reference to a function, that function assumes that it now owns that reference, and you are not responsible for it any longer.

Few functions steal references; the two notable exceptions are PyList_SetItem() and PyTuple_SetItem(), which steal a reference to the item (but not to the tuple or list into which the item is put!). These functions were designed to steal a reference because of a common idiom for populating a tuple or list with newly created objects; for example, the code to create the tuple (1, 2, "three") could look like this (forgetting about error handling for the moment; a better way to code this is shown below):

PyObject *t;

t = PyTuple_New(3);
PyTuple_SetItem(t, 0, PyLong_FromLong(1L));
PyTuple_SetItem(t, 1, PyLong_FromLong(2L));
PyTuple_SetItem(t, 2, PyUnicode_FromString("three"));

Here, PyLong_FromLong() returns a new reference which is immediately stolen by PyTuple_SetItem(). When you want to keep using an object although the reference to it will be stolen, use Py_INCREF() to grab another reference before calling the reference-stealing function.

Incidentally, PyTuple_SetItem() is the only way to set tuple items; PySequence_SetItem() and PyObject_SetItem() refuse to do this since tuples are an immutable data type. You should only use PyTuple_SetItem() for tuples that you are creating yourself.

Equivalent code for populating a list can be written using PyList_New() and PyList_SetItem().

However, in practice, you will rarely use these ways of creating and populating a tuple or list. There’s a generic function, Py_BuildValue(), that can create most common objects from C values, directed by a format string. For example, the above two blocks of code could be replaced by the following (which also takes care of the error checking):

PyObject *tuple, *list;

tuple = Py_BuildValue("(iis)", 1, 2, "three");
list = Py_BuildValue("[iis]", 1, 2, "three");

It is much more common to use PyObject_SetItem() and friends with items whose references you are only borrowing, like arguments that were passed in to the function you are writing. In that case, their behaviour regarding reference counts is much saner, since you don’t have to increment a reference count so you can give a reference away (“have it be stolen”). For example, this function sets all items of a list (actually, any mutable sequence) to a given item:

int
set_all(PyObject *target, PyObject *item)
{
    Py_ssize_t i, n;

    n = PyObject_Length(target);
    if (n < 0)
        return -1;
    for (i = 0; i < n; i++) {
        PyObject *index = PyLong_FromSsize_t(i);
        if (!index)
            return -1;
        if (PyObject_SetItem(target, index, item) < 0) {
            Py_DECREF(index);
            return -1;
        }
        Py_DECREF(index);
    }
    return 0;
}

The situation is slightly different for function return values. While passing a reference to most functions does not change your ownership responsibilities for that reference, many functions that return a reference to an object give you ownership of the reference. The reason is simple: in many cases, the returned object is created on the fly, and the reference you get is the only reference to the object. Therefore, the generic functions that return object references, like PyObject_GetItem() and PySequence_GetItem(), always return a new reference (the caller becomes the owner of the reference).

It is important to realize that whether you own a reference returned by a function depends on which function you call only — the plumage (the type of the object passed as an argument to the function) doesn’t enter into it! Thus, if you extract an item from a list using PyList_GetItem(), you don’t own the reference — but if you obtain the same item from the same list using PySequence_GetItem() (which happens to take exactly the same arguments), you do own a reference to the returned object.

Here is an example of how you could write a function that computes the sum of the items in a list of integers; once using PyList_GetItem(), and once using PySequence_GetItem().

long
sum_list(PyObject *list)
{
    Py_ssize_t i, n;
    long total = 0, value;
    PyObject *item;

    n = PyList_Size(list);
    if (n < 0)
        return -1; /* Not a list */
    for (i = 0; i < n; i++) {
        item = PyList_GetItem(list, i); /* Can't fail */
        if (!PyLong_Check(item)) continue; /* Skip non-integers */
        value = PyLong_AsLong(item);
        if (value == -1 && PyErr_Occurred())
            /* Integer too big to fit in a C long, bail out */
            return -1;
        total += value;
    }
    return total;
}

long
sum_sequence(PyObject *sequence)
{
    Py_ssize_t i, n;
    long total = 0, value;
    PyObject *item;
    n = PySequence_Length(sequence);
    if (n < 0)
        return -1; /* Has no length */
    for (i = 0; i < n; i++) {
        item = PySequence_GetItem(sequence, i);
        if (item == NULL)
            return -1; /* Not a sequence, or other failure */
        if (PyLong_Check(item)) {
            value = PyLong_AsLong(item);
            Py_DECREF(item);
            if (value == -1 && PyErr_Occurred())
                /* Integer too big to fit in a C long, bail out */
                return -1;
            total += value;
        }
        else {
            Py_DECREF(item); /* Discard reference ownership */
        }
    }
    return total;
}

Types

There are few other data types that play a significant role in the Python/C API; most are simple C types such as int, long, double and char*. A few structure types are used to describe static tables used to list the functions exported by a module or the data attributes of a new object type, and another is used to describe the value of a complex number. These will be discussed together with the functions that use them.

Exceptions

The Python programmer only needs to deal with exceptions if specific error handling is required; unhandled exceptions are automatically propagated to the caller, then to the caller’s caller, and so on, until they reach the top-level interpreter, where they are reported to the user accompanied by a stack traceback.

For C programmers, however, error checking always has to be explicit. All functions in the Python/C API can raise exceptions, unless an explicit claim is made otherwise in a function’s documentation. In general, when a function encounters an error, it sets an exception, discards any object references that it owns, and returns an error indicator. If not documented otherwise, this indicator is either NULL or -1, depending on the function’s return type. A few functions return a Boolean true/false result, with false indicating an error. Very few functions return no explicit error indicator or have an ambiguous return value, and require explicit testing for errors with PyErr_Occurred(). These exceptions are always explicitly documented.

Exception state is maintained in per-thread storage (this is equivalent to using global storage in an unthreaded application). A thread can be in one of two states: an exception has occurred, or not. The function PyErr_Occurred() can be used to check for this: it returns a borrowed reference to the exception type object when an exception has occurred, and NULL otherwise. There are a number of functions to set the exception state: PyErr_SetString() is the most common (though not the most general) function to set the exception state, and PyErr_Clear() clears the exception state.

The full exception state consists of three objects (all of which can be NULL): the exception type, the corresponding exception value, and the traceback. These have the same meanings as the Python result of sys.exc_info(); however, they are not the same: the Python objects represent the last exception being handled by a Python try … except statement, while the C level exception state only exists while an exception is being passed on between C functions until it reaches the Python bytecode interpreter’s main loop, which takes care of transferring it to sys.exc_info() and friends.

Note that starting with Python 1.5, the preferred, thread-safe way to access the exception state from Python code is to call the function sys.exc_info(), which returns the per-thread exception state for Python code. Also, the semantics of both ways to access the exception state have changed so that a function which catches an exception will save and restore its thread’s exception state so as to preserve the exception state of its caller. This prevents common bugs in exception handling code caused by an innocent-looking function overwriting the exception being handled; it also reduces the often unwanted lifetime extension for objects that are referenced by the stack frames in the traceback.

As a general principle, a function that calls another function to perform some task should check whether the called function raised an exception, and if so, pass the exception state on to its caller. It should discard any object references that it owns, and return an error indicator, but it should not set another exception — that would overwrite the exception that was just raised, and lose important information about the exact cause of the error.

A simple example of detecting exceptions and passing them on is shown in the sum_sequence() example above. It so happens that this example doesn’t need to clean up any owned references when it detects an error. The following example function shows some error cleanup. First, to remind you why you like Python, we show the equivalent Python code:

def incr_item(dict, key):
    try:
        item = dict[key]
    except KeyError:
        item = 0
    dict[key] = item + 1

Here is the corresponding C code, in all its glory:

int
incr_item(PyObject *dict, PyObject *key)
{
    /* Objects all initialized to NULL for Py_XDECREF */
    PyObject *item = NULL, *const_one = NULL, *incremented_item = NULL;
    int rv = -1; /* Return value initialized to -1 (failure) */

    item = PyObject_GetItem(dict, key);
    if (item == NULL) {
        /* Handle KeyError only: */
        if (!PyErr_ExceptionMatches(PyExc_KeyError))
            goto error;

        /* Clear the error and use zero: */
        PyErr_Clear();
        item = PyLong_FromLong(0L);
        if (item == NULL)
            goto error;
    }
    const_one = PyLong_FromLong(1L);
    if (const_one == NULL)
        goto error;

    incremented_item = PyNumber_Add(item, const_one);
    if (incremented_item == NULL)
        goto error;

    if (PyObject_SetItem(dict, key, incremented_item) < 0)
        goto error;
    rv = 0; /* Success */
    /* Continue with cleanup code */

 error:
    /* Cleanup code, shared by success and failure path */

    /* Use Py_XDECREF() to ignore NULL references */
    Py_XDECREF(item);
    Py_XDECREF(const_one);
    Py_XDECREF(incremented_item);

    return rv; /* -1 for error, 0 for success */
}

This example represents an endorsed use of the goto statement in C! It illustrates the use of PyErr_ExceptionMatches() and PyErr_Clear() to handle specific exceptions, and the use of Py_XDECREF() to dispose of owned references that may be NULL (note the 'X' in the name; Py_DECREF() would crash when confronted with a NULL reference). It is important that the variables used to hold owned references are initialized to NULL for this to work; likewise, the proposed return value is initialized to -1 (failure) and only set to success after the final call made is successful.

Embedding Python

The one important task that only embedders (as opposed to extension writers) of the Python interpreter have to worry about is the initialization, and possibly the finalization, of the Python interpreter. Most functionality of the interpreter can only be used after the interpreter has been initialized.

The basic initialization function is Py_Initialize(). This initializes the table of loaded modules, and creates the fundamental modules builtins, __main__, and sys. It also initializes the module search path (sys.path).

Py_Initialize() does not set the “script argument list” (sys.argv). If this variable is needed by Python code that will be executed later, it must be set explicitly with a call to PySys_SetArgvEx(argc, argv, updatepath) after the call to Py_Initialize().

On most systems (in particular, on Unix and Windows, although the details are slightly different), Py_Initialize() calculates the module search path based upon its best guess for the location of the standard Python interpreter executable, assuming that the Python library is found in a fixed location relative to the Python interpreter executable. In particular, it looks for a directory named lib/pythonX.Y relative to the parent directory where the executable named python is found on the shell command search path (the environment variable PATH).

For instance, if the Python executable is found in /usr/local/bin/python, it will assume that the libraries are in /usr/local/lib/pythonX.Y. (In fact, this particular path is also the “fallback” location, used when no executable file named python is found along PATH.) The user can override this behavior by setting the environment variable PYTHONHOME, or insert additional directories in front of the standard path by setting PYTHONPATH.

The embedding application can steer the search by calling Py_SetProgramName(file) before calling Py_Initialize(). Note that PYTHONHOME still overrides this and PYTHONPATH is still inserted in front of the standard path. An application that requires total control has to provide its own implementation of Py_GetPath(), Py_GetPrefix(), Py_GetExecPrefix(), and Py_GetProgramFullPath() (all defined in Modules/getpath.c).

Sometimes, it is desirable to “uninitialize” Python. For instance, the application may want to start over (make another call to Py_Initialize()) or the application is simply done with its use of Python and wants to free memory allocated by Python. This can be accomplished by calling Py_FinalizeEx(). The function Py_IsInitialized() returns true if Python is currently in the initialized state. More information about these functions is given in a later chapter. Notice that Py_FinalizeEx() does not free all memory allocated by the Python interpreter, e.g. memory allocated by extension modules currently cannot be released.

Debugging Builds

Python can be built with several macros to enable extra checks of the interpreter and extension modules. These checks tend to add a large amount of overhead to the runtime so they are not enabled by default.

A full list of the various types of debugging builds is in the file Misc/SpecialBuilds.txt in the Python source distribution. Builds are available that support tracing of reference counts, debugging the memory allocator, or low-level profiling of the main interpreter loop. Only the most frequently-used builds will be described in the remainder of this section.

Compiling the interpreter with the Py_DEBUG macro defined produces what is generally meant by “a debug build” of Python. Py_DEBUG is enabled in the Unix build by adding --with-pydebug to the ./configure command. It is also implied by the presence of the not-Python-specific _DEBUG macro. When Py_DEBUG is enabled in the Unix build, compiler optimization is disabled.

In addition to the reference count debugging described below, the following extra checks are performed:

Extra checks are added to the object allocator.

Extra checks are added to the parser and compiler.

Downcasts from wide types to narrow types are checked for loss of information.

A number of assertions are added to the dictionary and set implementations. In addition, the set object acquires a test_c_api() method.

Sanity checks of the input arguments are added to frame creation.

The storage for ints is initialized with a known invalid pattern to catch reference to uninitialized digits.

Low-level tracing and extra exception checking are added to the runtime virtual machine.

Extra checks are added to the memory arena implementation.

Extra debugging is added to the thread module.

There may be additional checks not mentioned here.

Defining Py_TRACE_REFS enables reference tracing. When defined, a circular doubly linked list of active objects is maintained by adding two extra fields to every PyObject. Total allocations are tracked as well. Upon exit, all existing references are printed. (In interactive mode this happens after every statement run by the interpreter.) Implied by Py_DEBUG.

Please refer to Misc/SpecialBuilds.txt in the Python source distribution for more detailed information.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

|

안정적인 응용 프로그램 바이너리 인터페이스

관례에 따라, 파이썬의 C API는 모든 배포마다 변경될 것입니다. 대부분 변경은 소스 호환되며, 일반적으로 기존 API를 변경하거나 API를 제거하지 않고 API를 추가하기만 합니다 (일부 인터페이스는 먼저 폐지된 후에 제거됩니다).

아쉽게도, API 호환성은 ABI(바이너리 호환성)로 확장되지 않습니다. 그 이유는 기본적으로 구조체 정의가 진화하기 때문인데, 새로운 필드를 추가하거나 필드의 형을 바꾸면 API가 손상되지는 않지만, ABI가 손상될 수 있습니다. 결과적으로, 확장 모듈은 파이썬 배포마다 다시 컴파일해야 합니다 (영향을 받는 인터페이스가 사용되지 않는 경우 유닉스에서는 예외일 수 있습니다). 또한, 윈도우에서 확장 모듈은 특정 pythonXY.dll과 링크되고 최신 모듈과 링크하기 위해 다시 컴파일할 필요가 있습니다.

파이썬 3.2부터, API 일부가 안정적인 ABI를 보장하도록 선언되었습니다. 이 API( “제한된 API”라고 합니다)를 사용하고자 하는 확장 모듈은 Py_LIMITED_API를 정의해야 합니다. 그러면 인터프리터의 세부 정보는 확장 모듈에 숨겨집니다; 그 대가로, 재컴파일 없이 모든 3.x 버전(x>=2)에서 작동하는 모듈이 빌드됩니다.

어떤 경우에는, 안정적인 ABI를 새로운 기능으로 확장해야 합니다. 이러한 새로운 API를 사용하고자 하는 확장 모듈은 지원하고자 하는 최소 파이썬 버전의 PY_VERSION_HEX 값(API와 ABI 버전 붙이기 참조)으로 Py_LIMITED_API를 설정해야 합니다 (예를 들어, 파이썬 3.3의 경우 0x03030000). 이러한 모듈은 모든 후속 파이썬 배포에서 작동하지만, 이전 배포에서 (심볼 누락으로 인해)로드하지 못합니다.

파이썬 3.2부터, 제한된 API에서 사용할 수 있는 함수 집합이 PEP 384 [https://www.python.org/dev/peps/pep-0384]에 문서로 만들어져 있습니다. C API 설명서에서, 제한된 API 일부가 아닌 API 요소는 “제한된 API 일부가 아닙니다.”로 표시됩니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

|

The Very High Level Layer

The functions in this chapter will let you execute Python source code given in a file or a buffer, but they will not let you interact in a more detailed way with the interpreter.

Several of these functions accept a start symbol from the grammar as a parameter. The available start symbols are Py_eval_input, Py_file_input, and Py_single_input. These are described following the functions which accept them as parameters.

Note also that several of these functions take FILE* parameters. One particular issue which needs to be handled carefully is that the FILE structure for different C libraries can be different and incompatible. Under Windows (at least), it is possible for dynamically linked extensions to actually use different libraries, so care should be taken that FILE* parameters are only passed to these functions if it is certain that they were created by the same library that the Python runtime is using.

int Py_Main(int argc, wchar_t **argv)

The main program for the standard interpreter. This is made available for programs which embed Python. The argc and argv parameters should be prepared exactly as those which are passed to a C program’s main() function (converted to wchar_t according to the user’s locale). It is important to note that the argument list may be modified (but the contents of the strings pointed to by the argument list are not). The return value will be 0 if the interpreter exits normally (i.e., without an exception), 1 if the interpreter exits due to an exception, or 2 if the parameter list does not represent a valid Python command line.

Note that if an otherwise unhandled SystemExit is raised, this function will not return 1, but exit the process, as long as Py_InspectFlag is not set.

int PyRun_AnyFile(FILE *fp, const char *filename)

This is a simplified interface to PyRun_AnyFileExFlags() below, leaving closeit set to 0 and flags set to NULL.

int PyRun_AnyFileFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)

This is a simplified interface to PyRun_AnyFileExFlags() below, leaving the closeit argument set to 0.

int PyRun_AnyFileEx(FILE *fp, const char *filename, int closeit)

This is a simplified interface to PyRun_AnyFileExFlags() below, leaving the flags argument set to NULL.

int PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit, PyCompilerFlags *flags)

If fp refers to a file associated with an interactive device (console or terminal input or Unix pseudo-terminal), return the value of PyRun_InteractiveLoop(), otherwise return the result of PyRun_SimpleFile(). filename is decoded from the filesystem encoding (sys.getfilesystemencoding()). If filename is NULL, this function uses "???" as the filename.

int PyRun_SimpleString(const char *command)

This is a simplified interface to PyRun_SimpleStringFlags() below, leaving the PyCompilerFlags* argument set to NULL.

int PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)

Executes the Python source code from command in the __main__ module according to the flags argument. If __main__ does not already exist, it is created. Returns 0 on success or -1 if an exception was raised. If there was an error, there is no way to get the exception information. For the meaning of flags, see below.

Note that if an otherwise unhandled SystemExit is raised, this function will not return -1, but exit the process, as long as Py_InspectFlag is not set.

int PyRun_SimpleFile(FILE *fp, const char *filename)

This is a simplified interface to PyRun_SimpleFileExFlags() below, leaving closeit set to 0 and flags set to NULL.

int PyRun_SimpleFileEx(FILE *fp, const char *filename, int closeit)

This is a simplified interface to PyRun_SimpleFileExFlags() below, leaving flags set to NULL.

int PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit, PyCompilerFlags *flags)

Similar to PyRun_SimpleStringFlags(), but the Python source code is read from fp instead of an in-memory string. filename should be the name of the file, it is decoded from the filesystem encoding (sys.getfilesystemencoding()). If closeit is true, the file is closed before PyRun_SimpleFileExFlags returns.

참고

On Windows, fp should be opened as binary mode (e.g. fopen(filename, "rb"). Otherwise, Python may not handle script file with LF line ending correctly.

int PyRun_InteractiveOne(FILE *fp, const char *filename)

This is a simplified interface to PyRun_InteractiveOneFlags() below, leaving flags set to NULL.

int PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)

Read and execute a single statement from a file associated with an interactive device according to the flags argument. The user will be prompted using sys.ps1 and sys.ps2. filename is decoded from the filesystem encoding (sys.getfilesystemencoding()).

Returns 0 when the input was executed successfully, -1 if there was an exception, or an error code from the errcode.h include file distributed as part of Python if there was a parse error. (Note that errcode.h is not included by Python.h, so must be included specifically if needed.)

int PyRun_InteractiveLoop(FILE *fp, const char *filename)

This is a simplified interface to PyRun_InteractiveLoopFlags() below, leaving flags set to NULL.

int PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)

Read and execute statements from a file associated with an interactive device until EOF is reached. The user will be prompted using sys.ps1 and sys.ps2. filename is decoded from the filesystem encoding (sys.getfilesystemencoding()). Returns 0 at EOF or a negative number upon failure.

int (*PyOS_InputHook)(void)

Can be set to point to a function with the prototype int func(void). The function will be called when Python’s interpreter prompt is about to become idle and wait for user input from the terminal. The return value is ignored. Overriding this hook can be used to integrate the interpreter’s prompt with other event loops, as done in the Modules/_tkinter.c in the Python source code.

char* (*PyOS_ReadlineFunctionPointer)(FILE *, FILE *, const char *)

Can be set to point to a function with the prototype char *func(FILE *stdin, FILE *stdout, char *prompt), overriding the default function used to read a single line of input at the interpreter’s prompt. The function is expected to output the string prompt if it’s not NULL, and then read a line of input from the provided standard input file, returning the resulting string. For example, The readline module sets this hook to provide line-editing and tab-completion features.

The result must be a string allocated by PyMem_RawMalloc() or PyMem_RawRealloc(), or NULL if an error occurred.

버전 3.4에서 변경: The result must be allocated by PyMem_RawMalloc() or PyMem_RawRealloc(), instead of being allocated by PyMem_Malloc() or PyMem_Realloc().

struct _node* PyParser_SimpleParseString(const char *str, int start)

This is a simplified interface to PyParser_SimpleParseStringFlagsFilename() below, leaving filename set to NULL and flags set to 0.

struct _node* PyParser_SimpleParseStringFlags(const char *str, int start, int flags)

This is a simplified interface to PyParser_SimpleParseStringFlagsFilename() below, leaving filename set to NULL.

struct _node* PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename, int start, int flags)

Parse Python source code from str using the start token start according to the flags argument. The result can be used to create a code object which can be evaluated efficiently. This is useful if a code fragment must be evaluated many times. filename is decoded from the filesystem encoding (sys.getfilesystemencoding()).

struct _node* PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)

This is a simplified interface to PyParser_SimpleParseFileFlags() below, leaving flags set to 0.

struct _node* PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)

Similar to PyParser_SimpleParseStringFlagsFilename(), but the Python source code is read from fp instead of an in-memory string.

PyObject* PyRun_String(const char *str, int start, PyObject *globals, PyObject *locals)

Return value: New reference.

This is a simplified interface to PyRun_StringFlags() below, leaving flags set to NULL.

PyObject* PyRun_StringFlags(const char *str, int start, PyObject *globals, PyObject *locals, PyCompilerFlags *flags)

Return value: New reference.

Execute Python source code from str in the context specified by the objects globals and locals with the compiler flags specified by flags. globals must be a dictionary; locals can be any object that implements the mapping protocol. The parameter start specifies the start token that should be used to parse the source code.

Returns the result of executing the code as a Python object, or NULL if an exception was raised.

PyObject* PyRun_File(FILE *fp, const char *filename, int start, PyObject *globals, PyObject *locals)

Return value: New reference.

This is a simplified interface to PyRun_FileExFlags() below, leaving closeit set to 0 and flags set to NULL.

PyObject* PyRun_FileEx(FILE *fp, const char *filename, int start, PyObject *globals, PyObject *locals, int closeit)

Return value: New reference.

This is a simplified interface to PyRun_FileExFlags() below, leaving flags set to NULL.

PyObject* PyRun_FileFlags(FILE *fp, const char *filename, int start, PyObject *globals, PyObject *locals, PyCompilerFlags *flags)

Return value: New reference.

This is a simplified interface to PyRun_FileExFlags() below, leaving closeit set to 0.

PyObject* PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals, PyObject *locals, int closeit, PyCompilerFlags *flags)

Return value: New reference.

Similar to PyRun_StringFlags(), but the Python source code is read from fp instead of an in-memory string. filename should be the name of the file, it is decoded from the filesystem encoding (sys.getfilesystemencoding()). If closeit is true, the file is closed before PyRun_FileExFlags() returns.

PyObject* Py_CompileString(const char *str, const char *filename, int start)

Return value: New reference.

This is a simplified interface to Py_CompileStringFlags() below, leaving flags set to NULL.

PyObject* Py_CompileStringFlags(const char *str, const char *filename, int start, PyCompilerFlags *flags)

Return value: New reference.

This is a simplified interface to Py_CompileStringExFlags() below, with optimize set to -1.

PyObject* Py_CompileStringObject(const char *str, PyObject *filename, int start, PyCompilerFlags *flags, int optimize)

Return value: New reference.

Parse and compile the Python source code in str, returning the resulting code object. The start token is given by start; this can be used to constrain the code which can be compiled and should be Py_eval_input, Py_file_input, or Py_single_input. The filename specified by filename is used to construct the code object and may appear in tracebacks or SyntaxError exception messages. This returns NULL if the code cannot be parsed or compiled.

The integer optimize specifies the optimization level of the compiler; a value of -1 selects the optimization level of the interpreter as given by -O options. Explicit levels are 0 (no optimization; __debug__ is true), 1 (asserts are removed, __debug__ is false) or 2 (docstrings are removed too).

버전 3.4에 추가.

PyObject* Py_CompileStringExFlags(const char *str, const char *filename, int start, PyCompilerFlags *flags, int optimize)

Return value: New reference.

Like Py_CompileStringObject(), but filename is a byte string decoded from the filesystem encoding (os.fsdecode()).

버전 3.2에 추가.

PyObject* PyEval_EvalCode(PyObject *co, PyObject *globals, PyObject *locals)

Return value: New reference.

This is a simplified interface to PyEval_EvalCodeEx(), with just the code object, and global and local variables. The other arguments are set to NULL.

PyObject* PyEval_EvalCodeEx(PyObject *co, PyObject *globals, PyObject *locals, PyObject *const *args, int argcount, PyObject *const *kws, int kwcount, PyObject *const *defs, int defcount, PyObject *kwdefs, PyObject *closure)

Return value: New reference.

Evaluate a precompiled code object, given a particular environment for its evaluation. This environment consists of a dictionary of global variables, a mapping object of local variables, arrays of arguments, keywords and defaults, a dictionary of default values for keyword-only arguments and a closure tuple of cells.

PyFrameObject

The C structure of the objects used to describe frame objects. The fields of this type are subject to change at any time.

PyObject* PyEval_EvalFrame(PyFrameObject *f)

Return value: New reference.

Evaluate an execution frame. This is a simplified interface to PyEval_EvalFrameEx(), for backward compatibility.

PyObject* PyEval_EvalFrameEx(PyFrameObject *f, int throwflag)

Return value: New reference.

This is the main, unvarnished function of Python interpretation. It is literally 2000 lines long. The code object associated with the execution frame f is executed, interpreting bytecode and executing calls as needed. The additional throwflag parameter can mostly be ignored - if true, then it causes an exception to immediately be thrown; this is used for the throw() methods of generator objects.

버전 3.4에서 변경: This function now includes a debug assertion to help ensure that it does not silently discard an active exception.

int PyEval_MergeCompilerFlags(PyCompilerFlags *cf)

This function changes the flags of the current evaluation frame, and returns true on success, false on failure.

int Py_eval_input

The start symbol from the Python grammar for isolated expressions; for use with Py_CompileString().

int Py_file_input

The start symbol from the Python grammar for sequences of statements as read from a file or other source; for use with Py_CompileString(). This is the symbol to use when compiling arbitrarily long Python source code.

int Py_single_input

The start symbol from the Python grammar for a single statement; for use with Py_CompileString(). This is the symbol used for the interactive interpreter loop.

struct PyCompilerFlags

This is the structure used to hold compiler flags. In cases where code is only being compiled, it is passed as int flags, and in cases where code is being executed, it is passed as PyCompilerFlags *flags. In this case, from __future__ import can modify flags.

Whenever PyCompilerFlags *flags is NULL, cf_flags is treated as equal to 0, and any modification due to from __future__ import is discarded.

struct PyCompilerFlags {
    int cf_flags;
}

int CO_FUTURE_DIVISION

This bit can be set in flags to cause division operator / to be interpreted as “true division” according to PEP 238 [https://www.python.org/dev/peps/pep-0238].

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

|

참조 횟수

이 섹션의 매크로는 파이썬 객체의 참조 횟수를 관리하는 데 사용됩니다.

void Py_INCREF(PyObject *o)

Increment the reference count for object o. The object must not be NULL; if you aren’t sure that it isn’t NULL, use Py_XINCREF().

void Py_XINCREF(PyObject *o)

Increment the reference count for object o. The object may be NULL, in which case the macro has no effect.

void Py_DECREF(PyObject *o)

Decrement the reference count for object o. The object must not be NULL; if you aren’t sure that it isn’t NULL, use Py_XDECREF(). If the reference count reaches zero, the object’s type’s deallocation function (which must not be NULL) is invoked.

경고

할당 해제 함수는 임의의 파이썬 코드가 호출되도록 할 수 있습니다 (예를 들어, __del__() 메서드가 있는 클래스 인스턴스가 할당 해제될 때). 이러한 코드에서의 예외는 전파되지 않지만, 실행된 코드는 모든 파이썬 전역 변수에 자유롭게 액세스할 수 있습니다. 이것은 Py_DECREF()가 호출되기 전에 전역 변수에서 도달할 수 있는 모든 객체가 일관성 있는 상태에 있어야 함을 뜻합니다. 예를 들어, 리스트에서 객체를 삭제하는 코드는 삭제된 객체에 대한 참조를 임시 변수에 복사하고, 리스트 데이터 구조를 갱신한 다음, 임시 변수에 대해 Py_DECREF()를 호출해야 합니다.

void Py_XDECREF(PyObject *o)

Decrement the reference count for object o. The object may be NULL, in which case the macro has no effect; otherwise the effect is the same as for Py_DECREF(), and the same warning applies.

void Py_CLEAR(PyObject *o)

Decrement the reference count for object o. The object may be NULL, in which case the macro has no effect; otherwise the effect is the same as for Py_DECREF(), except that the argument is also set to NULL. The warning for Py_DECREF() does not apply with respect to the object passed because the macro carefully uses a temporary variable and sets the argument to NULL before decrementing its reference count.

가비지 수집 중에 탐색 될 수 있는 변수의 값을 감소시킬 때마다 이 매크로를 사용하는 것이 좋습니다.

다음 함수는 파이썬의 실행 시간 동적 내장을 위한 것입니다: Py_IncRef(PyObject *o), Py_DecRef(PyObject *o). 이것들은 단순히 Py_XINCREF()와 Py_XDECREF()의 노출된 함수 버전입니다.

다음 함수나 매크로는 인터프리터 코어에서만 사용할 수 있습니다: _Py_Dealloc(), _Py_ForgetReference(), _Py_NewReference() 및 전역 변수 _Py_RefTotal.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

|

Exception Handling

The functions described in this chapter will let you handle and raise Python exceptions. It is important to understand some of the basics of Python exception handling. It works somewhat like the POSIX errno variable: there is a global indicator (per thread) of the last error that occurred. Most C API functions don’t clear this on success, but will set it to indicate the cause of the error on failure. Most C API functions also return an error indicator, usually NULL if they are supposed to return a pointer, or -1 if they return an integer (exception: the PyArg_*() functions return 1 for success and 0 for failure).

Concretely, the error indicator consists of three object pointers: the exception’s type, the exception’s value, and the traceback object. Any of those pointers can be NULL if non-set (although some combinations are forbidden, for example you can’t have a non-NULL traceback if the exception type is NULL).

When a function must fail because some function it called failed, it generally doesn’t set the error indicator; the function it called already set it. It is responsible for either handling the error and clearing the exception or returning after cleaning up any resources it holds (such as object references or memory allocations); it should not continue normally if it is not prepared to handle the error. If returning due to an error, it is important to indicate to the caller that an error has been set. If the error is not handled or carefully propagated, additional calls into the Python/C API may not behave as intended and may fail in mysterious ways.

참고

The error indicator is not the result of sys.exc_info(). The former corresponds to an exception that is not yet caught (and is therefore still propagating), while the latter returns an exception after it is caught (and has therefore stopped propagating).

Printing and clearing

void PyErr_Clear()

Clear the error indicator. If the error indicator is not set, there is no effect.

void PyErr_PrintEx(int set_sys_last_vars)

Print a standard traceback to sys.stderr and clear the error indicator. Unless the error is a SystemExit. In that case the no traceback is printed and Python process will exit with the error code specified by the SystemExit instance.

Call this function only when the error indicator is set. Otherwise it will cause a fatal error!

If set_sys_last_vars is nonzero, the variables sys.last_type, sys.last_value and sys.last_traceback will be set to the type, value and traceback of the printed exception, respectively.

void PyErr_Print()

Alias for PyErr_PrintEx(1).

void PyErr_WriteUnraisable(PyObject *obj)

This utility function prints a warning message to sys.stderr when an exception has been set but it is impossible for the interpreter to actually raise the exception. It is used, for example, when an exception occurs in an __del__() method.

The function is called with a single argument obj that identifies the context in which the unraisable exception occurred. If possible, the repr of obj will be printed in the warning message.

An exception must be set when calling this function.

Raising exceptions

These functions help you set the current thread’s error indicator. For convenience, some of these functions will always return a NULL pointer for use in a return statement.

void PyErr_SetString(PyObject *type, const char *message)

This is the most common way to set the error indicator. The first argument specifies the exception type; it is normally one of the standard exceptions, e.g. PyExc_RuntimeError. You need not increment its reference count. The second argument is an error message; it is decoded from 'utf-8’.

void PyErr_SetObject(PyObject *type, PyObject *value)

This function is similar to PyErr_SetString() but lets you specify an arbitrary Python object for the “value” of the exception.

PyObject* PyErr_Format(PyObject *exception, const char *format, ...)

Return value: Always NULL.

This function sets the error indicator and returns NULL. exception should be a Python exception class. The format and subsequent parameters help format the error message; they have the same meaning and values as in PyUnicode_FromFormat(). format is an ASCII-encoded string.

PyObject* PyErr_FormatV(PyObject *exception, const char *format, va_list vargs)

Return value: Always NULL.

Same as PyErr_Format(), but taking a va_list argument rather than a variable number of arguments.

버전 3.5에 추가.

void PyErr_SetNone(PyObject *type)

This is a shorthand for PyErr_SetObject(type, Py_None).

int PyErr_BadArgument()

This is a shorthand for PyErr_SetString(PyExc_TypeError, message), where message indicates that a built-in operation was invoked with an illegal argument. It is mostly for internal use.

PyObject* PyErr_NoMemory()

Return value: Always NULL.

This is a shorthand for PyErr_SetNone(PyExc_MemoryError); it returns NULL so an object allocation function can write return PyErr_NoMemory(); when it runs out of memory.

PyObject* PyErr_SetFromErrno(PyObject *type)

Return value: Always NULL.

This is a convenience function to raise an exception when a C library function has returned an error and set the C variable errno. It constructs a tuple object whose first item is the integer errno value and whose second item is the corresponding error message (gotten from strerror()), and then calls PyErr_SetObject(type, object). On Unix, when the errno value is EINTR, indicating an interrupted system call, this calls PyErr_CheckSignals(), and if that set the error indicator, leaves it set to that. The function always returns NULL, so a wrapper function around a system call can write return PyErr_SetFromErrno(type); when the system call returns an error.

PyObject* PyErr_SetFromErrnoWithFilenameObject(PyObject *type, PyObject *filenameObject)

Return value: Always NULL.

Similar to PyErr_SetFromErrno(), with the additional behavior that if filenameObject is not NULL, it is passed to the constructor of type as a third parameter. In the case of OSError exception, this is used to define the filename attribute of the exception instance.

PyObject* PyErr_SetFromErrnoWithFilenameObjects(PyObject *type, PyObject *filenameObject, PyObject *filenameObject2)

Return value: Always NULL.

Similar to PyErr_SetFromErrnoWithFilenameObject(), but takes a second filename object, for raising errors when a function that takes two filenames fails.

버전 3.4에 추가.

PyObject* PyErr_SetFromErrnoWithFilename(PyObject *type, const char *filename)

Return value: Always NULL.

Similar to PyErr_SetFromErrnoWithFilenameObject(), but the filename is given as a C string. filename is decoded from the filesystem encoding (os.fsdecode()).

PyObject* PyErr_SetFromWindowsErr(int ierr)

Return value: Always NULL.

This is a convenience function to raise WindowsError. If called with ierr of 0, the error code returned by a call to GetLastError() is used instead. It calls the Win32 function FormatMessage() to retrieve the Windows description of error code given by ierr or GetLastError(), then it constructs a tuple object whose first item is the ierr value and whose second item is the corresponding error message (gotten from FormatMessage()), and then calls PyErr_SetObject(PyExc_WindowsError, object). This function always returns NULL.

Availability: Windows.

PyObject* PyErr_SetExcFromWindowsErr(PyObject *type, int ierr)

Return value: Always NULL.

Similar to PyErr_SetFromWindowsErr(), with an additional parameter specifying the exception type to be raised.

Availability: Windows.

PyObject* PyErr_SetFromWindowsErrWithFilename(int ierr, const char *filename)

Return value: Always NULL.

Similar to PyErr_SetFromWindowsErrWithFilenameObject(), but the filename is given as a C string. filename is decoded from the filesystem encoding (os.fsdecode()).

Availability: Windows.

PyObject* PyErr_SetExcFromWindowsErrWithFilenameObject(PyObject *type, int ierr, PyObject *filename)

Return value: Always NULL.

Similar to PyErr_SetFromWindowsErrWithFilenameObject(), with an additional parameter specifying the exception type to be raised.

Availability: Windows.

PyObject* PyErr_SetExcFromWindowsErrWithFilenameObjects(PyObject *type, int ierr, PyObject *filename, PyObject *filename2)

Return value: Always NULL.

Similar to PyErr_SetExcFromWindowsErrWithFilenameObject(), but accepts a second filename object.

Availability: Windows.

버전 3.4에 추가.

PyObject* PyErr_SetExcFromWindowsErrWithFilename(PyObject *type, int ierr, const char *filename)

Return value: Always NULL.

Similar to PyErr_SetFromWindowsErrWithFilename(), with an additional parameter specifying the exception type to be raised.

Availability: Windows.

PyObject* PyErr_SetImportError(PyObject *msg, PyObject *name, PyObject *path)

Return value: Always NULL.

This is a convenience function to raise ImportError. msg will be set as the exception’s message string. name and path, both of which can be NULL, will be set as the ImportError’s respective name and path attributes.

버전 3.3에 추가.

void PyErr_SyntaxLocationObject(PyObject *filename, int lineno, int col_offset)

Set file, line, and offset information for the current exception. If the current exception is not a SyntaxError, then it sets additional attributes, which make the exception printing subsystem think the exception is a SyntaxError.

버전 3.4에 추가.

void PyErr_SyntaxLocationEx(const char *filename, int lineno, int col_offset)

Like PyErr_SyntaxLocationObject(), but filename is a byte string decoded from the filesystem encoding (os.fsdecode()).

버전 3.2에 추가.

void PyErr_SyntaxLocation(const char *filename, int lineno)

Like PyErr_SyntaxLocationEx(), but the col_offset parameter is omitted.

void PyErr_BadInternalCall()

This is a shorthand for PyErr_SetString(PyExc_SystemError, message), where message indicates that an internal operation (e.g. a Python/C API function) was invoked with an illegal argument. It is mostly for internal use.

Issuing warnings

Use these functions to issue warnings from C code. They mirror similar functions exported by the Python warnings module. They normally print a warning message to sys.stderr; however, it is also possible that the user has specified that warnings are to be turned into errors, and in that case they will raise an exception. It is also possible that the functions raise an exception because of a problem with the warning machinery. The return value is 0 if no exception is raised, or -1 if an exception is raised. (It is not possible to determine whether a warning message is actually printed, nor what the reason is for the exception; this is intentional.) If an exception is raised, the caller should do its normal exception handling (for example, Py_DECREF() owned references and return an error value).

int PyErr_WarnEx(PyObject *category, const char *message, Py_ssize_t stack_level)

Issue a warning message. The category argument is a warning category (see below) or NULL; the message argument is a UTF-8 encoded string. stack_level is a positive number giving a number of stack frames; the warning will be issued from the currently executing line of code in that stack frame. A stack_level of 1 is the function calling PyErr_WarnEx(), 2 is the function above that, and so forth.

Warning categories must be subclasses of PyExc_Warning; PyExc_Warning is a subclass of PyExc_Exception; the default warning category is PyExc_RuntimeWarning. The standard Python warning categories are available as global variables whose names are enumerated at Standard Warning Categories.

For information about warning control, see the documentation for the warnings module and the -W option in the command line documentation. There is no C API for warning control.

PyObject* PyErr_SetImportErrorSubclass(PyObject *exception, PyObject *msg, PyObject *name, PyObject *path)

Return value: Always NULL.

Much like PyErr_SetImportError() but this function allows for specifying a subclass of ImportError to raise.

버전 3.6에 추가.

int PyErr_WarnExplicitObject(PyObject *category, PyObject *message, PyObject *filename, int lineno, PyObject *module, PyObject *registry)

Issue a warning message with explicit control over all warning attributes. This is a straightforward wrapper around the Python function warnings.warn_explicit(), see there for more information. The module and registry arguments may be set to NULL to get the default effect described there.

버전 3.4에 추가.

int PyErr_WarnExplicit(PyObject *category, const char *message, const char *filename, int lineno, const char *module, PyObject *registry)

Similar to PyErr_WarnExplicitObject() except that message and module are UTF-8 encoded strings, and filename is decoded from the filesystem encoding (os.fsdecode()).

int PyErr_WarnFormat(PyObject *category, Py_ssize_t stack_level, const char *format, ...)

Function similar to PyErr_WarnEx(), but use PyUnicode_FromFormat() to format the warning message. format is an ASCII-encoded string.

버전 3.2에 추가.

int PyErr_ResourceWarning(PyObject *source, Py_ssize_t stack_level, const char *format, ...)

Function similar to PyErr_WarnFormat(), but category is ResourceWarning and it passes source to warnings.WarningMessage().

버전 3.6에 추가.

Querying the error indicator

PyObject* PyErr_Occurred()

Return value: Borrowed reference.

Test whether the error indicator is set. If set, return the exception type (the first argument to the last call to one of the PyErr_Set*() functions or to PyErr_Restore()). If not set, return NULL. You do not own a reference to the return value, so you do not need to Py_DECREF() it.

참고

Do not compare the return value to a specific exception; use PyErr_ExceptionMatches() instead, shown below. (The comparison could easily fail since the exception may be an instance instead of a class, in the case of a class exception, or it may be a subclass of the expected exception.)

int PyErr_ExceptionMatches(PyObject *exc)

Equivalent to PyErr_GivenExceptionMatches(PyErr_Occurred(), exc). This should only be called when an exception is actually set; a memory access violation will occur if no exception has been raised.

int PyErr_GivenExceptionMatches(PyObject *given, PyObject *exc)

Return true if the given exception matches the exception type in exc. If exc is a class object, this also returns true when given is an instance of a subclass. If exc is a tuple, all exception types in the tuple (and recursively in subtuples) are searched for a match.

void PyErr_Fetch(PyObject **ptype, PyObject **pvalue, PyObject **ptraceback)

Retrieve the error indicator into three variables whose addresses are passed. If the error indicator is not set, set all three variables to NULL. If it is set, it will be cleared and you own a reference to each object retrieved. The value and traceback object may be NULL even when the type object is not.

참고

This function is normally only used by code that needs to catch exceptions or by code that needs to save and restore the error indicator temporarily, e.g.:

{
   PyObject *type, *value, *traceback;
   PyErr_Fetch(&type, &value, &traceback);

   /* ... code that might produce other errors ... */

   PyErr_Restore(type, value, traceback);
}

void PyErr_Restore(PyObject *type, PyObject *value, PyObject *traceback)

Set the error indicator from the three objects. If the error indicator is already set, it is cleared first. If the objects are NULL, the error indicator is cleared. Do not pass a NULL type and non-NULL value or traceback. The exception type should be a class. Do not pass an invalid exception type or value. (Violating these rules will cause subtle problems later.) This call takes away a reference to each object: you must own a reference to each object before the call and after the call you no longer own these references. (If you don’t understand this, don’t use this function. I warned you.)

참고

This function is normally only used by code that needs to save and restore the error indicator temporarily. Use PyErr_Fetch() to save the current error indicator.

void PyErr_NormalizeException(PyObject**exc, PyObject**val, PyObject**tb)

Under certain circumstances, the values returned by PyErr_Fetch() below can be “unnormalized”, meaning that *exc is a class object but *val is not an instance of the same class. This function can be used to instantiate the class in that case. If the values are already normalized, nothing happens. The delayed normalization is implemented to improve performance.

참고

This function does not implicitly set the __traceback__ attribute on the exception value. If setting the traceback appropriately is desired, the following additional snippet is needed:

if (tb != NULL) {
  PyException_SetTraceback(val, tb);
}

void PyErr_GetExcInfo(PyObject **ptype, PyObject **pvalue, PyObject **ptraceback)

Retrieve the exception info, as known from sys.exc_info(). This refers to an exception that was already caught, not to an exception that was freshly raised. Returns new references for the three objects, any of which may be NULL. Does not modify the exception info state.

참고

This function is not normally used by code that wants to handle exceptions. Rather, it can be used when code needs to save and restore the exception state temporarily. Use PyErr_SetExcInfo() to restore or clear the exception state.

버전 3.3에 추가.

void PyErr_SetExcInfo(PyObject *type, PyObject *value, PyObject *traceback)

Set the exception info, as known from sys.exc_info(). This refers to an exception that was already caught, not to an exception that was freshly raised. This function steals the references of the arguments. To clear the exception state, pass NULL for all three arguments. For general rules about the three arguments, see PyErr_Restore().

참고

This function is not normally used by code that wants to handle exceptions. Rather, it can be used when code needs to save and restore the exception state temporarily. Use PyErr_GetExcInfo() to read the exception state.

버전 3.3에 추가.

Signal Handling

int PyErr_CheckSignals()

This function interacts with Python’s signal handling. It checks whether a signal has been sent to the processes and if so, invokes the corresponding signal handler. If the signal module is supported, this can invoke a signal handler written in Python. In all cases, the default effect for SIGINT is to raise the KeyboardInterrupt exception. If an exception is raised the error indicator is set and the function returns -1; otherwise the function returns 0. The error indicator may or may not be cleared if it was previously set.

void PyErr_SetInterrupt()

Simulate the effect of a SIGINT signal arriving. The next time PyErr_CheckSignals() is called, the Python signal handler for SIGINT will be called.

If SIGINT isn’t handled by Python (it was set to signal.SIG_DFL or signal.SIG_IGN), this function does nothing.

int PySignal_SetWakeupFd(int fd)

This utility function specifies a file descriptor to which the signal number is written as a single byte whenever a signal is received. fd must be non-blocking. It returns the previous such file descriptor.

The value -1 disables the feature; this is the initial state. This is equivalent to signal.set_wakeup_fd() in Python, but without any error checking. fd should be a valid file descriptor. The function should only be called from the main thread.

버전 3.5에서 변경: On Windows, the function now also supports socket handles.

Exception Classes

PyObject* PyErr_NewException(const char *name, PyObject *base, PyObject *dict)

Return value: New reference.

This utility function creates and returns a new exception class. The name argument must be the name of the new exception, a C string of the form module.classname. The base and dict arguments are normally NULL. This creates a class object derived from Exception (accessible in C as PyExc_Exception).

The __module__ attribute of the new class is set to the first part (up to the last dot) of the name argument, and the class name is set to the last part (after the last dot). The base argument can be used to specify alternate base classes; it can either be only one class or a tuple of classes. The dict argument can be used to specify a dictionary of class variables and methods.

PyObject* PyErr_NewExceptionWithDoc(const char *name, const char *doc, PyObject *base, PyObject *dict)

Return value: New reference.

Same as PyErr_NewException(), except that the new exception class can easily be given a docstring: If doc is non-NULL, it will be used as the docstring for the exception class.

버전 3.2에 추가.

Exception Objects

PyObject* PyException_GetTraceback(PyObject *ex)

Return value: New reference.

Return the traceback associated with the exception as a new reference, as accessible from Python through __traceback__. If there is no traceback associated, this returns NULL.

int PyException_SetTraceback(PyObject *ex, PyObject *tb)

Set the traceback associated with the exception to tb. Use Py_None to clear it.

PyObject* PyException_GetContext(PyObject *ex)

Return value: New reference.

Return the context (another exception instance during whose handling ex was raised) associated with the exception as a new reference, as accessible from Python through __context__. If there is no context associated, this returns NULL.

void PyException_SetContext(PyObject *ex, PyObject *ctx)

Set the context associated with the exception to ctx. Use NULL to clear it. There is no type check to make sure that ctx is an exception instance. This steals a reference to ctx.

PyObject* PyException_GetCause(PyObject *ex)

Return value: New reference.

Return the cause (either an exception instance, or None, set by raise ... from ...) associated with the exception as a new reference, as accessible from Python through __cause__.

void PyException_SetCause(PyObject *ex, PyObject *cause)

Set the cause associated with the exception to cause. Use NULL to clear it. There is no type check to make sure that cause is either an exception instance or None. This steals a reference to cause.

__suppress_context__ is implicitly set to True by this function.

Unicode Exception Objects

The following functions are used to create and modify Unicode exceptions from C.

PyObject* PyUnicodeDecodeError_Create(const char *encoding, const char *object, Py_ssize_t length, Py_ssize_t start, Py_ssize_t end, const char *reason)

Return value: New reference.

Create a UnicodeDecodeError object with the attributes encoding, object, length, start, end and reason. encoding and reason are UTF-8 encoded strings.

PyObject* PyUnicodeEncodeError_Create(const char *encoding, const Py_UNICODE *object, Py_ssize_t length, Py_ssize_t start, Py_ssize_t end, const char *reason)

Return value: New reference.

Create a UnicodeEncodeError object with the attributes encoding, object, length, start, end and reason. encoding and reason are UTF-8 encoded strings.

PyObject* PyUnicodeTranslateError_Create(const Py_UNICODE *object, Py_ssize_t length, Py_ssize_t start, Py_ssize_t end, const char *reason)

Return value: New reference.

Create a UnicodeTranslateError object with the attributes object, length, start, end and reason. reason is a UTF-8 encoded string.

PyObject* PyUnicodeDecodeError_GetEncoding(PyObject *exc)

PyObject* PyUnicodeEncodeError_GetEncoding(PyObject *exc)

Return value: New reference.

Return the encoding attribute of the given exception object.

PyObject* PyUnicodeDecodeError_GetObject(PyObject *exc)

PyObject* PyUnicodeEncodeError_GetObject(PyObject *exc)

PyObject* PyUnicodeTranslateError_GetObject(PyObject *exc)

Return value: New reference.

Return the object attribute of the given exception object.

int PyUnicodeDecodeError_GetStart(PyObject *exc, Py_ssize_t *start)

int PyUnicodeEncodeError_GetStart(PyObject *exc, Py_ssize_t *start)

int PyUnicodeTranslateError_GetStart(PyObject *exc, Py_ssize_t *start)

Get the start attribute of the given exception object and place it into *start. start must not be NULL. Return 0 on success, -1 on failure.

int PyUnicodeDecodeError_SetStart(PyObject *exc, Py_ssize_t start)

int PyUnicodeEncodeError_SetStart(PyObject *exc, Py_ssize_t start)

int PyUnicodeTranslateError_SetStart(PyObject *exc, Py_ssize_t start)

Set the start attribute of the given exception object to start. Return 0 on success, -1 on failure.

int PyUnicodeDecodeError_GetEnd(PyObject *exc, Py_ssize_t *end)

int PyUnicodeEncodeError_GetEnd(PyObject *exc, Py_ssize_t *end)

int PyUnicodeTranslateError_GetEnd(PyObject *exc, Py_ssize_t *end)

Get the end attribute of the given exception object and place it into *end. end must not be NULL. Return 0 on success, -1 on failure.

int PyUnicodeDecodeError_SetEnd(PyObject *exc, Py_ssize_t end)

int PyUnicodeEncodeError_SetEnd(PyObject *exc, Py_ssize_t end)

int PyUnicodeTranslateError_SetEnd(PyObject *exc, Py_ssize_t end)

Set the end attribute of the given exception object to end. Return 0 on success, -1 on failure.

PyObject* PyUnicodeDecodeError_GetReason(PyObject *exc)

PyObject* PyUnicodeEncodeError_GetReason(PyObject *exc)

PyObject* PyUnicodeTranslateError_GetReason(PyObject *exc)

Return value: New reference.

Return the reason attribute of the given exception object.

int PyUnicodeDecodeError_SetReason(PyObject *exc, const char *reason)

int PyUnicodeEncodeError_SetReason(PyObject *exc, const char *reason)

int PyUnicodeTranslateError_SetReason(PyObject *exc, const char *reason)

Set the reason attribute of the given exception object to reason. Return 0 on success, -1 on failure.

Recursion Control

These two functions provide a way to perform safe recursive calls at the C level, both in the core and in extension modules. They are needed if the recursive code does not necessarily invoke Python code (which tracks its recursion depth automatically).

int Py_EnterRecursiveCall(const char *where)

Marks a point where a recursive C-level call is about to be performed.

If USE_STACKCHECK is defined, this function checks if the OS stack overflowed using PyOS_CheckStack(). In this is the case, it sets a MemoryError and returns a nonzero value.

The function then checks if the recursion limit is reached. If this is the case, a RecursionError is set and a nonzero value is returned. Otherwise, zero is returned.

where should be a string such as " in instance check" to be concatenated to the RecursionError message caused by the recursion depth limit.

void Py_LeaveRecursiveCall()

Ends a Py_EnterRecursiveCall(). Must be called once for each successful invocation of Py_EnterRecursiveCall().

Properly implementing tp_repr for container types requires special recursion handling. In addition to protecting the stack, tp_repr also needs to track objects to prevent cycles. The following two functions facilitate this functionality. Effectively, these are the C equivalent to reprlib.recursive_repr().

int Py_ReprEnter(PyObject *object)

Called at the beginning of the tp_repr implementation to detect cycles.

If the object has already been processed, the function returns a positive integer. In that case the tp_repr implementation should return a string object indicating a cycle. As examples, dict objects return {...} and list objects return [...].

The function will return a negative integer if the recursion limit is reached. In that case the tp_repr implementation should typically return NULL.

Otherwise, the function returns zero and the tp_repr implementation can continue normally.

void Py_ReprLeave(PyObject *object)

Ends a Py_ReprEnter(). Must be called once for each invocation of Py_ReprEnter() that returns zero.

Standard Exceptions

All standard Python exceptions are available as global variables whose names are PyExc_ followed by the Python exception name. These have the type PyObject*; they are all class objects. For completeness, here are all the variables:

C Name

Python Name

Notes

PyExc_BaseException

BaseException

(1)

PyExc_Exception

Exception

(1)

PyExc_ArithmeticError

ArithmeticError

(1)

PyExc_AssertionError

AssertionError

PyExc_AttributeError

AttributeError

PyExc_BlockingIOError

BlockingIOError

PyExc_BrokenPipeError

BrokenPipeError

PyExc_BufferError

BufferError

PyExc_ChildProcessError

ChildProcessError

PyExc_ConnectionAbortedError

ConnectionAbortedError

PyExc_ConnectionError

ConnectionError

PyExc_ConnectionRefusedError

ConnectionRefusedError

PyExc_ConnectionResetError

ConnectionResetError

PyExc_EOFError

EOFError

PyExc_FileExistsError

FileExistsError

PyExc_FileNotFoundError

FileNotFoundError

PyExc_FloatingPointError

FloatingPointError

PyExc_GeneratorExit

GeneratorExit

PyExc_ImportError

ImportError

PyExc_IndentationError

IndentationError

PyExc_IndexError

IndexError

PyExc_InterruptedError

InterruptedError

PyExc_IsADirectoryError

IsADirectoryError

PyExc_KeyError

KeyError

PyExc_KeyboardInterrupt

KeyboardInterrupt

PyExc_LookupError

LookupError

(1)

PyExc_MemoryError

MemoryError

PyExc_ModuleNotFoundError

ModuleNotFoundError

PyExc_NameError

NameError

PyExc_NotADirectoryError

NotADirectoryError

PyExc_NotImplementedError

NotImplementedError

PyExc_OSError

OSError

(1)

PyExc_OverflowError

OverflowError

PyExc_PermissionError

PermissionError

PyExc_ProcessLookupError

ProcessLookupError

PyExc_RecursionError

RecursionError

PyExc_ReferenceError

ReferenceError

(2)

PyExc_RuntimeError

RuntimeError

PyExc_StopAsyncIteration

StopAsyncIteration

PyExc_StopIteration

StopIteration

PyExc_SyntaxError

SyntaxError

PyExc_SystemError

SystemError

PyExc_SystemExit

SystemExit

PyExc_TabError

TabError

PyExc_TimeoutError

TimeoutError

PyExc_TypeError

TypeError

PyExc_UnboundLocalError

UnboundLocalError

PyExc_UnicodeDecodeError

UnicodeDecodeError

PyExc_UnicodeEncodeError

UnicodeEncodeError

PyExc_UnicodeError

UnicodeError

PyExc_UnicodeTranslateError

UnicodeTranslateError

PyExc_ValueError

ValueError

PyExc_ZeroDivisionError

ZeroDivisionError

버전 3.3에 추가: PyExc_BlockingIOError, PyExc_BrokenPipeError, PyExc_ChildProcessError, PyExc_ConnectionError, PyExc_ConnectionAbortedError, PyExc_ConnectionRefusedError, PyExc_ConnectionResetError, PyExc_FileExistsError, PyExc_FileNotFoundError, PyExc_InterruptedError, PyExc_IsADirectoryError, PyExc_NotADirectoryError, PyExc_PermissionError, PyExc_ProcessLookupError and PyExc_TimeoutError were introduced following PEP 3151 [https://www.python.org/dev/peps/pep-3151].

버전 3.5에 추가: PyExc_StopAsyncIteration and PyExc_RecursionError.

버전 3.6에 추가: PyExc_ModuleNotFoundError.

These are compatibility aliases to PyExc_OSError:

C Name

Notes

PyExc_EnvironmentError

PyExc_IOError

PyExc_WindowsError

(3)

버전 3.3에서 변경: These aliases used to be separate exception types.

Notes:

This is a base class for other standard exceptions.

Only defined on Windows; protect code that uses this by testing that the preprocessor macro MS_WINDOWS is defined.

Standard Warning Categories

All standard Python warning categories are available as global variables whose names are PyExc_ followed by the Python exception name. These have the type PyObject*; they are all class objects. For completeness, here are all the variables:

C Name

Python Name

Notes

PyExc_Warning

Warning

(1)

PyExc_BytesWarning

BytesWarning

PyExc_DeprecationWarning

DeprecationWarning

PyExc_FutureWarning

FutureWarning

PyExc_ImportWarning

ImportWarning

PyExc_PendingDeprecationWarning

PendingDeprecationWarning

PyExc_ResourceWarning

ResourceWarning

PyExc_RuntimeWarning

RuntimeWarning

PyExc_SyntaxWarning

SyntaxWarning

PyExc_UnicodeWarning

UnicodeWarning

PyExc_UserWarning

UserWarning

버전 3.2에 추가: PyExc_ResourceWarning.

Notes:

This is a base class for other standard warning categories.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

|

유틸리티

이 장의 함수들은 C 코드의 플랫폼 간 호환성 개선, C에서 파이썬 모듈 사용, 함수 인자의 구문 분석 및 C값으로부터 파이썬 값을 구성하는 것에 이르기까지 다양한 유틸리티 작업을 수행합니다.

Operating System Utilities

System Functions

Process Control

모듈 임포트 하기

데이터 마샬링 지원

Parsing arguments and building values

Parsing arguments

Strings and buffers

Numbers

Other objects

API Functions

Building values

문자열 변환과 포매팅

리플렉션

코덱 등록소와 지원 함수

코덱 조회 API

유니코드 인코딩 에러 처리기용 등록소 API

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

유틸리티 »

|

Operating System Utilities

PyObject* PyOS_FSPath(PyObject *path)

Return value: New reference.

Return the file system representation for path. If the object is a str or bytes object, then its reference count is incremented. If the object implements the os.PathLike interface, then __fspath__() is returned as long as it is a str or bytes object. Otherwise TypeError is raised and NULL is returned.

버전 3.6에 추가.

int Py_FdIsInteractive(FILE *fp, const char *filename)

Return true (nonzero) if the standard I/O file fp with name filename is deemed interactive. This is the case for files for which isatty(fileno(fp)) is true. If the global flag Py_InteractiveFlag is true, this function also returns true if the filename pointer is NULL or if the name is equal to one of the strings '<stdin>' or '???'.

void PyOS_BeforeFork()

Function to prepare some internal state before a process fork. This should be called before calling fork() or any similar function that clones the current process. Only available on systems where fork() is defined.

버전 3.7에 추가.

void PyOS_AfterFork_Parent()

Function to update some internal state after a process fork. This should be called from the parent process after calling fork() or any similar function that clones the current process, regardless of whether process cloning was successful. Only available on systems where fork() is defined.

버전 3.7에 추가.

void PyOS_AfterFork_Child()

Function to update internal interpreter state after a process fork. This must be called from the child process after calling fork(), or any similar function that clones the current process, if there is any chance the process will call back into the Python interpreter. Only available on systems where fork() is defined.

버전 3.7에 추가.

더 보기

os.register_at_fork() allows registering custom Python functions to be called by PyOS_BeforeFork(), PyOS_AfterFork_Parent() and PyOS_AfterFork_Child().

void PyOS_AfterFork()

Function to update some internal state after a process fork; this should be called in the new process if the Python interpreter will continue to be used. If a new executable is loaded into the new process, this function does not need to be called.

버전 3.7부터 폐지: This function is superseded by PyOS_AfterFork_Child().

int PyOS_CheckStack()

Return true when the interpreter runs out of stack space. This is a reliable check, but is only available when USE_STACKCHECK is defined (currently on Windows using the Microsoft Visual C++ compiler). USE_STACKCHECK will be defined automatically; you should never change the definition in your own code.

PyOS_sighandler_t PyOS_getsig(int i)

Return the current signal handler for signal i. This is a thin wrapper around either sigaction() or signal(). Do not call those functions directly! PyOS_sighandler_t is a typedef alias for void (*)(int).

PyOS_sighandler_t PyOS_setsig(int i, PyOS_sighandler_t h)

Set the signal handler for signal i to be h; return the old signal handler. This is a thin wrapper around either sigaction() or signal(). Do not call those functions directly! PyOS_sighandler_t is a typedef alias for void (*)(int).

wchar_t* Py_DecodeLocale(const char* arg, size_t *size)

Decode a byte string from the locale encoding with the surrogateescape error handler: undecodable bytes are decoded as characters in range U+DC80..U+DCFF. If a byte sequence can be decoded as a surrogate character, escape the bytes using the surrogateescape error handler instead of decoding them.

Encoding, highest priority to lowest priority:

UTF-8 on macOS and Android;

UTF-8 if the Python UTF-8 mode is enabled;

ASCII if the LC_CTYPE locale is "C", nl_langinfo(CODESET) returns the ASCII encoding (or an alias), and mbstowcs() and wcstombs() functions uses the ISO-8859-1 encoding.

the current locale encoding.

Return a pointer to a newly allocated wide character string, use PyMem_RawFree() to free the memory. If size is not NULL, write the number of wide characters excluding the null character into *size

Return NULL on decoding error or memory allocation error. If size is not NULL, *size is set to (size_t)-1 on memory error or set to (size_t)-2 on decoding error.

Decoding errors should never happen, unless there is a bug in the C library.

Use the Py_EncodeLocale() function to encode the character string back to a byte string.

더 보기

The PyUnicode_DecodeFSDefaultAndSize() and PyUnicode_DecodeLocaleAndSize() functions.

버전 3.5에 추가.

버전 3.7에서 변경: The function now uses the UTF-8 encoding in the UTF-8 mode.

char* Py_EncodeLocale(const wchar_t *text, size_t *error_pos)

Encode a wide character string to the locale encoding with the surrogateescape error handler: surrogate characters in the range U+DC80..U+DCFF are converted to bytes 0x80..0xFF.

Encoding, highest priority to lowest priority:

UTF-8 on macOS and Android;

UTF-8 if the Python UTF-8 mode is enabled;

ASCII if the LC_CTYPE locale is "C", nl_langinfo(CODESET) returns the ASCII encoding (or an alias), and mbstowcs() and wcstombs() functions uses the ISO-8859-1 encoding.

the current locale encoding.

The function uses the UTF-8 encoding in the Python UTF-8 mode.

Return a pointer to a newly allocated byte string, use PyMem_Free() to free the memory. Return NULL on encoding error or memory allocation error

If error_pos is not NULL, *error_pos is set to (size_t)-1 on success, or set to the index of the invalid character on encoding error.

Use the Py_DecodeLocale() function to decode the bytes string back to a wide character string.

버전 3.7에서 변경: The function now uses the UTF-8 encoding in the UTF-8 mode.

더 보기

The PyUnicode_EncodeFSDefault() and PyUnicode_EncodeLocale() functions.

버전 3.5에 추가.

버전 3.7에서 변경: The function now supports the UTF-8 mode.

System Functions

These are utility functions that make functionality from the sys module accessible to C code. They all work with the current interpreter thread’s sys module’s dict, which is contained in the internal thread state structure.

PyObject *PySys_GetObject(const char *name)

Return value: Borrowed reference.

Return the object name from the sys module or NULL if it does not exist, without setting an exception.

int PySys_SetObject(const char *name, PyObject *v)

Set name in the sys module to v unless v is NULL, in which case name is deleted from the sys module. Returns 0 on success, -1 on error.

void PySys_ResetWarnOptions()

Reset sys.warnoptions to an empty list. This function may be called prior to Py_Initialize().

void PySys_AddWarnOption(const wchar_t *s)

Append s to sys.warnoptions. This function must be called prior to Py_Initialize() in order to affect the warnings filter list.

void PySys_AddWarnOptionUnicode(PyObject *unicode)

Append unicode to sys.warnoptions.

Note: this function is not currently usable from outside the CPython implementation, as it must be called prior to the implicit import of warnings in Py_Initialize() to be effective, but can’t be called until enough of the runtime has been initialized to permit the creation of Unicode objects.

void PySys_SetPath(const wchar_t *path)

Set sys.path to a list object of paths found in path which should be a list of paths separated with the platform’s search path delimiter (: on Unix, ; on Windows).

void PySys_WriteStdout(const char *format, ...)

Write the output string described by format to sys.stdout. No exceptions are raised, even if truncation occurs (see below).

format should limit the total size of the formatted output string to 1000 bytes or less – after 1000 bytes, the output string is truncated. In particular, this means that no unrestricted “%s” formats should occur; these should be limited using “%.<N>s” where <N> is a decimal number calculated so that <N> plus the maximum size of other formatted text does not exceed 1000 bytes. Also watch out for “%f”, which can print hundreds of digits for very large numbers.

If a problem occurs, or sys.stdout is unset, the formatted message is written to the real (C level) stdout.

void PySys_WriteStderr(const char *format, ...)

As PySys_WriteStdout(), but write to sys.stderr or stderr instead.

void PySys_FormatStdout(const char *format, ...)

Function similar to PySys_WriteStdout() but format the message using PyUnicode_FromFormatV() and don’t truncate the message to an arbitrary length.

버전 3.2에 추가.

void PySys_FormatStderr(const char *format, ...)

As PySys_FormatStdout(), but write to sys.stderr or stderr instead.

버전 3.2에 추가.

void PySys_AddXOption(const wchar_t *s)

Parse s as a set of -X options and add them to the current options mapping as returned by PySys_GetXOptions(). This function may be called prior to Py_Initialize().

버전 3.2에 추가.

PyObject *PySys_GetXOptions()

Return value: Borrowed reference.

Return the current dictionary of -X options, similarly to sys._xoptions. On error, NULL is returned and an exception is set.

버전 3.2에 추가.

Process Control

void Py_FatalError(const char *message)

Print a fatal error message and kill the process. No cleanup is performed. This function should only be invoked when a condition is detected that would make it dangerous to continue using the Python interpreter; e.g., when the object administration appears to be corrupted. On Unix, the standard C library function abort() is called which will attempt to produce a core file.

void Py_Exit(int status)

Exit the current process. This calls Py_FinalizeEx() and then calls the standard C library function exit(status). If Py_FinalizeEx() indicates an error, the exit status is set to 120.

버전 3.6에서 변경: Errors from finalization no longer ignored.

int Py_AtExit(void (*func)())

Register a cleanup function to be called by Py_FinalizeEx(). The cleanup function will be called with no arguments and should return no value. At most 32 cleanup functions can be registered. When the registration is successful, Py_AtExit() returns 0; on failure, it returns -1. The cleanup function registered last is called first. Each cleanup function will be called at most once. Since Python’s internal finalization will have completed before the cleanup function, no Python APIs should be called by func.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

유틸리티 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

유틸리티 »

|

모듈 임포트 하기

PyObject* PyImport_ImportModule(const char *name)

Return value: New reference.

This is a simplified interface to PyImport_ImportModuleEx() below, leaving the globals and locals arguments set to NULL and level set to 0. When the name argument contains a dot (when it specifies a submodule of a package), the fromlist argument is set to the list ['*'] so that the return value is the named module rather than the top-level package containing it as would otherwise be the case. (Unfortunately, this has an additional side effect when name in fact specifies a subpackage instead of a submodule: the submodules specified in the package’s __all__ variable are loaded.) Return a new reference to the imported module, or NULL with an exception set on failure. A failing import of a module doesn’t leave the module in sys.modules.

이 함수는 항상 절대 임포트를 사용합니다.

PyObject* PyImport_ImportModuleNoBlock(const char *name)

Return value: New reference.

이 함수는 PyImport_ImportModule()의 폐지된 별칭입니다.

버전 3.3에서 변경: 이 기능은 다른 스레드가 임포트 잠금을 보유한 경우 즉시 실패했었습니다. 그러나 파이썬 3.3에서는, 잠금 방식이 대부분의 목적에서 모듈 단위 잠금으로 전환되었기 때문에, 이 함수의 특수한 동작은 더는 필요하지 않습니다.

PyObject* PyImport_ImportModuleEx(const char *name, PyObject *globals, PyObject *locals, PyObject *fromlist)

Return value: New reference.

모듈을 임포트 합니다. 내장 파이썬 함수 __import__()를 통해 가장 잘 설명할 수 있습니다.

The return value is a new reference to the imported module or top-level package, or NULL with an exception set on failure. Like for __import__(), the return value when a submodule of a package was requested is normally the top-level package, unless a non-empty fromlist was given.

임포트 실패는 PyImport_ImportModule()처럼 불완전한 모듈 객체를 제거합니다.

PyObject* PyImport_ImportModuleLevelObject(PyObject *name, PyObject *globals, PyObject *locals, PyObject *fromlist, int level)

Return value: New reference.

모듈을 임포트 합니다. 표준 __import__() 함수가 이 함수를 직접 호출하기 때문에, 내장 파이썬 함수 __import__()를 통해 가장 잘 설명할 수 있습니다.

The return value is a new reference to the imported module or top-level package, or NULL with an exception set on failure. Like for __import__(), the return value when a submodule of a package was requested is normally the top-level package, unless a non-empty fromlist was given.

버전 3.3에 추가.

PyObject* PyImport_ImportModuleLevel(const char *name, PyObject *globals, PyObject *locals, PyObject *fromlist, int level)

Return value: New reference.

PyImport_ImportModuleLevelObject()와 비슷하지만, name은 유니코드 객체 대신 UTF-8로 인코딩된 문자열입니다.

버전 3.3에서 변경: level의 음수 값은 더는 허용되지 않습니다.

PyObject* PyImport_Import(PyObject *name)

Return value: New reference.

이것은 현재 “임포트 훅 함수”를 호출하는 고수준 인터페이스입니다 (명시적인 level 0을 사용하는데, 절대 임포트를 뜻합니다). 현재 전역의 __builtins__에 있는 __import__() 함수를 호출합니다. 이는 현재 환경에 설치된 임포트 훅을 사용하여 임포트가 수행됨을 의미합니다.

이 함수는 항상 절대 임포트를 사용합니다.

PyObject* PyImport_ReloadModule(PyObject *m)

Return value: New reference.

Reload a module. Return a new reference to the reloaded module, or NULL with an exception set on failure (the module still exists in this case).

PyObject* PyImport_AddModuleObject(PyObject *name)

Return value: Borrowed reference.

Return the module object corresponding to a module name. The name argument may be of the form package.module. First check the modules dictionary if there’s one there, and if not, create a new one and insert it in the modules dictionary. Return NULL with an exception set on failure.

참고

이 함수는 모듈을 로드하거나 임포트 하지 않습니다; 모듈이 아직 로드되지 않았으면, 빈 모듈 객체를 얻게 됩니다. 모듈을 임포트 하려면 PyImport_ImportModule()이나 그 변형 중 하나를 사용하십시오. name에서 점으로 구분된 이름으로 암시된 패키지 구조는 이미 존재하지 않는다면 만들어지지 않습니다.

버전 3.3에 추가.

PyObject* PyImport_AddModule(const char *name)

Return value: Borrowed reference.

PyImport_AddModuleObject()와 비슷하지만, name은 유니코드 객체 대신 UTF-8로 인코딩된 문자열입니다.

PyObject* PyImport_ExecCodeModule(const char *name, PyObject *co)

Return value: New reference.

Given a module name (possibly of the form package.module) and a code object read from a Python bytecode file or obtained from the built-in function compile(), load the module. Return a new reference to the module object, or NULL with an exception set if an error occurred. name is removed from sys.modules in error cases, even if name was already in sys.modules on entry to PyImport_ExecCodeModule(). Leaving incompletely initialized modules in sys.modules is dangerous, as imports of such modules have no way to know that the module object is an unknown (and probably damaged with respect to the module author’s intents) state.

모듈의 __spec__과 __loader__는 아직 설정되지 않았다면 적절한 값으로 설정됩니다. 스펙의 로더는 모듈의 __loader__(설정되었다면)로 설정되고, 그렇지 않으면 SourceFileLoader 의 인스턴스로 설정됩니다.

모듈의 __file__ 어트리뷰트는 코드 객체의 co_filename으로 설정됩니다. 해당한다면, __cached__도 설정됩니다.

이 함수는 이미 임포트 되었다면 모듈을 다시 로드합니다. 모듈을 다시 로드하는 의도된 방법은 PyImport_ReloadModule()을 참조하십시오.

name이 package.module 형식의 점으로 구분된 이름을 가리키면, 이미 만들어지지 않은 패키지 구조는 여전히 만들어지지 않습니다.

PyImport_ExecCodeModuleEx()와 PyImport_ExecCodeModuleWithPathnames()도 참조하십시오.

PyObject* PyImport_ExecCodeModuleEx(const char *name, PyObject *co, const char *pathname)

Return value: New reference.

PyImport_ExecCodeModule()과 유사하지만, 모듈 객체의 __file__ 어트리뷰트는 NULL이 아니라면 pathname으로 설정됩니다.

PyImport_ExecCodeModuleWithPathnames()도 참조하십시오.

PyObject* PyImport_ExecCodeModuleObject(PyObject *name, PyObject *co, PyObject *pathname, PyObject *cpathname)

Return value: New reference.

PyImport_ExecCodeModuleEx()와 유사하지만, 모듈 객체의 __cached__ 어트리뷰트는 NULL이 아니라면 cpathname으로 설정됩니다. 세 가지 함수 중 이것이 선호되는 것입니다.

버전 3.3에 추가.

PyObject* PyImport_ExecCodeModuleWithPathnames(const char *name, PyObject *co, const char *pathname, const char *cpathname)

Return value: New reference.

PyImport_ExecCodeModuleObject()와 유사하지만, name, pathname 및 cpathname은 UTF-8로 인코딩된 문자열입니다. pathname의 값이 NULL로 설정된 경우 어떤 값이 cpathname에서 와야하는지 알아내려고 합니다.

버전 3.2에 추가.

버전 3.3에서 변경: 바이트 코드 경로만 제공되면 소스 경로를 계산할 때 imp.source_from_cache()를 사용합니다.

long PyImport_GetMagicNumber()

파이썬 바이트 코드 파일(일명 .pyc 파일)의 매직 번호(magic number)를 반환합니다. 매직 번호는 바이트 코드 파일의 처음 4바이트에 리틀 엔디안 바이트 순서로 존재해야 합니다. 에러 시 -1을 반환합니다.

버전 3.3에서 변경: 실패 시 -1을 반환합니다.

const char * PyImport_GetMagicTag()

PEP 3147 [https://www.python.org/dev/peps/pep-3147] 형식 파이썬 바이트 코드 파일 이름의 매직 태그 문자열을 반환합니다. sys.implementation.cache_tag의 값은 신뢰할 수 있고 이 함수 대신 사용해야 함에 유의하십시오.

버전 3.2에 추가.

PyObject* PyImport_GetModuleDict()

Return value: Borrowed reference.

모듈 관리에 사용되는 딕셔너리(일명 sys.modules)를 반환합니다. 이것은 인터프리터마다 존재하는 변수임에 유의하십시오.

PyObject* PyImport_GetModule(PyObject *name)

Return value: New reference.

Return the already imported module with the given name. If the module has not been imported yet then returns NULL but does not set an error. Returns NULL and sets an error if the lookup failed.

버전 3.7에 추가.

PyObject* PyImport_GetImporter(PyObject *path)

Return value: New reference.

sys.path/pkg.__path__ 항목 path를 위한 파인더 객체를 반환합니다, sys.path_importer_cache 딕셔너리에서 꺼낼 수도 있습니다. 아직 캐시 되지 않았으면, 경로 항목을 처리할 수 있는 훅이 발견될 때까지 sys.path_hooks를 탐색합니다. 훅이 없으면 None을 반환합니다; 이것은 호출자에게 경로 기반 파인더가 이 경로 항목에 대한 파인더를 찾을 수 없음을 알려줍니다. sys.path_importer_cache에 결과를 캐시 합니다. 파인더 객체에 대한 새로운 참조를 반환합니다.

void _PyImport_Init()

임포트 메커니즘을 초기화합니다. 내부 전용입니다.

void PyImport_Cleanup()

모듈 테이블을 비웁니다. 내부 전용입니다.

void _PyImport_Fini()

임포트 메커니즘을 마무리합니다. 내부 전용입니다.

int PyImport_ImportFrozenModuleObject(PyObject *name)

Return value: New reference.

name이라는 이름의 프로즌 모듈(frozen module)을 로드합니다. 성공하면 1을, 모듈을 찾지 못하면 0을, 초기화에 실패하면 예외를 설정하고 -1을 반환합니다. 로드가 성공할 때 임포트 된 모듈에 액세스하려면 PyImport_ImportModule()을 사용하십시오. (잘못된 이름에 주의하십시오 — 이 함수는 모듈이 이미 임포트 되었을 때 다시 로드합니다.)

버전 3.3에 추가.

버전 3.4에서 변경: __file__ 어트리뷰트는 더는 모듈에 설정되지 않습니다.

int PyImport_ImportFrozenModule(const char *name)

PyImport_ImportFrozenModuleObject()와 비슷하지만, name은 유니코드 객체 대신 UTF-8로 인코딩된 문자열입니다.

struct _frozen

이것은 freeze 유틸리티(파이썬 소스 배포의 Tools/freeze/를 참조하십시오)가 생성한 프로즌 모듈 디스크립터를 위한 구조체 형 정의입니다. Include/import.h에 있는 정의는 다음과 같습니다:

struct _frozen {
    const char *name;
    const unsigned char *code;
    int size;
};

const struct _frozen* PyImport_FrozenModules

This pointer is initialized to point to an array of struct _frozen records, terminated by one whose members are all NULL or zero. When a frozen module is imported, it is searched in this table. Third-party code could play tricks with this to provide a dynamically created collection of frozen modules.

int PyImport_AppendInittab(const char *name, PyObject* (*initfunc)(void))

기존의 내장 모듈 테이블에 단일 모듈을 추가합니다. 이것은 PyImport_ExtendInittab()을 감싸는 편리한 래퍼인데, 테이블을 확장할 수 없으면 -1을 반환합니다. 새 모듈은 name이라는 이름으로 임포트 될 수 있으며, initfunc 함수를 처음 시도한 임포트에서 호출되는 초기화 함수로 사용합니다. Py_Initialize() 전에 호출해야 합니다.

struct _inittab

내장 모듈 목록에 있는 단일 항목을 기술하는 구조체. 각 구조체는 인터프리터에 내장된 모듈의 이름과 초기화 함수를 제공합니다. 이름은 ASCII로 인코딩된 문자열입니다. 파이썬을 내장하는 프로그램은 PyImport_ExtendInittab()과 함께 이러한 구조체의 배열을 사용하여 추가 내장 모듈을 제공 할 수 있습니다. 구조체는 Include/import.h에서 다음과 같이 정의됩니다:

struct _inittab {
    const char *name;           /* ASCII encoded string */
    PyObject* (*initfunc)(void);
};

int PyImport_ExtendInittab(struct _inittab *newtab)

Add a collection of modules to the table of built-in modules. The newtab array must end with a sentinel entry which contains NULL for the name field; failure to provide the sentinel value can result in a memory fault. Returns 0 on success or -1 if insufficient memory could be allocated to extend the internal table. In the event of failure, no modules are added to the internal table. This should be called before Py_Initialize().

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

유틸리티 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

유틸리티 »

|

데이터 마샬링 지원

이러한 루틴은 C 코드가 marshal 모듈과 같은 데이터 형식을 사용하여 직렬화된 객체로 작업 할 수 있도록 합니다. 직렬화 형식으로 데이터를 쓰는 함수와 데이터를 다시 읽는 데 사용할 수 있는 추가 함수가 있습니다. 마샬링 된 데이터를 저장하는 데 사용되는 파일은 바이너리 모드로 열어야 합니다.

숫자 값은 최하위 바이트가 먼저 저장됩니다.

The module supports two versions of the data format: version 0 is the historical version, version 1 shares interned strings in the file, and upon unmarshalling. Version 2 uses a binary format for floating point numbers. Py_MARSHAL_VERSION indicates the current file format (currently 2).

void PyMarshal_WriteLongToFile(long value, FILE *file, int version)

long 정수 value를 file로 마샬합니다. value의 최하위 32비트 만 기록합니다; 기본 long 형의 크기와 관계없이. version은 파일 형식을 나타냅니다.

This function can fail, in which case it sets the error indicator. Use PyErr_Occurred() to check for that.

void PyMarshal_WriteObjectToFile(PyObject *value, FILE *file, int version)

파이썬 객체 value를 file로 마샬합니다. version은 파일 형식을 나타냅니다.

This function can fail, in which case it sets the error indicator. Use PyErr_Occurred() to check for that.

PyObject* PyMarshal_WriteObjectToString(PyObject *value, int version)

Return value: New reference.

마샬된 value 표현을 포함한 바이트열 객체를 반환합니다. version은 파일 형식을 나타냅니다.

다음 함수를 사용하면 마샬된 값을 다시 읽을 수 있습니다.

long PyMarshal_ReadLongFromFile(FILE *file)

읽기 위해 열린 FILE*의 데이터 스트림에서 C long을 반환합니다. 이 함수를 사용하면 long의 기본 크기와 관계없이 32비트 값만 읽을 수 있습니다.

에러 시, 적절한 예외(EOFError)를 설정하고 -1을 반환합니다.

int PyMarshal_ReadShortFromFile(FILE *file)

읽기 위해 열린 FILE*의 데이터 스트림에서 C short를 반환합니다. 이 함수를 사용하면 short의 기본 크기와 관계없이 16비트 값만 읽을 수 있습니다.

에러 시, 적절한 예외(EOFError)를 설정하고 -1을 반환합니다.

PyObject* PyMarshal_ReadObjectFromFile(FILE *file)

Return value: New reference.

읽기 위해 열린 FILE*의 데이터 스트림에서 파이썬 객체를 반환합니다.

On error, sets the appropriate exception (EOFError, ValueError or TypeError) and returns NULL.

PyObject* PyMarshal_ReadLastObjectFromFile(FILE *file)

Return value: New reference.

읽기 위해 열린 FILE*의 데이터 스트림에서 파이썬 객체를 반환합니다. PyMarshal_ReadObjectFromFile()와 달리, 이 함수는 더는 파일에서 객체를 읽지 않을 것이라고 가정함으로써, 파일 데이터를 메모리에 적극적으로 로드 할 수 있고, 파일에서 한 바이트씩 읽는 대신 메모리에 있는 데이터에서 역 직렬화가 작동할 수 있습니다. 파일에서 어떤 것도 읽지 않을 것이라는 확신이 들 경우에만 이 변형을 사용하십시오.

On error, sets the appropriate exception (EOFError, ValueError or TypeError) and returns NULL.

PyObject* PyMarshal_ReadObjectFromString(const char *data, Py_ssize_t len)

Return value: New reference.

data가 가리키는 len 바이트를 포함하는 바이트 버퍼의 데이터 스트림에서 파이썬 객체를 반환합니다.

On error, sets the appropriate exception (EOFError, ValueError or TypeError) and returns NULL.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

유틸리티 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

유틸리티 »

|

Parsing arguments and building values

These functions are useful when creating your own extensions functions and methods. Additional information and examples are available in 파이썬 인터프리터 확장 및 내장.

The first three of these functions described, PyArg_ParseTuple(), PyArg_ParseTupleAndKeywords(), and PyArg_Parse(), all use format strings which are used to tell the function about the expected arguments. The format strings use the same syntax for each of these functions.

Parsing arguments

A format string consists of zero or more “format units.” A format unit describes one Python object; it is usually a single character or a parenthesized sequence of format units. With a few exceptions, a format unit that is not a parenthesized sequence normally corresponds to a single address argument to these functions. In the following description, the quoted form is the format unit; the entry in (round) parentheses is the Python object type that matches the format unit; and the entry in [square] brackets is the type of the C variable(s) whose address should be passed.

Strings and buffers

These formats allow accessing an object as a contiguous chunk of memory. You don’t have to provide raw storage for the returned unicode or bytes area.

In general, when a format sets a pointer to a buffer, the buffer is managed by the corresponding Python object, and the buffer shares the lifetime of this object. You won’t have to release any memory yourself. The only exceptions are es, es#, et and et#.

However, when a Py_buffer structure gets filled, the underlying buffer is locked so that the caller can subsequently use the buffer even inside a Py_BEGIN_ALLOW_THREADS block without the risk of mutable data being resized or destroyed. As a result, you have to call PyBuffer_Release() after you have finished processing the data (or in any early abort case).

Unless otherwise stated, buffers are not NUL-terminated.

Some formats require a read-only bytes-like object, and set a pointer instead of a buffer structure. They work by checking that the object’s PyBufferProcs.bf_releasebuffer field is NULL, which disallows mutable objects such as bytearray.

참고

For all # variants of formats (s#, y#, etc.), the type of the length argument (int or Py_ssize_t) is controlled by defining the macro PY_SSIZE_T_CLEAN before including Python.h. If the macro was defined, length is a Py_ssize_t rather than an int. This behavior will change in a future Python version to only support Py_ssize_t and drop int support. It is best to always define PY_SSIZE_T_CLEAN.

s (str) [const char *]

Convert a Unicode object to a C pointer to a character string. A pointer to an existing string is stored in the character pointer variable whose address you pass. The C string is NUL-terminated. The Python string must not contain embedded null code points; if it does, a ValueError exception is raised. Unicode objects are converted to C strings using 'utf-8' encoding. If this conversion fails, a UnicodeError is raised.

참고

This format does not accept bytes-like objects. If you want to accept filesystem paths and convert them to C character strings, it is preferable to use the O& format with PyUnicode_FSConverter() as converter.

버전 3.5에서 변경: Previously, TypeError was raised when embedded null code points were encountered in the Python string.

s* (str or bytes-like object) [Py_buffer]

This format accepts Unicode objects as well as bytes-like objects. It fills a Py_buffer structure provided by the caller. In this case the resulting C string may contain embedded NUL bytes. Unicode objects are converted to C strings using 'utf-8' encoding.

s# (str, read-only bytes-like object) [const char *, int or Py_ssize_t]

Like s*, except that it doesn’t accept mutable objects. The result is stored into two C variables, the first one a pointer to a C string, the second one its length. The string may contain embedded null bytes. Unicode objects are converted to C strings using 'utf-8' encoding.

z (str or None) [const char *]

Like s, but the Python object may also be None, in which case the C pointer is set to NULL.

z* (str, bytes-like object or None) [Py_buffer]

Like s*, but the Python object may also be None, in which case the buf member of the Py_buffer structure is set to NULL.

z# (str, read-only bytes-like object or None) [const char *, int or Py_ssize_t]

Like s#, but the Python object may also be None, in which case the C pointer is set to NULL.

y (read-only bytes-like object) [const char *]

This format converts a bytes-like object to a C pointer to a character string; it does not accept Unicode objects. The bytes buffer must not contain embedded null bytes; if it does, a ValueError exception is raised.

버전 3.5에서 변경: Previously, TypeError was raised when embedded null bytes were encountered in the bytes buffer.

y* (bytes-like object) [Py_buffer]

This variant on s* doesn’t accept Unicode objects, only bytes-like objects. This is the recommended way to accept binary data.

y# (read-only bytes-like object) [const char *, int or Py_ssize_t]

This variant on s# doesn’t accept Unicode objects, only bytes-like objects.

S (bytes) [PyBytesObject *]

Requires that the Python object is a bytes object, without attempting any conversion. Raises TypeError if the object is not a bytes object. The C variable may also be declared as PyObject*.

Y (bytearray) [PyByteArrayObject *]

Requires that the Python object is a bytearray object, without attempting any conversion. Raises TypeError if the object is not a bytearray object. The C variable may also be declared as PyObject*.

u (str) [const Py_UNICODE *]

Convert a Python Unicode object to a C pointer to a NUL-terminated buffer of Unicode characters. You must pass the address of a Py_UNICODE pointer variable, which will be filled with the pointer to an existing Unicode buffer. Please note that the width of a Py_UNICODE character depends on compilation options (it is either 16 or 32 bits). The Python string must not contain embedded null code points; if it does, a ValueError exception is raised.

버전 3.5에서 변경: Previously, TypeError was raised when embedded null code points were encountered in the Python string.

Deprecated since version 3.3, will be removed in version 4.0: Part of the old-style Py_UNICODE API; please migrate to using PyUnicode_AsWideCharString().

u# (str) [const Py_UNICODE *, int or Py_ssize_t]

This variant on u stores into two C variables, the first one a pointer to a Unicode data buffer, the second one its length. This variant allows null code points.

Deprecated since version 3.3, will be removed in version 4.0: Part of the old-style Py_UNICODE API; please migrate to using PyUnicode_AsWideCharString().

Z (str or None) [const Py_UNICODE *]

Like u, but the Python object may also be None, in which case the Py_UNICODE pointer is set to NULL.

Deprecated since version 3.3, will be removed in version 4.0: Part of the old-style Py_UNICODE API; please migrate to using PyUnicode_AsWideCharString().

Z# (str or None) [const Py_UNICODE *, int or Py_ssize_t]

Like u#, but the Python object may also be None, in which case the Py_UNICODE pointer is set to NULL.

Deprecated since version 3.3, will be removed in version 4.0: Part of the old-style Py_UNICODE API; please migrate to using PyUnicode_AsWideCharString().

U (str) [PyObject *]

Requires that the Python object is a Unicode object, without attempting any conversion. Raises TypeError if the object is not a Unicode object. The C variable may also be declared as PyObject*.

w* (read-write bytes-like object) [Py_buffer]

This format accepts any object which implements the read-write buffer interface. It fills a Py_buffer structure provided by the caller. The buffer may contain embedded null bytes. The caller have to call PyBuffer_Release() when it is done with the buffer.

es (str) [const char *encoding, char **buffer]

This variant on s is used for encoding Unicode into a character buffer. It only works for encoded data without embedded NUL bytes.

This format requires two arguments. The first is only used as input, and must be a const char* which points to the name of an encoding as a NUL-terminated string, or NULL, in which case 'utf-8' encoding is used. An exception is raised if the named encoding is not known to Python. The second argument must be a char**; the value of the pointer it references will be set to a buffer with the contents of the argument text. The text will be encoded in the encoding specified by the first argument.

PyArg_ParseTuple() will allocate a buffer of the needed size, copy the encoded data into this buffer and adjust *buffer to reference the newly allocated storage. The caller is responsible for calling PyMem_Free() to free the allocated buffer after use.

et (str, bytes or bytearray) [const char *encoding, char **buffer]

Same as es except that byte string objects are passed through without recoding them. Instead, the implementation assumes that the byte string object uses the encoding passed in as parameter.

es# (str) [const char *encoding, char **buffer, int or Py_ssize_t *buffer_length]

This variant on s# is used for encoding Unicode into a character buffer. Unlike the es format, this variant allows input data which contains NUL characters.

It requires three arguments. The first is only used as input, and must be a const char* which points to the name of an encoding as a NUL-terminated string, or NULL, in which case 'utf-8' encoding is used. An exception is raised if the named encoding is not known to Python. The second argument must be a char**; the value of the pointer it references will be set to a buffer with the contents of the argument text. The text will be encoded in the encoding specified by the first argument. The third argument must be a pointer to an integer; the referenced integer will be set to the number of bytes in the output buffer.

There are two modes of operation:

If *buffer points a NULL pointer, the function will allocate a buffer of the needed size, copy the encoded data into this buffer and set *buffer to reference the newly allocated storage. The caller is responsible for calling PyMem_Free() to free the allocated buffer after usage.

If *buffer points to a non-NULL pointer (an already allocated buffer), PyArg_ParseTuple() will use this location as the buffer and interpret the initial value of *buffer_length as the buffer size. It will then copy the encoded data into the buffer and NUL-terminate it. If the buffer is not large enough, a ValueError will be set.

In both cases, *buffer_length is set to the length of the encoded data without the trailing NUL byte.

et# (str, bytes or bytearray) [const char *encoding, char **buffer, int or Py_ssize_t *buffer_length]

Same as es# except that byte string objects are passed through without recoding them. Instead, the implementation assumes that the byte string object uses the encoding passed in as parameter.

Numbers

b (int) [unsigned char]

Convert a nonnegative Python integer to an unsigned tiny int, stored in a C unsigned char.

B (int) [unsigned char]

Convert a Python integer to a tiny int without overflow checking, stored in a C unsigned char.

h (int) [short int]

Convert a Python integer to a C short int.

H (int) [unsigned short int]

Convert a Python integer to a C unsigned short int, without overflow checking.

i (int) [int]

Convert a Python integer to a plain C int.

I (int) [unsigned int]

Convert a Python integer to a C unsigned int, without overflow checking.

l (int) [long int]

Convert a Python integer to a C long int.

k (int) [unsigned long]

Convert a Python integer to a C unsigned long without overflow checking.

L (int) [long long]

Convert a Python integer to a C long long.

K (int) [unsigned long long]

Convert a Python integer to a C unsigned long long without overflow checking.

n (int) [Py_ssize_t]

Convert a Python integer to a C Py_ssize_t.

c (bytes or bytearray of length 1) [char]

Convert a Python byte, represented as a bytes or bytearray object of length 1, to a C char.

버전 3.3에서 변경: Allow bytearray objects.

C (str of length 1) [int]

Convert a Python character, represented as a str object of length 1, to a C int.

f (float) [float]

Convert a Python floating point number to a C float.

d (float) [double]

Convert a Python floating point number to a C double.

D (complex) [Py_complex]

Convert a Python complex number to a C Py_complex structure.

Other objects

O (object) [PyObject *]

Store a Python object (without any conversion) in a C object pointer. The C program thus receives the actual object that was passed. The object’s reference count is not increased. The pointer stored is not NULL.

O! (object) [typeobject, PyObject *]

Store a Python object in a C object pointer. This is similar to O, but takes two C arguments: the first is the address of a Python type object, the second is the address of the C variable (of type PyObject*) into which the object pointer is stored. If the Python object does not have the required type, TypeError is raised.

O& (object) [converter, anything]

Convert a Python object to a C variable through a converter function. This takes two arguments: the first is a function, the second is the address of a C variable (of arbitrary type), converted to void *. The converter function in turn is called as follows:

status = converter(object, address);

where object is the Python object to be converted and address is the void* argument that was passed to the PyArg_Parse*() function. The returned status should be 1 for a successful conversion and 0 if the conversion has failed. When the conversion fails, the converter function should raise an exception and leave the content of address unmodified.

If the converter returns Py_CLEANUP_SUPPORTED, it may get called a second time if the argument parsing eventually fails, giving the converter a chance to release any memory that it had already allocated. In this second call, the object parameter will be NULL; address will have the same value as in the original call.

버전 3.1에서 변경: Py_CLEANUP_SUPPORTED was added.

p (bool) [int]

Tests the value passed in for truth (a boolean predicate) and converts the result to its equivalent C true/false integer value. Sets the int to 1 if the expression was true and 0 if it was false. This accepts any valid Python value. See 논리값 검사 for more information about how Python tests values for truth.

버전 3.3에 추가.

(items) (tuple) [matching-items]

The object must be a Python sequence whose length is the number of format units in items. The C arguments must correspond to the individual format units in items. Format units for sequences may be nested.

It is possible to pass “long” integers (integers whose value exceeds the platform’s LONG_MAX) however no proper range checking is done — the most significant bits are silently truncated when the receiving field is too small to receive the value (actually, the semantics are inherited from downcasts in C — your mileage may vary).

A few other characters have a meaning in a format string. These may not occur inside nested parentheses. They are:

|

Indicates that the remaining arguments in the Python argument list are optional. The C variables corresponding to optional arguments should be initialized to their default value — when an optional argument is not specified, PyArg_ParseTuple() does not touch the contents of the corresponding C variable(s).

$

PyArg_ParseTupleAndKeywords() only: Indicates that the remaining arguments in the Python argument list are keyword-only. Currently, all keyword-only arguments must also be optional arguments, so | must always be specified before $ in the format string.

버전 3.3에 추가.

:

The list of format units ends here; the string after the colon is used as the function name in error messages (the “associated value” of the exception that PyArg_ParseTuple() raises).

;

The list of format units ends here; the string after the semicolon is used as the error message instead of the default error message. : and ; mutually exclude each other.

Note that any Python object references which are provided to the caller are borrowed references; do not decrement their reference count!

Additional arguments passed to these functions must be addresses of variables whose type is determined by the format string; these are used to store values from the input tuple. There are a few cases, as described in the list of format units above, where these parameters are used as input values; they should match what is specified for the corresponding format unit in that case.

For the conversion to succeed, the arg object must match the format and the format must be exhausted. On success, the PyArg_Parse*() functions return true, otherwise they return false and raise an appropriate exception. When the PyArg_Parse*() functions fail due to conversion failure in one of the format units, the variables at the addresses corresponding to that and the following format units are left untouched.

API Functions

int PyArg_ParseTuple(PyObject *args, const char *format, ...)

Parse the parameters of a function that takes only positional parameters into local variables. Returns true on success; on failure, it returns false and raises the appropriate exception.

int PyArg_VaParse(PyObject *args, const char *format, va_list vargs)

Identical to PyArg_ParseTuple(), except that it accepts a va_list rather than a variable number of arguments.

int PyArg_ParseTupleAndKeywords(PyObject *args, PyObject *kw, const char *format, char *keywords[], ...)

Parse the parameters of a function that takes both positional and keyword parameters into local variables. The keywords argument is a NULL-terminated array of keyword parameter names. Empty names denote positional-only parameters. Returns true on success; on failure, it returns false and raises the appropriate exception.

버전 3.6에서 변경: Added support for positional-only parameters.

int PyArg_VaParseTupleAndKeywords(PyObject *args, PyObject *kw, const char *format, char *keywords[], va_list vargs)

Identical to PyArg_ParseTupleAndKeywords(), except that it accepts a va_list rather than a variable number of arguments.

int PyArg_ValidateKeywordArguments(PyObject *)

Ensure that the keys in the keywords argument dictionary are strings. This is only needed if PyArg_ParseTupleAndKeywords() is not used, since the latter already does this check.

버전 3.2에 추가.

int PyArg_Parse(PyObject *args, const char *format, ...)

Function used to deconstruct the argument lists of “old-style” functions — these are functions which use the METH_OLDARGS parameter parsing method, which has been removed in Python 3. This is not recommended for use in parameter parsing in new code, and most code in the standard interpreter has been modified to no longer use this for that purpose. It does remain a convenient way to decompose other tuples, however, and may continue to be used for that purpose.

int PyArg_UnpackTuple(PyObject *args, const char *name, Py_ssize_t min, Py_ssize_t max, ...)

A simpler form of parameter retrieval which does not use a format string to specify the types of the arguments. Functions which use this method to retrieve their parameters should be declared as METH_VARARGS in function or method tables. The tuple containing the actual parameters should be passed as args; it must actually be a tuple. The length of the tuple must be at least min and no more than max; min and max may be equal. Additional arguments must be passed to the function, each of which should be a pointer to a PyObject* variable; these will be filled in with the values from args; they will contain borrowed references. The variables which correspond to optional parameters not given by args will not be filled in; these should be initialized by the caller. This function returns true on success and false if args is not a tuple or contains the wrong number of elements; an exception will be set if there was a failure.

This is an example of the use of this function, taken from the sources for the _weakref helper module for weak references:

static PyObject *
weakref_ref(PyObject *self, PyObject *args)
{
    PyObject *object;
    PyObject *callback = NULL;
    PyObject *result = NULL;

    if (PyArg_UnpackTuple(args, "ref", 1, 2, &object, &callback)) {
        result = PyWeakref_NewRef(object, callback);
    }
    return result;
}

The call to PyArg_UnpackTuple() in this example is entirely equivalent to this call to PyArg_ParseTuple():

PyArg_ParseTuple(args, "O|O:ref", &object, &callback)

Building values

PyObject* Py_BuildValue(const char *format, ...)

Return value: New reference.

Create a new value based on a format string similar to those accepted by the PyArg_Parse*() family of functions and a sequence of values. Returns the value or NULL in the case of an error; an exception will be raised if NULL is returned.

Py_BuildValue() does not always build a tuple. It builds a tuple only if its format string contains two or more format units. If the format string is empty, it returns None; if it contains exactly one format unit, it returns whatever object is described by that format unit. To force it to return a tuple of size 0 or one, parenthesize the format string.

When memory buffers are passed as parameters to supply data to build objects, as for the s and s# formats, the required data is copied. Buffers provided by the caller are never referenced by the objects created by Py_BuildValue(). In other words, if your code invokes malloc() and passes the allocated memory to Py_BuildValue(), your code is responsible for calling free() for that memory once Py_BuildValue() returns.

In the following description, the quoted form is the format unit; the entry in (round) parentheses is the Python object type that the format unit will return; and the entry in [square] brackets is the type of the C value(s) to be passed.

The characters space, tab, colon and comma are ignored in format strings (but not within format units such as s#). This can be used to make long format strings a tad more readable.

s (str or None) [const char *]

Convert a null-terminated C string to a Python str object using 'utf-8' encoding. If the C string pointer is NULL, None is used.

s# (str or None) [const char *, int or Py_ssize_t]

Convert a C string and its length to a Python str object using 'utf-8' encoding. If the C string pointer is NULL, the length is ignored and None is returned.

y (bytes) [const char *]

This converts a C string to a Python bytes object. If the C string pointer is NULL, None is returned.

y# (bytes) [const char *, int or Py_ssize_t]

This converts a C string and its lengths to a Python object. If the C string pointer is NULL, None is returned.

z (str or None) [const char *]

Same as s.

z# (str or None) [const char *, int or Py_ssize_t]

Same as s#.

u (str) [const wchar_t *]

Convert a null-terminated wchar_t buffer of Unicode (UTF-16 or UCS-4) data to a Python Unicode object. If the Unicode buffer pointer is NULL, None is returned.

u# (str) [const wchar_t *, int or Py_ssize_t]

Convert a Unicode (UTF-16 or UCS-4) data buffer and its length to a Python Unicode object. If the Unicode buffer pointer is NULL, the length is ignored and None is returned.

U (str or None) [const char *]

Same as s.

U# (str or None) [const char *, int or Py_ssize_t]

Same as s#.

i (int) [int]

Convert a plain C int to a Python integer object.

b (int) [char]

Convert a plain C char to a Python integer object.

h (int) [short int]

Convert a plain C short int to a Python integer object.

l (int) [long int]

Convert a C long int to a Python integer object.

B (int) [unsigned char]

Convert a C unsigned char to a Python integer object.

H (int) [unsigned short int]

Convert a C unsigned short int to a Python integer object.

I (int) [unsigned int]

Convert a C unsigned int to a Python integer object.

k (int) [unsigned long]

Convert a C unsigned long to a Python integer object.

L (int) [long long]

Convert a C long long to a Python integer object.

K (int) [unsigned long long]

Convert a C unsigned long long to a Python integer object.

n (int) [Py_ssize_t]

Convert a C Py_ssize_t to a Python integer.

c (bytes of length 1) [char]

Convert a C int representing a byte to a Python bytes object of length 1.

C (str of length 1) [int]

Convert a C int representing a character to Python str object of length 1.

d (float) [double]

Convert a C double to a Python floating point number.

f (float) [float]

Convert a C float to a Python floating point number.

D (complex) [Py_complex *]

Convert a C Py_complex structure to a Python complex number.

O (object) [PyObject *]

Pass a Python object untouched (except for its reference count, which is incremented by one). If the object passed in is a NULL pointer, it is assumed that this was caused because the call producing the argument found an error and set an exception. Therefore, Py_BuildValue() will return NULL but won’t raise an exception. If no exception has been raised yet, SystemError is set.

S (object) [PyObject *]

Same as O.

N (object) [PyObject *]

Same as O, except it doesn’t increment the reference count on the object. Useful when the object is created by a call to an object constructor in the argument list.

O& (object) [converter, anything]

Convert anything to a Python object through a converter function. The function is called with anything (which should be compatible with void *) as its argument and should return a “new” Python object, or NULL if an error occurred.

(items) (tuple) [matching-items]

Convert a sequence of C values to a Python tuple with the same number of items.

[items] (list) [matching-items]

Convert a sequence of C values to a Python list with the same number of items.

{items} (dict) [matching-items]

Convert a sequence of C values to a Python dictionary. Each pair of consecutive C values adds one item to the dictionary, serving as key and value, respectively.

If there is an error in the format string, the SystemError exception is set and NULL returned.

PyObject* Py_VaBuildValue(const char *format, va_list vargs)

Return value: New reference.

Identical to Py_BuildValue(), except that it accepts a va_list rather than a variable number of arguments.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

유틸리티 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

유틸리티 »

|

문자열 변환과 포매팅

숫자 변환과 포맷된 문자열 출력을 위한 함수.

int PyOS_snprintf(char *str, size_t size, const char *format, ...)

포맷 문자열 format 과 추가 인자에 따라 size 바이트를 넘지 않도록 str로 출력합니다. 유닉스 매뉴얼 페이지 snprintf(2)를 보십시오.

int PyOS_vsnprintf(char *str, size_t size, const char *format, va_list va)

포맷 문자열 format 과 가변 인자 목록 va에 따라 size 바이트를 넘지 않도록 str로 출력합니다. 유닉스 매뉴얼 페이지 vsnprintf(2)를 보십시오.

PyOS_snprintf()와 PyOS_vsnprintf()는 표준 C 라이브러리 함수 snprintf()와 vsnprintf()를 감쌉니다. 그들의 목적은 경계 조건에서 표준 C 함수가 제공하지 않는 수준의 일관된 동작을 보장하는 것입니다.

래퍼는 반환 시 str*[*size-1]이 항상 '\0'이 되도록 합니다. str에 size 바이트(후행 '\0' 포함)를 초과해서 쓰지 않습니다. 두 함수 모두 str != NULL, size > 0 및 format != NULL을 요구합니다.

If the platform doesn’t have vsnprintf() and the buffer size needed to avoid truncation exceeds size by more than 512 bytes, Python aborts with a Py_FatalError().

이 함수들의 반환 값(rv)은 다음과 같이 해석되어야 합니다:

0 <= rv < size 일 때, 출력 변환에 성공했으며 rv 문자가 str에 기록되었습니다 (str*[*rv]의 후행 '\0' 바이트 제외).

rv >= size 일 때, 출력 변환이 잘렸고 성공하려면 rv + 1 바이트의 버퍼가 필요합니다. str*[*size-1]은 이때 '\0'입니다.

rv < 0 일 때, “뭔가 나쁜 일이 일어났습니다.” 이때도 str*[*size-1]은 '\0'이지만, str의 나머지는 정의되지 않습니다. 에러의 정확한 원인은 하부 플랫폼에 따라 다릅니다.

다음 함수는 로케일 독립적인 문자열에서 숫자로의 변환을 제공합니다.

double PyOS_string_to_double(const char *s, char **endptr, PyObject *overflow_exception)

문자열 s를 double로 변환하고, 실패 시 파이썬 예외를 발생시킵니다. 허용되는 문자열 집합은 s가 선행이나 후행 공백을 가질 수 없다는 점을 제외하고는 파이썬의 float() 생성자가 허용하는 문자열 집합에 대응합니다. 변환은 현재 로케일과 독립적입니다.

endptr이 NULL이면, 전체 문자열을 변환합니다. 문자열이 부동 소수점 숫자의 유효한 표현이 아니면 ValueError를 발생시키고 -1.0을 반환합니다.

endptr이 NULL이 아니면, 가능한 한 많은 문자열을 변환하고 *endptr이 변환되지 않은 첫 번째 문자를 가리키도록 설정합니다. 문자열의 초기 세그먼트가 부동 소수점 숫자의 유효한 표현이 아니면, *endptr이 문자열의 시작을 가리키도록 설정하고, ValueError를 발생시키고 -1.0을 반환합니다.

s가 float에 저장하기에 너무 큰 값을 나타낼 때 (예를 들어, 여러 플랫폼에서 "1e500"가 그런 문자열입니다), overflow_exception가 NULL이면 (적절한 부호와 함께) Py_HUGE_VAL을 반환하고, 어떤 예외도 설정하지 않습니다. 그렇지 않으면, overflow_exception은 파이썬 예외 객체를 가리켜야 합니다; 그 예외를 발생시키고 -1.0를 반환합니다. 두 경우 모두, 변환된 값 다음의 첫 번째 문자를 가리키도록 *endptr을 설정합니다.

변환 중 다른 에러가 발생하면 (예를 들어 메모리 부족 에러), 적절한 파이썬 예외를 설정하고 -1.0을 반환합니다.

버전 3.1에 추가.

char* PyOS_double_to_string(double val, char format_code, int precision, int flags, int *ptype)

제공된 format_code, precision 및 flags를 사용하여 double val을 문자열로 변환합니다.

format_code는 'e', 'E', 'f', 'F', 'g', 'G' 또는 'r' 중 하나여야 합니다. 'r'의 경우, 제공된 precision은 0이어야 하며 무시됩니다. 'r' 포맷 코드는 표준 repr() 형식을 지정합니다.

flags can be zero or more of the values Py_DTSF_SIGN, Py_DTSF_ADD_DOT_0, or Py_DTSF_ALT, or-ed together:

Py_DTSF_SIGN means to always precede the returned string with a sign character, even if val is non-negative.

Py_DTSF_ADD_DOT_0 means to ensure that the returned string will not look like an integer.

Py_DTSF_ALT means to apply “alternate” formatting rules. See the documentation for the PyOS_snprintf() '#' specifier for details.

If ptype is non-NULL, then the value it points to will be set to one of Py_DTST_FINITE, Py_DTST_INFINITE, or Py_DTST_NAN, signifying that val is a finite number, an infinite number, or not a number, respectively.

The return value is a pointer to buffer with the converted string or NULL if the conversion failed. The caller is responsible for freeing the returned string by calling PyMem_Free().

버전 3.1에 추가.

int PyOS_stricmp(const char *s1, const char *s2)

대소 문자 구분 없는 문자열 비교. 이 함수는 대소 문자를 무시한다는 점만 제외하면 strcmp()와 거의 같게 작동합니다.

int PyOS_strnicmp(const char *s1, const char *s2, Py_ssize_t  size)

대소 문자 구분 없는 문자열 비교. 이 함수는 대소 문자를 무시한다는 점만 제외하면 strncmp()와 거의 같게 작동합니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

유틸리티 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

유틸리티 »

|

리플렉션

PyObject* PyEval_GetBuiltins()

Return value: Borrowed reference.

현재 실행 프레임이나 현재 실행 중인 프레임이 없으면 스레드 상태의 인터프리터의 builtins의 딕셔너리를 반환합니다.

PyObject* PyEval_GetLocals()

Return value: Borrowed reference.

Return a dictionary of the local variables in the current execution frame, or NULL if no frame is currently executing.

PyObject* PyEval_GetGlobals()

Return value: Borrowed reference.

Return a dictionary of the global variables in the current execution frame, or NULL if no frame is currently executing.

PyFrameObject* PyEval_GetFrame()

Return value: Borrowed reference.

Return the current thread state’s frame, which is NULL if no frame is currently executing.

int PyFrame_GetLineNumber(PyFrameObject *frame)

frame이 현재 실행 중인 줄 번호를 반환합니다.

const char* PyEval_GetFuncName(PyObject *func)

func가 함수, 클래스 또는 인스턴스 객체면 func의 이름을 반환하고, 그렇지 않으면 func의 형의 이름을 반환합니다.

const char* PyEval_GetFuncDesc(PyObject *func)

func의 형에 따라 설명 문자열을 반환합니다. 반환 값에는 함수 및 메서드의 “()”, ” constructor”, ” instance” 및 ” object” 가 포함됩니다. PyEval_GetFuncName()의 결과와 이어붙이면 func의 설명이 됩니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

유틸리티 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

유틸리티 »

|

코덱 등록소와 지원 함수

int PyCodec_Register(PyObject *search_function)

새로운 코덱 검색 함수를 등록합니다.

부작용으로, 아직 로드되지 않았다면, encodings 패키지를 로드하여 항상 검색 함수 목록의 첫 번째 항목이 되도록 합니다.

int PyCodec_KnownEncoding(const char *encoding)

지정된 encoding에 대해 등록된 코덱이 있는지에 따라 1 이나 0을 반환합니다. 이 함수는 항상 성공합니다.

PyObject* PyCodec_Encode(PyObject *object, const char *encoding, const char *errors)

Return value: New reference.

일반 코덱 기반 인코딩 API.

object is passed through the encoder function found for the given encoding using the error handling method defined by errors. errors may be NULL to use the default method defined for the codec. Raises a LookupError if no encoder can be found.

PyObject* PyCodec_Decode(PyObject *object, const char *encoding, const char *errors)

Return value: New reference.

일반 코덱 기반 디코딩 API.

object is passed through the decoder function found for the given encoding using the error handling method defined by errors. errors may be NULL to use the default method defined for the codec. Raises a LookupError if no encoder can be found.

코덱 조회 API

In the following functions, the encoding string is looked up converted to all lower-case characters, which makes encodings looked up through this mechanism effectively case-insensitive. If no codec is found, a KeyError is set and NULL returned.

PyObject* PyCodec_Encoder(const char *encoding)

Return value: New reference.

주어진 encoding에 대한 인코더 함수를 가져옵니다.

PyObject* PyCodec_Decoder(const char *encoding)

Return value: New reference.

주어진 encoding에 대한 디코더 함수를 가져옵니다.

PyObject* PyCodec_IncrementalEncoder(const char *encoding, const char *errors)

Return value: New reference.

지정된 encoding에 대한 IncrementalEncoder 객체를 가져옵니다.

PyObject* PyCodec_IncrementalDecoder(const char *encoding, const char *errors)

Return value: New reference.

지정된 encoding에 대한 IncrementalDecoder 객체를 가져옵니다.

PyObject* PyCodec_StreamReader(const char *encoding, PyObject *stream, const char *errors)

Return value: New reference.

지정된 encoding에 대한 StreamReader 팩토리 함수를 가져옵니다.

PyObject* PyCodec_StreamWriter(const char *encoding, PyObject *stream, const char *errors)

Return value: New reference.

지정된 encoding에 대한 StreamWriter 팩토리 함수를 가져옵니다.

유니코드 인코딩 에러 처리기용 등록소 API

int PyCodec_RegisterError(const char *name, PyObject *error)

지정된 name 으로 에러 처리 콜백 함수 error를 등록합니다. 코덱이 인코딩할 수 없는 문자/디코딩할 수 없는 바이트열을 발견하고, 인코드/디코드 함수를 호출할 때 name이 error 매개 변수로 지정되었을 때 이 콜백 함수를 호출합니다.

콜백은 하나의 인자로 UnicodeEncodeError, UnicodeDecodeError 또는 UnicodeTranslateError의 인스턴스를 받아들이는데, 문제가 되는 문자나 바이트의 시퀀스와 이들의 원본 문자열에서의 오프셋에 대한 정보를 담고 있습니다 (이 정보를 추출하는 함수는 Unicode Exception Objects를 참조하세요). 콜백은 주어진 예외를 발생시키거나, 문제가 있는 시퀀스의 대체와 원래 문자열에서 인코딩/디코딩을 다시 시작해야 하는 오프셋을 제공하는 정수를 포함하는 두 항목 튜플을 반환해야 합니다.

성공하면 0을, 에러면 -1을 반환합니다.

PyObject* PyCodec_LookupError(const char *name)

Return value: New reference.

Lookup the error handling callback function registered under name. As a special case NULL can be passed, in which case the error handling callback for “strict” will be returned.

PyObject* PyCodec_StrictErrors(PyObject *exc)

Return value: Always NULL.

exc를 예외로 발생시킵니다.

PyObject* PyCodec_IgnoreErrors(PyObject *exc)

Return value: New reference.

잘못된 입력을 건너뛰고, 유니코드 에러를 무시합니다.

PyObject* PyCodec_ReplaceErrors(PyObject *exc)

Return value: New reference.

유니코드 인코딩 에러를 ? 나 U+FFFD로 치환합니다.

PyObject* PyCodec_XMLCharRefReplaceErrors(PyObject *exc)

Return value: New reference.

유니코드 인코딩 에러를 XML 문자 참조로 치환합니다.

PyObject* PyCodec_BackslashReplaceErrors(PyObject *exc)

Return value: New reference.

유니코드 인코딩 에러를 백 슬래시 이스케이프(\x, \u 및 \U)로 치환합니다.

PyObject* PyCodec_NameReplaceErrors(PyObject *exc)

Return value: New reference.

유니코드 인코딩 에러를 \N{...} 이스케이프로 치환합니다.

버전 3.5에 추가.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

유틸리티 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

|

추상 객체 계층

이 장의 함수는 객체의 형과 무관하게, 혹은 광범위한 종류의 객체 형의 (예를 들어, 모든 숫자 형 또는 모든 시퀀스 형) 파이썬 객체와 상호 작용합니다. 적용되지 않는 객체 형에 사용되면, 파이썬 예외가 발생합니다.

PyList_New()로 만들었지만, 항목이 아직 NULL이 아닌 값으로 설정되지 않은 리스트 객체와 같이, 제대로 초기화되지 않은 객체에 대해서는 이 함수를 사용할 수 없습니다.

Object Protocol

숫자 프로토콜

시퀀스 프로토콜

매핑 프로토콜

이터레이터 프로토콜

버퍼 프로토콜

버퍼 구조체

버퍼 요청 유형

요청 독립적 필드

readonly, format

shape, strides, suboffsets

연속성 요청

복합 요청

복잡한 배열

NumPy-스타일: shape과 strides

PIL-스타일: shape, strides 및 suboffsets

버퍼 관련 함수

낡은 버퍼 프로토콜

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

추상 객체 계층 »

|

Object Protocol

PyObject* Py_NotImplemented

The NotImplemented singleton, used to signal that an operation is not implemented for the given type combination.

Py_RETURN_NOTIMPLEMENTED

Properly handle returning Py_NotImplemented from within a C function (that is, increment the reference count of NotImplemented and return it).

int PyObject_Print(PyObject *o, FILE *fp, int flags)

Print an object o, on file fp. Returns -1 on error. The flags argument is used to enable certain printing options. The only option currently supported is Py_PRINT_RAW; if given, the str() of the object is written instead of the repr().

int PyObject_HasAttr(PyObject *o, PyObject *attr_name)

Returns 1 if o has the attribute attr_name, and 0 otherwise. This is equivalent to the Python expression hasattr(o, attr_name). This function always succeeds.

Note that exceptions which occur while calling __getattr__() and __getattribute__() methods will get suppressed. To get error reporting use PyObject_GetAttr() instead.

int PyObject_HasAttrString(PyObject *o, const char *attr_name)

Returns 1 if o has the attribute attr_name, and 0 otherwise. This is equivalent to the Python expression hasattr(o, attr_name). This function always succeeds.

Note that exceptions which occur while calling __getattr__() and __getattribute__() methods and creating a temporary string object will get suppressed. To get error reporting use PyObject_GetAttrString() instead.

PyObject* PyObject_GetAttr(PyObject *o, PyObject *attr_name)

Return value: New reference.

Retrieve an attribute named attr_name from object o. Returns the attribute value on success, or NULL on failure. This is the equivalent of the Python expression o.attr_name.

PyObject* PyObject_GetAttrString(PyObject *o, const char *attr_name)

Return value: New reference.

Retrieve an attribute named attr_name from object o. Returns the attribute value on success, or NULL on failure. This is the equivalent of the Python expression o.attr_name.

PyObject* PyObject_GenericGetAttr(PyObject *o, PyObject *name)

Return value: New reference.

Generic attribute getter function that is meant to be put into a type object’s tp_getattro slot. It looks for a descriptor in the dictionary of classes in the object’s MRO as well as an attribute in the object’s __dict__ (if present). As outlined in 디스크립터 구현하기, data descriptors take preference over instance attributes, while non-data descriptors don’t. Otherwise, an AttributeError is raised.

int PyObject_SetAttr(PyObject *o, PyObject *attr_name, PyObject *v)

Set the value of the attribute named attr_name, for object o, to the value v. Raise an exception and return -1 on failure; return 0 on success. This is the equivalent of the Python statement o.attr_name = v.

If v is NULL, the attribute is deleted, however this feature is deprecated in favour of using PyObject_DelAttr().

int PyObject_SetAttrString(PyObject *o, const char *attr_name, PyObject *v)

Set the value of the attribute named attr_name, for object o, to the value v. Raise an exception and return -1 on failure; return 0 on success. This is the equivalent of the Python statement o.attr_name = v.

If v is NULL, the attribute is deleted, however this feature is deprecated in favour of using PyObject_DelAttrString().

int PyObject_GenericSetAttr(PyObject *o, PyObject *name, PyObject *value)

Generic attribute setter and deleter function that is meant to be put into a type object’s tp_setattro slot. It looks for a data descriptor in the dictionary of classes in the object’s MRO, and if found it takes preference over setting or deleting the attribute in the instance dictionary. Otherwise, the attribute is set or deleted in the object’s __dict__ (if present). On success, 0 is returned, otherwise an AttributeError is raised and -1 is returned.

int PyObject_DelAttr(PyObject *o, PyObject *attr_name)

Delete attribute named attr_name, for object o. Returns -1 on failure. This is the equivalent of the Python statement del o.attr_name.

int PyObject_DelAttrString(PyObject *o, const char *attr_name)

Delete attribute named attr_name, for object o. Returns -1 on failure. This is the equivalent of the Python statement del o.attr_name.

PyObject* PyObject_GenericGetDict(PyObject *o, void *context)

Return value: New reference.

A generic implementation for the getter of a __dict__ descriptor. It creates the dictionary if necessary.

버전 3.3에 추가.

int PyObject_GenericSetDict(PyObject *o, PyObject *value, void *context)

A generic implementation for the setter of a __dict__ descriptor. This implementation does not allow the dictionary to be deleted.

버전 3.3에 추가.

PyObject* PyObject_RichCompare(PyObject *o1, PyObject *o2, int opid)

Return value: New reference.

Compare the values of o1 and o2 using the operation specified by opid, which must be one of Py_LT, Py_LE, Py_EQ, Py_NE, Py_GT, or Py_GE, corresponding to <, <=, ==, !=, >, or >= respectively. This is the equivalent of the Python expression o1 op o2, where op is the operator corresponding to opid. Returns the value of the comparison on success, or NULL on failure.

int PyObject_RichCompareBool(PyObject *o1, PyObject *o2, int opid)

Compare the values of o1 and o2 using the operation specified by opid, which must be one of Py_LT, Py_LE, Py_EQ, Py_NE, Py_GT, or Py_GE, corresponding to <, <=, ==, !=, >, or >= respectively. Returns -1 on error, 0 if the result is false, 1 otherwise. This is the equivalent of the Python expression o1 op o2, where op is the operator corresponding to opid.

참고

If o1 and o2 are the same object, PyObject_RichCompareBool() will always return 1 for Py_EQ and 0 for Py_NE.

PyObject* PyObject_Repr(PyObject *o)

Return value: New reference.

Compute a string representation of object o. Returns the string representation on success, NULL on failure. This is the equivalent of the Python expression repr(o). Called by the repr() built-in function.

버전 3.4에서 변경: This function now includes a debug assertion to help ensure that it does not silently discard an active exception.

PyObject* PyObject_ASCII(PyObject *o)

Return value: New reference.

As PyObject_Repr(), compute a string representation of object o, but escape the non-ASCII characters in the string returned by PyObject_Repr() with \x, \u or \U escapes. This generates a string similar to that returned by PyObject_Repr() in Python 2. Called by the ascii() built-in function.

PyObject* PyObject_Str(PyObject *o)

Return value: New reference.

Compute a string representation of object o. Returns the string representation on success, NULL on failure. This is the equivalent of the Python expression str(o). Called by the str() built-in function and, therefore, by the print() function.

버전 3.4에서 변경: This function now includes a debug assertion to help ensure that it does not silently discard an active exception.

PyObject* PyObject_Bytes(PyObject *o)

Return value: New reference.

Compute a bytes representation of object o. NULL is returned on failure and a bytes object on success. This is equivalent to the Python expression bytes(o), when o is not an integer. Unlike bytes(o), a TypeError is raised when o is an integer instead of a zero-initialized bytes object.

int PyObject_IsSubclass(PyObject *derived, PyObject *cls)

Return 1 if the class derived is identical to or derived from the class cls, otherwise return 0. In case of an error, return -1.

If cls is a tuple, the check will be done against every entry in cls. The result will be 1 when at least one of the checks returns 1, otherwise it will be 0.

If cls has a __subclasscheck__() method, it will be called to determine the subclass status as described in PEP 3119 [https://www.python.org/dev/peps/pep-3119]. Otherwise, derived is a subclass of cls if it is a direct or indirect subclass, i.e. contained in cls.__mro__.

Normally only class objects, i.e. instances of type or a derived class, are considered classes. However, objects can override this by having a __bases__ attribute (which must be a tuple of base classes).

int PyObject_IsInstance(PyObject *inst, PyObject *cls)

Return 1 if inst is an instance of the class cls or a subclass of cls, or 0 if not. On error, returns -1 and sets an exception.

If cls is a tuple, the check will be done against every entry in cls. The result will be 1 when at least one of the checks returns 1, otherwise it will be 0.

If cls has a __instancecheck__() method, it will be called to determine the subclass status as described in PEP 3119 [https://www.python.org/dev/peps/pep-3119]. Otherwise, inst is an instance of cls if its class is a subclass of cls.

An instance inst can override what is considered its class by having a __class__ attribute.

An object cls can override if it is considered a class, and what its base classes are, by having a __bases__ attribute (which must be a tuple of base classes).

int PyCallable_Check(PyObject *o)

Determine if the object o is callable. Return 1 if the object is callable and 0 otherwise. This function always succeeds.

PyObject* PyObject_Call(PyObject *callable, PyObject *args, PyObject *kwargs)

Return value: New reference.

Call a callable Python object callable, with arguments given by the tuple args, and named arguments given by the dictionary kwargs.

args must not be NULL, use an empty tuple if no arguments are needed. If no named arguments are needed, kwargs can be NULL.

Return the result of the call on success, or raise an exception and return NULL on failure.

This is the equivalent of the Python expression: callable(*args, **kwargs).

PyObject* PyObject_CallObject(PyObject *callable, PyObject *args)

Return value: New reference.

Call a callable Python object callable, with arguments given by the tuple args. If no arguments are needed, then args can be NULL.

Return the result of the call on success, or raise an exception and return NULL on failure.

This is the equivalent of the Python expression: callable(*args).

PyObject* PyObject_CallFunction(PyObject *callable, const char *format, ...)

Return value: New reference.

Call a callable Python object callable, with a variable number of C arguments. The C arguments are described using a Py_BuildValue() style format string. The format can be NULL, indicating that no arguments are provided.

Return the result of the call on success, or raise an exception and return NULL on failure.

This is the equivalent of the Python expression: callable(*args).

Note that if you only pass PyObject * args, PyObject_CallFunctionObjArgs() is a faster alternative.

버전 3.4에서 변경: The type of format was changed from char *.

PyObject* PyObject_CallMethod(PyObject *obj, const char *name, const char *format, ...)

Return value: New reference.

Call the method named name of object obj with a variable number of C arguments. The C arguments are described by a Py_BuildValue() format string that should produce a tuple.

The format can be NULL, indicating that no arguments are provided.

Return the result of the call on success, or raise an exception and return NULL on failure.

This is the equivalent of the Python expression: obj.name(arg1, arg2, ...).

Note that if you only pass PyObject * args, PyObject_CallMethodObjArgs() is a faster alternative.

버전 3.4에서 변경: The types of name and format were changed from char *.

PyObject* PyObject_CallFunctionObjArgs(PyObject *callable, ..., NULL)

Return value: New reference.

Call a callable Python object callable, with a variable number of PyObject* arguments. The arguments are provided as a variable number of parameters followed by NULL.

Return the result of the call on success, or raise an exception and return NULL on failure.

This is the equivalent of the Python expression: callable(arg1, arg2, ...).

PyObject* PyObject_CallMethodObjArgs(PyObject *obj, PyObject *name, ..., NULL)

Return value: New reference.

Calls a method of the Python object obj, where the name of the method is given as a Python string object in name. It is called with a variable number of PyObject* arguments. The arguments are provided as a variable number of parameters followed by NULL.

Return the result of the call on success, or raise an exception and return NULL on failure.

Py_hash_t PyObject_Hash(PyObject *o)

Compute and return the hash value of an object o. On failure, return -1. This is the equivalent of the Python expression hash(o).

버전 3.2에서 변경: The return type is now Py_hash_t. This is a signed integer the same size as Py_ssize_t.

Py_hash_t PyObject_HashNotImplemented(PyObject *o)

Set a TypeError indicating that type(o) is not hashable and return -1. This function receives special treatment when stored in a tp_hash slot, allowing a type to explicitly indicate to the interpreter that it is not hashable.

int PyObject_IsTrue(PyObject *o)

Returns 1 if the object o is considered to be true, and 0 otherwise. This is equivalent to the Python expression not not o. On failure, return -1.

int PyObject_Not(PyObject *o)

Returns 0 if the object o is considered to be true, and 1 otherwise. This is equivalent to the Python expression not o. On failure, return -1.

PyObject* PyObject_Type(PyObject *o)

Return value: New reference.

When o is non-NULL, returns a type object corresponding to the object type of object o. On failure, raises SystemError and returns NULL. This is equivalent to the Python expression type(o). This function increments the reference count of the return value. There’s really no reason to use this function instead of the common expression o->ob_type, which returns a pointer of type PyTypeObject*, except when the incremented reference count is needed.

int PyObject_TypeCheck(PyObject *o, PyTypeObject *type)

Return true if the object o is of type type or a subtype of type. Both parameters must be non-NULL.

Py_ssize_t PyObject_Size(PyObject *o)

Py_ssize_t PyObject_Length(PyObject *o)

Return the length of object o. If the object o provides either the sequence and mapping protocols, the sequence length is returned. On error, -1 is returned. This is the equivalent to the Python expression len(o).

Py_ssize_t PyObject_LengthHint(PyObject *o, Py_ssize_t default)

Return an estimated length for the object o. First try to return its actual length, then an estimate using __length_hint__(), and finally return the default value. On error return -1. This is the equivalent to the Python expression operator.length_hint(o, default).

버전 3.4에 추가.

PyObject* PyObject_GetItem(PyObject *o, PyObject *key)

Return value: New reference.

Return element of o corresponding to the object key or NULL on failure. This is the equivalent of the Python expression o[key].

int PyObject_SetItem(PyObject *o, PyObject *key, PyObject *v)

Map the object key to the value v. Raise an exception and return -1 on failure; return 0 on success. This is the equivalent of the Python statement o[key] = v.

int PyObject_DelItem(PyObject *o, PyObject *key)

Remove the mapping for the object key from the object o. Return -1 on failure. This is equivalent to the Python statement del o[key].

PyObject* PyObject_Dir(PyObject *o)

Return value: New reference.

This is equivalent to the Python expression dir(o), returning a (possibly empty) list of strings appropriate for the object argument, or NULL if there was an error. If the argument is NULL, this is like the Python dir(), returning the names of the current locals; in this case, if no execution frame is active then NULL is returned but PyErr_Occurred() will return false.

PyObject* PyObject_GetIter(PyObject *o)

Return value: New reference.

This is equivalent to the Python expression iter(o). It returns a new iterator for the object argument, or the object itself if the object is already an iterator. Raises TypeError and returns NULL if the object cannot be iterated.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

추상 객체 계층 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

추상 객체 계층 »

|

숫자 프로토콜

int PyNumber_Check(PyObject *o)

객체 o가 숫자 프로토콜을 제공하면 1을 반환하고, 그렇지 않으면 거짓을 반환합니다. 이 함수는 항상 성공합니다.

PyObject* PyNumber_Add(PyObject *o1, PyObject *o2)

Return value: New reference.

Returns the result of adding o1 and o2, or NULL on failure. This is the equivalent of the Python expression o1 + o2.

PyObject* PyNumber_Subtract(PyObject *o1, PyObject *o2)

Return value: New reference.

Returns the result of subtracting o2 from o1, or NULL on failure. This is the equivalent of the Python expression o1 - o2.

PyObject* PyNumber_Multiply(PyObject *o1, PyObject *o2)

Return value: New reference.

Returns the result of multiplying o1 and o2, or NULL on failure. This is the equivalent of the Python expression o1 * o2.

PyObject* PyNumber_MatrixMultiply(PyObject *o1, PyObject *o2)

Return value: New reference.

Returns the result of matrix multiplication on o1 and o2, or NULL on failure. This is the equivalent of the Python expression o1 @ o2.

버전 3.5에 추가.

PyObject* PyNumber_FloorDivide(PyObject *o1, PyObject *o2)

Return value: New reference.

Return the floor of o1 divided by o2, or NULL on failure. This is equivalent to the “classic” division of integers.

PyObject* PyNumber_TrueDivide(PyObject *o1, PyObject *o2)

Return value: New reference.

Return a reasonable approximation for the mathematical value of o1 divided by o2, or NULL on failure. The return value is “approximate” because binary floating point numbers are approximate; it is not possible to represent all real numbers in base two. This function can return a floating point value when passed two integers.

PyObject* PyNumber_Remainder(PyObject *o1, PyObject *o2)

Return value: New reference.

Returns the remainder of dividing o1 by o2, or NULL on failure. This is the equivalent of the Python expression o1 % o2.

PyObject* PyNumber_Divmod(PyObject *o1, PyObject *o2)

Return value: New reference.

See the built-in function divmod(). Returns NULL on failure. This is the equivalent of the Python expression divmod(o1, o2).

PyObject* PyNumber_Power(PyObject *o1, PyObject *o2, PyObject *o3)

Return value: New reference.

See the built-in function pow(). Returns NULL on failure. This is the equivalent of the Python expression pow(o1, o2, o3), where o3 is optional. If o3 is to be ignored, pass Py_None in its place (passing NULL for o3 would cause an illegal memory access).

PyObject* PyNumber_Negative(PyObject *o)

Return value: New reference.

Returns the negation of o on success, or NULL on failure. This is the equivalent of the Python expression -o.

PyObject* PyNumber_Positive(PyObject *o)

Return value: New reference.

Returns o on success, or NULL on failure. This is the equivalent of the Python expression +o.

PyObject* PyNumber_Absolute(PyObject *o)

Return value: New reference.

Returns the absolute value of o, or NULL on failure. This is the equivalent of the Python expression abs(o).

PyObject* PyNumber_Invert(PyObject *o)

Return value: New reference.

Returns the bitwise negation of o on success, or NULL on failure. This is the equivalent of the Python expression ~o.

PyObject* PyNumber_Lshift(PyObject *o1, PyObject *o2)

Return value: New reference.

Returns the result of left shifting o1 by o2 on success, or NULL on failure. This is the equivalent of the Python expression o1 << o2.

PyObject* PyNumber_Rshift(PyObject *o1, PyObject *o2)

Return value: New reference.

Returns the result of right shifting o1 by o2 on success, or NULL on failure. This is the equivalent of the Python expression o1 >> o2.

PyObject* PyNumber_And(PyObject *o1, PyObject *o2)

Return value: New reference.

Returns the “bitwise and” of o1 and o2 on success and NULL on failure. This is the equivalent of the Python expression o1 & o2.

PyObject* PyNumber_Xor(PyObject *o1, PyObject *o2)

Return value: New reference.

Returns the “bitwise exclusive or” of o1 by o2 on success, or NULL on failure. This is the equivalent of the Python expression o1 ^ o2.

PyObject* PyNumber_Or(PyObject *o1, PyObject *o2)

Return value: New reference.

Returns the “bitwise or” of o1 and o2 on success, or NULL on failure. This is the equivalent of the Python expression o1 | o2.

PyObject* PyNumber_InPlaceAdd(PyObject *o1, PyObject *o2)

Return value: New reference.

Returns the result of adding o1 and o2, or NULL on failure. The operation is done in-place when o1 supports it. This is the equivalent of the Python statement o1 += o2.

PyObject* PyNumber_InPlaceSubtract(PyObject *o1, PyObject *o2)

Return value: New reference.

Returns the result of subtracting o2 from o1, or NULL on failure. The operation is done in-place when o1 supports it. This is the equivalent of the Python statement o1 -= o2.

PyObject* PyNumber_InPlaceMultiply(PyObject *o1, PyObject *o2)

Return value: New reference.

Returns the result of multiplying o1 and o2, or NULL on failure. The operation is done in-place when o1 supports it. This is the equivalent of the Python statement o1 *= o2.

PyObject* PyNumber_InPlaceMatrixMultiply(PyObject *o1, PyObject *o2)

Return value: New reference.

Returns the result of matrix multiplication on o1 and o2, or NULL on failure. The operation is done in-place when o1 supports it. This is the equivalent of the Python statement o1 @= o2.

버전 3.5에 추가.

PyObject* PyNumber_InPlaceFloorDivide(PyObject *o1, PyObject *o2)

Return value: New reference.

Returns the mathematical floor of dividing o1 by o2, or NULL on failure. The operation is done in-place when o1 supports it. This is the equivalent of the Python statement o1 //= o2.

PyObject* PyNumber_InPlaceTrueDivide(PyObject *o1, PyObject *o2)

Return value: New reference.

Return a reasonable approximation for the mathematical value of o1 divided by o2, or NULL on failure. The return value is “approximate” because binary floating point numbers are approximate; it is not possible to represent all real numbers in base two. This function can return a floating point value when passed two integers. The operation is done in-place when o1 supports it.

PyObject* PyNumber_InPlaceRemainder(PyObject *o1, PyObject *o2)

Return value: New reference.

Returns the remainder of dividing o1 by o2, or NULL on failure. The operation is done in-place when o1 supports it. This is the equivalent of the Python statement o1 %= o2.

PyObject* PyNumber_InPlacePower(PyObject *o1, PyObject *o2, PyObject *o3)

Return value: New reference.

See the built-in function pow(). Returns NULL on failure. The operation is done in-place when o1 supports it. This is the equivalent of the Python statement o1 **= o2 when o3 is Py_None, or an in-place variant of pow(o1, o2, o3) otherwise. If o3 is to be ignored, pass Py_None in its place (passing NULL for o3 would cause an illegal memory access).

PyObject* PyNumber_InPlaceLshift(PyObject *o1, PyObject *o2)

Return value: New reference.

Returns the result of left shifting o1 by o2 on success, or NULL on failure. The operation is done in-place when o1 supports it. This is the equivalent of the Python statement o1 <<= o2.

PyObject* PyNumber_InPlaceRshift(PyObject *o1, PyObject *o2)

Return value: New reference.

Returns the result of right shifting o1 by o2 on success, or NULL on failure. The operation is done in-place when o1 supports it. This is the equivalent of the Python statement o1 >>= o2.

PyObject* PyNumber_InPlaceAnd(PyObject *o1, PyObject *o2)

Return value: New reference.

Returns the “bitwise and” of o1 and o2 on success and NULL on failure. The operation is done in-place when o1 supports it. This is the equivalent of the Python statement o1 &= o2.

PyObject* PyNumber_InPlaceXor(PyObject *o1, PyObject *o2)

Return value: New reference.

Returns the “bitwise exclusive or” of o1 by o2 on success, or NULL on failure. The operation is done in-place when o1 supports it. This is the equivalent of the Python statement o1 ^= o2.

PyObject* PyNumber_InPlaceOr(PyObject *o1, PyObject *o2)

Return value: New reference.

Returns the “bitwise or” of o1 and o2 on success, or NULL on failure. The operation is done in-place when o1 supports it. This is the equivalent of the Python statement o1 |= o2.

PyObject* PyNumber_Long(PyObject *o)

Return value: New reference.

Returns the o converted to an integer object on success, or NULL on failure. This is the equivalent of the Python expression int(o).

PyObject* PyNumber_Float(PyObject *o)

Return value: New reference.

Returns the o converted to a float object on success, or NULL on failure. This is the equivalent of the Python expression float(o).

PyObject* PyNumber_Index(PyObject *o)

Return value: New reference.

Returns the o converted to a Python int on success or NULL with a TypeError exception raised on failure.

PyObject* PyNumber_ToBase(PyObject *n, int base)

Return value: New reference.

정수 n을 진수 base를 사용해서 변환한 문자열을 반환합니다. base 인자는 2, 8, 10 또는 16중 하나여야 합니다. 진수 2, 8 또는 16의 경우, 반환된 문자열은 '0b', '0o' 또는 '0x'의 진수 표시자가 각각 앞에 붙습니다. n이 파이썬 int가 아니면, 먼저 PyNumber_Index()로 변환됩니다.

Py_ssize_t PyNumber_AsSsize_t(PyObject *o, PyObject *exc)

o가 정수로 해석될 수 있으면, o를 Py_ssize_t 값으로 변환하여 반환합니다. 호출이 실패하면, 예외가 발생하고 -1이 반환됩니다.

If o can be converted to a Python int but the attempt to convert to a Py_ssize_t value would raise an OverflowError, then the exc argument is the type of exception that will be raised (usually IndexError or OverflowError). If exc is NULL, then the exception is cleared and the value is clipped to PY_SSIZE_T_MIN for a negative integer or PY_SSIZE_T_MAX for a positive integer.

int PyIndex_Check(PyObject *o)

o가 인덱스 정수(tp_as_number 구조의 nb_index 슬롯이 채워져 있습니다)면 1을 반환하고, 그렇지 않으면 0을 반환합니다. 이 함수는 항상 성공합니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

추상 객체 계층 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

추상 객체 계층 »

|

시퀀스 프로토콜

int PySequence_Check(PyObject *o)

객체가 시퀀스 프로토콜을 제공하면 1을 반환하고, 그렇지 않으면 0을 반환합니다. __getitem__() 메서드가 있는 파이썬 클래스의 경우 dict 서브 클래스가 아닌 한 1을 반환하는 것에 유의하십시오. 일반적으로 어떤 형의 키를 지원하는지 판단할 수 없기 때문입니다. 이 함수는 항상 성공합니다.

Py_ssize_t PySequence_Size(PyObject *o)

Py_ssize_t PySequence_Length(PyObject *o)

성공 시 시퀀스 o의 객체 수를 반환하고, 실패하면 -1을 반환합니다. 이것은 파이썬 표현식 len(o)와 동등합니다.

PyObject* PySequence_Concat(PyObject *o1, PyObject *o2)

Return value: New reference.

Return the concatenation of o1 and o2 on success, and NULL on failure. This is the equivalent of the Python expression o1 + o2.

PyObject* PySequence_Repeat(PyObject *o, Py_ssize_t count)

Return value: New reference.

Return the result of repeating sequence object o count times, or NULL on failure. This is the equivalent of the Python expression o * count.

PyObject* PySequence_InPlaceConcat(PyObject *o1, PyObject *o2)

Return value: New reference.

Return the concatenation of o1 and o2 on success, and NULL on failure. The operation is done in-place when o1 supports it. This is the equivalent of the Python expression o1 += o2.

PyObject* PySequence_InPlaceRepeat(PyObject *o, Py_ssize_t count)

Return value: New reference.

Return the result of repeating sequence object o count times, or NULL on failure. The operation is done in-place when o supports it. This is the equivalent of the Python expression o *= count.

PyObject* PySequence_GetItem(PyObject *o, Py_ssize_t i)

Return value: New reference.

Return the ith element of o, or NULL on failure. This is the equivalent of the Python expression o[i].

PyObject* PySequence_GetSlice(PyObject *o, Py_ssize_t i1, Py_ssize_t i2)

Return value: New reference.

Return the slice of sequence object o between i1 and i2, or NULL on failure. This is the equivalent of the Python expression o[i1:i2].

int PySequence_SetItem(PyObject *o, Py_ssize_t i, PyObject *v)

객체 v를 o의 i 번째 요소에 대입합니다. 실패하면 예외를 발생시키고 -1을 반환합니다; 성공하면 0을 반환합니다. 이것은 파이썬 문장 o[i] = v와 동등합니다. 이 함수는 v에 대한 참조를 훔치지 않습니다.

If v is NULL, the element is deleted, however this feature is deprecated in favour of using PySequence_DelItem().

int PySequence_DelItem(PyObject *o, Py_ssize_t i)

o 객체의 i 번째 요소를 삭제합니다. 실패하면 -1을 반환합니다. 이것은 파이썬 문장 del o[i]와 동등합니다.

int PySequence_SetSlice(PyObject *o, Py_ssize_t i1, Py_ssize_t i2, PyObject *v)

시퀀스 객체 v를 시퀀스 객체 o의 i1에서 i2 사이의 슬라이스에 대입합니다. 이것은 파이썬 문장 o[i1:i2] = v와 동등합니다.

int PySequence_DelSlice(PyObject *o, Py_ssize_t i1, Py_ssize_t i2)

시퀀스 객체 o의 i1에서 i2 사이의 슬라이스를 삭제합니다. 실패하면 -1을 반환합니다. 이것은 파이썬 문장 del o[i1:i2]와 동등합니다.

Py_ssize_t PySequence_Count(PyObject *o, PyObject *value)

o에 있는 value의 수를 반환합니다. 즉, o[key] == value를 만족하는 key의 수를 반환합니다. 실패하면 -1을 반환합니다. 이것은 파이썬 표현식 o.count(value)와 동등합니다.

int PySequence_Contains(PyObject *o, PyObject *value)

o에 value가 있는지 확인합니다. o의 항목 중 하나가 value와 같으면 1을 반환하고, 그렇지 않으면 0을 반환합니다. 에러 시 -1을 반환합니다. 이는 파이썬 표현식 value in o와 동등합니다.

Py_ssize_t PySequence_Index(PyObject *o, PyObject *value)

o[i] == value을 만족하는 첫 번째 인덱스 i를 반환합니다. 에러 시 -1을 반환합니다. 이것은 파이썬 표현식 o.index(value)와 동등합니다.

PyObject* PySequence_List(PyObject *o)

Return value: New reference.

Return a list object with the same contents as the sequence or iterable o, or NULL on failure. The returned list is guaranteed to be new. This is equivalent to the Python expression list(o).

PyObject* PySequence_Tuple(PyObject *o)

Return value: New reference.

Return a tuple object with the same contents as the sequence or iterable o, or NULL on failure. If o is a tuple, a new reference will be returned, otherwise a tuple will be constructed with the appropriate contents. This is equivalent to the Python expression tuple(o).

PyObject* PySequence_Fast(PyObject *o, const char *m)

Return value: New reference.

Return the sequence or iterable o as an object usable by the other PySequence_Fast* family of functions. If the object is not a sequence or iterable, raises TypeError with m as the message text. Returns NULL on failure.

The PySequence_Fast* functions are thus named because they assume o is a PyTupleObject or a PyListObject and access the data fields of o directly.

As a CPython implementation detail, if o is already a sequence or list, it will be returned.

Py_ssize_t PySequence_Fast_GET_SIZE(PyObject *o)

Returns the length of o, assuming that o was returned by PySequence_Fast() and that o is not NULL. The size can also be gotten by calling PySequence_Size() on o, but PySequence_Fast_GET_SIZE() is faster because it can assume o is a list or tuple.

PyObject* PySequence_Fast_GET_ITEM(PyObject *o, Py_ssize_t i)

Return value: Borrowed reference.

Return the ith element of o, assuming that o was returned by PySequence_Fast(), o is not NULL, and that i is within bounds.

PyObject** PySequence_Fast_ITEMS(PyObject *o)

Return the underlying array of PyObject pointers. Assumes that o was returned by PySequence_Fast() and o is not NULL.

리스트의 크기가 변경되면, 재할당이 항목 배열을 재배치할 수 있음에 유의하십시오. 따라서, 시퀀스가 변경될 수 없는 문맥에서만 하부 배열 포인터를 사용하십시오.

PyObject* PySequence_ITEM(PyObject *o, Py_ssize_t i)

Return value: New reference.

Return the ith element of o or NULL on failure. Faster form of PySequence_GetItem() but without checking that PySequence_Check() on o is true and without adjustment for negative indices.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

추상 객체 계층 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

추상 객체 계층 »

|

매핑 프로토콜

PyObject_GetItem(), PyObject_SetItem() 및 PyObject_DelItem()도 참조하십시오.

int PyMapping_Check(PyObject *o)

Return 1 if the object provides mapping protocol or supports slicing, and 0 otherwise. Note that it returns 1 for Python classes with a __getitem__() method since in general case it is impossible to determine what type of keys it supports. This function always succeeds.

Py_ssize_t PyMapping_Size(PyObject *o)

Py_ssize_t PyMapping_Length(PyObject *o)

성공 시 객체 o의 키 수를 반환하고, 실패하면 -1을 반환합니다. 이는 파이썬 표현식 len(o)와 동등합니다.

PyObject* PyMapping_GetItemString(PyObject *o, const char *key)

Return value: New reference.

Return element of o corresponding to the string key or NULL on failure. This is the equivalent of the Python expression o[key]. See also PyObject_GetItem().

int PyMapping_SetItemString(PyObject *o, const char *key, PyObject *v)

객체 o에서 문자열 key를 값 v에 매핑합니다. 실패하면 -1을 반환합니다. 이것은 파이썬 문장 o[key] = v와 동등합니다. PyObject_SetItem()도 참조하십시오.

int PyMapping_DelItem(PyObject *o, PyObject *key)

객체 o에서 객체 key에 대한 매핑을 제거합니다. 실패하면 -1을 반환합니다. 이것은 파이썬 문장 del o[key]와 동등합니다. 이것은 PyObject_DelItem()의 별칭입니다.

int PyMapping_DelItemString(PyObject *o, const char *key)

객체 o에서 문자열 key에 대한 매핑을 제거합니다. 실패하면 -1을 반환합니다. 이것은 파이썬 문장 del o[key]와 동등합니다.

int PyMapping_HasKey(PyObject *o, PyObject *key)

매핑 객체에 key 키가 있으면 1을 반환하고, 그렇지 않으면 0을 반환합니다. 이는 파이썬 표현식 key in o와 동등합니다. 이 함수는 항상 성공합니다.

__getitem__() 메서드를 호출하는 동안 발생하는 예외는 억제됨에 유의하십시오. 에러 보고를 받으려면 대신 PyObject_GetItem()을 사용하십시오.

int PyMapping_HasKeyString(PyObject *o, const char *key)

매핑 객체에 key 키가 있으면 1을 반환하고, 그렇지 않으면 0을 반환합니다. 이는 파이썬 표현식 key in o와 동등합니다. 이 함수는 항상 성공합니다.

__getitem__() 메서드를 호출하고 임시 문자열 객체를 만드는 동안 발생하는 예외는 억제됨에 유의하십시오. 에러 보고를 받으려면 대신 PyMapping_GetItemString()을 사용하십시오.

PyObject* PyMapping_Keys(PyObject *o)

Return value: New reference.

On success, return a list of the keys in object o. On failure, return NULL.

버전 3.7에서 변경: 이전에는 함수가 리스트나 튜플을 반환했습니다.

PyObject* PyMapping_Values(PyObject *o)

Return value: New reference.

On success, return a list of the values in object o. On failure, return NULL.

버전 3.7에서 변경: 이전에는 함수가 리스트나 튜플을 반환했습니다.

PyObject* PyMapping_Items(PyObject *o)

Return value: New reference.

On success, return a list of the items in object o, where each item is a tuple containing a key-value pair. On failure, return NULL.

버전 3.7에서 변경: 이전에는 함수가 리스트나 튜플을 반환했습니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

추상 객체 계층 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

추상 객체 계층 »

|

이터레이터 프로토콜

특히 이터레이터를 사용하기 위한 두 함수가 있습니다.

int PyIter_Check(PyObject *o)

객체 o가 이터레이터 프로토콜을 지원하면 참을 돌려줍니다.

PyObject* PyIter_Next(PyObject *o)

Return value: New reference.

Return the next value from the iteration o. The object must be an iterator (it is up to the caller to check this). If there are no remaining values, returns NULL with no exception set. If an error occurs while retrieving the item, returns NULL and passes along the exception.

이터레이터를 이터레이트하는 루프를 작성하려면, C 코드는 이런 식으로 되어야 합니다:

PyObject *iterator = PyObject_GetIter(obj);
PyObject *item;

if (iterator == NULL) {
    /* propagate error */
}

while ((item = PyIter_Next(iterator))) {
    /* do something with item */
    ...
    /* release reference when done */
    Py_DECREF(item);
}

Py_DECREF(iterator);

if (PyErr_Occurred()) {
    /* propagate error */
}
else {
    /* continue doing useful work */
}

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

추상 객체 계층 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

추상 객체 계층 »

|

버퍼 프로토콜

파이썬에서 사용할 수 있는 어떤 객체는 하부 메모리 배열 또는 버퍼에 대한 액세스를 감쌉니다. 이러한 객체에는 내장 bytes 와 bytearray, 그리고 array.array와 같은 일부 확장형이 포함됩니다. 제삼자 라이브러리도 이미지 처리나 수치 해석과 같은 특수한 용도로 자체 형을 정의할 수 있습니다.

이러한 형은 각각 고유의 의미가 있지만, (아마도) 큰 메모리 버퍼에 의해 뒷받침되는 공통된 특징을 공유합니다. 어떤 상황에서는 중간 복사 없이 직접 버퍼에 액세스하는 것이 바람직합니다.

파이썬은 C 수준에서 버퍼 프로토콜 형식으로 이러한 기능을 제공합니다. 이 프로토콜에는 두 가지 측면이 있습니다:

생산자 측에서는, 형이 “버퍼 인터페이스”를 내보낼 수 있는데, 그 형의 객체가 하부 버퍼의 정보를 노출할 수 있게 합니다. 이 인터페이스는 Buffer Object Structures 절에서 설명됩니다.

소비자 측에서는, 객체의 원시 하부 데이터에 대한 포인터를 얻기 위해 여러 가지 방법을 사용할 수 있습니다 (예를 들어 메서드 매개 변수).

bytes 와 bytearray와 같은 간단한 객체는 하부 버퍼를 바이트 지향 형식으로 노출합니다. 다른 형태도 가능합니다; 예를 들어, array.array에 의해 노출되는 요소는 멀티 바이트 값이 될 수 있습니다.

버퍼 인터페이스의 소비자 예는 파일 객체의 write() 메서드입니다: 버퍼 인터페이스를 통해 일련의 바이트를 내보낼 수 있는 모든 객체는 파일에 기록될 수 있습니다. write()가 전달된 객체의 내부 내용에 대한 읽기 전용 액세스만 필요하지만, readinto()와 같은 다른 메서드는 인자의 내용에 쓰기 액세스가 필요합니다. 버퍼 인터페이스는 객체가 읽기-쓰기와 읽기 전용 버퍼를 선택적으로 허용하거나 거부할 수 있도록 합니다.

버퍼 인터페이스의 소비자가 대상 객체에 대해 버퍼를 얻는 방법에는 두 가지가 있습니다:

올바른 매개 변수로 PyObject_GetBuffer()를 호출합니다;

y*, w* 또는 s* 형식 코드 중 하나를 사용하여 PyArg_ParseTuple()(또는 그 형제 중 하나)을 호출합니다.

두 경우 모두, 버퍼가 더는 필요하지 않으면 PyBuffer_Release()를 호출해야 합니다. 그렇게 하지 않으면 자원 누수와 같은 다양한 문제가 발생할 수 있습니다.

버퍼 구조체

버퍼 구조체(또는 단순히 “버퍼”)는 다른 객체의 바이너리 데이터를 파이썬 프로그래머에게 노출하는 방법으로 유용합니다. 또한, 복사 없는(zero-copy) 슬라이싱 메커니즘으로 사용할 수 있습니다. 메모리 블록을 참조하는 능력을 사용해서, 임의의 데이터를 파이썬 프로그래머에게 아주 쉽게 노출할 수 있습니다. 메모리는 C 확장의 큰 상수 배열일 수 있으며, 운영 체제 라이브러리로 전달되기 전에 조작하기 위한 원시 메모리 블록일 수도 있고, 네이티브 인 메모리(in-memory) 형식으로 구조화된 데이터를 전달하는 데 사용될 수도 있습니다.

파이썬 인터프리터가 노출하는 대부분의 데이터형과 달리, 버퍼는 PyObject 포인터가 아니라 단순한 C 구조체입니다. 이를 통해 매우 간단하게 만들고 복사할 수 있습니다. 버퍼를 감싸는 일반 래퍼가 필요할 때는, 메모리 뷰 객체를 만들 수 있습니다.

제공하는(exporting) 객체를 작성하는 간단한 지침은 버퍼 객체 구조체를 참조하십시오. 버퍼를 얻으려면, PyObject_GetBuffer()를 참조하십시오.

Py_buffer

void *buf

버퍼 필드에 의해 기술된 논리적 구조의 시작을 가리키는 포인터. 이것은 제공자(exporter)의 하부 물리적 메모리 블록 내의 모든 위치일 수 있습니다. 예를 들어, 음의 strides를 사용하면 값이 메모리 블록의 끝을 가리킬 수 있습니다.

연속 배열의 경우, 값은 메모리 블록의 시작을 가리킵니다.

void *obj

A new reference to the exporting object. The reference is owned by the consumer and automatically decremented and set to NULL by PyBuffer_Release(). The field is the equivalent of the return value of any standard C-API function.

As a special case, for temporary buffers that are wrapped by PyMemoryView_FromBuffer() or PyBuffer_FillInfo() this field is NULL. In general, exporting objects MUST NOT use this scheme.

Py_ssize_t len

product(shape) * itemsize. 연속 배열의 경우, 하부 메모리 블록의 길이입니다. 불연속 배열의 경우, 연속 표현으로 복사된다면 논리적 구조체가 갖게 될 길이입니다.

((char *)buf)[0] 에서 ((char *)buf)[len-1] 범위의 액세스는 연속성을 보장하는 요청으로 버퍼가 확보된 경우에만 유효합니다. 대부분 이러한 요청은 PyBUF_SIMPLE 또는 PyBUF_WRITABLE입니다.

int readonly

버퍼가 읽기 전용인지를 나타내는 표시기입니다. 이 필드는 PyBUF_WRITABLE 플래그로 제어됩니다.

Py_ssize_t itemsize

Item size in bytes of a single element. Same as the value of struct.calcsize() called on non-NULL format values.

Important exception: If a consumer requests a buffer without the PyBUF_FORMAT flag, format will be set to NULL, but itemsize still has the value for the original format.

shape이 있으면, product(shape) * itemsize == len 동치가 계속 성립하고 소비자는 itemsize를 사용하여 버퍼를 탐색할 수 있습니다.

If shape is NULL as a result of a PyBUF_SIMPLE or a PyBUF_WRITABLE request, the consumer must disregard itemsize and assume itemsize == 1.

const char *format

A NUL terminated string in struct module style syntax describing the contents of a single item. If this is NULL, "B" (unsigned bytes) is assumed.

이 필드는 PyBUF_FORMAT 플래그로 제어됩니다.

int ndim

The number of dimensions the memory represents as an n-dimensional array. If it is 0, buf points to a single item representing a scalar. In this case, shape, strides and suboffsets MUST be NULL.

매크로 PyBUF_MAX_NDIM는 최대 차원 수를 64로 제한합니다. 제공자는 이 제한을 존중해야 하며, 다차원 버퍼의 소비자는 PyBUF_MAX_NDIM 차원까지 처리할 수 있어야 합니다.

Py_ssize_t *shape

n-차원 배열로 메모리의 모양을 나타내는 길이 ndim의 Py_ssize_t 배열. shape[0] * ... * shape[ndim-1] * itemsize는 len과 같아야 합니다.

모양 값은 shape[n] >= 0로 제한됩니다. shape[n] == 0인 경우는 특별한 주의가 필요합니다. 자세한 정보는 복잡한 배열을 참조하십시오.

shape 배열은 소비자에게 읽기 전용입니다.

Py_ssize_t *strides

각 차원에서 새 요소를 가져오기 위해 건너뛸 바이트 수를 제공하는 길이 ndim의 Py_ssize_t 배열.

스트라이드 값은 임의의 정수일 수 있습니다. 일반 배열의 경우, 스트라이드는 보통 양수이지만, 소비자는 strides[n] <= 0인 경우를 처리할 수 있어야 합니다. 자세한 내용은 복잡한 배열을 참조하십시오.

strides 배열은 소비자에게 읽기 전용입니다.

Py_ssize_t *suboffsets

길이 ndim의 Py_ssize_t 배열. suboffsets[n] >= 0 면, n 번째 차원을 따라 저장된 값은 포인터이고 서브 오프셋 값은 역참조(de-referencing) 후 각 포인터에 더할 바이트 수를 나타냅니다. 음의 서브 오프셋 값은 역참조(de-referencing)가 발생하지 않아야 함을 나타냅니다 (연속 메모리 블록에서의 스트라이드).

If all suboffsets are negative (i.e. no de-referencing is needed), then this field must be NULL (the default value).

이 유형의 배열 표현은 파이썬 이미징 라이브러리(PIL)에서 사용됩니다. 이러한 배열 요소에 액세스하는 방법에 대한 자세한 내용은 복잡한 배열을 참조하십시오.

suboffsets 배열은 소비자에게 읽기 전용입니다.

void *internal

이것은 제공하는(exporting) 객체에 의해 내부적으로 사용됩니다. 예를 들어, 이것은 제공자(exporter)가 정수로 다시 캐스팅할 수 있으며, 버퍼가 해제될 때 shape, strides 및 suboffsets 배열을 해제해야 하는지에 대한 플래그를 저장하는 데 사용됩니다. 소비자가 이 값을 변경해서는 안 됩니다.

버퍼 요청 유형

버퍼는 대개 PyObject_GetBuffer()를 통해 제공하는(exporting) 객체로 버퍼 요청을 보내서 얻습니다. 메모리의 논리적 구조의 복잡성이 크게 다를 수 있으므로, 소비자는 처리할 수 있는 정확한 버퍼 유형을 지정하기 위해 flags 인자를 사용합니다.

모든 Py_buffer 필드는 요청 유형에 의해 모호하지 않게 정의됩니다.

요청 독립적 필드

다음 필드는 flags의 영향을 받지 않고 항상 올바른 값으로 채워져야 합니다: obj, buf, len, itemsize, ndim.

readonly, format

PyBUF_WRITABLE

readonly 필드를 제어합니다. 설정되면, 제공자는 반드시 쓰기 가능한 버퍼를 제공하거나 실패를 보고해야 합니다. 그렇지 않으면, 제공자는 읽기 전용 버퍼나 쓰기 가능 버퍼를 제공할 수 있지만, 모든 소비자에 대해 일관성을 유지해야 합니다.

PyBUF_FORMAT

Controls the format field. If set, this field MUST be filled in correctly. Otherwise, this field MUST be NULL.

PyBUF_WRITABLE은 다음 섹션의 모든 플래그와 | 될 수 있습니다. PyBUF_SIMPLE이 0으로 정의되므로, PyBUF_WRITABLE은 독립형 플래그로 사용되어 간단한 쓰기 가능한 버퍼를 요청할 수 있습니다.

PyBUF_FORMAT은 PyBUF_SIMPLE을 제외한 임의의 플래그와 | 될 수 있습니다. PyBUF_SIMPLE은 이미 형식 B(부호 없는 바이트)를 의미합니다.

shape, strides, suboffsets

메모리의 논리 구조를 제어하는 플래그는 복잡도가 감소하는 순서로 나열됩니다. 각 플래그는 그 아래에 있는 플래그의 모든 비트를 포함합니다.

요청

shape

strides

suboffsets

PyBUF_INDIRECT

yes

yes

필요하면

PyBUF_STRIDES

yes

yes

NULL

PyBUF_ND

yes

NULL

NULL

PyBUF_SIMPLE

NULL

NULL

NULL

연속성 요청

C 나 포트란 연속성을 명시적으로 요청할 수 있는데, 스트라이드 정보를 포함하기도 그렇지 않기도 합니다. 스트라이드 정보가 없으면, 버퍼는 C-연속이어야 합니다.

요청

shape

strides

suboffsets

연속성

PyBUF_C_CONTIGUOUS

yes

yes

NULL

C

PyBUF_F_CONTIGUOUS

yes

yes

NULL

F

PyBUF_ANY_CONTIGUOUS

yes

yes

NULL

C 또는 F

PyBUF_ND

yes

NULL

NULL

C

복합 요청

모든 가능한 요청은 앞 절의 플래그 조합에 의해 완전히 정의됩니다. 편의상, 버퍼 프로토콜은 자주 사용되는 조합을 단일 플래그로 제공합니다.

다음 표에서 U는 정의되지 않은 연속성을 나타냅니다. 소비자는 연속성을 판단하기 위해 PyBuffer_IsContiguous()를 호출해야 합니다.

요청

shape

strides

suboffsets

연속성

readonly

format

PyBUF_FULL

yes

yes

필요하면

U

0

yes

PyBUF_FULL_RO

yes

yes

필요하면

U

1 또는 0

yes

PyBUF_RECORDS

yes

yes

NULL

U

0

yes

PyBUF_RECORDS_RO

yes

yes

NULL

U

1 또는 0

yes

PyBUF_STRIDED

yes

yes

NULL

U

0

NULL

PyBUF_STRIDED_RO

yes

yes

NULL

U

1 또는 0

NULL

PyBUF_CONTIG

yes

NULL

NULL

C

0

NULL

PyBUF_CONTIG_RO

yes

NULL

NULL

C

1 또는 0

NULL

복잡한 배열

NumPy-스타일: shape과 strides

NumPy 스타일 배열의 논리적 구조는 itemsize, ndim, shape 및 strides로 정의됩니다.

If ndim == 0, the memory location pointed to by buf is interpreted as a scalar of size itemsize. In that case, both shape and strides are NULL.

If strides is NULL, the array is interpreted as a standard n-dimensional C-array. Otherwise, the consumer must access an n-dimensional array as follows:

ptr = (char *)buf + indices[0] * strides[0] + ... + indices[n-1] * strides[n-1];
item = *((typeof(item) *)ptr);

위에서 언급했듯이, buf는 실제 메모리 블록 내의 모든 위치를 가리킬 수 있습니다. 제공자(exporter)는 이 함수로 버퍼의 유효성을 검사 할 수 있습니다:

def verify_structure(memlen, itemsize, ndim, shape, strides, offset):
    """Verify that the parameters represent a valid array within
       the bounds of the allocated memory:
           char *mem: start of the physical memory block
           memlen: length of the physical memory block
           offset: (char *)buf - mem
    """
    if offset % itemsize:
        return False
    if offset < 0 or offset+itemsize > memlen:
        return False
    if any(v % itemsize for v in strides):
        return False

    if ndim <= 0:
        return ndim == 0 and not shape and not strides
    if 0 in shape:
        return True

    imin = sum(strides[j]*(shape[j]-1) for j in range(ndim)
               if strides[j] <= 0)
    imax = sum(strides[j]*(shape[j]-1) for j in range(ndim)
               if strides[j] > 0)

    return 0 <= offset+imin and offset+imax+itemsize <= memlen

PIL-스타일: shape, strides 및 suboffsets

일반 항목 외에도, PIL 스타일 배열에는 차원의 다음 요소를 가져오기 위해 따라야 하는 포인터가 포함될 수 있습니다. 예를 들어, 일반 3-차원 C 배열 char v[2][2][3]는 2개의 2-차원 배열을 가리키는 2개의 포인터 배열로 볼 수도 있습니다: char (*v[2])[2][3]. suboffsets 표현에서, 이 두 포인터는 buf의 시작 부분에 임베드 될 수 있는데, 메모리의 어느 위치 에나 배치될 수 있는 두 개의 char x[2][3] 배열을 가리킵니다.

Here is a function that returns a pointer to the element in an N-D array pointed to by an N-dimensional index when there are both non-NULL strides and suboffsets:

void *get_item_pointer(int ndim, void *buf, Py_ssize_t *strides,
                       Py_ssize_t *suboffsets, Py_ssize_t *indices) {
    char *pointer = (char*)buf;
    int i;
    for (i = 0; i < ndim; i++) {
        pointer += strides[i] * indices[i];
        if (suboffsets[i] >=0 ) {
            pointer = *((char**)pointer) + suboffsets[i];
        }
    }
    return (void*)pointer;
}

버퍼 관련 함수

int PyObject_CheckBuffer(PyObject *obj)

obj가 버퍼 인터페이스를 지원하면 1을 반환하고, 그렇지 않으면 0을 반환합니다. 1이 반환될 때, PyObject_GetBuffer()가 성공할 것이라고 보장하지는 않습니다. 이 함수는 항상 성공합니다.

int PyObject_GetBuffer(PyObject *exporter, Py_buffer *view, int flags)

Send a request to exporter to fill in view as specified by flags. If the exporter cannot provide a buffer of the exact type, it MUST raise PyExc_BufferError, set view->obj to NULL and return -1.

성공하면, view를 채우고, view->obj를 exporter에 대한 새 참조로 설정하고, 0을 반환합니다. 요청을 단일 객체로 리디렉션하는 연결된(chained) 버퍼 공급자의 경우, view->obj는 exporter 대신 이 객체를 참조할 수 있습니다 (버퍼 객체 구조체를 보세요).

PyObject_GetBuffer()에 대한 성공적인 호출은 PyBuffer_Release()에 대한 호출과 쌍을 이루어야 합니다, malloc()과 free()와 유사합니다. 따라서, 소비자가 버퍼로 작업한 후에는, PyBuffer_Release()를 정확히 한 번 호출해야 합니다.

void PyBuffer_Release(Py_buffer *view)

버퍼 view를 해제하고 view->obj에 대한 참조 횟수를 감소시킵니다. 버퍼가 더는 사용되지 않을 때, 이 함수를 반드시 호출해야 합니다. 그렇지 않으면 참조 누수가 발생할 수 있습니다.

PyObject_GetBuffer()를 통해 얻지 않은 버퍼에 이 함수를 호출하는 것은 에러입니다.

Py_ssize_t PyBuffer_SizeFromFormat(const char *)

format이 암시하는 itemsize를 반환합니다. 이 함수는 아직 구현되지 않았습니다.

int PyBuffer_IsContiguous(Py_buffer *view, char order)

view로 정의된 메모리가 C 스타일(order가 'C')이나 포트란 스타일(order가 'F') 연속이거나 둘 중 하나(order가 'A')면 1을 반환합니다. 그렇지 않으면 0을 반환합니다. 이 함수는 항상 성공합니다.

void* PyBuffer_GetPointer(Py_buffer *view, Py_ssize_t *indices)

Get the memory area pointed to by the indices inside the given view. indices must point to an array of view->ndim indices.

int PyBuffer_FromContiguous(Py_buffer *view, void *buf, Py_ssize_t len, char fort)

Copy contiguous len bytes from buf to view. fort can be 'C' or 'F' (for C-style or Fortran-style ordering). 0 is returned on success, -1 on error.

int PyBuffer_ToContiguous(void *buf, Py_buffer *src, Py_ssize_t len, char order)

Copy len bytes from src to its contiguous representation in buf. order can be 'C' or 'F' or 'A' (for C-style or Fortran-style ordering or either one). 0 is returned on success, -1 on error.

이 함수는 len != src->len이면 실패합니다.

void PyBuffer_FillContiguousStrides(int ndims, Py_ssize_t *shape, Py_ssize_t *strides, int itemsize, char order)

strides 배열을 주어진 요소당 바이트 수와 주어진 shape 으로 연속 (order가 'C'면 C 스타일, order가 'F'면 포트란 스타일) 배열의 바이트 스트라이드로 채웁니다.

int PyBuffer_FillInfo(Py_buffer *view, PyObject *exporter, void *buf, Py_ssize_t len, int readonly, int flags)

readonly에 따라 쓰기 가능성이 설정된 len 크기의 buf를 노출하려는 제공자(exporter)에 대한 버퍼 요청을 처리합니다. buf는 부호 없는 바이트의 시퀀스로 해석됩니다.

flags 인자는 요청 유형을 나타냅니다. 이 함수는 buf가 읽기 전용으로 지정되고 PyBUF_WRITABLE이 flags에 설정되어 있지 않으면, 항상 플래그가 지정하는 대로 view를 채웁니다.

On success, set view->obj to a new reference to exporter and return 0. Otherwise, raise PyExc_BufferError, set view->obj to NULL and return -1;

If this function is used as part of a getbufferproc, exporter MUST be set to the exporting object and flags must be passed unmodified. Otherwise, exporter MUST be NULL.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

추상 객체 계층 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

추상 객체 계층 »

|

낡은 버퍼 프로토콜

버전 3.0부터 폐지.

이 함수는 파이썬 2에서 “낡은 버퍼 프로토콜” API 일부분이었습니다. 파이썬 3에서는 이 프로토콜이 더는 존재하지 않지만 2.x 코드 이식을 쉽게 하도록 함수들은 여전히 노출됩니다. 이들은 새 버퍼 프로토콜를 둘러싼 호환성 래퍼 역할을 하지만, 버퍼를 제공할 때 얻은 자원의 수명을 제어할 수는 없습니다.

따라서, PyObject_GetBuffer()(또는 y* 나 w* 포맷 코드를 사용하는 PyArg_ParseTuple() 계열의 함수)를 호출하여 개체에 대한 버퍼 뷰를 가져오고, 버퍼 뷰를 해제할 수 있을 때 PyBuffer_Release()를 호출하는 것이 좋습니다.

int PyObject_AsCharBuffer(PyObject *obj, const char **buffer, Py_ssize_t *buffer_len)

문자 기반 입력으로 사용할 수 있는 읽기 전용 메모리 위치에 대한 포인터를 반환합니다. obj 인자는 단일 세그먼트 문자 버퍼 인터페이스를 지원해야 합니다. 성공하면, 0을 반환하고, buffer를 메모리 위치로 설정하고, buffer_len을 버퍼 길이로 설정합니다. 에러 시에, -1을 반환하고, TypeError를 설정합니다.

int PyObject_AsReadBuffer(PyObject *obj, const void **buffer, Py_ssize_t *buffer_len)

임의의 데이터를 포함하는 읽기 전용 메모리 위치에 대한 포인터를 반환합니다. obj 인자는 단일 세그먼트 읽기 가능 버퍼 인터페이스를 지원해야 합니다. 성공하면, 0을 반환하고, buffer를 메모리 위치로 설정하고, buffer_len을 버퍼 길이로 설정합니다. 에러 시에, -1을 반환하고, TypeError를 설정합니다.

int PyObject_CheckReadBuffer(PyObject *o)

o가 단일 세그먼트 읽기 가능 버퍼 인터페이스를 지원하면 1을 반환합니다. 그렇지 않으면, 0을 반환합니다. 이 함수는 항상 성공합니다.

이 함수는 버퍼를 가져오고 해제하려고 하며, 해당 함수를 호출하는 동안 발생하는 예외는 억제됨에 유의하십시오. 에러 보고를 받으려면 대신 PyObject_GetBuffer()를 사용하십시오.

int PyObject_AsWriteBuffer(PyObject *obj, void **buffer, Py_ssize_t *buffer_len)

쓰기 가능한 메모리 위치에 대한 포인터를 반환합니다. obj 인자는 단일 세그먼트, 문자 버퍼 인터페이스를 지원해야 합니다. 성공하면, 0을 반환하고, buffer를 메모리 위치로 설정하고, buffer_len을 버퍼 길이로 설정합니다. 에러 시에, -1을 반환하고, TypeError를 설정합니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

추상 객체 계층 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

|

구상 객체 계층

이 장의 함수는 특정 파이썬 객체 형에게만 적용됩니다. 그들에게 잘못된 형의 객체를 전달하는 것은 좋은 생각이 아닙니다; 파이썬 프로그램에서 객체를 받았는데 올바른 형을 가졌는지 확실하지 않다면, 먼저 형 검사를 수행해야 합니다; 예를 들어, 객체가 딕셔너리인지 확인하려면, PyDict_Check()를 사용하십시오. 이 장은 파이썬 객체 형의 “족보”처럼 구성되어 있습니다.

경고

While the functions described in this chapter carefully check the type of the objects which are passed in, many of them do not check for NULL being passed instead of a valid object. Allowing NULL to be passed in can cause memory access violations and immediate termination of the interpreter.

기본 객체

이 절에서는 파이썬 형 객체와 싱글톤 객체 None에 대해 설명합니다.

형 객체

None 객체

숫자 객체

정수 객체

불리언 객체

부동 소수점 객체

복소수 객체

C 구조체로서의 복소수

파이썬 객체로서의 복소수

시퀀스 객체

시퀀스 객체에 대한 일반적인 연산은 이전 장에서 논의했습니다; 이 절에서는 파이썬 언어에 고유한 특정 종류의 시퀀스 객체를 다룹니다.

바이트열 객체

바이트 배열 객체

형 검사 매크로

직접 API 함수

매크로

Unicode Objects and Codecs

Unicode Objects

Unicode Type

Unicode Character Properties

Creating and accessing Unicode strings

Deprecated Py_UNICODE APIs

Locale Encoding

File System Encoding

wchar_t Support

Built-in Codecs

Generic Codecs

UTF-8 Codecs

UTF-32 Codecs

UTF-16 Codecs

UTF-7 Codecs

Unicode-Escape Codecs

Raw-Unicode-Escape Codecs

Latin-1 Codecs

ASCII Codecs

Character Map Codecs

MBCS codecs for Windows

Methods & Slots

Methods and Slot Functions

튜플 객체

구조체 시퀀스 객체

리스트 객체

컨테이너 객체

딕셔너리 객체

집합 객체

함수 객체

함수 객체

인스턴스 메서드 객체

메서드 객체

셀 객체

코드 객체

기타 객체

파일 객체

Module Objects

Initializing C modules

Single-phase initialization

Multi-phase initialization

Low-level module creation functions

Support functions

Module lookup

이터레이터 객체

디스크립터 객체

슬라이스 객체

Ellipsis 객체

MemoryView 객체

약한 참조 객체

캡슐

제너레이터 객체

코루틴 객체

컨텍스트 변수 객체

DateTime 객체

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

구상 객체 계층 »

|

형 객체

PyTypeObject

내장형을 기술하는 데 사용되는 객체의 C 구조체.

PyObject* PyType_Type

이것은 형 객체의 형 객체입니다; 파이썬 계층의 type과 같은 객체입니다.

int PyType_Check(PyObject *o)

객체 o가 표준형 객체에서 파생된 형의 인스턴스를 포함하여 형 객체면 참을 반환합니다. 다른 모든 경우 거짓을 반환합니다.

int PyType_CheckExact(PyObject *o)

객체 o가 형 객체이지만, 표준형 객체의 서브 형이 아니면 참을 반환합니다. 다른 모든 경우 거짓을 반환합니다.

unsigned int PyType_ClearCache()

내부 조회 캐시를 지웁니다. 현재의 버전 태그를 반환합니다.

unsigned long PyType_GetFlags(PyTypeObject* type)

type의 tp_flags 멤버를 반환합니다. 이 함수는 주로 Py_LIMITED_API와 함께 사용하기 위한 것입니다; 개별 플래그 비트는 파이썬 배포 간에 안정적인 것으로 보장되지만, tp_flags 자체에 대한 액세스는 제한된 API 일부가 아닙니다.

버전 3.2에 추가.

버전 3.4에서 변경: 반환형은 이제 long이 아니라 unsigned long입니다.

void PyType_Modified(PyTypeObject *type)

형과 그것의 모든 서브 형에 대한 내부 검색 캐시를 무효로 합니다. 형의 어트리뷰트나 베이스 클래스를 수동으로 수정한 후에는 이 함수를 호출해야 합니다.

int PyType_HasFeature(PyTypeObject *o, int feature)

형 객체 o가 기능 feature를 설정하면 참을 반환합니다. 형 기능은 단일 비트 플래그로 표시됩니다.

int PyType_IS_GC(PyTypeObject *o)

형 객체가 순환 검출기에 대한 지원을 포함하고 있으면 참을 반환합니다. 이것은 형 플래그 Py_TPFLAGS_HAVE_GC를 검사합니다.

int PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)

a가 b의 서브 형이면 참을 반환합니다.

이 함수는 실제 서브 형만 검사합니다. 즉, __subclasscheck__()가 b에 대해 호출되지 않습니다. issubclass()가 수행하는 것과 같은 검사를 하려면 PyObject_IsSubclass()를 호출하십시오.

PyObject* PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems)

Return value: New reference.

Generic handler for the tp_alloc slot of a type object. Use Python’s default memory allocation mechanism to allocate a new instance and initialize all its contents to NULL.

PyObject* PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)

Return value: New reference.

형 객체의 tp_new 슬롯을 위한 일반 처리기. 형의 tp_alloc 슬롯을 사용하여 새 인스턴스를 만듭니다.

int PyType_Ready(PyTypeObject *type)

형 개체를 마무리합니다. 초기화를 완료하려면 모든 형 객체에 대해 이 메서드를 호출해야 합니다. 이 함수는 형의 베이스 클래스에서 상속된 슬롯을 추가합니다. 성공 시 0을 반환하고, 오류 시 -1을 반환하고 예외를 설정합니다.

PyObject* PyType_FromSpec(PyType_Spec *spec)

Return value: New reference.

함수에 전달된 spec으로 힙 형 객체를 만들고 반환합니다.

PyObject* PyType_FromSpecWithBases(PyType_Spec *spec, PyObject *bases)

Return value: New reference.

spec으로 힙 형 객체를 만들고 반환합니다. 이 외에도, 생성된 힙 형에는 bases 튜플에 포함된 모든 형이 베이스형으로 포함됩니다. 이를 통해 호출자는 다른 힙 형을 베이스형으로 참조할 수 있습니다.

버전 3.3에 추가.

void* PyType_GetSlot(PyTypeObject *type, int slot)

Return the function pointer stored in the given slot. If the result is NULL, this indicates that either the slot is NULL, or that the function was called with invalid parameters. Callers will typically cast the result pointer into the appropriate function type.

버전 3.4에 추가.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

구상 객체 계층 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

구상 객체 계층 »

|

None 객체

None에 대한 PyTypeObject는 파이썬/C API에서 직접 노출되지 않습니다. None은 싱글톤이기 때문에 (C에서 ==를 사용해서) 객체 아이덴티티를 검사하는 것으로 충분합니다. 같은 이유로 PyNone_Check() 함수가 없습니다.

PyObject* Py_None

값의 부재를 나타내는 파이썬 None 객체입니다. 이 객체에는 메서드가 없습니다. 참조 횟수와 관련하여 다른 객체와 마찬가지로 처리해야 합니다.

Py_RETURN_NONE

C 함수 내에서 Py_None를 반환하는 것을 올바르게 처리합니다 (즉, None의 참조 횟수를 증가시키고 반환합니다).

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

구상 객체 계층 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

구상 객체 계층 »

|

정수 객체

모든 정수는 임의의 크기의 “long” 정수 객체로 구현됩니다.

에러 시, 대부분의 PyLong_As* API는 숫자와 구별할 수 없는 (return type)-1을 반환합니다. 모호성을 제거하려면 PyErr_Occurred()를 사용하십시오.

PyLongObject

이 PyObject의 서브 형은 파이썬 정수 객체를 나타냅니다.

PyTypeObject PyLong_Type

이 PyTypeObject 인스턴스는 파이썬 정수 형을 나타냅니다. 이것은 파이썬 계층의 int와 같은 객체입니다.

int PyLong_Check(PyObject *p)

인자가 PyLongObject이나 PyLongObject의 서브 형이면 참을 반환합니다.

int PyLong_CheckExact(PyObject *p)

인자가 PyLongObject 이지만 PyLongObject의 서브 형이 아니면 참을 반환합니다.

PyObject* PyLong_FromLong(long v)

Return value: New reference.

Return a new PyLongObject object from v, or NULL on failure.

현재 구현은 -5와 256 사이의 모든 정수에 대해 정수 객체의 배열을 유지합니다. 이 범위에 있는 정수를 만들면 실제로는 기존 객체에 대한 참조만 반환됩니다. 따라서 1의 값을 변경하는 것이 가능합니다. 이때 파이썬의 동작은 정의되지 않은 것으로 판단됩니다. :-)

PyObject* PyLong_FromUnsignedLong(unsigned long v)

Return value: New reference.

Return a new PyLongObject object from a C unsigned long, or NULL on failure.

PyObject* PyLong_FromSsize_t(Py_ssize_t v)

Return value: New reference.

Return a new PyLongObject object from a C Py_ssize_t, or NULL on failure.

PyObject* PyLong_FromSize_t(size_t v)

Return value: New reference.

Return a new PyLongObject object from a C size_t, or NULL on failure.

PyObject* PyLong_FromLongLong(long long v)

Return value: New reference.

Return a new PyLongObject object from a C long long, or NULL on failure.

PyObject* PyLong_FromUnsignedLongLong(unsigned long long v)

Return value: New reference.

Return a new PyLongObject object from a C unsigned long long, or NULL on failure.

PyObject* PyLong_FromDouble(double v)

Return value: New reference.

Return a new PyLongObject object from the integer part of v, or NULL on failure.

PyObject* PyLong_FromString(const char *str, char **pend, int base)

Return value: New reference.

Return a new PyLongObject based on the string value in str, which is interpreted according to the radix in base. If pend is non-NULL, *pend will point to the first character in str which follows the representation of the number. If base is 0, str is interpreted using the 정수 리터럴 definition; in this case, leading zeros in a non-zero decimal number raises a ValueError. If base is not 0, it must be between 2 and 36, inclusive. Leading spaces and single underscores after a base specifier and between digits are ignored. If there are no digits, ValueError will be raised.

PyObject* PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)

Return value: New reference.

유니코드 숫자의 시퀀스를 파이썬 정숫값으로 변환합니다. 유니코드 문자열은 먼저 PyUnicode_EncodeDecimal()을 사용하여 바이트열로 인코딩된 다음 PyLong_FromString()을 사용하여 변환됩니다.

Deprecated since version 3.3, will be removed in version 4.0: 이전 스타일의 Py_UNICODE API의 일부; PyLong_FromUnicodeObject()를 사용하는 것으로 변경하십시오.

PyObject* PyLong_FromUnicodeObject(PyObject *u, int base)

Return value: New reference.

문자열 u의 유니코드 숫자 시퀀스를 파이썬 정숫값으로 변환합니다. 유니코드 문자열은 먼저 PyUnicode_EncodeDecimal()을 사용하여 바이트열로 인코딩된 다음 PyLong_FromString()을 사용하여 변환됩니다.

버전 3.3에 추가.

PyObject* PyLong_FromVoidPtr(void *p)

Return value: New reference.

포인터 p로부터 파이썬 정수를 만듭니다. 포인터 값은 PyLong_AsVoidPtr()를 사용하여 결괏값에서 조회할 수 있습니다.

long PyLong_AsLong(PyObject *obj)

obj의 C long 표현을 반환합니다. obj가 PyLongObject의 인스턴스가 아니면, (있다면) 먼저 __int__() 메서드를 호출하여 PyLongObject로 변환합니다.

obj의 값이 long의 범위를 벗어나면 OverflowError를 발생시킵니다.

에러 시 -1을 반환합니다. 모호성을 제거하려면 PyErr_Occurred()를 사용하십시오.

long PyLong_AsLongAndOverflow(PyObject *obj, int *overflow)

obj의 C long 표현을 반환합니다. obj가 PyLongObject의 인스턴스가 아니면, (있다면) 먼저 __int__() 메서드를 호출하여 PyLongObject로 변환합니다.

obj의 값이 LONG_MAX보다 크거나 LONG_MIN보다 작으면, *overflow를 각각 1이나 -1로 설정하고 -1을 반환합니다; 그렇지 않으면, *overflow를 0으로 설정합니다. 다른 예외가 발생하면 *overflow를 0으로 설정하고 -1을 평소와 같이 반환합니다.

에러 시 -1을 반환합니다. 모호성을 제거하려면 PyErr_Occurred()를 사용하십시오.

long long PyLong_AsLongLong(PyObject *obj)

obj의 C long long 표현을 반환합니다. obj가 PyLongObject의 인스턴스가 아니면, (있다면) 먼저 __int__() 메서드를 호출하여 PyLongObject로 변환합니다.

Raise OverflowError if the value of obj is out of range for a long long.

에러 시 -1을 반환합니다. 모호성을 제거하려면 PyErr_Occurred()를 사용하십시오.

long long PyLong_AsLongLongAndOverflow(PyObject *obj, int *overflow)

obj의 C long long 표현을 반환합니다. obj가 PyLongObject의 인스턴스가 아니면, (있다면) 먼저 __int__() 메서드를 호출하여 PyLongObject로 변환합니다.

obj의 값이 PY_LLONG_MAX보다 크거나 PY_LLONG_MIN보다 작으면, *overflow를 각각 1이나 -1로 설정하고 -1을 반환합니다; 그렇지 않으면, *overflow를 0으로 설정합니다. 다른 예외가 발생하면 *overflow를 0으로 설정하고 -1을 평소와 같이 반환합니다.

에러 시 -1을 반환합니다. 모호성을 제거하려면 PyErr_Occurred()를 사용하십시오.

버전 3.2에 추가.

Py_ssize_t PyLong_AsSsize_t(PyObject *pylong)

pylong의 C Py_ssize_t 표현을 반환합니다. pylong은 PyLongObject의 인스턴스여야 합니다.

pylong의 값이 Py_ssize_t의 범위를 벗어나면 OverflowError를 발생시킵니다.

에러 시 -1을 반환합니다. 모호성을 제거하려면 PyErr_Occurred()를 사용하십시오.

unsigned long PyLong_AsUnsignedLong(PyObject *pylong)

pylong의 C unsigned long 표현을 반환합니다. pylong은 PyLongObject의 인스턴스여야 합니다.

pylong의 값이 unsigned long의 범위를 벗어나면 OverflowError를 발생시킵니다.

에러 시 (unsigned long)-1을 반환합니다. 모호성을 제거하려면 PyErr_Occurred()를 사용하십시오.

size_t PyLong_AsSize_t(PyObject *pylong)

pylong의 C size_t 표현을 반환합니다. pylong은 PyLongObject의 인스턴스여야 합니다.

pylong의 값이 size_t의 범위를 벗어나면 OverflowError를 발생시킵니다.

에러 시 (size_t)-1을 반환합니다. 모호성을 제거하려면 PyErr_Occurred()를 사용하십시오.

unsigned long long PyLong_AsUnsignedLongLong(PyObject *pylong)

pylong의 C unsigned long long 표현을 반환합니다. pylong은 PyLongObject의 인스턴스여야 합니다.

pylong의 값이 unsigned long long의 범위를 벗어나면 OverflowError를 발생시킵니다.

에러 시 (unsigned long long)-1을 반환합니다. 모호성을 제거하려면 PyErr_Occurred()를 사용하십시오.

버전 3.1에서 변경: 음의 pylong는 이제 TypeError가 아니라 OverflowError를 발생시킵니다.

unsigned long PyLong_AsUnsignedLongMask(PyObject *obj)

obj의 C unsigned long 표현을 반환합니다. obj가 PyLongObject의 인스턴스가 아니면, (있다면) 먼저 __int__() 메서드를 호출하여 PyLongObject로 변환합니다.

obj의 값이 unsigned long의 범위를 벗어나면, 그 값의 모듈로 ULONG_MAX + 1 환원을 반환합니다.

에러 시 (unsigned long)-1을 반환합니다. 모호성을 제거하려면 PyErr_Occurred()를 사용하십시오.

unsigned long long PyLong_AsUnsignedLongLongMask(PyObject *obj)

obj의 C unsigned long long 표현을 반환합니다. obj가 PyLongObject의 인스턴스가 아니면, (있다면) 먼저 __int__() 메서드를 호출하여 PyLongObject로 변환합니다.

obj의 값이 unsigned long long의 범위를 벗어나면, 그 값의 모듈로 PY_ULLONG_MAX + 1 환원을 반환합니다.

에러 시 (unsigned long long)-1을 반환합니다. 모호성을 제거하려면 PyErr_Occurred()를 사용하십시오.

double PyLong_AsDouble(PyObject *pylong)

pylong의 C double 표현을 반환합니다. pylong은 PyLongObject의 인스턴스여야 합니다.

pylong의 값이 double의 범위를 벗어나면 OverflowError를 발생시킵니다.

에러 시 -1.0을 반환합니다. 모호성을 제거하려면 PyErr_Occurred()를 사용하십시오.

void* PyLong_AsVoidPtr(PyObject *pylong)

파이썬 정수 pylong을 C void 포인터로 변환합니다. pylong을 변환할 수 없으면, OverflowError가 발생합니다. 이것은 PyLong_FromVoidPtr()로 만들어진 값에 대해서만 사용할 수 있는 void 포인터를 생성하는 것이 보장됩니다.

Returns NULL on error. Use PyErr_Occurred() to disambiguate.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

구상 객체 계층 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

구상 객체 계층 »

|

불리언 객체

파이썬에서 불리언은 정수의 서브 클래스로 구현됩니다. Py_False와 Py_True라는 두 개의 부울만 있습니다. 따라서 일반적인 생성 및 삭제 함수는 부울에 적용되지 않습니다. 그러나 다음 매크로를 사용할 수 있습니다.

int PyBool_Check(PyObject *o)

o가 PyBool_Type 형이면 참을 돌려줍니다.

PyObject* Py_False

파이썬 False 객체. 이 객체는 메서드가 없습니다. 참조 카운트와 관련해서는 다른 객체와 마찬가지로 처리해야 합니다.

PyObject* Py_True

파이썬 True 객체. 이 객체는 메서드가 없습니다. 참조 카운트와 관련해서는 다른 객체와 마찬가지로 처리해야 합니다.

Py_RETURN_FALSE

함수에서 Py_False를 반환하고, 참조 카운트를 적절하게 증가시킵니다.

Py_RETURN_TRUE

함수에서 Py_True를 반환하고, 참조 카운트를 적절하게 증가시킵니다.

PyObject* PyBool_FromLong(long v)

Return value: New reference.

v의 논리값에 따라 Py_True 나 Py_False에 대한 새 참조를 반환합니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

구상 객체 계층 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

구상 객체 계층 »

|

부동 소수점 객체

PyFloatObject

이 PyObject의 서브 형은 파이썬 부동 소수점 객체를 나타냅니다.

PyTypeObject PyFloat_Type

이 PyTypeObject 인스턴스는 파이썬 부동 소수점 형을 나타냅니다. 이것은 파이썬 계층에서 float와 같은 객체입니다.

int PyFloat_Check(PyObject *p)

인자가 PyFloatObject 나 PyFloatObject의 서브 형이면 참을 반환합니다.

int PyFloat_CheckExact(PyObject *p)

인자가 PyFloatObject이지만 PyFloatObject의 서브 형은 아니면 참을 반환합니다.

PyObject* PyFloat_FromString(PyObject *str)

Return value: New reference.

Create a PyFloatObject object based on the string value in str, or NULL on failure.

PyObject* PyFloat_FromDouble(double v)

Return value: New reference.

Create a PyFloatObject object from v, or NULL on failure.

double PyFloat_AsDouble(PyObject *pyfloat)

pyfloat 의 내용의 C double 표현을 반환합니다. pyfloat가 파이썬 부동 소수점 객체가 아니지만 __float__() 메서드가 있으면, pyfloat를 float로 변환하기 위해 이 메서드가 먼저 호출됩니다. 이 메서드는 실패하면 -1.0을 반환하므로, PyErr_Occurred()를 호출하여 에러를 확인해야 합니다.

double PyFloat_AS_DOUBLE(PyObject *pyfloat)

에러 검사 없이 pyfloat 의 내용의 C double 표현을 반환합니다.

PyObject* PyFloat_GetInfo(void)

Return value: New reference.

float의 정밀도, 최솟값, 최댓값에 관한 정보를 포함한 structseq 인스턴스를 돌려줍니다. 헤더 파일 float.h를 감싸는 얇은 래퍼입니다.

double PyFloat_GetMax()

최대 표현 가능한 유한 float DBL_MAX를 C double로 반환합니다.

double PyFloat_GetMin()

최소 정규화된(normalized) 양의 float DBL_MIN를 C double로 반환합니다.

int PyFloat_ClearFreeList()

float 자유 목록(free list)을 비웁니다. 해제할 수 없는 항목의 수를 반환합니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

구상 객체 계층 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

구상 객체 계층 »

|

복소수 객체

파이썬의 복소수 객체는 C API에서 볼 때 두 개의 다른 형으로 구현됩니다: 하나는 파이썬 프로그램에 노출된 파이썬 객체이고, 다른 하나는 실제 복소수 값을 나타내는 C 구조체입니다. API는 두 가지 모두도 작업할 수 있는 함수를 제공합니다.

C 구조체로서의 복소수

매개 변수로 이러한 구조체를 받아들이고 결과로 반환하는 함수는 포인터를 통해 역참조하기보다는 값으로 다룹니다. 이는 API 전체에서 일관됩니다.

Py_complex

파이썬 복소수 객체의 값 부분에 해당하는 C 구조체. 복소수 객체를 다루는 대부분 함수는 이 형의 구조체를 입력 또는 출력값으로 적절하게 사용합니다. 다음과 같이 정의됩니다:

typedef struct {
   double real;
   double imag;
} Py_complex;

Py_complex _Py_c_sum(Py_complex left, Py_complex right)

C Py_complex 표현을 사용하여 두 복소수의 합을 반환합니다.

Py_complex _Py_c_diff(Py_complex left, Py_complex right)

C Py_complex 표현을 사용하여 두 복소수의 차이를 반환합니다.

Py_complex _Py_c_neg(Py_complex complex)

C Py_complex 표현을 사용하여 복소수 complex의 음의 값을 반환합니다.

Py_complex _Py_c_prod(Py_complex left, Py_complex right)

C Py_complex 표현을 사용하여 두 복소수의 곱을 반환합니다.

Py_complex _Py_c_quot(Py_complex dividend, Py_complex divisor)

C Py_complex 표현을 사용하여 두 복소수의 몫을 반환합니다.

divisor가 null이면, 이 메서드는 0을 반환하고, errno를 EDOM으로 설정합니다.

Py_complex _Py_c_pow(Py_complex num, Py_complex exp)

C Py_complex 표현을 사용하여 num의 exp 거듭제곱을 반환합니다.

num이 null이고 exp가 양의 실수가 아니면, 이 메서드는 0을 반환하고 errno를 EDOM으로 설정합니다.

파이썬 객체로서의 복소수

PyComplexObject

파이썬 복소수 객체를 나타내는 PyObject의 서브 형.

PyTypeObject PyComplex_Type

이 PyTypeObject 인스턴스는 파이썬 복소수 형을 나타냅니다. 파이썬 계층의 complex와 같은 객체입니다.

int PyComplex_Check(PyObject *p)

인자가 PyComplexObject 나 PyComplexObject의 서브 형이면 참을 반환합니다.

int PyComplex_CheckExact(PyObject *p)

인자가 PyComplexObject이지만, PyComplexObject의 서브 유형이 아니면 참을 반환합니다.

PyObject* PyComplex_FromCComplex(Py_complex v)

Return value: New reference.

C Py_complex 값으로 새로운 파이썬 복소수 객체를 만듭니다.

PyObject* PyComplex_FromDoubles(double real, double imag)

Return value: New reference.

real 및 imag로 새로운 PyComplexObject 객체를 반환합니다.

double PyComplex_RealAsDouble(PyObject *op)

op의 실수부를 C double로 반환합니다.

double PyComplex_ImagAsDouble(PyObject *op)

op의 허수부를 C double로 반환합니다.

Py_complex PyComplex_AsCComplex(PyObject *op)

복소수 op의 Py_complex 값을 반환합니다.

op가 파이썬 복소수 객체가 아니지만 __complex__() 메서드가 있으면, 이 메서드는 먼저 op를 파이썬 복소수 객체로 변환하도록 그 메서드를 호출합니다. 실패하면, 이 메서드는 -1.0를 실숫값으로 반환합니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

구상 객체 계층 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

구상 객체 계층 »

|

바이트열 객체

이 함수들은 바이트열 매개 변수가 필요할 때 바이트열이 아닌 매개 변수로 호출하면 TypeError를 발생시킵니다.

PyBytesObject

이 PyObject의 서브 형은 파이썬 바이트열 객체를 나타냅니다.

PyTypeObject PyBytes_Type

이 PyTypeObject의 인스턴스는 파이썬 바이트열 형을 나타냅니다; 파이썬 계층의 bytes와 같은 객체입니다.

int PyBytes_Check(PyObject *o)

객체 o가 바이트열 객체이거나 바이트열 형의 서브 형의 인스턴스면 참을 반환합니다.

int PyBytes_CheckExact(PyObject *o)

객체 o가 바이트열 객체이지만, 바이트열 형의 서브 형의 인스턴스는 아니면 참을 반환합니다.

PyObject* PyBytes_FromString(const char *v)

Return value: New reference.

Return a new bytes object with a copy of the string v as value on success, and NULL on failure. The parameter v must not be NULL; it will not be checked.

PyObject* PyBytes_FromStringAndSize(const char *v, Py_ssize_t len)

Return value: New reference.

Return a new bytes object with a copy of the string v as value and length len on success, and NULL on failure. If v is NULL, the contents of the bytes object are uninitialized.

PyObject* PyBytes_FromFormat(const char *format, ...)

Return value: New reference.

C printf()-스타일 format 문자열과 가변 개수의 인자를 받아서, 결과 파이썬 바이트열 객체의 크기를 계산하고 그 안에 값이 포맷된 바이트열 객체를 반환합니다. 가변 인자는 C 형이어야 하며 format 문자열에 있는 포맷 문자들과 정확히 대응해야 합니다. 허용되는 포맷 문자는 다음과 같습니다:

포맷 문자

형

주석

%%

n/a

리터럴 % 문자.

%c

int

단일 바이트, C int로 표현됩니다.

%d

int

printf("%d")와 동등합니다. 1

%u

unsigned int

printf("%u")와 동등합니다. 1

%ld

long

printf("%ld")와 동등합니다. 1

%lu

unsigned long

printf("%lu")와 동등합니다. 1

%zd

Py_ssize_t

printf("%zd")와 동등합니다. 1

%zu

size_t

printf("%zu")와 동등합니다. 1

%i

int

printf("%i")와 동등합니다. 1

%x

int

printf("%x")와 동등합니다. 1

%s

const char*

널-종료 C 문자 배열.

%p

const void*

C 포인터의 16진수 표현. 플랫폼의 printf가 어떤 결과를 내는지에 상관없이 리터럴 0x로 시작함이 보장된다는 점을 제외하고는 거의 printf("%p")와 동등합니다.

인식할 수 없는 포맷 문자는 포맷 문자열의 나머지 부분이 모두 결과 객체에 그대로 복사되게 만들고, 추가 인자는 무시됩니다.

1(1,2,3,4,5,6,7,8)

정수 지정자 (d, u, ld, lu, zd, zu, i, x)에서: 0-변환 플래그는 정밀도를 지정해도 영향을 미칩니다.

PyObject* PyBytes_FromFormatV(const char *format, va_list vargs)

Return value: New reference.

정확히 두 개의 인자를 취한다는 것을 제외하고는 PyBytes_FromFormat()과 같습니다.

PyObject* PyBytes_FromObject(PyObject *o)

Return value: New reference.

버퍼 프로토콜을 구현하는 객체 o의 바이트열 표현을 반환합니다.

Py_ssize_t PyBytes_Size(PyObject *o)

바이트열 객체 o의 길이를 반환합니다.

Py_ssize_t PyBytes_GET_SIZE(PyObject *o)

에러 검사 없는 PyBytes_Size()의 매크로 형식.

char* PyBytes_AsString(PyObject *o)

Return a pointer to the contents of o. The pointer refers to the internal buffer of o, which consists of len(o) + 1 bytes. The last byte in the buffer is always null, regardless of whether there are any other null bytes. The data must not be modified in any way, unless the object was just created using PyBytes_FromStringAndSize(NULL, size). It must not be deallocated. If o is not a bytes object at all, PyBytes_AsString() returns NULL and raises TypeError.

char* PyBytes_AS_STRING(PyObject *string)

에러 검사 없는 PyBytes_AsString()의 매크로 형식.

int PyBytes_AsStringAndSize(PyObject *obj, char **buffer, Py_ssize_t *length)

출력 변수 buffer와 length로 객체 obj의 널-종료 내용을 반환합니다.

If length is NULL, the bytes object may not contain embedded null bytes; if it does, the function returns -1 and a ValueError is raised.

buffer는 obj의 내부 버퍼를 가리키게 되는데, 끝에 추가 널 바이트가 포함됩니다 (length에는 포함되지 않습니다). 객체가 PyBytes_FromStringAndSize(NULL, size)를 사용하여 방금 만들어진 경우가 아니면 데이터를 수정해서는 안 됩니다. 할당을 해제해서는 안 됩니다. obj가 바이트열 객체가 아니면 PyBytes_AsStringAndSize()는 -1을 반환하고 TypeError를 발생시킵니다.

버전 3.5에서 변경: 이전에는, 바이트열 객체에 널 바이트가 포함되어 있으면 TypeError가 발생했습니다.

void PyBytes_Concat(PyObject **bytes, PyObject *newpart)

Create a new bytes object in *bytes containing the contents of newpart appended to bytes; the caller will own the new reference. The reference to the old value of bytes will be stolen. If the new object cannot be created, the old reference to bytes will still be discarded and the value of *bytes will be set to NULL; the appropriate exception will be set.

void PyBytes_ConcatAndDel(PyObject **bytes, PyObject *newpart)

bytes에 newpart의 내용을 덧붙인 새 바이트열 객체를 *bytes에 만듭니다. 이 버전은 newpart의 참조 횟수를 감소시킵니다.

int _PyBytes_Resize(PyObject **bytes, Py_ssize_t newsize)

A way to resize a bytes object even though it is “immutable”. Only use this to build up a brand new bytes object; don’t use this if the bytes may already be known in other parts of the code. It is an error to call this function if the refcount on the input bytes object is not one. Pass the address of an existing bytes object as an lvalue (it may be written into), and the new size desired. On success, *bytes holds the resized bytes object and 0 is returned; the address in *bytes may differ from its input value. If the reallocation fails, the original bytes object at *bytes is deallocated, *bytes is set to NULL, MemoryError is set, and -1 is returned.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

구상 객체 계층 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

구상 객체 계층 »

|

바이트 배열 객체

PyByteArrayObject

이 PyObject의 서브 형은 파이썬 bytearray 객체를 나타냅니다.

PyTypeObject PyByteArray_Type

이 PyTypeObject 인스턴스는 파이썬 bytearray 형을 나타냅니다; 파이썬 계층의 bytearray와 같은 객체입니다.

형 검사 매크로

int PyByteArray_Check(PyObject *o)

객체 o가 bytearray 객체이거나 bytearray 형의 서브 형 인스턴스면 참을 반환합니다.

int PyByteArray_CheckExact(PyObject *o)

객체 o가 bytearray 객체이지만, bytearray 형의 서브 형 인스턴스는 아니면 참을 반환합니다.

직접 API 함수

PyObject* PyByteArray_FromObject(PyObject *o)

Return value: New reference.

버퍼 프로토콜을 구현하는 임의의 객체(o)로부터 써서 새로운 bytearray 객체를 돌려줍니다.

PyObject* PyByteArray_FromStringAndSize(const char *string, Py_ssize_t len)

Return value: New reference.

Create a new bytearray object from string and its length, len. On failure, NULL is returned.

PyObject* PyByteArray_Concat(PyObject *a, PyObject *b)

Return value: New reference.

바이트 배열 a 와 b를 이어붙여 새로운 bytearray로 반환합니다.

Py_ssize_t PyByteArray_Size(PyObject *bytearray)

Return the size of bytearray after checking for a NULL pointer.

char* PyByteArray_AsString(PyObject *bytearray)

Return the contents of bytearray as a char array after checking for a NULL pointer. The returned array always has an extra null byte appended.

int PyByteArray_Resize(PyObject *bytearray, Py_ssize_t len)

bytearray의 내부 버퍼의 크기를 len으로 조정합니다.

매크로

이 매크로는 속도를 위해 안전을 희생하며 포인터를 확인하지 않습니다.

char* PyByteArray_AS_STRING(PyObject *bytearray)

PyByteArray_AsString()의 매크로 버전.

Py_ssize_t PyByteArray_GET_SIZE(PyObject *bytearray)

PyByteArray_Size()의 매크로 버전.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

구상 객체 계층 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

구상 객체 계층 »

|

Unicode Objects and Codecs

Unicode Objects

Since the implementation of PEP 393 [https://www.python.org/dev/peps/pep-0393] in Python 3.3, Unicode objects internally use a variety of representations, in order to allow handling the complete range of Unicode characters while staying memory efficient. There are special cases for strings where all code points are below 128, 256, or 65536; otherwise, code points must be below 1114112 (which is the full Unicode range).

Py_UNICODE* and UTF-8 representations are created on demand and cached in the Unicode object. The Py_UNICODE* representation is deprecated and inefficient; it should be avoided in performance- or memory-sensitive situations.

Due to the transition between the old APIs and the new APIs, Unicode objects can internally be in two states depending on how they were created:

“canonical” Unicode objects are all objects created by a non-deprecated Unicode API. They use the most efficient representation allowed by the implementation.

“legacy” Unicode objects have been created through one of the deprecated APIs (typically PyUnicode_FromUnicode()) and only bear the Py_UNICODE* representation; you will have to call PyUnicode_READY() on them before calling any other API.

Unicode Type

These are the basic Unicode object types used for the Unicode implementation in Python:

Py_UCS4

Py_UCS2

Py_UCS1

These types are typedefs for unsigned integer types wide enough to contain characters of 32 bits, 16 bits and 8 bits, respectively. When dealing with single Unicode characters, use Py_UCS4.

버전 3.3에 추가.

Py_UNICODE

This is a typedef of wchar_t, which is a 16-bit type or 32-bit type depending on the platform.

버전 3.3에서 변경: In previous versions, this was a 16-bit type or a 32-bit type depending on whether you selected a “narrow” or “wide” Unicode version of Python at build time.

PyASCIIObject

PyCompactUnicodeObject

PyUnicodeObject

These subtypes of PyObject represent a Python Unicode object. In almost all cases, they shouldn’t be used directly, since all API functions that deal with Unicode objects take and return PyObject pointers.

버전 3.3에 추가.

PyTypeObject PyUnicode_Type

This instance of PyTypeObject represents the Python Unicode type. It is exposed to Python code as str.

The following APIs are really C macros and can be used to do fast checks and to access internal read-only data of Unicode objects:

int PyUnicode_Check(PyObject *o)

Return true if the object o is a Unicode object or an instance of a Unicode subtype.

int PyUnicode_CheckExact(PyObject *o)

Return true if the object o is a Unicode object, but not an instance of a subtype.

int PyUnicode_READY(PyObject *o)

Ensure the string object o is in the “canonical” representation. This is required before using any of the access macros described below.

Returns 0 on success and -1 with an exception set on failure, which in particular happens if memory allocation fails.

버전 3.3에 추가.

Py_ssize_t PyUnicode_GET_LENGTH(PyObject *o)

Return the length of the Unicode string, in code points. o has to be a Unicode object in the “canonical” representation (not checked).

버전 3.3에 추가.

Py_UCS1* PyUnicode_1BYTE_DATA(PyObject *o)

Py_UCS2* PyUnicode_2BYTE_DATA(PyObject *o)

Py_UCS4* PyUnicode_4BYTE_DATA(PyObject *o)

Return a pointer to the canonical representation cast to UCS1, UCS2 or UCS4 integer types for direct character access. No checks are performed if the canonical representation has the correct character size; use PyUnicode_KIND() to select the right macro. Make sure PyUnicode_READY() has been called before accessing this.

버전 3.3에 추가.

PyUnicode_WCHAR_KIND

PyUnicode_1BYTE_KIND

PyUnicode_2BYTE_KIND

PyUnicode_4BYTE_KIND

Return values of the PyUnicode_KIND() macro.

버전 3.3에 추가.

int PyUnicode_KIND(PyObject *o)

Return one of the PyUnicode kind constants (see above) that indicate how many bytes per character this Unicode object uses to store its data. o has to be a Unicode object in the “canonical” representation (not checked).

버전 3.3에 추가.

void* PyUnicode_DATA(PyObject *o)

Return a void pointer to the raw Unicode buffer. o has to be a Unicode object in the “canonical” representation (not checked).

버전 3.3에 추가.

void PyUnicode_WRITE(int kind, void *data, Py_ssize_t index, Py_UCS4 value)

Write into a canonical representation data (as obtained with PyUnicode_DATA()). This macro does not do any sanity checks and is intended for usage in loops. The caller should cache the kind value and data pointer as obtained from other macro calls. index is the index in the string (starts at 0) and value is the new code point value which should be written to that location.

버전 3.3에 추가.

Py_UCS4 PyUnicode_READ(int kind, void *data, Py_ssize_t index)

Read a code point from a canonical representation data (as obtained with PyUnicode_DATA()). No checks or ready calls are performed.

버전 3.3에 추가.

Py_UCS4 PyUnicode_READ_CHAR(PyObject *o, Py_ssize_t index)

Read a character from a Unicode object o, which must be in the “canonical” representation. This is less efficient than PyUnicode_READ() if you do multiple consecutive reads.

버전 3.3에 추가.

PyUnicode_MAX_CHAR_VALUE(PyObject *o)

Return the maximum code point that is suitable for creating another string based on o, which must be in the “canonical” representation. This is always an approximation but more efficient than iterating over the string.

버전 3.3에 추가.

int PyUnicode_ClearFreeList()

Clear the free list. Return the total number of freed items.

Py_ssize_t PyUnicode_GET_SIZE(PyObject *o)

Return the size of the deprecated Py_UNICODE representation, in code units (this includes surrogate pairs as 2 units). o has to be a Unicode object (not checked).

Deprecated since version 3.3, will be removed in version 4.0: Part of the old-style Unicode API, please migrate to using PyUnicode_GET_LENGTH().

Py_ssize_t PyUnicode_GET_DATA_SIZE(PyObject *o)

Return the size of the deprecated Py_UNICODE representation in bytes. o has to be a Unicode object (not checked).

Deprecated since version 3.3, will be removed in version 4.0: Part of the old-style Unicode API, please migrate to using PyUnicode_GET_LENGTH().

Py_UNICODE* PyUnicode_AS_UNICODE(PyObject *o)

const char* PyUnicode_AS_DATA(PyObject *o)

Return a pointer to a Py_UNICODE representation of the object. The returned buffer is always terminated with an extra null code point. It may also contain embedded null code points, which would cause the string to be truncated when used in most C functions. The AS_DATA form casts the pointer to const char *. The o argument has to be a Unicode object (not checked).

버전 3.3에서 변경: This macro is now inefficient – because in many cases the Py_UNICODE representation does not exist and needs to be created – and can fail (return NULL with an exception set). Try to port the code to use the new PyUnicode_nBYTE_DATA() macros or use PyUnicode_WRITE() or PyUnicode_READ().

Deprecated since version 3.3, will be removed in version 4.0: Part of the old-style Unicode API, please migrate to using the PyUnicode_nBYTE_DATA() family of macros.

Unicode Character Properties

Unicode provides many different character properties. The most often needed ones are available through these macros which are mapped to C functions depending on the Python configuration.

int Py_UNICODE_ISSPACE(Py_UNICODE ch)

Return 1 or 0 depending on whether ch is a whitespace character.

int Py_UNICODE_ISLOWER(Py_UNICODE ch)

Return 1 or 0 depending on whether ch is a lowercase character.

int Py_UNICODE_ISUPPER(Py_UNICODE ch)

Return 1 or 0 depending on whether ch is an uppercase character.

int Py_UNICODE_ISTITLE(Py_UNICODE ch)

Return 1 or 0 depending on whether ch is a titlecase character.

int Py_UNICODE_ISLINEBREAK(Py_UNICODE ch)

Return 1 or 0 depending on whether ch is a linebreak character.

int Py_UNICODE_ISDECIMAL(Py_UNICODE ch)

Return 1 or 0 depending on whether ch is a decimal character.

int Py_UNICODE_ISDIGIT(Py_UNICODE ch)

Return 1 or 0 depending on whether ch is a digit character.

int Py_UNICODE_ISNUMERIC(Py_UNICODE ch)

Return 1 or 0 depending on whether ch is a numeric character.

int Py_UNICODE_ISALPHA(Py_UNICODE ch)

Return 1 or 0 depending on whether ch is an alphabetic character.

int Py_UNICODE_ISALNUM(Py_UNICODE ch)

Return 1 or 0 depending on whether ch is an alphanumeric character.

int Py_UNICODE_ISPRINTABLE(Py_UNICODE ch)

Return 1 or 0 depending on whether ch is a printable character. Nonprintable characters are those characters defined in the Unicode character database as “Other” or “Separator”, excepting the ASCII space (0x20) which is considered printable. (Note that printable characters in this context are those which should not be escaped when repr() is invoked on a string. It has no bearing on the handling of strings written to sys.stdout or sys.stderr.)

These APIs can be used for fast direct character conversions:

Py_UNICODE Py_UNICODE_TOLOWER(Py_UNICODE ch)

Return the character ch converted to lower case.

버전 3.3부터 폐지: This function uses simple case mappings.

Py_UNICODE Py_UNICODE_TOUPPER(Py_UNICODE ch)

Return the character ch converted to upper case.

버전 3.3부터 폐지: This function uses simple case mappings.

Py_UNICODE Py_UNICODE_TOTITLE(Py_UNICODE ch)

Return the character ch converted to title case.

버전 3.3부터 폐지: This function uses simple case mappings.

int Py_UNICODE_TODECIMAL(Py_UNICODE ch)

Return the character ch converted to a decimal positive integer. Return -1 if this is not possible. This macro does not raise exceptions.

int Py_UNICODE_TODIGIT(Py_UNICODE ch)

Return the character ch converted to a single digit integer. Return -1 if this is not possible. This macro does not raise exceptions.

double Py_UNICODE_TONUMERIC(Py_UNICODE ch)

Return the character ch converted to a double. Return -1.0 if this is not possible. This macro does not raise exceptions.

These APIs can be used to work with surrogates:

Py_UNICODE_IS_SURROGATE(ch)

Check if ch is a surrogate (0xD800 <= ch <= 0xDFFF).

Py_UNICODE_IS_HIGH_SURROGATE(ch)

Check if ch is a high surrogate (0xD800 <= ch <= 0xDBFF).

Py_UNICODE_IS_LOW_SURROGATE(ch)

Check if ch is a low surrogate (0xDC00 <= ch <= 0xDFFF).

Py_UNICODE_JOIN_SURROGATES(high, low)

Join two surrogate characters and return a single Py_UCS4 value. high and low are respectively the leading and trailing surrogates in a surrogate pair.

Creating and accessing Unicode strings

To create Unicode objects and access their basic sequence properties, use these APIs:

PyObject* PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)

Return value: New reference.

Create a new Unicode object. maxchar should be the true maximum code point to be placed in the string. As an approximation, it can be rounded up to the nearest value in the sequence 127, 255, 65535, 1114111.

This is the recommended way to allocate a new Unicode object. Objects created using this function are not resizable.

버전 3.3에 추가.

PyObject* PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)

Return value: New reference.

Create a new Unicode object with the given kind (possible values are PyUnicode_1BYTE_KIND etc., as returned by PyUnicode_KIND()). The buffer must point to an array of size units of 1, 2 or 4 bytes per character, as given by the kind.

버전 3.3에 추가.

PyObject* PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)

Return value: New reference.

Create a Unicode object from the char buffer u. The bytes will be interpreted as being UTF-8 encoded. The buffer is copied into the new object. If the buffer is not NULL, the return value might be a shared object, i.e. modification of the data is not allowed.

If u is NULL, this function behaves like PyUnicode_FromUnicode() with the buffer set to NULL. This usage is deprecated in favor of PyUnicode_New().

PyObject *PyUnicode_FromString(const char *u)

Return value: New reference.

Create a Unicode object from a UTF-8 encoded null-terminated char buffer u.

PyObject* PyUnicode_FromFormat(const char *format, ...)

Return value: New reference.

Take a C printf()-style format string and a variable number of arguments, calculate the size of the resulting Python Unicode string and return a string with the values formatted into it. The variable arguments must be C types and must correspond exactly to the format characters in the format ASCII-encoded string. The following format characters are allowed:

Format Characters

Type

Comment

%%

n/a

The literal % character.

%c

int

A single character, represented as a C int.

%d

int

Equivalent to printf("%d"). 1

%u

unsigned int

Equivalent to printf("%u"). 1

%ld

long

Equivalent to printf("%ld"). 1

%li

long

Equivalent to printf("%li"). 1

%lu

unsigned long

Equivalent to printf("%lu"). 1

%lld

long long

Equivalent to printf("%lld"). 1

%lli

long long

Equivalent to printf("%lli"). 1

%llu

unsigned long long

Equivalent to printf("%llu"). 1

%zd

Py_ssize_t

Equivalent to printf("%zd"). 1

%zi

Py_ssize_t

Equivalent to printf("%zi"). 1

%zu

size_t

Equivalent to printf("%zu"). 1

%i

int

Equivalent to printf("%i"). 1

%x

int

Equivalent to printf("%x"). 1

%s

const char*

A null-terminated C character array.

%p

const void*

The hex representation of a C pointer. Mostly equivalent to printf("%p") except that it is guaranteed to start with the literal 0x regardless of what the platform’s printf yields.

%A

PyObject*

The result of calling ascii().

%U

PyObject*

A Unicode object.

%V

PyObject*, const char*

A Unicode object (which may be NULL) and a null-terminated C character array as a second parameter (which will be used, if the first parameter is NULL).

%S

PyObject*

The result of calling PyObject_Str().

%R

PyObject*

The result of calling PyObject_Repr().

An unrecognized format character causes all the rest of the format string to be copied as-is to the result string, and any extra arguments discarded.

참고

The width formatter unit is number of characters rather than bytes. The precision formatter unit is number of bytes for "%s" and "%V" (if the PyObject* argument is NULL), and a number of characters for "%A", "%U", "%S", "%R" and "%V" (if the PyObject* argument is not NULL).

1(1,2,3,4,5,6,7,8,9,10,11,12,13)

For integer specifiers (d, u, ld, li, lu, lld, lli, llu, zd, zi, zu, i, x): the 0-conversion flag has effect even when a precision is given.

버전 3.2에서 변경: Support for "%lld" and "%llu" added.

버전 3.3에서 변경: Support for "%li", "%lli" and "%zi" added.

버전 3.4에서 변경: Support width and precision formatter for "%s", "%A", "%U", "%V", "%S", "%R" added.

PyObject* PyUnicode_FromFormatV(const char *format, va_list vargs)

Return value: New reference.

Identical to PyUnicode_FromFormat() except that it takes exactly two arguments.

PyObject* PyUnicode_FromEncodedObject(PyObject *obj, const char *encoding, const char *errors)

Return value: New reference.

Decode an encoded object obj to a Unicode object.

bytes, bytearray and other bytes-like objects are decoded according to the given encoding and using the error handling defined by errors. Both can be NULL to have the interface use the default values (see Built-in Codecs for details).

All other objects, including Unicode objects, cause a TypeError to be set.

The API returns NULL if there was an error. The caller is responsible for decref’ing the returned objects.

Py_ssize_t PyUnicode_GetLength(PyObject *unicode)

Return the length of the Unicode object, in code points.

버전 3.3에 추가.

Py_ssize_t PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start, PyObject *from, Py_ssize_t from_start, Py_ssize_t how_many)

Copy characters from one Unicode object into another. This function performs character conversion when necessary and falls back to memcpy() if possible. Returns -1 and sets an exception on error, otherwise returns the number of copied characters.

버전 3.3에 추가.

Py_ssize_t PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length, Py_UCS4 fill_char)

Fill a string with a character: write fill_char into unicode[start:start+length].

Fail if fill_char is bigger than the string maximum character, or if the string has more than 1 reference.

Return the number of written character, or return -1 and raise an exception on error.

버전 3.3에 추가.

int PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 character)

Write a character to a string. The string must have been created through PyUnicode_New(). Since Unicode strings are supposed to be immutable, the string must not be shared, or have been hashed yet.

This function checks that unicode is a Unicode object, that the index is not out of bounds, and that the object can be modified safely (i.e. that it its reference count is one).

버전 3.3에 추가.

Py_UCS4 PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)

Read a character from a string. This function checks that unicode is a Unicode object and the index is not out of bounds, in contrast to the macro version PyUnicode_READ_CHAR().

버전 3.3에 추가.

PyObject* PyUnicode_Substring(PyObject *str, Py_ssize_t start, Py_ssize_t end)

Return value: New reference.

Return a substring of str, from character index start (included) to character index end (excluded). Negative indices are not supported.

버전 3.3에 추가.

Py_UCS4* PyUnicode_AsUCS4(PyObject *u, Py_UCS4 *buffer, Py_ssize_t buflen, int copy_null)

Copy the string u into a UCS4 buffer, including a null character, if copy_null is set. Returns NULL and sets an exception on error (in particular, a SystemError if buflen is smaller than the length of u). buffer is returned on success.

버전 3.3에 추가.

Py_UCS4* PyUnicode_AsUCS4Copy(PyObject *u)

Copy the string u into a new UCS4 buffer that is allocated using PyMem_Malloc(). If this fails, NULL is returned with a MemoryError set. The returned buffer always has an extra null code point appended.

버전 3.3에 추가.

Deprecated Py_UNICODE APIs

Deprecated since version 3.3, will be removed in version 4.0.

These API functions are deprecated with the implementation of PEP 393 [https://www.python.org/dev/peps/pep-0393]. Extension modules can continue using them, as they will not be removed in Python 3.x, but need to be aware that their use can now cause performance and memory hits.

PyObject* PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size)

Return value: New reference.

Create a Unicode object from the Py_UNICODE buffer u of the given size. u may be NULL which causes the contents to be undefined. It is the user’s responsibility to fill in the needed data. The buffer is copied into the new object.

If the buffer is not NULL, the return value might be a shared object. Therefore, modification of the resulting Unicode object is only allowed when u is NULL.

If the buffer is NULL, PyUnicode_READY() must be called once the string content has been filled before using any of the access macros such as PyUnicode_KIND().

Please migrate to using PyUnicode_FromKindAndData(), PyUnicode_FromWideChar() or PyUnicode_New().

Py_UNICODE* PyUnicode_AsUnicode(PyObject *unicode)

Return a read-only pointer to the Unicode object’s internal Py_UNICODE buffer, or NULL on error. This will create the Py_UNICODE* representation of the object if it is not yet available. The buffer is always terminated with an extra null code point. Note that the resulting Py_UNICODE string may also contain embedded null code points, which would cause the string to be truncated when used in most C functions.

Please migrate to using PyUnicode_AsUCS4(), PyUnicode_AsWideChar(), PyUnicode_ReadChar() or similar new APIs.

PyObject* PyUnicode_TransformDecimalToASCII(Py_UNICODE *s, Py_ssize_t size)

Return value: New reference.

Create a Unicode object by replacing all decimal digits in Py_UNICODE buffer of the given size by ASCII digits 0–9 according to their decimal value. Return NULL if an exception occurs.

Py_UNICODE* PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)

Like PyUnicode_AsUnicode(), but also saves the Py_UNICODE() array length (excluding the extra null terminator) in size. Note that the resulting Py_UNICODE* string may contain embedded null code points, which would cause the string to be truncated when used in most C functions.

버전 3.3에 추가.

Py_UNICODE* PyUnicode_AsUnicodeCopy(PyObject *unicode)

Create a copy of a Unicode string ending with a null code point. Return NULL and raise a MemoryError exception on memory allocation failure, otherwise return a new allocated buffer (use PyMem_Free() to free the buffer). Note that the resulting Py_UNICODE* string may contain embedded null code points, which would cause the string to be truncated when used in most C functions.

버전 3.2에 추가.

Please migrate to using PyUnicode_AsUCS4Copy() or similar new APIs.

Py_ssize_t PyUnicode_GetSize(PyObject *unicode)

Return the size of the deprecated Py_UNICODE representation, in code units (this includes surrogate pairs as 2 units).

Please migrate to using PyUnicode_GetLength().

PyObject* PyUnicode_FromObject(PyObject *obj)

Return value: New reference.

Copy an instance of a Unicode subtype to a new true Unicode object if necessary. If obj is already a true Unicode object (not a subtype), return the reference with incremented refcount.

Objects other than Unicode or its subtypes will cause a TypeError.

Locale Encoding

The current locale encoding can be used to decode text from the operating system.

PyObject* PyUnicode_DecodeLocaleAndSize(const char *str, Py_ssize_t len, const char *errors)

Return value: New reference.

Decode a string from UTF-8 on Android, or from the current locale encoding on other platforms. The supported error handlers are "strict" and "surrogateescape" (PEP 383 [https://www.python.org/dev/peps/pep-0383]). The decoder uses "strict" error handler if errors is NULL. str must end with a null character but cannot contain embedded null characters.

Use PyUnicode_DecodeFSDefaultAndSize() to decode a string from Py_FileSystemDefaultEncoding (the locale encoding read at Python startup).

This function ignores the Python UTF-8 mode.

더 보기

The Py_DecodeLocale() function.

버전 3.3에 추가.

버전 3.7에서 변경: The function now also uses the current locale encoding for the surrogateescape error handler, except on Android. Previously, Py_DecodeLocale() was used for the surrogateescape, and the current locale encoding was used for strict.

PyObject* PyUnicode_DecodeLocale(const char *str, const char *errors)

Return value: New reference.

Similar to PyUnicode_DecodeLocaleAndSize(), but compute the string length using strlen().

버전 3.3에 추가.

PyObject* PyUnicode_EncodeLocale(PyObject *unicode, const char *errors)

Return value: New reference.

Encode a Unicode object to UTF-8 on Android, or to the current locale encoding on other platforms. The supported error handlers are "strict" and "surrogateescape" (PEP 383 [https://www.python.org/dev/peps/pep-0383]). The encoder uses "strict" error handler if errors is NULL. Return a bytes object. unicode cannot contain embedded null characters.

Use PyUnicode_EncodeFSDefault() to encode a string to Py_FileSystemDefaultEncoding (the locale encoding read at Python startup).

This function ignores the Python UTF-8 mode.

더 보기

The Py_EncodeLocale() function.

버전 3.3에 추가.

버전 3.7에서 변경: The function now also uses the current locale encoding for the surrogateescape error handler, except on Android. Previously, Py_EncodeLocale() was used for the surrogateescape, and the current locale encoding was used for strict.

File System Encoding

To encode and decode file names and other environment strings, Py_FileSystemDefaultEncoding should be used as the encoding, and Py_FileSystemDefaultEncodeErrors should be used as the error handler (PEP 383 [https://www.python.org/dev/peps/pep-0383] and PEP 529 [https://www.python.org/dev/peps/pep-0529]). To encode file names to bytes during argument parsing, the "O&" converter should be used, passing PyUnicode_FSConverter() as the conversion function:

int PyUnicode_FSConverter(PyObject* obj, void* result)

ParseTuple converter: encode str objects – obtained directly or through the os.PathLike interface – to bytes using PyUnicode_EncodeFSDefault(); bytes objects are output as-is. result must be a PyBytesObject* which must be released when it is no longer used.

버전 3.1에 추가.

버전 3.6에서 변경: Accepts a path-like object.

To decode file names to str during argument parsing, the "O&" converter should be used, passing PyUnicode_FSDecoder() as the conversion function:

int PyUnicode_FSDecoder(PyObject* obj, void* result)

ParseTuple converter: decode bytes objects – obtained either directly or indirectly through the os.PathLike interface – to str using PyUnicode_DecodeFSDefaultAndSize(); str objects are output as-is. result must be a PyUnicodeObject* which must be released when it is no longer used.

버전 3.2에 추가.

버전 3.6에서 변경: Accepts a path-like object.

PyObject* PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)

Return value: New reference.

Decode a string using Py_FileSystemDefaultEncoding and the Py_FileSystemDefaultEncodeErrors error handler.

If Py_FileSystemDefaultEncoding is not set, fall back to the locale encoding.

Py_FileSystemDefaultEncoding is initialized at startup from the locale encoding and cannot be modified later. If you need to decode a string from the current locale encoding, use PyUnicode_DecodeLocaleAndSize().

더 보기

The Py_DecodeLocale() function.

버전 3.6에서 변경: Use Py_FileSystemDefaultEncodeErrors error handler.

PyObject* PyUnicode_DecodeFSDefault(const char *s)

Return value: New reference.

Decode a null-terminated string using Py_FileSystemDefaultEncoding and the Py_FileSystemDefaultEncodeErrors error handler.

If Py_FileSystemDefaultEncoding is not set, fall back to the locale encoding.

Use PyUnicode_DecodeFSDefaultAndSize() if you know the string length.

버전 3.6에서 변경: Use Py_FileSystemDefaultEncodeErrors error handler.

PyObject* PyUnicode_EncodeFSDefault(PyObject *unicode)

Return value: New reference.

Encode a Unicode object to Py_FileSystemDefaultEncoding with the Py_FileSystemDefaultEncodeErrors error handler, and return bytes. Note that the resulting bytes object may contain null bytes.

If Py_FileSystemDefaultEncoding is not set, fall back to the locale encoding.

Py_FileSystemDefaultEncoding is initialized at startup from the locale encoding and cannot be modified later. If you need to encode a string to the current locale encoding, use PyUnicode_EncodeLocale().

더 보기

The Py_EncodeLocale() function.

버전 3.2에 추가.

버전 3.6에서 변경: Use Py_FileSystemDefaultEncodeErrors error handler.

wchar_t Support

wchar_t support for platforms which support it:

PyObject* PyUnicode_FromWideChar(const wchar_t *w, Py_ssize_t size)

Return value: New reference.

Create a Unicode object from the wchar_t buffer w of the given size. Passing -1 as the size indicates that the function must itself compute the length, using wcslen. Return NULL on failure.

Py_ssize_t PyUnicode_AsWideChar(PyObject *unicode, wchar_t *w, Py_ssize_t size)

Copy the Unicode object contents into the wchar_t buffer w. At most size wchar_t characters are copied (excluding a possibly trailing null termination character). Return the number of wchar_t characters copied or -1 in case of an error. Note that the resulting wchar_t* string may or may not be null-terminated. It is the responsibility of the caller to make sure that the wchar_t* string is null-terminated in case this is required by the application. Also, note that the wchar_t* string might contain null characters, which would cause the string to be truncated when used with most C functions.

wchar_t* PyUnicode_AsWideCharString(PyObject *unicode, Py_ssize_t *size)

Convert the Unicode object to a wide character string. The output string always ends with a null character. If size is not NULL, write the number of wide characters (excluding the trailing null termination character) into *size. Note that the resulting wchar_t string might contain null characters, which would cause the string to be truncated when used with most C functions. If size is NULL and the wchar_t* string contains null characters a ValueError is raised.

Returns a buffer allocated by PyMem_Alloc() (use PyMem_Free() to free it) on success. On error, returns NULL and *size is undefined. Raises a MemoryError if memory allocation is failed.

버전 3.2에 추가.

버전 3.7에서 변경: Raises a ValueError if size is NULL and the wchar_t* string contains null characters.

Built-in Codecs

Python provides a set of built-in codecs which are written in C for speed. All of these codecs are directly usable via the following functions.

Many of the following APIs take two arguments encoding and errors, and they have the same semantics as the ones of the built-in str() string object constructor.

Setting encoding to NULL causes the default encoding to be used which is ASCII. The file system calls should use PyUnicode_FSConverter() for encoding file names. This uses the variable Py_FileSystemDefaultEncoding internally. This variable should be treated as read-only: on some systems, it will be a pointer to a static string, on others, it will change at run-time (such as when the application invokes setlocale).

Error handling is set by errors which may also be set to NULL meaning to use the default handling defined for the codec. Default error handling for all built-in codecs is “strict” (ValueError is raised).

The codecs all use a similar interface. Only deviation from the following generic ones are documented for simplicity.

Generic Codecs

These are the generic codec APIs:

PyObject* PyUnicode_Decode(const char *s, Py_ssize_t size, const char *encoding, const char *errors)

Return value: New reference.

Create a Unicode object by decoding size bytes of the encoded string s. encoding and errors have the same meaning as the parameters of the same name in the str() built-in function. The codec to be used is looked up using the Python codec registry. Return NULL if an exception was raised by the codec.

PyObject* PyUnicode_AsEncodedString(PyObject *unicode, const char *encoding, const char *errors)

Return value: New reference.

Encode a Unicode object and return the result as Python bytes object. encoding and errors have the same meaning as the parameters of the same name in the Unicode encode() method. The codec to be used is looked up using the Python codec registry. Return NULL if an exception was raised by the codec.

PyObject* PyUnicode_Encode(const Py_UNICODE *s, Py_ssize_t size, const char *encoding, const char *errors)

Return value: New reference.

Encode the Py_UNICODE buffer s of the given size and return a Python bytes object. encoding and errors have the same meaning as the parameters of the same name in the Unicode encode() method. The codec to be used is looked up using the Python codec registry. Return NULL if an exception was raised by the codec.

Deprecated since version 3.3, will be removed in version 4.0: Part of the old-style Py_UNICODE API; please migrate to using PyUnicode_AsEncodedString().

UTF-8 Codecs

These are the UTF-8 codec APIs:

PyObject* PyUnicode_DecodeUTF8(const char *s, Py_ssize_t size, const char *errors)

Return value: New reference.

Create a Unicode object by decoding size bytes of the UTF-8 encoded string s. Return NULL if an exception was raised by the codec.

PyObject* PyUnicode_DecodeUTF8Stateful(const char *s, Py_ssize_t size, const char *errors, Py_ssize_t *consumed)

Return value: New reference.

If consumed is NULL, behave like PyUnicode_DecodeUTF8(). If consumed is not NULL, trailing incomplete UTF-8 byte sequences will not be treated as an error. Those bytes will not be decoded and the number of bytes that have been decoded will be stored in consumed.

PyObject* PyUnicode_AsUTF8String(PyObject *unicode)

Return value: New reference.

Encode a Unicode object using UTF-8 and return the result as Python bytes object. Error handling is “strict”. Return NULL if an exception was raised by the codec.

const char* PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *size)

Return a pointer to the UTF-8 encoding of the Unicode object, and store the size of the encoded representation (in bytes) in size. The size argument can be NULL; in this case no size will be stored. The returned buffer always has an extra null byte appended (not included in size), regardless of whether there are any other null code points.

In the case of an error, NULL is returned with an exception set and no size is stored.

This caches the UTF-8 representation of the string in the Unicode object, and subsequent calls will return a pointer to the same buffer. The caller is not responsible for deallocating the buffer.

버전 3.3에 추가.

버전 3.7에서 변경: The return type is now const char * rather of char *.

const char* PyUnicode_AsUTF8(PyObject *unicode)

As PyUnicode_AsUTF8AndSize(), but does not store the size.

버전 3.3에 추가.

버전 3.7에서 변경: The return type is now const char * rather of char *.

PyObject* PyUnicode_EncodeUTF8(const Py_UNICODE *s, Py_ssize_t size, const char *errors)

Return value: New reference.

Encode the Py_UNICODE buffer s of the given size using UTF-8 and return a Python bytes object. Return NULL if an exception was raised by the codec.

Deprecated since version 3.3, will be removed in version 4.0: Part of the old-style Py_UNICODE API; please migrate to using PyUnicode_AsUTF8String(), PyUnicode_AsUTF8AndSize() or PyUnicode_AsEncodedString().

UTF-32 Codecs

These are the UTF-32 codec APIs:

PyObject* PyUnicode_DecodeUTF32(const char *s, Py_ssize_t size, const char *errors, int *byteorder)

Return value: New reference.

Decode size bytes from a UTF-32 encoded buffer string and return the corresponding Unicode object. errors (if non-NULL) defines the error handling. It defaults to “strict”.

If byteorder is non-NULL, the decoder starts decoding using the given byte order:

*byteorder == -1: little endian
*byteorder == 0:  native order
*byteorder == 1:  big endian

If *byteorder is zero, and the first four bytes of the input data are a byte order mark (BOM), the decoder switches to this byte order and the BOM is not copied into the resulting Unicode string. If *byteorder is -1 or 1, any byte order mark is copied to the output.

After completion, *byteorder is set to the current byte order at the end of input data.

If byteorder is NULL, the codec starts in native order mode.

Return NULL if an exception was raised by the codec.

PyObject* PyUnicode_DecodeUTF32Stateful(const char *s, Py_ssize_t size, const char *errors, int *byteorder, Py_ssize_t *consumed)

Return value: New reference.

If consumed is NULL, behave like PyUnicode_DecodeUTF32(). If consumed is not NULL, PyUnicode_DecodeUTF32Stateful() will not treat trailing incomplete UTF-32 byte sequences (such as a number of bytes not divisible by four) as an error. Those bytes will not be decoded and the number of bytes that have been decoded will be stored in consumed.

PyObject* PyUnicode_AsUTF32String(PyObject *unicode)

Return value: New reference.

Return a Python byte string using the UTF-32 encoding in native byte order. The string always starts with a BOM mark. Error handling is “strict”. Return NULL if an exception was raised by the codec.

PyObject* PyUnicode_EncodeUTF32(const Py_UNICODE *s, Py_ssize_t size, const char *errors, int byteorder)

Return value: New reference.

Return a Python bytes object holding the UTF-32 encoded value of the Unicode data in s. Output is written according to the following byte order:

byteorder == -1: little endian
byteorder == 0:  native byte order (writes a BOM mark)
byteorder == 1:  big endian

If byteorder is 0, the output string will always start with the Unicode BOM mark (U+FEFF). In the other two modes, no BOM mark is prepended.

If Py_UNICODE_WIDE is not defined, surrogate pairs will be output as a single code point.

Return NULL if an exception was raised by the codec.

Deprecated since version 3.3, will be removed in version 4.0: Part of the old-style Py_UNICODE API; please migrate to using PyUnicode_AsUTF32String() or PyUnicode_AsEncodedString().

UTF-16 Codecs

These are the UTF-16 codec APIs:

PyObject* PyUnicode_DecodeUTF16(const char *s, Py_ssize_t size, const char *errors, int *byteorder)

Return value: New reference.

Decode size bytes from a UTF-16 encoded buffer string and return the corresponding Unicode object. errors (if non-NULL) defines the error handling. It defaults to “strict”.

If byteorder is non-NULL, the decoder starts decoding using the given byte order:

*byteorder == -1: little endian
*byteorder == 0:  native order
*byteorder == 1:  big endian

If *byteorder is zero, and the first two bytes of the input data are a byte order mark (BOM), the decoder switches to this byte order and the BOM is not copied into the resulting Unicode string. If *byteorder is -1 or 1, any byte order mark is copied to the output (where it will result in either a \ufeff or a \ufffe character).

After completion, *byteorder is set to the current byte order at the end of input data.

If byteorder is NULL, the codec starts in native order mode.

Return NULL if an exception was raised by the codec.

PyObject* PyUnicode_DecodeUTF16Stateful(const char *s, Py_ssize_t size, const char *errors, int *byteorder, Py_ssize_t *consumed)

Return value: New reference.

If consumed is NULL, behave like PyUnicode_DecodeUTF16(). If consumed is not NULL, PyUnicode_DecodeUTF16Stateful() will not treat trailing incomplete UTF-16 byte sequences (such as an odd number of bytes or a split surrogate pair) as an error. Those bytes will not be decoded and the number of bytes that have been decoded will be stored in consumed.

PyObject* PyUnicode_AsUTF16String(PyObject *unicode)

Return value: New reference.

Return a Python byte string using the UTF-16 encoding in native byte order. The string always starts with a BOM mark. Error handling is “strict”. Return NULL if an exception was raised by the codec.

PyObject* PyUnicode_EncodeUTF16(const Py_UNICODE *s, Py_ssize_t size, const char *errors, int byteorder)

Return value: New reference.

Return a Python bytes object holding the UTF-16 encoded value of the Unicode data in s. Output is written according to the following byte order:

byteorder == -1: little endian
byteorder == 0:  native byte order (writes a BOM mark)
byteorder == 1:  big endian

If byteorder is 0, the output string will always start with the Unicode BOM mark (U+FEFF). In the other two modes, no BOM mark is prepended.

If Py_UNICODE_WIDE is defined, a single Py_UNICODE value may get represented as a surrogate pair. If it is not defined, each Py_UNICODE values is interpreted as a UCS-2 character.

Return NULL if an exception was raised by the codec.

Deprecated since version 3.3, will be removed in version 4.0: Part of the old-style Py_UNICODE API; please migrate to using PyUnicode_AsUTF16String() or PyUnicode_AsEncodedString().

UTF-7 Codecs

These are the UTF-7 codec APIs:

PyObject* PyUnicode_DecodeUTF7(const char *s, Py_ssize_t size, const char *errors)

Return value: New reference.

Create a Unicode object by decoding size bytes of the UTF-7 encoded string s. Return NULL if an exception was raised by the codec.

PyObject* PyUnicode_DecodeUTF7Stateful(const char *s, Py_ssize_t size, const char *errors, Py_ssize_t *consumed)

Return value: New reference.

If consumed is NULL, behave like PyUnicode_DecodeUTF7(). If consumed is not NULL, trailing incomplete UTF-7 base-64 sections will not be treated as an error. Those bytes will not be decoded and the number of bytes that have been decoded will be stored in consumed.

PyObject* PyUnicode_EncodeUTF7(const Py_UNICODE *s, Py_ssize_t size, int base64SetO, int base64WhiteSpace, const char *errors)

Return value: New reference.

Encode the Py_UNICODE buffer of the given size using UTF-7 and return a Python bytes object. Return NULL if an exception was raised by the codec.

If base64SetO is nonzero, “Set O” (punctuation that has no otherwise special meaning) will be encoded in base-64. If base64WhiteSpace is nonzero, whitespace will be encoded in base-64. Both are set to zero for the Python “utf-7” codec.

Deprecated since version 3.3, will be removed in version 4.0: Part of the old-style Py_UNICODE API; please migrate to using PyUnicode_AsEncodedString().

Unicode-Escape Codecs

These are the “Unicode Escape” codec APIs:

PyObject* PyUnicode_DecodeUnicodeEscape(const char *s, Py_ssize_t size, const char *errors)

Return value: New reference.

Create a Unicode object by decoding size bytes of the Unicode-Escape encoded string s. Return NULL if an exception was raised by the codec.

PyObject* PyUnicode_AsUnicodeEscapeString(PyObject *unicode)

Return value: New reference.

Encode a Unicode object using Unicode-Escape and return the result as a bytes object. Error handling is “strict”. Return NULL if an exception was raised by the codec.

PyObject* PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s, Py_ssize_t size)

Return value: New reference.

Encode the Py_UNICODE buffer of the given size using Unicode-Escape and return a bytes object. Return NULL if an exception was raised by the codec.

Deprecated since version 3.3, will be removed in version 4.0: Part of the old-style Py_UNICODE API; please migrate to using PyUnicode_AsUnicodeEscapeString().

Raw-Unicode-Escape Codecs

These are the “Raw Unicode Escape” codec APIs:

PyObject* PyUnicode_DecodeRawUnicodeEscape(const char *s, Py_ssize_t size, const char *errors)

Return value: New reference.

Create a Unicode object by decoding size bytes of the Raw-Unicode-Escape encoded string s. Return NULL if an exception was raised by the codec.

PyObject* PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)

Return value: New reference.

Encode a Unicode object using Raw-Unicode-Escape and return the result as a bytes object. Error handling is “strict”. Return NULL if an exception was raised by the codec.

PyObject* PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s, Py_ssize_t size)

Return value: New reference.

Encode the Py_UNICODE buffer of the given size using Raw-Unicode-Escape and return a bytes object. Return NULL if an exception was raised by the codec.

Deprecated since version 3.3, will be removed in version 4.0: Part of the old-style Py_UNICODE API; please migrate to using PyUnicode_AsRawUnicodeEscapeString() or PyUnicode_AsEncodedString().

Latin-1 Codecs

These are the Latin-1 codec APIs: Latin-1 corresponds to the first 256 Unicode ordinals and only these are accepted by the codecs during encoding.

PyObject* PyUnicode_DecodeLatin1(const char *s, Py_ssize_t size, const char *errors)

Return value: New reference.

Create a Unicode object by decoding size bytes of the Latin-1 encoded string s. Return NULL if an exception was raised by the codec.

PyObject* PyUnicode_AsLatin1String(PyObject *unicode)

Return value: New reference.

Encode a Unicode object using Latin-1 and return the result as Python bytes object. Error handling is “strict”. Return NULL if an exception was raised by the codec.

PyObject* PyUnicode_EncodeLatin1(const Py_UNICODE *s, Py_ssize_t size, const char *errors)

Return value: New reference.

Encode the Py_UNICODE buffer of the given size using Latin-1 and return a Python bytes object. Return NULL if an exception was raised by the codec.

Deprecated since version 3.3, will be removed in version 4.0: Part of the old-style Py_UNICODE API; please migrate to using PyUnicode_AsLatin1String() or PyUnicode_AsEncodedString().

ASCII Codecs

These are the ASCII codec APIs. Only 7-bit ASCII data is accepted. All other codes generate errors.

PyObject* PyUnicode_DecodeASCII(const char *s, Py_ssize_t size, const char *errors)

Return value: New reference.

Create a Unicode object by decoding size bytes of the ASCII encoded string s. Return NULL if an exception was raised by the codec.

PyObject* PyUnicode_AsASCIIString(PyObject *unicode)

Return value: New reference.

Encode a Unicode object using ASCII and return the result as Python bytes object. Error handling is “strict”. Return NULL if an exception was raised by the codec.

PyObject* PyUnicode_EncodeASCII(const Py_UNICODE *s, Py_ssize_t size, const char *errors)

Return value: New reference.

Encode the Py_UNICODE buffer of the given size using ASCII and return a Python bytes object. Return NULL if an exception was raised by the codec.

Deprecated since version 3.3, will be removed in version 4.0: Part of the old-style Py_UNICODE API; please migrate to using PyUnicode_AsASCIIString() or PyUnicode_AsEncodedString().

Character Map Codecs

This codec is special in that it can be used to implement many different codecs (and this is in fact what was done to obtain most of the standard codecs included in the encodings package). The codec uses mapping to encode and decode characters. The mapping objects provided must support the __getitem__() mapping interface; dictionaries and sequences work well.

These are the mapping codec APIs:

PyObject* PyUnicode_DecodeCharmap(const char *data, Py_ssize_t size, PyObject *mapping, const char *errors)

Return value: New reference.

Create a Unicode object by decoding size bytes of the encoded string s using the given mapping object. Return NULL if an exception was raised by the codec.

If mapping is NULL, Latin-1 decoding will be applied. Else mapping must map bytes ordinals (integers in the range from 0 to 255) to Unicode strings, integers (which are then interpreted as Unicode ordinals) or None. Unmapped data bytes – ones which cause a LookupError, as well as ones which get mapped to None, 0xFFFE or '\ufffe', are treated as undefined mappings and cause an error.

PyObject* PyUnicode_AsCharmapString(PyObject *unicode, PyObject *mapping)

Return value: New reference.

Encode a Unicode object using the given mapping object and return the result as a bytes object. Error handling is “strict”. Return NULL if an exception was raised by the codec.

The mapping object must map Unicode ordinal integers to bytes objects, integers in the range from 0 to 255 or None. Unmapped character ordinals (ones which cause a LookupError) as well as mapped to None are treated as “undefined mapping” and cause an error.

PyObject* PyUnicode_EncodeCharmap(const Py_UNICODE *s, Py_ssize_t size, PyObject *mapping, const char *errors)

Return value: New reference.

Encode the Py_UNICODE buffer of the given size using the given mapping object and return the result as a bytes object. Return NULL if an exception was raised by the codec.

Deprecated since version 3.3, will be removed in version 4.0: Part of the old-style Py_UNICODE API; please migrate to using PyUnicode_AsCharmapString() or PyUnicode_AsEncodedString().

The following codec API is special in that maps Unicode to Unicode.

PyObject* PyUnicode_Translate(PyObject *unicode, PyObject *mapping, const char *errors)

Return value: New reference.

Translate a Unicode object using the given mapping object and return the resulting Unicode object. Return NULL if an exception was raised by the codec.

The mapping object must map Unicode ordinal integers to Unicode strings, integers (which are then interpreted as Unicode ordinals) or None (causing deletion of the character). Unmapped character ordinals (ones which cause a LookupError) are left untouched and are copied as-is.

PyObject* PyUnicode_TranslateCharmap(const Py_UNICODE *s, Py_ssize_t size, PyObject *mapping, const char *errors)

Return value: New reference.

Translate a Py_UNICODE buffer of the given size by applying a character mapping table to it and return the resulting Unicode object. Return NULL when an exception was raised by the codec.

Deprecated since version 3.3, will be removed in version 4.0: Part of the old-style Py_UNICODE API; please migrate to using PyUnicode_Translate(). or generic codec based API

MBCS codecs for Windows

These are the MBCS codec APIs. They are currently only available on Windows and use the Win32 MBCS converters to implement the conversions. Note that MBCS (or DBCS) is a class of encodings, not just one. The target encoding is defined by the user settings on the machine running the codec.

PyObject* PyUnicode_DecodeMBCS(const char *s, Py_ssize_t size, const char *errors)

Return value: New reference.

Create a Unicode object by decoding size bytes of the MBCS encoded string s. Return NULL if an exception was raised by the codec.

PyObject* PyUnicode_DecodeMBCSStateful(const char *s, Py_ssize_t size, const char *errors, Py_ssize_t *consumed)

Return value: New reference.

If consumed is NULL, behave like PyUnicode_DecodeMBCS(). If consumed is not NULL, PyUnicode_DecodeMBCSStateful() will not decode trailing lead byte and the number of bytes that have been decoded will be stored in consumed.

PyObject* PyUnicode_AsMBCSString(PyObject *unicode)

Return value: New reference.

Encode a Unicode object using MBCS and return the result as Python bytes object. Error handling is “strict”. Return NULL if an exception was raised by the codec.

PyObject* PyUnicode_EncodeCodePage(int code_page, PyObject *unicode, const char *errors)

Return value: New reference.

Encode the Unicode object using the specified code page and return a Python bytes object. Return NULL if an exception was raised by the codec. Use CP_ACP code page to get the MBCS encoder.

버전 3.3에 추가.

PyObject* PyUnicode_EncodeMBCS(const Py_UNICODE *s, Py_ssize_t size, const char *errors)

Return value: New reference.

Encode the Py_UNICODE buffer of the given size using MBCS and return a Python bytes object. Return NULL if an exception was raised by the codec.

Deprecated since version 3.3, will be removed in version 4.0: Part of the old-style Py_UNICODE API; please migrate to using PyUnicode_AsMBCSString(), PyUnicode_EncodeCodePage() or PyUnicode_AsEncodedString().

Methods & Slots

Methods and Slot Functions

The following APIs are capable of handling Unicode objects and strings on input (we refer to them as strings in the descriptions) and return Unicode objects or integers as appropriate.

They all return NULL or -1 if an exception occurs.

PyObject* PyUnicode_Concat(PyObject *left, PyObject *right)

Return value: New reference.

Concat two strings giving a new Unicode string.

PyObject* PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)

Return value: New reference.

Split a string giving a list of Unicode strings. If sep is NULL, splitting will be done at all whitespace substrings. Otherwise, splits occur at the given separator. At most maxsplit splits will be done. If negative, no limit is set. Separators are not included in the resulting list.

PyObject* PyUnicode_Splitlines(PyObject *s, int keepend)

Return value: New reference.

Split a Unicode string at line breaks, returning a list of Unicode strings. CRLF is considered to be one line break. If keepend is 0, the Line break characters are not included in the resulting strings.

PyObject* PyUnicode_Translate(PyObject *str, PyObject *table, const char *errors)

Translate a string by applying a character mapping table to it and return the resulting Unicode object.

The mapping table must map Unicode ordinal integers to Unicode ordinal integers or None (causing deletion of the character).

Mapping tables need only provide the __getitem__() interface; dictionaries and sequences work well. Unmapped character ordinals (ones which cause a LookupError) are left untouched and are copied as-is.

errors has the usual meaning for codecs. It may be NULL which indicates to use the default error handling.

PyObject* PyUnicode_Join(PyObject *separator, PyObject *seq)

Return value: New reference.

Join a sequence of strings using the given separator and return the resulting Unicode string.

Py_ssize_t PyUnicode_Tailmatch(PyObject *str, PyObject *substr, Py_ssize_t start, Py_ssize_t end, int direction)

Return 1 if substr matches str[start:end] at the given tail end (direction == -1 means to do a prefix match, direction == 1 a suffix match), 0 otherwise. Return -1 if an error occurred.

Py_ssize_t PyUnicode_Find(PyObject *str, PyObject *substr, Py_ssize_t start, Py_ssize_t end, int direction)

Return the first position of substr in str[start:end] using the given direction (direction == 1 means to do a forward search, direction == -1 a backward search). The return value is the index of the first match; a value of -1 indicates that no match was found, and -2 indicates that an error occurred and an exception has been set.

Py_ssize_t PyUnicode_FindChar(PyObject *str, Py_UCS4 ch, Py_ssize_t start, Py_ssize_t end, int direction)

Return the first position of the character ch in str[start:end] using the given direction (direction == 1 means to do a forward search, direction == -1 a backward search). The return value is the index of the first match; a value of -1 indicates that no match was found, and -2 indicates that an error occurred and an exception has been set.

버전 3.3에 추가.

버전 3.7에서 변경: start and end are now adjusted to behave like str[start:end].

Py_ssize_t PyUnicode_Count(PyObject *str, PyObject *substr, Py_ssize_t start, Py_ssize_t end)

Return the number of non-overlapping occurrences of substr in str[start:end]. Return -1 if an error occurred.

PyObject* PyUnicode_Replace(PyObject *str, PyObject *substr, PyObject *replstr, Py_ssize_t maxcount)

Return value: New reference.

Replace at most maxcount occurrences of substr in str with replstr and return the resulting Unicode object. maxcount == -1 means replace all occurrences.

int PyUnicode_Compare(PyObject *left, PyObject *right)

Compare two strings and return -1, 0, 1 for less than, equal, and greater than, respectively.

This function returns -1 upon failure, so one should call PyErr_Occurred() to check for errors.

int PyUnicode_CompareWithASCIIString(PyObject *uni, const char *string)

Compare a Unicode object, uni, with string and return -1, 0, 1 for less than, equal, and greater than, respectively. It is best to pass only ASCII-encoded strings, but the function interprets the input string as ISO-8859-1 if it contains non-ASCII characters.

This function does not raise exceptions.

PyObject* PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)

Return value: New reference.

Rich compare two Unicode strings and return one of the following:

NULL in case an exception was raised

Py_True or Py_False for successful comparisons

Py_NotImplemented in case the type combination is unknown

Possible values for op are Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, and Py_LE.

PyObject* PyUnicode_Format(PyObject *format, PyObject *args)

Return value: New reference.

Return a new string object from format and args; this is analogous to format % args.

int PyUnicode_Contains(PyObject *container, PyObject *element)

Check whether element is contained in container and return true or false accordingly.

element has to coerce to a one element Unicode string. -1 is returned if there was an error.

void PyUnicode_InternInPlace(PyObject **string)

Intern the argument *string in place. The argument must be the address of a pointer variable pointing to a Python Unicode string object. If there is an existing interned string that is the same as *string, it sets *string to it (decrementing the reference count of the old string object and incrementing the reference count of the interned string object), otherwise it leaves *string alone and interns it (incrementing its reference count). (Clarification: even though there is a lot of talk about reference counts, think of this function as reference-count-neutral; you own the object after the call if and only if you owned it before the call.)

PyObject* PyUnicode_InternFromString(const char *v)

Return value: New reference.

A combination of PyUnicode_FromString() and PyUnicode_InternInPlace(), returning either a new Unicode string object that has been interned, or a new (“owned”) reference to an earlier interned string object with the same value.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

구상 객체 계층 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

구상 객체 계층 »

|

튜플 객체

PyTupleObject

이 PyObject의 서브 형은 파이썬 튜플 객체를 나타냅니다.

PyTypeObject PyTuple_Type

이 PyTypeObject 인스턴스는 파이썬 튜플 형을 나타냅니다. 파이썬 계층의 tuple과 같은 객체입니다.

int PyTuple_Check(PyObject *p)

p가 튜플 객체이거나 튜플 형의 서브 형의 인스턴스면 참을 돌려줍니다.

int PyTuple_CheckExact(PyObject *p)

p가 튜플 객체이지만, 튜플 형의 서브 형의 인스턴스는 아니면 참을 돌려줍니다.

PyObject* PyTuple_New(Py_ssize_t len)

Return value: New reference.

Return a new tuple object of size len, or NULL on failure.

PyObject* PyTuple_Pack(Py_ssize_t n, ...)

Return value: New reference.

Return a new tuple object of size n, or NULL on failure. The tuple values are initialized to the subsequent n C arguments pointing to Python objects. PyTuple_Pack(2, a, b) is equivalent to Py_BuildValue("(OO)", a, b).

Py_ssize_t PyTuple_Size(PyObject *p)

튜플 객체에 대한 포인터를 받아서, 해당 튜플의 크기를 반환합니다.

Py_ssize_t PyTuple_GET_SIZE(PyObject *p)

Return the size of the tuple p, which must be non-NULL and point to a tuple; no error checking is performed.

PyObject* PyTuple_GetItem(PyObject *p, Py_ssize_t pos)

Return value: Borrowed reference.

Return the object at position pos in the tuple pointed to by p. If pos is out of bounds, return NULL and set an IndexError exception.

PyObject* PyTuple_GET_ITEM(PyObject *p, Py_ssize_t pos)

Return value: Borrowed reference.

PyTuple_GetItem()와 비슷하지만, 인자를 확인하지 않습니다.

PyObject* PyTuple_GetSlice(PyObject *p, Py_ssize_t low, Py_ssize_t high)

Return value: New reference.

Return the slice of the tuple pointed to by p between low and high, or NULL on failure. This is the equivalent of the Python expression p[low:high]. Indexing from the end of the list is not supported.

int PyTuple_SetItem(PyObject *p, Py_ssize_t pos, PyObject *o)

Insert a reference to object o at position pos of the tuple pointed to by p. Return 0 on success. If pos is out of bounds, return -1 and set an IndexError exception.

참고

This function “steals” a reference to o and discards a reference to an item already in the tuple at the affected position.

void PyTuple_SET_ITEM(PyObject *p, Py_ssize_t pos, PyObject *o)

PyTuple_SetItem()과 비슷하지만, 에러 검사는 하지 않으며 새로운 튜플을 채울 때*만* 사용해야 합니다.

참고

This macro “steals” a reference to o, and, unlike PyTuple_SetItem(), does not discard a reference to any item that is being replaced; any reference in the tuple at position pos will be leaked.

int _PyTuple_Resize(PyObject **p, Py_ssize_t newsize)

Can be used to resize a tuple. newsize will be the new length of the tuple. Because tuples are supposed to be immutable, this should only be used if there is only one reference to the object. Do not use this if the tuple may already be known to some other part of the code. The tuple will always grow or shrink at the end. Think of this as destroying the old tuple and creating a new one, only more efficiently. Returns 0 on success. Client code should never assume that the resulting value of *p will be the same as before calling this function. If the object referenced by *p is replaced, the original *p is destroyed. On failure, returns -1 and sets *p to NULL, and raises MemoryError or SystemError.

int PyTuple_ClearFreeList()

자유 목록(free list)을 지웁니다. 해제된 총 항목 수를 반환합니다.

구조체 시퀀스 객체

구조체 시퀀스(struct sequence) 객체는 namedtuple() 객체의 C 등가물입니다, 즉 어트리뷰트를 통해 항목에 액세스할 수 있는 시퀀스입니다. 구조체 시퀀스를 만들려면, 먼저 특정 구조체 시퀀스 형을 만들어야 합니다.

PyTypeObject* PyStructSequence_NewType(PyStructSequence_Desc *desc)

Return value: New reference.

아래에 설명된 desc의 데이터로 새로운 구조체 시퀀스 형을 만듭니다. 결과 형의 인스턴스는 PyStructSequence_New()로 만들 수 있습니다.

void PyStructSequence_InitType(PyTypeObject *type, PyStructSequence_Desc *desc)

desc로 구조체 시퀀스 형 type을 재자리에서 초기화합니다.

int PyStructSequence_InitType2(PyTypeObject *type, PyStructSequence_Desc *desc)

PyStructSequence_InitType와 같지만, 성공하면 0을, 실패하면 -1을 반환합니다.

버전 3.4에 추가.

PyStructSequence_Desc

만들 구조체 시퀀스 형의 메타 정보를 포함합니다.

필드

C 형

의미

name

const char *

구조체 시퀀스 형의 이름

doc

const char *

pointer to docstring for the type or NULL to omit

fields

PyStructSequence_Field *

pointer to NULL-terminated array with field names of the new type

n_in_sequence

int

파이썬 측에서 볼 수 있는 필드 수 (튜플로 사용된 경우)

PyStructSequence_Field

구조체 시퀀스의 필드를 기술합니다. 구조체 시퀀스는 튜플로 모형화되므로, 모든 필드는 PyObject* 형을 취합니다. PyStructSequence_Desc의 fields 배열의 인덱스는 구조체 시퀀스의 어떤 필드가 기술되는지를 결정합니다.

필드

C 형

의미

name

const char *

name for the field or NULL to end the list of named fields, set to PyStructSequence_UnnamedField to leave unnamed

doc

const char *

field docstring or NULL to omit

char* PyStructSequence_UnnamedField

이름 없는 상태로 남겨두기 위한 필드 이름의 특수 값.

PyObject* PyStructSequence_New(PyTypeObject *type)

Return value: New reference.

PyStructSequence_NewType()으로 만든 type의 인스턴스를 만듭니다.

PyObject* PyStructSequence_GetItem(PyObject *p, Py_ssize_t pos)

Return value: Borrowed reference.

p가 가리키는 구조체 시퀀스의 위치 pos에 있는 객체를 돌려줍니다. 범위 검사가 수행되지 않습니다.

PyObject* PyStructSequence_GET_ITEM(PyObject *p, Py_ssize_t pos)

Return value: Borrowed reference.

PyStructSequence_GetItem()과 동등한 매크로.

void PyStructSequence_SetItem(PyObject *p, Py_ssize_t pos, PyObject *o)

구조체 시퀀스 p의 인덱스 pos에 있는 필드를 값 o로 설정합니다. PyTuple_SET_ITEM()과 마찬가지로, 이것은 새로운 인스턴스를 채울 때만 사용해야 합니다.

참고

이 함수는 o에 대한 참조를 “훔칩니다”.

void PyStructSequence_SET_ITEM(PyObject *p, Py_ssize_t *pos, PyObject *o)

PyStructSequence_SetItem()과 동등한 매크로.

참고

이 함수는 o에 대한 참조를 “훔칩니다”.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

구상 객체 계층 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

구상 객체 계층 »

|

리스트 객체

PyListObject

이 PyObject의 서브 형은 파이썬 리스트 객체를 나타냅니다.

PyTypeObject PyList_Type

이 PyTypeObject 인스턴스는 파이썬 리스트 형을 나타냅니다. 이것은 파이썬 계층의 list와 같은 객체입니다.

int PyList_Check(PyObject *p)

p가 리스트 객체나 리스트 형의 서브 형 인스턴스면 참을 반환합니다.

int PyList_CheckExact(PyObject *p)

p가 리스트 객체이지만 리스트 형의 서브 형의 인스턴스가 아니면 참을 반환합니다.

PyObject* PyList_New(Py_ssize_t len)

Return value: New reference.

Return a new list of length len on success, or NULL on failure.

참고

len이 0보다 크면, 반환된 리스트 객체의 항목은 NULL로 설정됩니다. 따라서 모든 항목을 PyList_SetItem()로 실제 객체로 설정하기 전에 PySequence_SetItem()와 같은 추상 API 함수를 사용하거나 파이썬 코드에 객체를 노출할 수 없습니다.

Py_ssize_t PyList_Size(PyObject *list)

list에서 리스트 객체의 길이를 반환합니다; 이는 리스트 객체에 대한 len(list)와 동등합니다.

Py_ssize_t PyList_GET_SIZE(PyObject *list)

에러 검사 없는 PyList_Size()의 매크로 형식.

PyObject* PyList_GetItem(PyObject *list, Py_ssize_t index)

Return value: Borrowed reference.

Return the object at position index in the list pointed to by list. The position must be non-negative; indexing from the end of the list is not supported. If index is out of bounds (<0 or >=len(list)), return NULL and set an IndexError exception.

PyObject* PyList_GET_ITEM(PyObject *list, Py_ssize_t i)

Return value: Borrowed reference.

에러 검사 없는 PyList_GetItem()의 매크로 형식.

int PyList_SetItem(PyObject *list, Py_ssize_t index, PyObject *item)

Set the item at index index in list to item. Return 0 on success. If index is out of bounds, return -1 and set an IndexError exception.

참고

이 함수는 item에 대한 참조를 “훔치고” 영향을 받는 위치의 리스트에 이미 있는 항목에 대한 참조를 버립니다.

void PyList_SET_ITEM(PyObject *list, Py_ssize_t i, PyObject *o)

에러 검사 없는 PyList_SetItem()의 매크로 형식. 일반적으로 이전 내용이 없는 새 리스트를 채우는 데 사용됩니다.

참고

이 매크로는 item에 대한 참조를 “훔치고”, PyList_SetItem()과는 달리 대체되는 항목에 대한 참조를 버리지 않습니다; list 의 i 위치에 있는 참조는 누수를 일으킵니다.

int PyList_Insert(PyObject *list, Py_ssize_t index, PyObject *item)

항목 item을 리스트 list의 인덱스 index 앞에 삽입합니다. 성공하면 0을 반환합니다; 실패하면 -1을 반환하고 예외를 설정합니다. list.insert(index, item)에 해당합니다.

int PyList_Append(PyObject *list, PyObject *item)

리스트 list의 끝에 객체 item을 추가합니다. 성공하면 0을 반환합니다; 실패하면 -1을 반환하고 예외를 설정합니다. list.append(item)에 해당합니다.

PyObject* PyList_GetSlice(PyObject *list, Py_ssize_t low, Py_ssize_t high)

Return value: New reference.

Return a list of the objects in list containing the objects between low and high. Return NULL and set an exception if unsuccessful. Analogous to list[low:high]. Indexing from the end of the list is not supported.

int PyList_SetSlice(PyObject *list, Py_ssize_t low, Py_ssize_t high, PyObject *itemlist)

Set the slice of list between low and high to the contents of itemlist. Analogous to list[low:high] = itemlist. The itemlist may be NULL, indicating the assignment of an empty list (slice deletion). Return 0 on success, -1 on failure. Indexing from the end of the list is not supported.

int PyList_Sort(PyObject *list)

list 항목을 제자리에서 정렬합니다. 성공하면 0을, 실패하면 -1을 반환합니다. 이것은 list.sort()와 동등합니다.

int PyList_Reverse(PyObject *list)

list의 항목을 제자리에서 뒤집습니다. 성공하면 0을, 실패하면 -1을 반환합니다. 이것은 list.reverse()와 동등합니다.

PyObject* PyList_AsTuple(PyObject *list)

Return value: New reference.

list의 내용을 포함하는 새 튜플 객체를 반환합니다; tuple(list)와 동등합니다.

int PyList_ClearFreeList()

자유 목록(free list)을 비웁니다. 해제된 항목의 총수를 반환합니다.

버전 3.3에 추가.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

구상 객체 계층 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

구상 객체 계층 »

|

딕셔너리 객체

PyDictObject

이 PyObject의 서브 형은 파이썬 딕셔너리 객체를 나타냅니다.

PyTypeObject PyDict_Type

이 PyTypeObject 인스턴스는 파이썬 딕셔너리 형을 나타냅니다. 이것은 파이썬 계층의 dict와 같은 객체입니다.

int PyDict_Check(PyObject *p)

p가 dict 객체이거나 dict 형의 서브 형의 인스턴스면 참을 반환합니다.

int PyDict_CheckExact(PyObject *p)

p가 dict 객체이지만, dict 형의 서브 형의 인스턴스는 아니면 참을 반환합니다.

PyObject* PyDict_New()

Return value: New reference.

Return a new empty dictionary, or NULL on failure.

PyObject* PyDictProxy_New(PyObject *mapping)

Return value: New reference.

읽기 전용 동작을 강제하는 매핑을 위한 types.MappingProxyType 객체를 반환합니다. 이것은 일반적으로 비 동적 클래스 형을 위한 딕셔너리의 수정을 방지하기 위해 뷰를 만드는 데 사용됩니다.

void PyDict_Clear(PyObject *p)

기존 딕셔너리의 모든 키-값 쌍을 비웁니다.

int PyDict_Contains(PyObject *p, PyObject *key)

딕셔너리 p에 key가 포함되어 있는지 확인합니다. p의 항목이 key와 일치하면 1을 반환하고, 그렇지 않으면 0을 반환합니다. 에러면 -1을 반환합니다. 이는 파이썬 표현식 key in p와 동등합니다.

PyObject* PyDict_Copy(PyObject *p)

Return value: New reference.

p와 같은 키-값 쌍을 포함하는 새 딕셔너리를 반환합니다.

int PyDict_SetItem(PyObject *p, PyObject *key, PyObject *val)

딕셔너리 p에 value를 key 키로 삽입합니다. key는 해시 가능해야 합니다. 그렇지 않으면 TypeError가 발생합니다. 성공하면 0을, 실패하면 -1을 반환합니다.

int PyDict_SetItemString(PyObject *p, const char *key, PyObject *val)

key를 키로 사용하여 딕셔너리 p에 value를 삽입합니다. key는 const char*여야 합니다. 키 객체는 PyUnicode_FromString(key)를 사용하여 만듭니다. 성공하면 0을, 실패하면 -1을 반환합니다.

int PyDict_DelItem(PyObject *p, PyObject *key)

딕셔너리 p에서 키가 key인 항목을 제거합니다. key는 해시 가능해야 합니다. 그렇지 않으면 TypeError가 발생합니다. 성공하면 0을, 실패하면 -1을 반환합니다.

int PyDict_DelItemString(PyObject *p, const char *key)

딕셔너리 p에서 문자열 key로 지정된 키의 항목을 제거합니다. 성공하면 0을, 실패하면 -1을 반환합니다.

PyObject* PyDict_GetItem(PyObject *p, PyObject *key)

Return value: Borrowed reference.

Return the object from dictionary p which has a key key. Return NULL if the key key is not present, but without setting an exception.

__hash__()와 __eq__() 메서드를 호출하는 동안 발생하는 예외는 억제됩니다. 에러 보고를 얻으려면 대신 PyDict_GetItemWithError()를 사용하십시오.

PyObject* PyDict_GetItemWithError(PyObject *p, PyObject *key)

Return value: Borrowed reference.

Variant of PyDict_GetItem() that does not suppress exceptions. Return NULL with an exception set if an exception occurred. Return NULL without an exception set if the key wasn’t present.

PyObject* PyDict_GetItemString(PyObject *p, const char *key)

Return value: Borrowed reference.

이것은 PyDict_GetItem()와 같지만, key가 PyObject*가 아닌 const char*로 지정됩니다.

__hash__()와 __eq__() 메서드를 호출하고 임시 문자열 객체를 만드는 동안 발생하는 예외는 억제됩니다. 에러 보고를 얻으려면 대신 PyDict_GetItemWithError()를 사용하십시오.

PyObject* PyDict_SetDefault(PyObject *p, PyObject *key, PyObject *defaultobj)

Return value: Borrowed reference.

이것은 파이썬 수준의 dict.setdefault()와 같습니다. 존재하면, 딕셔너리 p에서 key에 해당하는 값을 반환합니다. 키가 dict에 없으면, 값 defaultobj로 삽입되고, defaultobj가 반환됩니다. 이 함수는 key의 해시 함수를 조회 및 삽입을 위해 독립적으로 평가하는 대신 한 번만 평가합니다.

버전 3.4에 추가.

PyObject* PyDict_Items(PyObject *p)

Return value: New reference.

딕셔너리의 모든 항목을 포함하는 PyListObject를 반환합니다.

PyObject* PyDict_Keys(PyObject *p)

Return value: New reference.

딕셔너리의 모든 키를 포함하는 PyListObject를 반환합니다.

PyObject* PyDict_Values(PyObject *p)

Return value: New reference.

딕셔너리 p의 모든 값을 포함하는 PyListObject를 반환합니다.

Py_ssize_t PyDict_Size(PyObject *p)

딕셔너리에 있는 항목의 수를 반환합니다. 이는 딕셔너리에 대한 len(p)와 동등합니다.

int PyDict_Next(PyObject *p, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue)

Iterate over all key-value pairs in the dictionary p. The Py_ssize_t referred to by ppos must be initialized to 0 prior to the first call to this function to start the iteration; the function returns true for each pair in the dictionary, and false once all pairs have been reported. The parameters pkey and pvalue should either point to PyObject* variables that will be filled in with each key and value, respectively, or may be NULL. Any references returned through them are borrowed. ppos should not be altered during iteration. Its value represents offsets within the internal dictionary structure, and since the structure is sparse, the offsets are not consecutive.

예를 들면:

PyObject *key, *value;
Py_ssize_t pos = 0;

while (PyDict_Next(self->dict, &pos, &key, &value)) {
    /* do something interesting with the values... */
    ...
}

딕셔너리 p는 이터레이션 중에 변경해서는 안 됩니다. 딕셔너리를 이터레이트 할 때 값을 변경하는 것은 안전하지만, 키 집합이 변경되지 않는 한만 그렇습니다. 예를 들면:

PyObject *key, *value;
Py_ssize_t pos = 0;

while (PyDict_Next(self->dict, &pos, &key, &value)) {
    long i = PyLong_AsLong(value);
    if (i == -1 && PyErr_Occurred()) {
        return -1;
    }
    PyObject *o = PyLong_FromLong(i + 1);
    if (o == NULL)
        return -1;
    if (PyDict_SetItem(self->dict, key, o) < 0) {
        Py_DECREF(o);
        return -1;
    }
    Py_DECREF(o);
}

int PyDict_Merge(PyObject *a, PyObject *b, int override)

매핑 객체 b를 이터레이트 하면서, 키-값 쌍을 딕셔너리 a에 추가합니다. b는 딕셔너리거나 PyMapping_Keys()와 PyObject_GetItem()를 지원하는 모든 객체일 수 있습니다. override가 참이면, a에 있는 기존 쌍이 b에서 일치하는 키가 있으면 교체되고, 그렇지 않으면 a와 일치하는 키가 없을 때만 쌍이 추가됩니다. 성공하면 0을 반환하고, 예외가 발생하면 -1을 반환합니다.

int PyDict_Update(PyObject *a, PyObject *b)

이는 C에서 PyDict_Merge(a, b, 1)와 같고, 두 번째 인자에 “keys” 어트리뷰트가 없을 때 PyDict_Update()가 키-값 쌍의 시퀀스에 대해 이터레이트 하지 않는다는 점만 제외하면, 파이썬에서 a.update(b)와 유사합니다. 성공하면 0을 반환하고, 예외가 발생하면 -1을 반환합니다.

int PyDict_MergeFromSeq2(PyObject *a, PyObject *seq2, int override)

seq2의 키-값 쌍으로 딕셔너리 a를 갱신하거나 병합합니다. seq2는 키-값 쌍으로 간주하는 길이 2의 이터러블 객체를 생성하는 이터러블 객체여야 합니다. 중복 키가 있으면, override가 참이면 마지막이 승리하고, 그렇지 않으면 첫 번째가 승리합니다. 성공 시 0을 반환하고, 예외가 발생하면 -1을 반환합니다. 동등한 파이썬은 이렇습니다(반환 값 제외)

def PyDict_MergeFromSeq2(a, seq2, override):
    for key, value in seq2:
        if override or key not in a:
            a[key] = value

int PyDict_ClearFreeList()

자유 목록(free list)을 비웁니다. 해제된 항목의 총수를 반환합니다.

버전 3.3에 추가.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

구상 객체 계층 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

구상 객체 계층 »

|

집합 객체

이 절에서는 set과 frozenset 객체에 대한 공용 API에 대해 자세히 설명합니다. 아래 나열되지 않은 기능은 추상 객체 프로토콜 (PyObject_CallMethod(), PyObject_RichCompareBool(), PyObject_Hash(), PyObject_Repr(), PyObject_IsTrue(), PyObject_Print() 및 PyObject_GetIter()를 포함합니다)이나 추상 숫자 프로토콜 (PyNumber_And(), PyNumber_Subtract(), PyNumber_Or(), PyNumber_Xor(), PyNumber_InPlaceAnd(), PyNumber_InPlaceSubtract(), PyNumber_InPlaceOr() 및 PyNumber_InPlaceXor()을 포함합니다).

PySetObject

이 PyObject의 서브 형은 set과 frozenset 객체 모두의 내부 데이터를 담는 데 사용됩니다. 이것은 작은 집합은 고정 크기(튜플 저장과 매우 흡사함)이고, 중형과 대형 집합은 별도의 가변 크기 메모리 블록(리스트 저장소처럼)을 가리킨다는 점에서 PyDictObject와 비슷합니다. 이 구조체의 필드는 아무것도 공개되지 않은 것으로 취급되어야 하며, 변경될 수 있습니다. 모든 액세스는 구조체의 값을 조작하기보다는 설명된 API를 통해 수행해야 합니다.

PyTypeObject PySet_Type

이것은 파이썬 set 형을 나타내는 PyTypeObject의 인스턴스입니다.

PyTypeObject PyFrozenSet_Type

이것은 파이썬 frozenset 형을 나타내는 PyTypeObject의 인스턴스입니다.

다음 형 검사 매크로는 모든 파이썬 객체에 대한 포인터에서 작동합니다. 마찬가지로, 생성자 함수는 모든 이터러블 파이썬 객체에서 작동합니다.

int PySet_Check(PyObject *p)

p가 set 객체나 서브 형의 인스턴스면 참을 반환합니다.

int PyFrozenSet_Check(PyObject *p)

p가 frozenset 객체나 서브 형의 인스턴스면 참을 반환합니다.

int PyAnySet_Check(PyObject *p)

p가 set 객체, frozenset 객체 또는 서브 형의 인스턴스면 참을 반환합니다.

int PyAnySet_CheckExact(PyObject *p)

p가 set 객체나 frozenset 객체이지만, 서브 형의 인스턴스는 아니면 참을 반환합니다.

int PyFrozenSet_CheckExact(PyObject *p)

p가 frozenset 객체이지만, 서브 형의 인스턴스는 아니면 참을 반환합니다.

PyObject* PySet_New(PyObject *iterable)

Return value: New reference.

Return a new set containing objects returned by the iterable. The iterable may be NULL to create a new empty set. Return the new set on success or NULL on failure. Raise TypeError if iterable is not actually iterable. The constructor is also useful for copying a set (c=set(s)).

PyObject* PyFrozenSet_New(PyObject *iterable)

Return value: New reference.

Return a new frozenset containing objects returned by the iterable. The iterable may be NULL to create a new empty frozenset. Return the new set on success or NULL on failure. Raise TypeError if iterable is not actually iterable.

set 이나 frozenset의 인스턴스 또는 그들의 서브 형의 인스턴스에 대해 다음 함수와 매크로를 사용할 수 있습니다.

Py_ssize_t PySet_Size(PyObject *anyset)

set 이나 frozenset 객체의 길이를 반환합니다. len(anyset)와 동등합니다. anyset이 set, frozenset 또는 서브 형의 인스턴스가 아니면 PyExc_SystemError를 발생시킵니다.

Py_ssize_t PySet_GET_SIZE(PyObject *anyset)

에러 검사 없는 PySet_Size()의 매크로 형식.

int PySet_Contains(PyObject *anyset, PyObject *key)

발견되면 1을, 발견되지 않으면 0을, 에러가 발생하면 -1을 반환합니다. 파이썬 __contains__() 메서드와는 달리, 이 함수는 해시 불가능한 집합을 임시 frozenset으로 자동 변환하지 않습니다. key가 해시 불가능하면, TypeError를 발생시킵니다. anyset이 set, frozenset 또는 서브 형의 인스턴스가 아니면 PyExc_SystemError를 발생시킵니다.

int PySet_Add(PyObject *set, PyObject *key)

key를 set 인스턴스에 추가합니다. 또한 frozenset 인스턴스에도 작동합니다 (PyTuple_SetItem()처럼 다른 코드에 노출되기 전에 새로운 frozenset의 값을 채우는 데 사용할 수 있습니다). 성공하면 0을, 실패하면 -1을 반환합니다. key가 해시 불가능하면, TypeError를 발생시킵니다. 성장할 공간이 없다면 MemoryError를 발생시킵니다. set이 set 이나 그 서브 형의 인스턴스가 아니면 SystemError를 발생시킵니다.

다음 함수는 set 이나 그것의 서브 형의 인스턴스에는 사용할 수 있지만, frozenset 이나 그 서브 형의 인스턴스에는 사용할 수 없습니다.

int PySet_Discard(PyObject *set, PyObject *key)

발견되고 제거되면 1을 반환하고, 발견되지 않으면(아무런 일도 하지 않습니다) 0을 반환하고, 에러가 발생하면 -1을 반환합니다. 발견할 수 없는 키에 대해 KeyError를 발생시키지 않습니다. key가 해시 불가능하면 TypeError를 발생시킵니다. 파이썬 discard() 메서드와는 달리, 이 함수는 해시 불가능한 집합을 임시 frozenset으로 자동 변환하지 않습니다. set이 set 이나 그 서브 형의 인스턴스가 아니면 PyExc_SystemError를 발생시킵니다.

PyObject* PySet_Pop(PyObject *set)

Return value: New reference.

Return a new reference to an arbitrary object in the set, and removes the object from the set. Return NULL on failure. Raise KeyError if the set is empty. Raise a SystemError if set is not an instance of set or its subtype.

int PySet_Clear(PyObject *set)

기존의 모든 요소 집합을 비웁니다.

int PySet_ClearFreeList()

자유 목록(free list)을 비웁니다. 해제된 항목의 총수를 반환합니다.

버전 3.3에 추가.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

구상 객체 계층 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

구상 객체 계층 »

|

함수 객체

파이썬 함수와 관련된 몇 가지 함수가 있습니다.

PyFunctionObject

함수에 사용되는 C 구조체.

PyTypeObject PyFunction_Type

이것은 PyTypeObject의 인스턴스이며 파이썬 함수 형을 나타냅니다. 파이썬 프로그래머에게 types.FunctionType으로 노출됩니다.

int PyFunction_Check(PyObject *o)

Return true if o is a function object (has type PyFunction_Type). The parameter must not be NULL.

PyObject* PyFunction_New(PyObject *code, PyObject *globals)

Return value: New reference.

코드 객체 code와 연관된 새 함수 객체를 반환합니다. globals는 함수에서 액세스할 수 있는 전역 변수가 있는 딕셔너리이어야 합니다.

The function’s docstring and name are retrieved from the code object. __module__ is retrieved from globals. The argument defaults, annotations and closure are set to NULL. __qualname__ is set to the same value as the function’s name.

PyObject* PyFunction_NewWithQualName(PyObject *code, PyObject *globals, PyObject *qualname)

Return value: New reference.

As PyFunction_New(), but also allows setting the function object’s __qualname__ attribute. qualname should be a unicode object or NULL; if NULL, the __qualname__ attribute is set to the same value as its __name__ attribute.

버전 3.3에 추가.

PyObject* PyFunction_GetCode(PyObject *op)

Return value: Borrowed reference.

함수 객체 op와 연관된 코드 객체를 반환합니다.

PyObject* PyFunction_GetGlobals(PyObject *op)

Return value: Borrowed reference.

함수 객체 op와 연관된 전역 딕셔너리를 반환합니다.

PyObject* PyFunction_GetModule(PyObject *op)

Return value: Borrowed reference.

함수 객체 op의 __module__ 어트리뷰트를 반환합니다. 이것은 일반적으로 모듈 이름을 포함하는 문자열이지만, 파이썬 코드로 다른 객체로 설정할 수 있습니다.

PyObject* PyFunction_GetDefaults(PyObject *op)

Return value: Borrowed reference.

Return the argument default values of the function object op. This can be a tuple of arguments or NULL.

int PyFunction_SetDefaults(PyObject *op, PyObject *defaults)

Set the argument default values for the function object op. defaults must be Py_None or a tuple.

실패하면 SystemError를 발생시키고 -1을 반환합니다.

PyObject* PyFunction_GetClosure(PyObject *op)

Return value: Borrowed reference.

Return the closure associated with the function object op. This can be NULL or a tuple of cell objects.

int PyFunction_SetClosure(PyObject *op, PyObject *closure)

Set the closure associated with the function object op. closure must be Py_None or a tuple of cell objects.

실패하면 SystemError를 발생시키고 -1을 반환합니다.

PyObject *PyFunction_GetAnnotations(PyObject *op)

Return value: Borrowed reference.

Return the annotations of the function object op. This can be a mutable dictionary or NULL.

int PyFunction_SetAnnotations(PyObject *op, PyObject *annotations)

Set the annotations for the function object op. annotations must be a dictionary or Py_None.

실패하면 SystemError를 발생시키고 -1을 반환합니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

구상 객체 계층 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

구상 객체 계층 »

|

인스턴스 메서드 객체

인스턴스 메서드는 PyCFunction에 대한 래퍼이며 PyCFunction를 클래스 객체에 연결하는 새로운 방법입니다. 이전의 PyMethod_New(func, NULL, class) 호출을 대체합니다.

PyTypeObject PyInstanceMethod_Type

이 PyTypeObject 인스턴스는 파이썬 인스턴스 메서드 형을 나타냅니다. 파이썬 프로그램에는 노출되지 않습니다.

int PyInstanceMethod_Check(PyObject *o)

Return true if o is an instance method object (has type PyInstanceMethod_Type). The parameter must not be NULL.

PyObject* PyInstanceMethod_New(PyObject *func)

Return value: New reference.

새 인스턴스 메서드 객체를 반환합니다. func는 임의의 콜러블 객체인데, func는 인스턴스 메서드가 호출될 때 호출될 함수입니다.

PyObject* PyInstanceMethod_Function(PyObject *im)

Return value: Borrowed reference.

인스턴스 메서드 im과 연관된 함수 객체를 반환합니다.

PyObject* PyInstanceMethod_GET_FUNCTION(PyObject *im)

Return value: Borrowed reference.

오류 검사를 피하는 PyInstanceMethod_Function()의 매크로 버전.

메서드 객체

메서드는 연결된(bound) 함수 객체입니다. 메서드는 항상 사용자 정의 클래스의 인스턴스에 연결됩니다. 연결되지 않은(unbound) 메서드(클래스 객체에 연결된 메서드)는 더는 사용할 수 없습니다.

PyTypeObject PyMethod_Type

이 PyTypeObject 인스턴스는 파이썬 메서드 형을 나타냅니다. 이것은 파이썬 프로그램에 types.MethodType로 노출됩니다.

int PyMethod_Check(PyObject *o)

Return true if o is a method object (has type PyMethod_Type). The parameter must not be NULL.

PyObject* PyMethod_New(PyObject *func, PyObject *self)

Return value: New reference.

Return a new method object, with func being any callable object and self the instance the method should be bound. func is the function that will be called when the method is called. self must not be NULL.

PyObject* PyMethod_Function(PyObject *meth)

Return value: Borrowed reference.

meth 메서드와 연관된 함수 객체를 반환합니다.

PyObject* PyMethod_GET_FUNCTION(PyObject *meth)

Return value: Borrowed reference.

오류 검사를 피하는 PyMethod_Function()의 매크로 버전.

PyObject* PyMethod_Self(PyObject *meth)

Return value: Borrowed reference.

meth 메서드와 연관된 인스턴스를 반환합니다.

PyObject* PyMethod_GET_SELF(PyObject *meth)

Return value: Borrowed reference.

오류 검사를 피하는 PyMethod_Self()의 매크로 버전.

int PyMethod_ClearFreeList()

자유 목록을 지웁니다. 해제된 총 항목 수를 반환합니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

구상 객체 계층 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

구상 객체 계층 »

|

셀 객체

“셀” 객체는 여러 스코프에서 참조하는 변수를 구현하는 데 사용됩니다. 이러한 변수마다, 값을 저장하기 위해 셀 객체가 만들어집니다; 값을 참조하는 각 스택 프레임의 지역 변수에는 해당 변수를 사용하는 외부 스코프의 셀에 대한 참조가 포함됩니다. 값에 액세스하면, 셀 객체 자체 대신 셀에 포함된 값이 사용됩니다. 이러한 셀 객체의 역참조(de-referencing)는 생성된 바이트 코드로부터의 지원이 필요합니다; 액세스 시 자동으로 역참조되지 않습니다. 셀 객체는 다른 곳에 유용하지는 않습니다.

PyCellObject

셀 객체에 사용되는 C 구조체.

PyTypeObject PyCell_Type

셀 객체에 해당하는 형 객체.

int PyCell_Check(ob)

Return true if ob is a cell object; ob must not be NULL.

PyObject* PyCell_New(PyObject *ob)

Return value: New reference.

Create and return a new cell object containing the value ob. The parameter may be NULL.

PyObject* PyCell_Get(PyObject *cell)

Return value: New reference.

셀 cell의 내용을 반환합니다.

PyObject* PyCell_GET(PyObject *cell)

Return value: Borrowed reference.

Return the contents of the cell cell, but without checking that cell is non-NULL and a cell object.

int PyCell_Set(PyObject *cell, PyObject *value)

Set the contents of the cell object cell to value. This releases the reference to any current content of the cell. value may be NULL. cell must be non-NULL; if it is not a cell object, -1 will be returned. On success, 0 will be returned.

void PyCell_SET(PyObject *cell, PyObject *value)

Sets the value of the cell object cell to value. No reference counts are adjusted, and no checks are made for safety; cell must be non-NULL and must be a cell object.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

구상 객체 계층 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

구상 객체 계층 »

|

코드 객체

코드 객체는 CPython 구현의 저수준 세부 사항입니다. 각 객체는 아직 함수에 묶여 있지 않은 실행 가능한 코드 덩어리를 나타냅니다.

PyCodeObject

코드 객체를 설명하는 데 사용되는 객체의 C 구조체. 이 형의 필드는 언제든지 변경될 수 있습니다.

PyTypeObject PyCode_Type

이것은 Python code 형을 나타내는 PyTypeObject의 인스턴스입니다.

int PyCode_Check(PyObject *co)

co가 code 객체면 참을 반환합니다.

int PyCode_GetNumFree(PyCodeObject *co)

co에 있는 자유 변수의 개수를 반환합니다.

PyCodeObject* PyCode_New(int argcount, int kwonlyargcount, int nlocals, int stacksize, int flags, PyObject *code, PyObject *consts, PyObject *names, PyObject *varnames, PyObject *freevars, PyObject *cellvars, PyObject *filename, PyObject *name, int firstlineno, PyObject *lnotab)

Return value: New reference.

새 코드 객체를 반환합니다. 프레임을 만들기 위해 더미 코드 객체가 필요하면, 대신 PyCode_NewEmpty()를 사용하십시오. 바이트 코드의 정의가 자주 변경되기 때문에, PyCode_New()를 직접 호출하면 정확한 파이썬 버전에 구속될 수 있습니다.

PyCodeObject* PyCode_NewEmpty(const char *filename, const char *funcname, int firstlineno)

Return value: New reference.

지정된 파일명, 함수명 및 첫 번째 줄 번호를 갖는 새 빈 코드 객체를 반환합니다. 결과 코드 객체를 exec() 또는 eval()하는 것은 불법입니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

구상 객체 계층 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

구상 객체 계층 »

|

파일 객체

이 API는 C 표준 라이브러리의 버퍼링 된 I/O (FILE*) 지원에 의존하는 내장 파일 객체에 대한 파이썬 2 C API의 최소 에뮬레이션입니다. 파이썬 3에서, 파일과 스트림은 새로운 io 모듈을 사용합니다. 이 모듈은 운영 체제의 저수준 버퍼링 되지 않은 I/O 위에 여러 계층을 정의합니다. 아래에서 설명하는 함수는 이러한 새로운 API에 대한 편리한 C 래퍼이며, 주로 인터프리터의 내부 오류 보고를 위한 것입니다; 제삼자 코드는 대신 io API에 액세스하는 것이 좋습니다.

PyFile_FromFd(int fd, const char *name, const char *mode, int buffering, const char *encoding, const char *errors, const char *newline, int closefd)

Return value: New reference.

Create a Python file object from the file descriptor of an already opened file fd. The arguments name, encoding, errors and newline can be NULL to use the defaults; buffering can be -1 to use the default. name is ignored and kept for backward compatibility. Return NULL on failure. For a more comprehensive description of the arguments, please refer to the io.open() function documentation.

경고

파이썬 스트림이 자체적인 버퍼링 계층을 가지고 있으므로, OS 수준의 파일 기술자와 혼합하면 여러 예기치 못한 문제가 발생할 수 있습니다 (가령 데이터의 예상치 못한 순서).

버전 3.2에서 변경: name 어트리뷰트를 무시합니다.

int PyObject_AsFileDescriptor(PyObject *p)

p와 관련된 파일 기술자를 int로 반환합니다. 객체가 정수면, 값이 반환됩니다. 그렇지 않으면 객체의 fileno() 메서드가 있으면 호출됩니다; 메서드는 반드시 정수를 반환해야 하고, 그 값이 파일 기술자 값으로 반환됩니다. 실패하면 예외를 설정하고 -1을 반환합니다.

PyObject* PyFile_GetLine(PyObject *p, int n)

Return value: New reference.

p.readline([n])과 동등합니다. 이 함수는 객체 p에서 한 줄을 읽습니다. p는 파일 객체나 readline() 메서드가 있는 임의의 객체일 수 있습니다. n이 0이면, 줄의 길이와 관계없이 정확히 한 줄을 읽습니다. n이 0보다 크면, n 바이트 이상을 파일에서 읽지 않습니다; 불완전한 줄이 반환될 수 있습니다. 두 경우 모두, 파일 끝에 즉시 도달하면 빈 문자열이 반환됩니다. 그러나 n이 0보다 작으면, 길이와 관계없이 한 줄을 읽지만, 파일 끝에 즉시 도달하면 EOFError가 발생합니다.

int PyFile_WriteObject(PyObject *obj, PyObject *p, int flags)

객체 obj를 파일 객체 p에 씁니다. flags에서 지원되는 유일한 플래그는 Py_PRINT_RAW입니다; 주어지면, repr() 대신 객체의 str()이 기록됩니다. 성공하면 0을, 실패하면 -1을 반환합니다; 적절한 예외가 설정됩니다.

int PyFile_WriteString(const char *s, PyObject *p)

문자열 s를 파일 객체 p에 씁니다. 성공하면 0을 반환하고, 실패하면 -1을 반환합니다; 적절한 예외가 설정됩니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

구상 객체 계층 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

구상 객체 계층 »

|

Module Objects

PyTypeObject PyModule_Type

This instance of PyTypeObject represents the Python module type. This is exposed to Python programs as types.ModuleType.

int PyModule_Check(PyObject *p)

Return true if p is a module object, or a subtype of a module object.

int PyModule_CheckExact(PyObject *p)

Return true if p is a module object, but not a subtype of PyModule_Type.

PyObject* PyModule_NewObject(PyObject *name)

Return value: New reference.

Return a new module object with the __name__ attribute set to name. The module’s __name__, __doc__, __package__, and __loader__ attributes are filled in (all but __name__ are set to None); the caller is responsible for providing a __file__ attribute.

버전 3.3에 추가.

버전 3.4에서 변경: __package__ and __loader__ are set to None.

PyObject* PyModule_New(const char *name)

Return value: New reference.

Similar to PyModule_NewObject(), but the name is a UTF-8 encoded string instead of a Unicode object.

PyObject* PyModule_GetDict(PyObject *module)

Return value: Borrowed reference.

Return the dictionary object that implements module’s namespace; this object is the same as the __dict__ attribute of the module object. If module is not a module object (or a subtype of a module object), SystemError is raised and NULL is returned.

It is recommended extensions use other PyModule_*() and PyObject_*() functions rather than directly manipulate a module’s __dict__.

PyObject* PyModule_GetNameObject(PyObject *module)

Return value: New reference.

Return module’s __name__ value. If the module does not provide one, or if it is not a string, SystemError is raised and NULL is returned.

버전 3.3에 추가.

const char* PyModule_GetName(PyObject *module)

Similar to PyModule_GetNameObject() but return the name encoded to 'utf-8'.

void* PyModule_GetState(PyObject *module)

Return the “state” of the module, that is, a pointer to the block of memory allocated at module creation time, or NULL. See PyModuleDef.m_size.

PyModuleDef* PyModule_GetDef(PyObject *module)

Return a pointer to the PyModuleDef struct from which the module was created, or NULL if the module wasn’t created from a definition.

PyObject* PyModule_GetFilenameObject(PyObject *module)

Return value: New reference.

Return the name of the file from which module was loaded using module’s __file__ attribute. If this is not defined, or if it is not a unicode string, raise SystemError and return NULL; otherwise return a reference to a Unicode object.

버전 3.2에 추가.

const char* PyModule_GetFilename(PyObject *module)

Similar to PyModule_GetFilenameObject() but return the filename encoded to ‘utf-8’.

버전 3.2부터 폐지: PyModule_GetFilename() raises UnicodeEncodeError on unencodable filenames, use PyModule_GetFilenameObject() instead.

Initializing C modules

Modules objects are usually created from extension modules (shared libraries which export an initialization function), or compiled-in modules (where the initialization function is added using PyImport_AppendInittab()). See C와 C++ 확장 빌드하기 or 내장된 파이썬을 확장하기 for details.

The initialization function can either pass a module definition instance to PyModule_Create(), and return the resulting module object, or request “multi-phase initialization” by returning the definition struct itself.

PyModuleDef

The module definition struct, which holds all information needed to create a module object. There is usually only one statically initialized variable of this type for each module.

PyModuleDef_Base m_base

Always initialize this member to PyModuleDef_HEAD_INIT.

const char *m_name

Name for the new module.

const char *m_doc

Docstring for the module; usually a docstring variable created with PyDoc_STRVAR is used.

Py_ssize_t m_size

Module state may be kept in a per-module memory area that can be retrieved with PyModule_GetState(), rather than in static globals. This makes modules safe for use in multiple sub-interpreters.

This memory area is allocated based on m_size on module creation, and freed when the module object is deallocated, after the m_free function has been called, if present.

Setting m_size to -1 means that the module does not support sub-interpreters, because it has global state.

Setting it to a non-negative value means that the module can be re-initialized and specifies the additional amount of memory it requires for its state. Non-negative m_size is required for multi-phase initialization.

See PEP 3121 [https://www.python.org/dev/peps/pep-3121] for more details.

PyMethodDef* m_methods

A pointer to a table of module-level functions, described by PyMethodDef values. Can be NULL if no functions are present.

PyModuleDef_Slot* m_slots

An array of slot definitions for multi-phase initialization, terminated by a {0, NULL} entry. When using single-phase initialization, m_slots must be NULL.

버전 3.5에서 변경: Prior to version 3.5, this member was always set to NULL, and was defined as:

inquiry m_reload

traverseproc m_traverse

A traversal function to call during GC traversal of the module object, or NULL if not needed. This function may be called before module state is allocated (PyModule_GetState() may return NULL), and before the Py_mod_exec function is executed.

inquiry m_clear

A clear function to call during GC clearing of the module object, or NULL if not needed. This function may be called before module state is allocated (PyModule_GetState() may return NULL), and before the Py_mod_exec function is executed.

freefunc m_free

A function to call during deallocation of the module object, or NULL if not needed. This function may be called before module state is allocated (PyModule_GetState() may return NULL), and before the Py_mod_exec function is executed.

Single-phase initialization

The module initialization function may create and return the module object directly. This is referred to as “single-phase initialization”, and uses one of the following two module creation functions:

PyObject* PyModule_Create(PyModuleDef *def)

Return value: New reference.

Create a new module object, given the definition in def. This behaves like PyModule_Create2() with module_api_version set to PYTHON_API_VERSION.

PyObject* PyModule_Create2(PyModuleDef *def, int module_api_version)

Return value: New reference.

Create a new module object, given the definition in def, assuming the API version module_api_version. If that version does not match the version of the running interpreter, a RuntimeWarning is emitted.

참고

Most uses of this function should be using PyModule_Create() instead; only use this if you are sure you need it.

Before it is returned from in the initialization function, the resulting module object is typically populated using functions like PyModule_AddObject().

Multi-phase initialization

An alternate way to specify extensions is to request “multi-phase initialization”. Extension modules created this way behave more like Python modules: the initialization is split between the creation phase, when the module object is created, and the execution phase, when it is populated. The distinction is similar to the __new__() and __init__() methods of classes.

Unlike modules created using single-phase initialization, these modules are not singletons: if the sys.modules entry is removed and the module is re-imported, a new module object is created, and the old module is subject to normal garbage collection – as with Python modules. By default, multiple modules created from the same definition should be independent: changes to one should not affect the others. This means that all state should be specific to the module object (using e.g. using PyModule_GetState()), or its contents (such as the module’s __dict__ or individual classes created with PyType_FromSpec()).

All modules created using multi-phase initialization are expected to support sub-interpreters. Making sure multiple modules are independent is typically enough to achieve this.

To request multi-phase initialization, the initialization function (PyInit_modulename) returns a PyModuleDef instance with non-empty m_slots. Before it is returned, the PyModuleDef instance must be initialized with the following function:

PyObject* PyModuleDef_Init(PyModuleDef *def)

Return value: Borrowed reference.

Ensures a module definition is a properly initialized Python object that correctly reports its type and reference count.

Returns def cast to PyObject*, or NULL if an error occurred.

버전 3.5에 추가.

The m_slots member of the module definition must point to an array of PyModuleDef_Slot structures:

PyModuleDef_Slot

int slot

A slot ID, chosen from the available values explained below.

void* value

Value of the slot, whose meaning depends on the slot ID.

버전 3.5에 추가.

The m_slots array must be terminated by a slot with id 0.

The available slot types are:

Py_mod_create

Specifies a function that is called to create the module object itself. The value pointer of this slot must point to a function of the signature:

PyObject* create_module(PyObject *spec, PyModuleDef *def)

The function receives a ModuleSpec instance, as defined in PEP 451 [https://www.python.org/dev/peps/pep-0451], and the module definition. It should return a new module object, or set an error and return NULL.

This function should be kept minimal. In particular, it should not call arbitrary Python code, as trying to import the same module again may result in an infinite loop.

Multiple Py_mod_create slots may not be specified in one module definition.

If Py_mod_create is not specified, the import machinery will create a normal module object using PyModule_New(). The name is taken from spec, not the definition, to allow extension modules to dynamically adjust to their place in the module hierarchy and be imported under different names through symlinks, all while sharing a single module definition.

There is no requirement for the returned object to be an instance of PyModule_Type. Any type can be used, as long as it supports setting and getting import-related attributes. However, only PyModule_Type instances may be returned if the PyModuleDef has non-NULL m_traverse, m_clear, m_free; non-zero m_size; or slots other than Py_mod_create.

Py_mod_exec

Specifies a function that is called to execute the module. This is equivalent to executing the code of a Python module: typically, this function adds classes and constants to the module. The signature of the function is:

int exec_module(PyObject* module)

If multiple Py_mod_exec slots are specified, they are processed in the order they appear in the m_slots array.

See PEP 489 [https://www.python.org/dev/peps/pep-0489] for more details on multi-phase initialization.

Low-level module creation functions

The following functions are called under the hood when using multi-phase initialization. They can be used directly, for example when creating module objects dynamically. Note that both PyModule_FromDefAndSpec and PyModule_ExecDef must be called to fully initialize a module.

PyObject * PyModule_FromDefAndSpec(PyModuleDef *def, PyObject *spec)

Return value: New reference.

Create a new module object, given the definition in module and the ModuleSpec spec. This behaves like PyModule_FromDefAndSpec2() with module_api_version set to PYTHON_API_VERSION.

버전 3.5에 추가.

PyObject * PyModule_FromDefAndSpec2(PyModuleDef *def, PyObject *spec, int module_api_version)

Return value: New reference.

Create a new module object, given the definition in module and the ModuleSpec spec, assuming the API version module_api_version. If that version does not match the version of the running interpreter, a RuntimeWarning is emitted.

참고

Most uses of this function should be using PyModule_FromDefAndSpec() instead; only use this if you are sure you need it.

버전 3.5에 추가.

int PyModule_ExecDef(PyObject *module, PyModuleDef *def)

Process any execution slots (Py_mod_exec) given in def.

버전 3.5에 추가.

int PyModule_SetDocString(PyObject *module, const char *docstring)

Set the docstring for module to docstring. This function is called automatically when creating a module from PyModuleDef, using either PyModule_Create or PyModule_FromDefAndSpec.

버전 3.5에 추가.

int PyModule_AddFunctions(PyObject *module, PyMethodDef *functions)

Add the functions from the NULL terminated functions array to module. Refer to the PyMethodDef documentation for details on individual entries (due to the lack of a shared module namespace, module level “functions” implemented in C typically receive the module as their first parameter, making them similar to instance methods on Python classes). This function is called automatically when creating a module from PyModuleDef, using either PyModule_Create or PyModule_FromDefAndSpec.

버전 3.5에 추가.

Support functions

The module initialization function (if using single phase initialization) or a function called from a module execution slot (if using multi-phase initialization), can use the following functions to help initialize the module state:

int PyModule_AddObject(PyObject *module, const char *name, PyObject *value)

Add an object to module as name. This is a convenience function which can be used from the module’s initialization function. This steals a reference to value on success. Return -1 on error, 0 on success.

참고

Unlike other functions that steal references, PyModule_AddObject() only decrements the reference count of value on success.

This means that its return value must be checked, and calling code must Py_DECREF() value manually on error. Example usage:

Py_INCREF(spam);
if (PyModule_AddObject(module, "spam", spam) < 0) {
    Py_DECREF(module);
    Py_DECREF(spam);
    return NULL;
}

int PyModule_AddIntConstant(PyObject *module, const char *name, long value)

Add an integer constant to module as name. This convenience function can be used from the module’s initialization function. Return -1 on error, 0 on success.

int PyModule_AddStringConstant(PyObject *module, const char *name, const char *value)

Add a string constant to module as name. This convenience function can be used from the module’s initialization function. The string value must be NULL-terminated. Return -1 on error, 0 on success.

int PyModule_AddIntMacro(PyObject *module, macro)

Add an int constant to module. The name and the value are taken from macro. For example PyModule_AddIntMacro(module, AF_INET) adds the int constant AF_INET with the value of AF_INET to module. Return -1 on error, 0 on success.

int PyModule_AddStringMacro(PyObject *module, macro)

Add a string constant to module.

Module lookup

Single-phase initialization creates singleton modules that can be looked up in the context of the current interpreter. This allows the module object to be retrieved later with only a reference to the module definition.

These functions will not work on modules created using multi-phase initialization, since multiple such modules can be created from a single definition.

PyObject* PyState_FindModule(PyModuleDef *def)

Return value: Borrowed reference.

Returns the module object that was created from def for the current interpreter. This method requires that the module object has been attached to the interpreter state with PyState_AddModule() beforehand. In case the corresponding module object is not found or has not been attached to the interpreter state yet, it returns NULL.

int PyState_AddModule(PyObject *module, PyModuleDef *def)

Attaches the module object passed to the function to the interpreter state. This allows the module object to be accessible via PyState_FindModule().

Only effective on modules created using single-phase initialization.

Python calls PyState_AddModule automatically after importing a module, so it is unnecessary (but harmless) to call it from module initialization code. An explicit call is needed only if the module’s own init code subsequently calls PyState_FindModule. The function is mainly intended for implementing alternative import mechanisms (either by calling it directly, or by referring to its implementation for details of the required state updates).

Return 0 on success or -1 on failure.

버전 3.3에 추가.

int PyState_RemoveModule(PyModuleDef *def)

Removes the module object created from def from the interpreter state. Return 0 on success or -1 on failure.

버전 3.3에 추가.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

구상 객체 계층 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

구상 객체 계층 »

|

이터레이터 객체

파이썬은 두 개의 범용 이터레이터 객체를 제공합니다. 첫째, 시퀀스 이터레이터는 __getitem__() 메서드를 지원하는 임의의 시퀀스와 작동합니다. 둘째는 콜러블 객체와 종료 신호(sentinel) 값을 사용하고, 시퀀스의 각 항목에 대해 콜러블을 호출하고, 종료 신호 값이 반환될 때 이터레이션을 종료합니다.

PyTypeObject PySeqIter_Type

PySeqIter_New()와 내장 시퀀스 형에 대한 iter() 내장 함수의 단일 인자 형식에 의해 반환된 이터레이터 객체에 대한 형 객체.

int PySeqIter_Check(op)

op의 형이 PySeqIter_Type이면 참을 돌려줍니다.

PyObject* PySeqIter_New(PyObject *seq)

Return value: New reference.

일반 시퀀스 객체 seq와 함께 작동하는 이터레이터를 반환합니다. 시퀀스가 서브스크립션 연산에서 IndexError를 일으키면 이터레이션이 끝납니다.

PyTypeObject PyCallIter_Type

PyCallIter_New()와 iter() 내장 함수의 두 인자 형식에 의해 반환된 이터레이터 객체에 대한 형 객체.

int PyCallIter_Check(op)

op의 형이 PyCallIter_Type이면 참을 돌려줍니다.

PyObject* PyCallIter_New(PyObject *callable, PyObject *sentinel)

Return value: New reference.

새로운 이터레이터를 돌려줍니다. 첫 번째 매개 변수 callable은 매개 변수 없이 호출할 수 있는 모든 파이썬 콜러블 객체일 수 있습니다; 각 호출은 이터레이션의 다음 항목을 반환해야 합니다. callable이 sentinel와 같은 값을 반환하면 이터레이션이 종료됩니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

구상 객체 계층 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

구상 객체 계층 »

|

디스크립터 객체

“디스크립터”는 객체의 일부 어트리뷰트를 기술하는 객체입니다. 그것들은 형 객체의 딕셔너리에 있습니다.

PyTypeObject PyProperty_Type

내장 디스크립터 형들을 위한 형 객체.

PyObject* PyDescr_NewGetSet(PyTypeObject *type, struct PyGetSetDef *getset)

Return value: New reference.

PyObject* PyDescr_NewMember(PyTypeObject *type, struct PyMemberDef *meth)

Return value: New reference.

PyObject* PyDescr_NewMethod(PyTypeObject *type, struct PyMethodDef *meth)

Return value: New reference.

PyObject* PyDescr_NewWrapper(PyTypeObject *type, struct wrapperbase *wrapper, void *wrapped)

Return value: New reference.

PyObject* PyDescr_NewClassMethod(PyTypeObject *type, PyMethodDef *method)

Return value: New reference.

int PyDescr_IsData(PyObject *descr)

디스크립터 객체 descr가 데이터 어트리뷰트를 기술하고 있으면 참을 반환하고, 메서드를 기술하면 거짓을 돌려줍니다. descr는 디스크립터 객체여야 합니다; 오류 검사는 없습니다.

PyObject* PyWrapper_New(PyObject *, PyObject *)

Return value: New reference.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

구상 객체 계층 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

구상 객체 계층 »

|

슬라이스 객체

PyTypeObject PySlice_Type

슬라이스 객체의 형 객체. 이것은 파이썬 계층의 slice와 같습니다.

int PySlice_Check(PyObject *ob)

Return true if ob is a slice object; ob must not be NULL.

PyObject* PySlice_New(PyObject *start, PyObject *stop, PyObject *step)

Return value: New reference.

Return a new slice object with the given values. The start, stop, and step parameters are used as the values of the slice object attributes of the same names. Any of the values may be NULL, in which case the None will be used for the corresponding attribute. Return NULL if the new object could not be allocated.

int PySlice_GetIndices(PyObject *slice, Py_ssize_t length, Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t *step)

길이가 length인 시퀀스를 가정하여, 슬라이스 객체 slice에서 start, stop 및 step 인덱스를 가져옵니다. length보다 큰 인덱스를 에러로 처리합니다.

성공하면 0을 반환하고, 에러면 예외 설정 없이 -1을 반환합니다 (인덱스 중 하나가 None이 아니고 정수로 변환되지 않는 한, 이때는 예외를 설정하고 -1을 반환합니다).

이 기능을 사용하고 싶지는 않을 것입니다.

버전 3.2에서 변경: 전에는 slice 매개 변수의 매개 변수 형이 PySliceObject*였습니다.

int PySlice_GetIndicesEx(PyObject *slice, Py_ssize_t length, Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t *step, Py_ssize_t *slicelength)

PySlice_GetIndices()를 쓸만하게 대체합니다. 길이가 length인 시퀀스를 가정하여, 슬라이스 객체 slice에서 start, stop 및 step 인덱스를 가져오고, slicelength에 슬라이스의 길이를 저장합니다. 범위를 벗어난 인덱스는 일반 슬라이스의 처리와 일관된 방식으로 잘립니다.

성공하면 0을 반환하고, 에러면 예외를 설정하고 -1을 반환합니다.

참고

이 함수는 크기를 조정할 수 있는 시퀀스에는 안전하지 않은 것으로 간주합니다. 호출은 PySlice_Unpack()와 PySlice_AdjustIndices()의 조합으로 대체되어야 합니다. 즉

if (PySlice_GetIndicesEx(slice, length, &start, &stop, &step, &slicelength) < 0) {
    // return error
}

은 다음으로 대체됩니다

if (PySlice_Unpack(slice, &start, &stop, &step) < 0) {
    // return error
}
slicelength = PySlice_AdjustIndices(length, &start, &stop, step);

버전 3.2에서 변경: 전에는 slice 매개 변수의 매개 변수 형이 PySliceObject*였습니다.

버전 3.6.1에서 변경: Py_LIMITED_API가 설정되어 있지 않거나 0x03050400과 0x03060000 (포함하지 않음) 사이나 0x03060100 이상의 값으로 설정되었으면, PySlice_GetIndicesEx()는 PySlice_Unpack()과 PySlice_AdjustIndices()를 사용하는 매크로로 구현됩니다. 인자 start, stop 및 step는 여러 번 평가됩니다.

버전 3.6.1부터 폐지: Py_LIMITED_API가 0x03050400보다 작거나 0x03060000과 0x03060100 (포함하지 않음) 사이의 값으로 설정되었으면 PySlice_GetIndicesEx()는 폐지된 함수입니다.

int PySlice_Unpack(PyObject *slice, Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t *step)

슬라이스 객체의 start, stop 및 step 데이터 멤버를 C 정수로 추출합니다. PY_SSIZE_T_MAX보다 큰 값을 PY_SSIZE_T_MAX로 조용히 줄이고, PY_SSIZE_T_MIN보다 작은 start 와 stop 값을 PY_SSIZE_T_MIN로 조용히 높이고, -PY_SSIZE_T_MAX보다 작은 step 값을 -PY_SSIZE_T_MAX로 조용히 높입니다.

에러면 -1을, 성공하면 0을 반환합니다.

버전 3.6.1에 추가.

Py_ssize_t PySlice_AdjustIndices(Py_ssize_t length, Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t step)

지정된 length 길이의 시퀀스를 가정하여 start/stop 슬라이스 인덱스를 조정합니다. 범위를 벗어난 인덱스는 일반 슬라이스의 처리와 일관된 방식으로 잘립니다.

슬라이스의 길이를 반환합니다. 항상 성공합니다. 파이썬 코드를 호출하지 않습니다.

버전 3.6.1에 추가.

Ellipsis 객체

PyObject *Py_Ellipsis

파이썬 Ellipsis 객체. 이 객체에는 메서드가 없습니다. 참조 횟수와 관련하여 다른 객체와 마찬가지로 처리해야 합니다. Py_None과 마찬가지로 싱글 톤 객체입니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

구상 객체 계층 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

구상 객체 계층 »

|

MemoryView 객체

memoryview 객체는 C 수준 버퍼 인터페이스를 다른 객체와 마찬가지로 전달될 수 있는 파이썬 객체로 노출합니다.

PyObject *PyMemoryView_FromObject(PyObject *obj)

Return value: New reference.

버퍼 인터페이스를 제공하는 객체에서 memoryview 객체를 만듭니다. obj가 쓰기 가능한 버퍼 제공을 지원하면, memoryview 객체는 읽기/쓰기가 되고, 그렇지 않으면 읽기 전용이거나 제공자의 재량에 따라 읽기/쓰기가 될 수 있습니다.

PyObject *PyMemoryView_FromMemory(char *mem, Py_ssize_t size, int flags)

Return value: New reference.

mem를 하부 버퍼로 사용하여 memoryview 객체를 만듭니다. flags는 PyBUF_READ 나 PyBUF_WRITE 중 하나일 수 있습니다.

버전 3.3에 추가.

PyObject *PyMemoryView_FromBuffer(Py_buffer *view)

Return value: New reference.

주어진 버퍼 구조체 view를 감싸는 memoryview 객체를 만듭니다. 간단한 바이트 버퍼의 경우는, PyMemoryView_FromMemory()가 선호되는 함수입니다.

PyObject *PyMemoryView_GetContiguous(PyObject *obj, int buffertype, char order)

Return value: New reference.

버퍼 인터페이스를 정의하는 객체로부터 메모리의 연속 청크(‘C’ 나 ‘F’ortran order로)로 memoryview 객체를 만듭니다. 메모리가 연속적이면 memoryview 객체는 원래 메모리를 가리킵니다. 그렇지 않으면, 복사본이 만들어지고 memoryview는 새 바이트열 객체를 가리킵니다.

int PyMemoryView_Check(PyObject *obj)

객체 obj가 memoryview 객체면 참을 반환합니다. 현재는 memoryview의 서브 클래스를 만들 수 없습니다.

Py_buffer *PyMemoryView_GET_BUFFER(PyObject *mview)

제공자 버퍼의 memoryview의 비공개 복사본의 포인터를 돌려줍니다. mview는 반드시 memoryview 인스턴스여야 합니다; 이 매크로는 형을 확인하지 않으므로 직접 검사해야 합니다, 그렇지 않으면 충돌 위험이 있습니다.

Py_buffer *PyMemoryView_GET_BASE(PyObject *mview)

Return either a pointer to the exporting object that the memoryview is based on or NULL if the memoryview has been created by one of the functions PyMemoryView_FromMemory() or PyMemoryView_FromBuffer(). mview must be a memoryview instance.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

구상 객체 계층 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

구상 객체 계층 »

|

약한 참조 객체

파이썬은 약한 참조를 1급 객체로 지원합니다. 약한 참조를 직접 구현하는 두 가지 구체적인 객체 형이 있습니다. 첫 번째는 간단한 참조 객체이며, 두 번째는 가능한 한 원래 객체의 프락시 역할을 합니다.

int PyWeakref_Check(ob)

ob가 참조 객체나 프락시 객체면 참을 반환합니다.

int PyWeakref_CheckRef(ob)

ob가 참조 객체면 참을 반환합니다.

int PyWeakref_CheckProxy(ob)

ob가 프락시 객체면 참을 반환합니다.

PyObject* PyWeakref_NewRef(PyObject *ob, PyObject *callback)

Return value: New reference.

Return a weak reference object for the object ob. This will always return a new reference, but is not guaranteed to create a new object; an existing reference object may be returned. The second parameter, callback, can be a callable object that receives notification when ob is garbage collected; it should accept a single parameter, which will be the weak reference object itself. callback may also be None or NULL. If ob is not a weakly-referencable object, or if callback is not callable, None, or NULL, this will return NULL and raise TypeError.

PyObject* PyWeakref_NewProxy(PyObject *ob, PyObject *callback)

Return value: New reference.

Return a weak reference proxy object for the object ob. This will always return a new reference, but is not guaranteed to create a new object; an existing proxy object may be returned. The second parameter, callback, can be a callable object that receives notification when ob is garbage collected; it should accept a single parameter, which will be the weak reference object itself. callback may also be None or NULL. If ob is not a weakly-referencable object, or if callback is not callable, None, or NULL, this will return NULL and raise TypeError.

PyObject* PyWeakref_GetObject(PyObject *ref)

Return value: Borrowed reference.

약한 참조(ref)로부터 참조된 객체를 반환합니다. 참조가 더는 살아있지 않으면, Py_None을 반환합니다.

참고

이 함수는 참조된 객체에 대한 빌린 참조를 반환합니다. 이는 객체를 계속 사용하는 동안 객체가 파괴될 수 없음을 알고 있을 때를 제외하고, 객체에 대해 항상 Py_INCREF()를 호출해야 함을 뜻합니다.

PyObject* PyWeakref_GET_OBJECT(PyObject *ref)

Return value: Borrowed reference.

PyWeakref_GetObject()와 유사하지만, 에러 검사를 수행하지 않는 매크로로 구현됩니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

구상 객체 계층 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

구상 객체 계층 »

|

캡슐

이 객체 사용에 대한 자세한 정보는 Providing a C API for an Extension Module를 참조하십시오.

버전 3.1에 추가.

PyCapsule

이 PyObject의 서브 형은 불투명한 값을 나타내며, 파이썬 코드를 통해 다른 C 코드로 불투명한 값(void* 포인터로)을 전달해야 하는 C 확장 모듈에 유용합니다. 이것은 한 모듈에서 정의된 C 함수 포인터를 다른 모듈에서 사용할 수 있게 만드는 데 종종 사용되므로, 일반 임포트 메커니즘을 사용하여 동적으로 로드된 모듈에 정의된 C API에 액세스할 수 있습니다.

PyCapsule_Destructor

캡슐에 대한 파괴자(destructor) 콜백 형. 이렇게 정의됩니다:

typedef void (*PyCapsule_Destructor)(PyObject *);

PyCapsule_Destructor 콜백의 의미는 PyCapsule_New()를 참조하십시오.

int PyCapsule_CheckExact(PyObject *p)

인자가 PyCapsule이면 참을 돌려줍니다.

PyObject* PyCapsule_New(void *pointer, const char *name, PyCapsule_Destructor destructor)

Return value: New reference.

Create a PyCapsule encapsulating the pointer. The pointer argument may not be NULL.

On failure, set an exception and return NULL.

The name string may either be NULL or a pointer to a valid C string. If non-NULL, this string must outlive the capsule. (Though it is permitted to free it inside the destructor.)

If the destructor argument is not NULL, it will be called with the capsule as its argument when it is destroyed.

이 캡슐을 모듈의 어트리뷰트로 저장하려면, name을 modulename.attributename로 지정해야 합니다. 이렇게 하면 다른 모듈이 PyCapsule_Import()를 사용하여 캡슐을 임포트 할 수 있습니다.

void* PyCapsule_GetPointer(PyObject *capsule, const char *name)

Retrieve the pointer stored in the capsule. On failure, set an exception and return NULL.

The name parameter must compare exactly to the name stored in the capsule. If the name stored in the capsule is NULL, the name passed in must also be NULL. Python uses the C function strcmp() to compare capsule names.

PyCapsule_Destructor PyCapsule_GetDestructor(PyObject *capsule)

Return the current destructor stored in the capsule. On failure, set an exception and return NULL.

It is legal for a capsule to have a NULL destructor. This makes a NULL return code somewhat ambiguous; use PyCapsule_IsValid() or PyErr_Occurred() to disambiguate.

void* PyCapsule_GetContext(PyObject *capsule)

Return the current context stored in the capsule. On failure, set an exception and return NULL.

It is legal for a capsule to have a NULL context. This makes a NULL return code somewhat ambiguous; use PyCapsule_IsValid() or PyErr_Occurred() to disambiguate.

const char* PyCapsule_GetName(PyObject *capsule)

Return the current name stored in the capsule. On failure, set an exception and return NULL.

It is legal for a capsule to have a NULL name. This makes a NULL return code somewhat ambiguous; use PyCapsule_IsValid() or PyErr_Occurred() to disambiguate.

void* PyCapsule_Import(const char *name, int no_block)

모듈의 캡슐 어트리뷰트에서 C 객체에 대한 포인터를 임포트 합니다. name 매개 변수는 module.attribute 처럼 어트리뷰트의 전체 이름을 지정해야 합니다. 캡슐에 저장된 name은, 이 문자열과 정확히 일치해야 합니다. no_block이 참이면, 블록하지 않고 모듈을 임포트 합니다 (PyImport_ImportModuleNoBlock()를 사용해서). no_block이 거짓이면, 모듈을 평범하게 임포트 합니다 (PyImport_ImportModule()을 사용해서).

Return the capsule’s internal pointer on success. On failure, set an exception and return NULL.

int PyCapsule_IsValid(PyObject *capsule, const char *name)

Determines whether or not capsule is a valid capsule. A valid capsule is non-NULL, passes PyCapsule_CheckExact(), has a non-NULL pointer stored in it, and its internal name matches the name parameter. (See PyCapsule_GetPointer() for information on how capsule names are compared.)

즉, PyCapsule_IsValid()가 참값을 반환하면, 모든 접근자(PyCapsule_Get()으로 시작하는 모든 함수)에 대한 호출이 성공함이 보장됩니다.

객체가 유효하고 전달된 이름과 일치하면 0이 아닌 값을 반환합니다. 그렇지 않으면 0을 반환합니다. 이 함수는 실패하지 않습니다.

int PyCapsule_SetContext(PyObject *capsule, void *context)

capsule 내부의 컨텍스트 포인터를 context로 설정합니다.

성공하면 0을 반환합니다. 실패하면 0이 아닌 값을 반환하고 예외를 설정합니다.

int PyCapsule_SetDestructor(PyObject *capsule, PyCapsule_Destructor destructor)

capsule 내부의 파괴자를 destructor로 설정합니다.

성공하면 0을 반환합니다. 실패하면 0이 아닌 값을 반환하고 예외를 설정합니다.

int PyCapsule_SetName(PyObject *capsule, const char *name)

Set the name inside capsule to name. If non-NULL, the name must outlive the capsule. If the previous name stored in the capsule was not NULL, no attempt is made to free it.

성공하면 0을 반환합니다. 실패하면 0이 아닌 값을 반환하고 예외를 설정합니다.

int PyCapsule_SetPointer(PyObject *capsule, void *pointer)

Set the void pointer inside capsule to pointer. The pointer may not be NULL.

성공하면 0을 반환합니다. 실패하면 0이 아닌 값을 반환하고 예외를 설정합니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

구상 객체 계층 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

구상 객체 계층 »

|

제너레이터 객체

제너레이터 객체는 파이썬이 제너레이터 이터레이터를 구현하기 위해 사용하는 객체입니다. 일반적으로 PyGen_New() 또는 PyGen_NewWithQualName()를 명시적으로 호출하는 것이 아니라, 값을 일드(yield)하는 함수를 이터레이트하여 만들어집니다.

PyGenObject

제너레이터 객체에 사용되는 C 구조체.

PyTypeObject PyGen_Type

제너레이터 객체에 해당하는 형 객체

int PyGen_Check(PyObject *ob)

Return true if ob is a generator object; ob must not be NULL.

int PyGen_CheckExact(PyObject *ob)

Return true if ob’s type is PyGen_Type; ob must not be NULL.

PyObject* PyGen_New(PyFrameObject *frame)

Return value: New reference.

Create and return a new generator object based on the frame object. A reference to frame is stolen by this function. The argument must not be NULL.

PyObject* PyGen_NewWithQualName(PyFrameObject *frame, PyObject *name, PyObject *qualname)

Return value: New reference.

Create and return a new generator object based on the frame object, with __name__ and __qualname__ set to name and qualname. A reference to frame is stolen by this function. The frame argument must not be NULL.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

구상 객체 계층 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

구상 객체 계층 »

|

코루틴 객체

버전 3.5에 추가.

코루틴 객체는 async 키워드로 선언된 함수가 반환하는 것입니다.

PyCoroObject

코루틴 객체에 사용되는 C 구조체.

PyTypeObject PyCoro_Type

코루틴 객체에 해당하는 형 객체.

int PyCoro_CheckExact(PyObject *ob)

Return true if ob’s type is PyCoro_Type; ob must not be NULL.

PyObject* PyCoro_New(PyFrameObject *frame, PyObject *name, PyObject *qualname)

Return value: New reference.

Create and return a new coroutine object based on the frame object, with __name__ and __qualname__ set to name and qualname. A reference to frame is stolen by this function. The frame argument must not be NULL.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

구상 객체 계층 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

구상 객체 계층 »

|

컨텍스트 변수 객체

참고

버전 3.7.1에서 변경:

파이썬 3.7.1에서 모든 컨텍스트 변수 C API의 서명이 PyContext, PyContextVar 및 PyContextToken 대신 PyObject 포인터를 사용하도록 변경되었습니다, 예를 들어:

// in 3.7.0:
PyContext *PyContext_New(void);

// in 3.7.1+:
PyObject *PyContext_New(void);

자세한 내용은 bpo-34762 [https://bugs.python.org/issue?@action=redirect&bpo=34762]를 참조하십시오.

버전 3.7에 추가.

이 절에서는 contextvars 모듈을 위한 공용 C API에 대해 자세히 설명합니다.

PyContext

contextvars.Context 객체를 나타내는 데 사용되는 C 구조체.

PyContextVar

contextvars.ContextVar 객체를 나타내는 데 사용되는 C 구조체.

PyContextToken

contextvars.Token 객체를 나타내는 데 사용되는 C 구조체.

PyTypeObject PyContext_Type

context 형을 나타내는 형 객체.

PyTypeObject PyContextVar_Type

컨텍스트 변수 형을 나타내는 형 객체.

PyTypeObject PyContextToken_Type

컨텍스트 변수 토큰 형을 나타내는 형 객체.

형 검사 매크로:

int PyContext_CheckExact(PyObject *o)

Return true if o is of type PyContext_Type. o must not be NULL. This function always succeeds.

int PyContextVar_CheckExact(PyObject *o)

Return true if o is of type PyContextVar_Type. o must not be NULL. This function always succeeds.

int PyContextToken_CheckExact(PyObject *o)

Return true if o is of type PyContextToken_Type. o must not be NULL. This function always succeeds.

컨텍스트 객체 관리 함수:

PyObject *PyContext_New(void)

Return value: New reference.

새로운 빈 컨텍스트 객체를 만듭니다. 에러가 발생하면 NULL를 반환합니다.

PyObject *PyContext_Copy(PyObject *ctx)

Return value: New reference.

전달된 ctx 컨텍스트 객체의 얕은 복사본을 만듭니다. 에러가 발생하면 NULL을 반환합니다.

PyObject *PyContext_CopyCurrent(void)

Return value: New reference.

현재 스레드 컨텍스트의 얕은 복사본을 만듭니다. 에러가 발생하면 NULL을 반환합니다.

int PyContext_Enter(PyObject *ctx)

현재 스레드의 현재 컨텍스트로 ctx를 설정합니다. 성공 시 0을 반환하고, 에러 시 -1을 반환합니다.

int PyContext_Exit(PyObject *ctx)

ctx 컨텍스트를 비활성화하고 이전 컨텍스트를 현재 스레드의 현재 컨텍스트로 복원합니다. 성공 시 0을 반환하고, 에러 시 -1을 반환합니다.

int PyContext_ClearFreeList()

컨텍스트 변수 자유 목록을 지웁니다. 해제된 총 항목 수를 반환합니다. 이 함수는 항상 성공합니다.

컨텍스트 변수 함수:

PyObject *PyContextVar_New(const char *name, PyObject *def)

Return value: New reference.

새 ContextVar 객체를 만듭니다. name 매개 변수는 인트로스펙션과 디버그 목적으로 사용됩니다. def 매개 변수는 선택적으로 컨텍스트 변수의 기본값을 지정할 수 있습니다. 에러가 발생하면, 이 함수는 NULL을 반환합니다.

int PyContextVar_Get(PyObject *var, PyObject *default_value, PyObject **value)

컨텍스트 변수의 값을 가져옵니다. 조회하는 동안 에러가 발생하면 -1을 반환하고, 값이 있는지와 상관없이 에러가 발생하지 않으면 0을 반환합니다.

컨텍스트 변수가 발견되면, value는 그것을 가리키는 포인터가 됩니다. 컨텍스트 변수가 발견되지 않으면, value는 다음을 가리 킵니다:

default_value, NULL이 아니면;

var의 기본값, NULL이 아니면;

NULL

값이 발견되면, 이 함수는 그것에 대한 새 참조를 만듭니다.

PyObject *PyContextVar_Set(PyObject *var, PyObject *value)

Return value: New reference.

현재 컨텍스트에서 var의 값을 value로 설정합니다. PyObject 객체에 대한 포인터를 반환하거나, 에러가 발생하면 NULL을 반환합니다.

int PyContextVar_Reset(PyObject *var, PyObject *token)

var 컨텍스트 변수의 상태를 token을 반환한 PyContextVar_Set() 호출 전의 상태로 재설정합니다. 이 함수는 성공 시 0을 반환하고, 에러 시 -1을 반환합니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

구상 객체 계층 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

구상 객체 계층 »

|

DateTime 객체

다양한 날짜와 시간 객체가 datetime 모듈에서 제공됩니다. 이 함수를 사용하기 전에, 헤더 파일 datetime.h가 소스에 포함되어야 하고 (Python.h가 포함하지 않음에 유의하십시오), 일반적으로 모듈 초기화 함수의 일부로 PyDateTime_IMPORT 매크로를 호출해야 합니다. 매크로는 C 구조체에 대한 포인터를 다음 매크로에서 사용되는 static 변수 PyDateTimeAPI에 넣습니다.

UTC 싱글톤에 액세스하기 위한 매크로:

PyObject* PyDateTime_TimeZone_UTC

UTC를 나타내는 시간대 싱글톤을 반환합니다, datetime.timezone.utc와 같은 객체입니다.

버전 3.7에 추가.

형 검사 매크로:

int PyDate_Check(PyObject *ob)

Return true if ob is of type PyDateTime_DateType or a subtype of PyDateTime_DateType. ob must not be NULL.

int PyDate_CheckExact(PyObject *ob)

Return true if ob is of type PyDateTime_DateType. ob must not be NULL.

int PyDateTime_Check(PyObject *ob)

Return true if ob is of type PyDateTime_DateTimeType or a subtype of PyDateTime_DateTimeType. ob must not be NULL.

int PyDateTime_CheckExact(PyObject *ob)

Return true if ob is of type PyDateTime_DateTimeType. ob must not be NULL.

int PyTime_Check(PyObject *ob)

Return true if ob is of type PyDateTime_TimeType or a subtype of PyDateTime_TimeType. ob must not be NULL.

int PyTime_CheckExact(PyObject *ob)

Return true if ob is of type PyDateTime_TimeType. ob must not be NULL.

int PyDelta_Check(PyObject *ob)

Return true if ob is of type PyDateTime_DeltaType or a subtype of PyDateTime_DeltaType. ob must not be NULL.

int PyDelta_CheckExact(PyObject *ob)

Return true if ob is of type PyDateTime_DeltaType. ob must not be NULL.

int PyTZInfo_Check(PyObject *ob)

Return true if ob is of type PyDateTime_TZInfoType or a subtype of PyDateTime_TZInfoType. ob must not be NULL.

int PyTZInfo_CheckExact(PyObject *ob)

Return true if ob is of type PyDateTime_TZInfoType. ob must not be NULL.

객체를 만드는 매크로:

PyObject* PyDate_FromDate(int year, int month, int day)

Return value: New reference.

지정된 년, 월, 일의 datetime.date 객체를 반환합니다.

PyObject* PyDateTime_FromDateAndTime(int year, int month, int day, int hour, int minute, int second, int usecond)

Return value: New reference.

지정된 년, 월, 일, 시, 분, 초 및 마이크로초의 datetime.datetime 객체를 반환합니다.

PyObject* PyDateTime_FromDateAndTimeAndFold(int year, int month, int day, int hour, int minute, int second, int usecond, int fold)

Return value: New reference.

지정된 년, 월, 일, 시, 분, 초, 마이크로초 및 fold의 datetime.datetime 객체를 반환합니다.

버전 3.6에 추가.

PyObject* PyTime_FromTime(int hour, int minute, int second, int usecond)

Return value: New reference.

지정된 시, 분, 초 및 마이크로초의 datetime.time 객체를 반환합니다.

PyObject* PyTime_FromTimeAndFold(int hour, int minute, int second, int usecond, int fold)

Return value: New reference.

지정된 시, 분, 초, 마이크로초 및 fold의 datetime.time 객체를 반환합니다.

버전 3.6에 추가.

PyObject* PyDelta_FromDSU(int days, int seconds, int useconds)

Return value: New reference.

지정된 일, 초 및 마이크로초 수를 나타내는 datetime.timedelta 객체를 반환합니다. 결과 마이크로초와 초가 datetime.timedelta 객체에 관해 설명된 범위에 있도록 정규화가 수행됩니다.

PyObject* PyTimeZone_FromOffset(PyDateTime_DeltaType* offset)

Return value: New reference.

offset 인자로 나타내지는 이름이 없는 고정 오프셋의 datetime.timezone 객체를 돌려줍니다.

버전 3.7에 추가.

PyObject* PyTimeZone_FromOffsetAndName(PyDateTime_DeltaType* offset, PyUnicode* name)

Return value: New reference.

offset 인자와 tzname name으로 나타내지는 고정 오프셋의 datetime.timezone 객체를 돌려줍니다.

버전 3.7에 추가.

Macros to extract fields from date objects. The argument must be an instance of PyDateTime_Date, including subclasses (such as PyDateTime_DateTime). The argument must not be NULL, and the type is not checked:

int PyDateTime_GET_YEAR(PyDateTime_Date *o)

양의 int로, 년을 반환합니다.

int PyDateTime_GET_MONTH(PyDateTime_Date *o)

1에서 12까지의 int로, 월을 반환합니다.

int PyDateTime_GET_DAY(PyDateTime_Date *o)

1에서 31까지의 int로, 일을 반환합니다.

Macros to extract fields from datetime objects. The argument must be an instance of PyDateTime_DateTime, including subclasses. The argument must not be NULL, and the type is not checked:

int PyDateTime_DATE_GET_HOUR(PyDateTime_DateTime *o)

0부터 23까지의 int로, 시를 반환합니다.

int PyDateTime_DATE_GET_MINUTE(PyDateTime_DateTime *o)

0부터 59까지의 int로, 분을 반환합니다.

int PyDateTime_DATE_GET_SECOND(PyDateTime_DateTime *o)

0부터 59까지의 int로, 초를 반환합니다.

int PyDateTime_DATE_GET_MICROSECOND(PyDateTime_DateTime *o)

0부터 999999까지의 int로, 마이크로초를 반환합니다.

int PyDateTime_DATE_GET_FOLD(PyDateTime_DateTime *o)

Return the fold, as an int from 0 through 1.

버전 3.6에 추가.

Macros to extract fields from time objects. The argument must be an instance of PyDateTime_Time, including subclasses. The argument must not be NULL, and the type is not checked:

int PyDateTime_TIME_GET_HOUR(PyDateTime_Time *o)

0부터 23까지의 int로, 시를 반환합니다.

int PyDateTime_TIME_GET_MINUTE(PyDateTime_Time *o)

0부터 59까지의 int로, 분을 반환합니다.

int PyDateTime_TIME_GET_SECOND(PyDateTime_Time *o)

0부터 59까지의 int로, 초를 반환합니다.

int PyDateTime_TIME_GET_MICROSECOND(PyDateTime_Time *o)

0부터 999999까지의 int로, 마이크로초를 반환합니다.

int PyDateTime_TIME_GET_FOLD(PyDateTime_Time *o)

Return the fold, as an int from 0 through 1.

버전 3.6에 추가.

Macros to extract fields from time delta objects. The argument must be an instance of PyDateTime_Delta, including subclasses. The argument must not be NULL, and the type is not checked:

int PyDateTime_DELTA_GET_DAYS(PyDateTime_Delta *o)

-999999999에서 999999999까지의 int로, 일 수를 반환합니다.

버전 3.3에 추가.

int PyDateTime_DELTA_GET_SECONDS(PyDateTime_Delta *o)

0부터 86399까지의 int로, 초 수를 반환합니다.

버전 3.3에 추가.

int PyDateTime_DELTA_GET_MICROSECONDS(PyDateTime_Delta *o)

0에서 999999까지의 int로, 마이크로초 수를 반환합니다.

버전 3.3에 추가.

DB API를 구현하는 모듈의 편의를 위한 매크로:

PyObject* PyDateTime_FromTimestamp(PyObject *args)

Return value: New reference.

datetime.datetime.fromtimestamp()에 전달하는 데 적합한 인자 튜플로 새 datetime.datetime 객체를 만들고 반환합니다.

PyObject* PyDate_FromTimestamp(PyObject *args)

Return value: New reference.

datetime.date.fromtimestamp()에 전달하는 데 적합한 인자 튜플로 새 datetime.date 객체를 만들고 반환합니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

구상 객체 계층 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

|

Initialization, Finalization, and Threads

Before Python Initialization

In an application embedding Python, the Py_Initialize() function must be called before using any other Python/C API functions; with the exception of a few functions and the global configuration variables.

The following functions can be safely called before Python is initialized:

Configuration functions:

PyImport_AppendInittab()

PyImport_ExtendInittab()

PyInitFrozenExtensions()

PyMem_SetAllocator()

PyMem_SetupDebugHooks()

PyObject_SetArenaAllocator()

Py_SetPath()

Py_SetProgramName()

Py_SetPythonHome()

Py_SetStandardStreamEncoding()

PySys_AddWarnOption()

PySys_AddXOption()

PySys_ResetWarnOptions()

Informative functions:

Py_IsInitialized()

PyMem_GetAllocator()

PyObject_GetArenaAllocator()

Py_GetBuildInfo()

Py_GetCompiler()

Py_GetCopyright()

Py_GetPlatform()

Py_GetVersion()

Utilities:

Py_DecodeLocale()

Memory allocators:

PyMem_RawMalloc()

PyMem_RawRealloc()

PyMem_RawCalloc()

PyMem_RawFree()

참고

The following functions should not be called before Py_Initialize(): Py_EncodeLocale(), Py_GetPath(), Py_GetPrefix(), Py_GetExecPrefix(), Py_GetProgramFullPath(), Py_GetPythonHome(), Py_GetProgramName() and PyEval_InitThreads().

Global configuration variables

Python has variables for the global configuration to control different features and options. By default, these flags are controlled by command line options.

When a flag is set by an option, the value of the flag is the number of times that the option was set. For example, -b sets Py_BytesWarningFlag to 1 and -bb sets Py_BytesWarningFlag to 2.

Py_BytesWarningFlag

Issue a warning when comparing bytes or bytearray with str or bytes with int. Issue an error if greater or equal to 2.

Set by the -b option.

Py_DebugFlag

Turn on parser debugging output (for expert only, depending on compilation options).

Set by the -d option and the PYTHONDEBUG environment variable.

Py_DontWriteBytecodeFlag

If set to non-zero, Python won’t try to write .pyc files on the import of source modules.

Set by the -B option and the PYTHONDONTWRITEBYTECODE environment variable.

Py_FrozenFlag

Suppress error messages when calculating the module search path in Py_GetPath().

Private flag used by _freeze_importlib and frozenmain programs.

Py_HashRandomizationFlag

Set to 1 if the PYTHONHASHSEED environment variable is set to a non-empty string.

If the flag is non-zero, read the PYTHONHASHSEED environment variable to initialize the secret hash seed.

Py_IgnoreEnvironmentFlag

Ignore all PYTHON* environment variables, e.g. PYTHONPATH and PYTHONHOME, that might be set.

Set by the -E and -I options.

Py_InspectFlag

When a script is passed as first argument or the -c option is used, enter interactive mode after executing the script or the command, even when sys.stdin does not appear to be a terminal.

Set by the -i option and the PYTHONINSPECT environment variable.

Py_InteractiveFlag

Set by the -i option.

Py_IsolatedFlag

Run Python in isolated mode. In isolated mode sys.path contains neither the script’s directory nor the user’s site-packages directory.

Set by the -I option.

버전 3.4에 추가.

Py_LegacyWindowsFSEncodingFlag

If the flag is non-zero, use the mbcs encoding instead of the UTF-8 encoding for the filesystem encoding.

Set to 1 if the PYTHONLEGACYWINDOWSFSENCODING environment variable is set to a non-empty string.

See PEP 529 [https://www.python.org/dev/peps/pep-0529] for more details.

Availability: Windows.

Py_LegacyWindowsStdioFlag

If the flag is non-zero, use io.FileIO instead of WindowsConsoleIO for sys standard streams.

Set to 1 if the PYTHONLEGACYWINDOWSSTDIO environment variable is set to a non-empty string.

See PEP 528 [https://www.python.org/dev/peps/pep-0528] for more details.

Availability: Windows.

Py_NoSiteFlag

Disable the import of the module site and the site-dependent manipulations of sys.path that it entails. Also disable these manipulations if site is explicitly imported later (call site.main() if you want them to be triggered).

Set by the -S option.

Py_NoUserSiteDirectory

Don’t add the user site-packages directory to sys.path.

Set by the -s and -I options, and the PYTHONNOUSERSITE environment variable.

Py_OptimizeFlag

Set by the -O option and the PYTHONOPTIMIZE environment variable.

Py_QuietFlag

Don’t display the copyright and version messages even in interactive mode.

Set by the -q option.

버전 3.2에 추가.

Py_UnbufferedStdioFlag

Force the stdout and stderr streams to be unbuffered.

Set by the -u option and the PYTHONUNBUFFERED environment variable.

Py_VerboseFlag

Print a message each time a module is initialized, showing the place (filename or built-in module) from which it is loaded. If greater or equal to 2, print a message for each file that is checked for when searching for a module. Also provides information on module cleanup at exit.

Set by the -v option and the PYTHONVERBOSE environment variable.

Initializing and finalizing the interpreter

void Py_Initialize()

Initialize the Python interpreter. In an application embedding Python, this should be called before using any other Python/C API functions; see Before Python Initialization for the few exceptions.

This initializes the table of loaded modules (sys.modules), and creates the fundamental modules builtins, __main__ and sys. It also initializes the module search path (sys.path). It does not set sys.argv; use PySys_SetArgvEx() for that. This is a no-op when called for a second time (without calling Py_FinalizeEx() first). There is no return value; it is a fatal error if the initialization fails.

참고

On Windows, changes the console mode from O_TEXT to O_BINARY, which will also affect non-Python uses of the console using the C Runtime.

void Py_InitializeEx(int initsigs)

This function works like Py_Initialize() if initsigs is 1. If initsigs is 0, it skips initialization registration of signal handlers, which might be useful when Python is embedded.

int Py_IsInitialized()

Return true (nonzero) when the Python interpreter has been initialized, false (zero) if not. After Py_FinalizeEx() is called, this returns false until Py_Initialize() is called again.

int Py_FinalizeEx()

Undo all initializations made by Py_Initialize() and subsequent use of Python/C API functions, and destroy all sub-interpreters (see Py_NewInterpreter() below) that were created and not yet destroyed since the last call to Py_Initialize(). Ideally, this frees all memory allocated by the Python interpreter. This is a no-op when called for a second time (without calling Py_Initialize() again first). Normally the return value is 0. If there were errors during finalization (flushing buffered data), -1 is returned.

This function is provided for a number of reasons. An embedding application might want to restart Python without having to restart the application itself. An application that has loaded the Python interpreter from a dynamically loadable library (or DLL) might want to free all memory allocated by Python before unloading the DLL. During a hunt for memory leaks in an application a developer might want to free all memory allocated by Python before exiting from the application.

Bugs and caveats: The destruction of modules and objects in modules is done in random order; this may cause destructors (__del__() methods) to fail when they depend on other objects (even functions) or modules. Dynamically loaded extension modules loaded by Python are not unloaded. Small amounts of memory allocated by the Python interpreter may not be freed (if you find a leak, please report it). Memory tied up in circular references between objects is not freed. Some memory allocated by extension modules may not be freed. Some extensions may not work properly if their initialization routine is called more than once; this can happen if an application calls Py_Initialize() and Py_FinalizeEx() more than once.

버전 3.6에 추가.

void Py_Finalize()

This is a backwards-compatible version of Py_FinalizeEx() that disregards the return value.

Process-wide parameters

int Py_SetStandardStreamEncoding(const char *encoding, const char *errors)

This function should be called before Py_Initialize(), if it is called at all. It specifies which encoding and error handling to use with standard IO, with the same meanings as in str.encode().

It overrides PYTHONIOENCODING values, and allows embedding code to control IO encoding when the environment variable does not work.

encoding and/or errors may be NULL to use PYTHONIOENCODING and/or default values (depending on other settings).

Note that sys.stderr always uses the “backslashreplace” error handler, regardless of this (or any other) setting.

If Py_FinalizeEx() is called, this function will need to be called again in order to affect subsequent calls to Py_Initialize().

Returns 0 if successful, a nonzero value on error (e.g. calling after the interpreter has already been initialized).

버전 3.4에 추가.

void Py_SetProgramName(const wchar_t *name)

This function should be called before Py_Initialize() is called for the first time, if it is called at all. It tells the interpreter the value of the argv[0] argument to the main() function of the program (converted to wide characters). This is used by Py_GetPath() and some other functions below to find the Python run-time libraries relative to the interpreter executable. The default value is 'python'. The argument should point to a zero-terminated wide character string in static storage whose contents will not change for the duration of the program’s execution. No code in the Python interpreter will change the contents of this storage.

Use Py_DecodeLocale() to decode a bytes string to get a wchar_* string.

wchar* Py_GetProgramName()

Return the program name set with Py_SetProgramName(), or the default. The returned string points into static storage; the caller should not modify its value.

wchar_t* Py_GetPrefix()

Return the prefix for installed platform-independent files. This is derived through a number of complicated rules from the program name set with Py_SetProgramName() and some environment variables; for example, if the program name is '/usr/local/bin/python', the prefix is '/usr/local'. The returned string points into static storage; the caller should not modify its value. This corresponds to the prefix variable in the top-level Makefile and the --prefix argument to the configure script at build time. The value is available to Python code as sys.prefix. It is only useful on Unix. See also the next function.

wchar_t* Py_GetExecPrefix()

Return the exec-prefix for installed platform-dependent files. This is derived through a number of complicated rules from the program name set with Py_SetProgramName() and some environment variables; for example, if the program name is '/usr/local/bin/python', the exec-prefix is '/usr/local'. The returned string points into static storage; the caller should not modify its value. This corresponds to the exec_prefix variable in the top-level Makefile and the --exec-prefix argument to the configure script at build time. The value is available to Python code as sys.exec_prefix. It is only useful on Unix.

Background: The exec-prefix differs from the prefix when platform dependent files (such as executables and shared libraries) are installed in a different directory tree. In a typical installation, platform dependent files may be installed in the /usr/local/plat subtree while platform independent may be installed in /usr/local.

Generally speaking, a platform is a combination of hardware and software families, e.g. Sparc machines running the Solaris 2.x operating system are considered the same platform, but Intel machines running Solaris 2.x are another platform, and Intel machines running Linux are yet another platform. Different major revisions of the same operating system generally also form different platforms. Non-Unix operating systems are a different story; the installation strategies on those systems are so different that the prefix and exec-prefix are meaningless, and set to the empty string. Note that compiled Python bytecode files are platform independent (but not independent from the Python version by which they were compiled!).

System administrators will know how to configure the mount or automount programs to share /usr/local between platforms while having /usr/local/plat be a different filesystem for each platform.

wchar_t* Py_GetProgramFullPath()

Return the full program name of the Python executable; this is computed as a side-effect of deriving the default module search path from the program name (set by Py_SetProgramName() above). The returned string points into static storage; the caller should not modify its value. The value is available to Python code as sys.executable.

wchar_t* Py_GetPath()

Return the default module search path; this is computed from the program name (set by Py_SetProgramName() above) and some environment variables. The returned string consists of a series of directory names separated by a platform dependent delimiter character. The delimiter character is ':' on Unix and Mac OS X, ';' on Windows. The returned string points into static storage; the caller should not modify its value. The list sys.path is initialized with this value on interpreter startup; it can be (and usually is) modified later to change the search path for loading modules.

void Py_SetPath(const wchar_t *)

Set the default module search path. If this function is called before Py_Initialize(), then Py_GetPath() won’t attempt to compute a default search path but uses the one provided instead. This is useful if Python is embedded by an application that has full knowledge of the location of all modules. The path components should be separated by the platform dependent delimiter character, which is ':' on Unix and Mac OS X, ';' on Windows.

This also causes sys.executable to be set only to the raw program name (see Py_SetProgramName()) and for sys.prefix and sys.exec_prefix to be empty. It is up to the caller to modify these if required after calling Py_Initialize().

Use Py_DecodeLocale() to decode a bytes string to get a wchar_* string.

The path argument is copied internally, so the caller may free it after the call completes.

const char* Py_GetVersion()

Return the version of this Python interpreter. This is a string that looks something like

"3.0a5+ (py3k:63103M, May 12 2008, 00:53:55) \n[GCC 4.2.3]"

The first word (up to the first space character) is the current Python version; the first three characters are the major and minor version separated by a period. The returned string points into static storage; the caller should not modify its value. The value is available to Python code as sys.version.

const char* Py_GetPlatform()

Return the platform identifier for the current platform. On Unix, this is formed from the “official” name of the operating system, converted to lower case, followed by the major revision number; e.g., for Solaris 2.x, which is also known as SunOS 5.x, the value is 'sunos5'. On Mac OS X, it is 'darwin'. On Windows, it is 'win'. The returned string points into static storage; the caller should not modify its value. The value is available to Python code as sys.platform.

const char* Py_GetCopyright()

Return the official copyright string for the current Python version, for example

'Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam'

The returned string points into static storage; the caller should not modify its value. The value is available to Python code as sys.copyright.

const char* Py_GetCompiler()

Return an indication of the compiler used to build the current Python version, in square brackets, for example:

"[GCC 2.7.2.2]"

The returned string points into static storage; the caller should not modify its value. The value is available to Python code as part of the variable sys.version.

const char* Py_GetBuildInfo()

Return information about the sequence number and build date and time of the current Python interpreter instance, for example

"#67, Aug  1 1997, 22:34:28"

The returned string points into static storage; the caller should not modify its value. The value is available to Python code as part of the variable sys.version.

void PySys_SetArgvEx(int argc, wchar_t **argv, int updatepath)

Set sys.argv based on argc and argv. These parameters are similar to those passed to the program’s main() function with the difference that the first entry should refer to the script file to be executed rather than the executable hosting the Python interpreter. If there isn’t a script that will be run, the first entry in argv can be an empty string. If this function fails to initialize sys.argv, a fatal condition is signalled using Py_FatalError().

If updatepath is zero, this is all the function does. If updatepath is non-zero, the function also modifies sys.path according to the following algorithm:

If the name of an existing script is passed in argv[0], the absolute path of the directory where the script is located is prepended to sys.path.

Otherwise (that is, if argc is 0 or argv[0] doesn’t point to an existing file name), an empty string is prepended to sys.path, which is the same as prepending the current working directory (".").

Use Py_DecodeLocale() to decode a bytes string to get a wchar_* string.

참고

It is recommended that applications embedding the Python interpreter for purposes other than executing a single script pass 0 as updatepath, and update sys.path themselves if desired. See CVE-2008-5983 [https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2008-5983].

On versions before 3.1.3, you can achieve the same effect by manually popping the first sys.path element after having called PySys_SetArgv(), for example using:

PyRun_SimpleString("import sys; sys.path.pop(0)\n");

버전 3.1.3에 추가.

void PySys_SetArgv(int argc, wchar_t **argv)

This function works like PySys_SetArgvEx() with updatepath set to 1 unless the python interpreter was started with the -I.

Use Py_DecodeLocale() to decode a bytes string to get a wchar_* string.

버전 3.4에서 변경: The updatepath value depends on -I.

void Py_SetPythonHome(const wchar_t *home)

Set the default “home” directory, that is, the location of the standard Python libraries. See PYTHONHOME for the meaning of the argument string.

The argument should point to a zero-terminated character string in static storage whose contents will not change for the duration of the program’s execution. No code in the Python interpreter will change the contents of this storage.

Use Py_DecodeLocale() to decode a bytes string to get a wchar_* string.

w_char* Py_GetPythonHome()

Return the default “home”, that is, the value set by a previous call to Py_SetPythonHome(), or the value of the PYTHONHOME environment variable if it is set.

Thread State and the Global Interpreter Lock

The Python interpreter is not fully thread-safe. In order to support multi-threaded Python programs, there’s a global lock, called the global interpreter lock or GIL, that must be held by the current thread before it can safely access Python objects. Without the lock, even the simplest operations could cause problems in a multi-threaded program: for example, when two threads simultaneously increment the reference count of the same object, the reference count could end up being incremented only once instead of twice.

Therefore, the rule exists that only the thread that has acquired the GIL may operate on Python objects or call Python/C API functions. In order to emulate concurrency of execution, the interpreter regularly tries to switch threads (see sys.setswitchinterval()). The lock is also released around potentially blocking I/O operations like reading or writing a file, so that other Python threads can run in the meantime.

The Python interpreter keeps some thread-specific bookkeeping information inside a data structure called PyThreadState. There’s also one global variable pointing to the current PyThreadState: it can be retrieved using PyThreadState_Get().

Releasing the GIL from extension code

Most extension code manipulating the GIL has the following simple structure:

Save the thread state in a local variable.
Release the global interpreter lock.
... Do some blocking I/O operation ...
Reacquire the global interpreter lock.
Restore the thread state from the local variable.

This is so common that a pair of macros exists to simplify it:

Py_BEGIN_ALLOW_THREADS
... Do some blocking I/O operation ...
Py_END_ALLOW_THREADS

The Py_BEGIN_ALLOW_THREADS macro opens a new block and declares a hidden local variable; the Py_END_ALLOW_THREADS macro closes the block.

The block above expands to the following code:

PyThreadState *_save;

_save = PyEval_SaveThread();
... Do some blocking I/O operation ...
PyEval_RestoreThread(_save);

Here is how these functions work: the global interpreter lock is used to protect the pointer to the current thread state. When releasing the lock and saving the thread state, the current thread state pointer must be retrieved before the lock is released (since another thread could immediately acquire the lock and store its own thread state in the global variable). Conversely, when acquiring the lock and restoring the thread state, the lock must be acquired before storing the thread state pointer.

참고

Calling system I/O functions is the most common use case for releasing the GIL, but it can also be useful before calling long-running computations which don’t need access to Python objects, such as compression or cryptographic functions operating over memory buffers. For example, the standard zlib and hashlib modules release the GIL when compressing or hashing data.

Non-Python created threads

When threads are created using the dedicated Python APIs (such as the threading module), a thread state is automatically associated to them and the code showed above is therefore correct. However, when threads are created from C (for example by a third-party library with its own thread management), they don’t hold the GIL, nor is there a thread state structure for them.

If you need to call Python code from these threads (often this will be part of a callback API provided by the aforementioned third-party library), you must first register these threads with the interpreter by creating a thread state data structure, then acquiring the GIL, and finally storing their thread state pointer, before you can start using the Python/C API. When you are done, you should reset the thread state pointer, release the GIL, and finally free the thread state data structure.

The PyGILState_Ensure() and PyGILState_Release() functions do all of the above automatically. The typical idiom for calling into Python from a C thread is:

PyGILState_STATE gstate;
gstate = PyGILState_Ensure();

/* Perform Python actions here. */
result = CallSomeFunction();
/* evaluate result or handle exception */

/* Release the thread. No Python API allowed beyond this point. */
PyGILState_Release(gstate);

Note that the PyGILState_*() functions assume there is only one global interpreter (created automatically by Py_Initialize()). Python supports the creation of additional interpreters (using Py_NewInterpreter()), but mixing multiple interpreters and the PyGILState_*() API is unsupported.

Another important thing to note about threads is their behaviour in the face of the C fork() call. On most systems with fork(), after a process forks only the thread that issued the fork will exist. That also means any locks held by other threads will never be released. Python solves this for os.fork() by acquiring the locks it uses internally before the fork, and releasing them afterwards. In addition, it resets any Lock Objects in the child. When extending or embedding Python, there is no way to inform Python of additional (non-Python) locks that need to be acquired before or reset after a fork. OS facilities such as pthread_atfork() would need to be used to accomplish the same thing. Additionally, when extending or embedding Python, calling fork() directly rather than through os.fork() (and returning to or calling into Python) may result in a deadlock by one of Python’s internal locks being held by a thread that is defunct after the fork. PyOS_AfterFork_Child() tries to reset the necessary locks, but is not always able to.

High-level API

These are the most commonly used types and functions when writing C extension code, or when embedding the Python interpreter:

PyInterpreterState

This data structure represents the state shared by a number of cooperating threads. Threads belonging to the same interpreter share their module administration and a few other internal items. There are no public members in this structure.

Threads belonging to different interpreters initially share nothing, except process state like available memory, open file descriptors and such. The global interpreter lock is also shared by all threads, regardless of to which interpreter they belong.

PyThreadState

This data structure represents the state of a single thread. The only public data member is PyInterpreterState *interp, which points to this thread’s interpreter state.

void PyEval_InitThreads()

Initialize and acquire the global interpreter lock. It should be called in the main thread before creating a second thread or engaging in any other thread operations such as PyEval_ReleaseThread(tstate). It is not needed before calling PyEval_SaveThread() or PyEval_RestoreThread().

This is a no-op when called for a second time.

버전 3.7에서 변경: This function is now called by Py_Initialize(), so you don’t have to call it yourself anymore.

버전 3.2에서 변경: This function cannot be called before Py_Initialize() anymore.

int PyEval_ThreadsInitialized()

Returns a non-zero value if PyEval_InitThreads() has been called. This function can be called without holding the GIL, and therefore can be used to avoid calls to the locking API when running single-threaded.

버전 3.7에서 변경: The GIL is now initialized by Py_Initialize().

PyThreadState* PyEval_SaveThread()

Release the global interpreter lock (if it has been created and thread support is enabled) and reset the thread state to NULL, returning the previous thread state (which is not NULL). If the lock has been created, the current thread must have acquired it.

void PyEval_RestoreThread(PyThreadState *tstate)

Acquire the global interpreter lock (if it has been created and thread support is enabled) and set the thread state to tstate, which must not be NULL. If the lock has been created, the current thread must not have acquired it, otherwise deadlock ensues.

참고

Calling this function from a thread when the runtime is finalizing will terminate the thread, even if the thread was not created by Python. You can use _Py_IsFinalizing() or sys.is_finalizing() to check if the interpreter is in process of being finalized before calling this function to avoid unwanted termination.

PyThreadState* PyThreadState_Get()

Return the current thread state. The global interpreter lock must be held. When the current thread state is NULL, this issues a fatal error (so that the caller needn’t check for NULL).

PyThreadState* PyThreadState_Swap(PyThreadState *tstate)

Swap the current thread state with the thread state given by the argument tstate, which may be NULL. The global interpreter lock must be held and is not released.

void PyEval_ReInitThreads()

This function is called from PyOS_AfterFork_Child() to ensure that newly created child processes don’t hold locks referring to threads which are not running in the child process.

The following functions use thread-local storage, and are not compatible with sub-interpreters:

PyGILState_STATE PyGILState_Ensure()

Ensure that the current thread is ready to call the Python C API regardless of the current state of Python, or of the global interpreter lock. This may be called as many times as desired by a thread as long as each call is matched with a call to PyGILState_Release(). In general, other thread-related APIs may be used between PyGILState_Ensure() and PyGILState_Release() calls as long as the thread state is restored to its previous state before the Release(). For example, normal usage of the Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS macros is acceptable.

The return value is an opaque “handle” to the thread state when PyGILState_Ensure() was called, and must be passed to PyGILState_Release() to ensure Python is left in the same state. Even though recursive calls are allowed, these handles cannot be shared - each unique call to PyGILState_Ensure() must save the handle for its call to PyGILState_Release().

When the function returns, the current thread will hold the GIL and be able to call arbitrary Python code. Failure is a fatal error.

참고

Calling this function from a thread when the runtime is finalizing will terminate the thread, even if the thread was not created by Python. You can use _Py_IsFinalizing() or sys.is_finalizing() to check if the interpreter is in process of being finalized before calling this function to avoid unwanted termination.

void PyGILState_Release(PyGILState_STATE)

Release any resources previously acquired. After this call, Python’s state will be the same as it was prior to the corresponding PyGILState_Ensure() call (but generally this state will be unknown to the caller, hence the use of the GILState API).

Every call to PyGILState_Ensure() must be matched by a call to PyGILState_Release() on the same thread.

PyThreadState* PyGILState_GetThisThreadState()

Get the current thread state for this thread. May return NULL if no GILState API has been used on the current thread. Note that the main thread always has such a thread-state, even if no auto-thread-state call has been made on the main thread. This is mainly a helper/diagnostic function.

int PyGILState_Check()

Return 1 if the current thread is holding the GIL and 0 otherwise. This function can be called from any thread at any time. Only if it has had its Python thread state initialized and currently is holding the GIL will it return 1. This is mainly a helper/diagnostic function. It can be useful for example in callback contexts or memory allocation functions when knowing that the GIL is locked can allow the caller to perform sensitive actions or otherwise behave differently.

버전 3.4에 추가.

The following macros are normally used without a trailing semicolon; look for example usage in the Python source distribution.

Py_BEGIN_ALLOW_THREADS

This macro expands to { PyThreadState *_save; _save = PyEval_SaveThread();. Note that it contains an opening brace; it must be matched with a following Py_END_ALLOW_THREADS macro. See above for further discussion of this macro.

Py_END_ALLOW_THREADS

This macro expands to PyEval_RestoreThread(_save); }. Note that it contains a closing brace; it must be matched with an earlier Py_BEGIN_ALLOW_THREADS macro. See above for further discussion of this macro.

Py_BLOCK_THREADS

This macro expands to PyEval_RestoreThread(_save);: it is equivalent to Py_END_ALLOW_THREADS without the closing brace.

Py_UNBLOCK_THREADS

This macro expands to _save = PyEval_SaveThread();: it is equivalent to Py_BEGIN_ALLOW_THREADS without the opening brace and variable declaration.

Low-level API

All of the following functions must be called after Py_Initialize().

버전 3.7에서 변경: Py_Initialize() now initializes the GIL.

PyInterpreterState* PyInterpreterState_New()

Create a new interpreter state object. The global interpreter lock need not be held, but may be held if it is necessary to serialize calls to this function.

void PyInterpreterState_Clear(PyInterpreterState *interp)

Reset all information in an interpreter state object. The global interpreter lock must be held.

void PyInterpreterState_Delete(PyInterpreterState *interp)

Destroy an interpreter state object. The global interpreter lock need not be held. The interpreter state must have been reset with a previous call to PyInterpreterState_Clear().

PyThreadState* PyThreadState_New(PyInterpreterState *interp)

Create a new thread state object belonging to the given interpreter object. The global interpreter lock need not be held, but may be held if it is necessary to serialize calls to this function.

void PyThreadState_Clear(PyThreadState *tstate)

Reset all information in a thread state object. The global interpreter lock must be held.

void PyThreadState_Delete(PyThreadState *tstate)

Destroy a thread state object. The global interpreter lock need not be held. The thread state must have been reset with a previous call to PyThreadState_Clear().

PY_INT64_T PyInterpreterState_GetID(PyInterpreterState *interp)

Return the interpreter’s unique ID. If there was any error in doing so then -1 is returned and an error is set.

버전 3.7에 추가.

PyObject* PyThreadState_GetDict()

Return value: Borrowed reference.

Return a dictionary in which extensions can store thread-specific state information. Each extension should use a unique key to use to store state in the dictionary. It is okay to call this function when no current thread state is available. If this function returns NULL, no exception has been raised and the caller should assume no current thread state is available.

int PyThreadState_SetAsyncExc(unsigned long id, PyObject *exc)

Asynchronously raise an exception in a thread. The id argument is the thread id of the target thread; exc is the exception object to be raised. This function does not steal any references to exc. To prevent naive misuse, you must write your own C extension to call this. Must be called with the GIL held. Returns the number of thread states modified; this is normally one, but will be zero if the thread id isn’t found. If exc is NULL, the pending exception (if any) for the thread is cleared. This raises no exceptions.

버전 3.7에서 변경: The type of the id parameter changed from long to unsigned long.

void PyEval_AcquireThread(PyThreadState *tstate)

Acquire the global interpreter lock and set the current thread state to tstate, which should not be NULL. The lock must have been created earlier. If this thread already has the lock, deadlock ensues.

PyEval_RestoreThread() is a higher-level function which is always available (even when threads have not been initialized).

void PyEval_ReleaseThread(PyThreadState *tstate)

Reset the current thread state to NULL and release the global interpreter lock. The lock must have been created earlier and must be held by the current thread. The tstate argument, which must not be NULL, is only used to check that it represents the current thread state — if it isn’t, a fatal error is reported.

PyEval_SaveThread() is a higher-level function which is always available (even when threads have not been initialized).

void PyEval_AcquireLock()

Acquire the global interpreter lock. The lock must have been created earlier. If this thread already has the lock, a deadlock ensues.

버전 3.2부터 폐지: This function does not update the current thread state. Please use PyEval_RestoreThread() or PyEval_AcquireThread() instead.

void PyEval_ReleaseLock()

Release the global interpreter lock. The lock must have been created earlier.

버전 3.2부터 폐지: This function does not update the current thread state. Please use PyEval_SaveThread() or PyEval_ReleaseThread() instead.

Sub-interpreter support

While in most uses, you will only embed a single Python interpreter, there are cases where you need to create several independent interpreters in the same process and perhaps even in the same thread. Sub-interpreters allow you to do that. You can switch between sub-interpreters using the PyThreadState_Swap() function. You can create and destroy them using the following functions:

PyThreadState* Py_NewInterpreter()

Create a new sub-interpreter. This is an (almost) totally separate environment for the execution of Python code. In particular, the new interpreter has separate, independent versions of all imported modules, including the fundamental modules builtins, __main__ and sys. The table of loaded modules (sys.modules) and the module search path (sys.path) are also separate. The new environment has no sys.argv variable. It has new standard I/O stream file objects sys.stdin, sys.stdout and sys.stderr (however these refer to the same underlying file descriptors).

The return value points to the first thread state created in the new sub-interpreter. This thread state is made in the current thread state. Note that no actual thread is created; see the discussion of thread states below. If creation of the new interpreter is unsuccessful, NULL is returned; no exception is set since the exception state is stored in the current thread state and there may not be a current thread state. (Like all other Python/C API functions, the global interpreter lock must be held before calling this function and is still held when it returns; however, unlike most other Python/C API functions, there needn’t be a current thread state on entry.)

Extension modules are shared between (sub-)interpreters as follows: the first time a particular extension is imported, it is initialized normally, and a (shallow) copy of its module’s dictionary is squirreled away. When the same extension is imported by another (sub-)interpreter, a new module is initialized and filled with the contents of this copy; the extension’s init function is not called. Note that this is different from what happens when an extension is imported after the interpreter has been completely re-initialized by calling Py_FinalizeEx() and Py_Initialize(); in that case, the extension’s initmodule function is called again.

void Py_EndInterpreter(PyThreadState *tstate)

Destroy the (sub-)interpreter represented by the given thread state. The given thread state must be the current thread state. See the discussion of thread states below. When the call returns, the current thread state is NULL. All thread states associated with this interpreter are destroyed. (The global interpreter lock must be held before calling this function and is still held when it returns.) Py_FinalizeEx() will destroy all sub-interpreters that haven’t been explicitly destroyed at that point.

Bugs and caveats

Because sub-interpreters (and the main interpreter) are part of the same process, the insulation between them isn’t perfect — for example, using low-level file operations like os.close() they can (accidentally or maliciously) affect each other’s open files. Because of the way extensions are shared between (sub-)interpreters, some extensions may not work properly; this is especially likely when the extension makes use of (static) global variables, or when the extension manipulates its module’s dictionary after its initialization. It is possible to insert objects created in one sub-interpreter into a namespace of another sub-interpreter; this should be done with great care to avoid sharing user-defined functions, methods, instances or classes between sub-interpreters, since import operations executed by such objects may affect the wrong (sub-)interpreter’s dictionary of loaded modules.

Also note that combining this functionality with PyGILState_*() APIs is delicate, because these APIs assume a bijection between Python thread states and OS-level threads, an assumption broken by the presence of sub-interpreters. It is highly recommended that you don’t switch sub-interpreters between a pair of matching PyGILState_Ensure() and PyGILState_Release() calls. Furthermore, extensions (such as ctypes) using these APIs to allow calling of Python code from non-Python created threads will probably be broken when using sub-interpreters.

Asynchronous Notifications

A mechanism is provided to make asynchronous notifications to the main interpreter thread. These notifications take the form of a function pointer and a void pointer argument.

int Py_AddPendingCall(int (*func)(void *), void *arg)

Schedule a function to be called from the main interpreter thread. On success, 0 is returned and func is queued for being called in the main thread. On failure, -1 is returned without setting any exception.

When successfully queued, func will be eventually called from the main interpreter thread with the argument arg. It will be called asynchronously with respect to normally running Python code, but with both these conditions met:

on a bytecode boundary;

with the main thread holding the global interpreter lock (func can therefore use the full C API).

func must return 0 on success, or -1 on failure with an exception set. func won’t be interrupted to perform another asynchronous notification recursively, but it can still be interrupted to switch threads if the global interpreter lock is released.

This function doesn’t need a current thread state to run, and it doesn’t need the global interpreter lock.

경고

This is a low-level function, only useful for very special cases. There is no guarantee that func will be called as quick as possible. If the main thread is busy executing a system call, func won’t be called before the system call returns. This function is generally not suitable for calling Python code from arbitrary C threads. Instead, use the PyGILState API.

버전 3.1에 추가.

Profiling and Tracing

The Python interpreter provides some low-level support for attaching profiling and execution tracing facilities. These are used for profiling, debugging, and coverage analysis tools.

This C interface allows the profiling or tracing code to avoid the overhead of calling through Python-level callable objects, making a direct C function call instead. The essential attributes of the facility have not changed; the interface allows trace functions to be installed per-thread, and the basic events reported to the trace function are the same as had been reported to the Python-level trace functions in previous versions.

int (*Py_tracefunc)(PyObject *obj, PyFrameObject *frame, int what, PyObject *arg)

The type of the trace function registered using PyEval_SetProfile() and PyEval_SetTrace(). The first parameter is the object passed to the registration function as obj, frame is the frame object to which the event pertains, what is one of the constants PyTrace_CALL, PyTrace_EXCEPTION, PyTrace_LINE, PyTrace_RETURN, PyTrace_C_CALL, PyTrace_C_EXCEPTION, PyTrace_C_RETURN, or PyTrace_OPCODE, and arg depends on the value of what:

Value of what

Meaning of arg

PyTrace_CALL

Always Py_None.

PyTrace_EXCEPTION

Exception information as returned by sys.exc_info().

PyTrace_LINE

Always Py_None.

PyTrace_RETURN

Value being returned to the caller, or NULL if caused by an exception.

PyTrace_C_CALL

Function object being called.

PyTrace_C_EXCEPTION

Function object being called.

PyTrace_C_RETURN

Function object being called.

PyTrace_OPCODE

Always Py_None.

int PyTrace_CALL

The value of the what parameter to a Py_tracefunc function when a new call to a function or method is being reported, or a new entry into a generator. Note that the creation of the iterator for a generator function is not reported as there is no control transfer to the Python bytecode in the corresponding frame.

int PyTrace_EXCEPTION

The value of the what parameter to a Py_tracefunc function when an exception has been raised. The callback function is called with this value for what when after any bytecode is processed after which the exception becomes set within the frame being executed. The effect of this is that as exception propagation causes the Python stack to unwind, the callback is called upon return to each frame as the exception propagates. Only trace functions receives these events; they are not needed by the profiler.

int PyTrace_LINE

The value passed as the what parameter to a Py_tracefunc function (but not a profiling function) when a line-number event is being reported. It may be disabled for a frame by setting f_trace_lines to 0 on that frame.

int PyTrace_RETURN

The value for the what parameter to Py_tracefunc functions when a call is about to return.

int PyTrace_C_CALL

The value for the what parameter to Py_tracefunc functions when a C function is about to be called.

int PyTrace_C_EXCEPTION

The value for the what parameter to Py_tracefunc functions when a C function has raised an exception.

int PyTrace_C_RETURN

The value for the what parameter to Py_tracefunc functions when a C function has returned.

int PyTrace_OPCODE

The value for the what parameter to Py_tracefunc functions (but not profiling functions) when a new opcode is about to be executed. This event is not emitted by default: it must be explicitly requested by setting f_trace_opcodes to 1 on the frame.

void PyEval_SetProfile(Py_tracefunc func, PyObject *obj)

Set the profiler function to func. The obj parameter is passed to the function as its first parameter, and may be any Python object, or NULL. If the profile function needs to maintain state, using a different value for obj for each thread provides a convenient and thread-safe place to store it. The profile function is called for all monitored events except PyTrace_LINE PyTrace_OPCODE and PyTrace_EXCEPTION.

void PyEval_SetTrace(Py_tracefunc func, PyObject *obj)

Set the tracing function to func. This is similar to PyEval_SetProfile(), except the tracing function does receive line-number events and per-opcode events, but does not receive any event related to C function objects being called. Any trace function registered using PyEval_SetTrace() will not receive PyTrace_C_CALL, PyTrace_C_EXCEPTION or PyTrace_C_RETURN as a value for the what parameter.

Advanced Debugger Support

These functions are only intended to be used by advanced debugging tools.

PyInterpreterState* PyInterpreterState_Head()

Return the interpreter state object at the head of the list of all such objects.

PyInterpreterState* PyInterpreterState_Main()

Return the main interpreter state object.

PyInterpreterState* PyInterpreterState_Next(PyInterpreterState *interp)

Return the next interpreter state object after interp from the list of all such objects.

PyThreadState * PyInterpreterState_ThreadHead(PyInterpreterState *interp)

Return the pointer to the first PyThreadState object in the list of threads associated with the interpreter interp.

PyThreadState* PyThreadState_Next(PyThreadState *tstate)

Return the next thread state object after tstate from the list of all such objects belonging to the same PyInterpreterState object.

Thread Local Storage Support

The Python interpreter provides low-level support for thread-local storage (TLS) which wraps the underlying native TLS implementation to support the Python-level thread local storage API (threading.local). The CPython C level APIs are similar to those offered by pthreads and Windows: use a thread key and functions to associate a void* value per thread.

The GIL does not need to be held when calling these functions; they supply their own locking.

Note that Python.h does not include the declaration of the TLS APIs, you need to include pythread.h to use thread-local storage.

참고

None of these API functions handle memory management on behalf of the void* values. You need to allocate and deallocate them yourself. If the void* values happen to be PyObject*, these functions don’t do refcount operations on them either.

Thread Specific Storage (TSS) API

TSS API is introduced to supersede the use of the existing TLS API within the CPython interpreter. This API uses a new type Py_tss_t instead of int to represent thread keys.

버전 3.7에 추가.

더 보기

“A New C-API for Thread-Local Storage in CPython” (PEP 539 [https://www.python.org/dev/peps/pep-0539])

Py_tss_t

This data structure represents the state of a thread key, the definition of which may depend on the underlying TLS implementation, and it has an internal field representing the key’s initialization state. There are no public members in this structure.

When Py_LIMITED_API is not defined, static allocation of this type by Py_tss_NEEDS_INIT is allowed.

Py_tss_NEEDS_INIT

This macro expands to the initializer for Py_tss_t variables. Note that this macro won’t be defined with Py_LIMITED_API.

Dynamic Allocation

Dynamic allocation of the Py_tss_t, required in extension modules built with Py_LIMITED_API, where static allocation of this type is not possible due to its implementation being opaque at build time.

Py_tss_t* PyThread_tss_alloc()

Return a value which is the same state as a value initialized with Py_tss_NEEDS_INIT, or NULL in the case of dynamic allocation failure.

void PyThread_tss_free(Py_tss_t *key)

Free the given key allocated by PyThread_tss_alloc(), after first calling PyThread_tss_delete() to ensure any associated thread locals have been unassigned. This is a no-op if the key argument is NULL.

참고

A freed key becomes a dangling pointer, you should reset the key to NULL.

Methods

The parameter key of these functions must not be NULL. Moreover, the behaviors of PyThread_tss_set() and PyThread_tss_get() are undefined if the given Py_tss_t has not been initialized by PyThread_tss_create().

int PyThread_tss_is_created(Py_tss_t *key)

Return a non-zero value if the given Py_tss_t has been initialized by PyThread_tss_create().

int PyThread_tss_create(Py_tss_t *key)

Return a zero value on successful initialization of a TSS key. The behavior is undefined if the value pointed to by the key argument is not initialized by Py_tss_NEEDS_INIT. This function can be called repeatedly on the same key – calling it on an already initialized key is a no-op and immediately returns success.

void PyThread_tss_delete(Py_tss_t *key)

Destroy a TSS key to forget the values associated with the key across all threads, and change the key’s initialization state to uninitialized. A destroyed key is able to be initialized again by PyThread_tss_create(). This function can be called repeatedly on the same key – calling it on an already destroyed key is a no-op.

int PyThread_tss_set(Py_tss_t *key, void *value)

Return a zero value to indicate successfully associating a void* value with a TSS key in the current thread. Each thread has a distinct mapping of the key to a void* value.

void* PyThread_tss_get(Py_tss_t *key)

Return the void* value associated with a TSS key in the current thread. This returns NULL if no value is associated with the key in the current thread.

Thread Local Storage (TLS) API

버전 3.7부터 폐지: This API is superseded by Thread Specific Storage (TSS) API.

참고

This version of the API does not support platforms where the native TLS key is defined in a way that cannot be safely cast to int. On such platforms, PyThread_create_key() will return immediately with a failure status, and the other TLS functions will all be no-ops on such platforms.

Due to the compatibility problem noted above, this version of the API should not be used in new code.

int PyThread_create_key()

void PyThread_delete_key(int key)

int PyThread_set_key_value(int key, void *value)

void* PyThread_get_key_value(int key)

void PyThread_delete_key_value(int key)

void PyThread_ReInitTLS()

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

|

Memory Management

Overview

Memory management in Python involves a private heap containing all Python objects and data structures. The management of this private heap is ensured internally by the Python memory manager. The Python memory manager has different components which deal with various dynamic storage management aspects, like sharing, segmentation, preallocation or caching.

At the lowest level, a raw memory allocator ensures that there is enough room in the private heap for storing all Python-related data by interacting with the memory manager of the operating system. On top of the raw memory allocator, several object-specific allocators operate on the same heap and implement distinct memory management policies adapted to the peculiarities of every object type. For example, integer objects are managed differently within the heap than strings, tuples or dictionaries because integers imply different storage requirements and speed/space tradeoffs. The Python memory manager thus delegates some of the work to the object-specific allocators, but ensures that the latter operate within the bounds of the private heap.

It is important to understand that the management of the Python heap is performed by the interpreter itself and that the user has no control over it, even if they regularly manipulate object pointers to memory blocks inside that heap. The allocation of heap space for Python objects and other internal buffers is performed on demand by the Python memory manager through the Python/C API functions listed in this document.

To avoid memory corruption, extension writers should never try to operate on Python objects with the functions exported by the C library: malloc(), calloc(), realloc() and free(). This will result in mixed calls between the C allocator and the Python memory manager with fatal consequences, because they implement different algorithms and operate on different heaps. However, one may safely allocate and release memory blocks with the C library allocator for individual purposes, as shown in the following example:

PyObject *res;
char *buf = (char *) malloc(BUFSIZ); /* for I/O */

if (buf == NULL)
    return PyErr_NoMemory();
...Do some I/O operation involving buf...
res = PyBytes_FromString(buf);
free(buf); /* malloc'ed */
return res;

In this example, the memory request for the I/O buffer is handled by the C library allocator. The Python memory manager is involved only in the allocation of the bytes object returned as a result.

In most situations, however, it is recommended to allocate memory from the Python heap specifically because the latter is under control of the Python memory manager. For example, this is required when the interpreter is extended with new object types written in C. Another reason for using the Python heap is the desire to inform the Python memory manager about the memory needs of the extension module. Even when the requested memory is used exclusively for internal, highly-specific purposes, delegating all memory requests to the Python memory manager causes the interpreter to have a more accurate image of its memory footprint as a whole. Consequently, under certain circumstances, the Python memory manager may or may not trigger appropriate actions, like garbage collection, memory compaction or other preventive procedures. Note that by using the C library allocator as shown in the previous example, the allocated memory for the I/O buffer escapes completely the Python memory manager.

더 보기

The PYTHONMALLOC environment variable can be used to configure the memory allocators used by Python.

The PYTHONMALLOCSTATS environment variable can be used to print statistics of the pymalloc memory allocator every time a new pymalloc object arena is created, and on shutdown.

Raw Memory Interface

The following function sets are wrappers to the system allocator. These functions are thread-safe, the GIL does not need to be held.

The default raw memory allocator uses the following functions: malloc(), calloc(), realloc() and free(); call malloc(1) (or calloc(1, 1)) when requesting zero bytes.

버전 3.4에 추가.

void* PyMem_RawMalloc(size_t n)

Allocates n bytes and returns a pointer of type void* to the allocated memory, or NULL if the request fails.

Requesting zero bytes returns a distinct non-NULL pointer if possible, as if PyMem_RawMalloc(1) had been called instead. The memory will not have been initialized in any way.

void* PyMem_RawCalloc(size_t nelem, size_t elsize)

Allocates nelem elements each whose size in bytes is elsize and returns a pointer of type void* to the allocated memory, or NULL if the request fails. The memory is initialized to zeros.

Requesting zero elements or elements of size zero bytes returns a distinct non-NULL pointer if possible, as if PyMem_RawCalloc(1, 1) had been called instead.

버전 3.5에 추가.

void* PyMem_RawRealloc(void *p, size_t n)

Resizes the memory block pointed to by p to n bytes. The contents will be unchanged to the minimum of the old and the new sizes.

If p is NULL, the call is equivalent to PyMem_RawMalloc(n); else if n is equal to zero, the memory block is resized but is not freed, and the returned pointer is non-NULL.

Unless p is NULL, it must have been returned by a previous call to PyMem_RawMalloc(), PyMem_RawRealloc() or PyMem_RawCalloc().

If the request fails, PyMem_RawRealloc() returns NULL and p remains a valid pointer to the previous memory area.

void PyMem_RawFree(void *p)

Frees the memory block pointed to by p, which must have been returned by a previous call to PyMem_RawMalloc(), PyMem_RawRealloc() or PyMem_RawCalloc(). Otherwise, or if PyMem_RawFree(p) has been called before, undefined behavior occurs.

If p is NULL, no operation is performed.

Memory Interface

The following function sets, modeled after the ANSI C standard, but specifying behavior when requesting zero bytes, are available for allocating and releasing memory from the Python heap.

The default memory allocator uses the pymalloc memory allocator.

경고

The GIL must be held when using these functions.

버전 3.6에서 변경: The default allocator is now pymalloc instead of system malloc().

void* PyMem_Malloc(size_t n)

Allocates n bytes and returns a pointer of type void* to the allocated memory, or NULL if the request fails.

Requesting zero bytes returns a distinct non-NULL pointer if possible, as if PyMem_Malloc(1) had been called instead. The memory will not have been initialized in any way.

void* PyMem_Calloc(size_t nelem, size_t elsize)

Allocates nelem elements each whose size in bytes is elsize and returns a pointer of type void* to the allocated memory, or NULL if the request fails. The memory is initialized to zeros.

Requesting zero elements or elements of size zero bytes returns a distinct non-NULL pointer if possible, as if PyMem_Calloc(1, 1) had been called instead.

버전 3.5에 추가.

void* PyMem_Realloc(void *p, size_t n)

Resizes the memory block pointed to by p to n bytes. The contents will be unchanged to the minimum of the old and the new sizes.

If p is NULL, the call is equivalent to PyMem_Malloc(n); else if n is equal to zero, the memory block is resized but is not freed, and the returned pointer is non-NULL.

Unless p is NULL, it must have been returned by a previous call to PyMem_Malloc(), PyMem_Realloc() or PyMem_Calloc().

If the request fails, PyMem_Realloc() returns NULL and p remains a valid pointer to the previous memory area.

void PyMem_Free(void *p)

Frees the memory block pointed to by p, which must have been returned by a previous call to PyMem_Malloc(), PyMem_Realloc() or PyMem_Calloc(). Otherwise, or if PyMem_Free(p) has been called before, undefined behavior occurs.

If p is NULL, no operation is performed.

The following type-oriented macros are provided for convenience. Note that TYPE refers to any C type.

TYPE* PyMem_New(TYPE, size_t n)

Same as PyMem_Malloc(), but allocates (n * sizeof(TYPE)) bytes of memory. Returns a pointer cast to TYPE*. The memory will not have been initialized in any way.

TYPE* PyMem_Resize(void *p, TYPE, size_t n)

Same as PyMem_Realloc(), but the memory block is resized to (n * sizeof(TYPE)) bytes. Returns a pointer cast to TYPE*. On return, p will be a pointer to the new memory area, or NULL in the event of failure.

This is a C preprocessor macro; p is always reassigned. Save the original value of p to avoid losing memory when handling errors.

void PyMem_Del(void *p)

Same as PyMem_Free().

In addition, the following macro sets are provided for calling the Python memory allocator directly, without involving the C API functions listed above. However, note that their use does not preserve binary compatibility across Python versions and is therefore deprecated in extension modules.

PyMem_MALLOC(size)

PyMem_NEW(type, size)

PyMem_REALLOC(ptr, size)

PyMem_RESIZE(ptr, type, size)

PyMem_FREE(ptr)

PyMem_DEL(ptr)

Object allocators

The following function sets, modeled after the ANSI C standard, but specifying behavior when requesting zero bytes, are available for allocating and releasing memory from the Python heap.

The default object allocator uses the pymalloc memory allocator.

경고

The GIL must be held when using these functions.

void* PyObject_Malloc(size_t n)

Allocates n bytes and returns a pointer of type void* to the allocated memory, or NULL if the request fails.

Requesting zero bytes returns a distinct non-NULL pointer if possible, as if PyObject_Malloc(1) had been called instead. The memory will not have been initialized in any way.

void* PyObject_Calloc(size_t nelem, size_t elsize)

Allocates nelem elements each whose size in bytes is elsize and returns a pointer of type void* to the allocated memory, or NULL if the request fails. The memory is initialized to zeros.

Requesting zero elements or elements of size zero bytes returns a distinct non-NULL pointer if possible, as if PyObject_Calloc(1, 1) had been called instead.

버전 3.5에 추가.

void* PyObject_Realloc(void *p, size_t n)

Resizes the memory block pointed to by p to n bytes. The contents will be unchanged to the minimum of the old and the new sizes.

If p is NULL, the call is equivalent to PyObject_Malloc(n); else if n is equal to zero, the memory block is resized but is not freed, and the returned pointer is non-NULL.

Unless p is NULL, it must have been returned by a previous call to PyObject_Malloc(), PyObject_Realloc() or PyObject_Calloc().

If the request fails, PyObject_Realloc() returns NULL and p remains a valid pointer to the previous memory area.

void PyObject_Free(void *p)

Frees the memory block pointed to by p, which must have been returned by a previous call to PyObject_Malloc(), PyObject_Realloc() or PyObject_Calloc(). Otherwise, or if PyObject_Free(p) has been called before, undefined behavior occurs.

If p is NULL, no operation is performed.

Default Memory Allocators

Default memory allocators:

Configuration

Name

PyMem_RawMalloc

PyMem_Malloc

PyObject_Malloc

Release build

"pymalloc"

malloc

pymalloc

pymalloc

Debug build

"pymalloc_debug"

malloc + debug

pymalloc + debug

pymalloc + debug

Release build, without pymalloc

"malloc"

malloc

malloc

malloc

Debug build, without pymalloc

"malloc_debug"

malloc + debug

malloc + debug

malloc + debug

Legend:

Name: value for PYTHONMALLOC environment variable

malloc: system allocators from the standard C library, C functions: malloc(), calloc(), realloc() and free()

pymalloc: pymalloc memory allocator

“+ debug”: with debug hooks installed by PyMem_SetupDebugHooks()

Customize Memory Allocators

버전 3.4에 추가.

PyMemAllocatorEx

Structure used to describe a memory block allocator. The structure has four fields:

Field

Meaning

void *ctx

user context passed as first argument

void* malloc(void *ctx, size_t size)

allocate a memory block

void* calloc(void *ctx, size_t nelem, size_t elsize)

allocate a memory block initialized with zeros

void* realloc(void *ctx, void *ptr, size_t new_size)

allocate or resize a memory block

void free(void *ctx, void *ptr)

free a memory block

버전 3.5에서 변경: The PyMemAllocator structure was renamed to PyMemAllocatorEx and a new calloc field was added.

PyMemAllocatorDomain

Enum used to identify an allocator domain. Domains:

PYMEM_DOMAIN_RAW

Functions:

PyMem_RawMalloc()

PyMem_RawRealloc()

PyMem_RawCalloc()

PyMem_RawFree()

PYMEM_DOMAIN_MEM

Functions:

PyMem_Malloc(),

PyMem_Realloc()

PyMem_Calloc()

PyMem_Free()

PYMEM_DOMAIN_OBJ

Functions:

PyObject_Malloc()

PyObject_Realloc()

PyObject_Calloc()

PyObject_Free()

void PyMem_GetAllocator(PyMemAllocatorDomain domain, PyMemAllocatorEx *allocator)

Get the memory block allocator of the specified domain.

void PyMem_SetAllocator(PyMemAllocatorDomain domain, PyMemAllocatorEx *allocator)

Set the memory block allocator of the specified domain.

The new allocator must return a distinct non-NULL pointer when requesting zero bytes.

For the PYMEM_DOMAIN_RAW domain, the allocator must be thread-safe: the GIL is not held when the allocator is called.

If the new allocator is not a hook (does not call the previous allocator), the PyMem_SetupDebugHooks() function must be called to reinstall the debug hooks on top on the new allocator.

void PyMem_SetupDebugHooks(void)

Setup hooks to detect bugs in the Python memory allocator functions.

Newly allocated memory is filled with the byte 0xCD (CLEANBYTE), freed memory is filled with the byte 0xDD (DEADBYTE). Memory blocks are surrounded by “forbidden bytes” (FORBIDDENBYTE: byte 0xFD).

Runtime checks:

Detect API violations, ex: PyObject_Free() called on a buffer allocated by PyMem_Malloc()

Detect write before the start of the buffer (buffer underflow)

Detect write after the end of the buffer (buffer overflow)

Check that the GIL is held when allocator functions of PYMEM_DOMAIN_OBJ (ex: PyObject_Malloc()) and PYMEM_DOMAIN_MEM (ex: PyMem_Malloc()) domains are called

On error, the debug hooks use the tracemalloc module to get the traceback where a memory block was allocated. The traceback is only displayed if tracemalloc is tracing Python memory allocations and the memory block was traced.

These hooks are installed by default if Python is compiled in debug mode. The PYTHONMALLOC environment variable can be used to install debug hooks on a Python compiled in release mode.

버전 3.6에서 변경: This function now also works on Python compiled in release mode. On error, the debug hooks now use tracemalloc to get the traceback where a memory block was allocated. The debug hooks now also check if the GIL is held when functions of PYMEM_DOMAIN_OBJ and PYMEM_DOMAIN_MEM domains are called.

버전 3.7.3에서 변경: Byte patterns 0xCB (CLEANBYTE), 0xDB (DEADBYTE) and 0xFB (FORBIDDENBYTE) have been replaced with 0xCD, 0xDD and 0xFD to use the same values than Windows CRT debug malloc() and free().

The pymalloc allocator

Python has a pymalloc allocator optimized for small objects (smaller or equal to 512 bytes) with a short lifetime. It uses memory mappings called “arenas” with a fixed size of 256 KiB. It falls back to PyMem_RawMalloc() and PyMem_RawRealloc() for allocations larger than 512 bytes.

pymalloc is the default allocator of the PYMEM_DOMAIN_MEM (ex: PyMem_Malloc()) and PYMEM_DOMAIN_OBJ (ex: PyObject_Malloc()) domains.

The arena allocator uses the following functions:

VirtualAlloc() and VirtualFree() on Windows,

mmap() and munmap() if available,

malloc() and free() otherwise.

Customize pymalloc Arena Allocator

버전 3.4에 추가.

PyObjectArenaAllocator

Structure used to describe an arena allocator. The structure has three fields:

Field

Meaning

void *ctx

user context passed as first argument

void* alloc(void *ctx, size_t size)

allocate an arena of size bytes

void free(void *ctx, size_t size, void *ptr)

free an arena

PyObject_GetArenaAllocator(PyObjectArenaAllocator *allocator)

Get the arena allocator.

PyObject_SetArenaAllocator(PyObjectArenaAllocator *allocator)

Set the arena allocator.

tracemalloc C API

버전 3.7에 추가.

int PyTraceMalloc_Track(unsigned int domain, uintptr_t ptr, size_t size)

Track an allocated memory block in the tracemalloc module.

Return 0 on success, return -1 on error (failed to allocate memory to store the trace). Return -2 if tracemalloc is disabled.

If memory block is already tracked, update the existing trace.

int PyTraceMalloc_Untrack(unsigned int domain, uintptr_t ptr)

Untrack an allocated memory block in the tracemalloc module. Do nothing if the block was not tracked.

Return -2 if tracemalloc is disabled, otherwise return 0.

Examples

Here is the example from section Overview, rewritten so that the I/O buffer is allocated from the Python heap by using the first function set:

PyObject *res;
char *buf = (char *) PyMem_Malloc(BUFSIZ); /* for I/O */

if (buf == NULL)
    return PyErr_NoMemory();
/* ...Do some I/O operation involving buf... */
res = PyBytes_FromString(buf);
PyMem_Free(buf); /* allocated with PyMem_Malloc */
return res;

The same code using the type-oriented function set:

PyObject *res;
char *buf = PyMem_New(char, BUFSIZ); /* for I/O */

if (buf == NULL)
    return PyErr_NoMemory();
/* ...Do some I/O operation involving buf... */
res = PyBytes_FromString(buf);
PyMem_Del(buf); /* allocated with PyMem_New */
return res;

Note that in the two examples above, the buffer is always manipulated via functions belonging to the same set. Indeed, it is required to use the same memory API family for a given memory block, so that the risk of mixing different allocators is reduced to a minimum. The following code sequence contains two errors, one of which is labeled as fatal because it mixes two different allocators operating on different heaps.

char *buf1 = PyMem_New(char, BUFSIZ);
char *buf2 = (char *) malloc(BUFSIZ);
char *buf3 = (char *) PyMem_Malloc(BUFSIZ);
...
PyMem_Del(buf3);  /* Wrong -- should be PyMem_Free() */
free(buf2);       /* Right -- allocated via malloc() */
free(buf1);       /* Fatal -- should be PyMem_Del()  */

In addition to the functions aimed at handling raw memory blocks from the Python heap, objects in Python are allocated and released with PyObject_New(), PyObject_NewVar() and PyObject_Del().

These will be explained in the next chapter on defining and implementing new object types in C.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

|

객체 구현 지원

이 장에서는 새 객체 형을 정의할 때 사용되는 함수, 형 및 매크로에 관해 설명합니다.

힙에 객체 할당하기

Common Object Structures

Type Objects

Number Object Structures

Mapping Object Structures

Sequence Object Structures

Buffer Object Structures

Async Object Structures

순환 가비지 수집 지원

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

객체 구현 지원 »

|

힙에 객체 할당하기

PyObject* _PyObject_New(PyTypeObject *type)

Return value: New reference.

PyVarObject* _PyObject_NewVar(PyTypeObject *type, Py_ssize_t size)

Return value: New reference.

PyObject* PyObject_Init(PyObject *op, PyTypeObject *type)

Return value: Borrowed reference.

새로 할당된 객체 op를 형과 초기 참조로 초기화합니다. 초기화된 객체를 반환합니다. type이 객체가 순환 가비지 감지기에 참여함을 나타내면, 감지기의 감시되는 객체 집합에 추가됩니다. 객체의 다른 필드는 영향을 받지 않습니다.

PyVarObject* PyObject_InitVar(PyVarObject *op, PyTypeObject *type, Py_ssize_t size)

Return value: Borrowed reference.

이것은 PyObject_Init()가 수행하는 모든 작업을 수행하고, 가변 크기 객체의 길이 정보도 초기화합니다.

TYPE* PyObject_New(TYPE, PyTypeObject *type)

Return value: New reference.

C 구조체 형 TYPE과 파이썬 형 객체 type을 사용하여 새로운 파이썬 객체를 할당합니다. 파이썬 객체 헤더로 정의되지 않은 필드는 초기화되지 않습니다; 객체의 참조 횟수는 1이 됩니다. 메모리 할당의 크기는 형 객체의 tp_basicsize 필드에서 결정됩니다.

TYPE* PyObject_NewVar(TYPE, PyTypeObject *type, Py_ssize_t size)

Return value: New reference.

C 구조체 형 TYPE과 파이썬 타입 형 type을 사용하여 새로운 파이썬 객체를 할당합니다. 파이썬 객체 헤더로 정의되지 않은 필드는 초기화되지 않습니다. 할당된 메모리는 TYPE 구조체에 더해 type의 tp_itemsize 필드에 의해 주어진 크기의 size 필드를 허용합니다. 이는 튜플과 같은 객체를 구현할 때 유용합니다. 튜플은 만들 때 크기를 결정할 수 있습니다. 같은 할당에 필드 배열을 포함 시키면, 할당 횟수가 줄어들어, 메모리 관리 효율성이 향상됩니다.

void PyObject_Del(void *op)

PyObject_New() 나 PyObject_NewVar()를 사용한 객체에 할당된 메모리를 해제합니다. 이것은 일반적으로 객체의 형에 지정된 tp_dealloc 처리기에서 호출됩니다. 메모리가 더는 유효한 파이썬 객체가 아니므로, 이 호출 후에는 객체의 필드에 액세스해서는 안 됩니다.

PyObject _Py_NoneStruct

파이썬에서 None으로 노출되는 객체. 이 객체에 대한 포인터로 평가되는 Py_None 매크로를 사용해서 액세스해야 합니다.

더 보기

PyModule_Create()

확장 모듈을 할당하고 만듭니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

객체 구현 지원 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

객체 구현 지원 »

|

Common Object Structures

There are a large number of structures which are used in the definition of object types for Python. This section describes these structures and how they are used.

All Python objects ultimately share a small number of fields at the beginning of the object’s representation in memory. These are represented by the PyObject and PyVarObject types, which are defined, in turn, by the expansions of some macros also used, whether directly or indirectly, in the definition of all other Python objects.

PyObject

All object types are extensions of this type. This is a type which contains the information Python needs to treat a pointer to an object as an object. In a normal “release” build, it contains only the object’s reference count and a pointer to the corresponding type object. Nothing is actually declared to be a PyObject, but every pointer to a Python object can be cast to a PyObject*. Access to the members must be done by using the macros Py_REFCNT and Py_TYPE.

PyVarObject

This is an extension of PyObject that adds the ob_size field. This is only used for objects that have some notion of length. This type does not often appear in the Python/C API. Access to the members must be done by using the macros Py_REFCNT, Py_TYPE, and Py_SIZE.

PyObject_HEAD

This is a macro used when declaring new types which represent objects without a varying length. The PyObject_HEAD macro expands to:

PyObject ob_base;

See documentation of PyObject above.

PyObject_VAR_HEAD

This is a macro used when declaring new types which represent objects with a length that varies from instance to instance. The PyObject_VAR_HEAD macro expands to:

PyVarObject ob_base;

See documentation of PyVarObject above.

Py_TYPE(o)

This macro is used to access the ob_type member of a Python object. It expands to:

(((PyObject*)(o))->ob_type)

Py_REFCNT(o)

This macro is used to access the ob_refcnt member of a Python object. It expands to:

(((PyObject*)(o))->ob_refcnt)

Py_SIZE(o)

This macro is used to access the ob_size member of a Python object. It expands to:

(((PyVarObject*)(o))->ob_size)

PyObject_HEAD_INIT(type)

This is a macro which expands to initialization values for a new PyObject type. This macro expands to:

_PyObject_EXTRA_INIT
1, type,

PyVarObject_HEAD_INIT(type, size)

This is a macro which expands to initialization values for a new PyVarObject type, including the ob_size field. This macro expands to:

_PyObject_EXTRA_INIT
1, type, size,

PyCFunction

Type of the functions used to implement most Python callables in C. Functions of this type take two PyObject* parameters and return one such value. If the return value is NULL, an exception shall have been set. If not NULL, the return value is interpreted as the return value of the function as exposed in Python. The function must return a new reference.

PyCFunctionWithKeywords

Type of the functions used to implement Python callables in C with signature METH_VARARGS | METH_KEYWORDS.

_PyCFunctionFast

Type of the functions used to implement Python callables in C with signature METH_FASTCALL.

_PyCFunctionFastWithKeywords

Type of the functions used to implement Python callables in C with signature METH_FASTCALL | METH_KEYWORDS.

PyMethodDef

Structure used to describe a method of an extension type. This structure has four fields:

Field

C Type

Meaning

ml_name

const char *

name of the method

ml_meth

PyCFunction

pointer to the C implementation

ml_flags

int

flag bits indicating how the call should be constructed

ml_doc

const char *

points to the contents of the docstring

The ml_meth is a C function pointer. The functions may be of different types, but they always return PyObject*. If the function is not of the PyCFunction, the compiler will require a cast in the method table. Even though PyCFunction defines the first parameter as PyObject*, it is common that the method implementation uses the specific C type of the self object.

The ml_flags field is a bitfield which can include the following flags. The individual flags indicate either a calling convention or a binding convention.

There are four basic calling conventions for positional arguments and two of them can be combined with METH_KEYWORDS to support also keyword arguments. So there are a total of 6 calling conventions:

METH_VARARGS

This is the typical calling convention, where the methods have the type PyCFunction. The function expects two PyObject* values. The first one is the self object for methods; for module functions, it is the module object. The second parameter (often called args) is a tuple object representing all arguments. This parameter is typically processed using PyArg_ParseTuple() or PyArg_UnpackTuple().

METH_VARARGS | METH_KEYWORDS

Methods with these flags must be of type PyCFunctionWithKeywords. The function expects three parameters: self, args, kwargs where kwargs is a dictionary of all the keyword arguments or possibly NULL if there are no keyword arguments. The parameters are typically processed using PyArg_ParseTupleAndKeywords().

METH_FASTCALL

Fast calling convention supporting only positional arguments. The methods have the type _PyCFunctionFast. The first parameter is self, the second parameter is a C array of PyObject* values indicating the arguments and the third parameter is the number of arguments (the length of the array).

This is not part of the limited API.

버전 3.7에 추가.

METH_FASTCALL | METH_KEYWORDS

Extension of METH_FASTCALL supporting also keyword arguments, with methods of type _PyCFunctionFastWithKeywords. Keyword arguments are passed the same way as in the vectorcall protocol: there is an additional fourth PyObject* parameter which is a tuple representing the names of the keyword arguments or possibly NULL if there are no keywords. The values of the keyword arguments are stored in the args array, after the positional arguments.

This is not part of the limited API.

버전 3.7에 추가.

METH_NOARGS

Methods without parameters don’t need to check whether arguments are given if they are listed with the METH_NOARGS flag. They need to be of type PyCFunction. The first parameter is typically named self and will hold a reference to the module or object instance. In all cases the second parameter will be NULL.

METH_O

Methods with a single object argument can be listed with the METH_O flag, instead of invoking PyArg_ParseTuple() with a "O" argument. They have the type PyCFunction, with the self parameter, and a PyObject* parameter representing the single argument.

These two constants are not used to indicate the calling convention but the binding when use with methods of classes. These may not be used for functions defined for modules. At most one of these flags may be set for any given method.

METH_CLASS

The method will be passed the type object as the first parameter rather than an instance of the type. This is used to create class methods, similar to what is created when using the classmethod() built-in function.

METH_STATIC

The method will be passed NULL as the first parameter rather than an instance of the type. This is used to create static methods, similar to what is created when using the staticmethod() built-in function.

One other constant controls whether a method is loaded in place of another definition with the same method name.

METH_COEXIST

The method will be loaded in place of existing definitions. Without METH_COEXIST, the default is to skip repeated definitions. Since slot wrappers are loaded before the method table, the existence of a sq_contains slot, for example, would generate a wrapped method named __contains__() and preclude the loading of a corresponding PyCFunction with the same name. With the flag defined, the PyCFunction will be loaded in place of the wrapper object and will co-exist with the slot. This is helpful because calls to PyCFunctions are optimized more than wrapper object calls.

PyMemberDef

Structure which describes an attribute of a type which corresponds to a C struct member. Its fields are:

Field

C Type

Meaning

name

const char *

name of the member

type

int

the type of the member in the C struct

offset

Py_ssize_t

the offset in bytes that the member is located on the type’s object struct

flags

int

flag bits indicating if the field should be read-only or writable

doc

const char *

points to the contents of the docstring

type can be one of many T_ macros corresponding to various C types. When the member is accessed in Python, it will be converted to the equivalent Python type.

Macro name

C type

T_SHORT

short

T_INT

int

T_LONG

long

T_FLOAT

float

T_DOUBLE

double

T_STRING

const char *

T_OBJECT

PyObject *

T_OBJECT_EX

PyObject *

T_CHAR

char

T_BYTE

char

T_UBYTE

unsigned char

T_UINT

unsigned int

T_USHORT

unsigned short

T_ULONG

unsigned long

T_BOOL

char

T_LONGLONG

long long

T_ULONGLONG

unsigned long long

T_PYSSIZET

Py_ssize_t

T_OBJECT and T_OBJECT_EX differ in that T_OBJECT returns None if the member is NULL and T_OBJECT_EX raises an AttributeError. Try to use T_OBJECT_EX over T_OBJECT because T_OBJECT_EX handles use of the del statement on that attribute more correctly than T_OBJECT.

flags can be 0 for write and read access or READONLY for read-only access. Using T_STRING for type implies READONLY. T_STRING data is interpreted as UTF-8. Only T_OBJECT and T_OBJECT_EX members can be deleted. (They are set to NULL).

PyGetSetDef

Structure to define property-like access for a type. See also description of the PyTypeObject.tp_getset slot.

Field

C Type

Meaning

name

const char *

attribute name

get

getter

C Function to get the attribute

set

setter

optional C function to set or delete the attribute, if omitted the attribute is readonly

doc

const char *

optional docstring

closure

void *

optional function pointer, providing additional data for getter and setter

The get function takes one PyObject* parameter (the instance) and a function pointer (the associated closure):

typedef PyObject *(*getter)(PyObject *, void *);

It should return a new reference on success or NULL with a set exception on failure.

set functions take two PyObject* parameters (the instance and the value to be set) and a function pointer (the associated closure):

typedef int (*setter)(PyObject *, PyObject *, void *);

In case the attribute should be deleted the second parameter is NULL. Should return 0 on success or -1 with a set exception on failure.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

객체 구현 지원 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

객체 구현 지원 »

|

Type Objects

Perhaps one of the most important structures of the Python object system is the structure that defines a new type: the PyTypeObject structure. Type objects can be handled using any of the PyObject_*() or PyType_*() functions, but do not offer much that’s interesting to most Python applications. These objects are fundamental to how objects behave, so they are very important to the interpreter itself and to any extension module that implements new types.

Type objects are fairly large compared to most of the standard types. The reason for the size is that each type object stores a large number of values, mostly C function pointers, each of which implements a small part of the type’s functionality. The fields of the type object are examined in detail in this section. The fields will be described in the order in which they occur in the structure.

Typedefs: unaryfunc, binaryfunc, ternaryfunc, inquiry, intargfunc, intintargfunc, intobjargproc, intintobjargproc, objobjargproc, destructor, freefunc, printfunc, getattrfunc, getattrofunc, setattrfunc, setattrofunc, reprfunc, hashfunc

The structure definition for PyTypeObject can be found in Include/object.h. For convenience of reference, this repeats the definition found there:

typedef struct _typeobject {
    PyObject_VAR_HEAD
    const char *tp_name; /* For printing, in format "<module>.<name>" */
    Py_ssize_t tp_basicsize, tp_itemsize; /* For allocation */

    /* Methods to implement standard operations */

    destructor tp_dealloc;
    printfunc tp_print;
    getattrfunc tp_getattr;
    setattrfunc tp_setattr;
    PyAsyncMethods *tp_as_async; /* formerly known as tp_compare (Python 2)
                                    or tp_reserved (Python 3) */
    reprfunc tp_repr;

    /* Method suites for standard classes */

    PyNumberMethods *tp_as_number;
    PySequenceMethods *tp_as_sequence;
    PyMappingMethods *tp_as_mapping;

    /* More standard operations (here for binary compatibility) */

    hashfunc tp_hash;
    ternaryfunc tp_call;
    reprfunc tp_str;
    getattrofunc tp_getattro;
    setattrofunc tp_setattro;

    /* Functions to access object as input/output buffer */
    PyBufferProcs *tp_as_buffer;

    /* Flags to define presence of optional/expanded features */
    unsigned long tp_flags;

    const char *tp_doc; /* Documentation string */

    /* call function for all accessible objects */
    traverseproc tp_traverse;

    /* delete references to contained objects */
    inquiry tp_clear;

    /* rich comparisons */
    richcmpfunc tp_richcompare;

    /* weak reference enabler */
    Py_ssize_t tp_weaklistoffset;

    /* Iterators */
    getiterfunc tp_iter;
    iternextfunc tp_iternext;

    /* Attribute descriptor and subclassing stuff */
    struct PyMethodDef *tp_methods;
    struct PyMemberDef *tp_members;
    struct PyGetSetDef *tp_getset;
    struct _typeobject *tp_base;
    PyObject *tp_dict;
    descrgetfunc tp_descr_get;
    descrsetfunc tp_descr_set;
    Py_ssize_t tp_dictoffset;
    initproc tp_init;
    allocfunc tp_alloc;
    newfunc tp_new;
    freefunc tp_free; /* Low-level free-memory routine */
    inquiry tp_is_gc; /* For PyObject_IS_GC */
    PyObject *tp_bases;
    PyObject *tp_mro; /* method resolution order */
    PyObject *tp_cache;
    PyObject *tp_subclasses;
    PyObject *tp_weaklist;
    destructor tp_del;

    /* Type attribute cache version tag. Added in version 2.6 */
    unsigned int tp_version_tag;

    destructor tp_finalize;

} PyTypeObject;

The type object structure extends the PyVarObject structure. The ob_size field is used for dynamic types (created by type_new(), usually called from a class statement). Note that PyType_Type (the metatype) initializes tp_itemsize, which means that its instances (i.e. type objects) must have the ob_size field.

PyObject* PyObject._ob_next

PyObject* PyObject._ob_prev

These fields are only present when the macro Py_TRACE_REFS is defined. Their initialization to NULL is taken care of by the PyObject_HEAD_INIT macro. For statically allocated objects, these fields always remain NULL. For dynamically allocated objects, these two fields are used to link the object into a doubly-linked list of all live objects on the heap. This could be used for various debugging purposes; currently the only use is to print the objects that are still alive at the end of a run when the environment variable PYTHONDUMPREFS is set.

These fields are not inherited by subtypes.

Py_ssize_t PyObject.ob_refcnt

This is the type object’s reference count, initialized to 1 by the PyObject_HEAD_INIT macro. Note that for statically allocated type objects, the type’s instances (objects whose ob_type points back to the type) do not count as references. But for dynamically allocated type objects, the instances do count as references.

This field is not inherited by subtypes.

PyTypeObject* PyObject.ob_type

This is the type’s type, in other words its metatype. It is initialized by the argument to the PyObject_HEAD_INIT macro, and its value should normally be &PyType_Type. However, for dynamically loadable extension modules that must be usable on Windows (at least), the compiler complains that this is not a valid initializer. Therefore, the convention is to pass NULL to the PyObject_HEAD_INIT macro and to initialize this field explicitly at the start of the module’s initialization function, before doing anything else. This is typically done like this:

Foo_Type.ob_type = &PyType_Type;

This should be done before any instances of the type are created. PyType_Ready() checks if ob_type is NULL, and if so, initializes it to the ob_type field of the base class. PyType_Ready() will not change this field if it is non-zero.

This field is inherited by subtypes.

Py_ssize_t PyVarObject.ob_size

For statically allocated type objects, this should be initialized to zero. For dynamically allocated type objects, this field has a special internal meaning.

This field is not inherited by subtypes.

const char* PyTypeObject.tp_name

Pointer to a NUL-terminated string containing the name of the type. For types that are accessible as module globals, the string should be the full module name, followed by a dot, followed by the type name; for built-in types, it should be just the type name. If the module is a submodule of a package, the full package name is part of the full module name. For example, a type named T defined in module M in subpackage Q in package P should have the tp_name initializer "P.Q.M.T".

For dynamically allocated type objects, this should just be the type name, and the module name explicitly stored in the type dict as the value for key '__module__'.

For statically allocated type objects, the tp_name field should contain a dot. Everything before the last dot is made accessible as the __module__ attribute, and everything after the last dot is made accessible as the __name__ attribute.

If no dot is present, the entire tp_name field is made accessible as the __name__ attribute, and the __module__ attribute is undefined (unless explicitly set in the dictionary, as explained above). This means your type will be impossible to pickle. Additionally, it will not be listed in module documentations created with pydoc.

This field is not inherited by subtypes.

Py_ssize_t PyTypeObject.tp_basicsize

Py_ssize_t PyTypeObject.tp_itemsize

These fields allow calculating the size in bytes of instances of the type.

There are two kinds of types: types with fixed-length instances have a zero tp_itemsize field, types with variable-length instances have a non-zero tp_itemsize field. For a type with fixed-length instances, all instances have the same size, given in tp_basicsize.

For a type with variable-length instances, the instances must have an ob_size field, and the instance size is tp_basicsize plus N times tp_itemsize, where N is the “length” of the object. The value of N is typically stored in the instance’s ob_size field. There are exceptions: for example, ints use a negative ob_size to indicate a negative number, and N is abs(ob_size) there. Also, the presence of an ob_size field in the instance layout doesn’t mean that the instance structure is variable-length (for example, the structure for the list type has fixed-length instances, yet those instances have a meaningful ob_size field).

The basic size includes the fields in the instance declared by the macro PyObject_HEAD or PyObject_VAR_HEAD (whichever is used to declare the instance struct) and this in turn includes the _ob_prev and _ob_next fields if they are present. This means that the only correct way to get an initializer for the tp_basicsize is to use the sizeof operator on the struct used to declare the instance layout. The basic size does not include the GC header size.

These fields are inherited separately by subtypes. If the base type has a non-zero tp_itemsize, it is generally not safe to set tp_itemsize to a different non-zero value in a subtype (though this depends on the implementation of the base type).

A note about alignment: if the variable items require a particular alignment, this should be taken care of by the value of tp_basicsize. Example: suppose a type implements an array of double. tp_itemsize is sizeof(double). It is the programmer’s responsibility that tp_basicsize is a multiple of sizeof(double) (assuming this is the alignment requirement for double).

destructor PyTypeObject.tp_dealloc

A pointer to the instance destructor function. This function must be defined unless the type guarantees that its instances will never be deallocated (as is the case for the singletons None and Ellipsis).

The destructor function is called by the Py_DECREF() and Py_XDECREF() macros when the new reference count is zero. At this point, the instance is still in existence, but there are no references to it. The destructor function should free all references which the instance owns, free all memory buffers owned by the instance (using the freeing function corresponding to the allocation function used to allocate the buffer), and finally (as its last action) call the type’s tp_free function. If the type is not subtypable (doesn’t have the Py_TPFLAGS_BASETYPE flag bit set), it is permissible to call the object deallocator directly instead of via tp_free. The object deallocator should be the one used to allocate the instance; this is normally PyObject_Del() if the instance was allocated using PyObject_New() or PyObject_VarNew(), or PyObject_GC_Del() if the instance was allocated using PyObject_GC_New() or PyObject_GC_NewVar().

This field is inherited by subtypes.

printfunc PyTypeObject.tp_print

Reserved slot, formerly used for print formatting in Python 2.x.

getattrfunc PyTypeObject.tp_getattr

An optional pointer to the get-attribute-string function.

This field is deprecated. When it is defined, it should point to a function that acts the same as the tp_getattro function, but taking a C string instead of a Python string object to give the attribute name. The signature is

PyObject * tp_getattr(PyObject *o, char *attr_name);

This field is inherited by subtypes together with tp_getattro: a subtype inherits both tp_getattr and tp_getattro from its base type when the subtype’s tp_getattr and tp_getattro are both NULL.

setattrfunc PyTypeObject.tp_setattr

An optional pointer to the function for setting and deleting attributes.

This field is deprecated. When it is defined, it should point to a function that acts the same as the tp_setattro function, but taking a C string instead of a Python string object to give the attribute name. The signature is

PyObject * tp_setattr(PyObject *o, char *attr_name, PyObject *v);

The v argument is set to NULL to delete the attribute. This field is inherited by subtypes together with tp_setattro: a subtype inherits both tp_setattr and tp_setattro from its base type when the subtype’s tp_setattr and tp_setattro are both NULL.

PyAsyncMethods* tp_as_async

Pointer to an additional structure that contains fields relevant only to objects which implement awaitable and asynchronous iterator protocols at the C-level. See Async Object Structures for details.

버전 3.5에 추가: Formerly known as tp_compare and tp_reserved.

reprfunc PyTypeObject.tp_repr

An optional pointer to a function that implements the built-in function repr().

The signature is the same as for PyObject_Repr(); it must return a string or a Unicode object. Ideally, this function should return a string that, when passed to eval(), given a suitable environment, returns an object with the same value. If this is not feasible, it should return a string starting with '<' and ending with '>' from which both the type and the value of the object can be deduced.

When this field is not set, a string of the form <%s object at %p> is returned, where %s is replaced by the type name, and %p by the object’s memory address.

This field is inherited by subtypes.

PyNumberMethods* tp_as_number

Pointer to an additional structure that contains fields relevant only to objects which implement the number protocol. These fields are documented in Number Object Structures.

The tp_as_number field is not inherited, but the contained fields are inherited individually.

PySequenceMethods* tp_as_sequence

Pointer to an additional structure that contains fields relevant only to objects which implement the sequence protocol. These fields are documented in Sequence Object Structures.

The tp_as_sequence field is not inherited, but the contained fields are inherited individually.

PyMappingMethods* tp_as_mapping

Pointer to an additional structure that contains fields relevant only to objects which implement the mapping protocol. These fields are documented in Mapping Object Structures.

The tp_as_mapping field is not inherited, but the contained fields are inherited individually.

hashfunc PyTypeObject.tp_hash

An optional pointer to a function that implements the built-in function hash().

The signature is the same as for PyObject_Hash(); it must return a value of the type Py_hash_t. The value -1 should not be returned as a normal return value; when an error occurs during the computation of the hash value, the function should set an exception and return -1.

This field can be set explicitly to PyObject_HashNotImplemented() to block inheritance of the hash method from a parent type. This is interpreted as the equivalent of __hash__ = None at the Python level, causing isinstance(o, collections.Hashable) to correctly return False. Note that the converse is also true - setting __hash__ = None on a class at the Python level will result in the tp_hash slot being set to PyObject_HashNotImplemented().

When this field is not set, an attempt to take the hash of the object raises TypeError.

This field is inherited by subtypes together with tp_richcompare: a subtype inherits both of tp_richcompare and tp_hash, when the subtype’s tp_richcompare and tp_hash are both NULL.

ternaryfunc PyTypeObject.tp_call

An optional pointer to a function that implements calling the object. This should be NULL if the object is not callable. The signature is the same as for PyObject_Call().

This field is inherited by subtypes.

reprfunc PyTypeObject.tp_str

An optional pointer to a function that implements the built-in operation str(). (Note that str is a type now, and str() calls the constructor for that type. This constructor calls PyObject_Str() to do the actual work, and PyObject_Str() will call this handler.)

The signature is the same as for PyObject_Str(); it must return a string or a Unicode object. This function should return a “friendly” string representation of the object, as this is the representation that will be used, among other things, by the print() function.

When this field is not set, PyObject_Repr() is called to return a string representation.

This field is inherited by subtypes.

getattrofunc PyTypeObject.tp_getattro

An optional pointer to the get-attribute function.

The signature is the same as for PyObject_GetAttr(). It is usually convenient to set this field to PyObject_GenericGetAttr(), which implements the normal way of looking for object attributes.

This field is inherited by subtypes together with tp_getattr: a subtype inherits both tp_getattr and tp_getattro from its base type when the subtype’s tp_getattr and tp_getattro are both NULL.

setattrofunc PyTypeObject.tp_setattro

An optional pointer to the function for setting and deleting attributes.

The signature is the same as for PyObject_SetAttr(), but setting v to NULL to delete an attribute must be supported. It is usually convenient to set this field to PyObject_GenericSetAttr(), which implements the normal way of setting object attributes.

This field is inherited by subtypes together with tp_setattr: a subtype inherits both tp_setattr and tp_setattro from its base type when the subtype’s tp_setattr and tp_setattro are both NULL.

PyBufferProcs* PyTypeObject.tp_as_buffer

Pointer to an additional structure that contains fields relevant only to objects which implement the buffer interface. These fields are documented in Buffer Object Structures.

The tp_as_buffer field is not inherited, but the contained fields are inherited individually.

unsigned long PyTypeObject.tp_flags

This field is a bit mask of various flags. Some flags indicate variant semantics for certain situations; others are used to indicate that certain fields in the type object (or in the extension structures referenced via tp_as_number, tp_as_sequence, tp_as_mapping, and tp_as_buffer) that were historically not always present are valid; if such a flag bit is clear, the type fields it guards must not be accessed and must be considered to have a zero or NULL value instead.

Inheritance of this field is complicated. Most flag bits are inherited individually, i.e. if the base type has a flag bit set, the subtype inherits this flag bit. The flag bits that pertain to extension structures are strictly inherited if the extension structure is inherited, i.e. the base type’s value of the flag bit is copied into the subtype together with a pointer to the extension structure. The Py_TPFLAGS_HAVE_GC flag bit is inherited together with the tp_traverse and tp_clear fields, i.e. if the Py_TPFLAGS_HAVE_GC flag bit is clear in the subtype and the tp_traverse and tp_clear fields in the subtype exist and have NULL values.

The following bit masks are currently defined; these can be ORed together using the | operator to form the value of the tp_flags field. The macro PyType_HasFeature() takes a type and a flags value, tp and f, and checks whether tp->tp_flags & f is non-zero.

Py_TPFLAGS_HEAPTYPE

This bit is set when the type object itself is allocated on the heap. In this case, the ob_type field of its instances is considered a reference to the type, and the type object is INCREF’ed when a new instance is created, and DECREF’ed when an instance is destroyed (this does not apply to instances of subtypes; only the type referenced by the instance’s ob_type gets INCREF’ed or DECREF’ed).

Py_TPFLAGS_BASETYPE

This bit is set when the type can be used as the base type of another type. If this bit is clear, the type cannot be subtyped (similar to a “final” class in Java).

Py_TPFLAGS_READY

This bit is set when the type object has been fully initialized by PyType_Ready().

Py_TPFLAGS_READYING

This bit is set while PyType_Ready() is in the process of initializing the type object.

Py_TPFLAGS_HAVE_GC

This bit is set when the object supports garbage collection. If this bit is set, instances must be created using PyObject_GC_New() and destroyed using PyObject_GC_Del(). More information in section 순환 가비지 수집 지원. This bit also implies that the GC-related fields tp_traverse and tp_clear are present in the type object.

Py_TPFLAGS_DEFAULT

This is a bitmask of all the bits that pertain to the existence of certain fields in the type object and its extension structures. Currently, it includes the following bits: Py_TPFLAGS_HAVE_STACKLESS_EXTENSION, Py_TPFLAGS_HAVE_VERSION_TAG.

Py_TPFLAGS_LONG_SUBCLASS

Py_TPFLAGS_LIST_SUBCLASS

Py_TPFLAGS_TUPLE_SUBCLASS

Py_TPFLAGS_BYTES_SUBCLASS

Py_TPFLAGS_UNICODE_SUBCLASS

Py_TPFLAGS_DICT_SUBCLASS

Py_TPFLAGS_BASE_EXC_SUBCLASS

Py_TPFLAGS_TYPE_SUBCLASS

These flags are used by functions such as PyLong_Check() to quickly determine if a type is a subclass of a built-in type; such specific checks are faster than a generic check, like PyObject_IsInstance(). Custom types that inherit from built-ins should have their tp_flags set appropriately, or the code that interacts with such types will behave differently depending on what kind of check is used.

Py_TPFLAGS_HAVE_FINALIZE

This bit is set when the tp_finalize slot is present in the type structure.

버전 3.4에 추가.

const char* PyTypeObject.tp_doc

An optional pointer to a NUL-terminated C string giving the docstring for this type object. This is exposed as the __doc__ attribute on the type and instances of the type.

This field is not inherited by subtypes.

traverseproc PyTypeObject.tp_traverse

An optional pointer to a traversal function for the garbage collector. This is only used if the Py_TPFLAGS_HAVE_GC flag bit is set. More information about Python’s garbage collection scheme can be found in section 순환 가비지 수집 지원.

The tp_traverse pointer is used by the garbage collector to detect reference cycles. A typical implementation of a tp_traverse function simply calls Py_VISIT() on each of the instance’s members that are Python objects that the instance owns. For example, this is function local_traverse() from the _thread extension module:

static int
local_traverse(localobject *self, visitproc visit, void *arg)
{
    Py_VISIT(self->args);
    Py_VISIT(self->kw);
    Py_VISIT(self->dict);
    return 0;
}

Note that Py_VISIT() is called only on those members that can participate in reference cycles. Although there is also a self->key member, it can only be NULL or a Python string and therefore cannot be part of a reference cycle.

On the other hand, even if you know a member can never be part of a cycle, as a debugging aid you may want to visit it anyway just so the gc module’s get_referents() function will include it.

경고

When implementing tp_traverse, only the members that the instance owns (by having strong references to them) must be visited. For instance, if an object supports weak references via the tp_weaklist slot, the pointer supporting the linked list (what tp_weaklist points to) must not be visited as the instance does not directly own the weak references to itself (the weakreference list is there to support the weak reference machinery, but the instance has no strong reference to the elements inside it, as they are allowed to be removed even if the instance is still alive).

Note that Py_VISIT() requires the visit and arg parameters to local_traverse() to have these specific names; don’t name them just anything.

This field is inherited by subtypes together with tp_clear and the Py_TPFLAGS_HAVE_GC flag bit: the flag bit, tp_traverse, and tp_clear are all inherited from the base type if they are all zero in the subtype.

inquiry PyTypeObject.tp_clear

An optional pointer to a clear function for the garbage collector. This is only used if the Py_TPFLAGS_HAVE_GC flag bit is set.

The tp_clear member function is used to break reference cycles in cyclic garbage detected by the garbage collector. Taken together, all tp_clear functions in the system must combine to break all reference cycles. This is subtle, and if in any doubt supply a tp_clear function. For example, the tuple type does not implement a tp_clear function, because it’s possible to prove that no reference cycle can be composed entirely of tuples. Therefore the tp_clear functions of other types must be sufficient to break any cycle containing a tuple. This isn’t immediately obvious, and there’s rarely a good reason to avoid implementing tp_clear.

Implementations of tp_clear should drop the instance’s references to those of its members that may be Python objects, and set its pointers to those members to NULL, as in the following example:

static int
local_clear(localobject *self)
{
    Py_CLEAR(self->key);
    Py_CLEAR(self->args);
    Py_CLEAR(self->kw);
    Py_CLEAR(self->dict);
    return 0;
}

The Py_CLEAR() macro should be used, because clearing references is delicate: the reference to the contained object must not be decremented until after the pointer to the contained object is set to NULL. This is because decrementing the reference count may cause the contained object to become trash, triggering a chain of reclamation activity that may include invoking arbitrary Python code (due to finalizers, or weakref callbacks, associated with the contained object). If it’s possible for such code to reference self again, it’s important that the pointer to the contained object be NULL at that time, so that self knows the contained object can no longer be used. The Py_CLEAR() macro performs the operations in a safe order.

Because the goal of tp_clear functions is to break reference cycles, it’s not necessary to clear contained objects like Python strings or Python integers, which can’t participate in reference cycles. On the other hand, it may be convenient to clear all contained Python objects, and write the type’s tp_dealloc function to invoke tp_clear.

More information about Python’s garbage collection scheme can be found in section 순환 가비지 수집 지원.

This field is inherited by subtypes together with tp_traverse and the Py_TPFLAGS_HAVE_GC flag bit: the flag bit, tp_traverse, and tp_clear are all inherited from the base type if they are all zero in the subtype.

richcmpfunc PyTypeObject.tp_richcompare

An optional pointer to the rich comparison function, whose signature is PyObject *tp_richcompare(PyObject *a, PyObject *b, int op). The first parameter is guaranteed to be an instance of the type that is defined by PyTypeObject.

The function should return the result of the comparison (usually Py_True or Py_False). If the comparison is undefined, it must return Py_NotImplemented, if another error occurred it must return NULL and set an exception condition.

참고

If you want to implement a type for which only a limited set of comparisons makes sense (e.g. == and !=, but not < and friends), directly raise TypeError in the rich comparison function.

This field is inherited by subtypes together with tp_hash: a subtype inherits tp_richcompare and tp_hash when the subtype’s tp_richcompare and tp_hash are both NULL.

The following constants are defined to be used as the third argument for tp_richcompare and for PyObject_RichCompare():

Constant

Comparison

Py_LT

<

Py_LE

<=

Py_EQ

==

Py_NE

!=

Py_GT

>

Py_GE

>=

The following macro is defined to ease writing rich comparison functions:

PyObject *Py_RETURN_RICHCOMPARE(VAL_A, VAL_B, int op)

Return Py_True or Py_False from the function, depending on the result of a comparison. VAL_A and VAL_B must be orderable by C comparison operators (for example, they may be C ints or floats). The third argument specifies the requested operation, as for PyObject_RichCompare().

The return value’s reference count is properly incremented.

On error, sets an exception and returns NULL from the function.

버전 3.7에 추가.

Py_ssize_t PyTypeObject.tp_weaklistoffset

If the instances of this type are weakly referenceable, this field is greater than zero and contains the offset in the instance structure of the weak reference list head (ignoring the GC header, if present); this offset is used by PyObject_ClearWeakRefs() and the PyWeakref_*() functions. The instance structure needs to include a field of type PyObject* which is initialized to NULL.

Do not confuse this field with tp_weaklist; that is the list head for weak references to the type object itself.

This field is inherited by subtypes, but see the rules listed below. A subtype may override this offset; this means that the subtype uses a different weak reference list head than the base type. Since the list head is always found via tp_weaklistoffset, this should not be a problem.

When a type defined by a class statement has no __slots__ declaration, and none of its base types are weakly referenceable, the type is made weakly referenceable by adding a weak reference list head slot to the instance layout and setting the tp_weaklistoffset of that slot’s offset.

When a type’s __slots__ declaration contains a slot named __weakref__, that slot becomes the weak reference list head for instances of the type, and the slot’s offset is stored in the type’s tp_weaklistoffset.

When a type’s __slots__ declaration does not contain a slot named __weakref__, the type inherits its tp_weaklistoffset from its base type.

getiterfunc PyTypeObject.tp_iter

An optional pointer to a function that returns an iterator for the object. Its presence normally signals that the instances of this type are iterable (although sequences may be iterable without this function).

This function has the same signature as PyObject_GetIter().

This field is inherited by subtypes.

iternextfunc PyTypeObject.tp_iternext

An optional pointer to a function that returns the next item in an iterator. When the iterator is exhausted, it must return NULL; a StopIteration exception may or may not be set. When another error occurs, it must return NULL too. Its presence signals that the instances of this type are iterators.

Iterator types should also define the tp_iter function, and that function should return the iterator instance itself (not a new iterator instance).

This function has the same signature as PyIter_Next().

This field is inherited by subtypes.

struct PyMethodDef* PyTypeObject.tp_methods

An optional pointer to a static NULL-terminated array of PyMethodDef structures, declaring regular methods of this type.

For each entry in the array, an entry is added to the type’s dictionary (see tp_dict below) containing a method descriptor.

This field is not inherited by subtypes (methods are inherited through a different mechanism).

struct PyMemberDef* PyTypeObject.tp_members

An optional pointer to a static NULL-terminated array of PyMemberDef structures, declaring regular data members (fields or slots) of instances of this type.

For each entry in the array, an entry is added to the type’s dictionary (see tp_dict below) containing a member descriptor.

This field is not inherited by subtypes (members are inherited through a different mechanism).

struct PyGetSetDef* PyTypeObject.tp_getset

An optional pointer to a static NULL-terminated array of PyGetSetDef structures, declaring computed attributes of instances of this type.

For each entry in the array, an entry is added to the type’s dictionary (see tp_dict below) containing a getset descriptor.

This field is not inherited by subtypes (computed attributes are inherited through a different mechanism).

PyTypeObject* PyTypeObject.tp_base

An optional pointer to a base type from which type properties are inherited. At this level, only single inheritance is supported; multiple inheritance require dynamically creating a type object by calling the metatype.

This field is not inherited by subtypes (obviously), but it defaults to &PyBaseObject_Type (which to Python programmers is known as the type object).

PyObject* PyTypeObject.tp_dict

The type’s dictionary is stored here by PyType_Ready().

This field should normally be initialized to NULL before PyType_Ready is called; it may also be initialized to a dictionary containing initial attributes for the type. Once PyType_Ready() has initialized the type, extra attributes for the type may be added to this dictionary only if they don’t correspond to overloaded operations (like __add__()).

This field is not inherited by subtypes (though the attributes defined in here are inherited through a different mechanism).

경고

It is not safe to use PyDict_SetItem() on or otherwise modify tp_dict with the dictionary C-API.

descrgetfunc PyTypeObject.tp_descr_get

An optional pointer to a “descriptor get” function.

The function signature is

PyObject * tp_descr_get(PyObject *self, PyObject *obj, PyObject *type);

This field is inherited by subtypes.

descrsetfunc PyTypeObject.tp_descr_set

An optional pointer to a function for setting and deleting a descriptor’s value.

The function signature is

int tp_descr_set(PyObject *self, PyObject *obj, PyObject *value);

The value argument is set to NULL to delete the value. This field is inherited by subtypes.

Py_ssize_t PyTypeObject.tp_dictoffset

If the instances of this type have a dictionary containing instance variables, this field is non-zero and contains the offset in the instances of the type of the instance variable dictionary; this offset is used by PyObject_GenericGetAttr().

Do not confuse this field with tp_dict; that is the dictionary for attributes of the type object itself.

If the value of this field is greater than zero, it specifies the offset from the start of the instance structure. If the value is less than zero, it specifies the offset from the end of the instance structure. A negative offset is more expensive to use, and should only be used when the instance structure contains a variable-length part. This is used for example to add an instance variable dictionary to subtypes of str or tuple. Note that the tp_basicsize field should account for the dictionary added to the end in that case, even though the dictionary is not included in the basic object layout. On a system with a pointer size of 4 bytes, tp_dictoffset should be set to -4 to indicate that the dictionary is at the very end of the structure.

The real dictionary offset in an instance can be computed from a negative tp_dictoffset as follows:

dictoffset = tp_basicsize + abs(ob_size)*tp_itemsize + tp_dictoffset
if dictoffset is not aligned on sizeof(void*):
    round up to sizeof(void*)

where tp_basicsize, tp_itemsize and tp_dictoffset are taken from the type object, and ob_size is taken from the instance. The absolute value is taken because ints use the sign of ob_size to store the sign of the number. (There’s never a need to do this calculation yourself; it is done for you by _PyObject_GetDictPtr().)

This field is inherited by subtypes, but see the rules listed below. A subtype may override this offset; this means that the subtype instances store the dictionary at a difference offset than the base type. Since the dictionary is always found via tp_dictoffset, this should not be a problem.

When a type defined by a class statement has no __slots__ declaration, and none of its base types has an instance variable dictionary, a dictionary slot is added to the instance layout and the tp_dictoffset is set to that slot’s offset.

When a type defined by a class statement has a __slots__ declaration, the type inherits its tp_dictoffset from its base type.

(Adding a slot named __dict__ to the __slots__ declaration does not have the expected effect, it just causes confusion. Maybe this should be added as a feature just like __weakref__ though.)

initproc PyTypeObject.tp_init

An optional pointer to an instance initialization function.

This function corresponds to the __init__() method of classes. Like __init__(), it is possible to create an instance without calling __init__(), and it is possible to reinitialize an instance by calling its __init__() method again.

The function signature is

int tp_init(PyObject *self, PyObject *args, PyObject *kwds)

The self argument is the instance to be initialized; the args and kwds arguments represent positional and keyword arguments of the call to __init__().

The tp_init function, if not NULL, is called when an instance is created normally by calling its type, after the type’s tp_new function has returned an instance of the type. If the tp_new function returns an instance of some other type that is not a subtype of the original type, no tp_init function is called; if tp_new returns an instance of a subtype of the original type, the subtype’s tp_init is called.

This field is inherited by subtypes.

allocfunc PyTypeObject.tp_alloc

An optional pointer to an instance allocation function.

The function signature is

PyObject *tp_alloc(PyTypeObject *self, Py_ssize_t nitems)

The purpose of this function is to separate memory allocation from memory initialization. It should return a pointer to a block of memory of adequate length for the instance, suitably aligned, and initialized to zeros, but with ob_refcnt set to 1 and ob_type set to the type argument. If the type’s tp_itemsize is non-zero, the object’s ob_size field should be initialized to nitems and the length of the allocated memory block should be tp_basicsize + nitems*tp_itemsize, rounded up to a multiple of sizeof(void*); otherwise, nitems is not used and the length of the block should be tp_basicsize.

Do not use this function to do any other instance initialization, not even to allocate additional memory; that should be done by tp_new.

This field is inherited by static subtypes, but not by dynamic subtypes (subtypes created by a class statement); in the latter, this field is always set to PyType_GenericAlloc(), to force a standard heap allocation strategy. That is also the recommended value for statically defined types.

newfunc PyTypeObject.tp_new

An optional pointer to an instance creation function.

If this function is NULL for a particular type, that type cannot be called to create new instances; presumably there is some other way to create instances, like a factory function.

The function signature is

PyObject *tp_new(PyTypeObject *subtype, PyObject *args, PyObject *kwds)

The subtype argument is the type of the object being created; the args and kwds arguments represent positional and keyword arguments of the call to the type. Note that subtype doesn’t have to equal the type whose tp_new function is called; it may be a subtype of that type (but not an unrelated type).

The tp_new function should call subtype->tp_alloc(subtype, nitems) to allocate space for the object, and then do only as much further initialization as is absolutely necessary. Initialization that can safely be ignored or repeated should be placed in the tp_init handler. A good rule of thumb is that for immutable types, all initialization should take place in tp_new, while for mutable types, most initialization should be deferred to tp_init.

This field is inherited by subtypes, except it is not inherited by static types whose tp_base is NULL or &PyBaseObject_Type.

destructor PyTypeObject.tp_free

An optional pointer to an instance deallocation function. Its signature is freefunc:

void tp_free(void *)

An initializer that is compatible with this signature is PyObject_Free().

This field is inherited by static subtypes, but not by dynamic subtypes (subtypes created by a class statement); in the latter, this field is set to a deallocator suitable to match PyType_GenericAlloc() and the value of the Py_TPFLAGS_HAVE_GC flag bit.

inquiry PyTypeObject.tp_is_gc

An optional pointer to a function called by the garbage collector.

The garbage collector needs to know whether a particular object is collectible or not. Normally, it is sufficient to look at the object’s type’s tp_flags field, and check the Py_TPFLAGS_HAVE_GC flag bit. But some types have a mixture of statically and dynamically allocated instances, and the statically allocated instances are not collectible. Such types should define this function; it should return 1 for a collectible instance, and 0 for a non-collectible instance. The signature is

int tp_is_gc(PyObject *self)

(The only example of this are types themselves. The metatype, PyType_Type, defines this function to distinguish between statically and dynamically allocated types.)

This field is inherited by subtypes.

PyObject* PyTypeObject.tp_bases

Tuple of base types.

This is set for types created by a class statement. It should be NULL for statically defined types.

This field is not inherited.

PyObject* PyTypeObject.tp_mro

Tuple containing the expanded set of base types, starting with the type itself and ending with object, in Method Resolution Order.

This field is not inherited; it is calculated fresh by PyType_Ready().

destructor PyTypeObject.tp_finalize

An optional pointer to an instance finalization function. Its signature is destructor:

void tp_finalize(PyObject *)

If tp_finalize is set, the interpreter calls it once when finalizing an instance. It is called either from the garbage collector (if the instance is part of an isolated reference cycle) or just before the object is deallocated. Either way, it is guaranteed to be called before attempting to break reference cycles, ensuring that it finds the object in a sane state.

tp_finalize should not mutate the current exception status; therefore, a recommended way to write a non-trivial finalizer is:

static void
local_finalize(PyObject *self)
{
    PyObject *error_type, *error_value, *error_traceback;

    /* Save the current exception, if any. */
    PyErr_Fetch(&error_type, &error_value, &error_traceback);

    /* ... */

    /* Restore the saved exception. */
    PyErr_Restore(error_type, error_value, error_traceback);
}

For this field to be taken into account (even through inheritance), you must also set the Py_TPFLAGS_HAVE_FINALIZE flags bit.

This field is inherited by subtypes.

버전 3.4에 추가.

더 보기

“Safe object finalization” (PEP 442 [https://www.python.org/dev/peps/pep-0442])

PyObject* PyTypeObject.tp_cache

Unused. Not inherited. Internal use only.

PyObject* PyTypeObject.tp_subclasses

List of weak references to subclasses. Not inherited. Internal use only.

PyObject* PyTypeObject.tp_weaklist

Weak reference list head, for weak references to this type object. Not inherited. Internal use only.

The remaining fields are only defined if the feature test macro COUNT_ALLOCS is defined, and are for internal use only. They are documented here for completeness. None of these fields are inherited by subtypes.

Py_ssize_t PyTypeObject.tp_allocs

Number of allocations.

Py_ssize_t PyTypeObject.tp_frees

Number of frees.

Py_ssize_t PyTypeObject.tp_maxalloc

Maximum simultaneously allocated objects.

PyTypeObject* PyTypeObject.tp_next

Pointer to the next type object with a non-zero tp_allocs field.

Also, note that, in a garbage collected Python, tp_dealloc may be called from any Python thread, not just the thread which created the object (if the object becomes part of a refcount cycle, that cycle might be collected by a garbage collection on any thread). This is not a problem for Python API calls, since the thread on which tp_dealloc is called will own the Global Interpreter Lock (GIL). However, if the object being destroyed in turn destroys objects from some other C or C++ library, care should be taken to ensure that destroying those objects on the thread which called tp_dealloc will not violate any assumptions of the library.

Number Object Structures

PyNumberMethods

This structure holds pointers to the functions which an object uses to implement the number protocol. Each function is used by the function of similar name documented in the 숫자 프로토콜 section.

Here is the structure definition:

typedef struct {
     binaryfunc nb_add;
     binaryfunc nb_subtract;
     binaryfunc nb_multiply;
     binaryfunc nb_remainder;
     binaryfunc nb_divmod;
     ternaryfunc nb_power;
     unaryfunc nb_negative;
     unaryfunc nb_positive;
     unaryfunc nb_absolute;
     inquiry nb_bool;
     unaryfunc nb_invert;
     binaryfunc nb_lshift;
     binaryfunc nb_rshift;
     binaryfunc nb_and;
     binaryfunc nb_xor;
     binaryfunc nb_or;
     unaryfunc nb_int;
     void *nb_reserved;
     unaryfunc nb_float;

     binaryfunc nb_inplace_add;
     binaryfunc nb_inplace_subtract;
     binaryfunc nb_inplace_multiply;
     binaryfunc nb_inplace_remainder;
     ternaryfunc nb_inplace_power;
     binaryfunc nb_inplace_lshift;
     binaryfunc nb_inplace_rshift;
     binaryfunc nb_inplace_and;
     binaryfunc nb_inplace_xor;
     binaryfunc nb_inplace_or;

     binaryfunc nb_floor_divide;
     binaryfunc nb_true_divide;
     binaryfunc nb_inplace_floor_divide;
     binaryfunc nb_inplace_true_divide;

     unaryfunc nb_index;

     binaryfunc nb_matrix_multiply;
     binaryfunc nb_inplace_matrix_multiply;
} PyNumberMethods;

참고

Binary and ternary functions must check the type of all their operands, and implement the necessary conversions (at least one of the operands is an instance of the defined type). If the operation is not defined for the given operands, binary and ternary functions must return Py_NotImplemented, if another error occurred they must return NULL and set an exception.

참고

The nb_reserved field should always be NULL. It was previously called nb_long, and was renamed in Python 3.0.1.

Mapping Object Structures

PyMappingMethods

This structure holds pointers to the functions which an object uses to implement the mapping protocol. It has three members:

lenfunc PyMappingMethods.mp_length

This function is used by PyMapping_Size() and PyObject_Size(), and has the same signature. This slot may be set to NULL if the object has no defined length.

binaryfunc PyMappingMethods.mp_subscript

This function is used by PyObject_GetItem() and PySequence_GetSlice(), and has the same signature as PyObject_GetItem(). This slot must be filled for the PyMapping_Check() function to return 1, it can be NULL otherwise.

objobjargproc PyMappingMethods.mp_ass_subscript

This function is used by PyObject_SetItem(), PyObject_DelItem(), PyObject_SetSlice() and PyObject_DelSlice(). It has the same signature as PyObject_SetItem(), but v can also be set to NULL to delete an item. If this slot is NULL, the object does not support item assignment and deletion.

Sequence Object Structures

PySequenceMethods

This structure holds pointers to the functions which an object uses to implement the sequence protocol.

lenfunc PySequenceMethods.sq_length

This function is used by PySequence_Size() and PyObject_Size(), and has the same signature. It is also used for handling negative indices via the sq_item and the sq_ass_item slots.

binaryfunc PySequenceMethods.sq_concat

This function is used by PySequence_Concat() and has the same signature. It is also used by the + operator, after trying the numeric addition via the nb_add slot.

ssizeargfunc PySequenceMethods.sq_repeat

This function is used by PySequence_Repeat() and has the same signature. It is also used by the * operator, after trying numeric multiplication via the nb_multiply slot.

ssizeargfunc PySequenceMethods.sq_item

This function is used by PySequence_GetItem() and has the same signature. It is also used by PyObject_GetItem(), after trying the subscription via the mp_subscript slot. This slot must be filled for the PySequence_Check() function to return 1, it can be NULL otherwise.

Negative indexes are handled as follows: if the sq_length slot is filled, it is called and the sequence length is used to compute a positive index which is passed to sq_item. If sq_length is NULL, the index is passed as is to the function.

ssizeobjargproc PySequenceMethods.sq_ass_item

This function is used by PySequence_SetItem() and has the same signature. It is also used by PyObject_SetItem() and PyObject_DelItem(), after trying the item assignment and deletion via the mp_ass_subscript slot. This slot may be left to NULL if the object does not support item assignment and deletion.

objobjproc PySequenceMethods.sq_contains

This function may be used by PySequence_Contains() and has the same signature. This slot may be left to NULL, in this case PySequence_Contains() simply traverses the sequence until it finds a match.

binaryfunc PySequenceMethods.sq_inplace_concat

This function is used by PySequence_InPlaceConcat() and has the same signature. It should modify its first operand, and return it. This slot may be left to NULL, in this case PySequence_InPlaceConcat() will fall back to PySequence_Concat(). It is also used by the augmented assignment +=, after trying numeric in-place addition via the nb_inplace_add slot.

ssizeargfunc PySequenceMethods.sq_inplace_repeat

This function is used by PySequence_InPlaceRepeat() and has the same signature. It should modify its first operand, and return it. This slot may be left to NULL, in this case PySequence_InPlaceRepeat() will fall back to PySequence_Repeat(). It is also used by the augmented assignment *=, after trying numeric in-place multiplication via the nb_inplace_multiply slot.

Buffer Object Structures

PyBufferProcs

This structure holds pointers to the functions required by the Buffer protocol. The protocol defines how an exporter object can expose its internal data to consumer objects.

getbufferproc PyBufferProcs.bf_getbuffer

The signature of this function is:

int (PyObject *exporter, Py_buffer *view, int flags);

Handle a request to exporter to fill in view as specified by flags. Except for point (3), an implementation of this function MUST take these steps:

Check if the request can be met. If not, raise PyExc_BufferError, set view->obj to NULL and return -1.

Fill in the requested fields.

Increment an internal counter for the number of exports.

Set view->obj to exporter and increment view->obj.

Return 0.

If exporter is part of a chain or tree of buffer providers, two main schemes can be used:

Re-export: Each member of the tree acts as the exporting object and sets view->obj to a new reference to itself.

Redirect: The buffer request is redirected to the root object of the tree. Here, view->obj will be a new reference to the root object.

The individual fields of view are described in section Buffer structure, the rules how an exporter must react to specific requests are in section Buffer request types.

All memory pointed to in the Py_buffer structure belongs to the exporter and must remain valid until there are no consumers left. format, shape, strides, suboffsets and internal are read-only for the consumer.

PyBuffer_FillInfo() provides an easy way of exposing a simple bytes buffer while dealing correctly with all request types.

PyObject_GetBuffer() is the interface for the consumer that wraps this function.

releasebufferproc PyBufferProcs.bf_releasebuffer

The signature of this function is:

void (PyObject *exporter, Py_buffer *view);

Handle a request to release the resources of the buffer. If no resources need to be released, PyBufferProcs.bf_releasebuffer may be NULL. Otherwise, a standard implementation of this function will take these optional steps:

Decrement an internal counter for the number of exports.

If the counter is 0, free all memory associated with view.

The exporter MUST use the internal field to keep track of buffer-specific resources. This field is guaranteed to remain constant, while a consumer MAY pass a copy of the original buffer as the view argument.

This function MUST NOT decrement view->obj, since that is done automatically in PyBuffer_Release() (this scheme is useful for breaking reference cycles).

PyBuffer_Release() is the interface for the consumer that wraps this function.

Async Object Structures

버전 3.5에 추가.

PyAsyncMethods

This structure holds pointers to the functions required to implement awaitable and asynchronous iterator objects.

Here is the structure definition:

typedef struct {
    unaryfunc am_await;
    unaryfunc am_aiter;
    unaryfunc am_anext;
} PyAsyncMethods;

unaryfunc PyAsyncMethods.am_await

The signature of this function is:

PyObject *am_await(PyObject *self)

The returned object must be an iterator, i.e. PyIter_Check() must return 1 for it.

This slot may be set to NULL if an object is not an awaitable.

unaryfunc PyAsyncMethods.am_aiter

The signature of this function is:

PyObject *am_aiter(PyObject *self)

Must return an awaitable object. See __anext__() for details.

This slot may be set to NULL if an object does not implement asynchronous iteration protocol.

unaryfunc PyAsyncMethods.am_anext

The signature of this function is:

PyObject *am_anext(PyObject *self)

Must return an awaitable object. See __anext__() for details. This slot may be set to NULL.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

객체 구현 지원 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

객체 구현 지원 »

|

순환 가비지 수집 지원

순환 참조를 포함하는 가비지를 탐지하고 수집하는 파이썬의 지원은 역시 컨테이너일 수 있는 다른 객체의 “컨테이너” 인 객체 형의 지원이 필요합니다. 다른 객체에 대한 참조를 저장하지 않거나, 원자 형(가령 숫자나 문자열)에 대한 참조만 저장하는 형은 가비지 수집에 대한 어떤 명시적인 지원을 제공할 필요가 없습니다.

컨테이너형을 만들려면, 형 객체의 tp_flags 필드가 Py_TPFLAGS_HAVE_GC를 포함해야 하고 tp_traverse 처리기 구현을 제공해야 합니다. 형의 인스턴스가 가변이면, tp_clear 구현도 제공해야 합니다.

Py_TPFLAGS_HAVE_GC

이 플래그가 설정된 형의 객체는 여기에 설명된 규칙을 준수해야 합니다. 편의를 위해 이러한 객체를 컨테이너 객체라고 하겠습니다.

컨테이너형의 생성자는 두 가지 규칙을 준수해야 합니다:

객체의 메모리는 PyObject_GC_New() 나 PyObject_GC_NewVar()를 사용하여 할당해야 합니다.

다른 컨테이너에 대한 참조를 포함할 수 있는 모든 필드가 초기화되면, PyObject_GC_Track()를 호출해야 합니다.

TYPE* PyObject_GC_New(TYPE, PyTypeObject *type)

PyObject_New()와 유사하지만, Py_TPFLAGS_HAVE_GC 플래그가 설정된 컨테이너 객체를 위한 것.

TYPE* PyObject_GC_NewVar(TYPE, PyTypeObject *type, Py_ssize_t size)

PyObject_NewVar()와 유사하지만, Py_TPFLAGS_HAVE_GC 플래그가 설정된 컨테이너 객체를 위한 것.

TYPE* PyObject_GC_Resize(TYPE, PyVarObject *op, Py_ssize_t newsize)

Resize an object allocated by PyObject_NewVar(). Returns the resized object or NULL on failure. op must not be tracked by the collector yet.

void PyObject_GC_Track(PyObject *op)

수집기가 추적하는 컨테이너 객체 집합에 객체 op를 추가합니다. 수집기는 예기치 않은 시간에 실행될 수 있으므로 추적되는 동안 객체가 유효해야 합니다. tp_traverse 처리기가 탐색하는 모든 필드가 유효해지면 호출해야 합니다, 보통 생성자의 끝부분 근처입니다.

void _PyObject_GC_TRACK(PyObject *op)

PyObject_GC_Track()의 매크로 버전. 확장 모듈에는 사용하지 말아야 합니다.

버전 3.6부터 폐지: 이 매크로는 파이썬 3.8에서 삭제되었습니다.

마찬가지로, 객체의 할당해제자(deallocator)는 비슷한 규칙 쌍을 준수해야 합니다:

다른 컨테이너를 참조하는 필드가 무효화 되기 전에, PyObject_GC_UnTrack()를 호출해야 합니다.

객체의 메모리는 PyObject_GC_Del()를 사용하여 할당 해제되어야 합니다.

void PyObject_GC_Del(void *op)

PyObject_GC_New() 나 PyObject_GC_NewVar()를 사용하여 객체에 할당된 메모리를 해제합니다.

void PyObject_GC_UnTrack(void *op)

수집기가 추적하는 컨테이너 객체 집합에서 op 객체를 제거합니다. PyObject_GC_Track()를 이 객체에 대해 다시 호출하여 추적 객체 집합에 다시 추가할 수 있음에 유의하십시오. 할당해제자(tp_dealloc 처리기)는 tp_traverse 처리기에서 사용하는 필드가 무효화 되기 전에 객체에 대해 이 함수를 호출해야 합니다.

void _PyObject_GC_UNTRACK(PyObject *op)

PyObject_GC_UnTrack()의 매크로 버전. 확장 모듈에는 사용하지 말아야 합니다.

버전 3.6부터 폐지: 이 매크로는 파이썬 3.8에서 삭제되었습니다.

tp_traverse 처리기는 다음과 같은 형의 함수 매개 변수를 받아들입니다:

int (*visitproc)(PyObject *object, void *arg)

tp_traverse 처리기에 전달되는 방문자 함수의 형. 이 함수는 탐색하는 객체를 object로, tp_traverse 처리기의 세 번째 매개 변수를 arg로 호출되어야 합니다. 파이썬 코어는 순환 가비지 탐지를 구현하기 위해 여러 방문자 함수를 사용합니다; 사용자가 자신의 방문자 함수를 작성해야 할 필요는 없습니다.

tp_traverse 처리기는 다음 형이어야 합니다:

int (*traverseproc)(PyObject *self, visitproc visit, void *arg)

Traversal function for a container object. Implementations must call the visit function for each object directly contained by self, with the parameters to visit being the contained object and the arg value passed to the handler. The visit function must not be called with a NULL object argument. If visit returns a non-zero value that value should be returned immediately.

tp_traverse 처리기 작성을 단순화하기 위해, Py_VISIT() 매크로가 제공됩니다. 이 매크로를 사용하려면, tp_traverse 구현은 인자의 이름을 정확히 visit 와 arg로 지정해야 합니다:

void Py_VISIT(PyObject *o)

If o is not NULL, call the visit callback, with arguments o and arg. If visit returns a non-zero value, then return it. Using this macro, tp_traverse handlers look like:

static int
my_traverse(Noddy *self, visitproc visit, void *arg)
{
    Py_VISIT(self->foo);
    Py_VISIT(self->bar);
    return 0;
}

The tp_clear handler must be of the inquiry type, or NULL if the object is immutable.

int (*inquiry)(PyObject *self)

참조 순환을 생성했을 수 있는 참조를 삭제합니다. 불변 객체는 참조 순환을 직접 생성할 수 없으므로, 이 메서드를 정의 할 필요가 없습니다. 이 메서드를 호출한 후에도 객체가 유효해야 합니다 (단지 참조에 대해 Py_DECREF()를 호출하지 마십시오). 이 객체가 참조 순환에 참여하고 있음을 수집기가 감지하면 이 메서드를 호출합니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

객체 구현 지원 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

|

API와 ABI 버전 붙이기

PY_VERSION_HEX는 단일 정수로 인코딩된 파이썬 버전 번호입니다.

예를 들어 PY_VERSION_HEX가 0x030401a2로 설정되면, 기본 버전 정보는 다음과 같은 방식으로 32비트 숫자로 처리하여 찾을 수 있습니다:

바이트

비트 (빅 엔디안 순서)

뜻

1

1-8

PY_MAJOR_VERSION (3.4.1a2의 3)

2

9-16

PY_MINOR_VERSION (3.4.1a2의 4)

3

17-24

PY_MICRO_VERSION (3.4.1a2의 1)

4

25-28

PY_RELEASE_LEVEL (알파는 0xA, 베타는 0xB, 배포 후보는 0xC, 최종은 0xF). 이 예에서는 알파입니다.

29-32

PY_RELEASE_SERIAL (3.4.1a2의 2, 최종 배포는 0)

따라서 3.4.1a2는 16진수 버전 0x030401a2입니다.

모든 주어진 매크로는 Include/patchlevel.h [https://github.com/python/cpython/tree/3.7/Include/patchlevel.h]에 정의됩니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬/C API 레퍼런스 설명서 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

|

파이썬 모듈 배포하기

이메일

distutils-sig@python.org

널리 사용되는 공개 소스 개발 프로젝트로서, 파이썬에는 적극적으로 지원하는 기여자와 사용자의 커뮤니티가 있어, 자신들의 소프트웨어를 공개 소스 라이센스 계약에 따라 다른 파이썬 개발자가 사용할 수 있도록 합니다.

이를 통해 파이썬 사용자는 효과적으로 공유하고 공동 작업할 수 있으며, 다른 사람들이 공통 (심지어 때로는 희귀한) 문제에 대해 이미 만든 솔루션의 이점을 누릴 수 있을 뿐 아니라, 자체 솔루션을 공동 풀에 잠재적으로 제공할 수 있습니다.

이 지침서는 이 절차의 배포 부분을 다룹니다. 다른 파이썬 프로젝트를 설치하는 지침은 설치 지침서 를 참조하십시오.

참고

기업 및 기타 기관 사용자의 경우, 많은 조직에서 공개 소스 소프트웨어를 사용하고 공헌하는 데 대한 자체 정책을 시행하고 있음을 알고 있어야 합니다. 파이썬과 함께 제공되는 배포 및 설치 도구를 사용할 때 이러한 정책을 고려하십시오.

핵심 용어

파이썬 패키지 색인 [https://pypi.org] 은 다른 파이썬 사용자가 사용할 수 있도록 만들어진 공개 소스 라이선스 패키지의 공용 저장소입니다.

the Python Packaging Authority [https://www.pypa.io/] are the group of developers and documentation authors responsible for the maintenance and evolution of the standard packaging tools and the associated metadata and file format standards. They maintain a variety of tools, documentation and issue trackers on both GitHub [https://github.com/pypa] and Bitbucket [https://bitbucket.org/pypa/].

distutils 는 1998년에 파이썬 표준 라이브러리에 처음 추가된 최초의 빌드 및 배포 시스템입니다. distutils 의 직접 사용이 단계적으로 폐지되고 있지만, 여전히 현재의 패키징 및 배포 기반 시설의 기초를 이루고 있고, 표준 라이브러리의 일부로 남아있을 뿐만 아니라, 그 이름은 다른 방식으로도 (가령 파이썬 패키징 표준 개발을 조정하는 데 사용되는 메일링 리스트의 이름으로) 남아있습니다.

setuptools [https://setuptools.readthedocs.io/en/latest/] 는 2004년에 처음 공개된, distutils 에 대한 (거의) 드롭인(drop-in) 대체품입니다. 수정되지 않은 distutils 도구와 비교할 때, 가장 주목할만한 추가는 다른 패키지에 대한 의존성을 선언할 수 있는 능력이었습니다. 현재, distutils 에 대한 보다 정기적으로 업데이트되는 대안으로 추천되는데, 광범위한 파이썬 버전에서 최근 패키징 표준을 더 일관성 있게 지원합니다.

wheel [https://wheel.readthedocs.io/](이 문맥에서)은 distutils/setuptools [https://setuptools.readthedocs.io/en/latest/] 에 bdist_wheel 명령을 추가하는 프로젝트입니다. 이것은 파이썬 라이브러리를, 바이너리 확장을 포함한 것이라도, 로컬에서 빌드될 필요 없이 시스템에 설치될 수 있게 해주는 크로스 플랫폼 바이너리 패키징 형식(“휠” 이나 “휠 파일”로 불리고, PEP 427 [https://www.python.org/dev/peps/pep-0427]에서 정의됩니다)을 생성합니다.

공개 소스 라이센스 와 협업

전 세계 대부분 지역에서, 소프트웨어는 자동으로 저작권의 보호를 받습니다. 즉, 다른 개발자가 소프트웨어를 복사, 사용, 수정 및 재배포하기 위해서는 명시적 허락이 필요합니다.

공개 소스 라이선스는 상대적으로 일관된 방식으로 그러한 허락을 명시적으로 부여하는 방법으로, 다양한 문제에 대한 공통 솔루션을 자유롭게 만듦으로써 개발자가 효율적으로 공유하고 협업할 수 있게 합니다. 이로 인해 많은 개발자는 자신의 특정 상황에 상대적으로 고유한 문제에 집중하는 시간을 더 많이 할애할 수 있습니다.

파이썬과 함께 제공되는 배포 도구는 개발자가 그렇게 하고자 할 때 소프트웨어의 공통 풀로 다시 기여하는 것을 합리적으로 손쉽게 만들도록 설계되었습니다.

같은 배포 도구는, 공개 소스 소프트웨어로 게시되는지에 관계없이, 소프트웨어를 조직 내에서 배포하는데 사용될 수도 있습니다.

도구 설치하기

표준 라이브러리에는 최신 파이썬 패키징 표준을 지원하는 빌드 도구가 포함되어 있지 않습니다. 핵심 개발팀이 파이썬의 이전 버전에서도 일관되게 작동하는 표준 도구를 갖는 것이 중요하다는 사실을 발견했기 때문입니다.

현재 권장되는 빌드 및 배포 도구는 명령 줄에서 pip 모듈을 호출하여 설치할 수 있습니다:

python -m pip install setuptools wheel twine

참고

POSIX 사용자(맥 OS X 와 리눅스 사용자를 포함합니다)의 경우, 이 지침은 가상 환경 을 사용한다고 가정합니다.

윈도우 사용자의 경우, 이 지침은 파이썬을 설치할 때 시스템 PATH 환경 변수를 조정하는 옵션이 선택되었다고 가정합니다.

파이썬 패키징 사용자 지침서에는 현재 권장되는 도구 [https://packaging.python.org/guides/tool-recommendations/#packaging-tool-recommendations] 에 대한 자세한 내용이 들어 있습니다.

파이썬 패키징 사용자 지침서 읽기

파이썬 패키징 사용자 지침서는 프로젝트를 만들고 출판하는 것에 관련된 다양한 핵심 단계와 요소를 다루고 있습니다:

프로젝트 구조

프로젝트들 빌드하고 패키징하기

프로젝트를 파이썬 패키지 색인에 올리기

어떻게 …?

이것들은 몇 가지 일반적인 작업에 대한 빠른 답변 또는 링크입니다.

… 내 프로젝트의 이름을 고릅니까?

이것이 쉬운 주제는 아니지만, 여기 몇 가지 팁이 있습니다:

파이썬 패키지 색인을 검사해서 이름이 이미 사용 중인지 확인하십시오

check popular hosting sites like GitHub, Bitbucket, etc to see if there is already a project with that name

고려 중인 이름으로 웹 검색에서 뭐가 나오는지 확인하십시오

특히 흔한 단어(특히 여러 의미가 있는 단어)는 피해야 합니다, 사용자가 여러분의 소프트웨어를 검색할 때 찾기 어렵게 만들기 때문입니다

… 바이너리 확장을 만들고 배포합니까?

이것은 정확히 당신이 달성하고자 하는 목표에 따라 다양한 대안을 사용할 수 있는 실제로 꽤 복잡한 주제입니다. 자세한 정보와 권장 사항은 파이썬 패키징 사용자 지침서를 참조하십시오.

더 보기

파이썬 패키징 사용자 지침서: 바이너리 확장 [https://packaging.python.org/guides/packaging-binary-extensions/]

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

|

파이썬 모듈 설치하기

이메일

distutils-sig@python.org

널리 사용되는 공개 소스 개발 프로젝트로서, 파이썬에는 적극적으로 지원하는 기여자와 사용자의 커뮤니티가 있어, 자신들의 소프트웨어를 공개 소스 라이센스 계약에 따라 다른 파이썬 개발자가 사용할 수 있도록 합니다.

이를 통해 파이썬 사용자는 효과적으로 공유하고 공동 작업할 수 있으며, 다른 사람들이 공통 (심지어 때로는 희귀한) 문제에 대해 이미 만든 솔루션의 이점을 누릴 수 있을 뿐 아니라, 자체 솔루션을 공동 풀에 잠재적으로 제공할 수 있습니다.

이 지침서는 이 절차의 설치 부분을 다룹니다. 자신의 파이썬 프로젝트를 만들고 공유하는 지침은 배포 지침서 를 참조하십시오.

참고

기업 및 기타 기관 사용자의 경우, 많은 조직에서 공개 소스 소프트웨어를 사용하고 공헌하는 데 대한 자체 정책을 시행하고 있음을 알고 있어야 합니다. 파이썬과 함께 제공되는 배포 및 설치 도구를 사용할 때 이러한 정책을 고려하십시오.

핵심 용어

pip 는 선호되는 설치 프로그램입니다. 파이썬 3.4부터, 기본적으로 파이썬 바이너리 설치 프로그램에 포함되어 있습니다.

가상 환경 은 패키지가 시스템 전체에 설치되는 것이 아니라, 특정 응용 프로그램에 사용되도록 설치될 수 있도록 하는 반 격리 된 파이썬 환경입니다.

venv 는 가상 환경을 만들기 위한 표준 도구이며, 파이썬 3.3 이후로 파이썬의 일부입니다. 파이썬 3.4부터, 생성되는 모든 가상 환경에 기본적으로 pip 를 설치합니다.

virtualenv 는 venv 에 대한 제삼자 대안(그리고 전임자)입니다. venv 를 아예 제공하지 않거나, 생성되는 환경에 pip 를 자동으로 설치할 수 없는, 3.4 이전의 파이썬 버전에서 가상 환경을 사용할 수 있도록 합니다.

파이썬 패키지 색인 [https://pypi.org] 은 다른 파이썬 사용자가 사용할 수 있도록 만들어진 공개 소스 라이선스 패키지의 공용 저장소입니다.

the Python Packaging Authority [https://www.pypa.io/] is the group of developers and documentation authors responsible for the maintenance and evolution of the standard packaging tools and the associated metadata and file format standards. They maintain a variety of tools, documentation, and issue trackers on both GitHub [https://github.com/pypa] and Bitbucket [https://bitbucket.org/pypa/].

distutils 는 1998년에 파이썬 표준 라이브러리에 처음 추가된 최초의 빌드 및 배포 시스템입니다. distutils 의 직접 사용이 단계적으로 폐지되고 있지만, 여전히 현재의 패키징 및 배포 기반 시설의 기초를 이루고 있고, 표준 라이브러리의 일부로 남아있을 뿐만 아니라, 그 이름은 다른 방식으로도 (가령 파이썬 패키징 표준 개발을 조정하는 데 사용되는 메일링 리스트의 이름으로) 남아있습니다.

버전 3.6부터 폐지: pyvenv 는 파이썬 3.3과 3.4에서 가상 환경을 만드는 데 추천되는 도구였으며 파이썬 3.6에서 폐지되었습니다 [https://docs.python.org/dev/whatsnew/3.6.html#deprecated-features].

버전 3.5에서 변경: 이제 가상 환경을 만드는데 venv 사용을 권장합니다.

더 보기

파이썬 패키징 사용자 지침서: 가상 환경 생성과 사용 [https://packaging.python.org/installing/#creating-virtual-environments]

기본 사용법

표준 패키징 도구는 모두 명령 줄에서 사용하도록 설계되었습니다.

다음 명령은 파이썬 패키지 색인에서 최신 버전의 모듈과 그 의존성을 설치합니다:

python -m pip install SomePackage

참고

POSIX 사용자(맥 OS X 와 리눅스 사용자를 포함합니다)의 경우, 이 지침서의의 예제는 가상 환경 을 사용한다고 가정합니다.

윈도우 사용자의 경우, 이 지침서의 예제는 파이썬을 설치할 때 시스템 PATH 환경 변수를 조정하는 옵션이 선택되었다고 가정합니다.

정확한 버전이나 최소 버전을 명령 줄에서 직접 지정할 수도 있습니다. >, < 와 같은 비교 연산자나 셸에서 해석되는 다른 특수 문자를 사용할 때는, 패키지 이름과 버전을 큰따옴표로 묶어야 합니다:

python -m pip install SomePackage==1.0.4    # specific version
python -m pip install "SomePackage>=1.0.4"  # minimum version

일반적으로, 적절한 모듈이 이미 설치되어있으면, 다시 설치하려고 해도 아무런 효과가 없습니다. 기존 모듈을 업그레이드하려면 명시적으로 요청해야 합니다:

python -m pip install --upgrade SomePackage

pip 와 그 기능에 관한 더 많은 정보와 자원은 파이썬 패키징 사용자 지침서 [https://packaging.python.org] 에서 찾을 수 있습니다.

가상 환경의 생성은 venv 모듈을 통해 수행됩니다. 활성 가상 환경에 패키지를 설치하려면 위에 표시된 명령을 사용합니다.

더 보기

파이썬 패키징 사용자 지침서: 파이썬 배포 패키지 설치하기 [https://packaging.python.org/installing/]

어떻게 …?

이것들은 몇 가지 일반적인 작업에 대한 빠른 답변 또는 링크입니다.

… 파이썬 3.4 이전 버전의 파이썬에서 pip 를 설치합니까?

파이썬은 pip 를 파이썬 3.4에 와서야 포함하기 시작했습니다. 이전 버전의 경우, pip 는 파이썬 패키징 사용자 지침서에 설명된 대로 “부트스트랩(bootstrapped)” 될 필요가 있습니다.

더 보기

파이썬 패키징 사용자 지침서: 패키지 설치 요구 사항 [https://packaging.python.org/installing/#requirements-for-installing-packages]

… 현재 사용자만을 위해 패키지를 설치합니까?

--user 옵션을 python -m pip install 에 넘겨주면 시스템의 모든 사용자가 아닌 현재 사용자를 위해서만 패키지를 설치합니다.

… 과학 계산용 파이썬 패키지를 설치합니까?

많은 과학 계산용 파이썬 패키지는 복잡한 바이너리 의존성을 가지고 있고, 현재 pip 를 사용하여 직접 설치하기가 쉽지 않습니다. 이 시점에서, 사용자가 이 패키지들을 pip 로 설치하려고 시도하는 것보다 다른 방법 [https://packaging.python.org/science/] 으로 설치하는 것이 더 쉬운 경우가 종종 있습니다.

더 보기

파이썬 패키징 사용자 지침서: 과학 계산용 패키지 설치하기 [https://packaging.python.org/science/]

… 병렬로 설치된 여러 버전의 파이썬으로 작업합니까?

리눅스, 맥 OS X 및 다른 POSIX 시스템에서는, 버전이 지정된 파이썬 명령을 -m 스위치와 조합하여 적절한 pip 사본을 실행하십시오:

python2   -m pip install SomePackage  # default Python 2
python2.7 -m pip install SomePackage  # specifically Python 2.7
python3   -m pip install SomePackage  # default Python 3
python3.4 -m pip install SomePackage  # specifically Python 3.4

적절히 버전이 지정된 pip 명령도 제공될 수 있습니다.

윈도우에서는 py 파이썬 실행기를 -m 스위치와 조합해서 사용하십시오:

py -2   -m pip install SomePackage  # default Python 2
py -2.7 -m pip install SomePackage  # specifically Python 2.7
py -3   -m pip install SomePackage  # default Python 3
py -3.4 -m pip install SomePackage  # specifically Python 3.4

흔히 만나는 설치 문제

리눅스에 시스템 파이썬 설치하기

리눅스 시스템에서, 보통 파이썬 설치가 배포 일부로 포함됩니다. 이 파이썬 설치에 설치하려면 시스템에 대한 루트 액세스가 필요하며, pip 를 사용하여 구성 요소가 예기치 않게 업그레이드되면 시스템 패키지 관리자와 시스템의 다른 구성 요소의 작동을 방해할 수 있습니다.

이러한 시스템에서는, pip 로 패키지를 설치할 때 가상 환경이나 사용자별 설치를 사용하는 것이 더 좋습니다.

Pip가 설치되지 않았습니다.

pip 가 기본적으로 설치되지 않았을 수도 있습니다. 한가지 가능한 해결법은 다음과 같습니다:

python -m ensurepip --default-pip

pip 설치 [https://packaging.python.org/tutorials/installing-packages/#install-pip-setuptools-and-wheel] 에 대한 추가 자원도 있습니다.

바이너리 확장 설치하기

파이썬은 일반적으로 소스 기반 배포에 크게 의존하고 있으며, 최종 사용자가 설치 프로세스의 일부로 소스로부터 확장 모듈을 컴파일할 것으로 기대합니다.

바이너리 wheel 형식에 대한 지원의 도입과 파이썬 패키지 색인을 통해 적어도 윈도우와 맥 OS X 용의 휠을 게시할 수 있게 됨에 따라, 사용자가 스스로 빌드하기 보다는 점차 사전 빌드된 확장들을 설치할 수 있게 되어, 이 문제는 시간이 지날수록 줄어들 것으로 예상합니다.

wheel 파일로 아직 사용할 수 없는 과학 계산용 소프트웨어 [https://packaging.python.org/science/] 설치를 위한 어떤 해결책들은 로컬에서 빌드할 필요 없이 다른 바이너리 확장을 얻는 데 도움이 될 수 있습니다.

더 보기

파이썬 패키징 사용자 지침서: 바이너리 확장 [https://packaging.python.org/extensions/]

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

|

파이썬 HOWTO

파이썬 HOWTO 는 구체적인 한 가지 주제를 상당히 완전하게 다루려고 시도하는 문서입니다. 리눅스 설명서 프로젝트의 HOWTO 컬렉션을 모델로 삼아, 이 컬렉션은 파이썬 라이브러리 레퍼런스보다 자세한 문서를 작성하기 위한 노력입니다.

현재, 준비된 HOWTO 들입니다:

Porting Python 2 Code to Python 3

확장 모듈을 파이썬 3에 이식하기

Curses Programming with Python

Descriptor HowTo Guide

함수형 프로그래밍 HOWTO

로깅 HOWTO

로깅 요리책

Regular Expression HOWTO

소켓 프로그래밍 HOWTO

정렬 HOW TO

유니코드 HOWTO

HOWTO Fetch Internet Resources Using The urllib Package

Argparse 자습서

ipaddress 모듈에 대한 소개

Argument Clinic How-To

DTrace와 SystemTap으로 CPython 계측하기

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 HOWTO »

|

Porting Python 2 Code to Python 3

author

Brett Cannon

Abstract

With Python 3 being the future of Python while Python 2 is still in active use, it is good to have your project available for both major releases of Python. This guide is meant to help you figure out how best to support both Python 2 & 3 simultaneously.

If you are looking to port an extension module instead of pure Python code, please see 확장 모듈을 파이썬 3에 이식하기.

If you would like to read one core Python developer’s take on why Python 3 came into existence, you can read Nick Coghlan’s Python 3 Q & A [https://ncoghlan-devs-python-notes.readthedocs.io/en/latest/python3/questions_and_answers.html] or Brett Cannon’s Why Python 3 exists [https://snarky.ca/why-python-3-exists].

For help with porting, you can email the python-porting [https://mail.python.org/mailman/listinfo/python-porting] mailing list with questions.

The Short Explanation

To make your project be single-source Python 2/3 compatible, the basic steps are:

Only worry about supporting Python 2.7

Make sure you have good test coverage (coverage.py [https://pypi.org/project/coverage] can help; pip install coverage)

Learn the differences between Python 2 & 3

Use Futurize [http://python-future.org/automatic_conversion.html] (or Modernize [https://python-modernize.readthedocs.io/]) to update your code (e.g. pip install future)

Use Pylint [https://pypi.org/project/pylint] to help make sure you don’t regress on your Python 3 support (pip install pylint)

Use caniusepython3 [https://pypi.org/project/caniusepython3] to find out which of your dependencies are blocking your use of Python 3 (pip install caniusepython3)

Once your dependencies are no longer blocking you, use continuous integration to make sure you stay compatible with Python 2 & 3 (tox [https://pypi.org/project/tox] can help test against multiple versions of Python; pip install tox)

Consider using optional static type checking to make sure your type usage works in both Python 2 & 3 (e.g. use mypy [http://mypy-lang.org/] to check your typing under both Python 2 & Python 3).

Details

A key point about supporting Python 2 & 3 simultaneously is that you can start today! Even if your dependencies are not supporting Python 3 yet that does not mean you can’t modernize your code now to support Python 3. Most changes required to support Python 3 lead to cleaner code using newer practices even in Python 2 code.

Another key point is that modernizing your Python 2 code to also support Python 3 is largely automated for you. While you might have to make some API decisions thanks to Python 3 clarifying text data versus binary data, the lower-level work is now mostly done for you and thus can at least benefit from the automated changes immediately.

Keep those key points in mind while you read on about the details of porting your code to support Python 2 & 3 simultaneously.

Drop support for Python 2.6 and older

While you can make Python 2.5 work with Python 3, it is much easier if you only have to work with Python 2.7. If dropping Python 2.5 is not an option then the six [https://pypi.org/project/six] project can help you support Python 2.5 & 3 simultaneously (pip install six). Do realize, though, that nearly all the projects listed in this HOWTO will not be available to you.

If you are able to skip Python 2.5 and older, then the required changes to your code should continue to look and feel like idiomatic Python code. At worst you will have to use a function instead of a method in some instances or have to import a function instead of using a built-in one, but otherwise the overall transformation should not feel foreign to you.

But you should aim for only supporting Python 2.7. Python 2.6 is no longer freely supported and thus is not receiving bugfixes. This means you will have to work around any issues you come across with Python 2.6. There are also some tools mentioned in this HOWTO which do not support Python 2.6 (e.g., Pylint [https://pypi.org/project/pylint]), and this will become more commonplace as time goes on. It will simply be easier for you if you only support the versions of Python that you have to support.

Make sure you specify the proper version support in your setup.py file

In your setup.py file you should have the proper trove classifier [https://pypi.org/classifiers] specifying what versions of Python you support. As your project does not support Python 3 yet you should at least have Programming Language :: Python :: 2 :: Only specified. Ideally you should also specify each major/minor version of Python that you do support, e.g. Programming Language :: Python :: 2.7.

Have good test coverage

Once you have your code supporting the oldest version of Python 2 you want it to, you will want to make sure your test suite has good coverage. A good rule of thumb is that if you want to be confident enough in your test suite that any failures that appear after having tools rewrite your code are actual bugs in the tools and not in your code. If you want a number to aim for, try to get over 80% coverage (and don’t feel bad if you find it hard to get better than 90% coverage). If you don’t already have a tool to measure test coverage then coverage.py [https://pypi.org/project/coverage] is recommended.

Learn the differences between Python 2 & 3

Once you have your code well-tested you are ready to begin porting your code to Python 3! But to fully understand how your code is going to change and what you want to look out for while you code, you will want to learn what changes Python 3 makes in terms of Python 2. Typically the two best ways of doing that is reading the “What’s New” doc for each release of Python 3 and the Porting to Python 3 [http://python3porting.com/] book (which is free online). There is also a handy cheat sheet [http://python-future.org/compatible_idioms.html] from the Python-Future project.

Update your code

Once you feel like you know what is different in Python 3 compared to Python 2, it’s time to update your code! You have a choice between two tools in porting your code automatically: Futurize [http://python-future.org/automatic_conversion.html] and Modernize [https://python-modernize.readthedocs.io/]. Which tool you choose will depend on how much like Python 3 you want your code to be. Futurize [http://python-future.org/automatic_conversion.html] does its best to make Python 3 idioms and practices exist in Python 2, e.g. backporting the bytes type from Python 3 so that you have semantic parity between the major versions of Python. Modernize [https://python-modernize.readthedocs.io/], on the other hand, is more conservative and targets a Python 2/3 subset of Python, directly relying on six [https://pypi.org/project/six] to help provide compatibility. As Python 3 is the future, it might be best to consider Futurize to begin adjusting to any new practices that Python 3 introduces which you are not accustomed to yet.

Regardless of which tool you choose, they will update your code to run under Python 3 while staying compatible with the version of Python 2 you started with. Depending on how conservative you want to be, you may want to run the tool over your test suite first and visually inspect the diff to make sure the transformation is accurate. After you have transformed your test suite and verified that all the tests still pass as expected, then you can transform your application code knowing that any tests which fail is a translation failure.

Unfortunately the tools can’t automate everything to make your code work under Python 3 and so there are a handful of things you will need to update manually to get full Python 3 support (which of these steps are necessary vary between the tools). Read the documentation for the tool you choose to use to see what it fixes by default and what it can do optionally to know what will (not) be fixed for you and what you may have to fix on your own (e.g. using io.open() over the built-in open() function is off by default in Modernize). Luckily, though, there are only a couple of things to watch out for which can be considered large issues that may be hard to debug if not watched for.

Division

In Python 3, 5 / 2 == 2.5 and not 2; all division between int values result in a float. This change has actually been planned since Python 2.2 which was released in 2002. Since then users have been encouraged to add from __future__ import division to any and all files which use the / and // operators or to be running the interpreter with the -Q flag. If you have not been doing this then you will need to go through your code and do two things:

Add from __future__ import division to your files

Update any division operator as necessary to either use // to use floor division or continue using / and expect a float

The reason that / isn’t simply translated to // automatically is that if an object defines a __truediv__ method but not __floordiv__ then your code would begin to fail (e.g. a user-defined class that uses / to signify some operation but not // for the same thing or at all).

Text versus binary data

In Python 2 you could use the str type for both text and binary data. Unfortunately this confluence of two different concepts could lead to brittle code which sometimes worked for either kind of data, sometimes not. It also could lead to confusing APIs if people didn’t explicitly state that something that accepted str accepted either text or binary data instead of one specific type. This complicated the situation especially for anyone supporting multiple languages as APIs wouldn’t bother explicitly supporting unicode when they claimed text data support.

To make the distinction between text and binary data clearer and more pronounced, Python 3 did what most languages created in the age of the internet have done and made text and binary data distinct types that cannot blindly be mixed together (Python predates widespread access to the internet). For any code that deals only with text or only binary data, this separation doesn’t pose an issue. But for code that has to deal with both, it does mean you might have to now care about when you are using text compared to binary data, which is why this cannot be entirely automated.

To start, you will need to decide which APIs take text and which take binary (it is highly recommended you don’t design APIs that can take both due to the difficulty of keeping the code working; as stated earlier it is difficult to do well). In Python 2 this means making sure the APIs that take text can work with unicode and those that work with binary data work with the bytes type from Python 3 (which is a subset of str in Python 2 and acts as an alias for bytes type in Python 2). Usually the biggest issue is realizing which methods exist on which types in Python 2 & 3 simultaneously (for text that’s unicode in Python 2 and str in Python 3, for binary that’s str/bytes in Python 2 and bytes in Python 3). The following table lists the unique methods of each data type across Python 2 & 3 (e.g., the decode() method is usable on the equivalent binary data type in either Python 2 or 3, but it can’t be used by the textual data type consistently between Python 2 and 3 because str in Python 3 doesn’t have the method). Do note that as of Python 3.5 the __mod__ method was added to the bytes type.

Text data

Binary data

decode

encode

format

isdecimal

isnumeric

Making the distinction easier to handle can be accomplished by encoding and decoding between binary data and text at the edge of your code. This means that when you receive text in binary data, you should immediately decode it. And if your code needs to send text as binary data then encode it as late as possible. This allows your code to work with only text internally and thus eliminates having to keep track of what type of data you are working with.

The next issue is making sure you know whether the string literals in your code represent text or binary data. You should add a b prefix to any literal that presents binary data. For text you should add a u prefix to the text literal. (there is a __future__ import to force all unspecified literals to be Unicode, but usage has shown it isn’t as effective as adding a b or u prefix to all literals explicitly)

As part of this dichotomy you also need to be careful about opening files. Unless you have been working on Windows, there is a chance you have not always bothered to add the b mode when opening a binary file (e.g., rb for binary reading). Under Python 3, binary files and text files are clearly distinct and mutually incompatible; see the io module for details. Therefore, you must make a decision of whether a file will be used for binary access (allowing binary data to be read and/or written) or textual access (allowing text data to be read and/or written). You should also use io.open() for opening files instead of the built-in open() function as the io module is consistent from Python 2 to 3 while the built-in open() function is not (in Python 3 it’s actually io.open()). Do not bother with the outdated practice of using codecs.open() as that’s only necessary for keeping compatibility with Python 2.5.

The constructors of both str and bytes have different semantics for the same arguments between Python 2 & 3. Passing an integer to bytes in Python 2 will give you the string representation of the integer: bytes(3) == '3'. But in Python 3, an integer argument to bytes will give you a bytes object as long as the integer specified, filled with null bytes: bytes(3) == b'\x00\x00\x00'. A similar worry is necessary when passing a bytes object to str. In Python 2 you just get the bytes object back: str(b'3') == b'3'. But in Python 3 you get the string representation of the bytes object: str(b'3') == "b'3'".

Finally, the indexing of binary data requires careful handling (slicing does not require any special handling). In Python 2, b'123'[1] == b'2' while in Python 3 b'123'[1] == 50. Because binary data is simply a collection of binary numbers, Python 3 returns the integer value for the byte you index on. But in Python 2 because bytes == str, indexing returns a one-item slice of bytes. The six [https://pypi.org/project/six] project has a function named six.indexbytes() which will return an integer like in Python 3: six.indexbytes(b'123', 1).

To summarize:

Decide which of your APIs take text and which take binary data

Make sure that your code that works with text also works with unicode and code for binary data works with bytes in Python 2 (see the table above for what methods you cannot use for each type)

Mark all binary literals with a b prefix, textual literals with a u prefix

Decode binary data to text as soon as possible, encode text as binary data as late as possible

Open files using io.open() and make sure to specify the b mode when appropriate

Be careful when indexing into binary data

Use feature detection instead of version detection

Inevitably you will have code that has to choose what to do based on what version of Python is running. The best way to do this is with feature detection of whether the version of Python you’re running under supports what you need. If for some reason that doesn’t work then you should make the version check be against Python 2 and not Python 3. To help explain this, let’s look at an example.

Let’s pretend that you need access to a feature of importlib that is available in Python’s standard library since Python 3.3 and available for Python 2 through importlib2 [https://pypi.org/project/importlib2] on PyPI. You might be tempted to write code to access e.g. the importlib.abc module by doing the following:

import sys

if sys.version_info[0] == 3:
    from importlib import abc
else:
    from importlib2 import abc

The problem with this code is what happens when Python 4 comes out? It would be better to treat Python 2 as the exceptional case instead of Python 3 and assume that future Python versions will be more compatible with Python 3 than Python 2:

import sys

if sys.version_info[0] > 2:
    from importlib import abc
else:
    from importlib2 import abc

The best solution, though, is to do no version detection at all and instead rely on feature detection. That avoids any potential issues of getting the version detection wrong and helps keep you future-compatible:

try:
    from importlib import abc
except ImportError:
    from importlib2 import abc

Prevent compatibility regressions

Once you have fully translated your code to be compatible with Python 3, you will want to make sure your code doesn’t regress and stop working under Python 3. This is especially true if you have a dependency which is blocking you from actually running under Python 3 at the moment.

To help with staying compatible, any new modules you create should have at least the following block of code at the top of it:

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

You can also run Python 2 with the -3 flag to be warned about various compatibility issues your code triggers during execution. If you turn warnings into errors with -Werror then you can make sure that you don’t accidentally miss a warning.

You can also use the Pylint [https://pypi.org/project/pylint] project and its --py3k flag to lint your code to receive warnings when your code begins to deviate from Python 3 compatibility. This also prevents you from having to run Modernize [https://python-modernize.readthedocs.io/] or Futurize [http://python-future.org/automatic_conversion.html] over your code regularly to catch compatibility regressions. This does require you only support Python 2.7 and Python 3.4 or newer as that is Pylint’s minimum Python version support.

Check which dependencies block your transition

After you have made your code compatible with Python 3 you should begin to care about whether your dependencies have also been ported. The caniusepython3 [https://pypi.org/project/caniusepython3] project was created to help you determine which projects – directly or indirectly – are blocking you from supporting Python 3. There is both a command-line tool as well as a web interface at https://caniusepython3.com.

The project also provides code which you can integrate into your test suite so that you will have a failing test when you no longer have dependencies blocking you from using Python 3. This allows you to avoid having to manually check your dependencies and to be notified quickly when you can start running on Python 3.

Update your setup.py file to denote Python 3 compatibility

Once your code works under Python 3, you should update the classifiers in your setup.py to contain Programming Language :: Python :: 3 and to not specify sole Python 2 support. This will tell anyone using your code that you support Python 2 and 3. Ideally you will also want to add classifiers for each major/minor version of Python you now support.

Use continuous integration to stay compatible

Once you are able to fully run under Python 3 you will want to make sure your code always works under both Python 2 & 3. Probably the best tool for running your tests under multiple Python interpreters is tox [https://pypi.org/project/tox]. You can then integrate tox with your continuous integration system so that you never accidentally break Python 2 or 3 support.

You may also want to use the -bb flag with the Python 3 interpreter to trigger an exception when you are comparing bytes to strings or bytes to an int (the latter is available starting in Python 3.5). By default type-differing comparisons simply return False, but if you made a mistake in your separation of text/binary data handling or indexing on bytes you wouldn’t easily find the mistake. This flag will raise an exception when these kinds of comparisons occur, making the mistake much easier to track down.

And that’s mostly it! At this point your code base is compatible with both Python 2 and 3 simultaneously. Your testing will also be set up so that you don’t accidentally break Python 2 or 3 compatibility regardless of which version you typically run your tests under while developing.

Consider using optional static type checking

Another way to help port your code is to use a static type checker like mypy [http://mypy-lang.org/] or pytype [https://github.com/google/pytype] on your code. These tools can be used to analyze your code as if it’s being run under Python 2, then you can run the tool a second time as if your code is running under Python 3. By running a static type checker twice like this you can discover if you’re e.g. misusing binary data type in one version of Python compared to another. If you add optional type hints to your code you can also explicitly state whether your APIs use textual or binary data, helping to make sure everything functions as expected in both versions of Python.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 HOWTO »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 HOWTO »

|

확장 모듈을 파이썬 3에 이식하기

저자

Benjamin Peterson

요약

C-API를 변경하는 것이 파이썬 3의 목표 중 하나는 아니었지만, 파이썬 수준의 많은 변경으로 인해 파이썬 2의 API를 그대로 남겨두는 것은 불가능했습니다. 사실, int()와 long() 통합과 같은 일부 변경 사항은 C 수준에서 더 분명합니다. 이 문서는 비 호환성을 기록으로 남기고 그 문제를 해결하는 방법을 설명합니다.

조건부 컴파일

어떤 코드를 파이썬 3에서만 컴파일하는 가장 쉬운 방법은 PY_MAJOR_VERSION이 3 이상인지 확인하는 것입니다.

#if PY_MAJOR_VERSION >= 3
#define IS_PY3K
#endif

존재하지 않는 API 함수는 조건 블록 내에서 동등한 것으로 별칭을 만들 수 있습니다.

객체 API의 변경 사항

파이썬 3은 비슷한 기능을 가진 일부 형을 병합하면서 다른 것들은 깨끗하게 분리합니다.

str/unicode 통합

파이썬 3의 str() 형은 파이썬 2의 unicode()와 동등합니다; C 함수는 모두 PyUnicode_*입니다. 이전의 8비트 문자열형은 bytes()가 되었고, C 함수는 PyBytes_*가 되었습니다. 파이썬 2.6 이상은 호환성 헤더 bytesobject.h를 제공하며, PyBytes 이름을 PyString 으로 매핑합니다. 파이썬 3과의 최상의 호환성을 위해, 텍스트 데이터에는 PyUnicode를, 바이너리 데이터에는 PyBytes를 사용해야 합니다. 파이썬 3의 PyBytes와 PyUnicode가 파이썬 2의 PyString과 PyUnicode처럼 교환할 수 없다는 것을 기억하는 것도 중요합니다. 다음 예는 PyUnicode, PyString 및 PyBytes에 대한 모범 사례를 보여줍니다.

#include "stdlib.h"
#include "Python.h"
#include "bytesobject.h"

/* text example */
static PyObject *
say_hello(PyObject *self, PyObject *args) {
    PyObject *name, *result;

    if (!PyArg_ParseTuple(args, "U:say_hello", &name))
        return NULL;

    result = PyUnicode_FromFormat("Hello, %S!", name);
    return result;
}

/* just a forward */
static char * do_encode(PyObject *);

/* bytes example */
static PyObject *
encode_object(PyObject *self, PyObject *args) {
    char *encoded;
    PyObject *result, *myobj;

    if (!PyArg_ParseTuple(args, "O:encode_object", &myobj))
        return NULL;

    encoded = do_encode(myobj);
    if (encoded == NULL)
        return NULL;
    result = PyBytes_FromString(encoded);
    free(encoded);
    return result;
}

long/int 통합

파이썬 3은 오직 하나의 정수형 int()만을 가집니다. 그러나 이것은 실제로 파이썬 2의 long() 형에 해당합니다 - 파이썬 2에서 사용된 int() 형은 제거되었습니다. C-API에서, PyInt_* 함수는 동등한 PyLong_* 함수로 대체됩니다.

모듈 초기화와 상태

파이썬 3에는 개선된 확장 모듈 초기화 시스템이 있습니다. (PEP 3121 [https://www.python.org/dev/peps/pep-3121]를 참조하십시오.) 모듈 상태를 전역에 저장하는 대신, 인터프리터별 구조체에 저장해야 합니다. 파이썬 2와 파이썬 3 모두에서 올바르게 동작하는 모듈을 만드는 것은 까다 롭습니다. 다음의 간단한 예제는 방법을 보여줍니다.

#include "Python.h"

struct module_state {
    PyObject *error;
};

#if PY_MAJOR_VERSION >= 3
#define GETSTATE(m) ((struct module_state*)PyModule_GetState(m))
#else
#define GETSTATE(m) (&_state)
static struct module_state _state;
#endif

static PyObject *
error_out(PyObject *m) {
    struct module_state *st = GETSTATE(m);
    PyErr_SetString(st->error, "something bad happened");
    return NULL;
}

static PyMethodDef myextension_methods[] = {
    {"error_out", (PyCFunction)error_out, METH_NOARGS, NULL},
    {NULL, NULL}
};

#if PY_MAJOR_VERSION >= 3

static int myextension_traverse(PyObject *m, visitproc visit, void *arg) {
    Py_VISIT(GETSTATE(m)->error);
    return 0;
}

static int myextension_clear(PyObject *m) {
    Py_CLEAR(GETSTATE(m)->error);
    return 0;
}

static struct PyModuleDef moduledef = {
        PyModuleDef_HEAD_INIT,
        "myextension",
        NULL,
        sizeof(struct module_state),
        myextension_methods,
        NULL,
        myextension_traverse,
        myextension_clear,
        NULL
};

#define INITERROR return NULL

PyMODINIT_FUNC
PyInit_myextension(void)

#else
#define INITERROR return

void
initmyextension(void)
#endif
{
#if PY_MAJOR_VERSION >= 3
    PyObject *module = PyModule_Create(&moduledef);
#else
    PyObject *module = Py_InitModule("myextension", myextension_methods);
#endif

    if (module == NULL)
        INITERROR;
    struct module_state *st = GETSTATE(module);

    st->error = PyErr_NewException("myextension.Error", NULL, NULL);
    if (st->error == NULL) {
        Py_DECREF(module);
        INITERROR;
    }

#if PY_MAJOR_VERSION >= 3
    return module;
#endif
}

캡슐로 대체된 CObject

Capsule 객체는 CObject를 대체하기 위해 파이썬 3.1과 2.7에 도입되었습니다. CObject는 유용했지만, CObject API는 문제가 있었습니다: 유효한 CObject를 구분할 수 없어서 불일치한 CObject가 인터프리터에 충돌을 일으킬 수 있도록 했고, 일부 API는 C의 정의되지 않은 동작에 의존했습니다. (캡슐을 뒷받침하는 이유에 대한 자세한 내용은 bpo-5630 [https://bugs.python.org/issue?@action=redirect&bpo=5630]를 참조하십시오.)

현재 CObject를 사용하고 있고, 3.1 이상으로 이전하려고 한다면, 캡슐로 전환해야 합니다. CObject는 3.1과 2.7에서 폐지되었고, 파이썬 3.2에서 완전히 제거되었습니다. 2.7이나 3.1 이상만 지원한다면, 단순히 Capsule로 전환할 수 있습니다. 파이썬 3.0이나 2.7 이전의 파이썬 버전을 지원해야 한다면, CObject와 캡슐을 모두 지원해야 합니다. (파이썬 3.0은 더는 지원되지 않으며 프로덕션 용도로 권장되지 않음에 유의하십시오.)

다음 예제 헤더 파일 capsulethunk.h는 문제를 해결할 수 있습니다. Capsule API로 코드를 작성하고, Python.h 다음에 이 헤더 파일을 포함하십시오. 여러분의 코드는 자동으로 캡슐이 있는 파이썬 버전에서 캡슐을 사용하고, 캡슐을 사용할 수 없을 때 CObject로 전환합니다.

capsulethunk.h는 CObject를 사용하여 캡슐을 시뮬레이션합니다. 그러나, CObject는 캡슐의 “이름(name)”을 저장할 장소를 제공하지 않습니다. 결과적으로 capsulethunk.h가 만든 시뮬레이트 된 Capsule 객체는 실제 캡슐과 약간 다르게 동작합니다. 구체적으로:

PyCapsule_New()에 전달된 name 매개 변수는 무시됩니다.

PyCapsule_IsValid() 와 PyCapsule_GetPointer()에 전달된 name 매개 변수는 무시되며, name에 대한 에러 검사는 수행되지 않습니다.

PyCapsule_GetName()은 항상 NULL을 반환합니다.

PyCapsule_SetName()은 항상 예외를 발생시키고 실패를 반환합니다. (CObject에 이름을 저장할 수 있는 방법이 없으므로, 여기서 조용한 실패보다 요란한 PyCapsule_SetName()의 실패를 선호합니다. 이것이 불편하다면, 적절하다고 생각하는 대로 로컬 복사본을 자유롭게 수정하십시오.)

capsulethunk.h는 파이썬 소스 배포판의 Doc/includes/capsulethunk.h [https://github.com/python/cpython/tree/3.7/Doc/includes/capsulethunk.h]에서 찾을 수 있습니다. 여러분의 편의를 위해 여기에도 포함합니다:

#ifndef __CAPSULETHUNK_H
#define __CAPSULETHUNK_H

#if (    (PY_VERSION_HEX <  0x02070000) \
     || ((PY_VERSION_HEX >= 0x03000000) \
      && (PY_VERSION_HEX <  0x03010000)) )

#define __PyCapsule_GetField(capsule, field, default_value) \
    ( PyCapsule_CheckExact(capsule) \
        ? (((PyCObject *)capsule)->field) \
        : (default_value) \
    ) \

#define __PyCapsule_SetField(capsule, field, value) \
    ( PyCapsule_CheckExact(capsule) \
        ? (((PyCObject *)capsule)->field = value), 1 \
        : 0 \
    ) \

#define PyCapsule_Type PyCObject_Type

#define PyCapsule_CheckExact(capsule) (PyCObject_Check(capsule))
#define PyCapsule_IsValid(capsule, name) (PyCObject_Check(capsule))

#define PyCapsule_New(pointer, name, destructor) \
    (PyCObject_FromVoidPtr(pointer, destructor))

#define PyCapsule_GetPointer(capsule, name) \
    (PyCObject_AsVoidPtr(capsule))

/* Don't call PyCObject_SetPointer here, it fails if there's a destructor */
#define PyCapsule_SetPointer(capsule, pointer) \
    __PyCapsule_SetField(capsule, cobject, pointer)

#define PyCapsule_GetDestructor(capsule) \
    __PyCapsule_GetField(capsule, destructor)

#define PyCapsule_SetDestructor(capsule, dtor) \
    __PyCapsule_SetField(capsule, destructor, dtor)

/*
 * Sorry, there's simply no place
 * to store a Capsule "name" in a CObject.
 */
#define PyCapsule_GetName(capsule) NULL

static int
PyCapsule_SetName(PyObject *capsule, const char *unused)
{
    unused = unused;
    PyErr_SetString(PyExc_NotImplementedError,
        "can't use PyCapsule_SetName with CObjects");
    return 1;
}

#define PyCapsule_GetContext(capsule) \
    __PyCapsule_GetField(capsule, descr)

#define PyCapsule_SetContext(capsule, context) \
    __PyCapsule_SetField(capsule, descr, context)

static void *
PyCapsule_Import(const char *name, int no_block)
{
    PyObject *object = NULL;
    void *return_value = NULL;
    char *trace;
    size_t name_length = (strlen(name) + 1) * sizeof(char);
    char *name_dup = (char *)PyMem_MALLOC(name_length);

    if (!name_dup) {
        return NULL;
    }

    memcpy(name_dup, name, name_length);

    trace = name_dup;
    while (trace) {
        char *dot = strchr(trace, '.');
        if (dot) {
            *dot++ = '\0';
        }

        if (object == NULL) {
            if (no_block) {
                object = PyImport_ImportModuleNoBlock(trace);
            } else {
                object = PyImport_ImportModule(trace);
                if (!object) {
                    PyErr_Format(PyExc_ImportError,
                        "PyCapsule_Import could not "
                        "import module \"%s\"", trace);
                }
            }
        } else {
            PyObject *object2 = PyObject_GetAttrString(object, trace);
            Py_DECREF(object);
            object = object2;
        }
        if (!object) {
            goto EXIT;
        }

        trace = dot;
    }

    if (PyCObject_Check(object)) {
        PyCObject *cobject = (PyCObject *)object;
        return_value = cobject->cobject;
    } else {
        PyErr_Format(PyExc_AttributeError,
            "PyCapsule_Import \"%s\" is not valid",
            name);
    }

EXIT:
    Py_XDECREF(object);
    if (name_dup) {
        PyMem_FREE(name_dup);
    }
    return return_value;
}

#endif /* #if PY_VERSION_HEX < 0x02070000 */

#endif /* __CAPSULETHUNK_H */

다른 옵션

새 확장 모듈을 작성하고 있다면, Cython [http://cython.org/]을 고려하십시오. 파이썬과 비슷한 언어를 C로 변환합니다. 만들어진 확장 모듈은 파이썬 3과 파이썬 2 모두와 호환됩니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 HOWTO »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 HOWTO »

|

Curses Programming with Python

Author

A.M. Kuchling, Eric S. Raymond

Release

2.04

Abstract

This document describes how to use the curses extension module to control text-mode displays.

What is curses?

The curses library supplies a terminal-independent screen-painting and keyboard-handling facility for text-based terminals; such terminals include VT100s, the Linux console, and the simulated terminal provided by various programs. Display terminals support various control codes to perform common operations such as moving the cursor, scrolling the screen, and erasing areas. Different terminals use widely differing codes, and often have their own minor quirks.

In a world of graphical displays, one might ask “why bother”? It’s true that character-cell display terminals are an obsolete technology, but there are niches in which being able to do fancy things with them are still valuable. One niche is on small-footprint or embedded Unixes that don’t run an X server. Another is tools such as OS installers and kernel configurators that may have to run before any graphical support is available.

The curses library provides fairly basic functionality, providing the programmer with an abstraction of a display containing multiple non-overlapping windows of text. The contents of a window can be changed in various ways—adding text, erasing it, changing its appearance—and the curses library will figure out what control codes need to be sent to the terminal to produce the right output. curses doesn’t provide many user-interface concepts such as buttons, checkboxes, or dialogs; if you need such features, consider a user interface library such as Urwid [https://pypi.org/project/urwid/].

The curses library was originally written for BSD Unix; the later System V versions of Unix from AT&T added many enhancements and new functions. BSD curses is no longer maintained, having been replaced by ncurses, which is an open-source implementation of the AT&T interface. If you’re using an open-source Unix such as Linux or FreeBSD, your system almost certainly uses ncurses. Since most current commercial Unix versions are based on System V code, all the functions described here will probably be available. The older versions of curses carried by some proprietary Unixes may not support everything, though.

The Windows version of Python doesn’t include the curses module. A ported version called UniCurses [https://pypi.org/project/UniCurses] is available. You could also try the Console module [http://effbot.org/zone/console-index.htm] written by Fredrik Lundh, which doesn’t use the same API as curses but provides cursor-addressable text output and full support for mouse and keyboard input.

The Python curses module

The Python module is a fairly simple wrapper over the C functions provided by curses; if you’re already familiar with curses programming in C, it’s really easy to transfer that knowledge to Python. The biggest difference is that the Python interface makes things simpler by merging different C functions such as addstr(), mvaddstr(), and mvwaddstr() into a single addstr() method. You’ll see this covered in more detail later.

This HOWTO is an introduction to writing text-mode programs with curses and Python. It doesn’t attempt to be a complete guide to the curses API; for that, see the Python library guide’s section on ncurses, and the C manual pages for ncurses. It will, however, give you the basic ideas.

Starting and ending a curses application

Before doing anything, curses must be initialized. This is done by calling the initscr() function, which will determine the terminal type, send any required setup codes to the terminal, and create various internal data structures. If successful, initscr() returns a window object representing the entire screen; this is usually called stdscr after the name of the corresponding C variable.

import curses
stdscr = curses.initscr()

Usually curses applications turn off automatic echoing of keys to the screen, in order to be able to read keys and only display them under certain circumstances. This requires calling the noecho() function.

curses.noecho()

Applications will also commonly need to react to keys instantly, without requiring the Enter key to be pressed; this is called cbreak mode, as opposed to the usual buffered input mode.

curses.cbreak()

Terminals usually return special keys, such as the cursor keys or navigation keys such as Page Up and Home, as a multibyte escape sequence. While you could write your application to expect such sequences and process them accordingly, curses can do it for you, returning a special value such as curses.KEY_LEFT. To get curses to do the job, you’ll have to enable keypad mode.

stdscr.keypad(True)

Terminating a curses application is much easier than starting one. You’ll need to call:

curses.nocbreak()
stdscr.keypad(False)
curses.echo()

to reverse the curses-friendly terminal settings. Then call the endwin() function to restore the terminal to its original operating mode.

curses.endwin()

A common problem when debugging a curses application is to get your terminal messed up when the application dies without restoring the terminal to its previous state. In Python this commonly happens when your code is buggy and raises an uncaught exception. Keys are no longer echoed to the screen when you type them, for example, which makes using the shell difficult.

In Python you can avoid these complications and make debugging much easier by importing the curses.wrapper() function and using it like this:

from curses import wrapper

def main(stdscr):
    # Clear screen
    stdscr.clear()

    # This raises ZeroDivisionError when i == 10.
    for i in range(0, 11):
        v = i-10
        stdscr.addstr(i, 0, '10 divided by {} is {}'.format(v, 10/v))

    stdscr.refresh()
    stdscr.getkey()

wrapper(main)

The wrapper() function takes a callable object and does the initializations described above, also initializing colors if color support is present. wrapper() then runs your provided callable. Once the callable returns, wrapper() will restore the original state of the terminal. The callable is called inside a try…except that catches exceptions, restores the state of the terminal, and then re-raises the exception. Therefore your terminal won’t be left in a funny state on exception and you’ll be able to read the exception’s message and traceback.

Windows and Pads

Windows are the basic abstraction in curses. A window object represents a rectangular area of the screen, and supports methods to display text, erase it, allow the user to input strings, and so forth.

The stdscr object returned by the initscr() function is a window object that covers the entire screen. Many programs may need only this single window, but you might wish to divide the screen into smaller windows, in order to redraw or clear them separately. The newwin() function creates a new window of a given size, returning the new window object.

begin_x = 20; begin_y = 7
height = 5; width = 40
win = curses.newwin(height, width, begin_y, begin_x)

Note that the coordinate system used in curses is unusual. Coordinates are always passed in the order y,x, and the top-left corner of a window is coordinate (0,0). This breaks the normal convention for handling coordinates where the x coordinate comes first. This is an unfortunate difference from most other computer applications, but it’s been part of curses since it was first written, and it’s too late to change things now.

Your application can determine the size of the screen by using the curses.LINES and curses.COLS variables to obtain the y and x sizes. Legal coordinates will then extend from (0,0) to (curses.LINES - 1, curses.COLS - 1).

When you call a method to display or erase text, the effect doesn’t immediately show up on the display. Instead you must call the refresh() method of window objects to update the screen.

This is because curses was originally written with slow 300-baud terminal connections in mind; with these terminals, minimizing the time required to redraw the screen was very important. Instead curses accumulates changes to the screen and displays them in the most efficient manner when you call refresh(). For example, if your program displays some text in a window and then clears the window, there’s no need to send the original text because they’re never visible.

In practice, explicitly telling curses to redraw a window doesn’t really complicate programming with curses much. Most programs go into a flurry of activity, and then pause waiting for a keypress or some other action on the part of the user. All you have to do is to be sure that the screen has been redrawn before pausing to wait for user input, by first calling stdscr.refresh() or the refresh() method of some other relevant window.

A pad is a special case of a window; it can be larger than the actual display screen, and only a portion of the pad displayed at a time. Creating a pad requires the pad’s height and width, while refreshing a pad requires giving the coordinates of the on-screen area where a subsection of the pad will be displayed.

pad = curses.newpad(100, 100)
# These loops fill the pad with letters; addch() is
# explained in the next section
for y in range(0, 99):
    for x in range(0, 99):
        pad.addch(y,x, ord('a') + (x*x+y*y) % 26)

# Displays a section of the pad in the middle of the screen.
# (0,0) : coordinate of upper-left corner of pad area to display.
# (5,5) : coordinate of upper-left corner of window area to be filled
#         with pad content.
# (20, 75) : coordinate of lower-right corner of window area to be
#          : filled with pad content.
pad.refresh( 0,0, 5,5, 20,75)

The refresh() call displays a section of the pad in the rectangle extending from coordinate (5,5) to coordinate (20,75) on the screen; the upper left corner of the displayed section is coordinate (0,0) on the pad. Beyond that difference, pads are exactly like ordinary windows and support the same methods.

If you have multiple windows and pads on screen there is a more efficient way to update the screen and prevent annoying screen flicker as each part of the screen gets updated. refresh() actually does two things:

Calls the noutrefresh() method of each window to update an underlying data structure representing the desired state of the screen.

Calls the function doupdate() function to change the physical screen to match the desired state recorded in the data structure.

Instead you can call noutrefresh() on a number of windows to update the data structure, and then call doupdate() to update the screen.

Displaying Text

From a C programmer’s point of view, curses may sometimes look like a twisty maze of functions, all subtly different. For example, addstr() displays a string at the current cursor location in the stdscr window, while mvaddstr() moves to a given y,x coordinate first before displaying the string. waddstr() is just like addstr(), but allows specifying a window to use instead of using stdscr by default. mvwaddstr() allows specifying both a window and a coordinate.

Fortunately the Python interface hides all these details. stdscr is a window object like any other, and methods such as addstr() accept multiple argument forms. Usually there are four different forms.

Form

Description

str or ch

Display the string str or character ch at the current position

str or ch, attr

Display the string str or character ch, using attribute attr at the current position

y, x, str or ch

Move to position y,x within the window, and display str or ch

y, x, str or ch, attr

Move to position y,x within the window, and display str or ch, using attribute attr

Attributes allow displaying text in highlighted forms such as boldface, underline, reverse code, or in color. They’ll be explained in more detail in the next subsection.

The addstr() method takes a Python string or bytestring as the value to be displayed. The contents of bytestrings are sent to the terminal as-is. Strings are encoded to bytes using the value of the window’s encoding attribute; this defaults to the default system encoding as returned by locale.getpreferredencoding().

The addch() methods take a character, which can be either a string of length 1, a bytestring of length 1, or an integer.

Constants are provided for extension characters; these constants are integers greater than 255. For example, ACS_PLMINUS is a +/- symbol, and ACS_ULCORNER is the upper left corner of a box (handy for drawing borders). You can also use the appropriate Unicode character.

Windows remember where the cursor was left after the last operation, so if you leave out the y,x coordinates, the string or character will be displayed wherever the last operation left off. You can also move the cursor with the move(y,x) method. Because some terminals always display a flashing cursor, you may want to ensure that the cursor is positioned in some location where it won’t be distracting; it can be confusing to have the cursor blinking at some apparently random location.

If your application doesn’t need a blinking cursor at all, you can call curs_set(False) to make it invisible. For compatibility with older curses versions, there’s a leaveok(bool) function that’s a synonym for curs_set(). When bool is true, the curses library will attempt to suppress the flashing cursor, and you won’t need to worry about leaving it in odd locations.

Attributes and Color

Characters can be displayed in different ways. Status lines in a text-based application are commonly shown in reverse video, or a text viewer may need to highlight certain words. curses supports this by allowing you to specify an attribute for each cell on the screen.

An attribute is an integer, each bit representing a different attribute. You can try to display text with multiple attribute bits set, but curses doesn’t guarantee that all the possible combinations are available, or that they’re all visually distinct. That depends on the ability of the terminal being used, so it’s safest to stick to the most commonly available attributes, listed here.

Attribute

Description

A_BLINK

Blinking text

A_BOLD

Extra bright or bold text

A_DIM

Half bright text

A_REVERSE

Reverse-video text

A_STANDOUT

The best highlighting mode available

A_UNDERLINE

Underlined text

So, to display a reverse-video status line on the top line of the screen, you could code:

stdscr.addstr(0, 0, "Current mode: Typing mode",
              curses.A_REVERSE)
stdscr.refresh()

The curses library also supports color on those terminals that provide it. The most common such terminal is probably the Linux console, followed by color xterms.

To use color, you must call the start_color() function soon after calling initscr(), to initialize the default color set (the curses.wrapper() function does this automatically). Once that’s done, the has_colors() function returns TRUE if the terminal in use can actually display color. (Note: curses uses the American spelling ‘color’, instead of the Canadian/British spelling ‘colour’. If you’re used to the British spelling, you’ll have to resign yourself to misspelling it for the sake of these functions.)

The curses library maintains a finite number of color pairs, containing a foreground (or text) color and a background color. You can get the attribute value corresponding to a color pair with the color_pair() function; this can be bitwise-OR’ed with other attributes such as A_REVERSE, but again, such combinations are not guaranteed to work on all terminals.

An example, which displays a line of text using color pair 1:

stdscr.addstr("Pretty text", curses.color_pair(1))
stdscr.refresh()

As I said before, a color pair consists of a foreground and background color. The init_pair(n, f, b) function changes the definition of color pair n, to foreground color f and background color b. Color pair 0 is hard-wired to white on black, and cannot be changed.

Colors are numbered, and start_color() initializes 8 basic colors when it activates color mode. They are: 0:black, 1:red, 2:green, 3:yellow, 4:blue, 5:magenta, 6:cyan, and 7:white. The curses module defines named constants for each of these colors: curses.COLOR_BLACK, curses.COLOR_RED, and so forth.

Let’s put all this together. To change color 1 to red text on a white background, you would call:

curses.init_pair(1, curses.COLOR_RED, curses.COLOR_WHITE)

When you change a color pair, any text already displayed using that color pair will change to the new colors. You can also display new text in this color with:

stdscr.addstr(0,0, "RED ALERT!", curses.color_pair(1))

Very fancy terminals can change the definitions of the actual colors to a given RGB value. This lets you change color 1, which is usually red, to purple or blue or any other color you like. Unfortunately, the Linux console doesn’t support this, so I’m unable to try it out, and can’t provide any examples. You can check if your terminal can do this by calling can_change_color(), which returns True if the capability is there. If you’re lucky enough to have such a talented terminal, consult your system’s man pages for more information.

User Input

The C curses library offers only very simple input mechanisms. Python’s curses module adds a basic text-input widget. (Other libraries such as Urwid [https://pypi.org/project/urwid/] have more extensive collections of widgets.)

There are two methods for getting input from a window:

getch() refreshes the screen and then waits for the user to hit a key, displaying the key if echo() has been called earlier. You can optionally specify a coordinate to which the cursor should be moved before pausing.

getkey() does the same thing but converts the integer to a string. Individual characters are returned as 1-character strings, and special keys such as function keys return longer strings containing a key name such as KEY_UP or ^G.

It’s possible to not wait for the user using the nodelay() window method. After nodelay(True), getch() and getkey() for the window become non-blocking. To signal that no input is ready, getch() returns curses.ERR (a value of -1) and getkey() raises an exception. There’s also a halfdelay() function, which can be used to (in effect) set a timer on each getch(); if no input becomes available within a specified delay (measured in tenths of a second), curses raises an exception.

The getch() method returns an integer; if it’s between 0 and 255, it represents the ASCII code of the key pressed. Values greater than 255 are special keys such as Page Up, Home, or the cursor keys. You can compare the value returned to constants such as curses.KEY_PPAGE, curses.KEY_HOME, or curses.KEY_LEFT. The main loop of your program may look something like this:

while True:
    c = stdscr.getch()
    if c == ord('p'):
        PrintDocument()
    elif c == ord('q'):
        break  # Exit the while loop
    elif c == curses.KEY_HOME:
        x = y = 0

The curses.ascii module supplies ASCII class membership functions that take either integer or 1-character string arguments; these may be useful in writing more readable tests for such loops. It also supplies conversion functions that take either integer or 1-character-string arguments and return the same type. For example, curses.ascii.ctrl() returns the control character corresponding to its argument.

There’s also a method to retrieve an entire string, getstr(). It isn’t used very often, because its functionality is quite limited; the only editing keys available are the backspace key and the Enter key, which terminates the string. It can optionally be limited to a fixed number of characters.

curses.echo()            # Enable echoing of characters

# Get a 15-character string, with the cursor on the top line
s = stdscr.getstr(0,0, 15)

The curses.textpad module supplies a text box that supports an Emacs-like set of keybindings. Various methods of the Textbox class support editing with input validation and gathering the edit results either with or without trailing spaces. Here’s an example:

import curses
from curses.textpad import Textbox, rectangle

def main(stdscr):
    stdscr.addstr(0, 0, "Enter IM message: (hit Ctrl-G to send)")

    editwin = curses.newwin(5,30, 2,1)
    rectangle(stdscr, 1,0, 1+5+1, 1+30+1)
    stdscr.refresh()

    box = Textbox(editwin)

    # Let the user edit until Ctrl-G is struck.
    box.edit()

    # Get resulting contents
    message = box.gather()

See the library documentation on curses.textpad for more details.

For More Information

This HOWTO doesn’t cover some advanced topics, such as reading the contents of the screen or capturing mouse events from an xterm instance, but the Python library page for the curses module is now reasonably complete. You should browse it next.

If you’re in doubt about the detailed behavior of the curses functions, consult the manual pages for your curses implementation, whether it’s ncurses or a proprietary Unix vendor’s. The manual pages will document any quirks, and provide complete lists of all the functions, attributes, and ACS_* characters available to you.

Because the curses API is so large, some functions aren’t supported in the Python interface. Often this isn’t because they’re difficult to implement, but because no one has needed them yet. Also, Python doesn’t yet support the menu library associated with ncurses. Patches adding support for these would be welcome; see the Python Developer’s Guide [https://devguide.python.org/] to learn more about submitting patches to Python.

Writing Programs with NCURSES [http://invisible-island.net/ncurses/ncurses-intro.html]: a lengthy tutorial for C programmers.

The ncurses man page [https://linux.die.net/man/3/ncurses]

The ncurses FAQ [http://invisible-island.net/ncurses/ncurses.faq.html]

“Use curses… don’t swear” [https://www.youtube.com/watch?v=eN1eZtjLEnU]: video of a PyCon 2013 talk on controlling terminals using curses or Urwid.

“Console Applications with Urwid” [http://www.pyvideo.org/video/1568/console-applications-with-urwid]: video of a PyCon CA 2012 talk demonstrating some applications written using Urwid.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 HOWTO »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 HOWTO »

|

Descriptor HowTo Guide

Author

Raymond Hettinger

Contact

<python at rcn dot com>

목차

Descriptor HowTo Guide

Abstract

Definition and Introduction

Descriptor Protocol

Invoking Descriptors

Descriptor Example

Properties

Functions and Methods

Static Methods and Class Methods

Abstract

Defines descriptors, summarizes the protocol, and shows how descriptors are called. Examines a custom descriptor and several built-in Python descriptors including functions, properties, static methods, and class methods. Shows how each works by giving a pure Python equivalent and a sample application.

Learning about descriptors not only provides access to a larger toolset, it creates a deeper understanding of how Python works and an appreciation for the elegance of its design.

Definition and Introduction

In general, a descriptor is an object attribute with “binding behavior”, one whose attribute access has been overridden by methods in the descriptor protocol. Those methods are __get__(), __set__(), and __delete__(). If any of those methods are defined for an object, it is said to be a descriptor.

The default behavior for attribute access is to get, set, or delete the attribute from an object’s dictionary. For instance, a.x has a lookup chain starting with a.__dict__['x'], then type(a).__dict__['x'], and continuing through the base classes of type(a) excluding metaclasses. If the looked-up value is an object defining one of the descriptor methods, then Python may override the default behavior and invoke the descriptor method instead. Where this occurs in the precedence chain depends on which descriptor methods were defined.

Descriptors are a powerful, general purpose protocol. They are the mechanism behind properties, methods, static methods, class methods, and super(). They are used throughout Python itself to implement the new style classes introduced in version 2.2. Descriptors simplify the underlying C-code and offer a flexible set of new tools for everyday Python programs.

Descriptor Protocol

descr.__get__(self, obj, type=None) -> value

descr.__set__(self, obj, value) -> None

descr.__delete__(self, obj) -> None

That is all there is to it. Define any of these methods and an object is considered a descriptor and can override default behavior upon being looked up as an attribute.

If an object defines both __get__() and __set__(), it is considered a data descriptor. Descriptors that only define __get__() are called non-data descriptors (they are typically used for methods but other uses are possible).

Data and non-data descriptors differ in how overrides are calculated with respect to entries in an instance’s dictionary. If an instance’s dictionary has an entry with the same name as a data descriptor, the data descriptor takes precedence. If an instance’s dictionary has an entry with the same name as a non-data descriptor, the dictionary entry takes precedence.

To make a read-only data descriptor, define both __get__() and __set__() with the __set__() raising an AttributeError when called. Defining the __set__() method with an exception raising placeholder is enough to make it a data descriptor.

Invoking Descriptors

A descriptor can be called directly by its method name. For example, d.__get__(obj).

Alternatively, it is more common for a descriptor to be invoked automatically upon attribute access. For example, obj.d looks up d in the dictionary of obj. If d defines the method __get__(), then d.__get__(obj) is invoked according to the precedence rules listed below.

The details of invocation depend on whether obj is an object or a class.

For objects, the machinery is in object.__getattribute__() which transforms b.x into type(b).__dict__['x'].__get__(b, type(b)). The implementation works through a precedence chain that gives data descriptors priority over instance variables, instance variables priority over non-data descriptors, and assigns lowest priority to __getattr__() if provided. The full C implementation can be found in PyObject_GenericGetAttr() in Objects/object.c [https://github.com/python/cpython/tree/3.7/Objects/object.c].

For classes, the machinery is in type.__getattribute__() which transforms B.x into B.__dict__['x'].__get__(None, B). In pure Python, it looks like:

def __getattribute__(self, key):
    "Emulate type_getattro() in Objects/typeobject.c"
    v = object.__getattribute__(self, key)
    if hasattr(v, '__get__'):
        return v.__get__(None, self)
    return v

The important points to remember are:

descriptors are invoked by the __getattribute__() method

overriding __getattribute__() prevents automatic descriptor calls

object.__getattribute__() and type.__getattribute__() make different calls to __get__().

data descriptors always override instance dictionaries.

non-data descriptors may be overridden by instance dictionaries.

The object returned by super() also has a custom __getattribute__() method for invoking descriptors. The call super(B, obj).m() searches obj.__class__.__mro__ for the base class A immediately following B and then returns A.__dict__['m'].__get__(obj, B). If not a descriptor, m is returned unchanged. If not in the dictionary, m reverts to a search using object.__getattribute__().

The implementation details are in super_getattro() in Objects/typeobject.c [https://github.com/python/cpython/tree/3.7/Objects/typeobject.c]. and a pure Python equivalent can be found in Guido’s Tutorial [https://www.python.org/download/releases/2.2.3/descrintro/#cooperation].

The details above show that the mechanism for descriptors is embedded in the __getattribute__() methods for object, type, and super(). Classes inherit this machinery when they derive from object or if they have a meta-class providing similar functionality. Likewise, classes can turn-off descriptor invocation by overriding __getattribute__().

Descriptor Example

The following code creates a class whose objects are data descriptors which print a message for each get or set. Overriding __getattribute__() is alternate approach that could do this for every attribute. However, this descriptor is useful for monitoring just a few chosen attributes:

class RevealAccess(object):
    """A data descriptor that sets and returns values
       normally and prints a message logging their access.
    """

    def __init__(self, initval=None, name='var'):
        self.val = initval
        self.name = name

    def __get__(self, obj, objtype):
        print('Retrieving', self.name)
        return self.val

    def __set__(self, obj, val):
        print('Updating', self.name)
        self.val = val

>>> class MyClass(object):
...     x = RevealAccess(10, 'var "x"')
...     y = 5
...
>>> m = MyClass()
>>> m.x
Retrieving var "x"
10
>>> m.x = 20
Updating var "x"
>>> m.x
Retrieving var "x"
20
>>> m.y
5

The protocol is simple and offers exciting possibilities. Several use cases are so common that they have been packaged into individual function calls. Properties, bound methods, static methods, and class methods are all based on the descriptor protocol.

Properties

Calling property() is a succinct way of building a data descriptor that triggers function calls upon access to an attribute. Its signature is:

property(fget=None, fset=None, fdel=None, doc=None) -> property attribute

The documentation shows a typical use to define a managed attribute x:

class C(object):
    def getx(self): return self.__x
    def setx(self, value): self.__x = value
    def delx(self): del self.__x
    x = property(getx, setx, delx, "I'm the 'x' property.")

To see how property() is implemented in terms of the descriptor protocol, here is a pure Python equivalent:

class Property(object):
    "Emulate PyProperty_Type() in Objects/descrobject.c"

    def __init__(self, fget=None, fset=None, fdel=None, doc=None):
        self.fget = fget
        self.fset = fset
        self.fdel = fdel
        if doc is None and fget is not None:
            doc = fget.__doc__
        self.__doc__ = doc

    def __get__(self, obj, objtype=None):
        if obj is None:
            return self
        if self.fget is None:
            raise AttributeError("unreadable attribute")
        return self.fget(obj)

    def __set__(self, obj, value):
        if self.fset is None:
            raise AttributeError("can't set attribute")
        self.fset(obj, value)

    def __delete__(self, obj):
        if self.fdel is None:
            raise AttributeError("can't delete attribute")
        self.fdel(obj)

    def getter(self, fget):
        return type(self)(fget, self.fset, self.fdel, self.__doc__)

    def setter(self, fset):
        return type(self)(self.fget, fset, self.fdel, self.__doc__)

    def deleter(self, fdel):
        return type(self)(self.fget, self.fset, fdel, self.__doc__)

The property() builtin helps whenever a user interface has granted attribute access and then subsequent changes require the intervention of a method.

For instance, a spreadsheet class may grant access to a cell value through Cell('b10').value. Subsequent improvements to the program require the cell to be recalculated on every access; however, the programmer does not want to affect existing client code accessing the attribute directly. The solution is to wrap access to the value attribute in a property data descriptor:

class Cell(object):
    . . .
    def getvalue(self):
        "Recalculate the cell before returning value"
        self.recalc()
        return self._value
    value = property(getvalue)

Functions and Methods

Python’s object oriented features are built upon a function based environment. Using non-data descriptors, the two are merged seamlessly.

Class dictionaries store methods as functions. In a class definition, methods are written using def or lambda, the usual tools for creating functions. Methods only differ from regular functions in that the first argument is reserved for the object instance. By Python convention, the instance reference is called self but may be called this or any other variable name.

To support method calls, functions include the __get__() method for binding methods during attribute access. This means that all functions are non-data descriptors which return bound methods when they are invoked from an object. In pure Python, it works like this:

class Function(object):
    . . .
    def __get__(self, obj, objtype=None):
        "Simulate func_descr_get() in Objects/funcobject.c"
        if obj is None:
            return self
        return types.MethodType(self, obj)

Running the interpreter shows how the function descriptor works in practice:

>>> class D(object):
...     def f(self, x):
...         return x
...
>>> d = D()

# Access through the class dictionary does not invoke __get__.
# It just returns the underlying function object.
>>> D.__dict__['f']
<function D.f at 0x00C45070>

# Dotted access from a class calls __get__() which just returns
# the underlying function unchanged.
>>> D.f
<function D.f at 0x00C45070>

# The function has a __qualname__ attribute to support introspection
>>> D.f.__qualname__
'D.f'

# Dotted access from an instance calls __get__() which returns the
# function wrapped in a bound method object
>>> d.f
<bound method D.f of <__main__.D object at 0x00B18C90>>

# Internally, the bound method stores the underlying function,
# the bound instance, and the class of the bound instance.
>>> d.f.__func__
<function D.f at 0x1012e5ae8>
>>> d.f.__self__
<__main__.D object at 0x1012e1f98>
>>> d.f.__class__
<class 'method'>

Static Methods and Class Methods

Non-data descriptors provide a simple mechanism for variations on the usual patterns of binding functions into methods.

To recap, functions have a __get__() method so that they can be converted to a method when accessed as attributes. The non-data descriptor transforms an obj.f(*args) call into f(obj, *args). Calling klass.f(*args) becomes f(*args).

This chart summarizes the binding and its two most useful variants:

Transformation

Called from an Object

Called from a Class

function

f(obj, *args)

f(*args)

staticmethod

f(*args)

f(*args)

classmethod

f(type(obj), *args)

f(klass, *args)

Static methods return the underlying function without changes. Calling either c.f or C.f is the equivalent of a direct lookup into object.__getattribute__(c, "f") or object.__getattribute__(C, "f"). As a result, the function becomes identically accessible from either an object or a class.

Good candidates for static methods are methods that do not reference the self variable.

For instance, a statistics package may include a container class for experimental data. The class provides normal methods for computing the average, mean, median, and other descriptive statistics that depend on the data. However, there may be useful functions which are conceptually related but do not depend on the data. For instance, erf(x) is handy conversion routine that comes up in statistical work but does not directly depend on a particular dataset. It can be called either from an object or the class: s.erf(1.5) --> .9332 or Sample.erf(1.5) --> .9332.

Since staticmethods return the underlying function with no changes, the example calls are unexciting:

>>> class E(object):
...     def f(x):
...         print(x)
...     f = staticmethod(f)
...
>>> E.f(3)
3
>>> E().f(3)
3

Using the non-data descriptor protocol, a pure Python version of staticmethod() would look like this:

class StaticMethod(object):
    "Emulate PyStaticMethod_Type() in Objects/funcobject.c"

    def __init__(self, f):
        self.f = f

    def __get__(self, obj, objtype=None):
        return self.f

Unlike static methods, class methods prepend the class reference to the argument list before calling the function. This format is the same for whether the caller is an object or a class:

>>> class E(object):
...     def f(klass, x):
...         return klass.__name__, x
...     f = classmethod(f)
...
>>> print(E.f(3))
('E', 3)
>>> print(E().f(3))
('E', 3)

This behavior is useful whenever the function only needs to have a class reference and does not care about any underlying data. One use for classmethods is to create alternate class constructors. In Python 2.3, the classmethod dict.fromkeys() creates a new dictionary from a list of keys. The pure Python equivalent is:

class Dict(object):
    . . .
    def fromkeys(klass, iterable, value=None):
        "Emulate dict_fromkeys() in Objects/dictobject.c"
        d = klass()
        for key in iterable:
            d[key] = value
        return d
    fromkeys = classmethod(fromkeys)

Now a new dictionary of unique keys can be constructed like this:

>>> Dict.fromkeys('abracadabra')
{'a': None, 'r': None, 'b': None, 'c': None, 'd': None}

Using the non-data descriptor protocol, a pure Python version of classmethod() would look like this:

class ClassMethod(object):
    "Emulate PyClassMethod_Type() in Objects/funcobject.c"

    def __init__(self, f):
        self.f = f

    def __get__(self, obj, klass=None):
        if klass is None:
            klass = type(obj)
        def newfunc(*args):
            return self.f(klass, *args)
        return newfunc

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 HOWTO »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 HOWTO »

|

함수형 프로그래밍 HOWTO

저자

A. M. Kuchling

버전

0.32

이 문서에서는, 함수형 방식으로 프로그램을 구현하는데 적합한 파이썬의 특성에 대해 알아볼 것입니다. 함수형 프로그래밍의 개념을 소개한 뒤에, 이터레이터 , 제너레이터 와 같은 언어의 특성과 itertools , functools 와 같은 관련 라이브러리 모듈을 살펴볼 것입니다.

소개

이 절에서는 함수형 프로그래밍의 기본적인 개념을 설명합니다; 만약 단순히 파이썬의 언어적 특성에 관해서만 관심이 있으시다면, 이터레이터 절로 건너뛰세요.

프로그래밍 언어들은 다음과 같이 각각 다른 방식으로 문제를 더 작은 부분으로 분할하는 방법을 지원합니다:

대부분의 프로그래밍 언어들은 절차적 입니다: 프로그램은 컴퓨터에 프로그램의 입력을 어떻게 할지 알려주는 명령 목록입니다. C, 파스칼, 유닉스 셸과 같은 것들은 절차적 언어입니다.

선언적 언어에서는 해결해야 할 문제를 설명하는 명세서를 작성하고, 언어 구현은 계산을 효과적으로 수행하는 방법을 파악합니다. SQL은 가장 친숙한 선언적 언어입니다; SQL 질의는 검색하고 싶은 데이터 세트를 설명하고, SQL 엔진은 테이블을 스캔하거나 인덱스를 사용할 것인지, 어떤 하위 구문을 먼저 수행해야 하는지 등을 결정합니다.

객체지향 프로그램은 객체들의 컬렉션을 다룹니다. 객체는 내부적인 상태를 갖고 있으며 이 내부적인 상태를 어떤 방식으로 가져오거나 수정하는 메서드를 제공합니다. 스몰토크와 자바는 객체지향 언어입니다. C++ 와 파이썬은 객체지향 프로그래밍을 지원하는 언어이지만, 객체 지향적인 특성들을 사용하도록 강제하지는 않습니다.

함수형 프로그래밍은 함수들의 세트로 문제를 분해합니다. 이상적으로 말하면, 함수들은 입력을 받아서 출력을 만들어내기만 하며, 주어진 입력에 대해 생성된 출력에 영향을 끼칠만한 어떠한 내부적인 상태도 가지지 않습니다. 잘 알려진 함수형 언어로는 ML 계열(Standard ML, OCaml 및 다른 변형)과 하스켈이 있습니다.

일부 컴퓨터 언어의 설계자들은 프로그래밍에 대한 한 가지의 특별한 접근 방식을 강조합니다. 이것은 종종 다른 접근 방식으로 프로그램을 작성하는 것을 어렵게 만듭니다. 다른 언어들은 다양한 접근 방법을 지원하는 다중 패러다임 언어입니다. Lisp, C++, 파이썬 등은 다중 패러다임 언어입니다; 이러한 언어에서는 절차적, 객체 지향적 혹은 함수형으로 프로그램이나 라이브러리를 작성할 수 있습니다. 거대한 프로그램에서, 각 구역은 서로 다른 접근 방법을 사용하여 작성될 수 있습니다; 예를 들어 처리 로직이 절차적 혹은 함수형으로 작성되었을 때, GUI는 객체 지향적으로 작성될 수 있습니다.

함수형 프로그램에서, 입력은 여러 함수의 세트를 통해 흘러 다닙니다. 각 함수는 입력으로부터 동작해서 출력을 만들어냅니다. 함수형 방식은 내부 상태를 수정하거나 함수의 반환 값에서 보이지 않는 다른 변경사항들을 만드는 부작용이 있는 함수를 사용하지 않습니다. 부작용이 전혀 없는 함수를 순수 함수 라고 합니다. 부작용을 피한다는 것은 프로그램이 실행될 때 수정될 수 있는 자료 구조를 사용하지 않는다는 의미입니다; 모든 함수의 출력은 입력에만 의존해야 합니다.

어떤 언어는 순수성에 대해 매우 엄격하며, a=3 혹은 c = a + b 와 같은 대입문조차 없지만, 모든 부작용을 피하는 것은 어렵습니다. 예를 들어, 화면에 출력하거나 디스크 파일에 쓰는 작업은 부작용입니다. 구체적인 예로, 파이썬에서 print() 혹은 time.sleep() 함수를 호출하면 의미 없는 값을 반환합니다; 이 함수들은 화면에 문자열을 보내거나 잠시 동안 실행을 일시 중지하는 작업과 같은 부작용을 위해 호출합니다.

함수형 방식으로 작성된 파이썬 프로그램은 보통 극단적으로 모든 I/O 혹은 대입문을 회피하는 방식으로 나아가지는 않습니다; 대신 함수형처럼 보이는 인터페이스를 제공하며 내부적으로는 함수형이 아닌 기능들을 사용합니다. 예를 들어 함수의 구현은 여전히 지역 변수에 값을 대입하는 방식이 사용되지만 전역 변수를 수정하거나 다른 부작용을 발생시키지는 않습니다.

함수형 프로그래밍은 객체 지향 프로그래밍의 반대라고 생각할 수 있습니다. 객체는 내부 상태들을 갖고 있으며 이 상태들을 수정할 수 있는 메서드의 호출 모음이 포함된 작은 캡슐이며, 프로그램은 올바른 상태 변경 집합을 구성합니다. 함수형 프로그래밍은 가능한 한 상태 변경을 피하고자 하며 함수 간의 데이터 흐름을 사용합니다. 파이썬에서는 응용 프로그램의 객체를 나타내는 인스턴스(이메일 메시지, 트랜잭션 등)를 가져와서 반환하는 함수를 작성함으로써 두 가지 접근 방식을 결합할 수 있습니다.

함수형 설계는 동작 방식에 이상한 제약이 있는 것처럼 보일 수 있습니다. 왜 객체와 부작용을 피해야만 할까요? 함수형 방식은 이론적으로도, 실질적으로도 다음과 같은 장점이 있습니다:

형식적 증명 가능성.

모듈성.

결합성.

디버깅과 테스트 용이성.

형식적 증명 가능성

이론적인 장점은 함수형 프로그램이 정확하다는 수학적 증명을 만드는 것이 더 쉽다는 것입니다.

오랫동안 연구자들은 수학적으로 프로그램이 정확하다는 것을 증명하는 방법을 찾는 데 관심을 보여왔습니다. 이것은 수많은 입력에 대해 프로그램을 테스트하고 출력이 정확하다고 결론짓거나, 프로그램의 소스코드를 읽어보고 코드가 올바르다고 결론짓는 것과는 다릅니다; 그들의 목표는 입력 가능한 모든 것에 대해 프로그램이 올바른 결과를 산출한다는 엄격한 증거를 찾는 것입니다.

프로그램이 올바른지 증명하기 위해 사용하는 기술은 항상 참인 입력 데이터와 프로그램의 변수라는 특성을 지닌 불변자 를 작성하는 것입니다. 각 코드 행에 대해, 그 행이 실행되기 전에 불변자 X와 Y가 참이라면, 그 행이 실행된 후에 약간 다른 불변자 X’ 및 Y’가 참이라는 것을 보여줍니다. 이 작업은 프로그램이 종료될 때까지 계속되며, 종료 시점에서 불변자는 프로그램의 출력으로써 원하는 조건과 일치해야만 합니다.

함수형 프로그래밍에서 값 대입을 피하려는 이유는 값 대입이 이러한 기법을 활용하는 것을 어렵게 만들기 때문입니다; 대입은 다음 단계로 나아갈 수 있는 새 불변자를 만들지 않은 채로, 대입전에 참이었던 불변자를 무너뜨릴 수 있습니다.

불행하게도, 정확한 프로그램임을 증명하는 것은 실제로는 비실용적이며 파이썬 소프트웨어와 관련이 없습니다. 사소한 프로그램일지라도 여러 페이지 분량의 증명이 필요합니다; 적당히 복잡한 프로그램에 대한 정확성의 증명은 엄청난 양일 것이며, 매일 사용하는 프로그램 (파이썬 인터프리터, XML 파서, 웹 브라우저)의 정확성은 거의 증명이 불가능할 수도 있습니다. 만약 증명을 작성하거나 만들었더라도, 그 증명이 검증된 것인지 의구심이 들 것입니다; 어쩌면 그 증명에 오류가 있을 수도 있고, 프로그램의 정확성이 증명되었다고 잘못 믿고 있을 수도 있습니다.

모듈성

함수형 프로그래밍의 실질적인 이점은 문제를 작은 조각으로 분해하도록 강제한다는 점입니다. 결과적으로 프로그램은 더욱 모듈화가 됩니다. 복잡한 변환을 수행하는 거대한 함수보다, 한 가지 작업을 수행하는 작은 함수를 명시하고 작성하기가 더 쉽습니다. 작은 함수는 읽기에도 더 쉽고 오류를 확인하기도 쉽습니다.

디버깅과 테스트 용이성

함수형 방식 프로그램은 테스트하고 디버깅하는 것이 더 쉽습니다.

일반적으로 함수가 작고 분명하게 명시되기 때문에 디버깅이 단순화됩니다. 프로그램이 동작하지 않는다면, 각 함수는 데이터가 올바른지 확인할 수 있는 접점이 됩니다. 중간 지점의 입력과 출력을 살펴보면 버그가 있는 함수를 빠르게 분간할 수 있습니다.

각 함수는 잠재적으로 단위 테스트의 대상이기 때문에 테스트가 더 쉽습니다. 함수는 테스트를 실행하기 전에 복제해야 하는 시스템 상태에 의존하지 않습니다; 올바른 입력을 만들고 결과가 예상과 일치하는지 확인만 하면 됩니다.

결합성

함수형 방식의 프로그램을 만들 때, 다양한 입력과 출력으로 여러 가지 함수를 작성하게 됩니다. 이러한 함수 중 일부는 불가피하게 특정 응용 프로그램에 특화될 수 있지만, 대체로 다양한 프로그램에서 유용하게 사용할 수 있습니다. 예를 들어 디렉터리 경로를 받아서 그 디렉터리 내의 모든 XML 파일을 반환하는 함수나, 혹은 파일명을 받아서 그 내용을 반환하는 함수는 다양한 상황에 적용할 수 있습니다.

시간이 흐르면, 여러분은 개인적인 유틸리티 라이브러리를 구성하게 될 것입니다. 보통, 새로운 구성으로 기존 함수를 배치하고 현재 작업에 특화된 몇 가지 함수만을 작성해서 새로운 프로그램을 구성하게 됩니다.

이터레이터

함수형 방식의 프로그램을 작성하는 중요한 토대가 되는 파이썬 언어의 기능을 살펴보겠습니다: 이터레이터.

이터레이터는 데이터 스트림을 나타내는 객체입니다; 이 객체는 한 번에 한 요소씩 데이터를 반환합니다. 파이썬 이터레이터는 반드시 __next__() 라는 메서드를 지원해야 합니다. 이 메서드는 인자를 취하지 않고 항상 스트림의 다음 요소를 반환합니다. 만약 스트림에 더는 요소가 없다면, __next__() 는 StopIteration 예외를 발생시켜야 합니다. 이터레이터가 유한할 필요는 없습니다; 무한한 데이터 스트림을 생성하는 이터레이터를 작성하는 것도 합리적인 방법입니다.

내장 함수 iter() 는 임의의 객체를 취하여 객체의 내용이나 요소를 반환하는 이터레이터를 반환합니다. 객체가 이터레이션을 지원하지 않으면 TypeError 를 발생시킵니다. 파이썬의 내장 데이터형 중 몇 가지가 이터레이션을 지원하는데, 가장 일반적인 것은 리스트와 딕셔너리입니다. 이터레이터를 얻을 수 있는 객체는 이터러블 이라고 불립니다.

수동으로 이터레이션 인터페이스를 실험해볼 수 있습니다:

>>> L = [1, 2, 3]
>>> it = iter(L)
>>> it
<...iterator object at ...>
>>> it.__next__()  # same as next(it)
1
>>> next(it)
2
>>> next(it)
3
>>> next(it)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
>>>

파이썬은 여러 다른 컨텍스트에서 이터러블 객체를 기대하며, 가장 중요한 것은 for 문입니다. for X in Y 문에서 Y는 반드시 이터레이터 혹은 iter() 가 이터레이터를 생성할 수 있는 객체이어야 합니다. 다음 두 문장은 같은 의미입니다:

for i in iter(obj):
    print(i)

for i in obj:
    print(i)

이터레이터는 list() 또는 tuple() 생성자 함수를 사용하여 리스트나 튜플로 나타낼 수 있습니다:

>>> L = [1, 2, 3]
>>> iterator = iter(L)
>>> t = tuple(iterator)
>>> t
(1, 2, 3)

시퀀스 언패킹 또한 이터레이터를 지원합니다: 이터레이터가 N개의 요소를 반환한다는 것을 알고 있다면, 그것들을 N-튜플로 언패킹할 수 있습니다:

>>> L = [1, 2, 3]
>>> iterator = iter(L)
>>> a, b, c = iterator
>>> a, b, c
(1, 2, 3)

max() 및 min() 과 같은 내장 함수는 하나의 이터레이터 인자를 취할 수 있으며 가장 큰 혹은 가장 작은 요소를 반환합니다. "in" 과 "not in" 연산자 또한 이터레이터를 지원합니다: 이터레이터가 반환한 스트림에서 X가 발견되면 X in iterator 는 참입니다. 이터레이터가 무한하다면 명백한 문제에 부딪힙니다; max() 와 min() 는 영원히 결과를 반환하지 않으며, 요소 X가 스트림에서 나타나지 않으면 "in" 과 "not in" 연산자 역시 영원히 결과를 반환하지 않을 것입니다.

이터레이터에서는 오직 앞으로만 나아갈 수 있다는 점에 유의하세요; 이전 요소를 가져오거나, 이터레이터를 재설정하거나, 사본을 만들 방법은 없습니다. 이터레이터 객체는 선택적으로 이러한 추가 기능을 제공할 수 있지만, 이터레이터 프로토콜은 __next__() 메서드만 명시해두었습니다. 함수는 모든 이터레이터의 출력을 소비할 수 있으므로 같은 스트림에서 다른 작업을 수행해야 하는 경우 새로운 이터레이터를 만들어야 합니다.

이터레이터를 지원하는 데이터형

리스트와 튜플이 이터레이터를 어떻게 지원하는지 이미 살펴보았습니다. 실제로 문자열과 같은 파이썬 시퀀스형은 이터레이터의 생성을 자동으로 지원합니다.

iter() 를 딕셔너리에 적용하면 딕셔너리의 키를 반복하는 이터레이터를 반환합니다:

>>> m = {'Jan': 1, 'Feb': 2, 'Mar': 3, 'Apr': 4, 'May': 5, 'Jun': 6,
...      'Jul': 7, 'Aug': 8, 'Sep': 9, 'Oct': 10, 'Nov': 11, 'Dec': 12}
>>> for key in m:
...     print(key, m[key])
Jan 1
Feb 2
Mar 3
Apr 4
May 5
Jun 6
Jul 7
Aug 8
Sep 9
Oct 10
Nov 11
Dec 12

파이썬 3.7부터는, 딕셔너리 이터레이션 순서가 삽입 순서와 같음을 보장합니다. 이전 버전에서는, 동작이 지정되지 않았고 구현마다 다를 수 있었습니다.

iter() 를 딕셔너리에 적용하는 것은 항상 키를 반복하지만, 딕셔너리에는 다른 이터레이터를 반환하는 메서드가 있습니다. 값이나 키/값 쌍을 반복하는 경우에는 명시적으로 values() 혹은 items() 메서드를 사용하여 적절한 이터레이터를 얻을 수 있습니다.

dict() 생성자는 (키, 값) 튜플의 유한한 스트림을 반환하는 이터레이터를 받을 수 있습니다:

>>> L = [('Italy', 'Rome'), ('France', 'Paris'), ('US', 'Washington DC')]
>>> dict(iter(L))
{'Italy': 'Rome', 'France': 'Paris', 'US': 'Washington DC'}

또한 파일은 더는 새로운 줄이 없을 때까지 readline() 메서드를 호출하여 이터레이션을 지원합니다. 즉, 다음과 같이 파일의 각 행을 읽을 수 있습니다:

for line in file:
    # do something for each line
    ...

집합은 이터러블에서 내용을 가져와서 집합의 원소를 반복할 수 있습니다:

S = {2, 3, 5, 7, 11, 13}
for i in S:
    print(i)

제너레이터 표현식과 리스트 컴프리헨션

이터레이터의 출력에 대한 두 가지 일반적인 연산은 1) 모든 요소에 대해 어떤 연산을 수행하고, 2) 어떤 조건을 만족하는 요소의 부분 집합을 선택하는 것입니다. 예를 들어 문자열 리스트가 있으면 각 줄에서 후미 공백을 제거하거나, 주어진 부분 문자열을 포함하는 모든 문자열을 추출할 수 있습니다.

리스트 컴프리헨션과 제너레이터 표현식(줄임말: “listcomps” 및 “genexps”)은 함수형 프로그래밍 언어 하스켈(https://www.haskell.org/)에서 빌린 이러한 작업을 위한 간결한 표기법입니다. 다음 코드를 사용하여 문자열 스트림에서 모든 공백을 제거할 수 있습니다:

line_list = ['  line 1\n', 'line 2  \n', ...]

# Generator expression -- returns iterator
stripped_iter = (line.strip() for line in line_list)

# List comprehension -- returns list
stripped_list = [line.strip() for line in line_list]

"if" 조건을 추가하여 특정 요소만 선택할 수도 있습니다:

stripped_list = [line.strip() for line in line_list
                 if line != ""]

리스트 컴프리헨션을 사용하면 파이썬 리스트를 얻을 수 있습니다; stripped_list 는 이터레이터가 아니라 결과 행을 담고 있는 리스트입니다. 제너레이터 표현식은 필요에 따라 값을 계산하는 이터레이터를 반환하며 모든 값을 한 번에 구체화할 필요가 없습니다. 즉, 무한 스트림이나 매우 많은 양의 데이터를 반환하는 이터레이터로 작업하는 경우 리스트 컴프리헨션은 유용하지 않습니다. 제너레이터 표현식은 이러한 상황에서 유용합니다.

제너레이터 표현식은 괄호(“()”)로 묶여 있으며 리스트 컴프리헨션은 대괄호(“[]”)로 묶여 있습니다. 제너레이터 표현식은 다음과 같은 형식입니다:

( expression for expr in sequence1
             if condition1
             for expr2 in sequence2
             if condition2
             for expr3 in sequence3 ...
             if condition3
             for exprN in sequenceN
             if conditionN )

다시 말하면, 리스트 컴프리헨션을 위해서는 바깥쪽 괄호만 다릅니다(괄호 대신 대괄호).

생성된 출력의 요소는 expression 의 연속적인 값이 될 것입니다. if 절은 모두 선택적입니다; if 절이 존재한다면, expression 은 condition 이 참일 때만 평가되고 결과에 추가됩니다.

제너레이터 표현식은 항상 괄호 안에 작성해야 하지만 함수 호출을 알리는 괄호도 포함됩니다. 함수에 즉시 전달되는 이터레이터를 만들고 싶다면 다음과 같이 작성할 수 있습니다:

obj_total = sum(obj.count for obj in list_all_objects())

for...in 절은 반복할 시퀀스를 포함합니다. 시퀀스는 왼쪽에서 오른쪽으로 반복되며 병렬로 처리되지 않기 때문에 같은 길이일 필요는 없습니다. sequence1 의 각 요소에 대해 sequence2 는 처음부터 반복됩니다. sequence3 은 sequence1 과 sequence2 의 각각 모든 결과에 대해 반복됩니다.

다른 식으로 표현하면, 리스트 컴프리헨션 혹은 제너레이터 표현식은 다음 파이썬 코드와 같습니다:

for expr1 in sequence1:
    if not (condition1):
        continue   # Skip this element
    for expr2 in sequence2:
        if not (condition2):
            continue   # Skip this element
        ...
        for exprN in sequenceN:
            if not (conditionN):
                continue   # Skip this element

            # Output the value of
            # the expression.

이것은 여러 개의 for...in 절이 있지만 if 절이 없을 때 결과 출력의 길이가 모든 시퀀스 길이의 곱과 같음을 의미합니다. 길이가 3인 두 개의 리스트가 있는 경우 출력 목록의 길이는 9개입니다:

>>> seq1 = 'abc'
>>> seq2 = (1, 2, 3)
>>> [(x, y) for x in seq1 for y in seq2]
[('a', 1), ('a', 2), ('a', 3),
 ('b', 1), ('b', 2), ('b', 3),
 ('c', 1), ('c', 2), ('c', 3)]

파이썬 문법의 모호함을 피하고자, expression 이 튜플을 생성하고 있다면, 괄호로 묶어야 합니다. 아래의 첫 번째 리스트 컴프리헨션은 구문 오류이며, 두 번째는 올바릅니다:

# Syntax error
[x, y for x in seq1 for y in seq2]
# Correct
[(x, y) for x in seq1 for y in seq2]

제너레이터

제너레이터는 이터레이터를 작성하는 작업을 단순화하는 특별한 클래스의 함수입니다. 일반 함수는 값을 계산하여 반환하지만, 제너레이터는 값의 스트림을 반환하는 이터레이터를 반환합니다.

파이썬이나 C에서 정규 함수 호출이 어떻게 작동하는지 잘 알고 있을 것입니다. 함수를 호출하면 지역 변수가 생성되는 비공개 이름 공간이 생깁니다. 함수가 return 문에 도달하면 지역 변수가 소멸하고 그 값이 호출자에게 반환됩니다. 같은 함수를 나중에 호출하면 새로운 비공개 이름 공간과 새로운 지역 변수 집합이 만들어집니다. 그러나 지역 변수가 함수를 빠져나갈 때 버려지지 않으면 어떻게 될까요? 나중에 중단했던 곳에서 함수를 다시 시작할 수 있다면 어떨까요? 이것이 제너레이터가 제공하는 것입니다; 그들은 재개 가능한 함수라고 생각할 수 있습니다.

다음은 제너레이터 함수의 가장 간단한 예입니다:

>>> def generate_ints(N):
...    for i in range(N):
...        yield i

yield 키워드를 포함하는 함수는 제너레이터 함수입니다; 이것은 파이썬의 바이트코드 컴파일러에 의해 감지됩니다. 결과적으로 컴파일러는 특별하게 함수를 컴파일합니다.

제너레이터 함수를 호출하면 단일 값을 반환하지 않습니다; 대신 이터레이터 프로토콜을 지원하는 제너레이터 객체를 반환합니다. yield 표현식을 실행하면 제너레이터는 return 문과 비슷하게 i 의 값을 출력합니다. yield 와 return 의 큰 차이점은 yield 에 도달하면 제너레이터의 실행 상태가 일시 중단되고 지역 변수가 보존된다는 것입니다. 제너레이터의 __next__() 메서드가 다음에 실행될 때, 함수가 다시 실행됩니다.

다음은 generate_ints() 제너레이터의 사용 예입니다:

>>> gen = generate_ints(3)
>>> gen
<generator object generate_ints at ...>
>>> next(gen)
0
>>> next(gen)
1
>>> next(gen)
2
>>> next(gen)
Traceback (most recent call last):
  File "stdin", line 1, in <module>
  File "stdin", line 2, in generate_ints
StopIteration

여러분은 똑같이 for i in generate_ints(5) 또는 a, b, c = generate_ints(3) 라고 쓸 수 있습니다.

제너레이터 함수 내에서, return value 는 __next__() 메서드에서 StopIteration(value) 를 발생시킵니다. 이런 일이 발생하거나 함수의 맨 아래에 도달하면 값의 행렬이 끝나고 제너레이터는 더는 값을 산출할 수 없습니다.

직접 클래스를 작성하고 제너레이터의 모든 지역 변수를 인스턴스 변수로 저장하여 제너레이터의 효과를 수동으로 얻을 수 있습니다. 예를 들어, 정수 리스트를 반환하는 것은 self.count 를 0으로 설정하고 __next__() 메서드로 self.count 를 증가시켜 반환하는 식으로 수행할 수 있습니다. 그러나, 다소 복잡한 제너레이터의 경우에는 해당 클래스를 작성하는 것이 훨씬 더 복잡할 수 있습니다.

파이썬의 라이브러리인 Lib/test/test_generators.py [https://github.com/python/cpython/tree/3.7/Lib/test/test_generators.py] 에 포함된 테스트 묶음에는 더 많은 흥미로운 예제들이 있습니다. 제너레이터를 재귀적으로 사용하여 트리를 중위 순회하는 것을 구현하는 하나의 제너레이터가 있습니다.

# A recursive generator that generates Tree leaves in in-order.
def inorder(t):
    if t:
        for x in inorder(t.left):
            yield x

        yield t.label

        for x in inorder(t.right):
            yield x

test_generators.py 의 다른 두 가지 예는, N-여왕 문제(NxN 체스판에 서로 다른 왕비를 위협할 수 없도록 N개의 왕비를 배치하는 문제)와 기사의 여행(기사가 NxN 체스판의 모든 칸을 정확히 한 번씩 갈 수 있도록 하는 방법을 찾는 문제)입니다.

제너레이터에 값 전달하기

파이썬 2.4 및 그 이전 버전에서 제너레이터는 출력만 생성했습니다. 제너레이터의 코드가 이터레이터를 만들기 위해 호출된 후에는 그 실행이 다시 시작될 때 함수에 새로운 정보를 전달할 방법이 없었습니다. 제너레이터가 전역 변수를 보거나 호출자가 수정할 수 있는 변경 가능한 객체를 전달함으로써 이 기능을 해킹할 수 있지만, 이러한 접근법은 지저분한 방식입니다.

파이썬 2.5에서는 제너레이터에 값을 전달하는 간단한 방법이 있습니다. yield 는 표현식이 되어 변수에 대입하거나 다른 식으로 조작할 수 있는 값을 반환합니다:

val = (yield i)

위 예제처럼 반환 값으로 무엇인가를 할 때 yield 표현식 주위에 항상 괄호를 넣는 것이 좋습니다. 괄호는 항상 필요한 것은 아니지만 필요한 시점을 기억하지 않고 항상 추가하기가 더 쉽습니다.

(PEP 342 [https://www.python.org/dev/peps/pep-0342] 는 정확한 규칙을 설명합니다. 이것은 대입의 오른쪽에 있는 최상위 표현식에서 발생하는 경우를 제외하고 항상 yield 표현식을 괄호로 묶어야 한다는 것입니다. val = yield i 라고 쓸 수도 있지만, val = (yield i) + 12 처럼 연산이 있을 때는 괄호를 써야합니다.)

값은 send(value) 메서드를 호출하여 제너레이터로 보내집니다. 이 메서드는 제너레이터의 코드를 다시 시작하고 yield 표현식은 지정된 값을 반환합니다. 만약 정규 __next__() 메서드가 호출되면 yield 는 None 을 반환합니다.

다음은 1씩 증가하며 내부 카운터값을 변경할 수 있는 간단한 카운터입니다.

def counter(maximum):
    i = 0
    while i < maximum:
        val = (yield i)
        # If value provided, change counter
        if val is not None:
            i = val
        else:
            i += 1

다음은 카운터 변경의 예시입니다:

>>> it = counter(10)
>>> next(it)
0
>>> next(it)
1
>>> it.send(8)
8
>>> next(it)
9
>>> next(it)
Traceback (most recent call last):
  File "t.py", line 15, in <module>
    it.next()
StopIteration

yield 가 종종 None 을 반환할 것이므로, 항상 이 경우를 확인해야 합니다. send() 메서드가 제너레이터 함수를 다시 시작하는데 사용되는 유일한 메서드가 아니라면, 표현식의 결괏값을 확인없이 사용하지 마세요.

send() 외에도 제너레이터에 대한 두 가지 다른 메서드가 있습니다:

throw(type, value=None, traceback=None) 는 제너레이터 내에서 예외를 발생시키는 데 사용됩니다; 예외는 제너레이터의 실행이 일시 중지된 yield 표현식에 의해 발생합니다.

close() 는 생성자 내에서 GeneratorExit 예외를 발생시켜 이터레이션을 종료합니다. 이 예외가 발생하면 제너레이터의 코드는 GeneratorExit 또는 StopIteration 을 발생시켜야 합니다; 예외를 받고도 다른 작업을 하는 것은 금지되어 있으며 RuntimeError 를 촉발합니다. close() 는 제너레이터가 가비지로 수거될 때 파이썬의 가비지 수거기에 의해 호출될 것입니다.

GeneratorExit 이 발생할 때 정리 작업을 위한 코드를 실행해야 한다면 GeneratorExit 를 잡는 대신 try: ... finally: 를 사용하는 것이 좋습니다.

이러한 변화의 누적 효과는 제너레이터를 일방적인 정보 생산자에서 생산자와 소비자 모두로 전환하는 것입니다.

제너레이터는 코루틴 이 되어 더 일반적인 형태의 서브루틴이 됩니다. 서브루틴은 한 지점에서 시작되고 다른 한 지점(함수의 맨 위와 return 문)에서 빠져나옵니다. 그러나 여러 다른 지점에서 코루틴을 시작하고 빠져나오고 다시 시작할 수 있습니다(yield 문).

내장 함수

이터레이터에서 자주 사용되는 내장 함수를 자세히 살펴보겠습니다.

파이썬의 두 가지 내장 함수인 map() 와 filter() 는 제너레이터 표현식의 기능을 복제합니다:

map(f, iterA, iterB, ...) 은 다음과 같은 시퀀스에 대한 이터레이터를 반환합니다.

f(iterA[0], iterB[0]), f(iterA[1], iterB[1]), f(iterA[2], iterB[2]), ....

>>> def upper(s):
...     return s.upper()

>>> list(map(upper, ['sentence', 'fragment']))
['SENTENCE', 'FRAGMENT']
>>> [upper(s) for s in ['sentence', 'fragment']]
['SENTENCE', 'FRAGMENT']

물론 리스트 컴프리헨션으로 같은 효과를 얻을 수 있습니다.

filter(predicate, iter) 는 특정 조건을 만족하는 모든 시퀀스 요소에 대한 이터레이터를 반환하며, 마찬가지로 리스트 컴프리헨션에 의해 복제됩니다. predicate 는 어떤 조건의 진릿값을 반환하는 함수입니다; filter() 와 함께 사용하는 경우, predicate는 단일 값을 받아들여야 합니다.

>>> def is_even(x):
...     return (x % 2) == 0

>>> list(filter(is_even, range(10)))
[0, 2, 4, 6, 8]

또한 이것은 리스트 컴프리헨션으로 작성될 수 있습니다:

>>> list(x for x in range(10) if is_even(x))
[0, 2, 4, 6, 8]

enumerate(iter, start=0) 는 카운트(start 부터)와 각 요소를 포함하는 2-튜플을 반환하는 이터러블의 요소를 계산합니다.

>>> for item in enumerate(['subject', 'verb', 'object']):
...     print(item)
(0, 'subject')
(1, 'verb')
(2, 'object')

enumerate() 는 리스트를 반복하고 특정 조건이 충족되는 인덱스를 기록할 때 자주 사용됩니다:

f = open('data.txt', 'r')
for i, line in enumerate(f):
    if line.strip() == '':
        print('Blank line at line #%i' % i)

sorted(iterable, key=None, reverse=False) 는 이터러블의 모든 요소를 리스트로 모으고, 리스트를 정렬하고, 정렬된 결과를 반환합니다. key 와 reverse 인자는 생성된 리스트의 sort() 메서드로 전달됩니다.

>>> import random
>>> # Generate 8 random numbers between [0, 10000)
>>> rand_list = random.sample(range(10000), 8)
>>> rand_list
[769, 7953, 9828, 6431, 8442, 9878, 6213, 2207]
>>> sorted(rand_list)
[769, 2207, 6213, 6431, 7953, 8442, 9828, 9878]
>>> sorted(rand_list, reverse=True)
[9878, 9828, 8442, 7953, 6431, 6213, 2207, 769]

(정렬에 대한 자세한 설명은 정렬 HOW TO 를 참고하세요.)

any(iter) 및 all(iter) 내장 함수는 이터러블의 진릿값을 봅니다. any() 는 이터러블의 어떤 요소가 참이면 True 를 반환하고, all() 은 모든 요소가 참이면 True 를 반환합니다:

>>> any([0, 1, 0])
True
>>> any([0, 0, 0])
False
>>> any([1, 1, 1])
True
>>> all([0, 1, 0])
False
>>> all([0, 0, 0])
False
>>> all([1, 1, 1])
True

zip(iterA, iterB, ...) 은 각 이터러블에서 하나의 요소를 취하여 튜플로 반환합니다:

zip(['a', 'b', 'c'], (1, 2, 3)) =>
  ('a', 1), ('b', 2), ('c', 3)

이 함수는 결과를 반환하기 전에 메모리 내의 리스트를 구성하거나 모든 입력 이터레이터를 처리하지 않습니다; 대신 튜플은 요청된 경우에만 생성하여 반환합니다. (이 동작의 전문 용어는 느긋한 평가 [https://en.wikipedia.org/wiki/Lazy_evaluation] 입니다.)

이 이터레이터는 모두 같은 길이의 이터러블과 함께 사용하기 위한 것입니다. 이터러블의 길이가 다른 경우 결과 스트림은 가장 짧은 이터러블과 같은 길이가 됩니다.

zip(['a', 'b'], (1, 2, 3)) =>
  ('a', 1), ('b', 2)

더 긴 이터레이터에서 나머지 요소는 버려질 수 있기 때문에 이런 방식은 피해야 합니다. 즉, 삭제된 요소를 건너뛸 위험이 있으므로 이터레이터를 계속 사용할 수 없습니다.

itertools 모듈

itertools 모듈은 공통적으로 사용되는 많은 이터레이터와 몇몇 이터레이터를 결합하기 위한 함수를 포함합니다. 이 절에서는 작은 예제를 보여줌으로써 모듈의 내용을 소개합니다.

모듈의 기능은 몇 가지 광범위한 클래스로 분류됩니다:

기존 이터레이터를 기반으로 새로운 이터레이터를 만드는 함수.

이터레이터의 요소를 함수 인자로 처리하는 함수.

이터레이터의 출력 부분을 선택하는 함수.

이터레이터의 출력을 분류하는 함수.

새로운 이터레이터 만들기

itertools.count(start, step) 는 균등하게 간격을 둔 값들의 무한한 스트림을 반환합니다. 선택적으로 기본값이 0인 시작 번호와 기본값이 1인 숫자 사이의 간격을 제공할 수 있습니다:

itertools.count() =>
  0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ...
itertools.count(10) =>
  10, 11, 12, 13, 14, 15, 16, 17, 18, 19, ...
itertools.count(10, 5) =>
  10, 15, 20, 25, 30, 35, 40, 45, 50, 55, ...

itertools.cycle(iter) 은 제공된 이터러블의 내용 사본을 저장하고 처음부터 마지막까지 요소를 반환하는 새로운 이터레이터를 반환합니다. 새로운 이터레이터는 이러한 요소를 무한히 반복합니다.

itertools.cycle([1, 2, 3, 4, 5]) =>
  1, 2, 3, 4, 5, 1, 2, 3, 4, 5, ...

itertools.repeat(elem, [n]) 는 제공된 요소를 n 번 반환하거나, n 이 제공되지 않으면 끝없이 요소를 반환합니다.

itertools.repeat('abc') =>
  abc, abc, abc, abc, abc, abc, abc, abc, abc, abc, ...
itertools.repeat('abc', 5) =>
  abc, abc, abc, abc, abc

itertools.chain(iterA, iterB, ...) 은 임의의 수의 이터러블을 입력으로 취하여, 첫 번째 이터러블의 모든 요소를 반환한 다음 두 번째 요소의 모든 요소를 반환하고, 모든 이터러블이 다 소모될 때까지 이 동작을 반복합니다.

itertools.chain(['a', 'b', 'c'], (1, 2, 3)) =>
  a, b, c, 1, 2, 3

itertools.islice(iter, [start], stop, [step]) 는 이터레이터의 조각 스트림을 반환합니다. 단일 stop 인자를 사용하면 처음 stop개 요소가 반환됩니다. 시작 인덱스를 지정하면 stop-start 요소가 생기고, step 에 값을 지정하면 요소는 그에 따라 생략됩니다. 파이썬의 문자열 및 리스트 슬라이싱과 달리, start, stop, step 에 음수값을 사용할 수 없습니다.

itertools.islice(range(10), 8) =>
  0, 1, 2, 3, 4, 5, 6, 7
itertools.islice(range(10), 2, 8) =>
  2, 3, 4, 5, 6, 7
itertools.islice(range(10), 2, 8, 2) =>
  2, 4, 6

itertools.tee(iter, [n]) 는 이터레이터를 복제합니다; 원본 이터레이터의 내용을 모두 반환하는 n 개의 독립적인 이터레이터를 반환합니다. n 에 대한 값을 제공하지 않으면 기본값은 2입니다. 이터레이터를 복제하려면 원본 이터레이터의 일부 내용을 저장해야 하므로 이터레이터가 크고 새로운 이터레이터 중 하나가 다른 것보다 많이 소비된다면 이것은 상당한 메모리를 소비할 수 있습니다.

itertools.tee( itertools.count() ) =>
   iterA, iterB

where iterA ->
   0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ...

and   iterB ->
   0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ...

요소에 대한 함수 호출

operator 모듈은 파이썬의 연산자에 대응하는 함수 집합을 포함합니다. 예를 들어 operator.add(a, b) (두 개의 값을 더하기), operator.ne(a, b) (a != b 와 동일) 및 operator.attrgetter('id') (.id 어트리뷰트를 가져오는 콜러블을 반환)와 같은 함수가 있습니다.

itertools.starmap(func, iter) 은 이터러블이 튜플의 스트림을 반환할 것이라고 가정하고, 이 튜플을 인자로 사용하여 func 를 호출합니다:

itertools.starmap(os.path.join,
                  [('/bin', 'python'), ('/usr', 'bin', 'java'),
                   ('/usr', 'bin', 'perl'), ('/usr', 'bin', 'ruby')])
=>
  /bin/python, /usr/bin/java, /usr/bin/perl, /usr/bin/ruby

요소 선택하기

또 다른 함수 모음은 서술자에 기초하여 이터러블 요소의 부분 집합을 선택합니다.

itertools.filterfalse(predicate, iter) 는 filter() 의 반대이며, predicate가 거짓을 반환하는 모든 요소를 반환합니다:

itertools.filterfalse(is_even, itertools.count()) =>
  1, 3, 5, 7, 9, 11, 13, 15, ...

itertools.takewhile(predicate, iter) 은 predicate가 참을 반환하는 한, 요소를 반환합니다. predicate가 거짓을 반환하면 이터레이터는 결과의 종료를 알립니다.

def less_than_10(x):
    return x < 10

itertools.takewhile(less_than_10, itertools.count()) =>
  0, 1, 2, 3, 4, 5, 6, 7, 8, 9

itertools.takewhile(is_even, itertools.count()) =>
  0

itertools.dropwhile(predicate, iter) 은 predicate가 참을 반환하는 동안 요소를 버리고, 나머지 이터러블의 결과를 반환합니다.

itertools.dropwhile(less_than_10, itertools.count()) =>
  10, 11, 12, 13, 14, 15, 16, 17, 18, 19, ...

itertools.dropwhile(is_even, itertools.count()) =>
  1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ...

itertools.compress(data, selectors) 는 두 개의 이터레이터를 취하고 selectors 의 해당 요소가 참인 data 의 요소만을 반환하고, 한쪽이 고갈될 때마다 중단합니다:

itertools.compress([1, 2, 3, 4, 5], [True, True, False, False, True]) =>
   1, 2, 5

조합 함수

itertools.combinations(iterable, r) 는 iterable 에 포함된 모든 요소의 가능한 r-튜플 조합을 제공하는 이터레이터를 반환합니다.

itertools.combinations([1, 2, 3, 4, 5], 2) =>
  (1, 2), (1, 3), (1, 4), (1, 5),
  (2, 3), (2, 4), (2, 5),
  (3, 4), (3, 5),
  (4, 5)

itertools.combinations([1, 2, 3, 4, 5], 3) =>
  (1, 2, 3), (1, 2, 4), (1, 2, 5), (1, 3, 4), (1, 3, 5), (1, 4, 5),
  (2, 3, 4), (2, 3, 5), (2, 4, 5),
  (3, 4, 5)

각 튜플 내의 원소들은 iterable 이 반환한 것과 같은 순서로 유지됩니다. 예를 들어 위의 예시에서 숫자 1은 항상 2, 3, 4 또는 5 앞에 옵니다. 비슷한 함수인 itertools.permutations(iterable, r=None) 은 제약 조건을 제거하여 길이 r 의 가능한 모든 순열을 반환합니다:

itertools.permutations([1, 2, 3, 4, 5], 2) =>
  (1, 2), (1, 3), (1, 4), (1, 5),
  (2, 1), (2, 3), (2, 4), (2, 5),
  (3, 1), (3, 2), (3, 4), (3, 5),
  (4, 1), (4, 2), (4, 3), (4, 5),
  (5, 1), (5, 2), (5, 3), (5, 4)

itertools.permutations([1, 2, 3, 4, 5]) =>
  (1, 2, 3, 4, 5), (1, 2, 3, 5, 4), (1, 2, 4, 3, 5),
  ...
  (5, 4, 3, 2, 1)

r 에 값을 지정하지 않으면 이터러블의 길이가 사용됩니다. 즉, 모든 요소가 치환됩니다.

이 함수는 위치별로 가능한 모든 조합을 생성하며 iterable 의 내용이 고유해야 할 필요는 없습니다:

itertools.permutations('aba', 3) =>
  ('a', 'b', 'a'), ('a', 'a', 'b'), ('b', 'a', 'a'),
  ('b', 'a', 'a'), ('a', 'a', 'b'), ('a', 'b', 'a')

같은 튜플 ('a', 'a', 'b') 가 두 번 발생하지만, 두 개의 ‘a’ 문자열은 다른 위치에서 왔습니다.

itertools.combinations_with_replacement(iterable, r) 함수는 다른 제약을 완화합니다: 요소는 단일 튜플 내에서 반복될 수 있습니다. 개념적으로 요소는 각 튜플의 첫 번째 위치에 대해 선택되고 두 번째 요소가 선택되기 전에 대체됩니다.

itertools.combinations_with_replacement([1, 2, 3, 4, 5], 2) =>
  (1, 1), (1, 2), (1, 3), (1, 4), (1, 5),
  (2, 2), (2, 3), (2, 4), (2, 5),
  (3, 3), (3, 4), (3, 5),
  (4, 4), (4, 5),
  (5, 5)

요소 분류

마지막으로 소개할 itertools.groupby(iter, key_func=None) 함수는 가장 복잡합니다. key_func(elem) 는 이터러블에 의해 반환된 각 요소에 대한 키값을 계산할 수 있는 함수입니다. 키 함수를 제공하지 않으면 키는 단순히 각 요소 자체입니다.

groupby() 는 이터러블 내부에서 키값이 같은 연속된 모든 요소를 수집하여 키값과 해당 키를 가진 요소의 이터러블을 포함하는 2-튜플의 스트림을 반환합니다.

city_list = [('Decatur', 'AL'), ('Huntsville', 'AL'), ('Selma', 'AL'),
             ('Anchorage', 'AK'), ('Nome', 'AK'),
             ('Flagstaff', 'AZ'), ('Phoenix', 'AZ'), ('Tucson', 'AZ'),
             ...
            ]

def get_state(city_state):
    return city_state[1]

itertools.groupby(city_list, get_state) =>
  ('AL', iterator-1),
  ('AK', iterator-2),
  ('AZ', iterator-3), ...

where
iterator-1 =>
  ('Decatur', 'AL'), ('Huntsville', 'AL'), ('Selma', 'AL')
iterator-2 =>
  ('Anchorage', 'AK'), ('Nome', 'AK')
iterator-3 =>
  ('Flagstaff', 'AZ'), ('Phoenix', 'AZ'), ('Tucson', 'AZ')

groupby() 는 이터러블 내부의 내용이 키에 따라 이미 정렬되었다고 가정합니다. 반환된 이터레이터 역시 이터러블 내부를 사용하므로 이터레이터-2와 해당 키를 요청하기 전에 이터레이터-1의 결과를 소진해야 합니다.

functools 모듈

파이썬 2.5의 functools 모듈은 고차 함수를 포함하고 있습니다. 고차 함수 는 하나 이상의 함수를 입력으로 사용하고 새로운 함수를 반환합니다. 이 모듈에서 가장 유용한 도구는 functools.partial() 함수입니다.

함수형 방식으로 작성된 프로그램의 경우, 일부 매개 변수가 채워진 기존 함수의 변형이 필요한 경우가 있습니다. 파이썬 함수 f(a, b, c) 를 고려해보세요; 파이썬 함수인 f(1, b, c) 에 해당하는 새로운 함수 g(b, c) 를 만들 수 있습니다; 이를 “부분적 함수 적용” 이라고 합니다.

partial() 의 생성자는 (function, arg1, arg2, ..., kwarg1=value1, kwarg2=value2) 와 같은 인자를 취합니다. 결과 객체는 콜러블이므로, 채워진 인자로 function 을 실행하기 위해서는 결과 객체를 호출하면 됩니다.

작지만 현실적인 예가 있습니다:

import functools

def log(message, subsystem):
    """Write the contents of 'message' to the specified subsystem."""
    print('%s: %s' % (subsystem, message))
    ...

server_log = functools.partial(log, subsystem='server')
server_log('Unable to open socket')

functools.reduce(func, iter, [initial_value]) 는 모든 이터러블 요소에 대해 누적 연산을 수행하므로 무한 이터러블에 적용할 수 없습니다. func 는 두 요소를 사용하여 하나의 값을 반환하는 함수이어야 합니다. functools.reduce() 는 이터레이터가 반환한 처음 두 요소 A와 B를 취해 func(A, B) 를 계산합니다. 그다음 세 번째 요소인 C를 취해 func(func(A, B), C) 를 계산하고, 이 결과를 반환된 네 번째 요소와 결합해 이터러블이 소진될 때까지 계속합니다. 이터러블이 전혀 값을 반환하지 않으면 TypeError 예외가 발생합니다. 초기값이 제공되면 시작점으로 사용되며 func(initial_value, A) 가 첫 번째로 계산됩니다.

>>> import operator, functools
>>> functools.reduce(operator.concat, ['A', 'BB', 'C'])
'ABBC'
>>> functools.reduce(operator.concat, [])
Traceback (most recent call last):
  ...
TypeError: reduce() of empty sequence with no initial value
>>> functools.reduce(operator.mul, [1, 2, 3], 1)
6
>>> functools.reduce(operator.mul, [], 1)
1

operator.add() 를 functools.reduce() 와 함께 사용하면 이터러블의 모든 요소를 합합니다. 이 경우는 매우 일반적이어서 이를 계산하기 위해 sum() 이라는 특수 내장 함수가 제공됩니다:

>>> import functools, operator
>>> functools.reduce(operator.add, [1, 2, 3, 4], 0)
10
>>> sum([1, 2, 3, 4])
10
>>> sum([])
0

그렇지만 functools.reduce() 를 사용하는 많은 경우에 명백하게 for 루프만 작성하는 것이 더 명확할 수 있습니다:

import functools
# Instead of:
product = functools.reduce(operator.mul, [1, 2, 3], 1)

# You can write:
product = 1
for i in [1, 2, 3]:
    product *= i

관련 함수는 itertools.accumulate(iterable, func=operator.add) 입니다. 같은 계산을 수행하지만, 최종 결과만 반환하는 대신 accumulate() 는 각 부분 결과를 반환하는 이터레이터를 반환합니다:

itertools.accumulate([1, 2, 3, 4, 5]) =>
  1, 3, 6, 10, 15

itertools.accumulate([1, 2, 3, 4, 5], operator.mul) =>
  1, 2, 6, 24, 120

operator 모듈

operator 모듈은 이전에 언급되었습니다. 여기에는 파이썬 연산자에 해당하는 함수 집합이 포함되어 있습니다. 단일 연산을 수행하는 사소한 함수를 작성하지 않아도 되므로 이러한 함수는 함수형 방식 코드에서 유용합니다.

이 모듈의 몇몇 함수는 다음과 같습니다:

수학 연산: add(), sub(), mul(), floordiv(), abs(), …

논리 연산: not_(), truth().

비트 연산: and_(), or_(), invert().

비교: eq(), ne(), lt(), le(), gt(), ge().

객체 아이덴티티: is_(), is_not().

전체 목록은 연산자 모듈의 문서를 참고하세요.

작은 함수와 람다 표현식

함수형 방식의 프로그램을 작성할 때, 서술자로 동작하거나 어떤 식으로든 요소를 결합하는 작은 함수가 필요할 것입니다.

파이썬 내장 함수나 적당한 모듈 함수가 있다면, 새로운 함수를 정의할 필요가 전혀 없습니다:

stripped_lines = [line.strip() for line in lines]
existing_files = filter(os.path.exists, file_list)

필요한 기능이 없다면 작성해야 합니다. 작은 함수를 작성하는 한 가지 방법은 lambda 표현식을 사용하는 것입니다. lambda 는 여러 매개 변수와 이들 매개 변수를 결합하는 표현식을 취해 표현식의 값을 반환하는 익명의 함수를 만듭니다:

adder = lambda x, y: x+y

print_assign = lambda name, value: name + '=' + str(value)

다른 방법은 def 문을 사용하고 일반적인 방식으로 함수를 정의하는 것입니다:

def adder(x, y):
    return x + y

def print_assign(name, value):
    return name + '=' + str(value)

어떤 대안이 바람직할까요? 이것은 스타일에 대한 질문입니다; 필자가 평소에 사용하는 방법은 lambda 사용을 피하는 것입니다.

필자가 선호하는 방식에 대한 이유 중 하나는 lambda 가 정의할 수 있는 함수가 상당히 제한적이기 때문입니다. 결과는 단일 표현식으로 계산할 수 있어야 합니다. 즉, if... elif... else 비교 또는 try... except 문을 가질 수 없습니다. lambda 문에서 너무 많은 것을 하려고 하면, 읽기 어려운 복잡한 표현으로 끝날 것입니다. 다음 코드가 무엇을 하는지 빠르게 알아보세요.

import functools
total = functools.reduce(lambda a, b: (0, a[1] + b[1]), items)[1]

여러분은 이해할 수 있지만, 어떻게 동작하는지 이해하기 위해 표현식을 풀어내는 데 시간이 걸립니다. 짧게 중첩된 def 문을 사용하면 좀 더 나은 것을 만들 수 있습니다:

import functools
def combine(a, b):
    return 0, a[1] + b[1]

total = functools.reduce(combine, items)[1]

그러나 단순히 for 루프를 사용했다면 가장 좋았을 것입니다:

total = 0
for a, b in items:
    total += b

혹은 sum() 내장 함수와 제너레이터 표현식이었어도 좋았을 것입니다:

total = sum(b for a, b in items)

functools.reduce() 를 사용하는 많은 경우, for 루프로 작성했을 때 더 명확합니다.

Fredrik Lundh는 한때 lambda 사용법의 리팩토링을 위해 다음과 같은 규칙 집합을 제안했습니다:

람다 함수를 작성하세요.

람다가 하는 일에 관해 설명하는 글을 쓰세요.

잠깐 설명을 검토하고 설명의 본질을 포착하는 이름을 생각해보세요.

해당 이름을 사용하여 람다를 def 문으로 변환합니다.

설명을 삭제하세요.

필자는 이 규칙을 정말 좋아하지만, 여러분은 이렇게 람다가 없는 방식이 더 나은지에 대해 동의하지 않을 수 있습니다.

개정내역 및 감사의 글

필자는 이 글의 다양한 초안을 제안하고 수정하고 도와준 다음 사람들에게 감사하고 싶습니다: Ian Bicking, Nick Coghlan, Nick Efford, Raymond Hettinger, Jim Jewett, Mike Krell, Leandro Lameiro, Jussi Salmela, Collin Winter, Blake Winton.

버전 0.1: 2006년 6월 30일 게시.

버전 0.11: 2006년 7월 1일 게시. 오타 수정.

버전 0.2: 2006년 7월 10일 게시. 제너레이터 표현식과 리스트 컴프리헨션 섹션을 하나로 통합. 오타 수정.

버전 0.21: 튜터 메일링 리스트에서 추천된 참고 문헌을 추가.

버전 0.30: Collin Winter가 작성한 functional 모듈에 대한 섹션 추가; 연산자 모듈에 대한 짧은 섹션 추가; 몇 가지 다른 편집.

참고 문헌

일반

Harold Abelson과 Gerald Jay Sussman, Julie Sussman의 Structure and Interpretation of Computer Programs. 전체 문서는 https://mitpress.mit.edu/sicp/ 에 있습니다. 이 고전적인 컴퓨터 과학 교과서에서 2장과 3장은 프로그램 내에서 데이터 흐름을 구성하기 위해 시퀀스와 스트림을 사용하는 방법을 설명합니다. 이 책은 스킴(Scheme)을 예제로 사용하지만, 이 장에서 설명한 디자인 방식 중 상당수는 함수형 방식 파이썬 코드에 적용할 수 있습니다.

http://www.defmacro.org/ramblings/fp.html: 오랜 역사적 소개와 함께 자바 예제를 사용한 함수형 프로그래밍에 대한 일반적인 개론.

https://en.wikipedia.org/wiki/Functional_programming: 함수형 프로그래밍을 설명하는 일반 위키피디아 항목.

https://en.wikipedia.org/wiki/Coroutine: 코루틴에 대한 항목.

https://en.wikipedia.org/wiki/Currying: 커링 개념에 대한 항목.

파이썬 특정

http://gnosis.cx/TPiP/: David Mertz의 책 Text Processing in Python 의 첫 번째 장에서는 “Utilizing Higher-Order Functions in Text Processing” 절에서 텍스트 처리를 위한 함수형 프로그래밍에 관해 설명합니다.

Mertz also wrote a 3-part series of articles on functional programming for IBM’s DeveloperWorks site; see part 1 [https://developer.ibm.com/articles/l-prog/], part 2 [https://developer.ibm.com/tutorials/l-prog2/], and part 3 [https://developer.ibm.com/tutorials/l-prog3/],

파이썬 설명서

itertools 모듈에 대한 설명서

functools 모듈에 대한 설명서

operator 모듈에 대한 설명서

PEP 289 [https://www.python.org/dev/peps/pep-0289]: “제너레이터 표현식”

PEP 342 [https://www.python.org/dev/peps/pep-0342]: “개선된 제너레이터를 통한 코루틴” 은 파이썬 2.5의 새로운 제너레이터 기능을 설명합니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 HOWTO »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 HOWTO »

|

로깅 HOWTO

저자

Vinay Sajip <vinay_sajip at red-dove dot com>

기초 로깅 자습서

로깅은 어떤 소프트웨어가 실행될 때 발생하는 이벤트를 추적하는 수단입니다. 소프트웨어 개발자는 코드에 로깅 호출을 추가하여 특정 이벤트가 발생했음을 나타냅니다. 이벤트는 선택적으로 가변 데이터 (즉, 이벤트 발생마다 잠재적으로 다른 데이터)를 포함할 수 있는 설명 메시지로 기술됩니다. 이벤트는 또한 개발자가 이벤트에 부여한 중요도를 가지고 있습니다; 중요도는 수준(level) 또는 심각도(severity) 라고도 부를 수 있습니다.

로깅을 사용할 때

로깅은 간단한 로깅 사용을 위한 일련의 편리 함수를 제공합니다. debug(), info(), warning(), error() 그리고 critical() 입니다. 로깅을 사용할 때를 결정하려면 아래 표를 참조하십시오. 일반적인 작업 집합 각각에 대해 사용하기에 가장 적합한 도구를 설명합니다.

수행하려는 작업

작업을 위한 최상의 도구

명령행 스크립트 또는 프로그램의 일반적인 사용을 위한 콘솔 출력 표시

print()

프로그램의 정상 작동 중에 발생하는 이벤트 보고 (가령 상태 모니터링이나 결함 조사)

logging.info() (또는 진단 목적의 아주 자세한 출력의 경우 logging.debug())

특정 실행시간 이벤트와 관련하여 경고를 발행

라이브러리 코드에서 warnings.warn(): 문제를 피할 수 있고 경고를 제거하기 위해 클라이언트 응용 프로그램이 수정되어야 하는 경우

logging.warning(): 클라이언트 응용 프로그램이 할 수 있는 일이 없는 상황이지만 이벤트를 계속 주목해야 하는 경우

특정 실행시간 이벤트와 관련하여 에러를 보고

예외를 일으킵니다

예외를 발생시키지 않고 에러의 억제를 보고 (가령 장기 실행 서버 프로세스의 에러 처리기)

구체적인 에러와 응용 프로그램 영역에 적절한 logging.error(), logging.exception(), logging.critical()

로깅 함수는 추적되는 이벤트의 수준 또는 심각도를 따라 명명됩니다. 표준 수준과 그 용도는 아래에 설명되어 있습니다 (심각도가 높아지는 순서대로).:

수준

사용할 때

DEBUG

상세한 정보. 보통 문제를 진단할 때만 필요합니다.

INFO

예상대로 작동하는지에 대한 확인.

WARNING

예상치 못한 일이 발생했거나 가까운 미래에 발생할 문제(예를 들어 ‘디스크 공간 부족’)에 대한 표시. 소프트웨어는 여전히 예상대로 작동합니다.

ERROR

더욱 심각한 문제로 인해, 소프트웨어가 일부 기능을 수행하지 못했습니다.

CRITICAL

심각한 에러. 프로그램 자체가 계속 실행되지 않을 수 있음을 나타냅니다.

기본 수준은 WARNING 입니다. 이는 logging 패키지가 달리 구성되지 않는 한, 이 수준 이상의 이벤트만 추적된다는 것을 의미합니다.

추적되는 이벤트는 여러 방식으로 처리될 수 있습니다. 추적된 이벤트를 처리하는 가장 간단한 방법은 콘솔에 인쇄하는 것입니다. 또 다른 일반적인 방법은 디스크 파일에 기록하는 것입니다.

간단한 예

아주 간단한 예는 이렇습니다:

import logging
logging.warning('Watch out!')  # will print a message to the console
logging.info('I told you so')  # will not print anything

이 줄들을 스크립트에 입력하고 실행하면:

WARNING:root:Watch out!

이 콘솔에 출력됩니다. 기본 수준이 WARNING 이므로, INFO 메시지는 나타나지 않습니다. 인쇄된 메시지에는 수준 표시와 로깅 호출에 제공된 이벤트의 설명(즉, ‘Watch out!’)이 포함됩니다. 당장은 ‘root’ 부분에 대해서는 걱정하지 마십시오: 나중에 설명합니다. 필요한 경우 실제 출력을 매우 유연하게 포맷 할 수 있습니다; 포매팅 옵션도 나중에 설명합니다.

파일에 로깅 하기

매우 일반적인 상황은 로깅 이벤트를 파일에 기록하는 것이므로, 다음으로 살펴보겠습니다. 새로 시작된 파이썬 인터프리터에서 다음을 시도해보고, 위에서 설명한 세션을 계속 진행하지는 마십시오:

import logging
logging.basicConfig(filename='example.log',level=logging.DEBUG)
logging.debug('This message should go to the log file')
logging.info('So should this')
logging.warning('And this, too')

이제 파일을 열고 내용을 살펴본다면, 로그 메시지를 찾을 수 있습니다:

DEBUG:root:This message should go to the log file
INFO:root:So should this
WARNING:root:And this, too

이 예제는 추적 임곗값 역할을 하는 로깅 수준을 설정하는 방법도 보여줍니다. 이 경우 임곗값을 DEBUG 로 설정했기 때문에 모든 메시지가 출력되었습니다.

다음과 같은 방식으로 명령행 옵션에서 로깅 수준을 설정하려고 하고:

--log=INFO

어떤 변수 loglevel 에 --log 로 전달된 매개 변수의 값이 들어있다면, 이런 방법으로:

getattr(logging, loglevel.upper())

level 인자를 통해 basicConfig() 에게 전달할 값을 얻습니다. 아마 다음 예제에서와같이, 사용자 입력 값을 오류 검사 하고 싶을 겁니다:

# assuming loglevel is bound to the string value obtained from the
# command line argument. Convert to upper case to allow the user to
# specify --log=DEBUG or --log=debug
numeric_level = getattr(logging, loglevel.upper(), None)
if not isinstance(numeric_level, int):
    raise ValueError('Invalid log level: %s' % loglevel)
logging.basicConfig(level=numeric_level, ...)

basicConfig() 에 대한 호출은 debug(), info() 등의 호출 전에 올 필요가 있습니다. 일회용의 간단한 설정 기능으로 의도되었기 때문에, 오직 첫 번째 호출만 뭔가 할 수 있습니다: 후속 호출은 사실상 아무 작업도 수행하지 않습니다.

위의 스크립트를 여러 번 실행하면, 후속 실행의 메시지가 example.log 파일에 추가됩니다. 이전 실행의 메시지를 기억하지 않고, 각 실행이 새로 시작하게 하려면, 위 예제에서 호출이 filemode 인자를 지정하도록 다음과 같이 변경할 수 있습니다:

logging.basicConfig(filename='example.log', filemode='w', level=logging.DEBUG)

출력은 이전과 같지만, 더는 로그 파일에 덧붙여지지 않으므로 이전 실행의 메시지는 손실됩니다.

여러 모듈에서의 로깅

프로그램이 여러 모듈로 구성되어있는 경우, 로깅을 구성하는 방법의 예는 다음과 같습니다:

# myapp.py
import logging
import mylib

def main():
    logging.basicConfig(filename='myapp.log', level=logging.INFO)
    logging.info('Started')
    mylib.do_something()
    logging.info('Finished')

if __name__ == '__main__':
    main()

# mylib.py
import logging

def do_something():
    logging.info('Doing something')

myapp.py 를 실행하면, myapp.log 에 다음과 같이 표시됩니다:

INFO:root:Started
INFO:root:Doing something
INFO:root:Finished

여러분이 기대한 것이기를 바랍니다. mylib.py 의 패턴을 사용하여 이것을 여러 모듈로 일반화 할 수 있습니다. 이 간단한 사용 패턴의 경우, 이벤트 설명을 보는 것 외에, 로그 파일을 들여다보는 것만으로는 메시지가 응용 프로그램의 어디서 왔는지 알 수 없습니다. 메시지의 위치를 추적하려면, 자습서 수준 이상의 문서를 참조해야 합니다 – 고급 로깅 자습서를 참조하세요.

변수 데이터 로깅

변수 데이터를 기록하려면, 이벤트 설명 메시지에 포맷 문자열을 사용하고 변수 데이터를 인자로 추가하십시오. 예를 들면:

import logging
logging.warning('%s before you %s', 'Look', 'leap!')

이것은 다음과 같이 출력합니다:

WARNING:root:Look before you leap!

보시다시피, 이벤트 설명 메시지에 가변 데이터를 병합하는데 이전 %-스타일의 문자열 포매팅을 사용합니다. 이전 버전과의 호환성을 위한 것입니다: logging 패키지는 str.format() 과 string.Template 과 같은 새로운 포매팅 옵션 이전부터 존재해왔습니다. 이 새로운 포매팅 옵션 역시 지원되지만, 이 자습서의 범위를 벗어납니다: 좀 더 자세한 정보는 응용 프로그램 전체에서 특정 포맷 스타일 사용하기를 참조하세요.

표시된 메시지의 포맷 변경

메시지를 표시하는 데 사용되는 포맷을 변경하려면 사용할 format을 지정해야 합니다:

import logging
logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.DEBUG)
logging.debug('This message should appear on the console')
logging.info('So should this')
logging.warning('And this, too')

이것은 다음과 같이 인쇄합니다:

DEBUG:This message should appear on the console
INFO:So should this
WARNING:And this, too

앞의 예제에서 나타난 ‘root’ 가 사라졌음에 주목하십시오. 포맷 문자열에 나타날 수 있는 모든 것은 LogRecord 어트리뷰트 문서를 참고하게요. 하지만, 간단한 사용을 위해서는 levelname (심각도), message (이벤트 설명, 변수 데이터 포함) 와 아마도 발생 시각을 표시해야 할 것입니다. 이것은 다음 섹션에서 설명합니다.

메시지에 날짜/시간 표시

이벤트의 날짜와 시간을 표시하려면, 포맷 문자열에 ‘%(asctime)s’ 을 넣으십시오:

import logging
logging.basicConfig(format='%(asctime)s %(message)s')
logging.warning('is when this event was logged.')

이것은 이런 식으로 인쇄합니다:

2010-12-12 11:41:42,612 is when this event was logged.

(위에 나온) 날짜/시간 표시의 기본 포맷은 ISO8601 또는 RFC 3339 [https://tools.ietf.org/html/rfc3339.html]와 같습니다. 날짜/시간의 포맷을 좀 더 제어해야 하는 경우, 이 예제에서와같이 basicConfig 에 datefmt 인자를 제공하십시오:

import logging
logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')
logging.warning('is when this event was logged.')

그러면 다음과 같이 표시됩니다:

12/12/2010 11:46:36 AM is when this event was logged.

datefmt 인자의 형식은 time.strftime() 에 의해 지원되는 것과 같습니다.

다음 단계

이것으로 기본 자습서를 마칩니다. 여러분이 로깅을 시작하고 사용하는데 충분할 겁니다. logging 패키지가 더 많은 것들을 제공하지만, 최선의 결과를 얻으려면 다음 섹션을 읽는 데 시간을 조금 더 투자하시기 바랍니다. 준비되었다면, 좋아하는 음료 한잔 준비하시고 계속합시다.

로깅 요구가 간단하면, 위의 예제를 사용하여 자신의 스크립트에 로깅을 통합하십시오. 문제가 발생하거나 이해할 수 없는 부분이 있으면 comp.lang.python 유즈넷 그룹에 질문을 올리십시오 (https://groups.google.com/forum/#!forum/comp.lang.python 에 있습니다). 도움을 받는 데 아주 오래 걸리지는 않을 겁니다.

아직 계신가요? 위의 기본 섹션보다 약간 더 고급/심층적인 자습서를 제공하는 다음 몇 섹션을 계속 읽을 수 있습니다. 그 후에, 로깅 요리책을 살펴볼 수 있습니다.

고급 로깅 자습서

logging 라이브러리는 모듈 방식으로 구성되며, 로거, 처리기, 필터 및 포매터와 같은 여러 범주의 구성 요소를 제공합니다.

로거는 응용 프로그램 코드가 직접 사용하는 인터페이스를 노출합니다.

처리기는 (로거에 의해 만들어진) 로그 레코드를 적절한 목적지로 보냅니다.

필터는 출력할 로그 레코드를 결정하기 위한 보다 정밀한 기능을 제공합니다.

포매터는 최종 출력에서 로그 레코드의 배치를 지정합니다.

로그 이벤트 정보는 LogRecord 인스턴스를 통해 로거, 처리기, 필터 및 포매터 간에 전달됩니다.

로깅은 Logger 클래스(이하 로거 (loggers) 라고 합니다) 인스턴스의 메서드를 호출하여 수행됩니다. 각 인스턴스에는 이름이 있으며, 점(마침표)을 구분 기호로 사용하여 개념적으로는 이름 공간 계층 구조로 배열됩니다. 예를 들어, ‘scan’이라는 로거는 ‘scan.text’, ‘scan.html’ 및 ‘scan.pdf’ 로거의 부모입니다. 로거 이름은 원하는 어떤 것이건 될 수 있으며, 로그 된 메시지가 시작된 응용 프로그램 영역을 나타냅니다.

로거의 이름을 지을 때 사용할 좋은 규칙은 다음과 같이 로깅을 사용하는 각 모듈에서 모듈 수준 로거를 사용하는 것입니다:

logger = logging.getLogger(__name__)

이것은 로거 이름이 패키지/모듈 계층을 추적한다는 것을 의미하며, 로거 이름으로부터 이벤트가 기록되는 위치를 직관적으로 명확히 알 수 있습니다.

로거 계층의 뿌리를 루트 로거라고 합니다. 이것이 debug(), info(), warning(), error() 그리고 critical() 함수에 의해 사용되는 로거인데, 루트 로거의 같은 이름의 메서드들 호출합니다. 함수와 메서드는 같은 서명을 가집니다. 루트 로거의 이름은 로그 된 출력에 ‘root’ 로 인쇄됩니다.

물론 로그 메시지를 다른 대상에 기록하는 것도 가능합니다. 로그 메시지를 파일, HTTP GET/POST 위치, SMTP를 통한 전자 메일, 일반 소켓, 큐 또는 syslog 나 윈도우 NT 이벤트 로그와 같은 OS 특정 로깅 메커니즘에 쓰는 지원이 패키지에 포함되어 있습니다. 목적지는 처리기 (handler) 클래스에 의해 제공됩니다. 내장된 처리기 클래스에 의해 충족되지 않는 특별한 요구 사항이 있는 경우, 자체 로그 대상 클래스를 작성할 수 있습니다.

기본적으로, 로그 메시지에는 대상이 설정되지 않습니다. 자습서 예제에서와같이 basicConfig()를 사용하여 대상(가령 콘솔 또는 파일)을 지정할 수 있습니다. debug(), info(), warning(), error() 및 critical() 함수를 호출하면 목적지가 설정되어 있지 않은지 확인합니다; 설정되지 않았다면, 실제 메시지 출력을 하기 위해 루트 로거에 위임하기 전에, 콘솔(sys.stderr)을 대상으로 설정하고 표시되는 메시지의 기본 포맷을 설정합니다.

메시지에 대해 basicConfig() 에 의해 설정된 기본 포맷은 다음과 같습니다:

severity:logger name:message

포맷 문자열을 format 키워드 인자로 basicConfig() 에 전달하여 이를 변경할 수 있습니다. 포맷 문자열 작성 방법과 관련된 모든 옵션은 Formatter 객체를 참조하십시오.

로깅 흐름

로거 및 처리기에서 로그 이벤트 정보의 흐름은 다음 도표에 설명되어 있습니다.

로거

Logger 객체는 세 가지 작업을 합니다. 첫째, 응용 프로그램이 실행시간에 메시지를 기록 할 수 있도록 여러 메서드를 응용 프로그램 코드에 노출합니다. 둘째, 로거 객체는 심각도 (기본 필터링 장치) 또는 필터 객체에 따라 어떤 로그 메시지를 처리할지 결정합니다. 셋째, 로거 객체는 관련 로그 메시지를 관심 있는 모든 로그 처리기로 전달합니다.

로거 객체에서 가장 널리 사용되는 메서드는 두 가지 범주로 분류됩니다: 구성 및 메시지 전송

다음은 가장 일반적인 구성 메서드입니다:

Logger.setLevel()은 로거가 처리할 가장 낮은 심각도의 로그 메시지를 지정합니다. debug은 가장 낮은 내장 심각도 수준이고 critical은 가장 높은 내장 심각도입니다. 예를 들어, 심각도 수준이 INFO이면 로거는 INFO, WARNING, ERROR 및 CRITICAL 메시지만 처리하고 DEBUG 메시지는 무시합니다.

Logger.addHandler() 와 Logger.removeHandler() 는 로거 객체에서 처리기 객체를 추가하고 제거합니다. 처리기는 처리기에서 더욱 자세히 다룹니다.

Logger.addFilter() 와 Logger.removeFilter() 는 로거 객체에서 필터 객체를 추가하고 제거합니다. 필터는 Filter 객체에서 더욱 자세히 다룹니다.

생성 한 모든 로거에서 항상 이 메서드를 호출할 필요는 없습니다. 이 섹션의 마지막 두 단락을 참조하십시오.

로거 객체가 구성된 상태에서 다음 메서드는 로그 메시지를 만듭니다:

Logger.debug(), Logger.info(), Logger.warning(), Logger.error() 그리고 Logger.critical()은 모두 메시지 와 메서드 이름에 해당하는 수준으로 로그 레코드를 만듭니다. 메시지는 실제로는 포맷 문자열이며, %s, %d, %f 등의 표준 문자열 치환 문법을 포함 할 수 있습니다. 나머지 인자들은 메시지의 치환 필드에 해당하는 객체 목록입니다. **kwargs 의 경우, 로깅 메서드는 exc_info 라는 키워드에 대해서만 신경을 쓰고 예외 정보를 로깅 할지를 결정할 때 사용합니다.

Logger.exception() 은 Logger.error() 와 비슷한 로그 메시지를 생성합니다. 차이점은 Logger.exception() 가 스택 트레이스를 덤프한다는 것입니다. 예외 처리기에서만 이 메서드를 호출하십시오.

Logger.log() 는 명시적 인자로 로그 수준을 받아들입니다. 위에 나열된 로그 수준 편의 메서드를 사용하는 것보다 로깅 메시지를 만들 때 더 장황해지지만, 사용자 정의 로그 수준으로 로깅 하는 방법입니다.

getLogger() 는 이름이 제공되는 경우 지정된 이름을 가진 로거 인스턴스에 대한 참조를 반환하고, 그렇지 않으면 root 를 반환합니다. 이름은 마침표로 구분된 계층적 구조입니다. 같은 이름으로 getLogger() 를 여러 번 호출하면 같은 로거 객체에 대한 참조를 반환합니다. 계층적 목록에서 더 아래쪽에 있는 로거는 목록에서 상위에 있는 로거의 자식입니다. 예를 들어, 이름이 foo 인 로거가 주어지면, foo.bar, foo.bar.baz, 그리고 foo.bam 의 이름을 가진 로거는 모두 foo 의 자손입니다.

로거에는 실효 수준 이라는 개념이 있습니다. 수준이 로거에 명시적으로 설정되지 않은 경우, 부모 수준을 실효 수준으로 대신 사용합니다. 부모가 명시적 수준 집합을 가지고 있지 않으면, 다시 그것의 부모가 검사되고, 등등 - 명시적으로 설정된 수준이 발견될 때까지 모든 조상이 검색됩니다. 루트 로거는 항상 명시적인 수준 집합(기본적으로 WARNING)을 가지고 있습니다. 이벤트 처리 여부를 결정할 때, 로거의 실효 수준이 이벤트가 로거 처리기로 전달되는지를 판별하는 데 사용됩니다.

자식 로거는 조상 로거와 연관된 처리기로 메시지를 전달합니다. 이 때문에 응용 프로그램에서 사용하는 모든 로거에 대해 처리기를 정의하고 구성할 필요가 없습니다. 최상위 수준 로거에 대한 처리기를 구성하고 필요에 따라 자식 로거를 만드는 것으로 충분합니다. (그러나, 로거의 propagate 어트리뷰트를 False 로 설정하여 전파를 끌 수 있습니다.)

처리기

Handler 객체는 (로그 메시지의 심각도를 기반으로) 적절한 로그 메시지를 처리기의 지정된 대상으로 전달하는 역할을 합니다. Logger 객체는 addHandler() 메서드를 사용하여 0개 이상의 처리기 객체를 자신에게 추가 할 수 있습니다. 예를 들어, 응용 프로그램은 모든 로그 메시지를 로그 파일로 보내고, 에러(error)와 그 이상의 모든 로그 메시지를 표준 출력으로 보내고, 모든 심각한 에러(critical) 메시지를 전자 메일 주소로 보낼 수 있습니다. 이 시나리오에서는 각 처리기가 특정 심각도의 메시지를 특정 위치로 보내는 3개의 개별 처리기가 필요합니다.

표준 라이브러리에는 꽤 많은 처리기형이 포함되어있습니다 (유용한 처리기 참조). 자습서는 주로 StreamHandler 와 FileHandler 를 예제에서 사용합니다.

처리기에는 응용 프로그램 개발자가 직접 신경 써야 할 메서드가 거의 없습니다. 기본 제공 처리기 객체를 사용하는 (즉, 사용자 정의 처리기를 만들지 않는) 응용 프로그램 개발자와 관련이 있는 처리기 메서드는 다음과 같은 구성 메서드뿐입니다:

setLevel() 메서드는 로거 객체에서와 마찬가지로 적절한 목적지로 보내지는 가장 낮은 심각도를 지정합니다. 왜 두 개의 setLevel() 메서드가 있어야 할까요? 로거에 설정된 수준은 처리기에 전달할 메시지의 심각도를 판별합니다. 각 처리기에 설정된 수준은 처리기가 전송할 메시지를 결정합니다.

setFormatter() 는 처리기가 사용할 포매터 객체를 선택합니다.

addFilter() 와 removeFilter() 는 각각 처리기에서 필터 객체를 구성하고 해제합니다.

응용 프로그램 코드는 Handler 의 인스턴스를 직접 인스턴스화해서 사용해서는 안 됩니다. 대신, Handler 클래스는 모든 처리기가 가져야 하는 인터페이스를 정의하고 자식 클래스가 사용할 수 있는 (또는 재정의할 수 있는) 기본 동작을 설정하는 베이스 클래스입니다.

포매터

포매터 객체는 로그 메시지의 최종 순서, 구조 및 내용을 구성합니다. 베이스 logging.Handler 클래스와는 달리, 응용 프로그램 코드는 포매터 클래스를 인스턴스화 할 수 있습니다. 응용 프로그램에 특별한 동작이 필요한 경우 포매터의 서브 클래스를 만들 수도 있습니다. 생성자는 세 가지 선택적 인자를 취합니다 – 메시지 포맷 문자열, 날짜 포맷 문자열 및 스타일 지시자.

logging.Formatter.__init__(fmt=None, datefmt=None, style='%')

메시지 포맷 문자열이 없으면, 기본값은 날 메시지를 사용하는 것입니다. 날짜 포맷 문자열이 없으면, 기본 날짜 형식은 다음과 같습니다:

%Y-%m-%d %H:%M:%S

끝에 밀리 초가 기록됩니다. style 은 %, ‘{’ 또는 ‘$’ 중 하나입니다. 이 중 하나가 지정되지 않으면, ‘%’ 가 사용됩니다.

style 이 ‘%’ 이면, 메시지 포맷 문자열은 %(<dictionary key>)s 스타일의 문자열 치환을 사용합니다; 가능한 키는 LogRecord 어트리뷰트 에 문서로 만들어져 있습니다. style이 ‘{’ 인 경우 메시지 포맷 문자열은 str.format()(키워드 인자 사용)과 호환되는 것으로 가정하고, 스타일이 ‘$’ 이면 메시지 포맷 문자열은 string.Template.substitute() 가 기대하는 것과 일치해야 합니다.

버전 3.2에서 변경: style 매개 변수를 추가했습니다.

다음 메시지 포맷 문자열은 사람이 읽을 수 있는 형식의 시간, 메시지의 심각도 및 메시지의 내용을 순서대로 기록합니다:

'%(asctime)s - %(levelname)s - %(message)s'

포매터는 사용자가 구성 할 수 있는 함수를 사용하여 레코드의 생성 시간을 튜플로 변환합니다. 기본적으로, time.localtime() 이 사용됩니다; 특정 포매터 인스턴스에 대해 이를 변경하려면, 인스턴스의 converter 어트리뷰트를 time.localtime() 또는 time.gmtime() 과 같은 서명을 가진 함수로 설정하십시오. 모든 포매터를 변경하려면, 예를 들어 모든 로깅 시간을 GMT로 표시하려면, Formatter 클래스의 converter 어트리뷰트를 설정하십시오 (GMT 표시를 위해 time.gmtime 으로).

로깅 구성

프로그래머는 세 가지 방법으로 로깅을 구성 할 수 있습니다:

위에 나열된 구성 메서드를 호출하는 파이썬 코드를 사용하여 로거, 처리기 및 포매터를 명시적으로 만듭니다.

로깅 구성 파일을 만들고, fileConfig() 함수를 사용하여 그것을 읽습니다.

구성 정보의 딕셔너리를 만들고, dictConfig() 함수에 전달합니다.

마지막 두 옵션에 대한 참조 설명서는 구성 함수를 참조하십시오. 다음 예제는 파이썬 코드를 사용하여 매우 단순한 로거, 콘솔 처리기 및 간단한 포매터를 구성합니다:

import logging

# create logger
logger = logging.getLogger('simple_example')
logger.setLevel(logging.DEBUG)

# create console handler and set level to debug
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)

# create formatter
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

# add formatter to ch
ch.setFormatter(formatter)

# add ch to logger
logger.addHandler(ch)

# 'application' code
logger.debug('debug message')
logger.info('info message')
logger.warning('warn message')
logger.error('error message')
logger.critical('critical message')

명령행에서 이 모듈을 실행하면 다음과 같이 출력됩니다:

$ python simple_logging_module.py
2005-03-19 15:10:26,618 - simple_example - DEBUG - debug message
2005-03-19 15:10:26,620 - simple_example - INFO - info message
2005-03-19 15:10:26,695 - simple_example - WARNING - warn message
2005-03-19 15:10:26,697 - simple_example - ERROR - error message
2005-03-19 15:10:26,773 - simple_example - CRITICAL - critical message

다음의 파이썬 모듈은 위에 열거된 예제와 거의 같고 객체의 이름 만 다른 로거, 처리기 및 포매터를 생성합니다:

import logging
import logging.config

logging.config.fileConfig('logging.conf')

# create logger
logger = logging.getLogger('simpleExample')

# 'application' code
logger.debug('debug message')
logger.info('info message')
logger.warning('warn message')
logger.error('error message')
logger.critical('critical message')

logging.conf 파일은 이렇습니다:

[loggers]
keys=root,simpleExample

[handlers]
keys=consoleHandler

[formatters]
keys=simpleFormatter

[logger_root]
level=DEBUG
handlers=consoleHandler

[logger_simpleExample]
level=DEBUG
handlers=consoleHandler
qualname=simpleExample
propagate=0

[handler_consoleHandler]
class=StreamHandler
level=DEBUG
formatter=simpleFormatter
args=(sys.stdout,)

[formatter_simpleFormatter]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
datefmt=

출력은 구성 파일 기반이 아닌 예제와 거의 같습니다:

$ python simple_logging_config.py
2005-03-19 15:38:55,977 - simpleExample - DEBUG - debug message
2005-03-19 15:38:55,979 - simpleExample - INFO - info message
2005-03-19 15:38:56,054 - simpleExample - WARNING - warn message
2005-03-19 15:38:56,055 - simpleExample - ERROR - error message
2005-03-19 15:38:56,130 - simpleExample - CRITICAL - critical message

구성 파일 접근법이 파이썬 코드 접근법보다 몇 가지 장점이 있음을 알 수 있습니다. 주로 구성과 코드의 분리와 코더가 아니라도 로깅 속성을 쉽게 수정할 수 있다는 것입니다.

경고

fileConfig() 함수는 기본 매개 변수 disable_existing_loggers 를 취하는데, 하위 호환성을 위해 기본값은 True 입니다. 이것들은 여러분이 원하는 것일 수도 있고 아닐 수도 있습니다. 왜냐하면 fileConfig() 호출 전에 존재하는 모든 비 루트 로거들이, 구성에서 명시적으로 명명되지 않는 한, 비활성화되기 때문입니다. 자세한 내용은 참조 설명서를 참조하고, 원한다면 이 매개 변수에 False 를 지정하십시오.

dictConfig() 에 전달된 딕셔너리 또한 disable_existing_loggers 키로 논리값을 지정할 수 있습니다. 딕셔너리에 명시적으로 지정되지 않으면 기본적으로 True 로 해석됩니다. 이것은 위에서 설명한 로거 비활성화 동작으로 이어지는데, 여러분이 원하는 것이 아닐 수도 있습니다. 이 경우 키에 명시적으로 False 값을 제공하십시오.

구성 파일에서 참조되는 클래스 이름은 logging 모듈에 상대적이거나, 일반적인 임포트 메커니즘을 사용하여 결정할 수 있는 절댓값이어야 합니다. 따라서, WatchedFileHandler (logging 모듈에 상대적) 또는 mypackage.mymodule.MyHandler (패키지 mypackage 와 모듈 mymodule 에 정의된 클래스, 여기서 mypackage 는 파이썬 임포트 경로에서 사용 가능해야 합니다).

파이썬 3.2에서는 구성 정보를 보관하는 딕셔너리를 사용하여 로깅을 구성하는 새로운 방법이 도입되었습니다. 이는 위에 설명된 구성 파일 기반 접근 방식의 기능을 제공하며, 새로운 응용 프로그램 및 배포에 권장되는 구성 방법입니다. 파이썬 딕셔너리가 구성 정보를 저장하는 데 사용되고, 다른 방법을 사용하여 해당 딕셔너리를 채울 수 있으므로 더 많은 구성 옵션을 갖게 됩니다. 예를 들어, 구성 딕셔너리를 채우는데 JSON 형식의 구성 파일이나, YAML 처리 기능에 액세스할 수 있는 경우, YAML 형식의 파일을 사용할 수 있습니다. 물론, 파이썬 코드로 딕셔너리를 만들거나, 소켓을 통해 피클 된 형태로 수신하거나, 그 밖의 응용 프로그램에 적합한 어떤 방식도 사용할 수 있습니다.

다음은 새로운 딕셔너리 기반 접근 방식으로 YAML 형식으로 위와 같이 구성한 예입니다:

version: 1
formatters:
  simple:
    format: '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
handlers:
  console:
    class: logging.StreamHandler
    level: DEBUG
    formatter: simple
    stream: ext://sys.stdout
loggers:
  simpleExample:
    level: DEBUG
    handlers: [console]
    propagate: no
root:
  level: DEBUG
  handlers: [console]

딕셔너리를 사용하여 로깅 하는 방법에 대한 자세한 내용은 구성 함수를 참조하십시오.

구성이 제공되지 않으면 어떻게 되는가

로깅 구성이 제공되지 않으면, 로깅 이벤트를 출력해야 하지만 이벤트를 출력하는 처리기를 찾을 수 없는 상황이 발생할 수 있습니다. 이러한 상황에서 logging 패키지의 동작은 파이썬 버전에 따라 다릅니다.

3.2 이전의 파이썬 버전의 경우 동작은 다음과 같습니다:

logging.raiseExceptions 가 False (프로덕션 모드)이면, 이벤트가 조용히 무시됩니다.

logging.raiseExceptions 가 True (개발 모드) 이면, ‘No handlers could be found for logger X.Y.Z’ 라는 메시지가 한 번 인쇄됩니다.

파이썬 3.2 및 이후 버전에서는 다음과 같이 동작합니다:

이 이벤트는 logging.lastResort 에 저장된 ‘최후 수단 처리기’를 사용하여 출력됩니다. 이 내부 처리기는 어떤 로거와도 연관되어 있지 않고, 이벤트 설명 메시지를 sys.stderr 의 현재 값으로 쓰는 (따라서 현재 효과를 발휘하고 있는 모든 리디렉션을 존중합니다) StreamHandler 처럼 동작합니다. 메시지에는 어떤 포매팅도 적용되지 않습니다 - 이벤트 설명 메시지가 그대로 인쇄됩니다. 처리기의 수준은 WARNING 으로 설정되어 있으므로, 이보다 크거나 같은 심각도의 모든 이벤트가 출력됩니다.

3.2 이전의 동작을 얻으려면, logging.lastResort 를 None 으로 설정할 수 있습니다.

라이브러리 로깅 구성

로깅을 사용하는 라이브러리를 개발할 때, 라이브러리에서 로깅을 사용하는 방법을 문서로 만들어야 합니다 - 예를 들어, 사용된 로거의 이름. 또한, 로깅 구성에 대한 고려가 필요합니다. 사용하는 응용 프로그램이 로깅을 사용하지 않고 라이브러리 코드가 로깅을 호출하면, (앞 절에서 설명했듯이) 심각도가 WARNING 이상인 이벤트는 sys.stderr 에 출력됩니다. 이것이 최상의 기본 동작인 것으로 간주합니다.

어떤 이유로 로깅 구성이 없을 때 이 메시지가 인쇄되는 것을 원하지 않는다면, 라이브러리의 최상위 로거에 아무것도 하지 않는 처리기를 연결할 수 있습니다. 이렇게 하면 메시지가 인쇄되는 것을 피할 수 있습니다. 라이브러리의 이벤트를 위한 처리기가 항상 존재하기 때문입니다: 단지 아무런 출력도 만들지 않을 뿐입니다. 라이브러리 사용자가 응용 프로그램이 사용하기 위해 로깅을 구성하면, 아마도 그 구성이 어떤 처리기를 추가할 것이고, 수준이 적절하게 구성된 경우 라이브러리에서 이루어진 로깅 호출은 그 처리기로 정상적으로 출력을 보낼 것입니다.

아무것도 하지 않는 처리기가 logging 패키지에 포함되어 있습니다: NullHandler (파이썬 3.1부터). 이 처리기의 인스턴스는 라이브러리가 사용하는 로깅 이름 공간의 최상위 로거에 추가될 수 있습니다 (만약 로깅 구성이 없는 경우 라이브러리가 로깅한 이벤트가 sys.stderr 에 출력되는 것을 막으려면). 라이브러리 foo 에 의한 모든 로깅이 ‘foo.x’, ‘foo.x.y’ 등과 일치하는 이름을 가진 로거들만 사용한다면, 다음과 같은 코드가:

import logging
logging.getLogger('foo').addHandler(logging.NullHandler())

원하는 효과를 주어야 합니다. 만약 조직이 여러 라이브러리를 만든다면, 지정된 로거 이름으로 단순한 ‘foo’ 대신에 ‘orgname.foo’를 사용할 수 있습니다.

참고

NullHandler 이외의 처리기를 라이브러리의 로거에 추가하지 않는 것이 좋습니다. 이것은 처리기 구성이 라이브러리를 사용하는 응용 프로그램 개발자의 특권이기 때문입니다. 응용 프로그램 개발자는 사용자와 응용 프로그램에 가장 적합한 처리기가 무엇인지 알고 있습니다. 여러분이 처리기를 ‘이면에서’ 추가하면, 단위 테스트를 수행하고 그들의 요구사항에 맞는 로그를 전달하는 작업을 방해할 수 있습니다.

로깅 수준

로깅 수준의 숫자 값은 다음 표에 나와 있습니다. 이것은 주로 여러분 자신의 수준을 정의하고 사전 정의된 수준에 상대적인 특정 값을 갖도록 하려는 경우 관심의 대상입니다. 같은 숫자 값을 가진 수준을 정의하면 미리 정의된 값을 덮어씁니다; 사전 정의된 이름이 유실됩니다.

수준

숫자 값

CRITICAL

50

ERROR

40

WARNING

30

INFO

20

DEBUG

10

NOTSET

0

또한, 수준은 개발자가 설정하거나 저장된 로깅 구성을 로드하여 로거와 연관될 수 있습니다. 로깅 메서드가 로거에 호출되면, 로거는 자체 수준을 메서드 호출과 연관된 수준과 비교합니다. 로거 수준이 메서드 호출보다 높으면 실제로 로깅 메시지가 생성되지 않습니다. 이것은 로그 출력의 상세도를 제어하는 기본 메커니즘입니다.

로깅 메시지는 LogRecord 클래스의 인스턴스로 인코딩됩니다. 로거가 실제로 이벤트를 로그 하기로 하면, LogRecord 인스턴스가 로깅 메시지로부터 만들어집니다.

로깅 메시지는 Handler 클래스의 서브 클래스의 인스턴스인 처리기 (handlers) 를 통한 전달 메커니즘을 적용받게 됩니다. 처리기는 로그된 메시지(LogRecord 형식)가 대상 독자(가령 최종 사용자, 지원 데스크 직원, 시스템 관리자, 개발자)에게 유용한 특정 위치(또는 위치 집합)에 도달하도록 할 책임이 있습니다. 처리기로는 특정 목적지를 위한 LogRecord 인스턴스가 전달됩니다. 각 로거에는 0개 이상의 처리기가 연관될 수 있습니다 (Logger 의 addHandler() 메서드를 통해). 로거에 직접 연관된 모든 처리기뿐만 아니라, (로거의 propagate 플래그가 거짓 값으로 설정되어 있지 않은 한, 그 지점에서 부모 처리기로의 전달이 멈춥니다) 로거의 모든 조상과 연관된 모든 처리기가 메시지를 전달하도록 호출됩니다.

로거와 마찬가지로, 처리기도 연관된 수준을 가질 수 있습니다. 처리기의 수준은 로거의 수준과 같은 방식으로 필터의 역할을 합니다. 처리기가 실제로 이벤트를 전달하기로 하면, emit() 메서드가 목적지로 메시지를 보내기 위해 사용됩니다. Handler 의 대부분의 사용자 정의 서브 클래스는 이 emit() 를 재정의해야 합니다.

사용자 정의 수준

여러분 자신의 수준을 정의하는 것이 가능하지만 필요하지는 않은데, 현재의 수준이 실무 경험에 근거하여 선택되었기 때문입니다. 하지만, 사용자 정의 수준이 필요하다고 확신하는 경우, 이를 수행할 때 많은 주의를 기울여야 합니다. 라이브러리를 개발하고 있다면 사용자 지정 수준을 정의하는 것은 매우 나쁜 생각일 수 있습니다. 왜냐하면, 여러 라이브러리 작성자가 모두 자신의 사용자 정의 수준을 정의하면, 주어진 숫자 값이 라이브러리마다 각기 다른 것을 의미 할 수 있으므로, 사용 중인 개발자가 함께 사용하는 여러 라이브러리의 로깅 결과를 제어하거나 해석하는 것이 어려울 수 있기 때문입니다.

유용한 처리기

베이스 Handler 클래스 외에도 많은 유용한 서브 클래스가 제공됩니다:

StreamHandler 인스턴스는 스트림(파일류 객체)에 메시지를 보냅니다.

FileHandler 인스턴스는 디스크 파일에 메시지를 보냅니다.

BaseRotatingHandler 는 특정 지점에서 로그 파일을 회전시키는 처리기의 베이스 클래스입니다. 직접 인스턴스화하는 것은 아닙니다. 대신 RotatingFileHandler 또는 TimedRotatingFileHandler 를 사용하십시오.

RotatingFileHandler 인스턴스는 디스크 파일에 메시지를 보내는데, 최대 로그 파일 크기와 로그 파일 회전을 지원합니다.

TimedRotatingFileHandler 인스턴스는 디스크 파일에 메시지를 보내는데, 일정한 시간 간격으로 로그 파일을 회전시킵니다.

SocketHandler 인스턴스는 TCP/IP 소켓에 메시지를 보냅니다. 3.4부터, 유닉스 도메인 소켓도 지원됩니다.

DatagramHandler 인스턴스는 UDP 소켓에 메시지를 보냅니다. 3.4부터, 유닉스 도메인 소켓도 지원됩니다.

SMTPHandler 인스턴스는 지정된 전자 우편 주소로 메시지를 보냅니다.

SysLogHandler 인스턴스는 유닉스 syslog 데몬(원격 기계에 있는 것도 가능합니다)에 메시지를 보냅니다.

NTEventLogHandler 인스턴스는 윈도우 NT/2000/XP 이벤트 로그에 메시지를 보냅니다.

MemoryHandler 인스턴스는 메모리에 있는 버퍼에 메시지를 보내는데, 특정 기준이 만족 될 때마다 플러시 됩니다.

HTTPHandler 인스턴스는 GET 또는 POST 을 사용해서 HTTP 서버에 메시지를 보냅니다.

WatchedFileHandler 인스턴스는 그들이 로깅하고 있는 파일을 감시합니다. 파일이 변경되면 닫히고 파일 이름을 사용하여 다시 열립니다. 이 처리기는 유닉스 계열 시스템에서만 유용합니다; 윈도우는 사용된 하부 메커니즘을 지원하지 않습니다.

QueueHandler 인스턴스는 queue 또는 multiprocessing 모듈에 구현된 것과 같은 큐로 메시지를 보냅니다.

NullHandler 인스턴스는 에러 메시지로 아무것도 하지 않습니다. 라이브러리 개발자가 로깅을 사용하지만, 라이브러리 사용자가 로깅을 구성하지 않으면 표시될 수 있는 ‘No handlers could be found for logger XXX’ 라는 메시지를 피하려고 할 때 사용합니다. 자세한 정보는 라이브러리 로깅 구성 를 보십시오.

버전 3.1에 추가: NullHandler 클래스.

버전 3.2에 추가: QueueHandler 클래스.

NullHandler, StreamHandler 와 FileHandler 클래스는 코어 logging 패키지에 정의되어 있습니다. 다른 처리기는 하위 모듈인 logging.handlers 에 정의되어 있습니다. (구성 기능을 위한, 또 다른 하위 모듈 logging.config 도 있습니다.)

로그된 메시지는 Formatter 클래스의 인스턴스를 통해 표시를 위해 포맷됩니다. % 연산자와 딕셔너리와 함께 사용하기에 적합한 포맷 문자열로 초기화됩니다.

일괄 처리로 여러 개의 메시지를 포맷하려면, BufferingFormatter 의 인스턴스를 사용할 수 있습니다. 포맷 문자열(일괄 처리 때 각 메시지에 적용됩니다)에 더해, 헤더와 트레일러 포맷 문자열에 대한 고려가 있습니다.

로거 수준과 처리기 수준을 기반으로 필터링하는 것만으로는 충분하지 않은 경우, Logger 및 Handler 인스턴스에 (addFilter() 메서드를 통해) Filter 인스턴스를 추가 할 수 있습니다. 메시지를 더 처리하기로 하기 전에, 로거와 처리기는 모든 필터에 허락을 요청합니다. 한 필터라도 거짓 값을 반환하면 메시지는 더 처리되지 않습니다.

기본적인 Filter 기능은 특정 로거 이름으로 필터링하는 것을 지원합니다. 이 기능을 사용하면, 명명된 로거와 그 자식으로 보낸 메시지는 필터를 통과하도록 허용되고, 다른 모든 메시지는 삭제됩니다.

로깅 중에 발생하는 예외

logging 패키지는 프로덕션에서 로깅 하는 동안 발생하는 예외를 삼키도록 설계되었습니다. 이는 로깅 이벤트를 처리하는 동안 발생하는 에러(가령 잘못된 로깅 구성, 네트워크 또는 기타 유사한 에러)가 로깅을 사용하는 응용 프로그램을 조기에 종료시키지 않도록 하기 위한 것입니다.

SystemExit 과 KeyboardInterrupt 예외는 절대 삼켜지지 않습니다. Handler 서브 클래스의 emit() 메서드가 실행되는 동안 발생하는 다른 예외는 handleError() 메서드에 전달됩니다.

Handler 에 있는 handleError() 의 기본 구현은 모듈 수준 변수 raiseExceptions 가 설정되어 있는지를 검사합니다. 설정되어있으면, 트레이스백이 sys.stderr 에 인쇄됩니다. 설정되지 않았으면 예외를 삼킵니다.

참고

raiseExceptions 의 기본값은 True 입니다. 개발 중에는, 보통 발생하는 예외에 대한 알림을 받기를 원하기 때문입니다. 프로덕션 용도로는 raiseExceptions 를 False 로 설정하는 것이 좋습니다.

임의의 객체를 메시지로 사용하기

앞의 절과 예제에서 이벤트를 로깅할 때 전달되는 메시지는 문자열이라고 가정했습니다. 그러나 이것만 가능한 것은 아닙니다. 임의의 객체를 메시지로 전달할 수 있으며, 로깅 시스템이 이를 문자열 표현으로 변환해야 할 때 __str__() 메서드가 호출됩니다. 사실, 원한다면, 문자열 표현을 계산하는 것을 완전히 피할 수 있습니다 - 예를 들어, SocketHandler 는 이벤트를 피클링해서 와이어를 통해 전송하는 방식으로 이벤트를 보냅니다.

최적화

메시지 인자의 포매팅은 피할 수 없을 때까지 연기됩니다. 하지만, 로깅 메서드에 전달된 인자를 계산하는 것 또한 비용이 많이들 수 있고, 로거가 이벤트를 버리는 경우에는 수행하지 않고 싶을 수 있습니다. 꼭 해야 할 것을 결정하기 위해서, level 인자를 취하고 해당 수준의 호출이 로거에 의해 이벤트가 생성되면 참을 반환하는 isEnabledFor() 메서드를 호출 할 수 있습니다. 다음과 같은 코드를 작성할 수 있습니다:

if logger.isEnabledFor(logging.DEBUG):
    logger.debug('Message with %s, %s', expensive_func1(),
                                        expensive_func2())

그러면, 로거의 수준이 DEBUG 보다 높게 설정된 경우, expensive_func1() 과 expensive_func2() 호출은 절대 일어나지 않습니다.

참고

때에 따라, isEnabledFor() 자체가 원하는 것보다 더 비쌀 수 있습니다 (예를 들어, 명시적 수준이 로거 계층의 상단에서만 설정된 깊이 중첩된 로거의 경우). 그러한 경우 (또는 꽉 짜인 루프 내에서 메서드를 호출하지 않으려는 경우) 지역이나 인스턴스 변수에 isEnabledFor() 의 호출 결과를 캐시하고, 매번 메서드를 호출하는 대신 그 값을 사용할 수 있습니다. 이러한 캐시 된 값은 응용 프로그램이 실행되는 동안 로깅 구성이 동적으로 변경될 때(그리 흔한 경우는 아닙니다)만 재계산될 필요가 있습니다.

로깅 정보를 수집하는 방법을 보다 정밀하게 제어해야 하는 특정 응용 프로그램에 대해 수행할 수 있는 다른 최적화가 있습니다. 다음은 필요하지 않은 로깅 처리를 피하고자 수행할 수 있는 작업 목록입니다:

수집하고 싶지 않은 것

수집하는 것을 피하는 방법

호출이 이루어진 위치에 관한 정보.

logging._srcfile 을 None 으로 설정하십시오. 이렇게 하면 sys._getframe() 호출을 피할 수 있는데, PyPy 가 파이썬 3.x를 지원할 때, PyPy(sys._getframe() 를 사용하는 코드의 속도를 높일 수 없습니다)와 같은 환경에서 코드 속도를 높이는 데 도움이 됩니다.

스레딩 정보.

logging.logThreads 를 0 으로 설정하십시오.

프로세스 정보.

logging.logProcesses 를 0 으로 설정하십시오.

또한, 코어 logging 모듈에는 기본 처리기만 포함됩니다. logging.handlers 와 logging.config 를 임포트 하지 않으면 메모리를 차지하지 않습니다.

더 보기

모듈 logging

logging 모듈에 관한 API 레퍼런스.

모듈 logging.config

logging 모듈용 구성 API.

모듈 logging.handlers

logging 모듈에 포함된 유용한 처리기.

로깅 요리책

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 HOWTO »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 HOWTO »

|

로깅 요리책

저자

Vinay Sajip <vinay_sajip at red-dove dot com>

이 페이지는 과거에 유용했던 로깅 관련 조리법을 많이 포함하고 있습니다.

여러 모듈에서 로깅 사용하기

logging.getLogger('someLogger') 를 여러 번 호출하면 같은 로거 객체에 대한 참조가 반환됩니다. 같은 모듈 내에서뿐만 아니라, 같은 파이썬 인터프리터 프로세스에 있는 한, 여러 모듈에서도 마찬가지입니다. 참조가 같은 객체를 가리킨다는 것에 더해, 응용 프로그램 코드는 하나의 모듈에서 부모 로거를 정의 및 구성하고 별도의 모듈에서 자식 로거를 생성 (구성하지 않음) 할 수 있으며, 자식에 대한 모든 로거 호출은 부모로 전달됩니다. 다음은 메인 모듈입니다:

import logging
import auxiliary_module

# create logger with 'spam_application'
logger = logging.getLogger('spam_application')
logger.setLevel(logging.DEBUG)
# create file handler which logs even debug messages
fh = logging.FileHandler('spam.log')
fh.setLevel(logging.DEBUG)
# create console handler with a higher log level
ch = logging.StreamHandler()
ch.setLevel(logging.ERROR)
# create formatter and add it to the handlers
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
ch.setFormatter(formatter)
# add the handlers to the logger
logger.addHandler(fh)
logger.addHandler(ch)

logger.info('creating an instance of auxiliary_module.Auxiliary')
a = auxiliary_module.Auxiliary()
logger.info('created an instance of auxiliary_module.Auxiliary')
logger.info('calling auxiliary_module.Auxiliary.do_something')
a.do_something()
logger.info('finished auxiliary_module.Auxiliary.do_something')
logger.info('calling auxiliary_module.some_function()')
auxiliary_module.some_function()
logger.info('done with auxiliary_module.some_function()')

다음은 보조 모듈입니다:

import logging

# create logger
module_logger = logging.getLogger('spam_application.auxiliary')

class Auxiliary:
    def __init__(self):
        self.logger = logging.getLogger('spam_application.auxiliary.Auxiliary')
        self.logger.info('creating an instance of Auxiliary')

    def do_something(self):
        self.logger.info('doing something')
        a = 1 + 1
        self.logger.info('done doing something')

def some_function():
    module_logger.info('received a call to "some_function"')

출력은 이렇게 됩니다:

2005-03-23 23:47:11,663 - spam_application - INFO -
   creating an instance of auxiliary_module.Auxiliary
2005-03-23 23:47:11,665 - spam_application.auxiliary.Auxiliary - INFO -
   creating an instance of Auxiliary
2005-03-23 23:47:11,665 - spam_application - INFO -
   created an instance of auxiliary_module.Auxiliary
2005-03-23 23:47:11,668 - spam_application - INFO -
   calling auxiliary_module.Auxiliary.do_something
2005-03-23 23:47:11,668 - spam_application.auxiliary.Auxiliary - INFO -
   doing something
2005-03-23 23:47:11,669 - spam_application.auxiliary.Auxiliary - INFO -
   done doing something
2005-03-23 23:47:11,670 - spam_application - INFO -
   finished auxiliary_module.Auxiliary.do_something
2005-03-23 23:47:11,671 - spam_application - INFO -
   calling auxiliary_module.some_function()
2005-03-23 23:47:11,672 - spam_application.auxiliary - INFO -
   received a call to 'some_function'
2005-03-23 23:47:11,673 - spam_application - INFO -
   done with auxiliary_module.some_function()

여러 스레드에서 로깅 하기

여러 스레드에서 로깅 하는데 특별한 노력이 필요하지는 않습니다. 다음 예제에서는 메인 (최초) 스레드와 다른 스레드에서의 로깅을 보여줍니다:

import logging
import threading
import time

def worker(arg):
    while not arg['stop']:
        logging.debug('Hi from myfunc')
        time.sleep(0.5)

def main():
    logging.basicConfig(level=logging.DEBUG, format='%(relativeCreated)6d %(threadName)s %(message)s')
    info = {'stop': False}
    thread = threading.Thread(target=worker, args=(info,))
    thread.start()
    while True:
        try:
            logging.debug('Hello from main')
            time.sleep(0.75)
        except KeyboardInterrupt:
            info['stop'] = True
            break
    thread.join()

if __name__ == '__main__':
    main()

실행하면 스크립트는 다음과 같이 인쇄합니다:

   0 Thread-1 Hi from myfunc
   3 MainThread Hello from main
 505 Thread-1 Hi from myfunc
 755 MainThread Hello from main
1007 Thread-1 Hi from myfunc
1507 MainThread Hello from main
1508 Thread-1 Hi from myfunc
2010 Thread-1 Hi from myfunc
2258 MainThread Hello from main
2512 Thread-1 Hi from myfunc
3009 MainThread Hello from main
3013 Thread-1 Hi from myfunc
3515 Thread-1 Hi from myfunc
3761 MainThread Hello from main
4017 Thread-1 Hi from myfunc
4513 MainThread Hello from main
4518 Thread-1 Hi from myfunc

예상대로 로그 출력이 산재해 있음을 볼 수 있습니다. 물론, 이 방법은 여기에 표시된 것보다 많은 스레드에서도 작동합니다.

다중 처리기 및 포매터

로거는 일반 파이썬 객체입니다. addHandler() 메서드에는 추가할 수 있는 처리기의 수에 대한 최소 또는 최대 할당량이 없습니다. 때로는 응용 프로그램이 모든 심각도의 모든 메시지를 텍스트 파일에 기록하는 동시에, 에러 또는 그 이상을 콘솔에 기록하는 것이 유용 할 수 있습니다. 이렇게 설정하려면, 적절한 처리기를 구성하기만 하면 됩니다. 응용 프로그램 코드의 로깅 호출은 변경되지 않습니다. 다음은 앞의 간단한 모듈 기반 구성 예제를 약간 수정 한 것입니다:

import logging

logger = logging.getLogger('simple_example')
logger.setLevel(logging.DEBUG)
# create file handler which logs even debug messages
fh = logging.FileHandler('spam.log')
fh.setLevel(logging.DEBUG)
# create console handler with a higher log level
ch = logging.StreamHandler()
ch.setLevel(logging.ERROR)
# create formatter and add it to the handlers
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
ch.setFormatter(formatter)
fh.setFormatter(formatter)
# add the handlers to logger
logger.addHandler(ch)
logger.addHandler(fh)

# 'application' code
logger.debug('debug message')
logger.info('info message')
logger.warning('warn message')
logger.error('error message')
logger.critical('critical message')

‘응용 프로그램’ 코드는 여러 처리기에 신경 쓰지 않습니다. 변경된 것은 fh 라는 새로운 처리기의 추가 및 구성뿐입니다.

중요도가 높거나 낮은 필터를 사용하여 새 처리기를 만드는 기능은 응용 프로그램을 작성하고 테스트할 때 매우 유용합니다. 디버깅을 위해 많은 print 문을 사용하는 대신에 logger.debug 를 사용하십시오: 나중에 삭제하거나 주석 처리해야 할 print 문과 달리, logger.debug 문은 소스 코드에서 그대로 유지될 수 있고, 그들을 다시 필요로 할 때까지 휴면 상태로 남아 있습니다. 그때, 필요한 유일한 변경은 로거 또는 처리기의 심각도 수준을 DEBUG로 수정하는 것입니다.

여러 대상으로 로깅 하기

다른 메시지 포맷으로 다른 상황에서 콘솔과 파일에 기록하려고 한다고 가정 해 봅시다. DEBUG 이상 수준의 메시지를 파일에 기록하고, 수준 INFO 이상인 메시지를 콘솔에 기록하려고 한다고 가정 해보십시오. 또한, 타임스탬프가 파일에는 포함되어야 하지만, 콘솔 메시지에는 없어야 한다고 가정합시다. 이렇게 하면 됩니다:

import logging

# set up logging to file - see previous section for more details
logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
                    datefmt='%m-%d %H:%M',
                    filename='/temp/myapp.log',
                    filemode='w')
# define a Handler which writes INFO messages or higher to the sys.stderr
console = logging.StreamHandler()
console.setLevel(logging.INFO)
# set a format which is simpler for console use
formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
# tell the handler to use this format
console.setFormatter(formatter)
# add the handler to the root logger
logging.getLogger('').addHandler(console)

# Now, we can log to the root logger, or any other logger. First the root...
logging.info('Jackdaws love my big sphinx of quartz.')

# Now, define a couple of other loggers which might represent areas in your
# application:

logger1 = logging.getLogger('myapp.area1')
logger2 = logging.getLogger('myapp.area2')

logger1.debug('Quick zephyrs blow, vexing daft Jim.')
logger1.info('How quickly daft jumping zebras vex.')
logger2.warning('Jail zesty vixen who grabbed pay from quack.')
logger2.error('The five boxing wizards jump quickly.')

실행하면 콘솔에는 다음과 같이 출력됩니다.

root        : INFO     Jackdaws love my big sphinx of quartz.
myapp.area1 : INFO     How quickly daft jumping zebras vex.
myapp.area2 : WARNING  Jail zesty vixen who grabbed pay from quack.
myapp.area2 : ERROR    The five boxing wizards jump quickly.

파일에는 이렇게 기록됩니다.

10-22 22:19 root         INFO     Jackdaws love my big sphinx of quartz.
10-22 22:19 myapp.area1  DEBUG    Quick zephyrs blow, vexing daft Jim.
10-22 22:19 myapp.area1  INFO     How quickly daft jumping zebras vex.
10-22 22:19 myapp.area2  WARNING  Jail zesty vixen who grabbed pay from quack.
10-22 22:19 myapp.area2  ERROR    The five boxing wizards jump quickly.

보시다시피 DEBUG 메시지는 파일에만 표시됩니다. 다른 메시지는 두 목적지로 전송됩니다.

이 예제는 콘솔과 파일 처리기를 사용하지만, 여러분이 선택하는 처리기의 수나 조합에 제약이 없습니다.

구성 서버 예제

다음은 로깅 구성 서버를 사용하는 모듈의 예입니다:

import logging
import logging.config
import time
import os

# read initial config file
logging.config.fileConfig('logging.conf')

# create and start listener on port 9999
t = logging.config.listen(9999)
t.start()

logger = logging.getLogger('simpleExample')

try:
    # loop through logging calls to see the difference
    # new configurations make, until Ctrl+C is pressed
    while True:
        logger.debug('debug message')
        logger.info('info message')
        logger.warning('warn message')
        logger.error('error message')
        logger.critical('critical message')
        time.sleep(5)
except KeyboardInterrupt:
    # cleanup
    logging.config.stopListening()
    t.join()

다음은 파일 이름을 받아서, 그 파일을 새 로깅 구성으로 (이진 인코딩된 길이를 적절하게 앞에 붙여서) 서버로 보내는 스크립트입니다:

#!/usr/bin/env python
import socket, sys, struct

with open(sys.argv[1], 'rb') as f:
    data_to_send = f.read()

HOST = 'localhost'
PORT = 9999
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print('connecting...')
s.connect((HOST, PORT))
print('sending config...')
s.send(struct.pack('>L', len(data_to_send)))
s.send(data_to_send)
s.close()
print('complete')

블록 하는 처리기 다루기

때로는 로깅 처리기가 로깅 중인 스레드를 블록 하지 않고 작업을 수행해야 하는 경우가 있습니다. 이것은 웹 응용 프로그램에서 흔히 나타나는 요구사항이지만, 물론 다른 시나리오에서도 발생합니다.

흔히 느린 행동을 보이는 범인은 SMTPHandler 입니다: 개발자의 통제 밖에 있는 여러 가지 이유로, 이메일을 보내는 데 오랜 시간이 걸릴 수 있습니다 (예를 들어, 잘 동작하지 않는 메일 또는 네트워크 인프라). 그러나 거의 모든 네트워크 기반 처리기는 블록 할 수 있습니다. SocketHandler 작업도 너무 느린 DNS 질의를 이면에서 수행 할 수 있습니다 (그리고 이 질의는 여러분의 통제 밖에 있는, 파이썬 계층 아래의 소켓 라이브러리 코드 깊숙이 있을 수 있습니다).

한 가지 해결책은 두 부분으로 된 접근법을 사용하는 것입니다. 첫 번째 부분에서는, 성능이 중요한 스레드에서 액세스하는 로거에 QueueHandler 만 붙입니다. 그들은 단순히 큐에 씁니다. 충분한 용량으로 큐의 크기를 조정하거나, 크기의 상한이 없도록 초기화 할 수 있습니다. 큐에 대한 쓰기는 일반적으로 신속하게 받아들여지지만, 코드에서 예방책으로 queue.Full 예외를 잡아야 할 것입니다. 코드에 성능이 중요한 스레드가 있는 라이브러리 개발자인 경우, 코드를 사용할 다른 개발자의 이익을 위해 이것을 (여러분의 로거에 QueueHandlers 만 붙이라는 제안과 함께) 문서로 만들어야 합니다.

해결책의 두 번째 부분은 QueueListener며, 이는 QueueHandler 에 상응하여 설계되었습니다. QueueListener 는 매우 간단합니다: 큐와 처리기를 넘겨주면 QueueHandlers (또는 LogRecords 의 다른 소스)에서 보낸 LogRecord를 큐에서 수신하는 내부 스레드를 시작합니다. LogRecords 는 큐에서 제거되고 처리를 위해 처리기로 전달됩니다.

별도의 QueueListener 클래스를 사용하면 같은 인스턴스를 사용하여 여러 개의 QueueHandlers 를 처리할 수 있다는 장점이 있습니다. 이것은 특별한 이점 없이 처리기당 하나의 스레드를 먹게 되는 기존의 처리기 클래스의 스레드 버전을 만드는 것보다 자원 친화적입니다.

이 두 클래스를 사용하는 예제는 다음과 같습니다 (임포트 생략):

que = queue.Queue(-1)  # no limit on size
queue_handler = QueueHandler(que)
handler = logging.StreamHandler()
listener = QueueListener(que, handler)
root = logging.getLogger()
root.addHandler(queue_handler)
formatter = logging.Formatter('%(threadName)s: %(message)s')
handler.setFormatter(formatter)
listener.start()
# The log output will display the thread which generated
# the event (the main thread) rather than the internal
# thread which monitors the internal queue. This is what
# you want to happen.
root.warning('Look out!')
listener.stop()

실행하면, 다음과 같은 결과를 만듭니다:

MainThread: Look out!

버전 3.5에서 변경: 파이썬 3.5 이전 버전에서는, QueueListener 는 항상 큐에서 받은 모든 메시지를 초기화될 때 제공된 모든 처리기로 전달했습니다. (이것은 큐가 채워질 때 수준 필터링이 모두 반대편에서 행해졌다고 가정했기 때문입니다.) 3.5 이후부터, 이 동작은 키워드 인자 respect_handler_level=True 를 리스너의 생성자에 전달함으로써 변경될 수 있습니다. 이렇게 할 때, 리스너는 각 메시지의 수준을 처리기의 수준과 비교하여, 적절한 메시지만 처리기에 전달되도록 합니다.

네트워크에서 로깅 이벤트 보내고 받기

네트워크를 통해 로깅 이벤트를 보내고, 받는 쪽에서 처리하려고 한다고 합시다. 이렇게 하는 간단한 방법은 SocketHandler 인스턴스를 보내는 쪽의 루트 로거에 연결하는 것입니다:

import logging, logging.handlers

rootLogger = logging.getLogger('')
rootLogger.setLevel(logging.DEBUG)
socketHandler = logging.handlers.SocketHandler('localhost',
                    logging.handlers.DEFAULT_TCP_LOGGING_PORT)
# don't bother with a formatter, since a socket handler sends the event as
# an unformatted pickle
rootLogger.addHandler(socketHandler)

# Now, we can log to the root logger, or any other logger. First the root...
logging.info('Jackdaws love my big sphinx of quartz.')

# Now, define a couple of other loggers which might represent areas in your
# application:

logger1 = logging.getLogger('myapp.area1')
logger2 = logging.getLogger('myapp.area2')

logger1.debug('Quick zephyrs blow, vexing daft Jim.')
logger1.info('How quickly daft jumping zebras vex.')
logger2.warning('Jail zesty vixen who grabbed pay from quack.')
logger2.error('The five boxing wizards jump quickly.')

수신 측에서는 socketserver 모듈을 사용하여 수신기를 구성할 수 있습니다. 기본적인 작업 예제는 다음과 같습니다:

import pickle
import logging
import logging.handlers
import socketserver
import struct

class LogRecordStreamHandler(socketserver.StreamRequestHandler):
    """Handler for a streaming logging request.

    This basically logs the record using whatever logging policy is
    configured locally.
    """

    def handle(self):
        """
        Handle multiple requests - each expected to be a 4-byte length,
        followed by the LogRecord in pickle format. Logs the record
        according to whatever policy is configured locally.
        """
        while True:
            chunk = self.connection.recv(4)
            if len(chunk) < 4:
                break
            slen = struct.unpack('>L', chunk)[0]
            chunk = self.connection.recv(slen)
            while len(chunk) < slen:
                chunk = chunk + self.connection.recv(slen - len(chunk))
            obj = self.unPickle(chunk)
            record = logging.makeLogRecord(obj)
            self.handleLogRecord(record)

    def unPickle(self, data):
        return pickle.loads(data)

    def handleLogRecord(self, record):
        # if a name is specified, we use the named logger rather than the one
        # implied by the record.
        if self.server.logname is not None:
            name = self.server.logname
        else:
            name = record.name
        logger = logging.getLogger(name)
        # N.B. EVERY record gets logged. This is because Logger.handle
        # is normally called AFTER logger-level filtering. If you want
        # to do filtering, do it at the client end to save wasting
        # cycles and network bandwidth!
        logger.handle(record)

class LogRecordSocketReceiver(socketserver.ThreadingTCPServer):
    """
    Simple TCP socket-based logging receiver suitable for testing.
    """

    allow_reuse_address = True

    def __init__(self, host='localhost',
                 port=logging.handlers.DEFAULT_TCP_LOGGING_PORT,
                 handler=LogRecordStreamHandler):
        socketserver.ThreadingTCPServer.__init__(self, (host, port), handler)
        self.abort = 0
        self.timeout = 1
        self.logname = None

    def serve_until_stopped(self):
        import select
        abort = 0
        while not abort:
            rd, wr, ex = select.select([self.socket.fileno()],
                                       [], [],
                                       self.timeout)
            if rd:
                self.handle_request()
            abort = self.abort

def main():
    logging.basicConfig(
        format='%(relativeCreated)5d %(name)-15s %(levelname)-8s %(message)s')
    tcpserver = LogRecordSocketReceiver()
    print('About to start TCP server...')
    tcpserver.serve_until_stopped()

if __name__ == '__main__':
    main()

먼저 서버를 실행한 다음 클라이언트를 실행합니다. 클라이언트 쪽에서는 콘솔에 아무것도 인쇄되지 않습니다. 서버 측에서 다음과 같은 내용이 보여야 합니다.:

About to start TCP server...
   59 root            INFO     Jackdaws love my big sphinx of quartz.
   59 myapp.area1     DEBUG    Quick zephyrs blow, vexing daft Jim.
   69 myapp.area1     INFO     How quickly daft jumping zebras vex.
   69 myapp.area2     WARNING  Jail zesty vixen who grabbed pay from quack.
   69 myapp.area2     ERROR    The five boxing wizards jump quickly.

일부 시나리오에서는 피클이 몇 가지 보안 문제를 수반함에 유의하십시오. 이 문제가 중요하면, makePickle() 메서드를 재정의하고 거기서 여러분의 대안을 구현해서 다른 직렬화를 사용하는 한편, 위의 스크립트가 그 직렬화를 사용하도록 수정하십시오.

로그 출력에 문맥 정보 추가

로깅 호출에 전달된 매개 변수 외에도 로깅 출력에 문맥 정보가 포함되기 원하는 경우가 있습니다. 예를 들어, 네트워크 응용 프로그램에서, (원격 클라이언트의 사용자 이름 또는 IP 주소와 같은) 클라이언트별 정보를 로그에 기록하는 것이 바람직 할 수 있습니다. 이를 달성하기 위해 extra 매개 변수를 사용할 수는 있지만, 이러한 방식으로 정보를 전달하는 것이 항상 편리하지는 않습니다. 연결마다 Logger 인스턴스를 만들고 싶을지 모르지만, 이러한 인스턴스는 가비지 수집되지 않기 때문에 좋지 않습니다. Logger 인스턴스의 수가 응용 프로그램 로깅에 사용하고자 하는 세분성 수준에 의존적일 때 이것이 실제로 문제가 되지는 않지만, Logger 인스턴스의 수가 실질적으로 무제한이 되면 관리하기 어려울 수 있습니다.

문맥 정보 전달에 LoggerAdapters 사용하기

로깅 이벤트 정보와 함께 출력되는 문맥 정보를 전달하는 쉬운 방법은 LoggerAdapter 클래스를 사용하는 것입니다. 이 클래스는 Logger처럼 보이도록 설계되어 있어서, debug(), info(), warning(), error(), exception(), critical() 및 log()를 호출할 수 있습니다. 이 메서드들은 Logger 에 있는 것과 똑같은 서명을 가지므로, 두 형의 인스턴스를 같은 의미로 사용할 수 있습니다.

LoggerAdapter 의 인스턴스를 생성할 때, Logger 인스턴스와 문맥 정보가 포함된 딕셔너리류 객체를 전달합니다. LoggerAdapter 의 인스턴스에서 로깅 메서드 중 하나를 호출하면, 생성자에 전달된 하위 Logger 인스턴스에 호출을 위임하고, 이 호출에 문맥 정보를 전달하도록 배치합니다. 다음은 LoggerAdapter 코드에서 발췌한 내용입니다:

def debug(self, msg, *args, **kwargs):
    """
    Delegate a debug call to the underlying logger, after adding
    contextual information from this adapter instance.
    """
    msg, kwargs = self.process(msg, kwargs)
    self.logger.debug(msg, *args, **kwargs)

LoggerAdapter 의 process() 메서드는 문맥 정보가 로그 출력에 추가되는 곳입니다. 로깅 호출의 메시지 및 키워드 인자를 받아서, 하부 로거에 대한 호출에서 사용될 (대체로) 수정된 버전을 돌려줍니다. 이 메서드의 기본 구현은 메시지는 그대로 두고, 키워드 인자에 생성자로 전달된 딕셔너리류 객체를 값으로 갖는 ‘extra’ 키를 삽입합니다. 물론, 어댑터에 대한 호출에서 ‘extra’ 키워드 인자를 전달한 경우 자동으로 덮어씁니다.

‘extra’를 사용하는 장점은, 딕셔너리류 객체에 들어있는 값이 LogRecord 인스턴스의 __dict__에 병합되어, 키에 대해 알고 있는 Formatter 인스턴스로 사용자 정의된 문자열을 사용할 수 있게 된다는 것입니다. 다른 방법이 필요한 경우, 가령 메시지 문자열의 앞이나 뒤에 문맥 정보를 덧붙이려는 경우, LoggerAdapter 의 서브 클래스를 만들고, 필요한 작업을 수행하기 위해 process() 를 재정의해야 합니다. 다음은 간단한 예제입니다:

class CustomAdapter(logging.LoggerAdapter):
    """
    This example adapter expects the passed in dict-like object to have a
    'connid' key, whose value in brackets is prepended to the log message.
    """
    def process(self, msg, kwargs):
        return '[%s] %s' % (self.extra['connid'], msg), kwargs

이런 식으로 사용할 수 있습니다:

logger = logging.getLogger(__name__)
adapter = CustomAdapter(logger, {'connid': some_conn_id})

그러면 어댑터에 로그 하는 모든 이벤트는 로그 메시지 앞에 some_conn_id 값이 붙습니다.

딕셔너리 이외의 객체를 사용하여 문맥 정보 전달하기

실제 딕셔너리를 LoggerAdapter 에 전달할 필요는 없습니다 - 로깅에 딕셔너리처럼 보일 수 있도록, __getitem__ 과 __iter__ 를 구현하는 클래스의 인스턴스를 전달할 수 있습니다. 값을 동적으로 생성하려는 경우 (반면에 딕셔너리에 들어있는 값은 바뀌지 않습니다) 유용합니다.

문맥 정보 전달에 필터 사용하기

사용자 정의 Filter를 사용하여 로그 출력에 문맥 정보를 추가할 수도 있습니다. Filter 인스턴스는 전달된 LogRecords 를 수정할 수 있는데, 어트리뷰트를 추가해서 적절한 포맷 문자열이나 필요하다면 사용자 정의 Formatter를 사용해서 출력되도록 할 수 있습니다.

예를 들어 웹 응용 프로그램에서, 처리 중인 요청(또는 적어도 그것의 흥미로운 부분)을 스레드 로컬 (threading.local) 변수에 저장한 다음, Filter 에서 액세스해서, 요청에서 온 정보를 - 원격 IP 주소와 원격 사용자의 사용자 이름이라고 합시다 - 위의 LoggerAdapter 예제에서와같이 어트리뷰트 이름 ‘ip’와 ‘user’를 사용하여 LogRecord 에 추가할 수 있습니다. 이 경우 같은 포맷 문자열을 사용하여 위에 표시된 것과 비슷한 출력을 얻을 수 있습니다. 다음은 스크립트 예입니다:

import logging
from random import choice

class ContextFilter(logging.Filter):
    """
    This is a filter which injects contextual information into the log.

    Rather than use actual contextual information, we just use random
    data in this demo.
    """

    USERS = ['jim', 'fred', 'sheila']
    IPS = ['123.231.231.123', '127.0.0.1', '192.168.0.1']

    def filter(self, record):

        record.ip = choice(ContextFilter.IPS)
        record.user = choice(ContextFilter.USERS)
        return True

if __name__ == '__main__':
    levels = (logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL)
    logging.basicConfig(level=logging.DEBUG,
                        format='%(asctime)-15s %(name)-5s %(levelname)-8s IP: %(ip)-15s User: %(user)-8s %(message)s')
    a1 = logging.getLogger('a.b.c')
    a2 = logging.getLogger('d.e.f')

    f = ContextFilter()
    a1.addFilter(f)
    a2.addFilter(f)
    a1.debug('A debug message')
    a1.info('An info message with %s', 'some parameters')
    for x in range(10):
        lvl = choice(levels)
        lvlname = logging.getLevelName(lvl)
        a2.log(lvl, 'A message at %s level with %d %s', lvlname, 2, 'parameters')

실행하면 다음과 같은 결과가 나옵니다:

2010-09-06 22:38:15,292 a.b.c DEBUG    IP: 123.231.231.123 User: fred     A debug message
2010-09-06 22:38:15,300 a.b.c INFO     IP: 192.168.0.1     User: sheila   An info message with some parameters
2010-09-06 22:38:15,300 d.e.f CRITICAL IP: 127.0.0.1       User: sheila   A message at CRITICAL level with 2 parameters
2010-09-06 22:38:15,300 d.e.f ERROR    IP: 127.0.0.1       User: jim      A message at ERROR level with 2 parameters
2010-09-06 22:38:15,300 d.e.f DEBUG    IP: 127.0.0.1       User: sheila   A message at DEBUG level with 2 parameters
2010-09-06 22:38:15,300 d.e.f ERROR    IP: 123.231.231.123 User: fred     A message at ERROR level with 2 parameters
2010-09-06 22:38:15,300 d.e.f CRITICAL IP: 192.168.0.1     User: jim      A message at CRITICAL level with 2 parameters
2010-09-06 22:38:15,300 d.e.f CRITICAL IP: 127.0.0.1       User: sheila   A message at CRITICAL level with 2 parameters
2010-09-06 22:38:15,300 d.e.f DEBUG    IP: 192.168.0.1     User: jim      A message at DEBUG level with 2 parameters
2010-09-06 22:38:15,301 d.e.f ERROR    IP: 127.0.0.1       User: sheila   A message at ERROR level with 2 parameters
2010-09-06 22:38:15,301 d.e.f DEBUG    IP: 123.231.231.123 User: fred     A message at DEBUG level with 2 parameters
2010-09-06 22:38:15,301 d.e.f INFO     IP: 123.231.231.123 User: fred     A message at INFO level with 2 parameters

여러 프로세스에서 단일 파일에 로깅 하기

logging 이 스레드-안전하고, 단일 프로세스의 여러 스레드에서 단일 파일로 로깅 하는 것이 지원되지만, 파이썬에서 여러 프로세스가 단일 파일에 액세스하는 것을 직렬화하는 표준적인 방법이 없으므로, 여러 프로세스에서 단일 파일로 로깅 하는 것은 지원되지 않습니다. 여러 프로세스에서 하나의 파일에 로그 해야 하는 경우, 이 작업을 수행하는 한 가지 방법은 모든 프로세스가 로그를 SocketHandler 에 기록하고, 소켓에서 읽어서 파일로 로그 하는 소켓 서버를 구현하는 별도의 프로세스를 사용하는 것입니다. (원한다면, 기존 프로세스 중 하나에서 한 스레드가 이 기능을 전담하도록 할 수 있습니다.) 이 섹션에서 이 접근법을 더 자세하게 설명하고, 여러분의 응용 프로그램에 적용하기 위한 출발점으로 사용할 수 있는 작동하는 소켓 수신기를 제공합니다.

multiprocessing 모듈을 포함하는 최신 버전의 파이썬을 사용하고 있다면, 이 모듈의 Lock 클래스를 사용하는 독자적인 처리기를 작성하여 여러 프로세스에서 파일에 액세스하는 것을 직렬화 할 수 있습니다. 기존 FileHandler 와 서브 클래스들은, 앞으로는 가능할 수 있지만, 현재 multiprocessing을 사용하지 않습니다. 현재 multiprocessing 모듈이 모든 플랫폼에서 작동하는 록 기능을 제공하지는 않는다는 것에 유의하십시오 (https://bugs.python.org/issue3770 를 참조하세요).

또는, Queue 와 QueueHandler 를 사용하여, 모든 로깅 이벤트를 다중 프로세스 응용 프로그램의 프로세스 중 하나에 보낼 수 있습니다. 다음 예제 스크립트는 이렇게 하는 방법을 보여줍니다; 예제에서 별도의 리스너 프로세스가 다른 프로세스가 보낸 이벤트를 수신하고 자체 로깅 구성에 따라 이벤트를 기록합니다. 이 예제가 한 가지 방법만을 보여 주지만 (예를 들어, 별도의 리스너 프로세스 대신 리스너 스레드를 사용할 수도 있습니다 – 구현은 비슷할 것입니다), 리스너와 응용 프로그램의 다른 프로세스가 완전히 다른 로깅 구성을 사용하도록 허용하고, 여러분 자신의 특별한 요구 사항을 충족하는 코드의 기초로 사용할 수 있습니다:

# You'll need these imports in your own code
import logging
import logging.handlers
import multiprocessing

# Next two import lines for this demo only
from random import choice, random
import time

#
# Because you'll want to define the logging configurations for listener and workers, the
# listener and worker process functions take a configurer parameter which is a callable
# for configuring logging for that process. These functions are also passed the queue,
# which they use for communication.
#
# In practice, you can configure the listener however you want, but note that in this
# simple example, the listener does not apply level or filter logic to received records.
# In practice, you would probably want to do this logic in the worker processes, to avoid
# sending events which would be filtered out between processes.
#
# The size of the rotated files is made small so you can see the results easily.
def listener_configurer():
    root = logging.getLogger()
    h = logging.handlers.RotatingFileHandler('mptest.log', 'a', 300, 10)
    f = logging.Formatter('%(asctime)s %(processName)-10s %(name)s %(levelname)-8s %(message)s')
    h.setFormatter(f)
    root.addHandler(h)

# This is the listener process top-level loop: wait for logging events
# (LogRecords)on the queue and handle them, quit when you get a None for a
# LogRecord.
def listener_process(queue, configurer):
    configurer()
    while True:
        try:
            record = queue.get()
            if record is None:  # We send this as a sentinel to tell the listener to quit.
                break
            logger = logging.getLogger(record.name)
            logger.handle(record)  # No level or filter logic applied - just do it!
        except Exception:
            import sys, traceback
            print('Whoops! Problem:', file=sys.stderr)
            traceback.print_exc(file=sys.stderr)

# Arrays used for random selections in this demo

LEVELS = [logging.DEBUG, logging.INFO, logging.WARNING,
          logging.ERROR, logging.CRITICAL]

LOGGERS = ['a.b.c', 'd.e.f']

MESSAGES = [
    'Random message #1',
    'Random message #2',
    'Random message #3',
]

# The worker configuration is done at the start of the worker process run.
# Note that on Windows you can't rely on fork semantics, so each process
# will run the logging configuration code when it starts.
def worker_configurer(queue):
    h = logging.handlers.QueueHandler(queue)  # Just the one handler needed
    root = logging.getLogger()
    root.addHandler(h)
    # send all messages, for demo; no other level or filter logic applied.
    root.setLevel(logging.DEBUG)

# This is the worker process top-level loop, which just logs ten events with
# random intervening delays before terminating.
# The print messages are just so you know it's doing something!
def worker_process(queue, configurer):
    configurer(queue)
    name = multiprocessing.current_process().name
    print('Worker started: %s' % name)
    for i in range(10):
        time.sleep(random())
        logger = logging.getLogger(choice(LOGGERS))
        level = choice(LEVELS)
        message = choice(MESSAGES)
        logger.log(level, message)
    print('Worker finished: %s' % name)

# Here's where the demo gets orchestrated. Create the queue, create and start
# the listener, create ten workers and start them, wait for them to finish,
# then send a None to the queue to tell the listener to finish.
def main():
    queue = multiprocessing.Queue(-1)
    listener = multiprocessing.Process(target=listener_process,
                                       args=(queue, listener_configurer))
    listener.start()
    workers = []
    for i in range(10):
        worker = multiprocessing.Process(target=worker_process,
                                         args=(queue, worker_configurer))
        workers.append(worker)
        worker.start()
    for w in workers:
        w.join()
    queue.put_nowait(None)
    listener.join()

if __name__ == '__main__':
    main()

위의 스크립트 변형은 로깅을 메인 프로세스의 별도의 스레드에서 유지합니다:

import logging
import logging.config
import logging.handlers
from multiprocessing import Process, Queue
import random
import threading
import time

def logger_thread(q):
    while True:
        record = q.get()
        if record is None:
            break
        logger = logging.getLogger(record.name)
        logger.handle(record)

def worker_process(q):
    qh = logging.handlers.QueueHandler(q)
    root = logging.getLogger()
    root.setLevel(logging.DEBUG)
    root.addHandler(qh)
    levels = [logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR,
              logging.CRITICAL]
    loggers = ['foo', 'foo.bar', 'foo.bar.baz',
               'spam', 'spam.ham', 'spam.ham.eggs']
    for i in range(100):
        lvl = random.choice(levels)
        logger = logging.getLogger(random.choice(loggers))
        logger.log(lvl, 'Message no. %d', i)

if __name__ == '__main__':
    q = Queue()
    d = {
        'version': 1,
        'formatters': {
            'detailed': {
                'class': 'logging.Formatter',
                'format': '%(asctime)s %(name)-15s %(levelname)-8s %(processName)-10s %(message)s'
            }
        },
        'handlers': {
            'console': {
                'class': 'logging.StreamHandler',
                'level': 'INFO',
            },
            'file': {
                'class': 'logging.FileHandler',
                'filename': 'mplog.log',
                'mode': 'w',
                'formatter': 'detailed',
            },
            'foofile': {
                'class': 'logging.FileHandler',
                'filename': 'mplog-foo.log',
                'mode': 'w',
                'formatter': 'detailed',
            },
            'errors': {
                'class': 'logging.FileHandler',
                'filename': 'mplog-errors.log',
                'mode': 'w',
                'level': 'ERROR',
                'formatter': 'detailed',
            },
        },
        'loggers': {
            'foo': {
                'handlers': ['foofile']
            }
        },
        'root': {
            'level': 'DEBUG',
            'handlers': ['console', 'file', 'errors']
        },
    }
    workers = []
    for i in range(5):
        wp = Process(target=worker_process, name='worker %d' % (i + 1), args=(q,))
        workers.append(wp)
        wp.start()
    logging.config.dictConfig(d)
    lp = threading.Thread(target=logger_thread, args=(q,))
    lp.start()
    # At this point, the main process could do some useful work of its own
    # Once it's done that, it can wait for the workers to terminate...
    for wp in workers:
        wp.join()
    # And now tell the logging thread to finish up, too
    q.put(None)
    lp.join()

이 변형은 특정 로거에 대한 구성을 적용하는 방법을 보여줍니다 - 예를 들어, foo 로거는 foo 서브 시스템의 모든 이벤트를 mplog-foo.log 파일에 저장하는 특별한 처리기를 갖고 있습니다. 이것은 메인 프로세스의 로깅 시스템이 ( 로깅 이벤트가 작업자 프로세스에서 만들어졌다 하더라도) 메시지를 적절한 대상으로 전달하는 데 사용됩니다.

Using concurrent.futures.ProcessPoolExecutor

If you want to use concurrent.futures.ProcessPoolExecutor to start your worker processes, you need to create the queue slightly differently. Instead of

queue = multiprocessing.Queue(-1)

you should use

queue = multiprocessing.Manager().Queue(-1)  # also works with the examples above

and you can then replace the worker creation from this:

workers = []
for i in range(10):
    worker = multiprocessing.Process(target=worker_process,
                                     args=(queue, worker_configurer))
    workers.append(worker)
    worker.start()
for w in workers:
    w.join()

to this (remembering to first import concurrent.futures):

with concurrent.futures.ProcessPoolExecutor(max_workers=10) as executor:
    for i in range(10):
        executor.submit(worker_process, queue, worker_configurer)

파일 회전 사용하기

때로는 로그 파일이 특정 크기까지 커지도록 한 다음, 새 파일을 열고 그곳에 로그에 기록하려고 할 수 있습니다. 이 파일들을 특정 수만 유지하고, 그 수 만큼의 파일이 만들어지면, 파일을 회전시켜 파일의 개수와 크기 모두 제한되도록 하고 싶을 수 있습니다. 이 사용 패턴을 위해, logging 패키지는 RotatingFileHandler 를 제공합니다:

import glob
import logging
import logging.handlers

LOG_FILENAME = 'logging_rotatingfile_example.out'

# Set up a specific logger with our desired output level
my_logger = logging.getLogger('MyLogger')
my_logger.setLevel(logging.DEBUG)

# Add the log message handler to the logger
handler = logging.handlers.RotatingFileHandler(
              LOG_FILENAME, maxBytes=20, backupCount=5)

my_logger.addHandler(handler)

# Log some messages
for i in range(20):
    my_logger.debug('i = %d' % i)

# See what files are created
logfiles = glob.glob('%s*' % LOG_FILENAME)

for filename in logfiles:
    print(filename)

결과는 6개의 파일이어야 하고, 각기 응용 프로그램에 대한 로그 기록의 일부입니다:

logging_rotatingfile_example.out
logging_rotatingfile_example.out.1
logging_rotatingfile_example.out.2
logging_rotatingfile_example.out.3
logging_rotatingfile_example.out.4
logging_rotatingfile_example.out.5

가장 최근의 파일은 항상 logging_rotatingfile_example.out 이며, 크기 제한에 도달할 때마다 접미사 .1 이 붙은 이름으로 변경됩니다. 기존 백업 파일 각각의 이름이 변경되어 접미사가 증가하고 ( .1 이 .2 가 되는 등) .6 파일이 지워집니다.

분명, 이 예제는 로그 길이를 극단적으로 작게 설정합니다. maxBytes 를 적절한 값으로 설정하고 싶을 겁니다.

대체 포매팅 스타일 사용하기

logging이 파이썬 표준 라이브러리에 추가되었을 때, 가변 내용으로 메시지를 포맷하는 유일한 방법은 %-포매팅 방법을 사용하는 것이었습니다. 그 이후로, 파이썬은 두 개의 새로운 포매팅 접근법을 얻었습니다: string.Template(파이썬 2.4에 추가됨)과 str.format()(파이썬 2.6에 추가됨).

로깅은 (3.2부터) 이 두 가지 추가 포매팅 스타일에 대해 개선된 지원을 제공합니다. Formatter 클래스는 style 이라는 추가적인 키워드 매개 변수를 취하도록 개선되었습니다. 기본값은 '%' 이지만, 다른 두 가지 포매팅 스타일에 해당하는 '{' 및 '$' 를 사용할 수 있습니다. (여러분이 기대하듯이) 이전 버전과의 호환성은 기본적으로 유지되지만, style 매개변수를 명시적으로 지정하면 str.format() 또는 string.Template 과 함께 작동하는 포맷 문자열을 지정할 수 있습니다. 다음은 가능성을 보여주기 위한 예제 콘솔 세션입니다:

>>> import logging
>>> root = logging.getLogger()
>>> root.setLevel(logging.DEBUG)
>>> handler = logging.StreamHandler()
>>> bf = logging.Formatter('{asctime} {name} {levelname:8s} {message}',
...                        style='{')
>>> handler.setFormatter(bf)
>>> root.addHandler(handler)
>>> logger = logging.getLogger('foo.bar')
>>> logger.debug('This is a DEBUG message')
2010-10-28 15:11:55,341 foo.bar DEBUG    This is a DEBUG message
>>> logger.critical('This is a CRITICAL message')
2010-10-28 15:12:11,526 foo.bar CRITICAL This is a CRITICAL message
>>> df = logging.Formatter('$asctime $name ${levelname} $message',
...                        style='$')
>>> handler.setFormatter(df)
>>> logger.debug('This is a DEBUG message')
2010-10-28 15:13:06,924 foo.bar DEBUG This is a DEBUG message
>>> logger.critical('This is a CRITICAL message')
2010-10-28 15:13:11,494 foo.bar CRITICAL This is a CRITICAL message
>>>

로그로 최종 출력하기 위해 로깅 메시지를 포매팅하는 것은 개별 로깅 메시지가 구성되는 방식과 완전히 별개입니다. 개별 메시지에는 다음과 같이 %-포매팅을 사용할 수 있습니다:

>>> logger.error('This is an%s %s %s', 'other,', 'ERROR,', 'message')
2010-10-28 15:19:29,833 foo.bar ERROR This is another, ERROR, message
>>>

로깅 호출(logger.debug(), logger.info() 등)은 실제 로깅 메시지 자체를 위해서는 위치 매개 변수만을 취하고, 키워드 매개 변수는 실제 로깅 호출을 어떻게 다뤄야 하는지를 지정하는 옵션을 결정하는 용도로만 사용됩니다 (예를 들어, 트레이스백 정보를 로그 해야 할지를 가리키는 exc_info 키워드 매개 변수나 로그에 추가되는 문맥 정보를 나타내는 extra 키워드 매개 변수). 그래서 여러분은 str.format() 또는 string.Template 문법을 사용하여 직접 로깅 호출을 할 수 없습니다, 내부적으로 logging 패키지가 %-포매팅을 사용하여 포맷 문자열과 변수 인자를 병합하기 때문입니다. 이전 버전과의 호환성을 유지하는 동안은 이 상황이 바뀌지 않을 것입니다. 기존 코드에 있는 모든 로깅 호출이 %-포맷 문자열을 사용하기 때문입니다.

그러나 {}- 및 $- 포매팅을 사용하여 개별 로그 메시지를 구성하는 방법이 있습니다. 메시지의 경우, 메시지 포맷 문자열로 임의의 객체를 사용할 수 있으며, logging 패키지는 실제 형식 문자열을 얻기 위해 그 객체에 대해 str() 을 호출한다는 것을 상기하십시오. 다음 두 가지 클래스를 고려하십시오:

class BraceMessage:
    def __init__(self, fmt, *args, **kwargs):
        self.fmt = fmt
        self.args = args
        self.kwargs = kwargs

    def __str__(self):
        return self.fmt.format(*self.args, **self.kwargs)

class DollarMessage:
    def __init__(self, fmt, **kwargs):
        self.fmt = fmt
        self.kwargs = kwargs

    def __str__(self):
        from string import Template
        return Template(self.fmt).substitute(**self.kwargs)

이 중 하나를 포맷 문자열 대신 사용하면, {}- 또는 $-포매팅을 사용하여 포맷된 로그 출력의 “%(message)s”, “{message}” 또는 “$message” 자리에 나타나는 실제 “message” 부분을 만들 수 있습니다. 어떤 것을 로그 하고 싶을 때마다 클래스 이름을 사용하는 것은 다소 꼴사납지만, __(두 개의 밑줄 —- gettext.gettext() 나 그 형제들의 동의어/별칭으로 사용되는 _ 과 혼동하지 마세요)와 같은 별칭을 사용하면 꽤 쓸만합니다.

위의 클래스가 파이썬에 포함되어 있지는 않지만, 아주 쉽게 여러분의 코드에 복사하여 붙여넣을 수 있습니다. 다음과 같이 사용될 수 있습니다 (wherever 라는 모듈에서 선언되었다고 가정합니다):

>>> from wherever import BraceMessage as __
>>> print(__('Message with {0} {name}', 2, name='placeholders'))
Message with 2 placeholders
>>> class Point: pass
...
>>> p = Point()
>>> p.x = 0.5
>>> p.y = 0.5
>>> print(__('Message with coordinates: ({point.x:.2f}, {point.y:.2f})',
...       point=p))
Message with coordinates: (0.50, 0.50)
>>> from wherever import DollarMessage as __
>>> print(__('Message with $num $what', num=2, what='placeholders'))
Message with 2 placeholders
>>>

위의 예제는 print() 를 사용하여 포매팅이 어떻게 작동하는지 보여주고 있지만, 물론 이 접근법으로 실제 로깅 할 때는 logger.debug() 나 그와 유사한 것을 사용해야 합니다.

한 가지 지적할 점은, 이 접근법이 성능상으로 큰 문제가 없다는 것입니다: 실제 포매팅은 로깅 호출을 할 때가 아니라 로깅 된 메시지를 실제로 처리기가 로그로 출력할 때 (그리고 실제로 그렇게 될 때만) 발생합니다. 그래서 여러분이 실수할 수도 있을 특이함은 괄호가 포맷 문자열과 인자들을 모두 감싼다는 것뿐입니다. __ 표기법이 단지 XXXMessage 클래스 중 하나에 대한 생성자 호출의 편의 문법이기 때문입니다.

원한다면, LoggerAdapter 를 사용하여 다음 예제와 같이 위와 유사한 효과를 얻을 수 있습니다:

import logging

class Message(object):
    def __init__(self, fmt, args):
        self.fmt = fmt
        self.args = args

    def __str__(self):
        return self.fmt.format(*self.args)

class StyleAdapter(logging.LoggerAdapter):
    def __init__(self, logger, extra=None):
        super(StyleAdapter, self).__init__(logger, extra or {})

    def log(self, level, msg, *args, **kwargs):
        if self.isEnabledFor(level):
            msg, kwargs = self.process(msg, kwargs)
            self.logger._log(level, Message(msg, args), (), **kwargs)

logger = StyleAdapter(logging.getLogger(__name__))

def main():
    logger.debug('Hello, {}', 'world!')

if __name__ == '__main__':
    logging.basicConfig(level=logging.DEBUG)
    main()

이 스크립트는 파이썬 3.2 이상에서 실행될 때 Hello, world! 라는 메시지를 기록해야 합니다.

사용자 정의 LogRecord

모든 로깅 이벤트는 LogRecord 인스턴스로 표현됩니다. 이벤트가 로그 되고 로거 수준에 의해 필터링 되지 않으면, LogRecord 가 생성되고 이벤트에 대한 정보로 채워진 다음 해당 로거(와 그 조상들, 계층 상위로의 전파가 비활성화된 지점의 로거까지)의 처리기로 전달됩니다. 파이썬 3.2 이전에는, 이 생성이 일어나는 곳이 두 곳밖에 없었습니다:

Logger.makeRecord(), 이벤트 로깅의 일반적인 프로세스에서 호출됩니다. 인스턴스를 생성하기 위해 LogRecord 를 직접 호출합니다.

makeLogRecord(), LogRecord에 추가될 어트리뷰트를 포함하는 딕셔너리와 함께 호출됩니다. 보통 적절한 딕셔너리가 네트워크를 통해 (예를 들어, SocketHandler 를 통해 피클 형태로, 또는 HTTPHandler 를 통해 JSON 형식으로) 수신될 때 호출됩니다.

이것은 보통 LogRecord 로 특별한 것을 할 필요가 있다면, 다음 중 하나를 해야 한다는 것을 의미합니다.

Logger.makeRecord() 를 재정의하는 자신만의 Logger 서브 클래스를 만들고, 관심 있는 로거의 인스턴스가 만들어지기 전에 setLoggerClass() 를 사용하여 설정하십시오.

로거나 처리기에 Filter를 추가해서 filter() 메서드가 호출될 때 필요한 특별한 조작을 하십시오.

첫 번째 접근법은 여러 라이브러리가 서로 다른 일을 하고 싶어 하는 시나리오에서는 다루기 힘들 것입니다. 각자 자신의 Logger 서브 클래스를 설정하려고 시도할 것이고, 마지막 것이 이기게 될 것입니다.

두 번째 접근법은 많은 경우에 합리적으로 잘 작동하지만, LogRecord 의 특별한 서브 클래스를 사용할 수는 없습니다. 라이브러리 개발자는 로거에 적절한 필터를 설정할 수 있지만, 새로운 로거를 도입할 때마다 이를 수행해야 한다는 것을 기억해야 합니다. 이를 고려하지 않는다면 새 패키지나 모듈을 추가하고 모듈 수준에서 단순히 다음과 같이 합니다:

logger = logging.getLogger(__name__)

이것은 아마도 고려해야 할 많은 것 중 하나일 뿐입니다. 개발자는 자신의 최상위 로거에 첨부된 NullHandler 에도 필터를 추가 할 수 있지만, 응용 프로그램 개발자가 하위 수준 라이브러리 로거에 처리기를 연결하면 호출되지 않습니다 — 그래서 그 처리기로부터의 출력은 라이브러리 개발자의 의도를 반영하지 못합니다.

파이썬 3.2 이상에서는, LogRecord 생성이 사용자가 지정할 수 있는 팩토리를 통해 수행됩니다. 팩토리는 setLogRecordFactory() 로 설정할 수 있고, getLogRecordFactory() 로 조회할 수 있는 콜러블입니다. 팩토리는 LogRecord 생성자와 같은 서명으로 호출되고, 기본 설정은 LogRecord 입니다.

이 방법을 사용하면 사용자 정의 팩토리가 LogRecord 생성의 모든 측면을 제어 할 수 있습니다. 예를 들어, 서브 클래스를 반환하거나, 다음과 같은 방법으로 생성된 레코드에 어트리뷰트를 추가 할 수 있습니다:

old_factory = logging.getLogRecordFactory()

def record_factory(*args, **kwargs):
    record = old_factory(*args, **kwargs)
    record.custom_attribute = 0xdecafbad
    return record

logging.setLogRecordFactory(record_factory)

이 패턴은 서로 다른 라이브러리가 팩토리를 체인으로 연결할 수 있도록 하며, 서로의 어트리뷰트를 덮어쓰거나 의도하지 않게 표준으로 제공된 어트리뷰트를 덮어쓰지 않는 한, 놀랄 일은 없어야 합니다. 그러나 체인의 각 고리는 모든 로깅 작업에 실행시간 오버헤드를 추가하므로, Filter를 사용해서 원하는 결과를 얻을 수 없을 때만 이 기법을 사용해야 합니다.

QueueHandler 서브 클래스 만들기 - ZeroMQ 예제

QueueHandler 서브 클래스를 사용하여 다른 유형의 큐에 메시지를 보낼 수 있습니다, 예를 들어 ZeroMQ ‘publish’ 소켓. 아래 예제에서, 소켓은 별도로 생성되어 처리기로 (‘queue’로) 전달됩니다:

import zmq   # using pyzmq, the Python binding for ZeroMQ
import json  # for serializing records portably

ctx = zmq.Context()
sock = zmq.Socket(ctx, zmq.PUB)  # or zmq.PUSH, or other suitable value
sock.bind('tcp://*:5556')        # or wherever

class ZeroMQSocketHandler(QueueHandler):
    def enqueue(self, record):
        self.queue.send_json(record.__dict__)

handler = ZeroMQSocketHandler(sock)

물론 구성하는 다른 방법이 있습니다. 예를 들어 처리기가 소켓을 만드는데 필요한 데이터를 전달하는 것입니다:

class ZeroMQSocketHandler(QueueHandler):
    def __init__(self, uri, socktype=zmq.PUB, ctx=None):
        self.ctx = ctx or zmq.Context()
        socket = zmq.Socket(self.ctx, socktype)
        socket.bind(uri)
        super().__init__(socket)

    def enqueue(self, record):
        self.queue.send_json(record.__dict__)

    def close(self):
        self.queue.close()

QueueListener 서브 클래스 만들기 - ZeroMQ 예제

다른 유형의 큐에서 메시지를 받기 위해 QueueListener 의 서브 클래스를 만들 수도 있습니다, 예를 들어 ZeroMQ ‘subscribe’ 소켓. 다음은 그 예입니다:

class ZeroMQSocketListener(QueueListener):
    def __init__(self, uri, *handlers, **kwargs):
        self.ctx = kwargs.get('ctx') or zmq.Context()
        socket = zmq.Socket(self.ctx, zmq.SUB)
        socket.setsockopt_string(zmq.SUBSCRIBE, '')  # subscribe to everything
        socket.connect(uri)
        super().__init__(socket, *handlers, **kwargs)

    def dequeue(self):
        msg = self.queue.recv_json()
        return logging.makeLogRecord(msg)

더 보기

모듈 logging

logging 모듈에 대한 API 레퍼런스

모듈 logging.config

logging 모듈용 구성 API.

모듈 logging.handlers

logging 모듈에 포함된 유용한 처리기.

기초 로깅 자습서

고급 로깅 자습서

딕셔너리 기반 구성의 예

다음은 로깅 구성 딕셔너리의 예입니다 - 장고 프로젝트 설명서 [https://docs.djangoproject.com/en/1.9/topics/logging/#configuring-logging] 에서 가져왔습니다. 이 딕셔너리를 dictConfig() 로 전달하여 구성을 적용합니다:

LOGGING = {
    'version': 1,
    'disable_existing_loggers': True,
    'formatters': {
        'verbose': {
            'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'
        },
        'simple': {
            'format': '%(levelname)s %(message)s'
        },
    },
    'filters': {
        'special': {
            '()': 'project.logging.SpecialFilter',
            'foo': 'bar',
        }
    },
    'handlers': {
        'null': {
            'level':'DEBUG',
            'class':'django.utils.log.NullHandler',
        },
        'console':{
            'level':'DEBUG',
            'class':'logging.StreamHandler',
            'formatter': 'simple'
        },
        'mail_admins': {
            'level': 'ERROR',
            'class': 'django.utils.log.AdminEmailHandler',
            'filters': ['special']
        }
    },
    'loggers': {
        'django': {
            'handlers':['null'],
            'propagate': True,
            'level':'INFO',
        },
        'django.request': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': False,
        },
        'myproject.custom': {
            'handlers': ['console', 'mail_admins'],
            'level': 'INFO',
            'filters': ['special']
        }
    }
}

이 구성에 대한 더 자세한 정보는 장고 설명서의 관련 섹션 [https://docs.djangoproject.com/en/1.9/topics/logging/#configuring-logging] 을 참조하세요.

rotator와 namer를 사용해서 로그 회전 처리하기

다음 코드 조각에 namer 와 rotator를 정의하는 예가 있는데, 로그 파일을 zlib 기반으로 압축합니다:

def namer(name):
    return name + ".gz"

def rotator(source, dest):
    with open(source, "rb") as sf:
        data = sf.read()
        compressed = zlib.compress(data, 9)
        with open(dest, "wb") as df:
            df.write(compressed)
    os.remove(source)

rh = logging.handlers.RotatingFileHandler(...)
rh.rotator = rotator
rh.namer = namer

이것은 “진짜” .gz 파일이 아닙니다. 단순히 압축된 데이터일 뿐이고, 실제 gzip 파일에서 찾을 수 있는 “컨테이너” 가 없습니다. 이 코드 조각은 단지 설명을 위한 것일 뿐입니다.

좀 더 정교한 multiprocessing 예제

다음 동작하는 예제에서는 구성 파일을 사용하여 로깅을 multiprocessing과 함께 사용하는 방법을 보여줍니다. 구성은 매우 간단하지만, 실제 multiprocessing 시나리오에서 더 복잡한 구성을 구현할 수 있음을 예시합니다.

이 예에서, 주 프로세스는 리스너 프로세스와 몇 개의 작업자 프로세스를 생성합니다. 주 프로세스, 리스너 및 작업자를 위한 세 가지 구성이 있습니다 (모든 작업자는 같은 구성을 공유합니다). 주 프로세스에서의 로깅, 작업자가 QueueHandler에 로그 하는 방법, 그리고 리스너가 QueueListener 및 더욱 복잡한 로깅 구성을 구현하고 큐를 통해 수신한 이벤트를 구성에서 지정된 처리기로 전달하도록 배치하는 는 방법을 볼 수 있습니다. 이러한 구성은 설명을 위한 것이지만, 이 예제를 여러분 자신의 시나리오에 적용할 수 있어야 합니다.

스크립트는 다음과 같습니다 - 독스트링과 주석이 어떻게 작동하는지 잘 설명하기를 바랍니다:

import logging
import logging.config
import logging.handlers
from multiprocessing import Process, Queue, Event, current_process
import os
import random
import time

class MyHandler:
    """
    A simple handler for logging events. It runs in the listener process and
    dispatches events to loggers based on the name in the received record,
    which then get dispatched, by the logging system, to the handlers
    configured for those loggers.
    """
    def handle(self, record):
        logger = logging.getLogger(record.name)
        # The process name is transformed just to show that it's the listener
        # doing the logging to files and console
        record.processName = '%s (for %s)' % (current_process().name, record.processName)
        logger.handle(record)

def listener_process(q, stop_event, config):
    """
    This could be done in the main process, but is just done in a separate
    process for illustrative purposes.

    This initialises logging according to the specified configuration,
    starts the listener and waits for the main process to signal completion
    via the event. The listener is then stopped, and the process exits.
    """
    logging.config.dictConfig(config)
    listener = logging.handlers.QueueListener(q, MyHandler())
    listener.start()
    if os.name == 'posix':
        # On POSIX, the setup logger will have been configured in the
        # parent process, but should have been disabled following the
        # dictConfig call.
        # On Windows, since fork isn't used, the setup logger won't
        # exist in the child, so it would be created and the message
        # would appear - hence the "if posix" clause.
        logger = logging.getLogger('setup')
        logger.critical('Should not appear, because of disabled logger ...')
    stop_event.wait()
    listener.stop()

def worker_process(config):
    """
    A number of these are spawned for the purpose of illustration. In
    practice, they could be a heterogeneous bunch of processes rather than
    ones which are identical to each other.

    This initialises logging according to the specified configuration,
    and logs a hundred messages with random levels to randomly selected
    loggers.

    A small sleep is added to allow other processes a chance to run. This
    is not strictly needed, but it mixes the output from the different
    processes a bit more than if it's left out.
    """
    logging.config.dictConfig(config)
    levels = [logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR,
              logging.CRITICAL]
    loggers = ['foo', 'foo.bar', 'foo.bar.baz',
               'spam', 'spam.ham', 'spam.ham.eggs']
    if os.name == 'posix':
        # On POSIX, the setup logger will have been configured in the
        # parent process, but should have been disabled following the
        # dictConfig call.
        # On Windows, since fork isn't used, the setup logger won't
        # exist in the child, so it would be created and the message
        # would appear - hence the "if posix" clause.
        logger = logging.getLogger('setup')
        logger.critical('Should not appear, because of disabled logger ...')
    for i in range(100):
        lvl = random.choice(levels)
        logger = logging.getLogger(random.choice(loggers))
        logger.log(lvl, 'Message no. %d', i)
        time.sleep(0.01)

def main():
    q = Queue()
    # The main process gets a simple configuration which prints to the console.
    config_initial = {
        'version': 1,
        'formatters': {
            'detailed': {
                'class': 'logging.Formatter',
                'format': '%(asctime)s %(name)-15s %(levelname)-8s %(processName)-10s %(message)s'
            }
        },
        'handlers': {
            'console': {
                'class': 'logging.StreamHandler',
                'level': 'INFO',
            },
        },
        'root': {
            'level': 'DEBUG',
            'handlers': ['console']
        },
    }
    # The worker process configuration is just a QueueHandler attached to the
    # root logger, which allows all messages to be sent to the queue.
    # We disable existing loggers to disable the "setup" logger used in the
    # parent process. This is needed on POSIX because the logger will
    # be there in the child following a fork().
    config_worker = {
        'version': 1,
        'disable_existing_loggers': True,
        'handlers': {
            'queue': {
                'class': 'logging.handlers.QueueHandler',
                'queue': q,
            },
        },
        'root': {
            'level': 'DEBUG',
            'handlers': ['queue']
        },
    }
    # The listener process configuration shows that the full flexibility of
    # logging configuration is available to dispatch events to handlers however
    # you want.
    # We disable existing loggers to disable the "setup" logger used in the
    # parent process. This is needed on POSIX because the logger will
    # be there in the child following a fork().
    config_listener = {
        'version': 1,
        'disable_existing_loggers': True,
        'formatters': {
            'detailed': {
                'class': 'logging.Formatter',
                'format': '%(asctime)s %(name)-15s %(levelname)-8s %(processName)-10s %(message)s'
            },
            'simple': {
                'class': 'logging.Formatter',
                'format': '%(name)-15s %(levelname)-8s %(processName)-10s %(message)s'
            }
        },
        'handlers': {
            'console': {
                'class': 'logging.StreamHandler',
                'level': 'INFO',
                'formatter': 'simple',
            },
            'file': {
                'class': 'logging.FileHandler',
                'filename': 'mplog.log',
                'mode': 'w',
                'formatter': 'detailed',
            },
            'foofile': {
                'class': 'logging.FileHandler',
                'filename': 'mplog-foo.log',
                'mode': 'w',
                'formatter': 'detailed',
            },
            'errors': {
                'class': 'logging.FileHandler',
                'filename': 'mplog-errors.log',
                'mode': 'w',
                'level': 'ERROR',
                'formatter': 'detailed',
            },
        },
        'loggers': {
            'foo': {
                'handlers': ['foofile']
            }
        },
        'root': {
            'level': 'DEBUG',
            'handlers': ['console', 'file', 'errors']
        },
    }
    # Log some initial events, just to show that logging in the parent works
    # normally.
    logging.config.dictConfig(config_initial)
    logger = logging.getLogger('setup')
    logger.info('About to create workers ...')
    workers = []
    for i in range(5):
        wp = Process(target=worker_process, name='worker %d' % (i + 1),
                     args=(config_worker,))
        workers.append(wp)
        wp.start()
        logger.info('Started worker: %s', wp.name)
    logger.info('About to create listener ...')
    stop_event = Event()
    lp = Process(target=listener_process, name='listener',
                 args=(q, stop_event, config_listener))
    lp.start()
    logger.info('Started listener')
    # We now hang around for the workers to finish their work.
    for wp in workers:
        wp.join()
    # Workers all done, listening can now stop.
    # Logging in the parent still works normally.
    logger.info('Telling listener to stop ...')
    stop_event.set()
    lp.join()
    logger.info('All done.')

if __name__ == '__main__':
    main()

SysLogHandler로 전송된 메시지에 BOM 삽입하기

RFC 5424 [https://tools.ietf.org/html/rfc5424.html] 는 유니코드 메시지가 다음 구조를 갖는 바이트들로 syslog 데몬에 전송되어야 함을 요구합니다: 선택적인 순수 ASCII 구성 요소, 그 뒤를 이어 UTF-8 바이트 순서 표식 (BOM), 그 뒤를 이어 UTF-8으로 인코딩된 유니코드. (이 규격의 관련 절 [https://tools.ietf.org/html/rfc5424.html#section-6] 을 참조하십시오.)

파이썬 3.1에서, BOM을 메시지에 삽입하는 코드가 SysLogHandler 에 추가되었지만, 유감스럽게도, BOM이 메시지의 시작 부분에 나타나서 그 앞에 순수 ASCII 구성 요소를 허락하지 않도록 잘못 구현되었습니다.

이 동작이 잘못됨에 따라, 잘못된 BOM 삽입 코드가 파이썬 3.2.4 이상에서 제거되었습니다. 그러나, 올바른 코드로 대체되지는 않았고, BOM을 포함하고, 그 앞에 순수 ASCII 시퀀스, 그 뒤에 UTF-8으로 인코딩된 임의의 유니코드로 구성된 RFC 5424 [https://tools.ietf.org/html/rfc5424.html]-호환 메시지를 생성하려는 경우 다음과 같이 해야 합니다:

Formatter 인스턴스를 SysLogHandler 인스턴스에 다음과 같은 포맷 문자열과 함께 첨부하십시오:

'ASCII section\ufeffUnicode section'

유니코드 코드 포인트 U+FEFF는, UTF-8을 사용하여 인코딩될 때, UTF-8 BOM으로 인코딩됩니다 – 바이트열 b'\xef\xbb\xbf'.

ASCII section을 원하는 자리 표시기로 바꾸십시오. 그러나 치환 후 나타나는 데이터가 항상 ASCII임미 보장되어야 합니다 (그렇게 되면, UTF-8 인코딩 이후에는 변경되지 않은 채로 유지됩니다).

Unidcode section을 원하는 자리 표시기로 바꾸십시오; 치환 후 나타나는 데이터에 ASCII 범위를 벗어나는 문자가 포함되어 있어도 괜찮습니다 – UTF-8을 사용하여 인코딩됩니다.

포맷된 된 메시지는 SysLogHandler 에 의해 UTF-8 인코딩을 사용하여 인코딩*됩니다*. 위의 규칙을 따르는 경우, RFC 5424 [https://tools.ietf.org/html/rfc5424.html]-호환 메시지를 생성할 수 있어야 합니다. 그렇지 않으면, logging이 불평하지 않을 수도 있지만, 메시지가 RFC 5424와 호환되지 않고 syslog 데몬이 불평 할 수 있습니다.

구조적 로깅 구현

대부분의 로깅 메시지는 사람이 읽을 수 있도록 만들어졌기 때문에 쉽게 기계에서 파싱 할 수 없지만, 프로그램에서 (복잡한 정규식을 사용하지 않고도) 구문 분석할 수 있는 구조화된 포맷으로 메시지를 출력하려는 상황이 있을 수 있습니다. 이것은 logging 패키지를 사용하여 쉽게 달성 할 수 있습니다. 이것이 달성될 수 있는 여러 가지 방법이 있지만, 다음은 JSON을 사용하여 기계가 파싱할 수 있는 방식으로 이벤트를 직렬화하는 간단한 접근법입니다:

import json
import logging

class StructuredMessage(object):
    def __init__(self, message, **kwargs):
        self.message = message
        self.kwargs = kwargs

    def __str__(self):
        return '%s >>> %s' % (self.message, json.dumps(self.kwargs))

_ = StructuredMessage   # optional, to improve readability

logging.basicConfig(level=logging.INFO, format='%(message)s')
logging.info(_('message 1', foo='bar', bar='baz', num=123, fnum=123.456))

위의 스크립트가 실행되면 다음과 같이 인쇄됩니다:

message 1 >>> {"fnum": 123.456, "num": 123, "bar": "baz", "foo": "bar"}

항목의 순서는 사용된 파이썬 버전에 따라 다를 수 있습니다.

좀 더 특별한 처리가 필요한 경우, 다음 예제와 같이 사용자 정의 JSON 인코더를 사용할 수 있습니다:

from __future__ import unicode_literals

import json
import logging

# This next bit is to ensure the script runs unchanged on 2.x and 3.x
try:
    unicode
except NameError:
    unicode = str

class Encoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, set):
            return tuple(o)
        elif isinstance(o, unicode):
            return o.encode('unicode_escape').decode('ascii')
        return super(Encoder, self).default(o)

class StructuredMessage(object):
    def __init__(self, message, **kwargs):
        self.message = message
        self.kwargs = kwargs

    def __str__(self):
        s = Encoder().encode(self.kwargs)
        return '%s >>> %s' % (self.message, s)

_ = StructuredMessage   # optional, to improve readability

def main():
    logging.basicConfig(level=logging.INFO, format='%(message)s')
    logging.info(_('message 1', set_value={1, 2, 3}, snowman='\u2603'))

if __name__ == '__main__':
    main()

위의 스크립트를 실행하면 다음과 같이 인쇄합니다:

message 1 >>> {"snowman": "\u2603", "set_value": [1, 2, 3]}

항목의 순서는 사용된 파이썬 버전에 따라 다를 수 있습니다.

dictConfig()로 처리기를 사용자 정의하기

특정 상황에서 로깅 처리기를 사용자 정의하고 싶을 때가 있고, dictConfig()를 사용하고 있다면 서브 클래스를 만들지 않고도 이 작업을 수행 할 수 있습니다. 예를 들어, 로그 파일의 소유권을 설정하고 싶다고 합시다. POSIX에서, shutil.chown() 을 사용하면 쉽게 할 수 있지만, 표준 라이브러리의 파일 처리기는 내장된 지원을 제공하지 않습니다. 다음과 같은 일반 함수를 사용하여 처리기 생성을 사용자 정의 할 수 있습니다:

def owned_file_handler(filename, mode='a', encoding=None, owner=None):
    if owner:
        if not os.path.exists(filename):
            open(filename, 'a').close()
        shutil.chown(filename, *owner)
    return logging.FileHandler(filename, mode, encoding)

그런 다음, dictConfig() 에 전달되는 로깅 구성에서, 이 함수를 호출하여 로깅 처리기를 생성하도록 지정할 수 있습니다:

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'default': {
            'format': '%(asctime)s %(levelname)s %(name)s %(message)s'
        },
    },
    'handlers': {
        'file':{
            # The values below are popped from this dictionary and
            # used to create the handler, set the handler's level and
            # its formatter.
            '()': owned_file_handler,
            'level':'DEBUG',
            'formatter': 'default',
            # The values below are passed to the handler creator callable
            # as keyword arguments.
            'owner': ['pulse', 'pulse'],
            'filename': 'chowntest.log',
            'mode': 'w',
            'encoding': 'utf-8',
        },
    },
    'root': {
        'handlers': ['file'],
        'level': 'DEBUG',
    },
}

이 예제에서는 단지 예를 들기 위해 pulse 라는 사용자와 그룹을 사용하여 소유권을 설정합니다. 작동하는 스크립트 chowntest.py 로 정리하면:

import logging, logging.config, os, shutil

def owned_file_handler(filename, mode='a', encoding=None, owner=None):
    if owner:
        if not os.path.exists(filename):
            open(filename, 'a').close()
        shutil.chown(filename, *owner)
    return logging.FileHandler(filename, mode, encoding)

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'default': {
            'format': '%(asctime)s %(levelname)s %(name)s %(message)s'
        },
    },
    'handlers': {
        'file':{
            # The values below are popped from this dictionary and
            # used to create the handler, set the handler's level and
            # its formatter.
            '()': owned_file_handler,
            'level':'DEBUG',
            'formatter': 'default',
            # The values below are passed to the handler creator callable
            # as keyword arguments.
            'owner': ['pulse', 'pulse'],
            'filename': 'chowntest.log',
            'mode': 'w',
            'encoding': 'utf-8',
        },
    },
    'root': {
        'handlers': ['file'],
        'level': 'DEBUG',
    },
}

logging.config.dictConfig(LOGGING)
logger = logging.getLogger('mylogger')
logger.debug('A debug message')

이것을 실행하기 위해서는, 아마도 root 로 실행해야 할 것입니다:

$ sudo python3.3 chowntest.py
$ cat chowntest.log
2013-11-05 09:34:51,128 DEBUG mylogger A debug message
$ ls -l chowntest.log
-rw-r--r-- 1 pulse pulse 55 2013-11-05 09:34 chowntest.log

이 예제는 shutil.chown() 이 등장한 파이썬 3.3을 사용합니다. 이 접근법은 dictConfig()를 지원하는 모든 파이썬 버전에서 작동합니다 - 파이썬 2.7, 3.2 이상. 3.3 이전 버전의 경우, (예를 들어) os.chown() 을 사용하여 실제 소유권 변경을 구현해야 합니다.

실제로는, 처리기 생성 함수가 프로젝트 어딘가에 있는 유틸리티 모듈에 있을 수 있습니다. 구성에 있는 다음과 같은 줄 대신:

'()': owned_file_handler,

예를 들면 이렇게 쓸 수 있습니다:

'()': 'ext://project.util.owned_file_handler',

여기서 project.util 은 함수가 있는 패키지의 실제 이름으로 바꿀 수 있습니다. 위의 작업 스크립트에서 'ext://__main__.owned_file_handler' 를 사용해도 됩니다. 여기서, 실제 콜러블은 ext:// 스펙으로부터 dictConfig() 에 의해 결정됩니다.

이 예제는 희망하건대 다른 형태의 파일 변경을 - 예를 들어 특정 POSIX 권한 비트 설정 - 같은 방법으로 (os.chmod() 를 사용해서) 구현하는 방법도 알려줍니다.

물론 이 접근법은 FileHandler 이외의 처리기 유형으로도 확장될 수 있습니다 - 예를 들어, 회전 파일 처리기 중 하나 또는 다른 유형의 처리기 모두.

응용 프로그램 전체에서 특정 포맷 스타일 사용하기

파이썬 3.2에서, Formatter 는 style 키워드 매개변수를 얻었는데, 이전 버전과의 호환성을 위해 % 를 기본값으로 사용하면서 { 또는 $ 를 지정하면 str.format() 과 string.Template 에 의해 지원되는 포매팅 접근법을 사용할 수 있도록 합니다. 이것은 로그 되는 최종 출력으로 로깅 메시지를 포매팅하는 것과 관계된 것이고, 개별 로깅 메시지가 만들어지는 방법과는 무관함에 주의하십시오.

로깅 호출(debug(), info() 등)은 실제 로깅 메시지 자체를 위해서는 위치 매개 변수만을 취하고, 키워드 매개 변수는 실제 로깅 호출을 어떻게 다뤄야 하는지를 지정하는 옵션을 결정하는 용도로만 사용됩니다 (예를 들어, 트레이스백 정보를 로그 해야 할지를 가리키는 exc_info 키워드 매개 변수나 로그에 추가되는 문맥 정보를 나타내는 extra 키워드 매개 변수). 그래서 여러분은 str.format() 또는 string.Template 문법을 사용하여 직접 로깅 호출을 할 수 없습니다, 내부적으로 logging 패키지가 %-포매팅을 사용하여 포맷 문자열과 변수 인자를 병합하기 때문입니다. 이전 버전과의 호환성을 유지하는 동안은 이 상황이 바뀌지 않을 것입니다. 기존 코드에 있는 모든 로깅 호출이 %-포맷 문자열을 사용하기 때문입니다.

포맷 스타일을 특정 로거와 연관시키는 제안이 있었지만, 이전 버전과의 호환성 문제가 있는데, 기존 코드가 그 로거 이름으로 %-포매팅을 사용할 수 있기 때문입니다.

제삼자 라이브러리와 여러분의 코드 간에 상호 운용이 가능하도록 로깅 하려면, 개별 로깅 호출 수준에서 포매팅을 결정해야 합니다. 이렇게 할 때 대체 포매팅 스타일을 수용 할 수 있는 몇 가지 길이 열립니다.

LogRecord 팩토리 사용

파이썬 3.2에서, 위에서 언급 한 Formatter 변경 사항과 함께, logging 패키지는 setLogRecordFactory() 함수를 사용하여 사용자가 자신의 LogRecord 서브 클래스를 설정할 수 있는 기능을 얻었습니다. 이것을 사용하면, 원하는 일을 하도록 getMessage() 메서드를 재정의하는 여러분 자신의 LogRecord 서브 클래스를 설정할 수 있습니다. 이 메서드의 베이스 클래스 구현이 msg % args 포매팅이 일어나는 곳이며, 여러분이 대체 포매팅으로 치환할 수 있는 곳입니다; 그러나, 모든 포매팅 스타일을 지원하면서 다른 코드와의 상호 운용성을 보장하기 위해 %-포매팅을 기본값으로 사용하도록 주의해야 합니다. 또한, 베이스 구현과 마찬가지로 str(self.msg) 를 호출하도록 주의해야 합니다.

자세한 정보는 setLogRecordFactory()와 LogRecord 에 대한 레퍼런스 설명서를 참조하십시오.

사용자 정의 메시지 객체 사용

{}- 및 $-포매팅을 사용하여 개별 로그 메시지를 작성할 수 있는 또 다른, 아마도 더 간단한 방법이 있습니다. (임의의 객체를 메시지로 사용하기에서) 로깅 할 때 임의의 객체를 메시지 포맷 문자열로 사용할 수 있고, logging 패키지는 그 객체에 대해 str() 을 호출하여 실제 형식 문자열을 얻는다고 했던 것을 기억하실 수 있을 겁니다. 다음 두 클래스를 생각해봅시다:

class BraceMessage(object):
    def __init__(self, fmt, *args, **kwargs):
        self.fmt = fmt
        self.args = args
        self.kwargs = kwargs

    def __str__(self):
        return self.fmt.format(*self.args, **self.kwargs)

class DollarMessage(object):
    def __init__(self, fmt, **kwargs):
        self.fmt = fmt
        self.kwargs = kwargs

    def __str__(self):
        from string import Template
        return Template(self.fmt).substitute(**self.kwargs)

이 중 하나를 포맷 문자열 대신 사용하면, {}- 또는 $-포매팅을 사용하여 포맷된 로그 출력의 “%(message)s”, “{message}” 또는 “$message” 자리에 나타나는 실제 “message” 부분을 만들 수 있습니다. 어떤 것을 로그 하고 싶을 때마다 클래스 이름을 사용하는 것이 다소 꼴사납다면, 메시지에 M 이나 _ 과 같은 별칭을 사용해서 더 쓸만하게 만들 수 있습니다 (또는 지역화에 _ 를 사용하고 있다면, 아마도 __).

이 접근법의 예가 아래에 나와 있습니다. 먼저, str.format() 를 사용하는 포매팅입니다:

>>> __ = BraceMessage
>>> print(__('Message with {0} {1}', 2, 'placeholders'))
Message with 2 placeholders
>>> class Point: pass
...
>>> p = Point()
>>> p.x = 0.5
>>> p.y = 0.5
>>> print(__('Message with coordinates: ({point.x:.2f}, {point.y:.2f})', point=p))
Message with coordinates: (0.50, 0.50)

두 번째로, string.Template 를 사용하는 포매팅입니다:

>>> __ = DollarMessage
>>> print(__('Message with $num $what', num=2, what='placeholders'))
Message with 2 placeholders
>>>

한 가지 지적할 점은, 이 접근법이 성능상으로 큰 문제가 없다는 것입니다: 실제 포매팅은 로깅 호출을 할 때가 아니라 로깅 된 메시지를 실제로 처리기가 로그로 출력할 때 (그리고 실제로 그렇게 될 때만) 발생합니다. 그래서 여러분이 실수할 수도 있을 특이함은 괄호가 포맷 문자열과 인자들을 모두 감싼다는 것뿐입니다. __ 표기법이 단지 XXXMessage 클래스 중 하나에 대한 생성자 호출의 편의 문법이기 때문입니다.

dictConfig()로 필터 구성하기

dictConfig() 를 사용하여 필터를 구성할 수 있습니다. 하지만 처음에는 어떻게 해야 할지 명확하지 않을 수 있습니다 (그래서 이 조리법을 제공합니다). Filter 가 표준 라이브러리에 포함된 유일한 필터 클래스이고, 많은 요구 사항을 충족시키지는 않을 것이기 때문에 (오직 베이스 클래스로 제공됩니다), 일반적으로 filter() 메서드를 재정의하는 여러분 자신의 Filter 서브 클래스를 정의할 필요가 있습니다. 이렇게 하려면, 필터를 생성하는 데 사용될 콜러블을 필터의 구성 딕셔너리에 () 키로 지정하십시오 (클래스가 가장 분명하지만 Filter 인스턴스를 반환하는 콜러블은 모두 가능합니다). 다음은 완전한 예입니다:

import logging
import logging.config
import sys

class MyFilter(logging.Filter):
    def __init__(self, param=None):
        self.param = param

    def filter(self, record):
        if self.param is None:
            allow = True
        else:
            allow = self.param not in record.msg
        if allow:
            record.msg = 'changed: ' + record.msg
        return allow

LOGGING = {
    'version': 1,
    'filters': {
        'myfilter': {
            '()': MyFilter,
            'param': 'noshow',
        }
    },
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
            'filters': ['myfilter']
        }
    },
    'root': {
        'level': 'DEBUG',
        'handlers': ['console']
    },
}

if __name__ == '__main__':
    logging.config.dictConfig(LOGGING)
    logging.debug('hello')
    logging.debug('hello - noshow')

이 예제는 인스턴스를 만드는 콜러블로 키워드 매개 변수 형식으로 구성 데이터를 전달하는 방법을 보여줍니다. 실행하면, 위의 스크립트는 다음을 인쇄합니다:

changed: hello

필터가 구성된 대로 작동하고 있음을 보여줍니다.

주목해야 할 몇 가지 추가 사항:

구성에서 직접 참조할 수 없는 경우 (예를 들어, 다른 모듈에 있고 구성 딕셔너리가 있는 곳에서 직접 임포트 할 수 없는 경우), 외부 객체에 대한 액세스 에 설명된 대로 ext://... 형식을 사용할 수 있습니다. 예를 들어, 위의 예에서 MyFilter 대신 'ext://__main__.MyFilter' 를 사용할 수 있습니다.

필터뿐만 아니라, 이 기술을 사용자 정의 처리기 및 포매터를 구성하는데 사용할 수도 있습니다. logging이 구성에서 사용자 정의 객체를 어떻게 지원하는지에 대한 더 많은 정보는 사용자 정의 객체 를 보시고, 위의 다른 요리책 조리법 dictConfig()로 처리기를 사용자 정의하기 도 보십시오.

사용자 정의된 예외 포매팅

예외 포매팅을 사용자 정의하고 싶을 때가 있습니다 - 논쟁의 여지는 있지만, 예외 정보가 포함된 경우에도 이벤트 당 정확히 한 줄이 기록되기 원한다고 합시다. 다음 예제처럼, 사용자 정의 포매터 클래스를 사용할 수 있습니다:

import logging

class OneLineExceptionFormatter(logging.Formatter):
    def formatException(self, exc_info):
        """
        Format an exception so that it prints on a single line.
        """
        result = super(OneLineExceptionFormatter, self).formatException(exc_info)
        return repr(result)  # or format into one line however you want to

    def format(self, record):
        s = super(OneLineExceptionFormatter, self).format(record)
        if record.exc_text:
            s = s.replace('\n', '') + '|'
        return s

def configure_logging():
    fh = logging.FileHandler('output.txt', 'w')
    f = OneLineExceptionFormatter('%(asctime)s|%(levelname)s|%(message)s|',
                                  '%d/%m/%Y %H:%M:%S')
    fh.setFormatter(f)
    root = logging.getLogger()
    root.setLevel(logging.DEBUG)
    root.addHandler(fh)

def main():
    configure_logging()
    logging.info('Sample message')
    try:
        x = 1 / 0
    except ZeroDivisionError as e:
        logging.exception('ZeroDivisionError: %s', e)

if __name__ == '__main__':
    main()

실행하면, 정확하게 두 줄의 파일이 생성됩니다:

28/01/2015 07:21:23|INFO|Sample message|
28/01/2015 07:21:23|ERROR|ZeroDivisionError: integer division or modulo by zero|'Traceback (most recent call last):\n  File "logtest7.py", line 30, in main\n    x = 1 / 0\nZeroDivisionError: integer division or modulo by zero'|

위의 처리는 단순하지만, 예외 정보를 원하는 대로 포맷하는 방법을 알려줍니다. traceback 모듈은 더욱 전문화된 요구에 도움이 될 수 있습니다.

로깅 메시지 말하기

로깅 메시지를 보여주는 대신 들려주는 것이 바람직한 상황이 있을 수 있습니다. 여러분의 시스템에 텍스트-음성 변환 (TTS) 기능이 있다면 쉽습니다, 파이썬 바인딩이 없어도 됩니다. 대부분의 TTS 시스템에는 실행할 수 있는 명령행 프로그램이 있으며, 이것을 subprocess 를 사용하여 처리기에서 호출 할 수 있습니다. 여기서 TTS 명령행 프로그램이 사용자와 상호 작용하거나, 완료하는 데 오랜 시간이 걸릴 것으로 기대되지 않으며, 로그 되는 메시지의 빈도가 메시지로 사용자를 압도할 정도로 높지 않으며, 메시지는 동시에 처리되지 않고 한 번에 하나씩 읽어도 된다고 가정합니다. 아래의 예제 구현은 다음 메시지가 처리되기 전에 하나의 메시지를 다 읽을 때까지 대기하고, 이 때문에 다른 처리기가 대기 상태로 유지될 수 있습니다. 다음은 espeak TTS 패키지가 사용 가능하다고 가정하는 접근법을 보여주는 간단한 예입니다:

import logging
import subprocess
import sys

class TTSHandler(logging.Handler):
    def emit(self, record):
        msg = self.format(record)
        # Speak slowly in a female English voice
        cmd = ['espeak', '-s150', '-ven+f3', msg]
        p = subprocess.Popen(cmd, stdout=subprocess.PIPE,
                             stderr=subprocess.STDOUT)
        # wait for the program to finish
        p.communicate()

def configure_logging():
    h = TTSHandler()
    root = logging.getLogger()
    root.addHandler(h)
    # the default formatter just returns the message
    root.setLevel(logging.DEBUG)

def main():
    logging.info('Hello')
    logging.debug('Goodbye')

if __name__ == '__main__':
    configure_logging()
    sys.exit(main())

실행하면, 이 스크립트는 여성 음성으로 “Hello”와 “Goodbye”를 차례대로 말합니다.

물론 위의 접근법은 다른 TTS 시스템과 명령행에서 실행되는 외부 프로그램을 통해 메시지를 처리 할 수 있는 전혀 다른 시스템에도 적용될 수 있습니다.

로깅 메시지를 버퍼링하고 조건부 출력하기

임시 영역에 메시지를 기록하고 특정 조건이 발생할 때만 메시지를 출력하려는 상황이 있을 수 있습니다. 예를 들어, 함수에서 디버그 이벤트를 로깅 하기를 원할 수 있습니다. 함수가 에러 없이 완료되면 수집된 디버그 정보로 로그를 어지럽히고 싶지 않지만, 에러가 있으면 에러뿐만 아니라 모든 디버그 정보를 출력하고 싶습니다.

다음은 로깅이 이러한 방식으로 작동하기 원하는 함수에 데코레이터를 사용하여 이를 수행할 방법을 보여주는 예제입니다. logging.handlers.MemoryHandler 를 사용하는데, 어떤 상황이 발생할 때까지 로그 된 이벤트를 버퍼링할 수 있도록 하고, 때가 되면 버퍼링 된 이벤트들이 flush 됩니다 - 처리를 위해 다른 처리기(target 처리기)로 전달됩니다. 기본적으로, MemoryHandler 는 버퍼가 다 차거나 수준이 지정된 임계값보다 크거나 같은 이벤트가 발생하면 플러시 됩니다. 사용자 정의 플러시 동작을 원할 경우, 이 조리법을 MemoryHandler 의 더 특수한 서브 클래스와 함께 사용할 수 있습니다.

예제 스크립트에는 간단한 함수 foo 가 있는데, 모든 로그 수준을 순회하면서, 어떤 수준으로 로그 할지를 sys.stderr 에 쓴 다음, 그 수준으로 실제 메시지를 로깅 합니다. 매개 변수를 foo 에 전달할 수 있는데, 참이면 ERROR 및 CRITICAL 수준으로 로그 합니다 - 그렇지 않으면 DEBUG, INFO 및 WARNING 수준에서만 로그 합니다.

The script just arranges to decorate foo with a decorator which will do the conditional logging that’s required. The decorator takes a logger as a parameter and attaches a memory handler for the duration of the call to the decorated function. The decorator can be additionally parameterised using a target handler, a level at which flushing should occur, and a capacity for the buffer (number of records buffered). These default to a StreamHandler which writes to sys.stderr, logging.ERROR and 100 respectively.

스크립트는 다음과 같습니다:

import logging
from logging.handlers import MemoryHandler
import sys

logger = logging.getLogger(__name__)
logger.addHandler(logging.NullHandler())

def log_if_errors(logger, target_handler=None, flush_level=None, capacity=None):
    if target_handler is None:
        target_handler = logging.StreamHandler()
    if flush_level is None:
        flush_level = logging.ERROR
    if capacity is None:
        capacity = 100
    handler = MemoryHandler(capacity, flushLevel=flush_level, target=target_handler)

    def decorator(fn):
        def wrapper(*args, **kwargs):
            logger.addHandler(handler)
            try:
                return fn(*args, **kwargs)
            except Exception:
                logger.exception('call failed')
                raise
            finally:
                super(MemoryHandler, handler).flush()
                logger.removeHandler(handler)
        return wrapper

    return decorator

def write_line(s):
    sys.stderr.write('%s\n' % s)

def foo(fail=False):
    write_line('about to log at DEBUG ...')
    logger.debug('Actually logged at DEBUG')
    write_line('about to log at INFO ...')
    logger.info('Actually logged at INFO')
    write_line('about to log at WARNING ...')
    logger.warning('Actually logged at WARNING')
    if fail:
        write_line('about to log at ERROR ...')
        logger.error('Actually logged at ERROR')
        write_line('about to log at CRITICAL ...')
        logger.critical('Actually logged at CRITICAL')
    return fail

decorated_foo = log_if_errors(logger)(foo)

if __name__ == '__main__':
    logger.setLevel(logging.DEBUG)
    write_line('Calling undecorated foo with False')
    assert not foo(False)
    write_line('Calling undecorated foo with True')
    assert foo(True)
    write_line('Calling decorated foo with False')
    assert not decorated_foo(False)
    write_line('Calling decorated foo with True')
    assert decorated_foo(True)

이 스크립트를 실행하면 다음과 같은 출력이 나타납니다.:

Calling undecorated foo with False
about to log at DEBUG ...
about to log at INFO ...
about to log at WARNING ...
Calling undecorated foo with True
about to log at DEBUG ...
about to log at INFO ...
about to log at WARNING ...
about to log at ERROR ...
about to log at CRITICAL ...
Calling decorated foo with False
about to log at DEBUG ...
about to log at INFO ...
about to log at WARNING ...
Calling decorated foo with True
about to log at DEBUG ...
about to log at INFO ...
about to log at WARNING ...
about to log at ERROR ...
Actually logged at DEBUG
Actually logged at INFO
Actually logged at WARNING
Actually logged at ERROR
about to log at CRITICAL ...
Actually logged at CRITICAL

보시다시피, 실제 로깅 출력은 심각도가 ERROR 이상인 이벤트가 기록될 때만 발생하지만, 이 경우 심각도가 낮은 이전 이벤트도 기록됩니다.

물론 전통적인 데코레이션 수단을 쓸 수 있습니다.:

@log_if_errors(logger)
def foo(fail=False):
    ...

구성을 통해 UTC(GMT)로 시간을 포맷하기

때로는 UTC를 사용하여 시간을 포맷하고 싶습니다. 아래에 표시된 UTCFormatter 와 같은 클래스를 사용할 수 있습니다:

import logging
import time

class UTCFormatter(logging.Formatter):
    converter = time.gmtime

이제 Formatter 대신 코드에서 UTCFormatter 를 사용할 수 있습니다. 구성을 통해 이를 수행하려면, 다음에 나오는 완전한 예제에 의해 설명된 접근법으로 dictConfig() API를 사용할 수 있습니다:

import logging
import logging.config
import time

class UTCFormatter(logging.Formatter):
    converter = time.gmtime

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'utc': {
            '()': UTCFormatter,
            'format': '%(asctime)s %(message)s',
        },
        'local': {
            'format': '%(asctime)s %(message)s',
        }
    },
    'handlers': {
        'console1': {
            'class': 'logging.StreamHandler',
            'formatter': 'utc',
        },
        'console2': {
            'class': 'logging.StreamHandler',
            'formatter': 'local',
        },
    },
    'root': {
        'handlers': ['console1', 'console2'],
   }
}

if __name__ == '__main__':
    logging.config.dictConfig(LOGGING)
    logging.warning('The local time is %s', time.asctime())

이 스크립트를 실행하면, 다음과 같은 내용을 인쇄합니다:

2015-10-17 12:53:29,501 The local time is Sat Oct 17 13:53:29 2015
2015-10-17 13:53:29,501 The local time is Sat Oct 17 13:53:29 2015

시간이 한 처리기에서는 UTC로, 다른 처리기에서는 지역 시간으로 포맷되는 것을 보여줍니다.

선택적 로깅을 위해 컨텍스트 관리자 사용하기

로깅 구성을 일시적으로 변경하고 무언가를 한 후에 되돌리는 것이 유용할 때가 있습니다. 이를 위해, 컨텍스트 관리자는 로깅 컨텍스트를 저장하고 복원하는 가장 분명한 방법입니다. 다음은 그러한 컨텍스트 관리자의 간단한 예입니다. 컨텍스트 관리자의 범위 안에서 선택적으로 로깅 수준을 변경하고 로깅 처리기를 추가 할 수 있습니다:

import logging
import sys

class LoggingContext(object):
    def __init__(self, logger, level=None, handler=None, close=True):
        self.logger = logger
        self.level = level
        self.handler = handler
        self.close = close

    def __enter__(self):
        if self.level is not None:
            self.old_level = self.logger.level
            self.logger.setLevel(self.level)
        if self.handler:
            self.logger.addHandler(self.handler)

    def __exit__(self, et, ev, tb):
        if self.level is not None:
            self.logger.setLevel(self.old_level)
        if self.handler:
            self.logger.removeHandler(self.handler)
        if self.handler and self.close:
            self.handler.close()
        # implicit return of None => don't swallow exceptions

수준 값을 지정하면, 로거의 수준은 컨텍스트 관리자가 적용되는 with 블록의 범위 안에서 해당 값으로 설정됩니다. 처리기를 지정하면, 블록 진입 시 로거에 추가되고 블록에서 빠져나갈 때 제거됩니다. 블록을 빠져나갈 때 처리기를 닫도록 관리자에게 요청할 수도 있습니다 - 더는 처리기가 필요하지 않으면 이렇게 할 수 있습니다.

작동 원리를 보여주기 위해, 다음 코드 블록을 위에 추가 할 수 있습니다:

if __name__ == '__main__':
    logger = logging.getLogger('foo')
    logger.addHandler(logging.StreamHandler())
    logger.setLevel(logging.INFO)
    logger.info('1. This should appear just once on stderr.')
    logger.debug('2. This should not appear.')
    with LoggingContext(logger, level=logging.DEBUG):
        logger.debug('3. This should appear once on stderr.')
    logger.debug('4. This should not appear.')
    h = logging.StreamHandler(sys.stdout)
    with LoggingContext(logger, level=logging.DEBUG, handler=h, close=True):
        logger.debug('5. This should appear twice - once on stderr and once on stdout.')
    logger.info('6. This should appear just once on stderr.')
    logger.debug('7. This should not appear.')

우리는 초기에 로거 수준을 INFO 로 설정합니다. 그래서 메시지 #1은 나타나고 메시지 #2는 나타나지 않습니다. 그다음에 with 블록에서 수준을 DEBUG 로 임시 변경하면, 메시지 #3이 나타납니다. 블록이 종료되면 로거 수준이 INFO 로 복원되므로, 메시지 #4가 표시되지 않습니다. 그다음 with 블록에서 수준을 다시 DEBUG 로 다시 설정하지만, sys.stdout 으로 쓰는 처리기도 추가합니다. 따라서 메시지 #5는 콘솔에 두 번 표시됩니다 (stderr 를 통해 한 번, stdout 을 통해 한 번). with 문장이 완료된 후에 상태는 이전과 같으므로, (메시지 #1처럼) 메시지 #6이 나타나고, (메시지 #2처럼) 메시지 #7은 보이지 않습니다.

이렇게 만든 스크립트를 실행하면, 결과는 다음과 같습니다:

$ python logctx.py
1. This should appear just once on stderr.
3. This should appear once on stderr.
5. This should appear twice - once on stderr and once on stdout.
5. This should appear twice - once on stderr and once on stdout.
6. This should appear just once on stderr.

다시 실행하면서 stderr 를 /dev/null 로 리디렉트하면, 다음과 같이 stdout 으로 출력된 메시지만 나타납니다:

$ python logctx.py 2>/dev/null
5. This should appear twice - once on stderr and once on stdout.

다시 한번, 하지만 stdout 을 /dev/null 로 리디렉트하면, 이렇게 됩니다:

$ python logctx.py >/dev/null
1. This should appear just once on stderr.
3. This should appear once on stderr.
5. This should appear twice - once on stderr and once on stdout.
6. This should appear just once on stderr.

이 경우, stdout 에 인쇄된 메시지 #5는 예상대로 나타나지 않습니다.

물론 여기서 설명한 방법을 일반화 할 수 있습니다. 예를 들어 로깅 필터를 임시로 첨부 할 수 있습니다. 위의 코드는 파이썬 2와 파이썬 3에서 모두 작동합니다.

A CLI application starter template

Here’s an example which shows how you can:

Use a logging level based on command-line arguments

Dispatch to multiple subcommands in separate files, all logging at the same level in a consistent way

Make use of simple, minimal configuration

Suppose we have a command-line application whose job is to stop, start or restart some services. This could be organised for the purposes of illustration as a file app.py that is the main script for the application, with individual commands implemented in start.py, stop.py and restart.py. Suppose further that we want to control the verbosity of the application via a command-line argument, defaulting to logging.INFO. Here’s one way that app.py could be written:

import argparse
import importlib
import logging
import os
import sys

def main(args=None):
    scriptname = os.path.basename(__file__)
    parser = argparse.ArgumentParser(scriptname)
    levels = ('DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL')
    parser.add_argument('--log-level', default='INFO', choices=levels)
    subparsers = parser.add_subparsers(dest='command',
                                       help='Available commands:')
    start_cmd = subparsers.add_parser('start', help='Start a service')
    start_cmd.add_argument('name', metavar='NAME',
                           help='Name of service to start')
    stop_cmd = subparsers.add_parser('stop',
                                     help='Stop one or more services')
    stop_cmd.add_argument('names', metavar='NAME', nargs='+',
                          help='Name of service to stop')
    restart_cmd = subparsers.add_parser('restart',
                                        help='Restart one or more services')
    restart_cmd.add_argument('names', metavar='NAME', nargs='+',
                             help='Name of service to restart')
    options = parser.parse_args()
    # the code to dispatch commands could all be in this file. For the purposes
    # of illustration only, we implement each command in a separate module.
    try:
        mod = importlib.import_module(options.command)
        cmd = getattr(mod, 'command')
    except (ImportError, AttributeError):
        print('Unable to find the code for command \'%s\'' % options.command)
        return 1
    # Could get fancy here and load configuration from file or dictionary
    logging.basicConfig(level=options.log_level,
                        format='%(levelname)s %(name)s %(message)s')
    cmd(options)

if __name__ == '__main__':
    sys.exit(main())

And the start, stop and restart commands can be implemented in separate modules, like so for starting:

# start.py
import logging

logger = logging.getLogger(__name__)

def command(options):
    logger.debug('About to start %s', options.name)
    # actually do the command processing here ...
    logger.info('Started the \'%s\' service.', options.name)

and thus for stopping:

# stop.py
import logging

logger = logging.getLogger(__name__)

def command(options):
    n = len(options.names)
    if n == 1:
        plural = ''
        services = '\'%s\'' % options.names[0]
    else:
        plural = 's'
        services = ', '.join('\'%s\'' % name for name in options.names)
        i = services.rfind(', ')
        services = services[:i] + ' and ' + services[i + 2:]
    logger.debug('About to stop %s', services)
    # actually do the command processing here ...
    logger.info('Stopped the %s service%s.', services, plural)

and similarly for restarting:

# restart.py
import logging

logger = logging.getLogger(__name__)

def command(options):
    n = len(options.names)
    if n == 1:
        plural = ''
        services = '\'%s\'' % options.names[0]
    else:
        plural = 's'
        services = ', '.join('\'%s\'' % name for name in options.names)
        i = services.rfind(', ')
        services = services[:i] + ' and ' + services[i + 2:]
    logger.debug('About to restart %s', services)
    # actually do the command processing here ...
    logger.info('Restarted the %s service%s.', services, plural)

If we run this application with the default log level, we get output like this:

$ python app.py start foo
INFO start Started the 'foo' service.

$ python app.py stop foo bar
INFO stop Stopped the 'foo' and 'bar' services.

$ python app.py restart foo bar baz
INFO restart Restarted the 'foo', 'bar' and 'baz' services.

The first word is the logging level, and the second word is the module or package name of the place where the event was logged.

If we change the logging level, then we can change the information sent to the log. For example, if we want more information:

$ python app.py --log-level DEBUG start foo
DEBUG start About to start foo
INFO start Started the 'foo' service.

$ python app.py --log-level DEBUG stop foo bar
DEBUG stop About to stop 'foo' and 'bar'
INFO stop Stopped the 'foo' and 'bar' services.

$ python app.py --log-level DEBUG restart foo bar baz
DEBUG restart About to restart 'foo', 'bar' and 'baz'
INFO restart Restarted the 'foo', 'bar' and 'baz' services.

And if we want less:

$ python app.py --log-level WARNING start foo
$ python app.py --log-level WARNING stop foo bar
$ python app.py --log-level WARNING restart foo bar baz

In this case, the commands don’t print anything to the console, since nothing at WARNING level or above is logged by them.

A Qt GUI for logging

A question that comes up from time to time is about how to log to a GUI application. The Qt [https://www.qt.io/] framework is a popular cross-platform UI framework with Python bindings using PySide2 [https://pypi.org/project/PySide2/] or PyQt5 [https://pypi.org/project/PyQt5/] libraries.

The following example shows how to log to a Qt GUI. This introduces a simple QtHandler class which takes a callable, which should be a slot in the main thread that does GUI updates. A worker thread is also created to show how you can log to the GUI from both the UI itself (via a button for manual logging) as well as a worker thread doing work in the background (here, just logging messages at random levels with random short delays in between).

The worker thread is implemented using Qt’s QThread class rather than the threading module, as there are circumstances where one has to use QThread, which offers better integration with other Qt components.

The code should work with recent releases of either PySide2 or PyQt5. You should be able to adapt the approach to earlier versions of Qt. Please refer to the comments in the code snippet for more detailed information.

import datetime
import logging
import random
import sys
import time

# Deal with minor differences between PySide2 and PyQt5
try:
    from PySide2 import QtCore, QtGui, QtWidgets
    Signal = QtCore.Signal
    Slot = QtCore.Slot
except ImportError:
    from PyQt5 import QtCore, QtGui, QtWidgets
    Signal = QtCore.pyqtSignal
    Slot = QtCore.pyqtSlot

logger = logging.getLogger(__name__)

#
# Signals need to be contained in a QObject or subclass in order to be correctly
# initialized.
#
class Signaller(QtCore.QObject):
    signal = Signal(str, logging.LogRecord)

#
# Output to a Qt GUI is only supposed to happen on the main thread. So, this
# handler is designed to take a slot function which is set up to run in the main
# thread. In this example, the function takes a string argument which is a
# formatted log message, and the log record which generated it. The formatted
# string is just a convenience - you could format a string for output any way
# you like in the slot function itself.
#
# You specify the slot function to do whatever GUI updates you want. The handler
# doesn't know or care about specific UI elements.
#
class QtHandler(logging.Handler):
    def __init__(self, slotfunc, *args, **kwargs):
        super(QtHandler, self).__init__(*args, **kwargs)
        self.signaller = Signaller()
        self.signaller.signal.connect(slotfunc)

    def emit(self, record):
        s = self.format(record)
        self.signaller.signal.emit(s, record)

#
# This example uses QThreads, which means that the threads at the Python level
# are named something like "Dummy-1". The function below gets the Qt name of the
# current thread.
#
def ctname():
    return QtCore.QThread.currentThread().objectName()

#
# Used to generate random levels for logging.
#
LEVELS = (logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR,
          logging.CRITICAL)

#
# This worker class represents work that is done in a thread separate to the
# main thread. The way the thread is kicked off to do work is via a button press
# that connects to a slot in the worker.
#
# Because the default threadName value in the LogRecord isn't much use, we add
# a qThreadName which contains the QThread name as computed above, and pass that
# value in an "extra" dictionary which is used to update the LogRecord with the
# QThread name.
#
# This example worker just outputs messages sequentially, interspersed with
# random delays of the order of a few seconds.
#
class Worker(QtCore.QObject):
    @Slot()
    def start(self):
        extra = {'qThreadName': ctname() }
        logger.debug('Started work', extra=extra)
        i = 1
        # Let the thread run until interrupted. This allows reasonably clean
        # thread termination.
        while not QtCore.QThread.currentThread().isInterruptionRequested():
            delay = 0.5 + random.random() * 2
            time.sleep(delay)
            level = random.choice(LEVELS)
            logger.log(level, 'Message after delay of %3.1f: %d', delay, i, extra=extra)
            i += 1

#
# Implement a simple UI for this cookbook example. This contains:
#
# * A read-only text edit window which holds formatted log messages
# * A button to start work and log stuff in a separate thread
# * A button to log something from the main thread
# * A button to clear the log window
#
class Window(QtWidgets.QWidget):

    COLORS = {
        logging.DEBUG: 'black',
        logging.INFO: 'blue',
        logging.WARNING: 'orange',
        logging.ERROR: 'red',
        logging.CRITICAL: 'purple',
    }

    def __init__(self, app):
        super(Window, self).__init__()
        self.app = app
        self.textedit = te = QtWidgets.QPlainTextEdit(self)
        # Set whatever the default monospace font is for the platform
        f = QtGui.QFont('nosuchfont')
        f.setStyleHint(f.Monospace)
        te.setFont(f)
        te.setReadOnly(True)
        PB = QtWidgets.QPushButton
        self.work_button = PB('Start background work', self)
        self.log_button = PB('Log a message at a random level', self)
        self.clear_button = PB('Clear log window', self)
        self.handler = h = QtHandler(self.update_status)
        # Remember to use qThreadName rather than threadName in the format string.
        fs = '%(asctime)s %(qThreadName)-12s %(levelname)-8s %(message)s'
        formatter = logging.Formatter(fs)
        h.setFormatter(formatter)
        logger.addHandler(h)
        # Set up to terminate the QThread when we exit
        app.aboutToQuit.connect(self.force_quit)

        # Lay out all the widgets
        layout = QtWidgets.QVBoxLayout(self)
        layout.addWidget(te)
        layout.addWidget(self.work_button)
        layout.addWidget(self.log_button)
        layout.addWidget(self.clear_button)
        self.setFixedSize(900, 400)

        # Connect the non-worker slots and signals
        self.log_button.clicked.connect(self.manual_update)
        self.clear_button.clicked.connect(self.clear_display)

        # Start a new worker thread and connect the slots for the worker
        self.start_thread()
        self.work_button.clicked.connect(self.worker.start)
        # Once started, the button should be disabled
        self.work_button.clicked.connect(lambda : self.work_button.setEnabled(False))

    def start_thread(self):
        self.worker = Worker()
        self.worker_thread = QtCore.QThread()
        self.worker.setObjectName('Worker')
        self.worker_thread.setObjectName('WorkerThread')  # for qThreadName
        self.worker.moveToThread(self.worker_thread)
        # This will start an event loop in the worker thread
        self.worker_thread.start()

    def kill_thread(self):
        # Just tell the worker to stop, then tell it to quit and wait for that
        # to happen
        self.worker_thread.requestInterruption()
        if self.worker_thread.isRunning():
            self.worker_thread.quit()
            self.worker_thread.wait()
        else:
            print('worker has already exited.')

    def force_quit(self):
        # For use when the window is closed
        if self.worker_thread.isRunning():
            self.kill_thread()

    # The functions below update the UI and run in the main thread because
    # that's where the slots are set up

    @Slot(str, logging.LogRecord)
    def update_status(self, status, record):
        color = self.COLORS.get(record.levelno, 'black')
        s = '<pre><font color="%s">%s</font></pre>' % (color, status)
        self.textedit.appendHtml(s)

    @Slot()
    def manual_update(self):
        # This function uses the formatted message passed in, but also uses
        # information from the record to format the message in an appropriate
        # color according to its severity (level).
        level = random.choice(LEVELS)
        extra = {'qThreadName': ctname() }
        logger.log(level, 'Manually logged!', extra=extra)

    @Slot()
    def clear_display(self):
        self.textedit.clear()

def main():
    QtCore.QThread.currentThread().setObjectName('MainThread')
    logging.getLogger().setLevel(logging.DEBUG)
    app = QtWidgets.QApplication(sys.argv)
    example = Window(app)
    example.show()
    sys.exit(app.exec_())

if __name__=='__main__':
    main()

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 HOWTO »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 HOWTO »

|

Regular Expression HOWTO

Author

A.M. Kuchling <amk@amk.ca>

Abstract

This document is an introductory tutorial to using regular expressions in Python with the re module. It provides a gentler introduction than the corresponding section in the Library Reference.

Introduction

Regular expressions (called REs, or regexes, or regex patterns) are essentially a tiny, highly specialized programming language embedded inside Python and made available through the re module. Using this little language, you specify the rules for the set of possible strings that you want to match; this set might contain English sentences, or e-mail addresses, or TeX commands, or anything you like. You can then ask questions such as “Does this string match the pattern?”, or “Is there a match for the pattern anywhere in this string?”. You can also use REs to modify a string or to split it apart in various ways.

Regular expression patterns are compiled into a series of bytecodes which are then executed by a matching engine written in C. For advanced use, it may be necessary to pay careful attention to how the engine will execute a given RE, and write the RE in a certain way in order to produce bytecode that runs faster. Optimization isn’t covered in this document, because it requires that you have a good understanding of the matching engine’s internals.

The regular expression language is relatively small and restricted, so not all possible string processing tasks can be done using regular expressions. There are also tasks that can be done with regular expressions, but the expressions turn out to be very complicated. In these cases, you may be better off writing Python code to do the processing; while Python code will be slower than an elaborate regular expression, it will also probably be more understandable.

Simple Patterns

We’ll start by learning about the simplest possible regular expressions. Since regular expressions are used to operate on strings, we’ll begin with the most common task: matching characters.

For a detailed explanation of the computer science underlying regular expressions (deterministic and non-deterministic finite automata), you can refer to almost any textbook on writing compilers.

Matching Characters

Most letters and characters will simply match themselves. For example, the regular expression test will match the string test exactly. (You can enable a case-insensitive mode that would let this RE match Test or TEST as well; more about this later.)

There are exceptions to this rule; some characters are special metacharacters, and don’t match themselves. Instead, they signal that some out-of-the-ordinary thing should be matched, or they affect other portions of the RE by repeating them or changing their meaning. Much of this document is devoted to discussing various metacharacters and what they do.

Here’s a complete list of the metacharacters; their meanings will be discussed in the rest of this HOWTO.

. ^ $ * + ? { } [ ] \ | ( )

The first metacharacters we’ll look at are [ and ]. They’re used for specifying a character class, which is a set of characters that you wish to match. Characters can be listed individually, or a range of characters can be indicated by giving two characters and separating them by a '-'. For example, [abc] will match any of the characters a, b, or c; this is the same as [a-c], which uses a range to express the same set of characters. If you wanted to match only lowercase letters, your RE would be [a-z].

Metacharacters are not active inside classes. For example, [akm$] will match any of the characters 'a', 'k', 'm', or '$'; '$' is usually a metacharacter, but inside a character class it’s stripped of its special nature.

You can match the characters not listed within the class by complementing the set. This is indicated by including a '^' as the first character of the class. For example, [^5] will match any character except '5'. If the caret appears elsewhere in a character class, it does not have special meaning. For example: [5^] will match either a '5' or a '^'.

Perhaps the most important metacharacter is the backslash, \. As in Python string literals, the backslash can be followed by various characters to signal various special sequences. It’s also used to escape all the metacharacters so you can still match them in patterns; for example, if you need to match a [ or \, you can precede them with a backslash to remove their special meaning: \[ or \\.

Some of the special sequences beginning with '\' represent predefined sets of characters that are often useful, such as the set of digits, the set of letters, or the set of anything that isn’t whitespace.

Let’s take an example: \w matches any alphanumeric character. If the regex pattern is expressed in bytes, this is equivalent to the class [a-zA-Z0-9_]. If the regex pattern is a string, \w will match all the characters marked as letters in the Unicode database provided by the unicodedata module. You can use the more restricted definition of \w in a string pattern by supplying the re.ASCII flag when compiling the regular expression.

The following list of special sequences isn’t complete. For a complete list of sequences and expanded class definitions for Unicode string patterns, see the last part of Regular Expression Syntax in the Standard Library reference. In general, the Unicode versions match any character that’s in the appropriate category in the Unicode database.

\d

Matches any decimal digit; this is equivalent to the class [0-9].

\D

Matches any non-digit character; this is equivalent to the class [^0-9].

\s

Matches any whitespace character; this is equivalent to the class [ \t\n\r\f\v].

\S

Matches any non-whitespace character; this is equivalent to the class [^ \t\n\r\f\v].

\w

Matches any alphanumeric character; this is equivalent to the class [a-zA-Z0-9_].

\W

Matches any non-alphanumeric character; this is equivalent to the class [^a-zA-Z0-9_].

These sequences can be included inside a character class. For example, [\s,.] is a character class that will match any whitespace character, or ',' or '.'.

The final metacharacter in this section is .. It matches anything except a newline character, and there’s an alternate mode (re.DOTALL) where it will match even a newline. . is often used where you want to match “any character”.

Repeating Things

Being able to match varying sets of characters is the first thing regular expressions can do that isn’t already possible with the methods available on strings. However, if that was the only additional capability of regexes, they wouldn’t be much of an advance. Another capability is that you can specify that portions of the RE must be repeated a certain number of times.

The first metacharacter for repeating things that we’ll look at is *. * doesn’t match the literal character '*'; instead, it specifies that the previous character can be matched zero or more times, instead of exactly once.

For example, ca*t will match 'ct' (0 'a' characters), 'cat' (1 'a'), 'caaat' (3 'a' characters), and so forth.

Repetitions such as * are greedy; when repeating a RE, the matching engine will try to repeat it as many times as possible. If later portions of the pattern don’t match, the matching engine will then back up and try again with fewer repetitions.

A step-by-step example will make this more obvious. Let’s consider the expression a[bcd]*b. This matches the letter 'a', zero or more letters from the class [bcd], and finally ends with a 'b'. Now imagine matching this RE against the string 'abcbd'.

Step

Matched

Explanation

1

a

The a in the RE matches.

2

abcbd

The engine matches [bcd]*, going as far as it can, which is to the end of the string.

3

Failure

The engine tries to match b, but the current position is at the end of the string, so it fails.

4

abcb

Back up, so that [bcd]* matches one less character.

5

Failure

Try b again, but the current position is at the last character, which is a 'd'.

6

abc

Back up again, so that [bcd]* is only matching bc.

6

abcb

Try b again. This time the character at the current position is 'b', so it succeeds.

The end of the RE has now been reached, and it has matched 'abcb'. This demonstrates how the matching engine goes as far as it can at first, and if no match is found it will then progressively back up and retry the rest of the RE again and again. It will back up until it has tried zero matches for [bcd]*, and if that subsequently fails, the engine will conclude that the string doesn’t match the RE at all.

Another repeating metacharacter is +, which matches one or more times. Pay careful attention to the difference between * and +; * matches zero or more times, so whatever’s being repeated may not be present at all, while + requires at least one occurrence. To use a similar example, ca+t will match 'cat' (1 'a'), 'caaat' (3 'a's), but won’t match 'ct'.

There are two more repeating qualifiers. The question mark character, ?, matches either once or zero times; you can think of it as marking something as being optional. For example, home-?brew matches either 'homebrew' or 'home-brew'.

The most complicated repeated qualifier is {m,n}, where m and n are decimal integers. This qualifier means there must be at least m repetitions, and at most n. For example, a/{1,3}b will match 'a/b', 'a//b', and 'a///b'. It won’t match 'ab', which has no slashes, or 'a////b', which has four.

You can omit either m or n; in that case, a reasonable value is assumed for the missing value. Omitting m is interpreted as a lower limit of 0, while omitting n results in an upper bound of infinity.

Readers of a reductionist bent may notice that the three other qualifiers can all be expressed using this notation. {0,} is the same as *, {1,} is equivalent to +, and {0,1} is the same as ?. It’s better to use *, +, or ? when you can, simply because they’re shorter and easier to read.

Using Regular Expressions

Now that we’ve looked at some simple regular expressions, how do we actually use them in Python? The re module provides an interface to the regular expression engine, allowing you to compile REs into objects and then perform matches with them.

Compiling Regular Expressions

Regular expressions are compiled into pattern objects, which have methods for various operations such as searching for pattern matches or performing string substitutions.

>>> import re
>>> p = re.compile('ab*')
>>> p
re.compile('ab*')

re.compile() also accepts an optional flags argument, used to enable various special features and syntax variations. We’ll go over the available settings later, but for now a single example will do:

>>> p = re.compile('ab*', re.IGNORECASE)

The RE is passed to re.compile() as a string. REs are handled as strings because regular expressions aren’t part of the core Python language, and no special syntax was created for expressing them. (There are applications that don’t need REs at all, so there’s no need to bloat the language specification by including them.) Instead, the re module is simply a C extension module included with Python, just like the socket or zlib modules.

Putting REs in strings keeps the Python language simpler, but has one disadvantage which is the topic of the next section.

The Backslash Plague

As stated earlier, regular expressions use the backslash character ('\') to indicate special forms or to allow special characters to be used without invoking their special meaning. This conflicts with Python’s usage of the same character for the same purpose in string literals.

Let’s say you want to write a RE that matches the string \section, which might be found in a LaTeX file. To figure out what to write in the program code, start with the desired string to be matched. Next, you must escape any backslashes and other metacharacters by preceding them with a backslash, resulting in the string \\section. The resulting string that must be passed to re.compile() must be \\section. However, to express this as a Python string literal, both backslashes must be escaped again.

Characters

Stage

\section

Text string to be matched

\\section

Escaped backslash for re.compile()

"\\\\section"

Escaped backslashes for a string literal

In short, to match a literal backslash, one has to write '\\\\' as the RE string, because the regular expression must be \\, and each backslash must be expressed as \\ inside a regular Python string literal. In REs that feature backslashes repeatedly, this leads to lots of repeated backslashes and makes the resulting strings difficult to understand.

The solution is to use Python’s raw string notation for regular expressions; backslashes are not handled in any special way in a string literal prefixed with 'r', so r"\n" is a two-character string containing '\' and 'n', while "\n" is a one-character string containing a newline. Regular expressions will often be written in Python code using this raw string notation.

In addition, special escape sequences that are valid in regular expressions, but not valid as Python string literals, now result in a DeprecationWarning and will eventually become a SyntaxError, which means the sequences will be invalid if raw string notation or escaping the backslashes isn’t used.

Regular String

Raw string

"ab*"

r"ab*"

"\\\\section"

r"\\section"

"\\w+\\s+\\1"

r"\w+\s+\1"

Performing Matches

Once you have an object representing a compiled regular expression, what do you do with it? Pattern objects have several methods and attributes. Only the most significant ones will be covered here; consult the re docs for a complete listing.

Method/Attribute

Purpose

match()

Determine if the RE matches at the beginning of the string.

search()

Scan through a string, looking for any location where this RE matches.

findall()

Find all substrings where the RE matches, and returns them as a list.

finditer()

Find all substrings where the RE matches, and returns them as an iterator.

match() and search() return None if no match can be found. If they’re successful, a match object instance is returned, containing information about the match: where it starts and ends, the substring it matched, and more.

You can learn about this by interactively experimenting with the re module. If you have tkinter available, you may also want to look at Tools/demo/redemo.py [https://github.com/python/cpython/tree/3.7/Tools/demo/redemo.py], a demonstration program included with the Python distribution. It allows you to enter REs and strings, and displays whether the RE matches or fails. redemo.py can be quite useful when trying to debug a complicated RE.

This HOWTO uses the standard Python interpreter for its examples. First, run the Python interpreter, import the re module, and compile a RE:

>>> import re
>>> p = re.compile('[a-z]+')
>>> p
re.compile('[a-z]+')

Now, you can try matching various strings against the RE [a-z]+. An empty string shouldn’t match at all, since + means ‘one or more repetitions’. match() should return None in this case, which will cause the interpreter to print no output. You can explicitly print the result of match() to make this clear.

>>> p.match("")
>>> print(p.match(""))
None

Now, let’s try it on a string that it should match, such as tempo. In this case, match() will return a match object, so you should store the result in a variable for later use.

>>> m = p.match('tempo')
>>> m
<re.Match object; span=(0, 5), match='tempo'>

Now you can query the match object for information about the matching string. Match object instances also have several methods and attributes; the most important ones are:

Method/Attribute

Purpose

group()

Return the string matched by the RE

start()

Return the starting position of the match

end()

Return the ending position of the match

span()

Return a tuple containing the (start, end) positions of the match

Trying these methods will soon clarify their meaning:

>>> m.group()
'tempo'
>>> m.start(), m.end()
(0, 5)
>>> m.span()
(0, 5)

group() returns the substring that was matched by the RE. start() and end() return the starting and ending index of the match. span() returns both start and end indexes in a single tuple. Since the match() method only checks if the RE matches at the start of a string, start() will always be zero. However, the search() method of patterns scans through the string, so the match may not start at zero in that case.

>>> print(p.match('::: message'))
None
>>> m = p.search('::: message'); print(m)
<re.Match object; span=(4, 11), match='message'>
>>> m.group()
'message'
>>> m.span()
(4, 11)

In actual programs, the most common style is to store the match object in a variable, and then check if it was None. This usually looks like:

p = re.compile( ... )
m = p.match( 'string goes here' )
if m:
    print('Match found: ', m.group())
else:
    print('No match')

Two pattern methods return all of the matches for a pattern. findall() returns a list of matching strings:

>>> p = re.compile(r'\d+')
>>> p.findall('12 drummers drumming, 11 pipers piping, 10 lords a-leaping')
['12', '11', '10']

The r prefix, making the literal a raw string literal, is needed in this example because escape sequences in a normal “cooked” string literal that are not recognized by Python, as opposed to regular expressions, now result in a DeprecationWarning and will eventually become a SyntaxError. See The Backslash Plague.

findall() has to create the entire list before it can be returned as the result. The finditer() method returns a sequence of match object instances as an iterator:

>>> iterator = p.finditer('12 drummers drumming, 11 ... 10 ...')
>>> iterator
<callable_iterator object at 0x...>
>>> for match in iterator:
...     print(match.span())
...
(0, 2)
(22, 24)
(29, 31)

Module-Level Functions

You don’t have to create a pattern object and call its methods; the re module also provides top-level functions called match(), search(), findall(), sub(), and so forth. These functions take the same arguments as the corresponding pattern method with the RE string added as the first argument, and still return either None or a match object instance.

>>> print(re.match(r'From\s+', 'Fromage amk'))
None
>>> re.match(r'From\s+', 'From amk Thu May 14 19:12:10 1998')
<re.Match object; span=(0, 5), match='From '>

Under the hood, these functions simply create a pattern object for you and call the appropriate method on it. They also store the compiled object in a cache, so future calls using the same RE won’t need to parse the pattern again and again.

Should you use these module-level functions, or should you get the pattern and call its methods yourself? If you’re accessing a regex within a loop, pre-compiling it will save a few function calls. Outside of loops, there’s not much difference thanks to the internal cache.

Compilation Flags

Compilation flags let you modify some aspects of how regular expressions work. Flags are available in the re module under two names, a long name such as IGNORECASE and a short, one-letter form such as I. (If you’re familiar with Perl’s pattern modifiers, the one-letter forms use the same letters; the short form of re.VERBOSE is re.X, for example.) Multiple flags can be specified by bitwise OR-ing them; re.I | re.M sets both the I and M flags, for example.

Here’s a table of the available flags, followed by a more detailed explanation of each one.

Flag

Meaning

ASCII, A

Makes several escapes like \w, \b, \s and \d match only on ASCII characters with the respective property.

DOTALL, S

Make . match any character, including newlines.

IGNORECASE, I

Do case-insensitive matches.

LOCALE, L

Do a locale-aware match.

MULTILINE, M

Multi-line matching, affecting ^ and $.

VERBOSE, X (for ‘extended’)

Enable verbose REs, which can be organized more cleanly and understandably.

I

IGNORECASE

Perform case-insensitive matching; character class and literal strings will match letters by ignoring case. For example, [A-Z] will match lowercase letters, too. Full Unicode matching also works unless the ASCII flag is used to disable non-ASCII matches. When the Unicode patterns [a-z] or [A-Z] are used in combination with the IGNORECASE flag, they will match the 52 ASCII letters and 4 additional non-ASCII letters: ‘İ’ (U+0130, Latin capital letter I with dot above), ‘ı’ (U+0131, Latin small letter dotless i), ‘ſ’ (U+017F, Latin small letter long s) and ‘K’ (U+212A, Kelvin sign). Spam will match 'Spam', 'spam', 'spAM', or 'ſpam' (the latter is matched only in Unicode mode). This lowercasing doesn’t take the current locale into account; it will if you also set the LOCALE flag.

L

LOCALE

Make \w, \W, \b, \B and case-insensitive matching dependent on the current locale instead of the Unicode database.

Locales are a feature of the C library intended to help in writing programs that take account of language differences. For example, if you’re processing encoded French text, you’d want to be able to write \w+ to match words, but \w only matches the character class [A-Za-z] in bytes patterns; it won’t match bytes corresponding to é or ç. If your system is configured properly and a French locale is selected, certain C functions will tell the program that the byte corresponding to é should also be considered a letter. Setting the LOCALE flag when compiling a regular expression will cause the resulting compiled object to use these C functions for \w; this is slower, but also enables \w+ to match French words as you’d expect. The use of this flag is discouraged in Python 3 as the locale mechanism is very unreliable, it only handles one “culture” at a time, and it only works with 8-bit locales. Unicode matching is already enabled by default in Python 3 for Unicode (str) patterns, and it is able to handle different locales/languages.

M

MULTILINE

(^ and $ haven’t been explained yet; they’ll be introduced in section More Metacharacters.)

Usually ^ matches only at the beginning of the string, and $ matches only at the end of the string and immediately before the newline (if any) at the end of the string. When this flag is specified, ^ matches at the beginning of the string and at the beginning of each line within the string, immediately following each newline. Similarly, the $ metacharacter matches either at the end of the string and at the end of each line (immediately preceding each newline).

S

DOTALL

Makes the '.' special character match any character at all, including a newline; without this flag, '.' will match anything except a newline.

A

ASCII

Make \w, \W, \b, \B, \s and \S perform ASCII-only matching instead of full Unicode matching. This is only meaningful for Unicode patterns, and is ignored for byte patterns.

X

VERBOSE

This flag allows you to write regular expressions that are more readable by granting you more flexibility in how you can format them. When this flag has been specified, whitespace within the RE string is ignored, except when the whitespace is in a character class or preceded by an unescaped backslash; this lets you organize and indent the RE more clearly. This flag also lets you put comments within a RE that will be ignored by the engine; comments are marked by a '#' that’s neither in a character class or preceded by an unescaped backslash.

For example, here’s a RE that uses re.VERBOSE; see how much easier it is to read?

charref = re.compile(r"""
 &[#]                # Start of a numeric entity reference
 (
     0[0-7]+         # Octal form
   | [0-9]+          # Decimal form
   | x[0-9a-fA-F]+   # Hexadecimal form
 )
 ;                   # Trailing semicolon
""", re.VERBOSE)

Without the verbose setting, the RE would look like this:

charref = re.compile("&#(0[0-7]+"
                     "|[0-9]+"
                     "|x[0-9a-fA-F]+);")

In the above example, Python’s automatic concatenation of string literals has been used to break up the RE into smaller pieces, but it’s still more difficult to understand than the version using re.VERBOSE.

More Pattern Power

So far we’ve only covered a part of the features of regular expressions. In this section, we’ll cover some new metacharacters, and how to use groups to retrieve portions of the text that was matched.

More Metacharacters

There are some metacharacters that we haven’t covered yet. Most of them will be covered in this section.

Some of the remaining metacharacters to be discussed are zero-width assertions. They don’t cause the engine to advance through the string; instead, they consume no characters at all, and simply succeed or fail. For example, \b is an assertion that the current position is located at a word boundary; the position isn’t changed by the \b at all. This means that zero-width assertions should never be repeated, because if they match once at a given location, they can obviously be matched an infinite number of times.

|

Alternation, or the “or” operator. If A and B are regular expressions, A|B will match any string that matches either A or B. | has very low precedence in order to make it work reasonably when you’re alternating multi-character strings. Crow|Servo will match either 'Crow' or 'Servo', not 'Cro', a 'w' or an 'S', and 'ervo'.

To match a literal '|', use \|, or enclose it inside a character class, as in [|].

^

Matches at the beginning of lines. Unless the MULTILINE flag has been set, this will only match at the beginning of the string. In MULTILINE mode, this also matches immediately after each newline within the string.

For example, if you wish to match the word From only at the beginning of a line, the RE to use is ^From.

>>> print(re.search('^From', 'From Here to Eternity'))
<re.Match object; span=(0, 4), match='From'>
>>> print(re.search('^From', 'Reciting From Memory'))
None

To match a literal '^', use \^.

$

Matches at the end of a line, which is defined as either the end of the string, or any location followed by a newline character.

>>> print(re.search('}$', '{block}'))
<re.Match object; span=(6, 7), match='}'>
>>> print(re.search('}$', '{block} '))
None
>>> print(re.search('}$', '{block}\n'))
<re.Match object; span=(6, 7), match='}'>

To match a literal '$', use \$ or enclose it inside a character class, as in [$].

\A

Matches only at the start of the string. When not in MULTILINE mode, \A and ^ are effectively the same. In MULTILINE mode, they’re different: \A still matches only at the beginning of the string, but ^ may match at any location inside the string that follows a newline character.

\Z

Matches only at the end of the string.

\b

Word boundary. This is a zero-width assertion that matches only at the beginning or end of a word. A word is defined as a sequence of alphanumeric characters, so the end of a word is indicated by whitespace or a non-alphanumeric character.

The following example matches class only when it’s a complete word; it won’t match when it’s contained inside another word.

>>> p = re.compile(r'\bclass\b')
>>> print(p.search('no class at all'))
<re.Match object; span=(3, 8), match='class'>
>>> print(p.search('the declassified algorithm'))
None
>>> print(p.search('one subclass is'))
None

There are two subtleties you should remember when using this special sequence. First, this is the worst collision between Python’s string literals and regular expression sequences. In Python’s string literals, \b is the backspace character, ASCII value 8. If you’re not using raw strings, then Python will convert the \b to a backspace, and your RE won’t match as you expect it to. The following example looks the same as our previous RE, but omits the 'r' in front of the RE string.

>>> p = re.compile('\bclass\b')
>>> print(p.search('no class at all'))
None
>>> print(p.search('\b' + 'class' + '\b'))
<re.Match object; span=(0, 7), match='\x08class\x08'>

Second, inside a character class, where there’s no use for this assertion, \b represents the backspace character, for compatibility with Python’s string literals.

\B

Another zero-width assertion, this is the opposite of \b, only matching when the current position is not at a word boundary.

Grouping

Frequently you need to obtain more information than just whether the RE matched or not. Regular expressions are often used to dissect strings by writing a RE divided into several subgroups which match different components of interest. For example, an RFC-822 header line is divided into a header name and a value, separated by a ':', like this:

From: author@example.com
User-Agent: Thunderbird 1.5.0.9 (X11/20061227)
MIME-Version: 1.0
To: editor@example.com

This can be handled by writing a regular expression which matches an entire header line, and has one group which matches the header name, and another group which matches the header’s value.

Groups are marked by the '(', ')' metacharacters. '(' and ')' have much the same meaning as they do in mathematical expressions; they group together the expressions contained inside them, and you can repeat the contents of a group with a repeating qualifier, such as *, +, ?, or {m,n}. For example, (ab)* will match zero or more repetitions of ab.

>>> p = re.compile('(ab)*')
>>> print(p.match('ababababab').span())
(0, 10)

Groups indicated with '(', ')' also capture the starting and ending index of the text that they match; this can be retrieved by passing an argument to group(), start(), end(), and span(). Groups are numbered starting with 0. Group 0 is always present; it’s the whole RE, so match object methods all have group 0 as their default argument. Later we’ll see how to express groups that don’t capture the span of text that they match.

>>> p = re.compile('(a)b')
>>> m = p.match('ab')
>>> m.group()
'ab'
>>> m.group(0)
'ab'

Subgroups are numbered from left to right, from 1 upward. Groups can be nested; to determine the number, just count the opening parenthesis characters, going from left to right.

>>> p = re.compile('(a(b)c)d')
>>> m = p.match('abcd')
>>> m.group(0)
'abcd'
>>> m.group(1)
'abc'
>>> m.group(2)
'b'

group() can be passed multiple group numbers at a time, in which case it will return a tuple containing the corresponding values for those groups.

>>> m.group(2,1,2)
('b', 'abc', 'b')

The groups() method returns a tuple containing the strings for all the subgroups, from 1 up to however many there are.

>>> m.groups()
('abc', 'b')

Backreferences in a pattern allow you to specify that the contents of an earlier capturing group must also be found at the current location in the string. For example, \1 will succeed if the exact contents of group 1 can be found at the current position, and fails otherwise. Remember that Python’s string literals also use a backslash followed by numbers to allow including arbitrary characters in a string, so be sure to use a raw string when incorporating backreferences in a RE.

For example, the following RE detects doubled words in a string.

>>> p = re.compile(r'\b(\w+)\s+\1\b')
>>> p.search('Paris in the the spring').group()
'the the'

Backreferences like this aren’t often useful for just searching through a string — there are few text formats which repeat data in this way — but you’ll soon find out that they’re very useful when performing string substitutions.

Non-capturing and Named Groups

Elaborate REs may use many groups, both to capture substrings of interest, and to group and structure the RE itself. In complex REs, it becomes difficult to keep track of the group numbers. There are two features which help with this problem. Both of them use a common syntax for regular expression extensions, so we’ll look at that first.

Perl 5 is well known for its powerful additions to standard regular expressions. For these new features the Perl developers couldn’t choose new single-keystroke metacharacters or new special sequences beginning with \ without making Perl’s regular expressions confusingly different from standard REs. If they chose & as a new metacharacter, for example, old expressions would be assuming that & was a regular character and wouldn’t have escaped it by writing \& or [&].

The solution chosen by the Perl developers was to use (?...) as the extension syntax. ? immediately after a parenthesis was a syntax error because the ? would have nothing to repeat, so this didn’t introduce any compatibility problems. The characters immediately after the ? indicate what extension is being used, so (?=foo) is one thing (a positive lookahead assertion) and (?:foo) is something else (a non-capturing group containing the subexpression foo).

Python supports several of Perl’s extensions and adds an extension syntax to Perl’s extension syntax. If the first character after the question mark is a P, you know that it’s an extension that’s specific to Python.

Now that we’ve looked at the general extension syntax, we can return to the features that simplify working with groups in complex REs.

Sometimes you’ll want to use a group to denote a part of a regular expression, but aren’t interested in retrieving the group’s contents. You can make this fact explicit by using a non-capturing group: (?:...), where you can replace the ... with any other regular expression.

>>> m = re.match("([abc])+", "abc")
>>> m.groups()
('c',)
>>> m = re.match("(?:[abc])+", "abc")
>>> m.groups()
()

Except for the fact that you can’t retrieve the contents of what the group matched, a non-capturing group behaves exactly the same as a capturing group; you can put anything inside it, repeat it with a repetition metacharacter such as *, and nest it within other groups (capturing or non-capturing). (?:...) is particularly useful when modifying an existing pattern, since you can add new groups without changing how all the other groups are numbered. It should be mentioned that there’s no performance difference in searching between capturing and non-capturing groups; neither form is any faster than the other.

A more significant feature is named groups: instead of referring to them by numbers, groups can be referenced by a name.

The syntax for a named group is one of the Python-specific extensions: (?P<name>...). name is, obviously, the name of the group. Named groups behave exactly like capturing groups, and additionally associate a name with a group. The match object methods that deal with capturing groups all accept either integers that refer to the group by number or strings that contain the desired group’s name. Named groups are still given numbers, so you can retrieve information about a group in two ways:

>>> p = re.compile(r'(?P<word>\b\w+\b)')
>>> m = p.search( '(((( Lots of punctuation )))' )
>>> m.group('word')
'Lots'
>>> m.group(1)
'Lots'

Named groups are handy because they let you use easily-remembered names, instead of having to remember numbers. Here’s an example RE from the imaplib module:

InternalDate = re.compile(r'INTERNALDATE "'
        r'(?P<day>[ 123][0-9])-(?P<mon>[A-Z][a-z][a-z])-'
        r'(?P<year>[0-9][0-9][0-9][0-9])'
        r' (?P<hour>[0-9][0-9]):(?P<min>[0-9][0-9]):(?P<sec>[0-9][0-9])'
        r' (?P<zonen>[-+])(?P<zoneh>[0-9][0-9])(?P<zonem>[0-9][0-9])'
        r'"')

It’s obviously much easier to retrieve m.group('zonem'), instead of having to remember to retrieve group 9.

The syntax for backreferences in an expression such as (...)\1 refers to the number of the group. There’s naturally a variant that uses the group name instead of the number. This is another Python extension: (?P=name) indicates that the contents of the group called name should again be matched at the current point. The regular expression for finding doubled words, \b(\w+)\s+\1\b can also be written as \b(?P<word>\w+)\s+(?P=word)\b:

>>> p = re.compile(r'\b(?P<word>\w+)\s+(?P=word)\b')
>>> p.search('Paris in the the spring').group()
'the the'

Lookahead Assertions

Another zero-width assertion is the lookahead assertion. Lookahead assertions are available in both positive and negative form, and look like this:

(?=...)

Positive lookahead assertion. This succeeds if the contained regular expression, represented here by ..., successfully matches at the current location, and fails otherwise. But, once the contained expression has been tried, the matching engine doesn’t advance at all; the rest of the pattern is tried right where the assertion started.

(?!...)

Negative lookahead assertion. This is the opposite of the positive assertion; it succeeds if the contained expression doesn’t match at the current position in the string.

To make this concrete, let’s look at a case where a lookahead is useful. Consider a simple pattern to match a filename and split it apart into a base name and an extension, separated by a .. For example, in news.rc, news is the base name, and rc is the filename’s extension.

The pattern to match this is quite simple:

.*[.].*$

Notice that the . needs to be treated specially because it’s a metacharacter, so it’s inside a character class to only match that specific character. Also notice the trailing $; this is added to ensure that all the rest of the string must be included in the extension. This regular expression matches foo.bar and autoexec.bat and sendmail.cf and printers.conf.

Now, consider complicating the problem a bit; what if you want to match filenames where the extension is not bat? Some incorrect attempts:

.*[.][^b].*$ The first attempt above tries to exclude bat by requiring that the first character of the extension is not a b. This is wrong, because the pattern also doesn’t match foo.bar.

.*[.]([^b]..|.[^a].|..[^t])$

The expression gets messier when you try to patch up the first solution by requiring one of the following cases to match: the first character of the extension isn’t b; the second character isn’t a; or the third character isn’t t. This accepts foo.bar and rejects autoexec.bat, but it requires a three-letter extension and won’t accept a filename with a two-letter extension such as sendmail.cf. We’ll complicate the pattern again in an effort to fix it.

.*[.]([^b].?.?|.[^a]?.?|..?[^t]?)$

In the third attempt, the second and third letters are all made optional in order to allow matching extensions shorter than three characters, such as sendmail.cf.

The pattern’s getting really complicated now, which makes it hard to read and understand. Worse, if the problem changes and you want to exclude both bat and exe as extensions, the pattern would get even more complicated and confusing.

A negative lookahead cuts through all this confusion:

.*[.](?!bat$)[^.]*$ The negative lookahead means: if the expression bat doesn’t match at this point, try the rest of the pattern; if bat$ does match, the whole pattern will fail. The trailing $ is required to ensure that something like sample.batch, where the extension only starts with bat, will be allowed. The [^.]* makes sure that the pattern works when there are multiple dots in the filename.

Excluding another filename extension is now easy; simply add it as an alternative inside the assertion. The following pattern excludes filenames that end in either bat or exe:

.*[.](?!bat$|exe$)[^.]*$

Modifying Strings

Up to this point, we’ve simply performed searches against a static string. Regular expressions are also commonly used to modify strings in various ways, using the following pattern methods:

Method/Attribute

Purpose

split()

Split the string into a list, splitting it wherever the RE matches

sub()

Find all substrings where the RE matches, and replace them with a different string

subn()

Does the same thing as sub(), but returns the new string and the number of replacements

Splitting Strings

The split() method of a pattern splits a string apart wherever the RE matches, returning a list of the pieces. It’s similar to the split() method of strings but provides much more generality in the delimiters that you can split by; string split() only supports splitting by whitespace or by a fixed string. As you’d expect, there’s a module-level re.split() function, too.

.split(string[, maxsplit=0])

Split string by the matches of the regular expression. If capturing parentheses are used in the RE, then their contents will also be returned as part of the resulting list. If maxsplit is nonzero, at most maxsplit splits are performed.

You can limit the number of splits made, by passing a value for maxsplit. When maxsplit is nonzero, at most maxsplit splits will be made, and the remainder of the string is returned as the final element of the list. In the following example, the delimiter is any sequence of non-alphanumeric characters.

>>> p = re.compile(r'\W+')
>>> p.split('This is a test, short and sweet, of split().')
['This', 'is', 'a', 'test', 'short', 'and', 'sweet', 'of', 'split', '']
>>> p.split('This is a test, short and sweet, of split().', 3)
['This', 'is', 'a', 'test, short and sweet, of split().']

Sometimes you’re not only interested in what the text between delimiters is, but also need to know what the delimiter was. If capturing parentheses are used in the RE, then their values are also returned as part of the list. Compare the following calls:

>>> p = re.compile(r'\W+')
>>> p2 = re.compile(r'(\W+)')
>>> p.split('This... is a test.')
['This', 'is', 'a', 'test', '']
>>> p2.split('This... is a test.')
['This', '... ', 'is', ' ', 'a', ' ', 'test', '.', '']

The module-level function re.split() adds the RE to be used as the first argument, but is otherwise the same.

>>> re.split(r'[\W]+', 'Words, words, words.')
['Words', 'words', 'words', '']
>>> re.split(r'([\W]+)', 'Words, words, words.')
['Words', ', ', 'words', ', ', 'words', '.', '']
>>> re.split(r'[\W]+', 'Words, words, words.', 1)
['Words', 'words, words.']

Search and Replace

Another common task is to find all the matches for a pattern, and replace them with a different string. The sub() method takes a replacement value, which can be either a string or a function, and the string to be processed.

.sub(replacement, string[, count=0])

Returns the string obtained by replacing the leftmost non-overlapping occurrences of the RE in string by the replacement replacement. If the pattern isn’t found, string is returned unchanged.

The optional argument count is the maximum number of pattern occurrences to be replaced; count must be a non-negative integer. The default value of 0 means to replace all occurrences.

Here’s a simple example of using the sub() method. It replaces colour names with the word colour:

>>> p = re.compile('(blue|white|red)')
>>> p.sub('colour', 'blue socks and red shoes')
'colour socks and colour shoes'
>>> p.sub('colour', 'blue socks and red shoes', count=1)
'colour socks and red shoes'

The subn() method does the same work, but returns a 2-tuple containing the new string value and the number of replacements that were performed:

>>> p = re.compile('(blue|white|red)')
>>> p.subn('colour', 'blue socks and red shoes')
('colour socks and colour shoes', 2)
>>> p.subn('colour', 'no colours at all')
('no colours at all', 0)

Empty matches are replaced only when they’re not adjacent to a previous empty match.

>>> p = re.compile('x*')
>>> p.sub('-', 'abxd')
'-a-b--d-'

If replacement is a string, any backslash escapes in it are processed. That is, \n is converted to a single newline character, \r is converted to a carriage return, and so forth. Unknown escapes such as \& are left alone. Backreferences, such as \6, are replaced with the substring matched by the corresponding group in the RE. This lets you incorporate portions of the original text in the resulting replacement string.

This example matches the word section followed by a string enclosed in {, }, and changes section to subsection:

>>> p = re.compile('section{ ( [^}]* ) }', re.VERBOSE)
>>> p.sub(r'subsection{\1}','section{First} section{second}')
'subsection{First} subsection{second}'

There’s also a syntax for referring to named groups as defined by the (?P<name>...) syntax. \g<name> will use the substring matched by the group named name, and \g<number> uses the corresponding group number. \g<2> is therefore equivalent to \2, but isn’t ambiguous in a replacement string such as \g<2>0. (\20 would be interpreted as a reference to group 20, not a reference to group 2 followed by the literal character '0'.) The following substitutions are all equivalent, but use all three variations of the replacement string.

>>> p = re.compile('section{ (?P<name> [^}]* ) }', re.VERBOSE)
>>> p.sub(r'subsection{\1}','section{First}')
'subsection{First}'
>>> p.sub(r'subsection{\g<1>}','section{First}')
'subsection{First}'
>>> p.sub(r'subsection{\g<name>}','section{First}')
'subsection{First}'

replacement can also be a function, which gives you even more control. If replacement is a function, the function is called for every non-overlapping occurrence of pattern. On each call, the function is passed a match object argument for the match and can use this information to compute the desired replacement string and return it.

In the following example, the replacement function translates decimals into hexadecimal:

>>> def hexrepl(match):
...     "Return the hex string for a decimal number"
...     value = int(match.group())
...     return hex(value)
...
>>> p = re.compile(r'\d+')
>>> p.sub(hexrepl, 'Call 65490 for printing, 49152 for user code.')
'Call 0xffd2 for printing, 0xc000 for user code.'

When using the module-level re.sub() function, the pattern is passed as the first argument. The pattern may be provided as an object or as a string; if you need to specify regular expression flags, you must either use a pattern object as the first parameter, or use embedded modifiers in the pattern string, e.g. sub("(?i)b+", "x", "bbbb BBBB") returns 'x x'.

Common Problems

Regular expressions are a powerful tool for some applications, but in some ways their behaviour isn’t intuitive and at times they don’t behave the way you may expect them to. This section will point out some of the most common pitfalls.

Use String Methods

Sometimes using the re module is a mistake. If you’re matching a fixed string, or a single character class, and you’re not using any re features such as the IGNORECASE flag, then the full power of regular expressions may not be required. Strings have several methods for performing operations with fixed strings and they’re usually much faster, because the implementation is a single small C loop that’s been optimized for the purpose, instead of the large, more generalized regular expression engine.

One example might be replacing a single fixed string with another one; for example, you might replace word with deed. re.sub() seems like the function to use for this, but consider the replace() method. Note that replace() will also replace word inside words, turning swordfish into sdeedfish, but the naive RE word would have done that, too. (To avoid performing the substitution on parts of words, the pattern would have to be \bword\b, in order to require that word have a word boundary on either side. This takes the job beyond replace()’s abilities.)

Another common task is deleting every occurrence of a single character from a string or replacing it with another single character. You might do this with something like re.sub('\n', ' ', S), but translate() is capable of doing both tasks and will be faster than any regular expression operation can be.

In short, before turning to the re module, consider whether your problem can be solved with a faster and simpler string method.

match() versus search()

The match() function only checks if the RE matches at the beginning of the string while search() will scan forward through the string for a match. It’s important to keep this distinction in mind. Remember, match() will only report a successful match which will start at 0; if the match wouldn’t start at zero, match() will not report it.

>>> print(re.match('super', 'superstition').span())
(0, 5)
>>> print(re.match('super', 'insuperable'))
None

On the other hand, search() will scan forward through the string, reporting the first match it finds.

>>> print(re.search('super', 'superstition').span())
(0, 5)
>>> print(re.search('super', 'insuperable').span())
(2, 7)

Sometimes you’ll be tempted to keep using re.match(), and just add .* to the front of your RE. Resist this temptation and use re.search() instead. The regular expression compiler does some analysis of REs in order to speed up the process of looking for a match. One such analysis figures out what the first character of a match must be; for example, a pattern starting with Crow must match starting with a 'C'. The analysis lets the engine quickly scan through the string looking for the starting character, only trying the full match if a 'C' is found.

Adding .* defeats this optimization, requiring scanning to the end of the string and then backtracking to find a match for the rest of the RE. Use re.search() instead.

Greedy versus Non-Greedy

When repeating a regular expression, as in a*, the resulting action is to consume as much of the pattern as possible. This fact often bites you when you’re trying to match a pair of balanced delimiters, such as the angle brackets surrounding an HTML tag. The naive pattern for matching a single HTML tag doesn’t work because of the greedy nature of .*.

>>> s = '<html><head><title>Title</title>'
>>> len(s)
32
>>> print(re.match('<.*>', s).span())
(0, 32)
>>> print(re.match('<.*>', s).group())
<html><head><title>Title</title>

The RE matches the '<' in '<html>', and the .* consumes the rest of the string. There’s still more left in the RE, though, and the > can’t match at the end of the string, so the regular expression engine has to backtrack character by character until it finds a match for the >. The final match extends from the '<' in '<html>' to the '>' in '</title>', which isn’t what you want.

In this case, the solution is to use the non-greedy qualifiers *?, +?, ??, or {m,n}?, which match as little text as possible. In the above example, the '>' is tried immediately after the first '<' matches, and when it fails, the engine advances a character at a time, retrying the '>' at every step. This produces just the right result:

>>> print(re.match('<.*?>', s).group())
<html>

(Note that parsing HTML or XML with regular expressions is painful. Quick-and-dirty patterns will handle common cases, but HTML and XML have special cases that will break the obvious regular expression; by the time you’ve written a regular expression that handles all of the possible cases, the patterns will be very complicated. Use an HTML or XML parser module for such tasks.)

Using re.VERBOSE

By now you’ve probably noticed that regular expressions are a very compact notation, but they’re not terribly readable. REs of moderate complexity can become lengthy collections of backslashes, parentheses, and metacharacters, making them difficult to read and understand.

For such REs, specifying the re.VERBOSE flag when compiling the regular expression can be helpful, because it allows you to format the regular expression more clearly.

The re.VERBOSE flag has several effects. Whitespace in the regular expression that isn’t inside a character class is ignored. This means that an expression such as dog | cat is equivalent to the less readable dog|cat, but [a b] will still match the characters 'a', 'b', or a space. In addition, you can also put comments inside a RE; comments extend from a # character to the next newline. When used with triple-quoted strings, this enables REs to be formatted more neatly:

pat = re.compile(r"""
 \s*                 # Skip leading whitespace
 (?P<header>[^:]+)   # Header name
 \s* :               # Whitespace, and a colon
 (?P<value>.*?)      # The header's value -- *? used to
                     # lose the following trailing whitespace
 \s*$                # Trailing whitespace to end-of-line
""", re.VERBOSE)

This is far more readable than:

pat = re.compile(r"\s*(?P<header>[^:]+)\s*:(?P<value>.*?)\s*$")

Feedback

Regular expressions are a complicated topic. Did this document help you understand them? Were there parts that were unclear, or Problems you encountered that weren’t covered here? If so, please send suggestions for improvements to the author.

The most complete book on regular expressions is almost certainly Jeffrey Friedl’s Mastering Regular Expressions, published by O’Reilly. Unfortunately, it exclusively concentrates on Perl and Java’s flavours of regular expressions, and doesn’t contain any Python material at all, so it won’t be useful as a reference for programming in Python. (The first edition covered Python’s now-removed regex module, which won’t help you much.) Consider checking it out from your library.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 HOWTO »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 HOWTO »

|

소켓 프로그래밍 HOWTO

저자

Gordon McMillan

개요

소켓은 거의 모든 곳에서 사용되지만, 가장 심하게 오해된 기술 중 하나입니다. 이것은 10,000피트 상공에서 본 소켓 개요입니다. 진짜 자습서는 아닙니다 - 여러분은 여전히 작동하도록 만들기 위해 해야 할 일이 있습니다. 세부 사항을 다루지는 않습니다만 (그것 것들이 많이 있습니다), 그것들을 적당히 사용하기에 충분한 배경을 줄 수 있기를 바랍니다.

소켓

INET (즉, IPv4) 소켓에 관해서만 이야기할 것이지만, 사용 중인 소켓의 99% 이상을 차지합니다. 또한, STREAM (즉, TCP) 소켓에 관해서만 이야기할 것입니다 - 여러분이 무엇을 하고 있는지 정말로 알고 있지 (그럴 때 이 HOWTO는 필요 없습니다!) 않다면, 다른 모든 것보다 STREAM 소켓으로 더 나은 동작과 성능을 얻을 수 있습니다. 소켓이 무엇인지에 대한 수수께끼뿐만 아니라 블로킹과 비 블로킹 소켓으로 작업하는 방법에 대한 힌트를 분명하게 하려고 합니다. 하지만 블로킹 소켓에 관해 이야기하는 것으로 시작할 것입니다. 비 블로킹 소켓을 다루기 전에 이것이 어떻게 작동하는지 알아야 합니다.

이러한 것들을 이해하는데 어려움을 주는 한 부분은 문맥에 따라 “소켓”이 여러 가지 미묘하게 다른 것을 뜻할 수 있다는 것입니다. 그래서 먼저, 대화의 끝점인 “클라이언트” 소켓과, 배전반 운영자와 비슷한 “서버” 소켓을 구별해 보겠습니다. 클라이언트 응용 프로그램(예를 들어, 여러분의 브라우저)은 “클라이언트” 소켓만 사용합니다; 이것이 대화하는 웹 서버는 “서버” 소켓과 “클라이언트” 소켓을 모두 사용합니다.

역사

IPC의 다양한 형태 중에서, 소켓이 가장 많이 사용됩니다. 특정 플랫폼에서 다른 형태의 IPC가 더 빠를 가능성이 있지만, 크로스 플랫폼 통신의 경우 소켓이 유일한 게임의 법칙입니다.

BSD 계열 유닉스의 일부로 버클리에서 발명되었습니다. 인터넷과 함께 산불처럼 퍼졌습니다. 좋은 의미에서 — INET과 소켓의 조합은 전 세계의 임의의 기계와 믿을 수 없을 만큼 쉽게 대화를 나눌 수 있도록 합니다 (적어도 다른 체계와 비교할 때).

소켓 만들기

대충 말하면, 이 페이지로 연결되는 링크를 클릭하면 브라우저가 다음과 같은 작업을 수행합니다:

# create an INET, STREAMing socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# now connect to the web server on port 80 - the normal http port
s.connect(("www.python.org", 80))

connect가 완료되면, 소켓 s를 사용하여 페이지의 텍스트 요청을 보낼 수 있습니다. 같은 소켓으로 응답을 읽은 다음 파괴됩니다. 그렇습니다, 파괴됩니다. 클라이언트 소켓은 일반적으로 하나의 교환(또는 일련의 작은 교환 집합)에서만 사용됩니다.

웹 서버에서 일어나는 일은 좀 더 복잡합니다. 첫째, 웹 서버는 “서버 소켓”을 만듭니다:

# create an INET, STREAMing socket
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# bind the socket to a public host, and a well-known port
serversocket.bind((socket.gethostname(), 80))
# become a server socket
serversocket.listen(5)

알아 두어야 할 몇 가지 사항: 소켓을 외부 세계에서 볼 수 있도록 socket.gethostname()를 사용했습니다. s.bind(('localhost', 80)) 이나 s.bind(('127.0.0.1', 80))을 사용했다면, 여전히 “서버” 소켓을 가지게 되지만 같은 기계 내에서만 볼 수 있는 소켓을 갖게 됩니다. s.bind(('', 80))은 시스템에 있는 모든 주소로 소켓에 연결할 수 있음을 나타냅니다.

두 번째로 주목해야 할 점: 낮은 번호의 포트는 일반적으로 “잘 알려진” 서비스(HTTP, SNMP 등)를 위해 예약되어 있습니다. 연습 중이라면 적당히 높은 번호(4 자릿수)를 사용하십시오.

마지막으로, listen에 대한 인자는 외부 연결을 거부하기 전에 최대 5개의 연결 요청을 큐에 넣기를 원한다는 것을 소켓 라이브러리에 알립니다. 코드의 나머지 부분이 제대로 작성되었다면, 이것으로 충분합니다.

이제 우리는 포트 80에서 대기하는 “서버” 소켓을 가지고 있고, 웹 서버의 메인 루프를 입력할 수 있습니다:

while True:
    # accept connections from outside
    (clientsocket, address) = serversocket.accept()
    # now do something with the clientsocket
    # in this case, we'll pretend this is a threaded server
    ct = client_thread(clientsocket)
    ct.run()

실제로 이 루프가 작동할 수 있는 3가지 일반적인 방법이 있습니다 - clientsocket를 처리하기 위해 스레드로 보내거나, clientsocket를 처리할 새 프로세스를 만들거나, 비 블로킹 소켓을 사용하도록 이 응용 프로그램을 재구성하고, select를 사용하여 “서버” 소켓과 활성 clientsocket들 간에 다중화(multiplexing)합니다. 나중에 자세히 다룹니다. 지금 이해해야 할 중요한 점: 이것이 “서버” 소켓이 하는 전부입니다. 어떤 데이터도 보내지 않습니다. 어떤 데이터도 수신하지 않습니다. 단지 “클라이언트” 소켓을 생성할 뿐입니다. 각 clientsocket은 우리가 바인드 한 호스트와 포트로 connect()를 수행하는 다른 “클라이언트” 소켓에 대한 응답으로 만들어집니다. clientsocket를 만들자마자, 더 많은 연결을 기다리는 것으로 돌아갑니다. 두 개의 “클라이언트” 는 자유롭게 대화를 나눌 수 있습니다 - 그들은 대화를 끝낼 때 재활용되는 어떤 동적으로 할당된 포트를 사용합니다.

IPC

한 기계의 두 프로세스 간에 빠른 IPC가 필요하다면, 파이프나 공유 메모리를 살펴야 합니다. AF_INET 소켓을 사용하기로 했다면, “서버” 소켓을 'localhost'에 바인드 하십시오. 대부분 플랫폼에서, 이것은 네트워크 코드의 두어 개의 계층을 건너뛰는 지름길을 취할 것이고, 꽤 빨라집니다.

더 보기

multiprocessing은 교차 플랫폼 IPC를 고수준 API로 통합합니다.

소켓 사용하기

첫 번째로 주목해야 할 점은 웹 브라우저의 “클라이언트” 소켓과 웹 서버의 “클라이언트” 소켓은 같은 녀석이라는 것입니다. 즉, 이것은 “피어 투 피어(peer to peer)” 대화입니다. 또는 다른 방식으로 표현하면, 설계자로서, 대화를 위한 예절의 규칙이 무엇인지 결정해야 합니다. 일반적으로, connect하는 소켓이 요청이나 로그인을 보내 대화를 시작합니다. 그러나 이것은 설계상의 결정입니다 - 소켓의 규칙이 아닙니다.

이제 통신에 사용할 두 벌의 동사가 있습니다. send와 recv를 사용하거나, 클라이언트 소켓을 파일류로 변환한 후 read와 write를 사용할 수 있습니다. 후자는 자바가 소켓을 제공하는 방식입니다. flush를 소켓에 사용해야 한다고 경고하는 것 외에는, 여기에 대해서는 언급하지 않을 것입니다. 이것들은 버퍼 된 “파일”이며, 일반적인 실수는 어떤 것을 write하고는 응답을 read하는 것입니다. flush가 없으면, 요청이 여전히 출력 버퍼에 남아있을 수 있으므로 응답을 영원히 기다리게 될 수 있습니다.

이제 소켓의 주요 걸림돌에 도달했습니다 - send와 recv는 네트워크 버퍼에서 작동합니다. 이것들은 여러분이 넘겨준 모든 바이트를 처리하지 않을 수 있습니다, 그들의 주 관심사는 네트워크 버퍼를 처리하는 것이기 때문입니다. 일반적으로, 연관된 네트워크 버퍼가 채워지거나(send) 비워지면(recv) 반환됩니다. 그런 다음 처리 한 바이트 수를 알려줍니다. 메시지가 완전히 처리될 때까지 다시 호출하는 것은 여러분의 책임입니다.

recv가 0바이트를 반환하면, 다른 쪽이 연결을 닫았거나 닫고 있다는 뜻입니다. 이 연결에서 더는 데이터를 받지 못합니다. 영원히. 데이터를 성공적으로 보낼 수는 있습니다; 나중에 이것에 대해 더 이야기하겠습니다.

HTTP와 같은 프로토콜은 하나의 전송에만 소켓을 사용합니다. 클라이언트는 요청을 보낸 다음 응답을 읽습니다. 그게 전부입니다. 소켓은 버려집니다. 이는 클라이언트가 0바이트를 수신하여 응답의 끝을 감지할 수 있음을 뜻합니다.

그러나 추가 전송을 위해 소켓을 재사용할 계획이라면, 소켓에는 EOT 가 없다는 것을 알아야 합니다. 반복합니다: 소켓 send 또는 recv가 0바이트를 처리한 후 반환되면 연결이 끊어진 것입니다. 연결이 끊어진 것이 아니라면, 소켓은 (당분간) 읽을 것이 아무것도 없다는 것을 알려주지 않을 것이므로, recv에서 영원히 기다릴 수 있습니다. 이것에 대해 조금 더 생각해보면, 소켓의 근본적인 진실을 깨닫게 될 것입니다: 메시지는 고정 길이거나 (억), 구분자로 표시되거나 (어깨를 으쓱), 얼마나 긴지 표시하거나 (훨씬 낫다), 연결을 닫아서 끝내야 합니다. 선택은 전적으로 여러분의 것입니다, (하지만 어떤 방법이 다른 것보다 올바릅니다).

연결을 끝내기를 원하지 않는다고 가정하면, 가장 간단한 해결책은 고정 길이 메시지입니다:

class MySocket:
    """demonstration class only
      - coded for clarity, not efficiency
    """

    def __init__(self, sock=None):
        if sock is None:
            self.sock = socket.socket(
                            socket.AF_INET, socket.SOCK_STREAM)
        else:
            self.sock = sock

    def connect(self, host, port):
        self.sock.connect((host, port))

    def mysend(self, msg):
        totalsent = 0
        while totalsent < MSGLEN:
            sent = self.sock.send(msg[totalsent:])
            if sent == 0:
                raise RuntimeError("socket connection broken")
            totalsent = totalsent + sent

    def myreceive(self):
        chunks = []
        bytes_recd = 0
        while bytes_recd < MSGLEN:
            chunk = self.sock.recv(min(MSGLEN - bytes_recd, 2048))
            if chunk == b'':
                raise RuntimeError("socket connection broken")
            chunks.append(chunk)
            bytes_recd = bytes_recd + len(chunk)
        return b''.join(chunks)

여기에 있는 전송 코드는 거의 모든 메시지전달 체계에서 사용할 수 있습니다 - 파이썬에서는 문자열을 보내고 len()를 사용하여 길이를 파악할 수 있습니다 (\0 문자가 포함되어 있어도). 더 복잡한 부분은 대부분 수신 코드입니다. (그리고 C에서도, 메시지가 \0을 포함하고 있을 때 strlen을 사용할 수 없다는 점을 제외하면 몹시 나쁘지는 않습니다.)

가장 쉬운 개선은 메시지의 첫 번째 문자를 메시지 유형의 표시자로 만들고, 유형이 길이를 결정하도록 하는 것입니다. 이제 두 개의 recv가 있습니다 - (적어도) 첫 번째 문자를 가져와서 길이를 조회할 수 있도록 하는 첫 번째와 나머지를 얻는 루프로 구성된 두 번째입니다. 구분자로 가기로 했다면, 임의의 청크 크기(4096이나 8192는 네트워크 버퍼 크기와 종종 잘 맞습니다)로 수신하고 받은 내용에서 구분자를 검색하게 될 것입니다.

하나의 복잡성을 알아 두어야 합니다: 여러분의 대화형 프로토콜이 (어떤 종류의 응답 없이) 여러 메시지를 연속적으로 보내는 것을 허락하고, recv에 임의의 청크 크기를 전달하면 다음 메시지의 시작 부분도 함께 읽는 일이 일어날 수 있습니다. 필요할 때까지 보관해 두어야 합니다.

메시지의 길이를 앞에 붙이면 (5자리 숫자라고 합시다) 더 복잡해집니다, (믿거나 말거나) 한 번의 recv로 5문자를 모두 얻을 수 없을 수 있기 때문입니다. 연습 중에는 이런 일이 일어나지 않을 것입니다; 하지만 네트워크 로드가 높으면, 두 개의 recv 루프를 사용하지 않는 한 여러분의 코드는 금방 망가지게 됩니다 - 길이를 결정하는 첫 번째와 메시지의 데이터 부분을 가져오는 두 번째입니다. 지저분합니다. 또한 send가 항상 한 번에 모든 것을 처리하지 못하는 것을 발견하게 될 것입니다. 그리고 이 단락을 읽었음에도, 결국 당신은 이 문제에 당하게 될 것입니다!

공간을 절약하고, 여러분의 성격을 단련하고, (그리고 제 경쟁적 지위를 유지하기 위해) 이러한 향상은 독자를 위한 연습으로 남겨둡니다. 이제 정리해봅시다.

바이너리 데이터

바이너리 데이터를 소켓을 통해 전송하는 것은 완벽히 가능합니다. 가장 큰 문제점은 모든 기계가 바이너리 데이터에 대해 같은 형식을 사용하는 것은 아니라는 점입니다. 예를 들어, 모토로라 칩은 값 1을 갖는 16비트 정수를 16진수 바이트 00 01로 나타냅니다. 그러나 인텔과 DEC은 바이트 반전됩니다 - 같은 1은 01 00입니다. 소켓 라이브러리에는 16과 32비트 정수 변환을 위한 호출이 있습니다 - ntohl, htonl, ntohs, htons 여기서 “n”은 network을 의미하고, “h”는 host를 의미하고, “s”는 short를 의미하고, “l”은 long를 의미합니다. 네트워크 순서가 호스트 순서인 곳에서는 아무것도 수행하지 않지만, 바이트 반전되는 기계에서는 바이트가 적절히 스와프됩니다.

오늘날의 32비트 기계에서는, 바이너리 데이터의 ASCII 표현이 바이너리 표현보다 작은 경우가 많습니다. 놀라울 정도로 많은 경우에, 이 모든 long이 값 0이나 1을 갖기 때문입니다. 문자열 “0” 은 2바이트지만 바이너리는 4바이트입니다. 물론, 이것은 고정 길이 메시지에는 적합하지 않습니다. 결정, 결정.

연결 끊기

엄밀히 말하면, close를 사용하기 전에 소켓에 shutdown을 사용해야 합니다. shutdown은 반대편 소켓에 대한 권고입니다. 전달하는 인자에 따라, “더는 보내지 않을 것이지만, 여전히 들을 겁니다” 나 “듣고 있지 않습니다, 즐거웠습니다!”를 뜻할 수 있습니다. 그러나, 대부분 소켓 라이브러리는 프로그래머가 이 예절을 무시하는 방식으로 사용되었고 일반적으로 close가 shutdown(); close()와 같습니다. 따라서 대부분 상황에서 명시적인 shutdown은 필요하지 않습니다.

shutdown을 효과적으로 사용하는 한 가지 방법은 HTTP와 비슷한 교환에서입니다. 클라이언트는 요청을 보낸 다음 shutdown(1)을 수행합니다. 그러면 서버에 “이 클라이언트는 전송을 완료했지만 계속 받을 수 있습니다.”라고 말하게 됩니다. 서버는 0바이트의 수신으로 “EOF”를 감지할 수 있습니다. 요청을 완료했다고 가정할 수 있습니다. 서버가 응답을 보냅니다. send가 성공적으로 완료되면, 클라이언트는 여전히 수신 중입니다.

파이썬은 자동 shutdown을 한 걸음 더 나아가서, 소켓이 가비지 수집될 때 필요하면 자동으로 close를 수행한다고 말합니다. 그러나 이것에 의존하는 것은 매우 나쁜 습관입니다. close를 하지 않고 소켓이 사라지면, 반대편 끝은 여러분이 단지 느려지고 있다고 생각하면서 무한정 멈출 수 있습니다. 제발 완료되면 소켓을 close해 주세요.

소켓이 죽을 때

아마도 블로킹 소켓 사용에 관한 최악의 경우는 상대방이 (close를 수행하지 않고) 갑자기 다운되었을 때 일어나는 일입니다. 소켓이 멈출 수 있습니다. TCP는 신뢰성 있는 프로토콜이며, 연결을 포기하기 전에 아주 오랜 시간 동안 기다립니다. 스레드를 사용하고 있다면, 스레드 전체가 실질적으로 죽습니다. 이것에 대해 당신이 할 수 있는 일이 별로 없습니다. 블로킹 읽기를 수행하는 동안 록을 잡는 것과 같은 어리석은 짓을 하지 않는 한, 스레드는 자원을 많이 소비하지 않습니다. 스레드를 죽이려고 하지 마십시오 - 스레드가 프로세스보다 효율적인 부분적인 이유는 자원 재활용과 관련된 오버헤드를 회피한다는 것입니다. 즉, 스레드를 죽이면 전체 프로세스가 엉망이 될 가능성이 있습니다.

비 블로킹 소켓

앞의 내용을 이해했다면 소켓을 사용하는 방법에 대해 알아야 할 대부분을 이미 알고 있습니다. 거의 같은 방식으로 같은 호출을 계속 사용합니다. 여러분이 올바르게 사용하기만 한다면, 여러분의 앱을 거의 완전해질 겁니다.

In Python, you use socket.setblocking(0) to make it non-blocking. In C, it’s more complex, (for one thing, you’ll need to choose between the BSD flavor O_NONBLOCK and the almost indistinguishable POSIX flavor O_NDELAY, which is completely different from TCP_NODELAY), but it’s the exact same idea. You do this after creating the socket, but before using it. (Actually, if you’re nuts, you can switch back and forth.)

동작의 주요 차이점은 send, recv, connect 및 accept가 아무것도 하지 않고 반환될 수 있다는 것입니다. 여러분에게는 (물론) 많은 선택지가 있습니다. 반환 코드와 에러 코드를 확인하면서 일반적으로 자신을 미치게 만들 수 있습니다. 믿기지 않는다면, 한번 시도해보십시오. 여러분의 앱은 커지고, 버그가 많으며 CPU를 소진할 겁니다. 그러니 뇌사에 이르게 할 해결책은 건너뛰고 올바르게 해 봅시다.

select를 사용하십시오.

C에서, select 코딩은 상당히 복잡합니다. 파이썬에서, 이것은 달콤한 조각이지만, 여러분이 파이썬에서 select를 이해한다면 C에서도 거의 문제가 없을 만큼 C 버전에 아주 가깝습니다:

ready_to_read, ready_to_write, in_error = \
               select.select(
                  potential_readers,
                  potential_writers,
                  potential_errs,
                  timeout)

select로 세 개의 리스트를 전달합니다: 첫 번째는 읽으려는 모든 소켓을 포함합니다; 두 번째는 쓰려는 모든 소켓, 그리고 마지막으로 (보통 비어있는데) 에러를 검사하려는 소켓들입니다. 소켓이 둘 이상의 리스트에 들어갈 수 있음에 유의해야 합니다. select 호출은 블로킹이지만, 시간제한을 지정할 수 있습니다. 이것은 일반적으로 민감한 작업입니다 - 달리할 좋은 이유가 없다면 긴 제한 시간(가령 1분)을 주십시오.

반환 값으로, 세 개의 리스트를 얻게 됩니다. 실제로 읽을 수 있고, 쓸 수 있고, 에러가 있는 소켓이 들어있습니다. 이 리스트는 각기 여러분이 전달한 해당 목록의 부분집합(비어있는 것도 가능합니다)입니다.

소켓이 반환된 읽기 가능한 리스트에 있다면, 그 소켓에 대한 recv가 무언가를 반환하리라는 것을 알 수 있습니다. 쓰기 가능한 리스트도 마찬가지입니다. 무언가를 보낼 수 있습니다. 아마 당신이 원하는 전부는 아니겠지만, 무언가는 아무것도 아닌 것보다 낫습니다. (사실, 합리적으로 건강한 소켓은 쓰기 가능 상태로 반환될 것입니다 - 단지 네트워크 송신 버퍼 공간을 사용할 수 있음을 뜻합니다.)

“서버” 소켓이 있다면, potential_readers 리스트에 넣으십시오. 읽기 가능한 리스트에 등장하면, accept가 (거의 확실하게) 작동합니다. 다른 곳으로 connect하는 새 소켓을 만들었으면, potential_writers 리스트에 넣으십시오. 쓰기 가능한 리스트에 등장하면, 연결되었을 확률이 높습니다.

사실, select는 블로킹 소켓에서도 편리할 수 있습니다. 블록 할지 판단하는 한 가지 방법입니다 - 소켓은 버퍼에 무엇인가가 있으면 읽기 가능으로 반환됩니다. 그러나, 이것은 상대방이 완료했는지 아니면 단지 다른 일로 바쁜 것인지를 결정하는 문제에는 여전히 도움이 되지 않습니다.

이식성 경고: 유닉스에서, select는 소켓과 파일 모두에서 작동합니다. 윈도우에서 이런 시도를 하지 마십시오. 윈도우에서 select는 소켓에서만 작동합니다. 또한, C에서 많은 고급 소켓 옵션은 윈도우에서 다르게 동작함에 유의하십시오. 사실, 윈도우에서 저는 보통 소켓에 스레드를 사용합니다 (아주 잘 작동합니다).

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 HOWTO »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 HOWTO »

|

정렬 HOW TO

저자

Andrew Dalke와 Raymond Hettinger

배포

0.1

파이썬 리스트에는 리스트를 제자리에서(in-place) 수정하는 내장 list.sort() 메서드가 있습니다. 또한, 이터러블로부터 새로운 정렬된 리스트를 만드는 sorted() 내장 함수가 있습니다.

이 문서에서는, 파이썬을 사용하여 데이터를 정렬하는 다양한 기술을 살펴봅니다.

정렬 기초

간단한 오름차순 정렬은 매우 쉽습니다; 그저 sorted() 함수를 호출하면 됩니다. 새로운 정렬된 리스트를 반환합니다:

>>> sorted([5, 2, 3, 1, 4])
[1, 2, 3, 4, 5]

list.sort() 메서드를 사용할 수도 있습니다. 리스트를 제자리에서 수정합니다 (그리고 혼동을 피하고자 None을 반환합니다). 일반적으로 sorted()보다 덜 편리합니다 - 하지만 원래 목록이 필요하지 않다면, 이것이 약간 더 효율적입니다.

>>> a = [5, 2, 3, 1, 4]
>>> a.sort()
>>> a
[1, 2, 3, 4, 5]

또 다른 점은 list.sort() 메서드가 리스트에게만 정의된다는 것입니다. 이와 달리, sorted() 함수는 모든 이터러블을 받아들입니다.

>>> sorted({1: 'D', 2: 'B', 3: 'B', 4: 'E', 5: 'A'})
[1, 2, 3, 4, 5]

키 함수

list.sort()와 sorted()는 모두 비교하기 전에 각 리스트 요소에 대해 호출할 함수를 지정하는 key 매개 변수를 가지고 있습니다.

예를 들어, 다음은 대소 문자를 구분하지 않는 문자열 비교입니다:

>>> sorted("This is a test string from Andrew".split(), key=str.lower)
['a', 'Andrew', 'from', 'is', 'string', 'test', 'This']

key 매개 변수의 값은 단일 인자를 취하고 정렬 목적으로 사용할 키를 반환하는 함수여야 합니다. 키 함수가 각 입력 레코드에 대해 정확히 한 번 호출되기 때문에 이 기법은 빠릅니다.

일반적인 패턴은 객체의 인덱스 중 일부를 키로 사용하여 복잡한 객체를 정렬하는 것입니다. 예를 들어:

>>> student_tuples = [
...     ('john', 'A', 15),
...     ('jane', 'B', 12),
...     ('dave', 'B', 10),
... ]
>>> sorted(student_tuples, key=lambda student: student[2])   # sort by age
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

같은 기법이 이름있는 어트리뷰트를 갖는 객체에서도 작동합니다. 예를 들어:

>>> class Student:
...     def __init__(self, name, grade, age):
...         self.name = name
...         self.grade = grade
...         self.age = age
...     def __repr__(self):
...         return repr((self.name, self.grade, self.age))

>>> student_objects = [
...     Student('john', 'A', 15),
...     Student('jane', 'B', 12),
...     Student('dave', 'B', 10),
... ]
>>> sorted(student_objects, key=lambda student: student.age)   # sort by age
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

operator 모듈 함수

위에서 보여준 키 함수 패턴은 매우 일반적이므로, 파이썬은 액세스 함수를 더 쉽고 빠르게 만드는 편리 함수를 제공합니다. operator 모듈에는 itemgetter(), attrgetter() 및 methodcaller() 함수가 있습니다.

이러한 함수를 사용하면, 위의 예제가 더 간단 해지고 빨라집니다:

>>> from operator import itemgetter, attrgetter

>>> sorted(student_tuples, key=itemgetter(2))
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

>>> sorted(student_objects, key=attrgetter('age'))
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

operator 모듈 함수는 다중 수준의 정렬을 허용합니다. 예를 들어, 먼저 grade로 정렬한 다음 age로 정렬하려면, 이렇게 합니다:

>>> sorted(student_tuples, key=itemgetter(1,2))
[('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)]

>>> sorted(student_objects, key=attrgetter('grade', 'age'))
[('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)]

오름차순과 내림차순

list.sort()와 sorted()는 모두 불리언 값을 갖는 reverse 매개 변수를 받아들입니다. 내림차순 정렬을 지정하는 데 사용됩니다. 예를 들어, 학생 데이터를 역 age 순서로 얻으려면, 이렇게 합니다:

>>> sorted(student_tuples, key=itemgetter(2), reverse=True)
[('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]

>>> sorted(student_objects, key=attrgetter('age'), reverse=True)
[('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]

정렬 안정성과 복잡한 정렬

정렬은 안정적 [https://en.wikipedia.org/wiki/Sorting_algorithm#Stability]임이 보장됩니다. 즉, 여러 레코드가 같은 키를 가질 때, 원래의 순서가 유지됩니다.

>>> data = [('red', 1), ('blue', 1), ('red', 2), ('blue', 2)]
>>> sorted(data, key=itemgetter(0))
[('blue', 1), ('blue', 2), ('red', 1), ('red', 2)]

blue에 대한 두 레코드가 원래 순서를 유지해서 ('blue', 1)이 ('blue', 2)보다 앞에 나옴이 보장됨에 유의하십시오.

이 멋진 속성은 일련의 정렬 단계로 복잡한 정렬을 만들 수 있도록 합니다. 예를 들어, 학생 데이터를 grade의 내림차순으로 정렬한 다음, age의 오름차순으로 정렬하려면, 먼저 age 정렬을 수행한 다음 grade를 사용하여 다시 정렬합니다:

>>> s = sorted(student_objects, key=attrgetter('age'))     # sort on secondary key
>>> sorted(s, key=attrgetter('grade'), reverse=True)       # now sort on primary key, descending
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

파이썬에서 사용된 Timsort [https://en.wikipedia.org/wiki/Timsort] 알고리즘은 데이터 집합에 이미 존재하는 순서를 활용할 수 있으므로 효율적으로 여러 번의 정렬을 수행합니다.

장식-정렬-복원을 사용하는 낡은 방법

이 관용구는 그것의 세 단계를 따라 장식-정렬-복원(Decorate-Sort-Undecorate)이라고 합니다:

첫째, 초기 리스트가 정렬 순서를 제어하는 새로운 값으로 장식됩니다.

둘째, 장식된 리스트를 정렬합니다.

마지막으로, 장식을 제거하여, 새 순서로 초깃값만 포함하는 리스트를 만듭니다.

예를 들어, DSU 방식을 사용하여 grade로 학생 데이터를 정렬하려면 다음과 같이 합니다:

>>> decorated = [(student.grade, i, student) for i, student in enumerate(student_objects)]
>>> decorated.sort()
>>> [student for grade, i, student in decorated]               # undecorate
[('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]

이 관용구는 튜플이 사전식으로 비교되기 때문에 작동합니다; 첫 번째 항목이 비교됩니다; 그들이 같으면 두 번째 항목이 비교되고, 이런 식으로 계속됩니다.

모든 경우에 장식된 리스트에 인덱스 i를 포함할 필요는 없지만, 두 가지 이점이 있습니다:

정렬이 안정적입니다 – 두 항목이 같은 키를 가지면, 그 들의 순서가 정렬된 리스트에 유지됩니다.

장식된 튜플의 순서는 최대 처음 두 항목에 의해 결정되므로 원래 항목은 비교 가능할 필요가 없습니다. 그래서 예를 들어, 원래 리스트에는 직접 정렬될 수 없는 복소수가 포함될 수 있습니다.

이 관용구의 또 다른 이름은 펄 프로그래머들 사이에서 이것을 대중화한 Randal L. Schwartz의 이름을 딴 Schwartzian 변환 [https://en.wikipedia.org/wiki/Schwartzian_transform]입니다.

이제 파이썬 정렬이 키 함수를 제공하기 때문에, 이 기법은 자주 필요하지 않습니다.

cmp 매개 변수를 사용하는 낡은 방법

이 HOWTO에서 제공하는 많은 구문은 파이썬 2.4 이상을 가정합니다. 그전에는, sorted() 내장 함수가 없었으며 list.sort()는 키워드 인자를 취하지 않았습니다. 대신, 모든 Py2.x 버전은 사용자 지정 비교 함수를 처리하기 위해 cmp 매개 변수를 지원했습니다.

Py3.0에서는, cmp 매개 변수가 완전히 제거되었습니다 (언어를 단순화하고 통합하기 위한 노력의 일환으로, 풍부한 비교(rich comparisons)와 __cmp__() 매직 메서드 간의 충돌을 제거했습니다).

Py2.x에서, sort는 비교 작업을 위해 호출할 수 있는 선택적 함수를 허용했습니다. 이 함수는 비교할 두 개의 인자를 취한 다음, 첫 번째가 두 번째보다 작으면(less-than) 음수 값을 반환하고, 같으면 0을 반환하고, 크면(greater-than) 양수 값을 반환해야 합니다. 예를 들어, 다음과 같이 할 수 있습니다:

>>> def numeric_compare(x, y):
...     return x - y
>>> sorted([5, 2, 4, 1, 3], cmp=numeric_compare)
[1, 2, 3, 4, 5]

또는 비교 순서를 다음과 같이 뒤집을 수 있습니다:

>>> def reverse_numeric(x, y):
...     return y - x
>>> sorted([5, 2, 4, 1, 3], cmp=reverse_numeric)
[5, 4, 3, 2, 1]

파이썬 2.x에서 3.x로 코드를 이식할 때, 사용자가 비교 함수를 제공하고 이를 키 함수로 변환해야 하는 상황이 발생할 수 있습니다. 다음 래퍼를 사용하면 쉽게 할 수 있습니다:

def cmp_to_key(mycmp):
    'Convert a cmp= function into a key= function'
    class K:
        def __init__(self, obj, *args):
            self.obj = obj
        def __lt__(self, other):
            return mycmp(self.obj, other.obj) < 0
        def __gt__(self, other):
            return mycmp(self.obj, other.obj) > 0
        def __eq__(self, other):
            return mycmp(self.obj, other.obj) == 0
        def __le__(self, other):
            return mycmp(self.obj, other.obj) <= 0
        def __ge__(self, other):
            return mycmp(self.obj, other.obj) >= 0
        def __ne__(self, other):
            return mycmp(self.obj, other.obj) != 0
    return K

키 함수로 변환하려면, 단지 이전 비교 함수를 감싸면 됩니다:

>>> sorted([5, 2, 4, 1, 3], key=cmp_to_key(reverse_numeric))
[5, 4, 3, 2, 1]

파이썬 3.2에서, functools.cmp_to_key() 함수가 표준 라이브러리의 functools 모듈에 추가되었습니다.

잡동사니

로케일 인식 정렬의 경우, 키 함수로는 locale.strxfrm()를, 비교 함수로는 locale.strcoll()을 사용하십시오.

reverse 매개 변수는 여전히 정렬 안정성을 유지합니다 (그래서 같은 키를 갖는 레코드는 원래 순서를 유지합니다). 흥미롭게도, 그 효과는 내장 reversed() 함수를 두 번 사용하여 매개 변수 없이 흉내 낼 수 있습니다:

>>> data = [('red', 1), ('blue', 1), ('red', 2), ('blue', 2)]
>>> standard_way = sorted(data, key=itemgetter(0), reverse=True)
>>> double_reversed = list(reversed(sorted(reversed(data), key=itemgetter(0))))
>>> assert standard_way == double_reversed
>>> standard_way
[('red', 1), ('red', 2), ('blue', 1), ('blue', 2)]

정렬 루틴은 두 객체를 비교할 때 __lt__()를 사용하도록 보장됩니다. 따라서 __lt__() 메서드를 정의하여, 표준 정렬 순서를 클래스에 추가하기는 쉽습니다:

>>> Student.__lt__ = lambda self, other: self.age < other.age
>>> sorted(student_objects)
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

키 함수는 정렬되는 객체에 직접 의존할 필요가 없습니다. 키 함수는 외부 자원에 액세스할 수도 있습니다. 예를 들어, 학생 성적이 딕셔너리에 저장되어 있다면, 학생 이름의 별도 리스트를 정렬하는 데 사용할 수 있습니다:

>>> students = ['dave', 'john', 'jane']
>>> newgrades = {'john': 'F', 'jane':'A', 'dave': 'C'}
>>> sorted(students, key=newgrades.__getitem__)
['jane', 'dave', 'john']

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 HOWTO »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 HOWTO »

|

유니코드 HOWTO

버전

1.12

This HOWTO discusses Python’s support for the Unicode specification for representing textual data, and explains various problems that people commonly encounter when trying to work with Unicode.

유니코드 소개

정의

Today’s programs need to be able to handle a wide variety of characters. Applications are often internationalized to display messages and output in a variety of user-selectable languages; the same program might need to output an error message in English, French, Japanese, Hebrew, or Russian. Web content can be written in any of these languages and can also include a variety of emoji symbols. Python’s string type uses the Unicode Standard for representing characters, which lets Python programs work with all these different possible characters.

Unicode (https://www.unicode.org/) is a specification that aims to list every character used by human languages and give each character its own unique code. The Unicode specifications are continually revised and updated to add new languages and symbols.

A character is the smallest possible component of a text. ‘A’, ‘B’, ‘C’, etc., are all different characters. So are ‘È’ and ‘Í’. Characters vary depending on the language or context you’re talking about. For example, there’s a character for “Roman Numeral One”, ‘Ⅰ’, that’s separate from the uppercase letter ‘I’. They’ll usually look the same, but these are two different characters that have different meanings.

The Unicode standard describes how characters are represented by code points. A code point value is an integer in the range 0 to 0x10FFFF (about 1.1 million values, with some 110 thousand assigned so far). In the standard and in this document, a code point is written using the notation U+265E to mean the character with value 0x265e (9,822 in decimal).

The Unicode standard contains a lot of tables listing characters and their corresponding code points:

0061    'a'; LATIN SMALL LETTER A
0062    'b'; LATIN SMALL LETTER B
0063    'c'; LATIN SMALL LETTER C
...
007B    '{'; LEFT CURLY BRACKET
...
2167    'Ⅷ'; ROMAN NUMERAL EIGHT
2168    'Ⅸ'; ROMAN NUMERAL NINE
...
265E    '♞'; BLACK CHESS KNIGHT
265F    '♟'; BLACK CHESS PAWN
...
1F600   '😀'; GRINNING FACE
1F609   '😉'; WINKING FACE
...

엄밀히 말하자면, 이러한 정의는 ‘이것이 문자 U+265E’라고 말하는 것은 의미가 없음을 뜻합니다. U+265E는 어떤 특정 문자를 표현하는 코드 포인트일 뿐입니다; 이 경우에는 ‘BLACK CHESS KNIGHT’(’♞’)를 나타냅니다. 일상적인 문맥에서 코드 포인트와 문자 사이의 구분은 때때로 잊힐 겁니다.

문자는 화면이나 종이에 글리프라 불리는 그래픽 요소의 집합으로 표시됩니다. 예를 들어 대문자 A의 글리프는 두 개의 대각 획과 한 개의 수평 획이지만, 정확한 세부사항은 글꼴에 따라 다릅니다. 대부분의 파이썬 코드는 글리프를 걱정할 필요가 없습니다; 표시할 올바른 글리프를 찾는 것은 일반적으로 GUI 툴킷이나 터미널의 글꼴 렌더러의 일입니다.

인코딩

To summarize the previous section: a Unicode string is a sequence of code points, which are numbers from 0 through 0x10FFFF (1,114,111 decimal). This sequence of code points needs to be represented in memory as a set of code units, and code units are then mapped to 8-bit bytes. The rules for translating a Unicode string into a sequence of bytes are called a character encoding, or just an encoding.

The first encoding you might think of is using 32-bit integers as the code unit, and then using the CPU’s representation of 32-bit integers. In this representation, the string “Python” might look like this:

   P           y           t           h           o           n
0x50 00 00 00 79 00 00 00 74 00 00 00 68 00 00 00 6f 00 00 00 6e 00 00 00
   0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23

이 표현은 간단하지만 여러 문제를 가지고 있습니다.

이식성이 없습니다; 다른 프로세서는 바이트를 다르게 정렬합니다.

이는 공간을 매우 낭비하는 겁니다. 대부분 텍스트에서 주요 코드 포인트는 127 또는 255보다 작으므로 많은 공간이 0x00으로 채워집니다. 위의 문자열은 ASCII 표현에 필요한 6 바이트와 비교하여 24 바이트를 사용합니다. 늘어난 RAM 사용은 중요하지 않지만(데스크톱 컴퓨터는 기가바이트 단위의 RAM을 갖고 있고, 문자열은 대개 그 정도로 크지 않습니다), 디스크와 네트워크 대역폭 사용을 4배로 확장하는 것은 용납할 수 없습니다.

strlen()과 같은 기존의 C 함수와 호환이 안 되기 때문에 새로운 와이드 문자열 함수 계열을 사용해야 합니다.

Therefore this encoding isn’t used very much, and people instead choose other encodings that are more efficient and convenient, such as UTF-8.

UTF-8 is one of the most commonly used encodings, and Python often defaults to using it. UTF stands for “Unicode Transformation Format”, and the ‘8’ means that 8-bit values are used in the encoding. (There are also UTF-16 and UTF-32 encodings, but they are less frequently used than UTF-8.) UTF-8 uses the following rules:

만약 코드 포인트가 128보다 작다면, 해당 바이트 값으로 표현됩니다.

만약 코드 포인트가 128보다 크거나 같다면, 시퀀스의 각 바이트가 128에서 255 사이인 둘, 셋 또는 네 개의 바이트 시퀀스로 바뀝니다.

UTF-8은 몇 가지 편리한 특징이 있습니다:

모든 유니코드 코드 포인트를 처리 할 수 있습니다.

A Unicode string is turned into a sequence of bytes that contains embedded zero bytes only where they represent the null character (U+0000). This means that UTF-8 strings can be processed by C functions such as strcpy() and sent through protocols that can’t handle zero bytes for anything other than end-of-string markers.

ASCII 텍스트의 문자열 역시 유효한 UTF-8 텍스트입니다.

UTF-8은 꽤 알찹니다; 일반적으로 사용되는 문자 대부분을 한두 개의 바이트로 표현할 수 있습니다.

만약 바이트가 손상 또는 손실되었다면, 다음 UTF-8 인코딩 코드 포인트의 시작을 결정하고 다시 동기화할 수 있습니다. 무작위 8비트 데이터가 유효한 UTF-8처럼 보일 가능성은 낮습니다.

UTF-8 is a byte oriented encoding. The encoding specifies that each character is represented by a specific sequence of one or more bytes. This avoids the byte-ordering issues that can occur with integer and word oriented encodings, like UTF-16 and UTF-32, where the sequence of bytes varies depending on the hardware on which the string was encoded.

참조

유니코드 컨소시엄 사이트 [http://www.unicode.org]는 유니코드 사양의 문자 차트, 용어집 그리고 PDF 버전의 유니코드 명세를 갖고 있습니다. 어려운 읽기를 준비하세요. 유니코드의 기원과 개발의 연대기 [http://www.unicode.org/history/] 역시 이 사이트에서 볼 수 있습니다.

On the Computerphile Youtube channel, Tom Scott briefly discusses the history of Unicode and UTF-8 <https://www.youtube.com/watch?v=MijmeoH9LT4> (9 minutes 36 seconds).

Jukka Korpela는 표준을 이해할 수 있도록 유니코드 문자표 읽기에 대한 입문 안내서 [http://jkorpela.fi/unicode/guide.html]를 작성했습니다.

또 다른 좋은 입문 글 [https://www.joelonsoftware.com/2003/10/08/the-absolute-minimum-every-software-developer-absolutely-positively-must-know-about-unicode-and-character-sets-no-excuses/]을 Joel Spolsky가 썼습니다. 이 입문서로도 명확하지 않은 경우 계속하기 전에 이 대체 문서를 읽으세요.

위키피디아 항목은 때때로 도움이 됩니다; 예를 들어, “문자 인코딩 [https://en.wikipedia.org/wiki/Character_encoding]”과 UTF-8 [https://en.wikipedia.org/wiki/UTF-8] 항목을 보세요.

파이썬의 유니코드 지원

이제 유니코드의 기초를 배웠으므로 파이썬의 유니코드 기능을 살펴볼 수 있습니다.

문자열 형

Since Python 3.0, the language’s str type contains Unicode characters, meaning any string created using "unicode rocks!", 'unicode rocks!', or the triple-quoted string syntax is stored as Unicode.

파이썬 소스 코드의 기본 인코딩은 UTF-8이므로 문자열 리터럴에 유니코드 문자를 쉽게 포함할 수 있습니다:

try:
    with open('/tmp/input.txt', 'r') as f:
        ...
except OSError:
    # 'File not found' error message.
    print("Fichier non trouvé")

사이드 노트: 파이썬 3은 유니코드 문자를 식별자에서도 지원합니다:

répertoire = "/tmp/records.log"
with open(répertoire, "w") as f:
    f.write("test\n")

편집기에서 특정 문자를 입력 할수 없거나 어떤 이유에서 ASCII만으로 소스 코드를 작성하고자 한다면, 문자열 리터럴에 이스케이프 시퀀스를 사용할 수 있습니다. (시스템에 따라 다르지만, u 이스케이프 대신에 진짜 대문자 델타 글리프가 나타날 수 있습니다.)

>>> "\N{GREEK CAPITAL LETTER DELTA}"  # Using the character name
'\u0394'
>>> "\u0394"                          # Using a 16-bit hex value
'\u0394'
>>> "\U00000394"                      # Using a 32-bit hex value
'\u0394'

추가로, 문자열을 bytes의 decode() 메서드를 사용하여 만들 수 있습니다. 이 메서드는 UTF-8과 같은 encoding 인자와 선택적으로 erros 인자를 받습니다.

errors 인자는 인코딩의 규칙에 따라 입력 문자열을 변환할 수 없는 경우의 응답을 지정합니다. 이 인자의 유효한 값은 'strict' (UnicodeDecodeError 예외 발생), 'replace' (U+FFFD, REPLACEMENT CHARACTER 사용), 'ignore' (유니코드 결과에서 문자를 그냥 생략), 또는 'backslashreplace' (\xNN 이스케이프 시퀀스를 삽입)입니다. 다음 에제는 그 차이점을 보여줍니다:

>>> b'\x80abc'.decode("utf-8", "strict")
Traceback (most recent call last):
    ...
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x80 in position 0:
  invalid start byte
>>> b'\x80abc'.decode("utf-8", "replace")
'\ufffdabc'
>>> b'\x80abc'.decode("utf-8", "backslashreplace")
'\\x80abc'
>>> b'\x80abc'.decode("utf-8", "ignore")
'abc'

인코딩은 인코딩의 이름을 포함하는 문자열로 지정됩니다. 파이썬에는 대략 100개의 서로 다른 인코딩이 있습니다. 리스트는 Standard Encodings에서 파이썬 라이브러리 레퍼런스를 보세요. 어떤 인코딩은 다양한 이름을 갖습니다; 예를 들어, 'latin-1', 'iso_8859_1' 그리고 '8859’ 는 전부 같은 인코딩의 동의어입니다.

한 문자 유니코드 문자열은 정수를 받고 해당 코드 포인트를 포함하는 길이 1인 유니코드 문자열을 반환하는 chr() 내장 함수로도 만들 수 있습니다. 반대 작업은 한 문자 유니코드 문자열을 받고 코드 포인트 값을 반환하는 ord() 내장 함수입니다:

>>> chr(57344)
'\ue000'
>>> ord('\ue000')
57344

바이트열로 변환

bytes.decode()의 반대 메서드는 요청된 encoding으로 인코딩 된 유니코드 문자열의 bytes를 반환하는 str.encode()입니다.

errors 매개변수는 decode() 메서드의 매개변수와 같지만 가능한 핸들러를 조금 더 제공합니다. 'strict', 'ignore', 'replace' (이 경우 인코딩할 수 없는 문자 대신에 물음표를 삽입)뿐만 아니라 'xmlcharrefreplace' (XML 문자 참조 삽입), backslashreplace (\uNNNN 이스케이프 시퀀스 삽입) 그리고 namereplace (\N{...} 이스케이프 시퀀스 삽입)도 있습니다.

아래 예제에서 서로 다른 결과를 보여줍니다:

>>> u = chr(40960) + 'abcd' + chr(1972)
>>> u.encode('utf-8')
b'\xea\x80\x80abcd\xde\xb4'
>>> u.encode('ascii')
Traceback (most recent call last):
    ...
UnicodeEncodeError: 'ascii' codec can't encode character '\ua000' in
  position 0: ordinal not in range(128)
>>> u.encode('ascii', 'ignore')
b'abcd'
>>> u.encode('ascii', 'replace')
b'?abcd?'
>>> u.encode('ascii', 'xmlcharrefreplace')
b'&#40960;abcd&#1972;'
>>> u.encode('ascii', 'backslashreplace')
b'\\ua000abcd\\u07b4'
>>> u.encode('ascii', 'namereplace')
b'\\N{YI SYLLABLE IT}abcd\\u07b4'

사용 가능한 인코딩을 등록하고 접근할 수 있도록 하는 저수준 루틴은 codecs 모듈에서 찾을 수 있습니다. 새로운 인코딩을 구현하는 것도 codecs 모듈의 이해가 필요합니다. 하지만 이 모듈에 의해서 반환되는 인코딩과 디코딩 함수는 대체로 편안한 것보다는 저수준이며, 새로운 인코딩을 작성하는 것은 전문적인 작업이므로 HOWTO에서 이 모듈을 다루지는 않겠습니다.

파이썬 소스 코드에서 유니코드 리터럴

파이썬 소스 코드에서 특정한 유니코드 코드 포인트는 \u 이스케이프 시퀀스로 쓸 수 있으며, 코드 포인트를 의미하는 네 개의 16진수가 뒤따릅니다. \U 이스케이프 시퀀스와 비슷하지만 네 개가 아닌 여덟 개의 숫자여야 합니다:

>>> s = "a\xac\u1234\u20ac\U00008000"
... #     ^^^^ two-digit hex escape
... #         ^^^^^^ four-digit Unicode escape
... #                     ^^^^^^^^^^ eight-digit Unicode escape
>>> [ord(c) for c in s]
[97, 172, 4660, 8364, 32768]

127보다 큰 코드 포인트에 대해 이스케이프 시퀀스를 사용하는 것은 양이 적을 때 괜찮지만, 프랑스어나 다른 악센트를 사용하는 언어로 작성된 프로그램 메시지 같이 악센트가 있는 문자를 사용할 경우 성가십니다. chr() 내장 함수를 이용하여 문자열을 조립할 수는 있지만 더 짜증납니다.

사용하는 언어의 자연스러운 인코딩으로 리터럴을 쓸 수 있어야 이상적입니다. 그래야 악센트가 있는 문자를 자연스럽게 표시하는 사용자가 가장 좋아하는 편집기로 파이썬 소스 코드를 편집할 수 있고, 실행시점에 올바른 문자를 가질 수 있습니다.

파이썬은 소스 코드를 UTF-8로 작성하는 것을 기본으로 지원하지만, 원하는 인코딩을 선언한다면 거의 모든 인코딩을 쓸 수 있습니다. 이는 소스 파일의 첫 번째 또는 두 번째 줄에 특별한 주석을 포함해 작동합니다:

#!/usr/bin/env python
# -*- coding: latin-1 -*-

u = 'abcdé'
print(ord(u[-1]))

이 문법은 파일에 지역적인 변수를 명시하는데 사용되는 이맥스 표기법에서 영감을 받았습니다. 이맥스는 수많은 서로 다른 변수를 지원하지만 파이썬은 오직 ‘coding’만을 지원합니다. -*- 기호는 이맥스에게 주석이 특별함을 나타냅니다; 파이썬에게 아무 의미도 없지만 그저 관례를 따르는 것뿐입니다. 파이썬은 주석에서 coding: name이나 coding=name을 찾습니다.

이러한 주석을 포함하지 않는다면, 이미 언급한 것처럼 기본 인코딩으로 UTF-8이 사용됩니다. PEP 263 [https://www.python.org/dev/peps/pep-0263]에서 정보를 더 보시기 바랍니다.

유니코드 속성

The Unicode specification includes a database of information about code points. For each defined code point, the information includes the character’s name, its category, the numeric value if applicable (for characters representing numeric concepts such as the Roman numerals, fractions such as one-third and four-fifths, etc.). There are also display-related properties, such as how to use the code point in bidirectional text.

아래의 프로그램은 몇몇 개의 문자에 대한 정보를 표시하고 특정한 문자의 숫자 값을 출력합니다:

import unicodedata

u = chr(233) + chr(0x0bf2) + chr(3972) + chr(6000) + chr(13231)

for i, c in enumerate(u):
    print(i, '%04x' % ord(c), unicodedata.category(c), end=" ")
    print(unicodedata.name(c))

# Get numeric value of second character
print(unicodedata.numeric(u[1]))

실행했을 때 다음을 출력합니다:

0 00e9 Ll LATIN SMALL LETTER E WITH ACUTE
1 0bf2 No TAMIL NUMBER ONE THOUSAND
2 0f84 Mn TIBETAN MARK HALANTA
3 1770 Lo TAGBANWA LETTER SA
4 33af So SQUARE RAD OVER S SQUARED
1000.0

카테고리 코드는 문자의 유형을 설명하는 약어입니다. 이것들은 “Letter”, “Number”, “Punctuation”, 또는 “Symbol”과 같은 카테고리로 묶여 있고, 이는 하위 카테고리로 나누어 집니다. 위 결과물에서 코드를 가져와 보면, 'Ll'는 ‘Letter, lowercase’, 'No'는 “Number, other”, 'Mn'은 “Mark, nonspacing”, 그리고 'So'는 “Symbol, other”를 뜻합니다. 카테고리 코드 목록에 대해서는 유니코드 문자 데이터베이스 문서의 일반 카테고리값 섹션 [http://www.unicode.org/reports/tr44/#General_Category_Values]을 보세요.

Comparing Strings

Unicode adds some complication to comparing strings, because the same set of characters can be represented by different sequences of code points. For example, a letter like ‘ê’ can be represented as a single code point U+00EA, or as U+0065 U+0302, which is the code point for ‘e’ followed by a code point for ‘COMBINING CIRCUMFLEX ACCENT’. These will produce the same output when printed, but one is a string of length 1 and the other is of length 2.

One tool for a case-insensitive comparison is the casefold() string method that converts a string to a case-insensitive form following an algorithm described by the Unicode Standard. This algorithm has special handling for characters such as the German letter ‘ß’ (code point U+00DF), which becomes the pair of lowercase letters ‘ss’.

>>> street = 'Gürzenichstraße'
>>> street.casefold()
'gürzenichstrasse'

A second tool is the unicodedata module’s normalize() function that converts strings to one of several normal forms, where letters followed by a combining character are replaced with single characters. normalize() can be used to perform string comparisons that won’t falsely report inequality if two strings use combining characters differently:

import unicodedata

def compare_strs(s1, s2):
    def NFD(s):
        return unicodedata.normalize('NFD', s)

    return NFD(s1) == NFD(s2)

single_char = 'ê'
multiple_chars = '\N{LATIN SMALL LETTER E}\N{COMBINING CIRCUMFLEX ACCENT}'
print('length of first string=', len(single_char))
print('length of second string=', len(multiple_chars))
print(compare_strs(single_char, multiple_chars))

실행했을 때 다음을 출력합니다:

$ python3 compare-strs.py
length of first string= 1
length of second string= 2
True

The first argument to the normalize() function is a string giving the desired normalization form, which can be one of ‘NFC’, ‘NFKC’, ‘NFD’, and ‘NFKD’.

The Unicode Standard also specifies how to do caseless comparisons:

import unicodedata

def compare_caseless(s1, s2):
    def NFD(s):
        return unicodedata.normalize('NFD', s)

    return NFD(NFD(s1).casefold()) == NFD(NFD(s2).casefold())

# Example usage
single_char = 'ê'
multiple_chars = '\N{LATIN CAPITAL LETTER E}\N{COMBINING CIRCUMFLEX ACCENT}'

print(compare_caseless(single_char, multiple_chars))

This will print True. (Why is NFD() invoked twice? Because there are a few characters that make casefold() return a non-normalized string, so the result needs to be normalized again. See section 3.13 of the Unicode Standard for a discussion and an example.)

유니코드 정규식

re 모듈이 지원하는 정규식은 바이트열 또는 문자열로 제공됩니다. \d와 \w 같은 특별한 문자 시퀀스 몇몇은 패턴이 바이트열 또는 문자열에 의해 지원되는지 여부에 따라 다른 의미가 있습니다. 예를 들어, 바이트열에서 \d는 [0-9]와 일치하지만, 문자열에서는 'Nd' 카테고리에 속하는 아무 문자와 일치합니다.

이 예제의 문자열은 태국과 아라비아 숫자로 쓰인 숫자 57을 갖고 있습니다:

import re
p = re.compile(r'\d+')

s = "Over \u0e55\u0e57 57 flavours"
m = p.search(s)
print(repr(m.group()))

실행했을 때, \d+은 태국 숫자와 일치하고 출력합니다. re.ASCII 플래그를 compile()에 제공했을 경우, \d+는 부분 문자열 “57”을 대신 일치시킵니다.

비슷하게, \w는 매우 다양한 유니코드와 일치하지만, 바이트열이거나 re.ASCII가 제공되면 오직 [a-zA-Z0-9_]과 일치하고, \s는 유니코드 공백 문자나 [ \t\n\r\f\v]와 일치합니다.

참조

파이썬 유니코드 지원에 대한 몇 개의 좋은 대안 토론은 다음과 같습니다:

Nick Coghlan의 파이썬 3의 텍스트 파일 처리 [http://python-notes.curiousefficiency.org/en/latest/python3/text_file_processing.html].

Ned Batchelder가 PyCon 2012에서 발표한 실용 유니코드 [https://nedbatchelder.com/text/unipain.html].

str 타입은 파이썬 라이브러리 레퍼런스 텍스트 시퀀스 형 — str에 설명되어 있습니다.

unicodedata 모듈에 대한 문서입니다.

codecs 모듈에 대한 문서입니다.

Marc-André Lemburg는 EuroPython 2002에서 발표한 “파이썬과 유니코드”라는 제목의 프레젠테이션 (PDF 슬라이드) [https://downloads.egenix.com/python/Unicode-EPC2002-Talk.pdf]을 주었습니다. 이 슬라이드는 파이썬 2의 유니코드 기능(유니코드 문자열 타입을 unicode라 부르고 리터럴 u로 시작하는) 디자인에 대한 훌륭한 개요서입니다.

유니코드 데이터 읽고 쓰기

유니코드 데이터로 동작하는 코드를 작성했다면, 다음은 입출력이 문제입니다. 프로그램에 유니코드 문자열을 어떻게 집어넣을 것인가, 그리고 유니코드를 어떻게 저장 또는 전송에 적합한 형식으로 유니코드를 전환할 것인가?

입력 소스 및 출력 대상에 따라 아무것도 할 필요 없을 수도 있습니다; 응용 프로그램에서 사용되는 라이브러리가 유니코드를 기본 지원하는지 확인해야 됩니다. 예를 들어, XML 파서는 종종 유니코드 데이터를 반환합니다. 많은 관계형 데이터베이스 역시 유니코드 값 칼럼을 지원하고, SQL 질의로부터 유니코드 값을 반환받을 수 있습니다.

유니코드 데이터는 디스크에 쓰이거나 소켓에 전달되기 전에 보통 특정 인코딩으로 변경됩니다. 다음의 모든 작업을 직접 할 수 있습니다: 파일 열기, 8-bit 바이트열 객체 읽기, 그리고 bytes.decode(encoding)로 바이트열 전환하기. 하지만 이러한 수동 접근은 권장하지 않습니다.

한 가지 문제는 인코딩의 멀티 바이트 특성입니다; 하나의 유니코드 문자는 여러 바이트로 표현됩니다. 임의의 크기의 청크로 파일을 읽으려면 (1024 또는 4096바이트라 할 때), 단일 유니코드 문자를 인코딩하는 바이트 일부만 청크 끝에 읽는 경우를 잡기 위해 에러 처리 코드를 작성해야 합니다. 한 가지 해결책은 파일 전체를 메모리에 읽고 디코딩을 수행하는 것이지만, 극도로 큰 파일로 작업하는 것을 방해합니다; 2기가바이트 파일을 읽어야만 한다면, 2기가바이트 메모리가 필요합니다. (인코딩된 문자열과 유니코드 버전을 잠깐 메모리에 가지고 있어야 하므로 실제로는 더 필요합니다.)

부분 코딩 시퀀스의 경우를 잡기 위해 저수준 디코딩 인터페이스를 사용하는 것이 해결방법입니다. 이를 구현하는 작업은 이미 수행되었습니다: 내장 open() 함수는 파일 내용물이 지정된 인코딩이라고 가정하고, read() 또는 write()와 같은 메서드에서 유니코드 매개변수를 받아들이는 파일 객체를 반환할 수 있습니다. 이는 str.encode()와 bytes.decode()에서처럼 해석되는 open()의 encoding과 errors 매개변수를 통해 작동합니다.

그러므로 파일에서 유니코드를 읽는 것은 간단합니다:

with open('unicode.txt', encoding='utf-8') as f:
    for line in f:
        print(repr(line))

업데이트 모드로 파일을 열어 읽기 또는 쓰기를 할 수도 있습니다:

with open('test', encoding='utf-8', mode='w+') as f:
    f.write('\u4500 blah blah blah\n')
    f.seek(0)
    print(repr(f.readline()[:1]))

유니코드 문자 U+FEFF는 바이트 순서 표시(BOM)로 사용되고, 파일의 바이트 순서를 자동감지하기 위해 파일의 맨 처음 문자로 쓰이기도 합니다. UTF-16과 같은 일부 인코딩에서는 파일 시작 부분에 BOM이 있어야합니다; 이러한 인코딩이 쓰일 때, BOM이 자동으로 첫번째 문자로 작성되고 파일을 읽을 때 조용히 없어집니다. 리틀 엔디안과 빅 엔디안을 위해 특정 바이트 순서를 지정하고 BOM을 생략하지 않는 ‘utf-16-le’와 ‘utf-16-be’ 같은 인코딩의 변종들이 있습니다.

일부 영역에서는 UTF-8로 인코딩된 파일의 시작 부분에 “BOM”을 사용하는 것이 관례이기도 합니다; UTF-8은 바이트 순서에 의존하지 않으므로 이 이름은 오해의 소지가 있습니다. 이 표시는 이 파일이 UTF-8로 인코딩했음을 단순히 알립니다. 그런 파일을 읽으려면 자동으로 이 표시를 건너뛰기 위해 ‘utf-8-sig’ 코덱을 사용하세요.

유니코드 파일 이름

Most of the operating systems in common use today support filenames that contain arbitrary Unicode characters. Usually this is implemented by converting the Unicode string into some encoding that varies depending on the system. Today Python is converging on using UTF-8: Python on MacOS has used UTF-8 for several versions, and Python 3.6 switched to using UTF-8 on Windows as well. On Unix systems, there will only be a filesystem encoding if you’ve set the LANG or LC_CTYPE environment variables; if you haven’t, the default encoding is again UTF-8.

인코딩을 수동으로 하고 싶을 때를 대비하여 sys.getfilesystemencoding() 함수는 현재 사용하고 있는 시스템의 인코딩을 반환하지만, 귀찮게 그럴 이유는 없습니다. 읽기 또는 쓰기를 위해 파일을 열 때, 보통 파일 이름으로 유니코드 문자열을 제공하기만 하면 되고, 자동으로 올바른 인코딩으로 변환됩니다:

filename = 'filename\u4500abc'
with open(filename, 'w') as f:
    f.write('blah\n')

os 모듈 안의 os.stat()과 같은 함수 역시 유니코드 파일 이름을 수용합니다.

The os.listdir() function returns filenames, which raises an issue: should it return the Unicode version of filenames, or should it return bytes containing the encoded versions? os.listdir() can do both, depending on whether you provided the directory path as bytes or a Unicode string. If you pass a Unicode string as the path, filenames will be decoded using the filesystem’s encoding and a list of Unicode strings will be returned, while passing a byte path will return the filenames as bytes. For example, assuming the default filesystem encoding is UTF-8, running the following program:

fn = 'filename\u4500abc'
f = open(fn, 'w')
f.close()

import os
print(os.listdir(b'.'))
print(os.listdir('.'))

아래의 출력을 만들 것입니다:

$ python listdir-test.py
[b'filename\xe4\x94\x80abc', ...]
['filename\u4500abc', ...]

첫번째 리스트는 UTF-8로 인코딩된 파일 이름을 갖고, 두 번째 리스트는 유니코드 버전을 갖습니다.

Note that on most occasions, you should can just stick with using Unicode with these APIs. The bytes APIs should only be used on systems where undecodable file names can be present; that’s pretty much only Unix systems now.

유니코드 인식 프로그램 작성 팁

이 섹션은 유니코드를 다루는 소프트웨어를 작성할 때의 몇 가지 제안을 제공합니다.

가장 중요한 팁은:

소프트웨어는 가능한 한 빨리 입력 데이터를 디코딩하고 마지막에만 출력을 인코딩하여 내부적으로는 유니코드 문자열에서만 작동하는 것이 좋습니다.

유니코드와 바이트 문자열을 수용하는 처리 함수를 작성하려고 시도한다면, 두 가지 다른 종류의 문자열을 결합할 때마다 프로그램이 버그에 취약하다는 것을 알 수 있습니다. 자동 인코딩이나 디코딩은 없습니다: str + bytes을 수행한다면 TypeError가 발생합니다.

웹 브라우저나 다른 신뢰할 수 없는 소스로부터 온 데이터를 사용할 때, 일반적인 기법은 생성된 명령행에서 문자열을 사용하거나 데이터베이스에 저장하기 전에 문자열에서 잘못된 문자를 검사하는 것입니다. 이렇게 하고 있다면, 인코딩된 바이트열 데이터가 아닌 디코딩 된 문자열을 검사하도록 조심하기 바랍니다; 어떤 인코딩은 일대일 대응되지 않거나 ASCII와 완전히 호환되지 않는 흥미로운 속성을 가지고 있습니다. 입력 데이터가 인코딩을 지정하는 경우 특히 그러한데, 공격자가 인코딩한 바이트 스트림 안에 악의적인 텍스트를 숨기는 방법을 택할 수 있기 때문입니다.

파일 인코딩끼리 변환

StreamRecoder 클래스는 인코딩 #1으로 데이터를 반환하는 스트림을 받아서 인코딩 #2로 데이터를 반환하는 스트림처럼 동작하여 인코딩 간에 투명하게 변환할 수 있습니다.

예를 들어, Latin-1을 사용하는 f 입력 파일을 가지고 있다면, 이를 UTF-8로 인코딩한 바이트열을 반환하기 위해 StreamRecoder로 감쌀 수 있습니다:

new_f = codecs.StreamRecoder(f,
    # en/decoder: used by read() to encode its results and
    # by write() to decode its input.
    codecs.getencoder('utf-8'), codecs.getdecoder('utf-8'),

    # reader/writer: used to read and write to the stream.
    codecs.getreader('latin-1'), codecs.getwriter('latin-1') )

알 수 없는 인코딩의 파일

파일을 변경해야 하지만 파일의 인코딩을 모를 때 할 수 있는 일은 무엇일까요? 인코딩이 ASCII 호환이라는 것을 알고 있고 ASCII 일부분을 검토 또는 수정만 하고자 한다면, surrogateescape 에러 핸들러와 함께 파일을 열 수 있습니다:

with open(fname, 'r', encoding="ascii", errors="surrogateescape") as f:
    data = f.read()

# make changes to the string 'data'

with open(fname + '.new', 'w',
          encoding="ascii", errors="surrogateescape") as f:
    f.write(data)

The surrogateescape error handler will decode any non-ASCII bytes as code points in a special range running from U+DC80 to U+DCFF. These code points will then turn back into the same bytes when the surrogateescape error handler is used to encode the data and write it back out.

참조

David Beazley가 PyCon 2010에서 발표한 파이썬3 입출력 마스터하기 [http://pyvideo.org/video/289/pycon-2010--mastering-python-3-i-o]의 한 섹션은 텍스트 처리와 바이너리 데이터 처리에 대해 논의합니다.

Marc-André Lemburg의 프레젠테이션 PDF 슬라이드 “파이썬에서 유니코드 인식 프로그램 작성” [https://downloads.egenix.com/python/LSM2005-Developing-Unicode-aware-applications-in-Python.pdf]은 문자 인코딩에 관한 질문은 물론 응용 프로그램을 국제화하고 지역화하는 방법에 관해 설명합니다. 이 슬라이드는 파이썬 2.x만을 다룹니다.

PyCon 2013에서 Benjamin Peterson이 발표한 파이썬에서 유니코드의 내부 [http://pyvideo.org/video/1768/the-guts-of-unicode-in-python]은 파이썬 3.3에서 내부 유니코드 표현에 대해 논의합니다.

감사 인사

이 문서의 초안은 Andrew Kuchling이 썼습니다. 이후 Alexander Belopolsky, Georg Brandl, Andrew Kuchling, 그리고 Ezio Melotti에 의해 개정되었습니다.

Thanks to the following people who have noted errors or offered suggestions on this article: Éric Araujo, Nicholas Bastin, Nick Coghlan, Marius Gedminas, Kent Johnson, Ken Krugler, Marc-André Lemburg, Martin von Löwis, Terry J. Reedy, Serhiy Storchaka, Eryk Sun, Chad Whitacre, Graham Wideman.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 HOWTO »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 HOWTO »

|

HOWTO Fetch Internet Resources Using The urllib Package

Author

Michael Foord [http://www.voidspace.org.uk/python/index.shtml]

참고

There is a French translation of an earlier revision of this HOWTO, available at urllib2 - Le Manuel manquant [http://www.voidspace.org.uk/python/articles/urllib2_francais.shtml].

Introduction

Related Articles

You may also find useful the following article on fetching web resources with Python:

Basic Authentication [http://www.voidspace.org.uk/python/articles/authentication.shtml]

A tutorial on Basic Authentication, with examples in Python.

urllib.request is a Python module for fetching URLs (Uniform Resource Locators). It offers a very simple interface, in the form of the urlopen function. This is capable of fetching URLs using a variety of different protocols. It also offers a slightly more complex interface for handling common situations - like basic authentication, cookies, proxies and so on. These are provided by objects called handlers and openers.

urllib.request supports fetching URLs for many “URL schemes” (identified by the string before the ":" in URL - for example "ftp" is the URL scheme of "ftp://python.org/") using their associated network protocols (e.g. FTP, HTTP). This tutorial focuses on the most common case, HTTP.

For straightforward situations urlopen is very easy to use. But as soon as you encounter errors or non-trivial cases when opening HTTP URLs, you will need some understanding of the HyperText Transfer Protocol. The most comprehensive and authoritative reference to HTTP is RFC 2616 [https://tools.ietf.org/html/rfc2616.html]. This is a technical document and not intended to be easy to read. This HOWTO aims to illustrate using urllib, with enough detail about HTTP to help you through. It is not intended to replace the urllib.request docs, but is supplementary to them.

Fetching URLs

The simplest way to use urllib.request is as follows:

import urllib.request
with urllib.request.urlopen('http://python.org/') as response:
   html = response.read()

If you wish to retrieve a resource via URL and store it in a temporary location, you can do so via the shutil.copyfileobj() and tempfile.NamedTemporaryFile() functions:

import shutil
import tempfile
import urllib.request

with urllib.request.urlopen('http://python.org/') as response:
    with tempfile.NamedTemporaryFile(delete=False) as tmp_file:
        shutil.copyfileobj(response, tmp_file)

with open(tmp_file.name) as html:
    pass

Many uses of urllib will be that simple (note that instead of an ‘http:’ URL we could have used a URL starting with ‘ftp:’, ‘file:’, etc.). However, it’s the purpose of this tutorial to explain the more complicated cases, concentrating on HTTP.

HTTP is based on requests and responses - the client makes requests and servers send responses. urllib.request mirrors this with a Request object which represents the HTTP request you are making. In its simplest form you create a Request object that specifies the URL you want to fetch. Calling urlopen with this Request object returns a response object for the URL requested. This response is a file-like object, which means you can for example call .read() on the response:

import urllib.request

req = urllib.request.Request('http://www.voidspace.org.uk')
with urllib.request.urlopen(req) as response:
   the_page = response.read()

Note that urllib.request makes use of the same Request interface to handle all URL schemes. For example, you can make an FTP request like so:

req = urllib.request.Request('ftp://example.com/')

In the case of HTTP, there are two extra things that Request objects allow you to do: First, you can pass data to be sent to the server. Second, you can pass extra information (“metadata”) about the data or the about request itself, to the server - this information is sent as HTTP “headers”. Let’s look at each of these in turn.

Data

Sometimes you want to send data to a URL (often the URL will refer to a CGI (Common Gateway Interface) script or other web application). With HTTP, this is often done using what’s known as a POST request. This is often what your browser does when you submit a HTML form that you filled in on the web. Not all POSTs have to come from forms: you can use a POST to transmit arbitrary data to your own application. In the common case of HTML forms, the data needs to be encoded in a standard way, and then passed to the Request object as the data argument. The encoding is done using a function from the urllib.parse library.

import urllib.parse
import urllib.request

url = 'http://www.someserver.com/cgi-bin/register.cgi'
values = {'name' : 'Michael Foord',
          'location' : 'Northampton',
          'language' : 'Python' }

data = urllib.parse.urlencode(values)
data = data.encode('ascii') # data should be bytes
req = urllib.request.Request(url, data)
with urllib.request.urlopen(req) as response:
   the_page = response.read()

Note that other encodings are sometimes required (e.g. for file upload from HTML forms - see HTML Specification, Form Submission [https://www.w3.org/TR/REC-html40/interact/forms.html#h-17.13] for more details).

If you do not pass the data argument, urllib uses a GET request. One way in which GET and POST requests differ is that POST requests often have “side-effects”: they change the state of the system in some way (for example by placing an order with the website for a hundredweight of tinned spam to be delivered to your door). Though the HTTP standard makes it clear that POSTs are intended to always cause side-effects, and GET requests never to cause side-effects, nothing prevents a GET request from having side-effects, nor a POST requests from having no side-effects. Data can also be passed in an HTTP GET request by encoding it in the URL itself.

This is done as follows:

>>> import urllib.request
>>> import urllib.parse
>>> data = {}
>>> data['name'] = 'Somebody Here'
>>> data['location'] = 'Northampton'
>>> data['language'] = 'Python'
>>> url_values = urllib.parse.urlencode(data)
>>> print(url_values)  # The order may differ from below.
name=Somebody+Here&language=Python&location=Northampton
>>> url = 'http://www.example.com/example.cgi'
>>> full_url = url + '?' + url_values
>>> data = urllib.request.urlopen(full_url)

Notice that the full URL is created by adding a ? to the URL, followed by the encoded values.

Headers

We’ll discuss here one particular HTTP header, to illustrate how to add headers to your HTTP request.

Some websites 1 dislike being browsed by programs, or send different versions to different browsers 2. By default urllib identifies itself as Python-urllib/x.y (where x and y are the major and minor version numbers of the Python release, e.g. Python-urllib/2.5), which may confuse the site, or just plain not work. The way a browser identifies itself is through the User-Agent header 3. When you create a Request object you can pass a dictionary of headers in. The following example makes the same request as above, but identifies itself as a version of Internet Explorer 4.

import urllib.parse
import urllib.request

url = 'http://www.someserver.com/cgi-bin/register.cgi'
user_agent = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64)'
values = {'name': 'Michael Foord',
          'location': 'Northampton',
          'language': 'Python' }
headers = {'User-Agent': user_agent}

data = urllib.parse.urlencode(values)
data = data.encode('ascii')
req = urllib.request.Request(url, data, headers)
with urllib.request.urlopen(req) as response:
   the_page = response.read()

The response also has two useful methods. See the section on info and geturl which comes after we have a look at what happens when things go wrong.

Handling Exceptions

urlopen raises URLError when it cannot handle a response (though as usual with Python APIs, built-in exceptions such as ValueError, TypeError etc. may also be raised).

HTTPError is the subclass of URLError raised in the specific case of HTTP URLs.

The exception classes are exported from the urllib.error module.

URLError

Often, URLError is raised because there is no network connection (no route to the specified server), or the specified server doesn’t exist. In this case, the exception raised will have a ‘reason’ attribute, which is a tuple containing an error code and a text error message.

e.g.

>>> req = urllib.request.Request('http://www.pretend_server.org')
>>> try: urllib.request.urlopen(req)
... except urllib.error.URLError as e:
...     print(e.reason)
...
(4, 'getaddrinfo failed')

HTTPError

Every HTTP response from the server contains a numeric “status code”. Sometimes the status code indicates that the server is unable to fulfil the request. The default handlers will handle some of these responses for you (for example, if the response is a “redirection” that requests the client fetch the document from a different URL, urllib will handle that for you). For those it can’t handle, urlopen will raise an HTTPError. Typical errors include ‘404’ (page not found), ‘403’ (request forbidden), and ‘401’ (authentication required).

See section 10 of RFC 2616 [https://tools.ietf.org/html/rfc2616.html] for a reference on all the HTTP error codes.

The HTTPError instance raised will have an integer ‘code’ attribute, which corresponds to the error sent by the server.

Error Codes

Because the default handlers handle redirects (codes in the 300 range), and codes in the 100–299 range indicate success, you will usually only see error codes in the 400–599 range.

http.server.BaseHTTPRequestHandler.responses is a useful dictionary of response codes in that shows all the response codes used by RFC 2616 [https://tools.ietf.org/html/rfc2616.html]. The dictionary is reproduced here for convenience

# Table mapping response codes to messages; entries have the
# form {code: (shortmessage, longmessage)}.
responses = {
    100: ('Continue', 'Request received, please continue'),
    101: ('Switching Protocols',
          'Switching to new protocol; obey Upgrade header'),

    200: ('OK', 'Request fulfilled, document follows'),
    201: ('Created', 'Document created, URL follows'),
    202: ('Accepted',
          'Request accepted, processing continues off-line'),
    203: ('Non-Authoritative Information', 'Request fulfilled from cache'),
    204: ('No Content', 'Request fulfilled, nothing follows'),
    205: ('Reset Content', 'Clear input form for further input.'),
    206: ('Partial Content', 'Partial content follows.'),

    300: ('Multiple Choices',
          'Object has several resources -- see URI list'),
    301: ('Moved Permanently', 'Object moved permanently -- see URI list'),
    302: ('Found', 'Object moved temporarily -- see URI list'),
    303: ('See Other', 'Object moved -- see Method and URL list'),
    304: ('Not Modified',
          'Document has not changed since given time'),
    305: ('Use Proxy',
          'You must use proxy specified in Location to access this '
          'resource.'),
    307: ('Temporary Redirect',
          'Object moved temporarily -- see URI list'),

    400: ('Bad Request',
          'Bad request syntax or unsupported method'),
    401: ('Unauthorized',
          'No permission -- see authorization schemes'),
    402: ('Payment Required',
          'No payment -- see charging schemes'),
    403: ('Forbidden',
          'Request forbidden -- authorization will not help'),
    404: ('Not Found', 'Nothing matches the given URI'),
    405: ('Method Not Allowed',
          'Specified method is invalid for this server.'),
    406: ('Not Acceptable', 'URI not available in preferred format.'),
    407: ('Proxy Authentication Required', 'You must authenticate with '
          'this proxy before proceeding.'),
    408: ('Request Timeout', 'Request timed out; try again later.'),
    409: ('Conflict', 'Request conflict.'),
    410: ('Gone',
          'URI no longer exists and has been permanently removed.'),
    411: ('Length Required', 'Client must specify Content-Length.'),
    412: ('Precondition Failed', 'Precondition in headers is false.'),
    413: ('Request Entity Too Large', 'Entity is too large.'),
    414: ('Request-URI Too Long', 'URI is too long.'),
    415: ('Unsupported Media Type', 'Entity body in unsupported format.'),
    416: ('Requested Range Not Satisfiable',
          'Cannot satisfy request range.'),
    417: ('Expectation Failed',
          'Expect condition could not be satisfied.'),

    500: ('Internal Server Error', 'Server got itself in trouble'),
    501: ('Not Implemented',
          'Server does not support this operation'),
    502: ('Bad Gateway', 'Invalid responses from another server/proxy.'),
    503: ('Service Unavailable',
          'The server cannot process the request due to a high load'),
    504: ('Gateway Timeout',
          'The gateway server did not receive a timely response'),
    505: ('HTTP Version Not Supported', 'Cannot fulfill request.'),
    }

When an error is raised the server responds by returning an HTTP error code and an error page. You can use the HTTPError instance as a response on the page returned. This means that as well as the code attribute, it also has read, geturl, and info, methods as returned by the urllib.response module:

>>> req = urllib.request.Request('http://www.python.org/fish.html')
>>> try:
...     urllib.request.urlopen(req)
... except urllib.error.HTTPError as e:
...     print(e.code)
...     print(e.read())
...
404
b'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\n\n\n<html
  ...
  <title>Page Not Found</title>\n
  ...

Wrapping it Up

So if you want to be prepared for HTTPError or URLError there are two basic approaches. I prefer the second approach.

Number 1

from urllib.request import Request, urlopen
from urllib.error import URLError, HTTPError
req = Request(someurl)
try:
    response = urlopen(req)
except HTTPError as e:
    print('The server couldn\'t fulfill the request.')
    print('Error code: ', e.code)
except URLError as e:
    print('We failed to reach a server.')
    print('Reason: ', e.reason)
else:
    # everything is fine

참고

The except HTTPError must come first, otherwise except URLError will also catch an HTTPError.

Number 2

from urllib.request import Request, urlopen
from urllib.error import URLError
req = Request(someurl)
try:
    response = urlopen(req)
except URLError as e:
    if hasattr(e, 'reason'):
        print('We failed to reach a server.')
        print('Reason: ', e.reason)
    elif hasattr(e, 'code'):
        print('The server couldn\'t fulfill the request.')
        print('Error code: ', e.code)
else:
    # everything is fine

info and geturl

The response returned by urlopen (or the HTTPError instance) has two useful methods info() and geturl() and is defined in the module urllib.response..

geturl - this returns the real URL of the page fetched. This is useful because urlopen (or the opener object used) may have followed a redirect. The URL of the page fetched may not be the same as the URL requested.

info - this returns a dictionary-like object that describes the page fetched, particularly the headers sent by the server. It is currently an http.client.HTTPMessage instance.

Typical headers include ‘Content-length’, ‘Content-type’, and so on. See the Quick Reference to HTTP Headers [http://jkorpela.fi/http.html] for a useful listing of HTTP headers with brief explanations of their meaning and use.

Openers and Handlers

When you fetch a URL you use an opener (an instance of the perhaps confusingly-named urllib.request.OpenerDirector). Normally we have been using the default opener - via urlopen - but you can create custom openers. Openers use handlers. All the “heavy lifting” is done by the handlers. Each handler knows how to open URLs for a particular URL scheme (http, ftp, etc.), or how to handle an aspect of URL opening, for example HTTP redirections or HTTP cookies.

You will want to create openers if you want to fetch URLs with specific handlers installed, for example to get an opener that handles cookies, or to get an opener that does not handle redirections.

To create an opener, instantiate an OpenerDirector, and then call .add_handler(some_handler_instance) repeatedly.

Alternatively, you can use build_opener, which is a convenience function for creating opener objects with a single function call. build_opener adds several handlers by default, but provides a quick way to add more and/or override the default handlers.

Other sorts of handlers you might want to can handle proxies, authentication, and other common but slightly specialised situations.

install_opener can be used to make an opener object the (global) default opener. This means that calls to urlopen will use the opener you have installed.

Opener objects have an open method, which can be called directly to fetch urls in the same way as the urlopen function: there’s no need to call install_opener, except as a convenience.

Basic Authentication

To illustrate creating and installing a handler we will use the HTTPBasicAuthHandler. For a more detailed discussion of this subject – including an explanation of how Basic Authentication works - see the Basic Authentication Tutorial [http://www.voidspace.org.uk/python/articles/authentication.shtml].

When authentication is required, the server sends a header (as well as the 401 error code) requesting authentication. This specifies the authentication scheme and a ‘realm’. The header looks like: WWW-Authenticate: SCHEME realm="REALM".

e.g.

WWW-Authenticate: Basic realm="cPanel Users"

The client should then retry the request with the appropriate name and password for the realm included as a header in the request. This is ‘basic authentication’. In order to simplify this process we can create an instance of HTTPBasicAuthHandler and an opener to use this handler.

The HTTPBasicAuthHandler uses an object called a password manager to handle the mapping of URLs and realms to passwords and usernames. If you know what the realm is (from the authentication header sent by the server), then you can use a HTTPPasswordMgr. Frequently one doesn’t care what the realm is. In that case, it is convenient to use HTTPPasswordMgrWithDefaultRealm. This allows you to specify a default username and password for a URL. This will be supplied in the absence of you providing an alternative combination for a specific realm. We indicate this by providing None as the realm argument to the add_password method.

The top-level URL is the first URL that requires authentication. URLs “deeper” than the URL you pass to .add_password() will also match.

# create a password manager
password_mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()

# Add the username and password.
# If we knew the realm, we could use it instead of None.
top_level_url = "http://example.com/foo/"
password_mgr.add_password(None, top_level_url, username, password)

handler = urllib.request.HTTPBasicAuthHandler(password_mgr)

# create "opener" (OpenerDirector instance)
opener = urllib.request.build_opener(handler)

# use the opener to fetch a URL
opener.open(a_url)

# Install the opener.
# Now all calls to urllib.request.urlopen use our opener.
urllib.request.install_opener(opener)

참고

In the above example we only supplied our HTTPBasicAuthHandler to build_opener. By default openers have the handlers for normal situations – ProxyHandler (if a proxy setting such as an http_proxy environment variable is set), UnknownHandler, HTTPHandler, HTTPDefaultErrorHandler, HTTPRedirectHandler, FTPHandler, FileHandler, DataHandler, HTTPErrorProcessor.

top_level_url is in fact either a full URL (including the ‘http:’ scheme component and the hostname and optionally the port number) e.g. "http://example.com/" or an “authority” (i.e. the hostname, optionally including the port number) e.g. "example.com" or "example.com:8080" (the latter example includes a port number). The authority, if present, must NOT contain the “userinfo” component - for example "joe:password@example.com" is not correct.

Proxies

urllib will auto-detect your proxy settings and use those. This is through the ProxyHandler, which is part of the normal handler chain when a proxy setting is detected. Normally that’s a good thing, but there are occasions when it may not be helpful 5. One way to do this is to setup our own ProxyHandler, with no proxies defined. This is done using similar steps to setting up a Basic Authentication [http://www.voidspace.org.uk/python/articles/authentication.shtml] handler:

>>> proxy_support = urllib.request.ProxyHandler({})
>>> opener = urllib.request.build_opener(proxy_support)
>>> urllib.request.install_opener(opener)

참고

Currently urllib.request does not support fetching of https locations through a proxy. However, this can be enabled by extending urllib.request as shown in the recipe 6.

참고

HTTP_PROXY will be ignored if a variable REQUEST_METHOD is set; see the documentation on getproxies().

Sockets and Layers

The Python support for fetching resources from the web is layered. urllib uses the http.client library, which in turn uses the socket library.

As of Python 2.3 you can specify how long a socket should wait for a response before timing out. This can be useful in applications which have to fetch web pages. By default the socket module has no timeout and can hang. Currently, the socket timeout is not exposed at the http.client or urllib.request levels. However, you can set the default timeout globally for all sockets using

import socket
import urllib.request

# timeout in seconds
timeout = 10
socket.setdefaulttimeout(timeout)

# this call to urllib.request.urlopen now uses the default timeout
# we have set in the socket module
req = urllib.request.Request('http://www.voidspace.org.uk')
response = urllib.request.urlopen(req)

Footnotes

This document was reviewed and revised by John Lee.

1

Google for example.

2

Browser sniffing is a very bad practice for website design - building sites using web standards is much more sensible. Unfortunately a lot of sites still send different versions to different browsers.

3

The user agent for MSIE 6 is ‘Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322)’

4

For details of more HTTP request headers, see Quick Reference to HTTP Headers [http://jkorpela.fi/http.html].

5

In my case I have to use a proxy to access the internet at work. If you attempt to fetch localhost URLs through this proxy it blocks them. IE is set to use the proxy, which urllib picks up on. In order to test scripts with a localhost server, I have to prevent urllib from using the proxy.

6

urllib opener for SSL proxy (CONNECT method): ASPN Cookbook Recipe [https://code.activestate.com/recipes/456195/].

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 HOWTO »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 HOWTO »

|

Argparse 자습서

저자

Tshepang Lekhonkhobe

이 자습서는 파이썬 표준 라이브러리에서 권장하는 명령행 파싱 모듈인 argparse 에 대한 소개입니다.

참고

같은 작업을 수행하는 다른 두 모듈이 있습니다, getopt (C 언어에서 getopt() 와 동등합니다) 와 폐지된 optparse. argparse 는 optparse 에 기반을 두고 있어서 사용법 면에서 매우 비슷합니다.

개념

ls 명령을 사용하여 이 입문서에서 다룰 기능들을 살펴봅시다:

$ ls
cpython  devguide  prog.py  pypy  rm-unused-function.patch
$ ls pypy
ctypes_configure  demo  dotviewer  include  lib_pypy  lib-python ...
$ ls -l
total 20
drwxr-xr-x 19 wena wena 4096 Feb 18 18:51 cpython
drwxr-xr-x  4 wena wena 4096 Feb  8 12:04 devguide
-rwxr-xr-x  1 wena wena  535 Feb 19 00:05 prog.py
drwxr-xr-x 14 wena wena 4096 Feb  7 00:59 pypy
-rw-r--r--  1 wena wena  741 Feb 18 01:01 rm-unused-function.patch
$ ls --help
Usage: ls [OPTION]... [FILE]...
List information about the FILEs (the current directory by default).
Sort entries alphabetically if none of -cftuvSUX nor --sort is specified.
...

네 가지 명령에서 배울 수 있는 몇 가지 개념들입니다:

ls 명령은 옵션 없이 실행될 때도 유용합니다. 기본적으로 현재 디렉터리의 내용을 표시합니다.

기본적으로 제공하는 것 이상으로 원한다면, 조금 더 말합니다. 이 경우에는 다른 디렉터리인 pypy 를 표시하기를 원합니다. 우리가 한 것은 위치 인자라고 알려진 것을 지정하는 것입니다. 프로그램이 명령행에 표시되는 위치를 기준으로 값을 어떻게 처리해야 하는지를 알아야 하므로 이런 이름이 사용됩니다. 이 개념은 cp 와 같은 명령에 더 적절합니다. 가장 기본적인 사용법은 cp SRC DEST 입니다. 첫 번째 위치는 복사하고자 하는 것 이고 두 번째 위치는 사본을 저장할 곳 입니다.

자, 프로그램의 행동을 바꾸고 싶다고 합시다. 이 예에서는 파일 이름만 표시하는 대신 각 파일에 대한 정보를 더 많이 표시합니다. 이 경우 -l 은 옵션 인자로 알려져 있습니다.

이것이 도움말 텍스트입니다. 이전에 사용해보지 않은 프로그램을 접했을 때 도움말 텍스트를 읽는 것만으로 작동하는 방식을 이해할 수 있다는 점에서 매우 유용합니다.

기본

(거의) 아무것도 하지 않는 아주 간단한 예제로 시작합시다:

import argparse
parser = argparse.ArgumentParser()
parser.parse_args()

다음은 코드를 실행한 결과입니다:

$ python3 prog.py
$ python3 prog.py --help
usage: prog.py [-h]

optional arguments:
  -h, --help  show this help message and exit
$ python3 prog.py --verbose
usage: prog.py [-h]
prog.py: error: unrecognized arguments: --verbose
$ python3 prog.py foo
usage: prog.py [-h]
prog.py: error: unrecognized arguments: foo

일어난 일은 이렇습니다:

옵션 없이 스크립트를 실행하면 아무것도 표준 출력에 표시되지 않습니다. 별로 유용하지 않습니다.

두 번째는 argparse 모듈의 쓸모를 보여주기 시작합니다. 거의 아무것도 하지 않았지만 이미 도움말을 얻었습니다.

--help 옵션은, -h 로 단축할 수도 있습니다, 무료로 얻을 수 있는 유일한 옵션입니다 (즉, 지정할 필요가 없습니다). 다른 값을 지정하면 오류가 발생합니다. 그러나 그때조차도 우리는 사용 안내를 얻습니다, 여전히 공짜입니다.

위치 인자 소개

예:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("echo")
args = parser.parse_args()
print(args.echo)

코드를 실행합니다:

$ python3 prog.py
usage: prog.py [-h] echo
prog.py: error: the following arguments are required: echo
$ python3 prog.py --help
usage: prog.py [-h] echo

positional arguments:
  echo

optional arguments:
  -h, --help  show this help message and exit
$ python3 prog.py foo
foo

이런 일이 일어났습니다:

add_argument() 메서드를 추가했습니다. 이 메서드는 프로그램이 받고 싶은 명령행 옵션을 지정하기 위해 사용합니다. 이 경우 기능과 일치하도록 echo 라고 이름 붙였습니다.

이제 프로그램을 호출하려면 옵션을 지정해야 합니다.

parse_args() 메서드는 실제로 지정된 옵션으로부터 온 데이터를 돌려줍니다. 이 경우에는 echo 입니다.

변수는 argparse 이 공짜로 수행하는 일종의 ‘마법’ 입니다 (즉, 값이 저장되는 변수를 지정할 필요가 없습니다). 또한, 그 이름이 메서드에 주어진 문자열 인자 echo 와 일치함을 알 수 있습니다.

그러나 도움말이 멋지게 보이지만, 현재로서는 가능한 최선이 아닙니다. 예를 들어 echo 가 위치 인자임을 볼 수 있지만, 추측하거나 소스 코드를 읽는 것 외에는 그것이 무엇을 하는지 모릅니다. 그럼 좀 더 유용하게 만들어 봅시다:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("echo", help="echo the string you use here")
args = parser.parse_args()
print(args.echo)

그러면 이렇게 됩니다:

$ python3 prog.py -h
usage: prog.py [-h] echo

positional arguments:
  echo        echo the string you use here

optional arguments:
  -h, --help  show this help message and exit

이제, 뭔가 더 쓸모있는 일을 하는 것은 어떻습니까:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("square", help="display a square of a given number")
args = parser.parse_args()
print(args.square**2)

다음은 코드를 실행한 결과입니다:

$ python3 prog.py 4
Traceback (most recent call last):
  File "prog.py", line 5, in <module>
    print(args.square**2)
TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int'

잘 안됐습니다. 우리가 달리 지시하지 않는다면, argparse 는 우리가 준 옵션들을 문자열로 취급하기 때문입니다. 그럼, argparse 에게 그 입력을 정수로 취급하라고 알려줍시다:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("square", help="display a square of a given number",
                    type=int)
args = parser.parse_args()
print(args.square**2)

다음은 코드를 실행한 결과입니다:

$ python3 prog.py 4
16
$ python3 prog.py four
usage: prog.py [-h] square
prog.py: error: argument square: invalid int value: 'four'

잘 됩니다. 이제 이 프로그램은 잘못된 입력이 올 때 더 진행하지 않고 종료하기조차 합니다.

옵션 인자 소개

지금까지 우리는 위치 인자를 다뤘습니다. 옵션 인자를 추가하는 방법에 대해 살펴봅시다:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--verbosity", help="increase output verbosity")
args = parser.parse_args()
if args.verbosity:
    print("verbosity turned on")

출력은 이렇습니다:

$ python3 prog.py --verbosity 1
verbosity turned on
$ python3 prog.py
$ python3 prog.py --help
usage: prog.py [-h] [--verbosity VERBOSITY]

optional arguments:
  -h, --help            show this help message and exit
  --verbosity VERBOSITY
                        increase output verbosity
$ python3 prog.py --verbosity
usage: prog.py [-h] [--verbosity VERBOSITY]
prog.py: error: argument --verbosity: expected one argument

일어난 일은 이렇습니다:

이 프로그램은 --verbosity 가 지정되었을 때 어떤 것을 표시하고 그렇지 않을 때는 아무것도 표시하지 않도록 작성되었습니다.

옵션이 실제로 선택 사항임을 확인하기 위해, 이 옵션을 사용하지 않고 프로그램을 실행할 때 오류가 없습니다. 기본적으로 옵션 인자가 사용되지 않는다면 관련 변수 (이 경우 args.verbosity)는 값으로 None 이 주어집니다. 이 때문에 if 문의 논리값 검사가 실패합니다.

도움말 메시지가 약간 달라졌습니다.

--verbosity 옵션을 사용할 때, 어떤 값을 지정해야 합니다. 어떤 값이건 상관없습니다.

위의 예제는 --verbosity 에 임의의 정숫값을 허용하지만, 우리의 간단한 프로그램에서는 실제로 True 또는 False 두 값만 쓸모 있습니다. 그것에 맞게 코드를 수정합시다:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--verbose", help="increase output verbosity",
                    action="store_true")
args = parser.parse_args()
if args.verbose:
    print("verbosity turned on")

출력은 이렇습니다:

$ python3 prog.py --verbose
verbosity turned on
$ python3 prog.py --verbose 1
usage: prog.py [-h] [--verbose]
prog.py: error: unrecognized arguments: 1
$ python3 prog.py --help
usage: prog.py [-h] [--verbose]

optional arguments:
  -h, --help  show this help message and exit
  --verbose   increase output verbosity

일어난 일은 이렇습니다:

이 옵션은 이제 값을 요구하는 것이 아니라 플래그입니다. 이 개념과 일치하도록 옵션의 이름을 변경하기까지 했습니다. 새로운 키워드 action 을 지정하고, "store_true" 값을 지정했습니다. 이것은, 옵션이 지정되면 args.verbose 에 값 True 를 대입하라는 뜻입니다. 지정하지 않으면 묵시적으로 False 입니다.

값을 지정하면 불평하는데, 플래그의 정의를 따르고 있습니다.

도움말 텍스트가 바뀐 것을 확인하십시오.

짧은 옵션

명령행 사용법에 익숙하다면 짧은 옵션 버전에 관한 내용을 아직 다루지 않았음을 알 수 있을 겁니다. 아주 간단합니다:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-v", "--verbose", help="increase output verbosity",
                    action="store_true")
args = parser.parse_args()
if args.verbose:
    print("verbosity turned on")

그러면 이렇게 됩니다:

$ python3 prog.py -v
verbosity turned on
$ python3 prog.py --help
usage: prog.py [-h] [-v]

optional arguments:
  -h, --help     show this help message and exit
  -v, --verbose  increase output verbosity

새로운 기능은 도움말 텍스트에도 반영됩니다.

위치 및 옵션 인자 결합하기

프로그램이 점점 복잡해지고 있습니다:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("square", type=int,
                    help="display a square of a given number")
parser.add_argument("-v", "--verbose", action="store_true",
                    help="increase output verbosity")
args = parser.parse_args()
answer = args.square**2
if args.verbose:
    print("the square of {} equals {}".format(args.square, answer))
else:
    print(answer)

이제 출력은 이렇게 됩니다:

$ python3 prog.py
usage: prog.py [-h] [-v] square
prog.py: error: the following arguments are required: square
$ python3 prog.py 4
16
$ python3 prog.py 4 --verbose
the square of 4 equals 16
$ python3 prog.py --verbose 4
the square of 4 equals 16

위치 인자를 다시 도입했기 때문에, 불평합니다.

순서는 중요하지 않습니다.

이 프로그램에 여러 상세도를 지정할 수 있도록 하는 능력을 다시 부여하고, 실제로 그것을 사용하는 것은 어떨까요:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("square", type=int,
                    help="display a square of a given number")
parser.add_argument("-v", "--verbosity", type=int,
                    help="increase output verbosity")
args = parser.parse_args()
answer = args.square**2
if args.verbosity == 2:
    print("the square of {} equals {}".format(args.square, answer))
elif args.verbosity == 1:
    print("{}^2 == {}".format(args.square, answer))
else:
    print(answer)

출력은 이렇습니다:

$ python3 prog.py 4
16
$ python3 prog.py 4 -v
usage: prog.py [-h] [-v VERBOSITY] square
prog.py: error: argument -v/--verbosity: expected one argument
$ python3 prog.py 4 -v 1
4^2 == 16
$ python3 prog.py 4 -v 2
the square of 4 equals 16
$ python3 prog.py 4 -v 3
16

우리 프로그램의 버그를 드러내는 마지막 것을 제외하고는 그럴듯해 보입니다. --verbosity 옵션이 받아들일 수 있는 값을 제한해서 고쳐봅시다:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("square", type=int,
                    help="display a square of a given number")
parser.add_argument("-v", "--verbosity", type=int, choices=[0, 1, 2],
                    help="increase output verbosity")
args = parser.parse_args()
answer = args.square**2
if args.verbosity == 2:
    print("the square of {} equals {}".format(args.square, answer))
elif args.verbosity == 1:
    print("{}^2 == {}".format(args.square, answer))
else:
    print(answer)

출력은 이렇습니다:

$ python3 prog.py 4 -v 3
usage: prog.py [-h] [-v {0,1,2}] square
prog.py: error: argument -v/--verbosity: invalid choice: 3 (choose from 0, 1, 2)
$ python3 prog.py 4 -h
usage: prog.py [-h] [-v {0,1,2}] square

positional arguments:
  square                display a square of a given number

optional arguments:
  -h, --help            show this help message and exit
  -v {0,1,2}, --verbosity {0,1,2}
                        increase output verbosity

변경 내용은 오류 메시지와 도움말 문자열에도 반영됩니다.

이제 상세도를 다루는 다른 접근법을 사용해 봅시다, 이 방법은 꽤 널리 사용됩니다. 또한, 이 방법은 CPython 실행 파일이 자신의 상세도를 처리하는 방식과도 일치합니다 (python --help 의 결과를 확인하십시오):

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("square", type=int,
                    help="display the square of a given number")
parser.add_argument("-v", "--verbosity", action="count",
                    help="increase output verbosity")
args = parser.parse_args()
answer = args.square**2
if args.verbosity == 2:
    print("the square of {} equals {}".format(args.square, answer))
elif args.verbosity == 1:
    print("{}^2 == {}".format(args.square, answer))
else:
    print(answer)

특정 옵션 인자를 지정한 횟수를 계산하기 위해 “count” 라는 또 다른 액션을 도입했습니다:

$ python3 prog.py 4
16
$ python3 prog.py 4 -v
4^2 == 16
$ python3 prog.py 4 -vv
the square of 4 equals 16
$ python3 prog.py 4 --verbosity --verbosity
the square of 4 equals 16
$ python3 prog.py 4 -v 1
usage: prog.py [-h] [-v] square
prog.py: error: unrecognized arguments: 1
$ python3 prog.py 4 -h
usage: prog.py [-h] [-v] square

positional arguments:
  square           display a square of a given number

optional arguments:
  -h, --help       show this help message and exit
  -v, --verbosity  increase output verbosity
$ python3 prog.py 4 -vvv
16

예, 이제 이전 버전의 스크립트처럼 (action="store_true" 와 유사하게) 플래그가 되었습니다. 출력되는 불평이 설명됩니다.

또한 “store_true” 액션과 비슷하게 작동하기도 합니다.

이제 여기에서 “count” 액션이 제공하는 것을 보여줍니다. 이런 종류의 사용법을 전에도 보았을 것입니다.

그리고, -v 플래그를 지정하지 않으면 그 플래그는 None 값으로 간주합니다.

예측하듯이, 플래그의 긴 형식을 지정하면, 같은 출력이 얻어져야 합니다.

안타깝게도 스크립트가 얻은 새로운 기능에 대한 도움말 출력은 그다지 유익하지 않지만, 스크립트의 문서를 개선하면 항상 해결할 수 있습니다 (예, help 키워드 인자를 사용해서).

마지막 출력은 우리 프로그램의 버그를 노출합니다.

고칩시다:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("square", type=int,
                    help="display a square of a given number")
parser.add_argument("-v", "--verbosity", action="count",
                    help="increase output verbosity")
args = parser.parse_args()
answer = args.square**2

# bugfix: replace == with >=
if args.verbosity >= 2:
    print("the square of {} equals {}".format(args.square, answer))
elif args.verbosity >= 1:
    print("{}^2 == {}".format(args.square, answer))
else:
    print(answer)

그러면 이렇게 됩니다:

$ python3 prog.py 4 -vvv
the square of 4 equals 16
$ python3 prog.py 4 -vvvv
the square of 4 equals 16
$ python3 prog.py 4
Traceback (most recent call last):
  File "prog.py", line 11, in <module>
    if args.verbosity >= 2:
TypeError: '>=' not supported between instances of 'NoneType' and 'int'

첫 번째 출력은 잘 동작하고, 앞에서 나온 버그를 고칩니다. 즉, 2보다 크거나 같은 (>=) 모든 값을 최대의 상세도로 취급하고 싶습니다.

세 번째 결과가 좋지 않습니다.

이 버그를 고쳐 봅시다:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("square", type=int,
                    help="display a square of a given number")
parser.add_argument("-v", "--verbosity", action="count", default=0,
                    help="increase output verbosity")
args = parser.parse_args()
answer = args.square**2
if args.verbosity >= 2:
    print("the square of {} equals {}".format(args.square, answer))
elif args.verbosity >= 1:
    print("{}^2 == {}".format(args.square, answer))
else:
    print(answer)

또 다른 키워드 default 를 소개했습니다. 다른 int 값과 비교하기 위해 0 으로 설정했습니다. 기본적으로, 옵션 인자가 지정되지 않으면 None 값을 갖게 되고, 그것은 int 값과 비교될 수 없음을 (그래서 TypeError 예외를 일으킵니다) 기억하십시오.

그리고:

$ python3 prog.py 4
16

여러분은 지금까지 배운 것만으로도 아주 멀리 갈 수 있으며, 우리는 단지 표면을 긁었을 뿐입니다. argparse 모듈은 매우 강력합니다. 이 자습서를 끝내기 전에 좀 더 탐색해 보겠습니다.

조금 더 발전시키기

우리의 작은 프로그램을 확장하여 제곱만이 아닌 다른 거듭제곱을 수행하기를 원하면 어떻게 될까요:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("x", type=int, help="the base")
parser.add_argument("y", type=int, help="the exponent")
parser.add_argument("-v", "--verbosity", action="count", default=0)
args = parser.parse_args()
answer = args.x**args.y
if args.verbosity >= 2:
    print("{} to the power {} equals {}".format(args.x, args.y, answer))
elif args.verbosity >= 1:
    print("{}^{} == {}".format(args.x, args.y, answer))
else:
    print(answer)

출력:

$ python3 prog.py
usage: prog.py [-h] [-v] x y
prog.py: error: the following arguments are required: x, y
$ python3 prog.py -h
usage: prog.py [-h] [-v] x y

positional arguments:
  x                the base
  y                the exponent

optional arguments:
  -h, --help       show this help message and exit
  -v, --verbosity
$ python3 prog.py 4 2 -v
4^2 == 16

지금까지는 표시되는 텍스트를 변경 하기 위해 상세도를 사용했습니다. 다음 예제는 대신 더 많은 텍스트를 표시하기 위해 상세도를 사용합니다:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("x", type=int, help="the base")
parser.add_argument("y", type=int, help="the exponent")
parser.add_argument("-v", "--verbosity", action="count", default=0)
args = parser.parse_args()
answer = args.x**args.y
if args.verbosity >= 2:
    print("Running '{}'".format(__file__))
if args.verbosity >= 1:
    print("{}^{} == ".format(args.x, args.y), end="")
print(answer)

출력:

$ python3 prog.py 4 2
16
$ python3 prog.py 4 2 -v
4^2 == 16
$ python3 prog.py 4 2 -vv
Running 'prog.py'
4^2 == 16

충돌하는 옵션들

지금까지 우리는 argparse.ArgumentParser 인스턴스의 두 가지 메서드로 작업 해왔습니다. 세 번째를 소개합시다, add_mutually_exclusive_group(). 이것은 서로 배타적인 옵션을 지정할 수 있도록 합니다. 새로운 기능을 더 잘 이해할 수 있도록 프로그램의 나머지 부분을 변경해 보겠습니다: --quiet 옵션을 도입하는데 --verbose 의 반대입니다:

import argparse

parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group()
group.add_argument("-v", "--verbose", action="store_true")
group.add_argument("-q", "--quiet", action="store_true")
parser.add_argument("x", type=int, help="the base")
parser.add_argument("y", type=int, help="the exponent")
args = parser.parse_args()
answer = args.x**args.y

if args.quiet:
    print(answer)
elif args.verbose:
    print("{} to the power {} equals {}".format(args.x, args.y, answer))
else:
    print("{}^{} == {}".format(args.x, args.y, answer))

프로그램은 이제 더 간단 해졌으며, 데모를 위해 일부 기능을 잃어버렸습니다. 어쨌든, 출력은 이렇습니다:

$ python3 prog.py 4 2
4^2 == 16
$ python3 prog.py 4 2 -q
16
$ python3 prog.py 4 2 -v
4 to the power 2 equals 16
$ python3 prog.py 4 2 -vq
usage: prog.py [-h] [-v | -q] x y
prog.py: error: argument -q/--quiet: not allowed with argument -v/--verbose
$ python3 prog.py 4 2 -v --quiet
usage: prog.py [-h] [-v | -q] x y
prog.py: error: argument -q/--quiet: not allowed with argument -v/--verbose

따라가기 쉽습니다. 여러분이 얻는 유연성을 볼 수 있도록 마지막 출력을 추가했습니다. 즉, 긴 형식 옵션을 짧은 형식 옵션과 섞어 쓸 수 있습니다.

결론을 내리기 전에, 여러분은 아마도 사용자들이 모를 경우를 대비해서 프로그램의 주요 목적을 알려주기를 원할 것입니다:

import argparse

parser = argparse.ArgumentParser(description="calculate X to the power of Y")
group = parser.add_mutually_exclusive_group()
group.add_argument("-v", "--verbose", action="store_true")
group.add_argument("-q", "--quiet", action="store_true")
parser.add_argument("x", type=int, help="the base")
parser.add_argument("y", type=int, help="the exponent")
args = parser.parse_args()
answer = args.x**args.y

if args.quiet:
    print(answer)
elif args.verbose:
    print("{} to the power {} equals {}".format(args.x, args.y, answer))
else:
    print("{}^{} == {}".format(args.x, args.y, answer))

사용법 텍스트의 약간의 차이점에 유의하십시오. [-v | -q] 에 주목해야 하는데, -v 나 -q 를 사용할 수 있지만 동시에 둘 다를 사용할 수는 없다는 뜻입니다:

$ python3 prog.py --help
usage: prog.py [-h] [-v | -q] x y

calculate X to the power of Y

positional arguments:
  x              the base
  y              the exponent

optional arguments:
  -h, --help     show this help message and exit
  -v, --verbose
  -q, --quiet

맺음말

argparse 모듈은 여기에 제시된 것보다 훨씬 많은 것을 제공합니다. 문서는 아주 상세하고 철저하며 예제가 풍부합니다. 이 자습서를 끝내면 압도감 없이 쉽게 소화할 수 있을 겁니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 HOWTO »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 HOWTO »

|

ipaddress 모듈에 대한 소개

저자

Peter Moody

저자

Nick Coghlan

개요

이 문서에서는 ipaddress 모듈을 간략하게 소개하고자 합니다. 주로 IP 네트워킹 용어에 익숙하지 않은 사용자를 대상으로 하지만, ipaddress가 IP 네트워크 주소 개념을 나타내는 방식에 대한 개요를 원하는 네트워크 엔지니어에게 유용할 수도 있습니다.

주소/네트워크/인터페이스 객체 만들기

ipaddress는 IP 주소를 검사하고 조작하는 모듈이기 때문에, 가장 먼저 하고 싶어 할 일은 몇몇 객체를 만드는 것입니다. ipaddress를 사용하여 문자열과 정수로 객체를 만들 수 있습니다.

IP 버전에 대한 참고 사항

특히 IP 주소 지정에 익숙하지 않은 독자는, 인터넷 프로토콜이 현재 프로토콜 버전 4에서 버전 6으로 이동하는 과정에 있음을 아는 것이 중요합니다. 이러한 전환은 주로 프로토콜 버전 4가 전 세계의 요구 사항을 처리할 수 있는 충분한 주소를 제공하지 못하기 때문에 발생하고 있습니다. 특히 인터넷에 직접 연결되는 장치의 수가 증가함에 따라 더욱더 그렇습니다.

프로토콜의 두 버전 간의 차이점에 대한 자세한 설명은 이 소개의 범위를 벗어나지만, 독자는 최소한 이 두 버전이 존재한다는 사실을 알고 있어야 하며, 때로는 한 버전이나 다른 버전을 강제로 사용해야 할 필요가 있습니다.

IP 호스트 주소

주소, 종종 “호스트 주소” 라고 하는 것은 IP 주소 지정으로 작업할 때 가장 기본 단위입니다. 주소를 만드는 가장 간단한 방법은 ipaddress.ip_address() 팩토리 함수를 사용하는 것인데, 전달된 값을 기반으로 IPv4나 IPv6 주소 중 어느 것을 만들지 자동으로 결정합니다:

>>> ipaddress.ip_address('192.0.2.1')
IPv4Address('192.0.2.1')
>>> ipaddress.ip_address('2001:DB8::1')
IPv6Address('2001:db8::1')

주소는 정수에서 직접 만들 수도 있습니다. 32비트에 들어맞는 값은 IPv4 주소로 간주합니다:

>>> ipaddress.ip_address(3221225985)
IPv4Address('192.0.2.1')
>>> ipaddress.ip_address(42540766411282592856903984951653826561)
IPv6Address('2001:db8::1')

IPv4나 IPv6 주소를 강제로 사용하려면, 해당 클래스를 직접 호출할 수 있습니다. 이것은 작은 정수를 위한 IPv6 주소 생성을 강제하는 데 특히 유용합니다:

>>> ipaddress.ip_address(1)
IPv4Address('0.0.0.1')
>>> ipaddress.IPv4Address(1)
IPv4Address('0.0.0.1')
>>> ipaddress.IPv6Address(1)
IPv6Address('::1')

네트워크 정의

호스트 주소는 대개 IP 네트워크로 그룹화되므로, ipaddress는 네트워크 정의를 만들고, 검사하고, 조작할 방법을 제공합니다. IP 네트워크 객체는 해당 네트워크의 일부인 호스트 주소의 범위를 정의하는 문자열로 만들어집니다. 이 정보의 가장 간단한 형식은 “네트워크 주소/네트워크 접두사” 쌍입니다. 접두어는 주소가 네트워크 일부인지 판별하기 위해 비교되는 선행 비트 수를 정의하고, 네트워크 주소는 그 비트들의 기대되는 값을 정의합니다.

주소의 경우, 정확한 IP 버전을 자동으로 결정하는 팩토리 함수가 제공됩니다:

>>> ipaddress.ip_network('192.0.2.0/24')
IPv4Network('192.0.2.0/24')
>>> ipaddress.ip_network('2001:db8::0/96')
IPv6Network('2001:db8::/96')

네트워크 객체는 호스트 비트가 설정될 수 없습니다. 이것의 실제 효과는 192.0.2.1/24가 네트워크를 설명하지 않는다는 것입니다. 이러한 정의는 인터페이스 객체라고 불리는데, 그 이유는 주어진 네트워크상의 컴퓨터의 네트워크 인터페이스를 기술하기 위해 네트워크상의 IP(ip-on-a-network) 표기법이 일반적으로 사용되기 때문입니다. 자세한 내용은 다음 절에서 설명합니다.

기본적으로, 호스트 비트가 설정된 네트워크 객체를 만들려고 하면 ValueError가 발생합니다. 추가 비트를 강제로 0으로 변환하도록 요청하려면, 플래그 strict=False를 생성자에 전달할 수 있습니다:

>>> ipaddress.ip_network('192.0.2.1/24')
Traceback (most recent call last):
   ...
ValueError: 192.0.2.1/24 has host bits set
>>> ipaddress.ip_network('192.0.2.1/24', strict=False)
IPv4Network('192.0.2.0/24')

문자열 형식은 유연성이 훨씬 뛰어나지만, 호스트 주소와 마찬가지로 정수로 네트워크를 정의할 수도 있습니다. 이 경우, 네트워크는 정수로 식별되는 단일 주소만 포함하는 것으로 간주하므로, 네트워크 접두사는 전체 네트워크 주소를 포함합니다:

>>> ipaddress.ip_network(3221225984)
IPv4Network('192.0.2.0/32')
>>> ipaddress.ip_network(42540766411282592856903984951653826560)
IPv6Network('2001:db8::/128')

주소와 마찬가지로, 팩토리 함수를 사용하는 대신 클래스 생성자를 직접 호출하여 특정 종류의 네트워크를 만들 수 있습니다.

호스트 인터페이스

위에서 언급했듯이, 특정 네트워크상의 주소를 설명해야 하는 경우, 주소로도 네트워크 클래스로도 충분하지 않습니다. 192.0.2.1/24와 같은 표기법은 네트워크 엔지니어와 방화벽과 라우터 용 도구를 작성하는 사람들이 “네트워크 192.0.2.0/24 상의 호스트 192.0.2.1” 의 줄임말로 많이 사용합니다. 따라서, ipaddress는 주소를 특정 네트워크와 결합하는 혼성 클래스 집합을 제공합니다. 생성을 위한 인터페이스는 주소 부분이 네트워크 주소로 제한되지 않는 것을 제외하고는 네트워크 객체를 정의하는 것과 같습니다.

>>> ipaddress.ip_interface('192.0.2.1/24')
IPv4Interface('192.0.2.1/24')
>>> ipaddress.ip_interface('2001:db8::1/96')
IPv6Interface('2001:db8::1/96')

정수 입력이 받아들여지고 (네트워크처럼), 특정 IP 버전의 사용은 관련 생성자를 직접 호출함으로써 강제될 수 있습니다.

주소/네트워크/인터페이스 객체 검사

여러분은 IPv(4|6)(Address|Network|Interface) 객체를 만드는 데 어려움을 겪었다면, 아마도 이에 대한 정보를 얻고 자 할 것입니다. ipaddress는 이 작업을 쉽고 직관적으로 만들려고 합니다.

IP 버전 추출하기:

>>> addr4 = ipaddress.ip_address('192.0.2.1')
>>> addr6 = ipaddress.ip_address('2001:db8::1')
>>> addr6.version
6
>>> addr4.version
4

인터페이스에서 네트워크 얻기:

>>> host4 = ipaddress.ip_interface('192.0.2.1/24')
>>> host4.network
IPv4Network('192.0.2.0/24')
>>> host6 = ipaddress.ip_interface('2001:db8::1/96')
>>> host6.network
IPv6Network('2001:db8::/96')

네트워크에 있는 개별 주소의 개수 찾기:

>>> net4 = ipaddress.ip_network('192.0.2.0/24')
>>> net4.num_addresses
256
>>> net6 = ipaddress.ip_network('2001:db8::0/96')
>>> net6.num_addresses
4294967296

네트워크에서 “사용 가능한” 주소 이터레이트하기:

>>> net4 = ipaddress.ip_network('192.0.2.0/24')
>>> for x in net4.hosts():
...     print(x)
192.0.2.1
192.0.2.2
192.0.2.3
192.0.2.4
...
192.0.2.252
192.0.2.253
192.0.2.254

넷 마스크(netmask)(즉, 네트워크 접두사에 해당하는 비트들)나 호스트 마스크(hostmask)(넷 마스크에 포함되지 않은 비트들) 얻기:

>>> net4 = ipaddress.ip_network('192.0.2.0/24')
>>> net4.netmask
IPv4Address('255.255.255.0')
>>> net4.hostmask
IPv4Address('0.0.0.255')
>>> net6 = ipaddress.ip_network('2001:db8::0/96')
>>> net6.netmask
IPv6Address('ffff:ffff:ffff:ffff:ffff:ffff::')
>>> net6.hostmask
IPv6Address('::ffff:ffff')

주소를 펼치거나 압축하기:

>>> addr6.exploded
'2001:0db8:0000:0000:0000:0000:0000:0001'
>>> addr6.compressed
'2001:db8::1'
>>> net6.exploded
'2001:0db8:0000:0000:0000:0000:0000:0000/96'
>>> net6.compressed
'2001:db8::/96'

IPv4는 펼치기와 압축을 지원하지 않지만, 연관된 객체는 여전히 관련 프로퍼티를 제공하므로 버전 중립적인 코드가 IPv4 주소를 올바르게 처리하면서도 IPv6 주소에 대해 가장 간결하거나 가장 자세한 형식을 쉽게 사용할 수 있습니다.

주소 리스트로서의 네트워크

네트워크를 리스트로 취급하는 것이 때로 유용합니다. 즉, 다음과 같이 인덱싱할 수 있습니다:

>>> net4[1]
IPv4Address('192.0.2.1')
>>> net4[-1]
IPv4Address('192.0.2.255')
>>> net6[1]
IPv6Address('2001:db8::1')
>>> net6[-1]
IPv6Address('2001:db8::ffff:ffff')

이것은 또한 네트워크 객체가 다음과 같은 리스트 멤버십 테스트 문법을 사용하는 데 적합하다는 것을 의미합니다:

if address in network:
    # do something

포함 테스트는 네트워크 접두어를 기반으로 효율적으로 수행됩니다:

>>> addr4 = ipaddress.ip_address('192.0.2.1')
>>> addr4 in ipaddress.ip_network('192.0.2.0/24')
True
>>> addr4 in ipaddress.ip_network('192.0.3.0/24')
False

비교

ipaddress는 의미가 있는 곳에서 객체를 비교하는 간단하고 직관적인 방법을 제공합니다:

>>> ipaddress.ip_address('192.0.2.1') < ipaddress.ip_address('192.0.2.2')
True

다른 버전이나 다른 형의 객체를 비교하려고 하면 TypeError 예외가 발생합니다.

다른 모듈과 함께 IP 주소 사용하기

IP 주소를 사용하는 다른 모듈(가령 socket)은 일반적으로 이 모듈의 객체를 직접 받아들이지 않습니다. 대신, 다른 모듈이 받아들일 수 있는 정수나 문자열로 강제 변환되어야 합니다:

>>> addr4 = ipaddress.ip_address('192.0.2.1')
>>> str(addr4)
'192.0.2.1'
>>> int(addr4)
3221225985

인스턴스 생성 실패 시 세부 사항 가져오기

버전에 구애받지 않는 팩토리 함수를 사용하여 주소/네트워크/인터페이스 객체를 만들 때, 단순히 전달된 값이 해당 형의 객체로 인식되지 않는다는 일반 에러 메시지와 함께 에러가 ValueError로 보고됩니다. 구체적인 에러가 없는 이유는 거부된 이유에 대한 자세한 정보를 제공하기 위해서는 값이 IPv4나 IPv6 중 어는 것으로 가정되는지를 알아야 하기 때문입니다.

이 추가 세부 정보를 액세스하는 것이 유용한 사용 사례를 지원하기 위해, 개별 클래스 생성자는 실제로 ValueError 서브 클래스 ipaddress.AddressValueError와 ipaddress.NetmaskValueError를 발생시켜 정의의 어느 부분에서 구문 분석하는 데 실패했는지 정확히 가리킵니다.

에러 메시지는 클래스 생성자를 직접 사용할 때 훨씬 자세해집니다. 예를 들어:

>>> ipaddress.ip_address("192.168.0.256")
Traceback (most recent call last):
  ...
ValueError: '192.168.0.256' does not appear to be an IPv4 or IPv6 address
>>> ipaddress.IPv4Address("192.168.0.256")
Traceback (most recent call last):
  ...
ipaddress.AddressValueError: Octet 256 (> 255) not permitted in '192.168.0.256'

>>> ipaddress.ip_network("192.168.0.1/64")
Traceback (most recent call last):
  ...
ValueError: '192.168.0.1/64' does not appear to be an IPv4 or IPv6 network
>>> ipaddress.IPv4Network("192.168.0.1/64")
Traceback (most recent call last):
  ...
ipaddress.NetmaskValueError: '64' is not a valid netmask

그러나, 두 모듈 특정 예외 모두 부모 클래스로 ValueError를 가지므로, 특정 유형의 에러에 관심이 없다면, 여전히 다음과 같은 코드를 작성할 수 있습니다:

try:
    network = ipaddress.IPv4Network(address)
except ValueError:
    print('address/netmask is invalid for IPv4:', address)

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 HOWTO »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 HOWTO »

|

Argument Clinic How-To

author

Larry Hastings

Abstract

Argument Clinic is a preprocessor for CPython C files. Its purpose is to automate all the boilerplate involved with writing argument parsing code for “builtins”. This document shows you how to convert your first C function to work with Argument Clinic, and then introduces some advanced topics on Argument Clinic usage.

Currently Argument Clinic is considered internal-only for CPython. Its use is not supported for files outside CPython, and no guarantees are made regarding backwards compatibility for future versions. In other words: if you maintain an external C extension for CPython, you’re welcome to experiment with Argument Clinic in your own code. But the version of Argument Clinic that ships with the next version of CPython could be totally incompatible and break all your code.

The Goals Of Argument Clinic

Argument Clinic’s primary goal is to take over responsibility for all argument parsing code inside CPython. This means that, when you convert a function to work with Argument Clinic, that function should no longer do any of its own argument parsing—the code generated by Argument Clinic should be a “black box” to you, where CPython calls in at the top, and your code gets called at the bottom, with PyObject *args (and maybe PyObject *kwargs) magically converted into the C variables and types you need.

In order for Argument Clinic to accomplish its primary goal, it must be easy to use. Currently, working with CPython’s argument parsing library is a chore, requiring maintaining redundant information in a surprising number of places. When you use Argument Clinic, you don’t have to repeat yourself.

Obviously, no one would want to use Argument Clinic unless it’s solving their problem—and without creating new problems of its own. So it’s paramount that Argument Clinic generate correct code. It’d be nice if the code was faster, too, but at the very least it should not introduce a major speed regression. (Eventually Argument Clinic should make a major speedup possible—we could rewrite its code generator to produce tailor-made argument parsing code, rather than calling the general-purpose CPython argument parsing library. That would make for the fastest argument parsing possible!)

Additionally, Argument Clinic must be flexible enough to work with any approach to argument parsing. Python has some functions with some very strange parsing behaviors; Argument Clinic’s goal is to support all of them.

Finally, the original motivation for Argument Clinic was to provide introspection “signatures” for CPython builtins. It used to be, the introspection query functions would throw an exception if you passed in a builtin. With Argument Clinic, that’s a thing of the past!

One idea you should keep in mind, as you work with Argument Clinic: the more information you give it, the better job it’ll be able to do. Argument Clinic is admittedly relatively simple right now. But as it evolves it will get more sophisticated, and it should be able to do many interesting and smart things with all the information you give it.

Basic Concepts And Usage

Argument Clinic ships with CPython; you’ll find it in Tools/clinic/clinic.py. If you run that script, specifying a C file as an argument:

$ python3 Tools/clinic/clinic.py foo.c

Argument Clinic will scan over the file looking for lines that look exactly like this:

/*[clinic input]

When it finds one, it reads everything up to a line that looks exactly like this:

[clinic start generated code]*/

Everything in between these two lines is input for Argument Clinic. All of these lines, including the beginning and ending comment lines, are collectively called an Argument Clinic “block”.

When Argument Clinic parses one of these blocks, it generates output. This output is rewritten into the C file immediately after the block, followed by a comment containing a checksum. The Argument Clinic block now looks like this:

/*[clinic input]
... clinic input goes here ...
[clinic start generated code]*/
... clinic output goes here ...
/*[clinic end generated code: checksum=...]*/

If you run Argument Clinic on the same file a second time, Argument Clinic will discard the old output and write out the new output with a fresh checksum line. However, if the input hasn’t changed, the output won’t change either.

You should never modify the output portion of an Argument Clinic block. Instead, change the input until it produces the output you want. (That’s the purpose of the checksum—to detect if someone changed the output, as these edits would be lost the next time Argument Clinic writes out fresh output.)

For the sake of clarity, here’s the terminology we’ll use with Argument Clinic:

The first line of the comment (/*[clinic input]) is the start line.

The last line of the initial comment ([clinic start generated code]*/) is the end line.

The last line (/*[clinic end generated code: checksum=...]*/) is the checksum line.

In between the start line and the end line is the input.

In between the end line and the checksum line is the output.

All the text collectively, from the start line to the checksum line inclusively, is the block. (A block that hasn’t been successfully processed by Argument Clinic yet doesn’t have output or a checksum line, but it’s still considered a block.)

Converting Your First Function

The best way to get a sense of how Argument Clinic works is to convert a function to work with it. Here, then, are the bare minimum steps you’d need to follow to convert a function to work with Argument Clinic. Note that for code you plan to check in to CPython, you really should take the conversion farther, using some of the advanced concepts you’ll see later on in the document (like “return converters” and “self converters”). But we’ll keep it simple for this walkthrough so you can learn.

Let’s dive in!

Make sure you’re working with a freshly updated checkout of the CPython trunk.

Find a Python builtin that calls either PyArg_ParseTuple() or PyArg_ParseTupleAndKeywords(), and hasn’t been converted to work with Argument Clinic yet. For my example I’m using _pickle.Pickler.dump().

If the call to the PyArg_Parse function uses any of the following format units:

O&
O!
es
es#
et
et#

or if it has multiple calls to PyArg_ParseTuple(), you should choose a different function. Argument Clinic does support all of these scenarios. But these are advanced topics—let’s do something simpler for your first function.

Also, if the function has multiple calls to PyArg_ParseTuple() or PyArg_ParseTupleAndKeywords() where it supports different types for the same argument, or if the function uses something besides PyArg_Parse functions to parse its arguments, it probably isn’t suitable for conversion to Argument Clinic. Argument Clinic doesn’t support generic functions or polymorphic parameters.

Add the following boilerplate above the function, creating our block:

/*[clinic input]
[clinic start generated code]*/

Cut the docstring and paste it in between the [clinic] lines, removing all the junk that makes it a properly quoted C string. When you’re done you should have just the text, based at the left margin, with no line wider than 80 characters. (Argument Clinic will preserve indents inside the docstring.)

If the old docstring had a first line that looked like a function signature, throw that line away. (The docstring doesn’t need it anymore—when you use help() on your builtin in the future, the first line will be built automatically based on the function’s signature.)

Sample:

/*[clinic input]
Write a pickled representation of obj to the open file.
[clinic start generated code]*/

If your docstring doesn’t have a “summary” line, Argument Clinic will complain. So let’s make sure it has one. The “summary” line should be a paragraph consisting of a single 80-column line at the beginning of the docstring.

(Our example docstring consists solely of a summary line, so the sample code doesn’t have to change for this step.)

Above the docstring, enter the name of the function, followed by a blank line. This should be the Python name of the function, and should be the full dotted path to the function—it should start with the name of the module, include any sub-modules, and if the function is a method on a class it should include the class name too.

Sample:

/*[clinic input]
_pickle.Pickler.dump

Write a pickled representation of obj to the open file.
[clinic start generated code]*/

If this is the first time that module or class has been used with Argument Clinic in this C file, you must declare the module and/or class. Proper Argument Clinic hygiene prefers declaring these in a separate block somewhere near the top of the C file, in the same way that include files and statics go at the top. (In our sample code we’ll just show the two blocks next to each other.)

The name of the class and module should be the same as the one seen by Python. Check the name defined in the PyModuleDef or PyTypeObject as appropriate.

When you declare a class, you must also specify two aspects of its type in C: the type declaration you’d use for a pointer to an instance of this class, and a pointer to the PyTypeObject for this class.

Sample:

/*[clinic input]
module _pickle
class _pickle.Pickler "PicklerObject *" "&Pickler_Type"
[clinic start generated code]*/

/*[clinic input]
_pickle.Pickler.dump

Write a pickled representation of obj to the open file.
[clinic start generated code]*/

Declare each of the parameters to the function. Each parameter should get its own line. All the parameter lines should be indented from the function name and the docstring.

The general form of these parameter lines is as follows:

name_of_parameter: converter

If the parameter has a default value, add that after the converter:

name_of_parameter: converter = default_value

Argument Clinic’s support for “default values” is quite sophisticated; please see the section below on default values for more information.

Add a blank line below the parameters.

What’s a “converter”? It establishes both the type of the variable used in C, and the method to convert the Python value into a C value at runtime. For now you’re going to use what’s called a “legacy converter”—a convenience syntax intended to make porting old code into Argument Clinic easier.

For each parameter, copy the “format unit” for that parameter from the PyArg_Parse() format argument and specify that as its converter, as a quoted string. (“format unit” is the formal name for the one-to-three character substring of the format parameter that tells the argument parsing function what the type of the variable is and how to convert it. For more on format units please see Parsing arguments and building values.)

For multicharacter format units like z#, use the entire two-or-three character string.

Sample:

 /*[clinic input]
 module _pickle
 class _pickle.Pickler "PicklerObject *" "&Pickler_Type"
 [clinic start generated code]*/

 /*[clinic input]
 _pickle.Pickler.dump

    obj: 'O'

Write a pickled representation of obj to the open file.
[clinic start generated code]*/

If your function has | in the format string, meaning some parameters have default values, you can ignore it. Argument Clinic infers which parameters are optional based on whether or not they have default values.

If your function has $ in the format string, meaning it takes keyword-only arguments, specify * on a line by itself before the first keyword-only argument, indented the same as the parameter lines.

(_pickle.Pickler.dump has neither, so our sample is unchanged.)

If the existing C function calls PyArg_ParseTuple() (as opposed to PyArg_ParseTupleAndKeywords()), then all its arguments are positional-only.

To mark all parameters as positional-only in Argument Clinic, add a / on a line by itself after the last parameter, indented the same as the parameter lines.

Currently this is all-or-nothing; either all parameters are positional-only, or none of them are. (In the future Argument Clinic may relax this restriction.)

Sample:

/*[clinic input]
module _pickle
class _pickle.Pickler "PicklerObject *" "&Pickler_Type"
[clinic start generated code]*/

/*[clinic input]
_pickle.Pickler.dump

    obj: 'O'
    /

Write a pickled representation of obj to the open file.
[clinic start generated code]*/

It’s helpful to write a per-parameter docstring for each parameter. But per-parameter docstrings are optional; you can skip this step if you prefer.

Here’s how to add a per-parameter docstring. The first line of the per-parameter docstring must be indented further than the parameter definition. The left margin of this first line establishes the left margin for the whole per-parameter docstring; all the text you write will be outdented by this amount. You can write as much text as you like, across multiple lines if you wish.

Sample:

/*[clinic input]
module _pickle
class _pickle.Pickler "PicklerObject *" "&Pickler_Type"
[clinic start generated code]*/

/*[clinic input]
_pickle.Pickler.dump

    obj: 'O'
        The object to be pickled.
    /

Write a pickled representation of obj to the open file.
[clinic start generated code]*/

Save and close the file, then run Tools/clinic/clinic.py on it. With luck everything worked—your block now has output, and a .c.h file has been generated! Reopen the file in your text editor to see:

/*[clinic input]
_pickle.Pickler.dump

    obj: 'O'
        The object to be pickled.
    /

Write a pickled representation of obj to the open file.
[clinic start generated code]*/

static PyObject *
_pickle_Pickler_dump(PicklerObject *self, PyObject *obj)
/*[clinic end generated code: output=87ecad1261e02ac7 input=552eb1c0f52260d9]*/

Obviously, if Argument Clinic didn’t produce any output, it’s because it found an error in your input. Keep fixing your errors and retrying until Argument Clinic processes your file without complaint.

For readability, most of the glue code has been generated to a .c.h file. You’ll need to include that in your original .c file, typically right after the clinic module block:

#include "clinic/_pickle.c.h"

Double-check that the argument-parsing code Argument Clinic generated looks basically the same as the existing code.

First, ensure both places use the same argument-parsing function. The existing code must call either PyArg_ParseTuple() or PyArg_ParseTupleAndKeywords(); ensure that the code generated by Argument Clinic calls the exact same function.

Second, the format string passed in to PyArg_ParseTuple() or PyArg_ParseTupleAndKeywords() should be exactly the same as the hand-written one in the existing function, up to the colon or semi-colon.

(Argument Clinic always generates its format strings with a : followed by the name of the function. If the existing code’s format string ends with ;, to provide usage help, this change is harmless—don’t worry about it.)

Third, for parameters whose format units require two arguments (like a length variable, or an encoding string, or a pointer to a conversion function), ensure that the second argument is exactly the same between the two invocations.

Fourth, inside the output portion of the block you’ll find a preprocessor macro defining the appropriate static PyMethodDef structure for this builtin:

#define __PICKLE_PICKLER_DUMP_METHODDEF    \
{"dump", (PyCFunction)__pickle_Pickler_dump, METH_O, __pickle_Pickler_dump__doc__},

This static structure should be exactly the same as the existing static PyMethodDef structure for this builtin.

If any of these items differ in any way, adjust your Argument Clinic function specification and rerun Tools/clinic/clinic.py until they are the same.

Notice that the last line of its output is the declaration of your “impl” function. This is where the builtin’s implementation goes. Delete the existing prototype of the function you’re modifying, but leave the opening curly brace. Now delete its argument parsing code and the declarations of all the variables it dumps the arguments into. Notice how the Python arguments are now arguments to this impl function; if the implementation used different names for these variables, fix it.

Let’s reiterate, just because it’s kind of weird. Your code should now look like this:

static return_type
your_function_impl(...)
/*[clinic end generated code: checksum=...]*/
{
...

Argument Clinic generated the checksum line and the function prototype just above it. You should write the opening (and closing) curly braces for the function, and the implementation inside.

Sample:

/*[clinic input]
module _pickle
class _pickle.Pickler "PicklerObject *" "&Pickler_Type"
[clinic start generated code]*/
/*[clinic end generated code: checksum=da39a3ee5e6b4b0d3255bfef95601890afd80709]*/

/*[clinic input]
_pickle.Pickler.dump

    obj: 'O'
        The object to be pickled.
    /

Write a pickled representation of obj to the open file.
[clinic start generated code]*/

PyDoc_STRVAR(__pickle_Pickler_dump__doc__,
"Write a pickled representation of obj to the open file.\n"
"\n"
...
static PyObject *
_pickle_Pickler_dump_impl(PicklerObject *self, PyObject *obj)
/*[clinic end generated code: checksum=3bd30745bf206a48f8b576a1da3d90f55a0a4187]*/
{
    /* Check whether the Pickler was initialized correctly (issue3664).
       Developers often forget to call __init__() in their subclasses, which
       would trigger a segfault without this check. */
    if (self->write == NULL) {
        PyErr_Format(PicklingError,
                     "Pickler.__init__() was not called by %s.__init__()",
                     Py_TYPE(self)->tp_name);
        return NULL;
    }

    if (_Pickler_ClearBuffer(self) < 0)
        return NULL;

    ...

Remember the macro with the PyMethodDef structure for this function? Find the existing PyMethodDef structure for this function and replace it with a reference to the macro. (If the builtin is at module scope, this will probably be very near the end of the file; if the builtin is a class method, this will probably be below but relatively near to the implementation.)

Note that the body of the macro contains a trailing comma. So when you replace the existing static PyMethodDef structure with the macro, don’t add a comma to the end.

Sample:

static struct PyMethodDef Pickler_methods[] = {
    __PICKLE_PICKLER_DUMP_METHODDEF
    __PICKLE_PICKLER_CLEAR_MEMO_METHODDEF
    {NULL, NULL}                /* sentinel */
};

Compile, then run the relevant portions of the regression-test suite. This change should not introduce any new compile-time warnings or errors, and there should be no externally-visible change to Python’s behavior.

Well, except for one difference: inspect.signature() run on your function should now provide a valid signature!

Congratulations, you’ve ported your first function to work with Argument Clinic!

Advanced Topics

Now that you’ve had some experience working with Argument Clinic, it’s time for some advanced topics.

Symbolic default values

The default value you provide for a parameter can’t be any arbitrary expression. Currently the following are explicitly supported:

Numeric constants (integer and float)

String constants

True, False, and None

Simple symbolic constants like sys.maxsize, which must start with the name of the module

In case you’re curious, this is implemented in from_builtin() in Lib/inspect.py.

(In the future, this may need to get even more elaborate, to allow full expressions like CONSTANT - 1.)

Renaming the C functions and variables generated by Argument Clinic

Argument Clinic automatically names the functions it generates for you. Occasionally this may cause a problem, if the generated name collides with the name of an existing C function. There’s an easy solution: override the names used for the C functions. Just add the keyword "as" to your function declaration line, followed by the function name you wish to use. Argument Clinic will use that function name for the base (generated) function, then add "_impl" to the end and use that for the name of the impl function.

For example, if we wanted to rename the C function names generated for pickle.Pickler.dump, it’d look like this:

/*[clinic input]
pickle.Pickler.dump as pickler_dumper

...

The base function would now be named pickler_dumper(), and the impl function would now be named pickler_dumper_impl().

Similarly, you may have a problem where you want to give a parameter a specific Python name, but that name may be inconvenient in C. Argument Clinic allows you to give a parameter different names in Python and in C, using the same "as" syntax:

/*[clinic input]
pickle.Pickler.dump

    obj: object
    file as file_obj: object
    protocol: object = NULL
    *
    fix_imports: bool = True

Here, the name used in Python (in the signature and the keywords array) would be file, but the C variable would be named file_obj.

You can use this to rename the self parameter too!

Converting functions using PyArg_UnpackTuple

To convert a function parsing its arguments with PyArg_UnpackTuple(), simply write out all the arguments, specifying each as an object. You may specify the type argument to cast the type as appropriate. All arguments should be marked positional-only (add a / on a line by itself after the last argument).

Currently the generated code will use PyArg_ParseTuple(), but this will change soon.

Optional Groups

Some legacy functions have a tricky approach to parsing their arguments: they count the number of positional arguments, then use a switch statement to call one of several different PyArg_ParseTuple() calls depending on how many positional arguments there are. (These functions cannot accept keyword-only arguments.) This approach was used to simulate optional arguments back before PyArg_ParseTupleAndKeywords() was created.

While functions using this approach can often be converted to use PyArg_ParseTupleAndKeywords(), optional arguments, and default values, it’s not always possible. Some of these legacy functions have behaviors PyArg_ParseTupleAndKeywords() doesn’t directly support. The most obvious example is the builtin function range(), which has an optional argument on the left side of its required argument! Another example is curses.window.addch(), which has a group of two arguments that must always be specified together. (The arguments are called x and y; if you call the function passing in x, you must also pass in y—and if you don’t pass in x you may not pass in y either.)

In any case, the goal of Argument Clinic is to support argument parsing for all existing CPython builtins without changing their semantics. Therefore Argument Clinic supports this alternate approach to parsing, using what are called optional groups. Optional groups are groups of arguments that must all be passed in together. They can be to the left or the right of the required arguments. They can only be used with positional-only parameters.

참고

Optional groups are only intended for use when converting functions that make multiple calls to PyArg_ParseTuple()! Functions that use any other approach for parsing arguments should almost never be converted to Argument Clinic using optional groups. Functions using optional groups currently cannot have accurate signatures in Python, because Python just doesn’t understand the concept. Please avoid using optional groups wherever possible.

To specify an optional group, add a [ on a line by itself before the parameters you wish to group together, and a ] on a line by itself after these parameters. As an example, here’s how curses.window.addch uses optional groups to make the first two parameters and the last parameter optional:

/*[clinic input]

curses.window.addch

    [
    x: int
      X-coordinate.
    y: int
      Y-coordinate.
    ]

    ch: object
      Character to add.

    [
    attr: long
      Attributes for the character.
    ]
    /

...

Notes:

For every optional group, one additional parameter will be passed into the impl function representing the group. The parameter will be an int named group_{direction}_{number}, where {direction} is either right or left depending on whether the group is before or after the required parameters, and {number} is a monotonically increasing number (starting at 1) indicating how far away the group is from the required parameters. When the impl is called, this parameter will be set to zero if this group was unused, and set to non-zero if this group was used. (By used or unused, I mean whether or not the parameters received arguments in this invocation.)

If there are no required arguments, the optional groups will behave as if they’re to the right of the required arguments.

In the case of ambiguity, the argument parsing code favors parameters on the left (before the required parameters).

Optional groups can only contain positional-only parameters.

Optional groups are only intended for legacy code. Please do not use optional groups for new code.

Using real Argument Clinic converters, instead of “legacy converters”

To save time, and to minimize how much you need to learn to achieve your first port to Argument Clinic, the walkthrough above tells you to use “legacy converters”. “Legacy converters” are a convenience, designed explicitly to make porting existing code to Argument Clinic easier. And to be clear, their use is acceptable when porting code for Python 3.4.

However, in the long term we probably want all our blocks to use Argument Clinic’s real syntax for converters. Why? A couple reasons:

The proper converters are far easier to read and clearer in their intent.

There are some format units that are unsupported as “legacy converters”, because they require arguments, and the legacy converter syntax doesn’t support specifying arguments.

In the future we may have a new argument parsing library that isn’t restricted to what PyArg_ParseTuple() supports; this flexibility won’t be available to parameters using legacy converters.

Therefore, if you don’t mind a little extra effort, please use the normal converters instead of legacy converters.

In a nutshell, the syntax for Argument Clinic (non-legacy) converters looks like a Python function call. However, if there are no explicit arguments to the function (all functions take their default values), you may omit the parentheses. Thus bool and bool() are exactly the same converters.

All arguments to Argument Clinic converters are keyword-only. All Argument Clinic converters accept the following arguments:

c_default

The default value for this parameter when defined in C. Specifically, this will be the initializer for the variable declared in the “parse function”. See the section on default values for how to use this. Specified as a string.

annotation

The annotation value for this parameter. Not currently supported, because PEP 8 mandates that the Python library may not use annotations.

In addition, some converters accept additional arguments. Here is a list of these arguments, along with their meanings:

accept

A set of Python types (and possibly pseudo-types); this restricts the allowable Python argument to values of these types. (This is not a general-purpose facility; as a rule it only supports specific lists of types as shown in the legacy converter table.)

To accept None, add NoneType to this set.

bitwise

Only supported for unsigned integers. The native integer value of this Python argument will be written to the parameter without any range checking, even for negative values.

converter

Only supported by the object converter. Specifies the name of a C “converter function” to use to convert this object to a native type.

encoding

Only supported for strings. Specifies the encoding to use when converting this string from a Python str (Unicode) value into a C char * value.

subclass_of

Only supported for the object converter. Requires that the Python value be a subclass of a Python type, as expressed in C.

type

Only supported for the object and self converters. Specifies the C type that will be used to declare the variable. Default value is "PyObject *".

zeroes

Only supported for strings. If true, embedded NUL bytes ('\\0') are permitted inside the value. The length of the string will be passed in to the impl function, just after the string parameter, as a parameter named <parameter_name>_length.

Please note, not every possible combination of arguments will work. Usually these arguments are implemented by specific PyArg_ParseTuple format units, with specific behavior. For example, currently you cannot call unsigned_short without also specifying bitwise=True. Although it’s perfectly reasonable to think this would work, these semantics don’t map to any existing format unit. So Argument Clinic doesn’t support it. (Or, at least, not yet.)

Below is a table showing the mapping of legacy converters into real Argument Clinic converters. On the left is the legacy converter, on the right is the text you’d replace it with.

'B'

unsigned_char(bitwise=True)

'b'

unsigned_char

'c'

char

'C'

int(accept={str})

'd'

double

'D'

Py_complex

'es'

str(encoding='name_of_encoding')

'es#'

str(encoding='name_of_encoding', zeroes=True)

'et'

str(encoding='name_of_encoding', accept={bytes, bytearray, str})

'et#'

str(encoding='name_of_encoding', accept={bytes, bytearray, str}, zeroes=True)

'f'

float

'h'

short

'H'

unsigned_short(bitwise=True)

'i'

int

'I'

unsigned_int(bitwise=True)

'k'

unsigned_long(bitwise=True)

'K'

unsigned_long_long(bitwise=True)

'l'

long

'L'

long long

'n'

Py_ssize_t

'O'

object

'O!'

object(subclass_of='&PySomething_Type')

'O&'

object(converter='name_of_c_function')

'p'

bool

'S'

PyBytesObject

's'

str

's#'

str(zeroes=True)

's*'

Py_buffer(accept={buffer, str})

'U'

unicode

'u'

Py_UNICODE

'u#'

Py_UNICODE(zeroes=True)

'w*'

Py_buffer(accept={rwbuffer})

'Y'

PyByteArrayObject

'y'

str(accept={bytes})

'y#'

str(accept={robuffer}, zeroes=True)

'y*'

Py_buffer

'Z'

Py_UNICODE(accept={str, NoneType})

'Z#'

Py_UNICODE(accept={str, NoneType}, zeroes=True)

'z'

str(accept={str, NoneType})

'z#'

str(accept={str, NoneType}, zeroes=True)

'z*'

Py_buffer(accept={buffer, str, NoneType})

As an example, here’s our sample pickle.Pickler.dump using the proper converter:

/*[clinic input]
pickle.Pickler.dump

    obj: object
        The object to be pickled.
    /

Write a pickled representation of obj to the open file.
[clinic start generated code]*/

Argument Clinic will show you all the converters it has available. For each converter it’ll show you all the parameters it accepts, along with the default value for each parameter. Just run Tools/clinic/clinic.py --converters to see the full list.

Py_buffer

When using the Py_buffer converter (or the 's*', 'w*', '*y', or 'z*' legacy converters), you must not call PyBuffer_Release() on the provided buffer. Argument Clinic generates code that does it for you (in the parsing function).

Advanced converters

Remember those format units you skipped for your first time because they were advanced? Here’s how to handle those too.

The trick is, all those format units take arguments—either conversion functions, or types, or strings specifying an encoding. (But “legacy converters” don’t support arguments. That’s why we skipped them for your first function.) The argument you specified to the format unit is now an argument to the converter; this argument is either converter (for O&), subclass_of (for O!), or encoding (for all the format units that start with e).

When using subclass_of, you may also want to use the other custom argument for object(): type, which lets you set the type actually used for the parameter. For example, if you want to ensure that the object is a subclass of PyUnicode_Type, you probably want to use the converter object(type='PyUnicodeObject *', subclass_of='&PyUnicode_Type').

One possible problem with using Argument Clinic: it takes away some possible flexibility for the format units starting with e. When writing a PyArg_Parse call by hand, you could theoretically decide at runtime what encoding string to pass in to PyArg_ParseTuple(). But now this string must be hard-coded at Argument-Clinic-preprocessing-time. This limitation is deliberate; it made supporting this format unit much easier, and may allow for future optimizations. This restriction doesn’t seem unreasonable; CPython itself always passes in static hard-coded encoding strings for parameters whose format units start with e.

Parameter default values

Default values for parameters can be any of a number of values. At their simplest, they can be string, int, or float literals:

foo: str = "abc"
bar: int = 123
bat: float = 45.6

They can also use any of Python’s built-in constants:

yep:  bool = True
nope: bool = False
nada: object = None

There’s also special support for a default value of NULL, and for simple expressions, documented in the following sections.

The NULL default value

For string and object parameters, you can set them to None to indicate that there’s no default. However, that means the C variable will be initialized to Py_None. For convenience’s sakes, there’s a special value called NULL for just this reason: from Python’s perspective it behaves like a default value of None, but the C variable is initialized with NULL.

Expressions specified as default values

The default value for a parameter can be more than just a literal value. It can be an entire expression, using math operators and looking up attributes on objects. However, this support isn’t exactly simple, because of some non-obvious semantics.

Consider the following example:

foo: Py_ssize_t = sys.maxsize - 1

sys.maxsize can have different values on different platforms. Therefore Argument Clinic can’t simply evaluate that expression locally and hard-code it in C. So it stores the default in such a way that it will get evaluated at runtime, when the user asks for the function’s signature.

What namespace is available when the expression is evaluated? It’s evaluated in the context of the module the builtin came from. So, if your module has an attribute called “max_widgets”, you may simply use it:

foo: Py_ssize_t = max_widgets

If the symbol isn’t found in the current module, it fails over to looking in sys.modules. That’s how it can find sys.maxsize for example. (Since you don’t know in advance what modules the user will load into their interpreter, it’s best to restrict yourself to modules that are preloaded by Python itself.)

Evaluating default values only at runtime means Argument Clinic can’t compute the correct equivalent C default value. So you need to tell it explicitly. When you use an expression, you must also specify the equivalent expression in C, using the c_default parameter to the converter:

foo: Py_ssize_t(c_default="PY_SSIZE_T_MAX - 1") = sys.maxsize - 1

Another complication: Argument Clinic can’t know in advance whether or not the expression you supply is valid. It parses it to make sure it looks legal, but it can’t actually know. You must be very careful when using expressions to specify values that are guaranteed to be valid at runtime!

Finally, because expressions must be representable as static C values, there are many restrictions on legal expressions. Here’s a list of Python features you’re not permitted to use:

Function calls.

Inline if statements (3 if foo else 5).

Automatic sequence unpacking (*[1, 2, 3]).

List/set/dict comprehensions and generator expressions.

Tuple/list/set/dict literals.

Using a return converter

By default the impl function Argument Clinic generates for you returns PyObject *. But your C function often computes some C type, then converts it into the PyObject * at the last moment. Argument Clinic handles converting your inputs from Python types into native C types—why not have it convert your return value from a native C type into a Python type too?

That’s what a “return converter” does. It changes your impl function to return some C type, then adds code to the generated (non-impl) function to handle converting that value into the appropriate PyObject *.

The syntax for return converters is similar to that of parameter converters. You specify the return converter like it was a return annotation on the function itself. Return converters behave much the same as parameter converters; they take arguments, the arguments are all keyword-only, and if you’re not changing any of the default arguments you can omit the parentheses.

(If you use both "as" and a return converter for your function, the "as" should come before the return converter.)

There’s one additional complication when using return converters: how do you indicate an error has occurred? Normally, a function returns a valid (non-NULL) pointer for success, and NULL for failure. But if you use an integer return converter, all integers are valid. How can Argument Clinic detect an error? Its solution: each return converter implicitly looks for a special value that indicates an error. If you return that value, and an error has been set (PyErr_Occurred() returns a true value), then the generated code will propagate the error. Otherwise it will encode the value you return like normal.

Currently Argument Clinic supports only a few return converters:

bool
int
unsigned int
long
unsigned int
size_t
Py_ssize_t
float
double
DecodeFSDefault

None of these take parameters. For the first three, return -1 to indicate error. For DecodeFSDefault, the return type is const char *; return a NULL pointer to indicate an error.

(There’s also an experimental NoneType converter, which lets you return Py_None on success or NULL on failure, without having to increment the reference count on Py_None. I’m not sure it adds enough clarity to be worth using.)

To see all the return converters Argument Clinic supports, along with their parameters (if any), just run Tools/clinic/clinic.py --converters for the full list.

Cloning existing functions

If you have a number of functions that look similar, you may be able to use Clinic’s “clone” feature. When you clone an existing function, you reuse:

its parameters, including

their names,

their converters, with all parameters,

their default values,

their per-parameter docstrings,

their kind (whether they’re positional only, positional or keyword, or keyword only), and

its return converter.

The only thing not copied from the original function is its docstring; the syntax allows you to specify a new docstring.

Here’s the syntax for cloning a function:

/*[clinic input]
module.class.new_function [as c_basename] = module.class.existing_function

Docstring for new_function goes here.
[clinic start generated code]*/

(The functions can be in different modules or classes. I wrote module.class in the sample just to illustrate that you must use the full path to both functions.)

Sorry, there’s no syntax for partially-cloning a function, or cloning a function then modifying it. Cloning is an all-or nothing proposition.

Also, the function you are cloning from must have been previously defined in the current file.

Calling Python code

The rest of the advanced topics require you to write Python code which lives inside your C file and modifies Argument Clinic’s runtime state. This is simple: you simply define a Python block.

A Python block uses different delimiter lines than an Argument Clinic function block. It looks like this:

/*[python input]
# python code goes here
[python start generated code]*/

All the code inside the Python block is executed at the time it’s parsed. All text written to stdout inside the block is redirected into the “output” after the block.

As an example, here’s a Python block that adds a static integer variable to the C code:

/*[python input]
print('static int __ignored_unused_variable__ = 0;')
[python start generated code]*/
static int __ignored_unused_variable__ = 0;
/*[python checksum:...]*/

Using a “self converter”

Argument Clinic automatically adds a “self” parameter for you using a default converter. It automatically sets the type of this parameter to the “pointer to an instance” you specified when you declared the type. However, you can override Argument Clinic’s converter and specify one yourself. Just add your own self parameter as the first parameter in a block, and ensure that its converter is an instance of self_converter or a subclass thereof.

What’s the point? This lets you override the type of self, or give it a different default name.

How do you specify the custom type you want to cast self to? If you only have one or two functions with the same type for self, you can directly use Argument Clinic’s existing self converter, passing in the type you want to use as the type parameter:

/*[clinic input]

_pickle.Pickler.dump

  self: self(type="PicklerObject *")
  obj: object
  /

Write a pickled representation of the given object to the open file.
[clinic start generated code]*/

On the other hand, if you have a lot of functions that will use the same type for self, it’s best to create your own converter, subclassing self_converter but overwriting the type member:

/*[python input]
class PicklerObject_converter(self_converter):
    type = "PicklerObject *"
[python start generated code]*/

/*[clinic input]

_pickle.Pickler.dump

  self: PicklerObject
  obj: object
  /

Write a pickled representation of the given object to the open file.
[clinic start generated code]*/

Writing a custom converter

As we hinted at in the previous section… you can write your own converters! A converter is simply a Python class that inherits from CConverter. The main purpose of a custom converter is if you have a parameter using the O& format unit—parsing this parameter means calling a PyArg_ParseTuple() “converter function”.

Your converter class should be named *something*_converter. If the name follows this convention, then your converter class will be automatically registered with Argument Clinic; its name will be the name of your class with the _converter suffix stripped off. (This is accomplished with a metaclass.)

You shouldn’t subclass CConverter.__init__. Instead, you should write a converter_init() function. converter_init() always accepts a self parameter; after that, all additional parameters must be keyword-only. Any arguments passed in to the converter in Argument Clinic will be passed along to your converter_init().

There are some additional members of CConverter you may wish to specify in your subclass. Here’s the current list:

type

The C type to use for this variable. type should be a Python string specifying the type, e.g. int. If this is a pointer type, the type string should end with ' *'.

default

The Python default value for this parameter, as a Python value. Or the magic value unspecified if there is no default.

py_default

default as it should appear in Python code, as a string. Or None if there is no default.

c_default

default as it should appear in C code, as a string. Or None if there is no default.

c_ignored_default

The default value used to initialize the C variable when there is no default, but not specifying a default may result in an “uninitialized variable” warning. This can easily happen when using option groups—although properly-written code will never actually use this value, the variable does get passed in to the impl, and the C compiler will complain about the “use” of the uninitialized value. This value should always be a non-empty string.

converter

The name of the C converter function, as a string.

impl_by_reference

A boolean value. If true, Argument Clinic will add a & in front of the name of the variable when passing it into the impl function.

parse_by_reference

A boolean value. If true, Argument Clinic will add a & in front of the name of the variable when passing it into PyArg_ParseTuple().

Here’s the simplest example of a custom converter, from Modules/zlibmodule.c:

/*[python input]

class ssize_t_converter(CConverter):
    type = 'Py_ssize_t'
    converter = 'ssize_t_converter'

[python start generated code]*/
/*[python end generated code: output=da39a3ee5e6b4b0d input=35521e4e733823c7]*/

This block adds a converter to Argument Clinic named ssize_t. Parameters declared as ssize_t will be declared as type Py_ssize_t, and will be parsed by the 'O&' format unit, which will call the ssize_t_converter converter function. ssize_t variables automatically support default values.

More sophisticated custom converters can insert custom C code to handle initialization and cleanup. You can see more examples of custom converters in the CPython source tree; grep the C files for the string CConverter.

Writing a custom return converter

Writing a custom return converter is much like writing a custom converter. Except it’s somewhat simpler, because return converters are themselves much simpler.

Return converters must subclass CReturnConverter. There are no examples yet of custom return converters, because they are not widely used yet. If you wish to write your own return converter, please read Tools/clinic/clinic.py, specifically the implementation of CReturnConverter and all its subclasses.

METH_O and METH_NOARGS

To convert a function using METH_O, make sure the function’s single argument is using the object converter, and mark the arguments as positional-only:

/*[clinic input]
meth_o_sample

     argument: object
     /
[clinic start generated code]*/

To convert a function using METH_NOARGS, just don’t specify any arguments.

You can still use a self converter, a return converter, and specify a type argument to the object converter for METH_O.

tp_new and tp_init functions

You can convert tp_new and tp_init functions. Just name them __new__ or __init__ as appropriate. Notes:

The function name generated for __new__ doesn’t end in __new__ like it would by default. It’s just the name of the class, converted into a valid C identifier.

No PyMethodDef #define is generated for these functions.

__init__ functions return int, not PyObject *.

Use the docstring as the class docstring.

Although __new__ and __init__ functions must always accept both the args and kwargs objects, when converting you may specify any signature for these functions that you like. (If your function doesn’t support keywords, the parsing function generated will throw an exception if it receives any.)

Changing and redirecting Clinic’s output

It can be inconvenient to have Clinic’s output interspersed with your conventional hand-edited C code. Luckily, Clinic is configurable: you can buffer up its output for printing later (or earlier!), or write its output to a separate file. You can also add a prefix or suffix to every line of Clinic’s generated output.

While changing Clinic’s output in this manner can be a boon to readability, it may result in Clinic code using types before they are defined, or your code attempting to use Clinic-generated code before it is defined. These problems can be easily solved by rearranging the declarations in your file, or moving where Clinic’s generated code goes. (This is why the default behavior of Clinic is to output everything into the current block; while many people consider this hampers readability, it will never require rearranging your code to fix definition-before-use problems.)

Let’s start with defining some terminology:

field

A field, in this context, is a subsection of Clinic’s output. For example, the #define for the PyMethodDef structure is a field, called methoddef_define. Clinic has seven different fields it can output per function definition:

docstring_prototype
docstring_definition
methoddef_define
impl_prototype
parser_prototype
parser_definition
impl_definition

All the names are of the form "<a>_<b>", where "<a>" is the semantic object represented (the parsing function, the impl function, the docstring, or the methoddef structure) and "<b>" represents what kind of statement the field is. Field names that end in "_prototype" represent forward declarations of that thing, without the actual body/data of the thing; field names that end in "_definition" represent the actual definition of the thing, with the body/data of the thing. ("methoddef" is special, it’s the only one that ends with "_define", representing that it’s a preprocessor #define.)

destination

A destination is a place Clinic can write output to. There are five built-in destinations:

block

The default destination: printed in the output section of the current Clinic block.

buffer

A text buffer where you can save text for later. Text sent here is appended to the end of any existing text. It’s an error to have any text left in the buffer when Clinic finishes processing a file.

file

A separate “clinic file” that will be created automatically by Clinic. The filename chosen for the file is {basename}.clinic{extension}, where basename and extension were assigned the output from os.path.splitext() run on the current file. (Example: the file destination for _pickle.c would be written to _pickle.clinic.c.)

Important: When using a file destination, you must check in the generated file!

two-pass

A buffer like buffer. However, a two-pass buffer can only be dumped once, and it prints out all text sent to it during all processing, even from Clinic blocks after the dumping point.

suppress

The text is suppressed—thrown away.

Clinic defines five new directives that let you reconfigure its output.

The first new directive is dump:

dump <destination>

This dumps the current contents of the named destination into the output of the current block, and empties it. This only works with buffer and two-pass destinations.

The second new directive is output. The most basic form of output is like this:

output <field> <destination>

This tells Clinic to output field to destination. output also supports a special meta-destination, called everything, which tells Clinic to output all fields to that destination.

output has a number of other functions:

output push
output pop
output preset <preset>

output push and output pop allow you to push and pop configurations on an internal configuration stack, so that you can temporarily modify the output configuration, then easily restore the previous configuration. Simply push before your change to save the current configuration, then pop when you wish to restore the previous configuration.

output preset sets Clinic’s output to one of several built-in preset configurations, as follows:

block

Clinic’s original starting configuration. Writes everything immediately after the input block.

Suppress the parser_prototype and docstring_prototype, write everything else to block.

file

Designed to write everything to the “clinic file” that it can. You then #include this file near the top of your file. You may need to rearrange your file to make this work, though usually this just means creating forward declarations for various typedef and PyTypeObject definitions.

Suppress the parser_prototype and docstring_prototype, write the impl_definition to block, and write everything else to file.

The default filename is "{dirname}/clinic/{basename}.h".

buffer

Save up most of the output from Clinic, to be written into your file near the end. For Python files implementing modules or builtin types, it’s recommended that you dump the buffer just above the static structures for your module or builtin type; these are normally very near the end. Using buffer may require even more editing than file, if your file has static PyMethodDef arrays defined in the middle of the file.

Suppress the parser_prototype, impl_prototype, and docstring_prototype, write the impl_definition to block, and write everything else to file.

two-pass

Similar to the buffer preset, but writes forward declarations to the two-pass buffer, and definitions to the buffer. This is similar to the buffer preset, but may require less editing than buffer. Dump the two-pass buffer near the top of your file, and dump the buffer near the end just like you would when using the buffer preset.

Suppresses the impl_prototype, write the impl_definition to block, write docstring_prototype, methoddef_define, and parser_prototype to two-pass, write everything else to buffer.

partial-buffer

Similar to the buffer preset, but writes more things to block, only writing the really big chunks of generated code to buffer. This avoids the definition-before-use problem of buffer completely, at the small cost of having slightly more stuff in the block’s output. Dump the buffer near the end, just like you would when using the buffer preset.

Suppresses the impl_prototype, write the docstring_definition and parser_definition to buffer, write everything else to block.

The third new directive is destination:

destination <name> <command> [...]

This performs an operation on the destination named name.

There are two defined subcommands: new and clear.

The new subcommand works like this:

destination <name> new <type>

This creates a new destination with name <name> and type <type>.

There are five destination types:

suppress

Throws the text away.

block

Writes the text to the current block. This is what Clinic originally did.

buffer

A simple text buffer, like the “buffer” builtin destination above.

file

A text file. The file destination takes an extra argument, a template to use for building the filename, like so:

destination <name> new <type> <file_template>

The template can use three strings internally that will be replaced by bits of the filename:

{path}

The full path to the file, including directory and full filename.

{dirname}

The name of the directory the file is in.

{basename}

Just the name of the file, not including the directory.

{basename_root}

Basename with the extension clipped off (everything up to but not including the last ‘.’).

{basename_extension}

The last ‘.’ and everything after it. If the basename does not contain a period, this will be the empty string.

If there are no periods in the filename, {basename} and {filename} are the same, and {extension} is empty. “{basename}{extension}” is always exactly the same as “{filename}”.”

two-pass

A two-pass buffer, like the “two-pass” builtin destination above.

The clear subcommand works like this:

destination <name> clear

It removes all the accumulated text up to this point in the destination. (I don’t know what you’d need this for, but I thought maybe it’d be useful while someone’s experimenting.)

The fourth new directive is set:

set line_prefix "string"
set line_suffix "string"

set lets you set two internal variables in Clinic. line_prefix is a string that will be prepended to every line of Clinic’s output; line_suffix is a string that will be appended to every line of Clinic’s output.

Both of these support two format strings:

{block comment start}

Turns into the string /*, the start-comment text sequence for C files.

{block comment end}

Turns into the string */, the end-comment text sequence for C files.

The final new directive is one you shouldn’t need to use directly, called preserve:

preserve

This tells Clinic that the current contents of the output should be kept, unmodified. This is used internally by Clinic when dumping output into file files; wrapping it in a Clinic block lets Clinic use its existing checksum functionality to ensure the file was not modified by hand before it gets overwritten.

The #ifdef trick

If you’re converting a function that isn’t available on all platforms, there’s a trick you can use to make life a little easier. The existing code probably looks like this:

#ifdef HAVE_FUNCTIONNAME
static module_functionname(...)
{
...
}
#endif /* HAVE_FUNCTIONNAME */

And then in the PyMethodDef structure at the bottom the existing code will have:

#ifdef HAVE_FUNCTIONNAME
{'functionname', ... },
#endif /* HAVE_FUNCTIONNAME */

In this scenario, you should enclose the body of your impl function inside the #ifdef, like so:

#ifdef HAVE_FUNCTIONNAME
/*[clinic input]
module.functionname
...
[clinic start generated code]*/
static module_functionname(...)
{
...
}
#endif /* HAVE_FUNCTIONNAME */

Then, remove those three lines from the PyMethodDef structure, replacing them with the macro Argument Clinic generated:

MODULE_FUNCTIONNAME_METHODDEF

(You can find the real name for this macro inside the generated code. Or you can calculate it yourself: it’s the name of your function as defined on the first line of your block, but with periods changed to underscores, uppercased, and "_METHODDEF" added to the end.)

Perhaps you’re wondering: what if HAVE_FUNCTIONNAME isn’t defined? The MODULE_FUNCTIONNAME_METHODDEF macro won’t be defined either!

Here’s where Argument Clinic gets very clever. It actually detects that the Argument Clinic block might be deactivated by the #ifdef. When that happens, it generates a little extra code that looks like this:

#ifndef MODULE_FUNCTIONNAME_METHODDEF
    #define MODULE_FUNCTIONNAME_METHODDEF
#endif /* !defined(MODULE_FUNCTIONNAME_METHODDEF) */

That means the macro always works. If the function is defined, this turns into the correct structure, including the trailing comma. If the function is undefined, this turns into nothing.

However, this causes one ticklish problem: where should Argument Clinic put this extra code when using the “block” output preset? It can’t go in the output block, because that could be deactivated by the #ifdef. (That’s the whole point!)

In this situation, Argument Clinic writes the extra code to the “buffer” destination. This may mean that you get a complaint from Argument Clinic:

Warning in file "Modules/posixmodule.c" on line 12357:
Destination buffer 'buffer' not empty at end of file, emptying.

When this happens, just open your file, find the dump buffer block that Argument Clinic added to your file (it’ll be at the very bottom), then move it above the PyMethodDef structure where that macro is used.

Using Argument Clinic in Python files

It’s actually possible to use Argument Clinic to preprocess Python files. There’s no point to using Argument Clinic blocks, of course, as the output wouldn’t make any sense to the Python interpreter. But using Argument Clinic to run Python blocks lets you use Python as a Python preprocessor!

Since Python comments are different from C comments, Argument Clinic blocks embedded in Python files look slightly different. They look like this:

#/*[python input]
#print("def foo(): pass")
#[python start generated code]*/
def foo(): pass
#/*[python checksum:...]*/

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 HOWTO »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 HOWTO »

|

DTrace와 SystemTap으로 CPython 계측하기

저자

David Malcolm

저자

Łukasz Langa

DTrace와 SystemTap은 컴퓨터 시스템의 프로세스가 하는 일을 검사할 수 있는 모니터링 도구입니다. 둘 다 도메인 특정 언어를 사용하여 다음과 같은 작업을 하는 스크립트를 작성할 수 있도록 합니다:

관찰할 프로세스를 걸러내기

관심 있는 프로세스에서 자료를 수집하기

데이터에 대한 보고서를 생성하기

파이썬 3.6부터, CPython은 DTrace나 SystemTap 스크립트에서 볼 수 있는 “마커(markers)”(“프로브(probes)”라고도 합니다)를 내장하도록 빌드할 수 있어서, 시스템에서 CPython 프로세스가 수행하고 있는 작업을 쉽게 관찰할 수 있습니다.

CPython implementation detail: DTrace 마커는 CPython 인터프리터의 구현 세부 사항입니다. CPython 버전 간의 프로브 호환성에 대한 보장은 없습니다. CPython 버전을 변경할 때 경고 없이 DTrace 스크립트가 작동하지 않거나 올바르게 작동하지 않을 수 있습니다.

정적 마커 활성화하기

macOS는 DTrace를 기본적으로 지원합니다. 리눅스에서는, SystemTap을 위한 마커를 내장하도록 CPython을 빌드하려면, SystemTap 개발 도구를 설치해야 합니다.

리눅스 기계에서, 이렇게 하면 됩니다:

$ yum install systemtap-sdt-devel

또는:

$ sudo apt-get install systemtap-sdt-dev

그런 다음 CPython은 --with-dtrace로 구성되어야 합니다:

checking for --with-dtrace... yes

macOS에서, 배경에서 파이썬 프로세스를 실행하고 파이썬 공급자가 제공 한 모든 프로브를 나열하여 사용 가능한 DTrace 프로브를 나열할 수 있습니다:

$ python3.6 -q &
$ sudo dtrace -l -P python$!  # or: dtrace -l -m python3.6

   ID   PROVIDER            MODULE                          FUNCTION NAME
29564 python18035        python3.6          _PyEval_EvalFrameDefault function-entry
29565 python18035        python3.6             dtrace_function_entry function-entry
29566 python18035        python3.6          _PyEval_EvalFrameDefault function-return
29567 python18035        python3.6            dtrace_function_return function-return
29568 python18035        python3.6                           collect gc-done
29569 python18035        python3.6                           collect gc-start
29570 python18035        python3.6          _PyEval_EvalFrameDefault line
29571 python18035        python3.6                 maybe_dtrace_line line

리눅스에서, “.note.stapsdt” 섹션이 있는지 확인하여 빌드 된 바이너리에 SystemTap 정적 마커가 있는지 확인할 수 있습니다.

$ readelf -S ./python | grep .note.stapsdt
[30] .note.stapsdt        NOTE         0000000000000000 00308d78

파이썬을 공유 라이브러리(–enable-shared로)로 빌드했다면, 공유 라이브러리 내에서 대신 찾아야 합니다. 예를 들면:

$ readelf -S libpython3.3dm.so.1.0 | grep .note.stapsdt
[29] .note.stapsdt        NOTE         0000000000000000 00365b68

충분히 최신의 readelf는 메타 데이터를 인쇄할 수 있습니다:

$ readelf -n ./python

Displaying notes found at file offset 0x00000254 with length 0x00000020:
    Owner                 Data size          Description
    GNU                  0x00000010          NT_GNU_ABI_TAG (ABI version tag)
        OS: Linux, ABI: 2.6.32

Displaying notes found at file offset 0x00000274 with length 0x00000024:
    Owner                 Data size          Description
    GNU                  0x00000014          NT_GNU_BUILD_ID (unique build ID bitstring)
        Build ID: df924a2b08a7e89f6e11251d4602022977af2670

Displaying notes found at file offset 0x002d6c30 with length 0x00000144:
    Owner                 Data size          Description
    stapsdt              0x00000031          NT_STAPSDT (SystemTap probe descriptors)
        Provider: python
        Name: gc__start
        Location: 0x00000000004371c3, Base: 0x0000000000630ce2, Semaphore: 0x00000000008d6bf6
        Arguments: -4@%ebx
    stapsdt              0x00000030          NT_STAPSDT (SystemTap probe descriptors)
        Provider: python
        Name: gc__done
        Location: 0x00000000004374e1, Base: 0x0000000000630ce2, Semaphore: 0x00000000008d6bf8
        Arguments: -8@%rax
    stapsdt              0x00000045          NT_STAPSDT (SystemTap probe descriptors)
        Provider: python
        Name: function__entry
        Location: 0x000000000053db6c, Base: 0x0000000000630ce2, Semaphore: 0x00000000008d6be8
        Arguments: 8@%rbp 8@%r12 -4@%eax
    stapsdt              0x00000046          NT_STAPSDT (SystemTap probe descriptors)
        Provider: python
        Name: function__return
        Location: 0x000000000053dba8, Base: 0x0000000000630ce2, Semaphore: 0x00000000008d6bea
        Arguments: 8@%rbp 8@%r12 -4@%eax

위의 메타 데이터에는 SystemTap 스크립트에서 사용되는 추적 훅을 활성화하도록 전략적으로 배치된 기계 코드 명령어를 패치하는 방법을 설명하는 SystemTap에 대한 정보가 포함되어 있습니다.

정적 DTrace 프로브

다음 예제 DTrace 스크립트는 파이썬 스크립트의 호출/반환 계층 구조를 표시하는 데 사용할 수 있습니다. “start”라는 함수의 호출 내부에서만 추적합니다. 즉, 임포트 시점의 함수 호출은 나열되지 않습니다:

self int indent;

python$target:::function-entry
/copyinstr(arg1) == "start"/
{
        self->trace = 1;
}

python$target:::function-entry
/self->trace/
{
        printf("%d\t%*s:", timestamp, 15, probename);
        printf("%*s", self->indent, "");
        printf("%s:%s:%d\n", basename(copyinstr(arg0)), copyinstr(arg1), arg2);
        self->indent++;
}

python$target:::function-return
/self->trace/
{
        self->indent--;
        printf("%d\t%*s:", timestamp, 15, probename);
        printf("%*s", self->indent, "");
        printf("%s:%s:%d\n", basename(copyinstr(arg0)), copyinstr(arg1), arg2);
}

python$target:::function-return
/copyinstr(arg1) == "start"/
{
        self->trace = 0;
}

다음과 같은 식으로 호출할 수 있습니다:

$ sudo dtrace -q -s call_stack.d -c "python3.6 script.py"

출력은 이런 식입니다:

156641360502280  function-entry:call_stack.py:start:23
156641360518804  function-entry: call_stack.py:function_1:1
156641360532797  function-entry:  call_stack.py:function_3:9
156641360546807 function-return:  call_stack.py:function_3:10
156641360563367 function-return: call_stack.py:function_1:2
156641360578365  function-entry: call_stack.py:function_2:5
156641360591757  function-entry:  call_stack.py:function_1:1
156641360605556  function-entry:   call_stack.py:function_3:9
156641360617482 function-return:   call_stack.py:function_3:10
156641360629814 function-return:  call_stack.py:function_1:2
156641360642285 function-return: call_stack.py:function_2:6
156641360656770  function-entry: call_stack.py:function_3:9
156641360669707 function-return: call_stack.py:function_3:10
156641360687853  function-entry: call_stack.py:function_4:13
156641360700719 function-return: call_stack.py:function_4:14
156641360719640  function-entry: call_stack.py:function_5:18
156641360732567 function-return: call_stack.py:function_5:21
156641360747370 function-return:call_stack.py:start:28

정적 SystemTap 마커

SystemTap 통합을 사용하는 저수준의 방법은 정적 마커를 직접 사용하는 것입니다. 이를 포함하는 바이너리 파일을 명시적으로 지정해야 합니다.

예를 들어, 이 SystemTap 스크립트는 파이썬 스크립트의 호출/반환 계층 구조를 표시하는 데 사용할 수 있습니다:

probe process("python").mark("function__entry") {
     filename = user_string($arg1);
     funcname = user_string($arg2);
     lineno = $arg3;

     printf("%s => %s in %s:%d\\n",
            thread_indent(1), funcname, filename, lineno);
}

probe process("python").mark("function__return") {
    filename = user_string($arg1);
    funcname = user_string($arg2);
    lineno = $arg3;

    printf("%s <= %s in %s:%d\\n",
           thread_indent(-1), funcname, filename, lineno);
}

다음과 같은 식으로 호출할 수 있습니다:

$ stap \
  show-call-hierarchy.stp \
  -c "./python test.py"

출력은 이런 식입니다:

11408 python(8274):        => __contains__ in Lib/_abcoll.py:362
11414 python(8274):         => __getitem__ in Lib/os.py:425
11418 python(8274):          => encode in Lib/os.py:490
11424 python(8274):          <= encode in Lib/os.py:493
11428 python(8274):         <= __getitem__ in Lib/os.py:426
11433 python(8274):        <= __contains__ in Lib/_abcoll.py:366

이때 열은 다음과 같습니다:

스크립트 시작으로부터 마이크로초 단위의 시간

실행 파일의 이름

프로세스의 PID

나머지는 스크립트가 실행될 때 호출/반환 계층 구조를 나타냅니다.

CPython의 –enable-shared 빌드의 경우, 마커는 libpython 공유 라이브러리 내에 포함되어 있으며, 프로브의 점으로 구분된 경로는 이를 반영해야 합니다. 예를 들어, 위의 예제에서 다음과 같은 줄은:

probe process("python").mark("function__entry") {

대신 이렇게 되어야 합니다:

probe process("python").library("libpython3.6dm.so.1.0").mark("function__entry") {

(CPython 3.6의 디버그 빌드를 가정하고 있습니다)

사용 가능한 정적 마커

function__entry(str filename, str funcname, int lineno)

이 마커는 파이썬 함수의 실행이 시작되었음을 나타냅니다. 순수 파이썬 (바이트 코드) 함수에서만 트리거 됩니다.

파일명, 함수 이름 및 줄 번호가 위치 인자로 추적 스크립트에 제공됩니다. $arg1, $arg2, $arg3를 사용하여 액세스해야 합니다:

$arg1 : (const char *) 파일명, user_string($arg1)를 사용하여 액세스할 수 있습니다

$arg2 : (const char *) 함수 이름, user_string($arg2)를 사용하여 액세스할 수 있습니다

$arg3 : int 줄 번호

function__return(str filename, str funcname, int lineno)

이 마커는 function__entry()의 반대이며, 파이썬 함수의 실행이 종료되었음을 나타냅니다 (return를 통해서나 예외를 통해). 순수 파이썬 (바이트 코드) 함수에서만 트리거 됩니다.

인자는 function__entry()와 같습니다.

line(str filename, str funcname, int lineno)

이 마커는 파이썬 줄이 실행되려고 함을 나타냅니다. 파이썬 프로파일러를 사용하는 줄 단위 추적과 동등합니다. C 함수 내에서는 트리거 되지 않습니다.

인자는 function__entry()와 같습니다.

gc__start(int generation)

파이썬 인터프리터가 가비지 수집 사이클을 시작할 때 발생합니다. arg0은 gc.collect()처럼 스캔할 세대(generation)입니다.

gc__done(long collected)

파이썬 인터프리터가 가비지 수집 사이클을 끝낼 때 발생합니다. arg0은 수집된 객체 수입니다.

import__find__load__start(str modulename)

importlib가 모듈을 찾고 로드하기 전에 발생합니다. arg0은 모듈 이름입니다.

버전 3.7에 추가.

import__find__load__done(str modulename, int found)

importlib의 모듈을 찾고 로드하는 함수가 호출 된 후에 발생합니다. arg0은 모듈 이름이고, arg1은 모듈이 성공적으로 로드되었는지를 나타냅니다.

버전 3.7에 추가.

SystemTap 탭셋

SystemTap 통합을 사용하는 고수준의 방법은 “탭셋(tapset)”을 사용하는 것입니다: SystemTap의 라이브러리에 해당하는 것입니다, 정적 마커의 저수준 세부 정보를 숨깁니다.

다음은 CPython의 비공유 빌드에 기반한 탭셋 파일입니다:

/*
   Provide a higher-level wrapping around the function__entry and
   function__return markers:
 \*/
probe python.function.entry = process("python").mark("function__entry")
{
    filename = user_string($arg1);
    funcname = user_string($arg2);
    lineno = $arg3;
    frameptr = $arg4
}
probe python.function.return = process("python").mark("function__return")
{
    filename = user_string($arg1);
    funcname = user_string($arg2);
    lineno = $arg3;
    frameptr = $arg4
}

이 파일을 SystemTap의 tapset 디렉터리(예를 들어, /usr/share/systemtap/tapset)에 설치하면, 다음과 같은 추가 프로브 포인트를 사용할 수 있습니다:

python.function.entry(str filename, str funcname, int lineno, frameptr)

이 프로브 포인트는 파이썬 함수의 실행이 시작되었음을 나타냅니다. 순수 파이썬 (바이트 코드) 함수에서만 트리거 됩니다.

python.function.return(str filename, str funcname, int lineno, frameptr)

이 프로브 포인트는 python.function.return()의 반대이며, 파이썬 함수의 실행이 종료되었음을 나타냅니다 (return를 통해서나 예외를 통해). 순수 파이썬 (바이트 코드) 함수에서만 트리거 됩니다.

예제

이 SystemTap 스크립트는 위의 탭셋을 사용하여, 정적 마커의 이름을 직접 지정하지 않고도, 파이썬 함수 호출 계층 구조를 추적하는 위의 예제를 보다 명확하게 구현합니다.:

probe python.function.entry
{
  printf("%s => %s in %s:%d\n",
         thread_indent(1), funcname, filename, lineno);
}

probe python.function.return
{
  printf("%s <= %s in %s:%d\n",
         thread_indent(-1), funcname, filename, lineno);
}

다음 스크립트는 위의 탭셋을 사용하여 실행 중인 모든 CPython 코드의 top과 비슷한 보기를 제공합니다. 전체 시스템에서 1초마다 가장 자주 진입하는 바이트 코드 프레임 20개를 표시합니다:

global fn_calls;

probe python.function.entry
{
    fn_calls[pid(), filename, funcname, lineno] += 1;
}

probe timer.ms(1000) {
    printf("\033[2J\033[1;1H") /* clear screen \*/
    printf("%6s %80s %6s %30s %6s\n",
           "PID", "FILENAME", "LINE", "FUNCTION", "CALLS")
    foreach ([pid, filename, funcname, lineno] in fn_calls- limit 20) {
        printf("%6d %80s %6d %30s %6d\n",
            pid, filename, lineno, funcname,
            fn_calls[pid, filename, funcname, lineno]);
    }
    delete fn_calls;
}

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 HOWTO »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

|

파이썬 자주 나오는 질문들

General Python FAQ

Programming FAQ

Design and History FAQ

Library and Extension FAQ

확장/내장 FAQ

Python on Windows FAQ

그래픽 사용자 인터페이스 FAQ

“왜 내 컴퓨터에 파이썬이 설치되어 있습니까?” FAQ

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 자주 나오는 질문들 »

|

General Python FAQ

목차

General Python FAQ

General Information

What is Python?

What is the Python Software Foundation?

Are there copyright restrictions on the use of Python?

Why was Python created in the first place?

What is Python good for?

How does the Python version numbering scheme work?

How do I obtain a copy of the Python source?

How do I get documentation on Python?

I’ve never programmed before. Is there a Python tutorial?

Is there a newsgroup or mailing list devoted to Python?

How do I get a beta test version of Python?

How do I submit bug reports and patches for Python?

Are there any published articles about Python that I can reference?

Are there any books on Python?

Where in the world is www.python.org located?

Why is it called Python?

Do I have to like “Monty Python’s Flying Circus”?

Python in the real world

How stable is Python?

How many people are using Python?

Have any significant projects been done in Python?

What new developments are expected for Python in the future?

Is it reasonable to propose incompatible changes to Python?

Is Python a good language for beginning programmers?

General Information

What is Python?

Python is an interpreted, interactive, object-oriented programming language. It incorporates modules, exceptions, dynamic typing, very high level dynamic data types, and classes. Python combines remarkable power with very clear syntax. It has interfaces to many system calls and libraries, as well as to various window systems, and is extensible in C or C++. It is also usable as an extension language for applications that need a programmable interface. Finally, Python is portable: it runs on many Unix variants, on the Mac, and on Windows 2000 and later.

To find out more, start with 파이썬 자습서. The Beginner’s Guide to Python [https://wiki.python.org/moin/BeginnersGuide] links to other introductory tutorials and resources for learning Python.

What is the Python Software Foundation?

The Python Software Foundation is an independent non-profit organization that holds the copyright on Python versions 2.1 and newer. The PSF’s mission is to advance open source technology related to the Python programming language and to publicize the use of Python. The PSF’s home page is at https://www.python.org/psf/.

Donations to the PSF are tax-exempt in the US. If you use Python and find it helpful, please contribute via the PSF donation page [https://www.python.org/psf/donations/].

Are there copyright restrictions on the use of Python?

You can do anything you want with the source, as long as you leave the copyrights in and display those copyrights in any documentation about Python that you produce. If you honor the copyright rules, it’s OK to use Python for commercial use, to sell copies of Python in source or binary form (modified or unmodified), or to sell products that incorporate Python in some form. We would still like to know about all commercial use of Python, of course.

See the PSF license page [https://www.python.org/psf/license/] to find further explanations and a link to the full text of the license.

The Python logo is trademarked, and in certain cases permission is required to use it. Consult the Trademark Usage Policy [https://www.python.org/psf/trademarks/] for more information.

Why was Python created in the first place?

Here’s a very brief summary of what started it all, written by Guido van Rossum:

I had extensive experience with implementing an interpreted language in the ABC group at CWI, and from working with this group I had learned a lot about language design. This is the origin of many Python features, including the use of indentation for statement grouping and the inclusion of very-high-level data types (although the details are all different in Python).

I had a number of gripes about the ABC language, but also liked many of its features. It was impossible to extend the ABC language (or its implementation) to remedy my complaints – in fact its lack of extensibility was one of its biggest problems. I had some experience with using Modula-2+ and talked with the designers of Modula-3 and read the Modula-3 report. Modula-3 is the origin of the syntax and semantics used for exceptions, and some other Python features.

I was working in the Amoeba distributed operating system group at CWI. We needed a better way to do system administration than by writing either C programs or Bourne shell scripts, since Amoeba had its own system call interface which wasn’t easily accessible from the Bourne shell. My experience with error handling in Amoeba made me acutely aware of the importance of exceptions as a programming language feature.

It occurred to me that a scripting language with a syntax like ABC but with access to the Amoeba system calls would fill the need. I realized that it would be foolish to write an Amoeba-specific language, so I decided that I needed a language that was generally extensible.

During the 1989 Christmas holidays, I had a lot of time on my hand, so I decided to give it a try. During the next year, while still mostly working on it in my own time, Python was used in the Amoeba project with increasing success, and the feedback from colleagues made me add many early improvements.

In February 1991, after just over a year of development, I decided to post to USENET. The rest is in the Misc/HISTORY file.

What is Python good for?

Python is a high-level general-purpose programming language that can be applied to many different classes of problems.

The language comes with a large standard library that covers areas such as string processing (regular expressions, Unicode, calculating differences between files), Internet protocols (HTTP, FTP, SMTP, XML-RPC, POP, IMAP, CGI programming), software engineering (unit testing, logging, profiling, parsing Python code), and operating system interfaces (system calls, filesystems, TCP/IP sockets). Look at the table of contents for 파이썬 표준 라이브러리 to get an idea of what’s available. A wide variety of third-party extensions are also available. Consult the Python Package Index [https://pypi.org] to find packages of interest to you.

How does the Python version numbering scheme work?

Python versions are numbered A.B.C or A.B. A is the major version number – it is only incremented for really major changes in the language. B is the minor version number, incremented for less earth-shattering changes. C is the micro-level – it is incremented for each bugfix release. See PEP 6 [https://www.python.org/dev/peps/pep-0006] for more information about bugfix releases.

Not all releases are bugfix releases. In the run-up to a new major release, a series of development releases are made, denoted as alpha, beta, or release candidate. Alphas are early releases in which interfaces aren’t yet finalized; it’s not unexpected to see an interface change between two alpha releases. Betas are more stable, preserving existing interfaces but possibly adding new modules, and release candidates are frozen, making no changes except as needed to fix critical bugs.

Alpha, beta and release candidate versions have an additional suffix. The suffix for an alpha version is “aN” for some small number N, the suffix for a beta version is “bN” for some small number N, and the suffix for a release candidate version is “cN” for some small number N. In other words, all versions labeled 2.0aN precede the versions labeled 2.0bN, which precede versions labeled 2.0cN, and those precede 2.0.

You may also find version numbers with a “+” suffix, e.g. “2.2+”. These are unreleased versions, built directly from the CPython development repository. In practice, after a final minor release is made, the version is incremented to the next minor version, which becomes the “a0” version, e.g. “2.4a0”.

See also the documentation for sys.version, sys.hexversion, and sys.version_info.

How do I obtain a copy of the Python source?

The latest Python source distribution is always available from python.org, at https://www.python.org/downloads/. The latest development sources can be obtained at https://github.com/python/cpython/.

The source distribution is a gzipped tar file containing the complete C source, Sphinx-formatted documentation, Python library modules, example programs, and several useful pieces of freely distributable software. The source will compile and run out of the box on most UNIX platforms.

Consult the Getting Started section of the Python Developer’s Guide [https://devguide.python.org/setup/] for more information on getting the source code and compiling it.

How do I get documentation on Python?

The standard documentation for the current stable version of Python is available at https://docs.python.org/3/. PDF, plain text, and downloadable HTML versions are also available at https://docs.python.org/3/download.html.

The documentation is written in reStructuredText and processed by the Sphinx documentation tool [http://sphinx-doc.org/]. The reStructuredText source for the documentation is part of the Python source distribution.

I’ve never programmed before. Is there a Python tutorial?

There are numerous tutorials and books available. The standard documentation includes 파이썬 자습서.

Consult the Beginner’s Guide [https://wiki.python.org/moin/BeginnersGuide] to find information for beginning Python programmers, including lists of tutorials.

Is there a newsgroup or mailing list devoted to Python?

There is a newsgroup, comp.lang.python, and a mailing list, python-list [https://mail.python.org/mailman/listinfo/python-list]. The newsgroup and mailing list are gatewayed into each other – if you can read news it’s unnecessary to subscribe to the mailing list. comp.lang.python is high-traffic, receiving hundreds of postings every day, and Usenet readers are often more able to cope with this volume.

Announcements of new software releases and events can be found in comp.lang.python.announce, a low-traffic moderated list that receives about five postings per day. It’s available as the python-announce mailing list [https://mail.python.org/mailman/listinfo/python-announce-list].

More info about other mailing lists and newsgroups can be found at https://www.python.org/community/lists/.

How do I get a beta test version of Python?

Alpha and beta releases are available from https://www.python.org/downloads/. All releases are announced on the comp.lang.python and comp.lang.python.announce newsgroups and on the Python home page at https://www.python.org/; an RSS feed of news is available.

You can also access the development version of Python through Git. See The Python Developer’s Guide [https://devguide.python.org/] for details.

How do I submit bug reports and patches for Python?

To report a bug or submit a patch, please use the Roundup installation at https://bugs.python.org/.

You must have a Roundup account to report bugs; this makes it possible for us to contact you if we have follow-up questions. It will also enable Roundup to send you updates as we act on your bug. If you had previously used SourceForge to report bugs to Python, you can obtain your Roundup password through Roundup’s password reset procedure [https://bugs.python.org/user?@template=forgotten].

For more information on how Python is developed, consult the Python Developer’s Guide [https://devguide.python.org/].

Are there any published articles about Python that I can reference?

It’s probably best to cite your favorite book about Python.

The very first article about Python was written in 1991 and is now quite outdated.

Guido van Rossum and Jelke de Boer, “Interactively Testing Remote Servers Using the Python Programming Language”, CWI Quarterly, Volume 4, Issue 4 (December 1991), Amsterdam, pp 283–303.

Are there any books on Python?

Yes, there are many, and more are being published. See the python.org wiki at https://wiki.python.org/moin/PythonBooks for a list.

You can also search online bookstores for “Python” and filter out the Monty Python references; or perhaps search for “Python” and “language”.

Where in the world is www.python.org located?

The Python project’s infrastructure is located all over the world and is managed by the Python Infrastructure Team. Details here [http://infra.psf.io].

Why is it called Python?

When he began implementing Python, Guido van Rossum was also reading the published scripts from “Monty Python’s Flying Circus” [https://en.wikipedia.org/wiki/Monty_Python], a BBC comedy series from the 1970s. Van Rossum thought he needed a name that was short, unique, and slightly mysterious, so he decided to call the language Python.

Do I have to like “Monty Python’s Flying Circus”?

No, but it helps. :)

Python in the real world

How stable is Python?

Very stable. New, stable releases have been coming out roughly every 6 to 18 months since 1991, and this seems likely to continue. Currently there are usually around 18 months between major releases.

The developers issue “bugfix” releases of older versions, so the stability of existing releases gradually improves. Bugfix releases, indicated by a third component of the version number (e.g. 3.5.3, 3.6.2), are managed for stability; only fixes for known problems are included in a bugfix release, and it’s guaranteed that interfaces will remain the same throughout a series of bugfix releases.

The latest stable releases can always be found on the Python download page [https://www.python.org/downloads/]. There are two production-ready versions of Python: 2.x and 3.x. The recommended version is 3.x, which is supported by most widely used libraries. Although 2.x is still widely used, it will not be maintained after January 1, 2020 [https://www.python.org/dev/peps/pep-0373/].

How many people are using Python?

There are probably tens of thousands of users, though it’s difficult to obtain an exact count.

Python is available for free download, so there are no sales figures, and it’s available from many different sites and packaged with many Linux distributions, so download statistics don’t tell the whole story either.

The comp.lang.python newsgroup is very active, but not all Python users post to the group or even read it.

Have any significant projects been done in Python?

See https://www.python.org/about/success for a list of projects that use Python. Consulting the proceedings for past Python conferences [https://www.python.org/community/workshops/] will reveal contributions from many different companies and organizations.

High-profile Python projects include the Mailman mailing list manager [http://www.list.org] and the Zope application server [http://www.zope.org]. Several Linux distributions, most notably Red Hat [https://www.redhat.com], have written part or all of their installer and system administration software in Python. Companies that use Python internally include Google, Yahoo, and Lucasfilm Ltd.

What new developments are expected for Python in the future?

See https://www.python.org/dev/peps/ for the Python Enhancement Proposals (PEPs). PEPs are design documents describing a suggested new feature for Python, providing a concise technical specification and a rationale. Look for a PEP titled “Python X.Y Release Schedule”, where X.Y is a version that hasn’t been publicly released yet.

New development is discussed on the python-dev mailing list [https://mail.python.org/mailman/listinfo/python-dev/].

Is it reasonable to propose incompatible changes to Python?

In general, no. There are already millions of lines of Python code around the world, so any change in the language that invalidates more than a very small fraction of existing programs has to be frowned upon. Even if you can provide a conversion program, there’s still the problem of updating all documentation; many books have been written about Python, and we don’t want to invalidate them all at a single stroke.

Providing a gradual upgrade path is necessary if a feature has to be changed. PEP 5 [https://www.python.org/dev/peps/pep-0005] describes the procedure followed for introducing backward-incompatible changes while minimizing disruption for users.

Is Python a good language for beginning programmers?

Yes.

It is still common to start students with a procedural and statically typed language such as Pascal, C, or a subset of C++ or Java. Students may be better served by learning Python as their first language. Python has a very simple and consistent syntax and a large standard library and, most importantly, using Python in a beginning programming course lets students concentrate on important programming skills such as problem decomposition and data type design. With Python, students can be quickly introduced to basic concepts such as loops and procedures. They can probably even work with user-defined objects in their very first course.

For a student who has never programmed before, using a statically typed language seems unnatural. It presents additional complexity that the student must master and slows the pace of the course. The students are trying to learn to think like a computer, decompose problems, design consistent interfaces, and encapsulate data. While learning to use a statically typed language is important in the long term, it is not necessarily the best topic to address in the students’ first programming course.

Many other aspects of Python make it a good first language. Like Java, Python has a large standard library so that students can be assigned programming projects very early in the course that do something. Assignments aren’t restricted to the standard four-function calculator and check balancing programs. By using the standard library, students can gain the satisfaction of working on realistic applications as they learn the fundamentals of programming. Using the standard library also teaches students about code reuse. Third-party modules such as PyGame are also helpful in extending the students’ reach.

Python’s interactive interpreter enables students to test language features while they’re programming. They can keep a window with the interpreter running while they enter their program’s source in another window. If they can’t remember the methods for a list, they can do something like this:

>>> L = []
>>> dir(L)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__',
'__dir__', '__doc__', '__eq__', '__format__', '__ge__',
'__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__',
'__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__',
'__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__',
'__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__',
'__sizeof__', '__str__', '__subclasshook__', 'append', 'clear',
'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove',
'reverse', 'sort']
>>> [d for d in dir(L) if '__' not in d]
['append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

>>> help(L.append)
Help on built-in function append:

append(...)
    L.append(object) -> None -- append object to end

>>> L.append(1)
>>> L
[1]

With the interpreter, documentation is never far from the student as they are programming.

There are also good IDEs for Python. IDLE is a cross-platform IDE for Python that is written in Python using Tkinter. PythonWin is a Windows-specific IDE. Emacs users will be happy to know that there is a very good Python mode for Emacs. All of these programming environments provide syntax highlighting, auto-indenting, and access to the interactive interpreter while coding. Consult the Python wiki [https://wiki.python.org/moin/PythonEditors] for a full list of Python editing environments.

If you want to discuss Python’s use in education, you may be interested in joining the edu-sig mailing list [https://www.python.org/community/sigs/current/edu-sig].

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 자주 나오는 질문들 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 자주 나오는 질문들 »

|

Programming FAQ

목차

Programming FAQ

General Questions

Is there a source code level debugger with breakpoints, single-stepping, etc.?

Is there a tool to help find bugs or perform static analysis?

How can I create a stand-alone binary from a Python script?

Are there coding standards or a style guide for Python programs?

Core Language

Why am I getting an UnboundLocalError when the variable has a value?

What are the rules for local and global variables in Python?

Why do lambdas defined in a loop with different values all return the same result?

How do I share global variables across modules?

What are the “best practices” for using import in a module?

Why are default values shared between objects?

How can I pass optional or keyword parameters from one function to another?

What is the difference between arguments and parameters?

Why did changing list ‘y’ also change list ‘x’?

How do I write a function with output parameters (call by reference)?

How do you make a higher order function in Python?

How do I copy an object in Python?

How can I find the methods or attributes of an object?

How can my code discover the name of an object?

What’s up with the comma operator’s precedence?

Is there an equivalent of C’s “?:” ternary operator?

Is it possible to write obfuscated one-liners in Python?

What does the slash(/) in the parameter list of a function mean?

Numbers and strings

How do I specify hexadecimal and octal integers?

Why does -22 // 10 return -3?

How do I convert a string to a number?

How do I convert a number to a string?

How do I modify a string in place?

How do I use strings to call functions/methods?

Is there an equivalent to Perl’s chomp() for removing trailing newlines from strings?

Is there a scanf() or sscanf() equivalent?

What does ‘UnicodeDecodeError’ or ‘UnicodeEncodeError’ error mean?

Performance

My program is too slow. How do I speed it up?

What is the most efficient way to concatenate many strings together?

Sequences (Tuples/Lists)

How do I convert between tuples and lists?

What’s a negative index?

How do I iterate over a sequence in reverse order?

How do you remove duplicates from a list?

How do you make an array in Python?

How do I create a multidimensional list?

How do I apply a method to a sequence of objects?

Why does a_tuple[i] += [‘item’] raise an exception when the addition works?

I want to do a complicated sort: can you do a Schwartzian Transform in Python?

How can I sort one list by values from another list?

Objects

What is a class?

What is a method?

What is self?

How do I check if an object is an instance of a given class or of a subclass of it?

What is delegation?

How do I call a method defined in a base class from a derived class that overrides it?

How can I organize my code to make it easier to change the base class?

How do I create static class data and static class methods?

How can I overload constructors (or methods) in Python?

I try to use __spam and I get an error about _SomeClassName__spam.

My class defines __del__ but it is not called when I delete the object.

How do I get a list of all instances of a given class?

Why does the result of id() appear to be not unique?

Modules

How do I create a .pyc file?

How do I find the current module name?

How can I have modules that mutually import each other?

__import__(‘x.y.z’) returns <module ‘x’>; how do I get z?

When I edit an imported module and reimport it, the changes don’t show up. Why does this happen?

General Questions

Is there a source code level debugger with breakpoints, single-stepping, etc.?

Yes.

Several debuggers for Python are described below, and the built-in function breakpoint() allows you to drop into any of them.

The pdb module is a simple but adequate console-mode debugger for Python. It is part of the standard Python library, and is documented in the Library Reference Manual. You can also write your own debugger by using the code for pdb as an example.

The IDLE interactive development environment, which is part of the standard Python distribution (normally available as Tools/scripts/idle), includes a graphical debugger.

PythonWin is a Python IDE that includes a GUI debugger based on pdb. The Pythonwin debugger colors breakpoints and has quite a few cool features such as debugging non-Pythonwin programs. Pythonwin is available as part of the Python for Windows Extensions [https://sourceforge.net/projects/pywin32/] project and as a part of the ActivePython distribution (see https://www.activestate.com/activepython).

Boa Constructor [http://boa-constructor.sourceforge.net/] is an IDE and GUI builder that uses wxWidgets. It offers visual frame creation and manipulation, an object inspector, many views on the source like object browsers, inheritance hierarchies, doc string generated html documentation, an advanced debugger, integrated help, and Zope support.

Eric [http://eric-ide.python-projects.org/] is an IDE built on PyQt and the Scintilla editing component.

Pydb is a version of the standard Python debugger pdb, modified for use with DDD (Data Display Debugger), a popular graphical debugger front end. Pydb can be found at http://bashdb.sourceforge.net/pydb/ and DDD can be found at https://www.gnu.org/software/ddd.

There are a number of commercial Python IDEs that include graphical debuggers. They include:

Wing IDE (https://wingware.com/)

Komodo IDE (https://komodoide.com/)

PyCharm (https://www.jetbrains.com/pycharm/)

Is there a tool to help find bugs or perform static analysis?

Yes.

PyChecker is a static analysis tool that finds bugs in Python source code and warns about code complexity and style. You can get PyChecker from http://pychecker.sourceforge.net/.

Pylint [https://www.pylint.org/] is another tool that checks if a module satisfies a coding standard, and also makes it possible to write plug-ins to add a custom feature. In addition to the bug checking that PyChecker performs, Pylint offers some additional features such as checking line length, whether variable names are well-formed according to your coding standard, whether declared interfaces are fully implemented, and more. https://docs.pylint.org/ provides a full list of Pylint’s features.

Static type checkers such as Mypy [http://mypy-lang.org/], Pyre [https://pyre-check.org/], and Pytype [https://github.com/google/pytype] can check type hints in Python source code.

How can I create a stand-alone binary from a Python script?

You don’t need the ability to compile Python to C code if all you want is a stand-alone program that users can download and run without having to install the Python distribution first. There are a number of tools that determine the set of modules required by a program and bind these modules together with a Python binary to produce a single executable.

One is to use the freeze tool, which is included in the Python source tree as Tools/freeze. It converts Python byte code to C arrays; a C compiler you can embed all your modules into a new program, which is then linked with the standard Python modules.

It works by scanning your source recursively for import statements (in both forms) and looking for the modules in the standard Python path as well as in the source directory (for built-in modules). It then turns the bytecode for modules written in Python into C code (array initializers that can be turned into code objects using the marshal module) and creates a custom-made config file that only contains those built-in modules which are actually used in the program. It then compiles the generated C code and links it with the rest of the Python interpreter to form a self-contained binary which acts exactly like your script.

Obviously, freeze requires a C compiler. There are several other utilities which don’t. One is Thomas Heller’s py2exe (Windows only) at

http://www.py2exe.org/

Another tool is Anthony Tuininga’s cx_Freeze [https://anthony-tuininga.github.io/cx_Freeze/].

Are there coding standards or a style guide for Python programs?

Yes. The coding style required for standard library modules is documented as PEP 8 [https://www.python.org/dev/peps/pep-0008].

Core Language

Why am I getting an UnboundLocalError when the variable has a value?

It can be a surprise to get the UnboundLocalError in previously working code when it is modified by adding an assignment statement somewhere in the body of a function.

This code:

>>> x = 10
>>> def bar():
...     print(x)
>>> bar()
10

works, but this code:

>>> x = 10
>>> def foo():
...     print(x)
...     x += 1

results in an UnboundLocalError:

>>> foo()
Traceback (most recent call last):
  ...
UnboundLocalError: local variable 'x' referenced before assignment

This is because when you make an assignment to a variable in a scope, that variable becomes local to that scope and shadows any similarly named variable in the outer scope. Since the last statement in foo assigns a new value to x, the compiler recognizes it as a local variable. Consequently when the earlier print(x) attempts to print the uninitialized local variable and an error results.

In the example above you can access the outer scope variable by declaring it global:

>>> x = 10
>>> def foobar():
...     global x
...     print(x)
...     x += 1
>>> foobar()
10

This explicit declaration is required in order to remind you that (unlike the superficially analogous situation with class and instance variables) you are actually modifying the value of the variable in the outer scope:

>>> print(x)
11

You can do a similar thing in a nested scope using the nonlocal keyword:

>>> def foo():
...    x = 10
...    def bar():
...        nonlocal x
...        print(x)
...        x += 1
...    bar()
...    print(x)
>>> foo()
10
11

What are the rules for local and global variables in Python?

In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a value anywhere within the function’s body, it’s assumed to be a local unless explicitly declared as global.

Though a bit surprising at first, a moment’s consideration explains this. On one hand, requiring global for assigned variables provides a bar against unintended side-effects. On the other hand, if global was required for all global references, you’d be using global all the time. You’d have to declare as global every reference to a built-in function or to a component of an imported module. This clutter would defeat the usefulness of the global declaration for identifying side-effects.

Why do lambdas defined in a loop with different values all return the same result?

Assume you use a for loop to define a few different lambdas (or even plain functions), e.g.:

>>> squares = []
>>> for x in range(5):
...     squares.append(lambda: x**2)

This gives you a list that contains 5 lambdas that calculate x**2. You might expect that, when called, they would return, respectively, 0, 1, 4, 9, and 16. However, when you actually try you will see that they all return 16:

>>> squares[2]()
16
>>> squares[4]()
16

This happens because x is not local to the lambdas, but is defined in the outer scope, and it is accessed when the lambda is called — not when it is defined. At the end of the loop, the value of x is 4, so all the functions now return 4**2, i.e. 16. You can also verify this by changing the value of x and see how the results of the lambdas change:

>>> x = 8
>>> squares[2]()
64

In order to avoid this, you need to save the values in variables local to the lambdas, so that they don’t rely on the value of the global x:

>>> squares = []
>>> for x in range(5):
...     squares.append(lambda n=x: n**2)

Here, n=x creates a new variable n local to the lambda and computed when the lambda is defined so that it has the same value that x had at that point in the loop. This means that the value of n will be 0 in the first lambda, 1 in the second, 2 in the third, and so on. Therefore each lambda will now return the correct result:

>>> squares[2]()
4
>>> squares[4]()
16

Note that this behaviour is not peculiar to lambdas, but applies to regular functions too.

How do I share global variables across modules?

The canonical way to share information across modules within a single program is to create a special module (often called config or cfg). Just import the config module in all modules of your application; the module then becomes available as a global name. Because there is only one instance of each module, any changes made to the module object get reflected everywhere. For example:

config.py:

x = 0   # Default value of the 'x' configuration setting

mod.py:

import config
config.x = 1

main.py:

import config
import mod
print(config.x)

Note that using a module is also the basis for implementing the Singleton design pattern, for the same reason.

What are the “best practices” for using import in a module?

In general, don’t use from modulename import *. Doing so clutters the importer’s namespace, and makes it much harder for linters to detect undefined names.

Import modules at the top of a file. Doing so makes it clear what other modules your code requires and avoids questions of whether the module name is in scope. Using one import per line makes it easy to add and delete module imports, but using multiple imports per line uses less screen space.

It’s good practice if you import modules in the following order:

standard library modules – e.g. sys, os, getopt, re

third-party library modules (anything installed in Python’s site-packages directory) – e.g. mx.DateTime, ZODB, PIL.Image, etc.

locally-developed modules

It is sometimes necessary to move imports to a function or class to avoid problems with circular imports. Gordon McMillan says:

Circular imports are fine where both modules use the “import <module>” form of import. They fail when the 2nd module wants to grab a name out of the first (“from module import name”) and the import is at the top level. That’s because names in the 1st are not yet available, because the first module is busy importing the 2nd.

In this case, if the second module is only used in one function, then the import can easily be moved into that function. By the time the import is called, the first module will have finished initializing, and the second module can do its import.

It may also be necessary to move imports out of the top level of code if some of the modules are platform-specific. In that case, it may not even be possible to import all of the modules at the top of the file. In this case, importing the correct modules in the corresponding platform-specific code is a good option.

Only move imports into a local scope, such as inside a function definition, if it’s necessary to solve a problem such as avoiding a circular import or are trying to reduce the initialization time of a module. This technique is especially helpful if many of the imports are unnecessary depending on how the program executes. You may also want to move imports into a function if the modules are only ever used in that function. Note that loading a module the first time may be expensive because of the one time initialization of the module, but loading a module multiple times is virtually free, costing only a couple of dictionary lookups. Even if the module name has gone out of scope, the module is probably available in sys.modules.

Why are default values shared between objects?

This type of bug commonly bites neophyte programmers. Consider this function:

def foo(mydict={}):  # Danger: shared reference to one dict for all calls
    ... compute something ...
    mydict[key] = value
    return mydict

The first time you call this function, mydict contains a single item. The second time, mydict contains two items because when foo() begins executing, mydict starts out with an item already in it.

It is often expected that a function call creates new objects for default values. This is not what happens. Default values are created exactly once, when the function is defined. If that object is changed, like the dictionary in this example, subsequent calls to the function will refer to this changed object.

By definition, immutable objects such as numbers, strings, tuples, and None, are safe from change. Changes to mutable objects such as dictionaries, lists, and class instances can lead to confusion.

Because of this feature, it is good programming practice to not use mutable objects as default values. Instead, use None as the default value and inside the function, check if the parameter is None and create a new list/dictionary/whatever if it is. For example, don’t write:

def foo(mydict={}):
    ...

but:

def foo(mydict=None):
    if mydict is None:
        mydict = {}  # create a new dict for local namespace

This feature can be useful. When you have a function that’s time-consuming to compute, a common technique is to cache the parameters and the resulting value of each call to the function, and return the cached value if the same value is requested again. This is called “memoizing”, and can be implemented like this:

# Callers can only provide two parameters and optionally pass _cache by keyword
def expensive(arg1, arg2, *, _cache={}):
    if (arg1, arg2) in _cache:
        return _cache[(arg1, arg2)]

    # Calculate the value
    result = ... expensive computation ...
    _cache[(arg1, arg2)] = result           # Store result in the cache
    return result

You could use a global variable containing a dictionary instead of the default value; it’s a matter of taste.

How can I pass optional or keyword parameters from one function to another?

Collect the arguments using the * and ** specifiers in the function’s parameter list; this gives you the positional arguments as a tuple and the keyword arguments as a dictionary. You can then pass these arguments when calling another function by using * and **:

def f(x, *args, **kwargs):
    ...
    kwargs['width'] = '14.3c'
    ...
    g(x, *args, **kwargs)

What is the difference between arguments and parameters?

Parameters are defined by the names that appear in a function definition, whereas arguments are the values actually passed to a function when calling it. Parameters define what types of arguments a function can accept. For example, given the function definition:

def func(foo, bar=None, **kwargs):
    pass

foo, bar and kwargs are parameters of func. However, when calling func, for example:

func(42, bar=314, extra=somevar)

the values 42, 314, and somevar are arguments.

Why did changing list ‘y’ also change list ‘x’?

If you wrote code like:

>>> x = []
>>> y = x
>>> y.append(10)
>>> y
[10]
>>> x
[10]

you might be wondering why appending an element to y changed x too.

There are two factors that produce this result:

Variables are simply names that refer to objects. Doing y = x doesn’t create a copy of the list – it creates a new variable y that refers to the same object x refers to. This means that there is only one object (the list), and both x and y refer to it.

Lists are mutable, which means that you can change their content.

After the call to append(), the content of the mutable object has changed from [] to [10]. Since both the variables refer to the same object, using either name accesses the modified value [10].

If we instead assign an immutable object to x:

>>> x = 5  # ints are immutable
>>> y = x
>>> x = x + 1  # 5 can't be mutated, we are creating a new object here
>>> x
6
>>> y
5

we can see that in this case x and y are not equal anymore. This is because integers are immutable, and when we do x = x + 1 we are not mutating the int 5 by incrementing its value; instead, we are creating a new object (the int 6) and assigning it to x (that is, changing which object x refers to). After this assignment we have two objects (the ints 6 and 5) and two variables that refer to them (x now refers to 6 but y still refers to 5).

Some operations (for example y.append(10) and y.sort()) mutate the object, whereas superficially similar operations (for example y = y + [10] and sorted(y)) create a new object. In general in Python (and in all cases in the standard library) a method that mutates an object will return None to help avoid getting the two types of operations confused. So if you mistakenly write y.sort() thinking it will give you a sorted copy of y, you’ll instead end up with None, which will likely cause your program to generate an easily diagnosed error.

However, there is one class of operations where the same operation sometimes has different behaviors with different types: the augmented assignment operators. For example, += mutates lists but not tuples or ints (a_list += [1, 2, 3] is equivalent to a_list.extend([1, 2, 3]) and mutates a_list, whereas some_tuple += (1, 2, 3) and some_int += 1 create new objects).

In other words:

If we have a mutable object (list, dict, set, etc.), we can use some specific operations to mutate it and all the variables that refer to it will see the change.

If we have an immutable object (str, int, tuple, etc.), all the variables that refer to it will always see the same value, but operations that transform that value into a new value always return a new object.

If you want to know if two variables refer to the same object or not, you can use the is operator, or the built-in function id().

How do I write a function with output parameters (call by reference)?

Remember that arguments are passed by assignment in Python. Since assignment just creates references to objects, there’s no alias between an argument name in the caller and callee, and so no call-by-reference per se. You can achieve the desired effect in a number of ways.

By returning a tuple of the results:

def func2(a, b):
    a = 'new-value'        # a and b are local names
    b = b + 1              # assigned to new objects
    return a, b            # return new values

x, y = 'old-value', 99
x, y = func2(x, y)
print(x, y)                # output: new-value 100

This is almost always the clearest solution.

By using global variables. This isn’t thread-safe, and is not recommended.

By passing a mutable (changeable in-place) object:

def func1(a):
    a[0] = 'new-value'     # 'a' references a mutable list
    a[1] = a[1] + 1        # changes a shared object

args = ['old-value', 99]
func1(args)
print(args[0], args[1])    # output: new-value 100

By passing in a dictionary that gets mutated:

def func3(args):
    args['a'] = 'new-value'     # args is a mutable dictionary
    args['b'] = args['b'] + 1   # change it in-place

args = {'a': 'old-value', 'b': 99}
func3(args)
print(args['a'], args['b'])

Or bundle up values in a class instance:

class callByRef:
    def __init__(self, **args):
        for (key, value) in args.items():
            setattr(self, key, value)

def func4(args):
    args.a = 'new-value'        # args is a mutable callByRef
    args.b = args.b + 1         # change object in-place

args = callByRef(a='old-value', b=99)
func4(args)
print(args.a, args.b)

There’s almost never a good reason to get this complicated.

Your best choice is to return a tuple containing the multiple results.

How do you make a higher order function in Python?

You have two choices: you can use nested scopes or you can use callable objects. For example, suppose you wanted to define linear(a,b) which returns a function f(x) that computes the value a*x+b. Using nested scopes:

def linear(a, b):
    def result(x):
        return a * x + b
    return result

Or using a callable object:

class linear:

    def __init__(self, a, b):
        self.a, self.b = a, b

    def __call__(self, x):
        return self.a * x + self.b

In both cases,

taxes = linear(0.3, 2)

gives a callable object where taxes(10e6) == 0.3 * 10e6 + 2.

The callable object approach has the disadvantage that it is a bit slower and results in slightly longer code. However, note that a collection of callables can share their signature via inheritance:

class exponential(linear):
    # __init__ inherited
    def __call__(self, x):
        return self.a * (x ** self.b)

Object can encapsulate state for several methods:

class counter:

    value = 0

    def set(self, x):
        self.value = x

    def up(self):
        self.value = self.value + 1

    def down(self):
        self.value = self.value - 1

count = counter()
inc, dec, reset = count.up, count.down, count.set

Here inc(), dec() and reset() act like functions which share the same counting variable.

How do I copy an object in Python?

In general, try copy.copy() or copy.deepcopy() for the general case. Not all objects can be copied, but most can.

Some objects can be copied more easily. Dictionaries have a copy() method:

newdict = olddict.copy()

Sequences can be copied by slicing:

new_l = l[:]

How can I find the methods or attributes of an object?

For an instance x of a user-defined class, dir(x) returns an alphabetized list of the names containing the instance attributes and methods and attributes defined by its class.

How can my code discover the name of an object?

Generally speaking, it can’t, because objects don’t really have names. Essentially, assignment always binds a name to a value; the same is true of def and class statements, but in that case the value is a callable. Consider the following code:

>>> class A:
...     pass
...
>>> B = A
>>> a = B()
>>> b = a
>>> print(b)
<__main__.A object at 0x16D07CC>
>>> print(a)
<__main__.A object at 0x16D07CC>

Arguably the class has a name: even though it is bound to two names and invoked through the name B the created instance is still reported as an instance of class A. However, it is impossible to say whether the instance’s name is a or b, since both names are bound to the same value.

Generally speaking it should not be necessary for your code to “know the names” of particular values. Unless you are deliberately writing introspective programs, this is usually an indication that a change of approach might be beneficial.

In comp.lang.python, Fredrik Lundh once gave an excellent analogy in answer to this question:

The same way as you get the name of that cat you found on your porch: the cat (object) itself cannot tell you its name, and it doesn’t really care – so the only way to find out what it’s called is to ask all your neighbours (namespaces) if it’s their cat (object)…

….and don’t be surprised if you’ll find that it’s known by many names, or no name at all!

What’s up with the comma operator’s precedence?

Comma is not an operator in Python. Consider this session:

>>> "a" in "b", "a"
(False, 'a')

Since the comma is not an operator, but a separator between expressions the above is evaluated as if you had entered:

("a" in "b"), "a"

not:

"a" in ("b", "a")

The same is true of the various assignment operators (=, += etc). They are not truly operators but syntactic delimiters in assignment statements.

Is there an equivalent of C’s “?:” ternary operator?

Yes, there is. The syntax is as follows:

[on_true] if [expression] else [on_false]

x, y = 50, 25
small = x if x < y else y

Before this syntax was introduced in Python 2.5, a common idiom was to use logical operators:

[expression] and [on_true] or [on_false]

However, this idiom is unsafe, as it can give wrong results when on_true has a false boolean value. Therefore, it is always better to use the ... if ... else ... form.

Is it possible to write obfuscated one-liners in Python?

Yes. Usually this is done by nesting lambda within lambda. See the following three examples, due to Ulf Bartelt:

from functools import reduce

# Primes < 1000
print(list(filter(None,map(lambda y:y*reduce(lambda x,y:x*y!=0,
map(lambda x,y=y:y%x,range(2,int(pow(y,0.5)+1))),1),range(2,1000)))))

# First 10 Fibonacci numbers
print(list(map(lambda x,f=lambda x,f:(f(x-1,f)+f(x-2,f)) if x>1 else 1:
f(x,f), range(10))))

# Mandelbrot set
print((lambda Ru,Ro,Iu,Io,IM,Sx,Sy:reduce(lambda x,y:x+y,map(lambda y,
Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,Sy=Sy,L=lambda yc,Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,i=IM,
Sx=Sx,Sy=Sy:reduce(lambda x,y:x+y,map(lambda x,xc=Ru,yc=yc,Ru=Ru,Ro=Ro,
i=i,Sx=Sx,F=lambda xc,yc,x,y,k,f=lambda xc,yc,x,y,k,f:(k<=0)or (x*x+y*y
>=4.0) or 1+f(xc,yc,x*x-y*y+xc,2.0*x*y+yc,k-1,f):f(xc,yc,x,y,k,f):chr(
64+F(Ru+x*(Ro-Ru)/Sx,yc,0,0,i)),range(Sx))):L(Iu+y*(Io-Iu)/Sy),range(Sy
))))(-2.1, 0.7, -1.2, 1.2, 30, 80, 24))
#    \___ ___/  \___ ___/  |   |   |__ lines on screen
#        V          V      |   |______ columns on screen
#        |          |      |__________ maximum of "iterations"
#        |          |_________________ range on y axis
#        |____________________________ range on x axis

Don’t try this at home, kids!

What does the slash(/) in the parameter list of a function mean?

A slash in the argument list of a function denotes that the parameters prior to it are positional-only. Positional-only parameters are the ones without an externally-usable name. Upon calling a function that accepts positional-only parameters, arguments are mapped to parameters based solely on their position. For example, pow() is a function that accepts positional-only parameters. Its documentation looks like this:

>>> help(pow)
Help on built-in function pow in module builtins:

pow(x, y, z=None, /)
   Equivalent to x**y (with two arguments) or x**y % z (with three arguments)

   Some types, such as ints, are able to use a more efficient algorithm when
   invoked using the three argument form.

The slash at the end of the parameter list means that all three parameters are positional-only. Thus, calling pow() with keyword aguments would lead to an error:

>>> pow(x=3, y=4)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: pow() takes no keyword arguments

Note that as of this writing this is only documentational and no valid syntax in Python, although there is PEP 570 [https://www.python.org/dev/peps/pep-0570], which proposes a syntax for position-only parameters in Python.

Numbers and strings

How do I specify hexadecimal and octal integers?

To specify an octal digit, precede the octal value with a zero, and then a lower or uppercase “o”. For example, to set the variable “a” to the octal value “10” (8 in decimal), type:

>>> a = 0o10
>>> a
8

Hexadecimal is just as easy. Simply precede the hexadecimal number with a zero, and then a lower or uppercase “x”. Hexadecimal digits can be specified in lower or uppercase. For example, in the Python interpreter:

>>> a = 0xa5
>>> a
165
>>> b = 0XB2
>>> b
178

Why does -22 // 10 return -3?

It’s primarily driven by the desire that i % j have the same sign as j. If you want that, and also want:

i == (i // j) * j + (i % j)

then integer division has to return the floor. C also requires that identity to hold, and then compilers that truncate i // j need to make i % j have the same sign as i.

There are few real use cases for i % j when j is negative. When j is positive, there are many, and in virtually all of them it’s more useful for i % j to be >= 0. If the clock says 10 now, what did it say 200 hours ago? -190 % 12 == 2 is useful; -190 % 12 == -10 is a bug waiting to bite.

How do I convert a string to a number?

For integers, use the built-in int() type constructor, e.g. int('144') == 144. Similarly, float() converts to floating-point, e.g. float('144') == 144.0.

By default, these interpret the number as decimal, so that int('0144') == 144 and int('0x144') raises ValueError. int(string, base) takes the base to convert from as a second optional argument, so int('0x144', 16) == 324. If the base is specified as 0, the number is interpreted using Python’s rules: a leading ‘0o’ indicates octal, and ‘0x’ indicates a hex number.

Do not use the built-in function eval() if all you need is to convert strings to numbers. eval() will be significantly slower and it presents a security risk: someone could pass you a Python expression that might have unwanted side effects. For example, someone could pass __import__('os').system("rm -rf $HOME") which would erase your home directory.

eval() also has the effect of interpreting numbers as Python expressions, so that e.g. eval('09') gives a syntax error because Python does not allow leading ‘0’ in a decimal number (except ‘0’).

How do I convert a number to a string?

To convert, e.g., the number 144 to the string ‘144’, use the built-in type constructor str(). If you want a hexadecimal or octal representation, use the built-in functions hex() or oct(). For fancy formatting, see the 포맷 문자열 리터럴 and 포맷 문자열 문법 sections, e.g. "{:04d}".format(144) yields '0144' and "{:.3f}".format(1.0/3.0) yields '0.333'.

How do I modify a string in place?

You can’t, because strings are immutable. In most situations, you should simply construct a new string from the various parts you want to assemble it from. However, if you need an object with the ability to modify in-place unicode data, try using an io.StringIO object or the array module:

>>> import io
>>> s = "Hello, world"
>>> sio = io.StringIO(s)
>>> sio.getvalue()
'Hello, world'
>>> sio.seek(7)
7
>>> sio.write("there!")
6
>>> sio.getvalue()
'Hello, there!'

>>> import array
>>> a = array.array('u', s)
>>> print(a)
array('u', 'Hello, world')
>>> a[0] = 'y'
>>> print(a)
array('u', 'yello, world')
>>> a.tounicode()
'yello, world'

How do I use strings to call functions/methods?

There are various techniques.

The best is to use a dictionary that maps strings to functions. The primary advantage of this technique is that the strings do not need to match the names of the functions. This is also the primary technique used to emulate a case construct:

def a():
    pass

def b():
    pass

dispatch = {'go': a, 'stop': b}  # Note lack of parens for funcs

dispatch[get_input()]()  # Note trailing parens to call function

Use the built-in function getattr():

import foo
getattr(foo, 'bar')()

Note that getattr() works on any object, including classes, class instances, modules, and so on.

This is used in several places in the standard library, like this:

class Foo:
    def do_foo(self):
        ...

    def do_bar(self):
        ...

f = getattr(foo_instance, 'do_' + opname)
f()

Use locals() or eval() to resolve the function name:

def myFunc():
    print("hello")

fname = "myFunc"

f = locals()[fname]
f()

f = eval(fname)
f()

Note: Using eval() is slow and dangerous. If you don’t have absolute control over the contents of the string, someone could pass a string that resulted in an arbitrary function being executed.

Is there an equivalent to Perl’s chomp() for removing trailing newlines from strings?

You can use S.rstrip("\r\n") to remove all occurrences of any line terminator from the end of the string S without removing other trailing whitespace. If the string S represents more than one line, with several empty lines at the end, the line terminators for all the blank lines will be removed:

>>> lines = ("line 1 \r\n"
...          "\r\n"
...          "\r\n")
>>> lines.rstrip("\n\r")
'line 1 '

Since this is typically only desired when reading text one line at a time, using S.rstrip() this way works well.

Is there a scanf() or sscanf() equivalent?

Not as such.

For simple input parsing, the easiest approach is usually to split the line into whitespace-delimited words using the split() method of string objects and then convert decimal strings to numeric values using int() or float(). split() supports an optional “sep” parameter which is useful if the line uses something other than whitespace as a separator.

For more complicated input parsing, regular expressions are more powerful than C’s sscanf() and better suited for the task.

What does ‘UnicodeDecodeError’ or ‘UnicodeEncodeError’ error mean?

See the 유니코드 HOWTO.

Performance

My program is too slow. How do I speed it up?

That’s a tough one, in general. First, here are a list of things to remember before diving further:

Performance characteristics vary across Python implementations. This FAQ focuses on CPython.

Behaviour can vary across operating systems, especially when talking about I/O or multi-threading.

You should always find the hot spots in your program before attempting to optimize any code (see the profile module).

Writing benchmark scripts will allow you to iterate quickly when searching for improvements (see the timeit module).

It is highly recommended to have good code coverage (through unit testing or any other technique) before potentially introducing regressions hidden in sophisticated optimizations.

That being said, there are many tricks to speed up Python code. Here are some general principles which go a long way towards reaching acceptable performance levels:

Making your algorithms faster (or changing to faster ones) can yield much larger benefits than trying to sprinkle micro-optimization tricks all over your code.

Use the right data structures. Study documentation for the 내장형 and the collections module.

When the standard library provides a primitive for doing something, it is likely (although not guaranteed) to be faster than any alternative you may come up with. This is doubly true for primitives written in C, such as builtins and some extension types. For example, be sure to use either the list.sort() built-in method or the related sorted() function to do sorting (and see the 정렬 HOW TO for examples of moderately advanced usage).

Abstractions tend to create indirections and force the interpreter to work more. If the levels of indirection outweigh the amount of useful work done, your program will be slower. You should avoid excessive abstraction, especially under the form of tiny functions or methods (which are also often detrimental to readability).

If you have reached the limit of what pure Python can allow, there are tools to take you further away. For example, Cython [http://cython.org] can compile a slightly modified version of Python code into a C extension, and can be used on many different platforms. Cython can take advantage of compilation (and optional type annotations) to make your code significantly faster than when interpreted. If you are confident in your C programming skills, you can also write a C extension module yourself.

더 보기

The wiki page devoted to performance tips [https://wiki.python.org/moin/PythonSpeed/PerformanceTips].

What is the most efficient way to concatenate many strings together?

str and bytes objects are immutable, therefore concatenating many strings together is inefficient as each concatenation creates a new object. In the general case, the total runtime cost is quadratic in the total string length.

To accumulate many str objects, the recommended idiom is to place them into a list and call str.join() at the end:

chunks = []
for s in my_strings:
    chunks.append(s)
result = ''.join(chunks)

(another reasonably efficient idiom is to use io.StringIO)

To accumulate many bytes objects, the recommended idiom is to extend a bytearray object using in-place concatenation (the += operator):

result = bytearray()
for b in my_bytes_objects:
    result += b

Sequences (Tuples/Lists)

How do I convert between tuples and lists?

The type constructor tuple(seq) converts any sequence (actually, any iterable) into a tuple with the same items in the same order.

For example, tuple([1, 2, 3]) yields (1, 2, 3) and tuple('abc') yields ('a', 'b', 'c'). If the argument is a tuple, it does not make a copy but returns the same object, so it is cheap to call tuple() when you aren’t sure that an object is already a tuple.

The type constructor list(seq) converts any sequence or iterable into a list with the same items in the same order. For example, list((1, 2, 3)) yields [1, 2, 3] and list('abc') yields ['a', 'b', 'c']. If the argument is a list, it makes a copy just like seq[:] would.

What’s a negative index?

Python sequences are indexed with positive numbers and negative numbers. For positive numbers 0 is the first index 1 is the second index and so forth. For negative indices -1 is the last index and -2 is the penultimate (next to last) index and so forth. Think of seq[-n] as the same as seq[len(seq)-n].

Using negative indices can be very convenient. For example S[:-1] is all of the string except for its last character, which is useful for removing the trailing newline from a string.

How do I iterate over a sequence in reverse order?

Use the reversed() built-in function, which is new in Python 2.4:

for x in reversed(sequence):
    ...  # do something with x ...

This won’t touch your original sequence, but build a new copy with reversed order to iterate over.

With Python 2.3, you can use an extended slice syntax:

for x in sequence[::-1]:
    ...  # do something with x ...

How do you remove duplicates from a list?

See the Python Cookbook for a long discussion of many ways to do this:

https://code.activestate.com/recipes/52560/

If you don’t mind reordering the list, sort it and then scan from the end of the list, deleting duplicates as you go:

if mylist:
    mylist.sort()
    last = mylist[-1]
    for i in range(len(mylist)-2, -1, -1):
        if last == mylist[i]:
            del mylist[i]
        else:
            last = mylist[i]

If all elements of the list may be used as set keys (i.e. they are all hashable) this is often faster

mylist = list(set(mylist))

This converts the list into a set, thereby removing duplicates, and then back into a list.

How do you make an array in Python?

Use a list:

["this", 1, "is", "an", "array"]

Lists are equivalent to C or Pascal arrays in their time complexity; the primary difference is that a Python list can contain objects of many different types.

The array module also provides methods for creating arrays of fixed types with compact representations, but they are slower to index than lists. Also note that the Numeric extensions and others define array-like structures with various characteristics as well.

To get Lisp-style linked lists, you can emulate cons cells using tuples:

lisp_list = ("like",  ("this",  ("example", None) ) )

If mutability is desired, you could use lists instead of tuples. Here the analogue of lisp car is lisp_list[0] and the analogue of cdr is lisp_list[1]. Only do this if you’re sure you really need to, because it’s usually a lot slower than using Python lists.

How do I create a multidimensional list?

You probably tried to make a multidimensional array like this:

>>> A = [[None] * 2] * 3

This looks correct if you print it:

>>> A
[[None, None], [None, None], [None, None]]

But when you assign a value, it shows up in multiple places:

>>> A[0][0] = 5
>>> A
[[5, None], [5, None], [5, None]]

The reason is that replicating a list with * doesn’t create copies, it only creates references to the existing objects. The *3 creates a list containing 3 references to the same list of length two. Changes to one row will show in all rows, which is almost certainly not what you want.

The suggested approach is to create a list of the desired length first and then fill in each element with a newly created list:

A = [None] * 3
for i in range(3):
    A[i] = [None] * 2

This generates a list containing 3 different lists of length two. You can also use a list comprehension:

w, h = 2, 3
A = [[None] * w for i in range(h)]

Or, you can use an extension that provides a matrix datatype; NumPy [http://www.numpy.org/] is the best known.

How do I apply a method to a sequence of objects?

Use a list comprehension:

result = [obj.method() for obj in mylist]

Why does a_tuple[i] += [‘item’] raise an exception when the addition works?

This is because of a combination of the fact that augmented assignment operators are assignment operators, and the difference between mutable and immutable objects in Python.

This discussion applies in general when augmented assignment operators are applied to elements of a tuple that point to mutable objects, but we’ll use a list and += as our exemplar.

If you wrote:

>>> a_tuple = (1, 2)
>>> a_tuple[0] += 1
Traceback (most recent call last):
   ...
TypeError: 'tuple' object does not support item assignment

The reason for the exception should be immediately clear: 1 is added to the object a_tuple[0] points to (1), producing the result object, 2, but when we attempt to assign the result of the computation, 2, to element 0 of the tuple, we get an error because we can’t change what an element of a tuple points to.

Under the covers, what this augmented assignment statement is doing is approximately this:

>>> result = a_tuple[0] + 1
>>> a_tuple[0] = result
Traceback (most recent call last):
  ...
TypeError: 'tuple' object does not support item assignment

It is the assignment part of the operation that produces the error, since a tuple is immutable.

When you write something like:

>>> a_tuple = (['foo'], 'bar')
>>> a_tuple[0] += ['item']
Traceback (most recent call last):
  ...
TypeError: 'tuple' object does not support item assignment

The exception is a bit more surprising, and even more surprising is the fact that even though there was an error, the append worked:

>>> a_tuple[0]
['foo', 'item']

To see why this happens, you need to know that (a) if an object implements an __iadd__ magic method, it gets called when the += augmented assignment is executed, and its return value is what gets used in the assignment statement; and (b) for lists, __iadd__ is equivalent to calling extend on the list and returning the list. That’s why we say that for lists, += is a “shorthand” for list.extend:

>>> a_list = []
>>> a_list += [1]
>>> a_list
[1]

This is equivalent to:

>>> result = a_list.__iadd__([1])
>>> a_list = result

The object pointed to by a_list has been mutated, and the pointer to the mutated object is assigned back to a_list. The end result of the assignment is a no-op, since it is a pointer to the same object that a_list was previously pointing to, but the assignment still happens.

Thus, in our tuple example what is happening is equivalent to:

>>> result = a_tuple[0].__iadd__(['item'])
>>> a_tuple[0] = result
Traceback (most recent call last):
  ...
TypeError: 'tuple' object does not support item assignment

The __iadd__ succeeds, and thus the list is extended, but even though result points to the same object that a_tuple[0] already points to, that final assignment still results in an error, because tuples are immutable.

I want to do a complicated sort: can you do a Schwartzian Transform in Python?

The technique, attributed to Randal Schwartz of the Perl community, sorts the elements of a list by a metric which maps each element to its “sort value”. In Python, use the key argument for the list.sort() method:

Isorted = L[:]
Isorted.sort(key=lambda s: int(s[10:15]))

How can I sort one list by values from another list?

Merge them into an iterator of tuples, sort the resulting list, and then pick out the element you want.

>>> list1 = ["what", "I'm", "sorting", "by"]
>>> list2 = ["something", "else", "to", "sort"]
>>> pairs = zip(list1, list2)
>>> pairs = sorted(pairs)
>>> pairs
[("I'm", 'else'), ('by', 'sort'), ('sorting', 'to'), ('what', 'something')]
>>> result = [x[1] for x in pairs]
>>> result
['else', 'sort', 'to', 'something']

An alternative for the last step is:

>>> result = []
>>> for p in pairs: result.append(p[1])

If you find this more legible, you might prefer to use this instead of the final list comprehension. However, it is almost twice as slow for long lists. Why? First, the append() operation has to reallocate memory, and while it uses some tricks to avoid doing that each time, it still has to do it occasionally, and that costs quite a bit. Second, the expression “result.append” requires an extra attribute lookup, and third, there’s a speed reduction from having to make all those function calls.

Objects

What is a class?

A class is the particular object type created by executing a class statement. Class objects are used as templates to create instance objects, which embody both the data (attributes) and code (methods) specific to a datatype.

A class can be based on one or more other classes, called its base class(es). It then inherits the attributes and methods of its base classes. This allows an object model to be successively refined by inheritance. You might have a generic Mailbox class that provides basic accessor methods for a mailbox, and subclasses such as MboxMailbox, MaildirMailbox, OutlookMailbox that handle various specific mailbox formats.

What is a method?

A method is a function on some object x that you normally call as x.name(arguments...). Methods are defined as functions inside the class definition:

class C:
    def meth(self, arg):
        return arg * 2 + self.attribute

What is self?

Self is merely a conventional name for the first argument of a method. A method defined as meth(self, a, b, c) should be called as x.meth(a, b, c) for some instance x of the class in which the definition occurs; the called method will think it is called as meth(x, a, b, c).

See also Why must ‘self’ be used explicitly in method definitions and calls?.

How do I check if an object is an instance of a given class or of a subclass of it?

Use the built-in function isinstance(obj, cls). You can check if an object is an instance of any of a number of classes by providing a tuple instead of a single class, e.g. isinstance(obj, (class1, class2, ...)), and can also check whether an object is one of Python’s built-in types, e.g. isinstance(obj, str) or isinstance(obj, (int, float, complex)).

Note that most programs do not use isinstance() on user-defined classes very often. If you are developing the classes yourself, a more proper object-oriented style is to define methods on the classes that encapsulate a particular behaviour, instead of checking the object’s class and doing a different thing based on what class it is. For example, if you have a function that does something:

def search(obj):
    if isinstance(obj, Mailbox):
        ...  # code to search a mailbox
    elif isinstance(obj, Document):
        ...  # code to search a document
    elif ...

A better approach is to define a search() method on all the classes and just call it:

class Mailbox:
    def search(self):
        ...  # code to search a mailbox

class Document:
    def search(self):
        ...  # code to search a document

obj.search()

What is delegation?

Delegation is an object oriented technique (also called a design pattern). Let’s say you have an object x and want to change the behaviour of just one of its methods. You can create a new class that provides a new implementation of the method you’re interested in changing and delegates all other methods to the corresponding method of x.

Python programmers can easily implement delegation. For example, the following class implements a class that behaves like a file but converts all written data to uppercase:

class UpperOut:

    def __init__(self, outfile):
        self._outfile = outfile

    def write(self, s):
        self._outfile.write(s.upper())

    def __getattr__(self, name):
        return getattr(self._outfile, name)

Here the UpperOut class redefines the write() method to convert the argument string to uppercase before calling the underlying self._outfile.write() method. All other methods are delegated to the underlying self._outfile object. The delegation is accomplished via the __getattr__ method; consult the language reference for more information about controlling attribute access.

Note that for more general cases delegation can get trickier. When attributes must be set as well as retrieved, the class must define a __setattr__() method too, and it must do so carefully. The basic implementation of __setattr__() is roughly equivalent to the following:

class X:
    ...
    def __setattr__(self, name, value):
        self.__dict__[name] = value
    ...

Most __setattr__() implementations must modify self.__dict__ to store local state for self without causing an infinite recursion.

How do I call a method defined in a base class from a derived class that overrides it?

Use the built-in super() function:

class Derived(Base):
    def meth(self):
        super(Derived, self).meth()

For version prior to 3.0, you may be using classic classes: For a class definition such as class Derived(Base): ... you can call method meth() defined in Base (or one of Base’s base classes) as Base.meth(self, arguments...). Here, Base.meth is an unbound method, so you need to provide the self argument.

How can I organize my code to make it easier to change the base class?

You could define an alias for the base class, assign the real base class to it before your class definition, and use the alias throughout your class. Then all you have to change is the value assigned to the alias. Incidentally, this trick is also handy if you want to decide dynamically (e.g. depending on availability of resources) which base class to use. Example:

BaseAlias = <real base class>

class Derived(BaseAlias):
    def meth(self):
        BaseAlias.meth(self)
        ...

How do I create static class data and static class methods?

Both static data and static methods (in the sense of C++ or Java) are supported in Python.

For static data, simply define a class attribute. To assign a new value to the attribute, you have to explicitly use the class name in the assignment:

class C:
    count = 0   # number of times C.__init__ called

    def __init__(self):
        C.count = C.count + 1

    def getcount(self):
        return C.count  # or return self.count

c.count also refers to C.count for any c such that isinstance(c, C) holds, unless overridden by c itself or by some class on the base-class search path from c.__class__ back to C.

Caution: within a method of C, an assignment like self.count = 42 creates a new and unrelated instance named “count” in self’s own dict. Rebinding of a class-static data name must always specify the class whether inside a method or not:

C.count = 314

Static methods are possible:

class C:
    @staticmethod
    def static(arg1, arg2, arg3):
        # No 'self' parameter!
        ...

However, a far more straightforward way to get the effect of a static method is via a simple module-level function:

def getcount():
    return C.count

If your code is structured so as to define one class (or tightly related class hierarchy) per module, this supplies the desired encapsulation.

How can I overload constructors (or methods) in Python?

This answer actually applies to all methods, but the question usually comes up first in the context of constructors.

In C++ you’d write

class C {
    C() { cout << "No arguments\n"; }
    C(int i) { cout << "Argument is " << i << "\n"; }
}

In Python you have to write a single constructor that catches all cases using default arguments. For example:

class C:
    def __init__(self, i=None):
        if i is None:
            print("No arguments")
        else:
            print("Argument is", i)

This is not entirely equivalent, but close enough in practice.

You could also try a variable-length argument list, e.g.

def __init__(self, *args):
    ...

The same approach works for all method definitions.

I try to use __spam and I get an error about _SomeClassName__spam.

Variable names with double leading underscores are “mangled” to provide a simple but effective way to define class private variables. Any identifier of the form __spam (at least two leading underscores, at most one trailing underscore) is textually replaced with _classname__spam, where classname is the current class name with any leading underscores stripped.

This doesn’t guarantee privacy: an outside user can still deliberately access the “_classname__spam” attribute, and private values are visible in the object’s __dict__. Many Python programmers never bother to use private variable names at all.

My class defines __del__ but it is not called when I delete the object.

There are several possible reasons for this.

The del statement does not necessarily call __del__() – it simply decrements the object’s reference count, and if this reaches zero __del__() is called.

If your data structures contain circular links (e.g. a tree where each child has a parent reference and each parent has a list of children) the reference counts will never go back to zero. Once in a while Python runs an algorithm to detect such cycles, but the garbage collector might run some time after the last reference to your data structure vanishes, so your __del__() method may be called at an inconvenient and random time. This is inconvenient if you’re trying to reproduce a problem. Worse, the order in which object’s __del__() methods are executed is arbitrary. You can run gc.collect() to force a collection, but there are pathological cases where objects will never be collected.

Despite the cycle collector, it’s still a good idea to define an explicit close() method on objects to be called whenever you’re done with them. The close() method can then remove attributes that refer to subobjects. Don’t call __del__() directly – __del__() should call close() and close() should make sure that it can be called more than once for the same object.

Another way to avoid cyclical references is to use the weakref module, which allows you to point to objects without incrementing their reference count. Tree data structures, for instance, should use weak references for their parent and sibling references (if they need them!).

Finally, if your __del__() method raises an exception, a warning message is printed to sys.stderr.

How do I get a list of all instances of a given class?

Python does not keep track of all instances of a class (or of a built-in type). You can program the class’s constructor to keep track of all instances by keeping a list of weak references to each instance.

Why does the result of id() appear to be not unique?

The id() builtin returns an integer that is guaranteed to be unique during the lifetime of the object. Since in CPython, this is the object’s memory address, it happens frequently that after an object is deleted from memory, the next freshly created object is allocated at the same position in memory. This is illustrated by this example:

>>> id(1000)
13901272
>>> id(2000)
13901272

The two ids belong to different integer objects that are created before, and deleted immediately after execution of the id() call. To be sure that objects whose id you want to examine are still alive, create another reference to the object:

>>> a = 1000; b = 2000
>>> id(a)
13901272
>>> id(b)
13891296

Modules

How do I create a .pyc file?

When a module is imported for the first time (or when the source file has changed since the current compiled file was created) a .pyc file containing the compiled code should be created in a __pycache__ subdirectory of the directory containing the .py file. The .pyc file will have a filename that starts with the same name as the .py file, and ends with .pyc, with a middle component that depends on the particular python binary that created it. (See PEP 3147 [https://www.python.org/dev/peps/pep-3147] for details.)

One reason that a .pyc file may not be created is a permissions problem with the directory containing the source file, meaning that the __pycache__ subdirectory cannot be created. This can happen, for example, if you develop as one user but run as another, such as if you are testing with a web server.

Unless the PYTHONDONTWRITEBYTECODE environment variable is set, creation of a .pyc file is automatic if you’re importing a module and Python has the ability (permissions, free space, etc…) to create a __pycache__ subdirectory and write the compiled module to that subdirectory.

Running Python on a top level script is not considered an import and no .pyc will be created. For example, if you have a top-level module foo.py that imports another module xyz.py, when you run foo (by typing python foo.py as a shell command), a .pyc will be created for xyz because xyz is imported, but no .pyc file will be created for foo since foo.py isn’t being imported.

If you need to create a .pyc file for foo – that is, to create a .pyc file for a module that is not imported – you can, using the py_compile and compileall modules.

The py_compile module can manually compile any module. One way is to use the compile() function in that module interactively:

>>> import py_compile
>>> py_compile.compile('foo.py')

This will write the .pyc to a __pycache__ subdirectory in the same location as foo.py (or you can override that with the optional parameter cfile).

You can also automatically compile all files in a directory or directories using the compileall module. You can do it from the shell prompt by running compileall.py and providing the path of a directory containing Python files to compile:

python -m compileall .

How do I find the current module name?

A module can find out its own module name by looking at the predefined global variable __name__. If this has the value '__main__', the program is running as a script. Many modules that are usually used by importing them also provide a command-line interface or a self-test, and only execute this code after checking __name__:

def main():
    print('Running test...')
    ...

if __name__ == '__main__':
    main()

How can I have modules that mutually import each other?

Suppose you have the following modules:

foo.py:

from bar import bar_var
foo_var = 1

bar.py:

from foo import foo_var
bar_var = 2

The problem is that the interpreter will perform the following steps:

main imports foo

Empty globals for foo are created

foo is compiled and starts executing

foo imports bar

Empty globals for bar are created

bar is compiled and starts executing

bar imports foo (which is a no-op since there already is a module named foo)

bar.foo_var = foo.foo_var

The last step fails, because Python isn’t done with interpreting foo yet and the global symbol dictionary for foo is still empty.

The same thing happens when you use import foo, and then try to access foo.foo_var in global code.

There are (at least) three possible workarounds for this problem.

Guido van Rossum recommends avoiding all uses of from <module> import ..., and placing all code inside functions. Initializations of global variables and class variables should use constants or built-in functions only. This means everything from an imported module is referenced as <module>.<name>.

Jim Roskind suggests performing steps in the following order in each module:

exports (globals, functions, and classes that don’t need imported base classes)

import statements

active code (including globals that are initialized from imported values).

van Rossum doesn’t like this approach much because the imports appear in a strange place, but it does work.

Matthias Urlichs recommends restructuring your code so that the recursive import is not necessary in the first place.

These solutions are not mutually exclusive.

__import__(‘x.y.z’) returns <module ‘x’>; how do I get z?

Consider using the convenience function import_module() from importlib instead:

z = importlib.import_module('x.y.z')

When I edit an imported module and reimport it, the changes don’t show up. Why does this happen?

For reasons of efficiency as well as consistency, Python only reads the module file on the first time a module is imported. If it didn’t, in a program consisting of many modules where each one imports the same basic module, the basic module would be parsed and re-parsed many times. To force re-reading of a changed module, do this:

import importlib
import modname
importlib.reload(modname)

Warning: this technique is not 100% fool-proof. In particular, modules containing statements like

from modname import some_objects

will continue to work with the old version of the imported objects. If the module contains class definitions, existing class instances will not be updated to use the new class definition. This can result in the following paradoxical behaviour:

>>> import importlib
>>> import cls
>>> c = cls.C()                # Create an instance of C
>>> importlib.reload(cls)
<module 'cls' from 'cls.py'>
>>> isinstance(c, cls.C)       # isinstance is false?!?
False

The nature of the problem is made clear if you print out the “identity” of the class objects:

>>> hex(id(c.__class__))
'0x7352a0'
>>> hex(id(cls.C))
'0x4198d0'

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 자주 나오는 질문들 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 자주 나오는 질문들 »

|

Design and History FAQ

목차

Design and History FAQ

Why does Python use indentation for grouping of statements?

Why am I getting strange results with simple arithmetic operations?

Why are floating-point calculations so inaccurate?

Why are Python strings immutable?

Why must ‘self’ be used explicitly in method definitions and calls?

Why can’t I use an assignment in an expression?

Why does Python use methods for some functionality (e.g. list.index()) but functions for other (e.g. len(list))?

Why is join() a string method instead of a list or tuple method?

How fast are exceptions?

Why isn’t there a switch or case statement in Python?

Can’t you emulate threads in the interpreter instead of relying on an OS-specific thread implementation?

Why can’t lambda expressions contain statements?

Can Python be compiled to machine code, C or some other language?

How does Python manage memory?

Why doesn’t CPython use a more traditional garbage collection scheme?

Why isn’t all memory freed when CPython exits?

Why are there separate tuple and list data types?

How are lists implemented in CPython?

How are dictionaries implemented in CPython?

Why must dictionary keys be immutable?

Why doesn’t list.sort() return the sorted list?

How do you specify and enforce an interface spec in Python?

Why is there no goto?

Why can’t raw strings (r-strings) end with a backslash?

Why doesn’t Python have a “with” statement for attribute assignments?

Why are colons required for the if/while/def/class statements?

Why does Python allow commas at the end of lists and tuples?

Why does Python use indentation for grouping of statements?

Guido van Rossum believes that using indentation for grouping is extremely elegant and contributes a lot to the clarity of the average Python program. Most people learn to love this feature after a while.

Since there are no begin/end brackets there cannot be a disagreement between grouping perceived by the parser and the human reader. Occasionally C programmers will encounter a fragment of code like this:

if (x <= y)
        x++;
        y--;
z++;

Only the x++ statement is executed if the condition is true, but the indentation leads you to believe otherwise. Even experienced C programmers will sometimes stare at it a long time wondering why y is being decremented even for x > y.

Because there are no begin/end brackets, Python is much less prone to coding-style conflicts. In C there are many different ways to place the braces. If you’re used to reading and writing code that uses one style, you will feel at least slightly uneasy when reading (or being required to write) another style.

Many coding styles place begin/end brackets on a line by themselves. This makes programs considerably longer and wastes valuable screen space, making it harder to get a good overview of a program. Ideally, a function should fit on one screen (say, 20–30 lines). 20 lines of Python can do a lot more work than 20 lines of C. This is not solely due to the lack of begin/end brackets – the lack of declarations and the high-level data types are also responsible – but the indentation-based syntax certainly helps.

Why am I getting strange results with simple arithmetic operations?

See the next question.

Why are floating-point calculations so inaccurate?

Users are often surprised by results like this:

>>> 1.2 - 1.0
0.19999999999999996

and think it is a bug in Python. It’s not. This has little to do with Python, and much more to do with how the underlying platform handles floating-point numbers.

The float type in CPython uses a C double for storage. A float object’s value is stored in binary floating-point with a fixed precision (typically 53 bits) and Python uses C operations, which in turn rely on the hardware implementation in the processor, to perform floating-point operations. This means that as far as floating-point operations are concerned, Python behaves like many popular languages including C and Java.

Many numbers that can be written easily in decimal notation cannot be expressed exactly in binary floating-point. For example, after:

>>> x = 1.2

the value stored for x is a (very good) approximation to the decimal value 1.2, but is not exactly equal to it. On a typical machine, the actual stored value is:

1.0011001100110011001100110011001100110011001100110011 (binary)

which is exactly:

1.1999999999999999555910790149937383830547332763671875 (decimal)

The typical precision of 53 bits provides Python floats with 15–16 decimal digits of accuracy.

For a fuller explanation, please see the floating point arithmetic chapter in the Python tutorial.

Why are Python strings immutable?

There are several advantages.

One is performance: knowing that a string is immutable means we can allocate space for it at creation time, and the storage requirements are fixed and unchanging. This is also one of the reasons for the distinction between tuples and lists.

Another advantage is that strings in Python are considered as “elemental” as numbers. No amount of activity will change the value 8 to anything else, and in Python, no amount of activity will change the string “eight” to anything else.

Why must ‘self’ be used explicitly in method definitions and calls?

The idea was borrowed from Modula-3. It turns out to be very useful, for a variety of reasons.

First, it’s more obvious that you are using a method or instance attribute instead of a local variable. Reading self.x or self.meth() makes it absolutely clear that an instance variable or method is used even if you don’t know the class definition by heart. In C++, you can sort of tell by the lack of a local variable declaration (assuming globals are rare or easily recognizable) – but in Python, there are no local variable declarations, so you’d have to look up the class definition to be sure. Some C++ and Java coding standards call for instance attributes to have an m_ prefix, so this explicitness is still useful in those languages, too.

Second, it means that no special syntax is necessary if you want to explicitly reference or call the method from a particular class. In C++, if you want to use a method from a base class which is overridden in a derived class, you have to use the :: operator – in Python you can write baseclass.methodname(self, <argument list>). This is particularly useful for __init__() methods, and in general in cases where a derived class method wants to extend the base class method of the same name and thus has to call the base class method somehow.

Finally, for instance variables it solves a syntactic problem with assignment: since local variables in Python are (by definition!) those variables to which a value is assigned in a function body (and that aren’t explicitly declared global), there has to be some way to tell the interpreter that an assignment was meant to assign to an instance variable instead of to a local variable, and it should preferably be syntactic (for efficiency reasons). C++ does this through declarations, but Python doesn’t have declarations and it would be a pity having to introduce them just for this purpose. Using the explicit self.var solves this nicely. Similarly, for using instance variables, having to write self.var means that references to unqualified names inside a method don’t have to search the instance’s directories. To put it another way, local variables and instance variables live in two different namespaces, and you need to tell Python which namespace to use.

Why can’t I use an assignment in an expression?

Many people used to C or Perl complain that they want to use this C idiom:

while (line = readline(f)) {
    // do something with line
}

where in Python you’re forced to write this:

while True:
    line = f.readline()
    if not line:
        break
    ...  # do something with line

The reason for not allowing assignment in Python expressions is a common, hard-to-find bug in those other languages, caused by this construct:

if (x = 0) {
    // error handling
}
else {
    // code that only works for nonzero x
}

The error is a simple typo: x = 0, which assigns 0 to the variable x, was written while the comparison x == 0 is certainly what was intended.

Many alternatives have been proposed. Most are hacks that save some typing but use arbitrary or cryptic syntax or keywords, and fail the simple criterion for language change proposals: it should intuitively suggest the proper meaning to a human reader who has not yet been introduced to the construct.

An interesting phenomenon is that most experienced Python programmers recognize the while True idiom and don’t seem to be missing the assignment in expression construct much; it’s only newcomers who express a strong desire to add this to the language.

There’s an alternative way of spelling this that seems attractive but is generally less robust than the “while True” solution:

line = f.readline()
while line:
    ...  # do something with line...
    line = f.readline()

The problem with this is that if you change your mind about exactly how you get the next line (e.g. you want to change it into sys.stdin.readline()) you have to remember to change two places in your program – the second occurrence is hidden at the bottom of the loop.

The best approach is to use iterators, making it possible to loop through objects using the for statement. For example, file objects support the iterator protocol, so you can write simply:

for line in f:
    ...  # do something with line...

Why does Python use methods for some functionality (e.g. list.index()) but functions for other (e.g. len(list))?

As Guido said:

(a) For some operations, prefix notation just reads better than postfix – prefix (and infix!) operations have a long tradition in mathematics which likes notations where the visuals help the mathematician thinking about a problem. Compare the easy with which we rewrite a formula like x*(a+b) into x*a + x*b to the clumsiness of doing the same thing using a raw OO notation.

(b) When I read code that says len(x) I know that it is asking for the length of something. This tells me two things: the result is an integer, and the argument is some kind of container. To the contrary, when I read x.len(), I have to already know that x is some kind of container implementing an interface or inheriting from a class that has a standard len(). Witness the confusion we occasionally have when a class that is not implementing a mapping has a get() or keys() method, or something that isn’t a file has a write() method.

—https://mail.python.org/pipermail/python-3000/2006-November/004643.html

Why is join() a string method instead of a list or tuple method?

Strings became much more like other standard types starting in Python 1.6, when methods were added which give the same functionality that has always been available using the functions of the string module. Most of these new methods have been widely accepted, but the one which appears to make some programmers feel uncomfortable is:

", ".join(['1', '2', '4', '8', '16'])

which gives the result:

"1, 2, 4, 8, 16"

There are two common arguments against this usage.

The first runs along the lines of: “It looks really ugly using a method of a string literal (string constant)”, to which the answer is that it might, but a string literal is just a fixed value. If the methods are to be allowed on names bound to strings there is no logical reason to make them unavailable on literals.

The second objection is typically cast as: “I am really telling a sequence to join its members together with a string constant”. Sadly, you aren’t. For some reason there seems to be much less difficulty with having split() as a string method, since in that case it is easy to see that

"1, 2, 4, 8, 16".split(", ")

is an instruction to a string literal to return the substrings delimited by the given separator (or, by default, arbitrary runs of white space).

join() is a string method because in using it you are telling the separator string to iterate over a sequence of strings and insert itself between adjacent elements. This method can be used with any argument which obeys the rules for sequence objects, including any new classes you might define yourself. Similar methods exist for bytes and bytearray objects.

How fast are exceptions?

A try/except block is extremely efficient if no exceptions are raised. Actually catching an exception is expensive. In versions of Python prior to 2.0 it was common to use this idiom:

try:
    value = mydict[key]
except KeyError:
    mydict[key] = getvalue(key)
    value = mydict[key]

This only made sense when you expected the dict to have the key almost all the time. If that wasn’t the case, you coded it like this:

if key in mydict:
    value = mydict[key]
else:
    value = mydict[key] = getvalue(key)

For this specific case, you could also use value = dict.setdefault(key, getvalue(key)), but only if the getvalue() call is cheap enough because it is evaluated in all cases.

Why isn’t there a switch or case statement in Python?

You can do this easily enough with a sequence of if... elif... elif... else. There have been some proposals for switch statement syntax, but there is no consensus (yet) on whether and how to do range tests. See PEP 275 [https://www.python.org/dev/peps/pep-0275] for complete details and the current status.

For cases where you need to choose from a very large number of possibilities, you can create a dictionary mapping case values to functions to call. For example:

def function_1(...):
    ...

functions = {'a': function_1,
             'b': function_2,
             'c': self.method_1, ...}

func = functions[value]
func()

For calling methods on objects, you can simplify yet further by using the getattr() built-in to retrieve methods with a particular name:

def visit_a(self, ...):
    ...
...

def dispatch(self, value):
    method_name = 'visit_' + str(value)
    method = getattr(self, method_name)
    method()

It’s suggested that you use a prefix for the method names, such as visit_ in this example. Without such a prefix, if values are coming from an untrusted source, an attacker would be able to call any method on your object.

Can’t you emulate threads in the interpreter instead of relying on an OS-specific thread implementation?

Answer 1: Unfortunately, the interpreter pushes at least one C stack frame for each Python stack frame. Also, extensions can call back into Python at almost random moments. Therefore, a complete threads implementation requires thread support for C.

Answer 2: Fortunately, there is Stackless Python [https://github.com/stackless-dev/stackless/wiki], which has a completely redesigned interpreter loop that avoids the C stack.

Why can’t lambda expressions contain statements?

Python lambda expressions cannot contain statements because Python’s syntactic framework can’t handle statements nested inside expressions. However, in Python, this is not a serious problem. Unlike lambda forms in other languages, where they add functionality, Python lambdas are only a shorthand notation if you’re too lazy to define a function.

Functions are already first class objects in Python, and can be declared in a local scope. Therefore the only advantage of using a lambda instead of a locally-defined function is that you don’t need to invent a name for the function – but that’s just a local variable to which the function object (which is exactly the same type of object that a lambda expression yields) is assigned!

Can Python be compiled to machine code, C or some other language?

Cython [http://cython.org/] compiles a modified version of Python with optional annotations into C extensions. Nuitka [http://www.nuitka.net/] is an up-and-coming compiler of Python into C++ code, aiming to support the full Python language. For compiling to Java you can consider VOC [https://voc.readthedocs.io].

How does Python manage memory?

The details of Python memory management depend on the implementation. The standard implementation of Python, CPython, uses reference counting to detect inaccessible objects, and another mechanism to collect reference cycles, periodically executing a cycle detection algorithm which looks for inaccessible cycles and deletes the objects involved. The gc module provides functions to perform a garbage collection, obtain debugging statistics, and tune the collector’s parameters.

Other implementations (such as Jython [http://www.jython.org] or PyPy [http://www.pypy.org]), however, can rely on a different mechanism such as a full-blown garbage collector. This difference can cause some subtle porting problems if your Python code depends on the behavior of the reference counting implementation.

In some Python implementations, the following code (which is fine in CPython) will probably run out of file descriptors:

for file in very_long_list_of_files:
    f = open(file)
    c = f.read(1)

Indeed, using CPython’s reference counting and destructor scheme, each new assignment to f closes the previous file. With a traditional GC, however, those file objects will only get collected (and closed) at varying and possibly long intervals.

If you want to write code that will work with any Python implementation, you should explicitly close the file or use the with statement; this will work regardless of memory management scheme:

for file in very_long_list_of_files:
    with open(file) as f:
        c = f.read(1)

Why doesn’t CPython use a more traditional garbage collection scheme?

For one thing, this is not a C standard feature and hence it’s not portable. (Yes, we know about the Boehm GC library. It has bits of assembler code for most common platforms, not for all of them, and although it is mostly transparent, it isn’t completely transparent; patches are required to get Python to work with it.)

Traditional GC also becomes a problem when Python is embedded into other applications. While in a standalone Python it’s fine to replace the standard malloc() and free() with versions provided by the GC library, an application embedding Python may want to have its own substitute for malloc() and free(), and may not want Python’s. Right now, CPython works with anything that implements malloc() and free() properly.

Why isn’t all memory freed when CPython exits?

Objects referenced from the global namespaces of Python modules are not always deallocated when Python exits. This may happen if there are circular references. There are also certain bits of memory that are allocated by the C library that are impossible to free (e.g. a tool like Purify will complain about these). Python is, however, aggressive about cleaning up memory on exit and does try to destroy every single object.

If you want to force Python to delete certain things on deallocation use the atexit module to run a function that will force those deletions.

Why are there separate tuple and list data types?

Lists and tuples, while similar in many respects, are generally used in fundamentally different ways. Tuples can be thought of as being similar to Pascal records or C structs; they’re small collections of related data which may be of different types which are operated on as a group. For example, a Cartesian coordinate is appropriately represented as a tuple of two or three numbers.

Lists, on the other hand, are more like arrays in other languages. They tend to hold a varying number of objects all of which have the same type and which are operated on one-by-one. For example, os.listdir('.') returns a list of strings representing the files in the current directory. Functions which operate on this output would generally not break if you added another file or two to the directory.

Tuples are immutable, meaning that once a tuple has been created, you can’t replace any of its elements with a new value. Lists are mutable, meaning that you can always change a list’s elements. Only immutable elements can be used as dictionary keys, and hence only tuples and not lists can be used as keys.

How are lists implemented in CPython?

CPython’s lists are really variable-length arrays, not Lisp-style linked lists. The implementation uses a contiguous array of references to other objects, and keeps a pointer to this array and the array’s length in a list head structure.

This makes indexing a list a[i] an operation whose cost is independent of the size of the list or the value of the index.

When items are appended or inserted, the array of references is resized. Some cleverness is applied to improve the performance of appending items repeatedly; when the array must be grown, some extra space is allocated so the next few times don’t require an actual resize.

How are dictionaries implemented in CPython?

CPython’s dictionaries are implemented as resizable hash tables. Compared to B-trees, this gives better performance for lookup (the most common operation by far) under most circumstances, and the implementation is simpler.

Dictionaries work by computing a hash code for each key stored in the dictionary using the hash() built-in function. The hash code varies widely depending on the key and a per-process seed; for example, “Python” could hash to -539294296 while “python”, a string that differs by a single bit, could hash to 1142331976. The hash code is then used to calculate a location in an internal array where the value will be stored. Assuming that you’re storing keys that all have different hash values, this means that dictionaries take constant time – O(1), in Big-O notation – to retrieve a key.

Why must dictionary keys be immutable?

The hash table implementation of dictionaries uses a hash value calculated from the key value to find the key. If the key were a mutable object, its value could change, and thus its hash could also change. But since whoever changes the key object can’t tell that it was being used as a dictionary key, it can’t move the entry around in the dictionary. Then, when you try to look up the same object in the dictionary it won’t be found because its hash value is different. If you tried to look up the old value it wouldn’t be found either, because the value of the object found in that hash bin would be different.

If you want a dictionary indexed with a list, simply convert the list to a tuple first; the function tuple(L) creates a tuple with the same entries as the list L. Tuples are immutable and can therefore be used as dictionary keys.

Some unacceptable solutions that have been proposed:

Hash lists by their address (object ID). This doesn’t work because if you construct a new list with the same value it won’t be found; e.g.:

mydict = {[1, 2]: '12'}
print(mydict[[1, 2]])

would raise a KeyError exception because the id of the [1, 2] used in the second line differs from that in the first line. In other words, dictionary keys should be compared using ==, not using is.

Make a copy when using a list as a key. This doesn’t work because the list, being a mutable object, could contain a reference to itself, and then the copying code would run into an infinite loop.

Allow lists as keys but tell the user not to modify them. This would allow a class of hard-to-track bugs in programs when you forgot or modified a list by accident. It also invalidates an important invariant of dictionaries: every value in d.keys() is usable as a key of the dictionary.

Mark lists as read-only once they are used as a dictionary key. The problem is that it’s not just the top-level object that could change its value; you could use a tuple containing a list as a key. Entering anything as a key into a dictionary would require marking all objects reachable from there as read-only – and again, self-referential objects could cause an infinite loop.

There is a trick to get around this if you need to, but use it at your own risk: You can wrap a mutable structure inside a class instance which has both a __eq__() and a __hash__() method. You must then make sure that the hash value for all such wrapper objects that reside in a dictionary (or other hash based structure), remain fixed while the object is in the dictionary (or other structure).

class ListWrapper:
    def __init__(self, the_list):
        self.the_list = the_list

    def __eq__(self, other):
        return self.the_list == other.the_list

    def __hash__(self):
        l = self.the_list
        result = 98767 - len(l)*555
        for i, el in enumerate(l):
            try:
                result = result + (hash(el) % 9999999) * 1001 + i
            except Exception:
                result = (result % 7777777) + i * 333
        return result

Note that the hash computation is complicated by the possibility that some members of the list may be unhashable and also by the possibility of arithmetic overflow.

Furthermore it must always be the case that if o1 == o2 (ie o1.__eq__(o2) is True) then hash(o1) == hash(o2) (ie, o1.__hash__() == o2.__hash__()), regardless of whether the object is in a dictionary or not. If you fail to meet these restrictions dictionaries and other hash based structures will misbehave.

In the case of ListWrapper, whenever the wrapper object is in a dictionary the wrapped list must not change to avoid anomalies. Don’t do this unless you are prepared to think hard about the requirements and the consequences of not meeting them correctly. Consider yourself warned.

Why doesn’t list.sort() return the sorted list?

In situations where performance matters, making a copy of the list just to sort it would be wasteful. Therefore, list.sort() sorts the list in place. In order to remind you of that fact, it does not return the sorted list. This way, you won’t be fooled into accidentally overwriting a list when you need a sorted copy but also need to keep the unsorted version around.

If you want to return a new list, use the built-in sorted() function instead. This function creates a new list from a provided iterable, sorts it and returns it. For example, here’s how to iterate over the keys of a dictionary in sorted order:

for key in sorted(mydict):
    ...  # do whatever with mydict[key]...

How do you specify and enforce an interface spec in Python?

An interface specification for a module as provided by languages such as C++ and Java describes the prototypes for the methods and functions of the module. Many feel that compile-time enforcement of interface specifications helps in the construction of large programs.

Python 2.6 adds an abc module that lets you define Abstract Base Classes (ABCs). You can then use isinstance() and issubclass() to check whether an instance or a class implements a particular ABC. The collections.abc module defines a set of useful ABCs such as Iterable, Container, and MutableMapping.

For Python, many of the advantages of interface specifications can be obtained by an appropriate test discipline for components. There is also a tool, PyChecker, which can be used to find problems due to subclassing.

A good test suite for a module can both provide a regression test and serve as a module interface specification and a set of examples. Many Python modules can be run as a script to provide a simple “self test.” Even modules which use complex external interfaces can often be tested in isolation using trivial “stub” emulations of the external interface. The doctest and unittest modules or third-party test frameworks can be used to construct exhaustive test suites that exercise every line of code in a module.

An appropriate testing discipline can help build large complex applications in Python as well as having interface specifications would. In fact, it can be better because an interface specification cannot test certain properties of a program. For example, the append() method is expected to add new elements to the end of some internal list; an interface specification cannot test that your append() implementation will actually do this correctly, but it’s trivial to check this property in a test suite.

Writing test suites is very helpful, and you might want to design your code with an eye to making it easily tested. One increasingly popular technique, test-directed development, calls for writing parts of the test suite first, before you write any of the actual code. Of course Python allows you to be sloppy and not write test cases at all.

Why is there no goto?

You can use exceptions to provide a “structured goto” that even works across function calls. Many feel that exceptions can conveniently emulate all reasonable uses of the “go” or “goto” constructs of C, Fortran, and other languages. For example:

class label(Exception): pass  # declare a label

try:
    ...
    if condition: raise label()  # goto label
    ...
except label:  # where to goto
    pass
...

This doesn’t allow you to jump into the middle of a loop, but that’s usually considered an abuse of goto anyway. Use sparingly.

Why can’t raw strings (r-strings) end with a backslash?

More precisely, they can’t end with an odd number of backslashes: the unpaired backslash at the end escapes the closing quote character, leaving an unterminated string.

Raw strings were designed to ease creating input for processors (chiefly regular expression engines) that want to do their own backslash escape processing. Such processors consider an unmatched trailing backslash to be an error anyway, so raw strings disallow that. In return, they allow you to pass on the string quote character by escaping it with a backslash. These rules work well when r-strings are used for their intended purpose.

If you’re trying to build Windows pathnames, note that all Windows system calls accept forward slashes too:

f = open("/mydir/file.txt")  # works fine!

If you’re trying to build a pathname for a DOS command, try e.g. one of

dir = r"\this\is\my\dos\dir" "\\"
dir = r"\this\is\my\dos\dir\ "[:-1]
dir = "\\this\\is\\my\\dos\\dir\\"

Why doesn’t Python have a “with” statement for attribute assignments?

Python has a ‘with’ statement that wraps the execution of a block, calling code on the entrance and exit from the block. Some language have a construct that looks like this:

with obj:
    a = 1               # equivalent to obj.a = 1
    total = total + 1   # obj.total = obj.total + 1

In Python, such a construct would be ambiguous.

Other languages, such as Object Pascal, Delphi, and C++, use static types, so it’s possible to know, in an unambiguous way, what member is being assigned to. This is the main point of static typing – the compiler always knows the scope of every variable at compile time.

Python uses dynamic types. It is impossible to know in advance which attribute will be referenced at runtime. Member attributes may be added or removed from objects on the fly. This makes it impossible to know, from a simple reading, what attribute is being referenced: a local one, a global one, or a member attribute?

For instance, take the following incomplete snippet:

def foo(a):
    with a:
        print(x)

The snippet assumes that “a” must have a member attribute called “x”. However, there is nothing in Python that tells the interpreter this. What should happen if “a” is, let us say, an integer? If there is a global variable named “x”, will it be used inside the with block? As you see, the dynamic nature of Python makes such choices much harder.

The primary benefit of “with” and similar language features (reduction of code volume) can, however, easily be achieved in Python by assignment. Instead of:

function(args).mydict[index][index].a = 21
function(args).mydict[index][index].b = 42
function(args).mydict[index][index].c = 63

write this:

ref = function(args).mydict[index][index]
ref.a = 21
ref.b = 42
ref.c = 63

This also has the side-effect of increasing execution speed because name bindings are resolved at run-time in Python, and the second version only needs to perform the resolution once.

Why are colons required for the if/while/def/class statements?

The colon is required primarily to enhance readability (one of the results of the experimental ABC language). Consider this:

if a == b
    print(a)

versus

if a == b:
    print(a)

Notice how the second one is slightly easier to read. Notice further how a colon sets off the example in this FAQ answer; it’s a standard usage in English.

Another minor reason is that the colon makes it easier for editors with syntax highlighting; they can look for colons to decide when indentation needs to be increased instead of having to do a more elaborate parsing of the program text.

Why does Python allow commas at the end of lists and tuples?

Python lets you add a trailing comma at the end of lists, tuples, and dictionaries:

[1, 2, 3,]
('a', 'b', 'c',)
d = {
    "A": [1, 5],
    "B": [6, 7],  # last trailing comma is optional but good style
}

There are several reasons to allow this.

When you have a literal value for a list, tuple, or dictionary spread across multiple lines, it’s easier to add more elements because you don’t have to remember to add a comma to the previous line. The lines can also be reordered without creating a syntax error.

Accidentally omitting the comma can lead to errors that are hard to diagnose. For example:

x = [
  "fee",
  "fie"
  "foo",
  "fum"
]

This list looks like it has four elements, but it actually contains three: “fee”, “fiefoo” and “fum”. Always adding the comma avoids this source of error.

Allowing the trailing comma may also make programmatic code generation easier.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 자주 나오는 질문들 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 자주 나오는 질문들 »

|

Library and Extension FAQ

목차

Library and Extension FAQ

General Library Questions

How do I find a module or application to perform task X?

Where is the math.py (socket.py, regex.py, etc.) source file?

How do I make a Python script executable on Unix?

Is there a curses/termcap package for Python?

Is there an equivalent to C’s onexit() in Python?

Why don’t my signal handlers work?

Common tasks

How do I test a Python program or component?

How do I create documentation from doc strings?

How do I get a single keypress at a time?

Threads

How do I program using threads?

None of my threads seem to run: why?

How do I parcel out work among a bunch of worker threads?

What kinds of global value mutation are thread-safe?

Can’t we get rid of the Global Interpreter Lock?

Input and Output

How do I delete a file? (And other file questions…)

How do I copy a file?

How do I read (or write) binary data?

I can’t seem to use os.read() on a pipe created with os.popen(); why?

How do I access the serial (RS232) port?

Why doesn’t closing sys.stdout (stdin, stderr) really close it?

Network/Internet Programming

What WWW tools are there for Python?

How can I mimic CGI form submission (METHOD=POST)?

What module should I use to help with generating HTML?

How do I send mail from a Python script?

How do I avoid blocking in the connect() method of a socket?

Databases

Are there any interfaces to database packages in Python?

How do you implement persistent objects in Python?

Mathematics and Numerics

How do I generate random numbers in Python?

General Library Questions

How do I find a module or application to perform task X?

Check the Library Reference to see if there’s a relevant standard library module. (Eventually you’ll learn what’s in the standard library and will be able to skip this step.)

For third-party packages, search the Python Package Index [https://pypi.org] or try Google [https://www.google.com] or another Web search engine. Searching for “Python” plus a keyword or two for your topic of interest will usually find something helpful.

Where is the math.py (socket.py, regex.py, etc.) source file?

If you can’t find a source file for a module it may be a built-in or dynamically loaded module implemented in C, C++ or other compiled language. In this case you may not have the source file or it may be something like mathmodule.c, somewhere in a C source directory (not on the Python Path).

There are (at least) three kinds of modules in Python:

modules written in Python (.py);

modules written in C and dynamically loaded (.dll, .pyd, .so, .sl, etc);

modules written in C and linked with the interpreter; to get a list of these, type:

import sys
print(sys.builtin_module_names)

How do I make a Python script executable on Unix?

You need to do two things: the script file’s mode must be executable and the first line must begin with #! followed by the path of the Python interpreter.

The first is done by executing chmod +x scriptfile or perhaps chmod 755 scriptfile.

The second can be done in a number of ways. The most straightforward way is to write

#!/usr/local/bin/python

as the very first line of your file, using the pathname for where the Python interpreter is installed on your platform.

If you would like the script to be independent of where the Python interpreter lives, you can use the env program. Almost all Unix variants support the following, assuming the Python interpreter is in a directory on the user’s PATH:

#!/usr/bin/env python

Don’t do this for CGI scripts. The PATH variable for CGI scripts is often very minimal, so you need to use the actual absolute pathname of the interpreter.

Occasionally, a user’s environment is so full that the /usr/bin/env program fails; or there’s no env program at all. In that case, you can try the following hack (due to Alex Rezinsky):

#! /bin/sh
""":"
exec python $0 ${1+"$@"}
"""

The minor disadvantage is that this defines the script’s __doc__ string. However, you can fix that by adding

__doc__ = """...Whatever..."""

Is there a curses/termcap package for Python?

For Unix variants: The standard Python source distribution comes with a curses module in the Modules [https://github.com/python/cpython/tree/3.7/Modules] subdirectory, though it’s not compiled by default. (Note that this is not available in the Windows distribution – there is no curses module for Windows.)

The curses module supports basic curses features as well as many additional functions from ncurses and SYSV curses such as colour, alternative character set support, pads, and mouse support. This means the module isn’t compatible with operating systems that only have BSD curses, but there don’t seem to be any currently maintained OSes that fall into this category.

For Windows: use the consolelib module [http://effbot.org/zone/console-index.htm].

Is there an equivalent to C’s onexit() in Python?

The atexit module provides a register function that is similar to C’s onexit().

Why don’t my signal handlers work?

The most common problem is that the signal handler is declared with the wrong argument list. It is called as

handler(signum, frame)

so it should be declared with two arguments:

def handler(signum, frame):
    ...

Common tasks

How do I test a Python program or component?

Python comes with two testing frameworks. The doctest module finds examples in the docstrings for a module and runs them, comparing the output with the expected output given in the docstring.

The unittest module is a fancier testing framework modelled on Java and Smalltalk testing frameworks.

To make testing easier, you should use good modular design in your program. Your program should have almost all functionality encapsulated in either functions or class methods – and this sometimes has the surprising and delightful effect of making the program run faster (because local variable accesses are faster than global accesses). Furthermore the program should avoid depending on mutating global variables, since this makes testing much more difficult to do.

The “global main logic” of your program may be as simple as

if __name__ == "__main__":
    main_logic()

at the bottom of the main module of your program.

Once your program is organized as a tractable collection of functions and class behaviours you should write test functions that exercise the behaviours. A test suite that automates a sequence of tests can be associated with each module. This sounds like a lot of work, but since Python is so terse and flexible it’s surprisingly easy. You can make coding much more pleasant and fun by writing your test functions in parallel with the “production code”, since this makes it easy to find bugs and even design flaws earlier.

“Support modules” that are not intended to be the main module of a program may include a self-test of the module.

if __name__ == "__main__":
    self_test()

Even programs that interact with complex external interfaces may be tested when the external interfaces are unavailable by using “fake” interfaces implemented in Python.

How do I create documentation from doc strings?

The pydoc module can create HTML from the doc strings in your Python source code. An alternative for creating API documentation purely from docstrings is epydoc [http://epydoc.sourceforge.net/]. Sphinx [http://sphinx-doc.org] can also include docstring content.

How do I get a single keypress at a time?

For Unix variants there are several solutions. It’s straightforward to do this using curses, but curses is a fairly large module to learn.

Threads

How do I program using threads?

Be sure to use the threading module and not the _thread module. The threading module builds convenient abstractions on top of the low-level primitives provided by the _thread module.

Aahz has a set of slides from his threading tutorial that are helpful; see http://www.pythoncraft.com/OSCON2001/.

None of my threads seem to run: why?

As soon as the main thread exits, all threads are killed. Your main thread is running too quickly, giving the threads no time to do any work.

A simple fix is to add a sleep to the end of the program that’s long enough for all the threads to finish:

import threading, time

def thread_task(name, n):
    for i in range(n):
        print(name, i)

for i in range(10):
    T = threading.Thread(target=thread_task, args=(str(i), i))
    T.start()

time.sleep(10)  # <---------------------------!

But now (on many platforms) the threads don’t run in parallel, but appear to run sequentially, one at a time! The reason is that the OS thread scheduler doesn’t start a new thread until the previous thread is blocked.

A simple fix is to add a tiny sleep to the start of the run function:

def thread_task(name, n):
    time.sleep(0.001)  # <--------------------!
    for i in range(n):
        print(name, i)

for i in range(10):
    T = threading.Thread(target=thread_task, args=(str(i), i))
    T.start()

time.sleep(10)

Instead of trying to guess a good delay value for time.sleep(), it’s better to use some kind of semaphore mechanism. One idea is to use the queue module to create a queue object, let each thread append a token to the queue when it finishes, and let the main thread read as many tokens from the queue as there are threads.

How do I parcel out work among a bunch of worker threads?

The easiest way is to use the new concurrent.futures module, especially the ThreadPoolExecutor class.

Or, if you want fine control over the dispatching algorithm, you can write your own logic manually. Use the queue module to create a queue containing a list of jobs. The Queue class maintains a list of objects and has a .put(obj) method that adds items to the queue and a .get() method to return them. The class will take care of the locking necessary to ensure that each job is handed out exactly once.

Here’s a trivial example:

import threading, queue, time

# The worker thread gets jobs off the queue.  When the queue is empty, it
# assumes there will be no more work and exits.
# (Realistically workers will run until terminated.)
def worker():
    print('Running worker')
    time.sleep(0.1)
    while True:
        try:
            arg = q.get(block=False)
        except queue.Empty:
            print('Worker', threading.currentThread(), end=' ')
            print('queue empty')
            break
        else:
            print('Worker', threading.currentThread(), end=' ')
            print('running with argument', arg)
            time.sleep(0.5)

# Create queue
q = queue.Queue()

# Start a pool of 5 workers
for i in range(5):
    t = threading.Thread(target=worker, name='worker %i' % (i+1))
    t.start()

# Begin adding work to the queue
for i in range(50):
    q.put(i)

# Give threads time to run
print('Main thread sleeping')
time.sleep(5)

When run, this will produce the following output:

Running worker
Running worker
Running worker
Running worker
Running worker
Main thread sleeping
Worker <Thread(worker 1, started 130283832797456)> running with argument 0
Worker <Thread(worker 2, started 130283824404752)> running with argument 1
Worker <Thread(worker 3, started 130283816012048)> running with argument 2
Worker <Thread(worker 4, started 130283807619344)> running with argument 3
Worker <Thread(worker 5, started 130283799226640)> running with argument 4
Worker <Thread(worker 1, started 130283832797456)> running with argument 5
...

Consult the module’s documentation for more details; the Queue class provides a featureful interface.

What kinds of global value mutation are thread-safe?

A global interpreter lock (GIL) is used internally to ensure that only one thread runs in the Python VM at a time. In general, Python offers to switch among threads only between bytecode instructions; how frequently it switches can be set via sys.setswitchinterval(). Each bytecode instruction and therefore all the C implementation code reached from each instruction is therefore atomic from the point of view of a Python program.

In theory, this means an exact accounting requires an exact understanding of the PVM bytecode implementation. In practice, it means that operations on shared variables of built-in data types (ints, lists, dicts, etc) that “look atomic” really are.

For example, the following operations are all atomic (L, L1, L2 are lists, D, D1, D2 are dicts, x, y are objects, i, j are ints):

L.append(x)
L1.extend(L2)
x = L[i]
x = L.pop()
L1[i:j] = L2
L.sort()
x = y
x.field = y
D[x] = y
D1.update(D2)
D.keys()

These aren’t:

i = i+1
L.append(L[-1])
L[i] = L[j]
D[x] = D[x] + 1

Operations that replace other objects may invoke those other objects’ __del__() method when their reference count reaches zero, and that can affect things. This is especially true for the mass updates to dictionaries and lists. When in doubt, use a mutex!

Can’t we get rid of the Global Interpreter Lock?

The global interpreter lock (GIL) is often seen as a hindrance to Python’s deployment on high-end multiprocessor server machines, because a multi-threaded Python program effectively only uses one CPU, due to the insistence that (almost) all Python code can only run while the GIL is held.

Back in the days of Python 1.5, Greg Stein actually implemented a comprehensive patch set (the “free threading” patches) that removed the GIL and replaced it with fine-grained locking. Adam Olsen recently did a similar experiment in his python-safethread [https://code.google.com/archive/p/python-safethread] project. Unfortunately, both experiments exhibited a sharp drop in single-thread performance (at least 30% slower), due to the amount of fine-grained locking necessary to compensate for the removal of the GIL.

This doesn’t mean that you can’t make good use of Python on multi-CPU machines! You just have to be creative with dividing the work up between multiple processes rather than multiple threads. The ProcessPoolExecutor class in the new concurrent.futures module provides an easy way of doing so; the multiprocessing module provides a lower-level API in case you want more control over dispatching of tasks.

Judicious use of C extensions will also help; if you use a C extension to perform a time-consuming task, the extension can release the GIL while the thread of execution is in the C code and allow other threads to get some work done. Some standard library modules such as zlib and hashlib already do this.

It has been suggested that the GIL should be a per-interpreter-state lock rather than truly global; interpreters then wouldn’t be able to share objects. Unfortunately, this isn’t likely to happen either. It would be a tremendous amount of work, because many object implementations currently have global state. For example, small integers and short strings are cached; these caches would have to be moved to the interpreter state. Other object types have their own free list; these free lists would have to be moved to the interpreter state. And so on.

And I doubt that it can even be done in finite time, because the same problem exists for 3rd party extensions. It is likely that 3rd party extensions are being written at a faster rate than you can convert them to store all their global state in the interpreter state.

And finally, once you have multiple interpreters not sharing any state, what have you gained over running each interpreter in a separate process?

Input and Output

How do I delete a file? (And other file questions…)

Use os.remove(filename) or os.unlink(filename); for documentation, see the os module. The two functions are identical; unlink() is simply the name of the Unix system call for this function.

To remove a directory, use os.rmdir(); use os.mkdir() to create one. os.makedirs(path) will create any intermediate directories in path that don’t exist. os.removedirs(path) will remove intermediate directories as long as they’re empty; if you want to delete an entire directory tree and its contents, use shutil.rmtree().

To rename a file, use os.rename(old_path, new_path).

To truncate a file, open it using f = open(filename, "rb+"), and use f.truncate(offset); offset defaults to the current seek position. There’s also os.ftruncate(fd, offset) for files opened with os.open(), where fd is the file descriptor (a small integer).

The shutil module also contains a number of functions to work on files including copyfile(), copytree(), and rmtree().

How do I copy a file?

The shutil module contains a copyfile() function. Note that on MacOS 9 it doesn’t copy the resource fork and Finder info.

How do I read (or write) binary data?

To read or write complex binary data formats, it’s best to use the struct module. It allows you to take a string containing binary data (usually numbers) and convert it to Python objects; and vice versa.

For example, the following code reads two 2-byte integers and one 4-byte integer in big-endian format from a file:

import struct

with open(filename, "rb") as f:
    s = f.read(8)
    x, y, z = struct.unpack(">hhl", s)

The ‘>’ in the format string forces big-endian data; the letter ‘h’ reads one “short integer” (2 bytes), and ‘l’ reads one “long integer” (4 bytes) from the string.

For data that is more regular (e.g. a homogeneous list of ints or floats), you can also use the array module.

참고

To read and write binary data, it is mandatory to open the file in binary mode (here, passing "rb" to open()). If you use "r" instead (the default), the file will be open in text mode and f.read() will return str objects rather than bytes objects.

I can’t seem to use os.read() on a pipe created with os.popen(); why?

os.read() is a low-level function which takes a file descriptor, a small integer representing the opened file. os.popen() creates a high-level file object, the same type returned by the built-in open() function. Thus, to read n bytes from a pipe p created with os.popen(), you need to use p.read(n).

How do I access the serial (RS232) port?

For Win32, POSIX (Linux, BSD, etc.), Jython:

http://pyserial.sourceforge.net

For Unix, see a Usenet post by Mitch Chapman:

https://groups.google.com/groups?selm=34A04430.CF9@ohioee.com

Why doesn’t closing sys.stdout (stdin, stderr) really close it?

Python file objects are a high-level layer of abstraction on low-level C file descriptors.

For most file objects you create in Python via the built-in open() function, f.close() marks the Python file object as being closed from Python’s point of view, and also arranges to close the underlying C file descriptor. This also happens automatically in f’s destructor, when f becomes garbage.

But stdin, stdout and stderr are treated specially by Python, because of the special status also given to them by C. Running sys.stdout.close() marks the Python-level file object as being closed, but does not close the associated C file descriptor.

To close the underlying C file descriptor for one of these three, you should first be sure that’s what you really want to do (e.g., you may confuse extension modules trying to do I/O). If it is, use os.close():

os.close(stdin.fileno())
os.close(stdout.fileno())
os.close(stderr.fileno())

Or you can use the numeric constants 0, 1 and 2, respectively.

Network/Internet Programming

What WWW tools are there for Python?

See the chapters titled 인터넷 프로토콜과 지원 and 인터넷 데이터 처리 in the Library Reference Manual. Python has many modules that will help you build server-side and client-side web systems.

A summary of available frameworks is maintained by Paul Boddie at https://wiki.python.org/moin/WebProgramming.

Cameron Laird maintains a useful set of pages about Python web technologies at http://phaseit.net/claird/comp.lang.python/web_python.

How can I mimic CGI form submission (METHOD=POST)?

I would like to retrieve web pages that are the result of POSTing a form. Is there existing code that would let me do this easily?

Yes. Here’s a simple example that uses urllib.request:

#!/usr/local/bin/python

import urllib.request

# build the query string
qs = "First=Josephine&MI=Q&Last=Public"

# connect and send the server a path
req = urllib.request.urlopen('http://www.some-server.out-there'
                             '/cgi-bin/some-cgi-script', data=qs)
with req:
    msg, hdrs = req.read(), req.info()

Note that in general for percent-encoded POST operations, query strings must be quoted using urllib.parse.urlencode(). For example, to send name=Guy Steele, Jr.:

>>> import urllib.parse
>>> urllib.parse.urlencode({'name': 'Guy Steele, Jr.'})
'name=Guy+Steele%2C+Jr.'

더 보기

HOWTO Fetch Internet Resources Using The urllib Package for extensive examples.

What module should I use to help with generating HTML?

You can find a collection of useful links on the Web Programming wiki page [https://wiki.python.org/moin/WebProgramming].

How do I send mail from a Python script?

Use the standard library module smtplib.

Here’s a very simple interactive mail sender that uses it. This method will work on any host that supports an SMTP listener.

import sys, smtplib

fromaddr = input("From: ")
toaddrs  = input("To: ").split(',')
print("Enter message, end with ^D:")
msg = ''
while True:
    line = sys.stdin.readline()
    if not line:
        break
    msg += line

# The actual mail send
server = smtplib.SMTP('localhost')
server.sendmail(fromaddr, toaddrs, msg)
server.quit()

A Unix-only alternative uses sendmail. The location of the sendmail program varies between systems; sometimes it is /usr/lib/sendmail, sometimes /usr/sbin/sendmail. The sendmail manual page will help you out. Here’s some sample code:

import os

SENDMAIL = "/usr/sbin/sendmail"  # sendmail location
p = os.popen("%s -t -i" % SENDMAIL, "w")
p.write("To: receiver@example.com\n")
p.write("Subject: test\n")
p.write("\n")  # blank line separating headers from body
p.write("Some text\n")
p.write("some more text\n")
sts = p.close()
if sts != 0:
    print("Sendmail exit status", sts)

How do I avoid blocking in the connect() method of a socket?

The select module is commonly used to help with asynchronous I/O on sockets.

To prevent the TCP connect from blocking, you can set the socket to non-blocking mode. Then when you do the connect(), you will either connect immediately (unlikely) or get an exception that contains the error number as .errno. errno.EINPROGRESS indicates that the connection is in progress, but hasn’t finished yet. Different OSes will return different values, so you’re going to have to check what’s returned on your system.

You can use the connect_ex() method to avoid creating an exception. It will just return the errno value. To poll, you can call connect_ex() again later – 0 or errno.EISCONN indicate that you’re connected – or you can pass this socket to select to check if it’s writable.

참고

The asyncore module presents a framework-like approach to the problem of writing non-blocking networking code. The third-party Twisted [https://twistedmatrix.com/trac/] library is a popular and feature-rich alternative.

Databases

Are there any interfaces to database packages in Python?

Yes.

Interfaces to disk-based hashes such as DBM and GDBM are also included with standard Python. There is also the sqlite3 module, which provides a lightweight disk-based relational database.

Support for most relational databases is available. See the DatabaseProgramming wiki page [https://wiki.python.org/moin/DatabaseProgramming] for details.

How do you implement persistent objects in Python?

The pickle library module solves this in a very general way (though you still can’t store things like open files, sockets or windows), and the shelve library module uses pickle and (g)dbm to create persistent mappings containing arbitrary Python objects.

Mathematics and Numerics

How do I generate random numbers in Python?

The standard module random implements a random number generator. Usage is simple:

import random
random.random()

This returns a random floating point number in the range [0, 1).

There are also many other specialized generators in this module, such as:

randrange(a, b) chooses an integer in the range [a, b).

uniform(a, b) chooses a floating point number in the range [a, b).

normalvariate(mean, sdev) samples the normal (Gaussian) distribution.

Some higher-level functions operate on sequences directly, such as:

choice(S) chooses random element from a given sequence

shuffle(L) shuffles a list in-place, i.e. permutes it randomly

There’s also a Random class you can instantiate to create independent multiple random number generators.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 자주 나오는 질문들 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 자주 나오는 질문들 »

|

확장/내장 FAQ

목차

확장/내장 FAQ

C로 나만의 함수를 만들 수 있습니까?

C++로 나만의 함수를 만들 수 있습니까?

C를 쓰는 것은 어렵습니다; 대안이 있습니까?

C에서 임의의 파이썬 문장을 어떻게 실행할 수 있습니까?

C에서 임의의 파이썬 표현식을 어떻게 평가할 수 있습니까?

파이썬 객체에서 C값을 어떻게 추출합니까?

Py_BuildValue()를 사용하여 임의 길이의 튜플을 만드는 방법은 무엇입니까?

C에서 객체의 메서드를 어떻게 호출합니까?

PyErr_Print()의 출력(또는 stdout/stderr로 인쇄되는 모든 것)을 어떻게 잡습니까?

C에서 파이썬으로 작성된 모듈에 어떻게 액세스합니까?

파이썬에서 C++ 객체에 어떻게 인터페이스 합니까?

Setup 파일을 사용하여 모듈을 추가했는데 make가 실패합니다; 왜 그렇습니까?

확장을 어떻게 디버깅합니까?

리눅스 시스템에서 파이썬 모듈을 컴파일하고 싶지만, 일부 파일이 없습니다. 왜 그렇습니까?

“잘못된 입력”과 “불완전한 입력”을 어떻게 구별할 수 있습니까?

정의되지 않은 g++ 기호 __builtin_new나 __pure_virtual을 어떻게 찾을 수 있습니까?

일부 메서드는 C로 구현되고 그 밖의 것은 파이썬으로 구현된 (예를 들어 상속을 통해) 객체 클래스를 만들 수 있습니까?

C로 나만의 함수를 만들 수 있습니까?

그렇습니다. 함수, 변수, 예외 및 심지어 새로운 형을 포함하는 내장 모듈을 C로 만들 수 있습니다. 파이썬 인터프리터 확장 및 내장 문서에 설명되어 있습니다.

대부분의 중급이나 고급 파이썬 서적에서도 이 주제를 다룰 것입니다.

C++로 나만의 함수를 만들 수 있습니까?

그렇습니다, C++에 있는 C 호환성 기능을 사용합니다. 파이썬 인클루드(include) 파일 주위에 extern "C" { ... }를 배치하고 파이썬 인터프리터가 호출할 각 함수 앞에 extern "C"를 배치하십시오. 생성자를 가진 전역이나 정적(static) C++ 객체는 대개 좋은 생각이 아닙니다.

C를 쓰는 것은 어렵습니다; 대안이 있습니까?

수행하려는 작업에 따라, 여러분 만의 C 확장을 작성하는 여러 가지 대안이 있습니다.

Cython [http://cython.org]과 관련 Pyrex [https://www.cosc.canterbury.ac.nz/greg.ewing/python/Pyrex/]는 약간 수정된 파이썬 형식을 받아들이고 해당 C 코드를 생성하는 컴파일러입니다. Cython과 Pyrex를 사용하면 파이썬의 C API를 배우지 않고도 확장을 작성할 수 있습니다.

현재 파이썬 확장이 없는 일부 C나 C++ 라이브러리에 대한 인터페이스가 필요하면, 라이브러리의 데이터형과 함수를 SWIG [http://www.swig.org]과 같은 도구로 래핑할 수 있습니다. SIP [https://riverbankcomputing.com/software/sip/intro], CXX [http://cxx.sourceforge.net/], Boost [http://www.boost.org/libs/python/doc/index.html] 또는 Weave [https://github.com/scipy/weave]도 C++ 라이브러리 래핑의 대안입니다.

C에서 임의의 파이썬 문장을 어떻게 실행할 수 있습니까?

이를 수행하는 최상위 수준 함수는 PyRun_SimpleString()이며, 이는 모듈 __main__의 컨텍스트에서 실행될 단일 문자열 인자를 취하고 성공하면 0을 반환하고 (SyntaxError를 포함하는) 예외가 발생하면 -1을 반환합니다. 더 많은 제어를 원하면, PyRun_String()을 사용하십시오; Python/pythonrun.c에 있는 PyRun_SimpleString() 소스를 참조하십시오.

C에서 임의의 파이썬 표현식을 어떻게 평가할 수 있습니까?

이전 질문에서 나온 PyRun_String() 함수를 start 기호 Py_eval_input을 사용하여 호출하십시오; 표현식을 구문 분석하고, 평가하고 값을 반환합니다.

파이썬 객체에서 C값을 어떻게 추출합니까?

이는 객체의 형에 따라 다릅니다. 튜플이면, PyTuple_Size()는 길이를 반환하고 PyTuple_GetItem()은 지정된 인덱스의 항목을 반환합니다. 리스트는 비슷한 함수를 가지고 있습니다, PyListSize()와 PyList_GetItem().

바이트열에서는, PyBytes_Size()는 길이를 반환하고 PyBytes_AsStringAndSize()는 값과 길이에 대한 포인터를 제공합니다. 파이썬 바이트열 객체는 널(null) 바이트를 포함할 수 있어서 C의 strlen()을 사용할 수 없음에 유의하십시오.

To test the type of an object, first make sure it isn’t NULL, and then use PyBytes_Check(), PyTuple_Check(), PyList_Check(), etc.

소위 ‘추상’ 인터페이스가 제공하는 파이썬 객체에 대한 고수준 API도 있습니다 – 자세한 내용은 Include/abstract.h를 읽으십시오. PySequence_Length(), PySequence_GetItem() 등과 같은 호출로 모든 종류의 파이썬 시퀀스와 인터페이스 할 수 있을 뿐만 아니라 숫자(PyNumber_Index() 등)와 PyMapping API의 매핑과 같은 다른 많은 유용한 프로토콜을 지원합니다.

Py_BuildValue()를 사용하여 임의 길이의 튜플을 만드는 방법은 무엇입니까?

그럴 수 없습니다. 대신 PyTuple_Pack()을 사용하십시오.

C에서 객체의 메서드를 어떻게 호출합니까?

PyObject_CallMethod() 함수는 객체의 임의의 메서드를 호출하는 데 사용할 수 있습니다. 매개 변수는 객체, 호출할 메서드의 이름, Py_BuildValue()에 사용되는 것과 같은 포맷 문자열 및 인자 값입니다:

PyObject *
PyObject_CallMethod(PyObject *object, const char *method_name,
                    const char *arg_format, ...);

메서드가 있는 모든 객체에서 작동합니다 – 내장이나 사용자 정의 모두 작동합니다. 반환 값을 Py_DECREF()할 책임은 여러분에게 있습니다.

예를 들어, 인자 10, 0으로 파일 객체의 “seek” 메서드를 호출하려면 (파일 객체 포인터가 “f”라고 가정합니다):

res = PyObject_CallMethod(f, "seek", "(ii)", 10, 0);
if (res == NULL) {
        ... an exception occurred ...
}
else {
        Py_DECREF(res);
}

PyObject_CallObject()는 항상 인자 목록에 대한 튜플을 원하므로, 인자 없이 함수를 호출하려면, format으로 “()”를 전달하고, 하나의 인자로 함수를 호출하려면, 인자를 괄호로 묶습니다, 예를 들어 “(i)”.

PyErr_Print()의 출력(또는 stdout/stderr로 인쇄되는 모든 것)을 어떻게 잡습니까?

파이썬 코드에서, write() 메서드를 지원하는 객체를 정의하십시오. 이 객체를 sys.stdout과 sys.stderr에 대입하십시오. print_error를 호출하거나 표준 트레이스백 메커니즘이 작동하도록 두십시오. 그러면 출력은 여러분의 write() 메서드가 보내는 곳으로 갑니다.

이렇게 하는 가장 쉬운 방법은 io.StringIO 클래스를 사용하는 것입니다:

>>> import io, sys
>>> sys.stdout = io.StringIO()
>>> print('foo')
>>> print('hello world!')
>>> sys.stderr.write(sys.stdout.getvalue())
foo
hello world!

같은 작업을 수행하는 사용자 정의 객체는 다음과 같습니다:

>>> import io, sys
>>> class StdoutCatcher(io.TextIOBase):
...     def __init__(self):
...         self.data = []
...     def write(self, stuff):
...         self.data.append(stuff)
...
>>> import sys
>>> sys.stdout = StdoutCatcher()
>>> print('foo')
>>> print('hello world!')
>>> sys.stderr.write(''.join(sys.stdout.data))
foo
hello world!

C에서 파이썬으로 작성된 모듈에 어떻게 액세스합니까?

다음과 같이 모듈 객체에 대한 포인터를 얻을 수 있습니다:

module = PyImport_ImportModule("<modulename>");

모듈을 아직 임포트 하지 않았으면 (즉, sys.modules에 아직 없으면), 이것은 모듈을 초기화합니다; 그렇지 않으면 단순히 sys.modules["<modulename>"]의 값을 반환합니다. 이것은 모듈을 어떤 이름 공간에도 넣지 않음에 유의하십시오 – 단지 초기화되도록 하고 sys.modules에 저장되도록 합니다.

그런 다음, 다음과 같이 모듈의 어트리뷰트(즉 모듈에 정의된 모든 이름)에 액세스할 수 있습니다:

attr = PyObject_GetAttrString(module, "<attrname>");

모듈에 있는 변수에 대입하기 위해 PyObject_SetAttrString()을 호출하는 것도 작동합니다.

파이썬에서 C++ 객체에 어떻게 인터페이스 합니까?

요구 사항에 따라 여러 가지 접근 방식이 있습니다. 이 작업을 수동으로 수행하려면, “확장 및 내장” 문서를 읽는 것으로 시작하십시오. 파이썬 런타임 시스템의 경우 C와 C++ 사이에는 큰 차이가 없다는 것을 상기하십시오 – 따라서 C 구조체 (포인터) 형을 중심으로 새로운 파이썬 형을 작성하는 전략이 C++ 객체에도 적용됩니다.

C++ 라이브러리의 경우, C를 쓰는 것은 어렵습니다; 대안이 있습니까?를 참조하십시오.

Setup 파일을 사용하여 모듈을 추가했는데 make가 실패합니다; 왜 그렇습니까?

Setup은 개행으로 끝나야 하며, 개행이 없으면 빌드 프로세스가 실패합니다. (이 문제를 해결하려면 지저분한 셸 스크립트 해킹이 필요하며, 이 버그는 너무 사소해서 그런 노력을 들일만 한 가치가 없는 것 같습니다.)

확장을 어떻게 디버깅합니까?

동적으로 로드된 확장에 GDB를 사용할 때, 확장이 로드될 때까지 확장에 중단점을 설정할 수 없습니다.

.gdbinit 파일에서 (또는 대화식으로) 다음 명령을 추가하십시오:

br _PyImport_LoadDynamicModule

그런 다음, GDB를 실행할 때:

$ gdb /local/bin/python
gdb) run myscript.py
gdb) continue # repeat until your extension is loaded
gdb) finish   # so that your extension is loaded
gdb) br myfunction.c:50
gdb) continue

리눅스 시스템에서 파이썬 모듈을 컴파일하고 싶지만, 일부 파일이 없습니다. 왜 그렇습니까?

대부분의 포장된 버전의 파이썬은 파이썬 확장을 컴파일하는 데 필요한 다양한 파일이 포함된 /usr/lib/python2.x/config/ 디렉터리가 포함되어 있지 않습니다.

레드햇의 경우, 필요한 파일을 얻으려면 python-devel RPM을 설치하십시오.

데비안의 경우, apt-get install python-dev를 실행하십시오.

“잘못된 입력”과 “불완전한 입력”을 어떻게 구별할 수 있습니까?

때로 파이썬 대화식 인터프리터의 동작을 흉내 내고 싶을 때가 있습니다. 이것은 입력이 불완전할 때 (예를 들어, “if” 문의 시작을 입력했거나 괄호나 삼중 문자열 따옴표를 닫지 않았을 때) 계속 프롬프트를 표시하지만, 입력이 유효하지 않으면 즉시 문법 에러 메시지를 표시합니다.

파이썬에서는 codeop 모듈을 사용할 수 있습니다. 이 모듈은 구문 분석기의 동작을 충분히 근사합니다. 예를 들어, IDLE은 이것을 사용합니다.

C에서 이렇게 하는 가장 쉬운 방법은 PyRun_InteractiveLoop()를 호출하고 (아마 별도의 스레드에서), 파이썬 인터프리터가 입력을 처리하도록 하는 것입니다. PyOS_ReadlineFunctionPointer() 가 여러분의 사용자 정의 입력 함수를 가리 키도록 설정할 수도 있습니다. 자세한 힌트는 Modules/readline.c와 Parser/myreadline.c를 참조하십시오.

그러나 때로는 나머지 응용 프로그램과 같은 스레드에서 내장된 파이썬 인터프리터를 실행해야 하고, 사용자 입력을 기다리는 동안 PyRun_InteractiveLoop()를 중지할 수 없습니다. 한 가지 해결책은 PyParser_ParseString()을 호출하고 e.error가 E_EOF와 같은지를 검사하는 것인데, 이는 입력이 불완전하다는 것을 의미합니다. 다음은 Alex Farber의 코드에서 영감을 얻은 테스트 되지 않은 샘플 코드 조각입니다:

#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include <node.h>
#include <errcode.h>
#include <grammar.h>
#include <parsetok.h>
#include <compile.h>

int testcomplete(char *code)
  /* code should end in \n */
  /* return -1 for error, 0 for incomplete, 1 for complete */
{
  node *n;
  perrdetail e;

  n = PyParser_ParseString(code, &_PyParser_Grammar,
                           Py_file_input, &e);
  if (n == NULL) {
    if (e.error == E_EOF)
      return 0;
    return -1;
  }

  PyNode_Free(n);
  return 1;
}

다른 해결책은 수신된 문자열을 Py_CompileString()으로 컴파일하려고 하는 것입니다. 에러 없이 컴파일되면, PyEval_EvalCode()를 호출하여 반환된 코드 객체를 실행해 보십시오. 그렇지 않으면 나중을 위해 입력을 저장하십시오. 컴파일이 실패하면, 예외 튜플에서 메시지 문자열을 추출하고 이를 “unexpected EOF while parsing” 문자열과 비교하여 에러인지 단지 더 많은 입력이 필요한지를 확인하십시오. 다음은 GNU readline 라이브러리를 사용하는 완전한 예제입니다 (readline()을 호출하는 동안 SIGINT를 무시하고자 할 수 있습니다):

#include <stdio.h>
#include <readline.h>

#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include <object.h>
#include <compile.h>
#include <eval.h>

int main (int argc, char* argv[])
{
  int i, j, done = 0;                          /* lengths of line, code */
  char ps1[] = ">>> ";
  char ps2[] = "... ";
  char *prompt = ps1;
  char *msg, *line, *code = NULL;
  PyObject *src, *glb, *loc;
  PyObject *exc, *val, *trb, *obj, *dum;

  Py_Initialize ();
  loc = PyDict_New ();
  glb = PyDict_New ();
  PyDict_SetItemString (glb, "__builtins__", PyEval_GetBuiltins ());

  while (!done)
  {
    line = readline (prompt);

    if (NULL == line)                          /* Ctrl-D pressed */
    {
      done = 1;
    }
    else
    {
      i = strlen (line);

      if (i > 0)
        add_history (line);                    /* save non-empty lines */

      if (NULL == code)                        /* nothing in code yet */
        j = 0;
      else
        j = strlen (code);

      code = realloc (code, i + j + 2);
      if (NULL == code)                        /* out of memory */
        exit (1);

      if (0 == j)                              /* code was empty, so */
        code[0] = '\0';                        /* keep strncat happy */

      strncat (code, line, i);                 /* append line to code */
      code[i + j] = '\n';                      /* append '\n' to code */
      code[i + j + 1] = '\0';

      src = Py_CompileString (code, "<stdin>", Py_single_input);

      if (NULL != src)                         /* compiled just fine - */
      {
        if (ps1  == prompt ||                  /* ">>> " or */
            '\n' == code[i + j - 1])           /* "... " and double '\n' */
        {                                               /* so execute it */
          dum = PyEval_EvalCode (src, glb, loc);
          Py_XDECREF (dum);
          Py_XDECREF (src);
          free (code);
          code = NULL;
          if (PyErr_Occurred ())
            PyErr_Print ();
          prompt = ps1;
        }
      }                                        /* syntax error or E_EOF? */
      else if (PyErr_ExceptionMatches (PyExc_SyntaxError))
      {
        PyErr_Fetch (&exc, &val, &trb);        /* clears exception! */

        if (PyArg_ParseTuple (val, "sO", &msg, &obj) &&
            !strcmp (msg, "unexpected EOF while parsing")) /* E_EOF */
        {
          Py_XDECREF (exc);
          Py_XDECREF (val);
          Py_XDECREF (trb);
          prompt = ps2;
        }
        else                                   /* some other syntax error */
        {
          PyErr_Restore (exc, val, trb);
          PyErr_Print ();
          free (code);
          code = NULL;
          prompt = ps1;
        }
      }
      else                                     /* some non-syntax error */
      {
        PyErr_Print ();
        free (code);
        code = NULL;
        prompt = ps1;
      }

      free (line);
    }
  }

  Py_XDECREF(glb);
  Py_XDECREF(loc);
  Py_Finalize();
  exit(0);
}

정의되지 않은 g++ 기호 __builtin_new나 __pure_virtual을 어떻게 찾을 수 있습니까?

g++ 확장 모듈을 동적으로 로드하려면, 파이썬을 다시 컴파일하고, g++를 사용하여 다시 링크하고 (파이썬 Modules Makefile에서 LINKCC를 변경하십시오), g++를 사용하여 여러분의 확장 모듈을 링크해야 합니다 (예를 들어, g++ -shared -o mymodule.so mymodule.o).

일부 메서드는 C로 구현되고 그 밖의 것은 파이썬으로 구현된 (예를 들어 상속을 통해) 객체 클래스를 만들 수 있습니까?

그렇습니다, int, list, dict 등과 같은 내장 클래스를 상속할 수 있습니다.

Boost 파이썬 라이브러리(BPL, http://www.boost.org/libs/python/doc/index.html)는 C++에서 이를 수행하는 방법을 제공합니다 (즉, BPL을 사용하여 C++로 작성된 확장 클래스를 상속할 수 있습니다).

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 자주 나오는 질문들 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 자주 나오는 질문들 »

|

Python on Windows FAQ

목차

Python on Windows FAQ

How do I run a Python program under Windows?

How do I make Python scripts executable?

Why does Python sometimes take so long to start?

How do I make an executable from a Python script?

Is a *.pyd file the same as a DLL?

How can I embed Python into a Windows application?

How do I keep editors from inserting tabs into my Python source?

How do I check for a keypress without blocking?

How do I run a Python program under Windows?

This is not necessarily a straightforward question. If you are already familiar with running programs from the Windows command line then everything will seem obvious; otherwise, you might need a little more guidance.

Unless you use some sort of integrated development environment, you will end up typing Windows commands into what is variously referred to as a “DOS window” or “Command prompt window”. Usually you can create such a window from your search bar by searching for cmd. You should be able to recognize when you have started such a window because you will see a Windows “command prompt”, which usually looks like this:

C:\>

The letter may be different, and there might be other things after it, so you might just as easily see something like:

D:\YourName\Projects\Python>

depending on how your computer has been set up and what else you have recently done with it. Once you have started such a window, you are well on the way to running Python programs.

You need to realize that your Python scripts have to be processed by another program called the Python interpreter. The interpreter reads your script, compiles it into bytecodes, and then executes the bytecodes to run your program. So, how do you arrange for the interpreter to handle your Python?

First, you need to make sure that your command window recognises the word “py” as an instruction to start the interpreter. If you have opened a command window, you should try entering the command py and hitting return:

C:\Users\YourName> py

You should then see something like:

Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:04:45) [MSC v.1900 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>

You have started the interpreter in “interactive mode”. That means you can enter Python statements or expressions interactively and have them executed or evaluated while you wait. This is one of Python’s strongest features. Check it by entering a few expressions of your choice and seeing the results:

>>> print("Hello")
Hello
>>> "Hello" * 3
'HelloHelloHello'

Many people use the interactive mode as a convenient yet highly programmable calculator. When you want to end your interactive Python session, call the exit() function or hold the Ctrl key down while you enter a Z, then hit the “Enter” key to get back to your Windows command prompt.

You may also find that you have a Start-menu entry such as Start ‣ Programs ‣ Python 3.x ‣ Python (command line) that results in you seeing the >>> prompt in a new window. If so, the window will disappear after you call the exit() function or enter the Ctrl-Z character; Windows is running a single “python” command in the window, and closes it when you terminate the interpreter.

Now that we know the py command is recognized, you can give your Python script to it. You’ll have to give either an absolute or a relative path to the Python script. Let’s say your Python script is located in your desktop and is named hello.py, and your command prompt is nicely opened in your home directory so you’re seeing something similar to:

C:\Users\YourName>

So now you’ll ask the py command to give your script to Python by typing py followed by your script path:

C:\Users\YourName> py Desktop\hello.py
hello

How do I make Python scripts executable?

On Windows, the standard Python installer already associates the .py extension with a file type (Python.File) and gives that file type an open command that runs the interpreter (D:\Program Files\Python\python.exe "%1" %*). This is enough to make scripts executable from the command prompt as ‘foo.py’. If you’d rather be able to execute the script by simple typing ‘foo’ with no extension you need to add .py to the PATHEXT environment variable.

Why does Python sometimes take so long to start?

Usually Python starts very quickly on Windows, but occasionally there are bug reports that Python suddenly begins to take a long time to start up. This is made even more puzzling because Python will work fine on other Windows systems which appear to be configured identically.

The problem may be caused by a misconfiguration of virus checking software on the problem machine. Some virus scanners have been known to introduce startup overhead of two orders of magnitude when the scanner is configured to monitor all reads from the filesystem. Try checking the configuration of virus scanning software on your systems to ensure that they are indeed configured identically. McAfee, when configured to scan all file system read activity, is a particular offender.

How do I make an executable from a Python script?

See cx_Freeze [https://anthony-tuininga.github.io/cx_Freeze/] for a distutils extension that allows you to create console and GUI executables from Python code. py2exe [http://www.py2exe.org/], the most popular extension for building Python 2.x-based executables, does not yet support Python 3 but a version that does is in development.

Is a *.pyd file the same as a DLL?

Yes, .pyd files are dll’s, but there are a few differences. If you have a DLL named foo.pyd, then it must have a function PyInit_foo(). You can then write Python “import foo”, and Python will search for foo.pyd (as well as foo.py, foo.pyc) and if it finds it, will attempt to call PyInit_foo() to initialize it. You do not link your .exe with foo.lib, as that would cause Windows to require the DLL to be present.

Note that the search path for foo.pyd is PYTHONPATH, not the same as the path that Windows uses to search for foo.dll. Also, foo.pyd need not be present to run your program, whereas if you linked your program with a dll, the dll is required. Of course, foo.pyd is required if you want to say import foo. In a DLL, linkage is declared in the source code with __declspec(dllexport). In a .pyd, linkage is defined in a list of available functions.

How can I embed Python into a Windows application?

Embedding the Python interpreter in a Windows app can be summarized as follows:

Do _not_ build Python into your .exe file directly. On Windows, Python must be a DLL to handle importing modules that are themselves DLL’s. (This is the first key undocumented fact.) Instead, link to pythonNN.dll; it is typically installed in C:\Windows\System. NN is the Python version, a number such as “33” for Python 3.3.

You can link to Python in two different ways. Load-time linking means linking against pythonNN.lib, while run-time linking means linking against pythonNN.dll. (General note: pythonNN.lib is the so-called “import lib” corresponding to pythonNN.dll. It merely defines symbols for the linker.)

Run-time linking greatly simplifies link options; everything happens at run time. Your code must load pythonNN.dll using the Windows LoadLibraryEx() routine. The code must also use access routines and data in pythonNN.dll (that is, Python’s C API’s) using pointers obtained by the Windows GetProcAddress() routine. Macros can make using these pointers transparent to any C code that calls routines in Python’s C API.

Borland note: convert pythonNN.lib to OMF format using Coff2Omf.exe first.

If you use SWIG, it is easy to create a Python “extension module” that will make the app’s data and methods available to Python. SWIG will handle just about all the grungy details for you. The result is C code that you link into your .exe file (!) You do _not_ have to create a DLL file, and this also simplifies linking.

SWIG will create an init function (a C function) whose name depends on the name of the extension module. For example, if the name of the module is leo, the init function will be called initleo(). If you use SWIG shadow classes, as you should, the init function will be called initleoc(). This initializes a mostly hidden helper class used by the shadow class.

The reason you can link the C code in step 2 into your .exe file is that calling the initialization function is equivalent to importing the module into Python! (This is the second key undocumented fact.)

In short, you can use the following code to initialize the Python interpreter with your extension module.

#include "python.h"
...
Py_Initialize();  // Initialize Python.
initmyAppc();  // Initialize (import) the helper class.
PyRun_SimpleString("import myApp");  // Import the shadow class.

There are two problems with Python’s C API which will become apparent if you use a compiler other than MSVC, the compiler used to build pythonNN.dll.

Problem 1: The so-called “Very High Level” functions that take FILE * arguments will not work in a multi-compiler environment because each compiler’s notion of a struct FILE will be different. From an implementation standpoint these are very _low_ level functions.

Problem 2: SWIG generates the following code when generating wrappers to void functions:

Py_INCREF(Py_None);
_resultobj = Py_None;
return _resultobj;

Alas, Py_None is a macro that expands to a reference to a complex data structure called _Py_NoneStruct inside pythonNN.dll. Again, this code will fail in a mult-compiler environment. Replace such code by:

return Py_BuildValue("");

It may be possible to use SWIG’s %typemap command to make the change automatically, though I have not been able to get this to work (I’m a complete SWIG newbie).

Using a Python shell script to put up a Python interpreter window from inside your Windows app is not a good idea; the resulting window will be independent of your app’s windowing system. Rather, you (or the wxPythonWindow class) should create a “native” interpreter window. It is easy to connect that window to the Python interpreter. You can redirect Python’s i/o to _any_ object that supports read and write, so all you need is a Python object (defined in your extension module) that contains read() and write() methods.

How do I keep editors from inserting tabs into my Python source?

The FAQ does not recommend using tabs, and the Python style guide, PEP 8 [https://www.python.org/dev/peps/pep-0008], recommends 4 spaces for distributed Python code; this is also the Emacs python-mode default.

Under any editor, mixing tabs and spaces is a bad idea. MSVC is no different in this respect, and is easily configured to use spaces: Take Tools ‣ Options ‣ Tabs, and for file type “Default” set “Tab size” and “Indent size” to 4, and select the “Insert spaces” radio button.

Python raises IndentationError or TabError if mixed tabs and spaces are causing problems in leading whitespace. You may also run the tabnanny module to check a directory tree in batch mode.

How do I check for a keypress without blocking?

Use the msvcrt module. This is a standard Windows-specific extension module. It defines a function kbhit() which checks whether a keyboard hit is present, and getch() which gets one character without echoing it.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 자주 나오는 질문들 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 자주 나오는 질문들 »

|

그래픽 사용자 인터페이스 FAQ

목차

그래픽 사용자 인터페이스 FAQ

일반적인 GUI 질문

파이썬에 어떤 플랫폼 독립적인 GUI 툴킷이 있습니까?

Tkinter

wxWidgets

Qt

Gtk+

Kivy

FLTK

OpenGL

파이썬에 어떤 플랫폼 특정 GUI 툴킷이 있습니까?

Tkinter 질문

Tkinter 응용 프로그램을 어떻게 고정(freeze)합니까?

I/O를 기다리는 동안 Tk 이벤트를 처리하도록 할 수 있습니까?

Tkinter에서 키 바인딩이 동작하지 않습니다: 이유가 무엇입니까?

일반적인 GUI 질문

파이썬에 어떤 플랫폼 독립적인 GUI 툴킷이 있습니까?

여러분이 목표로 하는 플랫폼에 따라, 몇 가지가 있습니다. 그들 중 일부는 아직 파이썬 3에 이식되지 않았습니다. 적어도 Tkinter와 Qt는 파이썬 3과 호환되는 것으로 알려져 있습니다.

Tkinter

파이썬의 표준 빌드에는 Tcl/Tk 위젯 집합에 대한 객체 지향 인터페이스가 포함되는데, tkinter라고 불립니다. 이것이 아마도 가장 (파이썬의 대부분 바이너리 배포 [https://www.python.org/downloads/]에 포함되어 있으므로) 설치하고 사용하기 쉽습니다. 소스에 대한 안내를 포함하는 Tk에 대한 자세한 내용은 Tcl/Tk 홈페이지 [https://www.tcl.tk]를 참조하십시오. Tcl/Tk는 맥 OS X, 윈도우 및 유닉스 플랫폼에 완벽하게 호환됩니다.

wxWidgets

wxWidgets(https://www.wxwidgets.org)는 C++로 작성된 무료이고 이식성 있는 GUI 클래스 라이브러리인데, 많은 플랫폼에서 네이티브 룩앤필을 제공합니다. 윈도우, 맥 OS X, GTK, X11 가 모두 현재 안정 타깃에 포함됩니다. 파이썬, 펄, 루비등 다양한 언어에서 언어 바인딩을 사용할 수 있습니다.

wxPython [https://www.wxpython.org]은 wxwidgets의 파이썬 바인딩입니다. 공식 wxWidgets 배포보다 약간 뒤떨어 지지기는 하지만, 순수 파이썬 확장을 통해 다른 언어 바인딩에서는 사용할 수 없는 많은 기능을 제공하기도 합니다. 활발한 wxPython 사용자와 개발자 커뮤니티가 있습니다.

wxWidgets와 wxPython은 모두 프리웨어나 셰어웨어뿐만 아니라 상업용 제품에서의 사용을 허락하는 관대한 라이센스가 있는 무료 공개 소스 소프트웨어입니다.

Qt

Qt 툴킷(PyQt [https://riverbankcomputing.com/software/pyqt/intro]나 PySide [https://wiki.qt.io/PySide]를 사용하는)이나 KDE(PyKDE4 [https://techbase.kde.org/Languages/Python/Using_PyKDE_4])를 위한 바인딩을 사용할 수 있습니다. PyQt는 현재 PySide보다 더 성숙하지만, 독점 응용 프로그램을 작성하려면 Riverbank Computing [https://www.riverbankcomputing.com/commercial/license-faq]에서 PyQt 라이센스를 사야 합니다. PySide는 모든 응용 프로그램에서 무료입니다.

Qt 4.5 이상은 LGPL 라이센스에 따라 라이센스가 부여됩니다; 또한, 상용 라이센스는 The Qt Company [https://www.qt.io/licensing/]에서 제공됩니다.

Gtk+

파이썬용 GObject 인트로스펙션 바인딩 [https://wiki.gnome.org/Projects/PyGObject]를 사용하면 GTK+ 3 응용 프로그램을 작성할 수 있습니다. 파이썬 GTK+ 3 자습서 [https://python-gtk-3-tutorial.readthedocs.io]도 있습니다.

Gtk+ 2 툴킷 [https://www.gtk.org]을 위한 이전 PyGtk 바인딩은 James Henstridge가 구현했습니다; <http://www.pygtk.org>를 보세요.

Kivy

Kivy [https://kivy.org/]는 데스크톱 운영 체제(윈도우, macOS, 리눅스)와 모바일 장치(안드로이드, iOS)를 모두 지원하는 교차 플랫폼 GUI 라이브러리입니다. 이것은 파이썬과 Cython으로 작성되었으며 다양한 범위의 윈도우 백 엔드를 사용할 수 있습니다.

Kivy는 MIT 라이선스에 따라 배포되는 무료 공개 소스 소프트웨어입니다.

FLTK

간단하면서도 강력하고 성숙한 교차 플랫폼 윈도우 시스템인 FLTK 툴킷 [http://www.fltk.org]용 파이썬 바인딩이 PyFLTK 프로젝트 [http://pyfltk.sourceforge.net]에서 제공됩니다.

OpenGL

OpenGL 바인딩은 PyOpenGL [http://pyopengl.sourceforge.net]을 참조하십시오.

파이썬에 어떤 플랫폼 특정 GUI 툴킷이 있습니까?

PyObjc Objective-C 브리지 [https://pypi.org/project/pyobjc/]를 설치함으로써, 파이썬 프로그램은 맥 OS X의 Cocoa 라이브러리를 사용할 수 있습니다.

Mark Hammond의 Pythonwin에는 Microsoft Foundation Classes에 대한 인터페이스와 주로 파이썬으로 MFC 클래스를 사용하여 작성된 파이썬 프로그래밍 환경이 포함되어 있습니다.

Tkinter 질문

Tkinter 응용 프로그램을 어떻게 고정(freeze)합니까?

Freeze는 독립 실행형 응용 프로그램을 만드는 도구입니다. Tkinter 응용 프로그램을 고정할 때, 응용 프로그램은 여전히 Tcl과 Tk 라이브러리가 필요하므로 진정한 독립 실행형이 아닙니다.

한 가지 해결책은 응용 프로그램을 Tcl과 Tk 라이브러리와 함께 제공하고, 그것들을 실행 시간에 TCL_LIBRARY와 TK_LIBRARY 환경 변수를 사용하여 가리키는 것입니다.

진정한 독립 실행형 응용 프로그램을 얻으려면, 라이브러리를 구성하는 Tcl 스크립트도 응용 프로그램에 통합해야 합니다. 이를 지원하는 한 가지 도구는 Tix 배포판 (http://tix.sourceforge.net/)의 일부인 SAM(독립 실행형 모듈)입니다.

SAM이 활성화된 Tix를 빌드하고, 파이썬의 Modules/tkappinit.c 내부에서 Tclsam_init() 등을 적절하게 호출하고, libtclsam과 libtksam과 링크합니다 (Tix 라이브러리도 포함할 수 있습니다).

I/O를 기다리는 동안 Tk 이벤트를 처리하도록 할 수 있습니까?

윈도우 이외의 다른 플랫폼에서라면, 그렇습니다, 그리고 스레드가 필요하지도 않습니다! 그러나 I/O 코드를 약간 재구성해야 합니다. Tk는 Xt의 XtAddInput() 호출과 동등한 것을 갖고 있는데, 파일 기술자에서 I/O가 가능할 때 Tk 메인 루프에서 호출할 콜백 함수를 등록할 수 있도록 합니다. 파일 처리기를 참조하십시오.

Tkinter에서 키 바인딩이 동작하지 않습니다: 이유가 무엇입니까?

자주 들리는 불만은 적절한 키를 눌러도 bind() 메서드로 이벤트에 연결된 이벤트 처리기가 처리되지 않는다는 것입니다.

가장 흔한 원인은 바인딩이 적용되는 위젯에 “키보드 포커스”가 없는 것입니다. focus 명령에 대한 Tk 설명서를 확인하십시오. 보통 위젯은 그것을 클릭할 때 키보드 포커스를 받습니다 (라벨은 그렇지 않습니다; takefocus 옵션을 보십시오).

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 자주 나오는 질문들 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 자주 나오는 질문들 »

|

“왜 내 컴퓨터에 파이썬이 설치되어 있습니까?” FAQ

파이썬이 무엇입니까?

파이썬은 프로그래밍 언어입니다. 많은 다른 응용 프로그램에 사용됩니다. 파이썬은 배우기 쉬우므로 일부 고등학교와 대학에서는 입문 프로그래밍 언어로 사용되지만, Google, NASA 및 Lucasfilm Ltd.와 같은 곳에서 전문 소프트웨어 개발자가 사용하기도 합니다.

파이썬에 대해 더 알고 싶다면, 파이썬 입문자 지침서 [https://wiki.python.org/moin/BeginnersGuide]부터 시작하십시오.

내 컴퓨터에 파이썬이 설치된 이유는 무엇입니까?

파이썬이 시스템에 설치되어 있지만 설치한 기억이 없다면, 그렇게 될 수 있는 몇 가지 가능한 방법이 있습니다.

아마도 컴퓨터의 다른 사용자가 프로그래밍을 배우고 싶어 하고 그것을 설치했을 것입니다; 당신은 누가 컴퓨터를 사용했고 설치했는지 추측해야 합니다.

컴퓨터에 설치된 제삼자 응용 프로그램이 파이썬으로 작성되었으며, 파이썬 설치를 포함할 수 있습니다. GUI 프로그램에서 네트워크 서버와 관리 스크립트에 이르기까지 그런 응용 프로그램이 많이 있습니다.

일부 윈도우 컴퓨터에는 파이썬이 설치되어 있습니다. 이 글을 쓰는 시점에, 우리는 파이썬이 포함된 Hewlett-Packard와 Compaq의 컴퓨터에 대해 알고 있습니다. 분명히 HP/Compaq의 관리 도구 중 일부가 파이썬으로 작성되었을 겁니다.

맥 OS X 및 일부 리눅스 배포판과 같은 많은 유닉스 호환 운영 체제에는 기본적으로 파이썬이 설치되어 있습니다; 기본 설치에 포함되어 있습니다.

파이썬을 삭제할 수 있습니까?

파이썬이 어디서 왔는지에 달려 있습니다.

누군가 의도적으로 설치했으면, 아무 문제도 일으키지 않고 제거할 수 있습니다. 윈도우에서는, 제어판의 프로그램 추가/제거 아이콘을 사용하십시오.

제삼자 응용 프로그램에서 파이썬을 설치했다면, 제거할 수도 있지만, 해당 응용 프로그램이 더는 작동하지 않게 됩니다. 파이썬을 직접 제거하는 대신 해당 응용 프로그램의 제거 프로그램을 사용해야 합니다.

파이썬이 운영체제와 함께 제공되었다면, 제거하는 것은 바람직하지 않습니다. 제거하면, 파이썬으로 작성된 모든 도구가 더는 실행되지 않으며, 그중 일부는 중요할 수 있습니다. 문제를 해결하려면 다시 시스템을 재설치해야 할 수 있습니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 자주 나오는 질문들 »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

|

용어집

>>>

대화형 셸의 기본 파이썬 프롬프트. 인터프리터에서 대화형으로 실행될 수 있는 코드 예에서 자주 볼 수 있습니다.

...

들여쓰기 된 코드 블록의 코드를 입력할 때, 쌍을 이루는 구분자 (괄호, 대괄호, 중괄호) 안에 코드를 입력할 때, 데코레이터 지정 후의 대화형 셸의 기본 파이썬 프롬프트.

2to3

파이썬 2.x 코드를 파이썬 3.x 코드로 변환하려고 시도하는 도구인데, 소스를 구문 분석하고 구문 분석 트리를 탐색해서 감지할 수 있는 대부분의 비호환성을 다룹니다.

2to3 는 표준 라이브러리에서 lib2to3 로 제공됩니다; 독립적으로 실행할 수 있는 스크립트는 Tools/scripts/2to3 로 제공됩니다. 2to3 - 파이썬 2에서 파이썬 3으로 자동 코드 변환을 보세요.

abstract base class (추상 베이스 클래스)

추상 베이스 클래스는 hasattr() 같은 다른 테크닉들이 불편하거나 미묘하게 잘못된 (예를 들어, 매직 메서드) 경우, 인터페이스를 정의하는 방법을 제공함으로써 덕 타이핑 을 보완합니다. ABC는 가상 서브 클래스를 도입하는데, 클래스를 계승하지 않으면서도 isinstance() 와 issubclass() 에 의해 감지될 수 있는 클래스들입니다; abc 모듈 설명서를 보세요. 파이썬에는 많은 내장 ABC 들이 따라오는데 다음과 같은 것들이 있습니다: 자료 구조 (collections.abc 모듈에서), 숫자 (numbers 모듈에서), 스트림 (io 모듈에서), 임포트 파인더와 로더 (importlib.abc 모듈에서). abc 모듈을 사용해서 자신만의 ABC를 만들 수도 있습니다.

annotation (어노테이션)

관습에 따라 형 힌트 로 사용되는 변수, 클래스 어트리뷰트 또는 함수 매개변수 나 반환 값과 연결된 레이블입니다.

지역 변수의 어노테이션은 실행 시간에 액세스할 수 없지만, 전역 변수, 클래스 속성 및 함수의 어노테이션은 각각 모듈, 클래스, 함수의 __annotations__ 특수 어트리뷰트에 저장됩니다.

이 기능을 설명하는 변수 어노테이션, 함수 어노테이션, PEP 484 [https://www.python.org/dev/peps/pep-0484], PEP 526 [https://www.python.org/dev/peps/pep-0526]을 참조하세요.

argument (인자)

함수를 호출할 때 함수 (또는 메서드) 로 전달되는 값. 두 종류의 인자가 있습니다:

키워드 인자 (keyword argument): 함수 호출 때 식별자가 앞에 붙은 인자 (예를 들어, name=) 또는 ** 를 앞에 붙인 딕셔너리로 전달되는 인자. 예를 들어, 다음과 같은 complex() 호출에서 3 과 5 는 모두 키워드 인자입니다:

complex(real=3, imag=5)
complex(**{'real': 3, 'imag': 5})

위치 인자 (positional argument): 키워드 인자가 아닌 인자. 위치 인자들은 인자 목록의 처음에 나오거나 이터러블 의 앞에 * 를 붙여 전달할 수 있습니다. 예를 들어, 다음과 같은 호출에서 3 과 5 는 모두 위치 인자입니다.

complex(3, 5)
complex(*(3, 5))

인자는 함수 바디의 이름 붙은 지역 변수에 대입됩니다. 이 대입에 적용되는 규칙들에 대해서는 호출 절을 보세요. 문법적으로, 어떤 표현식이건 인자로 사용될 수 있습니다; 구해진 값이 지역 변수에 대입됩니다.

용어집의 매개변수 항목과 FAQ 질문 인자와 매개변수의 차이 와 PEP 362 [https://www.python.org/dev/peps/pep-0362]도 보세요.

asynchronous context manager (비동기 컨텍스트 관리자)

__aenter__() 와 __aexit__() 메서드를 정의함으로써 async with 문에서 보이는 환경을 제어하는 객체. PEP 492 [https://www.python.org/dev/peps/pep-0492]로 도입되었습니다.

asynchronous generator (비동기 제너레이터)

비동기 제너레이터 이터레이터 를 돌려주는 함수. async def 로 정의되는 코루틴 함수처럼 보이는데, async for 루프가 사용할 수 있는 일련의 값들을 만드는 yield 표현식을 포함한다는 점이 다릅니다.

보통 비동기 제너레이터 함수를 가리키지만, 어떤 문맥에서는 비동기 제너레이터 이터레이터 를 가리킵니다. 의도하는 의미가 명확하지 않은 경우는, 완전한 용어를 써서 모호함을 없앱니다.

비동기 제너레이터 함수는 await 표현식과, async for 문과, async with 문을 포함할 수 있습니다.

asynchronous generator iterator (비동기 제너레이터 이터레이터)

비동기 제너레이터 함수가 만드는 객체.

비동기 이터레이터 인데 __anext__() 를 호출하면 어웨이터블 객체를 돌려주고, 이것은 다음 yield 표현식 까지 비동기 제너레이터 함수의 바디를 실행합니다.

각 yield는 일시적으로 처리를 중단하고, 그 위치의 (지역 변수들과 대기 중인 try-문들을 포함하는) 실행 상태를 기억합니다. 비동기 제너레이터 이터레이터 가 __anext__() 가 돌려주는 또 하나의 어웨이터블로 재개되면, 떠난 곳으로 복귀합니다. PEP 492 [https://www.python.org/dev/peps/pep-0492]와 PEP 525 [https://www.python.org/dev/peps/pep-0525]를 보세요.

asynchronous iterable (비동기 이터러블)

async for 문에서 사용될 수 있는 객체. __aiter__() 메서드는 비동기 이터레이터 를 돌려줘야 합니다. PEP 492 [https://www.python.org/dev/peps/pep-0492] 로 도입되었습니다.

asynchronous iterator (비동기 이터레이터)

__aiter__() 와 __anext__() 메서드를 구현하는 객체. __anext__ 는 어웨이터블 객체를 돌려줘야 합니다. async for는 StopAsyncIteration 예외가 발생할 때까지 비동기 이터레이터의 __anext__() 메서드가 돌려주는 어웨이터블을 풉니다. PEP 492 [https://www.python.org/dev/peps/pep-0492]로 도입되었습니다.

attribute (어트리뷰트)

점표현식을 사용하는 이름으로 참조되는 객체와 결합한 값. 예를 들어, 객체 o가 어트리뷰트 a를 가지면, o.a처럼 참조됩니다.

awaitable (어웨이터블)

await 표현식에 사용할 수 있는 객체. 코루틴 이나 __await__() 메서드를 가진 객체가 될 수 있습니다. PEP 492 [https://www.python.org/dev/peps/pep-0492]를 보세요.

BDFL

자비로운 종신 독재자 (Benevolent Dictator For Life), 즉 Guido van Rossum [https://gvanrossum.github.io/], 파이썬의 창시자.

binary file (바이너리 파일)

바이트열류 객체들을 읽고 쓸 수 있는 파일 객체. 바이너리 파일의 예로는 바이너리 모드 ('rb', 'wb' 또는 'rb+') 로 열린 파일, sys.stdin.buffer, sys.stdout.buffer, io.BytesIO 와 gzip.GzipFile 의 인스턴스를 들 수 있습니다.

str 객체를 읽고 쓸 수 있는 파일 객체에 대해서는 텍스트 파일 도 참조하세요.

bytes-like object (바이트열류 객체)

버퍼 프로토콜 를 지원하고 C-연속 버퍼를 익스포트 할 수 있습니다. 여러 공통 memoryview 객체들은 물론이고 bytes, bytearray, array.array 객체들을 포함합니다. 바이트열류 객체들은 바이너리 데이터를 다루는 여러 가지 연산들에 사용될 수 있습니다; 압축, 바이너리 파일로 저장, 소켓을 통한 전송 같은 것들이 있습니다.

어떤 연산들은 바이너리 데이터가 가변적일 필요가 있습니다. 이런 경우에 설명서는 종종 “읽고-쓰기 바이트열류 객체”라고 표현합니다. 가변 버퍼 객체의 예로는 bytearray 와 bytearray 의 memoryview 가 있습니다. 다른 연산들은 바이너리 데이터가 불변 객체 (“읽기 전용 바이트열류 객체”)에 저장되도록 요구합니다; 이런 것들의 예로는 bytes와 bytes 객체의 memoryview 가 있습니다.

bytecode (바이트 코드)

파이썬 소스 코드는 바이트 코드로 컴파일되는데, CPython 인터프리터에서 파이썬 프로그램의 내부 표현입니다. 바이트 코드는 .pyc 파일에 캐시 되어, 같은 파일을 두 번째 실행할 때 더 빨라지게 만듭니다 (소스에서 바이트 코드로의 재컴파일을 피할 수 있습니다). 이 “중간 언어” 는 각 바이트 코드에 대응하는 기계를 실행하는 가상 기계 에서 실행된다고 말합니다. 바이트 코드는 서로 다른 파이썬 가상 기계에서 작동할 것으로 기대하지도, 파이썬 배포 간에 안정적이지도 않다는 것에 주의해야 합니다.

바이트 코드 명령어들의 목록은 dis 모듈 설명서에 나옵니다.

class (클래스)

사용자 정의 객체들을 만들기 위한 주형. 클래스 정의는 보통 클래스의 인스턴스를 대상으로 연산하는 메서드 정의들을 포함합니다.

class variable (클래스 변수)

클래스에서 정의되고 클래스 수준 (즉, 클래스의 인스턴스에서가 아니라) 에서만 수정되는 변수.

coercion (코어션)

같은 형의 두 인자를 수반하는 연산이 일어나는 동안, 한 형의 인스턴스를 다른 형으로 묵시적으로 변환하는 것. 예를 들어, int(3.15)는 실수를 정수 3으로 변환합니다. 하지만, 3+4.5 에서, 각 인자는 다른 형이고 (하나는 int, 다른 하나는 float), 둘을 더하기 전에 같은 형으로 변환해야 합니다. 그렇지 않으면 TypeError를 일으킵니다. 코어션 없이는, 호환되는 형들조차도 프로그래머가 같은 형으로 정규화해주어야 합니다, 예를 들어, 그냥 3+4.5 하는 대신 float(3)+4.5.

complex number (복소수)

익숙한 실수 시스템의 확장인데, 모든 숫자가 실수부와 허수부의 합으로 표현됩니다. 허수부는 실수에 허수 단위(-1의 제곱근)를 곱한 것인데, 종종 수학에서는 i로, 공학에서는 j로 표기합니다. 파이썬은 후자의 표기법을 쓰는 복소수를 기본 지원합니다; 허수부는 j 접미사를 붙여서 표기합니다, 예를 들어, 3+1j. math 모듈의 복소수 버전이 필요하면, cmath를 사용합니다. 복소수의 활용은 꽤 수준 높은 수학적 기능입니다. 필요하다고 느끼지 못한다면, 거의 확실히 무시해도 좋습니다.

context manager (컨텍스트 관리자)

__enter__() 와 __exit__() 메서드를 정의함으로써 with 문에서 보이는 환경을 제어하는 객체. PEP 343 [https://www.python.org/dev/peps/pep-0343]으로 도입되었습니다.

context variable (컨텍스트 변수)

컨텍스트에 따라 다른 값을 가질 수 있는 변수. 이는 각 실행 스레드가 변수에 대해 다른 값을 가질 수 있는 스레드-로컬 저장소와 비슷합니다. 그러나, 컨텍스트 변수를 통해, 하나의 실행 스레드에 여러 컨텍스트가 있을 수 있으며 컨텍스트 변수의 주 용도는 동시성 비동기 태스크에서 변수를 추적하는 것입니다. contextvars를 참조하십시오.

contiguous (연속)

버퍼는 정확히 C-연속(C-contiguous)이거나 포트란 연속(Fortran contiguous)일 때 연속이라고 여겨집니다. 영차원 버퍼는 C-연속이면서 포트란 연속입니다. 일차원 배열에서, 항목들은 서로에 인접하고, 0에서 시작하는 오름차순 인덱스의 순서대로 메모리에 배치되어야 합니다. 다차원 C-연속 배열에서, 메모리 주소의 순서대로 항목들을 방문할 때 마지막 인덱스가 가장 빨리 변합니다. 하지만, 포트란 연속 배열에서는, 첫 번째 인덱스가 가장 빨리 변합니다.

coroutine (코루틴)

Coroutines are a more generalized form of subroutines. Subroutines are entered at one point and exited at another point. Coroutines can be entered, exited, and resumed at many different points. They can be implemented with the async def statement. See also PEP 492 [https://www.python.org/dev/peps/pep-0492].

coroutine function (코루틴 함수)

코루틴 객체를 돌려주는 함수. 코루틴 함수는 async def 문으로 정의될 수 있고, await 와 async for와 async with 키워드를 포함할 수 있습니다. 이것들은 PEP 492 [https://www.python.org/dev/peps/pep-0492] 에 의해 도입되었습니다.

CPython

파이썬 프로그래밍 언어의 규범적인 구현인데, python.org [https://www.python.org]에서 배포됩니다. 이 구현을 Jython 이나 IronPython 과 같은 다른 것들과 구별할 필요가 있을 때 용어 “CPython” 이 사용됩니다.

decorator (데코레이터)

다른 함수를 돌려주는 함수인데, 보통 @wrapper 문법을 사용한 함수 변환으로 적용됩니다. 데코레이터의 흔한 예는 classmethod() 과 staticmethod() 입니다.

데코레이터 문법은 단지 편의 문법일 뿐입니다. 다음 두 함수 정의는 의미상으로 동등합니다:

def f(...):
    ...
f = staticmethod(f)

@staticmethod
def f(...):
    ...

같은 개념이 클래스에도 존재하지만, 덜 자주 쓰입니다. 데코레이터에 대한 더 자세한 내용은 함수 정의 와 클래스 정의 의 설명서를 보면 됩니다.

descriptor (디스크립터)

메서드 __get__() 이나 __set__() 이나 __delete__()를 정의하는 객체. 클래스 어트리뷰트가 디스크립터일 때, 어트리뷰트 조회는 특별한 연결 작용을 일으킵니다. 보통, a.b를 읽거나, 쓰거나, 삭제하는데 사용할 때, a의 클래스 딕셔너리에서 b 라고 이름 붙여진 객체를 찾습니다. 하지만 b가 디스크립터면, 해당하는 디스크립터 메서드가 호출됩니다. 디스크립터를 이해하는 것은 파이썬에 대한 깊은 이해의 열쇠인데, 함수, 메서드, 프로퍼티, 클래스 메서드, 스태틱 메서드, 슈퍼클래스 참조 등의 많은 기능의 기초를 이루고 있기 때문입니다.

디스크립터의 메서드들에 대한 자세한 내용은 디스크립터 구현하기에 나옵니다.

dictionary (딕셔너리)

임의의 키를 값에 대응시키는 연관 배열 (associative array). 키는 __hash__() 와 __eq__() 메서드를 갖는 모든 객체가 될 수 있습니다. 펄에서 해시라고 부릅니다.

dictionary view (딕셔너리 뷰)

dict.keys(), dict.values(), dict.items() 메서드가 돌려주는 객체들을 딕셔너리 뷰라고 부릅니다. 이것들은 딕셔너리 항목들에 대한 동적인 뷰를 제공하는데, 딕셔너리가 변경될 때, 뷰가 이 변화를 반영한다는 뜻입니다. 딕셔너리 뷰를 완전한 리스트로 바꾸려면 list(dictview)를 사용하면 됩니다. 딕셔너리 뷰 객체를 보세요.

docstring (독스트링)

클래스, 함수, 모듈에서 첫 번째 표현식으로 나타나는 문자열 리터럴. 스위트가 실행될 때는 무시되지만, 컴파일러에 의해 인지되어 둘러싼 클래스, 함수, 모듈의 __doc__ 어트리뷰트로 삽입됩니다. 인트로스팩션을 통해 사용할 수 있으므로, 객체의 설명서를 위한 규범적인 장소입니다.

duck-typing (덕 타이핑)

올바른 인터페이스를 가졌는지 판단하는데 객체의 형을 보지 않는 프로그래밍 스타일; 대신, 단순히 메서드나 어트리뷰트가 호출되거나 사용됩니다 (“오리처럼 보이고 오리처럼 꽥꽥댄다면, 그것은 오리다.”) 특정한 형 대신에 인터페이스를 강조함으로써, 잘 설계된 코드는 다형적인 치환을 허락함으로써 유연성을 개선할 수 있습니다. 덕 타이핑은 type() 이나 isinstance() 을 사용한 검사를 피합니다. (하지만, 덕 타이핑이 추상 베이스 클래스 로 보완될 수 있음에 유의해야 합니다.) 대신에, hasattr() 검사나 EAFP 프로그래밍을 씁니다.

EAFP

허락보다는 용서를 구하기가 쉽다 (Easier to ask for forgiveness than permission). 이 흔히 볼 수 있는 파이썬 코딩 스타일은, 올바른 키나 어트리뷰트의 존재를 가정하고, 그 가정이 틀리면 예외를 잡습니다. 이 깔끔하고 빠른 스타일은 많은 try와 except 문의 존재로 특징지어집니다. 이 테크닉은 C와 같은 다른 많은 언어에서 자주 사용되는 LBYL 스타일과 대비됩니다.

expression (표현식)

어떤 값으로 구해질 수 있는 문법적인 조각. 다른 말로 표현하면, 표현식은 리터럴, 이름, 어트리뷰트 액세스, 연산자, 함수들과 같은 값을 돌려주는 표현 요소들을 쌓아 올린 것입니다. 다른 많은 언어와 대조적으로, 모든 언어 구성물들이 표현식인 것은 아닙니다. while처럼, 표현식으로 사용할 수 없는 문장 들이 있습니다. 대입 또한 문장이고, 표현식이 아닙니다.

extension module (확장 모듈)

C 나 C++로 작성된 모듈인데, 파이썬의 C API를 사용해서 핵심이나 사용자 코드와 상호 작용합니다.

f-string (f-문자열)

'f' 나 'F' 를 앞에 붙인 문자열 리터럴들을 흔히 “f-문자열”이라고 부르는데, 포맷 문자열 리터럴 의 줄임말입니다. PEP 498 [https://www.python.org/dev/peps/pep-0498] 을 보세요.

file object (파일 객체)

하부 자원에 대해 파일 지향적 API(read() 나 write() 같은 메서드들)를 드러내는 객체. 만들어진 방법에 따라, 파일 객체는 실제 디스크 상의 파일이나 다른 저장 장치나 통신 장치 (예를 들어, 표준 입출력, 인-메모리 버퍼, 소켓, 파이프, 등등)에 대한 액세스를 중계할 수 있습니다. 파일 객체는 파일류 객체 (file-like objects)나 스트림 (streams) 이라고도 불립니다.

실제로는 세 부류의 파일 객체들이 있습니다. 날(raw) 바이너리 파일, 버퍼드(buffered) 바이너리 파일, 텍스트 파일. 이들의 인터페이스는 io 모듈에서 정의됩니다. 파일 객체를 만드는 규범적인 방법은 open() 함수를 쓰는 것입니다.

file-like object (파일류 객체)

파일 객체 의 비슷한 말.

finder (파인더)

임포트될 모듈을 위한 로더 를 찾으려고 시도하는 객체.

파이썬 3.3. 이후로, 두 종류의 파인더가 있습니다: sys.meta_path 와 함께 사용하는 메타 경로 파인더 와 sys.path_hooks 과 함께 사용하는 경로 엔트리 파인더.

더 자세한 내용은 PEP 302 [https://www.python.org/dev/peps/pep-0302], PEP 420 [https://www.python.org/dev/peps/pep-0420], PEP 451 [https://www.python.org/dev/peps/pep-0451] 에 나옵니다.

floor division (정수 나눗셈)

가장 가까운 정수로 내림하는 수학적 나눗셈. 정수 나눗셈 연산자는 // 다. 예를 들어, 표현식 11 // 4 의 값은 2가 되지만, 실수 나눗셈은 2.75를 돌려줍니다. (-11) // 4 가 -2.75를 내림 한 -3이 됨에 유의해야 합니다. PEP 238 [https://www.python.org/dev/peps/pep-0238]을 보세요.

function (함수)

호출자에게 어떤 값을 돌려주는 일련의 문장들. 없거나 그 이상의 인자 가 전달될 수 있는데, 바디의 실행에 사용될 수 있습니다. 매개변수 와 메서드 와 함수 정의 섹션도 보세요.

function annotation (함수 어노테이션)

함수 매개변수나 반환 값의 어노테이션.

함수 어노테이션은 일반적으로 형 힌트 로 사용됩니다: 예를 들어, 이 함수는 두 개의 int 인자를 받아들일 것으로 기대되고, 동시에 int 반환 값을 줄 것으로 기대됩니다:

def sum_two_numbers(a: int, b: int) -> int:
   return a + b

함수 어노테이션 문법은 함수 정의 절에서 설명합니다.

이 기능을 설명하는 변수 어노테이션 과 PEP 484 [https://www.python.org/dev/peps/pep-0484]를 참조하세요.

__future__

프로그래머가 현재 인터프리터와 호환되지 않는 새 언어 기능들을 활성화할 수 있도록 하는 가상 모듈.

__future__ 모듈을 임포트하고 그 변수들의 값들을 구해서, 새 기능이 언제 처음으로 언어에 추가되었고, 언제부터 그것이 기본이 되는지 볼 수 있습니다:

>>> import __future__
>>> __future__.division
_Feature((2, 2, 0, 'alpha', 2), (3, 0, 0, 'alpha', 0), 8192)

garbage collection (가비지 수거)

더 사용되지 않는 메모리를 반납하는 절차. 파이썬은 참조 횟수 추적과 참조 순환을 감지하고 끊을 수 있는 순환 가비지 수거기를 통해 가비지 수거를 수행합니다. 가비지 수거기는 gc 모듈을 사용해서 제어할 수 있습니다.

generator (제너레이터)

제너레이터 이터레이터 를 돌려주는 함수. 일반 함수처럼 보이는데, 일련의 값들을 만드는 yield 표현식을 포함한다는 점이 다릅니다. 이 값들은 for-루프로 사용하거나 next() 함수로 한 번에 하나씩 꺼낼 수 있습니다.

보통 제너레이터 함수를 가리키지만, 어떤 문맥에서는 제너레이터 이터레이터 를 가리킵니다. 의도하는 의미가 명확하지 않은 경우는, 완전한 용어를 써서 모호함을 없앱니다.

generator iterator (제너레이터 이터레이터)

제너레이터 함수가 만드는 객체.

각 yield는 일시적으로 처리를 중단하고, 그 위치의 (지역 변수들과 대기 중인 try-문들을 포함하는) 실행 상태를 기억합니다. 제너레이터 이터레이터 가 재개되면, 떠난 곳으로 복귀합니다 (호출마다 새로 시작하는 함수와 대비됩니다).

generator expression (제너레이터 표현식)

이터레이터를 돌려주는 표현식. 루프 변수와 범위를 정의하는 for 절과 생략 가능한 if 절이 뒤에 붙는 일반 표현식 처럼 보입니다. 결합한 표현식은 둘러싼 함수를 위한 값들을 만들어냅니다:

>>> sum(i*i for i in range(10))         # sum of squares 0, 1, 4, ... 81
285

generic function (제네릭 함수)

같은 연산을 서로 다른 형들에 대해 구현한 여러 함수로 구성된 함수. 호출 때 어떤 구현이 사용될지는 디스패치 알고리즘에 의해 결정됩니다.

싱글 디스패치 용어집 항목과 functools.singledispatch() 데코레이터와 PEP 443 [https://www.python.org/dev/peps/pep-0443]도 보세요.

GIL

전역 인터프리터 록 을 보세요.

global interpreter lock (전역 인터프리터 록)

한 번에 오직 하나의 스레드가 파이썬 바이트 코드 를 실행하도록 보장하기 위해 CPython 인터프리터가 사용하는 메커니즘. (dict와 같은 중요한 내장형들을 포함하는) 객체 모델이 묵시적으로 동시 액세스에 대해 안전하도록 만들어서 CPython 구현을 단순하게 만듭니다. 인터프리터 전체를 잠그는 것은 인터프리터를 다중스레드화하기 쉽게 만드는 대신, 다중 프로세서 기계가 제공하는 병렬성의 많은 부분을 희생합니다.

하지만, 어떤 확장 모듈들은, 표준이나 제삼자 모두, 압축이나 해싱 같은 계산 집약적인 작업을 수행할 때는 GIL을 반납하도록 설계되었습니다. 또한, I/O를 할 때는 항상 GIL을 반납합니다.

(훨씬 더 미세하게 공유 데이터를 잠그는) “스레드에 자유로운(free-threaded)” 인터프리터를 만들고자 하는 과거의 노력은 성공적이지 못했는데, 흔한 단일 프로세서 경우의 성능 저하가 심하기 때문입니다. 이 성능 이슈를 극복하는 것은 구현을 훨씬 복잡하게 만들어서 유지 비용이 더 들어갈 것으로 여겨지고 있습니다.

hash-based pyc (해시 기반 pyc)

유효성을 판별하기 위해 해당 소스 파일의 최종 수정 시간이 아닌 해시를 사용하는 바이트 코드 캐시 파일. 캐시된 바이트 코드 무효화을 참조하세요.

hashable (해시 가능)

객체가 일생 그 값이 변하지 않는 해시값을 갖고 (__hash__() 메서드가 필요합니다), 다른 객체와 비교될 수 있으면 (__eq__() 메서드가 필요합니다), 해시 가능하다고 합니다. 같다고 비교되는 해시 가능한 객체들의 해시값은 같아야 합니다.

해시 가능성은 객체를 딕셔너리의 키나 집합의 멤버로 사용할 수 있게 하는데, 이 자료 구조들이 내부적으로 해시값을 사용하기 때문입니다.

대부분 파이썬의 불변 내장 객체들은 해시 가능합니다; (리스트나 딕셔너리 같은) 가변 컨테이너들은 그렇지 않습니다; (튜플이나 frozenset 같은) 불변 컨테이너들은 그들의 요소들이 해시 가능할 때만 해시 가능합니다. 사용자 정의 클래스의 인스턴스 객체들은 기본적으로 해시 가능합니다. (자기 자신을 제외하고는) 모두 다르다고 비교되고, 해시값은 id()로 부터 만들어집니다.

IDLE

파이썬을 위한 통합 개발 환경 (Integrated Development Environment). IDLE은 파이썬의 표준 배포판에 따라오는 기초적인 편집기와 인터프리터 환경입니다.

immutable (불변)

고정된 값을 갖는 객체. 불변 객체는 숫자, 문자열, 튜플을 포함합니다. 이런 객체들은 변경될 수 없습니다. 새 값을 저장하려면 새 객체를 만들어야 합니다. 변하지 않는 해시값이 있어야 하는 곳에서 중요한 역할을 합니다, 예를 들어, 딕셔너리의 키.

import path (임포트 경로)

경로 기반 파인더 가 임포트 할 모듈을 찾기 위해 검색하는 장소들 (또는 경로 엔트리) 의 목록. 임포트 하는 동안, 이 장소들의 목록은 보통 sys.path 로부터 옵니다, 하지만 서브 패키지의 경우 부모 패키지의 __path__ 어트리뷰트로부터 올 수도 있습니다.

importing (임포팅)

한 모듈의 파이썬 코드가 다른 모듈의 파이썬 코드에서 사용될 수 있도록 하는 절차.

importer (임포터)

모듈을 찾기도 하고 로드 하기도 하는 객체; 동시에 파인더 이자 로더 객체입니다.

interactive (대화형)

파이썬은 대화형 인터프리터를 갖고 있는데, 인터프리터 프롬프트에서 문장과 표현식을 입력할 수 있고, 즉각 실행된 결과를 볼 수 있다는 뜻입니다. 인자 없이 단지 python을 실행하세요 (컴퓨터의 주메뉴에서 선택하는 것도 가능할 수 있습니다). 새 아이디어를 검사하거나 모듈과 패키지를 들여다보는 매우 강력한 방법입니다 (help(x)를 기억하세요).

interpreted (인터프리티드)

바이트 코드 컴파일러의 존재 때문에 그 구분이 흐릿해지기는 하지만, 파이썬은 컴파일 언어가 아니라 인터프리터 언어입니다. 이것은 명시적으로 실행 파일을 만들지 않고도, 소스 파일을 직접 실행할 수 있다는 뜻입니다. 그 프로그램이 좀 더 천천히 실행되기는 하지만, 인터프리터 언어는 보통 컴파일 언어보다 짧은 개발/디버깅 주기를 갖습니다. 대화형 도 보세요.

interpreter shutdown (인터프리터 종료)

종료하라는 요청을 받을 때, 파이썬 인터프리터는 특별한 시기에 진입하는데, 모듈이나 여러 가지 중요한 내부 구조들과 같은 모든 할당된 자원들을 단계적으로 반납합니다. 또한, 가비지 수거기 를 여러 번 호출합니다. 사용자 정의 파괴자나 weakref 콜백에 있는 코드들의 실행을 시작시킬 수 있습니다. 종료 시기 동안 실행되는 코드는 다양한 예외들을 만날 수 있는데, 그것이 의존하는 자원들이 더 기능하지 않을 수 있기 때문입니다 (흔한 예는 라이브러리 모듈이나 경고 장치들입니다).

인터프리터 종료의 주된 원인은 실행되는 __main__ 모듈이나 스크립트가 실행을 끝내는 것입니다.

iterable (이터러블)

멤버들을 한 번에 하나씩 돌려줄 수 있는 객체. 이터러블의 예로는 모든 (list, str, tuple 같은) 시퀀스 형들, dict 같은 몇몇 비 시퀀스 형들, 파일 객체들, __iter__() 나 시퀀스 개념을 구현하는 __getitem__() 메서드를 써서 정의한 모든 클래스의 객체들이 있습니다.

이터러블은 for 루프에 사용될 수 있고, 시퀀스를 필요로 하는 다른 많은 곳 (zip(), map(), …) 에 사용될 수 있습니다. 이터러블 객체가 내장 함수 iter() 에 인자로 전달되면, 그 객체의 이터레이터를 돌려줍니다. 이 이터레이터는 값들의 집합을 한 번 거치는 동안 유효합니다. 이터러블을 사용할 때, 보통은 iter() 를 호출하거나, 이터레이터 객체를 직접 다룰 필요는 없습니다. for 문은 이것들을 여러분을 대신해서 자동으로 해주는데, 루프를 도는 동안 이터레이터를 잡아둘 이름 없는 변수를 만듭니다. 이터레이터, 시퀀스, 제너레이터 도 보세요.

iterator (이터레이터)

데이터의 스트림을 표현하는 객체. 이터레이터의 __next__() 메서드를 반복적으로 호출하면 (또는 내장 함수 next() 로 전달하면) 스트림에 있는 항목들을 차례대로 돌려줍니다. 더 이상의 데이터가 없을 때는 대신 StopIteration 예외를 일으킵니다. 이 지점에서, 이터레이터 객체는 소진되고, 이후의 모든 __next__() 메서드 호출은 StopIteration 예외를 다시 일으키기만 합니다. 이터레이터는 이터레이터 객체 자신을 돌려주는 __iter__() 메서드를 가질 것이 요구되기 때문에, 이터레이터는 이터러블이기도 하고 다른 이터러블들을 받아들이는 대부분의 곳에서 사용될 수 있습니다. 중요한 예외는 여러 번의 이터레이션을 시도하는 코드입니다. (list 같은) 컨테이너 객체는 iter() 함수로 전달하거나 for 루프에 사용할 때마다 새 이터레이터를 만듭니다. 이런 것을 이터레이터에 대해서 수행하려고 하면, 지난 이터레이션에 사용된 이미 소진된 이터레이터를 돌려줘서, 빈 컨테이너처럼 보이게 만듭니다.

이터레이터 형 에 더 자세한 내용이 있습니다.

key function (키 함수)

키 함수 또는 콜레이션(collation) 함수는 정렬(sorting)이나 배열(ordering)에 사용되는 값을 돌려주는 콜러블입니다. 예를 들어, locale.strxfrm() 은 로케일 특정 방식을 따르는 정렬 키를 만드는 데 사용됩니다.

파이썬의 많은 도구가 요소들이 어떻게 순서 지어지고 묶이는지를 제어하기 위해 키 함수를 받아들입니다. 이런 것들에는 min(), max(), sorted(), list.sort(), heapq.merge(), heapq.nsmallest(), heapq.nlargest(), itertools.groupby() 이 있습니다.

키 함수를 만드는 데는 여러 방법이 있습니다. 예를 들어, str.lower() 메서드는 케이스 구분 없는 정렬을 위한 키 함수로 사용될 수 있습니다. 대안적으로, 키 함수는 lambda 표현식으로 만들 수도 있는데, 이런 식입니다: lambda r: (r[0], r[2]). 또한, operator 모듈은 세 개의 키 함수 생성자를 제공합니다: attrgetter(), itemgetter(), methodcaller(). 키 함수를 만들고 사용하는 법에 대한 예로 Sorting HOW TO 를 보세요.

keyword argument (키워드 인자)

인자 를 보세요.

lambda (람다)

호출될 때 값이 구해지는 하나의 표현식 으로 구성된 이름 없는 인라인 함수. 람다 함수를 만드는 문법은 lambda [parameters]: expression 입니다.

LBYL

뛰기 전에 보라 (Look before you leap). 이 코딩 스타일은 호출이나 조회를 하기 전에 명시적으로 사전 조건들을 검사합니다. 이 스타일은 EAFP 접근법과 대비되고, 많은 if 문의 존재로 특징지어집니다.

다중 스레드 환경에서, LBYL 접근법은 “보기”와 “뛰기” 간에 경쟁 조건을 만들게 될 위험이 있습니다. 예를 들어, 코드 if key in mapping: return mapping[key] 는 검사 후에, 하지만 조회 전에, 다른 스레드가 key를 mapping에서 제거하면 실패할 수 있습니다. 이런 이슈는 록이나 EAFP 접근법을 사용함으로써 해결될 수 있습니다.

list (리스트)

내장 파이썬 시퀀스. 그 이름에도 불구하고, 원소에 대한 액세스가 O(1)이기 때문에, 연결 리스트(linked list)보다는 다른 언어의 배열과 유사합니다.

list comprehension (리스트 컴프리헨션)

시퀀스의 요소들 전부 또는 일부를 처리하고 그 결과를 리스트로 돌려주는 간결한 방법. result = ['{:#04x}'.format(x) for x in range(256) if x % 2 == 0] 는 0에서 255 사이에 있는 짝수들의 16진수 (0x..) 들을 포함하는 문자열의 리스트를 만듭니다. if 절은 생략할 수 있습니다. 생략하면, range(256)에 있는 모든 요소가 처리됩니다.

loader (로더)

모듈을 로드하는 객체. load_module() 이라는 이름의 메서드를 정의해야 합니다. 로더는 보통 파인더 가 돌려줍니다. 자세한 내용은 PEP 302 [https://www.python.org/dev/peps/pep-0302] 를, 추상 베이스 클래스 는 importlib.abc.Loader 를 보세요.

magic method (매직 메서드)

특수 메서드 의 비공식적인 비슷한 말.

mapping (매핑)

임의의 키 조회를 지원하고 Mapping 이나 MutableMapping 추상 베이스 클래스 에 지정된 메서드들을 구현하는 컨테이너 객체. 예로는 dict, collections.defaultdict, collections.OrderedDict, collections.Counter 를 들 수 있습니다.

meta path finder (메타 경로 파인더)

sys.meta_path 의 검색이 돌려주는 파인더. 메타 경로 파인더는 경로 엔트리 파인더 와 관련되어 있기는 하지만 다릅니다.

메타 경로 파인더가 구현하는 메서드들에 대해서는 importlib.abc.MetaPathFinder 를 보면 됩니다.

metaclass (메타 클래스)

클래스의 클래스. 클래스 정의는 클래스 이름, 클래스 딕셔너리, 베이스 클래스들의 목록을 만듭니다. 메타 클래스는 이 세 인자를 받아서 클래스를 만드는 책임을 집니다. 대부분의 객체 지향형 프로그래밍 언어들은 기본 구현을 제공합니다. 파이썬을 특별하게 만드는 것은 커스텀 메타 클래스를 만들 수 있다는 것입니다. 대부분 사용자에게는 이 도구가 전혀 필요 없지만, 필요가 생길 때, 메타 클래스는 강력하고 우아한 해법을 제공합니다. 어트리뷰트 액세스의 로깅(logging), 스레드 안전성의 추가, 객체 생성 추적, 싱글톤 구현과 많은 다른 작업에 사용됐습니다.

메타 클래스 에서 더 자세한 내용을 찾을 수 있습니다.

method (메서드)

클래스 바디 안에서 정의되는 함수. 그 클래스의 인스턴스의 어트리뷰트로서 호출되면, 그 메서드는 첫 번째 인자 (보통 self 라고 불린다) 로 인스턴스 객체를 받습니다. 함수 와 중첩된 스코프 를 보세요.

method resolution order (메서드 결정 순서)

메서드 결정 순서는 조회하는 동안 멤버를 검색하는 베이스 클래스들의 순서입니다. 2.3 릴리스부터 파이썬 인터프리터에 사용된 알고리즘의 상세한 내용은 The Python 2.3 Method Resolution Order [https://www.python.org/download/releases/2.3/mro/]를 보면 됩니다.

module (모듈)

파이썬 코드의 조직화 단위를 담당하는 객체. 모듈은 임의의 파이썬 객체들을 담는 이름 공간을 갖습니다. 모듈은 임포팅 절차에 의해 파이썬으로 로드됩니다.

패키지 도 보세요.

module spec (모듈 스펙)

모듈을 로드하는데 사용되는 임포트 관련 정보들을 담고 있는 이름 공간. importlib.machinery.ModuleSpec 의 인스턴스.

MRO

메서드 결정 순서 를 보세요.

mutable (가변)

가변 객체는 값이 변할 수 있지만 id() 는 일정하게 유지합니다. 불변 도 보세요.

named tuple (네임드 튜플)

The term “named tuple” applies to any type or class that inherits from tuple and whose indexable elements are also accessible using named attributes. The type or class may have other features as well.

Several built-in types are named tuples, including the values returned by time.localtime() and os.stat(). Another example is sys.float_info:

>>> sys.float_info[1]                   # indexed access
1024
>>> sys.float_info.max_exp              # named field access
1024
>>> isinstance(sys.float_info, tuple)   # kind of tuple
True

Some named tuples are built-in types (such as the above examples). Alternatively, a named tuple can be created from a regular class definition that inherits from tuple and that defines named fields. Such a class can be written by hand or it can be created with the factory function collections.namedtuple(). The latter technique also adds some extra methods that may not be found in hand-written or built-in named tuples.

namespace (이름 공간)

변수가 저장되는 장소. 이름 공간은 딕셔너리로 구현됩니다. 객체에 중첩된 이름 공간 (메서드 에서) 뿐만 아니라 지역, 전역, 내장 이름 공간이 있습니다. 이름 공간은 이름 충돌을 방지해서 모듈성을 지원합니다. 예를 들어, 함수 builtins.open 과 os.open() 은 그들의 이름 공간에 의해 구별됩니다. 또한, 이름 공간은 어떤 모듈이 함수를 구현하는지를 분명하게 만들어서 가독성과 유지 보수성에 도움을 줍니다. 예를 들어, random.seed() 또는 itertools.islice() 라고 쓰면 그 함수들이 각각 random 과 itertools 모듈에 의해 구현되었음이 명확해집니다.

namespace package (이름 공간 패키지)

오직 서브 패키지들의 컨테이너로만 기능하는 PEP 420 [https://www.python.org/dev/peps/pep-0420] 패키지. 이름 공간 패키지는 물리적인 실체가 없을 수도 있고, 특히 __init__.py 파일이 없으므로 정규 패키지 와는 다릅니다.

모듈 도 보세요.

nested scope (중첩된 스코프)

둘러싼 정의에서 변수를 참조하는 능력. 예를 들어, 다른 함수 내부에서 정의된 함수는 바깥 함수에 있는 변수들을 참조할 수 있습니다. 중첩된 스코프는 기본적으로는 참조만 가능할 뿐, 대입은 되지 않는다는 것에 주의해야 합니다. 지역 변수들은 가장 내부의 스코프에서 읽고 씁니다. 마찬가지로, 전역 변수들은 전역 이름 공간에서 읽고 씁니다. nonlocal 은 바깥 스코프에 쓰는 것을 허락합니다.

new-style class (뉴스타일 클래스)

지금은 모든 클래스 객체에 사용되고 있는 클래스 버전의 예전 이름. 초기의 파이썬 버전에서는, 오직 뉴스타일 클래스만 __slots__, 디스크립터, 프라퍼티, __getattribute__(), 클래스 메서드, 스태틱 메서드와 같은 파이썬의 새롭고 다양한 기능들을 사용할 수 있었습니다.

object (객체)

상태 (어트리뷰트나 값) 를 갖고 동작 (메서드) 이 정의된 모든 데이터. 또한, 모든 뉴스타일 클래스 의 최종적인 베이스 클래스입니다.

package (패키지)

서브 모듈들이나, 재귀적으로 서브 패키지들을 포함할 수 있는 파이썬 모듈. 기술적으로, 패키지는 __path__ 어트리뷰트가 있는 파이썬 모듈입니다.

정규 패키지 와 이름 공간 패키지 도 보세요.

parameter (매개변수)

함수 (또는 메서드) 정의에서 함수가 받을 수 있는 인자 (또는 어떤 경우 인자들) 를 지정하는 이름 붙은 엔티티. 다섯 종류의 매개변수가 있습니다:

위치-키워드 (positional-or-keyword): 위치 인자 나 키워드 인자 로 전달될 수 있는 인자를 지정합니다. 이것이 기본 형태의 매개변수입니다, 예를 들어 다음에서 foo 와 bar:

def func(foo, bar=None): ...

위치-전용 (positional-only): 위치로만 제공될 수 있는 인자를 지정합니다. 파이썬은 위치-전용 매개변수를 정의하는 문법을 갖고 있지 않습니다. 하지만, 어떤 매장 함수들은 위치-전용 매개변수를 갖습니다 (예를 들어, abs()).

키워드-전용 (keyword-only): 키워드로만 제공될 수 있는 인자를 지정합니다. 키워드-전용 매개변수는 함수 정의의 매개변수 목록에서 앞에 하나의 가변-위치 매개변수나 *를 그대로 포함해서 정의할 수 있습니다. 예를 들어, 다음에서 kw_only1 와 kw_only2:

def func(arg, *, kw_only1, kw_only2): ...

가변-위치 (var-positional): (다른 매개변수들에 의해서 이미 받아들여진 위치 인자들에 더해) 제공될 수 있는 위치 인자들의 임의의 시퀀스를 지정합니다. 이런 매개변수는 매개변수 이름에 * 를 앞에 붙여서 정의될 수 있습니다, 예를 들어 다음에서 args:

def func(*args, **kwargs): ...

가변-키워드 (var-keyword): (다른 매개변수들에 의해서 이미 받아들여진 키워드 인자들에 더해) 제공될 수 있는 임의의 개수 키워드 인자들을 지정합니다. 이런 매개변수는 매개변수 이름에 **를 앞에 붙여서 정의될 수 있습니다, 예를 들어 위의 예에서 kwargs.

매개변수는 선택적 인자들을 위한 기본값뿐만 아니라 선택적이거나 필수 인자들을 지정할 수 있습니다.

인자 용어집 항목, 인자와 매개변수의 차이에 나오는 FAQ 질문, inspect.Parameter 클래스, 함수 정의 절, PEP 362 [https://www.python.org/dev/peps/pep-0362]도 보세요.

path entry (경로 엔트리)

경로 기반 파인더 가 임포트 할 모듈들을 찾기 위해 참고하는 임포트 경로 상의 하나의 장소.

path entry finder (경로 엔트리 파인더)

sys.path_hooks 에 있는 콜러블 (즉, 경로 엔트리 훅) 이 돌려주는 파인더 인데, 주어진 경로 엔트리 로 모듈을 찾는 방법을 알고 있습니다.

경로 엔트리 파인더들이 구현하는 메서드들은 importlib.abc.PathEntryFinder 에 나옵니다.

path entry hook (경로 엔트리 훅)

sys.path_hook 리스트에 있는 콜러블인데, 특정 경로 엔트리 에서 모듈을 찾는 법을 알고 있다면 경로 엔트리 파인더 를 돌려줍니다.

path based finder (경로 기반 파인더)

기본 메타 경로 파인더들 중 하나인데, 임포트 경로 에서 모듈을 찾습니다.

path-like object (경로류 객체)

파일 시스템 경로를 나타내는 객체. 경로류 객체는 경로를 나타내는 str 나 bytes 객체이거나 os.PathLike 프로토콜을 구현하는 객체입니다. os.PathLike 프로토콜을 지원하는 객체는 os.fspath() 함수를 호출해서 str 나 bytes 파일 시스템 경로로 변환될 수 있습니다; 대신 os.fsdecode() 와 os.fsencode() 는 각각 str 나 bytes 결과를 보장하는데 사용될 수 있습니다. PEP 519 [https://www.python.org/dev/peps/pep-0519]로 도입되었습니다.

PEP

파이썬 개선 제안. PEP는 파이썬 커뮤니티에 정보를 제공하거나 파이썬 또는 그 프로세스 또는 환경에 대한 새로운 기능을 설명하는 설계 문서입니다. PEP는 제안된 기능에 대한 간결한 기술 사양 및 근거를 제공해야 합니다.

PEP는 주요 새로운 기능을 제안하고 문제에 대한 커뮤니티 입력을 수집하며 파이썬에 들어간 설계 결정을 문서로 만들기 위한 기본 메커니즘입니다. PEP 작성자는 커뮤니티 내에서 합의를 구축하고 반대 의견을 문서화 할 책임이 있습니다.

PEP 1 [https://www.python.org/dev/peps/pep-0001] 참조하세요.

portion (포션)

PEP 420 [https://www.python.org/dev/peps/pep-0420] 에서 정의한 것처럼, 이름 공간 패키지에 이바지하는 하나의 디렉터리에 들어있는 파일들의 집합 (zip 파일에 저장되는 것도 가능합니다).

positional argument (위치 인자)

인자 를 보세요.

provisional API (잠정 API)

잠정 API는 표준 라이브러리의 과거 호환성 보장으로부터 신중히 제외된 것입니다. 인터페이스의 큰 변화가 예상되지는 않지만, 잠정적이라고 표시되는 한, 코어 개발자들이 필요하다고 생각한다면 과거 호환성이 유지되지 않는 변경이 일어날 수 있습니다. 그런 변경은 불필요한 방식으로 일어나지는 않을 것입니다 — API를 포함하기 전에 놓친 중대하고 근본적인 결함이 발견된 경우에만 일어날 것입니다.

잠정 API에서조차도, 과거 호환성이 유지되지 않는 변경은 “최후의 수단”으로 여겨집니다 - 모든 식별된 문제들에 대해 과거 호환성을 유지하는 해법을 찾으려는 모든 시도가 선행됩니다.

이 절차는 표준 라이브러리가 오랜 시간 동안 잘못된 설계 오류에 발목 잡히지 않고 발전할 수 있도록 만듭니다. 더 자세한 내용은 PEP 411 [https://www.python.org/dev/peps/pep-0411]을 보면 됩니다.

provisional package (잠정 패키지)

잠정 API 를 보세요.

Python 3000 (파이썬 3000)

파이썬 3.x 배포 라인의 별명 (버전 3의 배포가 먼 미래의 이야기던 시절에 만들어진 이름이다.) 이것을 “Py3k” 로 줄여 쓰기도 합니다.

Pythonic (파이썬다운)

다른 언어들에서 일반적인 개념들을 사용해서 코드를 구현하는 대신, 파이썬 언어에서 가장 자주 사용되는 이디엄들을 가까이 따르는 아이디어나 코드 조각. 예를 들어, 파이썬에서 자주 쓰는 이디엄은 for 문을 사용해서 이터러블의 모든 요소로 루핑하는 것입니다. 다른 많은 언어에는 이런 종류의 구성물이 없으므로, 파이썬에 익숙하지 않은 사람들은 대신에 숫자 카운터를 사용하기도 합니다:

for i in range(len(food)):
    print(food[i])

더 깔끔한, 파이썬다운 방법은 이렇습니다:

for piece in food:
    print(piece)

qualified name (정규화된 이름)

모듈의 전역 스코프에서 모듈에 정의된 클래스, 함수, 메서드에 이르는 “경로”를 보여주는 점으로 구분된 이름. PEP 3155 [https://www.python.org/dev/peps/pep-3155] 에서 정의됩니다. 최상위 함수와 클래스의 경우에, 정규화된 이름은 객체의 이름과 같습니다:

>>> class C:
...     class D:
...         def meth(self):
...             pass
...
>>> C.__qualname__
'C'
>>> C.D.__qualname__
'C.D'
>>> C.D.meth.__qualname__
'C.D.meth'

모듈을 가리키는데 사용될 때, 완전히 정규화된 이름(fully qualified name)은 모든 부모 패키지들을 포함해서 모듈로 가는 점으로 분리된 이름을 의미합니다, 예를 들어, email.mime.text:

>>> import email.mime.text
>>> email.mime.text.__name__
'email.mime.text'

reference count (참조 횟수)

객체에 대한 참조의 개수. 객체의 참조 횟수가 0으로 떨어지면, 메모리가 반납됩니다. 참조 횟수 추적은 일반적으로 파이썬 코드에 노출되지는 않지만, CPython 구현의 핵심 요소입니다. sys 모듈은 특정 객체의 참조 횟수를 돌려주는 getrefcount() 을 정의합니다.

regular package (정규 패키지)

__init__.py 파일을 포함하는 디렉터리와 같은 전통적인 패키지.

이름 공간 패키지 도 보세요.

__slots__

클래스 내부의 선언인데, 인스턴스 어트리뷰트들을 위한 공간을 미리 선언하고 인스턴스 딕셔너리를 제거함으로써 메모리를 절감하는 효과를 줍니다. 인기 있기는 하지만, 이 테크닉은 올바르게 사용하기가 좀 까다로운 편이라서, 메모리에 민감한 응용 프로그램에서 많은 수의 인스턴스가 있는 특별한 경우로 한정하는 것이 좋습니다.

sequence (시퀀스)

__getitem__() 특수 메서드를 통해 정수 인덱스를 사용한 빠른 요소 액세스를 지원하고, 시퀀스의 길이를 돌려주는 __len__() 메서드를 정의하는 이터러블. 몇몇 내장 시퀀스들을 나열해보면, list, str, tuple, bytes 가 있습니다. dict 또한 __getitem__() 과 __len__() 을 지원하지만, 조회에 정수 대신 임의의 불변 키를 사용하기 때문에 시퀀스가 아니라 매핑으로 취급된다는 것에 주의해야 합니다.

collections.abc.Sequence 추상 베이스 클래스는 __getitem__() 과 __len__()을 넘어서 훨씬 풍부한 인터페이스를 정의하는데, count(), index(), __contains__(), __reversed__()를 추가합니다. 이 확장된 인터페이스를 구현한 형을 register()를 사용해서 명시적으로 등록할 수 있습니다.

single dispatch (싱글 디스패치)

구현이 하나의 인자의 형에 기초해서 결정되는 제네릭 함수 디스패치의 한 형태.

slice (슬라이스)

보통 시퀀스 의 일부를 포함하는 객체. 슬라이스는 서브 스크립트 표기법을 사용해서 만듭니다. variable_name[1:3:5] 처럼, [] 안에서 여러 개의 숫자를 콜론으로 분리합니다. 대괄호 (서브 스크립트) 표기법은 내부적으로 slice 객체를 사용합니다.

special method (특수 메서드)

파이썬이 형에 어떤 연산을, 덧셈 같은, 실행할 때 묵시적으로 호출되는 메서드. 이런 메서드는 두 개의 밑줄로 시작하고 끝나는 이름을 갖고 있습니다. 특수 메서드는 특수 메서드 이름들 에 문서로 만들어져 있습니다.

statement (문장)

문장은 스위트 (코드의 “블록(block)”) 를 구성하는 부분입니다. 문장은 표현식 이거나 키워드를 사용하는 여러 가지 구조물 중의 하나입니다. 가령 if, while, for.

text encoding (텍스트 인코딩)

유니코드 문자열을 바이트열로 인코딩하는 코덱.

text file (텍스트 파일)

str 객체를 읽고 쓸 수 있는 파일 객체. 종종, 텍스트 파일은 실제로는 바이트 지향 데이터스트림을 액세스하고 텍스트 인코딩 을 자동 처리합니다. 텍스트 파일의 예로는 텍스트 모드 ('r' 또는 'w') 로 열린 파일, sys.stdin, sys.stdout, io.StringIO 의 인스턴스를 들 수 있습니다.

바이트열류 객체 를 읽고 쓸 수 있는 파일 객체에 대해서는 바이너리 파일 도 참조하세요.

triple-quoted string (삼중 따옴표 된 문자열)

따옴표 (”) 나 작은따옴표 (’) 세 개로 둘러싸인 문자열. 그냥 따옴표 하나로 둘러싸인 문자열에 없는 기능을 제공하지는 않지만, 여러 가지 이유에서 쓸모가 있습니다. 이스케이프 되지 않은 작은따옴표나 큰따옴표를 문자열 안에 포함할 수 있도록 하고, 연결 문자를 쓰지 않고도 여러 줄에 걸칠 수 있는데, 독스트링을 쓸 때 특히 쓸모 있습니다.

type (형)

파이썬 객체의 형은 그것이 어떤 종류의 객체인지를 결정합니다; 모든 객체는 형이 있습니다. 객체의 형은 __class__ 어트리뷰트로 액세스할 수 있거나 type(obj)로 얻을 수 있습니다.

type alias (형 에일리어스)

형을 식별자에 대입하여 만들어지는 형의 동의어.

형 에일리어스는 형 힌트를 단순화하는 데 유용합니다. 예를 들면:

from typing import List, Tuple

def remove_gray_shades(
        colors: List[Tuple[int, int, int]]) -> List[Tuple[int, int, int]]:
    pass

는 다음과 같이 더 읽기 쉽게 만들 수 있습니다:

from typing import List, Tuple

Color = Tuple[int, int, int]

def remove_gray_shades(colors: List[Color]) -> List[Color]:
    pass

이 기능을 설명하는 typing과 PEP 484 [https://www.python.org/dev/peps/pep-0484]를 참조하세요.

type hint (형 힌트)

변수, 클래스 어트리뷰트 및 함수 매개변수 나 반환 값의 기대되는 형을 지정하는 어노테이션.

형 힌트는 선택 사항이며 파이썬에서 강제되지는 않습니다. 하지만, 정적 형 분석 도구에 유용하며 IDE의 코드 완성 및 리팩토링을 돕습니다.

지역 변수를 제외하고, 전역 변수, 클래스 어트리뷰트 및 함수의 형 힌트는 typing.get_type_hints()를 사용하여 액세스할 수 있습니다.

이 기능을 설명하는 typing과 PEP 484 [https://www.python.org/dev/peps/pep-0484]를 참조하세요.

universal newlines (유니버설 줄 넘김)

다음과 같은 것들을 모두 줄의 끝으로 인식하는, 텍스트 스트림을 해석하는 태도: 유닉스 개행 문자 관례 '\n', 윈도우즈 관례 '\r\n', 예전의 매킨토시 관례 '\r'. 추가적인 사용에 관해서는 bytes.splitlines() 뿐만 아니라 PEP 278 [https://www.python.org/dev/peps/pep-0278] 와 PEP 3116 [https://www.python.org/dev/peps/pep-3116] 도 보세요.

variable annotation (변수 어노테이션)

변수 또는 클래스 어트리뷰트의 어노테이션.

변수 또는 클래스 어트리뷰트에 어노테이션을 달 때 대입은 선택 사항입니다:

class C:
    field: 'annotation'

변수 어노테이션은 일반적으로 형 힌트로 사용됩니다: 예를 들어, 이 변수는 int 값을 가질 것으로 기대됩니다:

count: int = 0

변수 어노테이션 문법은 섹션 어노테이트된 대입문(Annotated assignment statements) 에서 설명합니다.

이 기능을 설명하는 함수 어노테이션, PEP 484 [https://www.python.org/dev/peps/pep-0484] 및 PEP 526 [https://www.python.org/dev/peps/pep-0526]을 참조하세요.

virtual environment (가상 환경)

파이썬 사용자와 응용 프로그램이, 같은 시스템에서 실행되는 다른 파이썬 응용 프로그램들의 동작에 영향을 주지 않으면서, 파이썬 배포 패키지들을 설치하거나 업그레이드하는 것을 가능하게 하는, 협력적으로 격리된 실행 환경.

venv 도 보세요.

virtual machine (가상 기계)

소프트웨어만으로 정의된 컴퓨터. 파이썬의 가상 기계는 바이트 코드 컴파일러가 출력하는 바이트 코드를 실행합니다.

Zen of Python (파이썬 젠)

파이썬 디자인 원리와 철학들의 목록인데, 인어를 이해하고 사용하는 데 도움이 됩니다. 이 목록은 대화형 프롬프트에서 “import this” 를 입력하면 보입니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

|

이 설명서에 관하여

이 설명서는 reStructuredText [http://docutils.sourceforge.net/rst.html] 소스에서 만들어진 것으로, 파이썬 설명서를 위해 특별히 제작된 문서 처리기인 Sphinx [http://sphinx-doc.org/] 를 사용했습니다.

설명서와 이를 위한 툴체인 개발은 파이썬 자체와 마찬가지로 전적으로 자원봉사자의 노력입니다. 기여하고 싶다면, 참여 방법에 대한 정보는 버그 다루기 페이지를 참고하십시오. 새로운 자원봉사자는 언제나 환영합니다!

다음 분들에게 많은 감사를 드립니다:

Fred L. Drake, Jr., 원래 파이썬 설명서 도구 집합의 작성자이자 많은 콘텐츠의 작가;

reStructuredText와 Docutils 스위트를 만드는 Docutils [http://docutils.sourceforge.net/] 프로젝트.

Fredrik Lundh, 그의 Alternative Python Reference [http://effbot.org/zone/pyref.htm] 프로젝트에서 Sphinx가 많은 아이디어를 얻었습니다.

파이썬 설명서의 공헌자들

많은 사람이 파이썬 언어, 파이썬 표준 라이브러리 및 파이썬 설명서에 기여했습니다. 기여자의 부분적인 목록은 파이썬 소스 배포판의 Misc/ACKS [https://github.com/python/cpython/tree/3.7/Misc/ACKS] 를 참조하십시오.

파이썬이 이런 멋진 설명서를 갖게 된 것은 파이썬 커뮤니티의 입력과 기여 때문입니다 – 감사합니다!

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

|

버그 다루기

파이썬은 안정성에 대해 명성을 쌓아온 성숙한 프로그래밍 언어입니다. 이 평판을 유지하기 위해, 개발자는 파이썬에서 여러분이 발견한 결함을 알고 싶어 합니다.

때로는 버그를 직접 수정하고 패치를 파이썬에 제공하는 것이 프로세스를 간소화하고 인력을 덜 요구하기 때문에 더 빠를 수 있습니다. 이바지하는 방법을 배우세요.

설명서 버그

이 설명서에서 버그를 발견하거나 개선 제안을 하고 싶다면, 버그 보고서를 추적기 에 등록해 주세요. 문제가 한국어 번역에만 존재한다면, https://github.com/python/python-docs-ko/issues 에 등록해야 합니다. 수정하는 방법에 대한 제안이 있다면, 포함 시켜 주세요.

시간이 부족하다면, 설명서 버그 보고서를 docs@python.org 로 전자 메일로 보낼 수도 있습니다 (동작 버그는 python-list@python.org 로 보낼 수 있습니다). ‘docs@’ 는 자원 봉사자가 운영하는 메일링리스트입니다; 처리되는 데 다소 시간이 걸릴 수 있지만, 여러분의 요청에 대한 통지가 있을 것입니다.

더 보기

파이썬 문제 추적기의 Documentation bugs [https://github.com/python/cpython/issues?q=is%3Aissue+is%3Aopen+label%3Adocs]

파이썬 문제 추적기 사용하기

Issue reports for Python itself should be submitted via the GitHub issues tracker (https://github.com/python/cpython/issues). The GitHub issues tracker offers a web form which allows pertinent information to be entered and submitted to the developers.

The first step in filing a report is to determine whether the problem has already been reported. The advantage in doing so, aside from saving the developers’ time, is that you learn what has been done to fix it; it may be that the problem has already been fixed for the next release, or additional information is needed (in which case you are welcome to provide it if you can!). To do this, search the tracker using the search box at the top of the page.

If the problem you’re reporting is not already in the list, log in to GitHub. If you don’t already have a GitHub account, create a new account using the “Sign up” link. It is not possible to submit a bug report anonymously.

Being now logged in, you can submit an issue. Click on the “New issue” button in the top bar to report a new issue.

The submission form has two fields, “Title” and “Comment”.

For the “Title” field, enter a very short description of the problem; less than ten words is good.

“Comment” 입력란에, 문제를 자세히 설명하는데, 기대한 것과 실제로 일어난 것을 포함합니다. 확장 모듈이 개입하고 있는지, 그리고 사용 중인 하드웨어 및 소프트웨어 플랫폼 (적절한 버전 정보 포함)을 포함해야 합니다.

Each issue report will be reviewed by a developer who will determine what needs to be done to correct the problem. You will receive an update each time an action is taken on the issue.

더 보기

버그를 효과적으로 보고하는 방법 [https://www.chiark.greenend.org.uk/~sgtatham/bugs.html]

유용한 버그 보고서를 작성하는 방법에 대해 자세히 설명하는 기사. 이것은 어떤 종류의 정보가 유용하고 왜 유용한지를 설명합니다.

Bug Report Writing Guidelines [https://developer.mozilla.org/en-US/docs/Mozilla/QA/Bug_writing_guidelines]

좋은 버그 리포트 작성에 관한 정보. 이 중 일부는 모질라(Mozilla) 프로젝트에만 적용되지만, 일반적인 우수 사례를 설명합니다.

파이썬에 직접 이바지하기 입문

발견한 버그를 보고하는 것 외에도, 패치를 제출하여 문제를 해결할 수 있습니다. 파이썬을 패치하는 방법에 대한 더 많은 정보는 Python Developer’s Guide [https://devguide.python.org/] 에서 찾을 수 있습니다. 질문이 있으면, core-mentorship mailing list [https://mail.python.org/mailman3/lists/core-mentorship.python.org/] 는 파이썬에서 문제를 수정하는 과정에 관한 모든 질문에 대한 답변을 얻을 수 있는 친근한 곳입니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

|

저작권

파이썬과 이 설명서는:

Copyright © 2001-2023 Python Software Foundation. All rights reserved.

Copyright © 2000 BeOpen.com. All rights reserved.

Copyright © 1995-2000 Corporation for National Research Initiatives. All rights reserved.

Copyright © 1991-1995 Stichting Mathematisch Centrum. All rights reserved.

전체 라이센스 및 사용 권한 정보는 역사와 라이센스 에서 제공합니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

|

역사와 라이센스

소프트웨어의 역사

파이썬은 ABC라는 언어의 후계자로서 네덜란드의 Stichting Mathematisch Centrum (CWI, https://www.cwi.nl/ 참조)의 Guido van Rossum에 의해 1990년대 초반에 만들어졌습니다. 파이썬에는 다른 사람들의 많은 공헌이 포함되었지만, Guido는 파이썬의 주요 저자로 남아 있습니다.

1995년, Guido는 Virginia의 Reston에 있는 Corporation for National Research Initiatives(CNRI, https://www.cnri.reston.va.us/ 참조)에서 파이썬 작업을 계속했고, 이곳에서 여러 버전의 소프트웨어를 출시했습니다.

In May 2000, Guido and the Python core development team moved to BeOpen.com to form the BeOpen PythonLabs team. In October of the same year, the PythonLabs team moved to Digital Creations (now Zope Corporation; see https://www.zope.org/). In 2001, the Python Software Foundation (PSF, see https://www.python.org/psf/) was formed, a non-profit organization created specifically to own Python-related Intellectual Property. Zope Corporation is a sponsoring member of the PSF.

모든 파이썬 배포판은 공개 소스입니다 (공개 소스 정의에 대해서는 https://opensource.org/를 참조하십시오). 역사적으로, 대부분 (하지만 전부는 아닙니다) 파이썬 배포판은 GPL과 호환됩니다; 아래의 표는 다양한 배포판을 요약한 것입니다.

배포판

파생된 곳

해

소유자

GPL 호환?

0.9.0 ~ 1.2

n/a

1991-1995

CWI

yes

1.3 ~ 1.5.2

1.2

1995-1999

CNRI

yes

1.6

1.5.2

2000

CNRI

no

2.0

1.6

2000

BeOpen.com

no

1.6.1

1.6

2001

CNRI

no

2.1

2.0+1.6.1

2001

PSF

no

2.0.1

2.0+1.6.1

2001

PSF

yes

2.1.1

2.1+2.0.1

2001

PSF

yes

2.1.2

2.1.1

2002

PSF

yes

2.1.3

2.1.2

2002

PSF

yes

2.2 이상

2.1.1

2001-현재

PSF

yes

참고

GPL과 호환된다는 것은 우리가 GPL로 파이썬을 배포한다는 것을 의미하지는 않습니다. 모든 파이썬 라이센스는 GPL과 달리 여러분의 변경을 공개 소스로 만들지 않고 수정된 버전을 배포할 수 있게 합니다. GPL 호환 라이센스는 파이썬과 GPL 하에 발표된 다른 소프트웨어를 결합할 수 있게 합니다; 다른 것들은 그렇지 않습니다.

Guido의 지도하에 이 배포를 가능하게 만든 많은 외부 자원봉사자들에게 감사드립니다.

파이썬에 액세스하거나 사용하기 위한 이용 약관

PSF LICENSE AGREEMENT FOR PYTHON 3.7.17

1. This LICENSE AGREEMENT is between the Python Software Foundation ("PSF"), and
   the Individual or Organization ("Licensee") accessing and otherwise using Python
   3.7.17 software in source or binary form and its associated documentation.

2. Subject to the terms and conditions of this License Agreement, PSF hereby
   grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce,
   analyze, test, perform and/or display publicly, prepare derivative works,
   distribute, and otherwise use Python 3.7.17 alone or in any derivative
   version, provided, however, that PSF's License Agreement and PSF's notice of
   copyright, i.e., "Copyright © 2001-2023 Python Software Foundation; All Rights
   Reserved" are retained in Python 3.7.17 alone or in any derivative version
   prepared by Licensee.

3. In the event Licensee prepares a derivative work that is based on or
   incorporates Python 3.7.17 or any part thereof, and wants to make the
   derivative work available to others as provided herein, then Licensee hereby
   agrees to include in any such work a brief summary of the changes made to Python
   3.7.17.

4. PSF is making Python 3.7.17 available to Licensee on an "AS IS" basis.
   PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.  BY WAY OF
   EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND DISCLAIMS ANY REPRESENTATION OR
   WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE
   USE OF PYTHON 3.7.17 WILL NOT INFRINGE ANY THIRD PARTY RIGHTS.

5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON 3.7.17
   FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF
   MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 3.7.17, OR ANY DERIVATIVE
   THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.

6. This License Agreement will automatically terminate upon a material breach of
   its terms and conditions.

7. Nothing in this License Agreement shall be deemed to create any relationship
   of agency, partnership, or joint venture between PSF and Licensee.  This License
   Agreement does not grant permission to use PSF trademarks or trade name in a
   trademark sense to endorse or promote products or services of Licensee, or any
   third party.

8. By copying, installing or otherwise using Python 3.7.17, Licensee agrees
   to be bound by the terms and conditions of this License Agreement.

BEOPEN.COM LICENSE AGREEMENT FOR PYTHON 2.0

BEOPEN PYTHON OPEN SOURCE LICENSE AGREEMENT VERSION 1

1. This LICENSE AGREEMENT is between BeOpen.com ("BeOpen"), having an office at
   160 Saratoga Avenue, Santa Clara, CA 95051, and the Individual or Organization
   ("Licensee") accessing and otherwise using this software in source or binary
   form and its associated documentation ("the Software").

2. Subject to the terms and conditions of this BeOpen Python License Agreement,
   BeOpen hereby grants Licensee a non-exclusive, royalty-free, world-wide license
   to reproduce, analyze, test, perform and/or display publicly, prepare derivative
   works, distribute, and otherwise use the Software alone or in any derivative
   version, provided, however, that the BeOpen Python License is retained in the
   Software, alone or in any derivative version prepared by Licensee.

3. BeOpen is making the Software available to Licensee on an "AS IS" basis.
   BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.  BY WAY OF
   EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO AND DISCLAIMS ANY REPRESENTATION OR
   WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE
   USE OF THE SOFTWARE WILL NOT INFRINGE ANY THIRD PARTY RIGHTS.

4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE SOFTWARE FOR
   ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF USING,
   MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY DERIVATIVE THEREOF, EVEN IF
   ADVISED OF THE POSSIBILITY THEREOF.

5. This License Agreement will automatically terminate upon a material breach of
   its terms and conditions.

6. This License Agreement shall be governed by and interpreted in all respects
   by the law of the State of California, excluding conflict of law provisions.
   Nothing in this License Agreement shall be deemed to create any relationship of
   agency, partnership, or joint venture between BeOpen and Licensee.  This License
   Agreement does not grant permission to use BeOpen trademarks or trade names in a
   trademark sense to endorse or promote products or services of Licensee, or any
   third party.  As an exception, the "BeOpen Python" logos available at
   http://www.pythonlabs.com/logos.html may be used according to the permissions
   granted on that web page.

7. By copying, installing or otherwise using the software, Licensee agrees to be
   bound by the terms and conditions of this License Agreement.

CNRI LICENSE AGREEMENT FOR PYTHON 1.6.1

1. This LICENSE AGREEMENT is between the Corporation for National Research
   Initiatives, having an office at 1895 Preston White Drive, Reston, VA 20191
   ("CNRI"), and the Individual or Organization ("Licensee") accessing and
   otherwise using Python 1.6.1 software in source or binary form and its
   associated documentation.

2. Subject to the terms and conditions of this License Agreement, CNRI hereby
   grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce,
   analyze, test, perform and/or display publicly, prepare derivative works,
   distribute, and otherwise use Python 1.6.1 alone or in any derivative version,
   provided, however, that CNRI's License Agreement and CNRI's notice of copyright,
   i.e., "Copyright © 1995-2001 Corporation for National Research Initiatives; All
   Rights Reserved" are retained in Python 1.6.1 alone or in any derivative version
   prepared by Licensee.  Alternately, in lieu of CNRI's License Agreement,
   Licensee may substitute the following text (omitting the quotes): "Python 1.6.1
   is made available subject to the terms and conditions in CNRI's License
   Agreement.  This Agreement together with Python 1.6.1 may be located on the
   Internet using the following unique, persistent identifier (known as a handle):
   1895.22/1013.  This Agreement may also be obtained from a proxy server on the
   Internet using the following URL: http://hdl.handle.net/1895.22/1013."

3. In the event Licensee prepares a derivative work that is based on or
   incorporates Python 1.6.1 or any part thereof, and wants to make the derivative
   work available to others as provided herein, then Licensee hereby agrees to
   include in any such work a brief summary of the changes made to Python 1.6.1.

4. CNRI is making Python 1.6.1 available to Licensee on an "AS IS" basis.  CNRI
   MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.  BY WAY OF EXAMPLE,
   BUT NOT LIMITATION, CNRI MAKES NO AND DISCLAIMS ANY REPRESENTATION OR WARRANTY
   OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF
   PYTHON 1.6.1 WILL NOT INFRINGE ANY THIRD PARTY RIGHTS.

5. CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON 1.6.1 FOR
   ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF
   MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 1.6.1, OR ANY DERIVATIVE
   THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.

6. This License Agreement will automatically terminate upon a material breach of
   its terms and conditions.

7. This License Agreement shall be governed by the federal intellectual property
   law of the United States, including without limitation the federal copyright
   law, and, to the extent such U.S. federal law does not apply, by the law of the
   Commonwealth of Virginia, excluding Virginia's conflict of law provisions.
   Notwithstanding the foregoing, with regard to derivative works based on Python
   1.6.1 that incorporate non-separable material that was previously distributed
   under the GNU General Public License (GPL), the law of the Commonwealth of
   Virginia shall govern this License Agreement only as to issues arising under or
   with respect to Paragraphs 4, 5, and 7 of this License Agreement.  Nothing in
   this License Agreement shall be deemed to create any relationship of agency,
   partnership, or joint venture between CNRI and Licensee.  This License Agreement
   does not grant permission to use CNRI trademarks or trade name in a trademark
   sense to endorse or promote products or services of Licensee, or any third
   party.

8. By clicking on the "ACCEPT" button where indicated, or by copying, installing
   or otherwise using Python 1.6.1, Licensee agrees to be bound by the terms and
   conditions of this License Agreement.

CWI LICENSE AGREEMENT FOR PYTHON 0.9.0 THROUGH 1.2

Copyright © 1991 - 1995, Stichting Mathematisch Centrum Amsterdam, The
Netherlands.  All rights reserved.

Permission to use, copy, modify, and distribute this software and its
documentation for any purpose and without fee is hereby granted, provided that
the above copyright notice appear in all copies and that both that copyright
notice and this permission notice appear in supporting documentation, and that
the name of Stichting Mathematisch Centrum or CWI not be used in advertising or
publicity pertaining to distribution of the software without specific, written
prior permission.

STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE FOR ANY SPECIAL, INDIRECT
OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
SOFTWARE.

포함된 소프트웨어에 대한 라이센스 및 승인

이 섹션은 파이썬 배포판에 포함된 제삼자 소프트웨어에 대한 불완전하지만 늘어나고 있는 라이센스와 승인의 목록입니다.

메르센 트위스터

_random 모듈은 http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/MT2002/emt19937ar.html 에서 내려받은 코드에 기반한 코드를 포함합니다. 다음은 원래 코드의 주석을 그대로 옮긴 것입니다:

A C-program for MT19937, with initialization improved 2002/1/26.
Coded by Takuji Nishimura and Makoto Matsumoto.

Before using, initialize the state by using init_genrand(seed)
or init_by_array(init_key, key_length).

Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura,
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

 1. Redistributions of source code must retain the above copyright
    notice, this list of conditions and the following disclaimer.

 2. Redistributions in binary form must reproduce the above copyright
    notice, this list of conditions and the following disclaimer in the
    documentation and/or other materials provided with the distribution.

 3. The names of its contributors may not be used to endorse or promote
    products derived from this software without specific prior written
    permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Any feedback is very welcome.
http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html
email: m-mat @ math.sci.hiroshima-u.ac.jp (remove space)

소켓

socket 모듈은 getaddrinfo()와 getnameinfo() 함수를 사용합니다. 이들은 WIDE Project, http://www.wide.ad.jp/, 에서 온 별도 소스 파일로 코딩되어 있습니다.

Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.
3. Neither the name of the project nor the names of its contributors
   may be used to endorse or promote products derived from this software
   without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.

비동기 소켓 서비스

asynchat과 asyncore 모듈은 다음과 같은 주의 사항을 포함합니다:

Copyright 1996 by Sam Rushing

                        All Rights Reserved

Permission to use, copy, modify, and distribute this software and
its documentation for any purpose and without fee is hereby
granted, provided that the above copyright notice appear in all
copies and that both that copyright notice and this permission
notice appear in supporting documentation, and that the name of Sam
Rushing not be used in advertising or publicity pertaining to
distribution of the software without specific, written prior
permission.

SAM RUSHING DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN
NO EVENT SHALL SAM RUSHING BE LIABLE FOR ANY SPECIAL, INDIRECT OR
CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

쿠키 관리

http.cookies 모듈은 다음과 같은 주의 사항을 포함합니다:

Copyright 2000 by Timothy O'Malley <timo@alum.mit.edu>

               All Rights Reserved

Permission to use, copy, modify, and distribute this software
and its documentation for any purpose and without fee is hereby
granted, provided that the above copyright notice appear in all
copies and that both that copyright notice and this permission
notice appear in supporting documentation, and that the name of
Timothy O'Malley  not be used in advertising or publicity
pertaining to distribution of the software without specific, written
prior permission.

Timothy O'Malley DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS, IN NO EVENT SHALL Timothy O'Malley BE LIABLE FOR
ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.

실행 추적

trace 모듈은 다음과 같은 주의 사항을 포함합니다:

portions copyright 2001, Autonomous Zones Industries, Inc., all rights...
err...  reserved and offered to the public under the terms of the
Python 2.2 license.
Author: Zooko O'Whielacronx
http://zooko.com/
mailto:zooko@zooko.com

Copyright 2000, Mojam Media, Inc., all rights reserved.
Author: Skip Montanaro

Copyright 1999, Bioreason, Inc., all rights reserved.
Author: Andrew Dalke

Copyright 1995-1997, Automatrix, Inc., all rights reserved.
Author: Skip Montanaro

Copyright 1991-1995, Stichting Mathematisch Centrum, all rights reserved.

Permission to use, copy, modify, and distribute this Python software and
its associated documentation for any purpose without fee is hereby
granted, provided that the above copyright notice appears in all copies,
and that both that copyright notice and this permission notice appear in
supporting documentation, and that the name of neither Automatrix,
Bioreason or Mojam Media be used in advertising or publicity pertaining to
distribution of the software without specific, written prior permission.

UUencode 및 UUdecode 함수

uu 모듈은 다음과 같은 주의 사항을 포함합니다:

Copyright 1994 by Lance Ellinghouse
Cathedral City, California Republic, United States of America.
                       All Rights Reserved
Permission to use, copy, modify, and distribute this software and its
documentation for any purpose and without fee is hereby granted,
provided that the above copyright notice appear in all copies and that
both that copyright notice and this permission notice appear in
supporting documentation, and that the name of Lance Ellinghouse
not be used in advertising or publicity pertaining to distribution
of the software without specific, written prior permission.
LANCE ELLINGHOUSE DISCLAIMS ALL WARRANTIES WITH REGARD TO
THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS, IN NO EVENT SHALL LANCE ELLINGHOUSE CENTRUM BE LIABLE
FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

Modified by Jack Jansen, CWI, July 1995:
- Use binascii module to do the actual line-by-line conversion
  between ascii and binary. This results in a 1000-fold speedup. The C
  version is still 5 times faster, though.
- Arguments more compliant with Python standard

XML 원격 프로시저 호출

xmlrpc.client 모듈은 다음과 같은 주의 사항을 포함합니다:

    The XML-RPC client interface is

Copyright (c) 1999-2002 by Secret Labs AB
Copyright (c) 1999-2002 by Fredrik Lundh

By obtaining, using, and/or copying this software and/or its
associated documentation, you agree that you have read, understood,
and will comply with the following terms and conditions:

Permission to use, copy, modify, and distribute this software and
its associated documentation for any purpose and without fee is
hereby granted, provided that the above copyright notice appears in
all copies, and that both that copyright notice and this permission
notice appear in supporting documentation, and that the name of
Secret Labs AB or the author not be used in advertising or publicity
pertaining to distribution of the software without specific, written
prior permission.

SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT-
ABILITY AND FITNESS.  IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR
BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY
DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
OF THIS SOFTWARE.

test_epoll

test_epoll 모듈은 다음과 같은 주의 사항을 포함합니다:

Copyright (c) 2001-2006 Twisted Matrix Laboratories.

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Select kqueue

select 모듈은 kqueue 인터페이스에 대해 다음과 같은 주의 사항을 포함합니다:

Copyright (c) 2000 Doug White, 2006 James Knight, 2007 Christian Heimes
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.

SipHash24

파일 Python/pyhash.c 에는 Dan Bernstein의 SipHash24 알고리즘의 Marek Majkowski의 구현이 포함되어 있습니다. 여기에는 다음과 같은 내용이 포함되어 있습니다:

<MIT License>
Copyright (c) 2013  Marek Majkowski <marek@popcount.org>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
</MIT License>

Original location:
   https://github.com/majek/csiphash/

Solution inspired by code from:
   Samuel Neves (supercop/crypto_auth/siphash24/little)
   djb (supercop/crypto_auth/siphash24/little2)
   Jean-Philippe Aumasson (https://131002.net/siphash/siphash24.c)

strtod 와 dtoa

C double과 문자열 간의 변환을 위한 C 함수 dtoa 와 strtod 를 제공하는 파일 Python/dtoa.c 는 현재 http://www.netlib.org/fp/ 에서 얻을 수 있는 David M. Gay의 같은 이름의 파일에서 파생되었습니다. 2009년 3월 16일에 받은 원본 파일에는 다음과 같은 저작권 및 라이센스 공지가 포함되어 있습니다:

/****************************************************************
 *
 * The author of this software is David M. Gay.
 *
 * Copyright (c) 1991, 2000, 2001 by Lucent Technologies.
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose without fee is hereby granted, provided that this entire notice
 * is included in all copies of any software which is or includes a copy
 * or modification of this software and in all copies of the supporting
 * documentation for such software.
 *
 * THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR IMPLIED
 * WARRANTY.  IN PARTICULAR, NEITHER THE AUTHOR NOR LUCENT MAKES ANY
 * REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE MERCHANTABILITY
 * OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR PURPOSE.
 *
 ***************************************************************/

OpenSSL

모듈 hashlib, posix, ssl, crypt 는 운영 체제가 사용할 수 있게 하면 추가의 성능을 위해 OpenSSL 라이브러리를 사용합니다. 또한, 윈도우와 맥 OS X 파이썬 설치 프로그램은 OpenSSL 라이브러리 사본을 포함할 수 있으므로, 여기에 OpenSSL 라이센스 사본을 포함합니다:

 LICENSE ISSUES
 ==============

 The OpenSSL toolkit stays under a dual license, i.e. both the conditions of
 the OpenSSL License and the original SSLeay license apply to the toolkit.
 See below for the actual license texts. Actually both licenses are BSD-style
 Open Source licenses. In case of any license issues related to OpenSSL
 please contact openssl-core@openssl.org.

 OpenSSL License
 ---------------

   /* ====================================================================
    * Copyright (c) 1998-2008 The OpenSSL Project.  All rights reserved.
    *
    * Redistribution and use in source and binary forms, with or without
    * modification, are permitted provided that the following conditions
    * are met:
    *
    * 1. Redistributions of source code must retain the above copyright
    *    notice, this list of conditions and the following disclaimer.
    *
    * 2. Redistributions in binary form must reproduce the above copyright
    *    notice, this list of conditions and the following disclaimer in
    *    the documentation and/or other materials provided with the
    *    distribution.
    *
    * 3. All advertising materials mentioning features or use of this
    *    software must display the following acknowledgment:
    *    "This product includes software developed by the OpenSSL Project
    *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
    *
    * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
    *    endorse or promote products derived from this software without
    *    prior written permission. For written permission, please contact
    *    openssl-core@openssl.org.
    *
    * 5. Products derived from this software may not be called "OpenSSL"
    *    nor may "OpenSSL" appear in their names without prior written
    *    permission of the OpenSSL Project.
    *
    * 6. Redistributions of any form whatsoever must retain the following
    *    acknowledgment:
    *    "This product includes software developed by the OpenSSL Project
    *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
    *
    * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
    * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
    * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
    * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
    * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
    * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
    * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
    * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
    * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
    * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
    * OF THE POSSIBILITY OF SUCH DAMAGE.
    * ====================================================================
    *
    * This product includes cryptographic software written by Eric Young
    * (eay@cryptsoft.com).  This product includes software written by Tim
    * Hudson (tjh@cryptsoft.com).
    *
    */

Original SSLeay License
-----------------------

   /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
    * All rights reserved.
    *
    * This package is an SSL implementation written
    * by Eric Young (eay@cryptsoft.com).
    * The implementation was written so as to conform with Netscapes SSL.
    *
    * This library is free for commercial and non-commercial use as long as
    * the following conditions are aheared to.  The following conditions
    * apply to all code found in this distribution, be it the RC4, RSA,
    * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
    * included with this distribution is covered by the same copyright terms
    * except that the holder is Tim Hudson (tjh@cryptsoft.com).
    *
    * Copyright remains Eric Young's, and as such any Copyright notices in
    * the code are not to be removed.
    * If this package is used in a product, Eric Young should be given attribution
    * as the author of the parts of the library used.
    * This can be in the form of a textual message at program startup or
    * in documentation (online or textual) provided with the package.
    *
    * Redistribution and use in source and binary forms, with or without
    * modification, are permitted provided that the following conditions
    * are met:
    * 1. Redistributions of source code must retain the copyright
    *    notice, this list of conditions and the following disclaimer.
    * 2. Redistributions in binary form must reproduce the above copyright
    *    notice, this list of conditions and the following disclaimer in the
    *    documentation and/or other materials provided with the distribution.
    * 3. All advertising materials mentioning features or use of this software
    *    must display the following acknowledgement:
    *    "This product includes cryptographic software written by
    *     Eric Young (eay@cryptsoft.com)"
    *    The word 'cryptographic' can be left out if the rouines from the library
    *    being used are not cryptographic related :-).
    * 4. If you include any Windows specific code (or a derivative thereof) from
    *    the apps directory (application code) you must include an acknowledgement:
    *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
    *
    * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
    * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
    * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
    * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
    * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
    * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
    * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
    * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
    * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
    * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
    * SUCH DAMAGE.
    *
    * The licence and distribution terms for any publically available version or
    * derivative of this code cannot be changed.  i.e. this code cannot simply be
    * copied and put under another distribution licence
    * [including the GNU Public Licence.]
    */

expat

pyexpat 확장은 빌드를 --with-system-expat 로 구성하지 않는 한, 포함된 expat 소스 사본을 사용하여 빌드됩니다:

Copyright (c) 1998, 1999, 2000 Thai Open Source Software Center Ltd
                               and Clark Cooper

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

libffi

_ctypes 확장은 빌드를 --with-system-libffi 로 구성하지 않는 한, 포함된 libffi 소스 사본을 사용하여 빌드됩니다:

Copyright (c) 1996-2008  Red Hat, Inc and others.

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
``Software''), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.

zlib

zlib 확장은 시스템에서 발견된 zlib 버전이 너무 오래되어서 빌드에 사용될 수 없으면, 포함된 zlib 소스 사본을 사용하여 빌드됩니다:

Copyright (C) 1995-2011 Jean-loup Gailly and Mark Adler

This software is provided 'as-is', without any express or implied
warranty.  In no event will the authors be held liable for any damages
arising from the use of this software.

Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:

1. The origin of this software must not be misrepresented; you must not
   claim that you wrote the original software. If you use this software
   in a product, an acknowledgment in the product documentation would be
   appreciated but is not required.

2. Altered source versions must be plainly marked as such, and must not be
   misrepresented as being the original software.

3. This notice may not be removed or altered from any source distribution.

Jean-loup Gailly        Mark Adler
jloup@gzip.org          madler@alumni.caltech.edu

cfuhash

tracemalloc 에 의해 사용되는 해시 테이블의 구현은 cfuhash 프로젝트를 기반으로 합니다:

Copyright (c) 2005 Don Owens
All rights reserved.

This code is released under the BSD license:

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

  * Redistributions of source code must retain the above copyright
    notice, this list of conditions and the following disclaimer.

  * Redistributions in binary form must reproduce the above
    copyright notice, this list of conditions and the following
    disclaimer in the documentation and/or other materials provided
    with the distribution.

  * Neither the name of the author nor the names of its
    contributors may be used to endorse or promote products derived
    from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
OF THE POSSIBILITY OF SUCH DAMAGE.

libmpdec

_decimal 모듈은 빌드를 --with-system-libmpdec 로 구성하지 않는 한, 포함된 libmpdec 소스 사본을 사용하여 빌드됩니다:

Copyright (c) 2008-2016 Stefan Krah. All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

1. Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

|

파이썬 모듈 배포 (레거시 버전)

저자

Greg Ward, Anthony Baxter

이메일

distutils-sig@python.org

더 보기

파이썬 모듈 배포하기

최신 모듈 배포 설명서

이 문서는 모듈 개발자의 관점에서 파이썬 배포 유틸리티(“Distutils”)를 설명합니다. Distutils를 사용하여 파이썬 모듈과 확장을 빌드/릴리스/설치 절차에 대한 오버헤드 없이 광범위한 사용자가 쉽게 사용할 수 있도록 하는 방법을 설명합니다.

참고

이 지침서는 이 파이썬 버전 일부로 제공되는 확장을 빌드하고 배포하기 위한 기본 도구만을 다루고 있습니다. 제삼자 도구는 사용하기 더 쉽고 더 안전한 대안을 제공합니다. 자세한 정보는 파이썬 패키징 사용자 지침서의 빠른 추천 섹션 [https://packaging.python.org/guides/tool-recommendations/]을 참조하십시오.

1. An Introduction to Distutils

1.1. Concepts & Terminology

1.2. A Simple Example

1.3. General Python terminology

1.4. Distutils-specific terminology

2. Writing the Setup Script

2.1. Listing whole packages

2.2. Listing individual modules

2.3. Describing extension modules

2.4. Relationships between Distributions and Packages

2.5. Installing Scripts

2.6. Installing Package Data

2.7. Installing Additional Files

2.8. Additional meta-data

2.9. Debugging the setup script

3. 설치 구성 파일 작성하기

4. Creating a Source Distribution

4.1. Specifying the files to distribute

4.2. Manifest-related options

5. Creating Built Distributions

5.1. Creating RPM packages

5.2. Creating Windows Installers

5.3. Cross-compiling on Windows

5.4. Vista User Access Control (UAC)

6. Examples

6.1. Pure Python distribution (by module)

6.2. Pure Python distribution (by package)

6.3. Single extension module

6.4. Checking a package

6.5. Reading the metadata

7. Distutils 확장하기

7.1. 새 명령 통합하기

7.2. 새 배포 유형 추가하기

8. 명령 레퍼런스

8.1. 모듈 설치하기: install 명령 군

8.2. 소스 배포 만들기: sdist 명령

9. API Reference

9.1. distutils.core — Core Distutils functionality

9.2. distutils.ccompiler — CCompiler base class

9.3. distutils.unixccompiler — Unix C Compiler

9.4. distutils.msvccompiler — Microsoft Compiler

9.5. distutils.bcppcompiler — Borland Compiler

9.6. distutils.cygwincompiler — Cygwin Compiler

9.7. distutils.archive_util — Archiving utilities

9.8. distutils.dep_util — Dependency checking

9.9. distutils.dir_util — Directory tree operations

9.10. distutils.file_util — Single file operations

9.11. distutils.util — Miscellaneous other utility functions

9.12. distutils.dist — The Distribution class

9.13. distutils.extension — The Extension class

9.14. distutils.debug — Distutils debug mode

9.15. distutils.errors — Distutils exceptions

9.16. distutils.fancy_getopt — Wrapper around the standard getopt module

9.17. distutils.filelist — The FileList class

9.18. distutils.log — Simple PEP 282-style logging

9.19. distutils.spawn — Spawn a sub-process

9.20. distutils.sysconfig — System configuration information

9.21. distutils.text_file — The TextFile class

9.22. distutils.version — Version number classes

9.23. distutils.cmd — Abstract base class for Distutils commands

9.24. Creating a new Distutils command

9.25. distutils.command — Individual Distutils commands

9.26. distutils.command.bdist — Build a binary installer

9.27. distutils.command.bdist_packager — Abstract base class for packagers

9.28. distutils.command.bdist_dumb — Build a “dumb” installer

9.29. distutils.command.bdist_msi — Build a Microsoft Installer binary package

9.30. distutils.command.bdist_rpm — Build a binary distribution as a Redhat RPM and SRPM

9.31. distutils.command.bdist_wininst — Build a Windows installer

9.32. distutils.command.sdist — Build a source distribution

9.33. distutils.command.build — Build all files of a package

9.34. distutils.command.build_clib — Build any C libraries in a package

9.35. distutils.command.build_ext — Build any extensions in a package

9.36. distutils.command.build_py — Build the .py/.pyc files of a package

9.37. distutils.command.build_scripts — Build the scripts of a package

9.38. distutils.command.clean — Clean a package build area

9.39. distutils.command.config — Perform package configuration

9.40. distutils.command.install — Install a package

9.41. distutils.command.install_data — Install data files from a package

9.42. distutils.command.install_headers — Install C/C++ header files from a package

9.43. distutils.command.install_lib — Install library files from a package

9.44. distutils.command.install_scripts — Install script files from a package

9.45. distutils.command.register — Register a module with the Python Package Index

9.46. distutils.command.check — Check the meta-data of a package

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 모듈 배포 (레거시 버전) »

|

1. An Introduction to Distutils

This document covers using the Distutils to distribute your Python modules, concentrating on the role of developer/distributor: if you’re looking for information on installing Python modules, you should refer to the 파이썬 모듈 설치 (레거시 버전) chapter.

1.1. Concepts & Terminology

Using the Distutils is quite simple, both for module developers and for users/administrators installing third-party modules. As a developer, your responsibilities (apart from writing solid, well-documented and well-tested code, of course!) are:

write a setup script (setup.py by convention)

(optional) write a setup configuration file

create a source distribution

(optional) create one or more built (binary) distributions

Each of these tasks is covered in this document.

Not all module developers have access to a multitude of platforms, so it’s not always feasible to expect them to create a multitude of built distributions. It is hoped that a class of intermediaries, called packagers, will arise to address this need. Packagers will take source distributions released by module developers, build them on one or more platforms, and release the resulting built distributions. Thus, users on the most popular platforms will be able to install most popular Python module distributions in the most natural way for their platform, without having to run a single setup script or compile a line of code.

1.2. A Simple Example

The setup script is usually quite simple, although since it’s written in Python, there are no arbitrary limits to what you can do with it, though you should be careful about putting arbitrarily expensive operations in your setup script. Unlike, say, Autoconf-style configure scripts, the setup script may be run multiple times in the course of building and installing your module distribution.

If all you want to do is distribute a module called foo, contained in a file foo.py, then your setup script can be as simple as this:

from distutils.core import setup
setup(name='foo',
      version='1.0',
      py_modules=['foo'],
      )

Some observations:

most information that you supply to the Distutils is supplied as keyword arguments to the setup() function

those keyword arguments fall into two categories: package metadata (name, version number) and information about what’s in the package (a list of pure Python modules, in this case)

modules are specified by module name, not filename (the same will hold true for packages and extensions)

it’s recommended that you supply a little more metadata, in particular your name, email address and a URL for the project (see section Writing the Setup Script for an example)

To create a source distribution for this module, you would create a setup script, setup.py, containing the above code, and run this command from a terminal:

python setup.py sdist

For Windows, open a command prompt window (Start ‣ Accessories) and change the command to:

setup.py sdist

sdist will create an archive file (e.g., tarball on Unix, ZIP file on Windows) containing your setup script setup.py, and your module foo.py. The archive file will be named foo-1.0.tar.gz (or .zip), and will unpack into a directory foo-1.0.

If an end-user wishes to install your foo module, all they have to do is download foo-1.0.tar.gz (or .zip), unpack it, and—from the foo-1.0 directory—run

python setup.py install

which will ultimately copy foo.py to the appropriate directory for third-party modules in their Python installation.

This simple example demonstrates some fundamental concepts of the Distutils. First, both developers and installers have the same basic user interface, i.e. the setup script. The difference is which Distutils commands they use: the sdist command is almost exclusively for module developers, while install is more often for installers (although most developers will want to install their own code occasionally).

If you want to make things really easy for your users, you can create one or more built distributions for them. For instance, if you are running on a Windows machine, and want to make things easy for other Windows users, you can create an executable installer (the most appropriate type of built distribution for this platform) with the bdist_wininst command. For example:

python setup.py bdist_wininst

will create an executable installer, foo-1.0.win32.exe, in the current directory.

Other useful built distribution formats are RPM, implemented by the bdist_rpm command, Solaris pkgtool (bdist_pkgtool), and HP-UX swinstall (bdist_sdux). For example, the following command will create an RPM file called foo-1.0.noarch.rpm:

python setup.py bdist_rpm

(The bdist_rpm command uses the rpm executable, therefore this has to be run on an RPM-based system such as Red Hat Linux, SuSE Linux, or Mandrake Linux.)

You can find out what distribution formats are available at any time by running

python setup.py bdist --help-formats

1.3. General Python terminology

If you’re reading this document, you probably have a good idea of what modules, extensions, and so forth are. Nevertheless, just to be sure that everyone is operating from a common starting point, we offer the following glossary of common Python terms:

module

the basic unit of code reusability in Python: a block of code imported by some other code. Three types of modules concern us here: pure Python modules, extension modules, and packages.

pure Python module

a module written in Python and contained in a single .py file (and possibly associated .pyc files). Sometimes referred to as a “pure module.”

extension module

a module written in the low-level language of the Python implementation: C/C++ for Python, Java for Jython. Typically contained in a single dynamically loadable pre-compiled file, e.g. a shared object (.so) file for Python extensions on Unix, a DLL (given the .pyd extension) for Python extensions on Windows, or a Java class file for Jython extensions. (Note that currently, the Distutils only handles C/C++ extensions for Python.)

package

a module that contains other modules; typically contained in a directory in the filesystem and distinguished from other directories by the presence of a file __init__.py.

root package

the root of the hierarchy of packages. (This isn’t really a package, since it doesn’t have an __init__.py file. But we have to call it something.) The vast majority of the standard library is in the root package, as are many small, standalone third-party modules that don’t belong to a larger module collection. Unlike regular packages, modules in the root package can be found in many directories: in fact, every directory listed in sys.path contributes modules to the root package.

1.4. Distutils-specific terminology

The following terms apply more specifically to the domain of distributing Python modules using the Distutils:

module distribution

a collection of Python modules distributed together as a single downloadable resource and meant to be installed en masse. Examples of some well-known module distributions are NumPy, SciPy, Pillow, or mxBase. (This would be called a package, except that term is already taken in the Python context: a single module distribution may contain zero, one, or many Python packages.)

pure module distribution

a module distribution that contains only pure Python modules and packages. Sometimes referred to as a “pure distribution.”

non-pure module distribution

a module distribution that contains at least one extension module. Sometimes referred to as a “non-pure distribution.”

distribution root

the top-level directory of your source tree (or source distribution); the directory where setup.py exists. Generally setup.py will be run from this directory.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 모듈 배포 (레거시 버전) »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 모듈 배포 (레거시 버전) »

|

2. Writing the Setup Script

The setup script is the centre of all activity in building, distributing, and installing modules using the Distutils. The main purpose of the setup script is to describe your module distribution to the Distutils, so that the various commands that operate on your modules do the right thing. As we saw in section A Simple Example above, the setup script consists mainly of a call to setup(), and most information supplied to the Distutils by the module developer is supplied as keyword arguments to setup().

Here’s a slightly more involved example, which we’ll follow for the next couple of sections: the Distutils’ own setup script. (Keep in mind that although the Distutils are included with Python 1.6 and later, they also have an independent existence so that Python 1.5.2 users can use them to install other module distributions. The Distutils’ own setup script, shown here, is used to install the package into Python 1.5.2.)

#!/usr/bin/env python

from distutils.core import setup

setup(name='Distutils',
      version='1.0',
      description='Python Distribution Utilities',
      author='Greg Ward',
      author_email='gward@python.net',
      url='https://www.python.org/sigs/distutils-sig/',
      packages=['distutils', 'distutils.command'],
     )

There are only two differences between this and the trivial one-file distribution presented in section A Simple Example: more metadata, and the specification of pure Python modules by package, rather than by module. This is important since the Distutils consist of a couple of dozen modules split into (so far) two packages; an explicit list of every module would be tedious to generate and difficult to maintain. For more information on the additional meta-data, see section Additional meta-data.

Note that any pathnames (files or directories) supplied in the setup script should be written using the Unix convention, i.e. slash-separated. The Distutils will take care of converting this platform-neutral representation into whatever is appropriate on your current platform before actually using the pathname. This makes your setup script portable across operating systems, which of course is one of the major goals of the Distutils. In this spirit, all pathnames in this document are slash-separated.

This, of course, only applies to pathnames given to Distutils functions. If you, for example, use standard Python functions such as glob.glob() or os.listdir() to specify files, you should be careful to write portable code instead of hardcoding path separators:

glob.glob(os.path.join('mydir', 'subdir', '*.html'))
os.listdir(os.path.join('mydir', 'subdir'))

2.1. Listing whole packages

The packages option tells the Distutils to process (build, distribute, install, etc.) all pure Python modules found in each package mentioned in the packages list. In order to do this, of course, there has to be a correspondence between package names and directories in the filesystem. The default correspondence is the most obvious one, i.e. package distutils is found in the directory distutils relative to the distribution root. Thus, when you say packages = ['foo'] in your setup script, you are promising that the Distutils will find a file foo/__init__.py (which might be spelled differently on your system, but you get the idea) relative to the directory where your setup script lives. If you break this promise, the Distutils will issue a warning but still process the broken package anyway.

If you use a different convention to lay out your source directory, that’s no problem: you just have to supply the package_dir option to tell the Distutils about your convention. For example, say you keep all Python source under lib, so that modules in the “root package” (i.e., not in any package at all) are in lib, modules in the foo package are in lib/foo, and so forth. Then you would put

package_dir = {'': 'lib'}

in your setup script. The keys to this dictionary are package names, and an empty package name stands for the root package. The values are directory names relative to your distribution root. In this case, when you say packages = ['foo'], you are promising that the file lib/foo/__init__.py exists.

Another possible convention is to put the foo package right in lib, the foo.bar package in lib/bar, etc. This would be written in the setup script as

package_dir = {'foo': 'lib'}

A package: dir entry in the package_dir dictionary implicitly applies to all packages below package, so the foo.bar case is automatically handled here. In this example, having packages = ['foo', 'foo.bar'] tells the Distutils to look for lib/__init__.py and lib/bar/__init__.py. (Keep in mind that although package_dir applies recursively, you must explicitly list all packages in packages: the Distutils will not recursively scan your source tree looking for any directory with an __init__.py file.)

2.2. Listing individual modules

For a small module distribution, you might prefer to list all modules rather than listing packages—especially the case of a single module that goes in the “root package” (i.e., no package at all). This simplest case was shown in section A Simple Example; here is a slightly more involved example:

py_modules = ['mod1', 'pkg.mod2']

This describes two modules, one of them in the “root” package, the other in the pkg package. Again, the default package/directory layout implies that these two modules can be found in mod1.py and pkg/mod2.py, and that pkg/__init__.py exists as well. And again, you can override the package/directory correspondence using the package_dir option.

2.3. Describing extension modules

Just as writing Python extension modules is a bit more complicated than writing pure Python modules, describing them to the Distutils is a bit more complicated. Unlike pure modules, it’s not enough just to list modules or packages and expect the Distutils to go out and find the right files; you have to specify the extension name, source file(s), and any compile/link requirements (include directories, libraries to link with, etc.).

All of this is done through another keyword argument to setup(), the ext_modules option. ext_modules is just a list of Extension instances, each of which describes a single extension module. Suppose your distribution includes a single extension, called foo and implemented by foo.c. If no additional instructions to the compiler/linker are needed, describing this extension is quite simple:

Extension('foo', ['foo.c'])

The Extension class can be imported from distutils.core along with setup(). Thus, the setup script for a module distribution that contains only this one extension and nothing else might be:

from distutils.core import setup, Extension
setup(name='foo',
      version='1.0',
      ext_modules=[Extension('foo', ['foo.c'])],
      )

The Extension class (actually, the underlying extension-building machinery implemented by the build_ext command) supports a great deal of flexibility in describing Python extensions, which is explained in the following sections.

2.3.1. Extension names and packages

The first argument to the Extension constructor is always the name of the extension, including any package names. For example,

Extension('foo', ['src/foo1.c', 'src/foo2.c'])

describes an extension that lives in the root package, while

Extension('pkg.foo', ['src/foo1.c', 'src/foo2.c'])

describes the same extension in the pkg package. The source files and resulting object code are identical in both cases; the only difference is where in the filesystem (and therefore where in Python’s namespace hierarchy) the resulting extension lives.

If you have a number of extensions all in the same package (or all under the same base package), use the ext_package keyword argument to setup(). For example,

setup(...,
      ext_package='pkg',
      ext_modules=[Extension('foo', ['foo.c']),
                   Extension('subpkg.bar', ['bar.c'])],
     )

will compile foo.c to the extension pkg.foo, and bar.c to pkg.subpkg.bar.

2.3.2. Extension source files

The second argument to the Extension constructor is a list of source files. Since the Distutils currently only support C, C++, and Objective-C extensions, these are normally C/C++/Objective-C source files. (Be sure to use appropriate extensions to distinguish C++ source files: .cc and .cpp seem to be recognized by both Unix and Windows compilers.)

However, you can also include SWIG interface (.i) files in the list; the build_ext command knows how to deal with SWIG extensions: it will run SWIG on the interface file and compile the resulting C/C++ file into your extension.

This warning notwithstanding, options to SWIG can be currently passed like this:

setup(...,
      ext_modules=[Extension('_foo', ['foo.i'],
                             swig_opts=['-modern', '-I../include'])],
      py_modules=['foo'],
     )

Or on the commandline like this:

> python setup.py build_ext --swig-opts="-modern -I../include"

On some platforms, you can include non-source files that are processed by the compiler and included in your extension. Currently, this just means Windows message text (.mc) files and resource definition (.rc) files for Visual C++. These will be compiled to binary resource (.res) files and linked into the executable.

2.3.3. Preprocessor options

Three optional arguments to Extension will help if you need to specify include directories to search or preprocessor macros to define/undefine: include_dirs, define_macros, and undef_macros.

For example, if your extension requires header files in the include directory under your distribution root, use the include_dirs option:

Extension('foo', ['foo.c'], include_dirs=['include'])

You can specify absolute directories there; if you know that your extension will only be built on Unix systems with X11R6 installed to /usr, you can get away with

Extension('foo', ['foo.c'], include_dirs=['/usr/include/X11'])

You should avoid this sort of non-portable usage if you plan to distribute your code: it’s probably better to write C code like

#include <X11/Xlib.h>

If you need to include header files from some other Python extension, you can take advantage of the fact that header files are installed in a consistent way by the Distutils install_headers command. For example, the Numerical Python header files are installed (on a standard Unix installation) to /usr/local/include/python1.5/Numerical. (The exact location will differ according to your platform and Python installation.) Since the Python include directory—/usr/local/include/python1.5 in this case—is always included in the search path when building Python extensions, the best approach is to write C code like

#include <Numerical/arrayobject.h>

If you must put the Numerical include directory right into your header search path, though, you can find that directory using the Distutils distutils.sysconfig module:

from distutils.sysconfig import get_python_inc
incdir = os.path.join(get_python_inc(plat_specific=1), 'Numerical')
setup(...,
      Extension(..., include_dirs=[incdir]),
      )

Even though this is quite portable—it will work on any Python installation, regardless of platform—it’s probably easier to just write your C code in the sensible way.

You can define and undefine pre-processor macros with the define_macros and undef_macros options. define_macros takes a list of (name, value) tuples, where name is the name of the macro to define (a string) and value is its value: either a string or None. (Defining a macro FOO to None is the equivalent of a bare #define FOO in your C source: with most compilers, this sets FOO to the string 1.) undef_macros is just a list of macros to undefine.

For example:

Extension(...,
          define_macros=[('NDEBUG', '1'),
                         ('HAVE_STRFTIME', None)],
          undef_macros=['HAVE_FOO', 'HAVE_BAR'])

is the equivalent of having this at the top of every C source file:

#define NDEBUG 1
#define HAVE_STRFTIME
#undef HAVE_FOO
#undef HAVE_BAR

2.3.4. Library options

You can also specify the libraries to link against when building your extension, and the directories to search for those libraries. The libraries option is a list of libraries to link against, library_dirs is a list of directories to search for libraries at link-time, and runtime_library_dirs is a list of directories to search for shared (dynamically loaded) libraries at run-time.

For example, if you need to link against libraries known to be in the standard library search path on target systems

Extension(...,
          libraries=['gdbm', 'readline'])

If you need to link with libraries in a non-standard location, you’ll have to include the location in library_dirs:

Extension(...,
          library_dirs=['/usr/X11R6/lib'],
          libraries=['X11', 'Xt'])

(Again, this sort of non-portable construct should be avoided if you intend to distribute your code.)

2.3.5. Other options

There are still some other options which can be used to handle special cases.

The optional option is a boolean; if it is true, a build failure in the extension will not abort the build process, but instead simply not install the failing extension.

The extra_objects option is a list of object files to be passed to the linker. These files must not have extensions, as the default extension for the compiler is used.

extra_compile_args and extra_link_args can be used to specify additional command line options for the respective compiler and linker command lines.

export_symbols is only useful on Windows. It can contain a list of symbols (functions or variables) to be exported. This option is not needed when building compiled extensions: Distutils will automatically add initmodule to the list of exported symbols.

The depends option is a list of files that the extension depends on (for example header files). The build command will call the compiler on the sources to rebuild extension if any on this files has been modified since the previous build.

2.4. Relationships between Distributions and Packages

A distribution may relate to packages in three specific ways:

It can require packages or modules.

It can provide packages or modules.

It can obsolete packages or modules.

These relationships can be specified using keyword arguments to the distutils.core.setup() function.

Dependencies on other Python modules and packages can be specified by supplying the requires keyword argument to setup(). The value must be a list of strings. Each string specifies a package that is required, and optionally what versions are sufficient.

To specify that any version of a module or package is required, the string should consist entirely of the module or package name. Examples include 'mymodule' and 'xml.parsers.expat'.

If specific versions are required, a sequence of qualifiers can be supplied in parentheses. Each qualifier may consist of a comparison operator and a version number. The accepted comparison operators are:

<    >    ==
<=   >=   !=

These can be combined by using multiple qualifiers separated by commas (and optional whitespace). In this case, all of the qualifiers must be matched; a logical AND is used to combine the evaluations.

Let’s look at a bunch of examples:

Requires Expression

Explanation

==1.0

Only version 1.0 is compatible

>1.0, !=1.5.1, <2.0

Any version after 1.0 and before 2.0 is compatible, except 1.5.1

Now that we can specify dependencies, we also need to be able to specify what we provide that other distributions can require. This is done using the provides keyword argument to setup(). The value for this keyword is a list of strings, each of which names a Python module or package, and optionally identifies the version. If the version is not specified, it is assumed to match that of the distribution.

Some examples:

Provides Expression

Explanation

mypkg

Provide mypkg, using the distribution version

mypkg (1.1)

Provide mypkg version 1.1, regardless of the distribution version

A package can declare that it obsoletes other packages using the obsoletes keyword argument. The value for this is similar to that of the requires keyword: a list of strings giving module or package specifiers. Each specifier consists of a module or package name optionally followed by one or more version qualifiers. Version qualifiers are given in parentheses after the module or package name.

The versions identified by the qualifiers are those that are obsoleted by the distribution being described. If no qualifiers are given, all versions of the named module or package are understood to be obsoleted.

2.5. Installing Scripts

So far we have been dealing with pure and non-pure Python modules, which are usually not run by themselves but imported by scripts.

Scripts are files containing Python source code, intended to be started from the command line. Scripts don’t require Distutils to do anything very complicated. The only clever feature is that if the first line of the script starts with #! and contains the word “python”, the Distutils will adjust the first line to refer to the current interpreter location. By default, it is replaced with the current interpreter location. The --executable (or -e) option will allow the interpreter path to be explicitly overridden.

The scripts option simply is a list of files to be handled in this way. From the PyXML setup script:

setup(...,
      scripts=['scripts/xmlproc_parse', 'scripts/xmlproc_val']
      )

버전 3.1에서 변경: All the scripts will also be added to the MANIFEST file if no template is provided. See Specifying the files to distribute.

2.6. Installing Package Data

Often, additional files need to be installed into a package. These files are often data that’s closely related to the package’s implementation, or text files containing documentation that might be of interest to programmers using the package. These files are called package data.

Package data can be added to packages using the package_data keyword argument to the setup() function. The value must be a mapping from package name to a list of relative path names that should be copied into the package. The paths are interpreted as relative to the directory containing the package (information from the package_dir mapping is used if appropriate); that is, the files are expected to be part of the package in the source directories. They may contain glob patterns as well.

The path names may contain directory portions; any necessary directories will be created in the installation.

For example, if a package should contain a subdirectory with several data files, the files can be arranged like this in the source tree:

setup.py
src/
    mypkg/
        __init__.py
        module.py
        data/
            tables.dat
            spoons.dat
            forks.dat

The corresponding call to setup() might be:

setup(...,
      packages=['mypkg'],
      package_dir={'mypkg': 'src/mypkg'},
      package_data={'mypkg': ['data/*.dat']},
      )

버전 3.1에서 변경: All the files that match package_data will be added to the MANIFEST file if no template is provided. See Specifying the files to distribute.

2.7. Installing Additional Files

The data_files option can be used to specify additional files needed by the module distribution: configuration files, message catalogs, data files, anything which doesn’t fit in the previous categories.

data_files specifies a sequence of (directory, files) pairs in the following way:

setup(...,
      data_files=[('bitmaps', ['bm/b1.gif', 'bm/b2.gif']),
                  ('config', ['cfg/data.cfg'])],
     )

Each (directory, files) pair in the sequence specifies the installation directory and the files to install there.

Each file name in files is interpreted relative to the setup.py script at the top of the package source distribution. Note that you can specify the directory where the data files will be installed, but you cannot rename the data files themselves.

The directory should be a relative path. It is interpreted relative to the installation prefix (Python’s sys.prefix for system installations; site.USER_BASE for user installations). Distutils allows directory to be an absolute installation path, but this is discouraged since it is incompatible with the wheel packaging format. No directory information from files is used to determine the final location of the installed file; only the name of the file is used.

You can specify the data_files options as a simple sequence of files without specifying a target directory, but this is not recommended, and the install command will print a warning in this case. To install data files directly in the target directory, an empty string should be given as the directory.

버전 3.1에서 변경: All the files that match data_files will be added to the MANIFEST file if no template is provided. See Specifying the files to distribute.

2.8. Additional meta-data

The setup script may include additional meta-data beyond the name and version. This information includes:

Meta-Data

Description

Value

Notes

name

name of the package

short string

(1)

version

version of this release

short string

(1)(2)

author

package author’s name

short string

(3)

author_email

email address of the package author

email address

(3)

maintainer

package maintainer’s name

short string

(3)

maintainer_email

email address of the package maintainer

email address

(3)

url

home page for the package

URL

(1)

description

short, summary description of the package

short string

long_description

longer description of the package

long string

(4)

download_url

location where the package may be downloaded

URL

classifiers

a list of classifiers

list of strings

(6)(7)

platforms

a list of platforms

list of strings

(6)(8)

keywords

a list of keywords

list of strings

(6)(8)

license

license for the package

short string

(5)

Notes:

These fields are required.

It is recommended that versions take the form major.minor[.patch[.sub]].

Either the author or the maintainer must be identified. If maintainer is provided, distutils lists it as the author in PKG-INFO.

The long_description field is used by PyPI when you publish a package, to build its project page.

The license field is a text indicating the license covering the package where the license is not a selection from the “License” Trove classifiers. See the Classifier field. Notice that there’s a licence distribution option which is deprecated but still acts as an alias for license.

This field must be a list.

The valid classifiers are listed on PyPI [https://pypi.org/classifiers].

To preserve backward compatibility, this field also accepts a string. If you pass a comma-separated string 'foo, bar', it will be converted to ['foo', 'bar'], Otherwise, it will be converted to a list of one string.

‘short string’

A single line of text, not more than 200 characters.

‘long string’

Multiple lines of plain text in reStructuredText format (see http://docutils.sourceforge.net/).

‘list of strings’

See below.

Encoding the version information is an art in itself. Python packages generally adhere to the version format major.minor[.patch][sub]. The major number is 0 for initial, experimental releases of software. It is incremented for releases that represent major milestones in a package. The minor number is incremented when important new features are added to the package. The patch number increments when bug-fix releases are made. Additional trailing version information is sometimes used to indicate sub-releases. These are “a1,a2,…,aN” (for alpha releases, where functionality and API may change), “b1,b2,…,bN” (for beta releases, which only fix bugs) and “pr1,pr2,…,prN” (for final pre-release release testing). Some examples:

0.1.0

the first, experimental release of a package

1.0.1a2

the second alpha release of the first patch version of 1.0

classifiers must be specified in a list:

setup(...,
      classifiers=[
          'Development Status :: 4 - Beta',
          'Environment :: Console',
          'Environment :: Web Environment',
          'Intended Audience :: End Users/Desktop',
          'Intended Audience :: Developers',
          'Intended Audience :: System Administrators',
          'License :: OSI Approved :: Python Software Foundation License',
          'Operating System :: MacOS :: MacOS X',
          'Operating System :: Microsoft :: Windows',
          'Operating System :: POSIX',
          'Programming Language :: Python',
          'Topic :: Communications :: Email',
          'Topic :: Office/Business',
          'Topic :: Software Development :: Bug Tracking',
          ],
      )

버전 3.7에서 변경: setup now warns when classifiers, keywords or platforms fields are not specified as a list or a string.

2.9. Debugging the setup script

Sometimes things go wrong, and the setup script doesn’t do what the developer wants.

Distutils catches any exceptions when running the setup script, and print a simple error message before the script is terminated. The motivation for this behaviour is to not confuse administrators who don’t know much about Python and are trying to install a package. If they get a big long traceback from deep inside the guts of Distutils, they may think the package or the Python installation is broken because they don’t read all the way down to the bottom and see that it’s a permission problem.

On the other hand, this doesn’t help the developer to find the cause of the failure. For this purpose, the DISTUTILS_DEBUG environment variable can be set to anything except an empty string, and distutils will now print detailed information about what it is doing, dump the full traceback when an exception occurs, and print the whole command line when an external program (like a C compiler) fails.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 모듈 배포 (레거시 버전) »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 모듈 배포 (레거시 버전) »

|

3. 설치 구성 파일 작성하기

종종, 배포판을 빌드하는데 필요한 모든 것을 사전에 작성하는 것은 불가능합니다: 사용자나 시스템에서 정보를 얻어야 계속 진행할 수 있습니다. 그 정보가 매우 간단하다면 —예를 들어, C 헤더 파일이나 라이브러리를 검색할 디렉터리 목록— 사용자가 편집할 수 있는 구성 파일 setup.cfg를 제공하는 것은 저렴하고 쉬운 방법입니다. 구성 파일을 사용하면 모든 명령 옵션에 대한 기본값을 제공할 수도 있습니다. 이 옵션은 설치하는 사람이 명령 줄이나 구성 파일을 편집해서 재정의하도록 할 수 있습니다.

설치 구성 파일은 설치 스크립트(이상적으로는, 설치하는 사람에게 불투명한 1)와 설치 스크립트에 대한 명령 줄(여러분의 제어를 벗어나고 전적으로 설치하는 사람에 달려 있습니다) 사이의 유용한 중간 지대입니다. 사실, setup.cfg(와 대상 시스템에 있는 다른 모든 Distutils 구성 파일)는 설치 스크립트의 내용 뒤에, 하지만 명령 줄 앞에서 처리됩니다. 이것은 몇 가지 유용한 결과를 줍니다:

설치하는 사람은 setup.cfg를 편집하여 여러분이 setup.py에 넣은 것을 재정의할 수 있습니다.

여러분은 setup.py에서 쉽게 설정할 수 없는 옵션에 대해 비표준 기본값을 제공할 수 있습니다

설치하는 사람은 setup.py에 대한 명령 줄 옵션을 사용하여 setup.cfg의 모든 것을 재정의할 수 있습니다

구성 파일의 기본 문법은 간단합니다:

[command]
option=value
...

여기서 command는 Distutils 명령 (예를 들어, build_py, install) 중 하나이며, option은 명령이 지원하는 옵션 중 하나입니다. 각 명령에 대해 임의의 수의 옵션을 제공할 수 있으며, 임의의 수의 명령 섹션을 파일에 포함할 수 있습니다. '#' 문자에서 줄의 끝까지 확장되는 주석과 마찬가지로 공백 줄은 무시됩니다. 긴 옵션 값은 단순히 이어지는 줄을 들여쓰기하는 것으로 여러 줄로 나눌 수 있습니다.

범용 --help 옵션을 사용하여 특정 명령이 지원하는 옵션 목록을 찾을 수 있습니다, 예를 들어

$ python setup.py --help build_ext
[...]
Options for 'build_ext' command:
  --build-lib (-b)     directory for compiled extension modules
  --build-temp (-t)    directory for temporary files (build by-products)
  --inplace (-i)       ignore build-lib and put compiled extensions into the
                       source directory alongside your pure Python modules
  --include-dirs (-I)  list of directories to search for header files
  --define (-D)        C preprocessor macros to define
  --undef (-U)         C preprocessor macros to undefine
  --swig-opts          list of SWIG command line options
[...]

명령 줄에서 --foo-bar로 입력되는 옵션은 구성 파일에서 foo_bar로 표시해야 함에 유의하십시오.

예를 들어, 여러분의 확장을 “제자리(in-place)”에 빌드하려고 한다고 합시다 — 즉, 확장 pkg.ext이 있고, 컴파일된 확장 파일(유닉스에서 ext.so이라고 합시다)이 여러분의 순수 파이썬 모듈 pkg.mod1와 pkg.mod2과 같은 소스 디렉터리에 들어가기를 원합니다. 이렇게 하려면 항상 명령 줄에서 --inplace 옵션을 사용할 수 있습니다:

python setup.py build_ext --inplace

그러나 이렇게 하려면 항상 build_ext 명령을 명시적으로 지정하고, --inplace를 제공하는 것을 기억해야 합니다. 더 쉬운 방법은 이 배포판의 설정 파일인 setup.cfg에 인코딩하여, 이 옵션을 “설정하고 잊어버리는” 것입니다:

[build_ext]
inplace=1

이것은 build_ext를 명시적으로 지정했는지와 관계없이, 이 모듈 배포의 모든 빌드에 영향을 미칩니다. 소스 배포판에 setup.cfg를 포함 시키면, 최종 사용자 빌드에도 영향을 미칩니다 — 항상 제자리에서 확장을 빌드하면 모듈 배포 설치를 망가뜨릴 수 있으므로, 이 옵션의 경우는 나쁜 생각일 수 있습니다. 그러나 어떤 특별한 경우에는, 설치 디렉터리에 모듈이 바로 빌드되기 때문에 유용한 기능이라고 상상할 수 있습니다. (설치 디렉터리에 빌드 될 것으로 기대하는 확장을 배포하는 것은 거의 항상 나쁜 생각입니다.)

다른 예: 어떤 명령은 실행마다 변경되지는 않는 많은 옵션을 사용합니다; 예를 들어, bdist_rpm은 RPM 배포를 만들기 위해 “spec” 파일을 생성하는 데 필요한 모든 것을 알아야 합니다. 이 정보 중 일부는 설치 스크립트에서 오고, 일부는 Distutils가 자동으로 생성합니다 (가령 설치된 파일 목록). 그러나 그중 일부는 bdist_rpm에 대한 옵션으로 제공되어야 하는데, 실행 때마다 명령 줄에서 수행하는 것은 매우 따분합니다. 그래서, 여기 Distutils 자체의 setup.cfg에서 발췌한 내용이 있습니다:

[bdist_rpm]
release = 1
packager = Greg Ward <gward@python.net>
doc_files = CHANGES.txt
            README.txt
            USAGE.txt
            doc/
            examples/

doc_files 옵션은 가독성을 위해 여러 줄에 나누어 공백으로 구분된 문자열일 뿐임에 유의하십시오.

더 보기

“파이썬 모듈 설치”의 Syntax of config files

구성 파일에 대한 자세한 내용은 시스템 관리자용 설명서에 있습니다.

각주

1

이 이상은 아마도 자동 구성이 Distutils에 의해 완전히 지원되기 전까지는 달성되지 않을 것입니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 모듈 배포 (레거시 버전) »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 모듈 배포 (레거시 버전) »

|

4. Creating a Source Distribution

As shown in section A Simple Example, you use the sdist command to create a source distribution. In the simplest case,

python setup.py sdist

(assuming you haven’t specified any sdist options in the setup script or config file), sdist creates the archive of the default format for the current platform. The default format is a gzip’ed tar file (.tar.gz) on Unix, and ZIP file on Windows.

You can specify as many formats as you like using the --formats option, for example:

python setup.py sdist --formats=gztar,zip

to create a gzipped tarball and a zip file. The available formats are:

Format

Description

Notes

zip

zip file (.zip)

(1),(3)

gztar

gzip’ed tar file (.tar.gz)

(2)

bztar

bzip2’ed tar file (.tar.bz2)

xztar

xz’ed tar file (.tar.xz)

ztar

compressed tar file (.tar.Z)

(4)

tar

tar file (.tar)

버전 3.5에서 변경: Added support for the xztar format.

Notes:

default on Windows

default on Unix

requires either external zip utility or zipfile module (part of the standard Python library since Python 1.6)

requires the compress program. Notice that this format is now pending for deprecation and will be removed in the future versions of Python.

When using any tar format (gztar, bztar, xztar, ztar or tar), under Unix you can specify the owner and group names that will be set for each member of the archive.

For example, if you want all files of the archive to be owned by root:

python setup.py sdist --owner=root --group=root

4.1. Specifying the files to distribute

If you don’t supply an explicit list of files (or instructions on how to generate one), the sdist command puts a minimal default set into the source distribution:

all Python source files implied by the py_modules and packages options

all C source files mentioned in the ext_modules or libraries options

scripts identified by the scripts option See Installing Scripts.

anything that looks like a test script: test/test*.py (currently, the Distutils don’t do anything with test scripts except include them in source distributions, but in the future there will be a standard for testing Python module distributions)

Any of the standard README files (README, README.txt, or README.rst), setup.py (or whatever you called your setup script), and setup.cfg.

all files that matches the package_data metadata. See Installing Package Data.

all files that matches the data_files metadata. See Installing Additional Files.

Sometimes this is enough, but usually you will want to specify additional files to distribute. The typical way to do this is to write a manifest template, called MANIFEST.in by default. The manifest template is just a list of instructions for how to generate your manifest file, MANIFEST, which is the exact list of files to include in your source distribution. The sdist command processes this template and generates a manifest based on its instructions and what it finds in the filesystem.

If you prefer to roll your own manifest file, the format is simple: one filename per line, regular files (or symlinks to them) only. If you do supply your own MANIFEST, you must specify everything: the default set of files described above does not apply in this case.

버전 3.1에서 변경: An existing generated MANIFEST will be regenerated without sdist comparing its modification time to the one of MANIFEST.in or setup.py.

버전 3.1.3에서 변경: MANIFEST files start with a comment indicating they are generated. Files without this comment are not overwritten or removed.

버전 3.2.2에서 변경: sdist will read a MANIFEST file if no MANIFEST.in exists, like it used to do.

버전 3.7에서 변경: README.rst is now included in the list of distutils standard READMEs.

The manifest template has one command per line, where each command specifies a set of files to include or exclude from the source distribution. For an example, again we turn to the Distutils’ own manifest template:

include *.txt
recursive-include examples *.txt *.py
prune examples/sample?/build

The meanings should be fairly clear: include all files in the distribution root matching *.txt, all files anywhere under the examples directory matching *.txt or *.py, and exclude all directories matching examples/sample?/build. All of this is done after the standard include set, so you can exclude files from the standard set with explicit instructions in the manifest template. (Or, you can use the --no-defaults option to disable the standard set entirely.) There are several other commands available in the manifest template mini-language; see section 소스 배포 만들기: sdist 명령.

The order of commands in the manifest template matters: initially, we have the list of default files as described above, and each command in the template adds to or removes from that list of files. Once we have fully processed the manifest template, we remove files that should not be included in the source distribution:

all files in the Distutils “build” tree (default build/)

all files in directories named RCS, CVS, .svn, .hg, .git, .bzr or _darcs

Now we have our complete list of files, which is written to the manifest for future reference, and then used to build the source distribution archive(s).

You can disable the default set of included files with the --no-defaults option, and you can disable the standard exclude set with --no-prune.

Following the Distutils’ own manifest template, let’s trace how the sdist command builds the list of files to include in the Distutils source distribution:

include all Python source files in the distutils and distutils/command subdirectories (because packages corresponding to those two directories were mentioned in the packages option in the setup script—see section Writing the Setup Script)

include README.txt, setup.py, and setup.cfg (standard files)

include test/test*.py (standard files)

include *.txt in the distribution root (this will find README.txt a second time, but such redundancies are weeded out later)

include anything matching *.txt or *.py in the sub-tree under examples,

exclude all files in the sub-trees starting at directories matching examples/sample?/build—this may exclude files included by the previous two steps, so it’s important that the prune command in the manifest template comes after the recursive-include command

exclude the entire build tree, and any RCS, CVS, .svn, .hg, .git, .bzr and _darcs directories

Just like in the setup script, file and directory names in the manifest template should always be slash-separated; the Distutils will take care of converting them to the standard representation on your platform. That way, the manifest template is portable across operating systems.

4.2. Manifest-related options

The normal course of operations for the sdist command is as follows:

if the manifest file (MANIFEST by default) exists and the first line does not have a comment indicating it is generated from MANIFEST.in, then it is used as is, unaltered

if the manifest file doesn’t exist or has been previously automatically generated, read MANIFEST.in and create the manifest

if neither MANIFEST nor MANIFEST.in exist, create a manifest with just the default file set

use the list of files now in MANIFEST (either just generated or read in) to create the source distribution archive(s)

There are a couple of options that modify this behaviour. First, use the --no-defaults and --no-prune to disable the standard “include” and “exclude” sets.

Second, you might just want to (re)generate the manifest, but not create a source distribution:

python setup.py sdist --manifest-only

-o is a shortcut for --manifest-only.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 모듈 배포 (레거시 버전) »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 모듈 배포 (레거시 버전) »

|

5. Creating Built Distributions

A “built distribution” is what you’re probably used to thinking of either as a “binary package” or an “installer” (depending on your background). It’s not necessarily binary, though, because it might contain only Python source code and/or byte-code; and we don’t call it a package, because that word is already spoken for in Python. (And “installer” is a term specific to the world of mainstream desktop systems.)

A built distribution is how you make life as easy as possible for installers of your module distribution: for users of RPM-based Linux systems, it’s a binary RPM; for Windows users, it’s an executable installer; for Debian-based Linux users, it’s a Debian package; and so forth. Obviously, no one person will be able to create built distributions for every platform under the sun, so the Distutils are designed to enable module developers to concentrate on their specialty—writing code and creating source distributions—while an intermediary species called packagers springs up to turn source distributions into built distributions for as many platforms as there are packagers.

Of course, the module developer could be their own packager; or the packager could be a volunteer “out there” somewhere who has access to a platform which the original developer does not; or it could be software periodically grabbing new source distributions and turning them into built distributions for as many platforms as the software has access to. Regardless of who they are, a packager uses the setup script and the bdist command family to generate built distributions.

As a simple example, if I run the following command in the Distutils source tree:

python setup.py bdist

then the Distutils builds my module distribution (the Distutils itself in this case), does a “fake” installation (also in the build directory), and creates the default type of built distribution for my platform. The default format for built distributions is a “dumb” tar file on Unix, and a simple executable installer on Windows. (That tar file is considered “dumb” because it has to be unpacked in a specific location to work.)

Thus, the above command on a Unix system creates Distutils-1.0.plat.tar.gz; unpacking this tarball from the right place installs the Distutils just as though you had downloaded the source distribution and run python setup.py install. (The “right place” is either the root of the filesystem or Python’s prefix directory, depending on the options given to the bdist_dumb command; the default is to make dumb distributions relative to prefix.)

Obviously, for pure Python distributions, this isn’t any simpler than just running python setup.py install—but for non-pure distributions, which include extensions that would need to be compiled, it can mean the difference between someone being able to use your extensions or not. And creating “smart” built distributions, such as an RPM package or an executable installer for Windows, is far more convenient for users even if your distribution doesn’t include any extensions.

The bdist command has a --formats option, similar to the sdist command, which you can use to select the types of built distribution to generate: for example,

python setup.py bdist --format=zip

would, when run on a Unix system, create Distutils-1.0.plat.zip—again, this archive would be unpacked from the root directory to install the Distutils.

The available formats for built distributions are:

Format

Description

Notes

gztar

gzipped tar file (.tar.gz)

(1)

bztar

bzipped tar file (.tar.bz2)

xztar

xzipped tar file (.tar.xz)

ztar

compressed tar file (.tar.Z)

(3)

tar

tar file (.tar)

zip

zip file (.zip)

(2),(4)

rpm

RPM

(5)

pkgtool

Solaris pkgtool

sdux

HP-UX swinstall

wininst

self-extracting ZIP file for Windows

(4)

msi

Microsoft Installer.

버전 3.5에서 변경: Added support for the xztar format.

Notes:

default on Unix

default on Windows

requires external compress utility.

requires either external zip utility or zipfile module (part of the standard Python library since Python 1.6)

requires external rpm utility, version 3.0.4 or better (use rpm --version to find out which version you have)

You don’t have to use the bdist command with the --formats option; you can also use the command that directly implements the format you’re interested in. Some of these bdist “sub-commands” actually generate several similar formats; for instance, the bdist_dumb command generates all the “dumb” archive formats (tar, gztar, bztar, xztar, ztar, and zip), and bdist_rpm generates both binary and source RPMs. The bdist sub-commands, and the formats generated by each, are:

Command

Formats

bdist_dumb

tar, gztar, bztar, xztar, ztar, zip

bdist_rpm

rpm, srpm

bdist_wininst

wininst

bdist_msi

msi

The following sections give details on the individual bdist_* commands.

5.1. Creating RPM packages

The RPM format is used by many popular Linux distributions, including Red Hat, SuSE, and Mandrake. If one of these (or any of the other RPM-based Linux distributions) is your usual environment, creating RPM packages for other users of that same distribution is trivial. Depending on the complexity of your module distribution and differences between Linux distributions, you may also be able to create RPMs that work on different RPM-based distributions.

The usual way to create an RPM of your module distribution is to run the bdist_rpm command:

python setup.py bdist_rpm

or the bdist command with the --format option:

python setup.py bdist --formats=rpm

The former allows you to specify RPM-specific options; the latter allows you to easily specify multiple formats in one run. If you need to do both, you can explicitly specify multiple bdist_* commands and their options:

python setup.py bdist_rpm --packager="John Doe <jdoe@example.org>" \
                bdist_wininst --target-version="2.0"

Creating RPM packages is driven by a .spec file, much as using the Distutils is driven by the setup script. To make your life easier, the bdist_rpm command normally creates a .spec file based on the information you supply in the setup script, on the command line, and in any Distutils configuration files. Various options and sections in the .spec file are derived from options in the setup script as follows:

RPM .spec file option or section

Distutils setup script option

Name

name

Summary (in preamble)

description

Version

version

Vendor

author and author_email, or — & maintainer and maintainer_email

Copyright

license

Url

url

%description (section)

long_description

Additionally, there are many options in .spec files that don’t have corresponding options in the setup script. Most of these are handled through options to the bdist_rpm command as follows:

RPM .spec file option or section

bdist_rpm option

default value

Release

release

“1”

Group

group

“Development/Libraries”

Vendor

vendor

(see above)

Packager

packager

(none)

Provides

provides

(none)

Requires

requires

(none)

Conflicts

conflicts

(none)

Obsoletes

obsoletes

(none)

Distribution

distribution_name

(none)

BuildRequires

build_requires

(none)

Icon

icon

(none)

Obviously, supplying even a few of these options on the command-line would be tedious and error-prone, so it’s usually best to put them in the setup configuration file, setup.cfg—see section 설치 구성 파일 작성하기. If you distribute or package many Python module distributions, you might want to put options that apply to all of them in your personal Distutils configuration file (~/.pydistutils.cfg). If you want to temporarily disable this file, you can pass the --no-user-cfg option to setup.py.

There are three steps to building a binary RPM package, all of which are handled automatically by the Distutils:

create a .spec file, which describes the package (analogous to the Distutils setup script; in fact, much of the information in the setup script winds up in the .spec file)

create the source RPM

create the “binary” RPM (which may or may not contain binary code, depending on whether your module distribution contains Python extensions)

Normally, RPM bundles the last two steps together; when you use the Distutils, all three steps are typically bundled together.

If you wish, you can separate these three steps. You can use the --spec-only option to make bdist_rpm just create the .spec file and exit; in this case, the .spec file will be written to the “distribution directory”—normally dist/, but customizable with the --dist-dir option. (Normally, the .spec file winds up deep in the “build tree,” in a temporary directory created by bdist_rpm.)

5.2. Creating Windows Installers

Executable installers are the natural format for binary distributions on Windows. They display a nice graphical user interface, display some information about the module distribution to be installed taken from the metadata in the setup script, let the user select a few options, and start or cancel the installation.

Since the metadata is taken from the setup script, creating Windows installers is usually as easy as running:

python setup.py bdist_wininst

or the bdist command with the --formats option:

python setup.py bdist --formats=wininst

If you have a pure module distribution (only containing pure Python modules and packages), the resulting installer will be version independent and have a name like foo-1.0.win32.exe. Note that creating wininst binary distributions in only supported on Windows systems.

If you have a non-pure distribution, the extensions can only be created on a Windows platform, and will be Python version dependent. The installer filename will reflect this and now has the form foo-1.0.win32-py2.0.exe. You have to create a separate installer for every Python version you want to support.

The installer will try to compile pure modules into bytecode after installation on the target system in normal and optimizing mode. If you don’t want this to happen for some reason, you can run the bdist_wininst command with the --no-target-compile and/or the --no-target-optimize option.

By default the installer will display the cool “Python Powered” logo when it is run, but you can also supply your own 152x261 bitmap which must be a Windows .bmp file with the --bitmap option.

The installer will also display a large title on the desktop background window when it is run, which is constructed from the name of your distribution and the version number. This can be changed to another text by using the --title option.

The installer file will be written to the “distribution directory” — normally dist/, but customizable with the --dist-dir option.

5.3. Cross-compiling on Windows

Starting with Python 2.6, distutils is capable of cross-compiling between Windows platforms. In practice, this means that with the correct tools installed, you can use a 32bit version of Windows to create 64bit extensions and vice-versa.

To build for an alternate platform, specify the --plat-name option to the build command. Valid values are currently ‘win32’, and ‘win-amd64’. For example, on a 32bit version of Windows, you could execute:

python setup.py build --plat-name=win-amd64

to build a 64bit version of your extension. The Windows Installers also support this option, so the command:

python setup.py build --plat-name=win-amd64 bdist_wininst

would create a 64bit installation executable on your 32bit version of Windows.

To cross-compile, you must download the Python source code and cross-compile Python itself for the platform you are targeting - it is not possible from a binary installation of Python (as the .lib etc file for other platforms are not included.) In practice, this means the user of a 32 bit operating system will need to use Visual Studio 2008 to open the PCbuild/PCbuild.sln solution in the Python source tree and build the “x64” configuration of the ‘pythoncore’ project before cross-compiling extensions is possible.

Note that by default, Visual Studio 2008 does not install 64bit compilers or tools. You may need to reexecute the Visual Studio setup process and select these tools (using Control Panel->[Add/Remove] Programs is a convenient way to check or modify your existing install.)

5.3.1. The Postinstallation script

Starting with Python 2.3, a postinstallation script can be specified with the --install-script option. The basename of the script must be specified, and the script filename must also be listed in the scripts argument to the setup function.

This script will be run at installation time on the target system after all the files have been copied, with argv[1] set to -install, and again at uninstallation time before the files are removed with argv[1] set to -remove.

The installation script runs embedded in the windows installer, every output (sys.stdout, sys.stderr) is redirected into a buffer and will be displayed in the GUI after the script has finished.

Some functions especially useful in this context are available as additional built-in functions in the installation script.

directory_created(path)

file_created(path)

These functions should be called when a directory or file is created by the postinstall script at installation time. It will register path with the uninstaller, so that it will be removed when the distribution is uninstalled. To be safe, directories are only removed if they are empty.

get_special_folder_path(csidl_string)

This function can be used to retrieve special folder locations on Windows like the Start Menu or the Desktop. It returns the full path to the folder. csidl_string must be one of the following strings:

"CSIDL_APPDATA"

"CSIDL_COMMON_STARTMENU"
"CSIDL_STARTMENU"

"CSIDL_COMMON_DESKTOPDIRECTORY"
"CSIDL_DESKTOPDIRECTORY"

"CSIDL_COMMON_STARTUP"
"CSIDL_STARTUP"

"CSIDL_COMMON_PROGRAMS"
"CSIDL_PROGRAMS"

"CSIDL_FONTS"

If the folder cannot be retrieved, OSError is raised.

Which folders are available depends on the exact Windows version, and probably also the configuration. For details refer to Microsoft’s documentation of the SHGetSpecialFolderPath() function.

create_shortcut(target, description, filename[, arguments[, workdir[, iconpath[, iconindex]]]])

This function creates a shortcut. target is the path to the program to be started by the shortcut. description is the description of the shortcut. filename is the title of the shortcut that the user will see. arguments specifies the command line arguments, if any. workdir is the working directory for the program. iconpath is the file containing the icon for the shortcut, and iconindex is the index of the icon in the file iconpath. Again, for details consult the Microsoft documentation for the IShellLink interface.

5.4. Vista User Access Control (UAC)

Starting with Python 2.6, bdist_wininst supports a --user-access-control option. The default is ‘none’ (meaning no UAC handling is done), and other valid values are ‘auto’ (meaning prompt for UAC elevation if Python was installed for all users) and ‘force’ (meaning always prompt for elevation).

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 모듈 배포 (레거시 버전) »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 모듈 배포 (레거시 버전) »

|

6. Examples

This chapter provides a number of basic examples to help get started with distutils. Additional information about using distutils can be found in the Distutils Cookbook.

더 보기

Distutils Cookbook [https://wiki.python.org/moin/Distutils/Cookbook]

Collection of recipes showing how to achieve more control over distutils.

6.1. Pure Python distribution (by module)

If you’re just distributing a couple of modules, especially if they don’t live in a particular package, you can specify them individually using the py_modules option in the setup script.

In the simplest case, you’ll have two files to worry about: a setup script and the single module you’re distributing, foo.py in this example:

<root>/
        setup.py
        foo.py

(In all diagrams in this section, <root> will refer to the distribution root directory.) A minimal setup script to describe this situation would be:

from distutils.core import setup
setup(name='foo',
      version='1.0',
      py_modules=['foo'],
      )

Note that the name of the distribution is specified independently with the name option, and there’s no rule that says it has to be the same as the name of the sole module in the distribution (although that’s probably a good convention to follow). However, the distribution name is used to generate filenames, so you should stick to letters, digits, underscores, and hyphens.

Since py_modules is a list, you can of course specify multiple modules, eg. if you’re distributing modules foo and bar, your setup might look like this:

<root>/
        setup.py
        foo.py
        bar.py

and the setup script might be

from distutils.core import setup
setup(name='foobar',
      version='1.0',
      py_modules=['foo', 'bar'],
      )

You can put module source files into another directory, but if you have enough modules to do that, it’s probably easier to specify modules by package rather than listing them individually.

6.2. Pure Python distribution (by package)

If you have more than a couple of modules to distribute, especially if they are in multiple packages, it’s probably easier to specify whole packages rather than individual modules. This works even if your modules are not in a package; you can just tell the Distutils to process modules from the root package, and that works the same as any other package (except that you don’t have to have an __init__.py file).

The setup script from the last example could also be written as

from distutils.core import setup
setup(name='foobar',
      version='1.0',
      packages=[''],
      )

(The empty string stands for the root package.)

If those two files are moved into a subdirectory, but remain in the root package, e.g.:

<root>/
        setup.py
        src/      foo.py
                  bar.py

then you would still specify the root package, but you have to tell the Distutils where source files in the root package live:

from distutils.core import setup
setup(name='foobar',
      version='1.0',
      package_dir={'': 'src'},
      packages=[''],
      )

More typically, though, you will want to distribute multiple modules in the same package (or in sub-packages). For example, if the foo and bar modules belong in package foobar, one way to layout your source tree is

<root>/
        setup.py
        foobar/
                 __init__.py
                 foo.py
                 bar.py

This is in fact the default layout expected by the Distutils, and the one that requires the least work to describe in your setup script:

from distutils.core import setup
setup(name='foobar',
      version='1.0',
      packages=['foobar'],
      )

If you want to put modules in directories not named for their package, then you need to use the package_dir option again. For example, if the src directory holds modules in the foobar package:

<root>/
        setup.py
        src/
                 __init__.py
                 foo.py
                 bar.py

an appropriate setup script would be

from distutils.core import setup
setup(name='foobar',
      version='1.0',
      package_dir={'foobar': 'src'},
      packages=['foobar'],
      )

Or, you might put modules from your main package right in the distribution root:

<root>/
        setup.py
        __init__.py
        foo.py
        bar.py

in which case your setup script would be

from distutils.core import setup
setup(name='foobar',
      version='1.0',
      package_dir={'foobar': ''},
      packages=['foobar'],
      )

(The empty string also stands for the current directory.)

If you have sub-packages, they must be explicitly listed in packages, but any entries in package_dir automatically extend to sub-packages. (In other words, the Distutils does not scan your source tree, trying to figure out which directories correspond to Python packages by looking for __init__.py files.) Thus, if the default layout grows a sub-package:

<root>/
        setup.py
        foobar/
                 __init__.py
                 foo.py
                 bar.py
                 subfoo/
                           __init__.py
                           blah.py

then the corresponding setup script would be

from distutils.core import setup
setup(name='foobar',
      version='1.0',
      packages=['foobar', 'foobar.subfoo'],
      )

6.3. Single extension module

Extension modules are specified using the ext_modules option. package_dir has no effect on where extension source files are found; it only affects the source for pure Python modules. The simplest case, a single extension module in a single C source file, is:

<root>/
        setup.py
        foo.c

If the foo extension belongs in the root package, the setup script for this could be

from distutils.core import setup
from distutils.extension import Extension
setup(name='foobar',
      version='1.0',
      ext_modules=[Extension('foo', ['foo.c'])],
      )

If the extension actually belongs in a package, say foopkg, then

With exactly the same source tree layout, this extension can be put in the foopkg package simply by changing the name of the extension:

from distutils.core import setup
from distutils.extension import Extension
setup(name='foobar',
      version='1.0',
      ext_modules=[Extension('foopkg.foo', ['foo.c'])],
      )

6.4. Checking a package

The check command allows you to verify if your package meta-data meet the minimum requirements to build a distribution.

To run it, just call it using your setup.py script. If something is missing, check will display a warning.

Let’s take an example with a simple script:

from distutils.core import setup

setup(name='foobar')

Running the check command will display some warnings:

$ python setup.py check
running check
warning: check: missing required meta-data: version, url
warning: check: missing meta-data: either (author and author_email) or
         (maintainer and maintainer_email) must be supplied

If you use the reStructuredText syntax in the long_description field and docutils [http://docutils.sourceforge.net] is installed you can check if the syntax is fine with the check command, using the restructuredtext option.

For example, if the setup.py script is changed like this:

from distutils.core import setup

desc = """\
My description
==============

This is the description of the ``foobar`` package.
"""

setup(name='foobar', version='1', author='tarek',
    author_email='tarek@ziade.org',
    url='http://example.com', long_description=desc)

Where the long description is broken, check will be able to detect it by using the docutils parser:

$ python setup.py check --restructuredtext
running check
warning: check: Title underline too short. (line 2)
warning: check: Could not finish the parsing.

6.5. Reading the metadata

The distutils.core.setup() function provides a command-line interface that allows you to query the metadata fields of a project through the setup.py script of a given project:

$ python setup.py --name
distribute

This call reads the name metadata by running the distutils.core.setup() function. Although, when a source or binary distribution is created with Distutils, the metadata fields are written in a static file called PKG-INFO. When a Distutils-based project is installed in Python, the PKG-INFO file is copied alongside the modules and packages of the distribution under NAME-VERSION-pyX.X.egg-info, where NAME is the name of the project, VERSION its version as defined in the Metadata, and pyX.X the major and minor version of Python like 2.7 or 3.2.

You can read back this static file, by using the distutils.dist.DistributionMetadata class and its read_pkg_file() method:

>>> from distutils.dist import DistributionMetadata
>>> metadata = DistributionMetadata()
>>> metadata.read_pkg_file(open('distribute-0.6.8-py2.7.egg-info'))
>>> metadata.name
'distribute'
>>> metadata.version
'0.6.8'
>>> metadata.description
'Easily download, build, install, upgrade, and uninstall Python packages'

Notice that the class can also be instantiated with a metadata file path to loads its values:

>>> pkg_info_path = 'distribute-0.6.8-py2.7.egg-info'
>>> DistributionMetadata(pkg_info_path).name
'distribute'

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 모듈 배포 (레거시 버전) »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 모듈 배포 (레거시 버전) »

|

7. Distutils 확장하기

Distutils는 다양한 방법으로 확장할 수 있습니다. 대부분 확장은 새로운 명령이나 기존 명령의 대체 형식을 취합니다. 예를 들어, 새로운 유형의 플랫폼 특정 패키징을 지원하기 위해 새로운 명령을 작성할 수 있습니다. 반면, 기존 명령을 대체하여 명령이 패키지에서 작동하는 방식의 세부 사항을 수정할 수 있습니다.

distutils의 대부분 확장은 기존 명령을 수정하고자 하는 setup.py 스크립트 내에서 이루어집니다; 많은 사람은 편의상 .py 파일 외에 패키지에 복사해야 하는 몇 가지 파일 확장자를 추가합니다.

대부분 distutils 명령 구현은 distutils.cmd.Command 클래스의 서브 클래스입니다. 새 명령은 Command를 직접 상속할 수 있지만, 대체 명령은 종종 대체할 명령을 직접 서브클래싱해서, 간접적으로 Command를 상속합니다. 명령은 Command에서 파생되어야 합니다.

7.1. 새 명령 통합하기

새로운 명령 구현을 distutils에 통합하는 여러 방법이 있습니다. 가장 어려운 것은 distutils 자체에 새로운 기능을 넣기 위해 로비를 하고, 그 지원을 제공하는 파이썬 버전을 기다리는 (그리고 요구하는) 것입니다. 이것은 여러 가지 이유로 정말 어렵습니다.

가장 흔한, 그리고 아마도 대부분 필요에 가장 합리적인 것은, setup.py 스크립트에 새 구현을 넣고 distutils.core.setup() 함수에서 이를 사용하도록 하는 것입니다.:

from distutils.command.build_py import build_py as _build_py
from distutils.core import setup

class build_py(_build_py):
    """Specialized Python source builder."""

    # implement whatever needs to be different...

setup(cmdclass={'build_py': build_py},
      ...)

이 방법은 특정 패키지를 사용하기 위해 새로운 구현을 사용해야 할 때 가장 유용합니다. 패키지에 관심이 있는 모든 사람이 새로운 명령 구현을 가질 필요가 있기 때문입니다.

파이썬 2.4부터는, 세 번째 옵션을 사용할 수 있습니다. 파이썬 설치를 수정하지 않고도 기존 setup.py 스크립트를 지원할 수 있는 새로운 명령을 추가 할 수 있습니다. 이것은 제삼자 확장이 추가 패키징 시스템에 대한 지원을 제공토록 할 것으로 기대되지만, 명령은 distutils 명령을 사용할 수 있는 모든 것에 사용할 수 있습니다. 새로운 구성 옵션, command_packages (명령 줄 옵션 --command-packages), 을 사용하여 명령을 구현하는 모듈을 검색할 추가 패키지를 지정할 수 있습니다. 모든 distutils 옵션과 마찬가지로, 이것은 명령 줄이나 구성 파일에서 지정할 수 있습니다. 이 옵션은 구성 파일의 [global] 섹션이나, 명령 줄의 모든 명령 앞에서만 설정할 수 있습니다. 구성 파일에 설정하면, 명령 줄에서 재정의할 수 있습니다; 명령 줄에서 빈 문자열로 설정하면 기본값이 사용됩니다. 이것은 패키지와 함께 제공된 구성 파일에서 절대로 설정해서는 안 됩니다.

이 새로운 옵션은 명령 구현을 위해 검색되는 패키지 리스트에 원하는 만큼 패키지를 추가하는 데 사용할 수 있습니다; 여러 패키지 이름은 쉼표로 구분해야 합니다. 지정하지 않으면, 검색은 distutils.command 패키지에서만 수행됩니다. 그러나, setup.py가 옵션 --command-packages distcmds,buildcmds로 실행되면, 패키지 distutils.command, distcmds 및 buildcmds가 이 순서로 검색됩니다. 새 명령은 같은 이름의 모듈에, 같은 이름을 공유하는 클래스에 의해 구현될 것으로 기대됩니다. 위의 예제 명령 줄 옵션에서, bdist_openpkg 명령은 distcmds.bdist_openpkg.bdist_openpkg나 buildcmds.bdist_openpkg.bdist_openpkg 클래스로 구현될 수 있습니다.

7.2. 새 배포 유형 추가하기

배포본(dist/ 디렉터리의 파일)을 만드는 명령은 (command, filename) 쌍을 self.distribution.dist_files에 추가하여 upload가 PyPI에 올릴 수 있도록 해야 합니다. 쌍의 filename에는 경로 정보가 없고, 파일 자체의 이름만 들어 있습니다. 드라이 런 모드에서, 생성될 것을 나타내기 위해 쌍을 여전히 추가해야 합니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 모듈 배포 (레거시 버전) »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 모듈 배포 (레거시 버전) »

|

8. 명령 레퍼런스

8.1. 모듈 설치하기: install 명령 군

install 명령은 build 명령이 실행되었는지 확인한 다음 부속 명령 install_lib, install_data 및 install_scripts를 실행합니다.

8.1.1. install_data

이 명령은 배포와 함께 제공된 모든 데이터 파일을 설치합니다.

8.1.2. install_scripts

이 명령은 배포에 있는 모든 (파이썬) 스크립트를 설치합니다.

8.2. 소스 배포 만들기: sdist 명령

매니페스트(manifest) 템플릿 명령은 다음과 같습니다:

명령

설명

include pat1 pat2 ...

나열된 패턴 중 어느 하나와 일치하는 모든 파일을 포함합니다

exclude pat1 pat2 ...

나열된 패턴 중 어느 하나와 일치하는 모든 파일 제외합니다

recursive-include dir pat1 pat2 ...

나열된 패턴 중 어느 하나와 일치하는 dir 아래의 모든 파일을 포함합니다

recursive-exclude dir pat1 pat2 ...

나열된 패턴 중 어느 하나와 일치하는 dir 아래의 모든 파일을 제외합니다

global-include pat1 pat2 ...

소스 트리에서 나열된 패턴 중 어느 하나와 일치하는 모든 파일을 포함합니다

global-exclude pat1 pat2 ...

소스 트리에서 나열된 패턴 중 어느 하나와 일치하는 모든 파일을 제외합니다

prune dir

dir 아래의 모든 파일을 제외합니다

graft dir

dir 아래의 모든 파일을 포함합니다

여기에서 패턴은 유닉스 스타일 “glob” 패턴입니다: *는 일반 파일명 문자의 모든 시퀀스와 일치하고, ?는 하나의 일반 파일명 문자와 일치하며, [range]는 range의 문자(예를 들어, a-z, a-zA-Z, a-f0-9_.)와 일치합니다. “일반 파일명 문자”의 정의는 플랫폼에 따라 다릅니다: 유닉스에서는 슬래시를 제외한 모든 것입니다; 윈도우에서는 역 슬래시나 콜론을 제외한 모든 것입니다.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 모듈 배포 (레거시 버전) »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 모듈 배포 (레거시 버전) »

|

9. API Reference

9.1. distutils.core — Core Distutils functionality

The distutils.core module is the only module that needs to be installed to use the Distutils. It provides the setup() (which is called from the setup script). Indirectly provides the distutils.dist.Distribution and distutils.cmd.Command class.

distutils.core.setup(arguments)

The basic do-everything function that does most everything you could ever ask for from a Distutils method.

The setup function takes a large number of arguments. These are laid out in the following table.

argument name

value

type

name

The name of the package

a string

version

The version number of the package; see distutils.version

a string

description

A single line describing the package

a string

long_description

Longer description of the package

a string

author

The name of the package author

a string

author_email

The email address of the package author

a string

maintainer

The name of the current maintainer, if different from the author. Note that if the maintainer is provided, distutils will use it as the author in PKG-INFO

a string

maintainer_email

The email address of the current maintainer, if different from the author

a string

url

A URL for the package (homepage)

a string

download_url

A URL to download the package

a string

packages

A list of Python packages that distutils will manipulate

a list of strings

py_modules

A list of Python modules that distutils will manipulate

a list of strings

scripts

A list of standalone script files to be built and installed

a list of strings

ext_modules

A list of Python extensions to be built

a list of instances of distutils.core.Extension

classifiers

A list of categories for the package

a list of strings; valid classifiers are listed on PyPI [https://pypi.org/classifiers].

distclass

the Distribution class to use

a subclass of distutils.core.Distribution

script_name

The name of the setup.py script - defaults to sys.argv[0]

a string

script_args

Arguments to supply to the setup script

a list of strings

options

default options for the setup script

a dictionary

license

The license for the package

a string

keywords

Descriptive meta-data, see PEP 314 [https://www.python.org/dev/peps/pep-0314]

a list of strings or a comma-separated string

platforms

a list of strings or a comma-separated string

cmdclass

A mapping of command names to Command subclasses

a dictionary

data_files

A list of data files to install

a list

package_dir

A mapping of package to directory names

a dictionary

distutils.core.run_setup(script_name[, script_args=None, stop_after='run'])

Run a setup script in a somewhat controlled environment, and return the distutils.dist.Distribution instance that drives things. This is useful if you need to find out the distribution meta-data (passed as keyword args from script to setup()), or the contents of the config files or command-line.

script_name is a file that will be read and run with exec(). sys.argv[0] will be replaced with script for the duration of the call. script_args is a list of strings; if supplied, sys.argv[1:] will be replaced by script_args for the duration of the call.

stop_after tells setup() when to stop processing; possible values:

value

description

init

Stop after the Distribution instance has been created and populated with the keyword arguments to setup()

config

Stop after config files have been parsed (and their data stored in the Distribution instance)

commandline

Stop after the command-line (sys.argv[1:] or script_args) have been parsed (and the data stored in the Distribution instance.)

run

Stop after all commands have been run (the same as if setup() had been called in the usual way). This is the default value.

In addition, the distutils.core module exposed a number of classes that live elsewhere.

Extension from distutils.extension

Command from distutils.cmd

Distribution from distutils.dist

A short description of each of these follows, but see the relevant module for the full reference.

class distutils.core.Extension

The Extension class describes a single C or C++ extension module in a setup script. It accepts the following keyword arguments in its constructor:

argument name

value

type

name

the full name of the extension, including any packages — ie. not a filename or pathname, but Python dotted name

a string

sources

list of source filenames, relative to the distribution root (where the setup script lives), in Unix form (slash-separated) for portability. Source files may be C, C++, SWIG (.i), platform-specific resource files, or whatever else is recognized by the build_ext command as source for a Python extension.

a list of strings

include_dirs

list of directories to search for C/C++ header files (in Unix form for portability)

a list of strings

define_macros

list of macros to define; each macro is defined using a 2-tuple (name, value), where value is either the string to define it to or None to define it without a particular value (equivalent of #define FOO in source or -DFOO on Unix C compiler command line)

a list of tuples

undef_macros

list of macros to undefine explicitly

a list of strings

library_dirs

list of directories to search for C/C++ libraries at link time

a list of strings

libraries

list of library names (not filenames or paths) to link against

a list of strings

runtime_library_dirs

list of directories to search for C/C++ libraries at run time (for shared extensions, this is when the extension is loaded)

a list of strings

extra_objects

list of extra files to link with (eg. object files not implied by ‘sources’, static library that must be explicitly specified, binary resource files, etc.)

a list of strings

extra_compile_args

any extra platform- and compiler-specific information to use when compiling the source files in ‘sources’. For platforms and compilers where a command line makes sense, this is typically a list of command-line arguments, but for other platforms it could be anything.

a list of strings

extra_link_args

any extra platform- and compiler-specific information to use when linking object files together to create the extension (or to create a new static Python interpreter). Similar interpretation as for ‘extra_compile_args’.

a list of strings

export_symbols

list of symbols to be exported from a shared extension. Not used on all platforms, and not generally necessary for Python extensions, which typically export exactly one symbol: init + extension_name.

a list of strings

depends

list of files that the extension depends on

a list of strings

language

extension language (i.e. 'c', 'c++', 'objc'). Will be detected from the source extensions if not provided.

a string

optional

specifies that a build failure in the extension should not abort the build process, but simply skip the extension.

a boolean

class distutils.core.Distribution

A Distribution describes how to build, install and package up a Python software package.

See the setup() function for a list of keyword arguments accepted by the Distribution constructor. setup() creates a Distribution instance.

버전 3.7에서 변경: Distribution now warns if classifiers, keywords and platforms fields are not specified as a list or a string.

class distutils.core.Command

A Command class (or rather, an instance of one of its subclasses) implement a single distutils command.

9.2. distutils.ccompiler — CCompiler base class

This module provides the abstract base class for the CCompiler classes. A CCompiler instance can be used for all the compile and link steps needed to build a single project. Methods are provided to set options for the compiler — macro definitions, include directories, link path, libraries and the like.

This module provides the following functions.

distutils.ccompiler.gen_lib_options(compiler, library_dirs, runtime_library_dirs, libraries)

Generate linker options for searching library directories and linking with specific libraries. libraries and library_dirs are, respectively, lists of library names (not filenames!) and search directories. Returns a list of command-line options suitable for use with some compiler (depending on the two format strings passed in).

distutils.ccompiler.gen_preprocess_options(macros, include_dirs)

Generate C pre-processor options (-D, -U, -I) as used by at least two types of compilers: the typical Unix compiler and Visual C++. macros is the usual thing, a list of 1- or 2-tuples, where (name,) means undefine (-U) macro name, and (name, value) means define (-D) macro name to value. include_dirs is just a list of directory names to be added to the header file search path (-I). Returns a list of command-line options suitable for either Unix compilers or Visual C++.

distutils.ccompiler.get_default_compiler(osname, platform)

Determine the default compiler to use for the given platform.

osname should be one of the standard Python OS names (i.e. the ones returned by os.name) and platform the common value returned by sys.platform for the platform in question.

The default values are os.name and sys.platform in case the parameters are not given.

distutils.ccompiler.new_compiler(plat=None, compiler=None, verbose=0, dry_run=0, force=0)

Factory function to generate an instance of some CCompiler subclass for the supplied platform/compiler combination. plat defaults to os.name (eg. 'posix', 'nt'), and compiler defaults to the default compiler for that platform. Currently only 'posix' and 'nt' are supported, and the default compilers are “traditional Unix interface” (UnixCCompiler class) and Visual C++ (MSVCCompiler class). Note that it’s perfectly possible to ask for a Unix compiler object under Windows, and a Microsoft compiler object under Unix—if you supply a value for compiler, plat is ignored.

distutils.ccompiler.show_compilers()

Print list of available compilers (used by the --help-compiler options to build, build_ext, build_clib).

class distutils.ccompiler.CCompiler([verbose=0, dry_run=0, force=0])

The abstract base class CCompiler defines the interface that must be implemented by real compiler classes. The class also has some utility methods used by several compiler classes.

The basic idea behind a compiler abstraction class is that each instance can be used for all the compile/link steps in building a single project. Thus, attributes common to all of those compile and link steps — include directories, macros to define, libraries to link against, etc. — are attributes of the compiler instance. To allow for variability in how individual files are treated, most of those attributes may be varied on a per-compilation or per-link basis.

The constructor for each subclass creates an instance of the Compiler object. Flags are verbose (show verbose output), dry_run (don’t actually execute the steps) and force (rebuild everything, regardless of dependencies). All of these flags default to 0 (off). Note that you probably don’t want to instantiate CCompiler or one of its subclasses directly - use the distutils.CCompiler.new_compiler() factory function instead.

The following methods allow you to manually alter compiler options for the instance of the Compiler class.

add_include_dir(dir)

Add dir to the list of directories that will be searched for header files. The compiler is instructed to search directories in the order in which they are supplied by successive calls to add_include_dir().

set_include_dirs(dirs)

Set the list of directories that will be searched to dirs (a list of strings). Overrides any preceding calls to add_include_dir(); subsequent calls to add_include_dir() add to the list passed to set_include_dirs(). This does not affect any list of standard include directories that the compiler may search by default.

add_library(libname)

Add libname to the list of libraries that will be included in all links driven by this compiler object. Note that libname should *not* be the name of a file containing a library, but the name of the library itself: the actual filename will be inferred by the linker, the compiler, or the compiler class (depending on the platform).

The linker will be instructed to link against libraries in the order they were supplied to add_library() and/or set_libraries(). It is perfectly valid to duplicate library names; the linker will be instructed to link against libraries as many times as they are mentioned.

set_libraries(libnames)

Set the list of libraries to be included in all links driven by this compiler object to libnames (a list of strings). This does not affect any standard system libraries that the linker may include by default.

add_library_dir(dir)

Add dir to the list of directories that will be searched for libraries specified to add_library() and set_libraries(). The linker will be instructed to search for libraries in the order they are supplied to add_library_dir() and/or set_library_dirs().

set_library_dirs(dirs)

Set the list of library search directories to dirs (a list of strings). This does not affect any standard library search path that the linker may search by default.

add_runtime_library_dir(dir)

Add dir to the list of directories that will be searched for shared libraries at runtime.

set_runtime_library_dirs(dirs)

Set the list of directories to search for shared libraries at runtime to dirs (a list of strings). This does not affect any standard search path that the runtime linker may search by default.

define_macro(name[, value=None])

Define a preprocessor macro for all compilations driven by this compiler object. The optional parameter value should be a string; if it is not supplied, then the macro will be defined without an explicit value and the exact outcome depends on the compiler used.

undefine_macro(name)

Undefine a preprocessor macro for all compilations driven by this compiler object. If the same macro is defined by define_macro() and undefined by undefine_macro() the last call takes precedence (including multiple redefinitions or undefinitions). If the macro is redefined/undefined on a per-compilation basis (ie. in the call to compile()), then that takes precedence.

add_link_object(object)

Add object to the list of object files (or analogues, such as explicitly named library files or the output of “resource compilers”) to be included in every link driven by this compiler object.

set_link_objects(objects)

Set the list of object files (or analogues) to be included in every link to objects. This does not affect any standard object files that the linker may include by default (such as system libraries).

The following methods implement methods for autodetection of compiler options, providing some functionality similar to GNU autoconf.

detect_language(sources)

Detect the language of a given file, or list of files. Uses the instance attributes language_map (a dictionary), and language_order (a list) to do the job.

find_library_file(dirs, lib[, debug=0])

Search the specified list of directories for a static or shared library file lib and return the full path to that file. If debug is true, look for a debugging version (if that makes sense on the current platform). Return None if lib wasn’t found in any of the specified directories.

has_function(funcname[, includes=None, include_dirs=None, libraries=None, library_dirs=None])

Return a boolean indicating whether funcname is supported on the current platform. The optional arguments can be used to augment the compilation environment by providing additional include files and paths and libraries and paths.

library_dir_option(dir)

Return the compiler option to add dir to the list of directories searched for libraries.

library_option(lib)

Return the compiler option to add lib to the list of libraries linked into the shared library or executable.

runtime_library_dir_option(dir)

Return the compiler option to add dir to the list of directories searched for runtime libraries.

set_executables(**args)

Define the executables (and options for them) that will be run to perform the various stages of compilation. The exact set of executables that may be specified here depends on the compiler class (via the ‘executables’ class attribute), but most will have:

attribute

description

compiler

the C/C++ compiler

linker_so

linker used to create shared objects and libraries

linker_exe

linker used to create binary executables

archiver

static library creator

On platforms with a command-line (Unix, DOS/Windows), each of these is a string that will be split into executable name and (optional) list of arguments. (Splitting the string is done similarly to how Unix shells operate: words are delimited by spaces, but quotes and backslashes can override this. See distutils.util.split_quoted().)

The following methods invoke stages in the build process.

compile(sources[, output_dir=None, macros=None, include_dirs=None, debug=0, extra_preargs=None, extra_postargs=None, depends=None])

Compile one or more source files. Generates object files (e.g. transforms a .c file to a .o file.)

sources must be a list of filenames, most likely C/C++ files, but in reality anything that can be handled by a particular compiler and compiler class (eg. MSVCCompiler can handle resource files in sources). Return a list of object filenames, one per source filename in sources. Depending on the implementation, not all source files will necessarily be compiled, but all corresponding object filenames will be returned.

If output_dir is given, object files will be put under it, while retaining their original path component. That is, foo/bar.c normally compiles to foo/bar.o (for a Unix implementation); if output_dir is build, then it would compile to build/foo/bar.o.

macros, if given, must be a list of macro definitions. A macro definition is either a (name, value) 2-tuple or a (name,) 1-tuple. The former defines a macro; if the value is None, the macro is defined without an explicit value. The 1-tuple case undefines a macro. Later definitions/redefinitions/undefinitions take precedence.

include_dirs, if given, must be a list of strings, the directories to add to the default include file search path for this compilation only.

debug is a boolean; if true, the compiler will be instructed to output debug symbols in (or alongside) the object file(s).

extra_preargs and extra_postargs are implementation-dependent. On platforms that have the notion of a command-line (e.g. Unix, DOS/Windows), they are most likely lists of strings: extra command-line arguments to prepend/append to the compiler command line. On other platforms, consult the implementation class documentation. In any event, they are intended as an escape hatch for those occasions when the abstract compiler framework doesn’t cut the mustard.

depends, if given, is a list of filenames that all targets depend on. If a source file is older than any file in depends, then the source file will be recompiled. This supports dependency tracking, but only at a coarse granularity.

Raises CompileError on failure.

create_static_lib(objects, output_libname[, output_dir=None, debug=0, target_lang=None])

Link a bunch of stuff together to create a static library file. The “bunch of stuff” consists of the list of object files supplied as objects, the extra object files supplied to add_link_object() and/or set_link_objects(), the libraries supplied to add_library() and/or set_libraries(), and the libraries supplied as libraries (if any).

output_libname should be a library name, not a filename; the filename will be inferred from the library name. output_dir is the directory where the library file will be put.

debug is a boolean; if true, debugging information will be included in the library (note that on most platforms, it is the compile step where this matters: the debug flag is included here just for consistency).

target_lang is the target language for which the given objects are being compiled. This allows specific linkage time treatment of certain languages.

Raises LibError on failure.

link(target_desc, objects, output_filename[, output_dir=None, libraries=None, library_dirs=None, runtime_library_dirs=None, export_symbols=None, debug=0, extra_preargs=None, extra_postargs=None, build_temp=None, target_lang=None])

Link a bunch of stuff together to create an executable or shared library file.

The “bunch of stuff” consists of the list of object files supplied as objects. output_filename should be a filename. If output_dir is supplied, output_filename is relative to it (i.e. output_filename can provide directory components if needed).

libraries is a list of libraries to link against. These are library names, not filenames, since they’re translated into filenames in a platform-specific way (eg. foo becomes libfoo.a on Unix and foo.lib on DOS/Windows). However, they can include a directory component, which means the linker will look in that specific directory rather than searching all the normal locations.

library_dirs, if supplied, should be a list of directories to search for libraries that were specified as bare library names (ie. no directory component). These are on top of the system default and those supplied to add_library_dir() and/or set_library_dirs(). runtime_library_dirs is a list of directories that will be embedded into the shared library and used to search for other shared libraries that *it* depends on at run-time. (This may only be relevant on Unix.)

export_symbols is a list of symbols that the shared library will export. (This appears to be relevant only on Windows.)

debug is as for compile() and create_static_lib(), with the slight distinction that it actually matters on most platforms (as opposed to create_static_lib(), which includes a debug flag mostly for form’s sake).

extra_preargs and extra_postargs are as for compile() (except of course that they supply command-line arguments for the particular linker being used).

target_lang is the target language for which the given objects are being compiled. This allows specific linkage time treatment of certain languages.

Raises LinkError on failure.

link_executable(objects, output_progname[, output_dir=None, libraries=None, library_dirs=None, runtime_library_dirs=None, debug=0, extra_preargs=None, extra_postargs=None, target_lang=None])

Link an executable. output_progname is the name of the file executable, while objects are a list of object filenames to link in. Other arguments are as for the link() method.

link_shared_lib(objects, output_libname[, output_dir=None, libraries=None, library_dirs=None, runtime_library_dirs=None, export_symbols=None, debug=0, extra_preargs=None, extra_postargs=None, build_temp=None, target_lang=None])

Link a shared library. output_libname is the name of the output library, while objects is a list of object filenames to link in. Other arguments are as for the link() method.

link_shared_object(objects, output_filename[, output_dir=None, libraries=None, library_dirs=None, runtime_library_dirs=None, export_symbols=None, debug=0, extra_preargs=None, extra_postargs=None, build_temp=None, target_lang=None])

Link a shared object. output_filename is the name of the shared object that will be created, while objects is a list of object filenames to link in. Other arguments are as for the link() method.

preprocess(source[, output_file=None, macros=None, include_dirs=None, extra_preargs=None, extra_postargs=None])

Preprocess a single C/C++ source file, named in source. Output will be written to file named output_file, or stdout if output_file not supplied. macros is a list of macro definitions as for compile(), which will augment the macros set with define_macro() and undefine_macro(). include_dirs is a list of directory names that will be added to the default list, in the same way as add_include_dir().

Raises PreprocessError on failure.

The following utility methods are defined by the CCompiler class, for use by the various concrete subclasses.

executable_filename(basename[, strip_dir=0, output_dir=''])

Returns the filename of the executable for the given basename. Typically for non-Windows platforms this is the same as the basename, while Windows will get a .exe added.

library_filename(libname[, lib_type='static', strip_dir=0, output_dir=''])

Returns the filename for the given library name on the current platform. On Unix a library with lib_type of 'static' will typically be of the form liblibname.a, while a lib_type of 'dynamic' will be of the form liblibname.so.

object_filenames(source_filenames[, strip_dir=0, output_dir=''])

Returns the name of the object files for the given source files. source_filenames should be a list of filenames.

shared_object_filename(basename[, strip_dir=0, output_dir=''])

Returns the name of a shared object file for the given file name basename.

execute(func, args[, msg=None, level=1])

Invokes distutils.util.execute(). This method invokes a Python function func with the given arguments args, after logging and taking into account the dry_run flag.

spawn(cmd)

Invokes distutils.util.spawn(). This invokes an external process to run the given command.

mkpath(name[, mode=511])

Invokes distutils.dir_util.mkpath(). This creates a directory and any missing ancestor directories.

move_file(src, dst)

Invokes distutils.file_util.move_file(). Renames src to dst.

announce(msg[, level=1])

Write a message using distutils.log.debug().

warn(msg)

Write a warning message msg to standard error.

debug_print(msg)

If the debug flag is set on this CCompiler instance, print msg to standard output, otherwise do nothing.

9.3. distutils.unixccompiler — Unix C Compiler

This module provides the UnixCCompiler class, a subclass of CCompiler that handles the typical Unix-style command-line C compiler:

macros defined with -Dname[=value]

macros undefined with -Uname

include search directories specified with -Idir

libraries specified with -llib

library search directories specified with -Ldir

compile handled by cc (or similar) executable with -c option: compiles .c to .o

link static library handled by ar command (possibly with ranlib)

link shared library handled by cc -shared

9.4. distutils.msvccompiler — Microsoft Compiler

This module provides MSVCCompiler, an implementation of the abstract CCompiler class for Microsoft Visual Studio. Typically, extension modules need to be compiled with the same compiler that was used to compile Python. For Python 2.3 and earlier, the compiler was Visual Studio 6. For Python 2.4 and 2.5, the compiler is Visual Studio .NET 2003.

MSVCCompiler will normally choose the right compiler, linker etc. on its own. To override this choice, the environment variables DISTUTILS_USE_SDK and MSSdk must be both set. MSSdk indicates that the current environment has been setup by the SDK’s SetEnv.Cmd script, or that the environment variables had been registered when the SDK was installed; DISTUTILS_USE_SDK indicates that the distutils user has made an explicit choice to override the compiler selection by MSVCCompiler.

9.5. distutils.bcppcompiler — Borland Compiler

This module provides BorlandCCompiler, a subclass of the abstract CCompiler class for the Borland C++ compiler.

9.6. distutils.cygwincompiler — Cygwin Compiler

This module provides the CygwinCCompiler class, a subclass of UnixCCompiler that handles the Cygwin port of the GNU C compiler to Windows. It also contains the Mingw32CCompiler class which handles the mingw32 port of GCC (same as cygwin in no-cygwin mode).

9.7. distutils.archive_util — Archiving utilities

This module provides a few functions for creating archive files, such as tarballs or zipfiles.

distutils.archive_util.make_archive(base_name, format[, root_dir=None, base_dir=None, verbose=0, dry_run=0])

Create an archive file (eg. zip or tar). base_name is the name of the file to create, minus any format-specific extension; format is the archive format: one of zip, tar, gztar, bztar, xztar, or ztar. root_dir is a directory that will be the root directory of the archive; ie. we typically chdir into root_dir before creating the archive. base_dir is the directory where we start archiving from; ie. base_dir will be the common prefix of all files and directories in the archive. root_dir and base_dir both default to the current directory. Returns the name of the archive file.

버전 3.5에서 변경: Added support for the xztar format.

distutils.archive_util.make_tarball(base_name, base_dir[, compress='gzip', verbose=0, dry_run=0])

‘Create an (optional compressed) archive as a tar file from all files in and under base_dir. compress must be 'gzip' (the default), 'bzip2', 'xz', 'compress', or None. For the 'compress' method the compression utility named by compress must be on the default program search path, so this is probably Unix-specific. The output tar file will be named base_dir.tar, possibly plus the appropriate compression extension (.gz, .bz2, .xz or .Z). Return the output filename.

버전 3.5에서 변경: Added support for the xz compression.

distutils.archive_util.make_zipfile(base_name, base_dir[, verbose=0, dry_run=0])

Create a zip file from all files in and under base_dir. The output zip file will be named base_name + .zip. Uses either the zipfile Python module (if available) or the InfoZIP zip utility (if installed and found on the default search path). If neither tool is available, raises DistutilsExecError. Returns the name of the output zip file.

9.8. distutils.dep_util — Dependency checking

This module provides functions for performing simple, timestamp-based dependency of files and groups of files; also, functions based entirely on such timestamp dependency analysis.

distutils.dep_util.newer(source, target)

Return true if source exists and is more recently modified than target, or if source exists and target doesn’t. Return false if both exist and target is the same age or newer than source. Raise DistutilsFileError if source does not exist.

distutils.dep_util.newer_pairwise(sources, targets)

Walk two filename lists in parallel, testing if each source is newer than its corresponding target. Return a pair of lists (sources, targets) where source is newer than target, according to the semantics of newer().

distutils.dep_util.newer_group(sources, target[, missing='error'])

Return true if target is out-of-date with respect to any file listed in sources. In other words, if target exists and is newer than every file in sources, return false; otherwise return true. missing controls what we do when a source file is missing; the default ('error') is to blow up with an OSError from inside os.stat(); if it is 'ignore', we silently drop any missing source files; if it is 'newer', any missing source files make us assume that target is out-of-date (this is handy in “dry-run” mode: it’ll make you pretend to carry out commands that wouldn’t work because inputs are missing, but that doesn’t matter because you’re not actually going to run the commands).

9.9. distutils.dir_util — Directory tree operations

This module provides functions for operating on directories and trees of directories.

distutils.dir_util.mkpath(name[, mode=0o777, verbose=0, dry_run=0])

Create a directory and any missing ancestor directories. If the directory already exists (or if name is the empty string, which means the current directory, which of course exists), then do nothing. Raise DistutilsFileError if unable to create some directory along the way (eg. some sub-path exists, but is a file rather than a directory). If verbose is true, print a one-line summary of each mkdir to stdout. Return the list of directories actually created.

distutils.dir_util.create_tree(base_dir, files[, mode=0o777, verbose=0, dry_run=0])

Create all the empty directories under base_dir needed to put files there. base_dir is just the name of a directory which doesn’t necessarily exist yet; files is a list of filenames to be interpreted relative to base_dir. base_dir + the directory portion of every file in files will be created if it doesn’t already exist. mode, verbose and dry_run flags are as for mkpath().

distutils.dir_util.copy_tree(src, dst[, preserve_mode=1, preserve_times=1, preserve_symlinks=0, update=0, verbose=0, dry_run=0])

Copy an entire directory tree src to a new location dst. Both src and dst must be directory names. If src is not a directory, raise DistutilsFileError. If dst does not exist, it is created with mkpath(). The end result of the copy is that every file in src is copied to dst, and directories under src are recursively copied to dst. Return the list of files that were copied or might have been copied, using their output name. The return value is unaffected by update or dry_run: it is simply the list of all files under src, with the names changed to be under dst.

preserve_mode and preserve_times are the same as for distutils.file_util.copy_file(); note that they only apply to regular files, not to directories. If preserve_symlinks is true, symlinks will be copied as symlinks (on platforms that support them!); otherwise (the default), the destination of the symlink will be copied. update and verbose are the same as for copy_file().

Files in src that begin with .nfs are skipped (more information on these files is available in answer D2 of the NFS FAQ page [http://nfs.sourceforge.net/#section_d]).

버전 3.3.1에서 변경: NFS files are ignored.

distutils.dir_util.remove_tree(directory[, verbose=0, dry_run=0])

Recursively remove directory and all files and directories underneath it. Any errors are ignored (apart from being reported to sys.stdout if verbose is true).

9.10. distutils.file_util — Single file operations

This module contains some utility functions for operating on individual files.

distutils.file_util.copy_file(src, dst[, preserve_mode=1, preserve_times=1, update=0, link=None, verbose=0, dry_run=0])

Copy file src to dst. If dst is a directory, then src is copied there with the same name; otherwise, it must be a filename. (If the file exists, it will be ruthlessly clobbered.) If preserve_mode is true (the default), the file’s mode (type and permission bits, or whatever is analogous on the current platform) is copied. If preserve_times is true (the default), the last-modified and last-access times are copied as well. If update is true, src will only be copied if dst does not exist, or if dst does exist but is older than src.

link allows you to make hard links (using os.link()) or symbolic links (using os.symlink()) instead of copying: set it to 'hard' or 'sym'; if it is None (the default), files are copied. Don’t set link on systems that don’t support it: copy_file() doesn’t check if hard or symbolic linking is available. It uses _copy_file_contents() to copy file contents.

Return a tuple (dest_name, copied): dest_name is the actual name of the output file, and copied is true if the file was copied (or would have been copied, if dry_run true).

distutils.file_util.move_file(src, dst[, verbose, dry_run])

Move file src to dst. If dst is a directory, the file will be moved into it with the same name; otherwise, src is just renamed to dst. Returns the new full name of the file.

경고

Handles cross-device moves on Unix using copy_file(). What about other systems?

distutils.file_util.write_file(filename, contents)

Create a file called filename and write contents (a sequence of strings without line terminators) to it.

9.11. distutils.util — Miscellaneous other utility functions

This module contains other assorted bits and pieces that don’t fit into any other utility module.

distutils.util.get_platform()

Return a string that identifies the current platform. This is used mainly to distinguish platform-specific build directories and platform-specific built distributions. Typically includes the OS name and version and the architecture (as supplied by ‘os.uname()’), although the exact information included depends on the OS; e.g., on Linux, the kernel version isn’t particularly important.

Examples of returned values:

linux-i586

linux-alpha

solaris-2.6-sun4u

For non-POSIX platforms, currently just returns sys.platform.

For Mac OS X systems the OS version reflects the minimal version on which binaries will run (that is, the value of MACOSX_DEPLOYMENT_TARGET during the build of Python), not the OS version of the current system.

For universal binary builds on Mac OS X the architecture value reflects the universal binary status instead of the architecture of the current processor. For 32-bit universal binaries the architecture is fat, for 64-bit universal binaries the architecture is fat64, and for 4-way universal binaries the architecture is universal. Starting from Python 2.7 and Python 3.2 the architecture fat3 is used for a 3-way universal build (ppc, i386, x86_64) and intel is used for a universal build with the i386 and x86_64 architectures

Examples of returned values on Mac OS X:

macosx-10.3-ppc

macosx-10.3-fat

macosx-10.5-universal

macosx-10.6-intel

distutils.util.convert_path(pathname)

Return ‘pathname’ as a name that will work on the native filesystem, i.e. split it on ‘/’ and put it back together again using the current directory separator. Needed because filenames in the setup script are always supplied in Unix style, and have to be converted to the local convention before we can actually use them in the filesystem. Raises ValueError on non-Unix-ish systems if pathname either starts or ends with a slash.

distutils.util.change_root(new_root, pathname)

Return pathname with new_root prepended. If pathname is relative, this is equivalent to os.path.join(new_root,pathname) Otherwise, it requires making pathname relative and then joining the two, which is tricky on DOS/Windows.

distutils.util.check_environ()

Ensure that ‘os.environ’ has all the environment variables we guarantee that users can use in config files, command-line options, etc. Currently this includes:

HOME - user’s home directory (Unix only)

PLAT - description of the current platform, including hardware and OS (see get_platform())

distutils.util.subst_vars(s, local_vars)

Perform shell/Perl-style variable substitution on s. Every occurrence of $ followed by a name is considered a variable, and variable is substituted by the value found in the local_vars dictionary, or in os.environ if it’s not in local_vars. os.environ is first checked/augmented to guarantee that it contains certain values: see check_environ(). Raise ValueError for any variables not found in either local_vars or os.environ.

Note that this is not a fully-fledged string interpolation function. A valid $variable can consist only of upper and lower case letters, numbers and an underscore. No { } or ( ) style quoting is available.

distutils.util.split_quoted(s)

Split a string up according to Unix shell-like rules for quotes and backslashes. In short: words are delimited by spaces, as long as those spaces are not escaped by a backslash, or inside a quoted string. Single and double quotes are equivalent, and the quote characters can be backslash-escaped. The backslash is stripped from any two-character escape sequence, leaving only the escaped character. The quote characters are stripped from any quoted string. Returns a list of words.

distutils.util.execute(func, args[, msg=None, verbose=0, dry_run=0])

Perform some action that affects the outside world (for instance, writing to the filesystem). Such actions are special because they are disabled by the dry_run flag. This method takes care of all that bureaucracy for you; all you have to do is supply the function to call and an argument tuple for it (to embody the “external action” being performed), and an optional message to print.

distutils.util.strtobool(val)

Convert a string representation of truth to true (1) or false (0).

True values are y, yes, t, true, on and 1; false values are n, no, f, false, off and 0. Raises ValueError if val is anything else.

distutils.util.byte_compile(py_files[, optimize=0, force=0, prefix=None, base_dir=None, verbose=1, dry_run=0, direct=None])

Byte-compile a collection of Python source files to .pyc files in a __pycache__ subdirectory (see PEP 3147 [https://www.python.org/dev/peps/pep-3147] and PEP 488 [https://www.python.org/dev/peps/pep-0488]). py_files is a list of files to compile; any files that don’t end in .py are silently skipped. optimize must be one of the following:

0 - don’t optimize

1 - normal optimization (like python -O)

2 - extra optimization (like python -OO)

If force is true, all files are recompiled regardless of timestamps.

The source filename encoded in each bytecode file defaults to the filenames listed in py_files; you can modify these with prefix and basedir. prefix is a string that will be stripped off of each source filename, and base_dir is a directory name that will be prepended (after prefix is stripped). You can supply either or both (or neither) of prefix and base_dir, as you wish.

If dry_run is true, doesn’t actually do anything that would affect the filesystem.

Byte-compilation is either done directly in this interpreter process with the standard py_compile module, or indirectly by writing a temporary script and executing it. Normally, you should let byte_compile() figure out to use direct compilation or not (see the source for details). The direct flag is used by the script generated in indirect mode; unless you know what you’re doing, leave it set to None.

버전 3.2.3에서 변경: Create .pyc files with an import magic tag in their name, in a __pycache__ subdirectory instead of files without tag in the current directory.

버전 3.5에서 변경: Create .pyc files according to PEP 488 [https://www.python.org/dev/peps/pep-0488].

distutils.util.rfc822_escape(header)

Return a version of header escaped for inclusion in an RFC 822 [https://tools.ietf.org/html/rfc822.html] header, by ensuring there are 8 spaces space after each newline. Note that it does no other modification of the string.

9.12. distutils.dist — The Distribution class

This module provides the Distribution class, which represents the module distribution being built/installed/distributed.

9.13. distutils.extension — The Extension class

This module provides the Extension class, used to describe C/C++ extension modules in setup scripts.

9.14. distutils.debug — Distutils debug mode

This module provides the DEBUG flag.

9.15. distutils.errors — Distutils exceptions

Provides exceptions used by the Distutils modules. Note that Distutils modules may raise standard exceptions; in particular, SystemExit is usually raised for errors that are obviously the end-user’s fault (eg. bad command-line arguments).

This module is safe to use in from ... import * mode; it only exports symbols whose names start with Distutils and end with Error.

9.16. distutils.fancy_getopt — Wrapper around the standard getopt module

This module provides a wrapper around the standard getopt module that provides the following additional features:

short and long options are tied together

options have help strings, so fancy_getopt() could potentially create a complete usage summary

options set attributes of a passed-in object

boolean options can have “negative aliases” — eg. if --quiet is the “negative alias” of --verbose, then --quiet on the command line sets verbose to false.

distutils.fancy_getopt.fancy_getopt(options, negative_opt, object, args)

Wrapper function. options is a list of (long_option, short_option, help_string) 3-tuples as described in the constructor for FancyGetopt. negative_opt should be a dictionary mapping option names to option names, both the key and value should be in the options list. object is an object which will be used to store values (see the getopt() method of the FancyGetopt class). args is the argument list. Will use sys.argv[1:] if you pass None as args.

distutils.fancy_getopt.wrap_text(text, width)

Wraps text to less than width wide.

class distutils.fancy_getopt.FancyGetopt([option_table=None])

The option_table is a list of 3-tuples: (long_option, short_option, help_string)

If an option takes an argument, its long_option should have '=' appended; short_option should just be a single character, no ':' in any case. short_option should be None if a long_option doesn’t have a corresponding short_option. All option tuples must have long options.

The FancyGetopt class provides the following methods:

FancyGetopt.getopt([args=None, object=None])

Parse command-line options in args. Store as attributes on object.

If args is None or not supplied, uses sys.argv[1:]. If object is None or not supplied, creates a new OptionDummy instance, stores option values there, and returns a tuple (args, object). If object is supplied, it is modified in place and getopt() just returns args; in both cases, the returned args is a modified copy of the passed-in args list, which is left untouched.

FancyGetopt.get_option_order()

Returns the list of (option, value) tuples processed by the previous run of getopt() Raises RuntimeError if getopt() hasn’t been called yet.

FancyGetopt.generate_help([header=None])

Generate help text (a list of strings, one per suggested line of output) from the option table for this FancyGetopt object.

If supplied, prints the supplied header at the top of the help.

9.17. distutils.filelist — The FileList class

This module provides the FileList class, used for poking about the filesystem and building lists of files.

9.18. distutils.log — Simple PEP 282-style logging

9.19. distutils.spawn — Spawn a sub-process

This module provides the spawn() function, a front-end to various platform-specific functions for launching another program in a sub-process. Also provides find_executable() to search the path for a given executable name.

9.20. distutils.sysconfig — System configuration information

The distutils.sysconfig module provides access to Python’s low-level configuration information. The specific configuration variables available depend heavily on the platform and configuration. The specific variables depend on the build process for the specific version of Python being run; the variables are those found in the Makefile and configuration header that are installed with Python on Unix systems. The configuration header is called pyconfig.h for Python versions starting with 2.2, and config.h for earlier versions of Python.

Some additional functions are provided which perform some useful manipulations for other parts of the distutils package.

distutils.sysconfig.PREFIX

The result of os.path.normpath(sys.prefix).

distutils.sysconfig.EXEC_PREFIX

The result of os.path.normpath(sys.exec_prefix).

distutils.sysconfig.get_config_var(name)

Return the value of a single variable. This is equivalent to get_config_vars().get(name).

distutils.sysconfig.get_config_vars(...)

Return a set of variable definitions. If there are no arguments, this returns a dictionary mapping names of configuration variables to values. If arguments are provided, they should be strings, and the return value will be a sequence giving the associated values. If a given name does not have a corresponding value, None will be included for that variable.

distutils.sysconfig.get_config_h_filename()

Return the full path name of the configuration header. For Unix, this will be the header generated by the configure script; for other platforms the header will have been supplied directly by the Python source distribution. The file is a platform-specific text file.

distutils.sysconfig.get_makefile_filename()

Return the full path name of the Makefile used to build Python. For Unix, this will be a file generated by the configure script; the meaning for other platforms will vary. The file is a platform-specific text file, if it exists. This function is only useful on POSIX platforms.

distutils.sysconfig.get_python_inc([plat_specific[, prefix]])

Return the directory for either the general or platform-dependent C include files. If plat_specific is true, the platform-dependent include directory is returned; if false or omitted, the platform-independent directory is returned. If prefix is given, it is used as either the prefix instead of PREFIX, or as the exec-prefix instead of EXEC_PREFIX if plat_specific is true.

distutils.sysconfig.get_python_lib([plat_specific[, standard_lib[, prefix]]])

Return the directory for either the general or platform-dependent library installation. If plat_specific is true, the platform-dependent include directory is returned; if false or omitted, the platform-independent directory is returned. If prefix is given, it is used as either the prefix instead of PREFIX, or as the exec-prefix instead of EXEC_PREFIX if plat_specific is true. If standard_lib is true, the directory for the standard library is returned rather than the directory for the installation of third-party extensions.

The following function is only intended for use within the distutils package.

distutils.sysconfig.customize_compiler(compiler)

Do any platform-specific customization of a distutils.ccompiler.CCompiler instance.

This function is only needed on Unix at this time, but should be called consistently to support forward-compatibility. It inserts the information that varies across Unix flavors and is stored in Python’s Makefile. This information includes the selected compiler, compiler and linker options, and the extension used by the linker for shared objects.

This function is even more special-purpose, and should only be used from Python’s own build procedures.

distutils.sysconfig.set_python_build()

Inform the distutils.sysconfig module that it is being used as part of the build process for Python. This changes a lot of relative locations for files, allowing them to be located in the build area rather than in an installed Python.

9.21. distutils.text_file — The TextFile class

This module provides the TextFile class, which gives an interface to text files that (optionally) takes care of stripping comments, ignoring blank lines, and joining lines with backslashes.

class distutils.text_file.TextFile([filename=None, file=None, **options])

This class provides a file-like object that takes care of all the things you commonly want to do when processing a text file that has some line-by-line syntax: strip comments (as long as # is your comment character), skip blank lines, join adjacent lines by escaping the newline (ie. backslash at end of line), strip leading and/or trailing whitespace. All of these are optional and independently controllable.

The class provides a warn() method so you can generate warning messages that report physical line number, even if the logical line in question spans multiple physical lines. Also provides unreadline() for implementing line-at-a-time lookahead.

TextFile instances are create with either filename, file, or both. RuntimeError is raised if both are None. filename should be a string, and file a file object (or something that provides readline() and close() methods). It is recommended that you supply at least filename, so that TextFile can include it in warning messages. If file is not supplied, TextFile creates its own using the open() built-in function.

The options are all boolean, and affect the values returned by readline()

option name

description

default

strip_comments

strip from '#' to end-of-line, as well as any whitespace leading up to the '#'—unless it is escaped by a backslash

true

lstrip_ws

strip leading whitespace from each line before returning it

false

rstrip_ws

strip trailing whitespace (including line terminator!) from each line before returning it.

true

skip_blanks

skip lines that are empty *after* stripping comments and whitespace. (If both lstrip_ws and rstrip_ws are false, then some lines may consist of solely whitespace: these will *not* be skipped, even if skip_blanks is true.)

true

join_lines

if a backslash is the last non-newline character on a line after stripping comments and whitespace, join the following line to it to form one logical line; if N consecutive lines end with a backslash, then N+1 physical lines will be joined to form one logical line.

false

collapse_join

strip leading whitespace from lines that are joined to their predecessor; only matters if (join_lines and not lstrip_ws)

false

Note that since rstrip_ws can strip the trailing newline, the semantics of readline() must differ from those of the built-in file object’s readline() method! In particular, readline() returns None for end-of-file: an empty string might just be a blank line (or an all-whitespace line), if rstrip_ws is true but skip_blanks is not.

open(filename)

Open a new file filename. This overrides any file or filename constructor arguments.

close()

Close the current file and forget everything we know about it (including the filename and the current line number).

warn(msg[, line=None])

Print (to stderr) a warning message tied to the current logical line in the current file. If the current logical line in the file spans multiple physical lines, the warning refers to the whole range, such as "lines 3-5". If line is supplied, it overrides the current line number; it may be a list or tuple to indicate a range of physical lines, or an integer for a single physical line.

readline()

Read and return a single logical line from the current file (or from an internal buffer if lines have previously been “unread” with unreadline()). If the join_lines option is true, this may involve reading multiple physical lines concatenated into a single string. Updates the current line number, so calling warn() after readline() emits a warning about the physical line(s) just read. Returns None on end-of-file, since the empty string can occur if rstrip_ws is true but strip_blanks is not.

readlines()

Read and return the list of all logical lines remaining in the current file. This updates the current line number to the last line of the file.

unreadline(line)

Push line (a string) onto an internal buffer that will be checked by future readline() calls. Handy for implementing a parser with line-at-a-time lookahead. Note that lines that are “unread” with unreadline() are not subsequently re-cleansed (whitespace stripped, or whatever) when read with readline(). If multiple calls are made to unreadline() before a call to readline(), the lines will be returned most in most recent first order.

9.22. distutils.version — Version number classes

9.23. distutils.cmd — Abstract base class for Distutils commands

This module supplies the abstract base class Command.

class distutils.cmd.Command(dist)

Abstract base class for defining command classes, the “worker bees” of the Distutils. A useful analogy for command classes is to think of them as subroutines with local variables called options. The options are declared in initialize_options() and defined (given their final values) in finalize_options(), both of which must be defined by every command class. The distinction between the two is necessary because option values might come from the outside world (command line, config file, …), and any options dependent on other options must be computed after these outside influences have been processed — hence finalize_options(). The body of the subroutine, where it does all its work based on the values of its options, is the run() method, which must also be implemented by every command class.

The class constructor takes a single argument dist, a Distribution instance.

9.24. Creating a new Distutils command

This section outlines the steps to create a new Distutils command.

A new command lives in a module in the distutils.command package. There is a sample template in that directory called command_template. Copy this file to a new module with the same name as the new command you’re implementing. This module should implement a class with the same name as the module (and the command). So, for instance, to create the command peel_banana (so that users can run setup.py peel_banana), you’d copy command_template to distutils/command/peel_banana.py, then edit it so that it’s implementing the class peel_banana, a subclass of distutils.cmd.Command.

Subclasses of Command must define the following methods.

Command.initialize_options()

Set default values for all the options that this command supports. Note that these defaults may be overridden by other commands, by the setup script, by config files, or by the command-line. Thus, this is not the place to code dependencies between options; generally, initialize_options() implementations are just a bunch of self.foo = None assignments.

Command.finalize_options()

Set final values for all the options that this command supports. This is always called as late as possible, ie. after any option assignments from the command-line or from other commands have been done. Thus, this is the place to code option dependencies: if foo depends on bar, then it is safe to set foo from bar as long as foo still has the same value it was assigned in initialize_options().

Command.run()

A command’s raison d’etre: carry out the action it exists to perform, controlled by the options initialized in initialize_options(), customized by other commands, the setup script, the command-line, and config files, and finalized in finalize_options(). All terminal output and filesystem interaction should be done by run().

Command.sub_commands

sub_commands formalizes the notion of a “family” of commands, e.g. install as the parent with sub-commands install_lib, install_headers, etc. The parent of a family of commands defines sub_commands as a class attribute; it’s a list of 2-tuples (command_name, predicate), with command_name a string and predicate a function, a string or None. predicate is a method of the parent command that determines whether the corresponding command is applicable in the current situation. (E.g. install_headers is only applicable if we have any C header files to install.) If predicate is None, that command is always applicable.

sub_commands is usually defined at the end of a class, because predicates can be methods of the class, so they must already have been defined. The canonical example is the install command.

9.25. distutils.command — Individual Distutils commands

9.26. distutils.command.bdist — Build a binary installer

9.27. distutils.command.bdist_packager — Abstract base class for packagers

9.28. distutils.command.bdist_dumb — Build a “dumb” installer

9.29. distutils.command.bdist_msi — Build a Microsoft Installer binary package

class distutils.command.bdist_msi.bdist_msi

Builds a Windows Installer [https://msdn.microsoft.com/en-us/library/cc185688(VS.85).aspx] (.msi) binary package.

In most cases, the bdist_msi installer is a better choice than the bdist_wininst installer, because it provides better support for Win64 platforms, allows administrators to perform non-interactive installations, and allows installation through group policies.

9.30. distutils.command.bdist_rpm — Build a binary distribution as a Redhat RPM and SRPM

9.31. distutils.command.bdist_wininst — Build a Windows installer

9.32. distutils.command.sdist — Build a source distribution

9.33. distutils.command.build — Build all files of a package

9.34. distutils.command.build_clib — Build any C libraries in a package

9.35. distutils.command.build_ext — Build any extensions in a package

9.36. distutils.command.build_py — Build the .py/.pyc files of a package

class distutils.command.build_py.build_py

class distutils.command.build_py.build_py_2to3

Alternative implementation of build_py which also runs the 2to3 conversion library on each .py file that is going to be installed. To use this in a setup.py file for a distribution that is designed to run with both Python 2.x and 3.x, add:

try:
    from distutils.command.build_py import build_py_2to3 as build_py
except ImportError:
    from distutils.command.build_py import build_py

to your setup.py, and later:

cmdclass = {'build_py': build_py}

to the invocation of setup().

9.37. distutils.command.build_scripts — Build the scripts of a package

9.38. distutils.command.clean — Clean a package build area

This command removes the temporary files created by build and its subcommands, like intermediary compiled object files. With the --all option, the complete build directory will be removed.

Extension modules built in place will not be cleaned, as they are not in the build directory.

9.39. distutils.command.config — Perform package configuration

9.40. distutils.command.install — Install a package

9.41. distutils.command.install_data — Install data files from a package

9.42. distutils.command.install_headers — Install C/C++ header files from a package

9.43. distutils.command.install_lib — Install library files from a package

9.44. distutils.command.install_scripts — Install script files from a package

9.45. distutils.command.register — Register a module with the Python Package Index

The register command registers the package with the Python Package Index. This is described in more detail in PEP 301 [https://www.python.org/dev/peps/pep-0301].

9.46. distutils.command.check — Check the meta-data of a package

The check command performs some tests on the meta-data of a package. For example, it verifies that all required meta-data are provided as the arguments passed to the setup() function.

탐색

색인

모듈 |

다음 |

이전 |

Python »

3.7.17 Documentation »

파이썬 모듈 배포 (레거시 버전) »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

이전 |

Python »

3.7.17 Documentation »

|

파이썬 모듈 설치 (레거시 버전)

Author

Greg Ward

더 보기

파이썬 모듈 설치하기

The up to date module installation documentations

This document describes the Python Distribution Utilities (“Distutils”) from the end-user’s point-of-view, describing how to extend the capabilities of a standard Python installation by building and installing third-party Python modules and extensions.

참고

This guide only covers the basic tools for building and distributing extensions that are provided as part of this version of Python. Third party tools offer easier to use and more secure alternatives. Refer to the quick recommendations section [https://packaging.python.org/guides/tool-recommendations/] in the Python Packaging User Guide for more information.

Introduction

Although Python’s extensive standard library covers many programming needs, there often comes a time when you need to add some new functionality to your Python installation in the form of third-party modules. This might be necessary to support your own programming, or to support an application that you want to use and that happens to be written in Python.

In the past, there has been little support for adding third-party modules to an existing Python installation. With the introduction of the Python Distribution Utilities (Distutils for short) in Python 2.0, this changed.

This document is aimed primarily at the people who need to install third-party Python modules: end-users and system administrators who just need to get some Python application running, and existing Python programmers who want to add some new goodies to their toolbox. You don’t need to know Python to read this document; there will be some brief forays into using Python’s interactive mode to explore your installation, but that’s it. If you’re looking for information on how to distribute your own Python modules so that others may use them, see the 파이썬 모듈 배포 (레거시 버전) manual. Debugging the setup script may also be of interest.

Best case: trivial installation

In the best case, someone will have prepared a special version of the module distribution you want to install that is targeted specifically at your platform and is installed just like any other software on your platform. For example, the module developer might make an executable installer available for Windows users, an RPM package for users of RPM-based Linux systems (Red Hat, SuSE, Mandrake, and many others), a Debian package for users of Debian-based Linux systems, and so forth.

In that case, you would download the installer appropriate to your platform and do the obvious thing with it: run it if it’s an executable installer, rpm --install it if it’s an RPM, etc. You don’t need to run Python or a setup script, you don’t need to compile anything—you might not even need to read any instructions (although it’s always a good idea to do so anyway).

Of course, things will not always be that easy. You might be interested in a module distribution that doesn’t have an easy-to-use installer for your platform. In that case, you’ll have to start with the source distribution released by the module’s author/maintainer. Installing from a source distribution is not too hard, as long as the modules are packaged in the standard way. The bulk of this document is about building and installing modules from standard source distributions.

The new standard: Distutils

If you download a module source distribution, you can tell pretty quickly if it was packaged and distributed in the standard way, i.e. using the Distutils. First, the distribution’s name and version number will be featured prominently in the name of the downloaded archive, e.g. foo-1.0.tar.gz or widget-0.9.7.zip. Next, the archive will unpack into a similarly-named directory: foo-1.0 or widget-0.9.7. Additionally, the distribution will contain a setup script setup.py, and a file named README.txt or possibly just README, which should explain that building and installing the module distribution is a simple matter of running one command from a terminal:

python setup.py install

For Windows, this command should be run from a command prompt window (Start ‣ Accessories):

setup.py install

If all these things are true, then you already know how to build and install the modules you’ve just downloaded: Run the command above. Unless you need to install things in a non-standard way or customize the build process, you don’t really need this manual. Or rather, the above command is everything you need to get out of this manual.

Standard Build and Install

As described in section The new standard: Distutils, building and installing a module distribution using the Distutils is usually one simple command to run from a terminal:

python setup.py install

Platform variations

You should always run the setup command from the distribution root directory, i.e. the top-level subdirectory that the module source distribution unpacks into. For example, if you’ve just downloaded a module source distribution foo-1.0.tar.gz onto a Unix system, the normal thing to do is:

gunzip -c foo-1.0.tar.gz | tar xf -    # unpacks into directory foo-1.0
cd foo-1.0
python setup.py install

On Windows, you’d probably download foo-1.0.zip. If you downloaded the archive file to C:\Temp, then it would unpack into C:\Temp\foo-1.0; you can use either an archive manipulator with a graphical user interface (such as WinZip) or a command-line tool (such as unzip or pkunzip) to unpack the archive. Then, open a command prompt window and run:

cd c:\Temp\foo-1.0
python setup.py install

Splitting the job up

Running setup.py install builds and installs all modules in one run. If you prefer to work incrementally—especially useful if you want to customize the build process, or if things are going wrong—you can use the setup script to do one thing at a time. This is particularly helpful when the build and install will be done by different users—for example, you might want to build a module distribution and hand it off to a system administrator for installation (or do it yourself, with super-user privileges).

For example, you can build everything in one step, and then install everything in a second step, by invoking the setup script twice:

python setup.py build
python setup.py install

If you do this, you will notice that running the install command first runs the build command, which—in this case—quickly notices that it has nothing to do, since everything in the build directory is up-to-date.

You may not need this ability to break things down often if all you do is install modules downloaded off the ‘net, but it’s very handy for more advanced tasks. If you get into distributing your own Python modules and extensions, you’ll run lots of individual Distutils commands on their own.

How building works

As implied above, the build command is responsible for putting the files to install into a build directory. By default, this is build under the distribution root; if you’re excessively concerned with speed, or want to keep the source tree pristine, you can change the build directory with the --build-base option. For example:

python setup.py build --build-base=/path/to/pybuild/foo-1.0

(Or you could do this permanently with a directive in your system or personal Distutils configuration file; see section Distutils Configuration Files.) Normally, this isn’t necessary.

The default layout for the build tree is as follows:

--- build/ --- lib/
or
--- build/ --- lib.<plat>/
               temp.<plat>/

where <plat> expands to a brief description of the current OS/hardware platform and Python version. The first form, with just a lib directory, is used for “pure module distributions”—that is, module distributions that include only pure Python modules. If a module distribution contains any extensions (modules written in C/C++), then the second form, with two <plat> directories, is used. In that case, the temp.plat directory holds temporary files generated by the compile/link process that don’t actually get installed. In either case, the lib (or lib.plat) directory contains all Python modules (pure Python and extensions) that will be installed.

In the future, more directories will be added to handle Python scripts, documentation, binary executables, and whatever else is needed to handle the job of installing Python modules and applications.

How installation works

After the build command runs (whether you run it explicitly, or the install command does it for you), the work of the install command is relatively simple: all it has to do is copy everything under build/lib (or build/lib.plat) to your chosen installation directory.

If you don’t choose an installation directory—i.e., if you just run setup.py install—then the install command installs to the standard location for third-party Python modules. This location varies by platform and by how you built/installed Python itself. On Unix (and Mac OS X, which is also Unix-based), it also depends on whether the module distribution being installed is pure Python or contains extensions (“non-pure”):

Platform

Standard installation location

Default value

Notes

Unix (pure)

prefix/lib/pythonX.Y/site-packages

/usr/local/lib/pythonX.Y/site-packages

(1)

Unix (non-pure)

exec-prefix/lib/pythonX.Y/site-packages

/usr/local/lib/pythonX.Y/site-packages

(1)

Windows

prefix\Lib\site-packages

C:\PythonXY\Lib\site-packages

(2)

Notes:

Most Linux distributions include Python as a standard part of the system, so prefix and exec-prefix are usually both /usr on Linux. If you build Python yourself on Linux (or any Unix-like system), the default prefix and exec-prefix are /usr/local.

The default installation directory on Windows was C:\Program Files\Python under Python 1.6a1, 1.5.2, and earlier.

prefix and exec-prefix stand for the directories that Python is installed to, and where it finds its libraries at run-time. They are always the same under Windows, and very often the same under Unix and Mac OS X. You can find out what your Python installation uses for prefix and exec-prefix by running Python in interactive mode and typing a few simple commands. Under Unix, just type python at the shell prompt. Under Windows, choose Start ‣ Programs ‣ Python X.Y ‣ Python (command line). Once the interpreter is started, you type Python code at the prompt. For example, on my Linux system, I type the three Python statements shown below, and get the output as shown, to find out my prefix and exec-prefix:

Python 2.4 (#26, Aug  7 2004, 17:19:02)
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.prefix
'/usr'
>>> sys.exec_prefix
'/usr'

A few other placeholders are used in this document: X.Y stands for the version of Python, for example 3.2; abiflags will be replaced by the value of sys.abiflags or the empty string for platforms which don’t define ABI flags; distname will be replaced by the name of the module distribution being installed. Dots and capitalization are important in the paths; for example, a value that uses python3.2 on UNIX will typically use Python32 on Windows.

If you don’t want to install modules to the standard location, or if you don’t have permission to write there, then you need to read about alternate installations in section Alternate Installation. If you want to customize your installation directories more heavily, see section Custom Installation on custom installations.

Alternate Installation

Often, it is necessary or desirable to install modules to a location other than the standard location for third-party Python modules. For example, on a Unix system you might not have permission to write to the standard third-party module directory. Or you might wish to try out a module before making it a standard part of your local Python installation. This is especially true when upgrading a distribution already present: you want to make sure your existing base of scripts still works with the new version before actually upgrading.

The Distutils install command is designed to make installing module distributions to an alternate location simple and painless. The basic idea is that you supply a base directory for the installation, and the install command picks a set of directories (called an installation scheme) under this base directory in which to install files. The details differ across platforms, so read whichever of the following sections applies to you.

Note that the various alternate installation schemes are mutually exclusive: you can pass --user, or --home, or --prefix and --exec-prefix, or --install-base and --install-platbase, but you can’t mix from these groups.

Alternate installation: the user scheme

This scheme is designed to be the most convenient solution for users that don’t have write permission to the global site-packages directory or don’t want to install into it. It is enabled with a simple option:

python setup.py install --user

Files will be installed into subdirectories of site.USER_BASE (written as userbase hereafter). This scheme installs pure Python modules and extension modules in the same location (also known as site.USER_SITE). Here are the values for UNIX, including Mac OS X:

Type of file

Installation directory

modules

userbase/lib/pythonX.Y/site-packages

scripts

userbase/bin

data

userbase

C headers

userbase/include/pythonX.Yabiflags/distname

And here are the values used on Windows:

Type of file

Installation directory

modules

userbase\PythonXY\site-packages

scripts

userbase\PythonXY\Scripts

data

userbase

C headers

userbase\PythonXY\Include{distname}

The advantage of using this scheme compared to the other ones described below is that the user site-packages directory is under normal conditions always included in sys.path (see site for more information), which means that there is no additional step to perform after running the setup.py script to finalize the installation.

The build_ext command also has a --user option to add userbase/include to the compiler search path for header files and userbase/lib to the compiler search path for libraries as well as to the runtime search path for shared C libraries (rpath).

Alternate installation: the home scheme

The idea behind the “home scheme” is that you build and maintain a personal stash of Python modules. This scheme’s name is derived from the idea of a “home” directory on Unix, since it’s not unusual for a Unix user to make their home directory have a layout similar to /usr/ or /usr/local/. This scheme can be used by anyone, regardless of the operating system they are installing for.

Installing a new module distribution is as simple as

python setup.py install --home=<dir>

where you can supply any directory you like for the --home option. On Unix, lazy typists can just type a tilde (~); the install command will expand this to your home directory:

python setup.py install --home=~

To make Python find the distributions installed with this scheme, you may have to modify Python’s search path or edit sitecustomize (see site) to call site.addsitedir() or edit sys.path.

The --home option defines the installation base directory. Files are installed to the following directories under the installation base as follows:

Type of file

Installation directory

modules

home/lib/python

scripts

home/bin

data

home

C headers

home/include/python/distname

(Mentally replace slashes with backslashes if you’re on Windows.)

Alternate installation: Unix (the prefix scheme)

The “prefix scheme” is useful when you wish to use one Python installation to perform the build/install (i.e., to run the setup script), but install modules into the third-party module directory of a different Python installation (or something that looks like a different Python installation). If this sounds a trifle unusual, it is—that’s why the user and home schemes come before. However, there are at least two known cases where the prefix scheme will be useful.

First, consider that many Linux distributions put Python in /usr, rather than the more traditional /usr/local. This is entirely appropriate, since in those cases Python is part of “the system” rather than a local add-on. However, if you are installing Python modules from source, you probably want them to go in /usr/local/lib/python2.X rather than /usr/lib/python2.X. This can be done with

/usr/bin/python setup.py install --prefix=/usr/local

Another possibility is a network filesystem where the name used to write to a remote directory is different from the name used to read it: for example, the Python interpreter accessed as /usr/local/bin/python might search for modules in /usr/local/lib/python2.X, but those modules would have to be installed to, say, /mnt/@server/export/lib/python2.X. This could be done with

/usr/local/bin/python setup.py install --prefix=/mnt/@server/export

In either case, the --prefix option defines the installation base, and the --exec-prefix option defines the platform-specific installation base, which is used for platform-specific files. (Currently, this just means non-pure module distributions, but could be expanded to C libraries, binary executables, etc.) If --exec-prefix is not supplied, it defaults to --prefix. Files are installed as follows:

Type of file

Installation directory

Python modules

prefix/lib/pythonX.Y/site-packages

extension modules

exec-prefix/lib/pythonX.Y/site-packages

scripts

prefix/bin

data

prefix

C headers

prefix/include/pythonX.Yabiflags/distname

There is no requirement that --prefix or --exec-prefix actually point to an alternate Python installation; if the directories listed above do not already exist, they are created at installation time.

Incidentally, the real reason the prefix scheme is important is simply that a standard Unix installation uses the prefix scheme, but with --prefix and --exec-prefix supplied by Python itself as sys.prefix and sys.exec_prefix. Thus, you might think you’ll never use the prefix scheme, but every time you run python setup.py install without any other options, you’re using it.

Note that installing extensions to an alternate Python installation has no effect on how those extensions are built: in particular, the Python header files (Python.h and friends) installed with the Python interpreter used to run the setup script will be used in compiling extensions. It is your responsibility to ensure that the interpreter used to run extensions installed in this way is compatible with the interpreter used to build them. The best way to do this is to ensure that the two interpreters are the same version of Python (possibly different builds, or possibly copies of the same build). (Of course, if your --prefix and --exec-prefix don’t even point to an alternate Python installation, this is immaterial.)

Alternate installation: Windows (the prefix scheme)

Windows has no concept of a user’s home directory, and since the standard Python installation under Windows is simpler than under Unix, the --prefix option has traditionally been used to install additional packages in separate locations on Windows.

python setup.py install --prefix="\Temp\Python"

to install modules to the \Temp\Python directory on the current drive.

The installation base is defined by the --prefix option; the --exec-prefix option is not supported under Windows, which means that pure Python modules and extension modules are installed into the same location. Files are installed as follows:

Type of file

Installation directory

modules

prefix\Lib\site-packages

scripts

prefix\Scripts

data

prefix

C headers

prefix\Include{distname}

Custom Installation

Sometimes, the alternate installation schemes described in section Alternate Installation just don’t do what you want. You might want to tweak just one or two directories while keeping everything under the same base directory, or you might want to completely redefine the installation scheme. In either case, you’re creating a custom installation scheme.

To create a custom installation scheme, you start with one of the alternate schemes and override some of the installation directories used for the various types of files, using these options:

Type of file

Override option

Python modules

--install-purelib

extension modules

--install-platlib

all modules

--install-lib

scripts

--install-scripts

data

--install-data

C headers

--install-headers

These override options can be relative, absolute, or explicitly defined in terms of one of the installation base directories. (There are two installation base directories, and they are normally the same—they only differ when you use the Unix “prefix scheme” and supply different --prefix and --exec-prefix options; using --install-lib will override values computed or given for --install-purelib and --install-platlib, and is recommended for schemes that don’t make a difference between Python and extension modules.)

For example, say you’re installing a module distribution to your home directory under Unix—but you want scripts to go in ~/scripts rather than ~/bin. As you might expect, you can override this directory with the --install-scripts option; in this case, it makes most sense to supply a relative path, which will be interpreted relative to the installation base directory (your home directory, in this case):

python setup.py install --home=~ --install-scripts=scripts

Another Unix example: suppose your Python installation was built and installed with a prefix of /usr/local/python, so under a standard installation scripts will wind up in /usr/local/python/bin. If you want them in /usr/local/bin instead, you would supply this absolute directory for the --install-scripts option:

python setup.py install --install-scripts=/usr/local/bin

(This performs an installation using the “prefix scheme”, where the prefix is whatever your Python interpreter was installed with— /usr/local/python in this case.)

If you maintain Python on Windows, you might want third-party modules to live in a subdirectory of prefix, rather than right in prefix itself. This is almost as easy as customizing the script installation directory—you just have to remember that there are two types of modules to worry about, Python and extension modules, which can conveniently be both controlled by one option:

python setup.py install --install-lib=Site

The specified installation directory is relative to prefix. Of course, you also have to ensure that this directory is in Python’s module search path, such as by putting a .pth file in a site directory (see site). See section Modifying Python’s Search Path to find out how to modify Python’s search path.

If you want to define an entire installation scheme, you just have to supply all of the installation directory options. The recommended way to do this is to supply relative paths; for example, if you want to maintain all Python module-related files under python in your home directory, and you want a separate directory for each platform that you use your home directory from, you might define the following installation scheme:

python setup.py install --home=~ \
                        --install-purelib=python/lib \
                        --install-platlib=python/lib.$PLAT \
                        --install-scripts=python/scripts
                        --install-data=python/data

or, equivalently,

python setup.py install --home=~/python \
                        --install-purelib=lib \
                        --install-platlib='lib.$PLAT' \
                        --install-scripts=scripts
                        --install-data=data

$PLAT is not (necessarily) an environment variable—it will be expanded by the Distutils as it parses your command line options, just as it does when parsing your configuration file(s).

Obviously, specifying the entire installation scheme every time you install a new module distribution would be very tedious. Thus, you can put these options into your Distutils config file (see section Distutils Configuration Files):

[install]
install-base=$HOME
install-purelib=python/lib
install-platlib=python/lib.$PLAT
install-scripts=python/scripts
install-data=python/data

or, equivalently,

[install]
install-base=$HOME/python
install-purelib=lib
install-platlib=lib.$PLAT
install-scripts=scripts
install-data=data

Note that these two are not equivalent if you supply a different installation base directory when you run the setup script. For example,

python setup.py install --install-base=/tmp

would install pure modules to /tmp/python/lib in the first case, and to /tmp/lib in the second case. (For the second case, you probably want to supply an installation base of /tmp/python.)

You probably noticed the use of $HOME and $PLAT in the sample configuration file input. These are Distutils configuration variables, which bear a strong resemblance to environment variables. In fact, you can use environment variables in config files on platforms that have such a notion but the Distutils additionally define a few extra variables that may not be in your environment, such as $PLAT. (And of course, on systems that don’t have environment variables, such as Mac OS 9, the configuration variables supplied by the Distutils are the only ones you can use.) See section Distutils Configuration Files for details.

참고

When a virtual environment is activated, any options that change the installation path will be ignored from all distutils configuration files to prevent inadvertently installing projects outside of the virtual environment.

Modifying Python’s Search Path

When the Python interpreter executes an import statement, it searches for both Python code and extension modules along a search path. A default value for the path is configured into the Python binary when the interpreter is built. You can determine the path by importing the sys module and printing the value of sys.path.

$ python
Python 2.2 (#11, Oct  3 2002, 13:31:27)
[GCC 2.96 20000731 (Red Hat Linux 7.3 2.96-112)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.path
['', '/usr/local/lib/python2.3', '/usr/local/lib/python2.3/plat-linux2',
 '/usr/local/lib/python2.3/lib-tk', '/usr/local/lib/python2.3/lib-dynload',
 '/usr/local/lib/python2.3/site-packages']
>>>

The null string in sys.path represents the current working directory.

The expected convention for locally installed packages is to put them in the …/site-packages/ directory, but you may want to install Python modules into some arbitrary directory. For example, your site may have a convention of keeping all software related to the web server under /www. Add-on Python modules might then belong in /www/python, and in order to import them, this directory must be added to sys.path. There are several different ways to add the directory.

The most convenient way is to add a path configuration file to a directory that’s already on Python’s path, usually to the .../site-packages/ directory. Path configuration files have an extension of .pth, and each line must contain a single path that will be appended to sys.path. (Because the new paths are appended to sys.path, modules in the added directories will not override standard modules. This means you can’t use this mechanism for installing fixed versions of standard modules.)

Paths can be absolute or relative, in which case they’re relative to the directory containing the .pth file. See the documentation of the site module for more information.

A slightly less convenient way is to edit the site.py file in Python’s standard library, and modify sys.path. site.py is automatically imported when the Python interpreter is executed, unless the -S switch is supplied to suppress this behaviour. So you could simply edit site.py and add two lines to it:

import sys
sys.path.append('/www/python/')

However, if you reinstall the same major version of Python (perhaps when upgrading from 2.2 to 2.2.2, for example) site.py will be overwritten by the stock version. You’d have to remember that it was modified and save a copy before doing the installation.

There are two environment variables that can modify sys.path. PYTHONHOME sets an alternate value for the prefix of the Python installation. For example, if PYTHONHOME is set to /www/python, the search path will be set to ['', '/www/python/lib/pythonX.Y/', '/www/python/lib/pythonX.Y/plat-linux2', ...].

The PYTHONPATH variable can be set to a list of paths that will be added to the beginning of sys.path. For example, if PYTHONPATH is set to /www/python:/opt/py, the search path will begin with ['/www/python', '/opt/py']. (Note that directories must exist in order to be added to sys.path; the site module removes paths that don’t exist.)

Finally, sys.path is just a regular Python list, so any Python application can modify it by adding or removing entries.

Distutils Configuration Files

As mentioned above, you can use Distutils configuration files to record personal or site preferences for any Distutils options. That is, any option to any command can be stored in one of two or three (depending on your platform) configuration files, which will be consulted before the command-line is parsed. This means that configuration files will override default values, and the command-line will in turn override configuration files. Furthermore, if multiple configuration files apply, values from “earlier” files are overridden by “later” files.

Location and names of config files

The names and locations of the configuration files vary slightly across platforms. On Unix and Mac OS X, the three configuration files (in the order they are processed) are:

Type of file

Location and filename

Notes

system

prefix/lib/pythonver/distutils/distutils.cfg

(1)

personal

$HOME/.pydistutils.cfg

(2)

local

setup.cfg

(3)

And on Windows, the configuration files are:

Type of file

Location and filename

Notes

system

prefix\Lib\distutils\distutils.cfg

(4)

personal

%HOME%\pydistutils.cfg

(5)

local

setup.cfg

(3)

On all platforms, the “personal” file can be temporarily disabled by passing the –no-user-cfg option.

Notes:

Strictly speaking, the system-wide configuration file lives in the directory where the Distutils are installed; under Python 1.6 and later on Unix, this is as shown. For Python 1.5.2, the Distutils will normally be installed to prefix/lib/python1.5/site-packages/distutils, so the system configuration file should be put there under Python 1.5.2.

On Unix, if the HOME environment variable is not defined, the user’s home directory will be determined with the getpwuid() function from the standard pwd module. This is done by the os.path.expanduser() function used by Distutils.

I.e., in the current directory (usually the location of the setup script).

(See also note (1).) Under Python 1.6 and later, Python’s default “installation prefix” is C:\Python, so the system configuration file is normally C:\Python\Lib\distutils\distutils.cfg. Under Python 1.5.2, the default prefix was C:\Program Files\Python, and the Distutils were not part of the standard library—so the system configuration file would be C:\Program Files\Python\distutils\distutils.cfg in a standard Python 1.5.2 installation under Windows.

On Windows, if the HOME environment variable is not defined, USERPROFILE then HOMEDRIVE and HOMEPATH will be tried. This is done by the os.path.expanduser() function used by Distutils.

Syntax of config files

The Distutils configuration files all have the same syntax. The config files are grouped into sections. There is one section for each Distutils command, plus a global section for global options that affect every command. Each section consists of one option per line, specified as option=value.

For example, the following is a complete config file that just forces all commands to run quietly by default:

[global]
verbose=0

If this is installed as the system config file, it will affect all processing of any Python module distribution by any user on the current system. If it is installed as your personal config file (on systems that support them), it will affect only module distributions processed by you. And if it is used as the setup.cfg for a particular module distribution, it affects only that distribution.

You could override the default “build base” directory and make the build* commands always forcibly rebuild all files with the following:

[build]
build-base=blib
force=1

which corresponds to the command-line arguments

python setup.py build --build-base=blib --force

except that including the build command on the command-line means that command will be run. Including a particular command in config files has no such implication; it only means that if the command is run, the options in the config file will apply. (Or if other commands that derive values from it are run, they will use the values in the config file.)

You can find out the complete list of options for any command using the --help option, e.g.:

python setup.py build --help

and you can find out the complete list of global options by using --help without a command:

python setup.py --help

See also the “Reference” section of the “Distributing Python Modules” manual.

Building Extensions: Tips and Tricks

Whenever possible, the Distutils try to use the configuration information made available by the Python interpreter used to run the setup.py script. For example, the same compiler and linker flags used to compile Python will also be used for compiling extensions. Usually this will work well, but in complicated situations this might be inappropriate. This section discusses how to override the usual Distutils behaviour.

Tweaking compiler/linker flags

Compiling a Python extension written in C or C++ will sometimes require specifying custom flags for the compiler and linker in order to use a particular library or produce a special kind of object code. This is especially true if the extension hasn’t been tested on your platform, or if you’re trying to cross-compile Python.

In the most general case, the extension author might have foreseen that compiling the extensions would be complicated, and provided a Setup file for you to edit. This will likely only be done if the module distribution contains many separate extension modules, or if they often require elaborate sets of compiler flags in order to work.

A Setup file, if present, is parsed in order to get a list of extensions to build. Each line in a Setup describes a single module. Lines have the following structure:

module ... [sourcefile ...] [cpparg ...] [library ...]

Let’s examine each of the fields in turn.

module is the name of the extension module to be built, and should be a valid Python identifier. You can’t just change this in order to rename a module (edits to the source code would also be needed), so this should be left alone.

sourcefile is anything that’s likely to be a source code file, at least judging by the filename. Filenames ending in .c are assumed to be written in C, filenames ending in .C, .cc, and .c++ are assumed to be C++, and filenames ending in .m or .mm are assumed to be in Objective C.

cpparg is an argument for the C preprocessor, and is anything starting with -I, -D, -U or -C.

library is anything ending in .a or beginning with -l or -L.

If a particular platform requires a special library on your platform, you can add it by editing the Setup file and running python setup.py build. For example, if the module defined by the line

foo foomodule.c

must be linked with the math library libm.a on your platform, simply add -lm to the line:

foo foomodule.c -lm

Arbitrary switches intended for the compiler or the linker can be supplied with the -Xcompiler arg and -Xlinker arg options:

foo foomodule.c -Xcompiler -o32 -Xlinker -shared -lm

The next option after -Xcompiler and -Xlinker will be appended to the proper command line, so in the above example the compiler will be passed the -o32 option, and the linker will be passed -shared. If a compiler option requires an argument, you’ll have to supply multiple -Xcompiler options; for example, to pass -x c++ the Setup file would have to contain -Xcompiler -x -Xcompiler c++.

Compiler flags can also be supplied through setting the CFLAGS environment variable. If set, the contents of CFLAGS will be added to the compiler flags specified in the Setup file.

Using non-Microsoft compilers on Windows

Borland/CodeGear C++

This subsection describes the necessary steps to use Distutils with the Borland C++ compiler version 5.5. First you have to know that Borland’s object file format (OMF) is different from the format used by the Python version you can download from the Python or ActiveState Web site. (Python is built with Microsoft Visual C++, which uses COFF as the object file format.) For this reason you have to convert Python’s library python25.lib into the Borland format. You can do this as follows:

coff2omf python25.lib python25_bcpp.lib

The coff2omf program comes with the Borland compiler. The file python25.lib is in the Libs directory of your Python installation. If your extension uses other libraries (zlib, …) you have to convert them too.

The converted files have to reside in the same directories as the normal libraries.

How does Distutils manage to use these libraries with their changed names? If the extension needs a library (eg. foo) Distutils checks first if it finds a library with suffix _bcpp (eg. foo_bcpp.lib) and then uses this library. In the case it doesn’t find such a special library it uses the default name (foo.lib.) 1

To let Distutils compile your extension with Borland C++ you now have to type:

python setup.py build --compiler=bcpp

If you want to use the Borland C++ compiler as the default, you could specify this in your personal or system-wide configuration file for Distutils (see section Distutils Configuration Files.)

더 보기

C++Builder Compiler [https://www.embarcadero.com/products]

Information about the free C++ compiler from Borland, including links to the download pages.

Creating Python Extensions Using Borland’s Free Compiler [http://www.cyberus.ca/~g_will/pyExtenDL.shtml]

Document describing how to use Borland’s free command-line C++ compiler to build Python.

GNU C / Cygwin / MinGW

This section describes the necessary steps to use Distutils with the GNU C/C++ compilers in their Cygwin and MinGW distributions. 2 For a Python interpreter that was built with Cygwin, everything should work without any of these following steps.

Not all extensions can be built with MinGW or Cygwin, but many can. Extensions most likely to not work are those that use C++ or depend on Microsoft Visual C extensions.

To let Distutils compile your extension with Cygwin you have to type:

python setup.py build --compiler=cygwin

and for Cygwin in no-cygwin mode 3 or for MinGW type:

python setup.py build --compiler=mingw32

If you want to use any of these options/compilers as default, you should consider writing it in your personal or system-wide configuration file for Distutils (see section Distutils Configuration Files.)

Older Versions of Python and MinGW

The following instructions only apply if you’re using a version of Python inferior to 2.4.1 with a MinGW inferior to 3.0.0 (with binutils-2.13.90-20030111-1).

These compilers require some special libraries. This task is more complex than for Borland’s C++, because there is no program to convert the library. First you have to create a list of symbols which the Python DLL exports. (You can find a good program for this task at https://sourceforge.net/projects/mingw/files/MinGW/Extension/pexports/).

pexports python25.dll >python25.def

The location of an installed python25.dll will depend on the installation options and the version and language of Windows. In a “just for me” installation, it will appear in the root of the installation directory. In a shared installation, it will be located in the system directory.

Then you can create from these information an import library for gcc.

/cygwin/bin/dlltool --dllname python25.dll --def python25.def --output-lib libpython25.a

The resulting library has to be placed in the same directory as python25.lib. (Should be the libs directory under your Python installation directory.)

If your extension uses other libraries (zlib,…) you might have to convert them too. The converted files have to reside in the same directories as the normal libraries do.

더 보기

Building Python modules on MS Windows platform with MinGW [http://old.zope.org/Members/als/tips/win32_mingw_modules]

Information about building the required libraries for the MinGW environment.

Footnotes

1

This also means you could replace all existing COFF-libraries with OMF-libraries of the same name.

2

Check https://www.sourceware.org/cygwin/ and http://www.mingw.org/ for more information

3

Then you have no POSIX emulation available, but you also don’t need cygwin1.dll.

탐색

색인

모듈 |

이전 |

Python »

3.7.17 Documentation »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

Python »

3.7.17 Documentation »

|

Python 모듈 목록

_ | a | b | c | d | e | f | g | h | i | j | k | l | m | n | o | p | q | r | s | t | u | v | w | x | z

| _ |
| __future__ | Future statement definitions
| __main__ | The environment where the top-level script is run.
| _dummy_thread | Drop-in replacement for the _thread module.
| _thread | Low-level threading API.
| a |
| abc | Abstract base classes according to PEP 3119.
| aifc | Read and write audio files in AIFF or AIFC format.
| argparse | Command-line option and argument parsing library.
| array | Space efficient arrays of uniformly typed numeric values.
| ast | Abstract Syntax Tree classes and manipulation.
| asynchat | Support for asynchronous command/response protocols.
| asyncio | Asynchronous I/O.
| asyncore | A base class for developing asynchronous socket handling services.
| atexit | Register and execute cleanup functions.
| audioop | Manipulate raw audio data.
| b |
| base64 | RFC 3548: Base16, Base32, Base64 Data Encodings; Base85 and Ascii85
| bdb | Debugger framework.
| binascii | Tools for converting between binary and various ASCII-encoded binary representations.
| binhex | Encode and decode files in binhex4 format.
| bisect | Array bisection algorithms for binary searching.
| builtins | The module that provides the built-in namespace.
| bz2 | Interfaces for bzip2 compression and decompression.
| c |
| calendar | Functions for working with calendars, including some emulation of the Unix cal program.
| cgi | Helpers for running Python scripts via the Common Gateway Interface.
| cgitb | Configurable traceback handler for CGI scripts.
| chunk | Module to read IFF chunks.
| cmath | Mathematical functions for complex numbers.
| cmd | Build line-oriented command interpreters.
| code | Facilities to implement read-eval-print loops.
| codecs | Encode and decode data and streams.
| codeop | Compile (possibly incomplete) Python code.
- | collections | Container datatypes
|     collections.abc | Abstract base classes for containers
| colorsys | Conversion functions between RGB and other color systems.
| compileall | Tools for byte-compiling all Python source files in a directory tree.
- | concurrent |
|     concurrent.futures | Execute computations concurrently using threads or processes.
| configparser | Configuration file parser.
| contextlib | Utilities for with-statement contexts.
| contextvars | Context Variables
| copy | Shallow and deep copy operations.
| copyreg | Register pickle support functions.
| cProfile |
| crypt (Unix) | The crypt() function used to check Unix passwords.
| csv | Write and read tabular data to and from delimited files.
| ctypes | A foreign function library for Python.
- | curses (Unix) | An interface to the curses library, providing portable terminal handling.
|     curses.ascii | Constants and set-membership functions for ASCII characters.
|     curses.panel | A panel stack extension that adds depth to curses windows.
|     curses.textpad | Emacs-like input editing in a curses window.
| d |
| dataclasses | Generate special methods on user-defined classes.
| datetime | Basic date and time types.
- | dbm | Interfaces to various Unix "database" formats.
|     dbm.dumb | Portable implementation of the simple DBM interface.
|     dbm.gnu (Unix) | GNU's reinterpretation of dbm.
|     dbm.ndbm (Unix) | The standard "database" interface, based on ndbm.
| decimal | Implementation of the General Decimal Arithmetic Specification.
| difflib | Helpers for computing differences between objects.
| dis | Disassembler for Python bytecode.
- | distutils | Support for building and installing Python modules into an existing Python installation.
|     distutils.archive_util | Utility functions for creating archive files (tarballs, zip files, ...)
|     distutils.bcppcompiler |
|     distutils.ccompiler | Abstract CCompiler class
|     distutils.cmd | Provides the abstract base class :class:`~distutils.cmd.Command`. This class is subclassed by the modules in the distutils.command subpackage.
|     distutils.command | Contains one module for each standard Distutils command.
|     distutils.command.bdist | Build a binary installer for a package
|     distutils.command.bdist_dumb | Build a "dumb" installer - a simple archive of files
|     distutils.command.bdist_msi | Build a binary distribution as a Windows MSI file
|     distutils.command.bdist_packager | Abstract base class for packagers
|     distutils.command.bdist_rpm | Build a binary distribution as a Redhat RPM and SRPM
|     distutils.command.bdist_wininst | Build a Windows installer
|     distutils.command.build | Build all files of a package
|     distutils.command.build_clib | Build any C libraries in a package
|     distutils.command.build_ext | Build any extensions in a package
|     distutils.command.build_py | Build the .py/.pyc files of a package
|     distutils.command.build_scripts | Build the scripts of a package
|     distutils.command.check | Check the meta-data of a package
|     distutils.command.clean | Clean a package build area
|     distutils.command.config | Perform package configuration
|     distutils.command.install | Install a package
|     distutils.command.install_data | Install data files from a package
|     distutils.command.install_headers | Install C/C++ header files from a package
|     distutils.command.install_lib | Install library files from a package
|     distutils.command.install_scripts | Install script files from a package
|     distutils.command.register | Register a module with the Python Package Index
|     distutils.command.sdist | Build a source distribution
|     distutils.core | The core Distutils functionality
|     distutils.cygwinccompiler |
|     distutils.debug | Provides the debug flag for distutils
|     distutils.dep_util | Utility functions for simple dependency checking
|     distutils.dir_util | Utility functions for operating on directories and directory trees
|     distutils.dist | Provides the Distribution class, which represents the module distribution being built/installed/distributed
|     distutils.errors | Provides standard distutils exceptions
|     distutils.extension | Provides the Extension class, used to describe C/C++ extension modules in setup scripts
|     distutils.fancy_getopt | Additional getopt functionality
|     distutils.file_util | Utility functions for operating on single files
|     distutils.filelist | The FileList class, used for poking about the file system and building lists of files.
|     distutils.log | A simple logging mechanism, 282-style
|     distutils.msvccompiler | Microsoft Compiler
|     distutils.spawn | Provides the spawn() function
|     distutils.sysconfig | Low-level access to configuration information of the Python interpreter.
|     distutils.text_file | Provides the TextFile class, a simple interface to text files
|     distutils.unixccompiler | UNIX C Compiler
|     distutils.util | Miscellaneous other utility functions
|     distutils.version | Implements classes that represent module version numbers.
| doctest | Test pieces of code within docstrings.
| dummy_threading | Drop-in replacement for the threading module.
| e |
- | email | Package supporting the parsing, manipulating, and generating email messages.
|     email.charset | Character Sets
|     email.contentmanager | Storing and Retrieving Content from MIME Parts
|     email.encoders | Encoders for email message payloads.
|     email.errors | The exception classes used by the email package.
|     email.generator | Generate flat text email messages from a message structure.
|     email.header | Representing non-ASCII headers
|     email.headerregistry | Automatic Parsing of headers based on the field name
|     email.iterators | Iterate over a message object tree.
|     email.message | The base class representing email messages.
|     email.mime | Build MIME messages.
|     email.parser | Parse flat text email messages to produce a message object structure.
|     email.policy | Controlling the parsing and generating of messages
|     email.utils | Miscellaneous email package utilities.
- | encodings |
|     encodings.idna | Internationalized Domain Names implementation
|     encodings.mbcs | Windows ANSI codepage
|     encodings.utf_8_sig | UTF-8 codec with BOM signature
| ensurepip | Bootstrapping the "pip" installer into an existing Python installation or virtual environment.
| enum | Implementation of an enumeration class.
| errno | Standard errno system symbols.
| f |
| faulthandler | Dump the Python traceback.
| fcntl (Unix) | The fcntl() and ioctl() system calls.
| filecmp | Compare files efficiently.
| fileinput | Loop over standard input or a list of files.
| fnmatch | Unix shell style filename pattern matching.
| formatter | 폐지: Generic output formatter and device interface.
| fractions | Rational numbers.
| ftplib | FTP protocol client (requires sockets).
| functools | Higher-order functions and operations on callable objects.
| g |
| gc | Interface to the cycle-detecting garbage collector.
| getopt | Portable parser for command line options; support both short and long option names.
| getpass | Portable reading of passwords and retrieval of the userid.
| gettext | Multilingual internationalization services.
| glob | Unix shell style pathname pattern expansion.
| grp (Unix) | The group database (getgrnam() and friends).
| gzip | Interfaces for gzip compression and decompression using file objects.
| h |
| hashlib | Secure hash and message digest algorithms.
| heapq | Heap queue algorithm (a.k.a. priority queue).
| hmac | Keyed-Hashing for Message Authentication (HMAC) implementation
- | html | Helpers for manipulating HTML.
|     html.entities | Definitions of HTML general entities.
|     html.parser | A simple parser that can handle HTML and XHTML.
- | http | HTTP status codes and messages
|     http.client | HTTP and HTTPS protocol client (requires sockets).
|     http.cookiejar | Classes for automatic handling of HTTP cookies.
|     http.cookies | Support for HTTP state management (cookies).
|     http.server | HTTP server and request handlers.
| i |
| imaplib | IMAP4 protocol client (requires sockets).
| imghdr | Determine the type of image contained in a file or byte stream.
| imp | 폐지: Access the implementation of the import statement.
- | importlib | The implementation of the import machinery.
|     importlib.abc | Abstract base classes related to import
|     importlib.machinery | Importers and path hooks
|     importlib.resources | Package resource reading, opening, and access
|     importlib.util | Utility code for importers
| inspect | Extract information and source code from live objects.
| io | Core tools for working with streams.
| ipaddress | IPv4/IPv6 manipulation library.
| itertools | Functions creating iterators for efficient looping.
| j |
- | json | Encode and decode the JSON format.
|     json.tool | A command line to validate and pretty-print JSON.
| k |
| keyword | Test whether a string is a keyword in Python.
| l |
| lib2to3 | The 2to3 library
| linecache | Provides random access to individual lines from text files.
| locale | Internationalization services.
- | logging | Flexible event logging system for applications.
|     logging.config | Configuration of the logging module.
|     logging.handlers | Handlers for the logging module.
| lzma | A Python wrapper for the liblzma compression library.
| m |
| macpath | Mac OS 9 path manipulation functions.
| mailbox | Manipulate mailboxes in various formats
| mailcap | Mailcap file handling.
| marshal | Convert Python objects to streams of bytes and back (with different constraints).
| math | Mathematical functions (sin() etc.).
| mimetypes | Mapping of filename extensions to MIME types.
| mmap | Interface to memory-mapped files for Unix and Windows.
| modulefinder | Find modules used by a script.
| msilib (Windows) | Creation of Microsoft Installer files, and CAB files.
| msvcrt (Windows) | Miscellaneous useful routines from the MS VC++ runtime.
- | multiprocessing | Process-based parallelism.
|     multiprocessing.connection | API for dealing with sockets.
|     multiprocessing.dummy | Dumb wrapper around threading.
|     multiprocessing.managers | Share data between process with shared objects.
|     multiprocessing.pool | Create pools of processes.
|     multiprocessing.sharedctypes | Allocate ctypes objects from shared memory.
| n |
| netrc | Loading of .netrc files.
| nis (Unix) | Interface to Sun's NIS (Yellow Pages) library.
| nntplib | NNTP protocol client (requires sockets).
| numbers | Numeric abstract base classes (Complex, Real, Integral, etc.).
| o |
| operator | Functions corresponding to the standard operators.
| optparse | 폐지: Command-line option parsing library.
- | os | Miscellaneous operating system interfaces.
|     os.path | Operations on pathnames.
| ossaudiodev (Linux, FreeBSD) | Access to OSS-compatible audio devices.
| p |
| parser | Access parse trees for Python source code.
| pathlib | Object-oriented filesystem paths
| pdb | The Python debugger for interactive interpreters.
| pickle | Convert Python objects to streams of bytes and back.
| pickletools | Contains extensive comments about the pickle protocols and pickle-machine opcodes, as well as some useful functions.
| pipes (Unix) | A Python interface to Unix shell pipelines.
| pkgutil | Utilities for the import system.
| platform | Retrieves as much platform identifying data as possible.
| plistlib | Generate and parse Mac OS X plist files.
| poplib | POP3 protocol client (requires sockets).
| posix (Unix) | The most common POSIX system calls (normally used via module os).
| pprint | Data pretty printer.
| profile | Python source profiler.
| pstats | Statistics object for use with the profiler.
| pty (Linux) | Pseudo-Terminal Handling for Linux.
| pwd (Unix) | The password database (getpwnam() and friends).
| py_compile | Generate byte-code files from Python source files.
| pyclbr | Supports information extraction for a Python module browser.
| pydoc | Documentation generator and online help system.
| q |
| queue | A synchronized queue class.
| quopri | Encode and decode files using the MIME quoted-printable encoding.
| r |
| random | Generate pseudo-random numbers with various common distributions.
| re | Regular expression operations.
| readline (Unix) | GNU readline support for Python.
| reprlib | Alternate repr() implementation with size limits.
| resource (Unix) | An interface to provide resource usage information on the current process.
| rlcompleter | Python identifier completion, suitable for the GNU readline library.
| runpy | Locate and run Python modules without importing them first.
| s |
| sched | General purpose event scheduler.
| secrets | Generate secure random numbers for managing secrets.
| select | Wait for I/O completion on multiple streams.
| selectors | High-level I/O multiplexing.
| shelve | Python object persistence.
| shlex | Simple lexical analysis for Unix shell-like languages.
| shutil | High-level file operations, including copying.
| signal | Set handlers for asynchronous events.
| site | Module responsible for site-specific configuration.
| smtpd | A SMTP server implementation in Python.
| smtplib | SMTP protocol client (requires sockets).
| sndhdr | Determine type of a sound file.
| socket | Low-level networking interface.
| socketserver | A framework for network servers.
| spwd (Unix) | The shadow password database (getspnam() and friends).
| sqlite3 | A DB-API 2.0 implementation using SQLite 3.x.
| ssl | TLS/SSL wrapper for socket objects
| stat | Utilities for interpreting the results of os.stat(), os.lstat() and os.fstat().
| statistics | Mathematical statistics functions
| string | Common string operations.
| stringprep | String preparation, as per RFC 3453
| struct | Interpret bytes as packed binary data.
| subprocess | Subprocess management.
| sunau | Provide an interface to the Sun AU sound format.
| symbol | Constants representing internal nodes of the parse tree.
| symtable | Interface to the compiler's internal symbol tables.
| sys | Access system-specific parameters and functions.
| sysconfig | Python's configuration information
| syslog (Unix) | An interface to the Unix syslog library routines.
| t |
| tabnanny | Tool for detecting white space related problems in Python source files in a directory tree.
| tarfile | Read and write tar-format archive files.
| telnetlib | Telnet client class.
| tempfile | Generate temporary files and directories.
| termios (Unix) | POSIX style tty control.
- | test | Regression tests package containing the testing suite for Python.
|     test.support | Support for Python's regression test suite.
|     test.support.script_helper | Support for Python's script execution tests.
| textwrap | Text wrapping and filling
| threading | Thread-based parallelism.
| time | Time access and conversions.
| timeit | Measure the execution time of small code snippets.
- | tkinter | Interface to Tcl/Tk for graphical user interfaces
|     tkinter.scrolledtext (Tk) | Text widget with a vertical scroll bar.
|     tkinter.tix | Tk Extension Widgets for Tkinter
|     tkinter.ttk | Tk themed widget set
| token | Constants representing terminal nodes of the parse tree.
| tokenize | Lexical scanner for Python source code.
| trace | Trace or track Python statement execution.
| traceback | Print or retrieve a stack traceback.
| tracemalloc | Trace memory allocations.
| tty (Unix) | Utility functions that perform common terminal control operations.
| turtle | An educational framework for simple graphics applications
| turtledemo | A viewer for example turtle scripts
| types | Names for built-in types.
| typing | Support for type hints (see PEP 484).
| u |
| unicodedata | Access the Unicode Database.
- | unittest | Unit testing framework for Python.
|     unittest.mock | Mock object library.
- | urllib |
|     urllib.error | Exception classes raised by urllib.request.
|     urllib.parse | Parse URLs into or assemble them from components.
|     urllib.request | Extensible library for opening URLs.
|     urllib.response | Response classes used by urllib.
|     urllib.robotparser | Load a robots.txt file and answer questions about fetchability of other URLs.
| uu | Encode and decode files in uuencode format.
| uuid | UUID objects (universally unique identifiers) according to RFC 4122
| v |
| venv | Creation of virtual environments.
| w |
| warnings | Issue warning messages and control their disposition.
| wave | Provide an interface to the WAV sound format.
| weakref | Support for weak references and weak dictionaries.
| webbrowser | Easy-to-use controller for Web browsers.
| winreg (Windows) | Routines and objects for manipulating the Windows registry.
| winsound (Windows) | Access to the sound-playing machinery for Windows.
- | wsgiref | WSGI Utilities and Reference Implementation.
|     wsgiref.handlers | WSGI server/gateway base classes.
|     wsgiref.headers | WSGI response header tools.
|     wsgiref.simple_server | A simple WSGI HTTP server.
|     wsgiref.util | WSGI environment utilities.
|     wsgiref.validate | WSGI conformance checker.
| x |
| xdrlib | Encoders and decoders for the External Data Representation (XDR).
- | xml | Package containing XML processing modules
|     xml.dom | Document Object Model API for Python.
|     xml.dom.minidom | Minimal Document Object Model (DOM) implementation.
|     xml.dom.pulldom | Support for building partial DOM trees from SAX events.
|     xml.etree.ElementTree | Implementation of the ElementTree API.
|     xml.parsers.expat | An interface to the Expat non-validating XML parser.
|     xml.parsers.expat.errors |
|     xml.parsers.expat.model |
|     xml.sax | Package containing SAX2 base classes and convenience functions.
|     xml.sax.handler | Base classes for SAX event handlers.
|     xml.sax.saxutils | Convenience functions and classes for use with SAX.
|     xml.sax.xmlreader | Interface which SAX-compliant XML parsers must implement.
- | xmlrpc |
|     xmlrpc.client | XML-RPC client access.
|     xmlrpc.server | Basic XML-RPC server implementations.
| z |
| zipapp | Manage executable Python zip archives
| zipfile | Read and write ZIP-format archive files.
| zipimport | Support for importing Python modules from ZIP archives.
| zlib | Low-level interface to compression and decompression routines compatible with gzip.

탐색

색인

모듈 |

Python »

3.7.17 Documentation »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

Python »

3.7.17 Documentation »

|

색인

알파벳별 색인:

기호 | _ | A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | X | Y | Z | ᄀ | ᄂ | ᄆ | ᄋ | ᄏ | ᄑ | ᄒ

한 페이지에 전체 색인 보기 (큰 경우가 있으므로 주의)

탐색

색인

모듈 |

Python »

3.7.17 Documentation »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

Python »

3.7.17 Documentation »

|

Download Python 3.7.17 Documentation

Last updated on: 6월 28, 2023.

To download an archive containing all the documents for this version of Python in one of various formats, follow one of links in this table.

Format | Packed as .zip | Packed as .tar.bz2
PDF (US-Letter paper size) | Download (ca. 13 MiB) | Download (ca. 13 MiB)
PDF (A4 paper size) | Download (ca. 13 MiB) | Download (ca. 13 MiB)
HTML | Download (ca. 9 MiB) | Download (ca. 6 MiB)
Plain Text | Download (ca. 3 MiB) | Download (ca. 2 MiB)
EPUB | Download (ca. 5 MiB) |

These archives contain all the content in the documentation.

HTML Help (.chm) files are made available in the "Windows" section on the Python download page.

Unpacking

Unix users should download the .tar.bz2 archives; these are bzipped tar archives and can be handled in the usual way using tar and the bzip2 program. The InfoZIP unzip program can be used to handle the ZIP archives if desired. The .tar.bz2 archives provide the best compression and fastest download times.

Windows users can use the ZIP archives since those are customary on that platform. These are created on Unix using the InfoZIP zip program.

Problems

If you have comments or suggestions for the Python documentation, please send email to docs@python.org.

탐색

색인

모듈 |

Python »

3.7.17 Documentation »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

Python »

3.7.17 Documentation »

|

Index – A

A (re 모듈)

A-LAW, [1]

a-LAW

a2b_base64() (binascii 모듈)

a2b_hex() (binascii 모듈)

a2b_hqx() (binascii 모듈)

a2b_qp() (binascii 모듈)

a2b_uu() (binascii 모듈)

a85decode() (base64 모듈)

a85encode() (base64 모듈)

ABC (abc 클래스)

abc (모듈)

ABCMeta (abc 클래스)

abiflags (sys 모듈)

abort()

(asyncio.DatagramTransport 메서드)

(asyncio.WriteTransport 메서드)

(ftplib.FTP 메서드)

(os 모듈)

(threading.Barrier 메서드)

above() (curses.panel.Panel 메서드)

ABOVE_NORMAL_PRIORITY_CLASS (subprocess 모듈)

abs

내장 함수, [1]

abs() (decimal.Context 메서드)

(operator 모듈)

(내장 함수)

abspath() (os.path 모듈)

abstract base class (추상 베이스 클래스)

AbstractAsyncContextManager (contextlib 클래스)

AbstractBasicAuthHandler (urllib.request 클래스)

AbstractChildWatcher (asyncio 클래스)

abstractclassmethod() (abc 모듈)

AbstractContextManager (contextlib 클래스)

AbstractDigestAuthHandler (urllib.request 클래스)

AbstractEventLoop (asyncio 클래스)

AbstractEventLoopPolicy (asyncio 클래스)

AbstractFormatter (formatter 클래스)

abstractmethod() (abc 모듈)

abstractproperty() (abc 모듈)

AbstractSet (typing 클래스)

abstractstaticmethod() (abc 모듈)

AbstractWriter (formatter 클래스)

accept() (asyncore.dispatcher 메서드)

(multiprocessing.connection.Listener 메서드)

(socket.socket 메서드)

access() (os 모듈)

accumulate() (itertools 모듈)

aclose() (agen 메서드)

(contextlib.AsyncExitStack 메서드)

acos() (cmath 모듈)

(math 모듈)

acosh() (cmath 모듈)

(math 모듈)

acquire() (_thread.lock 메서드)

(asyncio.Condition의 메서드)

(asyncio.Lock의 메서드)

(asyncio.Semaphore의 메서드)

(logging.Handler 메서드)

(multiprocessing.Lock 메서드)

(multiprocessing.RLock 메서드)

(threading.Condition 메서드)

(threading.Lock 메서드)

(threading.RLock 메서드)

(threading.Semaphore 메서드)

acquire_lock() (imp 모듈)

Action (argparse 클래스)

action (optparse.Option의 속성)

ACTIONS (optparse.Option의 속성)

active_children() (multiprocessing 모듈)

active_count() (threading 모듈)

add() (audioop 모듈)

(decimal.Context 메서드)

(frozenset 메서드)

(mailbox.Mailbox 메서드)

(mailbox.Maildir 메서드)

(msilib.RadioButtonGroup 메서드)

(operator 모듈)

(pstats.Stats 메서드)

(tarfile.TarFile 메서드)

(tkinter.ttk.Notebook 메서드)

add_alias() (email.charset 모듈)

add_alternative() (email.message.EmailMessage 메서드)

add_argument() (argparse.ArgumentParser 메서드)

add_argument_group() (argparse.ArgumentParser 메서드)

add_attachment() (email.message.EmailMessage 메서드)

add_cgi_vars() (wsgiref.handlers.BaseHandler 메서드)

add_charset() (email.charset 모듈)

add_child_handler() (asyncio.AbstractChildWatcher 메서드)

add_codec() (email.charset 모듈)

add_cookie_header() (http.cookiejar.CookieJar 메서드)

add_data() (msilib 모듈)

add_done_callback() (asyncio.Future 메서드)

(asyncio.Task 메서드)

(concurrent.futures.Future 메서드)

add_fallback() (gettext.NullTranslations 메서드)

add_file() (msilib.Directory 메서드)

add_flag() (mailbox.MaildirMessage 메서드)

(mailbox.mboxMessage 메서드)

(mailbox.MMDFMessage 메서드)

add_flowing_data() (formatter.formatter 메서드)

add_folder() (mailbox.Maildir 메서드)

(mailbox.MH 메서드)

add_get_handler() (email.contentmanager.ContentManager 메서드)

add_handler() (urllib.request.OpenerDirector 메서드)

add_header() (email.message.EmailMessage 메서드)

(email.message.Message 메서드)

(urllib.request.Request 메서드)

(wsgiref.headers.Headers 메서드)

add_history() (readline 모듈)

add_hor_rule() (formatter.formatter 메서드)

add_include_dir() (distutils.ccompiler.CCompiler 메서드)

add_label() (mailbox.BabylMessage 메서드)

add_label_data() (formatter.formatter 메서드)

add_library() (distutils.ccompiler.CCompiler 메서드)

add_library_dir() (distutils.ccompiler.CCompiler 메서드)

add_line_break() (formatter.formatter 메서드)

add_link_object() (distutils.ccompiler.CCompiler 메서드)

add_literal_data() (formatter.formatter 메서드)

add_mutually_exclusive_group() (argparse.ArgumentParser 메서드)

add_option() (optparse.OptionParser 메서드)

add_parent() (urllib.request.BaseHandler 메서드)

add_password() (urllib.request.HTTPPasswordMgr 메서드)

(urllib.request.HTTPPasswordMgrWithPriorAuth 메서드)

add_reader() (asyncio.loop 메서드)

add_related() (email.message.EmailMessage 메서드)

add_runtime_library_dir() (distutils.ccompiler.CCompiler 메서드)

add_section() (configparser.ConfigParser 메서드)

(configparser.RawConfigParser 메서드)

add_sequence() (mailbox.MHMessage 메서드)

add_set_handler() (email.contentmanager.ContentManager 메서드)

add_signal_handler() (asyncio.loop 메서드)

add_stream() (msilib 모듈)

add_subparsers() (argparse.ArgumentParser 메서드)

add_tables() (msilib 모듈)

add_type() (mimetypes 모듈)

add_unredirected_header() (urllib.request.Request 메서드)

add_writer() (asyncio.loop 메서드)

addch() (curses.window 메서드)

addCleanup() (unittest.TestCase 메서드)

addcomponent() (turtle.Shape 메서드)

addError() (unittest.TestResult 메서드)

addExpectedFailure() (unittest.TestResult 메서드)

addFailure() (unittest.TestResult 메서드)

addfile() (tarfile.TarFile 메서드)

addFilter() (logging.Handler 메서드)

(logging.Logger 메서드)

addHandler() (logging.Logger 메서드)

addition

addLevelName() (logging 모듈)

addnstr() (curses.window 메서드)

AddPackagePath() (modulefinder 모듈)

addr (smtpd.SMTPChannel의 속성)

addr_spec (email.headerregistry.Address의 속성)

Address (email.headerregistry 클래스)

address (email.headerregistry.SingleAddressHeader의 속성)

(multiprocessing.connection.Listener의 속성)

(multiprocessing.managers.BaseManager의 속성)

address_exclude() (ipaddress.IPv4Network 메서드)

(ipaddress.IPv6Network 메서드)

address_family (socketserver.BaseServer의 속성)

address_string() (http.server.BaseHTTPRequestHandler 메서드)

addresses (email.headerregistry.AddressHeader의 속성)

(email.headerregistry.Group의 속성)

AddressHeader (email.headerregistry 클래스)

addressof() (ctypes 모듈)

AddressValueError

addshape() (turtle 모듈)

addsitedir() (site 모듈)

addSkip() (unittest.TestResult 메서드)

addstr() (curses.window 메서드)

addSubTest() (unittest.TestResult 메서드)

addSuccess() (unittest.TestResult 메서드)

addTest() (unittest.TestSuite 메서드)

addTests() (unittest.TestSuite 메서드)

addTypeEqualityFunc() (unittest.TestCase 메서드)

addUnexpectedSuccess() (unittest.TestResult 메서드)

adjust_int_max_str_digits() (test.support 모듈)

adjusted() (decimal.Decimal 메서드)

adler32() (zlib 모듈)

ADPCM, Intel/DVI

adpcm2lin() (audioop 모듈)

AF_ALG (socket 모듈)

AF_CAN (socket 모듈)

AF_INET (socket 모듈)

AF_INET6 (socket 모듈)

AF_LINK (socket 모듈)

AF_PACKET (socket 모듈)

AF_RDS (socket 모듈)

AF_UNIX (socket 모듈)

AF_VSOCK (socket 모듈)

aifc (모듈)

aifc() (aifc.aifc 메서드)

AIFF, [1]

aiff() (aifc.aifc 메서드)

AIFF-C, [1]

alarm() (signal 모듈)

alaw2lin() (audioop 모듈)

ALERT_DESCRIPTION_HANDSHAKE_FAILURE (ssl 모듈)

ALERT_DESCRIPTION_INTERNAL_ERROR (ssl 모듈)

AlertDescription (ssl 클래스)

algorithms_available (hashlib 모듈)

algorithms_guaranteed (hashlib 모듈)

alias (pdb command)

alignment() (ctypes 모듈)

alive (weakref.finalize의 속성)

all() (내장 함수)

all_errors (ftplib 모듈)

all_features (xml.sax.handler 모듈)

all_frames (tracemalloc.Filter의 속성)

all_properties (xml.sax.handler 모듈)

all_suffixes() (importlib.machinery 모듈)

all_tasks() (asyncio 모듈)

(asyncio.Task의 클래스 메서드)

allocate_lock() (_thread 모듈)

allow_reuse_address (socketserver.BaseServer의 속성)

allowed_domains() (http.cookiejar.DefaultCookiePolicy 메서드)

alt() (curses.ascii 모듈)

ALT_DIGITS (locale 모듈)

altsep (os 모듈)

altzone (time 모듈)

ALWAYS_EQ (test.support 모듈)

ALWAYS_TYPED_ACTIONS (optparse.Option의 속성)

AMPER (token 모듈)

AMPEREQUAL (token 모듈)

and

bitwise

연산자, [1], [2]

and_() (operator 모듈)

annotated

assignment

annotation (inspect.Parameter의 속성)

(어노테이션)

annotations

function, [1]

announce() (distutils.ccompiler.CCompiler 메서드)

anonymous

function

answer_challenge() (multiprocessing.connection 모듈)

anticipate_failure() (test.support 모듈)

Any (typing 모듈)

ANY (unittest.mock 모듈)

any() (내장 함수)

AnyStr (typing 모듈)

api_version (sys 모듈)

apop() (poplib.POP3 메서드)

APPDATA

append() (array.array 메서드)

(collections.deque 메서드)

(email.header.Header 메서드)

(imaplib.IMAP4 메서드)

(msilib.CAB 메서드)

(pipes.Template 메서드)

(sequence method)

(xml.etree.ElementTree.Element 메서드)

append_history_file() (readline 모듈)

appendChild() (xml.dom.Node 메서드)

appendleft() (collections.deque 메서드)

application_uri() (wsgiref.util 모듈)

apply (2to3 fixer)

apply() (multiprocessing.pool.Pool 메서드)

apply_async() (multiprocessing.pool.Pool 메서드)

apply_defaults() (inspect.BoundArguments 메서드)

architecture() (platform 모듈)

archive (zipimport.zipimporter의 속성)

aRepr (reprlib 모듈)

argparse (모듈)

args (BaseException의 속성)

(functools.partial의 속성)

(inspect.BoundArguments의 속성)

(pdb command)

(subprocess.CompletedProcess의 속성)

(subprocess.Popen의 속성)

args_from_interpreter_flags() (test.support 모듈)

argtypes (ctypes._FuncPtr의 속성)

argument

call semantics

difference from parameter

function

function definition

argument (인자)

ArgumentDefaultsHelpFormatter (argparse 클래스)

ArgumentError

ArgumentParser (argparse 클래스)

arguments (inspect.BoundArguments의 속성)

argv (in module sys)

(sys 모듈)

arithmetic

conversion

operation, binary

operation, unary

ArithmeticError

array

모듈, [1]

array (array 클래스)

Array (ctypes 클래스)

array (모듈)

Array() (multiprocessing 모듈)

(multiprocessing.managers.SyncManager 메서드)

(multiprocessing.sharedctypes 모듈)

arrays

arraysize (sqlite3.Cursor의 속성)

article() (nntplib.NNTP 메서드)

as

except clause

import statement

with statement

키워드, [1], [2]

as_bytes() (email.message.EmailMessage 메서드)

(email.message.Message 메서드)

as_completed() (asyncio 모듈)

(concurrent.futures 모듈)

as_integer_ratio() (decimal.Decimal 메서드)

(float 메서드)

AS_IS (formatter 모듈)

as_posix() (pathlib.PurePath 메서드)

as_string() (email.message.EmailMessage 메서드)

(email.message.Message 메서드)

as_tuple() (decimal.Decimal 메서드)

as_uri() (pathlib.PurePath 메서드)

ASCII, [1]

ascii

(re 모듈)

내장 함수

ascii() (curses.ascii 모듈)

(내장 함수)

ascii_letters (string 모듈)

ascii_lowercase (string 모듈)

ascii_uppercase (string 모듈)

asctime() (time 모듈)

asdict() (dataclasses 모듈)

asend() (agen 메서드)

asin() (cmath 모듈)

(math 모듈)

asinh() (cmath 모듈)

(math 모듈)

assert

글, [1]

assert_any_call() (unittest.mock.Mock 메서드)

assert_called() (unittest.mock.Mock 메서드)

assert_called_once() (unittest.mock.Mock 메서드)

assert_called_once_with() (unittest.mock.Mock 메서드)

assert_called_with() (unittest.mock.Mock 메서드)

assert_has_calls() (unittest.mock.Mock 메서드)

assert_line_data() (formatter.formatter 메서드)

assert_not_called() (unittest.mock.Mock 메서드)

assert_python_failure() (test.support.script_helper 모듈)

assert_python_ok() (test.support.script_helper 모듈)

assertAlmostEqual() (unittest.TestCase 메서드)

assertCountEqual() (unittest.TestCase 메서드)

assertDictEqual() (unittest.TestCase 메서드)

assertEqual() (unittest.TestCase 메서드)

assertFalse() (unittest.TestCase 메서드)

assertGreater() (unittest.TestCase 메서드)

assertGreaterEqual() (unittest.TestCase 메서드)

assertIn() (unittest.TestCase 메서드)

AssertionError

예외

assertions

debugging

assertIs() (unittest.TestCase 메서드)

assertIsInstance() (unittest.TestCase 메서드)

assertIsNone() (unittest.TestCase 메서드)

assertIsNot() (unittest.TestCase 메서드)

assertIsNotNone() (unittest.TestCase 메서드)

assertLess() (unittest.TestCase 메서드)

assertLessEqual() (unittest.TestCase 메서드)

assertListEqual() (unittest.TestCase 메서드)

assertLogs() (unittest.TestCase 메서드)

assertMultiLineEqual() (unittest.TestCase 메서드)

assertNotAlmostEqual() (unittest.TestCase 메서드)

assertNotEqual() (unittest.TestCase 메서드)

assertNotIn() (unittest.TestCase 메서드)

assertNotIsInstance() (unittest.TestCase 메서드)

assertNotRegex() (unittest.TestCase 메서드)

assertRaises() (unittest.TestCase 메서드)

assertRaisesRegex() (unittest.TestCase 메서드)

assertRegex() (unittest.TestCase 메서드)

asserts (2to3 fixer)

assertSequenceEqual() (unittest.TestCase 메서드)

assertSetEqual() (unittest.TestCase 메서드)

assertTrue() (unittest.TestCase 메서드)

assertTupleEqual() (unittest.TestCase 메서드)

assertWarns() (unittest.TestCase 메서드)

assertWarnsRegex() (unittest.TestCase 메서드)

assignment

annotated

attribute, [1]

augmented

class attribute

class instance attribute

slice

slicing

statement, [1]

subscript

subscription

target list

AST (ast 클래스)

ast (모듈)

astimezone() (datetime.datetime 메서드)

astuple() (dataclasses 모듈)

async

키워드

async def

글

async for

in comprehensions

글

async with

글

async_chat (asynchat 클래스)

async_chat.ac_in_buffer_size (asynchat 모듈)

async_chat.ac_out_buffer_size (asynchat 모듈)

AsyncContextManager (typing 클래스)

asynccontextmanager() (contextlib 모듈)

AsyncExitStack (contextlib 클래스)

AsyncGenerator (collections.abc 클래스)

(typing 클래스)

AsyncGeneratorType (types 모듈)

asynchat (모듈)

asynchronous context manager (비동기 컨텍스트 관리자)

asynchronous generator

asynchronous iterator

function

asynchronous generator (비동기 제너레이터)

asynchronous generator iterator (비동기 제너레이터 이터레이터)

asynchronous iterable (비동기 이터러블)

asynchronous iterator (비동기 이터레이터)

asynchronous-generator

객체

asyncio (모듈)

asyncio.subprocess.DEVNULL (asyncio 모듈)

asyncio.subprocess.PIPE (asyncio 모듈)

asyncio.subprocess.Process (asyncio 클래스)

asyncio.subprocess.STDOUT (asyncio 모듈)

AsyncIterable (collections.abc 클래스)

(typing 클래스)

AsyncIterator (collections.abc 클래스)

(typing 클래스)

asyncore (모듈)

AsyncResult (multiprocessing.pool 클래스)

AT (token 모듈)

at_eof() (asyncio.StreamReader 메서드)

atan() (cmath 모듈)

(math 모듈)

atan2() (math 모듈)

atanh() (cmath 모듈)

(math 모듈)

ATEQUAL (token 모듈)

atexit (weakref.finalize의 속성)

(모듈)

athrow() (agen 메서드)

atof() (locale 모듈)

atoi() (locale 모듈)

atom

attach() (email.message.Message 메서드)

attach_loop() (asyncio.AbstractChildWatcher 메서드)

attach_mock() (unittest.mock.Mock 메서드)

AttlistDeclHandler() (xml.parsers.expat.xmlparser 메서드)

attrgetter() (operator 모듈)

attrib (xml.etree.ElementTree.Element의 속성)

attribute

assignment, [1]

assignment, class

assignment, class instance

class

class instance

deletion

generic special

reference

special

attribute (어트리뷰트)

AttributeError

예외

attributes (xml.dom.Node의 속성)

AttributesImpl (xml.sax.xmlreader 클래스)

AttributesNSImpl (xml.sax.xmlreader 클래스)

attroff() (curses.window 메서드)

attron() (curses.window 메서드)

attrset() (curses.window 메서드)

Audio Interchange File Format, [1]

AUDIO_FILE_ENCODING_ADPCM_G721 (sunau 모듈)

AUDIO_FILE_ENCODING_ADPCM_G722 (sunau 모듈)

AUDIO_FILE_ENCODING_ADPCM_G723_3 (sunau 모듈)

AUDIO_FILE_ENCODING_ADPCM_G723_5 (sunau 모듈)

AUDIO_FILE_ENCODING_ALAW_8 (sunau 모듈)

AUDIO_FILE_ENCODING_DOUBLE (sunau 모듈)

AUDIO_FILE_ENCODING_FLOAT (sunau 모듈)

AUDIO_FILE_ENCODING_LINEAR_16 (sunau 모듈)

AUDIO_FILE_ENCODING_LINEAR_24 (sunau 모듈)

AUDIO_FILE_ENCODING_LINEAR_32 (sunau 모듈)

AUDIO_FILE_ENCODING_LINEAR_8 (sunau 모듈)

AUDIO_FILE_ENCODING_MULAW_8 (sunau 모듈)

AUDIO_FILE_MAGIC (sunau 모듈)

AUDIODEV

audioop (모듈)

augmented

assignment

auth() (ftplib.FTP_TLS 메서드)

(smtplib.SMTP 메서드)

authenticate() (imaplib.IMAP4 메서드)

AuthenticationError

authenticators() (netrc.netrc 메서드)

authkey (multiprocessing.Process의 속성)

auto (enum 클래스)

autorange() (timeit.Timer 메서드)

avg() (audioop 모듈)

avgpp() (audioop 모듈)

avoids_symlink_attacks (shutil.rmtree의 속성)

await

in comprehensions

키워드, [1]

Awaitable (collections.abc 클래스)

(typing 클래스)

awaitable (어웨이터블)

탐색

색인

모듈 |

Python »

3.7.17 Documentation »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

Python »

3.7.17 Documentation »

|

Index – B

b"

bytes literal

b'

bytes literal

b16decode() (base64 모듈)

b16encode() (base64 모듈)

b2a_base64() (binascii 모듈)

b2a_hex() (binascii 모듈)

b2a_hqx() (binascii 모듈)

b2a_qp() (binascii 모듈)

b2a_uu() (binascii 모듈)

b32decode() (base64 모듈)

b32encode() (base64 모듈)

b64decode() (base64 모듈)

b64encode() (base64 모듈)

b85decode() (base64 모듈)

b85encode() (base64 모듈)

Babyl (mailbox 클래스)

BabylMessage (mailbox 클래스)

back() (turtle 모듈)

backslash character

backslashreplace_errors() (codecs 모듈)

backup() (sqlite3.Connection 메서드)

backward() (turtle 모듈)

BadStatusLine

BadZipFile

BadZipfile

Balloon (tkinter.tix 클래스)

Barrier (multiprocessing 클래스)

(threading 클래스)

Barrier() (multiprocessing.managers.SyncManager 메서드)

base64

encoding

모듈

base64 (모듈)

base_exec_prefix (sys 모듈)

base_prefix (sys 모듈)

BaseCGIHandler (wsgiref.handlers 클래스)

BaseCookie (http.cookies 클래스)

BaseException

BaseHandler (urllib.request 클래스)

(wsgiref.handlers 클래스)

BaseHeader (email.headerregistry 클래스)

BaseHTTPRequestHandler (http.server 클래스)

BaseManager (multiprocessing.managers 클래스)

basename() (os.path 모듈)

BaseProtocol (asyncio 클래스)

BaseProxy (multiprocessing.managers 클래스)

BaseRequestHandler (socketserver 클래스)

BaseRotatingHandler (logging.handlers 클래스)

BaseSelector (selectors 클래스)

BaseServer (socketserver 클래스)

basestring (2to3 fixer)

BaseTransport (asyncio 클래스)

basicConfig() (logging 모듈)

BasicContext (decimal 클래스)

BasicInterpolation (configparser 클래스)

BasicTestRunner (test.support 클래스)

baudrate() (curses 모듈)

bbox() (tkinter.ttk.Treeview 메서드)

BDADDR_ANY (socket 모듈)

BDADDR_LOCAL (socket 모듈)

bdb

모듈

Bdb (bdb 클래스)

bdb (모듈)

BdbQuit

BDFL

bdist_msi (distutils.command.bdist_msi 클래스)

beep() (curses 모듈)

Beep() (winsound 모듈)

BEFORE_ASYNC_WITH (opcode)

begin_fill() (turtle 모듈)

begin_poly() (turtle 모듈)

below() (curses.panel.Panel 메서드)

BELOW_NORMAL_PRIORITY_CLASS (subprocess 모듈)

Benchmarking

benchmarking, [1], [2], [3]

betavariate() (random 모듈)

bgcolor() (turtle 모듈)

bgpic() (turtle 모듈)

bias() (audioop 모듈)

bidirectional() (unicodedata 모듈)

bigaddrspacetest() (test.support 모듈)

BigEndianStructure (ctypes 클래스)

bigmemtest() (test.support 모듈)

bin() (내장 함수)

binary

arithmetic operation

bitwise operation

data, packing

literals

Binary (msilib 클래스)

(xmlrpc.client 클래스)

binary file (바이너리 파일)

binary literal

binary mode

binary semaphores

BINARY_ADD (opcode)

BINARY_AND (opcode)

BINARY_FLOOR_DIVIDE (opcode)

BINARY_LSHIFT (opcode)

BINARY_MATRIX_MULTIPLY (opcode)

BINARY_MODULO (opcode)

BINARY_MULTIPLY (opcode)

BINARY_OR (opcode)

BINARY_POWER (opcode)

BINARY_RSHIFT (opcode)

BINARY_SUBSCR (opcode)

BINARY_SUBTRACT (opcode)

BINARY_TRUE_DIVIDE (opcode)

BINARY_XOR (opcode)

BinaryIO (typing 클래스)

binascii (모듈)

bind (widgets)

bind() (asyncore.dispatcher 메서드)

(inspect.Signature 메서드)

(socket.socket 메서드)

bind_partial() (inspect.Signature 메서드)

bind_port() (test.support 모듈)

bind_textdomain_codeset() (gettext 모듈)

bind_unix_socket() (test.support 모듈)

binding

global name

name, [1], [2], [3], [4], [5], [6]

bindtextdomain() (gettext 모듈)

(locale 모듈)

binhex

모듈

binhex (모듈)

binhex() (binhex 모듈)

bisect (모듈)

bisect() (bisect 모듈)

bisect_left() (bisect 모듈)

bisect_right() (bisect 모듈)

bit_length() (int 메서드)

bitmap() (msilib.Dialog 메서드)

bitwise

and

operation, binary

operation, unary

operations

or

xor

bk() (turtle 모듈)

bkgd() (curses.window 메서드)

bkgdset() (curses.window 메서드)

blake2b() (hashlib 모듈)

blake2b, blake2s

blake2b.MAX_DIGEST_SIZE (hashlib 모듈)

blake2b.MAX_KEY_SIZE (hashlib 모듈)

blake2b.PERSON_SIZE (hashlib 모듈)

blake2b.SALT_SIZE (hashlib 모듈)

blake2s() (hashlib 모듈)

blake2s.MAX_DIGEST_SIZE (hashlib 모듈)

blake2s.MAX_KEY_SIZE (hashlib 모듈)

blake2s.PERSON_SIZE (hashlib 모듈)

blake2s.SALT_SIZE (hashlib 모듈)

blank line

block

code

block_size (hmac.HMAC의 속성)

blocked_domains() (http.cookiejar.DefaultCookiePolicy 메서드)

BlockingIOError, [1]

blocksize (http.client.HTTPConnection의 속성)

BNF, [1]

body() (nntplib.NNTP 메서드)

body_encode() (email.charset.Charset 메서드)

body_encoding (email.charset.Charset의 속성)

body_line_iterator() (email.iterators 모듈)

BOM (codecs 모듈)

BOM_BE (codecs 모듈)

BOM_LE (codecs 모듈)

BOM_UTF16 (codecs 모듈)

BOM_UTF16_BE (codecs 모듈)

BOM_UTF16_LE (codecs 모듈)

BOM_UTF32 (codecs 모듈)

BOM_UTF32_BE (codecs 모듈)

BOM_UTF32_LE (codecs 모듈)

BOM_UTF8 (codecs 모듈)

bool (내장 클래스)

Boolean

operation

operations, [1]

type

values

객체, [1]

BOOLEAN_STATES (configparser.ConfigParser의 속성)

bootstrap() (ensurepip 모듈)

border() (curses.window 메서드)

bottom() (curses.panel.Panel 메서드)

bottom_panel() (curses.panel 모듈)

BoundArguments (inspect 클래스)

BoundaryError

BoundedSemaphore (asyncio 클래스)

(multiprocessing 클래스)

(threading 클래스)

BoundedSemaphore() (multiprocessing.managers.SyncManager 메서드)

box() (curses.window 메서드)

bpformat() (bdb.Breakpoint 메서드)

bpprint() (bdb.Breakpoint 메서드)

break

글, [1], [2], [3], [4]

break (pdb command)

break_anywhere() (bdb.Bdb 메서드)

break_here() (bdb.Bdb 메서드)

break_long_words (textwrap.TextWrapper의 속성)

BREAK_LOOP (opcode)

break_on_hyphens (textwrap.TextWrapper의 속성)

Breakpoint (bdb 클래스)

breakpoint() (내장 함수)

breakpointhook() (sys 모듈)

breakpoints

broadcast_address (ipaddress.IPv4Network의 속성)

(ipaddress.IPv6Network의 속성)

broken (threading.Barrier의 속성)

BrokenBarrierError

BrokenExecutor

BrokenPipeError

BrokenProcessPool

BrokenThreadPool

BROWSER, [1]

BsdDbShelf (shelve 클래스)

buffer (2to3 fixer)

(io.TextIOBase의 속성)

(unittest.TestResult의 속성)

buffer interface

(see buffer protocol)

buffer object

(see buffer protocol)

buffer protocol

binary sequence types

str (built-in class)

buffer size, I/O

buffer_info() (array.array 메서드)

buffer_size (xml.parsers.expat.xmlparser의 속성)

buffer_text (xml.parsers.expat.xmlparser의 속성)

buffer_updated() (asyncio.BufferedProtocol 메서드)

buffer_used (xml.parsers.expat.xmlparser의 속성)

BufferedIOBase (io 클래스)

BufferedProtocol (asyncio 클래스)

BufferedRandom (io 클래스)

BufferedReader (io 클래스)

BufferedRWPair (io 클래스)

BufferedWriter (io 클래스)

BufferError

BufferingHandler (logging.handlers 클래스)

BufferTooShort

bufsize() (ossaudiodev.oss_audio_device 메서드)

BUILD_CONST_KEY_MAP (opcode)

BUILD_LIST (opcode)

BUILD_LIST_UNPACK (opcode)

BUILD_MAP (opcode)

BUILD_MAP_UNPACK (opcode)

BUILD_MAP_UNPACK_WITH_CALL (opcode)

build_opener() (urllib.request 모듈)

build_py (distutils.command.build_py 클래스)

build_py_2to3 (distutils.command.build_py 클래스)

BUILD_SET (opcode)

BUILD_SET_UNPACK (opcode)

BUILD_SLICE (opcode)

BUILD_STRING (opcode)

BUILD_TUPLE (opcode)

BUILD_TUPLE_UNPACK (opcode)

BUILD_TUPLE_UNPACK_WITH_CALL (opcode)

built-in

method

types

built-in function

call

객체, [1]

built-in method

call

객체, [1]

builtin_module_names (sys 모듈)

BuiltinFunctionType (types 모듈)

BuiltinImporter (importlib.machinery 클래스)

BuiltinMethodType (types 모듈)

builtins

모듈, [1], [2], [3], [4]

builtins (모듈)

ButtonBox (tkinter.tix 클래스)

bye() (turtle 모듈)

byref() (ctypes 모듈)

byte

byte-code

file, [1]

byte_compile() (distutils.util 모듈)

bytearray

formatting

interpolation

methods

객체, [1], [2], [3]

bytearray (내장 클래스)

bytecode

Bytecode (dis 클래스)

bytecode (바이트 코드)

Bytecode.codeobj (dis 모듈)

Bytecode.first_line (dis 모듈)

BYTECODE_SUFFIXES (importlib.machinery 모듈)

byteorder (sys 모듈)

bytes

formatting

interpolation

methods

str (built-in class)

객체, [1], [2]

내장 함수, [1]

bytes (uuid.UUID의 속성)

(내장 클래스)

bytes literal

bytes-like object (바이트열류 객체)

bytes_le (uuid.UUID의 속성)

BytesFeedParser (email.parser 클래스)

BytesGenerator (email.generator 클래스)

BytesHeaderParser (email.parser 클래스)

BytesIO (io 클래스)

BytesParser (email.parser 클래스)

ByteString (collections.abc 클래스)

(typing 클래스)

byteswap() (array.array 메서드)

(audioop 모듈)

BytesWarning

bz2 (모듈)

BZ2Compressor (bz2 클래스)

BZ2Decompressor (bz2 클래스)

BZ2File (bz2 클래스)

탐색

색인

모듈 |

Python »

3.7.17 Documentation »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

Python »

3.7.17 Documentation »

|

Index – C

C

language, [1], [2], [3], [4], [5]

structures

C-contiguous, [1]

c_bool (ctypes 클래스)

C_BUILTIN (imp 모듈)

c_byte (ctypes 클래스)

c_char (ctypes 클래스)

c_char_p (ctypes 클래스)

c_contiguous (memoryview의 속성)

c_double (ctypes 클래스)

C_EXTENSION (imp 모듈)

c_float (ctypes 클래스)

c_int (ctypes 클래스)

c_int16 (ctypes 클래스)

c_int32 (ctypes 클래스)

c_int64 (ctypes 클래스)

c_int8 (ctypes 클래스)

c_long (ctypes 클래스)

c_longdouble (ctypes 클래스)

c_longlong (ctypes 클래스)

c_short (ctypes 클래스)

c_size_t (ctypes 클래스)

c_ssize_t (ctypes 클래스)

c_ubyte (ctypes 클래스)

c_uint (ctypes 클래스)

c_uint16 (ctypes 클래스)

c_uint32 (ctypes 클래스)

c_uint64 (ctypes 클래스)

c_uint8 (ctypes 클래스)

c_ulong (ctypes 클래스)

c_ulonglong (ctypes 클래스)

c_ushort (ctypes 클래스)

c_void_p (ctypes 클래스)

c_wchar (ctypes 클래스)

c_wchar_p (ctypes 클래스)

CAB (msilib 클래스)

cache_from_source() (imp 모듈)

(importlib.util 모듈)

cached (importlib.machinery.ModuleSpec의 속성)

CacheFTPHandler (urllib.request 클래스)

calcobjsize() (test.support 모듈)

calcsize() (struct 모듈)

calcvobjsize() (test.support 모듈)

Calendar (calendar 클래스)

calendar (모듈)

calendar() (calendar 모듈)

call

built-in function

built-in method

class instance

class object, [1], [2]

function, [1], [2]

instance, [1]

method

procedure

user-defined function

call() (subprocess 모듈)

(unittest.mock 모듈)

call_args (unittest.mock.Mock의 속성)

call_args_list (unittest.mock.Mock의 속성)

call_at() (asyncio.loop 메서드)

call_count (unittest.mock.Mock의 속성)

call_exception_handler() (asyncio.loop 메서드)

CALL_FUNCTION (opcode)

CALL_FUNCTION_EX (opcode)

CALL_FUNCTION_KW (opcode)

call_later() (asyncio.loop 메서드)

call_list() (unittest.mock.call 메서드)

CALL_METHOD (opcode)

call_soon() (asyncio.loop 메서드)

call_soon_threadsafe() (asyncio.loop 메서드)

call_tracing() (sys 모듈)

callable

객체, [1]

Callable (collections.abc 클래스)

(typing 모듈)

callable() (내장 함수)

CallableProxyType (weakref 모듈)

callback (optparse.Option의 속성)

callback() (contextlib.ExitStack 메서드)

callback_args (optparse.Option의 속성)

callback_kwargs (optparse.Option의 속성)

callbacks (gc 모듈)

called (unittest.mock.Mock의 속성)

CalledProcessError

calloc()

CAN_BCM (socket 모듈)

can_change_color() (curses 모듈)

can_fetch() (urllib.robotparser.RobotFileParser 메서드)

CAN_ISOTP (socket 모듈)

CAN_RAW_FD_FRAMES (socket 모듈)

can_symlink() (test.support 모듈)

can_write_eof() (asyncio.StreamWriter 메서드)

(asyncio.WriteTransport 메서드)

can_xattr() (test.support 모듈)

cancel() (asyncio.Future 메서드)

(asyncio.Handle 메서드)

(asyncio.Task 메서드)

(concurrent.futures.Future 메서드)

(sched.scheduler 메서드)

(threading.Timer 메서드)

cancel_dump_traceback_later() (faulthandler 모듈)

cancel_join_thread() (multiprocessing.Queue 메서드)

cancelled() (asyncio.Future 메서드)

(asyncio.Handle 메서드)

(asyncio.Task 메서드)

(concurrent.futures.Future 메서드)

CancelledError, [1]

CannotSendHeader

CannotSendRequest

canonic() (bdb.Bdb 메서드)

canonical() (decimal.Context 메서드)

(decimal.Decimal 메서드)

capa() (poplib.POP3 메서드)

capitalize() (bytearray 메서드)

(bytes 메서드)

(str 메서드)

Capsule

객체

captured_stderr() (test.support 모듈)

captured_stdin() (test.support 모듈)

captured_stdout() (test.support 모듈)

captureWarnings() (logging 모듈)

capwords() (string 모듈)

casefold() (str 메서드)

cast() (ctypes 모듈)

(memoryview 메서드)

(typing 모듈)

cat() (nis 모듈)

catch_warnings (warnings 클래스)

category() (unicodedata 모듈)

cbreak() (curses 모듈)

CC

ccc() (ftplib.FTP_TLS 메서드)

CCompiler (distutils.ccompiler 클래스)

CDLL (ctypes 클래스)

ceil() (in module math)

(math 모듈)

center() (bytearray 메서드)

(bytes 메서드)

(str 메서드)

CERT_NONE (ssl 모듈)

CERT_OPTIONAL (ssl 모듈)

CERT_REQUIRED (ssl 모듈)

cert_store_stats() (ssl.SSLContext 메서드)

cert_time_to_seconds() (ssl 모듈)

CertificateError

certificates

CFLAGS, [1], [2]

CFUNCTYPE() (ctypes 모듈)

CGI

debugging

exceptions

protocol

security

tracebacks

cgi (모듈)

cgi_directories (http.server.CGIHTTPRequestHandler의 속성)

CGIHandler (wsgiref.handlers 클래스)

CGIHTTPRequestHandler (http.server 클래스)

cgitb (모듈)

CGIXMLRPCRequestHandler (xmlrpc.server 클래스)

chain() (itertools 모듈)

chaining

comparisons, [1]

exception

ChainMap (collections 클래스)

(typing 클래스)

change_cwd() (test.support 모듈)

change_root() (distutils.util 모듈)

CHANNEL_BINDING_TYPES (ssl 모듈)

channel_class (smtpd.SMTPServer의 속성)

channels() (ossaudiodev.oss_audio_device 메서드)

CHAR_MAX (locale 모듈)

character, [1], [2]

CharacterDataHandler() (xml.parsers.expat.xmlparser 메서드)

characters() (xml.sax.handler.ContentHandler 메서드)

characters_written (BlockingIOError의 속성)

Charset (email.charset 클래스)

charset() (gettext.NullTranslations 메서드)

chdir() (os 모듈)

check (lzma.LZMADecompressor의 속성)

check() (imaplib.IMAP4 메서드)

(tabnanny 모듈)

check__all__() (test.support 모듈)

check_call() (subprocess 모듈)

check_environ() (distutils.util 모듈)

check_free_after_iterating() (test.support 모듈)

check_hostname (ssl.SSLContext의 속성)

check_impl_detail() (test.support 모듈)

check_no_resource_warning() (test.support 모듈)

check_output() (doctest.OutputChecker 메서드)

(subprocess 모듈)

check_returncode() (subprocess.CompletedProcess 메서드)

check_syntax_error() (test.support 모듈)

check_unused_args() (string.Formatter 메서드)

check_warnings() (test.support 모듈)

checkbox() (msilib.Dialog 메서드)

checkcache() (linecache 모듈)

CHECKED_HASH (py_compile.PycInvalidationMode의 속성)

checkfuncname() (bdb 모듈)

CheckList (tkinter.tix 클래스)

checksizeof() (test.support 모듈)

checksum

Cyclic Redundancy Check

chflags() (os 모듈)

chgat() (curses.window 메서드)

childNodes (xml.dom.Node의 속성)

ChildProcessError

children (pyclbr.Class의 속성)

(pyclbr.Function의 속성)

chmod() (os 모듈)

(pathlib.Path 메서드)

choice() (random 모듈)

(secrets 모듈)

choices (optparse.Option의 속성)

choices() (random 모듈)

chown() (os 모듈)

(shutil 모듈)

chr

내장 함수

chr() (내장 함수)

chroot() (os 모듈)

Chunk (chunk 클래스)

chunk (모듈)

cipher

DES

cipher() (ssl.SSLSocket 메서드)

circle() (turtle 모듈)

CIRCUMFLEX (token 모듈)

CIRCUMFLEXEQUAL (token 모듈)

Clamped (decimal 클래스)

class

attribute

attribute assignment

body

constructor

definition, [1]

instance

name

객체, [1], [2]

글

Class (symtable 클래스)

class (클래스)

Class browser

class instance

attribute

attribute assignment

call

객체, [1], [2]

class object

call, [1], [2]

class variable (클래스 변수)

classmethod

내장 함수

classmethod() (내장 함수)

ClassMethodDescriptorType (types 모듈)

ClassVar (typing 모듈)

clause

CLD_CONTINUED (os 모듈)

CLD_DUMPED (os 모듈)

CLD_EXITED (os 모듈)

CLD_TRAPPED (os 모듈)

clean() (mailbox.Maildir 메서드)

cleandoc() (inspect 모듈)

CleanImport (test.support 클래스)

cleanup functions

clear (pdb command)

Clear Breakpoint

clear() (asyncio.Event 메서드)

(collections.deque 메서드)

(curses.window 메서드)

(dict 메서드)

(email.message.EmailMessage 메서드)

(frame 메서드)

(frozenset 메서드)

(http.cookiejar.CookieJar 메서드)

(mailbox.Mailbox 메서드)

(sequence method)

(threading.Event 메서드)

(turtle 모듈), [1]

(xml.etree.ElementTree.Element 메서드)

clear_all_breaks() (bdb.Bdb 메서드)

clear_all_file_breaks() (bdb.Bdb 메서드)

clear_bpbynumber() (bdb.Bdb 메서드)

clear_break() (bdb.Bdb 메서드)

clear_cache() (filecmp 모듈)

clear_content() (email.message.EmailMessage 메서드)

clear_flags() (decimal.Context 메서드)

clear_frames() (traceback 모듈)

clear_history() (readline 모듈)

clear_session_cookies() (http.cookiejar.CookieJar 메서드)

clear_traces() (tracemalloc 모듈)

clear_traps() (decimal.Context 메서드)

clearcache() (linecache 모듈)

ClearData() (msilib.Record 메서드)

clearok() (curses.window 메서드)

clearscreen() (turtle 모듈)

clearstamp() (turtle 모듈)

clearstamps() (turtle 모듈)

Client() (multiprocessing.connection 모듈)

client_address (http.server.BaseHTTPRequestHandler의 속성)

clock() (time 모듈)

CLOCK_BOOTTIME (time 모듈)

clock_getres() (time 모듈)

clock_gettime() (time 모듈)

clock_gettime_ns() (time 모듈)

CLOCK_HIGHRES (time 모듈)

CLOCK_MONOTONIC (time 모듈)

CLOCK_MONOTONIC_RAW (time 모듈)

CLOCK_PROCESS_CPUTIME_ID (time 모듈)

CLOCK_PROF (time 모듈)

CLOCK_REALTIME (time 모듈)

clock_settime() (time 모듈)

clock_settime_ns() (time 모듈)

CLOCK_THREAD_CPUTIME_ID (time 모듈)

CLOCK_UPTIME (time 모듈)

clone() (email.generator.BytesGenerator 메서드)

(email.generator.Generator 메서드)

(email.policy.Policy 메서드)

(pipes.Template 메서드)

(turtle 모듈)

cloneNode() (xml.dom.Node 메서드)

close() (aifc.aifc 메서드), [1]

(asyncio.AbstractChildWatcher 메서드)

(asyncio.BaseTransport 메서드)

(asyncio.loop 메서드)

(asyncio.Server 메서드)

(asyncio.StreamWriter 메서드)

(asyncio.SubprocessTransport 메서드)

(asyncore.dispatcher 메서드)

(chunk.Chunk 메서드)

(contextlib.ExitStack 메서드)

(coroutine 메서드)

(dbm.dumb.dumbdbm 메서드)

(dbm.gnu.gdbm 메서드)

(dbm.ndbm.ndbm 메서드)

(distutils.text_file.TextFile 메서드)

(email.parser.BytesFeedParser 메서드)

(fileinput 모듈)

(ftplib.FTP 메서드)

(generator 메서드)

(html.parser.HTMLParser 메서드)

(http.client.HTTPConnection 메서드)

(imaplib.IMAP4 메서드)

(in module os)

(io.IOBase 메서드)

(logging.FileHandler 메서드)

(logging.Handler 메서드)

(logging.handlers.MemoryHandler 메서드)

(logging.handlers.NTEventLogHandler 메서드)

(logging.handlers.SocketHandler 메서드)

(logging.handlers.SysLogHandler 메서드)

(mailbox.Mailbox 메서드)

(mailbox.Maildir 메서드)

(mailbox.MH 메서드)

(mmap.mmap 메서드)

Close() (msilib.Database 메서드)

(msilib.View 메서드)

close() (multiprocessing.connection.Connection 메서드)

(multiprocessing.connection.Listener 메서드)

(multiprocessing.pool.Pool 메서드)

(multiprocessing.Process 메서드)

(multiprocessing.Queue 메서드)

(os 모듈)

(os.scandir 메서드)

(ossaudiodev.oss_audio_device 메서드)

(ossaudiodev.oss_mixer_device 메서드)

(select.devpoll 메서드)

(select.epoll 메서드)

(select.kqueue 메서드)

(selectors.BaseSelector 메서드)

(shelve.Shelf 메서드)

(socket 모듈)

(socket.socket 메서드)

(sqlite3.Connection 메서드)

(sqlite3.Cursor 메서드)

(sunau.AU_read 메서드)

(sunau.AU_write 메서드)

(tarfile.TarFile 메서드)

(telnetlib.Telnet 메서드)

(urllib.request.BaseHandler 메서드)

(wave.Wave_read 메서드)

(wave.Wave_write 메서드)

Close() (winreg.PyHKEY 메서드)

close() (xml.etree.ElementTree.TreeBuilder 메서드)

(xml.etree.ElementTree.XMLParser 메서드)

(xml.etree.ElementTree.XMLPullParser 메서드)

(xml.sax.xmlreader.IncrementalParser 메서드)

(zipfile.ZipFile 메서드)

close_connection (http.server.BaseHTTPRequestHandler의 속성)

close_when_done() (asynchat.async_chat 메서드)

closed (http.client.HTTPResponse의 속성)

(io.IOBase의 속성)

(mmap.mmap의 속성)

(ossaudiodev.oss_audio_device의 속성)

(select.devpoll의 속성)

(select.epoll의 속성)

(select.kqueue의 속성)

CloseKey() (winreg 모듈)

closelog() (syslog 모듈)

closerange() (os 모듈)

closing() (contextlib 모듈)

clrtobot() (curses.window 메서드)

clrtoeol() (curses.window 메서드)

cmath (모듈)

cmd

모듈

Cmd (cmd 클래스)

cmd (subprocess.CalledProcessError의 속성)

(subprocess.TimeoutExpired의 속성)

(모듈)

cmdloop() (cmd.Cmd 메서드)

cmdqueue (cmd.Cmd의 속성)

cmp() (filecmp 모듈)

cmp_op (dis 모듈)

cmp_to_key() (functools 모듈)

cmpfiles() (filecmp 모듈)

CMSG_LEN() (socket 모듈)

CMSG_SPACE() (socket 모듈)

co_argcount (code object attribute)

CO_ASYNC_GENERATOR (inspect 모듈)

co_cellvars (code object attribute)

co_code (code object attribute)

co_consts (code object attribute)

CO_COROUTINE (inspect 모듈)

co_filename (code object attribute)

co_firstlineno (code object attribute)

co_flags (code object attribute)

co_freevars (code object attribute)

CO_FUTURE_DIVISION (C 변수)

CO_GENERATOR (inspect 모듈)

CO_ITERABLE_COROUTINE (inspect 모듈)

co_lnotab (code object attribute)

co_name (code object attribute)

co_names (code object attribute)

CO_NESTED (inspect 모듈)

CO_NEWLOCALS (inspect 모듈)

co_nlocals (code object attribute)

CO_NOFREE (inspect 모듈)

CO_OPTIMIZED (inspect 모듈)

co_stacksize (code object attribute)

CO_VARARGS (inspect 모듈)

CO_VARKEYWORDS (inspect 모듈)

co_varnames (code object attribute)

code

block

code (SystemExit의 속성)

(urllib.error.HTTPError의 속성)

(xml.etree.ElementTree.ParseError의 속성)

(xml.parsers.expat.ExpatError의 속성)

(모듈)

code object, [1], [2], [3]

code_info() (dis 모듈)

CodecInfo (codecs 클래스)

Codecs

decode

encode

codecs (모듈)

coded_value (http.cookies.Morsel의 속성)

codeop (모듈)

codepoint2name (html.entities 모듈)

codes (xml.parsers.expat.errors 모듈)

CODESET (locale 모듈)

CodeType (types 모듈)

coding

style

coercion (코어션)

col_offset (ast.AST의 속성)

collapse_addresses() (ipaddress 모듈)

collapse_rfc2231_value() (email.utils 모듈)

collect() (gc 모듈)

collect_incoming_data() (asynchat.async_chat 메서드)

Collection (collections.abc 클래스)

(typing 클래스)

collections (모듈)

collections.abc (모듈)

colno (json.JSONDecodeError의 속성)

(re.error의 속성)

COLON (token 모듈)

color() (turtle 모듈)

color_content() (curses 모듈)

color_pair() (curses 모듈)

colormode() (turtle 모듈)

colorsys (모듈)

COLS, [1]

column() (tkinter.ttk.Treeview 메서드)

COLUMNS, [1]

columns (os.terminal_size의 속성)

combinations() (itertools 모듈)

combinations_with_replacement() (itertools 모듈)

combine() (datetime.datetime의 클래스 메서드)

combining() (unicodedata 모듈)

ComboBox (tkinter.tix 클래스)

Combobox (tkinter.ttk 클래스)

comma

trailing

COMMA (token 모듈)

Command (distutils.cmd 클래스)

(distutils.core 클래스)

command (http.server.BaseHTTPRequestHandler의 속성)

command line

command line option

--check-hash-based-pycs default|always|never

--help

--version

-?

-b

-B

-c <command>

-d

-E

-h

-i

-I

-J

-m <module-name>

-O

-OO

-q

-R

-s

-S

-u

-V

-v

-W arg

-x

-X

CommandCompiler (codeop 클래스)

commands (pdb command)

comment

(http.cookiejar.Cookie의 속성)

COMMENT (token 모듈)

comment (zipfile.ZipFile의 속성)

(zipfile.ZipInfo의 속성)

Comment() (xml.etree.ElementTree 모듈)

comment_url (http.cookiejar.Cookie의 속성)

commenters (shlex.shlex의 속성)

CommentHandler() (xml.parsers.expat.xmlparser 메서드)

commit() (msilib.CAB 메서드)

Commit() (msilib.Database 메서드)

commit() (sqlite3.Connection 메서드)

common (filecmp.dircmp의 속성)

Common Gateway Interface

common_dirs (filecmp.dircmp의 속성)

common_files (filecmp.dircmp의 속성)

common_funny (filecmp.dircmp의 속성)

common_types (mimetypes 모듈)

commonpath() (os.path 모듈)

commonprefix() (os.path 모듈)

communicate() (asyncio.asyncio.subprocess.Process의 메서드)

(subprocess.Popen 메서드)

compare() (decimal.Context 메서드)

(decimal.Decimal 메서드)

(difflib.Differ 메서드)

compare_digest() (hmac 모듈)

(secrets 모듈)

compare_networks() (ipaddress.IPv4Network 메서드)

(ipaddress.IPv6Network 메서드)

COMPARE_OP (opcode)

compare_signal() (decimal.Context 메서드)

(decimal.Decimal 메서드)

compare_to() (tracemalloc.Snapshot 메서드)

compare_total() (decimal.Context 메서드)

(decimal.Decimal 메서드)

compare_total_mag() (decimal.Context 메서드)

(decimal.Decimal 메서드)

comparing

objects

comparison

operator

COMPARISON_FLAGS (doctest 모듈)

comparisons

chaining, [1]

compat32 (email.policy 모듈)

Compat32 (email.policy 클래스)

compile

내장 함수, [1], [2], [3], [4]

Compile (codeop 클래스)

compile() (distutils.ccompiler.CCompiler 메서드)

(parser.ST 메서드)

(py_compile 모듈)

(re 모듈)

(내장 함수)

compile_command() (code 모듈)

(codeop 모듈)

compile_dir() (compileall 모듈)

compile_file() (compileall 모듈)

compile_path() (compileall 모듈)

compileall (모듈)

compileall command line option

--invalidation-mode [timestamp|checked-hash|unchecked-hash]

-b

-d destdir

-f

-i list

-j N

-l

-q

-r

-x regex

directory ...

file ...

compilest() (parser 모듈)

complete() (rlcompleter.Completer 메서드)

complete_statement() (sqlite3 모듈)

completedefault() (cmd.Cmd 메서드)

CompletedProcess (subprocess 클래스)

complex

number

객체

내장 함수, [1]

Complex (numbers 클래스)

complex (내장 클래스)

complex literal

complex number

literals

객체, [1]

complex number (복소수)

compound

statement

comprehensions

list

compress() (bz2 모듈)

(bz2.BZ2Compressor 메서드)

(gzip 모듈)

(itertools 모듈)

(lzma 모듈)

(lzma.LZMACompressor 메서드)

(zlib 모듈)

(zlib.Compress 메서드)

compress_size (zipfile.ZipInfo의 속성)

compress_type (zipfile.ZipInfo의 속성)

compressed (ipaddress.IPv4Address의 속성)

(ipaddress.IPv4Network의 속성)

(ipaddress.IPv6Address의 속성)

(ipaddress.IPv6Network의 속성)

compression() (ssl.SSLSocket 메서드)

CompressionError

compressobj() (zlib 모듈)

COMSPEC, [1]

concat() (operator 모듈)

concatenation

operation

concurrent.futures (모듈)

Condition (asyncio 클래스)

(multiprocessing 클래스)

condition (pdb command)

Condition (threading 클래스)

condition() (msilib.Control 메서드)

Condition() (multiprocessing.managers.SyncManager 메서드)

Conditional

expression

conditional

expression

ConfigParser (configparser 클래스)

configparser (모듈)

configuration

file

file, debugger

file, path

configuration information

configure() (tkinter.ttk.Style 메서드)

configure_mock() (unittest.mock.Mock 메서드)

confstr() (os 모듈)

confstr_names (os 모듈)

conjugate() (complex number method)

(decimal.Decimal 메서드)

(numbers.Complex의 메서드)

conn (smtpd.SMTPChannel의 속성)

connect() (asyncore.dispatcher 메서드)

(ftplib.FTP 메서드)

(http.client.HTTPConnection 메서드)

(multiprocessing.managers.BaseManager 메서드)

(smtplib.SMTP 메서드)

(socket.socket 메서드)

(sqlite3 모듈)

connect_accepted_socket() (asyncio.loop의 메서드)

connect_ex() (socket.socket 메서드)

connect_read_pipe() (asyncio.loop의 메서드)

connect_write_pipe() (asyncio.loop의 메서드)

Connection (multiprocessing.connection 클래스)

(sqlite3 클래스)

connection (sqlite3.Cursor의 속성)

connection_lost() (asyncio.BaseProtocol 메서드)

connection_made() (asyncio.BaseProtocol 메서드)

ConnectionAbortedError

ConnectionError

ConnectionRefusedError

ConnectionResetError

ConnectRegistry() (winreg 모듈)

const (optparse.Option의 속성)

constant

constructor

class

constructor() (copyreg 모듈)

consumed (asyncio.LimitOverrunError의 속성)

container, [1]

iteration over

Container (collections.abc 클래스)

(typing 클래스)

contains() (operator 모듈)

content type

MIME

content_manager (email.policy.EmailPolicy의 속성)

content_type (email.headerregistry.ContentTypeHeader의 속성)

ContentDispositionHeader (email.headerregistry 클래스)

ContentHandler (xml.sax.handler 클래스)

ContentManager (email.contentmanager 클래스)

contents (ctypes._Pointer의 속성)

contents() (importlib.abc.ResourceReader의 메서드)

(importlib.resources 모듈)

ContentTooShortError

ContentTransferEncoding (email.headerregistry 클래스)

ContentTypeHeader (email.headerregistry 클래스)

Context (contextvars 클래스)

(decimal 클래스)

context (ssl.SSLSocket의 속성)

context management protocol

context manager, [1]

(컨텍스트 관리자)

context variable (컨텍스트 변수)

context_diff() (difflib 모듈)

ContextDecorator (contextlib 클래스)

contextlib (모듈)

ContextManager (typing 클래스)

contextmanager() (contextlib 모듈)

ContextVar (contextvars 클래스)

contextvars (모듈)

contextvars.Token (contextvars 클래스)

contiguous

(memoryview의 속성)

(연속)

continue

글, [1], [2], [3], [4]

continue (pdb command)

CONTINUE_LOOP (opcode)

Control (msilib 클래스)

(tkinter.tix 클래스)

control() (msilib.Dialog 메서드)

(select.kqueue 메서드)

controlnames (curses.ascii 모듈)

controls() (ossaudiodev.oss_mixer_device 메서드)

conversion

arithmetic

string, [1]

ConversionError

conversions

numeric

convert_arg_line_to_args() (argparse.ArgumentParser 메서드)

convert_field() (string.Formatter 메서드)

convert_path() (distutils.util 모듈)

Cookie (http.cookiejar 클래스)

CookieError

CookieJar (http.cookiejar 클래스)

cookiejar (urllib.request.HTTPCookieProcessor의 속성)

CookiePolicy (http.cookiejar 클래스)

Coordinated Universal Time

Copy

copy

protocol

모듈

copy (모듈)

copy() (collections.deque 메서드)

(contextvars.Context 메서드)

(copy 모듈)

(decimal.Context 메서드)

(dict 메서드)

(frozenset 메서드)

(hashlib.hash 메서드)

(hmac.HMAC 메서드)

(http.cookies.Morsel 메서드)

(imaplib.IMAP4 메서드)

(multiprocessing.sharedctypes 모듈)

(pipes.Template 메서드)

(sequence method)

(shutil 모듈)

(types.MappingProxyType 메서드)

(zlib.Compress 메서드)

(zlib.Decompress 메서드)

copy2() (shutil 모듈)

copy_abs() (decimal.Context 메서드)

(decimal.Decimal 메서드)

copy_context() (contextvars 모듈)

copy_decimal() (decimal.Context 메서드)

copy_file() (distutils.file_util 모듈)

copy_location() (ast 모듈)

copy_negate() (decimal.Context 메서드)

(decimal.Decimal 메서드)

copy_sign() (decimal.Context 메서드)

(decimal.Decimal 메서드)

copy_tree() (distutils.dir_util 모듈)

copyfile() (shutil 모듈)

copyfileobj() (shutil 모듈)

copying files

copymode() (shutil 모듈)

copyreg (모듈)

copyright (in module sys)

(sys 모듈)

(내장 변수)

copysign() (math 모듈)

copystat() (shutil 모듈)

copytree() (shutil 모듈)

coroutine, [1]

function

Coroutine (collections.abc 클래스)

(typing 클래스)

coroutine (코루틴)

coroutine function (코루틴 함수)

coroutine() (asyncio 모듈)

(types 모듈)

CoroutineType (types 모듈)

cos() (cmath 모듈)

(math 모듈)

cosh() (cmath 모듈)

(math 모듈)

count (tracemalloc.StatisticDiff의 속성)

(tracemalloc.Statistic의 속성)

count() (array.array 메서드)

(bytearray 메서드)

(bytes 메서드)

(collections.deque 메서드)

(itertools 모듈)

(sequence method)

(str 메서드)

count_diff (tracemalloc.StatisticDiff의 속성)

Counter (collections 클래스)

(typing 클래스)

countOf() (operator 모듈)

countTestCases() (unittest.TestCase 메서드)

(unittest.TestSuite 메서드)

CoverageResults (trace 클래스)

CPP

CPPFLAGS

cProfile (모듈)

CPU time, [1], [2]

cpu_count() (multiprocessing 모듈)

(os 모듈)

CPython

cpython_only() (test.support 모듈)

crawl_delay() (urllib.robotparser.RobotFileParser 메서드)

CRC (zipfile.ZipInfo의 속성)

crc32() (binascii 모듈)

(zlib 모듈)

crc_hqx() (binascii 모듈)

create() (imaplib.IMAP4 메서드)

(venv 모듈)

(venv.EnvBuilder 메서드)

create_aggregate() (sqlite3.Connection 메서드)

create_archive() (zipapp 모듈)

create_autospec() (unittest.mock 모듈)

CREATE_BREAKAWAY_FROM_JOB (subprocess 모듈)

create_collation() (sqlite3.Connection 메서드)

create_configuration() (venv.EnvBuilder 메서드)

create_connection() (asyncio.loop의 메서드)

(socket 모듈)

create_datagram_endpoint() (asyncio.loop의 메서드)

create_decimal() (decimal.Context 메서드)

create_decimal_from_float() (decimal.Context 메서드)

create_default_context() (ssl 모듈)

CREATE_DEFAULT_ERROR_MODE (subprocess 모듈)

create_empty_file() (test.support 모듈)

create_function() (sqlite3.Connection 메서드)

create_future() (asyncio.loop 메서드)

create_module (C 함수)

create_module() (importlib.abc.Loader 메서드)

(importlib.machinery.ExtensionFileLoader 메서드)

CREATE_NEW_CONSOLE (subprocess 모듈)

CREATE_NEW_PROCESS_GROUP (subprocess 모듈)

CREATE_NO_WINDOW (subprocess 모듈)

create_server() (asyncio.loop의 메서드)

create_shortcut() (내장 함수)

create_socket() (asyncore.dispatcher 메서드)

create_static_lib() (distutils.ccompiler.CCompiler 메서드)

create_stats() (profile.Profile 메서드)

create_string_buffer() (ctypes 모듈)

create_subprocess_exec() (asyncio 모듈)

create_subprocess_shell() (asyncio 모듈)

create_system (zipfile.ZipInfo의 속성)

create_task() (asyncio 모듈)

(asyncio.loop 메서드)

create_tree() (distutils.dir_util 모듈)

create_unicode_buffer() (ctypes 모듈)

create_unix_connection() (asyncio.loop의 메서드)

create_unix_server() (asyncio.loop의 메서드)

create_version (zipfile.ZipInfo의 속성)

createAttribute() (xml.dom.Document 메서드)

createAttributeNS() (xml.dom.Document 메서드)

createComment() (xml.dom.Document 메서드)

createDocument() (xml.dom.DOMImplementation 메서드)

createDocumentType() (xml.dom.DOMImplementation 메서드)

createElement() (xml.dom.Document 메서드)

createElementNS() (xml.dom.Document 메서드)

createfilehandler() (tkinter.Widget.tk 메서드)

CreateKey() (winreg 모듈)

CreateKeyEx() (winreg 모듈)

createLock() (logging.Handler 메서드)

(logging.NullHandler 메서드)

createProcessingInstruction() (xml.dom.Document 메서드)

CreateRecord() (msilib 모듈)

createSocket() (logging.handlers.SocketHandler 메서드)

createTextNode() (xml.dom.Document 메서드)

credits (내장 변수)

critical() (logging 모듈)

(logging.Logger 메서드)

CRNCYSTR (locale 모듈)

cross() (audioop 모듈)

crypt

모듈

crypt (모듈)

crypt() (crypt 모듈)

crypt(3), [1], [2]

cryptography

cssclass_month (calendar.HTMLCalendar의 속성)

cssclass_month_head (calendar.HTMLCalendar의 속성)

cssclass_noday (calendar.HTMLCalendar의 속성)

cssclass_year (calendar.HTMLCalendar의 속성)

cssclass_year_head (calendar.HTMLCalendar의 속성)

cssclasses (calendar.HTMLCalendar의 속성)

cssclasses_weekday_head (calendar.HTMLCalendar의 속성)

csv

(모듈)

cte (email.headerregistry.ContentTransferEncoding의 속성)

cte_type (email.policy.Policy의 속성)

ctermid() (os 모듈)

ctime() (datetime.date 메서드)

(datetime.datetime 메서드)

(time 모듈)

ctrl() (curses.ascii 모듈)

CTRL_BREAK_EVENT (signal 모듈)

CTRL_C_EVENT (signal 모듈)

ctypes (모듈)

curdir (os 모듈)

currency() (locale 모듈)

current() (tkinter.ttk.Combobox 메서드)

current_process() (multiprocessing 모듈)

current_task() (asyncio 모듈)

(asyncio.Task의 클래스 메서드)

current_thread() (threading 모듈)

CurrentByteIndex (xml.parsers.expat.xmlparser의 속성)

CurrentColumnNumber (xml.parsers.expat.xmlparser의 속성)

currentframe() (inspect 모듈)

CurrentLineNumber (xml.parsers.expat.xmlparser의 속성)

curs_set() (curses 모듈)

curses (모듈)

curses.ascii (모듈)

curses.panel (모듈)

curses.textpad (모듈)

Cursor (sqlite3 클래스)

cursor() (sqlite3.Connection 메서드)

cursyncup() (curses.window 메서드)

customize_compiler() (distutils.sysconfig 모듈)

Cut

cwd() (ftplib.FTP 메서드)

(pathlib.Path의 클래스 메서드)

cycle() (itertools 모듈)

Cyclic Redundancy Check

탐색

색인

모듈 |

Python »

3.7.17 Documentation »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

Python »

3.7.17 Documentation »

|

Index – D

D_FMT (locale 모듈)

D_T_FMT (locale 모듈)

daemon (multiprocessing.Process의 속성)

(threading.Thread의 속성)

dangling

else

data

packing binary

tabular

type

type, immutable

data (collections.UserDict의 속성)

(collections.UserList의 속성)

(collections.UserString의 속성)

Data (plistlib 클래스)

data (select.kevent의 속성)

(selectors.SelectorKey의 속성)

(urllib.request.Request의 속성)

(xml.dom.Comment의 속성)

(xml.dom.ProcessingInstruction의 속성)

(xml.dom.Text의 속성)

(xmlrpc.client.Binary의 속성)

data() (xml.etree.ElementTree.TreeBuilder 메서드)

data_open() (urllib.request.DataHandler 메서드)

data_received() (asyncio.Protocol 메서드)

database

Unicode

DatabaseError

databases

dataclass() (dataclasses 모듈)

dataclasses (모듈)

datagram_received() (asyncio.DatagramProtocol 메서드)

DatagramHandler (logging.handlers 클래스)

DatagramProtocol (asyncio 클래스)

DatagramRequestHandler (socketserver 클래스)

DatagramTransport (asyncio 클래스)

DataHandler (urllib.request 클래스)

date (datetime 클래스)

date() (datetime.datetime 메서드)

(nntplib.NNTP 메서드)

date_time (zipfile.ZipInfo의 속성)

date_time_string() (http.server.BaseHTTPRequestHandler 메서드)

DateHeader (email.headerregistry 클래스)

datetime (datetime 클래스)

(email.headerregistry.DateHeader의 속성)

DateTime (xmlrpc.client 클래스)

datetime (모듈)

datum

day (datetime.datetime의 속성)

(datetime.date의 속성)

day_abbr (calendar 모듈)

day_name (calendar 모듈)

daylight (time 모듈)

Daylight Saving Time

DbfilenameShelf (shelve 클래스)

dbm (모듈)

dbm.dumb (모듈)

dbm.gnu

모듈, [1]

dbm.gnu (모듈)

dbm.ndbm

모듈, [1]

dbm.ndbm (모듈)

dcgettext() (locale 모듈)

deallocation, object

debug (imaplib.IMAP4의 속성)

(pdb command)

DEBUG (re 모듈)

debug (shlex.shlex의 속성)

(zipfile.ZipFile의 속성)

debug() (doctest 모듈)

(logging 모듈)

(logging.Logger 메서드)

(pipes.Template 메서드)

(unittest.TestCase 메서드)

(unittest.TestSuite 메서드)

DEBUG_BYTECODE_SUFFIXES (importlib.machinery 모듈)

DEBUG_COLLECTABLE (gc 모듈)

DEBUG_LEAK (gc 모듈)

debug_print() (distutils.ccompiler.CCompiler 메서드)

DEBUG_SAVEALL (gc 모듈)

debug_src() (doctest 모듈)

DEBUG_STATS (gc 모듈)

DEBUG_UNCOLLECTABLE (gc 모듈)

debugger, [1], [2]

configuration file

debugging

assertions

CGI

DebuggingServer (smtpd 클래스)

debuglevel (http.client.HTTPResponse의 속성)

DebugRunner (doctest 클래스)

Decimal (decimal 클래스)

decimal (모듈)

decimal literal

decimal() (unicodedata 모듈)

DecimalException (decimal 클래스)

decode

Codecs

decode (codecs.CodecInfo의 속성)

decode() (base64 모듈)

(bytearray 메서드)

(bytes 메서드)

(codecs 모듈)

(codecs.Codec 메서드)

(codecs.IncrementalDecoder 메서드)

(json.JSONDecoder 메서드)

(quopri 모듈)

(uu 모듈)

(xmlrpc.client.Binary 메서드)

(xmlrpc.client.DateTime 메서드)

decode_header() (email.header 모듈)

(nntplib 모듈)

decode_params() (email.utils 모듈)

decode_rfc2231() (email.utils 모듈)

decode_source() (importlib.util 모듈)

decodebytes() (base64 모듈)

DecodedGenerator (email.generator 클래스)

decodestring() (base64 모듈)

(quopri 모듈)

decomposition() (unicodedata 모듈)

decompress() (bz2 모듈)

(bz2.BZ2Decompressor 메서드)

(gzip 모듈)

(lzma 모듈)

(lzma.LZMADecompressor 메서드)

(zlib 모듈)

(zlib.Decompress 메서드)

decompressobj() (zlib 모듈)

decorator (데코레이터)

DEDENT (token 모듈)

DEDENT token, [1]

dedent() (textwrap 모듈)

deepcopy() (copy 모듈)

def

글

def_prog_mode() (curses 모듈)

def_shell_mode() (curses 모듈)

default

parameter value

default (email.policy 모듈)

(inspect.Parameter의 속성)

(optparse.Option의 속성)

DEFAULT (unittest.mock 모듈)

default() (cmd.Cmd 메서드)

(json.JSONEncoder 메서드)

DEFAULT_BUFFER_SIZE (io 모듈)

default_bufsize (xml.dom.pulldom 모듈)

default_exception_handler() (asyncio.loop 메서드)

default_factory (collections.defaultdict의 속성)

DEFAULT_FORMAT (tarfile 모듈)

DEFAULT_IGNORES (filecmp 모듈)

default_open() (urllib.request.BaseHandler 메서드)

DEFAULT_PROTOCOL (pickle 모듈)

default_timer() (timeit 모듈)

DefaultContext (decimal 클래스)

DefaultCookiePolicy (http.cookiejar 클래스)

defaultdict (collections 클래스)

DefaultDict (typing 클래스)

DefaultEventLoopPolicy (asyncio 클래스)

DefaultHandler() (xml.parsers.expat.xmlparser 메서드)

DefaultHandlerExpand() (xml.parsers.expat.xmlparser 메서드)

defaults() (configparser.ConfigParser 메서드)

DefaultSelector (selectors 클래스)

defaultTestLoader (unittest 모듈)

defaultTestResult() (unittest.TestCase 메서드)

defects (email.headerregistry.BaseHeader의 속성)

(email.message.EmailMessage의 속성)

(email.message.Message의 속성)

define_macro() (distutils.ccompiler.CCompiler 메서드)

definition

class, [1]

function, [1]

defpath (os 모듈)

DefragResult (urllib.parse 클래스)

DefragResultBytes (urllib.parse 클래스)

degrees() (math 모듈)

(turtle 모듈)

del

글, [1], [2], [3]

del_param() (email.message.EmailMessage 메서드)

(email.message.Message 메서드)

delattr() (내장 함수)

delay() (turtle 모듈)

delay_output() (curses 모듈)

delayload (http.cookiejar.FileCookieJar의 속성)

delch() (curses.window 메서드)

dele() (poplib.POP3 메서드)

delete() (ftplib.FTP 메서드)

(imaplib.IMAP4 메서드)

(tkinter.ttk.Treeview 메서드)

DELETE_ATTR (opcode)

DELETE_DEREF (opcode)

DELETE_FAST (opcode)

DELETE_GLOBAL (opcode)

DELETE_NAME (opcode)

DELETE_SUBSCR (opcode)

deleteacl() (imaplib.IMAP4 메서드)

deletefilehandler() (tkinter.Widget.tk 메서드)

DeleteKey() (winreg 모듈)

DeleteKeyEx() (winreg 모듈)

deleteln() (curses.window 메서드)

deleteMe() (bdb.Breakpoint 메서드)

DeleteValue() (winreg 모듈)

deletion

attribute

target

target list

delimiter (csv.Dialect의 속성)

delimiters

delitem() (operator 모듈)

deliver_challenge() (multiprocessing.connection 모듈)

delocalize() (locale 모듈)

demo_app() (wsgiref.simple_server 모듈)

denominator (fractions.Fraction의 속성)

(numbers.Rational의 속성)

DeprecationWarning

deque (collections 클래스)

Deque (typing 클래스)

dequeue() (logging.handlers.QueueListener 메서드)

DER_cert_to_PEM_cert() (ssl 모듈)

derwin() (curses.window 메서드)

DES

cipher

description (sqlite3.Cursor의 속성)

description() (nntplib.NNTP 메서드)

descriptions() (nntplib.NNTP 메서드)

descriptor (디스크립터)

dest (optparse.Option의 속성)

destructor, [1]

detach() (io.BufferedIOBase 메서드)

(io.TextIOBase 메서드)

(socket.socket 메서드)

(tkinter.ttk.Treeview 메서드)

(weakref.finalize 메서드)

Detach() (winreg.PyHKEY 메서드)

DETACHED_PROCESS (subprocess 모듈)

detect_api_mismatch() (test.support 모듈)

detect_encoding() (tokenize 모듈)

detect_language() (distutils.ccompiler.CCompiler 메서드)

deterministic profiling

device_encoding() (os 모듈)

devnull (os 모듈)

DEVNULL (subprocess 모듈)

devpoll() (select 모듈)

DevpollSelector (selectors 클래스)

dgettext() (gettext 모듈)

(locale 모듈)

Dialect (csv 클래스)

dialect (csv.csvreader의 속성)

(csv.csvwriter의 속성)

Dialog (msilib 클래스)

dict (2to3 fixer)

Dict (typing 클래스)

dict (내장 클래스)

dict() (multiprocessing.managers.SyncManager 메서드)

dictConfig() (logging.config 모듈)

dictionary

display

type, operations on

객체, [1], [2], [3], [4], [5], [6], [7]

dictionary (딕셔너리)

dictionary view (딕셔너리 뷰)

DictReader (csv 클래스)

DictWriter (csv 클래스)

diff_bytes() (difflib 모듈)

diff_files (filecmp.dircmp의 속성)

Differ (difflib 클래스), [1]

difference() (frozenset 메서드)

difference_update() (frozenset 메서드)

difflib (모듈)

digest() (hashlib.hash 메서드)

(hashlib.shake 메서드)

(hmac 모듈)

(hmac.HMAC 메서드)

digest_size (hmac.HMAC의 속성)

digit() (unicodedata 모듈)

digits (string 모듈)

dir() (ftplib.FTP 메서드)

(내장 함수)

dircmp (filecmp 클래스)

directory

changing

creating

deleting, [1]

site-packages

traversal, [1]

walking, [1]

directory (http.server.SimpleHTTPRequestHandler의 속성)

Directory (msilib 클래스)

directory ...

compileall command line option

directory_created() (내장 함수)

DirEntry (os 클래스)

DirList (tkinter.tix 클래스)

dirname() (os.path 모듈)

DirSelectBox (tkinter.tix 클래스)

DirSelectDialog (tkinter.tix 클래스)

DirsOnSysPath (test.support 클래스)

DirTree (tkinter.tix 클래스)

dis (모듈)

dis() (dis 모듈)

(dis.Bytecode 메서드)

(pickletools 모듈)

disable (pdb command)

disable() (bdb.Breakpoint 메서드)

(faulthandler 모듈)

(gc 모듈)

(logging 모듈)

(profile.Profile 메서드)

disable_faulthandler() (test.support 모듈)

disable_gc() (test.support 모듈)

disable_interspersed_args() (optparse.OptionParser 메서드)

DisableReflectionKey() (winreg 모듈)

disassemble() (dis 모듈)

discard (http.cookiejar.Cookie의 속성)

discard() (frozenset 메서드)

(mailbox.Mailbox 메서드)

(mailbox.MH 메서드)

discard_buffers() (asynchat.async_chat 메서드)

disco() (dis 모듈)

discover() (unittest.TestLoader 메서드)

disk_usage() (shutil 모듈)

dispatch_call() (bdb.Bdb 메서드)

dispatch_exception() (bdb.Bdb 메서드)

dispatch_line() (bdb.Bdb 메서드)

dispatch_return() (bdb.Bdb 메서드)

dispatch_table (pickle.Pickler의 속성)

dispatcher (asyncore 클래스)

dispatcher_with_send (asyncore 클래스)

display

dictionary

list

set

display (pdb command)

display_name (email.headerregistry.Address의 속성)

(email.headerregistry.Group의 속성)

displayhook() (sys 모듈)

dist() (platform 모듈)

distance() (turtle 모듈)

distb() (dis 모듈)

Distribution (distutils.core 클래스)

distutils (모듈)

distutils.archive_util (모듈)

distutils.bcppcompiler (모듈)

distutils.ccompiler (모듈)

distutils.cmd (모듈)

distutils.command (모듈)

distutils.command.bdist (모듈)

distutils.command.bdist_dumb (모듈)

distutils.command.bdist_msi (모듈)

distutils.command.bdist_packager (모듈)

distutils.command.bdist_rpm (모듈)

distutils.command.bdist_wininst (모듈)

distutils.command.build (모듈)

distutils.command.build_clib (모듈)

distutils.command.build_ext (모듈)

distutils.command.build_py (모듈)

distutils.command.build_scripts (모듈)

distutils.command.check (모듈)

distutils.command.clean (모듈)

distutils.command.config (모듈)

distutils.command.install (모듈)

distutils.command.install_data (모듈)

distutils.command.install_headers (모듈)

distutils.command.install_lib (모듈)

distutils.command.install_scripts (모듈)

distutils.command.register (모듈)

distutils.command.sdist (모듈)

distutils.core (모듈)

distutils.cygwinccompiler (모듈)

distutils.debug (모듈)

distutils.dep_util (모듈)

distutils.dir_util (모듈)

distutils.dist (모듈)

distutils.errors (모듈)

distutils.extension (모듈)

distutils.fancy_getopt (모듈)

distutils.file_util (모듈)

distutils.filelist (모듈)

distutils.log (모듈)

distutils.msvccompiler (모듈)

distutils.spawn (모듈)

distutils.sysconfig (모듈)

distutils.text_file (모듈)

distutils.unixccompiler (모듈)

distutils.util (모듈)

distutils.version (모듈)

DISTUTILS_DEBUG

divide() (decimal.Context 메서드)

divide_int() (decimal.Context 메서드)

division

DivisionByZero (decimal 클래스)

divmod

내장 함수, [1], [2]

divmod() (decimal.Context 메서드)

(내장 함수)

DllCanUnloadNow() (ctypes 모듈)

DllGetClassObject() (ctypes 모듈)

dllhandle (sys 모듈)

dngettext() (gettext 모듈)

do_clear() (bdb.Bdb 메서드)

do_command() (curses.textpad.Textbox 메서드)

do_GET() (http.server.SimpleHTTPRequestHandler 메서드)

do_handshake() (ssl.SSLSocket 메서드)

do_HEAD() (http.server.SimpleHTTPRequestHandler 메서드)

do_POST() (http.server.CGIHTTPRequestHandler 메서드)

doc (json.JSONDecodeError의 속성)

doc_header (cmd.Cmd의 속성)

DocCGIXMLRPCRequestHandler (xmlrpc.server 클래스)

DocFileSuite() (doctest 모듈)

doCleanups() (unittest.TestCase 메서드)

docmd() (smtplib.SMTP 메서드)

docstring

(doctest.DocTest의 속성)

(독스트링)

docstrings, [1]

DocTest (doctest 클래스)

doctest (모듈)

DocTestFailure

DocTestFinder (doctest 클래스)

DocTestParser (doctest 클래스)

DocTestRunner (doctest 클래스)

DocTestSuite() (doctest 모듈)

doctype() (xml.etree.ElementTree.TreeBuilder 메서드)

(xml.etree.ElementTree.XMLParser 메서드)

documentation

generation

online

documentation string

documentation strings, [1]

documentElement (xml.dom.Document의 속성)

DocXMLRPCRequestHandler (xmlrpc.server 클래스)

DocXMLRPCServer (xmlrpc.server 클래스)

domain (email.headerregistry.Address의 속성)

(tracemalloc.DomainFilter의 속성)

(tracemalloc.Filter의 속성)

(tracemalloc.Trace의 속성)

domain_initial_dot (http.cookiejar.Cookie의 속성)

domain_return_ok() (http.cookiejar.CookiePolicy 메서드)

domain_specified (http.cookiejar.Cookie의 속성)

DomainFilter (tracemalloc 클래스)

DomainLiberal (http.cookiejar.DefaultCookiePolicy의 속성)

DomainRFC2965Match (http.cookiejar.DefaultCookiePolicy의 속성)

DomainStrict (http.cookiejar.DefaultCookiePolicy의 속성)

DomainStrictNoDots (http.cookiejar.DefaultCookiePolicy의 속성)

DomainStrictNonDomain (http.cookiejar.DefaultCookiePolicy의 속성)

DOMEventStream (xml.dom.pulldom 클래스)

DOMException

DomstringSizeErr

done() (asyncio.Future 메서드)

(asyncio.Task 메서드)

(concurrent.futures.Future 메서드)

(turtle 모듈)

(xdrlib.Unpacker 메서드)

DONT_ACCEPT_BLANKLINE (doctest 모듈)

DONT_ACCEPT_TRUE_FOR_1 (doctest 모듈)

dont_write_bytecode (sys 모듈)

doRollover() (logging.handlers.RotatingFileHandler 메서드)

(logging.handlers.TimedRotatingFileHandler 메서드)

DOT (token 모듈)

dot() (turtle 모듈)

DOTALL (re 모듈)

doublequote (csv.Dialect의 속성)

DOUBLESLASH (token 모듈)

DOUBLESLASHEQUAL (token 모듈)

DOUBLESTAR (token 모듈)

DOUBLESTAREQUAL (token 모듈)

doupdate() (curses 모듈)

down (pdb command)

down() (turtle 모듈)

drain() (asyncio.StreamWriter의 메서드)

drop_whitespace (textwrap.TextWrapper의 속성)

dropwhile() (itertools 모듈)

dst() (datetime.datetime 메서드)

(datetime.time 메서드)

(datetime.timezone 메서드)

(datetime.tzinfo 메서드)

DTDHandler (xml.sax.handler 클래스)

duck-typing (덕 타이핑)

DumbWriter (formatter 클래스)

dummy_threading (모듈)

dump() (ast 모듈)

(json 모듈)

(marshal 모듈)

(pickle 모듈)

(pickle.Pickler 메서드)

(plistlib 모듈)

(tracemalloc.Snapshot 메서드)

(xml.etree.ElementTree 모듈)

dump_stats() (profile.Profile 메서드)

(pstats.Stats 메서드)

dump_traceback() (faulthandler 모듈)

dump_traceback_later() (faulthandler 모듈)

dumps() (json 모듈)

(marshal 모듈)

(pickle 모듈)

(plistlib 모듈)

(xmlrpc.client 모듈)

dup() (os 모듈)

(socket.socket 메서드)

dup2() (os 모듈)

DUP_TOP (opcode)

DUP_TOP_TWO (opcode)

DuplicateOptionError

DuplicateSectionError

dwFlags (subprocess.STARTUPINFO의 속성)

DynamicClassAttribute() (types 모듈)

탐색

색인

모듈 |

Python »

3.7.17 Documentation »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

Python »

3.7.17 Documentation »

|

Index – E

e

in numeric literal

e (cmath 모듈)

(math 모듈)

E2BIG (errno 모듈)

EACCES (errno 모듈)

EADDRINUSE (errno 모듈)

EADDRNOTAVAIL (errno 모듈)

EADV (errno 모듈)

EAFNOSUPPORT (errno 모듈)

EAFP

EAGAIN (errno 모듈)

EALREADY (errno 모듈)

east_asian_width() (unicodedata 모듈)

EBADE (errno 모듈)

EBADF (errno 모듈)

EBADFD (errno 모듈)

EBADMSG (errno 모듈)

EBADR (errno 모듈)

EBADRQC (errno 모듈)

EBADSLT (errno 모듈)

EBFONT (errno 모듈)

EBUSY (errno 모듈)

ECHILD (errno 모듈)

echo() (curses 모듈)

echochar() (curses.window 메서드)

ECHRNG (errno 모듈)

ECOMM (errno 모듈)

ECONNABORTED (errno 모듈)

ECONNREFUSED (errno 모듈)

ECONNRESET (errno 모듈)

EDEADLK (errno 모듈)

EDEADLOCK (errno 모듈)

EDESTADDRREQ (errno 모듈)

edit() (curses.textpad.Textbox 메서드)

EDOM (errno 모듈)

EDOTDOT (errno 모듈)

EDQUOT (errno 모듈)

EEXIST (errno 모듈)

EFAULT (errno 모듈)

EFBIG (errno 모듈)

effective() (bdb 모듈)

ehlo() (smtplib.SMTP 메서드)

ehlo_or_helo_if_needed() (smtplib.SMTP 메서드)

EHOSTDOWN (errno 모듈)

EHOSTUNREACH (errno 모듈)

EIDRM (errno 모듈)

EILSEQ (errno 모듈)

EINPROGRESS (errno 모듈)

EINTR (errno 모듈)

EINVAL (errno 모듈)

EIO (errno 모듈)

EISCONN (errno 모듈)

EISDIR (errno 모듈)

EISNAM (errno 모듈)

EL2HLT (errno 모듈)

EL2NSYNC (errno 모듈)

EL3HLT (errno 모듈)

EL3RST (errno 모듈)

Element (xml.etree.ElementTree 클래스)

element_create() (tkinter.ttk.Style 메서드)

element_names() (tkinter.ttk.Style 메서드)

element_options() (tkinter.ttk.Style 메서드)

ElementDeclHandler() (xml.parsers.expat.xmlparser 메서드)

elements() (collections.Counter 메서드)

ElementTree (xml.etree.ElementTree 클래스)

ELIBACC (errno 모듈)

ELIBBAD (errno 모듈)

ELIBEXEC (errno 모듈)

ELIBMAX (errno 모듈)

ELIBSCN (errno 모듈)

elif

키워드

Ellinghouse, Lance

Ellipsis

객체

ELLIPSIS (doctest 모듈)

(token 모듈)

Ellipsis (내장 변수)

ELNRNG (errno 모듈)

ELOOP (errno 모듈)

else

conditional expression

dangling

키워드, [1], [2], [3], [4], [5]

email (모듈)

email.charset (모듈)

email.contentmanager (모듈)

email.encoders (모듈)

email.errors (모듈)

email.generator (모듈)

email.header (모듈)

email.headerregistry (모듈)

email.iterators (모듈)

email.message (모듈)

email.mime (모듈)

email.parser (모듈)

email.policy (모듈)

email.utils (모듈)

EmailMessage (email.message 클래스)

EmailPolicy (email.policy 클래스)

EMFILE (errno 모듈)

emit() (logging.FileHandler 메서드)

(logging.Handler 메서드)

(logging.handlers.BufferingHandler 메서드)

(logging.handlers.DatagramHandler 메서드)

(logging.handlers.HTTPHandler 메서드)

(logging.handlers.NTEventLogHandler 메서드)

(logging.handlers.QueueHandler 메서드)

(logging.handlers.RotatingFileHandler 메서드)

(logging.handlers.SMTPHandler 메서드)

(logging.handlers.SocketHandler 메서드)

(logging.handlers.SysLogHandler 메서드)

(logging.handlers.TimedRotatingFileHandler 메서드)

(logging.handlers.WatchedFileHandler 메서드)

(logging.NullHandler 메서드)

(logging.StreamHandler 메서드)

EMLINK (errno 모듈)

Empty

empty

list

tuple, [1]

empty (inspect.Parameter의 속성)

(inspect.Signature의 속성)

empty() (asyncio.Queue 메서드)

(multiprocessing.Queue 메서드)

(multiprocessing.SimpleQueue 메서드)

(queue.Queue 메서드)

(queue.SimpleQueue 메서드)

(sched.scheduler 메서드)

EMPTY_NAMESPACE (xml.dom 모듈)

emptyline() (cmd.Cmd 메서드)

EMSGSIZE (errno 모듈)

EMULTIHOP (errno 모듈)

enable (pdb command)

enable() (bdb.Breakpoint 메서드)

(cgitb 모듈)

(faulthandler 모듈)

(gc 모듈)

(imaplib.IMAP4 메서드)

(profile.Profile 메서드)

enable_callback_tracebacks() (sqlite3 모듈)

enable_interspersed_args() (optparse.OptionParser 메서드)

enable_load_extension() (sqlite3.Connection 메서드)

enable_traversal() (tkinter.ttk.Notebook 메서드)

ENABLE_USER_SITE (site 모듈)

EnableReflectionKey() (winreg 모듈)

ENAMETOOLONG (errno 모듈)

ENAVAIL (errno 모듈)

enclose() (curses.window 메서드)

encode

Codecs

encode (codecs.CodecInfo의 속성)

encode() (base64 모듈)

(codecs 모듈)

(codecs.Codec 메서드)

(codecs.IncrementalEncoder 메서드)

(email.header.Header 메서드)

(json.JSONEncoder 메서드)

(quopri 모듈)

(str 메서드)

(uu 모듈)

(xmlrpc.client.Binary 메서드)

(xmlrpc.client.DateTime 메서드)

encode_7or8bit() (email.encoders 모듈)

encode_base64() (email.encoders 모듈)

encode_noop() (email.encoders 모듈)

encode_quopri() (email.encoders 모듈)

encode_rfc2231() (email.utils 모듈)

encodebytes() (base64 모듈)

EncodedFile() (codecs 모듈)

encodePriority() (logging.handlers.SysLogHandler 메서드)

encodestring() (base64 모듈)

(quopri 모듈)

encoding

base64

quoted-printable

encoding (curses.window의 속성)

(io.TextIOBase의 속성)

ENCODING (tarfile 모듈)

(token 모듈)

encoding (UnicodeError의 속성)

encoding declarations (source file)

encodings.idna (모듈)

encodings.mbcs (모듈)

encodings.utf_8_sig (모듈)

encodings_map (mimetypes 모듈)

(mimetypes.MimeTypes의 속성)

end (UnicodeError의 속성)

end() (re.Match 메서드)

(xml.etree.ElementTree.TreeBuilder 메서드)

end_fill() (turtle 모듈)

END_FINALLY (opcode)

end_headers() (http.server.BaseHTTPRequestHandler 메서드)

end_paragraph() (formatter.formatter 메서드)

end_poly() (turtle 모듈)

EndCdataSectionHandler() (xml.parsers.expat.xmlparser 메서드)

EndDoctypeDeclHandler() (xml.parsers.expat.xmlparser 메서드)

endDocument() (xml.sax.handler.ContentHandler 메서드)

endElement() (xml.sax.handler.ContentHandler 메서드)

EndElementHandler() (xml.parsers.expat.xmlparser 메서드)

endElementNS() (xml.sax.handler.ContentHandler 메서드)

endheaders() (http.client.HTTPConnection 메서드)

ENDMARKER (token 모듈)

EndNamespaceDeclHandler() (xml.parsers.expat.xmlparser 메서드)

endpos (re.Match의 속성)

endPrefixMapping() (xml.sax.handler.ContentHandler 메서드)

endswith() (bytearray 메서드)

(bytes 메서드)

(str 메서드)

endwin() (curses 모듈)

ENETDOWN (errno 모듈)

ENETRESET (errno 모듈)

ENETUNREACH (errno 모듈)

ENFILE (errno 모듈)

ENOANO (errno 모듈)

ENOBUFS (errno 모듈)

ENOCSI (errno 모듈)

ENODATA (errno 모듈)

ENODEV (errno 모듈)

ENOENT (errno 모듈)

ENOEXEC (errno 모듈)

ENOLCK (errno 모듈)

ENOLINK (errno 모듈)

ENOMEM (errno 모듈)

ENOMSG (errno 모듈)

ENONET (errno 모듈)

ENOPKG (errno 모듈)

ENOPROTOOPT (errno 모듈)

ENOSPC (errno 모듈)

ENOSR (errno 모듈)

ENOSTR (errno 모듈)

ENOSYS (errno 모듈)

ENOTBLK (errno 모듈)

ENOTCONN (errno 모듈)

ENOTDIR (errno 모듈)

ENOTEMPTY (errno 모듈)

ENOTNAM (errno 모듈)

ENOTSOCK (errno 모듈)

ENOTTY (errno 모듈)

ENOTUNIQ (errno 모듈)

enqueue() (logging.handlers.QueueHandler 메서드)

enqueue_sentinel() (logging.handlers.QueueListener 메서드)

ensure_directories() (venv.EnvBuilder 메서드)

ensure_future() (asyncio 모듈)

ensurepip (모듈)

enter() (sched.scheduler 메서드)

enter_async_context() (contextlib.AsyncExitStack 메서드)

enter_context() (contextlib.ExitStack 메서드)

enterabs() (sched.scheduler 메서드)

entities (xml.dom.DocumentType의 속성)

EntityDeclHandler() (xml.parsers.expat.xmlparser 메서드)

entitydefs (html.entities 모듈)

EntityResolver (xml.sax.handler 클래스)

Enum (enum 클래스)

enum (모듈)

enum_certificates() (ssl 모듈)

enum_crls() (ssl 모듈)

enumerate() (threading 모듈)

(내장 함수)

EnumKey() (winreg 모듈)

EnumValue() (winreg 모듈)

EnvBuilder (venv 클래스)

environ (os 모듈)

(posix 모듈)

environb (os 모듈)

environment

environment variables

deleting

setting

EnvironmentError

Environments

virtual

EnvironmentVarGuard (test.support 클래스)

ENXIO (errno 모듈)

eof (bz2.BZ2Decompressor의 속성)

(lzma.LZMADecompressor의 속성)

(shlex.shlex의 속성)

(ssl.MemoryBIO의 속성)

(zlib.Decompress의 속성)

eof_received() (asyncio.BufferedProtocol 메서드)

(asyncio.Protocol 메서드)

EOFError

(built-in exception)

EOPNOTSUPP (errno 모듈)

EOVERFLOW (errno 모듈)

EPERM (errno 모듈)

EPFNOSUPPORT (errno 모듈)

epilogue (email.message.EmailMessage의 속성)

(email.message.Message의 속성)

EPIPE (errno 모듈)

epoch

epoll() (select 모듈)

EpollSelector (selectors 클래스)

EPROTO (errno 모듈)

EPROTONOSUPPORT (errno 모듈)

EPROTOTYPE (errno 모듈)

eq() (operator 모듈)

EQEQUAL (token 모듈)

EQUAL (token 모듈)

ERA (locale 모듈)

ERA_D_FMT (locale 모듈)

ERA_D_T_FMT (locale 모듈)

ERA_T_FMT (locale 모듈)

ERANGE (errno 모듈)

erase() (curses.window 메서드)

erasechar() (curses 모듈)

EREMCHG (errno 모듈)

EREMOTE (errno 모듈)

EREMOTEIO (errno 모듈)

ERESTART (errno 모듈)

erf() (math 모듈)

erfc() (math 모듈)

EROFS (errno 모듈)

ERR (curses 모듈)

errcheck (ctypes._FuncPtr의 속성)

errcode (xmlrpc.client.ProtocolError의 속성)

errmsg (xmlrpc.client.ProtocolError의 속성)

errno

모듈

errno (OSError의 속성)

(모듈)

Error, [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12]

error, [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12], [13], [14], [15], [16], [17]

error handling

error() (argparse.ArgumentParser 메서드)

(logging 모듈)

(logging.Logger 메서드)

(urllib.request.OpenerDirector 메서드)

(xml.sax.handler.ErrorHandler 메서드)

error_body (wsgiref.handlers.BaseHandler의 속성)

error_content_type (http.server.BaseHTTPRequestHandler의 속성)

error_headers (wsgiref.handlers.BaseHandler의 속성)

error_leader() (shlex.shlex 메서드)

error_message_format (http.server.BaseHTTPRequestHandler의 속성)

error_output() (wsgiref.handlers.BaseHandler 메서드)

error_perm

error_proto, [1]

error_received() (asyncio.DatagramProtocol 메서드)

error_reply

error_status (wsgiref.handlers.BaseHandler의 속성)

error_temp

ErrorByteIndex (xml.parsers.expat.xmlparser의 속성)

errorcode (errno 모듈)

ErrorCode (xml.parsers.expat.xmlparser의 속성)

ErrorColumnNumber (xml.parsers.expat.xmlparser의 속성)

ErrorHandler (xml.sax.handler 클래스)

ErrorLineNumber (xml.parsers.expat.xmlparser의 속성)

Errors

logging

errors

(io.TextIOBase의 속성)

(unittest.TestLoader의 속성)

(unittest.TestResult의 속성)

ErrorString() (xml.parsers.expat 모듈)

ERRORTOKEN (token 모듈)

escape (shlex.shlex의 속성)

escape sequence

escape() (cgi 모듈)

(glob 모듈)

(html 모듈)

(re 모듈)

(xml.sax.saxutils 모듈)

escapechar (csv.Dialect의 속성)

escapedquotes (shlex.shlex의 속성)

ESHUTDOWN (errno 모듈)

ESOCKTNOSUPPORT (errno 모듈)

ESPIPE (errno 모듈)

ESRCH (errno 모듈)

ESRMNT (errno 모듈)

ESTALE (errno 모듈)

ESTRPIPE (errno 모듈)

ETIME (errno 모듈)

ETIMEDOUT (errno 모듈)

Etiny() (decimal.Context 메서드)

ETOOMANYREFS (errno 모듈)

Etop() (decimal.Context 메서드)

ETXTBSY (errno 모듈)

EUCLEAN (errno 모듈)

EUNATCH (errno 모듈)

EUSERS (errno 모듈)

eval

내장 함수, [1], [2], [3], [4], [5]

eval() (내장 함수)

evaluation

order

Event (asyncio 클래스)

(multiprocessing 클래스)

(threading 클래스)

event scheduling

event() (msilib.Control 메서드)

Event() (multiprocessing.managers.SyncManager 메서드)

events (selectors.SelectorKey의 속성)

(widgets)

EWOULDBLOCK (errno 모듈)

EX_CANTCREAT (os 모듈)

EX_CONFIG (os 모듈)

EX_DATAERR (os 모듈)

EX_IOERR (os 모듈)

EX_NOHOST (os 모듈)

EX_NOINPUT (os 모듈)

EX_NOPERM (os 모듈)

EX_NOTFOUND (os 모듈)

EX_NOUSER (os 모듈)

EX_OK (os 모듈)

EX_OSERR (os 모듈)

EX_OSFILE (os 모듈)

EX_PROTOCOL (os 모듈)

EX_SOFTWARE (os 모듈)

EX_TEMPFAIL (os 모듈)

EX_UNAVAILABLE (os 모듈)

EX_USAGE (os 모듈)

Example (doctest 클래스)

example (doctest.DocTestFailure의 속성)

(doctest.UnexpectedException의 속성)

examples (doctest.DocTest의 속성)

exc_info (doctest.UnexpectedException의 속성)

(in module sys)

exc_info() (in module sys)

(sys 모듈)

exc_msg (doctest.Example의 속성)

exc_type (traceback.TracebackException의 속성)

excel (csv 클래스)

excel_tab (csv 클래스)

except

글

키워드

except (2to3 fixer)

excepthook() (in module sys)

(sys 모듈)

Exception

exception, [1]

chaining

handler

raising

EXCEPTION (tkinter 모듈)

exception handler

exception() (asyncio.Future 메서드)

(asyncio.Task 메서드)

(concurrent.futures.Future 메서드)

(logging 모듈)

(logging.Logger 메서드)

exceptions

in CGI scripts

exclusive

or

EXDEV (errno 모듈)

exec

내장 함수, [1], [2], [3]

exec (2to3 fixer)

exec() (내장 함수)

exec_module (C 함수)

exec_module() (importlib.abc.InspectLoader 메서드)

(importlib.abc.Loader 메서드)

(importlib.abc.SourceLoader 메서드)

(importlib.machinery.ExtensionFileLoader 메서드)

exec_prefix, [1], [2]

EXEC_PREFIX (distutils.sysconfig 모듈)

exec_prefix (sys 모듈)

execfile (2to3 fixer)

execl() (os 모듈)

execle() (os 모듈)

execlp() (os 모듈)

execlpe() (os 모듈)

executable (in module sys)

(sys 모듈)

Executable Zip Files

executable_filename() (distutils.ccompiler.CCompiler 메서드)

execute() (distutils.ccompiler.CCompiler 메서드)

(distutils.util 모듈)

Execute() (msilib.View 메서드)

execute() (sqlite3.Connection 메서드)

(sqlite3.Cursor 메서드)

executemany() (sqlite3.Connection 메서드)

(sqlite3.Cursor 메서드)

executescript() (sqlite3.Connection 메서드)

(sqlite3.Cursor 메서드)

execution

frame, [1]

restricted

stack

execution model

ExecutionLoader (importlib.abc 클래스)

Executor (concurrent.futures 클래스)

execv() (os 모듈)

execve() (os 모듈)

execvp() (os 모듈)

execvpe() (os 모듈)

ExFileSelectBox (tkinter.tix 클래스)

EXFULL (errno 모듈)

exists() (os.path 모듈)

(pathlib.Path 메서드)

(tkinter.ttk.Treeview 메서드)

exit (내장 변수)

exit()

(_thread 모듈)

(argparse.ArgumentParser 메서드)

(sys 모듈)

exitcode (multiprocessing.Process의 속성)

exitfunc (2to3 fixer)

exitonclick() (turtle 모듈)

ExitStack (contextlib 클래스)

exp() (cmath 모듈)

(decimal.Context 메서드)

(decimal.Decimal 메서드)

(math 모듈)

expand() (re.Match 메서드)

expand_tabs (textwrap.TextWrapper의 속성)

ExpandEnvironmentStrings() (winreg 모듈)

expandNode() (xml.dom.pulldom.DOMEventStream 메서드)

expandtabs() (bytearray 메서드)

(bytes 메서드)

(str 메서드)

expanduser() (os.path 모듈)

(pathlib.Path 메서드)

expandvars() (os.path 모듈)

Expat

ExpatError

expect() (telnetlib.Telnet 메서드)

expected (asyncio.IncompleteReadError의 속성)

expectedFailure() (unittest 모듈)

expectedFailures (unittest.TestResult의 속성)

expires (http.cookiejar.Cookie의 속성)

exploded (ipaddress.IPv4Address의 속성)

(ipaddress.IPv4Network의 속성)

(ipaddress.IPv6Address의 속성)

(ipaddress.IPv6Network의 속성)

expm1() (math 모듈)

expovariate() (random 모듈)

expr() (parser 모듈)

expression

Conditional

conditional

generator

lambda, [1]

list, [1], [2]

statement

yield

expression (표현식)

expunge() (imaplib.IMAP4 메서드)

extend() (array.array 메서드)

(collections.deque 메서드)

(sequence method)

(xml.etree.ElementTree.Element 메서드)

extend_path() (pkgutil 모듈)

EXTENDED_ARG (opcode)

ExtendedContext (decimal 클래스)

ExtendedInterpolation (configparser 클래스)

extendleft() (collections.deque 메서드)

extension

module

Extension (distutils.core 클래스)

extension module (확장 모듈)

EXTENSION_SUFFIXES (importlib.machinery 모듈)

ExtensionFileLoader (importlib.machinery 클래스)

extensions_map (http.server.SimpleHTTPRequestHandler의 속성)

External Data Representation, [1]

external_attr (zipfile.ZipInfo의 속성)

ExternalClashError

ExternalEntityParserCreate() (xml.parsers.expat.xmlparser 메서드)

ExternalEntityRefHandler() (xml.parsers.expat.xmlparser 메서드)

extra (zipfile.ZipInfo의 속성)

extract() (tarfile.TarFile 메서드)

(traceback.StackSummary의 클래스 메서드)

(zipfile.ZipFile 메서드)

extract_cookies() (http.cookiejar.CookieJar 메서드)

extract_stack() (traceback 모듈)

extract_tb() (traceback 모듈)

extract_version (zipfile.ZipInfo의 속성)

extractall() (tarfile.TarFile 메서드)

(zipfile.ZipFile 메서드)

ExtractError

extractfile() (tarfile.TarFile 메서드)

extsep (os 모듈)

탐색

색인

모듈 |

Python »

3.7.17 Documentation »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

Python »

3.7.17 Documentation »

|

Index – F

f"

formatted string literal

f'

formatted string literal

f-string

(f-문자열)

f_back (frame attribute)

f_builtins (frame attribute)

f_code (frame attribute)

f_contiguous (memoryview의 속성)

f_globals (frame attribute)

f_lasti (frame attribute)

f_lineno (frame attribute)

f_locals (frame attribute)

F_LOCK (os 모듈)

F_OK (os 모듈)

F_TEST (os 모듈)

F_TLOCK (os 모듈)

f_trace (frame attribute)

f_trace_lines (frame attribute)

f_trace_opcodes (frame attribute)

F_ULOCK (os 모듈)

fabs() (math 모듈)

factorial() (math 모듈)

factory() (importlib.util.LazyLoader의 클래스 메서드)

fail() (unittest.TestCase 메서드)

FAIL_FAST (doctest 모듈)

failfast (unittest.TestResult의 속성)

failureException (unittest.TestCase의 속성)

failures (unittest.TestResult의 속성)

FakePath (test.support 클래스)

False, [1], [2]

false

False (Built-in object)

(내장 변수)

family (socket.socket의 속성)

fancy_getopt() (distutils.fancy_getopt 모듈)

FancyGetopt (distutils.fancy_getopt 클래스)

FancyURLopener (urllib.request 클래스)

fast (pickle.Pickler의 속성)

FastChildWatcher (asyncio 클래스)

fatalError() (xml.sax.handler.ErrorHandler 메서드)

Fault (xmlrpc.client 클래스)

faultCode (xmlrpc.client.Fault의 속성)

faulthandler (모듈)

faultString (xmlrpc.client.Fault의 속성)

fchdir() (os 모듈)

fchmod() (os 모듈)

fchown() (os 모듈)

FCICreate() (msilib 모듈)

fcntl (모듈)

fcntl() (fcntl 모듈)

fd (selectors.SelectorKey의 속성)

fd() (turtle 모듈)

fd_count() (test.support 모듈)

fdatasync() (os 모듈)

fdopen() (os 모듈)

Feature (msilib 클래스)

feature_external_ges (xml.sax.handler 모듈)

feature_external_pes (xml.sax.handler 모듈)

feature_namespace_prefixes (xml.sax.handler 모듈)

feature_namespaces (xml.sax.handler 모듈)

feature_string_interning (xml.sax.handler 모듈)

feature_validation (xml.sax.handler 모듈)

feed() (email.parser.BytesFeedParser 메서드)

(html.parser.HTMLParser 메서드)

(xml.etree.ElementTree.XMLParser 메서드)

(xml.etree.ElementTree.XMLPullParser 메서드)

(xml.sax.xmlreader.IncrementalParser 메서드)

FeedParser (email.parser 클래스)

fetch() (imaplib.IMAP4 메서드)

Fetch() (msilib.View 메서드)

fetchall() (sqlite3.Cursor 메서드)

fetchmany() (sqlite3.Cursor 메서드)

fetchone() (sqlite3.Cursor 메서드)

fflags (select.kevent의 속성)

Field (dataclasses 클래스)

field() (dataclasses 모듈)

field_size_limit() (csv 모듈)

fieldnames (csv.csvreader의 속성)

fields (uuid.UUID의 속성)

fields() (dataclasses 모듈)

file

.ini

.pdbrc

byte-code, [1]

configuration

copying

debugger configuration

large files

mime.types

modes

path configuration

plist

temporary

객체, [1]

file (pyclbr.Class의 속성)

(pyclbr.Function의 속성)

file ...

compileall command line option

file control

UNIX

file name

temporary

file object

io module

open() built-in function

file object (파일 객체)

file-like object (파일류 객체)

FILE_ATTRIBUTE_ARCHIVE (stat 모듈)

FILE_ATTRIBUTE_COMPRESSED (stat 모듈)

FILE_ATTRIBUTE_DEVICE (stat 모듈)

FILE_ATTRIBUTE_DIRECTORY (stat 모듈)

FILE_ATTRIBUTE_ENCRYPTED (stat 모듈)

FILE_ATTRIBUTE_HIDDEN (stat 모듈)

FILE_ATTRIBUTE_INTEGRITY_STREAM (stat 모듈)

FILE_ATTRIBUTE_NO_SCRUB_DATA (stat 모듈)

FILE_ATTRIBUTE_NORMAL (stat 모듈)

FILE_ATTRIBUTE_NOT_CONTENT_INDEXED (stat 모듈)

FILE_ATTRIBUTE_OFFLINE (stat 모듈)

FILE_ATTRIBUTE_READONLY (stat 모듈)

FILE_ATTRIBUTE_REPARSE_POINT (stat 모듈)

FILE_ATTRIBUTE_SPARSE_FILE (stat 모듈)

FILE_ATTRIBUTE_SYSTEM (stat 모듈)

FILE_ATTRIBUTE_TEMPORARY (stat 모듈)

FILE_ATTRIBUTE_VIRTUAL (stat 모듈)

file_created() (내장 함수)

file_dispatcher (asyncore 클래스)

file_open() (urllib.request.FileHandler 메서드)

file_size (zipfile.ZipInfo의 속성)

file_wrapper (asyncore 클래스)

filecmp (모듈)

fileConfig() (logging.config 모듈)

FileCookieJar (http.cookiejar 클래스)

FileEntry (tkinter.tix 클래스)

FileExistsError

FileFinder (importlib.machinery 클래스)

FileHandler (logging 클래스)

(urllib.request 클래스)

FileInput (fileinput 클래스)

fileinput (모듈)

FileIO (io 클래스)

filelineno() (fileinput 모듈)

FileLoader (importlib.abc 클래스)

filemode() (stat 모듈)

filename (doctest.DocTest의 속성)

(http.cookiejar.FileCookieJar의 속성)

(OSError의 속성)

(traceback.TracebackException의 속성)

(tracemalloc.Frame의 속성)

(zipfile.ZipFile의 속성)

(zipfile.ZipInfo의 속성)

filename() (fileinput 모듈)

filename2 (OSError의 속성)

filename_only (tabnanny 모듈)

filename_pattern (tracemalloc.Filter의 속성)

filenames

pathname expansion

wildcard expansion

fileno() (fileinput 모듈)

(http.client.HTTPResponse 메서드)

(io.IOBase 메서드)

(multiprocessing.connection.Connection 메서드)

(ossaudiodev.oss_audio_device 메서드)

(ossaudiodev.oss_mixer_device 메서드)

(select.devpoll 메서드)

(select.epoll 메서드)

(select.kqueue 메서드)

(selectors.DevpollSelector 메서드)

(selectors.EpollSelector 메서드)

(selectors.KqueueSelector 메서드)

(socket.socket 메서드)

(socketserver.BaseServer 메서드)

(telnetlib.Telnet 메서드)

FileNotFoundError

fileobj (selectors.SelectorKey의 속성)

FileSelectBox (tkinter.tix 클래스)

FileType (argparse 클래스)

FileWrapper (wsgiref.util 클래스)

fill() (textwrap 모듈)

(textwrap.TextWrapper 메서드)

fillcolor() (turtle 모듈)

filling() (turtle 모듈)

filter (2to3 fixer)

Filter (logging 클래스)

filter (select.kevent의 속성)

Filter (tracemalloc 클래스)

filter() (curses 모듈)

(fnmatch 모듈)

(logging.Filter 메서드)

(logging.Handler 메서드)

(logging.Logger 메서드)

(내장 함수)

FILTER_DIR (unittest.mock 모듈)

filter_traces() (tracemalloc.Snapshot 메서드)

filterfalse() (itertools 모듈)

filterwarnings() (warnings 모듈)

finalization, of objects

finalize (weakref 클래스)

finalize_options() (distutils.cmd.Command 메서드)

finalizer

finally

키워드, [1], [2], [3], [4]

find() (bytearray 메서드)

(bytes 메서드)

(doctest.DocTestFinder 메서드)

(gettext 모듈)

(mmap.mmap 메서드)

(str 메서드)

(xml.etree.ElementTree.Element 메서드)

(xml.etree.ElementTree.ElementTree 메서드)

find_class() (pickle protocol)

(pickle.Unpickler 메서드)

find_library() (ctypes.util 모듈)

find_library_file() (distutils.ccompiler.CCompiler 메서드)

find_loader() (importlib 모듈)

(importlib.abc.PathEntryFinder 메서드)

(importlib.machinery.FileFinder 메서드)

(pkgutil 모듈)

find_longest_match() (difflib.SequenceMatcher 메서드)

find_module() (imp 모듈)

(imp.NullImporter 메서드)

(importlib.abc.Finder의 메서드)

(importlib.abc.MetaPathFinder 메서드)

(importlib.abc.PathEntryFinder 메서드)

(importlib.machinery.PathFinder의 클래스 메서드)

(zipimport.zipimporter 메서드)

find_msvcrt() (ctypes.util 모듈)

find_spec

finder

find_spec() (importlib.abc.MetaPathFinder 메서드)

(importlib.abc.PathEntryFinder 메서드)

(importlib.machinery.FileFinder 메서드)

(importlib.machinery.PathFinder의 클래스 메서드)

(importlib.util 모듈)

find_unused_port() (test.support 모듈)

find_user_password() (urllib.request.HTTPPasswordMgr 메서드), [1]

findall() (re 모듈)

(re.Pattern 메서드)

(xml.etree.ElementTree.Element 메서드)

(xml.etree.ElementTree.ElementTree 메서드)

findCaller() (logging.Logger 메서드)

finder

find_spec

Finder (importlib.abc 클래스)

finder (파인더)

findfactor() (audioop 모듈)

findfile() (test.support 모듈)

findfit() (audioop 모듈)

finditer() (re 모듈)

(re.Pattern 메서드)

findlabels() (dis 모듈)

findlinestarts() (dis 모듈)

findmatch() (mailcap 모듈)

findmax() (audioop 모듈)

findtext() (xml.etree.ElementTree.Element 메서드)

(xml.etree.ElementTree.ElementTree 메서드)

finish() (socketserver.BaseRequestHandler 메서드)

finish_request() (socketserver.BaseServer 메서드)

firstChild (xml.dom.Node의 속성)

firstkey() (dbm.gnu.gdbm 메서드)

firstweekday() (calendar 모듈)

fix_missing_locations() (ast 모듈)

fix_sentence_endings (textwrap.TextWrapper의 속성)

Flag (enum 클래스)

flag_bits (zipfile.ZipInfo의 속성)

flags (re.Pattern의 속성)

(select.kevent의 속성)

(sys 모듈)

flash() (curses 모듈)

flatten() (email.generator.BytesGenerator 메서드)

(email.generator.Generator 메서드)

flattening

objects

float

내장 함수, [1], [2]

float (내장 클래스)

float_info (sys 모듈)

float_repr_style (sys 모듈)

floating point

literals

number

객체, [1], [2]

floating point literal

FloatingPointError

FloatOperation (decimal 클래스)

flock() (fcntl 모듈)

floor division (정수 나눗셈)

floor() (in module math)

(math 모듈)

floordiv() (operator 모듈)

flush() (bz2.BZ2Compressor 메서드)

(formatter.writer 메서드)

(io.BufferedWriter 메서드)

(io.IOBase 메서드)

(logging.Handler 메서드)

(logging.handlers.BufferingHandler 메서드)

(logging.handlers.MemoryHandler 메서드)

(logging.StreamHandler 메서드)

(lzma.LZMACompressor 메서드)

(mailbox.Mailbox 메서드)

(mailbox.Maildir 메서드)

(mailbox.MH 메서드)

(mmap.mmap 메서드)

(zlib.Compress 메서드)

(zlib.Decompress 메서드)

flush_headers() (http.server.BaseHTTPRequestHandler 메서드)

flush_softspace() (formatter.formatter 메서드)

flushinp() (curses 모듈)

FlushKey() (winreg 모듈)

fma() (decimal.Context 메서드)

(decimal.Decimal 메서드)

fmod() (math 모듈)

FMT_BINARY (plistlib 모듈)

FMT_XML (plistlib 모듈)

fnmatch (모듈)

fnmatch() (fnmatch 모듈)

fnmatchcase() (fnmatch 모듈)

focus() (tkinter.ttk.Treeview 메서드)

fold (datetime.datetime의 속성)

(datetime.time의 속성)

fold() (email.headerregistry.BaseHeader 메서드)

(email.policy.Compat32 메서드)

(email.policy.EmailPolicy 메서드)

(email.policy.Policy 메서드)

fold_binary() (email.policy.Compat32 메서드)

(email.policy.EmailPolicy 메서드)

(email.policy.Policy 메서드)

for

in comprehensions

글, [1], [2], [3]

FOR_ITER (opcode)

forget() (test.support 모듈)

(tkinter.ttk.Notebook 메서드)

fork() (os 모듈)

(pty 모듈)

ForkingMixIn (socketserver 클래스)

ForkingTCPServer (socketserver 클래스)

ForkingUDPServer (socketserver 클래스)

forkpty() (os 모듈)

form

lambda

Form (tkinter.tix 클래스)

format (memoryview의 속성)

(struct.Struct의 속성)

format() (built-in function)

__str__() (object method)

format() (locale 모듈)

(logging.Formatter 메서드)

(logging.Handler 메서드)

(pprint.PrettyPrinter 메서드)

(str 메서드)

(string.Formatter 메서드)

(traceback.StackSummary 메서드)

(traceback.TracebackException 메서드)

(tracemalloc.Traceback 메서드)

(내장 함수)

format_datetime() (email.utils 모듈)

format_exc() (traceback 모듈)

format_exception() (traceback 모듈)

format_exception_only() (traceback 모듈)

(traceback.TracebackException 메서드)

format_field() (string.Formatter 메서드)

format_help() (argparse.ArgumentParser 메서드)

format_list() (traceback 모듈)

format_map() (str 메서드)

format_stack() (traceback 모듈)

format_stack_entry() (bdb.Bdb 메서드)

format_string() (locale 모듈)

format_tb() (traceback 모듈)

format_usage() (argparse.ArgumentParser 메서드)

FORMAT_VALUE (opcode)

formataddr() (email.utils 모듈)

formatargspec() (inspect 모듈)

formatargvalues() (inspect 모듈)

formatdate() (email.utils 모듈)

FormatError

FormatError() (ctypes 모듈)

formatException() (logging.Formatter 메서드)

formatmonth() (calendar.HTMLCalendar 메서드)

(calendar.TextCalendar 메서드)

formatStack() (logging.Formatter 메서드)

formatted string literal

Formatter (logging 클래스)

(string 클래스)

formatter (모듈)

formatTime() (logging.Formatter 메서드)

formatting

bytearray (%)

bytes (%)

formatting, string (%)

formatwarning() (warnings 모듈)

formatyear() (calendar.HTMLCalendar 메서드)

(calendar.TextCalendar 메서드)

formatyearpage() (calendar.HTMLCalendar 메서드)

Fortran contiguous, [1]

forward() (turtle 모듈)

ForwardRef (typing 클래스)

found_terminator() (asynchat.async_chat 메서드)

fpathconf() (os 모듈)

fqdn (smtpd.SMTPChannel의 속성)

Fraction (fractions 클래스)

fractions (모듈)

frame

execution, [1]

객체

frame (tkinter.scrolledtext.ScrolledText의 속성)

Frame (tracemalloc 클래스)

FrameSummary (traceback 클래스)

FrameType (types 모듈)

free

variable

free()

freeze utility

freeze() (gc 모듈)

freeze_support() (multiprocessing 모듈)

frexp() (math 모듈)

from

import statement, [1]

yield from expression

키워드, [1]

from_address() (ctypes._CData 메서드)

from_buffer() (ctypes._CData 메서드)

from_buffer_copy() (ctypes._CData 메서드)

from_bytes() (int의 클래스 메서드)

from_callable() (inspect.Signature의 클래스 메서드)

from_decimal() (fractions.Fraction 메서드)

from_exception() (traceback.TracebackException의 클래스 메서드)

from_file() (zipfile.ZipInfo의 클래스 메서드)

from_float() (decimal.Decimal 메서드)

(fractions.Fraction 메서드)

from_iterable() (itertools.chain의 클래스 메서드)

from_list() (traceback.StackSummary의 클래스 메서드)

from_param() (ctypes._CData 메서드)

from_traceback() (dis.Bytecode의 클래스 메서드)

frombuf() (tarfile.TarInfo의 클래스 메서드)

frombytes() (array.array 메서드)

fromfd() (select.epoll 메서드)

(select.kqueue 메서드)

(socket 모듈)

fromfile() (array.array 메서드)

fromhex() (bytearray의 클래스 메서드)

(bytes의 클래스 메서드)

(float의 클래스 메서드)

fromisoformat() (datetime.datetime의 클래스 메서드)

(datetime.date의 클래스 메서드)

(datetime.time의 클래스 메서드)

fromkeys() (collections.Counter 메서드)

(dict의 클래스 메서드)

fromlist() (array.array 메서드)

fromordinal() (datetime.datetime의 클래스 메서드)

(datetime.date의 클래스 메서드)

fromshare() (socket 모듈)

fromstring() (array.array 메서드)

(xml.etree.ElementTree 모듈)

fromstringlist() (xml.etree.ElementTree 모듈)

fromtarfile() (tarfile.TarInfo의 클래스 메서드)

fromtimestamp() (datetime.datetime의 클래스 메서드)

(datetime.date의 클래스 메서드)

fromunicode() (array.array 메서드)

fromutc() (datetime.timezone 메서드)

(datetime.tzinfo 메서드)

FrozenImporter (importlib.machinery 클래스)

FrozenInstanceError

frozenset

객체, [1]

FrozenSet (typing 클래스)

frozenset (내장 클래스)

fs_is_case_insensitive() (test.support 모듈)

FS_NONASCII (test.support 모듈)

fsdecode() (os 모듈)

fsencode() (os 모듈)

fspath() (os 모듈)

fstat() (os 모듈)

fstatvfs() (os 모듈)

fsum() (math 모듈)

fsync() (os 모듈)

FTP

ftplib (standard module)

protocol, [1]

FTP (ftplib 클래스)

ftp_open() (urllib.request.FTPHandler 메서드)

FTP_TLS (ftplib 클래스)

FTPHandler (urllib.request 클래스)

ftplib (모듈)

ftruncate() (os 모듈)

Full

full() (asyncio.Queue 메서드)

(multiprocessing.Queue 메서드)

(queue.Queue 메서드)

full_url (urllib.request.Request의 속성)

fullmatch() (re 모듈)

(re.Pattern 메서드)

func (functools.partial의 속성)

funcattrs (2to3 fixer)

function

annotations, [1]

anonymous

argument

call, [1], [2]

call, user-defined

definition, [1]

generator, [1]

name, [1]

user-defined

객체, [1], [2], [3], [4], [5]

Function (symtable 클래스)

function (함수)

function annotation (함수 어노테이션)

function__entry (C 함수)

function__return (C 함수)

FunctionTestCase (unittest 클래스)

FunctionType (types 모듈)

functools (모듈)

funny_files (filecmp.dircmp의 속성)

future

statement

future (2to3 fixer)

Future (asyncio 클래스)

(concurrent.futures 클래스)

FutureWarning

fwalk() (os 모듈)

탐색

색인

모듈 |

Python »

3.7.17 Documentation »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

Python »

3.7.17 Documentation »

|

Index – G

G.722

gaierror

gamma() (math 모듈)

gammavariate() (random 모듈)

garbage (gc 모듈)

garbage collection

(가비지 수거)

gather() (curses.textpad.Textbox 메서드)

gauss() (random 모듈)

gc (모듈)

gc__done (C 함수)

gc__start (C 함수)

gc_collect() (test.support 모듈)

gcd() (fractions 모듈)

(math 모듈)

ge() (operator 모듈)

gen_lib_options() (distutils.ccompiler 모듈)

gen_preprocess_options() (distutils.ccompiler 모듈)

gen_uuid() (msilib 모듈)

generate_help() (distutils.fancy_getopt.FancyGetopt 메서드)

generator

expression

function, [1], [2]

iterator, [1]

객체, [1], [2]

Generator (collections.abc 클래스)

(email.generator 클래스)

(typing 클래스)

generator (제너레이터)

generator expression

(제너레이터 표현식)

generator iterator (제너레이터 이터레이터)

GeneratorExit

예외, [1]

GeneratorType (types 모듈)

generic

special attribute

Generic (typing 클래스)

generic function (제네릭 함수)

generic_visit() (ast.NodeVisitor 메서드)

genops() (pickletools 모듈)

get() (asyncio.Queue의 메서드)

(configparser.ConfigParser 메서드)

(contextvars.Context 메서드)

(contextvars.ContextVar 메서드)

(dict 메서드)

(email.message.EmailMessage 메서드)

(email.message.Message 메서드)

(mailbox.Mailbox 메서드)

(multiprocessing.pool.AsyncResult 메서드)

(multiprocessing.Queue 메서드)

(multiprocessing.SimpleQueue 메서드)

(ossaudiodev.oss_mixer_device 메서드)

(queue.Queue 메서드)

(queue.SimpleQueue 메서드)

(tkinter.ttk.Combobox 메서드)

(tkinter.ttk.Spinbox 메서드)

(types.MappingProxyType 메서드)

(webbrowser 모듈)

(xml.etree.ElementTree.Element 메서드)

GET_AITER (opcode)

get_all() (email.message.EmailMessage 메서드)

(email.message.Message 메서드)

(wsgiref.headers.Headers 메서드)

get_all_breaks() (bdb.Bdb 메서드)

get_all_start_methods() (multiprocessing 모듈)

GET_ANEXT (opcode)

get_app() (wsgiref.simple_server.WSGIServer 메서드)

get_archive_formats() (shutil 모듈)

get_asyncgen_hooks() (sys 모듈)

get_attribute() (test.support 모듈)

GET_AWAITABLE (opcode)

get_begidx() (readline 모듈)

get_blocking() (os 모듈)

get_body() (email.message.EmailMessage 메서드)

get_body_encoding() (email.charset.Charset 메서드)

get_boundary() (email.message.EmailMessage 메서드)

(email.message.Message 메서드)

get_bpbynumber() (bdb.Bdb 메서드)

get_break() (bdb.Bdb 메서드)

get_breaks() (bdb.Bdb 메서드)

get_buffer() (asyncio.BufferedProtocol 메서드)

(xdrlib.Packer 메서드)

(xdrlib.Unpacker 메서드)

get_bytes() (mailbox.Mailbox 메서드)

get_ca_certs() (ssl.SSLContext 메서드)

get_cache_token() (abc 모듈)

get_channel_binding() (ssl.SSLSocket 메서드)

get_charset() (email.message.Message 메서드)

get_charsets() (email.message.EmailMessage 메서드)

(email.message.Message 메서드)

get_child_watcher() (asyncio 모듈)

(asyncio.AbstractEventLoopPolicy 메서드)

get_children() (symtable.SymbolTable 메서드)

(tkinter.ttk.Treeview 메서드)

get_ciphers() (ssl.SSLContext 메서드)

get_clock_info() (time 모듈)

get_close_matches() (difflib 모듈)

get_code() (importlib.abc.InspectLoader 메서드)

(importlib.abc.SourceLoader 메서드)

(importlib.machinery.ExtensionFileLoader 메서드)

(importlib.machinery.SourcelessFileLoader 메서드)

(zipimport.zipimporter 메서드)

get_completer() (readline 모듈)

get_completer_delims() (readline 모듈)

get_completion_type() (readline 모듈)

get_config_h_filename() (distutils.sysconfig 모듈)

(sysconfig 모듈)

get_config_var() (distutils.sysconfig 모듈)

(sysconfig 모듈)

get_config_vars() (distutils.sysconfig 모듈)

(sysconfig 모듈)

get_content() (email.contentmanager 모듈)

(email.contentmanager.ContentManager 메서드)

(email.message.EmailMessage 메서드)

get_content_charset() (email.message.EmailMessage 메서드)

(email.message.Message 메서드)

get_content_disposition() (email.message.EmailMessage 메서드)

(email.message.Message 메서드)

get_content_maintype() (email.message.EmailMessage 메서드)

(email.message.Message 메서드)

get_content_subtype() (email.message.EmailMessage 메서드)

(email.message.Message 메서드)

get_content_type() (email.message.EmailMessage 메서드)

(email.message.Message 메서드)

get_context() (multiprocessing 모듈)

get_coroutine_origin_tracking_depth() (sys 모듈)

get_coroutine_wrapper() (sys 모듈)

get_count() (gc 모듈)

get_current_history_length() (readline 모듈)

get_data() (importlib.abc.FileLoader의 메서드)

(importlib.abc.ResourceLoader의 메서드)

(pkgutil 모듈)

(zipimport.zipimporter 메서드)

get_date() (mailbox.MaildirMessage 메서드)

get_debug() (asyncio.loop 메서드)

(gc 모듈)

get_default() (argparse.ArgumentParser 메서드)

get_default_compiler() (distutils.ccompiler 모듈)

get_default_domain() (nis 모듈)

get_default_type() (email.message.EmailMessage 메서드)

(email.message.Message 메서드)

get_default_verify_paths() (ssl 모듈)

get_dialect() (csv 모듈)

get_docstring() (ast 모듈)

get_doctest() (doctest.DocTestParser 메서드)

get_endidx() (readline 모듈)

get_environ() (wsgiref.simple_server.WSGIRequestHandler 메서드)

get_errno() (ctypes 모듈)

get_event_loop() (asyncio 모듈)

(asyncio.AbstractEventLoopPolicy 메서드)

get_event_loop_policy() (asyncio 모듈)

get_examples() (doctest.DocTestParser 메서드)

get_exception_handler() (asyncio.loop 메서드)

get_exec_path() (os 모듈)

get_extra_info() (asyncio.BaseTransport 메서드)

(asyncio.StreamWriter 메서드)

get_field() (string.Formatter 메서드)

get_file() (mailbox.Babyl 메서드)

(mailbox.Mailbox 메서드)

(mailbox.Maildir 메서드)

(mailbox.mbox 메서드)

(mailbox.MH 메서드)

(mailbox.MMDF 메서드)

get_file_breaks() (bdb.Bdb 메서드)

get_filename() (email.message.EmailMessage 메서드)

(email.message.Message 메서드)

(importlib.abc.ExecutionLoader의 메서드)

(importlib.abc.FileLoader의 메서드)

(importlib.machinery.ExtensionFileLoader 메서드)

(zipimport.zipimporter 메서드)

get_flags() (mailbox.MaildirMessage 메서드)

(mailbox.mboxMessage 메서드)

(mailbox.MMDFMessage 메서드)

get_folder() (mailbox.Maildir 메서드)

(mailbox.MH 메서드)

get_frees() (symtable.Function 메서드)

get_freeze_count() (gc 모듈)

get_from() (mailbox.mboxMessage 메서드)

(mailbox.MMDFMessage 메서드)

get_full_url() (urllib.request.Request 메서드)

get_globals() (symtable.Function 메서드)

get_grouped_opcodes() (difflib.SequenceMatcher 메서드)

get_handle_inheritable() (os 모듈)

get_header() (urllib.request.Request 메서드)

get_history_item() (readline 모듈)

get_history_length() (readline 모듈)

get_id() (symtable.SymbolTable 메서드)

get_ident() (_thread 모듈)

(threading 모듈)

get_identifiers() (symtable.SymbolTable 메서드)

get_importer() (pkgutil 모듈)

get_info() (mailbox.MaildirMessage 메서드)

get_inheritable() (os 모듈)

(socket.socket 메서드)

get_instructions() (dis 모듈)

get_int_max_str_digits() (sys 모듈)

get_interpreter() (zipapp 모듈)

GET_ITER (opcode)

get_key() (selectors.BaseSelector 메서드)

get_labels() (mailbox.Babyl 메서드)

(mailbox.BabylMessage 메서드)

get_last_error() (ctypes 모듈)

get_line_buffer() (readline 모듈)

get_lineno() (symtable.SymbolTable 메서드)

get_loader() (pkgutil 모듈)

get_locals() (symtable.Function 메서드)

get_logger() (multiprocessing 모듈)

get_loop() (asyncio.Future 메서드)

(asyncio.Server 메서드)

get_magic() (imp 모듈)

get_makefile_filename() (distutils.sysconfig 모듈)

(sysconfig 모듈)

get_map() (selectors.BaseSelector의 메서드)

get_matching_blocks() (difflib.SequenceMatcher 메서드)

get_message() (mailbox.Mailbox 메서드)

get_method() (urllib.request.Request 메서드)

get_methods() (symtable.Class 메서드)

get_mixed_type_key() (ipaddress 모듈)

get_name() (symtable.Symbol 메서드)

(symtable.SymbolTable 메서드)

get_namespace() (symtable.Symbol 메서드)

get_namespaces() (symtable.Symbol 메서드)

get_nonstandard_attr() (http.cookiejar.Cookie 메서드)

get_nowait() (asyncio.Queue 메서드)

(multiprocessing.Queue 메서드)

(queue.Queue 메서드)

(queue.SimpleQueue 메서드)

get_object_traceback() (tracemalloc 모듈)

get_objects() (gc 모듈)

get_opcodes() (difflib.SequenceMatcher 메서드)

get_option() (optparse.OptionParser 메서드)

get_option_group() (optparse.OptionParser 메서드)

get_option_order() (distutils.fancy_getopt.FancyGetopt 메서드)

get_original_stdout() (test.support 모듈)

get_osfhandle() (msvcrt 모듈)

get_output_charset() (email.charset.Charset 메서드)

get_param() (email.message.Message 메서드)

get_parameters() (symtable.Function 메서드)

get_params() (email.message.Message 메서드)

get_path() (sysconfig 모듈)

get_path_names() (sysconfig 모듈)

get_paths() (sysconfig 모듈)

get_payload() (email.message.Message 메서드)

get_pid() (asyncio.SubprocessTransport 메서드)

get_pipe_transport() (asyncio.SubprocessTransport 메서드)

get_platform() (distutils.util 모듈)

(sysconfig 모듈)

get_poly() (turtle 모듈)

get_position() (xdrlib.Unpacker 메서드)

get_protocol() (asyncio.BaseTransport 메서드)

get_python_inc() (distutils.sysconfig 모듈)

get_python_lib() (distutils.sysconfig 모듈)

get_python_version() (sysconfig 모듈)

get_recsrc() (ossaudiodev.oss_mixer_device 메서드)

get_referents() (gc 모듈)

get_referrers() (gc 모듈)

get_request() (socketserver.BaseServer 메서드)

get_returncode() (asyncio.SubprocessTransport 메서드)

get_running_loop() (asyncio 모듈)

get_scheme() (wsgiref.handlers.BaseHandler 메서드)

get_scheme_names() (sysconfig 모듈)

get_sequences() (mailbox.MH 메서드)

(mailbox.MHMessage 메서드)

get_server() (multiprocessing.managers.BaseManager 메서드)

get_server_certificate() (ssl 모듈)

get_shapepoly() (turtle 모듈)

get_socket() (telnetlib.Telnet 메서드)

get_source() (importlib.abc.InspectLoader의 메서드)

(importlib.abc.SourceLoader 메서드)

(importlib.machinery.ExtensionFileLoader 메서드)

(importlib.machinery.SourcelessFileLoader 메서드)

(zipimport.zipimporter 메서드)

get_special_folder_path() (내장 함수)

get_stack() (asyncio.Task 메서드)

(bdb.Bdb 메서드)

get_start_method() (multiprocessing 모듈)

get_starttag_text() (html.parser.HTMLParser 메서드)

get_stats() (gc 모듈)

get_stderr() (wsgiref.handlers.BaseHandler 메서드)

(wsgiref.simple_server.WSGIRequestHandler 메서드)

get_stdin() (wsgiref.handlers.BaseHandler 메서드)

get_string() (mailbox.Mailbox 메서드)

get_subdir() (mailbox.MaildirMessage 메서드)

get_suffixes() (imp 모듈)

get_symbols() (symtable.SymbolTable 메서드)

get_tag() (imp 모듈)

get_task_factory() (asyncio.loop 메서드)

get_terminal_size() (os 모듈)

(shutil 모듈)

get_terminator() (asynchat.async_chat 메서드)

get_threshold() (gc 모듈)

get_token() (shlex.shlex 메서드)

get_traceback_limit() (tracemalloc 모듈)

get_traced_memory() (tracemalloc 모듈)

get_tracemalloc_memory() (tracemalloc 모듈)

get_type() (symtable.SymbolTable 메서드)

get_type_hints() (typing 모듈)

get_unixfrom() (email.message.EmailMessage 메서드)

(email.message.Message 메서드)

get_unpack_formats() (shutil 모듈)

get_usage() (optparse.OptionParser 메서드)

get_value() (string.Formatter 메서드)

get_version() (optparse.OptionParser 메서드)

get_visible() (mailbox.BabylMessage 메서드)

get_wch() (curses.window 메서드)

get_write_buffer_limits() (asyncio.WriteTransport 메서드)

get_write_buffer_size() (asyncio.WriteTransport 메서드)

GET_YIELD_FROM_ITER (opcode)

getacl() (imaplib.IMAP4 메서드)

getaddresses() (email.utils 모듈)

getaddrinfo() (asyncio.loop의 메서드)

(socket 모듈)

getallocatedblocks() (sys 모듈)

getandroidapilevel() (sys 모듈)

getannotation() (imaplib.IMAP4 메서드)

getargspec() (inspect 모듈)

getargvalues() (inspect 모듈)

getatime() (os.path 모듈)

getattr() (내장 함수)

getattr_static() (inspect 모듈)

getAttribute() (xml.dom.Element 메서드)

getAttributeNode() (xml.dom.Element 메서드)

getAttributeNodeNS() (xml.dom.Element 메서드)

getAttributeNS() (xml.dom.Element 메서드)

GetBase() (xml.parsers.expat.xmlparser 메서드)

getbegyx() (curses.window 메서드)

getbkgd() (curses.window 메서드)

getblocking() (socket.socket 메서드)

getboolean() (configparser.ConfigParser 메서드)

getbuffer() (io.BytesIO 메서드)

getByteStream() (xml.sax.xmlreader.InputSource 메서드)

getcallargs() (inspect 모듈)

getcanvas() (turtle 모듈)

getcapabilities() (nntplib.NNTP 메서드)

getcaps() (mailcap 모듈)

getch() (curses.window 메서드)

(msvcrt 모듈)

getCharacterStream() (xml.sax.xmlreader.InputSource 메서드)

getche() (msvcrt 모듈)

getcheckinterval() (sys 모듈)

getChild() (logging.Logger 메서드)

getchildren() (xml.etree.ElementTree.Element 메서드)

getclasstree() (inspect 모듈)

getclosurevars() (inspect 모듈)

GetColumnInfo() (msilib.View 메서드)

getColumnNumber() (xml.sax.xmlreader.Locator 메서드)

getcomments() (inspect 모듈)

getcompname() (aifc.aifc 메서드)

(sunau.AU_read 메서드)

(wave.Wave_read 메서드)

getcomptype() (aifc.aifc 메서드)

(sunau.AU_read 메서드)

(wave.Wave_read 메서드)

getContentHandler() (xml.sax.xmlreader.XMLReader 메서드)

getcontext() (decimal 모듈)

getcoroutinelocals() (inspect 모듈)

getcoroutinestate() (inspect 모듈)

getctime() (os.path 모듈)

getcwd() (os 모듈)

getcwdb() (os 모듈)

getcwdu (2to3 fixer)

getdecoder() (codecs 모듈)

getdefaultencoding() (sys 모듈)

getdefaultlocale() (locale 모듈)

getdefaulttimeout() (socket 모듈)

getdlopenflags() (sys 모듈)

getdoc() (inspect 모듈)

getDOMImplementation() (xml.dom 모듈)

getDTDHandler() (xml.sax.xmlreader.XMLReader 메서드)

getEffectiveLevel() (logging.Logger 메서드)

getegid() (os 모듈)

getElementsByTagName() (xml.dom.Document 메서드)

(xml.dom.Element 메서드)

getElementsByTagNameNS() (xml.dom.Document 메서드)

(xml.dom.Element 메서드)

getencoder() (codecs 모듈)

getEncoding() (xml.sax.xmlreader.InputSource 메서드)

getEntityResolver() (xml.sax.xmlreader.XMLReader 메서드)

getenv() (os 모듈)

getenvb() (os 모듈)

getErrorHandler() (xml.sax.xmlreader.XMLReader 메서드)

geteuid() (os 모듈)

getEvent() (xml.dom.pulldom.DOMEventStream 메서드)

getEventCategory() (logging.handlers.NTEventLogHandler 메서드)

getEventType() (logging.handlers.NTEventLogHandler 메서드)

getException() (xml.sax.SAXException 메서드)

getFeature() (xml.sax.xmlreader.XMLReader 메서드)

GetFieldCount() (msilib.Record 메서드)

getfile() (inspect 모듈)

getfilesystemencodeerrors() (sys 모듈)

getfilesystemencoding() (sys 모듈)

getfirst() (cgi.FieldStorage 메서드)

getfloat() (configparser.ConfigParser 메서드)

getfmts() (ossaudiodev.oss_audio_device 메서드)

getfqdn() (socket 모듈)

getframeinfo() (inspect 모듈)

getframerate() (aifc.aifc 메서드)

(sunau.AU_read 메서드)

(wave.Wave_read 메서드)

getfullargspec() (inspect 모듈)

getgeneratorlocals() (inspect 모듈)

getgeneratorstate() (inspect 모듈)

getgid() (os 모듈)

getgrall() (grp 모듈)

getgrgid() (grp 모듈)

getgrnam() (grp 모듈)

getgrouplist() (os 모듈)

getgroups() (os 모듈)

getheader() (http.client.HTTPResponse 메서드)

getheaders() (http.client.HTTPResponse 메서드)

gethostbyaddr() (in module socket)

(socket 모듈)

gethostbyname() (socket 모듈)

gethostbyname_ex() (socket 모듈)

gethostname() (in module socket)

(socket 모듈)

getincrementaldecoder() (codecs 모듈)

getincrementalencoder() (codecs 모듈)

getinfo() (zipfile.ZipFile 메서드)

getinnerframes() (inspect 모듈)

GetInputContext() (xml.parsers.expat.xmlparser 메서드)

getint() (configparser.ConfigParser 메서드)

GetInteger() (msilib.Record 메서드)

getitem() (operator 모듈)

getiterator() (xml.etree.ElementTree.Element 메서드)

(xml.etree.ElementTree.ElementTree 메서드)

getitimer() (signal 모듈)

getkey() (curses.window 메서드)

GetLastError() (ctypes 모듈)

getLength() (xml.sax.xmlreader.Attributes 메서드)

getLevelName() (logging 모듈)

getline() (linecache 모듈)

getLineNumber() (xml.sax.xmlreader.Locator 메서드)

getlist() (cgi.FieldStorage 메서드)

getloadavg() (os 모듈)

getlocale() (locale 모듈)

getLogger() (logging 모듈)

getLoggerClass() (logging 모듈)

getlogin() (os 모듈)

getLogRecordFactory() (logging 모듈)

getmark() (aifc.aifc 메서드)

(sunau.AU_read 메서드)

(wave.Wave_read 메서드)

getmarkers() (aifc.aifc 메서드)

(sunau.AU_read 메서드)

(wave.Wave_read 메서드)

getmaxyx() (curses.window 메서드)

getmember() (tarfile.TarFile 메서드)

getmembers() (inspect 모듈)

(tarfile.TarFile 메서드)

getMessage() (logging.LogRecord 메서드)

(xml.sax.SAXException 메서드)

getMessageID() (logging.handlers.NTEventLogHandler 메서드)

getmodule() (inspect 모듈)

getmodulename() (inspect 모듈)

getmouse() (curses 모듈)

getmro() (inspect 모듈)

getmtime() (os.path 모듈)

getname() (chunk.Chunk 메서드)

getName() (threading.Thread 메서드)

getNameByQName() (xml.sax.xmlreader.AttributesNS 메서드)

getnameinfo() (asyncio.loop의 메서드)

(socket 모듈)

getnames() (tarfile.TarFile 메서드)

getNames() (xml.sax.xmlreader.Attributes 메서드)

getnchannels() (aifc.aifc 메서드)

(sunau.AU_read 메서드)

(wave.Wave_read 메서드)

getnframes() (aifc.aifc 메서드)

(sunau.AU_read 메서드)

(wave.Wave_read 메서드)

getnode

getnode() (uuid 모듈)

getopt (모듈)

getopt() (distutils.fancy_getopt.FancyGetopt 메서드)

(getopt 모듈)

GetoptError

getouterframes() (inspect 모듈)

getoutput() (subprocess 모듈)

getpagesize() (resource 모듈)

getparams() (aifc.aifc 메서드)

(sunau.AU_read 메서드)

(wave.Wave_read 메서드)

getparyx() (curses.window 메서드)

getpass (모듈)

getpass() (getpass 모듈)

GetPassWarning

getpeercert() (ssl.SSLSocket 메서드)

getpeername() (socket.socket 메서드)

getpen() (turtle 모듈)

getpgid() (os 모듈)

getpgrp() (os 모듈)

getpid() (os 모듈)

getpos() (html.parser.HTMLParser 메서드)

getppid() (os 모듈)

getpreferredencoding() (locale 모듈)

getpriority() (os 모듈)

getprofile() (sys 모듈)

GetProperty() (msilib.SummaryInformation 메서드)

getProperty() (xml.sax.xmlreader.XMLReader 메서드)

GetPropertyCount() (msilib.SummaryInformation 메서드)

getprotobyname() (socket 모듈)

getproxies() (urllib.request 모듈)

getPublicId() (xml.sax.xmlreader.InputSource 메서드)

(xml.sax.xmlreader.Locator 메서드)

getpwall() (pwd 모듈)

getpwnam() (pwd 모듈)

getpwuid() (pwd 모듈)

getQNameByName() (xml.sax.xmlreader.AttributesNS 메서드)

getQNames() (xml.sax.xmlreader.AttributesNS 메서드)

getquota() (imaplib.IMAP4 메서드)

getquotaroot() (imaplib.IMAP4 메서드)

getrandbits() (random 모듈)

getrandom() (os 모듈)

getreader() (codecs 모듈)

getrecursionlimit() (sys 모듈)

getrefcount() (sys 모듈)

getresgid() (os 모듈)

getresponse() (http.client.HTTPConnection 메서드)

getresuid() (os 모듈)

getrlimit() (resource 모듈)

getroot() (xml.etree.ElementTree.ElementTree 메서드)

getrusage() (resource 모듈)

getsample() (audioop 모듈)

getsampwidth() (aifc.aifc 메서드)

(sunau.AU_read 메서드)

(wave.Wave_read 메서드)

getscreen() (turtle 모듈)

getservbyname() (socket 모듈)

getservbyport() (socket 모듈)

GetSetDescriptorType (types 모듈)

getshapes() (turtle 모듈)

getsid() (os 모듈)

getsignal() (signal 모듈)

getsitepackages() (site 모듈)

getsize() (chunk.Chunk 메서드)

(os.path 모듈)

getsizeof() (sys 모듈)

getsockname() (socket.socket 메서드)

getsockopt() (socket.socket 메서드)

getsource() (inspect 모듈)

getsourcefile() (inspect 모듈)

getsourcelines() (inspect 모듈)

getspall() (spwd 모듈)

getspnam() (spwd 모듈)

getstate() (codecs.IncrementalDecoder 메서드)

(codecs.IncrementalEncoder 메서드)

(random 모듈)

getstatusoutput() (subprocess 모듈)

getstr() (curses.window 메서드)

GetString() (msilib.Record 메서드)

getSubject() (logging.handlers.SMTPHandler 메서드)

GetSummaryInformation() (msilib.Database 메서드)

getswitchinterval() (sys 모듈)

getSystemId() (xml.sax.xmlreader.InputSource 메서드)

(xml.sax.xmlreader.Locator 메서드)

getsyx() (curses 모듈)

gettarinfo() (tarfile.TarFile 메서드)

gettempdir() (tempfile 모듈)

gettempdirb() (tempfile 모듈)

gettempprefix() (tempfile 모듈)

gettempprefixb() (tempfile 모듈)

getTestCaseNames() (unittest.TestLoader 메서드)

gettext (모듈)

gettext() (gettext 모듈)

(gettext.GNUTranslations 메서드)

(gettext.NullTranslations 메서드)

(locale 모듈)

gettimeout() (socket.socket 메서드)

gettrace() (sys 모듈)

getturtle() (turtle 모듈)

getType() (xml.sax.xmlreader.Attributes 메서드)

getuid() (os 모듈)

geturl() (urllib.parse.urllib.parse.SplitResult 메서드)

getuser() (getpass 모듈)

getuserbase() (site 모듈)

getusersitepackages() (site 모듈)

getvalue() (io.BytesIO 메서드)

(io.StringIO 메서드)

getValue() (xml.sax.xmlreader.Attributes 메서드)

getValueByQName() (xml.sax.xmlreader.AttributesNS 메서드)

getwch() (msvcrt 모듈)

getwche() (msvcrt 모듈)

getweakrefcount() (weakref 모듈)

getweakrefs() (weakref 모듈)

getwelcome() (ftplib.FTP 메서드)

(nntplib.NNTP 메서드)

(poplib.POP3 메서드)

getwin() (curses 모듈)

getwindowsversion() (sys 모듈)

getwriter() (codecs 모듈)

getxattr() (os 모듈)

getyx() (curses.window 메서드)

gid (tarfile.TarInfo의 속성)

GIL

glob

모듈

glob (모듈)

glob() (glob 모듈)

(msilib.Directory 메서드)

(pathlib.Path 메서드)

global

name binding

namespace

글, [1]

global interpreter lock

(전역 인터프리터 록)

globals() (내장 함수)

globs (doctest.DocTest의 속성)

gmtime() (time 모듈)

gname (tarfile.TarInfo의 속성)

GNOME

GNU_FORMAT (tarfile 모듈)

gnu_getopt() (getopt 모듈)

GNUTranslations (gettext 클래스)

got (doctest.DocTestFailure의 속성)

goto() (turtle 모듈)

grammar

Graphical User Interface

GREATER (token 모듈)

GREATEREQUAL (token 모듈)

Greenwich Mean Time

GRND_NONBLOCK (os 모듈)

GRND_RANDOM (os 모듈)

Group (email.headerregistry 클래스)

group() (nntplib.NNTP 메서드)

(pathlib.Path 메서드)

(re.Match 메서드)

groupby() (itertools 모듈)

groupdict() (re.Match 메서드)

groupindex (re.Pattern의 속성)

grouping

groups (email.headerregistry.AddressHeader의 속성)

(re.Pattern의 속성)

groups() (re.Match 메서드)

grp (모듈)

gt() (operator 모듈)

guess_all_extensions() (mimetypes 모듈)

(mimetypes.MimeTypes 메서드)

guess_extension() (mimetypes 모듈)

(mimetypes.MimeTypes 메서드)

guess_scheme() (wsgiref.util 모듈)

guess_type() (mimetypes 모듈)

(mimetypes.MimeTypes 메서드)

GUI

gzip (모듈)

GzipFile (gzip 클래스)

탐색

색인

모듈 |

Python »

3.7.17 Documentation »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

Python »

3.7.17 Documentation »

|

Index – H

halfdelay() (curses 모듈)

Handle (asyncio 클래스)

handle an exception

handle() (http.server.BaseHTTPRequestHandler 메서드)

(logging.Handler 메서드)

(logging.handlers.QueueListener 메서드)

(logging.Logger 메서드)

(logging.NullHandler 메서드)

(socketserver.BaseRequestHandler 메서드)

(wsgiref.simple_server.WSGIRequestHandler 메서드)

handle_accept() (asyncore.dispatcher 메서드)

handle_accepted() (asyncore.dispatcher 메서드)

handle_charref() (html.parser.HTMLParser 메서드)

handle_close() (asyncore.dispatcher 메서드)

handle_comment() (html.parser.HTMLParser 메서드)

handle_connect() (asyncore.dispatcher 메서드)

handle_data() (html.parser.HTMLParser 메서드)

handle_decl() (html.parser.HTMLParser 메서드)

handle_defect() (email.policy.Policy 메서드)

handle_endtag() (html.parser.HTMLParser 메서드)

handle_entityref() (html.parser.HTMLParser 메서드)

handle_error() (asyncore.dispatcher 메서드)

(socketserver.BaseServer 메서드)

handle_expect_100() (http.server.BaseHTTPRequestHandler 메서드)

handle_expt() (asyncore.dispatcher 메서드)

handle_one_request() (http.server.BaseHTTPRequestHandler 메서드)

handle_pi() (html.parser.HTMLParser 메서드)

handle_read() (asyncore.dispatcher 메서드)

handle_request() (socketserver.BaseServer 메서드)

(xmlrpc.server.CGIXMLRPCRequestHandler 메서드)

handle_startendtag() (html.parser.HTMLParser 메서드)

handle_starttag() (html.parser.HTMLParser 메서드)

handle_timeout() (socketserver.BaseServer 메서드)

handle_write() (asyncore.dispatcher 메서드)

handleError() (logging.Handler 메서드)

(logging.handlers.SocketHandler 메서드)

handler

exception

Handler (logging 클래스)

handler() (cgitb 모듈)

harmonic_mean() (statistics 모듈)

HAS_ALPN (ssl 모듈)

has_children() (symtable.SymbolTable 메서드)

has_colors() (curses 모듈)

HAS_ECDH (ssl 모듈)

has_exec() (symtable.SymbolTable 메서드)

has_extn() (smtplib.SMTP 메서드)

has_function() (distutils.ccompiler.CCompiler 메서드)

has_header() (csv.Sniffer 메서드)

(urllib.request.Request 메서드)

has_ic() (curses 모듈)

has_il() (curses 모듈)

has_ipv6 (socket 모듈)

has_key (2to3 fixer)

has_key() (curses 모듈)

has_location (importlib.machinery.ModuleSpec의 속성)

HAS_NEVER_CHECK_COMMON_NAME (ssl 모듈)

has_nonstandard_attr() (http.cookiejar.Cookie 메서드)

HAS_NPN (ssl 모듈)

has_option() (configparser.ConfigParser 메서드)

(optparse.OptionParser 메서드)

has_section() (configparser.ConfigParser 메서드)

HAS_SNI (ssl 모듈)

HAS_SSLv2 (ssl 모듈)

HAS_SSLv3 (ssl 모듈)

has_ticket (ssl.SSLSession의 속성)

HAS_TLSv1 (ssl 모듈)

HAS_TLSv1_1 (ssl 모듈)

HAS_TLSv1_2 (ssl 모듈)

HAS_TLSv1_3 (ssl 모듈)

hasattr() (내장 함수)

hasAttribute() (xml.dom.Element 메서드)

hasAttributeNS() (xml.dom.Element 메서드)

hasAttributes() (xml.dom.Node 메서드)

hasChildNodes() (xml.dom.Node 메서드)

hascompare (dis 모듈)

hasconst (dis 모듈)

hasFeature() (xml.dom.DOMImplementation 메서드)

hasfree (dis 모듈)

hash

내장 함수, [1], [2], [3]

hash character

hash() (내장 함수)

hash-based pyc (해시 기반 pyc)

hash.block_size (hashlib 모듈)

hash.digest_size (hashlib 모듈)

hash_info (sys 모듈)

hashable

Hashable (collections.abc 클래스)

(typing 클래스)

hashable (해시 가능)

hasHandlers() (logging.Logger 메서드)

hashlib (모듈)

hasjabs (dis 모듈)

hasjrel (dis 모듈)

haslocal (dis 모듈)

hasname (dis 모듈)

HAVE_ARGUMENT (opcode)

HAVE_CONTEXTVAR (decimal 모듈)

HAVE_DOCSTRINGS (test.support 모듈)

HAVE_THREADS (decimal 모듈)

HCI_DATA_DIR (socket 모듈)

HCI_FILTER (socket 모듈)

HCI_TIME_STAMP (socket 모듈)

head() (nntplib.NNTP 메서드)

Header (email.header 클래스)

header_encode() (email.charset.Charset 메서드)

header_encode_lines() (email.charset.Charset 메서드)

header_encoding (email.charset.Charset의 속성)

header_factory (email.policy.EmailPolicy의 속성)

header_fetch_parse() (email.policy.Compat32 메서드)

(email.policy.EmailPolicy 메서드)

(email.policy.Policy 메서드)

header_items() (urllib.request.Request 메서드)

header_max_count() (email.policy.EmailPolicy 메서드)

(email.policy.Policy 메서드)

header_offset (zipfile.ZipInfo의 속성)

header_source_parse() (email.policy.Compat32 메서드)

(email.policy.EmailPolicy 메서드)

(email.policy.Policy 메서드)

header_store_parse() (email.policy.Compat32 메서드)

(email.policy.EmailPolicy 메서드)

(email.policy.Policy 메서드)

HeaderError

HeaderParseError

HeaderParser (email.parser 클래스)

HeaderRegistry (email.headerregistry 클래스)

headers

MIME, [1]

headers (http.server.BaseHTTPRequestHandler의 속성)

(urllib.error.HTTPError의 속성)

Headers (wsgiref.headers 클래스)

headers (xmlrpc.client.ProtocolError의 속성)

heading() (tkinter.ttk.Treeview 메서드)

(turtle 모듈)

heapify() (heapq 모듈)

heapmin() (msvcrt 모듈)

heappop() (heapq 모듈)

heappush() (heapq 모듈)

heappushpop() (heapq 모듈)

heapq (모듈)

heapreplace() (heapq 모듈)

helo() (smtplib.SMTP 메서드)

help

online

내장 함수

help (optparse.Option의 속성)

(pdb command)

help() (nntplib.NNTP 메서드)

(내장 함수)

herror

hex (uuid.UUID의 속성)

hex() (bytearray 메서드)

(bytes 메서드)

(float 메서드)

(memoryview 메서드)

(내장 함수)

hexadecimal

literals

hexadecimal literal

hexbin() (binhex 모듈)

hexdigest() (hashlib.hash 메서드)

(hashlib.shake 메서드)

(hmac.HMAC 메서드)

hexdigits (string 모듈)

hexlify() (binascii 모듈)

hexversion (sys 모듈)

hidden() (curses.panel.Panel 메서드)

hide() (curses.panel.Panel 메서드)

(tkinter.ttk.Notebook 메서드)

hide_cookie2 (http.cookiejar.CookiePolicy의 속성)

hideturtle() (turtle 모듈)

hierarchy

type

HierarchyRequestErr

HIGH_PRIORITY_CLASS (subprocess 모듈)

HIGHEST_PROTOCOL (pickle 모듈)

HKEY_CLASSES_ROOT (winreg 모듈)

HKEY_CURRENT_CONFIG (winreg 모듈)

HKEY_CURRENT_USER (winreg 모듈)

HKEY_DYN_DATA (winreg 모듈)

HKEY_LOCAL_MACHINE (winreg 모듈)

HKEY_PERFORMANCE_DATA (winreg 모듈)

HKEY_USERS (winreg 모듈)

hline() (curses.window 메서드)

HList (tkinter.tix 클래스)

hls_to_rgb() (colorsys 모듈)

hmac (모듈)

HOME, [1], [2], [3], [4]

home() (pathlib.Path의 클래스 메서드)

(turtle 모듈)

HOMEDRIVE, [1]

HOMEPATH, [1]

hook_compressed() (fileinput 모듈)

hook_encoded() (fileinput 모듈)

hooks

import

meta

path

host (urllib.request.Request의 속성)

hostmask (ipaddress.IPv4Network의 속성)

(ipaddress.IPv6Network의 속성)

hostname_checks_common_name (ssl.SSLContext의 속성)

hosts (netrc.netrc의 속성)

hosts() (ipaddress.IPv4Network 메서드)

(ipaddress.IPv6Network 메서드)

hour (datetime.datetime의 속성)

(datetime.time의 속성)

HRESULT (ctypes 클래스)

hStdError (subprocess.STARTUPINFO의 속성)

hStdInput (subprocess.STARTUPINFO의 속성)

hStdOutput (subprocess.STARTUPINFO의 속성)

hsv_to_rgb() (colorsys 모듈)

ht() (turtle 모듈)

HTML, [1]

html (모듈)

html() (cgitb 모듈)

html.entities (모듈)

html.parser (모듈)

html5 (html.entities 모듈)

HTMLCalendar (calendar 클래스)

HtmlDiff (difflib 클래스)

HTMLParser (html.parser 클래스)

htonl() (socket 모듈)

htons() (socket 모듈)

HTTP

http (standard module)

http.client (standard module)

protocol, [1], [2], [3], [4], [5]

HTTP (email.policy 모듈)

http (모듈)

http.client (모듈)

http.cookiejar (모듈)

http.cookies (모듈)

http.server

security

http.server (모듈)

http_error_301() (urllib.request.HTTPRedirectHandler 메서드)

http_error_302() (urllib.request.HTTPRedirectHandler 메서드)

http_error_303() (urllib.request.HTTPRedirectHandler 메서드)

http_error_307() (urllib.request.HTTPRedirectHandler 메서드)

http_error_401() (urllib.request.HTTPBasicAuthHandler 메서드)

(urllib.request.HTTPDigestAuthHandler 메서드)

http_error_407() (urllib.request.ProxyBasicAuthHandler 메서드)

(urllib.request.ProxyDigestAuthHandler 메서드)

http_error_auth_reqed() (urllib.request.AbstractBasicAuthHandler 메서드)

(urllib.request.AbstractDigestAuthHandler 메서드)

http_error_default() (urllib.request.BaseHandler 메서드)

http_open() (urllib.request.HTTPHandler 메서드)

HTTP_PORT (http.client 모듈)

http_proxy, [1], [2]

http_response() (urllib.request.HTTPErrorProcessor 메서드)

http_version (wsgiref.handlers.BaseHandler의 속성)

HTTPBasicAuthHandler (urllib.request 클래스)

HTTPConnection (http.client 클래스)

HTTPCookieProcessor (urllib.request 클래스)

httpd

HTTPDefaultErrorHandler (urllib.request 클래스)

HTTPDigestAuthHandler (urllib.request 클래스)

HTTPError

HTTPErrorProcessor (urllib.request 클래스)

HTTPException

HTTPHandler (logging.handlers 클래스)

(urllib.request 클래스)

HTTPPasswordMgr (urllib.request 클래스)

HTTPPasswordMgrWithDefaultRealm (urllib.request 클래스)

HTTPPasswordMgrWithPriorAuth (urllib.request 클래스)

HTTPRedirectHandler (urllib.request 클래스)

HTTPResponse (http.client 클래스)

https_open() (urllib.request.HTTPSHandler 메서드)

HTTPS_PORT (http.client 모듈)

https_response() (urllib.request.HTTPErrorProcessor 메서드)

HTTPSConnection (http.client 클래스)

HTTPServer (http.server 클래스)

HTTPSHandler (urllib.request 클래스)

HTTPStatus (http 클래스)

hypot() (math 모듈)

탐색

색인

모듈 |

Python »

3.7.17 Documentation »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

Python »

3.7.17 Documentation »

|

Index – I

I (re 모듈)

I/O control

buffering, [1]

POSIX

tty

UNIX

iadd() (operator 모듈)

iand() (operator 모듈)

iconcat() (operator 모듈)

id

내장 함수

id (ssl.SSLSession의 속성)

id() (unittest.TestCase 메서드)

(내장 함수)

idcok() (curses.window 메서드)

ident (select.kevent의 속성)

(threading.Thread의 속성)

identchars (cmd.Cmd의 속성)

identifier, [1]

identify() (tkinter.ttk.Notebook 메서드)

(tkinter.ttk.Treeview 메서드)

(tkinter.ttk.Widget 메서드)

identify_column() (tkinter.ttk.Treeview 메서드)

identify_element() (tkinter.ttk.Treeview 메서드)

identify_region() (tkinter.ttk.Treeview 메서드)

identify_row() (tkinter.ttk.Treeview 메서드)

identity

test

identity of an object

idioms (2to3 fixer)

IDLE, [1]

IDLE_PRIORITY_CLASS (subprocess 모듈)

IDLESTARTUP, [1], [2]

idlok() (curses.window 메서드)

if

conditional expression

in comprehensions

글, [1]

if_indextoname() (socket 모듈)

if_nameindex() (socket 모듈)

if_nametoindex() (socket 모듈)

ifloordiv() (operator 모듈)

iglob() (glob 모듈)

ignorableWhitespace() (xml.sax.handler.ContentHandler 메서드)

ignore (pdb command)

ignore_errors() (codecs 모듈)

IGNORE_EXCEPTION_DETAIL (doctest 모듈)

ignore_patterns() (shutil 모듈)

IGNORECASE (re 모듈)

ihave() (nntplib.NNTP 메서드)

IISCGIHandler (wsgiref.handlers 클래스)

ilshift() (operator 모듈)

imag (numbers.Complex의 속성)

imaginary literal

imap() (multiprocessing.pool.Pool 메서드)

IMAP4

protocol

IMAP4 (imaplib 클래스)

IMAP4.abort

IMAP4.error

IMAP4.readonly

IMAP4_SSL

protocol

IMAP4_SSL (imaplib 클래스)

IMAP4_stream

protocol

IMAP4_stream (imaplib 클래스)

imap_unordered() (multiprocessing.pool.Pool 메서드)

imaplib (모듈)

imatmul() (operator 모듈)

imghdr (모듈)

immedok() (curses.window 메서드)

immutable

data type

object, [1]

sequence types

객체

immutable (불변)

immutable object

immutable sequence

객체

immutable types

subclassing

imod() (operator 모듈)

imp

모듈

imp (모듈)

ImpImporter (pkgutil 클래스)

impl_detail() (test.support 모듈)

implementation (sys 모듈)

ImpLoader (pkgutil 클래스)

import

hooks

글, [1], [2], [3], [4]

import (2to3 fixer)

import hooks

import machinery

import path (임포트 경로)

import__find__load__done (C 함수)

import__find__load__start (C 함수)

import_fresh_module() (test.support 모듈)

IMPORT_FROM (opcode)

import_module() (importlib 모듈)

(test.support 모듈)

IMPORT_NAME (opcode)

IMPORT_STAR (opcode)

importer (임포터)

ImportError

예외

importing (임포팅)

importlib (모듈)

importlib.abc (모듈)

importlib.machinery (모듈)

importlib.resources (모듈)

importlib.util (모듈)

imports (2to3 fixer)

imports2 (2to3 fixer)

ImportWarning

ImproperConnectionState

imul() (operator 모듈)

in

연산자, [1], [2]

키워드

in_dll() (ctypes._CData 메서드)

in_table_a1() (stringprep 모듈)

in_table_b1() (stringprep 모듈)

in_table_c11() (stringprep 모듈)

in_table_c11_c12() (stringprep 모듈)

in_table_c12() (stringprep 모듈)

in_table_c21() (stringprep 모듈)

in_table_c21_c22() (stringprep 모듈)

in_table_c22() (stringprep 모듈)

in_table_c3() (stringprep 모듈)

in_table_c4() (stringprep 모듈)

in_table_c5() (stringprep 모듈)

in_table_c6() (stringprep 모듈)

in_table_c7() (stringprep 모듈)

in_table_c8() (stringprep 모듈)

in_table_c9() (stringprep 모듈)

in_table_d1() (stringprep 모듈)

in_table_d2() (stringprep 모듈)

in_transaction (sqlite3.Connection의 속성)

inch() (curses.window 메서드)

inclusive

or

inclusive (tracemalloc.DomainFilter의 속성)

(tracemalloc.Filter의 속성)

Incomplete

IncompleteRead

IncompleteReadError

incr_item(), [1]

increment_lineno() (ast 모듈)

IncrementalDecoder (codecs 클래스)

incrementaldecoder (codecs.CodecInfo의 속성)

IncrementalEncoder (codecs 클래스)

incrementalencoder (codecs.CodecInfo의 속성)

IncrementalNewlineDecoder (io 클래스)

IncrementalParser (xml.sax.xmlreader 클래스)

indent (doctest.Example의 속성)

INDENT (token 모듈)

INDENT token

indent() (textwrap 모듈)

indentation

IndentationError

index operation

index() (array.array 메서드)

(bytearray 메서드)

(bytes 메서드)

(collections.deque 메서드)

(operator 모듈)

(sequence method)

(str 메서드)

(tkinter.ttk.Notebook 메서드)

(tkinter.ttk.Treeview 메서드)

IndexError

indexOf() (operator 모듈)

IndexSizeErr

indices() (slice 메서드)

inet_aton() (socket 모듈)

inet_ntoa() (socket 모듈)

inet_ntop() (socket 모듈)

inet_pton() (socket 모듈)

Inexact (decimal 클래스)

inf (cmath 모듈)

(math 모듈)

infile

json.tool command line option

infile (shlex.shlex의 속성)

Infinity

infj (cmath 모듈)

info() (dis.Bytecode 메서드)

(gettext.NullTranslations 메서드)

(logging 모듈)

(logging.Logger 메서드)

infolist() (zipfile.ZipFile 메서드)

inheritance

ini file

init() (mimetypes 모듈)

init_color() (curses 모듈)

init_database() (msilib 모듈)

init_pair() (curses 모듈)

inited (mimetypes 모듈)

initgroups() (os 모듈)

initial_indent (textwrap.TextWrapper의 속성)

initialize_options() (distutils.cmd.Command 메서드)

initscr() (curses 모듈)

inode() (os.DirEntry 메서드)

INPLACE_ADD (opcode)

INPLACE_AND (opcode)

INPLACE_FLOOR_DIVIDE (opcode)

INPLACE_LSHIFT (opcode)

INPLACE_MATRIX_MULTIPLY (opcode)

INPLACE_MODULO (opcode)

INPLACE_MULTIPLY (opcode)

INPLACE_OR (opcode)

INPLACE_POWER (opcode)

INPLACE_RSHIFT (opcode)

INPLACE_SUBTRACT (opcode)

INPLACE_TRUE_DIVIDE (opcode)

INPLACE_XOR (opcode)

input

(2to3 fixer)

input() (fileinput 모듈)

(내장 함수)

input_charset (email.charset.Charset의 속성)

input_codec (email.charset.Charset의 속성)

InputOnly (tkinter.tix 클래스)

InputSource (xml.sax.xmlreader 클래스)

inquiry (C 데이터 형식)

insch() (curses.window 메서드)

insdelln() (curses.window 메서드)

insert() (array.array 메서드)

(collections.deque 메서드)

(sequence method)

(tkinter.ttk.Notebook 메서드)

(tkinter.ttk.Treeview 메서드)

(xml.etree.ElementTree.Element 메서드)

insert_text() (readline 모듈)

insertBefore() (xml.dom.Node 메서드)

insertln() (curses.window 메서드)

insnstr() (curses.window 메서드)

insort() (bisect 모듈)

insort_left() (bisect 모듈)

insort_right() (bisect 모듈)

inspect (모듈)

inspect command line option

--details

InspectLoader (importlib.abc 클래스)

insstr() (curses.window 메서드)

install() (gettext 모듈)

(gettext.NullTranslations 메서드)

install_opener() (urllib.request 모듈)

install_scripts() (venv.EnvBuilder 메서드)

installHandler() (unittest 모듈)

instance

call, [1]

class

객체, [1], [2]

instancemethod

객체

instate() (tkinter.ttk.Widget 메서드)

instr() (curses.window 메서드)

instream (shlex.shlex의 속성)

Instruction (dis 클래스)

Instruction.arg (dis 모듈)

Instruction.argrepr (dis 모듈)

Instruction.argval (dis 모듈)

Instruction.is_jump_target (dis 모듈)

Instruction.offset (dis 모듈)

Instruction.opcode (dis 모듈)

Instruction.opname (dis 모듈)

Instruction.starts_line (dis 모듈)

int

내장 함수, [1], [2]

int (uuid.UUID의 속성)

(내장 클래스)

Int2AP() (imaplib 모듈)

int_info (sys 모듈)

integer

literals

representation

types, operations on

객체, [1], [2]

integer literal

Integral (numbers 클래스)

Integrated Development Environment

IntegrityError

Intel/DVI ADPCM

IntEnum (enum 클래스)

interact (pdb command)

interact() (code 모듈)

(code.InteractiveConsole 메서드)

(telnetlib.Telnet 메서드)

interactive (대화형)

interactive mode

InteractiveConsole (code 클래스)

InteractiveInterpreter (code 클래스)

intern (2to3 fixer)

intern() (sys 모듈)

internal type

internal_attr (zipfile.ZipInfo의 속성)

Internaldate2tuple() (imaplib 모듈)

internalSubset (xml.dom.DocumentType의 속성)

Internet

interpolated string literal

interpolation

bytearray (%)

bytes (%)

interpolation, string (%)

InterpolationDepthError

InterpolationError

InterpolationMissingOptionError

InterpolationSyntaxError

interpreted (인터프리티드)

interpreter

interpreter lock

interpreter prompts

interpreter shutdown (인터프리터 종료)

interpreter_requires_environment() (test.support.script_helper 모듈)

interrupt() (sqlite3.Connection 메서드)

interrupt_main() (_thread 모듈)

InterruptedError

intersection() (frozenset 메서드)

intersection_update() (frozenset 메서드)

IntFlag (enum 클래스)

intro (cmd.Cmd의 속성)

InuseAttributeErr

inv() (operator 모듈)

InvalidAccessErr

invalidate_caches() (importlib 모듈)

(importlib.abc.MetaPathFinder 메서드)

(importlib.abc.PathEntryFinder 메서드)

(importlib.machinery.FileFinder 메서드)

(importlib.machinery.PathFinder의 클래스 메서드)

InvalidCharacterErr

InvalidModificationErr

InvalidOperation (decimal 클래스)

InvalidStateErr

InvalidStateError

InvalidURL

inversion

invert() (operator 모듈)

invocation

io

모듈

IO (typing 클래스)

io (모듈)

io.StringIO

객체

IOBase (io 클래스)

ioctl() (fcntl 모듈)

(socket.socket 메서드)

IOCTL_VM_SOCKETS_GET_LOCAL_CID (socket 모듈)

IOError

ior() (operator 모듈)

ip (ipaddress.IPv4Interface의 속성)

(ipaddress.IPv6Interface의 속성)

ip_address() (ipaddress 모듈)

ip_interface() (ipaddress 모듈)

ip_network() (ipaddress 모듈)

ipaddress (모듈)

ipow() (operator 모듈)

ipv4_mapped (ipaddress.IPv6Address의 속성)

IPv4Address (ipaddress 클래스)

IPv4Interface (ipaddress 클래스)

IPv4Network (ipaddress 클래스)

IPV6_ENABLED (test.support 모듈)

IPv6Address (ipaddress 클래스)

IPv6Interface (ipaddress 클래스)

IPv6Network (ipaddress 클래스)

irshift() (operator 모듈)

is

연산자, [1]

is not

연산자, [1]

is_() (operator 모듈)

is_absolute() (pathlib.PurePath 메서드)

is_alive() (multiprocessing.Process 메서드)

(threading.Thread 메서드)

is_android (test.support 모듈)

is_assigned() (symtable.Symbol 메서드)

is_attachment() (email.message.EmailMessage 메서드)

is_authenticated() (urllib.request.HTTPPasswordMgrWithPriorAuth 메서드)

is_block_device() (pathlib.Path 메서드)

is_blocked() (http.cookiejar.DefaultCookiePolicy 메서드)

is_canonical() (decimal.Context 메서드)

(decimal.Decimal 메서드)

is_char_device() (pathlib.Path 메서드)

IS_CHARACTER_JUNK() (difflib 모듈)

is_check_supported() (lzma 모듈)

is_closed() (asyncio.loop 메서드)

is_closing() (asyncio.BaseTransport 메서드)

(asyncio.StreamWriter 메서드)

is_dataclass() (dataclasses 모듈)

is_declared_global() (symtable.Symbol 메서드)

is_dir() (os.DirEntry 메서드)

(pathlib.Path 메서드)

(zipfile.ZipInfo 메서드)

is_enabled() (faulthandler 모듈)

is_expired() (http.cookiejar.Cookie 메서드)

is_fifo() (pathlib.Path 메서드)

is_file() (os.DirEntry 메서드)

(pathlib.Path 메서드)

is_finalizing() (sys 모듈)

is_finite() (decimal.Context 메서드)

(decimal.Decimal 메서드)

is_free() (symtable.Symbol 메서드)

is_global (ipaddress.IPv4Address의 속성)

(ipaddress.IPv6Address의 속성)

is_global() (symtable.Symbol 메서드)

is_hop_by_hop() (wsgiref.util 모듈)

is_imported() (symtable.Symbol 메서드)

is_infinite() (decimal.Context 메서드)

(decimal.Decimal 메서드)

is_integer() (float 메서드)

is_jython (test.support 모듈)

IS_LINE_JUNK() (difflib 모듈)

is_linetouched() (curses.window 메서드)

is_link_local (ipaddress.IPv4Address의 속성)

(ipaddress.IPv4Network의 속성)

(ipaddress.IPv6Address의 속성)

(ipaddress.IPv6Network의 속성)

is_local() (symtable.Symbol 메서드)

is_loopback (ipaddress.IPv4Address의 속성)

(ipaddress.IPv4Network의 속성)

(ipaddress.IPv6Address의 속성)

(ipaddress.IPv6Network의 속성)

is_mount() (pathlib.Path 메서드)

is_multicast (ipaddress.IPv4Address의 속성)

(ipaddress.IPv4Network의 속성)

(ipaddress.IPv6Address의 속성)

(ipaddress.IPv6Network의 속성)

is_multipart() (email.message.EmailMessage 메서드)

(email.message.Message 메서드)

is_namespace() (symtable.Symbol 메서드)

is_nan() (decimal.Context 메서드)

(decimal.Decimal 메서드)

is_nested() (symtable.SymbolTable 메서드)

is_normal() (decimal.Context 메서드)

(decimal.Decimal 메서드)

is_not() (operator 모듈)

is_not_allowed() (http.cookiejar.DefaultCookiePolicy 메서드)

is_optimized() (symtable.SymbolTable 메서드)

is_package() (importlib.abc.InspectLoader 메서드)

(importlib.abc.SourceLoader 메서드)

(importlib.machinery.ExtensionFileLoader 메서드)

(importlib.machinery.SourceFileLoader 메서드)

(importlib.machinery.SourcelessFileLoader 메서드)

(zipimport.zipimporter 메서드)

is_parameter() (symtable.Symbol 메서드)

is_private (ipaddress.IPv4Address의 속성)

(ipaddress.IPv4Network의 속성)

(ipaddress.IPv6Address의 속성)

(ipaddress.IPv6Network의 속성)

is_python_build() (sysconfig 모듈)

is_qnan() (decimal.Context 메서드)

(decimal.Decimal 메서드)

is_reading() (asyncio.ReadTransport 메서드)

is_referenced() (symtable.Symbol 메서드)

is_reserved (ipaddress.IPv4Address의 속성)

(ipaddress.IPv4Network의 속성)

(ipaddress.IPv6Address의 속성)

(ipaddress.IPv6Network의 속성)

is_reserved() (pathlib.PurePath 메서드)

is_resource() (importlib.abc.ResourceReader의 메서드)

(importlib.resources 모듈)

is_resource_enabled() (test.support 모듈)

is_running() (asyncio.loop 메서드)

is_safe (uuid.UUID의 속성)

is_serving() (asyncio.Server 메서드)

is_set() (asyncio.Event 메서드)

(threading.Event 메서드)

is_signed() (decimal.Context 메서드)

(decimal.Decimal 메서드)

is_site_local (ipaddress.IPv6Address의 속성)

(ipaddress.IPv6Network의 속성)

is_snan() (decimal.Context 메서드)

(decimal.Decimal 메서드)

is_socket() (pathlib.Path 메서드)

is_subnormal() (decimal.Context 메서드)

(decimal.Decimal 메서드)

is_symlink() (os.DirEntry 메서드)

(pathlib.Path 메서드)

is_tarfile() (tarfile 모듈)

is_term_resized() (curses 모듈)

is_tracing() (tracemalloc 모듈)

is_tracked() (gc 모듈)

is_unspecified (ipaddress.IPv4Address의 속성)

(ipaddress.IPv4Network의 속성)

(ipaddress.IPv6Address의 속성)

(ipaddress.IPv6Network의 속성)

is_wintouched() (curses.window 메서드)

is_zero() (decimal.Context 메서드)

(decimal.Decimal 메서드)

is_zipfile() (zipfile 모듈)

isabs() (os.path 모듈)

isabstract() (inspect 모듈)

IsADirectoryError

isalnum() (bytearray 메서드)

(bytes 메서드)

(curses.ascii 모듈)

(str 메서드)

isalpha() (bytearray 메서드)

(bytes 메서드)

(curses.ascii 모듈)

(str 메서드)

isascii() (bytearray 메서드)

(bytes 메서드)

(curses.ascii 모듈)

(str 메서드)

isasyncgen() (inspect 모듈)

isasyncgenfunction() (inspect 모듈)

isatty() (chunk.Chunk 메서드)

(io.IOBase 메서드)

(os 모듈)

isawaitable() (inspect 모듈)

isblank() (curses.ascii 모듈)

isblk() (tarfile.TarInfo 메서드)

isbuiltin() (inspect 모듈)

ischr() (tarfile.TarInfo 메서드)

isclass() (inspect 모듈)

isclose() (cmath 모듈)

(math 모듈)

iscntrl() (curses.ascii 모듈)

iscode() (inspect 모듈)

iscoroutine() (asyncio 모듈)

(inspect 모듈)

iscoroutinefunction() (asyncio 모듈)

(inspect 모듈)

isctrl() (curses.ascii 모듈)

isDaemon() (threading.Thread 메서드)

isdatadescriptor() (inspect 모듈)

isdecimal() (str 메서드)

isdev() (tarfile.TarInfo 메서드)

isdigit() (bytearray 메서드)

(bytes 메서드)

(curses.ascii 모듈)

(str 메서드)

isdir() (os.path 모듈)

(tarfile.TarInfo 메서드)

isdisjoint() (frozenset 메서드)

isdown() (turtle 모듈)

iselement() (xml.etree.ElementTree 모듈)

isenabled() (gc 모듈)

isEnabledFor() (logging.Logger 메서드)

isendwin() (curses 모듈)

ISEOF() (token 모듈)

isexpr() (parser 모듈)

(parser.ST 메서드)

isfifo() (tarfile.TarInfo 메서드)

isfile() (os.path 모듈)

(tarfile.TarInfo 메서드)

isfinite() (cmath 모듈)

(math 모듈)

isfirstline() (fileinput 모듈)

isframe() (inspect 모듈)

isfunction() (inspect 모듈)

isfuture() (asyncio 모듈)

isgenerator() (inspect 모듈)

isgeneratorfunction() (inspect 모듈)

isgetsetdescriptor() (inspect 모듈)

isgraph() (curses.ascii 모듈)

isidentifier() (str 메서드)

isinf() (cmath 모듈)

(math 모듈)

isinstance (2to3 fixer)

isinstance() (내장 함수)

iskeyword() (keyword 모듈)

isleap() (calendar 모듈)

islice() (itertools 모듈)

islink() (os.path 모듈)

islnk() (tarfile.TarInfo 메서드)

islower() (bytearray 메서드)

(bytes 메서드)

(curses.ascii 모듈)

(str 메서드)

ismemberdescriptor() (inspect 모듈)

ismeta() (curses.ascii 모듈)

ismethod() (inspect 모듈)

ismethoddescriptor() (inspect 모듈)

ismodule() (inspect 모듈)

ismount() (os.path 모듈)

isnan() (cmath 모듈)

(math 모듈)

ISNONTERMINAL() (token 모듈)

isnumeric() (str 메서드)

isocalendar() (datetime.date 메서드)

(datetime.datetime 메서드)

isoformat() (datetime.date 메서드)

(datetime.datetime 메서드)

(datetime.time 메서드)

isolation_level (sqlite3.Connection의 속성)

isoweekday() (datetime.date 메서드)

(datetime.datetime 메서드)

isprint() (curses.ascii 모듈)

isprintable() (str 메서드)

ispunct() (curses.ascii 모듈)

isreadable() (pprint 모듈)

(pprint.PrettyPrinter 메서드)

isrecursive() (pprint 모듈)

(pprint.PrettyPrinter 메서드)

isreg() (tarfile.TarInfo 메서드)

isReservedKey() (http.cookies.Morsel 메서드)

isroutine() (inspect 모듈)

isSameNode() (xml.dom.Node 메서드)

isspace() (bytearray 메서드)

(bytes 메서드)

(curses.ascii 모듈)

(str 메서드)

isstdin() (fileinput 모듈)

issubclass() (내장 함수)

issubset() (frozenset 메서드)

issuite() (parser 모듈)

(parser.ST 메서드)

issuperset() (frozenset 메서드)

issym() (tarfile.TarInfo 메서드)

ISTERMINAL() (token 모듈)

istitle() (bytearray 메서드)

(bytes 메서드)

(str 메서드)

istraceback() (inspect 모듈)

isub() (operator 모듈)

isupper() (bytearray 메서드)

(bytes 메서드)

(curses.ascii 모듈)

(str 메서드)

isvisible() (turtle 모듈)

isxdigit() (curses.ascii 모듈)

item

sequence

string

item selection

item() (tkinter.ttk.Treeview 메서드)

(xml.dom.NamedNodeMap 메서드)

(xml.dom.NodeList 메서드)

itemgetter() (operator 모듈)

items() (configparser.ConfigParser 메서드)

(contextvars.Context 메서드)

(dict 메서드)

(email.message.EmailMessage 메서드)

(email.message.Message 메서드)

(mailbox.Mailbox 메서드)

(types.MappingProxyType 메서드)

(xml.etree.ElementTree.Element 메서드)

itemsize (array.array의 속성)

(memoryview의 속성)

ItemsView (collections.abc 클래스)

(typing 클래스)

iter() (xml.etree.ElementTree.Element 메서드)

(xml.etree.ElementTree.ElementTree 메서드)

(내장 함수)

iter_attachments() (email.message.EmailMessage 메서드)

iter_child_nodes() (ast 모듈)

iter_fields() (ast 모듈)

iter_importers() (pkgutil 모듈)

iter_modules() (pkgutil 모듈)

iter_parts() (email.message.EmailMessage 메서드)

iter_unpack() (struct 모듈)

(struct.Struct 메서드)

iterable

unpacking

Iterable (collections.abc 클래스)

(typing 클래스)

iterable (이터러블)

Iterator (collections.abc 클래스)

(typing 클래스)

iterator (이터레이터)

iterator protocol

iterdecode() (codecs 모듈)

iterdir() (pathlib.Path 메서드)

iterdump() (sqlite3.Connection 메서드)

iterencode() (codecs 모듈)

(json.JSONEncoder 메서드)

iterfind() (xml.etree.ElementTree.Element 메서드)

(xml.etree.ElementTree.ElementTree 메서드)

iteritems() (mailbox.Mailbox 메서드)

iterkeys() (mailbox.Mailbox 메서드)

itermonthdates() (calendar.Calendar 메서드)

itermonthdays() (calendar.Calendar 메서드)

itermonthdays2() (calendar.Calendar 메서드)

itermonthdays3() (calendar.Calendar 메서드)

itermonthdays4() (calendar.Calendar 메서드)

iterparse() (xml.etree.ElementTree 모듈)

itertext() (xml.etree.ElementTree.Element 메서드)

itertools (2to3 fixer)

(모듈)

itertools_imports (2to3 fixer)

itervalues() (mailbox.Mailbox 메서드)

iterweekdays() (calendar.Calendar 메서드)

ITIMER_PROF (signal 모듈)

ITIMER_REAL (signal 모듈)

ITIMER_VIRTUAL (signal 모듈)

ItimerError

itruediv() (operator 모듈)

ixor() (operator 모듈)

탐색

색인

모듈 |

Python »

3.7.17 Documentation »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

Python »

3.7.17 Documentation »

|

Index – J

j

in numeric literal

Jansen, Jack

Java

language

java_ver() (platform 모듈)

join() (asyncio.Queue의 메서드)

(bytearray 메서드)

(bytes 메서드)

(multiprocessing.JoinableQueue 메서드)

(multiprocessing.pool.Pool 메서드)

(multiprocessing.Process 메서드)

(os.path 모듈)

(queue.Queue 메서드)

(str 메서드)

(threading.Thread 메서드)

join_thread() (multiprocessing.Queue 메서드)

(test.support 모듈)

JoinableQueue (multiprocessing 클래스)

joinpath() (pathlib.PurePath 메서드)

js_output() (http.cookies.BaseCookie 메서드)

(http.cookies.Morsel 메서드)

json

모듈

json (모듈)

json.tool (모듈)

json.tool command line option

--help

--sort-keys

-h

infile

outfile

JSONDecodeError

JSONDecoder (json 클래스)

JSONEncoder (json 클래스)

jump (pdb command)

JUMP_ABSOLUTE (opcode)

JUMP_FORWARD (opcode)

JUMP_IF_FALSE_OR_POP (opcode)

JUMP_IF_TRUE_OR_POP (opcode)

탐색

색인

모듈 |

Python »

3.7.17 Documentation »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

Python »

3.7.17 Documentation »

|

Index – K

kbhit() (msvcrt 모듈)

KDEDIR

kevent() (select 모듈)

key

(http.cookies.Morsel의 속성)

key function (키 함수)

key/datum pair

KEY_ALL_ACCESS (winreg 모듈)

KEY_CREATE_LINK (winreg 모듈)

KEY_CREATE_SUB_KEY (winreg 모듈)

KEY_ENUMERATE_SUB_KEYS (winreg 모듈)

KEY_EXECUTE (winreg 모듈)

KEY_NOTIFY (winreg 모듈)

KEY_QUERY_VALUE (winreg 모듈)

KEY_READ (winreg 모듈)

KEY_SET_VALUE (winreg 모듈)

KEY_WOW64_32KEY (winreg 모듈)

KEY_WOW64_64KEY (winreg 모듈)

KEY_WRITE (winreg 모듈)

KeyboardInterrupt

(built-in exception), [1]

KeyError

keyname() (curses 모듈)

keypad() (curses.window 메서드)

keyrefs() (weakref.WeakKeyDictionary 메서드)

keys() (contextvars.Context 메서드)

(dict 메서드)

(email.message.EmailMessage 메서드)

(email.message.Message 메서드)

(mailbox.Mailbox 메서드)

(sqlite3.Row 메서드)

(types.MappingProxyType 메서드)

(xml.etree.ElementTree.Element 메서드)

KeysView (collections.abc 클래스)

(typing 클래스)

keyword

(모듈)

keyword argument (키워드 인자)

keywords (functools.partial의 속성)

kill() (asyncio.asyncio.subprocess.Process 메서드)

(asyncio.SubprocessTransport 메서드)

(multiprocessing.Process 메서드)

(os 모듈)

(subprocess.Popen 메서드)

kill_python() (test.support.script_helper 모듈)

killchar() (curses 모듈)

killpg() (os 모듈)

kind (inspect.Parameter의 속성)

knownfiles (mimetypes 모듈)

kqueue() (select 모듈)

KqueueSelector (selectors 클래스)

kwargs (inspect.BoundArguments의 속성)

kwlist (keyword 모듈)

탐색

색인

모듈 |

Python »

3.7.17 Documentation »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

Python »

3.7.17 Documentation »

|

Index – L

L (re 모듈)

LabelEntry (tkinter.tix 클래스)

LabelFrame (tkinter.tix 클래스)

lambda

expression, [1]

form

lambda (람다)

LambdaType (types 모듈)

LANG, [1], [2], [3], [4]

LANGUAGE, [1]

language

C, [1], [2], [3], [4], [5]

Java

large files

LARGEST (test.support 모듈)

LargeZipFile

last() (nntplib.NNTP 메서드)

last_accepted (multiprocessing.connection.Listener의 속성)

last_traceback (in module sys)

(sys 모듈)

last_type (sys 모듈)

last_value (sys 모듈)

lastChild (xml.dom.Node의 속성)

lastcmd (cmd.Cmd의 속성)

lastgroup (re.Match의 속성)

lastindex (re.Match의 속성)

lastResort (logging 모듈)

lastrowid (sqlite3.Cursor의 속성)

layout() (tkinter.ttk.Style 메서드)

lazycache() (linecache 모듈)

LazyLoader (importlib.util 클래스)

LBRACE (token 모듈)

LBYL

LC_ALL, [1]

(locale 모듈)

LC_COLLATE (locale 모듈)

LC_CTYPE (locale 모듈)

LC_MESSAGES, [1]

(locale 모듈)

LC_MONETARY (locale 모듈)

LC_NUMERIC (locale 모듈)

LC_TIME (locale 모듈)

lchflags() (os 모듈)

lchmod() (os 모듈)

(pathlib.Path 메서드)

lchown() (os 모듈)

LDCXXSHARED

ldexp() (math 모듈)

LDFLAGS

ldgettext() (gettext 모듈)

ldngettext() (gettext 모듈)

le() (operator 모듈)

leading whitespace

leapdays() (calendar 모듈)

leaveok() (curses.window 메서드)

left (filecmp.dircmp의 속성)

left() (turtle 모듈)

left_list (filecmp.dircmp의 속성)

left_only (filecmp.dircmp의 속성)

LEFTSHIFT (token 모듈)

LEFTSHIFTEQUAL (token 모듈)

len

내장 함수, [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11]

len() (내장 함수)

length (xml.dom.NamedNodeMap의 속성)

(xml.dom.NodeList의 속성)

length_hint() (operator 모듈)

LESS (token 모듈)

LESSEQUAL (token 모듈)

lexical analysis

lexical definitions

lexists() (os.path 모듈)

lgamma() (math 모듈)

lgettext() (gettext 모듈)

(gettext.GNUTranslations 메서드)

(gettext.NullTranslations 메서드)

lib2to3 (모듈)

libc_ver() (platform 모듈)

library (dbm.ndbm 모듈)

(ssl.SSLError의 속성)

library_dir_option() (distutils.ccompiler.CCompiler 메서드)

library_filename() (distutils.ccompiler.CCompiler 메서드)

library_option() (distutils.ccompiler.CCompiler 메서드)

LibraryLoader (ctypes 클래스)

license (내장 변수)

LifoQueue (asyncio 클래스)

(queue 클래스)

light-weight processes

limit_denominator() (fractions.Fraction 메서드)

LimitOverrunError

lin2adpcm() (audioop 모듈)

lin2alaw() (audioop 모듈)

lin2lin() (audioop 모듈)

lin2ulaw() (audioop 모듈)

line (C 함수)

line continuation

line joining, [1]

line structure

line() (msilib.Dialog 메서드)

line-buffered I/O

line_buffering (io.TextIOWrapper의 속성)

line_num (csv.csvreader의 속성)

linecache (모듈)

lineno (ast.AST의 속성)

(doctest.DocTest의 속성)

(doctest.Example의 속성)

(json.JSONDecodeError의 속성)

(pyclbr.Class의 속성)

(pyclbr.Function의 속성)

(re.error의 속성)

(shlex.shlex의 속성)

(traceback.TracebackException의 속성)

(tracemalloc.Filter의 속성)

(tracemalloc.Frame의 속성)

(xml.parsers.expat.ExpatError의 속성)

lineno() (fileinput 모듈)

LINES, [1], [2], [3], [4]

lines (os.terminal_size의 속성)

linesep (email.policy.Policy의 속성)

(os 모듈)

lineterminator (csv.Dialect의 속성)

LineTooLong

link() (distutils.ccompiler.CCompiler 메서드)

(os 모듈)

link_executable() (distutils.ccompiler.CCompiler 메서드)

link_shared_lib() (distutils.ccompiler.CCompiler 메서드)

link_shared_object() (distutils.ccompiler.CCompiler 메서드)

linkname (tarfile.TarInfo의 속성)

linux_distribution() (platform 모듈)

list

assignment, target

comprehensions

deletion target

display

empty

expression, [1], [2]

target, [1]

type, operations on

객체, [1], [2], [3], [4], [5], [6], [7], [8]

list (pdb command)

List (typing 클래스)

list (내장 클래스)

(리스트)

list comprehension (리스트 컴프리헨션)

list() (imaplib.IMAP4 메서드)

(multiprocessing.managers.SyncManager 메서드)

(nntplib.NNTP 메서드)

(poplib.POP3 메서드)

(tarfile.TarFile 메서드)

LIST_APPEND (opcode)

list_dialects() (csv 모듈)

list_folders() (mailbox.Maildir 메서드)

(mailbox.MH 메서드)

listdir() (os 모듈)

listen() (asyncore.dispatcher 메서드)

(logging.config 모듈)

(socket.socket 메서드)

(turtle 모듈)

Listener (multiprocessing.connection 클래스)

listMethods() (xmlrpc.client.ServerProxy.system 메서드)

ListNoteBook (tkinter.tix 클래스)

listxattr() (os 모듈)

literal, [1]

literal_eval() (ast 모듈)

literals

binary

complex number

floating point

hexadecimal

integer

numeric

octal

LittleEndianStructure (ctypes 클래스)

ljust() (bytearray 메서드)

(bytes 메서드)

(str 메서드)

LK_LOCK (msvcrt 모듈)

LK_NBLCK (msvcrt 모듈)

LK_NBRLCK (msvcrt 모듈)

LK_RLCK (msvcrt 모듈)

LK_UNLCK (msvcrt 모듈)

ll (pdb command)

LMTP (smtplib 클래스)

ln() (decimal.Context 메서드)

(decimal.Decimal 메서드)

LNAME

lngettext() (gettext 모듈)

(gettext.GNUTranslations 메서드)

(gettext.NullTranslations 메서드)

load() (http.cookiejar.FileCookieJar 메서드)

(http.cookies.BaseCookie 메서드)

(json 모듈)

(marshal 모듈)

(pickle 모듈)

(pickle.Unpickler 메서드)

(plistlib 모듈)

(tracemalloc.Snapshot의 클래스 메서드)

LOAD_ATTR (opcode)

LOAD_BUILD_CLASS (opcode)

load_cert_chain() (ssl.SSLContext 메서드)

LOAD_CLASSDEREF (opcode)

LOAD_CLOSURE (opcode)

LOAD_CONST (opcode)

load_default_certs() (ssl.SSLContext 메서드)

LOAD_DEREF (opcode)

load_dh_params() (ssl.SSLContext 메서드)

load_extension() (sqlite3.Connection 메서드)

LOAD_FAST (opcode)

LOAD_GLOBAL (opcode)

LOAD_METHOD (opcode)

load_module() (imp 모듈)

(importlib.abc.FileLoader 메서드)

(importlib.abc.InspectLoader 메서드)

(importlib.abc.Loader 메서드)

(importlib.abc.SourceLoader 메서드)

(importlib.machinery.SourceFileLoader 메서드)

(importlib.machinery.SourcelessFileLoader 메서드)

(zipimport.zipimporter 메서드)

LOAD_NAME (opcode)

load_package_tests() (test.support 모듈)

load_verify_locations() (ssl.SSLContext 메서드)

loader

Loader (importlib.abc 클래스)

loader (importlib.machinery.ModuleSpec의 속성)

(로더)

loader_state (importlib.machinery.ModuleSpec의 속성)

LoadError

LoadKey() (winreg 모듈)

LoadLibrary() (ctypes.LibraryLoader 메서드)

loads() (json 모듈)

(marshal 모듈)

(pickle 모듈)

(plistlib 모듈)

(xmlrpc.client 모듈)

loadTestsFromModule() (unittest.TestLoader 메서드)

loadTestsFromName() (unittest.TestLoader 메서드)

loadTestsFromNames() (unittest.TestLoader 메서드)

loadTestsFromTestCase() (unittest.TestLoader 메서드)

local (threading 클래스)

localcontext() (decimal 모듈)

LOCALE (re 모듈)

locale (모듈)

localeconv() (locale 모듈)

LocaleHTMLCalendar (calendar 클래스)

LocaleTextCalendar (calendar 클래스)

localName (xml.dom.Attr의 속성)

(xml.dom.Node의 속성)

locals() (내장 함수)

localtime() (email.utils 모듈)

(time 모듈)

Locator (xml.sax.xmlreader 클래스)

Lock (asyncio 클래스)

(multiprocessing 클래스)

(threading 클래스)

lock() (mailbox.Babyl 메서드)

(mailbox.Mailbox 메서드)

(mailbox.Maildir 메서드)

(mailbox.mbox 메서드)

(mailbox.MH 메서드)

(mailbox.MMDF 메서드)

Lock() (multiprocessing.managers.SyncManager 메서드)

lock, interpreter

lock_held() (imp 모듈)

locked() (_thread.lock 메서드)

(asyncio.Condition 메서드)

(asyncio.Lock 메서드)

(asyncio.Semaphore 메서드)

(threading.Lock 메서드)

lockf() (fcntl 모듈)

(os 모듈)

locking() (msvcrt 모듈)

LockType (_thread 모듈)

log() (cmath 모듈)

(logging 모듈)

(logging.Logger 메서드)

(math 모듈)

log10() (cmath 모듈)

(decimal.Context 메서드)

(decimal.Decimal 메서드)

(math 모듈)

log1p() (math 모듈)

log2() (math 모듈)

log_date_time_string() (http.server.BaseHTTPRequestHandler 메서드)

log_error() (http.server.BaseHTTPRequestHandler 메서드)

log_exception() (wsgiref.handlers.BaseHandler 메서드)

log_message() (http.server.BaseHTTPRequestHandler 메서드)

log_request() (http.server.BaseHTTPRequestHandler 메서드)

log_to_stderr() (multiprocessing 모듈)

logb() (decimal.Context 메서드)

(decimal.Decimal 메서드)

Logger (logging 클래스)

LoggerAdapter (logging 클래스)

logging

Errors

logging (모듈)

logging.config (모듈)

logging.handlers (모듈)

logical line

logical_and() (decimal.Context 메서드)

(decimal.Decimal 메서드)

logical_invert() (decimal.Context 메서드)

(decimal.Decimal 메서드)

logical_or() (decimal.Context 메서드)

(decimal.Decimal 메서드)

logical_xor() (decimal.Context 메서드)

(decimal.Decimal 메서드)

login() (ftplib.FTP 메서드)

(imaplib.IMAP4 메서드)

(nntplib.NNTP 메서드)

(smtplib.SMTP 메서드)

login_cram_md5() (imaplib.IMAP4 메서드)

LOGNAME, [1]

lognormvariate() (random 모듈)

logout() (imaplib.IMAP4 메서드)

LogRecord (logging 클래스)

long (2to3 fixer)

long integer

객체

LONG_MAX

longMessage (unittest.TestCase의 속성)

longname() (curses 모듈)

lookup() (codecs 모듈)

(symtable.SymbolTable 메서드)

(tkinter.ttk.Style 메서드)

(unicodedata 모듈)

lookup_error() (codecs 모듈)

LookupError

loop

over mutable sequence

statement, [1], [2], [3]

loop control

target

loop() (asyncore 모듈)

lower() (bytearray 메서드)

(bytes 메서드)

(str 메서드)

LPAR (token 모듈)

lpAttributeList (subprocess.STARTUPINFO의 속성)

lru_cache() (functools 모듈)

lseek() (os 모듈)

lshift() (operator 모듈)

LSQB (token 모듈)

lstat() (os 모듈)

(pathlib.Path 메서드)

lstrip() (bytearray 메서드)

(bytes 메서드)

(str 메서드)

lsub() (imaplib.IMAP4 메서드)

lt() (operator 모듈)

(turtle 모듈)

LWPCookieJar (http.cookiejar 클래스)

lzma (모듈)

LZMACompressor (lzma 클래스)

LZMADecompressor (lzma 클래스)

LZMAError

LZMAFile (lzma 클래스)

탐색

색인

모듈 |

Python »

3.7.17 Documentation »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

Python »

3.7.17 Documentation »

|

Index – M

M (re 모듈)

mac_ver() (platform 모듈)

machine() (platform 모듈)

macpath (모듈)

macros (netrc.netrc의 속성)

magic

method

magic method (매직 메서드)

MAGIC_NUMBER (importlib.util 모듈)

MagicMock (unittest.mock 클래스)

Mailbox (mailbox 클래스)

mailbox (모듈)

mailcap (모듈)

Maildir (mailbox 클래스)

MaildirMessage (mailbox 클래스)

mailfrom (smtpd.SMTPChannel의 속성)

MailmanProxy (smtpd 클래스)

main(), [1], [2]

(py_compile 모듈)

(site 모듈)

(unittest 모듈)

main_thread() (threading 모듈)

mainloop() (turtle 모듈)

maintype (email.headerregistry.ContentTypeHeader의 속성)

major (email.headerregistry.MIMEVersionHeader의 속성)

major() (os 모듈)

make_alternative() (email.message.EmailMessage 메서드)

make_archive() (distutils.archive_util 모듈)

(shutil 모듈)

make_bad_fd() (test.support 모듈)

make_cookies() (http.cookiejar.CookieJar 메서드)

make_dataclass() (dataclasses 모듈)

make_file() (difflib.HtmlDiff 메서드)

MAKE_FUNCTION (opcode)

make_header() (email.header 모듈)

make_legacy_pyc() (test.support 모듈)

make_mixed() (email.message.EmailMessage 메서드)

make_msgid() (email.utils 모듈)

make_parser() (xml.sax 모듈)

make_pkg() (test.support.script_helper 모듈)

make_related() (email.message.EmailMessage 메서드)

make_script() (test.support.script_helper 모듈)

make_server() (wsgiref.simple_server 모듈)

make_table() (difflib.HtmlDiff 메서드)

make_tarball() (distutils.archive_util 모듈)

make_zip_pkg() (test.support.script_helper 모듈)

make_zip_script() (test.support.script_helper 모듈)

make_zipfile() (distutils.archive_util 모듈)

makedev() (os 모듈)

makedirs() (os 모듈)

makeelement() (xml.etree.ElementTree.Element 메서드)

makefile() (socket method)

(socket.socket 메서드)

makeLogRecord() (logging 모듈)

makePickle() (logging.handlers.SocketHandler 메서드)

makeRecord() (logging.Logger 메서드)

makeSocket() (logging.handlers.DatagramHandler 메서드)

(logging.handlers.SocketHandler 메서드)

maketrans() (bytearray의 정적 메서드)

(bytes의 정적 메서드)

(str의 정적 메서드)

malloc()

mangle_from_ (email.policy.Compat32의 속성)

(email.policy.Policy의 속성)

mangling

name, [1]

map (2to3 fixer)

map() (concurrent.futures.Executor 메서드)

(multiprocessing.pool.Pool 메서드)

(tkinter.ttk.Style 메서드)

(내장 함수)

MAP_ADD (opcode)

map_async() (multiprocessing.pool.Pool 메서드)

map_table_b2() (stringprep 모듈)

map_table_b3() (stringprep 모듈)

map_to_type() (email.headerregistry.HeaderRegistry 메서드)

mapLogRecord() (logging.handlers.HTTPHandler 메서드)

mapping

types, operations on

객체, [1], [2], [3], [4], [5]

Mapping (collections.abc 클래스)

(typing 클래스)

mapping (매핑)

mapping() (msilib.Control 메서드)

MappingProxyType (types 클래스)

MappingView (collections.abc 클래스)

(typing 클래스)

mapPriority() (logging.handlers.SysLogHandler 메서드)

maps (collections.ChainMap의 속성)

maps() (nis 모듈)

marshal (모듈)

marshalling

objects

masking

operations

Match (typing 클래스)

match() (nis 모듈)

(pathlib.PurePath 메서드)

(re 모듈)

(re.Pattern 메서드)

match_hostname() (ssl 모듈)

match_test() (test.support 모듈)

match_value() (test.support.Matcher 메서드)

Matcher (test.support 클래스)

matches() (test.support.Matcher 메서드)

math

모듈, [1]

math (모듈)

matmul() (operator 모듈)

matrix multiplication

max

내장 함수

max (datetime.datetime의 속성)

(datetime.date의 속성)

(datetime.timedelta의 속성)

(datetime.time의 속성)

max() (audioop 모듈)

(decimal.Context 메서드)

(decimal.Decimal 메서드)

(내장 함수)

max_count (email.headerregistry.BaseHeader의 속성)

MAX_EMAX (decimal 모듈)

MAX_INTERPOLATION_DEPTH (configparser 모듈)

max_line_length (email.policy.Policy의 속성)

max_lines (textwrap.TextWrapper의 속성)

max_mag() (decimal.Context 메서드)

(decimal.Decimal 메서드)

max_memuse (test.support 모듈)

MAX_PREC (decimal 모듈)

max_prefixlen (ipaddress.IPv4Address의 속성)

(ipaddress.IPv4Network의 속성)

(ipaddress.IPv6Address의 속성)

(ipaddress.IPv6Network의 속성)

MAX_Py_ssize_t (test.support 모듈)

maxarray (reprlib.Repr의 속성)

maxdeque (reprlib.Repr의 속성)

maxdict (reprlib.Repr의 속성)

maxDiff (unittest.TestCase의 속성)

maxfrozenset (reprlib.Repr의 속성)

MAXIMUM_SUPPORTED (ssl.TLSVersion의 속성)

maximum_version (ssl.SSLContext의 속성)

maxlen (collections.deque의 속성)

maxlevel (reprlib.Repr의 속성)

maxlist (reprlib.Repr의 속성)

maxlong (reprlib.Repr의 속성)

maxother (reprlib.Repr의 속성)

maxpp() (audioop 모듈)

maxset (reprlib.Repr의 속성)

maxsize (asyncio.Queue의 속성)

(sys 모듈)

maxstring (reprlib.Repr의 속성)

maxtuple (reprlib.Repr의 속성)

maxunicode (sys 모듈)

MAXYEAR (datetime 모듈)

MB_ICONASTERISK (winsound 모듈)

MB_ICONEXCLAMATION (winsound 모듈)

MB_ICONHAND (winsound 모듈)

MB_ICONQUESTION (winsound 모듈)

MB_OK (winsound 모듈)

mbox (mailbox 클래스)

mboxMessage (mailbox 클래스)

mean() (statistics 모듈)

median() (statistics 모듈)

median_grouped() (statistics 모듈)

median_high() (statistics 모듈)

median_low() (statistics 모듈)

MemberDescriptorType (types 모듈)

membership

test

memmove() (ctypes 모듈)

MemoryBIO (ssl 클래스)

MemoryError

MemoryHandler (logging.handlers 클래스)

memoryview

객체, [1]

memoryview (내장 클래스)

memset() (ctypes 모듈)

merge() (heapq 모듈)

Message (email.message 클래스)

(mailbox 클래스)

message digest, MD5

message_factory (email.policy.Policy의 속성)

message_from_binary_file() (email 모듈)

message_from_bytes() (email 모듈)

message_from_file() (email 모듈)

message_from_string() (email 모듈)

MessageBeep() (winsound 모듈)

MessageClass (http.server.BaseHTTPRequestHandler의 속성)

MessageError

MessageParseError

messages (xml.parsers.expat.errors 모듈)

meta

hooks

meta hooks

meta path finder (메타 경로 파인더)

meta() (curses 모듈)

meta_path (sys 모듈)

metaclass

(2to3 fixer)

(메타 클래스)

metaclass hint

MetaPathFinder (importlib.abc 클래스)

metavar (optparse.Option의 속성)

MetavarTypeHelpFormatter (argparse 클래스)

Meter (tkinter.tix 클래스)

METH_CLASS (내장 변수)

METH_COEXIST (내장 변수)

METH_FASTCALL (내장 변수)

METH_NOARGS (내장 변수)

METH_O (내장 변수)

METH_STATIC (내장 변수)

METH_VARARGS (내장 변수)

method

built-in

call

magic

special

user-defined

객체, [1], [2], [3], [4], [5]

method (urllib.request.Request의 속성)

(메서드)

method resolution order (메서드 결정 순서)

METHOD_BLOWFISH (crypt 모듈)

method_calls (unittest.mock.Mock의 속성)

METHOD_CRYPT (crypt 모듈)

METHOD_MD5 (crypt 모듈)

METHOD_SHA256 (crypt 모듈)

METHOD_SHA512 (crypt 모듈)

methodattrs (2to3 fixer)

methodcaller() (operator 모듈)

MethodDescriptorType (types 모듈)

methodHelp() (xmlrpc.client.ServerProxy.system 메서드)

methods

bytearray

bytes

string

methods (crypt 모듈)

(pyclbr.Class의 속성)

methodSignature() (xmlrpc.client.ServerProxy.system 메서드)

MethodType (in module types), [1]

(types 모듈)

MethodWrapperType (types 모듈)

MH (mailbox 클래스)

MHMessage (mailbox 클래스)

microsecond (datetime.datetime의 속성)

(datetime.time의 속성)

MIME

base64 encoding

content type

headers, [1]

quoted-printable encoding

MIMEApplication (email.mime.application 클래스)

MIMEAudio (email.mime.audio 클래스)

MIMEBase (email.mime.base 클래스)

MIMEImage (email.mime.image 클래스)

MIMEMessage (email.mime.message 클래스)

MIMEMultipart (email.mime.multipart 클래스)

MIMENonMultipart (email.mime.nonmultipart 클래스)

MIMEPart (email.message 클래스)

MIMEText (email.mime.text 클래스)

MimeTypes (mimetypes 클래스)

mimetypes (모듈)

MIMEVersionHeader (email.headerregistry 클래스)

min

내장 함수

min (datetime.datetime의 속성)

(datetime.date의 속성)

(datetime.timedelta의 속성)

(datetime.time의 속성)

min() (decimal.Context 메서드)

(decimal.Decimal 메서드)

(내장 함수)

MIN_EMIN (decimal 모듈)

MIN_ETINY (decimal 모듈)

min_mag() (decimal.Context 메서드)

(decimal.Decimal 메서드)

MINEQUAL (token 모듈)

MINIMUM_SUPPORTED (ssl.TLSVersion의 속성)

minimum_version (ssl.SSLContext의 속성)

minmax() (audioop 모듈)

minor (email.headerregistry.MIMEVersionHeader의 속성)

minor() (os 모듈)

minus

MINUS (token 모듈)

minus() (decimal.Context 메서드)

minute (datetime.datetime의 속성)

(datetime.time의 속성)

MINYEAR (datetime 모듈)

mirrored() (unicodedata 모듈)

misc_header (cmd.Cmd의 속성)

MISSING (contextvars.contextvars.Token.Token의 속성)

MISSING_C_DOCSTRINGS (test.support 모듈)

missing_compiler_executable() (test.support 모듈)

MissingSectionHeaderError

MIXERDEV

mkd() (ftplib.FTP 메서드)

mkdir() (os 모듈)

(pathlib.Path 메서드)

mkdtemp() (tempfile 모듈)

mkfifo() (os 모듈)

mknod() (os 모듈)

mkpath() (distutils.ccompiler.CCompiler 메서드)

(distutils.dir_util 모듈)

mksalt() (crypt 모듈)

mkstemp() (tempfile 모듈)

mktemp() (tempfile 모듈)

mktime() (time 모듈)

mktime_tz() (email.utils 모듈)

mlsd() (ftplib.FTP 메서드)

mmap (mmap 클래스)

(모듈)

MMDF (mailbox 클래스)

MMDFMessage (mailbox 클래스)

Mock (unittest.mock 클래스)

mock_add_spec() (unittest.mock.Mock 메서드)

mock_calls (unittest.mock.Mock의 속성)

mock_open() (unittest.mock 모듈)

mod() (operator 모듈)

mode (io.FileIO의 속성)

(ossaudiodev.oss_audio_device의 속성)

(tarfile.TarInfo의 속성)

mode() (statistics 모듈)

(turtle 모듈)

modes

file

modf() (math 모듈)

modified() (urllib.robotparser.RobotFileParser 메서드)

Modify() (msilib.View 메서드)

modify() (select.devpoll 메서드)

(select.epoll 메서드)

(select.poll 메서드)

(selectors.BaseSelector 메서드)

module

extension

importing

namespace

search path, [1], [2], [3], [4], [5], [6], [7]

객체, [1], [2]

module (pyclbr.Class의 속성)

(pyclbr.Function의 속성)

(모듈)

module spec

(모듈 스펙)

module_for_loader() (importlib.util 모듈)

module_from_spec() (importlib.util 모듈)

module_repr() (importlib.abc.Loader 메서드)

ModuleFinder (modulefinder 클래스)

modulefinder (모듈)

ModuleInfo (pkgutil 클래스)

ModuleNotFoundError

modules (in module sys), [1]

(modulefinder.ModuleFinder의 속성)

(sys 모듈)

modules_cleanup() (test.support 모듈)

modules_setup() (test.support 모듈)

ModuleSpec (importlib.machinery 클래스)

ModuleType (in module types)

(types 클래스)

modulo

monotonic() (time 모듈)

monotonic_ns() (time 모듈)

month (datetime.datetime의 속성)

(datetime.date의 속성)

month() (calendar 모듈)

month_abbr (calendar 모듈)

month_name (calendar 모듈)

monthcalendar() (calendar 모듈)

monthdatescalendar() (calendar.Calendar 메서드)

monthdays2calendar() (calendar.Calendar 메서드)

monthdayscalendar() (calendar.Calendar 메서드)

monthrange() (calendar 모듈)

Morsel (http.cookies 클래스)

most_common() (collections.Counter 메서드)

mouseinterval() (curses 모듈)

mousemask() (curses 모듈)

move() (curses.panel.Panel 메서드)

(curses.window 메서드)

(mmap.mmap 메서드)

(shutil 모듈)

(tkinter.ttk.Treeview 메서드)

move_file() (distutils.ccompiler.CCompiler 메서드)

(distutils.file_util 모듈)

move_to_end() (collections.OrderedDict 메서드)

MozillaCookieJar (http.cookiejar 클래스)

MRO

mro() (class 메서드)

msg (http.client.HTTPResponse의 속성)

(json.JSONDecodeError의 속성)

(re.error의 속성)

(traceback.TracebackException의 속성)

msg() (telnetlib.Telnet 메서드)

msi

msilib (모듈)

msvcrt (모듈)

mt_interact() (telnetlib.Telnet 메서드)

mtime (gzip.GzipFile의 속성)

(tarfile.TarInfo의 속성)

mtime() (urllib.robotparser.RobotFileParser 메서드)

mul() (audioop 모듈)

(operator 모듈)

MultiCall (xmlrpc.client 클래스)

MULTILINE (re 모듈)

MultipartConversionError

multiplication

multiply() (decimal.Context 메서드)

multiprocessing (모듈)

multiprocessing.connection (모듈)

multiprocessing.dummy (모듈)

multiprocessing.Manager() (multiprocessing.sharedctypes 모듈)

multiprocessing.managers (모듈)

multiprocessing.pool (모듈)

multiprocessing.sharedctypes (모듈)

mutable

sequence types

객체, [1], [2]

mutable (가변)

mutable object

mutable sequence

loop over

객체

MutableMapping (collections.abc 클래스)

(typing 클래스)

MutableSequence (collections.abc 클래스)

(typing 클래스)

MutableSet (collections.abc 클래스)

(typing 클래스)

mvderwin() (curses.window 메서드)

mvwin() (curses.window 메서드)

myrights() (imaplib.IMAP4 메서드)

탐색

색인

모듈 |

Python »

3.7.17 Documentation »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

Python »

3.7.17 Documentation »

|

Index – N

N_TOKENS (token 모듈)

n_waiting (threading.Barrier의 속성)

name, [1], [2]

binding, [1], [2], [3], [4], [5], [6]

binding, global

class

function, [1]

mangling, [1]

rebinding

unbinding

name (codecs.CodecInfo의 속성)

(contextvars.ContextVar의 속성)

(doctest.DocTest의 속성)

(email.headerregistry.BaseHeader의 속성)

(hashlib.hash의 속성)

(hmac.HMAC의 속성)

(http.cookiejar.Cookie의 속성)

(importlib.abc.FileLoader의 속성)

(importlib.machinery.ExtensionFileLoader의 속성)

(importlib.machinery.ModuleSpec의 속성)

(importlib.machinery.SourceFileLoader의 속성)

(importlib.machinery.SourcelessFileLoader의 속성)

(inspect.Parameter의 속성)

(io.FileIO의 속성)

(multiprocessing.Process의 속성)

(os 모듈)

(os.DirEntry의 속성)

(ossaudiodev.oss_audio_device의 속성)

(pyclbr.Class의 속성)

(pyclbr.Function의 속성)

(tarfile.TarInfo의 속성)

(threading.Thread의 속성)

NAME (token 모듈)

name (xml.dom.Attr의 속성)

(xml.dom.DocumentType의 속성)

name() (unicodedata 모듈)

name2codepoint (html.entities 모듈)

named tuple (네임드 튜플)

NamedTemporaryFile() (tempfile 모듈)

NamedTuple (typing 클래스)

namedtuple() (collections 모듈)

NameError

예외

NameError (built-in exception)

namelist() (zipfile.ZipFile 메서드)

nameprep() (encodings.idna 모듈)

namer (logging.handlers.BaseRotatingHandler의 속성)

namereplace_errors() (codecs 모듈)

names

private

namespace

global

module

package

Namespace (argparse 클래스)

(multiprocessing.managers 클래스)

namespace (이름 공간)

namespace package (이름 공간 패키지)

namespace() (imaplib.IMAP4 메서드)

Namespace() (multiprocessing.managers.SyncManager 메서드)

NAMESPACE_DNS (uuid 모듈)

NAMESPACE_OID (uuid 모듈)

NAMESPACE_URL (uuid 모듈)

NAMESPACE_X500 (uuid 모듈)

NamespaceErr

namespaceURI (xml.dom.Node의 속성)

NaN

nan (cmath 모듈)

(math 모듈)

nanj (cmath 모듈)

NannyNag

napms() (curses 모듈)

nargs (optparse.Option의 속성)

nbytes (memoryview의 속성)

ndiff() (difflib 모듈)

ndim (memoryview의 속성)

ne (2to3 fixer)

ne() (operator 모듈)

needs_input (bz2.BZ2Decompressor의 속성)

(lzma.LZMADecompressor의 속성)

neg() (operator 모듈)

negation

nested scope (중첩된 스코프)

netmask (ipaddress.IPv4Network의 속성)

(ipaddress.IPv6Network의 속성)

NetmaskValueError

netrc (netrc 클래스)

(모듈)

NetrcParseError

netscape (http.cookiejar.CookiePolicy의 속성)

network (ipaddress.IPv4Interface의 속성)

(ipaddress.IPv6Interface의 속성)

Network News Transfer Protocol

network_address (ipaddress.IPv4Network의 속성)

(ipaddress.IPv6Network의 속성)

new() (hashlib 모듈)

(hmac 모듈)

new-style class (뉴스타일 클래스)

new_alignment() (formatter.writer 메서드)

new_child() (collections.ChainMap 메서드)

new_class() (types 모듈)

new_compiler() (distutils.ccompiler 모듈)

new_event_loop() (asyncio 모듈)

(asyncio.AbstractEventLoopPolicy 메서드)

new_font() (formatter.writer 메서드)

new_margin() (formatter.writer 메서드)

new_module() (imp 모듈)

new_panel() (curses.panel 모듈)

new_spacing() (formatter.writer 메서드)

new_styles() (formatter.writer 메서드)

newer() (distutils.dep_util 모듈)

newer_group() (distutils.dep_util 모듈)

newer_pairwise() (distutils.dep_util 모듈)

newgroups() (nntplib.NNTP 메서드)

NEWLINE (token 모듈)

NEWLINE token, [1]

newlines (io.TextIOBase의 속성)

newnews() (nntplib.NNTP 메서드)

newpad() (curses 모듈)

NewType() (typing 모듈)

newwin() (curses 모듈)

next (2to3 fixer)

(pdb command)

next() (nntplib.NNTP 메서드)

(tarfile.TarFile 메서드)

(tkinter.ttk.Treeview 메서드)

(내장 함수)

next_minus() (decimal.Context 메서드)

(decimal.Decimal 메서드)

next_plus() (decimal.Context 메서드)

(decimal.Decimal 메서드)

next_toward() (decimal.Context 메서드)

(decimal.Decimal 메서드)

nextfile() (fileinput 모듈)

nextkey() (dbm.gnu.gdbm 메서드)

nextSibling (xml.dom.Node의 속성)

ngettext() (gettext 모듈)

(gettext.GNUTranslations 메서드)

(gettext.NullTranslations 메서드)

nice() (os 모듈)

nis (모듈)

NL (token 모듈)

nl() (curses 모듈)

nl_langinfo() (locale 모듈)

nlargest() (heapq 모듈)

nlst() (ftplib.FTP 메서드)

NNTP

protocol

NNTP (nntplib 클래스)

nntp_implementation (nntplib.NNTP의 속성)

NNTP_SSL (nntplib 클래스)

nntp_version (nntplib.NNTP의 속성)

NNTPDataError

NNTPError

nntplib (모듈)

NNTPPermanentError

NNTPProtocolError

NNTPReplyError

NNTPTemporaryError

no_proxy

no_tracing() (test.support 모듈)

no_type_check() (typing 모듈)

no_type_check_decorator() (typing 모듈)

nocbreak() (curses 모듈)

NoDataAllowedErr

node() (platform 모듈)

nodelay() (curses.window 메서드)

nodeName (xml.dom.Node의 속성)

NodeTransformer (ast 클래스)

nodeType (xml.dom.Node의 속성)

nodeValue (xml.dom.Node의 속성)

NodeVisitor (ast 클래스)

noecho() (curses 모듈)

NOEXPR (locale 모듈)

NoModificationAllowedErr

nonblock() (ossaudiodev.oss_audio_device 메서드)

NonCallableMagicMock (unittest.mock 클래스)

NonCallableMock (unittest.mock 클래스)

None

객체, [1], [2]

None (Built-in object)

(내장 변수)

nonl() (curses 모듈)

nonlocal

글

nonzero (2to3 fixer)

noop() (imaplib.IMAP4 메서드)

(poplib.POP3 메서드)

NoOptionError

NOP (opcode)

noqiflush() (curses 모듈)

noraw() (curses 모듈)

NoReturn (typing 모듈)

NORMAL_PRIORITY_CLASS (subprocess 모듈)

normalize() (decimal.Context 메서드)

(decimal.Decimal 메서드)

(locale 모듈)

(unicodedata 모듈)

(xml.dom.Node 메서드)

NORMALIZE_WHITESPACE (doctest 모듈)

normalvariate() (random 모듈)

normcase() (os.path 모듈)

normpath() (os.path 모듈)

NoSectionError

NoSuchMailboxError

not

연산자, [1]

not in

연산자, [1], [2]

not_() (operator 모듈)

NotADirectoryError

notation

notationDecl() (xml.sax.handler.DTDHandler 메서드)

NotationDeclHandler() (xml.parsers.expat.xmlparser 메서드)

notations (xml.dom.DocumentType의 속성)

NotConnected

NoteBook (tkinter.tix 클래스)

Notebook (tkinter.ttk 클래스)

NotEmptyError

NOTEQUAL (token 모듈)

NotFoundErr

notify() (asyncio.Condition 메서드)

(threading.Condition 메서드)

notify_all() (asyncio.Condition 메서드)

(threading.Condition 메서드)

notimeout() (curses.window 메서드)

NotImplemented

객체

NotImplemented (내장 변수)

NotImplementedError

NotStandaloneHandler() (xml.parsers.expat.xmlparser 메서드)

NotSupportedErr

NotSupportedError

noutrefresh() (curses.window 메서드)

now() (datetime.datetime의 클래스 메서드)

NSIG (signal 모듈)

nsmallest() (heapq 모듈)

NT_OFFSET (token 모듈)

NTEventLogHandler (logging.handlers 클래스)

ntohl() (socket 모듈)

ntohs() (socket 모듈)

ntransfercmd() (ftplib.FTP 메서드)

null

operation, [1]

nullcontext() (contextlib 모듈)

NullFormatter (formatter 클래스)

NullHandler (logging 클래스)

NullImporter (imp 클래스)

NullTranslations (gettext 클래스)

NullWriter (formatter 클래스)

num_addresses (ipaddress.IPv4Network의 속성)

(ipaddress.IPv6Network의 속성)

number

complex

floating point

Number (numbers 클래스)

NUMBER (token 모듈)

number_class() (decimal.Context 메서드)

(decimal.Decimal 메서드)

numbers (모듈)

numerator (fractions.Fraction의 속성)

(numbers.Rational의 속성)

numeric

conversions

literals

object

types, operations on

객체, [1], [2], [3]

numeric literal

numeric() (unicodedata 모듈)

Numerical Python

numinput() (turtle 모듈)

numliterals (2to3 fixer)

탐색

색인

모듈 |

Python »

3.7.17 Documentation »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

Python »

3.7.17 Documentation »

|

Index – O

O_APPEND (os 모듈)

O_ASYNC (os 모듈)

O_BINARY (os 모듈)

O_CLOEXEC (os 모듈)

O_CREAT (os 모듈)

O_DIRECT (os 모듈)

O_DIRECTORY (os 모듈)

O_DSYNC (os 모듈)

O_EXCL (os 모듈)

O_EXLOCK (os 모듈)

O_NDELAY (os 모듈)

O_NOATIME (os 모듈)

O_NOCTTY (os 모듈)

O_NOFOLLOW (os 모듈)

O_NOINHERIT (os 모듈)

O_NONBLOCK (os 모듈)

O_PATH (os 모듈)

O_RANDOM (os 모듈)

O_RDONLY (os 모듈)

O_RDWR (os 모듈)

O_RSYNC (os 모듈)

O_SEQUENTIAL (os 모듈)

O_SHLOCK (os 모듈)

O_SHORT_LIVED (os 모듈)

O_SYNC (os 모듈)

O_TEMPORARY (os 모듈)

O_TEXT (os 모듈)

O_TMPFILE (os 모듈)

O_TRUNC (os 모듈)

O_WRONLY (os 모듈)

obj (memoryview의 속성)

object

code, [1], [2], [3]

deallocation

finalization

immutable, [1]

numeric

object (UnicodeError의 속성)

(객체)

(내장 클래스)

object.__slots__ (내장 변수)

object_filenames() (distutils.ccompiler.CCompiler 메서드)

objects

comparing

flattening

marshalling

persistent

pickling

serializing

obufcount() (ossaudiodev.oss_audio_device 메서드)

obuffree() (ossaudiodev.oss_audio_device 메서드)

oct() (내장 함수)

octal

literals

octal literal

octdigits (string 모듈)

offset (traceback.TracebackException의 속성)

(xml.parsers.expat.ExpatError의 속성)

OK (curses 모듈)

old_value (contextvars.contextvars.Token.Token의 속성)

OleDLL (ctypes 클래스)

onclick() (turtle 모듈), [1]

ondrag() (turtle 모듈)

onecmd() (cmd.Cmd 메서드)

onkey() (turtle 모듈)

onkeypress() (turtle 모듈)

onkeyrelease() (turtle 모듈)

onrelease() (turtle 모듈)

onscreenclick() (turtle 모듈)

ontimer() (turtle 모듈)

OP (token 모듈)

OP_ALL (ssl 모듈)

OP_CIPHER_SERVER_PREFERENCE (ssl 모듈)

OP_ENABLE_MIDDLEBOX_COMPAT (ssl 모듈)

OP_NO_COMPRESSION (ssl 모듈)

OP_NO_RENEGOTIATION (ssl 모듈)

OP_NO_SSLv2 (ssl 모듈)

OP_NO_SSLv3 (ssl 모듈)

OP_NO_TICKET (ssl 모듈)

OP_NO_TLSv1 (ssl 모듈)

OP_NO_TLSv1_1 (ssl 모듈)

OP_NO_TLSv1_2 (ssl 모듈)

OP_NO_TLSv1_3 (ssl 모듈)

OP_SINGLE_DH_USE (ssl 모듈)

OP_SINGLE_ECDH_USE (ssl 모듈)

open

내장 함수, [1]

open() (aifc 모듈)

(bz2 모듈)

(codecs 모듈)

(dbm 모듈)

(dbm.dumb 모듈)

(dbm.gnu 모듈)

(dbm.ndbm 모듈)

(distutils.text_file.TextFile 메서드)

(gzip 모듈)

(imaplib.IMAP4 메서드)

(io 모듈)

(lzma 모듈)

(os 모듈)

(ossaudiodev 모듈)

(pathlib.Path 메서드)

(pipes.Template 메서드)

(shelve 모듈)

(sunau 모듈)

(tarfile 모듈)

(tarfile.TarFile의 클래스 메서드)

(telnetlib.Telnet 메서드)

(tokenize 모듈)

(urllib.request.OpenerDirector 메서드)

(urllib.request.URLopener 메서드)

(wave 모듈)

(webbrowser 모듈)

(webbrowser.controller 메서드)

(zipfile.ZipFile 메서드)

(내장 함수)

open_binary() (importlib.resources 모듈)

open_connection() (asyncio 모듈)

open_new() (webbrowser 모듈)

(webbrowser.controller 메서드)

open_new_tab() (webbrowser 모듈)

(webbrowser.controller 메서드)

open_osfhandle() (msvcrt 모듈)

open_resource() (importlib.abc.ResourceReader의 메서드)

open_text() (importlib.resources 모듈)

open_unix_connection() (asyncio 모듈)

open_unknown() (urllib.request.URLopener 메서드)

open_urlresource() (test.support 모듈)

OpenDatabase() (msilib 모듈)

OpenerDirector (urllib.request 클래스)

openfp() (sunau 모듈)

(wave 모듈)

OpenKey() (winreg 모듈)

OpenKeyEx() (winreg 모듈)

openlog() (syslog 모듈)

openmixer() (ossaudiodev 모듈)

openpty() (os 모듈)

(pty 모듈)

OpenSSL

(use in module hashlib)

(use in module ssl)

OPENSSL_VERSION (ssl 모듈)

OPENSSL_VERSION_INFO (ssl 모듈)

OPENSSL_VERSION_NUMBER (ssl 모듈)

OpenView() (msilib.Database 메서드)

operation

binary arithmetic

binary bitwise

Boolean

concatenation

null, [1]

power

repetition

shifting

slice

subscript

unary arithmetic

unary bitwise

OperationalError

operations

bitwise

Boolean, [1]

masking

shifting

operations on

dictionary type

integer types

list type

mapping types

numeric types

sequence types, [1]

operator

+ (plus), [1], [2]

- (minus), [1], [2]

comparison

overloading

precedence

ternary

operator (2to3 fixer)

(모듈)

operators

opmap (dis 모듈)

opname (dis 모듈)

optim_args_from_interpreter_flags() (test.support 모듈)

optimize() (pickletools 모듈)

OPTIMIZED_BYTECODE_SUFFIXES (importlib.machinery 모듈)

Optional (typing 모듈)

OptionGroup (optparse 클래스)

OptionMenu (tkinter.tix 클래스)

OptionParser (optparse 클래스)

options (doctest.Example의 속성)

Options (ssl 클래스)

options (ssl.SSLContext의 속성)

options() (configparser.ConfigParser 메서드)

optionxform() (configparser.ConfigParser 메서드), [1]

optparse (모듈)

or

bitwise

exclusive

inclusive

연산자, [1], [2]

or_() (operator 모듈)

ord

내장 함수

ord() (내장 함수)

order

evaluation

ordered_attributes (xml.parsers.expat.xmlparser의 속성)

OrderedDict (collections 클래스)

(typing 클래스)

origin (importlib.machinery.ModuleSpec의 속성)

origin_req_host (urllib.request.Request의 속성)

origin_server (wsgiref.handlers.BaseHandler의 속성)

os

모듈

os (모듈)

os.path (모듈)

os_environ (wsgiref.handlers.BaseHandler의 속성)

OSError

ossaudiodev (모듈)

OSSAudioError

outfile

json.tool command line option

output

standard

output (subprocess.CalledProcessError의 속성)

(subprocess.TimeoutExpired의 속성)

(unittest.TestCase의 속성)

output() (http.cookies.BaseCookie 메서드)

(http.cookies.Morsel 메서드)

output_charset (email.charset.Charset의 속성)

output_charset() (gettext.NullTranslations 메서드)

output_codec (email.charset.Charset의 속성)

output_difference() (doctest.OutputChecker 메서드)

OutputChecker (doctest 클래스)

OutputString() (http.cookies.Morsel 메서드)

over() (nntplib.NNTP 메서드)

Overflow (decimal 클래스)

OverflowError

(built-in exception), [1], [2], [3], [4], [5]

overlaps() (ipaddress.IPv4Network 메서드)

(ipaddress.IPv6Network 메서드)

overlay() (curses.window 메서드)

overload() (typing 모듈)

overloading

operator

overwrite() (curses.window 메서드)

owner() (pathlib.Path 메서드)

탐색

색인

모듈 |

Python »

3.7.17 Documentation »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

Python »

3.7.17 Documentation »

|

Index – P

p (pdb command)

P_ALL (os 모듈)

P_DETACH (os 모듈)

P_NOWAIT (os 모듈)

P_NOWAITO (os 모듈)

P_OVERLAY (os 모듈)

P_PGID (os 모듈)

P_PID (os 모듈)

P_WAIT (os 모듈)

pack() (mailbox.MH 메서드)

(struct 모듈)

(struct.Struct 메서드)

pack_array() (xdrlib.Packer 메서드)

pack_bytes() (xdrlib.Packer 메서드)

pack_double() (xdrlib.Packer 메서드)

pack_farray() (xdrlib.Packer 메서드)

pack_float() (xdrlib.Packer 메서드)

pack_fopaque() (xdrlib.Packer 메서드)

pack_fstring() (xdrlib.Packer 메서드)

pack_into() (struct 모듈)

(struct.Struct 메서드)

pack_list() (xdrlib.Packer 메서드)

pack_opaque() (xdrlib.Packer 메서드)

pack_string() (xdrlib.Packer 메서드)

package, [1]

namespace

portion

regular

Package (importlib.resources 모듈)

package (패키지)

package variable

__all__

packed (ipaddress.IPv4Address의 속성)

(ipaddress.IPv6Address의 속성)

Packer (xdrlib 클래스)

packing

binary data

packing (widgets)

PAGER

pair_content() (curses 모듈)

pair_number() (curses 모듈)

PanedWindow (tkinter.tix 클래스)

parameter

call semantics

difference from argument

function definition

value, default

Parameter (inspect 클래스)

parameter (매개변수)

ParameterizedMIMEHeader (email.headerregistry 클래스)

parameters (inspect.Signature의 속성)

params (email.headerregistry.ParameterizedMIMEHeader의 속성)

pardir (os 모듈)

paren (2to3 fixer)

parent (importlib.machinery.ModuleSpec의 속성)

(pyclbr.Class의 속성)

(pyclbr.Function의 속성)

(urllib.request.BaseHandler의 속성)

parent() (tkinter.ttk.Treeview 메서드)

parenthesized form

parentNode (xml.dom.Node의 속성)

parents (collections.ChainMap의 속성)

paretovariate() (random 모듈)

parse() (ast 모듈)

(cgi 모듈)

(doctest.DocTestParser 메서드)

(email.parser.BytesParser 메서드)

(email.parser.Parser 메서드)

(string.Formatter 메서드)

(urllib.robotparser.RobotFileParser 메서드)

(xml.dom.minidom 모듈)

(xml.dom.pulldom 모듈)

(xml.etree.ElementTree 모듈)

(xml.etree.ElementTree.ElementTree 메서드)

Parse() (xml.parsers.expat.xmlparser 메서드)

parse() (xml.sax 모듈)

(xml.sax.xmlreader.XMLReader 메서드)

parse_and_bind() (readline 모듈)

parse_args() (argparse.ArgumentParser 메서드)

PARSE_COLNAMES (sqlite3 모듈)

parse_config_h() (sysconfig 모듈)

PARSE_DECLTYPES (sqlite3 모듈)

parse_header() (cgi 모듈)

parse_intermixed_args() (argparse.ArgumentParser 메서드)

parse_known_args() (argparse.ArgumentParser 메서드)

parse_known_intermixed_args() (argparse.ArgumentParser 메서드)

parse_multipart() (cgi 모듈)

parse_qs() (cgi 모듈)

(urllib.parse 모듈)

parse_qsl() (cgi 모듈)

(urllib.parse 모듈)

parseaddr() (email.utils 모듈)

parsebytes() (email.parser.BytesParser 메서드)

parsedate() (email.utils 모듈)

parsedate_to_datetime() (email.utils 모듈)

parsedate_tz() (email.utils 모듈)

ParseError (xml.etree.ElementTree 클래스)

ParseFile() (xml.parsers.expat.xmlparser 메서드)

ParseFlags() (imaplib 모듈)

parser

Parser (email.parser 클래스)

parser (모듈)

ParserCreate() (xml.parsers.expat 모듈)

ParserError

ParseResult (urllib.parse 클래스)

ParseResultBytes (urllib.parse 클래스)

parsestr() (email.parser.Parser 메서드)

parseString() (xml.dom.minidom 모듈)

(xml.dom.pulldom 모듈)

(xml.sax 모듈)

parsing

Python source code

URL

ParsingError

partial (asyncio.IncompleteReadError의 속성)

partial() (functools 모듈)

(imaplib.IMAP4 메서드)

partialmethod (functools 클래스)

parties (threading.Barrier의 속성)

partition() (bytearray 메서드)

(bytes 메서드)

(str 메서드)

pass

글

pass_() (poplib.POP3 메서드)

Paste

patch() (test.support 모듈)

(unittest.mock 모듈)

patch.dict() (unittest.mock 모듈)

patch.multiple() (unittest.mock 모듈)

patch.object() (unittest.mock 모듈)

patch.stopall() (unittest.mock 모듈)

PATH, [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12], [13], [14], [15], [16], [17], [18], [19], [20], [21], [22], [23], [24], [25], [26], [27], [28], [29], [30], [31], [32], [33], [34], [35]

path

configuration file

hooks

module search, [1], [2], [3], [4], [5], [6], [7]

operations, [1]

path (http.cookiejar.Cookie의 속성)

(http.server.BaseHTTPRequestHandler의 속성)

(importlib.abc.FileLoader의 속성)

(importlib.machinery.ExtensionFileLoader의 속성)

(importlib.machinery.FileFinder의 속성)

(importlib.machinery.SourceFileLoader의 속성)

(importlib.machinery.SourcelessFileLoader의 속성)

(in module sys), [1], [2], [3]

(os.DirEntry의 속성)

Path (pathlib 클래스)

path (sys 모듈)

path based finder

(경로 기반 파인더)

Path browser

path entry (경로 엔트리)

path entry finder (경로 엔트리 파인더)

path entry hook (경로 엔트리 훅)

path hooks

path() (importlib.resources 모듈)

path-like object (경로류 객체)

path_hook() (importlib.machinery.FileFinder의 클래스 메서드)

path_hooks (sys 모듈)

path_importer_cache (sys 모듈)

path_mtime() (importlib.abc.SourceLoader 메서드)

path_return_ok() (http.cookiejar.CookiePolicy 메서드)

path_stats() (importlib.abc.SourceLoader 메서드)

(importlib.machinery.SourceFileLoader 메서드)

pathconf() (os 모듈)

pathconf_names (os 모듈)

PathEntryFinder (importlib.abc 클래스)

PATHEXT, [1]

PathFinder (importlib.machinery 클래스)

pathlib (모듈)

PathLike (os 클래스)

pathname2url() (urllib.request 모듈)

pathsep (os 모듈)

pattern (re.error의 속성)

(re.Pattern의 속성)

Pattern (typing 클래스)

pause() (signal 모듈)

pause_reading() (asyncio.ReadTransport 메서드)

pause_writing() (asyncio.BaseProtocol 메서드)

PAX_FORMAT (tarfile 모듈)

pax_headers (tarfile.TarFile의 속성)

(tarfile.TarInfo의 속성)

pbkdf2_hmac() (hashlib 모듈)

pd() (turtle 모듈)

Pdb (class in pdb)

(pdb 클래스)

pdb (모듈)

peek() (bz2.BZ2File 메서드)

(gzip.GzipFile 메서드)

(io.BufferedReader 메서드)

(lzma.LZMAFile 메서드)

(weakref.finalize 메서드)

peer (smtpd.SMTPChannel의 속성)

PEM_cert_to_DER_cert() (ssl 모듈)

pen() (turtle 모듈)

pencolor() (turtle 모듈)

pending (ssl.MemoryBIO의 속성)

pending() (ssl.SSLSocket 메서드)

PendingDeprecationWarning

pendown() (turtle 모듈)

pensize() (turtle 모듈)

penup() (turtle 모듈)

PEP

PERCENT (token 모듈)

PERCENTEQUAL (token 모듈)

perf_counter() (time 모듈)

perf_counter_ns() (time 모듈)

Performance

PermissionError

permutations() (itertools 모듈)

Persist() (msilib.SummaryInformation 메서드)

persistence

persistent

objects

persistent_id (pickle protocol)

persistent_id() (pickle.Pickler 메서드)

persistent_load (pickle protocol)

persistent_load() (pickle.Unpickler 메서드)

PF_CAN (socket 모듈)

PF_PACKET (socket 모듈)

PF_RDS (socket 모듈)

pformat() (pprint 모듈)

(pprint.PrettyPrinter 메서드)

PGO (test.support 모듈)

phase() (cmath 모듈)

Philbrick, Geoff

physical line, [1], [2]

pi (cmath 모듈)

(math 모듈)

pickle

모듈, [1], [2], [3]

pickle (모듈)

pickle() (copyreg 모듈)

PickleError

Pickler (pickle 클래스)

pickletools (모듈)

pickletools command line option

--annotate

--indentlevel=<num>

--memo

--output=<file>

--preamble=<preamble>

-a

-l

-m

-o

-p

pickling

objects

PicklingError

pid (asyncio.asyncio.subprocess.Process의 속성)

(multiprocessing.Process의 속성)

(subprocess.Popen의 속성)

PIPE (subprocess 모듈)

Pipe() (multiprocessing 모듈)

pipe() (os 모듈)

pipe2() (os 모듈)

PIPE_BUF (select 모듈)

pipe_connection_lost() (asyncio.SubprocessProtocol 메서드)

pipe_data_received() (asyncio.SubprocessProtocol 메서드)

PIPE_MAX_SIZE (test.support 모듈)

pipes (모듈)

PKG_DIRECTORY (imp 모듈)

pkgutil (모듈)

placeholder (textwrap.TextWrapper의 속성)

PLAT

platform (in module sys)

(sys 모듈)

(모듈)

platform() (platform 모듈)

PlaySound() (winsound 모듈)

plist

file

plistlib (모듈)

plock() (os 모듈)

plus

PLUS (token 모듈)

plus() (decimal.Context 메서드)

PLUSEQUAL (token 모듈)

pm() (pdb 모듈)

POINTER() (ctypes 모듈)

pointer() (ctypes 모듈)

polar() (cmath 모듈)

Policy (email.policy 클래스)

poll() (multiprocessing.connection.Connection 메서드)

(select 모듈)

(select.devpoll 메서드)

(select.epoll 메서드)

(select.poll 메서드)

(subprocess.Popen 메서드)

PollSelector (selectors 클래스)

Pool (multiprocessing.pool 클래스)

pop() (array.array 메서드)

(collections.deque 메서드)

(dict 메서드)

(frozenset 메서드)

(mailbox.Mailbox 메서드)

(sequence method)

POP3

protocol

POP3 (poplib 클래스)

POP3_SSL (poplib 클래스)

pop_alignment() (formatter.formatter 메서드)

pop_all() (contextlib.ExitStack 메서드)

POP_BLOCK (opcode)

POP_EXCEPT (opcode)

pop_font() (formatter.formatter 메서드)

POP_JUMP_IF_FALSE (opcode)

POP_JUMP_IF_TRUE (opcode)

pop_margin() (formatter.formatter 메서드)

pop_source() (shlex.shlex 메서드)

pop_style() (formatter.formatter 메서드)

POP_TOP (opcode)

Popen (subprocess 클래스)

popen() (in module os), [1]

(os 모듈)

(platform 모듈)

popitem() (collections.OrderedDict 메서드)

(dict 메서드)

(mailbox.Mailbox 메서드)

popleft() (collections.deque 메서드)

poplib (모듈)

PopupMenu (tkinter.tix 클래스)

port (http.cookiejar.Cookie의 속성)

port_specified (http.cookiejar.Cookie의 속성)

portion

package

portion (포션)

pos (json.JSONDecodeError의 속성)

(re.error의 속성)

(re.Match의 속성)

pos() (operator 모듈)

(turtle 모듈)

position (xml.etree.ElementTree.ParseError의 속성)

position() (turtle 모듈)

positional argument (위치 인자)

POSIX

I/O control

threads

posix (모듈)

POSIX_FADV_DONTNEED (os 모듈)

POSIX_FADV_NOREUSE (os 모듈)

POSIX_FADV_NORMAL (os 모듈)

POSIX_FADV_RANDOM (os 모듈)

POSIX_FADV_SEQUENTIAL (os 모듈)

POSIX_FADV_WILLNEED (os 모듈)

posix_fadvise() (os 모듈)

posix_fallocate() (os 모듈)

POSIXLY_CORRECT

PosixPath (pathlib 클래스)

post() (nntplib.NNTP 메서드)

(ossaudiodev.oss_audio_device 메서드)

post_handshake_auth (ssl.SSLContext의 속성)

post_mortem() (pdb 모듈)

post_setup() (venv.EnvBuilder 메서드)

postcmd() (cmd.Cmd 메서드)

postloop() (cmd.Cmd 메서드)

pow

내장 함수, [1], [2], [3], [4], [5]

pow() (math 모듈)

(operator 모듈)

(내장 함수)

power

operation

power() (decimal.Context 메서드)

pp (pdb command)

pprint (모듈)

pprint() (pprint 모듈)

(pprint.PrettyPrinter 메서드)

prcal() (calendar 모듈)

pread() (os 모듈)

preadv() (os 모듈)

preamble (email.message.EmailMessage의 속성)

(email.message.Message의 속성)

precedence

operator

precmd() (cmd.Cmd 메서드)

prefix, [1], [2], [3]

PREFIX (distutils.sysconfig 모듈)

prefix (sys 모듈)

(xml.dom.Attr의 속성)

(xml.dom.Node의 속성)

(zipimport.zipimporter의 속성)

PREFIXES (site 모듈)

prefixlen (ipaddress.IPv4Network의 속성)

(ipaddress.IPv6Network의 속성)

preloop() (cmd.Cmd 메서드)

prepare() (logging.handlers.QueueHandler 메서드)

(logging.handlers.QueueListener 메서드)

prepare_class() (types 모듈)

prepare_input_source() (xml.sax.saxutils 모듈)

prepend() (pipes.Template 메서드)

preprocess() (distutils.ccompiler.CCompiler 메서드)

PrettyPrinter (pprint 클래스)

prev() (tkinter.ttk.Treeview 메서드)

previousSibling (xml.dom.Node의 속성)

primary

print

내장 함수

print (2to3 fixer)

print() (built-in function)

__str__() (object method)

print() (내장 함수)

print_callees() (pstats.Stats 메서드)

print_callers() (pstats.Stats 메서드)

print_directory() (cgi 모듈)

print_environ() (cgi 모듈)

print_environ_usage() (cgi 모듈)

print_exc() (timeit.Timer 메서드)

(traceback 모듈)

print_exception() (traceback 모듈)

PRINT_EXPR (opcode)

print_form() (cgi 모듈)

print_help() (argparse.ArgumentParser 메서드)

print_last() (traceback 모듈)

print_stack() (asyncio.Task 메서드)

(traceback 모듈)

print_stats() (profile.Profile 메서드)

(pstats.Stats 메서드)

print_tb() (traceback 모듈)

print_usage() (argparse.ArgumentParser 메서드)

(optparse.OptionParser 메서드)

print_version() (optparse.OptionParser 메서드)

printable (string 모듈)

printdir() (zipfile.ZipFile 메서드)

printf-style formatting, [1]

PRIO_PGRP (os 모듈)

PRIO_PROCESS (os 모듈)

PRIO_USER (os 모듈)

PriorityQueue (asyncio 클래스)

(queue 클래스)

private

names

prlimit() (resource 모듈)

prmonth() (calendar 모듈)

(calendar.TextCalendar 메서드)

ProactorEventLoop (asyncio 클래스)

procedure

call

process

group, [1]

id

id of parent

killing, [1]

scheduling priority, [1]

signalling, [1]

Process (multiprocessing 클래스)

process() (logging.LoggerAdapter 메서드)

process_exited() (asyncio.SubprocessProtocol 메서드)

process_message() (smtpd.SMTPServer 메서드)

process_request() (socketserver.BaseServer 메서드)

process_time() (time 모듈)

process_time_ns() (time 모듈)

process_tokens() (tabnanny 모듈)

ProcessError

processes, light-weight

ProcessingInstruction() (xml.etree.ElementTree 모듈)

processingInstruction() (xml.sax.handler.ContentHandler 메서드)

ProcessingInstructionHandler() (xml.parsers.expat.xmlparser 메서드)

ProcessLookupError

processor time, [1], [2]

processor() (platform 모듈)

ProcessPoolExecutor (concurrent.futures 클래스)

product() (itertools 모듈)

Profile (profile 클래스)

profile (모듈)

profile function, [1], [2]

profiler, [1]

profiling, deterministic

program

ProgrammingError

Progressbar (tkinter.ttk 클래스)

prompt (cmd.Cmd의 속성)

prompt_user_passwd() (urllib.request.FancyURLopener 메서드)

prompts, interpreter

propagate (logging.Logger의 속성)

property (내장 클래스)

property list

property_declaration_handler (xml.sax.handler 모듈)

property_dom_node (xml.sax.handler 모듈)

property_lexical_handler (xml.sax.handler 모듈)

property_xml_string (xml.sax.handler 모듈)

PropertyMock (unittest.mock 클래스)

prot_c() (ftplib.FTP_TLS 메서드)

prot_p() (ftplib.FTP_TLS 메서드)

proto (socket.socket의 속성)

protocol

CGI

context management

copy

FTP, [1]

HTTP, [1], [2], [3], [4], [5]

IMAP4

IMAP4_SSL

IMAP4_stream

iterator

NNTP

POP3

SMTP

Telnet

Protocol (asyncio 클래스)

protocol (ssl.SSLContext의 속성)

PROTOCOL_SSLv2 (ssl 모듈)

PROTOCOL_SSLv23 (ssl 모듈)

PROTOCOL_SSLv3 (ssl 모듈)

PROTOCOL_TLS (ssl 모듈)

PROTOCOL_TLS_CLIENT (ssl 모듈)

PROTOCOL_TLS_SERVER (ssl 모듈)

PROTOCOL_TLSv1 (ssl 모듈)

PROTOCOL_TLSv1_1 (ssl 모듈)

PROTOCOL_TLSv1_2 (ssl 모듈)

protocol_version (http.server.BaseHTTPRequestHandler의 속성)

PROTOCOL_VERSION (imaplib.IMAP4의 속성)

ProtocolError (xmlrpc.client 클래스)

provisional API (잠정 API)

provisional package (잠정 패키지)

proxy() (weakref 모듈)

proxyauth() (imaplib.IMAP4 메서드)

ProxyBasicAuthHandler (urllib.request 클래스)

ProxyDigestAuthHandler (urllib.request 클래스)

ProxyHandler (urllib.request 클래스)

ProxyType (weakref 모듈)

ProxyTypes (weakref 모듈)

pryear() (calendar.TextCalendar 메서드)

ps1 (sys 모듈)

ps2 (sys 모듈)

pstats (모듈)

pstdev() (statistics 모듈)

pthread_getcpuclockid() (time 모듈)

pthread_kill() (signal 모듈)

pthread_sigmask() (signal 모듈)

pthreads

pty

모듈

pty (모듈)

pu() (turtle 모듈)

publicId (xml.dom.DocumentType의 속성)

PullDom (xml.dom.pulldom 클래스)

punctuation (string 모듈)

punctuation_chars (shlex.shlex의 속성)

PurePath (pathlib 클래스)

PurePath.anchor (pathlib 모듈)

PurePath.drive (pathlib 모듈)

PurePath.name (pathlib 모듈)

PurePath.parent (pathlib 모듈)

PurePath.parents (pathlib 모듈)

PurePath.parts (pathlib 모듈)

PurePath.root (pathlib 모듈)

PurePath.stem (pathlib 모듈)

PurePath.suffix (pathlib 모듈)

PurePath.suffixes (pathlib 모듈)

PurePosixPath (pathlib 클래스)

PureProxy (smtpd 클래스)

PureWindowsPath (pathlib 클래스)

purge() (re 모듈)

Purpose.CLIENT_AUTH (ssl 모듈)

Purpose.SERVER_AUTH (ssl 모듈)

push() (asynchat.async_chat 메서드)

(code.InteractiveConsole 메서드)

(contextlib.ExitStack 메서드)

push_alignment() (formatter.formatter 메서드)

push_async_callback() (contextlib.AsyncExitStack 메서드)

push_async_exit() (contextlib.AsyncExitStack 메서드)

push_font() (formatter.formatter 메서드)

push_margin() (formatter.formatter 메서드)

push_source() (shlex.shlex 메서드)

push_style() (formatter.formatter 메서드)

push_token() (shlex.shlex 메서드)

push_with_producer() (asynchat.async_chat 메서드)

pushbutton() (msilib.Dialog 메서드)

put() (asyncio.Queue의 메서드)

(multiprocessing.Queue 메서드)

(multiprocessing.SimpleQueue 메서드)

(queue.Queue 메서드)

(queue.SimpleQueue 메서드)

put_nowait() (asyncio.Queue 메서드)

(multiprocessing.Queue 메서드)

(queue.Queue 메서드)

(queue.SimpleQueue 메서드)

putch() (msvcrt 모듈)

putenv() (os 모듈)

putheader() (http.client.HTTPConnection 메서드)

putp() (curses 모듈)

putrequest() (http.client.HTTPConnection 메서드)

putwch() (msvcrt 모듈)

putwin() (curses.window 메서드)

pvariance() (statistics 모듈)

pwd

모듈

pwd (모듈)

pwd() (ftplib.FTP 메서드)

pwrite() (os 모듈)

pwritev() (os 모듈)

Py_ABS (C 매크로)

Py_AddPendingCall (C 함수)

Py_AddPendingCall()

Py_AtExit (C 함수)

Py_BEGIN_ALLOW_THREADS

(C 매크로)

Py_BLOCK_THREADS (C 매크로)

Py_buffer (C 데이터 형식)

Py_buffer.buf (C 멤버 변수)

Py_buffer.format (C 멤버 변수)

Py_buffer.internal (C 멤버 변수)

Py_buffer.itemsize (C 멤버 변수)

Py_buffer.len (C 멤버 변수)

Py_buffer.ndim (C 멤버 변수)

Py_buffer.obj (C 멤버 변수)

Py_buffer.readonly (C 멤버 변수)

Py_buffer.shape (C 멤버 변수)

Py_buffer.strides (C 멤버 변수)

Py_buffer.suboffsets (C 멤버 변수)

Py_BuildValue (C 함수)

Py_BytesWarningFlag (C 변수)

Py_CHARMASK (C 매크로)

Py_CLEAR (C 함수)

py_compile (모듈)

PY_COMPILED (imp 모듈)

Py_CompileString (C 함수)

Py_CompileString(), [1], [2]

Py_CompileStringExFlags (C 함수)

Py_CompileStringFlags (C 함수)

Py_CompileStringObject (C 함수)

Py_complex (C 데이터 형식)

Py_DebugFlag (C 변수)

Py_DecodeLocale (C 함수)

Py_DECREF (C 함수)

Py_DECREF()

Py_DontWriteBytecodeFlag (C 변수)

Py_Ellipsis (C 변수)

Py_EncodeLocale (C 함수)

Py_END_ALLOW_THREADS

(C 매크로)

Py_EndInterpreter (C 함수)

Py_EnterRecursiveCall (C 함수)

Py_eval_input (C 변수)

Py_Exit (C 함수)

Py_False (C 변수)

Py_FatalError (C 함수)

Py_FatalError()

Py_FdIsInteractive (C 함수)

Py_file_input (C 변수)

Py_Finalize (C 함수)

Py_FinalizeEx (C 함수)

Py_FinalizeEx(), [1], [2], [3], [4]

PY_FROZEN (imp 모듈)

Py_FrozenFlag (C 변수)

Py_GetBuildInfo (C 함수)

Py_GetCompiler (C 함수)

Py_GetCopyright (C 함수)

Py_GETENV (C 매크로)

Py_GetExecPrefix (C 함수)

Py_GetExecPrefix()

Py_GetPath (C 함수)

Py_GetPath(), [1], [2]

Py_GetPlatform (C 함수)

Py_GetPrefix (C 함수)

Py_GetPrefix()

Py_GetProgramFullPath (C 함수)

Py_GetProgramFullPath()

Py_GetProgramName (C 함수)

Py_GetPythonHome (C 함수)

Py_GetVersion (C 함수)

Py_HashRandomizationFlag (C 변수)

Py_IgnoreEnvironmentFlag (C 변수)

Py_INCREF (C 함수)

Py_INCREF()

Py_Initialize (C 함수)

Py_Initialize(), [1], [2], [3]

Py_InitializeEx (C 함수)

Py_InspectFlag (C 변수)

Py_InteractiveFlag (C 변수)

Py_IsInitialized (C 함수)

Py_IsInitialized()

Py_IsolatedFlag (C 변수)

Py_LeaveRecursiveCall (C 함수)

Py_LegacyWindowsFSEncodingFlag (C 변수)

Py_LegacyWindowsStdioFlag (C 변수)

Py_Main (C 함수)

Py_MAX (C 매크로)

Py_MEMBER_SIZE (C 매크로)

Py_MIN (C 매크로)

Py_mod_create (C 변수)

Py_mod_exec (C 변수)

Py_NewInterpreter (C 함수)

Py_None (C 변수)

Py_NoSiteFlag (C 변수)

Py_NotImplemented (C 변수)

Py_NoUserSiteDirectory (C 변수)

py_object (ctypes 클래스)

Py_OptimizeFlag (C 변수)

Py_PRINT_RAW

PY_PYTHON

Py_QuietFlag (C 변수)

Py_REFCNT (C 매크로)

Py_ReprEnter (C 함수)

Py_ReprLeave (C 함수)

Py_RETURN_FALSE (C 매크로)

Py_RETURN_NONE (C 매크로)

Py_RETURN_NOTIMPLEMENTED (C 매크로)

Py_RETURN_RICHCOMPARE (C 함수)

Py_RETURN_TRUE (C 매크로)

Py_SetPath (C 함수)

Py_SetPath()

Py_SetProgramName (C 함수)

Py_SetProgramName(), [1], [2], [3]

Py_SetPythonHome (C 함수)

Py_SetStandardStreamEncoding (C 함수)

Py_single_input (C 변수)

Py_SIZE (C 매크로)

PY_SOURCE (imp 모듈)

PY_SSIZE_T_MAX

Py_STRINGIFY (C 매크로)

Py_TPFLAGS_BASE_EXC_SUBCLASS (내장 변수)

Py_TPFLAGS_BASETYPE (내장 변수)

Py_TPFLAGS_BYTES_SUBCLASS (내장 변수)

Py_TPFLAGS_DEFAULT (내장 변수)

Py_TPFLAGS_DICT_SUBCLASS (내장 변수)

Py_TPFLAGS_HAVE_FINALIZE (내장 변수)

Py_TPFLAGS_HAVE_GC (내장 변수)

Py_TPFLAGS_HEAPTYPE (내장 변수)

Py_TPFLAGS_LIST_SUBCLASS (내장 변수)

Py_TPFLAGS_LONG_SUBCLASS (내장 변수)

Py_TPFLAGS_READY (내장 변수)

Py_TPFLAGS_READYING (내장 변수)

Py_TPFLAGS_TUPLE_SUBCLASS (내장 변수)

Py_TPFLAGS_TYPE_SUBCLASS (내장 변수)

Py_TPFLAGS_UNICODE_SUBCLASS (내장 변수)

Py_tracefunc (C 데이터 형식)

Py_True (C 변수)

Py_tss_NEEDS_INIT (C 매크로)

Py_tss_t (C 데이터 형식)

Py_TYPE (C 매크로)

Py_UCS1 (C 데이터 형식)

Py_UCS2 (C 데이터 형식)

Py_UCS4 (C 데이터 형식)

Py_UNBLOCK_THREADS (C 매크로)

Py_UnbufferedStdioFlag (C 변수)

Py_UNICODE (C 데이터 형식)

Py_UNICODE_IS_HIGH_SURROGATE (C 매크로)

Py_UNICODE_IS_LOW_SURROGATE (C 매크로)

Py_UNICODE_IS_SURROGATE (C 매크로)

Py_UNICODE_ISALNUM (C 함수)

Py_UNICODE_ISALPHA (C 함수)

Py_UNICODE_ISDECIMAL (C 함수)

Py_UNICODE_ISDIGIT (C 함수)

Py_UNICODE_ISLINEBREAK (C 함수)

Py_UNICODE_ISLOWER (C 함수)

Py_UNICODE_ISNUMERIC (C 함수)

Py_UNICODE_ISPRINTABLE (C 함수)

Py_UNICODE_ISSPACE (C 함수)

Py_UNICODE_ISTITLE (C 함수)

Py_UNICODE_ISUPPER (C 함수)

Py_UNICODE_JOIN_SURROGATES (C 매크로)

Py_UNICODE_TODECIMAL (C 함수)

Py_UNICODE_TODIGIT (C 함수)

Py_UNICODE_TOLOWER (C 함수)

Py_UNICODE_TONUMERIC (C 함수)

Py_UNICODE_TOTITLE (C 함수)

Py_UNICODE_TOUPPER (C 함수)

Py_UNREACHABLE (C 매크로)

Py_UNUSED (C 매크로)

Py_VaBuildValue (C 함수)

Py_VerboseFlag (C 변수)

Py_VISIT (C 함수)

Py_XDECREF (C 함수)

Py_XDECREF()

Py_XINCREF (C 함수)

PyAnySet_Check (C 함수)

PyAnySet_CheckExact (C 함수)

PyArg_Parse (C 함수)

PyArg_ParseTuple (C 함수)

PyArg_ParseTuple()

PyArg_ParseTupleAndKeywords (C 함수)

PyArg_ParseTupleAndKeywords()

PyArg_UnpackTuple (C 함수)

PyArg_ValidateKeywordArguments (C 함수)

PyArg_VaParse (C 함수)

PyArg_VaParseTupleAndKeywords (C 함수)

PyASCIIObject (C 데이터 형식)

PyAsyncMethods (C 데이터 형식)

PyAsyncMethods.am_aiter (C 멤버 변수)

PyAsyncMethods.am_anext (C 멤버 변수)

PyAsyncMethods.am_await (C 멤버 변수)

PyBool_Check (C 함수)

PyBool_FromLong (C 함수)

PyBUF_ANY_CONTIGUOUS (C 매크로)

PyBUF_C_CONTIGUOUS (C 매크로)

PyBUF_CONTIG (C 매크로)

PyBUF_CONTIG_RO (C 매크로)

PyBUF_F_CONTIGUOUS (C 매크로)

PyBUF_FORMAT (C 매크로)

PyBUF_FULL (C 매크로)

PyBUF_FULL_RO (C 매크로)

PyBUF_INDIRECT (C 매크로)

PyBUF_ND (C 매크로), [1]

PyBUF_RECORDS (C 매크로)

PyBUF_RECORDS_RO (C 매크로)

PyBUF_SIMPLE (C 매크로)

PyBUF_STRIDED (C 매크로)

PyBUF_STRIDED_RO (C 매크로)

PyBUF_STRIDES (C 매크로)

PyBUF_WRITABLE (C 매크로)

PyBuffer_FillContiguousStrides (C 함수)

PyBuffer_FillInfo (C 함수)

PyBuffer_FromContiguous (C 함수)

PyBuffer_GetPointer (C 함수)

PyBuffer_IsContiguous (C 함수)

PyBuffer_Release (C 함수)

PyBuffer_SizeFromFormat (C 함수)

PyBuffer_ToContiguous (C 함수)

PyBufferProcs

(C 데이터 형식)

PyBufferProcs.bf_getbuffer (C 멤버 변수)

PyBufferProcs.bf_releasebuffer (C 멤버 변수)

PyByteArray_AS_STRING (C 함수)

PyByteArray_AsString (C 함수)

PyByteArray_Check (C 함수)

PyByteArray_CheckExact (C 함수)

PyByteArray_Concat (C 함수)

PyByteArray_FromObject (C 함수)

PyByteArray_FromStringAndSize (C 함수)

PyByteArray_GET_SIZE (C 함수)

PyByteArray_Resize (C 함수)

PyByteArray_Size (C 함수)

PyByteArray_Type (C 변수)

PyByteArrayObject (C 데이터 형식)

PyBytes_AS_STRING (C 함수)

PyBytes_AsString (C 함수)

PyBytes_AsStringAndSize (C 함수)

PyBytes_Check (C 함수)

PyBytes_CheckExact (C 함수)

PyBytes_Concat (C 함수)

PyBytes_ConcatAndDel (C 함수)

PyBytes_FromFormat (C 함수)

PyBytes_FromFormatV (C 함수)

PyBytes_FromObject (C 함수)

PyBytes_FromString (C 함수)

PyBytes_FromStringAndSize (C 함수)

PyBytes_GET_SIZE (C 함수)

PyBytes_Size (C 함수)

PyBytes_Type (C 변수)

PyBytesObject (C 데이터 형식)

PyCallable_Check (C 함수)

PyCallIter_Check (C 함수)

PyCallIter_New (C 함수)

PyCallIter_Type (C 변수)

PyCapsule (C 데이터 형식)

PyCapsule_CheckExact (C 함수)

PyCapsule_Destructor (C 데이터 형식)

PyCapsule_GetContext (C 함수)

PyCapsule_GetDestructor (C 함수)

PyCapsule_GetName (C 함수)

PyCapsule_GetPointer (C 함수)

PyCapsule_Import (C 함수)

PyCapsule_IsValid (C 함수)

PyCapsule_New (C 함수)

PyCapsule_SetContext (C 함수)

PyCapsule_SetDestructor (C 함수)

PyCapsule_SetName (C 함수)

PyCapsule_SetPointer (C 함수)

PyCell_Check (C 함수)

PyCell_GET (C 함수)

PyCell_Get (C 함수)

PyCell_New (C 함수)

PyCell_SET (C 함수)

PyCell_Set (C 함수)

PyCell_Type (C 변수)

PyCellObject (C 데이터 형식)

PyCFunction (C 데이터 형식)

PyCFunctionWithKeywords (C 데이터 형식)

PycInvalidationMode (py_compile 클래스)

pyclbr (모듈)

PyCode_Check (C 함수)

PyCode_GetNumFree (C 함수)

PyCode_New (C 함수)

PyCode_NewEmpty (C 함수)

PyCode_Type (C 변수)

PyCodec_BackslashReplaceErrors (C 함수)

PyCodec_Decode (C 함수)

PyCodec_Decoder (C 함수)

PyCodec_Encode (C 함수)

PyCodec_Encoder (C 함수)

PyCodec_IgnoreErrors (C 함수)

PyCodec_IncrementalDecoder (C 함수)

PyCodec_IncrementalEncoder (C 함수)

PyCodec_KnownEncoding (C 함수)

PyCodec_LookupError (C 함수)

PyCodec_NameReplaceErrors (C 함수)

PyCodec_Register (C 함수)

PyCodec_RegisterError (C 함수)

PyCodec_ReplaceErrors (C 함수)

PyCodec_StreamReader (C 함수)

PyCodec_StreamWriter (C 함수)

PyCodec_StrictErrors (C 함수)

PyCodec_XMLCharRefReplaceErrors (C 함수)

PyCodeObject (C 데이터 형식)

PyCompactUnicodeObject (C 데이터 형식)

PyCompileError

PyCompilerFlags (C 데이터 형식)

PyComplex_AsCComplex (C 함수)

PyComplex_Check (C 함수)

PyComplex_CheckExact (C 함수)

PyComplex_FromCComplex (C 함수)

PyComplex_FromDoubles (C 함수)

PyComplex_ImagAsDouble (C 함수)

PyComplex_RealAsDouble (C 함수)

PyComplex_Type (C 변수)

PyComplexObject (C 데이터 형식)

PyContext (C 데이터 형식)

PyContext_CheckExact (C 함수)

PyContext_ClearFreeList (C 함수)

PyContext_Copy (C 함수)

PyContext_CopyCurrent (C 함수)

PyContext_Enter (C 함수)

PyContext_Exit (C 함수)

PyContext_New (C 함수)

PyContext_Type (C 변수)

PyContextToken (C 데이터 형식)

PyContextToken_CheckExact (C 함수)

PyContextToken_Type (C 변수)

PyContextVar (C 데이터 형식)

PyContextVar_CheckExact (C 함수)

PyContextVar_Get (C 함수)

PyContextVar_New (C 함수)

PyContextVar_Reset (C 함수)

PyContextVar_Set (C 함수)

PyContextVar_Type (C 변수)

PyCoro_CheckExact (C 함수)

PyCoro_New (C 함수)

PyCoro_Type (C 변수)

PyCoroObject (C 데이터 형식)

PyDate_Check (C 함수)

PyDate_CheckExact (C 함수)

PyDate_FromDate (C 함수)

PyDate_FromTimestamp (C 함수)

PyDateTime_Check (C 함수)

PyDateTime_CheckExact (C 함수)

PyDateTime_DATE_GET_FOLD (C 함수)

PyDateTime_DATE_GET_HOUR (C 함수)

PyDateTime_DATE_GET_MICROSECOND (C 함수)

PyDateTime_DATE_GET_MINUTE (C 함수)

PyDateTime_DATE_GET_SECOND (C 함수)

PyDateTime_DELTA_GET_DAYS (C 함수)

PyDateTime_DELTA_GET_MICROSECONDS (C 함수)

PyDateTime_DELTA_GET_SECONDS (C 함수)

PyDateTime_FromDateAndTime (C 함수)

PyDateTime_FromDateAndTimeAndFold (C 함수)

PyDateTime_FromTimestamp (C 함수)

PyDateTime_GET_DAY (C 함수)

PyDateTime_GET_MONTH (C 함수)

PyDateTime_GET_YEAR (C 함수)

PyDateTime_TIME_GET_FOLD (C 함수)

PyDateTime_TIME_GET_HOUR (C 함수)

PyDateTime_TIME_GET_MICROSECOND (C 함수)

PyDateTime_TIME_GET_MINUTE (C 함수)

PyDateTime_TIME_GET_SECOND (C 함수)

PyDateTime_TimeZone_UTC (C 변수)

PyDelta_Check (C 함수)

PyDelta_CheckExact (C 함수)

PyDelta_FromDSU (C 함수)

PyDescr_IsData (C 함수)

PyDescr_NewClassMethod (C 함수)

PyDescr_NewGetSet (C 함수)

PyDescr_NewMember (C 함수)

PyDescr_NewMethod (C 함수)

PyDescr_NewWrapper (C 함수)

PyDict_Check (C 함수)

PyDict_CheckExact (C 함수)

PyDict_Clear (C 함수)

PyDict_ClearFreeList (C 함수)

PyDict_Contains (C 함수)

PyDict_Copy (C 함수)

PyDict_DelItem (C 함수)

PyDict_DelItemString (C 함수)

PyDict_GetItem (C 함수)

PyDict_GetItemString (C 함수)

PyDict_GetItemWithError (C 함수)

PyDict_Items (C 함수)

PyDict_Keys (C 함수)

PyDict_Merge (C 함수)

PyDict_MergeFromSeq2 (C 함수)

PyDict_New (C 함수)

PyDict_Next (C 함수)

PyDict_SetDefault (C 함수)

PyDict_SetItem (C 함수)

PyDict_SetItemString (C 함수)

PyDict_Size (C 함수)

PyDict_Type (C 변수)

PyDict_Update (C 함수)

PyDict_Values (C 함수)

PyDictObject (C 데이터 형식)

PyDictProxy_New (C 함수)

PyDLL (ctypes 클래스)

pydoc (모듈)

PyDoc_STR (C 매크로)

PyDoc_STRVAR (C 매크로)

PyErr_BadArgument (C 함수)

PyErr_BadInternalCall (C 함수)

PyErr_CheckSignals (C 함수)

PyErr_Clear (C 함수)

PyErr_Clear(), [1]

PyErr_ExceptionMatches (C 함수)

PyErr_ExceptionMatches()

PyErr_Fetch (C 함수)

PyErr_Fetch()

PyErr_Format (C 함수)

PyErr_FormatV (C 함수)

PyErr_GetExcInfo (C 함수)

PyErr_GivenExceptionMatches (C 함수)

PyErr_NewException (C 함수)

PyErr_NewExceptionWithDoc (C 함수)

PyErr_NoMemory (C 함수)

PyErr_NormalizeException (C 함수)

PyErr_Occurred (C 함수)

PyErr_Occurred()

PyErr_Print (C 함수)

PyErr_PrintEx (C 함수)

PyErr_ResourceWarning (C 함수)

PyErr_Restore (C 함수)

PyErr_Restore()

PyErr_SetExcFromWindowsErr (C 함수)

PyErr_SetExcFromWindowsErrWithFilename (C 함수)

PyErr_SetExcFromWindowsErrWithFilenameObject (C 함수)

PyErr_SetExcFromWindowsErrWithFilenameObjects (C 함수)

PyErr_SetExcInfo (C 함수)

PyErr_SetFromErrno (C 함수)

PyErr_SetFromErrnoWithFilename (C 함수)

PyErr_SetFromErrnoWithFilenameObject (C 함수)

PyErr_SetFromErrnoWithFilenameObjects (C 함수)

PyErr_SetFromWindowsErr (C 함수)

PyErr_SetFromWindowsErrWithFilename (C 함수)

PyErr_SetImportError (C 함수)

PyErr_SetImportErrorSubclass (C 함수)

PyErr_SetInterrupt (C 함수)

PyErr_SetNone (C 함수)

PyErr_SetObject (C 함수)

PyErr_SetString (C 함수)

PyErr_SetString()

PyErr_SyntaxLocation (C 함수)

PyErr_SyntaxLocationEx (C 함수)

PyErr_SyntaxLocationObject (C 함수)

PyErr_WarnEx (C 함수)

PyErr_WarnExplicit (C 함수)

PyErr_WarnExplicitObject (C 함수)

PyErr_WarnFormat (C 함수)

PyErr_WriteUnraisable (C 함수)

PyEval_AcquireLock (C 함수)

PyEval_AcquireThread (C 함수)

PyEval_AcquireThread()

PyEval_EvalCode (C 함수)

PyEval_EvalCodeEx (C 함수)

PyEval_EvalFrame (C 함수)

PyEval_EvalFrameEx (C 함수)

PyEval_GetBuiltins (C 함수)

PyEval_GetFrame (C 함수)

PyEval_GetFuncDesc (C 함수)

PyEval_GetFuncName (C 함수)

PyEval_GetGlobals (C 함수)

PyEval_GetLocals (C 함수)

PyEval_InitThreads (C 함수)

PyEval_InitThreads()

PyEval_MergeCompilerFlags (C 함수)

PyEval_ReInitThreads (C 함수)

PyEval_ReleaseLock (C 함수)

PyEval_ReleaseThread (C 함수)

PyEval_ReleaseThread()

PyEval_RestoreThread (C 함수)

PyEval_RestoreThread(), [1]

PyEval_SaveThread (C 함수)

PyEval_SaveThread(), [1]

PyEval_SetProfile (C 함수)

PyEval_SetTrace (C 함수)

PyEval_ThreadsInitialized (C 함수)

PyExc_ArithmeticError

PyExc_AssertionError

PyExc_AttributeError

PyExc_BaseException

PyExc_BlockingIOError

PyExc_BrokenPipeError

PyExc_BufferError

PyExc_BytesWarning

PyExc_ChildProcessError

PyExc_ConnectionAbortedError

PyExc_ConnectionError

PyExc_ConnectionRefusedError

PyExc_ConnectionResetError

PyExc_DeprecationWarning

PyExc_EnvironmentError

PyExc_EOFError

PyExc_Exception

PyExc_FileExistsError

PyExc_FileNotFoundError

PyExc_FloatingPointError

PyExc_FutureWarning

PyExc_GeneratorExit

PyExc_ImportError

PyExc_ImportWarning

PyExc_IndentationError

PyExc_IndexError

PyExc_InterruptedError

PyExc_IOError

PyExc_IsADirectoryError

PyExc_KeyboardInterrupt

PyExc_KeyError

PyExc_LookupError

PyExc_MemoryError

PyExc_ModuleNotFoundError

PyExc_NameError

PyExc_NotADirectoryError

PyExc_NotImplementedError

PyExc_OSError

PyExc_OverflowError

PyExc_PendingDeprecationWarning

PyExc_PermissionError

PyExc_ProcessLookupError

PyExc_RecursionError

PyExc_ReferenceError

PyExc_ResourceWarning

PyExc_RuntimeError

PyExc_RuntimeWarning

PyExc_StopAsyncIteration

PyExc_StopIteration

PyExc_SyntaxError

PyExc_SyntaxWarning

PyExc_SystemError

PyExc_SystemExit

PyExc_TabError

PyExc_TimeoutError

PyExc_TypeError

PyExc_UnboundLocalError

PyExc_UnicodeDecodeError

PyExc_UnicodeEncodeError

PyExc_UnicodeError

PyExc_UnicodeTranslateError

PyExc_UnicodeWarning

PyExc_UserWarning

PyExc_ValueError

PyExc_Warning

PyExc_WindowsError

PyExc_ZeroDivisionError

PyException_GetCause (C 함수)

PyException_GetContext (C 함수)

PyException_GetTraceback (C 함수)

PyException_SetCause (C 함수)

PyException_SetContext (C 함수)

PyException_SetTraceback (C 함수)

pyexpat

모듈

PyFile_FromFd (C 함수)

PyFile_GetLine (C 함수)

PyFile_WriteObject (C 함수)

PyFile_WriteString (C 함수)

PyFloat_AS_DOUBLE (C 함수)

PyFloat_AsDouble (C 함수)

PyFloat_Check (C 함수)

PyFloat_CheckExact (C 함수)

PyFloat_ClearFreeList (C 함수)

PyFloat_FromDouble (C 함수)

PyFloat_FromString (C 함수)

PyFloat_GetInfo (C 함수)

PyFloat_GetMax (C 함수)

PyFloat_GetMin (C 함수)

PyFloat_Type (C 변수)

PyFloatObject (C 데이터 형식)

PyFrame_GetLineNumber (C 함수)

PyFrameObject (C 데이터 형식)

PyFrozenSet_Check (C 함수)

PyFrozenSet_CheckExact (C 함수)

PyFrozenSet_New (C 함수)

PyFrozenSet_Type (C 변수)

PyFunction_Check (C 함수)

PyFunction_GetAnnotations (C 함수)

PyFunction_GetClosure (C 함수)

PyFunction_GetCode (C 함수)

PyFunction_GetDefaults (C 함수)

PyFunction_GetGlobals (C 함수)

PyFunction_GetModule (C 함수)

PyFunction_New (C 함수)

PyFunction_NewWithQualName (C 함수)

PyFunction_SetAnnotations (C 함수)

PyFunction_SetClosure (C 함수)

PyFunction_SetDefaults (C 함수)

PyFunction_Type (C 변수)

PyFunctionObject (C 데이터 형식)

PYFUNCTYPE() (ctypes 모듈)

PyGen_Check (C 함수)

PyGen_CheckExact (C 함수)

PyGen_New (C 함수)

PyGen_NewWithQualName (C 함수)

PyGen_Type (C 변수)

PyGenObject (C 데이터 형식)

PyGetSetDef (C 데이터 형식)

PyGILState_Check (C 함수)

PyGILState_Ensure (C 함수)

PyGILState_GetThisThreadState (C 함수)

PyGILState_Release (C 함수)

PyImport_AddModule (C 함수)

PyImport_AddModuleObject (C 함수)

PyImport_AppendInittab (C 함수)

PyImport_Cleanup (C 함수)

PyImport_ExecCodeModule (C 함수)

PyImport_ExecCodeModuleEx (C 함수)

PyImport_ExecCodeModuleObject (C 함수)

PyImport_ExecCodeModuleWithPathnames (C 함수)

PyImport_ExtendInittab (C 함수)

PyImport_FrozenModules (C 변수)

PyImport_GetImporter (C 함수)

PyImport_GetMagicNumber (C 함수)

PyImport_GetMagicTag (C 함수)

PyImport_GetModule (C 함수)

PyImport_GetModuleDict (C 함수)

PyImport_Import (C 함수)

PyImport_ImportFrozenModule (C 함수)

PyImport_ImportFrozenModuleObject (C 함수)

PyImport_ImportModule (C 함수)

PyImport_ImportModuleEx (C 함수)

PyImport_ImportModuleLevel (C 함수)

PyImport_ImportModuleLevelObject (C 함수)

PyImport_ImportModuleNoBlock (C 함수)

PyImport_ReloadModule (C 함수)

PyIndex_Check (C 함수)

PyInit_modulename (C 함수)

PyInstanceMethod_Check (C 함수)

PyInstanceMethod_Function (C 함수)

PyInstanceMethod_GET_FUNCTION (C 함수)

PyInstanceMethod_New (C 함수)

PyInstanceMethod_Type (C 변수)

PyInterpreterState (C 데이터 형식)

PyInterpreterState_Clear (C 함수)

PyInterpreterState_Delete (C 함수)

PyInterpreterState_GetID (C 함수)

PyInterpreterState_Head (C 함수)

PyInterpreterState_Main (C 함수)

PyInterpreterState_New (C 함수)

PyInterpreterState_Next (C 함수)

PyInterpreterState_ThreadHead (C 함수)

PyIter_Check (C 함수)

PyIter_Next (C 함수)

PyList_Append (C 함수)

PyList_AsTuple (C 함수)

PyList_Check (C 함수)

PyList_CheckExact (C 함수)

PyList_ClearFreeList (C 함수)

PyList_GET_ITEM (C 함수)

PyList_GET_SIZE (C 함수)

PyList_GetItem (C 함수)

PyList_GetItem()

PyList_GetSlice (C 함수)

PyList_Insert (C 함수)

PyList_New (C 함수)

PyList_Reverse (C 함수)

PyList_SET_ITEM (C 함수)

PyList_SetItem (C 함수)

PyList_SetItem()

PyList_SetSlice (C 함수)

PyList_Size (C 함수)

PyList_Sort (C 함수)

PyList_Type (C 변수)

PyListObject (C 데이터 형식)

PyLong_AsDouble (C 함수)

PyLong_AsLong (C 함수)

PyLong_AsLongAndOverflow (C 함수)

PyLong_AsLongLong (C 함수)

PyLong_AsLongLongAndOverflow (C 함수)

PyLong_AsSize_t (C 함수)

PyLong_AsSsize_t (C 함수)

PyLong_AsUnsignedLong (C 함수)

PyLong_AsUnsignedLongLong (C 함수)

PyLong_AsUnsignedLongLongMask (C 함수)

PyLong_AsUnsignedLongMask (C 함수)

PyLong_AsVoidPtr (C 함수)

PyLong_Check (C 함수)

PyLong_CheckExact (C 함수)

PyLong_FromDouble (C 함수)

PyLong_FromLong (C 함수)

PyLong_FromLongLong (C 함수)

PyLong_FromSize_t (C 함수)

PyLong_FromSsize_t (C 함수)

PyLong_FromString (C 함수)

PyLong_FromUnicode (C 함수)

PyLong_FromUnicodeObject (C 함수)

PyLong_FromUnsignedLong (C 함수)

PyLong_FromUnsignedLongLong (C 함수)

PyLong_FromVoidPtr (C 함수)

PyLong_Type (C 변수)

PyLongObject (C 데이터 형식)

PyMapping_Check (C 함수)

PyMapping_DelItem (C 함수)

PyMapping_DelItemString (C 함수)

PyMapping_GetItemString (C 함수)

PyMapping_HasKey (C 함수)

PyMapping_HasKeyString (C 함수)

PyMapping_Items (C 함수)

PyMapping_Keys (C 함수)

PyMapping_Length (C 함수)

PyMapping_SetItemString (C 함수)

PyMapping_Size (C 함수)

PyMapping_Values (C 함수)

PyMappingMethods (C 데이터 형식)

PyMappingMethods.mp_ass_subscript (C 멤버 변수)

PyMappingMethods.mp_length (C 멤버 변수)

PyMappingMethods.mp_subscript (C 멤버 변수)

PyMarshal_ReadLastObjectFromFile (C 함수)

PyMarshal_ReadLongFromFile (C 함수)

PyMarshal_ReadObjectFromFile (C 함수)

PyMarshal_ReadObjectFromString (C 함수)

PyMarshal_ReadShortFromFile (C 함수)

PyMarshal_WriteLongToFile (C 함수)

PyMarshal_WriteObjectToFile (C 함수)

PyMarshal_WriteObjectToString (C 함수)

PyMem_Calloc (C 함수)

PyMem_Del (C 함수)

PYMEM_DOMAIN_MEM (C 변수)

PYMEM_DOMAIN_OBJ (C 변수)

PYMEM_DOMAIN_RAW (C 변수)

PyMem_Free (C 함수)

PyMem_GetAllocator (C 함수)

PyMem_Malloc (C 함수)

PyMem_New (C 함수)

PyMem_RawCalloc (C 함수)

PyMem_RawFree (C 함수)

PyMem_RawMalloc (C 함수)

PyMem_RawRealloc (C 함수)

PyMem_Realloc (C 함수)

PyMem_Resize (C 함수)

PyMem_SetAllocator (C 함수)

PyMem_SetupDebugHooks (C 함수)

PyMemAllocatorDomain (C 데이터 형식)

PyMemAllocatorEx (C 데이터 형식)

PyMemberDef (C 데이터 형식)

PyMemoryView_Check (C 함수)

PyMemoryView_FromBuffer (C 함수)

PyMemoryView_FromMemory (C 함수)

PyMemoryView_FromObject (C 함수)

PyMemoryView_GET_BASE (C 함수)

PyMemoryView_GET_BUFFER (C 함수)

PyMemoryView_GetContiguous (C 함수)

PyMethod_Check (C 함수)

PyMethod_ClearFreeList (C 함수)

PyMethod_Function (C 함수)

PyMethod_GET_FUNCTION (C 함수)

PyMethod_GET_SELF (C 함수)

PyMethod_New (C 함수)

PyMethod_Self (C 함수)

PyMethod_Type (C 변수)

PyMethodDef (C 데이터 형식)

PyModule_AddFunctions (C 함수)

PyModule_AddIntConstant (C 함수)

PyModule_AddIntMacro (C 함수)

PyModule_AddObject (C 함수)

PyModule_AddStringConstant (C 함수)

PyModule_AddStringMacro (C 함수)

PyModule_Check (C 함수)

PyModule_CheckExact (C 함수)

PyModule_Create (C 함수)

PyModule_Create2 (C 함수)

PyModule_ExecDef (C 함수)

PyModule_FromDefAndSpec (C 함수)

PyModule_FromDefAndSpec2 (C 함수)

PyModule_GetDef (C 함수)

PyModule_GetDict (C 함수)

PyModule_GetFilename (C 함수)

PyModule_GetFilenameObject (C 함수)

PyModule_GetName (C 함수)

PyModule_GetNameObject (C 함수)

PyModule_GetState (C 함수)

PyModule_New (C 함수)

PyModule_NewObject (C 함수)

PyModule_SetDocString (C 함수)

PyModule_Type (C 변수)

PyModuleDef (C 데이터 형식)

PyModuleDef.m_base (C 멤버 변수)

PyModuleDef.m_clear (C 멤버 변수)

PyModuleDef.m_doc (C 멤버 변수)

PyModuleDef.m_free (C 멤버 변수)

PyModuleDef.m_methods (C 멤버 변수)

PyModuleDef.m_name (C 멤버 변수)

PyModuleDef.m_reload (C 멤버 변수)

PyModuleDef.m_size (C 멤버 변수)

PyModuleDef.m_slots (C 멤버 변수)

PyModuleDef.m_traverse (C 멤버 변수)

PyModuleDef_Init (C 함수)

PyModuleDef_Slot (C 데이터 형식)

PyModuleDef_Slot.slot (C 멤버 변수)

PyModuleDef_Slot.value (C 멤버 변수)

PyNumber_Absolute (C 함수)

PyNumber_Add (C 함수)

PyNumber_And (C 함수)

PyNumber_AsSsize_t (C 함수)

PyNumber_Check (C 함수)

PyNumber_Divmod (C 함수)

PyNumber_Float (C 함수)

PyNumber_FloorDivide (C 함수)

PyNumber_Index (C 함수)

PyNumber_InPlaceAdd (C 함수)

PyNumber_InPlaceAnd (C 함수)

PyNumber_InPlaceFloorDivide (C 함수)

PyNumber_InPlaceLshift (C 함수)

PyNumber_InPlaceMatrixMultiply (C 함수)

PyNumber_InPlaceMultiply (C 함수)

PyNumber_InPlaceOr (C 함수)

PyNumber_InPlacePower (C 함수)

PyNumber_InPlaceRemainder (C 함수)

PyNumber_InPlaceRshift (C 함수)

PyNumber_InPlaceSubtract (C 함수)

PyNumber_InPlaceTrueDivide (C 함수)

PyNumber_InPlaceXor (C 함수)

PyNumber_Invert (C 함수)

PyNumber_Long (C 함수)

PyNumber_Lshift (C 함수)

PyNumber_MatrixMultiply (C 함수)

PyNumber_Multiply (C 함수)

PyNumber_Negative (C 함수)

PyNumber_Or (C 함수)

PyNumber_Positive (C 함수)

PyNumber_Power (C 함수)

PyNumber_Remainder (C 함수)

PyNumber_Rshift (C 함수)

PyNumber_Subtract (C 함수)

PyNumber_ToBase (C 함수)

PyNumber_TrueDivide (C 함수)

PyNumber_Xor (C 함수)

PyNumberMethods (C 데이터 형식)

PyObject (C 데이터 형식)

PyObject._ob_next (C 멤버 변수)

PyObject._ob_prev (C 멤버 변수)

PyObject.ob_refcnt (C 멤버 변수)

PyObject.ob_type (C 멤버 변수)

PyObject_AsCharBuffer (C 함수)

PyObject_ASCII (C 함수)

PyObject_AsFileDescriptor (C 함수)

PyObject_AsReadBuffer (C 함수)

PyObject_AsWriteBuffer (C 함수)

PyObject_Bytes (C 함수)

PyObject_Call (C 함수)

PyObject_CallFunction (C 함수)

PyObject_CallFunctionObjArgs (C 함수)

PyObject_CallMethod (C 함수)

PyObject_CallMethodObjArgs (C 함수)

PyObject_CallObject (C 함수)

PyObject_CallObject()

PyObject_Calloc (C 함수)

PyObject_CheckBuffer (C 함수)

PyObject_CheckReadBuffer (C 함수)

PyObject_Del (C 함수)

PyObject_DelAttr (C 함수)

PyObject_DelAttrString (C 함수)

PyObject_DelItem (C 함수)

PyObject_Dir (C 함수)

PyObject_Free (C 함수)

PyObject_GC_Del (C 함수)

PyObject_GC_New (C 함수)

PyObject_GC_NewVar (C 함수)

PyObject_GC_Resize (C 함수)

PyObject_GC_Track (C 함수)

PyObject_GC_UnTrack (C 함수)

PyObject_GenericGetAttr (C 함수)

PyObject_GenericGetDict (C 함수)

PyObject_GenericSetAttr (C 함수)

PyObject_GenericSetDict (C 함수)

PyObject_GetArenaAllocator (C 함수)

PyObject_GetAttr (C 함수)

PyObject_GetAttrString (C 함수)

PyObject_GetBuffer (C 함수)

PyObject_GetItem (C 함수)

PyObject_GetIter (C 함수)

PyObject_HasAttr (C 함수)

PyObject_HasAttrString (C 함수)

PyObject_Hash (C 함수)

PyObject_HashNotImplemented (C 함수)

PyObject_HEAD (C 매크로)

PyObject_HEAD_INIT (C 매크로)

PyObject_Init (C 함수)

PyObject_InitVar (C 함수)

PyObject_IsInstance (C 함수)

PyObject_IsSubclass (C 함수)

PyObject_IsTrue (C 함수)

PyObject_Length (C 함수)

PyObject_LengthHint (C 함수)

PyObject_Malloc (C 함수)

PyObject_New (C 함수)

PyObject_NewVar (C 함수)

PyObject_Not (C 함수)

PyObject_Print (C 함수)

PyObject_Realloc (C 함수)

PyObject_Repr (C 함수)

PyObject_RichCompare (C 함수)

PyObject_RichCompareBool (C 함수)

PyObject_SetArenaAllocator (C 함수)

PyObject_SetAttr (C 함수)

PyObject_SetAttrString (C 함수)

PyObject_SetItem (C 함수)

PyObject_Size (C 함수)

PyObject_Str (C 함수)

PyObject_Type (C 함수)

PyObject_TypeCheck (C 함수)

PyObject_VAR_HEAD (C 매크로)

PyObjectArenaAllocator (C 데이터 형식)

PyOS_AfterFork (C 함수)

PyOS_AfterFork_Child (C 함수)

PyOS_AfterFork_Parent (C 함수)

PyOS_BeforeFork (C 함수)

PyOS_CheckStack (C 함수)

PyOS_double_to_string (C 함수)

PyOS_FSPath (C 함수)

PyOS_getsig (C 함수)

PyOS_InputHook (C 변수)

PyOS_ReadlineFunctionPointer (C 변수)

PyOS_setsig (C 함수)

PyOS_snprintf (C 함수)

PyOS_stricmp (C 함수)

PyOS_string_to_double (C 함수)

PyOS_strnicmp (C 함수)

PyOS_vsnprintf (C 함수)

PyParser_SimpleParseFile (C 함수)

PyParser_SimpleParseFileFlags (C 함수)

PyParser_SimpleParseString (C 함수)

PyParser_SimpleParseStringFlags (C 함수)

PyParser_SimpleParseStringFlagsFilename (C 함수)

PyPI

(see Python Package Index (PyPI))

PyProperty_Type (C 변수)

PyRun_AnyFile (C 함수)

PyRun_AnyFileEx (C 함수)

PyRun_AnyFileExFlags (C 함수)

PyRun_AnyFileFlags (C 함수)

PyRun_File (C 함수)

PyRun_FileEx (C 함수)

PyRun_FileExFlags (C 함수)

PyRun_FileFlags (C 함수)

PyRun_InteractiveLoop (C 함수)

PyRun_InteractiveLoopFlags (C 함수)

PyRun_InteractiveOne (C 함수)

PyRun_InteractiveOneFlags (C 함수)

PyRun_SimpleFile (C 함수)

PyRun_SimpleFileEx (C 함수)

PyRun_SimpleFileExFlags (C 함수)

PyRun_SimpleString (C 함수)

PyRun_SimpleStringFlags (C 함수)

PyRun_String (C 함수)

PyRun_StringFlags (C 함수)

PySeqIter_Check (C 함수)

PySeqIter_New (C 함수)

PySeqIter_Type (C 변수)

PySequence_Check (C 함수)

PySequence_Concat (C 함수)

PySequence_Contains (C 함수)

PySequence_Count (C 함수)

PySequence_DelItem (C 함수)

PySequence_DelSlice (C 함수)

PySequence_Fast (C 함수)

PySequence_Fast_GET_ITEM (C 함수)

PySequence_Fast_GET_SIZE (C 함수)

PySequence_Fast_ITEMS (C 함수)

PySequence_GetItem (C 함수)

PySequence_GetItem()

PySequence_GetSlice (C 함수)

PySequence_Index (C 함수)

PySequence_InPlaceConcat (C 함수)

PySequence_InPlaceRepeat (C 함수)

PySequence_ITEM (C 함수)

PySequence_Length (C 함수)

PySequence_List (C 함수)

PySequence_Repeat (C 함수)

PySequence_SetItem (C 함수)

PySequence_SetSlice (C 함수)

PySequence_Size (C 함수)

PySequence_Tuple (C 함수)

PySequenceMethods (C 데이터 형식)

PySequenceMethods.sq_ass_item (C 멤버 변수)

PySequenceMethods.sq_concat (C 멤버 변수)

PySequenceMethods.sq_contains (C 멤버 변수)

PySequenceMethods.sq_inplace_concat (C 멤버 변수)

PySequenceMethods.sq_inplace_repeat (C 멤버 변수)

PySequenceMethods.sq_item (C 멤버 변수)

PySequenceMethods.sq_length (C 멤버 변수)

PySequenceMethods.sq_repeat (C 멤버 변수)

PySet_Add (C 함수)

PySet_Check (C 함수)

PySet_Clear (C 함수)

PySet_ClearFreeList (C 함수)

PySet_Contains (C 함수)

PySet_Discard (C 함수)

PySet_GET_SIZE (C 함수)

PySet_New (C 함수)

PySet_Pop (C 함수)

PySet_Size (C 함수)

PySet_Type (C 변수)

PySetObject (C 데이터 형식)

PySignal_SetWakeupFd (C 함수)

PySlice_AdjustIndices (C 함수)

PySlice_Check (C 함수)

PySlice_GetIndices (C 함수)

PySlice_GetIndicesEx (C 함수)

PySlice_New (C 함수)

PySlice_Type (C 변수)

PySlice_Unpack (C 함수)

PyState_AddModule (C 함수)

PyState_FindModule (C 함수)

PyState_RemoveModule (C 함수)

PyStructSequence_Desc (C 데이터 형식)

PyStructSequence_Field (C 데이터 형식)

PyStructSequence_GET_ITEM (C 함수)

PyStructSequence_GetItem (C 함수)

PyStructSequence_InitType (C 함수)

PyStructSequence_InitType2 (C 함수)

PyStructSequence_New (C 함수)

PyStructSequence_NewType (C 함수)

PyStructSequence_SET_ITEM (C 함수)

PyStructSequence_SetItem (C 함수)

PyStructSequence_UnnamedField (C 변수)

PySys_AddWarnOption (C 함수)

PySys_AddWarnOptionUnicode (C 함수)

PySys_AddXOption (C 함수)

PySys_FormatStderr (C 함수)

PySys_FormatStdout (C 함수)

PySys_GetObject (C 함수)

PySys_GetXOptions (C 함수)

PySys_ResetWarnOptions (C 함수)

PySys_SetArgv (C 함수)

PySys_SetArgv()

PySys_SetArgvEx (C 함수)

PySys_SetArgvEx(), [1]

PySys_SetObject (C 함수)

PySys_SetPath (C 함수)

PySys_WriteStderr (C 함수)

PySys_WriteStdout (C 함수)

Python 3000 (파이썬 3000)

Python Editor

Python Package Index (PyPI)

PYTHON*, [1], [2], [3], [4], [5]

python.function.entry (C 함수)

python.function.return (C 함수)

python_branch() (platform 모듈)

python_build() (platform 모듈)

python_compiler() (platform 모듈)

PYTHON_DOM

python_implementation() (platform 모듈)

python_is_optimized() (test.support 모듈)

python_revision() (platform 모듈)

python_version() (platform 모듈)

python_version_tuple() (platform 모듈)

PYTHONASYNCIODEBUG, [1]

PYTHONBREAKPOINT, [1], [2], [3]

PYTHONCASEOK

PYTHONCOERCECLOCALE, [1]

PYTHONDEBUG, [1]

PYTHONDEVMODE, [1]

PYTHONDOCS

PYTHONDONTWRITEBYTECODE, [1], [2], [3], [4], [5]

PYTHONDUMPREFS

PYTHONFAULTHANDLER, [1]

PYTHONHASHSEED, [1], [2], [3], [4], [5], [6], [7], [8]

PYTHONHOME, [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12], [13], [14], [15]

Pythonic (파이썬다운)

PYTHONINSPECT, [1], [2]

PYTHONINTMAXSTRDIGITS, [1], [2], [3], [4]

PYTHONIOENCODING, [1], [2], [3], [4], [5], [6]

PYTHONLEGACYWINDOWSFSENCODING, [1], [2]

PYTHONLEGACYWINDOWSSTDIO, [1], [2], [3]

PYTHONMALLOC, [1], [2], [3], [4], [5], [6]

PYTHONMALLOCSTATS, [1]

PYTHONNOUSERSITE, [1], [2], [3]

PYTHONOPTIMIZE, [1]

PYTHONPATH, [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12], [13], [14], [15], [16], [17], [18], [19], [20], [21], [22], [23], [24]

PYTHONPROFILEIMPORTTIME, [1], [2]

PYTHONSHOWALLOCCOUNT

PYTHONSHOWREFCOUNT

PYTHONSTARTUP, [1], [2], [3], [4], [5], [6], [7], [8], [9]

PYTHONTRACEMALLOC, [1], [2]

PYTHONUNBUFFERED, [1]

PYTHONUSERBASE, [1], [2]

PYTHONUSERSITE

PYTHONUTF8, [1], [2], [3], [4]

PYTHONVERBOSE, [1]

PYTHONWARNINGS, [1], [2], [3], [4], [5], [6], [7]

PyThread_create_key (C 함수)

PyThread_delete_key (C 함수)

PyThread_delete_key_value (C 함수)

PyThread_get_key_value (C 함수)

PyThread_ReInitTLS (C 함수)

PyThread_set_key_value (C 함수)

PyThread_tss_alloc (C 함수)

PyThread_tss_create (C 함수)

PyThread_tss_delete (C 함수)

PyThread_tss_free (C 함수)

PyThread_tss_get (C 함수)

PyThread_tss_is_created (C 함수)

PyThread_tss_set (C 함수)

PyThreadState, [1]

(C 데이터 형식)

PyThreadState_Clear (C 함수)

PyThreadState_Delete (C 함수)

PyThreadState_Get (C 함수)

PyThreadState_GetDict (C 함수)

PyThreadState_New (C 함수)

PyThreadState_Next (C 함수)

PyThreadState_SetAsyncExc (C 함수)

PyThreadState_Swap (C 함수)

PyTime_Check (C 함수)

PyTime_CheckExact (C 함수)

PyTime_FromTime (C 함수)

PyTime_FromTimeAndFold (C 함수)

PyTimeZone_FromOffset (C 함수)

PyTimeZone_FromOffsetAndName (C 함수)

PyTrace_C_CALL (C 변수)

PyTrace_C_EXCEPTION (C 변수)

PyTrace_C_RETURN (C 변수)

PyTrace_CALL (C 변수)

PyTrace_EXCEPTION (C 변수)

PyTrace_LINE (C 변수)

PyTrace_OPCODE (C 변수)

PyTrace_RETURN (C 변수)

PyTraceMalloc_Track (C 함수)

PyTraceMalloc_Untrack (C 함수)

PyTuple_Check (C 함수)

PyTuple_CheckExact (C 함수)

PyTuple_ClearFreeList (C 함수)

PyTuple_GET_ITEM (C 함수)

PyTuple_GET_SIZE (C 함수)

PyTuple_GetItem (C 함수)

PyTuple_GetSlice (C 함수)

PyTuple_New (C 함수)

PyTuple_Pack (C 함수)

PyTuple_SET_ITEM (C 함수)

PyTuple_SetItem (C 함수)

PyTuple_SetItem()

PyTuple_Size (C 함수)

PyTuple_Type (C 변수)

PyTupleObject (C 데이터 형식)

PyType_Check (C 함수)

PyType_CheckExact (C 함수)

PyType_ClearCache (C 함수)

PyType_FromSpec (C 함수)

PyType_FromSpecWithBases (C 함수)

PyType_GenericAlloc (C 함수)

PyType_GenericNew (C 함수)

PyType_GetFlags (C 함수)

PyType_GetSlot (C 함수)

PyType_HasFeature (C 함수)

PyType_IS_GC (C 함수)

PyType_IsSubtype (C 함수)

PyType_Modified (C 함수)

PyType_Ready (C 함수)

PyType_Type (C 변수)

PyTypeObject (C 데이터 형식)

PyTypeObject.tp_alloc (C 멤버 변수)

PyTypeObject.tp_allocs (C 멤버 변수)

PyTypeObject.tp_as_buffer (C 멤버 변수)

PyTypeObject.tp_base (C 멤버 변수)

PyTypeObject.tp_bases (C 멤버 변수)

PyTypeObject.tp_basicsize (C 멤버 변수)

PyTypeObject.tp_cache (C 멤버 변수)

PyTypeObject.tp_call (C 멤버 변수)

PyTypeObject.tp_clear (C 멤버 변수)

PyTypeObject.tp_dealloc (C 멤버 변수)

PyTypeObject.tp_descr_get (C 멤버 변수)

PyTypeObject.tp_descr_set (C 멤버 변수)

PyTypeObject.tp_dict (C 멤버 변수)

PyTypeObject.tp_dictoffset (C 멤버 변수)

PyTypeObject.tp_doc (C 멤버 변수)

PyTypeObject.tp_finalize (C 멤버 변수)

PyTypeObject.tp_flags (C 멤버 변수)

PyTypeObject.tp_free (C 멤버 변수)

PyTypeObject.tp_frees (C 멤버 변수)

PyTypeObject.tp_getattr (C 멤버 변수)

PyTypeObject.tp_getattro (C 멤버 변수)

PyTypeObject.tp_getset (C 멤버 변수)

PyTypeObject.tp_hash (C 멤버 변수)

PyTypeObject.tp_init (C 멤버 변수)

PyTypeObject.tp_is_gc (C 멤버 변수)

PyTypeObject.tp_itemsize (C 멤버 변수)

PyTypeObject.tp_iter (C 멤버 변수)

PyTypeObject.tp_iternext (C 멤버 변수)

PyTypeObject.tp_maxalloc (C 멤버 변수)

PyTypeObject.tp_members (C 멤버 변수)

PyTypeObject.tp_methods (C 멤버 변수)

PyTypeObject.tp_mro (C 멤버 변수)

PyTypeObject.tp_name (C 멤버 변수)

PyTypeObject.tp_new (C 멤버 변수)

PyTypeObject.tp_next (C 멤버 변수)

PyTypeObject.tp_print (C 멤버 변수)

PyTypeObject.tp_repr (C 멤버 변수)

PyTypeObject.tp_richcompare (C 멤버 변수)

PyTypeObject.tp_setattr (C 멤버 변수)

PyTypeObject.tp_setattro (C 멤버 변수)

PyTypeObject.tp_str (C 멤버 변수)

PyTypeObject.tp_subclasses (C 멤버 변수)

PyTypeObject.tp_traverse (C 멤버 변수)

PyTypeObject.tp_weaklist (C 멤버 변수)

PyTypeObject.tp_weaklistoffset (C 멤버 변수)

PyTZInfo_Check (C 함수)

PyTZInfo_CheckExact (C 함수)

PyUnicode_1BYTE_DATA (C 함수)

PyUnicode_1BYTE_KIND (C 매크로)

PyUnicode_2BYTE_DATA (C 함수)

PyUnicode_2BYTE_KIND (C 매크로)

PyUnicode_4BYTE_DATA (C 함수)

PyUnicode_4BYTE_KIND (C 매크로)

PyUnicode_AS_DATA (C 함수)

PyUnicode_AS_UNICODE (C 함수)

PyUnicode_AsASCIIString (C 함수)

PyUnicode_AsCharmapString (C 함수)

PyUnicode_AsEncodedString (C 함수)

PyUnicode_AsLatin1String (C 함수)

PyUnicode_AsMBCSString (C 함수)

PyUnicode_AsRawUnicodeEscapeString (C 함수)

PyUnicode_AsUCS4 (C 함수)

PyUnicode_AsUCS4Copy (C 함수)

PyUnicode_AsUnicode (C 함수)

PyUnicode_AsUnicodeAndSize (C 함수)

PyUnicode_AsUnicodeCopy (C 함수)

PyUnicode_AsUnicodeEscapeString (C 함수)

PyUnicode_AsUTF16String (C 함수)

PyUnicode_AsUTF32String (C 함수)

PyUnicode_AsUTF8 (C 함수)

PyUnicode_AsUTF8AndSize (C 함수)

PyUnicode_AsUTF8String (C 함수)

PyUnicode_AsWideChar (C 함수)

PyUnicode_AsWideCharString (C 함수)

PyUnicode_Check (C 함수)

PyUnicode_CheckExact (C 함수)

PyUnicode_ClearFreeList (C 함수)

PyUnicode_Compare (C 함수)

PyUnicode_CompareWithASCIIString (C 함수)

PyUnicode_Concat (C 함수)

PyUnicode_Contains (C 함수)

PyUnicode_CopyCharacters (C 함수)

PyUnicode_Count (C 함수)

PyUnicode_DATA (C 함수)

PyUnicode_Decode (C 함수)

PyUnicode_DecodeASCII (C 함수)

PyUnicode_DecodeCharmap (C 함수)

PyUnicode_DecodeFSDefault (C 함수)

PyUnicode_DecodeFSDefaultAndSize (C 함수)

PyUnicode_DecodeLatin1 (C 함수)

PyUnicode_DecodeLocale (C 함수)

PyUnicode_DecodeLocaleAndSize (C 함수)

PyUnicode_DecodeMBCS (C 함수)

PyUnicode_DecodeMBCSStateful (C 함수)

PyUnicode_DecodeRawUnicodeEscape (C 함수)

PyUnicode_DecodeUnicodeEscape (C 함수)

PyUnicode_DecodeUTF16 (C 함수)

PyUnicode_DecodeUTF16Stateful (C 함수)

PyUnicode_DecodeUTF32 (C 함수)

PyUnicode_DecodeUTF32Stateful (C 함수)

PyUnicode_DecodeUTF7 (C 함수)

PyUnicode_DecodeUTF7Stateful (C 함수)

PyUnicode_DecodeUTF8 (C 함수)

PyUnicode_DecodeUTF8Stateful (C 함수)

PyUnicode_Encode (C 함수)

PyUnicode_EncodeASCII (C 함수)

PyUnicode_EncodeCharmap (C 함수)

PyUnicode_EncodeCodePage (C 함수)

PyUnicode_EncodeFSDefault (C 함수)

PyUnicode_EncodeLatin1 (C 함수)

PyUnicode_EncodeLocale (C 함수)

PyUnicode_EncodeMBCS (C 함수)

PyUnicode_EncodeRawUnicodeEscape (C 함수)

PyUnicode_EncodeUnicodeEscape (C 함수)

PyUnicode_EncodeUTF16 (C 함수)

PyUnicode_EncodeUTF32 (C 함수)

PyUnicode_EncodeUTF7 (C 함수)

PyUnicode_EncodeUTF8 (C 함수)

PyUnicode_Fill (C 함수)

PyUnicode_Find (C 함수)

PyUnicode_FindChar (C 함수)

PyUnicode_Format (C 함수)

PyUnicode_FromEncodedObject (C 함수)

PyUnicode_FromFormat (C 함수)

PyUnicode_FromFormatV (C 함수)

PyUnicode_FromKindAndData (C 함수)

PyUnicode_FromObject (C 함수)

PyUnicode_FromString (C 함수)

PyUnicode_FromString()

PyUnicode_FromStringAndSize (C 함수)

PyUnicode_FromUnicode (C 함수)

PyUnicode_FromWideChar (C 함수)

PyUnicode_FSConverter (C 함수)

PyUnicode_FSDecoder (C 함수)

PyUnicode_GET_DATA_SIZE (C 함수)

PyUnicode_GET_LENGTH (C 함수)

PyUnicode_GET_SIZE (C 함수)

PyUnicode_GetLength (C 함수)

PyUnicode_GetSize (C 함수)

PyUnicode_InternFromString (C 함수)

PyUnicode_InternInPlace (C 함수)

PyUnicode_Join (C 함수)

PyUnicode_KIND (C 함수)

PyUnicode_MAX_CHAR_VALUE (C 함수)

PyUnicode_New (C 함수)

PyUnicode_READ (C 함수)

PyUnicode_READ_CHAR (C 함수)

PyUnicode_ReadChar (C 함수)

PyUnicode_READY (C 함수)

PyUnicode_Replace (C 함수)

PyUnicode_RichCompare (C 함수)

PyUnicode_Split (C 함수)

PyUnicode_Splitlines (C 함수)

PyUnicode_Substring (C 함수)

PyUnicode_Tailmatch (C 함수)

PyUnicode_TransformDecimalToASCII (C 함수)

PyUnicode_Translate (C 함수), [1]

PyUnicode_TranslateCharmap (C 함수)

PyUnicode_Type (C 변수)

PyUnicode_WCHAR_KIND (C 매크로)

PyUnicode_WRITE (C 함수)

PyUnicode_WriteChar (C 함수)

PyUnicodeDecodeError_Create (C 함수)

PyUnicodeDecodeError_GetEncoding (C 함수)

PyUnicodeDecodeError_GetEnd (C 함수)

PyUnicodeDecodeError_GetObject (C 함수)

PyUnicodeDecodeError_GetReason (C 함수)

PyUnicodeDecodeError_GetStart (C 함수)

PyUnicodeDecodeError_SetEnd (C 함수)

PyUnicodeDecodeError_SetReason (C 함수)

PyUnicodeDecodeError_SetStart (C 함수)

PyUnicodeEncodeError_Create (C 함수)

PyUnicodeEncodeError_GetEncoding (C 함수)

PyUnicodeEncodeError_GetEnd (C 함수)

PyUnicodeEncodeError_GetObject (C 함수)

PyUnicodeEncodeError_GetReason (C 함수)

PyUnicodeEncodeError_GetStart (C 함수)

PyUnicodeEncodeError_SetEnd (C 함수)

PyUnicodeEncodeError_SetReason (C 함수)

PyUnicodeEncodeError_SetStart (C 함수)

PyUnicodeObject (C 데이터 형식)

PyUnicodeTranslateError_Create (C 함수)

PyUnicodeTranslateError_GetEnd (C 함수)

PyUnicodeTranslateError_GetObject (C 함수)

PyUnicodeTranslateError_GetReason (C 함수)

PyUnicodeTranslateError_GetStart (C 함수)

PyUnicodeTranslateError_SetEnd (C 함수)

PyUnicodeTranslateError_SetReason (C 함수)

PyUnicodeTranslateError_SetStart (C 함수)

PyVarObject (C 데이터 형식)

PyVarObject.ob_size (C 멤버 변수)

PyVarObject_HEAD_INIT (C 매크로)

PyWeakref_Check (C 함수)

PyWeakref_CheckProxy (C 함수)

PyWeakref_CheckRef (C 함수)

PyWeakref_GET_OBJECT (C 함수)

PyWeakref_GetObject (C 함수)

PyWeakref_NewProxy (C 함수)

PyWeakref_NewRef (C 함수)

PyWrapper_New (C 함수)

PyZipFile (zipfile 클래스)

탐색

색인

모듈 |

Python »

3.7.17 Documentation »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

Python »

3.7.17 Documentation »

|

Index – Q

qiflush() (curses 모듈)

QName (xml.etree.ElementTree 클래스)

qsize() (asyncio.Queue 메서드)

(multiprocessing.Queue 메서드)

(queue.Queue 메서드)

(queue.SimpleQueue 메서드)

qualified name (정규화된 이름)

quantize() (decimal.Context 메서드)

(decimal.Decimal 메서드)

QueryInfoKey() (winreg 모듈)

QueryReflectionKey() (winreg 모듈)

QueryValue() (winreg 모듈)

QueryValueEx() (winreg 모듈)

Queue (asyncio 클래스)

(multiprocessing 클래스)

(queue 클래스)

queue (sched.scheduler의 속성)

(모듈)

Queue() (multiprocessing.managers.SyncManager 메서드)

QueueEmpty

QueueFull

QueueHandler (logging.handlers 클래스)

QueueListener (logging.handlers 클래스)

quick_ratio() (difflib.SequenceMatcher 메서드)

quit (pdb command)

(내장 변수)

quit() (ftplib.FTP 메서드)

(nntplib.NNTP 메서드)

(poplib.POP3 메서드)

(smtplib.SMTP 메서드)

quopri (모듈)

quote() (email.utils 모듈)

(shlex 모듈)

(urllib.parse 모듈)

QUOTE_ALL (csv 모듈)

quote_from_bytes() (urllib.parse 모듈)

QUOTE_MINIMAL (csv 모듈)

QUOTE_NONE (csv 모듈)

QUOTE_NONNUMERIC (csv 모듈)

quote_plus() (urllib.parse 모듈)

quoteattr() (xml.sax.saxutils 모듈)

quotechar (csv.Dialect의 속성)

quoted-printable

encoding

quotes (shlex.shlex의 속성)

quoting (csv.Dialect의 속성)

탐색

색인

모듈 |

Python »

3.7.17 Documentation »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

Python »

3.7.17 Documentation »

|

Index – R

r"

raw string literal

r'

raw string literal

R_OK (os 모듈)

radians() (math 모듈)

(turtle 모듈)

RadioButtonGroup (msilib 클래스)

radiogroup() (msilib.Dialog 메서드)

radix() (decimal.Context 메서드)

(decimal.Decimal 메서드)

RADIXCHAR (locale 모듈)

raise

글, [1]

raise (2to3 fixer)

raise an exception

raise_on_defect (email.policy.Policy의 속성)

RAISE_VARARGS (opcode)

raising

exception

RAND_add() (ssl 모듈)

RAND_bytes() (ssl 모듈)

RAND_egd() (ssl 모듈)

RAND_pseudo_bytes() (ssl 모듈)

RAND_status() (ssl 모듈)

randbelow() (secrets 모듈)

randbits() (secrets 모듈)

randint() (random 모듈)

Random (random 클래스)

random (모듈)

random() (random 모듈)

randrange() (random 모듈)

range

객체

내장 함수

range (내장 클래스)

RARROW (token 모듈)

ratecv() (audioop 모듈)

ratio() (difflib.SequenceMatcher 메서드)

Rational (numbers 클래스)

raw (io.BufferedIOBase의 속성)

raw string

raw() (curses 모듈)

raw_data_manager (email.contentmanager 모듈)

raw_decode() (json.JSONDecoder 메서드)

raw_input (2to3 fixer)

raw_input() (code.InteractiveConsole 메서드)

RawArray() (multiprocessing.sharedctypes 모듈)

RawConfigParser (configparser 클래스)

RawDescriptionHelpFormatter (argparse 클래스)

RawIOBase (io 클래스)

RawPen (turtle 클래스)

RawTextHelpFormatter (argparse 클래스)

RawTurtle (turtle 클래스)

RawValue() (multiprocessing.sharedctypes 모듈)

RBRACE (token 모듈)

rcpttos (smtpd.SMTPChannel의 속성)

re

모듈, [1]

re (re.Match의 속성)

(모듈)

read() (asyncio.StreamReader의 메서드)

(chunk.Chunk 메서드)

(codecs.StreamReader 메서드)

(configparser.ConfigParser 메서드)

(http.client.HTTPResponse 메서드)

(imaplib.IMAP4 메서드)

(io.BufferedIOBase 메서드)

(io.BufferedReader 메서드)

(io.RawIOBase 메서드)

(io.TextIOBase 메서드)

(mimetypes.MimeTypes 메서드)

(mmap.mmap 메서드)

(os 모듈)

(ossaudiodev.oss_audio_device 메서드)

(ssl.MemoryBIO 메서드)

(ssl.SSLSocket 메서드)

(urllib.robotparser.RobotFileParser 메서드)

(zipfile.ZipFile 메서드)

read1() (io.BufferedIOBase 메서드)

(io.BufferedReader 메서드)

(io.BytesIO 메서드)

read_all() (telnetlib.Telnet 메서드)

read_binary() (importlib.resources 모듈)

read_byte() (mmap.mmap 메서드)

read_bytes() (pathlib.Path 메서드)

read_dict() (configparser.ConfigParser 메서드)

read_eager() (telnetlib.Telnet 메서드)

read_environ() (wsgiref.handlers 모듈)

read_events() (xml.etree.ElementTree.XMLPullParser 메서드)

read_file() (configparser.ConfigParser 메서드)

read_history_file() (readline 모듈)

read_init_file() (readline 모듈)

read_lazy() (telnetlib.Telnet 메서드)

read_mime_types() (mimetypes 모듈)

READ_RESTRICTED

read_sb_data() (telnetlib.Telnet 메서드)

read_some() (telnetlib.Telnet 메서드)

read_string() (configparser.ConfigParser 메서드)

read_text() (importlib.resources 모듈)

(pathlib.Path 메서드)

read_token() (shlex.shlex 메서드)

read_until() (telnetlib.Telnet 메서드)

read_very_eager() (telnetlib.Telnet 메서드)

read_very_lazy() (telnetlib.Telnet 메서드)

read_windows_registry() (mimetypes.MimeTypes 메서드)

READABLE (tkinter 모듈)

readable() (asyncore.dispatcher 메서드)

(io.IOBase 메서드)

readall() (io.RawIOBase 메서드)

reader() (csv 모듈)

ReadError

readexactly() (asyncio.StreamReader의 메서드)

readfp() (configparser.ConfigParser 메서드)

(mimetypes.MimeTypes 메서드)

readframes() (aifc.aifc 메서드)

(sunau.AU_read 메서드)

(wave.Wave_read 메서드)

readinto() (http.client.HTTPResponse 메서드)

(io.BufferedIOBase 메서드)

(io.RawIOBase 메서드)

readinto1() (io.BufferedIOBase 메서드)

(io.BytesIO 메서드)

readline (모듈)

readline() (asyncio.StreamReader의 메서드)

(codecs.StreamReader 메서드)

(distutils.text_file.TextFile 메서드)

(imaplib.IMAP4 메서드)

(io.IOBase 메서드)

(io.TextIOBase 메서드)

(mmap.mmap 메서드)

readlines() (codecs.StreamReader 메서드)

(distutils.text_file.TextFile 메서드)

(io.IOBase 메서드)

readlink() (os 모듈)

readmodule() (pyclbr 모듈)

readmodule_ex() (pyclbr 모듈)

READONLY

readonly (memoryview의 속성)

readPlist() (plistlib 모듈)

readPlistFromBytes() (plistlib 모듈)

ReadTransport (asyncio 클래스)

readuntil() (asyncio.StreamReader의 메서드)

readv() (os 모듈)

ready() (multiprocessing.pool.AsyncResult 메서드)

Real (numbers 클래스)

real (numbers.Complex의 속성)

Real Media File Format

real_max_memuse (test.support 모듈)

real_quick_ratio() (difflib.SequenceMatcher 메서드)

realloc()

realpath() (os.path 모듈)

REALTIME_PRIORITY_CLASS (subprocess 모듈)

reap_children() (test.support 모듈)

reap_threads() (test.support 모듈)

reason (http.client.HTTPResponse의 속성)

(ssl.SSLError의 속성)

(UnicodeError의 속성)

(urllib.error.HTTPError의 속성)

(urllib.error.URLError의 속성)

reattach() (tkinter.ttk.Treeview 메서드)

rebinding

name

reccontrols() (ossaudiodev.oss_mixer_device 메서드)

received_data (smtpd.SMTPChannel의 속성)

received_lines (smtpd.SMTPChannel의 속성)

recent() (imaplib.IMAP4 메서드)

reconfigure() (io.TextIOWrapper 메서드)

record_original_stdout() (test.support 모듈)

records (unittest.TestCase의 속성)

rect() (cmath 모듈)

rectangle() (curses.textpad 모듈)

RecursionError

recursive_repr() (reprlib 모듈)

recv() (asyncore.dispatcher 메서드)

(multiprocessing.connection.Connection 메서드)

(socket.socket 메서드)

recv_bytes() (multiprocessing.connection.Connection 메서드)

recv_bytes_into() (multiprocessing.connection.Connection 메서드)

recv_into() (socket.socket 메서드)

recvfrom() (socket.socket 메서드)

recvfrom_into() (socket.socket 메서드)

recvmsg() (socket.socket 메서드)

recvmsg_into() (socket.socket 메서드)

redirect_request() (urllib.request.HTTPRedirectHandler 메서드)

redirect_stderr() (contextlib 모듈)

redirect_stdout() (contextlib 모듈)

redisplay() (readline 모듈)

redrawln() (curses.window 메서드)

redrawwin() (curses.window 메서드)

reduce (2to3 fixer)

reduce() (functools 모듈)

ref (weakref 클래스)

refcount_test() (test.support 모듈)

reference

attribute

reference count (참조 횟수)

reference counting

ReferenceError

ReferenceType (weakref 모듈)

refold_source (email.policy.EmailPolicy의 속성)

refresh() (curses.window 메서드)

REG_BINARY (winreg 모듈)

REG_DWORD (winreg 모듈)

REG_DWORD_BIG_ENDIAN (winreg 모듈)

REG_DWORD_LITTLE_ENDIAN (winreg 모듈)

REG_EXPAND_SZ (winreg 모듈)

REG_FULL_RESOURCE_DESCRIPTOR (winreg 모듈)

REG_LINK (winreg 모듈)

REG_MULTI_SZ (winreg 모듈)

REG_NONE (winreg 모듈)

REG_QWORD (winreg 모듈)

REG_QWORD_LITTLE_ENDIAN (winreg 모듈)

REG_RESOURCE_LIST (winreg 모듈)

REG_RESOURCE_REQUIREMENTS_LIST (winreg 모듈)

REG_SZ (winreg 모듈)

register() (abc.ABCMeta 메서드)

(atexit 모듈)

(codecs 모듈)

(faulthandler 모듈)

(multiprocessing.managers.BaseManager 메서드)

(select.devpoll 메서드)

(select.epoll 메서드)

(select.poll 메서드)

(selectors.BaseSelector의 메서드)

(webbrowser 모듈)

register_adapter() (sqlite3 모듈)

register_archive_format() (shutil 모듈)

register_at_fork() (os 모듈)

register_converter() (sqlite3 모듈)

register_defect() (email.policy.Policy 메서드)

register_dialect() (csv 모듈)

register_error() (codecs 모듈)

register_function() (xmlrpc.server.CGIXMLRPCRequestHandler 메서드)

(xmlrpc.server.SimpleXMLRPCServer 메서드)

register_instance() (xmlrpc.server.CGIXMLRPCRequestHandler 메서드)

(xmlrpc.server.SimpleXMLRPCServer 메서드)

register_introspection_functions() (xmlrpc.server.CGIXMLRPCRequestHandler 메서드)

(xmlrpc.server.SimpleXMLRPCServer 메서드)

register_multicall_functions() (xmlrpc.server.CGIXMLRPCRequestHandler 메서드)

(xmlrpc.server.SimpleXMLRPCServer 메서드)

register_namespace() (xml.etree.ElementTree 모듈)

register_optionflag() (doctest 모듈)

register_shape() (turtle 모듈)

register_unpack_format() (shutil 모듈)

registerDOMImplementation() (xml.dom 모듈)

registerResult() (unittest 모듈)

regular

package

regular package (정규 패키지)

relative

import

URL

relative_to() (pathlib.PurePath 메서드)

release() (_thread.lock 메서드)

(asyncio.Condition 메서드)

(asyncio.Lock 메서드)

(asyncio.Semaphore 메서드)

(logging.Handler 메서드)

(memoryview 메서드)

(multiprocessing.Lock 메서드)

(multiprocessing.RLock 메서드)

(platform 모듈)

(threading.Condition 메서드)

(threading.Lock 메서드)

(threading.RLock 메서드)

(threading.Semaphore 메서드)

release_lock() (imp 모듈)

reload (2to3 fixer)

reload() (imp 모듈)

(importlib 모듈)

relpath() (os.path 모듈)

remainder() (decimal.Context 메서드)

(math 모듈)

remainder_near() (decimal.Context 메서드)

(decimal.Decimal 메서드)

RemoteDisconnected

remove() (array.array 메서드)

(collections.deque 메서드)

(frozenset 메서드)

(mailbox.Mailbox 메서드)

(mailbox.MH 메서드)

(os 모듈)

(sequence method)

(xml.etree.ElementTree.Element 메서드)

remove_child_handler() (asyncio.AbstractChildWatcher 메서드)

remove_done_callback() (asyncio.Future 메서드)

(asyncio.Task 메서드)

remove_flag() (mailbox.MaildirMessage 메서드)

(mailbox.mboxMessage 메서드)

(mailbox.MMDFMessage 메서드)

remove_folder() (mailbox.Maildir 메서드)

(mailbox.MH 메서드)

remove_header() (urllib.request.Request 메서드)

remove_history_item() (readline 모듈)

remove_label() (mailbox.BabylMessage 메서드)

remove_option() (configparser.ConfigParser 메서드)

(optparse.OptionParser 메서드)

remove_pyc() (msilib.Directory 메서드)

remove_reader() (asyncio.loop 메서드)

remove_section() (configparser.ConfigParser 메서드)

remove_sequence() (mailbox.MHMessage 메서드)

remove_signal_handler() (asyncio.loop 메서드)

remove_tree() (distutils.dir_util 모듈)

remove_writer() (asyncio.loop 메서드)

removeAttribute() (xml.dom.Element 메서드)

removeAttributeNode() (xml.dom.Element 메서드)

removeAttributeNS() (xml.dom.Element 메서드)

removeChild() (xml.dom.Node 메서드)

removedirs() (os 모듈)

removeFilter() (logging.Handler 메서드)

(logging.Logger 메서드)

removeHandler() (logging.Logger 메서드)

(unittest 모듈)

removeResult() (unittest 모듈)

removexattr() (os 모듈)

rename() (ftplib.FTP 메서드)

(imaplib.IMAP4 메서드)

(os 모듈)

(pathlib.Path 메서드)

renames (2to3 fixer)

renames() (os 모듈)

reopenIfNeeded() (logging.handlers.WatchedFileHandler 메서드)

reorganize() (dbm.gnu.gdbm 메서드)

repeat() (itertools 모듈)

(timeit 모듈)

(timeit.Timer 메서드)

repetition

operation

replace() (bytearray 메서드)

(bytes 메서드)

(curses.panel.Panel 메서드)

(dataclasses 모듈)

(datetime.date 메서드)

(datetime.datetime 메서드)

(datetime.time 메서드)

(inspect.Parameter 메서드)

(inspect.Signature 메서드)

(os 모듈)

(pathlib.Path 메서드)

(str 메서드)

replace_errors() (codecs 모듈)

replace_header() (email.message.EmailMessage 메서드)

(email.message.Message 메서드)

replace_history_item() (readline 모듈)

replace_whitespace (textwrap.TextWrapper의 속성)

replaceChild() (xml.dom.Node 메서드)

ReplacePackage() (modulefinder 모듈)

report() (filecmp.dircmp 메서드)

(modulefinder.ModuleFinder 메서드)

REPORT_CDIFF (doctest 모듈)

report_failure() (doctest.DocTestRunner 메서드)

report_full_closure() (filecmp.dircmp 메서드)

REPORT_NDIFF (doctest 모듈)

REPORT_ONLY_FIRST_FAILURE (doctest 모듈)

report_partial_closure() (filecmp.dircmp 메서드)

report_start() (doctest.DocTestRunner 메서드)

report_success() (doctest.DocTestRunner 메서드)

REPORT_UDIFF (doctest 모듈)

report_unexpected_exception() (doctest.DocTestRunner 메서드)

REPORTING_FLAGS (doctest 모듈)

repr

내장 함수, [1], [2], [3]

repr (2to3 fixer)

Repr (reprlib 클래스)

repr() (built-in function)

__repr__() (object method)

repr() (reprlib 모듈)

(reprlib.Repr 메서드)

(내장 함수)

repr1() (reprlib.Repr 메서드)

representation

integer

reprlib (모듈)

Request (urllib.request 클래스)

request() (http.client.HTTPConnection 메서드)

request_queue_size (socketserver.BaseServer의 속성)

request_rate() (urllib.robotparser.RobotFileParser 메서드)

request_uri() (wsgiref.util 모듈)

request_version (http.server.BaseHTTPRequestHandler의 속성)

RequestHandlerClass (socketserver.BaseServer의 속성)

requestline (http.server.BaseHTTPRequestHandler의 속성)

requires() (test.support 모듈)

requires_bz2() (test.support 모듈)

requires_docstrings() (test.support 모듈)

requires_freebsd_version() (test.support 모듈)

requires_gzip() (test.support 모듈)

requires_IEEE_754() (test.support 모듈)

requires_linux_version() (test.support 모듈)

requires_lzma() (test.support 모듈)

requires_mac_version() (test.support 모듈)

requires_resource() (test.support 모듈)

requires_zlib() (test.support 모듈)

reserved (zipfile.ZipInfo의 속성)

reserved word

RESERVED_FUTURE (uuid 모듈)

RESERVED_MICROSOFT (uuid 모듈)

RESERVED_NCS (uuid 모듈)

reset() (bdb.Bdb 메서드)

(codecs.IncrementalDecoder 메서드)

(codecs.IncrementalEncoder 메서드)

(codecs.StreamReader 메서드)

(codecs.StreamWriter 메서드)

(contextvars.ContextVar 메서드)

(html.parser.HTMLParser 메서드)

(ossaudiodev.oss_audio_device 메서드)

(pipes.Template 메서드)

(threading.Barrier 메서드)

(turtle 모듈), [1]

(xdrlib.Packer 메서드)

(xdrlib.Unpacker 메서드)

(xml.dom.pulldom.DOMEventStream 메서드)

(xml.sax.xmlreader.IncrementalParser 메서드)

reset_mock() (unittest.mock.Mock 메서드)

reset_prog_mode() (curses 모듈)

reset_shell_mode() (curses 모듈)

resetbuffer() (code.InteractiveConsole 메서드)

resetlocale() (locale 모듈)

resetscreen() (turtle 모듈)

resetty() (curses 모듈)

resetwarnings() (warnings 모듈)

resize() (ctypes 모듈)

(curses.window 메서드)

(mmap.mmap 메서드)

resize_term() (curses 모듈)

resizemode() (turtle 모듈)

resizeterm() (curses 모듈)

resolution (datetime.datetime의 속성)

(datetime.date의 속성)

(datetime.timedelta의 속성)

(datetime.time의 속성)

resolve() (pathlib.Path 메서드)

resolve_bases() (types 모듈)

resolve_name() (importlib.util 모듈)

resolveEntity() (xml.sax.handler.EntityResolver 메서드)

Resource (importlib.resources 모듈)

resource (모듈)

resource_path() (importlib.abc.ResourceReader의 메서드)

ResourceDenied

ResourceLoader (importlib.abc 클래스)

ResourceReader (importlib.abc 클래스)

ResourceWarning

response (nntplib.NNTPError의 속성)

response() (imaplib.IMAP4 메서드)

ResponseNotReady

responses (http.client 모듈)

(http.server.BaseHTTPRequestHandler의 속성)

restart (pdb command)

restore() (difflib 모듈)

RESTRICTED

restricted

execution

restype (ctypes._FuncPtr의 속성)

result() (asyncio.Future 메서드)

(asyncio.Task 메서드)

(concurrent.futures.Future 메서드)

results() (trace.Trace 메서드)

resume_reading() (asyncio.ReadTransport 메서드)

resume_writing() (asyncio.BaseProtocol 메서드)

retr() (poplib.POP3 메서드)

retrbinary() (ftplib.FTP 메서드)

retrieve() (urllib.request.URLopener 메서드)

retrlines() (ftplib.FTP 메서드)

return

글, [1], [2]

return (pdb command)

return_annotation (inspect.Signature의 속성)

return_ok() (http.cookiejar.CookiePolicy 메서드)

RETURN_VALUE (opcode)

return_value (unittest.mock.Mock의 속성)

returncode (asyncio.asyncio.subprocess.Process의 속성)

(subprocess.CalledProcessError의 속성)

(subprocess.CompletedProcess의 속성)

(subprocess.Popen의 속성)

retval (pdb command)

reverse() (array.array 메서드)

(audioop 모듈)

(collections.deque 메서드)

(sequence method)

reverse_order() (pstats.Stats 메서드)

reverse_pointer (ipaddress.IPv4Address의 속성)

(ipaddress.IPv6Address의 속성)

reversed() (내장 함수)

Reversible (collections.abc 클래스)

(typing 클래스)

revert() (http.cookiejar.FileCookieJar 메서드)

rewind() (aifc.aifc 메서드)

(sunau.AU_read 메서드)

(wave.Wave_read 메서드)

RFC

RFC 1014, [1]

RFC 1123

RFC 1321

RFC 1422, [1]

RFC 1521, [1], [2]

RFC 1522, [1], [2]

RFC 1524, [1]

RFC 1730

RFC 1738

RFC 1750

RFC 1766, [1]

RFC 1808, [1], [2]

RFC 1832, [1]

RFC 1869, [1]

RFC 1870, [1], [2]

RFC 1939, [1]

RFC 2033

RFC 2045, [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12], [13], [14]

RFC 2045#section-6.8

RFC 2046, [1], [2]

RFC 2047, [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12]

RFC 2060, [1]

RFC 2068

RFC 2104, [1]

RFC 2109, [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12], [13], [14]

RFC 2183, [1], [2]

RFC 2231, [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12], [13], [14]

RFC 2295

RFC 2342, [1]

RFC 2368

RFC 2373, [1], [2]

RFC 2396, [1], [2], [3], [4]

RFC 2397

RFC 2449

RFC 2487

RFC 2518

RFC 2595, [1]

RFC 2616, [1], [2], [3], [4], [5], [6], [7], [8], [9]

RFC 2732, [1], [2]

RFC 2774

RFC 2818, [1]

RFC 2821

RFC 2822, [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12], [13], [14], [15], [16], [17]

RFC 2964

RFC 2965, [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12], [13], [14], [15], [16], [17], [18], [19]

RFC 2980, [1]

RFC 3056

RFC 3171

RFC 3207

RFC 3229

RFC 3280

RFC 3330

RFC 3339

RFC 3454, [1]

RFC 3490, [1], [2], [3]

RFC 3490#section-3.1

RFC 3492, [1]

RFC 3493

RFC 3501

RFC 3542, [1]

RFC 3548, [1], [2], [3], [4], [5]

RFC 3659

RFC 3879

RFC 3927

RFC 3977, [1], [2], [3], [4]

RFC 3986, [1], [2], [3], [4], [5], [6], [7]

RFC 4086

RFC 4122, [1], [2], [3], [4], [5], [6], [7], [8]

RFC 4180

RFC 4193

RFC 4217

RFC 4291

RFC 4380

RFC 4627, [1]

RFC 4642

RFC 4918, [1], [2], [3], [4]

RFC 4954, [1]

RFC 5161, [1]

RFC 5233, [1]

RFC 5246, [1]

RFC 5280, [1], [2], [3], [4]

RFC 5321, [1], [2], [3], [4]

RFC 5322, [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12], [13], [14], [15], [16], [17], [18], [19], [20], [21]

RFC 5424, [1], [2], [3]

RFC 5424#section-6

RFC 5735

RFC 5842, [1]

RFC 5929

RFC 6066, [1], [2]

RFC 6125, [1]

RFC 6152, [1]

RFC 6531, [1], [2], [3], [4], [5], [6], [7], [8]

RFC 6532, [1], [2], [3], [4]

RFC 6585, [1], [2], [3]

RFC 6855, [1], [2], [3]

RFC 6856, [1]

RFC 7159, [1], [2]

RFC 7230, [1]

RFC 7231, [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12], [13], [14], [15], [16], [17], [18], [19], [20], [21], [22], [23], [24], [25], [26], [27], [28], [29], [30], [31], [32], [33], [34]

RFC 7232, [1]

RFC 7233, [1]

RFC 7235, [1]

RFC 7238

RFC 7301, [1], [2]

RFC 7525

RFC 7540

RFC 7693

RFC 7914

RFC 821, [1]

RFC 822, [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11]

RFC 854, [1]

RFC 959, [1]

RFC 977

rfc2109 (http.cookiejar.Cookie의 속성)

rfc2109_as_netscape (http.cookiejar.DefaultCookiePolicy의 속성)

rfc2965 (http.cookiejar.CookiePolicy의 속성)

rfc822_escape() (distutils.util 모듈)

RFC_4122 (uuid 모듈)

rfile (http.server.BaseHTTPRequestHandler의 속성)

rfind() (bytearray 메서드)

(bytes 메서드)

(mmap.mmap 메서드)

(str 메서드)

rgb_to_hls() (colorsys 모듈)

rgb_to_hsv() (colorsys 모듈)

rgb_to_yiq() (colorsys 모듈)

rglob() (pathlib.Path 메서드)

right (filecmp.dircmp의 속성)

right() (turtle 모듈)

right_list (filecmp.dircmp의 속성)

right_only (filecmp.dircmp의 속성)

RIGHTSHIFT (token 모듈)

RIGHTSHIFTEQUAL (token 모듈)

rindex() (bytearray 메서드)

(bytes 메서드)

(str 메서드)

rjust() (bytearray 메서드)

(bytes 메서드)

(str 메서드)

rlcompleter (모듈)

rlecode_hqx() (binascii 모듈)

rledecode_hqx() (binascii 모듈)

RLIM_INFINITY (resource 모듈)

RLIMIT_AS (resource 모듈)

RLIMIT_CORE (resource 모듈)

RLIMIT_CPU (resource 모듈)

RLIMIT_DATA (resource 모듈)

RLIMIT_FSIZE (resource 모듈)

RLIMIT_MEMLOCK (resource 모듈)

RLIMIT_MSGQUEUE (resource 모듈)

RLIMIT_NICE (resource 모듈)

RLIMIT_NOFILE (resource 모듈)

RLIMIT_NPROC (resource 모듈)

RLIMIT_NPTS (resource 모듈)

RLIMIT_OFILE (resource 모듈)

RLIMIT_RSS (resource 모듈)

RLIMIT_RTPRIO (resource 모듈)

RLIMIT_RTTIME (resource 모듈)

RLIMIT_SBSIZE (resource 모듈)

RLIMIT_SIGPENDING (resource 모듈)

RLIMIT_STACK (resource 모듈)

RLIMIT_SWAP (resource 모듈)

RLIMIT_VMEM (resource 모듈)

RLock (multiprocessing 클래스)

(threading 클래스)

RLock() (multiprocessing.managers.SyncManager 메서드)

rmd() (ftplib.FTP 메서드)

rmdir() (os 모듈)

(pathlib.Path 메서드)

(test.support 모듈)

RMFF

rms() (audioop 모듈)

rmtree() (shutil 모듈)

(test.support 모듈)

RobotFileParser (urllib.robotparser 클래스)

robots.txt

rollback() (sqlite3.Connection 메서드)

ROT_THREE (opcode)

ROT_TWO (opcode)

rotate() (collections.deque 메서드)

(decimal.Context 메서드)

(decimal.Decimal 메서드)

(logging.handlers.BaseRotatingHandler 메서드)

RotatingFileHandler (logging.handlers 클래스)

rotation_filename() (logging.handlers.BaseRotatingHandler 메서드)

rotator (logging.handlers.BaseRotatingHandler의 속성)

round

내장 함수

round() (내장 함수)

ROUND_05UP (decimal 모듈)

ROUND_CEILING (decimal 모듈)

ROUND_DOWN (decimal 모듈)

ROUND_FLOOR (decimal 모듈)

ROUND_HALF_DOWN (decimal 모듈)

ROUND_HALF_EVEN (decimal 모듈)

ROUND_HALF_UP (decimal 모듈)

ROUND_UP (decimal 모듈)

Rounded (decimal 클래스)

Row (sqlite3 클래스)

row_factory (sqlite3.Connection의 속성)

rowcount (sqlite3.Cursor의 속성)

RPAR (token 모듈)

rpartition() (bytearray 메서드)

(bytes 메서드)

(str 메서드)

rpc_paths (xmlrpc.server.SimpleXMLRPCRequestHandler의 속성)

rpop() (poplib.POP3 메서드)

rset() (poplib.POP3 메서드)

rshift() (operator 모듈)

rsplit() (bytearray 메서드)

(bytes 메서드)

(str 메서드)

RSQB (token 모듈)

rstrip() (bytearray 메서드)

(bytes 메서드)

(str 메서드)

rt() (turtle 모듈)

RTLD_DEEPBIND (os 모듈)

RTLD_GLOBAL (os 모듈)

RTLD_LAZY (os 모듈)

RTLD_LOCAL (os 모듈)

RTLD_NODELETE (os 모듈)

RTLD_NOLOAD (os 모듈)

RTLD_NOW (os 모듈)

ruler (cmd.Cmd의 속성)

run (pdb command)

Run script

run() (asyncio 모듈)

(bdb.Bdb 메서드)

(contextvars.Context 메서드)

(distutils.cmd.Command 메서드)

(doctest.DocTestRunner 메서드)

(multiprocessing.Process 메서드)

(pdb 모듈)

(pdb.Pdb 메서드)

(profile 모듈)

(profile.Profile 메서드)

(sched.scheduler 메서드)

(subprocess 모듈)

(test.support.BasicTestRunner 메서드)

(threading.Thread 메서드)

(trace.Trace 메서드)

(unittest.TestCase 메서드)

(unittest.TestSuite 메서드)

(unittest.TextTestRunner 메서드)

(wsgiref.handlers.BaseHandler 메서드)

run_coroutine_threadsafe() (asyncio 모듈)

run_docstring_examples() (doctest 모듈)

run_doctest() (test.support 모듈)

run_forever() (asyncio.loop 메서드)

run_in_executor() (asyncio.loop의 메서드)

run_in_subinterp() (test.support 모듈)

run_module() (runpy 모듈)

run_path() (runpy 모듈)

run_python_until_end() (test.support.script_helper 모듈)

run_script() (modulefinder.ModuleFinder 메서드)

run_setup() (distutils.core 모듈)

run_unittest() (test.support 모듈)

run_until_complete() (asyncio.loop 메서드)

run_with_locale() (test.support 모듈)

run_with_tz() (test.support 모듈)

runcall() (bdb.Bdb 메서드)

(pdb 모듈)

(pdb.Pdb 메서드)

(profile.Profile 메서드)

runcode() (code.InteractiveInterpreter 메서드)

runctx() (bdb.Bdb 메서드)

(profile 모듈)

(profile.Profile 메서드)

(trace.Trace 메서드)

runeval() (bdb.Bdb 메서드)

(pdb 모듈)

(pdb.Pdb 메서드)

runfunc() (trace.Trace 메서드)

running() (concurrent.futures.Future 메서드)

runpy (모듈)

runsource() (code.InteractiveInterpreter 메서드)

runtime_library_dir_option() (distutils.ccompiler.CCompiler 메서드)

RuntimeError

RuntimeWarning

RUSAGE_BOTH (resource 모듈)

RUSAGE_CHILDREN (resource 모듈)

RUSAGE_SELF (resource 모듈)

RUSAGE_THREAD (resource 모듈)

RWF_DSYNC (os 모듈)

RWF_HIPRI (os 모듈)

RWF_NOWAIT (os 모듈)

RWF_SYNC (os 모듈)

탐색

색인

모듈 |

Python »

3.7.17 Documentation »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

Python »

3.7.17 Documentation »

|

Index – S

S (re 모듈)

S_ENFMT (stat 모듈)

S_IEXEC (stat 모듈)

S_IFBLK (stat 모듈)

S_IFCHR (stat 모듈)

S_IFDIR (stat 모듈)

S_IFDOOR (stat 모듈)

S_IFIFO (stat 모듈)

S_IFLNK (stat 모듈)

S_IFMT() (stat 모듈)

S_IFPORT (stat 모듈)

S_IFREG (stat 모듈)

S_IFSOCK (stat 모듈)

S_IFWHT (stat 모듈)

S_IMODE() (stat 모듈)

S_IREAD (stat 모듈)

S_IRGRP (stat 모듈)

S_IROTH (stat 모듈)

S_IRUSR (stat 모듈)

S_IRWXG (stat 모듈)

S_IRWXO (stat 모듈)

S_IRWXU (stat 모듈)

S_ISBLK() (stat 모듈)

S_ISCHR() (stat 모듈)

S_ISDIR() (stat 모듈)

S_ISDOOR() (stat 모듈)

S_ISFIFO() (stat 모듈)

S_ISGID (stat 모듈)

S_ISLNK() (stat 모듈)

S_ISPORT() (stat 모듈)

S_ISREG() (stat 모듈)

S_ISSOCK() (stat 모듈)

S_ISUID (stat 모듈)

S_ISVTX (stat 모듈)

S_ISWHT() (stat 모듈)

S_IWGRP (stat 모듈)

S_IWOTH (stat 모듈)

S_IWRITE (stat 모듈)

S_IWUSR (stat 모듈)

S_IXGRP (stat 모듈)

S_IXOTH (stat 모듈)

S_IXUSR (stat 모듈)

safe (uuid.SafeUUID의 속성)

safe_substitute() (string.Template 메서드)

SafeChildWatcher (asyncio 클래스)

saferepr() (pprint 모듈)

SafeUUID (uuid 클래스)

same_files (filecmp.dircmp의 속성)

same_quantum() (decimal.Context 메서드)

(decimal.Decimal 메서드)

samefile() (os.path 모듈)

(pathlib.Path 메서드)

SameFileError

sameopenfile() (os.path 모듈)

samestat() (os.path 모듈)

sample() (random 모듈)

save() (http.cookiejar.FileCookieJar 메서드)

SAVEDCWD (test.support 모듈)

SaveKey() (winreg 모듈)

SaveSignals (test.support 클래스)

savetty() (curses 모듈)

SAX2DOM (xml.dom.pulldom 클래스)

SAXException

SAXNotRecognizedException

SAXNotSupportedException

SAXParseException

scaleb() (decimal.Context 메서드)

(decimal.Decimal 메서드)

scandir() (os 모듈)

scanf()

sched (모듈)

SCHED_BATCH (os 모듈)

SCHED_FIFO (os 모듈)

sched_get_priority_max() (os 모듈)

sched_get_priority_min() (os 모듈)

sched_getaffinity() (os 모듈)

sched_getparam() (os 모듈)

sched_getscheduler() (os 모듈)

SCHED_IDLE (os 모듈)

SCHED_OTHER (os 모듈)

sched_param (os 클래스)

sched_priority (os.sched_param의 속성)

SCHED_RESET_ON_FORK (os 모듈)

SCHED_RR (os 모듈)

sched_rr_get_interval() (os 모듈)

sched_setaffinity() (os 모듈)

sched_setparam() (os 모듈)

sched_setscheduler() (os 모듈)

SCHED_SPORADIC (os 모듈)

sched_yield() (os 모듈)

scheduler (sched 클래스)

schema (msilib 모듈)

scope, [1]

Screen (turtle 클래스)

screensize() (turtle 모듈)

script_from_examples() (doctest 모듈)

scroll() (curses.window 메서드)

ScrolledCanvas (turtle 클래스)

scrollok() (curses.window 메서드)

scrypt() (hashlib 모듈)

sdterr

stdin stdout

seal() (unittest.mock 모듈)

search

path, module, [1], [2], [3], [4], [5], [6], [7]

search() (imaplib.IMAP4 메서드)

(re 모듈)

(re.Pattern 메서드)

second (datetime.datetime의 속성)

(datetime.time의 속성)

seconds since the epoch

secrets (모듈)

SECTCRE (configparser.ConfigParser의 속성)

sections() (configparser.ConfigParser 메서드)

secure (http.cookiejar.Cookie의 속성)

secure hash algorithm, SHA1, SHA224, SHA256, SHA384, SHA512

Secure Sockets Layer

security

CGI

http.server

see() (tkinter.ttk.Treeview 메서드)

seed() (random 모듈)

seek() (chunk.Chunk 메서드)

(io.IOBase 메서드)

(io.TextIOBase 메서드)

(mmap.mmap 메서드)

SEEK_CUR (os 모듈)

SEEK_END (os 모듈)

SEEK_SET (os 모듈)

seekable() (io.IOBase 메서드)

seen_greeting (smtpd.SMTPChannel의 속성)

Select (tkinter.tix 클래스)

select (모듈)

select() (imaplib.IMAP4 메서드)

(select 모듈)

(selectors.BaseSelector의 메서드)

(tkinter.ttk.Notebook 메서드)

selected_alpn_protocol() (ssl.SSLSocket 메서드)

selected_npn_protocol() (ssl.SSLSocket 메서드)

selection() (tkinter.ttk.Treeview 메서드)

selection_add() (tkinter.ttk.Treeview 메서드)

selection_remove() (tkinter.ttk.Treeview 메서드)

selection_set() (tkinter.ttk.Treeview 메서드)

selection_toggle() (tkinter.ttk.Treeview 메서드)

selector (urllib.request.Request의 속성)

SelectorEventLoop (asyncio 클래스)

SelectorKey (selectors 클래스)

selectors (모듈)

SelectSelector (selectors 클래스)

Semaphore (asyncio 클래스)

(multiprocessing 클래스)

(threading 클래스)

Semaphore() (multiprocessing.managers.SyncManager 메서드)

semaphores, binary

SEMI (token 모듈)

send() (asyncore.dispatcher 메서드)

(coroutine 메서드)

(generator 메서드)

(http.client.HTTPConnection 메서드)

(imaplib.IMAP4 메서드)

(logging.handlers.DatagramHandler 메서드)

(logging.handlers.SocketHandler 메서드)

(multiprocessing.connection.Connection 메서드)

(socket.socket 메서드)

send_bytes() (multiprocessing.connection.Connection 메서드)

send_error() (http.server.BaseHTTPRequestHandler 메서드)

send_flowing_data() (formatter.writer 메서드)

send_header() (http.server.BaseHTTPRequestHandler 메서드)

send_hor_rule() (formatter.writer 메서드)

send_label_data() (formatter.writer 메서드)

send_line_break() (formatter.writer 메서드)

send_literal_data() (formatter.writer 메서드)

send_message() (smtplib.SMTP 메서드)

send_paragraph() (formatter.writer 메서드)

send_response() (http.server.BaseHTTPRequestHandler 메서드)

send_response_only() (http.server.BaseHTTPRequestHandler 메서드)

send_signal() (asyncio.asyncio.subprocess.Process 메서드)

(asyncio.SubprocessTransport 메서드)

(subprocess.Popen 메서드)

sendall() (socket.socket 메서드)

sendcmd() (ftplib.FTP 메서드)

sendfile() (asyncio.loop의 메서드)

(os 모듈)

(socket.socket 메서드)

(wsgiref.handlers.BaseHandler 메서드)

SendfileNotAvailableError

sendmail() (smtplib.SMTP 메서드)

sendmsg() (socket.socket 메서드)

sendmsg_afalg() (socket.socket 메서드)

sendto() (asyncio.DatagramTransport 메서드)

(socket.socket 메서드)

sentinel (multiprocessing.Process의 속성)

(unittest.mock 모듈)

sep (os 모듈)

sequence

item

iteration

types, immutable

types, mutable

types, operations on, [1]

객체, [1], [2], [3], [4], [5], [6], [7], [8]

Sequence (collections.abc 클래스)

sequence (msilib 모듈)

Sequence (typing 클래스)

sequence (시퀀스)

sequence2st() (parser 모듈)

SequenceMatcher (difflib 클래스), [1]

serializing

objects

serve_forever() (asyncio.Server의 메서드)

(socketserver.BaseServer 메서드)

server

WWW, [1]

Server (asyncio 클래스)

server (http.server.BaseHTTPRequestHandler의 속성)

server_activate() (socketserver.BaseServer 메서드)

server_address (socketserver.BaseServer의 속성)

server_bind() (socketserver.BaseServer 메서드)

server_close() (socketserver.BaseServer 메서드)

server_hostname (ssl.SSLSocket의 속성)

server_side (ssl.SSLSocket의 속성)

server_software (wsgiref.handlers.BaseHandler의 속성)

server_version (http.server.BaseHTTPRequestHandler의 속성)

(http.server.SimpleHTTPRequestHandler의 속성)

ServerProxy (xmlrpc.client 클래스)

service_actions() (socketserver.BaseServer 메서드)

session (ssl.SSLSocket의 속성)

session_reused (ssl.SSLSocket의 속성)

session_stats() (ssl.SSLContext 메서드)

set

display

객체, [1], [2], [3]

Set (collections.abc 클래스)

(typing 클래스)

set (내장 클래스)

Set Breakpoint

set type

객체

set() (asyncio.Event 메서드)

(configparser.ConfigParser 메서드)

(configparser.RawConfigParser 메서드)

(contextvars.ContextVar 메서드)

(http.cookies.Morsel 메서드)

(ossaudiodev.oss_mixer_device 메서드)

(test.support.EnvironmentVarGuard 메서드)

(threading.Event 메서드)

(tkinter.ttk.Combobox 메서드)

(tkinter.ttk.Spinbox 메서드)

(tkinter.ttk.Treeview 메서드)

(xml.etree.ElementTree.Element 메서드)

SET_ADD (opcode)

set_all()

set_allowed_domains() (http.cookiejar.DefaultCookiePolicy 메서드)

set_alpn_protocols() (ssl.SSLContext 메서드)

set_app() (wsgiref.simple_server.WSGIServer 메서드)

set_asyncgen_hooks() (sys 모듈)

set_authorizer() (sqlite3.Connection 메서드)

set_auto_history() (readline 모듈)

set_blocked_domains() (http.cookiejar.DefaultCookiePolicy 메서드)

set_blocking() (os 모듈)

set_boundary() (email.message.EmailMessage 메서드)

(email.message.Message 메서드)

set_break() (bdb.Bdb 메서드)

set_charset() (email.message.Message 메서드)

set_child_watcher() (asyncio 모듈)

(asyncio.AbstractEventLoopPolicy 메서드)

set_children() (tkinter.ttk.Treeview 메서드)

set_ciphers() (ssl.SSLContext 메서드)

set_completer() (readline 모듈)

set_completer_delims() (readline 모듈)

set_completion_display_matches_hook() (readline 모듈)

set_content() (email.contentmanager 모듈)

(email.contentmanager.ContentManager 메서드)

(email.message.EmailMessage 메서드)

set_continue() (bdb.Bdb 메서드)

set_cookie() (http.cookiejar.CookieJar 메서드)

set_cookie_if_ok() (http.cookiejar.CookieJar 메서드)

set_coroutine_origin_tracking_depth() (sys 모듈)

set_coroutine_wrapper() (sys 모듈)

set_current() (msilib.Feature 메서드)

set_data() (importlib.abc.SourceLoader 메서드)

(importlib.machinery.SourceFileLoader 메서드)

set_date() (mailbox.MaildirMessage 메서드)

set_debug() (asyncio.loop 메서드)

(gc 모듈)

set_debuglevel() (ftplib.FTP 메서드)

(http.client.HTTPConnection 메서드)

(nntplib.NNTP 메서드)

(poplib.POP3 메서드)

(smtplib.SMTP 메서드)

(telnetlib.Telnet 메서드)

set_default_executor() (asyncio.loop 메서드)

set_default_type() (email.message.EmailMessage 메서드)

(email.message.Message 메서드)

set_default_verify_paths() (ssl.SSLContext 메서드)

set_defaults() (argparse.ArgumentParser 메서드)

(optparse.OptionParser 메서드)

set_ecdh_curve() (ssl.SSLContext 메서드)

set_errno() (ctypes 모듈)

set_event_loop() (asyncio 모듈)

(asyncio.AbstractEventLoopPolicy 메서드)

set_event_loop_policy() (asyncio 모듈)

set_exception() (asyncio.Future 메서드)

(concurrent.futures.Future 메서드)

set_exception_handler() (asyncio.loop 메서드)

set_executable() (multiprocessing 모듈)

set_executables() (distutils.ccompiler.CCompiler 메서드)

set_flags() (mailbox.MaildirMessage 메서드)

(mailbox.mboxMessage 메서드)

(mailbox.MMDFMessage 메서드)

set_from() (mailbox.mboxMessage 메서드)

(mailbox.MMDFMessage 메서드)

set_handle_inheritable() (os 모듈)

set_history_length() (readline 모듈)

set_include_dirs() (distutils.ccompiler.CCompiler 메서드)

set_info() (mailbox.MaildirMessage 메서드)

set_inheritable() (os 모듈)

(socket.socket 메서드)

set_int_max_str_digits() (sys 모듈)

set_labels() (mailbox.BabylMessage 메서드)

set_last_error() (ctypes 모듈)

set_libraries() (distutils.ccompiler.CCompiler 메서드)

set_library_dirs() (distutils.ccompiler.CCompiler 메서드)

set_link_objects() (distutils.ccompiler.CCompiler 메서드)

set_literal (2to3 fixer)

set_loader() (importlib.util 모듈)

set_match_tests() (test.support 모듈)

set_memlimit() (test.support 모듈)

set_next() (bdb.Bdb 메서드)

set_nonstandard_attr() (http.cookiejar.Cookie 메서드)

set_npn_protocols() (ssl.SSLContext 메서드)

set_ok() (http.cookiejar.CookiePolicy 메서드)

set_option_negotiation_callback() (telnetlib.Telnet 메서드)

set_output_charset() (gettext.NullTranslations 메서드)

set_package() (importlib.util 모듈)

set_param() (email.message.EmailMessage 메서드)

(email.message.Message 메서드)

set_pasv() (ftplib.FTP 메서드)

set_payload() (email.message.Message 메서드)

set_policy() (http.cookiejar.CookieJar 메서드)

set_position() (xdrlib.Unpacker 메서드)

set_pre_input_hook() (readline 모듈)

set_progress_handler() (sqlite3.Connection 메서드)

set_protocol() (asyncio.BaseTransport 메서드)

set_proxy() (urllib.request.Request 메서드)

set_python_build() (distutils.sysconfig 모듈)

set_quit() (bdb.Bdb 메서드)

set_recsrc() (ossaudiodev.oss_mixer_device 메서드)

set_result() (asyncio.Future 메서드)

(concurrent.futures.Future 메서드)

set_return() (bdb.Bdb 메서드)

set_running_or_notify_cancel() (concurrent.futures.Future 메서드)

set_runtime_library_dirs() (distutils.ccompiler.CCompiler 메서드)

set_seq1() (difflib.SequenceMatcher 메서드)

set_seq2() (difflib.SequenceMatcher 메서드)

set_seqs() (difflib.SequenceMatcher 메서드)

set_sequences() (mailbox.MH 메서드)

(mailbox.MHMessage 메서드)

set_server_documentation() (xmlrpc.server.DocCGIXMLRPCRequestHandler 메서드)

(xmlrpc.server.DocXMLRPCServer 메서드)

set_server_name() (xmlrpc.server.DocCGIXMLRPCRequestHandler 메서드)

(xmlrpc.server.DocXMLRPCServer 메서드)

set_server_title() (xmlrpc.server.DocCGIXMLRPCRequestHandler 메서드)

(xmlrpc.server.DocXMLRPCServer 메서드)

set_servername_callback (ssl.SSLContext의 속성)

set_spacing() (formatter.formatter 메서드)

set_start_method() (multiprocessing 모듈)

set_startup_hook() (readline 모듈)

set_step() (bdb.Bdb 메서드)

set_subdir() (mailbox.MaildirMessage 메서드)

set_task_factory() (asyncio.loop 메서드)

set_terminator() (asynchat.async_chat 메서드)

set_threshold() (gc 모듈)

set_trace() (bdb 모듈)

(bdb.Bdb 메서드)

(pdb 모듈)

(pdb.Pdb 메서드)

set_trace_callback() (sqlite3.Connection 메서드)

set_tunnel() (http.client.HTTPConnection 메서드)

set_type() (email.message.Message 메서드)

set_unittest_reportflags() (doctest 모듈)

set_unixfrom() (email.message.EmailMessage 메서드)

(email.message.Message 메서드)

set_until() (bdb.Bdb 메서드)

set_url() (urllib.robotparser.RobotFileParser 메서드)

set_usage() (optparse.OptionParser 메서드)

set_userptr() (curses.panel.Panel 메서드)

set_visible() (mailbox.BabylMessage 메서드)

set_wakeup_fd() (signal 모듈)

set_write_buffer_limits() (asyncio.WriteTransport 메서드)

setacl() (imaplib.IMAP4 메서드)

setannotation() (imaplib.IMAP4 메서드)

setattr() (내장 함수)

setAttribute() (xml.dom.Element 메서드)

setAttributeNode() (xml.dom.Element 메서드)

setAttributeNodeNS() (xml.dom.Element 메서드)

setAttributeNS() (xml.dom.Element 메서드)

SetBase() (xml.parsers.expat.xmlparser 메서드)

setblocking() (socket.socket 메서드)

setByteStream() (xml.sax.xmlreader.InputSource 메서드)

setcbreak() (tty 모듈)

setCharacterStream() (xml.sax.xmlreader.InputSource 메서드)

setcheckinterval() (sys 모듈)

setcomptype() (aifc.aifc 메서드)

(sunau.AU_write 메서드)

(wave.Wave_write 메서드)

setContentHandler() (xml.sax.xmlreader.XMLReader 메서드)

setcontext() (decimal 모듈)

setDaemon() (threading.Thread 메서드)

setdefault() (dict 메서드)

(http.cookies.Morsel 메서드)

setdefaulttimeout() (socket 모듈)

setdlopenflags() (sys 모듈)

setDocumentLocator() (xml.sax.handler.ContentHandler 메서드)

setDTDHandler() (xml.sax.xmlreader.XMLReader 메서드)

setegid() (os 모듈)

setEncoding() (xml.sax.xmlreader.InputSource 메서드)

setEntityResolver() (xml.sax.xmlreader.XMLReader 메서드)

setErrorHandler() (xml.sax.xmlreader.XMLReader 메서드)

seteuid() (os 모듈)

setFeature() (xml.sax.xmlreader.XMLReader 메서드)

setfirstweekday() (calendar 모듈)

setfmt() (ossaudiodev.oss_audio_device 메서드)

setFormatter() (logging.Handler 메서드)

setframerate() (aifc.aifc 메서드)

(sunau.AU_write 메서드)

(wave.Wave_write 메서드)

setgid() (os 모듈)

setgroups() (os 모듈)

seth() (turtle 모듈)

setheading() (turtle 모듈)

sethostname() (socket 모듈)

SetInteger() (msilib.Record 메서드)

setitem() (operator 모듈)

setitimer() (signal 모듈)

setLevel() (logging.Handler 메서드)

(logging.Logger 메서드)

setlocale() (locale 모듈)

setLocale() (xml.sax.xmlreader.XMLReader 메서드)

setLoggerClass() (logging 모듈)

setlogmask() (syslog 모듈)

setLogRecordFactory() (logging 모듈)

setmark() (aifc.aifc 메서드)

setMaxConns() (urllib.request.CacheFTPHandler 메서드)

setmode() (msvcrt 모듈)

setName() (threading.Thread 메서드)

setnchannels() (aifc.aifc 메서드)

(sunau.AU_write 메서드)

(wave.Wave_write 메서드)

setnframes() (aifc.aifc 메서드)

(sunau.AU_write 메서드)

(wave.Wave_write 메서드)

SetParamEntityParsing() (xml.parsers.expat.xmlparser 메서드)

setparameters() (ossaudiodev.oss_audio_device 메서드)

setparams() (aifc.aifc 메서드)

(sunau.AU_write 메서드)

(wave.Wave_write 메서드)

setpassword() (zipfile.ZipFile 메서드)

setpgid() (os 모듈)

setpgrp() (os 모듈)

setpos() (aifc.aifc 메서드)

(sunau.AU_read 메서드)

(turtle 모듈)

(wave.Wave_read 메서드)

setposition() (turtle 모듈)

setpriority() (os 모듈)

setprofile() (sys 모듈)

(threading 모듈)

SetProperty() (msilib.SummaryInformation 메서드)

setProperty() (xml.sax.xmlreader.XMLReader 메서드)

setPublicId() (xml.sax.xmlreader.InputSource 메서드)

setquota() (imaplib.IMAP4 메서드)

setraw() (tty 모듈)

setrecursionlimit() (sys 모듈)

setregid() (os 모듈)

setresgid() (os 모듈)

setresuid() (os 모듈)

setreuid() (os 모듈)

setrlimit() (resource 모듈)

setsampwidth() (aifc.aifc 메서드)

(sunau.AU_write 메서드)

(wave.Wave_write 메서드)

setscrreg() (curses.window 메서드)

setsid() (os 모듈)

setsockopt() (socket.socket 메서드), [1], [2]

setstate() (codecs.IncrementalDecoder 메서드)

(codecs.IncrementalEncoder 메서드)

(random 모듈)

setStream() (logging.StreamHandler 메서드)

SetStream() (msilib.Record 메서드)

SetString() (msilib.Record 메서드)

setswitchinterval() (in module sys)

(sys 모듈)

(test.support 모듈)

setSystemId() (xml.sax.xmlreader.InputSource 메서드)

setsyx() (curses 모듈)

setTarget() (logging.handlers.MemoryHandler 메서드)

settiltangle() (turtle 모듈)

settimeout() (socket.socket 메서드)

setTimeout() (urllib.request.CacheFTPHandler 메서드)

settrace() (sys 모듈)

(threading 모듈)

setuid() (os 모듈)

setundobuffer() (turtle 모듈)

setup() (distutils.core 모듈)

(socketserver.BaseRequestHandler 메서드)

(turtle 모듈)

setUp() (unittest.TestCase 메서드)

SETUP_ANNOTATIONS (opcode)

SETUP_ASYNC_WITH (opcode)

setup_environ() (wsgiref.handlers.BaseHandler 메서드)

SETUP_EXCEPT (opcode)

SETUP_FINALLY (opcode)

SETUP_LOOP (opcode)

setup_python() (venv.EnvBuilder 메서드)

setup_scripts() (venv.EnvBuilder 메서드)

setup_testing_defaults() (wsgiref.util 모듈)

SETUP_WITH (opcode)

setUpClass() (unittest.TestCase 메서드)

setupterm() (curses 모듈)

SetValue() (winreg 모듈)

SetValueEx() (winreg 모듈)

setworldcoordinates() (turtle 모듈)

setx() (turtle 모듈)

setxattr() (os 모듈)

sety() (turtle 모듈)

SF_APPEND (stat 모듈)

SF_ARCHIVED (stat 모듈)

SF_IMMUTABLE (stat 모듈)

SF_MNOWAIT (os 모듈)

SF_NODISKIO (os 모듈)

SF_NOUNLINK (stat 모듈)

SF_SNAPSHOT (stat 모듈)

SF_SYNC (os 모듈)

shape (memoryview의 속성)

Shape (turtle 클래스)

shape() (turtle 모듈)

shapesize() (turtle 모듈)

shapetransform() (turtle 모듈)

share() (socket.socket 메서드)

shared_ciphers() (ssl.SSLSocket 메서드)

shared_object_filename() (distutils.ccompiler.CCompiler 메서드)

shearfactor() (turtle 모듈)

Shelf (shelve 클래스)

shelve

모듈

shelve (모듈)

shift() (decimal.Context 메서드)

(decimal.Decimal 메서드)

shift_path_info() (wsgiref.util 모듈)

shifting

operation

operations

shlex (shlex 클래스)

(모듈)

shortDescription() (unittest.TestCase 메서드)

shorten() (textwrap 모듈)

shouldFlush() (logging.handlers.BufferingHandler 메서드)

(logging.handlers.MemoryHandler 메서드)

shouldStop (unittest.TestResult의 속성)

show() (curses.panel.Panel 메서드)

show_code() (dis 모듈)

show_compilers() (distutils.ccompiler 모듈)

showsyntaxerror() (code.InteractiveInterpreter 메서드)

showtraceback() (code.InteractiveInterpreter 메서드)

showturtle() (turtle 모듈)

showwarning() (warnings 모듈)

shuffle() (random 모듈)

shutdown() (concurrent.futures.Executor 메서드)

(imaplib.IMAP4 메서드)

(logging 모듈)

(multiprocessing.managers.BaseManager 메서드)

(socket.socket 메서드)

(socketserver.BaseServer 메서드)

shutdown_asyncgens() (asyncio.loop의 메서드)

shutil (모듈)

side_effect (unittest.mock.Mock의 속성)

SIG_BLOCK (signal 모듈)

SIG_DFL (signal 모듈)

SIG_IGN (signal 모듈)

SIG_SETMASK (signal 모듈)

SIG_UNBLOCK (signal 모듈)

SIGABRT (signal 모듈)

SIGALRM (signal 모듈)

SIGBREAK (signal 모듈)

SIGBUS (signal 모듈)

SIGCHLD (signal 모듈)

SIGCLD (signal 모듈)

SIGCONT (signal 모듈)

SIGFPE (signal 모듈)

SIGHUP (signal 모듈)

SIGILL (signal 모듈)

SIGINT, [1]

(signal 모듈)

siginterrupt() (signal 모듈)

SIGKILL (signal 모듈)

signal

모듈, [1]

signal (모듈)

signal() (signal 모듈)

Signature (inspect 클래스)

signature (inspect.BoundArguments의 속성)

signature() (inspect 모듈)

sigpending() (signal 모듈)

SIGPIPE (signal 모듈)

SIGSEGV (signal 모듈)

SIGTERM (signal 모듈)

sigtimedwait() (signal 모듈)

SIGUSR1 (signal 모듈)

SIGUSR2 (signal 모듈)

sigwait() (signal 모듈)

sigwaitinfo() (signal 모듈)

SIGWINCH (signal 모듈)

simple

statement

Simple Mail Transfer Protocol

SimpleCookie (http.cookies 클래스)

simplefilter() (warnings 모듈)

SimpleHandler (wsgiref.handlers 클래스)

SimpleHTTPRequestHandler (http.server 클래스)

SimpleNamespace (types 클래스)

SimpleQueue (multiprocessing 클래스)

(queue 클래스)

SimpleXMLRPCRequestHandler (xmlrpc.server 클래스)

SimpleXMLRPCServer (xmlrpc.server 클래스)

sin() (cmath 모듈)

(math 모듈)

single dispatch (싱글 디스패치)

SingleAddressHeader (email.headerregistry 클래스)

singledispatch() (functools 모듈)

singleton

tuple

sinh() (cmath 모듈)

(math 모듈)

SIO_KEEPALIVE_VALS (socket 모듈)

SIO_LOOPBACK_FAST_PATH (socket 모듈)

SIO_RCVALL (socket 모듈)

site (모듈)

site command line option

--user-base

--user-site

site-packages

directory

sitecustomize

모듈

sixtofour (ipaddress.IPv6Address의 속성)

size (struct.Struct의 속성)

(tarfile.TarInfo의 속성)

(tracemalloc.StatisticDiff의 속성)

(tracemalloc.Statistic의 속성)

(tracemalloc.Trace의 속성)

size() (ftplib.FTP 메서드)

(mmap.mmap 메서드)

size_diff (tracemalloc.StatisticDiff의 속성)

SIZE_MAX

Sized (collections.abc 클래스)

(typing 클래스)

sizeof() (ctypes 모듈)

SKIP (doctest 모듈)

skip() (chunk.Chunk 메서드)

(unittest 모듈)

skip_unless_bind_unix_socket() (test.support 모듈)

skip_unless_symlink() (test.support 모듈)

skip_unless_xattr() (test.support 모듈)

skipIf() (unittest 모듈)

skipinitialspace (csv.Dialect의 속성)

skipped (unittest.TestResult의 속성)

skippedEntity() (xml.sax.handler.ContentHandler 메서드)

SkipTest

skipTest() (unittest.TestCase 메서드)

skipUnless() (unittest 모듈)

SLASH (token 모듈)

SLASHEQUAL (token 모듈)

slave() (nntplib.NNTP 메서드)

sleep() (asyncio 모듈)

(time 모듈)

slice

assignment

operation

객체

내장 함수, [1]

slice (내장 클래스)

(슬라이스)

slicing, [1], [2]

assignment

SMALLEST (test.support 모듈)

SMTP

protocol

SMTP (email.policy 모듈)

(smtplib 클래스)

smtp_server (smtpd.SMTPChannel의 속성)

SMTP_SSL (smtplib 클래스)

smtp_state (smtpd.SMTPChannel의 속성)

SMTPAuthenticationError

SMTPChannel (smtpd 클래스)

SMTPConnectError

smtpd (모듈)

SMTPDataError

SMTPException

SMTPHandler (logging.handlers 클래스)

SMTPHeloError

smtplib (모듈)

SMTPNotSupportedError

SMTPRecipientsRefused

SMTPResponseException

SMTPSenderRefused

SMTPServer (smtpd 클래스)

SMTPServerDisconnected

SMTPUTF8 (email.policy 모듈)

Snapshot (tracemalloc 클래스)

SND_ALIAS (winsound 모듈)

SND_ASYNC (winsound 모듈)

SND_FILENAME (winsound 모듈)

SND_LOOP (winsound 모듈)

SND_MEMORY (winsound 모듈)

SND_NODEFAULT (winsound 모듈)

SND_NOSTOP (winsound 모듈)

SND_NOWAIT (winsound 모듈)

SND_PURGE (winsound 모듈)

sndhdr (모듈)

sni_callback (ssl.SSLContext의 속성)

sniff() (csv.Sniffer 메서드)

Sniffer (csv 클래스)

sock_accept() (asyncio.loop의 메서드)

SOCK_CLOEXEC (socket 모듈)

sock_connect() (asyncio.loop의 메서드)

SOCK_DGRAM (socket 모듈)

SOCK_MAX_SIZE (test.support 모듈)

SOCK_NONBLOCK (socket 모듈)

SOCK_RAW (socket 모듈)

SOCK_RDM (socket 모듈)

sock_recv() (asyncio.loop의 메서드)

sock_recv_into() (asyncio.loop의 메서드)

sock_sendall() (asyncio.loop의 메서드)

sock_sendfile() (asyncio.loop의 메서드)

SOCK_SEQPACKET (socket 모듈)

SOCK_STREAM (socket 모듈)

socket

객체

모듈

socket (socketserver.BaseServer의 속성)

(모듈)

socket() (imaplib.IMAP4 메서드)

(in module socket)

(socket 모듈)

socket_type (socketserver.BaseServer의 속성)

SocketHandler (logging.handlers 클래스)

socketpair() (socket 모듈)

sockets (asyncio.Server의 속성)

socketserver (모듈)

SocketType (socket 모듈)

SOL_ALG (socket 모듈)

SOL_RDS (socket 모듈)

SOMAXCONN (socket 모듈)

sort() (imaplib.IMAP4 메서드)

(list 메서드)

sort_stats() (pstats.Stats 메서드)

sortdict() (test.support 모듈)

sorted() (내장 함수)

sortTestMethodsUsing (unittest.TestLoader의 속성)

source (doctest.Example의 속성)

(pdb command)

(shlex.shlex의 속성)

source character set

SOURCE_DATE_EPOCH, [1], [2], [3], [4], [5], [6]

source_from_cache() (imp 모듈)

(importlib.util 모듈)

source_hash() (importlib.util 모듈)

SOURCE_SUFFIXES (importlib.machinery 모듈)

source_to_code() (importlib.abc.InspectLoader의 정적 메서드)

SourceFileLoader (importlib.machinery 클래스)

sourcehook() (shlex.shlex 메서드)

SourcelessFileLoader (importlib.machinery 클래스)

SourceLoader (importlib.abc 클래스)

space

in printf-style formatting, [1]

in string formatting

span() (re.Match 메서드)

spawn() (distutils.ccompiler.CCompiler 메서드)

(pty 모듈)

spawn_python() (test.support.script_helper 모듈)

spawnl() (os 모듈)

spawnle() (os 모듈)

spawnlp() (os 모듈)

spawnlpe() (os 모듈)

spawnv() (os 모듈)

spawnve() (os 모듈)

spawnvp() (os 모듈)

spawnvpe() (os 모듈)

spec_from_file_location() (importlib.util 모듈)

spec_from_loader() (importlib.util 모듈)

special

attribute

attribute, generic

method

special method (특수 메서드)

specified_attributes (xml.parsers.expat.xmlparser의 속성)

speed() (ossaudiodev.oss_audio_device 메서드)

(turtle 모듈)

Spinbox (tkinter.ttk 클래스)

split() (bytearray 메서드)

(bytes 메서드)

(os.path 모듈)

(re 모듈)

(re.Pattern 메서드)

(shlex 모듈)

(str 메서드)

split_quoted() (distutils.util 모듈)

splitdrive() (os.path 모듈)

splitext() (os.path 모듈)

splitlines() (bytearray 메서드)

(bytes 메서드)

(str 메서드)

SplitResult (urllib.parse 클래스)

SplitResultBytes (urllib.parse 클래스)

SpooledTemporaryFile() (tempfile 모듈)

sprintf-style formatting, [1]

spwd (모듈)

sqlite3 (모듈)

sqlite_version (sqlite3 모듈)

sqlite_version_info (sqlite3 모듈)

sqrt() (cmath 모듈)

(decimal.Context 메서드)

(decimal.Decimal 메서드)

(math 모듈)

SSL

ssl (모듈)

SSL_CERT_FILE

SSL_CERT_PATH

ssl_version (ftplib.FTP_TLS의 속성)

SSLCertVerificationError

SSLContext (ssl 클래스)

SSLEOFError

SSLError

SSLErrorNumber (ssl 클래스)

SSLObject (ssl 클래스)

sslobject_class (ssl.SSLContext의 속성)

SSLSession (ssl 클래스)

SSLSocket (ssl 클래스)

sslsocket_class (ssl.SSLContext의 속성)

SSLSyscallError

SSLv3 (ssl.TLSVersion의 속성)

SSLWantReadError

SSLWantWriteError

SSLZeroReturnError

st() (turtle 모듈)

st2list() (parser 모듈)

st2tuple() (parser 모듈)

st_atime (os.stat_result의 속성)

ST_ATIME (stat 모듈)

st_atime_ns (os.stat_result의 속성)

st_birthtime (os.stat_result의 속성)

st_blksize (os.stat_result의 속성)

st_blocks (os.stat_result의 속성)

st_creator (os.stat_result의 속성)

st_ctime (os.stat_result의 속성)

ST_CTIME (stat 모듈)

st_ctime_ns (os.stat_result의 속성)

st_dev (os.stat_result의 속성)

ST_DEV (stat 모듈)

st_file_attributes (os.stat_result의 속성)

st_flags (os.stat_result의 속성)

st_fstype (os.stat_result의 속성)

st_gen (os.stat_result의 속성)

st_gid (os.stat_result의 속성)

ST_GID (stat 모듈)

st_ino (os.stat_result의 속성)

ST_INO (stat 모듈)

st_mode (os.stat_result의 속성)

ST_MODE (stat 모듈)

st_mtime (os.stat_result의 속성)

ST_MTIME (stat 모듈)

st_mtime_ns (os.stat_result의 속성)

st_nlink (os.stat_result의 속성)

ST_NLINK (stat 모듈)

st_rdev (os.stat_result의 속성)

st_rsize (os.stat_result의 속성)

st_size (os.stat_result의 속성)

ST_SIZE (stat 모듈)

st_type (os.stat_result의 속성)

st_uid (os.stat_result의 속성)

ST_UID (stat 모듈)

stack

execution

trace

stack (traceback.TracebackException의 속성)

stack viewer

stack() (inspect 모듈)

stack_effect() (dis 모듈)

stack_size() (_thread 모듈)

(threading 모듈)

stackable

streams

StackSummary (traceback 클래스)

stamp() (turtle 모듈)

standard

output

Standard C

standard input

standard_b64decode() (base64 모듈)

standard_b64encode() (base64 모듈)

standarderror (2to3 fixer)

standend() (curses.window 메서드)

standout() (curses.window 메서드)

STAR (token 모듈)

STAREQUAL (token 모듈)

starmap() (itertools 모듈)

(multiprocessing.pool.Pool 메서드)

starmap_async() (multiprocessing.pool.Pool 메서드)

start (range의 속성)

(slice object attribute), [1]

(UnicodeError의 속성)

start() (logging.handlers.QueueListener 메서드)

(multiprocessing.managers.BaseManager 메서드)

(multiprocessing.Process 메서드)

(re.Match 메서드)

(threading.Thread 메서드)

(tkinter.ttk.Progressbar 메서드)

(tracemalloc 모듈)

(xml.etree.ElementTree.TreeBuilder 메서드)

start_color() (curses 모듈)

start_component() (msilib.Directory 메서드)

start_new_thread() (_thread 모듈)

start_server() (asyncio 모듈)

start_serving() (asyncio.Server의 메서드)

start_threads() (test.support 모듈)

start_tls() (asyncio.loop의 메서드)

start_unix_server() (asyncio 모듈)

StartCdataSectionHandler() (xml.parsers.expat.xmlparser 메서드)

StartDoctypeDeclHandler() (xml.parsers.expat.xmlparser 메서드)

startDocument() (xml.sax.handler.ContentHandler 메서드)

startElement() (xml.sax.handler.ContentHandler 메서드)

StartElementHandler() (xml.parsers.expat.xmlparser 메서드)

startElementNS() (xml.sax.handler.ContentHandler 메서드)

STARTF_USESHOWWINDOW (subprocess 모듈)

STARTF_USESTDHANDLES (subprocess 모듈)

startfile() (os 모듈)

StartNamespaceDeclHandler() (xml.parsers.expat.xmlparser 메서드)

startPrefixMapping() (xml.sax.handler.ContentHandler 메서드)

startswith() (bytearray 메서드)

(bytes 메서드)

(str 메서드)

startTest() (unittest.TestResult 메서드)

startTestRun() (unittest.TestResult 메서드)

starttls() (imaplib.IMAP4 메서드)

(nntplib.NNTP 메서드)

(smtplib.SMTP 메서드)

STARTUPINFO (subprocess 클래스)

stat

모듈

stat (모듈)

stat() (nntplib.NNTP 메서드)

(os 모듈)

(os.DirEntry 메서드)

(pathlib.Path 메서드)

(poplib.POP3 메서드)

stat_result (os 클래스)

state() (tkinter.ttk.Widget 메서드)

statement

assignment, [1]

assignment, annotated

assignment, augmented

compound

expression

future

loop, [1], [2], [3]

simple

statement (문장)

statement grouping

staticmethod

내장 함수

staticmethod() (내장 함수)

Statistic (tracemalloc 클래스)

StatisticDiff (tracemalloc 클래스)

statistics (모듈)

statistics() (tracemalloc.Snapshot 메서드)

StatisticsError

Stats (pstats 클래스)

status (http.client.HTTPResponse의 속성)

status() (imaplib.IMAP4 메서드)

statvfs() (os 모듈)

STD_ERROR_HANDLE (subprocess 모듈)

STD_INPUT_HANDLE (subprocess 모듈)

STD_OUTPUT_HANDLE (subprocess 모듈)

StdButtonBox (tkinter.tix 클래스)

stderr (asyncio.asyncio.subprocess.Process의 속성)

(in module sys), [1]

(subprocess.CalledProcessError의 속성)

(subprocess.CompletedProcess의 속성)

(subprocess.Popen의 속성)

(subprocess.TimeoutExpired의 속성)

(sys 모듈)

stdev() (statistics 모듈)

stdin

stdout sdterr

stdin (asyncio.asyncio.subprocess.Process의 속성)

(in module sys), [1]

(subprocess.Popen의 속성)

(sys 모듈)

stdio

stdout

sdterr, stdin

stdout (asyncio.asyncio.subprocess.Process의 속성)

(in module sys), [1]

STDOUT (subprocess 모듈)

stdout (subprocess.CalledProcessError의 속성)

(subprocess.CompletedProcess의 속성)

(subprocess.Popen의 속성)

(subprocess.TimeoutExpired의 속성)

(sys 모듈)

step (pdb command)

(range의 속성)

(slice object attribute), [1]

step() (tkinter.ttk.Progressbar 메서드)

stereocontrols() (ossaudiodev.oss_mixer_device 메서드)

stls() (poplib.POP3 메서드)

stop (range의 속성)

(slice object attribute), [1]

stop() (asyncio.loop 메서드)

(logging.handlers.QueueListener 메서드)

(tkinter.ttk.Progressbar 메서드)

(tracemalloc 모듈)

(unittest.TestResult 메서드)

stop_here() (bdb.Bdb 메서드)

StopAsyncIteration

예외

StopIteration

예외, [1]

stopListening() (logging.config 모듈)

stopTest() (unittest.TestResult 메서드)

stopTestRun() (unittest.TestResult 메서드)

storbinary() (ftplib.FTP 메서드)

store() (imaplib.IMAP4 메서드)

STORE_ACTIONS (optparse.Option의 속성)

STORE_ATTR (opcode)

STORE_DEREF (opcode)

STORE_FAST (opcode)

STORE_GLOBAL (opcode)

STORE_NAME (opcode)

STORE_SUBSCR (opcode)

storlines() (ftplib.FTP 메서드)

str (built-in class)

(see also string)

str (내장 클래스)

str() (locale 모듈)

strcoll() (locale 모듈)

StreamError

StreamHandler (logging 클래스)

StreamReader (asyncio 클래스)

(codecs 클래스)

streamreader (codecs.CodecInfo의 속성)

StreamReaderWriter (codecs 클래스)

StreamRecoder (codecs 클래스)

StreamRequestHandler (socketserver 클래스)

streams

stackable

StreamWriter (asyncio 클래스)

(codecs 클래스)

streamwriter (codecs.CodecInfo의 속성)

strerror (OSError의 속성)

strerror()

(os 모듈)

strftime() (datetime.date 메서드)

(datetime.datetime 메서드)

(datetime.time 메서드)

(time 모듈)

strict (csv.Dialect의 속성)

(email.policy 모듈)

strict_domain (http.cookiejar.DefaultCookiePolicy의 속성)

strict_errors() (codecs 모듈)

strict_ns_domain (http.cookiejar.DefaultCookiePolicy의 속성)

strict_ns_set_initial_dollar (http.cookiejar.DefaultCookiePolicy의 속성)

strict_ns_set_path (http.cookiejar.DefaultCookiePolicy의 속성)

strict_ns_unverifiable (http.cookiejar.DefaultCookiePolicy의 속성)

strict_rfc2965_unverifiable (http.cookiejar.DefaultCookiePolicy의 속성)

strides (memoryview의 속성)

string

__format__() (object method)

__str__() (object method)

conversion, [1]

format() (built-in function)

formatted literal

formatting, printf

immutable sequences

interpolated literal

interpolation, printf

item

methods

object representation

PyObject_Str (C function)

str (built-in class)

str() (built-in function)

text sequence type

객체, [1], [2]

모듈

string (re.Match의 속성)

STRING (token 모듈)

string (모듈)

string literal

string_at() (ctypes 모듈)

StringIO (io 클래스)

stringprep (모듈)

strings, documentation, [1]

strip() (bytearray 메서드)

(bytes 메서드)

(str 메서드)

strip_dirs() (pstats.Stats 메서드)

strip_python_strerr() (test.support 모듈)

stripspaces (curses.textpad.Textbox의 속성)

strptime() (datetime.datetime의 클래스 메서드)

(time 모듈)

strtobool() (distutils.util 모듈)

struct

모듈

Struct (struct 클래스)

struct (모듈)

struct_time (time 클래스)

Structure (ctypes 클래스)

structures

C

strxfrm() (locale 모듈)

STType (parser 모듈)

style

coding

Style (tkinter.ttk 클래스)

sub() (operator 모듈)

(re 모듈)

(re.Pattern 메서드)

sub_commands (distutils.cmd.Command의 속성)

subclassing

immutable types

subdirs (filecmp.dircmp의 속성)

SubElement() (xml.etree.ElementTree 모듈)

submit() (concurrent.futures.Executor 메서드)

submodule_search_locations (importlib.machinery.ModuleSpec의 속성)

subn() (re 모듈)

(re.Pattern 메서드)

subnet_of() (ipaddress.IPv4Network 메서드)

(ipaddress.IPv6Network 메서드)

subnets() (ipaddress.IPv4Network 메서드)

(ipaddress.IPv6Network 메서드)

Subnormal (decimal 클래스)

suboffsets (memoryview의 속성)

subpad() (curses.window 메서드)

subprocess (모듈)

subprocess_exec() (asyncio.loop의 메서드)

subprocess_shell() (asyncio.loop의 메서드)

SubprocessError

SubprocessProtocol (asyncio 클래스)

SubprocessTransport (asyncio 클래스)

subscribe() (imaplib.IMAP4 메서드)

subscript

assignment

operation

subscription, [1], [2], [3]

assignment

subsequent_indent (textwrap.TextWrapper의 속성)

subst_vars() (distutils.util 모듈)

substitute() (string.Template 메서드)

subTest() (unittest.TestCase 메서드)

subtract() (collections.Counter 메서드)

(decimal.Context 메서드)

subtraction

subtype (email.headerregistry.ContentTypeHeader의 속성)

subwin() (curses.window 메서드)

successful() (multiprocessing.pool.AsyncResult 메서드)

suffix_map (mimetypes 모듈)

(mimetypes.MimeTypes의 속성)

suite

suite() (parser 모듈)

suiteClass (unittest.TestLoader의 속성)

sum() (내장 함수)

sum_list()

sum_sequence(), [1]

summarize() (doctest.DocTestRunner 메서드)

summarize_address_range() (ipaddress 모듈)

sunau (모듈)

super (pyclbr.Class의 속성)

super() (내장 함수)

supernet() (ipaddress.IPv4Network 메서드)

(ipaddress.IPv6Network 메서드)

supernet_of() (ipaddress.IPv4Network 메서드)

(ipaddress.IPv6Network 메서드)

supports_bytes_environ (os 모듈)

supports_dir_fd (os 모듈)

supports_effective_ids (os 모듈)

supports_fd (os 모듈)

supports_follow_symlinks (os 모듈)

supports_unicode_filenames (os.path 모듈)

SupportsAbs (typing 클래스)

SupportsBytes (typing 클래스)

SupportsComplex (typing 클래스)

SupportsFloat (typing 클래스)

SupportsInt (typing 클래스)

SupportsRound (typing 클래스)

suppress() (contextlib 모듈)

SuppressCrashReport (test.support 클래스)

SW_HIDE (subprocess 모듈)

swap_attr() (test.support 모듈)

swap_item() (test.support 모듈)

swapcase() (bytearray 메서드)

(bytes 메서드)

(str 메서드)

sym_name (symbol 모듈)

Symbol (symtable 클래스)

symbol (모듈)

SymbolTable (symtable 클래스)

symlink() (os 모듈)

symlink_to() (pathlib.Path 메서드)

symmetric_difference() (frozenset 메서드)

symmetric_difference_update() (frozenset 메서드)

symtable (모듈)

symtable() (symtable 모듈)

sync() (dbm.dumb.dumbdbm 메서드)

(dbm.gnu.gdbm 메서드)

(os 모듈)

(ossaudiodev.oss_audio_device 메서드)

(shelve.Shelf 메서드)

syncdown() (curses.window 메서드)

synchronized() (multiprocessing.sharedctypes 모듈)

SyncManager (multiprocessing.managers 클래스)

syncok() (curses.window 메서드)

syncup() (curses.window 메서드)

syntax

SyntaxErr

SyntaxError

SyntaxWarning

sys

모듈, [1], [2], [3], [4], [5], [6]

sys (모듈)

sys.exc_info

sys.last_traceback

sys.meta_path

sys.modules

sys.path

sys.path_hooks

sys.path_importer_cache

sys.stderr

sys.stdin

sys.stdout

sys_exc (2to3 fixer)

sys_version (http.server.BaseHTTPRequestHandler의 속성)

sysconf() (os 모듈)

sysconf_names (os 모듈)

sysconfig (모듈)

syslog (모듈)

syslog() (syslog 모듈)

SysLogHandler (logging.handlers 클래스)

system() (os 모듈)

(platform 모듈)

system_alias() (platform 모듈)

system_must_validate_cert() (test.support 모듈)

SystemError

(built-in exception), [1]

SystemExit

(built-in exception)

systemId (xml.dom.DocumentType의 속성)

SystemRandom (random 클래스)

(secrets 클래스)

SystemRoot

탐색

색인

모듈 |

Python »

3.7.17 Documentation »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

Python »

3.7.17 Documentation »

|

Index – T

T_FMT (locale 모듈)

T_FMT_AMPM (locale 모듈)

tab

tab() (tkinter.ttk.Notebook 메서드)

TabError

tabnanny (모듈)

tabs() (tkinter.ttk.Notebook 메서드)

tabsize (textwrap.TextWrapper의 속성)

tabular

data

tag (xml.etree.ElementTree.Element의 속성)

tag_bind() (tkinter.ttk.Treeview 메서드)

tag_configure() (tkinter.ttk.Treeview 메서드)

tag_has() (tkinter.ttk.Treeview 메서드)

tagName (xml.dom.Element의 속성)

tail (xml.etree.ElementTree.Element의 속성)

take_snapshot() (tracemalloc 모듈)

takewhile() (itertools 모듈)

tan() (cmath 모듈)

(math 모듈)

tanh() (cmath 모듈)

(math 모듈)

TarError

TarFile (tarfile 클래스), [1]

tarfile (모듈)

tarfile command line option

--create <tarfile> <source1> ... <sourceN>

--extract <tarfile> [<output_dir>]

--list <tarfile>

--test <tarfile>

--verbose

-c <tarfile> <source1> ... <sourceN>

-e <tarfile> [<output_dir>]

-l <tarfile>

-t <tarfile>

-v

target

deletion

list, [1]

list assignment

list, deletion

loop control

target (xml.dom.ProcessingInstruction의 속성)

TarInfo (tarfile 클래스)

Task (asyncio 클래스)

task_done() (asyncio.Queue 메서드)

(multiprocessing.JoinableQueue 메서드)

(queue.Queue 메서드)

tau (cmath 모듈)

(math 모듈)

tb_frame (traceback attribute)

tb_lasti (traceback attribute)

tb_lineno (traceback attribute)

tb_locals (unittest.TestResult의 속성)

tb_next (traceback attribute)

tbreak (pdb command)

tcdrain() (termios 모듈)

tcflow() (termios 모듈)

tcflush() (termios 모듈)

tcgetattr() (termios 모듈)

tcgetpgrp() (os 모듈)

Tcl() (tkinter 모듈)

TCL_LIBRARY

TCPServer (socketserver 클래스)

tcsendbreak() (termios 모듈)

tcsetattr() (termios 모듈)

tcsetpgrp() (os 모듈)

tearDown() (unittest.TestCase 메서드)

tearDownClass() (unittest.TestCase 메서드)

tee() (itertools 모듈)

tell() (aifc.aifc 메서드), [1]

(chunk.Chunk 메서드)

(io.IOBase 메서드)

(io.TextIOBase 메서드)

(mmap.mmap 메서드)

(sunau.AU_read 메서드)

(sunau.AU_write 메서드)

(wave.Wave_read 메서드)

(wave.Wave_write 메서드)

Telnet (telnetlib 클래스)

telnetlib (모듈)

TEMP

temp_cwd() (test.support 모듈)

temp_dir() (test.support 모듈)

temp_umask() (test.support 모듈)

tempdir (tempfile 모듈)

tempfile (모듈)

Template (pipes 클래스)

(string 클래스)

template (string.Template의 속성)

temporary

file

file name

TemporaryDirectory() (tempfile 모듈)

TemporaryFile() (tempfile 모듈)

teredo (ipaddress.IPv6Address의 속성)

TERM, [1]

termattrs() (curses 모듈)

terminal_size (os 클래스)

terminate() (asyncio.asyncio.subprocess.Process 메서드)

(asyncio.SubprocessTransport 메서드)

(multiprocessing.pool.Pool 메서드)

(multiprocessing.Process 메서드)

(subprocess.Popen 메서드)

termination model

termios (모듈)

termname() (curses 모듈)

ternary

operator

test

identity

membership

test (doctest.DocTestFailure의 속성)

(doctest.UnexpectedException의 속성)

(모듈)

test() (cgi 모듈)

test.support (모듈)

test.support.script_helper (모듈)

TEST_DATA_DIR (test.support 모듈)

TEST_HOME_DIR (test.support 모듈)

TEST_HTTP_URL (test.support 모듈)

TEST_SUPPORT_DIR (test.support 모듈)

TestCase (unittest 클래스)

TestFailed

testfile() (doctest 모듈)

TESTFN (test.support 모듈)

TESTFN_ENCODING (test.support 모듈)

TESTFN_NONASCII (test.support 모듈)

TESTFN_UNDECODABLE (test.support 모듈)

TESTFN_UNENCODABLE (test.support 모듈)

TESTFN_UNICODE (test.support 모듈)

TestHandler (test.support 클래스)

TestLoader (unittest 클래스)

testMethodPrefix (unittest.TestLoader의 속성)

testmod() (doctest 모듈)

testNamePatterns (unittest.TestLoader의 속성)

TestResult (unittest 클래스)

tests (imghdr 모듈)

testsource() (doctest 모듈)

testsRun (unittest.TestResult의 속성)

TestSuite (unittest 클래스)

testzip() (zipfile.ZipFile 메서드)

text (msilib 모듈)

(traceback.TracebackException의 속성)

Text (typing 클래스)

text (xml.etree.ElementTree.Element의 속성)

text encoding (텍스트 인코딩)

text file (텍스트 파일)

text mode

text() (cgitb 모듈)

(msilib.Dialog 메서드)

text_factory (sqlite3.Connection의 속성)

Textbox (curses.textpad 클래스)

TextCalendar (calendar 클래스)

textdomain() (gettext 모듈)

(locale 모듈)

TextFile (distutils.text_file 클래스)

textinput() (turtle 모듈)

TextIO (typing 클래스)

TextIOBase (io 클래스)

TextIOWrapper (io 클래스)

TextTestResult (unittest 클래스)

TextTestRunner (unittest 클래스)

textwrap (모듈)

TextWrapper (textwrap 클래스)

theme_create() (tkinter.ttk.Style 메서드)

theme_names() (tkinter.ttk.Style 메서드)

theme_settings() (tkinter.ttk.Style 메서드)

theme_use() (tkinter.ttk.Style 메서드)

THOUSEP (locale 모듈)

Thread (threading 클래스)

thread() (imaplib.IMAP4 메서드)

thread_info (sys 모듈)

thread_time() (time 모듈)

thread_time_ns() (time 모듈)

threading (모듈)

threading_cleanup() (test.support 모듈)

threading_setup() (test.support 모듈)

ThreadingHTTPServer (http.server 클래스)

ThreadingMixIn (socketserver 클래스)

ThreadingTCPServer (socketserver 클래스)

ThreadingUDPServer (socketserver 클래스)

ThreadPool (multiprocessing.pool 클래스)

ThreadPoolExecutor (concurrent.futures 클래스)

threads

POSIX

throw (2to3 fixer)

throw() (coroutine 메서드)

(generator 메서드)

ticket_lifetime_hint (ssl.SSLSession의 속성)

tigetflag() (curses 모듈)

tigetnum() (curses 모듈)

tigetstr() (curses 모듈)

TILDE (token 모듈)

tilt() (turtle 모듈)

tiltangle() (turtle 모듈)

time (datetime 클래스)

(ssl.SSLSession의 속성)

(모듈)

time() (asyncio.loop 메서드)

(datetime.datetime 메서드)

(time 모듈)

Time2Internaldate() (imaplib 모듈)

time_ns() (time 모듈)

timedelta (datetime 클래스)

TimedRotatingFileHandler (logging.handlers 클래스)

timegm() (calendar 모듈)

timeit (모듈)

timeit command line option

--help

--number=N

--process

--repeat=N

--setup=S

--unit=U

--verbose

-h

-n N

-p

-r N

-s S

-u

-v

timeit() (timeit 모듈)

(timeit.Timer 메서드)

timeout

(socketserver.BaseServer의 속성)

(ssl.SSLSession의 속성)

(subprocess.TimeoutExpired의 속성)

timeout() (curses.window 메서드)

TIMEOUT_MAX (_thread 모듈)

(threading 모듈)

TimeoutError, [1], [2], [3]

TimeoutExpired

Timer (threading 클래스)

(timeit 클래스)

TimerHandle (asyncio 클래스)

times() (os 모듈)

TIMESTAMP (py_compile.PycInvalidationMode의 속성)

timestamp() (datetime.datetime 메서드)

timetuple() (datetime.date 메서드)

(datetime.datetime 메서드)

timetz() (datetime.datetime 메서드)

timezone (datetime 클래스)

(time 모듈)

title() (bytearray 메서드)

(bytes 메서드)

(str 메서드)

(turtle 모듈)

Tix

tix_addbitmapdir() (tkinter.tix.tixCommand 메서드)

tix_cget() (tkinter.tix.tixCommand 메서드)

tix_configure() (tkinter.tix.tixCommand 메서드)

tix_filedialog() (tkinter.tix.tixCommand 메서드)

tix_getbitmap() (tkinter.tix.tixCommand 메서드)

tix_getimage() (tkinter.tix.tixCommand 메서드)

tix_option_get() (tkinter.tix.tixCommand 메서드)

tix_resetoptions() (tkinter.tix.tixCommand 메서드)

tixCommand (tkinter.tix 클래스)

Tk

(tkinter 클래스)

(tkinter.tix 클래스)

Tk Option Data Types

TK_LIBRARY

Tkinter

tkinter (모듈)

tkinter.scrolledtext (모듈)

tkinter.tix (모듈)

tkinter.ttk (모듈)

TList (tkinter.tix 클래스)

TLS

TLSv1 (ssl.TLSVersion의 속성)

TLSv1_1 (ssl.TLSVersion의 속성)

TLSv1_2 (ssl.TLSVersion의 속성)

TLSv1_3 (ssl.TLSVersion의 속성)

TLSVersion (ssl 클래스)

TMP

TMPDIR

to_bytes() (int 메서드)

to_eng_string() (decimal.Context 메서드)

(decimal.Decimal 메서드)

to_integral() (decimal.Decimal 메서드)

to_integral_exact() (decimal.Context 메서드)

(decimal.Decimal 메서드)

to_integral_value() (decimal.Decimal 메서드)

to_sci_string() (decimal.Context 메서드)

ToASCII() (encodings.idna 모듈)

tobuf() (tarfile.TarInfo 메서드)

tobytes() (array.array 메서드)

(memoryview 메서드)

today() (datetime.datetime의 클래스 메서드)

(datetime.date의 클래스 메서드)

tofile() (array.array 메서드)

tok_name (token 모듈)

token

(shlex.shlex의 속성)

(모듈)

token_bytes() (secrets 모듈)

token_hex() (secrets 모듈)

token_urlsafe() (secrets 모듈)

TokenError

tokenize (모듈)

tokenize command line option

--exact

--help

-e

-h

tokenize() (tokenize 모듈)

tolist() (array.array 메서드)

(memoryview 메서드)

(parser.ST 메서드)

tomono() (audioop 모듈)

toordinal() (datetime.date 메서드)

(datetime.datetime 메서드)

top() (curses.panel.Panel 메서드)

(poplib.POP3 메서드)

top_panel() (curses.panel 모듈)

toprettyxml() (xml.dom.minidom.Node 메서드)

tostereo() (audioop 모듈)

tostring() (array.array 메서드)

(xml.etree.ElementTree 모듈)

tostringlist() (xml.etree.ElementTree 모듈)

total_changes (sqlite3.Connection의 속성)

total_ordering() (functools 모듈)

total_seconds() (datetime.timedelta 메서드)

totuple() (parser.ST 메서드)

touch() (pathlib.Path 메서드)

touchline() (curses.window 메서드)

touchwin() (curses.window 메서드)

tounicode() (array.array 메서드)

ToUnicode() (encodings.idna 모듈)

towards() (turtle 모듈)

toxml() (xml.dom.minidom.Node 메서드)

tp_as_async (C 멤버 변수)

tp_as_mapping (C 멤버 변수)

tp_as_number (C 멤버 변수)

tp_as_sequence (C 멤버 변수)

tparm() (curses 모듈)

trace

stack

Trace (trace 클래스)

(tracemalloc 클래스)

trace (모듈)

trace command line option

--count

--coverdir=<dir>

--file=<file>

--help

--ignore-dir=<dir>

--ignore-module=<mod>

--listfuncs

--missing

--no-report

--report

--summary

--timing

--trace

--trackcalls

--version

-c

-C

-f

-g

-l

-m

-r

-R

-s

-t

-T

trace function, [1], [2]

trace() (inspect 모듈)

trace_dispatch() (bdb.Bdb 메서드)

traceback

객체, [1], [2], [3], [4]

Traceback (tracemalloc 클래스)

traceback (tracemalloc.StatisticDiff의 속성)

(tracemalloc.Statistic의 속성)

(tracemalloc.Trace의 속성)

(모듈)

traceback_limit (tracemalloc.Snapshot의 속성)

(wsgiref.handlers.BaseHandler의 속성)

TracebackException (traceback 클래스)

tracebacklimit (sys 모듈)

tracebacks

in CGI scripts

TracebackType (types 클래스)

tracemalloc (모듈)

tracer() (turtle 모듈)

traces (tracemalloc.Snapshot의 속성)

trailing

comma

transfercmd() (ftplib.FTP 메서드)

transient_internet() (test.support 모듈)

TransientResource (test.support 클래스)

translate() (bytearray 메서드)

(bytes 메서드)

(fnmatch 모듈)

(str 메서드)

translation() (gettext 모듈)

Transport (asyncio 클래스)

transport (asyncio.StreamWriter의 속성)

Transport Layer Security

traverseproc (C 데이터 형식)

Tree (tkinter.tix 클래스)

TreeBuilder (xml.etree.ElementTree 클래스)

Treeview (tkinter.ttk 클래스)

triangular() (random 모듈)

triple-quoted string

(삼중 따옴표 된 문자열)

True, [1], [2]

true

True (내장 변수)

truediv() (operator 모듈)

trunc() (in module math)

(math 모듈)

truncate() (io.IOBase 메서드)

(os 모듈)

truth

value

truth() (operator 모듈)

try

글, [1], [2]

ttk

tty

I/O control

tty (모듈)

ttyname() (os 모듈)

tuple

empty, [1]

singleton

객체, [1], [2], [3], [4], [5], [6]

내장 함수, [1]

Tuple (typing 모듈)

tuple (내장 클래스)

tuple2st() (parser 모듈)

tuple_params (2to3 fixer)

Turtle (turtle 클래스)

turtle (모듈)

turtledemo (모듈)

turtles() (turtle 모듈)

TurtleScreen (turtle 클래스)

turtlesize() (turtle 모듈)

type

Boolean

data

hierarchy

immutable data

operations on dictionary

operations on list

객체, [1], [2]

내장 함수, [1], [2], [3]

type (optparse.Option의 속성)

(socket.socket의 속성)

(tarfile.TarInfo의 속성)

Type (typing 클래스)

type (urllib.request.Request의 속성)

(내장 클래스)

(형)

type alias (형 에일리어스)

type hint (형 힌트)

type of an object

type_check_only() (typing 모듈)

TYPE_CHECKER (optparse.Option의 속성)

TYPE_CHECKING (typing 모듈)

typeahead() (curses 모듈)

typecode (array.array의 속성)

typecodes (array 모듈)

TYPED_ACTIONS (optparse.Option의 속성)

typed_subpart_iterator() (email.iterators 모듈)

TypeError

예외

types

built-in

immutable sequence

mutable sequence

operations on integer

operations on mapping

operations on numeric

operations on sequence, [1]

모듈

types (2to3 fixer)

TYPES (optparse.Option의 속성)

types (모듈)

types, internal

types_map (mimetypes 모듈)

(mimetypes.MimeTypes의 속성)

types_map_inv (mimetypes.MimeTypes의 속성)

TypeVar (typing 클래스)

typing (모듈)

TZ, [1], [2], [3], [4], [5]

tzinfo (datetime 클래스)

(datetime.datetime의 속성)

(datetime.time의 속성)

tzname (time 모듈)

tzname() (datetime.datetime 메서드)

(datetime.time 메서드)

(datetime.timezone 메서드)

(datetime.tzinfo 메서드)

tzset() (time 모듈)

탐색

색인

모듈 |

Python »

3.7.17 Documentation »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

Python »

3.7.17 Documentation »

|

Index – U

u"

string literal

u'

string literal

u-LAW, [1], [2]

ucd_3_2_0 (unicodedata 모듈)

udata (select.kevent의 속성)

UDPServer (socketserver 클래스)

UF_APPEND (stat 모듈)

UF_COMPRESSED (stat 모듈)

UF_HIDDEN (stat 모듈)

UF_IMMUTABLE (stat 모듈)

UF_NODUMP (stat 모듈)

UF_NOUNLINK (stat 모듈)

UF_OPAQUE (stat 모듈)

uid (tarfile.TarInfo의 속성)

uid() (imaplib.IMAP4 메서드)

uidl() (poplib.POP3 메서드)

ulaw2lin() (audioop 모듈)

ULONG_MAX

umask() (os 모듈)

unalias (pdb command)

uname (tarfile.TarInfo의 속성)

uname() (os 모듈)

(platform 모듈)

unary

arithmetic operation

bitwise operation

UNARY_INVERT (opcode)

UNARY_NEGATIVE (opcode)

UNARY_NOT (opcode)

UNARY_POSITIVE (opcode)

unbinding

name

UnboundLocalError, [1]

unbuffered I/O

UNC paths

and os.makedirs()

UNCHECKED_HASH (py_compile.PycInvalidationMode의 속성)

unconsumed_tail (zlib.Decompress의 속성)

unctrl() (curses 모듈)

(curses.ascii 모듈)

undefine_macro() (distutils.ccompiler.CCompiler 메서드)

Underflow (decimal 클래스)

undisplay (pdb command)

undo() (turtle 모듈)

undobufferentries() (turtle 모듈)

undoc_header (cmd.Cmd의 속성)

unescape() (html 모듈)

(xml.sax.saxutils 모듈)

UnexpectedException

unexpectedSuccesses (unittest.TestResult의 속성)

unfreeze() (gc 모듈)

unget_wch() (curses 모듈)

ungetch() (curses 모듈)

(msvcrt 모듈)

ungetmouse() (curses 모듈)

ungetwch() (msvcrt 모듈)

unhexlify() (binascii 모듈)

Unicode, [1], [2]

database

unicode (2to3 fixer)

Unicode Consortium

unicodedata (모듈)

UnicodeDecodeError

UnicodeEncodeError

UnicodeError

UnicodeTranslateError

UnicodeWarning

unidata_version (unicodedata 모듈)

unified_diff() (difflib 모듈)

uniform() (random 모듈)

UnimplementedFileMode

Union (ctypes 클래스)

(typing 모듈)

union() (frozenset 메서드)

unique() (enum 모듈), [1]

unittest (모듈)

unittest command line option

--buffer

--catch

--failfast

--locals

-b

-c

-f

-k

unittest-discover command line option

--pattern pattern

--start-directory directory

--top-level-directory directory

--verbose

-p

-s

-t

-v

unittest.mock (모듈)

universal newlines

bytearray.splitlines method

bytes.splitlines method

csv.reader function

importlib.abc.InspectLoader.get_source method

io.IncrementalNewlineDecoder class

io.TextIOWrapper class

open() built-in function

str.splitlines method

subprocess module

What's new, [1], [2], [3]

universal newlines (유니버설 줄 넘김)

UNIX

file control

I/O control

unix_dialect (csv 클래스)

unix_shell (test.support 모듈)

UnixDatagramServer (socketserver 클래스)

UnixStreamServer (socketserver 클래스)

unknown (uuid.SafeUUID의 속성)

unknown_decl() (html.parser.HTMLParser 메서드)

unknown_open() (urllib.request.BaseHandler 메서드)

(urllib.request.UnknownHandler 메서드)

UnknownHandler (urllib.request 클래스)

UnknownProtocol

UnknownTransferEncoding

unlink() (os 모듈)

(pathlib.Path 메서드)

(test.support 모듈)

(xml.dom.minidom.Node 메서드)

unload() (test.support 모듈)

unlock() (mailbox.Babyl 메서드)

(mailbox.Mailbox 메서드)

(mailbox.Maildir 메서드)

(mailbox.mbox 메서드)

(mailbox.MH 메서드)

(mailbox.MMDF 메서드)

unpack() (struct 모듈)

(struct.Struct 메서드)

unpack_archive() (shutil 모듈)

unpack_array() (xdrlib.Unpacker 메서드)

unpack_bytes() (xdrlib.Unpacker 메서드)

unpack_double() (xdrlib.Unpacker 메서드)

UNPACK_EX (opcode)

unpack_farray() (xdrlib.Unpacker 메서드)

unpack_float() (xdrlib.Unpacker 메서드)

unpack_fopaque() (xdrlib.Unpacker 메서드)

unpack_from() (struct 모듈)

(struct.Struct 메서드)

unpack_fstring() (xdrlib.Unpacker 메서드)

unpack_list() (xdrlib.Unpacker 메서드)

unpack_opaque() (xdrlib.Unpacker 메서드)

UNPACK_SEQUENCE (opcode)

unpack_string() (xdrlib.Unpacker 메서드)

Unpacker (xdrlib 클래스)

unpacking

dictionary

in function calls

iterable

unparsedEntityDecl() (xml.sax.handler.DTDHandler 메서드)

UnparsedEntityDeclHandler() (xml.parsers.expat.xmlparser 메서드)

Unpickler (pickle 클래스)

UnpicklingError

unquote() (email.utils 모듈)

(urllib.parse 모듈)

unquote_plus() (urllib.parse 모듈)

unquote_to_bytes() (urllib.parse 모듈)

unreachable object

unreadline() (distutils.text_file.TextFile 메서드)

unrecognized escape sequence

unregister() (atexit 모듈)

(faulthandler 모듈)

(select.devpoll 메서드)

(select.epoll 메서드)

(select.poll 메서드)

(selectors.BaseSelector의 메서드)

unregister_archive_format() (shutil 모듈)

unregister_dialect() (csv 모듈)

unregister_unpack_format() (shutil 모듈)

unsafe (uuid.SafeUUID의 속성)

unset() (test.support.EnvironmentVarGuard 메서드)

unsetenv() (os 모듈)

UnstructuredHeader (email.headerregistry 클래스)

unsubscribe() (imaplib.IMAP4 메서드)

UnsupportedOperation

until (pdb command)

untokenize() (tokenize 모듈)

untouchwin() (curses.window 메서드)

unused_data (bz2.BZ2Decompressor의 속성)

(lzma.LZMADecompressor의 속성)

(zlib.Decompress의 속성)

unverifiable (urllib.request.Request의 속성)

unwrap() (inspect 모듈)

(ssl.SSLSocket 메서드)

up (pdb command)

up() (turtle 모듈)

update() (collections.Counter 메서드)

(dict 메서드)

(frozenset 메서드)

(hashlib.hash 메서드)

(hmac.HMAC 메서드)

(http.cookies.Morsel 메서드)

(mailbox.Mailbox 메서드)

(mailbox.Maildir 메서드)

(trace.CoverageResults 메서드)

(turtle 모듈)

update_authenticated() (urllib.request.HTTPPasswordMgrWithPriorAuth 메서드)

update_lines_cols() (curses 모듈)

update_panels() (curses.panel 모듈)

update_visible() (mailbox.BabylMessage 메서드)

update_wrapper() (functools 모듈)

upper() (bytearray 메서드)

(bytes 메서드)

(str 메서드)

urandom() (os 모듈)

URL, [1], [2], [3]

parsing

relative

url (xmlrpc.client.ProtocolError의 속성)

url2pathname() (urllib.request 모듈)

urlcleanup() (urllib.request 모듈)

urldefrag() (urllib.parse 모듈)

urlencode() (urllib.parse 모듈)

URLError

urljoin() (urllib.parse 모듈)

urllib (2to3 fixer)

(모듈)

urllib.error (모듈)

urllib.parse (모듈)

urllib.request

모듈

urllib.request (모듈)

urllib.response (모듈)

urllib.robotparser (모듈)

urlopen() (urllib.request 모듈)

URLopener (urllib.request 클래스)

urlparse() (urllib.parse 모듈)

urlretrieve() (urllib.request 모듈)

urlsafe_b64decode() (base64 모듈)

urlsafe_b64encode() (base64 모듈)

urlsplit() (urllib.parse 모듈)

urlunparse() (urllib.parse 모듈)

urlunsplit() (urllib.parse 모듈)

urn (uuid.UUID의 속성)

use_default_colors() (curses 모듈)

use_env() (curses 모듈)

use_rawinput (cmd.Cmd의 속성)

UseForeignDTD() (xml.parsers.expat.xmlparser 메서드)

USER

user

effective id

id

id, setting

user() (poplib.POP3 메서드)

user-defined

function

function call

method

user-defined function

객체, [1], [2]

user-defined method

객체

USER_BASE

(site 모듈)

user_call() (bdb.Bdb 메서드)

user_exception() (bdb.Bdb 메서드)

user_line() (bdb.Bdb 메서드)

user_return() (bdb.Bdb 메서드)

USER_SITE (site 모듈)

usercustomize

모듈

UserDict (collections 클래스)

UserList (collections 클래스)

USERNAME, [1]

username (email.headerregistry.Address의 속성)

USERPROFILE, [1]

userptr() (curses.panel.Panel 메서드)

UserString (collections 클래스)

UserWarning

USTAR_FORMAT (tarfile 모듈)

UTC

utc (datetime.timezone의 속성)

utcfromtimestamp() (datetime.datetime의 클래스 메서드)

utcnow() (datetime.datetime의 클래스 메서드)

utcoffset() (datetime.datetime 메서드)

(datetime.time 메서드)

(datetime.timezone 메서드)

(datetime.tzinfo 메서드)

utctimetuple() (datetime.datetime 메서드)

utf8 (email.policy.EmailPolicy의 속성)

utf8() (poplib.POP3 메서드)

utf8_enabled (imaplib.IMAP4의 속성)

utime() (os 모듈)

uu

모듈

uu (모듈)

UUID (uuid 클래스)

uuid (모듈)

uuid1

uuid1() (uuid 모듈)

uuid3

uuid3() (uuid 모듈)

uuid4

uuid4() (uuid 모듈)

uuid5

uuid5() (uuid 모듈)

UuidCreate() (msilib 모듈)

탐색

색인

모듈 |

Python »

3.7.17 Documentation »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

Python »

3.7.17 Documentation »

|

Index – V

v4_int_to_packed() (ipaddress 모듈)

v6_int_to_packed() (ipaddress 모듈)

validator() (wsgiref.validate 모듈)

value

default parameter

truth

value (ctypes._SimpleCData의 속성)

(http.cookiejar.Cookie의 속성)

(http.cookies.Morsel의 속성)

(xml.dom.Attr의 속성)

value of an object

Value() (multiprocessing 모듈)

(multiprocessing.managers.SyncManager 메서드)

(multiprocessing.sharedctypes 모듈)

value_decode() (http.cookies.BaseCookie 메서드)

value_encode() (http.cookies.BaseCookie 메서드)

ValueError

예외

valuerefs() (weakref.WeakValueDictionary 메서드)

values

Boolean

writing

values() (contextvars.Context 메서드)

(dict 메서드)

(email.message.EmailMessage 메서드)

(email.message.Message 메서드)

(mailbox.Mailbox 메서드)

(types.MappingProxyType 메서드)

ValuesView (collections.abc 클래스)

(typing 클래스)

var (contextvars.contextvars.Token.Token의 속성)

variable

free

variable annotation (변수 어노테이션)

variance() (statistics 모듈)

variant (uuid.UUID의 속성)

vars() (내장 함수)

vbar (tkinter.scrolledtext.ScrolledText의 속성)

VBAR (token 모듈)

VBAREQUAL (token 모듈)

Vec2D (turtle 클래스)

venv (모듈)

VERBOSE (re 모듈)

verbose (tabnanny 모듈)

(test.support 모듈)

verify() (smtplib.SMTP 메서드)

verify_client_post_handshake() (ssl.SSLSocket 메서드)

verify_code (ssl.SSLCertVerificationError의 속성)

VERIFY_CRL_CHECK_CHAIN (ssl 모듈)

VERIFY_CRL_CHECK_LEAF (ssl 모듈)

VERIFY_DEFAULT (ssl 모듈)

verify_flags (ssl.SSLContext의 속성)

verify_message (ssl.SSLCertVerificationError의 속성)

verify_mode (ssl.SSLContext의 속성)

verify_request() (socketserver.BaseServer 메서드)

VERIFY_X509_STRICT (ssl 모듈)

VERIFY_X509_TRUSTED_FIRST (ssl 모듈)

VerifyFlags (ssl 클래스)

VerifyMode (ssl 클래스)

version (curses 모듈)

(email.headerregistry.MIMEVersionHeader의 속성)

(http.client.HTTPResponse의 속성)

(http.cookiejar.Cookie의 속성)

(in module sys), [1], [2]

(ipaddress.IPv4Address의 속성)

(ipaddress.IPv4Network의 속성)

(ipaddress.IPv6Address의 속성)

(ipaddress.IPv6Network의 속성)

(marshal 모듈)

(sqlite3 모듈)

(sys 모듈)

(urllib.request.URLopener의 속성)

(uuid.UUID의 속성)

version() (ensurepip 모듈)

(platform 모듈)

(ssl.SSLSocket 메서드)

version_info (sqlite3 모듈)

(sys 모듈)

version_string() (http.server.BaseHTTPRequestHandler 메서드)

vformat() (string.Formatter 메서드)

virtual

Environments

virtual environment (가상 환경)

virtual machine (가상 기계)

visit() (ast.NodeVisitor 메서드)

visitproc (C 데이터 형식)

vline() (curses.window 메서드)

voidcmd() (ftplib.FTP 메서드)

volume (zipfile.ZipInfo의 속성)

vonmisesvariate() (random 모듈)

탐색

색인

모듈 |

Python »

3.7.17 Documentation »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

Python »

3.7.17 Documentation »

|

Index – W

W_OK (os 모듈)

wait() (asyncio 모듈)

(asyncio.asyncio.subprocess.Process의 메서드)

(asyncio.Condition의 메서드)

(asyncio.Event의 메서드)

(concurrent.futures 모듈)

(multiprocessing.connection 모듈)

(multiprocessing.pool.AsyncResult 메서드)

(os 모듈)

(subprocess.Popen 메서드)

(threading.Barrier 메서드)

(threading.Condition 메서드)

(threading.Event 메서드)

wait3() (os 모듈)

wait4() (os 모듈)

wait_closed() (asyncio.Server의 메서드)

(asyncio.StreamWriter의 메서드)

wait_for() (asyncio 모듈)

(asyncio.Condition의 메서드)

(threading.Condition 메서드)

wait_threads_exit() (test.support 모듈)

waitid() (os 모듈)

waitpid() (os 모듈)

walk() (ast 모듈)

(email.message.EmailMessage 메서드)

(email.message.Message 메서드)

(os 모듈)

walk_packages() (pkgutil 모듈)

walk_stack() (traceback 모듈)

walk_tb() (traceback 모듈)

want (doctest.Example의 속성)

warn() (distutils.ccompiler.CCompiler 메서드)

(distutils.text_file.TextFile 메서드)

(warnings 모듈)

warn_explicit() (warnings 모듈)

Warning, [1]

warning() (logging 모듈)

(logging.Logger 메서드)

(xml.sax.handler.ErrorHandler 메서드)

warnings

(모듈)

WarningsRecorder (test.support 클래스)

warnoptions (sys 모듈)

wasSuccessful() (unittest.TestResult 메서드)

WatchedFileHandler (logging.handlers 클래스)

wave (모듈)

WCONTINUED (os 모듈)

WCOREDUMP() (os 모듈)

WeakKeyDictionary (weakref 클래스)

WeakMethod (weakref 클래스)

weakref (모듈)

WeakSet (weakref 클래스)

WeakValueDictionary (weakref 클래스)

webbrowser (모듈)

weekday() (calendar 모듈)

(datetime.date 메서드)

(datetime.datetime 메서드)

weekheader() (calendar 모듈)

weibullvariate() (random 모듈)

WEXITED (os 모듈)

WEXITSTATUS() (os 모듈)

wfile (http.server.BaseHTTPRequestHandler의 속성)

what() (imghdr 모듈)

(sndhdr 모듈)

whathdr() (sndhdr 모듈)

whatis (pdb command)

when() (asyncio.TimerHandle 메서드)

where (pdb command)

which() (shutil 모듈)

whichdb() (dbm 모듈)

while

글, [1], [2], [3]

whitespace (shlex.shlex의 속성)

(string 모듈)

whitespace_split (shlex.shlex의 속성)

Widget (tkinter.ttk 클래스)

width (textwrap.TextWrapper의 속성)

width() (turtle 모듈)

WIFCONTINUED() (os 모듈)

WIFEXITED() (os 모듈)

WIFSIGNALED() (os 모듈)

WIFSTOPPED() (os 모듈)

win32_ver() (platform 모듈)

WinDLL (ctypes 클래스)

window manager (widgets)

window() (curses.panel.Panel 메서드)

window_height() (turtle 모듈)

window_width() (turtle 모듈)

Windows

Windows ini file

WindowsError

WindowsPath (pathlib 클래스)

WindowsProactorEventLoopPolicy (asyncio 클래스)

WindowsRegistryFinder (importlib.machinery 클래스)

winerror (OSError의 속성)

WinError() (ctypes 모듈)

WINFUNCTYPE() (ctypes 모듈)

winreg (모듈)

WinSock

winsound (모듈)

winver (sys 모듈)

with

글, [1]

WITH_CLEANUP_FINISH (opcode)

WITH_CLEANUP_START (opcode)

with_hostmask (ipaddress.IPv4Interface의 속성)

(ipaddress.IPv4Network의 속성)

(ipaddress.IPv6Interface의 속성)

(ipaddress.IPv6Network의 속성)

with_name() (pathlib.PurePath 메서드)

with_netmask (ipaddress.IPv4Interface의 속성)

(ipaddress.IPv4Network의 속성)

(ipaddress.IPv6Interface의 속성)

(ipaddress.IPv6Network의 속성)

with_prefixlen (ipaddress.IPv4Interface의 속성)

(ipaddress.IPv4Network의 속성)

(ipaddress.IPv6Interface의 속성)

(ipaddress.IPv6Network의 속성)

with_pymalloc() (test.support 모듈)

with_suffix() (pathlib.PurePath 메서드)

with_traceback() (BaseException 메서드)

WNOHANG (os 모듈)

WNOWAIT (os 모듈)

wordchars (shlex.shlex의 속성)

World Wide Web, [1], [2]

wrap() (textwrap 모듈)

(textwrap.TextWrapper 메서드)

wrap_bio() (ssl.SSLContext 메서드)

wrap_future() (asyncio 모듈)

wrap_socket() (ssl 모듈)

(ssl.SSLContext 메서드)

wrap_text() (distutils.fancy_getopt 모듈)

wrapper() (curses 모듈)

WrapperDescriptorType (types 모듈)

wraps() (functools 모듈)

WRITABLE (tkinter 모듈)

writable() (asyncore.dispatcher 메서드)

(io.IOBase 메서드)

write() (asyncio.StreamWriter 메서드)

(asyncio.WriteTransport 메서드)

(code.InteractiveInterpreter 메서드)

(codecs.StreamWriter 메서드)

(configparser.ConfigParser 메서드)

(email.generator.BytesGenerator 메서드)

(email.generator.Generator 메서드)

(io.BufferedIOBase 메서드)

(io.BufferedWriter 메서드)

(io.RawIOBase 메서드)

(io.TextIOBase 메서드)

(mmap.mmap 메서드)

(os 모듈)

(ossaudiodev.oss_audio_device 메서드)

(ssl.MemoryBIO 메서드)

(ssl.SSLSocket 메서드)

(telnetlib.Telnet 메서드)

(turtle 모듈)

(xml.etree.ElementTree.ElementTree 메서드)

(zipfile.ZipFile 메서드)

write_byte() (mmap.mmap 메서드)

write_bytes() (pathlib.Path 메서드)

write_docstringdict() (turtle 모듈)

write_eof() (asyncio.StreamWriter 메서드)

(asyncio.WriteTransport 메서드)

(ssl.MemoryBIO 메서드)

write_file() (distutils.file_util 모듈)

write_history_file() (readline 모듈)

WRITE_RESTRICTED

write_results() (trace.CoverageResults 메서드)

write_text() (pathlib.Path 메서드)

write_through (io.TextIOWrapper의 속성)

writeall() (ossaudiodev.oss_audio_device 메서드)

writeframes() (aifc.aifc 메서드)

(sunau.AU_write 메서드)

(wave.Wave_write 메서드)

writeframesraw() (aifc.aifc 메서드)

(sunau.AU_write 메서드)

(wave.Wave_write 메서드)

writeheader() (csv.DictWriter 메서드)

writelines() (asyncio.StreamWriter 메서드)

(asyncio.WriteTransport 메서드)

(codecs.StreamWriter 메서드)

(io.IOBase 메서드)

writePlist() (plistlib 모듈)

writePlistToBytes() (plistlib 모듈)

writepy() (zipfile.PyZipFile 메서드)

writer (formatter.formatter의 속성)

writer() (csv 모듈)

writerow() (csv.csvwriter 메서드)

writerows() (csv.csvwriter 메서드)

writestr() (zipfile.ZipFile 메서드)

WriteTransport (asyncio 클래스)

writev() (os 모듈)

writexml() (xml.dom.minidom.Node 메서드)

writing

values

WrongDocumentErr

ws_comma (2to3 fixer)

wsgi_file_wrapper (wsgiref.handlers.BaseHandler의 속성)

wsgi_multiprocess (wsgiref.handlers.BaseHandler의 속성)

wsgi_multithread (wsgiref.handlers.BaseHandler의 속성)

wsgi_run_once (wsgiref.handlers.BaseHandler의 속성)

wsgiref (모듈)

wsgiref.handlers (모듈)

wsgiref.headers (모듈)

wsgiref.simple_server (모듈)

wsgiref.util (모듈)

wsgiref.validate (모듈)

WSGIRequestHandler (wsgiref.simple_server 클래스)

WSGIServer (wsgiref.simple_server 클래스)

wShowWindow (subprocess.STARTUPINFO의 속성)

WSTOPPED (os 모듈)

WSTOPSIG() (os 모듈)

wstring_at() (ctypes 모듈)

WTERMSIG() (os 모듈)

WUNTRACED (os 모듈)

WWW, [1], [2]

server, [1]

탐색

색인

모듈 |

Python »

3.7.17 Documentation »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

Python »

3.7.17 Documentation »

|

Index – X

X (re 모듈)

X509 certificate

X_OK (os 모듈)

xatom() (imaplib.IMAP4 메서드)

XATTR_CREATE (os 모듈)

XATTR_REPLACE (os 모듈)

XATTR_SIZE_MAX (os 모듈)

xcor() (turtle 모듈)

XDR

xdrlib (모듈)

xhdr() (nntplib.NNTP 메서드)

XHTML

XHTML_NAMESPACE (xml.dom 모듈)

xml (모듈)

XML() (xml.etree.ElementTree 모듈)

xml.dom (모듈)

xml.dom.minidom (모듈)

xml.dom.pulldom (모듈)

xml.etree.ElementInclude.default_loader() (xml.etree.ElementTree 모듈)

xml.etree.ElementInclude.include() (xml.etree.ElementTree 모듈)

xml.etree.ElementTree (모듈)

xml.parsers.expat (모듈)

xml.parsers.expat.errors (모듈)

xml.parsers.expat.model (모듈)

xml.sax (모듈)

xml.sax.handler (모듈)

xml.sax.saxutils (모듈)

xml.sax.xmlreader (모듈)

XML_ERROR_ABORTED (xml.parsers.expat.errors 모듈)

XML_ERROR_ASYNC_ENTITY (xml.parsers.expat.errors 모듈)

XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF (xml.parsers.expat.errors 모듈)

XML_ERROR_BAD_CHAR_REF (xml.parsers.expat.errors 모듈)

XML_ERROR_BINARY_ENTITY_REF (xml.parsers.expat.errors 모듈)

XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING (xml.parsers.expat.errors 모듈)

XML_ERROR_DUPLICATE_ATTRIBUTE (xml.parsers.expat.errors 모듈)

XML_ERROR_ENTITY_DECLARED_IN_PE (xml.parsers.expat.errors 모듈)

XML_ERROR_EXTERNAL_ENTITY_HANDLING (xml.parsers.expat.errors 모듈)

XML_ERROR_FEATURE_REQUIRES_XML_DTD (xml.parsers.expat.errors 모듈)

XML_ERROR_FINISHED (xml.parsers.expat.errors 모듈)

XML_ERROR_INCOMPLETE_PE (xml.parsers.expat.errors 모듈)

XML_ERROR_INCORRECT_ENCODING (xml.parsers.expat.errors 모듈)

XML_ERROR_INVALID_TOKEN (xml.parsers.expat.errors 모듈)

XML_ERROR_JUNK_AFTER_DOC_ELEMENT (xml.parsers.expat.errors 모듈)

XML_ERROR_MISPLACED_XML_PI (xml.parsers.expat.errors 모듈)

XML_ERROR_NO_ELEMENTS (xml.parsers.expat.errors 모듈)

XML_ERROR_NO_MEMORY (xml.parsers.expat.errors 모듈)

XML_ERROR_NOT_STANDALONE (xml.parsers.expat.errors 모듈)

XML_ERROR_NOT_SUSPENDED (xml.parsers.expat.errors 모듈)

XML_ERROR_PARAM_ENTITY_REF (xml.parsers.expat.errors 모듈)

XML_ERROR_PARTIAL_CHAR (xml.parsers.expat.errors 모듈)

XML_ERROR_PUBLICID (xml.parsers.expat.errors 모듈)

XML_ERROR_RECURSIVE_ENTITY_REF (xml.parsers.expat.errors 모듈)

XML_ERROR_SUSPEND_PE (xml.parsers.expat.errors 모듈)

XML_ERROR_SUSPENDED (xml.parsers.expat.errors 모듈)

XML_ERROR_SYNTAX (xml.parsers.expat.errors 모듈)

XML_ERROR_TAG_MISMATCH (xml.parsers.expat.errors 모듈)

XML_ERROR_TEXT_DECL (xml.parsers.expat.errors 모듈)

XML_ERROR_UNBOUND_PREFIX (xml.parsers.expat.errors 모듈)

XML_ERROR_UNCLOSED_CDATA_SECTION (xml.parsers.expat.errors 모듈)

XML_ERROR_UNCLOSED_TOKEN (xml.parsers.expat.errors 모듈)

XML_ERROR_UNDECLARING_PREFIX (xml.parsers.expat.errors 모듈)

XML_ERROR_UNDEFINED_ENTITY (xml.parsers.expat.errors 모듈)

XML_ERROR_UNEXPECTED_STATE (xml.parsers.expat.errors 모듈)

XML_ERROR_UNKNOWN_ENCODING (xml.parsers.expat.errors 모듈)

XML_ERROR_XML_DECL (xml.parsers.expat.errors 모듈)

XML_NAMESPACE (xml.dom 모듈)

xmlcharrefreplace_errors() (codecs 모듈)

XmlDeclHandler() (xml.parsers.expat.xmlparser 메서드)

XMLFilterBase (xml.sax.saxutils 클래스)

XMLGenerator (xml.sax.saxutils 클래스)

XMLID() (xml.etree.ElementTree 모듈)

XMLNS_NAMESPACE (xml.dom 모듈)

XMLParser (xml.etree.ElementTree 클래스)

XMLParserType (xml.parsers.expat 모듈)

XMLPullParser (xml.etree.ElementTree 클래스)

XMLReader (xml.sax.xmlreader 클래스)

xmlrpc.client (모듈)

xmlrpc.server (모듈)

xor

bitwise

xor() (operator 모듈)

xover() (nntplib.NNTP 메서드)

xpath() (nntplib.NNTP 메서드)

xrange (2to3 fixer)

xreadlines (2to3 fixer)

xview() (tkinter.ttk.Treeview 메서드)

탐색

색인

모듈 |

Python »

3.7.17 Documentation »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

Python »

3.7.17 Documentation »

|

Index – Y

ycor() (turtle 모듈)

year (datetime.datetime의 속성)

(datetime.date의 속성)

Year 2038

yeardatescalendar() (calendar.Calendar 메서드)

yeardays2calendar() (calendar.Calendar 메서드)

yeardayscalendar() (calendar.Calendar 메서드)

YESEXPR (locale 모듈)

yield

examples

expression

yield from (in What's New)

글

키워드

YIELD_FROM (opcode)

YIELD_VALUE (opcode)

yiq_to_rgb() (colorsys 모듈)

yview() (tkinter.ttk.Treeview 메서드)

탐색

색인

모듈 |

Python »

3.7.17 Documentation »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

Python »

3.7.17 Documentation »

|

Index – Z

Zen of Python (파이썬 젠)

ZeroDivisionError

예외

zfill() (bytearray 메서드)

(bytes 메서드)

(str 메서드)

zip (2to3 fixer)

zip() (내장 함수)

ZIP_BZIP2 (zipfile 모듈)

ZIP_DEFLATED (zipfile 모듈)

zip_longest() (itertools 모듈)

ZIP_LZMA (zipfile 모듈)

ZIP_STORED (zipfile 모듈)

zipapp (모듈)

zipapp command line option

--compress

--help

--info

--main=<mainfn>

--output=<output>

--python=<interpreter>

-c

-h

-m <mainfn>

-o <output>

-p <interpreter>

ZipFile (zipfile 클래스)

zipfile (모듈)

zipfile command line option

--create <zipfile> <source1> ... <sourceN>

--extract <zipfile> <output_dir>

--list <zipfile>

--test <zipfile>

-c <zipfile> <source1> ... <sourceN>

-e <zipfile> <output_dir>

-l <zipfile>

-t <zipfile>

zipimport (모듈)

zipimporter (zipimport 클래스)

ZipImportError

ZipInfo (zipfile 클래스)

zlib (모듈)

ZLIB_RUNTIME_VERSION (zlib 모듈)

ZLIB_VERSION (zlib 모듈)

탐색

색인

모듈 |

Python »

3.7.17 Documentation »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

Python »

3.7.17 Documentation »

|

Index – _

_ (underscore)

gettext

in numeric literal, [1]

in string formatting

_, identifiers

__, identifiers

__abs__() (object 메서드)

(operator 모듈)

__add__() (object 메서드)

(operator 모듈)

__aenter__() (object 메서드)

__aexit__() (object 메서드)

__aiter__() (object 메서드)

__all__

(optional module attribute)

(package variable)

__and__() (object 메서드)

(operator 모듈)

__anext__() (agen 메서드)

(object 메서드)

__annotations__ (class attribute)

(function attribute)

(module attribute)

__await__() (object 메서드)

__bases__ (class attribute)

(class의 속성)

__bool__() (object method)

(object 메서드)

__breakpointhook__ (sys 모듈)

__bytes__() (email.message.EmailMessage 메서드)

(email.message.Message 메서드)

(object 메서드)

__cached__

__call__() (email.headerregistry.HeaderRegistry 메서드)

(object method)

(object 메서드)

(weakref.finalize 메서드)

__callback__ (weakref.ref의 속성)

__cause__ (exception attribute)

(traceback.TracebackException의 속성)

__ceil__() (fractions.Fraction 메서드)

(object 메서드)

__class__ (instance attribute)

(instance의 속성)

(method cell)

(module attribute)

(unittest.mock.Mock의 속성)

__class_getitem__() (object의 클래스 메서드)

__classcell__ (class namespace entry)

__closure__ (function attribute)

__code__ (function attribute)

(function object attribute)

__complex__() (object 메서드)

__concat__() (operator 모듈)

__contains__() (email.message.EmailMessage 메서드)

(email.message.Message 메서드)

(mailbox.Mailbox 메서드)

(object 메서드)

(operator 모듈)

__context__ (exception attribute)

(traceback.TracebackException의 속성)

__copy__() (copy protocol)

__debug__

(내장 변수)

__deepcopy__() (copy protocol)

__defaults__ (function attribute)

__del__() (io.IOBase 메서드)

(object 메서드)

__delattr__() (object 메서드)

__delete__() (object 메서드)

__delitem__() (email.message.EmailMessage 메서드)

(email.message.Message 메서드)

(mailbox.Mailbox 메서드)

(mailbox.MH 메서드)

(object 메서드)

(operator 모듈)

__dict__ (class attribute)

(function attribute)

(instance attribute)

(module attribute), [1]

(object의 속성)

__dir__ (module attribute)

__dir__() (object 메서드)

(unittest.mock.Mock 메서드)

__displayhook__ (sys 모듈)

__divmod__() (object 메서드)

__doc__ (class attribute)

(function attribute)

(method attribute)

(module attribute), [1]

(types.ModuleType의 속성)

__enter__() (contextmanager 메서드)

(object 메서드)

(winreg.PyHKEY 메서드)

__eq__() (email.charset.Charset 메서드)

(email.header.Header 메서드)

(instance method)

(memoryview 메서드)

(object 메서드)

(operator 모듈)

__excepthook__ (sys 모듈)

__exit__() (contextmanager 메서드)

(object 메서드)

(winreg.PyHKEY 메서드)

__file__

(module attribute), [1], [2]

__float__() (object 메서드)

__floor__() (fractions.Fraction 메서드)

(object 메서드)

__floordiv__() (object 메서드)

(operator 모듈)

__format__

__format__() (datetime.date 메서드)

(datetime.datetime 메서드)

(datetime.time 메서드)

(object 메서드)

__fspath__() (os.PathLike의 메서드)

__func__ (method attribute)

__future__

future statement

__future__ (모듈)

__ge__() (instance method)

(object 메서드)

(operator 모듈)

__get__() (object 메서드)

__getattr__ (module attribute)

__getattr__() (object 메서드)

__getattribute__() (object 메서드)

__getitem__() (email.headerregistry.HeaderRegistry 메서드)

(email.message.EmailMessage 메서드)

(email.message.Message 메서드)

(mailbox.Mailbox 메서드)

(mapping object method)

(object 메서드)

(operator 모듈)

(re.Match 메서드)

__getnewargs__() (object 메서드)

__getnewargs_ex__() (object 메서드)

__getstate__() (copy protocol)

(object 메서드)

__globals__ (function attribute)

__gt__() (instance method)

(object 메서드)

(operator 모듈)

__hash__() (object 메서드)

__iadd__() (object 메서드)

(operator 모듈)

__iand__() (object 메서드)

(operator 모듈)

__iconcat__() (operator 모듈)

__ifloordiv__() (object 메서드)

(operator 모듈)

__ilshift__() (object 메서드)

(operator 모듈)

__imatmul__() (object 메서드)

(operator 모듈)

__imod__() (object 메서드)

(operator 모듈)

__import__

내장 함수

__import__() (importlib 모듈)

(내장 함수)

__imul__() (object 메서드)

(operator 모듈)

__index__() (object 메서드)

(operator 모듈)

__init__() (difflib.HtmlDiff 메서드)

(logging.Handler 메서드)

(logging.logging.Formatter 메서드)

(object 메서드)

__init_subclass__() (object의 클래스 메서드)

__instancecheck__() (class 메서드)

__int__() (object 메서드)

__interactivehook__ (sys 모듈)

__inv__() (operator 모듈)

__invert__() (object 메서드)

(operator 모듈)

__ior__() (object 메서드)

(operator 모듈)

__ipow__() (object 메서드)

(operator 모듈)

__irshift__() (object 메서드)

(operator 모듈)

__isub__() (object 메서드)

(operator 모듈)

__iter__() (container 메서드)

(iterator 메서드)

(mailbox.Mailbox 메서드)

(object 메서드)

(unittest.TestSuite 메서드)

__itruediv__() (object 메서드)

(operator 모듈)

__ixor__() (object 메서드)

(operator 모듈)

__kwdefaults__ (function attribute)

__le__() (instance method)

(object 메서드)

(operator 모듈)

__len__() (email.message.EmailMessage 메서드)

(email.message.Message 메서드)

(mailbox.Mailbox 메서드)

(mapping object method)

(object 메서드)

__length_hint__() (object 메서드)

__loader__

(module attribute)

(types.ModuleType의 속성)

__lshift__() (object 메서드)

(operator 모듈)

__lt__() (instance method)

(object 메서드)

(operator 모듈)

__main__

모듈, [1], [2], [3], [4], [5], [6], [7]

__main__ (모듈)

__matmul__() (object 메서드)

(operator 모듈)

__missing__()

(collections.defaultdict 메서드)

(object 메서드)

__mod__() (object 메서드)

(operator 모듈)

__module__ (class attribute)

(function attribute)

(method attribute)

__mro__ (class의 속성)

__mul__() (object 메서드)

(operator 모듈)

__name__

(class attribute)

(definition의 속성)

(function attribute)

(method attribute)

(module attribute), [1], [2]

(types.ModuleType의 속성)

__ne__() (email.charset.Charset 메서드)

(email.header.Header 메서드)

(instance method)

(object 메서드)

(operator 모듈)

__neg__() (object 메서드)

(operator 모듈)

__new__() (object 메서드)

__next__() (csv.csvreader 메서드)

(generator 메서드)

(iterator 메서드)

__not__() (operator 모듈)

__or__() (object 메서드)

(operator 모듈)

__package__

(module attribute)

(types.ModuleType의 속성)

__path__

__pos__() (object 메서드)

(operator 모듈)

__pow__() (object 메서드)

(operator 모듈)

__prepare__ (metaclass method)

__qualname__ (definition의 속성)

__radd__() (object 메서드)

__rand__() (object 메서드)

__rdivmod__() (object 메서드)

__reduce__() (object 메서드)

__reduce_ex__() (object 메서드)

__repr__() (multiprocessing.managers.BaseProxy 메서드)

(netrc.netrc 메서드)

(object 메서드)

__reversed__() (object 메서드)

__rfloordiv__() (object 메서드)

__rlshift__() (object 메서드)

__rmatmul__() (object 메서드)

__rmod__() (object 메서드)

__rmul__() (object 메서드)

__ror__() (object 메서드)

__round__() (fractions.Fraction 메서드)

(object 메서드)

__rpow__() (object 메서드)

__rrshift__() (object 메서드)

__rshift__() (object 메서드)

(operator 모듈)

__rsub__() (object 메서드)

__rtruediv__() (object 메서드)

__rxor__() (object 메서드)

__self__ (method attribute)

__set__() (object 메서드)

__set_name__() (object 메서드)

__setattr__() (object 메서드)

__setitem__() (email.message.EmailMessage 메서드)

(email.message.Message 메서드)

(mailbox.Mailbox 메서드)

(mailbox.Maildir 메서드)

(object 메서드)

(operator 모듈)

__setstate__() (copy protocol)

(object 메서드)

__slots__

__spec__

__stderr__ (sys 모듈)

__stdin__ (sys 모듈)

__stdout__ (sys 모듈)

__str__() (datetime.date 메서드)

(datetime.datetime 메서드)

(datetime.time 메서드)

(email.charset.Charset 메서드)

(email.header.Header 메서드)

(email.headerregistry.Address 메서드)

(email.headerregistry.Group 메서드)

(email.message.EmailMessage 메서드)

(email.message.Message 메서드)

(multiprocessing.managers.BaseProxy 메서드)

(object 메서드)

__sub__() (object 메서드)

(operator 모듈)

__subclasscheck__() (class 메서드)

__subclasses__() (class 메서드)

__subclasshook__() (abc.ABCMeta 메서드)

__suppress_context__ (traceback.TracebackException의 속성)

__traceback__ (exception attribute)

__truediv__() (object 메서드)

(operator 모듈)

__trunc__() (object 메서드)

__xor__() (object 메서드)

(operator 모듈)

_anonymous_ (ctypes.Structure의 속성)

_asdict() (collections.somenamedtuple 메서드)

_b_base_ (ctypes._CData의 속성)

_b_needsfree_ (ctypes._CData의 속성)

_callmethod() (multiprocessing.managers.BaseProxy 메서드)

_CData (ctypes 클래스)

_clear_type_cache() (sys 모듈)

_current_frames() (sys 모듈)

_debugmallocstats() (sys 모듈)

_dummy_thread (모듈)

_enablelegacywindowsfsencoding() (sys 모듈)

_exit() (os 모듈)

_field_defaults (collections.somenamedtuple의 속성)

_fields (ast.AST의 속성)

(collections.somenamedtuple의 속성)

_fields_ (ctypes.Structure의 속성)

_flush() (wsgiref.handlers.BaseHandler 메서드)

_frozen (C 데이터 형식)

_FuncPtr (ctypes 클래스)

_get_child_mock() (unittest.mock.Mock 메서드)

_getframe() (sys 모듈)

_getvalue() (multiprocessing.managers.BaseProxy 메서드)

_handle (ctypes.PyDLL의 속성)

_inittab (C 데이터 형식)

_length_ (ctypes.Array의 속성)

_locale

모듈

_make() (collections.somenamedtuple의 클래스 메서드)

_makeResult() (unittest.TextTestRunner 메서드)

_name (ctypes.PyDLL의 속성)

_objects (ctypes._CData의 속성)

_pack_ (ctypes.Structure의 속성)

_parse() (gettext.NullTranslations 메서드)

_Pointer (ctypes 클래스)

_Py_c_diff (C 함수)

_Py_c_neg (C 함수)

_Py_c_pow (C 함수)

_Py_c_prod (C 함수)

_Py_c_quot (C 함수)

_Py_c_sum (C 함수)

_Py_NoneStruct (C 변수)

_PyBytes_Resize (C 함수)

_PyCFunctionFast (C 데이터 형식)

_PyCFunctionFastWithKeywords (C 데이터 형식)

_PyImport_Fini (C 함수)

_PyImport_Init (C 함수)

_PyObject_GC_TRACK (C 함수)

_PyObject_GC_UNTRACK (C 함수)

_PyObject_New (C 함수)

_PyObject_NewVar (C 함수)

_PyTuple_Resize (C 함수)

_replace() (collections.somenamedtuple 메서드)

_setroot() (xml.etree.ElementTree.ElementTree 메서드)

_SimpleCData (ctypes 클래스)

_structure() (email.iterators 모듈)

_thread

모듈

_thread (모듈)

_type_ (ctypes._Pointer의 속성)

(ctypes.Array의 속성)

_write() (wsgiref.handlers.BaseHandler 메서드)

_xoptions (sys 모듈)

탐색

색인

모듈 |

Python »

3.7.17 Documentation »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

Python »

3.7.17 Documentation »

|

색인

기호 | _ | A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | X | Y | Z | ᄀ | ᄂ | ᄆ | ᄋ | ᄏ | ᄑ | ᄒ

기호

! (exclamation)

in a command interpreter

in curses module

in formatted string literal

in glob-style wildcards, [1]

in string formatting

in struct format strings

! (pdb command)

!=

연산자, [1]

" (double quote)

string literal

"""

string literal

# (hash)

comment, [1], [2]

in doctests

in printf-style formatting, [1]

in regular expressions

in string formatting

source encoding declaration

$ (dollar)

environment variables expansion

in regular expressions

in template strings

interpolation in configuration files

% (percent)

datetime format, [1], [2]

environment variables expansion (Windows), [1]

interpolation in configuration files

printf-style formatting, [1]

연산자, [1]

%=

augmented assignment

& (ampersand)

연산자, [1]

&=

augmented assignment

' (single quote)

string literal

'''

string literal

() (parentheses)

call

class definition

function definition

generator expression

in assignment target list

in printf-style formatting, [1]

in regular expressions

tuple display

(?

in regular expressions

(?!

in regular expressions

(?#

in regular expressions

(?:

in regular expressions

(?<!

in regular expressions

(?<=

in regular expressions

(?=

in regular expressions

(?P<

in regular expressions

(?P=

in regular expressions

* (asterisk)

function definition

import statement

in argparse module

in assignment target list

in AST grammar

in expression lists

in function calls, [1]

in glob-style wildcards, [1]

in printf-style formatting, [1]

in regular expressions

연산자, [1]

**

function definition

in dictionary displays

in function calls, [1]

in glob-style wildcards

연산자, [1]

**=

augmented assignment

*=

augmented assignment

*?

in regular expressions

+ (plus)

binary operator, [1]

in argparse module

in doctests

in printf-style formatting, [1]

in regular expressions

in string formatting

unary operator, [1]

+=

augmented assignment

+?

in regular expressions

, (comma)

argument list

expression list, [1], [2], [3], [4]

identifier list, [1]

import statement

in dictionary displays

in string formatting

in target list

parameter list

slicing

with statement

- (minus)

binary operator, [1]

in doctests

in glob-style wildcards, [1]

in printf-style formatting, [1]

in regular expressions

in string formatting

unary operator, [1]

--annotate

pickletools command line option

--buffer

unittest command line option

--catch

unittest command line option

--check-hash-based-pycs default|always|never

command line option

--compress

zipapp command line option

--count

trace command line option

--coverdir=<dir>

trace command line option

--create <tarfile> <source1> ... <sourceN>

tarfile command line option

--create <zipfile> <source1> ... <sourceN>

zipfile command line option

--details

inspect command line option

--exact

tokenize command line option

--extract <tarfile> [<output_dir>]

tarfile command line option

--extract <zipfile> <output_dir>

zipfile command line option

--failfast

unittest command line option

--file=<file>

trace command line option

--help

command line option

json.tool command line option

timeit command line option

tokenize command line option

trace command line option

zipapp command line option

--ignore-dir=<dir>

trace command line option

--ignore-module=<mod>

trace command line option

--indentlevel=<num>

pickletools command line option

--info

zipapp command line option

--invalidation-mode [timestamp|checked-hash|unchecked-hash]

compileall command line option

--list <tarfile>

tarfile command line option

--list <zipfile>

zipfile command line option

--listfuncs

trace command line option

--locals

unittest command line option

--main=<mainfn>

zipapp command line option

--memo

pickletools command line option

--missing

trace command line option

--no-report

trace command line option

--number=N

timeit command line option

--output=<file>

pickletools command line option

--output=<output>

zipapp command line option

--pattern pattern

unittest-discover command line option

--preamble=<preamble>

pickletools command line option

--process

timeit command line option

--python=<interpreter>

zipapp command line option

--repeat=N

timeit command line option

--report

trace command line option

--setup=S

timeit command line option

--sort-keys

json.tool command line option

--start-directory directory

unittest-discover command line option

--summary

trace command line option

--test <tarfile>

tarfile command line option

--test <zipfile>

zipfile command line option

--timing

trace command line option

--top-level-directory directory

unittest-discover command line option

--trace

trace command line option

--trackcalls

trace command line option

--unit=U

timeit command line option

--user-base

site command line option

--user-site

site command line option

--verbose

tarfile command line option

timeit command line option

unittest-discover command line option

--version

command line option

trace command line option

-=

augmented assignment

->

function annotations, [1]

-?

command line option

-a

pickletools command line option

-B

command line option

-b

command line option

compileall command line option

unittest command line option

-C

trace command line option

-c

trace command line option

unittest command line option

zipapp command line option

-c <command>

command line option

-c <tarfile> <source1> ... <sourceN>

tarfile command line option

-c <zipfile> <source1> ... <sourceN>

zipfile command line option

-d

command line option

-d destdir

compileall command line option

-E

command line option

-e

tokenize command line option

-e <tarfile> [<output_dir>]

tarfile command line option

-e <zipfile> <output_dir>

zipfile command line option

-f

compileall command line option

trace command line option

unittest command line option

-g

trace command line option

-h

command line option

json.tool command line option

timeit command line option

tokenize command line option

zipapp command line option

-I

command line option

-i

command line option

-i list

compileall command line option

-J

command line option

-j N

compileall command line option

-k

unittest command line option

-l

compileall command line option

pickletools command line option

trace command line option

-l <tarfile>

tarfile command line option

-l <zipfile>

zipfile command line option

-m

pickletools command line option

trace command line option

-m <mainfn>

zipapp command line option

-m <module-name>

command line option

-n N

timeit command line option

-O

command line option

-o

pickletools command line option

-o <output>

zipapp command line option

-OO

command line option

-p

pickletools command line option

timeit command line option

unittest-discover command line option

-p <interpreter>

zipapp command line option

-q

command line option

compileall command line option

-R

command line option

trace command line option

-r

compileall command line option

trace command line option

-r N

timeit command line option

-S

command line option

-s

command line option

trace command line option

unittest-discover command line option

-s S

timeit command line option

-T

trace command line option

-t

trace command line option

unittest-discover command line option

-t <tarfile>

tarfile command line option

-t <zipfile>

zipfile command line option

-u

command line option

timeit command line option

-V

command line option

-v

command line option

tarfile command line option

timeit command line option

unittest-discover command line option

-W arg

command line option

-X

command line option

-x

command line option

-x regex

compileall command line option

. (dot)

attribute reference

in glob-style wildcards

in numeric literal

in pathnames, [1]

in printf-style formatting, [1]

in regular expressions

in string formatting

in Tkinter

..

in pathnames

...

ellipsis literal, [1], [2]

in doctests

interpreter prompt, [1]

placeholder, [1], [2]

.ini

file

.pdbrc

file

/ (slash)

in pathnames, [1]

연산자, [1]

//

연산자, [1]

//=

augmented assignment

/=

augmented assignment

0b

integer literal

0o

integer literal

0x

integer literal

2-digit years

2to3

: (colon)

annotated variable

compound statement, [1], [2], [3], [4], [5], [6]

function annotations, [1]

in dictionary expressions

in formatted string literal

in SQL statements

in string formatting

lambda expression

path separator (POSIX)

slicing

; (semicolon), [1]

< (less)

in string formatting

in struct format strings

연산자, [1]

<<

연산자, [1]

<<=

augmented assignment

<=

연산자, [1]

<BLANKLINE>

= (equals)

assignment statement

class definition

function definition

in function calls

in string formatting

in struct format strings

==

연산자, [1]

> (greater)

in string formatting

in struct format strings

연산자, [1]

>=

연산자, [1]

>>

연산자, [1]

>>=

augmented assignment

>>>

interpreter prompt, [1]

? (question mark)

in a command interpreter

in argparse module

in AST grammar

in glob-style wildcards, [1]

in regular expressions

in SQL statements

in struct format strings, [1]

replacement character

??

in regular expressions

@ (at)

class definition

function definition

in struct format strings

연산자

[] (square brackets)

in assignment target list

in glob-style wildcards, [1]

in regular expressions

in string formatting

list expression

subscription

\ (backslash)

escape sequence, [1]

in pathnames (Windows)

in regular expressions, [1], [2]

\\

escape sequence

in regular expressions

\A

in regular expressions

\a

escape sequence

in regular expressions

\B

in regular expressions

\b

escape sequence

in regular expressions, [1]

\D

in regular expressions

\d

in regular expressions

\f

escape sequence

in regular expressions

\g

in regular expressions

\N

escape sequence, [1]

in regular expressions

\n

escape sequence

in regular expressions

\r

escape sequence

in regular expressions

\S

in regular expressions

\s

in regular expressions

\t

escape sequence

in regular expressions

\U

escape sequence, [1]

in regular expressions

\u

escape sequence, [1]

in regular expressions

\v

escape sequence

in regular expressions

\W

in regular expressions

\w

in regular expressions

\x

escape sequence, [1]

in regular expressions

\Z

in regular expressions

^ (caret)

in curses module

in regular expressions, [1]

in string formatting

marker, [1]

연산자, [1]

^=

augmented assignment

{} (curly brackets)

dictionary expression

in formatted string literal

in regular expressions

in string formatting

set expression

| (vertical bar)

in regular expressions

연산자, [1]

|=

augmented assignment

~ (tilde)

home directory expansion

연산자, [1]

_

_ (underscore)

gettext

in numeric literal, [1]

in string formatting

_, identifiers

__, identifiers

__abs__() (object 메서드)

(operator 모듈)

__add__() (object 메서드)

(operator 모듈)

__aenter__() (object 메서드)

__aexit__() (object 메서드)

__aiter__() (object 메서드)

__all__

(optional module attribute)

(package variable)

__and__() (object 메서드)

(operator 모듈)

__anext__() (agen 메서드)

(object 메서드)

__annotations__ (class attribute)

(function attribute)

(module attribute)

__await__() (object 메서드)

__bases__ (class attribute)

(class의 속성)

__bool__() (object method)

(object 메서드)

__breakpointhook__ (sys 모듈)

__bytes__() (email.message.EmailMessage 메서드)

(email.message.Message 메서드)

(object 메서드)

__cached__

__call__() (email.headerregistry.HeaderRegistry 메서드)

(object method)

(object 메서드)

(weakref.finalize 메서드)

__callback__ (weakref.ref의 속성)

__cause__ (exception attribute)

(traceback.TracebackException의 속성)

__ceil__() (fractions.Fraction 메서드)

(object 메서드)

__class__ (instance attribute)

(instance의 속성)

(method cell)

(module attribute)

(unittest.mock.Mock의 속성)

__class_getitem__() (object의 클래스 메서드)

__classcell__ (class namespace entry)

__closure__ (function attribute)

__code__ (function attribute)

(function object attribute)

__complex__() (object 메서드)

__concat__() (operator 모듈)

__contains__() (email.message.EmailMessage 메서드)

(email.message.Message 메서드)

(mailbox.Mailbox 메서드)

(object 메서드)

(operator 모듈)

__context__ (exception attribute)

(traceback.TracebackException의 속성)

__copy__() (copy protocol)

__debug__

(내장 변수)

__deepcopy__() (copy protocol)

__defaults__ (function attribute)

__del__() (io.IOBase 메서드)

(object 메서드)

__delattr__() (object 메서드)

__delete__() (object 메서드)

__delitem__() (email.message.EmailMessage 메서드)

(email.message.Message 메서드)

(mailbox.Mailbox 메서드)

(mailbox.MH 메서드)

(object 메서드)

(operator 모듈)

__dict__ (class attribute)

(function attribute)

(instance attribute)

(module attribute), [1]

(object의 속성)

__dir__ (module attribute)

__dir__() (object 메서드)

(unittest.mock.Mock 메서드)

__displayhook__ (sys 모듈)

__divmod__() (object 메서드)

__doc__ (class attribute)

(function attribute)

(method attribute)

(module attribute), [1]

(types.ModuleType의 속성)

__enter__() (contextmanager 메서드)

(object 메서드)

(winreg.PyHKEY 메서드)

__eq__() (email.charset.Charset 메서드)

(email.header.Header 메서드)

(instance method)

(memoryview 메서드)

(object 메서드)

(operator 모듈)

__excepthook__ (sys 모듈)

__exit__() (contextmanager 메서드)

(object 메서드)

(winreg.PyHKEY 메서드)

__file__

(module attribute), [1], [2]

__float__() (object 메서드)

__floor__() (fractions.Fraction 메서드)

(object 메서드)

__floordiv__() (object 메서드)

(operator 모듈)

__format__

__format__() (datetime.date 메서드)

(datetime.datetime 메서드)

(datetime.time 메서드)

(object 메서드)

__fspath__() (os.PathLike의 메서드)

__func__ (method attribute)

__future__

future statement

__future__ (모듈)

__ge__() (instance method)

(object 메서드)

(operator 모듈)

__get__() (object 메서드)

__getattr__ (module attribute)

__getattr__() (object 메서드)

__getattribute__() (object 메서드)

__getitem__() (email.headerregistry.HeaderRegistry 메서드)

(email.message.EmailMessage 메서드)

(email.message.Message 메서드)

(mailbox.Mailbox 메서드)

(mapping object method)

(object 메서드)

(operator 모듈)

(re.Match 메서드)

__getnewargs__() (object 메서드)

__getnewargs_ex__() (object 메서드)

__getstate__() (copy protocol)

(object 메서드)

__globals__ (function attribute)

__gt__() (instance method)

(object 메서드)

(operator 모듈)

__hash__() (object 메서드)

__iadd__() (object 메서드)

(operator 모듈)

__iand__() (object 메서드)

(operator 모듈)

__iconcat__() (operator 모듈)

__ifloordiv__() (object 메서드)

(operator 모듈)

__ilshift__() (object 메서드)

(operator 모듈)

__imatmul__() (object 메서드)

(operator 모듈)

__imod__() (object 메서드)

(operator 모듈)

__import__

내장 함수

__import__() (importlib 모듈)

(내장 함수)

__imul__() (object 메서드)

(operator 모듈)

__index__() (object 메서드)

(operator 모듈)

__init__() (difflib.HtmlDiff 메서드)

(logging.Handler 메서드)

(logging.logging.Formatter 메서드)

(object 메서드)

__init_subclass__() (object의 클래스 메서드)

__instancecheck__() (class 메서드)

__int__() (object 메서드)

__interactivehook__ (sys 모듈)

__inv__() (operator 모듈)

__invert__() (object 메서드)

(operator 모듈)

__ior__() (object 메서드)

(operator 모듈)

__ipow__() (object 메서드)

(operator 모듈)

__irshift__() (object 메서드)

(operator 모듈)

__isub__() (object 메서드)

(operator 모듈)

__iter__() (container 메서드)

(iterator 메서드)

(mailbox.Mailbox 메서드)

(object 메서드)

(unittest.TestSuite 메서드)

__itruediv__() (object 메서드)

(operator 모듈)

__ixor__() (object 메서드)

(operator 모듈)

__kwdefaults__ (function attribute)

__le__() (instance method)

(object 메서드)

(operator 모듈)

__len__() (email.message.EmailMessage 메서드)

(email.message.Message 메서드)

(mailbox.Mailbox 메서드)

(mapping object method)

(object 메서드)

__length_hint__() (object 메서드)

__loader__

(module attribute)

(types.ModuleType의 속성)

__lshift__() (object 메서드)

(operator 모듈)

__lt__() (instance method)

(object 메서드)

(operator 모듈)

__main__

모듈, [1], [2], [3], [4], [5], [6], [7]

__main__ (모듈)

__matmul__() (object 메서드)

(operator 모듈)

__missing__()

(collections.defaultdict 메서드)

(object 메서드)

__mod__() (object 메서드)

(operator 모듈)

__module__ (class attribute)

(function attribute)

(method attribute)

__mro__ (class의 속성)

__mul__() (object 메서드)

(operator 모듈)

__name__

(class attribute)

(definition의 속성)

(function attribute)

(method attribute)

(module attribute), [1], [2]

(types.ModuleType의 속성)

__ne__() (email.charset.Charset 메서드)

(email.header.Header 메서드)

(instance method)

(object 메서드)

(operator 모듈)

__neg__() (object 메서드)

(operator 모듈)

__new__() (object 메서드)

__next__() (csv.csvreader 메서드)

(generator 메서드)

(iterator 메서드)

__not__() (operator 모듈)

__or__() (object 메서드)

(operator 모듈)

__package__

(module attribute)

(types.ModuleType의 속성)

__path__

__pos__() (object 메서드)

(operator 모듈)

__pow__() (object 메서드)

(operator 모듈)

__prepare__ (metaclass method)

__qualname__ (definition의 속성)

__radd__() (object 메서드)

__rand__() (object 메서드)

__rdivmod__() (object 메서드)

__reduce__() (object 메서드)

__reduce_ex__() (object 메서드)

__repr__() (multiprocessing.managers.BaseProxy 메서드)

(netrc.netrc 메서드)

(object 메서드)

__reversed__() (object 메서드)

__rfloordiv__() (object 메서드)

__rlshift__() (object 메서드)

__rmatmul__() (object 메서드)

__rmod__() (object 메서드)

__rmul__() (object 메서드)

__ror__() (object 메서드)

__round__() (fractions.Fraction 메서드)

(object 메서드)

__rpow__() (object 메서드)

__rrshift__() (object 메서드)

__rshift__() (object 메서드)

(operator 모듈)

__rsub__() (object 메서드)

__rtruediv__() (object 메서드)

__rxor__() (object 메서드)

__self__ (method attribute)

__set__() (object 메서드)

__set_name__() (object 메서드)

__setattr__() (object 메서드)

__setitem__() (email.message.EmailMessage 메서드)

(email.message.Message 메서드)

(mailbox.Mailbox 메서드)

(mailbox.Maildir 메서드)

(object 메서드)

(operator 모듈)

__setstate__() (copy protocol)

(object 메서드)

__slots__

__spec__

__stderr__ (sys 모듈)

__stdin__ (sys 모듈)

__stdout__ (sys 모듈)

__str__() (datetime.date 메서드)

(datetime.datetime 메서드)

(datetime.time 메서드)

(email.charset.Charset 메서드)

(email.header.Header 메서드)

(email.headerregistry.Address 메서드)

(email.headerregistry.Group 메서드)

(email.message.EmailMessage 메서드)

(email.message.Message 메서드)

(multiprocessing.managers.BaseProxy 메서드)

(object 메서드)

__sub__() (object 메서드)

(operator 모듈)

__subclasscheck__() (class 메서드)

__subclasses__() (class 메서드)

__subclasshook__() (abc.ABCMeta 메서드)

__suppress_context__ (traceback.TracebackException의 속성)

__traceback__ (exception attribute)

__truediv__() (object 메서드)

(operator 모듈)

__trunc__() (object 메서드)

__xor__() (object 메서드)

(operator 모듈)

_anonymous_ (ctypes.Structure의 속성)

_asdict() (collections.somenamedtuple 메서드)

_b_base_ (ctypes._CData의 속성)

_b_needsfree_ (ctypes._CData의 속성)

_callmethod() (multiprocessing.managers.BaseProxy 메서드)

_CData (ctypes 클래스)

_clear_type_cache() (sys 모듈)

_current_frames() (sys 모듈)

_debugmallocstats() (sys 모듈)

_dummy_thread (모듈)

_enablelegacywindowsfsencoding() (sys 모듈)

_exit() (os 모듈)

_field_defaults (collections.somenamedtuple의 속성)

_fields (ast.AST의 속성)

(collections.somenamedtuple의 속성)

_fields_ (ctypes.Structure의 속성)

_flush() (wsgiref.handlers.BaseHandler 메서드)

_frozen (C 데이터 형식)

_FuncPtr (ctypes 클래스)

_get_child_mock() (unittest.mock.Mock 메서드)

_getframe() (sys 모듈)

_getvalue() (multiprocessing.managers.BaseProxy 메서드)

_handle (ctypes.PyDLL의 속성)

_inittab (C 데이터 형식)

_length_ (ctypes.Array의 속성)

_locale

모듈

_make() (collections.somenamedtuple의 클래스 메서드)

_makeResult() (unittest.TextTestRunner 메서드)

_name (ctypes.PyDLL의 속성)

_objects (ctypes._CData의 속성)

_pack_ (ctypes.Structure의 속성)

_parse() (gettext.NullTranslations 메서드)

_Pointer (ctypes 클래스)

_Py_c_diff (C 함수)

_Py_c_neg (C 함수)

_Py_c_pow (C 함수)

_Py_c_prod (C 함수)

_Py_c_quot (C 함수)

_Py_c_sum (C 함수)

_Py_NoneStruct (C 변수)

_PyBytes_Resize (C 함수)

_PyCFunctionFast (C 데이터 형식)

_PyCFunctionFastWithKeywords (C 데이터 형식)

_PyImport_Fini (C 함수)

_PyImport_Init (C 함수)

_PyObject_GC_TRACK (C 함수)

_PyObject_GC_UNTRACK (C 함수)

_PyObject_New (C 함수)

_PyObject_NewVar (C 함수)

_PyTuple_Resize (C 함수)

_replace() (collections.somenamedtuple 메서드)

_setroot() (xml.etree.ElementTree.ElementTree 메서드)

_SimpleCData (ctypes 클래스)

_structure() (email.iterators 모듈)

_thread

모듈

_thread (모듈)

_type_ (ctypes._Pointer의 속성)

(ctypes.Array의 속성)

_write() (wsgiref.handlers.BaseHandler 메서드)

_xoptions (sys 모듈)

A

A (re 모듈)

A-LAW, [1]

a-LAW

a2b_base64() (binascii 모듈)

a2b_hex() (binascii 모듈)

a2b_hqx() (binascii 모듈)

a2b_qp() (binascii 모듈)

a2b_uu() (binascii 모듈)

a85decode() (base64 모듈)

a85encode() (base64 모듈)

ABC (abc 클래스)

abc (모듈)

ABCMeta (abc 클래스)

abiflags (sys 모듈)

abort()

(asyncio.DatagramTransport 메서드)

(asyncio.WriteTransport 메서드)

(ftplib.FTP 메서드)

(os 모듈)

(threading.Barrier 메서드)

above() (curses.panel.Panel 메서드)

ABOVE_NORMAL_PRIORITY_CLASS (subprocess 모듈)

abs

내장 함수, [1]

abs() (decimal.Context 메서드)

(operator 모듈)

(내장 함수)

abspath() (os.path 모듈)

abstract base class (추상 베이스 클래스)

AbstractAsyncContextManager (contextlib 클래스)

AbstractBasicAuthHandler (urllib.request 클래스)

AbstractChildWatcher (asyncio 클래스)

abstractclassmethod() (abc 모듈)

AbstractContextManager (contextlib 클래스)

AbstractDigestAuthHandler (urllib.request 클래스)

AbstractEventLoop (asyncio 클래스)

AbstractEventLoopPolicy (asyncio 클래스)

AbstractFormatter (formatter 클래스)

abstractmethod() (abc 모듈)

abstractproperty() (abc 모듈)

AbstractSet (typing 클래스)

abstractstaticmethod() (abc 모듈)

AbstractWriter (formatter 클래스)

accept() (asyncore.dispatcher 메서드)

(multiprocessing.connection.Listener 메서드)

(socket.socket 메서드)

access() (os 모듈)

accumulate() (itertools 모듈)

aclose() (agen 메서드)

(contextlib.AsyncExitStack 메서드)

acos() (cmath 모듈)

(math 모듈)

acosh() (cmath 모듈)

(math 모듈)

acquire() (_thread.lock 메서드)

(asyncio.Condition의 메서드)

(asyncio.Lock의 메서드)

(asyncio.Semaphore의 메서드)

(logging.Handler 메서드)

(multiprocessing.Lock 메서드)

(multiprocessing.RLock 메서드)

(threading.Condition 메서드)

(threading.Lock 메서드)

(threading.RLock 메서드)

(threading.Semaphore 메서드)

acquire_lock() (imp 모듈)

Action (argparse 클래스)

action (optparse.Option의 속성)

ACTIONS (optparse.Option의 속성)

active_children() (multiprocessing 모듈)

active_count() (threading 모듈)

add() (audioop 모듈)

(decimal.Context 메서드)

(frozenset 메서드)

(mailbox.Mailbox 메서드)

(mailbox.Maildir 메서드)

(msilib.RadioButtonGroup 메서드)

(operator 모듈)

(pstats.Stats 메서드)

(tarfile.TarFile 메서드)

(tkinter.ttk.Notebook 메서드)

add_alias() (email.charset 모듈)

add_alternative() (email.message.EmailMessage 메서드)

add_argument() (argparse.ArgumentParser 메서드)

add_argument_group() (argparse.ArgumentParser 메서드)

add_attachment() (email.message.EmailMessage 메서드)

add_cgi_vars() (wsgiref.handlers.BaseHandler 메서드)

add_charset() (email.charset 모듈)

add_child_handler() (asyncio.AbstractChildWatcher 메서드)

add_codec() (email.charset 모듈)

add_cookie_header() (http.cookiejar.CookieJar 메서드)

add_data() (msilib 모듈)

add_done_callback() (asyncio.Future 메서드)

(asyncio.Task 메서드)

(concurrent.futures.Future 메서드)

add_fallback() (gettext.NullTranslations 메서드)

add_file() (msilib.Directory 메서드)

add_flag() (mailbox.MaildirMessage 메서드)

(mailbox.mboxMessage 메서드)

(mailbox.MMDFMessage 메서드)

add_flowing_data() (formatter.formatter 메서드)

add_folder() (mailbox.Maildir 메서드)

(mailbox.MH 메서드)

add_get_handler() (email.contentmanager.ContentManager 메서드)

add_handler() (urllib.request.OpenerDirector 메서드)

add_header() (email.message.EmailMessage 메서드)

(email.message.Message 메서드)

(urllib.request.Request 메서드)

(wsgiref.headers.Headers 메서드)

add_history() (readline 모듈)

add_hor_rule() (formatter.formatter 메서드)

add_include_dir() (distutils.ccompiler.CCompiler 메서드)

add_label() (mailbox.BabylMessage 메서드)

add_label_data() (formatter.formatter 메서드)

add_library() (distutils.ccompiler.CCompiler 메서드)

add_library_dir() (distutils.ccompiler.CCompiler 메서드)

add_line_break() (formatter.formatter 메서드)

add_link_object() (distutils.ccompiler.CCompiler 메서드)

add_literal_data() (formatter.formatter 메서드)

add_mutually_exclusive_group() (argparse.ArgumentParser 메서드)

add_option() (optparse.OptionParser 메서드)

add_parent() (urllib.request.BaseHandler 메서드)

add_password() (urllib.request.HTTPPasswordMgr 메서드)

(urllib.request.HTTPPasswordMgrWithPriorAuth 메서드)

add_reader() (asyncio.loop 메서드)

add_related() (email.message.EmailMessage 메서드)

add_runtime_library_dir() (distutils.ccompiler.CCompiler 메서드)

add_section() (configparser.ConfigParser 메서드)

(configparser.RawConfigParser 메서드)

add_sequence() (mailbox.MHMessage 메서드)

add_set_handler() (email.contentmanager.ContentManager 메서드)

add_signal_handler() (asyncio.loop 메서드)

add_stream() (msilib 모듈)

add_subparsers() (argparse.ArgumentParser 메서드)

add_tables() (msilib 모듈)

add_type() (mimetypes 모듈)

add_unredirected_header() (urllib.request.Request 메서드)

add_writer() (asyncio.loop 메서드)

addch() (curses.window 메서드)

addCleanup() (unittest.TestCase 메서드)

addcomponent() (turtle.Shape 메서드)

addError() (unittest.TestResult 메서드)

addExpectedFailure() (unittest.TestResult 메서드)

addFailure() (unittest.TestResult 메서드)

addfile() (tarfile.TarFile 메서드)

addFilter() (logging.Handler 메서드)

(logging.Logger 메서드)

addHandler() (logging.Logger 메서드)

addition

addLevelName() (logging 모듈)

addnstr() (curses.window 메서드)

AddPackagePath() (modulefinder 모듈)

addr (smtpd.SMTPChannel의 속성)

addr_spec (email.headerregistry.Address의 속성)

Address (email.headerregistry 클래스)

address (email.headerregistry.SingleAddressHeader의 속성)

(multiprocessing.connection.Listener의 속성)

(multiprocessing.managers.BaseManager의 속성)

address_exclude() (ipaddress.IPv4Network 메서드)

(ipaddress.IPv6Network 메서드)

address_family (socketserver.BaseServer의 속성)

address_string() (http.server.BaseHTTPRequestHandler 메서드)

addresses (email.headerregistry.AddressHeader의 속성)

(email.headerregistry.Group의 속성)

AddressHeader (email.headerregistry 클래스)

addressof() (ctypes 모듈)

AddressValueError

addshape() (turtle 모듈)

addsitedir() (site 모듈)

addSkip() (unittest.TestResult 메서드)

addstr() (curses.window 메서드)

addSubTest() (unittest.TestResult 메서드)

addSuccess() (unittest.TestResult 메서드)

addTest() (unittest.TestSuite 메서드)

addTests() (unittest.TestSuite 메서드)

addTypeEqualityFunc() (unittest.TestCase 메서드)

addUnexpectedSuccess() (unittest.TestResult 메서드)

adjust_int_max_str_digits() (test.support 모듈)

adjusted() (decimal.Decimal 메서드)

adler32() (zlib 모듈)

ADPCM, Intel/DVI

adpcm2lin() (audioop 모듈)

AF_ALG (socket 모듈)

AF_CAN (socket 모듈)

AF_INET (socket 모듈)

AF_INET6 (socket 모듈)

AF_LINK (socket 모듈)

AF_PACKET (socket 모듈)

AF_RDS (socket 모듈)

AF_UNIX (socket 모듈)

AF_VSOCK (socket 모듈)

aifc (모듈)

aifc() (aifc.aifc 메서드)

AIFF, [1]

aiff() (aifc.aifc 메서드)

AIFF-C, [1]

alarm() (signal 모듈)

alaw2lin() (audioop 모듈)

ALERT_DESCRIPTION_HANDSHAKE_FAILURE (ssl 모듈)

ALERT_DESCRIPTION_INTERNAL_ERROR (ssl 모듈)

AlertDescription (ssl 클래스)

algorithms_available (hashlib 모듈)

algorithms_guaranteed (hashlib 모듈)

alias (pdb command)

alignment() (ctypes 모듈)

alive (weakref.finalize의 속성)

all() (내장 함수)

all_errors (ftplib 모듈)

all_features (xml.sax.handler 모듈)

all_frames (tracemalloc.Filter의 속성)

all_properties (xml.sax.handler 모듈)

all_suffixes() (importlib.machinery 모듈)

all_tasks() (asyncio 모듈)

(asyncio.Task의 클래스 메서드)

allocate_lock() (_thread 모듈)

allow_reuse_address (socketserver.BaseServer의 속성)

allowed_domains() (http.cookiejar.DefaultCookiePolicy 메서드)

alt() (curses.ascii 모듈)

ALT_DIGITS (locale 모듈)

altsep (os 모듈)

altzone (time 모듈)

ALWAYS_EQ (test.support 모듈)

ALWAYS_TYPED_ACTIONS (optparse.Option의 속성)

AMPER (token 모듈)

AMPEREQUAL (token 모듈)

and

bitwise

연산자, [1], [2]

and_() (operator 모듈)

annotated

assignment

annotation (inspect.Parameter의 속성)

(어노테이션)

annotations

function, [1]

announce() (distutils.ccompiler.CCompiler 메서드)

anonymous

function

answer_challenge() (multiprocessing.connection 모듈)

anticipate_failure() (test.support 모듈)

Any (typing 모듈)

ANY (unittest.mock 모듈)

any() (내장 함수)

AnyStr (typing 모듈)

api_version (sys 모듈)

apop() (poplib.POP3 메서드)

APPDATA

append() (array.array 메서드)

(collections.deque 메서드)

(email.header.Header 메서드)

(imaplib.IMAP4 메서드)

(msilib.CAB 메서드)

(pipes.Template 메서드)

(sequence method)

(xml.etree.ElementTree.Element 메서드)

append_history_file() (readline 모듈)

appendChild() (xml.dom.Node 메서드)

appendleft() (collections.deque 메서드)

application_uri() (wsgiref.util 모듈)

apply (2to3 fixer)

apply() (multiprocessing.pool.Pool 메서드)

apply_async() (multiprocessing.pool.Pool 메서드)

apply_defaults() (inspect.BoundArguments 메서드)

architecture() (platform 모듈)

archive (zipimport.zipimporter의 속성)

aRepr (reprlib 모듈)

argparse (모듈)

args (BaseException의 속성)

(functools.partial의 속성)

(inspect.BoundArguments의 속성)

(pdb command)

(subprocess.CompletedProcess의 속성)

(subprocess.Popen의 속성)

args_from_interpreter_flags() (test.support 모듈)

argtypes (ctypes._FuncPtr의 속성)

argument

call semantics

difference from parameter

function

function definition

argument (인자)

ArgumentDefaultsHelpFormatter (argparse 클래스)

ArgumentError

ArgumentParser (argparse 클래스)

arguments (inspect.BoundArguments의 속성)

argv (in module sys)

(sys 모듈)

arithmetic

conversion

operation, binary

operation, unary

ArithmeticError

array

모듈, [1]

array (array 클래스)

Array (ctypes 클래스)

array (모듈)

Array() (multiprocessing 모듈)

(multiprocessing.managers.SyncManager 메서드)

(multiprocessing.sharedctypes 모듈)

arrays

arraysize (sqlite3.Cursor의 속성)

article() (nntplib.NNTP 메서드)

as

except clause

import statement

with statement

키워드, [1], [2]

as_bytes() (email.message.EmailMessage 메서드)

(email.message.Message 메서드)

as_completed() (asyncio 모듈)

(concurrent.futures 모듈)

as_integer_ratio() (decimal.Decimal 메서드)

(float 메서드)

AS_IS (formatter 모듈)

as_posix() (pathlib.PurePath 메서드)

as_string() (email.message.EmailMessage 메서드)

(email.message.Message 메서드)

as_tuple() (decimal.Decimal 메서드)

as_uri() (pathlib.PurePath 메서드)

ASCII, [1]

ascii

(re 모듈)

내장 함수

ascii() (curses.ascii 모듈)

(내장 함수)

ascii_letters (string 모듈)

ascii_lowercase (string 모듈)

ascii_uppercase (string 모듈)

asctime() (time 모듈)

asdict() (dataclasses 모듈)

asend() (agen 메서드)

asin() (cmath 모듈)

(math 모듈)

asinh() (cmath 모듈)

(math 모듈)

assert

글, [1]

assert_any_call() (unittest.mock.Mock 메서드)

assert_called() (unittest.mock.Mock 메서드)

assert_called_once() (unittest.mock.Mock 메서드)

assert_called_once_with() (unittest.mock.Mock 메서드)

assert_called_with() (unittest.mock.Mock 메서드)

assert_has_calls() (unittest.mock.Mock 메서드)

assert_line_data() (formatter.formatter 메서드)

assert_not_called() (unittest.mock.Mock 메서드)

assert_python_failure() (test.support.script_helper 모듈)

assert_python_ok() (test.support.script_helper 모듈)

assertAlmostEqual() (unittest.TestCase 메서드)

assertCountEqual() (unittest.TestCase 메서드)

assertDictEqual() (unittest.TestCase 메서드)

assertEqual() (unittest.TestCase 메서드)

assertFalse() (unittest.TestCase 메서드)

assertGreater() (unittest.TestCase 메서드)

assertGreaterEqual() (unittest.TestCase 메서드)

assertIn() (unittest.TestCase 메서드)

AssertionError

예외

assertions

debugging

assertIs() (unittest.TestCase 메서드)

assertIsInstance() (unittest.TestCase 메서드)

assertIsNone() (unittest.TestCase 메서드)

assertIsNot() (unittest.TestCase 메서드)

assertIsNotNone() (unittest.TestCase 메서드)

assertLess() (unittest.TestCase 메서드)

assertLessEqual() (unittest.TestCase 메서드)

assertListEqual() (unittest.TestCase 메서드)

assertLogs() (unittest.TestCase 메서드)

assertMultiLineEqual() (unittest.TestCase 메서드)

assertNotAlmostEqual() (unittest.TestCase 메서드)

assertNotEqual() (unittest.TestCase 메서드)

assertNotIn() (unittest.TestCase 메서드)

assertNotIsInstance() (unittest.TestCase 메서드)

assertNotRegex() (unittest.TestCase 메서드)

assertRaises() (unittest.TestCase 메서드)

assertRaisesRegex() (unittest.TestCase 메서드)

assertRegex() (unittest.TestCase 메서드)

asserts (2to3 fixer)

assertSequenceEqual() (unittest.TestCase 메서드)

assertSetEqual() (unittest.TestCase 메서드)

assertTrue() (unittest.TestCase 메서드)

assertTupleEqual() (unittest.TestCase 메서드)

assertWarns() (unittest.TestCase 메서드)

assertWarnsRegex() (unittest.TestCase 메서드)

assignment

annotated

attribute, [1]

augmented

class attribute

class instance attribute

slice

slicing

statement, [1]

subscript

subscription

target list

AST (ast 클래스)

ast (모듈)

astimezone() (datetime.datetime 메서드)

astuple() (dataclasses 모듈)

async

키워드

async def

글

async for

in comprehensions

글

async with

글

async_chat (asynchat 클래스)

async_chat.ac_in_buffer_size (asynchat 모듈)

async_chat.ac_out_buffer_size (asynchat 모듈)

AsyncContextManager (typing 클래스)

asynccontextmanager() (contextlib 모듈)

AsyncExitStack (contextlib 클래스)

AsyncGenerator (collections.abc 클래스)

(typing 클래스)

AsyncGeneratorType (types 모듈)

asynchat (모듈)

asynchronous context manager (비동기 컨텍스트 관리자)

asynchronous generator

asynchronous iterator

function

asynchronous generator (비동기 제너레이터)

asynchronous generator iterator (비동기 제너레이터 이터레이터)

asynchronous iterable (비동기 이터러블)

asynchronous iterator (비동기 이터레이터)

asynchronous-generator

객체

asyncio (모듈)

asyncio.subprocess.DEVNULL (asyncio 모듈)

asyncio.subprocess.PIPE (asyncio 모듈)

asyncio.subprocess.Process (asyncio 클래스)

asyncio.subprocess.STDOUT (asyncio 모듈)

AsyncIterable (collections.abc 클래스)

(typing 클래스)

AsyncIterator (collections.abc 클래스)

(typing 클래스)

asyncore (모듈)

AsyncResult (multiprocessing.pool 클래스)

AT (token 모듈)

at_eof() (asyncio.StreamReader 메서드)

atan() (cmath 모듈)

(math 모듈)

atan2() (math 모듈)

atanh() (cmath 모듈)

(math 모듈)

ATEQUAL (token 모듈)

atexit (weakref.finalize의 속성)

(모듈)

athrow() (agen 메서드)

atof() (locale 모듈)

atoi() (locale 모듈)

atom

attach() (email.message.Message 메서드)

attach_loop() (asyncio.AbstractChildWatcher 메서드)

attach_mock() (unittest.mock.Mock 메서드)

AttlistDeclHandler() (xml.parsers.expat.xmlparser 메서드)

attrgetter() (operator 모듈)

attrib (xml.etree.ElementTree.Element의 속성)

attribute

assignment, [1]

assignment, class

assignment, class instance

class

class instance

deletion

generic special

reference

special

attribute (어트리뷰트)

AttributeError

예외

attributes (xml.dom.Node의 속성)

AttributesImpl (xml.sax.xmlreader 클래스)

AttributesNSImpl (xml.sax.xmlreader 클래스)

attroff() (curses.window 메서드)

attron() (curses.window 메서드)

attrset() (curses.window 메서드)

Audio Interchange File Format, [1]

AUDIO_FILE_ENCODING_ADPCM_G721 (sunau 모듈)

AUDIO_FILE_ENCODING_ADPCM_G722 (sunau 모듈)

AUDIO_FILE_ENCODING_ADPCM_G723_3 (sunau 모듈)

AUDIO_FILE_ENCODING_ADPCM_G723_5 (sunau 모듈)

AUDIO_FILE_ENCODING_ALAW_8 (sunau 모듈)

AUDIO_FILE_ENCODING_DOUBLE (sunau 모듈)

AUDIO_FILE_ENCODING_FLOAT (sunau 모듈)

AUDIO_FILE_ENCODING_LINEAR_16 (sunau 모듈)

AUDIO_FILE_ENCODING_LINEAR_24 (sunau 모듈)

AUDIO_FILE_ENCODING_LINEAR_32 (sunau 모듈)

AUDIO_FILE_ENCODING_LINEAR_8 (sunau 모듈)

AUDIO_FILE_ENCODING_MULAW_8 (sunau 모듈)

AUDIO_FILE_MAGIC (sunau 모듈)

AUDIODEV

audioop (모듈)

augmented

assignment

auth() (ftplib.FTP_TLS 메서드)

(smtplib.SMTP 메서드)

authenticate() (imaplib.IMAP4 메서드)

AuthenticationError

authenticators() (netrc.netrc 메서드)

authkey (multiprocessing.Process의 속성)

auto (enum 클래스)

autorange() (timeit.Timer 메서드)

avg() (audioop 모듈)

avgpp() (audioop 모듈)

avoids_symlink_attacks (shutil.rmtree의 속성)

await

in comprehensions

키워드, [1]

Awaitable (collections.abc 클래스)

(typing 클래스)

awaitable (어웨이터블)

B

b"

bytes literal

b'

bytes literal

b16decode() (base64 모듈)

b16encode() (base64 모듈)

b2a_base64() (binascii 모듈)

b2a_hex() (binascii 모듈)

b2a_hqx() (binascii 모듈)

b2a_qp() (binascii 모듈)

b2a_uu() (binascii 모듈)

b32decode() (base64 모듈)

b32encode() (base64 모듈)

b64decode() (base64 모듈)

b64encode() (base64 모듈)

b85decode() (base64 모듈)

b85encode() (base64 모듈)

Babyl (mailbox 클래스)

BabylMessage (mailbox 클래스)

back() (turtle 모듈)

backslash character

backslashreplace_errors() (codecs 모듈)

backup() (sqlite3.Connection 메서드)

backward() (turtle 모듈)

BadStatusLine

BadZipFile

BadZipfile

Balloon (tkinter.tix 클래스)

Barrier (multiprocessing 클래스)

(threading 클래스)

Barrier() (multiprocessing.managers.SyncManager 메서드)

base64

encoding

모듈

base64 (모듈)

base_exec_prefix (sys 모듈)

base_prefix (sys 모듈)

BaseCGIHandler (wsgiref.handlers 클래스)

BaseCookie (http.cookies 클래스)

BaseException

BaseHandler (urllib.request 클래스)

(wsgiref.handlers 클래스)

BaseHeader (email.headerregistry 클래스)

BaseHTTPRequestHandler (http.server 클래스)

BaseManager (multiprocessing.managers 클래스)

basename() (os.path 모듈)

BaseProtocol (asyncio 클래스)

BaseProxy (multiprocessing.managers 클래스)

BaseRequestHandler (socketserver 클래스)

BaseRotatingHandler (logging.handlers 클래스)

BaseSelector (selectors 클래스)

BaseServer (socketserver 클래스)

basestring (2to3 fixer)

BaseTransport (asyncio 클래스)

basicConfig() (logging 모듈)

BasicContext (decimal 클래스)

BasicInterpolation (configparser 클래스)

BasicTestRunner (test.support 클래스)

baudrate() (curses 모듈)

bbox() (tkinter.ttk.Treeview 메서드)

BDADDR_ANY (socket 모듈)

BDADDR_LOCAL (socket 모듈)

bdb

모듈

Bdb (bdb 클래스)

bdb (모듈)

BdbQuit

BDFL

bdist_msi (distutils.command.bdist_msi 클래스)

beep() (curses 모듈)

Beep() (winsound 모듈)

BEFORE_ASYNC_WITH (opcode)

begin_fill() (turtle 모듈)

begin_poly() (turtle 모듈)

below() (curses.panel.Panel 메서드)

BELOW_NORMAL_PRIORITY_CLASS (subprocess 모듈)

Benchmarking

benchmarking, [1], [2], [3]

betavariate() (random 모듈)

bgcolor() (turtle 모듈)

bgpic() (turtle 모듈)

bias() (audioop 모듈)

bidirectional() (unicodedata 모듈)

bigaddrspacetest() (test.support 모듈)

BigEndianStructure (ctypes 클래스)

bigmemtest() (test.support 모듈)

bin() (내장 함수)

binary

arithmetic operation

bitwise operation

data, packing

literals

Binary (msilib 클래스)

(xmlrpc.client 클래스)

binary file (바이너리 파일)

binary literal

binary mode

binary semaphores

BINARY_ADD (opcode)

BINARY_AND (opcode)

BINARY_FLOOR_DIVIDE (opcode)

BINARY_LSHIFT (opcode)

BINARY_MATRIX_MULTIPLY (opcode)

BINARY_MODULO (opcode)

BINARY_MULTIPLY (opcode)

BINARY_OR (opcode)

BINARY_POWER (opcode)

BINARY_RSHIFT (opcode)

BINARY_SUBSCR (opcode)

BINARY_SUBTRACT (opcode)

BINARY_TRUE_DIVIDE (opcode)

BINARY_XOR (opcode)

BinaryIO (typing 클래스)

binascii (모듈)

bind (widgets)

bind() (asyncore.dispatcher 메서드)

(inspect.Signature 메서드)

(socket.socket 메서드)

bind_partial() (inspect.Signature 메서드)

bind_port() (test.support 모듈)

bind_textdomain_codeset() (gettext 모듈)

bind_unix_socket() (test.support 모듈)

binding

global name

name, [1], [2], [3], [4], [5], [6]

bindtextdomain() (gettext 모듈)

(locale 모듈)

binhex

모듈

binhex (모듈)

binhex() (binhex 모듈)

bisect (모듈)

bisect() (bisect 모듈)

bisect_left() (bisect 모듈)

bisect_right() (bisect 모듈)

bit_length() (int 메서드)

bitmap() (msilib.Dialog 메서드)

bitwise

and

operation, binary

operation, unary

operations

or

xor

bk() (turtle 모듈)

bkgd() (curses.window 메서드)

bkgdset() (curses.window 메서드)

blake2b() (hashlib 모듈)

blake2b, blake2s

blake2b.MAX_DIGEST_SIZE (hashlib 모듈)

blake2b.MAX_KEY_SIZE (hashlib 모듈)

blake2b.PERSON_SIZE (hashlib 모듈)

blake2b.SALT_SIZE (hashlib 모듈)

blake2s() (hashlib 모듈)

blake2s.MAX_DIGEST_SIZE (hashlib 모듈)

blake2s.MAX_KEY_SIZE (hashlib 모듈)

blake2s.PERSON_SIZE (hashlib 모듈)

blake2s.SALT_SIZE (hashlib 모듈)

blank line

block

code

block_size (hmac.HMAC의 속성)

blocked_domains() (http.cookiejar.DefaultCookiePolicy 메서드)

BlockingIOError, [1]

blocksize (http.client.HTTPConnection의 속성)

BNF, [1]

body() (nntplib.NNTP 메서드)

body_encode() (email.charset.Charset 메서드)

body_encoding (email.charset.Charset의 속성)

body_line_iterator() (email.iterators 모듈)

BOM (codecs 모듈)

BOM_BE (codecs 모듈)

BOM_LE (codecs 모듈)

BOM_UTF16 (codecs 모듈)

BOM_UTF16_BE (codecs 모듈)

BOM_UTF16_LE (codecs 모듈)

BOM_UTF32 (codecs 모듈)

BOM_UTF32_BE (codecs 모듈)

BOM_UTF32_LE (codecs 모듈)

BOM_UTF8 (codecs 모듈)

bool (내장 클래스)

Boolean

operation

operations, [1]

type

values

객체, [1]

BOOLEAN_STATES (configparser.ConfigParser의 속성)

bootstrap() (ensurepip 모듈)

border() (curses.window 메서드)

bottom() (curses.panel.Panel 메서드)

bottom_panel() (curses.panel 모듈)

BoundArguments (inspect 클래스)

BoundaryError

BoundedSemaphore (asyncio 클래스)

(multiprocessing 클래스)

(threading 클래스)

BoundedSemaphore() (multiprocessing.managers.SyncManager 메서드)

box() (curses.window 메서드)

bpformat() (bdb.Breakpoint 메서드)

bpprint() (bdb.Breakpoint 메서드)

break

글, [1], [2], [3], [4]

break (pdb command)

break_anywhere() (bdb.Bdb 메서드)

break_here() (bdb.Bdb 메서드)

break_long_words (textwrap.TextWrapper의 속성)

BREAK_LOOP (opcode)

break_on_hyphens (textwrap.TextWrapper의 속성)

Breakpoint (bdb 클래스)

breakpoint() (내장 함수)

breakpointhook() (sys 모듈)

breakpoints

broadcast_address (ipaddress.IPv4Network의 속성)

(ipaddress.IPv6Network의 속성)

broken (threading.Barrier의 속성)

BrokenBarrierError

BrokenExecutor

BrokenPipeError

BrokenProcessPool

BrokenThreadPool

BROWSER, [1]

BsdDbShelf (shelve 클래스)

buffer (2to3 fixer)

(io.TextIOBase의 속성)

(unittest.TestResult의 속성)

buffer interface

(see buffer protocol)

buffer object

(see buffer protocol)

buffer protocol

binary sequence types

str (built-in class)

buffer size, I/O

buffer_info() (array.array 메서드)

buffer_size (xml.parsers.expat.xmlparser의 속성)

buffer_text (xml.parsers.expat.xmlparser의 속성)

buffer_updated() (asyncio.BufferedProtocol 메서드)

buffer_used (xml.parsers.expat.xmlparser의 속성)

BufferedIOBase (io 클래스)

BufferedProtocol (asyncio 클래스)

BufferedRandom (io 클래스)

BufferedReader (io 클래스)

BufferedRWPair (io 클래스)

BufferedWriter (io 클래스)

BufferError

BufferingHandler (logging.handlers 클래스)

BufferTooShort

bufsize() (ossaudiodev.oss_audio_device 메서드)

BUILD_CONST_KEY_MAP (opcode)

BUILD_LIST (opcode)

BUILD_LIST_UNPACK (opcode)

BUILD_MAP (opcode)

BUILD_MAP_UNPACK (opcode)

BUILD_MAP_UNPACK_WITH_CALL (opcode)

build_opener() (urllib.request 모듈)

build_py (distutils.command.build_py 클래스)

build_py_2to3 (distutils.command.build_py 클래스)

BUILD_SET (opcode)

BUILD_SET_UNPACK (opcode)

BUILD_SLICE (opcode)

BUILD_STRING (opcode)

BUILD_TUPLE (opcode)

BUILD_TUPLE_UNPACK (opcode)

BUILD_TUPLE_UNPACK_WITH_CALL (opcode)

built-in

method

types

built-in function

call

객체, [1]

built-in method

call

객체, [1]

builtin_module_names (sys 모듈)

BuiltinFunctionType (types 모듈)

BuiltinImporter (importlib.machinery 클래스)

BuiltinMethodType (types 모듈)

builtins

모듈, [1], [2], [3], [4]

builtins (모듈)

ButtonBox (tkinter.tix 클래스)

bye() (turtle 모듈)

byref() (ctypes 모듈)

byte

byte-code

file, [1]

byte_compile() (distutils.util 모듈)

bytearray

formatting

interpolation

methods

객체, [1], [2], [3]

bytearray (내장 클래스)

bytecode

Bytecode (dis 클래스)

bytecode (바이트 코드)

Bytecode.codeobj (dis 모듈)

Bytecode.first_line (dis 모듈)

BYTECODE_SUFFIXES (importlib.machinery 모듈)

byteorder (sys 모듈)

bytes

formatting

interpolation

methods

str (built-in class)

객체, [1], [2]

내장 함수, [1]

bytes (uuid.UUID의 속성)

(내장 클래스)

bytes literal

bytes-like object (바이트열류 객체)

bytes_le (uuid.UUID의 속성)

BytesFeedParser (email.parser 클래스)

BytesGenerator (email.generator 클래스)

BytesHeaderParser (email.parser 클래스)

BytesIO (io 클래스)

BytesParser (email.parser 클래스)

ByteString (collections.abc 클래스)

(typing 클래스)

byteswap() (array.array 메서드)

(audioop 모듈)

BytesWarning

bz2 (모듈)

BZ2Compressor (bz2 클래스)

BZ2Decompressor (bz2 클래스)

BZ2File (bz2 클래스)

C

C

language, [1], [2], [3], [4], [5]

structures

C-contiguous, [1]

c_bool (ctypes 클래스)

C_BUILTIN (imp 모듈)

c_byte (ctypes 클래스)

c_char (ctypes 클래스)

c_char_p (ctypes 클래스)

c_contiguous (memoryview의 속성)

c_double (ctypes 클래스)

C_EXTENSION (imp 모듈)

c_float (ctypes 클래스)

c_int (ctypes 클래스)

c_int16 (ctypes 클래스)

c_int32 (ctypes 클래스)

c_int64 (ctypes 클래스)

c_int8 (ctypes 클래스)

c_long (ctypes 클래스)

c_longdouble (ctypes 클래스)

c_longlong (ctypes 클래스)

c_short (ctypes 클래스)

c_size_t (ctypes 클래스)

c_ssize_t (ctypes 클래스)

c_ubyte (ctypes 클래스)

c_uint (ctypes 클래스)

c_uint16 (ctypes 클래스)

c_uint32 (ctypes 클래스)

c_uint64 (ctypes 클래스)

c_uint8 (ctypes 클래스)

c_ulong (ctypes 클래스)

c_ulonglong (ctypes 클래스)

c_ushort (ctypes 클래스)

c_void_p (ctypes 클래스)

c_wchar (ctypes 클래스)

c_wchar_p (ctypes 클래스)

CAB (msilib 클래스)

cache_from_source() (imp 모듈)

(importlib.util 모듈)

cached (importlib.machinery.ModuleSpec의 속성)

CacheFTPHandler (urllib.request 클래스)

calcobjsize() (test.support 모듈)

calcsize() (struct 모듈)

calcvobjsize() (test.support 모듈)

Calendar (calendar 클래스)

calendar (모듈)

calendar() (calendar 모듈)

call

built-in function

built-in method

class instance

class object, [1], [2]

function, [1], [2]

instance, [1]

method

procedure

user-defined function

call() (subprocess 모듈)

(unittest.mock 모듈)

call_args (unittest.mock.Mock의 속성)

call_args_list (unittest.mock.Mock의 속성)

call_at() (asyncio.loop 메서드)

call_count (unittest.mock.Mock의 속성)

call_exception_handler() (asyncio.loop 메서드)

CALL_FUNCTION (opcode)

CALL_FUNCTION_EX (opcode)

CALL_FUNCTION_KW (opcode)

call_later() (asyncio.loop 메서드)

call_list() (unittest.mock.call 메서드)

CALL_METHOD (opcode)

call_soon() (asyncio.loop 메서드)

call_soon_threadsafe() (asyncio.loop 메서드)

call_tracing() (sys 모듈)

callable

객체, [1]

Callable (collections.abc 클래스)

(typing 모듈)

callable() (내장 함수)

CallableProxyType (weakref 모듈)

callback (optparse.Option의 속성)

callback() (contextlib.ExitStack 메서드)

callback_args (optparse.Option의 속성)

callback_kwargs (optparse.Option의 속성)

callbacks (gc 모듈)

called (unittest.mock.Mock의 속성)

CalledProcessError

calloc()

CAN_BCM (socket 모듈)

can_change_color() (curses 모듈)

can_fetch() (urllib.robotparser.RobotFileParser 메서드)

CAN_ISOTP (socket 모듈)

CAN_RAW_FD_FRAMES (socket 모듈)

can_symlink() (test.support 모듈)

can_write_eof() (asyncio.StreamWriter 메서드)

(asyncio.WriteTransport 메서드)

can_xattr() (test.support 모듈)

cancel() (asyncio.Future 메서드)

(asyncio.Handle 메서드)

(asyncio.Task 메서드)

(concurrent.futures.Future 메서드)

(sched.scheduler 메서드)

(threading.Timer 메서드)

cancel_dump_traceback_later() (faulthandler 모듈)

cancel_join_thread() (multiprocessing.Queue 메서드)

cancelled() (asyncio.Future 메서드)

(asyncio.Handle 메서드)

(asyncio.Task 메서드)

(concurrent.futures.Future 메서드)

CancelledError, [1]

CannotSendHeader

CannotSendRequest

canonic() (bdb.Bdb 메서드)

canonical() (decimal.Context 메서드)

(decimal.Decimal 메서드)

capa() (poplib.POP3 메서드)

capitalize() (bytearray 메서드)

(bytes 메서드)

(str 메서드)

Capsule

객체

captured_stderr() (test.support 모듈)

captured_stdin() (test.support 모듈)

captured_stdout() (test.support 모듈)

captureWarnings() (logging 모듈)

capwords() (string 모듈)

casefold() (str 메서드)

cast() (ctypes 모듈)

(memoryview 메서드)

(typing 모듈)

cat() (nis 모듈)

catch_warnings (warnings 클래스)

category() (unicodedata 모듈)

cbreak() (curses 모듈)

CC

ccc() (ftplib.FTP_TLS 메서드)

CCompiler (distutils.ccompiler 클래스)

CDLL (ctypes 클래스)

ceil() (in module math)

(math 모듈)

center() (bytearray 메서드)

(bytes 메서드)

(str 메서드)

CERT_NONE (ssl 모듈)

CERT_OPTIONAL (ssl 모듈)

CERT_REQUIRED (ssl 모듈)

cert_store_stats() (ssl.SSLContext 메서드)

cert_time_to_seconds() (ssl 모듈)

CertificateError

certificates

CFLAGS, [1], [2]

CFUNCTYPE() (ctypes 모듈)

CGI

debugging

exceptions

protocol

security

tracebacks

cgi (모듈)

cgi_directories (http.server.CGIHTTPRequestHandler의 속성)

CGIHandler (wsgiref.handlers 클래스)

CGIHTTPRequestHandler (http.server 클래스)

cgitb (모듈)

CGIXMLRPCRequestHandler (xmlrpc.server 클래스)

chain() (itertools 모듈)

chaining

comparisons, [1]

exception

ChainMap (collections 클래스)

(typing 클래스)

change_cwd() (test.support 모듈)

change_root() (distutils.util 모듈)

CHANNEL_BINDING_TYPES (ssl 모듈)

channel_class (smtpd.SMTPServer의 속성)

channels() (ossaudiodev.oss_audio_device 메서드)

CHAR_MAX (locale 모듈)

character, [1], [2]

CharacterDataHandler() (xml.parsers.expat.xmlparser 메서드)

characters() (xml.sax.handler.ContentHandler 메서드)

characters_written (BlockingIOError의 속성)

Charset (email.charset 클래스)

charset() (gettext.NullTranslations 메서드)

chdir() (os 모듈)

check (lzma.LZMADecompressor의 속성)

check() (imaplib.IMAP4 메서드)

(tabnanny 모듈)

check__all__() (test.support 모듈)

check_call() (subprocess 모듈)

check_environ() (distutils.util 모듈)

check_free_after_iterating() (test.support 모듈)

check_hostname (ssl.SSLContext의 속성)

check_impl_detail() (test.support 모듈)

check_no_resource_warning() (test.support 모듈)

check_output() (doctest.OutputChecker 메서드)

(subprocess 모듈)

check_returncode() (subprocess.CompletedProcess 메서드)

check_syntax_error() (test.support 모듈)

check_unused_args() (string.Formatter 메서드)

check_warnings() (test.support 모듈)

checkbox() (msilib.Dialog 메서드)

checkcache() (linecache 모듈)

CHECKED_HASH (py_compile.PycInvalidationMode의 속성)

checkfuncname() (bdb 모듈)

CheckList (tkinter.tix 클래스)

checksizeof() (test.support 모듈)

checksum

Cyclic Redundancy Check

chflags() (os 모듈)

chgat() (curses.window 메서드)

childNodes (xml.dom.Node의 속성)

ChildProcessError

children (pyclbr.Class의 속성)

(pyclbr.Function의 속성)

chmod() (os 모듈)

(pathlib.Path 메서드)

choice() (random 모듈)

(secrets 모듈)

choices (optparse.Option의 속성)

choices() (random 모듈)

chown() (os 모듈)

(shutil 모듈)

chr

내장 함수

chr() (내장 함수)

chroot() (os 모듈)

Chunk (chunk 클래스)

chunk (모듈)

cipher

DES

cipher() (ssl.SSLSocket 메서드)

circle() (turtle 모듈)

CIRCUMFLEX (token 모듈)

CIRCUMFLEXEQUAL (token 모듈)

Clamped (decimal 클래스)

class

attribute

attribute assignment

body

constructor

definition, [1]

instance

name

객체, [1], [2]

글

Class (symtable 클래스)

class (클래스)

Class browser

class instance

attribute

attribute assignment

call

객체, [1], [2]

class object

call, [1], [2]

class variable (클래스 변수)

classmethod

내장 함수

classmethod() (내장 함수)

ClassMethodDescriptorType (types 모듈)

ClassVar (typing 모듈)

clause

CLD_CONTINUED (os 모듈)

CLD_DUMPED (os 모듈)

CLD_EXITED (os 모듈)

CLD_TRAPPED (os 모듈)

clean() (mailbox.Maildir 메서드)

cleandoc() (inspect 모듈)

CleanImport (test.support 클래스)

cleanup functions

clear (pdb command)

Clear Breakpoint

clear() (asyncio.Event 메서드)

(collections.deque 메서드)

(curses.window 메서드)

(dict 메서드)

(email.message.EmailMessage 메서드)

(frame 메서드)

(frozenset 메서드)

(http.cookiejar.CookieJar 메서드)

(mailbox.Mailbox 메서드)

(sequence method)

(threading.Event 메서드)

(turtle 모듈), [1]

(xml.etree.ElementTree.Element 메서드)

clear_all_breaks() (bdb.Bdb 메서드)

clear_all_file_breaks() (bdb.Bdb 메서드)

clear_bpbynumber() (bdb.Bdb 메서드)

clear_break() (bdb.Bdb 메서드)

clear_cache() (filecmp 모듈)

clear_content() (email.message.EmailMessage 메서드)

clear_flags() (decimal.Context 메서드)

clear_frames() (traceback 모듈)

clear_history() (readline 모듈)

clear_session_cookies() (http.cookiejar.CookieJar 메서드)

clear_traces() (tracemalloc 모듈)

clear_traps() (decimal.Context 메서드)

clearcache() (linecache 모듈)

ClearData() (msilib.Record 메서드)

clearok() (curses.window 메서드)

clearscreen() (turtle 모듈)

clearstamp() (turtle 모듈)

clearstamps() (turtle 모듈)

Client() (multiprocessing.connection 모듈)

client_address (http.server.BaseHTTPRequestHandler의 속성)

clock() (time 모듈)

CLOCK_BOOTTIME (time 모듈)

clock_getres() (time 모듈)

clock_gettime() (time 모듈)

clock_gettime_ns() (time 모듈)

CLOCK_HIGHRES (time 모듈)

CLOCK_MONOTONIC (time 모듈)

CLOCK_MONOTONIC_RAW (time 모듈)

CLOCK_PROCESS_CPUTIME_ID (time 모듈)

CLOCK_PROF (time 모듈)

CLOCK_REALTIME (time 모듈)

clock_settime() (time 모듈)

clock_settime_ns() (time 모듈)

CLOCK_THREAD_CPUTIME_ID (time 모듈)

CLOCK_UPTIME (time 모듈)

clone() (email.generator.BytesGenerator 메서드)

(email.generator.Generator 메서드)

(email.policy.Policy 메서드)

(pipes.Template 메서드)

(turtle 모듈)

cloneNode() (xml.dom.Node 메서드)

close() (aifc.aifc 메서드), [1]

(asyncio.AbstractChildWatcher 메서드)

(asyncio.BaseTransport 메서드)

(asyncio.loop 메서드)

(asyncio.Server 메서드)

(asyncio.StreamWriter 메서드)

(asyncio.SubprocessTransport 메서드)

(asyncore.dispatcher 메서드)

(chunk.Chunk 메서드)

(contextlib.ExitStack 메서드)

(coroutine 메서드)

(dbm.dumb.dumbdbm 메서드)

(dbm.gnu.gdbm 메서드)

(dbm.ndbm.ndbm 메서드)

(distutils.text_file.TextFile 메서드)

(email.parser.BytesFeedParser 메서드)

(fileinput 모듈)

(ftplib.FTP 메서드)

(generator 메서드)

(html.parser.HTMLParser 메서드)

(http.client.HTTPConnection 메서드)

(imaplib.IMAP4 메서드)

(in module os)

(io.IOBase 메서드)

(logging.FileHandler 메서드)

(logging.Handler 메서드)

(logging.handlers.MemoryHandler 메서드)

(logging.handlers.NTEventLogHandler 메서드)

(logging.handlers.SocketHandler 메서드)

(logging.handlers.SysLogHandler 메서드)

(mailbox.Mailbox 메서드)

(mailbox.Maildir 메서드)

(mailbox.MH 메서드)

(mmap.mmap 메서드)

Close() (msilib.Database 메서드)

(msilib.View 메서드)

close() (multiprocessing.connection.Connection 메서드)

(multiprocessing.connection.Listener 메서드)

(multiprocessing.pool.Pool 메서드)

(multiprocessing.Process 메서드)

(multiprocessing.Queue 메서드)

(os 모듈)

(os.scandir 메서드)

(ossaudiodev.oss_audio_device 메서드)

(ossaudiodev.oss_mixer_device 메서드)

(select.devpoll 메서드)

(select.epoll 메서드)

(select.kqueue 메서드)

(selectors.BaseSelector 메서드)

(shelve.Shelf 메서드)

(socket 모듈)

(socket.socket 메서드)

(sqlite3.Connection 메서드)

(sqlite3.Cursor 메서드)

(sunau.AU_read 메서드)

(sunau.AU_write 메서드)

(tarfile.TarFile 메서드)

(telnetlib.Telnet 메서드)

(urllib.request.BaseHandler 메서드)

(wave.Wave_read 메서드)

(wave.Wave_write 메서드)

Close() (winreg.PyHKEY 메서드)

close() (xml.etree.ElementTree.TreeBuilder 메서드)

(xml.etree.ElementTree.XMLParser 메서드)

(xml.etree.ElementTree.XMLPullParser 메서드)

(xml.sax.xmlreader.IncrementalParser 메서드)

(zipfile.ZipFile 메서드)

close_connection (http.server.BaseHTTPRequestHandler의 속성)

close_when_done() (asynchat.async_chat 메서드)

closed (http.client.HTTPResponse의 속성)

(io.IOBase의 속성)

(mmap.mmap의 속성)

(ossaudiodev.oss_audio_device의 속성)

(select.devpoll의 속성)

(select.epoll의 속성)

(select.kqueue의 속성)

CloseKey() (winreg 모듈)

closelog() (syslog 모듈)

closerange() (os 모듈)

closing() (contextlib 모듈)

clrtobot() (curses.window 메서드)

clrtoeol() (curses.window 메서드)

cmath (모듈)

cmd

모듈

Cmd (cmd 클래스)

cmd (subprocess.CalledProcessError의 속성)

(subprocess.TimeoutExpired의 속성)

(모듈)

cmdloop() (cmd.Cmd 메서드)

cmdqueue (cmd.Cmd의 속성)

cmp() (filecmp 모듈)

cmp_op (dis 모듈)

cmp_to_key() (functools 모듈)

cmpfiles() (filecmp 모듈)

CMSG_LEN() (socket 모듈)

CMSG_SPACE() (socket 모듈)

co_argcount (code object attribute)

CO_ASYNC_GENERATOR (inspect 모듈)

co_cellvars (code object attribute)

co_code (code object attribute)

co_consts (code object attribute)

CO_COROUTINE (inspect 모듈)

co_filename (code object attribute)

co_firstlineno (code object attribute)

co_flags (code object attribute)

co_freevars (code object attribute)

CO_FUTURE_DIVISION (C 변수)

CO_GENERATOR (inspect 모듈)

CO_ITERABLE_COROUTINE (inspect 모듈)

co_lnotab (code object attribute)

co_name (code object attribute)

co_names (code object attribute)

CO_NESTED (inspect 모듈)

CO_NEWLOCALS (inspect 모듈)

co_nlocals (code object attribute)

CO_NOFREE (inspect 모듈)

CO_OPTIMIZED (inspect 모듈)

co_stacksize (code object attribute)

CO_VARARGS (inspect 모듈)

CO_VARKEYWORDS (inspect 모듈)

co_varnames (code object attribute)

code

block

code (SystemExit의 속성)

(urllib.error.HTTPError의 속성)

(xml.etree.ElementTree.ParseError의 속성)

(xml.parsers.expat.ExpatError의 속성)

(모듈)

code object, [1], [2], [3]

code_info() (dis 모듈)

CodecInfo (codecs 클래스)

Codecs

decode

encode

codecs (모듈)

coded_value (http.cookies.Morsel의 속성)

codeop (모듈)

codepoint2name (html.entities 모듈)

codes (xml.parsers.expat.errors 모듈)

CODESET (locale 모듈)

CodeType (types 모듈)

coding

style

coercion (코어션)

col_offset (ast.AST의 속성)

collapse_addresses() (ipaddress 모듈)

collapse_rfc2231_value() (email.utils 모듈)

collect() (gc 모듈)

collect_incoming_data() (asynchat.async_chat 메서드)

Collection (collections.abc 클래스)

(typing 클래스)

collections (모듈)

collections.abc (모듈)

colno (json.JSONDecodeError의 속성)

(re.error의 속성)

COLON (token 모듈)

color() (turtle 모듈)

color_content() (curses 모듈)

color_pair() (curses 모듈)

colormode() (turtle 모듈)

colorsys (모듈)

COLS, [1]

column() (tkinter.ttk.Treeview 메서드)

COLUMNS, [1]

columns (os.terminal_size의 속성)

combinations() (itertools 모듈)

combinations_with_replacement() (itertools 모듈)

combine() (datetime.datetime의 클래스 메서드)

combining() (unicodedata 모듈)

ComboBox (tkinter.tix 클래스)

Combobox (tkinter.ttk 클래스)

comma

trailing

COMMA (token 모듈)

Command (distutils.cmd 클래스)

(distutils.core 클래스)

command (http.server.BaseHTTPRequestHandler의 속성)

command line

command line option

--check-hash-based-pycs default|always|never

--help

--version

-?

-b

-B

-c <command>

-d

-E

-h

-i

-I

-J

-m <module-name>

-O

-OO

-q

-R

-s

-S

-u

-V

-v

-W arg

-x

-X

CommandCompiler (codeop 클래스)

commands (pdb command)

comment

(http.cookiejar.Cookie의 속성)

COMMENT (token 모듈)

comment (zipfile.ZipFile의 속성)

(zipfile.ZipInfo의 속성)

Comment() (xml.etree.ElementTree 모듈)

comment_url (http.cookiejar.Cookie의 속성)

commenters (shlex.shlex의 속성)

CommentHandler() (xml.parsers.expat.xmlparser 메서드)

commit() (msilib.CAB 메서드)

Commit() (msilib.Database 메서드)

commit() (sqlite3.Connection 메서드)

common (filecmp.dircmp의 속성)

Common Gateway Interface

common_dirs (filecmp.dircmp의 속성)

common_files (filecmp.dircmp의 속성)

common_funny (filecmp.dircmp의 속성)

common_types (mimetypes 모듈)

commonpath() (os.path 모듈)

commonprefix() (os.path 모듈)

communicate() (asyncio.asyncio.subprocess.Process의 메서드)

(subprocess.Popen 메서드)

compare() (decimal.Context 메서드)

(decimal.Decimal 메서드)

(difflib.Differ 메서드)

compare_digest() (hmac 모듈)

(secrets 모듈)

compare_networks() (ipaddress.IPv4Network 메서드)

(ipaddress.IPv6Network 메서드)

COMPARE_OP (opcode)

compare_signal() (decimal.Context 메서드)

(decimal.Decimal 메서드)

compare_to() (tracemalloc.Snapshot 메서드)

compare_total() (decimal.Context 메서드)

(decimal.Decimal 메서드)

compare_total_mag() (decimal.Context 메서드)

(decimal.Decimal 메서드)

comparing

objects

comparison

operator

COMPARISON_FLAGS (doctest 모듈)

comparisons

chaining, [1]

compat32 (email.policy 모듈)

Compat32 (email.policy 클래스)

compile

내장 함수, [1], [2], [3], [4]

Compile (codeop 클래스)

compile() (distutils.ccompiler.CCompiler 메서드)

(parser.ST 메서드)

(py_compile 모듈)

(re 모듈)

(내장 함수)

compile_command() (code 모듈)

(codeop 모듈)

compile_dir() (compileall 모듈)

compile_file() (compileall 모듈)

compile_path() (compileall 모듈)

compileall (모듈)

compileall command line option

--invalidation-mode [timestamp|checked-hash|unchecked-hash]

-b

-d destdir

-f

-i list

-j N

-l

-q

-r

-x regex

directory ...

file ...

compilest() (parser 모듈)

complete() (rlcompleter.Completer 메서드)

complete_statement() (sqlite3 모듈)

completedefault() (cmd.Cmd 메서드)

CompletedProcess (subprocess 클래스)

complex

number

객체

내장 함수, [1]

Complex (numbers 클래스)

complex (내장 클래스)

complex literal

complex number

literals

객체, [1]

complex number (복소수)

compound

statement

comprehensions

list

compress() (bz2 모듈)

(bz2.BZ2Compressor 메서드)

(gzip 모듈)

(itertools 모듈)

(lzma 모듈)

(lzma.LZMACompressor 메서드)

(zlib 모듈)

(zlib.Compress 메서드)

compress_size (zipfile.ZipInfo의 속성)

compress_type (zipfile.ZipInfo의 속성)

compressed (ipaddress.IPv4Address의 속성)

(ipaddress.IPv4Network의 속성)

(ipaddress.IPv6Address의 속성)

(ipaddress.IPv6Network의 속성)

compression() (ssl.SSLSocket 메서드)

CompressionError

compressobj() (zlib 모듈)

COMSPEC, [1]

concat() (operator 모듈)

concatenation

operation

concurrent.futures (모듈)

Condition (asyncio 클래스)

(multiprocessing 클래스)

condition (pdb command)

Condition (threading 클래스)

condition() (msilib.Control 메서드)

Condition() (multiprocessing.managers.SyncManager 메서드)

Conditional

expression

conditional

expression

ConfigParser (configparser 클래스)

configparser (모듈)

configuration

file

file, debugger

file, path

configuration information

configure() (tkinter.ttk.Style 메서드)

configure_mock() (unittest.mock.Mock 메서드)

confstr() (os 모듈)

confstr_names (os 모듈)

conjugate() (complex number method)

(decimal.Decimal 메서드)

(numbers.Complex의 메서드)

conn (smtpd.SMTPChannel의 속성)

connect() (asyncore.dispatcher 메서드)

(ftplib.FTP 메서드)

(http.client.HTTPConnection 메서드)

(multiprocessing.managers.BaseManager 메서드)

(smtplib.SMTP 메서드)

(socket.socket 메서드)

(sqlite3 모듈)

connect_accepted_socket() (asyncio.loop의 메서드)

connect_ex() (socket.socket 메서드)

connect_read_pipe() (asyncio.loop의 메서드)

connect_write_pipe() (asyncio.loop의 메서드)

Connection (multiprocessing.connection 클래스)

(sqlite3 클래스)

connection (sqlite3.Cursor의 속성)

connection_lost() (asyncio.BaseProtocol 메서드)

connection_made() (asyncio.BaseProtocol 메서드)

ConnectionAbortedError

ConnectionError

ConnectionRefusedError

ConnectionResetError

ConnectRegistry() (winreg 모듈)

const (optparse.Option의 속성)

constant

constructor

class

constructor() (copyreg 모듈)

consumed (asyncio.LimitOverrunError의 속성)

container, [1]

iteration over

Container (collections.abc 클래스)

(typing 클래스)

contains() (operator 모듈)

content type

MIME

content_manager (email.policy.EmailPolicy의 속성)

content_type (email.headerregistry.ContentTypeHeader의 속성)

ContentDispositionHeader (email.headerregistry 클래스)

ContentHandler (xml.sax.handler 클래스)

ContentManager (email.contentmanager 클래스)

contents (ctypes._Pointer의 속성)

contents() (importlib.abc.ResourceReader의 메서드)

(importlib.resources 모듈)

ContentTooShortError

ContentTransferEncoding (email.headerregistry 클래스)

ContentTypeHeader (email.headerregistry 클래스)

Context (contextvars 클래스)

(decimal 클래스)

context (ssl.SSLSocket의 속성)

context management protocol

context manager, [1]

(컨텍스트 관리자)

context variable (컨텍스트 변수)

context_diff() (difflib 모듈)

ContextDecorator (contextlib 클래스)

contextlib (모듈)

ContextManager (typing 클래스)

contextmanager() (contextlib 모듈)

ContextVar (contextvars 클래스)

contextvars (모듈)

contextvars.Token (contextvars 클래스)

contiguous

(memoryview의 속성)

(연속)

continue

글, [1], [2], [3], [4]

continue (pdb command)

CONTINUE_LOOP (opcode)

Control (msilib 클래스)

(tkinter.tix 클래스)

control() (msilib.Dialog 메서드)

(select.kqueue 메서드)

controlnames (curses.ascii 모듈)

controls() (ossaudiodev.oss_mixer_device 메서드)

conversion

arithmetic

string, [1]

ConversionError

conversions

numeric

convert_arg_line_to_args() (argparse.ArgumentParser 메서드)

convert_field() (string.Formatter 메서드)

convert_path() (distutils.util 모듈)

Cookie (http.cookiejar 클래스)

CookieError

CookieJar (http.cookiejar 클래스)

cookiejar (urllib.request.HTTPCookieProcessor의 속성)

CookiePolicy (http.cookiejar 클래스)

Coordinated Universal Time

Copy

copy

protocol

모듈

copy (모듈)

copy() (collections.deque 메서드)

(contextvars.Context 메서드)

(copy 모듈)

(decimal.Context 메서드)

(dict 메서드)

(frozenset 메서드)

(hashlib.hash 메서드)

(hmac.HMAC 메서드)

(http.cookies.Morsel 메서드)

(imaplib.IMAP4 메서드)

(multiprocessing.sharedctypes 모듈)

(pipes.Template 메서드)

(sequence method)

(shutil 모듈)

(types.MappingProxyType 메서드)

(zlib.Compress 메서드)

(zlib.Decompress 메서드)

copy2() (shutil 모듈)

copy_abs() (decimal.Context 메서드)

(decimal.Decimal 메서드)

copy_context() (contextvars 모듈)

copy_decimal() (decimal.Context 메서드)

copy_file() (distutils.file_util 모듈)

copy_location() (ast 모듈)

copy_negate() (decimal.Context 메서드)

(decimal.Decimal 메서드)

copy_sign() (decimal.Context 메서드)

(decimal.Decimal 메서드)

copy_tree() (distutils.dir_util 모듈)

copyfile() (shutil 모듈)

copyfileobj() (shutil 모듈)

copying files

copymode() (shutil 모듈)

copyreg (모듈)

copyright (in module sys)

(sys 모듈)

(내장 변수)

copysign() (math 모듈)

copystat() (shutil 모듈)

copytree() (shutil 모듈)

coroutine, [1]

function

Coroutine (collections.abc 클래스)

(typing 클래스)

coroutine (코루틴)

coroutine function (코루틴 함수)

coroutine() (asyncio 모듈)

(types 모듈)

CoroutineType (types 모듈)

cos() (cmath 모듈)

(math 모듈)

cosh() (cmath 모듈)

(math 모듈)

count (tracemalloc.StatisticDiff의 속성)

(tracemalloc.Statistic의 속성)

count() (array.array 메서드)

(bytearray 메서드)

(bytes 메서드)

(collections.deque 메서드)

(itertools 모듈)

(sequence method)

(str 메서드)

count_diff (tracemalloc.StatisticDiff의 속성)

Counter (collections 클래스)

(typing 클래스)

countOf() (operator 모듈)

countTestCases() (unittest.TestCase 메서드)

(unittest.TestSuite 메서드)

CoverageResults (trace 클래스)

CPP

CPPFLAGS

cProfile (모듈)

CPU time, [1], [2]

cpu_count() (multiprocessing 모듈)

(os 모듈)

CPython

cpython_only() (test.support 모듈)

crawl_delay() (urllib.robotparser.RobotFileParser 메서드)

CRC (zipfile.ZipInfo의 속성)

crc32() (binascii 모듈)

(zlib 모듈)

crc_hqx() (binascii 모듈)

create() (imaplib.IMAP4 메서드)

(venv 모듈)

(venv.EnvBuilder 메서드)

create_aggregate() (sqlite3.Connection 메서드)

create_archive() (zipapp 모듈)

create_autospec() (unittest.mock 모듈)

CREATE_BREAKAWAY_FROM_JOB (subprocess 모듈)

create_collation() (sqlite3.Connection 메서드)

create_configuration() (venv.EnvBuilder 메서드)

create_connection() (asyncio.loop의 메서드)

(socket 모듈)

create_datagram_endpoint() (asyncio.loop의 메서드)

create_decimal() (decimal.Context 메서드)

create_decimal_from_float() (decimal.Context 메서드)

create_default_context() (ssl 모듈)

CREATE_DEFAULT_ERROR_MODE (subprocess 모듈)

create_empty_file() (test.support 모듈)

create_function() (sqlite3.Connection 메서드)

create_future() (asyncio.loop 메서드)

create_module (C 함수)

create_module() (importlib.abc.Loader 메서드)

(importlib.machinery.ExtensionFileLoader 메서드)

CREATE_NEW_CONSOLE (subprocess 모듈)

CREATE_NEW_PROCESS_GROUP (subprocess 모듈)

CREATE_NO_WINDOW (subprocess 모듈)

create_server() (asyncio.loop의 메서드)

create_shortcut() (내장 함수)

create_socket() (asyncore.dispatcher 메서드)

create_static_lib() (distutils.ccompiler.CCompiler 메서드)

create_stats() (profile.Profile 메서드)

create_string_buffer() (ctypes 모듈)

create_subprocess_exec() (asyncio 모듈)

create_subprocess_shell() (asyncio 모듈)

create_system (zipfile.ZipInfo의 속성)

create_task() (asyncio 모듈)

(asyncio.loop 메서드)

create_tree() (distutils.dir_util 모듈)

create_unicode_buffer() (ctypes 모듈)

create_unix_connection() (asyncio.loop의 메서드)

create_unix_server() (asyncio.loop의 메서드)

create_version (zipfile.ZipInfo의 속성)

createAttribute() (xml.dom.Document 메서드)

createAttributeNS() (xml.dom.Document 메서드)

createComment() (xml.dom.Document 메서드)

createDocument() (xml.dom.DOMImplementation 메서드)

createDocumentType() (xml.dom.DOMImplementation 메서드)

createElement() (xml.dom.Document 메서드)

createElementNS() (xml.dom.Document 메서드)

createfilehandler() (tkinter.Widget.tk 메서드)

CreateKey() (winreg 모듈)

CreateKeyEx() (winreg 모듈)

createLock() (logging.Handler 메서드)

(logging.NullHandler 메서드)

createProcessingInstruction() (xml.dom.Document 메서드)

CreateRecord() (msilib 모듈)

createSocket() (logging.handlers.SocketHandler 메서드)

createTextNode() (xml.dom.Document 메서드)

credits (내장 변수)

critical() (logging 모듈)

(logging.Logger 메서드)

CRNCYSTR (locale 모듈)

cross() (audioop 모듈)

crypt

모듈

crypt (모듈)

crypt() (crypt 모듈)

crypt(3), [1], [2]

cryptography

cssclass_month (calendar.HTMLCalendar의 속성)

cssclass_month_head (calendar.HTMLCalendar의 속성)

cssclass_noday (calendar.HTMLCalendar의 속성)

cssclass_year (calendar.HTMLCalendar의 속성)

cssclass_year_head (calendar.HTMLCalendar의 속성)

cssclasses (calendar.HTMLCalendar의 속성)

cssclasses_weekday_head (calendar.HTMLCalendar의 속성)

csv

(모듈)

cte (email.headerregistry.ContentTransferEncoding의 속성)

cte_type (email.policy.Policy의 속성)

ctermid() (os 모듈)

ctime() (datetime.date 메서드)

(datetime.datetime 메서드)

(time 모듈)

ctrl() (curses.ascii 모듈)

CTRL_BREAK_EVENT (signal 모듈)

CTRL_C_EVENT (signal 모듈)

ctypes (모듈)

curdir (os 모듈)

currency() (locale 모듈)

current() (tkinter.ttk.Combobox 메서드)

current_process() (multiprocessing 모듈)

current_task() (asyncio 모듈)

(asyncio.Task의 클래스 메서드)

current_thread() (threading 모듈)

CurrentByteIndex (xml.parsers.expat.xmlparser의 속성)

CurrentColumnNumber (xml.parsers.expat.xmlparser의 속성)

currentframe() (inspect 모듈)

CurrentLineNumber (xml.parsers.expat.xmlparser의 속성)

curs_set() (curses 모듈)

curses (모듈)

curses.ascii (모듈)

curses.panel (모듈)

curses.textpad (모듈)

Cursor (sqlite3 클래스)

cursor() (sqlite3.Connection 메서드)

cursyncup() (curses.window 메서드)

customize_compiler() (distutils.sysconfig 모듈)

Cut

cwd() (ftplib.FTP 메서드)

(pathlib.Path의 클래스 메서드)

cycle() (itertools 모듈)

Cyclic Redundancy Check

D

D_FMT (locale 모듈)

D_T_FMT (locale 모듈)

daemon (multiprocessing.Process의 속성)

(threading.Thread의 속성)

dangling

else

data

packing binary

tabular

type

type, immutable

data (collections.UserDict의 속성)

(collections.UserList의 속성)

(collections.UserString의 속성)

Data (plistlib 클래스)

data (select.kevent의 속성)

(selectors.SelectorKey의 속성)

(urllib.request.Request의 속성)

(xml.dom.Comment의 속성)

(xml.dom.ProcessingInstruction의 속성)

(xml.dom.Text의 속성)

(xmlrpc.client.Binary의 속성)

data() (xml.etree.ElementTree.TreeBuilder 메서드)

data_open() (urllib.request.DataHandler 메서드)

data_received() (asyncio.Protocol 메서드)

database

Unicode

DatabaseError

databases

dataclass() (dataclasses 모듈)

dataclasses (모듈)

datagram_received() (asyncio.DatagramProtocol 메서드)

DatagramHandler (logging.handlers 클래스)

DatagramProtocol (asyncio 클래스)

DatagramRequestHandler (socketserver 클래스)

DatagramTransport (asyncio 클래스)

DataHandler (urllib.request 클래스)

date (datetime 클래스)

date() (datetime.datetime 메서드)

(nntplib.NNTP 메서드)

date_time (zipfile.ZipInfo의 속성)

date_time_string() (http.server.BaseHTTPRequestHandler 메서드)

DateHeader (email.headerregistry 클래스)

datetime (datetime 클래스)

(email.headerregistry.DateHeader의 속성)

DateTime (xmlrpc.client 클래스)

datetime (모듈)

datum

day (datetime.datetime의 속성)

(datetime.date의 속성)

day_abbr (calendar 모듈)

day_name (calendar 모듈)

daylight (time 모듈)

Daylight Saving Time

DbfilenameShelf (shelve 클래스)

dbm (모듈)

dbm.dumb (모듈)

dbm.gnu

모듈, [1]

dbm.gnu (모듈)

dbm.ndbm

모듈, [1]

dbm.ndbm (모듈)

dcgettext() (locale 모듈)

deallocation, object

debug (imaplib.IMAP4의 속성)

(pdb command)

DEBUG (re 모듈)

debug (shlex.shlex의 속성)

(zipfile.ZipFile의 속성)

debug() (doctest 모듈)

(logging 모듈)

(logging.Logger 메서드)

(pipes.Template 메서드)

(unittest.TestCase 메서드)

(unittest.TestSuite 메서드)

DEBUG_BYTECODE_SUFFIXES (importlib.machinery 모듈)

DEBUG_COLLECTABLE (gc 모듈)

DEBUG_LEAK (gc 모듈)

debug_print() (distutils.ccompiler.CCompiler 메서드)

DEBUG_SAVEALL (gc 모듈)

debug_src() (doctest 모듈)

DEBUG_STATS (gc 모듈)

DEBUG_UNCOLLECTABLE (gc 모듈)

debugger, [1], [2]

configuration file

debugging

assertions

CGI

DebuggingServer (smtpd 클래스)

debuglevel (http.client.HTTPResponse의 속성)

DebugRunner (doctest 클래스)

Decimal (decimal 클래스)

decimal (모듈)

decimal literal

decimal() (unicodedata 모듈)

DecimalException (decimal 클래스)

decode

Codecs

decode (codecs.CodecInfo의 속성)

decode() (base64 모듈)

(bytearray 메서드)

(bytes 메서드)

(codecs 모듈)

(codecs.Codec 메서드)

(codecs.IncrementalDecoder 메서드)

(json.JSONDecoder 메서드)

(quopri 모듈)

(uu 모듈)

(xmlrpc.client.Binary 메서드)

(xmlrpc.client.DateTime 메서드)

decode_header() (email.header 모듈)

(nntplib 모듈)

decode_params() (email.utils 모듈)

decode_rfc2231() (email.utils 모듈)

decode_source() (importlib.util 모듈)

decodebytes() (base64 모듈)

DecodedGenerator (email.generator 클래스)

decodestring() (base64 모듈)

(quopri 모듈)

decomposition() (unicodedata 모듈)

decompress() (bz2 모듈)

(bz2.BZ2Decompressor 메서드)

(gzip 모듈)

(lzma 모듈)

(lzma.LZMADecompressor 메서드)

(zlib 모듈)

(zlib.Decompress 메서드)

decompressobj() (zlib 모듈)

decorator (데코레이터)

DEDENT (token 모듈)

DEDENT token, [1]

dedent() (textwrap 모듈)

deepcopy() (copy 모듈)

def

글

def_prog_mode() (curses 모듈)

def_shell_mode() (curses 모듈)

default

parameter value

default (email.policy 모듈)

(inspect.Parameter의 속성)

(optparse.Option의 속성)

DEFAULT (unittest.mock 모듈)

default() (cmd.Cmd 메서드)

(json.JSONEncoder 메서드)

DEFAULT_BUFFER_SIZE (io 모듈)

default_bufsize (xml.dom.pulldom 모듈)

default_exception_handler() (asyncio.loop 메서드)

default_factory (collections.defaultdict의 속성)

DEFAULT_FORMAT (tarfile 모듈)

DEFAULT_IGNORES (filecmp 모듈)

default_open() (urllib.request.BaseHandler 메서드)

DEFAULT_PROTOCOL (pickle 모듈)

default_timer() (timeit 모듈)

DefaultContext (decimal 클래스)

DefaultCookiePolicy (http.cookiejar 클래스)

defaultdict (collections 클래스)

DefaultDict (typing 클래스)

DefaultEventLoopPolicy (asyncio 클래스)

DefaultHandler() (xml.parsers.expat.xmlparser 메서드)

DefaultHandlerExpand() (xml.parsers.expat.xmlparser 메서드)

defaults() (configparser.ConfigParser 메서드)

DefaultSelector (selectors 클래스)

defaultTestLoader (unittest 모듈)

defaultTestResult() (unittest.TestCase 메서드)

defects (email.headerregistry.BaseHeader의 속성)

(email.message.EmailMessage의 속성)

(email.message.Message의 속성)

define_macro() (distutils.ccompiler.CCompiler 메서드)

definition

class, [1]

function, [1]

defpath (os 모듈)

DefragResult (urllib.parse 클래스)

DefragResultBytes (urllib.parse 클래스)

degrees() (math 모듈)

(turtle 모듈)

del

글, [1], [2], [3]

del_param() (email.message.EmailMessage 메서드)

(email.message.Message 메서드)

delattr() (내장 함수)

delay() (turtle 모듈)

delay_output() (curses 모듈)

delayload (http.cookiejar.FileCookieJar의 속성)

delch() (curses.window 메서드)

dele() (poplib.POP3 메서드)

delete() (ftplib.FTP 메서드)

(imaplib.IMAP4 메서드)

(tkinter.ttk.Treeview 메서드)

DELETE_ATTR (opcode)

DELETE_DEREF (opcode)

DELETE_FAST (opcode)

DELETE_GLOBAL (opcode)

DELETE_NAME (opcode)

DELETE_SUBSCR (opcode)

deleteacl() (imaplib.IMAP4 메서드)

deletefilehandler() (tkinter.Widget.tk 메서드)

DeleteKey() (winreg 모듈)

DeleteKeyEx() (winreg 모듈)

deleteln() (curses.window 메서드)

deleteMe() (bdb.Breakpoint 메서드)

DeleteValue() (winreg 모듈)

deletion

attribute

target

target list

delimiter (csv.Dialect의 속성)

delimiters

delitem() (operator 모듈)

deliver_challenge() (multiprocessing.connection 모듈)

delocalize() (locale 모듈)

demo_app() (wsgiref.simple_server 모듈)

denominator (fractions.Fraction의 속성)

(numbers.Rational의 속성)

DeprecationWarning

deque (collections 클래스)

Deque (typing 클래스)

dequeue() (logging.handlers.QueueListener 메서드)

DER_cert_to_PEM_cert() (ssl 모듈)

derwin() (curses.window 메서드)

DES

cipher

description (sqlite3.Cursor의 속성)

description() (nntplib.NNTP 메서드)

descriptions() (nntplib.NNTP 메서드)

descriptor (디스크립터)

dest (optparse.Option의 속성)

destructor, [1]

detach() (io.BufferedIOBase 메서드)

(io.TextIOBase 메서드)

(socket.socket 메서드)

(tkinter.ttk.Treeview 메서드)

(weakref.finalize 메서드)

Detach() (winreg.PyHKEY 메서드)

DETACHED_PROCESS (subprocess 모듈)

detect_api_mismatch() (test.support 모듈)

detect_encoding() (tokenize 모듈)

detect_language() (distutils.ccompiler.CCompiler 메서드)

deterministic profiling

device_encoding() (os 모듈)

devnull (os 모듈)

DEVNULL (subprocess 모듈)

devpoll() (select 모듈)

DevpollSelector (selectors 클래스)

dgettext() (gettext 모듈)

(locale 모듈)

Dialect (csv 클래스)

dialect (csv.csvreader의 속성)

(csv.csvwriter의 속성)

Dialog (msilib 클래스)

dict (2to3 fixer)

Dict (typing 클래스)

dict (내장 클래스)

dict() (multiprocessing.managers.SyncManager 메서드)

dictConfig() (logging.config 모듈)

dictionary

display

type, operations on

객체, [1], [2], [3], [4], [5], [6], [7]

dictionary (딕셔너리)

dictionary view (딕셔너리 뷰)

DictReader (csv 클래스)

DictWriter (csv 클래스)

diff_bytes() (difflib 모듈)

diff_files (filecmp.dircmp의 속성)

Differ (difflib 클래스), [1]

difference() (frozenset 메서드)

difference_update() (frozenset 메서드)

difflib (모듈)

digest() (hashlib.hash 메서드)

(hashlib.shake 메서드)

(hmac 모듈)

(hmac.HMAC 메서드)

digest_size (hmac.HMAC의 속성)

digit() (unicodedata 모듈)

digits (string 모듈)

dir() (ftplib.FTP 메서드)

(내장 함수)

dircmp (filecmp 클래스)

directory

changing

creating

deleting, [1]

site-packages

traversal, [1]

walking, [1]

directory (http.server.SimpleHTTPRequestHandler의 속성)

Directory (msilib 클래스)

directory ...

compileall command line option

directory_created() (내장 함수)

DirEntry (os 클래스)

DirList (tkinter.tix 클래스)

dirname() (os.path 모듈)

DirSelectBox (tkinter.tix 클래스)

DirSelectDialog (tkinter.tix 클래스)

DirsOnSysPath (test.support 클래스)

DirTree (tkinter.tix 클래스)

dis (모듈)

dis() (dis 모듈)

(dis.Bytecode 메서드)

(pickletools 모듈)

disable (pdb command)

disable() (bdb.Breakpoint 메서드)

(faulthandler 모듈)

(gc 모듈)

(logging 모듈)

(profile.Profile 메서드)

disable_faulthandler() (test.support 모듈)

disable_gc() (test.support 모듈)

disable_interspersed_args() (optparse.OptionParser 메서드)

DisableReflectionKey() (winreg 모듈)

disassemble() (dis 모듈)

discard (http.cookiejar.Cookie의 속성)

discard() (frozenset 메서드)

(mailbox.Mailbox 메서드)

(mailbox.MH 메서드)

discard_buffers() (asynchat.async_chat 메서드)

disco() (dis 모듈)

discover() (unittest.TestLoader 메서드)

disk_usage() (shutil 모듈)

dispatch_call() (bdb.Bdb 메서드)

dispatch_exception() (bdb.Bdb 메서드)

dispatch_line() (bdb.Bdb 메서드)

dispatch_return() (bdb.Bdb 메서드)

dispatch_table (pickle.Pickler의 속성)

dispatcher (asyncore 클래스)

dispatcher_with_send (asyncore 클래스)

display

dictionary

list

set

display (pdb command)

display_name (email.headerregistry.Address의 속성)

(email.headerregistry.Group의 속성)

displayhook() (sys 모듈)

dist() (platform 모듈)

distance() (turtle 모듈)

distb() (dis 모듈)

Distribution (distutils.core 클래스)

distutils (모듈)

distutils.archive_util (모듈)

distutils.bcppcompiler (모듈)

distutils.ccompiler (모듈)

distutils.cmd (모듈)

distutils.command (모듈)

distutils.command.bdist (모듈)

distutils.command.bdist_dumb (모듈)

distutils.command.bdist_msi (모듈)

distutils.command.bdist_packager (모듈)

distutils.command.bdist_rpm (모듈)

distutils.command.bdist_wininst (모듈)

distutils.command.build (모듈)

distutils.command.build_clib (모듈)

distutils.command.build_ext (모듈)

distutils.command.build_py (모듈)

distutils.command.build_scripts (모듈)

distutils.command.check (모듈)

distutils.command.clean (모듈)

distutils.command.config (모듈)

distutils.command.install (모듈)

distutils.command.install_data (모듈)

distutils.command.install_headers (모듈)

distutils.command.install_lib (모듈)

distutils.command.install_scripts (모듈)

distutils.command.register (모듈)

distutils.command.sdist (모듈)

distutils.core (모듈)

distutils.cygwinccompiler (모듈)

distutils.debug (모듈)

distutils.dep_util (모듈)

distutils.dir_util (모듈)

distutils.dist (모듈)

distutils.errors (모듈)

distutils.extension (모듈)

distutils.fancy_getopt (모듈)

distutils.file_util (모듈)

distutils.filelist (모듈)

distutils.log (모듈)

distutils.msvccompiler (모듈)

distutils.spawn (모듈)

distutils.sysconfig (모듈)

distutils.text_file (모듈)

distutils.unixccompiler (모듈)

distutils.util (모듈)

distutils.version (모듈)

DISTUTILS_DEBUG

divide() (decimal.Context 메서드)

divide_int() (decimal.Context 메서드)

division

DivisionByZero (decimal 클래스)

divmod

내장 함수, [1], [2]

divmod() (decimal.Context 메서드)

(내장 함수)

DllCanUnloadNow() (ctypes 모듈)

DllGetClassObject() (ctypes 모듈)

dllhandle (sys 모듈)

dngettext() (gettext 모듈)

do_clear() (bdb.Bdb 메서드)

do_command() (curses.textpad.Textbox 메서드)

do_GET() (http.server.SimpleHTTPRequestHandler 메서드)

do_handshake() (ssl.SSLSocket 메서드)

do_HEAD() (http.server.SimpleHTTPRequestHandler 메서드)

do_POST() (http.server.CGIHTTPRequestHandler 메서드)

doc (json.JSONDecodeError의 속성)

doc_header (cmd.Cmd의 속성)

DocCGIXMLRPCRequestHandler (xmlrpc.server 클래스)

DocFileSuite() (doctest 모듈)

doCleanups() (unittest.TestCase 메서드)

docmd() (smtplib.SMTP 메서드)

docstring

(doctest.DocTest의 속성)

(독스트링)

docstrings, [1]

DocTest (doctest 클래스)

doctest (모듈)

DocTestFailure

DocTestFinder (doctest 클래스)

DocTestParser (doctest 클래스)

DocTestRunner (doctest 클래스)

DocTestSuite() (doctest 모듈)

doctype() (xml.etree.ElementTree.TreeBuilder 메서드)

(xml.etree.ElementTree.XMLParser 메서드)

documentation

generation

online

documentation string

documentation strings, [1]

documentElement (xml.dom.Document의 속성)

DocXMLRPCRequestHandler (xmlrpc.server 클래스)

DocXMLRPCServer (xmlrpc.server 클래스)

domain (email.headerregistry.Address의 속성)

(tracemalloc.DomainFilter의 속성)

(tracemalloc.Filter의 속성)

(tracemalloc.Trace의 속성)

domain_initial_dot (http.cookiejar.Cookie의 속성)

domain_return_ok() (http.cookiejar.CookiePolicy 메서드)

domain_specified (http.cookiejar.Cookie의 속성)

DomainFilter (tracemalloc 클래스)

DomainLiberal (http.cookiejar.DefaultCookiePolicy의 속성)

DomainRFC2965Match (http.cookiejar.DefaultCookiePolicy의 속성)

DomainStrict (http.cookiejar.DefaultCookiePolicy의 속성)

DomainStrictNoDots (http.cookiejar.DefaultCookiePolicy의 속성)

DomainStrictNonDomain (http.cookiejar.DefaultCookiePolicy의 속성)

DOMEventStream (xml.dom.pulldom 클래스)

DOMException

DomstringSizeErr

done() (asyncio.Future 메서드)

(asyncio.Task 메서드)

(concurrent.futures.Future 메서드)

(turtle 모듈)

(xdrlib.Unpacker 메서드)

DONT_ACCEPT_BLANKLINE (doctest 모듈)

DONT_ACCEPT_TRUE_FOR_1 (doctest 모듈)

dont_write_bytecode (sys 모듈)

doRollover() (logging.handlers.RotatingFileHandler 메서드)

(logging.handlers.TimedRotatingFileHandler 메서드)

DOT (token 모듈)

dot() (turtle 모듈)

DOTALL (re 모듈)

doublequote (csv.Dialect의 속성)

DOUBLESLASH (token 모듈)

DOUBLESLASHEQUAL (token 모듈)

DOUBLESTAR (token 모듈)

DOUBLESTAREQUAL (token 모듈)

doupdate() (curses 모듈)

down (pdb command)

down() (turtle 모듈)

drain() (asyncio.StreamWriter의 메서드)

drop_whitespace (textwrap.TextWrapper의 속성)

dropwhile() (itertools 모듈)

dst() (datetime.datetime 메서드)

(datetime.time 메서드)

(datetime.timezone 메서드)

(datetime.tzinfo 메서드)

DTDHandler (xml.sax.handler 클래스)

duck-typing (덕 타이핑)

DumbWriter (formatter 클래스)

dummy_threading (모듈)

dump() (ast 모듈)

(json 모듈)

(marshal 모듈)

(pickle 모듈)

(pickle.Pickler 메서드)

(plistlib 모듈)

(tracemalloc.Snapshot 메서드)

(xml.etree.ElementTree 모듈)

dump_stats() (profile.Profile 메서드)

(pstats.Stats 메서드)

dump_traceback() (faulthandler 모듈)

dump_traceback_later() (faulthandler 모듈)

dumps() (json 모듈)

(marshal 모듈)

(pickle 모듈)

(plistlib 모듈)

(xmlrpc.client 모듈)

dup() (os 모듈)

(socket.socket 메서드)

dup2() (os 모듈)

DUP_TOP (opcode)

DUP_TOP_TWO (opcode)

DuplicateOptionError

DuplicateSectionError

dwFlags (subprocess.STARTUPINFO의 속성)

DynamicClassAttribute() (types 모듈)

E

e

in numeric literal

e (cmath 모듈)

(math 모듈)

E2BIG (errno 모듈)

EACCES (errno 모듈)

EADDRINUSE (errno 모듈)

EADDRNOTAVAIL (errno 모듈)

EADV (errno 모듈)

EAFNOSUPPORT (errno 모듈)

EAFP

EAGAIN (errno 모듈)

EALREADY (errno 모듈)

east_asian_width() (unicodedata 모듈)

EBADE (errno 모듈)

EBADF (errno 모듈)

EBADFD (errno 모듈)

EBADMSG (errno 모듈)

EBADR (errno 모듈)

EBADRQC (errno 모듈)

EBADSLT (errno 모듈)

EBFONT (errno 모듈)

EBUSY (errno 모듈)

ECHILD (errno 모듈)

echo() (curses 모듈)

echochar() (curses.window 메서드)

ECHRNG (errno 모듈)

ECOMM (errno 모듈)

ECONNABORTED (errno 모듈)

ECONNREFUSED (errno 모듈)

ECONNRESET (errno 모듈)

EDEADLK (errno 모듈)

EDEADLOCK (errno 모듈)

EDESTADDRREQ (errno 모듈)

edit() (curses.textpad.Textbox 메서드)

EDOM (errno 모듈)

EDOTDOT (errno 모듈)

EDQUOT (errno 모듈)

EEXIST (errno 모듈)

EFAULT (errno 모듈)

EFBIG (errno 모듈)

effective() (bdb 모듈)

ehlo() (smtplib.SMTP 메서드)

ehlo_or_helo_if_needed() (smtplib.SMTP 메서드)

EHOSTDOWN (errno 모듈)

EHOSTUNREACH (errno 모듈)

EIDRM (errno 모듈)

EILSEQ (errno 모듈)

EINPROGRESS (errno 모듈)

EINTR (errno 모듈)

EINVAL (errno 모듈)

EIO (errno 모듈)

EISCONN (errno 모듈)

EISDIR (errno 모듈)

EISNAM (errno 모듈)

EL2HLT (errno 모듈)

EL2NSYNC (errno 모듈)

EL3HLT (errno 모듈)

EL3RST (errno 모듈)

Element (xml.etree.ElementTree 클래스)

element_create() (tkinter.ttk.Style 메서드)

element_names() (tkinter.ttk.Style 메서드)

element_options() (tkinter.ttk.Style 메서드)

ElementDeclHandler() (xml.parsers.expat.xmlparser 메서드)

elements() (collections.Counter 메서드)

ElementTree (xml.etree.ElementTree 클래스)

ELIBACC (errno 모듈)

ELIBBAD (errno 모듈)

ELIBEXEC (errno 모듈)

ELIBMAX (errno 모듈)

ELIBSCN (errno 모듈)

elif

키워드

Ellinghouse, Lance

Ellipsis

객체

ELLIPSIS (doctest 모듈)

(token 모듈)

Ellipsis (내장 변수)

ELNRNG (errno 모듈)

ELOOP (errno 모듈)

else

conditional expression

dangling

키워드, [1], [2], [3], [4], [5]

email (모듈)

email.charset (모듈)

email.contentmanager (모듈)

email.encoders (모듈)

email.errors (모듈)

email.generator (모듈)

email.header (모듈)

email.headerregistry (모듈)

email.iterators (모듈)

email.message (모듈)

email.mime (모듈)

email.parser (모듈)

email.policy (모듈)

email.utils (모듈)

EmailMessage (email.message 클래스)

EmailPolicy (email.policy 클래스)

EMFILE (errno 모듈)

emit() (logging.FileHandler 메서드)

(logging.Handler 메서드)

(logging.handlers.BufferingHandler 메서드)

(logging.handlers.DatagramHandler 메서드)

(logging.handlers.HTTPHandler 메서드)

(logging.handlers.NTEventLogHandler 메서드)

(logging.handlers.QueueHandler 메서드)

(logging.handlers.RotatingFileHandler 메서드)

(logging.handlers.SMTPHandler 메서드)

(logging.handlers.SocketHandler 메서드)

(logging.handlers.SysLogHandler 메서드)

(logging.handlers.TimedRotatingFileHandler 메서드)

(logging.handlers.WatchedFileHandler 메서드)

(logging.NullHandler 메서드)

(logging.StreamHandler 메서드)

EMLINK (errno 모듈)

Empty

empty

list

tuple, [1]

empty (inspect.Parameter의 속성)

(inspect.Signature의 속성)

empty() (asyncio.Queue 메서드)

(multiprocessing.Queue 메서드)

(multiprocessing.SimpleQueue 메서드)

(queue.Queue 메서드)

(queue.SimpleQueue 메서드)

(sched.scheduler 메서드)

EMPTY_NAMESPACE (xml.dom 모듈)

emptyline() (cmd.Cmd 메서드)

EMSGSIZE (errno 모듈)

EMULTIHOP (errno 모듈)

enable (pdb command)

enable() (bdb.Breakpoint 메서드)

(cgitb 모듈)

(faulthandler 모듈)

(gc 모듈)

(imaplib.IMAP4 메서드)

(profile.Profile 메서드)

enable_callback_tracebacks() (sqlite3 모듈)

enable_interspersed_args() (optparse.OptionParser 메서드)

enable_load_extension() (sqlite3.Connection 메서드)

enable_traversal() (tkinter.ttk.Notebook 메서드)

ENABLE_USER_SITE (site 모듈)

EnableReflectionKey() (winreg 모듈)

ENAMETOOLONG (errno 모듈)

ENAVAIL (errno 모듈)

enclose() (curses.window 메서드)

encode

Codecs

encode (codecs.CodecInfo의 속성)

encode() (base64 모듈)

(codecs 모듈)

(codecs.Codec 메서드)

(codecs.IncrementalEncoder 메서드)

(email.header.Header 메서드)

(json.JSONEncoder 메서드)

(quopri 모듈)

(str 메서드)

(uu 모듈)

(xmlrpc.client.Binary 메서드)

(xmlrpc.client.DateTime 메서드)

encode_7or8bit() (email.encoders 모듈)

encode_base64() (email.encoders 모듈)

encode_noop() (email.encoders 모듈)

encode_quopri() (email.encoders 모듈)

encode_rfc2231() (email.utils 모듈)

encodebytes() (base64 모듈)

EncodedFile() (codecs 모듈)

encodePriority() (logging.handlers.SysLogHandler 메서드)

encodestring() (base64 모듈)

(quopri 모듈)

encoding

base64

quoted-printable

encoding (curses.window의 속성)

(io.TextIOBase의 속성)

ENCODING (tarfile 모듈)

(token 모듈)

encoding (UnicodeError의 속성)

encoding declarations (source file)

encodings.idna (모듈)

encodings.mbcs (모듈)

encodings.utf_8_sig (모듈)

encodings_map (mimetypes 모듈)

(mimetypes.MimeTypes의 속성)

end (UnicodeError의 속성)

end() (re.Match 메서드)

(xml.etree.ElementTree.TreeBuilder 메서드)

end_fill() (turtle 모듈)

END_FINALLY (opcode)

end_headers() (http.server.BaseHTTPRequestHandler 메서드)

end_paragraph() (formatter.formatter 메서드)

end_poly() (turtle 모듈)

EndCdataSectionHandler() (xml.parsers.expat.xmlparser 메서드)

EndDoctypeDeclHandler() (xml.parsers.expat.xmlparser 메서드)

endDocument() (xml.sax.handler.ContentHandler 메서드)

endElement() (xml.sax.handler.ContentHandler 메서드)

EndElementHandler() (xml.parsers.expat.xmlparser 메서드)

endElementNS() (xml.sax.handler.ContentHandler 메서드)

endheaders() (http.client.HTTPConnection 메서드)

ENDMARKER (token 모듈)

EndNamespaceDeclHandler() (xml.parsers.expat.xmlparser 메서드)

endpos (re.Match의 속성)

endPrefixMapping() (xml.sax.handler.ContentHandler 메서드)

endswith() (bytearray 메서드)

(bytes 메서드)

(str 메서드)

endwin() (curses 모듈)

ENETDOWN (errno 모듈)

ENETRESET (errno 모듈)

ENETUNREACH (errno 모듈)

ENFILE (errno 모듈)

ENOANO (errno 모듈)

ENOBUFS (errno 모듈)

ENOCSI (errno 모듈)

ENODATA (errno 모듈)

ENODEV (errno 모듈)

ENOENT (errno 모듈)

ENOEXEC (errno 모듈)

ENOLCK (errno 모듈)

ENOLINK (errno 모듈)

ENOMEM (errno 모듈)

ENOMSG (errno 모듈)

ENONET (errno 모듈)

ENOPKG (errno 모듈)

ENOPROTOOPT (errno 모듈)

ENOSPC (errno 모듈)

ENOSR (errno 모듈)

ENOSTR (errno 모듈)

ENOSYS (errno 모듈)

ENOTBLK (errno 모듈)

ENOTCONN (errno 모듈)

ENOTDIR (errno 모듈)

ENOTEMPTY (errno 모듈)

ENOTNAM (errno 모듈)

ENOTSOCK (errno 모듈)

ENOTTY (errno 모듈)

ENOTUNIQ (errno 모듈)

enqueue() (logging.handlers.QueueHandler 메서드)

enqueue_sentinel() (logging.handlers.QueueListener 메서드)

ensure_directories() (venv.EnvBuilder 메서드)

ensure_future() (asyncio 모듈)

ensurepip (모듈)

enter() (sched.scheduler 메서드)

enter_async_context() (contextlib.AsyncExitStack 메서드)

enter_context() (contextlib.ExitStack 메서드)

enterabs() (sched.scheduler 메서드)

entities (xml.dom.DocumentType의 속성)

EntityDeclHandler() (xml.parsers.expat.xmlparser 메서드)

entitydefs (html.entities 모듈)

EntityResolver (xml.sax.handler 클래스)

Enum (enum 클래스)

enum (모듈)

enum_certificates() (ssl 모듈)

enum_crls() (ssl 모듈)

enumerate() (threading 모듈)

(내장 함수)

EnumKey() (winreg 모듈)

EnumValue() (winreg 모듈)

EnvBuilder (venv 클래스)

environ (os 모듈)

(posix 모듈)

environb (os 모듈)

environment

environment variables

deleting

setting

EnvironmentError

Environments

virtual

EnvironmentVarGuard (test.support 클래스)

ENXIO (errno 모듈)

eof (bz2.BZ2Decompressor의 속성)

(lzma.LZMADecompressor의 속성)

(shlex.shlex의 속성)

(ssl.MemoryBIO의 속성)

(zlib.Decompress의 속성)

eof_received() (asyncio.BufferedProtocol 메서드)

(asyncio.Protocol 메서드)

EOFError

(built-in exception)

EOPNOTSUPP (errno 모듈)

EOVERFLOW (errno 모듈)

EPERM (errno 모듈)

EPFNOSUPPORT (errno 모듈)

epilogue (email.message.EmailMessage의 속성)

(email.message.Message의 속성)

EPIPE (errno 모듈)

epoch

epoll() (select 모듈)

EpollSelector (selectors 클래스)

EPROTO (errno 모듈)

EPROTONOSUPPORT (errno 모듈)

EPROTOTYPE (errno 모듈)

eq() (operator 모듈)

EQEQUAL (token 모듈)

EQUAL (token 모듈)

ERA (locale 모듈)

ERA_D_FMT (locale 모듈)

ERA_D_T_FMT (locale 모듈)

ERA_T_FMT (locale 모듈)

ERANGE (errno 모듈)

erase() (curses.window 메서드)

erasechar() (curses 모듈)

EREMCHG (errno 모듈)

EREMOTE (errno 모듈)

EREMOTEIO (errno 모듈)

ERESTART (errno 모듈)

erf() (math 모듈)

erfc() (math 모듈)

EROFS (errno 모듈)

ERR (curses 모듈)

errcheck (ctypes._FuncPtr의 속성)

errcode (xmlrpc.client.ProtocolError의 속성)

errmsg (xmlrpc.client.ProtocolError의 속성)

errno

모듈

errno (OSError의 속성)

(모듈)

Error, [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12]

error, [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12], [13], [14], [15], [16], [17]

error handling

error() (argparse.ArgumentParser 메서드)

(logging 모듈)

(logging.Logger 메서드)

(urllib.request.OpenerDirector 메서드)

(xml.sax.handler.ErrorHandler 메서드)

error_body (wsgiref.handlers.BaseHandler의 속성)

error_content_type (http.server.BaseHTTPRequestHandler의 속성)

error_headers (wsgiref.handlers.BaseHandler의 속성)

error_leader() (shlex.shlex 메서드)

error_message_format (http.server.BaseHTTPRequestHandler의 속성)

error_output() (wsgiref.handlers.BaseHandler 메서드)

error_perm

error_proto, [1]

error_received() (asyncio.DatagramProtocol 메서드)

error_reply

error_status (wsgiref.handlers.BaseHandler의 속성)

error_temp

ErrorByteIndex (xml.parsers.expat.xmlparser의 속성)

errorcode (errno 모듈)

ErrorCode (xml.parsers.expat.xmlparser의 속성)

ErrorColumnNumber (xml.parsers.expat.xmlparser의 속성)

ErrorHandler (xml.sax.handler 클래스)

ErrorLineNumber (xml.parsers.expat.xmlparser의 속성)

Errors

logging

errors

(io.TextIOBase의 속성)

(unittest.TestLoader의 속성)

(unittest.TestResult의 속성)

ErrorString() (xml.parsers.expat 모듈)

ERRORTOKEN (token 모듈)

escape (shlex.shlex의 속성)

escape sequence

escape() (cgi 모듈)

(glob 모듈)

(html 모듈)

(re 모듈)

(xml.sax.saxutils 모듈)

escapechar (csv.Dialect의 속성)

escapedquotes (shlex.shlex의 속성)

ESHUTDOWN (errno 모듈)

ESOCKTNOSUPPORT (errno 모듈)

ESPIPE (errno 모듈)

ESRCH (errno 모듈)

ESRMNT (errno 모듈)

ESTALE (errno 모듈)

ESTRPIPE (errno 모듈)

ETIME (errno 모듈)

ETIMEDOUT (errno 모듈)

Etiny() (decimal.Context 메서드)

ETOOMANYREFS (errno 모듈)

Etop() (decimal.Context 메서드)

ETXTBSY (errno 모듈)

EUCLEAN (errno 모듈)

EUNATCH (errno 모듈)

EUSERS (errno 모듈)

eval

내장 함수, [1], [2], [3], [4], [5]

eval() (내장 함수)

evaluation

order

Event (asyncio 클래스)

(multiprocessing 클래스)

(threading 클래스)

event scheduling

event() (msilib.Control 메서드)

Event() (multiprocessing.managers.SyncManager 메서드)

events (selectors.SelectorKey의 속성)

(widgets)

EWOULDBLOCK (errno 모듈)

EX_CANTCREAT (os 모듈)

EX_CONFIG (os 모듈)

EX_DATAERR (os 모듈)

EX_IOERR (os 모듈)

EX_NOHOST (os 모듈)

EX_NOINPUT (os 모듈)

EX_NOPERM (os 모듈)

EX_NOTFOUND (os 모듈)

EX_NOUSER (os 모듈)

EX_OK (os 모듈)

EX_OSERR (os 모듈)

EX_OSFILE (os 모듈)

EX_PROTOCOL (os 모듈)

EX_SOFTWARE (os 모듈)

EX_TEMPFAIL (os 모듈)

EX_UNAVAILABLE (os 모듈)

EX_USAGE (os 모듈)

Example (doctest 클래스)

example (doctest.DocTestFailure의 속성)

(doctest.UnexpectedException의 속성)

examples (doctest.DocTest의 속성)

exc_info (doctest.UnexpectedException의 속성)

(in module sys)

exc_info() (in module sys)

(sys 모듈)

exc_msg (doctest.Example의 속성)

exc_type (traceback.TracebackException의 속성)

excel (csv 클래스)

excel_tab (csv 클래스)

except

글

키워드

except (2to3 fixer)

excepthook() (in module sys)

(sys 모듈)

Exception

exception, [1]

chaining

handler

raising

EXCEPTION (tkinter 모듈)

exception handler

exception() (asyncio.Future 메서드)

(asyncio.Task 메서드)

(concurrent.futures.Future 메서드)

(logging 모듈)

(logging.Logger 메서드)

exceptions

in CGI scripts

exclusive

or

EXDEV (errno 모듈)

exec

내장 함수, [1], [2], [3]

exec (2to3 fixer)

exec() (내장 함수)

exec_module (C 함수)

exec_module() (importlib.abc.InspectLoader 메서드)

(importlib.abc.Loader 메서드)

(importlib.abc.SourceLoader 메서드)

(importlib.machinery.ExtensionFileLoader 메서드)

exec_prefix, [1], [2]

EXEC_PREFIX (distutils.sysconfig 모듈)

exec_prefix (sys 모듈)

execfile (2to3 fixer)

execl() (os 모듈)

execle() (os 모듈)

execlp() (os 모듈)

execlpe() (os 모듈)

executable (in module sys)

(sys 모듈)

Executable Zip Files

executable_filename() (distutils.ccompiler.CCompiler 메서드)

execute() (distutils.ccompiler.CCompiler 메서드)

(distutils.util 모듈)

Execute() (msilib.View 메서드)

execute() (sqlite3.Connection 메서드)

(sqlite3.Cursor 메서드)

executemany() (sqlite3.Connection 메서드)

(sqlite3.Cursor 메서드)

executescript() (sqlite3.Connection 메서드)

(sqlite3.Cursor 메서드)

execution

frame, [1]

restricted

stack

execution model

ExecutionLoader (importlib.abc 클래스)

Executor (concurrent.futures 클래스)

execv() (os 모듈)

execve() (os 모듈)

execvp() (os 모듈)

execvpe() (os 모듈)

ExFileSelectBox (tkinter.tix 클래스)

EXFULL (errno 모듈)

exists() (os.path 모듈)

(pathlib.Path 메서드)

(tkinter.ttk.Treeview 메서드)

exit (내장 변수)

exit()

(_thread 모듈)

(argparse.ArgumentParser 메서드)

(sys 모듈)

exitcode (multiprocessing.Process의 속성)

exitfunc (2to3 fixer)

exitonclick() (turtle 모듈)

ExitStack (contextlib 클래스)

exp() (cmath 모듈)

(decimal.Context 메서드)

(decimal.Decimal 메서드)

(math 모듈)

expand() (re.Match 메서드)

expand_tabs (textwrap.TextWrapper의 속성)

ExpandEnvironmentStrings() (winreg 모듈)

expandNode() (xml.dom.pulldom.DOMEventStream 메서드)

expandtabs() (bytearray 메서드)

(bytes 메서드)

(str 메서드)

expanduser() (os.path 모듈)

(pathlib.Path 메서드)

expandvars() (os.path 모듈)

Expat

ExpatError

expect() (telnetlib.Telnet 메서드)

expected (asyncio.IncompleteReadError의 속성)

expectedFailure() (unittest 모듈)

expectedFailures (unittest.TestResult의 속성)

expires (http.cookiejar.Cookie의 속성)

exploded (ipaddress.IPv4Address의 속성)

(ipaddress.IPv4Network의 속성)

(ipaddress.IPv6Address의 속성)

(ipaddress.IPv6Network의 속성)

expm1() (math 모듈)

expovariate() (random 모듈)

expr() (parser 모듈)

expression

Conditional

conditional

generator

lambda, [1]

list, [1], [2]

statement

yield

expression (표현식)

expunge() (imaplib.IMAP4 메서드)

extend() (array.array 메서드)

(collections.deque 메서드)

(sequence method)

(xml.etree.ElementTree.Element 메서드)

extend_path() (pkgutil 모듈)

EXTENDED_ARG (opcode)

ExtendedContext (decimal 클래스)

ExtendedInterpolation (configparser 클래스)

extendleft() (collections.deque 메서드)

extension

module

Extension (distutils.core 클래스)

extension module (확장 모듈)

EXTENSION_SUFFIXES (importlib.machinery 모듈)

ExtensionFileLoader (importlib.machinery 클래스)

extensions_map (http.server.SimpleHTTPRequestHandler의 속성)

External Data Representation, [1]

external_attr (zipfile.ZipInfo의 속성)

ExternalClashError

ExternalEntityParserCreate() (xml.parsers.expat.xmlparser 메서드)

ExternalEntityRefHandler() (xml.parsers.expat.xmlparser 메서드)

extra (zipfile.ZipInfo의 속성)

extract() (tarfile.TarFile 메서드)

(traceback.StackSummary의 클래스 메서드)

(zipfile.ZipFile 메서드)

extract_cookies() (http.cookiejar.CookieJar 메서드)

extract_stack() (traceback 모듈)

extract_tb() (traceback 모듈)

extract_version (zipfile.ZipInfo의 속성)

extractall() (tarfile.TarFile 메서드)

(zipfile.ZipFile 메서드)

ExtractError

extractfile() (tarfile.TarFile 메서드)

extsep (os 모듈)

F

f"

formatted string literal

f'

formatted string literal

f-string

(f-문자열)

f_back (frame attribute)

f_builtins (frame attribute)

f_code (frame attribute)

f_contiguous (memoryview의 속성)

f_globals (frame attribute)

f_lasti (frame attribute)

f_lineno (frame attribute)

f_locals (frame attribute)

F_LOCK (os 모듈)

F_OK (os 모듈)

F_TEST (os 모듈)

F_TLOCK (os 모듈)

f_trace (frame attribute)

f_trace_lines (frame attribute)

f_trace_opcodes (frame attribute)

F_ULOCK (os 모듈)

fabs() (math 모듈)

factorial() (math 모듈)

factory() (importlib.util.LazyLoader의 클래스 메서드)

fail() (unittest.TestCase 메서드)

FAIL_FAST (doctest 모듈)

failfast (unittest.TestResult의 속성)

failureException (unittest.TestCase의 속성)

failures (unittest.TestResult의 속성)

FakePath (test.support 클래스)

False, [1], [2]

false

False (Built-in object)

(내장 변수)

family (socket.socket의 속성)

fancy_getopt() (distutils.fancy_getopt 모듈)

FancyGetopt (distutils.fancy_getopt 클래스)

FancyURLopener (urllib.request 클래스)

fast (pickle.Pickler의 속성)

FastChildWatcher (asyncio 클래스)

fatalError() (xml.sax.handler.ErrorHandler 메서드)

Fault (xmlrpc.client 클래스)

faultCode (xmlrpc.client.Fault의 속성)

faulthandler (모듈)

faultString (xmlrpc.client.Fault의 속성)

fchdir() (os 모듈)

fchmod() (os 모듈)

fchown() (os 모듈)

FCICreate() (msilib 모듈)

fcntl (모듈)

fcntl() (fcntl 모듈)

fd (selectors.SelectorKey의 속성)

fd() (turtle 모듈)

fd_count() (test.support 모듈)

fdatasync() (os 모듈)

fdopen() (os 모듈)

Feature (msilib 클래스)

feature_external_ges (xml.sax.handler 모듈)

feature_external_pes (xml.sax.handler 모듈)

feature_namespace_prefixes (xml.sax.handler 모듈)

feature_namespaces (xml.sax.handler 모듈)

feature_string_interning (xml.sax.handler 모듈)

feature_validation (xml.sax.handler 모듈)

feed() (email.parser.BytesFeedParser 메서드)

(html.parser.HTMLParser 메서드)

(xml.etree.ElementTree.XMLParser 메서드)

(xml.etree.ElementTree.XMLPullParser 메서드)

(xml.sax.xmlreader.IncrementalParser 메서드)

FeedParser (email.parser 클래스)

fetch() (imaplib.IMAP4 메서드)

Fetch() (msilib.View 메서드)

fetchall() (sqlite3.Cursor 메서드)

fetchmany() (sqlite3.Cursor 메서드)

fetchone() (sqlite3.Cursor 메서드)

fflags (select.kevent의 속성)

Field (dataclasses 클래스)

field() (dataclasses 모듈)

field_size_limit() (csv 모듈)

fieldnames (csv.csvreader의 속성)

fields (uuid.UUID의 속성)

fields() (dataclasses 모듈)

file

.ini

.pdbrc

byte-code, [1]

configuration

copying

debugger configuration

large files

mime.types

modes

path configuration

plist

temporary

객체, [1]

file (pyclbr.Class의 속성)

(pyclbr.Function의 속성)

file ...

compileall command line option

file control

UNIX

file name

temporary

file object

io module

open() built-in function

file object (파일 객체)

file-like object (파일류 객체)

FILE_ATTRIBUTE_ARCHIVE (stat 모듈)

FILE_ATTRIBUTE_COMPRESSED (stat 모듈)

FILE_ATTRIBUTE_DEVICE (stat 모듈)

FILE_ATTRIBUTE_DIRECTORY (stat 모듈)

FILE_ATTRIBUTE_ENCRYPTED (stat 모듈)

FILE_ATTRIBUTE_HIDDEN (stat 모듈)

FILE_ATTRIBUTE_INTEGRITY_STREAM (stat 모듈)

FILE_ATTRIBUTE_NO_SCRUB_DATA (stat 모듈)

FILE_ATTRIBUTE_NORMAL (stat 모듈)

FILE_ATTRIBUTE_NOT_CONTENT_INDEXED (stat 모듈)

FILE_ATTRIBUTE_OFFLINE (stat 모듈)

FILE_ATTRIBUTE_READONLY (stat 모듈)

FILE_ATTRIBUTE_REPARSE_POINT (stat 모듈)

FILE_ATTRIBUTE_SPARSE_FILE (stat 모듈)

FILE_ATTRIBUTE_SYSTEM (stat 모듈)

FILE_ATTRIBUTE_TEMPORARY (stat 모듈)

FILE_ATTRIBUTE_VIRTUAL (stat 모듈)

file_created() (내장 함수)

file_dispatcher (asyncore 클래스)

file_open() (urllib.request.FileHandler 메서드)

file_size (zipfile.ZipInfo의 속성)

file_wrapper (asyncore 클래스)

filecmp (모듈)

fileConfig() (logging.config 모듈)

FileCookieJar (http.cookiejar 클래스)

FileEntry (tkinter.tix 클래스)

FileExistsError

FileFinder (importlib.machinery 클래스)

FileHandler (logging 클래스)

(urllib.request 클래스)

FileInput (fileinput 클래스)

fileinput (모듈)

FileIO (io 클래스)

filelineno() (fileinput 모듈)

FileLoader (importlib.abc 클래스)

filemode() (stat 모듈)

filename (doctest.DocTest의 속성)

(http.cookiejar.FileCookieJar의 속성)

(OSError의 속성)

(traceback.TracebackException의 속성)

(tracemalloc.Frame의 속성)

(zipfile.ZipFile의 속성)

(zipfile.ZipInfo의 속성)

filename() (fileinput 모듈)

filename2 (OSError의 속성)

filename_only (tabnanny 모듈)

filename_pattern (tracemalloc.Filter의 속성)

filenames

pathname expansion

wildcard expansion

fileno() (fileinput 모듈)

(http.client.HTTPResponse 메서드)

(io.IOBase 메서드)

(multiprocessing.connection.Connection 메서드)

(ossaudiodev.oss_audio_device 메서드)

(ossaudiodev.oss_mixer_device 메서드)

(select.devpoll 메서드)

(select.epoll 메서드)

(select.kqueue 메서드)

(selectors.DevpollSelector 메서드)

(selectors.EpollSelector 메서드)

(selectors.KqueueSelector 메서드)

(socket.socket 메서드)

(socketserver.BaseServer 메서드)

(telnetlib.Telnet 메서드)

FileNotFoundError

fileobj (selectors.SelectorKey의 속성)

FileSelectBox (tkinter.tix 클래스)

FileType (argparse 클래스)

FileWrapper (wsgiref.util 클래스)

fill() (textwrap 모듈)

(textwrap.TextWrapper 메서드)

fillcolor() (turtle 모듈)

filling() (turtle 모듈)

filter (2to3 fixer)

Filter (logging 클래스)

filter (select.kevent의 속성)

Filter (tracemalloc 클래스)

filter() (curses 모듈)

(fnmatch 모듈)

(logging.Filter 메서드)

(logging.Handler 메서드)

(logging.Logger 메서드)

(내장 함수)

FILTER_DIR (unittest.mock 모듈)

filter_traces() (tracemalloc.Snapshot 메서드)

filterfalse() (itertools 모듈)

filterwarnings() (warnings 모듈)

finalization, of objects

finalize (weakref 클래스)

finalize_options() (distutils.cmd.Command 메서드)

finalizer

finally

키워드, [1], [2], [3], [4]

find() (bytearray 메서드)

(bytes 메서드)

(doctest.DocTestFinder 메서드)

(gettext 모듈)

(mmap.mmap 메서드)

(str 메서드)

(xml.etree.ElementTree.Element 메서드)

(xml.etree.ElementTree.ElementTree 메서드)

find_class() (pickle protocol)

(pickle.Unpickler 메서드)

find_library() (ctypes.util 모듈)

find_library_file() (distutils.ccompiler.CCompiler 메서드)

find_loader() (importlib 모듈)

(importlib.abc.PathEntryFinder 메서드)

(importlib.machinery.FileFinder 메서드)

(pkgutil 모듈)

find_longest_match() (difflib.SequenceMatcher 메서드)

find_module() (imp 모듈)

(imp.NullImporter 메서드)

(importlib.abc.Finder의 메서드)

(importlib.abc.MetaPathFinder 메서드)

(importlib.abc.PathEntryFinder 메서드)

(importlib.machinery.PathFinder의 클래스 메서드)

(zipimport.zipimporter 메서드)

find_msvcrt() (ctypes.util 모듈)

find_spec

finder

find_spec() (importlib.abc.MetaPathFinder 메서드)

(importlib.abc.PathEntryFinder 메서드)

(importlib.machinery.FileFinder 메서드)

(importlib.machinery.PathFinder의 클래스 메서드)

(importlib.util 모듈)

find_unused_port() (test.support 모듈)

find_user_password() (urllib.request.HTTPPasswordMgr 메서드), [1]

findall() (re 모듈)

(re.Pattern 메서드)

(xml.etree.ElementTree.Element 메서드)

(xml.etree.ElementTree.ElementTree 메서드)

findCaller() (logging.Logger 메서드)

finder

find_spec

Finder (importlib.abc 클래스)

finder (파인더)

findfactor() (audioop 모듈)

findfile() (test.support 모듈)

findfit() (audioop 모듈)

finditer() (re 모듈)

(re.Pattern 메서드)

findlabels() (dis 모듈)

findlinestarts() (dis 모듈)

findmatch() (mailcap 모듈)

findmax() (audioop 모듈)

findtext() (xml.etree.ElementTree.Element 메서드)

(xml.etree.ElementTree.ElementTree 메서드)

finish() (socketserver.BaseRequestHandler 메서드)

finish_request() (socketserver.BaseServer 메서드)

firstChild (xml.dom.Node의 속성)

firstkey() (dbm.gnu.gdbm 메서드)

firstweekday() (calendar 모듈)

fix_missing_locations() (ast 모듈)

fix_sentence_endings (textwrap.TextWrapper의 속성)

Flag (enum 클래스)

flag_bits (zipfile.ZipInfo의 속성)

flags (re.Pattern의 속성)

(select.kevent의 속성)

(sys 모듈)

flash() (curses 모듈)

flatten() (email.generator.BytesGenerator 메서드)

(email.generator.Generator 메서드)

flattening

objects

float

내장 함수, [1], [2]

float (내장 클래스)

float_info (sys 모듈)

float_repr_style (sys 모듈)

floating point

literals

number

객체, [1], [2]

floating point literal

FloatingPointError

FloatOperation (decimal 클래스)

flock() (fcntl 모듈)

floor division (정수 나눗셈)

floor() (in module math)

(math 모듈)

floordiv() (operator 모듈)

flush() (bz2.BZ2Compressor 메서드)

(formatter.writer 메서드)

(io.BufferedWriter 메서드)

(io.IOBase 메서드)

(logging.Handler 메서드)

(logging.handlers.BufferingHandler 메서드)

(logging.handlers.MemoryHandler 메서드)

(logging.StreamHandler 메서드)

(lzma.LZMACompressor 메서드)

(mailbox.Mailbox 메서드)

(mailbox.Maildir 메서드)

(mailbox.MH 메서드)

(mmap.mmap 메서드)

(zlib.Compress 메서드)

(zlib.Decompress 메서드)

flush_headers() (http.server.BaseHTTPRequestHandler 메서드)

flush_softspace() (formatter.formatter 메서드)

flushinp() (curses 모듈)

FlushKey() (winreg 모듈)

fma() (decimal.Context 메서드)

(decimal.Decimal 메서드)

fmod() (math 모듈)

FMT_BINARY (plistlib 모듈)

FMT_XML (plistlib 모듈)

fnmatch (모듈)

fnmatch() (fnmatch 모듈)

fnmatchcase() (fnmatch 모듈)

focus() (tkinter.ttk.Treeview 메서드)

fold (datetime.datetime의 속성)

(datetime.time의 속성)

fold() (email.headerregistry.BaseHeader 메서드)

(email.policy.Compat32 메서드)

(email.policy.EmailPolicy 메서드)

(email.policy.Policy 메서드)

fold_binary() (email.policy.Compat32 메서드)

(email.policy.EmailPolicy 메서드)

(email.policy.Policy 메서드)

for

in comprehensions

글, [1], [2], [3]

FOR_ITER (opcode)

forget() (test.support 모듈)

(tkinter.ttk.Notebook 메서드)

fork() (os 모듈)

(pty 모듈)

ForkingMixIn (socketserver 클래스)

ForkingTCPServer (socketserver 클래스)

ForkingUDPServer (socketserver 클래스)

forkpty() (os 모듈)

form

lambda

Form (tkinter.tix 클래스)

format (memoryview의 속성)

(struct.Struct의 속성)

format() (built-in function)

__str__() (object method)

format() (locale 모듈)

(logging.Formatter 메서드)

(logging.Handler 메서드)

(pprint.PrettyPrinter 메서드)

(str 메서드)

(string.Formatter 메서드)

(traceback.StackSummary 메서드)

(traceback.TracebackException 메서드)

(tracemalloc.Traceback 메서드)

(내장 함수)

format_datetime() (email.utils 모듈)

format_exc() (traceback 모듈)

format_exception() (traceback 모듈)

format_exception_only() (traceback 모듈)

(traceback.TracebackException 메서드)

format_field() (string.Formatter 메서드)

format_help() (argparse.ArgumentParser 메서드)

format_list() (traceback 모듈)

format_map() (str 메서드)

format_stack() (traceback 모듈)

format_stack_entry() (bdb.Bdb 메서드)

format_string() (locale 모듈)

format_tb() (traceback 모듈)

format_usage() (argparse.ArgumentParser 메서드)

FORMAT_VALUE (opcode)

formataddr() (email.utils 모듈)

formatargspec() (inspect 모듈)

formatargvalues() (inspect 모듈)

formatdate() (email.utils 모듈)

FormatError

FormatError() (ctypes 모듈)

formatException() (logging.Formatter 메서드)

formatmonth() (calendar.HTMLCalendar 메서드)

(calendar.TextCalendar 메서드)

formatStack() (logging.Formatter 메서드)

formatted string literal

Formatter (logging 클래스)

(string 클래스)

formatter (모듈)

formatTime() (logging.Formatter 메서드)

formatting

bytearray (%)

bytes (%)

formatting, string (%)

formatwarning() (warnings 모듈)

formatyear() (calendar.HTMLCalendar 메서드)

(calendar.TextCalendar 메서드)

formatyearpage() (calendar.HTMLCalendar 메서드)

Fortran contiguous, [1]

forward() (turtle 모듈)

ForwardRef (typing 클래스)

found_terminator() (asynchat.async_chat 메서드)

fpathconf() (os 모듈)

fqdn (smtpd.SMTPChannel의 속성)

Fraction (fractions 클래스)

fractions (모듈)

frame

execution, [1]

객체

frame (tkinter.scrolledtext.ScrolledText의 속성)

Frame (tracemalloc 클래스)

FrameSummary (traceback 클래스)

FrameType (types 모듈)

free

variable

free()

freeze utility

freeze() (gc 모듈)

freeze_support() (multiprocessing 모듈)

frexp() (math 모듈)

from

import statement, [1]

yield from expression

키워드, [1]

from_address() (ctypes._CData 메서드)

from_buffer() (ctypes._CData 메서드)

from_buffer_copy() (ctypes._CData 메서드)

from_bytes() (int의 클래스 메서드)

from_callable() (inspect.Signature의 클래스 메서드)

from_decimal() (fractions.Fraction 메서드)

from_exception() (traceback.TracebackException의 클래스 메서드)

from_file() (zipfile.ZipInfo의 클래스 메서드)

from_float() (decimal.Decimal 메서드)

(fractions.Fraction 메서드)

from_iterable() (itertools.chain의 클래스 메서드)

from_list() (traceback.StackSummary의 클래스 메서드)

from_param() (ctypes._CData 메서드)

from_traceback() (dis.Bytecode의 클래스 메서드)

frombuf() (tarfile.TarInfo의 클래스 메서드)

frombytes() (array.array 메서드)

fromfd() (select.epoll 메서드)

(select.kqueue 메서드)

(socket 모듈)

fromfile() (array.array 메서드)

fromhex() (bytearray의 클래스 메서드)

(bytes의 클래스 메서드)

(float의 클래스 메서드)

fromisoformat() (datetime.datetime의 클래스 메서드)

(datetime.date의 클래스 메서드)

(datetime.time의 클래스 메서드)

fromkeys() (collections.Counter 메서드)

(dict의 클래스 메서드)

fromlist() (array.array 메서드)

fromordinal() (datetime.datetime의 클래스 메서드)

(datetime.date의 클래스 메서드)

fromshare() (socket 모듈)

fromstring() (array.array 메서드)

(xml.etree.ElementTree 모듈)

fromstringlist() (xml.etree.ElementTree 모듈)

fromtarfile() (tarfile.TarInfo의 클래스 메서드)

fromtimestamp() (datetime.datetime의 클래스 메서드)

(datetime.date의 클래스 메서드)

fromunicode() (array.array 메서드)

fromutc() (datetime.timezone 메서드)

(datetime.tzinfo 메서드)

FrozenImporter (importlib.machinery 클래스)

FrozenInstanceError

frozenset

객체, [1]

FrozenSet (typing 클래스)

frozenset (내장 클래스)

fs_is_case_insensitive() (test.support 모듈)

FS_NONASCII (test.support 모듈)

fsdecode() (os 모듈)

fsencode() (os 모듈)

fspath() (os 모듈)

fstat() (os 모듈)

fstatvfs() (os 모듈)

fsum() (math 모듈)

fsync() (os 모듈)

FTP

ftplib (standard module)

protocol, [1]

FTP (ftplib 클래스)

ftp_open() (urllib.request.FTPHandler 메서드)

FTP_TLS (ftplib 클래스)

FTPHandler (urllib.request 클래스)

ftplib (모듈)

ftruncate() (os 모듈)

Full

full() (asyncio.Queue 메서드)

(multiprocessing.Queue 메서드)

(queue.Queue 메서드)

full_url (urllib.request.Request의 속성)

fullmatch() (re 모듈)

(re.Pattern 메서드)

func (functools.partial의 속성)

funcattrs (2to3 fixer)

function

annotations, [1]

anonymous

argument

call, [1], [2]

call, user-defined

definition, [1]

generator, [1]

name, [1]

user-defined

객체, [1], [2], [3], [4], [5]

Function (symtable 클래스)

function (함수)

function annotation (함수 어노테이션)

function__entry (C 함수)

function__return (C 함수)

FunctionTestCase (unittest 클래스)

FunctionType (types 모듈)

functools (모듈)

funny_files (filecmp.dircmp의 속성)

future

statement

future (2to3 fixer)

Future (asyncio 클래스)

(concurrent.futures 클래스)

FutureWarning

fwalk() (os 모듈)

G

G.722

gaierror

gamma() (math 모듈)

gammavariate() (random 모듈)

garbage (gc 모듈)

garbage collection

(가비지 수거)

gather() (curses.textpad.Textbox 메서드)

gauss() (random 모듈)

gc (모듈)

gc__done (C 함수)

gc__start (C 함수)

gc_collect() (test.support 모듈)

gcd() (fractions 모듈)

(math 모듈)

ge() (operator 모듈)

gen_lib_options() (distutils.ccompiler 모듈)

gen_preprocess_options() (distutils.ccompiler 모듈)

gen_uuid() (msilib 모듈)

generate_help() (distutils.fancy_getopt.FancyGetopt 메서드)

generator

expression

function, [1], [2]

iterator, [1]

객체, [1], [2]

Generator (collections.abc 클래스)

(email.generator 클래스)

(typing 클래스)

generator (제너레이터)

generator expression

(제너레이터 표현식)

generator iterator (제너레이터 이터레이터)

GeneratorExit

예외, [1]

GeneratorType (types 모듈)

generic

special attribute

Generic (typing 클래스)

generic function (제네릭 함수)

generic_visit() (ast.NodeVisitor 메서드)

genops() (pickletools 모듈)

get() (asyncio.Queue의 메서드)

(configparser.ConfigParser 메서드)

(contextvars.Context 메서드)

(contextvars.ContextVar 메서드)

(dict 메서드)

(email.message.EmailMessage 메서드)

(email.message.Message 메서드)

(mailbox.Mailbox 메서드)

(multiprocessing.pool.AsyncResult 메서드)

(multiprocessing.Queue 메서드)

(multiprocessing.SimpleQueue 메서드)

(ossaudiodev.oss_mixer_device 메서드)

(queue.Queue 메서드)

(queue.SimpleQueue 메서드)

(tkinter.ttk.Combobox 메서드)

(tkinter.ttk.Spinbox 메서드)

(types.MappingProxyType 메서드)

(webbrowser 모듈)

(xml.etree.ElementTree.Element 메서드)

GET_AITER (opcode)

get_all() (email.message.EmailMessage 메서드)

(email.message.Message 메서드)

(wsgiref.headers.Headers 메서드)

get_all_breaks() (bdb.Bdb 메서드)

get_all_start_methods() (multiprocessing 모듈)

GET_ANEXT (opcode)

get_app() (wsgiref.simple_server.WSGIServer 메서드)

get_archive_formats() (shutil 모듈)

get_asyncgen_hooks() (sys 모듈)

get_attribute() (test.support 모듈)

GET_AWAITABLE (opcode)

get_begidx() (readline 모듈)

get_blocking() (os 모듈)

get_body() (email.message.EmailMessage 메서드)

get_body_encoding() (email.charset.Charset 메서드)

get_boundary() (email.message.EmailMessage 메서드)

(email.message.Message 메서드)

get_bpbynumber() (bdb.Bdb 메서드)

get_break() (bdb.Bdb 메서드)

get_breaks() (bdb.Bdb 메서드)

get_buffer() (asyncio.BufferedProtocol 메서드)

(xdrlib.Packer 메서드)

(xdrlib.Unpacker 메서드)

get_bytes() (mailbox.Mailbox 메서드)

get_ca_certs() (ssl.SSLContext 메서드)

get_cache_token() (abc 모듈)

get_channel_binding() (ssl.SSLSocket 메서드)

get_charset() (email.message.Message 메서드)

get_charsets() (email.message.EmailMessage 메서드)

(email.message.Message 메서드)

get_child_watcher() (asyncio 모듈)

(asyncio.AbstractEventLoopPolicy 메서드)

get_children() (symtable.SymbolTable 메서드)

(tkinter.ttk.Treeview 메서드)

get_ciphers() (ssl.SSLContext 메서드)

get_clock_info() (time 모듈)

get_close_matches() (difflib 모듈)

get_code() (importlib.abc.InspectLoader 메서드)

(importlib.abc.SourceLoader 메서드)

(importlib.machinery.ExtensionFileLoader 메서드)

(importlib.machinery.SourcelessFileLoader 메서드)

(zipimport.zipimporter 메서드)

get_completer() (readline 모듈)

get_completer_delims() (readline 모듈)

get_completion_type() (readline 모듈)

get_config_h_filename() (distutils.sysconfig 모듈)

(sysconfig 모듈)

get_config_var() (distutils.sysconfig 모듈)

(sysconfig 모듈)

get_config_vars() (distutils.sysconfig 모듈)

(sysconfig 모듈)

get_content() (email.contentmanager 모듈)

(email.contentmanager.ContentManager 메서드)

(email.message.EmailMessage 메서드)

get_content_charset() (email.message.EmailMessage 메서드)

(email.message.Message 메서드)

get_content_disposition() (email.message.EmailMessage 메서드)

(email.message.Message 메서드)

get_content_maintype() (email.message.EmailMessage 메서드)

(email.message.Message 메서드)

get_content_subtype() (email.message.EmailMessage 메서드)

(email.message.Message 메서드)

get_content_type() (email.message.EmailMessage 메서드)

(email.message.Message 메서드)

get_context() (multiprocessing 모듈)

get_coroutine_origin_tracking_depth() (sys 모듈)

get_coroutine_wrapper() (sys 모듈)

get_count() (gc 모듈)

get_current_history_length() (readline 모듈)

get_data() (importlib.abc.FileLoader의 메서드)

(importlib.abc.ResourceLoader의 메서드)

(pkgutil 모듈)

(zipimport.zipimporter 메서드)

get_date() (mailbox.MaildirMessage 메서드)

get_debug() (asyncio.loop 메서드)

(gc 모듈)

get_default() (argparse.ArgumentParser 메서드)

get_default_compiler() (distutils.ccompiler 모듈)

get_default_domain() (nis 모듈)

get_default_type() (email.message.EmailMessage 메서드)

(email.message.Message 메서드)

get_default_verify_paths() (ssl 모듈)

get_dialect() (csv 모듈)

get_docstring() (ast 모듈)

get_doctest() (doctest.DocTestParser 메서드)

get_endidx() (readline 모듈)

get_environ() (wsgiref.simple_server.WSGIRequestHandler 메서드)

get_errno() (ctypes 모듈)

get_event_loop() (asyncio 모듈)

(asyncio.AbstractEventLoopPolicy 메서드)

get_event_loop_policy() (asyncio 모듈)

get_examples() (doctest.DocTestParser 메서드)

get_exception_handler() (asyncio.loop 메서드)

get_exec_path() (os 모듈)

get_extra_info() (asyncio.BaseTransport 메서드)

(asyncio.StreamWriter 메서드)

get_field() (string.Formatter 메서드)

get_file() (mailbox.Babyl 메서드)

(mailbox.Mailbox 메서드)

(mailbox.Maildir 메서드)

(mailbox.mbox 메서드)

(mailbox.MH 메서드)

(mailbox.MMDF 메서드)

get_file_breaks() (bdb.Bdb 메서드)

get_filename() (email.message.EmailMessage 메서드)

(email.message.Message 메서드)

(importlib.abc.ExecutionLoader의 메서드)

(importlib.abc.FileLoader의 메서드)

(importlib.machinery.ExtensionFileLoader 메서드)

(zipimport.zipimporter 메서드)

get_flags() (mailbox.MaildirMessage 메서드)

(mailbox.mboxMessage 메서드)

(mailbox.MMDFMessage 메서드)

get_folder() (mailbox.Maildir 메서드)

(mailbox.MH 메서드)

get_frees() (symtable.Function 메서드)

get_freeze_count() (gc 모듈)

get_from() (mailbox.mboxMessage 메서드)

(mailbox.MMDFMessage 메서드)

get_full_url() (urllib.request.Request 메서드)

get_globals() (symtable.Function 메서드)

get_grouped_opcodes() (difflib.SequenceMatcher 메서드)

get_handle_inheritable() (os 모듈)

get_header() (urllib.request.Request 메서드)

get_history_item() (readline 모듈)

get_history_length() (readline 모듈)

get_id() (symtable.SymbolTable 메서드)

get_ident() (_thread 모듈)

(threading 모듈)

get_identifiers() (symtable.SymbolTable 메서드)

get_importer() (pkgutil 모듈)

get_info() (mailbox.MaildirMessage 메서드)

get_inheritable() (os 모듈)

(socket.socket 메서드)

get_instructions() (dis 모듈)

get_int_max_str_digits() (sys 모듈)

get_interpreter() (zipapp 모듈)

GET_ITER (opcode)

get_key() (selectors.BaseSelector 메서드)

get_labels() (mailbox.Babyl 메서드)

(mailbox.BabylMessage 메서드)

get_last_error() (ctypes 모듈)

get_line_buffer() (readline 모듈)

get_lineno() (symtable.SymbolTable 메서드)

get_loader() (pkgutil 모듈)

get_locals() (symtable.Function 메서드)

get_logger() (multiprocessing 모듈)

get_loop() (asyncio.Future 메서드)

(asyncio.Server 메서드)

get_magic() (imp 모듈)

get_makefile_filename() (distutils.sysconfig 모듈)

(sysconfig 모듈)

get_map() (selectors.BaseSelector의 메서드)

get_matching_blocks() (difflib.SequenceMatcher 메서드)

get_message() (mailbox.Mailbox 메서드)

get_method() (urllib.request.Request 메서드)

get_methods() (symtable.Class 메서드)

get_mixed_type_key() (ipaddress 모듈)

get_name() (symtable.Symbol 메서드)

(symtable.SymbolTable 메서드)

get_namespace() (symtable.Symbol 메서드)

get_namespaces() (symtable.Symbol 메서드)

get_nonstandard_attr() (http.cookiejar.Cookie 메서드)

get_nowait() (asyncio.Queue 메서드)

(multiprocessing.Queue 메서드)

(queue.Queue 메서드)

(queue.SimpleQueue 메서드)

get_object_traceback() (tracemalloc 모듈)

get_objects() (gc 모듈)

get_opcodes() (difflib.SequenceMatcher 메서드)

get_option() (optparse.OptionParser 메서드)

get_option_group() (optparse.OptionParser 메서드)

get_option_order() (distutils.fancy_getopt.FancyGetopt 메서드)

get_original_stdout() (test.support 모듈)

get_osfhandle() (msvcrt 모듈)

get_output_charset() (email.charset.Charset 메서드)

get_param() (email.message.Message 메서드)

get_parameters() (symtable.Function 메서드)

get_params() (email.message.Message 메서드)

get_path() (sysconfig 모듈)

get_path_names() (sysconfig 모듈)

get_paths() (sysconfig 모듈)

get_payload() (email.message.Message 메서드)

get_pid() (asyncio.SubprocessTransport 메서드)

get_pipe_transport() (asyncio.SubprocessTransport 메서드)

get_platform() (distutils.util 모듈)

(sysconfig 모듈)

get_poly() (turtle 모듈)

get_position() (xdrlib.Unpacker 메서드)

get_protocol() (asyncio.BaseTransport 메서드)

get_python_inc() (distutils.sysconfig 모듈)

get_python_lib() (distutils.sysconfig 모듈)

get_python_version() (sysconfig 모듈)

get_recsrc() (ossaudiodev.oss_mixer_device 메서드)

get_referents() (gc 모듈)

get_referrers() (gc 모듈)

get_request() (socketserver.BaseServer 메서드)

get_returncode() (asyncio.SubprocessTransport 메서드)

get_running_loop() (asyncio 모듈)

get_scheme() (wsgiref.handlers.BaseHandler 메서드)

get_scheme_names() (sysconfig 모듈)

get_sequences() (mailbox.MH 메서드)

(mailbox.MHMessage 메서드)

get_server() (multiprocessing.managers.BaseManager 메서드)

get_server_certificate() (ssl 모듈)

get_shapepoly() (turtle 모듈)

get_socket() (telnetlib.Telnet 메서드)

get_source() (importlib.abc.InspectLoader의 메서드)

(importlib.abc.SourceLoader 메서드)

(importlib.machinery.ExtensionFileLoader 메서드)

(importlib.machinery.SourcelessFileLoader 메서드)

(zipimport.zipimporter 메서드)

get_special_folder_path() (내장 함수)

get_stack() (asyncio.Task 메서드)

(bdb.Bdb 메서드)

get_start_method() (multiprocessing 모듈)

get_starttag_text() (html.parser.HTMLParser 메서드)

get_stats() (gc 모듈)

get_stderr() (wsgiref.handlers.BaseHandler 메서드)

(wsgiref.simple_server.WSGIRequestHandler 메서드)

get_stdin() (wsgiref.handlers.BaseHandler 메서드)

get_string() (mailbox.Mailbox 메서드)

get_subdir() (mailbox.MaildirMessage 메서드)

get_suffixes() (imp 모듈)

get_symbols() (symtable.SymbolTable 메서드)

get_tag() (imp 모듈)

get_task_factory() (asyncio.loop 메서드)

get_terminal_size() (os 모듈)

(shutil 모듈)

get_terminator() (asynchat.async_chat 메서드)

get_threshold() (gc 모듈)

get_token() (shlex.shlex 메서드)

get_traceback_limit() (tracemalloc 모듈)

get_traced_memory() (tracemalloc 모듈)

get_tracemalloc_memory() (tracemalloc 모듈)

get_type() (symtable.SymbolTable 메서드)

get_type_hints() (typing 모듈)

get_unixfrom() (email.message.EmailMessage 메서드)

(email.message.Message 메서드)

get_unpack_formats() (shutil 모듈)

get_usage() (optparse.OptionParser 메서드)

get_value() (string.Formatter 메서드)

get_version() (optparse.OptionParser 메서드)

get_visible() (mailbox.BabylMessage 메서드)

get_wch() (curses.window 메서드)

get_write_buffer_limits() (asyncio.WriteTransport 메서드)

get_write_buffer_size() (asyncio.WriteTransport 메서드)

GET_YIELD_FROM_ITER (opcode)

getacl() (imaplib.IMAP4 메서드)

getaddresses() (email.utils 모듈)

getaddrinfo() (asyncio.loop의 메서드)

(socket 모듈)

getallocatedblocks() (sys 모듈)

getandroidapilevel() (sys 모듈)

getannotation() (imaplib.IMAP4 메서드)

getargspec() (inspect 모듈)

getargvalues() (inspect 모듈)

getatime() (os.path 모듈)

getattr() (내장 함수)

getattr_static() (inspect 모듈)

getAttribute() (xml.dom.Element 메서드)

getAttributeNode() (xml.dom.Element 메서드)

getAttributeNodeNS() (xml.dom.Element 메서드)

getAttributeNS() (xml.dom.Element 메서드)

GetBase() (xml.parsers.expat.xmlparser 메서드)

getbegyx() (curses.window 메서드)

getbkgd() (curses.window 메서드)

getblocking() (socket.socket 메서드)

getboolean() (configparser.ConfigParser 메서드)

getbuffer() (io.BytesIO 메서드)

getByteStream() (xml.sax.xmlreader.InputSource 메서드)

getcallargs() (inspect 모듈)

getcanvas() (turtle 모듈)

getcapabilities() (nntplib.NNTP 메서드)

getcaps() (mailcap 모듈)

getch() (curses.window 메서드)

(msvcrt 모듈)

getCharacterStream() (xml.sax.xmlreader.InputSource 메서드)

getche() (msvcrt 모듈)

getcheckinterval() (sys 모듈)

getChild() (logging.Logger 메서드)

getchildren() (xml.etree.ElementTree.Element 메서드)

getclasstree() (inspect 모듈)

getclosurevars() (inspect 모듈)

GetColumnInfo() (msilib.View 메서드)

getColumnNumber() (xml.sax.xmlreader.Locator 메서드)

getcomments() (inspect 모듈)

getcompname() (aifc.aifc 메서드)

(sunau.AU_read 메서드)

(wave.Wave_read 메서드)

getcomptype() (aifc.aifc 메서드)

(sunau.AU_read 메서드)

(wave.Wave_read 메서드)

getContentHandler() (xml.sax.xmlreader.XMLReader 메서드)

getcontext() (decimal 모듈)

getcoroutinelocals() (inspect 모듈)

getcoroutinestate() (inspect 모듈)

getctime() (os.path 모듈)

getcwd() (os 모듈)

getcwdb() (os 모듈)

getcwdu (2to3 fixer)

getdecoder() (codecs 모듈)

getdefaultencoding() (sys 모듈)

getdefaultlocale() (locale 모듈)

getdefaulttimeout() (socket 모듈)

getdlopenflags() (sys 모듈)

getdoc() (inspect 모듈)

getDOMImplementation() (xml.dom 모듈)

getDTDHandler() (xml.sax.xmlreader.XMLReader 메서드)

getEffectiveLevel() (logging.Logger 메서드)

getegid() (os 모듈)

getElementsByTagName() (xml.dom.Document 메서드)

(xml.dom.Element 메서드)

getElementsByTagNameNS() (xml.dom.Document 메서드)

(xml.dom.Element 메서드)

getencoder() (codecs 모듈)

getEncoding() (xml.sax.xmlreader.InputSource 메서드)

getEntityResolver() (xml.sax.xmlreader.XMLReader 메서드)

getenv() (os 모듈)

getenvb() (os 모듈)

getErrorHandler() (xml.sax.xmlreader.XMLReader 메서드)

geteuid() (os 모듈)

getEvent() (xml.dom.pulldom.DOMEventStream 메서드)

getEventCategory() (logging.handlers.NTEventLogHandler 메서드)

getEventType() (logging.handlers.NTEventLogHandler 메서드)

getException() (xml.sax.SAXException 메서드)

getFeature() (xml.sax.xmlreader.XMLReader 메서드)

GetFieldCount() (msilib.Record 메서드)

getfile() (inspect 모듈)

getfilesystemencodeerrors() (sys 모듈)

getfilesystemencoding() (sys 모듈)

getfirst() (cgi.FieldStorage 메서드)

getfloat() (configparser.ConfigParser 메서드)

getfmts() (ossaudiodev.oss_audio_device 메서드)

getfqdn() (socket 모듈)

getframeinfo() (inspect 모듈)

getframerate() (aifc.aifc 메서드)

(sunau.AU_read 메서드)

(wave.Wave_read 메서드)

getfullargspec() (inspect 모듈)

getgeneratorlocals() (inspect 모듈)

getgeneratorstate() (inspect 모듈)

getgid() (os 모듈)

getgrall() (grp 모듈)

getgrgid() (grp 모듈)

getgrnam() (grp 모듈)

getgrouplist() (os 모듈)

getgroups() (os 모듈)

getheader() (http.client.HTTPResponse 메서드)

getheaders() (http.client.HTTPResponse 메서드)

gethostbyaddr() (in module socket)

(socket 모듈)

gethostbyname() (socket 모듈)

gethostbyname_ex() (socket 모듈)

gethostname() (in module socket)

(socket 모듈)

getincrementaldecoder() (codecs 모듈)

getincrementalencoder() (codecs 모듈)

getinfo() (zipfile.ZipFile 메서드)

getinnerframes() (inspect 모듈)

GetInputContext() (xml.parsers.expat.xmlparser 메서드)

getint() (configparser.ConfigParser 메서드)

GetInteger() (msilib.Record 메서드)

getitem() (operator 모듈)

getiterator() (xml.etree.ElementTree.Element 메서드)

(xml.etree.ElementTree.ElementTree 메서드)

getitimer() (signal 모듈)

getkey() (curses.window 메서드)

GetLastError() (ctypes 모듈)

getLength() (xml.sax.xmlreader.Attributes 메서드)

getLevelName() (logging 모듈)

getline() (linecache 모듈)

getLineNumber() (xml.sax.xmlreader.Locator 메서드)

getlist() (cgi.FieldStorage 메서드)

getloadavg() (os 모듈)

getlocale() (locale 모듈)

getLogger() (logging 모듈)

getLoggerClass() (logging 모듈)

getlogin() (os 모듈)

getLogRecordFactory() (logging 모듈)

getmark() (aifc.aifc 메서드)

(sunau.AU_read 메서드)

(wave.Wave_read 메서드)

getmarkers() (aifc.aifc 메서드)

(sunau.AU_read 메서드)

(wave.Wave_read 메서드)

getmaxyx() (curses.window 메서드)

getmember() (tarfile.TarFile 메서드)

getmembers() (inspect 모듈)

(tarfile.TarFile 메서드)

getMessage() (logging.LogRecord 메서드)

(xml.sax.SAXException 메서드)

getMessageID() (logging.handlers.NTEventLogHandler 메서드)

getmodule() (inspect 모듈)

getmodulename() (inspect 모듈)

getmouse() (curses 모듈)

getmro() (inspect 모듈)

getmtime() (os.path 모듈)

getname() (chunk.Chunk 메서드)

getName() (threading.Thread 메서드)

getNameByQName() (xml.sax.xmlreader.AttributesNS 메서드)

getnameinfo() (asyncio.loop의 메서드)

(socket 모듈)

getnames() (tarfile.TarFile 메서드)

getNames() (xml.sax.xmlreader.Attributes 메서드)

getnchannels() (aifc.aifc 메서드)

(sunau.AU_read 메서드)

(wave.Wave_read 메서드)

getnframes() (aifc.aifc 메서드)

(sunau.AU_read 메서드)

(wave.Wave_read 메서드)

getnode

getnode() (uuid 모듈)

getopt (모듈)

getopt() (distutils.fancy_getopt.FancyGetopt 메서드)

(getopt 모듈)

GetoptError

getouterframes() (inspect 모듈)

getoutput() (subprocess 모듈)

getpagesize() (resource 모듈)

getparams() (aifc.aifc 메서드)

(sunau.AU_read 메서드)

(wave.Wave_read 메서드)

getparyx() (curses.window 메서드)

getpass (모듈)

getpass() (getpass 모듈)

GetPassWarning

getpeercert() (ssl.SSLSocket 메서드)

getpeername() (socket.socket 메서드)

getpen() (turtle 모듈)

getpgid() (os 모듈)

getpgrp() (os 모듈)

getpid() (os 모듈)

getpos() (html.parser.HTMLParser 메서드)

getppid() (os 모듈)

getpreferredencoding() (locale 모듈)

getpriority() (os 모듈)

getprofile() (sys 모듈)

GetProperty() (msilib.SummaryInformation 메서드)

getProperty() (xml.sax.xmlreader.XMLReader 메서드)

GetPropertyCount() (msilib.SummaryInformation 메서드)

getprotobyname() (socket 모듈)

getproxies() (urllib.request 모듈)

getPublicId() (xml.sax.xmlreader.InputSource 메서드)

(xml.sax.xmlreader.Locator 메서드)

getpwall() (pwd 모듈)

getpwnam() (pwd 모듈)

getpwuid() (pwd 모듈)

getQNameByName() (xml.sax.xmlreader.AttributesNS 메서드)

getQNames() (xml.sax.xmlreader.AttributesNS 메서드)

getquota() (imaplib.IMAP4 메서드)

getquotaroot() (imaplib.IMAP4 메서드)

getrandbits() (random 모듈)

getrandom() (os 모듈)

getreader() (codecs 모듈)

getrecursionlimit() (sys 모듈)

getrefcount() (sys 모듈)

getresgid() (os 모듈)

getresponse() (http.client.HTTPConnection 메서드)

getresuid() (os 모듈)

getrlimit() (resource 모듈)

getroot() (xml.etree.ElementTree.ElementTree 메서드)

getrusage() (resource 모듈)

getsample() (audioop 모듈)

getsampwidth() (aifc.aifc 메서드)

(sunau.AU_read 메서드)

(wave.Wave_read 메서드)

getscreen() (turtle 모듈)

getservbyname() (socket 모듈)

getservbyport() (socket 모듈)

GetSetDescriptorType (types 모듈)

getshapes() (turtle 모듈)

getsid() (os 모듈)

getsignal() (signal 모듈)

getsitepackages() (site 모듈)

getsize() (chunk.Chunk 메서드)

(os.path 모듈)

getsizeof() (sys 모듈)

getsockname() (socket.socket 메서드)

getsockopt() (socket.socket 메서드)

getsource() (inspect 모듈)

getsourcefile() (inspect 모듈)

getsourcelines() (inspect 모듈)

getspall() (spwd 모듈)

getspnam() (spwd 모듈)

getstate() (codecs.IncrementalDecoder 메서드)

(codecs.IncrementalEncoder 메서드)

(random 모듈)

getstatusoutput() (subprocess 모듈)

getstr() (curses.window 메서드)

GetString() (msilib.Record 메서드)

getSubject() (logging.handlers.SMTPHandler 메서드)

GetSummaryInformation() (msilib.Database 메서드)

getswitchinterval() (sys 모듈)

getSystemId() (xml.sax.xmlreader.InputSource 메서드)

(xml.sax.xmlreader.Locator 메서드)

getsyx() (curses 모듈)

gettarinfo() (tarfile.TarFile 메서드)

gettempdir() (tempfile 모듈)

gettempdirb() (tempfile 모듈)

gettempprefix() (tempfile 모듈)

gettempprefixb() (tempfile 모듈)

getTestCaseNames() (unittest.TestLoader 메서드)

gettext (모듈)

gettext() (gettext 모듈)

(gettext.GNUTranslations 메서드)

(gettext.NullTranslations 메서드)

(locale 모듈)

gettimeout() (socket.socket 메서드)

gettrace() (sys 모듈)

getturtle() (turtle 모듈)

getType() (xml.sax.xmlreader.Attributes 메서드)

getuid() (os 모듈)

geturl() (urllib.parse.urllib.parse.SplitResult 메서드)

getuser() (getpass 모듈)

getuserbase() (site 모듈)

getusersitepackages() (site 모듈)

getvalue() (io.BytesIO 메서드)

(io.StringIO 메서드)

getValue() (xml.sax.xmlreader.Attributes 메서드)

getValueByQName() (xml.sax.xmlreader.AttributesNS 메서드)

getwch() (msvcrt 모듈)

getwche() (msvcrt 모듈)

getweakrefcount() (weakref 모듈)

getweakrefs() (weakref 모듈)

getwelcome() (ftplib.FTP 메서드)

(nntplib.NNTP 메서드)

(poplib.POP3 메서드)

getwin() (curses 모듈)

getwindowsversion() (sys 모듈)

getwriter() (codecs 모듈)

getxattr() (os 모듈)

getyx() (curses.window 메서드)

gid (tarfile.TarInfo의 속성)

GIL

glob

모듈

glob (모듈)

glob() (glob 모듈)

(msilib.Directory 메서드)

(pathlib.Path 메서드)

global

name binding

namespace

글, [1]

global interpreter lock

(전역 인터프리터 록)

globals() (내장 함수)

globs (doctest.DocTest의 속성)

gmtime() (time 모듈)

gname (tarfile.TarInfo의 속성)

GNOME

GNU_FORMAT (tarfile 모듈)

gnu_getopt() (getopt 모듈)

GNUTranslations (gettext 클래스)

got (doctest.DocTestFailure의 속성)

goto() (turtle 모듈)

grammar

Graphical User Interface

GREATER (token 모듈)

GREATEREQUAL (token 모듈)

Greenwich Mean Time

GRND_NONBLOCK (os 모듈)

GRND_RANDOM (os 모듈)

Group (email.headerregistry 클래스)

group() (nntplib.NNTP 메서드)

(pathlib.Path 메서드)

(re.Match 메서드)

groupby() (itertools 모듈)

groupdict() (re.Match 메서드)

groupindex (re.Pattern의 속성)

grouping

groups (email.headerregistry.AddressHeader의 속성)

(re.Pattern의 속성)

groups() (re.Match 메서드)

grp (모듈)

gt() (operator 모듈)

guess_all_extensions() (mimetypes 모듈)

(mimetypes.MimeTypes 메서드)

guess_extension() (mimetypes 모듈)

(mimetypes.MimeTypes 메서드)

guess_scheme() (wsgiref.util 모듈)

guess_type() (mimetypes 모듈)

(mimetypes.MimeTypes 메서드)

GUI

gzip (모듈)

GzipFile (gzip 클래스)

H

halfdelay() (curses 모듈)

Handle (asyncio 클래스)

handle an exception

handle() (http.server.BaseHTTPRequestHandler 메서드)

(logging.Handler 메서드)

(logging.handlers.QueueListener 메서드)

(logging.Logger 메서드)

(logging.NullHandler 메서드)

(socketserver.BaseRequestHandler 메서드)

(wsgiref.simple_server.WSGIRequestHandler 메서드)

handle_accept() (asyncore.dispatcher 메서드)

handle_accepted() (asyncore.dispatcher 메서드)

handle_charref() (html.parser.HTMLParser 메서드)

handle_close() (asyncore.dispatcher 메서드)

handle_comment() (html.parser.HTMLParser 메서드)

handle_connect() (asyncore.dispatcher 메서드)

handle_data() (html.parser.HTMLParser 메서드)

handle_decl() (html.parser.HTMLParser 메서드)

handle_defect() (email.policy.Policy 메서드)

handle_endtag() (html.parser.HTMLParser 메서드)

handle_entityref() (html.parser.HTMLParser 메서드)

handle_error() (asyncore.dispatcher 메서드)

(socketserver.BaseServer 메서드)

handle_expect_100() (http.server.BaseHTTPRequestHandler 메서드)

handle_expt() (asyncore.dispatcher 메서드)

handle_one_request() (http.server.BaseHTTPRequestHandler 메서드)

handle_pi() (html.parser.HTMLParser 메서드)

handle_read() (asyncore.dispatcher 메서드)

handle_request() (socketserver.BaseServer 메서드)

(xmlrpc.server.CGIXMLRPCRequestHandler 메서드)

handle_startendtag() (html.parser.HTMLParser 메서드)

handle_starttag() (html.parser.HTMLParser 메서드)

handle_timeout() (socketserver.BaseServer 메서드)

handle_write() (asyncore.dispatcher 메서드)

handleError() (logging.Handler 메서드)

(logging.handlers.SocketHandler 메서드)

handler

exception

Handler (logging 클래스)

handler() (cgitb 모듈)

harmonic_mean() (statistics 모듈)

HAS_ALPN (ssl 모듈)

has_children() (symtable.SymbolTable 메서드)

has_colors() (curses 모듈)

HAS_ECDH (ssl 모듈)

has_exec() (symtable.SymbolTable 메서드)

has_extn() (smtplib.SMTP 메서드)

has_function() (distutils.ccompiler.CCompiler 메서드)

has_header() (csv.Sniffer 메서드)

(urllib.request.Request 메서드)

has_ic() (curses 모듈)

has_il() (curses 모듈)

has_ipv6 (socket 모듈)

has_key (2to3 fixer)

has_key() (curses 모듈)

has_location (importlib.machinery.ModuleSpec의 속성)

HAS_NEVER_CHECK_COMMON_NAME (ssl 모듈)

has_nonstandard_attr() (http.cookiejar.Cookie 메서드)

HAS_NPN (ssl 모듈)

has_option() (configparser.ConfigParser 메서드)

(optparse.OptionParser 메서드)

has_section() (configparser.ConfigParser 메서드)

HAS_SNI (ssl 모듈)

HAS_SSLv2 (ssl 모듈)

HAS_SSLv3 (ssl 모듈)

has_ticket (ssl.SSLSession의 속성)

HAS_TLSv1 (ssl 모듈)

HAS_TLSv1_1 (ssl 모듈)

HAS_TLSv1_2 (ssl 모듈)

HAS_TLSv1_3 (ssl 모듈)

hasattr() (내장 함수)

hasAttribute() (xml.dom.Element 메서드)

hasAttributeNS() (xml.dom.Element 메서드)

hasAttributes() (xml.dom.Node 메서드)

hasChildNodes() (xml.dom.Node 메서드)

hascompare (dis 모듈)

hasconst (dis 모듈)

hasFeature() (xml.dom.DOMImplementation 메서드)

hasfree (dis 모듈)

hash

내장 함수, [1], [2], [3]

hash character

hash() (내장 함수)

hash-based pyc (해시 기반 pyc)

hash.block_size (hashlib 모듈)

hash.digest_size (hashlib 모듈)

hash_info (sys 모듈)

hashable

Hashable (collections.abc 클래스)

(typing 클래스)

hashable (해시 가능)

hasHandlers() (logging.Logger 메서드)

hashlib (모듈)

hasjabs (dis 모듈)

hasjrel (dis 모듈)

haslocal (dis 모듈)

hasname (dis 모듈)

HAVE_ARGUMENT (opcode)

HAVE_CONTEXTVAR (decimal 모듈)

HAVE_DOCSTRINGS (test.support 모듈)

HAVE_THREADS (decimal 모듈)

HCI_DATA_DIR (socket 모듈)

HCI_FILTER (socket 모듈)

HCI_TIME_STAMP (socket 모듈)

head() (nntplib.NNTP 메서드)

Header (email.header 클래스)

header_encode() (email.charset.Charset 메서드)

header_encode_lines() (email.charset.Charset 메서드)

header_encoding (email.charset.Charset의 속성)

header_factory (email.policy.EmailPolicy의 속성)

header_fetch_parse() (email.policy.Compat32 메서드)

(email.policy.EmailPolicy 메서드)

(email.policy.Policy 메서드)

header_items() (urllib.request.Request 메서드)

header_max_count() (email.policy.EmailPolicy 메서드)

(email.policy.Policy 메서드)

header_offset (zipfile.ZipInfo의 속성)

header_source_parse() (email.policy.Compat32 메서드)

(email.policy.EmailPolicy 메서드)

(email.policy.Policy 메서드)

header_store_parse() (email.policy.Compat32 메서드)

(email.policy.EmailPolicy 메서드)

(email.policy.Policy 메서드)

HeaderError

HeaderParseError

HeaderParser (email.parser 클래스)

HeaderRegistry (email.headerregistry 클래스)

headers

MIME, [1]

headers (http.server.BaseHTTPRequestHandler의 속성)

(urllib.error.HTTPError의 속성)

Headers (wsgiref.headers 클래스)

headers (xmlrpc.client.ProtocolError의 속성)

heading() (tkinter.ttk.Treeview 메서드)

(turtle 모듈)

heapify() (heapq 모듈)

heapmin() (msvcrt 모듈)

heappop() (heapq 모듈)

heappush() (heapq 모듈)

heappushpop() (heapq 모듈)

heapq (모듈)

heapreplace() (heapq 모듈)

helo() (smtplib.SMTP 메서드)

help

online

내장 함수

help (optparse.Option의 속성)

(pdb command)

help() (nntplib.NNTP 메서드)

(내장 함수)

herror

hex (uuid.UUID의 속성)

hex() (bytearray 메서드)

(bytes 메서드)

(float 메서드)

(memoryview 메서드)

(내장 함수)

hexadecimal

literals

hexadecimal literal

hexbin() (binhex 모듈)

hexdigest() (hashlib.hash 메서드)

(hashlib.shake 메서드)

(hmac.HMAC 메서드)

hexdigits (string 모듈)

hexlify() (binascii 모듈)

hexversion (sys 모듈)

hidden() (curses.panel.Panel 메서드)

hide() (curses.panel.Panel 메서드)

(tkinter.ttk.Notebook 메서드)

hide_cookie2 (http.cookiejar.CookiePolicy의 속성)

hideturtle() (turtle 모듈)

hierarchy

type

HierarchyRequestErr

HIGH_PRIORITY_CLASS (subprocess 모듈)

HIGHEST_PROTOCOL (pickle 모듈)

HKEY_CLASSES_ROOT (winreg 모듈)

HKEY_CURRENT_CONFIG (winreg 모듈)

HKEY_CURRENT_USER (winreg 모듈)

HKEY_DYN_DATA (winreg 모듈)

HKEY_LOCAL_MACHINE (winreg 모듈)

HKEY_PERFORMANCE_DATA (winreg 모듈)

HKEY_USERS (winreg 모듈)

hline() (curses.window 메서드)

HList (tkinter.tix 클래스)

hls_to_rgb() (colorsys 모듈)

hmac (모듈)

HOME, [1], [2], [3], [4]

home() (pathlib.Path의 클래스 메서드)

(turtle 모듈)

HOMEDRIVE, [1]

HOMEPATH, [1]

hook_compressed() (fileinput 모듈)

hook_encoded() (fileinput 모듈)

hooks

import

meta

path

host (urllib.request.Request의 속성)

hostmask (ipaddress.IPv4Network의 속성)

(ipaddress.IPv6Network의 속성)

hostname_checks_common_name (ssl.SSLContext의 속성)

hosts (netrc.netrc의 속성)

hosts() (ipaddress.IPv4Network 메서드)

(ipaddress.IPv6Network 메서드)

hour (datetime.datetime의 속성)

(datetime.time의 속성)

HRESULT (ctypes 클래스)

hStdError (subprocess.STARTUPINFO의 속성)

hStdInput (subprocess.STARTUPINFO의 속성)

hStdOutput (subprocess.STARTUPINFO의 속성)

hsv_to_rgb() (colorsys 모듈)

ht() (turtle 모듈)

HTML, [1]

html (모듈)

html() (cgitb 모듈)

html.entities (모듈)

html.parser (모듈)

html5 (html.entities 모듈)

HTMLCalendar (calendar 클래스)

HtmlDiff (difflib 클래스)

HTMLParser (html.parser 클래스)

htonl() (socket 모듈)

htons() (socket 모듈)

HTTP

http (standard module)

http.client (standard module)

protocol, [1], [2], [3], [4], [5]

HTTP (email.policy 모듈)

http (모듈)

http.client (모듈)

http.cookiejar (모듈)

http.cookies (모듈)

http.server

security

http.server (모듈)

http_error_301() (urllib.request.HTTPRedirectHandler 메서드)

http_error_302() (urllib.request.HTTPRedirectHandler 메서드)

http_error_303() (urllib.request.HTTPRedirectHandler 메서드)

http_error_307() (urllib.request.HTTPRedirectHandler 메서드)

http_error_401() (urllib.request.HTTPBasicAuthHandler 메서드)

(urllib.request.HTTPDigestAuthHandler 메서드)

http_error_407() (urllib.request.ProxyBasicAuthHandler 메서드)

(urllib.request.ProxyDigestAuthHandler 메서드)

http_error_auth_reqed() (urllib.request.AbstractBasicAuthHandler 메서드)

(urllib.request.AbstractDigestAuthHandler 메서드)

http_error_default() (urllib.request.BaseHandler 메서드)

http_open() (urllib.request.HTTPHandler 메서드)

HTTP_PORT (http.client 모듈)

http_proxy, [1], [2]

http_response() (urllib.request.HTTPErrorProcessor 메서드)

http_version (wsgiref.handlers.BaseHandler의 속성)

HTTPBasicAuthHandler (urllib.request 클래스)

HTTPConnection (http.client 클래스)

HTTPCookieProcessor (urllib.request 클래스)

httpd

HTTPDefaultErrorHandler (urllib.request 클래스)

HTTPDigestAuthHandler (urllib.request 클래스)

HTTPError

HTTPErrorProcessor (urllib.request 클래스)

HTTPException

HTTPHandler (logging.handlers 클래스)

(urllib.request 클래스)

HTTPPasswordMgr (urllib.request 클래스)

HTTPPasswordMgrWithDefaultRealm (urllib.request 클래스)

HTTPPasswordMgrWithPriorAuth (urllib.request 클래스)

HTTPRedirectHandler (urllib.request 클래스)

HTTPResponse (http.client 클래스)

https_open() (urllib.request.HTTPSHandler 메서드)

HTTPS_PORT (http.client 모듈)

https_response() (urllib.request.HTTPErrorProcessor 메서드)

HTTPSConnection (http.client 클래스)

HTTPServer (http.server 클래스)

HTTPSHandler (urllib.request 클래스)

HTTPStatus (http 클래스)

hypot() (math 모듈)

I

I (re 모듈)

I/O control

buffering, [1]

POSIX

tty

UNIX

iadd() (operator 모듈)

iand() (operator 모듈)

iconcat() (operator 모듈)

id

내장 함수

id (ssl.SSLSession의 속성)

id() (unittest.TestCase 메서드)

(내장 함수)

idcok() (curses.window 메서드)

ident (select.kevent의 속성)

(threading.Thread의 속성)

identchars (cmd.Cmd의 속성)

identifier, [1]

identify() (tkinter.ttk.Notebook 메서드)

(tkinter.ttk.Treeview 메서드)

(tkinter.ttk.Widget 메서드)

identify_column() (tkinter.ttk.Treeview 메서드)

identify_element() (tkinter.ttk.Treeview 메서드)

identify_region() (tkinter.ttk.Treeview 메서드)

identify_row() (tkinter.ttk.Treeview 메서드)

identity

test

identity of an object

idioms (2to3 fixer)

IDLE, [1]

IDLE_PRIORITY_CLASS (subprocess 모듈)

IDLESTARTUP, [1], [2]

idlok() (curses.window 메서드)

if

conditional expression

in comprehensions

글, [1]

if_indextoname() (socket 모듈)

if_nameindex() (socket 모듈)

if_nametoindex() (socket 모듈)

ifloordiv() (operator 모듈)

iglob() (glob 모듈)

ignorableWhitespace() (xml.sax.handler.ContentHandler 메서드)

ignore (pdb command)

ignore_errors() (codecs 모듈)

IGNORE_EXCEPTION_DETAIL (doctest 모듈)

ignore_patterns() (shutil 모듈)

IGNORECASE (re 모듈)

ihave() (nntplib.NNTP 메서드)

IISCGIHandler (wsgiref.handlers 클래스)

ilshift() (operator 모듈)

imag (numbers.Complex의 속성)

imaginary literal

imap() (multiprocessing.pool.Pool 메서드)

IMAP4

protocol

IMAP4 (imaplib 클래스)

IMAP4.abort

IMAP4.error

IMAP4.readonly

IMAP4_SSL

protocol

IMAP4_SSL (imaplib 클래스)

IMAP4_stream

protocol

IMAP4_stream (imaplib 클래스)

imap_unordered() (multiprocessing.pool.Pool 메서드)

imaplib (모듈)

imatmul() (operator 모듈)

imghdr (모듈)

immedok() (curses.window 메서드)

immutable

data type

object, [1]

sequence types

객체

immutable (불변)

immutable object

immutable sequence

객체

immutable types

subclassing

imod() (operator 모듈)

imp

모듈

imp (모듈)

ImpImporter (pkgutil 클래스)

impl_detail() (test.support 모듈)

implementation (sys 모듈)

ImpLoader (pkgutil 클래스)

import

hooks

글, [1], [2], [3], [4]

import (2to3 fixer)

import hooks

import machinery

import path (임포트 경로)

import__find__load__done (C 함수)

import__find__load__start (C 함수)

import_fresh_module() (test.support 모듈)

IMPORT_FROM (opcode)

import_module() (importlib 모듈)

(test.support 모듈)

IMPORT_NAME (opcode)

IMPORT_STAR (opcode)

importer (임포터)

ImportError

예외

importing (임포팅)

importlib (모듈)

importlib.abc (모듈)

importlib.machinery (모듈)

importlib.resources (모듈)

importlib.util (모듈)

imports (2to3 fixer)

imports2 (2to3 fixer)

ImportWarning

ImproperConnectionState

imul() (operator 모듈)

in

연산자, [1], [2]

키워드

in_dll() (ctypes._CData 메서드)

in_table_a1() (stringprep 모듈)

in_table_b1() (stringprep 모듈)

in_table_c11() (stringprep 모듈)

in_table_c11_c12() (stringprep 모듈)

in_table_c12() (stringprep 모듈)

in_table_c21() (stringprep 모듈)

in_table_c21_c22() (stringprep 모듈)

in_table_c22() (stringprep 모듈)

in_table_c3() (stringprep 모듈)

in_table_c4() (stringprep 모듈)

in_table_c5() (stringprep 모듈)

in_table_c6() (stringprep 모듈)

in_table_c7() (stringprep 모듈)

in_table_c8() (stringprep 모듈)

in_table_c9() (stringprep 모듈)

in_table_d1() (stringprep 모듈)

in_table_d2() (stringprep 모듈)

in_transaction (sqlite3.Connection의 속성)

inch() (curses.window 메서드)

inclusive

or

inclusive (tracemalloc.DomainFilter의 속성)

(tracemalloc.Filter의 속성)

Incomplete

IncompleteRead

IncompleteReadError

incr_item(), [1]

increment_lineno() (ast 모듈)

IncrementalDecoder (codecs 클래스)

incrementaldecoder (codecs.CodecInfo의 속성)

IncrementalEncoder (codecs 클래스)

incrementalencoder (codecs.CodecInfo의 속성)

IncrementalNewlineDecoder (io 클래스)

IncrementalParser (xml.sax.xmlreader 클래스)

indent (doctest.Example의 속성)

INDENT (token 모듈)

INDENT token

indent() (textwrap 모듈)

indentation

IndentationError

index operation

index() (array.array 메서드)

(bytearray 메서드)

(bytes 메서드)

(collections.deque 메서드)

(operator 모듈)

(sequence method)

(str 메서드)

(tkinter.ttk.Notebook 메서드)

(tkinter.ttk.Treeview 메서드)

IndexError

indexOf() (operator 모듈)

IndexSizeErr

indices() (slice 메서드)

inet_aton() (socket 모듈)

inet_ntoa() (socket 모듈)

inet_ntop() (socket 모듈)

inet_pton() (socket 모듈)

Inexact (decimal 클래스)

inf (cmath 모듈)

(math 모듈)

infile

json.tool command line option

infile (shlex.shlex의 속성)

Infinity

infj (cmath 모듈)

info() (dis.Bytecode 메서드)

(gettext.NullTranslations 메서드)

(logging 모듈)

(logging.Logger 메서드)

infolist() (zipfile.ZipFile 메서드)

inheritance

ini file

init() (mimetypes 모듈)

init_color() (curses 모듈)

init_database() (msilib 모듈)

init_pair() (curses 모듈)

inited (mimetypes 모듈)

initgroups() (os 모듈)

initial_indent (textwrap.TextWrapper의 속성)

initialize_options() (distutils.cmd.Command 메서드)

initscr() (curses 모듈)

inode() (os.DirEntry 메서드)

INPLACE_ADD (opcode)

INPLACE_AND (opcode)

INPLACE_FLOOR_DIVIDE (opcode)

INPLACE_LSHIFT (opcode)

INPLACE_MATRIX_MULTIPLY (opcode)

INPLACE_MODULO (opcode)

INPLACE_MULTIPLY (opcode)

INPLACE_OR (opcode)

INPLACE_POWER (opcode)

INPLACE_RSHIFT (opcode)

INPLACE_SUBTRACT (opcode)

INPLACE_TRUE_DIVIDE (opcode)

INPLACE_XOR (opcode)

input

(2to3 fixer)

input() (fileinput 모듈)

(내장 함수)

input_charset (email.charset.Charset의 속성)

input_codec (email.charset.Charset의 속성)

InputOnly (tkinter.tix 클래스)

InputSource (xml.sax.xmlreader 클래스)

inquiry (C 데이터 형식)

insch() (curses.window 메서드)

insdelln() (curses.window 메서드)

insert() (array.array 메서드)

(collections.deque 메서드)

(sequence method)

(tkinter.ttk.Notebook 메서드)

(tkinter.ttk.Treeview 메서드)

(xml.etree.ElementTree.Element 메서드)

insert_text() (readline 모듈)

insertBefore() (xml.dom.Node 메서드)

insertln() (curses.window 메서드)

insnstr() (curses.window 메서드)

insort() (bisect 모듈)

insort_left() (bisect 모듈)

insort_right() (bisect 모듈)

inspect (모듈)

inspect command line option

--details

InspectLoader (importlib.abc 클래스)

insstr() (curses.window 메서드)

install() (gettext 모듈)

(gettext.NullTranslations 메서드)

install_opener() (urllib.request 모듈)

install_scripts() (venv.EnvBuilder 메서드)

installHandler() (unittest 모듈)

instance

call, [1]

class

객체, [1], [2]

instancemethod

객체

instate() (tkinter.ttk.Widget 메서드)

instr() (curses.window 메서드)

instream (shlex.shlex의 속성)

Instruction (dis 클래스)

Instruction.arg (dis 모듈)

Instruction.argrepr (dis 모듈)

Instruction.argval (dis 모듈)

Instruction.is_jump_target (dis 모듈)

Instruction.offset (dis 모듈)

Instruction.opcode (dis 모듈)

Instruction.opname (dis 모듈)

Instruction.starts_line (dis 모듈)

int

내장 함수, [1], [2]

int (uuid.UUID의 속성)

(내장 클래스)

Int2AP() (imaplib 모듈)

int_info (sys 모듈)

integer

literals

representation

types, operations on

객체, [1], [2]

integer literal

Integral (numbers 클래스)

Integrated Development Environment

IntegrityError

Intel/DVI ADPCM

IntEnum (enum 클래스)

interact (pdb command)

interact() (code 모듈)

(code.InteractiveConsole 메서드)

(telnetlib.Telnet 메서드)

interactive (대화형)

interactive mode

InteractiveConsole (code 클래스)

InteractiveInterpreter (code 클래스)

intern (2to3 fixer)

intern() (sys 모듈)

internal type

internal_attr (zipfile.ZipInfo의 속성)

Internaldate2tuple() (imaplib 모듈)

internalSubset (xml.dom.DocumentType의 속성)

Internet

interpolated string literal

interpolation

bytearray (%)

bytes (%)

interpolation, string (%)

InterpolationDepthError

InterpolationError

InterpolationMissingOptionError

InterpolationSyntaxError

interpreted (인터프리티드)

interpreter

interpreter lock

interpreter prompts

interpreter shutdown (인터프리터 종료)

interpreter_requires_environment() (test.support.script_helper 모듈)

interrupt() (sqlite3.Connection 메서드)

interrupt_main() (_thread 모듈)

InterruptedError

intersection() (frozenset 메서드)

intersection_update() (frozenset 메서드)

IntFlag (enum 클래스)

intro (cmd.Cmd의 속성)

InuseAttributeErr

inv() (operator 모듈)

InvalidAccessErr

invalidate_caches() (importlib 모듈)

(importlib.abc.MetaPathFinder 메서드)

(importlib.abc.PathEntryFinder 메서드)

(importlib.machinery.FileFinder 메서드)

(importlib.machinery.PathFinder의 클래스 메서드)

InvalidCharacterErr

InvalidModificationErr

InvalidOperation (decimal 클래스)

InvalidStateErr

InvalidStateError

InvalidURL

inversion

invert() (operator 모듈)

invocation

io

모듈

IO (typing 클래스)

io (모듈)

io.StringIO

객체

IOBase (io 클래스)

ioctl() (fcntl 모듈)

(socket.socket 메서드)

IOCTL_VM_SOCKETS_GET_LOCAL_CID (socket 모듈)

IOError

ior() (operator 모듈)

ip (ipaddress.IPv4Interface의 속성)

(ipaddress.IPv6Interface의 속성)

ip_address() (ipaddress 모듈)

ip_interface() (ipaddress 모듈)

ip_network() (ipaddress 모듈)

ipaddress (모듈)

ipow() (operator 모듈)

ipv4_mapped (ipaddress.IPv6Address의 속성)

IPv4Address (ipaddress 클래스)

IPv4Interface (ipaddress 클래스)

IPv4Network (ipaddress 클래스)

IPV6_ENABLED (test.support 모듈)

IPv6Address (ipaddress 클래스)

IPv6Interface (ipaddress 클래스)

IPv6Network (ipaddress 클래스)

irshift() (operator 모듈)

is

연산자, [1]

is not

연산자, [1]

is_() (operator 모듈)

is_absolute() (pathlib.PurePath 메서드)

is_alive() (multiprocessing.Process 메서드)

(threading.Thread 메서드)

is_android (test.support 모듈)

is_assigned() (symtable.Symbol 메서드)

is_attachment() (email.message.EmailMessage 메서드)

is_authenticated() (urllib.request.HTTPPasswordMgrWithPriorAuth 메서드)

is_block_device() (pathlib.Path 메서드)

is_blocked() (http.cookiejar.DefaultCookiePolicy 메서드)

is_canonical() (decimal.Context 메서드)

(decimal.Decimal 메서드)

is_char_device() (pathlib.Path 메서드)

IS_CHARACTER_JUNK() (difflib 모듈)

is_check_supported() (lzma 모듈)

is_closed() (asyncio.loop 메서드)

is_closing() (asyncio.BaseTransport 메서드)

(asyncio.StreamWriter 메서드)

is_dataclass() (dataclasses 모듈)

is_declared_global() (symtable.Symbol 메서드)

is_dir() (os.DirEntry 메서드)

(pathlib.Path 메서드)

(zipfile.ZipInfo 메서드)

is_enabled() (faulthandler 모듈)

is_expired() (http.cookiejar.Cookie 메서드)

is_fifo() (pathlib.Path 메서드)

is_file() (os.DirEntry 메서드)

(pathlib.Path 메서드)

is_finalizing() (sys 모듈)

is_finite() (decimal.Context 메서드)

(decimal.Decimal 메서드)

is_free() (symtable.Symbol 메서드)

is_global (ipaddress.IPv4Address의 속성)

(ipaddress.IPv6Address의 속성)

is_global() (symtable.Symbol 메서드)

is_hop_by_hop() (wsgiref.util 모듈)

is_imported() (symtable.Symbol 메서드)

is_infinite() (decimal.Context 메서드)

(decimal.Decimal 메서드)

is_integer() (float 메서드)

is_jython (test.support 모듈)

IS_LINE_JUNK() (difflib 모듈)

is_linetouched() (curses.window 메서드)

is_link_local (ipaddress.IPv4Address의 속성)

(ipaddress.IPv4Network의 속성)

(ipaddress.IPv6Address의 속성)

(ipaddress.IPv6Network의 속성)

is_local() (symtable.Symbol 메서드)

is_loopback (ipaddress.IPv4Address의 속성)

(ipaddress.IPv4Network의 속성)

(ipaddress.IPv6Address의 속성)

(ipaddress.IPv6Network의 속성)

is_mount() (pathlib.Path 메서드)

is_multicast (ipaddress.IPv4Address의 속성)

(ipaddress.IPv4Network의 속성)

(ipaddress.IPv6Address의 속성)

(ipaddress.IPv6Network의 속성)

is_multipart() (email.message.EmailMessage 메서드)

(email.message.Message 메서드)

is_namespace() (symtable.Symbol 메서드)

is_nan() (decimal.Context 메서드)

(decimal.Decimal 메서드)

is_nested() (symtable.SymbolTable 메서드)

is_normal() (decimal.Context 메서드)

(decimal.Decimal 메서드)

is_not() (operator 모듈)

is_not_allowed() (http.cookiejar.DefaultCookiePolicy 메서드)

is_optimized() (symtable.SymbolTable 메서드)

is_package() (importlib.abc.InspectLoader 메서드)

(importlib.abc.SourceLoader 메서드)

(importlib.machinery.ExtensionFileLoader 메서드)

(importlib.machinery.SourceFileLoader 메서드)

(importlib.machinery.SourcelessFileLoader 메서드)

(zipimport.zipimporter 메서드)

is_parameter() (symtable.Symbol 메서드)

is_private (ipaddress.IPv4Address의 속성)

(ipaddress.IPv4Network의 속성)

(ipaddress.IPv6Address의 속성)

(ipaddress.IPv6Network의 속성)

is_python_build() (sysconfig 모듈)

is_qnan() (decimal.Context 메서드)

(decimal.Decimal 메서드)

is_reading() (asyncio.ReadTransport 메서드)

is_referenced() (symtable.Symbol 메서드)

is_reserved (ipaddress.IPv4Address의 속성)

(ipaddress.IPv4Network의 속성)

(ipaddress.IPv6Address의 속성)

(ipaddress.IPv6Network의 속성)

is_reserved() (pathlib.PurePath 메서드)

is_resource() (importlib.abc.ResourceReader의 메서드)

(importlib.resources 모듈)

is_resource_enabled() (test.support 모듈)

is_running() (asyncio.loop 메서드)

is_safe (uuid.UUID의 속성)

is_serving() (asyncio.Server 메서드)

is_set() (asyncio.Event 메서드)

(threading.Event 메서드)

is_signed() (decimal.Context 메서드)

(decimal.Decimal 메서드)

is_site_local (ipaddress.IPv6Address의 속성)

(ipaddress.IPv6Network의 속성)

is_snan() (decimal.Context 메서드)

(decimal.Decimal 메서드)

is_socket() (pathlib.Path 메서드)

is_subnormal() (decimal.Context 메서드)

(decimal.Decimal 메서드)

is_symlink() (os.DirEntry 메서드)

(pathlib.Path 메서드)

is_tarfile() (tarfile 모듈)

is_term_resized() (curses 모듈)

is_tracing() (tracemalloc 모듈)

is_tracked() (gc 모듈)

is_unspecified (ipaddress.IPv4Address의 속성)

(ipaddress.IPv4Network의 속성)

(ipaddress.IPv6Address의 속성)

(ipaddress.IPv6Network의 속성)

is_wintouched() (curses.window 메서드)

is_zero() (decimal.Context 메서드)

(decimal.Decimal 메서드)

is_zipfile() (zipfile 모듈)

isabs() (os.path 모듈)

isabstract() (inspect 모듈)

IsADirectoryError

isalnum() (bytearray 메서드)

(bytes 메서드)

(curses.ascii 모듈)

(str 메서드)

isalpha() (bytearray 메서드)

(bytes 메서드)

(curses.ascii 모듈)

(str 메서드)

isascii() (bytearray 메서드)

(bytes 메서드)

(curses.ascii 모듈)

(str 메서드)

isasyncgen() (inspect 모듈)

isasyncgenfunction() (inspect 모듈)

isatty() (chunk.Chunk 메서드)

(io.IOBase 메서드)

(os 모듈)

isawaitable() (inspect 모듈)

isblank() (curses.ascii 모듈)

isblk() (tarfile.TarInfo 메서드)

isbuiltin() (inspect 모듈)

ischr() (tarfile.TarInfo 메서드)

isclass() (inspect 모듈)

isclose() (cmath 모듈)

(math 모듈)

iscntrl() (curses.ascii 모듈)

iscode() (inspect 모듈)

iscoroutine() (asyncio 모듈)

(inspect 모듈)

iscoroutinefunction() (asyncio 모듈)

(inspect 모듈)

isctrl() (curses.ascii 모듈)

isDaemon() (threading.Thread 메서드)

isdatadescriptor() (inspect 모듈)

isdecimal() (str 메서드)

isdev() (tarfile.TarInfo 메서드)

isdigit() (bytearray 메서드)

(bytes 메서드)

(curses.ascii 모듈)

(str 메서드)

isdir() (os.path 모듈)

(tarfile.TarInfo 메서드)

isdisjoint() (frozenset 메서드)

isdown() (turtle 모듈)

iselement() (xml.etree.ElementTree 모듈)

isenabled() (gc 모듈)

isEnabledFor() (logging.Logger 메서드)

isendwin() (curses 모듈)

ISEOF() (token 모듈)

isexpr() (parser 모듈)

(parser.ST 메서드)

isfifo() (tarfile.TarInfo 메서드)

isfile() (os.path 모듈)

(tarfile.TarInfo 메서드)

isfinite() (cmath 모듈)

(math 모듈)

isfirstline() (fileinput 모듈)

isframe() (inspect 모듈)

isfunction() (inspect 모듈)

isfuture() (asyncio 모듈)

isgenerator() (inspect 모듈)

isgeneratorfunction() (inspect 모듈)

isgetsetdescriptor() (inspect 모듈)

isgraph() (curses.ascii 모듈)

isidentifier() (str 메서드)

isinf() (cmath 모듈)

(math 모듈)

isinstance (2to3 fixer)

isinstance() (내장 함수)

iskeyword() (keyword 모듈)

isleap() (calendar 모듈)

islice() (itertools 모듈)

islink() (os.path 모듈)

islnk() (tarfile.TarInfo 메서드)

islower() (bytearray 메서드)

(bytes 메서드)

(curses.ascii 모듈)

(str 메서드)

ismemberdescriptor() (inspect 모듈)

ismeta() (curses.ascii 모듈)

ismethod() (inspect 모듈)

ismethoddescriptor() (inspect 모듈)

ismodule() (inspect 모듈)

ismount() (os.path 모듈)

isnan() (cmath 모듈)

(math 모듈)

ISNONTERMINAL() (token 모듈)

isnumeric() (str 메서드)

isocalendar() (datetime.date 메서드)

(datetime.datetime 메서드)

isoformat() (datetime.date 메서드)

(datetime.datetime 메서드)

(datetime.time 메서드)

isolation_level (sqlite3.Connection의 속성)

isoweekday() (datetime.date 메서드)

(datetime.datetime 메서드)

isprint() (curses.ascii 모듈)

isprintable() (str 메서드)

ispunct() (curses.ascii 모듈)

isreadable() (pprint 모듈)

(pprint.PrettyPrinter 메서드)

isrecursive() (pprint 모듈)

(pprint.PrettyPrinter 메서드)

isreg() (tarfile.TarInfo 메서드)

isReservedKey() (http.cookies.Morsel 메서드)

isroutine() (inspect 모듈)

isSameNode() (xml.dom.Node 메서드)

isspace() (bytearray 메서드)

(bytes 메서드)

(curses.ascii 모듈)

(str 메서드)

isstdin() (fileinput 모듈)

issubclass() (내장 함수)

issubset() (frozenset 메서드)

issuite() (parser 모듈)

(parser.ST 메서드)

issuperset() (frozenset 메서드)

issym() (tarfile.TarInfo 메서드)

ISTERMINAL() (token 모듈)

istitle() (bytearray 메서드)

(bytes 메서드)

(str 메서드)

istraceback() (inspect 모듈)

isub() (operator 모듈)

isupper() (bytearray 메서드)

(bytes 메서드)

(curses.ascii 모듈)

(str 메서드)

isvisible() (turtle 모듈)

isxdigit() (curses.ascii 모듈)

item

sequence

string

item selection

item() (tkinter.ttk.Treeview 메서드)

(xml.dom.NamedNodeMap 메서드)

(xml.dom.NodeList 메서드)

itemgetter() (operator 모듈)

items() (configparser.ConfigParser 메서드)

(contextvars.Context 메서드)

(dict 메서드)

(email.message.EmailMessage 메서드)

(email.message.Message 메서드)

(mailbox.Mailbox 메서드)

(types.MappingProxyType 메서드)

(xml.etree.ElementTree.Element 메서드)

itemsize (array.array의 속성)

(memoryview의 속성)

ItemsView (collections.abc 클래스)

(typing 클래스)

iter() (xml.etree.ElementTree.Element 메서드)

(xml.etree.ElementTree.ElementTree 메서드)

(내장 함수)

iter_attachments() (email.message.EmailMessage 메서드)

iter_child_nodes() (ast 모듈)

iter_fields() (ast 모듈)

iter_importers() (pkgutil 모듈)

iter_modules() (pkgutil 모듈)

iter_parts() (email.message.EmailMessage 메서드)

iter_unpack() (struct 모듈)

(struct.Struct 메서드)

iterable

unpacking

Iterable (collections.abc 클래스)

(typing 클래스)

iterable (이터러블)

Iterator (collections.abc 클래스)

(typing 클래스)

iterator (이터레이터)

iterator protocol

iterdecode() (codecs 모듈)

iterdir() (pathlib.Path 메서드)

iterdump() (sqlite3.Connection 메서드)

iterencode() (codecs 모듈)

(json.JSONEncoder 메서드)

iterfind() (xml.etree.ElementTree.Element 메서드)

(xml.etree.ElementTree.ElementTree 메서드)

iteritems() (mailbox.Mailbox 메서드)

iterkeys() (mailbox.Mailbox 메서드)

itermonthdates() (calendar.Calendar 메서드)

itermonthdays() (calendar.Calendar 메서드)

itermonthdays2() (calendar.Calendar 메서드)

itermonthdays3() (calendar.Calendar 메서드)

itermonthdays4() (calendar.Calendar 메서드)

iterparse() (xml.etree.ElementTree 모듈)

itertext() (xml.etree.ElementTree.Element 메서드)

itertools (2to3 fixer)

(모듈)

itertools_imports (2to3 fixer)

itervalues() (mailbox.Mailbox 메서드)

iterweekdays() (calendar.Calendar 메서드)

ITIMER_PROF (signal 모듈)

ITIMER_REAL (signal 모듈)

ITIMER_VIRTUAL (signal 모듈)

ItimerError

itruediv() (operator 모듈)

ixor() (operator 모듈)

J

j

in numeric literal

Jansen, Jack

Java

language

java_ver() (platform 모듈)

join() (asyncio.Queue의 메서드)

(bytearray 메서드)

(bytes 메서드)

(multiprocessing.JoinableQueue 메서드)

(multiprocessing.pool.Pool 메서드)

(multiprocessing.Process 메서드)

(os.path 모듈)

(queue.Queue 메서드)

(str 메서드)

(threading.Thread 메서드)

join_thread() (multiprocessing.Queue 메서드)

(test.support 모듈)

JoinableQueue (multiprocessing 클래스)

joinpath() (pathlib.PurePath 메서드)

js_output() (http.cookies.BaseCookie 메서드)

(http.cookies.Morsel 메서드)

json

모듈

json (모듈)

json.tool (모듈)

json.tool command line option

--help

--sort-keys

-h

infile

outfile

JSONDecodeError

JSONDecoder (json 클래스)

JSONEncoder (json 클래스)

jump (pdb command)

JUMP_ABSOLUTE (opcode)

JUMP_FORWARD (opcode)

JUMP_IF_FALSE_OR_POP (opcode)

JUMP_IF_TRUE_OR_POP (opcode)

K

kbhit() (msvcrt 모듈)

KDEDIR

kevent() (select 모듈)

key

(http.cookies.Morsel의 속성)

key function (키 함수)

key/datum pair

KEY_ALL_ACCESS (winreg 모듈)

KEY_CREATE_LINK (winreg 모듈)

KEY_CREATE_SUB_KEY (winreg 모듈)

KEY_ENUMERATE_SUB_KEYS (winreg 모듈)

KEY_EXECUTE (winreg 모듈)

KEY_NOTIFY (winreg 모듈)

KEY_QUERY_VALUE (winreg 모듈)

KEY_READ (winreg 모듈)

KEY_SET_VALUE (winreg 모듈)

KEY_WOW64_32KEY (winreg 모듈)

KEY_WOW64_64KEY (winreg 모듈)

KEY_WRITE (winreg 모듈)

KeyboardInterrupt

(built-in exception), [1]

KeyError

keyname() (curses 모듈)

keypad() (curses.window 메서드)

keyrefs() (weakref.WeakKeyDictionary 메서드)

keys() (contextvars.Context 메서드)

(dict 메서드)

(email.message.EmailMessage 메서드)

(email.message.Message 메서드)

(mailbox.Mailbox 메서드)

(sqlite3.Row 메서드)

(types.MappingProxyType 메서드)

(xml.etree.ElementTree.Element 메서드)

KeysView (collections.abc 클래스)

(typing 클래스)

keyword

(모듈)

keyword argument (키워드 인자)

keywords (functools.partial의 속성)

kill() (asyncio.asyncio.subprocess.Process 메서드)

(asyncio.SubprocessTransport 메서드)

(multiprocessing.Process 메서드)

(os 모듈)

(subprocess.Popen 메서드)

kill_python() (test.support.script_helper 모듈)

killchar() (curses 모듈)

killpg() (os 모듈)

kind (inspect.Parameter의 속성)

knownfiles (mimetypes 모듈)

kqueue() (select 모듈)

KqueueSelector (selectors 클래스)

kwargs (inspect.BoundArguments의 속성)

kwlist (keyword 모듈)

L

L (re 모듈)

LabelEntry (tkinter.tix 클래스)

LabelFrame (tkinter.tix 클래스)

lambda

expression, [1]

form

lambda (람다)

LambdaType (types 모듈)

LANG, [1], [2], [3], [4]

LANGUAGE, [1]

language

C, [1], [2], [3], [4], [5]

Java

large files

LARGEST (test.support 모듈)

LargeZipFile

last() (nntplib.NNTP 메서드)

last_accepted (multiprocessing.connection.Listener의 속성)

last_traceback (in module sys)

(sys 모듈)

last_type (sys 모듈)

last_value (sys 모듈)

lastChild (xml.dom.Node의 속성)

lastcmd (cmd.Cmd의 속성)

lastgroup (re.Match의 속성)

lastindex (re.Match의 속성)

lastResort (logging 모듈)

lastrowid (sqlite3.Cursor의 속성)

layout() (tkinter.ttk.Style 메서드)

lazycache() (linecache 모듈)

LazyLoader (importlib.util 클래스)

LBRACE (token 모듈)

LBYL

LC_ALL, [1]

(locale 모듈)

LC_COLLATE (locale 모듈)

LC_CTYPE (locale 모듈)

LC_MESSAGES, [1]

(locale 모듈)

LC_MONETARY (locale 모듈)

LC_NUMERIC (locale 모듈)

LC_TIME (locale 모듈)

lchflags() (os 모듈)

lchmod() (os 모듈)

(pathlib.Path 메서드)

lchown() (os 모듈)

LDCXXSHARED

ldexp() (math 모듈)

LDFLAGS

ldgettext() (gettext 모듈)

ldngettext() (gettext 모듈)

le() (operator 모듈)

leading whitespace

leapdays() (calendar 모듈)

leaveok() (curses.window 메서드)

left (filecmp.dircmp의 속성)

left() (turtle 모듈)

left_list (filecmp.dircmp의 속성)

left_only (filecmp.dircmp의 속성)

LEFTSHIFT (token 모듈)

LEFTSHIFTEQUAL (token 모듈)

len

내장 함수, [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11]

len() (내장 함수)

length (xml.dom.NamedNodeMap의 속성)

(xml.dom.NodeList의 속성)

length_hint() (operator 모듈)

LESS (token 모듈)

LESSEQUAL (token 모듈)

lexical analysis

lexical definitions

lexists() (os.path 모듈)

lgamma() (math 모듈)

lgettext() (gettext 모듈)

(gettext.GNUTranslations 메서드)

(gettext.NullTranslations 메서드)

lib2to3 (모듈)

libc_ver() (platform 모듈)

library (dbm.ndbm 모듈)

(ssl.SSLError의 속성)

library_dir_option() (distutils.ccompiler.CCompiler 메서드)

library_filename() (distutils.ccompiler.CCompiler 메서드)

library_option() (distutils.ccompiler.CCompiler 메서드)

LibraryLoader (ctypes 클래스)

license (내장 변수)

LifoQueue (asyncio 클래스)

(queue 클래스)

light-weight processes

limit_denominator() (fractions.Fraction 메서드)

LimitOverrunError

lin2adpcm() (audioop 모듈)

lin2alaw() (audioop 모듈)

lin2lin() (audioop 모듈)

lin2ulaw() (audioop 모듈)

line (C 함수)

line continuation

line joining, [1]

line structure

line() (msilib.Dialog 메서드)

line-buffered I/O

line_buffering (io.TextIOWrapper의 속성)

line_num (csv.csvreader의 속성)

linecache (모듈)

lineno (ast.AST의 속성)

(doctest.DocTest의 속성)

(doctest.Example의 속성)

(json.JSONDecodeError의 속성)

(pyclbr.Class의 속성)

(pyclbr.Function의 속성)

(re.error의 속성)

(shlex.shlex의 속성)

(traceback.TracebackException의 속성)

(tracemalloc.Filter의 속성)

(tracemalloc.Frame의 속성)

(xml.parsers.expat.ExpatError의 속성)

lineno() (fileinput 모듈)

LINES, [1], [2], [3], [4]

lines (os.terminal_size의 속성)

linesep (email.policy.Policy의 속성)

(os 모듈)

lineterminator (csv.Dialect의 속성)

LineTooLong

link() (distutils.ccompiler.CCompiler 메서드)

(os 모듈)

link_executable() (distutils.ccompiler.CCompiler 메서드)

link_shared_lib() (distutils.ccompiler.CCompiler 메서드)

link_shared_object() (distutils.ccompiler.CCompiler 메서드)

linkname (tarfile.TarInfo의 속성)

linux_distribution() (platform 모듈)

list

assignment, target

comprehensions

deletion target

display

empty

expression, [1], [2]

target, [1]

type, operations on

객체, [1], [2], [3], [4], [5], [6], [7], [8]

list (pdb command)

List (typing 클래스)

list (내장 클래스)

(리스트)

list comprehension (리스트 컴프리헨션)

list() (imaplib.IMAP4 메서드)

(multiprocessing.managers.SyncManager 메서드)

(nntplib.NNTP 메서드)

(poplib.POP3 메서드)

(tarfile.TarFile 메서드)

LIST_APPEND (opcode)

list_dialects() (csv 모듈)

list_folders() (mailbox.Maildir 메서드)

(mailbox.MH 메서드)

listdir() (os 모듈)

listen() (asyncore.dispatcher 메서드)

(logging.config 모듈)

(socket.socket 메서드)

(turtle 모듈)

Listener (multiprocessing.connection 클래스)

listMethods() (xmlrpc.client.ServerProxy.system 메서드)

ListNoteBook (tkinter.tix 클래스)

listxattr() (os 모듈)

literal, [1]

literal_eval() (ast 모듈)

literals

binary

complex number

floating point

hexadecimal

integer

numeric

octal

LittleEndianStructure (ctypes 클래스)

ljust() (bytearray 메서드)

(bytes 메서드)

(str 메서드)

LK_LOCK (msvcrt 모듈)

LK_NBLCK (msvcrt 모듈)

LK_NBRLCK (msvcrt 모듈)

LK_RLCK (msvcrt 모듈)

LK_UNLCK (msvcrt 모듈)

ll (pdb command)

LMTP (smtplib 클래스)

ln() (decimal.Context 메서드)

(decimal.Decimal 메서드)

LNAME

lngettext() (gettext 모듈)

(gettext.GNUTranslations 메서드)

(gettext.NullTranslations 메서드)

load() (http.cookiejar.FileCookieJar 메서드)

(http.cookies.BaseCookie 메서드)

(json 모듈)

(marshal 모듈)

(pickle 모듈)

(pickle.Unpickler 메서드)

(plistlib 모듈)

(tracemalloc.Snapshot의 클래스 메서드)

LOAD_ATTR (opcode)

LOAD_BUILD_CLASS (opcode)

load_cert_chain() (ssl.SSLContext 메서드)

LOAD_CLASSDEREF (opcode)

LOAD_CLOSURE (opcode)

LOAD_CONST (opcode)

load_default_certs() (ssl.SSLContext 메서드)

LOAD_DEREF (opcode)

load_dh_params() (ssl.SSLContext 메서드)

load_extension() (sqlite3.Connection 메서드)

LOAD_FAST (opcode)

LOAD_GLOBAL (opcode)

LOAD_METHOD (opcode)

load_module() (imp 모듈)

(importlib.abc.FileLoader 메서드)

(importlib.abc.InspectLoader 메서드)

(importlib.abc.Loader 메서드)

(importlib.abc.SourceLoader 메서드)

(importlib.machinery.SourceFileLoader 메서드)

(importlib.machinery.SourcelessFileLoader 메서드)

(zipimport.zipimporter 메서드)

LOAD_NAME (opcode)

load_package_tests() (test.support 모듈)

load_verify_locations() (ssl.SSLContext 메서드)

loader

Loader (importlib.abc 클래스)

loader (importlib.machinery.ModuleSpec의 속성)

(로더)

loader_state (importlib.machinery.ModuleSpec의 속성)

LoadError

LoadKey() (winreg 모듈)

LoadLibrary() (ctypes.LibraryLoader 메서드)

loads() (json 모듈)

(marshal 모듈)

(pickle 모듈)

(plistlib 모듈)

(xmlrpc.client 모듈)

loadTestsFromModule() (unittest.TestLoader 메서드)

loadTestsFromName() (unittest.TestLoader 메서드)

loadTestsFromNames() (unittest.TestLoader 메서드)

loadTestsFromTestCase() (unittest.TestLoader 메서드)

local (threading 클래스)

localcontext() (decimal 모듈)

LOCALE (re 모듈)

locale (모듈)

localeconv() (locale 모듈)

LocaleHTMLCalendar (calendar 클래스)

LocaleTextCalendar (calendar 클래스)

localName (xml.dom.Attr의 속성)

(xml.dom.Node의 속성)

locals() (내장 함수)

localtime() (email.utils 모듈)

(time 모듈)

Locator (xml.sax.xmlreader 클래스)

Lock (asyncio 클래스)

(multiprocessing 클래스)

(threading 클래스)

lock() (mailbox.Babyl 메서드)

(mailbox.Mailbox 메서드)

(mailbox.Maildir 메서드)

(mailbox.mbox 메서드)

(mailbox.MH 메서드)

(mailbox.MMDF 메서드)

Lock() (multiprocessing.managers.SyncManager 메서드)

lock, interpreter

lock_held() (imp 모듈)

locked() (_thread.lock 메서드)

(asyncio.Condition 메서드)

(asyncio.Lock 메서드)

(asyncio.Semaphore 메서드)

(threading.Lock 메서드)

lockf() (fcntl 모듈)

(os 모듈)

locking() (msvcrt 모듈)

LockType (_thread 모듈)

log() (cmath 모듈)

(logging 모듈)

(logging.Logger 메서드)

(math 모듈)

log10() (cmath 모듈)

(decimal.Context 메서드)

(decimal.Decimal 메서드)

(math 모듈)

log1p() (math 모듈)

log2() (math 모듈)

log_date_time_string() (http.server.BaseHTTPRequestHandler 메서드)

log_error() (http.server.BaseHTTPRequestHandler 메서드)

log_exception() (wsgiref.handlers.BaseHandler 메서드)

log_message() (http.server.BaseHTTPRequestHandler 메서드)

log_request() (http.server.BaseHTTPRequestHandler 메서드)

log_to_stderr() (multiprocessing 모듈)

logb() (decimal.Context 메서드)

(decimal.Decimal 메서드)

Logger (logging 클래스)

LoggerAdapter (logging 클래스)

logging

Errors

logging (모듈)

logging.config (모듈)

logging.handlers (모듈)

logical line

logical_and() (decimal.Context 메서드)

(decimal.Decimal 메서드)

logical_invert() (decimal.Context 메서드)

(decimal.Decimal 메서드)

logical_or() (decimal.Context 메서드)

(decimal.Decimal 메서드)

logical_xor() (decimal.Context 메서드)

(decimal.Decimal 메서드)

login() (ftplib.FTP 메서드)

(imaplib.IMAP4 메서드)

(nntplib.NNTP 메서드)

(smtplib.SMTP 메서드)

login_cram_md5() (imaplib.IMAP4 메서드)

LOGNAME, [1]

lognormvariate() (random 모듈)

logout() (imaplib.IMAP4 메서드)

LogRecord (logging 클래스)

long (2to3 fixer)

long integer

객체

LONG_MAX

longMessage (unittest.TestCase의 속성)

longname() (curses 모듈)

lookup() (codecs 모듈)

(symtable.SymbolTable 메서드)

(tkinter.ttk.Style 메서드)

(unicodedata 모듈)

lookup_error() (codecs 모듈)

LookupError

loop

over mutable sequence

statement, [1], [2], [3]

loop control

target

loop() (asyncore 모듈)

lower() (bytearray 메서드)

(bytes 메서드)

(str 메서드)

LPAR (token 모듈)

lpAttributeList (subprocess.STARTUPINFO의 속성)

lru_cache() (functools 모듈)

lseek() (os 모듈)

lshift() (operator 모듈)

LSQB (token 모듈)

lstat() (os 모듈)

(pathlib.Path 메서드)

lstrip() (bytearray 메서드)

(bytes 메서드)

(str 메서드)

lsub() (imaplib.IMAP4 메서드)

lt() (operator 모듈)

(turtle 모듈)

LWPCookieJar (http.cookiejar 클래스)

lzma (모듈)

LZMACompressor (lzma 클래스)

LZMADecompressor (lzma 클래스)

LZMAError

LZMAFile (lzma 클래스)

M

M (re 모듈)

mac_ver() (platform 모듈)

machine() (platform 모듈)

macpath (모듈)

macros (netrc.netrc의 속성)

magic

method

magic method (매직 메서드)

MAGIC_NUMBER (importlib.util 모듈)

MagicMock (unittest.mock 클래스)

Mailbox (mailbox 클래스)

mailbox (모듈)

mailcap (모듈)

Maildir (mailbox 클래스)

MaildirMessage (mailbox 클래스)

mailfrom (smtpd.SMTPChannel의 속성)

MailmanProxy (smtpd 클래스)

main(), [1], [2]

(py_compile 모듈)

(site 모듈)

(unittest 모듈)

main_thread() (threading 모듈)

mainloop() (turtle 모듈)

maintype (email.headerregistry.ContentTypeHeader의 속성)

major (email.headerregistry.MIMEVersionHeader의 속성)

major() (os 모듈)

make_alternative() (email.message.EmailMessage 메서드)

make_archive() (distutils.archive_util 모듈)

(shutil 모듈)

make_bad_fd() (test.support 모듈)

make_cookies() (http.cookiejar.CookieJar 메서드)

make_dataclass() (dataclasses 모듈)

make_file() (difflib.HtmlDiff 메서드)

MAKE_FUNCTION (opcode)

make_header() (email.header 모듈)

make_legacy_pyc() (test.support 모듈)

make_mixed() (email.message.EmailMessage 메서드)

make_msgid() (email.utils 모듈)

make_parser() (xml.sax 모듈)

make_pkg() (test.support.script_helper 모듈)

make_related() (email.message.EmailMessage 메서드)

make_script() (test.support.script_helper 모듈)

make_server() (wsgiref.simple_server 모듈)

make_table() (difflib.HtmlDiff 메서드)

make_tarball() (distutils.archive_util 모듈)

make_zip_pkg() (test.support.script_helper 모듈)

make_zip_script() (test.support.script_helper 모듈)

make_zipfile() (distutils.archive_util 모듈)

makedev() (os 모듈)

makedirs() (os 모듈)

makeelement() (xml.etree.ElementTree.Element 메서드)

makefile() (socket method)

(socket.socket 메서드)

makeLogRecord() (logging 모듈)

makePickle() (logging.handlers.SocketHandler 메서드)

makeRecord() (logging.Logger 메서드)

makeSocket() (logging.handlers.DatagramHandler 메서드)

(logging.handlers.SocketHandler 메서드)

maketrans() (bytearray의 정적 메서드)

(bytes의 정적 메서드)

(str의 정적 메서드)

malloc()

mangle_from_ (email.policy.Compat32의 속성)

(email.policy.Policy의 속성)

mangling

name, [1]

map (2to3 fixer)

map() (concurrent.futures.Executor 메서드)

(multiprocessing.pool.Pool 메서드)

(tkinter.ttk.Style 메서드)

(내장 함수)

MAP_ADD (opcode)

map_async() (multiprocessing.pool.Pool 메서드)

map_table_b2() (stringprep 모듈)

map_table_b3() (stringprep 모듈)

map_to_type() (email.headerregistry.HeaderRegistry 메서드)

mapLogRecord() (logging.handlers.HTTPHandler 메서드)

mapping

types, operations on

객체, [1], [2], [3], [4], [5]

Mapping (collections.abc 클래스)

(typing 클래스)

mapping (매핑)

mapping() (msilib.Control 메서드)

MappingProxyType (types 클래스)

MappingView (collections.abc 클래스)

(typing 클래스)

mapPriority() (logging.handlers.SysLogHandler 메서드)

maps (collections.ChainMap의 속성)

maps() (nis 모듈)

marshal (모듈)

marshalling

objects

masking

operations

Match (typing 클래스)

match() (nis 모듈)

(pathlib.PurePath 메서드)

(re 모듈)

(re.Pattern 메서드)

match_hostname() (ssl 모듈)

match_test() (test.support 모듈)

match_value() (test.support.Matcher 메서드)

Matcher (test.support 클래스)

matches() (test.support.Matcher 메서드)

math

모듈, [1]

math (모듈)

matmul() (operator 모듈)

matrix multiplication

max

내장 함수

max (datetime.datetime의 속성)

(datetime.date의 속성)

(datetime.timedelta의 속성)

(datetime.time의 속성)

max() (audioop 모듈)

(decimal.Context 메서드)

(decimal.Decimal 메서드)

(내장 함수)

max_count (email.headerregistry.BaseHeader의 속성)

MAX_EMAX (decimal 모듈)

MAX_INTERPOLATION_DEPTH (configparser 모듈)

max_line_length (email.policy.Policy의 속성)

max_lines (textwrap.TextWrapper의 속성)

max_mag() (decimal.Context 메서드)

(decimal.Decimal 메서드)

max_memuse (test.support 모듈)

MAX_PREC (decimal 모듈)

max_prefixlen (ipaddress.IPv4Address의 속성)

(ipaddress.IPv4Network의 속성)

(ipaddress.IPv6Address의 속성)

(ipaddress.IPv6Network의 속성)

MAX_Py_ssize_t (test.support 모듈)

maxarray (reprlib.Repr의 속성)

maxdeque (reprlib.Repr의 속성)

maxdict (reprlib.Repr의 속성)

maxDiff (unittest.TestCase의 속성)

maxfrozenset (reprlib.Repr의 속성)

MAXIMUM_SUPPORTED (ssl.TLSVersion의 속성)

maximum_version (ssl.SSLContext의 속성)

maxlen (collections.deque의 속성)

maxlevel (reprlib.Repr의 속성)

maxlist (reprlib.Repr의 속성)

maxlong (reprlib.Repr의 속성)

maxother (reprlib.Repr의 속성)

maxpp() (audioop 모듈)

maxset (reprlib.Repr의 속성)

maxsize (asyncio.Queue의 속성)

(sys 모듈)

maxstring (reprlib.Repr의 속성)

maxtuple (reprlib.Repr의 속성)

maxunicode (sys 모듈)

MAXYEAR (datetime 모듈)

MB_ICONASTERISK (winsound 모듈)

MB_ICONEXCLAMATION (winsound 모듈)

MB_ICONHAND (winsound 모듈)

MB_ICONQUESTION (winsound 모듈)

MB_OK (winsound 모듈)

mbox (mailbox 클래스)

mboxMessage (mailbox 클래스)

mean() (statistics 모듈)

median() (statistics 모듈)

median_grouped() (statistics 모듈)

median_high() (statistics 모듈)

median_low() (statistics 모듈)

MemberDescriptorType (types 모듈)

membership

test

memmove() (ctypes 모듈)

MemoryBIO (ssl 클래스)

MemoryError

MemoryHandler (logging.handlers 클래스)

memoryview

객체, [1]

memoryview (내장 클래스)

memset() (ctypes 모듈)

merge() (heapq 모듈)

Message (email.message 클래스)

(mailbox 클래스)

message digest, MD5

message_factory (email.policy.Policy의 속성)

message_from_binary_file() (email 모듈)

message_from_bytes() (email 모듈)

message_from_file() (email 모듈)

message_from_string() (email 모듈)

MessageBeep() (winsound 모듈)

MessageClass (http.server.BaseHTTPRequestHandler의 속성)

MessageError

MessageParseError

messages (xml.parsers.expat.errors 모듈)

meta

hooks

meta hooks

meta path finder (메타 경로 파인더)

meta() (curses 모듈)

meta_path (sys 모듈)

metaclass

(2to3 fixer)

(메타 클래스)

metaclass hint

MetaPathFinder (importlib.abc 클래스)

metavar (optparse.Option의 속성)

MetavarTypeHelpFormatter (argparse 클래스)

Meter (tkinter.tix 클래스)

METH_CLASS (내장 변수)

METH_COEXIST (내장 변수)

METH_FASTCALL (내장 변수)

METH_NOARGS (내장 변수)

METH_O (내장 변수)

METH_STATIC (내장 변수)

METH_VARARGS (내장 변수)

method

built-in

call

magic

special

user-defined

객체, [1], [2], [3], [4], [5]

method (urllib.request.Request의 속성)

(메서드)

method resolution order (메서드 결정 순서)

METHOD_BLOWFISH (crypt 모듈)

method_calls (unittest.mock.Mock의 속성)

METHOD_CRYPT (crypt 모듈)

METHOD_MD5 (crypt 모듈)

METHOD_SHA256 (crypt 모듈)

METHOD_SHA512 (crypt 모듈)

methodattrs (2to3 fixer)

methodcaller() (operator 모듈)

MethodDescriptorType (types 모듈)

methodHelp() (xmlrpc.client.ServerProxy.system 메서드)

methods

bytearray

bytes

string

methods (crypt 모듈)

(pyclbr.Class의 속성)

methodSignature() (xmlrpc.client.ServerProxy.system 메서드)

MethodType (in module types), [1]

(types 모듈)

MethodWrapperType (types 모듈)

MH (mailbox 클래스)

MHMessage (mailbox 클래스)

microsecond (datetime.datetime의 속성)

(datetime.time의 속성)

MIME

base64 encoding

content type

headers, [1]

quoted-printable encoding

MIMEApplication (email.mime.application 클래스)

MIMEAudio (email.mime.audio 클래스)

MIMEBase (email.mime.base 클래스)

MIMEImage (email.mime.image 클래스)

MIMEMessage (email.mime.message 클래스)

MIMEMultipart (email.mime.multipart 클래스)

MIMENonMultipart (email.mime.nonmultipart 클래스)

MIMEPart (email.message 클래스)

MIMEText (email.mime.text 클래스)

MimeTypes (mimetypes 클래스)

mimetypes (모듈)

MIMEVersionHeader (email.headerregistry 클래스)

min

내장 함수

min (datetime.datetime의 속성)

(datetime.date의 속성)

(datetime.timedelta의 속성)

(datetime.time의 속성)

min() (decimal.Context 메서드)

(decimal.Decimal 메서드)

(내장 함수)

MIN_EMIN (decimal 모듈)

MIN_ETINY (decimal 모듈)

min_mag() (decimal.Context 메서드)

(decimal.Decimal 메서드)

MINEQUAL (token 모듈)

MINIMUM_SUPPORTED (ssl.TLSVersion의 속성)

minimum_version (ssl.SSLContext의 속성)

minmax() (audioop 모듈)

minor (email.headerregistry.MIMEVersionHeader의 속성)

minor() (os 모듈)

minus

MINUS (token 모듈)

minus() (decimal.Context 메서드)

minute (datetime.datetime의 속성)

(datetime.time의 속성)

MINYEAR (datetime 모듈)

mirrored() (unicodedata 모듈)

misc_header (cmd.Cmd의 속성)

MISSING (contextvars.contextvars.Token.Token의 속성)

MISSING_C_DOCSTRINGS (test.support 모듈)

missing_compiler_executable() (test.support 모듈)

MissingSectionHeaderError

MIXERDEV

mkd() (ftplib.FTP 메서드)

mkdir() (os 모듈)

(pathlib.Path 메서드)

mkdtemp() (tempfile 모듈)

mkfifo() (os 모듈)

mknod() (os 모듈)

mkpath() (distutils.ccompiler.CCompiler 메서드)

(distutils.dir_util 모듈)

mksalt() (crypt 모듈)

mkstemp() (tempfile 모듈)

mktemp() (tempfile 모듈)

mktime() (time 모듈)

mktime_tz() (email.utils 모듈)

mlsd() (ftplib.FTP 메서드)

mmap (mmap 클래스)

(모듈)

MMDF (mailbox 클래스)

MMDFMessage (mailbox 클래스)

Mock (unittest.mock 클래스)

mock_add_spec() (unittest.mock.Mock 메서드)

mock_calls (unittest.mock.Mock의 속성)

mock_open() (unittest.mock 모듈)

mod() (operator 모듈)

mode (io.FileIO의 속성)

(ossaudiodev.oss_audio_device의 속성)

(tarfile.TarInfo의 속성)

mode() (statistics 모듈)

(turtle 모듈)

modes

file

modf() (math 모듈)

modified() (urllib.robotparser.RobotFileParser 메서드)

Modify() (msilib.View 메서드)

modify() (select.devpoll 메서드)

(select.epoll 메서드)

(select.poll 메서드)

(selectors.BaseSelector 메서드)

module

extension

importing

namespace

search path, [1], [2], [3], [4], [5], [6], [7]

객체, [1], [2]

module (pyclbr.Class의 속성)

(pyclbr.Function의 속성)

(모듈)

module spec

(모듈 스펙)

module_for_loader() (importlib.util 모듈)

module_from_spec() (importlib.util 모듈)

module_repr() (importlib.abc.Loader 메서드)

ModuleFinder (modulefinder 클래스)

modulefinder (모듈)

ModuleInfo (pkgutil 클래스)

ModuleNotFoundError

modules (in module sys), [1]

(modulefinder.ModuleFinder의 속성)

(sys 모듈)

modules_cleanup() (test.support 모듈)

modules_setup() (test.support 모듈)

ModuleSpec (importlib.machinery 클래스)

ModuleType (in module types)

(types 클래스)

modulo

monotonic() (time 모듈)

monotonic_ns() (time 모듈)

month (datetime.datetime의 속성)

(datetime.date의 속성)

month() (calendar 모듈)

month_abbr (calendar 모듈)

month_name (calendar 모듈)

monthcalendar() (calendar 모듈)

monthdatescalendar() (calendar.Calendar 메서드)

monthdays2calendar() (calendar.Calendar 메서드)

monthdayscalendar() (calendar.Calendar 메서드)

monthrange() (calendar 모듈)

Morsel (http.cookies 클래스)

most_common() (collections.Counter 메서드)

mouseinterval() (curses 모듈)

mousemask() (curses 모듈)

move() (curses.panel.Panel 메서드)

(curses.window 메서드)

(mmap.mmap 메서드)

(shutil 모듈)

(tkinter.ttk.Treeview 메서드)

move_file() (distutils.ccompiler.CCompiler 메서드)

(distutils.file_util 모듈)

move_to_end() (collections.OrderedDict 메서드)

MozillaCookieJar (http.cookiejar 클래스)

MRO

mro() (class 메서드)

msg (http.client.HTTPResponse의 속성)

(json.JSONDecodeError의 속성)

(re.error의 속성)

(traceback.TracebackException의 속성)

msg() (telnetlib.Telnet 메서드)

msi

msilib (모듈)

msvcrt (모듈)

mt_interact() (telnetlib.Telnet 메서드)

mtime (gzip.GzipFile의 속성)

(tarfile.TarInfo의 속성)

mtime() (urllib.robotparser.RobotFileParser 메서드)

mul() (audioop 모듈)

(operator 모듈)

MultiCall (xmlrpc.client 클래스)

MULTILINE (re 모듈)

MultipartConversionError

multiplication

multiply() (decimal.Context 메서드)

multiprocessing (모듈)

multiprocessing.connection (모듈)

multiprocessing.dummy (모듈)

multiprocessing.Manager() (multiprocessing.sharedctypes 모듈)

multiprocessing.managers (모듈)

multiprocessing.pool (모듈)

multiprocessing.sharedctypes (모듈)

mutable

sequence types

객체, [1], [2]

mutable (가변)

mutable object

mutable sequence

loop over

객체

MutableMapping (collections.abc 클래스)

(typing 클래스)

MutableSequence (collections.abc 클래스)

(typing 클래스)

MutableSet (collections.abc 클래스)

(typing 클래스)

mvderwin() (curses.window 메서드)

mvwin() (curses.window 메서드)

myrights() (imaplib.IMAP4 메서드)

N

N_TOKENS (token 모듈)

n_waiting (threading.Barrier의 속성)

name, [1], [2]

binding, [1], [2], [3], [4], [5], [6]

binding, global

class

function, [1]

mangling, [1]

rebinding

unbinding

name (codecs.CodecInfo의 속성)

(contextvars.ContextVar의 속성)

(doctest.DocTest의 속성)

(email.headerregistry.BaseHeader의 속성)

(hashlib.hash의 속성)

(hmac.HMAC의 속성)

(http.cookiejar.Cookie의 속성)

(importlib.abc.FileLoader의 속성)

(importlib.machinery.ExtensionFileLoader의 속성)

(importlib.machinery.ModuleSpec의 속성)

(importlib.machinery.SourceFileLoader의 속성)

(importlib.machinery.SourcelessFileLoader의 속성)

(inspect.Parameter의 속성)

(io.FileIO의 속성)

(multiprocessing.Process의 속성)

(os 모듈)

(os.DirEntry의 속성)

(ossaudiodev.oss_audio_device의 속성)

(pyclbr.Class의 속성)

(pyclbr.Function의 속성)

(tarfile.TarInfo의 속성)

(threading.Thread의 속성)

NAME (token 모듈)

name (xml.dom.Attr의 속성)

(xml.dom.DocumentType의 속성)

name() (unicodedata 모듈)

name2codepoint (html.entities 모듈)

named tuple (네임드 튜플)

NamedTemporaryFile() (tempfile 모듈)

NamedTuple (typing 클래스)

namedtuple() (collections 모듈)

NameError

예외

NameError (built-in exception)

namelist() (zipfile.ZipFile 메서드)

nameprep() (encodings.idna 모듈)

namer (logging.handlers.BaseRotatingHandler의 속성)

namereplace_errors() (codecs 모듈)

names

private

namespace

global

module

package

Namespace (argparse 클래스)

(multiprocessing.managers 클래스)

namespace (이름 공간)

namespace package (이름 공간 패키지)

namespace() (imaplib.IMAP4 메서드)

Namespace() (multiprocessing.managers.SyncManager 메서드)

NAMESPACE_DNS (uuid 모듈)

NAMESPACE_OID (uuid 모듈)

NAMESPACE_URL (uuid 모듈)

NAMESPACE_X500 (uuid 모듈)

NamespaceErr

namespaceURI (xml.dom.Node의 속성)

NaN

nan (cmath 모듈)

(math 모듈)

nanj (cmath 모듈)

NannyNag

napms() (curses 모듈)

nargs (optparse.Option의 속성)

nbytes (memoryview의 속성)

ndiff() (difflib 모듈)

ndim (memoryview의 속성)

ne (2to3 fixer)

ne() (operator 모듈)

needs_input (bz2.BZ2Decompressor의 속성)

(lzma.LZMADecompressor의 속성)

neg() (operator 모듈)

negation

nested scope (중첩된 스코프)

netmask (ipaddress.IPv4Network의 속성)

(ipaddress.IPv6Network의 속성)

NetmaskValueError

netrc (netrc 클래스)

(모듈)

NetrcParseError

netscape (http.cookiejar.CookiePolicy의 속성)

network (ipaddress.IPv4Interface의 속성)

(ipaddress.IPv6Interface의 속성)

Network News Transfer Protocol

network_address (ipaddress.IPv4Network의 속성)

(ipaddress.IPv6Network의 속성)

new() (hashlib 모듈)

(hmac 모듈)

new-style class (뉴스타일 클래스)

new_alignment() (formatter.writer 메서드)

new_child() (collections.ChainMap 메서드)

new_class() (types 모듈)

new_compiler() (distutils.ccompiler 모듈)

new_event_loop() (asyncio 모듈)

(asyncio.AbstractEventLoopPolicy 메서드)

new_font() (formatter.writer 메서드)

new_margin() (formatter.writer 메서드)

new_module() (imp 모듈)

new_panel() (curses.panel 모듈)

new_spacing() (formatter.writer 메서드)

new_styles() (formatter.writer 메서드)

newer() (distutils.dep_util 모듈)

newer_group() (distutils.dep_util 모듈)

newer_pairwise() (distutils.dep_util 모듈)

newgroups() (nntplib.NNTP 메서드)

NEWLINE (token 모듈)

NEWLINE token, [1]

newlines (io.TextIOBase의 속성)

newnews() (nntplib.NNTP 메서드)

newpad() (curses 모듈)

NewType() (typing 모듈)

newwin() (curses 모듈)

next (2to3 fixer)

(pdb command)

next() (nntplib.NNTP 메서드)

(tarfile.TarFile 메서드)

(tkinter.ttk.Treeview 메서드)

(내장 함수)

next_minus() (decimal.Context 메서드)

(decimal.Decimal 메서드)

next_plus() (decimal.Context 메서드)

(decimal.Decimal 메서드)

next_toward() (decimal.Context 메서드)

(decimal.Decimal 메서드)

nextfile() (fileinput 모듈)

nextkey() (dbm.gnu.gdbm 메서드)

nextSibling (xml.dom.Node의 속성)

ngettext() (gettext 모듈)

(gettext.GNUTranslations 메서드)

(gettext.NullTranslations 메서드)

nice() (os 모듈)

nis (모듈)

NL (token 모듈)

nl() (curses 모듈)

nl_langinfo() (locale 모듈)

nlargest() (heapq 모듈)

nlst() (ftplib.FTP 메서드)

NNTP

protocol

NNTP (nntplib 클래스)

nntp_implementation (nntplib.NNTP의 속성)

NNTP_SSL (nntplib 클래스)

nntp_version (nntplib.NNTP의 속성)

NNTPDataError

NNTPError

nntplib (모듈)

NNTPPermanentError

NNTPProtocolError

NNTPReplyError

NNTPTemporaryError

no_proxy

no_tracing() (test.support 모듈)

no_type_check() (typing 모듈)

no_type_check_decorator() (typing 모듈)

nocbreak() (curses 모듈)

NoDataAllowedErr

node() (platform 모듈)

nodelay() (curses.window 메서드)

nodeName (xml.dom.Node의 속성)

NodeTransformer (ast 클래스)

nodeType (xml.dom.Node의 속성)

nodeValue (xml.dom.Node의 속성)

NodeVisitor (ast 클래스)

noecho() (curses 모듈)

NOEXPR (locale 모듈)

NoModificationAllowedErr

nonblock() (ossaudiodev.oss_audio_device 메서드)

NonCallableMagicMock (unittest.mock 클래스)

NonCallableMock (unittest.mock 클래스)

None

객체, [1], [2]

None (Built-in object)

(내장 변수)

nonl() (curses 모듈)

nonlocal

글

nonzero (2to3 fixer)

noop() (imaplib.IMAP4 메서드)

(poplib.POP3 메서드)

NoOptionError

NOP (opcode)

noqiflush() (curses 모듈)

noraw() (curses 모듈)

NoReturn (typing 모듈)

NORMAL_PRIORITY_CLASS (subprocess 모듈)

normalize() (decimal.Context 메서드)

(decimal.Decimal 메서드)

(locale 모듈)

(unicodedata 모듈)

(xml.dom.Node 메서드)

NORMALIZE_WHITESPACE (doctest 모듈)

normalvariate() (random 모듈)

normcase() (os.path 모듈)

normpath() (os.path 모듈)

NoSectionError

NoSuchMailboxError

not

연산자, [1]

not in

연산자, [1], [2]

not_() (operator 모듈)

NotADirectoryError

notation

notationDecl() (xml.sax.handler.DTDHandler 메서드)

NotationDeclHandler() (xml.parsers.expat.xmlparser 메서드)

notations (xml.dom.DocumentType의 속성)

NotConnected

NoteBook (tkinter.tix 클래스)

Notebook (tkinter.ttk 클래스)

NotEmptyError

NOTEQUAL (token 모듈)

NotFoundErr

notify() (asyncio.Condition 메서드)

(threading.Condition 메서드)

notify_all() (asyncio.Condition 메서드)

(threading.Condition 메서드)

notimeout() (curses.window 메서드)

NotImplemented

객체

NotImplemented (내장 변수)

NotImplementedError

NotStandaloneHandler() (xml.parsers.expat.xmlparser 메서드)

NotSupportedErr

NotSupportedError

noutrefresh() (curses.window 메서드)

now() (datetime.datetime의 클래스 메서드)

NSIG (signal 모듈)

nsmallest() (heapq 모듈)

NT_OFFSET (token 모듈)

NTEventLogHandler (logging.handlers 클래스)

ntohl() (socket 모듈)

ntohs() (socket 모듈)

ntransfercmd() (ftplib.FTP 메서드)

null

operation, [1]

nullcontext() (contextlib 모듈)

NullFormatter (formatter 클래스)

NullHandler (logging 클래스)

NullImporter (imp 클래스)

NullTranslations (gettext 클래스)

NullWriter (formatter 클래스)

num_addresses (ipaddress.IPv4Network의 속성)

(ipaddress.IPv6Network의 속성)

number

complex

floating point

Number (numbers 클래스)

NUMBER (token 모듈)

number_class() (decimal.Context 메서드)

(decimal.Decimal 메서드)

numbers (모듈)

numerator (fractions.Fraction의 속성)

(numbers.Rational의 속성)

numeric

conversions

literals

object

types, operations on

객체, [1], [2], [3]

numeric literal

numeric() (unicodedata 모듈)

Numerical Python

numinput() (turtle 모듈)

numliterals (2to3 fixer)

O

O_APPEND (os 모듈)

O_ASYNC (os 모듈)

O_BINARY (os 모듈)

O_CLOEXEC (os 모듈)

O_CREAT (os 모듈)

O_DIRECT (os 모듈)

O_DIRECTORY (os 모듈)

O_DSYNC (os 모듈)

O_EXCL (os 모듈)

O_EXLOCK (os 모듈)

O_NDELAY (os 모듈)

O_NOATIME (os 모듈)

O_NOCTTY (os 모듈)

O_NOFOLLOW (os 모듈)

O_NOINHERIT (os 모듈)

O_NONBLOCK (os 모듈)

O_PATH (os 모듈)

O_RANDOM (os 모듈)

O_RDONLY (os 모듈)

O_RDWR (os 모듈)

O_RSYNC (os 모듈)

O_SEQUENTIAL (os 모듈)

O_SHLOCK (os 모듈)

O_SHORT_LIVED (os 모듈)

O_SYNC (os 모듈)

O_TEMPORARY (os 모듈)

O_TEXT (os 모듈)

O_TMPFILE (os 모듈)

O_TRUNC (os 모듈)

O_WRONLY (os 모듈)

obj (memoryview의 속성)

object

code, [1], [2], [3]

deallocation

finalization

immutable, [1]

numeric

object (UnicodeError의 속성)

(객체)

(내장 클래스)

object.__slots__ (내장 변수)

object_filenames() (distutils.ccompiler.CCompiler 메서드)

objects

comparing

flattening

marshalling

persistent

pickling

serializing

obufcount() (ossaudiodev.oss_audio_device 메서드)

obuffree() (ossaudiodev.oss_audio_device 메서드)

oct() (내장 함수)

octal

literals

octal literal

octdigits (string 모듈)

offset (traceback.TracebackException의 속성)

(xml.parsers.expat.ExpatError의 속성)

OK (curses 모듈)

old_value (contextvars.contextvars.Token.Token의 속성)

OleDLL (ctypes 클래스)

onclick() (turtle 모듈), [1]

ondrag() (turtle 모듈)

onecmd() (cmd.Cmd 메서드)

onkey() (turtle 모듈)

onkeypress() (turtle 모듈)

onkeyrelease() (turtle 모듈)

onrelease() (turtle 모듈)

onscreenclick() (turtle 모듈)

ontimer() (turtle 모듈)

OP (token 모듈)

OP_ALL (ssl 모듈)

OP_CIPHER_SERVER_PREFERENCE (ssl 모듈)

OP_ENABLE_MIDDLEBOX_COMPAT (ssl 모듈)

OP_NO_COMPRESSION (ssl 모듈)

OP_NO_RENEGOTIATION (ssl 모듈)

OP_NO_SSLv2 (ssl 모듈)

OP_NO_SSLv3 (ssl 모듈)

OP_NO_TICKET (ssl 모듈)

OP_NO_TLSv1 (ssl 모듈)

OP_NO_TLSv1_1 (ssl 모듈)

OP_NO_TLSv1_2 (ssl 모듈)

OP_NO_TLSv1_3 (ssl 모듈)

OP_SINGLE_DH_USE (ssl 모듈)

OP_SINGLE_ECDH_USE (ssl 모듈)

open

내장 함수, [1]

open() (aifc 모듈)

(bz2 모듈)

(codecs 모듈)

(dbm 모듈)

(dbm.dumb 모듈)

(dbm.gnu 모듈)

(dbm.ndbm 모듈)

(distutils.text_file.TextFile 메서드)

(gzip 모듈)

(imaplib.IMAP4 메서드)

(io 모듈)

(lzma 모듈)

(os 모듈)

(ossaudiodev 모듈)

(pathlib.Path 메서드)

(pipes.Template 메서드)

(shelve 모듈)

(sunau 모듈)

(tarfile 모듈)

(tarfile.TarFile의 클래스 메서드)

(telnetlib.Telnet 메서드)

(tokenize 모듈)

(urllib.request.OpenerDirector 메서드)

(urllib.request.URLopener 메서드)

(wave 모듈)

(webbrowser 모듈)

(webbrowser.controller 메서드)

(zipfile.ZipFile 메서드)

(내장 함수)

open_binary() (importlib.resources 모듈)

open_connection() (asyncio 모듈)

open_new() (webbrowser 모듈)

(webbrowser.controller 메서드)

open_new_tab() (webbrowser 모듈)

(webbrowser.controller 메서드)

open_osfhandle() (msvcrt 모듈)

open_resource() (importlib.abc.ResourceReader의 메서드)

open_text() (importlib.resources 모듈)

open_unix_connection() (asyncio 모듈)

open_unknown() (urllib.request.URLopener 메서드)

open_urlresource() (test.support 모듈)

OpenDatabase() (msilib 모듈)

OpenerDirector (urllib.request 클래스)

openfp() (sunau 모듈)

(wave 모듈)

OpenKey() (winreg 모듈)

OpenKeyEx() (winreg 모듈)

openlog() (syslog 모듈)

openmixer() (ossaudiodev 모듈)

openpty() (os 모듈)

(pty 모듈)

OpenSSL

(use in module hashlib)

(use in module ssl)

OPENSSL_VERSION (ssl 모듈)

OPENSSL_VERSION_INFO (ssl 모듈)

OPENSSL_VERSION_NUMBER (ssl 모듈)

OpenView() (msilib.Database 메서드)

operation

binary arithmetic

binary bitwise

Boolean

concatenation

null, [1]

power

repetition

shifting

slice

subscript

unary arithmetic

unary bitwise

OperationalError

operations

bitwise

Boolean, [1]

masking

shifting

operations on

dictionary type

integer types

list type

mapping types

numeric types

sequence types, [1]

operator

+ (plus), [1], [2]

- (minus), [1], [2]

comparison

overloading

precedence

ternary

operator (2to3 fixer)

(모듈)

operators

opmap (dis 모듈)

opname (dis 모듈)

optim_args_from_interpreter_flags() (test.support 모듈)

optimize() (pickletools 모듈)

OPTIMIZED_BYTECODE_SUFFIXES (importlib.machinery 모듈)

Optional (typing 모듈)

OptionGroup (optparse 클래스)

OptionMenu (tkinter.tix 클래스)

OptionParser (optparse 클래스)

options (doctest.Example의 속성)

Options (ssl 클래스)

options (ssl.SSLContext의 속성)

options() (configparser.ConfigParser 메서드)

optionxform() (configparser.ConfigParser 메서드), [1]

optparse (모듈)

or

bitwise

exclusive

inclusive

연산자, [1], [2]

or_() (operator 모듈)

ord

내장 함수

ord() (내장 함수)

order

evaluation

ordered_attributes (xml.parsers.expat.xmlparser의 속성)

OrderedDict (collections 클래스)

(typing 클래스)

origin (importlib.machinery.ModuleSpec의 속성)

origin_req_host (urllib.request.Request의 속성)

origin_server (wsgiref.handlers.BaseHandler의 속성)

os

모듈

os (모듈)

os.path (모듈)

os_environ (wsgiref.handlers.BaseHandler의 속성)

OSError

ossaudiodev (모듈)

OSSAudioError

outfile

json.tool command line option

output

standard

output (subprocess.CalledProcessError의 속성)

(subprocess.TimeoutExpired의 속성)

(unittest.TestCase의 속성)

output() (http.cookies.BaseCookie 메서드)

(http.cookies.Morsel 메서드)

output_charset (email.charset.Charset의 속성)

output_charset() (gettext.NullTranslations 메서드)

output_codec (email.charset.Charset의 속성)

output_difference() (doctest.OutputChecker 메서드)

OutputChecker (doctest 클래스)

OutputString() (http.cookies.Morsel 메서드)

over() (nntplib.NNTP 메서드)

Overflow (decimal 클래스)

OverflowError

(built-in exception), [1], [2], [3], [4], [5]

overlaps() (ipaddress.IPv4Network 메서드)

(ipaddress.IPv6Network 메서드)

overlay() (curses.window 메서드)

overload() (typing 모듈)

overloading

operator

overwrite() (curses.window 메서드)

owner() (pathlib.Path 메서드)

P

p (pdb command)

P_ALL (os 모듈)

P_DETACH (os 모듈)

P_NOWAIT (os 모듈)

P_NOWAITO (os 모듈)

P_OVERLAY (os 모듈)

P_PGID (os 모듈)

P_PID (os 모듈)

P_WAIT (os 모듈)

pack() (mailbox.MH 메서드)

(struct 모듈)

(struct.Struct 메서드)

pack_array() (xdrlib.Packer 메서드)

pack_bytes() (xdrlib.Packer 메서드)

pack_double() (xdrlib.Packer 메서드)

pack_farray() (xdrlib.Packer 메서드)

pack_float() (xdrlib.Packer 메서드)

pack_fopaque() (xdrlib.Packer 메서드)

pack_fstring() (xdrlib.Packer 메서드)

pack_into() (struct 모듈)

(struct.Struct 메서드)

pack_list() (xdrlib.Packer 메서드)

pack_opaque() (xdrlib.Packer 메서드)

pack_string() (xdrlib.Packer 메서드)

package, [1]

namespace

portion

regular

Package (importlib.resources 모듈)

package (패키지)

package variable

__all__

packed (ipaddress.IPv4Address의 속성)

(ipaddress.IPv6Address의 속성)

Packer (xdrlib 클래스)

packing

binary data

packing (widgets)

PAGER

pair_content() (curses 모듈)

pair_number() (curses 모듈)

PanedWindow (tkinter.tix 클래스)

parameter

call semantics

difference from argument

function definition

value, default

Parameter (inspect 클래스)

parameter (매개변수)

ParameterizedMIMEHeader (email.headerregistry 클래스)

parameters (inspect.Signature의 속성)

params (email.headerregistry.ParameterizedMIMEHeader의 속성)

pardir (os 모듈)

paren (2to3 fixer)

parent (importlib.machinery.ModuleSpec의 속성)

(pyclbr.Class의 속성)

(pyclbr.Function의 속성)

(urllib.request.BaseHandler의 속성)

parent() (tkinter.ttk.Treeview 메서드)

parenthesized form

parentNode (xml.dom.Node의 속성)

parents (collections.ChainMap의 속성)

paretovariate() (random 모듈)

parse() (ast 모듈)

(cgi 모듈)

(doctest.DocTestParser 메서드)

(email.parser.BytesParser 메서드)

(email.parser.Parser 메서드)

(string.Formatter 메서드)

(urllib.robotparser.RobotFileParser 메서드)

(xml.dom.minidom 모듈)

(xml.dom.pulldom 모듈)

(xml.etree.ElementTree 모듈)

(xml.etree.ElementTree.ElementTree 메서드)

Parse() (xml.parsers.expat.xmlparser 메서드)

parse() (xml.sax 모듈)

(xml.sax.xmlreader.XMLReader 메서드)

parse_and_bind() (readline 모듈)

parse_args() (argparse.ArgumentParser 메서드)

PARSE_COLNAMES (sqlite3 모듈)

parse_config_h() (sysconfig 모듈)

PARSE_DECLTYPES (sqlite3 모듈)

parse_header() (cgi 모듈)

parse_intermixed_args() (argparse.ArgumentParser 메서드)

parse_known_args() (argparse.ArgumentParser 메서드)

parse_known_intermixed_args() (argparse.ArgumentParser 메서드)

parse_multipart() (cgi 모듈)

parse_qs() (cgi 모듈)

(urllib.parse 모듈)

parse_qsl() (cgi 모듈)

(urllib.parse 모듈)

parseaddr() (email.utils 모듈)

parsebytes() (email.parser.BytesParser 메서드)

parsedate() (email.utils 모듈)

parsedate_to_datetime() (email.utils 모듈)

parsedate_tz() (email.utils 모듈)

ParseError (xml.etree.ElementTree 클래스)

ParseFile() (xml.parsers.expat.xmlparser 메서드)

ParseFlags() (imaplib 모듈)

parser

Parser (email.parser 클래스)

parser (모듈)

ParserCreate() (xml.parsers.expat 모듈)

ParserError

ParseResult (urllib.parse 클래스)

ParseResultBytes (urllib.parse 클래스)

parsestr() (email.parser.Parser 메서드)

parseString() (xml.dom.minidom 모듈)

(xml.dom.pulldom 모듈)

(xml.sax 모듈)

parsing

Python source code

URL

ParsingError

partial (asyncio.IncompleteReadError의 속성)

partial() (functools 모듈)

(imaplib.IMAP4 메서드)

partialmethod (functools 클래스)

parties (threading.Barrier의 속성)

partition() (bytearray 메서드)

(bytes 메서드)

(str 메서드)

pass

글

pass_() (poplib.POP3 메서드)

Paste

patch() (test.support 모듈)

(unittest.mock 모듈)

patch.dict() (unittest.mock 모듈)

patch.multiple() (unittest.mock 모듈)

patch.object() (unittest.mock 모듈)

patch.stopall() (unittest.mock 모듈)

PATH, [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12], [13], [14], [15], [16], [17], [18], [19], [20], [21], [22], [23], [24], [25], [26], [27], [28], [29], [30], [31], [32], [33], [34], [35]

path

configuration file

hooks

module search, [1], [2], [3], [4], [5], [6], [7]

operations, [1]

path (http.cookiejar.Cookie의 속성)

(http.server.BaseHTTPRequestHandler의 속성)

(importlib.abc.FileLoader의 속성)

(importlib.machinery.ExtensionFileLoader의 속성)

(importlib.machinery.FileFinder의 속성)

(importlib.machinery.SourceFileLoader의 속성)

(importlib.machinery.SourcelessFileLoader의 속성)

(in module sys), [1], [2], [3]

(os.DirEntry의 속성)

Path (pathlib 클래스)

path (sys 모듈)

path based finder

(경로 기반 파인더)

Path browser

path entry (경로 엔트리)

path entry finder (경로 엔트리 파인더)

path entry hook (경로 엔트리 훅)

path hooks

path() (importlib.resources 모듈)

path-like object (경로류 객체)

path_hook() (importlib.machinery.FileFinder의 클래스 메서드)

path_hooks (sys 모듈)

path_importer_cache (sys 모듈)

path_mtime() (importlib.abc.SourceLoader 메서드)

path_return_ok() (http.cookiejar.CookiePolicy 메서드)

path_stats() (importlib.abc.SourceLoader 메서드)

(importlib.machinery.SourceFileLoader 메서드)

pathconf() (os 모듈)

pathconf_names (os 모듈)

PathEntryFinder (importlib.abc 클래스)

PATHEXT, [1]

PathFinder (importlib.machinery 클래스)

pathlib (모듈)

PathLike (os 클래스)

pathname2url() (urllib.request 모듈)

pathsep (os 모듈)

pattern (re.error의 속성)

(re.Pattern의 속성)

Pattern (typing 클래스)

pause() (signal 모듈)

pause_reading() (asyncio.ReadTransport 메서드)

pause_writing() (asyncio.BaseProtocol 메서드)

PAX_FORMAT (tarfile 모듈)

pax_headers (tarfile.TarFile의 속성)

(tarfile.TarInfo의 속성)

pbkdf2_hmac() (hashlib 모듈)

pd() (turtle 모듈)

Pdb (class in pdb)

(pdb 클래스)

pdb (모듈)

peek() (bz2.BZ2File 메서드)

(gzip.GzipFile 메서드)

(io.BufferedReader 메서드)

(lzma.LZMAFile 메서드)

(weakref.finalize 메서드)

peer (smtpd.SMTPChannel의 속성)

PEM_cert_to_DER_cert() (ssl 모듈)

pen() (turtle 모듈)

pencolor() (turtle 모듈)

pending (ssl.MemoryBIO의 속성)

pending() (ssl.SSLSocket 메서드)

PendingDeprecationWarning

pendown() (turtle 모듈)

pensize() (turtle 모듈)

penup() (turtle 모듈)

PEP

PERCENT (token 모듈)

PERCENTEQUAL (token 모듈)

perf_counter() (time 모듈)

perf_counter_ns() (time 모듈)

Performance

PermissionError

permutations() (itertools 모듈)

Persist() (msilib.SummaryInformation 메서드)

persistence

persistent

objects

persistent_id (pickle protocol)

persistent_id() (pickle.Pickler 메서드)

persistent_load (pickle protocol)

persistent_load() (pickle.Unpickler 메서드)

PF_CAN (socket 모듈)

PF_PACKET (socket 모듈)

PF_RDS (socket 모듈)

pformat() (pprint 모듈)

(pprint.PrettyPrinter 메서드)

PGO (test.support 모듈)

phase() (cmath 모듈)

Philbrick, Geoff

physical line, [1], [2]

pi (cmath 모듈)

(math 모듈)

pickle

모듈, [1], [2], [3]

pickle (모듈)

pickle() (copyreg 모듈)

PickleError

Pickler (pickle 클래스)

pickletools (모듈)

pickletools command line option

--annotate

--indentlevel=<num>

--memo

--output=<file>

--preamble=<preamble>

-a

-l

-m

-o

-p

pickling

objects

PicklingError

pid (asyncio.asyncio.subprocess.Process의 속성)

(multiprocessing.Process의 속성)

(subprocess.Popen의 속성)

PIPE (subprocess 모듈)

Pipe() (multiprocessing 모듈)

pipe() (os 모듈)

pipe2() (os 모듈)

PIPE_BUF (select 모듈)

pipe_connection_lost() (asyncio.SubprocessProtocol 메서드)

pipe_data_received() (asyncio.SubprocessProtocol 메서드)

PIPE_MAX_SIZE (test.support 모듈)

pipes (모듈)

PKG_DIRECTORY (imp 모듈)

pkgutil (모듈)

placeholder (textwrap.TextWrapper의 속성)

PLAT

platform (in module sys)

(sys 모듈)

(모듈)

platform() (platform 모듈)

PlaySound() (winsound 모듈)

plist

file

plistlib (모듈)

plock() (os 모듈)

plus

PLUS (token 모듈)

plus() (decimal.Context 메서드)

PLUSEQUAL (token 모듈)

pm() (pdb 모듈)

POINTER() (ctypes 모듈)

pointer() (ctypes 모듈)

polar() (cmath 모듈)

Policy (email.policy 클래스)

poll() (multiprocessing.connection.Connection 메서드)

(select 모듈)

(select.devpoll 메서드)

(select.epoll 메서드)

(select.poll 메서드)

(subprocess.Popen 메서드)

PollSelector (selectors 클래스)

Pool (multiprocessing.pool 클래스)

pop() (array.array 메서드)

(collections.deque 메서드)

(dict 메서드)

(frozenset 메서드)

(mailbox.Mailbox 메서드)

(sequence method)

POP3

protocol

POP3 (poplib 클래스)

POP3_SSL (poplib 클래스)

pop_alignment() (formatter.formatter 메서드)

pop_all() (contextlib.ExitStack 메서드)

POP_BLOCK (opcode)

POP_EXCEPT (opcode)

pop_font() (formatter.formatter 메서드)

POP_JUMP_IF_FALSE (opcode)

POP_JUMP_IF_TRUE (opcode)

pop_margin() (formatter.formatter 메서드)

pop_source() (shlex.shlex 메서드)

pop_style() (formatter.formatter 메서드)

POP_TOP (opcode)

Popen (subprocess 클래스)

popen() (in module os), [1]

(os 모듈)

(platform 모듈)

popitem() (collections.OrderedDict 메서드)

(dict 메서드)

(mailbox.Mailbox 메서드)

popleft() (collections.deque 메서드)

poplib (모듈)

PopupMenu (tkinter.tix 클래스)

port (http.cookiejar.Cookie의 속성)

port_specified (http.cookiejar.Cookie의 속성)

portion

package

portion (포션)

pos (json.JSONDecodeError의 속성)

(re.error의 속성)

(re.Match의 속성)

pos() (operator 모듈)

(turtle 모듈)

position (xml.etree.ElementTree.ParseError의 속성)

position() (turtle 모듈)

positional argument (위치 인자)

POSIX

I/O control

threads

posix (모듈)

POSIX_FADV_DONTNEED (os 모듈)

POSIX_FADV_NOREUSE (os 모듈)

POSIX_FADV_NORMAL (os 모듈)

POSIX_FADV_RANDOM (os 모듈)

POSIX_FADV_SEQUENTIAL (os 모듈)

POSIX_FADV_WILLNEED (os 모듈)

posix_fadvise() (os 모듈)

posix_fallocate() (os 모듈)

POSIXLY_CORRECT

PosixPath (pathlib 클래스)

post() (nntplib.NNTP 메서드)

(ossaudiodev.oss_audio_device 메서드)

post_handshake_auth (ssl.SSLContext의 속성)

post_mortem() (pdb 모듈)

post_setup() (venv.EnvBuilder 메서드)

postcmd() (cmd.Cmd 메서드)

postloop() (cmd.Cmd 메서드)

pow

내장 함수, [1], [2], [3], [4], [5]

pow() (math 모듈)

(operator 모듈)

(내장 함수)

power

operation

power() (decimal.Context 메서드)

pp (pdb command)

pprint (모듈)

pprint() (pprint 모듈)

(pprint.PrettyPrinter 메서드)

prcal() (calendar 모듈)

pread() (os 모듈)

preadv() (os 모듈)

preamble (email.message.EmailMessage의 속성)

(email.message.Message의 속성)

precedence

operator

precmd() (cmd.Cmd 메서드)

prefix, [1], [2], [3]

PREFIX (distutils.sysconfig 모듈)

prefix (sys 모듈)

(xml.dom.Attr의 속성)

(xml.dom.Node의 속성)

(zipimport.zipimporter의 속성)

PREFIXES (site 모듈)

prefixlen (ipaddress.IPv4Network의 속성)

(ipaddress.IPv6Network의 속성)

preloop() (cmd.Cmd 메서드)

prepare() (logging.handlers.QueueHandler 메서드)

(logging.handlers.QueueListener 메서드)

prepare_class() (types 모듈)

prepare_input_source() (xml.sax.saxutils 모듈)

prepend() (pipes.Template 메서드)

preprocess() (distutils.ccompiler.CCompiler 메서드)

PrettyPrinter (pprint 클래스)

prev() (tkinter.ttk.Treeview 메서드)

previousSibling (xml.dom.Node의 속성)

primary

print

내장 함수

print (2to3 fixer)

print() (built-in function)

__str__() (object method)

print() (내장 함수)

print_callees() (pstats.Stats 메서드)

print_callers() (pstats.Stats 메서드)

print_directory() (cgi 모듈)

print_environ() (cgi 모듈)

print_environ_usage() (cgi 모듈)

print_exc() (timeit.Timer 메서드)

(traceback 모듈)

print_exception() (traceback 모듈)

PRINT_EXPR (opcode)

print_form() (cgi 모듈)

print_help() (argparse.ArgumentParser 메서드)

print_last() (traceback 모듈)

print_stack() (asyncio.Task 메서드)

(traceback 모듈)

print_stats() (profile.Profile 메서드)

(pstats.Stats 메서드)

print_tb() (traceback 모듈)

print_usage() (argparse.ArgumentParser 메서드)

(optparse.OptionParser 메서드)

print_version() (optparse.OptionParser 메서드)

printable (string 모듈)

printdir() (zipfile.ZipFile 메서드)

printf-style formatting, [1]

PRIO_PGRP (os 모듈)

PRIO_PROCESS (os 모듈)

PRIO_USER (os 모듈)

PriorityQueue (asyncio 클래스)

(queue 클래스)

private

names

prlimit() (resource 모듈)

prmonth() (calendar 모듈)

(calendar.TextCalendar 메서드)

ProactorEventLoop (asyncio 클래스)

procedure

call

process

group, [1]

id

id of parent

killing, [1]

scheduling priority, [1]

signalling, [1]

Process (multiprocessing 클래스)

process() (logging.LoggerAdapter 메서드)

process_exited() (asyncio.SubprocessProtocol 메서드)

process_message() (smtpd.SMTPServer 메서드)

process_request() (socketserver.BaseServer 메서드)

process_time() (time 모듈)

process_time_ns() (time 모듈)

process_tokens() (tabnanny 모듈)

ProcessError

processes, light-weight

ProcessingInstruction() (xml.etree.ElementTree 모듈)

processingInstruction() (xml.sax.handler.ContentHandler 메서드)

ProcessingInstructionHandler() (xml.parsers.expat.xmlparser 메서드)

ProcessLookupError

processor time, [1], [2]

processor() (platform 모듈)

ProcessPoolExecutor (concurrent.futures 클래스)

product() (itertools 모듈)

Profile (profile 클래스)

profile (모듈)

profile function, [1], [2]

profiler, [1]

profiling, deterministic

program

ProgrammingError

Progressbar (tkinter.ttk 클래스)

prompt (cmd.Cmd의 속성)

prompt_user_passwd() (urllib.request.FancyURLopener 메서드)

prompts, interpreter

propagate (logging.Logger의 속성)

property (내장 클래스)

property list

property_declaration_handler (xml.sax.handler 모듈)

property_dom_node (xml.sax.handler 모듈)

property_lexical_handler (xml.sax.handler 모듈)

property_xml_string (xml.sax.handler 모듈)

PropertyMock (unittest.mock 클래스)

prot_c() (ftplib.FTP_TLS 메서드)

prot_p() (ftplib.FTP_TLS 메서드)

proto (socket.socket의 속성)

protocol

CGI

context management

copy

FTP, [1]

HTTP, [1], [2], [3], [4], [5]

IMAP4

IMAP4_SSL

IMAP4_stream

iterator

NNTP

POP3

SMTP

Telnet

Protocol (asyncio 클래스)

protocol (ssl.SSLContext의 속성)

PROTOCOL_SSLv2 (ssl 모듈)

PROTOCOL_SSLv23 (ssl 모듈)

PROTOCOL_SSLv3 (ssl 모듈)

PROTOCOL_TLS (ssl 모듈)

PROTOCOL_TLS_CLIENT (ssl 모듈)

PROTOCOL_TLS_SERVER (ssl 모듈)

PROTOCOL_TLSv1 (ssl 모듈)

PROTOCOL_TLSv1_1 (ssl 모듈)

PROTOCOL_TLSv1_2 (ssl 모듈)

protocol_version (http.server.BaseHTTPRequestHandler의 속성)

PROTOCOL_VERSION (imaplib.IMAP4의 속성)

ProtocolError (xmlrpc.client 클래스)

provisional API (잠정 API)

provisional package (잠정 패키지)

proxy() (weakref 모듈)

proxyauth() (imaplib.IMAP4 메서드)

ProxyBasicAuthHandler (urllib.request 클래스)

ProxyDigestAuthHandler (urllib.request 클래스)

ProxyHandler (urllib.request 클래스)

ProxyType (weakref 모듈)

ProxyTypes (weakref 모듈)

pryear() (calendar.TextCalendar 메서드)

ps1 (sys 모듈)

ps2 (sys 모듈)

pstats (모듈)

pstdev() (statistics 모듈)

pthread_getcpuclockid() (time 모듈)

pthread_kill() (signal 모듈)

pthread_sigmask() (signal 모듈)

pthreads

pty

모듈

pty (모듈)

pu() (turtle 모듈)

publicId (xml.dom.DocumentType의 속성)

PullDom (xml.dom.pulldom 클래스)

punctuation (string 모듈)

punctuation_chars (shlex.shlex의 속성)

PurePath (pathlib 클래스)

PurePath.anchor (pathlib 모듈)

PurePath.drive (pathlib 모듈)

PurePath.name (pathlib 모듈)

PurePath.parent (pathlib 모듈)

PurePath.parents (pathlib 모듈)

PurePath.parts (pathlib 모듈)

PurePath.root (pathlib 모듈)

PurePath.stem (pathlib 모듈)

PurePath.suffix (pathlib 모듈)

PurePath.suffixes (pathlib 모듈)

PurePosixPath (pathlib 클래스)

PureProxy (smtpd 클래스)

PureWindowsPath (pathlib 클래스)

purge() (re 모듈)

Purpose.CLIENT_AUTH (ssl 모듈)

Purpose.SERVER_AUTH (ssl 모듈)

push() (asynchat.async_chat 메서드)

(code.InteractiveConsole 메서드)

(contextlib.ExitStack 메서드)

push_alignment() (formatter.formatter 메서드)

push_async_callback() (contextlib.AsyncExitStack 메서드)

push_async_exit() (contextlib.AsyncExitStack 메서드)

push_font() (formatter.formatter 메서드)

push_margin() (formatter.formatter 메서드)

push_source() (shlex.shlex 메서드)

push_style() (formatter.formatter 메서드)

push_token() (shlex.shlex 메서드)

push_with_producer() (asynchat.async_chat 메서드)

pushbutton() (msilib.Dialog 메서드)

put() (asyncio.Queue의 메서드)

(multiprocessing.Queue 메서드)

(multiprocessing.SimpleQueue 메서드)

(queue.Queue 메서드)

(queue.SimpleQueue 메서드)

put_nowait() (asyncio.Queue 메서드)

(multiprocessing.Queue 메서드)

(queue.Queue 메서드)

(queue.SimpleQueue 메서드)

putch() (msvcrt 모듈)

putenv() (os 모듈)

putheader() (http.client.HTTPConnection 메서드)

putp() (curses 모듈)

putrequest() (http.client.HTTPConnection 메서드)

putwch() (msvcrt 모듈)

putwin() (curses.window 메서드)

pvariance() (statistics 모듈)

pwd

모듈

pwd (모듈)

pwd() (ftplib.FTP 메서드)

pwrite() (os 모듈)

pwritev() (os 모듈)

Py_ABS (C 매크로)

Py_AddPendingCall (C 함수)

Py_AddPendingCall()

Py_AtExit (C 함수)

Py_BEGIN_ALLOW_THREADS

(C 매크로)

Py_BLOCK_THREADS (C 매크로)

Py_buffer (C 데이터 형식)

Py_buffer.buf (C 멤버 변수)

Py_buffer.format (C 멤버 변수)

Py_buffer.internal (C 멤버 변수)

Py_buffer.itemsize (C 멤버 변수)

Py_buffer.len (C 멤버 변수)

Py_buffer.ndim (C 멤버 변수)

Py_buffer.obj (C 멤버 변수)

Py_buffer.readonly (C 멤버 변수)

Py_buffer.shape (C 멤버 변수)

Py_buffer.strides (C 멤버 변수)

Py_buffer.suboffsets (C 멤버 변수)

Py_BuildValue (C 함수)

Py_BytesWarningFlag (C 변수)

Py_CHARMASK (C 매크로)

Py_CLEAR (C 함수)

py_compile (모듈)

PY_COMPILED (imp 모듈)

Py_CompileString (C 함수)

Py_CompileString(), [1], [2]

Py_CompileStringExFlags (C 함수)

Py_CompileStringFlags (C 함수)

Py_CompileStringObject (C 함수)

Py_complex (C 데이터 형식)

Py_DebugFlag (C 변수)

Py_DecodeLocale (C 함수)

Py_DECREF (C 함수)

Py_DECREF()

Py_DontWriteBytecodeFlag (C 변수)

Py_Ellipsis (C 변수)

Py_EncodeLocale (C 함수)

Py_END_ALLOW_THREADS

(C 매크로)

Py_EndInterpreter (C 함수)

Py_EnterRecursiveCall (C 함수)

Py_eval_input (C 변수)

Py_Exit (C 함수)

Py_False (C 변수)

Py_FatalError (C 함수)

Py_FatalError()

Py_FdIsInteractive (C 함수)

Py_file_input (C 변수)

Py_Finalize (C 함수)

Py_FinalizeEx (C 함수)

Py_FinalizeEx(), [1], [2], [3], [4]

PY_FROZEN (imp 모듈)

Py_FrozenFlag (C 변수)

Py_GetBuildInfo (C 함수)

Py_GetCompiler (C 함수)

Py_GetCopyright (C 함수)

Py_GETENV (C 매크로)

Py_GetExecPrefix (C 함수)

Py_GetExecPrefix()

Py_GetPath (C 함수)

Py_GetPath(), [1], [2]

Py_GetPlatform (C 함수)

Py_GetPrefix (C 함수)

Py_GetPrefix()

Py_GetProgramFullPath (C 함수)

Py_GetProgramFullPath()

Py_GetProgramName (C 함수)

Py_GetPythonHome (C 함수)

Py_GetVersion (C 함수)

Py_HashRandomizationFlag (C 변수)

Py_IgnoreEnvironmentFlag (C 변수)

Py_INCREF (C 함수)

Py_INCREF()

Py_Initialize (C 함수)

Py_Initialize(), [1], [2], [3]

Py_InitializeEx (C 함수)

Py_InspectFlag (C 변수)

Py_InteractiveFlag (C 변수)

Py_IsInitialized (C 함수)

Py_IsInitialized()

Py_IsolatedFlag (C 변수)

Py_LeaveRecursiveCall (C 함수)

Py_LegacyWindowsFSEncodingFlag (C 변수)

Py_LegacyWindowsStdioFlag (C 변수)

Py_Main (C 함수)

Py_MAX (C 매크로)

Py_MEMBER_SIZE (C 매크로)

Py_MIN (C 매크로)

Py_mod_create (C 변수)

Py_mod_exec (C 변수)

Py_NewInterpreter (C 함수)

Py_None (C 변수)

Py_NoSiteFlag (C 변수)

Py_NotImplemented (C 변수)

Py_NoUserSiteDirectory (C 변수)

py_object (ctypes 클래스)

Py_OptimizeFlag (C 변수)

Py_PRINT_RAW

PY_PYTHON

Py_QuietFlag (C 변수)

Py_REFCNT (C 매크로)

Py_ReprEnter (C 함수)

Py_ReprLeave (C 함수)

Py_RETURN_FALSE (C 매크로)

Py_RETURN_NONE (C 매크로)

Py_RETURN_NOTIMPLEMENTED (C 매크로)

Py_RETURN_RICHCOMPARE (C 함수)

Py_RETURN_TRUE (C 매크로)

Py_SetPath (C 함수)

Py_SetPath()

Py_SetProgramName (C 함수)

Py_SetProgramName(), [1], [2], [3]

Py_SetPythonHome (C 함수)

Py_SetStandardStreamEncoding (C 함수)

Py_single_input (C 변수)

Py_SIZE (C 매크로)

PY_SOURCE (imp 모듈)

PY_SSIZE_T_MAX

Py_STRINGIFY (C 매크로)

Py_TPFLAGS_BASE_EXC_SUBCLASS (내장 변수)

Py_TPFLAGS_BASETYPE (내장 변수)

Py_TPFLAGS_BYTES_SUBCLASS (내장 변수)

Py_TPFLAGS_DEFAULT (내장 변수)

Py_TPFLAGS_DICT_SUBCLASS (내장 변수)

Py_TPFLAGS_HAVE_FINALIZE (내장 변수)

Py_TPFLAGS_HAVE_GC (내장 변수)

Py_TPFLAGS_HEAPTYPE (내장 변수)

Py_TPFLAGS_LIST_SUBCLASS (내장 변수)

Py_TPFLAGS_LONG_SUBCLASS (내장 변수)

Py_TPFLAGS_READY (내장 변수)

Py_TPFLAGS_READYING (내장 변수)

Py_TPFLAGS_TUPLE_SUBCLASS (내장 변수)

Py_TPFLAGS_TYPE_SUBCLASS (내장 변수)

Py_TPFLAGS_UNICODE_SUBCLASS (내장 변수)

Py_tracefunc (C 데이터 형식)

Py_True (C 변수)

Py_tss_NEEDS_INIT (C 매크로)

Py_tss_t (C 데이터 형식)

Py_TYPE (C 매크로)

Py_UCS1 (C 데이터 형식)

Py_UCS2 (C 데이터 형식)

Py_UCS4 (C 데이터 형식)

Py_UNBLOCK_THREADS (C 매크로)

Py_UnbufferedStdioFlag (C 변수)

Py_UNICODE (C 데이터 형식)

Py_UNICODE_IS_HIGH_SURROGATE (C 매크로)

Py_UNICODE_IS_LOW_SURROGATE (C 매크로)

Py_UNICODE_IS_SURROGATE (C 매크로)

Py_UNICODE_ISALNUM (C 함수)

Py_UNICODE_ISALPHA (C 함수)

Py_UNICODE_ISDECIMAL (C 함수)

Py_UNICODE_ISDIGIT (C 함수)

Py_UNICODE_ISLINEBREAK (C 함수)

Py_UNICODE_ISLOWER (C 함수)

Py_UNICODE_ISNUMERIC (C 함수)

Py_UNICODE_ISPRINTABLE (C 함수)

Py_UNICODE_ISSPACE (C 함수)

Py_UNICODE_ISTITLE (C 함수)

Py_UNICODE_ISUPPER (C 함수)

Py_UNICODE_JOIN_SURROGATES (C 매크로)

Py_UNICODE_TODECIMAL (C 함수)

Py_UNICODE_TODIGIT (C 함수)

Py_UNICODE_TOLOWER (C 함수)

Py_UNICODE_TONUMERIC (C 함수)

Py_UNICODE_TOTITLE (C 함수)

Py_UNICODE_TOUPPER (C 함수)

Py_UNREACHABLE (C 매크로)

Py_UNUSED (C 매크로)

Py_VaBuildValue (C 함수)

Py_VerboseFlag (C 변수)

Py_VISIT (C 함수)

Py_XDECREF (C 함수)

Py_XDECREF()

Py_XINCREF (C 함수)

PyAnySet_Check (C 함수)

PyAnySet_CheckExact (C 함수)

PyArg_Parse (C 함수)

PyArg_ParseTuple (C 함수)

PyArg_ParseTuple()

PyArg_ParseTupleAndKeywords (C 함수)

PyArg_ParseTupleAndKeywords()

PyArg_UnpackTuple (C 함수)

PyArg_ValidateKeywordArguments (C 함수)

PyArg_VaParse (C 함수)

PyArg_VaParseTupleAndKeywords (C 함수)

PyASCIIObject (C 데이터 형식)

PyAsyncMethods (C 데이터 형식)

PyAsyncMethods.am_aiter (C 멤버 변수)

PyAsyncMethods.am_anext (C 멤버 변수)

PyAsyncMethods.am_await (C 멤버 변수)

PyBool_Check (C 함수)

PyBool_FromLong (C 함수)

PyBUF_ANY_CONTIGUOUS (C 매크로)

PyBUF_C_CONTIGUOUS (C 매크로)

PyBUF_CONTIG (C 매크로)

PyBUF_CONTIG_RO (C 매크로)

PyBUF_F_CONTIGUOUS (C 매크로)

PyBUF_FORMAT (C 매크로)

PyBUF_FULL (C 매크로)

PyBUF_FULL_RO (C 매크로)

PyBUF_INDIRECT (C 매크로)

PyBUF_ND (C 매크로), [1]

PyBUF_RECORDS (C 매크로)

PyBUF_RECORDS_RO (C 매크로)

PyBUF_SIMPLE (C 매크로)

PyBUF_STRIDED (C 매크로)

PyBUF_STRIDED_RO (C 매크로)

PyBUF_STRIDES (C 매크로)

PyBUF_WRITABLE (C 매크로)

PyBuffer_FillContiguousStrides (C 함수)

PyBuffer_FillInfo (C 함수)

PyBuffer_FromContiguous (C 함수)

PyBuffer_GetPointer (C 함수)

PyBuffer_IsContiguous (C 함수)

PyBuffer_Release (C 함수)

PyBuffer_SizeFromFormat (C 함수)

PyBuffer_ToContiguous (C 함수)

PyBufferProcs

(C 데이터 형식)

PyBufferProcs.bf_getbuffer (C 멤버 변수)

PyBufferProcs.bf_releasebuffer (C 멤버 변수)

PyByteArray_AS_STRING (C 함수)

PyByteArray_AsString (C 함수)

PyByteArray_Check (C 함수)

PyByteArray_CheckExact (C 함수)

PyByteArray_Concat (C 함수)

PyByteArray_FromObject (C 함수)

PyByteArray_FromStringAndSize (C 함수)

PyByteArray_GET_SIZE (C 함수)

PyByteArray_Resize (C 함수)

PyByteArray_Size (C 함수)

PyByteArray_Type (C 변수)

PyByteArrayObject (C 데이터 형식)

PyBytes_AS_STRING (C 함수)

PyBytes_AsString (C 함수)

PyBytes_AsStringAndSize (C 함수)

PyBytes_Check (C 함수)

PyBytes_CheckExact (C 함수)

PyBytes_Concat (C 함수)

PyBytes_ConcatAndDel (C 함수)

PyBytes_FromFormat (C 함수)

PyBytes_FromFormatV (C 함수)

PyBytes_FromObject (C 함수)

PyBytes_FromString (C 함수)

PyBytes_FromStringAndSize (C 함수)

PyBytes_GET_SIZE (C 함수)

PyBytes_Size (C 함수)

PyBytes_Type (C 변수)

PyBytesObject (C 데이터 형식)

PyCallable_Check (C 함수)

PyCallIter_Check (C 함수)

PyCallIter_New (C 함수)

PyCallIter_Type (C 변수)

PyCapsule (C 데이터 형식)

PyCapsule_CheckExact (C 함수)

PyCapsule_Destructor (C 데이터 형식)

PyCapsule_GetContext (C 함수)

PyCapsule_GetDestructor (C 함수)

PyCapsule_GetName (C 함수)

PyCapsule_GetPointer (C 함수)

PyCapsule_Import (C 함수)

PyCapsule_IsValid (C 함수)

PyCapsule_New (C 함수)

PyCapsule_SetContext (C 함수)

PyCapsule_SetDestructor (C 함수)

PyCapsule_SetName (C 함수)

PyCapsule_SetPointer (C 함수)

PyCell_Check (C 함수)

PyCell_GET (C 함수)

PyCell_Get (C 함수)

PyCell_New (C 함수)

PyCell_SET (C 함수)

PyCell_Set (C 함수)

PyCell_Type (C 변수)

PyCellObject (C 데이터 형식)

PyCFunction (C 데이터 형식)

PyCFunctionWithKeywords (C 데이터 형식)

PycInvalidationMode (py_compile 클래스)

pyclbr (모듈)

PyCode_Check (C 함수)

PyCode_GetNumFree (C 함수)

PyCode_New (C 함수)

PyCode_NewEmpty (C 함수)

PyCode_Type (C 변수)

PyCodec_BackslashReplaceErrors (C 함수)

PyCodec_Decode (C 함수)

PyCodec_Decoder (C 함수)

PyCodec_Encode (C 함수)

PyCodec_Encoder (C 함수)

PyCodec_IgnoreErrors (C 함수)

PyCodec_IncrementalDecoder (C 함수)

PyCodec_IncrementalEncoder (C 함수)

PyCodec_KnownEncoding (C 함수)

PyCodec_LookupError (C 함수)

PyCodec_NameReplaceErrors (C 함수)

PyCodec_Register (C 함수)

PyCodec_RegisterError (C 함수)

PyCodec_ReplaceErrors (C 함수)

PyCodec_StreamReader (C 함수)

PyCodec_StreamWriter (C 함수)

PyCodec_StrictErrors (C 함수)

PyCodec_XMLCharRefReplaceErrors (C 함수)

PyCodeObject (C 데이터 형식)

PyCompactUnicodeObject (C 데이터 형식)

PyCompileError

PyCompilerFlags (C 데이터 형식)

PyComplex_AsCComplex (C 함수)

PyComplex_Check (C 함수)

PyComplex_CheckExact (C 함수)

PyComplex_FromCComplex (C 함수)

PyComplex_FromDoubles (C 함수)

PyComplex_ImagAsDouble (C 함수)

PyComplex_RealAsDouble (C 함수)

PyComplex_Type (C 변수)

PyComplexObject (C 데이터 형식)

PyContext (C 데이터 형식)

PyContext_CheckExact (C 함수)

PyContext_ClearFreeList (C 함수)

PyContext_Copy (C 함수)

PyContext_CopyCurrent (C 함수)

PyContext_Enter (C 함수)

PyContext_Exit (C 함수)

PyContext_New (C 함수)

PyContext_Type (C 변수)

PyContextToken (C 데이터 형식)

PyContextToken_CheckExact (C 함수)

PyContextToken_Type (C 변수)

PyContextVar (C 데이터 형식)

PyContextVar_CheckExact (C 함수)

PyContextVar_Get (C 함수)

PyContextVar_New (C 함수)

PyContextVar_Reset (C 함수)

PyContextVar_Set (C 함수)

PyContextVar_Type (C 변수)

PyCoro_CheckExact (C 함수)

PyCoro_New (C 함수)

PyCoro_Type (C 변수)

PyCoroObject (C 데이터 형식)

PyDate_Check (C 함수)

PyDate_CheckExact (C 함수)

PyDate_FromDate (C 함수)

PyDate_FromTimestamp (C 함수)

PyDateTime_Check (C 함수)

PyDateTime_CheckExact (C 함수)

PyDateTime_DATE_GET_FOLD (C 함수)

PyDateTime_DATE_GET_HOUR (C 함수)

PyDateTime_DATE_GET_MICROSECOND (C 함수)

PyDateTime_DATE_GET_MINUTE (C 함수)

PyDateTime_DATE_GET_SECOND (C 함수)

PyDateTime_DELTA_GET_DAYS (C 함수)

PyDateTime_DELTA_GET_MICROSECONDS (C 함수)

PyDateTime_DELTA_GET_SECONDS (C 함수)

PyDateTime_FromDateAndTime (C 함수)

PyDateTime_FromDateAndTimeAndFold (C 함수)

PyDateTime_FromTimestamp (C 함수)

PyDateTime_GET_DAY (C 함수)

PyDateTime_GET_MONTH (C 함수)

PyDateTime_GET_YEAR (C 함수)

PyDateTime_TIME_GET_FOLD (C 함수)

PyDateTime_TIME_GET_HOUR (C 함수)

PyDateTime_TIME_GET_MICROSECOND (C 함수)

PyDateTime_TIME_GET_MINUTE (C 함수)

PyDateTime_TIME_GET_SECOND (C 함수)

PyDateTime_TimeZone_UTC (C 변수)

PyDelta_Check (C 함수)

PyDelta_CheckExact (C 함수)

PyDelta_FromDSU (C 함수)

PyDescr_IsData (C 함수)

PyDescr_NewClassMethod (C 함수)

PyDescr_NewGetSet (C 함수)

PyDescr_NewMember (C 함수)

PyDescr_NewMethod (C 함수)

PyDescr_NewWrapper (C 함수)

PyDict_Check (C 함수)

PyDict_CheckExact (C 함수)

PyDict_Clear (C 함수)

PyDict_ClearFreeList (C 함수)

PyDict_Contains (C 함수)

PyDict_Copy (C 함수)

PyDict_DelItem (C 함수)

PyDict_DelItemString (C 함수)

PyDict_GetItem (C 함수)

PyDict_GetItemString (C 함수)

PyDict_GetItemWithError (C 함수)

PyDict_Items (C 함수)

PyDict_Keys (C 함수)

PyDict_Merge (C 함수)

PyDict_MergeFromSeq2 (C 함수)

PyDict_New (C 함수)

PyDict_Next (C 함수)

PyDict_SetDefault (C 함수)

PyDict_SetItem (C 함수)

PyDict_SetItemString (C 함수)

PyDict_Size (C 함수)

PyDict_Type (C 변수)

PyDict_Update (C 함수)

PyDict_Values (C 함수)

PyDictObject (C 데이터 형식)

PyDictProxy_New (C 함수)

PyDLL (ctypes 클래스)

pydoc (모듈)

PyDoc_STR (C 매크로)

PyDoc_STRVAR (C 매크로)

PyErr_BadArgument (C 함수)

PyErr_BadInternalCall (C 함수)

PyErr_CheckSignals (C 함수)

PyErr_Clear (C 함수)

PyErr_Clear(), [1]

PyErr_ExceptionMatches (C 함수)

PyErr_ExceptionMatches()

PyErr_Fetch (C 함수)

PyErr_Fetch()

PyErr_Format (C 함수)

PyErr_FormatV (C 함수)

PyErr_GetExcInfo (C 함수)

PyErr_GivenExceptionMatches (C 함수)

PyErr_NewException (C 함수)

PyErr_NewExceptionWithDoc (C 함수)

PyErr_NoMemory (C 함수)

PyErr_NormalizeException (C 함수)

PyErr_Occurred (C 함수)

PyErr_Occurred()

PyErr_Print (C 함수)

PyErr_PrintEx (C 함수)

PyErr_ResourceWarning (C 함수)

PyErr_Restore (C 함수)

PyErr_Restore()

PyErr_SetExcFromWindowsErr (C 함수)

PyErr_SetExcFromWindowsErrWithFilename (C 함수)

PyErr_SetExcFromWindowsErrWithFilenameObject (C 함수)

PyErr_SetExcFromWindowsErrWithFilenameObjects (C 함수)

PyErr_SetExcInfo (C 함수)

PyErr_SetFromErrno (C 함수)

PyErr_SetFromErrnoWithFilename (C 함수)

PyErr_SetFromErrnoWithFilenameObject (C 함수)

PyErr_SetFromErrnoWithFilenameObjects (C 함수)

PyErr_SetFromWindowsErr (C 함수)

PyErr_SetFromWindowsErrWithFilename (C 함수)

PyErr_SetImportError (C 함수)

PyErr_SetImportErrorSubclass (C 함수)

PyErr_SetInterrupt (C 함수)

PyErr_SetNone (C 함수)

PyErr_SetObject (C 함수)

PyErr_SetString (C 함수)

PyErr_SetString()

PyErr_SyntaxLocation (C 함수)

PyErr_SyntaxLocationEx (C 함수)

PyErr_SyntaxLocationObject (C 함수)

PyErr_WarnEx (C 함수)

PyErr_WarnExplicit (C 함수)

PyErr_WarnExplicitObject (C 함수)

PyErr_WarnFormat (C 함수)

PyErr_WriteUnraisable (C 함수)

PyEval_AcquireLock (C 함수)

PyEval_AcquireThread (C 함수)

PyEval_AcquireThread()

PyEval_EvalCode (C 함수)

PyEval_EvalCodeEx (C 함수)

PyEval_EvalFrame (C 함수)

PyEval_EvalFrameEx (C 함수)

PyEval_GetBuiltins (C 함수)

PyEval_GetFrame (C 함수)

PyEval_GetFuncDesc (C 함수)

PyEval_GetFuncName (C 함수)

PyEval_GetGlobals (C 함수)

PyEval_GetLocals (C 함수)

PyEval_InitThreads (C 함수)

PyEval_InitThreads()

PyEval_MergeCompilerFlags (C 함수)

PyEval_ReInitThreads (C 함수)

PyEval_ReleaseLock (C 함수)

PyEval_ReleaseThread (C 함수)

PyEval_ReleaseThread()

PyEval_RestoreThread (C 함수)

PyEval_RestoreThread(), [1]

PyEval_SaveThread (C 함수)

PyEval_SaveThread(), [1]

PyEval_SetProfile (C 함수)

PyEval_SetTrace (C 함수)

PyEval_ThreadsInitialized (C 함수)

PyExc_ArithmeticError

PyExc_AssertionError

PyExc_AttributeError

PyExc_BaseException

PyExc_BlockingIOError

PyExc_BrokenPipeError

PyExc_BufferError

PyExc_BytesWarning

PyExc_ChildProcessError

PyExc_ConnectionAbortedError

PyExc_ConnectionError

PyExc_ConnectionRefusedError

PyExc_ConnectionResetError

PyExc_DeprecationWarning

PyExc_EnvironmentError

PyExc_EOFError

PyExc_Exception

PyExc_FileExistsError

PyExc_FileNotFoundError

PyExc_FloatingPointError

PyExc_FutureWarning

PyExc_GeneratorExit

PyExc_ImportError

PyExc_ImportWarning

PyExc_IndentationError

PyExc_IndexError

PyExc_InterruptedError

PyExc_IOError

PyExc_IsADirectoryError

PyExc_KeyboardInterrupt

PyExc_KeyError

PyExc_LookupError

PyExc_MemoryError

PyExc_ModuleNotFoundError

PyExc_NameError

PyExc_NotADirectoryError

PyExc_NotImplementedError

PyExc_OSError

PyExc_OverflowError

PyExc_PendingDeprecationWarning

PyExc_PermissionError

PyExc_ProcessLookupError

PyExc_RecursionError

PyExc_ReferenceError

PyExc_ResourceWarning

PyExc_RuntimeError

PyExc_RuntimeWarning

PyExc_StopAsyncIteration

PyExc_StopIteration

PyExc_SyntaxError

PyExc_SyntaxWarning

PyExc_SystemError

PyExc_SystemExit

PyExc_TabError

PyExc_TimeoutError

PyExc_TypeError

PyExc_UnboundLocalError

PyExc_UnicodeDecodeError

PyExc_UnicodeEncodeError

PyExc_UnicodeError

PyExc_UnicodeTranslateError

PyExc_UnicodeWarning

PyExc_UserWarning

PyExc_ValueError

PyExc_Warning

PyExc_WindowsError

PyExc_ZeroDivisionError

PyException_GetCause (C 함수)

PyException_GetContext (C 함수)

PyException_GetTraceback (C 함수)

PyException_SetCause (C 함수)

PyException_SetContext (C 함수)

PyException_SetTraceback (C 함수)

pyexpat

모듈

PyFile_FromFd (C 함수)

PyFile_GetLine (C 함수)

PyFile_WriteObject (C 함수)

PyFile_WriteString (C 함수)

PyFloat_AS_DOUBLE (C 함수)

PyFloat_AsDouble (C 함수)

PyFloat_Check (C 함수)

PyFloat_CheckExact (C 함수)

PyFloat_ClearFreeList (C 함수)

PyFloat_FromDouble (C 함수)

PyFloat_FromString (C 함수)

PyFloat_GetInfo (C 함수)

PyFloat_GetMax (C 함수)

PyFloat_GetMin (C 함수)

PyFloat_Type (C 변수)

PyFloatObject (C 데이터 형식)

PyFrame_GetLineNumber (C 함수)

PyFrameObject (C 데이터 형식)

PyFrozenSet_Check (C 함수)

PyFrozenSet_CheckExact (C 함수)

PyFrozenSet_New (C 함수)

PyFrozenSet_Type (C 변수)

PyFunction_Check (C 함수)

PyFunction_GetAnnotations (C 함수)

PyFunction_GetClosure (C 함수)

PyFunction_GetCode (C 함수)

PyFunction_GetDefaults (C 함수)

PyFunction_GetGlobals (C 함수)

PyFunction_GetModule (C 함수)

PyFunction_New (C 함수)

PyFunction_NewWithQualName (C 함수)

PyFunction_SetAnnotations (C 함수)

PyFunction_SetClosure (C 함수)

PyFunction_SetDefaults (C 함수)

PyFunction_Type (C 변수)

PyFunctionObject (C 데이터 형식)

PYFUNCTYPE() (ctypes 모듈)

PyGen_Check (C 함수)

PyGen_CheckExact (C 함수)

PyGen_New (C 함수)

PyGen_NewWithQualName (C 함수)

PyGen_Type (C 변수)

PyGenObject (C 데이터 형식)

PyGetSetDef (C 데이터 형식)

PyGILState_Check (C 함수)

PyGILState_Ensure (C 함수)

PyGILState_GetThisThreadState (C 함수)

PyGILState_Release (C 함수)

PyImport_AddModule (C 함수)

PyImport_AddModuleObject (C 함수)

PyImport_AppendInittab (C 함수)

PyImport_Cleanup (C 함수)

PyImport_ExecCodeModule (C 함수)

PyImport_ExecCodeModuleEx (C 함수)

PyImport_ExecCodeModuleObject (C 함수)

PyImport_ExecCodeModuleWithPathnames (C 함수)

PyImport_ExtendInittab (C 함수)

PyImport_FrozenModules (C 변수)

PyImport_GetImporter (C 함수)

PyImport_GetMagicNumber (C 함수)

PyImport_GetMagicTag (C 함수)

PyImport_GetModule (C 함수)

PyImport_GetModuleDict (C 함수)

PyImport_Import (C 함수)

PyImport_ImportFrozenModule (C 함수)

PyImport_ImportFrozenModuleObject (C 함수)

PyImport_ImportModule (C 함수)

PyImport_ImportModuleEx (C 함수)

PyImport_ImportModuleLevel (C 함수)

PyImport_ImportModuleLevelObject (C 함수)

PyImport_ImportModuleNoBlock (C 함수)

PyImport_ReloadModule (C 함수)

PyIndex_Check (C 함수)

PyInit_modulename (C 함수)

PyInstanceMethod_Check (C 함수)

PyInstanceMethod_Function (C 함수)

PyInstanceMethod_GET_FUNCTION (C 함수)

PyInstanceMethod_New (C 함수)

PyInstanceMethod_Type (C 변수)

PyInterpreterState (C 데이터 형식)

PyInterpreterState_Clear (C 함수)

PyInterpreterState_Delete (C 함수)

PyInterpreterState_GetID (C 함수)

PyInterpreterState_Head (C 함수)

PyInterpreterState_Main (C 함수)

PyInterpreterState_New (C 함수)

PyInterpreterState_Next (C 함수)

PyInterpreterState_ThreadHead (C 함수)

PyIter_Check (C 함수)

PyIter_Next (C 함수)

PyList_Append (C 함수)

PyList_AsTuple (C 함수)

PyList_Check (C 함수)

PyList_CheckExact (C 함수)

PyList_ClearFreeList (C 함수)

PyList_GET_ITEM (C 함수)

PyList_GET_SIZE (C 함수)

PyList_GetItem (C 함수)

PyList_GetItem()

PyList_GetSlice (C 함수)

PyList_Insert (C 함수)

PyList_New (C 함수)

PyList_Reverse (C 함수)

PyList_SET_ITEM (C 함수)

PyList_SetItem (C 함수)

PyList_SetItem()

PyList_SetSlice (C 함수)

PyList_Size (C 함수)

PyList_Sort (C 함수)

PyList_Type (C 변수)

PyListObject (C 데이터 형식)

PyLong_AsDouble (C 함수)

PyLong_AsLong (C 함수)

PyLong_AsLongAndOverflow (C 함수)

PyLong_AsLongLong (C 함수)

PyLong_AsLongLongAndOverflow (C 함수)

PyLong_AsSize_t (C 함수)

PyLong_AsSsize_t (C 함수)

PyLong_AsUnsignedLong (C 함수)

PyLong_AsUnsignedLongLong (C 함수)

PyLong_AsUnsignedLongLongMask (C 함수)

PyLong_AsUnsignedLongMask (C 함수)

PyLong_AsVoidPtr (C 함수)

PyLong_Check (C 함수)

PyLong_CheckExact (C 함수)

PyLong_FromDouble (C 함수)

PyLong_FromLong (C 함수)

PyLong_FromLongLong (C 함수)

PyLong_FromSize_t (C 함수)

PyLong_FromSsize_t (C 함수)

PyLong_FromString (C 함수)

PyLong_FromUnicode (C 함수)

PyLong_FromUnicodeObject (C 함수)

PyLong_FromUnsignedLong (C 함수)

PyLong_FromUnsignedLongLong (C 함수)

PyLong_FromVoidPtr (C 함수)

PyLong_Type (C 변수)

PyLongObject (C 데이터 형식)

PyMapping_Check (C 함수)

PyMapping_DelItem (C 함수)

PyMapping_DelItemString (C 함수)

PyMapping_GetItemString (C 함수)

PyMapping_HasKey (C 함수)

PyMapping_HasKeyString (C 함수)

PyMapping_Items (C 함수)

PyMapping_Keys (C 함수)

PyMapping_Length (C 함수)

PyMapping_SetItemString (C 함수)

PyMapping_Size (C 함수)

PyMapping_Values (C 함수)

PyMappingMethods (C 데이터 형식)

PyMappingMethods.mp_ass_subscript (C 멤버 변수)

PyMappingMethods.mp_length (C 멤버 변수)

PyMappingMethods.mp_subscript (C 멤버 변수)

PyMarshal_ReadLastObjectFromFile (C 함수)

PyMarshal_ReadLongFromFile (C 함수)

PyMarshal_ReadObjectFromFile (C 함수)

PyMarshal_ReadObjectFromString (C 함수)

PyMarshal_ReadShortFromFile (C 함수)

PyMarshal_WriteLongToFile (C 함수)

PyMarshal_WriteObjectToFile (C 함수)

PyMarshal_WriteObjectToString (C 함수)

PyMem_Calloc (C 함수)

PyMem_Del (C 함수)

PYMEM_DOMAIN_MEM (C 변수)

PYMEM_DOMAIN_OBJ (C 변수)

PYMEM_DOMAIN_RAW (C 변수)

PyMem_Free (C 함수)

PyMem_GetAllocator (C 함수)

PyMem_Malloc (C 함수)

PyMem_New (C 함수)

PyMem_RawCalloc (C 함수)

PyMem_RawFree (C 함수)

PyMem_RawMalloc (C 함수)

PyMem_RawRealloc (C 함수)

PyMem_Realloc (C 함수)

PyMem_Resize (C 함수)

PyMem_SetAllocator (C 함수)

PyMem_SetupDebugHooks (C 함수)

PyMemAllocatorDomain (C 데이터 형식)

PyMemAllocatorEx (C 데이터 형식)

PyMemberDef (C 데이터 형식)

PyMemoryView_Check (C 함수)

PyMemoryView_FromBuffer (C 함수)

PyMemoryView_FromMemory (C 함수)

PyMemoryView_FromObject (C 함수)

PyMemoryView_GET_BASE (C 함수)

PyMemoryView_GET_BUFFER (C 함수)

PyMemoryView_GetContiguous (C 함수)

PyMethod_Check (C 함수)

PyMethod_ClearFreeList (C 함수)

PyMethod_Function (C 함수)

PyMethod_GET_FUNCTION (C 함수)

PyMethod_GET_SELF (C 함수)

PyMethod_New (C 함수)

PyMethod_Self (C 함수)

PyMethod_Type (C 변수)

PyMethodDef (C 데이터 형식)

PyModule_AddFunctions (C 함수)

PyModule_AddIntConstant (C 함수)

PyModule_AddIntMacro (C 함수)

PyModule_AddObject (C 함수)

PyModule_AddStringConstant (C 함수)

PyModule_AddStringMacro (C 함수)

PyModule_Check (C 함수)

PyModule_CheckExact (C 함수)

PyModule_Create (C 함수)

PyModule_Create2 (C 함수)

PyModule_ExecDef (C 함수)

PyModule_FromDefAndSpec (C 함수)

PyModule_FromDefAndSpec2 (C 함수)

PyModule_GetDef (C 함수)

PyModule_GetDict (C 함수)

PyModule_GetFilename (C 함수)

PyModule_GetFilenameObject (C 함수)

PyModule_GetName (C 함수)

PyModule_GetNameObject (C 함수)

PyModule_GetState (C 함수)

PyModule_New (C 함수)

PyModule_NewObject (C 함수)

PyModule_SetDocString (C 함수)

PyModule_Type (C 변수)

PyModuleDef (C 데이터 형식)

PyModuleDef.m_base (C 멤버 변수)

PyModuleDef.m_clear (C 멤버 변수)

PyModuleDef.m_doc (C 멤버 변수)

PyModuleDef.m_free (C 멤버 변수)

PyModuleDef.m_methods (C 멤버 변수)

PyModuleDef.m_name (C 멤버 변수)

PyModuleDef.m_reload (C 멤버 변수)

PyModuleDef.m_size (C 멤버 변수)

PyModuleDef.m_slots (C 멤버 변수)

PyModuleDef.m_traverse (C 멤버 변수)

PyModuleDef_Init (C 함수)

PyModuleDef_Slot (C 데이터 형식)

PyModuleDef_Slot.slot (C 멤버 변수)

PyModuleDef_Slot.value (C 멤버 변수)

PyNumber_Absolute (C 함수)

PyNumber_Add (C 함수)

PyNumber_And (C 함수)

PyNumber_AsSsize_t (C 함수)

PyNumber_Check (C 함수)

PyNumber_Divmod (C 함수)

PyNumber_Float (C 함수)

PyNumber_FloorDivide (C 함수)

PyNumber_Index (C 함수)

PyNumber_InPlaceAdd (C 함수)

PyNumber_InPlaceAnd (C 함수)

PyNumber_InPlaceFloorDivide (C 함수)

PyNumber_InPlaceLshift (C 함수)

PyNumber_InPlaceMatrixMultiply (C 함수)

PyNumber_InPlaceMultiply (C 함수)

PyNumber_InPlaceOr (C 함수)

PyNumber_InPlacePower (C 함수)

PyNumber_InPlaceRemainder (C 함수)

PyNumber_InPlaceRshift (C 함수)

PyNumber_InPlaceSubtract (C 함수)

PyNumber_InPlaceTrueDivide (C 함수)

PyNumber_InPlaceXor (C 함수)

PyNumber_Invert (C 함수)

PyNumber_Long (C 함수)

PyNumber_Lshift (C 함수)

PyNumber_MatrixMultiply (C 함수)

PyNumber_Multiply (C 함수)

PyNumber_Negative (C 함수)

PyNumber_Or (C 함수)

PyNumber_Positive (C 함수)

PyNumber_Power (C 함수)

PyNumber_Remainder (C 함수)

PyNumber_Rshift (C 함수)

PyNumber_Subtract (C 함수)

PyNumber_ToBase (C 함수)

PyNumber_TrueDivide (C 함수)

PyNumber_Xor (C 함수)

PyNumberMethods (C 데이터 형식)

PyObject (C 데이터 형식)

PyObject._ob_next (C 멤버 변수)

PyObject._ob_prev (C 멤버 변수)

PyObject.ob_refcnt (C 멤버 변수)

PyObject.ob_type (C 멤버 변수)

PyObject_AsCharBuffer (C 함수)

PyObject_ASCII (C 함수)

PyObject_AsFileDescriptor (C 함수)

PyObject_AsReadBuffer (C 함수)

PyObject_AsWriteBuffer (C 함수)

PyObject_Bytes (C 함수)

PyObject_Call (C 함수)

PyObject_CallFunction (C 함수)

PyObject_CallFunctionObjArgs (C 함수)

PyObject_CallMethod (C 함수)

PyObject_CallMethodObjArgs (C 함수)

PyObject_CallObject (C 함수)

PyObject_CallObject()

PyObject_Calloc (C 함수)

PyObject_CheckBuffer (C 함수)

PyObject_CheckReadBuffer (C 함수)

PyObject_Del (C 함수)

PyObject_DelAttr (C 함수)

PyObject_DelAttrString (C 함수)

PyObject_DelItem (C 함수)

PyObject_Dir (C 함수)

PyObject_Free (C 함수)

PyObject_GC_Del (C 함수)

PyObject_GC_New (C 함수)

PyObject_GC_NewVar (C 함수)

PyObject_GC_Resize (C 함수)

PyObject_GC_Track (C 함수)

PyObject_GC_UnTrack (C 함수)

PyObject_GenericGetAttr (C 함수)

PyObject_GenericGetDict (C 함수)

PyObject_GenericSetAttr (C 함수)

PyObject_GenericSetDict (C 함수)

PyObject_GetArenaAllocator (C 함수)

PyObject_GetAttr (C 함수)

PyObject_GetAttrString (C 함수)

PyObject_GetBuffer (C 함수)

PyObject_GetItem (C 함수)

PyObject_GetIter (C 함수)

PyObject_HasAttr (C 함수)

PyObject_HasAttrString (C 함수)

PyObject_Hash (C 함수)

PyObject_HashNotImplemented (C 함수)

PyObject_HEAD (C 매크로)

PyObject_HEAD_INIT (C 매크로)

PyObject_Init (C 함수)

PyObject_InitVar (C 함수)

PyObject_IsInstance (C 함수)

PyObject_IsSubclass (C 함수)

PyObject_IsTrue (C 함수)

PyObject_Length (C 함수)

PyObject_LengthHint (C 함수)

PyObject_Malloc (C 함수)

PyObject_New (C 함수)

PyObject_NewVar (C 함수)

PyObject_Not (C 함수)

PyObject_Print (C 함수)

PyObject_Realloc (C 함수)

PyObject_Repr (C 함수)

PyObject_RichCompare (C 함수)

PyObject_RichCompareBool (C 함수)

PyObject_SetArenaAllocator (C 함수)

PyObject_SetAttr (C 함수)

PyObject_SetAttrString (C 함수)

PyObject_SetItem (C 함수)

PyObject_Size (C 함수)

PyObject_Str (C 함수)

PyObject_Type (C 함수)

PyObject_TypeCheck (C 함수)

PyObject_VAR_HEAD (C 매크로)

PyObjectArenaAllocator (C 데이터 형식)

PyOS_AfterFork (C 함수)

PyOS_AfterFork_Child (C 함수)

PyOS_AfterFork_Parent (C 함수)

PyOS_BeforeFork (C 함수)

PyOS_CheckStack (C 함수)

PyOS_double_to_string (C 함수)

PyOS_FSPath (C 함수)

PyOS_getsig (C 함수)

PyOS_InputHook (C 변수)

PyOS_ReadlineFunctionPointer (C 변수)

PyOS_setsig (C 함수)

PyOS_snprintf (C 함수)

PyOS_stricmp (C 함수)

PyOS_string_to_double (C 함수)

PyOS_strnicmp (C 함수)

PyOS_vsnprintf (C 함수)

PyParser_SimpleParseFile (C 함수)

PyParser_SimpleParseFileFlags (C 함수)

PyParser_SimpleParseString (C 함수)

PyParser_SimpleParseStringFlags (C 함수)

PyParser_SimpleParseStringFlagsFilename (C 함수)

PyPI

(see Python Package Index (PyPI))

PyProperty_Type (C 변수)

PyRun_AnyFile (C 함수)

PyRun_AnyFileEx (C 함수)

PyRun_AnyFileExFlags (C 함수)

PyRun_AnyFileFlags (C 함수)

PyRun_File (C 함수)

PyRun_FileEx (C 함수)

PyRun_FileExFlags (C 함수)

PyRun_FileFlags (C 함수)

PyRun_InteractiveLoop (C 함수)

PyRun_InteractiveLoopFlags (C 함수)

PyRun_InteractiveOne (C 함수)

PyRun_InteractiveOneFlags (C 함수)

PyRun_SimpleFile (C 함수)

PyRun_SimpleFileEx (C 함수)

PyRun_SimpleFileExFlags (C 함수)

PyRun_SimpleString (C 함수)

PyRun_SimpleStringFlags (C 함수)

PyRun_String (C 함수)

PyRun_StringFlags (C 함수)

PySeqIter_Check (C 함수)

PySeqIter_New (C 함수)

PySeqIter_Type (C 변수)

PySequence_Check (C 함수)

PySequence_Concat (C 함수)

PySequence_Contains (C 함수)

PySequence_Count (C 함수)

PySequence_DelItem (C 함수)

PySequence_DelSlice (C 함수)

PySequence_Fast (C 함수)

PySequence_Fast_GET_ITEM (C 함수)

PySequence_Fast_GET_SIZE (C 함수)

PySequence_Fast_ITEMS (C 함수)

PySequence_GetItem (C 함수)

PySequence_GetItem()

PySequence_GetSlice (C 함수)

PySequence_Index (C 함수)

PySequence_InPlaceConcat (C 함수)

PySequence_InPlaceRepeat (C 함수)

PySequence_ITEM (C 함수)

PySequence_Length (C 함수)

PySequence_List (C 함수)

PySequence_Repeat (C 함수)

PySequence_SetItem (C 함수)

PySequence_SetSlice (C 함수)

PySequence_Size (C 함수)

PySequence_Tuple (C 함수)

PySequenceMethods (C 데이터 형식)

PySequenceMethods.sq_ass_item (C 멤버 변수)

PySequenceMethods.sq_concat (C 멤버 변수)

PySequenceMethods.sq_contains (C 멤버 변수)

PySequenceMethods.sq_inplace_concat (C 멤버 변수)

PySequenceMethods.sq_inplace_repeat (C 멤버 변수)

PySequenceMethods.sq_item (C 멤버 변수)

PySequenceMethods.sq_length (C 멤버 변수)

PySequenceMethods.sq_repeat (C 멤버 변수)

PySet_Add (C 함수)

PySet_Check (C 함수)

PySet_Clear (C 함수)

PySet_ClearFreeList (C 함수)

PySet_Contains (C 함수)

PySet_Discard (C 함수)

PySet_GET_SIZE (C 함수)

PySet_New (C 함수)

PySet_Pop (C 함수)

PySet_Size (C 함수)

PySet_Type (C 변수)

PySetObject (C 데이터 형식)

PySignal_SetWakeupFd (C 함수)

PySlice_AdjustIndices (C 함수)

PySlice_Check (C 함수)

PySlice_GetIndices (C 함수)

PySlice_GetIndicesEx (C 함수)

PySlice_New (C 함수)

PySlice_Type (C 변수)

PySlice_Unpack (C 함수)

PyState_AddModule (C 함수)

PyState_FindModule (C 함수)

PyState_RemoveModule (C 함수)

PyStructSequence_Desc (C 데이터 형식)

PyStructSequence_Field (C 데이터 형식)

PyStructSequence_GET_ITEM (C 함수)

PyStructSequence_GetItem (C 함수)

PyStructSequence_InitType (C 함수)

PyStructSequence_InitType2 (C 함수)

PyStructSequence_New (C 함수)

PyStructSequence_NewType (C 함수)

PyStructSequence_SET_ITEM (C 함수)

PyStructSequence_SetItem (C 함수)

PyStructSequence_UnnamedField (C 변수)

PySys_AddWarnOption (C 함수)

PySys_AddWarnOptionUnicode (C 함수)

PySys_AddXOption (C 함수)

PySys_FormatStderr (C 함수)

PySys_FormatStdout (C 함수)

PySys_GetObject (C 함수)

PySys_GetXOptions (C 함수)

PySys_ResetWarnOptions (C 함수)

PySys_SetArgv (C 함수)

PySys_SetArgv()

PySys_SetArgvEx (C 함수)

PySys_SetArgvEx(), [1]

PySys_SetObject (C 함수)

PySys_SetPath (C 함수)

PySys_WriteStderr (C 함수)

PySys_WriteStdout (C 함수)

Python 3000 (파이썬 3000)

Python Editor

Python Package Index (PyPI)

PYTHON*, [1], [2], [3], [4], [5]

python.function.entry (C 함수)

python.function.return (C 함수)

python_branch() (platform 모듈)

python_build() (platform 모듈)

python_compiler() (platform 모듈)

PYTHON_DOM

python_implementation() (platform 모듈)

python_is_optimized() (test.support 모듈)

python_revision() (platform 모듈)

python_version() (platform 모듈)

python_version_tuple() (platform 모듈)

PYTHONASYNCIODEBUG, [1]

PYTHONBREAKPOINT, [1], [2], [3]

PYTHONCASEOK

PYTHONCOERCECLOCALE, [1]

PYTHONDEBUG, [1]

PYTHONDEVMODE, [1]

PYTHONDOCS

PYTHONDONTWRITEBYTECODE, [1], [2], [3], [4], [5]

PYTHONDUMPREFS

PYTHONFAULTHANDLER, [1]

PYTHONHASHSEED, [1], [2], [3], [4], [5], [6], [7], [8]

PYTHONHOME, [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12], [13], [14], [15]

Pythonic (파이썬다운)

PYTHONINSPECT, [1], [2]

PYTHONINTMAXSTRDIGITS, [1], [2], [3], [4]

PYTHONIOENCODING, [1], [2], [3], [4], [5], [6]

PYTHONLEGACYWINDOWSFSENCODING, [1], [2]

PYTHONLEGACYWINDOWSSTDIO, [1], [2], [3]

PYTHONMALLOC, [1], [2], [3], [4], [5], [6]

PYTHONMALLOCSTATS, [1]

PYTHONNOUSERSITE, [1], [2], [3]

PYTHONOPTIMIZE, [1]

PYTHONPATH, [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12], [13], [14], [15], [16], [17], [18], [19], [20], [21], [22], [23], [24]

PYTHONPROFILEIMPORTTIME, [1], [2]

PYTHONSHOWALLOCCOUNT

PYTHONSHOWREFCOUNT

PYTHONSTARTUP, [1], [2], [3], [4], [5], [6], [7], [8], [9]

PYTHONTRACEMALLOC, [1], [2]

PYTHONUNBUFFERED, [1]

PYTHONUSERBASE, [1], [2]

PYTHONUSERSITE

PYTHONUTF8, [1], [2], [3], [4]

PYTHONVERBOSE, [1]

PYTHONWARNINGS, [1], [2], [3], [4], [5], [6], [7]

PyThread_create_key (C 함수)

PyThread_delete_key (C 함수)

PyThread_delete_key_value (C 함수)

PyThread_get_key_value (C 함수)

PyThread_ReInitTLS (C 함수)

PyThread_set_key_value (C 함수)

PyThread_tss_alloc (C 함수)

PyThread_tss_create (C 함수)

PyThread_tss_delete (C 함수)

PyThread_tss_free (C 함수)

PyThread_tss_get (C 함수)

PyThread_tss_is_created (C 함수)

PyThread_tss_set (C 함수)

PyThreadState, [1]

(C 데이터 형식)

PyThreadState_Clear (C 함수)

PyThreadState_Delete (C 함수)

PyThreadState_Get (C 함수)

PyThreadState_GetDict (C 함수)

PyThreadState_New (C 함수)

PyThreadState_Next (C 함수)

PyThreadState_SetAsyncExc (C 함수)

PyThreadState_Swap (C 함수)

PyTime_Check (C 함수)

PyTime_CheckExact (C 함수)

PyTime_FromTime (C 함수)

PyTime_FromTimeAndFold (C 함수)

PyTimeZone_FromOffset (C 함수)

PyTimeZone_FromOffsetAndName (C 함수)

PyTrace_C_CALL (C 변수)

PyTrace_C_EXCEPTION (C 변수)

PyTrace_C_RETURN (C 변수)

PyTrace_CALL (C 변수)

PyTrace_EXCEPTION (C 변수)

PyTrace_LINE (C 변수)

PyTrace_OPCODE (C 변수)

PyTrace_RETURN (C 변수)

PyTraceMalloc_Track (C 함수)

PyTraceMalloc_Untrack (C 함수)

PyTuple_Check (C 함수)

PyTuple_CheckExact (C 함수)

PyTuple_ClearFreeList (C 함수)

PyTuple_GET_ITEM (C 함수)

PyTuple_GET_SIZE (C 함수)

PyTuple_GetItem (C 함수)

PyTuple_GetSlice (C 함수)

PyTuple_New (C 함수)

PyTuple_Pack (C 함수)

PyTuple_SET_ITEM (C 함수)

PyTuple_SetItem (C 함수)

PyTuple_SetItem()

PyTuple_Size (C 함수)

PyTuple_Type (C 변수)

PyTupleObject (C 데이터 형식)

PyType_Check (C 함수)

PyType_CheckExact (C 함수)

PyType_ClearCache (C 함수)

PyType_FromSpec (C 함수)

PyType_FromSpecWithBases (C 함수)

PyType_GenericAlloc (C 함수)

PyType_GenericNew (C 함수)

PyType_GetFlags (C 함수)

PyType_GetSlot (C 함수)

PyType_HasFeature (C 함수)

PyType_IS_GC (C 함수)

PyType_IsSubtype (C 함수)

PyType_Modified (C 함수)

PyType_Ready (C 함수)

PyType_Type (C 변수)

PyTypeObject (C 데이터 형식)

PyTypeObject.tp_alloc (C 멤버 변수)

PyTypeObject.tp_allocs (C 멤버 변수)

PyTypeObject.tp_as_buffer (C 멤버 변수)

PyTypeObject.tp_base (C 멤버 변수)

PyTypeObject.tp_bases (C 멤버 변수)

PyTypeObject.tp_basicsize (C 멤버 변수)

PyTypeObject.tp_cache (C 멤버 변수)

PyTypeObject.tp_call (C 멤버 변수)

PyTypeObject.tp_clear (C 멤버 변수)

PyTypeObject.tp_dealloc (C 멤버 변수)

PyTypeObject.tp_descr_get (C 멤버 변수)

PyTypeObject.tp_descr_set (C 멤버 변수)

PyTypeObject.tp_dict (C 멤버 변수)

PyTypeObject.tp_dictoffset (C 멤버 변수)

PyTypeObject.tp_doc (C 멤버 변수)

PyTypeObject.tp_finalize (C 멤버 변수)

PyTypeObject.tp_flags (C 멤버 변수)

PyTypeObject.tp_free (C 멤버 변수)

PyTypeObject.tp_frees (C 멤버 변수)

PyTypeObject.tp_getattr (C 멤버 변수)

PyTypeObject.tp_getattro (C 멤버 변수)

PyTypeObject.tp_getset (C 멤버 변수)

PyTypeObject.tp_hash (C 멤버 변수)

PyTypeObject.tp_init (C 멤버 변수)

PyTypeObject.tp_is_gc (C 멤버 변수)

PyTypeObject.tp_itemsize (C 멤버 변수)

PyTypeObject.tp_iter (C 멤버 변수)

PyTypeObject.tp_iternext (C 멤버 변수)

PyTypeObject.tp_maxalloc (C 멤버 변수)

PyTypeObject.tp_members (C 멤버 변수)

PyTypeObject.tp_methods (C 멤버 변수)

PyTypeObject.tp_mro (C 멤버 변수)

PyTypeObject.tp_name (C 멤버 변수)

PyTypeObject.tp_new (C 멤버 변수)

PyTypeObject.tp_next (C 멤버 변수)

PyTypeObject.tp_print (C 멤버 변수)

PyTypeObject.tp_repr (C 멤버 변수)

PyTypeObject.tp_richcompare (C 멤버 변수)

PyTypeObject.tp_setattr (C 멤버 변수)

PyTypeObject.tp_setattro (C 멤버 변수)

PyTypeObject.tp_str (C 멤버 변수)

PyTypeObject.tp_subclasses (C 멤버 변수)

PyTypeObject.tp_traverse (C 멤버 변수)

PyTypeObject.tp_weaklist (C 멤버 변수)

PyTypeObject.tp_weaklistoffset (C 멤버 변수)

PyTZInfo_Check (C 함수)

PyTZInfo_CheckExact (C 함수)

PyUnicode_1BYTE_DATA (C 함수)

PyUnicode_1BYTE_KIND (C 매크로)

PyUnicode_2BYTE_DATA (C 함수)

PyUnicode_2BYTE_KIND (C 매크로)

PyUnicode_4BYTE_DATA (C 함수)

PyUnicode_4BYTE_KIND (C 매크로)

PyUnicode_AS_DATA (C 함수)

PyUnicode_AS_UNICODE (C 함수)

PyUnicode_AsASCIIString (C 함수)

PyUnicode_AsCharmapString (C 함수)

PyUnicode_AsEncodedString (C 함수)

PyUnicode_AsLatin1String (C 함수)

PyUnicode_AsMBCSString (C 함수)

PyUnicode_AsRawUnicodeEscapeString (C 함수)

PyUnicode_AsUCS4 (C 함수)

PyUnicode_AsUCS4Copy (C 함수)

PyUnicode_AsUnicode (C 함수)

PyUnicode_AsUnicodeAndSize (C 함수)

PyUnicode_AsUnicodeCopy (C 함수)

PyUnicode_AsUnicodeEscapeString (C 함수)

PyUnicode_AsUTF16String (C 함수)

PyUnicode_AsUTF32String (C 함수)

PyUnicode_AsUTF8 (C 함수)

PyUnicode_AsUTF8AndSize (C 함수)

PyUnicode_AsUTF8String (C 함수)

PyUnicode_AsWideChar (C 함수)

PyUnicode_AsWideCharString (C 함수)

PyUnicode_Check (C 함수)

PyUnicode_CheckExact (C 함수)

PyUnicode_ClearFreeList (C 함수)

PyUnicode_Compare (C 함수)

PyUnicode_CompareWithASCIIString (C 함수)

PyUnicode_Concat (C 함수)

PyUnicode_Contains (C 함수)

PyUnicode_CopyCharacters (C 함수)

PyUnicode_Count (C 함수)

PyUnicode_DATA (C 함수)

PyUnicode_Decode (C 함수)

PyUnicode_DecodeASCII (C 함수)

PyUnicode_DecodeCharmap (C 함수)

PyUnicode_DecodeFSDefault (C 함수)

PyUnicode_DecodeFSDefaultAndSize (C 함수)

PyUnicode_DecodeLatin1 (C 함수)

PyUnicode_DecodeLocale (C 함수)

PyUnicode_DecodeLocaleAndSize (C 함수)

PyUnicode_DecodeMBCS (C 함수)

PyUnicode_DecodeMBCSStateful (C 함수)

PyUnicode_DecodeRawUnicodeEscape (C 함수)

PyUnicode_DecodeUnicodeEscape (C 함수)

PyUnicode_DecodeUTF16 (C 함수)

PyUnicode_DecodeUTF16Stateful (C 함수)

PyUnicode_DecodeUTF32 (C 함수)

PyUnicode_DecodeUTF32Stateful (C 함수)

PyUnicode_DecodeUTF7 (C 함수)

PyUnicode_DecodeUTF7Stateful (C 함수)

PyUnicode_DecodeUTF8 (C 함수)

PyUnicode_DecodeUTF8Stateful (C 함수)

PyUnicode_Encode (C 함수)

PyUnicode_EncodeASCII (C 함수)

PyUnicode_EncodeCharmap (C 함수)

PyUnicode_EncodeCodePage (C 함수)

PyUnicode_EncodeFSDefault (C 함수)

PyUnicode_EncodeLatin1 (C 함수)

PyUnicode_EncodeLocale (C 함수)

PyUnicode_EncodeMBCS (C 함수)

PyUnicode_EncodeRawUnicodeEscape (C 함수)

PyUnicode_EncodeUnicodeEscape (C 함수)

PyUnicode_EncodeUTF16 (C 함수)

PyUnicode_EncodeUTF32 (C 함수)

PyUnicode_EncodeUTF7 (C 함수)

PyUnicode_EncodeUTF8 (C 함수)

PyUnicode_Fill (C 함수)

PyUnicode_Find (C 함수)

PyUnicode_FindChar (C 함수)

PyUnicode_Format (C 함수)

PyUnicode_FromEncodedObject (C 함수)

PyUnicode_FromFormat (C 함수)

PyUnicode_FromFormatV (C 함수)

PyUnicode_FromKindAndData (C 함수)

PyUnicode_FromObject (C 함수)

PyUnicode_FromString (C 함수)

PyUnicode_FromString()

PyUnicode_FromStringAndSize (C 함수)

PyUnicode_FromUnicode (C 함수)

PyUnicode_FromWideChar (C 함수)

PyUnicode_FSConverter (C 함수)

PyUnicode_FSDecoder (C 함수)

PyUnicode_GET_DATA_SIZE (C 함수)

PyUnicode_GET_LENGTH (C 함수)

PyUnicode_GET_SIZE (C 함수)

PyUnicode_GetLength (C 함수)

PyUnicode_GetSize (C 함수)

PyUnicode_InternFromString (C 함수)

PyUnicode_InternInPlace (C 함수)

PyUnicode_Join (C 함수)

PyUnicode_KIND (C 함수)

PyUnicode_MAX_CHAR_VALUE (C 함수)

PyUnicode_New (C 함수)

PyUnicode_READ (C 함수)

PyUnicode_READ_CHAR (C 함수)

PyUnicode_ReadChar (C 함수)

PyUnicode_READY (C 함수)

PyUnicode_Replace (C 함수)

PyUnicode_RichCompare (C 함수)

PyUnicode_Split (C 함수)

PyUnicode_Splitlines (C 함수)

PyUnicode_Substring (C 함수)

PyUnicode_Tailmatch (C 함수)

PyUnicode_TransformDecimalToASCII (C 함수)

PyUnicode_Translate (C 함수), [1]

PyUnicode_TranslateCharmap (C 함수)

PyUnicode_Type (C 변수)

PyUnicode_WCHAR_KIND (C 매크로)

PyUnicode_WRITE (C 함수)

PyUnicode_WriteChar (C 함수)

PyUnicodeDecodeError_Create (C 함수)

PyUnicodeDecodeError_GetEncoding (C 함수)

PyUnicodeDecodeError_GetEnd (C 함수)

PyUnicodeDecodeError_GetObject (C 함수)

PyUnicodeDecodeError_GetReason (C 함수)

PyUnicodeDecodeError_GetStart (C 함수)

PyUnicodeDecodeError_SetEnd (C 함수)

PyUnicodeDecodeError_SetReason (C 함수)

PyUnicodeDecodeError_SetStart (C 함수)

PyUnicodeEncodeError_Create (C 함수)

PyUnicodeEncodeError_GetEncoding (C 함수)

PyUnicodeEncodeError_GetEnd (C 함수)

PyUnicodeEncodeError_GetObject (C 함수)

PyUnicodeEncodeError_GetReason (C 함수)

PyUnicodeEncodeError_GetStart (C 함수)

PyUnicodeEncodeError_SetEnd (C 함수)

PyUnicodeEncodeError_SetReason (C 함수)

PyUnicodeEncodeError_SetStart (C 함수)

PyUnicodeObject (C 데이터 형식)

PyUnicodeTranslateError_Create (C 함수)

PyUnicodeTranslateError_GetEnd (C 함수)

PyUnicodeTranslateError_GetObject (C 함수)

PyUnicodeTranslateError_GetReason (C 함수)

PyUnicodeTranslateError_GetStart (C 함수)

PyUnicodeTranslateError_SetEnd (C 함수)

PyUnicodeTranslateError_SetReason (C 함수)

PyUnicodeTranslateError_SetStart (C 함수)

PyVarObject (C 데이터 형식)

PyVarObject.ob_size (C 멤버 변수)

PyVarObject_HEAD_INIT (C 매크로)

PyWeakref_Check (C 함수)

PyWeakref_CheckProxy (C 함수)

PyWeakref_CheckRef (C 함수)

PyWeakref_GET_OBJECT (C 함수)

PyWeakref_GetObject (C 함수)

PyWeakref_NewProxy (C 함수)

PyWeakref_NewRef (C 함수)

PyWrapper_New (C 함수)

PyZipFile (zipfile 클래스)

Q

qiflush() (curses 모듈)

QName (xml.etree.ElementTree 클래스)

qsize() (asyncio.Queue 메서드)

(multiprocessing.Queue 메서드)

(queue.Queue 메서드)

(queue.SimpleQueue 메서드)

qualified name (정규화된 이름)

quantize() (decimal.Context 메서드)

(decimal.Decimal 메서드)

QueryInfoKey() (winreg 모듈)

QueryReflectionKey() (winreg 모듈)

QueryValue() (winreg 모듈)

QueryValueEx() (winreg 모듈)

Queue (asyncio 클래스)

(multiprocessing 클래스)

(queue 클래스)

queue (sched.scheduler의 속성)

(모듈)

Queue() (multiprocessing.managers.SyncManager 메서드)

QueueEmpty

QueueFull

QueueHandler (logging.handlers 클래스)

QueueListener (logging.handlers 클래스)

quick_ratio() (difflib.SequenceMatcher 메서드)

quit (pdb command)

(내장 변수)

quit() (ftplib.FTP 메서드)

(nntplib.NNTP 메서드)

(poplib.POP3 메서드)

(smtplib.SMTP 메서드)

quopri (모듈)

quote() (email.utils 모듈)

(shlex 모듈)

(urllib.parse 모듈)

QUOTE_ALL (csv 모듈)

quote_from_bytes() (urllib.parse 모듈)

QUOTE_MINIMAL (csv 모듈)

QUOTE_NONE (csv 모듈)

QUOTE_NONNUMERIC (csv 모듈)

quote_plus() (urllib.parse 모듈)

quoteattr() (xml.sax.saxutils 모듈)

quotechar (csv.Dialect의 속성)

quoted-printable

encoding

quotes (shlex.shlex의 속성)

quoting (csv.Dialect의 속성)

R

r"

raw string literal

r'

raw string literal

R_OK (os 모듈)

radians() (math 모듈)

(turtle 모듈)

RadioButtonGroup (msilib 클래스)

radiogroup() (msilib.Dialog 메서드)

radix() (decimal.Context 메서드)

(decimal.Decimal 메서드)

RADIXCHAR (locale 모듈)

raise

글, [1]

raise (2to3 fixer)

raise an exception

raise_on_defect (email.policy.Policy의 속성)

RAISE_VARARGS (opcode)

raising

exception

RAND_add() (ssl 모듈)

RAND_bytes() (ssl 모듈)

RAND_egd() (ssl 모듈)

RAND_pseudo_bytes() (ssl 모듈)

RAND_status() (ssl 모듈)

randbelow() (secrets 모듈)

randbits() (secrets 모듈)

randint() (random 모듈)

Random (random 클래스)

random (모듈)

random() (random 모듈)

randrange() (random 모듈)

range

객체

내장 함수

range (내장 클래스)

RARROW (token 모듈)

ratecv() (audioop 모듈)

ratio() (difflib.SequenceMatcher 메서드)

Rational (numbers 클래스)

raw (io.BufferedIOBase의 속성)

raw string

raw() (curses 모듈)

raw_data_manager (email.contentmanager 모듈)

raw_decode() (json.JSONDecoder 메서드)

raw_input (2to3 fixer)

raw_input() (code.InteractiveConsole 메서드)

RawArray() (multiprocessing.sharedctypes 모듈)

RawConfigParser (configparser 클래스)

RawDescriptionHelpFormatter (argparse 클래스)

RawIOBase (io 클래스)

RawPen (turtle 클래스)

RawTextHelpFormatter (argparse 클래스)

RawTurtle (turtle 클래스)

RawValue() (multiprocessing.sharedctypes 모듈)

RBRACE (token 모듈)

rcpttos (smtpd.SMTPChannel의 속성)

re

모듈, [1]

re (re.Match의 속성)

(모듈)

read() (asyncio.StreamReader의 메서드)

(chunk.Chunk 메서드)

(codecs.StreamReader 메서드)

(configparser.ConfigParser 메서드)

(http.client.HTTPResponse 메서드)

(imaplib.IMAP4 메서드)

(io.BufferedIOBase 메서드)

(io.BufferedReader 메서드)

(io.RawIOBase 메서드)

(io.TextIOBase 메서드)

(mimetypes.MimeTypes 메서드)

(mmap.mmap 메서드)

(os 모듈)

(ossaudiodev.oss_audio_device 메서드)

(ssl.MemoryBIO 메서드)

(ssl.SSLSocket 메서드)

(urllib.robotparser.RobotFileParser 메서드)

(zipfile.ZipFile 메서드)

read1() (io.BufferedIOBase 메서드)

(io.BufferedReader 메서드)

(io.BytesIO 메서드)

read_all() (telnetlib.Telnet 메서드)

read_binary() (importlib.resources 모듈)

read_byte() (mmap.mmap 메서드)

read_bytes() (pathlib.Path 메서드)

read_dict() (configparser.ConfigParser 메서드)

read_eager() (telnetlib.Telnet 메서드)

read_environ() (wsgiref.handlers 모듈)

read_events() (xml.etree.ElementTree.XMLPullParser 메서드)

read_file() (configparser.ConfigParser 메서드)

read_history_file() (readline 모듈)

read_init_file() (readline 모듈)

read_lazy() (telnetlib.Telnet 메서드)

read_mime_types() (mimetypes 모듈)

READ_RESTRICTED

read_sb_data() (telnetlib.Telnet 메서드)

read_some() (telnetlib.Telnet 메서드)

read_string() (configparser.ConfigParser 메서드)

read_text() (importlib.resources 모듈)

(pathlib.Path 메서드)

read_token() (shlex.shlex 메서드)

read_until() (telnetlib.Telnet 메서드)

read_very_eager() (telnetlib.Telnet 메서드)

read_very_lazy() (telnetlib.Telnet 메서드)

read_windows_registry() (mimetypes.MimeTypes 메서드)

READABLE (tkinter 모듈)

readable() (asyncore.dispatcher 메서드)

(io.IOBase 메서드)

readall() (io.RawIOBase 메서드)

reader() (csv 모듈)

ReadError

readexactly() (asyncio.StreamReader의 메서드)

readfp() (configparser.ConfigParser 메서드)

(mimetypes.MimeTypes 메서드)

readframes() (aifc.aifc 메서드)

(sunau.AU_read 메서드)

(wave.Wave_read 메서드)

readinto() (http.client.HTTPResponse 메서드)

(io.BufferedIOBase 메서드)

(io.RawIOBase 메서드)

readinto1() (io.BufferedIOBase 메서드)

(io.BytesIO 메서드)

readline (모듈)

readline() (asyncio.StreamReader의 메서드)

(codecs.StreamReader 메서드)

(distutils.text_file.TextFile 메서드)

(imaplib.IMAP4 메서드)

(io.IOBase 메서드)

(io.TextIOBase 메서드)

(mmap.mmap 메서드)

readlines() (codecs.StreamReader 메서드)

(distutils.text_file.TextFile 메서드)

(io.IOBase 메서드)

readlink() (os 모듈)

readmodule() (pyclbr 모듈)

readmodule_ex() (pyclbr 모듈)

READONLY

readonly (memoryview의 속성)

readPlist() (plistlib 모듈)

readPlistFromBytes() (plistlib 모듈)

ReadTransport (asyncio 클래스)

readuntil() (asyncio.StreamReader의 메서드)

readv() (os 모듈)

ready() (multiprocessing.pool.AsyncResult 메서드)

Real (numbers 클래스)

real (numbers.Complex의 속성)

Real Media File Format

real_max_memuse (test.support 모듈)

real_quick_ratio() (difflib.SequenceMatcher 메서드)

realloc()

realpath() (os.path 모듈)

REALTIME_PRIORITY_CLASS (subprocess 모듈)

reap_children() (test.support 모듈)

reap_threads() (test.support 모듈)

reason (http.client.HTTPResponse의 속성)

(ssl.SSLError의 속성)

(UnicodeError의 속성)

(urllib.error.HTTPError의 속성)

(urllib.error.URLError의 속성)

reattach() (tkinter.ttk.Treeview 메서드)

rebinding

name

reccontrols() (ossaudiodev.oss_mixer_device 메서드)

received_data (smtpd.SMTPChannel의 속성)

received_lines (smtpd.SMTPChannel의 속성)

recent() (imaplib.IMAP4 메서드)

reconfigure() (io.TextIOWrapper 메서드)

record_original_stdout() (test.support 모듈)

records (unittest.TestCase의 속성)

rect() (cmath 모듈)

rectangle() (curses.textpad 모듈)

RecursionError

recursive_repr() (reprlib 모듈)

recv() (asyncore.dispatcher 메서드)

(multiprocessing.connection.Connection 메서드)

(socket.socket 메서드)

recv_bytes() (multiprocessing.connection.Connection 메서드)

recv_bytes_into() (multiprocessing.connection.Connection 메서드)

recv_into() (socket.socket 메서드)

recvfrom() (socket.socket 메서드)

recvfrom_into() (socket.socket 메서드)

recvmsg() (socket.socket 메서드)

recvmsg_into() (socket.socket 메서드)

redirect_request() (urllib.request.HTTPRedirectHandler 메서드)

redirect_stderr() (contextlib 모듈)

redirect_stdout() (contextlib 모듈)

redisplay() (readline 모듈)

redrawln() (curses.window 메서드)

redrawwin() (curses.window 메서드)

reduce (2to3 fixer)

reduce() (functools 모듈)

ref (weakref 클래스)

refcount_test() (test.support 모듈)

reference

attribute

reference count (참조 횟수)

reference counting

ReferenceError

ReferenceType (weakref 모듈)

refold_source (email.policy.EmailPolicy의 속성)

refresh() (curses.window 메서드)

REG_BINARY (winreg 모듈)

REG_DWORD (winreg 모듈)

REG_DWORD_BIG_ENDIAN (winreg 모듈)

REG_DWORD_LITTLE_ENDIAN (winreg 모듈)

REG_EXPAND_SZ (winreg 모듈)

REG_FULL_RESOURCE_DESCRIPTOR (winreg 모듈)

REG_LINK (winreg 모듈)

REG_MULTI_SZ (winreg 모듈)

REG_NONE (winreg 모듈)

REG_QWORD (winreg 모듈)

REG_QWORD_LITTLE_ENDIAN (winreg 모듈)

REG_RESOURCE_LIST (winreg 모듈)

REG_RESOURCE_REQUIREMENTS_LIST (winreg 모듈)

REG_SZ (winreg 모듈)

register() (abc.ABCMeta 메서드)

(atexit 모듈)

(codecs 모듈)

(faulthandler 모듈)

(multiprocessing.managers.BaseManager 메서드)

(select.devpoll 메서드)

(select.epoll 메서드)

(select.poll 메서드)

(selectors.BaseSelector의 메서드)

(webbrowser 모듈)

register_adapter() (sqlite3 모듈)

register_archive_format() (shutil 모듈)

register_at_fork() (os 모듈)

register_converter() (sqlite3 모듈)

register_defect() (email.policy.Policy 메서드)

register_dialect() (csv 모듈)

register_error() (codecs 모듈)

register_function() (xmlrpc.server.CGIXMLRPCRequestHandler 메서드)

(xmlrpc.server.SimpleXMLRPCServer 메서드)

register_instance() (xmlrpc.server.CGIXMLRPCRequestHandler 메서드)

(xmlrpc.server.SimpleXMLRPCServer 메서드)

register_introspection_functions() (xmlrpc.server.CGIXMLRPCRequestHandler 메서드)

(xmlrpc.server.SimpleXMLRPCServer 메서드)

register_multicall_functions() (xmlrpc.server.CGIXMLRPCRequestHandler 메서드)

(xmlrpc.server.SimpleXMLRPCServer 메서드)

register_namespace() (xml.etree.ElementTree 모듈)

register_optionflag() (doctest 모듈)

register_shape() (turtle 모듈)

register_unpack_format() (shutil 모듈)

registerDOMImplementation() (xml.dom 모듈)

registerResult() (unittest 모듈)

regular

package

regular package (정규 패키지)

relative

import

URL

relative_to() (pathlib.PurePath 메서드)

release() (_thread.lock 메서드)

(asyncio.Condition 메서드)

(asyncio.Lock 메서드)

(asyncio.Semaphore 메서드)

(logging.Handler 메서드)

(memoryview 메서드)

(multiprocessing.Lock 메서드)

(multiprocessing.RLock 메서드)

(platform 모듈)

(threading.Condition 메서드)

(threading.Lock 메서드)

(threading.RLock 메서드)

(threading.Semaphore 메서드)

release_lock() (imp 모듈)

reload (2to3 fixer)

reload() (imp 모듈)

(importlib 모듈)

relpath() (os.path 모듈)

remainder() (decimal.Context 메서드)

(math 모듈)

remainder_near() (decimal.Context 메서드)

(decimal.Decimal 메서드)

RemoteDisconnected

remove() (array.array 메서드)

(collections.deque 메서드)

(frozenset 메서드)

(mailbox.Mailbox 메서드)

(mailbox.MH 메서드)

(os 모듈)

(sequence method)

(xml.etree.ElementTree.Element 메서드)

remove_child_handler() (asyncio.AbstractChildWatcher 메서드)

remove_done_callback() (asyncio.Future 메서드)

(asyncio.Task 메서드)

remove_flag() (mailbox.MaildirMessage 메서드)

(mailbox.mboxMessage 메서드)

(mailbox.MMDFMessage 메서드)

remove_folder() (mailbox.Maildir 메서드)

(mailbox.MH 메서드)

remove_header() (urllib.request.Request 메서드)

remove_history_item() (readline 모듈)

remove_label() (mailbox.BabylMessage 메서드)

remove_option() (configparser.ConfigParser 메서드)

(optparse.OptionParser 메서드)

remove_pyc() (msilib.Directory 메서드)

remove_reader() (asyncio.loop 메서드)

remove_section() (configparser.ConfigParser 메서드)

remove_sequence() (mailbox.MHMessage 메서드)

remove_signal_handler() (asyncio.loop 메서드)

remove_tree() (distutils.dir_util 모듈)

remove_writer() (asyncio.loop 메서드)

removeAttribute() (xml.dom.Element 메서드)

removeAttributeNode() (xml.dom.Element 메서드)

removeAttributeNS() (xml.dom.Element 메서드)

removeChild() (xml.dom.Node 메서드)

removedirs() (os 모듈)

removeFilter() (logging.Handler 메서드)

(logging.Logger 메서드)

removeHandler() (logging.Logger 메서드)

(unittest 모듈)

removeResult() (unittest 모듈)

removexattr() (os 모듈)

rename() (ftplib.FTP 메서드)

(imaplib.IMAP4 메서드)

(os 모듈)

(pathlib.Path 메서드)

renames (2to3 fixer)

renames() (os 모듈)

reopenIfNeeded() (logging.handlers.WatchedFileHandler 메서드)

reorganize() (dbm.gnu.gdbm 메서드)

repeat() (itertools 모듈)

(timeit 모듈)

(timeit.Timer 메서드)

repetition

operation

replace() (bytearray 메서드)

(bytes 메서드)

(curses.panel.Panel 메서드)

(dataclasses 모듈)

(datetime.date 메서드)

(datetime.datetime 메서드)

(datetime.time 메서드)

(inspect.Parameter 메서드)

(inspect.Signature 메서드)

(os 모듈)

(pathlib.Path 메서드)

(str 메서드)

replace_errors() (codecs 모듈)

replace_header() (email.message.EmailMessage 메서드)

(email.message.Message 메서드)

replace_history_item() (readline 모듈)

replace_whitespace (textwrap.TextWrapper의 속성)

replaceChild() (xml.dom.Node 메서드)

ReplacePackage() (modulefinder 모듈)

report() (filecmp.dircmp 메서드)

(modulefinder.ModuleFinder 메서드)

REPORT_CDIFF (doctest 모듈)

report_failure() (doctest.DocTestRunner 메서드)

report_full_closure() (filecmp.dircmp 메서드)

REPORT_NDIFF (doctest 모듈)

REPORT_ONLY_FIRST_FAILURE (doctest 모듈)

report_partial_closure() (filecmp.dircmp 메서드)

report_start() (doctest.DocTestRunner 메서드)

report_success() (doctest.DocTestRunner 메서드)

REPORT_UDIFF (doctest 모듈)

report_unexpected_exception() (doctest.DocTestRunner 메서드)

REPORTING_FLAGS (doctest 모듈)

repr

내장 함수, [1], [2], [3]

repr (2to3 fixer)

Repr (reprlib 클래스)

repr() (built-in function)

__repr__() (object method)

repr() (reprlib 모듈)

(reprlib.Repr 메서드)

(내장 함수)

repr1() (reprlib.Repr 메서드)

representation

integer

reprlib (모듈)

Request (urllib.request 클래스)

request() (http.client.HTTPConnection 메서드)

request_queue_size (socketserver.BaseServer의 속성)

request_rate() (urllib.robotparser.RobotFileParser 메서드)

request_uri() (wsgiref.util 모듈)

request_version (http.server.BaseHTTPRequestHandler의 속성)

RequestHandlerClass (socketserver.BaseServer의 속성)

requestline (http.server.BaseHTTPRequestHandler의 속성)

requires() (test.support 모듈)

requires_bz2() (test.support 모듈)

requires_docstrings() (test.support 모듈)

requires_freebsd_version() (test.support 모듈)

requires_gzip() (test.support 모듈)

requires_IEEE_754() (test.support 모듈)

requires_linux_version() (test.support 모듈)

requires_lzma() (test.support 모듈)

requires_mac_version() (test.support 모듈)

requires_resource() (test.support 모듈)

requires_zlib() (test.support 모듈)

reserved (zipfile.ZipInfo의 속성)

reserved word

RESERVED_FUTURE (uuid 모듈)

RESERVED_MICROSOFT (uuid 모듈)

RESERVED_NCS (uuid 모듈)

reset() (bdb.Bdb 메서드)

(codecs.IncrementalDecoder 메서드)

(codecs.IncrementalEncoder 메서드)

(codecs.StreamReader 메서드)

(codecs.StreamWriter 메서드)

(contextvars.ContextVar 메서드)

(html.parser.HTMLParser 메서드)

(ossaudiodev.oss_audio_device 메서드)

(pipes.Template 메서드)

(threading.Barrier 메서드)

(turtle 모듈), [1]

(xdrlib.Packer 메서드)

(xdrlib.Unpacker 메서드)

(xml.dom.pulldom.DOMEventStream 메서드)

(xml.sax.xmlreader.IncrementalParser 메서드)

reset_mock() (unittest.mock.Mock 메서드)

reset_prog_mode() (curses 모듈)

reset_shell_mode() (curses 모듈)

resetbuffer() (code.InteractiveConsole 메서드)

resetlocale() (locale 모듈)

resetscreen() (turtle 모듈)

resetty() (curses 모듈)

resetwarnings() (warnings 모듈)

resize() (ctypes 모듈)

(curses.window 메서드)

(mmap.mmap 메서드)

resize_term() (curses 모듈)

resizemode() (turtle 모듈)

resizeterm() (curses 모듈)

resolution (datetime.datetime의 속성)

(datetime.date의 속성)

(datetime.timedelta의 속성)

(datetime.time의 속성)

resolve() (pathlib.Path 메서드)

resolve_bases() (types 모듈)

resolve_name() (importlib.util 모듈)

resolveEntity() (xml.sax.handler.EntityResolver 메서드)

Resource (importlib.resources 모듈)

resource (모듈)

resource_path() (importlib.abc.ResourceReader의 메서드)

ResourceDenied

ResourceLoader (importlib.abc 클래스)

ResourceReader (importlib.abc 클래스)

ResourceWarning

response (nntplib.NNTPError의 속성)

response() (imaplib.IMAP4 메서드)

ResponseNotReady

responses (http.client 모듈)

(http.server.BaseHTTPRequestHandler의 속성)

restart (pdb command)

restore() (difflib 모듈)

RESTRICTED

restricted

execution

restype (ctypes._FuncPtr의 속성)

result() (asyncio.Future 메서드)

(asyncio.Task 메서드)

(concurrent.futures.Future 메서드)

results() (trace.Trace 메서드)

resume_reading() (asyncio.ReadTransport 메서드)

resume_writing() (asyncio.BaseProtocol 메서드)

retr() (poplib.POP3 메서드)

retrbinary() (ftplib.FTP 메서드)

retrieve() (urllib.request.URLopener 메서드)

retrlines() (ftplib.FTP 메서드)

return

글, [1], [2]

return (pdb command)

return_annotation (inspect.Signature의 속성)

return_ok() (http.cookiejar.CookiePolicy 메서드)

RETURN_VALUE (opcode)

return_value (unittest.mock.Mock의 속성)

returncode (asyncio.asyncio.subprocess.Process의 속성)

(subprocess.CalledProcessError의 속성)

(subprocess.CompletedProcess의 속성)

(subprocess.Popen의 속성)

retval (pdb command)

reverse() (array.array 메서드)

(audioop 모듈)

(collections.deque 메서드)

(sequence method)

reverse_order() (pstats.Stats 메서드)

reverse_pointer (ipaddress.IPv4Address의 속성)

(ipaddress.IPv6Address의 속성)

reversed() (내장 함수)

Reversible (collections.abc 클래스)

(typing 클래스)

revert() (http.cookiejar.FileCookieJar 메서드)

rewind() (aifc.aifc 메서드)

(sunau.AU_read 메서드)

(wave.Wave_read 메서드)

RFC

RFC 1014, [1]

RFC 1123

RFC 1321

RFC 1422, [1]

RFC 1521, [1], [2]

RFC 1522, [1], [2]

RFC 1524, [1]

RFC 1730

RFC 1738

RFC 1750

RFC 1766, [1]

RFC 1808, [1], [2]

RFC 1832, [1]

RFC 1869, [1]

RFC 1870, [1], [2]

RFC 1939, [1]

RFC 2033

RFC 2045, [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12], [13], [14]

RFC 2045#section-6.8

RFC 2046, [1], [2]

RFC 2047, [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12]

RFC 2060, [1]

RFC 2068

RFC 2104, [1]

RFC 2109, [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12], [13], [14]

RFC 2183, [1], [2]

RFC 2231, [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12], [13], [14]

RFC 2295

RFC 2342, [1]

RFC 2368

RFC 2373, [1], [2]

RFC 2396, [1], [2], [3], [4]

RFC 2397

RFC 2449

RFC 2487

RFC 2518

RFC 2595, [1]

RFC 2616, [1], [2], [3], [4], [5], [6], [7], [8], [9]

RFC 2732, [1], [2]

RFC 2774

RFC 2818, [1]

RFC 2821

RFC 2822, [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12], [13], [14], [15], [16], [17]

RFC 2964

RFC 2965, [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12], [13], [14], [15], [16], [17], [18], [19]

RFC 2980, [1]

RFC 3056

RFC 3171

RFC 3207

RFC 3229

RFC 3280

RFC 3330

RFC 3339

RFC 3454, [1]

RFC 3490, [1], [2], [3]

RFC 3490#section-3.1

RFC 3492, [1]

RFC 3493

RFC 3501

RFC 3542, [1]

RFC 3548, [1], [2], [3], [4], [5]

RFC 3659

RFC 3879

RFC 3927

RFC 3977, [1], [2], [3], [4]

RFC 3986, [1], [2], [3], [4], [5], [6], [7]

RFC 4086

RFC 4122, [1], [2], [3], [4], [5], [6], [7], [8]

RFC 4180

RFC 4193

RFC 4217

RFC 4291

RFC 4380

RFC 4627, [1]

RFC 4642

RFC 4918, [1], [2], [3], [4]

RFC 4954, [1]

RFC 5161, [1]

RFC 5233, [1]

RFC 5246, [1]

RFC 5280, [1], [2], [3], [4]

RFC 5321, [1], [2], [3], [4]

RFC 5322, [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12], [13], [14], [15], [16], [17], [18], [19], [20], [21]

RFC 5424, [1], [2], [3]

RFC 5424#section-6

RFC 5735

RFC 5842, [1]

RFC 5929

RFC 6066, [1], [2]

RFC 6125, [1]

RFC 6152, [1]

RFC 6531, [1], [2], [3], [4], [5], [6], [7], [8]

RFC 6532, [1], [2], [3], [4]

RFC 6585, [1], [2], [3]

RFC 6855, [1], [2], [3]

RFC 6856, [1]

RFC 7159, [1], [2]

RFC 7230, [1]

RFC 7231, [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12], [13], [14], [15], [16], [17], [18], [19], [20], [21], [22], [23], [24], [25], [26], [27], [28], [29], [30], [31], [32], [33], [34]

RFC 7232, [1]

RFC 7233, [1]

RFC 7235, [1]

RFC 7238

RFC 7301, [1], [2]

RFC 7525

RFC 7540

RFC 7693

RFC 7914

RFC 821, [1]

RFC 822, [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11]

RFC 854, [1]

RFC 959, [1]

RFC 977

rfc2109 (http.cookiejar.Cookie의 속성)

rfc2109_as_netscape (http.cookiejar.DefaultCookiePolicy의 속성)

rfc2965 (http.cookiejar.CookiePolicy의 속성)

rfc822_escape() (distutils.util 모듈)

RFC_4122 (uuid 모듈)

rfile (http.server.BaseHTTPRequestHandler의 속성)

rfind() (bytearray 메서드)

(bytes 메서드)

(mmap.mmap 메서드)

(str 메서드)

rgb_to_hls() (colorsys 모듈)

rgb_to_hsv() (colorsys 모듈)

rgb_to_yiq() (colorsys 모듈)

rglob() (pathlib.Path 메서드)

right (filecmp.dircmp의 속성)

right() (turtle 모듈)

right_list (filecmp.dircmp의 속성)

right_only (filecmp.dircmp의 속성)

RIGHTSHIFT (token 모듈)

RIGHTSHIFTEQUAL (token 모듈)

rindex() (bytearray 메서드)

(bytes 메서드)

(str 메서드)

rjust() (bytearray 메서드)

(bytes 메서드)

(str 메서드)

rlcompleter (모듈)

rlecode_hqx() (binascii 모듈)

rledecode_hqx() (binascii 모듈)

RLIM_INFINITY (resource 모듈)

RLIMIT_AS (resource 모듈)

RLIMIT_CORE (resource 모듈)

RLIMIT_CPU (resource 모듈)

RLIMIT_DATA (resource 모듈)

RLIMIT_FSIZE (resource 모듈)

RLIMIT_MEMLOCK (resource 모듈)

RLIMIT_MSGQUEUE (resource 모듈)

RLIMIT_NICE (resource 모듈)

RLIMIT_NOFILE (resource 모듈)

RLIMIT_NPROC (resource 모듈)

RLIMIT_NPTS (resource 모듈)

RLIMIT_OFILE (resource 모듈)

RLIMIT_RSS (resource 모듈)

RLIMIT_RTPRIO (resource 모듈)

RLIMIT_RTTIME (resource 모듈)

RLIMIT_SBSIZE (resource 모듈)

RLIMIT_SIGPENDING (resource 모듈)

RLIMIT_STACK (resource 모듈)

RLIMIT_SWAP (resource 모듈)

RLIMIT_VMEM (resource 모듈)

RLock (multiprocessing 클래스)

(threading 클래스)

RLock() (multiprocessing.managers.SyncManager 메서드)

rmd() (ftplib.FTP 메서드)

rmdir() (os 모듈)

(pathlib.Path 메서드)

(test.support 모듈)

RMFF

rms() (audioop 모듈)

rmtree() (shutil 모듈)

(test.support 모듈)

RobotFileParser (urllib.robotparser 클래스)

robots.txt

rollback() (sqlite3.Connection 메서드)

ROT_THREE (opcode)

ROT_TWO (opcode)

rotate() (collections.deque 메서드)

(decimal.Context 메서드)

(decimal.Decimal 메서드)

(logging.handlers.BaseRotatingHandler 메서드)

RotatingFileHandler (logging.handlers 클래스)

rotation_filename() (logging.handlers.BaseRotatingHandler 메서드)

rotator (logging.handlers.BaseRotatingHandler의 속성)

round

내장 함수

round() (내장 함수)

ROUND_05UP (decimal 모듈)

ROUND_CEILING (decimal 모듈)

ROUND_DOWN (decimal 모듈)

ROUND_FLOOR (decimal 모듈)

ROUND_HALF_DOWN (decimal 모듈)

ROUND_HALF_EVEN (decimal 모듈)

ROUND_HALF_UP (decimal 모듈)

ROUND_UP (decimal 모듈)

Rounded (decimal 클래스)

Row (sqlite3 클래스)

row_factory (sqlite3.Connection의 속성)

rowcount (sqlite3.Cursor의 속성)

RPAR (token 모듈)

rpartition() (bytearray 메서드)

(bytes 메서드)

(str 메서드)

rpc_paths (xmlrpc.server.SimpleXMLRPCRequestHandler의 속성)

rpop() (poplib.POP3 메서드)

rset() (poplib.POP3 메서드)

rshift() (operator 모듈)

rsplit() (bytearray 메서드)

(bytes 메서드)

(str 메서드)

RSQB (token 모듈)

rstrip() (bytearray 메서드)

(bytes 메서드)

(str 메서드)

rt() (turtle 모듈)

RTLD_DEEPBIND (os 모듈)

RTLD_GLOBAL (os 모듈)

RTLD_LAZY (os 모듈)

RTLD_LOCAL (os 모듈)

RTLD_NODELETE (os 모듈)

RTLD_NOLOAD (os 모듈)

RTLD_NOW (os 모듈)

ruler (cmd.Cmd의 속성)

run (pdb command)

Run script

run() (asyncio 모듈)

(bdb.Bdb 메서드)

(contextvars.Context 메서드)

(distutils.cmd.Command 메서드)

(doctest.DocTestRunner 메서드)

(multiprocessing.Process 메서드)

(pdb 모듈)

(pdb.Pdb 메서드)

(profile 모듈)

(profile.Profile 메서드)

(sched.scheduler 메서드)

(subprocess 모듈)

(test.support.BasicTestRunner 메서드)

(threading.Thread 메서드)

(trace.Trace 메서드)

(unittest.TestCase 메서드)

(unittest.TestSuite 메서드)

(unittest.TextTestRunner 메서드)

(wsgiref.handlers.BaseHandler 메서드)

run_coroutine_threadsafe() (asyncio 모듈)

run_docstring_examples() (doctest 모듈)

run_doctest() (test.support 모듈)

run_forever() (asyncio.loop 메서드)

run_in_executor() (asyncio.loop의 메서드)

run_in_subinterp() (test.support 모듈)

run_module() (runpy 모듈)

run_path() (runpy 모듈)

run_python_until_end() (test.support.script_helper 모듈)

run_script() (modulefinder.ModuleFinder 메서드)

run_setup() (distutils.core 모듈)

run_unittest() (test.support 모듈)

run_until_complete() (asyncio.loop 메서드)

run_with_locale() (test.support 모듈)

run_with_tz() (test.support 모듈)

runcall() (bdb.Bdb 메서드)

(pdb 모듈)

(pdb.Pdb 메서드)

(profile.Profile 메서드)

runcode() (code.InteractiveInterpreter 메서드)

runctx() (bdb.Bdb 메서드)

(profile 모듈)

(profile.Profile 메서드)

(trace.Trace 메서드)

runeval() (bdb.Bdb 메서드)

(pdb 모듈)

(pdb.Pdb 메서드)

runfunc() (trace.Trace 메서드)

running() (concurrent.futures.Future 메서드)

runpy (모듈)

runsource() (code.InteractiveInterpreter 메서드)

runtime_library_dir_option() (distutils.ccompiler.CCompiler 메서드)

RuntimeError

RuntimeWarning

RUSAGE_BOTH (resource 모듈)

RUSAGE_CHILDREN (resource 모듈)

RUSAGE_SELF (resource 모듈)

RUSAGE_THREAD (resource 모듈)

RWF_DSYNC (os 모듈)

RWF_HIPRI (os 모듈)

RWF_NOWAIT (os 모듈)

RWF_SYNC (os 모듈)

S

S (re 모듈)

S_ENFMT (stat 모듈)

S_IEXEC (stat 모듈)

S_IFBLK (stat 모듈)

S_IFCHR (stat 모듈)

S_IFDIR (stat 모듈)

S_IFDOOR (stat 모듈)

S_IFIFO (stat 모듈)

S_IFLNK (stat 모듈)

S_IFMT() (stat 모듈)

S_IFPORT (stat 모듈)

S_IFREG (stat 모듈)

S_IFSOCK (stat 모듈)

S_IFWHT (stat 모듈)

S_IMODE() (stat 모듈)

S_IREAD (stat 모듈)

S_IRGRP (stat 모듈)

S_IROTH (stat 모듈)

S_IRUSR (stat 모듈)

S_IRWXG (stat 모듈)

S_IRWXO (stat 모듈)

S_IRWXU (stat 모듈)

S_ISBLK() (stat 모듈)

S_ISCHR() (stat 모듈)

S_ISDIR() (stat 모듈)

S_ISDOOR() (stat 모듈)

S_ISFIFO() (stat 모듈)

S_ISGID (stat 모듈)

S_ISLNK() (stat 모듈)

S_ISPORT() (stat 모듈)

S_ISREG() (stat 모듈)

S_ISSOCK() (stat 모듈)

S_ISUID (stat 모듈)

S_ISVTX (stat 모듈)

S_ISWHT() (stat 모듈)

S_IWGRP (stat 모듈)

S_IWOTH (stat 모듈)

S_IWRITE (stat 모듈)

S_IWUSR (stat 모듈)

S_IXGRP (stat 모듈)

S_IXOTH (stat 모듈)

S_IXUSR (stat 모듈)

safe (uuid.SafeUUID의 속성)

safe_substitute() (string.Template 메서드)

SafeChildWatcher (asyncio 클래스)

saferepr() (pprint 모듈)

SafeUUID (uuid 클래스)

same_files (filecmp.dircmp의 속성)

same_quantum() (decimal.Context 메서드)

(decimal.Decimal 메서드)

samefile() (os.path 모듈)

(pathlib.Path 메서드)

SameFileError

sameopenfile() (os.path 모듈)

samestat() (os.path 모듈)

sample() (random 모듈)

save() (http.cookiejar.FileCookieJar 메서드)

SAVEDCWD (test.support 모듈)

SaveKey() (winreg 모듈)

SaveSignals (test.support 클래스)

savetty() (curses 모듈)

SAX2DOM (xml.dom.pulldom 클래스)

SAXException

SAXNotRecognizedException

SAXNotSupportedException

SAXParseException

scaleb() (decimal.Context 메서드)

(decimal.Decimal 메서드)

scandir() (os 모듈)

scanf()

sched (모듈)

SCHED_BATCH (os 모듈)

SCHED_FIFO (os 모듈)

sched_get_priority_max() (os 모듈)

sched_get_priority_min() (os 모듈)

sched_getaffinity() (os 모듈)

sched_getparam() (os 모듈)

sched_getscheduler() (os 모듈)

SCHED_IDLE (os 모듈)

SCHED_OTHER (os 모듈)

sched_param (os 클래스)

sched_priority (os.sched_param의 속성)

SCHED_RESET_ON_FORK (os 모듈)

SCHED_RR (os 모듈)

sched_rr_get_interval() (os 모듈)

sched_setaffinity() (os 모듈)

sched_setparam() (os 모듈)

sched_setscheduler() (os 모듈)

SCHED_SPORADIC (os 모듈)

sched_yield() (os 모듈)

scheduler (sched 클래스)

schema (msilib 모듈)

scope, [1]

Screen (turtle 클래스)

screensize() (turtle 모듈)

script_from_examples() (doctest 모듈)

scroll() (curses.window 메서드)

ScrolledCanvas (turtle 클래스)

scrollok() (curses.window 메서드)

scrypt() (hashlib 모듈)

sdterr

stdin stdout

seal() (unittest.mock 모듈)

search

path, module, [1], [2], [3], [4], [5], [6], [7]

search() (imaplib.IMAP4 메서드)

(re 모듈)

(re.Pattern 메서드)

second (datetime.datetime의 속성)

(datetime.time의 속성)

seconds since the epoch

secrets (모듈)

SECTCRE (configparser.ConfigParser의 속성)

sections() (configparser.ConfigParser 메서드)

secure (http.cookiejar.Cookie의 속성)

secure hash algorithm, SHA1, SHA224, SHA256, SHA384, SHA512

Secure Sockets Layer

security

CGI

http.server

see() (tkinter.ttk.Treeview 메서드)

seed() (random 모듈)

seek() (chunk.Chunk 메서드)

(io.IOBase 메서드)

(io.TextIOBase 메서드)

(mmap.mmap 메서드)

SEEK_CUR (os 모듈)

SEEK_END (os 모듈)

SEEK_SET (os 모듈)

seekable() (io.IOBase 메서드)

seen_greeting (smtpd.SMTPChannel의 속성)

Select (tkinter.tix 클래스)

select (모듈)

select() (imaplib.IMAP4 메서드)

(select 모듈)

(selectors.BaseSelector의 메서드)

(tkinter.ttk.Notebook 메서드)

selected_alpn_protocol() (ssl.SSLSocket 메서드)

selected_npn_protocol() (ssl.SSLSocket 메서드)

selection() (tkinter.ttk.Treeview 메서드)

selection_add() (tkinter.ttk.Treeview 메서드)

selection_remove() (tkinter.ttk.Treeview 메서드)

selection_set() (tkinter.ttk.Treeview 메서드)

selection_toggle() (tkinter.ttk.Treeview 메서드)

selector (urllib.request.Request의 속성)

SelectorEventLoop (asyncio 클래스)

SelectorKey (selectors 클래스)

selectors (모듈)

SelectSelector (selectors 클래스)

Semaphore (asyncio 클래스)

(multiprocessing 클래스)

(threading 클래스)

Semaphore() (multiprocessing.managers.SyncManager 메서드)

semaphores, binary

SEMI (token 모듈)

send() (asyncore.dispatcher 메서드)

(coroutine 메서드)

(generator 메서드)

(http.client.HTTPConnection 메서드)

(imaplib.IMAP4 메서드)

(logging.handlers.DatagramHandler 메서드)

(logging.handlers.SocketHandler 메서드)

(multiprocessing.connection.Connection 메서드)

(socket.socket 메서드)

send_bytes() (multiprocessing.connection.Connection 메서드)

send_error() (http.server.BaseHTTPRequestHandler 메서드)

send_flowing_data() (formatter.writer 메서드)

send_header() (http.server.BaseHTTPRequestHandler 메서드)

send_hor_rule() (formatter.writer 메서드)

send_label_data() (formatter.writer 메서드)

send_line_break() (formatter.writer 메서드)

send_literal_data() (formatter.writer 메서드)

send_message() (smtplib.SMTP 메서드)

send_paragraph() (formatter.writer 메서드)

send_response() (http.server.BaseHTTPRequestHandler 메서드)

send_response_only() (http.server.BaseHTTPRequestHandler 메서드)

send_signal() (asyncio.asyncio.subprocess.Process 메서드)

(asyncio.SubprocessTransport 메서드)

(subprocess.Popen 메서드)

sendall() (socket.socket 메서드)

sendcmd() (ftplib.FTP 메서드)

sendfile() (asyncio.loop의 메서드)

(os 모듈)

(socket.socket 메서드)

(wsgiref.handlers.BaseHandler 메서드)

SendfileNotAvailableError

sendmail() (smtplib.SMTP 메서드)

sendmsg() (socket.socket 메서드)

sendmsg_afalg() (socket.socket 메서드)

sendto() (asyncio.DatagramTransport 메서드)

(socket.socket 메서드)

sentinel (multiprocessing.Process의 속성)

(unittest.mock 모듈)

sep (os 모듈)

sequence

item

iteration

types, immutable

types, mutable

types, operations on, [1]

객체, [1], [2], [3], [4], [5], [6], [7], [8]

Sequence (collections.abc 클래스)

sequence (msilib 모듈)

Sequence (typing 클래스)

sequence (시퀀스)

sequence2st() (parser 모듈)

SequenceMatcher (difflib 클래스), [1]

serializing

objects

serve_forever() (asyncio.Server의 메서드)

(socketserver.BaseServer 메서드)

server

WWW, [1]

Server (asyncio 클래스)

server (http.server.BaseHTTPRequestHandler의 속성)

server_activate() (socketserver.BaseServer 메서드)

server_address (socketserver.BaseServer의 속성)

server_bind() (socketserver.BaseServer 메서드)

server_close() (socketserver.BaseServer 메서드)

server_hostname (ssl.SSLSocket의 속성)

server_side (ssl.SSLSocket의 속성)

server_software (wsgiref.handlers.BaseHandler의 속성)

server_version (http.server.BaseHTTPRequestHandler의 속성)

(http.server.SimpleHTTPRequestHandler의 속성)

ServerProxy (xmlrpc.client 클래스)

service_actions() (socketserver.BaseServer 메서드)

session (ssl.SSLSocket의 속성)

session_reused (ssl.SSLSocket의 속성)

session_stats() (ssl.SSLContext 메서드)

set

display

객체, [1], [2], [3]

Set (collections.abc 클래스)

(typing 클래스)

set (내장 클래스)

Set Breakpoint

set type

객체

set() (asyncio.Event 메서드)

(configparser.ConfigParser 메서드)

(configparser.RawConfigParser 메서드)

(contextvars.ContextVar 메서드)

(http.cookies.Morsel 메서드)

(ossaudiodev.oss_mixer_device 메서드)

(test.support.EnvironmentVarGuard 메서드)

(threading.Event 메서드)

(tkinter.ttk.Combobox 메서드)

(tkinter.ttk.Spinbox 메서드)

(tkinter.ttk.Treeview 메서드)

(xml.etree.ElementTree.Element 메서드)

SET_ADD (opcode)

set_all()

set_allowed_domains() (http.cookiejar.DefaultCookiePolicy 메서드)

set_alpn_protocols() (ssl.SSLContext 메서드)

set_app() (wsgiref.simple_server.WSGIServer 메서드)

set_asyncgen_hooks() (sys 모듈)

set_authorizer() (sqlite3.Connection 메서드)

set_auto_history() (readline 모듈)

set_blocked_domains() (http.cookiejar.DefaultCookiePolicy 메서드)

set_blocking() (os 모듈)

set_boundary() (email.message.EmailMessage 메서드)

(email.message.Message 메서드)

set_break() (bdb.Bdb 메서드)

set_charset() (email.message.Message 메서드)

set_child_watcher() (asyncio 모듈)

(asyncio.AbstractEventLoopPolicy 메서드)

set_children() (tkinter.ttk.Treeview 메서드)

set_ciphers() (ssl.SSLContext 메서드)

set_completer() (readline 모듈)

set_completer_delims() (readline 모듈)

set_completion_display_matches_hook() (readline 모듈)

set_content() (email.contentmanager 모듈)

(email.contentmanager.ContentManager 메서드)

(email.message.EmailMessage 메서드)

set_continue() (bdb.Bdb 메서드)

set_cookie() (http.cookiejar.CookieJar 메서드)

set_cookie_if_ok() (http.cookiejar.CookieJar 메서드)

set_coroutine_origin_tracking_depth() (sys 모듈)

set_coroutine_wrapper() (sys 모듈)

set_current() (msilib.Feature 메서드)

set_data() (importlib.abc.SourceLoader 메서드)

(importlib.machinery.SourceFileLoader 메서드)

set_date() (mailbox.MaildirMessage 메서드)

set_debug() (asyncio.loop 메서드)

(gc 모듈)

set_debuglevel() (ftplib.FTP 메서드)

(http.client.HTTPConnection 메서드)

(nntplib.NNTP 메서드)

(poplib.POP3 메서드)

(smtplib.SMTP 메서드)

(telnetlib.Telnet 메서드)

set_default_executor() (asyncio.loop 메서드)

set_default_type() (email.message.EmailMessage 메서드)

(email.message.Message 메서드)

set_default_verify_paths() (ssl.SSLContext 메서드)

set_defaults() (argparse.ArgumentParser 메서드)

(optparse.OptionParser 메서드)

set_ecdh_curve() (ssl.SSLContext 메서드)

set_errno() (ctypes 모듈)

set_event_loop() (asyncio 모듈)

(asyncio.AbstractEventLoopPolicy 메서드)

set_event_loop_policy() (asyncio 모듈)

set_exception() (asyncio.Future 메서드)

(concurrent.futures.Future 메서드)

set_exception_handler() (asyncio.loop 메서드)

set_executable() (multiprocessing 모듈)

set_executables() (distutils.ccompiler.CCompiler 메서드)

set_flags() (mailbox.MaildirMessage 메서드)

(mailbox.mboxMessage 메서드)

(mailbox.MMDFMessage 메서드)

set_from() (mailbox.mboxMessage 메서드)

(mailbox.MMDFMessage 메서드)

set_handle_inheritable() (os 모듈)

set_history_length() (readline 모듈)

set_include_dirs() (distutils.ccompiler.CCompiler 메서드)

set_info() (mailbox.MaildirMessage 메서드)

set_inheritable() (os 모듈)

(socket.socket 메서드)

set_int_max_str_digits() (sys 모듈)

set_labels() (mailbox.BabylMessage 메서드)

set_last_error() (ctypes 모듈)

set_libraries() (distutils.ccompiler.CCompiler 메서드)

set_library_dirs() (distutils.ccompiler.CCompiler 메서드)

set_link_objects() (distutils.ccompiler.CCompiler 메서드)

set_literal (2to3 fixer)

set_loader() (importlib.util 모듈)

set_match_tests() (test.support 모듈)

set_memlimit() (test.support 모듈)

set_next() (bdb.Bdb 메서드)

set_nonstandard_attr() (http.cookiejar.Cookie 메서드)

set_npn_protocols() (ssl.SSLContext 메서드)

set_ok() (http.cookiejar.CookiePolicy 메서드)

set_option_negotiation_callback() (telnetlib.Telnet 메서드)

set_output_charset() (gettext.NullTranslations 메서드)

set_package() (importlib.util 모듈)

set_param() (email.message.EmailMessage 메서드)

(email.message.Message 메서드)

set_pasv() (ftplib.FTP 메서드)

set_payload() (email.message.Message 메서드)

set_policy() (http.cookiejar.CookieJar 메서드)

set_position() (xdrlib.Unpacker 메서드)

set_pre_input_hook() (readline 모듈)

set_progress_handler() (sqlite3.Connection 메서드)

set_protocol() (asyncio.BaseTransport 메서드)

set_proxy() (urllib.request.Request 메서드)

set_python_build() (distutils.sysconfig 모듈)

set_quit() (bdb.Bdb 메서드)

set_recsrc() (ossaudiodev.oss_mixer_device 메서드)

set_result() (asyncio.Future 메서드)

(concurrent.futures.Future 메서드)

set_return() (bdb.Bdb 메서드)

set_running_or_notify_cancel() (concurrent.futures.Future 메서드)

set_runtime_library_dirs() (distutils.ccompiler.CCompiler 메서드)

set_seq1() (difflib.SequenceMatcher 메서드)

set_seq2() (difflib.SequenceMatcher 메서드)

set_seqs() (difflib.SequenceMatcher 메서드)

set_sequences() (mailbox.MH 메서드)

(mailbox.MHMessage 메서드)

set_server_documentation() (xmlrpc.server.DocCGIXMLRPCRequestHandler 메서드)

(xmlrpc.server.DocXMLRPCServer 메서드)

set_server_name() (xmlrpc.server.DocCGIXMLRPCRequestHandler 메서드)

(xmlrpc.server.DocXMLRPCServer 메서드)

set_server_title() (xmlrpc.server.DocCGIXMLRPCRequestHandler 메서드)

(xmlrpc.server.DocXMLRPCServer 메서드)

set_servername_callback (ssl.SSLContext의 속성)

set_spacing() (formatter.formatter 메서드)

set_start_method() (multiprocessing 모듈)

set_startup_hook() (readline 모듈)

set_step() (bdb.Bdb 메서드)

set_subdir() (mailbox.MaildirMessage 메서드)

set_task_factory() (asyncio.loop 메서드)

set_terminator() (asynchat.async_chat 메서드)

set_threshold() (gc 모듈)

set_trace() (bdb 모듈)

(bdb.Bdb 메서드)

(pdb 모듈)

(pdb.Pdb 메서드)

set_trace_callback() (sqlite3.Connection 메서드)

set_tunnel() (http.client.HTTPConnection 메서드)

set_type() (email.message.Message 메서드)

set_unittest_reportflags() (doctest 모듈)

set_unixfrom() (email.message.EmailMessage 메서드)

(email.message.Message 메서드)

set_until() (bdb.Bdb 메서드)

set_url() (urllib.robotparser.RobotFileParser 메서드)

set_usage() (optparse.OptionParser 메서드)

set_userptr() (curses.panel.Panel 메서드)

set_visible() (mailbox.BabylMessage 메서드)

set_wakeup_fd() (signal 모듈)

set_write_buffer_limits() (asyncio.WriteTransport 메서드)

setacl() (imaplib.IMAP4 메서드)

setannotation() (imaplib.IMAP4 메서드)

setattr() (내장 함수)

setAttribute() (xml.dom.Element 메서드)

setAttributeNode() (xml.dom.Element 메서드)

setAttributeNodeNS() (xml.dom.Element 메서드)

setAttributeNS() (xml.dom.Element 메서드)

SetBase() (xml.parsers.expat.xmlparser 메서드)

setblocking() (socket.socket 메서드)

setByteStream() (xml.sax.xmlreader.InputSource 메서드)

setcbreak() (tty 모듈)

setCharacterStream() (xml.sax.xmlreader.InputSource 메서드)

setcheckinterval() (sys 모듈)

setcomptype() (aifc.aifc 메서드)

(sunau.AU_write 메서드)

(wave.Wave_write 메서드)

setContentHandler() (xml.sax.xmlreader.XMLReader 메서드)

setcontext() (decimal 모듈)

setDaemon() (threading.Thread 메서드)

setdefault() (dict 메서드)

(http.cookies.Morsel 메서드)

setdefaulttimeout() (socket 모듈)

setdlopenflags() (sys 모듈)

setDocumentLocator() (xml.sax.handler.ContentHandler 메서드)

setDTDHandler() (xml.sax.xmlreader.XMLReader 메서드)

setegid() (os 모듈)

setEncoding() (xml.sax.xmlreader.InputSource 메서드)

setEntityResolver() (xml.sax.xmlreader.XMLReader 메서드)

setErrorHandler() (xml.sax.xmlreader.XMLReader 메서드)

seteuid() (os 모듈)

setFeature() (xml.sax.xmlreader.XMLReader 메서드)

setfirstweekday() (calendar 모듈)

setfmt() (ossaudiodev.oss_audio_device 메서드)

setFormatter() (logging.Handler 메서드)

setframerate() (aifc.aifc 메서드)

(sunau.AU_write 메서드)

(wave.Wave_write 메서드)

setgid() (os 모듈)

setgroups() (os 모듈)

seth() (turtle 모듈)

setheading() (turtle 모듈)

sethostname() (socket 모듈)

SetInteger() (msilib.Record 메서드)

setitem() (operator 모듈)

setitimer() (signal 모듈)

setLevel() (logging.Handler 메서드)

(logging.Logger 메서드)

setlocale() (locale 모듈)

setLocale() (xml.sax.xmlreader.XMLReader 메서드)

setLoggerClass() (logging 모듈)

setlogmask() (syslog 모듈)

setLogRecordFactory() (logging 모듈)

setmark() (aifc.aifc 메서드)

setMaxConns() (urllib.request.CacheFTPHandler 메서드)

setmode() (msvcrt 모듈)

setName() (threading.Thread 메서드)

setnchannels() (aifc.aifc 메서드)

(sunau.AU_write 메서드)

(wave.Wave_write 메서드)

setnframes() (aifc.aifc 메서드)

(sunau.AU_write 메서드)

(wave.Wave_write 메서드)

SetParamEntityParsing() (xml.parsers.expat.xmlparser 메서드)

setparameters() (ossaudiodev.oss_audio_device 메서드)

setparams() (aifc.aifc 메서드)

(sunau.AU_write 메서드)

(wave.Wave_write 메서드)

setpassword() (zipfile.ZipFile 메서드)

setpgid() (os 모듈)

setpgrp() (os 모듈)

setpos() (aifc.aifc 메서드)

(sunau.AU_read 메서드)

(turtle 모듈)

(wave.Wave_read 메서드)

setposition() (turtle 모듈)

setpriority() (os 모듈)

setprofile() (sys 모듈)

(threading 모듈)

SetProperty() (msilib.SummaryInformation 메서드)

setProperty() (xml.sax.xmlreader.XMLReader 메서드)

setPublicId() (xml.sax.xmlreader.InputSource 메서드)

setquota() (imaplib.IMAP4 메서드)

setraw() (tty 모듈)

setrecursionlimit() (sys 모듈)

setregid() (os 모듈)

setresgid() (os 모듈)

setresuid() (os 모듈)

setreuid() (os 모듈)

setrlimit() (resource 모듈)

setsampwidth() (aifc.aifc 메서드)

(sunau.AU_write 메서드)

(wave.Wave_write 메서드)

setscrreg() (curses.window 메서드)

setsid() (os 모듈)

setsockopt() (socket.socket 메서드), [1], [2]

setstate() (codecs.IncrementalDecoder 메서드)

(codecs.IncrementalEncoder 메서드)

(random 모듈)

setStream() (logging.StreamHandler 메서드)

SetStream() (msilib.Record 메서드)

SetString() (msilib.Record 메서드)

setswitchinterval() (in module sys)

(sys 모듈)

(test.support 모듈)

setSystemId() (xml.sax.xmlreader.InputSource 메서드)

setsyx() (curses 모듈)

setTarget() (logging.handlers.MemoryHandler 메서드)

settiltangle() (turtle 모듈)

settimeout() (socket.socket 메서드)

setTimeout() (urllib.request.CacheFTPHandler 메서드)

settrace() (sys 모듈)

(threading 모듈)

setuid() (os 모듈)

setundobuffer() (turtle 모듈)

setup() (distutils.core 모듈)

(socketserver.BaseRequestHandler 메서드)

(turtle 모듈)

setUp() (unittest.TestCase 메서드)

SETUP_ANNOTATIONS (opcode)

SETUP_ASYNC_WITH (opcode)

setup_environ() (wsgiref.handlers.BaseHandler 메서드)

SETUP_EXCEPT (opcode)

SETUP_FINALLY (opcode)

SETUP_LOOP (opcode)

setup_python() (venv.EnvBuilder 메서드)

setup_scripts() (venv.EnvBuilder 메서드)

setup_testing_defaults() (wsgiref.util 모듈)

SETUP_WITH (opcode)

setUpClass() (unittest.TestCase 메서드)

setupterm() (curses 모듈)

SetValue() (winreg 모듈)

SetValueEx() (winreg 모듈)

setworldcoordinates() (turtle 모듈)

setx() (turtle 모듈)

setxattr() (os 모듈)

sety() (turtle 모듈)

SF_APPEND (stat 모듈)

SF_ARCHIVED (stat 모듈)

SF_IMMUTABLE (stat 모듈)

SF_MNOWAIT (os 모듈)

SF_NODISKIO (os 모듈)

SF_NOUNLINK (stat 모듈)

SF_SNAPSHOT (stat 모듈)

SF_SYNC (os 모듈)

shape (memoryview의 속성)

Shape (turtle 클래스)

shape() (turtle 모듈)

shapesize() (turtle 모듈)

shapetransform() (turtle 모듈)

share() (socket.socket 메서드)

shared_ciphers() (ssl.SSLSocket 메서드)

shared_object_filename() (distutils.ccompiler.CCompiler 메서드)

shearfactor() (turtle 모듈)

Shelf (shelve 클래스)

shelve

모듈

shelve (모듈)

shift() (decimal.Context 메서드)

(decimal.Decimal 메서드)

shift_path_info() (wsgiref.util 모듈)

shifting

operation

operations

shlex (shlex 클래스)

(모듈)

shortDescription() (unittest.TestCase 메서드)

shorten() (textwrap 모듈)

shouldFlush() (logging.handlers.BufferingHandler 메서드)

(logging.handlers.MemoryHandler 메서드)

shouldStop (unittest.TestResult의 속성)

show() (curses.panel.Panel 메서드)

show_code() (dis 모듈)

show_compilers() (distutils.ccompiler 모듈)

showsyntaxerror() (code.InteractiveInterpreter 메서드)

showtraceback() (code.InteractiveInterpreter 메서드)

showturtle() (turtle 모듈)

showwarning() (warnings 모듈)

shuffle() (random 모듈)

shutdown() (concurrent.futures.Executor 메서드)

(imaplib.IMAP4 메서드)

(logging 모듈)

(multiprocessing.managers.BaseManager 메서드)

(socket.socket 메서드)

(socketserver.BaseServer 메서드)

shutdown_asyncgens() (asyncio.loop의 메서드)

shutil (모듈)

side_effect (unittest.mock.Mock의 속성)

SIG_BLOCK (signal 모듈)

SIG_DFL (signal 모듈)

SIG_IGN (signal 모듈)

SIG_SETMASK (signal 모듈)

SIG_UNBLOCK (signal 모듈)

SIGABRT (signal 모듈)

SIGALRM (signal 모듈)

SIGBREAK (signal 모듈)

SIGBUS (signal 모듈)

SIGCHLD (signal 모듈)

SIGCLD (signal 모듈)

SIGCONT (signal 모듈)

SIGFPE (signal 모듈)

SIGHUP (signal 모듈)

SIGILL (signal 모듈)

SIGINT, [1]

(signal 모듈)

siginterrupt() (signal 모듈)

SIGKILL (signal 모듈)

signal

모듈, [1]

signal (모듈)

signal() (signal 모듈)

Signature (inspect 클래스)

signature (inspect.BoundArguments의 속성)

signature() (inspect 모듈)

sigpending() (signal 모듈)

SIGPIPE (signal 모듈)

SIGSEGV (signal 모듈)

SIGTERM (signal 모듈)

sigtimedwait() (signal 모듈)

SIGUSR1 (signal 모듈)

SIGUSR2 (signal 모듈)

sigwait() (signal 모듈)

sigwaitinfo() (signal 모듈)

SIGWINCH (signal 모듈)

simple

statement

Simple Mail Transfer Protocol

SimpleCookie (http.cookies 클래스)

simplefilter() (warnings 모듈)

SimpleHandler (wsgiref.handlers 클래스)

SimpleHTTPRequestHandler (http.server 클래스)

SimpleNamespace (types 클래스)

SimpleQueue (multiprocessing 클래스)

(queue 클래스)

SimpleXMLRPCRequestHandler (xmlrpc.server 클래스)

SimpleXMLRPCServer (xmlrpc.server 클래스)

sin() (cmath 모듈)

(math 모듈)

single dispatch (싱글 디스패치)

SingleAddressHeader (email.headerregistry 클래스)

singledispatch() (functools 모듈)

singleton

tuple

sinh() (cmath 모듈)

(math 모듈)

SIO_KEEPALIVE_VALS (socket 모듈)

SIO_LOOPBACK_FAST_PATH (socket 모듈)

SIO_RCVALL (socket 모듈)

site (모듈)

site command line option

--user-base

--user-site

site-packages

directory

sitecustomize

모듈

sixtofour (ipaddress.IPv6Address의 속성)

size (struct.Struct의 속성)

(tarfile.TarInfo의 속성)

(tracemalloc.StatisticDiff의 속성)

(tracemalloc.Statistic의 속성)

(tracemalloc.Trace의 속성)

size() (ftplib.FTP 메서드)

(mmap.mmap 메서드)

size_diff (tracemalloc.StatisticDiff의 속성)

SIZE_MAX

Sized (collections.abc 클래스)

(typing 클래스)

sizeof() (ctypes 모듈)

SKIP (doctest 모듈)

skip() (chunk.Chunk 메서드)

(unittest 모듈)

skip_unless_bind_unix_socket() (test.support 모듈)

skip_unless_symlink() (test.support 모듈)

skip_unless_xattr() (test.support 모듈)

skipIf() (unittest 모듈)

skipinitialspace (csv.Dialect의 속성)

skipped (unittest.TestResult의 속성)

skippedEntity() (xml.sax.handler.ContentHandler 메서드)

SkipTest

skipTest() (unittest.TestCase 메서드)

skipUnless() (unittest 모듈)

SLASH (token 모듈)

SLASHEQUAL (token 모듈)

slave() (nntplib.NNTP 메서드)

sleep() (asyncio 모듈)

(time 모듈)

slice

assignment

operation

객체

내장 함수, [1]

slice (내장 클래스)

(슬라이스)

slicing, [1], [2]

assignment

SMALLEST (test.support 모듈)

SMTP

protocol

SMTP (email.policy 모듈)

(smtplib 클래스)

smtp_server (smtpd.SMTPChannel의 속성)

SMTP_SSL (smtplib 클래스)

smtp_state (smtpd.SMTPChannel의 속성)

SMTPAuthenticationError

SMTPChannel (smtpd 클래스)

SMTPConnectError

smtpd (모듈)

SMTPDataError

SMTPException

SMTPHandler (logging.handlers 클래스)

SMTPHeloError

smtplib (모듈)

SMTPNotSupportedError

SMTPRecipientsRefused

SMTPResponseException

SMTPSenderRefused

SMTPServer (smtpd 클래스)

SMTPServerDisconnected

SMTPUTF8 (email.policy 모듈)

Snapshot (tracemalloc 클래스)

SND_ALIAS (winsound 모듈)

SND_ASYNC (winsound 모듈)

SND_FILENAME (winsound 모듈)

SND_LOOP (winsound 모듈)

SND_MEMORY (winsound 모듈)

SND_NODEFAULT (winsound 모듈)

SND_NOSTOP (winsound 모듈)

SND_NOWAIT (winsound 모듈)

SND_PURGE (winsound 모듈)

sndhdr (모듈)

sni_callback (ssl.SSLContext의 속성)

sniff() (csv.Sniffer 메서드)

Sniffer (csv 클래스)

sock_accept() (asyncio.loop의 메서드)

SOCK_CLOEXEC (socket 모듈)

sock_connect() (asyncio.loop의 메서드)

SOCK_DGRAM (socket 모듈)

SOCK_MAX_SIZE (test.support 모듈)

SOCK_NONBLOCK (socket 모듈)

SOCK_RAW (socket 모듈)

SOCK_RDM (socket 모듈)

sock_recv() (asyncio.loop의 메서드)

sock_recv_into() (asyncio.loop의 메서드)

sock_sendall() (asyncio.loop의 메서드)

sock_sendfile() (asyncio.loop의 메서드)

SOCK_SEQPACKET (socket 모듈)

SOCK_STREAM (socket 모듈)

socket

객체

모듈

socket (socketserver.BaseServer의 속성)

(모듈)

socket() (imaplib.IMAP4 메서드)

(in module socket)

(socket 모듈)

socket_type (socketserver.BaseServer의 속성)

SocketHandler (logging.handlers 클래스)

socketpair() (socket 모듈)

sockets (asyncio.Server의 속성)

socketserver (모듈)

SocketType (socket 모듈)

SOL_ALG (socket 모듈)

SOL_RDS (socket 모듈)

SOMAXCONN (socket 모듈)

sort() (imaplib.IMAP4 메서드)

(list 메서드)

sort_stats() (pstats.Stats 메서드)

sortdict() (test.support 모듈)

sorted() (내장 함수)

sortTestMethodsUsing (unittest.TestLoader의 속성)

source (doctest.Example의 속성)

(pdb command)

(shlex.shlex의 속성)

source character set

SOURCE_DATE_EPOCH, [1], [2], [3], [4], [5], [6]

source_from_cache() (imp 모듈)

(importlib.util 모듈)

source_hash() (importlib.util 모듈)

SOURCE_SUFFIXES (importlib.machinery 모듈)

source_to_code() (importlib.abc.InspectLoader의 정적 메서드)

SourceFileLoader (importlib.machinery 클래스)

sourcehook() (shlex.shlex 메서드)

SourcelessFileLoader (importlib.machinery 클래스)

SourceLoader (importlib.abc 클래스)

space

in printf-style formatting, [1]

in string formatting

span() (re.Match 메서드)

spawn() (distutils.ccompiler.CCompiler 메서드)

(pty 모듈)

spawn_python() (test.support.script_helper 모듈)

spawnl() (os 모듈)

spawnle() (os 모듈)

spawnlp() (os 모듈)

spawnlpe() (os 모듈)

spawnv() (os 모듈)

spawnve() (os 모듈)

spawnvp() (os 모듈)

spawnvpe() (os 모듈)

spec_from_file_location() (importlib.util 모듈)

spec_from_loader() (importlib.util 모듈)

special

attribute

attribute, generic

method

special method (특수 메서드)

specified_attributes (xml.parsers.expat.xmlparser의 속성)

speed() (ossaudiodev.oss_audio_device 메서드)

(turtle 모듈)

Spinbox (tkinter.ttk 클래스)

split() (bytearray 메서드)

(bytes 메서드)

(os.path 모듈)

(re 모듈)

(re.Pattern 메서드)

(shlex 모듈)

(str 메서드)

split_quoted() (distutils.util 모듈)

splitdrive() (os.path 모듈)

splitext() (os.path 모듈)

splitlines() (bytearray 메서드)

(bytes 메서드)

(str 메서드)

SplitResult (urllib.parse 클래스)

SplitResultBytes (urllib.parse 클래스)

SpooledTemporaryFile() (tempfile 모듈)

sprintf-style formatting, [1]

spwd (모듈)

sqlite3 (모듈)

sqlite_version (sqlite3 모듈)

sqlite_version_info (sqlite3 모듈)

sqrt() (cmath 모듈)

(decimal.Context 메서드)

(decimal.Decimal 메서드)

(math 모듈)

SSL

ssl (모듈)

SSL_CERT_FILE

SSL_CERT_PATH

ssl_version (ftplib.FTP_TLS의 속성)

SSLCertVerificationError

SSLContext (ssl 클래스)

SSLEOFError

SSLError

SSLErrorNumber (ssl 클래스)

SSLObject (ssl 클래스)

sslobject_class (ssl.SSLContext의 속성)

SSLSession (ssl 클래스)

SSLSocket (ssl 클래스)

sslsocket_class (ssl.SSLContext의 속성)

SSLSyscallError

SSLv3 (ssl.TLSVersion의 속성)

SSLWantReadError

SSLWantWriteError

SSLZeroReturnError

st() (turtle 모듈)

st2list() (parser 모듈)

st2tuple() (parser 모듈)

st_atime (os.stat_result의 속성)

ST_ATIME (stat 모듈)

st_atime_ns (os.stat_result의 속성)

st_birthtime (os.stat_result의 속성)

st_blksize (os.stat_result의 속성)

st_blocks (os.stat_result의 속성)

st_creator (os.stat_result의 속성)

st_ctime (os.stat_result의 속성)

ST_CTIME (stat 모듈)

st_ctime_ns (os.stat_result의 속성)

st_dev (os.stat_result의 속성)

ST_DEV (stat 모듈)

st_file_attributes (os.stat_result의 속성)

st_flags (os.stat_result의 속성)

st_fstype (os.stat_result의 속성)

st_gen (os.stat_result의 속성)

st_gid (os.stat_result의 속성)

ST_GID (stat 모듈)

st_ino (os.stat_result의 속성)

ST_INO (stat 모듈)

st_mode (os.stat_result의 속성)

ST_MODE (stat 모듈)

st_mtime (os.stat_result의 속성)

ST_MTIME (stat 모듈)

st_mtime_ns (os.stat_result의 속성)

st_nlink (os.stat_result의 속성)

ST_NLINK (stat 모듈)

st_rdev (os.stat_result의 속성)

st_rsize (os.stat_result의 속성)

st_size (os.stat_result의 속성)

ST_SIZE (stat 모듈)

st_type (os.stat_result의 속성)

st_uid (os.stat_result의 속성)

ST_UID (stat 모듈)

stack

execution

trace

stack (traceback.TracebackException의 속성)

stack viewer

stack() (inspect 모듈)

stack_effect() (dis 모듈)

stack_size() (_thread 모듈)

(threading 모듈)

stackable

streams

StackSummary (traceback 클래스)

stamp() (turtle 모듈)

standard

output

Standard C

standard input

standard_b64decode() (base64 모듈)

standard_b64encode() (base64 모듈)

standarderror (2to3 fixer)

standend() (curses.window 메서드)

standout() (curses.window 메서드)

STAR (token 모듈)

STAREQUAL (token 모듈)

starmap() (itertools 모듈)

(multiprocessing.pool.Pool 메서드)

starmap_async() (multiprocessing.pool.Pool 메서드)

start (range의 속성)

(slice object attribute), [1]

(UnicodeError의 속성)

start() (logging.handlers.QueueListener 메서드)

(multiprocessing.managers.BaseManager 메서드)

(multiprocessing.Process 메서드)

(re.Match 메서드)

(threading.Thread 메서드)

(tkinter.ttk.Progressbar 메서드)

(tracemalloc 모듈)

(xml.etree.ElementTree.TreeBuilder 메서드)

start_color() (curses 모듈)

start_component() (msilib.Directory 메서드)

start_new_thread() (_thread 모듈)

start_server() (asyncio 모듈)

start_serving() (asyncio.Server의 메서드)

start_threads() (test.support 모듈)

start_tls() (asyncio.loop의 메서드)

start_unix_server() (asyncio 모듈)

StartCdataSectionHandler() (xml.parsers.expat.xmlparser 메서드)

StartDoctypeDeclHandler() (xml.parsers.expat.xmlparser 메서드)

startDocument() (xml.sax.handler.ContentHandler 메서드)

startElement() (xml.sax.handler.ContentHandler 메서드)

StartElementHandler() (xml.parsers.expat.xmlparser 메서드)

startElementNS() (xml.sax.handler.ContentHandler 메서드)

STARTF_USESHOWWINDOW (subprocess 모듈)

STARTF_USESTDHANDLES (subprocess 모듈)

startfile() (os 모듈)

StartNamespaceDeclHandler() (xml.parsers.expat.xmlparser 메서드)

startPrefixMapping() (xml.sax.handler.ContentHandler 메서드)

startswith() (bytearray 메서드)

(bytes 메서드)

(str 메서드)

startTest() (unittest.TestResult 메서드)

startTestRun() (unittest.TestResult 메서드)

starttls() (imaplib.IMAP4 메서드)

(nntplib.NNTP 메서드)

(smtplib.SMTP 메서드)

STARTUPINFO (subprocess 클래스)

stat

모듈

stat (모듈)

stat() (nntplib.NNTP 메서드)

(os 모듈)

(os.DirEntry 메서드)

(pathlib.Path 메서드)

(poplib.POP3 메서드)

stat_result (os 클래스)

state() (tkinter.ttk.Widget 메서드)

statement

assignment, [1]

assignment, annotated

assignment, augmented

compound

expression

future

loop, [1], [2], [3]

simple

statement (문장)

statement grouping

staticmethod

내장 함수

staticmethod() (내장 함수)

Statistic (tracemalloc 클래스)

StatisticDiff (tracemalloc 클래스)

statistics (모듈)

statistics() (tracemalloc.Snapshot 메서드)

StatisticsError

Stats (pstats 클래스)

status (http.client.HTTPResponse의 속성)

status() (imaplib.IMAP4 메서드)

statvfs() (os 모듈)

STD_ERROR_HANDLE (subprocess 모듈)

STD_INPUT_HANDLE (subprocess 모듈)

STD_OUTPUT_HANDLE (subprocess 모듈)

StdButtonBox (tkinter.tix 클래스)

stderr (asyncio.asyncio.subprocess.Process의 속성)

(in module sys), [1]

(subprocess.CalledProcessError의 속성)

(subprocess.CompletedProcess의 속성)

(subprocess.Popen의 속성)

(subprocess.TimeoutExpired의 속성)

(sys 모듈)

stdev() (statistics 모듈)

stdin

stdout sdterr

stdin (asyncio.asyncio.subprocess.Process의 속성)

(in module sys), [1]

(subprocess.Popen의 속성)

(sys 모듈)

stdio

stdout

sdterr, stdin

stdout (asyncio.asyncio.subprocess.Process의 속성)

(in module sys), [1]

STDOUT (subprocess 모듈)

stdout (subprocess.CalledProcessError의 속성)

(subprocess.CompletedProcess의 속성)

(subprocess.Popen의 속성)

(subprocess.TimeoutExpired의 속성)

(sys 모듈)

step (pdb command)

(range의 속성)

(slice object attribute), [1]

step() (tkinter.ttk.Progressbar 메서드)

stereocontrols() (ossaudiodev.oss_mixer_device 메서드)

stls() (poplib.POP3 메서드)

stop (range의 속성)

(slice object attribute), [1]

stop() (asyncio.loop 메서드)

(logging.handlers.QueueListener 메서드)

(tkinter.ttk.Progressbar 메서드)

(tracemalloc 모듈)

(unittest.TestResult 메서드)

stop_here() (bdb.Bdb 메서드)

StopAsyncIteration

예외

StopIteration

예외, [1]

stopListening() (logging.config 모듈)

stopTest() (unittest.TestResult 메서드)

stopTestRun() (unittest.TestResult 메서드)

storbinary() (ftplib.FTP 메서드)

store() (imaplib.IMAP4 메서드)

STORE_ACTIONS (optparse.Option의 속성)

STORE_ATTR (opcode)

STORE_DEREF (opcode)

STORE_FAST (opcode)

STORE_GLOBAL (opcode)

STORE_NAME (opcode)

STORE_SUBSCR (opcode)

storlines() (ftplib.FTP 메서드)

str (built-in class)

(see also string)

str (내장 클래스)

str() (locale 모듈)

strcoll() (locale 모듈)

StreamError

StreamHandler (logging 클래스)

StreamReader (asyncio 클래스)

(codecs 클래스)

streamreader (codecs.CodecInfo의 속성)

StreamReaderWriter (codecs 클래스)

StreamRecoder (codecs 클래스)

StreamRequestHandler (socketserver 클래스)

streams

stackable

StreamWriter (asyncio 클래스)

(codecs 클래스)

streamwriter (codecs.CodecInfo의 속성)

strerror (OSError의 속성)

strerror()

(os 모듈)

strftime() (datetime.date 메서드)

(datetime.datetime 메서드)

(datetime.time 메서드)

(time 모듈)

strict (csv.Dialect의 속성)

(email.policy 모듈)

strict_domain (http.cookiejar.DefaultCookiePolicy의 속성)

strict_errors() (codecs 모듈)

strict_ns_domain (http.cookiejar.DefaultCookiePolicy의 속성)

strict_ns_set_initial_dollar (http.cookiejar.DefaultCookiePolicy의 속성)

strict_ns_set_path (http.cookiejar.DefaultCookiePolicy의 속성)

strict_ns_unverifiable (http.cookiejar.DefaultCookiePolicy의 속성)

strict_rfc2965_unverifiable (http.cookiejar.DefaultCookiePolicy의 속성)

strides (memoryview의 속성)

string

__format__() (object method)

__str__() (object method)

conversion, [1]

format() (built-in function)

formatted literal

formatting, printf

immutable sequences

interpolated literal

interpolation, printf

item

methods

object representation

PyObject_Str (C function)

str (built-in class)

str() (built-in function)

text sequence type

객체, [1], [2]

모듈

string (re.Match의 속성)

STRING (token 모듈)

string (모듈)

string literal

string_at() (ctypes 모듈)

StringIO (io 클래스)

stringprep (모듈)

strings, documentation, [1]

strip() (bytearray 메서드)

(bytes 메서드)

(str 메서드)

strip_dirs() (pstats.Stats 메서드)

strip_python_strerr() (test.support 모듈)

stripspaces (curses.textpad.Textbox의 속성)

strptime() (datetime.datetime의 클래스 메서드)

(time 모듈)

strtobool() (distutils.util 모듈)

struct

모듈

Struct (struct 클래스)

struct (모듈)

struct_time (time 클래스)

Structure (ctypes 클래스)

structures

C

strxfrm() (locale 모듈)

STType (parser 모듈)

style

coding

Style (tkinter.ttk 클래스)

sub() (operator 모듈)

(re 모듈)

(re.Pattern 메서드)

sub_commands (distutils.cmd.Command의 속성)

subclassing

immutable types

subdirs (filecmp.dircmp의 속성)

SubElement() (xml.etree.ElementTree 모듈)

submit() (concurrent.futures.Executor 메서드)

submodule_search_locations (importlib.machinery.ModuleSpec의 속성)

subn() (re 모듈)

(re.Pattern 메서드)

subnet_of() (ipaddress.IPv4Network 메서드)

(ipaddress.IPv6Network 메서드)

subnets() (ipaddress.IPv4Network 메서드)

(ipaddress.IPv6Network 메서드)

Subnormal (decimal 클래스)

suboffsets (memoryview의 속성)

subpad() (curses.window 메서드)

subprocess (모듈)

subprocess_exec() (asyncio.loop의 메서드)

subprocess_shell() (asyncio.loop의 메서드)

SubprocessError

SubprocessProtocol (asyncio 클래스)

SubprocessTransport (asyncio 클래스)

subscribe() (imaplib.IMAP4 메서드)

subscript

assignment

operation

subscription, [1], [2], [3]

assignment

subsequent_indent (textwrap.TextWrapper의 속성)

subst_vars() (distutils.util 모듈)

substitute() (string.Template 메서드)

subTest() (unittest.TestCase 메서드)

subtract() (collections.Counter 메서드)

(decimal.Context 메서드)

subtraction

subtype (email.headerregistry.ContentTypeHeader의 속성)

subwin() (curses.window 메서드)

successful() (multiprocessing.pool.AsyncResult 메서드)

suffix_map (mimetypes 모듈)

(mimetypes.MimeTypes의 속성)

suite

suite() (parser 모듈)

suiteClass (unittest.TestLoader의 속성)

sum() (내장 함수)

sum_list()

sum_sequence(), [1]

summarize() (doctest.DocTestRunner 메서드)

summarize_address_range() (ipaddress 모듈)

sunau (모듈)

super (pyclbr.Class의 속성)

super() (내장 함수)

supernet() (ipaddress.IPv4Network 메서드)

(ipaddress.IPv6Network 메서드)

supernet_of() (ipaddress.IPv4Network 메서드)

(ipaddress.IPv6Network 메서드)

supports_bytes_environ (os 모듈)

supports_dir_fd (os 모듈)

supports_effective_ids (os 모듈)

supports_fd (os 모듈)

supports_follow_symlinks (os 모듈)

supports_unicode_filenames (os.path 모듈)

SupportsAbs (typing 클래스)

SupportsBytes (typing 클래스)

SupportsComplex (typing 클래스)

SupportsFloat (typing 클래스)

SupportsInt (typing 클래스)

SupportsRound (typing 클래스)

suppress() (contextlib 모듈)

SuppressCrashReport (test.support 클래스)

SW_HIDE (subprocess 모듈)

swap_attr() (test.support 모듈)

swap_item() (test.support 모듈)

swapcase() (bytearray 메서드)

(bytes 메서드)

(str 메서드)

sym_name (symbol 모듈)

Symbol (symtable 클래스)

symbol (모듈)

SymbolTable (symtable 클래스)

symlink() (os 모듈)

symlink_to() (pathlib.Path 메서드)

symmetric_difference() (frozenset 메서드)

symmetric_difference_update() (frozenset 메서드)

symtable (모듈)

symtable() (symtable 모듈)

sync() (dbm.dumb.dumbdbm 메서드)

(dbm.gnu.gdbm 메서드)

(os 모듈)

(ossaudiodev.oss_audio_device 메서드)

(shelve.Shelf 메서드)

syncdown() (curses.window 메서드)

synchronized() (multiprocessing.sharedctypes 모듈)

SyncManager (multiprocessing.managers 클래스)

syncok() (curses.window 메서드)

syncup() (curses.window 메서드)

syntax

SyntaxErr

SyntaxError

SyntaxWarning

sys

모듈, [1], [2], [3], [4], [5], [6]

sys (모듈)

sys.exc_info

sys.last_traceback

sys.meta_path

sys.modules

sys.path

sys.path_hooks

sys.path_importer_cache

sys.stderr

sys.stdin

sys.stdout

sys_exc (2to3 fixer)

sys_version (http.server.BaseHTTPRequestHandler의 속성)

sysconf() (os 모듈)

sysconf_names (os 모듈)

sysconfig (모듈)

syslog (모듈)

syslog() (syslog 모듈)

SysLogHandler (logging.handlers 클래스)

system() (os 모듈)

(platform 모듈)

system_alias() (platform 모듈)

system_must_validate_cert() (test.support 모듈)

SystemError

(built-in exception), [1]

SystemExit

(built-in exception)

systemId (xml.dom.DocumentType의 속성)

SystemRandom (random 클래스)

(secrets 클래스)

SystemRoot

T

T_FMT (locale 모듈)

T_FMT_AMPM (locale 모듈)

tab

tab() (tkinter.ttk.Notebook 메서드)

TabError

tabnanny (모듈)

tabs() (tkinter.ttk.Notebook 메서드)

tabsize (textwrap.TextWrapper의 속성)

tabular

data

tag (xml.etree.ElementTree.Element의 속성)

tag_bind() (tkinter.ttk.Treeview 메서드)

tag_configure() (tkinter.ttk.Treeview 메서드)

tag_has() (tkinter.ttk.Treeview 메서드)

tagName (xml.dom.Element의 속성)

tail (xml.etree.ElementTree.Element의 속성)

take_snapshot() (tracemalloc 모듈)

takewhile() (itertools 모듈)

tan() (cmath 모듈)

(math 모듈)

tanh() (cmath 모듈)

(math 모듈)

TarError

TarFile (tarfile 클래스), [1]

tarfile (모듈)

tarfile command line option

--create <tarfile> <source1> ... <sourceN>

--extract <tarfile> [<output_dir>]

--list <tarfile>

--test <tarfile>

--verbose

-c <tarfile> <source1> ... <sourceN>

-e <tarfile> [<output_dir>]

-l <tarfile>

-t <tarfile>

-v

target

deletion

list, [1]

list assignment

list, deletion

loop control

target (xml.dom.ProcessingInstruction의 속성)

TarInfo (tarfile 클래스)

Task (asyncio 클래스)

task_done() (asyncio.Queue 메서드)

(multiprocessing.JoinableQueue 메서드)

(queue.Queue 메서드)

tau (cmath 모듈)

(math 모듈)

tb_frame (traceback attribute)

tb_lasti (traceback attribute)

tb_lineno (traceback attribute)

tb_locals (unittest.TestResult의 속성)

tb_next (traceback attribute)

tbreak (pdb command)

tcdrain() (termios 모듈)

tcflow() (termios 모듈)

tcflush() (termios 모듈)

tcgetattr() (termios 모듈)

tcgetpgrp() (os 모듈)

Tcl() (tkinter 모듈)

TCL_LIBRARY

TCPServer (socketserver 클래스)

tcsendbreak() (termios 모듈)

tcsetattr() (termios 모듈)

tcsetpgrp() (os 모듈)

tearDown() (unittest.TestCase 메서드)

tearDownClass() (unittest.TestCase 메서드)

tee() (itertools 모듈)

tell() (aifc.aifc 메서드), [1]

(chunk.Chunk 메서드)

(io.IOBase 메서드)

(io.TextIOBase 메서드)

(mmap.mmap 메서드)

(sunau.AU_read 메서드)

(sunau.AU_write 메서드)

(wave.Wave_read 메서드)

(wave.Wave_write 메서드)

Telnet (telnetlib 클래스)

telnetlib (모듈)

TEMP

temp_cwd() (test.support 모듈)

temp_dir() (test.support 모듈)

temp_umask() (test.support 모듈)

tempdir (tempfile 모듈)

tempfile (모듈)

Template (pipes 클래스)

(string 클래스)

template (string.Template의 속성)

temporary

file

file name

TemporaryDirectory() (tempfile 모듈)

TemporaryFile() (tempfile 모듈)

teredo (ipaddress.IPv6Address의 속성)

TERM, [1]

termattrs() (curses 모듈)

terminal_size (os 클래스)

terminate() (asyncio.asyncio.subprocess.Process 메서드)

(asyncio.SubprocessTransport 메서드)

(multiprocessing.pool.Pool 메서드)

(multiprocessing.Process 메서드)

(subprocess.Popen 메서드)

termination model

termios (모듈)

termname() (curses 모듈)

ternary

operator

test

identity

membership

test (doctest.DocTestFailure의 속성)

(doctest.UnexpectedException의 속성)

(모듈)

test() (cgi 모듈)

test.support (모듈)

test.support.script_helper (모듈)

TEST_DATA_DIR (test.support 모듈)

TEST_HOME_DIR (test.support 모듈)

TEST_HTTP_URL (test.support 모듈)

TEST_SUPPORT_DIR (test.support 모듈)

TestCase (unittest 클래스)

TestFailed

testfile() (doctest 모듈)

TESTFN (test.support 모듈)

TESTFN_ENCODING (test.support 모듈)

TESTFN_NONASCII (test.support 모듈)

TESTFN_UNDECODABLE (test.support 모듈)

TESTFN_UNENCODABLE (test.support 모듈)

TESTFN_UNICODE (test.support 모듈)

TestHandler (test.support 클래스)

TestLoader (unittest 클래스)

testMethodPrefix (unittest.TestLoader의 속성)

testmod() (doctest 모듈)

testNamePatterns (unittest.TestLoader의 속성)

TestResult (unittest 클래스)

tests (imghdr 모듈)

testsource() (doctest 모듈)

testsRun (unittest.TestResult의 속성)

TestSuite (unittest 클래스)

testzip() (zipfile.ZipFile 메서드)

text (msilib 모듈)

(traceback.TracebackException의 속성)

Text (typing 클래스)

text (xml.etree.ElementTree.Element의 속성)

text encoding (텍스트 인코딩)

text file (텍스트 파일)

text mode

text() (cgitb 모듈)

(msilib.Dialog 메서드)

text_factory (sqlite3.Connection의 속성)

Textbox (curses.textpad 클래스)

TextCalendar (calendar 클래스)

textdomain() (gettext 모듈)

(locale 모듈)

TextFile (distutils.text_file 클래스)

textinput() (turtle 모듈)

TextIO (typing 클래스)

TextIOBase (io 클래스)

TextIOWrapper (io 클래스)

TextTestResult (unittest 클래스)

TextTestRunner (unittest 클래스)

textwrap (모듈)

TextWrapper (textwrap 클래스)

theme_create() (tkinter.ttk.Style 메서드)

theme_names() (tkinter.ttk.Style 메서드)

theme_settings() (tkinter.ttk.Style 메서드)

theme_use() (tkinter.ttk.Style 메서드)

THOUSEP (locale 모듈)

Thread (threading 클래스)

thread() (imaplib.IMAP4 메서드)

thread_info (sys 모듈)

thread_time() (time 모듈)

thread_time_ns() (time 모듈)

threading (모듈)

threading_cleanup() (test.support 모듈)

threading_setup() (test.support 모듈)

ThreadingHTTPServer (http.server 클래스)

ThreadingMixIn (socketserver 클래스)

ThreadingTCPServer (socketserver 클래스)

ThreadingUDPServer (socketserver 클래스)

ThreadPool (multiprocessing.pool 클래스)

ThreadPoolExecutor (concurrent.futures 클래스)

threads

POSIX

throw (2to3 fixer)

throw() (coroutine 메서드)

(generator 메서드)

ticket_lifetime_hint (ssl.SSLSession의 속성)

tigetflag() (curses 모듈)

tigetnum() (curses 모듈)

tigetstr() (curses 모듈)

TILDE (token 모듈)

tilt() (turtle 모듈)

tiltangle() (turtle 모듈)

time (datetime 클래스)

(ssl.SSLSession의 속성)

(모듈)

time() (asyncio.loop 메서드)

(datetime.datetime 메서드)

(time 모듈)

Time2Internaldate() (imaplib 모듈)

time_ns() (time 모듈)

timedelta (datetime 클래스)

TimedRotatingFileHandler (logging.handlers 클래스)

timegm() (calendar 모듈)

timeit (모듈)

timeit command line option

--help

--number=N

--process

--repeat=N

--setup=S

--unit=U

--verbose

-h

-n N

-p

-r N

-s S

-u

-v

timeit() (timeit 모듈)

(timeit.Timer 메서드)

timeout

(socketserver.BaseServer의 속성)

(ssl.SSLSession의 속성)

(subprocess.TimeoutExpired의 속성)

timeout() (curses.window 메서드)

TIMEOUT_MAX (_thread 모듈)

(threading 모듈)

TimeoutError, [1], [2], [3]

TimeoutExpired

Timer (threading 클래스)

(timeit 클래스)

TimerHandle (asyncio 클래스)

times() (os 모듈)

TIMESTAMP (py_compile.PycInvalidationMode의 속성)

timestamp() (datetime.datetime 메서드)

timetuple() (datetime.date 메서드)

(datetime.datetime 메서드)

timetz() (datetime.datetime 메서드)

timezone (datetime 클래스)

(time 모듈)

title() (bytearray 메서드)

(bytes 메서드)

(str 메서드)

(turtle 모듈)

Tix

tix_addbitmapdir() (tkinter.tix.tixCommand 메서드)

tix_cget() (tkinter.tix.tixCommand 메서드)

tix_configure() (tkinter.tix.tixCommand 메서드)

tix_filedialog() (tkinter.tix.tixCommand 메서드)

tix_getbitmap() (tkinter.tix.tixCommand 메서드)

tix_getimage() (tkinter.tix.tixCommand 메서드)

tix_option_get() (tkinter.tix.tixCommand 메서드)

tix_resetoptions() (tkinter.tix.tixCommand 메서드)

tixCommand (tkinter.tix 클래스)

Tk

(tkinter 클래스)

(tkinter.tix 클래스)

Tk Option Data Types

TK_LIBRARY

Tkinter

tkinter (모듈)

tkinter.scrolledtext (모듈)

tkinter.tix (모듈)

tkinter.ttk (모듈)

TList (tkinter.tix 클래스)

TLS

TLSv1 (ssl.TLSVersion의 속성)

TLSv1_1 (ssl.TLSVersion의 속성)

TLSv1_2 (ssl.TLSVersion의 속성)

TLSv1_3 (ssl.TLSVersion의 속성)

TLSVersion (ssl 클래스)

TMP

TMPDIR

to_bytes() (int 메서드)

to_eng_string() (decimal.Context 메서드)

(decimal.Decimal 메서드)

to_integral() (decimal.Decimal 메서드)

to_integral_exact() (decimal.Context 메서드)

(decimal.Decimal 메서드)

to_integral_value() (decimal.Decimal 메서드)

to_sci_string() (decimal.Context 메서드)

ToASCII() (encodings.idna 모듈)

tobuf() (tarfile.TarInfo 메서드)

tobytes() (array.array 메서드)

(memoryview 메서드)

today() (datetime.datetime의 클래스 메서드)

(datetime.date의 클래스 메서드)

tofile() (array.array 메서드)

tok_name (token 모듈)

token

(shlex.shlex의 속성)

(모듈)

token_bytes() (secrets 모듈)

token_hex() (secrets 모듈)

token_urlsafe() (secrets 모듈)

TokenError

tokenize (모듈)

tokenize command line option

--exact

--help

-e

-h

tokenize() (tokenize 모듈)

tolist() (array.array 메서드)

(memoryview 메서드)

(parser.ST 메서드)

tomono() (audioop 모듈)

toordinal() (datetime.date 메서드)

(datetime.datetime 메서드)

top() (curses.panel.Panel 메서드)

(poplib.POP3 메서드)

top_panel() (curses.panel 모듈)

toprettyxml() (xml.dom.minidom.Node 메서드)

tostereo() (audioop 모듈)

tostring() (array.array 메서드)

(xml.etree.ElementTree 모듈)

tostringlist() (xml.etree.ElementTree 모듈)

total_changes (sqlite3.Connection의 속성)

total_ordering() (functools 모듈)

total_seconds() (datetime.timedelta 메서드)

totuple() (parser.ST 메서드)

touch() (pathlib.Path 메서드)

touchline() (curses.window 메서드)

touchwin() (curses.window 메서드)

tounicode() (array.array 메서드)

ToUnicode() (encodings.idna 모듈)

towards() (turtle 모듈)

toxml() (xml.dom.minidom.Node 메서드)

tp_as_async (C 멤버 변수)

tp_as_mapping (C 멤버 변수)

tp_as_number (C 멤버 변수)

tp_as_sequence (C 멤버 변수)

tparm() (curses 모듈)

trace

stack

Trace (trace 클래스)

(tracemalloc 클래스)

trace (모듈)

trace command line option

--count

--coverdir=<dir>

--file=<file>

--help

--ignore-dir=<dir>

--ignore-module=<mod>

--listfuncs

--missing

--no-report

--report

--summary

--timing

--trace

--trackcalls

--version

-c

-C

-f

-g

-l

-m

-r

-R

-s

-t

-T

trace function, [1], [2]

trace() (inspect 모듈)

trace_dispatch() (bdb.Bdb 메서드)

traceback

객체, [1], [2], [3], [4]

Traceback (tracemalloc 클래스)

traceback (tracemalloc.StatisticDiff의 속성)

(tracemalloc.Statistic의 속성)

(tracemalloc.Trace의 속성)

(모듈)

traceback_limit (tracemalloc.Snapshot의 속성)

(wsgiref.handlers.BaseHandler의 속성)

TracebackException (traceback 클래스)

tracebacklimit (sys 모듈)

tracebacks

in CGI scripts

TracebackType (types 클래스)

tracemalloc (모듈)

tracer() (turtle 모듈)

traces (tracemalloc.Snapshot의 속성)

trailing

comma

transfercmd() (ftplib.FTP 메서드)

transient_internet() (test.support 모듈)

TransientResource (test.support 클래스)

translate() (bytearray 메서드)

(bytes 메서드)

(fnmatch 모듈)

(str 메서드)

translation() (gettext 모듈)

Transport (asyncio 클래스)

transport (asyncio.StreamWriter의 속성)

Transport Layer Security

traverseproc (C 데이터 형식)

Tree (tkinter.tix 클래스)

TreeBuilder (xml.etree.ElementTree 클래스)

Treeview (tkinter.ttk 클래스)

triangular() (random 모듈)

triple-quoted string

(삼중 따옴표 된 문자열)

True, [1], [2]

true

True (내장 변수)

truediv() (operator 모듈)

trunc() (in module math)

(math 모듈)

truncate() (io.IOBase 메서드)

(os 모듈)

truth

value

truth() (operator 모듈)

try

글, [1], [2]

ttk

tty

I/O control

tty (모듈)

ttyname() (os 모듈)

tuple

empty, [1]

singleton

객체, [1], [2], [3], [4], [5], [6]

내장 함수, [1]

Tuple (typing 모듈)

tuple (내장 클래스)

tuple2st() (parser 모듈)

tuple_params (2to3 fixer)

Turtle (turtle 클래스)

turtle (모듈)

turtledemo (모듈)

turtles() (turtle 모듈)

TurtleScreen (turtle 클래스)

turtlesize() (turtle 모듈)

type

Boolean

data

hierarchy

immutable data

operations on dictionary

operations on list

객체, [1], [2]

내장 함수, [1], [2], [3]

type (optparse.Option의 속성)

(socket.socket의 속성)

(tarfile.TarInfo의 속성)

Type (typing 클래스)

type (urllib.request.Request의 속성)

(내장 클래스)

(형)

type alias (형 에일리어스)

type hint (형 힌트)

type of an object

type_check_only() (typing 모듈)

TYPE_CHECKER (optparse.Option의 속성)

TYPE_CHECKING (typing 모듈)

typeahead() (curses 모듈)

typecode (array.array의 속성)

typecodes (array 모듈)

TYPED_ACTIONS (optparse.Option의 속성)

typed_subpart_iterator() (email.iterators 모듈)

TypeError

예외

types

built-in

immutable sequence

mutable sequence

operations on integer

operations on mapping

operations on numeric

operations on sequence, [1]

모듈

types (2to3 fixer)

TYPES (optparse.Option의 속성)

types (모듈)

types, internal

types_map (mimetypes 모듈)

(mimetypes.MimeTypes의 속성)

types_map_inv (mimetypes.MimeTypes의 속성)

TypeVar (typing 클래스)

typing (모듈)

TZ, [1], [2], [3], [4], [5]

tzinfo (datetime 클래스)

(datetime.datetime의 속성)

(datetime.time의 속성)

tzname (time 모듈)

tzname() (datetime.datetime 메서드)

(datetime.time 메서드)

(datetime.timezone 메서드)

(datetime.tzinfo 메서드)

tzset() (time 모듈)

U

u"

string literal

u'

string literal

u-LAW, [1], [2]

ucd_3_2_0 (unicodedata 모듈)

udata (select.kevent의 속성)

UDPServer (socketserver 클래스)

UF_APPEND (stat 모듈)

UF_COMPRESSED (stat 모듈)

UF_HIDDEN (stat 모듈)

UF_IMMUTABLE (stat 모듈)

UF_NODUMP (stat 모듈)

UF_NOUNLINK (stat 모듈)

UF_OPAQUE (stat 모듈)

uid (tarfile.TarInfo의 속성)

uid() (imaplib.IMAP4 메서드)

uidl() (poplib.POP3 메서드)

ulaw2lin() (audioop 모듈)

ULONG_MAX

umask() (os 모듈)

unalias (pdb command)

uname (tarfile.TarInfo의 속성)

uname() (os 모듈)

(platform 모듈)

unary

arithmetic operation

bitwise operation

UNARY_INVERT (opcode)

UNARY_NEGATIVE (opcode)

UNARY_NOT (opcode)

UNARY_POSITIVE (opcode)

unbinding

name

UnboundLocalError, [1]

unbuffered I/O

UNC paths

and os.makedirs()

UNCHECKED_HASH (py_compile.PycInvalidationMode의 속성)

unconsumed_tail (zlib.Decompress의 속성)

unctrl() (curses 모듈)

(curses.ascii 모듈)

undefine_macro() (distutils.ccompiler.CCompiler 메서드)

Underflow (decimal 클래스)

undisplay (pdb command)

undo() (turtle 모듈)

undobufferentries() (turtle 모듈)

undoc_header (cmd.Cmd의 속성)

unescape() (html 모듈)

(xml.sax.saxutils 모듈)

UnexpectedException

unexpectedSuccesses (unittest.TestResult의 속성)

unfreeze() (gc 모듈)

unget_wch() (curses 모듈)

ungetch() (curses 모듈)

(msvcrt 모듈)

ungetmouse() (curses 모듈)

ungetwch() (msvcrt 모듈)

unhexlify() (binascii 모듈)

Unicode, [1], [2]

database

unicode (2to3 fixer)

Unicode Consortium

unicodedata (모듈)

UnicodeDecodeError

UnicodeEncodeError

UnicodeError

UnicodeTranslateError

UnicodeWarning

unidata_version (unicodedata 모듈)

unified_diff() (difflib 모듈)

uniform() (random 모듈)

UnimplementedFileMode

Union (ctypes 클래스)

(typing 모듈)

union() (frozenset 메서드)

unique() (enum 모듈), [1]

unittest (모듈)

unittest command line option

--buffer

--catch

--failfast

--locals

-b

-c

-f

-k

unittest-discover command line option

--pattern pattern

--start-directory directory

--top-level-directory directory

--verbose

-p

-s

-t

-v

unittest.mock (모듈)

universal newlines

bytearray.splitlines method

bytes.splitlines method

csv.reader function

importlib.abc.InspectLoader.get_source method

io.IncrementalNewlineDecoder class

io.TextIOWrapper class

open() built-in function

str.splitlines method

subprocess module

What's new, [1], [2], [3]

universal newlines (유니버설 줄 넘김)

UNIX

file control

I/O control

unix_dialect (csv 클래스)

unix_shell (test.support 모듈)

UnixDatagramServer (socketserver 클래스)

UnixStreamServer (socketserver 클래스)

unknown (uuid.SafeUUID의 속성)

unknown_decl() (html.parser.HTMLParser 메서드)

unknown_open() (urllib.request.BaseHandler 메서드)

(urllib.request.UnknownHandler 메서드)

UnknownHandler (urllib.request 클래스)

UnknownProtocol

UnknownTransferEncoding

unlink() (os 모듈)

(pathlib.Path 메서드)

(test.support 모듈)

(xml.dom.minidom.Node 메서드)

unload() (test.support 모듈)

unlock() (mailbox.Babyl 메서드)

(mailbox.Mailbox 메서드)

(mailbox.Maildir 메서드)

(mailbox.mbox 메서드)

(mailbox.MH 메서드)

(mailbox.MMDF 메서드)

unpack() (struct 모듈)

(struct.Struct 메서드)

unpack_archive() (shutil 모듈)

unpack_array() (xdrlib.Unpacker 메서드)

unpack_bytes() (xdrlib.Unpacker 메서드)

unpack_double() (xdrlib.Unpacker 메서드)

UNPACK_EX (opcode)

unpack_farray() (xdrlib.Unpacker 메서드)

unpack_float() (xdrlib.Unpacker 메서드)

unpack_fopaque() (xdrlib.Unpacker 메서드)

unpack_from() (struct 모듈)

(struct.Struct 메서드)

unpack_fstring() (xdrlib.Unpacker 메서드)

unpack_list() (xdrlib.Unpacker 메서드)

unpack_opaque() (xdrlib.Unpacker 메서드)

UNPACK_SEQUENCE (opcode)

unpack_string() (xdrlib.Unpacker 메서드)

Unpacker (xdrlib 클래스)

unpacking

dictionary

in function calls

iterable

unparsedEntityDecl() (xml.sax.handler.DTDHandler 메서드)

UnparsedEntityDeclHandler() (xml.parsers.expat.xmlparser 메서드)

Unpickler (pickle 클래스)

UnpicklingError

unquote() (email.utils 모듈)

(urllib.parse 모듈)

unquote_plus() (urllib.parse 모듈)

unquote_to_bytes() (urllib.parse 모듈)

unreachable object

unreadline() (distutils.text_file.TextFile 메서드)

unrecognized escape sequence

unregister() (atexit 모듈)

(faulthandler 모듈)

(select.devpoll 메서드)

(select.epoll 메서드)

(select.poll 메서드)

(selectors.BaseSelector의 메서드)

unregister_archive_format() (shutil 모듈)

unregister_dialect() (csv 모듈)

unregister_unpack_format() (shutil 모듈)

unsafe (uuid.SafeUUID의 속성)

unset() (test.support.EnvironmentVarGuard 메서드)

unsetenv() (os 모듈)

UnstructuredHeader (email.headerregistry 클래스)

unsubscribe() (imaplib.IMAP4 메서드)

UnsupportedOperation

until (pdb command)

untokenize() (tokenize 모듈)

untouchwin() (curses.window 메서드)

unused_data (bz2.BZ2Decompressor의 속성)

(lzma.LZMADecompressor의 속성)

(zlib.Decompress의 속성)

unverifiable (urllib.request.Request의 속성)

unwrap() (inspect 모듈)

(ssl.SSLSocket 메서드)

up (pdb command)

up() (turtle 모듈)

update() (collections.Counter 메서드)

(dict 메서드)

(frozenset 메서드)

(hashlib.hash 메서드)

(hmac.HMAC 메서드)

(http.cookies.Morsel 메서드)

(mailbox.Mailbox 메서드)

(mailbox.Maildir 메서드)

(trace.CoverageResults 메서드)

(turtle 모듈)

update_authenticated() (urllib.request.HTTPPasswordMgrWithPriorAuth 메서드)

update_lines_cols() (curses 모듈)

update_panels() (curses.panel 모듈)

update_visible() (mailbox.BabylMessage 메서드)

update_wrapper() (functools 모듈)

upper() (bytearray 메서드)

(bytes 메서드)

(str 메서드)

urandom() (os 모듈)

URL, [1], [2], [3]

parsing

relative

url (xmlrpc.client.ProtocolError의 속성)

url2pathname() (urllib.request 모듈)

urlcleanup() (urllib.request 모듈)

urldefrag() (urllib.parse 모듈)

urlencode() (urllib.parse 모듈)

URLError

urljoin() (urllib.parse 모듈)

urllib (2to3 fixer)

(모듈)

urllib.error (모듈)

urllib.parse (모듈)

urllib.request

모듈

urllib.request (모듈)

urllib.response (모듈)

urllib.robotparser (모듈)

urlopen() (urllib.request 모듈)

URLopener (urllib.request 클래스)

urlparse() (urllib.parse 모듈)

urlretrieve() (urllib.request 모듈)

urlsafe_b64decode() (base64 모듈)

urlsafe_b64encode() (base64 모듈)

urlsplit() (urllib.parse 모듈)

urlunparse() (urllib.parse 모듈)

urlunsplit() (urllib.parse 모듈)

urn (uuid.UUID의 속성)

use_default_colors() (curses 모듈)

use_env() (curses 모듈)

use_rawinput (cmd.Cmd의 속성)

UseForeignDTD() (xml.parsers.expat.xmlparser 메서드)

USER

user

effective id

id

id, setting

user() (poplib.POP3 메서드)

user-defined

function

function call

method

user-defined function

객체, [1], [2]

user-defined method

객체

USER_BASE

(site 모듈)

user_call() (bdb.Bdb 메서드)

user_exception() (bdb.Bdb 메서드)

user_line() (bdb.Bdb 메서드)

user_return() (bdb.Bdb 메서드)

USER_SITE (site 모듈)

usercustomize

모듈

UserDict (collections 클래스)

UserList (collections 클래스)

USERNAME, [1]

username (email.headerregistry.Address의 속성)

USERPROFILE, [1]

userptr() (curses.panel.Panel 메서드)

UserString (collections 클래스)

UserWarning

USTAR_FORMAT (tarfile 모듈)

UTC

utc (datetime.timezone의 속성)

utcfromtimestamp() (datetime.datetime의 클래스 메서드)

utcnow() (datetime.datetime의 클래스 메서드)

utcoffset() (datetime.datetime 메서드)

(datetime.time 메서드)

(datetime.timezone 메서드)

(datetime.tzinfo 메서드)

utctimetuple() (datetime.datetime 메서드)

utf8 (email.policy.EmailPolicy의 속성)

utf8() (poplib.POP3 메서드)

utf8_enabled (imaplib.IMAP4의 속성)

utime() (os 모듈)

uu

모듈

uu (모듈)

UUID (uuid 클래스)

uuid (모듈)

uuid1

uuid1() (uuid 모듈)

uuid3

uuid3() (uuid 모듈)

uuid4

uuid4() (uuid 모듈)

uuid5

uuid5() (uuid 모듈)

UuidCreate() (msilib 모듈)

V

v4_int_to_packed() (ipaddress 모듈)

v6_int_to_packed() (ipaddress 모듈)

validator() (wsgiref.validate 모듈)

value

default parameter

truth

value (ctypes._SimpleCData의 속성)

(http.cookiejar.Cookie의 속성)

(http.cookies.Morsel의 속성)

(xml.dom.Attr의 속성)

value of an object

Value() (multiprocessing 모듈)

(multiprocessing.managers.SyncManager 메서드)

(multiprocessing.sharedctypes 모듈)

value_decode() (http.cookies.BaseCookie 메서드)

value_encode() (http.cookies.BaseCookie 메서드)

ValueError

예외

valuerefs() (weakref.WeakValueDictionary 메서드)

values

Boolean

writing

values() (contextvars.Context 메서드)

(dict 메서드)

(email.message.EmailMessage 메서드)

(email.message.Message 메서드)

(mailbox.Mailbox 메서드)

(types.MappingProxyType 메서드)

ValuesView (collections.abc 클래스)

(typing 클래스)

var (contextvars.contextvars.Token.Token의 속성)

variable

free

variable annotation (변수 어노테이션)

variance() (statistics 모듈)

variant (uuid.UUID의 속성)

vars() (내장 함수)

vbar (tkinter.scrolledtext.ScrolledText의 속성)

VBAR (token 모듈)

VBAREQUAL (token 모듈)

Vec2D (turtle 클래스)

venv (모듈)

VERBOSE (re 모듈)

verbose (tabnanny 모듈)

(test.support 모듈)

verify() (smtplib.SMTP 메서드)

verify_client_post_handshake() (ssl.SSLSocket 메서드)

verify_code (ssl.SSLCertVerificationError의 속성)

VERIFY_CRL_CHECK_CHAIN (ssl 모듈)

VERIFY_CRL_CHECK_LEAF (ssl 모듈)

VERIFY_DEFAULT (ssl 모듈)

verify_flags (ssl.SSLContext의 속성)

verify_message (ssl.SSLCertVerificationError의 속성)

verify_mode (ssl.SSLContext의 속성)

verify_request() (socketserver.BaseServer 메서드)

VERIFY_X509_STRICT (ssl 모듈)

VERIFY_X509_TRUSTED_FIRST (ssl 모듈)

VerifyFlags (ssl 클래스)

VerifyMode (ssl 클래스)

version (curses 모듈)

(email.headerregistry.MIMEVersionHeader의 속성)

(http.client.HTTPResponse의 속성)

(http.cookiejar.Cookie의 속성)

(in module sys), [1], [2]

(ipaddress.IPv4Address의 속성)

(ipaddress.IPv4Network의 속성)

(ipaddress.IPv6Address의 속성)

(ipaddress.IPv6Network의 속성)

(marshal 모듈)

(sqlite3 모듈)

(sys 모듈)

(urllib.request.URLopener의 속성)

(uuid.UUID의 속성)

version() (ensurepip 모듈)

(platform 모듈)

(ssl.SSLSocket 메서드)

version_info (sqlite3 모듈)

(sys 모듈)

version_string() (http.server.BaseHTTPRequestHandler 메서드)

vformat() (string.Formatter 메서드)

virtual

Environments

virtual environment (가상 환경)

virtual machine (가상 기계)

visit() (ast.NodeVisitor 메서드)

visitproc (C 데이터 형식)

vline() (curses.window 메서드)

voidcmd() (ftplib.FTP 메서드)

volume (zipfile.ZipInfo의 속성)

vonmisesvariate() (random 모듈)

W

W_OK (os 모듈)

wait() (asyncio 모듈)

(asyncio.asyncio.subprocess.Process의 메서드)

(asyncio.Condition의 메서드)

(asyncio.Event의 메서드)

(concurrent.futures 모듈)

(multiprocessing.connection 모듈)

(multiprocessing.pool.AsyncResult 메서드)

(os 모듈)

(subprocess.Popen 메서드)

(threading.Barrier 메서드)

(threading.Condition 메서드)

(threading.Event 메서드)

wait3() (os 모듈)

wait4() (os 모듈)

wait_closed() (asyncio.Server의 메서드)

(asyncio.StreamWriter의 메서드)

wait_for() (asyncio 모듈)

(asyncio.Condition의 메서드)

(threading.Condition 메서드)

wait_threads_exit() (test.support 모듈)

waitid() (os 모듈)

waitpid() (os 모듈)

walk() (ast 모듈)

(email.message.EmailMessage 메서드)

(email.message.Message 메서드)

(os 모듈)

walk_packages() (pkgutil 모듈)

walk_stack() (traceback 모듈)

walk_tb() (traceback 모듈)

want (doctest.Example의 속성)

warn() (distutils.ccompiler.CCompiler 메서드)

(distutils.text_file.TextFile 메서드)

(warnings 모듈)

warn_explicit() (warnings 모듈)

Warning, [1]

warning() (logging 모듈)

(logging.Logger 메서드)

(xml.sax.handler.ErrorHandler 메서드)

warnings

(모듈)

WarningsRecorder (test.support 클래스)

warnoptions (sys 모듈)

wasSuccessful() (unittest.TestResult 메서드)

WatchedFileHandler (logging.handlers 클래스)

wave (모듈)

WCONTINUED (os 모듈)

WCOREDUMP() (os 모듈)

WeakKeyDictionary (weakref 클래스)

WeakMethod (weakref 클래스)

weakref (모듈)

WeakSet (weakref 클래스)

WeakValueDictionary (weakref 클래스)

webbrowser (모듈)

weekday() (calendar 모듈)

(datetime.date 메서드)

(datetime.datetime 메서드)

weekheader() (calendar 모듈)

weibullvariate() (random 모듈)

WEXITED (os 모듈)

WEXITSTATUS() (os 모듈)

wfile (http.server.BaseHTTPRequestHandler의 속성)

what() (imghdr 모듈)

(sndhdr 모듈)

whathdr() (sndhdr 모듈)

whatis (pdb command)

when() (asyncio.TimerHandle 메서드)

where (pdb command)

which() (shutil 모듈)

whichdb() (dbm 모듈)

while

글, [1], [2], [3]

whitespace (shlex.shlex의 속성)

(string 모듈)

whitespace_split (shlex.shlex의 속성)

Widget (tkinter.ttk 클래스)

width (textwrap.TextWrapper의 속성)

width() (turtle 모듈)

WIFCONTINUED() (os 모듈)

WIFEXITED() (os 모듈)

WIFSIGNALED() (os 모듈)

WIFSTOPPED() (os 모듈)

win32_ver() (platform 모듈)

WinDLL (ctypes 클래스)

window manager (widgets)

window() (curses.panel.Panel 메서드)

window_height() (turtle 모듈)

window_width() (turtle 모듈)

Windows

Windows ini file

WindowsError

WindowsPath (pathlib 클래스)

WindowsProactorEventLoopPolicy (asyncio 클래스)

WindowsRegistryFinder (importlib.machinery 클래스)

winerror (OSError의 속성)

WinError() (ctypes 모듈)

WINFUNCTYPE() (ctypes 모듈)

winreg (모듈)

WinSock

winsound (모듈)

winver (sys 모듈)

with

글, [1]

WITH_CLEANUP_FINISH (opcode)

WITH_CLEANUP_START (opcode)

with_hostmask (ipaddress.IPv4Interface의 속성)

(ipaddress.IPv4Network의 속성)

(ipaddress.IPv6Interface의 속성)

(ipaddress.IPv6Network의 속성)

with_name() (pathlib.PurePath 메서드)

with_netmask (ipaddress.IPv4Interface의 속성)

(ipaddress.IPv4Network의 속성)

(ipaddress.IPv6Interface의 속성)

(ipaddress.IPv6Network의 속성)

with_prefixlen (ipaddress.IPv4Interface의 속성)

(ipaddress.IPv4Network의 속성)

(ipaddress.IPv6Interface의 속성)

(ipaddress.IPv6Network의 속성)

with_pymalloc() (test.support 모듈)

with_suffix() (pathlib.PurePath 메서드)

with_traceback() (BaseException 메서드)

WNOHANG (os 모듈)

WNOWAIT (os 모듈)

wordchars (shlex.shlex의 속성)

World Wide Web, [1], [2]

wrap() (textwrap 모듈)

(textwrap.TextWrapper 메서드)

wrap_bio() (ssl.SSLContext 메서드)

wrap_future() (asyncio 모듈)

wrap_socket() (ssl 모듈)

(ssl.SSLContext 메서드)

wrap_text() (distutils.fancy_getopt 모듈)

wrapper() (curses 모듈)

WrapperDescriptorType (types 모듈)

wraps() (functools 모듈)

WRITABLE (tkinter 모듈)

writable() (asyncore.dispatcher 메서드)

(io.IOBase 메서드)

write() (asyncio.StreamWriter 메서드)

(asyncio.WriteTransport 메서드)

(code.InteractiveInterpreter 메서드)

(codecs.StreamWriter 메서드)

(configparser.ConfigParser 메서드)

(email.generator.BytesGenerator 메서드)

(email.generator.Generator 메서드)

(io.BufferedIOBase 메서드)

(io.BufferedWriter 메서드)

(io.RawIOBase 메서드)

(io.TextIOBase 메서드)

(mmap.mmap 메서드)

(os 모듈)

(ossaudiodev.oss_audio_device 메서드)

(ssl.MemoryBIO 메서드)

(ssl.SSLSocket 메서드)

(telnetlib.Telnet 메서드)

(turtle 모듈)

(xml.etree.ElementTree.ElementTree 메서드)

(zipfile.ZipFile 메서드)

write_byte() (mmap.mmap 메서드)

write_bytes() (pathlib.Path 메서드)

write_docstringdict() (turtle 모듈)

write_eof() (asyncio.StreamWriter 메서드)

(asyncio.WriteTransport 메서드)

(ssl.MemoryBIO 메서드)

write_file() (distutils.file_util 모듈)

write_history_file() (readline 모듈)

WRITE_RESTRICTED

write_results() (trace.CoverageResults 메서드)

write_text() (pathlib.Path 메서드)

write_through (io.TextIOWrapper의 속성)

writeall() (ossaudiodev.oss_audio_device 메서드)

writeframes() (aifc.aifc 메서드)

(sunau.AU_write 메서드)

(wave.Wave_write 메서드)

writeframesraw() (aifc.aifc 메서드)

(sunau.AU_write 메서드)

(wave.Wave_write 메서드)

writeheader() (csv.DictWriter 메서드)

writelines() (asyncio.StreamWriter 메서드)

(asyncio.WriteTransport 메서드)

(codecs.StreamWriter 메서드)

(io.IOBase 메서드)

writePlist() (plistlib 모듈)

writePlistToBytes() (plistlib 모듈)

writepy() (zipfile.PyZipFile 메서드)

writer (formatter.formatter의 속성)

writer() (csv 모듈)

writerow() (csv.csvwriter 메서드)

writerows() (csv.csvwriter 메서드)

writestr() (zipfile.ZipFile 메서드)

WriteTransport (asyncio 클래스)

writev() (os 모듈)

writexml() (xml.dom.minidom.Node 메서드)

writing

values

WrongDocumentErr

ws_comma (2to3 fixer)

wsgi_file_wrapper (wsgiref.handlers.BaseHandler의 속성)

wsgi_multiprocess (wsgiref.handlers.BaseHandler의 속성)

wsgi_multithread (wsgiref.handlers.BaseHandler의 속성)

wsgi_run_once (wsgiref.handlers.BaseHandler의 속성)

wsgiref (모듈)

wsgiref.handlers (모듈)

wsgiref.headers (모듈)

wsgiref.simple_server (모듈)

wsgiref.util (모듈)

wsgiref.validate (모듈)

WSGIRequestHandler (wsgiref.simple_server 클래스)

WSGIServer (wsgiref.simple_server 클래스)

wShowWindow (subprocess.STARTUPINFO의 속성)

WSTOPPED (os 모듈)

WSTOPSIG() (os 모듈)

wstring_at() (ctypes 모듈)

WTERMSIG() (os 모듈)

WUNTRACED (os 모듈)

WWW, [1], [2]

server, [1]

X

X (re 모듈)

X509 certificate

X_OK (os 모듈)

xatom() (imaplib.IMAP4 메서드)

XATTR_CREATE (os 모듈)

XATTR_REPLACE (os 모듈)

XATTR_SIZE_MAX (os 모듈)

xcor() (turtle 모듈)

XDR

xdrlib (모듈)

xhdr() (nntplib.NNTP 메서드)

XHTML

XHTML_NAMESPACE (xml.dom 모듈)

xml (모듈)

XML() (xml.etree.ElementTree 모듈)

xml.dom (모듈)

xml.dom.minidom (모듈)

xml.dom.pulldom (모듈)

xml.etree.ElementInclude.default_loader() (xml.etree.ElementTree 모듈)

xml.etree.ElementInclude.include() (xml.etree.ElementTree 모듈)

xml.etree.ElementTree (모듈)

xml.parsers.expat (모듈)

xml.parsers.expat.errors (모듈)

xml.parsers.expat.model (모듈)

xml.sax (모듈)

xml.sax.handler (모듈)

xml.sax.saxutils (모듈)

xml.sax.xmlreader (모듈)

XML_ERROR_ABORTED (xml.parsers.expat.errors 모듈)

XML_ERROR_ASYNC_ENTITY (xml.parsers.expat.errors 모듈)

XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF (xml.parsers.expat.errors 모듈)

XML_ERROR_BAD_CHAR_REF (xml.parsers.expat.errors 모듈)

XML_ERROR_BINARY_ENTITY_REF (xml.parsers.expat.errors 모듈)

XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING (xml.parsers.expat.errors 모듈)

XML_ERROR_DUPLICATE_ATTRIBUTE (xml.parsers.expat.errors 모듈)

XML_ERROR_ENTITY_DECLARED_IN_PE (xml.parsers.expat.errors 모듈)

XML_ERROR_EXTERNAL_ENTITY_HANDLING (xml.parsers.expat.errors 모듈)

XML_ERROR_FEATURE_REQUIRES_XML_DTD (xml.parsers.expat.errors 모듈)

XML_ERROR_FINISHED (xml.parsers.expat.errors 모듈)

XML_ERROR_INCOMPLETE_PE (xml.parsers.expat.errors 모듈)

XML_ERROR_INCORRECT_ENCODING (xml.parsers.expat.errors 모듈)

XML_ERROR_INVALID_TOKEN (xml.parsers.expat.errors 모듈)

XML_ERROR_JUNK_AFTER_DOC_ELEMENT (xml.parsers.expat.errors 모듈)

XML_ERROR_MISPLACED_XML_PI (xml.parsers.expat.errors 모듈)

XML_ERROR_NO_ELEMENTS (xml.parsers.expat.errors 모듈)

XML_ERROR_NO_MEMORY (xml.parsers.expat.errors 모듈)

XML_ERROR_NOT_STANDALONE (xml.parsers.expat.errors 모듈)

XML_ERROR_NOT_SUSPENDED (xml.parsers.expat.errors 모듈)

XML_ERROR_PARAM_ENTITY_REF (xml.parsers.expat.errors 모듈)

XML_ERROR_PARTIAL_CHAR (xml.parsers.expat.errors 모듈)

XML_ERROR_PUBLICID (xml.parsers.expat.errors 모듈)

XML_ERROR_RECURSIVE_ENTITY_REF (xml.parsers.expat.errors 모듈)

XML_ERROR_SUSPEND_PE (xml.parsers.expat.errors 모듈)

XML_ERROR_SUSPENDED (xml.parsers.expat.errors 모듈)

XML_ERROR_SYNTAX (xml.parsers.expat.errors 모듈)

XML_ERROR_TAG_MISMATCH (xml.parsers.expat.errors 모듈)

XML_ERROR_TEXT_DECL (xml.parsers.expat.errors 모듈)

XML_ERROR_UNBOUND_PREFIX (xml.parsers.expat.errors 모듈)

XML_ERROR_UNCLOSED_CDATA_SECTION (xml.parsers.expat.errors 모듈)

XML_ERROR_UNCLOSED_TOKEN (xml.parsers.expat.errors 모듈)

XML_ERROR_UNDECLARING_PREFIX (xml.parsers.expat.errors 모듈)

XML_ERROR_UNDEFINED_ENTITY (xml.parsers.expat.errors 모듈)

XML_ERROR_UNEXPECTED_STATE (xml.parsers.expat.errors 모듈)

XML_ERROR_UNKNOWN_ENCODING (xml.parsers.expat.errors 모듈)

XML_ERROR_XML_DECL (xml.parsers.expat.errors 모듈)

XML_NAMESPACE (xml.dom 모듈)

xmlcharrefreplace_errors() (codecs 모듈)

XmlDeclHandler() (xml.parsers.expat.xmlparser 메서드)

XMLFilterBase (xml.sax.saxutils 클래스)

XMLGenerator (xml.sax.saxutils 클래스)

XMLID() (xml.etree.ElementTree 모듈)

XMLNS_NAMESPACE (xml.dom 모듈)

XMLParser (xml.etree.ElementTree 클래스)

XMLParserType (xml.parsers.expat 모듈)

XMLPullParser (xml.etree.ElementTree 클래스)

XMLReader (xml.sax.xmlreader 클래스)

xmlrpc.client (모듈)

xmlrpc.server (모듈)

xor

bitwise

xor() (operator 모듈)

xover() (nntplib.NNTP 메서드)

xpath() (nntplib.NNTP 메서드)

xrange (2to3 fixer)

xreadlines (2to3 fixer)

xview() (tkinter.ttk.Treeview 메서드)

Y

ycor() (turtle 모듈)

year (datetime.datetime의 속성)

(datetime.date의 속성)

Year 2038

yeardatescalendar() (calendar.Calendar 메서드)

yeardays2calendar() (calendar.Calendar 메서드)

yeardayscalendar() (calendar.Calendar 메서드)

YESEXPR (locale 모듈)

yield

examples

expression

yield from (in What's New)

글

키워드

YIELD_FROM (opcode)

YIELD_VALUE (opcode)

yiq_to_rgb() (colorsys 모듈)

yview() (tkinter.ttk.Treeview 메서드)

Z

Zen of Python (파이썬 젠)

ZeroDivisionError

예외

zfill() (bytearray 메서드)

(bytes 메서드)

(str 메서드)

zip (2to3 fixer)

zip() (내장 함수)

ZIP_BZIP2 (zipfile 모듈)

ZIP_DEFLATED (zipfile 모듈)

zip_longest() (itertools 모듈)

ZIP_LZMA (zipfile 모듈)

ZIP_STORED (zipfile 모듈)

zipapp (모듈)

zipapp command line option

--compress

--help

--info

--main=<mainfn>

--output=<output>

--python=<interpreter>

-c

-h

-m <mainfn>

-o <output>

-p <interpreter>

ZipFile (zipfile 클래스)

zipfile (모듈)

zipfile command line option

--create <zipfile> <source1> ... <sourceN>

--extract <zipfile> <output_dir>

--list <zipfile>

--test <zipfile>

-c <zipfile> <source1> ... <sourceN>

-e <zipfile> <output_dir>

-l <zipfile>

-t <zipfile>

zipimport (모듈)

zipimporter (zipimport 클래스)

ZipImportError

ZipInfo (zipfile 클래스)

zlib (모듈)

ZLIB_RUNTIME_VERSION (zlib 모듈)

ZLIB_VERSION (zlib 모듈)

ᄀ

객체

asynchronous-generator

Boolean, [1]

built-in function, [1]

built-in method, [1]

bytearray, [1], [2], [3]

bytes, [1], [2]

callable, [1]

Capsule

class, [1], [2]

class instance, [1], [2]

complex

complex number, [1]

dictionary, [1], [2], [3], [4], [5], [6], [7]

Ellipsis

file, [1]

floating point, [1], [2]

frame

frozenset, [1]

function, [1], [2], [3], [4], [5]

generator, [1], [2]

immutable

immutable sequence

instance, [1], [2]

instancemethod

integer, [1], [2]

io.StringIO

list, [1], [2], [3], [4], [5], [6], [7], [8]

long integer

mapping, [1], [2], [3], [4], [5]

memoryview, [1]

method, [1], [2], [3], [4], [5]

module, [1], [2]

mutable, [1], [2]

mutable sequence

None, [1], [2]

NotImplemented

numeric, [1], [2], [3]

range

sequence, [1], [2], [3], [4], [5], [6], [7], [8]

set, [1], [2], [3]

set type

slice

socket

string, [1], [2]

traceback, [1], [2], [3], [4]

tuple, [1], [2], [3], [4], [5], [6]

type, [1], [2]

user-defined function, [1], [2]

user-defined method

글

assert, [1]

async def

async for

async with

break, [1], [2], [3], [4]

class

continue, [1], [2], [3], [4]

def

del, [1], [2], [3]

except

for, [1], [2], [3]

global, [1]

if, [1]

import, [1], [2], [3], [4]

nonlocal

pass

raise, [1]

return, [1], [2]

try, [1], [2]

while, [1], [2], [3]

with, [1]

yield

ᄂ

내장 함수

__import__

abs, [1]

ascii

bytes, [1]

chr

classmethod

compile, [1], [2], [3], [4]

complex, [1]

divmod, [1], [2]

eval, [1], [2], [3], [4], [5]

exec, [1], [2], [3]

float, [1], [2]

hash, [1], [2], [3]

help

id

int, [1], [2]

len, [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11]

max

min

open, [1]

ord

pow, [1], [2], [3], [4], [5]

print

range

repr, [1], [2], [3]

round

slice, [1]

staticmethod

tuple, [1]

type, [1], [2], [3]

ᄆ

모듈

__main__, [1], [2], [3], [4], [5], [6], [7]

_locale

_thread

array, [1]

base64

bdb

binhex

builtins, [1], [2], [3], [4]

cmd

copy

crypt

dbm.gnu, [1]

dbm.ndbm, [1]

errno

glob

imp

io

json

math, [1]

os

pickle, [1], [2], [3]

pty

pwd

pyexpat

re, [1]

shelve

signal, [1]

sitecustomize

socket

stat

string

struct

sys, [1], [2], [3], [4], [5], [6]

types

urllib.request

usercustomize

uu

ᄋ

연산자

!=, [1]

% (percent), [1]

& (ampersand), [1]

* (asterisk), [1]

**, [1]

/ (slash), [1]

//, [1]

< (less), [1]

<<, [1]

<=, [1]

==, [1]

> (greater), [1]

>=, [1]

>>, [1]

@ (at)

^ (caret), [1]

| (vertical bar), [1]

~ (tilde), [1]

and, [1], [2]

in, [1], [2]

is, [1]

is not, [1]

not, [1]

not in, [1], [2]

or, [1], [2]

예외

AssertionError

AttributeError

GeneratorExit, [1]

ImportError

NameError

StopAsyncIteration

StopIteration, [1]

TypeError

ValueError

ZeroDivisionError

ᄏ

키워드

as, [1], [2]

async

await, [1]

elif

else, [1], [2], [3], [4], [5]

except

finally, [1], [2], [3], [4]

from, [1]

in

yield

ᄑ

파이썬 향상 제안

PEP 1

PEP 100

PEP 11, [1], [2], [3], [4]

PEP 205, [1]

PEP 207

PEP 208

PEP 217

PEP 218, [1], [2]

PEP 227, [1], [2]

PEP 229

PEP 230

PEP 232

PEP 234

PEP 235

PEP 236, [1]

PEP 237, [1], [2], [3], [4], [5]

PEP 238, [1], [2], [3], [4], [5], [6]

PEP 241

PEP 243

PEP 247

PEP 249, [1], [2], [3]

PEP 252, [1]

PEP 253, [1], [2], [3], [4]

PEP 255, [1], [2], [3], [4], [5]

PEP 261, [1]

PEP 263, [1], [2], [3], [4], [5]

PEP 264

PEP 273, [1], [2]

PEP 274

PEP 275

PEP 277

PEP 278, [1]

PEP 279

PEP 282, [1], [2], [3]

PEP 285, [1]

PEP 288

PEP 289, [1], [2]

PEP 292, [1]

PEP 293

PEP 3000

PEP 301, [1]

PEP 302, [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12], [13], [14], [15], [16], [17], [18], [19], [20], [21], [22], [23], [24], [25], [26]

PEP 305, [1]

PEP 307, [1], [2], [3]

PEP 308, [1], [2]

PEP 309

PEP 3100

PEP 3101, [1], [2], [3], [4]

PEP 3102

PEP 3104, [1]

PEP 3105, [1], [2]

PEP 3106

PEP 3107, [1], [2], [3], [4]

PEP 3108, [1], [2]

PEP 3109, [1]

PEP 3110, [1], [2]

PEP 3111

PEP 3112, [1]

PEP 3113

PEP 3114

PEP 3115, [1], [2], [3]

PEP 3116, [1], [2]

PEP 3118, [1], [2], [3], [4], [5]

PEP 3119, [1], [2], [3], [4], [5]

PEP 3120, [1], [2]

PEP 3121, [1], [2]

PEP 3123

PEP 3127

PEP 3129, [1]

PEP 3131, [1], [2]

PEP 3132, [1]

PEP 3134, [1], [2]

PEP 3135, [1]

PEP 3137

PEP 3138

PEP 314, [1]

PEP 3141, [1], [2]

PEP 3144

PEP 3147, [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12], [13], [14], [15], [16], [17], [18], [19], [20], [21]

PEP 3148, [1]

PEP 3149, [1]

PEP 3151, [1], [2], [3], [4], [5]

PEP 3154, [1], [2]

PEP 3155, [1]

PEP 3156, [1], [2], [3], [4]

PEP 318, [1], [2], [3]

PEP 322, [1]

PEP 324, [1]

PEP 325

PEP 327

PEP 328, [1], [2], [3], [4], [5], [6], [7], [8]

PEP 331

PEP 333, [1]

PEP 3333, [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12], [13], [14]

PEP 338, [1], [2], [3]

PEP 339

PEP 341

PEP 342, [1], [2], [3], [4], [5], [6]

PEP 343, [1], [2], [3], [4], [5], [6]

PEP 347

PEP 352, [1], [2]

PEP 353, [1], [2]

PEP 356

PEP 357

PEP 361

PEP 362, [1], [2], [3]

PEP 366, [1], [2], [3], [4], [5], [6]

PEP 370, [1], [2], [3], [4]

PEP 371

PEP 372, [1]

PEP 373

PEP 378, [1], [2]

PEP 380, [1]

PEP 383, [1], [2], [3], [4]

PEP 384, [1]

PEP 385

PEP 389, [1]

PEP 391, [1]

PEP 392

PEP 393, [1], [2], [3], [4], [5], [6], [7], [8], [9], [10]

PEP 395

PEP 397, [1], [2], [3]

PEP 398

PEP 4

PEP 405, [1]

PEP 409

PEP 411, [1], [2], [3], [4], [5], [6]

PEP 412

PEP 414, [1]

PEP 418

PEP 420, [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11]

PEP 421, [1], [2]

PEP 424, [1]

PEP 427

PEP 428, [1], [2]

PEP 429

PEP 432

PEP 434

PEP 435, [1], [2]

PEP 436, [1], [2]

PEP 441, [1]

PEP 442, [1], [2], [3], [4], [5], [6]

PEP 443, [1], [2]

PEP 445, [1], [2], [3]

PEP 446, [1], [2], [3]

PEP 448, [1], [2], [3], [4]

PEP 450, [1], [2]

PEP 451, [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12]

PEP 453, [1], [2], [3], [4], [5], [6], [7], [8], [9], [10]

PEP 454, [1], [2]

PEP 456, [1]

PEP 461, [1], [2]

PEP 465, [1], [2]

PEP 466, [1], [2], [3]

PEP 468, [1]

PEP 471, [1]

PEP 475, [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12], [13], [14], [15], [16], [17], [18], [19], [20], [21], [22], [23], [24], [25], [26], [27]

PEP 476

PEP 477

PEP 478

PEP 479, [1], [2], [3], [4], [5], [6]

PEP 483, [1]

PEP 484, [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12], [13], [14], [15], [16], [17], [18], [19]

PEP 485, [1], [2], [3]

PEP 486, [1]

PEP 487, [1], [2], [3]

PEP 488, [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12]

PEP 489, [1], [2], [3], [4], [5], [6], [7], [8], [9]

PEP 492, [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12], [13], [14], [15], [16], [17], [18], [19], [20]

PEP 493

PEP 494

PEP 495, [1]

PEP 498, [1], [2], [3]

PEP 5, [1]

PEP 506, [1]

PEP 511

PEP 515, [1], [2]

PEP 519, [1]

PEP 520

PEP 523, [1]

PEP 524, [1], [2], [3], [4], [5]

PEP 525, [1], [2], [3], [4], [5], [6]

PEP 526, [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11]

PEP 528, [1], [2]

PEP 529, [1], [2], [3], [4], [5], [6]

PEP 530, [1], [2]

PEP 538, [1], [2], [3], [4]

PEP 539, [1], [2]

PEP 540, [1], [2], [3]

PEP 545, [1]

PEP 552, [1], [2], [3], [4], [5]

PEP 553, [1]

PEP 557, [1]

PEP 560, [1], [2], [3], [4], [5], [6]

PEP 562, [1], [2], [3]

PEP 563, [1], [2]

PEP 564, [1], [2], [3]

PEP 565

PEP 567, [1], [2], [3], [4], [5], [6], [7]

PEP 570

PEP 6

PEP 628, [1]

PEP 7, [1], [2], [3]

PEP 8, [1], [2], [3], [4]

ᄒ

환경 변수

APPDATA

AUDIODEV

BROWSER, [1]

CC

CFLAGS, [1], [2]

COLS, [1]

COLUMNS, [1]

COMSPEC, [1]

CPP

CPPFLAGS

DISTUTILS_DEBUG

exec_prefix, [1], [2]

HOME, [1], [2], [3], [4]

HOMEDRIVE, [1]

HOMEPATH, [1]

http_proxy, [1], [2]

IDLESTARTUP, [1], [2]

KDEDIR

LANG, [1], [2], [3], [4]

LANGUAGE, [1]

LC_ALL, [1]

LC_MESSAGES, [1]

LDCXXSHARED

LDFLAGS

LINES, [1], [2], [3], [4]

LNAME

LOGNAME, [1]

MIXERDEV

no_proxy

PAGER

PATH, [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12], [13], [14], [15], [16], [17], [18], [19], [20], [21], [22], [23], [24], [25], [26], [27], [28], [29], [30], [31], [32], [33], [34], [35]

PATHEXT, [1]

PLAT

POSIXLY_CORRECT

prefix, [1], [2], [3]

PY_PYTHON

PYTHON*, [1], [2], [3], [4], [5]

PYTHON_DOM

PYTHONASYNCIODEBUG, [1], [2]

PYTHONBREAKPOINT, [1], [2], [3], [4]

PYTHONCASEOK, [1]

PYTHONCOERCECLOCALE, [1], [2]

PYTHONDEBUG, [1], [2]

PYTHONDEVMODE, [1], [2]

PYTHONDOCS

PYTHONDONTWRITEBYTECODE, [1], [2], [3], [4], [5], [6]

PYTHONDUMPREFS, [1]

PYTHONEXECUTABLE

PYTHONFAULTHANDLER, [1], [2]

PYTHONHASHSEED, [1], [2], [3], [4], [5], [6], [7], [8], [9]

PYTHONHOME, [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12], [13], [14], [15], [16]

PYTHONINSPECT, [1], [2], [3]

PYTHONINTMAXSTRDIGITS, [1], [2], [3], [4], [5]

PYTHONIOENCODING, [1], [2], [3], [4], [5], [6], [7]

PYTHONLEGACYWINDOWSFSENCODING, [1], [2], [3]

PYTHONLEGACYWINDOWSSTDIO, [1], [2], [3], [4]

PYTHONMALLOC, [1], [2], [3], [4], [5], [6], [7]

PYTHONMALLOCSTATS, [1], [2]

PYTHONNOUSERSITE, [1], [2], [3], [4]

PYTHONOPTIMIZE, [1], [2]

PYTHONPATH, [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12], [13], [14], [15], [16], [17], [18], [19], [20], [21], [22], [23], [24]

PYTHONPROFILEIMPORTTIME, [1], [2], [3]

PYTHONSHOWALLOCCOUNT

PYTHONSHOWREFCOUNT

PYTHONSTARTUP, [1], [2], [3], [4], [5], [6], [7], [8], [9], [10]

PYTHONTHREADDEBUG

PYTHONTRACEMALLOC, [1], [2], [3]

PYTHONUNBUFFERED, [1], [2]

PYTHONUSERBASE, [1], [2], [3]

PYTHONUSERSITE

PYTHONUTF8, [1], [2], [3], [4], [5]

PYTHONVERBOSE, [1], [2]

PYTHONWARNINGS, [1], [2], [3], [4], [5], [6], [7], [8]

SOURCE_DATE_EPOCH, [1], [2], [3], [4], [5], [6]

SSL_CERT_FILE

SSL_CERT_PATH

SystemRoot

TCL_LIBRARY

TEMP

TERM, [1]

TK_LIBRARY

TMP

TMPDIR

TZ, [1], [2], [3], [4], [5]

USER

USER_BASE

USERNAME, [1]

USERPROFILE, [1]

탐색

색인

모듈 |

Python »

3.7.17 Documentation »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

Python »

3.7.17 Documentation »

|

Index – ᄀ

객체

asynchronous-generator

Boolean, [1]

built-in function, [1]

built-in method, [1]

bytearray, [1], [2], [3]

bytes, [1], [2]

callable, [1]

Capsule

class, [1], [2]

class instance, [1], [2]

complex

complex number, [1]

dictionary, [1], [2], [3], [4], [5], [6], [7]

Ellipsis

file, [1]

floating point, [1], [2]

frame

frozenset, [1]

function, [1], [2], [3], [4], [5]

generator, [1], [2]

immutable

immutable sequence

instance, [1], [2]

instancemethod

integer, [1], [2]

io.StringIO

list, [1], [2], [3], [4], [5], [6], [7], [8]

long integer

mapping, [1], [2], [3], [4], [5]

memoryview, [1]

method, [1], [2], [3], [4], [5]

module, [1], [2]

mutable, [1], [2]

mutable sequence

None, [1], [2]

NotImplemented

numeric, [1], [2], [3]

range

sequence, [1], [2], [3], [4], [5], [6], [7], [8]

set, [1], [2], [3]

set type

slice

socket

string, [1], [2]

traceback, [1], [2], [3], [4]

tuple, [1], [2], [3], [4], [5], [6]

type, [1], [2]

user-defined function, [1], [2]

user-defined method

글

assert, [1]

async def

async for

async with

break, [1], [2], [3], [4]

class

continue, [1], [2], [3], [4]

def

del, [1], [2], [3]

except

for, [1], [2], [3]

global, [1]

if, [1]

import, [1], [2], [3], [4]

nonlocal

pass

raise, [1]

return, [1], [2]

try, [1], [2]

while, [1], [2], [3]

with, [1]

yield

탐색

색인

모듈 |

Python »

3.7.17 Documentation »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

Python »

3.7.17 Documentation »

|

Index – ᄂ

내장 함수

__import__

abs, [1]

ascii

bytes, [1]

chr

classmethod

compile, [1], [2], [3], [4]

complex, [1]

divmod, [1], [2]

eval, [1], [2], [3], [4], [5]

exec, [1], [2], [3]

float, [1], [2]

hash, [1], [2], [3]

help

id

int, [1], [2]

len, [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11]

max

min

open, [1]

ord

pow, [1], [2], [3], [4], [5]

print

range

repr, [1], [2], [3]

round

slice, [1]

staticmethod

tuple, [1]

type, [1], [2], [3]

탐색

색인

모듈 |

Python »

3.7.17 Documentation »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

Python »

3.7.17 Documentation »

|

Index – ᄆ

모듈

__main__, [1], [2], [3], [4], [5], [6], [7]

_locale

_thread

array, [1]

base64

bdb

binhex

builtins, [1], [2], [3], [4]

cmd

copy

crypt

dbm.gnu, [1]

dbm.ndbm, [1]

errno

glob

imp

io

json

math, [1]

os

pickle, [1], [2], [3]

pty

pwd

pyexpat

re, [1]

shelve

signal, [1]

sitecustomize

socket

stat

string

struct

sys, [1], [2], [3], [4], [5], [6]

types

urllib.request

usercustomize

uu

탐색

색인

모듈 |

Python »

3.7.17 Documentation »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

Python »

3.7.17 Documentation »

|

Index – ᄋ

연산자

!=, [1]

% (percent), [1]

& (ampersand), [1]

* (asterisk), [1]

**, [1]

/ (slash), [1]

//, [1]

< (less), [1]

<<, [1]

<=, [1]

==, [1]

> (greater), [1]

>=, [1]

>>, [1]

@ (at)

^ (caret), [1]

| (vertical bar), [1]

~ (tilde), [1]

and, [1], [2]

in, [1], [2]

is, [1]

is not, [1]

not, [1]

not in, [1], [2]

or, [1], [2]

예외

AssertionError

AttributeError

GeneratorExit, [1]

ImportError

NameError

StopAsyncIteration

StopIteration, [1]

TypeError

ValueError

ZeroDivisionError

탐색

색인

모듈 |

Python »

3.7.17 Documentation »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

Python »

3.7.17 Documentation »

|

Index – ᄏ

키워드

as, [1], [2]

async

await, [1]

elif

else, [1], [2], [3], [4], [5]

except

finally, [1], [2], [3], [4]

from, [1]

in

yield

탐색

색인

모듈 |

Python »

3.7.17 Documentation »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

Python »

3.7.17 Documentation »

|

Index – ᄑ

파이썬 향상 제안

PEP 1

PEP 100

PEP 11, [1], [2], [3], [4]

PEP 205, [1]

PEP 207

PEP 208

PEP 217

PEP 218, [1], [2]

PEP 227, [1], [2]

PEP 229

PEP 230

PEP 232

PEP 234

PEP 235

PEP 236, [1]

PEP 237, [1], [2], [3], [4], [5]

PEP 238, [1], [2], [3], [4], [5], [6]

PEP 241

PEP 243

PEP 247

PEP 249, [1], [2], [3]

PEP 252, [1]

PEP 253, [1], [2], [3], [4]

PEP 255, [1], [2], [3], [4], [5]

PEP 261, [1]

PEP 263, [1], [2], [3], [4], [5]

PEP 264

PEP 273, [1], [2]

PEP 274

PEP 275

PEP 277

PEP 278, [1]

PEP 279

PEP 282, [1], [2], [3]

PEP 285, [1]

PEP 288

PEP 289, [1], [2]

PEP 292, [1]

PEP 293

PEP 3000

PEP 301, [1]

PEP 302, [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12], [13], [14], [15], [16], [17], [18], [19], [20], [21], [22], [23], [24], [25], [26]

PEP 305, [1]

PEP 307, [1], [2], [3]

PEP 308, [1], [2]

PEP 309

PEP 3100

PEP 3101, [1], [2], [3], [4]

PEP 3102

PEP 3104, [1]

PEP 3105, [1], [2]

PEP 3106

PEP 3107, [1], [2], [3], [4]

PEP 3108, [1], [2]

PEP 3109, [1]

PEP 3110, [1], [2]

PEP 3111

PEP 3112, [1]

PEP 3113

PEP 3114

PEP 3115, [1], [2], [3]

PEP 3116, [1], [2]

PEP 3118, [1], [2], [3], [4], [5]

PEP 3119, [1], [2], [3], [4], [5]

PEP 3120, [1], [2]

PEP 3121, [1], [2]

PEP 3123

PEP 3127

PEP 3129, [1]

PEP 3131, [1], [2]

PEP 3132, [1]

PEP 3134, [1], [2]

PEP 3135, [1]

PEP 3137

PEP 3138

PEP 314, [1]

PEP 3141, [1], [2]

PEP 3144

PEP 3147, [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12], [13], [14], [15], [16], [17], [18], [19], [20], [21]

PEP 3148, [1]

PEP 3149, [1]

PEP 3151, [1], [2], [3], [4], [5]

PEP 3154, [1], [2]

PEP 3155, [1]

PEP 3156, [1], [2], [3], [4]

PEP 318, [1], [2], [3]

PEP 322, [1]

PEP 324, [1]

PEP 325

PEP 327

PEP 328, [1], [2], [3], [4], [5], [6], [7], [8]

PEP 331

PEP 333, [1]

PEP 3333, [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12], [13], [14]

PEP 338, [1], [2], [3]

PEP 339

PEP 341

PEP 342, [1], [2], [3], [4], [5], [6]

PEP 343, [1], [2], [3], [4], [5], [6]

PEP 347

PEP 352, [1], [2]

PEP 353, [1], [2]

PEP 356

PEP 357

PEP 361

PEP 362, [1], [2], [3]

PEP 366, [1], [2], [3], [4], [5], [6]

PEP 370, [1], [2], [3], [4]

PEP 371

PEP 372, [1]

PEP 373

PEP 378, [1], [2]

PEP 380, [1]

PEP 383, [1], [2], [3], [4]

PEP 384, [1]

PEP 385

PEP 389, [1]

PEP 391, [1]

PEP 392

PEP 393, [1], [2], [3], [4], [5], [6], [7], [8], [9], [10]

PEP 395

PEP 397, [1], [2], [3]

PEP 398

PEP 4

PEP 405, [1]

PEP 409

PEP 411, [1], [2], [3], [4], [5], [6]

PEP 412

PEP 414, [1]

PEP 418

PEP 420, [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11]

PEP 421, [1], [2]

PEP 424, [1]

PEP 427

PEP 428, [1], [2]

PEP 429

PEP 432

PEP 434

PEP 435, [1], [2]

PEP 436, [1], [2]

PEP 441, [1]

PEP 442, [1], [2], [3], [4], [5], [6]

PEP 443, [1], [2]

PEP 445, [1], [2], [3]

PEP 446, [1], [2], [3]

PEP 448, [1], [2], [3], [4]

PEP 450, [1], [2]

PEP 451, [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12]

PEP 453, [1], [2], [3], [4], [5], [6], [7], [8], [9], [10]

PEP 454, [1], [2]

PEP 456, [1]

PEP 461, [1], [2]

PEP 465, [1], [2]

PEP 466, [1], [2], [3]

PEP 468, [1]

PEP 471, [1]

PEP 475, [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12], [13], [14], [15], [16], [17], [18], [19], [20], [21], [22], [23], [24], [25], [26], [27]

PEP 476

PEP 477

PEP 478

PEP 479, [1], [2], [3], [4], [5], [6]

PEP 483, [1]

PEP 484, [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12], [13], [14], [15], [16], [17], [18], [19]

PEP 485, [1], [2], [3]

PEP 486, [1]

PEP 487, [1], [2], [3]

PEP 488, [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12]

PEP 489, [1], [2], [3], [4], [5], [6], [7], [8], [9]

PEP 492, [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12], [13], [14], [15], [16], [17], [18], [19], [20]

PEP 493

PEP 494

PEP 495, [1]

PEP 498, [1], [2], [3]

PEP 5, [1]

PEP 506, [1]

PEP 511

PEP 515, [1], [2]

PEP 519, [1]

PEP 520

PEP 523, [1]

PEP 524, [1], [2], [3], [4], [5]

PEP 525, [1], [2], [3], [4], [5], [6]

PEP 526, [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11]

PEP 528, [1], [2]

PEP 529, [1], [2], [3], [4], [5], [6]

PEP 530, [1], [2]

PEP 538, [1], [2], [3], [4]

PEP 539, [1], [2]

PEP 540, [1], [2], [3]

PEP 545, [1]

PEP 552, [1], [2], [3], [4], [5]

PEP 553, [1]

PEP 557, [1]

PEP 560, [1], [2], [3], [4], [5], [6]

PEP 562, [1], [2], [3]

PEP 563, [1], [2]

PEP 564, [1], [2], [3]

PEP 565

PEP 567, [1], [2], [3], [4], [5], [6], [7]

PEP 570

PEP 6

PEP 628, [1]

PEP 7, [1], [2], [3]

PEP 8, [1], [2], [3], [4]

탐색

색인

모듈 |

Python »

3.7.17 Documentation »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

Python »

3.7.17 Documentation »

|

Index – ᄒ

환경 변수

APPDATA

AUDIODEV

BROWSER, [1]

CC

CFLAGS, [1], [2]

COLS, [1]

COLUMNS, [1]

COMSPEC, [1]

CPP

CPPFLAGS

DISTUTILS_DEBUG

exec_prefix, [1], [2]

HOME, [1], [2], [3], [4]

HOMEDRIVE, [1]

HOMEPATH, [1]

http_proxy, [1], [2]

IDLESTARTUP, [1], [2]

KDEDIR

LANG, [1], [2], [3], [4]

LANGUAGE, [1]

LC_ALL, [1]

LC_MESSAGES, [1]

LDCXXSHARED

LDFLAGS

LINES, [1], [2], [3], [4]

LNAME

LOGNAME, [1]

MIXERDEV

no_proxy

PAGER

PATH, [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12], [13], [14], [15], [16], [17], [18], [19], [20], [21], [22], [23], [24], [25], [26], [27], [28], [29], [30], [31], [32], [33], [34], [35]

PATHEXT, [1]

PLAT

POSIXLY_CORRECT

prefix, [1], [2], [3]

PY_PYTHON

PYTHON*, [1], [2], [3], [4], [5]

PYTHON_DOM

PYTHONASYNCIODEBUG, [1], [2]

PYTHONBREAKPOINT, [1], [2], [3], [4]

PYTHONCASEOK, [1]

PYTHONCOERCECLOCALE, [1], [2]

PYTHONDEBUG, [1], [2]

PYTHONDEVMODE, [1], [2]

PYTHONDOCS

PYTHONDONTWRITEBYTECODE, [1], [2], [3], [4], [5], [6]

PYTHONDUMPREFS, [1]

PYTHONEXECUTABLE

PYTHONFAULTHANDLER, [1], [2]

PYTHONHASHSEED, [1], [2], [3], [4], [5], [6], [7], [8], [9]

PYTHONHOME, [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12], [13], [14], [15], [16]

PYTHONINSPECT, [1], [2], [3]

PYTHONINTMAXSTRDIGITS, [1], [2], [3], [4], [5]

PYTHONIOENCODING, [1], [2], [3], [4], [5], [6], [7]

PYTHONLEGACYWINDOWSFSENCODING, [1], [2], [3]

PYTHONLEGACYWINDOWSSTDIO, [1], [2], [3], [4]

PYTHONMALLOC, [1], [2], [3], [4], [5], [6], [7]

PYTHONMALLOCSTATS, [1], [2]

PYTHONNOUSERSITE, [1], [2], [3], [4]

PYTHONOPTIMIZE, [1], [2]

PYTHONPATH, [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12], [13], [14], [15], [16], [17], [18], [19], [20], [21], [22], [23], [24]

PYTHONPROFILEIMPORTTIME, [1], [2], [3]

PYTHONSHOWALLOCCOUNT

PYTHONSHOWREFCOUNT

PYTHONSTARTUP, [1], [2], [3], [4], [5], [6], [7], [8], [9], [10]

PYTHONTHREADDEBUG

PYTHONTRACEMALLOC, [1], [2], [3]

PYTHONUNBUFFERED, [1], [2]

PYTHONUSERBASE, [1], [2], [3]

PYTHONUSERSITE

PYTHONUTF8, [1], [2], [3], [4], [5]

PYTHONVERBOSE, [1], [2]

PYTHONWARNINGS, [1], [2], [3], [4], [5], [6], [7], [8]

SOURCE_DATE_EPOCH, [1], [2], [3], [4], [5], [6]

SSL_CERT_FILE

SSL_CERT_PATH

SystemRoot

TCL_LIBRARY

TEMP

TERM, [1]

TK_LIBRARY

TMP

TMPDIR

TZ, [1], [2], [3], [4], [5]

USER

USER_BASE

USERNAME, [1]

USERPROFILE, [1]

탐색

색인

모듈 |

Python »

3.7.17 Documentation »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

Python »

3.7.17 Documentation »

|

Index – 기호

! (exclamation)

in a command interpreter

in curses module

in formatted string literal

in glob-style wildcards, [1]

in string formatting

in struct format strings

! (pdb command)

!=

연산자, [1]

" (double quote)

string literal

"""

string literal

# (hash)

comment, [1], [2]

in doctests

in printf-style formatting, [1]

in regular expressions

in string formatting

source encoding declaration

$ (dollar)

environment variables expansion

in regular expressions

in template strings

interpolation in configuration files

% (percent)

datetime format, [1], [2]

environment variables expansion (Windows), [1]

interpolation in configuration files

printf-style formatting, [1]

연산자, [1]

%=

augmented assignment

& (ampersand)

연산자, [1]

&=

augmented assignment

' (single quote)

string literal

'''

string literal

() (parentheses)

call

class definition

function definition

generator expression

in assignment target list

in printf-style formatting, [1]

in regular expressions

tuple display

(?

in regular expressions

(?!

in regular expressions

(?#

in regular expressions

(?:

in regular expressions

(?<!

in regular expressions

(?<=

in regular expressions

(?=

in regular expressions

(?P<

in regular expressions

(?P=

in regular expressions

* (asterisk)

function definition

import statement

in argparse module

in assignment target list

in AST grammar

in expression lists

in function calls, [1]

in glob-style wildcards, [1]

in printf-style formatting, [1]

in regular expressions

연산자, [1]

**

function definition

in dictionary displays

in function calls, [1]

in glob-style wildcards

연산자, [1]

**=

augmented assignment

*=

augmented assignment

*?

in regular expressions

+ (plus)

binary operator, [1]

in argparse module

in doctests

in printf-style formatting, [1]

in regular expressions

in string formatting

unary operator, [1]

+=

augmented assignment

+?

in regular expressions

, (comma)

argument list

expression list, [1], [2], [3], [4]

identifier list, [1]

import statement

in dictionary displays

in string formatting

in target list

parameter list

slicing

with statement

- (minus)

binary operator, [1]

in doctests

in glob-style wildcards, [1]

in printf-style formatting, [1]

in regular expressions

in string formatting

unary operator, [1]

--annotate

pickletools command line option

--buffer

unittest command line option

--catch

unittest command line option

--check-hash-based-pycs default|always|never

command line option

--compress

zipapp command line option

--count

trace command line option

--coverdir=<dir>

trace command line option

--create <tarfile> <source1> ... <sourceN>

tarfile command line option

--create <zipfile> <source1> ... <sourceN>

zipfile command line option

--details

inspect command line option

--exact

tokenize command line option

--extract <tarfile> [<output_dir>]

tarfile command line option

--extract <zipfile> <output_dir>

zipfile command line option

--failfast

unittest command line option

--file=<file>

trace command line option

--help

command line option

json.tool command line option

timeit command line option

tokenize command line option

trace command line option

zipapp command line option

--ignore-dir=<dir>

trace command line option

--ignore-module=<mod>

trace command line option

--indentlevel=<num>

pickletools command line option

--info

zipapp command line option

--invalidation-mode [timestamp|checked-hash|unchecked-hash]

compileall command line option

--list <tarfile>

tarfile command line option

--list <zipfile>

zipfile command line option

--listfuncs

trace command line option

--locals

unittest command line option

--main=<mainfn>

zipapp command line option

--memo

pickletools command line option

--missing

trace command line option

--no-report

trace command line option

--number=N

timeit command line option

--output=<file>

pickletools command line option

--output=<output>

zipapp command line option

--pattern pattern

unittest-discover command line option

--preamble=<preamble>

pickletools command line option

--process

timeit command line option

--python=<interpreter>

zipapp command line option

--repeat=N

timeit command line option

--report

trace command line option

--setup=S

timeit command line option

--sort-keys

json.tool command line option

--start-directory directory

unittest-discover command line option

--summary

trace command line option

--test <tarfile>

tarfile command line option

--test <zipfile>

zipfile command line option

--timing

trace command line option

--top-level-directory directory

unittest-discover command line option

--trace

trace command line option

--trackcalls

trace command line option

--unit=U

timeit command line option

--user-base

site command line option

--user-site

site command line option

--verbose

tarfile command line option

timeit command line option

unittest-discover command line option

--version

command line option

trace command line option

-=

augmented assignment

->

function annotations, [1]

-?

command line option

-a

pickletools command line option

-B

command line option

-b

command line option

compileall command line option

unittest command line option

-C

trace command line option

-c

trace command line option

unittest command line option

zipapp command line option

-c <command>

command line option

-c <tarfile> <source1> ... <sourceN>

tarfile command line option

-c <zipfile> <source1> ... <sourceN>

zipfile command line option

-d

command line option

-d destdir

compileall command line option

-E

command line option

-e

tokenize command line option

-e <tarfile> [<output_dir>]

tarfile command line option

-e <zipfile> <output_dir>

zipfile command line option

-f

compileall command line option

trace command line option

unittest command line option

-g

trace command line option

-h

command line option

json.tool command line option

timeit command line option

tokenize command line option

zipapp command line option

-I

command line option

-i

command line option

-i list

compileall command line option

-J

command line option

-j N

compileall command line option

-k

unittest command line option

-l

compileall command line option

pickletools command line option

trace command line option

-l <tarfile>

tarfile command line option

-l <zipfile>

zipfile command line option

-m

pickletools command line option

trace command line option

-m <mainfn>

zipapp command line option

-m <module-name>

command line option

-n N

timeit command line option

-O

command line option

-o

pickletools command line option

-o <output>

zipapp command line option

-OO

command line option

-p

pickletools command line option

timeit command line option

unittest-discover command line option

-p <interpreter>

zipapp command line option

-q

command line option

compileall command line option

-R

command line option

trace command line option

-r

compileall command line option

trace command line option

-r N

timeit command line option

-S

command line option

-s

command line option

trace command line option

unittest-discover command line option

-s S

timeit command line option

-T

trace command line option

-t

trace command line option

unittest-discover command line option

-t <tarfile>

tarfile command line option

-t <zipfile>

zipfile command line option

-u

command line option

timeit command line option

-V

command line option

-v

command line option

tarfile command line option

timeit command line option

unittest-discover command line option

-W arg

command line option

-X

command line option

-x

command line option

-x regex

compileall command line option

. (dot)

attribute reference

in glob-style wildcards

in numeric literal

in pathnames, [1]

in printf-style formatting, [1]

in regular expressions

in string formatting

in Tkinter

..

in pathnames

...

ellipsis literal, [1], [2]

in doctests

interpreter prompt, [1]

placeholder, [1], [2]

.ini

file

.pdbrc

file

/ (slash)

in pathnames, [1]

연산자, [1]

//

연산자, [1]

//=

augmented assignment

/=

augmented assignment

0b

integer literal

0o

integer literal

0x

integer literal

2-digit years

2to3

: (colon)

annotated variable

compound statement, [1], [2], [3], [4], [5], [6]

function annotations, [1]

in dictionary expressions

in formatted string literal

in SQL statements

in string formatting

lambda expression

path separator (POSIX)

slicing

; (semicolon), [1]

< (less)

in string formatting

in struct format strings

연산자, [1]

<<

연산자, [1]

<<=

augmented assignment

<=

연산자, [1]

<BLANKLINE>

= (equals)

assignment statement

class definition

function definition

in function calls

in string formatting

in struct format strings

==

연산자, [1]

> (greater)

in string formatting

in struct format strings

연산자, [1]

>=

연산자, [1]

>>

연산자, [1]

>>=

augmented assignment

>>>

interpreter prompt, [1]

? (question mark)

in a command interpreter

in argparse module

in AST grammar

in glob-style wildcards, [1]

in regular expressions

in SQL statements

in struct format strings, [1]

replacement character

??

in regular expressions

@ (at)

class definition

function definition

in struct format strings

연산자

[] (square brackets)

in assignment target list

in glob-style wildcards, [1]

in regular expressions

in string formatting

list expression

subscription

\ (backslash)

escape sequence, [1]

in pathnames (Windows)

in regular expressions, [1], [2]

\\

escape sequence

in regular expressions

\A

in regular expressions

\a

escape sequence

in regular expressions

\B

in regular expressions

\b

escape sequence

in regular expressions, [1]

\D

in regular expressions

\d

in regular expressions

\f

escape sequence

in regular expressions

\g

in regular expressions

\N

escape sequence, [1]

in regular expressions

\n

escape sequence

in regular expressions

\r

escape sequence

in regular expressions

\S

in regular expressions

\s

in regular expressions

\t

escape sequence

in regular expressions

\U

escape sequence, [1]

in regular expressions

\u

escape sequence, [1]

in regular expressions

\v

escape sequence

in regular expressions

\W

in regular expressions

\w

in regular expressions

\x

escape sequence, [1]

in regular expressions

\Z

in regular expressions

^ (caret)

in curses module

in regular expressions, [1]

in string formatting

marker, [1]

연산자, [1]

^=

augmented assignment

{} (curly brackets)

dictionary expression

in formatted string literal

in regular expressions

in string formatting

set expression

| (vertical bar)

in regular expressions

연산자, [1]

|=

augmented assignment

~ (tilde)

home directory expansion

연산자, [1]

탐색

색인

모듈 |

Python »

3.7.17 Documentation »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

Python »

3.7.17 Documentation »

|

Python 3.7.17 문서

환영합니다! 파이썬 3.7.17 설명서의 한국어 번역입니다.

설명서의 파트들:

파이썬 3.7 의 새로운 기능은?
2.0 이후의 모든 "새로운 기능" 문서

자습서
여기에서 시작하세요

라이브러리 레퍼런스
베개 밑에 넣어 두세요

언어 레퍼런스
문법과 언어 요소들을 설명합니다

파이썬 설정 및 사용법
여러 플랫폼에서 파이썬을 사용하는 법

파이썬 HOWTO
특정 주제에 대한 심층적인 문서

파이썬 모듈 설치하기
파이썬 패키지 색인 및 기타 소스에서 설치하기

파이썬 모듈 배포하기
다른 사람들이 설치할 수 있도록 모듈을 게시하기

확장 및 내장
C/C++ 프로그래머를 위한 자습서

파이썬/C API
C/C++ 프로그래머를 위한 레퍼런스

FAQs
자주 나오는 질문들 (답도 있습니다!)

색인 및 표 목록:

모듈 총 색인
모든 모듈 조견표

전체 색인
함수, 클래스 및 용어 개관

용어집
가장 중요한 용어들을 설명합니다

검색 페이지
문서 검색

종합 목차
영역별 목차

메타 정보:

버그 보고하기

설명서 정보

파이썬의 역사와 라이센스

저작권

탐색

색인

모듈 |

Python »

3.7.17 Documentation »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

Python »

3.7.17 Documentation »

|

파이썬 패키지 색인 (PyPI)

파이썬 패키지 색인 [https://pypi.org]은 distutils와 기타 게시 도구로 패키징된 배포를 설명하는 메타 데이터와 배포 아카이브 자체를 저장합니다.

최신 PyPI 설명서에 대한 참조는 파이썬 패키징 사용자 지침서 읽기에서 찾을 수 있습니다.

탐색

색인

모듈 |

Python »

3.7.17 Documentation »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.

이 문서는 더는 지원되지 않는 이전 버전의 파이썬 용입니다. 업그레이드하고, 다음 설명서를 읽어야 합니다: 현재 안정 버전에 대한 파이썬 설명서.

탐색

색인

모듈 |

Python »

3.7.17 Documentation »

|

패키지 색인에 패키지 올리기

최신 PyPI 설명서에 대한 참조는 파이썬 패키징 사용자 지침서 읽기에서 찾을 수 있습니다.

탐색

색인

모듈 |

Python »

3.7.17 Documentation »

|

© 저작권 2001-2023, Python Software Foundation.
파이썬 소프트웨어 재단은 비영리 법인입니다. 기부를 부탁합니다.
최종 업데이트: 6월 28, 2023 버그를 찾았나요?
Sphinx 2.3.1 를 사용해서 만들었습니다.